Saturday, April 2, 2016

Android SL4A Python Development - Remotely from Desktop


SL4A is an fantastic framework on Android, but it is always pain to code on Android Device. I too feel the same while developing some python scripts on Android Device. In this post I will share my thoughts and scripts utilities to overcome this pain.

It would be so nice if we have an IDE for SL4A. Hope it will get developed soon. Till it is ready, I have an workaround to do coding on your desktop and execute it on Android Device or Emulator.

Working model of this is an simple socket-client program, where desktop client will send source code to the server which invokes python interpreter on the device and executes. The server also takes care of redirecting print messages or exceptions to the Client. Is this simple? Yes..!!

These utilities can work in two ways:
  • Usb interface via ADB
  • Wifi interface
If you want to choose USB interface, configure your device with enabled developers options and make sure your device can be accessed via adb interface. And  for Wifi option, the expectation is your desktop and device should be under same LAN.


My Setup Details:



My Android device is Lenovo K4-Note (un-rooted) installed with SL4A (r6.1.1.arm) and Python2 interpreter (r26) (more info @ https://github.com/kuri65536/python-for-android/blob/master/README.md). Coming to Desktop, I am working on Ubuntu 15.10 with python2.7.10. Hopefully it should work with all other Linux flavors and also on windows. Blindly I can say, it will work where python and ADB works.


Device Configuration:

Source code of 'runScriptServer.py':

#!/usr/bin/python
import sys
import socket
import code
import select

HOST = '0.0.0.0'
PORT = 2000

class sockFileObject(object):
    def __init__(self, conn):
        self.conn = conn
    def read(self, len):
        return self.conn.recv(len)
    def readScript(self):
        source = ''
        while (True):
            (rFds, wFds, oFds) = select.select([self.conn], [], [], 0.1)
            if (self.conn in rFds):
                source += self.conn.recv(2048)
            if (len(source) > 0) and (source[-1] == chr(0x04)):
                return(source[:-1])
    def write(self, str):
        return self.conn.send(str)
    def close(self):
        self.conn.close()
       

def main():
    server = socket.socket()
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind((HOST, PORT))
    while (True):
        print('Waiting...')
        server.listen(1)
        (conn, details) = server.accept()
        connFd = sockFileObject(conn)
        source = connFd.readScript()
        print('Executing...')
        sys.stdin = connFd
        sys.stdout = connFd
        sys.stderr = connFd
        interpreter = code.InteractiveInterpreter()
        interpreter.runcode(source)
        sys.stdin = sys.__stdin__
        sys.stdout = sys.__stdout__
        sys.stderr = sys.__stderr__
        connFd.close()
        print('Completed !!!')
    return(0)

if (__name__ == '__main__'):
    ret = main()
    sys.exit(ret)



Copy this script to the Android Device using adb push command or any other way you prefer (SCP, FTP, MTP, etc,.). Make sure it exists in '/sdcard/sl4a/scripts/' directory.

$ adb push runScriptServer.py /sdcard/sl4a/scripts/

Launch 'runScriptServer.py' script as an background service on the Android Device using SL4A script launcher GUI or using the following command if you are connected via ADB interface.

$ adb shell am start -a com.googlecode.android_scripting.action.LAUNCH_BACKGROUND_SCRIPT -n com.googlecode.android_scripting/.activity.ScriptingLayerServiceLauncher -e com.googlecode.android_scripting.extra.SCRIPT_PATH /sdcard/sl4a/scripts/runScriptServer.py

If script launched successfully your are done with the device side configurations.


Desktop Configuration:

Source code of 'runScriptClient.py': 
 
#!/usr/bin/python
import sys
import socket

HOST = '0.0.0.0'
PORT = 2000

def usage():
    printm(E, 'Usage: %s <scriptPath>' %(sys.argv[0]))

def main():
    if (len(sys.argv) < 2):
        usage()
        return(1)
    client = socket.socket()
    client.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    client.connect((HOST, PORT))
    scriptPath = sys.argv[1]
    fd = open(scriptPath, 'r')
    source = fd.read()
    fd.close()
    client.send(source)
    client.send(chr(0x04))
    while (True):
        output = client.recv(1024 * 20)
        if (len(output) == 0):
            break
        sys.stdout.write(output)
    client.close()
    return(0)

if (__name__ == '__main__'):
    ret = main()
    sys.exit(ret)



Copy this script to any location of your PATH env variable or add its directory path to the PATH variable. In Linux it can be done using the following command:

$ export PATH=$PATH:<pathToTheScript>


If you are choosing ADB option, one more thing you need to do more, that is port forwarding of the device to the desktop using the following command.

$ adb forward tcp:2000 tcp:2000


Now it the time to write actual android python code.

Source code of 'HelloWorld.py'

import android
msg = 'Welcome to the Android Python Scripting'
print(msg)
droid = android.Android()
droid.makeToast(msg)



Here I am using 'HelloWorld.py' script which prints 'Welcome to the Android Python Scripting' on the terminal and also on Android Device Screen.

Let execute this script remotely on selected Device from the Desktop terminal using

$ runScriptClient.py HelloWorld.py

As I mentioned earlier, print messages to the terminal will be redirected to the Desktop. With the above command you should see the print message in your desktop terminal where we have executed the script and same message should display on the Android Device Screen with the usage of 'makeToast()' android api. ENJOY...!!!

Hope this helps in your development. Please send your comments or suggession.

Happy Scripting....