-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathserial_sqlwriter.py
44 lines (36 loc) · 1.25 KB
/
serial_sqlwriter.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
from time import gmtime, strftime
import sqlite3
import serial
from sqlite3 import Error
import json
dbFile = "data.db"
ser = serial.Serial('/dev/ttyUSB0',115200)
def writeToDb(theTime, duckId, topic, messageId, payload, path, hops, duckType):
conn = sqlite3.connect(dbFile)
c = conn.cursor()
print ("Writing to db...")
try:
c.execute("INSERT INTO clusterData VALUES (?,?,?,?,?,?,?,?)", (theTime, duckId, topic, messageId, payload, path, hops, duckType))
conn.commit()
conn.close()
except Error as e:
print(e)
try:
db = sqlite3.connect(dbFile)
db.cursor().execute("CREATE TABLE IF NOT EXISTS clusterData (timestamp datetime, duck_id TEXT, topic TEXT, message_id TEXT, payload TEXT, path TEXT, hops INT, duck_type INT)")
db.commit()
db.close()
except Error as e:
print(e)
while True:
theTime = strftime("%Y-%m-%d %H:%M:%S", gmtime())
payload = ser.readline()
prstrip = payload.rstrip().decode('utf8')
if len(prstrip) >0:
print(prstrip)
try:
p = json.loads(prstrip)
writeToDb(theTime, p["DeviceID"], p["topic"], p["MessageID"], p["Payload"], p["path"],p["hops"],p["duckType"])
except:
print(prstrip)
print("Invalid Packet")