In my previous post I showed you how to connect your ESP 8266 to the Azure IoT hub and be able to receive messages from the IoT hub to turn on a LED. In this post I'll show you how to send data to the IoT hub. For this I need to use a sensor that I will read at regular intervals and then send the data back to the IoT hub. I picked a temperature and humidity sensor I had from the kit of sensors I bought
This sensor is compatible with the DHT MicroPython library. I order to connect to the IoT hub use the same connect code that is in my previous post. The difference with sending is you need a end point for MQTT to send you temperature and humidity data to. The topic to send to is as follows:
devices/<your deviceId>/messages/events/
So using the same device id as in the last post then my send topic would be devices/esp8266/messages/events/
To send a message to the IoT hub use the publish method. This needs the topic plus the message you want to send. I concatenated the temperature and humidity and separated them with a comma for simplicity
import dht
import time
sensor = dht.DHT11(machine.Pin(16))
mqtt=connectMQTT()
sendTopic = 'devices/<your deviceId>/messages/events/'
while True:
sensor.measure()
mqtt.publish(sendTopic,str(sensor.temperature())+','+str(sensor.humidity()),True)
time.sleep(1)
The code above is all that is required to read the sensor every second and send the data to the IoT hub.
In Visual Studio Code with the Azure IoT Hub Toolkit extension installed, you can monitor the messages that are sent to your IoT hub. In the devices view, right click on the device that has sent the data and select “Start Monitoring Built-in Event Endpoint”
This then displays the messages that are received by your IoT hub in the output window
You can see in the body of the received message the temperature and humidity values that were sent.
I still need to sort out generating the Shared Access Signature and also programmatically access the data I send to the IoT hub. I hope to have blog posts for these soon.