automatically attempt to reconnect to the MQTT if we fail to send a message

This commit is contained in:
Starbeamrainbowlabs 2022-06-30 21:44:25 +01:00
parent 856f2d27bb
commit bbb6d542f3
Signed by: sbrl
GPG key ID: 1BE5172E637709C2

View file

@ -66,6 +66,10 @@ PubSubClient mqtt;
Adafruit_BME280 bme; // I2C
/**
* Connect to the WiFi.
* @return void
*/
void connect_wifi() {
#ifndef WIFI_ENTERPRISE_ENABLED
Serial.print("personal");
@ -94,7 +98,64 @@ void connect_wifi() {
#endif
}
/**
* (Re)connect to the MQTT server.
* @return void
*/
void connect_mqtt() {
int delay = 1000;
while(true) {
Serial.print("MQTT: ");
mqtt = PubSubClient();
#ifdef MQTT_NO_TLS
Serial.print("notls");
#else
Serial.print("tls");
transport.setInsecure(); Serial.print(".");
#endif
// mqtt.setBufferSize(1000);
mqtt.setClient(transport); Serial.print(".");
mqtt.setServer(MQTT_SERVER, MQTT_PORT); Serial.print(".");
// Serial.print(MQTT_SERVER);
// Serial.print(":");
// Serial.print(MQTT_PORT);
// Serial.print(".");
if(mqtt.connect(
("autoplant_" + String(random(0, 999999))).c_str(),
MQTT_USERNAME, MQTT_PASSWORD)
) {
break;
}
/* Ref https://pubsubclient.knolleary.net/api#state
-4 : MQTT_CONNECTION_TIMEOUT - the server didn't respond within the keepalive time
-3 : MQTT_CONNECTION_LOST - the network connection was broken
-2 : MQTT_CONNECT_FAILED - the network connection failed
-1 : MQTT_DISCONNECTED - the client is disconnected cleanly
0 : MQTT_CONNECTED - the client is connected
1 : MQTT_CONNECT_BAD_PROTOCOL - the server doesn't support the requested version of MQTT
2 : MQTT_CONNECT_BAD_CLIENT_ID - the server rejected the client identifier
3 : MQTT_CONNECT_UNAVAILABLE - the server was unable to accept the connection
4 : MQTT_CONNECT_BAD_CREDENTIALS - the username/password were rejected
5 : MQTT_CONNECT_UNAUTHORIZED - the client was not authorized to connect
*/
int error_code = mqtt.state();
Serial.println("failed, error code "+String(error_code));
delay(delay);
delay += 1000;
if(delay > 60 * 1000) delay = 60 * 1000;
}
Serial.println("ok");
}
/**
* Read an analogue value from a sensor.
*
* @param int channel The channel on the analogue shift register to read from.
* @return float The analogue voltage read.
*/
float read_analog(int channel) {
const char* bin = std::bitset<8>(channel).to_string().c_str();
@ -113,6 +174,15 @@ float read_analog(int channel) {
return parsedValue;
}
/**
* Send an MQTT message.
* Does *not* attempt to reconnect if it fails.
*
* @param String id The 'hostname' of the sensor machine.
* @param String sensor The name of the sensor.
* @param float value The sensor value to send.
* @return bool Whether the MQTT messaage was sent successfully or not.
*/
bool send_mqtt(String id, String sensor, float value) {
// StaticJsonDocument<96> data;
//
@ -131,6 +201,26 @@ bool send_mqtt(String id, String sensor, float value) {
return result;
}
/**
* Send an MQTT message.
* Automatically attempts to reconnect if the connection fails for some reason.
*
* @param String id The 'hostname' of the sensor machine.
* @param String sensor The name of the sensor.
* @param float value The sensor value to send.
* @return bool Whether the MQTT messaage was sent successfully or not.
*/
bool do_send_mqtt(String id, String sensor, float value) {
bool result = send_mqtt(id, sensor, value);
if(!result) {
Serial.print("[mqtt] connection lost, error ");
Serial.println(value);
connect_mqtt();
}
result = send_mqtt(id, sensor, value);
return result;
}
void setup() {
Serial.begin(9600);
delay(1000);
@ -167,42 +257,7 @@ void setup() {
Serial.println(WiFi.status());
}
Serial.print("MQTT: ");
#ifdef MQTT_NO_TLS
Serial.print("notls");
#else
Serial.print("tls");
transport.setInsecure(); Serial.print(".");
#endif
// mqtt.setBufferSize(1000);
mqtt.setClient(transport); Serial.print(".");
mqtt.setServer(MQTT_SERVER, MQTT_PORT); Serial.print(".");
// Serial.print(MQTT_SERVER);
// Serial.print(":");
// Serial.print(MQTT_PORT);
// Serial.print(".");
if(!mqtt.connect(
("autoplant_" + String(random(0, 999999))).c_str(),
MQTT_USERNAME, MQTT_PASSWORD)
) {
/* Ref https://pubsubclient.knolleary.net/api#state
-4 : MQTT_CONNECTION_TIMEOUT - the server didn't respond within the keepalive time
-3 : MQTT_CONNECTION_LOST - the network connection was broken
-2 : MQTT_CONNECT_FAILED - the network connection failed
-1 : MQTT_DISCONNECTED - the client is disconnected cleanly
0 : MQTT_CONNECTED - the client is connected
1 : MQTT_CONNECT_BAD_PROTOCOL - the server doesn't support the requested version of MQTT
2 : MQTT_CONNECT_BAD_CLIENT_ID - the server rejected the client identifier
3 : MQTT_CONNECT_UNAVAILABLE - the server was unable to accept the connection
4 : MQTT_CONNECT_BAD_CREDENTIALS - the username/password were rejected
5 : MQTT_CONNECT_UNAUTHORIZED - the client was not authorized to connect
*/
int error_code = mqtt.state();
Serial.println("failed, error code "+String(error_code));
while(true) delay(10000);
}
Serial.println("ok");
connect_mqtt();
Serial.print("BME280: ");
@ -225,38 +280,38 @@ void loop() {
// StaticJsonDocument<96> data;
if(!send_mqtt(
if(!do_send_mqtt(
"autoplant-a",
"soil",
soil_a
)) Serial.println("[mqtt] Failed to send message");
if(!send_mqtt(
if(!do_send_mqtt(
"autoplant-a",
"water-level",
water_level_a
)) Serial.println("[mqtt] Failed to send message");
if(!send_mqtt(
if(!do_send_mqtt(
"autoplant-b",
"soil",
soil_b
)) Serial.println("[mqtt] Failed to send message");
if(!send_mqtt(
if(!do_send_mqtt(
"autoplant-b",
"water-level",
water_level_b
)) Serial.println("[mqtt] Failed to send message");
if(!send_mqtt(
if(!do_send_mqtt(
"autoplant-a",
"temperature",
temp
)) Serial.println("[mqtt] Failed to send message");
if(!send_mqtt(
if(!do_send_mqtt(
"autoplant-a",
"humidity",
humidity
)) Serial.println("[mqtt] Failed to send message");
if(!send_mqtt(
if(!do_send_mqtt(
"autoplant-a",
"pressure",
pressure