From d8ff2646a2c214f420c8fdc48dd690329d0b040b Mon Sep 17 00:00:00 2001 From: lexa Date: Fri, 28 Aug 2020 17:57:26 +0300 Subject: [PATCH] Init curt midroom --- Curt_MidRoom/.gitignore | 5 + Curt_MidRoom/.travis.yml | 67 +++++++ Curt_MidRoom/.vscode/extensions.json | 7 + Curt_MidRoom/include/README | 39 ++++ Curt_MidRoom/lib/README | 46 +++++ Curt_MidRoom/platformio.ini | 14 ++ Curt_MidRoom/src/main.cpp | 256 +++++++++++++++++++++++++++ Curt_MidRoom/test/README | 11 ++ MYS_Home.code-workspace | 4 + 9 files changed, 449 insertions(+) create mode 100644 Curt_MidRoom/.gitignore create mode 100644 Curt_MidRoom/.travis.yml create mode 100644 Curt_MidRoom/.vscode/extensions.json create mode 100644 Curt_MidRoom/include/README create mode 100644 Curt_MidRoom/lib/README create mode 100644 Curt_MidRoom/platformio.ini create mode 100644 Curt_MidRoom/src/main.cpp create mode 100644 Curt_MidRoom/test/README diff --git a/Curt_MidRoom/.gitignore b/Curt_MidRoom/.gitignore new file mode 100644 index 0000000..89cc49c --- /dev/null +++ b/Curt_MidRoom/.gitignore @@ -0,0 +1,5 @@ +.pio +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch diff --git a/Curt_MidRoom/.travis.yml b/Curt_MidRoom/.travis.yml new file mode 100644 index 0000000..a8bbc57 --- /dev/null +++ b/Curt_MidRoom/.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/Curt_MidRoom/.vscode/extensions.json b/Curt_MidRoom/.vscode/extensions.json new file mode 100644 index 0000000..0f0d740 --- /dev/null +++ b/Curt_MidRoom/.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/Curt_MidRoom/include/README b/Curt_MidRoom/include/README new file mode 100644 index 0000000..45496b1 --- /dev/null +++ b/Curt_MidRoom/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/Curt_MidRoom/lib/README b/Curt_MidRoom/lib/README new file mode 100644 index 0000000..8c9c29c --- /dev/null +++ b/Curt_MidRoom/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/Curt_MidRoom/platformio.ini b/Curt_MidRoom/platformio.ini new file mode 100644 index 0000000..d8a9f8a --- /dev/null +++ b/Curt_MidRoom/platformio.ini @@ -0,0 +1,14 @@ +; 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 = esp12e +framework = arduino diff --git a/Curt_MidRoom/src/main.cpp b/Curt_MidRoom/src/main.cpp new file mode 100644 index 0000000..c4ada57 --- /dev/null +++ b/Curt_MidRoom/src/main.cpp @@ -0,0 +1,256 @@ +#include +#include +#include +#include + +#define LED_WF (14) +#define LED_MQ (12) +#define LED_WRK (13) + +#define TUYA_OPEN "55aa000600056604000100" +#define TUYA_CLOSE "55aa000600056604000101" +#define TUYA_STOP "55aa000600056604000102" +// set position percentage +#define TUYA_SET_POSITION "55aa0006000865020004000000" // and 1 byte (0x00-0x64) + +// enable/disable reversed motor direction +#define TUYA_DISABLE_REVERSING "55aa000600056700000100" +#define TUYA_ENABLE_REVERSING "55aa000600056700000101" +#define CURT_CLOSING (1) +#define CURT_OPENING (2) +#define CURT_IDLE (0) + +const char* ssid = "wf-home"; +const char* password = "0ndthnrf"; +const char* mqtt_server = "192.168.1.250"; +unsigned long cRun = millis(); +double curr; +int nSec, nSampl; +uint8_t buffer[1024]; +bool reversed, curtOpened, curtClosed; +float position; +uint8_t offset; +uint8_t cur_operation; +uint8_t crc; + +AsyncMqttClient mqttClient; +Ticker mqttReconnectTimer; + +WiFiEventHandler wifiConnectHandler; +WiFiEventHandler wifiDisconnectHandler; +Ticker wifiReconnectTimer; + +void connectToWifi(); +void connectToMqtt(); +void onWifiConnect(const WiFiEventStationModeGotIP& event); +void onWifiDisconnect(const WiFiEventStationModeDisconnected& event); +void onMqttConnect(bool sessionPresent); +void onMqttDisconnect(AsyncMqttClientDisconnectReason reason); +void onMqttSubscribe(uint16_t packetId, uint8_t qos); +void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total); + +void setup(){ + Serial.begin(9600); + WiFi.mode(WIFI_STA); + WiFi.hostname("Cur-MidRoom"); + Serial.begin(9600); + + ArduinoOTA.onStart([]() { + Serial1.println("Start Update"); // "Начало OTA-апдейта" + }); + ArduinoOTA.onEnd([]() { + Serial1.println("\nEnd Update"); // "Завершение OTA-апдейта" + }); + ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { + //Serial1.printf("Progress: %u%%\r", (progress / (total / 100))); + }); + ArduinoOTA.onError([](ota_error_t error) { + Serial1.printf("Error[%u]: ", error); + if (error == OTA_AUTH_ERROR) Serial1.println("Auth Failed"); + // "Ошибка при аутентификации" + else if (error == OTA_BEGIN_ERROR) Serial1.println("Begin Failed"); + // "Ошибка при начале OTA-апдейта" + else if (error == OTA_CONNECT_ERROR) Serial1.println("Connect Failed"); + // "Ошибка при подключении" + else if (error == OTA_RECEIVE_ERROR) Serial1.println("Receive Failed"); + // "Ошибка при получении данных" + else if (error == OTA_END_ERROR) Serial1.println("End Failed"); + // "Ошибка при завершении OTA-апдейта" + }); + ArduinoOTA.begin(); + wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect); + wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnect); + + mqttClient.onConnect(onMqttConnect); + mqttClient.onDisconnect(onMqttDisconnect); + mqttClient.onSubscribe(onMqttSubscribe); + mqttClient.onMessage(onMqttMessage); + mqttClient.setServer(mqtt_server, 1883); + mqttClient.setClientId("Cur_MidRoom"); + + pinMode(LED_WF, OUTPUT); + pinMode(LED_MQ, OUTPUT); + pinMode(LED_WRK, OUTPUT); + //pinMode(5, INPUT_PULLUP); + digitalWrite(LED_WF, LOW); + digitalWrite(LED_MQ, LOW); + digitalWrite(LED_WRK, LOW); + connectToWifi(); + nSec = 0; + curr = -1; + nSampl = 0; +} + +void loop(){ + static bool led_wrk = false; + + ArduinoOTA.handle(); + crc = 0; + offset = 0; + while(Serial.available()){ + readByte(Serial.read()); + } + if(cRun + 999 < millis()){ + cRun = millis(); + if(WiFi.isConnected()){ + led_wrk = !led_wrk; + digitalWrite(LED_WRK, led_wrk); + nSampl++; + } + } +} + +void connectToWifi() { + Serial.println("Connecting to Wi-Fi..."); + WiFi.begin(ssid, password); +} + +void connectToMqtt() { + Serial.println("Connecting to MQTT..."); + mqttClient.connect(); +} + +void onWifiConnect(const WiFiEventStationModeGotIP& event) { + Serial.println("Connected to Wi-Fi."); + Serial.print("IP: "); + Serial.println(WiFi.localIP()); + connectToMqtt(); + digitalWrite(LED_WF, HIGH); +} + +void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) { + Serial.println("Disconnected from Wi-Fi."); + mqttReconnectTimer.detach(); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi + wifiReconnectTimer.once(2, connectToWifi); + digitalWrite(LED_WF, LOW); +} + +void onMqttConnect(bool sessionPresent) { + Serial.println("Connected to MQTT."); + Serial.print("Session present: "); + Serial.println(sessionPresent); + mqttClient.subscribe("/home/midroom/curtpos_set", 0); + digitalWrite(LED_MQ, HIGH); +} + +void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) { + //Serial.println("Disconnected from MQTT."); + + if (WiFi.isConnected()) { + mqttReconnectTimer.once(2, connectToMqtt); + } + digitalWrite(LED_MQ, LOW); +} + +void onMqttSubscribe(uint16_t packetId, uint8_t qos) { + Serial.println("Subscribe acknowledged."); + Serial.print(" packetId: "); + Serial.println(packetId); + Serial.print(" qos: "); + Serial.println(qos); +} + +void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) { + if(strcmp("/home/midroom/curtpos_set", topic) == 0){ + + } +} + +void readByte(uint8_t data) { + if ((offset == 0 && data == 0x55) || (offset == 1 && data == 0xAA) || offset) { + buffer[offset++] = data; + if (offset > 6) { + int len = buffer[4] << 8 | buffer[5]; + if (7 + len == offset) { + uint8_t crc = buffer[offset - 1]; + uint8_t sum = 0; + for (int i = 0; i < offset - 1; i++) sum += buffer[i]; + if (sum == crc) { + uint8_t cmd_type = buffer[3]; + uint8_t data_id = buffer[6]; + uint8_t data_size = buffer[9]; // only 1byte or 4bytes values + switch (cmd_type) { + case 0x07: { + switch (data_id) { + // Motor reversing state + case 0x67: { + reversed = !!buffer[10]; + break; + } + // Operation mode state + case 0x66: { + switch (buffer[10]) { + case 0x00: + cur_operation = CURT_CLOSING; + break; + case 0x02: + cur_operation = CURT_IDLE; + break; + case 0x01: + cur_operation = CURT_OPENING; + break; + } + break; + } + // Position report during operation + // Max value is 0x64 so the last byte is good enough + case 0x68: { + position = buffer[13] / 100.0f; + curtOpened = !!position; + break; + } + // Position report after operation + case 0x65: { + position = 1 - (buffer[13] / 100.0f); + if (position > 0.95) position = 1; + if (position < 0.05) position = 0; + curtOpened = !!position; + cur_operation = CURT_IDLE; + break; + } + } + Serial.println(cur_operation); + //publish_state(); + break; + } + } + } + offset = 0; + } + } + } +} + +void writeByte(uint8_t data) { + Serial.write(data); + crc += data; +} + +void writeHex(std::string data) { + int i = 0; + while (i < data.length()) { + const char hex[2] = {data[i++], data[i++]}; + uint8_t d = strtoul(hex, NULL, 16); + writeByte(d); + } +} diff --git a/Curt_MidRoom/test/README b/Curt_MidRoom/test/README new file mode 100644 index 0000000..c3b0ed6 --- /dev/null +++ b/Curt_MidRoom/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 3a7fe78..9121a47 100644 --- a/MYS_Home.code-workspace +++ b/MYS_Home.code-workspace @@ -50,6 +50,10 @@ }, { "path": "ESP_Electro" + }, + { + "name": "Curt_MidRoom", + "path": "Curt_MidRoom" } ], "settings": {