diff --git a/.gitignore b/.gitignore index 8340f35..fe90ee2 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ .piolibdeps .clang_complete .gcc-flags.json +.pio diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 0000000..e80666b --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,7 @@ +{ + // See http://go.microsoft.com/fwlink/?LinkId=827846 + // for the documentation about the extensions.json format + "recommendations": [ + "platformio.platformio-ide" + ] +} diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..1507357 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,5 @@ +{ + "files.associations": { + "functional": "cpp" + } +} \ No newline at end of file diff --git a/data/index.html b/data/index.html index b8bfd23..b04f242 100644 --- a/data/index.html +++ b/data/index.html @@ -6,7 +6,6 @@ - BBQ Master @@ -48,23 +47,23 @@
@@ -327,7 +326,7 @@ // Hide the bar element if value is invalid document.getElementById('sensorBar' + i).style.display = "none"; } - $('#batvoltage').html("" + data.bat + "v "); + $('#batvoltage').html("" + data.bat + "% "); // TempValues.push(data.sensors[i].v); document.getElementById('sensorBar' + i).getElementsByClassName('label')[0].innerText = data.sensors[i].n; @@ -445,9 +444,6 @@ diff --git a/platformio.ini b/platformio.ini index ccb033d..5fc8e3a 100644 --- a/platformio.ini +++ b/platformio.ini @@ -16,16 +16,16 @@ framework = arduino lib_deps = OneWire DallasTemperature - Time + https://github.com/PaulStoffregen/Time PubSubClient - https://github.com/mcspr/NtpClient.git#platformio-manifest + https://github.com/mcspr/NtpClient.git https://github.com/adafruit/Adafruit_ADS1X15.git https://github.com/me-no-dev/ESPAsyncWebServer.git https://github.com/alanswx/ESPAsyncWiFiManager.git https://github.com/bblanchon/ArduinoJson.git https://github.com/Phillaf/Arduino-SimpleList.git -; upload_port = COM5 +; upload_port = COM6 ; upload_speed = 921600 upload_protocol = espota upload_port = bbq_master diff --git a/src/BBQMaster/BBQMaster.cpp b/src/BBQMaster/BBQMaster.cpp index 4942740..509ebaf 100644 --- a/src/BBQMaster/BBQMaster.cpp +++ b/src/BBQMaster/BBQMaster.cpp @@ -19,21 +19,6 @@ // #define DEBUG_TELNET // #define DEBUG_EXTRA_OUTPUT -#define I2C_SDA_PIN 23 -#define I2C_SCL_PIN 22 -#define BATTERY_V_PIN 35 - -#define BAT_RATIO 0.0017240449438202 -#define NTC_MAX_ADC 27550.00 -#define NTC_REF_RES 62000 -#define NTC_SMP_TMP 25.81 -#define NTC_SMP_RES 52250 -#define NTC_BCOEFFICIENT 4200 //3950 -#define HIST_SIZE 20 -#define HIST_INT 5000 -#define SENSOR_READ_INT 1500 -#define MQTT_PUBLISH_PERIOD 10000 - // Macros for debugging #ifdef DEBUG_TELNET #define DEBUG_TELNET_PORT 23 @@ -55,42 +40,61 @@ #define DEBUG_PRINTLN_WITH_FMT(x, fmt) #endif +#define I2C_SDA_PIN 23 +#define I2C_SCL_PIN 22 +#define BATTERY_V_PIN 35 + +#define BAT_RATIO 0.0017240449438202 +#define NTC_MAX_ADC 27550.00 +#define NTC_REF_RES 62000 +#define NTC_SMP_TMP 25.81 +#define NTC_SMP_RES 52250 +#define NTC_BCOEFFICIENT 4200 //3950 +#define HIST_SIZE 20 +#define HIST_INT 5000 +#define SENSOR_READ_INT 1500 +#define MQTT_PUBLISH_PERIOD 10000 + Adafruit_ADS1115 g_ads (0x49); /* Use this for the 16-bit version */ AsyncWebServer g_server (80); OneWire g_oneWireTemp (17); DallasTemperature g_thermoCouples (&g_oneWireTemp); DNSServer dns; -// MAX31850KATB+-ND +// MAX31850KATB+-ND sensors DeviceAddress g_sensor1 = {0x3B, 0x45, 0x21, 0x18, 0x00, 0x00, 0x00, 0x2D}; DeviceAddress g_sensor2 = {0x3B, 0xF1, 0x22, 0x18, 0x00, 0x00, 0x00, 0xB8}; DeviceAddress g_sensor3 = {0x3B, 0xF3, 0x22, 0x18, 0x00, 0x00, 0x00, 0xD6}; DeviceAddress g_sensor4 = {0x3B, 0x43, 0x21, 0x18, 0x00, 0x00, 0x00, 0x9F}; double g_batteryVoltage = 0; -bool g_ntpError = false; +double g_batteryLevel = 0; short g_maxWorkingSensors = 0; +bool firmwareUpdating = false; +bool g_shouldSaveConfig = false; // Host name of the device. const char* g_hostName= "BBQ_Master"; // MQTT stuff -WiFiClient espClient; -PubSubClient g_mqttClient(espClient); +WiFiClient g_espClient; +PubSubClient g_mqttClient(g_espClient); // MQTT configs +#define MQTT_HOME_ASSISTANT_DISCOVERY_PREFIX "homeassistant" char g_mqtt_server[40] = "example.com"; char g_mqtt_port[6] = "1883"; char g_topicMQTTHeader[22 + 11]; -char g_topicAvailability[22 + 11 + 10]; -char g_topicState[22 + 11 + 10]; -char g_topicMQTTDiscover[22 + 11 + 10]; +char g_uniqueId[5]; // Representation of one temperature probe struct Sensor { + // Availability flag bool m_ind; + // Temperature double m_tempF; + // Name of the sensor String m_name; public: @@ -111,9 +115,6 @@ DataPoint g_lastSenUpdate; // Saving the history for the histogram SimpleList g_tempHist; -// Flag for saving data from wifi portal -bool g_shouldSaveConfig = false; - // Handle telnet debuging #if defined(DEBUG_TELNET) void handleTelnet(void) { @@ -134,8 +135,8 @@ void handleTelnet(void) { void setupOTA(const char *hostname) { // Config OTA updates - ArduinoOTA.onStart([]() { DEBUG_PRINTLN("Start"); }); - ArduinoOTA.onEnd([]() { DEBUG_PRINTLN("\nEnd"); }); + ArduinoOTA.onStart([]() { DEBUG_PRINTLN("Start. Disbling regular work!"); firmwareUpdating=true;}); + ArduinoOTA.onEnd([]() { DEBUG_PRINTLN("\nEnd"); firmwareUpdating = false;}); ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { DEBUG_PRINT_WITH_FMT("Progress: %u%%\r", (progress / (total / 100))); }); ArduinoOTA.onError([](ota_error_t error) { DEBUG_PRINT_WITH_FMT("Error[%u]: ", error); @@ -144,13 +145,14 @@ void setupOTA(const char *hostname) else if (error == OTA_CONNECT_ERROR) DEBUG_PRINTLN("Connect Failed"); else if (error == OTA_RECEIVE_ERROR) DEBUG_PRINTLN("Receive Failed"); else if (error == OTA_END_ERROR) DEBUG_PRINTLN("End Failed"); + firmwareUpdating = false; }); ArduinoOTA.setHostname(hostname); ArduinoOTA.begin(); } // Saving the config to SPIFF -void SaveConfig () { +void saveConfig () { DynamicJsonDocument json (256); json["mqtt_server"] = g_mqtt_server; json["mqtt_port"] = g_mqtt_port; @@ -164,7 +166,7 @@ void SaveConfig () { } // Reading the config from SPIFF -void ReadConfig () +void readConfig () { if (SPIFFS.begin()) { DEBUG_PRINTLN("SPIFFS started"); @@ -190,14 +192,12 @@ void ReadConfig () } else { DEBUG_PRINTLN("failed to load json config"); - SaveConfig (); + saveConfig (); } } } else - { - SaveConfig (); - } + saveConfig (); } else { DEBUG_PRINTLN("Formatting the flash..."); SPIFFS.format(); @@ -205,14 +205,8 @@ void ReadConfig () } } -// Call back for saving the config. -void SaveConfigCallback () { - DEBUG_PRINTLN("Should save config"); - g_shouldSaveConfig = true; -} - // Manages wifi portal -void ManageWifi (bool reset_config = false) +void manageWifi (bool reset_config = false) { // The extra parameters to be configured (can be either global or just in the setup) AsyncWiFiManagerParameter custom_mqtt_server("server", "MQTT server", g_mqtt_server, 39); @@ -224,7 +218,9 @@ void ManageWifi (bool reset_config = false) wifiManager.setMinimumSignalQuality(10); wifiManager.addParameter(&custom_mqtt_server); wifiManager.addParameter(&custom_mqtt_port); - wifiManager.setSaveConfigCallback(&SaveConfigCallback); + wifiManager.setSaveConfigCallback([](){ + g_shouldSaveConfig = true; + }); if (reset_config) wifiManager.startConfigPortal(g_hostName); @@ -235,13 +231,13 @@ void ManageWifi (bool reset_config = false) { strncpy(g_mqtt_server, custom_mqtt_server.getValue(), 39); strncpy(g_mqtt_port, custom_mqtt_port.getValue(), 5); - SaveConfig (); + saveConfig (); g_shouldSaveConfig = false; } } // Calculate NTC temp using steinhart equation -float NTCTemp (int16_t adcValue) +float calculateNTCTemp (int16_t adcValue) { if (adcValue < NTC_MAX_ADC) { @@ -264,7 +260,7 @@ float NTCTemp (int16_t adcValue) } // Check whether temperature is valid. -bool IsValidTemp (float temp) +bool isValidTemp (float temp) { if (temp <= 32.0 || temp > 1000.00) return false; @@ -272,10 +268,26 @@ bool IsValidTemp (float temp) return true; } -// Read all the sensors -void ReadSensors () +// Battery precentage calculator +float batteryLevel() { + g_batteryVoltage = analogRead (BATTERY_V_PIN) * BAT_RATIO; + float output = 0.0; //output value + const float battery_max = 4.20; //maximum voltage of battery + const float battery_min = 3.5; //minimum voltage of battery before shutdown + + output = ((g_batteryVoltage - battery_min) / (battery_max - battery_min)) * 100; + if (output < 100) + return output; + else + return 100.0f; +} + + +// Read all the sensors +void readSensors () +{ int16_t adc0, adc1, adc2, adc3; float ntc0, ntc1, ntc2, ntc3; // NTC readings @@ -284,10 +296,10 @@ void ReadSensors () adc2 = g_ads.readADC_SingleEnded (2); adc3 = g_ads.readADC_SingleEnded (3); - ntc0 = NTCTemp (adc0); - ntc1 = NTCTemp (adc1); - ntc2 = NTCTemp (adc2); - ntc3 = NTCTemp (adc3); + ntc0 = calculateNTCTemp (adc0); + ntc1 = calculateNTCTemp (adc1); + ntc2 = calculateNTCTemp (adc2); + ntc3 = calculateNTCTemp (adc3); float tcp0, tcp1, tcp2, tcp3; tcp0 = g_thermoCouples.getTempF (g_sensor1); @@ -299,19 +311,19 @@ void ReadSensors () if (tps > 0) { g_lastSenUpdate.m_time = tps; - g_lastSenUpdate.m_sensors[0] = Sensor (IsValidTemp (ntc0), ntc0, "NTC1"); - g_lastSenUpdate.m_sensors[1] = Sensor (IsValidTemp (ntc1), ntc1, "NTC2"); - g_lastSenUpdate.m_sensors[2] = Sensor (IsValidTemp (ntc2), ntc2, "NTC3"); - g_lastSenUpdate.m_sensors[3] = Sensor (IsValidTemp (ntc3), ntc3, "NTC4"); + g_lastSenUpdate.m_sensors[0] = Sensor (isValidTemp (ntc0), ntc0, "NTC1"); + g_lastSenUpdate.m_sensors[1] = Sensor (isValidTemp (ntc1), ntc1, "NTC2"); + g_lastSenUpdate.m_sensors[2] = Sensor (isValidTemp (ntc2), ntc2, "NTC3"); + g_lastSenUpdate.m_sensors[3] = Sensor (isValidTemp (ntc3), ntc3, "NTC4"); // Thermocouple readings - g_lastSenUpdate.m_sensors[4] = Sensor (IsValidTemp (tcp0), tcp0, "TC1"); - g_lastSenUpdate.m_sensors[5] = Sensor (IsValidTemp (tcp1), tcp1, "TC2"); - g_lastSenUpdate.m_sensors[6] = Sensor (IsValidTemp (tcp2), tcp2, "TC3"); - g_lastSenUpdate.m_sensors[7] = Sensor (IsValidTemp (tcp3), tcp3, "TC4"); + g_lastSenUpdate.m_sensors[4] = Sensor (isValidTemp (tcp0), tcp0, "TC1"); + g_lastSenUpdate.m_sensors[5] = Sensor (isValidTemp (tcp1), tcp1, "TC2"); + g_lastSenUpdate.m_sensors[6] = Sensor (isValidTemp (tcp2), tcp2, "TC3"); + g_lastSenUpdate.m_sensors[7] = Sensor (isValidTemp (tcp3), tcp3, "TC4"); } - g_batteryVoltage = analogRead (BATTERY_V_PIN) * BAT_RATIO; + g_batteryLevel = batteryLevel (); // Request thermo couple data g_thermoCouples.setWaitForConversion(false); // makes it async @@ -347,7 +359,7 @@ void ReadSensors () DynamicJsonDocument jsonSensorData () { DynamicJsonDocument json(1024); // Current JSON static buffer - json["bat"] = g_batteryVoltage; + json["bat"] = g_batteryLevel; json["t"] = g_lastSenUpdate.m_time; JsonArray sensors = json.createNestedArray ("sensors"); @@ -362,18 +374,16 @@ DynamicJsonDocument jsonSensorData () return json; } - // Send the last sensor data reading in json format. -void SendMeasures (AsyncWebServerRequest *request) +void sendMeasures (AsyncWebServerRequest *request) { char tempJson[1024]; serializeJson(jsonSensorData (), tempJson); request->send (200, "application/json", tempJson); // Send history data to the web client } - // Send the history in JSON format. -void SendHistory (AsyncWebServerRequest *request) +void sendHistory (AsyncWebServerRequest *request) { DEBUG_PRINTLN("Sending History"); DynamicJsonDocument json(5560 + 100); // Current JSON static buffer @@ -401,7 +411,7 @@ void SendHistory (AsyncWebServerRequest *request) } // Add a data point to the history -void AddDataPointToHistory () +void addDataPointToHistory () { short validSensors = 0; bool validData = false; @@ -435,6 +445,7 @@ void AddDataPointToHistory () #endif } +// Publish the MQTT payload. void publishToMQTT(const char* p_topic,const char* p_payload) { if (g_mqttClient.publish(p_topic, p_payload, true)) { DEBUG_PRINT(F("INFO: MQTT message published successfully, topic: ")); @@ -452,7 +463,9 @@ void publishToMQTT(const char* p_topic,const char* p_payload) { // Function that publishes birthMessage void publishAvailability() { - g_mqttClient.publish(g_topicAvailability, "online", true); + char topicAvailability[22 + 11 + 10]; + snprintf(topicAvailability, 22 + 11 + 10, "%s/avail",g_topicMQTTHeader); + g_mqttClient.publish(topicAvailability, "online", true); } // Function that publishes availability of each sensor @@ -469,77 +482,103 @@ void publishSensorAvailability() } } -// publish MQTT discovery config to let hassio auto discover the sensors. +// Publish MQTT discovery config to let hassio auto discover the sensors. void publishDiscovery(void) { // Create json config for battery level. - StaticJsonDocument<220> root; + char uniqueId[15]; + snprintf(uniqueId, 15, "%sbat", g_uniqueId); + char batDiscoverTopic[22 + 11 + 10]; + snprintf(batDiscoverTopic, 22 + 11 + 10, "%s/bat/config", g_topicMQTTHeader); + + StaticJsonDocument<500> root; + root["~"] = g_topicMQTTHeader; root["dev_cla"] = "battery"; - char batName[30]; - snprintf(batName, 30, "%s Battery.", g_hostName); - root["name"] = batName; - root["avty_t"] = g_topicAvailability; - root["stat_t"] = g_topicState; - root["unit_of_meas"] = "V"; + root["uniq_id"] = uniqueId; + root["name"] = "Battery"; + root["avty_t"] = "~/avail"; + root["stat_t"] = "~/state"; + root["unit_of_meas"] = "%"; root["val_tpl"] = "{{value_json.bat}}"; - char outgoingJsonBuffer[220]; + root["device"]["ids"] = g_uniqueId; + root["device"]["name"] = g_hostName; + root["device"]["mf"] = "DIY"; + root["device"]["mdl"] = "DIY"; + root["device"]["sw"] = "1.1"; + char outgoingJsonBuffer[500]; serializeJson(root, outgoingJsonBuffer); - publishToMQTT(g_topicMQTTDiscover, outgoingJsonBuffer); + publishToMQTT(batDiscoverTopic, outgoingJsonBuffer); // Create json config for each sensor. for (int i = 0; i < 8; i++) { - char sensorTopicHeader[22 + 11 + 20]; - snprintf(sensorTopicHeader, 22 + 11 + 20, "%s/%s/config", g_topicMQTTHeader, g_lastSenUpdate.m_sensors[i].m_name.c_str()); + char sensorConfigTopic[22 + 11 + 20]; + snprintf(sensorConfigTopic, 22 + 11 + 20, "%s/%s/config", g_topicMQTTHeader, g_lastSenUpdate.m_sensors[i].m_name.c_str()); + char availabilitySensorTopic[15]; + snprintf(availabilitySensorTopic, 15, "~/%s/avail", g_lastSenUpdate.m_sensors[i].m_name.c_str()); - StaticJsonDocument<250> sensorRoot; - sensorRoot["dev_cla"] = "temperature"; + char sensorId[15]; + snprintf(sensorId, 15, "%s%s", g_uniqueId, g_lastSenUpdate.m_sensors[i].m_name.c_str()); char sensorName[30]; - snprintf(sensorName, 30, "%s %s Temperature.", g_hostName, g_lastSenUpdate.m_sensors[i].m_name.c_str()); - sensorRoot["name"] = sensorName; - char availabilitySensorTopic[50]; - snprintf(availabilitySensorTopic, 22 + 11 + 20, "%s/%s/avail", g_topicMQTTHeader, g_lastSenUpdate.m_sensors[i].m_name.c_str()); - sensorRoot["avty_t"] = availabilitySensorTopic; - sensorRoot["stat_t"] = g_topicState; - sensorRoot["unit_of_meas"] = "°F"; + snprintf(sensorName, 30, "%s Temperature.", g_lastSenUpdate.m_sensors[i].m_name.c_str()); String jsonTemplate = "{{value_json.sensors[" + String(i) + "].v}}"; - sensorRoot["val_tpl"] = jsonTemplate; - sensorRoot["exp_aft"] = MQTT_PUBLISH_PERIOD/1000 + 5; - char sensorDisBuffer[250]; + StaticJsonDocument<500> sensorRoot; + sensorRoot["~"] = g_topicMQTTHeader; + sensorRoot["dev_cla"] = "temperature"; + sensorRoot["uniq_id"] = sensorId; + sensorRoot["name"] = sensorName; + sensorRoot["avty_t"] = availabilitySensorTopic; + sensorRoot["stat_t"] = "~/state"; + sensorRoot["unit_of_meas"] = "°F"; + sensorRoot["val_tpl"] = jsonTemplate; + sensorRoot["exp_aft"] = MQTT_PUBLISH_PERIOD/1000 + 5; // Invalidate the data if there is no data for 15seconds. + sensorRoot["device"]["ids"] = g_uniqueId; + sensorRoot["device"]["name"] = g_hostName; + sensorRoot["device"]["mf"] = "DIY"; + sensorRoot["device"]["mdl"] = "DIY"; + sensorRoot["device"]["sw"] = "1.1"; + + char sensorDisBuffer[500]; serializeJson(sensorRoot, sensorDisBuffer); - publishToMQTT(sensorTopicHeader, sensorDisBuffer); + publishToMQTT(sensorConfigTopic, sensorDisBuffer); } } // MQTT Connect. void connectToMqtt() { - DEBUG_PRINT("Connecting to MQTT with client id "); - String clientId = "BBQMaster_"; - clientId += String(random(0xffff), HEX); - DEBUG_PRINT(clientId); - DEBUG_PRINTLN("..."); - // Attempt to connect - if (g_mqttClient.connect(clientId.c_str(), "", "", g_topicAvailability, 0, true, "offline")) - { + DEBUG_PRINT("Connecting to MQTT with client id "); + String clientId = "BBQMaster_"; + clientId += String(random(0xffff), HEX); + DEBUG_PRINT(clientId); + DEBUG_PRINTLN("..."); + char topicAvailability[22 + 11 + 10]; + snprintf(topicAvailability, 22 + 11 + 10, "%s/avail",g_topicMQTTHeader); + + // Attempt to connect + if (g_mqttClient.connect(clientId.c_str(), "", "", topicAvailability, 0, true, "offline")) + { publishAvailability(); publishDiscovery(); - } - else - { + } + else + { DEBUG_PRINT("Failed to connect to MQTT! "); DEBUG_PRINT(g_mqttClient.state()); - DEBUG_PRINTLN(" Trying again in 5 seconds"); - } + DEBUG_PRINTLN(" Trying again in 60 seconds"); + } } // Publish MQTT states -void publishMqtt() +void publishDataToMqtt() { + char topicState[22 + 11 + 10]; + snprintf(topicState, 22 + 11 + 10, "%s/state", g_topicMQTTHeader); + char tempJson[1024]; serializeJson(jsonSensorData (), tempJson); - publishToMQTT (g_topicState, tempJson); + publishToMQTT (topicState, tempJson); publishSensorAvailability(); } @@ -559,14 +598,15 @@ void setup (void) g_thermoCouples.setResolution (12); // Read mqtt config from SPIFF - ReadConfig (); + readConfig (); // WIFI connect WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE); WiFi.setHostname(g_hostName); WiFi.mode(WIFI_STA); - ManageWifi (); + manageWifi (); + // Start the telnet server #if defined(DEBUG_TELNET) telnetServer.begin(); telnetServer.setNoDelay(true); @@ -577,11 +617,17 @@ void setup (void) // OTA stuff setupOTA (g_hostName); + // Get a unique ID using the mac address + byte mac[7]; + WiFi.macAddress(mac); + mac[6] = '\0'; + snprintf(g_uniqueId, 20, "%02X%02X", mac[4], mac[5]); + // Web server stuff if (!SPIFFS.begin ()) DEBUG_PRINTLN("SPIFFS Mount failed"); // Problème avec le stockage SPIFFS - Serious problem with SPIFFS - g_server.on ("/measures.json", SendMeasures); - g_server.on ("/history.json", SendHistory); + g_server.on ("/measures.json", sendMeasures); + g_server.on ("/history.json", sendHistory); g_server.serveStatic ("/js/bootstrap.min.js", SPIFFS, "/js/bootstrap.min.js", "max-age=86400"); g_server.serveStatic ("/js/jquery.min.js", SPIFFS, "/js/jquery-3.3.1.min.js", "max-age=86400"); @@ -606,7 +652,6 @@ void setup (void) DEBUG_PRINTLN("NTP server not reachable"); else if (error == invalidAddress) DEBUG_PRINTLN("Invalid NTP server address"); - g_ntpError = true; } else { @@ -619,60 +664,62 @@ void setup (void) NTP.setInterval (240); // MQTT Config - snprintf(g_topicMQTTHeader, 22 + 11, "homeassistant/sensor/%s", g_hostName); - snprintf(g_topicAvailability, 22 + 11 + 10, "%s/avail",g_topicMQTTHeader); - snprintf(g_topicState, 22 + 11 + 10, "%s/state", g_topicMQTTHeader); - snprintf(g_topicMQTTDiscover, 22 + 11 + 10, "%s/config", g_topicMQTTHeader); + snprintf(g_topicMQTTHeader, 22 + 11, "%s/sensor/%s", MQTT_HOME_ASSISTANT_DISCOVERY_PREFIX, g_hostName); g_mqttClient.setServer(g_mqtt_server, atoi(g_mqtt_port)); g_mqttClient.setBufferSize(512); + // connectToMqtt (); + randomSeed(micros()); } void loop (void) { -// handle the Telnet connection + // handle the Telnet connection #if defined(DEBUG_TELNET) - handleTelnet(); + handleTelnet(); #endif - unsigned long currentMillis = millis (); // Time now // Handle server requests ArduinoOTA.handle (); - // Connect to MQTT server - if (!g_mqttClient.connected()) + if (!firmwareUpdating) { - static unsigned long mqttConnectWaitPeriod; - if (currentMillis - mqttConnectWaitPeriod >= 5000) + // Connect to MQTT server + if (!g_mqttClient.connected()) { - mqttConnectWaitPeriod = currentMillis; - connectToMqtt (); + static unsigned long mqttConnectWaitPeriod; + if (currentMillis - mqttConnectWaitPeriod >= 30000) + { + mqttConnectWaitPeriod = currentMillis; + connectToMqtt (); + } + } + g_mqttClient.loop(); + + // Add a point to the history over time. + static unsigned long histPreviousMillis; + if (currentMillis - histPreviousMillis > HIST_INT) + { + histPreviousMillis = currentMillis; + addDataPointToHistory (); } - } - g_mqttClient.loop(); - // Add a point to the history over time. - static unsigned long histPreviousMillis; - if (currentMillis - histPreviousMillis > HIST_INT) - { - histPreviousMillis = currentMillis; - AddDataPointToHistory (); - } + // Read the sensor data. + static unsigned long prevMilForInputRead; + if (currentMillis - prevMilForInputRead >= SENSOR_READ_INT) + { + prevMilForInputRead = currentMillis; + readSensors (); + } - // Read the sensor data. - static unsigned long prevMilForInputRead; - if (currentMillis - prevMilForInputRead >= SENSOR_READ_INT) - { - prevMilForInputRead = currentMillis; - ReadSensors (); - } - - // Send MQTT state. - static unsigned long prevMilForMqttPublish; - if (currentMillis - prevMilForMqttPublish >= MQTT_PUBLISH_PERIOD) - { - prevMilForMqttPublish = currentMillis; - publishMqtt (); + // Send MQTT state. + static unsigned long prevMilForMqttPublish; + if (currentMillis - prevMilForMqttPublish >= MQTT_PUBLISH_PERIOD) + { + prevMilForMqttPublish = currentMillis; + if (g_mqttClient.connected()) + publishDataToMqtt (); + } } }