MQTT client for ESP on micropython

Based on the ESP-MicroPython codebase an example of a mqtt client.

The original example is here
https://github.com/RuiSantosdotme/ESP-MicroPython/blob/master/code/MQTT/MQTT_Hello_World/ESP_1/main.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
80

from umqttsimple import MQTTClient
import network
import ubinascii
import machine
import time


WIFI_SSID = "..."
WIFI_PASS = "..."
# server is test.mosquitto.org
MQTT_SERVER = "5.196.95.208"
MQTT_CLIENTID = "test"
MQTT_TOPIC = "hello-esp"


def sub_cb(topic, msg):
print('ESP received hello message')
print((topic, msg))


def connect_and_subscribe(mqtt_server, client_id, topic_sub):
client = MQTTClient(ubinascii.hexlify(client_id), mqtt_server)
client.set_callback(sub_cb)
client.connect()
client.subscribe(topic_sub)
print('Connected to %s MQTT broker, subscribed to %s topic' %
(mqtt_server, topic_sub))
return client


def restart_and_reconnect():
print('Failed to connect to MQTT broker. Reconnecting...')
time.sleep(10)
machine.reset()


def connect_mqtt(mqtt_server, client_id, topic_sub):
try:
client = connect_and_subscribe(mqtt_server, client_id, topic_sub)
except OSError as err:
restart_and_reconnect()

counter = 0
message_interval = 10
last_message = 0

while True:
try:
client.check_msg()
if (time.time() - last_message) > message_interval:
msg = b'Hello #%d' % counter
client.publish(topic_sub, msg)
last_message = time.time()
counter += 1
except OSError as err:
print("restarting, err", err)
restart_and_reconnect()


def connect_wifi():
print("Connecting to " + WIFI_SSID)
station = network.WLAN(network.STA_IF)
station.active(True)
station.connect(WIFI_SSID, WIFI_PASS)
while station.isconnected() == False:
pass
print('wifi connected')
print(station.ifconfig())


def run():
connect_wifi()
connect_mqtt(MQTT_SERVER, MQTT_CLIENTID, MQTT_TOPIC)


if __name__ == '__main__':
run()