>> MQTT.. Library Setup. Library Setup
Now, that we have the project built and synchronized, it's time to code the ESP32 to send data over the MQTT protocol.
1- To publish data over MQTT, install the libraries umqtt.robust and umqtt.simple.
First, we are going to add the folders to hold the libraries. Right click on the folder "ESP32" and select "New folder", and assign "lib" as the name.
2- Next, we have to add the library “umqtt” into the "lib" folder. Right click on the folder "lib" and select "New Folder" and assign it the name: "umqtt".
3- Then, click on the folder “umqtt” and select “New File”, assigning the name “simple.py”. Copy the code from the Micropython “simple.py”repository and paste it into “simple.py” file. Next, repeat these instructions but with “robust.py” as the file name and paste this “robust.py” Micropython library into the file.
**Save your simple.py and robust.py code files when finished.
4- Complete the setup by synchronizing the project. In the upper toolbar, select Packages > Pymakr > Synchronize project.
D. Coding time
1- Now that we have the project built and synchronized, it's time to code. To send data to Ubidots copy, paste, and save the below code into the “boot.py” file.
**Save the file once you’ve pasted the code in the "boot.py" file.
import time
import network
import machine as m).
from umqtt.robust import MQTTClient
import machine as m
ubidotsToken = “YOUR-UBIDOTS-TOKEN-HERE”
clientID = “RANDOM-ALPHA-NUMERIC-NAME_OR_IMEI DEVICE ID”
client = MQTTClient("clientID", "industrial.api.ubidots.com", 1883, user = ubidotsToken, password = ubidotsToken)
def checkwifi():
while not sta_if.isconnected():
time.sleep_ms(500)
print(".")
sta_if.connect()
pin13 = m.Pin(13, m.Pin.IN, m.Pin.PULL_UP)
def publish():
while True:
checkwifi()
client.connect()
lat = 6.2
lng = -75.56
var = repr(pin13.value())
msg = b'{"location": {"value":%s, "context":{"lat":%s, "lng":%s}}}' % (var, lat, lng)
print(msg)
client.publish(b"/v1.6/devices/ESP32", msg)
time.sleep(20)
publish()
3- Confirm all codes have been saved properly; then, synchronize the project once more. Repeat steps 6 and 4 above respectively. Once the project has been synchronized with the device, the module will run automatically.
Results
Go to your Ubidots account to visualize the device and data just created.
In less than 30 minutes, the ESP32 module is now available for publishing data to the Ubidots cloud over MQTT protocol, using WiFi. Now it’s time to build a dashboard and create widgets to manage the variables of your ESP32 module.