2012-11-09

Android CherryPy Cam

Android Twisted SpyCam:
http://kbcarte.wordpress.com/2011/08/31/android-twisted-spycam

Running CherryPy on Android:
http://www.defuze.org/archives/228-running-cherrypy-on-android-with-sl4a.html

Combining the two to run a CherryPy app on Android, which allow you to take a snapshot remotely by visiting http://x.x.x.x:8080 from a browser in the same LAN segment.

It needs to acquire at least a dim wakelock, otherwise it won't work after android goes to sleep.  Have to kill the app to release the wakelock though.

# -*- coding: utf-8 -*-

# Visit <phone_IP>:8080 to take a snapshot
# and display the snapshot in the web page.
# dkf 121104 creation

# The multiprocessing package isn't
# part of the ASE installation so
# we must disable multiprocessing logging
import logging
logging.logMultiprocessing = 0

import os.path

import android
import cherrypy

droid = android.Android()
here = os.path.abspath(os.path.dirname(__file__))

def snap():
    fn = os.path.join(here, 'latest.jpg')
    droid.cameraCapturePicture(fn, True)
    im = open(fn, 'rb')
    shot = im.read()
    im.close()
    os.remove(fn)
    return shot

class Root(object):
    def __init__(self):
        self.droid = android.Android()

    @cherrypy.expose
    def index(self):
        return "<a href='snapshot'>Click here to take snapshot</a>"

    @cherrypy.expose
    def snapshot(self):
        cherrypy.response.headers['content-type'] = 'image/jpeg'
        return snap()

def run():
    cherrypy.config.update({'server.socket_host': '0.0.0.0'})
    cherrypy.quickstart(Root(), '/')

if __name__ == '__main__':
    droid.wakeLockAcquireDim()
    run()


1 comment:

Anonymous said...

Thanks for this useful example.

I love Python!