Enabling MQTT
We’re using a secure connection, but can’t validate the SSL certificate from HiveMQ right now. This means we have to loosen restrictions a little bit by keeping the connection encrypted, but placing blind trust in the server on the other end. This would not be an optimal situation if some heavy industrial machinery was waiting for commands to run, but it’s not going to hurt us for a thermometer prototype.
This requires including another header and explicitly setting up a blind trust connection:
#include <WiFiClientSecure.h>
// in variables section
WiFiClientSecure net;
// in the connect() method
void connect() {
net.setInsecure();
}
To get MQTT working, we need to include the client library and also give it a variable to store its state.
It also has its own section in both connect() and setup() to handle startup and reconnects, and looks
vaguely familiar to code we already have.
#include <MQTT.h>
// in variables section
MQTTClient client;
// in the connect() method
void connect() {
// after other Serial.print + while{} loops
Serial.print("connecting to MQTT...");
while (!client.connect(MQTT_NAME, MQTT_NAME, MQTT_PASS)) {
Serial.print(".");
delay(1000);
}
}
// at startup in setup()
void setup() {
// WiFi.begin(...);
client.begin(MQTT_SERVER, MQTT_PORT, net);
}
In the main loop, it can also check if wifi has dropped between updates and make use of the connect()
method to reconnect before sending another message.
void loop()
{
// at the top of the loop
client.loop();
if (!client.connected()) {
connect();
}
}
And the message can be published after creating the JSON document is serialized.
if(ok) {
// serializeJson(doc, message);
// Serial.println(message);
client.publish(MQTT_TOPIC, message);
}
Notice a few of the #define macros from the Notepad document? They come into play here, too.
Here’s what it looks like assembled:
| |
If you just copied the above code block, don’t forget to change out #define statements with your own info!
With the board plugged in to USB, go ahead and upload it with mqtt info. The serial monitor will now show it connecting to HiveMQ, and we can watch the data stream on the server end.
Next Up: Verify MQTT