JNP3 16/17

Dependencies:   mbed nRF24L01P

server/databaseconnector.py

Committer:
Jan Kopa?ski
Date:
2017-01-11
Revision:
30:27c08888a838
Parent:
16:1569130916f1
Child:
35:0f01042765d6

File content as of revision 30:27c08888a838:

from sqlite3 import connect, Error
from threading import Lock

json_template = {
    'sensors': [
        {
            'name': 'Motion at the stairway',
            'type': 'bool',
            'value': None
        },
        {
            'name': 'Motion at the entrance',
            'type': 'bool',
            'value': None
        },
        {
            'name': 'Distance at the entrance',
            'type': 'number',
            'range': [0, 90],
            'unit': 'cm',
            'value': None
        },
        {
            'name': 'Volume inside',
            'type': 'number',
            'range': [-30, 30],
            'unit': 'dB',
            'value': 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)
        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 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]
            except Error:
                print 'Database error on read: ' + t
        self.mutex.release()
        return json_dict