changeset 1524:13b7e4de3824

whitespace Ignore-this: c727f388f197a6fae88595fe6d455c7d darcs-hash:971e4474b4dbd35a722be670f5599298fb5ec83f
author drewp <drewp@bigasterisk.com>
date Wed, 05 Feb 2020 00:29:13 -0800
parents 0da337780f22
children ce118c7c06d9
files service/dhcpleases/dhcpleases.py service/dpms/dpms_service.py service/environment/environment.py service/mqtt_graph_bridge/tasks.py service/powerEagle/reader.py service/reasoning/index.html service/reasoning/inputgraph.py service/rfid/index.html service/rfid/rfid.py service/rfid_pn532_py/index.html service/rfid_pn532_py/rfid.py service/tinyScreen/tiny_screen.py service/tradfri/tradfri.py
diffstat 13 files changed, 59 insertions(+), 72 deletions(-) [+]
line wrap: on
line diff
--- a/service/dhcpleases/dhcpleases.py	Wed Feb 05 00:23:06 2020 -0800
+++ b/service/dhcpleases/dhcpleases.py	Wed Feb 05 00:29:13 2020 -0800
@@ -28,7 +28,7 @@
 def timeLiteral(dt):
     return Literal(dt.replace(tzinfo=tzlocal()).isoformat(),
                    datatype=XSD.dateTime)
-    
+
 def macUri(macAddress: str) -> URIRef:
     return URIRef("http://bigasterisk.com/mac/%s" % macAddress.lower())
 
@@ -46,7 +46,7 @@
                 self.fileTimes[f] = mtime
                 ret = True
         return ret
-        
+
     def poll(self):
         if not self.anythingToRead():
             STATS.filesDidntChange += 1
@@ -67,7 +67,7 @@
                     g.add((uri, ROOM['dhcpHostname'], Literal(hostname), ctx))
 
             self.graph.setToGraph(g)
-            
+
 if __name__ == '__main__':
     arg = docopt("""
     Usage: store.py [options]
--- a/service/dpms/dpms_service.py	Wed Feb 05 00:23:06 2020 -0800
+++ b/service/dpms/dpms_service.py	Wed Feb 05 00:29:13 2020 -0800
@@ -59,7 +59,7 @@
     def get(self):
         self.set_header('content-type', 'text/plain')
         self.write(getMonitorState())
-        
+
     def put(self):
         body = self.request.body.strip()
         if body in ['on', 'off']:
@@ -73,7 +73,7 @@
         self.lastSent = None
         self.lastSentTime = 0
         task.LoopingCall(self.poll).start(5)
-        
+
     def poll(self):
         now = int(time.time())
         state = getMonitorState()
@@ -84,7 +84,7 @@
             URIRef("http://bigasterisk.com/host/%s/monitor" % host),
             ROOM['powerStateMeasured'],
             ROOM[getMonitorState()])
-        
+
         if state != self.lastSent or (now > self.lastSentTime + 3600):
             influx.write_points([
                 {'measurement': 'power',
@@ -92,13 +92,13 @@
                  'fields': {'value': 1 if state == 'on' else 0},
                  'time': now
                  }], time_precision='s')
-            
+
             self.lastSent = state
             self.lastSentTime = now
 
 masterGraph = PatchableGraph()
 poller = Poller()
-            
+
 reactor.listenTCP(9095, cyclone.web.Application([
     (r'/', Root),
     (r'/monitor', Monitor),
@@ -107,5 +107,3 @@
 ]), interface='::')
 
 reactor.run()
-
-
--- a/service/environment/environment.py	Wed Feb 05 00:23:06 2020 -0800
+++ b/service/environment/environment.py	Wed Feb 05 00:29:13 2020 -0800
@@ -28,7 +28,7 @@
 @STATS.update.time()
 def update(masterGraph):
     stmt = lambda s, p, o: masterGraph.patchObject(ROOM.environment, s, p, o)
-    
+
     now = datetime.datetime.now(tzlocal())
 
     stmt(DEV.environment, ROOM.localHour, Literal(now.hour))
@@ -53,7 +53,7 @@
     stmt(DEV.calendar, ROOM.twilight,
          ROOM['withinTwilight'] if isWithinTwilight(now) else ROOM['daytime'])
 
-       
+
 def main():
     arg = docopt("""
     Usage: environment.py [options]
@@ -89,4 +89,3 @@
 
 if __name__ == '__main__':
     main()
-    
--- a/service/mqtt_graph_bridge/tasks.py	Wed Feb 05 00:23:06 2020 -0800
+++ b/service/mqtt_graph_bridge/tasks.py	Wed Feb 05 00:29:13 2020 -0800
@@ -38,13 +38,3 @@
 @task
 def tail_mqtt(ctx):
     ctx.run(f'mosquitto_sub -h bang -p 10010 -d -v -t \#')
-
-
-
-
-
-
-
-
-
-    
--- a/service/powerEagle/reader.py	Wed Feb 05 00:23:06 2020 -0800
+++ b/service/powerEagle/reader.py	Wed Feb 05 00:29:13 2020 -0800
@@ -71,7 +71,7 @@
                     tags=dict(house='berkeley'),
                     time=int(startTime),
                 ))
