добавлено сохранение, упрощен код, вырезано лишнее
parent
408896e92a
commit
e1d77bb3b2
361
M5Atom_airqa.ino
361
M5Atom_airqa.ino
|
@ -15,7 +15,6 @@
|
|||
#include <ESP32httpUpdate.h> //Библиотека ОТА обновлений
|
||||
#include "M5Atom.h" //Библиотека атома для функции Led и Кнопки, можно упразднить и убрать
|
||||
|
||||
#include <Ticker.h> //Библиотека таймера для Led
|
||||
#include <WiFiUdp.h> //Udp клиент
|
||||
#include <NTPClient.h> //NTP запрос времени
|
||||
#include <TimeLib.h> //Внутреннее время
|
||||
|
@ -41,26 +40,27 @@ WiFiManager wm; // обьект менеджера
|
|||
WiFiManagerParameter custom_field;
|
||||
Preferences OTApreferences; //Обьект хранения настроек хеша прошивки
|
||||
|
||||
Ticker RGBWTicker;
|
||||
Adafruit_CCS811 ccs;
|
||||
ClosedCube_HDC1080 hdc1080;
|
||||
String JsonData;
|
||||
StaticJsonDocument<200> doc, other;
|
||||
|
||||
WiFiClient espClient;
|
||||
PubSubClient MqttClient(espClient);
|
||||
|
||||
IPAddress IpMqtt;
|
||||
|
||||
WiFiUDP ntpUDP;
|
||||
NTPClient timeClient(ntpUDP, "0.ua.pool.ntp.org", 7200, 60000); //Собственно сервер времени смещение и частоат запроса, но он вручную
|
||||
|
||||
const PROGMEM char *mqttHostName = "cctv.automation.art"; //Хостнейм брокера metrics.local cctv.automation.art //192.168.89.210
|
||||
unsigned int mqttPort = 8889; //Порт брокера 1883 8889
|
||||
const char *mqttHostName = "cctv.automation.art"; //Хостнейм брокера metrics.local cctv.automation.art //192.168.89.210
|
||||
unsigned int mqttPort = 8889; //Порт брокера 1883 8889
|
||||
|
||||
String getMacAddress();
|
||||
String macc = getMacAddress();
|
||||
|
||||
char *topicName, *willTopicName;
|
||||
char bufTopic[140];
|
||||
char bufWillTopic[150];
|
||||
|
||||
// +mac адресс девайса Префикс топика
|
||||
const PROGMEM char *mqttLogin = "login", //Логин пароль - необходимо сменить код при connect()
|
||||
*mqttPass = "password";
|
||||
|
@ -87,26 +87,11 @@ long rssi = 0;
|
|||
|
||||
//Кусок кода поправить - так делать нельзя
|
||||
#define NUM_AVER 5
|
||||
float averageT; // перем. среднего
|
||||
float valArrayT[NUM_AVER]; // массив
|
||||
byte idxT = 0;
|
||||
|
||||
float averageH; // перем. среднего
|
||||
float valArrayH[NUM_AVER]; // массив
|
||||
byte idxH = 0;
|
||||
|
||||
float averageECO; // перем. среднего
|
||||
float valArrayECO[NUM_AVER]; // массив
|
||||
byte idxECO = 0;
|
||||
|
||||
float averageTVOC; // перем. среднего
|
||||
float valArrayTVOC[NUM_AVER]; // массив
|
||||
byte idxTVOC = 0;
|
||||
float averageT, averageH, averageECO, averageTVOC; // перем. среднего
|
||||
float valArrayT[NUM_AVER], valArrayH[NUM_AVER], valArrayECO[NUM_AVER], valArrayTVOC[NUM_AVER]; // массив
|
||||
byte idxT = 0, idxH = 0, idxECO = 0, idxTVOC = 0;
|
||||
|
||||
bool mqttSendFlag = false;
|
||||
|
||||
// float arrT[5] = {0}, arrH[5] = {0};
|
||||
// int arrECO[5] = {0}, tvoc[5] = {0};
|
||||
int reqCounter = 0;
|
||||
bool flagblink = true;
|
||||
|
||||
|
@ -114,37 +99,26 @@ bool flagblink = true;
|
|||
void setup()
|
||||
{
|
||||
M5.begin(true, false, true);
|
||||
delay(50);
|
||||
Wire.begin(25, 21); //Пины для I2c на ATOM
|
||||
|
||||
pinMode(23, OUTPUT); //Пин датчика для работы
|
||||
digitalWrite(23, LOW);
|
||||
|
||||
WiFi.mode(WIFI_STA);
|
||||
//////Serial.begin(115200);
|
||||
//////Serial.setDebugOutput(true);
|
||||
delay(1000);
|
||||
//Serial.begin(115200);
|
||||
////////////Serial.setDebugOutput(true);
|
||||
|
||||
String topicTemp = "/aastudio/" + macc;
|
||||
String willTopicTemp = topicTemp + "/status";
|
||||
|
||||
char prefix[] = "/aastudio/";
|
||||
char statusPrefix[] = "/status";
|
||||
char bufprefix[200];
|
||||
topicTemp.toCharArray(bufTopic, topicTemp.length() + 1);
|
||||
willTopicTemp.toCharArray(bufWillTopic, willTopicTemp.length() + 1);
|
||||
|
||||
char maccbuff[15];
|
||||
macc.toCharArray(maccbuff, 15);
|
||||
|
||||
strcpy(prefix, bufprefix);
|
||||
strcpy(maccbuff, bufprefix);
|
||||
topicName = bufprefix;
|
||||
|
||||
strcpy(statusPrefix, bufprefix);
|
||||
|
||||
willTopicName = bufprefix;
|
||||
|
||||
//////Serial.println("\n Starting station");
|
||||
////////////Serial.println("\n Starting station");
|
||||
pinMode(TRIGGER_PIN, INPUT);
|
||||
// wm.resetSettings(); // wipe settings
|
||||
// add a custom input field
|
||||
// int customFieldLength = 40;
|
||||
// int customFieldLength = 40;
|
||||
// new (&custom_field) WiFiManagerParameter("customfieldid", "Custom Field Label", "Custom Field Value", customFieldLength,"placeholder=\"Custom Field Placeholder\"");
|
||||
// test custom html input type(checkbox)
|
||||
// new (&custom_field) WiFiManagerParameter("customfieldid", "Custom Field Label", "Custom Field Value", customFieldLength,"placeholder=\"Custom Field Placeholder\" type=\"checkbox\""); // custom html type
|
||||
|
@ -166,7 +140,7 @@ void setup()
|
|||
// wm.setShowStaticFields(true); // force show static ip fields
|
||||
// wm.setShowDnsFields(true); // force show dns field always
|
||||
// wm.setConnectTimeout(20); // how long to try to connect for before continuing
|
||||
wm.setConfigPortalTimeout(30); // auto close configportal after n seconds
|
||||
wm.setConfigPortalTimeout(60); // auto close configportal after n seconds
|
||||
// wm.setCaptivePortalEnable(false); // disable captive portal redirection
|
||||
// wm.setAPClientCheck(true); // avoid timeout if client connected to softap
|
||||
// wifi scan settings
|
||||
|
@ -181,17 +155,17 @@ void setup()
|
|||
res = wm.autoConnect("AirQaPortal", "12345678"); // Подключение к анонимной точке доступа
|
||||
if (!res)
|
||||
{
|
||||
//////Serial.println("Failed to connect or hit timeout");
|
||||
////////////Serial.println("Failed to connect or hit timeout");
|
||||
// ESP.restart();
|
||||
}
|
||||
else
|
||||
{
|
||||
//////Serial.println("Server AirQaPortal start");
|
||||
////////////Serial.println("Server AirQaPortal start");
|
||||
}
|
||||
|
||||
if (!ccs.begin()) //The device's I2C address is 0x5A
|
||||
{
|
||||
//////Serial.println("Failed to start sensor CCS811! ");
|
||||
////////////Serial.println("Failed to start sensor CCS811! ");
|
||||
}
|
||||
|
||||
ccs.setTempOffset(8.6);
|
||||
|
@ -214,51 +188,54 @@ void setMqttServer()
|
|||
IPAddress IpMqtt, ipaddr;
|
||||
|
||||
ipaddr = MDNS.queryHost(mqttHostName); // .local omitted
|
||||
// //////Serial.println(ipaddr.toString());
|
||||
// ////////////Serial.println(ipaddr.toString());
|
||||
if (ipaddr.toString() == "0.0.0.0")
|
||||
{
|
||||
Serial.println("MDNS.queryHost==0.0.0.0");
|
||||
//////Serial.println("MDNS.queryHost==0.0.0.0");
|
||||
|
||||
int err = WiFi.hostByName(mqttHostName, IpMqtt);
|
||||
if (err == 1)
|
||||
{
|
||||
delay(50);
|
||||
setServCall(IpMqtt);
|
||||
// MqttClient.setServer(IpMqtt, mqttPort);
|
||||
}
|
||||
else
|
||||
{
|
||||
Serial.print("Error code hostByName(): ");
|
||||
Serial.println(err);
|
||||
//////Serial.print("Error code hostByName(): ");
|
||||
//////Serial.println(err);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
setServCall(ipaddr);
|
||||
// MqttClient.setServer(ipaddr, mqttPort);
|
||||
}
|
||||
|
||||
Serial.printf("HTTP_UPDATE_FAILD Error (%d): %s", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str());
|
||||
Serial.println(ESPhttpUpdate.getLastError());
|
||||
Serial.println(ESPhttpUpdate.getLastErrorString().c_str());
|
||||
//////Serial.printf("Last Error UPDATE (%d): %s", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str());
|
||||
//////Serial.println(ESPhttpUpdate.getLastError());
|
||||
//////Serial.println(ESPhttpUpdate.getLastErrorString().c_str());
|
||||
}
|
||||
|
||||
void setServCall(IPAddress SetIpaddr)
|
||||
{
|
||||
//////Serial.println("setServCall");
|
||||
//////Serial.println(SetIpaddr);
|
||||
MqttClient.setServer(SetIpaddr, mqttPort);
|
||||
MqttClient.setCallback(callback);
|
||||
//////Serial.println("Set MQTT Server - OK");
|
||||
////////Serial.println("Set MQTT Server - OK");
|
||||
}
|
||||
|
||||
//Функция получения данных из MQTT если мы подпишемся на топики
|
||||
void callback(char *topic, byte *payload, unsigned int length)
|
||||
{
|
||||
//////Serial.print("Message arrived [");
|
||||
//////Serial.print(topic);
|
||||
////Serial.print("] ");
|
||||
////////////Serial.print("Message arrived [");
|
||||
////////////Serial.print(topic);
|
||||
//////////Serial.print("] ");
|
||||
for (int i = 0; i < length; i++)
|
||||
{
|
||||
////Serial.print((char)payload[i]);
|
||||
//////////Serial.print((char)payload[i]);
|
||||
}
|
||||
////Serial.println();
|
||||
//////////Serial.println();
|
||||
}
|
||||
|
||||
//Запрос времени NTP и установка локлаьного времени
|
||||
|
@ -267,9 +244,9 @@ void reqNtpTime()
|
|||
timeClient.update();
|
||||
uint32_t timeEpoch = timeClient.getEpochTime();
|
||||
setTime(timeEpoch);
|
||||
////Serial.print(timeEpoch);
|
||||
////Serial.print(" <=ntp== ==device=> ");
|
||||
////Serial.println(now());
|
||||
//////////Serial.print(timeEpoch);
|
||||
//////////Serial.print(" <=ntp== ==device=> ");
|
||||
//////////Serial.println(now());
|
||||
if (timeEpoch < 100000)
|
||||
{
|
||||
errorID = 1;
|
||||
|
@ -279,50 +256,48 @@ void reqNtpTime()
|
|||
//Нажатие кнопки для сброса
|
||||
void checkButton()
|
||||
{
|
||||
////Serial.println("Button Pressed to RESET");
|
||||
|
||||
wm.resetSettings();
|
||||
|
||||
//////Serial.println("Button Pressed to RESET");
|
||||
disconnectMQTT();
|
||||
wm.resetSettings();
|
||||
ESP.restart();
|
||||
|
||||
ESP.restart();
|
||||
//////////Serial.println("Starting config portal");
|
||||
//wm.setConfigPortalTimeout(120);
|
||||
|
||||
////Serial.println("Starting config portal");
|
||||
wm.setConfigPortalTimeout(120);
|
||||
// if (!wm.startConfigPortal("AirQaPortal", "12345678")) //Логин и пароль точки доступа
|
||||
// {
|
||||
// //////////Serial.println("failed to connect or hit timeout");
|
||||
|
||||
if (!wm.startConfigPortal("AirQaPortal", "12345678")) //Логин и пароль точки доступа
|
||||
{
|
||||
////Serial.println("failed to connect or hit timeout");
|
||||
delay(1000);
|
||||
// ESP.restart();
|
||||
}
|
||||
else
|
||||
{
|
||||
////Serial.println("Clien connected to AP");
|
||||
}
|
||||
}
|
||||
|
||||
String getParam(String name)
|
||||
{
|
||||
String value;
|
||||
if (wm.server->hasArg(name))
|
||||
{
|
||||
value = wm.server->arg(name);
|
||||
}
|
||||
return value;
|
||||
// // ESP.restart();
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// //////////Serial.println("Clien connected to AP");
|
||||
// }
|
||||
}
|
||||
|
||||
void saveParamCallback()
|
||||
{
|
||||
////Serial.println("[CALLBACK] saveParamCallback fired");
|
||||
////Serial.println("PARAM customfieldid = " + getParam("customfieldid"));
|
||||
//////Serial.println("[CALLBACK] saveParamCallback fired");
|
||||
//////Serial.println("PARAM customfieldid = " + getParam("customfieldid"));
|
||||
}
|
||||
|
||||
|
||||
// String getParam(String name)
|
||||
// {
|
||||
// String value;
|
||||
// if (wm.server->hasArg(name))
|
||||
// {
|
||||
// value = wm.server->arg(name);
|
||||
// }
|
||||
// return value;
|
||||
// }
|
||||
|
||||
//Обновление прошивки, происходит проверка и загрузка
|
||||
|
||||
void OTAUpdate()
|
||||
{
|
||||
////Serial.println("OTAUpdate() START");
|
||||
//////////Serial.println("OTAUpdate() START");
|
||||
bool flagOTA = false;
|
||||
String keyOTA;
|
||||
String payload;
|
||||
|
@ -332,19 +307,19 @@ void OTAUpdate()
|
|||
HTTPClient http;
|
||||
String serverPath = "http://meteosence.s-host.net/airqa/airquality.php?meteopas=e93gme9hAt9nSWaV&mac=" + macc + "&meteodata=gethash";
|
||||
|
||||
Serial.println(serverPath);
|
||||
//////Serial.println(serverPath);
|
||||
|
||||
http.begin(serverPath.c_str());
|
||||
int httpResponseCode = http.GET();
|
||||
|
||||
if (httpResponseCode > 0)
|
||||
{
|
||||
////Serial.print("HTTP Response code: ");
|
||||
////Serial.println(httpResponseCode);
|
||||
////////Serial.print("HTTP Response code: ");
|
||||
////////Serial.println(httpResponseCode);
|
||||
payload = http.getString();
|
||||
|
||||
////Serial.print("Data from HTTP request (OTA Hash): ");
|
||||
////Serial.println(payload);
|
||||
////////Serial.print("Data from HTTP request (OTA Hash): ");
|
||||
////////Serial.println(payload);
|
||||
|
||||
if (payload != "errno" || payload != "errfi")
|
||||
{
|
||||
|
@ -356,29 +331,29 @@ void OTAUpdate()
|
|||
OTApreferences.putString("md5HashOTA", "undifined");
|
||||
}
|
||||
|
||||
////Serial.print("md5HashOTA in device: ");
|
||||
////////Serial.print("md5HashOTA in device: ");
|
||||
keyOTA = OTApreferences.getString("md5HashOTA");
|
||||
////Serial.println(keyOTA);
|
||||
////////Serial.println(keyOTA);
|
||||
|
||||
if (payload != keyOTA)
|
||||
{
|
||||
flagOTA = true;
|
||||
OTApreferences.putString("md5HashOTA", payload);
|
||||
////Serial.println("flagOTA = true;");
|
||||
////////Serial.println("flagOTA = true;");
|
||||
}
|
||||
OTApreferences.end();
|
||||
}
|
||||
else
|
||||
{
|
||||
////Serial.print("Hosting return error: ");
|
||||
////Serial.println(payload);
|
||||
////////Serial.print("Hosting return error: ");
|
||||
////////Serial.println(payload);
|
||||
errorID = 3;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
////Serial.print("Error HTTP Response code: ");
|
||||
////Serial.println(httpResponseCode);
|
||||
////////Serial.print("Error HTTP Response code: ");
|
||||
////////Serial.println(httpResponseCode);
|
||||
errorID = 2;
|
||||
}
|
||||
// Free resources
|
||||
|
@ -386,13 +361,13 @@ void OTAUpdate()
|
|||
}
|
||||
else
|
||||
{
|
||||
////Serial.println("WHY WiFi is Disconnected??");
|
||||
////////Serial.println("WHY WiFi is Disconnected??");
|
||||
}
|
||||
|
||||
if (flagOTA == true)
|
||||
{
|
||||
// flagOTA = false;
|
||||
// ////Serial.println("flagOTA = false;");
|
||||
// ////////Serial.println("flagOTA = false;");
|
||||
|
||||
disconnectMQTT();
|
||||
|
||||
|
@ -406,29 +381,29 @@ void OTAUpdate()
|
|||
// Если указано значение true, модуль ESP перезагрузится после успешного завершения обновления. В случае ложного , модуль не перезагружается автоматически. Загруженная новая прошивка остается в стадии обновления флэш-памяти на модуле ESP.
|
||||
// Процесс загрузки во время следующего запуска модуля путем сброса скопирует обновленное микропрограммное обеспечение в фактическую область программы, и запустится новая программа эскиза. Значение по умолчанию верно.
|
||||
|
||||
////Serial.print("ret ");
|
||||
////Serial.println(ret);
|
||||
////////Serial.print("ret ");
|
||||
////////Serial.println(ret);
|
||||
|
||||
switch (ret)
|
||||
{
|
||||
case HTTP_UPDATE_FAILED:
|
||||
Serial.printf("HTTP_UPDATE_FAILD Error (%d): %s", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str());
|
||||
Serial.println(ESPhttpUpdate.getLastError());
|
||||
Serial.println(ESPhttpUpdate.getLastErrorString().c_str());
|
||||
//Serial.println("HTTP_UPDATE_FAILD Error");
|
||||
delay(3000);
|
||||
////Serial.printf("HTTP_UPDATE_FAILD Error (%d): %s", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str());
|
||||
////Serial.println(ESPhttpUpdate.getLastError());
|
||||
////Serial.println(ESPhttpUpdate.getLastErrorString().c_str());
|
||||
//////Serial.println("HTTP_UPDATE_FAILD Error");
|
||||
|
||||
ESP.restart();
|
||||
break;
|
||||
|
||||
case HTTP_UPDATE_NO_UPDATES:
|
||||
Serial.println("HTTP_UPDATE_NO_UPDATES");
|
||||
delay(3000);
|
||||
////Serial.println("HTTP_UPDATE_NO_UPDATES");
|
||||
|
||||
ESP.restart();
|
||||
break;
|
||||
|
||||
case HTTP_UPDATE_OK:
|
||||
Serial.println("HTTP_UPDATE_OK");
|
||||
delay(3000);
|
||||
////Serial.println("HTTP_UPDATE_OK");
|
||||
|
||||
ESP.restart();
|
||||
break;
|
||||
}
|
||||
|
@ -438,16 +413,14 @@ void OTAUpdate()
|
|||
//Функция для индикации Led
|
||||
void ledset(char color, bool blink = false)
|
||||
{
|
||||
M5.dis.setBrightness(100); //Половина яркости
|
||||
M5.dis.setBrightness(120); //Половина яркости
|
||||
switch (color)
|
||||
{
|
||||
case 'g':
|
||||
M5.dis.drawpix(0, 0xf00000); //Зеленый
|
||||
|
||||
break;
|
||||
case 'r':
|
||||
M5.dis.drawpix(0, 0x00f000); //Красный
|
||||
|
||||
break;
|
||||
case 'b':
|
||||
M5.dis.drawpix(0, 0x0000f0); //Синий
|
||||
|
@ -459,44 +432,6 @@ void ledset(char color, bool blink = false)
|
|||
M5.dis.clear();
|
||||
break;
|
||||
}
|
||||
if (blink == true)
|
||||
{ //Таймер для LED
|
||||
RGBWTicker.attach_ms(1000, ledBlinkTimer);
|
||||
}
|
||||
else
|
||||
{
|
||||
RGBWTicker.detach();
|
||||
}
|
||||
}
|
||||
|
||||
void ledBlinkTimer()
|
||||
{
|
||||
|
||||
if (flagblink == true)
|
||||
{
|
||||
M5.dis.setBrightness(0);
|
||||
M5.dis.drawpix(0, 0xf00000);
|
||||
|
||||
for (int b = 0; b <= 180; b++)
|
||||
{
|
||||
M5.dis.setBrightness(b);
|
||||
delay(7);
|
||||
}
|
||||
flagblink = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
M5.dis.setBrightness(180);
|
||||
M5.dis.drawpix(0, 0xf00000);
|
||||
for (int b = 180; b >= 0; b--)
|
||||
{
|
||||
M5.dis.setBrightness(b);
|
||||
delay(7);
|
||||
}
|
||||
//M5.dis.clear();
|
||||
flagblink = true;
|
||||
}
|
||||
}
|
||||
|
||||
//Получение мак адреса
|
||||
|
@ -512,8 +447,8 @@ String getMacAddress()
|
|||
//Установка коефициентов калибровки
|
||||
void SetCallibrationCoeff()
|
||||
{
|
||||
// ////Serial.print("Mac: ");
|
||||
// ////Serial.println(getMacAddress());
|
||||
// ////////Serial.print("Mac: ");
|
||||
// ////////Serial.println(getMacAddress());
|
||||
|
||||
//[24A160474D14, 5002919F5450, 5002918A38CC]
|
||||
//tcoeff[0,1,2]
|
||||
|
@ -550,7 +485,7 @@ float middleArifmT(float newVal)
|
|||
}
|
||||
averageT /= NUM_AVER; // делим
|
||||
|
||||
// ////Serial.println(averageT);
|
||||
// ////////Serial.println(averageT);
|
||||
return averageT; // возвращаем
|
||||
}
|
||||
|
||||
|
@ -632,14 +567,14 @@ void reqSensorData()
|
|||
{
|
||||
errorID = 7;
|
||||
}
|
||||
// ////Serial.println("Original data: ");
|
||||
// ////Serial.println(hdc1080.readTemperature());
|
||||
// ////Serial.println(hdc1080.readHumidity());
|
||||
// ////////Serial.println("Original data: ");
|
||||
// ////////Serial.println(hdc1080.readTemperature());
|
||||
// ////////Serial.println(hdc1080.readHumidity());
|
||||
|
||||
// ////Serial.println("Calibration data: ");
|
||||
// ////Serial.print(hdc1080Temp);
|
||||
// ////Serial.println(" ");
|
||||
// ////Serial.println(hdc1080Hum);
|
||||
// ////////Serial.println("Calibration data: ");
|
||||
// ////////Serial.print(hdc1080Temp);
|
||||
// ////////Serial.println(" ");
|
||||
// ////////Serial.println(hdc1080Hum);
|
||||
|
||||
TempAv = middleArifmT(hdc1080Temp);
|
||||
HumAv = middleArifmH(hdc1080Hum);
|
||||
|
@ -678,6 +613,9 @@ void SendMqttReq()
|
|||
dtostrf(TempAv * 100, 4, 0, TemperatureInt);
|
||||
dtostrf(HumAv * 100, 4, 0, HumidityInt);
|
||||
|
||||
int tBytes = SPIFFS.totalBytes()/1024;
|
||||
int uBytes = SPIFFS.usedBytes()/1024;
|
||||
|
||||
doc["swver"] = VersionSW;
|
||||
doc["t"] = atoi(TemperatureInt);
|
||||
doc["h"] = atoi(HumidityInt);
|
||||
|
@ -685,21 +623,23 @@ void SendMqttReq()
|
|||
doc["tvoc"] = (int)TvocAv;
|
||||
doc["rssi"] = rssi;
|
||||
// doc["hall"]= hall;
|
||||
doc["error"] = errorID; //По умолчанию 0
|
||||
doc["lasterror"] = errorID; //По умолчанию 0
|
||||
doc["memory"][0]= tBytes;
|
||||
doc["memory"][1] =uBytes;
|
||||
doc["time"] = now();
|
||||
|
||||
char resultString[200];
|
||||
String JsonData = "";
|
||||
|
||||
serializeJson(doc, JsonData);
|
||||
Serial.println(JsonData); //Вывод JSON строки в консоль
|
||||
JsonData.toCharArray(resultString, JsonData.length() + 1);
|
||||
////Serial.println(JsonData); //Вывод JSON строки в консоль
|
||||
JsonData.toCharArray(resultString, JsonData.length() + 1);
|
||||
|
||||
if (mqttSendFlag == true)
|
||||
{
|
||||
MqttClient.publish(topicName, resultString, true);
|
||||
//////Serial.println("SentToTopic - ok");
|
||||
errorID = 0;
|
||||
MqttClient.publish(bufTopic, resultString, true);
|
||||
////Serial.println("SentToTopic - ok");
|
||||
errorID = 0;
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -707,52 +647,39 @@ void SendMqttReq()
|
|||
//10 раз проверили и вернулись в общий цикл что бы вдруг что втянуть обновления
|
||||
void reconnectMqtt()
|
||||
{
|
||||
|
||||
//clientId += String(random(0xffff), HEX);
|
||||
//clientId.c_str()
|
||||
//MqttClient.connect(macc.c_str(), mqttLogin, mqttPass
|
||||
byte circle = 0;
|
||||
while (!MqttClient.connected())
|
||||
{
|
||||
////Serial.print("MQTT reconnect...");
|
||||
|
||||
circle++;
|
||||
if (circle == 5)
|
||||
if (circle == 5)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const char *clientId = macc.c_str();
|
||||
//macc += String(random(0xffff), HEX);
|
||||
String maccrandom = macc + String(random(0xffff), HEX);
|
||||
const char *clientId = maccrandom.c_str();
|
||||
|
||||
//const char *id,
|
||||
// const char *user,
|
||||
// const char *pass,
|
||||
// const char* willTopic,
|
||||
// uint8_t willQos,
|
||||
// boolean willRetain,
|
||||
// const char* willMessage,
|
||||
// boolean cleanSession
|
||||
//const char *id, const char* willTopic, uint8_t willQos, boolean willRetain, const char* willMessage
|
||||
////Serial.println(clientId);
|
||||
|
||||
//String WillfinishTopic = String(topicName) + macc + String(willTopicName);
|
||||
////Serial.println(WillfinishTopic);
|
||||
if (MqttClient.connect(clientId, bufWillTopic, 2, true, "OFFLINE"))
|
||||
{
|
||||
|
||||
if (MqttClient.connect(clientId, NULL, NULL, willTopicName, 2, true, "Offline"))
|
||||
{
|
||||
//String finishTopic = "";
|
||||
// finishTopic = String(topicName) + "/" + macc;
|
||||
MqttClient.publish(topicName, "CONNECT", true);
|
||||
MqttClient.publish(bufTopic, "CONNECT", true);
|
||||
MqttClient.publish(bufWillTopic, "ONLINE", true);
|
||||
|
||||
////Serial.println("Reconnect NOW");
|
||||
////Serial.println("MqttClient.connect() - OK");
|
||||
errorID = 8;
|
||||
// client.subscribe("inTopic");
|
||||
//client.subscribe("inTopic");
|
||||
mqttSendFlag = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
////Serial.print("failed сonnect to MQTT, rc=");
|
||||
Serial.println(MqttClient.state());
|
||||
/*
|
||||
////Serial.print("MqttClient.state() = ");
|
||||
////Serial.println(MqttClient.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
|
||||
|
@ -765,7 +692,7 @@ void reconnectMqtt()
|
|||
5 : MQTT_CONNECT_UNAUTHORIZED - the client was not authorized to connect
|
||||
*/
|
||||
mqttSendFlag = false;
|
||||
delay(100);
|
||||
delay(3000);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -781,15 +708,15 @@ void loop()
|
|||
{
|
||||
ledset('r', true);
|
||||
checkButton();
|
||||
}
|
||||
}
|
||||
|
||||
//По таймеру запруск обновления прошивки
|
||||
if (millis() - timingUpdate > nextM5Update)
|
||||
{
|
||||
reqNtpTime();
|
||||
OTAUpdate();
|
||||
// ////Serial.print("OTAUpdate() - ");
|
||||
// ////Serial.println(millis());
|
||||
// ////////Serial.print("OTAUpdate() - ");
|
||||
// ////////Serial.println(millis());
|
||||
timingUpdate = millis();
|
||||
}
|
||||
|
||||
|
@ -798,8 +725,8 @@ void loop()
|
|||
{
|
||||
reqSensorData();
|
||||
ledset('b', true);
|
||||
// ////Serial.print("reqSensorData() - ");
|
||||
// ////Serial.println(millis());
|
||||
// ////////Serial.print("reqSensorData() - ");
|
||||
// ////////Serial.println(millis());
|
||||
timingReqSensor = millis();
|
||||
}
|
||||
|
||||
|
@ -818,17 +745,17 @@ void loop()
|
|||
ledset('w', true);
|
||||
}
|
||||
|
||||
// ////Serial.println("=============");
|
||||
// ////////Serial.println("=============");
|
||||
// rssi = WiFi.RSSI();
|
||||
// ////Serial.println(rssi);
|
||||
// ////Serial.println("=============");
|
||||
// ////////Serial.println(rssi);
|
||||
// ////////Serial.println("=============");
|
||||
|
||||
MqttClient.loop();
|
||||
}
|
||||
|
||||
int disconnectMQTT()
|
||||
{
|
||||
MqttClient.publish(topicName, "DISCONNECT", false);
|
||||
{
|
||||
MqttClient.publish(bufTopic, "DISCONNECTED", true);
|
||||
MqttClient.disconnect();
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue