try:
uri = cherrypy.request.app.config['database']['uri']
client = MongoClient(uri)
- db = client.test.sensorlog
+ db = client.sensorhub.sensorlog
cursor = db.find().sort([("timestamp", pymongo.DESCENDING)]).limit(1)
item = dict(next(cursor))
del item['_id']
def get_since(self, when, until = None):
uri = cherrypy.request.app.config['database']['uri']
client = MongoClient(uri)
- db = client.test.sensorlog
+ db = client.sensorhub.sensorlog
selector = [{"timestamp": {"$gt": str(when)}}]
if not until is None:
selector.append({"timestamp": {"$lt": str(until)}})
def hosts(self):
uri = cherrypy.request.app.config['database']['uri']
client = MongoClient(uri)
- db = client.test.sensorlog
+ db = client.sensorhub.sensorlog
# groupby("name")
result = [x['_id'] for x in db.aggregate([{"$group": {"_id": "$name"}} ])]
return dict(response=result, version=self.version)
def sensors(self, hostname):
uri = cherrypy.request.app.config['database']['uri']
client = MongoClient(uri)
- db = client.test.sensorlog
+ db = client.sensorhub.sensorlog
groups = [x['_id'] for x in db.aggregate([
{"$match": {"name": hostname}},
{"$group": {"_id": "$sensors.id"}}
return json.dumps(res).encode(encoding="utf-8")
except Exception as e:
cherrypy.response.headers['content-type'] = 'application/json'
- self.log("error in \"since\": {0}\n {1}".format(str(e), repr(param)))
+ self.log("error in \"since\": {0}\n {1}".format(str(e), repr(cherrypy.request.params)))
res = dict(response='error', message=str(e))
res = json.dumps(res).encode(encoding='utf-8')
return res
__copyright__ = 'Copyright (c) 2016 Pat Thoyts'
class SensorDataIterator():
+ """Parse a sensor hub ASCII data file into discrete records.
+
+ The sensor hub emits ASCII data with one record per line but with some initial
+ lines prefixed with a # character as a comment and the initial line may get
+ truncated due to serial buffering.
+ The results may have from 1 to 3 temperature values depending on how many sensors
+ have been picked up."""
def __init__(self, filename):
self.filename = filename
self.re = re.compile(r': {(?P<T>.*?)} {(?P<H>.*?)} {(?P<P>.*?)}$')
granularity = 60 # 1 per minute
granularity = int(granularity)
mongo = MongoClient()
- db = mongo.test.sensorlog
+ db = mongo.sensorhub.sensorlog
db.drop()
r = db.insert_many([item for item in GranularData(iter(SensorData(filename)), granularity)])
print("imported {0} records".format(len(r.inserted_ids)))
return 0
+def update_from_logfile(filename, granularity = None):
+ """Import new records from the sensor-hub logfile into the mongo database."""
+ if granularity is None:
+ granularity = 60 # 1 per minute
+ granularity = int(granularity)
+ mongo = MongoClient()
+ db = mongo.sensorhub.sensorlog
+ # find the last entry in the database
+ cursor = db.find().sort([("timestamp", pymongo.DESCENDING)]).limit(1)
+ last = dict(next(cursor))
+ last_timestamp = int(last['timestamp']) + granularity
+ # skip logdata up to the last database entry
+ # add the remaining entries.
+ r = db.insert_many([x for x in GranularData(iter(SensorData(filename)), granularity)
+ if int(x['timestamp']) > last_timestamp])
+ print("imported {0} records".format(len(r.inserted_ids)))
+ return 0
+
def tojson(filename, granularity = None):
+ if granularity is None:
+ granularity = 60 # 1 per minute
for item in GranularData(iter(SensorData(filename)), granularity):
print(item)
return 0
'''
uri = 'mongodb://localhost:27017/test'
client = MongoClient(uri)
- db = client.test.sensorlog
+ db = client.sensorhub.sensorlog
#db.insert_one(json) / insert_many (iterable)
#cursor = db.find({"name": "spd-office"})
#cursor = db.find({"sensors.id": "office1", "sensors.value": "22.25"})
if len(sys.argv) > 1:
if sys.argv[1] == 'import':
import_logfile(*sys.argv[2:])
+ elif sys.argv[1] == 'update':
+ update_from_logfile(*sys.argv[2:])
elif sys.argv[1] == 'json':
tojson(*sys.argv[2:])
elif sys.argv[1] == 'test':