-                   
+
             self.influx.write_points(pts, time_precision='s')
         except Exception as e:
             traceback.print_exc()
--- a/service/reasoning/index.html	Wed Feb 05 00:23:06 2020 -0800
+++ b/service/reasoning/index.html	Wed Feb 05 00:29:13 2020 -0800
@@ -150,6 +150,7 @@
       </script>
     </div>
 
+
     <script type="module">
      import { render } from '/lib/lit-html/1.0.0/lit-html.js';
      import { graphView } from '/rdf/browse/graphView.js';
--- a/service/reasoning/inputgraph.py	Wed Feb 05 00:23:06 2020 -0800
+++ b/service/reasoning/inputgraph.py	Wed Feb 05 00:29:13 2020 -0800
@@ -12,7 +12,6 @@
 from greplin import scales
 
 from patchablegraph.patchsource import ReconnectingPatchSource
-
 from rdfdb.rdflibpatch import patchQuads
 
 log = logging.getLogger('fetch')
--- a/service/rfid/index.html	Wed Feb 05 00:23:06 2020 -0800
+++ b/service/rfid/index.html	Wed Feb 05 00:29:13 2020 -0800
@@ -46,7 +46,7 @@
        table {
            border-collapse: collapse;
        }
-       
+
        td, th {
            border: 1px solid gray;
        }
@@ -56,10 +56,10 @@
           <streamed-graph url="graph/events" graph="{{graph}}"></streamed-graph>
           <!-- also get a graph of users so we can look up cards -->
         </div>
-        
+
         <iron-ajax id="rewrite" url="rewrite" method="POST"></iron-ajax>
-        
-        Current reads: 
+
+        Current reads:
         <table>
           <tr><th>Card UID</th><th>Card text</th><th></th></tr>
           <template is="dom-repeat" items="{{currentReads}}">
@@ -74,7 +74,7 @@
             </tr>
           </template>
         </table>
