#!/usr/bin/python import os, socket, time, simplejson from threading import Thread from Queue import Queue from BeautifulSoup import BeautifulStoneSoup as soup events = Queue() def gen_buffer(): read_size = 5000 read_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) read_sock.connect(("127.0.0.1", 45054)) while True: try: buffer = read_sock.recv(read_size) if not buffer: continue else: yield buffer except: raise StopIteration exit(1) def monitor(i, out_queue): last_output = {} gen_soup = (soup(b) for b in gen_buffer()) for s in gen_soup: # Note the address='' part, change that to whatever matches your device(s) for d in s.findAll("device", address='00-1f-c5-21-6f-6d'): for a in s.device.findAll("axisvalue"): # curr = int(10 * (float(a['value']) % 10)) curr = int(float(a['value'])) last = last_output.get(a['axis'], 0) if curr != last: out_queue.put( { 'axis_event': (a['axis'], curr) } ) last_output[a['axis']] = curr # Note the address='' part, change that to whatever matches your device(s) for b in s.findAll("buttonchange", address="00-1f-c5-21-6f-6d"): curr = b['state'] last = last_output.get(b['id'], -1) if curr != last: out_queue.put( { 'button_event': (b['id'], b['state']) } ) last_output[b['id']] = curr def main(): worker = Thread(target=monitor, args=(0, events)) worker.setDaemon(True) worker.start() while True: output = [] for x in xrange(1, 10): out = events.get() # It's an ugly hack but I filter axis events here and device events in the monitor # so change as appropriate if 'axis_event' in out and 'wr' not in out['axis_event'][0]: pass elif out: output.append(out) events.task_done() # This is because I couldn't get my webserver to serve FIFO files (pipes) # nor could I get my get.JSON call to work when calling to a different port then the # page was served from if output: print ">>> Writing: %s" % (output) f = open("data.json", "w") f.write(simplejson.dumps(output)) f.close() if __name__ == '__main__': main()