changeset 304:e7cbf250188a

influx output, fade support, switch to Adafruit_DHT, start of Lcd8544 Ignore-this: dd9cae16daafd780a301728a1ce8eb38
author drewp@bigasterisk.com
date Fri, 16 Sep 2016 00:55:04 -0700
parents 66fe7a93753d
children 6614416dd2c3
files service/piNode/config/main.n3 service/piNode/devices.py service/piNode/export_to_influxdb.py service/piNode/piNode.py
diffstat 4 files changed, 265 insertions(+), 23 deletions(-) [+]
line wrap: on
line diff
--- a/service/piNode/config/main.n3	Mon Aug 29 00:27:46 2016 -0700
+++ b/service/piNode/config/main.n3	Fri Sep 16 00:55:04 2016 -0700
@@ -21,7 +21,11 @@
     board2pin:GPIO23 
     .
 
-ha:bedroomPiTemp a :OnboardTemperature .
+ha:bedroomPiTemp a :OnboardTemperature;
+ :influxMeasurement [
+    :measurement "temperatureF";
+    :predicate :temperatureF;
+    :tag [:key "host"; :value "bed"], [:key "location"; :value "bedPi"]] .
 
 board2pin:GPIO2 :gpioNumber 2 .
 board2pin:GPIO3 :gpioNumber 3 .
@@ -38,6 +42,12 @@
 
 board2pin:GPIO17 :connectedTo sensor:motionBed .
 sensor:motionBed a :MotionSensor;
+  :influxMeasurement [
+    :measurement "presence";
+    :predicate :sees;
+    :tag [:key "host"; :value "bed"],
+      [:key "sensor"; :value "motion"],
+      [:key "location"; :value "bed"]];
   :sees houseLoc:bed .
 
 :bedLedStrip a :RgbStrip;
@@ -46,7 +56,7 @@
   :blueChannel board2pin:GPIO4 .
     
 board2pin:GPIO27 :connectedTo :headboardWhite .
-:headboardWhite a :LedOutput ; :gamma 2 .
+:headboardWhite a :LedOutput ; :gamma 2; :fade "yes" .
   
 #board2pin:b29 :connectedTo board2ow: .
 #board2ow: a :OneWire;
@@ -65,18 +75,28 @@
     board3pin:GPIO17
     .
     
-ha:kitchenPiTemp a :OnboardTemperature .
+ha:kitchenPiTemp a :OnboardTemperature;
+   :influxMeasurement [
+    :measurement "temperatureF";
+    :predicate :temperatureF;
+    :tag [:key "host"; :value "kitchen"], [:key "location"; :value "kitchenPi"]] .
 
 board3pin:GPIO4 :gpioNumber 4; :connectedTo sensor:tempHumidKitchen .
 sensor:tempHumidKitchen a :TempHumidSensor;
   :sees houseLoc:kitchenCounter;
-  :graphiteName "system.house.temp.kitchenCounter" .
+  :influxMeasurement [
+    :measurement "temperatureF";
+    :predicate :temperatureF;
+    :tag [:key "host"; :value "kitchen"], [:key "location"; :value "kitchenCounter"]] .
 
 board3pin:GPIO17 :gpioNumber 17; :connectedTo board3ow: .
 board3ow: a :OneWire; :connectedTo board3ow:dev-000003a5a94c .
 board3ow:dev-000003a5a94c a :TemperatureSensor;
   :position houseLoc:kitchenCounter;
-  :graphiteName "system.house.temp.kitchenCounter_ds_test" .
+  :influxMeasurement [
+    :measurement "temperatureF";
+    :predicate :temperatureF;
+    :tag [:key "host"; :value "kitchen"], [:key "location"; :value "kitchenCounter_ds_test"]] .
 
 @prefix board4pin: <http://bigasterisk.com/homeauto/board4/pin/> .
 
@@ -86,6 +106,7 @@
   :onboardDevice ha:livingPiTemp;
   :hasPin
     board4pin:GPIO17,
