Восстановление после краша, данные ТВОК скорее всего сбрасываются каждую перезагрузку, независимо

master
SmartUaWIn 2021-03-30 10:21:24 +03:00
parent 9ec7e03635
commit 5f19f1ba2f
4 changed files with 153 additions and 102 deletions

BIN
38.bin Normal file

Binary file not shown.

BIN
39.bin Normal file

Binary file not shown.

View File

@ -55,7 +55,7 @@
#define CCS811_ADDR 0x5B //Default I2C Address
//#define CCS811_ADDR 0x5A //Alternate I2C Address
unsigned int VersionSW = 36; //65536 Версия прошивки
unsigned int VersionSW = 42; //65536 Версия прошивки
//15 - добавлено то, се, забыл вообще дописать что добавленоSerial
//19 - вывод в консоль всех действий, ошибки с обновлнеием - починил, прияногое мигание светодиодом, тест для поиска metrics.
@ -67,16 +67,19 @@ unsigned int VersionSW = 36; //65536 Версия прошивки
//26 - тест обновления сука - работает
//27 - таймаут станции без wifi 40 сек
//28 - калибровка вернулась
//29 - baseline выведен и отключен
//30 - новое освещение оранжевый цвет
//29 - baseline выведен из 24х часов и отключен
//30 - новое освещение оранжевый цвет который нихера не оранжевый
//31 - фиксим время
//32 - рестарт без wifi
//33 - бейслайн и куча изменений по переподключению mqtt
//34 - правка с опросом, бесконечный цикл
//35 - закоменчен вывод ошибок available
//36 - настройка mqtt по ip и режимы датчика
gpio_num_t pinWak = GPIO_NUM_23;
//35 - закоменчен вывод ошибок available
//36 - настройка mqtt по ip и режимы датчика - неудачная загрузка 27.03
//37-38 - сохранение ip metrics, и чтение из памяти, убрана базовая линия. Логин пароль.
// Фиксим получение временя 29.03
//39 новая функция преобразования Ip в строку.
//41 уменьшил код на 7%. Перезалив. Отвалились 3 из 5, но не отвалились, ходят за обновлениями, все успешно
//42
WiFiManager wm; // обьект менеджера
WiFiManagerParameter custom_field;
@ -84,25 +87,27 @@ Preferences OTApreferences; //Обьект хранения настроек х
Adafruit_CCS811 ccs;
ClosedCube_HDC1080 hdc1080;
StaticJsonDocument<200> doc, other;
StaticJsonDocument<200> doc;
WiFiClient espClient;
PubSubClient MqttClient(espClient);
IPAddress IpMqtt(192,168,89,210);
//IPAddress IpMqtt(192,168,89,210);
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org", 0, 60000); //Собственно сервер времени смещение и частоат запроса, но он вручную
NTPClient timeClient(ntpUDP, "0.ua.pool.ntp.org", 0, 60000); //Собственно сервер времени смещение и частоат запроса, но он вручную
const PROGMEM char *willmess = "{\"conn\":\"err\"}";
const char *mqttHostName = "metrics"; //Хостнейм брокера metrics.local cctv.automation.art //192.168.89.210
unsigned int mqttPort = 1883; //Порт брокера 1883 8889
const char *prefArea = "ota-config";
String getMacAddress();
String macc = getMacAddress();
String topicTemp = "aastudio/sens/" + macc + "/data/0";
String willTopicTemp = "aastudio/sens/" + macc + "/status";
const PROGMEM char *mqttLogin = "login", *mqttPass = "password";
const PROGMEM char *mqttLogin = "AA_Lab", *mqttPass = "automation.art$";
char bufTopic[140];
char bufWillTopic[150];
@ -110,18 +115,14 @@ char bufWillTopic[150];
const char *mqttIPHost;
RTC_DATA_ATTR byte countOta = 0;
int PROGMEM nextM5Update = 450000; //каждые 7.5 минут запрос обновления с сервера
int PROGMEM nextReqSensor = 10000; //опрос датчиков раз в 10 секунд
int PROGMEM nextMqttSend = 60000; //Отправка
float TempAv, HumAv, Eco2Av, TvocAv;
unsigned int BaselineTvoc = 0;
byte errorID = 0;
long rssi = 0;
byte idxT = 0, idxH = 0, idxECO = 0, idxTVOC = 0;
unsigned int cntWhile = 4;
bool mqttSendFlag = false;
int reqCounter = 0;
bool flagblink = true;
void ledset(byte color = 0, bool blink = false)
@ -147,17 +148,92 @@ void ledset(byte color = 0, bool blink = false)
}
}
IPAddress str2IP(String str)
{
IPAddress ret(getIpBlock(0, str), getIpBlock(1, str), getIpBlock(2, str), getIpBlock(3, str));
return ret;
}
int getIpBlock(int index, String str)
{
char separator = '.';
int found = 0;
int strIndex[] = {0, -1};
int maxIndex = str.length() - 1;
for (int i = 0; i <= maxIndex && found <= index; i++)
{
if (str.charAt(i) == separator || i == maxIndex)
{
found++;
strIndex[0] = strIndex[1] + 1;
strIndex[1] = (i == maxIndex) ? i + 1 : i;
}
}
return found > index ? str.substring(strIndex[0], strIndex[1]).toInt() : 0;
}
int setMqttServer(const char *mqttHostNameF, unsigned int mqttPortF)
{
mdns_init();
IPAddress ipaddr;
OTApreferences.begin("ota-config");
String keyIpMqtt = OTApreferences.getString("mqttip", "0");
//Если нет IP в preferences
Serial.print("keyIpMqtt: ");
Serial.println(keyIpMqtt);
if (keyIpMqtt == "0")
{
//Запрос по хостнейму .local
ipaddr = MDNS.queryHost(mqttHostNameF, 4000);
//Таймаут 4 секунды
//Если не получили по хостнейму МДНС
Serial.print("mdns: ");
Serial.println(ipaddr);
if (ipaddr.toString() == "0.0.0.0")
{
//Запрос к ДНС по адресу сайта
int err = WiFi.hostByName(mqttHostNameF, ipaddr);
////real internal timeout in lwip library is 14[s]
//Если получили по хостнейму
if (err == 1)
{
Serial.print("hostByName: ");
Serial.println(ipaddr);
MqttClient.setServer(ipaddr, mqttPortF);
OTApreferences.putString("mqttip", ipaddr.toString());
}
else
{
Serial.print("All method not FOUND IP");
}
}
else
{ //Если все хорошо
OTApreferences.putString("mqttip", ipaddr.toString());
MqttClient.setServer(ipaddr, mqttPortF);
}
}
else
{
MqttClient.setServer(str2IP(keyIpMqtt), mqttPortF);
}
OTApreferences.end();
return 0;
}
//Настройки
void setup()
{
Serial.begin(115200);
Serial.setDebugOutput(true);
btStop();
// esp_bt_controller_disable();
// adc_power_on();
M5.begin(true, false, true);
Wire.begin(25, 21); //Пины для I2c на ATOM
@ -169,18 +245,17 @@ void setup()
hdc1080.begin(0x40);
hdc1080.setResolution(HDC1080_RESOLUTION_11BIT, HDC1080_RESOLUTION_11BIT);
while (!ccs.begin() && !ccs.available()) //The device's I2C address is 0x5A
for (int t = 0; t <= cntWhile; t++)
{
ledset(1, true);
if (ccs.begin())
{
break;
}
ledset(1, false);
}
ccs.setDriveMode(CCS811_DRIVE_MODE_10SEC);
//ccs.setTempOffset(8.6);
//ccs.setBaseline(25725);
//Установка коеффициентов каллибровки по MAC адресу
// SetCallibrationCoeff();
delay(15);
//ccs.setTempOffset(8.6);
//ccs.setBaseline(25725);
WiFi.mode(WIFI_STA);
@ -194,72 +269,58 @@ void setup()
std::vector<const char *> menu = {"wifi", "info", "param", "sep", "restart", "exit"};
wm.setMenu(menu);
wm.setClass("invert");
// wm.setClass("invert");
wm.setConfigPortalTimeout(40);
wm.setMinimumSignalQuality(20);
wm.setScanDispPerc(true);
wm.setWiFiAutoReconnect(true);
bool res;
res = wm.autoConnect("AirQaPortal", "12345678"); // Подключение к анонимной точке доступа
bool res = wm.autoConnect("AirQaPortal", "12345678"); // Подключение к анонимной точке доступа
if (!res)
{
////////////Serial.println("Failed to connect or hit timeout");
ESP.restart();
}
else
{
////////////Serial.println("Server AirQaPortal start");
}
//Запрос IP сервера MQTT и установка сервера
MqttClient.setServer(IpMqtt, mqttPort);
reqNtpTime();
setMqttServer(mqttHostName, mqttPort);
if (reqNtpTime() == 1)
{
reqNtpTime();
}
}
//Установка сервера и порта
int reqNtpTime()
{
if (timeClient.update())
{
uint32_t timeEpoch = timeClient.getEpochTime();
if (timeEpoch < 1000000)
if (timeEpoch < 1600000000)
{
Serial.println("Error Time");
Serial.println("Error reqNtpTime() Time");
return 1;
}
setTime(timeEpoch);
// Serial.print(timeEpoch);
// Serial.print(" <=ntp== ==device=> ");
// Serial.println(now());
}
return 0;
}
int checkButton()
{
Serial.println("Button Pressed to RESET");
OTApreferences.begin(prefArea);
OTApreferences.clear();
OTApreferences.end();
wm.resetSettings();
ESP.restart();
//////////Serial.println("Starting config portal");
//wm.setConfigPortalTimeout(120);
// if (!wm.startConfigPortal("AirQaPortal", "12345678")) //Логин и пароль точки доступа
// {
// Serial.println("failed to connect or hit timeout");
// ESP.restart();
// }
// else
// {
// Serial.println("Clien connected to AP");
// }
return 0;
}
@ -289,7 +350,7 @@ void OTAUpdate()
if (payload != "errno" || payload != "errfi")
{
OTApreferences.begin("ota-config");
OTApreferences.begin(prefArea);
keyOTA = OTApreferences.getString("md5HashOTA");
if (keyOTA.length() <= 0)
@ -310,13 +371,11 @@ void OTAUpdate()
{
Serial.print("Host error: ");
Serial.println(payload);
errorID = 3;
}
}
else
{
Serial.println(httpResponseCode);
errorID = 2;
}
// Free resources
http.end();
@ -384,7 +443,7 @@ int SetCallibrationCoeff(String MacThat)
TempAv += -6.91;
HumAv += 7.95;
}
if (MacThat == "5002918A38CC")
{
TempAv += -5.72;
@ -415,40 +474,48 @@ int SetCallibrationCoeff(String MacThat)
//Запрос данных с датчиков.
void reqSensorData()
{
float hdc1080Temp = 0, hdc1080Hum = 0;
int eco2 = 0, tvoc = 0;
hdc1080Temp = hdc1080.readTemperature();
hdc1080Hum = hdc1080.readHumidity();
if (hdc1080Temp < -40 || hdc1080Temp > 60)
{
errorID = 6;
}
if (hdc1080Hum < 0 || hdc1080Temp > 100)
{
errorID = 7;
}
char outstr[6];
dtostrf(hdc1080Temp, 5, 2, outstr);
TempAv = atof(outstr);
dtostrf(hdc1080Hum, 5, 2, outstr);
HumAv = atof(outstr);
for (int g = 0; g <= 7; g++)
int counAvail = 0;
ledset(4, false);
while (!ccs.available())
{
while (!ccs.available())
counAvail++;
if (counAvail >= 1000)
{
// Serial.println("ccs.NONE available()");
}
break;
}
}
if (!ccs.readData())
Serial.print("counAvail: ");
Serial.println(counAvail);
for (int t = 0; t <= 7; t++)
{
Serial.println(ccs.readData());
{
ledset(2, false);
ccs.setEnvironmentalData(hdc1080Hum - 55, hdc1080Temp - 25);
eco2 = ccs.geteCO2();
delay(1200);
}
else
{
Serial.println("=======ECO TVOC NONE READ");
}
}
eco2 = ccs.geteCO2();
tvoc = ccs.getTVOC();
BaselineTvoc = ccs.getBaseline();
Serial.print(eco2);
@ -456,25 +523,9 @@ void reqSensorData()
Serial.print(tvoc);
Serial.print(" ");
Serial.println(BaselineTvoc);
}
else
{
Serial.println("==========ECO TVOC NONE READ");
}
// else
// {
// eco2 = 0;
// tvoc = 0;
// Serial.println("==========ECO TVOC NONE AVAILABLE");
// errorID = 5;
// delay(1000);
// }
}
Eco2Av = eco2;
TvocAv = tvoc;
rssi = WiFi.RSSI();
}
@ -553,6 +604,7 @@ int SendMqttReq(bool sendVal = true, bool sendStatus = true, byte statusConn = 1
doc["rssi"] = rssi;
doc["bsid"] = WiFi.BSSIDstr();
doc["ts"] = timeNow;
doc["tsexp"] = timeNow + 60 + 11;
doc["sv"] = VersionSW;
JsonData = "";
@ -574,8 +626,6 @@ void reconnectMqtt()
byte circle = 0;
while (!MqttClient.connected())
{
Serial.print("MQTT reconnect...");
circle++;
if (circle == 7)
{
@ -585,9 +635,9 @@ void reconnectMqtt()
String maccrandom = macc + String(random(0xffff), HEX);
const char *clientId = maccrandom.c_str();
if (MqttClient.connect(clientId, bufWillTopic, 2, true, willmess))
if (MqttClient.connect(clientId, mqttLogin, mqttPass, bufWillTopic, 2, true, willmess))
{
Serial.println("MqttClient.connect() - OK");
Serial.println("Mqttconnect - OK");
mqttSendFlag = true;
@ -595,7 +645,7 @@ void reconnectMqtt()
}
else
{
Serial.print("MqttClient.state() = ");
Serial.print("Mqtt.state() = ");
Serial.println(MqttClient.state());
/*
-4 : MQTT_CONNECTION_TIMEOUT - the server didn't respond within the keepalive time
@ -622,6 +672,7 @@ void loop()
if (!MqttClient.connected())
{
Serial.print("MQTT reconnect..");
reconnectMqtt();
}

Binary file not shown.