Include the humidity and pressure data in the sensor log JSON items and ASCII download.
authorPat Thoyts <Patrick.Thoyts@renishaw.com>
Tue, 17 May 2016 22:54:02 +0000 (23:54 +0100)
committerPat Thoyts <Patrick.Thoyts@renishaw.com>
Tue, 17 May 2016 22:54:02 +0000 (23:54 +0100)
sensor-hub.wsgi
sensordata.py

index 6009057b7d69a28fb7057c76c31b49df6193ba6d..4f27a8f172af2fdb56e0b9bf3dcb56f00b204cdb 100755 (executable)
@@ -128,6 +128,22 @@ class SensorHubService():
             return int(dateparser.parse(str).timestamp())
 
     def get_ascii(self, data):
+        for item in data:
+            t,h,p = 0,0,0
+            t = datetime.fromtimestamp(int(item['timestamp']))
+            if 'humidity' in item:
+                h = item['humidity']
+            if 'pressure' in item:
+                p = item['pressure']
+            m = "{0!s} {1!s} {2!s} {3!s} {4!s}".format(t.isoformat(),
+                                                       item['timestamp'],
+                                                       item['name'],
+                                                       h,
+                                                       p)
+            for sensor in sorted(item['sensors'], key=lambda x: x['id']):
+                m = m + " {0!s} {1:.2f}".format(sensor['id'], float(sensor['value']))
+            yield m + "\n"
+
     @cherrypy.expose
     def download(self, *args, **kwargs):
         try:
@@ -141,7 +157,7 @@ class SensorHubService():
                 data = self.get_since(param_from, param_until)
                 if cherrypy.request.params.get('type') == 'text':
                     cherrypy.response.headers['content-type'] = 'text/plain'
-                    raise Exception("not implemented")
+                    return self.get_ascii(data)
                 else:
                     cherrypy.response.headers['content-type'] = 'application/json'
                     res = dict(response="ok", result=[x for x in data], version=self.version)
index 42d84d592ef84c92b7e0357f75dc48e95fd369a3..4c0142596fece2ce97966c404037368332a85080 100644 (file)
@@ -44,7 +44,14 @@ class SensorDataIterator():
                 sensors = []
                 for sensor,value in zip(['office1','office2','office3'], m.group('T').split()):
                     sensors.append({'id': sensor, 'value': value })
-                return dict(timestamp=timestamp, name='spd-office', sensors=sensors)
+                item = dict(timestamp=timestamp, name='spd-office', sensors=sensors)
+                humidity = m.group('H').split()
+                if len(humidity) > 0:
+                    item['humidity'] = float(humidity[0])
+                pressure = m.group('P').split()
+                if len(pressure) > 0:
+                    item['pressure'] = float(pressure[0])
+                return item
 
 class SensorData():
     def __init__(self, filename):
@@ -79,6 +86,8 @@ class TestSensorData(unittest.TestCase):
             for sensor in item['sensors']:
                 check.append(sensor['id'])
             self.assertListEqual(['office1','office2','office3'], check)
+            self.assertIn('humidity', item.keys())
+            self.assertIn('pressure', item.keys())
             count = count + 1
         self.assertEqual(3, count)
 
@@ -107,6 +116,7 @@ def import_logfile(filename, granularity = None):
     mongo = MongoClient()
     db = mongo.sensorhub.sensorlog
     db.drop()
+    db.create_index([("timestamp", pymongo.ASCENDING)]) # creates if not already present
     r = db.insert_many([item for item in GranularData(iter(SensorData(filename)), granularity)])
     print("imported {0} records".format(len(r.inserted_ids)))
     return 0
@@ -148,7 +158,7 @@ def recent(*args, **kwargs):
     cursor = db.find().sort([("timestamp", pymongo.DESCENDING)]).limit(1)
     item = next(cursor)
     return item
-    
+
 def opendb():
     config = ConfigParser()
     config.read('sensor-hub.config')