-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain-MQTT-1.py
79 lines (67 loc) · 1.94 KB
/
main-MQTT-1.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
# Complete project details at https://RandomNerdTutorials.com
import time
from umqtt.simple import MQTTClient
import ubinascii
import machine
import micropython
import network
import esp
esp.osdebug(None)
import gc
gc.collect()
ssid = 'YOUR-WIFI-HERE'
password = 'YOUR-PASSWORD-HERE'
mqtt_server = 'YOUR-IP-SERVER-HERE'
#EXAMPLE IP ADDRESS
#mqtt_server = '192.168.1.144'
client_id = ubinascii.hexlify(machine.unique_id())
topic_sub = b'notification'
topic_pub = b'hello'
last_message = 0
message_interval = 5
counter = 0
station = network.WLAN(network.STA_IF)
station.active(True)
station.connect(ssid, password)
c = 0
while station.isconnected() == False:
print('Trying to connect {}'.format(c))
c += 1
time.sleep(0.5)
pass
print('Connection successful')
print(station.ifconfig())
######################################
######################################
######################################
def sub_cb(topic, msg):
print((topic, msg))
if topic == b'notification' and msg == b'received':
print('ESP received hello message')
def connect_and_subscribe():
global client_id, mqtt_server, topic_sub
client = MQTTClient(client_id, mqtt_server)
client.set_callback(sub_cb)
client.connect()
client.subscribe(topic_sub)
print('Connected to {} MQTT broker, subscribed to {} topic'.format(mqtt_server, topic_sub))
return client
def restart_and_reconnect():
print('Failed to connect to MQTT broker. Reconnecting...')
time.sleep(10)
machine.reset()
try:
client = connect_and_subscribe()
except OSError as e:
restart_and_reconnect()
while True:
try:
client.check_msg()
if (time.time() - last_message) > message_interval:
msg = b'Hello #{}'.format(counter)
print('Sending message: {}'.format(msg))
client.publish(topic_pub, msg)
last_message = time.time()
counter += 1
except OSError as e:
restart_and_reconnect()