Mercurial > code > home > repos > homeauto
changeset 51:d2842eedd56d
rewrite tomatowifi from restkit to cyclone httpclient
Ignore-this: dc012ad1d539d3a1c37c779e63c8cf4b
author | drewp@bigasterisk.com |
---|---|
date | Mon, 31 Dec 2012 15:01:04 -0800 |
parents | 56eeda98cac5 |
children | 875a37be1228 |
files | service/tomatoWifi/tomatoWifi.py service/tomatoWifi/wifi.py |
diffstat | 2 files changed, 36 insertions(+), 25 deletions(-) [+] |
line wrap: on
line diff
--- a/service/tomatoWifi/tomatoWifi.py Mon Dec 31 14:15:33 2012 -0800 +++ b/service/tomatoWifi/tomatoWifi.py Mon Dec 31 15:01:04 2012 -0800 @@ -11,9 +11,13 @@ Todo: this should be the one polling and writing to mongo, not entrancemusic """ from __future__ import division -import sys, cyclone.web, simplejson, traceback, time, pystache, datetime, restkit +import sys, cyclone.web, json, traceback, time, pystache, datetime, logging +from cyclone.httpclient import fetch +sys.path.append("/home/drewp/projects/photo/lib/python2.7/site-packages") from dateutil import tz from twisted.internet import reactor, task +from twisted.internet.defer import inlineCallbacks, returnValue + from pymongo import Connection, DESCENDING from rdflib import Namespace, Literal, URIRef @@ -36,7 +40,7 @@ DEV = Namespace("http://projects.bigasterisk.com/device/") ROOM = Namespace("http://projects.bigasterisk.com/room/") -reasoning = restkit.Resource("http://bang:9071/") +reasoning = "http://bang:9071/" class Index(PrettyErrorHandler, cyclone.web.RequestHandler): def get(self): @@ -44,7 +48,7 @@ age = time.time() - self.settings.poller.lastPollTime if age > 10: raise ValueError("poll data is stale. age=%s" % age) - + self.write("this is wifiusage. needs index page that embeds the table") class Table(PrettyErrorHandler, cyclone.web.RequestHandler): @@ -64,14 +68,14 @@ a.get('name'), a.get('mac')))))) - + class Json(PrettyErrorHandler, cyclone.web.RequestHandler): def get(self): self.set_header("Content-Type", "application/json") age = time.time() - self.settings.poller.lastPollTime if age > 10: raise ValueError("poll data is stale. age=%s" % age) - self.write(simplejson.dumps({"wifi" : self.settings.poller.lastAddrs, + self.write(json.dumps({"wifi" : self.settings.poller.lastAddrs, "dataAge" : age})) class GraphHandler(PrettyErrorHandler, cyclone.web.RequestHandler): @@ -99,7 +103,7 @@ self.set_header('Content-type', 'application/x-trig') self.write(g.asTrig()) - + class Application(cyclone.web.Application): def __init__(self, wifi, poller): handlers = [ @@ -111,7 +115,7 @@ ] settings = { 'wifi' : wifi, - 'poller' : poller, + 'poller' : poller, 'mongo' : Connection('bang', 27017, tz_aware=True)['house']['sensor'] } @@ -128,10 +132,11 @@ def assertCurrent(self): dt = time.time() - self.lastPollTime assert dt < 10, "last poll was %s sec ago" % dt - + + @inlineCallbacks def poll(self): try: - newAddrs = self.wifi.getPresentMacAddrs() + newAddrs = yield self.wifi.getPresentMacAddrs() newWithSignal = [a for a in newAddrs if a.get('signal')] @@ -144,15 +149,11 @@ self.doEntranceMusic(action) except Exception, e: log.error("entrancemusic error: %r", e) - + self.lastWithSignal = newWithSignal if actions: # this doesn't currently include signal strength changes - try: - reasoning.put("immediateUpdate", - # workaround for https://github.com/benoitc/restkit/issues/113 - headers={'User_Agent': 'tomatoWifi'}) - except Exception, e: - log.warn(e) + fetch(reasoning + "immediateUpdate", + headers={'user-agent': 'tomatoWifi'}).addErrback(log.warn) self.lastAddrs = newAddrs self.lastPollTime = time.time() except Exception, e: @@ -215,7 +216,7 @@ now = datetime.datetime.now(tz.gettz('UTC')) last = results[0]['created'].replace(tzinfo=tz.gettz('UTC')) return now - last - + if __name__ == '__main__': config = { @@ -225,6 +226,7 @@ from twisted.python import log as twlog #log.startLogging(sys.stdout) #log.setLevel(10) + log.setLevel(logging.DEBUG) mongo = Connection('bang', 27017)['visitor']['visitor']
--- a/service/tomatoWifi/wifi.py Mon Dec 31 14:15:33 2012 -0800 +++ b/service/tomatoWifi/wifi.py Mon Dec 31 15:01:04 2012 -0800 @@ -1,8 +1,14 @@ -import re, ast, restkit, logging, socket +import re, ast, logging, socket +from twisted.internet.defer import inlineCallbacks, returnValue +from cyclone.httpclient import fetch from rdflib import Literal, Graph log = logging.getLogger() +class Router(object): + def __repr__(self): + return repr(self.__dict__) + class Wifi(object): """ gather the users of wifi from the tomato routers @@ -37,12 +43,14 @@ for k, v in repl.items(): url = url.replace(k, v) - r = restkit.Resource(url, timeout=2) + r = Router() + r.url = url.replace('root:admin@', '') + r.headers = {'Authorization': ['Basic cm9vdDphZG1pbg==']} r.name = {'tomato1' : 'bigasterisk3', 'tomato2' : 'bigasterisk4'}[name.split('/')[1]] self.routers.append(r) - + @inlineCallbacks def getPresentMacAddrs(self): aboutIp = {} byMac = {} # mac : [ip] @@ -50,7 +58,8 @@ for router in self.routers: log.debug("GET %s", router) try: - data = router.get().body_string() + data = yield fetch(router.url, headers=router.headers, + timeout=2) except socket.error: log.warn("get on %s failed" % router) continue @@ -62,7 +71,7 @@ mac=mac, iface=iface, )) - + byMac.setdefault(mac, set()).add(ip) for (name, ip, mac, lease) in jsValue(data, 'dhcpd_lease'): @@ -74,9 +83,9 @@ mac=mac, lease=lease )) - + byMac.setdefault(mac, set()).add(ip) - + for iface, mac, signal in jsValue(data, 'wldev'): matched = False for addr in aboutIp.values(): @@ -102,7 +111,7 @@ addr['name'] = 'unknown' ret.append(addr) - return ret + returnValue(ret) def jsValue(js, variableName):