Last active
May 21, 2020 17:37
-
-
Save thisisjofrank/a0f39d1d347a60252d19c5b1c99ac002 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Include the required headers | |
#include <ESP8266WiFi.h> | |
#include "MqttConnection.h" | |
#include "DataStructures.h" | |
#include <WiFiClientSecure.h> | |
#include <MQTT.h> | |
// create an instance of WifiClientSecure, and call it espClient | |
WiFiClientSecure espClient; | |
// create an instance of the MQTTClient called client, provide it with a buffer of 4096 bytes to handle incoming messages | |
MQTTClient client(4096); | |
void mqtt_connection::ensure_mqtt_connected(void(*callback)(String&, String&)) | |
{ | |
if (client.connected()) { | |
return; | |
} | |
// set up an SSL fingerprint so that the secure client can verify the SSL cert of the MQTT broker | |
espClient.setFingerprint(cfg_->mqtt.certificate); | |
// tell the client the address of our broker, and provide it a wifi client (our secure client) to connect over | |
client.begin(cfg_->mqtt.server, cfg_->mqtt.port, espClient); | |
// pass a callback function to the client - which will call it for each message that's delivered over MQTT | |
client.onMessage(callback); | |
// receiving loop | |
while (!client.connected()) | |
{ | |
Serial.print(F("Attempting MQTT connection...")); | |
if (client.connect("tshirtHardware", cfg_->mqtt.user, cfg_->mqtt.password)) | |
{ | |
Serial.println(F("Connected.")); | |
client.subscribe(cfg_->mqtt.subscription); | |
} | |
else | |
{ | |
Serial.println(F("Failed to connect to MQTT - Trying again in 5 seconds...")); | |
delay(5000); | |
} | |
} | |
} | |
void mqtt_connection::process_messages() | |
{ | |
client.loop(); | |
} | |
int mqtt_connection::publish(String message) | |
{ | |
return client.publish(cfg_->mqtt.subscription, message); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment