powerguru-commit
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Powerguru-commit] [SCM] powerguru branch, master, updated. 894b685aa8c3


From: Rob Savoye
Subject: [Powerguru-commit] [SCM] powerguru branch, master, updated. 894b685aa8c34fdc4e18c0df36104c80613aa3ab
Date: Tue, 19 Feb 2019 14:28:19 -0500 (EST)

This is an automated email from the git hooks/post-receive script. It was
generated because a ref change was pushed to the repository containing
the project "powerguru".

The branch, master has been updated
       via  894b685aa8c34fdc4e18c0df36104c80613aa3ab (commit)
       via  a76928620eaf01f75ed3850807b85e00cfb379ba (commit)
       via  ada082dcf552d7e952570710a9810f25c91344ca (commit)
       via  cec807cabb4400131f8a58f775f3039197109492 (commit)
       via  49c45fbaa0bee90d32520cd76269d7d396f9a4eb (commit)
       via  6f12901d474141ab5162bdba94ffbfa26656db9a (commit)
       via  6c9af5cd937ffcb879c7c4f0c3c23492c1fb5b98 (commit)
       via  1990fc173cfccc0227f252c41c5a8dd85394e609 (commit)
      from  6bc680ddc1977d55c7adcc6aa6a9fc7c85e4a4d9 (commit)

Those revisions listed above that are new to this repository have
not appeared on any other notification email; so we list those
revisions in full, below.

- Log -----------------------------------------------------------------
http://git.savannah.gnu.org/cgit/powerguru.git/commit/?id=894b685aa8c34fdc4e18c0df36104c80613aa3ab


commit 894b685aa8c34fdc4e18c0df36104c80613aa3ab
Author: Rob Savoye <address@hidden>
Date:   Tue Feb 19 12:27:42 2019 -0700

    Add comments about types

diff --git a/python/sensor.py b/python/sensor.py
index 1ac3d68..03f74de 100755
--- a/python/sensor.py
+++ b/python/sensor.py
@@ -26,6 +26,8 @@ import psycopg2
 from datetime import datetime
 from enum import Enum
 
+# Types of sensors. These enums and their string values must match
+# the database schema's enum. See powerguru.sql for details.
 class SensorType(Enum):
     UNKNOWN = 0
     ACVOLTAGE = 1
@@ -39,6 +41,8 @@ class SensorType(Enum):
     UNSUPPORTED = 9
 sensorStrings= ('UNKNOWN', 'ACVOLTAGE', 'DCVOLTAGE', 'AUTH', 'BATTERY', 
'POWER', 'CLOCK', 'TEMPERATURE', 'MOISTURE', 'UNSUPPORTED' )
 
+# Types of devices. These enums and their string values must match
+# the database schema's enum. See powerguru.sql for details.
 class DeviceType(Enum):
     UNKNOWN = 0
     ONEWIRE = 1

http://git.savannah.gnu.org/cgit/powerguru.git/commit/?id=a76928620eaf01f75ed3850807b85e00cfb379ba


commit a76928620eaf01f75ed3850807b85e00cfb379ba
Author: Rob Savoye <address@hidden>
Date:   Tue Feb 19 12:27:12 2019 -0700

    Add support for triggers in the remote API

diff --git a/python/remote.py b/python/remote.py
index 9b5feab..c3d6c29 100644
--- a/python/remote.py
+++ b/python/remote.py
@@ -24,18 +24,28 @@ import socketserver
 from lxml import etree
 from lxml.etree import tostring
 import sensor
+from enum import Enum
+import triggers
+import psycopg2
 
 
 class client_handler(socketserver.BaseRequestHandler):
     """Create Server for client requests"""
-    
+
+    def setup(self, options=dict()):
+        print("SETUP"),
+
+    def server_activate(self):
+        print("ACTIVATE"),
+
+
     def handle(self):
         while True:
             # self.request is the TCP socket connected to the client
             self.data = self.request.recv(1024).strip()
             self.clientip = self.client_address[0]
             logging.info("{} wrote:".format(self.clientip))
-            #logging.debug(self.data)
+            # logging.debug(self.data)
             # If no data, the client dropped the network connection.
             # Return and this handler will ge restarted for the next
             # incoming connection.
@@ -55,24 +65,30 @@ class client_handler(socketserver.BaseRequestHandler):
             # These are the allowable top level XML tags
             if tag == "LIST":
                 logging.debug("LIST: %r" % xml.text)
-                # if no children, default to quering all sensors
+                # if no children, default to querying all sensors
                 if len(xml) == 0:
                     self.list_command(xml.text)
-                else:
-                    if xml[0].tag.upper() == "SENSORS":
+                elif xml[0].tag.upper() == "SENSORS":
                         self.list_command(xml[0].text)
+                # Don't do anything, just make  network connection
+                # is working. Mostly use for development
             elif tag == "NOP":
                 logging.debug("NOP: %r" % xml.text)
             elif tag == "HELO":
                 logging.debug("HELO: %r" % xml.text)
             elif tag == "POLL":
                 logging.debug("POLL: %r" % xml.text)
-            elif tag == "EVENT":
-                logging.debug("EVENT: %r" % xml.text)
-                self.event_command(xml.text)
+            elif tag == "TRIGGER":
+                logging.debug("TRIGGER: %r" % xml.text)
+                if len(xml) > 0:
+                    trigger = triggers.Triggers()
+                    trigger.fromXML(xml)
+                    trigger.dump()
+                    trigger.writeSQL()
+                    #self.event_command(xml.text)
             else:
                 logging.error("Tag %r not supported!" % tag)
-                #return
+                return
 
             if len(xml) > 0:
                 logging.debug("Has chidren")
@@ -92,7 +108,7 @@ class client_handler(socketserver.BaseRequestHandler):
         logging.debug("LIST command: %r" % text)
         if text is None or text.upper() == "ALL":
             xmldata = sensor.Sensors().makeXML()
-            logging.debug("XMLDATA: %r" % xmldata)
+            #logging.debug("XMLDATA: %r" % xmldata)
         else:
             if sensor.Sensors().get(text) != None:
                 xmldata = sensor.Sensors().get(text).makeXML()
@@ -100,6 +116,9 @@ class client_handler(socketserver.BaseRequestHandler):
                 logging.error("Bad sensor ID %r!" % text)
         self.request.sendall(xmldata.encode('utf-8'))
 
-    def event_command(self):
+    def event_command(self, event=""):
+        """ Handle events. Events are actions that we want to have
+        a timestamp for, so when looking at weather or power data,
+        we can see triggers for changes in the data."""
         logging.debug("EVENT command")
 

http://git.savannah.gnu.org/cgit/powerguru.git/commit/?id=ada082dcf552d7e952570710a9810f25c91344ca


commit ada082dcf552d7e952570710a9810f25c91344ca
Author: Rob Savoye <address@hidden>
Date:   Tue Feb 19 12:26:30 2019 -0700

    Use new options and postgresql classes

diff --git a/python/ownet.py b/python/ownet.py
index 83d5cdb..9aa20ad 100755
--- a/python/ownet.py
+++ b/python/ownet.py
@@ -26,26 +26,17 @@ from pyownet import protocol
 import onewire
 import psycopg2
 import sensor
+from options import CmdOptions
+from postgresql import Postgresql
 
-def ownet_handler(args, sensors):
-    logging.debug("Start ownet %r" % args)
 
-    # Connect to a postgresql database
-    try:
-        dbname = "powerguru"
-        connect = "dbname=" + dbname
-        dbshell = psycopg2.connect(connect)
-        if dbshell.closed == 0:
-            dbshell.autocommit = True
-            logging.info("Opened connection to %r" % dbname)
-            
-            dbcursor = dbshell.cursor()
-            if dbcursor.closed == 0:
-                logging.info("Opened cursor in %r" % dbname)
-                
-    except Exception as e:
-        logging.warning("Couldn't connect to database: %r" % e)
-        
+def ownet_handler(sensors):
+    logging.debug("Start ownet...")
+
+    options = CmdOptions()
+    options.dump()
+    db = Postgresql()
+    #db.dump()
 
     # It turns out that the network connection occcsasionally times out
     # reading data, which is ok to ignore most of the time. However,
@@ -61,18 +52,18 @@ def ownet_handler(args, sensors):
         retries -= 1
         # Get a list of all directories on the server
         try:
-            owproxy = protocol.proxy(host=args['owserver'], port=4304, 
persistent=True)
-            logging.info("Connected to OW server: %r" % args['owserver'])
+            owproxy = protocol.proxy(host=options.get('owserver'), port=4304, 
persistent=True)
+            logging.info("Connected to OW server: %r" % 
options.get('owserver'))
             owproxy.dir()
             break
         except Exception as e:
             logging.error("Couldn't connect to OW server: %r" % e)
+            continue
 
-    interval = int(args['interval'])
-    while interval > 0:
+    while db.isConnected():
         for dir in owproxy.dir():
             logging.info("Reading data from: %s:%s"
-                         % (args['owserver'], dir))
+                         % (options.get('owserver'), dir))
             sensor = dict()
             # Note that all the strings returned are wide strings, and
             # not ASCII. Because the 'b' qualifier for these strings
@@ -93,11 +84,6 @@ def ownet_handler(args, sensors):
                 time.sleep(1)   # give the server a second to recover
                 continue
 
-            #logging.debug("%r" % sensor)
-            # FIXME: format query and write to database
-            # dbcursor.execute(query)
-            # family | id | alias | type | timestamp
-
             if sensor['type'] == 'TEMPERATURE':
                 #logging.info("Found a temperature sensor: " + family + '.' + 
id)
                 temp = dict()
@@ -113,7 +99,7 @@ def ownet_handler(args, sensors):
                     continue
                 # By default, all temperature readings are in 'C' (Celcius)
                 # we convert to 'F' (Farenheit) if need be
-                if (args['scale'] == 'F'):
+                if (options.get('scale') == 'F'):
                     temp['temperature'] = (float(temp['temperature']) * 1.8) + 
32.0
                     if temp['lowtemp'] is not "0":
                         temp['lowtemp'] =  (float(temp['lowtemp']) * 1.8) + 
32.0
@@ -126,11 +112,11 @@ def ownet_handler(args, sensors):
                 query += ", " + str(temp['hightemp'])
                 query += ", 0"
                 #query += ", " + str(temp['humidity'])
-                query += ", " + "'" + args['scale'] + "'"
-                query += ", '" + time.strftime("%Y-%m-%d %H:%M:%S") + "'"
-                query += ");"
+                query += ", " + "'" + options.get('scale') + "'"
+                query += ", '" + time.strftime("%Y-%m-%d %H:%M:%S") + "');"
+                #query += ");"
                 #logging.debug(query)
-                dbcursor.execute(query)
+                db.query(query)
                 # id | temperature | temphigh | templow | scale | timestamp
  
             if sensor['type'] == 'POWER':
@@ -153,12 +139,11 @@ def ownet_handler(args, sensors):
                 query += ", 'DC'"
                 query += ", '" + time.strftime("%Y-%m-%d %H:%M:%S") + "'"
                 query += ");"
-                #logging.debug(query)
-                dbcursor.execute(query)
+                db.query(query)
                 # id | current | volts | type | timestamp
 
         # Don't eat up all the cpu cycles!
-        time.sleep(interval)
+        time.sleep(options.get('interval'))
 
         if errors > error_threshold:
             return

http://git.savannah.gnu.org/cgit/powerguru.git/commit/?id=cec807cabb4400131f8a58f775f3039197109492


commit cec807cabb4400131f8a58f775f3039197109492
Author: Rob Savoye <address@hidden>
Date:   Tue Feb 19 12:26:03 2019 -0700

    Change BATTERY type to POWER

diff --git a/python/onewire.py b/python/onewire.py
index fd23b03..e5c26ee 100755
--- a/python/onewire.py
+++ b/python/onewire.py
@@ -31,22 +31,22 @@ _family = dict();
 
 _family["A2"] = {"description":"AC Voltage", "chips":"mCM001", 
"type":"ACVOLTAGE"};
 _family["82"] = {"description":"Authorization", "chips":"DS1425", 
"type":"AUTH"};
-_family["30"] = {"description":"Battery", "chips":"DS2760", "type":"BATTERY"};
-_family["32"] = {"description":"Battery", "chips":"DS2780", "type":"BATTERY"};
-_family["35"] = {"description":"Battery", "chips":"DS2755", "type":"BATTERY"};
-_family["2E"] = {"description":"Battery", "chips":"DS2770", "type":"BATTERY"};
-_family["3D"] = {"description":"Battery", "chips":"DS2781", "type":"BATTERY"};
-_family["31"] = {"description":"Battery ID", "chips":"DS2720", 
"type":"BATTERY"};
-_family["26"] = {"description":"Battery monitor", "chips":"DS2438", 
"type":"BATTERY"};
-_family["51"] = {"description":"Battery monitor", "chips":"DS2751", 
"type":"BATTERY"};
-_family["1B"] = {"description":"Battery monitor", "chips":"DS2436", 
"type":"BATTERY"};
-_family["1E"] = {"description":"Battery monitor", "chips":"DS2437", 
"type":"BATTERY"};
+_family["30"] = {"description":"Battery", "chips":"DS2760", "type":"POWER"};
+_family["32"] = {"description":"Battery", "chips":"DS2780", "type":"POWER"};
+_family["35"] = {"description":"Battery", "chips":"DS2755", "type":"POWER"};
+_family["2E"] = {"description":"Battery", "chips":"DS2770", "type":"POWER"};
+_family["3D"] = {"description":"Battery", "chips":"DS2781", "type":"POWER"};
+_family["31"] = {"description":"Battery ID", "chips":"DS2720", "type":"POWER"};
+_family["26"] = {"description":"Battery monitor", "chips":"DS2438", 
"type":"POWER"};
+_family["51"] = {"description":"Battery monitor", "chips":"DS2751", 
"type":"POWER"};
+_family["1B"] = {"description":"Battery monitor", "chips":"DS2436", 
"type":"POWER"};
+_family["1E"] = {"description":"Battery monitor", "chips":"DS2437", 
"type":"POWER"};
 _family["24"] = {"description":"Clock", "chips":"DS2415", "type":"CLOCK"};
 _family["27"] = {"description":"Clock + interrupt", "chips":"DS2417", 
"type":"CLOCK"};
 _family["36"] = {"description":"Coulomb counter", "chips":"DS2740", 
"type":"UNSUPPORTED"};
 _family["1D"] = {"description":"Counter", "chips":"DS2423", 
"type":"UNSUPPORTED"};
 _family["16"] = {"description":"crypto-ibutton", "chips":"DS1954 DS1957", 
"type":"UNSUPPORTED"};
-_family["B2"] = {"description":"DC Current or Voltage", "chips":"mAM001", 
"type":"BATTERY"};
+_family["B2"] = {"description":"DC Current or Voltage", "chips":"mAM001", 
"type":"POWER"};
 _family["04"] = {"description":"EconoRam Time chi", "chips":"DS2404", 
"type":"UNSUPPORTED"};
 _family["7E"] = {"description":"Envoronmental Monitors", "chips":"EDS00xx", 
"type":"UNSUPPORTED"};
 _family["41"] = {"description":"Hygrocron", "chips":"DS1923", 
"type":"UNSUPPORTED"};

http://git.savannah.gnu.org/cgit/powerguru.git/commit/?id=49c45fbaa0bee90d32520cd76269d7d396f9a4eb


commit 49c45fbaa0bee90d32520cd76269d7d396f9a4eb
Author: Rob Savoye <address@hidden>
Date:   Tue Feb 19 12:25:28 2019 -0700

    Use new options and postgresql classes

diff --git a/python/i2c.py b/python/i2c.py
index d0ac980..588b28b 100644
--- a/python/i2c.py
+++ b/python/i2c.py
@@ -23,31 +23,22 @@ import logging
 import psycopg2
 from ina219 import INA219, DeviceRangeError
 import time
+from options import CmdOptions
+from postgresql import Postgresql
 
-def ina219_handler(options, sensors):
-    logging.debug("Start rtl_sdr %r" % options)
+
+def ina219_handler(sensors):
+    logging.debug("Start ina219...")
+
+    options = CmdOptions()
+    db = Postgresql()
+    #db.dump()
 
     SHUNT_OHMS = 0.1
     MAX_EXPECTED_AMPS = 2.0
     ina = INA219(SHUNT_OHMS, MAX_EXPECTED_AMPS)
     ina.configure(ina.RANGE_16V)
 
-    # Connect to a postgresql database
-    try:
-        dbname = "powerguru"
-        connect = "dbname=" + dbname
-        dbshell = psycopg2.connect(connect)
-        if dbshell.closed == 0:
-            dbshell.autocommit = True
-            logging.info("Opened connection to %r" % dbname)
-            
-            dbcursor = dbshell.cursor()
-            if dbcursor.closed == 0:
-                logging.info("Opened cursor in %r" % dbname)
-                
-    except Exception as e:
-        logging.warning("Couldn't connect to database: %r" % e)
-
     while True:
         try:
             print('Bus Voltage: {0:0.2f}V'.format(ina.voltage()))
@@ -60,8 +51,6 @@ def ina219_handler(options, sensors):
         except DeviceRangeError as e:
             # Current out of device range with specified shunt resister
             print(e)
-        logging.debug(query)
-        dbcursor.execute(query)
-        time.sleep(100)
-        #time.sleep(options['interval'])
+        db.query(query)
+        time.sleep(options.get('interval'))
 
diff --git a/python/rtl433.py b/python/rtl433.py
index 79935f1..d3a7a1d 100755
--- a/python/rtl433.py
+++ b/python/rtl433.py
@@ -29,33 +29,24 @@ import os
 import psycopg2
 import sensor
 import itertools, operator
+from options import CmdOptions
+from postgresql import Postgresql
 ON_POSIX = 'posix' in sys.builtin_module_names
 
-def rtl433_handler(options, sensors):
-    logging.debug("Start rtl_433 %r" % options)
+def rtl433_handler(sensors):
+    logging.debug("Start rtl_433...")
 
-    # Connect to a postgresql database
-    try:
-        dbname = "powerguru"
-        connect = "dbname=" + dbname
-        dbshell = psycopg2.connect(connect)
-        if dbshell.closed == 0:
-            dbshell.autocommit = True
-            logging.info("Opened connection to %r" % dbname)
-            dbcursor = dbshell.cursor()
-            if dbcursor.closed == 0:
-                logging.info("Opened cursor in %r" % dbname)
-
-    except Exception as e:
-        logging.warning("Couldn't connect to database: %r" % e)
+    options = CmdOptions()
+    db = Postgresql()
+    #db.dump()
 
     #ppp = Popen(cmd, stdout=PIPE, stderr=STDOUT, bufsize=1, 
close_fds=ON_POSIX)
-    cmd = [ 'rtl_433', '-F', 'csv', '-R', '40', '-T', '15']
+    cmd = [ 'rtl_433', '-F', 'csv', '-R', '40', '-T', '60']
     while True:
         ppp = Popen(cmd, stdout=PIPE, bufsize=0, close_fds=ON_POSIX)
         out, err = ppp.communicate()
         #out, err = ppp.communicate(timeout=0.5)
-        #print("FIXME0: %r" % retries)
+        #print("FIXME0: %r" % out)
         for line in out.splitlines():
             mapper = map
             #for line in ppp.readline():
@@ -84,17 +75,16 @@ def rtl433_handler(options, sensors):
             #else:
                 #sensor.sensors[temp['id']]['channel'] = temp['channel']
                 #sensor.sensors[temp['id']]['device'] = DeviceType.RTL433
-            sensors.dump()
+            #sensors.dump()
             # Convert from Celcius if needed
-            if (options['scale'] == 'F'):
+            if (options.get('scale') == 'F'):
                 temp['temperature'] = (float(temp['temperature']) * 1.8) + 
32.0;
                 #temp['lowtemp'] =  (float(temp['lowtemp']) * 1.8) + 32.0;
                 #temp['hightemp'] =  (float(temp['hightemp']) * 1.8) + 32.0;
-            query = """INSERT INTO weather VALUES( '%s', %s, %s, %s, %s, '%s', 
'%s' )  ON CONFLICT DO NOTHING;; """ % (temp['id'], temp['temperature'], "0", 
"0",  temp['humidity'], options['scale'], temp['timestamp'])
+            query = """INSERT INTO weather VALUES( '%s', %s, %s, %s, %s, '%s', 
'%s' )  ON CONFLICT DO NOTHING;; """ % (temp['id'], temp['temperature'], "0", 
"0",  temp['humidity'], options.get('scale'), temp['timestamp'])
             logging.debug(query)
-            dbcursor.execute(query)
-        #time.sleep(30)
-        time.sleep(int(options['interval']))
+            db.query(query)
+        time.sleep(options.get('interval'))
  
     # _sensors = list()
 
diff --git a/python/rtlsdr.py b/python/rtlsdr.py
old mode 100644
new mode 100755
index b2fa5ab..23d8946
--- a/python/rtlsdr.py
+++ b/python/rtlsdr.py
@@ -24,28 +24,14 @@ import logging
 #import time
 #import psycopg2
 #from rtlsdr import RtlSdr
+from options import CmdOptions
+from postgresql import Postgresql
 
 
-def rtlsdr_handler(args):
-    logging.debug("Start rtl_sdr %r" % args)
+def rtlsdr_handler(sensors):
+    logging.debug("Start rtl_sdr...")
     #self.sdr = RtlSdr(1, True,"00000001")
 
-    # # Connect to a postgresql database
-    # try:
-    #     dbname = "powerguru"
-    #     connect = "dbname=" + dbname
-    #     dbshell = psycopg2.connect(connect)
-    #     if dbshell.closed == 0:
-    #         dbshell.autocommit = True
-    #         logging.info("Opened connection to %r" % dbname)
-            
-    #         dbcursor = dbshell.cursor()
-    #         if dbcursor.closed == 0:
-    #             logging.info("Opened cursor in %r" % dbname)
-                
-    # except Exception as e:
-    #     logging.warning("Couldn't connect to database: %r" % e)
-        
-
-    _sensors = list()
-
+    options = CmdOptions()
+    #db = Postgresql()
+    #db.dump()

http://git.savannah.gnu.org/cgit/powerguru.git/commit/?id=6f12901d474141ab5162bdba94ffbfa26656db9a


commit 6f12901d474141ab5162bdba94ffbfa26656db9a
Author: Rob Savoye <address@hidden>
Date:   Tue Feb 19 12:25:07 2019 -0700

    Use new options and postgresql classes

