-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
103 lines (70 loc) · 2.21 KB
/
Copy pathmain.py
File metadata and controls
103 lines (70 loc) · 2.21 KB
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
from sanic import Sanic, response, Request, Websocket
import paho.mqtt.client as mqtt
import json
from datetime import datetime
import sqlite3
from models import MqttORM
app = Sanic(__name__)
try:
conn = sqlite3.connect('node-red-mqtt.db')
print('Opened database successfully')
conn.execute("""
CREATE TABLE IF NOT EXISTS mqttData(
ID INTEGER PRIMARY KEY AUTOINCREMENT,
topic TEXT NOT NULL,
payload TEXT NOTL NULL,
time TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP);""")
print('Table created successfully')
conn.close()
except AttributeError:
print('Mqtt Data is not created')
def on_connect(client, userdata, flags, rc):
print('Connected with result code ' + str(rc))
client.subscribe('#')
def on_message(client, userdata, msg):
print(msg.topic + " " + str(msg.payload))
conn = sqlite3.connect('node-red-mqtt.db')
sql = 'INSERT INTO mqttData (topic, payload) VALUES (?, ?)'
val = (msg.topic, msg.payload)
conn.execute(sql, val)
conn.commit()
try:
data = {
'topic': str(msg.topic),
'payload': str(msg.payload),
'time': str(datetime.now())
}
with open('mqtt_data.json', 'w') as outfile:
json.dump(data, outfile)
except TypeError:
print('Something went wrong')
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect('127.0.0.1', 1883, 60)
@app.listener('after_server_start')
async def listener(app, loop):
client.loop_start()
print('listener_7')
@app.route('/')
async def handler(request):
conn = sqlite3.connect('node-red-mqtt.db')
sql = 'SELECT * FROM mqttData'
data = conn.execute(sql)
conn.commit()
item = list(data)
print(str(item))
return response.json(str(item))
@app.websocket("/feed")
async def feed(request: Request, ws: Websocket):
while True:
conn = sqlite3.connect('node-red-mqtt.db')
sql = 'SELECT * FROM mqttData'
data = conn.execute(sql)
conn.commit()
item = list(data)
print('Sending: ' + item)
await ws.send(item)
item = await ws.recv()
if __name__ == '__main__':
app.run()