forked from johncobb/echobaseppp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cpdb.py
264 lines (168 loc) · 7.58 KB
/
cpdb.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
import threading
import time
import Queue
import subprocess
import sqlite3
import json
import time
import binascii
import os
import cpcobs
from cprfmsg import CpRfMsg
from cpdefs import CpDefs
from cpdefs import CpEncoding
class CpDbManager(threading.Thread):
def __init__(self, inetThread, *args):
self._target = self.task_handler
self._args = args
self.__lock = threading.Lock()
self.records = Queue.Queue(10)
self.closing = False # A flag to indicate thread shutdown
self.inetThread = inetThread
self.db = CpDb()
threading.Thread.__init__(self)
def run(self):
self._target(*self._args)
def get_queue_depth(self):
return self.records.qsize()
def task_handler(self):
# Initialize database
self.db.initDb()
while not self.closing:
if (self.records.qsize() > 0):
# Pop the tag_info from the queue
tag_info = self.records.get(True)
#Production (saving raw bytes)
#self.db_handler(tag_info)
# Debug (saving readable tag info)
self.db_handler_debug(tag_info)
self.db_handler(tag_info)
# Production (sending raw bytes)
#self.inet_handler(tag_info)
# Debug (sending json)
#self.inet_handler_debug(tag_info)
self.inet_handler(tag_info)
self.records.task_done()
# Let database breathe
time.sleep(.0005)
def inet_handler(self, tag_info):
# Hydrate the message
msg = CpRfMsg(tag_info)
if(CpDefs.Encoding == CpEncoding.CpJson):
# Send message as standard JSON object
self.inetThread.enqueue_packet(msg.toJson())
elif(CpDefs.Encoding == CpEncoding.CpJsonCustom):
# Send message as custom JSON object
self.inetThread.enqueue_packet(msg.toCustomJson())
elif(CpDefs.Encoding == CpEncoding.CpJsonCustomBase64):
# Send message as Base64 encoded custom JSON object
self.inetThread.enqueue_packet(msg.toCustomJsonBase64())
elif(CpDefs.Encoding == CpEncoding.CpRaw):
# Send message in raw byte format
self.inetThread.enqueue_packet(msg)
def inet_handler_debug(self, tag_info):
# Hydrate the message
msg = CpRfMsg(tag_info)
self.inetThread.enqueue_packet(msg.toJson())
def db_handler_debug(self, tag_info):
# Hydrate the message
msg = CpRfMsg(tag_info)
# Write record to database
self.db.updateRecord(msg.shortAddr, binascii.hexlify(tag_info))
def db_handler(self, tag_info):
# Hydrate the message
msg = CpRfMsg(tag_info)
# TODO: handler for writing raw bytes to database
self.db.updateRecordBlob(msg.shortAddr, tag_info)
pass
def enqueue_record(self, record):
try:
self.records.put(record, block=True, timeout=1)
except:
self.__lock.acquire()
print "The CpDb queue is full"
self.__lock.release()
def shutdown_thread(self):
print 'shutting down CpDbManager...'
self.__lock.acquire()
self.closing = True
self.__lock.release()
class CpDb():
dbPath = 'test.db'
def initDb(self):
# Remove file every time for now until version is implemented
if(os.path.isfile(self.dbPath)):
os.remove(self.dbPath)
# Add version checking,vacuum etc...
print 'Initializing database ', self.dbPath
self.createTables()
def createTables(self):
conn = sqlite3.connect(self.dbPath)
print "Database opened successfully"
conn.execute("CREATE TABLE TAGS (ID INT PRIMARY KEY NOT NULL, TAG CHAR(128), TIMESTAMP INT);")
conn.execute("CREATE TABLE TAGS2 (ID INT PRIMARY KEY NOT NULL, TAG CHAR(128), TAGBLOB BLOB, TIMESTAMP INT);")
#conn.execute("CREATE TABLE VERSION (REV INT);")
print "Table created successfully"
conn.execute("INSERT INTO TAGS (ID, TAG, TIMESTAMP) VALUES (1, 'DUMMY', 0)")
conn.execute("INSERT INTO TAGS2 (ID, TAG, TAGBLOB, TIMESTAMP) VALUES (1, 'DUMMY', NULL, 0)")
conn.commit()
print "Records created successfully"
conn.close()
def queryTable(self):
conn = sqlite3.connect(self.dbPath)
cursor = conn.execute("SELECT ID, TAG, TIMESTAMP from TAGS")
for row in cursor:
print "ID = ", row[0]
print "TAG = ", row[1]
print "TIMESTAMP = ", row[2], "\n"
print "queryTable: success";
conn.close()
def updateTable(self, tagId, tagInfo):
conn = sqlite3.connect(self.dbPath)
#sql = "INSERT OR REPLACE INTO TAGS (ID, TAG, TIMESTAMP) VALUES (1, '0123456789ABCDEF1', DATETIME('NOW'))"
sql = "INSERT OR REPLACE INTO TAGS (ID, TAG, TIMESTAMP) VALUES (%d, '%s', DATETIME('NOW'))", tagId, tagInfo
cursor = conn.execute(sql)
conn.commit()
if(CpDefs.LogVerboseRf):
print "updateTable: success";
conn.close()
def updateRecord(self, tagId, tagInfo):
conn = sqlite3.connect(self.dbPath)
#sql = "INSERT OR REPLACE INTO TAGS (ID, TAG, TIMESTAMP) VALUES (1, '0123456789ABCDEF1', DATETIME('NOW'))"
sql = "INSERT OR REPLACE INTO TAGS (ID, TAG, TIMESTAMP) VALUES (%d, '%s', DATETIME('NOW'))" % (tagId, tagInfo)
cursor = conn.execute(sql)
conn.commit()
if(CpDefs.LogVerboseRf):
print "updateRecord: success";
conn.close()
def updateRecordBlob(self, tagId, tagInfo):
conn = sqlite3.connect(self.dbPath)
#sql = "INSERT OR REPLACE INTO TAGS (ID, TAG, TIMESTAMP) VALUES (1, '0123456789ABCDEF1', DATETIME('NOW'))"
sql = "INSERT OR REPLACE INTO TAGS2 (ID, TAG, TAGBLOB, TIMESTAMP) VALUES (?, ?, ?, DATETIME('NOW'))"
cursor = conn.execute(sql, (tagId, binascii.hexlify(tagInfo), buffer(tagInfo)))
conn.commit()
if(CpDefs.LogVerboseRf):
print "updateRecordBlob: success";
conn.close()
def deleteRecord(self):
conn = sqlite3.connect(self.dbPath)
sql = "DELETE FROM TAGS WHERE ID = 2"
cursor = conn.execute(sql)
conn.commit()
if(CpDefs.LogVerboseRf):
print "Operation completed successfully";
conn.close()
def vacuumDb(self):
#call(["sqlite3 test.db", "\"VACUUM;\""])
proc = subprocess.Popen(['sqlite3', self.dbPath, 'VACUUM;'] , stdout=subprocess.PIPE)
response = proc.communicate()
print "Results:"
print response[0]
if __name__ == '__main__':
cpdb = CpDb()
#cpdb.createTables()
#cpdb.updateTable()
cpdb.queryTable()
cpdb.deleteRecord()
cpdb.queryTable()
#cpdb.vacuumDb()