diff --git a/python/gpio433.py b/python/gpio433.py
new file mode 100755
index 0000000..a59dd28
--- /dev/null
+++ b/python/gpio433.py
@@ -0,0 +1,62 @@
+#!/usr/bin/python3
+
+# 
+#   Copyright (C) 2019 Free Software Foundation, Inc.
+# 
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+# 
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+# 
+
+# API documentation at: https://pyownet.readthedocs.io/en/latest/
+
+import sys
+import epdb
+import logging
+import time
+#import psycopg2
+import sensor
+from datetime import datetime
+import platform
+import RPi.GPIO as GPIO
+from options import CmdOptions
+
+RECEIVED_SIGNAL = [[], []]  #[[time of reading], [signal reading]]
+MAX_DURATION = 20
+RECEIVE_PIN = 27
+
+def gpio433_handler(sensors):
+    logging.debug("Start gpio433...")
+
+    options = CmdOptions()
+    
+    GPIO.setmode(GPIO.BCM)
+    GPIO.setup(RECEIVE_PIN, GPIO.IN)
+    cumulative_time = 0
+    beginning_time = datetime.now()
+    print('**Started recording**')
+    while cumulative_time < MAX_DURATION:
+        time_delta = datetime.now() - beginning_time
+        RECEIVED_SIGNAL[0].append(time_delta)
+        RECEIVED_SIGNAL[1].append(GPIO.input(RECEIVE_PIN))
+        #print("%r\n" % RECEIVED_SIGNAL[1])
+        cumulative_time = time_delta.seconds
+    print('**Ended recording**')
+    print("%r samples recorded" % len(RECEIVED_SIGNAL[0]))
+    GPIO.cleanup()
+
+    print('**Processing results**')
+    for i in range(len(RECEIVED_SIGNAL[0])):
+        RECEIVED_SIGNAL[0][i] = RECEIVED_SIGNAL[0][i].seconds + 
RECEIVED_SIGNAL[0][i].microseconds/1000000.0
+
+    print('**Done processing results**')
+

http://git.savannah.gnu.org/cgit/powerguru.git/commit/?id=6c9af5cd937ffcb879c7c4f0c3c23492c1fb5b98


commit 6c9af5cd937ffcb879c7c4f0c3c23492c1fb5b98
Author: Rob Savoye <address@hidden>
Date:   Tue Feb 19 12:23:05 2019 -0700

    Use new options class for command line option processing

diff --git a/python/pgd.py b/python/pgd.py
index af88392..9978d68 100755
--- a/python/pgd.py
+++ b/python/pgd.py
@@ -36,47 +36,18 @@ import platform
 import i2c
 import remote
 import socketserver
+import os
+from options import CmdOptions
 
 
-# Setup default command line options
-options = dict()
-options['interval'] = "300"  # time interval to delay when polling for data
-options['owserver'] = "localhost"  # hostname of the owserver
-options['dbserver'] = "localhost"  # hostname of the database
-options['scale'] = "F"             # The scale, 'C' or 'F'
-
-# menu for --help
-def usage(argv):
-    print(argv[0] + ": options: ")
-    print("""\t--help(-h)   Help
-    \t--owserver(-w)    OW server [host[:port]], default '%s'
-    \t--dbserver(-d)    Database server [host]:port]], default '%s'
-    \t--interval(-i)    Set the time interval for device polling, default '%s'
-    \t--verbose(-v)     Enable verbosity
-    \t--scale(-s)       Set the temperature scale, 'F' or 'C', default '%s'
-    """ % (options['owserver'],
-           options['dbserver'],
-           options['interval'],
-           options['scale']))
-    quit()
-
-# Check command line arguments
-try:
-    (opts, val) = getopt.getopt(argv[1:], "h,w:,d:,s:,i:v,",
-           ["help", "owserver", "dbserver", "scale", "interval", "verbose"])
-except getopt.GetoptError as e:
-    logging.error('%r' % e)
-    usage(argv)
-    quit()
-
 # Setup a disk space log filemode. By default, everything
 # gets logged to the disk file
 logging.basicConfig(
-    filename='pgdpy.log',
-    filemode='w',
-    level=logging.DEBUG,
-    format= '[%(asctime)s] {%(filename)s:%(lineno)d} %(levelname)s - 
%(message)s',
-     datefmt='%Y-%m-%d %H:%M:%S'
+    filename = 'pgdpy.log',
+    filemode = 'w',
+    level = logging.DEBUG,
+    format = '[%(asctime)s] {%(filename)s:%(lineno)d} %(levelname)s - 
%(message)s',
+     datefmt = '%Y-%m-%d %H:%M:%S'
 )
 
 # Setup console logging, useful for debugging
