mqtt.cpp 7.1 KB
Newer Older
1
2
#include "mqtt.h"

Eric Duminil's avatar
Eric Duminil committed
3
4
5
6
7
8
9
#include "config.h"
#include "util.h" // -> time.h
#include "led_effects.h"
#include "sensor_console.h"
#include "wifi_util.h"
#include "src/lib/PubSubClient/src/PubSubClient.h"

10
11
namespace config {
  // Values should be defined in config.h
12
  uint16_t mqtt_sending_interval = MQTT_SENDING_INTERVAL; // [s]
13
14
15
16
17
18
19
20
21
  //INFO: Listen to every CO2 sensor which is connected to the server:
  //  mosquitto_sub -h MQTT_SERVER -t 'CO2sensors/#' -p 443 --capath /etc/ssl/certs/ -u "MQTT_USER" -P "MQTT_PASSWORD" -v
  const char *mqtt_server = MQTT_SERVER;
  const uint16_t mqtt_port = MQTT_PORT;
  const char *mqtt_user = MQTT_USER;
  const char *mqtt_password = MQTT_PASSWORD;
  const bool allow_mqtt_commands = ALLOW_MQTT_COMMANDS;
  const unsigned long wait_after_fail = 900; // [s] Wait 15 minutes after an MQTT connection fail, before trying again.
}
22
23
24
25
26

#if MQTT_ENCRYPTED
#  if defined(ESP32)
#    include <WiFiClientSecure.h>
#  endif
27
WiFiClientSecure espClient;
28
29
30
31
#else
WiFiClient espClient;
#endif

32
33
34
35
36
PubSubClient mqttClient(espClient);

namespace mqtt {
  unsigned long last_sent_at = 0;
  unsigned long last_failed_at = 0;
37
  bool connected = false;
38

Eric Duminil's avatar
Eric Duminil committed
39
  char publish_topic[21]; // e.g. "CO2sensors/ESPxxxxxx\0"
40
  const char *json_sensor_format;
41
  char last_successful_publish[23] = "";
42

Eric Duminil's avatar
Eric Duminil committed
43
  void initialize(const char *sensorId) {
44
    json_sensor_format = PSTR("{\"time\":\"%s\", \"co2\":%d, \"temp\":%.1f, \"rh\":%.1f}");
Eric Duminil's avatar
Eric Duminil committed
45
    snprintf(publish_topic, sizeof(publish_topic), "CO2sensors/%s", sensorId);
46
#if MQTT_ENCRYPTED
47
48
49
    // The sensor doesn't check the fingerprint of the MQTT broker, because otherwise this fingerprint should be updated
    // on the sensor every 3 months. The connection can still be encrypted, though:
    espClient.setInsecure(); // If not available for ESP32, please update Arduino IDE / PlatformIO
50
#endif
51
    mqttClient.setServer(config::mqtt_server, config::mqtt_port);
Eric Duminil's avatar
Eric Duminil committed
52

53
    sensor_console::defineIntCommand("mqtt", setMQTTinterval, F("60 (Sets MQTT sending interval, in s)"));
54
    sensor_console::defineCommand("send_local_ip", sendInfoAboutLocalNetwork,
55
        F("(Sends local IP and SSID via MQTT. Can be useful to find sensor)"));
56
57
  }

58
  void publish(const char *timestamp, int16_t co2, float temperature, float humidity) {
59
    if (WiFi.status() == WL_CONNECTED && mqttClient.connected()) {
60
      led_effects::onBoardLEDOn();
Eric Duminil's avatar
Eric Duminil committed
61
      Serial.print(F("MQTT - Publishing message ... "));
62
63

      char payload[75]; // Should be enough for json...
64
      snprintf(payload, sizeof(payload), json_sensor_format, timestamp, co2, temperature, humidity);
65
      // Topic is the same as clientID. e.g. 'CO2sensors/ESP3d03da'
Eric Duminil's avatar
Eric Duminil committed
66
      if (mqttClient.publish(publish_topic, payload)) {
Eric Duminil's avatar
Eric Duminil committed
67
        Serial.println(F("OK"));
68
        ntp::getLocalTime(last_successful_publish);
69
      } else {
Eric Duminil's avatar
Eric Duminil committed
70
        Serial.println(F("Failed."));
71
      }
72
      led_effects::onBoardLEDOff();
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
    }
  }