+    board4pin:GPIO18,
     board4pin:GPIO4,
     board4pin:GPIO27,
     board4pin:GPIO22 .
@@ -95,10 +116,30 @@
 board4pin:GPIO27 :gpioNumber 27; :connectedTo :livingRoomLamp2 .
 board4pin:GPIO22 :gpioNumber 22; :connectedTo :bookSwitch .
 
-ha:livingPiTemp a :OnboardTemperature .
+
+board4pin:GPIO18 :gpioNumber 18; :connectedTo :livingRgb .
+:livingRgb a :RgbPixels;
+  :colorOrder order:GRB;
+  :pixels (:livingRgb0 :livingRgb1 :livingRgb2 :livingRgb3) .
+
+
+ha:livingPiTemp a :OnboardTemperature;
+  :influxMeasurement [
+    :measurement "temperatureF";
+    :predicate :temperatureF;
+    :tag [:key "host"; :value "living"], [:key "location"; :value "livingPi"]] .
+
+
 sensor:tempHumidLivingRoomCeiling a :TempHumidSensor;
   :sees houseLoc:livingRoomCeiling;
-  :graphiteName "system.house.temp.livingRoomCeiling" .
+  :influxMeasurement [
+    :measurement "temperatureF";
+    :predicate :temperatureF;
+    :tag [:key "host"; :value "living"], [:key "location"; :value "livingRoomCeiling"]], [
+    :measurement "humidity";
+    :predicate :humidity;
+    :tag [:key "host"; :value "living"], [:key "location"; :value "livingRoomCeiling"]] .
+
 :livingRoomLamp1 a :LedOutput .
 :livingRoomLamp2 a :LedOutput .
 :bookSwitch a :Pushbutton; :style :inverted .
@@ -114,17 +155,27 @@
     board5pin:GPIO17,
     board5pin:GPIO18 .
 
-ha:changingPiTemp a :OnboardTemperature .
+ha:changingPiTemp a :OnboardTemperature;
+  :influxMeasurement [
+    :measurement "temperatureF";
+    :predicate :temperatureF;
+    :tag [:key "host"; :value "changing"], [:key "location"; :value "changingPi"]] .
 
 board5pin:GPIO4 :gpioNumber 4 .
 board5pin:GPIO17 :gpioNumber 17 .
 board5pin:GPIO18 :gpioNumber 18 .
 
 board5pin:GPIO4 :connectedTo :changingWhite .
-:changingWhite a :LedOutput .
+:changingWhite a :LedOutput; :fade "yes" .
 
 board5pin:GPIO17 :connectedTo sensor:motionChanging .
 sensor:motionChanging a :MotionSensor;
+  :influxMeasurement [
+    :measurement "presence";
+    :predicate :sees;
+    :tag [:key "host"; :value "changing"],
+      [:key "sensor"; :value "motion"],
+      [:key "location"; :value "changing"]];
   :sees :changing .
 
 board5pin:GPIO18 :connectedTo :changingRgb .
@@ -145,3 +196,107 @@
 board5:rgb4 rdfs:label "rgb4" .
 board5:rgb5 rdfs:label "rgb5" .
 
