mqtt.cpp 6.72 KB
Newer Older
1
2
3
4
#include "mqtt.h"

namespace config {
  // Values should be defined in config.h
5
  uint16_t sending_interval = MQTT_SENDING_INTERVAL; // [s]
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  //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.
}
#if defined(ESP32)
#  include <WiFiClientSecure.h>
#endif
WiFiClientSecure espClient;
PubSubClient mqttClient(espClient);

namespace mqtt {
  unsigned long last_sent_at = 0;
  unsigned long last_failed_at = 0;
24
  bool connected = false;
25
26
27
28
29

  String publish_topic;
  const char *json_sensor_format;
  String last_successful_publish = "";

Eric Duminil's avatar
Eric Duminil committed
30
31
32
33
34
35
36
37
  void setMQTTinterval(int32_t sending_interval) {
    config::sending_interval = sending_interval;
    Serial.print(F("Setting Sending Interval to : "));
    Serial.print(config::sending_interval);
    Serial.println("s.");
    led_effects::showKITTWheel(color::green, 1);
  }

38
39
40
41
  void initialize(String &topic) {
    json_sensor_format = PSTR("{\"time\":\"%s\", \"co2\":%d, \"temp\":%.1f, \"rh\":%.1f}");
    publish_topic = topic;
#if defined(ESP8266)
42
    espClient.setInsecure(); // Sorry, we don't want to flash the sensors every 3 months.
43
44
45
#endif
    // mqttClient.setSocketTimeout(config::mqtt_timeout); //NOTE: somehow doesn't seem to have any effect on connect()
    mqttClient.setServer(config::mqtt_server, config::mqtt_port);
Eric Duminil's avatar
Eric Duminil committed
46

Eric Duminil's avatar
Eric Duminil committed
47
    sensor_commands::defineCallback("mqtt", setMQTTinterval, " 60 (Sets MQTT sending interval, in s)");
48
49
50
51
  }

  void publish(const String &timestamp, int16_t co2, float temperature, float humidity) {
    if (WiFi.status() == WL_CONNECTED && mqttClient.connected()) {
52
      led_effects::onBoardLEDOn();
Eric Duminil's avatar
Eric Duminil committed
53
      Serial.print(F("MQTT - Publishing message ... "));
54
55
56
57
58

      char payload[75]; // Should be enough for json...
      snprintf(payload, sizeof(payload), json_sensor_format, timestamp.c_str(), co2, temperature, humidity);
      // Topic is the same as clientID. e.g. 'CO2sensors/ESP3d03da'
      if (mqttClient.publish(publish_topic.c_str(), payload)) {
Eric Duminil's avatar
Eric Duminil committed
59
        Serial.println(F("OK"));
60
61
        last_successful_publish = ntp::getLocalTime();
      } else {
Eric Duminil's avatar
Eric Duminil committed
62
        Serial.println(F("Failed."));
63
      }
64
      led_effects::onBoardLEDOff();
65
66
67
68
    }
  }

  void sendInfoAboutLocalNetwork() {
69
    char info_topic[60]; // Should be enough for "CO2sensors/ESPd03cc5/info"
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
    snprintf(info_topic, sizeof(info_topic), "%s/info", publish_topic.c_str());

    char payload[75]; // Should be enough for info json...
    const char *json_info_format = PSTR("{\"local_ip\":\"%s\", \"ssid\":\"%s\"}");
    snprintf(payload, sizeof(payload), json_info_format, WiFi.localIP().toString().c_str(), WiFi.SSID().c_str());

    mqttClient.publish(info_topic, payload);
  }

  /**
   * 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;
    }
91
    led_effects::onBoardLEDOn();
92
93
94
95
96
97
98
99
100
    Serial.print(F("Message arrived on topic: "));
    Serial.print(sub_topic);
    Serial.print(F(". Message: '"));
    String messageString;
    for (unsigned int i = 0; i < length; i++) {
      Serial.print((char) message[i]);
      messageString += (char) message[i];
    }
    Serial.println("'.");
Eric Duminil's avatar
Eric Duminil committed
101
    sensor_commands::run(messageString.c_str());
Eric Duminil's avatar
Eric Duminil committed
102
103
    delay(50);
    led_effects::onBoardLEDOff();
Eric Duminil's avatar
Eric Duminil committed
104
    return;
105

Eric Duminil's avatar
TODOs    
Eric Duminil committed
106
107
    //TODO: Move this logic to a separate class, which could be used by Serial/MQTT/WebServer

Eric Duminil's avatar
Eric Duminil committed
108
    if (messageString == "publish") {
109
110
      Serial.println(F("Forcing MQTT publish now."));
      publish(sensor::timestamp, sensor::co2, sensor::temperature, sensor::humidity);
111
#ifdef AMPEL_CSV
112
113
    } else if (messageString == "format_filesystem") {
      FS_LIB.format();
114
      led_effects::showKITTWheel(color::blue, 2);
115
#endif
116
    } else if (messageString == "night_mode") {
117
      led_effects::toggleNightMode();
118
119
120
    } else if (messageString == "local_ip") {
      sendInfoAboutLocalNetwork();
    } else if (messageString == "reset") {
Eric Duminil's avatar
Eric Duminil committed
121
      ESP.restart(); // softer than ESP.reset()
122
123
124
125
126
    } else {
    }
  }

  void reconnect() {
Eric Duminil's avatar
Eric Duminil committed
127
    if (last_failed_at > 0 && (seconds() - last_failed_at < config::wait_after_fail)) {
128
129
130
131
132
133
134
      // 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;
    }
Eric Duminil's avatar
Eric Duminil committed
135
    Serial.print(F("MQTT - Attempting connection..."));
136

137
    led_effects::onBoardLEDOn();
138
139
    // Wait for connection, at most 15s (default)
    mqttClient.connect(publish_topic.c_str(), config::mqtt_user, config::mqtt_password);
140
    led_effects::onBoardLEDOff();
141

142
143
144
    connected = mqttClient.connected();

    if (connected) {
145
      if (config::allow_mqtt_commands) {
146
        char control_topic[60]; // Should be enough for "CO2sensors/ESPd03cc5/control"
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
        snprintf(control_topic, sizeof(control_topic), "%s/control", publish_topic.c_str());
        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.");
    }
  }

Eric Duminil's avatar
Eric Duminil committed
163
  void publishIfTimeHasCome(const String &timeStamp, const int16_t &co2, const float &temp, const float &hum) {
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
    // Send message via MQTT according to sending interval
    unsigned long now = seconds();
    if (now - last_sent_at > config::sending_interval) {
      last_sent_at = now;
      publish(timeStamp, co2, temp, hum);
    }
  }

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

}