  /**
   * Allows sensor to be controlled by commands over MQTT
   *
   * mosquitto_pub -h MQTT_SERVER -t 'CO2sensors/SENSOR_ID/control' -p 443 --capath /etc/ssl/certs/ -u "MQTT_USER" -P "MQTT_PASSWORD" -m "reset"
   * mosquitto_pub -h MQTT_SERVER -t 'CO2sensors/SENSOR_ID/control' -p 443 --capath /etc/ssl/certs/ -u "MQTT_USER" -P "MQTT_PASSWORD" -m "timer 30"
   * mosquitto_pub -h MQTT_SERVER -t 'CO2sensors/SENSOR_ID/control' -p 443 --capath /etc/ssl/certs/ -u "MQTT_USER" -P "MQTT_PASSWORD" -m "mqtt 900"
   * mosquitto_pub -h MQTT_SERVER -t 'CO2sensors/SENSOR_ID/control' -p 443 --capath /etc/ssl/certs/ -u "MQTT_USER" -P "MQTT_PASSWORD" -m "calibrate 700"
   */
  void controlSensorCallback(char *sub_topic, byte *message, unsigned int length) {
    if (length == 0) {
      return;
    }
88
    led_effects::onBoardLEDOn();
89
    Serial.print(F("Message arrived on topic: "));
Eric Duminil's avatar
Eric Duminil committed
90
91
    Serial.println(sub_topic);
    char command[length + 1];
92
    for (unsigned int i = 0; i < length; i++) {
Eric Duminil's avatar
Eric Duminil committed
93
      command[i] = message[i];
94
    }
Eric Duminil's avatar
Eric Duminil committed
95
    command[length] = 0;
96
    sensor_console::execute(command);
Eric Duminil's avatar
Eric Duminil committed
97
    led_effects::onBoardLEDOff();
98
99
100
  }

  void reconnect() {
Eric Duminil's avatar
Eric Duminil committed
101
    if (last_failed_at > 0 && (seconds() - last_failed_at < config::wait_after_fail)) {
102
103
104
105
106
107
108
      // It failed less than wait_after_fail ago. Not even trying.
      return;
    }
    if (WiFi.status() != WL_CONNECTED) { //NOTE: Sadly, WiFi.status is sometimes WL_CONNECTED even though it's really not
      // No WIFI
      return;
    }
109

Eric Duminil's avatar
Eric Duminil committed
110
111
112
    Serial.print(F("MQTT - Attempting connection to "));
    Serial.print(MQTT_SERVER);
    Serial.print(MQTT_ENCRYPTED ? F(" (Encrypted") : F(" (Unencrypted"));
113
114
115
    Serial.print(F(", port "));
    Serial.print(MQTT_PORT);
    Serial.print(F(") ..."));
116

117
    led_effects::onBoardLEDOn();
118
    // Wait for connection, at most 15s (default)
Eric Duminil's avatar
Eric Duminil committed
119
    mqttClient.connect(publish_topic, config::mqtt_user, config::mqtt_password);
120
    led_effects::onBoardLEDOff();
121

122
123
124
    connected = mqttClient.connected();

    if (connected) {
125
      if (config::allow_mqtt_commands) {
126
        char control_topic[60]; // Should be enough for "CO2sensors/ESPd03cc5/control"
Eric Duminil's avatar
Eric Duminil committed
127
        snprintf(control_topic, sizeof(control_topic), "%s/control", publish_topic);
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
        mqttClient.subscribe(control_topic);
        mqttClient.setCallback(controlSensorCallback);
      }
      Serial.println(F(" Connected."));
      last_failed_at = 0;
    } else {
      last_failed_at = seconds();
      Serial.print(F(" Failed! Error code="));
      Serial.print(mqttClient.state());
      Serial.print(F(". Will try again in "));
      Serial.print(config::wait_after_fail);
      Serial.println("s.");
    }
  }

143
  void publishIfTimeHasCome(const char *timestamp, const int16_t &co2, const float &temp, const float &hum) {
144
145
    // Send message via MQTT according to sending interval
    unsigned long now = seconds();
146
    if (now - last_sent_at > config::mqtt_sending_interval) {
147
      last_sent_at = now;
148
      publish(timestamp, co2, temp, hum);
149
150
151
152
153
154
155
156
157
158
159
    }
  }

  void keepConnection() {
    // Keep MQTT connection
    if (!mqttClient.connected()) {
      reconnect();
    }
    mqttClient.loop();
  }

160
161
162
163
  /*****************************************************************
   * Callbacks for sensor commands                                 *
   *****************************************************************/
  void setMQTTinterval(int32_t sending_interval) {
164
    config::mqtt_sending_interval = sending_interval;
Eric Duminil's avatar
Eric Duminil committed
165
    Serial.print(F("Setting MQTT sending interval to : "));
166
    Serial.print(config::mqtt_sending_interval);
167
168
169
    Serial.println("s.");
    led_effects::showKITTWheel(color::green, 1);
  }
Eric Duminil's avatar
Eric Duminil committed
170
171
172
173
174
175

  // It can be hard to find the local IP of a sensor if it isn't connected to Serial port, and if mDNS is disabled.
  // If the sensor can be reach by MQTT, it can answer with info about local_ip and ssid.
  // The sensor will send the info to "CO2sensors/ESP123456/info".
  void sendInfoAboutLocalNetwork() {
    char info_topic[60]; // Should be enough for "CO2sensors/ESP123456/info"
Eric Duminil's avatar
Eric Duminil committed
176
    snprintf(info_topic, sizeof(info_topic), "%s/info", publish_topic);
Eric Duminil's avatar
Eric Duminil committed
177
178
179

    char payload[75]; // Should be enough for info json...
    const char *json_info_format = PSTR("{\"local_ip\":\"%s\", \"ssid\":\"%s\"}");
Eric Duminil's avatar
Eric Duminil committed
180
    snprintf(payload, sizeof(payload), json_info_format, wifi::local_ip, WIFI_SSID);
Eric Duminil's avatar
Eric Duminil committed
181
182
183

    mqttClient.publish(info_topic, payload);
  }
184
}