-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflaskk.py
33 lines (26 loc) · 862 Bytes
/
flaskk.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
import paho.mqtt.client as mqtt
import time
import json
import sqlite3
def on_connect(client, data, flags, rc):
client.subscribe("nsone/smartlamp")
def on_message(client, data, msg):
conn = sqlite3.connect("database.db")
cursor = conn.cursor()
print(msg.topic, msg.payload)
mdata = msg.payload.decode()
mdata = json.loads(mdata) # json -> dict
sensor = mdata["sensor"]
nilai = mdata["nilai"]
print(sensor, nilai)
cursor.execute("INSERT INTO iot (sensor, nilai, tanggal, waktu, stamp) VALUES ( '%s', %s, current_date, current_time, current_timestamp )" % ( sensor, nilai ))
conn.commit()
cursor.close()
conn.close()
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("broker.hivemq.com",1883)
client.loop_start()
while True:
time.sleep(10)