Micropython is quite capable firmware to build prototypes and do experiments. Paired with ESP8266 micro controller board, it builds a perfect IoT client, which can be further interfaced with variety of sensors, motors, relays etc.
Fundamental of IoT is data collection from sensors and connected IoT nodes. You can also establish machine to machine communication other the behavior of nodes in network. For eg turn on AC relay when temperature and humidity sensor breaches thresholds. Here we will see, how can be send messages using MQTT protocol via a MQTT broker.
Let us see how can you publish a message payload using MQTT protocol on micronpython.
First connect to WiFi network
>>> import network
>>> sta_if = network.WLAN(network.STA_IF)
>>> sta_if.active(True)
>>> sta_if.connect('SSID', 'WiFiPassword')
>>> sta_if.ifconfig()
('192.168.0.107', '255.255.255.0', '192.168.0.1', '192.168.0.1')
Connect to MQTT server with authentication (optional)
>>> from umqtt.simple import MQTTClient
>>> client = MQTTClient("ClientID_Name", "MQTT_Broker_IP_Host", port=1883, user=b'mqttuserName', password=b'mqttPassword')
>>> client.connect()
('192.168.0.23', 1883)
0
Publish message on “testsubject” topic after connecting to MQTT broker
>>> client.publish(b"testsubject", b"hello from esp")
On MQTT subscriber of “testsubject” you should see following
mosquitto_sub -h 192.168.0.23 -p 1883 -t testsubject -u iotuser -P iotpass
hello from esp