JNP3 16/17

Dependencies:   mbed nRF24L01P

Revision:
30:27c08888a838
Parent:
16:1569130916f1
Child:
35:0f01042765d6
--- a/server/databaseconnector.py	Tue Jan 10 16:40:04 2017 +0000
+++ b/server/databaseconnector.py	Wed Jan 11 00:11:56 2017 +0100
@@ -1,5 +1,5 @@
 from sqlite3 import connect, Error
-
+from threading import Lock
 
 json_template = {
     'sensors': [
@@ -37,12 +37,14 @@
         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:
@@ -50,16 +52,20 @@
         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)
-                value = self.curr.fetchone()[0]
-                json_dict['sensors'][i]['value'] = value
+                entry = self.curr.fetchone()
+                if entry:
+                    json_dict['sensors'][i]['value'] = entry[0]
             except Error:
                 print 'Database error on read: ' + t
-        return json_dict
\ No newline at end of file
+        self.mutex.release()
+        return json_dict