-        
+
       </template>
       <script>
        HTMLImports.whenReady(function () {
--- a/service/rfid/rfid.py	Wed Feb 05 00:23:06 2020 -0800
+++ b/service/rfid/rfid.py	Wed Feb 05 00:29:13 2020 -0800
@@ -45,7 +45,7 @@
             stmt = g.triples((None, None, None)).next()
         self._onStatement(user, stmt)
     post = put
-    
+
     def _onStatement(self, user, stmt):
         # write rfid to new key, etc.
         if stmt[1] == ROOM['keyContents']:
@@ -54,13 +54,13 @@
 
 def uidUri(card_id):
     return URIRef('http://bigasterisk.com/rfidCard/%010x' % card_id)
-        
+
 def uidArray(uri):
     prefix, h = uri.rsplit('/', 1)
     if prefix != 'http://bigasterisk.com/rfidCard':
         raise ValueError(uri)
     return [int(h[i * 2: i * 2 + 2], 16) for i in range(0, len(h), 2)]
-        
+
 class Rewrite(cyclone.web.RequestHandler):
     def post(self):
         agent = URIRef(self.request.headers['x-foaf-agent'])
@@ -72,16 +72,16 @@
             self.set_status(404, "no card present")
             # maybe retry a few more times since the card might be nearby
             return
-            
+
         text = ''.join(random.choice(string.uppercase) for n in range(32))
-        log.info('%s rewrites %s to %s, to be owned by %s', 
+        log.info('%s rewrites %s to %s, to be owned by %s',
                  agent, uid, text, body['user'])
-        
+
         #reader.KEY = private.rfid_key
         reader.write(uid, text)
         log.info('done with write')
 
-    
+
 sensor = ROOM['frontDoorWindowRfid']
 
 class ReadLoop(object):
@@ -92,7 +92,7 @@
 
         self.pollPeriodSecs = .1
         self.expireSecs = 2
-        
+
         task.LoopingCall(self.poll).start(self.pollPeriodSecs)
 
     @STATS.cardReadPoll.time()
@@ -114,7 +114,7 @@
         self.log[cardIdUri] = now
         if is_new:
             self.startCardRead(cardIdUri, textLit)
-        
+
     def flushOldReads(self, now):
         for uri in self.log.keys():
             if self.log[uri] < now - self.expireSecs:
@@ -138,9 +138,9 @@
         for spo in self.masterGraph._graph.triples(
                 (cardUri, ROOM['cardText'], None)):
             delQuads.append(spo + (ctx,))
-            
+
         self.masterGraph.patch(Patch(addQuads=[], delQuads=delQuads))
-        
+
     def _sendOneshot(self, oneshot):
         body = (' '.join('%s %s %s .' % (s.n3(), p.n3(), o.n3())
                          for s,p,o in oneshot)).encode('utf8')
@@ -155,8 +155,8 @@
                      url, e.getErrorMessage())
         d.addErrback(err)
 
-                                                              
-        
+
+
 if __name__ == '__main__':
     arg = docopt("""
     Usage: rfid.py [options]
--- a/service/rfid_pn532_py/index.html	Wed Feb 05 00:23:06 2020 -0800
+++ b/service/rfid_pn532_py/index.html	Wed Feb 05 00:29:13 2020 -0800
@@ -28,7 +28,7 @@
       <div id="out"></div>
       <script type="module" src="/rdf/streamed_graph_view.js"></script>
     </template>
-    
+
     <div class="served-resources">
       <a href="stats/">/stats/</a>
       <a href="graph">/graph</a>
--- a/service/rfid_pn532_py/rfid.py	Wed Feb 05 00:23:06 2020 -0800
+++ b/service/rfid_pn532_py/rfid.py	Wed Feb 05 00:29:13 2020 -0800
@@ -43,7 +43,7 @@
         except ValueError:
             obj = Literal(turtleLiteral)
         self._onStatements([(subj, pred, obj)])
-        
+
     def _onGraphBodyStatements(self, body, headers):
         g = Graph()
         g.parse(StringInputSource(body), format='nt')
@@ -51,7 +51,7 @@
             raise ValueError("expected graph body")
         self._onStatements(list(g.triples((None, None, None))))
     post = put
-    
+
     def _onStatements(self, stmts):
         # write rfid to new key, etc.
         if len(stmts) > 0 and stmts[0][1] == ROOM['keyContents']:
@@ -67,7 +67,7 @@
 
 def looksLikeBigasterisk(text):
     return text.startswith(BODY_VERSION + "*")
-    
+
 class Rewrite(cyclone.web.RequestHandler):
     def post(self):
         agent = URIRef(self.request.headers['x-foaf-agent'])
@@ -79,16 +79,16 @@
             self.set_status(404, "no card present")
             # maybe retry a few more times since the card might be nearby
             return
-            
+
         text = randomBody()
-        log.info('%s rewrites %s to %s, to be owned by %s', 
+        log.info('%s rewrites %s to %s, to be owned by %s',
                  agent, uid, text, body['user'])
-        
+
         #reader.KEY = private.rfid_key
         reader.write(uid, text)
         log.info('done with write')
 
-    
+
 sensor = ROOM['frontDoorWindowRfid']
 
 class ReadLoop(object):
@@ -166,9 +166,9 @@
         for spo in self.masterGraph._graph.triples(
                 (cardUri, ROOM['cardText'], None)):
             delQuads.append(spo + (ctx,))
-            
+
         self.masterGraph.patch(Patch(addQuads=[], delQuads=delQuads))
-        
+
     def _sendOneshot(self, oneshot):
         body = (' '.join('%s %s %s .' % (s.n3(), p.n3(), o.n3())
                          for s,p,o in oneshot)).encode('utf8')
@@ -183,8 +183,8 @@
                      url, e.getErrorMessage())
         d.addErrback(err)
 
-                                                              
-        
+
+
 if __name__ == '__main__':
     arg = docopt("""
     Usage: rfid.py [options]
@@ -199,7 +199,7 @@
         log.setLevel(logging.DEBUG)
         log.info(f'cyclone {cyclone.__version__}')
         defer.setDebugging(True)
-        
+
     masterGraph = PatchableGraph()
     reader = NfcDevice() if not arg['-n'] else FakeNfc()
 
--- a/service/tinyScreen/tiny_screen.py	Wed Feb 05 00:23:06 2020 -0800
+++ b/service/tinyScreen/tiny_screen.py	Wed Feb 05 00:29:13 2020 -0800
@@ -23,7 +23,7 @@
 
     def _stateImage(self, state):
         return Image.open('anim/%s.png' % state.rsplit('/')[-1])
-        
+
     def _initOutput(self, spiDevice, rotation):
         # CS on pin 26 (GPIO7; spi0 ce1), DC on pin 18 (GPIO24), RST held at VCC.
         self._dev = ssd1331(spi(device=spiDevice, port=0,
@@ -34,7 +34,7 @@
                                 gpio_DC=24,
                             ),
                             rotation=rotation)
-        
+
     def setContrast(self, contrast):
         """0..255"""
         self._dev.contrast(contrast)
@@ -71,7 +71,7 @@
         if self.goalState == ROOM['unlockNews']:
             # wrong during animation
             self.renderNews()
-        
+
     def renderNews(self):
         bg = self._stateImage(ROOM['unlockNews'])
         draw = ImageDraw.Draw(bg)
@@ -82,7 +82,7 @@
                 textwrap.fill(self.news, width=12).splitlines()):
             draw.text((24, 0 + 10 * i), line, font=font)
         self.display(bg)
-        
+
 class ScreenSim(Screen):
     def _initOutput(self):
         self.windowScale = 2
@@ -92,7 +92,7 @@
         self.surf = pygame.display.set_mode(
             (96 * self.windowScale, 64 * self.windowScale))
         time.sleep(.05) # something was causing the 1st update not to show
-        
+
     def display(self, img):
         pgi = self.pygame.image.fromstring(
             img.tobytes(), img.size, img.mode)
@@ -122,7 +122,7 @@
             assert len(g)
             stmts = list(g.triples((None, None, None)))
         self._onStatement(stmts)
-            
+
     def _onStatement(self, stmts):
         """
         (disp :brightness 1.0 . )
@@ -138,7 +138,7 @@
                 self.settings.screen.animateTo(stmt[2])
             else:
                 log.warn("ignoring %s", stmt)
-    
+
 if __name__ == '__main__':
     arg = docopt("""
     Usage: tiny_screen.py [options]
@@ -170,5 +170,5 @@
         ], screen=screen, masterGraph=masterGraph, debug=arg['-v']),
                       interface='::')
     log.warn('serving on %s', port)
