From 151a7067a93481c6982c57063156f73c77cbd117 Mon Sep 17 00:00:00 2001 From: SmartUA Date: Tue, 6 Apr 2021 11:33:58 +0300 Subject: [PATCH] =?UTF-8?q?=D0=98=D0=B7=D0=BC=D0=B5=D0=BD=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AAOffice_kitchen.ino | 459 +++++++++++++++++++++++-------------------- README.md | 9 +- 2 files changed, 253 insertions(+), 215 deletions(-) diff --git a/AAOffice_kitchen.ino b/AAOffice_kitchen.ino index bbd89bd..0a9c7da 100644 --- a/AAOffice_kitchen.ino +++ b/AAOffice_kitchen.ino @@ -1,7 +1,7 @@ /* Отправка данных на MQTT про обновление */ - + #include // https://github.com/tzapu/WiFiManager #include //Сохранение настроек хеша прошивки @@ -17,19 +17,22 @@ #include //Mtqq #include //Упакова в JSon - удобная библиотека #include +#include //Наша кнопочка при нажатии на которую произойдет вызов wifi менеджера и перезагрузка в станцию #define TRIGGER_PIN 39 #define safetyPin 33 #define buzzerPin 23 -#define VersionSW 2 +#define VersionSW 3 + +//3 - версия с прошивкой. extern const unsigned char image_arrow[77], image_x[77], image_error[77], image_wateok[77], image_connect[77], image_wifi[77]; //const unsigned int VersionSW = 5; //65536 Версия прошивки byte errorID = 0; //Сбор и вывод ошибок -//5 +Ticker BuzTicker; WiFiManager wm; // обьект менеджера //WiFiManagerParameter custom_field; @@ -38,61 +41,98 @@ StaticJsonDocument<200> doc; WiFiClient espClient; PubSubClient MqttClient(espClient); -IPAddress IpMqtt; +IPAddress IpMqtt(192, 168, 89, 210); WiFiUDP ntpUDP; -NTPClient timeClient(ntpUDP, "0.ua.pool.ntp.org", 7200, 60000); //Собственно сервер времени смещение и частоат запроса, но он вручную +NTPClient timeClient(ntpUDP, "192.168.89.210", 0, 60000); //Собственно сервер времени смещение и частоат запроса, но он вручную -const char *wmhostname="KitchenWater"; +const char *wmhostname = "KitchenWater"; const PROGMEM char *willmess = "{\"conn\":\"err\"}"; -const PROGMEM char *mqttHostName = "cctv.automation.art"; //Хостнейм брокера 192.168.89.210 cctv.automation.art:8889 -unsigned int mqttPort = 8889; // 1883 //Порт брокера 1883 -const PROGMEM char *mqttLogin = NULL, //Логин пароль - необходимо сменить код при connect() - *mqttPass = NULL; -const char *mqttIPHost; //тут хранится IP хоста по хостнейму +const PROGMEM char *mqttHostName = "192.168.89.210"; //Хостнейм брокера 192.168.89.210 cctv.automation.art:8889 +unsigned int mqttPort = 1883; // 1883 //Порт брокера 1883 +const PROGMEM char *mqttLogin = "AA_Lab", *mqttPass = "automation.art$"; +const char *mqttIPHost; +//тут хранится IP хоста по хостнейму unsigned long timingUpdate, timingReqSensor, timingSendMqtt; //Таймеры для millis() int PROGMEM nextM5Update = 450000; //каждые 7.5 минут запрос обновления с сервера //опрос датчиков раз в 10 секунд -short int PROGMEM nextMqttSend = 500; //Отправка String getMacAddress(); String macc = getMacAddress(); -bool buzFlag = true; +bool buzFlag = false; bool mqttSendFlag = false; bool safetyStateNow = true, safetyStateOld = true; int reqCounter = 0; short int rssi = 0; -bool flagHIGH = true; +bool flagHIGH = false; char bufTopic[140], bufWillTopic[150]; volatile short int debounce = 0; +TaskHandle_t Task1; +TaskHandle_t Task2; + +void Task1code(void *pvParameters); +void Task2code(void *pvParameters); +void buzAlarm(); +int SendMqttReq(bool, bool, byte); + void IRAM_ATTR detectWaterOn() { if (millis() - debounce >= 100 && digitalRead(safetyPin) == LOW) { debounce = millis(); buzFlag = true; - detachInterrupt(digitalPinToInterrupt(safetyPin)); + detachInterrupt(digitalPinToInterrupt(safetyPin)); } } //Настройки void setup() { + Serial.begin(115200); - M5.begin(true, false, true); - delay(50); - // Wire.begin(25, 21); //Пины для I2c на ATOM - M5.dis.setBrightness(30); - pinMode(safetyPin, INPUT_PULLDOWN); //Пин датчика для работы + vTaskDelay(50); + // Wire.begin(25, 21); //Пины для I2c на ATOM + M5.dis.setBrightness(50); + disPreSet((uint8_t *)image_connect, 0, 0); + + pinMode(safetyPin, INPUT); //Пин датчика для работы pinMode(buzzerPin, OUTPUT); digitalWrite(buzzerPin, LOW); + detectWaterOn(); + + Serial.println("--------"); + Serial.println(digitalRead(safetyPin)); + Serial.println("--------"); + + xTaskCreatePinnedToCore( + Task1code, /* Функция задачи */ + "Task1", /* Название задачи */ + 3024, /* Размер стека задачи */ + NULL, /* Параметр задачи */ + 0, /* Приоритет задачи */ + &Task1, /* Идентификатор задачи, чтобы ее можно было отслеживать */ + 0); /* Ядро для выполнения задачи (0) */ + vTaskDelay(100); + + // Создаем задачу с кодом из функции Task2code(), + // с приоритетом 1 и выполняемую на ядре 1: + xTaskCreatePinnedToCore( + Task2code, /* Функция задачи */ + "Task2", /* Название задачи */ + 7024, /* Размер стека задачи */ + NULL, /* Параметр задачи */ + 1, /* Приоритет задачи */ + &Task2, /* Идентификатор задачи, чтобы ее можно было отслеживать */ + 1); /* Ядро для выполнения задачи (1) */ + vTaskDelay(100); + attachInterrupt(digitalPinToInterrupt(safetyPin), detectWaterOn, CHANGE); // LOW – прерывание будет запущено, если на контакте будет значение «LOW» // HIGH – прерывание будет запущено, если на контакте будет значение «HIGH» @@ -100,111 +140,100 @@ void setup() // FALLING – прерывание будет запущено, если значение на контакте изменится с «HIGH» на «LOW» // RISING – прерывание будет запущено, если значение на контакте изменится с «LOW» на «HIGH» - Serial.setDebugOutput(true); + // Serial.setDebugOutput(true); - String topicTemp = "aastudio/" + macc + "/data/0"; - String willTopicTemp = "aastudio/" + macc + "/status"; - // String angleTopicTemp = topicTemp + "/setangle"; + String topicTemp = "aastudio/sens/" + macc + "/data/0"; + String willTopicTemp = "aastudio/sens/" + macc + "/status"; Serial.println(topicTemp); Serial.println(willTopicTemp); - ////Serial.println(angleTopicTemp); topicTemp.toCharArray(bufTopic, topicTemp.length() + 1); willTopicTemp.toCharArray(bufWillTopic, willTopicTemp.length() + 1); //angleTopicTemp.toCharArray(bufAngleTopic, angleTopicTemp.length() + 1); - disPreSet((uint8_t *)image_connect, 0, 0); - - //Serial.println("\n Starting station"); pinMode(TRIGGER_PIN, INPUT); // wm.resetSettings(); // wipe settings - // add a custom input field - //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 - // test custom html(radio) - //const char *custom_radio_str = "
One
Two
Three"; - //new (&custom_field) WiFiManagerParameter(custom_radio_str); // custom html input - //wm.addParameter(&custom_field); - //wm.setSaveParamsCallback(saveParamCallback); - // custom menu via array or vector - // menu tokens, "wifi","wifinoscan","info","param","close","sep","erase","restart","exit" (sep is seperator) (if param is in menu, params will not show up in wifi page!) - // const char* menu[] = {"wifi","info","param","sep","restart","exit"}; - // wm.setMenu(menu,6); + std::vector menu = {"wifi", "info", "param", "sep", "restart", "exit"}; wm.setMenu(menu); // set dark theme - wm.setClass("invert"); + wm.setClass("invert"); //set static ip // wm.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); // set static ip,gw,sn // 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(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 - // wm.setRemoveDuplicateAPs(false); // do not remove duplicate ap names (true) + wm.setConfigPortalTimeout(1); // 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 + // wm.setRemoveDuplicateAPs(false); // do not remove duplicate ap names (true) wm.setMinimumSignalQuality(10); // set min RSSI (percentage) to show in scans, null = 8% - // wm.setShowInfoErase(false); // do not show erase button on info page - wm.setScanDispPerc(true); // show RSSI as percentage not graph icons + // wm.setShowInfoErase(false); // do not show erase button on info page + wm.setScanDispPerc(true); // show RSSI as percentage not graph icons + wm.setConfigPortalBlocking(false); // wm.setBreakAfterConfig(true); // always exit configportal even if wifi save fails - // wm.setWiFiAutoReconnect(true); // if true, enable autoreconnecting - // wm.setConfigPortalBlocking(false); - wm.setHostname(wmhostname); - wm.setConfigPortalBlocking(false); + wm.setWiFiAutoReconnect(true); // if true, enable autoreconnecting + //wm.setHostname(wmhostname); bool res; - - // res = wm.autoConnect("KitchenM5Portal", "12345678"); - // if (!res) - // { - // Serial.println("Failed to connect or hit timeout"); - // //ESP.restart(); - // } - // else - // { - // Serial.println("connected - OK"); - // } - - //Запрос IP сервера MQTT и установка сервера - setMqttServer(); - reqNtpTime(); -} - -//Установка сервера и порта -void setMqttServer() -{ - mdns_init(); - - IPAddress IpMqtt, ipaddr; - ipaddr = MDNS.queryHost(mqttHostName); // .local omitted - // //Serial.println(ipaddr.toString()); - if (ipaddr.toString() == "0.0.0.0") + res = wm.autoConnect("KitchenM5Portal", "12345678"); + if (!res) { - Serial.println("Trying again to resolve mDNS"); - - int err = WiFi.hostByName(mqttHostName, IpMqtt); - if (err == 1) - { - delay(50); - setServCall(IpMqtt); - } - else - { - errorID = 1; - Serial.print("Error code hostByName(): "); - Serial.println(err); - } + Serial.println("Failed to connect or hit timeout"); + //ESP.restart(); } else { - setServCall(ipaddr); + Serial.println("WIFI - OK"); + } + + reqNtpTime(); + + setServCall(IpMqtt); + + if (!MqttClient.connected()) + { + reconnectMqtt(); + } + else + { + SendMqttReq(true, true, 1); } } +// Установка сервера и порта +// void setMqttServer() +// { +// mdns_init(); + +// IPAddress IpMqtt, ipaddr; +// ipaddr = MDNS.queryHost(mqttHostName); // .local omitted +// // //Serial.println(ipaddr.toString()); +// if (ipaddr.toString() == "0.0.0.0") +// { +// Serial.println("Trying again to resolve mDNS"); + +// int err = WiFi.hostByName(mqttHostName, IpMqtt); +// if (err == 1) +// { +// vTaskDelay(50); +// setServCall(IpMqtt); +// } +// else +// { +// errorID = 1; +// Serial.print("Error code hostByName(): "); +// Serial.println(err); +// } +// } +// else +// { +// setServCall(ipaddr); +// } +// } + void setServCall(IPAddress SetIpaddr) { MqttClient.setServer(SetIpaddr, mqttPort); @@ -243,10 +272,10 @@ void checkButton() disconnectMQTT(); wm.resetSettings(); - // + // wm.startConfigPortal(); - // ESP.restart(); + // ESP.restart(); } String getParam(String name) @@ -259,7 +288,6 @@ String getParam(String name) return value; } - //Обновление прошивки, происходит проверка и загрузка //Делается Get запрос на хостинг проверяется хеш, если хеш void OTAUpdate() @@ -402,14 +430,14 @@ int SendMqttReq(bool sendVal = true, bool sendStatus = true, byte statusConn = 1 doc.clear(); doc.garbageCollect(); - Serial.println(JsonData); //Вывод JSON строки в консоль + Serial.println(JsonData); JsonData.toCharArray(resultString, JsonData.length() + 1); MqttClient.publish(bufTopic, resultString, true); } if (sendStatus == true) { - const char *conn; + const char *conn; switch (statusConn) { @@ -425,6 +453,10 @@ int SendMqttReq(bool sendVal = true, bool sendStatus = true, byte statusConn = 1 conn = "slp"; break; + case 4: + conn = "upd"; + break; + default: break; } @@ -438,15 +470,15 @@ int SendMqttReq(bool sendVal = true, bool sendStatus = true, byte statusConn = 1 JsonData = ""; serializeJson(doc, JsonData); - Serial.println(JsonData); //Вывод JSON строки в консоль + Serial.println(JsonData); doc.clear(); doc.garbageCollect(); JsonData.toCharArray(resultString, JsonData.length() + 1); MqttClient.publish(bufWillTopic, resultString, true); + Serial.println("SentToTopic - ok"); } - ////Serial.println("SentToTopic - ok"); } return 0; } @@ -462,17 +494,8 @@ void reconnectMqtt() byte circle = 0; while (!MqttClient.connected()) { - Serial.println("MQTT reconnect..."); - circle++; - if(circle == 2) - { - disPreSet((uint8_t *)image_error, 0, 0); - break; - } - const char *clientId = macc.c_str(); - //macc += String(random(0xffff), HEX); - if(MqttClient.connect(clientId, bufWillTopic, 2, true, willmess)) + if (MqttClient.connect(clientId, mqttLogin, mqttPass, bufWillTopic, 2, true, willmess)) { mqttSendFlag = true; SendMqttReq(true, true, 1); @@ -495,131 +518,139 @@ void reconnectMqtt() */ errorID = 5; mqttSendFlag = false; - delay(1000); + } + circle++; + if (circle == 3) + { + break; } } } void loop() { - M5.update(); - if (buzFlag == true) - { - disPreSet((uint8_t *)image_arrow, 0, 0); - - safetyStateNow = false; - flagHIGH = true; - buzAlarm(true); - Serial.println(" buzFlag == true "); - } - - if (digitalRead(safetyPin) == HIGH && flagHIGH == true) - { - Serial.println(" digitalRead(safetyPin) == HIGH "); - buzFlag = false; - buzAlarm(false); - safetyStateNow = true; - - disPreSet((uint8_t *)image_wateok, 0, 0); - flagHIGH = false; - - attachInterrupt(digitalPinToInterrupt(safetyPin), detectWaterOn, CHANGE); - // LOW – прерывание будет запущено, если на контакте будет значение «LOW» - // HIGH – прерывание будет запущено, если на контакте будет значение «HIGH» - // CHANGE – прерывание будет запущено, если значение на контакте изменится (например, с «LOW» на «HIGH» или с «HIGH» на «LOW») - // FALLING – прерывание будет запущено, если значение на контакте изменится с «HIGH» на «LOW» - // RISING – прерывание будет запущено, если значение на контакте изменится с «LOW» на «HIGH» - } - - if (safetyStateNow != safetyStateOld) - { - SendMqttReq(true, true, 1); - safetyStateOld = safetyStateNow; - } - - if (WiFi.status() == WL_CONNECTED) - { - if (!MqttClient.connected()) - { - errorID = 7; - reconnectMqtt(); - } - } - else - { - Serial.println(WiFi.status()); - disPreSet((uint8_t *)image_wifi, 0, 0); - errorID = 6; - delay(3000); - ESP.restart(); - } - - // 40 секунд и происходит сброс настроек WIFI - if (M5.Btn.wasReleasefor(10000)) - { - checkButton(); - } - - if (M5.Btn.wasReleasefor(2000)) - { - buzAlarm(false); - } - - //По таймеру запруск обновления прошивки - if (millis() - timingUpdate > nextM5Update) - { - reqNtpTime(); - OTAUpdate(); - // //Serial.print("OTAUpdate() - "); - // //Serial.println(millis()); - timingUpdate = millis(); - } - - //Таймер отправки данных в брокер - - MqttClient.loop(); - wm.process(); } int disconnectMQTT() { + Serial.println("Disconnect MQTT server..."); SendMqttReq(false, true, 2); - MqttClient.disconnect(); return 0; } -// disPreSet((uint8_t *)image_wateok,0,0); int disPreSet(uint8_t *image_what, int8_t x, int8_t y) { // M5.dis.fillpix(0x000000); - M5.dis.clear(); - delay(100); + // M5.dis.clear(); + // vTaskDelay(100); M5.dis.displaybuff(image_what, x, y); - delay(100); - + vTaskDelay(500); return 0; } -int buzAlarm(bool buzFlag) +//ядро 0 ядро +void Task1code(void *pvParameters) { - Serial.print("Buzzer: "); - Serial.println(buzFlag); - - if (buzFlag == true) - { - // digitalWrite(buzzerPin, HIGH); - // delay(100); - // digitalWrite(buzzerPin, LOW); - // delay(100); - // digitalWrite(buzzerPin, HIGH); - // delay(200); - // digitalWrite(buzzerPin, LOW); - // delay(200); - } - else + for (;;) { - digitalWrite(buzzerPin, LOW); + if (buzFlag == true && flagHIGH == false) + { + safetyStateNow = false; + flagHIGH = true; + BuzTicker.attach_ms(900, buzAlarm); + + Serial.println(" buzFlag == true && flagHIGH == false "); + } + + if (digitalRead(safetyPin) == HIGH && flagHIGH == true) + { + Serial.println(" digitalRead(safetyPin) == HIGH && flagHIGH == true"); + buzFlag = false; + safetyStateNow = true; + BuzTicker.detach(); + + flagHIGH = false; + + attachInterrupt(digitalPinToInterrupt(safetyPin), detectWaterOn, CHANGE); + } + + if (M5.Btn.pressedFor(60000)) + { + checkButton(); + } + + if (M5.Btn.pressedFor(2000)) + { + Serial.println("KNOPKA SUKA"); + BuzTicker.detach(); + } + + MqttClient.loop(); + vTaskDelay(10); } - return 0; } + +// loop 1 ядро +void Task2code(void *pvParameters) +{ + for (;;) + { + M5.update(); + wm.process(); + + if (WiFi.status() != WL_CONNECTED) + { + disPreSet((uint8_t *)image_wifi, 0, 0); + } + + if (safetyStateNow != safetyStateOld) + { + Serial.println("safetyStateNow != safetyStateOld"); + SendMqttReq(true, true, 1); + + safetyStateOld = safetyStateNow; + } + + if (buzFlag == false) + { + disPreSet((uint8_t *)image_wateok, 0, 0); + } + else + { + disPreSet((uint8_t *)image_arrow, 0, 0); + } + + //По таймеру запруск обновления прошивки + if (millis() - timingUpdate > nextM5Update) + { + SendMqttReq(false, true, 4); + // reqNtpTime(); + OTAUpdate(); + // //Serial.print("OTAUpdate() - "); + // //Serial.println(millis()); + SendMqttReq(false, true, 1); + timingUpdate = millis(); + } + //Таймер отправки данных в брокер + + if (!MqttClient.connected()) + { + errorID = 7; + disPreSet((uint8_t *)image_error, 0, 0); + reconnectMqtt(); + } + vTaskDelay(10); + } +} + +void buzAlarm() +{ + digitalWrite(buzzerPin, HIGH); + vTaskDelay(100); + digitalWrite(buzzerPin, LOW); + vTaskDelay(100); + digitalWrite(buzzerPin, HIGH); + vTaskDelay(200); + digitalWrite(buzzerPin, LOW); +} \ No newline at end of file diff --git a/README.md b/README.md index 0137aac..1db0db9 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,6 @@ aastudio/94B97E92C24C/status {"swver":5,"waterlevel":1,"rssi":-69,"bsid":"70:4F:57:AA:2F:8A","lasterror":7,"time":1615576359} - Экран https://github.com/m5stack/M5Atom/blob/master/README.md @@ -34,3 +33,11 @@ https://github.com/m5stack/M5Atom/blob/master/README.md http://wikihandbk.com/wiki/ESP32:%D0%9F%D1%80%D0%B8%D0%BC%D0%B5%D1%80%D1%8B/%D0%98%D1%81%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5_ESP32_%D0%B2%D0%BC%D0%B5%D1%81%D1%82%D0%B5_%D1%81_PIR-%D0%B4%D0%B0%D1%82%D1%87%D0%B8%D0%BA%D0%BE%D0%BC_%D0%B4%D0%B2%D0%B8%D0%B6%D0%B5%D0%BD%D0%B8%D1%8F + + +Старт + + +Запустили сериал +Запустили М5 +Установили пины