diff service/environment/environment.py @ 1028:70d52fa8373a

add new jsonld/SSE support to environment service as a test Ignore-this: ae671e71966dbbb9d1f97e3596802d3d darcs-hash:f724b9da306be00428ef84967f34dfe07a62a4c6
author drewp <drewp@bigasterisk.com>
date Sun, 24 Jan 2016 07:12:25 -0800
parents a06d9921c2a3
children 596c645a1fc5
line wrap: on
line diff
--- a/service/environment/environment.py	Fri Jan 22 00:39:35 2016 -0800
+++ b/service/environment/environment.py	Sun Jan 24 07:12:25 2016 -0800
@@ -5,62 +5,74 @@
 
 """
 import sys, datetime, cyclone.web
-from twisted.internet import reactor
+from twisted.internet import reactor, task
 from dateutil.tz import tzlocal
 from dateutil.relativedelta import relativedelta, FR
 from rdflib import Namespace, Literal
-sys.path.append("/my/site/magma")
-from stategraph import StateGraph
 sys.path.append("/my/proj/homeauto/lib")
+from patchablegraph import PatchableGraph, writeGraphResponse, GraphEventsHandler
 from cycloneerr import PrettyErrorHandler
 from twilight import isWithinTwilight
 
+from rdfdoc import Doc
+
 ROOM = Namespace("http://projects.bigasterisk.com/room/")
 DEV = Namespace("http://projects.bigasterisk.com/device/")
 
+
 class GraphHandler(PrettyErrorHandler, cyclone.web.RequestHandler):
     def get(self):
-        g = StateGraph(ROOM.environment)
-        now = datetime.datetime.now(tzlocal())
+        writeGraphResponse(self, self.settings.masterGraph,
+                           self.request.headers.get('accept'))
+
+def update(masterGraph):
+    stmt = lambda s, p, o: masterGraph.patchObject(ROOM.environment, s, p, o)
+    
+    now = datetime.datetime.now(tzlocal())
 
-        g.add((DEV.environment, ROOM.localHour, Literal(now.hour)))
-        g.add((DEV.environment, ROOM.localTimeToMinute,
-               Literal(now.strftime("%H:%M"))))
-        g.add((DEV.environment, ROOM.localTimeToSecond,
-               Literal(now.strftime("%H:%M:%S"))))
-        g.add((DEV.environment, ROOM.localDayOfWeek,
-               Literal(now.strftime("%A"))))
-        g.add((DEV.environment, ROOM.localMonthDay,
-               Literal(now.strftime("%B %e"))))
-        g.add((DEV.environment, ROOM.localDate,
-               Literal(now.strftime("%Y-%m-%d"))))
+    stmt(DEV.environment, ROOM.localHour, Literal(now.hour))
+    stmt(DEV.environment, ROOM.localTimeToMinute,
+         Literal(now.strftime("%H:%M")))
+
+    stmt(DEV.environment, ROOM.localTimeToSecond,
+         Literal(now.strftime("%H:%M:%S")))
+
+    stmt(DEV.environment, ROOM.localDayOfWeek,
+         Literal(now.strftime("%A")))
+    stmt(DEV.environment, ROOM.localMonthDay,
+         Literal(now.strftime("%B %e")))
+    stmt(DEV.environment, ROOM.localDate,
+         Literal(now.strftime("%Y-%m-%d")))
 
-        for offset in range(-12, 7):
-            d = now.date() + datetime.timedelta(days=offset)
-            if d == d + relativedelta(day=31, weekday=FR(-1)):
-                g.add((DEV.calendar, ROOM.daysToLastFridayOfMonth,
-                       Literal(offset)))
+    for offset in range(-12, 7):
+        d = now.date() + datetime.timedelta(days=offset)
+        if d == d + relativedelta(day=31, weekday=FR(-1)):
+            stmt(DEV.calendar, ROOM.daysToLastFridayOfMonth, Literal(offset))
 
-        g.add((DEV.calendar, ROOM.twilight,
-               ROOM['withinTwilight'] if isWithinTwilight(now) else
-               ROOM['daytime']))
+    stmt(DEV.calendar, ROOM.twilight,
+         ROOM['withinTwilight'] if isWithinTwilight(now) else ROOM['daytime'])
+
+       
+def main():
+    from twisted.python import log as twlog
+    twlog.startLogging(sys.stderr)
+    masterGraph = PatchableGraph()
 
-        ct, body = g.asAccepted(self.request.headers.get('accept'))
-        self.set_header('Content-type', ct)
-        self.write(body)
-
-from rdfdoc import Doc
-        
-class Application(cyclone.web.Application):
-    def __init__(self):
-        handlers = [
-            (r"/()", cyclone.web.StaticFileHandler,
-             {"path": ".", "default_filename": "index.html"}),
-            (r'/graph', GraphHandler),
-            (r'/doc', Doc), # to be shared
-        ]
-        cyclone.web.Application.__init__(self, handlers)
+    class Application(cyclone.web.Application):
+        def __init__(self):
+            handlers = [
+                (r"/()", cyclone.web.StaticFileHandler,
+                 {"path": ".", "default_filename": "index.html"}),
+                (r'/graph', GraphHandler),
+                (r'/graph/events', GraphEventsHandler),
+                (r'/doc', Doc), # to be shared
+            ]
+            cyclone.web.Application.__init__(self, handlers,
+                                             masterGraph=masterGraph)
+    task.LoopingCall(update, masterGraph).start(1)
+    reactor.listenTCP(9075, Application())
+    reactor.run()
 
 if __name__ == '__main__':
-    reactor.listenTCP(9075, Application())
-    reactor.run()
+    main()
+