-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmqttNodeMCU.py
49 lines (40 loc) · 1.19 KB
/
mqttNodeMCU.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
import network
import time
import umqttsimple as mqtt
import machine
import ubinascii
import json
clientID = ubinascii.hexlify(machine.unique_id())
led = machine.Pin(2, machine.Pin.OUT)
led.value(1)
wlan = network.WLAN(network.STA_IF)
if not wlan.isconnected():
print("Connecting...")
wlan.active(True)
wlan.connect("TP-Link_4B8F", "25700086")
while not wlan.isconnected():
print(".", end='')
time.sleep(0.5)
print("\nNetwork config: ", wlan.ifconfig())
def subcallback(topic, msg):
print(topic, msg)
mdata = json.loads(msg.decode())
print(mdata["sensor"], mdata["nilai"])
if mdata["nilai"] > 37.0:
led.value(0)
else:
led.value(1)
print("ID: ", clientID)
client = mqtt.MQTTClient(clientID, "broker.hivemq.com")
client.set_callback(subcallback)
client.connect()
client.subscribe(b"nsone/smartlamp")
print("Connected")
lastime = time.time()
while True:
client.check_msg()
if time.time() - lastime >5:
mdata = {"sensor":"TEMP", "nilai":39.3}
message = json.dumps(mdata)
client.publish(b"nsone/smartlamp", message.encode())
lastime = time.time()