@@ -92,26 +63,8 @@ ch.setFormatter(formatter)
 root.addHandler(ch)
 terminator = ch.terminator
 verbosity = logging.CRITICAL
-
-# process command line arguments, will override the defaults
-for (opt, val) in opts:
-    if opt == '--help' or opt == '-h':
-        usage(argv)
-    elif opt == "--owserver" or opt == '-w':
-        options['owserver'] = val
-    elif opt == "--interval" or opt == '-i':
-        options['interval'] = val
-    elif opt == "--dbserver" or opt == '-d':
-        options['dbserver'] = val
-    elif opt == "--verbose" or opt == '-v':
-        if verbosity == logging.INFO:
-            verbosity = logging.DEBUG
-            formatter = logging.Formatter('{%(filename)s:%(lineno)d} 
%(levelname)s - %(message)s')
-            ch.setFormatter(formatter)
-        if verbosity == logging.CRITICAL:
-            verbosity = logging.INFO
-
-ch.setLevel(verbosity)
+formatter = logging.Formatter('{%(filename)s:%(lineno)d} %(levelname)s - 
%(message)s')
+ch.setFormatter(formatter)
 
 #
 # See if we're running on a Raspberry PI, since other platforms
@@ -129,6 +82,13 @@ else:
     pi = False
 logging.info("Running on %r" % on[0])
 
+# process command line arguments. This uses /proc, so we don't
+# have to pass anything in.
+opts = CmdOptions()
+opts.dump()
+
+ch.setLevel(opts.get('verbosity'))
+
 #
 # Collect the data about the connected sensors
 #
@@ -140,7 +100,7 @@ sensors.dump()
 #
 
 # OWFS network protocol
-ownet_thread = Thread(target=ownet.ownet_handler, args=(options, sensors))
+ownet_thread = Thread(target=ownet.ownet_handler, args=(sensors,))
 ownet_thread.start()
 
 # OWFS filesystem
@@ -148,21 +108,22 @@ ownet_thread.start()
 #onewire_thread.start()
 
 # rtl_433 filesystem
-rtl433_thread = Thread(target = rtl433.rtl433_handler, args = (options, 
sensors,))
+rtl433_thread = Thread(target = rtl433.rtl433_handler, args = (sensors,))
 rtl433_thread.start()
 
 # rtl_sdr
-rtlsdr_thread = Thread(target = rtlsdr.rtlsdr_handler, args = (options, 
sensors))
+rtlsdr_thread = Thread(target = rtlsdr.rtlsdr_handler, args = (sensors,))
 rtlsdr_thread.start()
 
 # GPIO only works on a Raspberry PI
 if pi is True:
     import gpio433
-    gpio433_thread = Thread(target = gpio433.gpio433_handler, args = (options, 
sensors))
+    gpio433_thread = Thread(target = gpio433.gpio433_handler, args = 
(sensors,))
     gpio433_thread.start()
 
-    i2c_thread = Thread(target = i2c.ina219_handler, args = (options, sensors))
+    i2c_thread = Thread(target = i2c.ina219_handler, args = (sensors,))
     i2c_thread.start()
+
 try:
     server = socketserver.TCPServer(("0.0.0.0", 7654), remote.client_handler)
     server.allow_reuse_address = True

http://git.savannah.gnu.org/cgit/powerguru.git/commit/?id=1990fc173cfccc0227f252c41c5a8dd85394e609


commit 1990fc173cfccc0227f252c41c5a8dd85394e609
Author: Rob Savoye <address@hidden>
Date:   Tue Feb 19 12:22:17 2019 -0700

    Refactored from different project, now works

diff --git a/python/postgresql.py b/python/postgresql.py
index 1738599..7d9dec9 100755
--- a/python/postgresql.py
+++ b/python/postgresql.py
@@ -17,59 +17,93 @@
 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 # 
 
-import pdb
+import epdb
 import glob
 import psycopg2
 import subprocess
 import logging
+from options import CmdOptions
 
 
-class postgresql(object):
+class Postgresql(object):
     """A class to work with a postgresql database"""
     def __init__(self):
-        self.dbname = ""
+        self.options = CmdOptions()
+        self.connect()
         self.result = ""
 
-    def connect(self, dbname):
+    def connect(self):
         """Connect to a postgresql server"""
-        logging.debug("plotcalls.connect(" + dbname + ")")
-        self.dbname = "";
-        connect = " dbname=" + dbname
-        
-        try:
-            self.dbshell = psycopg2.connect(connect)
-            if self.dbshell.closed == 0:
-                self.dbshell.autocommit = True
-                logging.info("Opened connection to %r %r" % (dbname, 
self.dbshell))
-                
-                self.dbcursor = self.dbshell.cursor()
-                if self.dbcursor.closed == 0:
-                    logging.info("Opened cursor in %r %r" % (dbname, 
self.dbcursor))
 
-        except Exception as e:
-            print("Couldn't connect to database: %r" % e)
+        # Supported parameters for connect are: 
+        # *database*: the database name (only as keyword argument)
+        # *user*: user name used to authenticate
+        # *password*: password used to authenticate
+        # *host*: database host address (defaults to UNIX socket if not 
provided)
+        # *port*: connection port number (defaults to 5432 if not provided)
+        dbserver = self.options.get('dbserver')
+        database = self.options.get('database')
+        connect = ""
+        if dbserver is not "localhost":
+            connect += "host='" + dbserver + "'"
+        connect += " dbname='" + database + "'"
+
+        logging.debug("postgresql.connect(%r)" % connect)
+        self.dbshell = psycopg2.connect(connect)
+        if self.dbshell.closed == 0:
+            self.dbshell.autocommit = True
+            logging.info("Opened connection to %r %r" % (database, 
self.dbshell))
 
-    def query(self, query, nores=""):
+            self.dbcursor = self.dbshell.cursor()
+            if self.dbcursor.closed == 0:
+                logging.info("Opened cursor in %r %r" % (database, 
self.dbcursor))
+
+    def query(self, query):
         """Query a postgresql database"""
-        logging.debug("pgdb.query(" + query + ")")
+
+        logging.debug("postgresql.query(" + query + ")")
+        #epdb.set_trace()
+        if self.dbshell.closed != 0:
+            logging.error("Database %r is not connected!" % 
self.options.get('database'))
+            return self.result
+
+        self.dbcursor.execute(query)
         try:
-            self.dbcursor.execute(query)
             self.result = self.dbcursor.fetchall()
-        except:
-            self.result = list()
-        #logging.debug("FIXME: query(%r)" % len(self.result))
-        nores = self.result
+        except psycopg2.ProgrammingError as e:
+            if e.pgcode != None:
+                logging.error("Query failed to fetch! %r" % e.pgcode)
+
+        #logging.debug("Returned %r rows from query: %r" % 
(self.dbcursor.rowcount, self.dbcursor.statusmessage))
+        #if self.dbcursor.rowcount is None:
+        parsed = query.split(' ')
+        table = ""
+        if parsed[0] == "INSERT":
+            table = parsed[2]
+        if self.dbcursor.statusmessage == "INSERT 0 1":
+            logging.debug("Inserted into %r" % (table))
+            self.result = self.dbcursor.statusmessage
+        elif self.dbcursor.statusmessage == "INSERT 0 0":
+            logging.debug("Already exists in database %r" % (table))
         return self.result
 