-    
+
     reactor.run()
--- a/service/tradfri/tradfri.py	Wed Feb 05 00:23:06 2020 -0800
+++ b/service/tradfri/tradfri.py	Wed Feb 05 00:29:13 2020 -0800
@@ -48,7 +48,7 @@
         task.LoopingCall(self.updateCur).start(60)
         for dev in self.devices:
             self.startObserve(dev)
-            
+
     def startObserve(self, dev):
         def onUpdate(dev):
             reactor.callFromThread(self.updateCur, dev)
@@ -75,13 +75,13 @@
             } for dev in self.devices],
             'graph': 'http://sticker:9059/graph', #todo
         }
-        
+
     def updateCur(self, dev=None):
         cur = [(s,p,o,self.ctx) for s,p,o in
                self.currentStateStatements([dev] if dev else self.devices)]
         self.graph.patch(Patch(addQuads=cur, delQuads=self.curStmts))
         self.curStmts = cur
-                
+
     def deviceStatements(self):
         for dev in self.devices:
             uri = devUri(dev)
@@ -94,7 +94,7 @@
                 yield (uri, ROOM['reachable'], ROOM['yes'] if dev.reachable else ROOM['no'])
             yield (uri, RDFS.label, Literal(dev.name))
             # no connection between remotes and lights?
-            
+
     def currentStateStatements(self, devs):
         for dev in self.devices:  # could scan just devs, but the Patch line needs a fix
             uri = devUri(dev)
@@ -115,7 +115,7 @@
                 #if light.hex_color:
                 #    yield (lightUri, ROOM['kelvinColor'], Literal(light.kelvin_color))
                 #    yield (lightUri, ROOM['color'], Literal('#%s' % light.hex_color))
-            
+
 
     def outputStatements(self, stmts):
         for stmt in stmts:
@@ -130,7 +130,7 @@
                             traceback.print_exc()
                             raise
         self.updateCur()
-      
+
 class OutputPage(cyclone.web.RequestHandler):
     def put(self):
         arg = self.request.arguments
@@ -159,7 +159,7 @@
             'host': hostname,
             'boards': [self.settings.hub.description()]
         }, indent=2))
-        
+
 def main():
     arg = docopt("""
     Usage: tradfri.py [options]
@@ -174,7 +174,7 @@
 
     masterGraph = PatchableGraph()
     hub = Hub(masterGraph, private.hubAddr, key=private.hubKey)
-    
+
     reactor.listenTCP(10009, cyclone.web.Application([
         (r"/()", cyclone.web.StaticFileHandler, {
             "path": "/opt/static", "default_filename": "index.html"}),