+
+
+@prefix board6pin: <http://bigasterisk.com/homeauto/board6/pin/> .
+@prefix board6ow: <http://bigasterisk.com/homeauto/board6/oneWire/> .
+
+ha:node6 a :PiBoard;
+  :hostname "garage";
+  :onboardDevice ha:garagePiTemp;
+  :hasPin
+    board6pin:GPIO4,
+    board6pin:GPIO17,
+    board6pin:GPIO7,
+    board6pin:GPIO8,
+    board6pin:GPIO15,
+    board6pin:GPIO18,
+    board6pin:GPIO24,
+    board6pin:GPIO25 .
+ha:garagePiTemp a :OnboardTemperature;
+  :influxMeasurement [
+    :measurement "temperatureF";
+    :predicate :temperatureF;
+    :tag [:key "host"; :value "garage"], [:key "location"; :value "garagePi"]] .
+
+board6pin:GPIO4 :gpioNumber 4; :connectedTo sensor:motionGarageDoorInside .
+sensor:motionGarageDoorInside a :MotionSensor;
+  :influxMeasurement [
+    :measurement "presence";
+    :predicate :sees;
+    :tag [:key "host"; :value "garage"],
+      [:key "sensor"; :value "motion"],
+      [:key "location"; :value "garageDoorInside"]];
+  :sees :garage .
+
+board6pin:GPIO17 :gpioNumber 17; :connectedTo board6ow: .
+board6ow: a :OneWire; :connectedTo board6ow:dev-000003a5c0fb .
+board6ow:dev-000003a5c0fb a :TemperatureSensor;
+  :position houseLoc:garage;
+  :influxMeasurement [
+    :measurement "temperatureF";
+    :predicate :temperatureF;
+    :tag [:key "host"; :value "garage"], [:key "location"; :value "garage"]] .
+
+board6pin:GPIO15 :gpioNumber 15; :connectedTo :garageOverhead .
+:garageOverhead a :LedOutput .
+
+board6pin:GPIO18 :gpioNumber 18; :connectedTo :garageRgb .
+:garageRgb a :RgbPixels;
+  :colorOrder order:GRB;
+  :pixels (:garageRgb0 :garageRgb1 :garageRgb2 :garageRgb3) .
+
+
+board6pin:GPIO25 :gpioNumber 25 .
+board6pin:GPIO24 :gpioNumber 24 .
+board6pin:GPIO8 :gpioNumber 8 .
+board6pin:GPIO7 :gpioNumber 7 .
+
+:garageLcd a :Lcd8544;
+  :din board6pin:GPIO25;
+  :clk board6pin:GPIO24;
+  :dc board6pin:GPIO8;
+  :rst board6pin:GPIO7 .
+  
+    
+
+
+
+
+@prefix board7pin: <http://bigasterisk.com/homeauto/board7/pin/> .
+
+ha:node7 a :PiBoard;
+  :hostname "downbath";
+  :onboardDevice ha:downbathPiTemp;
+  :hasPin
+    board7pin:GPIO17,
+    board7pin:GPIO4,
+    board7pin:GPIO27,
+    board7pin:GPIO22 .
+
+ha:downbathPiTemp a :OnboardTemperature;
+  :influxMeasurement "temperatureF";
+  :influxTag [:key "location"; :value "downBathPi"] .
+
+
+
+@prefix board8pin: <http://bigasterisk.com/homeauto/board8/pin/> .
+
+ha:node8 a :PiBoard;
+  :hostname "frontdoor";
+  :onboardDevice ha:frontdoorPiTemp;
+  :hasPin
+    board8pin:GPIO4 .
+
+ha:frontdoorPiTemp a :OnboardTemperature;
+  :influxMeasurement "temperatureF";
+  :influxTag [:key "location"; :value "downBathPi"] .
+
+board8pin:GPIO4 :gpioNumber 4; :connectedTo :frontdoorOpenSwitch .
+:frontdoorOpenSwitch a :Pushbutton; :style :inverted;
+:influxMeasurement [
+    :measurement "state";
+    :predicate :buttonState;
+    :tag [:key "host"; :value "frontdoor"],
+      [:key "sensor"; :value "open"],
+      [:key "location"; :value "frontDoor"]];.
--- a/service/piNode/devices.py	Mon Aug 29 00:27:46 2016 -0700
+++ b/service/piNode/devices.py	Fri Sep 16 00:55:04 2016 -0700
@@ -1,3 +1,6 @@
+"""
+https://github.com/juniorug/libsensorPy is a similar project
+"""
 from __future__ import division
 
 import time, logging, os
@@ -140,9 +143,10 @@
     # which is a bit fancier
     deviceType = ROOM['MotionSensor']
 