+    def isConnected(self):
+        if self.dbshell.closed == 0:
+            return True
+        else:
+            return False
+
     def dump(self):
-        print("Dumping data from pgdb class")
-        self.list_functions()
+        print("Dumping data from postgresql class")
+        print("\tDB server: %r" % self.options.get('dbserver'))
+        print("\tDatabase: %r" % self.options.get('database'))
+        #self.list_functions()
         if self.dbshell.closed == 0:
             status = "Open"
         else:
             status = "Closed"
-        print("Connection: " + status)
-        print("DSN: " + self.dbshell.dsn)
-        print("AutoCommit: " + str(self.dbshell.autocommit))
+        print("\tConnection: " + status)
+        print("\tDSN: " + self.dbshell.dsn)
+        print("\tAutoCommit: " + str(self.dbshell.autocommit))
         for i in self.dbshell.notices:
-            print("History: " + i.replace('\n', ''))
+            print("\tHistory: " + i.replace('\n', ''))

-----------------------------------------------------------------------

Summary of changes:
 python/gpio433.py    | 62 +++++++++++++++++++++++++++++++++
 python/i2c.py        | 33 ++++++------------
 python/onewire.py    | 22 ++++++------
 python/ownet.py      | 57 +++++++++++-------------------
 python/pgd.py        | 83 ++++++++++++--------------------------------
 python/postgresql.py | 98 +++++++++++++++++++++++++++++++++++-----------------
 python/remote.py     | 41 ++++++++++++++++------
 python/rtl433.py     | 38 ++++++++------------
 python/rtlsdr.py     | 28 ++++-----------
 python/sensor.py     |  4 +++
 10 files changed, 248 insertions(+), 218 deletions(-)
 create mode 100755 python/gpio433.py
 mode change 100644 => 100755 python/rtlsdr.py


hooks/post-receive
-- 
powerguru



reply via email to

[Prev in Thread] Current Thread [Next in Thread]