IoT - Kubus
/
Kubus
JNP3 16/17
server/databaseconnector.py
- Committer:
- pannaanna
- Date:
- 2017-01-23
- Revision:
- 68:e88f3fd2e9cf
- Parent:
- 65:7153b7640953
File content as of revision 68:e88f3fd2e9cf:
from sqlite3 import connect, Error from threading import Lock from datetime import datetime json_template = { 'sensors': [ { 'name': 'Motion at the stairway', 'type': 'bool', 'value': None, 'timestamp': None }, { 'name': 'Motion at the entrance', 'type': 'bool', 'value': None, 'timestamp': None }, { 'name': 'Distance at the entrance', 'type': 'number', 'range': [0, 90], 'unit': 'cm', 'value': None, 'timestamp': None }, { 'name': 'Volume inside', 'type': 'number', 'range': [-30, 30], 'unit': 'dB', 'value': None, 'timestamp': None } ] } funs = { 'pir1': lambda x: x, 'pir2': lambda x: x, 'distance': lambda x: 18 / (3.3 * x - 0.4), 'volume': lambda x: x, } class DatabaseConnector: def __init__(self, database, tables, separator=':'): self.tables = tables self.separator = separator self.conn = connect(database=database, check_same_thread=False) self.curr = self.conn.cursor() self.mutex = Lock() def write(self, table, data): if not data: return 'Request message is empty' vals = data.split(self.separator) vals += [datetime.now()] stmt = ("INSERT INTO %s VALUES (NULL" + (", ?" * len(vals)) + ")") % table self.mutex.acquire() try: self.curr.execute(stmt, vals) except Error as e: return e.message except: return 'Undefined exception' self.conn.commit() self.mutex.release() return None def read(self): stmt = 'SELECT value, timestamp FROM %s ORDER BY id DESC LIMIT 1' json_dict = json_template self.mutex.acquire() for i, t in enumerate(self.tables): try: self.curr.execute(stmt % t) entry = self.curr.fetchone() if entry: json_dict['sensors'][i]['value'] = funs[t](entry[0]) json_dict['sensors'][i]['timestamp'] = entry[1] except Error: print 'Database error on read: ' + t self.mutex.release() return json_dict