diff --git a/Kuhnya/.gitignore b/Kuhnya/.gitignore new file mode 100644 index 0000000..89cc49c --- /dev/null +++ b/Kuhnya/.gitignore @@ -0,0 +1,5 @@ +.pio +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch diff --git a/Kuhnya/.travis.yml b/Kuhnya/.travis.yml new file mode 100644 index 0000000..a8bbc57 --- /dev/null +++ b/Kuhnya/.travis.yml @@ -0,0 +1,67 @@ +# Continuous Integration (CI) is the practice, in software +# engineering, of merging all developer working copies with a shared mainline +# several times a day < https://docs.platformio.org/page/ci/index.html > +# +# Documentation: +# +# * Travis CI Embedded Builds with PlatformIO +# < https://docs.travis-ci.com/user/integration/platformio/ > +# +# * PlatformIO integration with Travis CI +# < https://docs.platformio.org/page/ci/travis.html > +# +# * User Guide for `platformio ci` command +# < https://docs.platformio.org/page/userguide/cmd_ci.html > +# +# +# Please choose one of the following templates (proposed below) and uncomment +# it (remove "# " before each line) or use own configuration according to the +# Travis CI documentation (see above). +# + + +# +# Template #1: General project. Test it using existing `platformio.ini`. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# install: +# - pip install -U platformio +# - platformio update +# +# script: +# - platformio run + + +# +# Template #2: The project is intended to be used as a library with examples. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# env: +# - PLATFORMIO_CI_SRC=path/to/test/file.c +# - PLATFORMIO_CI_SRC=examples/file.ino +# - PLATFORMIO_CI_SRC=path/to/test/directory +# +# install: +# - pip install -U platformio +# - platformio update +# +# script: +# - platformio ci --lib="." --board=ID_1 --board=ID_2 --board=ID_N diff --git a/Kuhnya/.vscode/extensions.json b/Kuhnya/.vscode/extensions.json new file mode 100644 index 0000000..0f0d740 --- /dev/null +++ b/Kuhnya/.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/Kuhnya/include/README b/Kuhnya/include/README new file mode 100644 index 0000000..45496b1 --- /dev/null +++ b/Kuhnya/include/README @@ -0,0 +1,39 @@ + +This directory is intended for project header files. + +A header file is a file containing C declarations and macro definitions +to be shared between several project source files. You request the use of a +header file in your project source file (C, C++, etc) located in `src` folder +by including it, with the C preprocessing directive `#include'. + +```src/main.c + +#include "header.h" + +int main (void) +{ + ... +} +``` + +Including a header file produces the same results as copying the header file +into each source file that needs it. Such copying would be time-consuming +and error-prone. With a header file, the related declarations appear +in only one place. If they need to be changed, they can be changed in one +place, and programs that include the header file will automatically use the +new version when next recompiled. The header file eliminates the labor of +finding and changing all the copies as well as the risk that a failure to +find one copy will result in inconsistencies within a program. + +In C, the usual convention is to give header files names that end with `.h'. +It is most portable to use only letters, digits, dashes, and underscores in +header file names, and at most one dot. + +Read more about using header files in official GCC documentation: + +* Include Syntax +* Include Operation +* Once-Only Headers +* Computed Includes + +https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html diff --git a/Kuhnya/include/main.h b/Kuhnya/include/main.h new file mode 100644 index 0000000..2a0393a --- /dev/null +++ b/Kuhnya/include/main.h @@ -0,0 +1,80 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +//#include +#include +#include +#include + +//#include + +DeviceAddress da[4] = { + {0x28, 0xFF, 0x75, 0x3f, 0x93, 0x16, 0x04, 0xce}, + {0x28, 0x85, 0xcd, 0x1b, 0x05, 0x00, 0x00, 0x48}, + {0x28, 0xff, 0x79, 0x41, 0x88, 0x16, 0x03, 0x5a}, + {0x28, 0x20, 0xbe, 0x1b, 0x05, 0x00, 0x00, 0xdc} +}; + +uint16_t stat[4]; + +#define MOVE_S D0 +#define GREEN D3 +#define BLUE D6 +#define LED_OUT D5 +#define ONE_WIRE D4 +#define BUTTON D7 +#define RED D8 + +const char* ssid = "wf-home"; +const char* password = "0ndthnrf"; +const char* mqtt_server = "192.168.1.250"; + +unsigned long crun; +//sensors_event_t temp_event, pressure_event, humidity_event; +float tempIn(NAN), tempOut(NAN), press(NAN), hum(NAN), tempHol(NAN), tempMor(NAN), tempHoM(NAN); +int lightSP, lightDB, adc; +char strFVal[11]; +int16_t minCount; +byte LCDpage; +bool lightOn; +//bool bmeread; +byte nSens = 0; +uint16_t mv, prMV; + +AsyncMqttClient mqttClient; +Ticker mqttReconnectTimer; + +WiFiEventHandler wifiConnectHandler; +WiFiEventHandler wifiDisconnectHandler; +Ticker wifiReconnectTimer; + +struct stData +{ + int SP; + int DB; +} lightData; + + +void showLCD(int page, bool mv); +void callback(char* topic, byte* message, unsigned int length); +void publishSec(); +void publishMin(); +//void reconnect(); +void getTemp(); + +void connectToWifi(); +void connectToMqtt(); +void onWifiConnect(const WiFiEventStationModeGotIP& event); +void onWifiDisconnect(const WiFiEventStationModeDisconnected& event); +void onMqttConnect(bool sessionPresent); +void onMqttDisconnect(AsyncMqttClientDisconnectReason reason); +void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total); diff --git a/Kuhnya/lib/README b/Kuhnya/lib/README new file mode 100644 index 0000000..8c9c29c --- /dev/null +++ b/Kuhnya/lib/README @@ -0,0 +1,46 @@ + +This directory is intended for project specific (private) libraries. +PlatformIO will compile them to static libraries and link into executable file. + +The source code of each library should be placed in a an own separate directory +("lib/your_library_name/[here are source files]"). + +For example, see a structure of the following two libraries `Foo` and `Bar`: + +|--lib +| | +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html +| | +| |--Foo +| | |- Foo.c +| | |- Foo.h +| | +| |- README --> THIS FILE +| +|- platformio.ini +|--src + |- main.c + +and a contents of `src/main.c`: +``` +#include +#include + +int main (void) +{ + ... +} + +``` + +PlatformIO Library Dependency Finder will find automatically dependent +libraries scanning project source files. + +More information about PlatformIO Library Dependency Finder +- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/Kuhnya/platformio.ini b/Kuhnya/platformio.ini new file mode 100644 index 0000000..aed8938 --- /dev/null +++ b/Kuhnya/platformio.ini @@ -0,0 +1,22 @@ +; PlatformIO Project Configuration File +; +; Build options: build flags, source filter +; Upload options: custom upload port, speed and extra flags +; Library options: dependencies, extra library storages +; Advanced options: extra scripting +; +; Please visit documentation for the other options and examples +; https://docs.platformio.org/page/projectconf.html + +[env:esp12e] +platform = espressif8266 +board = nodemcuv2 +framework = arduino +upload_protocol = espota +upload_port = 192.168.1.8 +lib_deps = + BME280 @ ^3.0.0 + milesburton/DallasTemperature @ ^3.9.1 + Bounce2 @ ^2.55 + LiquidCrystal_PCF8574 @ ^1.2.0 + AsyncMqttClient @ ^0.8.2 diff --git a/Kuhnya/src/main.cpp b/Kuhnya/src/main.cpp new file mode 100644 index 0000000..d90d763 --- /dev/null +++ b/Kuhnya/src/main.cpp @@ -0,0 +1,525 @@ +#include "main.h" + +OneWire oneWire(ONE_WIRE); +DallasTemperature sensors(&oneWire); +BME280I2C bme; +BME280::TempUnit tempUnit(BME280::TempUnit_Celsius); +BME280::PresUnit presUnit(BME280::PresUnit_Pa); + + +LiquidCrystal_PCF8574 lcd(0x3F); // set the LCD address to 0x27 for a 16 chars and 2 line display + +//Adafruit_BME280 bme280; // use I2C interface +//Adafruit_Sensor *bme_temp = bme280.getTemperatureSensor(); +//Adafruit_Sensor *bme_pressure = bme280.getPressureSensor(); +//Adafruit_Sensor *bme_humidity = bme280.getHumiditySensor(); + + + +WiFiClient espClient; +//PubSubClient client(espClient); + +Bounce butt = Bounce(); + +float tempC; +char f[4]; + +void setup() { + //Serial.begin(9600); + //Serial.println("Booting"); // "Загрузка" + + pinMode(RED, OUTPUT); + pinMode(GREEN, OUTPUT); + pinMode(BLUE, OUTPUT); + pinMode(LED_OUT, OUTPUT); + digitalWrite(LED_OUT, LOW); + pinMode(MOVE_S, INPUT); + pinMode(BUTTON, INPUT_PULLUP); + butt.attach(BUTTON); + butt.interval(5); // interval in ms + + Wire.begin(); + Wire.beginTransmission(0x3F); + int error = Wire.endTransmission(); + //Serial.print("Error: "); + //Serial.print(error); + + if (error == 0) { + //Serial.println(": LCD found."); + lcd.begin(16, 2); // initialize the lcd + lcd.clear(); + lcd.setBacklight(255); + } else { + //Serial.println(": LCD not found."); + } // if + lcd.setCursor(0, 0); + lcd.print("Booting"); + + WiFi.mode(WIFI_STA); + WiFi.hostname("ESP-Kuh"); +//----------------------------------------------------------------------- + // WiFi.begin(ssid, password); + // while (WiFi.waitForConnectResult() != WL_CONNECTED) { + // //Serial.println("Connection Failed! Rebooting..."); + // // "Соединиться не удалось! Перезагрузка..." + // delay(5000); + // ESP.restart(); + // } + // lcd.setCursor(0, 0); + // lcd.print("Connected"); +//----------------------------------------------------------------------- + + ArduinoOTA.onStart([]() { /*Serial.println("Start");*/}); // "Начало OTA-апдейта" + ArduinoOTA.onEnd([]() { /*Serial.println("\nEnd");*/}); // "Завершение OTA-апдейта" + ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { /*Serial.printf("Progress: %u%%\r", (progress / (total / 100)));*/ }); + ArduinoOTA.onError([](ota_error_t error) { + /*Serial.printf("Error[%u]: ", error); + if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); // "Ошибка при аутентификации" + else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); // "Ошибка при начале OTA-апдейта" + else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); // "Ошибка при подключении" + else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); // "Ошибка при получении данных" + else if (error == OTA_END_ERROR) Serial.println("End Failed"); // "Ошибка при завершении OTA-апдейта"*/ + }); + ArduinoOTA.begin(); + + //Serial.println("Ready"); // "Готово" + //Serial.print("IP address: "); // "IP-адрес: " + //Serial.println(WiFi.localIP()); + + bme.begin(); + + sensors.begin(); + sensors.setResolution(12); + sensors.requestTemperatures(); + lcd.setCursor(0, 0); + lcd.print("Measure temps..."); + delay(1000); + lcd.setCursor(0, 0); + lcd.print("Measure done... "); + //tempOut = sensors.getTempCByIndex(0); + tempOut = sensors.getTempC(da[0]); + if (tempOut == DEVICE_DISCONNECTED_C){ + tempOut = NAN; + stat[0] = 0; + } + else stat[0] = 1; + //delay(100); + //tempHol = sensors.getTempCByIndex(1); + tempHol = sensors.getTempC(da[1]); + if (tempHol == DEVICE_DISCONNECTED_C){ + tempHol = NAN; + stat[1] = 0; + } + else stat[1] = 1; + //delay(100); + //tempHoM = sensors.getTempCByIndex(2); + tempHoM = sensors.getTempC(da[2]); + if (tempHoM == DEVICE_DISCONNECTED_C){ + tempHoM = NAN; + stat[2] = 0; + } + else stat[2] = 1; + //delay(100); + //tempMor = sensors.getTempCByIndex(3); + tempMor = sensors.getTempC(da[3]); + if (tempMor == DEVICE_DISCONNECTED_C){ + tempMor = NAN; + stat[3] = 0; + } + else stat[3] = 1; + + //client.setServer(mqtt_server, 1883); + //client.setCallback(callback); + + EEPROM.begin(64); + EEPROM.get(0, lightData); + + lightSP = lightData.SP; + lightDB = lightData.DB; + /*lightData.DB = 20; + lightData.SP = 100; + EEPROM.put(0, lightData); + EEPROM.commit();*/ + + minCount = 0; + LCDpage = 0; + lightOn = false; + mv = prMV = digitalRead(MOVE_S); +//----------------------------------------------------------------------- + // if (!client.connected()) { + // reconnect(); + // } + // if (client.connected()) + // client.publish("/home/kuh/move", String(mv).c_str()); +//----------------------------------------------------------------------- + wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect); + wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnect); + + mqttClient.onConnect(onMqttConnect); + mqttClient.onDisconnect(onMqttDisconnect); + mqttClient.onMessage(onMqttMessage); + mqttClient.setServer(mqtt_server, 1883); + mqttClient.setClientId("ESPKuh"); + + connectToWifi(); +//----------------------------------------------------------------------- + + crun = millis(); +// bmeread = true; +} + +void loop() { + float tempT(NAN), humT(NAN), pressT(NAN); + + ArduinoOTA.handle(); + + butt.update(); + if (butt.rose()){ + LCDpage++; + if(LCDpage > 3) LCDpage = 0; + showLCD(LCDpage, mv); + } + if((crun + 199) < millis()){ + crun = millis(); + adc = analogRead(A0); + mv = digitalRead(MOVE_S); + if(mv != prMV){ + if(mv){ + //mv = true; + lcd.setBacklight(255); + mqttClient.publish("/home/kuh/move", 1, false, "1"); +//----------------------------------------------------------------------- + // if (client.connected()) + // client.publish("/home/kuh/move", String(mv).c_str()); +//----------------------------------------------------------------------- + } + else{ + //mv = false; + lcd.setBacklight(0); + mqttClient.publish("/home/kuh/move", 1, false, "0"); +//----------------------------------------------------------------------- + // if (client.connected()) + // client.publish("/home/kuh/move", String(mv).c_str()); +//----------------------------------------------------------------------- + } + prMV = mv; + } + if((adc > (lightSP + lightDB)) || (mv == false)){ + digitalWrite(LED_OUT, LOW); + lightOn = false; + } + if((mv == true) && (adc < lightSP)){ + digitalWrite(LED_OUT, HIGH); + lightOn = true; + } + + //if(((minCount+5) % 10) == 0){ //Once in Second + bme.read(pressT, tempT, humT, tempUnit, presUnit); + if(!isnan(pressT)){ + if(!isnan(press)) press += (pressT / 133.322f - press) / 600.0f; + else press = pressT / 133.322f; + } + if(!isnan(tempT)){ + if(!isnan(tempIn)) tempIn += (tempT - tempIn) / 300.0f; + else tempIn = tempT; + } + if(!isnan(humT)){ + if(!isnan(hum)) hum += (humT - hum) / 300.0f; + else hum = humT; + } + //} + minCount++; + if (minCount == 300){ //Once in Minute + lcd.begin(16, 2); + publishMin(); + minCount = 0; + } + if((minCount % 5) == 0){ //Once in Second + getTemp(); + publishSec(); + showLCD(LCDpage, mv); + } + } +} + +void showLCD(int page, bool l_on) +{ + //char s[5]; + char outS[20]; + //String s1, s2; + /*if(l_on) lcd.setBacklight(255); + else lcd.setBacklight(0);*/ + switch (page) + { + case 0: + //s1 = String(tempOut, 1); + //s2 = String(tempIn, 1); + + lcd.setCursor(0, 0); + //snprintf(outS, 17, "O:%5sC I:%4sC ", s1.c_str(), s2.c_str()); + lcd.printf("O:%5.1fC I:%4.1fC ", tempOut, tempIn); + lcd.setCursor(0, 1); + //s1 = String(hum, 1); + //s2 = String(press, 0); + //snprintf(outS, 17, "H:%4s%% Pr:%3smm", s1.c_str(), s2.c_str()); + lcd.printf("H:%4.1f%% Pr:%3.0fmm", hum, press); + break; + case 1: + //s1 = String(tempHol, 1); + //s2 = String(tempHoM, 1); + lcd.setCursor(0, 0); + //snprintf(outS, 17, "H:%4sC M:%5sC ", s1.c_str(), s2.c_str()); + lcd.printf("H:%4.1fC M:%5.1fC ", tempHol, tempHoM); + //s1 = String(tempMor, 1); + lcd.setCursor(0, 1); + //snprintf(outS, 17, "Mor:%5sC ", s1.c_str()); + lcd.printf("Mor:%5.1fC ", tempMor); + break; + case 2: + lcd.setCursor(0, 0); + //snprintf(outS, 17, "L: %3d SP: %3d ", adc, lightSP); + lcd.printf("L: %3d SP: %3d ", adc, lightSP); + lcd.print(outS); + lcd.setCursor(0, 1); + //snprintf(outS, 17, "DB: %2d MS: %1d L:%1d", lightDB, mv, lightOn); + lcd.printf("DB: %2u MS: %1u L:%1d", lightDB, mv, lightOn); + break; + case 3: + lcd.setCursor(0, 0); + lcd.printf("T1:%d T2:%d %d", stat[0], stat[1], nSens); + lcd.setCursor(0, 1); + lcd.printf("T3:%d T4:%d %3d", stat[2], stat[3], WiFi.RSSI()); + break; + default: + break; + } +} + +// void callback(char* topic, byte* message, unsigned int length) { +// bool w = false; +// //Serial.print("Message arrived on topic: "); +// // "Сообщение прибыло в топик: " +// //Serial.print(topic); +// //Serial.print(". Message: "); // ". Сообщение: " +// String messageTemp; + +// for (unsigned int i = 0; i < length; i++) { +// //Serial.print((char)message[i]); +// messageTemp += (char)message[i]; +// } +// if(strcmp(topic, "/home/kuh/light_sp_set") == 0){ +// lightSP = messageTemp.toInt(); +// w = true; +// } +// if(strcmp(topic, "/home/kuh/light_db_set") == 0){ +// lightDB = messageTemp.toInt(); +// w = true; +// } +// if(w){ +// lightData.SP = lightSP; +// lightData.DB = lightDB; +// EEPROM.put(0, lightData); +// EEPROM.commit(); +// } +// Serial.println(); +// } + +void publishSec() +{ + // if (!client.connected()) { + // reconnect(); + // } + // if(!client.loop()) + // client.connect("ESPKuh"); + // if (client.connected()) { + digitalWrite(GREEN, HIGH); + dtostrf(tempOut, 6, 1, strFVal); + mqttClient.publish("/hometest/kuh1s/temp_out", 1, false, strFVal); + dtostrf(tempIn, 6, 1, strFVal); + mqttClient.publish("/hometest/kuh1s/temp_in", 1, false, strFVal); + dtostrf(hum, 6, 1, strFVal); + mqttClient.publish("/hometest/kuh1s/humidity", 1, false, strFVal); + dtostrf(press, 6, 1, strFVal); + mqttClient.publish("/hometest/kuh1s/pressure", 1, false, strFVal); + itoa(adc, strFVal, 10); + mqttClient.publish("/hometest/kuh1s/light_cur", 1, false, strFVal); + dtostrf(tempHol, 6, 1, strFVal); + mqttClient.publish("/hometest/kuh1s/hol_top", 1, false, strFVal); + dtostrf(tempHoM, 6, 1, strFVal); + mqttClient.publish("/hometest/kuh1s/hol_down", 1, false, strFVal); + dtostrf(tempMor, 6, 1, strFVal); + mqttClient.publish("/hometest/kuh1s/moroz", 1, false, strFVal); + itoa(crun, strFVal, 10); + mqttClient.publish("/hometest/kuh1s/millis", 1, false, strFVal); + digitalWrite(GREEN, LOW); + //} +} + +void publishMin() +{ + // if (!client.connected()) { + // reconnect(); + // } + // if(!client.loop()) + // client.connect("ESPKuh"); + // if (client.connected()) { + digitalWrite(BLUE, HIGH); + if(!isnan(tempOut)){ + dtostrf(tempOut, 6, 1, strFVal); + mqttClient.publish("/home/kuh/temp_out", 1, false, strFVal); + } + if(!isnan(tempIn)){ + dtostrf(tempIn, 6, 1, strFVal); + mqttClient.publish("/home/kuh/temp_in", 1, false, strFVal); + } + if(!isnan(hum)){ + dtostrf(hum, 6, 1, strFVal); + mqttClient.publish("/home/kuh/humidity", 1, false, strFVal); + } + if(!isnan(press)){ + dtostrf(press, 6, 1, strFVal); + mqttClient.publish("/home/kuh/pressure", 1, false, strFVal); + } + itoa(lightSP, strFVal, 10); + mqttClient.publish("/home/kuh/light_sp", 1, false, strFVal); + itoa(lightDB, strFVal, 10); + mqttClient.publish("/home/kuh/light_db", 1, false, strFVal); + itoa(adc, strFVal, 10); + mqttClient.publish("/home/kuh/light_cur", 1, false, strFVal); + if(!isnan(tempHol)){ + dtostrf(tempHol, 6, 1, strFVal); + mqttClient.publish("/home/kuh/hol_top", 1, false, strFVal); + } + if(!isnan(tempHoM)){ + dtostrf(tempHoM, 6, 1, strFVal); + mqttClient.publish("/home/kuh/hol_down", 1, false, strFVal); + } + if(!isnan(tempMor)){ + dtostrf(tempMor, 6, 1, strFVal); + mqttClient.publish("/home/kuh/moroz", 1, false, strFVal); + } + ultoa(crun, strFVal, 10); + mqttClient.publish("/home/kuh/millis", 1, false, strFVal); +// digitalWrite(BLUE, LOW); +// } +} + +// void reconnect() { +// digitalWrite(RED, HIGH); +// //Serial.print("Attempting MQTT connection..."); +// // "Попытка подключиться к MQTT-брокеру... " +// // Пытаемся подключиться: +// if (client.connect("ESPKuh")) { +// //Serial.println("connected"); // "подключен" +// // подписываемся или переподписываемся на топик; +// // можно подписаться не только на один, а на несколько топиков +// client.subscribe("/home/kuh/light_sp_set"); +// client.subscribe("/home/kuh/light_db_set"); +// client.publish("/home/kuh/light_db_set", String(lightData.DB).c_str()); +// client.publish("/home/kuh/light_sb_set", String(lightData.SP).c_str()); +// } else { +// //Serial.print("failed, rc="); // "подключение не удалось" +// //Serial.print(client.state()); +// //Serial.println(" try again in 5 seconds"); +// } +// delay(100); +// digitalWrite(RED, LOW); +// } + +void getTemp() +{ + static bool readTemp = false; + if (readTemp){ + sensors.setWaitForConversion(false); + sensors.requestTemperatures(); + readTemp = !readTemp; + } + else{ + float t = sensors.getTempC(da[nSens]);//ByIndex(nSens); + //float t = sensors.getTempCByIndex(nSens); + //Serial.print(nSens); + //Serial.print(" Temp readed="); + //Serial.println(t); + if ((t > -127) && (t < 85)){ + stat[nSens] = 1; + switch(nSens){ + case 0: + if (!isnan(tempOut)) tempOut += (t - tempOut) / 240.0f; + else tempOut = t; + break; + case 1: + if (!isnan(tempHol)) tempHol += (t - tempHol) * 0.05f; + else tempHol = t; + break; + case 2: + if (!isnan(tempHoM)) tempHoM += (t - tempHoM) * 0.05f; + else tempHoM = t; + break; + case 3: + if (!isnan(tempMor)) tempMor += (t - tempMor) * 0.05f; + else tempMor = t; + break; + } + } + else stat[nSens] = 0; + if (++nSens > 3){ + nSens = 0; + readTemp = !readTemp; + } + } + //n++; +} + +void connectToWifi() { + WiFi.begin(ssid, password); +} + +void connectToMqtt() { + mqttClient.connect(); +} + +void onWifiConnect(const WiFiEventStationModeGotIP& event) { + connectToMqtt(); +} + +void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) { + mqttReconnectTimer.detach(); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi + wifiReconnectTimer.once(2, connectToWifi); +} + +void onMqttConnect(bool sessionPresent) { + char v[6]; + itoa(lightData.SP, v, 10); + mqttClient.publish("/home/kuh/light_sp_set", 1, false, v); + itoa(lightData.DB, v, 10); + mqttClient.publish("/home/kuh/light_db_set", 1, false, v); + mqttClient.publish("/home/kuh/move", 1, false, mv == 1 ? "1" : "0"); + mqttClient.subscribe("/home/kuh/light_sp_set", 1); + mqttClient.subscribe("/home/kuh/light_db_set", 1); + digitalWrite(BLUE, LOW); +} + +void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) { + if (WiFi.isConnected()) { + mqttReconnectTimer.once(2, connectToMqtt); + } + digitalWrite(BLUE, HIGH); +} + +void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) { + bool w = false; + if(strcmp(topic, "/home/kuh/light_sp_set") == 0){ + lightSP = atoi(payload); + w = true; + } + if(strcmp(topic, "/home/kuh/light_db_set") == 0){ + lightDB = atoi(payload); + w = true; + } + if(w){ + lightData.SP = lightSP; + lightData.DB = lightDB; + EEPROM.put(0, lightData); + EEPROM.commit(); + } +} diff --git a/Kuhnya/test/README b/Kuhnya/test/README new file mode 100644 index 0000000..c3b0ed6 --- /dev/null +++ b/Kuhnya/test/README @@ -0,0 +1,11 @@ + +This directory is intended for PIO Unit Testing and project tests. + +Unit Testing is a software testing method by which individual units of +source code, sets of one or more MCU program modules together with associated +control data, usage procedures, and operating procedures, are tested to +determine whether they are fit for use. Unit testing finds problems early +in the development cycle. + +More information about PIO Unit Testing: +- https://docs.platformio.org/page/plus/unit-testing.html diff --git a/MYS_Home.code-workspace b/MYS_Home.code-workspace index 391558a..1229dbf 100644 --- a/MYS_Home.code-workspace +++ b/MYS_Home.code-workspace @@ -7,10 +7,6 @@ "name": "I2C Scan", "path": "I2C Scan" }, - { - "name": "ESP12", - "path": "D:\\Projects\\Arduino\\ESP12" - }, { "name": "VT_ESP8266", "path": "VT_ESP8266" @@ -66,6 +62,9 @@ { "name": "KorMYS", "path": "KorMYS" + }, + { + "path": "Kuhnya" } ], "settings": {