IoT - Kubus
/
Kubus
JNP3 16/17
server/databaseconnector.py
- Committer:
- Jan Kopa?ski
- Date:
- 2017-01-17
- Revision:
- 36:6686483418a4
- Parent:
- 35:0f01042765d6
- Child:
- 65:7153b7640953
File content as of revision 36:6686483418a4:
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 } ] } 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'] = entry[0] json_dict['sensors'][i]['timestamp'] = entry[1] except Error: print 'Database error on read: ' + t self.mutex.release() return json_dict