-    def setup(self):
-        self.pi.set_mode(17, pigpio.INPUT)
-        self.pi.set_pull_up_down(17, pigpio.PUD_DOWN)
+    def __init__(self, graph, uri, pi, pinNumber):
+        super(MotionSensorInput, self).__init__(graph, uri, pi, pinNumber)
+        self.pi.set_mode(pinNumber, pigpio.INPUT)
+        self.pi.set_pull_up_down(pinNumber, pigpio.PUD_DOWN)
 
     def hostStateInit(self):
         self.lastRead = None
@@ -150,7 +154,7 @@
         self.lastMotionStart90 = 0
 
     def poll(self):
-        motion = self.pi.read(17)
+        motion = self.pi.read(self.pinNumber)
         now  = time.time()
         
         oneshot = []
@@ -255,16 +259,20 @@
 @register
 class TempHumidSensor(DeviceType):
     deviceType = ROOM['TempHumidSensor']
+    pollPeriod = 5
 
     def __init__(self, *a, **kw):
         DeviceType.__init__(self, *a, **kw)
-        sys.path.append('/opt/pigpio/EXAMPLES/Python/DHT22_AM2302_SENSOR')
-        import DHT22
-        self.sensor = DHT22.sensor(self.pi, self.pinNumber)
+        import Adafruit_DHT
+        self.mod = Adafruit_DHT
     
     def poll(self):
-        self.sensor.trigger()
-        humid, tempC = self.sensor.humidity(), self.sensor.temperature()
+        for tries in range(1):
+            # fails a lot, but I don't want to add too much delay in
+            # here- the next poll is coming soon
+            humid, tempC = self.mod.read(self.mod.DHT22, self.pinNumber)
+            if humid and tempC:
+                break
 
         stmts = set()
         if humid is not None:
@@ -335,6 +343,7 @@
     use for onewire. The pin number in this config is currently ignored.
     """
     deviceType = ROOM['OneWire']
+    pollPeriod = 2
     # deliberately written like arduinoNode's one for an easier merge.
     def __init__(self,  *a, **kw):
         DeviceType.__init__(self, *a, **kw)
@@ -416,7 +425,15 @@
 
     def hostStateInit(self):
         self.value = 0
-        self.fv = FilteredValue(self._setPwm)
+        if (self.uri, ROOM['fade'], None) in self.graph:
+            # incomplete- the object could be fade settings
+            self.fv = FilteredValue(self._setPwm)
+        else:
+            _setPwm = self._setPwm
+            class Instant(object):
+                def set(self, goal):
+                    _setPwm(goal)
+            self.fv = Instant()
         self.gamma = float(self.graph.value(self.uri, ROOM['gamma'], default=1))
     
     def setup(self):
@@ -534,6 +551,71 @@
             'pred': ROOM['color'],
         } for px in self.pixelUris]
 
+@register
+class Lcd8544(DeviceType):
+    """PCD8544 lcd (nokia 5110)"""
+    deviceType = ROOM['RgbStrip']
+    
+    @classmethod
+    def findInstances(cls, graph, board, pi):
+        for row in graph.query("""
+      SELECT DISTINCT ?dev ?din ?clk ?dc ?rst  WHERE {
+        ?dev a :Lcd8544 .
+        ?board :hasPin ?dinPin . ?dev :din ?dinPin . ?dinPin :gpioNumber ?din .
+        ?board :hasPin ?clkPin . ?dev :clk ?clkPin . ?clkPin :gpioNumber ?clk .
+        ?board :hasPin ?dcPin .  ?dev :dc ?dcPin .   ?dcPin :gpioNumber ?dc .
+        ?board :hasPin ?rstPin . ?dev :rst ?rstPin . ?rstPin :gpioNumber ?rst .
+      } ORDER BY ?dev""",
+                               initBindings=dict(board=board),
+                               initNs={'': ROOM}):
+            log.debug('found lcd %r', row)
+            yield cls(graph, row.dev, pi,
+                      int(row.din), int(row.clk),
+                      int(row.dc), int(row.rst))
+
+    def __init__(self, graph, uri, pi, din, clk, dc, rst):
+        super(Lcd8544, self).__init__(graph, uri, pi, None)
+
+
+        import RPi.GPIO
+        import Adafruit_Nokia_LCD
+        import Adafruit_GPIO.SPI
+        self.lcd = Adafruit_Nokia_LCD.PCD8544(
+            dc=8, rst=7,
+            spi=Adafruit_GPIO.SPI.BitBang(
+                Adafruit_Nokia_LCD.GPIO.RPiGPIOAdapter(RPi.GPIO),
+                sclk=clk,
+                mosi=din))
+        self.lcd.begin(contrast=60)
+            
+    def hostStatements(self):
+        return []
+        return [(self.uri, ROOM['color'], Literal(self.value))]
+        
+    def outputPatterns(self):
+        return []
+        return [(self.uri, ROOM['color'], None)]
+
+    def sendOutput(self, statements):
+        return
+        assert len(statements) == 1
+        assert statements[0][:2] == (self.uri, ROOM['color'])
+
+        rgb = self._rgbFromHex(statements[0][2])
+        self.value = statements[0][2]
+
+        for (i, v) in zip(self.rgb, rgb):
+            self.pi.set_PWM_dutycycle(i, v)
+        
+    def outputWidgets(self):
+        return []
+        return [{
+            'element': 'output-rgb',
+            'subj': self.uri,
+            'pred': ROOM['color'],
+        }]
+
+
         
 def makeDevices(graph, board, pi):
     out = []
--- a/service/piNode/export_to_influxdb.py	Mon Aug 29 00:27:46 2016 -0700
+++ b/service/piNode/export_to_influxdb.py	Fri Sep 16 00:55:04 2016 -0700
@@ -20,8 +20,6 @@
         graph = self.graph
         now = int(time.time())
       
-        log.debug('influxdb export:')
-
         points = []
         for stmt in currentStatements:
             if (stmt[0], stmt[1]) in self.measurements:
@@ -49,9 +47,9 @@
             self.influx.write_points(points, time_precision='s')
 
     def influxValue(self, rdfValue):
-        if rdfValue == ROOM['motion']:
+        if rdfValue in [ROOM['motion'], ROOM['pressed']]:
             value = 1
-        elif rdfValue == ROOM['noMotion']:
+        elif rdfValue in [ROOM['noMotion'], ROOM['notPressed']]:
             value = 0
         else:
             value = rdfValue.toPython()
--- a/service/piNode/piNode.py	Mon Aug 29 00:27:46 2016 -0700
+++ b/service/piNode/piNode.py	Fri Sep 16 00:55:04 2016 -0700
@@ -86,12 +86,14 @@
             log.exception("During poll:")
             
     def _pollMaybeError(self):
+        pollTime = {} # uri: sec
         for i in self._devs:
             now = time.time()
             if (hasattr(i, 'pollPeriod') and
                 self._lastPollTime.get(i.uri, 0) + i.pollPeriod > now):
                 continue
             new = i.poll()
+            pollTime[i.uri] = time.time() - now
             if isinstance(new, dict): # new style
                 oneshot = new['oneshot']
                 new = new['latest']
@@ -114,6 +116,11 @@
             if oneshot:
                 self._sendOneshot(oneshot)
             self._lastPollTime[i.uri] = now
+        if log.isEnabledFor(logging.DEBUG):
+            log.debug('poll times:')
+            for u, s in sorted(pollTime.items()):
+                log.debug("  %.4f ms %s", s * 1000, u)
+            log.debug('total poll time: %f ms', sum(pollTime.values()) * 1000)
         self._influx.exportToInflux(
             set.union(*[set(v) for v in self._statementsFromInputs.values()]))