-
Notifications
You must be signed in to change notification settings - Fork 6
/
database.py
71 lines (56 loc) · 2.4 KB
/
database.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
'''
Handle database interactions.
Read and write discovered Xsens DOTs.
'''
import sqlite3
from app_logger import Logger
logger = Logger(__name__)
class XsensDOTDatabase:
def __init__(self, name="database.sqlite"):
logger.logger.info("Connecting to database: {}...".format(name))
self.conn = sqlite3.connect(name)
self.cursor = self.conn.cursor()
self._create_tables()
def add_device(self, ble_address, status, signal_strength):
# Add an Xsens DOT device to the database
status = "Disconnected"
local_name = "Xsens DOT"
if self._device_already_found(ble_address):
logger.logger.debug("Device with address {} already in database.".format(ble_address))
else:
self.cursor.execute("INSERT INTO devices VALUES (?,?,?,?,?)",
([None, ble_address, local_name, status, signal_strength]))
self.conn.commit()
def _create_tables(self):
if not self._table_exists("devices"):
logger.logger.debug("`devices` table does not exist. Creating...")
self._create_device_table()
def _table_exists(self, name):
# Check if a table of `name` exists. If SELECT fails, it does not.
try:
self.cursor.execute("SELECT * FROM {}".format(name))
except sqlite3.OperationalError as e:
logger.logger.error(e)
return False
except Error as e:
logger.logger.error(e)
return False
return True
def _create_device_table(self):
# Create a table to store scanned Bluetooth devices in
try:
self.cursor.execute('''CREATE TABLE devices
(device_id INTEGER PRIMARY KEY,
ble_address varchar(17) NOT NULL ,
local_name varchar(20),
status varchar(20),
signal_strength_dbm INTEGER)''')
except sqlite3.OperationalError as e:
logger.logger.error(e)
def _device_already_found(self, ble_address):
device_cursor = self.cursor.execute(
"SELECT * FROM devices WHERE ble_address = '{}'".format(ble_address))
devices = device_cursor.fetchall()
if len(devices) == 0:
return False
return True