From 6f5800173ce382db3570e6cf9b8af0391059f4fa Mon Sep 17 00:00:00 2001 From: Theo Arends Date: Mon, 30 Apr 2018 17:10:21 +0200 Subject: [PATCH] v5.13.0 Release version 5.13.0 --- .gitignore | 10 +- README.md | 130 +- .../.github/ISSUE_TEMPLATE.md | 0 .../.github/PULL_REQUEST_TEMPLATE.md | 0 lib/Adafruit_SGP30-1.0.0.13/.gitignore | 4 + lib/Adafruit_SGP30-1.0.0.13/.travis.yml | 27 + .../Adafruit_SGP30.cpp | 243 ++++ lib/Adafruit_SGP30-1.0.0.13/Adafruit_SGP30.h | 68 + lib/Adafruit_SGP30-1.0.0.13/README.md | 18 + .../examples/sgp30test/sgp30test.ino | 45 + .../library.properties | 9 + lib/Adafruit_SGP30-1.0.0.13/license.txt | 26 + lib/Joba_Tsl2561/COPYING | 674 +++++++++ lib/Joba_Tsl2561/COPYING.LESSER | 165 +++ lib/Joba_Tsl2561/README | 20 + .../examples/Autogain/Autogain.ino | 65 + lib/Joba_Tsl2561/examples/Simple/Simple.ino | 56 + lib/Joba_Tsl2561/examples/Testing/Testing.ino | 163 +++ lib/Joba_Tsl2561/examples/Utility/Utility.ino | 87 ++ lib/Joba_Tsl2561/library.json | 13 + lib/Joba_Tsl2561/library.properties | 9 + lib/Joba_Tsl2561/src/Tsl2561.cpp | 134 ++ lib/Joba_Tsl2561/src/Tsl2561.h | 133 ++ lib/Joba_Tsl2561/src/Tsl2561Util.cpp | 193 +++ lib/Joba_Tsl2561/src/Tsl2561Util.h | 48 + lib/Mutichannel_Gas_Sensor/License.txt | 21 + lib/Mutichannel_Gas_Sensor/README.md | 45 + .../examples/GetVersion/GetVersion.ino | 20 + .../examples/I2C_Address/I2C_Address.ino | 25 + .../examples/RawData/RawData.ino | 57 + .../ReadSensorValue_Grove.ino | 81 ++ .../ReadSensorValue_Xadow.ino | 89 ++ .../UpdateFrimware/UpdateFrimware.ino | 513 +++++++ .../UpdateFrimware/bootloader_atmega168.h | 1028 ++++++++++++++ .../examples/UpdateFrimware/gpl.txt | 339 +++++ .../examples/calibration/calibration.ino | 35 + .../factory_setting/factory_setting.ino | 36 + .../examples/new_firmware/new_firmware.ino | 272 ++++ lib/Mutichannel_Gas_Sensor/library.json | 14 + lib/Mutichannel_Gas_Sensor/library.properties | 9 + .../src/MutichannelGasSensor.cpp | 729 ++++++++++ .../src/MutichannelGasSensor.h | 140 ++ lib/TSL2561-Arduino-Library/README.txt | 7 - lib/TSL2561-Arduino-Library/TSL2561.cpp | 301 ---- lib/TSL2561-Arduino-Library/TSL2561.h | 184 --- .../examples/tsl2561/tsl2561.ino | 63 - .../library.properties | 9 - lib/TasmotaMqtt-1.1.1/.gitignore | 28 + lib/TasmotaMqtt-1.1.1/README.md | 8 + .../examples/mqtt_pub/mqtt_pub.ino | 102 ++ .../examples/mqtt_sub/mqtt_sub.ino | 97 ++ lib/TasmotaMqtt-1.1.1/keywords.txt | 39 + lib/TasmotaMqtt-1.1.1/library.properties | 9 + lib/TasmotaMqtt-1.1.1/src/TasmotaMqtt.cpp | 194 +++ lib/TasmotaMqtt-1.1.1/src/TasmotaMqtt.h | 88 ++ lib/TasmotaMqtt-1.1.1/src/mqtt/debug.h | 19 + lib/TasmotaMqtt-1.1.1/src/mqtt/mqtt.c | 997 ++++++++++++++ lib/TasmotaMqtt-1.1.1/src/mqtt/mqtt.h | 148 ++ lib/TasmotaMqtt-1.1.1/src/mqtt/mqtt_msg.c | 487 +++++++ lib/TasmotaMqtt-1.1.1/src/mqtt/mqtt_msg.h | 141 ++ lib/TasmotaMqtt-1.1.1/src/mqtt/proto.c | 129 ++ lib/TasmotaMqtt-1.1.1/src/mqtt/proto.h | 32 + lib/TasmotaMqtt-1.1.1/src/mqtt/queue.c | 75 + lib/TasmotaMqtt-1.1.1/src/mqtt/queue.h | 44 + lib/TasmotaMqtt-1.1.1/src/mqtt/ringbuf.c | 67 + lib/TasmotaMqtt-1.1.1/src/mqtt/ringbuf.h | 19 + lib/TasmotaMqtt-1.1.1/src/mqtt/typedef.h | 17 + lib/TasmotaMqtt-1.1.1/src/mqtt/user_config.h | 15 + lib/TasmotaMqtt-1.1.1/src/mqtt/utils.c | 149 ++ lib/TasmotaMqtt-1.1.1/src/mqtt/utils.h | 9 + .../README.md | 2 +- .../examples/swsertest/swsertest.ino | 0 .../keywords.txt | 0 .../library.json | 4 +- .../library.properties | 4 +- .../src/TasmotaSerial.cpp | 31 +- .../src/TasmotaSerial.h | 5 +- lib/esp-knx-ip-0.5.0/DPT.h | 72 + lib/esp-knx-ip-0.5.0/LICENSE | 21 + lib/esp-knx-ip-0.5.0/README.md | 94 ++ lib/esp-knx-ip-0.5.0/esp-knx-ip-config.cpp | 358 +++++ .../esp-knx-ip-conversion.cpp | 87 ++ lib/esp-knx-ip-0.5.0/esp-knx-ip-send.cpp | 182 +++ lib/esp-knx-ip-0.5.0/esp-knx-ip-webserver.cpp | 540 ++++++++ lib/esp-knx-ip-0.5.0/esp-knx-ip.cpp | 659 +++++++++ lib/esp-knx-ip-0.5.0/esp-knx-ip.h | 571 ++++++++ .../environment-sensor/environment-sensor.ino | 159 +++ .../examples/sonoff/sonoff.ino | 183 +++ .../examples/static-config/static-config.ino | 142 ++ lib/esp-knx-ip-0.5.0/keywords.txt | 104 ++ lib/esp-knx-ip-0.5.0/library.properties | 10 + lib/esp-mqtt-arduino-1.0.1.02.1/.gitignore | 28 + lib/esp-mqtt-arduino-1.0.1.02.1/README.md | 15 + .../examples/mqtt_pub/mqtt_pub.ino | 102 ++ .../examples/mqtt_sub/mqtt_sub.ino | 95 ++ lib/esp-mqtt-arduino-1.0.1.02.1/keywords.txt | 43 + .../library.properties | 9 + lib/esp-mqtt-arduino-1.0.1.02.1/src/MQTT.cpp | 269 ++++ lib/esp-mqtt-arduino-1.0.1.02.1/src/MQTT.h | 93 ++ .../src/mqtt/debug.h | 19 + .../src/mqtt/mqtt.c | 1048 ++++++++++++++ .../src/mqtt/mqtt.h | 152 ++ .../src/mqtt/mqtt_config.h | 19 + .../src/mqtt/mqtt_msg.c | 487 +++++++ .../src/mqtt/mqtt_msg.h | 141 ++ .../src/mqtt/proto.c | 129 ++ .../src/mqtt/proto.h | 32 + .../src/mqtt/queue.c | 75 + .../src/mqtt/queue.h | 44 + .../src/mqtt/ringbuf.c | 67 + .../src/mqtt/ringbuf.h | 19 + .../src/mqtt/typedef.h | 17 + .../src/mqtt/utils.c | 149 ++ .../src/mqtt/utils.h | 9 + platformio.ini | 360 +++-- sonoff/_releasenotes.ino | 98 +- sonoff/i18n.h | 105 +- sonoff/language/bg-BG.h | 505 +++++++ sonoff/language/cs-CZ.h | 505 +++++++ sonoff/language/de-DE.h | 152 +- sonoff/language/el-GR.h | 505 +++++++ sonoff/language/en-GB.h | 68 +- sonoff/language/es-AR.h | 68 +- sonoff/language/fr-FR.h | 262 ++-- sonoff/language/hu-HU.h | 505 +++++++ sonoff/language/it-IT.h | 68 +- sonoff/language/nl-NL.h | 70 +- sonoff/language/pl-PL.h | 278 ++-- sonoff/language/pt-PT.h | 505 +++++++ sonoff/language/ru-RU.h | 505 +++++++ sonoff/language/zh-CN.h | 68 +- sonoff/language/zh-TW.h | 505 +++++++ sonoff/settings.h | 82 +- sonoff/settings.ino | 251 ++-- sonoff/sonoff.h | 50 +- sonoff/sonoff.ino | 1220 ++++++----------- sonoff/sonoff_post.h | 232 +++- sonoff/sonoff_template.h | 104 +- sonoff/support.ino | 393 ++++-- sonoff/user_config.h | 247 +++- sonoff/user_config_override.h | 44 - sonoff/user_config_override_sample.h | 96 ++ sonoff/webserver.ino | 328 ++--- sonoff/xdrv_00_mqtt.ino | 768 +++++++++++ sonoff/xdrv_01_light.ino | 92 +- sonoff/xdrv_02_irremote.ino | 19 +- sonoff/xdrv_03_energy.ino | 100 +- sonoff/xdrv_04_snfbridge.ino | 25 +- sonoff/xdrv_05_domoticz.ino | 44 +- sonoff/xdrv_07_home_assistant.ino | 142 +- sonoff/xdrv_08_serial_bridge.ino | 149 ++ sonoff/xdrv_09_timers.ino | 731 ++++++++++ sonoff/xdrv_10_rules.ino | 478 +++++++ sonoff/xdrv_11_knx.ino | 888 ++++++++++++ sonoff/xdrv_interface.ino | 13 +- sonoff/xplg_wemohue.ino | 9 +- sonoff/xplg_ws2812.ino | 86 +- sonoff/xsns_01_counter.ino | 17 +- sonoff/xsns_04_snfsc.ino | 18 +- sonoff/xsns_05_ds18b20.ino | 4 +- sonoff/xsns_05_ds18x20.ino | 30 +- sonoff/xsns_05_ds18x20_legacy.ino | 24 +- sonoff/xsns_06_dht.ino | 10 +- sonoff/xsns_07_sht1x.ino | 10 +- sonoff/xsns_08_htu21.ino | 10 +- sonoff/xsns_09_bmp.ino | 15 +- sonoff/xsns_10_bh1750.ino | 2 +- sonoff/xsns_11_veml6070.ino | 2 +- sonoff/xsns_12_ads1115.ino | 2 +- sonoff/xsns_12_ads1115_i2cdev.ino | 2 +- sonoff/xsns_13_ina219.ino | 6 +- sonoff/xsns_14_sht3x.ino | 89 +- sonoff/xsns_15_mhz19.ino | 5 +- sonoff/xsns_16_tsl2561.ino | 89 +- sonoff/xsns_17_senseair.ino | 5 +- sonoff/xsns_18_pms5003.ino | 9 + sonoff/xsns_19_mgs.ino | 121 ++ sonoff/xsns_20_novasds.ino | 155 +++ sonoff/xsns_21_sgp30.ino | 116 ++ sonoff/xsns_22_sr04.ino | 175 +++ sonoff/xsns_interface.ino | 17 +- 181 files changed, 25419 insertions(+), 2796 deletions(-) rename lib/{TSL2561-Arduino-Library => Adafruit_SGP30-1.0.0.13}/.github/ISSUE_TEMPLATE.md (100%) rename lib/{TSL2561-Arduino-Library => Adafruit_SGP30-1.0.0.13}/.github/PULL_REQUEST_TEMPLATE.md (100%) create mode 100644 lib/Adafruit_SGP30-1.0.0.13/.gitignore create mode 100644 lib/Adafruit_SGP30-1.0.0.13/.travis.yml create mode 100644 lib/Adafruit_SGP30-1.0.0.13/Adafruit_SGP30.cpp create mode 100644 lib/Adafruit_SGP30-1.0.0.13/Adafruit_SGP30.h create mode 100644 lib/Adafruit_SGP30-1.0.0.13/README.md create mode 100644 lib/Adafruit_SGP30-1.0.0.13/examples/sgp30test/sgp30test.ino create mode 100644 lib/Adafruit_SGP30-1.0.0.13/library.properties create mode 100644 lib/Adafruit_SGP30-1.0.0.13/license.txt create mode 100644 lib/Joba_Tsl2561/COPYING create mode 100644 lib/Joba_Tsl2561/COPYING.LESSER create mode 100644 lib/Joba_Tsl2561/README create mode 100644 lib/Joba_Tsl2561/examples/Autogain/Autogain.ino create mode 100644 lib/Joba_Tsl2561/examples/Simple/Simple.ino create mode 100644 lib/Joba_Tsl2561/examples/Testing/Testing.ino create mode 100644 lib/Joba_Tsl2561/examples/Utility/Utility.ino create mode 100644 lib/Joba_Tsl2561/library.json create mode 100644 lib/Joba_Tsl2561/library.properties create mode 100644 lib/Joba_Tsl2561/src/Tsl2561.cpp create mode 100644 lib/Joba_Tsl2561/src/Tsl2561.h create mode 100644 lib/Joba_Tsl2561/src/Tsl2561Util.cpp create mode 100644 lib/Joba_Tsl2561/src/Tsl2561Util.h create mode 100644 lib/Mutichannel_Gas_Sensor/License.txt create mode 100644 lib/Mutichannel_Gas_Sensor/README.md create mode 100644 lib/Mutichannel_Gas_Sensor/examples/GetVersion/GetVersion.ino create mode 100644 lib/Mutichannel_Gas_Sensor/examples/I2C_Address/I2C_Address.ino create mode 100644 lib/Mutichannel_Gas_Sensor/examples/RawData/RawData.ino create mode 100644 lib/Mutichannel_Gas_Sensor/examples/ReadSensorValue_Grove/ReadSensorValue_Grove.ino create mode 100644 lib/Mutichannel_Gas_Sensor/examples/ReadSensorValue_Xadow/ReadSensorValue_Xadow.ino create mode 100644 lib/Mutichannel_Gas_Sensor/examples/UpdateFrimware/UpdateFrimware.ino create mode 100644 lib/Mutichannel_Gas_Sensor/examples/UpdateFrimware/bootloader_atmega168.h create mode 100644 lib/Mutichannel_Gas_Sensor/examples/UpdateFrimware/gpl.txt create mode 100644 lib/Mutichannel_Gas_Sensor/examples/calibration/calibration.ino create mode 100644 lib/Mutichannel_Gas_Sensor/examples/factory_setting/factory_setting.ino create mode 100644 lib/Mutichannel_Gas_Sensor/examples/new_firmware/new_firmware.ino create mode 100644 lib/Mutichannel_Gas_Sensor/library.json create mode 100644 lib/Mutichannel_Gas_Sensor/library.properties create mode 100644 lib/Mutichannel_Gas_Sensor/src/MutichannelGasSensor.cpp create mode 100644 lib/Mutichannel_Gas_Sensor/src/MutichannelGasSensor.h delete mode 100644 lib/TSL2561-Arduino-Library/README.txt delete mode 100644 lib/TSL2561-Arduino-Library/TSL2561.cpp delete mode 100644 lib/TSL2561-Arduino-Library/TSL2561.h delete mode 100644 lib/TSL2561-Arduino-Library/examples/tsl2561/tsl2561.ino delete mode 100644 lib/TSL2561-Arduino-Library/library.properties create mode 100644 lib/TasmotaMqtt-1.1.1/.gitignore create mode 100644 lib/TasmotaMqtt-1.1.1/README.md create mode 100644 lib/TasmotaMqtt-1.1.1/examples/mqtt_pub/mqtt_pub.ino create mode 100644 lib/TasmotaMqtt-1.1.1/examples/mqtt_sub/mqtt_sub.ino create mode 100644 lib/TasmotaMqtt-1.1.1/keywords.txt create mode 100644 lib/TasmotaMqtt-1.1.1/library.properties create mode 100644 lib/TasmotaMqtt-1.1.1/src/TasmotaMqtt.cpp create mode 100644 lib/TasmotaMqtt-1.1.1/src/TasmotaMqtt.h create mode 100644 lib/TasmotaMqtt-1.1.1/src/mqtt/debug.h create mode 100644 lib/TasmotaMqtt-1.1.1/src/mqtt/mqtt.c create mode 100644 lib/TasmotaMqtt-1.1.1/src/mqtt/mqtt.h create mode 100644 lib/TasmotaMqtt-1.1.1/src/mqtt/mqtt_msg.c create mode 100644 lib/TasmotaMqtt-1.1.1/src/mqtt/mqtt_msg.h create mode 100644 lib/TasmotaMqtt-1.1.1/src/mqtt/proto.c create mode 100644 lib/TasmotaMqtt-1.1.1/src/mqtt/proto.h create mode 100644 lib/TasmotaMqtt-1.1.1/src/mqtt/queue.c create mode 100644 lib/TasmotaMqtt-1.1.1/src/mqtt/queue.h create mode 100644 lib/TasmotaMqtt-1.1.1/src/mqtt/ringbuf.c create mode 100644 lib/TasmotaMqtt-1.1.1/src/mqtt/ringbuf.h create mode 100644 lib/TasmotaMqtt-1.1.1/src/mqtt/typedef.h create mode 100644 lib/TasmotaMqtt-1.1.1/src/mqtt/user_config.h create mode 100644 lib/TasmotaMqtt-1.1.1/src/mqtt/utils.c create mode 100644 lib/TasmotaMqtt-1.1.1/src/mqtt/utils.h rename lib/{TasmotaSerial-1.1.0 => TasmotaSerial-1.2.0}/README.md (79%) rename lib/{TasmotaSerial-1.1.0 => TasmotaSerial-1.2.0}/examples/swsertest/swsertest.ino (100%) rename lib/{TasmotaSerial-1.1.0 => TasmotaSerial-1.2.0}/keywords.txt (100%) rename lib/{TasmotaSerial-1.1.0 => TasmotaSerial-1.2.0}/library.json (89%) rename lib/{TasmotaSerial-1.1.0 => TasmotaSerial-1.2.0}/library.properties (64%) rename lib/{TasmotaSerial-1.1.0 => TasmotaSerial-1.2.0}/src/TasmotaSerial.cpp (91%) rename lib/{TasmotaSerial-1.1.0 => TasmotaSerial-1.2.0}/src/TasmotaSerial.h (91%) create mode 100644 lib/esp-knx-ip-0.5.0/DPT.h create mode 100644 lib/esp-knx-ip-0.5.0/LICENSE create mode 100644 lib/esp-knx-ip-0.5.0/README.md create mode 100644 lib/esp-knx-ip-0.5.0/esp-knx-ip-config.cpp create mode 100644 lib/esp-knx-ip-0.5.0/esp-knx-ip-conversion.cpp create mode 100644 lib/esp-knx-ip-0.5.0/esp-knx-ip-send.cpp create mode 100644 lib/esp-knx-ip-0.5.0/esp-knx-ip-webserver.cpp create mode 100644 lib/esp-knx-ip-0.5.0/esp-knx-ip.cpp create mode 100644 lib/esp-knx-ip-0.5.0/esp-knx-ip.h create mode 100644 lib/esp-knx-ip-0.5.0/examples/environment-sensor/environment-sensor.ino create mode 100644 lib/esp-knx-ip-0.5.0/examples/sonoff/sonoff.ino create mode 100644 lib/esp-knx-ip-0.5.0/examples/static-config/static-config.ino create mode 100644 lib/esp-knx-ip-0.5.0/keywords.txt create mode 100644 lib/esp-knx-ip-0.5.0/library.properties create mode 100644 lib/esp-mqtt-arduino-1.0.1.02.1/.gitignore create mode 100644 lib/esp-mqtt-arduino-1.0.1.02.1/README.md create mode 100644 lib/esp-mqtt-arduino-1.0.1.02.1/examples/mqtt_pub/mqtt_pub.ino create mode 100644 lib/esp-mqtt-arduino-1.0.1.02.1/examples/mqtt_sub/mqtt_sub.ino create mode 100644 lib/esp-mqtt-arduino-1.0.1.02.1/keywords.txt create mode 100644 lib/esp-mqtt-arduino-1.0.1.02.1/library.properties create mode 100644 lib/esp-mqtt-arduino-1.0.1.02.1/src/MQTT.cpp create mode 100644 lib/esp-mqtt-arduino-1.0.1.02.1/src/MQTT.h create mode 100644 lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/debug.h create mode 100644 lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/mqtt.c create mode 100644 lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/mqtt.h create mode 100644 lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/mqtt_config.h create mode 100644 lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/mqtt_msg.c create mode 100644 lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/mqtt_msg.h create mode 100644 lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/proto.c create mode 100644 lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/proto.h create mode 100644 lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/queue.c create mode 100644 lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/queue.h create mode 100644 lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/ringbuf.c create mode 100644 lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/ringbuf.h create mode 100644 lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/typedef.h create mode 100644 lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/utils.c create mode 100644 lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/utils.h create mode 100644 sonoff/language/bg-BG.h create mode 100644 sonoff/language/cs-CZ.h create mode 100644 sonoff/language/el-GR.h create mode 100644 sonoff/language/hu-HU.h create mode 100644 sonoff/language/pt-PT.h create mode 100644 sonoff/language/ru-RU.h create mode 100644 sonoff/language/zh-TW.h delete mode 100644 sonoff/user_config_override.h create mode 100644 sonoff/user_config_override_sample.h create mode 100644 sonoff/xdrv_00_mqtt.ino create mode 100644 sonoff/xdrv_08_serial_bridge.ino create mode 100644 sonoff/xdrv_09_timers.ino create mode 100644 sonoff/xdrv_10_rules.ino create mode 100644 sonoff/xdrv_11_knx.ino create mode 100644 sonoff/xsns_19_mgs.ino create mode 100644 sonoff/xsns_20_novasds.ino create mode 100644 sonoff/xsns_21_sgp30.ino create mode 100644 sonoff/xsns_22_sr04.ino diff --git a/.gitignore b/.gitignore index 49359a587..c0b169286 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,14 @@ -.pioenvs +## OS specific ######## +.DS_Store +.fuse_hidden* + +## Project files ######.pioenvs .piolibdeps .clang_complete .gcc-flags.json .vscode +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json sonoff/user_config_override.h +.pioenvs diff --git a/README.md b/README.md index f6b4c9126..11b3741be 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ ## Sonoff-Tasmota -Alternative firmware for _ESP8266 based devices_ like [iTead](https://www.itead.cc/) _**Sonoff**_ with **web**, **timers**, 'Over The Air' (**OTA**) firmware updates and **sensors support**, allowing control under **Serial**, **HTTP** and **MQTT**, so as to be used on **Smart Home Systems**. Written for Arduino IDE and PlatformIO. +Alternative firmware for _ESP8266 based devices_ like [iTead](https://www.itead.cc/) _**Sonoff**_ with **web**, **timers**, 'Over The Air' (**OTA**) firmware updates and **sensors support**, allowing control under **Serial**, **HTTP**, **MQTT** and **KNX**, so as to be used on **Smart Home Systems**. Written for Arduino IDE and PlatformIO. [![GitHub version](https://img.shields.io/github/release/arendst/Sonoff-Tasmota.svg)](https://github.com/arendst/Sonoff-Tasmota/releases/latest) [![GitHub download](https://img.shields.io/github/downloads/arendst/Sonoff-Tasmota/total.svg)](https://github.com/arendst/Sonoff-Tasmota/releases/latest) @@ -10,6 +10,8 @@ If you like **Sonoff-Tasmota**, give it a star, or fork it and contribute! [![GitHub stars](https://img.shields.io/github/stars/arendst/Sonoff-Tasmota.svg?style=social&label=Star)](https://github.com/arendst/Sonoff-Tasmota/stargazers) [![GitHub forks](https://img.shields.io/github/forks/arendst/Sonoff-Tasmota.svg?style=social&label=Fork)](https://github.com/arendst/Sonoff-Tasmota/network) +See [sonoff/_releasenotes.ino](https://github.com/arendst/Sonoff-Tasmota/blob/master/sonoff/_releasenotes.ino) for change information. + ### Quick install Download one of the released binaries from https://github.com/arendst/Sonoff-Tasmota/releases and flash it to your hardware as documented in the wiki. @@ -39,9 +41,10 @@ The following devices are supported: - [iTead Sonoff SV](https://www.itead.cc/smart-home/sonoff-sv.html) - [iTead Sonoff TH10/TH16 with temperature sensor](https://www.itead.cc/smart-home/sonoff-th.html) - [iTead Sonoff Dual (R2)](https://www.itead.cc/smart-home/sonoff-dual.html) -- [iTead Sonoff Pow](https://www.itead.cc/smart-home/sonoff-pow.html) -- [iTead Sonoff 4CH](https://www.itead.cc/smart-home/sonoff-4ch.html) -- [iTead Sonoff 4CH Pro](https://www.itead.cc/smart-home/sonoff-4ch-pro.html) +- [iTead Sonoff Pow with Energy Monitoring](https://www.itead.cc/smart-home/sonoff-pow.html) +- [iTead Sonoff Pow R2 with Energy Monitoring](https://www.itead.cc/sonoff-pow-r2.html) +- [iTead Sonoff 4CH (R2)](https://www.itead.cc/smart-home/sonoff-4ch.html) +- [iTead Sonoff 4CH Pro (R2)](https://www.itead.cc/smart-home/sonoff-4ch-pro.html) - [iTead S20 Smart Socket](https://www.itead.cc/smart-socket.html) - [Sonoff S22 Smart Socket](https://github.com/arendst/Sonoff-Tasmota/issues/627) - [iTead Sonoff S31 Smart Socket with Energy Monitoring](https://www.itead.cc/sonoff-s31.html) @@ -49,7 +52,7 @@ The following devices are supported: - [iTead Sonoff Touch](https://www.itead.cc/sonoff-touch.html) - [iTead Sonoff T1](https://www.itead.cc/sonoff-t1.html) - [iTead Sonoff SC](https://www.itead.cc/sonoff-sc.html) -- [iTead Sonoff Led](https://www.itead.cc/sonoff-led.html) +- [iTead Sonoff Led](https://www.itead.cc/sonoff-led.html) - [iTead Sonoff BN-SZ01 Ceiling Led](https://www.itead.cc/bn-sz01.html) - [iTead Sonoff B1](https://www.itead.cc/sonoff-b1.html) - [iTead Sonoff RF Bridge 433](https://www.itead.cc/sonoff-rf-bridge-433.html) @@ -63,17 +66,126 @@ The following devices are supported: - AriLux AL-LC01, AL-LC06 and AL-LC11 PWM LED controller - [Supla device - Espablo-inCan mod. for electrical Installation box](https://forum.supla.org/viewtopic.php?f=33&t=2188) - [Luani HVIO board](https://luani.de/projekte/esp8266-hvio/) -- Wemos D1 mini and NodeMcu +- Wemos D1 mini, NodeMcu and Ledunia + +### Firmware release information +Different firmware images are released based on Features and Sensors selection guided by code and memory usage. + +- The Minimal version allows intermediate OTA uploads to support larger versions and does NOT change any persistent parameter. +- The Classic version allows single OTA uploads as did the previous Sonoff-Tasmota versions. + +#### Available Features and Sensors + +| Feature or Sensor | sonoff | classic | minimal | knx | allsensors | +|--------------------------------|--------|---------|---------|-----|------------| +| MY_LANGUAGE en-GB | x | x | x | x | x | +| MQTT_LIBRARY_TYPE PUBSUBCLIENT | x | x | x | x | x | +| USE_DOMOTICZ | x | x | - | x | x | +| USE_HOME_ASSISTANT | x | x | - | x | x | +| USE_MQTT_TLS | - | - | - | - | - | +| USE_KNX | - | - | - | x | - | +| USE_WEBSERVER | x | x | x | x | x | +| USE_EMULATION | x | x | - | - | x | +| USE_DISCOVERY | x | x | - | x | x | +| WEBSERVER_ADVERTISE | x | x | - | x | x | +| MQTT_HOST_DISCOVERY | x | x | - | x | x | +| USE_TIMERS | x | - | - | x | x | +| USE_TIMERS_WEB | x | - | - | x | x | +| USE_SUNRISE | x | - | - | x | x | +| USE_RULES | x | - | - | x | x | +| | | | | | | +| USE_ADC_VCC | x | x | x | x | x | +| USE_DS18B20 | x | x | - | x | - | +| USE_DS18x20 | - | - | - | - | x | +| USE_DS18x20_LEGACY | - | - | - | - | - | +| USE_I2C | x | x | - | x | x | +| USE_SHT | x | x | - | x | x | +| USE_SHT3X | x | x | - | x | x | +| USE_HTU | x | x | - | x | x | +| USE_BMP | x | x | - | x | x | +| USE_BME680 | - | - | - | - | x | +| USE_SGP30 | x | - | - | x | x | +| USE_BH1750 | x | x | - | x | x | +| USE_VEML6070 | - | - | - | - | x | +| USE_TSL2561 | - | - | - | - | x | +| USE_ADS1115 | - | - | - | - | x | +| USE_ADS1115_I2CDEV | - | - | - | - | - | +| USE_INA219 | - | - | - | - | x | +| USE_MGS | - | - | - | - | x | +| USE_SPI | - | - | - | - | - | +| USE_MHZ19 | x | x | - | x | x | +| USE_SENSEAIR | x | x | - | x | x | +| USE_PMS5003 | x | x | - | x | x | +| USE_NOVA_SDS | x | - | - | x | x | +| USE_PZEM004T | x | x | - | x | x | +| USE_SERIAL_BRIDGE | x | - | - | x | x | +| USE_IR_REMOTE | x | x | - | x | x | +| USE_IR_HVAC | - | - | - | - | x | +| USE_IR_RECEIVE | x | - | - | x | x | +| USE_WS2812 | x | x | - | x | x | +| USE_WS2812_DMA | - | - | - | - | - | +| USE_ARILUX_RF | x | x | - | x | x | +| USE_SR04 | x | - | - | x | x | + +#### Typical file size + +| ESP/Arduino library version | sonoff | classic | minimal | knx | allsensors | +|--------------------------------|--------|---------|---------|------|------------| +| ESP/Arduino lib v2.3.0 | 526k | 488k | 427k | 535k | 549k | +| ESP/Arduino lib v2.4.0 | 531k | 496k | 435k | 540k | 552k | +| ESP/Arduino lib v2.4.1 | 534k | 499k | 437k | 543k | 555k | ### Contribute - You can contribute to Sonoff-Tasmota by - providing Pull Requests (Features, Proof of Concepts, Language files or Fixes) - testing new released features and report issues -- donating to acquire hardware for testing and implementating or out of gratitude +- donating to acquire hardware for testing and implementing or out of gratitude [![donate](https://img.shields.io/badge/donate-PayPal-blue.svg)](https://paypal.me/tasmota) +### Credits + +#### Libraries used +Libraries used with Sonoff-Tasmota are: +- [ESP8266 core for Arduino](https://github.com/esp8266/Arduino) +- [Adafruit BME680](https://github.com/adafruit/Adafruit_BME680) +- [Adafruit Sensor](https://github.com/adafruit/Adafruit_Sensor) +- [Adafruit SGP30](https://github.com/adafruit/Adafruit_SGP30) +- [ArduinoJson](https://arduinojson.org/) +- [Esp8266MqttClient](https://github.com/tuanpmt/ESP8266MQTTClient) +- [esp-knx-ip](https://github.com/envy/esp-knx-ip) +- [esp-mqtt-arduino](https://github.com/i-n-g-o/esp-mqtt-arduino) +- [I2Cdevlib](https://github.com/jrowberg/i2cdevlib) +- [IRremoteEsp8266](https://github.com/markszabo/IRremoteESP8266) +- [JobaTsl2561](https://github.com/joba-1/Joba_Tsl2561) +- [MultiChannelGasSensor](http://wiki.seeedstudio.com/Grove-Multichannel_Gas_Sensor/) +- [NeoPixelBus](https://github.com/Makuna/NeoPixelBus) +- [OneWire](https://github.com/PaulStoffregen/OneWire) +- [PubSubClient](https://github.com/knolleary/pubsubclient) + +#### People inspiring me +People helping to keep the show on the road: +- David Lang providing initial issue resolution and code optimizations +- Heiko Krupp for his IRSend, HTU21, SI70xx and Wemo/Hue emulation drivers +- Wiktor Schmidt for Travis CI implementation +- Thom Dietrich for PlatformIO optimizations +- Marinus van den Broek for his EspEasy groundwork +- Pete Ba for more user friendly energy monitor calibration +- Lobradov providing compile optimization tips +- Flexiti for his initial timer implementation +- reloxx13 for his [SonWeb](https://github.com/reloxx13/SonWEB) management tool +- Joachim Banzhaf for his TSL2561 library and driver +- Gijs Noorlander for his MHZ19 and SenseAir drivers +- Emontnemery for his HomeAssistant Discovery concept and many code tuning tips +- Aidan Mountford for his HSB support +- Daniel Ztolnai for his Serial Bridge implementation +- Gerhard Mutz for his SGP30 and Sunrise/Sunset driver +- Nuno Ferreira for his HC-SR04 driver +- Adrian Scillato for his (security)fixes and implementing and maintaining KNX +- Raymond Mouthaan for managing Wemos Wiki information +- Norbert Richter, Frogmore42 and Jason2866 for providing many issue answers +- Many more providing Tips, Pocs or PRs + ### License -This program is licensed under GPL-3.0 \ No newline at end of file +This program is licensed under GPL-3.0 diff --git a/lib/TSL2561-Arduino-Library/.github/ISSUE_TEMPLATE.md b/lib/Adafruit_SGP30-1.0.0.13/.github/ISSUE_TEMPLATE.md similarity index 100% rename from lib/TSL2561-Arduino-Library/.github/ISSUE_TEMPLATE.md rename to lib/Adafruit_SGP30-1.0.0.13/.github/ISSUE_TEMPLATE.md diff --git a/lib/TSL2561-Arduino-Library/.github/PULL_REQUEST_TEMPLATE.md b/lib/Adafruit_SGP30-1.0.0.13/.github/PULL_REQUEST_TEMPLATE.md similarity index 100% rename from lib/TSL2561-Arduino-Library/.github/PULL_REQUEST_TEMPLATE.md rename to lib/Adafruit_SGP30-1.0.0.13/.github/PULL_REQUEST_TEMPLATE.md diff --git a/lib/Adafruit_SGP30-1.0.0.13/.gitignore b/lib/Adafruit_SGP30-1.0.0.13/.gitignore new file mode 100644 index 000000000..7f189125f --- /dev/null +++ b/lib/Adafruit_SGP30-1.0.0.13/.gitignore @@ -0,0 +1,4 @@ +*~ +Doxyfile* +doxygen_sqlite3.db +html \ No newline at end of file diff --git a/lib/Adafruit_SGP30-1.0.0.13/.travis.yml b/lib/Adafruit_SGP30-1.0.0.13/.travis.yml new file mode 100644 index 000000000..428f3434e --- /dev/null +++ b/lib/Adafruit_SGP30-1.0.0.13/.travis.yml @@ -0,0 +1,27 @@ +language: c +sudo: false + +# Blacklist +branches: + except: + - gh-pages + +env: + global: + - PRETTYNAME="Adafruit SGP30 Arduino Library" +# Optional, will default to "$TRAVIS_BUILD_DIR/Doxyfile" +# - DOXYFILE: $TRAVIS_BUILD_DIR/Doxyfile + +before_install: + - source <(curl -SLs https://raw.githubusercontent.com/adafruit/travis-ci-arduino/master/install.sh) + +#install: +# - arduino --install-library "Adafruit ILI9341","Adafruit GFX Library" + +script: + - build_main_platforms + +# Generate and deploy documentation +after_success: + - source <(curl -SLs https://raw.githubusercontent.com/adafruit/travis-ci-arduino/master/library_check.sh) + - source <(curl -SLs https://raw.githubusercontent.com/adafruit/travis-ci-arduino/master/doxy_gen_and_deploy.sh) \ No newline at end of file diff --git a/lib/Adafruit_SGP30-1.0.0.13/Adafruit_SGP30.cpp b/lib/Adafruit_SGP30-1.0.0.13/Adafruit_SGP30.cpp new file mode 100644 index 000000000..b2ccbe8da --- /dev/null +++ b/lib/Adafruit_SGP30-1.0.0.13/Adafruit_SGP30.cpp @@ -0,0 +1,243 @@ +/*! + * @file Adafruit_SGP30.cpp + * + * @mainpage Adafruit SGP30 gas sensor driver + * + * @section intro_sec Introduction + * + * This is the documentation for Adafruit's SGP30 driver for the + * Arduino platform. It is designed specifically to work with the + * Adafruit SGP30 breakout: http://www.adafruit.com/products/3709 + * + * These sensors use I2C to communicate, 2 pins (SCL+SDA) are required + * to interface with the breakout. + * + * Adafruit invests time and resources providing this open source code, + * please support Adafruit and open-source hardware by purchasing + * products from Adafruit! + * + * + * @section author Author + * Written by Ladyada for Adafruit Industries. + * + * @section license License + * BSD license, all text here must be included in any redistribution. + * + */ + + +#if ARDUINO >= 100 + #include "Arduino.h" +#else + #include "WProgram.h" +#endif + +#include "Adafruit_SGP30.h" + +//#define I2C_DEBUG + +/**************************************************************************/ +/*! + @brief Instantiates a new SGP30 class +*/ +/**************************************************************************/ +Adafruit_SGP30::Adafruit_SGP30() { +} + +/**************************************************************************/ +/*! + @brief Setups the hardware and detects a valid SGP30. Initializes I2C + then reads the serialnumber and checks that we are talking to an SGP30 + @param theWire Optional pointer to I2C interface, otherwise use Wire + @returns True if SGP30 found on I2C, False if something went wrong! +*/ +/**************************************************************************/ +boolean Adafruit_SGP30::begin(TwoWire *theWire) { + _i2caddr = SGP30_I2CADDR_DEFAULT; + if (theWire == NULL) { + _i2c = &Wire; + } else { + _i2c = theWire; + } + + _i2c->begin(); + + + uint8_t command[2]; + command[0] = 0x36; + command[1] = 0x82; + if (! readWordFromCommand(command, 2, 10, serialnumber, 3)) + return false; + + uint16_t featureset; + command[0] = 0x20; + command[1] = 0x2F; + if (! readWordFromCommand(command, 2, 10, &featureset, 1)) + return false; + //Serial.print("Featureset 0x"); Serial.println(featureset, HEX); + if (featureset != SGP30_FEATURESET) + return false; + if (! IAQinit()) + return false; + + return true; +} + +/**************************************************************************/ +/*! + @brief Commands the sensor to begin the IAQ algorithm. Must be called after startup. + @returns True if command completed successfully, false if something went wrong! +*/ +/**************************************************************************/ +boolean Adafruit_SGP30::IAQinit(void) { + uint8_t command[2]; + command[0] = 0x20; + command[1] = 0x03; + return readWordFromCommand(command, 2, 10); +} + +/**************************************************************************/ +/*! + @brief Commands the sensor to take a single eCO2/VOC measurement. Places results in {@link TVOC} and {@link eCO2} + @returns True if command completed successfully, false if something went wrong! +*/ +/**************************************************************************/ +boolean Adafruit_SGP30::IAQmeasure(void) { + uint8_t command[2]; + command[0] = 0x20; + command[1] = 0x08; + uint16_t reply[2]; + if (! readWordFromCommand(command, 2, 12, reply, 2)) + return false; + TVOC = reply[1]; + eCO2 = reply[0]; + return true; +} + +/**************************************************************************/ +/*! + @brief Request baseline calibration values for both CO2 and TVOC IAQ calculations. Places results in parameter memory locaitons. + @param eco2_base A pointer to a uint16_t which we will save the calibration value to + @param tvoc_base A pointer to a uint16_t which we will save the calibration value to + @returns True if command completed successfully, false if something went wrong! +*/ +/**************************************************************************/ +boolean Adafruit_SGP30::getIAQBaseline(uint16_t *eco2_base, uint16_t *tvoc_base) { + uint8_t command[2]; + command[0] = 0x20; + command[1] = 0x15; + uint16_t reply[2]; + if (! readWordFromCommand(command, 2, 10, reply, 2)) + return false; + *eco2_base = reply[0]; + *tvoc_base = reply[1]; + return true; +} + +/**************************************************************************/ +/*! + @brief Assign baseline calibration values for both CO2 and TVOC IAQ calculations. + @param eco2_base A uint16_t which we will save the calibration value from + @param tvoc_base A uint16_t which we will save the calibration value from + @returns True if command completed successfully, false if something went wrong! +*/ +/**************************************************************************/ +boolean Adafruit_SGP30::setIAQBaseline(uint16_t eco2_base, uint16_t tvoc_base) { + uint8_t command[8]; + command[0] = 0x20; + command[1] = 0x1e; + command[2] = tvoc_base >> 8; + command[3] = tvoc_base & 0xFF; + command[4] = generateCRC(command+2, 2); + command[5] = eco2_base >> 8; + command[6] = eco2_base & 0xFF; + command[7] = generateCRC(command+5, 2); + + return readWordFromCommand(command, 8, 10); +} + +/**************************************************************************/ +/*! + @brief I2C low level interfacing +*/ +/**************************************************************************/ + + +boolean Adafruit_SGP30::readWordFromCommand(uint8_t command[], uint8_t commandLength, uint16_t delayms, uint16_t *readdata, uint8_t readlen) +{ + uint8_t data; + + _i2c->beginTransmission(_i2caddr); + +#ifdef I2C_DEBUG + Serial.print("\t\t-> "); +#endif + + for (uint8_t i=0; iwrite(command[i]); +#ifdef I2C_DEBUG + Serial.print("0x"); Serial.print(command[i], HEX); Serial.print(", "); +#endif + } +#ifdef I2C_DEBUG + Serial.println(); +#endif + _i2c->endTransmission(); + + delay(delayms); + + if (readlen == 0) + return true; + + uint8_t replylen = readlen * (SGP30_WORD_LEN +1); + if (_i2c->requestFrom(_i2caddr, replylen) != replylen) + return false; + uint8_t replybuffer[replylen]; +#ifdef I2C_DEBUG + Serial.print("\t\t<- "); +#endif + for (uint8_t i=0; iread(); +#ifdef I2C_DEBUG + Serial.print("0x"); Serial.print(replybuffer[i], HEX); Serial.print(", "); +#endif + } + +#ifdef I2C_DEBUG + Serial.println(); +#endif + + for (uint8_t i=0; i + +// the i2c address +#define SGP30_I2CADDR_DEFAULT 0x58 ///< SGP30 has only one I2C address + +// commands and constants +#define SGP30_FEATURESET 0x0020 ///< The required set for this library +#define SGP30_CRC8_POLYNOMIAL 0x31 ///< Seed for SGP30's CRC polynomial +#define SGP30_CRC8_INIT 0xFF ///< Init value for CRC +#define SGP30_WORD_LEN 2 ///< 2 bytes per word + +/**************************************************************************/ +/*! Class that stores state and functions for interacting with SGP30 Gas Sensor */ +/**************************************************************************/ +class Adafruit_SGP30 { + public: + Adafruit_SGP30(); + boolean begin(TwoWire *theWire = NULL); + boolean IAQinit(void); + boolean IAQmeasure(void); + + boolean getIAQBaseline(uint16_t *eco2_base, uint16_t *tvoc_base); + boolean setIAQBaseline(uint16_t eco2_base, uint16_t tvoc_base); + + /** + * The last measurement of the IAQ-calculated Total Volatile Organic Compounds in ppb. This value is set when you call {@link IAQmeasure()} + */ + uint16_t TVOC; + + /** + * The last measurement of the IAQ-calculated equivalent CO2 in ppm. This value is set when you call {@link IAQmeasure()} + */ + uint16_t eCO2; + + /** + * The 48-bit serial number, this value is set when you call {@link begin()} + */ + uint16_t serialnumber[3]; + private: + TwoWire *_i2c; + uint8_t _i2caddr; + + void write(uint8_t address, uint8_t *data, uint8_t n); + void read(uint8_t address, uint8_t *data, uint8_t n); + boolean readWordFromCommand(uint8_t command[], uint8_t commandLength, uint16_t delay, uint16_t *readdata = NULL, uint8_t readlen = 0); + uint8_t generateCRC(uint8_t data[], uint8_t datalen); +}; diff --git a/lib/Adafruit_SGP30-1.0.0.13/README.md b/lib/Adafruit_SGP30-1.0.0.13/README.md new file mode 100644 index 000000000..44056b5c8 --- /dev/null +++ b/lib/Adafruit_SGP30-1.0.0.13/README.md @@ -0,0 +1,18 @@ +Adafruit_SGP30 +================ + +This is the Adafruit SGP30 Gas / Air Quality I2C sensor library + +Tested and works great with the Aadafruit SGP30 Breakout Board + * http://www.adafruit.com/products/3709 + +This chip uses I2C to communicate, 2 pins are required to interface + +Adafruit invests time and resources providing this open source code, +please support Adafruit and open-source hardware by purchasing +products from Adafruit! + +Written by Limor Fried for Adafruit Industries. +BSD license, check license.txt for more information +All text above must be included in any redistribution + diff --git a/lib/Adafruit_SGP30-1.0.0.13/examples/sgp30test/sgp30test.ino b/lib/Adafruit_SGP30-1.0.0.13/examples/sgp30test/sgp30test.ino new file mode 100644 index 000000000..6b9b3ea05 --- /dev/null +++ b/lib/Adafruit_SGP30-1.0.0.13/examples/sgp30test/sgp30test.ino @@ -0,0 +1,45 @@ +#include +#include "Adafruit_SGP30.h" + +Adafruit_SGP30 sgp; + +void setup() { + Serial.begin(9600); + Serial.println("SGP30 test"); + + if (! sgp.begin()){ + Serial.println("Sensor not found :("); + while (1); + } + Serial.print("Found SGP30 serial #"); + Serial.print(sgp.serialnumber[0], HEX); + Serial.print(sgp.serialnumber[1], HEX); + Serial.println(sgp.serialnumber[2], HEX); + + // If you have a baseline measurement from before you can assign it to start, to 'self-calibrate' + //sgp.setIAQBaseline(0x8E68, 0x8F41); // Will vary for each sensor! +} + +int counter = 0; +void loop() { + if (! sgp.IAQmeasure()) { + Serial.println("Measurement failed"); + return; + } + Serial.print("TVOC "); Serial.print(sgp.TVOC); Serial.print(" ppb\t"); + Serial.print("eCO2 "); Serial.print(sgp.eCO2); Serial.println(" ppm"); + delay(1000); + + counter++; + if (counter == 30) { + counter = 0; + + uint16_t TVOC_base, eCO2_base; + if (! sgp.getIAQBaseline(&eCO2_base, &TVOC_base)) { + Serial.println("Failed to get baseline readings"); + return; + } + Serial.print("****Baseline values: eCO2: 0x"); Serial.print(eCO2_base, HEX); + Serial.print(" & TVOC: 0x"); Serial.println(TVOC_base, HEX); + } +} \ No newline at end of file diff --git a/lib/Adafruit_SGP30-1.0.0.13/library.properties b/lib/Adafruit_SGP30-1.0.0.13/library.properties new file mode 100644 index 000000000..3520b4d38 --- /dev/null +++ b/lib/Adafruit_SGP30-1.0.0.13/library.properties @@ -0,0 +1,9 @@ +name=Adafruit SGP30 Sensor +version=1.0.2 +author=Adafruit +maintainer=Adafruit +sentence=This is an Arduino library for the Adafruit SGP30 Gas / Air Quality Sensor +paragraph=This is an Arduino library for the Adafruit SGP30 Gas / Air Quality Sensor +category=Sensors +url=https://github.com/adafruit/Adafruit_SGP30 +architectures=* diff --git a/lib/Adafruit_SGP30-1.0.0.13/license.txt b/lib/Adafruit_SGP30-1.0.0.13/license.txt new file mode 100644 index 000000000..f6a0f22b8 --- /dev/null +++ b/lib/Adafruit_SGP30-1.0.0.13/license.txt @@ -0,0 +1,26 @@ +Software License Agreement (BSD License) + +Copyright (c) 2012, Adafruit Industries +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: +1. Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. +3. Neither the name of the copyright holders nor the +names of its contributors may be used to endorse or promote products +derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/lib/Joba_Tsl2561/COPYING b/lib/Joba_Tsl2561/COPYING new file mode 100644 index 000000000..f288702d2 --- /dev/null +++ b/lib/Joba_Tsl2561/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/lib/Joba_Tsl2561/COPYING.LESSER b/lib/Joba_Tsl2561/COPYING.LESSER new file mode 100644 index 000000000..0a041280b --- /dev/null +++ b/lib/Joba_Tsl2561/COPYING.LESSER @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/lib/Joba_Tsl2561/README b/lib/Joba_Tsl2561/README new file mode 100644 index 000000000..86c1f1a0b --- /dev/null +++ b/lib/Joba_Tsl2561/README @@ -0,0 +1,20 @@ +This is a library for the TSL2561 digital luminosity sensors from Ams (Taos). + +Design goals: +* It is modularized so you can use only what you need if space/ram is constrained. +* It does not swallow error codes so you can react on them. +* It doesn't use floats as they are overkill for most IoT stuff. + +Datasheet used: +http://ams.com/eng/Products/Light-Sensors/Ambient-Light-Sensors/TSL2561/TSL2560-TSL2561-Datasheet +http://ams.com/eng/content/download/250094/975485/file/TSL2560-61_DS000110_2-00.pdf +http://ams.com/eng/content/view/download/145438 +http://ams.com/eng/content/view/download/181895 + +To use the library, just place the folder in your projects lib folder. +For usage, see the examples folder. + +The library has 3 classes: +Tsl2561 All register access as described in the datasheet, except for interrupts +Tsl2561Util Convenience functions like lux calculation or automatic gain +Tsl2561Int TODO, Interrupt related stuff (not needed if int pin unconnected) diff --git a/lib/Joba_Tsl2561/examples/Autogain/Autogain.ino b/lib/Joba_Tsl2561/examples/Autogain/Autogain.ino new file mode 100644 index 000000000..03da78d46 --- /dev/null +++ b/lib/Joba_Tsl2561/examples/Autogain/Autogain.ino @@ -0,0 +1,65 @@ +/* +Autogain tests for Tsl2561Util namespace. + +Copyright: Joachim Banzhaf, 2018 + +This file is part of the Joba_Tsl2561 Library. + + Joba_Tsl2561 is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Joba_Tsl2561 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Joba_Tsl2561. If not, see . +*/ + +#include + +Tsl2561 Tsl(Wire); +uint8_t id; + +void setup() { + Serial.begin(115200); + Wire.begin(); + while( !Tsl.begin() ) + ; // wait until chip detected or wdt reset + Serial.println("\nStarting Tsl2561Util autogain loop"); + Tsl.on(); + Tsl.id(id); +} + +void loop() { + uint16_t scaledFull = ~0, scaledIr = ~0; + uint32_t full = ~0, ir = ~0, milliLux = ~0; + bool gain = false; + Tsl2561::exposure_t exposure = Tsl2561::EXP_OFF; + + if( Tsl2561Util::autoGain(Tsl, gain, exposure, scaledFull, scaledIr) ) { + if( Tsl2561Util::normalizedLuminosity(gain, exposure, full = scaledFull, ir = scaledIr) ) { + if( Tsl2561Util::milliLux(full, ir, milliLux, Tsl2561::packageCS(id)) ) { + Serial.printf("Tsl2561 addr: 0x%02x, id: 0x%02x, sfull: %5u, sir: %5u, full: %5u, ir: %5u, gain: %d, exp: %d, lux: %5u.%03u\n", + Tsl.address(), id, scaledFull, scaledIr, full, ir, gain, exposure, milliLux/1000, milliLux%1000); + } + else { + Serial.printf("Tsl2561Util::milliLux(full=%u, ir=%u) error\n", full, ir); + } + } + else { + Serial.printf("Tsl2561Util::normalizedLuminosity(gain=%u, exposure=%u, sfull=%u, sir=%u, full=%u, ir=%u) error\n", + gain, exposure, scaledFull, scaledIr, full, ir); + } + } + else { + Serial.printf("Tsl2561Util::autoGain(gain=%u, exposure=%u, sfull=%u, sir=%u) error\n", + gain, exposure, scaledFull, scaledIr); + } + + delay(1000); +} + diff --git a/lib/Joba_Tsl2561/examples/Simple/Simple.ino b/lib/Joba_Tsl2561/examples/Simple/Simple.ino new file mode 100644 index 000000000..f1c2d88d9 --- /dev/null +++ b/lib/Joba_Tsl2561/examples/Simple/Simple.ino @@ -0,0 +1,56 @@ +/* +Simple tests for Tsl2561 class. No error checking is done. + +Copyright: Joachim Banzhaf, 2018 + +This file is part of the Joba_Tsl2561 Library. + + Joba_Tsl2561 is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Joba_Tsl2561 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Joba_Tsl2561. If not, see . +*/ + +#include + +Tsl2561 Tsl(Wire); + +void setup() { + Serial.begin(115200); + Wire.begin(); + Serial.println("\nStarting Tsl2561 simple loop"); +} + +void loop() { + Tsl.begin(); + if( Tsl.available() ) { + Tsl.on(); + + Tsl.setSensitivity(true, Tsl2561::EXP_14); + delay(16); + + uint8_t id; + uint16_t full, ir; + + Tsl.id(id); + Tsl.fullLuminosity(full); + Tsl.irLuminosity(ir); + + Serial.printf("Tsl2561 at 0x%02x(id=0x%02x) luminosity is %5u (full) and %5u (ir)\n", Tsl.address(), id, full, ir); + + Tsl.off(); + } + else { + Serial.println("No Tsl2561 found. Check wiring."); + } + + delay(5000); +} diff --git a/lib/Joba_Tsl2561/examples/Testing/Testing.ino b/lib/Joba_Tsl2561/examples/Testing/Testing.ino new file mode 100644 index 000000000..8fc6d121a --- /dev/null +++ b/lib/Joba_Tsl2561/examples/Testing/Testing.ino @@ -0,0 +1,163 @@ +/* +Tests for the Tsl2561 class. +It shows how to use every available method. + +Copyright: Joachim Banzhaf, 2018 + +This file is part of the Joba_Tsl2561 Library. + + Joba_Tsl2561 is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Joba_Tsl2561 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Joba_Tsl2561. If not, see . +*/ + +#include + +Tsl2561 Tsl(Wire); + +void showError( Tsl2561 &tsl ) { + Tsl2561::status_t status = tsl.status(); + Serial.printf("Error was %u: ", status); + switch( status ) { + case Tsl2561::ERR_OK: Serial.println("None"); break; + case Tsl2561::ERR_RW: Serial.println("Read/Write"); break; + case Tsl2561::ERR_BUSY: Serial.println("Busy"); break; + case Tsl2561::ERR_GONE: Serial.println("Gone"); break; + case Tsl2561::ERR_GENERAL: Serial.println("General"); break; + default: Serial.println("Unknown"); break; + } +} + +void testSensitivity( Tsl2561 &tsl, bool newGain, Tsl2561::exposure_t newExp ) { + if( tsl.on() ) { + uint32_t start = millis(); + Serial.printf("Chip powered on at %u\n", start); + + bool chipGain; + Tsl2561::exposure_t chipExp; + bool change = true; + if( tsl.getSensitivity(chipGain, chipExp) ) { + if( chipGain == newGain && chipExp == newExp ) { + change = false; + } + } + else { + Serial.print("getSensitivity failed. "); + showError(tsl); + } + + bool check = true; + if( change ) { + if( tsl.setSensitivity(newGain, newExp) ) { + Serial.printf("New gain = %d, exposure = 0x%02x\n", newGain, newExp); + } + else { + check = false; + Serial.print("setSensitivity failed. "); + showError(tsl); + } + } + + if( check ) { + uint16_t ir, full = 0; + while( !full && millis() - start < 1000 ) { + if( !tsl.fullLuminosity(full) ) { + Serial.print("Check full luminosity failed. "); + showError(tsl); + } + if( full ) { + if( !tsl.irLuminosity(ir) ) { + Serial.print("Check ir luminosity failed. "); + showError(tsl); + } + } + else { + delay(10); + } + } + + if( !full ) { + Serial.println("No luminosity reading after 1s. Too dark?"); + } + else { + Serial.printf("Got luminosity after %d ms. Full spectrum is %d and IR only is %d\n", millis() - start, full, ir); + } + } + + if( !tsl.off() ) { + Serial.print("Power off failed. "); + showError(tsl); + } + } + else { + Serial.print("Power on failed. "); + showError(tsl); + } +} + +bool testPackage( Tsl2561 &tsl ) { + uint8_t id; + if( tsl.id(id) ) { + Serial.printf("Chip has type %02x and revision %x\n", Tsl2561::type(id), Tsl2561::revision(id) ); + if( Tsl2561::packageT_FN_CL(id) ) { + Serial.println("Chip is a T, FN or CL type package"); + } + else if( Tsl2561::packageCS(id) ) { + Serial.println("Chip is a CS type package"); + } + else { + Serial.println("Chip is an unknown package"); + } + return true; + } + else { + Serial.print("Get Chip ID failed. "); + showError(tsl); + } + return false; +} + +void test( Tsl2561 &tsl ) { + bool ok = tsl.available(); + Serial.printf("\nTesting Tsl2561 at address %02x: %sfound\n", tsl.address(), ok ? "" : "NOT "); + if( ok ) { + if( testPackage(tsl) ) { + testSensitivity(tsl, Tsl2561::GAIN_OFF, Tsl2561::EXP_402); + testSensitivity(tsl, Tsl2561::GAIN_ON, Tsl2561::EXP_402); + testSensitivity(tsl, Tsl2561::GAIN_OFF, Tsl2561::EXP_101); + testSensitivity(tsl, Tsl2561::GAIN_ON, Tsl2561::EXP_101); + testSensitivity(tsl, Tsl2561::GAIN_OFF, Tsl2561::EXP_14); + testSensitivity(tsl, Tsl2561::GAIN_ON, Tsl2561::EXP_14); + } + } + else { + showError(tsl); + } +} + +void setup() { + Serial.begin(115200); + Wire.begin(); + Serial.println("\nStarting Tsl2561 testing loop"); +} + +void loop() { + Tsl.begin(Tsl2561::ADDR_GND); + test(Tsl); + Tsl.begin(Tsl2561::ADDR_FLOAT); + test(Tsl); + Tsl.begin(Tsl2561::ADDR_VDD); + test(Tsl); + Serial.println("\nNext test in 5s\n"); + delay(5000); +} + diff --git a/lib/Joba_Tsl2561/examples/Utility/Utility.ino b/lib/Joba_Tsl2561/examples/Utility/Utility.ino new file mode 100644 index 000000000..58e03ca14 --- /dev/null +++ b/lib/Joba_Tsl2561/examples/Utility/Utility.ino @@ -0,0 +1,87 @@ +/* +Simple tests for Tsl2561Util namespace. + +Copyright: Joachim Banzhaf, 2018 + +This file is part of the Joba_Tsl2561 Library. + + Joba_Tsl2561 is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Joba_Tsl2561 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Joba_Tsl2561. If not, see . +*/ + +#include + +Tsl2561::address_t addr[] = { Tsl2561::ADDR_GND, Tsl2561::ADDR_FLOAT, Tsl2561::ADDR_VDD }; +Tsl2561 Tsl(Wire); + +void setup() { + Serial.begin(115200); + Wire.begin(); + Serial.println("\nStarting Tsl2561Util loop"); +} + +void loop() { + bool found = false; + + for( uint8_t i = 0; i < sizeof(addr)/sizeof(addr[0]); i++ ) { + if( Tsl.begin(addr[i]) ) { + found = true; + Serial.println(); + + uint16_t scaledFull = 0, scaledIr; + uint32_t full, ir, milliLux; + uint8_t id; + bool gain; + Tsl2561::exposure_t exposure; + + for( uint8_t g=0; g<2; g++ ) { + gain = g; + for( uint8_t e=0; e<3; e++ ) { + exposure = (Tsl2561::exposure_t)e; + + Tsl.on(); + + Tsl.setSensitivity(gain, exposure); + Tsl2561Util::waitNext(exposure); + Tsl.id(id); + Tsl.getSensitivity(gain, exposure); + Tsl.fullLuminosity(scaledFull); + Tsl.irLuminosity(scaledIr); + + Serial.printf("Tsl2561 addr: 0x%02x, id: 0x%02x, sfull: %5u, sir: %5u, gain: %d, exp: %d", addr[i], id, scaledFull, scaledIr, gain, exposure); + + if( Tsl2561Util::normalizedLuminosity(gain, exposure, full = scaledFull, ir = scaledIr) ) { + if( Tsl2561Util::milliLux(full, ir, milliLux, Tsl2561::packageCS(id)) ) { + Serial.printf(", full: %5u, ir: %5u, lux: %5u.%03u\n", full, ir, milliLux/1000, milliLux%1000); + } + else { + Serial.printf(", full: %5u, ir: %5u: Tsl2561Util::milliLux() error\n", full, ir); + } + } + else { + Serial.printf(", full: %5u, ir: %5u: Tsl2561Util::normalizedLuminosity() error\n", full, ir); + } + + Tsl.off(); + } + } + } + } + + if( !found ) { + Serial.println("No Tsl2561 found. Check wiring."); + } + + delay(5000); +} + diff --git a/lib/Joba_Tsl2561/library.json b/lib/Joba_Tsl2561/library.json new file mode 100644 index 000000000..cacc33d5a --- /dev/null +++ b/lib/Joba_Tsl2561/library.json @@ -0,0 +1,13 @@ +{ + "name": "Joba_Tsl2561", + "version": "2.0.1", + "keywords": "twowire, i2c, bus, sensor, luminosity, illuminance, lux", + "description": "Arduino Library for ams (taos) luminance chip Tsl2561 with autogain", + "repository": + { + "type": "git", + "url": "https://github.com/joba-1/Joba_Tsl2561.git" + }, + "frameworks": "arduino", + "platforms": "*" +} diff --git a/lib/Joba_Tsl2561/library.properties b/lib/Joba_Tsl2561/library.properties new file mode 100644 index 000000000..148736de6 --- /dev/null +++ b/lib/Joba_Tsl2561/library.properties @@ -0,0 +1,9 @@ +name=Joba Tsl2561 Library +version=2.0.1 +author=joba-1 +maintainer=joba-1 +sentence=IoT library for using the Tsl2561 luminosity sensor +paragraph=Luminosity measurement in lux with autogain +category=Sensors +url=https://github.com/joba-1/Joba_Tsl2561 +architectures=* diff --git a/lib/Joba_Tsl2561/src/Tsl2561.cpp b/lib/Joba_Tsl2561/src/Tsl2561.cpp new file mode 100644 index 000000000..ad347f071 --- /dev/null +++ b/lib/Joba_Tsl2561/src/Tsl2561.cpp @@ -0,0 +1,134 @@ +/* +Copyright: Joachim Banzhaf, 2018 + +This file is part of the Joba_Tsl2561 Library. + + Joba_Tsl2561 is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Joba_Tsl2561 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Joba_Tsl2561. If not, see . +*/ + +#include "Tsl2561.h" + +Tsl2561::Tsl2561( TwoWire &wire ) : _addr(ADDR_NONE), _wire(wire), _status(ERR_OK) { +} + +bool Tsl2561::available() { + _wire.beginTransmission(_addr); + return (_status = static_cast(_wire.endTransmission())) == ERR_OK; +} + +bool Tsl2561::begin( address_t addr ) { + _addr = addr; + return available(); +} + +bool Tsl2561::begin() { + static address_t addr[] = { ADDR_GND, ADDR_FLOAT, ADDR_VDD }; + + for( uint8_t i=0; i(_wire.read()); + } + } + return (_status = static_cast(_wire.endTransmission())) == ERR_OK; +} + +bool Tsl2561::readWord( register_t reg, uint16_t &val ) { + _wire.beginTransmission(_addr); + _wire.write(reg | CONTROL_CMD); + if( _wire.endTransmission(false) == ERR_OK ) { + if( _wire.requestFrom(_addr, 2) ) { + val = (uint16_t)_wire.read() & 0xff; + val |= ((uint16_t)_wire.read() & 0xff) << 8; + } + } + return (_status = static_cast(_wire.endTransmission())) == ERR_OK; +} + +bool Tsl2561::writeByte( register_t reg, uint8_t val ) { + _wire.beginTransmission(_addr); + _wire.write(reg | CONTROL_CMD); + _wire.write(val); + return (_status = static_cast(_wire.endTransmission())) == ERR_OK; +} + +Tsl2561::status_t Tsl2561::status() const { + return _status; +} + +Tsl2561::address_t Tsl2561::address() const { + return _addr; +} + +bool Tsl2561::id( uint8_t &id ) { + return readByte(REG_ID, id); +} + +uint8_t Tsl2561::type( uint8_t id ) { + return id & PKG_ID; +} + +uint8_t Tsl2561::revision( uint8_t id ) { + return id & PKG_REV; +} + +bool Tsl2561::packageCS( uint8_t id ) { + return type(id) == PKG_CS; +} + +bool Tsl2561::packageT_FN_CL( uint8_t id ) { + return type(id) == PKG_T_FN_CL; +} + +bool Tsl2561::on() { + return writeByte(REG_CONTROL, POWER_ON); +} + +bool Tsl2561::off() { + return writeByte(REG_CONTROL, POWER_OFF); +} + +bool Tsl2561::setSensitivity( bool gain, exposure_t exposure ) { + return writeByte(REG_TIMING, (gain ? GAIN_ON : GAIN_OFF) | exposure); +} + +bool Tsl2561::getSensitivity( bool &gain, exposure_t &exposure ) +{ + uint8_t val; + if( readByte(REG_TIMING, val) ) { + gain = val & GAIN_ON; + exposure = static_cast(val & EXP_ON); + } + return _status == ERR_OK; +} + +bool Tsl2561::fullLuminosity( uint16_t &luminosity ) { + return readWord(REG_DATA0LOW, luminosity); +} + +bool Tsl2561::irLuminosity( uint16_t &luminosity ) { + return readWord(REG_DATA1LOW, luminosity); +} diff --git a/lib/Joba_Tsl2561/src/Tsl2561.h b/lib/Joba_Tsl2561/src/Tsl2561.h new file mode 100644 index 000000000..75056f912 --- /dev/null +++ b/lib/Joba_Tsl2561/src/Tsl2561.h @@ -0,0 +1,133 @@ +/* +Copyright: Joachim Banzhaf, 2018 + +This file is part of the Joba_Tsl2561 Library. + + Joba_Tsl2561 is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Joba_Tsl2561 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Joba_Tsl2561. If not, see . +*/ + +#ifndef Tsl2561_H +#define Tsl2561_H + +#include +#include + +class Tsl2561 { + +public: + + typedef enum { + ADDR_NONE = 0b0000000, + ADDR_GND = 0b0101001, + ADDR_FLOAT = 0b0111001, + ADDR_VDD = 0b1001001 + } address_t; + + typedef enum { + REG_CONTROL, // Control of basic functions + REG_TIMING, // Integration time/gain control + REG_THRESHLOWLOW, // Low byte of low interrupt threshold + REG_THRESHLOWHIGH, // High byte of low interrupt threshold + REG_THRESHHIGHLOW, // Low byte of high interrupt threshold + REG_THRESHHIGHHIGH, // High byte of high interrupt threshold + REG_INTERRUPT, // Interrupt control + REG_RESERVED1, + REG_CRC, // Factory test - not a user register + REG_RESERVED2, + REG_ID, // Part number/Rev ID + REG_RESERVED3, + REG_DATA0LOW, // Low byte of ADC channel 0 + REG_DATA0HIGH, // High byte of ADC channel 0 + REG_DATA1LOW, // Low byte of ADC channel 1 + REG_DATA1HIGH // High byte of ADC channel 1 + } register_t; + + enum { + CONTROL_CMD = 0b10000000, + CONTROL_CLEAR = 0b01000000, + CONTROL_WORD = 0b00100000, // SPI only? + CONTROL_BLOCK = 0b00010000, // SPI only? + CONTROL_ADDRESS = 0b00001111 + }; + + enum { + POWER_OFF, + POWER_ON = 0b11, + }; + + enum { + GAIN_OFF, + GAIN_ON = 0b00010000 + }; + + typedef enum { + EXP_ON = 0b00001011, + EXP_OFF = 0b00000011, + EXP_14 = 0b00000000, + EXP_101 = 0b00000001, + EXP_402 = 0b00000010 + } exposure_t; + + enum { + PKG_ID = 0b11110000, + PKG_REV = 0b00001111, + PKG_CS = 0b00010000, + PKG_T_FN_CL = 0b01010000 + }; + + typedef enum { + ERR_OK = 0, + ERR_GENERAL = 1, + ERR_GONE = 2, + ERR_RW = 3, + ERR_BUSY = 4 + } status_t; + + Tsl2561( TwoWire &wire ); + + bool begin( address_t addr ); + bool begin(); + + bool available(); + status_t status() const; + address_t address() const; + + bool id( uint8_t &id ); + static uint8_t type( uint8_t id ); + static uint8_t revision( uint8_t id ); + static bool packageCS( uint8_t id ); + static bool packageT_FN_CL( uint8_t id ); + + bool on(); + bool off(); + bool setSensitivity( bool gain, exposure_t exposure ); + bool getSensitivity( bool &gain, exposure_t &exposure ); + bool fullLuminosity( uint16_t &luminosity ); + bool irLuminosity( uint16_t &luminosity ); + +protected: + bool readByte( register_t reg, uint8_t &val ); + bool readWord( register_t reg, uint16_t &val ); + bool writeByte( register_t reg, uint8_t val ); + +private: + Tsl2561(); + Tsl2561( Tsl2561 & ); + + address_t _addr; + TwoWire &_wire; + status_t _status; +}; + +#endif diff --git a/lib/Joba_Tsl2561/src/Tsl2561Util.cpp b/lib/Joba_Tsl2561/src/Tsl2561Util.cpp new file mode 100644 index 000000000..92997b60b --- /dev/null +++ b/lib/Joba_Tsl2561/src/Tsl2561Util.cpp @@ -0,0 +1,193 @@ +/* +Copyright: Joachim Banzhaf, 2018 + +This file is part of the Joba_Tsl2561 Library. + + Joba_Tsl2561 is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Joba_Tsl2561 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Joba_Tsl2561. If not, see . +*/ + +#include "Tsl2561Util.h" + +namespace Tsl2561Util { + +// Tsl2561Util::normalizedLuminosity returncode false can mean: +// - saturation: full and/or ir have value ~0 (aka -1) +// - manual exposure time: full and ir are corrected only for gain +// If true, full and ir have values as if exposure was 402 and gain 16. +bool normalizedLuminosity( bool gain, Tsl2561::exposure_t exposure, uint32_t &full, uint32_t &ir ) { + + uint16_t scaledFull = (uint16_t)full; + uint16_t scaledIr = (uint16_t)ir; + + if( scaledFull ) { + + if( ! gain ) { + full <<= 4; + ir <<= 4; + } + + switch( exposure ) { + case Tsl2561::EXP_14: + full = (scaledFull >= 5047/4*3) ? ~0 : ((full + 5) * 322) / 11; + ir = (scaledIr >= 5047/4*3) ? ~0 : ((ir + 5) * 322) / 11; + break; + case Tsl2561::EXP_101: + full = (scaledFull >= 37177/4*3) ? ~0 : ((full + 40) * 322) / 81; + ir = (scaledIr >= 37177/4*3) ? ~0 : ((ir + 40) * 322) / 81; + break; + case Tsl2561::EXP_402: + if( scaledFull >= 65535/4*3 ) full = ~0; + if( scaledIr >= 65535/4*3 ) ir = ~0; + break; + default: + return false; + } + + return full != ~0U && ir != ~0U; + } + + return false; +} + +// Return upper saturation limit upto which chip returns accurate data +uint16_t getLimit( Tsl2561::exposure_t exposure ) { + switch( exposure ) { + case Tsl2561::EXP_14: return 5047/4*3; + case Tsl2561::EXP_101: return 37177/4*3; + default: return 65535/4*3; + } +} + +// Wait for one measurement interval plus some empirically tested extra millis +void waitNext( Tsl2561::exposure_t exposure ) { + switch( exposure ) { + case Tsl2561::EXP_14: delay(16); break; + case Tsl2561::EXP_101: delay(103); break; + default: delay(408); break; + } +} + +// Wait for next sample, read luminosity and adjust sensitivity, if needed and possible +bool autoGain( Tsl2561 &tsl, bool &gain, Tsl2561::exposure_t &exposure, uint16_t &full, uint16_t &ir ) { + + static const struct { + bool gain; + Tsl2561::exposure_t exposure; + } sensitivity[] = { + { false, Tsl2561::EXP_14, }, // min + { false, Tsl2561::EXP_101 }, + { true, Tsl2561::EXP_14 }, + { false, Tsl2561::EXP_402 }, + { true, Tsl2561::EXP_101 }, + { true, Tsl2561::EXP_402 } // max + }; + + // get current sensitivity + if( !tsl.getSensitivity(gain, exposure) ) { + return false; + } + + // find index of current sensitivity + uint8_t curr = 0; + while( curr < sizeof(sensitivity)/sizeof(sensitivity[0]) ) { + if( sensitivity[curr].gain == gain && sensitivity[curr].exposure == exposure ) { + break; + } + curr++; + } + if( curr == sizeof(sensitivity)/sizeof(sensitivity[0]) ) { + return false; // should not happen... + } + + // in a loop wait for next sample, get values and adjust sensitivity if needed + while( true ) { + waitNext(exposure); + + if( !tsl.fullLuminosity(full) || !tsl.irLuminosity(ir) ) { + return false; + } + + uint16_t limit = getLimit(exposure); + if( full >= 1000 && full <= limit ) { + return true; // new value within limits + } + + if( (full < 1000 && ++curr < sizeof(sensitivity)/sizeof(sensitivity[0])) + || (full > limit && curr-- > 0) ) { + if( !tsl.setSensitivity(sensitivity[curr].gain, sensitivity[curr].exposure) ) { + return false; + } + gain = sensitivity[curr].gain; + exposure = sensitivity[curr].exposure; + } + else { + return true; // saturated, but best we can do + } + } +} + +// Measurement is up to 20% too high for temperatures above 25°C. Compensate for that. +bool compensateTemperature( int16_t centiCelsius, uint32_t &full, uint32_t &ir ) { + // assume linear gradient 0% at 25°C to +20% at 70°C + if( centiCelsius >= -3000 && centiCelsius <= 7000 ) { + full -= (full * (centiCelsius - 2500) * 20) / (100 * (7000 - 2500)); + ir -= (ir * (centiCelsius - 2500) * 20) / (100 * (7000 - 2500)); + return true; + } + + return false; +} + +// Calculate lux from raw luminosity values +bool milliLux( uint32_t full, uint32_t ir, uint32_t &mLux, bool csType ) { + if( !full ) { + mLux = 0; + return true; + } + + uint32_t milliRatio = ir * 1000 / full; + + if( csType ) { + if( milliRatio < 130 ) { mLux = 1000 * full - 840 * ir; } + else if ( milliRatio < 260 ) { mLux = 1080 * full - 1380 * ir; } + else if ( milliRatio < 390 ) { mLux = 1160 * full - 1690 * ir; } + else if ( milliRatio < 520 ) { mLux = 1260 * full - 1940 * ir; } + else if ( milliRatio < 650 ) { mLux = 730 * full - 930 * ir; } + else if ( milliRatio < 800 ) { mLux = 500 * full - 575 * ir; } + else if ( milliRatio < 1300 ) { mLux = 110 * full - 85 * ir; } + else { + mLux = 0; + return false; + } + mLux /= 400 * 16 / 200; // 32 = counts/lux (cpl) + } + else { + if( milliRatio < 125 ) { mLux = 1000 * full - 895 * ir; } + else if ( milliRatio < 250 ) { mLux = 1070 * full - 1045 * ir; } + else if ( milliRatio < 375 ) { mLux = 1150 * full - 1790 * ir; } + else if ( milliRatio < 500 ) { mLux = 1260 * full - 2050 * ir; } + else if ( milliRatio < 610 ) { mLux = 740 * full - 1020 * ir; } + else if ( milliRatio < 800 ) { mLux = 420 * full - 500 * ir; } + else if ( milliRatio < 1300 ) { mLux = 48 * full - 37 * ir; } + else { + mLux = 0; + return false; + } + mLux /= 400 * 16 / 193; // 33 = counts/lux (cpl) + } + + return true; +} + +} // namespace Tsl2561Util diff --git a/lib/Joba_Tsl2561/src/Tsl2561Util.h b/lib/Joba_Tsl2561/src/Tsl2561Util.h new file mode 100644 index 000000000..58c5d4bbf --- /dev/null +++ b/lib/Joba_Tsl2561/src/Tsl2561Util.h @@ -0,0 +1,48 @@ +/* +Copyright: Joachim Banzhaf, 2018 + +This file is part of the Joba_Tsl2561 Library. + + Joba_Tsl2561 is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Joba_Tsl2561 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Joba_Tsl2561. If not, see . +*/ + +#ifndef Tsl2561Util_H +#define Tsl2561Util_H + +#include + +namespace Tsl2561Util { + + // delay until next sample is available + void waitNext( Tsl2561::exposure_t exposure ); + + // get saturation limit for given exposure time + uint16_t getLimit( Tsl2561::exposure_t exposure ); + + // in a loop wait for a sample, get it, check if within thresholds, + // until luminosity is either valid or at upper or lower saturation limit + bool autoGain( Tsl2561 &tsl, bool &gain, Tsl2561::exposure_t &exposure, uint16_t &full, uint16_t &ir ); + + // adjust luminosity as if measured with maximum exposure time and maximum gain + bool normalizedLuminosity( bool gain, Tsl2561::exposure_t exposure, uint32_t &full, uint32_t &ir ); + + // adjust luminosity according to sensor temperature (max +/-20% from 25°C) + bool compensateTemperature( int16_t centiCelsius, uint32_t &full, uint32_t &ir ); + + // calculate lux from normalized (and optionally temperature adjusted) luminosity + bool milliLux( uint32_t full, uint32_t ir, uint32_t &milliLux, bool csType = false ); + +}; + +#endif diff --git a/lib/Mutichannel_Gas_Sensor/License.txt b/lib/Mutichannel_Gas_Sensor/License.txt new file mode 100644 index 000000000..9fdaa0bb0 --- /dev/null +++ b/lib/Mutichannel_Gas_Sensor/License.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Seeed Technology Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/lib/Mutichannel_Gas_Sensor/README.md b/lib/Mutichannel_Gas_Sensor/README.md new file mode 100644 index 000000000..3f25574a9 --- /dev/null +++ b/lib/Mutichannel_Gas_Sensor/README.md @@ -0,0 +1,45 @@ +# Mutichannel_Gas_Sensor +This Arduino library is used for driving "Xadow - Mutichannel Gas Sensor" and "Grove - Mutichanel Gas Sensor" + + +## Usage: + +mutichannelGasSensor.begin(0x04); + +mutichannelGasSensor.powerOn(); + +then read the concentration of the specific gas you want to measure: + +mutichannelGasSensor.measure_NH3(); + +mutichannelGasSensor.measure_CO(); + +mutichannelGasSensor.measure_NO2(); + +mutichannelGasSensor.measure_C3H8(); + +mutichannelGasSensor.measure_C4H10(); + +mutichannelGasSensor.measure_CH4(); + +mutichannelGasSensor.measure_H2(); + +mutichannelGasSensor.measure_C2H5OH(); + +For details please move to [wiki page](http://www.seeedstudio.com/wiki/Grove_-_Multichannel_Gas_Sensor). + + + +---- + +This software is written by Jacky Zhang (![](http://www.seeedstudio.com/wiki/images/8/8f/Email_addr_of_jacky_zhang.png)) from [Seeed Technology Inc.](http://www.seeed.cc) and is licensed under [The MIT License](http://opensource.org/licenses/mit-license.php). Check License.txt/LICENSE for the details of MIT license.
+ +Contributing to this software is warmly welcomed. You can do this basically by
+[forking](https://help.github.com/articles/fork-a-repo), committing modifications and then [pulling requests](https://help.github.com/articles/using-pull-requests) (follow the links above
+for operating guide). Adding change log and your contact into file header is encouraged.
+Thanks for your contribution. + +Seeed is a hardware innovation platform for makers to grow inspirations into differentiating products. By working closely with technology providers of all scale, Seeed provides accessible technologies with quality, speed and supply chain knowledge. When prototypes are ready to iterate, Seeed helps productize 1 to 1,000 pcs using in-house engineering, supply chain management and agile manufacture forces. Seeed also team up with incubators, Chinese tech ecosystem, investors and distribution channels to portal Maker startups beyond. + + +[![Analytics](https://ga-beacon.appspot.com/UA-46589105-3/Mutichannel_Gas_Sensor)](https://github.com/igrigorik/ga-beacon) diff --git a/lib/Mutichannel_Gas_Sensor/examples/GetVersion/GetVersion.ino b/lib/Mutichannel_Gas_Sensor/examples/GetVersion/GetVersion.ino new file mode 100644 index 000000000..2dcf9f9c4 --- /dev/null +++ b/lib/Mutichannel_Gas_Sensor/examples/GetVersion/GetVersion.ino @@ -0,0 +1,20 @@ +// Get firmware version of Grove Multichannel Gas Sensor +#include +#include "MutichannelGasSensor.h" + +#define SENSOR_ADDR 0X04 // default to 0x04 + +void setup() +{ + Serial.begin(115200); + gas.begin(SENSOR_ADDR); + + unsigned char version = gas.getVersion(); + Serial.print("Version = "); + Serial.println(version); +} + +void loop() +{ + // nothing to do +} \ No newline at end of file diff --git a/lib/Mutichannel_Gas_Sensor/examples/I2C_Address/I2C_Address.ino b/lib/Mutichannel_Gas_Sensor/examples/I2C_Address/I2C_Address.ino new file mode 100644 index 000000000..925118245 --- /dev/null +++ b/lib/Mutichannel_Gas_Sensor/examples/I2C_Address/I2C_Address.ino @@ -0,0 +1,25 @@ +// change i2c address +// Loovee +// 2016-11-10 + +#include +#include "MutichannelGasSensor.h" + +#define SENSOR_ADDR_OLD 0x04 // default to 0x04 +#define SENSOR_ADDR_NEW 0x19 // change i2c address to 0x19 + +void setup() +{ + Serial.begin(115200); + gas.begin(SENSOR_ADDR_OLD); // + gas.change_i2c_address(SENSOR_ADDR_NEW); + Serial.print("I2C ADDRESS SET TO 0X");; + Serial.println(SENSOR_ADDR_NEW, HEX); +} + +void loop() +{ + +} + +// END FILE diff --git a/lib/Mutichannel_Gas_Sensor/examples/RawData/RawData.ino b/lib/Mutichannel_Gas_Sensor/examples/RawData/RawData.ino new file mode 100644 index 000000000..d154ddf16 --- /dev/null +++ b/lib/Mutichannel_Gas_Sensor/examples/RawData/RawData.ino @@ -0,0 +1,57 @@ +// get RAW data from the sensor +// Loovee +// 2016-11-10 + +#include +#include "MutichannelGasSensor.h" + +#define SENSOR_ADDR 0X04 // default to 0x04 + +void setup() +{ + Serial.begin(115200); + gas.begin(SENSOR_ADDR); // +} + +void loop() +{ + float R0_NH3, R0_CO, R0_NO2; + float Rs_NH3, Rs_CO, Rs_NO2; + float ratio_NH3, ratio_CO, ratio_NO2; + + R0_NH3 = gas.getR0(0); + R0_CO = gas.getR0(1); + R0_NO2 = gas.getR0(2); + + Rs_NH3 = gas.getRs(0); + Rs_CO = gas.getRs(1); + Rs_NO2 = gas.getRs(2); + + ratio_NH3 = Rs_NH3/R0_NH3; + ratio_CO = Rs_CO/R0_CO; + ratio_NO2 = Rs_NH3/R0_NO2; + + Serial.println("R0:"); + Serial.print(R0_NH3); + Serial.print('\t'); + Serial.print(R0_CO); + Serial.print('\t'); + Serial.println(R0_NO2); + + Serial.println("Rs:"); + Serial.print(Rs_NH3); + Serial.print('\t'); + Serial.print(Rs_CO); + Serial.print('\t'); + Serial.println(Rs_NO2); + + Serial.println("ratio:"); + Serial.print(ratio_NH3); + Serial.print('\t'); + Serial.print(ratio_CO); + Serial.print('\t'); + Serial.println(ratio_NO2); + + Serial.println("------------------------"); + delay(1000); +} diff --git a/lib/Mutichannel_Gas_Sensor/examples/ReadSensorValue_Grove/ReadSensorValue_Grove.ino b/lib/Mutichannel_Gas_Sensor/examples/ReadSensorValue_Grove/ReadSensorValue_Grove.ino new file mode 100644 index 000000000..983851668 --- /dev/null +++ b/lib/Mutichannel_Gas_Sensor/examples/ReadSensorValue_Grove/ReadSensorValue_Grove.ino @@ -0,0 +1,81 @@ +/* + This is a demo to test gas library + This code is running on Xadow-mainboard, and the I2C slave is Xadow-gas + There is a ATmega168PA on Xadow-gas, it get sensors output and feed back to master. + the data is raw ADC value, algorithm should be realized on master. + + please feel free to write email to me if there is any question + + Jacky Zhang, Embedded Software Engineer + qi.zhang@seeed.cc + 17,mar,2015 +*/ + +#include +#include "MutichannelGasSensor.h" + +void setup() +{ + Serial.begin(115200); // start serial for output + Serial.println("power on!"); + gas.begin(0x04);//the default I2C address of the slave is 0x04 + gas.powerOn(); + Serial.print("Firmware Version = "); + Serial.println(gas.getVersion()); +} + +void loop() +{ + float c; + + c = gas.measure_NH3(); + Serial.print("The concentration of NH3 is "); + if(c>=0) Serial.print(c); + else Serial.print("invalid"); + Serial.println(" ppm"); + + c = gas.measure_CO(); + Serial.print("The concentration of CO is "); + if(c>=0) Serial.print(c); + else Serial.print("invalid"); + Serial.println(" ppm"); + + c = gas.measure_NO2(); + Serial.print("The concentration of NO2 is "); + if(c>=0) Serial.print(c); + else Serial.print("invalid"); + Serial.println(" ppm"); + + c = gas.measure_C3H8(); + Serial.print("The concentration of C3H8 is "); + if(c>=0) Serial.print(c); + else Serial.print("invalid"); + Serial.println(" ppm"); + + c = gas.measure_C4H10(); + Serial.print("The concentration of C4H10 is "); + if(c>=0) Serial.print(c); + else Serial.print("invalid"); + Serial.println(" ppm"); + + c = gas.measure_CH4(); + Serial.print("The concentration of CH4 is "); + if(c>=0) Serial.print(c); + else Serial.print("invalid"); + Serial.println(" ppm"); + + c = gas.measure_H2(); + Serial.print("The concentration of H2 is "); + if(c>=0) Serial.print(c); + else Serial.print("invalid"); + Serial.println(" ppm"); + + c = gas.measure_C2H5OH(); + Serial.print("The concentration of C2H5OH is "); + if(c>=0) Serial.print(c); + else Serial.print("invalid"); + Serial.println(" ppm"); + + delay(1000); + Serial.println("..."); +} \ No newline at end of file diff --git a/lib/Mutichannel_Gas_Sensor/examples/ReadSensorValue_Xadow/ReadSensorValue_Xadow.ino b/lib/Mutichannel_Gas_Sensor/examples/ReadSensorValue_Xadow/ReadSensorValue_Xadow.ino new file mode 100644 index 000000000..a29813bc5 --- /dev/null +++ b/lib/Mutichannel_Gas_Sensor/examples/ReadSensorValue_Xadow/ReadSensorValue_Xadow.ino @@ -0,0 +1,89 @@ +/* + This is a demo to test gas library + This code is running on Xadow-mainboard, and the I2C slave is Xadow-gas + There is a ATmega168PA on Xadow-gas, it get sensors output and feed back to master. + the data is raw ADC value, algorithm should be realized on master. + + please feel free to write email to me if there is any question + + Jacky Zhang, Embedded Software Engineer + qi.zhang@seeed.cc + 17,mar,2015 +*/ + +#include "xadow.h" +#include +#include "MutichannelGasSensor.h" + +void setup() +{ + Xadow.init(); + + Serial.begin(9600); // start serial for output + Serial.println("power on!"); + + gas.begin(0x04);//the default I2C address of the slave is 0x04 + //gas.changeI2cAddr(0x10); + //gas.doCalibrate(); + + gas.powerOn(); +} + +void loop() +{ + float c; + + c = gas.measure_NH3(); + Serial.print("The concentration of NH3 is "); + if(c>=0) Serial.print(c); + else Serial.print("invalid"); + Serial.println(" ppm"); + + c = gas.measure_CO(); + Serial.print("The concentration of CO is "); + if(c>=0) Serial.print(c); + else Serial.print("invalid"); + Serial.println(" ppm"); + + c = gas.measure_NO2(); + Serial.print("The concentration of NO2 is "); + if(c>=0) Serial.print(c); + else Serial.print("invalid"); + Serial.println(" ppm"); + + c = gas.measure_C3H8(); + Serial.print("The concentration of C3H8 is "); + if(c>=0) Serial.print(c); + else Serial.print("invalid"); + Serial.println(" ppm"); + + c = gas.measure_C4H10(); + Serial.print("The concentration of C4H10 is "); + if(c>=0) Serial.print(c); + else Serial.print("invalid"); + Serial.println(" ppm"); + + c = gas.measure_CH4(); + Serial.print("The concentration of CH4 is "); + if(c>=0) Serial.print(c); + else Serial.print("invalid"); + Serial.println(" ppm"); + + c = gas.measure_H2(); + Serial.print("The concentration of H2 is "); + if(c>=0) Serial.print(c); + else Serial.print("invalid"); + Serial.println(" ppm"); + + c = gas.measure_C2H5OH(); + Serial.print("The concentration of C2H5OH is "); + if(c>=0) Serial.print(c); + else Serial.print("invalid"); + Serial.println(" ppm"); + + Xadow.greenLed(LEDON); + delay(500); + Xadow.greenLed(LEDOFF); + delay(500); + Serial.println("..."); +} \ No newline at end of file diff --git a/lib/Mutichannel_Gas_Sensor/examples/UpdateFrimware/UpdateFrimware.ino b/lib/Mutichannel_Gas_Sensor/examples/UpdateFrimware/UpdateFrimware.ino new file mode 100644 index 000000000..c690a52df --- /dev/null +++ b/lib/Mutichannel_Gas_Sensor/examples/UpdateFrimware/UpdateFrimware.ino @@ -0,0 +1,513 @@ +// Atmega chip programmer +// Author: Nick Gammon +// Date: 22nd May 2012 +// Version: 1.17 + +// Version 1.1: Reset foundSig to -1 each time around the loop. +// Version 1.2: Put hex bootloader data into separate files +// Version 1.3: Added verify, and MD5 sums +// Version 1.4: Added signatures for ATmeag8U2/16U2/32U2 (7 May 2012) +// Version 1.5: Added signature for ATmega1284P (8 May 2012) +// Version 1.6: Allow sketches to read bootloader area (lockbyte: 0x2F) +// Version 1.7: Added choice of bootloaders for the Atmega328P (8 MHz or 16 MHz) +// Version 1.8: Output an 8 MHz clock on pin 9 +// Version 1.9: Added support for Atmega1284P, and fixed some bugs +// Version 1.10: Corrected flash size for Atmega1284P. +// Version 1.11: Added support for Atmega1280. Removed MD5SUM stuff to make room. +// Version 1.12: Added signatures for ATtiny2313A, ATtiny4313, ATtiny13 +// Version 1.13: Added signature for Atmega8A +// Version 1.14: Added bootloader for Atmega8 +// Version 1.15: Removed extraneous 0xFF from some files +// Version 1.16: Added signature for Atmega328 +// Version 1.17: Allowed for running on the Leonardo, Micro, etc. + +/* + + Copyright 2012 Nick Gammon. + + + PERMISSION TO DISTRIBUTE + + Permission is hereby granted, free of charge, to any person obtaining a copy of this software + and associated documentation files (the "Software"), to deal in the Software without restriction, + including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + + LIMITATION OF LIABILITY + + The software is provided "as is", without warranty of any kind, express or implied, + including but not limited to the warranties of merchantability, fitness for a particular + purpose and noninfringement. In no event shall the authors or copyright holders be liable + for any claim, damages or other liability, whether in an action of contract, + tort or otherwise, arising from, out of or in connection with the software + or the use or other dealings in the software. + +*/ + +#include +#include + +const unsigned long BAUD_RATE = 115200; + +const byte CLOCKOUT = 9; +const byte RESET = 10; // --> goes to reset on the target board + +#if ARDUINO < 100 +const byte SCK = 13; // SPI clock +#endif + +// number of items in an array +#define NUMITEMS(arg) ((unsigned int) (sizeof (arg) / sizeof (arg [0]))) + +// programming commands to send via SPI to the chip +enum { + progamEnable = 0xAC, + + // writes are preceded by progamEnable + chipErase = 0x80, + writeLockByte = 0xE0, + writeLowFuseByte = 0xA0, + writeHighFuseByte = 0xA8, + writeExtendedFuseByte = 0xA4, + + pollReady = 0xF0, + + programAcknowledge = 0x53, + + readSignatureByte = 0x30, + readCalibrationByte = 0x38, + + readLowFuseByte = 0x50, readLowFuseByteArg2 = 0x00, + readExtendedFuseByte = 0x50, readExtendedFuseByteArg2 = 0x08, + readHighFuseByte = 0x58, readHighFuseByteArg2 = 0x08, + readLockByte = 0x58, readLockByteArg2 = 0x00, + + readProgramMemory = 0x20, + writeProgramMemory = 0x4C, + loadExtendedAddressByte = 0x4D, + loadProgramMemory = 0x40, + +}; // end of enum + +// structure to hold signature and other relevant data about each chip +typedef struct { + byte sig [3]; + char * desc; + unsigned long flashSize; + unsigned int baseBootSize; + const byte * bootloader; + unsigned long loaderStart; // bytes + unsigned int loaderLength; // bytes + unsigned long pageSize; // bytes + byte lowFuse, highFuse, extFuse, lockByte; +} signatureType; + +const unsigned long kb = 1024; + +// hex bootloader data +#include "bootloader_atmega168.h" + +// see Atmega328 datasheet page 298 +signatureType signatures [] = +{ + // signature description flash size bootloader size + + // Attiny84 family + { { 0x1E, 0x91, 0x0B }, "ATtiny24", 2 * kb, 0 }, + { { 0x1E, 0x92, 0x07 }, "ATtiny44", 4 * kb, 0 }, + { { 0x1E, 0x93, 0x0C }, "ATtiny84", 8 * kb, 0 }, + + // Attiny85 family + { { 0x1E, 0x91, 0x08 }, "ATtiny25", 2 * kb, 0 }, + { { 0x1E, 0x92, 0x06 }, "ATtiny45", 4 * kb, 0 }, + { { 0x1E, 0x93, 0x0B }, "ATtiny85", 8 * kb, 0 }, + + // Atmega328 family + { { 0x1E, 0x92, 0x0A }, "ATmega48PA", 4 * kb, 0 }, + { { 0x1E, 0x93, 0x0F }, "ATmega88PA", 8 * kb, 256 }, + { { 0x1E, 0x94, 0x0B }, "ATmega168PA", 16 * kb, 256, + atmega168_optiboot, // loader image + //0x3E00, // start address + 0x0, + sizeof atmega168_optiboot, + 128, // page size (for committing) + 0xC6, // fuse low byte: external full-swing crystal + 0xde, // fuse high byte: SPI enable, brown-out detection at 2.7V + 0xf8, // fuse extended byte: boot into bootloader, 512 byte bootloader + 0xcf }, // lock bits: SPM is not allowed to write to the Boot Loader section. +}; // end of signatures + +// if signature found in above table, this is its index +int foundSig = -1; +byte lastAddressMSB = 0; + +// execute one programming instruction ... b1 is command, b2, b3, b4 are arguments +// processor may return a result on the 4th transfer, this is returned. +byte program (const byte b1, const byte b2 = 0, const byte b3 = 0, const byte b4 = 0) +{ + SPI.transfer (b1); + SPI.transfer (b2); + SPI.transfer (b3); + return SPI.transfer (b4); +} // end of program + +// read a byte from flash memory +byte readFlash (unsigned long addr) +{ + byte high = (addr & 1) ? 0x08 : 0; // set if high byte wanted + addr >>= 1; // turn into word address + + // set the extended (most significant) address byte if necessary + byte MSB = (addr >> 16) & 0xFF; + if (MSB != lastAddressMSB) + { + program (loadExtendedAddressByte, 0, MSB); + lastAddressMSB = MSB; + } // end if different MSB + + return program (readProgramMemory | high, highByte (addr), lowByte (addr)); +} // end of readFlash + +// write a byte to the flash memory buffer (ready for committing) +byte writeFlash (unsigned long addr, const byte data) +{ + byte high = (addr & 1) ? 0x08 : 0; // set if high byte wanted + addr >>= 1; // turn into word address + program (loadProgramMemory | high, 0, lowByte (addr), data); +} // end of writeFlash + +// show a byte in hex with leading zero and optional newline +void showHex (const byte b, const boolean newline = false, const boolean show0x = true) +{ + if (show0x) + Serial.print (F("0x")); + // try to avoid using sprintf + char buf [4] = { ((b >> 4) & 0x0F) | '0', (b & 0x0F) | '0', ' ' , 0 }; + if (buf [0] > '9') + buf [0] += 7; + if (buf [1] > '9') + buf [1] += 7; + Serial.print (buf); + if (newline) + Serial.println (); +} // end of showHex + +// convert a boolean to Yes/No +void showYesNo (const boolean b, const boolean newline = false) +{ + if (b) + Serial.print (F("Yes")); + else + Serial.print (F("No")); + if (newline) + Serial.println (); +} // end of showYesNo + +// poll the target device until it is ready to be programmed +void pollUntilReady () +{ + while ((program (pollReady) & 1) == 1) + {} // wait till ready +} // end of pollUntilReady + +// commit page +void commitPage (unsigned long addr) +{ + //Serial.print (F("Committing page starting at 0x")); + //Serial.println (addr, HEX); + + addr >>= 1; // turn into word address + + // set the extended (most significant) address byte if necessary + byte MSB = (addr >> 16) & 0xFF; + if (MSB != lastAddressMSB) + { + program (loadExtendedAddressByte, 0, MSB); + lastAddressMSB = MSB; + } // end if different MSB + + program (writeProgramMemory, highByte (addr), lowByte (addr)); + pollUntilReady (); +} // end of commitPage + +// write specified value to specified fuse/lock byte +void writeFuse (const byte newValue, const byte instruction) +{ + if (newValue == 0) + return; // ignore + + program (progamEnable, instruction, 0, newValue); + pollUntilReady (); +} // end of writeFuse + +void getFuseBytes () +{ + Serial.print (F("LFuse = ")); + showHex (program (readLowFuseByte, readLowFuseByteArg2), true); + Serial.print (F("HFuse = ")); + showHex (program (readHighFuseByte, readHighFuseByteArg2), true); + Serial.print (F("EFuse = ")); + showHex (program (readExtendedFuseByte, readExtendedFuseByteArg2), true); + Serial.print (F("Lock byte = ")); + showHex (program (readLockByte, readLockByteArg2), true); + Serial.print ("Clock calibration = "); + showHex (program (readCalibrationByte), true); +} // end of getFuseBytes + +// burn the bootloader to the target device +void writeBootloader () +{ + + if (signatures [foundSig].bootloader == 0) + { + Serial.println (F("No bootloader support for this device.")); + return; + } // end if + + int i; + + byte lFuse = program (readLowFuseByte, readLowFuseByteArg2); + + byte newlFuse = signatures [foundSig].lowFuse; + byte newhFuse = signatures [foundSig].highFuse; + byte newextFuse = signatures [foundSig].extFuse; + byte newlockByte = signatures [foundSig].lockByte; + + unsigned long addr = signatures [foundSig].loaderStart; + unsigned int len = signatures [foundSig].loaderLength; + unsigned long pagesize = signatures [foundSig].pageSize; + unsigned long pagemask = ~(pagesize - 1); + const byte * bootloader = signatures [foundSig].bootloader; + + + Serial.print (F("Bootloader address = 0x")); + Serial.println (addr, HEX); + Serial.print (F("Bootloader length = ")); + Serial.print (len); + Serial.println (F(" bytes.")); + + byte subcommand = 'U'; + + // Atmega328P or Atmega328 + if (signatures [foundSig].sig [0] == 0x1E && + signatures [foundSig].sig [1] == 0x95 && + (signatures [foundSig].sig [2] == 0x0F || signatures [foundSig].sig [2] == 0x14) + ) + { + Serial.println (F("Type 'L' to use Lilypad (8 MHz) loader, or 'U' for Uno (16 MHz) loader ...")); + do + { + subcommand = toupper (Serial.read ()); + } while (subcommand != 'L' && subcommand != 'U'); + + if (subcommand == 'L') // use internal 8 MHz clock + { + Serial.println (F("Using Lilypad 8 MHz loader.")); + bootloader = atmega168_optiboot; + newlFuse = 0xE2; // internal 8 MHz oscillator + newhFuse = 0xDA; // 2048 byte bootloader, SPI enabled + addr = 0x7800; + len = sizeof atmega168_optiboot; + } // end of using the 8 MHz clock + else + Serial.println (F("Using Uno Optiboot 16 MHz loader.")); + } // end of being Atmega328P + + unsigned long oldPage = addr & pagemask; + + Serial.println (F("Type 'V' to verify, or 'G' to program the chip with the bootloader ...")); + char command; + do + { + command = toupper (Serial.read ()); + } while (command != 'G' && command != 'V'); + + if (command == 'G') + { + Serial.println (F("Erasing chip ...")); + program (progamEnable, chipErase); // erase it + pollUntilReady (); + Serial.println (F("Writing bootloader ...")); + for (i = 0; i < len; i += 2) + { + unsigned long thisPage = (addr + i) & pagemask; + // page changed? commit old one + if (thisPage != oldPage) + { + commitPage (oldPage); + oldPage = thisPage; + } + + unsigned char c1 = pgm_read_byte(bootloader + i); + unsigned char c2 = pgm_read_byte(bootloader + i+1); + + writeFlash (addr + i, c1); + writeFlash (addr + i + 1, c2); + } // end while doing each word + + Serial.println(); + + // commit final page + commitPage (oldPage); + Serial.println ("Written."); + } // end if programming + + Serial.println (F("Verifying ...")); + + // count errors + unsigned int errors = 0; + // check each byte + for (i = 0; i < signatures [foundSig].loaderLength; i++) + { + //if(i==0)Serial.print(" "); + byte found = readFlash (addr + i); + + byte expected = pgm_read_byte(bootloader + i); + if (found != expected) + { + if (errors <= 100) + { + Serial.print (F("Verification error at address ")); + Serial.print (addr + i, HEX); + Serial.print (F(". Got: ")); + showHex (found); + Serial.print (F(" Expected: ")); + showHex (expected, true); + } // end of haven't shown 100 errors yet + errors++; + } // end if error + } // end of for + + Serial.println("\r\n"); + if (errors == 0) + Serial.println (F("No errors found.")); + else + { + Serial.print (errors, DEC); + Serial.println (F(" verification error(s).")); + if (errors > 100) + Serial.println (F("First 100 shown.")); + return; // don't change fuses if errors + } // end if + + if (command == 'G') + { + Serial.println (F("Writing fuses ...")); + + writeFuse (newlFuse, writeLowFuseByte); + writeFuse (newhFuse, writeHighFuseByte); + writeFuse (newextFuse, writeExtendedFuseByte); + writeFuse (newlockByte, writeLockByte); + + // confirm them + getFuseBytes (); + } // end if programming + + Serial.println (F("Done.")); + +} // end of writeBootloader + + +void startProgramming () +{ + byte confirm; + pinMode (RESET, OUTPUT); + pinMode (SCK, OUTPUT); + + // we are in sync if we get back programAcknowledge on the third byte + do + { + delay (100); + // ensure SCK low + digitalWrite (SCK, LOW); + // then pulse reset, see page 309 of datasheet + digitalWrite (RESET, HIGH); + delay (1); // pulse for at least 2 clock cycles + digitalWrite (RESET, LOW); + delay (25); // wait at least 20 mS + SPI.transfer (progamEnable); + SPI.transfer (programAcknowledge); + confirm = SPI.transfer (0); + SPI.transfer (0); + } while (confirm != programAcknowledge); + + Serial.println (F("Entered programming mode OK.")); +} // end of startProgramming + +void getSignature () +{ + foundSig = -1; + lastAddressMSB = 0; + + byte sig [3]; + Serial.print (F("Signature = ")); + for (byte i = 0; i < 3; i++) + { + sig [i] = program (readSignatureByte, 0, i); + showHex (sig [i]); + } // end for each signature byte + Serial.println (); + + for (int j = 0; j < NUMITEMS (signatures); j++) + { + if (memcmp (sig, signatures [j].sig, sizeof sig) == 0) + { + foundSig = j; + Serial.print (F("Processor = ")); + Serial.println (signatures [j].desc); + Serial.print (F("Flash memory size = ")); + Serial.print (signatures [j].flashSize, DEC); + Serial.println (F(" bytes.")); + return; + } // end of signature found + } // end of for each signature + + Serial.println (F("Unrecogized signature.")); +} // end of getSignature + +void setup () +{ + Serial.begin (BAUD_RATE); + while (!Serial) ; // for Leonardo, Micro etc. + Serial.println (); + Serial.println (F("Atmega chip programmer.")); + Serial.println (F("Written by Nick Gammon.")); + + digitalWrite (RESET, HIGH); // ensure SS stays high for now + SPI.begin (); + + // slow down SPI for benefit of slower processors like the Attiny + SPI.setClockDivider (SPI_CLOCK_DIV64); + + pinMode (CLOCKOUT, OUTPUT); + + // set up Timer 1 + TCCR1A = _BV (COM1A0); // toggle OC1A on Compare Match + TCCR1B = _BV(WGM12) | _BV(CS10); // CTC, no prescaling + OCR1A = 0; // output every cycle + +} // end of setup + +void loop () +{ + startProgramming (); + getSignature (); + getFuseBytes (); + + // if we found a signature try to write a bootloader + if (foundSig != -1) + writeBootloader (); + + // release reset + digitalWrite (RESET, HIGH); + + Serial.println (F("Type 'C' when ready to continue with another chip ...")); + while (toupper (Serial.read ()) != 'C') + {} + +} // end of loop \ No newline at end of file diff --git a/lib/Mutichannel_Gas_Sensor/examples/UpdateFrimware/bootloader_atmega168.h b/lib/Mutichannel_Gas_Sensor/examples/UpdateFrimware/bootloader_atmega168.h new file mode 100644 index 000000000..d994914f8 --- /dev/null +++ b/lib/Mutichannel_Gas_Sensor/examples/UpdateFrimware/bootloader_atmega168.h @@ -0,0 +1,1028 @@ +// optiboot_atmega168.hex +// MD5 sum = 3A 89 30 4B 15 F5 BB 11 AA E6 E6 DC 7C F5 91 35 +const byte PROGMEM atmega168_optiboot [] = { + 0x0C, 0x94, 0x66, 0x00, 0x0C, 0x94, 0x8E, 0x00, 0x0C, 0x94, 0x8E, 0x00, 0x0C, 0x94, 0x8E, 0x00, + 0x0C, 0x94, 0x8E, 0x00, 0x0C, 0x94, 0x8E, 0x00, 0x0C, 0x94, 0x8E, 0x00, 0x0C, 0x94, 0x8E, 0x00, + 0x0C, 0x94, 0x8E, 0x00, 0x0C, 0x94, 0x8E, 0x00, 0x0C, 0x94, 0x8E, 0x00, 0x0C, 0x94, 0x8E, 0x00, + 0x0C, 0x94, 0x8E, 0x00, 0x0C, 0x94, 0x8E, 0x00, 0x0C, 0x94, 0x8E, 0x00, 0x0C, 0x94, 0x8E, 0x00, + 0x0C, 0x94, 0x89, 0x05, 0x0C, 0x94, 0x8E, 0x00, 0x0C, 0x94, 0x8E, 0x00, 0x0C, 0x94, 0x8E, 0x00, + 0x0C, 0x94, 0x8E, 0x00, 0x0C, 0x94, 0x8E, 0x00, 0x0C, 0x94, 0x8E, 0x00, 0x0C, 0x94, 0x8E, 0x00, + 0x0C, 0x94, 0x5C, 0x04, 0x0C, 0x94, 0x8E, 0x00, 0xA1, 0x02, 0xA4, 0x02, 0xA9, 0x02, 0xAE, 0x02, + 0x13, 0x03, 0xB3, 0x02, 0x13, 0x03, 0xC4, 0x02, 0xE5, 0x02, 0x00, 0x00, 0x00, 0x08, 0x00, 0x02, + 0x01, 0x00, 0x00, 0x03, 0x04, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, + 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x01, 0x02, 0x04, 0x08, + 0x10, 0x20, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x25, 0x00, 0x28, 0x00, 0x2B, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x24, 0x00, 0x27, 0x00, 0x2A, 0x00, 0x03, 0x04, 0x11, 0x24, 0x1F, 0xBE, + 0xCF, 0xEF, 0xD4, 0xE0, 0xDE, 0xBF, 0xCD, 0xBF, 0x11, 0xE0, 0xA0, 0xE0, 0xB1, 0xE0, 0xE6, 0xEB, + 0xFE, 0xE0, 0x02, 0xC0, 0x05, 0x90, 0x0D, 0x92, 0xA2, 0x31, 0xB1, 0x07, 0xD9, 0xF7, 0x22, 0xE0, + 0xA2, 0xE1, 0xB1, 0xE0, 0x01, 0xC0, 0x1D, 0x92, 0xA3, 0x30, 0xB2, 0x07, 0xE1, 0xF7, 0x10, 0xE0, + 0xCC, 0xEC, 0xD0, 0xE0, 0x04, 0xC0, 0x22, 0x97, 0xFE, 0x01, 0x0E, 0x94, 0x3F, 0x07, 0xCA, 0x3C, + 0xD1, 0x07, 0xC9, 0xF7, 0x0E, 0x94, 0x2D, 0x07, 0x0C, 0x94, 0x59, 0x07, 0x0C, 0x94, 0x00, 0x00, + 0x0C, 0x94, 0x43, 0x07, 0x1F, 0x93, 0xCF, 0x93, 0xDF, 0x93, 0xEC, 0x01, 0x16, 0x2F, 0x67, 0x2F, + 0x0E, 0x94, 0x4B, 0x07, 0x61, 0x2F, 0xCE, 0x01, 0x01, 0x96, 0xDF, 0x91, 0xCF, 0x91, 0x1F, 0x91, + 0x0C, 0x94, 0x4B, 0x07, 0x0F, 0x93, 0x1F, 0x93, 0xCF, 0x93, 0xDF, 0x93, 0xEC, 0x01, 0x0E, 0x94, + 0x90, 0x00, 0x08, 0x2F, 0x10, 0xE0, 0x10, 0x2F, 0x00, 0x27, 0xCE, 0x01, 0x01, 0x96, 0x0E, 0x94, + 0x90, 0x00, 0x98, 0x01, 0x28, 0x0F, 0x31, 0x1D, 0xC9, 0x01, 0xDF, 0x91, 0xCF, 0x91, 0x1F, 0x91, + 0x0F, 0x91, 0x08, 0x95, 0x80, 0xE0, 0x90, 0xE0, 0x0E, 0x94, 0xA2, 0x00, 0x86, 0x36, 0x94, 0x40, + 0xB1, 0xF1, 0x66, 0xE6, 0x74, 0xE0, 0x80, 0xE0, 0x90, 0xE0, 0x0E, 0x94, 0x92, 0x00, 0x6C, 0xE5, + 0x73, 0xE0, 0x82, 0xE0, 0x90, 0xE0, 0x0E, 0x94, 0x92, 0x00, 0x66, 0xEB, 0x73, 0xE0, 0x84, 0xE0, + 0x90, 0xE0, 0x0E, 0x94, 0x92, 0x00, 0x6B, 0xE9, 0x70, 0xE0, 0x86, 0xE0, 0x90, 0xE0, 0x0E, 0x94, + 0x92, 0x00, 0x6C, 0xE5, 0x73, 0xE0, 0x88, 0xE0, 0x90, 0xE0, 0x0E, 0x94, 0x92, 0x00, 0x66, 0xEB, + 0x73, 0xE0, 0x8A, 0xE0, 0x90, 0xE0, 0x0E, 0x94, 0x92, 0x00, 0x6B, 0xE9, 0x70, 0xE0, 0x8C, 0xE0, + 0x90, 0xE0, 0x0E, 0x94, 0x92, 0x00, 0x60, 0xE0, 0x70, 0xE0, 0x8E, 0xE0, 0x90, 0xE0, 0x0E, 0x94, + 0x92, 0x00, 0x64, 0xE0, 0x70, 0xE0, 0x84, 0xE1, 0x90, 0xE0, 0x0C, 0x94, 0x92, 0x00, 0x08, 0x95, + 0xCF, 0x92, 0xDF, 0x92, 0xEF, 0x92, 0xFF, 0x92, 0x1F, 0x93, 0xCF, 0x93, 0xDF, 0x93, 0x18, 0x2F, + 0xC0, 0xE4, 0xD0, 0xE0, 0xC1, 0x2C, 0xD1, 0x2C, 0x76, 0x01, 0x81, 0x2F, 0x0E, 0x94, 0x77, 0x06, + 0xAC, 0x01, 0x66, 0x27, 0x57, 0xFD, 0x60, 0x95, 0x76, 0x2F, 0xC4, 0x0E, 0xD5, 0x1E, 0xE6, 0x1E, + 0xF7, 0x1E, 0x21, 0x97, 0x91, 0xF7, 0xD7, 0x01, 0xC6, 0x01, 0x26, 0xE0, 0xB5, 0x95, 0xA7, 0x95, + 0x97, 0x95, 0x87, 0x95, 0x2A, 0x95, 0xD1, 0xF7, 0xDF, 0x91, 0xCF, 0x91, 0x1F, 0x91, 0xFF, 0x90, + 0xEF, 0x90, 0xDF, 0x90, 0xCF, 0x90, 0x08, 0x95, 0x0F, 0x93, 0x1F, 0x93, 0x80, 0x91, 0x22, 0x01, + 0x81, 0x11, 0x0D, 0xC0, 0x0E, 0x94, 0xD3, 0x05, 0x60, 0x93, 0x12, 0x01, 0x70, 0x93, 0x13, 0x01, + 0x80, 0x93, 0x14, 0x01, 0x90, 0x93, 0x15, 0x01, 0x81, 0xE0, 0x80, 0x93, 0x22, 0x01, 0x0E, 0x94, + 0xD3, 0x05, 0x00, 0x91, 0x12, 0x01, 0x10, 0x91, 0x13, 0x01, 0x20, 0x91, 0x14, 0x01, 0x30, 0x91, + 0x15, 0x01, 0x60, 0x1B, 0x71, 0x0B, 0x82, 0x0B, 0x93, 0x0B, 0x68, 0x3E, 0x73, 0x40, 0x81, 0x05, + 0x91, 0x05, 0xB0, 0xF1, 0x0E, 0x94, 0xD3, 0x05, 0x60, 0x93, 0x12, 0x01, 0x70, 0x93, 0x13, 0x01, + 0x80, 0x93, 0x14, 0x01, 0x90, 0x93, 0x15, 0x01, 0x8E, 0xE0, 0x90, 0xE0, 0x0E, 0x94, 0xF8, 0x00, + 0x90, 0x93, 0x35, 0x01, 0x80, 0x93, 0x34, 0x01, 0x8F, 0xE0, 0x90, 0xE0, 0x0E, 0x94, 0xF8, 0x00, + 0x90, 0x93, 0x33, 0x01, 0x80, 0x93, 0x32, 0x01, 0x80, 0xE1, 0x90, 0xE0, 0x0E, 0x94, 0xF8, 0x00, + 0x80, 0x93, 0x30, 0x01, 0x90, 0x93, 0x31, 0x01, 0x20, 0x91, 0x34, 0x01, 0x30, 0x91, 0x35, 0x01, + 0x30, 0x93, 0x2A, 0x01, 0x20, 0x93, 0x2B, 0x01, 0x20, 0x91, 0x32, 0x01, 0x30, 0x91, 0x33, 0x01, + 0x30, 0x93, 0x2C, 0x01, 0x20, 0x93, 0x2D, 0x01, 0x90, 0x93, 0x2E, 0x01, 0x80, 0x93, 0x2F, 0x01, + 0x1F, 0x91, 0x0F, 0x91, 0x08, 0x95, 0xCF, 0x93, 0xDF, 0x93, 0x61, 0xE0, 0x88, 0xE0, 0x0E, 0x94, + 0xBD, 0x06, 0x61, 0xE0, 0x88, 0xE0, 0x0E, 0x94, 0xF6, 0x06, 0x61, 0xE0, 0x89, 0xE0, 0x0E, 0x94, + 0xBD, 0x06, 0x0E, 0x94, 0xBA, 0x00, 0x84, 0xE1, 0x90, 0xE0, 0x0E, 0x94, 0xA2, 0x00, 0x80, 0x93, + 0x36, 0x01, 0xC5, 0xE0, 0xD0, 0xE0, 0x60, 0xE0, 0x89, 0xE0, 0x0E, 0x94, 0xF6, 0x06, 0x64, 0xE6, + 0x70, 0xE0, 0x80, 0xE0, 0x90, 0xE0, 0x0E, 0x94, 0x02, 0x06, 0x61, 0xE0, 0x89, 0xE0, 0x0E, 0x94, + 0xF6, 0x06, 0x64, 0xE6, 0x70, 0xE0, 0x80, 0xE0, 0x90, 0xE0, 0x0E, 0x94, 0x02, 0x06, 0x21, 0x97, + 0x51, 0xF7, 0x60, 0x91, 0x36, 0x01, 0x87, 0xE3, 0x91, 0xE0, 0x0E, 0x94, 0xE6, 0x03, 0x67, 0xEC, + 0x71, 0xE0, 0x87, 0xE3, 0x91, 0xE0, 0x0E, 0x94, 0xF9, 0x03, 0x62, 0xE9, 0x72, 0xE0, 0x87, 0xE3, + 0x91, 0xE0, 0xDF, 0x91, 0xCF, 0x91, 0x0C, 0x94, 0xFE, 0x03, 0x0C, 0x94, 0x24, 0x01, 0xBF, 0x92, + 0xCF, 0x92, 0xDF, 0x92, 0xEF, 0x92, 0xFF, 0x92, 0x0F, 0x93, 0x1F, 0x93, 0xCF, 0x93, 0xDF, 0x93, + 0x00, 0xD0, 0x00, 0xD0, 0x00, 0xD0, 0xCD, 0xB7, 0xDE, 0xB7, 0x81, 0x30, 0x91, 0x05, 0x39, 0xF4, + 0x87, 0xE3, 0x91, 0xE0, 0x0E, 0x94, 0x1E, 0x03, 0x80, 0x93, 0x21, 0x01, 0xA3, 0xC0, 0x82, 0x30, + 0x91, 0x05, 0x09, 0xF0, 0x56, 0xC0, 0x87, 0xE3, 0x91, 0xE0, 0x0E, 0x94, 0x1E, 0x03, 0x80, 0x93, + 0x21, 0x01, 0x87, 0xE3, 0x91, 0xE0, 0x0E, 0x94, 0x1E, 0x03, 0x80, 0x93, 0x20, 0x01, 0x30, 0x91, + 0x21, 0x01, 0x35, 0x30, 0xE9, 0xF4, 0x80, 0x93, 0x36, 0x01, 0xBC, 0x01, 0x77, 0x27, 0x84, 0xE1, + 0x90, 0xE0, 0x0E, 0x94, 0x92, 0x00, 0x60, 0x91, 0x36, 0x01, 0x87, 0xE3, 0x91, 0xE0, 0x26, 0x96, + 0x0F, 0xB6, 0xF8, 0x94, 0xDE, 0xBF, 0x0F, 0xBE, 0xCD, 0xBF, 0xDF, 0x91, 0xCF, 0x91, 0x1F, 0x91, + 0x0F, 0x91, 0xFF, 0x90, 0xEF, 0x90, 0xDF, 0x90, 0xCF, 0x90, 0xBF, 0x90, 0x0C, 0x94, 0xE6, 0x03, + 0x3A, 0x30, 0xD1, 0xF4, 0x81, 0x11, 0x02, 0xC0, 0x61, 0xE0, 0x04, 0xC0, 0x81, 0x30, 0x09, 0xF0, + 0x69, 0xC0, 0x60, 0xE0, 0x89, 0xE0, 0x26, 0x96, 0x0F, 0xB6, 0xF8, 0x94, 0xDE, 0xBF, 0x0F, 0xBE, + 0xCD, 0xBF, 0xDF, 0x91, 0xCF, 0x91, 0x1F, 0x91, 0x0F, 0x91, 0xFF, 0x90, 0xEF, 0x90, 0xDF, 0x90, + 0xCF, 0x90, 0xBF, 0x90, 0x0C, 0x94, 0xF6, 0x06, 0x3B, 0x30, 0x09, 0xF0, 0x53, 0xC0, 0x81, 0x11, + 0x02, 0xC0, 0x60, 0xE0, 0x04, 0xC0, 0x81, 0x30, 0x09, 0xF0, 0x4C, 0xC0, 0x61, 0xE0, 0x88, 0xE0, + 0xE2, 0xCF, 0x07, 0x97, 0x09, 0xF0, 0x46, 0xC0, 0x87, 0xE3, 0x91, 0xE0, 0x0E, 0x94, 0x1E, 0x03, + 0x80, 0x93, 0x21, 0x01, 0x8E, 0x01, 0x0F, 0x5F, 0x1F, 0x4F, 0x6E, 0x01, 0x87, 0xE0, 0xC8, 0x0E, + 0xD1, 0x1C, 0x87, 0xE3, 0x91, 0xE0, 0x0E, 0x94, 0x1E, 0x03, 0xB8, 0x2E, 0x87, 0xE3, 0x91, 0xE0, + 0x0E, 0x94, 0x1E, 0x03, 0xFB, 0x2C, 0xE1, 0x2C, 0x8E, 0x0D, 0x9F, 0x1D, 0xF8, 0x01, 0x81, 0x93, + 0x91, 0x93, 0x8F, 0x01, 0xEC, 0x15, 0xFD, 0x05, 0x61, 0xF7, 0x80, 0x91, 0x21, 0x01, 0x87, 0x30, + 0x09, 0xF5, 0x69, 0x81, 0x7A, 0x81, 0x88, 0xE0, 0x90, 0xE0, 0x0E, 0x94, 0x92, 0x00, 0x6B, 0x81, + 0x7C, 0x81, 0x8A, 0xE0, 0x90, 0xE0, 0x0E, 0x94, 0x92, 0x00, 0x6D, 0x81, 0x7E, 0x81, 0x8C, 0xE0, + 0x90, 0xE0, 0x26, 0x96, 0x0F, 0xB6, 0xF8, 0x94, 0xDE, 0xBF, 0x0F, 0xBE, 0xCD, 0xBF, 0xDF, 0x91, + 0xCF, 0x91, 0x1F, 0x91, 0x0F, 0x91, 0xFF, 0x90, 0xEF, 0x90, 0xDF, 0x90, 0xCF, 0x90, 0xBF, 0x90, + 0x0C, 0x94, 0x92, 0x00, 0x26, 0x96, 0x0F, 0xB6, 0xF8, 0x94, 0xDE, 0xBF, 0x0F, 0xBE, 0xCD, 0xBF, + 0xDF, 0x91, 0xCF, 0x91, 0x1F, 0x91, 0x0F, 0x91, 0xFF, 0x90, 0xEF, 0x90, 0xDF, 0x90, 0xCF, 0x90, + 0xBF, 0x90, 0x08, 0x95, 0xCF, 0x93, 0xDF, 0x93, 0x80, 0x91, 0x21, 0x01, 0x90, 0xE0, 0xFC, 0x01, + 0x31, 0x97, 0xE9, 0x30, 0xF1, 0x05, 0x08, 0xF0, 0x76, 0xC0, 0xEC, 0x5C, 0xFF, 0x4F, 0x0C, 0x94, + 0x3D, 0x07, 0x42, 0xE0, 0x50, 0xE0, 0x0C, 0xC0, 0x42, 0xE0, 0x50, 0xE0, 0x6C, 0xE2, 0x71, 0xE0, + 0x64, 0xC0, 0x42, 0xE0, 0x50, 0xE0, 0x6E, 0xE2, 0x71, 0xE0, 0x5F, 0xC0, 0x46, 0xE0, 0x50, 0xE0, + 0x6A, 0xE2, 0x71, 0xE0, 0x5A, 0xC0, 0xC0, 0x91, 0x20, 0x01, 0xD0, 0xE0, 0xCE, 0x01, 0x0E, 0x94, + 0x90, 0x00, 0x80, 0x93, 0x16, 0x01, 0xCE, 0x01, 0x01, 0x96, 0x0E, 0x94, 0x90, 0x00, 0x80, 0x93, + 0x17, 0x01, 0x42, 0xE0, 0x50, 0xE0, 0x47, 0xC0, 0x88, 0xE0, 0x90, 0xE0, 0x0E, 0x94, 0x90, 0x00, + 0x80, 0x93, 0x16, 0x01, 0x89, 0xE0, 0x90, 0xE0, 0x0E, 0x94, 0x90, 0x00, 0x80, 0x93, 0x17, 0x01, + 0x8A, 0xE0, 0x90, 0xE0, 0x0E, 0x94, 0x90, 0x00, 0x80, 0x93, 0x18, 0x01, 0x8B, 0xE0, 0x90, 0xE0, + 0x0E, 0x94, 0x90, 0x00, 0x80, 0x93, 0x19, 0x01, 0x8C, 0xE0, 0x90, 0xE0, 0x0E, 0x94, 0x90, 0x00, + 0x80, 0x93, 0x1A, 0x01, 0x8D, 0xE0, 0x90, 0xE0, 0x20, 0xC0, 0x82, 0xE0, 0x90, 0xE0, 0x0E, 0x94, + 0x90, 0x00, 0x80, 0x93, 0x16, 0x01, 0x83, 0xE0, 0x90, 0xE0, 0x0E, 0x94, 0x90, 0x00, 0x80, 0x93, + 0x17, 0x01, 0x84, 0xE0, 0x90, 0xE0, 0x0E, 0x94, 0x90, 0x00, 0x80, 0x93, 0x18, 0x01, 0x85, 0xE0, + 0x90, 0xE0, 0x0E, 0x94, 0x90, 0x00, 0x80, 0x93, 0x19, 0x01, 0x86, 0xE0, 0x90, 0xE0, 0x0E, 0x94, + 0x90, 0x00, 0x80, 0x93, 0x1A, 0x01, 0x87, 0xE0, 0x90, 0xE0, 0x0E, 0x94, 0x90, 0x00, 0x80, 0x93, + 0x1B, 0x01, 0x46, 0xE0, 0x50, 0xE0, 0x66, 0xE1, 0x71, 0xE0, 0x87, 0xE3, 0x91, 0xE0, 0xDF, 0x91, + 0xCF, 0x91, 0x0C, 0x94, 0x70, 0x03, 0xDF, 0x91, 0xCF, 0x91, 0x08, 0x95, 0x80, 0x91, 0x6A, 0x01, + 0x90, 0xE0, 0x20, 0x91, 0x6B, 0x01, 0x82, 0x1B, 0x91, 0x09, 0x08, 0x95, 0x20, 0x91, 0x6B, 0x01, + 0x80, 0x91, 0x6A, 0x01, 0x28, 0x17, 0x50, 0xF4, 0xE2, 0x2F, 0xF0, 0xE0, 0xE4, 0x59, 0xFE, 0x4F, + 0x80, 0x81, 0x90, 0xE0, 0x2F, 0x5F, 0x20, 0x93, 0x6B, 0x01, 0x08, 0x95, 0x8F, 0xEF, 0x9F, 0xEF, + 0x08, 0x95, 0xE0, 0x91, 0x6B, 0x01, 0x80, 0x91, 0x6A, 0x01, 0xE8, 0x17, 0x30, 0xF4, 0xF0, 0xE0, + 0xE4, 0x59, 0xFE, 0x4F, 0x80, 0x81, 0x90, 0xE0, 0x08, 0x95, 0x8F, 0xEF, 0x9F, 0xEF, 0x08, 0x95, + 0x08, 0x95, 0xE0, 0x91, 0x43, 0x01, 0xF0, 0x91, 0x44, 0x01, 0x30, 0x97, 0xE1, 0xF0, 0x30, 0x91, + 0x6B, 0x01, 0x20, 0x91, 0x6A, 0x01, 0x32, 0x17, 0xB0, 0xF0, 0x40, 0xE0, 0x24, 0x2F, 0x30, 0xE0, + 0x26, 0x17, 0x37, 0x07, 0x54, 0xF4, 0xDC, 0x01, 0xA2, 0x0F, 0xB3, 0x1F, 0x5C, 0x91, 0xD9, 0x01, + 0xA4, 0x59, 0xBE, 0x4F, 0x5C, 0x93, 0x4F, 0x5F, 0xF1, 0xCF, 0x10, 0x92, 0x6B, 0x01, 0x60, 0x93, + 0x6A, 0x01, 0xCB, 0x01, 0x09, 0x94, 0x08, 0x95, 0xE0, 0x91, 0x45, 0x01, 0xF0, 0x91, 0x46, 0x01, + 0x30, 0x97, 0x29, 0xF0, 0x10, 0x92, 0x49, 0x01, 0x10, 0x92, 0x48, 0x01, 0x09, 0x94, 0x08, 0x95, + 0xCF, 0x92, 0xDF, 0x92, 0xEF, 0x92, 0xFF, 0x92, 0x0F, 0x93, 0x1F, 0x93, 0xCF, 0x93, 0xDF, 0x93, + 0x7C, 0x01, 0xCB, 0x01, 0x8A, 0x01, 0x20, 0x91, 0x47, 0x01, 0x22, 0x23, 0x89, 0xF0, 0xEB, 0x01, + 0x6B, 0x01, 0xC4, 0x0E, 0xD5, 0x1E, 0xCC, 0x15, 0xDD, 0x05, 0x69, 0xF0, 0x69, 0x91, 0xD7, 0x01, + 0xED, 0x91, 0xFC, 0x91, 0x01, 0x90, 0xF0, 0x81, 0xE0, 0x2D, 0xC7, 0x01, 0x09, 0x95, 0xF3, 0xCF, + 0x64, 0x2F, 0x0E, 0x94, 0x29, 0x04, 0xC8, 0x01, 0xDF, 0x91, 0xCF, 0x91, 0x1F, 0x91, 0x0F, 0x91, + 0xFF, 0x90, 0xEF, 0x90, 0xDF, 0x90, 0xCF, 0x90, 0x08, 0x95, 0xCF, 0x93, 0xDF, 0x93, 0x1F, 0x92, + 0xCD, 0xB7, 0xDE, 0xB7, 0x69, 0x83, 0x20, 0x91, 0x47, 0x01, 0x22, 0x23, 0xD1, 0xF0, 0x20, 0x91, + 0x48, 0x01, 0x20, 0x32, 0x40, 0xF0, 0x21, 0xE0, 0x30, 0xE0, 0xFC, 0x01, 0x33, 0x83, 0x22, 0x83, + 0x80, 0xE0, 0x90, 0xE0, 0x15, 0xC0, 0x80, 0x91, 0x49, 0x01, 0xE8, 0x2F, 0xF0, 0xE0, 0xE6, 0x5B, + 0xFE, 0x4F, 0x99, 0x81, 0x90, 0x83, 0x8F, 0x5F, 0x80, 0x93, 0x49, 0x01, 0x80, 0x93, 0x48, 0x01, + 0x05, 0xC0, 0x61, 0xE0, 0xCE, 0x01, 0x01, 0x96, 0x0E, 0x94, 0x29, 0x04, 0x81, 0xE0, 0x90, 0xE0, + 0x0F, 0x90, 0xDF, 0x91, 0xCF, 0x91, 0x08, 0x95, 0xFC, 0x01, 0x13, 0x82, 0x12, 0x82, 0x48, 0xEE, + 0x53, 0xE0, 0x60, 0xE0, 0x70, 0xE0, 0x44, 0x83, 0x55, 0x83, 0x66, 0x83, 0x77, 0x83, 0x85, 0xE0, + 0x91, 0xE0, 0x91, 0x83, 0x80, 0x83, 0x08, 0x95, 0x10, 0x92, 0x6B, 0x01, 0x10, 0x92, 0x6A, 0x01, + 0x10, 0x92, 0x49, 0x01, 0x10, 0x92, 0x48, 0x01, 0x0C, 0x94, 0x07, 0x04, 0xCF, 0x93, 0xDF, 0x93, + 0xEC, 0x01, 0x86, 0x2F, 0x0E, 0x94, 0x25, 0x04, 0x84, 0xE6, 0x93, 0xE0, 0x0E, 0x94, 0x47, 0x04, + 0x81, 0xE4, 0x93, 0xE0, 0x0E, 0x94, 0x42, 0x04, 0xCE, 0x01, 0xDF, 0x91, 0xCF, 0x91, 0x0C, 0x94, + 0xDC, 0x03, 0x70, 0x93, 0x44, 0x01, 0x60, 0x93, 0x43, 0x01, 0x08, 0x95, 0x70, 0x93, 0x46, 0x01, + 0x60, 0x93, 0x45, 0x01, 0x08, 0x95, 0x87, 0xE3, 0x91, 0xE0, 0x0C, 0x94, 0xCC, 0x03, 0x10, 0x92, + 0xF9, 0x01, 0x81, 0xE0, 0x80, 0x93, 0xF7, 0x01, 0x10, 0x92, 0xF6, 0x01, 0x61, 0xE0, 0x82, 0xE1, + 0x0E, 0x94, 0xF6, 0x06, 0x61, 0xE0, 0x83, 0xE1, 0x0E, 0x94, 0xF6, 0x06, 0xE9, 0xEB, 0xF0, 0xE0, + 0x80, 0x81, 0x8E, 0x7F, 0x80, 0x83, 0x80, 0x81, 0x8D, 0x7F, 0x80, 0x83, 0x80, 0xE2, 0x80, 0x93, + 0xB8, 0x00, 0x85, 0xE4, 0x80, 0x93, 0xBC, 0x00, 0x08, 0x95, 0x88, 0x0F, 0x80, 0x93, 0xBA, 0x00, + 0x08, 0x95, 0x61, 0x32, 0x98, 0xF4, 0x20, 0x91, 0xF9, 0x01, 0x24, 0x30, 0x89, 0xF4, 0x60, 0x93, + 0xAE, 0x01, 0xFC, 0x01, 0x80, 0xEB, 0x91, 0xE0, 0xDC, 0x01, 0x2A, 0x2F, 0x28, 0x1B, 0x26, 0x17, + 0x18, 0xF4, 0x21, 0x91, 0x2D, 0x93, 0xF9, 0xCF, 0x80, 0xE0, 0x08, 0x95, 0x81, 0xE0, 0x08, 0x95, + 0x82, 0xE0, 0x08, 0x95, 0x90, 0x93, 0xF3, 0x01, 0x80, 0x93, 0xF2, 0x01, 0x08, 0x95, 0x90, 0x93, + 0xF5, 0x01, 0x80, 0x93, 0xF4, 0x01, 0x08, 0x95, 0x85, 0xED, 0x80, 0x93, 0xBC, 0x00, 0x80, 0x91, + 0xBC, 0x00, 0x84, 0xFD, 0xFC, 0xCF, 0x10, 0x92, 0xF9, 0x01, 0x08, 0x95, 0x85, 0xEC, 0x80, 0x93, + 0xBC, 0x00, 0x10, 0x92, 0xF9, 0x01, 0x08, 0x95, 0x1F, 0x92, 0x0F, 0x92, 0x0F, 0xB6, 0x0F, 0x92, + 0x11, 0x24, 0x2F, 0x93, 0x3F, 0x93, 0x4F, 0x93, 0x5F, 0x93, 0x6F, 0x93, 0x7F, 0x93, 0x8F, 0x93, + 0x9F, 0x93, 0xAF, 0x93, 0xBF, 0x93, 0xEF, 0x93, 0xFF, 0x93, 0x80, 0x91, 0xB9, 0x00, 0x88, 0x7F, + 0x80, 0x36, 0x09, 0xF4, 0x9E, 0xC0, 0x78, 0xF5, 0x88, 0x32, 0x09, 0xF4, 0x5D, 0xC0, 0x90, 0xF4, + 0x80, 0x31, 0x09, 0xF4, 0x56, 0xC0, 0x38, 0xF4, 0x88, 0x23, 0x09, 0xF4, 0xF5, 0xC0, 0x88, 0x30, + 0x09, 0xF4, 0x4F, 0xC0, 0xF5, 0xC0, 0x88, 0x31, 0x09, 0xF4, 0x4E, 0xC0, 0x80, 0x32, 0x09, 0xF4, + 0x5F, 0xC0, 0xEE, 0xC0, 0x80, 0x34, 0x09, 0xF4, 0x6A, 0xC0, 0x58, 0xF4, 0x80, 0x33, 0x09, 0xF4, + 0x57, 0xC0, 0x88, 0x33, 0x09, 0xF0, 0xE4, 0xC0, 0x80, 0x93, 0x8C, 0x01, 0x0E, 0x94, 0x56, 0x04, + 0xDF, 0xC0, 0x80, 0x35, 0x09, 0xF4, 0x4F, 0xC0, 0x88, 0x35, 0x09, 0xF4, 0x5D, 0xC0, 0x88, 0x34, + 0x09, 0xF0, 0xD6, 0xC0, 0xD3, 0xC0, 0x88, 0x39, 0x09, 0xF4, 0xC4, 0xC0, 0xA8, 0xF4, 0x88, 0x37, + 0x09, 0xF4, 0x67, 0xC0, 0x38, 0xF4, 0x88, 0x36, 0x09, 0xF4, 0x63, 0xC0, 0x80, 0x37, 0x09, 0xF4, + 0x60, 0xC0, 0xC6, 0xC0, 0x88, 0x38, 0x09, 0xF4, 0xB5, 0xC0, 0x80, 0x39, 0x09, 0xF4, 0x5F, 0xC0, + 0x80, 0x38, 0x09, 0xF0, 0xBD, 0xC0, 0x5B, 0xC0, 0x80, 0x3B, 0x09, 0xF4, 0x83, 0xC0, 0x38, 0xF4, + 0x80, 0x3A, 0x09, 0xF4, 0x66, 0xC0, 0x88, 0x3A, 0x09, 0xF4, 0x7C, 0xC0, 0xB1, 0xC0, 0x80, 0x3C, + 0x09, 0xF4, 0xA4, 0xC0, 0x88, 0x3C, 0x09, 0xF4, 0xA1, 0xC0, 0x88, 0x3B, 0x09, 0xF4, 0x87, 0xC0, + 0xA7, 0xC0, 0x80, 0x91, 0xF8, 0x01, 0x10, 0xC0, 0x90, 0x91, 0xD1, 0x01, 0x80, 0x91, 0xD0, 0x01, + 0x98, 0x17, 0x70, 0xF5, 0xE0, 0x91, 0xD1, 0x01, 0x81, 0xE0, 0x8E, 0x0F, 0x80, 0x93, 0xD1, 0x01, + 0xF0, 0xE0, 0xEE, 0x52, 0xFE, 0x4F, 0x80, 0x81, 0x80, 0x93, 0xBB, 0x00, 0x85, 0xEC, 0x83, 0xC0, + 0x80, 0x93, 0x8C, 0x01, 0x8B, 0xC0, 0xE0, 0x91, 0xD1, 0x01, 0x81, 0xE0, 0x8E, 0x0F, 0x80, 0x93, + 0xD1, 0x01, 0x80, 0x91, 0xBB, 0x00, 0xF0, 0xE0, 0xEE, 0x52, 0xFE, 0x4F, 0x80, 0x83, 0x90, 0x91, + 0xD1, 0x01, 0x80, 0x91, 0xD0, 0x01, 0x6B, 0xC0, 0xE0, 0x91, 0xD1, 0x01, 0x81, 0xE0, 0x8E, 0x0F, + 0x80, 0x93, 0xD1, 0x01, 0x80, 0x91, 0xBB, 0x00, 0xF0, 0xE0, 0xEE, 0x52, 0xFE, 0x4F, 0x80, 0x83, + 0x80, 0x91, 0xF7, 0x01, 0x81, 0x11, 0x6A, 0xC0, 0x81, 0xE0, 0x80, 0x93, 0xF6, 0x01, 0x84, 0xEA, + 0x5E, 0xC0, 0x83, 0xE0, 0x80, 0x93, 0xF9, 0x01, 0x10, 0x92, 0x8D, 0x01, 0xCF, 0xCF, 0x80, 0x91, + 0x8D, 0x01, 0x80, 0x32, 0x08, 0xF0, 0x4E, 0xC0, 0xE0, 0x91, 0x8D, 0x01, 0x81, 0xE0, 0x8E, 0x0F, + 0x80, 0x93, 0x8D, 0x01, 0x80, 0x91, 0xBB, 0x00, 0xF0, 0xE0, 0xE2, 0x57, 0xFE, 0x4F, 0x80, 0x83, + 0xBD, 0xCF, 0x0E, 0x94, 0x56, 0x04, 0x80, 0x91, 0x8D, 0x01, 0x80, 0x32, 0x30, 0xF4, 0xE0, 0x91, + 0x8D, 0x01, 0xF0, 0xE0, 0xE2, 0x57, 0xFE, 0x4F, 0x10, 0x82, 0x60, 0x91, 0x8D, 0x01, 0x70, 0xE0, + 0xE0, 0x91, 0xF2, 0x01, 0xF0, 0x91, 0xF3, 0x01, 0x8E, 0xE8, 0x91, 0xE0, 0x09, 0x95, 0x10, 0x92, + 0x8D, 0x01, 0x36, 0xC0, 0x84, 0xE0, 0x80, 0x93, 0xF9, 0x01, 0x10, 0x92, 0xAF, 0x01, 0x10, 0x92, + 0xAE, 0x01, 0xE0, 0x91, 0xF4, 0x01, 0xF0, 0x91, 0xF5, 0x01, 0x09, 0x95, 0x80, 0x91, 0xAE, 0x01, + 0x81, 0x11, 0x05, 0xC0, 0x81, 0xE0, 0x80, 0x93, 0xAE, 0x01, 0x10, 0x92, 0xB0, 0x01, 0xE0, 0x91, + 0xAF, 0x01, 0x81, 0xE0, 0x8E, 0x0F, 0x80, 0x93, 0xAF, 0x01, 0xF0, 0xE0, 0xE0, 0x55, 0xFE, 0x4F, + 0x80, 0x81, 0x80, 0x93, 0xBB, 0x00, 0x90, 0x91, 0xAF, 0x01, 0x80, 0x91, 0xAE, 0x01, 0x98, 0x17, + 0x08, 0xF4, 0x7C, 0xCF, 0x85, 0xE8, 0x80, 0x93, 0xBC, 0x00, 0x0A, 0xC0, 0x85, 0xEC, 0x80, 0x93, + 0xBC, 0x00, 0x10, 0x92, 0xF9, 0x01, 0x04, 0xC0, 0x10, 0x92, 0x8C, 0x01, 0x0E, 0x94, 0x4C, 0x04, + 0xFF, 0x91, 0xEF, 0x91, 0xBF, 0x91, 0xAF, 0x91, 0x9F, 0x91, 0x8F, 0x91, 0x7F, 0x91, 0x6F, 0x91, + 0x5F, 0x91, 0x4F, 0x91, 0x3F, 0x91, 0x2F, 0x91, 0x0F, 0x90, 0x0F, 0xBE, 0x0F, 0x90, 0x1F, 0x90, + 0x18, 0x95, 0x1F, 0x92, 0x0F, 0x92, 0x0F, 0xB6, 0x0F, 0x92, 0x11, 0x24, 0x2F, 0x93, 0x3F, 0x93, + 0x8F, 0x93, 0x9F, 0x93, 0xAF, 0x93, 0xBF, 0x93, 0x80, 0x91, 0xFB, 0x01, 0x90, 0x91, 0xFC, 0x01, + 0xA0, 0x91, 0xFD, 0x01, 0xB0, 0x91, 0xFE, 0x01, 0x30, 0x91, 0xFA, 0x01, 0x26, 0xE0, 0x23, 0x0F, + 0x2D, 0x37, 0x20, 0xF4, 0x02, 0x96, 0xA1, 0x1D, 0xB1, 0x1D, 0x05, 0xC0, 0x29, 0xE8, 0x23, 0x0F, + 0x03, 0x96, 0xA1, 0x1D, 0xB1, 0x1D, 0x20, 0x93, 0xFA, 0x01, 0x80, 0x93, 0xFB, 0x01, 0x90, 0x93, + 0xFC, 0x01, 0xA0, 0x93, 0xFD, 0x01, 0xB0, 0x93, 0xFE, 0x01, 0x80, 0x91, 0xFF, 0x01, 0x90, 0x91, + 0x00, 0x02, 0xA0, 0x91, 0x01, 0x02, 0xB0, 0x91, 0x02, 0x02, 0x01, 0x96, 0xA1, 0x1D, 0xB1, 0x1D, + 0x80, 0x93, 0xFF, 0x01, 0x90, 0x93, 0x00, 0x02, 0xA0, 0x93, 0x01, 0x02, 0xB0, 0x93, 0x02, 0x02, + 0xBF, 0x91, 0xAF, 0x91, 0x9F, 0x91, 0x8F, 0x91, 0x3F, 0x91, 0x2F, 0x91, 0x0F, 0x90, 0x0F, 0xBE, + 0x0F, 0x90, 0x1F, 0x90, 0x18, 0x95, 0x2F, 0xB7, 0xF8, 0x94, 0x60, 0x91, 0xFB, 0x01, 0x70, 0x91, + 0xFC, 0x01, 0x80, 0x91, 0xFD, 0x01, 0x90, 0x91, 0xFE, 0x01, 0x2F, 0xBF, 0x08, 0x95, 0x3F, 0xB7, + 0xF8, 0x94, 0x80, 0x91, 0xFF, 0x01, 0x90, 0x91, 0x00, 0x02, 0xA0, 0x91, 0x01, 0x02, 0xB0, 0x91, + 0x02, 0x02, 0x26, 0xB5, 0xA8, 0x9B, 0x05, 0xC0, 0x2F, 0x3F, 0x19, 0xF0, 0x01, 0x96, 0xA1, 0x1D, + 0xB1, 0x1D, 0x3F, 0xBF, 0x66, 0x27, 0x78, 0x2F, 0x89, 0x2F, 0x9A, 0x2F, 0x62, 0x0F, 0x71, 0x1D, + 0x81, 0x1D, 0x91, 0x1D, 0x43, 0xE0, 0x66, 0x0F, 0x77, 0x1F, 0x88, 0x1F, 0x99, 0x1F, 0x4A, 0x95, + 0xD1, 0xF7, 0x08, 0x95, 0x8F, 0x92, 0x9F, 0x92, 0xAF, 0x92, 0xBF, 0x92, 0xCF, 0x92, 0xDF, 0x92, + 0xEF, 0x92, 0xFF, 0x92, 0x6B, 0x01, 0x7C, 0x01, 0x0E, 0x94, 0xDF, 0x05, 0x4B, 0x01, 0x5C, 0x01, + 0xC1, 0x14, 0xD1, 0x04, 0xE1, 0x04, 0xF1, 0x04, 0xF1, 0xF0, 0x0E, 0x94, 0x3C, 0x07, 0x0E, 0x94, + 0xDF, 0x05, 0x68, 0x19, 0x79, 0x09, 0x8A, 0x09, 0x9B, 0x09, 0x68, 0x3E, 0x73, 0x40, 0x81, 0x05, + 0x91, 0x05, 0x70, 0xF3, 0x21, 0xE0, 0xC2, 0x1A, 0xD1, 0x08, 0xE1, 0x08, 0xF1, 0x08, 0x88, 0xEE, + 0x88, 0x0E, 0x83, 0xE0, 0x98, 0x1E, 0xA1, 0x1C, 0xB1, 0x1C, 0xC1, 0x14, 0xD1, 0x04, 0xE1, 0x04, + 0xF1, 0x04, 0x29, 0xF7, 0xDD, 0xCF, 0xFF, 0x90, 0xEF, 0x90, 0xDF, 0x90, 0xCF, 0x90, 0xBF, 0x90, + 0xAF, 0x90, 0x9F, 0x90, 0x8F, 0x90, 0x08, 0x95, 0x78, 0x94, 0x84, 0xB5, 0x82, 0x60, 0x84, 0xBD, + 0x84, 0xB5, 0x81, 0x60, 0x84, 0xBD, 0x85, 0xB5, 0x82, 0x60, 0x85, 0xBD, 0x85, 0xB5, 0x81, 0x60, + 0x85, 0xBD, 0xEE, 0xE6, 0xF0, 0xE0, 0x80, 0x81, 0x81, 0x60, 0x80, 0x83, 0xE1, 0xE8, 0xF0, 0xE0, + 0x10, 0x82, 0x80, 0x81, 0x82, 0x60, 0x80, 0x83, 0x80, 0x81, 0x81, 0x60, 0x80, 0x83, 0xE0, 0xE8, + 0xF0, 0xE0, 0x80, 0x81, 0x81, 0x60, 0x80, 0x83, 0xE1, 0xEB, 0xF0, 0xE0, 0x80, 0x81, 0x84, 0x60, + 0x80, 0x83, 0xE0, 0xEB, 0xF0, 0xE0, 0x80, 0x81, 0x81, 0x60, 0x80, 0x83, 0xEA, 0xE7, 0xF0, 0xE0, + 0x80, 0x81, 0x84, 0x60, 0x80, 0x83, 0x80, 0x81, 0x82, 0x60, 0x80, 0x83, 0x80, 0x81, 0x8E, 0x7F, + 0x80, 0x83, 0x80, 0x81, 0x80, 0x68, 0x80, 0x83, 0x10, 0x92, 0xC1, 0x00, 0x08, 0x95, 0x8E, 0x30, + 0x08, 0xF0, 0x8E, 0x50, 0x87, 0x70, 0x20, 0x91, 0x00, 0x01, 0x90, 0xE4, 0x29, 0x9F, 0x90, 0x01, + 0x11, 0x24, 0x82, 0x2B, 0x80, 0x93, 0x7C, 0x00, 0x80, 0x91, 0x7A, 0x00, 0x80, 0x64, 0x80, 0x93, + 0x7A, 0x00, 0x80, 0x91, 0x7A, 0x00, 0x86, 0xFD, 0xFC, 0xCF, 0x80, 0x91, 0x78, 0x00, 0x20, 0x91, + 0x79, 0x00, 0x90, 0xE0, 0x92, 0x2B, 0x08, 0x95, 0x83, 0x30, 0x81, 0xF0, 0x28, 0xF4, 0x81, 0x30, + 0x99, 0xF0, 0x82, 0x30, 0xA1, 0xF0, 0x08, 0x95, 0x87, 0x30, 0xA9, 0xF0, 0x88, 0x30, 0xB9, 0xF0, + 0x84, 0x30, 0xD1, 0xF4, 0x80, 0x91, 0x80, 0x00, 0x8F, 0x7D, 0x03, 0xC0, 0x80, 0x91, 0x80, 0x00, + 0x8F, 0x77, 0x80, 0x93, 0x80, 0x00, 0x08, 0x95, 0x84, 0xB5, 0x8F, 0x77, 0x02, 0xC0, 0x84, 0xB5, + 0x8F, 0x7D, 0x84, 0xBD, 0x08, 0x95, 0x80, 0x91, 0xB0, 0x00, 0x8F, 0x77, 0x03, 0xC0, 0x80, 0x91, + 0xB0, 0x00, 0x8F, 0x7D, 0x80, 0x93, 0xB0, 0x00, 0x08, 0x95, 0xCF, 0x93, 0xDF, 0x93, 0x90, 0xE0, + 0xFC, 0x01, 0xE2, 0x57, 0xFF, 0x4F, 0x24, 0x91, 0xFC, 0x01, 0xEE, 0x55, 0xFF, 0x4F, 0x84, 0x91, + 0x88, 0x23, 0x49, 0xF1, 0x90, 0xE0, 0x88, 0x0F, 0x99, 0x1F, 0xFC, 0x01, 0xE0, 0x54, 0xFF, 0x4F, + 0xA5, 0x91, 0xB4, 0x91, 0x8A, 0x54, 0x9F, 0x4F, 0xFC, 0x01, 0xC5, 0x91, 0xD4, 0x91, 0x9F, 0xB7, + 0x61, 0x11, 0x08, 0xC0, 0xF8, 0x94, 0x8C, 0x91, 0x20, 0x95, 0x82, 0x23, 0x8C, 0x93, 0x88, 0x81, + 0x82, 0x23, 0x0A, 0xC0, 0x62, 0x30, 0x51, 0xF4, 0xF8, 0x94, 0x8C, 0x91, 0x32, 0x2F, 0x30, 0x95, + 0x83, 0x23, 0x8C, 0x93, 0x88, 0x81, 0x82, 0x2B, 0x88, 0x83, 0x04, 0xC0, 0xF8, 0x94, 0x8C, 0x91, + 0x82, 0x2B, 0x8C, 0x93, 0x9F, 0xBF, 0xDF, 0x91, 0xCF, 0x91, 0x08, 0x95, 0x0F, 0x93, 0x1F, 0x93, + 0xCF, 0x93, 0xDF, 0x93, 0x1F, 0x92, 0xCD, 0xB7, 0xDE, 0xB7, 0x28, 0x2F, 0x30, 0xE0, 0xF9, 0x01, + 0xE6, 0x58, 0xFF, 0x4F, 0x84, 0x91, 0xF9, 0x01, 0xE2, 0x57, 0xFF, 0x4F, 0x14, 0x91, 0xF9, 0x01, + 0xEE, 0x55, 0xFF, 0x4F, 0x04, 0x91, 0x00, 0x23, 0xC9, 0xF0, 0x88, 0x23, 0x21, 0xF0, 0x69, 0x83, + 0x0E, 0x94, 0x94, 0x06, 0x69, 0x81, 0xE0, 0x2F, 0xF0, 0xE0, 0xEE, 0x0F, 0xFF, 0x1F, 0xEA, 0x54, + 0xFF, 0x4F, 0xA5, 0x91, 0xB4, 0x91, 0x9F, 0xB7, 0xF8, 0x94, 0x8C, 0x91, 0x61, 0x11, 0x03, 0xC0, + 0x10, 0x95, 0x81, 0x23, 0x01, 0xC0, 0x81, 0x2B, 0x8C, 0x93, 0x9F, 0xBF, 0x0F, 0x90, 0xDF, 0x91, + 0xCF, 0x91, 0x1F, 0x91, 0x0F, 0x91, 0x08, 0x95, 0x08, 0x95, 0x0E, 0x94, 0x3C, 0x06, 0x0E, 0x94, + 0x2C, 0x07, 0x0E, 0x94, 0x83, 0x01, 0xC0, 0xE0, 0xD0, 0xE0, 0x0E, 0x94, 0xC5, 0x01, 0x20, 0x97, + 0xE1, 0xF3, 0x0E, 0x94, 0x00, 0x00, 0xF9, 0xCF, 0x08, 0x95, 0xEE, 0x0F, 0xFF, 0x1F, 0x05, 0x90, + 0xF4, 0x91, 0xE0, 0x2D, 0x09, 0x94, 0xF9, 0x99, 0xFE, 0xCF, 0x92, 0xBD, 0x81, 0xBD, 0xF8, 0x9A, + 0x99, 0x27, 0x80, 0xB5, 0x08, 0x95, 0x26, 0x2F, 0xF9, 0x99, 0xFE, 0xCF, 0x1F, 0xBA, 0x92, 0xBD, + 0x81, 0xBD, 0x20, 0xBD, 0x0F, 0xB6, 0xF8, 0x94, 0xFA, 0x9A, 0xF9, 0x9A, 0x0F, 0xBE, 0x01, 0x96, + 0x08, 0x95, 0xF8, 0x94, 0xFF, 0xCF, 0x01, 0x00, 0x00, 0x00, 0x00, 0x9D, 0x03, 0x70, 0x03, 0x16, + 0x03, 0x1E, 0x03, 0x31, 0x03, 0x40, 0x03, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0x9F, 0xEF, 0x08, 0x95, 0x8C, 0xEE, 0x98, 0xE0, 0x89, 0x2B, 0x49, 0xF0, 0x80, 0xE0, 0x90, 0xE0, + 0x89, 0x2B, 0x29, 0xF0, 0x0E, 0x94, 0xEC, 0x08, 0x81, 0x11, 0x0C, 0x94, 0x00, 0x00, 0x08, 0x95, + 0xFC, 0x01, 0x84, 0x8D, 0xDF, 0x01, 0xA8, 0x0F, 0xB1, 0x1D, 0xA3, 0x5A, 0xBF, 0x4F, 0x2C, 0x91, + 0x84, 0x8D, 0x90, 0xE0, 0x01, 0x96, 0x8F, 0x73, 0x99, 0x27, 0x84, 0x8F, 0xA6, 0x89, 0xB7, 0x89, + 0x2C, 0x93, 0xA0, 0x89, 0xB1, 0x89, 0x8C, 0x91, 0x80, 0x64, 0x8C, 0x93, 0x93, 0x8D, 0x84, 0x8D, + 0x98, 0x13, 0x06, 0xC0, 0x02, 0x88, 0xF3, 0x89, 0xE0, 0x2D, 0x80, 0x81, 0x8F, 0x7D, 0x80, 0x83, + 0x08, 0x95, 0xCF, 0x93, 0xDF, 0x93, 0xEC, 0x01, 0x88, 0x8D, 0x88, 0x23, 0xC9, 0xF0, 0xEA, 0x89, + 0xFB, 0x89, 0x80, 0x81, 0x85, 0xFD, 0x05, 0xC0, 0xA8, 0x89, 0xB9, 0x89, 0x8C, 0x91, 0x86, 0xFD, + 0x0F, 0xC0, 0x0F, 0xB6, 0x07, 0xFC, 0xF5, 0xCF, 0x80, 0x81, 0x85, 0xFF, 0xF2, 0xCF, 0xA8, 0x89, + 0xB9, 0x89, 0x8C, 0x91, 0x85, 0xFF, 0xED, 0xCF, 0xCE, 0x01, 0x0E, 0x94, 0x90, 0x07, 0xE7, 0xCF, + 0xDF, 0x91, 0xCF, 0x91, 0x08, 0x95, 0xCF, 0x92, 0xDF, 0x92, 0xFF, 0x92, 0x0F, 0x93, 0x1F, 0x93, + 0xCF, 0x93, 0xDF, 0x93, 0x1F, 0x92, 0xCD, 0xB7, 0xDE, 0xB7, 0x6C, 0x01, 0x81, 0xE0, 0xD6, 0x01, + 0x58, 0x96, 0x8C, 0x93, 0x58, 0x97, 0x5B, 0x96, 0x9C, 0x91, 0x5B, 0x97, 0x5C, 0x96, 0x8C, 0x91, + 0x5C, 0x97, 0x98, 0x13, 0x07, 0xC0, 0x50, 0x96, 0xED, 0x91, 0xFC, 0x91, 0x51, 0x97, 0x80, 0x81, + 0x85, 0xFD, 0x2E, 0xC0, 0xF6, 0x01, 0x03, 0x8D, 0x10, 0xE0, 0x0F, 0x5F, 0x1F, 0x4F, 0x0F, 0x73, + 0x11, 0x27, 0xF0, 0x2E, 0xF6, 0x01, 0x84, 0x8D, 0xF8, 0x12, 0x11, 0xC0, 0x0F, 0xB6, 0x07, 0xFC, + 0xF9, 0xCF, 0xD6, 0x01, 0x50, 0x96, 0xED, 0x91, 0xFC, 0x91, 0x51, 0x97, 0x80, 0x81, 0x85, 0xFF, + 0xF1, 0xCF, 0xC6, 0x01, 0x69, 0x83, 0x0E, 0x94, 0x90, 0x07, 0x69, 0x81, 0xEB, 0xCF, 0x83, 0x8D, + 0xE8, 0x0F, 0xF1, 0x1D, 0xE3, 0x5A, 0xFF, 0x4F, 0x60, 0x83, 0xD6, 0x01, 0x5B, 0x96, 0x0C, 0x93, + 0x5B, 0x97, 0x52, 0x96, 0xED, 0x91, 0xFC, 0x91, 0x53, 0x97, 0x80, 0x81, 0x80, 0x62, 0x0C, 0xC0, + 0xD6, 0x01, 0x56, 0x96, 0xED, 0x91, 0xFC, 0x91, 0x57, 0x97, 0x60, 0x83, 0x50, 0x96, 0xED, 0x91, + 0xFC, 0x91, 0x51, 0x97, 0x80, 0x81, 0x80, 0x64, 0x80, 0x83, 0x81, 0xE0, 0x90, 0xE0, 0x0F, 0x90, + 0xDF, 0x91, 0xCF, 0x91, 0x1F, 0x91, 0x0F, 0x91, 0xFF, 0x90, 0xDF, 0x90, 0xCF, 0x90, 0x08, 0x95, + 0xBF, 0x92, 0xCF, 0x92, 0xDF, 0x92, 0xEF, 0x92, 0xFF, 0x92, 0xCF, 0x93, 0xDF, 0x93, 0xEC, 0x01, + 0x6A, 0x01, 0x7B, 0x01, 0xB2, 0x2E, 0x60, 0xE8, 0x74, 0xE8, 0x8E, 0xE1, 0x90, 0xE0, 0xA7, 0x01, + 0x96, 0x01, 0x0E, 0x94, 0x13, 0x0A, 0x21, 0x50, 0x31, 0x09, 0x41, 0x09, 0x51, 0x09, 0x56, 0x95, + 0x47, 0x95, 0x37, 0x95, 0x27, 0x95, 0xE8, 0x89, 0xF9, 0x89, 0x82, 0xE0, 0x80, 0x83, 0x21, 0x15, + 0x80, 0xE1, 0x38, 0x07, 0x98, 0xF0, 0xE8, 0x89, 0xF9, 0x89, 0x10, 0x82, 0x60, 0xE4, 0x72, 0xE4, + 0x8F, 0xE0, 0x90, 0xE0, 0xA7, 0x01, 0x96, 0x01, 0x0E, 0x94, 0x13, 0x0A, 0x21, 0x50, 0x31, 0x09, + 0x41, 0x09, 0x51, 0x09, 0x56, 0x95, 0x47, 0x95, 0x37, 0x95, 0x27, 0x95, 0xEC, 0x85, 0xFD, 0x85, + 0x30, 0x83, 0xEE, 0x85, 0xFF, 0x85, 0x20, 0x83, 0x18, 0x8E, 0xEC, 0x89, 0xFD, 0x89, 0xB0, 0x82, + 0xEA, 0x89, 0xFB, 0x89, 0x80, 0x81, 0x80, 0x61, 0x80, 0x83, 0xEA, 0x89, 0xFB, 0x89, 0x80, 0x81, + 0x88, 0x60, 0x80, 0x83, 0xEA, 0x89, 0xFB, 0x89, 0x80, 0x81, 0x80, 0x68, 0x80, 0x83, 0xEA, 0x89, + 0xFB, 0x89, 0x80, 0x81, 0x8F, 0x7D, 0x80, 0x83, 0xDF, 0x91, 0xCF, 0x91, 0xFF, 0x90, 0xEF, 0x90, + 0xDF, 0x90, 0xCF, 0x90, 0xBF, 0x90, 0x08, 0x95, 0x1F, 0x92, 0x0F, 0x92, 0x0F, 0xB6, 0x0F, 0x92, + 0x11, 0x24, 0x2F, 0x93, 0x8F, 0x93, 0x9F, 0x93, 0xEF, 0x93, 0xFF, 0x93, 0xE0, 0x91, 0x55, 0x02, + 0xF0, 0x91, 0x56, 0x02, 0x80, 0x81, 0xE0, 0x91, 0x5B, 0x02, 0xF0, 0x91, 0x5C, 0x02, 0x82, 0xFD, + 0x12, 0xC0, 0x90, 0x81, 0x80, 0x91, 0x5E, 0x02, 0x8F, 0x5F, 0x8F, 0x73, 0x20, 0x91, 0x5F, 0x02, + 0x82, 0x17, 0x51, 0xF0, 0xE0, 0x91, 0x5E, 0x02, 0xF0, 0xE0, 0xEB, 0x5B, 0xFD, 0x4F, 0x95, 0x8F, + 0x80, 0x93, 0x5E, 0x02, 0x01, 0xC0, 0x80, 0x81, 0xFF, 0x91, 0xEF, 0x91, 0x9F, 0x91, 0x8F, 0x91, + 0x2F, 0x91, 0x0F, 0x90, 0x0F, 0xBE, 0x0F, 0x90, 0x1F, 0x90, 0x18, 0x95, 0x1F, 0x92, 0x0F, 0x92, + 0x0F, 0xB6, 0x0F, 0x92, 0x11, 0x24, 0x2F, 0x93, 0x3F, 0x93, 0x4F, 0x93, 0x5F, 0x93, 0x6F, 0x93, + 0x7F, 0x93, 0x8F, 0x93, 0x9F, 0x93, 0xAF, 0x93, 0xBF, 0x93, 0xEF, 0x93, 0xFF, 0x93, 0x85, 0xE4, + 0x92, 0xE0, 0x0E, 0x94, 0x90, 0x07, 0xFF, 0x91, 0xEF, 0x91, 0xBF, 0x91, 0xAF, 0x91, 0x9F, 0x91, + 0x8F, 0x91, 0x7F, 0x91, 0x6F, 0x91, 0x5F, 0x91, 0x4F, 0x91, 0x3F, 0x91, 0x2F, 0x91, 0x0F, 0x90, + 0x0F, 0xBE, 0x0F, 0x90, 0x1F, 0x90, 0x18, 0x95, 0x85, 0xE4, 0x92, 0xE0, 0x0E, 0x94, 0x55, 0x07, + 0x21, 0xE0, 0x89, 0x2B, 0x09, 0xF4, 0x20, 0xE0, 0x82, 0x2F, 0x08, 0x95, 0x10, 0x92, 0x48, 0x02, + 0x10, 0x92, 0x47, 0x02, 0x88, 0xEE, 0x93, 0xE0, 0xA0, 0xE0, 0xB0, 0xE0, 0x80, 0x93, 0x49, 0x02, + 0x90, 0x93, 0x4A, 0x02, 0xA0, 0x93, 0x4B, 0x02, 0xB0, 0x93, 0x4C, 0x02, 0x87, 0xE3, 0x91, 0xE0, + 0x90, 0x93, 0x46, 0x02, 0x80, 0x93, 0x45, 0x02, 0x85, 0xEC, 0x90, 0xE0, 0x90, 0x93, 0x52, 0x02, + 0x80, 0x93, 0x51, 0x02, 0x84, 0xEC, 0x90, 0xE0, 0x90, 0x93, 0x54, 0x02, 0x80, 0x93, 0x53, 0x02, + 0x80, 0xEC, 0x90, 0xE0, 0x90, 0x93, 0x56, 0x02, 0x80, 0x93, 0x55, 0x02, 0x81, 0xEC, 0x90, 0xE0, + 0x90, 0x93, 0x58, 0x02, 0x80, 0x93, 0x57, 0x02, 0x82, 0xEC, 0x90, 0xE0, 0x90, 0x93, 0x5A, 0x02, + 0x80, 0x93, 0x59, 0x02, 0x86, 0xEC, 0x90, 0xE0, 0x90, 0x93, 0x5C, 0x02, 0x80, 0x93, 0x5B, 0x02, + 0x10, 0x92, 0x5E, 0x02, 0x10, 0x92, 0x5F, 0x02, 0x10, 0x92, 0x60, 0x02, 0x10, 0x92, 0x61, 0x02, + 0x08, 0x95, 0xCF, 0x92, 0xDF, 0x92, 0xEF, 0x92, 0xFF, 0x92, 0x0F, 0x93, 0x1F, 0x93, 0xCF, 0x93, + 0xDF, 0x93, 0x7C, 0x01, 0x6A, 0x01, 0xEB, 0x01, 0x00, 0xE0, 0x10, 0xE0, 0x0C, 0x15, 0x1D, 0x05, + 0x71, 0xF0, 0x69, 0x91, 0xD7, 0x01, 0xED, 0x91, 0xFC, 0x91, 0x01, 0x90, 0xF0, 0x81, 0xE0, 0x2D, + 0xC7, 0x01, 0x09, 0x95, 0x89, 0x2B, 0x19, 0xF0, 0x0F, 0x5F, 0x1F, 0x4F, 0xEF, 0xCF, 0xC8, 0x01, + 0xDF, 0x91, 0xCF, 0x91, 0x1F, 0x91, 0x0F, 0x91, 0xFF, 0x90, 0xEF, 0x90, 0xDF, 0x90, 0xCF, 0x90, + 0x08, 0x95, 0x61, 0x15, 0x71, 0x05, 0x81, 0xF0, 0xDB, 0x01, 0x0D, 0x90, 0x00, 0x20, 0xE9, 0xF7, + 0xAD, 0x01, 0x41, 0x50, 0x51, 0x09, 0x46, 0x1B, 0x57, 0x0B, 0xDC, 0x01, 0xED, 0x91, 0xFC, 0x91, + 0x02, 0x80, 0xF3, 0x81, 0xE0, 0x2D, 0x09, 0x94, 0x80, 0xE0, 0x90, 0xE0, 0x08, 0x95, 0x0C, 0x94, + 0x61, 0x09, 0x63, 0xE4, 0x71, 0xE0, 0x0C, 0x94, 0x61, 0x09, 0x0F, 0x93, 0x1F, 0x93, 0xCF, 0x93, + 0xDF, 0x93, 0xEC, 0x01, 0x0E, 0x94, 0x61, 0x09, 0x8C, 0x01, 0xCE, 0x01, 0x0E, 0x94, 0x79, 0x09, + 0x80, 0x0F, 0x91, 0x1F, 0xDF, 0x91, 0xCF, 0x91, 0x1F, 0x91, 0x0F, 0x91, 0x08, 0x95, 0x8F, 0x92, + 0x9F, 0x92, 0xAF, 0x92, 0xBF, 0x92, 0xDF, 0x92, 0xEF, 0x92, 0xFF, 0x92, 0x0F, 0x93, 0x1F, 0x93, + 0xCF, 0x93, 0xDF, 0x93, 0xCD, 0xB7, 0xDE, 0xB7, 0xA1, 0x97, 0x0F, 0xB6, 0xF8, 0x94, 0xDE, 0xBF, + 0x0F, 0xBE, 0xCD, 0xBF, 0x7C, 0x01, 0xF4, 0x2F, 0xD5, 0x2E, 0xCB, 0x01, 0x19, 0xA2, 0x22, 0x30, + 0x08, 0xF4, 0x2A, 0xE0, 0x8E, 0x01, 0x0F, 0x5D, 0x1F, 0x4F, 0x82, 0x2E, 0x91, 0x2C, 0xA1, 0x2C, + 0xB1, 0x2C, 0x6F, 0x2F, 0x7D, 0x2D, 0xA5, 0x01, 0x94, 0x01, 0x0E, 0x94, 0x13, 0x0A, 0xF2, 0x2F, + 0xD3, 0x2E, 0xCA, 0x01, 0x01, 0x50, 0x11, 0x09, 0x6A, 0x30, 0x14, 0xF4, 0xE0, 0xE3, 0x01, 0xC0, + 0xE7, 0xE3, 0xE6, 0x0F, 0xD8, 0x01, 0xEC, 0x93, 0x23, 0x2B, 0x24, 0x2B, 0x25, 0x2B, 0x49, 0xF7, + 0xB8, 0x01, 0xC7, 0x01, 0x0E, 0x94, 0x61, 0x09, 0xA1, 0x96, 0x0F, 0xB6, 0xF8, 0x94, 0xDE, 0xBF, + 0x0F, 0xBE, 0xCD, 0xBF, 0xDF, 0x91, 0xCF, 0x91, 0x1F, 0x91, 0x0F, 0x91, 0xFF, 0x90, 0xEF, 0x90, + 0xDF, 0x90, 0xBF, 0x90, 0xAF, 0x90, 0x9F, 0x90, 0x8F, 0x90, 0x08, 0x95, 0x21, 0x15, 0x31, 0x05, + 0x41, 0xF4, 0xDC, 0x01, 0xED, 0x91, 0xFC, 0x91, 0x01, 0x90, 0xF0, 0x81, 0xE0, 0x2D, 0x64, 0x2F, + 0x09, 0x94, 0x0C, 0x94, 0x8F, 0x09, 0x0F, 0x93, 0x1F, 0x93, 0xCF, 0x93, 0xDF, 0x93, 0xEC, 0x01, + 0x9A, 0x01, 0x46, 0x2F, 0x50, 0xE0, 0x60, 0xE0, 0x70, 0xE0, 0x0E, 0x94, 0xDE, 0x09, 0x8C, 0x01, + 0xCE, 0x01, 0x0E, 0x94, 0x79, 0x09, 0x80, 0x0F, 0x91, 0x1F, 0xDF, 0x91, 0xCF, 0x91, 0x1F, 0x91, + 0x0F, 0x91, 0x08, 0x95, 0x08, 0x95, 0x0E, 0x94, 0x65, 0x06, 0x0E, 0x94, 0x02, 0x0A, 0x0E, 0x94, + 0x95, 0x01, 0xC2, 0xE8, 0xD7, 0xE0, 0x0E, 0x94, 0xEE, 0x01, 0x20, 0x97, 0xE1, 0xF3, 0x0E, 0x94, + 0x82, 0x07, 0xF9, 0xCF, 0x08, 0x95, 0xA1, 0xE2, 0x1A, 0x2E, 0xAA, 0x1B, 0xBB, 0x1B, 0xFD, 0x01, + 0x0D, 0xC0, 0xAA, 0x1F, 0xBB, 0x1F, 0xEE, 0x1F, 0xFF, 0x1F, 0xA2, 0x17, 0xB3, 0x07, 0xE4, 0x07, + 0xF5, 0x07, 0x20, 0xF0, 0xA2, 0x1B, 0xB3, 0x0B, 0xE4, 0x0B, 0xF5, 0x0B, 0x66, 0x1F, 0x77, 0x1F, + 0x88, 0x1F, 0x99, 0x1F, 0x1A, 0x94, 0x69, 0xF7, 0x60, 0x95, 0x70, 0x95, 0x80, 0x95, 0x90, 0x95, + 0x9B, 0x01, 0xAC, 0x01, 0xBD, 0x01, 0xCF, 0x01, 0x08, 0x95, 0xEE, 0x0F, 0xFF, 0x1F, 0x05, 0x90, + 0xF4, 0x91, 0xE0, 0x2D, 0x09, 0x94, 0xF9, 0x99, 0xFE, 0xCF, 0x92, 0xBD, 0x81, 0xBD, 0xF8, 0x9A, + 0x99, 0x27, 0x80, 0xB5, 0x08, 0x95, 0x26, 0x2F, 0xF9, 0x99, 0xFE, 0xCF, 0x1F, 0xBA, 0x92, 0xBD, + 0x81, 0xBD, 0x20, 0xBD, 0x0F, 0xB6, 0xF8, 0x94, 0xFA, 0x9A, 0xF9, 0x9A, 0x0F, 0xBE, 0x01, 0x96, + 0x08, 0x95, 0xF8, 0x94, 0xFF, 0xCF, 0x01, 0x46, 0x41, 0x43, 0x54, 0x4F, 0x52, 0x59, 0x3A, 0x20, + 0x00, 0x59, 0x45, 0x53, 0x00, 0x4E, 0x4F, 0x00, 0x69, 0x32, 0x64, 0x20, 0x61, 0x64, 0x64, 0x72, + 0x65, 0x73, 0x73, 0x20, 0x3D, 0x20, 0x30, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0x03, 0x99, + 0x03, 0x3F, 0x03, 0x47, 0x03, 0x5A, 0x03, 0x69, 0x03, 0x00, 0x00, 0x00, 0x00, 0xD3, 0x07, 0x39, + 0x09, 0x55, 0x07, 0x6E, 0x07, 0x60, 0x07, 0xB1, 0x07, 0x0D, 0x0A, 0x00, 0x6E, 0x61, 0x6E, 0x00, + 0x69, 0x6E, 0x66, 0x00, 0x6F, 0x76, 0x66, 0x00, 0x2E, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0x0C, 0x94, 0x34, 0x1C, 0x0C, 0x94, 0x51, 0x1C, 0x0C, 0x94, 0x51, 0x1C, 0x0C, 0x94, 0x51, 0x1C, + 0x0C, 0x94, 0x51, 0x1C, 0x0C, 0x94, 0x51, 0x1C, 0x0C, 0x94, 0x51, 0x1C, 0x0C, 0x94, 0x51, 0x1C, + 0x0C, 0x94, 0x51, 0x1C, 0x0C, 0x94, 0x51, 0x1C, 0x0C, 0x94, 0x51, 0x1C, 0x0C, 0x94, 0x51, 0x1C, + 0x0C, 0x94, 0x51, 0x1C, 0x0C, 0x94, 0x51, 0x1C, 0x0C, 0x94, 0x51, 0x1C, 0x0C, 0x94, 0x51, 0x1C, + 0x0C, 0x94, 0x51, 0x1C, 0x0C, 0x94, 0x51, 0x1C, 0x0C, 0x94, 0x51, 0x1C, 0x0C, 0x94, 0x51, 0x1C, + 0x0C, 0x94, 0x51, 0x1C, 0x0C, 0x94, 0x51, 0x1C, 0x0C, 0x94, 0x51, 0x1C, 0x0C, 0x94, 0x51, 0x1C, + 0x0C, 0x94, 0x51, 0x1C, 0x0C, 0x94, 0x51, 0x1C, 0x11, 0x24, 0x1F, 0xBE, 0xCF, 0xEF, 0xD4, 0xE0, + 0xDE, 0xBF, 0xCD, 0xBF, 0x11, 0xE0, 0xA0, 0xE0, 0xB1, 0xE0, 0xEE, 0xEA, 0xFF, 0xE3, 0x02, 0xC0, + 0x05, 0x90, 0x0D, 0x92, 0xA2, 0x30, 0xB1, 0x07, 0xD9, 0xF7, 0x12, 0xE0, 0xA2, 0xE0, 0xB1, 0xE0, + 0x01, 0xC0, 0x1D, 0x92, 0xAD, 0x30, 0xB1, 0x07, 0xE1, 0xF7, 0x0E, 0x94, 0x33, 0x1D, 0x0C, 0x94, + 0xD5, 0x1F, 0x0C, 0x94, 0x00, 0x1C, 0x98, 0x2F, 0x95, 0x95, 0x95, 0x95, 0x95, 0x95, 0x95, 0x95, + 0x90, 0x5D, 0x8F, 0x70, 0x8A, 0x30, 0x7C, 0xF0, 0x28, 0x2F, 0x29, 0x5A, 0x80, 0x91, 0xC0, 0x00, + 0x85, 0xFF, 0xFC, 0xCF, 0x90, 0x93, 0xC6, 0x00, 0x80, 0x91, 0xC0, 0x00, 0x85, 0xFF, 0xFC, 0xCF, + 0x20, 0x93, 0xC6, 0x00, 0x08, 0x95, 0x28, 0x2F, 0x20, 0x5D, 0xF0, 0xCF, 0x98, 0x2F, 0x80, 0x91, + 0xC0, 0x00, 0x85, 0xFF, 0xFC, 0xCF, 0x90, 0x93, 0xC6, 0x00, 0x08, 0x95, 0xEF, 0x92, 0xFF, 0x92, + 0x0F, 0x93, 0x1F, 0x93, 0xEE, 0x24, 0xFF, 0x24, 0x87, 0x01, 0x80, 0x91, 0xC0, 0x00, 0x87, 0xFD, + 0x17, 0xC0, 0x08, 0x94, 0xE1, 0x1C, 0xF1, 0x1C, 0x01, 0x1D, 0x11, 0x1D, 0x81, 0xE2, 0xE8, 0x16, + 0x81, 0xEA, 0xF8, 0x06, 0x87, 0xE0, 0x08, 0x07, 0x80, 0xE0, 0x18, 0x07, 0x70, 0xF3, 0xE0, 0x91, + 0x04, 0x01, 0xF0, 0x91, 0x05, 0x01, 0x09, 0x95, 0x80, 0x91, 0xC0, 0x00, 0x87, 0xFF, 0xE9, 0xCF, + 0x80, 0x91, 0xC6, 0x00, 0x1F, 0x91, 0x0F, 0x91, 0xFF, 0x90, 0xEF, 0x90, 0x08, 0x95, 0x0E, 0x94, + 0x76, 0x1C, 0x98, 0x2F, 0x80, 0x91, 0xC0, 0x00, 0x85, 0xFF, 0xFC, 0xCF, 0x90, 0x93, 0xC6, 0x00, + 0x91, 0x36, 0x2C, 0xF4, 0x90, 0x33, 0x0C, 0xF0, 0x90, 0x53, 0x89, 0x2F, 0x08, 0x95, 0x97, 0x55, + 0x89, 0x2F, 0x08, 0x95, 0x1F, 0x93, 0x0E, 0x94, 0x9F, 0x1C, 0x18, 0x2F, 0x0E, 0x94, 0x9F, 0x1C, + 0x12, 0x95, 0x10, 0x7F, 0x81, 0x0F, 0x1F, 0x91, 0x08, 0x95, 0x1F, 0x93, 0x18, 0x2F, 0x88, 0x23, + 0x21, 0xF0, 0x0E, 0x94, 0x76, 0x1C, 0x11, 0x50, 0xE1, 0xF7, 0x1F, 0x91, 0x08, 0x95, 0x1F, 0x93, + 0x18, 0x2F, 0x0E, 0x94, 0x76, 0x1C, 0x80, 0x32, 0x49, 0xF0, 0x80, 0x91, 0x03, 0x01, 0x8F, 0x5F, + 0x80, 0x93, 0x03, 0x01, 0x85, 0x30, 0xC1, 0xF0, 0x1F, 0x91, 0x08, 0x95, 0x80, 0x91, 0xC0, 0x00, + 0x85, 0xFF, 0xFC, 0xCF, 0x84, 0xE1, 0x80, 0x93, 0xC6, 0x00, 0x80, 0x91, 0xC0, 0x00, 0x85, 0xFF, + 0xFC, 0xCF, 0x10, 0x93, 0xC6, 0x00, 0x80, 0x91, 0xC0, 0x00, 0x85, 0xFF, 0xFC, 0xCF, 0x80, 0xE1, + 0x80, 0x93, 0xC6, 0x00, 0x1F, 0x91, 0x08, 0x95, 0xE0, 0x91, 0x04, 0x01, 0xF0, 0x91, 0x05, 0x01, + 0x09, 0x95, 0x1F, 0x91, 0x08, 0x95, 0x0E, 0x94, 0x76, 0x1C, 0x80, 0x32, 0x41, 0xF0, 0x80, 0x91, + 0x03, 0x01, 0x8F, 0x5F, 0x80, 0x93, 0x03, 0x01, 0x85, 0x30, 0x81, 0xF0, 0x08, 0x95, 0x80, 0x91, + 0xC0, 0x00, 0x85, 0xFF, 0xFC, 0xCF, 0x84, 0xE1, 0x80, 0x93, 0xC6, 0x00, 0x80, 0x91, 0xC0, 0x00, + 0x85, 0xFF, 0xFC, 0xCF, 0x80, 0xE1, 0x80, 0x93, 0xC6, 0x00, 0x08, 0x95, 0xE0, 0x91, 0x04, 0x01, + 0xF0, 0x91, 0x05, 0x01, 0x09, 0x95, 0x08, 0x95, 0x10, 0x92, 0x0A, 0x02, 0x88, 0x23, 0xD1, 0xF0, + 0x90, 0xE0, 0x48, 0xEC, 0x50, 0xE0, 0x2D, 0x9A, 0x28, 0xEE, 0x33, 0xE0, 0xFA, 0x01, 0x31, 0x97, + 0xF1, 0xF7, 0x21, 0x50, 0x30, 0x40, 0xD1, 0xF7, 0x2D, 0x98, 0x28, 0xEE, 0x33, 0xE0, 0xFA, 0x01, + 0x31, 0x97, 0xF1, 0xF7, 0x21, 0x50, 0x30, 0x40, 0xD1, 0xF7, 0x9F, 0x5F, 0x98, 0x17, 0x58, 0xF3, + 0x80, 0x93, 0x0A, 0x02, 0x08, 0x95, 0x3F, 0x92, 0x4F, 0x92, 0x5F, 0x92, 0x6F, 0x92, 0x7F, 0x92, + 0x8F, 0x92, 0x9F, 0x92, 0xAF, 0x92, 0xBF, 0x92, 0xCF, 0x92, 0xDF, 0x92, 0xEF, 0x92, 0xFF, 0x92, + 0x0F, 0x93, 0x1F, 0x93, 0xCF, 0x93, 0xDF, 0x93, 0x94, 0xB7, 0x14, 0xBE, 0x80, 0x91, 0x60, 0x00, + 0x88, 0x61, 0x80, 0x93, 0x60, 0x00, 0x10, 0x92, 0x60, 0x00, 0x91, 0xFF, 0x0C, 0xC2, 0x89, 0xE1, + 0x80, 0x93, 0xC4, 0x00, 0x10, 0x92, 0xC5, 0x00, 0x88, 0xE1, 0x80, 0x93, 0xC1, 0x00, 0x86, 0xE0, + 0x80, 0x93, 0xC2, 0x00, 0x50, 0x98, 0x58, 0x9A, 0x25, 0x9A, 0x81, 0xE0, 0x0E, 0x94, 0x14, 0x1D, + 0x44, 0xE1, 0xF4, 0x2E, 0x3E, 0xE1, 0xE3, 0x2E, 0x24, 0xE9, 0xD2, 0x2E, 0x96, 0xE0, 0xC9, 0x2E, + 0x80, 0xE1, 0xB8, 0x2E, 0xAA, 0x24, 0xA3, 0x94, 0x01, 0xE4, 0x90, 0x2E, 0x16, 0xE5, 0x81, 0x2E, + 0xB2, 0xE5, 0x7B, 0x2E, 0xA0, 0xE2, 0x6A, 0x2E, 0xF9, 0xE4, 0x5F, 0x2E, 0xE3, 0xE5, 0x4E, 0x2E, + 0x70, 0xE5, 0x37, 0x2E, 0x0E, 0x94, 0x76, 0x1C, 0x80, 0x33, 0xB9, 0xF1, 0x81, 0x33, 0xC1, 0xF1, + 0x80, 0x34, 0x09, 0xF4, 0x70, 0xC0, 0x81, 0x34, 0x09, 0xF4, 0x77, 0xC0, 0x82, 0x34, 0x09, 0xF4, + 0x86, 0xC0, 0x85, 0x34, 0x09, 0xF4, 0x89, 0xC0, 0x80, 0x35, 0x39, 0xF1, 0x82, 0x35, 0x29, 0xF1, + 0x81, 0x35, 0x09, 0xF4, 0xAF, 0xC1, 0x85, 0x35, 0x09, 0xF4, 0x85, 0xC0, 0x86, 0x35, 0x09, 0xF4, + 0x8D, 0xC0, 0x84, 0x36, 0x09, 0xF4, 0x35, 0xC1, 0x84, 0x37, 0x09, 0xF4, 0xC1, 0xC0, 0x85, 0x37, + 0x09, 0xF4, 0x90, 0xC0, 0x86, 0x37, 0x09, 0xF4, 0x66, 0xC0, 0x80, 0x91, 0x03, 0x01, 0x8F, 0x5F, + 0x80, 0x93, 0x03, 0x01, 0x85, 0x30, 0x71, 0xF6, 0xE0, 0x91, 0x04, 0x01, 0xF0, 0x91, 0x05, 0x01, + 0x09, 0x95, 0x0E, 0x94, 0x76, 0x1C, 0x80, 0x33, 0x49, 0xF6, 0x0E, 0x94, 0xF3, 0x1C, 0xC2, 0xCF, + 0x0E, 0x94, 0x76, 0x1C, 0x80, 0x32, 0x49, 0xF7, 0x80, 0x91, 0xC0, 0x00, 0x85, 0xFF, 0xFC, 0xCF, + 0xF0, 0x92, 0xC6, 0x00, 0x80, 0x91, 0xC0, 0x00, 0x85, 0xFF, 0xFC, 0xCF, 0x90, 0x92, 0xC6, 0x00, + 0x80, 0x91, 0xC0, 0x00, 0x85, 0xFF, 0xFC, 0xCF, 0x80, 0x92, 0xC6, 0x00, 0x80, 0x91, 0xC0, 0x00, + 0x85, 0xFF, 0xFC, 0xCF, 0x70, 0x92, 0xC6, 0x00, 0x80, 0x91, 0xC0, 0x00, 0x85, 0xFF, 0xFC, 0xCF, + 0x60, 0x92, 0xC6, 0x00, 0x80, 0x91, 0xC0, 0x00, 0x85, 0xFF, 0xFC, 0xCF, 0x50, 0x92, 0xC6, 0x00, + 0x80, 0x91, 0xC0, 0x00, 0x85, 0xFF, 0xFC, 0xCF, 0x40, 0x92, 0xC6, 0x00, 0x80, 0x91, 0xC0, 0x00, + 0x85, 0xFF, 0xFC, 0xCF, 0x30, 0x92, 0xC6, 0x00, 0x80, 0x91, 0xC0, 0x00, 0x85, 0xFF, 0xFC, 0xCF, + 0xB0, 0x92, 0xC6, 0x00, 0x87, 0xCF, 0x0E, 0x94, 0x76, 0x1C, 0x86, 0x38, 0x08, 0xF4, 0xBD, 0xCF, + 0x0E, 0x94, 0x76, 0x1C, 0x0E, 0x94, 0xF3, 0x1C, 0x7D, 0xCF, 0x0E, 0x94, 0x76, 0x1C, 0x80, 0x38, + 0x09, 0xF4, 0x5A, 0xC0, 0x81, 0x38, 0x09, 0xF4, 0x53, 0xC0, 0x82, 0x38, 0x09, 0xF4, 0x40, 0xC1, + 0x88, 0x39, 0x09, 0xF4, 0x49, 0xC0, 0x80, 0xE0, 0x0E, 0x94, 0xC7, 0x1C, 0x6B, 0xCF, 0x84, 0xE1, + 0x0E, 0x94, 0xBD, 0x1C, 0x0E, 0x94, 0xF3, 0x1C, 0x65, 0xCF, 0x85, 0xE0, 0x0E, 0x94, 0xBD, 0x1C, + 0x0E, 0x94, 0xF3, 0x1C, 0x5F, 0xCF, 0x0E, 0x94, 0x76, 0x1C, 0x80, 0x93, 0x06, 0x01, 0x0E, 0x94, + 0x76, 0x1C, 0x80, 0x93, 0x07, 0x01, 0x0E, 0x94, 0xF3, 0x1C, 0x54, 0xCF, 0x0E, 0x94, 0x76, 0x1C, + 0x80, 0x33, 0x09, 0xF4, 0x21, 0xC1, 0x83, 0xE0, 0x0E, 0x94, 0xBD, 0x1C, 0x80, 0xE0, 0x0E, 0x94, + 0xC7, 0x1C, 0x48, 0xCF, 0x0E, 0x94, 0x76, 0x1C, 0x80, 0x32, 0x09, 0xF0, 0x6E, 0xCF, 0x80, 0x91, + 0xC0, 0x00, 0x85, 0xFF, 0xFC, 0xCF, 0xF0, 0x92, 0xC6, 0x00, 0x80, 0x91, 0xC0, 0x00, 0x85, 0xFF, + 0xFC, 0xCF, 0xE0, 0x92, 0xC6, 0x00, 0x80, 0x91, 0xC0, 0x00, 0x85, 0xFF, 0xFC, 0xCF, 0xD0, 0x92, + 0xC6, 0x00, 0x80, 0x91, 0xC0, 0x00, 0x85, 0xFF, 0xFC, 0xCF, 0xC0, 0x92, 0xC6, 0x00, 0x80, 0x91, + 0xC0, 0x00, 0x85, 0xFF, 0xFC, 0xCF, 0x9C, 0xCF, 0x83, 0xE0, 0x0E, 0x94, 0xC7, 0x1C, 0x22, 0xCF, + 0x81, 0xE0, 0x0E, 0x94, 0xC7, 0x1C, 0x1E, 0xCF, 0x82, 0xE0, 0x0E, 0x94, 0xC7, 0x1C, 0x1A, 0xCF, + 0x0E, 0x94, 0x76, 0x1C, 0x80, 0x93, 0x09, 0x02, 0x0E, 0x94, 0x76, 0x1C, 0x80, 0x93, 0x08, 0x02, + 0x80, 0x91, 0x06, 0x01, 0x90, 0x91, 0x07, 0x01, 0x88, 0x0F, 0x99, 0x1F, 0x90, 0x93, 0x07, 0x01, + 0x80, 0x93, 0x06, 0x01, 0x0E, 0x94, 0x76, 0x1C, 0x85, 0x34, 0x09, 0xF4, 0xC5, 0xC0, 0x80, 0x91, + 0x0C, 0x02, 0x8E, 0x7F, 0x80, 0x93, 0x0C, 0x02, 0x0E, 0x94, 0x76, 0x1C, 0x80, 0x32, 0x09, 0xF0, + 0xF9, 0xCE, 0x80, 0x91, 0xC0, 0x00, 0x85, 0xFF, 0xFC, 0xCF, 0xF0, 0x92, 0xC6, 0x00, 0x60, 0x91, + 0x08, 0x02, 0x70, 0x91, 0x09, 0x02, 0x61, 0x15, 0x71, 0x05, 0x91, 0xF1, 0x40, 0xE0, 0x50, 0xE0, + 0x80, 0x91, 0x0C, 0x02, 0xA8, 0x2F, 0xA1, 0x70, 0xB8, 0x2F, 0xB2, 0x70, 0x10, 0xC0, 0xBB, 0x23, + 0x61, 0xF1, 0xE0, 0x91, 0x06, 0x01, 0xF0, 0x91, 0x07, 0x01, 0x31, 0x96, 0xF0, 0x93, 0x07, 0x01, + 0xE0, 0x93, 0x06, 0x01, 0x4F, 0x5F, 0x5F, 0x4F, 0x46, 0x17, 0x57, 0x07, 0xC8, 0xF4, 0xAA, 0x23, + 0x71, 0xF3, 0xF9, 0x99, 0xFE, 0xCF, 0x20, 0x91, 0x06, 0x01, 0x30, 0x91, 0x07, 0x01, 0x32, 0xBD, + 0x21, 0xBD, 0xF8, 0x9A, 0x90, 0xB5, 0x80, 0x91, 0xC0, 0x00, 0x85, 0xFF, 0xFC, 0xCF, 0x90, 0x93, + 0xC6, 0x00, 0x2F, 0x5F, 0x3F, 0x4F, 0x30, 0x93, 0x07, 0x01, 0x20, 0x93, 0x06, 0x01, 0xE2, 0xCF, + 0x80, 0x91, 0xC0, 0x00, 0x85, 0xFF, 0xFC, 0xCF, 0x2B, 0xCF, 0xE0, 0x91, 0x06, 0x01, 0xF0, 0x91, + 0x07, 0x01, 0x94, 0x91, 0x80, 0x91, 0xC0, 0x00, 0x85, 0xFF, 0xFC, 0xCF, 0x90, 0x93, 0xC6, 0x00, + 0xCC, 0xCF, 0x0E, 0x94, 0x76, 0x1C, 0x80, 0x93, 0x09, 0x02, 0x0E, 0x94, 0x76, 0x1C, 0x80, 0x93, + 0x08, 0x02, 0x80, 0x91, 0x0C, 0x02, 0x8E, 0x7F, 0x80, 0x93, 0x0C, 0x02, 0x0E, 0x94, 0x76, 0x1C, + 0x85, 0x34, 0x29, 0xF4, 0x80, 0x91, 0x0C, 0x02, 0x81, 0x60, 0x80, 0x93, 0x0C, 0x02, 0x80, 0x91, + 0x08, 0x02, 0x90, 0x91, 0x09, 0x02, 0x89, 0x2B, 0x89, 0xF0, 0x00, 0xE0, 0x10, 0xE0, 0x0E, 0x94, + 0x76, 0x1C, 0xF8, 0x01, 0xE8, 0x5F, 0xFE, 0x4F, 0x80, 0x83, 0x0F, 0x5F, 0x1F, 0x4F, 0x80, 0x91, + 0x08, 0x02, 0x90, 0x91, 0x09, 0x02, 0x08, 0x17, 0x19, 0x07, 0x88, 0xF3, 0x0E, 0x94, 0x76, 0x1C, + 0x80, 0x32, 0x09, 0xF0, 0xA2, 0xCE, 0x80, 0x91, 0x0C, 0x02, 0x80, 0xFF, 0x62, 0xC0, 0x40, 0x91, + 0x06, 0x01, 0x50, 0x91, 0x07, 0x01, 0x44, 0x0F, 0x55, 0x1F, 0x50, 0x93, 0x07, 0x01, 0x40, 0x93, + 0x06, 0x01, 0x60, 0x91, 0x08, 0x02, 0x70, 0x91, 0x09, 0x02, 0x61, 0x15, 0x71, 0x05, 0xC9, 0xF0, + 0xE8, 0xE0, 0xF1, 0xE0, 0x9A, 0x01, 0xDB, 0x01, 0xAE, 0x0F, 0xBF, 0x1F, 0xF9, 0x99, 0xFE, 0xCF, + 0x32, 0xBD, 0x21, 0xBD, 0x81, 0x91, 0x80, 0xBD, 0xFA, 0x9A, 0xF9, 0x9A, 0x2F, 0x5F, 0x3F, 0x4F, + 0xEA, 0x17, 0xFB, 0x07, 0x99, 0xF7, 0x46, 0x0F, 0x57, 0x1F, 0x50, 0x93, 0x07, 0x01, 0x40, 0x93, + 0x06, 0x01, 0x80, 0x91, 0xC0, 0x00, 0x85, 0xFF, 0xFC, 0xCF, 0xF0, 0x92, 0xC6, 0x00, 0x80, 0x91, + 0xC0, 0x00, 0x85, 0xFF, 0xFC, 0xCF, 0xB4, 0xCE, 0x80, 0x91, 0x0C, 0x02, 0x81, 0x60, 0x80, 0x93, + 0x0C, 0x02, 0x3A, 0xCF, 0x0E, 0x94, 0xF3, 0x1C, 0x88, 0xE0, 0x80, 0x93, 0x60, 0x00, 0xFF, 0xCF, + 0x80, 0xE1, 0x0E, 0x94, 0xC7, 0x1C, 0x2E, 0xCE, 0x0E, 0x94, 0x76, 0x1C, 0x0E, 0x94, 0x76, 0x1C, + 0x18, 0x2F, 0x0E, 0x94, 0x76, 0x1C, 0x11, 0x23, 0x81, 0xF0, 0x11, 0x30, 0x51, 0xF0, 0x86, 0xE0, + 0x0E, 0x94, 0xC7, 0x1C, 0x1F, 0xCE, 0xE0, 0x91, 0x04, 0x01, 0xF0, 0x91, 0x05, 0x01, 0x09, 0x95, + 0xEE, 0xCD, 0x84, 0xE9, 0x0E, 0x94, 0xC7, 0x1C, 0x15, 0xCE, 0x8E, 0xE1, 0x0E, 0x94, 0xC7, 0x1C, + 0x11, 0xCE, 0x80, 0x91, 0x07, 0x01, 0x88, 0x23, 0x88, 0x0F, 0x88, 0x0B, 0x8A, 0x21, 0x80, 0x93, + 0x0B, 0x02, 0x80, 0x91, 0x06, 0x01, 0x90, 0x91, 0x07, 0x01, 0x88, 0x0F, 0x99, 0x1F, 0x90, 0x93, + 0x07, 0x01, 0x80, 0x93, 0x06, 0x01, 0x80, 0x91, 0x08, 0x02, 0x80, 0xFF, 0x09, 0xC0, 0x80, 0x91, + 0x08, 0x02, 0x90, 0x91, 0x09, 0x02, 0x01, 0x96, 0x90, 0x93, 0x09, 0x02, 0x80, 0x93, 0x08, 0x02, + 0xF8, 0x94, 0xF9, 0x99, 0xFE, 0xCF, 0x11, 0x27, 0xE0, 0x91, 0x06, 0x01, 0xF0, 0x91, 0x07, 0x01, + 0xC8, 0xE0, 0xD1, 0xE0, 0x80, 0x91, 0x08, 0x02, 0x90, 0x91, 0x09, 0x02, 0x10, 0x30, 0x91, 0xF4, + 0x00, 0x91, 0x57, 0x00, 0x01, 0x70, 0x01, 0x30, 0xD9, 0xF3, 0x03, 0xE0, 0x00, 0x93, 0x57, 0x00, + 0xE8, 0x95, 0x00, 0x91, 0x57, 0x00, 0x01, 0x70, 0x01, 0x30, 0xD9, 0xF3, 0x01, 0xE1, 0x00, 0x93, + 0x57, 0x00, 0xE8, 0x95, 0x09, 0x90, 0x19, 0x90, 0x00, 0x91, 0x57, 0x00, 0x01, 0x70, 0x01, 0x30, + 0xD9, 0xF3, 0x01, 0xE0, 0x00, 0x93, 0x57, 0x00, 0xE8, 0x95, 0x13, 0x95, 0x10, 0x34, 0x98, 0xF0, + 0x11, 0x27, 0x00, 0x91, 0x57, 0x00, 0x01, 0x70, 0x01, 0x30, 0xD9, 0xF3, 0x05, 0xE0, 0x00, 0x93, + 0x57, 0x00, 0xE8, 0x95, 0x00, 0x91, 0x57, 0x00, 0x01, 0x70, 0x01, 0x30, 0xD9, 0xF3, 0x01, 0xE1, + 0x00, 0x93, 0x57, 0x00, 0xE8, 0x95, 0x32, 0x96, 0x02, 0x97, 0x09, 0xF0, 0xC7, 0xCF, 0x10, 0x30, + 0x11, 0xF0, 0x02, 0x96, 0xE5, 0xCF, 0x11, 0x24, 0x5C, 0xCF, 0xF8, 0x94, 0xFF, 0xCF, 0x80, 0x00, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, +}; \ No newline at end of file diff --git a/lib/Mutichannel_Gas_Sensor/examples/UpdateFrimware/gpl.txt b/lib/Mutichannel_Gas_Sensor/examples/UpdateFrimware/gpl.txt new file mode 100644 index 000000000..d511905c1 --- /dev/null +++ b/lib/Mutichannel_Gas_Sensor/examples/UpdateFrimware/gpl.txt @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/lib/Mutichannel_Gas_Sensor/examples/calibration/calibration.ino b/lib/Mutichannel_Gas_Sensor/examples/calibration/calibration.ino new file mode 100644 index 000000000..1fe6dfa9b --- /dev/null +++ b/lib/Mutichannel_Gas_Sensor/examples/calibration/calibration.ino @@ -0,0 +1,35 @@ +// Calibration code for Grove - Multichannel Gas Sensor +// Note that it need 10 minutes pre-heat before calibration +// This code is writen by Loovee@2016-5-18 + +#include +#include "MutichannelGasSensor.h" + +#define SENSOR_ADDR 0X04 // default to 0x04 +#define PRE_HEAT_TIME 0 // pre-heat time, 10-30 minutes is recommended + +void setup() +{ + Serial.begin(115200); + gas.begin(SENSOR_ADDR); // + Serial.println("power on, and pre-heat"); + + for(int i=60*PRE_HEAT_TIME; i>=0; i--) + { + Serial.print(i/60); + Serial.print(":"); + Serial.println(i%60); + delay(1000); + } + + Serial.println("Begin to calibrate..."); + gas.doCalibrate(); + Serial.println("Calibration ok"); + + gas.display_eeprom(); +} + +void loop() +{ + +} diff --git a/lib/Mutichannel_Gas_Sensor/examples/factory_setting/factory_setting.ino b/lib/Mutichannel_Gas_Sensor/examples/factory_setting/factory_setting.ino new file mode 100644 index 000000000..e6f28a975 --- /dev/null +++ b/lib/Mutichannel_Gas_Sensor/examples/factory_setting/factory_setting.ino @@ -0,0 +1,36 @@ +// factory setting +// Loovee +// 2016-11-10 + +#include +#include "MutichannelGasSensor.h" + +#define SENSOR_ADDR 0X04 // default to 0x04 + +void setup() +{ + Serial.begin(115200); + Serial.println("Please input something to continue"); + while(!Serial.available()); + + gas.begin(SENSOR_ADDR); // + + Serial.println("FACTORY SETTING OK"); + + float R0_NH3, R0_CO, R0_NO2; + + R0_NH3 = gas.getR0(0); + R0_CO = gas.getR0(1); + R0_NO2 = gas.getR0(2); + + Serial.print("R0_NH3 = "); + Serial.println(R0_NH3); + Serial.print("R0_CO = "); + Serial.println(R0_CO); + Serial.print("R0_NO2 = "); + Serial.println(R0_NO2); +} + +void loop() +{ +} diff --git a/lib/Mutichannel_Gas_Sensor/examples/new_firmware/new_firmware.ino b/lib/Mutichannel_Gas_Sensor/examples/new_firmware/new_firmware.ino new file mode 100644 index 000000000..20735b212 --- /dev/null +++ b/lib/Mutichannel_Gas_Sensor/examples/new_firmware/new_firmware.ino @@ -0,0 +1,272 @@ +/*firmware of multichannel gas sensor v2.0*3 + write by loovee + 2016-11-6 + + Factory adc value of 3 channels: + NH3 = 860 + CO = 950 + NO2 = 155 + + Default address is 0x04 +*/ + +#include +#include + +#define DEFAULT_I2C_ADDR 0x04 +#define DBG 1 +// EEPROM ADDRESS +#define ADDR_IS_SET 0 // if this is the first time to run, if 1126, set +#define ADDR_FACTORY_ADC_NH3 2 +#define ADDR_FACTORY_ADC_CO 4 +#define ADDR_FACTORY_ADC_NO2 6 + +#define ADDR_USER_ADC_HN3 8 +#define ADDR_USER_ADC_CO 10 +#define ADDR_USER_ADC_NO2 12 +#define ADDR_IF_CALI 14 // IF USER HAD CALI +#define ADDR_I2C_ADDRESS 20 +// I2C COMMAND + +#define CMD_ADC_RES0 1 // NH3 +#define CMD_ADC_RES1 2 // CO +#define CMD_ADC_RES2 3 // NO2 +#define CMD_ADC_RESALL 4 // ALL CHANNEL +#define CMD_CHANGE_I2C 5 // CHANGE I2C +#define CMD_READ_EEPROM 6 // READ EEPROM VALUE, RETURN UNSIGNED INT +#define CMD_SET_R0_ADC 7 // SET R0 ADC VALUE +#define CMD_GET_R0_ADC 8 // GET R0 ADC VALUE +#define CMD_GET_R0_ADC_FACTORY 9 // GET FACTORY R0 ADC VALUE +#define CMD_CONTROL_LED 10 +#define CMD_CONTROL_PWR 11 + +// EEPROM READ AND WRITE - UNSIGNED INT +void eeprom_write(int addr, unsigned int value) +{ + EEPROM.write(addr, value>>8); + EEPROM.write(addr+1, value&0xff); +} + +unsigned int eeprom_read(int addr) +{ + unsigned int r = EEPROM.read(addr); + r <<= 8; + r+= EEPROM.read(addr+1); + return r; +} + +const int pin_pwr = 8; +const int pin_led = 9; + +const int pin_NH3 = A0; // RES0 +const int pin_CO = A1; // RES1 +const int pin_NO2 = A2; // RES2 + +unsigned char i2c_address = 0; + +#define LED_ON() digitalWrite(pin_led, LOW) +#define LED_OFF() digitalWrite(pin_led, HIGH) + +void factory_init() +{ +#if DBG + Serial.print("FACTORY: "); +#endif + if(1126 != eeprom_read(ADDR_IS_SET)) // IF FACTORY SET + { +#if DBG + Serial.println("YES"); +#endif + eeprom_write(ADDR_IS_SET, 1126); + eeprom_write(ADDR_FACTORY_ADC_NH3, 860); + eeprom_write(ADDR_FACTORY_ADC_CO, 950); + eeprom_write(ADDR_FACTORY_ADC_NO2, 155); + eeprom_write(ADDR_USER_ADC_HN3, 860); + eeprom_write(ADDR_USER_ADC_CO, 950); + eeprom_write(ADDR_USER_ADC_NO2, 155); + eeprom_write(ADDR_IF_CALI, 0); + eeprom_write(ADDR_I2C_ADDRESS, DEFAULT_I2C_ADDR); + } +#if DBG + else Serial.println("NO"); +#endif +} + +int getAnalog(int pin) +{ + long sum = 0; + for(int i=0; i<64; i++) + { + sum += analogRead(pin); + } + return sum>>6; +} + +unsigned int ADC_RES0 = 0; +unsigned int ADC_RES1 = 0; +unsigned int ADC_RES2 = 0; + +unsigned char raw_adc[6]; + +void updateValue() +{ + static unsigned long timer_s = millis(); + if(millis()-timer_s < 1000)return; + timer_s = millis(); + + ADC_RES0 = getAnalog(pin_NH3); + ADC_RES1 = getAnalog(pin_CO); + ADC_RES2 = getAnalog(pin_NO2); + + raw_adc[0] = ADC_RES0>>8; + raw_adc[1] = ADC_RES0; + raw_adc[2] = ADC_RES1>>8; + raw_adc[3] = ADC_RES1; + raw_adc[4] = ADC_RES2>>8; + raw_adc[5] = ADC_RES2; +} + +void setup() +{ +#if DBG + Serial.begin(115200); +#endif + pinMode(pin_pwr, OUTPUT); + digitalWrite(pin_pwr, HIGH); + pinMode(pin_led, OUTPUT); + + factory_init(); + i2c_address = eeprom_read(ADDR_I2C_ADDRESS); +#if DBG + Serial.print("i2d address = 0x"); + Serial.println(i2c_address, HEX); +#endif + for(int i=0; i<5; i++) + { + digitalWrite(pin_led, LOW); + delay(100); + digitalWrite(pin_led, HIGH); + delay(100); + } + + Wire.begin(i2c_address); // join i2c bus with address + Wire.onReceive(receiveCallback); // register receive callback + Wire.onRequest(requestCallback); // register request callback +} + +void loop() +{ + updateValue(); +} + +unsigned char recvCmd = 0; +unsigned char recvDta = 0; +unsigned char recvDtaStr[10]; + +void receiveCallback(int dtaCount) +{ + if(dtaCount == 1) + { + recvCmd = Wire.read(); + } + else if(dtaCount == 2) // set i2c address + { + recvCmd = Wire.read(); + recvDta = Wire.read(); + + if(CMD_CHANGE_I2C == recvCmd) + { + i2c_address = recvDta; + eeprom_write(ADDR_I2C_ADDRESS, i2c_address); + Wire.begin(i2c_address); + } + else if(CMD_CONTROL_LED == recvCmd) + { + if(0 == recvDta)LED_OFF(); + else if(1 == recvDta)LED_ON(); + } + else if(CMD_CONTROL_PWR == recvCmd) + { + if(0 == recvDta)digitalWrite(pin_pwr, LOW); + else if(1 == recvDta)digitalWrite(pin_pwr, HIGH); + } + } + else if(dtaCount == 7) // set ADC value + { + recvCmd = Wire.read(); + unsigned int dta[3]; + + for(int i=0; i<3; i++) + { + dta[i] = Wire.read(); + dta[i] <<= 8; + dta[i] += Wire.read(); + } + + if(recvCmd == CMD_SET_R0_ADC) + { + eeprom_write(ADDR_USER_ADC_HN3, dta[0]); + eeprom_write(ADDR_USER_ADC_CO, dta[1]); + eeprom_write(ADDR_USER_ADC_NO2, dta[2]); + } + } +} + +unsigned char rcDta[10]; +void requestCallback() +{ + switch(recvCmd) + { + case CMD_ADC_RES0: // NH3 + Wire.write(&raw_adc[0], 2); // HIGH FIRST + + break; + + case CMD_ADC_RES1: // CO + Wire.write(&raw_adc[2], 2); // HIGH FIRST + break; + + case CMD_ADC_RES2: // NO2 + Wire.write(&raw_adc[4], 2); // HIGH FIRST + break; + + case CMD_ADC_RESALL: + Wire.write(raw_adc, 6); + break; + + case CMD_READ_EEPROM: + rcDta[0] = EEPROM.read(recvDta); + rcDta[1] = EEPROM.read(recvDta+1); + Wire.write(rcDta, 2); + break; + + case CMD_GET_R0_ADC: + + rcDta[0] = EEPROM.read(ADDR_USER_ADC_HN3); + rcDta[1] = EEPROM.read(ADDR_USER_ADC_HN3+1); + rcDta[2] = EEPROM.read(ADDR_USER_ADC_CO); + rcDta[3] = EEPROM.read(ADDR_USER_ADC_CO+1); + rcDta[4] = EEPROM.read(ADDR_USER_ADC_NO2); + rcDta[5] = EEPROM.read(ADDR_USER_ADC_NO2+1); + + Wire.write(rcDta, 6); + + break; + + case CMD_GET_R0_ADC_FACTORY: + + rcDta[0] = EEPROM.read(ADDR_FACTORY_ADC_NH3); + rcDta[1] = EEPROM.read(ADDR_FACTORY_ADC_NH3+1); + rcDta[2] = EEPROM.read(ADDR_FACTORY_ADC_CO); + rcDta[3] = EEPROM.read(ADDR_FACTORY_ADC_CO+1); + rcDta[4] = EEPROM.read(ADDR_FACTORY_ADC_NO2); + rcDta[5] = EEPROM.read(ADDR_FACTORY_ADC_NO2+1); + + Wire.write(rcDta, 6); + break; + + default:; + } +} + +// END FILE diff --git a/lib/Mutichannel_Gas_Sensor/library.json b/lib/Mutichannel_Gas_Sensor/library.json new file mode 100644 index 000000000..653cd9ad8 --- /dev/null +++ b/lib/Mutichannel_Gas_Sensor/library.json @@ -0,0 +1,14 @@ +{ + "name": "Mutichannel_Gas_Sensor", + "keywords": "Gas Sensor", + "description": "Grove - Multichannel Gas Sensor", + "homepage": "http://wiki.seeed.cc/Grove-Multichannel_Gas_Sensor/", + "repository": + { + "type": "git", + "url": "https://github.com/Seeed-Studio/Mutichannel_Gas_Sensor.git" + }, + "version": "0.0.1", + "frameworks": "arduino", + "platforms": "*" +} diff --git a/lib/Mutichannel_Gas_Sensor/library.properties b/lib/Mutichannel_Gas_Sensor/library.properties new file mode 100644 index 000000000..d6f9d9899 --- /dev/null +++ b/lib/Mutichannel_Gas_Sensor/library.properties @@ -0,0 +1,9 @@ +name=Grove - Multichannel Gas Sensor +version=0.0.1 +author=WEMOS.CC +maintainer=WEMOS.CC +sentence=Library for the Grove - Multichannel Gas Sensor. +paragraph=Library for the Grove - Multichannel Gas Sensor. +category=Device Control +url=https://github.com/Seeed-Studio/Mutichannel_Gas_Sensor.git +architectures=* diff --git a/lib/Mutichannel_Gas_Sensor/src/MutichannelGasSensor.cpp b/lib/Mutichannel_Gas_Sensor/src/MutichannelGasSensor.cpp new file mode 100644 index 000000000..9be9473ef --- /dev/null +++ b/lib/Mutichannel_Gas_Sensor/src/MutichannelGasSensor.cpp @@ -0,0 +1,729 @@ +/* + MutichannelGasSensor.cpp + 2015 Copyright (c) Seeed Technology Inc. All right reserved. + + Author: Jacky Zhang + 2015-3-17 + http://www.seeed.cc/ + modi by Jack, 2015-8 + + The MIT License (MIT) + + Copyright (c) 2015 Seeed Technology Inc. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#include +#include +#include +#include "MutichannelGasSensor.h" + +/********************************************************************************************************* +** Function name: begin +** Descriptions: initialize I2C +*********************************************************************************************************/ +void MutichannelGasSensor::begin(int address) +{ + __version = 1; // version 1/2 + r0_inited = false; + + Wire.begin(); + i2cAddress = address; + __send_error = false; + __version = getVersion(); +} + +bool MutichannelGasSensor::isError() +{ + return __send_error; +} + +unsigned char MutichannelGasSensor::getVersion() +{ + if(get_addr_dta(CMD_READ_EEPROM, ADDR_IS_SET) == 1126) // get version + { + __version = 2; + return __version; + } + if (!__send_error) { + __version = 1; + } + else { + __version = -1; + } + return __version; +} + +void MutichannelGasSensor::begin() +{ + begin(DEFAULT_I2C_ADDR); +} + +/********************************************************************************************************* +** Function name: sendI2C +** Descriptions: send one byte to I2C Wire +*********************************************************************************************************/ +void MutichannelGasSensor::sendI2C(unsigned char dta) +{ + __send_error = false; + Wire.beginTransmission(i2cAddress); // transmit to device #4 + Wire.write(dta); // sends one byte + if (Wire.endTransmission()) { // stop transmitting + __send_error = true; + } +} + + +unsigned int MutichannelGasSensor::get_addr_dta(unsigned char addr_reg) +{ + int trys = 0; +START: + __send_error = false; + Wire.beginTransmission(i2cAddress); + Wire.write(addr_reg); + if (Wire.endTransmission()) { // stop transmitting + trys++; + __send_error = true; + if (trys > 3) { + return 0; + } + } + + Wire.requestFrom(i2cAddress, (uint8_t)2); + + unsigned int dta = 0; + + unsigned char raw[10]; + int cnt = 0; + + while(Wire.available()) + { + raw[cnt++] = Wire.read(); + } + + if(cnt == 0)goto START; + + dta = raw[0]; + dta <<= 8; + dta += raw[1]; + + switch(addr_reg) + { + case CH_VALUE_NH3: + + if(dta > 0) + { + adcValueR0_NH3_Buf = dta; + } + else + { + dta = adcValueR0_NH3_Buf; + } + + break; + + case CH_VALUE_CO: + + if(dta > 0) + { + adcValueR0_CO_Buf = dta; + } + else + { + dta = adcValueR0_CO_Buf; + } + + break; + + case CH_VALUE_NO2: + + if(dta > 0) + { + adcValueR0_NO2_Buf = dta; + } + else + { + dta = adcValueR0_NO2_Buf; + } + + break; + + default:; + } + return dta; +} + +unsigned int MutichannelGasSensor::get_addr_dta(unsigned char addr_reg, unsigned char __dta) +{ + int trys = 0; +START: + __send_error = false; + Wire.beginTransmission(i2cAddress); + Wire.write(addr_reg); + Wire.write(__dta); + if (Wire.endTransmission()) { // stop transmitting + trys++; + __send_error = true; + if (trys > 3) { + return 0; + } + } + + Wire.requestFrom(i2cAddress, (uint8_t)2); + + unsigned int dta = 0; + + unsigned char raw[10]; + int cnt = 0; + + while(Wire.available()) + { + raw[cnt++] = Wire.read(); + } + + if(cnt == 0)goto START; + + dta = raw[0]; + dta <<= 8; + dta += raw[1]; + + + return dta; +} + + +void MutichannelGasSensor::write_i2c(unsigned char addr, unsigned char *dta, unsigned char dta_len) +{ + __send_error = false; + Wire.beginTransmission(addr); + for(int i=0; i 100) + return -2;//time out + delay(2); + } + if(Wire.available() != 4) + return -3;//rtnData length wrong + buffer[0] = Wire.read(); + buffer[1] = Wire.read(); + buffer[2] = Wire.read(); + buffer[3] = Wire.read(); + checksum = (uint8_t)(buffer[0] + buffer[1] + buffer[2]); + if(checksum != buffer[3]) + return -4;//checksum wrong + rtnData = ((buffer[1] << 8) + buffer[2]); + + return rtnData;//successful +} + +/********************************************************************************************************* +** Function name: readR0 +** Descriptions: read R0 stored in slave MCU +*********************************************************************************************************/ +int16_t MutichannelGasSensor::readR0(void) +{ + int16_t rtnData = 0; + + rtnData = readData(0x11); + + if(rtnData > 0) + res0[0] = rtnData; + else + return rtnData; //unsuccessful + + rtnData = readData(0x12); + if(rtnData > 0) + res0[1] = rtnData; + else + return rtnData; //unsuccessful + + rtnData = readData(0x13); + if(rtnData > 0) + res0[2] = rtnData; + else + return rtnData; //unsuccessful + + return 1;//successful +} + +/********************************************************************************************************* +** Function name: readR +** Descriptions: read resistance value of each channel from slave MCU +*********************************************************************************************************/ +int16_t MutichannelGasSensor::readR(void) +{ + int16_t rtnData = 0; + + rtnData = readData(0x01); + if(rtnData >= 0) + res[0] = rtnData; + else + return rtnData;//unsuccessful + + rtnData = readData(0x02); + if(rtnData >= 0) + res[1] = rtnData; + else + return rtnData;//unsuccessful + + rtnData = readData(0x03); + if(rtnData >= 0) + res[2] = rtnData; + else + return rtnData;//unsuccessful + + return 0;//successful +} + +/********************************************************************************************************* +** Function name: readR +** Descriptions: calculate gas concentration of each channel from slave MCU +** Parameters: + gas - gas type +** Returns: + float value - concentration of the gas +*********************************************************************************************************/ +float MutichannelGasSensor::calcGas(int gas) +{ + + float ratio0, ratio1, ratio2; + if(1 == __version) + { + if(!r0_inited) + { + if(readR0() >= 0) r0_inited = true; + else return -1.0f; + } + + if(readR() < 0) + return -2.0f; + + ratio0 = (float)res[0] / res0[0]; + ratio1 = (float)res[1] / res0[1]; + ratio2 = (float)res[2] / res0[2]; + } + else if(2 == __version) + { + // how to calc ratio/123 + ledOn(); + int A0_0 = get_addr_dta(6, ADDR_USER_ADC_HN3); + int A0_1 = get_addr_dta(6, ADDR_USER_ADC_CO); + int A0_2 = get_addr_dta(6, ADDR_USER_ADC_NO2); + + int An_0 = get_addr_dta(CH_VALUE_NH3); + int An_1 = get_addr_dta(CH_VALUE_CO); + int An_2 = get_addr_dta(CH_VALUE_NO2); + + ratio0 = (float)An_0/(float)A0_0*(1023.0-A0_0)/(1023.0-An_0); + ratio1 = (float)An_1/(float)A0_1*(1023.0-A0_1)/(1023.0-An_1); + ratio2 = (float)An_2/(float)A0_2*(1023.0-A0_2)/(1023.0-An_2); + + } + + float c = 0; + + switch(gas) + { + case CO: + { + c = pow(ratio1, -1.179)*4.385; //mod by jack + break; + } + case NO2: + { + c = pow(ratio2, 1.007)/6.855; //mod by jack + break; + } + case NH3: + { + c = pow(ratio0, -1.67)/1.47; //modi by jack + break; + } + case C3H8: //add by jack + { + c = pow(ratio0, -2.518)*570.164; + break; + } + case C4H10: //add by jack + { + c = pow(ratio0, -2.138)*398.107; + break; + } + case GAS_CH4: //add by jack + { + c = pow(ratio1, -4.363)*630.957; + break; + } + case H2: //add by jack + { + c = pow(ratio1, -1.8)*0.73; + break; + } + case C2H5OH: //add by jack + { + c = pow(ratio1, -1.552)*1.622; + break; + } + default: + break; + } + + if(2==__version)ledOff(); + return isnan(c)?-3:c; +} + +/********************************************************************************************************* +** Function name: changeI2cAddr +** Descriptions: change I2C address of the slave MCU, and this address will be stored in EEPROM of slave MCU +*********************************************************************************************************/ +void MutichannelGasSensor::changeI2cAddr(uint8_t newAddr) +{ + Wire.beginTransmission(i2cAddress); // transmit to device + Wire.write(0x23); // sends one byte + Wire.write(newAddr); // sends one byte + if (Wire.endTransmission()){ // stop transmitting + __send_error = true; + } else { + i2cAddress = newAddr; + } +} + +/********************************************************************************************************* +** Function name: doCalibrate +** Descriptions: tell slave to do a calibration, it will take about 8s + after the calibration, must reread the R0 values +*********************************************************************************************************/ +void MutichannelGasSensor::doCalibrate(void) +{ + + if(1 == __version) + { + START: + + sendI2C(0x22); + if(readR0() > 0) + { + for(int i=0; i<3; i++) + { + Serial.print(res0[i]); + Serial.print('\t'); + } + } + else + { + delay(5000); + Serial.println("continue..."); + for(int i=0; i<3; i++) + { + Serial.print(res0[i]); + Serial.print('\t'); + } + Serial.println(); + goto START; + } + } + else if(2 == __version) + { + unsigned int i, a0, a1, a2; + while(1) + { + a0 = get_addr_dta(CH_VALUE_NH3); + a1 = get_addr_dta(CH_VALUE_CO); + a2 = get_addr_dta(CH_VALUE_NO2); + + Serial.print(a0); + Serial.print('\t'); + Serial.print(a1); + Serial.print('\t'); + Serial.print(a2); + Serial.println('\t'); + ledOn(); + + int cnt = 0; + for(i=0; i<20; i++) + { + if((a0 - get_addr_dta(CH_VALUE_NH3)) > 2 || (get_addr_dta(CH_VALUE_NH3) - a0) > 2)cnt++; + if((a1 - get_addr_dta(CH_VALUE_CO)) > 2 || (get_addr_dta(CH_VALUE_CO) - a1) > 2)cnt++; + if((a2 - get_addr_dta(CH_VALUE_NO2)) > 2 || (get_addr_dta(CH_VALUE_NO2) - a2) > 2)cnt++; + + if(cnt>5) + { + break; + } + delay(1000); + } + + ledOff(); + if(cnt <= 5)break; + delay(200); + } + + Serial.print("write user adc value: "); + Serial.print(a0);Serial.print('\t'); + Serial.print(a1);Serial.print('\t'); + Serial.print(a2);Serial.println('\t'); + + unsigned char tmp[7]; + + tmp[0] = 7; + + tmp[1] = a0>>8; + tmp[2] = a0&0xff; + + tmp[3] = a1>>8; + tmp[4] = a1&0xff; + + tmp[5] = a2>>8; + tmp[6] = a2&0xff; + + write_i2c(i2cAddress, tmp, 7); + } +} + +/********************************************************************************************************* +** Function name: powerOn +** Descriptions: power on sensor heater +*********************************************************************************************************/ +void MutichannelGasSensor::powerOn(void) +{ + if(__version == 1) + sendI2C(0x21); + else if(__version == 2) + { + dta_test[0] = 11; + dta_test[1] = 1; + write_i2c(i2cAddress, dta_test, 2); + } +} + +/********************************************************************************************************* +** Function name: powerOff +** Descriptions: power off sensor heater +*********************************************************************************************************/ +void MutichannelGasSensor::powerOff(void) +{ + if(__version == 1) + sendI2C(0x20); + else if(__version == 2) + { + dta_test[0] = 11; + dta_test[1] = 0; + write_i2c(i2cAddress, dta_test, 2); + } +} + +void MutichannelGasSensor::display_eeprom() +{ + if(__version == 1) + { + Serial.println("ERROR: display_eeprom() is NOT support by V1 firmware."); + return ; + } + + Serial.print("ADDR_IS_SET = "); Serial.println(get_addr_dta(CMD_READ_EEPROM, ADDR_IS_SET)); + Serial.print("ADDR_FACTORY_ADC_NH3 = "); Serial.println(get_addr_dta(CMD_READ_EEPROM, ADDR_FACTORY_ADC_NH3)); + Serial.print("ADDR_FACTORY_ADC_CO = "); Serial.println(get_addr_dta(CMD_READ_EEPROM, ADDR_FACTORY_ADC_CO)); + Serial.print("ADDR_FACTORY_ADC_NO2 = "); Serial.println(get_addr_dta(CMD_READ_EEPROM, ADDR_FACTORY_ADC_NO2)); + Serial.print("ADDR_USER_ADC_HN3 = "); Serial.println(get_addr_dta(CMD_READ_EEPROM, ADDR_USER_ADC_HN3)); + Serial.print("ADDR_USER_ADC_CO = "); Serial.println(get_addr_dta(CMD_READ_EEPROM, ADDR_USER_ADC_CO)); + Serial.print("ADDR_USER_ADC_NO2 = "); Serial.println(get_addr_dta(CMD_READ_EEPROM, ADDR_USER_ADC_NO2)); + Serial.print("ADDR_I2C_ADDRESS = "); Serial.println(get_addr_dta(CMD_READ_EEPROM, ADDR_I2C_ADDRESS)); +} + +float MutichannelGasSensor::getR0(unsigned char ch) // 0:CH3, 1:CO, 2:NO2 +{ + if(__version == 1) + { + Serial.println("ERROR: getR0() is NOT support by V1 firmware."); + return -1; + } + + int a = 0; + switch(ch) + { + case 0: // CH3 + a = get_addr_dta(CMD_READ_EEPROM, ADDR_USER_ADC_HN3); + Serial.print("a_ch3 = "); + Serial.println(a); + break; + + case 1: // CO + a = get_addr_dta(CMD_READ_EEPROM, ADDR_USER_ADC_CO); + Serial.print("a_co = "); + Serial.println(a); + break; + + case 2: // NO2 + a = get_addr_dta(CMD_READ_EEPROM, ADDR_USER_ADC_NO2); + Serial.print("a_no2 = "); + Serial.println(a); + break; + + default:; + } + + float r = 56.0*(float)a/(1023.0-(float)a); + return r; +} + +float MutichannelGasSensor::getRs(unsigned char ch) // 0:CH3, 1:CO, 2:NO2 +{ + + if(__version == 1) + { + Serial.println("ERROR: getRs() is NOT support by V1 firmware."); + return -1; + } + + int a = 0; + switch(ch) + { + case 0: // NH3 + a = get_addr_dta(1); + break; + + case 1: // CO + a = get_addr_dta(2); + break; + + case 2: // NO2 + a = get_addr_dta(3); + break; + + default:; + } + + float r = 56.0*(float)a/(1023.0-(float)a); + return r; +} + +// 1. change i2c address to 0x04 +// 2. change adc value of R0 to default +void MutichannelGasSensor::factory_setting() +{ + + unsigned char tmp[7]; + + unsigned char error; + unsigned char address = 0; + + for(address = 1; address < 127; address++ ) + { + // The i2c_scanner uses the return value of + // the Write.endTransmisstion to see if + // a device did acknowledge to the address. + Wire.beginTransmission(address); + error = Wire.endTransmission(); + if (error == 0) + { + // change i2c to 0x04 + + Serial.print("I2C address is: 0x"); + Serial.println(address, HEX); + Serial.println("Change I2C address to 0x04"); + + dta_test[0] = CMD_CHANGE_I2C; + dta_test[1] = 0x04; + write_i2c(address, dta_test, 2); + + i2cAddress = 0x04; + delay(100); + getVersion(); + break; + } + } + + unsigned int a0 = get_addr_dta(CMD_READ_EEPROM, ADDR_FACTORY_ADC_NH3); + unsigned int a1 = get_addr_dta(CMD_READ_EEPROM, ADDR_FACTORY_ADC_CO); + unsigned int a2 = get_addr_dta(CMD_READ_EEPROM, ADDR_FACTORY_ADC_NO2); + + tmp[0] = 7; + tmp[1] = a0>>8; + tmp[2] = a0&0xff; + tmp[3] = a1>>8; + tmp[4] = a1&0xff; + + tmp[5] = a2>>8; + tmp[6] = a2&0xff; + delay(100); + write_i2c(i2cAddress, tmp, 7); + delay(100); +} + +void MutichannelGasSensor::change_i2c_address(unsigned char addr) +{ + dta_test[0] = CMD_CHANGE_I2C; + dta_test[1] = addr; + write_i2c(i2cAddress, dta_test, 2); + + + Serial.print("FUNCTION: CHANGE I2C ADDRESS: 0X"); + Serial.print(i2cAddress, HEX); + Serial.print(" > 0x"); + Serial.println(addr, HEX); + + i2cAddress = addr; +} + +void MutichannelGasSensor::ledOn() +{ + dta_test[0] = CMD_CONTROL_LED; + dta_test[1] = 1; + write_i2c(i2cAddress, dta_test, 2); +} + +void MutichannelGasSensor::ledOff() +{ + dta_test[0] = CMD_CONTROL_LED; + dta_test[1] = 0; + write_i2c(i2cAddress, dta_test, 2); +} + +MutichannelGasSensor gas; +/********************************************************************************************************* + END FILE +*********************************************************************************************************/ \ No newline at end of file diff --git a/lib/Mutichannel_Gas_Sensor/src/MutichannelGasSensor.h b/lib/Mutichannel_Gas_Sensor/src/MutichannelGasSensor.h new file mode 100644 index 000000000..5f4ce7c7f --- /dev/null +++ b/lib/Mutichannel_Gas_Sensor/src/MutichannelGasSensor.h @@ -0,0 +1,140 @@ +/* + MutichannelGasSensor.h + 2015 Copyright (c) Seeed Technology Inc. All right reserved. + + Author: Jacky Zhang + 2015-3-17 + http://www.seeed.cc/ + modi by Jack, 2015-8 + + V2 by Loovee + 2016-11-11 + + The MIT License (MIT) + + Copyright (c) 2015 Seeed Technology Inc. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#ifndef __MUTICHANNELGASSENSOR_H__ +#define __MUTICHANNELGASSENSOR_H__ + +#define DEFAULT_I2C_ADDR 0x04 + +#define ADDR_IS_SET 0 // if this is the first time to run, if 1126, set +#define ADDR_FACTORY_ADC_NH3 2 +#define ADDR_FACTORY_ADC_CO 4 +#define ADDR_FACTORY_ADC_NO2 6 + +#define ADDR_USER_ADC_HN3 8 +#define ADDR_USER_ADC_CO 10 +#define ADDR_USER_ADC_NO2 12 +#define ADDR_IF_CALI 14 // IF USER HAD CALI + +#define ADDR_I2C_ADDRESS 20 + +#define CH_VALUE_NH3 1 +#define CH_VALUE_CO 2 +#define CH_VALUE_NO2 3 + +#define CMD_ADC_RES0 1 // NH3 +#define CMD_ADC_RES1 2 // CO +#define CMD_ADC_RES2 3 // NO2 +#define CMD_ADC_RESALL 4 // ALL CHANNEL +#define CMD_CHANGE_I2C 5 // CHANGE I2C +#define CMD_READ_EEPROM 6 // READ EEPROM VALUE, RETURN UNSIGNED INT +#define CMD_SET_R0_ADC 7 // SET R0 ADC VALUE +#define CMD_GET_R0_ADC 8 // GET R0 ADC VALUE +#define CMD_GET_R0_ADC_FACTORY 9 // GET FACTORY R0 ADC VALUE +#define CMD_CONTROL_LED 10 +#define CMD_CONTROL_PWR 11 + +enum{CO, NO2, NH3, C3H8, C4H10, GAS_CH4, H2, C2H5OH}; + +class MutichannelGasSensor{ + +private: + + int __version; + int __send_error; + unsigned char dta_test[20]; + + unsigned int readChAdcValue(int ch); + unsigned int adcValueR0_NH3_Buf; + unsigned int adcValueR0_CO_Buf; + unsigned int adcValueR0_NO2_Buf; + +public: + + uint8_t i2cAddress; //I2C address of this MCU + uint16_t res0[3]; //sensors res0 + uint16_t res[3]; //sensors res + bool r0_inited; + + + inline unsigned int get_addr_dta(unsigned char addr_reg); + inline unsigned int get_addr_dta(unsigned char addr_reg, unsigned char __dta); + inline void write_i2c(unsigned char addr, unsigned char *dta, unsigned char dta_len); + + void sendI2C(unsigned char dta); + int16_t readData(uint8_t cmd); + int16_t readR0(void); + int16_t readR(void); + float calcGas(int gas); + +public: + + void begin(int address); + void begin(); + void changeI2cAddr(uint8_t newAddr); + void powerOn(void); + void powerOff(void); + void doCalibrate(void); + + //get gas concentration, unit: ppm + float measure_CO(){return calcGas(CO);} + float measure_NO2(){return calcGas(NO2);} + float measure_NH3(){return calcGas(NH3);} + float measure_C3H8(){return calcGas(C3H8);} + float measure_C4H10(){return calcGas(C4H10);} + float measure_CH4(){return calcGas(GAS_CH4);} + float measure_H2(){return calcGas(H2);} + float measure_C2H5OH(){return calcGas(C2H5OH);} + + float getR0(unsigned char ch); // 0:CH3, 1:CO, 2:NO2 + float getRs(unsigned char ch); // 0:CH3, 1:CO, 2:NO2 + +public: + bool isError(); + void ledOn(); + void ledOff(); + void display_eeprom(); + void factory_setting(); + void change_i2c_address(unsigned char addr); + unsigned char getVersion(); +}; + +extern MutichannelGasSensor gas; + +#endif + +/********************************************************************************************************* + END FILE +*********************************************************************************************************/ \ No newline at end of file diff --git a/lib/TSL2561-Arduino-Library/README.txt b/lib/TSL2561-Arduino-Library/README.txt deleted file mode 100644 index f59baf9e8..000000000 --- a/lib/TSL2561-Arduino-Library/README.txt +++ /dev/null @@ -1,7 +0,0 @@ -This is an Arduino library for the TSL2561 digital luminosity (light) sensors. - -Pick one up at http://www.adafruit.com/products/439 - -To download. click the DOWNLOADS button in the top right corner, rename the uncompressed folder TSL2561. Check that the TSL2561 folder contains TSL2561.cpp and TSL2561.h - -Place the TSL2561 library folder your /libraries/ folder. You may need to create the libraries subfolder if its your first library. Restart the IDE. \ No newline at end of file diff --git a/lib/TSL2561-Arduino-Library/TSL2561.cpp b/lib/TSL2561-Arduino-Library/TSL2561.cpp deleted file mode 100644 index b033aad0a..000000000 --- a/lib/TSL2561-Arduino-Library/TSL2561.cpp +++ /dev/null @@ -1,301 +0,0 @@ -/**************************************************************************/ -/*! - @file tsl2561.c - @author K. Townsend (microBuilder.eu / adafruit.com) - - @section LICENSE - - Software License Agreement (BSD License) - - Copyright (c) 2010, microBuilder SARL, Adafruit Industries - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - 3. Neither the name of the copyright holders nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY - EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -/**************************************************************************/ - -#if defined ( ESP8266 ) - #include -#else - #include - #include -#endif -#include - -#include "TSL2561.h" - -TSL2561::TSL2561(uint8_t addr) { - _addr = addr; - _initialized = false; - _integration = TSL2561_INTEGRATIONTIME_13MS; - _gain = TSL2561_GAIN_16X; - - // we cant do wire initialization till later, because we havent loaded Wire yet -} - -boolean TSL2561::begin(void) { - Wire.begin(); - - // Initialise I2C - Wire.beginTransmission(_addr); -#if ARDUINO >= 100 - Wire.write(TSL2561_REGISTER_ID); -#else - Wire.send(TSL2561_REGISTER_ID); -#endif - Wire.endTransmission(); - Wire.requestFrom(_addr, 1); -#if ARDUINO >= 100 - int x = Wire.read(); -#else - int x = Wire.receive(); -#endif - //Serial.print("0x"); Serial.println(x, HEX); - if (x & 0x0A ) { - //Serial.println("Found TSL2561"); - } else { - return false; - } - _initialized = true; - - // Set default integration time and gain - setTiming(_integration); - setGain(_gain); - // Note: by default, the device is in power down mode on bootup - disable(); - - return true; -} - -void TSL2561::enable(void) -{ - if (!_initialized) begin(); - - // Enable the device by setting the control bit to 0x03 - write8(TSL2561_COMMAND_BIT | TSL2561_REGISTER_CONTROL, TSL2561_CONTROL_POWERON); -} - -void TSL2561::disable(void) -{ - if (!_initialized) begin(); - - // Disable the device by setting the control bit to 0x03 - write8(TSL2561_COMMAND_BIT | TSL2561_REGISTER_CONTROL, TSL2561_CONTROL_POWEROFF); -} - - -void TSL2561::setGain(tsl2561Gain_t gain) { - if (!_initialized) begin(); - - enable(); - _gain = gain; - write8(TSL2561_COMMAND_BIT | TSL2561_REGISTER_TIMING, _integration | _gain); - disable(); -} - -void TSL2561::setTiming(tsl2561IntegrationTime_t integration) -{ - if (!_initialized) begin(); - - enable(); - _integration = integration; - write8(TSL2561_COMMAND_BIT | TSL2561_REGISTER_TIMING, _integration | _gain); - disable(); -} - -uint32_t TSL2561::calculateLux(uint16_t ch0, uint16_t ch1) -{ - unsigned long chScale; - unsigned long channel1; - unsigned long channel0; - - switch (_integration) - { - case TSL2561_INTEGRATIONTIME_13MS: - chScale = TSL2561_LUX_CHSCALE_TINT0; - break; - case TSL2561_INTEGRATIONTIME_101MS: - chScale = TSL2561_LUX_CHSCALE_TINT1; - break; - default: // No scaling ... integration time = 402ms - chScale = (1 << TSL2561_LUX_CHSCALE); - break; - } - - // Scale for gain (1x or 16x) - if (!_gain) chScale = chScale << 4; - - // scale the channel values - channel0 = (ch0 * chScale) >> TSL2561_LUX_CHSCALE; - channel1 = (ch1 * chScale) >> TSL2561_LUX_CHSCALE; - - // find the ratio of the channel values (Channel1/Channel0) - unsigned long ratio1 = 0; - if (channel0 != 0) ratio1 = (channel1 << (TSL2561_LUX_RATIOSCALE+1)) / channel0; - - // round the ratio value - unsigned long ratio = (ratio1 + 1) >> 1; - - unsigned int b, m; - -#ifdef TSL2561_PACKAGE_CS - if ((ratio >= 0) && (ratio <= TSL2561_LUX_K1C)) - {b=TSL2561_LUX_B1C; m=TSL2561_LUX_M1C;} - else if (ratio <= TSL2561_LUX_K2C) - {b=TSL2561_LUX_B2C; m=TSL2561_LUX_M2C;} - else if (ratio <= TSL2561_LUX_K3C) - {b=TSL2561_LUX_B3C; m=TSL2561_LUX_M3C;} - else if (ratio <= TSL2561_LUX_K4C) - {b=TSL2561_LUX_B4C; m=TSL2561_LUX_M4C;} - else if (ratio <= TSL2561_LUX_K5C) - {b=TSL2561_LUX_B5C; m=TSL2561_LUX_M5C;} - else if (ratio <= TSL2561_LUX_K6C) - {b=TSL2561_LUX_B6C; m=TSL2561_LUX_M6C;} - else if (ratio <= TSL2561_LUX_K7C) - {b=TSL2561_LUX_B7C; m=TSL2561_LUX_M7C;} - else if (ratio > TSL2561_LUX_K8C) - {b=TSL2561_LUX_B8C; m=TSL2561_LUX_M8C;} -#else - if ((ratio >= 0) && (ratio <= TSL2561_LUX_K1T)) - {b=TSL2561_LUX_B1T; m=TSL2561_LUX_M1T;} - else if (ratio <= TSL2561_LUX_K2T) - {b=TSL2561_LUX_B2T; m=TSL2561_LUX_M2T;} - else if (ratio <= TSL2561_LUX_K3T) - {b=TSL2561_LUX_B3T; m=TSL2561_LUX_M3T;} - else if (ratio <= TSL2561_LUX_K4T) - {b=TSL2561_LUX_B4T; m=TSL2561_LUX_M4T;} - else if (ratio <= TSL2561_LUX_K5T) - {b=TSL2561_LUX_B5T; m=TSL2561_LUX_M5T;} - else if (ratio <= TSL2561_LUX_K6T) - {b=TSL2561_LUX_B6T; m=TSL2561_LUX_M6T;} - else if (ratio <= TSL2561_LUX_K7T) - {b=TSL2561_LUX_B7T; m=TSL2561_LUX_M7T;} - else if (ratio > TSL2561_LUX_K8T) - {b=TSL2561_LUX_B8T; m=TSL2561_LUX_M8T;} -#endif - - unsigned long temp; - temp = ((channel0 * b) - (channel1 * m)); - - // do not allow negative lux value - if (temp < 0) temp = 0; - - // round lsb (2^(LUX_SCALE-1)) - temp += (1 << (TSL2561_LUX_LUXSCALE-1)); - - // strip off fractional portion - uint32_t lux = temp >> TSL2561_LUX_LUXSCALE; - - // Signal I2C had no errors - return lux; -} - -uint32_t TSL2561::getFullLuminosity (void) -{ - if (!_initialized) begin(); - - // Enable the device by setting the control bit to 0x03 - enable(); - - // Wait x ms for ADC to complete - switch (_integration) - { - case TSL2561_INTEGRATIONTIME_13MS: - delay(14); - break; - case TSL2561_INTEGRATIONTIME_101MS: - delay(102); - break; - default: - delay(403); - break; - } - - uint32_t x; - x = read16(TSL2561_COMMAND_BIT | TSL2561_WORD_BIT | TSL2561_REGISTER_CHAN1_LOW); - x <<= 16; - x |= read16(TSL2561_COMMAND_BIT | TSL2561_WORD_BIT | TSL2561_REGISTER_CHAN0_LOW); - - disable(); - - return x; -} -uint16_t TSL2561::getLuminosity (uint8_t channel) { - - uint32_t x = getFullLuminosity(); - - if (channel == 0) { - // Reads two byte value from channel 0 (visible + infrared) - return (x & 0xFFFF); - } else if (channel == 1) { - // Reads two byte value from channel 1 (infrared) - return (x >> 16); - } else if (channel == 2) { - // Reads all and subtracts out just the visible! - return ( (x & 0xFFFF) - (x >> 16)); - } - - // unknown channel! - return 0; -} - - -uint16_t TSL2561::read16(uint8_t reg) -{ - uint16_t x; uint16_t t; - - Wire.beginTransmission(_addr); -#if ARDUINO >= 100 - Wire.write(reg); -#else - Wire.send(reg); -#endif - Wire.endTransmission(); - - Wire.requestFrom(_addr, 2); -#if ARDUINO >= 100 - t = Wire.read(); - x = Wire.read(); -#else - t = Wire.receive(); - x = Wire.receive(); -#endif - x <<= 8; - x |= t; - return x; -} - - - -void TSL2561::write8 (uint8_t reg, uint8_t value) -{ - Wire.beginTransmission(_addr); -#if ARDUINO >= 100 - Wire.write(reg); - Wire.write(value); -#else - Wire.send(reg); - Wire.send(value); -#endif - Wire.endTransmission(); -} diff --git a/lib/TSL2561-Arduino-Library/TSL2561.h b/lib/TSL2561-Arduino-Library/TSL2561.h deleted file mode 100644 index 2750f2b13..000000000 --- a/lib/TSL2561-Arduino-Library/TSL2561.h +++ /dev/null @@ -1,184 +0,0 @@ - -/**************************************************************************/ -/*! - @file tsl2561.h - @author K. Townsend (microBuilder.eu) - - @section LICENSE - - Software License Agreement (BSD License) - - Copyright (c) 2010, microBuilder SARL - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - 3. Neither the name of the copyright holders nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY - EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -/**************************************************************************/ - -#ifndef _TSL2561_H_ -#define _TSL2561_H_ - -#if ARDUINO >= 100 - #include -#else - #include -#endif -#include - -#define TSL2561_VISIBLE 2 // channel 0 - channel 1 -#define TSL2561_INFRARED 1 // channel 1 -#define TSL2561_FULLSPECTRUM 0 // channel 0 - -// 3 i2c address options! -#define TSL2561_ADDR_LOW 0x29 -#define TSL2561_ADDR_FLOAT 0x39 -#define TSL2561_ADDR_HIGH 0x49 - -// Lux calculations differ slightly for CS package -//#define TSL2561_PACKAGE_CS -#define TSL2561_PACKAGE_T_FN_CL - -#define TSL2561_READBIT (0x01) - -#define TSL2561_COMMAND_BIT (0x80) // Must be 1 -#define TSL2561_CLEAR_BIT (0x40) // Clears any pending interrupt (write 1 to clear) -#define TSL2561_WORD_BIT (0x20) // 1 = read/write word (rather than byte) -#define TSL2561_BLOCK_BIT (0x10) // 1 = using block read/write - -#define TSL2561_CONTROL_POWERON (0x03) -#define TSL2561_CONTROL_POWEROFF (0x00) - -#define TSL2561_LUX_LUXSCALE (14) // Scale by 2^14 -#define TSL2561_LUX_RATIOSCALE (9) // Scale ratio by 2^9 -#define TSL2561_LUX_CHSCALE (10) // Scale channel values by 2^10 -#define TSL2561_LUX_CHSCALE_TINT0 (0x7517) // 322/11 * 2^TSL2561_LUX_CHSCALE -#define TSL2561_LUX_CHSCALE_TINT1 (0x0FE7) // 322/81 * 2^TSL2561_LUX_CHSCALE - -// T, FN and CL package values -#define TSL2561_LUX_K1T (0x0040) // 0.125 * 2^RATIO_SCALE -#define TSL2561_LUX_B1T (0x01f2) // 0.0304 * 2^LUX_SCALE -#define TSL2561_LUX_M1T (0x01be) // 0.0272 * 2^LUX_SCALE -#define TSL2561_LUX_K2T (0x0080) // 0.250 * 2^RATIO_SCALE -#define TSL2561_LUX_B2T (0x0214) // 0.0325 * 2^LUX_SCALE -#define TSL2561_LUX_M2T (0x02d1) // 0.0440 * 2^LUX_SCALE -#define TSL2561_LUX_K3T (0x00c0) // 0.375 * 2^RATIO_SCALE -#define TSL2561_LUX_B3T (0x023f) // 0.0351 * 2^LUX_SCALE -#define TSL2561_LUX_M3T (0x037b) // 0.0544 * 2^LUX_SCALE -#define TSL2561_LUX_K4T (0x0100) // 0.50 * 2^RATIO_SCALE -#define TSL2561_LUX_B4T (0x0270) // 0.0381 * 2^LUX_SCALE -#define TSL2561_LUX_M4T (0x03fe) // 0.0624 * 2^LUX_SCALE -#define TSL2561_LUX_K5T (0x0138) // 0.61 * 2^RATIO_SCALE -#define TSL2561_LUX_B5T (0x016f) // 0.0224 * 2^LUX_SCALE -#define TSL2561_LUX_M5T (0x01fc) // 0.0310 * 2^LUX_SCALE -#define TSL2561_LUX_K6T (0x019a) // 0.80 * 2^RATIO_SCALE -#define TSL2561_LUX_B6T (0x00d2) // 0.0128 * 2^LUX_SCALE -#define TSL2561_LUX_M6T (0x00fb) // 0.0153 * 2^LUX_SCALE -#define TSL2561_LUX_K7T (0x029a) // 1.3 * 2^RATIO_SCALE -#define TSL2561_LUX_B7T (0x0018) // 0.00146 * 2^LUX_SCALE -#define TSL2561_LUX_M7T (0x0012) // 0.00112 * 2^LUX_SCALE -#define TSL2561_LUX_K8T (0x029a) // 1.3 * 2^RATIO_SCALE -#define TSL2561_LUX_B8T (0x0000) // 0.000 * 2^LUX_SCALE -#define TSL2561_LUX_M8T (0x0000) // 0.000 * 2^LUX_SCALE - -// CS package values -#define TSL2561_LUX_K1C (0x0043) // 0.130 * 2^RATIO_SCALE -#define TSL2561_LUX_B1C (0x0204) // 0.0315 * 2^LUX_SCALE -#define TSL2561_LUX_M1C (0x01ad) // 0.0262 * 2^LUX_SCALE -#define TSL2561_LUX_K2C (0x0085) // 0.260 * 2^RATIO_SCALE -#define TSL2561_LUX_B2C (0x0228) // 0.0337 * 2^LUX_SCALE -#define TSL2561_LUX_M2C (0x02c1) // 0.0430 * 2^LUX_SCALE -#define TSL2561_LUX_K3C (0x00c8) // 0.390 * 2^RATIO_SCALE -#define TSL2561_LUX_B3C (0x0253) // 0.0363 * 2^LUX_SCALE -#define TSL2561_LUX_M3C (0x0363) // 0.0529 * 2^LUX_SCALE -#define TSL2561_LUX_K4C (0x010a) // 0.520 * 2^RATIO_SCALE -#define TSL2561_LUX_B4C (0x0282) // 0.0392 * 2^LUX_SCALE -#define TSL2561_LUX_M4C (0x03df) // 0.0605 * 2^LUX_SCALE -#define TSL2561_LUX_K5C (0x014d) // 0.65 * 2^RATIO_SCALE -#define TSL2561_LUX_B5C (0x0177) // 0.0229 * 2^LUX_SCALE -#define TSL2561_LUX_M5C (0x01dd) // 0.0291 * 2^LUX_SCALE -#define TSL2561_LUX_K6C (0x019a) // 0.80 * 2^RATIO_SCALE -#define TSL2561_LUX_B6C (0x0101) // 0.0157 * 2^LUX_SCALE -#define TSL2561_LUX_M6C (0x0127) // 0.0180 * 2^LUX_SCALE -#define TSL2561_LUX_K7C (0x029a) // 1.3 * 2^RATIO_SCALE -#define TSL2561_LUX_B7C (0x0037) // 0.00338 * 2^LUX_SCALE -#define TSL2561_LUX_M7C (0x002b) // 0.00260 * 2^LUX_SCALE -#define TSL2561_LUX_K8C (0x029a) // 1.3 * 2^RATIO_SCALE -#define TSL2561_LUX_B8C (0x0000) // 0.000 * 2^LUX_SCALE -#define TSL2561_LUX_M8C (0x0000) // 0.000 * 2^LUX_SCALE - -enum -{ - TSL2561_REGISTER_CONTROL = 0x00, - TSL2561_REGISTER_TIMING = 0x01, - TSL2561_REGISTER_THRESHHOLDL_LOW = 0x02, - TSL2561_REGISTER_THRESHHOLDL_HIGH = 0x03, - TSL2561_REGISTER_THRESHHOLDH_LOW = 0x04, - TSL2561_REGISTER_THRESHHOLDH_HIGH = 0x05, - TSL2561_REGISTER_INTERRUPT = 0x06, - TSL2561_REGISTER_CRC = 0x08, - TSL2561_REGISTER_ID = 0x0A, - TSL2561_REGISTER_CHAN0_LOW = 0x0C, - TSL2561_REGISTER_CHAN0_HIGH = 0x0D, - TSL2561_REGISTER_CHAN1_LOW = 0x0E, - TSL2561_REGISTER_CHAN1_HIGH = 0x0F -}; - -typedef enum -{ - TSL2561_INTEGRATIONTIME_13MS = 0x00, // 13.7ms - TSL2561_INTEGRATIONTIME_101MS = 0x01, // 101ms - TSL2561_INTEGRATIONTIME_402MS = 0x02 // 402ms -} -tsl2561IntegrationTime_t; - -typedef enum -{ - TSL2561_GAIN_0X = 0x00, // No gain - TSL2561_GAIN_16X = 0x10, // 16x gain -} -tsl2561Gain_t; - - -class TSL2561 { - public: - TSL2561(uint8_t addr); - boolean begin(void); - void enable(void); - void disable(void); - void write8(uint8_t r, uint8_t v); - uint16_t read16(uint8_t reg); - - uint32_t calculateLux(uint16_t ch0, uint16_t ch1); - void setTiming(tsl2561IntegrationTime_t integration); - void setGain(tsl2561Gain_t gain); - uint16_t getLuminosity (uint8_t channel); - uint32_t getFullLuminosity (); - - private: - int8_t _addr; - tsl2561IntegrationTime_t _integration; - tsl2561Gain_t _gain; - - boolean _initialized; -}; -#endif diff --git a/lib/TSL2561-Arduino-Library/examples/tsl2561/tsl2561.ino b/lib/TSL2561-Arduino-Library/examples/tsl2561/tsl2561.ino deleted file mode 100644 index 775223071..000000000 --- a/lib/TSL2561-Arduino-Library/examples/tsl2561/tsl2561.ino +++ /dev/null @@ -1,63 +0,0 @@ -#include -#include "TSL2561.h" - -// Example for demonstrating the TSL2561 library - public domain! - -// connect SCL to analog 5 -// connect SDA to analog 4 -// connect VDD to 3.3V DC -// connect GROUND to common ground -// ADDR can be connected to ground, or vdd or left floating to change the i2c address - -// The address will be different depending on whether you let -// the ADDR pin float (addr 0x39), or tie it to ground or vcc. In those cases -// use TSL2561_ADDR_LOW (0x29) or TSL2561_ADDR_HIGH (0x49) respectively -TSL2561 tsl(TSL2561_ADDR_FLOAT); - -void setup(void) { - Serial.begin(9600); - - if (tsl.begin()) { - Serial.println("Found sensor"); - } else { - Serial.println("No sensor?"); - while (1); - } - - // You can change the gain on the fly, to adapt to brighter/dimmer light situations - //tsl.setGain(TSL2561_GAIN_0X); // set no gain (for bright situtations) - tsl.setGain(TSL2561_GAIN_16X); // set 16x gain (for dim situations) - - // Changing the integration time gives you a longer time over which to sense light - // longer timelines are slower, but are good in very low light situtations! - tsl.setTiming(TSL2561_INTEGRATIONTIME_13MS); // shortest integration time (bright light) - //tsl.setTiming(TSL2561_INTEGRATIONTIME_101MS); // medium integration time (medium light) - //tsl.setTiming(TSL2561_INTEGRATIONTIME_402MS); // longest integration time (dim light) - - // Now we're ready to get readings! -} - -void loop(void) { - // Simple data read example. Just read the infrared, fullspecrtrum diode - // or 'visible' (difference between the two) channels. - // This can take 13-402 milliseconds! Uncomment whichever of the following you want to read - uint16_t x = tsl.getLuminosity(TSL2561_VISIBLE); - //uint16_t x = tsl.getLuminosity(TSL2561_FULLSPECTRUM); - //uint16_t x = tsl.getLuminosity(TSL2561_INFRARED); - - Serial.println(x, DEC); - - // More advanced data read example. Read 32 bits with top 16 bits IR, bottom 16 bits full spectrum - // That way you can do whatever math and comparisons you want! - uint32_t lum = tsl.getFullLuminosity(); - uint16_t ir, full; - ir = lum >> 16; - full = lum & 0xFFFF; - Serial.print("IR: "); Serial.print(ir); Serial.print("\t\t"); - Serial.print("Full: "); Serial.print(full); Serial.print("\t"); - Serial.print("Visible: "); Serial.print(full - ir); Serial.print("\t"); - - Serial.print("Lux: "); Serial.println(tsl.calculateLux(full, ir)); - - delay(100); -} diff --git a/lib/TSL2561-Arduino-Library/library.properties b/lib/TSL2561-Arduino-Library/library.properties deleted file mode 100644 index 06d22f721..000000000 --- a/lib/TSL2561-Arduino-Library/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=TSL2561 Arduino Library -version=1.0.0 -author=Adafruit -maintainer=Adafruit -sentence=Arduino library for using the TSL2561 Luminosity sensor -paragraph=Arduino library for using the TSL2561 Luminosity sensor -category=Sensors -url=https://github.com/adafruit/TSL2561-Arduino-Library -architectures=* diff --git a/lib/TasmotaMqtt-1.1.1/.gitignore b/lib/TasmotaMqtt-1.1.1/.gitignore new file mode 100644 index 000000000..2ee75414c --- /dev/null +++ b/lib/TasmotaMqtt-1.1.1/.gitignore @@ -0,0 +1,28 @@ +# C++ objects and libs + +*.slo +*.lo +*.o +#*.a +*.la +*.lai +*.so +*.dll +*.dylib + +#Makefile +*-build-* +build-* +*.autosave + +# .log files (usually created by QtTest - thanks to VestniK) +*.log + + +# Editors temporary files +*~ + + +#OSX +.DS_Store +._* diff --git a/lib/TasmotaMqtt-1.1.1/README.md b/lib/TasmotaMqtt-1.1.1/README.md new file mode 100644 index 000000000..db197299e --- /dev/null +++ b/lib/TasmotaMqtt-1.1.1/README.md @@ -0,0 +1,8 @@ +MQTT +==== + +A Wrapper around mqtt for Arduino to be used with esp8266 modules. + +It wraps a slightly modified version of mqtt for esp8266 ported by Tuan PM. +Original code for esp: https://github.com/tuanpmt/esp_mqtt +Original code for contiki: https://github.com/esar/contiki-mqtt diff --git a/lib/TasmotaMqtt-1.1.1/examples/mqtt_pub/mqtt_pub.ino b/lib/TasmotaMqtt-1.1.1/examples/mqtt_pub/mqtt_pub.ino new file mode 100644 index 000000000..17b3be8db --- /dev/null +++ b/lib/TasmotaMqtt-1.1.1/examples/mqtt_pub/mqtt_pub.ino @@ -0,0 +1,102 @@ +#include +#include + +void myDataCb(String& topic, String& data); +void myPublishedCb(); +void myDisconnectedCb(); +void myConnectedCb(); + +#define CLIENT_ID "client1" + +// create MQTT object +MQTT myMqtt(CLIENT_ID, "192.168.0.1", 1883); + +// +const char* ssid = "ssid"; +const char* password = "ssid_password"; + + +// +void setup() { + Serial.begin(115200); + delay(1000); + + Serial.println(); + Serial.println(); + Serial.print("Connecting to "); + Serial.println(ssid); + + WiFi.begin(ssid, password); + + while (WiFi.status() != WL_CONNECTED) { + delay(500); + Serial.print("."); + } + + Serial.println(""); + Serial.println("WiFi connected"); + Serial.println("IP address: "); + Serial.println(WiFi.localIP()); + + Serial.println("Connecting to MQTT server"); + + // setup callbacks + myMqtt.onConnected(myConnectedCb); + myMqtt.onDisconnected(myDisconnectedCb); + myMqtt.onPublished(myPublishedCb); + myMqtt.onData(myDataCb); + + Serial.println("connect mqtt..."); + myMqtt.connect(); + + delay(10); +} + +// +void loop() { + + int value = analogRead(A0); + + String topic("/"); + topic += CLIENT_ID; + topic += "/value"; + + String valueStr(value); + + // publish value to topic + boolean result = myMqtt.publish(topic, valueStr); + + delay(1000); +} + + +/* + * + */ +void myConnectedCb() +{ + Serial.println("connected to MQTT server"); +} + +void myDisconnectedCb() +{ + Serial.println("disconnected. try to reconnect..."); + delay(500); + myMqtt.connect(); +} + +void myPublishedCb() +{ + //Serial.println("published."); +} + +void myDataCb(String& topic, String& data) +{ + + Serial.print(topic); + Serial.print(": "); + Serial.println(data); +} + + + diff --git a/lib/TasmotaMqtt-1.1.1/examples/mqtt_sub/mqtt_sub.ino b/lib/TasmotaMqtt-1.1.1/examples/mqtt_sub/mqtt_sub.ino new file mode 100644 index 000000000..e88e0a7bb --- /dev/null +++ b/lib/TasmotaMqtt-1.1.1/examples/mqtt_sub/mqtt_sub.ino @@ -0,0 +1,97 @@ +#include +#include + +// This needs testing + +void myDataCb(char* topic, uint8_t* data, unsigned int data_len); +void myPublishedCb(); +void myDisconnectedCb(); +void myConnectedCb(); + +#define CLIENT_ID "client3" +#define TOPIC "/client1/value" + +// create MQTT +TasmotaMqtt myMqtt(); + +const char* ssid = "ssid"; +const char* password = "ssid_password"; + +// +void setup() { + Serial.begin(115200); + delay(1000); + + Serial.println(); + Serial.println(); + Serial.print("Connecting to "); + Serial.println(ssid); + + WiFi.begin(ssid, password); + + while (WiFi.status() != WL_CONNECTED) { + delay(500); + Serial.print("."); + } + + Serial.println(""); + Serial.println("WiFi connected"); + Serial.println("IP address: "); + Serial.println(WiFi.localIP()); + + + Serial.println("Connecting to MQTT server"); + + myMqtt.InitConnection("192.168.0.1", 1883); + myMqtt.InitClient(CLIENT_ID, "", ""); + myMqtt.InitLWT("/lwt", "offline"); + + // setup callbacks + myMqtt.OnConnected(myConnectedCb); + myMqtt.OnDisconnected(myDisconnectedCb); + myMqtt.OnPublished(myPublishedCb); + myMqtt.OnData(myDataCb); + + Serial.println("connect mqtt..."); + myMqtt.Connect(); + + Serial.println("subscribe to topic..."); + myMqtt.Subscribe(TOPIC); + + delay(10); +} + +// +void loop() { +} + + +/* + * + */ +void myConnectedCb() +{ + Serial.println("connected to MQTT server"); +} + +void myDisconnectedCb() +{ + Serial.println("disconnected. try to reconnect..."); + delay(500); + myMqtt.Connect(); +} + +void myPublishedCb() +{ + //Serial.println("published."); +} + +void myDataCb(char* topic, uint8_t* data, unsigned int data_len) +{ + Serial.print(topic); + Serial.print(": "); + Serial.println(data); +} + + + diff --git a/lib/TasmotaMqtt-1.1.1/keywords.txt b/lib/TasmotaMqtt-1.1.1/keywords.txt new file mode 100644 index 000000000..198919125 --- /dev/null +++ b/lib/TasmotaMqtt-1.1.1/keywords.txt @@ -0,0 +1,39 @@ +####################################### +# Syntax Coloring Map For Test +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +TasmotaMqtt.h KEYWORD1 +TasmotaMqtt KEYWORD1 + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +InitConnection KEYWORD2 +InitClient KEYWORD2 +InitLWT KEYWORD2 + +Connect KEYWORD2 +Disconnect KEYWORD2 +Connected KEYWORD2 + +Publish KEYWORD2 +Subscribe KEYWORD2 + +#general +OnConnected KEYWORD2 +OnDisconnected KEYWORD2 +OnData KEYWORD2 + +####################################### +# Instances (KEYWORD2) +####################################### + +####################################### +# Constants (LITERAL1) +####################################### + diff --git a/lib/TasmotaMqtt-1.1.1/library.properties b/lib/TasmotaMqtt-1.1.1/library.properties new file mode 100644 index 000000000..5a3802f35 --- /dev/null +++ b/lib/TasmotaMqtt-1.1.1/library.properties @@ -0,0 +1,9 @@ +name=TasmotaMqtt +version=1.0.0 +author=Theo Arends +maintainer=Theo Arends +sentence=A Wrapper around mqtt for Arduino to be used with esp8266 modules. +paragraph=It wraps a slightly modified version of mqtt for esp8266 ported by Tuan PM. Original code for esp: https://github.com/tuanpmt/esp_mqtt Original code for contiki: https://github.com/esar/contiki-mqtt +category=Communication +url= +architectures=esp8266 \ No newline at end of file diff --git a/lib/TasmotaMqtt-1.1.1/src/TasmotaMqtt.cpp b/lib/TasmotaMqtt-1.1.1/src/TasmotaMqtt.cpp new file mode 100644 index 000000000..9beddd452 --- /dev/null +++ b/lib/TasmotaMqtt-1.1.1/src/TasmotaMqtt.cpp @@ -0,0 +1,194 @@ +/* + TasmotaMqtt.cpp - Wrapper for mqtt for esp8266 by Tuan PM for Tasmota + + Copyright (C) 2018 Theo Arends and Ingo Randolf + + This library is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#include "TasmotaMqtt.h" + +#include "user_interface.h" +#include "osapi.h" +#include "os_type.h" + +/*********************************************************************************************\ + * Prerequisite + * + * Copy .c and .h files from https://github.com/tuanpmt/esp_mqtt folder mqtt to folder mqtt + * - Replace BOOL with bool + * - Remove variables certificate and private_key from file mqtt.c + * - Add file user_config.h with default defines for + * MQTT_BUF_SIZE 256, MQTT_RECONNECT_TIMEOUT 5, QUEUE_BUFFER_SIZE 2048 and PROTOCOL_NAMEv311 +\*********************************************************************************************/ + +/*********************************************************************************************\ + * Mqtt internal callbacks +\*********************************************************************************************/ + +static void mqttConnectedCb(uint32_t *args) +{ + MQTT_Client* client = (MQTT_Client*)args; + TasmotaMqtt* _this = (TasmotaMqtt*)client->user_data; + if (_this && _this->onMqttConnectedCb) _this->onMqttConnectedCb(); +} + +static void mqttDisconnectedCb(uint32_t *args) +{ + MQTT_Client* client = (MQTT_Client*)args; + TasmotaMqtt* _this = (TasmotaMqtt*)client->user_data; + if (_this && _this->onMqttDisconnectedCb) _this->onMqttDisconnectedCb(); +} + +static void mqttPublishedCb(uint32_t *args) +{ + MQTT_Client* client = (MQTT_Client*)args; + TasmotaMqtt* _this = (TasmotaMqtt*)client->user_data; + if (_this && _this->onMqttPublishedCb) _this->onMqttPublishedCb(); +} + +static void mqttTimeoutCb(uint32_t *args) +{ + MQTT_Client* client = (MQTT_Client*)args; + TasmotaMqtt* _this = (TasmotaMqtt*)client->user_data; + if (_this && _this->onMqttTimeoutCb) _this->onMqttTimeoutCb(); +} + +static void mqttDataCb(uint32_t *args, const char* topic, uint32_t topic_len, const char *data, uint32_t data_len) +{ + MQTT_Client* client = (MQTT_Client*)args; + TasmotaMqtt* _this = (TasmotaMqtt*)client->user_data; + if (_this) _this->_onMqttDataCb(topic, topic_len, data, data_len); +} + +/*********************************************************************************************\ + * TasmotaMqtt class implementation +\*********************************************************************************************/ + +TasmotaMqtt::TasmotaMqtt() : + onMqttConnectedCb(0), + onMqttDisconnectedCb(0), + onMqttPublishedCb(0), + onMqttTimeoutCb(0), + onMqttDataCb(0) +{ +} + +TasmotaMqtt::~TasmotaMqtt() +{ + MQTT_DeleteClient(&mqttClient); +} + +void TasmotaMqtt::InitConnection(const char* host, uint32_t port, uint8_t security) +{ + MQTT_InitConnection(&mqttClient, (uint8_t*)host, port, security); + + // set user data + mqttClient.user_data = (void*)this; + + MQTT_OnConnected(&mqttClient, mqttConnectedCb); + MQTT_OnDisconnected(&mqttClient, mqttDisconnectedCb); + MQTT_OnPublished(&mqttClient, mqttPublishedCb); + MQTT_OnTimeout(&mqttClient, mqttTimeoutCb); + MQTT_OnData(&mqttClient, mqttDataCb); +} + +void TasmotaMqtt::InitClient(const char* client_id, const char* client_user, const char* client_pass, uint32_t keep_alive_time, uint8_t clean_session) +{ + MQTT_InitClient(&mqttClient, (uint8_t*)client_id, (uint8_t*)client_user, (uint8_t*)client_pass, keep_alive_time, clean_session); +} + +void TasmotaMqtt::DeleteClient() +{ + MQTT_DeleteClient(&mqttClient); +} + +void TasmotaMqtt::InitLWT(const char* will_topic, const char* will_msg, uint8_t will_qos, bool will_retain) +{ + MQTT_InitLWT(&mqttClient, (uint8_t*)will_topic, (uint8_t*)will_msg, will_qos, (uint8_t)will_retain); +} + +void TasmotaMqtt::OnConnected( void (*function)(void) ) +{ + onMqttConnectedCb = function; +} + +void TasmotaMqtt::OnDisconnected( void (*function)(void) ) +{ + onMqttDisconnectedCb = function; +} + +void TasmotaMqtt::OnPublished( void (*function)(void) ) +{ + onMqttPublishedCb = function; +} + +void TasmotaMqtt::OnTimeout( void (*function)(void) ) +{ + onMqttTimeoutCb = function; +} + +void TasmotaMqtt::OnData( void (*function)(char*, uint8_t*, unsigned int) ) +{ + onMqttDataCb = function; +} + +bool TasmotaMqtt::Subscribe(const char* topic, uint8_t qos) +{ + return MQTT_Subscribe(&mqttClient, (char*)topic, qos); +} + +bool TasmotaMqtt::Unsubscribe(const char* topic) +{ + return MQTT_UnSubscribe(&mqttClient, (char*)topic); +} + +void TasmotaMqtt::Connect() +{ + MQTT_Connect(&mqttClient); +} + +void TasmotaMqtt::Connect(const char* client_id, const char* client_user, const char* client_pass, const char* will_topic, const char* will_msg, uint8_t will_qos, bool will_retain) +{ + MQTT_InitClient(&mqttClient, (uint8_t*)client_id, (uint8_t*)client_user, (uint8_t*)client_pass, MQTT_KEEPALIVE, 1); + MQTT_InitLWT(&mqttClient, (uint8_t*)will_topic, (uint8_t*)will_msg, will_qos, (uint8_t)will_retain); + MQTT_Connect(&mqttClient); +} + +void TasmotaMqtt::Disconnect() +{ + MQTT_Disconnect(&mqttClient); +} + +bool TasmotaMqtt::Publish(const char* topic, const char* data, int data_length, int qos, bool retain) +{ + return MQTT_Publish(&mqttClient, topic, data, data_length, qos, (int)retain); +} + +bool TasmotaMqtt::Connected() +{ + return (mqttClient.connState > TCP_CONNECTED); +} + +/*********************************************************************************************/ + +void TasmotaMqtt::_onMqttDataCb(const char* topic, uint32_t topic_len, const char* data, uint32_t data_len) +{ + char topic_copy[topic_len +1]; + + memcpy(topic_copy, topic, topic_len); + topic_copy[topic_len] = 0; + if (0 == data_len) data = (const char*)&topic_copy + topic_len; + onMqttDataCb((char*)topic_copy, (byte*)data, data_len); +} diff --git a/lib/TasmotaMqtt-1.1.1/src/TasmotaMqtt.h b/lib/TasmotaMqtt-1.1.1/src/TasmotaMqtt.h new file mode 100644 index 000000000..e512d8d5a --- /dev/null +++ b/lib/TasmotaMqtt-1.1.1/src/TasmotaMqtt.h @@ -0,0 +1,88 @@ +/* + TasmotaMqtt.h - Wrapper for mqtt for esp8266 by Tuan PM for Tasmota + + Copyright (C) 2018 Theo Arends and Ingo Randolf + + This library is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifndef TasmotaMqtt_h +#define TasmotaMqtt_h +/*********************************************************************************************\ + * TasmotaMqtt supports currently only non-TLS MQTT + * + * Adapted from esp-mqtt-arduino by Ingo Randolf (https://github.com/i-n-g-o/esp-mqtt-arduino) +\*********************************************************************************************/ + +#include + +#include +#include +#include +#include +#include + +extern "C" { + #include + #include "mqtt/mqtt.h" +} + +// MQTT_KEEPALIVE : keepAlive interval in Seconds +#ifndef MQTT_KEEPALIVE +#define MQTT_KEEPALIVE 15 +#endif + +class TasmotaMqtt { +public: + TasmotaMqtt(); + ~TasmotaMqtt(); + + void InitConnection(const char* host, uint32_t port, uint8_t security = 0); + void InitClient(const char* client_id, const char* client_user, const char* client_pass, uint32_t keep_alive_time = MQTT_KEEPALIVE, uint8_t clean_session = 1); + void DeleteClient(); + void InitLWT(const char* will_topic, const char* will_msg, uint8_t will_qos = 0, bool will_retain = false); + + void OnConnected( void (*)(void) ); + void OnDisconnected( void (*)(void) ); + void OnPublished( void (*)(void) ); + void OnTimeout( void (*)(void) ); + void OnData( void (*)(char*, uint8_t*, unsigned int) ); + + bool Subscribe(const char* topic, uint8_t qos = 0); + bool Unsubscribe(const char* topic); + + void Connect(); + void Connect(const char* client_id, const char* client_user, const char* client_pass, const char* will_topic, const char* will_msg, uint8_t will_qos = 0, bool will_retain = false); + void Disconnect(); + + bool Publish(const char* topic, const char* data, int data_length, int qos = 0, bool retain = false); + + bool Connected(); + + int State() { return mqttClient.connState; }; + + void (*onMqttConnectedCb)(void); + void (*onMqttDisconnectedCb)(void); + void (*onMqttPublishedCb)(void); + void (*onMqttTimeoutCb)(void); + void (*onMqttDataCb) (char*, uint8_t*, unsigned int); + + // internal callback + void _onMqttDataCb(const char*, uint32_t, const char*, uint32_t); + +private: + MQTT_Client mqttClient; +}; + +#endif // TasmotaMqtt_h \ No newline at end of file diff --git a/lib/TasmotaMqtt-1.1.1/src/mqtt/debug.h b/lib/TasmotaMqtt-1.1.1/src/mqtt/debug.h new file mode 100644 index 000000000..f45dd6d8d --- /dev/null +++ b/lib/TasmotaMqtt-1.1.1/src/mqtt/debug.h @@ -0,0 +1,19 @@ +/* + * debug.h + * + * Created on: Dec 4, 2014 + * Author: Minh + */ + +#ifndef USER_DEBUG_H_ +#define USER_DEBUG_H_ + + +#if defined(MQTT_DEBUG_ON) +#define MQTT_INFO( format, ... ) os_printf( format, ## __VA_ARGS__ ) +#else +#define MQTT_INFO( format, ... ) +#endif + + +#endif /* USER_DEBUG_H_ */ diff --git a/lib/TasmotaMqtt-1.1.1/src/mqtt/mqtt.c b/lib/TasmotaMqtt-1.1.1/src/mqtt/mqtt.c new file mode 100644 index 000000000..06609fe4a --- /dev/null +++ b/lib/TasmotaMqtt-1.1.1/src/mqtt/mqtt.c @@ -0,0 +1,997 @@ +/* mqtt.c +* Protocol: http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html +* +* Copyright (c) 2014-2015, Tuan PM +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* +* * Redistributions of source code must retain the above copyright notice, +* this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of Redis nor the names of its contributors may be used +* to endorse or promote products derived from this software without +* specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +* POSSIBILITY OF SUCH DAMAGE. +*/ + +#include "user_interface.h" +#include "osapi.h" +#include "espconn.h" +#include "os_type.h" +#include "mem.h" +#include "mqtt_msg.h" +#include "debug.h" +#include "user_config.h" +#include "mqtt.h" +#include "queue.h" + +#define MQTT_TASK_PRIO 2 +#define MQTT_TASK_QUEUE_SIZE 1 +#define MQTT_SEND_TIMOUT 5 + +#ifndef MQTT_SSL_SIZE +#define MQTT_SSL_SIZE 5120 +#endif + +#ifndef QUEUE_BUFFER_SIZE +#define QUEUE_BUFFER_SIZE 2048 +#endif + +/* +unsigned char *default_certificate; +unsigned int default_certificate_len = 0; +unsigned char *default_private_key; +unsigned int default_private_key_len = 0; +*/ + +os_event_t mqtt_procTaskQueue[MQTT_TASK_QUEUE_SIZE]; + +#ifdef PROTOCOL_NAMEv311 +LOCAL uint8_t zero_len_id[2] = { 0, 0 }; +#endif + +LOCAL void ICACHE_FLASH_ATTR +mqtt_dns_found(const char *name, ip_addr_t *ipaddr, void *arg) +{ + struct espconn *pConn = (struct espconn *)arg; + MQTT_Client* client = (MQTT_Client *)pConn->reverse; + + + if (ipaddr == NULL) + { + MQTT_INFO("DNS: Found, but got no ip, try to reconnect\r\n"); + client->connState = TCP_RECONNECT_REQ; + return; + } + + MQTT_INFO("DNS: found ip %d.%d.%d.%d\n", + *((uint8 *) &ipaddr->addr), + *((uint8 *) &ipaddr->addr + 1), + *((uint8 *) &ipaddr->addr + 2), + *((uint8 *) &ipaddr->addr + 3)); + + if (client->ip.addr == 0 && ipaddr->addr != 0) + { + os_memcpy(client->pCon->proto.tcp->remote_ip, &ipaddr->addr, 4); + if (client->security) { +#ifdef MQTT_SSL_ENABLE + espconn_secure_set_size(ESPCONN_CLIENT, MQTT_SSL_SIZE); + espconn_secure_connect(client->pCon); +#else + MQTT_INFO("TCP: Do not support SSL\r\n"); +#endif + } + else { + espconn_connect(client->pCon); + } + + client->connState = TCP_CONNECTING; + MQTT_INFO("TCP: connecting...\r\n"); + } + + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); +} + + + +LOCAL void ICACHE_FLASH_ATTR +deliver_publish(MQTT_Client* client, uint8_t* message, int length) +{ + mqtt_event_data_t event_data; + + event_data.topic_length = length; + event_data.topic = mqtt_get_publish_topic(message, &event_data.topic_length); + event_data.data_length = length; + event_data.data = mqtt_get_publish_data(message, &event_data.data_length); + + if (client->dataCb) + client->dataCb((uint32_t*)client, event_data.topic, event_data.topic_length, event_data.data, event_data.data_length); + +} + +void ICACHE_FLASH_ATTR +mqtt_send_keepalive(MQTT_Client *client) +{ + MQTT_INFO("\r\nMQTT: Send keepalive packet to %s:%d!\r\n", client->host, client->port); + client->mqtt_state.outbound_message = mqtt_msg_pingreq(&client->mqtt_state.mqtt_connection); + client->mqtt_state.pending_msg_type = MQTT_MSG_TYPE_PINGREQ; + client->mqtt_state.pending_msg_type = mqtt_get_type(client->mqtt_state.outbound_message->data); + client->mqtt_state.pending_msg_id = mqtt_get_id(client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length); + + + client->sendTimeout = MQTT_SEND_TIMOUT; + MQTT_INFO("MQTT: Sending, type: %d, id: %04X\r\n", client->mqtt_state.pending_msg_type, client->mqtt_state.pending_msg_id); + err_t result = ESPCONN_OK; + if (client->security) { +#ifdef MQTT_SSL_ENABLE + result = espconn_secure_send(client->pCon, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length); +#else + MQTT_INFO("TCP: Do not support SSL\r\n"); +#endif + } + else { + result = espconn_send(client->pCon, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length); + } + + client->mqtt_state.outbound_message = NULL; + if (ESPCONN_OK == result) { + client->keepAliveTick = 0; + client->connState = MQTT_DATA; + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); + } + else { + client->connState = TCP_RECONNECT_DISCONNECTING; + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); + } +} + +/** + * @brief Delete tcp client and free all memory + * @param mqttClient: The mqtt client which contain TCP client + * @retval None + */ +void ICACHE_FLASH_ATTR +mqtt_tcpclient_delete(MQTT_Client *mqttClient) +{ + if (mqttClient->pCon != NULL) { + MQTT_INFO("TCP: Free memory\r\n"); + // Force abort connections + espconn_abort(mqttClient->pCon); + // Delete connections + espconn_delete(mqttClient->pCon); + + if (mqttClient->pCon->proto.tcp) { + os_free(mqttClient->pCon->proto.tcp); + mqttClient->pCon->proto.tcp = NULL; + } + os_free(mqttClient->pCon); + mqttClient->pCon = NULL; + } +} + +/** + * @brief Delete MQTT client and free all memory + * @param mqttClient: The mqtt client + * @retval None + */ +void ICACHE_FLASH_ATTR +mqtt_client_delete(MQTT_Client *mqttClient) +{ + if (mqttClient == NULL) + return; + + if (mqttClient->pCon != NULL) { + mqtt_tcpclient_delete(mqttClient); + } + + if (mqttClient->host != NULL) { + os_free(mqttClient->host); + mqttClient->host = NULL; + } + + if (mqttClient->user_data != NULL) { + os_free(mqttClient->user_data); + mqttClient->user_data = NULL; + } + + if (mqttClient->mqtt_state.in_buffer != NULL) { + os_free(mqttClient->mqtt_state.in_buffer); + mqttClient->mqtt_state.in_buffer = NULL; + } + + if (mqttClient->mqtt_state.out_buffer != NULL) { + os_free(mqttClient->mqtt_state.out_buffer); + mqttClient->mqtt_state.out_buffer = NULL; + } + + if (mqttClient->mqtt_state.outbound_message != NULL) { + if (mqttClient->mqtt_state.outbound_message->data != NULL) + { + os_free(mqttClient->mqtt_state.outbound_message->data); + mqttClient->mqtt_state.outbound_message->data = NULL; + } + } + + if (mqttClient->mqtt_state.mqtt_connection.buffer != NULL) { + // Already freed but not NULL + mqttClient->mqtt_state.mqtt_connection.buffer = NULL; + } + + if (mqttClient->connect_info.client_id != NULL) { +#ifdef PROTOCOL_NAMEv311 + /* Don't attempt to free if it's the zero_len array */ + if ( ((uint8_t*)mqttClient->connect_info.client_id) != zero_len_id ) + os_free(mqttClient->connect_info.client_id); +#else + os_free(mqttClient->connect_info.client_id); +#endif + mqttClient->connect_info.client_id = NULL; + } + + if (mqttClient->connect_info.username != NULL) { + os_free(mqttClient->connect_info.username); + mqttClient->connect_info.username = NULL; + } + + if (mqttClient->connect_info.password != NULL) { + os_free(mqttClient->connect_info.password); + mqttClient->connect_info.password = NULL; + } + + if (mqttClient->connect_info.will_topic != NULL) { + os_free(mqttClient->connect_info.will_topic); + mqttClient->connect_info.will_topic = NULL; + } + + if (mqttClient->connect_info.will_message != NULL) { + os_free(mqttClient->connect_info.will_message); + mqttClient->connect_info.will_message = NULL; + } + + if (mqttClient->msgQueue.buf != NULL) { + os_free(mqttClient->msgQueue.buf); + mqttClient->msgQueue.buf = NULL; + } + + // Initialize state + mqttClient->connState = WIFI_INIT; + // Clear callback functions to avoid abnormal callback + mqttClient->connectedCb = NULL; + mqttClient->disconnectedCb = NULL; + mqttClient->publishedCb = NULL; + mqttClient->timeoutCb = NULL; + mqttClient->dataCb = NULL; + + MQTT_INFO("MQTT: client already deleted\r\n"); +} + + +/** + * @brief Client received callback function. + * @param arg: contain the ip link information + * @param pdata: received data + * @param len: the lenght of received data + * @retval None + */ +void ICACHE_FLASH_ATTR +mqtt_tcpclient_recv(void *arg, char *pdata, unsigned short len) +{ + uint8_t msg_type; + uint8_t msg_qos; + uint16_t msg_id; + uint8_t msg_conn_ret; + + struct espconn *pCon = (struct espconn*)arg; + MQTT_Client *client = (MQTT_Client *)pCon->reverse; + +READPACKET: + MQTT_INFO("TCP: data received %d bytes\r\n", len); + // MQTT_INFO("STATE: %d\r\n", client->connState); + if (len < MQTT_BUF_SIZE && len > 0) { + os_memcpy(client->mqtt_state.in_buffer, pdata, len); + + msg_type = mqtt_get_type(client->mqtt_state.in_buffer); + msg_qos = mqtt_get_qos(client->mqtt_state.in_buffer); + msg_id = mqtt_get_id(client->mqtt_state.in_buffer, client->mqtt_state.in_buffer_length); + switch (client->connState) { + case MQTT_CONNECT_SENDING: + if (msg_type == MQTT_MSG_TYPE_CONNACK) { + if (client->mqtt_state.pending_msg_type != MQTT_MSG_TYPE_CONNECT) { + MQTT_INFO("MQTT: Invalid packet\r\n"); + if (client->security) { +#ifdef MQTT_SSL_ENABLE + espconn_secure_disconnect(client->pCon); +#else + MQTT_INFO("TCP: Do not support SSL\r\n"); +#endif + } + else { + espconn_disconnect(client->pCon); + } + } else { + msg_conn_ret = mqtt_get_connect_return_code(client->mqtt_state.in_buffer); + switch (msg_conn_ret) { + case CONNECTION_ACCEPTED: + MQTT_INFO("MQTT: Connected to %s:%d\r\n", client->host, client->port); + client->connState = MQTT_DATA; + if (client->connectedCb) + client->connectedCb((uint32_t*)client); + break; + case CONNECTION_REFUSE_PROTOCOL: + case CONNECTION_REFUSE_SERVER_UNAVAILABLE: + case CONNECTION_REFUSE_BAD_USERNAME: + case CONNECTION_REFUSE_NOT_AUTHORIZED: + MQTT_INFO("MQTT: Connection refuse, reason code: %d\r\n", msg_conn_ret); + default: + if (client->security) { +#ifdef MQTT_SSL_ENABLE + espconn_secure_disconnect(client->pCon); +#else + MQTT_INFO("TCP: Do not support SSL\r\n"); +#endif + } + else { + espconn_disconnect(client->pCon); + } + + } + + } + + } + break; + case MQTT_DATA: + case MQTT_KEEPALIVE_SEND: + client->mqtt_state.message_length_read = len; + client->mqtt_state.message_length = mqtt_get_total_length(client->mqtt_state.in_buffer, client->mqtt_state.message_length_read); + + + switch (msg_type) + { + + case MQTT_MSG_TYPE_SUBACK: + if (client->mqtt_state.pending_msg_type == MQTT_MSG_TYPE_SUBSCRIBE && client->mqtt_state.pending_msg_id == msg_id) + MQTT_INFO("MQTT: Subscribe successful\r\n"); + break; + case MQTT_MSG_TYPE_UNSUBACK: + if (client->mqtt_state.pending_msg_type == MQTT_MSG_TYPE_UNSUBSCRIBE && client->mqtt_state.pending_msg_id == msg_id) + MQTT_INFO("MQTT: UnSubscribe successful\r\n"); + break; + case MQTT_MSG_TYPE_PUBLISH: + if (msg_qos == 1) + client->mqtt_state.outbound_message = mqtt_msg_puback(&client->mqtt_state.mqtt_connection, msg_id); + else if (msg_qos == 2) + client->mqtt_state.outbound_message = mqtt_msg_pubrec(&client->mqtt_state.mqtt_connection, msg_id); + if (msg_qos == 1 || msg_qos == 2) { + MQTT_INFO("MQTT: Queue response QoS: %d\r\n", msg_qos); + if (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) { + MQTT_INFO("MQTT: Queue full\r\n"); + } + } + + deliver_publish(client, client->mqtt_state.in_buffer, client->mqtt_state.message_length_read); + break; + case MQTT_MSG_TYPE_PUBACK: + if (client->mqtt_state.pending_msg_type == MQTT_MSG_TYPE_PUBLISH && client->mqtt_state.pending_msg_id == msg_id) { + MQTT_INFO("MQTT: received MQTT_MSG_TYPE_PUBACK, finish QoS1 publish\r\n"); + } + + break; + case MQTT_MSG_TYPE_PUBREC: + client->mqtt_state.outbound_message = mqtt_msg_pubrel(&client->mqtt_state.mqtt_connection, msg_id); + if (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) { + MQTT_INFO("MQTT: Queue full\r\n"); + } + break; + case MQTT_MSG_TYPE_PUBREL: + client->mqtt_state.outbound_message = mqtt_msg_pubcomp(&client->mqtt_state.mqtt_connection, msg_id); + if (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) { + MQTT_INFO("MQTT: Queue full\r\n"); + } + break; + case MQTT_MSG_TYPE_PUBCOMP: + if (client->mqtt_state.pending_msg_type == MQTT_MSG_TYPE_PUBLISH && client->mqtt_state.pending_msg_id == msg_id) { + MQTT_INFO("MQTT: receive MQTT_MSG_TYPE_PUBCOMP, finish QoS2 publish\r\n"); + } + break; + case MQTT_MSG_TYPE_PINGREQ: + client->mqtt_state.outbound_message = mqtt_msg_pingresp(&client->mqtt_state.mqtt_connection); + if (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) { + MQTT_INFO("MQTT: Queue full\r\n"); + } + break; + case MQTT_MSG_TYPE_PINGRESP: + // Ignore + break; + } + // NOTE: this is done down here and not in the switch case above + // because the PSOCK_READBUF_LEN() won't work inside a switch + // statement due to the way protothreads resume. + if (msg_type == MQTT_MSG_TYPE_PUBLISH) + { + len = client->mqtt_state.message_length_read; + + if (client->mqtt_state.message_length < client->mqtt_state.message_length_read) + { + //client->connState = MQTT_PUBLISH_RECV; + //Not Implement yet + len -= client->mqtt_state.message_length; + pdata += client->mqtt_state.message_length; + + MQTT_INFO("Get another published message\r\n"); + goto READPACKET; + } + + } + break; + } + } else { + MQTT_INFO("ERROR: Message too long\r\n"); + } + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); +} + +/** + * @brief Client send over callback function. + * @param arg: contain the ip link information + * @retval None + */ +void ICACHE_FLASH_ATTR +mqtt_tcpclient_sent_cb(void *arg) +{ + struct espconn *pCon = (struct espconn *)arg; + MQTT_Client* client = (MQTT_Client *)pCon->reverse; + MQTT_INFO("TCP: Sent\r\n"); + client->sendTimeout = 0; + client->keepAliveTick = 0; + + if ((client->connState == MQTT_DATA || client->connState == MQTT_KEEPALIVE_SEND) + && client->mqtt_state.pending_msg_type == MQTT_MSG_TYPE_PUBLISH) { + if (client->publishedCb) + client->publishedCb((uint32_t*)client); + } + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); +} + +void ICACHE_FLASH_ATTR mqtt_timer(void *arg) +{ + MQTT_Client* client = (MQTT_Client*)arg; + + if (client->connState == MQTT_DATA) { + client->keepAliveTick ++; + if (client->keepAliveTick > (client->mqtt_state.connect_info->keepalive / 2)) { + client->connState = MQTT_KEEPALIVE_SEND; + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); + } + + } else if (client->connState == TCP_RECONNECT_REQ) { + client->reconnectTick ++; + if (client->reconnectTick > MQTT_RECONNECT_TIMEOUT) { + client->reconnectTick = 0; + client->connState = TCP_RECONNECT; + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); + if (client->timeoutCb) + client->timeoutCb((uint32_t*)client); + } + } + if (client->sendTimeout > 0) + client->sendTimeout --; +} + +void ICACHE_FLASH_ATTR +mqtt_tcpclient_discon_cb(void *arg) +{ + + struct espconn *pespconn = (struct espconn *)arg; + MQTT_Client* client = (MQTT_Client *)pespconn->reverse; + MQTT_INFO("TCP: Disconnected callback\r\n"); + if (TCP_DISCONNECTING == client->connState) { + client->connState = TCP_DISCONNECTED; + } + else if (MQTT_DELETING == client->connState) { + client->connState = MQTT_DELETED; + } + else { + client->connState = TCP_RECONNECT_REQ; + } + if (client->disconnectedCb) + client->disconnectedCb((uint32_t*)client); + + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); +} + + + +/** + * @brief Tcp client connect success callback function. + * @param arg: contain the ip link information + * @retval None + */ +void ICACHE_FLASH_ATTR +mqtt_tcpclient_connect_cb(void *arg) +{ + struct espconn *pCon = (struct espconn *)arg; + MQTT_Client* client = (MQTT_Client *)pCon->reverse; + + espconn_regist_disconcb(client->pCon, mqtt_tcpclient_discon_cb); + espconn_regist_recvcb(client->pCon, mqtt_tcpclient_recv);//////// + espconn_regist_sentcb(client->pCon, mqtt_tcpclient_sent_cb);/////// + MQTT_INFO("MQTT: Connected to broker %s:%d\r\n", client->host, client->port); + + mqtt_msg_init(&client->mqtt_state.mqtt_connection, client->mqtt_state.out_buffer, client->mqtt_state.out_buffer_length); + client->mqtt_state.outbound_message = mqtt_msg_connect(&client->mqtt_state.mqtt_connection, client->mqtt_state.connect_info); + client->mqtt_state.pending_msg_type = mqtt_get_type(client->mqtt_state.outbound_message->data); + client->mqtt_state.pending_msg_id = mqtt_get_id(client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length); + + + client->sendTimeout = MQTT_SEND_TIMOUT; + MQTT_INFO("MQTT: Sending, type: %d, id: %04X\r\n", client->mqtt_state.pending_msg_type, client->mqtt_state.pending_msg_id); + if (client->security) { +#ifdef MQTT_SSL_ENABLE + espconn_secure_send(client->pCon, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length); +#else + MQTT_INFO("TCP: Do not support SSL\r\n"); +#endif + } + else { + espconn_send(client->pCon, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length); + } + + client->mqtt_state.outbound_message = NULL; + client->connState = MQTT_CONNECT_SENDING; + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); +} + +/** + * @brief Tcp client connect repeat callback function. + * @param arg: contain the ip link information + * @retval None + */ +void ICACHE_FLASH_ATTR +mqtt_tcpclient_recon_cb(void *arg, sint8 errType) +{ + struct espconn *pCon = (struct espconn *)arg; + MQTT_Client* client = (MQTT_Client *)pCon->reverse; + + MQTT_INFO("TCP: Reconnect to %s:%d\r\n", client->host, client->port); + + client->connState = TCP_RECONNECT_REQ; + + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); + +} + +/** + * @brief MQTT publish function. + * @param client: MQTT_Client reference + * @param topic: string topic will publish to + * @param data: buffer data send point to + * @param data_length: length of data + * @param qos: qos + * @param retain: retain + * @retval TRUE if success queue + */ +bool ICACHE_FLASH_ATTR +MQTT_Publish(MQTT_Client *client, const char* topic, const char* data, int data_length, int qos, int retain) +{ + uint8_t dataBuffer[MQTT_BUF_SIZE]; + uint16_t dataLen; + client->mqtt_state.outbound_message = mqtt_msg_publish(&client->mqtt_state.mqtt_connection, + topic, data, data_length, + qos, retain, + &client->mqtt_state.pending_msg_id); + if (client->mqtt_state.outbound_message->length == 0) { + MQTT_INFO("MQTT: Queuing publish failed\r\n"); + return FALSE; + } + MQTT_INFO("MQTT: queuing publish, length: %d, queue size(%d/%d)\r\n", client->mqtt_state.outbound_message->length, client->msgQueue.rb.fill_cnt, client->msgQueue.rb.size); + while (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) { + MQTT_INFO("MQTT: Queue full\r\n"); + if (QUEUE_Gets(&client->msgQueue, dataBuffer, &dataLen, MQTT_BUF_SIZE) == -1) { + MQTT_INFO("MQTT: Serious buffer error\r\n"); + return FALSE; + } + } + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); + return TRUE; +} + +/** + * @brief MQTT subscibe function. + * @param client: MQTT_Client reference + * @param topic: string topic will subscribe + * @param qos: qos + * @retval TRUE if success queue + */ +bool ICACHE_FLASH_ATTR +MQTT_Subscribe(MQTT_Client *client, char* topic, uint8_t qos) +{ + uint8_t dataBuffer[MQTT_BUF_SIZE]; + uint16_t dataLen; + + client->mqtt_state.outbound_message = mqtt_msg_subscribe(&client->mqtt_state.mqtt_connection, + topic, qos, + &client->mqtt_state.pending_msg_id); + MQTT_INFO("MQTT: queue subscribe, topic\"%s\", id: %d\r\n", topic, client->mqtt_state.pending_msg_id); + while (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) { + MQTT_INFO("MQTT: Queue full\r\n"); + if (QUEUE_Gets(&client->msgQueue, dataBuffer, &dataLen, MQTT_BUF_SIZE) == -1) { + MQTT_INFO("MQTT: Serious buffer error\r\n"); + return FALSE; + } + } + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); + + return TRUE; +} + +/** + * @brief MQTT un-subscibe function. + * @param client: MQTT_Client reference + * @param topic: String topic will un-subscribe + * @retval TRUE if success queue + */ +bool ICACHE_FLASH_ATTR +MQTT_UnSubscribe(MQTT_Client *client, char* topic) +{ + uint8_t dataBuffer[MQTT_BUF_SIZE]; + uint16_t dataLen; + client->mqtt_state.outbound_message = mqtt_msg_unsubscribe(&client->mqtt_state.mqtt_connection, + topic, + &client->mqtt_state.pending_msg_id); + MQTT_INFO("MQTT: queue un-subscribe, topic\"%s\", id: %d\r\n", topic, client->mqtt_state.pending_msg_id); + while (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) { + MQTT_INFO("MQTT: Queue full\r\n"); + if (QUEUE_Gets(&client->msgQueue, dataBuffer, &dataLen, MQTT_BUF_SIZE) == -1) { + MQTT_INFO("MQTT: Serious buffer error\r\n"); + return FALSE; + } + } + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); + return TRUE; +} + +/** + * @brief MQTT ping function. + * @param client: MQTT_Client reference + * @retval TRUE if success queue + */ +bool ICACHE_FLASH_ATTR +MQTT_Ping(MQTT_Client *client) +{ + uint8_t dataBuffer[MQTT_BUF_SIZE]; + uint16_t dataLen; + client->mqtt_state.outbound_message = mqtt_msg_pingreq(&client->mqtt_state.mqtt_connection); + if (client->mqtt_state.outbound_message->length == 0) { + MQTT_INFO("MQTT: Queuing publish failed\r\n"); + return FALSE; + } + MQTT_INFO("MQTT: queuing publish, length: %d, queue size(%d/%d)\r\n", client->mqtt_state.outbound_message->length, client->msgQueue.rb.fill_cnt, client->msgQueue.rb.size); + while (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) { + MQTT_INFO("MQTT: Queue full\r\n"); + if (QUEUE_Gets(&client->msgQueue, dataBuffer, &dataLen, MQTT_BUF_SIZE) == -1) { + MQTT_INFO("MQTT: Serious buffer error\r\n"); + return FALSE; + } + } + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); + return TRUE; +} + +void ICACHE_FLASH_ATTR +MQTT_Task(os_event_t *e) +{ + MQTT_Client* client = (MQTT_Client*)e->par; + uint8_t dataBuffer[MQTT_BUF_SIZE]; + uint16_t dataLen; + if (e->par == 0) + return; + switch (client->connState) { + + case TCP_RECONNECT_REQ: + break; + case TCP_RECONNECT: + mqtt_tcpclient_delete(client); + MQTT_Connect(client); + MQTT_INFO("TCP: Reconnect to: %s:%d\r\n", client->host, client->port); + client->connState = TCP_CONNECTING; + break; + case MQTT_DELETING: + case TCP_DISCONNECTING: + case TCP_RECONNECT_DISCONNECTING: + if (client->security) { +#ifdef MQTT_SSL_ENABLE + espconn_secure_disconnect(client->pCon); +#else + MQTT_INFO("TCP: Do not support SSL\r\n"); +#endif + } + else { + espconn_disconnect(client->pCon); + } + break; + case TCP_DISCONNECTED: + MQTT_INFO("MQTT: Disconnected\r\n"); + mqtt_tcpclient_delete(client); + break; + case MQTT_DELETED: + MQTT_INFO("MQTT: Deleted client\r\n"); + mqtt_client_delete(client); + break; + case MQTT_KEEPALIVE_SEND: + mqtt_send_keepalive(client); + break; + case MQTT_DATA: + if (QUEUE_IsEmpty(&client->msgQueue) || client->sendTimeout != 0) { + break; + } + if (QUEUE_Gets(&client->msgQueue, dataBuffer, &dataLen, MQTT_BUF_SIZE) == 0) { + client->mqtt_state.pending_msg_type = mqtt_get_type(dataBuffer); + client->mqtt_state.pending_msg_id = mqtt_get_id(dataBuffer, dataLen); + + + client->sendTimeout = MQTT_SEND_TIMOUT; + MQTT_INFO("MQTT: Sending, type: %d, id: %04X\r\n", client->mqtt_state.pending_msg_type, client->mqtt_state.pending_msg_id); + client->keepAliveTick = 0; + if (client->security) { +#ifdef MQTT_SSL_ENABLE + espconn_secure_send(client->pCon, dataBuffer, dataLen); +#else + MQTT_INFO("TCP: Do not support SSL\r\n"); +#endif + } + else { + espconn_send(client->pCon, dataBuffer, dataLen); + } + + client->mqtt_state.outbound_message = NULL; + break; + } + break; + } +} + +/** + * @brief MQTT initialization connection function + * @param client: MQTT_Client reference + * @param host: Domain or IP string + * @param port: Port to connect + * @param security: 1 for ssl, 0 for none + * @retval None + */ +void ICACHE_FLASH_ATTR +MQTT_InitConnection(MQTT_Client *mqttClient, uint8_t* host, uint32_t port, uint8_t security) +{ + uint32_t temp; + MQTT_INFO("MQTT:InitConnection\r\n"); + os_memset(mqttClient, 0, sizeof(MQTT_Client)); + temp = os_strlen(host); + mqttClient->host = (uint8_t*)os_zalloc(temp + 1); + os_strcpy(mqttClient->host, host); + mqttClient->host[temp] = 0; + mqttClient->port = port; + mqttClient->security = security; + +} + +/** + * @brief MQTT initialization mqtt client function + * @param client: MQTT_Client reference + * @param clientid: MQTT client id + * @param client_user:MQTT client user + * @param client_pass:MQTT client password + * @param client_pass:MQTT keep alive timer, in second + * @retval None + */ +bool ICACHE_FLASH_ATTR +MQTT_InitClient(MQTT_Client *mqttClient, uint8_t* client_id, uint8_t* client_user, uint8_t* client_pass, uint32_t keepAliveTime, uint8_t cleanSession) +{ + uint32_t temp; + MQTT_INFO("MQTT:InitClient\r\n"); + + os_memset(&mqttClient->connect_info, 0, sizeof(mqtt_connect_info_t)); + + if ( !client_id ) + { + /* Should be allowed by broker, but clean session flag must be set. */ + #ifdef PROTOCOL_NAMEv311 + if (cleanSession) + { + mqttClient->connect_info.client_id = zero_len_id; + } else { + MQTT_INFO("cleanSession must be set to use 0 length client_id\r\n"); + return false; + } + /* Not supported. Return. */ + #else + MQTT_INFO("Client ID required for MQTT < 3.1.1!\r\n"); + return false; + #endif + } + + /* If connect_info's client_id is still NULL and we get here, we can * + * assume the passed client_id is non-NULL. */ + if ( !(mqttClient->connect_info.client_id) ) + { + temp = os_strlen(client_id); + mqttClient->connect_info.client_id = (uint8_t*)os_zalloc(temp + 1); + os_strcpy(mqttClient->connect_info.client_id, client_id); + mqttClient->connect_info.client_id[temp] = 0; + } + + if (client_user) + { + temp = os_strlen(client_user); + mqttClient->connect_info.username = (uint8_t*)os_zalloc(temp + 1); + os_strcpy(mqttClient->connect_info.username, client_user); + mqttClient->connect_info.username[temp] = 0; + } + + if (client_pass) + { + temp = os_strlen(client_pass); + mqttClient->connect_info.password = (uint8_t*)os_zalloc(temp + 1); + os_strcpy(mqttClient->connect_info.password, client_pass); + mqttClient->connect_info.password[temp] = 0; + } + + + mqttClient->connect_info.keepalive = keepAliveTime; + mqttClient->connect_info.clean_session = cleanSession; + + mqttClient->mqtt_state.in_buffer = (uint8_t *)os_zalloc(MQTT_BUF_SIZE); + mqttClient->mqtt_state.in_buffer_length = MQTT_BUF_SIZE; + mqttClient->mqtt_state.out_buffer = (uint8_t *)os_zalloc(MQTT_BUF_SIZE); + mqttClient->mqtt_state.out_buffer_length = MQTT_BUF_SIZE; + mqttClient->mqtt_state.connect_info = &mqttClient->connect_info; + + mqtt_msg_init(&mqttClient->mqtt_state.mqtt_connection, mqttClient->mqtt_state.out_buffer, mqttClient->mqtt_state.out_buffer_length); + + QUEUE_Init(&mqttClient->msgQueue, QUEUE_BUFFER_SIZE); + + system_os_task(MQTT_Task, MQTT_TASK_PRIO, mqtt_procTaskQueue, MQTT_TASK_QUEUE_SIZE); + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)mqttClient); + return true; +} +void ICACHE_FLASH_ATTR +MQTT_InitLWT(MQTT_Client *mqttClient, uint8_t* will_topic, uint8_t* will_msg, uint8_t will_qos, uint8_t will_retain) +{ + uint32_t temp; + temp = os_strlen(will_topic); + mqttClient->connect_info.will_topic = (uint8_t*)os_zalloc(temp + 1); + os_strcpy(mqttClient->connect_info.will_topic, will_topic); + mqttClient->connect_info.will_topic[temp] = 0; + + temp = os_strlen(will_msg); + mqttClient->connect_info.will_message = (uint8_t*)os_zalloc(temp + 1); + os_strcpy(mqttClient->connect_info.will_message, will_msg); + mqttClient->connect_info.will_message[temp] = 0; + + + mqttClient->connect_info.will_qos = will_qos; + mqttClient->connect_info.will_retain = will_retain; +} +/** + * @brief Begin connect to MQTT broker + * @param client: MQTT_Client reference + * @retval None + */ +void ICACHE_FLASH_ATTR +MQTT_Connect(MQTT_Client *mqttClient) +{ + if (mqttClient->pCon) { + // Clean up the old connection forcefully - using MQTT_Disconnect + // does not actually release the old connection until the + // disconnection callback is invoked. + mqtt_tcpclient_delete(mqttClient); + } + mqttClient->pCon = (struct espconn *)os_zalloc(sizeof(struct espconn)); + mqttClient->pCon->type = ESPCONN_TCP; + mqttClient->pCon->state = ESPCONN_NONE; + mqttClient->pCon->proto.tcp = (esp_tcp *)os_zalloc(sizeof(esp_tcp)); + mqttClient->pCon->proto.tcp->local_port = espconn_port(); + mqttClient->pCon->proto.tcp->remote_port = mqttClient->port; + mqttClient->pCon->reverse = mqttClient; + espconn_regist_connectcb(mqttClient->pCon, mqtt_tcpclient_connect_cb); + espconn_regist_reconcb(mqttClient->pCon, mqtt_tcpclient_recon_cb); + + mqttClient->keepAliveTick = 0; + mqttClient->reconnectTick = 0; + + + os_timer_disarm(&mqttClient->mqttTimer); + os_timer_setfn(&mqttClient->mqttTimer, (os_timer_func_t *)mqtt_timer, mqttClient); + os_timer_arm(&mqttClient->mqttTimer, 1000, 1); + + if (UTILS_StrToIP(mqttClient->host, &mqttClient->pCon->proto.tcp->remote_ip)) { + MQTT_INFO("TCP: Connect to ip %s:%d\r\n", mqttClient->host, mqttClient->port); + if (mqttClient->security) + { +#ifdef MQTT_SSL_ENABLE + espconn_secure_set_size(ESPCONN_CLIENT, MQTT_SSL_SIZE); + espconn_secure_connect(mqttClient->pCon); +#else + MQTT_INFO("TCP: Do not support SSL\r\n"); +#endif + } + else + { + espconn_connect(mqttClient->pCon); + } + } + else { + MQTT_INFO("TCP: Connect to domain %s:%d\r\n", mqttClient->host, mqttClient->port); + espconn_gethostbyname(mqttClient->pCon, mqttClient->host, &mqttClient->ip, mqtt_dns_found); + } + mqttClient->connState = TCP_CONNECTING; +} + +void ICACHE_FLASH_ATTR +MQTT_Disconnect(MQTT_Client *mqttClient) +{ + mqttClient->connState = TCP_DISCONNECTING; + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)mqttClient); + os_timer_disarm(&mqttClient->mqttTimer); +} + +void ICACHE_FLASH_ATTR +MQTT_DeleteClient(MQTT_Client *mqttClient) +{ + if (NULL == mqttClient) + return; + + mqttClient->connState = MQTT_DELETED; + // if(TCP_DISCONNECTED == mqttClient->connState) { + // mqttClient->connState = MQTT_DELETED; + // } else if(MQTT_DELETED != mqttClient->connState) { + // mqttClient->connState = MQTT_DELETING; + // } + + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)mqttClient); + os_timer_disarm(&mqttClient->mqttTimer); +} + +void ICACHE_FLASH_ATTR +MQTT_OnConnected(MQTT_Client *mqttClient, MqttCallback connectedCb) +{ + mqttClient->connectedCb = connectedCb; +} + +void ICACHE_FLASH_ATTR +MQTT_OnDisconnected(MQTT_Client *mqttClient, MqttCallback disconnectedCb) +{ + mqttClient->disconnectedCb = disconnectedCb; +} + +void ICACHE_FLASH_ATTR +MQTT_OnData(MQTT_Client *mqttClient, MqttDataCallback dataCb) +{ + mqttClient->dataCb = dataCb; +} + +void ICACHE_FLASH_ATTR +MQTT_OnPublished(MQTT_Client *mqttClient, MqttCallback publishedCb) +{ + mqttClient->publishedCb = publishedCb; +} + +void ICACHE_FLASH_ATTR +MQTT_OnTimeout(MQTT_Client *mqttClient, MqttCallback timeoutCb) +{ + mqttClient->timeoutCb = timeoutCb; +} diff --git a/lib/TasmotaMqtt-1.1.1/src/mqtt/mqtt.h b/lib/TasmotaMqtt-1.1.1/src/mqtt/mqtt.h new file mode 100644 index 000000000..96489107e --- /dev/null +++ b/lib/TasmotaMqtt-1.1.1/src/mqtt/mqtt.h @@ -0,0 +1,148 @@ +/* mqtt.h +* +* Copyright (c) 2014-2015, Tuan PM +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* +* * Redistributions of source code must retain the above copyright notice, +* this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of Redis nor the names of its contributors may be used +* to endorse or promote products derived from this software without +* specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +* POSSIBILITY OF SUCH DAMAGE. +*/ +#ifndef USER_AT_MQTT_H_ +#define USER_AT_MQTT_H_ +#include "user_config.h" +#include "mqtt_msg.h" +#include "user_interface.h" + +#include "queue.h" +typedef struct mqtt_event_data_t +{ + uint8_t type; + const char* topic; + const char* data; + uint16_t topic_length; + uint16_t data_length; + uint16_t data_offset; +} mqtt_event_data_t; + +typedef struct mqtt_state_t +{ + uint16_t port; + int auto_reconnect; + mqtt_connect_info_t* connect_info; + uint8_t* in_buffer; + uint8_t* out_buffer; + int in_buffer_length; + int out_buffer_length; + uint16_t message_length; + uint16_t message_length_read; + mqtt_message_t* outbound_message; + mqtt_connection_t mqtt_connection; + uint16_t pending_msg_id; + int pending_msg_type; + int pending_publish_qos; +} mqtt_state_t; + +typedef enum { + WIFI_INIT, + WIFI_CONNECTING, + WIFI_CONNECTING_ERROR, + WIFI_CONNECTED, + DNS_RESOLVE, + TCP_DISCONNECTING, + TCP_DISCONNECTED, + TCP_RECONNECT_DISCONNECTING, + TCP_RECONNECT_REQ, + TCP_RECONNECT, + TCP_CONNECTING, + TCP_CONNECTING_ERROR, + TCP_CONNECTED, + MQTT_CONNECT_SEND, + MQTT_CONNECT_SENDING, + MQTT_SUBSCIBE_SEND, + MQTT_SUBSCIBE_SENDING, + MQTT_DATA, + MQTT_KEEPALIVE_SEND, + MQTT_PUBLISH_RECV, + MQTT_PUBLISHING, + MQTT_DELETING, + MQTT_DELETED, +} tConnState; + +typedef void (*MqttCallback)(uint32_t *args); +typedef void (*MqttDataCallback)(uint32_t *args, const char* topic, uint32_t topic_len, const char *data, uint32_t lengh); + +typedef struct { + struct espconn *pCon; + uint8_t security; + uint8_t* host; + uint32_t port; + ip_addr_t ip; + mqtt_state_t mqtt_state; + mqtt_connect_info_t connect_info; + MqttCallback connectedCb; + MqttCallback disconnectedCb; + MqttCallback publishedCb; + MqttCallback timeoutCb; + MqttDataCallback dataCb; + ETSTimer mqttTimer; + uint32_t keepAliveTick; + uint32_t reconnectTick; + uint32_t sendTimeout; + tConnState connState; + QUEUE msgQueue; + void* user_data; +} MQTT_Client; + +#define SEC_NONSSL 0 +#define SEC_SSL 1 + +#define MQTT_FLAG_CONNECTED 1 +#define MQTT_FLAG_READY 2 +#define MQTT_FLAG_EXIT 4 + +#define MQTT_EVENT_TYPE_NONE 0 +#define MQTT_EVENT_TYPE_CONNECTED 1 +#define MQTT_EVENT_TYPE_DISCONNECTED 2 +#define MQTT_EVENT_TYPE_SUBSCRIBED 3 +#define MQTT_EVENT_TYPE_UNSUBSCRIBED 4 +#define MQTT_EVENT_TYPE_PUBLISH 5 +#define MQTT_EVENT_TYPE_PUBLISHED 6 +#define MQTT_EVENT_TYPE_EXITED 7 +#define MQTT_EVENT_TYPE_PUBLISH_CONTINUATION 8 + +void ICACHE_FLASH_ATTR MQTT_InitConnection(MQTT_Client *mqttClient, uint8_t* host, uint32_t port, uint8_t security); +bool ICACHE_FLASH_ATTR MQTT_InitClient(MQTT_Client *mqttClient, uint8_t* client_id, uint8_t* client_user, uint8_t* client_pass, uint32_t keepAliveTime, uint8_t cleanSession); +void ICACHE_FLASH_ATTR MQTT_DeleteClient(MQTT_Client *mqttClient); +void ICACHE_FLASH_ATTR MQTT_InitLWT(MQTT_Client *mqttClient, uint8_t* will_topic, uint8_t* will_msg, uint8_t will_qos, uint8_t will_retain); +void ICACHE_FLASH_ATTR MQTT_OnConnected(MQTT_Client *mqttClient, MqttCallback connectedCb); +void ICACHE_FLASH_ATTR MQTT_OnDisconnected(MQTT_Client *mqttClient, MqttCallback disconnectedCb); +void ICACHE_FLASH_ATTR MQTT_OnPublished(MQTT_Client *mqttClient, MqttCallback publishedCb); +void ICACHE_FLASH_ATTR MQTT_OnTimeout(MQTT_Client *mqttClient, MqttCallback timeoutCb); +void ICACHE_FLASH_ATTR MQTT_OnData(MQTT_Client *mqttClient, MqttDataCallback dataCb); +bool ICACHE_FLASH_ATTR MQTT_Subscribe(MQTT_Client *client, char* topic, uint8_t qos); +bool ICACHE_FLASH_ATTR MQTT_UnSubscribe(MQTT_Client *client, char* topic); +void ICACHE_FLASH_ATTR MQTT_Connect(MQTT_Client *mqttClient); +void ICACHE_FLASH_ATTR MQTT_Disconnect(MQTT_Client *mqttClient); +bool ICACHE_FLASH_ATTR MQTT_Publish(MQTT_Client *client, const char* topic, const char* data, int data_length, int qos, int retain); + +#endif /* USER_AT_MQTT_H_ */ diff --git a/lib/TasmotaMqtt-1.1.1/src/mqtt/mqtt_msg.c b/lib/TasmotaMqtt-1.1.1/src/mqtt/mqtt_msg.c new file mode 100644 index 000000000..57dcbac27 --- /dev/null +++ b/lib/TasmotaMqtt-1.1.1/src/mqtt/mqtt_msg.c @@ -0,0 +1,487 @@ +/* +* Copyright (c) 2014, Stephen Robinson +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions +* are met: +* +* 1. Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* 2. Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* 3. Neither the name of the copyright holder nor the names of its +* contributors may be used to endorse or promote products derived +* from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +* POSSIBILITY OF SUCH DAMAGE. +* +*/ + +#include +#include "mqtt_msg.h" +#include "user_config.h" +#define MQTT_MAX_FIXED_HEADER_SIZE 3 + +enum mqtt_connect_flag +{ + MQTT_CONNECT_FLAG_USERNAME = 1 << 7, + MQTT_CONNECT_FLAG_PASSWORD = 1 << 6, + MQTT_CONNECT_FLAG_WILL_RETAIN = 1 << 5, + MQTT_CONNECT_FLAG_WILL = 1 << 2, + MQTT_CONNECT_FLAG_CLEAN_SESSION = 1 << 1 +}; + +struct __attribute((__packed__)) mqtt_connect_variable_header +{ + uint8_t lengthMsb; + uint8_t lengthLsb; +#if defined(PROTOCOL_NAMEv31) + uint8_t magic[6]; +#elif defined(PROTOCOL_NAMEv311) + uint8_t magic[4]; +#else +#error "Please define protocol name" +#endif + uint8_t version; + uint8_t flags; + uint8_t keepaliveMsb; + uint8_t keepaliveLsb; +}; + +static int ICACHE_FLASH_ATTR append_string(mqtt_connection_t* connection, const char* string, int len) +{ + if (connection->message.length + len + 2 > connection->buffer_length) + return -1; + + connection->buffer[connection->message.length++] = len >> 8; + connection->buffer[connection->message.length++] = len & 0xff; + memcpy(connection->buffer + connection->message.length, string, len); + connection->message.length += len; + + return len + 2; +} + +static uint16_t ICACHE_FLASH_ATTR append_message_id(mqtt_connection_t* connection, uint16_t message_id) +{ + // If message_id is zero then we should assign one, otherwise + // we'll use the one supplied by the caller + while (message_id == 0) + message_id = ++connection->message_id; + + if (connection->message.length + 2 > connection->buffer_length) + return 0; + + connection->buffer[connection->message.length++] = message_id >> 8; + connection->buffer[connection->message.length++] = message_id & 0xff; + + return message_id; +} + +static int ICACHE_FLASH_ATTR init_message(mqtt_connection_t* connection) +{ + connection->message.length = MQTT_MAX_FIXED_HEADER_SIZE; + return MQTT_MAX_FIXED_HEADER_SIZE; +} + +static mqtt_message_t* ICACHE_FLASH_ATTR fail_message(mqtt_connection_t* connection) +{ + connection->message.data = connection->buffer; + connection->message.length = 0; + return &connection->message; +} + +static mqtt_message_t* ICACHE_FLASH_ATTR fini_message(mqtt_connection_t* connection, int type, int dup, int qos, int retain) +{ + int remaining_length = connection->message.length - MQTT_MAX_FIXED_HEADER_SIZE; + + if (remaining_length > 127) + { + connection->buffer[0] = ((type & 0x0f) << 4) | ((dup & 1) << 3) | ((qos & 3) << 1) | (retain & 1); + connection->buffer[1] = 0x80 | (remaining_length % 128); + connection->buffer[2] = remaining_length / 128; + connection->message.length = remaining_length + 3; + connection->message.data = connection->buffer; + } + else + { + connection->buffer[1] = ((type & 0x0f) << 4) | ((dup & 1) << 3) | ((qos & 3) << 1) | (retain & 1); + connection->buffer[2] = remaining_length; + connection->message.length = remaining_length + 2; + connection->message.data = connection->buffer + 1; + } + + return &connection->message; +} + +void ICACHE_FLASH_ATTR mqtt_msg_init(mqtt_connection_t* connection, uint8_t* buffer, uint16_t buffer_length) +{ + memset(connection, 0, sizeof(mqtt_connection_t)); + connection->buffer = buffer; + connection->buffer_length = buffer_length; +} + +int ICACHE_FLASH_ATTR mqtt_get_total_length(uint8_t* buffer, uint16_t length) +{ + int i; + int totlen = 0; + + for (i = 1; i < length; ++i) + { + totlen += (buffer[i] & 0x7f) << (7 * (i - 1)); + if ((buffer[i] & 0x80) == 0) + { + ++i; + break; + } + } + totlen += i; + + return totlen; +} + +const char* ICACHE_FLASH_ATTR mqtt_get_publish_topic(uint8_t* buffer, uint16_t* length) +{ + int i; + int totlen = 0; + int topiclen; + + for (i = 1; i < *length; ++i) + { + totlen += (buffer[i] & 0x7f) << (7 * (i - 1)); + if ((buffer[i] & 0x80) == 0) + { + ++i; + break; + } + } + totlen += i; + + if (i + 2 >= *length) + return NULL; + topiclen = buffer[i++] << 8; + topiclen |= buffer[i++]; + + if (i + topiclen > *length) + return NULL; + + *length = topiclen; + return (const char*)(buffer + i); +} + +const char* ICACHE_FLASH_ATTR mqtt_get_publish_data(uint8_t* buffer, uint16_t* length) +{ + int i; + int totlen = 0; + int topiclen; + int blength = *length; + *length = 0; + + for (i = 1; i < blength; ++i) + { + totlen += (buffer[i] & 0x7f) << (7 * (i - 1)); + if ((buffer[i] & 0x80) == 0) + { + ++i; + break; + } + } + totlen += i; + + if (i + 2 >= blength) + return NULL; + topiclen = buffer[i++] << 8; + topiclen |= buffer[i++]; + + if (i + topiclen >= blength) + return NULL; + + i += topiclen; + + if (mqtt_get_qos(buffer) > 0) + { + if (i + 2 >= blength) + return NULL; + i += 2; + } + + if (totlen < i) + return NULL; + + if (totlen <= blength) + *length = totlen - i; + else + *length = blength - i; + return (const char*)(buffer + i); +} + +uint16_t ICACHE_FLASH_ATTR mqtt_get_id(uint8_t* buffer, uint16_t length) +{ + if (length < 1) + return 0; + + switch (mqtt_get_type(buffer)) + { + case MQTT_MSG_TYPE_PUBLISH: + { + int i; + int topiclen; + + for (i = 1; i < length; ++i) + { + if ((buffer[i] & 0x80) == 0) + { + ++i; + break; + } + } + + if (i + 2 >= length) + return 0; + topiclen = buffer[i++] << 8; + topiclen |= buffer[i++]; + + if (i + topiclen >= length) + return 0; + i += topiclen; + + if (mqtt_get_qos(buffer) > 0) + { + if (i + 2 >= length) + return 0; + //i += 2; + } else { + return 0; + } + + return (buffer[i] << 8) | buffer[i + 1]; + } + case MQTT_MSG_TYPE_PUBACK: + case MQTT_MSG_TYPE_PUBREC: + case MQTT_MSG_TYPE_PUBREL: + case MQTT_MSG_TYPE_PUBCOMP: + case MQTT_MSG_TYPE_SUBACK: + case MQTT_MSG_TYPE_UNSUBACK: + case MQTT_MSG_TYPE_SUBSCRIBE: + { + // This requires the remaining length to be encoded in 1 byte, + // which it should be. + if (length >= 4 && (buffer[1] & 0x80) == 0) + return (buffer[2] << 8) | buffer[3]; + else + return 0; + } + + default: + return 0; + } +} + +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_connect(mqtt_connection_t* connection, mqtt_connect_info_t* info) +{ + struct mqtt_connect_variable_header* variable_header; + + init_message(connection); + + if (connection->message.length + sizeof(*variable_header) > connection->buffer_length) + return fail_message(connection); + variable_header = (void*)(connection->buffer + connection->message.length); + connection->message.length += sizeof(*variable_header); + + variable_header->lengthMsb = 0; +#if defined(PROTOCOL_NAMEv31) + variable_header->lengthLsb = 6; + memcpy(variable_header->magic, "MQIsdp", 6); + variable_header->version = 3; +#elif defined(PROTOCOL_NAMEv311) + variable_header->lengthLsb = 4; + memcpy(variable_header->magic, "MQTT", 4); + variable_header->version = 4; +#else +#error "Please define protocol name" +#endif + + variable_header->flags = 0; + variable_header->keepaliveMsb = info->keepalive >> 8; + variable_header->keepaliveLsb = info->keepalive & 0xff; + + if (info->clean_session) + variable_header->flags |= MQTT_CONNECT_FLAG_CLEAN_SESSION; + + if (info->client_id == NULL) + { + /* Never allowed */ + return fail_message(connection); + } + else if (info->client_id[0] == '\0') + { +#ifdef PROTOCOL_NAMEv311 + /* Allowed. Format 0 Length ID */ + append_string(connection, info->client_id, 2) ; +#else + /* 0 Length not allowed */ + return fail_message(connection); +#endif + } + else + { + /* No 0 data and at least 1 long. Good to go. */ + if(append_string(connection, info->client_id, strlen(info->client_id)) < 0) + return fail_message(connection); + } + + if (info->will_topic != NULL && info->will_topic[0] != '\0') + { + if (append_string(connection, info->will_topic, strlen(info->will_topic)) < 0) + return fail_message(connection); + + if (append_string(connection, info->will_message, strlen(info->will_message)) < 0) + return fail_message(connection); + + variable_header->flags |= MQTT_CONNECT_FLAG_WILL; + if (info->will_retain) + variable_header->flags |= MQTT_CONNECT_FLAG_WILL_RETAIN; + variable_header->flags |= (info->will_qos & 3) << 3; + } + + if (info->username != NULL && info->username[0] != '\0') + { + if (append_string(connection, info->username, strlen(info->username)) < 0) + return fail_message(connection); + + variable_header->flags |= MQTT_CONNECT_FLAG_USERNAME; + } + + if (info->password != NULL && info->password[0] != '\0') + { + if (append_string(connection, info->password, strlen(info->password)) < 0) + return fail_message(connection); + + variable_header->flags |= MQTT_CONNECT_FLAG_PASSWORD; + } + + return fini_message(connection, MQTT_MSG_TYPE_CONNECT, 0, 0, 0); +} + +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_publish(mqtt_connection_t* connection, const char* topic, const char* data, int data_length, int qos, int retain, uint16_t* message_id) +{ + init_message(connection); + + if (topic == NULL || topic[0] == '\0') + return fail_message(connection); + + if (append_string(connection, topic, strlen(topic)) < 0) + return fail_message(connection); + + if (qos > 0) + { + if ((*message_id = append_message_id(connection, 0)) == 0) + return fail_message(connection); + } + else + *message_id = 0; + + if (connection->message.length + data_length > connection->buffer_length) + return fail_message(connection); + memcpy(connection->buffer + connection->message.length, data, data_length); + connection->message.length += data_length; + + return fini_message(connection, MQTT_MSG_TYPE_PUBLISH, 0, qos, retain); +} + +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_puback(mqtt_connection_t* connection, uint16_t message_id) +{ + init_message(connection); + if (append_message_id(connection, message_id) == 0) + return fail_message(connection); + return fini_message(connection, MQTT_MSG_TYPE_PUBACK, 0, 0, 0); +} + +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pubrec(mqtt_connection_t* connection, uint16_t message_id) +{ + init_message(connection); + if (append_message_id(connection, message_id) == 0) + return fail_message(connection); + return fini_message(connection, MQTT_MSG_TYPE_PUBREC, 0, 0, 0); +} + +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pubrel(mqtt_connection_t* connection, uint16_t message_id) +{ + init_message(connection); + if (append_message_id(connection, message_id) == 0) + return fail_message(connection); + return fini_message(connection, MQTT_MSG_TYPE_PUBREL, 0, 1, 0); +} + +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pubcomp(mqtt_connection_t* connection, uint16_t message_id) +{ + init_message(connection); + if (append_message_id(connection, message_id) == 0) + return fail_message(connection); + return fini_message(connection, MQTT_MSG_TYPE_PUBCOMP, 0, 0, 0); +} + +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_subscribe(mqtt_connection_t* connection, const char* topic, int qos, uint16_t* message_id) +{ + init_message(connection); + + if (topic == NULL || topic[0] == '\0') + return fail_message(connection); + + if ((*message_id = append_message_id(connection, 0)) == 0) + return fail_message(connection); + + if (append_string(connection, topic, strlen(topic)) < 0) + return fail_message(connection); + + if (connection->message.length + 1 > connection->buffer_length) + return fail_message(connection); + connection->buffer[connection->message.length++] = qos; + + return fini_message(connection, MQTT_MSG_TYPE_SUBSCRIBE, 0, 1, 0); +} + +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_unsubscribe(mqtt_connection_t* connection, const char* topic, uint16_t* message_id) +{ + init_message(connection); + + if (topic == NULL || topic[0] == '\0') + return fail_message(connection); + + if ((*message_id = append_message_id(connection, 0)) == 0) + return fail_message(connection); + + if (append_string(connection, topic, strlen(topic)) < 0) + return fail_message(connection); + + return fini_message(connection, MQTT_MSG_TYPE_UNSUBSCRIBE, 0, 1, 0); +} + +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pingreq(mqtt_connection_t* connection) +{ + init_message(connection); + return fini_message(connection, MQTT_MSG_TYPE_PINGREQ, 0, 0, 0); +} + +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pingresp(mqtt_connection_t* connection) +{ + init_message(connection); + return fini_message(connection, MQTT_MSG_TYPE_PINGRESP, 0, 0, 0); +} + +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_disconnect(mqtt_connection_t* connection) +{ + init_message(connection); + return fini_message(connection, MQTT_MSG_TYPE_DISCONNECT, 0, 0, 0); +} diff --git a/lib/TasmotaMqtt-1.1.1/src/mqtt/mqtt_msg.h b/lib/TasmotaMqtt-1.1.1/src/mqtt/mqtt_msg.h new file mode 100644 index 000000000..be3cc55cb --- /dev/null +++ b/lib/TasmotaMqtt-1.1.1/src/mqtt/mqtt_msg.h @@ -0,0 +1,141 @@ +/* + * File: mqtt_msg.h + * Author: Minh Tuan + * + * Created on July 12, 2014, 1:05 PM + */ + +#ifndef MQTT_MSG_H +#define MQTT_MSG_H +#include "user_config.h" +#include "c_types.h" +#ifdef __cplusplus +extern "C" { +#endif + +/* +* Copyright (c) 2014, Stephen Robinson +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions +* are met: +* +* 1. Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* 2. Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* 3. Neither the name of the copyright holder nor the names of its +* contributors may be used to endorse or promote products derived +* from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +* POSSIBILITY OF SUCH DAMAGE. +* +*/ +/* 7 6 5 4 3 2 1 0*/ +/*| --- Message Type---- | DUP Flag | QoS Level | Retain | +/* Remaining Length */ + + +enum mqtt_message_type +{ + MQTT_MSG_TYPE_CONNECT = 1, + MQTT_MSG_TYPE_CONNACK = 2, + MQTT_MSG_TYPE_PUBLISH = 3, + MQTT_MSG_TYPE_PUBACK = 4, + MQTT_MSG_TYPE_PUBREC = 5, + MQTT_MSG_TYPE_PUBREL = 6, + MQTT_MSG_TYPE_PUBCOMP = 7, + MQTT_MSG_TYPE_SUBSCRIBE = 8, + MQTT_MSG_TYPE_SUBACK = 9, + MQTT_MSG_TYPE_UNSUBSCRIBE = 10, + MQTT_MSG_TYPE_UNSUBACK = 11, + MQTT_MSG_TYPE_PINGREQ = 12, + MQTT_MSG_TYPE_PINGRESP = 13, + MQTT_MSG_TYPE_DISCONNECT = 14 +}; + +enum mqtt_connect_return_code +{ + CONNECTION_ACCEPTED = 0, + CONNECTION_REFUSE_PROTOCOL, + CONNECTION_REFUSE_ID_REJECTED, + CONNECTION_REFUSE_SERVER_UNAVAILABLE, + CONNECTION_REFUSE_BAD_USERNAME, + CONNECTION_REFUSE_NOT_AUTHORIZED +}; + +typedef struct mqtt_message +{ + uint8_t* data; + uint16_t length; + +} mqtt_message_t; + +typedef struct mqtt_connection +{ + mqtt_message_t message; + + uint16_t message_id; + uint8_t* buffer; + uint16_t buffer_length; + +} mqtt_connection_t; + +typedef struct mqtt_connect_info +{ + char* client_id; + char* username; + char* password; + char* will_topic; + char* will_message; + uint32_t keepalive; + int will_qos; + int will_retain; + int clean_session; + +} mqtt_connect_info_t; + + +static inline int ICACHE_FLASH_ATTR mqtt_get_type(uint8_t* buffer) { return (buffer[0] & 0xf0) >> 4; } +static inline int ICACHE_FLASH_ATTR mqtt_get_connect_return_code(uint8_t* buffer) { return buffer[3]; } +static inline int ICACHE_FLASH_ATTR mqtt_get_dup(uint8_t* buffer) { return (buffer[0] & 0x08) >> 3; } +static inline int ICACHE_FLASH_ATTR mqtt_get_qos(uint8_t* buffer) { return (buffer[0] & 0x06) >> 1; } +static inline int ICACHE_FLASH_ATTR mqtt_get_retain(uint8_t* buffer) { return (buffer[0] & 0x01); } + +void ICACHE_FLASH_ATTR mqtt_msg_init(mqtt_connection_t* connection, uint8_t* buffer, uint16_t buffer_length); +int ICACHE_FLASH_ATTR mqtt_get_total_length(uint8_t* buffer, uint16_t length); +const char* ICACHE_FLASH_ATTR mqtt_get_publish_topic(uint8_t* buffer, uint16_t* length); +const char* ICACHE_FLASH_ATTR mqtt_get_publish_data(uint8_t* buffer, uint16_t* length); +uint16_t ICACHE_FLASH_ATTR mqtt_get_id(uint8_t* buffer, uint16_t length); + +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_connect(mqtt_connection_t* connection, mqtt_connect_info_t* info); +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_publish(mqtt_connection_t* connection, const char* topic, const char* data, int data_length, int qos, int retain, uint16_t* message_id); +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_puback(mqtt_connection_t* connection, uint16_t message_id); +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pubrec(mqtt_connection_t* connection, uint16_t message_id); +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pubrel(mqtt_connection_t* connection, uint16_t message_id); +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pubcomp(mqtt_connection_t* connection, uint16_t message_id); +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_subscribe(mqtt_connection_t* connection, const char* topic, int qos, uint16_t* message_id); +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_unsubscribe(mqtt_connection_t* connection, const char* topic, uint16_t* message_id); +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pingreq(mqtt_connection_t* connection); +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pingresp(mqtt_connection_t* connection); +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_disconnect(mqtt_connection_t* connection); + + +#ifdef __cplusplus +} +#endif + +#endif /* MQTT_MSG_H */ + diff --git a/lib/TasmotaMqtt-1.1.1/src/mqtt/proto.c b/lib/TasmotaMqtt-1.1.1/src/mqtt/proto.c new file mode 100644 index 000000000..84078b233 --- /dev/null +++ b/lib/TasmotaMqtt-1.1.1/src/mqtt/proto.c @@ -0,0 +1,129 @@ +#include "proto.h" +#include "ringbuf.h" +I8 ICACHE_FLASH_ATTR PROTO_Init(PROTO_PARSER *parser, PROTO_PARSE_CALLBACK *completeCallback, U8 *buf, U16 bufSize) +{ + parser->buf = buf; + parser->bufSize = bufSize; + parser->dataLen = 0; + parser->callback = completeCallback; + parser->isEsc = 0; + return 0; +} + +I8 ICACHE_FLASH_ATTR PROTO_ParseByte(PROTO_PARSER *parser, U8 value) +{ + switch (value) { + case 0x7D: + parser->isEsc = 1; + break; + + case 0x7E: + parser->dataLen = 0; + parser->isEsc = 0; + parser->isBegin = 1; + break; + + case 0x7F: + if (parser->callback != NULL) + parser->callback(); + parser->isBegin = 0; + return 0; + break; + + default: + if (parser->isBegin == 0) break; + + if (parser->isEsc) { + value ^= 0x20; + parser->isEsc = 0; + } + + if (parser->dataLen < parser->bufSize) + parser->buf[parser->dataLen++] = value; + + break; + } + return -1; +} + +I8 ICACHE_FLASH_ATTR PROTO_Parse(PROTO_PARSER *parser, U8 *buf, U16 len) +{ + while (len--) + PROTO_ParseByte(parser, *buf++); + + return 0; +} +I16 ICACHE_FLASH_ATTR PROTO_ParseRb(RINGBUF* rb, U8 *bufOut, U16* len, U16 maxBufLen) +{ + U8 c; + + PROTO_PARSER proto; + PROTO_Init(&proto, NULL, bufOut, maxBufLen); + while (RINGBUF_Get(rb, &c) == 0) { + if (PROTO_ParseByte(&proto, c) == 0) { + *len = proto.dataLen; + return 0; + } + } + return -1; +} +I16 ICACHE_FLASH_ATTR PROTO_Add(U8 *buf, const U8 *packet, I16 bufSize) +{ + U16 i = 2; + U16 len = *(U16*) packet; + + if (bufSize < 1) return -1; + + *buf++ = 0x7E; + bufSize--; + + while (len--) { + switch (*packet) { + case 0x7D: + case 0x7E: + case 0x7F: + if (bufSize < 2) return -1; + *buf++ = 0x7D; + *buf++ = *packet++ ^ 0x20; + i += 2; + bufSize -= 2; + break; + default: + if (bufSize < 1) return -1; + *buf++ = *packet++; + i++; + bufSize--; + break; + } + } + + if (bufSize < 1) return -1; + *buf++ = 0x7F; + + return i; +} + +I16 ICACHE_FLASH_ATTR PROTO_AddRb(RINGBUF *rb, const U8 *packet, I16 len) +{ + U16 i = 2; + if (RINGBUF_Put(rb, 0x7E) == -1) return -1; + while (len--) { + switch (*packet) { + case 0x7D: + case 0x7E: + case 0x7F: + if (RINGBUF_Put(rb, 0x7D) == -1) return -1; + if (RINGBUF_Put(rb, *packet++ ^ 0x20) == -1) return -1; + i += 2; + break; + default: + if (RINGBUF_Put(rb, *packet++) == -1) return -1; + i++; + break; + } + } + if (RINGBUF_Put(rb, 0x7F) == -1) return -1; + + return i; +} + diff --git a/lib/TasmotaMqtt-1.1.1/src/mqtt/proto.h b/lib/TasmotaMqtt-1.1.1/src/mqtt/proto.h new file mode 100644 index 000000000..a405bcb95 --- /dev/null +++ b/lib/TasmotaMqtt-1.1.1/src/mqtt/proto.h @@ -0,0 +1,32 @@ +/* + * File: proto.h + * Author: ThuHien + * + * Created on November 23, 2012, 8:57 AM + */ + +#ifndef _PROTO_H_ +#define _PROTO_H_ +#include +#include "typedef.h" +#include "ringbuf.h" + +typedef void(PROTO_PARSE_CALLBACK)(); + +typedef struct { + U8 *buf; + U16 bufSize; + U16 dataLen; + U8 isEsc; + U8 isBegin; + PROTO_PARSE_CALLBACK* callback; +} PROTO_PARSER; + +I8 ICACHE_FLASH_ATTR PROTO_Init(PROTO_PARSER *parser, PROTO_PARSE_CALLBACK *completeCallback, U8 *buf, U16 bufSize); +I8 ICACHE_FLASH_ATTR PROTO_Parse(PROTO_PARSER *parser, U8 *buf, U16 len); +I16 ICACHE_FLASH_ATTR PROTO_Add(U8 *buf, const U8 *packet, I16 bufSize); +I16 ICACHE_FLASH_ATTR PROTO_AddRb(RINGBUF *rb, const U8 *packet, I16 len); +I8 ICACHE_FLASH_ATTR PROTO_ParseByte(PROTO_PARSER *parser, U8 value); +I16 ICACHE_FLASH_ATTR PROTO_ParseRb(RINGBUF *rb, U8 *bufOut, U16* len, U16 maxBufLen); +#endif + diff --git a/lib/TasmotaMqtt-1.1.1/src/mqtt/queue.c b/lib/TasmotaMqtt-1.1.1/src/mqtt/queue.c new file mode 100644 index 000000000..5e4216d0f --- /dev/null +++ b/lib/TasmotaMqtt-1.1.1/src/mqtt/queue.c @@ -0,0 +1,75 @@ +/* str_queue.c +* +* Copyright (c) 2014-2015, Tuan PM +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* +* * Redistributions of source code must retain the above copyright notice, +* this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of Redis nor the names of its contributors may be used +* to endorse or promote products derived from this software without +* specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +* POSSIBILITY OF SUCH DAMAGE. +*/ +#include "queue.h" + +#include "user_interface.h" +#include "osapi.h" +#include "os_type.h" +#include "mem.h" +#include "proto.h" + +uint8_t *last_rb_p_r; +uint8_t *last_rb_p_w; +uint32_t last_fill_cnt; + +void ICACHE_FLASH_ATTR QUEUE_Init(QUEUE *queue, int bufferSize) +{ + queue->buf = (uint8_t*)os_zalloc(bufferSize); + RINGBUF_Init(&queue->rb, queue->buf, bufferSize); +} +int32_t ICACHE_FLASH_ATTR QUEUE_Puts(QUEUE *queue, uint8_t* buffer, uint16_t len) +{ + uint32_t ret; + + last_rb_p_r = queue->rb.p_r; + last_rb_p_w = queue->rb.p_w; + last_fill_cnt = queue->rb.fill_cnt; + + ret = PROTO_AddRb(&queue->rb, buffer, len); + if (ret == -1) { + // rolling ring buffer back + queue->rb.p_r = last_rb_p_r; + queue->rb.p_w = last_rb_p_w; + queue->rb.fill_cnt = last_fill_cnt; + } + return ret; +} +int32_t ICACHE_FLASH_ATTR QUEUE_Gets(QUEUE *queue, uint8_t* buffer, uint16_t* len, uint16_t maxLen) +{ + + return PROTO_ParseRb(&queue->rb, buffer, len, maxLen); +} + +bool ICACHE_FLASH_ATTR QUEUE_IsEmpty(QUEUE *queue) +{ + if (queue->rb.fill_cnt <= 0) + return TRUE; + return FALSE; +} diff --git a/lib/TasmotaMqtt-1.1.1/src/mqtt/queue.h b/lib/TasmotaMqtt-1.1.1/src/mqtt/queue.h new file mode 100644 index 000000000..79107f2d5 --- /dev/null +++ b/lib/TasmotaMqtt-1.1.1/src/mqtt/queue.h @@ -0,0 +1,44 @@ +/* str_queue.h -- +* +* Copyright (c) 2014-2015, Tuan PM +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* +* * Redistributions of source code must retain the above copyright notice, +* this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of Redis nor the names of its contributors may be used +* to endorse or promote products derived from this software without +* specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +* POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifndef USER_QUEUE_H_ +#define USER_QUEUE_H_ +#include "os_type.h" +#include "ringbuf.h" +typedef struct { + uint8_t *buf; + RINGBUF rb; +} QUEUE; + +void ICACHE_FLASH_ATTR QUEUE_Init(QUEUE *queue, int bufferSize); +int32_t ICACHE_FLASH_ATTR QUEUE_Puts(QUEUE *queue, uint8_t* buffer, uint16_t len); +int32_t ICACHE_FLASH_ATTR QUEUE_Gets(QUEUE *queue, uint8_t* buffer, uint16_t* len, uint16_t maxLen); +bool ICACHE_FLASH_ATTR QUEUE_IsEmpty(QUEUE *queue); +#endif /* USER_QUEUE_H_ */ diff --git a/lib/TasmotaMqtt-1.1.1/src/mqtt/ringbuf.c b/lib/TasmotaMqtt-1.1.1/src/mqtt/ringbuf.c new file mode 100644 index 000000000..fc882fd5c --- /dev/null +++ b/lib/TasmotaMqtt-1.1.1/src/mqtt/ringbuf.c @@ -0,0 +1,67 @@ +/** +* \file +* Ring Buffer library +*/ + +#include "ringbuf.h" + + +/** +* \brief init a RINGBUF object +* \param r pointer to a RINGBUF object +* \param buf pointer to a byte array +* \param size size of buf +* \return 0 if successfull, otherwise failed +*/ +I16 ICACHE_FLASH_ATTR RINGBUF_Init(RINGBUF *r, U8* buf, I32 size) +{ + if (r == NULL || buf == NULL || size < 2) return -1; + + r->p_o = r->p_r = r->p_w = buf; + r->fill_cnt = 0; + r->size = size; + + return 0; +} +/** +* \brief put a character into ring buffer +* \param r pointer to a ringbuf object +* \param c character to be put +* \return 0 if successfull, otherwise failed +*/ +I16 ICACHE_FLASH_ATTR RINGBUF_Put(RINGBUF *r, U8 c) +{ + if (r->fill_cnt >= r->size)return -1; // ring buffer is full, this should be atomic operation + + + r->fill_cnt++; // increase filled slots count, this should be atomic operation + + + *r->p_w++ = c; // put character into buffer + + if (r->p_w >= r->p_o + r->size) // rollback if write pointer go pass + r->p_w = r->p_o; // the physical boundary + + return 0; +} +/** +* \brief get a character from ring buffer +* \param r pointer to a ringbuf object +* \param c read character +* \return 0 if successfull, otherwise failed +*/ +I16 ICACHE_FLASH_ATTR RINGBUF_Get(RINGBUF *r, U8* c) +{ + if (r->fill_cnt <= 0)return -1; // ring buffer is empty, this should be atomic operation + + + r->fill_cnt--; // decrease filled slots count + + + *c = *r->p_r++; // get the character out + + if (r->p_r >= r->p_o + r->size) // rollback if write pointer go pass + r->p_r = r->p_o; // the physical boundary + + return 0; +} diff --git a/lib/TasmotaMqtt-1.1.1/src/mqtt/ringbuf.h b/lib/TasmotaMqtt-1.1.1/src/mqtt/ringbuf.h new file mode 100644 index 000000000..f1a4f7e8b --- /dev/null +++ b/lib/TasmotaMqtt-1.1.1/src/mqtt/ringbuf.h @@ -0,0 +1,19 @@ +#ifndef _RING_BUF_H_ +#define _RING_BUF_H_ + +#include +#include +#include "typedef.h" + +typedef struct { + U8* p_o; /**< Original pointer */ + U8* volatile p_r; /**< Read pointer */ + U8* volatile p_w; /**< Write pointer */ + volatile I32 fill_cnt; /**< Number of filled slots */ + I32 size; /**< Buffer size */ +} RINGBUF; + +I16 ICACHE_FLASH_ATTR RINGBUF_Init(RINGBUF *r, U8* buf, I32 size); +I16 ICACHE_FLASH_ATTR RINGBUF_Put(RINGBUF *r, U8 c); +I16 ICACHE_FLASH_ATTR RINGBUF_Get(RINGBUF *r, U8* c); +#endif diff --git a/lib/TasmotaMqtt-1.1.1/src/mqtt/typedef.h b/lib/TasmotaMqtt-1.1.1/src/mqtt/typedef.h new file mode 100644 index 000000000..887001ace --- /dev/null +++ b/lib/TasmotaMqtt-1.1.1/src/mqtt/typedef.h @@ -0,0 +1,17 @@ +/** +* \file +* Standard Types definition +*/ + +#ifndef _TYPE_DEF_H_ +#define _TYPE_DEF_H_ + +typedef char I8; +typedef unsigned char U8; +typedef short I16; +typedef unsigned short U16; +typedef long I32; +typedef unsigned long U32; +typedef unsigned long long U64; + +#endif diff --git a/lib/TasmotaMqtt-1.1.1/src/mqtt/user_config.h b/lib/TasmotaMqtt-1.1.1/src/mqtt/user_config.h new file mode 100644 index 000000000..125353ed0 --- /dev/null +++ b/lib/TasmotaMqtt-1.1.1/src/mqtt/user_config.h @@ -0,0 +1,15 @@ +#ifndef __MQTT_CONFIG_H__ +#define __MQTT_CONFIG_H__ + +//#define MQTT_SSL_ENABLE + +#define MQTT_RECONNECT_TIMEOUT 5 /*second*/ + +//#define MQTT_BUF_SIZE 1024 +#define MQTT_BUF_SIZE 512 +#define QUEUE_BUFFER_SIZE 2048 + +//#define PROTOCOL_NAMEv31 /*MQTT version 3.1 compatible with Mosquitto v0.15*/ +#define PROTOCOL_NAMEv311 /*MQTT version 3.11 compatible with https://eclipse.org/paho/clients/testing/*/ + +#endif // __MQTT_CONFIG_H__ \ No newline at end of file diff --git a/lib/TasmotaMqtt-1.1.1/src/mqtt/utils.c b/lib/TasmotaMqtt-1.1.1/src/mqtt/utils.c new file mode 100644 index 000000000..ac4c9272b --- /dev/null +++ b/lib/TasmotaMqtt-1.1.1/src/mqtt/utils.c @@ -0,0 +1,149 @@ +/* +* Copyright (c) 2014, Tuan PM +* Email: tuanpm@live.com +* +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions +* are met: +* +* 1. Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* 2. Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* 3. Neither the name of the copyright holder nor the names of its +* contributors may be used to endorse or promote products derived +* from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +* POSSIBILITY OF SUCH DAMAGE. +* +*/ +#include +#include +#include +#include +#include +#include "utils.h" + + +uint8_t ICACHE_FLASH_ATTR UTILS_IsIPV4 (int8_t *str) +{ + uint8_t segs = 0; /* Segment count. */ + uint8_t chcnt = 0; /* Character count within segment. */ + uint8_t accum = 0; /* Accumulator for segment. */ + /* Catch NULL pointer. */ + if (str == 0) + return 0; + /* Process every character in string. */ + + while (*str != '\0') { + /* Segment changeover. */ + + if (*str == '.') { + /* Must have some digits in segment. */ + if (chcnt == 0) + return 0; + /* Limit number of segments. */ + if (++segs == 4) + return 0; + /* Reset segment values and restart loop. */ + chcnt = accum = 0; + str++; + continue; + } + + /* Check numeric. */ + if ((*str < '0') || (*str > '9')) + return 0; + + /* Accumulate and check segment. */ + + if ((accum = accum * 10 + *str - '0') > 255) + return 0; + /* Advance other segment specific stuff and continue loop. */ + + chcnt++; + str++; + } + + /* Check enough segments and enough characters in last segment. */ + + if (segs != 3) + return 0; + if (chcnt == 0) + return 0; + /* Address okay. */ + + return 1; +} +uint8_t ICACHE_FLASH_ATTR UTILS_StrToIP(const int8_t* str, void *ip) +{ + + /* The count of the number of bytes processed. */ + int i; + /* A pointer to the next digit to process. */ + const char * start; + + start = str; + for (i = 0; i < 4; i++) { + /* The digit being processed. */ + char c; + /* The value of this byte. */ + int n = 0; + while (1) { + c = * start; + start++; + if (c >= '0' && c <= '9') { + n *= 10; + n += c - '0'; + } + /* We insist on stopping at "." if we are still parsing + the first, second, or third numbers. If we have reached + the end of the numbers, we will allow any character. */ + else if ((i < 3 && c == '.') || i == 3) { + break; + } + else { + return 0; + } + } + if (n >= 256) { + return 0; + } + ((uint8_t*)ip)[i] = n; + } + return 1; + +} +uint32_t ICACHE_FLASH_ATTR UTILS_Atoh(const int8_t *s) +{ + uint32_t value = 0, digit; + int8_t c; + + while ((c = *s++)) { + if ('0' <= c && c <= '9') + digit = c - '0'; + else if ('A' <= c && c <= 'F') + digit = c - 'A' + 10; + else if ('a' <= c && c <= 'f') + digit = c - 'a' + 10; + else break; + + value = (value << 4) | digit; + } + + return value; +} + diff --git a/lib/TasmotaMqtt-1.1.1/src/mqtt/utils.h b/lib/TasmotaMqtt-1.1.1/src/mqtt/utils.h new file mode 100644 index 000000000..fe2874803 --- /dev/null +++ b/lib/TasmotaMqtt-1.1.1/src/mqtt/utils.h @@ -0,0 +1,9 @@ +#ifndef _UTILS_H_ +#define _UTILS_H_ + +#include "c_types.h" + +uint32_t ICACHE_FLASH_ATTR UTILS_Atoh(const int8_t *s); +uint8_t ICACHE_FLASH_ATTR UTILS_StrToIP(const int8_t* str, void *ip); +uint8_t ICACHE_FLASH_ATTR UTILS_IsIPV4 (int8_t *str); +#endif diff --git a/lib/TasmotaSerial-1.1.0/README.md b/lib/TasmotaSerial-1.2.0/README.md similarity index 79% rename from lib/TasmotaSerial-1.1.0/README.md rename to lib/TasmotaSerial-1.2.0/README.md index 5c7a24721..205a9597c 100644 --- a/lib/TasmotaSerial-1.1.0/README.md +++ b/lib/TasmotaSerial-1.2.0/README.md @@ -1,6 +1,6 @@ # TasmotaSerial -Implementation of software serial library for the ESP8266 at 9600 baud +Implementation of software serial library for the ESP8266 Allows for several instances to be active at the same time. diff --git a/lib/TasmotaSerial-1.1.0/examples/swsertest/swsertest.ino b/lib/TasmotaSerial-1.2.0/examples/swsertest/swsertest.ino similarity index 100% rename from lib/TasmotaSerial-1.1.0/examples/swsertest/swsertest.ino rename to lib/TasmotaSerial-1.2.0/examples/swsertest/swsertest.ino diff --git a/lib/TasmotaSerial-1.1.0/keywords.txt b/lib/TasmotaSerial-1.2.0/keywords.txt similarity index 100% rename from lib/TasmotaSerial-1.1.0/keywords.txt rename to lib/TasmotaSerial-1.2.0/keywords.txt diff --git a/lib/TasmotaSerial-1.1.0/library.json b/lib/TasmotaSerial-1.2.0/library.json similarity index 89% rename from lib/TasmotaSerial-1.1.0/library.json rename to lib/TasmotaSerial-1.2.0/library.json index 986c6d7ac..e4b2ba8a3 100644 --- a/lib/TasmotaSerial-1.1.0/library.json +++ b/lib/TasmotaSerial-1.2.0/library.json @@ -1,10 +1,10 @@ { "name": "TasmotaSerial", - "version": "1.0.0", + "version": "1.2.0", "keywords": [ "serial", "io", "TasmotaSerial" ], - "description": "Implementation of software serial for ESP8266 at 9600 baud.", + "description": "Implementation of software serial for ESP8266.", "repository": { "type": "git", diff --git a/lib/TasmotaSerial-1.1.0/library.properties b/lib/TasmotaSerial-1.2.0/library.properties similarity index 64% rename from lib/TasmotaSerial-1.1.0/library.properties rename to lib/TasmotaSerial-1.2.0/library.properties index 703b613ee..d427d0fb3 100644 --- a/lib/TasmotaSerial-1.1.0/library.properties +++ b/lib/TasmotaSerial-1.2.0/library.properties @@ -1,8 +1,8 @@ name=TasmotaSerial -version=1.0 +version=1.2.0 author=Theo Arends maintainer=Theo Arends -sentence=Implementation of software serial for ESP8266 at 9600 baud. +sentence=Implementation of software serial for ESP8266. paragraph= category=Signal Input/Output url= diff --git a/lib/TasmotaSerial-1.1.0/src/TasmotaSerial.cpp b/lib/TasmotaSerial-1.2.0/src/TasmotaSerial.cpp similarity index 91% rename from lib/TasmotaSerial-1.1.0/src/TasmotaSerial.cpp rename to lib/TasmotaSerial-1.2.0/src/TasmotaSerial.cpp index 35881dfb3..c189442e6 100644 --- a/lib/TasmotaSerial-1.1.0/src/TasmotaSerial.cpp +++ b/lib/TasmotaSerial-1.2.0/src/TasmotaSerial.cpp @@ -87,9 +87,7 @@ TasmotaSerial::TasmotaSerial(int receive_pin, int transmit_pin) m_in_pos = m_out_pos = 0; if (m_rx_pin > -1) { m_buffer = (uint8_t*)malloc(TM_SERIAL_BUFFER_SIZE); - if (m_buffer == NULL) { - return; - } + if (m_buffer == NULL) return; // Use getCycleCount() loop to get as exact timing as possible m_bit_time = ESP.getCpuFreqMHz() *1000000 /TM_SERIAL_BAUDRATE; pinMode(m_rx_pin, INPUT); @@ -111,7 +109,8 @@ bool TasmotaSerial::isValidGPIOpin(int pin) bool TasmotaSerial::begin(long speed) { // Use getCycleCount() loop to get as exact timing as possible m_bit_time = ESP.getCpuFreqMHz() *1000000 /speed; - return m_valid && (speed <= TM_SERIAL_BAUDRATE); + m_high_speed = (speed > 9600); + return m_valid; } bool TasmotaSerial::begin() { @@ -123,17 +122,13 @@ void TasmotaSerial::flush() { } int TasmotaSerial::peek() { - if ((-1 == m_rx_pin) || (m_in_pos == m_out_pos)) { - return -1; - } + if ((-1 == m_rx_pin) || (m_in_pos == m_out_pos)) return -1; return m_buffer[m_out_pos]; } int TasmotaSerial::read() { - if ((-1 == m_rx_pin) || (m_in_pos == m_out_pos)) { - return -1; - } + if ((-1 == m_rx_pin) || (m_in_pos == m_out_pos)) return -1; uint8_t ch = m_buffer[m_out_pos]; m_out_pos = (m_out_pos +1) % TM_SERIAL_BUFFER_SIZE; return ch; @@ -142,23 +137,20 @@ int TasmotaSerial::read() int TasmotaSerial::available() { int avail = m_in_pos - m_out_pos; - if (avail < 0) { - avail += TM_SERIAL_BUFFER_SIZE; - } + if (avail < 0) avail += TM_SERIAL_BUFFER_SIZE; return avail; } #ifdef TM_SERIAL_USE_IRAM -#define TM_SERIAL_WAIT { while (ESP.getCycleCount()-start < wait) optimistic_yield(1); wait += m_bit_time; } // Watchdog timeouts +#define TM_SERIAL_WAIT { while (ESP.getCycleCount()-start < wait) if (!m_high_speed) optimistic_yield(1); wait += m_bit_time; } // Watchdog timeouts #else #define TM_SERIAL_WAIT { while (ESP.getCycleCount()-start < wait); wait += m_bit_time; } #endif size_t TasmotaSerial::write(uint8_t b) { - if (-1 == m_tx_pin) { - return 0; - } + if (-1 == m_tx_pin) return 0; + if (m_high_speed) cli(); // Disable interrupts in order to get a clean transmit unsigned long wait = m_bit_time; digitalWrite(m_tx_pin, HIGH); unsigned long start = ESP.getCycleCount(); @@ -173,6 +165,7 @@ size_t TasmotaSerial::write(uint8_t b) // Stop bit digitalWrite(m_tx_pin, HIGH); TM_SERIAL_WAIT; + if (m_high_speed) sei(); return 1; } @@ -191,9 +184,7 @@ void TasmotaSerial::rxRead() for (int i = 0; i < 8; i++) { TM_SERIAL_WAIT; rec >>= 1; - if (digitalRead(m_rx_pin)) { - rec |= 0x80; - } + if (digitalRead(m_rx_pin)) rec |= 0x80; } // Stop bit TM_SERIAL_WAIT; diff --git a/lib/TasmotaSerial-1.1.0/src/TasmotaSerial.h b/lib/TasmotaSerial-1.2.0/src/TasmotaSerial.h similarity index 91% rename from lib/TasmotaSerial-1.1.0/src/TasmotaSerial.h rename to lib/TasmotaSerial-1.2.0/src/TasmotaSerial.h index d18dd335f..0876590fe 100644 --- a/lib/TasmotaSerial-1.1.0/src/TasmotaSerial.h +++ b/lib/TasmotaSerial-1.2.0/src/TasmotaSerial.h @@ -20,12 +20,12 @@ #ifndef TasmotaSerial_h #define TasmotaSerial_h /*********************************************************************************************\ - * TasmotaSerial supports up to 9600 baud with fixed buffer size of 64 bytes using optional no iram + * TasmotaSerial supports up to 115200 baud with fixed buffer size of 64 bytes using optional no iram * * Based on EspSoftwareSerial v3.3.1 by Peter Lerup (https://github.com/plerup/espsoftwareserial) \*********************************************************************************************/ -#define TM_SERIAL_BAUDRATE 9600 // Max supported baudrate +#define TM_SERIAL_BAUDRATE 9600 // Default baudrate #define TM_SERIAL_BUFFER_SIZE 64 // Receive buffer size #include // Arduino_Esp8266 version information (ARDUINO_ESP8266_RELEASE and ARDUINO_ESP8266_RELEASE_2_3_0) @@ -57,6 +57,7 @@ class TasmotaSerial : public Stream { // Member variables bool m_valid; + bool m_high_speed; int m_rx_pin; int m_tx_pin; unsigned long m_bit_time; diff --git a/lib/esp-knx-ip-0.5.0/DPT.h b/lib/esp-knx-ip-0.5.0/DPT.h new file mode 100644 index 000000000..72e0c7f54 --- /dev/null +++ b/lib/esp-knx-ip-0.5.0/DPT.h @@ -0,0 +1,72 @@ +/** + * esp-knx-ip library for KNX/IP communication on an ESP8266 + * Author: Nico Weichbrodt + * License: MIT + */ + +typedef enum __dpt_1_001 +{ + DPT_1_001_OFF = 0x00, + DPT_1_001_ON = 0x01, +} dpt_1_001_t; + +typedef enum __dpt_2_001 +{ + DPT_2_001_NO_OFF = 0b00, + DPT_2_001_NO_ON = 0b01, + DPT_2_001_YES_OFF = 0b10, + DPT_2_001_YES_ON = 0b11, +} dpt_2_001_t; + +typedef enum __dpt_3_007 +{ + DPT_3_007_DECREASE_STOP = 0x00, + DPT_3_007_DECREASE_100 = 0x01, + DPT_3_007_DECREASE_50 = 0x02, + DPT_3_007_DECREASE_25 = 0x03, + DPT_3_007_DECREASE_12 = 0x04, + DPT_3_007_DECREASE_6 = 0x05, + DPT_3_007_DECREASE_3 = 0x06, + DPT_3_007_DECREASE_1 = 0x07, + DPT_3_007_INCREASE_STOP = 0x08, + DPT_3_007_INCREASE_100 = 0x09, + DPT_3_007_INCREASE_50 = 0x0A, + DPT_3_007_INCREASE_25 = 0x0B, + DPT_3_007_INCREASE_12 = 0x0C, + DPT_3_007_INCREASE_6 = 0x0D, + DPT_3_007_INCREASE_3 = 0x0E, + DPT_3_007_INCREASE_1 = 0x0F, +} dpt_3_007_t; + +typedef enum __weekday +{ + DPT_10_001_WEEKDAY_MONDAY = 1, + DPT_10_001_WEEKDAY_TUESDAY = 2, + DPT_10_001_WEEKDAY_WEDNESDAY = 3, + DPT_10_001_WEEKDAY_THURSDAY = 4, + DPT_10_001_WEEKDAY_FRIDAY = 5, + DPT_10_001_WEEKDAY_SATURDAY = 6, + DPT_10_001_WEEKDAY_SUNDAY = 8, +} weekday_t; + +typedef struct __time_of_day +{ + weekday_t weekday; + uint8_t hours; + uint8_t minutes; + uint8_t seconds; +} time_of_day_t; + +typedef struct __date +{ + uint8_t day; + uint8_t month; + uint8_t year; +} date_t; + +typedef struct __color +{ + uint8_t red; + uint8_t green; + uint8_t blue; +} color_t; \ No newline at end of file diff --git a/lib/esp-knx-ip-0.5.0/LICENSE b/lib/esp-knx-ip-0.5.0/LICENSE new file mode 100644 index 000000000..80f432a97 --- /dev/null +++ b/lib/esp-knx-ip-0.5.0/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Nico Weichbrodt + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/lib/esp-knx-ip-0.5.0/README.md b/lib/esp-knx-ip-0.5.0/README.md new file mode 100644 index 000000000..a93c09192 --- /dev/null +++ b/lib/esp-knx-ip-0.5.0/README.md @@ -0,0 +1,94 @@ +# ESP-KNX-IP # + +This is a library for the ESP8266 to enable KNXnet/IP communication. It uses UDP multicast on 224.0.23.12:3671. +It is intended to be used with the Arduino platform for the ESP8266. + +## How to use ## + +The library is under development. API may change multiple times in the future. + +API documentation is available [here](https://github.com/envy/esp-knx-ip/wiki/API) + +A simple example: + +```c++ +#include + +const char* ssid = "my-ssid"; // your network SSID (name) +const char* pass = "my-pw"; // your network password + +config_id_t my_GA; +config_id_t param_id; + +int8_t some_var = 0; + +void setup() +{ + // Register a callback that is called when a configurable group address is receiving a telegram + knx.register_callback("Set/Get callback", my_callback); + knx.register_callback("Write callback", my_other_callback); + + int default_val = 21; + param_id = knx.config_register_int("My Parameter", default_val); + + // Register a configurable group address for sending out answers + my_GA = knx.config_register_ga("Answer GA"); + + knx.load(); // Try to load a config from EEPROM + + WiFi.begin(ssid, pass); + while (WiFi.status() != WL_CONNECTED) { + delay(500); + } + + knx.start(); // Start everything. Must be called after WiFi connection has been established +} + +void loop() +{ + knx.loop(); +} + + +void my_callback(message_t const &msg, void *arg) +{ + switch (msg.ct) + { + case KNX_CT_WRITE: + // Save received data + some_var = knx.data_to_1byte_int(msg.data); + break; + case KNX_CT_READ: + // Answer with saved data + knx.answer1ByteInt(msg.received_on, some_var); + break; + } +} + +void my_other_callback(message_t const &msg, void *arg) +{ + switch (msg.ct) + { + case KNX_CT_WRITE: + // Write an answer somewhere else + int value = knx.config_get_int(param_id); + address_t ga = knx.config_get_ga(my_GA); + knx.answer1ByteInt(ga, (int8_t)value); + break; + } +} + +``` + +## How to configure (buildtime) ## + +Open the `esp-knx-ip.h` and take a look at the config options at the top inside the block marked `CONFIG` + +## How to configure (runtime) ## + +Simply visit the IP of your ESP with a webbrowser. You can configure the following: +* KNX physical address +* Which group address should trigger which callback +* Which group address are to be used by the program (e.g. for status replies) + +The configuration is dynamically generated from the code. diff --git a/lib/esp-knx-ip-0.5.0/esp-knx-ip-config.cpp b/lib/esp-knx-ip-0.5.0/esp-knx-ip-config.cpp new file mode 100644 index 000000000..8d2b7b39d --- /dev/null +++ b/lib/esp-knx-ip-0.5.0/esp-knx-ip-config.cpp @@ -0,0 +1,358 @@ +/** + * esp-knx-ip library for KNX/IP communication on an ESP8266 + * Author: Nico Weichbrodt + * License: MIT + */ + +#include "esp-knx-ip.h" + +/** + * Physical address functions + */ + +void ESPKNXIP::physical_address_set(address_t const &addr) +{ + physaddr = addr; +} + +address_t ESPKNXIP::physical_address_get() +{ + return physaddr; +} + +/** + * Configuration functions start here + */ +config_id_t ESPKNXIP::config_register_string(String name, uint8_t len, String _default, enable_condition_t cond) +{ + if (registered_configs >= MAX_CONFIGS) + return -1; + + if (_default.length() >= len) + return -1; + + config_id_t id = registered_configs; + + custom_configs[id].name = name; + custom_configs[id].type = CONFIG_TYPE_STRING; + custom_configs[id].len = sizeof(uint8_t) + len; + custom_configs[id].cond = cond; + if (id == 0) + custom_configs[id].offset = 0; + else + custom_configs[id].offset = custom_configs[id - 1].offset + custom_configs[id - 1].len; + + __config_set_string(id, _default); + + registered_configs++; + + DEBUG_PRINT("Registered config >"); + DEBUG_PRINT(name); + DEBUG_PRINT("< @ "); + DEBUG_PRINT(id); + DEBUG_PRINT("/string["); + DEBUG_PRINT(custom_configs[id].offset); + DEBUG_PRINT("+"); + DEBUG_PRINT(custom_configs[id].len); + DEBUG_PRINTLN("]"); + + return id; +} + +config_id_t ESPKNXIP::config_register_int(String name, int32_t _default, enable_condition_t cond) +{ + if (registered_configs >= MAX_CONFIGS) + return -1; + + config_id_t id = registered_configs; + + custom_configs[id].name = name; + custom_configs[id].type = CONFIG_TYPE_INT; + custom_configs[id].len = sizeof(uint8_t) + sizeof(int32_t); + custom_configs[id].cond = cond; + if (id == 0) + custom_configs[id].offset = 0; + else + custom_configs[id].offset = custom_configs[id - 1].offset + custom_configs[id - 1].len; + + __config_set_int(id, _default); + + registered_configs++; + + DEBUG_PRINT("Registered config >"); + DEBUG_PRINT(name); + DEBUG_PRINT("< @ "); + DEBUG_PRINT(id); + DEBUG_PRINT("/int["); + DEBUG_PRINT(custom_configs[id].offset); + DEBUG_PRINT("+"); + DEBUG_PRINT(custom_configs[id].len); + DEBUG_PRINTLN("]"); + + return id; +} + +config_id_t ESPKNXIP::config_register_bool(String name, bool _default, enable_condition_t cond) +{ + if (registered_configs >= MAX_CONFIGS) + return -1; + + config_id_t id = registered_configs; + + custom_configs[id].name = name; + custom_configs[id].type = CONFIG_TYPE_BOOL; + custom_configs[id].len = sizeof(uint8_t) + sizeof(uint8_t); + custom_configs[id].cond = cond; + if (id == 0) + custom_configs[id].offset = 0; + else + custom_configs[id].offset = custom_configs[id - 1].offset + custom_configs[id - 1].len; + + __config_set_bool(id, _default); + + registered_configs++; + + DEBUG_PRINT("Registered config >"); + DEBUG_PRINT(name); + DEBUG_PRINT("< @ "); + DEBUG_PRINT(id); + DEBUG_PRINT("/bool["); + DEBUG_PRINT(custom_configs[id].offset); + DEBUG_PRINT("+"); + DEBUG_PRINT(custom_configs[id].len); + DEBUG_PRINTLN("]"); + + return id; +} + +config_id_t ESPKNXIP::config_register_options(String name, option_entry_t *options, uint8_t _default, enable_condition_t cond) +{ + if (registered_configs >= MAX_CONFIGS) + return -1; + + if (options == nullptr || options->name == nullptr) + return -1; + + config_id_t id = registered_configs; + + custom_configs[id].name = name; + custom_configs[id].type = CONFIG_TYPE_OPTIONS; + custom_configs[id].len = sizeof(uint8_t) + sizeof(uint8_t); + custom_configs[id].cond = cond; + if (id == 0) + custom_configs[id].offset = 0; + else + custom_configs[id].offset = custom_configs[id - 1].offset + custom_configs[id - 1].len; + + custom_configs[id].data.options = options; + + __config_set_options(id, _default); + + registered_configs++; + + DEBUG_PRINT("Registered config >"); + DEBUG_PRINT(name); + DEBUG_PRINT("< @ "); + DEBUG_PRINT(id); + DEBUG_PRINT("/opt["); + DEBUG_PRINT(custom_configs[id].offset); + DEBUG_PRINT("+"); + DEBUG_PRINT(custom_configs[id].len); + DEBUG_PRINTLN("]"); + + return id; +} + +config_id_t ESPKNXIP::config_register_ga(String name, enable_condition_t cond) +{ + if (registered_configs >= MAX_CONFIGS) + return -1; + + config_id_t id = registered_configs; + + custom_configs[id].name = name; + custom_configs[id].type = CONFIG_TYPE_GA; + custom_configs[id].len = sizeof(uint8_t) + sizeof(address_t); + custom_configs[id].cond = cond; + if (id == 0) + custom_configs[id].offset = 0; + else + custom_configs[id].offset = custom_configs[id - 1].offset + custom_configs[id - 1].len; + + address_t t; + t.value = 0; + __config_set_ga(id, t); + + registered_configs++; + + DEBUG_PRINT("Registered config >"); + DEBUG_PRINT(name); + DEBUG_PRINT("< @ "); + DEBUG_PRINT(id); + DEBUG_PRINT("/ga["); + DEBUG_PRINT(custom_configs[id].offset); + DEBUG_PRINT("+"); + DEBUG_PRINT(custom_configs[id].len); + DEBUG_PRINTLN("]"); + + return id; +} + +void ESPKNXIP::__config_set_flags(config_id_t id, config_flags_t flags) +{ + DEBUG_PRINT("Setting flag @ "); + DEBUG_PRINT(custom_configs[id].offset); + DEBUG_PRINT(" to "); + DEBUG_PRINT(custom_config_data[custom_configs[id].offset], BIN); + DEBUG_PRINT(" | "); + DEBUG_PRINT(flags, BIN); + custom_config_data[custom_configs[id].offset] |= (uint8_t)flags; + DEBUG_PRINT(" = "); + DEBUG_PRINTLN(custom_config_data[custom_configs[id].offset], BIN); +} + +void ESPKNXIP::config_set_string(config_id_t id, String val) +{ + if (id >= registered_configs) + return; + if (custom_configs[id].type != CONFIG_TYPE_STRING) + return; + if (val.length() >= custom_configs[id].len) + return; + __config_set_flags(id, CONFIG_FLAGS_VALUE_SET); + __config_set_string(id, val); +} + +void ESPKNXIP::__config_set_string(config_id_t id, String &val) +{ + memcpy(&custom_config_data[custom_configs[id].offset + sizeof(uint8_t)], val.c_str(), val.length()+1); +} + +void ESPKNXIP::config_set_int(config_id_t id, int32_t val) +{ + if (id >= registered_configs) + return; + if (custom_configs[id].type != CONFIG_TYPE_INT) + return; + __config_set_flags(id, CONFIG_FLAGS_VALUE_SET); + __config_set_int(id, val); +} + +void ESPKNXIP::__config_set_int(config_id_t id, int32_t val) +{ + // This does not work for some reason: + // Could be due to pointer alignment + //int32_t *v = (int32_t *)(custom_config_data + custom_configs[id].offset); + //*v = val; + custom_config_data[custom_configs[id].offset + sizeof(uint8_t) + 0] = (uint8_t)((val & 0xFF000000) >> 24); + custom_config_data[custom_configs[id].offset + sizeof(uint8_t) + 1] = (uint8_t)((val & 0x00FF0000) >> 16); + custom_config_data[custom_configs[id].offset + sizeof(uint8_t) + 2] = (uint8_t)((val & 0x0000FF00) >> 8); + custom_config_data[custom_configs[id].offset + sizeof(uint8_t) + 3] = (uint8_t)((val & 0x000000FF) >> 0); +} + +void ESPKNXIP::config_set_bool(config_id_t id, bool val) +{ + if (id >= registered_configs) + return; + if (custom_configs[id].type != CONFIG_TYPE_BOOL) + return; + __config_set_flags(id, CONFIG_FLAGS_VALUE_SET); + __config_set_bool(id, val); +} + +void ESPKNXIP::__config_set_bool(config_id_t id, bool val) +{ + custom_config_data[custom_configs[id].offset + sizeof(uint8_t)] = val ? 1 : 0; +} + +void ESPKNXIP::config_set_options(config_id_t id, uint8_t val) +{ + if (id >= registered_configs) + return; + if (custom_configs[id].type != CONFIG_TYPE_OPTIONS) + return; + + option_entry_t *cur = custom_configs[id].data.options; + while (cur->name != nullptr) + { + if (cur->value == val) + { + __config_set_flags(id, CONFIG_FLAGS_VALUE_SET); + __config_set_options(id, val); + break; + } + cur++; + } +} + +void ESPKNXIP::__config_set_options(config_id_t id, uint8_t val) +{ + custom_config_data[custom_configs[id].offset + sizeof(uint8_t)] = val; +} + +void ESPKNXIP::config_set_ga(config_id_t id, address_t const &val) +{ + if (id >= registered_configs) + return; + if (custom_configs[id].type != CONFIG_TYPE_GA) + return; + __config_set_flags(id, CONFIG_FLAGS_VALUE_SET); + __config_set_ga(id, val); +} + +void ESPKNXIP::__config_set_ga(config_id_t id, address_t const &val) +{ + custom_config_data[custom_configs[id].offset + sizeof(uint8_t) + 0] = val.bytes.high; + custom_config_data[custom_configs[id].offset + sizeof(uint8_t) + 1] = val.bytes.low; +} + +String ESPKNXIP::config_get_string(config_id_t id) +{ + if (id >= registered_configs) + return String(""); + + return String((char *)&custom_config_data[custom_configs[id].offset + sizeof(uint8_t)]); +} + +int32_t ESPKNXIP::config_get_int(config_id_t id) +{ + if (id >= registered_configs) + return 0; + + int32_t v = (custom_config_data[custom_configs[id].offset + sizeof(uint8_t) + 0] << 24) + + (custom_config_data[custom_configs[id].offset + sizeof(uint8_t) + 1] << 16) + + (custom_config_data[custom_configs[id].offset + sizeof(uint8_t) + 2] << 8) + + (custom_config_data[custom_configs[id].offset + sizeof(uint8_t) + 3] << 0); + return v; +} + +bool ESPKNXIP::config_get_bool(config_id_t id) +{ + if (id >= registered_configs) + return false; + + return custom_config_data[custom_configs[id].offset + sizeof(uint8_t)] != 0; +} + +uint8_t ESPKNXIP::config_get_options(config_id_t id) +{ + if (id >= registered_configs) + return false; + + return custom_config_data[custom_configs[id].offset + sizeof(uint8_t)]; +} + +address_t ESPKNXIP::config_get_ga(config_id_t id) +{ + address_t t; + if (id >= registered_configs) + { + t.value = 0; + return t; + } + + t.bytes.high = custom_config_data[custom_configs[id].offset + sizeof(uint8_t) + 0]; + t.bytes.low = custom_config_data[custom_configs[id].offset + sizeof(uint8_t) + 1]; + + return t; +} diff --git a/lib/esp-knx-ip-0.5.0/esp-knx-ip-conversion.cpp b/lib/esp-knx-ip-0.5.0/esp-knx-ip-conversion.cpp new file mode 100644 index 000000000..9dc2fd563 --- /dev/null +++ b/lib/esp-knx-ip-0.5.0/esp-knx-ip-conversion.cpp @@ -0,0 +1,87 @@ +/** + * esp-knx-ip library for KNX/IP communication on an ESP8266 + * Author: Nico Weichbrodt + * License: MIT + */ + +#include "esp-knx-ip.h" + +/** + * Conversion functions + */ + +bool ESPKNXIP::data_to_bool(uint8_t *data) +{ + return (data[0] & 0x01) == 1 ? true : false; +} + +int8_t ESPKNXIP::data_to_1byte_int(uint8_t *data) +{ + return (int8_t)data[1]; +} + +uint8_t ESPKNXIP::data_to_1byte_uint(uint8_t *data) +{ + return data[1]; +} + +int16_t ESPKNXIP::data_to_2byte_int(uint8_t *data) +{ + return (int16_t)((data[1] << 8) | data[2]); +} + +uint16_t ESPKNXIP::data_to_2byte_uint(uint8_t *data) +{ + return (uint16_t)((data[1] << 8) | data[2]); +} + +float ESPKNXIP::data_to_2byte_float(uint8_t *data) +{ + //uint8_t sign = (data[1] & 0b10000000) >> 7; + uint8_t expo = (data[1] & 0b01111000) >> 3; + int16_t mant = ((data[1] & 0b10000111) << 8) | data[2]; + return 0.01f * mant * pow(2, expo); +} + +time_of_day_t ESPKNXIP::data_to_3byte_time(uint8_t *data) +{ + time_of_day_t time; + time.weekday = (weekday_t)((data[1] & 0b11100000) >> 5); + time.hours = (data[1] & 0b00011111); + time.minutes = (data[2] & 0b00111111); + time.seconds = (data[3] & 0b00111111); + return time; +} + +date_t ESPKNXIP::data_to_3byte_data(uint8_t *data) +{ + date_t date; + date.day = (data[1] & 0b00011111); + date.month = (data[2] & 0b00001111); + date.year = (data[3] & 0b01111111); + return date; +} + +color_t ESPKNXIP::data_to_3byte_color(uint8_t *data) +{ + color_t color; + color.red = data[1]; + color.green = data[2]; + color.blue = data[3]; + return color; +} + +int32_t ESPKNXIP::data_to_4byte_int(uint8_t *data) +{ + return (int32_t)((data[1] << 24) | (data[2] << 16) | (data[3] << 8) | (data[4] << 0)); +} + +uint32_t ESPKNXIP::data_to_4byte_uint(uint8_t *data) +{ + return (uint32_t)((data[1] << 24) | (data[2] << 16) | (data[3] << 8) | (data[4] << 0)); +} + +float ESPKNXIP::data_to_4byte_float(uint8_t *data) +{ + return (float)((data[1] << 24) | (data[2] << 16) | (data[3] << 8) |data[4]); +} \ No newline at end of file diff --git a/lib/esp-knx-ip-0.5.0/esp-knx-ip-send.cpp b/lib/esp-knx-ip-0.5.0/esp-knx-ip-send.cpp new file mode 100644 index 000000000..72459f922 --- /dev/null +++ b/lib/esp-knx-ip-0.5.0/esp-knx-ip-send.cpp @@ -0,0 +1,182 @@ +/** + * esp-knx-ip library for KNX/IP communication on an ESP8266 + * Author: Nico Weichbrodt + * License: MIT + */ + +#include "esp-knx-ip.h" + +/** + * Send functions + */ + +void ESPKNXIP::send(address_t const &receiver, knx_command_type_t ct, uint8_t data_len, uint8_t *data) +{ + if (receiver.value == 0) + return; + +#if SEND_CHECKSUM + uint32_t len = 6 + 2 + 8 + data_len + 1; // knx_pkt + cemi_msg + cemi_service + data + checksum +#else + uint32_t len = 6 + 2 + 8 + data_len; // knx_pkt + cemi_msg + cemi_service + data +#endif + DEBUG_PRINT(F("Creating packet with len ")); + DEBUG_PRINTLN(len) + uint8_t buf[len]; + knx_ip_pkt_t *knx_pkt = (knx_ip_pkt_t *)buf; + knx_pkt->header_len = 0x06; + knx_pkt->protocol_version = 0x10; + knx_pkt->service_type = __ntohs(KNX_ST_ROUTING_INDICATION); + knx_pkt->total_len.len = __ntohs(len); + cemi_msg_t *cemi_msg = (cemi_msg_t *)knx_pkt->pkt_data; + cemi_msg->message_code = KNX_MT_L_DATA_IND; + cemi_msg->additional_info_len = 0; + cemi_service_t *cemi_data = &cemi_msg->data.service_information; + cemi_data->control_1.bits.confirm = 0; + cemi_data->control_1.bits.ack = 0; + cemi_data->control_1.bits.priority = B11; + cemi_data->control_1.bits.system_broadcast = 0x01; + cemi_data->control_1.bits.repeat = 0x01; + cemi_data->control_1.bits.reserved = 0; + cemi_data->control_1.bits.frame_type = 0x01; + cemi_data->control_2.bits.extended_frame_format = 0x00; + cemi_data->control_2.bits.hop_count = 0x06; + cemi_data->control_2.bits.dest_addr_type = 0x01; + cemi_data->source = physaddr; + cemi_data->destination = receiver; + //cemi_data->destination.bytes.high = (area << 3) | line; + //cemi_data->destination.bytes.low = member; + cemi_data->data_len = data_len; + cemi_data->pci.apci = (ct & 0x0C) >> 2; + cemi_data->pci.tpci_seq_number = 0x00; // ??? + cemi_data->pci.tpci_comm_type = KNX_COT_UDP; // ??? + memcpy(cemi_data->data, data, data_len); + cemi_data->data[0] = (cemi_data->data[0] & 0x3F) | ((ct & 0x03) << 6); + +#if SEND_CHECKSUM + // Calculate checksum, which is just XOR of all bytes + uint8_t cs = buf[0] ^ buf[1]; + for (uint32_t i = 2; i < len - 1; ++i) + { + cs ^= buf[i]; + } + buf[len - 1] = cs; +#endif + +#ifdef ESP_KNX_DEBUG + DEBUG_PRINT(F("Sending packet:")); + for (int i = 0; i < len; ++i) + { + DEBUG_PRINT(F(" 0x")); + DEBUG_PRINT(buf[i], 16); + } + DEBUG_PRINTLN(F("")); +#endif + + udp.beginPacketMulticast(MULTICAST_IP, MULTICAST_PORT, WiFi.localIP()); + udp.write(buf, len); + udp.endPacket(); +} + +void ESPKNXIP::send_1bit(address_t const &receiver, knx_command_type_t ct, uint8_t bit) +{ + uint8_t buf[] = {(uint8_t)(bit & 0b00000001)}; + send(receiver, ct, 1, buf); +} + +void ESPKNXIP::send_2bit(address_t const &receiver, knx_command_type_t ct, uint8_t twobit) +{ + uint8_t buf[] = {(uint8_t)(twobit & 0b00000011)}; + send(receiver, ct, 1, buf); +} + +void ESPKNXIP::send_4bit(address_t const &receiver, knx_command_type_t ct, uint8_t fourbit) +{ + uint8_t buf[] = {(uint8_t)(fourbit & 0b00001111)}; + send(receiver, ct, 1, buf); +} + +void ESPKNXIP::send_1byte_int(address_t const &receiver, knx_command_type_t ct, int8_t val) +{ + uint8_t buf[] = {0x00, (uint8_t)val}; + send(receiver, ct, 2, buf); +} + +void ESPKNXIP::send_1byte_uint(address_t const &receiver, knx_command_type_t ct, uint8_t val) +{ + uint8_t buf[] = {0x00, val}; + send(receiver, ct, 2, buf); +} + +void ESPKNXIP::send_2byte_int(address_t const &receiver, knx_command_type_t ct, int16_t val) +{ + uint8_t buf[] = {0x00, (uint8_t)(val >> 8), (uint8_t)(val & 0x00FF)}; + send(receiver, ct, 3, buf); +} + +void ESPKNXIP::send_2byte_uint(address_t const &receiver, knx_command_type_t ct, uint16_t val) +{ + uint8_t buf[] = {0x00, (uint8_t)(val >> 8), (uint8_t)(val & 0x00FF)}; + send(receiver, ct, 3, buf); +} + +void ESPKNXIP::send_2byte_float(address_t const &receiver, knx_command_type_t ct, float val) +{ + float v = val * 100.0f; + int e = 0; + for (; v < -2048.0f; v /= 2) + ++e; + for (; v > 2047.0f; v /= 2) + ++e; + long m = round(v) & 0x7FF; + short msb = (short) (e << 3 | m >> 8); + if (val < 0.0f) + msb |= 0x80; + uint8_t buf[] = {0x00, (uint8_t)msb, (uint8_t)m}; + send(receiver, ct, 3, buf); +} + +void ESPKNXIP::send_3byte_time(address_t const &receiver, knx_command_type_t ct, uint8_t weekday, uint8_t hours, uint8_t minutes, uint8_t seconds) +{ + weekday <<= 5; + uint8_t buf[] = {0x00, (uint8_t)(((weekday << 5) & 0xE0) | (hours & 0x1F)), (uint8_t)(minutes & 0x3F), (uint8_t)(seconds & 0x3F)}; + send(receiver, ct, 4, buf); +} + +void ESPKNXIP::send_3byte_date(address_t const &receiver, knx_command_type_t ct, uint8_t day, uint8_t month, uint8_t year) +{ + uint8_t buf[] = {0x00, (uint8_t)(day & 0x1F), (uint8_t)(month & 0x0F), year}; + send(receiver, ct, 4, buf); +} + +void ESPKNXIP::send_3byte_color(address_t const &receiver, knx_command_type_t ct, uint8_t red, uint8_t green, uint8_t blue) +{ + uint8_t buf[] = {0x00, red, green, blue}; + send(receiver, ct, 4, buf); +} + +void ESPKNXIP::send_4byte_int(address_t const &receiver, knx_command_type_t ct, int32_t val) +{ + uint8_t buf[] = {0x00, + (uint8_t)((val & 0xFF000000) >> 24), + (uint8_t)((val & 0x00FF0000) >> 16), + (uint8_t)((val & 0x0000FF00) >> 8), + (uint8_t)((val & 0x000000FF) >> 0)}; + send(receiver, ct, 5, buf); +} + +void ESPKNXIP::send_4byte_uint(address_t const &receiver, knx_command_type_t ct, uint32_t val) +{ + uint8_t buf[] = {0x00, + (uint8_t)((val & 0xFF000000) >> 24), + (uint8_t)((val & 0x00FF0000) >> 16), + (uint8_t)((val & 0x0000FF00) >> 8), + (uint8_t)((val & 0x000000FF) >> 0)}; + send(receiver, ct, 5, buf); +} + +void ESPKNXIP::send_4byte_float(address_t const &receiver, knx_command_type_t ct, float val) +{ + uint8_t buf[] = {0x00, ((uint8_t *)&val)[3], ((uint8_t *)&val)[2], ((uint8_t *)&val)[1], ((uint8_t *)&val)[0]}; + send(receiver, ct, 5, buf); +} diff --git a/lib/esp-knx-ip-0.5.0/esp-knx-ip-webserver.cpp b/lib/esp-knx-ip-0.5.0/esp-knx-ip-webserver.cpp new file mode 100644 index 000000000..bdbc013fd --- /dev/null +++ b/lib/esp-knx-ip-0.5.0/esp-knx-ip-webserver.cpp @@ -0,0 +1,540 @@ +/** + * esp-knx-ip library for KNX/IP communication on an ESP8266 + * Author: Nico Weichbrodt + * License: MIT + */ + +#include "esp-knx-ip.h" + +void ESPKNXIP::__handle_root() +{ + String m = F(""); +#if USE_BOOTSTRAP + m += F(""); + m += F(""); +#endif + m += F("
"); + m += F("

ESP KNX

"); + + // Feedback + + if (registered_feedbacks > 0) + { + m += F("

Feedback

"); + for (feedback_id_t i = 0; i < registered_feedbacks; ++i) + { + if (feedbacks[i].cond && !feedbacks[i].cond()) + { + continue; + } + m += F("
"); + m += F("
"); + m += F("
"); + m += feedbacks[i].name; + m += F("
"); + switch (feedbacks[i].type) + { + case FEEDBACK_TYPE_INT: + m += F(""); + m += String(*(int32_t *)feedbacks[i].data); + m += F(""); + break; + case FEEDBACK_TYPE_FLOAT: + m += F(""); + m += feedbacks[i].options.float_options.prefix; + m += String(*(float *)feedbacks[i].data, feedbacks[i].options.float_options.precision); + m += feedbacks[i].options.float_options.suffix; + m += F(""); + break; + case FEEDBACK_TYPE_BOOL: + m += F(""); + m += (*(bool *)feedbacks[i].data) ? F("True") : F("False"); + m += F(""); + break; + case FEEDBACK_TYPE_ACTION: + m += F("
"); + break; + } + m += F("
"); + m += F("
"); + } + } + + if (registered_callbacks > 0) + m += F("

Callbacks

"); + + if (registered_callback_assignments > 0) + { + for (uint8_t i = 0; i < registered_callback_assignments; ++i) + { + // Skip empty slots + if ((callback_assignments[i].slot_flags & SLOT_FLAGS_USED) == 0) + { + continue; + } + // Skip disabled callbacks + if (callbacks[callback_assignments[i].callback_id].cond && !callbacks[callback_assignments[i].callback_id].cond()) + { + continue; + } + address_t &addr = callback_assignments[i].address; + m += F("
"); + m += F("
"); + m += F("
"); + m += addr.ga.area; + m += F("/"); + m += addr.ga.line; + m += F("/"); + m += addr.ga.member; + m += F(""); + m += F(""); + m += callbacks[callback_assignments[i].callback_id].name; + m += F("
"); + m += F("
"); + m += F("
"); + m += F("
"); + } + } + + if (registered_callbacks > 0) + { + m += F("
"); + m += F("
"); + m += F(""); + m += F("
/
"); + m += F(""); + m += F("
/
"); + m += F(""); + m += F("
->
"); + m += F(""); + m += F("
"); + m += F("
"); + m += F("
"); + } + + m += F("

Configuration

"); + + // Physical address + m += F("
"); + m += F("
"); + m += F("
Physical address
"); + m += F(""); + m += F("
.
"); + m += F(""); + m += F("
.
"); + m += F(""); + m += F("
"); + m += F("
"); + m += F("
"); + + if (registered_configs > 0) + { + for (config_id_t i = 0; i < registered_configs; ++i) + { + // Check if this config option has a enable condition and if so check that condition + if (custom_configs[i].cond && !custom_configs[i].cond()) + continue; + + m += F("
"); + m += F("
"); + m += F("
"); + m += custom_configs[i].name; + m += F("
"); + + switch (custom_configs[i].type) + { + case CONFIG_TYPE_STRING: + m += F(""); + break; + case CONFIG_TYPE_INT: + m += F(""); + break; + case CONFIG_TYPE_BOOL: + m += F("
"); + m += F(""); + m += F("
"); + break; + case CONFIG_TYPE_OPTIONS: + { + m += F(""); + break; + } + case CONFIG_TYPE_GA: + address_t a = config_get_ga(i); + m += F(""); + m += F("
/
"); + m += F(""); + m += F("
/
"); + m += F(""); + break; + } + m += F(""); + m += F("
"); + m += F("
"); + m += F("
"); + } + } + +#if !(DISABLE_EEPROM_BUTTONS && DISABLE_RESTORE_BUTTON && DISABLE_REBOOT_BUTTON) + // EEPROM save and restore + m += F("
"); + // Save to EEPROM +#if !DISABLE_EEPROM_BUTTONS + m += F("
"); + m += F("
"); + m += F(""); + m += F(""); + m += F("
"); + m += F("
"); + // Restore from EEPROM + m += F("
"); + m += F("
"); + m += F(""); + m += F(""); + m += F("
"); + m += F("
"); +#endif +#if !DISABLE_RESTORE_BUTTON + // Load Defaults + m += F("
"); + m += F("
"); + m += F(""); + m += F("
"); + m += F("
"); +#endif +#if !DISABLE_REBOOT_BUTTON + // Reboot + m += F("
"); + m += F("
"); + m += F(""); + m += F("
"); + m += F("
"); +#endif + m += F("
"); // row +#endif + + // End of page + m += F("
"); + server->send(200, F("text/html"), m); +} + +void ESPKNXIP::__handle_register() +{ + DEBUG_PRINTLN(F("Register called")); + if (server->hasArg(F("area")) && server->hasArg(F("line")) && server->hasArg(F("member")) && server->hasArg(F("cb"))) + { + uint8_t area = server->arg(F("area")).toInt(); + uint8_t line = server->arg(F("line")).toInt(); + uint8_t member = server->arg(F("member")).toInt(); + callback_id_t cb = (callback_id_t)server->arg(F("cb")).toInt(); + + DEBUG_PRINT(F("Got args: ")); + DEBUG_PRINT(area); + DEBUG_PRINT(F("/")); + DEBUG_PRINT(line); + DEBUG_PRINT(F("/")); + DEBUG_PRINT(member); + DEBUG_PRINT(F("/")); + DEBUG_PRINT(cb); + DEBUG_PRINTLN(F("")); + + if (area > 31 || line > 7) + { + DEBUG_PRINTLN(F("Area or Line wrong")); + goto end; + } + + if (!__callback_is_id_valid(cb)) + { + DEBUG_PRINTLN(F("Invalid callback id")); + goto end; + } + address_t ga = {.ga={line, area, member}}; + __callback_register_assignment(ga, cb); + } +end: + server->sendHeader(F("Location"),F(__ROOT_PATH)); + server->send(302); +} + +void ESPKNXIP::__handle_delete() +{ + DEBUG_PRINTLN(F("Delete called")); + if (server->hasArg(F("id"))) + { + callback_assignment_id_t id = (callback_assignment_id_t)server->arg(F("id")).toInt(); + + DEBUG_PRINT(F("Got args: ")); + DEBUG_PRINT(id); + DEBUG_PRINTLN(F("")); + + if (id >= registered_callback_assignments || (callback_assignments[id].slot_flags & SLOT_FLAGS_USED) == 0) + { + DEBUG_PRINTLN(F("ID wrong")); + goto end; + } + + __callback_delete_assignment(id); + } +end: + server->sendHeader(F("Location"),F(__ROOT_PATH)); + server->send(302); +} + +void ESPKNXIP::__handle_set() +{ + DEBUG_PRINTLN(F("Set called")); + if (server->hasArg(F("area")) && server->hasArg(F("line")) && server->hasArg(F("member"))) + { + uint8_t area = server->arg(F("area")).toInt(); + uint8_t line = server->arg(F("line")).toInt(); + uint8_t member = server->arg(F("member")).toInt(); + + DEBUG_PRINT(F("Got args: ")); + DEBUG_PRINT(area); + DEBUG_PRINT(F(".")); + DEBUG_PRINT(line); + DEBUG_PRINT(F(".")); + DEBUG_PRINT(member); + DEBUG_PRINTLN(F("")); + + if (area > 31 || line > 7) + { + DEBUG_PRINTLN(F("Area or Line wrong")); + goto end; + } + + physaddr.bytes.high = (area << 4) | line; + physaddr.bytes.low = member; + } +end: + server->sendHeader(F("Location"),F(__ROOT_PATH)); + server->send(302); +} + +void ESPKNXIP::__handle_config() +{ + DEBUG_PRINTLN(F("Config called")); + if (server->hasArg(F("id"))) + { + config_id_t id = server->arg(F("id")).toInt(); + + DEBUG_PRINT(F("Got args: ")); + DEBUG_PRINT(id); + DEBUG_PRINTLN(F("")); + + if (id < 0 || id >= registered_configs) + { + DEBUG_PRINTLN(F("ID wrong")); + goto end; + } + + switch (custom_configs[id].type) + { + case CONFIG_TYPE_STRING: + { + String v = server->arg(F("value")); + if (v.length() >= custom_configs[id].len) + goto end; + __config_set_flags(id, CONFIG_FLAGS_VALUE_SET); + __config_set_string(id, v); + break; + } + case CONFIG_TYPE_INT: + { + __config_set_flags(id, CONFIG_FLAGS_VALUE_SET); + __config_set_int(id, server->arg(F("value")).toInt()); + break; + } + case CONFIG_TYPE_BOOL: + { + __config_set_flags(id, CONFIG_FLAGS_VALUE_SET); + __config_set_bool(id, server->arg(F("value")).compareTo(F("on")) == 0); + break; + } + case CONFIG_TYPE_OPTIONS: + { + uint8_t val = (uint8_t)server->arg(F("value")).toInt(); + DEBUG_PRINT(F("Value: ")); + DEBUG_PRINTLN(val); + config_set_options(id, val); + break; + } + case CONFIG_TYPE_GA: + { + uint8_t area = server->arg(F("area")).toInt(); + uint8_t line = server->arg(F("line")).toInt(); + uint8_t member = server->arg(F("member")).toInt(); + if (area > 31 || line > 7) + { + DEBUG_PRINTLN(F("Area or Line wrong")); + goto end; + } + address_t tmp; + tmp.bytes.high = (area << 3) | line; + tmp.bytes.low = member; + __config_set_flags(id, CONFIG_FLAGS_VALUE_SET); + __config_set_ga(id, tmp); + break; + } + } + } +end: + server->sendHeader(F("Location"),F(__ROOT_PATH)); + server->send(302); +} + +void ESPKNXIP::__handle_feedback() +{ +DEBUG_PRINTLN(F("Feedback called")); + if (server->hasArg(F("id"))) + { + config_id_t id = server->arg(F("id")).toInt(); + + DEBUG_PRINT(F("Got args: ")); + DEBUG_PRINT(id); + DEBUG_PRINTLN(F("")); + + if (id < 0 || id >= registered_feedbacks) + { + DEBUG_PRINTLN(F("ID wrong")); + goto end; + } + + switch (feedbacks[id].type) + { + case FEEDBACK_TYPE_ACTION: + { + feedback_action_fptr_t func = (feedback_action_fptr_t)feedbacks[id].data; + void *arg = feedbacks[id].options.action_options.arg; + func(arg); + break; + } + default: + DEBUG_PRINTLN(F("Feedback has no action")); + break; + } + } +end: + server->sendHeader(F("Location"),F(__ROOT_PATH)); + server->send(302); +} + +#if !DISABLE_RESTORE_BUTTONS +void ESPKNXIP::__handle_restore() +{ + DEBUG_PRINTLN(F("Restore called")); + memcpy(custom_config_data, custom_config_default_data, MAX_CONFIG_SPACE); +end: + server->sendHeader(F("Location"),F(__ROOT_PATH)); + server->send(302); +} +#endif + +#if !DISABLE_REBOOT_BUTTONS +void ESPKNXIP::__handle_reboot() +{ + DEBUG_PRINTLN(F("Rebooting!")); + server->sendHeader(F("Location"),F(__ROOT_PATH)); + server->send(302); + delay(1000); + ESP.restart(); + //while(1); +} +#endif + +#if !DISABLE_EEPROM_BUTTONS +void ESPKNXIP::__handle_eeprom() +{ + DEBUG_PRINTLN(F("EEPROM called")); + if (server->hasArg(F("mode"))) + { + uint8_t mode = server->arg(F("mode")).toInt(); + + DEBUG_PRINT(F("Got args: ")); + DEBUG_PRINT(mode); + DEBUG_PRINTLN(F("")); + + if (mode == 1) + { + // save + save_to_eeprom(); + } + else if (mode == 2) + { + // restore + restore_from_eeprom(); + } + } +end: + server->sendHeader(F("Location"),F(__ROOT_PATH)); + server->send(302); +} +#endif diff --git a/lib/esp-knx-ip-0.5.0/esp-knx-ip.cpp b/lib/esp-knx-ip-0.5.0/esp-knx-ip.cpp new file mode 100644 index 000000000..b572333b9 --- /dev/null +++ b/lib/esp-knx-ip-0.5.0/esp-knx-ip.cpp @@ -0,0 +1,659 @@ +/** + * esp-knx-ip library for KNX/IP communication on an ESP8266 + * Author: Nico Weichbrodt + * License: MIT + */ + +#include "esp-knx-ip.h" + +char const *string_defaults[] = +{ + "Do this", + "True", + "False", + "" +}; + +ESPKNXIP::ESPKNXIP() : server(nullptr), + registered_callback_assignments(0), + free_callback_assignment_slots(0), + registered_callbacks(0), + free_callback_slots(0), + registered_configs(0), + registered_feedbacks(0) +{ + DEBUG_PRINTLN(); + DEBUG_PRINTLN("ESPKNXIP starting up"); + // Default physical address is 1.1.0 + physaddr.bytes.high = (/*area*/1 << 4) | /*line*/1; + physaddr.bytes.low = /*member*/0; + memset(callback_assignments, 0, MAX_CALLBACK_ASSIGNMENTS * sizeof(callback_assignment_t)); + memset(callbacks, 0, MAX_CALLBACKS * sizeof(callback_fptr_t)); + memset(custom_config_data, 0, MAX_CONFIG_SPACE * sizeof(uint8_t)); + memset(custom_config_default_data, 0, MAX_CONFIG_SPACE * sizeof(uint8_t)); + memset(custom_configs, 0, MAX_CONFIGS * sizeof(config_t)); +} + +void ESPKNXIP::load() +{ + memcpy(custom_config_default_data, custom_config_data, MAX_CONFIG_SPACE); + EEPROM.begin(EEPROM_SIZE); + restore_from_eeprom(); +} + +void ESPKNXIP::start(ESP8266WebServer *srv) +{ + server = srv; + __start(); +} + +void ESPKNXIP::start() +{ + server = new ESP8266WebServer(80); + __start(); +} + +void ESPKNXIP::__start() +{ + if (server != nullptr) + { + server->on(ROOT_PREFIX, [this](){ + __handle_root(); + }); + server->on(__ROOT_PATH, [this](){ + __handle_root(); + }); + server->on(__REGISTER_PATH, [this](){ + __handle_register(); + }); + server->on(__DELETE_PATH, [this](){ + __handle_delete(); + }); + server->on(__PHYS_PATH, [this](){ + __handle_set(); + }); +#if !DISABLE_EEPROM_BUTTONS + server->on(__EEPROM_PATH, [this](){ + __handle_eeprom(); + }); +#endif + server->on(__CONFIG_PATH, [this](){ + __handle_config(); + }); + server->on(__FEEDBACK_PATH, [this](){ + __handle_feedback(); + }); +#if !DISABLE_RESTORE_BUTTON + server->on(__RESTORE_PATH, [this](){ + __handle_restore(); + }); +#endif +#if !DISABLE_REBOOT_BUTTON + server->on(__REBOOT_PATH, [this](){ + __handle_reboot(); + }); +#endif + server->begin(); + } + + udp.beginMulticast(WiFi.localIP(), MULTICAST_IP, MULTICAST_PORT); +} + +void ESPKNXIP::save_to_eeprom() +{ + uint32_t address = 0; + uint64_t magic = EEPROM_MAGIC; + EEPROM.put(address, magic); + address += sizeof(uint64_t); + EEPROM.put(address++, registered_callback_assignments); + for (uint8_t i = 0; i < MAX_CALLBACK_ASSIGNMENTS; ++i) + { + EEPROM.put(address, callback_assignments[i].address); + address += sizeof(address_t); + } + for (uint8_t i = 0; i < MAX_CALLBACK_ASSIGNMENTS; ++i) + { + EEPROM.put(address, callback_assignments[i].callback_id); + address += sizeof(callback_id_t); + } + EEPROM.put(address, physaddr); + address += sizeof(address_t); + + EEPROM.put(address, custom_config_data); + address += sizeof(custom_config_data); + + EEPROM.commit(); + DEBUG_PRINT("Wrote to EEPROM: 0x"); + DEBUG_PRINTLN(address, HEX); +} + +void ESPKNXIP::restore_from_eeprom() +{ + uint32_t address = 0; + uint64_t magic = 0; + EEPROM.get(address, magic); + if (magic != EEPROM_MAGIC) + { + DEBUG_PRINTLN("No valid magic in EEPROM, aborting restore."); + DEBUG_PRINT("Expected 0x"); + DEBUG_PRINT((unsigned long)(EEPROM_MAGIC >> 32), HEX); + DEBUG_PRINT(" 0x"); + DEBUG_PRINT((unsigned long)(EEPROM_MAGIC), HEX); + DEBUG_PRINT(" got 0x"); + DEBUG_PRINT((unsigned long)(magic >> 32), HEX); + DEBUG_PRINT(" 0x"); + DEBUG_PRINTLN((unsigned long)magic, HEX); + return; + } + address += sizeof(uint64_t); + EEPROM.get(address++, registered_callback_assignments); + for (uint8_t i = 0; i < MAX_CALLBACK_ASSIGNMENTS; ++i) + { + EEPROM.get(address, callback_assignments[i].address); + if (callback_assignments[i].address.value != 0) + { + // if address is not 0/0/0 then mark slot as used + callback_assignments[i].slot_flags |= SLOT_FLAGS_USED; + DEBUG_PRINTLN("used slot"); + } + else + { + // if address is 0/0/0, then we found a free slot, yay! + // however, only count those slots, if we have not reached registered_callback_assignments yet + if (i < registered_callback_assignments) + { + DEBUG_PRINTLN("free slot before reaching registered_callback_assignments"); + free_callback_assignment_slots++; + } + else + { + DEBUG_PRINTLN("free slot"); + } + } + address += sizeof(address_t); + } + for (uint8_t i = 0; i < MAX_CALLBACK_ASSIGNMENTS; ++i) + { + EEPROM.get(address, callback_assignments[i].callback_id); + address += sizeof(callback_id_t); + } + EEPROM.get(address, physaddr); + address += sizeof(address_t); + + //EEPROM.get(address, custom_config_data); + //address += sizeof(custom_config_data); + uint32_t conf_offset = address; + for (uint8_t i = 0; i < registered_configs; ++i) + { + // First byte is flags. + config_flags_t flags = CONFIG_FLAGS_NO_FLAGS; + flags = (config_flags_t)EEPROM.read(address); + DEBUG_PRINT("Flag in EEPROM @ "); + DEBUG_PRINT(address - conf_offset); + DEBUG_PRINT(": "); + DEBUG_PRINTLN(flags, BIN); + custom_config_data[custom_configs[i].offset] = flags; + if (flags & CONFIG_FLAGS_VALUE_SET) + { + DEBUG_PRINTLN("Non-default value"); + for (int j = 0; j < custom_configs[i].len - sizeof(uint8_t); ++j) + { + custom_config_data[custom_configs[i].offset + sizeof(uint8_t) + j] = EEPROM.read(address + sizeof(uint8_t) + j); + } + } + + address += custom_configs[i].len; + } + + DEBUG_PRINT("Restored from EEPROM: 0x"); + DEBUG_PRINTLN(address, HEX); +} + +uint16_t ESPKNXIP::__ntohs(uint16_t n) +{ + return (uint16_t)((((uint8_t*)&n)[0] << 8) | (((uint8_t*)&n)[1])); +} + +callback_assignment_id_t ESPKNXIP::__callback_register_assignment(address_t address, callback_id_t id) +{ + if (registered_callback_assignments >= MAX_CALLBACK_ASSIGNMENTS) + return -1; + + if (free_callback_assignment_slots == 0) + { + callback_assignment_id_t aid = registered_callback_assignments; + + callback_assignments[aid].slot_flags |= SLOT_FLAGS_USED; + callback_assignments[aid].address = address; + callback_assignments[aid].callback_id = id; + registered_callback_assignments++; + return aid; + } + else + { + // find the free slot + for (callback_assignment_id_t aid = 0; aid < registered_callback_assignments; ++aid) + { + if (callback_assignments[aid].slot_flags & SLOT_FLAGS_USED) + { + // found a used slot + continue; + } + // and now an empty one + callback_assignments[aid].slot_flags |= SLOT_FLAGS_USED; + callback_assignments[aid].address = address; + callback_assignments[aid].callback_id = id; + + free_callback_assignment_slots--; + return id; + } + } +} + +void ESPKNXIP::__callback_delete_assignment(callback_assignment_id_t id) +{ + // TODO this can be optimized if we are deleting the last element + // as then we can decrement registered_callback_assignments + + // clear slot and mark it as empty + callback_assignments[id].slot_flags = SLOT_FLAGS_EMPTY; + callback_assignments[id].address.value = 0; + callback_assignments[id].callback_id = 0; + + if (id == registered_callback_assignments - 1) + { + DEBUG_PRINTLN("last cba deleted"); + // If this is the last callback, we can delete it by decrementing registered_callbacks. + registered_callback_assignments--; + + // However, if the assignment before this slot are also empty, we can decrement even further + // First check if this was also the first element + if (id == 0) + { + DEBUG_PRINTLN("really last cba"); + // If this was the last, then we are done. + return; + } + + id--; + while(true) + { + DEBUG_PRINT("checking "); + DEBUG_PRINTLN((int32_t)id); + if ((callback_assignments[id].slot_flags & SLOT_FLAGS_USED) == 0) + { + DEBUG_PRINTLN("merged free slot"); + // Slot before is empty + free_callback_assignment_slots--; + registered_callback_assignments--; + } + else + { + DEBUG_PRINTLN("aborted on used slot"); + // Slot is used, abort + return; + } + id--; + if (id == CALLBACK_ASSIGNMENT_ID_MAX) + { + DEBUG_PRINTLN("abort on wrap"); + // Wrap around, abort + return; + } + } + } + else + { + DEBUG_PRINTLN("free slot created"); + // there is now one more free slot + free_callback_assignment_slots++; + } +} + +bool ESPKNXIP::__callback_is_id_valid(callback_id_t id) +{ + if (id < registered_callbacks) + return true; + + if (callbacks[id].slot_flags & SLOT_FLAGS_USED) + return true; + + return false; +} + +callback_id_t ESPKNXIP::callback_register(String name, callback_fptr_t cb, void *arg, enable_condition_t cond) +{ + if (registered_callbacks >= MAX_CALLBACKS) + return -1; + + if (free_callback_slots == 0) + { + callback_id_t id = registered_callbacks; + + callbacks[id].slot_flags |= SLOT_FLAGS_USED; + callbacks[id].name = name; + callbacks[id].fkt = cb; + callbacks[id].cond = cond; + callbacks[id].arg = arg; + registered_callbacks++; + return id; + } + else + { + // find the free slot + for (callback_id_t id = 0; id < registered_callbacks; ++id) + { + if (callbacks[id].slot_flags & SLOT_FLAGS_USED) + { + // found a used slot + continue; + } + // and now an empty one + callbacks[id].slot_flags |= SLOT_FLAGS_USED; + callbacks[id].name = name; + callbacks[id].fkt = cb; + callbacks[id].cond = cond; + callbacks[id].arg = arg; + + free_callback_slots--; + return id; + } + } +} + +void ESPKNXIP::callback_deregister(callback_id_t id) +{ + if (!__callback_is_id_valid(id)) + return; + + // clear slot and mark it as empty + callbacks[id].slot_flags = SLOT_FLAGS_EMPTY; + callbacks[id].fkt = nullptr; + callbacks[id].cond = nullptr; + callbacks[id].arg = nullptr; + + if (id == registered_callbacks - 1) + { + // If this is the last callback, we can delete it by decrementing registered_callbacks. + registered_callbacks--; + + // However, if the callbacks before this slot are also empty, we can decrement even further + // First check if this was also the first element + if (id == 0) + { + // If this was the last, then we are done. + return; + } + + id--; + while(true) + { + if ((callbacks[id].slot_flags & SLOT_FLAGS_USED) == 0) + { + // Slot is empty + free_callback_slots--; + registered_callbacks--; + } + else + { + // Slot is used, abort + return; + } + id--; + if (id == CALLBACK_ASSIGNMENT_ID_MAX) + { + // Wrap around, abort + return; + } + } + } + else + { + // there is now one more free slot + free_callback_slots++; + } +} + +callback_assignment_id_t ESPKNXIP::callback_assign(callback_id_t id, address_t val) +{ + if (!__callback_is_id_valid(id)) + return -1; + + return __callback_register_assignment(val, id); +} + +void ESPKNXIP::callback_unassign(callback_assignment_id_t id) +{ + if (!__callback_is_id_valid(id)) + return; + + __callback_delete_assignment(id); +} + +/** + * Feedback functions start here + */ + +feedback_id_t ESPKNXIP::feedback_register_int(String name, int32_t *value, enable_condition_t cond) +{ + if (registered_feedbacks >= MAX_FEEDBACKS) + return -1; + + feedback_id_t id = registered_feedbacks; + + feedbacks[id].type = FEEDBACK_TYPE_INT; + feedbacks[id].name = name; + feedbacks[id].cond = cond; + feedbacks[id].data = (void *)value; + + registered_feedbacks++; + + return id; +} + +feedback_id_t ESPKNXIP::feedback_register_float(String name, float *value, uint8_t precision, char const *prefix, char const *suffix, enable_condition_t cond) +{ + if (registered_feedbacks >= MAX_FEEDBACKS) + return -1; + + feedback_id_t id = registered_feedbacks; + + feedbacks[id].type = FEEDBACK_TYPE_FLOAT; + feedbacks[id].name = name; + feedbacks[id].cond = cond; + feedbacks[id].data = (void *)value; + feedbacks[id].options.float_options.precision = precision; + feedbacks[id].options.float_options.prefix = prefix ? strdup(prefix) : STRING_DEFAULT_EMPTY; + feedbacks[id].options.float_options.suffix = suffix ? strdup(suffix) : STRING_DEFAULT_EMPTY; + + registered_feedbacks++; + + return id; +} + +feedback_id_t ESPKNXIP::feedback_register_bool(String name, bool *value, char const *true_text, char const *false_text, enable_condition_t cond) +{ + if (registered_feedbacks >= MAX_FEEDBACKS) + return -1; + + feedback_id_t id = registered_feedbacks; + + feedbacks[id].type = FEEDBACK_TYPE_BOOL; + feedbacks[id].name = name; + feedbacks[id].cond = cond; + feedbacks[id].data = (void *)value; + feedbacks[id].options.bool_options.true_text = true_text ? strdup(true_text) : STRING_DEFAULT_TRUE; + feedbacks[id].options.bool_options.false_text = false_text ? strdup(false_text) : STRING_DEFAULT_FALSE; + + registered_feedbacks++; + + return id; +} + +feedback_id_t ESPKNXIP::feedback_register_action(String name, feedback_action_fptr_t value, const char *btn_text, void *arg, enable_condition_t cond) +{ + if (registered_feedbacks >= MAX_FEEDBACKS) + return -1; + + feedback_id_t id = registered_feedbacks; + + feedbacks[id].type = FEEDBACK_TYPE_ACTION; + feedbacks[id].name = name; + feedbacks[id].cond = cond; + feedbacks[id].data = (void *)value; + feedbacks[id].options.action_options.arg = arg; + feedbacks[id].options.action_options.btn_text = btn_text ? strdup(btn_text) : STRING_DEFAULT_DO_THIS; + + registered_feedbacks++; + + return id; +} + +void ESPKNXIP::loop() +{ + __loop_knx(); + if (server != nullptr) + { + __loop_webserver(); + } +} + +void ESPKNXIP::__loop_webserver() +{ + server->handleClient(); +} + +void ESPKNXIP::__loop_knx() +{ + int read = udp.parsePacket(); + if (!read) + { + return; + } + DEBUG_PRINTLN(F("")); + DEBUG_PRINT(F("LEN: ")); + DEBUG_PRINTLN(read); + + uint8_t buf[read]; + + udp.read(buf, read); + udp.flush(); + + DEBUG_PRINT(F("Got packet:")); +#ifdef ESP_KNX_DEBUG + for (int i = 0; i < read; ++i) + { + DEBUG_PRINT(F(" 0x")); + DEBUG_PRINT(buf[i], 16); + } +#endif + DEBUG_PRINTLN(F("")); + + knx_ip_pkt_t *knx_pkt = (knx_ip_pkt_t *)buf; + + DEBUG_PRINT(F("ST: 0x")); + DEBUG_PRINTLN(__ntohs(knx_pkt->service_type), 16); + + if (knx_pkt->header_len != 0x06 && knx_pkt->protocol_version != 0x10 && knx_pkt->service_type != KNX_ST_ROUTING_INDICATION) + return; + + cemi_msg_t *cemi_msg = (cemi_msg_t *)knx_pkt->pkt_data; + + DEBUG_PRINT(F("MT: 0x")); + DEBUG_PRINTLN(cemi_msg->message_code, 16); + + if (cemi_msg->message_code != KNX_MT_L_DATA_IND) + return; + + DEBUG_PRINT(F("ADDI: 0x")); + DEBUG_PRINTLN(cemi_msg->additional_info_len, 16); + + cemi_service_t *cemi_data = &cemi_msg->data.service_information; + + if (cemi_msg->additional_info_len > 0) + cemi_data = (cemi_service_t *)(((uint8_t *)cemi_data) + cemi_msg->additional_info_len); + + DEBUG_PRINT(F("C1: 0x")); + DEBUG_PRINTLN(cemi_data->control_1.byte, 16); + + DEBUG_PRINT(F("C2: 0x")); + DEBUG_PRINTLN(cemi_data->control_2.byte, 16); + + DEBUG_PRINT(F("DT: 0x")); + DEBUG_PRINTLN(cemi_data->control_2.bits.dest_addr_type, 16); + + if (cemi_data->control_2.bits.dest_addr_type != 0x01) + return; + + DEBUG_PRINT(F("HC: 0x")); + DEBUG_PRINTLN(cemi_data->control_2.bits.hop_count, 16); + + DEBUG_PRINT(F("EFF: 0x")); + DEBUG_PRINTLN(cemi_data->control_2.bits.extended_frame_format, 16); + + DEBUG_PRINT(F("Source: 0x")); + DEBUG_PRINT(cemi_data->source.bytes.high, 16); + DEBUG_PRINT(F(" 0x")); + DEBUG_PRINTLN(cemi_data->source.bytes.low, 16); + + DEBUG_PRINT(F("Dest: 0x")); + DEBUG_PRINT(cemi_data->destination.bytes.high, 16); + DEBUG_PRINT(F(" 0x")); + DEBUG_PRINTLN(cemi_data->destination.bytes.low, 16); + + knx_command_type_t ct = (knx_command_type_t)(((cemi_data->data[0] & 0xC0) >> 6) | ((cemi_data->pci.apci & 0x03) << 2)); + + DEBUG_PRINT(F("CT: 0x")); + DEBUG_PRINTLN(ct, 16); + +#ifdef ESP_KNX_DEBUG + for (int i = 0; i < cemi_data->data_len; ++i) + { + DEBUG_PRINT(F(" 0x")); + DEBUG_PRINT(cemi_data->data[i], 16); + } +#endif + + DEBUG_PRINTLN(F("==")); + + // Call callbacks + for (int i = 0; i < registered_callback_assignments; ++i) + { + DEBUG_PRINT(F("Testing: 0x")); + DEBUG_PRINT(callback_assignments[i].address.bytes.high, 16); + DEBUG_PRINT(F(" 0x")); + DEBUG_PRINTLN(callback_assignments[i].address.bytes.low, 16); + if (cemi_data->destination.value == callback_assignments[i].address.value) + { + DEBUG_PRINTLN(F("Found match")); + if (callbacks[callback_assignments[i].callback_id].cond && !callbacks[callback_assignments[i].callback_id].cond()) + { + DEBUG_PRINTLN(F("But it's disabled")); +#if ALLOW_MULTIPLE_CALLBACKS_PER_ADDRESS + continue; +#else + return; +#endif + } + uint8_t data[cemi_data->data_len]; + memcpy(data, cemi_data->data, cemi_data->data_len); + data[0] = data[0] & 0x3F; + message_t msg = {}; + msg.ct = ct; + msg.received_on = cemi_data->destination; + msg.data_len = cemi_data->data_len; + msg.data = data; + callbacks[callback_assignments[i].callback_id].fkt(msg, callbacks[callback_assignments[i].callback_id].arg); +#if ALLOW_MULTIPLE_CALLBACKS_PER_ADDRESS + continue; +#else + return; +#endif + } + } + + return; +} + +// Global "singleton" object +ESPKNXIP knx; diff --git a/lib/esp-knx-ip-0.5.0/esp-knx-ip.h b/lib/esp-knx-ip-0.5.0/esp-knx-ip.h new file mode 100644 index 000000000..538264b3e --- /dev/null +++ b/lib/esp-knx-ip-0.5.0/esp-knx-ip.h @@ -0,0 +1,571 @@ +/** + * esp-knx-ip library for KNX/IP communication on an ESP8266 + * Author: Nico Weichbrodt + * License: MIT + */ + +#ifndef ESP_KNX_IP_H +#define ESP_KNX_IP_H + +/** + * CONFIG + * All MAX_ values must not exceed 255 (1 byte, except MAC_CONFIG_SPACE which can go up to 2 bytes, so 0xffff in theory) and must not be negative! + * Config space is restriced by EEPROM_SIZE (default 1024). + * Required EEPROM size is 8 + MAX_GA_CALLBACKS * 3 + 2 + MAX_CONFIG_SPACE which is 552 by default + */ +#define EEPROM_SIZE 1024 // [Default 1024] +#define MAX_CALLBACK_ASSIGNMENTS 10 // [Default 10] Maximum number of group address callbacks that can be stored +#define MAX_CALLBACKS 10 // [Default 10] Maximum number of callbacks that can be stored +#define MAX_CONFIGS 20 // [Default 20] Maximum number of config items that can be stored +#define MAX_CONFIG_SPACE 0x0200 // [Default 0x0200] Maximum number of bytes that can be stored for custom config + +#define MAX_FEEDBACKS 20 // [Default 20] Maximum number of feedbacks that can be shown + +// Callbacks +#define ALLOW_MULTIPLE_CALLBACKS_PER_ADDRESS 1 // [Default 0] Set to 1 to always test all assigned callbacks. This allows for multiple callbacks being assigned to the same address. If disabled, only the first assigned will be called. + +// Webserver related +#define USE_BOOTSTRAP 1 // [Default 1] Set to 1 to enable use of bootstrap CSS for nicer webconfig. CSS is loaded from bootstrapcdn.com. Set to 0 to disable +#define ROOT_PREFIX "" // [Default ""] This gets prepended to all webserver paths, default is empty string "". Set this to "/knx" if you want the config to be available on http:///knx +#define DISABLE_EEPROM_BUTTONS 1 // [Default 0] Set to 1 to disable the EEPROM buttons in the web ui. +#define DISABLE_REBOOT_BUTTON 1 // [Default 0] Set to 1 to disable the reboot button in the web ui. +#define DISABLE_RESTORE_BUTTON 1 // [Default 0] Set to 1 to disable the "restore defaults" button in the web ui. + +// These values normally don't need adjustment +#define MULTICAST_PORT 3671 // [Default 3671] +#define MULTICAST_IP IPAddress(224, 0, 23, 12) // [Default IPAddress(224, 0, 23, 12)] +#define SEND_CHECKSUM 0 + +// Uncomment to enable printing out debug messages. +//#define ESP_KNX_DEBUG +/** + * END CONFIG + */ + +#include "Arduino.h" +#include +#include +#include +#include + +#include "DPT.h" + +#define EEPROM_MAGIC (0xDEADBEEF00000000 + (MAX_CONFIG_SPACE) + (MAX_CALLBACK_ASSIGNMENTS << 16) + (MAX_CALLBACKS << 8)) + +// Define where debug output will be printed. +#ifndef DEBUG_PRINTER +#define DEBUG_PRINTER Serial +#endif + +// Setup debug printing macros. +#ifdef ESP_KNX_DEBUG + #define DEBUG_PRINT(...) { DEBUG_PRINTER.print(__VA_ARGS__); } + #define DEBUG_PRINTLN(...) { DEBUG_PRINTER.println(__VA_ARGS__); } +#else + #define DEBUG_PRINT(...) {} + #define DEBUG_PRINTLN(...) {} +#endif + +#define __ROOT_PATH ROOT_PREFIX"/" +#define __REGISTER_PATH ROOT_PREFIX"/register" +#define __DELETE_PATH ROOT_PREFIX"/delete" +#define __PHYS_PATH ROOT_PREFIX"/phys" +#define __EEPROM_PATH ROOT_PREFIX"/eeprom" +#define __CONFIG_PATH ROOT_PREFIX"/config" +#define __FEEDBACK_PATH ROOT_PREFIX"/feedback" +#define __RESTORE_PATH ROOT_PREFIX"/restore" +#define __REBOOT_PATH ROOT_PREFIX"/reboot" + +/** + * Different service types, we are mainly interested in KNX_ST_ROUTING_INDICATION + */ +typedef enum __knx_service_type +{ + KNX_ST_SEARCH_REQUEST = 0x0201, + KNX_ST_SEARCH_RESPONSE = 0x0202, + KNX_ST_DESCRIPTION_REQUEST = 0x0203, + KNX_ST_DESCRIPTION_RESPONSE = 0x0204, + KNX_ST_CONNECT_REQUEST = 0x0205, + KNX_ST_CONNECT_RESPONSE = 0x0206, + KNX_ST_CONNECTIONSTATE_REQUEST = 0x0207, + KNX_ST_CONNECTIONSTATE_RESPONSE = 0x0208, + KNX_ST_DISCONNECT_REQUEST = 0x0209, + KNX_ST_DISCONNECT_RESPONSE = 0x020A, + + KNX_ST_DEVICE_CONFIGURATION_REQUEST = 0x0310, + KNX_ST_DEVICE_CONFIGURATION_ACK = 0x0311, + + KNX_ST_TUNNELING_REQUEST = 0x0420, + KNX_ST_TUNNELING_ACK = 0x0421, + + KNX_ST_ROUTING_INDICATION = 0x0530, + KNX_ST_ROUTING_LOST_MESSAGE = 0x0531, + KNX_ST_ROUTING_BUSY = 0x0532, + +// KNX_ST_RLOG_START = 0x0600, +// KNX_ST_RLOG_END = 0x06FF, + + KNX_ST_REMOTE_DIAGNOSTIC_REQUEST = 0x0740, + KNX_ST_REMOTE_DIAGNOSTIC_RESPONSE = 0x0741, + KNX_ST_REMOTE_BASIC_CONFIGURATION_REQUEST = 0x0742, + KNX_ST_REMOTE_RESET_REQUEST = 0x0743, + +// KNX_ST_OBJSRV_START = 0x0800, +// KNX_ST_OBJSRV_END = 0x08FF, +} knx_service_type_t; + +/** + * Differnt command types, first three are of main interest + */ +typedef enum __knx_command_type +{ + KNX_CT_READ = 0x00, + KNX_CT_ANSWER = 0x01, + KNX_CT_WRITE = 0x02, + KNX_CT_INDIVIDUAL_ADDR_WRITE = 0x03, + KNX_CT_INDIVIDUAL_ADDR_REQUEST = 0x04, + KNX_CT_INDIVIDUAL_ADDR_RESPONSE = 0x05, + KNX_CT_ADC_READ = 0x06, + KNX_CT_ADC_ANSWER = 0x07, + KNX_CT_MEM_READ = 0x08, + KNX_CT_MEM_ANSWER = 0x09, + KNX_CT_MEM_WRITE = 0x0A, +//KNX_CT_UNKNOWN = 0x0B, + KNX_CT_MASK_VERSION_READ = 0x0C, + KNX_CT_MASK_VERSION_RESPONSE = 0x0D, + KNX_CT_RESTART = 0x0E, + KNX_CT_ESCAPE = 0x0F, +} knx_command_type_t; + +/** + * cEMI message types, mainly KNX_MT_L_DATA_IND is interesting + */ +typedef enum __knx_cemi_msg_type +{ + KNX_MT_L_DATA_REQ = 0x11, + KNX_MT_L_DATA_IND = 0x29, + KNX_MT_L_DATA_CON = 0x2E, +} knx_cemi_msg_type_t; + +/** + * TCPI communication type + */ +typedef enum __knx_communication_type { + KNX_COT_UDP = 0x00, // Unnumbered Data Packet + KNX_COT_NDP = 0x01, // Numbered Data Packet + KNX_COT_UCD = 0x02, // Unnumbered Control Data + KNX_COT_NCD = 0x03, // Numbered Control Data +} knx_communication_type_t; + +/** + * KNX/IP header + */ +typedef struct __knx_ip_pkt +{ + uint8_t header_len; // Should always be 0x06 + uint8_t protocol_version; // Should be version 1.0, transmitted as 0x10 + uint16_t service_type; // See knx_service_type_t + union + { + struct { + uint8_t first_byte; + uint8_t second_byte; + } bytes; + uint16_t len; + } total_len; // header_len + rest of pkt. This is a bit weird as the spec says this: If the total number of bytes transmitted is greater than 252 bytes, the first “Total Length” byte is set to FF (255). Only in this case the second byte includes additional length information + uint8_t pkt_data[]; // This is of type cemi_msg_t +} knx_ip_pkt_t; + +typedef struct __cemi_addi +{ + uint8_t type_id; + uint8_t len; + uint8_t data[]; +} cemi_addi_t; + +typedef union __address +{ + uint16_t value; + struct + { + uint8_t high; + uint8_t low; + } bytes; + struct __attribute__((packed)) + { + uint8_t line:3; + uint8_t area:5; + uint8_t member; + } ga; + struct __attribute__((packed)) + { + uint8_t line:4; + uint8_t area:4; + uint8_t member; + } pa; + uint8_t array[2]; +} address_t; + +typedef struct __cemi_service +{ + union + { + struct + { + // Struct is reversed due to bit order + uint8_t confirm:1; // 0 = no error, 1 = error + uint8_t ack:1; // 0 = no ack, 1 = ack + uint8_t priority:2; // 0 = system, 1 = high, 2 = urgent/alarm, 3 = normal + uint8_t system_broadcast:1; // 0 = system broadcast, 1 = broadcast + uint8_t repeat:1; // 0 = repeat on error, 1 = do not repeat + uint8_t reserved:1; // always zero + uint8_t frame_type:1; // 0 = extended, 1 = standard + } bits; + uint8_t byte; + } control_1; + union + { + struct + { + // Struct is reversed due to bit order + uint8_t extended_frame_format:4; + uint8_t hop_count:3; + uint8_t dest_addr_type:1; // 0 = individual, 1 = group + } bits; + uint8_t byte; + } control_2; + address_t source; + address_t destination; + uint8_t data_len; // length of data, excluding the tpci byte + struct + { + uint8_t apci:2; // If tpci.comm_type == KNX_COT_UCD or KNX_COT_NCD, then this is apparently control data? + uint8_t tpci_seq_number:4; + uint8_t tpci_comm_type:2; // See knx_communication_type_t + } pci; + uint8_t data[]; +} cemi_service_t; + +typedef struct __cemi_msg +{ + uint8_t message_code; + uint8_t additional_info_len; + union + { + cemi_addi_t additional_info[]; + cemi_service_t service_information; + } data; +} cemi_msg_t; + +typedef enum __config_type +{ + CONFIG_TYPE_UNKNOWN, + CONFIG_TYPE_INT, + CONFIG_TYPE_BOOL, + CONFIG_TYPE_STRING, + CONFIG_TYPE_OPTIONS, + CONFIG_TYPE_GA, +} config_type_t; + +typedef enum __feedback_type +{ + FEEDBACK_TYPE_UNKNOWN, + FEEDBACK_TYPE_INT, + FEEDBACK_TYPE_FLOAT, + FEEDBACK_TYPE_BOOL, + FEEDBACK_TYPE_ACTION, +} feedback_type_t; + +typedef enum __config_flags +{ + CONFIG_FLAGS_NO_FLAGS = 0, + CONFIG_FLAGS_VALUE_SET = 1, +} config_flags_t; + +typedef enum __slot_flags +{ + SLOT_FLAGS_EMPTY = 0, // Empty slots have no flags + SLOT_FLAGS_USED = 1, +} slot_flags_t; + +typedef struct __message +{ + knx_command_type_t ct; + address_t received_on; + uint8_t data_len; + uint8_t *data; +} message_t; + +typedef bool (*enable_condition_t)(void); +typedef void (*callback_fptr_t)(message_t const &msg, void *arg); +typedef void (*feedback_action_fptr_t)(void *arg); + +typedef uint8_t callback_id_t; +#define CALLBACK_ID_MAX UINT8_MAX +typedef uint8_t callback_assignment_id_t; +#define CALLBACK_ASSIGNMENT_ID_MAX UINT8_MAX +typedef uint8_t config_id_t; +typedef uint8_t feedback_id_t; + +typedef struct __option_entry +{ + char const *name; + uint8_t value; +} option_entry_t; + +typedef struct __config +{ + config_type_t type; + String name; + uint8_t offset; + uint8_t len; + enable_condition_t cond; + union { + option_entry_t *options; + } data; +} config_t; + +extern char const *string_defaults[]; +#define STRING_DEFAULT_DO_THIS (string_defaults[0]) +#define STRING_DEFAULT_TRUE (string_defaults[1]) +#define STRING_DEFAULT_FALSE (string_defaults[2]) +#define STRING_DEFAULT_EMPTY (string_defaults[3]) + +typedef struct __feedback_float_options +{ + uint8_t precision; + char const *prefix; + char const *suffix; +} feedback_float_options_t; + +typedef struct __feedback_bool_options +{ + char const *true_text; + char const *false_text; +} feedback_bool_options_t; + +typedef struct __feedback_action_options +{ + void *arg; + char const *btn_text; +} feedback_action_options_t; + +typedef struct __feedback +{ + feedback_type_t type; + String name; + enable_condition_t cond; + void *data; + union { + feedback_bool_options_t bool_options; + feedback_float_options_t float_options; + feedback_action_options_t action_options; + } options; +} feedback_t; + +typedef struct __callback +{ + uint8_t slot_flags; + callback_fptr_t fkt; + enable_condition_t cond; + void *arg; + String name; +} callback_t; + +typedef struct __callback_assignment +{ + uint8_t slot_flags; + address_t address; + callback_id_t callback_id; +} callback_assignment_t; + +class ESPKNXIP { + public: + ESPKNXIP(); + void load(); + void start(); + void start(ESP8266WebServer *srv); + void loop(); + + void save_to_eeprom(); + void restore_from_eeprom(); + + callback_id_t callback_register(String name, callback_fptr_t cb, void *arg = nullptr, enable_condition_t cond = nullptr); + callback_assignment_id_t callback_assign(callback_id_t id, address_t val); + void callback_deregister(callback_id_t id); + void callback_unassign(callback_assignment_id_t id); + + void physical_address_set(address_t const &addr); + address_t physical_address_get(); + + // Configuration functions + config_id_t config_register_string(String name, uint8_t len, String _default, enable_condition_t cond = nullptr); + config_id_t config_register_int(String name, int32_t _default, enable_condition_t cond = nullptr); + config_id_t config_register_bool(String name, bool _default, enable_condition_t cond = nullptr); + config_id_t config_register_options(String name, option_entry_t *options, uint8_t _default, enable_condition_t cond = nullptr); + config_id_t config_register_ga(String name, enable_condition_t cond = nullptr); + + String config_get_string(config_id_t id); + int32_t config_get_int(config_id_t id); + bool config_get_bool(config_id_t id); + uint8_t config_get_options(config_id_t id); + address_t config_get_ga(config_id_t id); + + void config_set_string(config_id_t id, String val); + void config_set_int(config_id_t id, int32_t val); + void config_set_bool(config_id_t, bool val); + void config_set_options(config_id_t id, uint8_t val); + void config_set_ga(config_id_t id, address_t const &val); + + // Feedback functions + feedback_id_t feedback_register_int(String name, int32_t *value, enable_condition_t cond = nullptr); + feedback_id_t feedback_register_float(String name, float *value, uint8_t precision = 2, char const *prefix = nullptr, char const *suffix = nullptr, enable_condition_t cond = nullptr); + feedback_id_t feedback_register_bool(String name, bool *value, char const *true_text = nullptr, char const *false_text = nullptr, enable_condition_t cond = nullptr); + feedback_id_t feedback_register_action(String name, feedback_action_fptr_t value, char const *btn_text = nullptr, void *arg = nullptr, enable_condition_t = nullptr); + + // Send functions + void send(address_t const &receiver, knx_command_type_t ct, uint8_t data_len, uint8_t *data); + + void send_1bit(address_t const &receiver, knx_command_type_t ct, uint8_t bit); + void send_2bit(address_t const &receiver, knx_command_type_t ct, uint8_t twobit); + void send_4bit(address_t const &receiver, knx_command_type_t ct, uint8_t fourbit); + void send_1byte_int(address_t const &receiver, knx_command_type_t ct, int8_t val); + void send_1byte_uint(address_t const &receiver, knx_command_type_t ct, uint8_t val); + void send_2byte_int(address_t const &receiver, knx_command_type_t ct, int16_t val); + void send_2byte_uint(address_t const &receiver, knx_command_type_t ct, uint16_t val); + void send_2byte_float(address_t const &receiver, knx_command_type_t ct, float val); + void send_3byte_time(address_t const &receiver, knx_command_type_t ct, uint8_t weekday, uint8_t hours, uint8_t minutes, uint8_t seconds); + void send_3byte_time(address_t const &receiver, knx_command_type_t ct, time_of_day_t const &time) { send_3byte_time(receiver, ct, time.weekday, time.hours, time.minutes, time.seconds); } + void send_3byte_date(address_t const &receiver, knx_command_type_t ct, uint8_t day, uint8_t month, uint8_t year); + void send_3byte_date(address_t const &receiver, knx_command_type_t ct, date_t const &date) { send_3byte_date(receiver, ct, date.day, date.month, date.year); } + void send_3byte_color(address_t const &receiver, knx_command_type_t ct, uint8_t red, uint8_t green, uint8_t blue); + void send_3byte_color(address_t const &receiver, knx_command_type_t ct, color_t const &color) { send_3byte_color(receiver, ct, color.red, color.green, color.blue); } + void send_4byte_int(address_t const &receiver, knx_command_type_t ct, int32_t val); + void send_4byte_uint(address_t const &receiver, knx_command_type_t ct, uint32_t val); + void send_4byte_float(address_t const &receiver, knx_command_type_t ct, float val); + + void write_1bit(address_t const &receiver, uint8_t bit) { send_1bit(receiver, KNX_CT_WRITE, bit); } + void write_2bit(address_t const &receiver, uint8_t twobit) { send_2bit(receiver, KNX_CT_WRITE, twobit); } + void write_4bit(address_t const &receiver, uint8_t fourbit) { send_4bit(receiver, KNX_CT_WRITE, fourbit); } + void write_1byte_int(address_t const &receiver, int8_t val) { send_1byte_int(receiver, KNX_CT_WRITE, val); } + void write_1byte_uint(address_t const &receiver, uint8_t val) { send_1byte_uint(receiver, KNX_CT_WRITE, val); } + void write_2byte_int(address_t const &receiver, int16_t val) { send_2byte_int(receiver, KNX_CT_WRITE, val); } + void write_2byte_uint(address_t const &receiver, uint16_t val) { send_2byte_uint(receiver, KNX_CT_WRITE, val); } + void write_2byte_float(address_t const &receiver, float val) { send_2byte_float(receiver, KNX_CT_WRITE, val); } + void write_3byte_time(address_t const &receiver, uint8_t weekday, uint8_t hours, uint8_t minutes, uint8_t seconds) { send_3byte_time(receiver, KNX_CT_WRITE, weekday, hours, minutes, seconds); } + void write_3byte_time(address_t const &receiver, time_of_day_t const &time) { send_3byte_time(receiver, KNX_CT_WRITE, time.weekday, time.hours, time.minutes, time.seconds); } + void write_3byte_date(address_t const &receiver, uint8_t day, uint8_t month, uint8_t year) { send_3byte_date(receiver, KNX_CT_WRITE, day, month, year); } + void write_3byte_date(address_t const &receiver, date_t const &date) { send_3byte_date(receiver, KNX_CT_WRITE, date.day, date.month, date.year); } + void write_3byte_color(address_t const &receiver, uint8_t red, uint8_t green, uint8_t blue) { send_3byte_color(receiver, KNX_CT_WRITE, red, green, blue); } + void write_3byte_color(address_t const &receiver, color_t const &color) { send_3byte_color(receiver, KNX_CT_WRITE, color); } + void write_4byte_int(address_t const &receiver, int32_t val) { send_4byte_int(receiver, KNX_CT_WRITE, val); } + void write_4byte_uint(address_t const &receiver, uint32_t val) { send_4byte_uint(receiver, KNX_CT_WRITE, val); } + void write_4byte_float(address_t const &receiver, float val) { send_4byte_float(receiver, KNX_CT_WRITE, val);} + + void answer_1bit(address_t const &receiver, uint8_t bit) { send_1bit(receiver, KNX_CT_ANSWER, bit); } + void answer_2bit(address_t const &receiver, uint8_t twobit) { send_2bit(receiver, KNX_CT_ANSWER, twobit); } + void answer_4bit(address_t const &receiver, uint8_t fourbit) { send_4bit(receiver, KNX_CT_ANSWER, fourbit); } + void answer_1byte_int(address_t const &receiver, int8_t val) { send_1byte_int(receiver, KNX_CT_ANSWER, val); } + void answer_1byte_uint(address_t const &receiver, uint8_t val) { send_1byte_uint(receiver, KNX_CT_ANSWER, val); } + void answer_2byte_int(address_t const &receiver, int16_t val) { send_2byte_int(receiver, KNX_CT_ANSWER, val); } + void answer_2byte_uint(address_t const &receiver, uint16_t val) { send_2byte_uint(receiver, KNX_CT_ANSWER, val); } + void answer_2byte_float(address_t const &receiver, float val) { send_2byte_float(receiver, KNX_CT_ANSWER, val); } + void answer_3byte_time(address_t const &receiver, uint8_t weekday, uint8_t hours, uint8_t minutes, uint8_t seconds) { send_3byte_time(receiver, KNX_CT_ANSWER, weekday, hours, minutes, seconds); } + void answer_3byte_time(address_t const &receiver, time_of_day_t const &time) { send_3byte_time(receiver, KNX_CT_ANSWER, time.weekday, time.hours, time.minutes, time.seconds); } + void answer_3byte_date(address_t const &receiver, uint8_t day, uint8_t month, uint8_t year) { send_3byte_date(receiver, KNX_CT_ANSWER, day, month, year); } + void answer_3byte_date(address_t const &receiver, date_t const &date) { send_3byte_date(receiver, KNX_CT_ANSWER, date.day, date.month, date.year); } + void answer_3byte_color(address_t const &receiver, uint8_t red, uint8_t green, uint8_t blue) { send_3byte_color(receiver, KNX_CT_ANSWER, red, green, blue); } + void answer_3byte_color(address_t const &receiver, color_t const &color) { send_3byte_color(receiver, KNX_CT_ANSWER, color); } + void answer_4byte_int(address_t const &receiver, int32_t val) { send_4byte_int(receiver, KNX_CT_ANSWER, val); } + void answer_4byte_uint(address_t const &receiver, uint32_t val) { send_4byte_uint(receiver, KNX_CT_ANSWER, val); } + void answer_4byte_float(address_t const &receiver, float val) { send_4byte_float(receiver, KNX_CT_ANSWER, val);} + + bool data_to_bool(uint8_t *data); + int8_t data_to_1byte_int(uint8_t *data); + uint8_t data_to_1byte_uint(uint8_t *data); + int16_t data_to_2byte_int(uint8_t *data); + uint16_t data_to_2byte_uint(uint8_t *data); + float data_to_2byte_float(uint8_t *data); + color_t data_to_3byte_color(uint8_t *data); + time_of_day_t data_to_3byte_time(uint8_t *data); + date_t data_to_3byte_data(uint8_t *data); + int32_t data_to_4byte_int(uint8_t *data); + uint32_t data_to_4byte_uint(uint8_t *data); + float data_to_4byte_float(uint8_t *data); + + static address_t GA_to_address(uint8_t area, uint8_t line, uint8_t member) + { + // Yes, the order is correct, see the struct definition above + address_t tmp = {.ga={line, area, member}}; + return tmp; + } + + static address_t PA_to_address(uint8_t area, uint8_t line, uint8_t member) + { + // Yes, the order is correct, see the struct definition above + address_t tmp = {.pa={line, area, member}}; + return tmp; + } + + private: + void __start(); + void __loop_knx(); + + // Webserver functions + void __loop_webserver(); + void __handle_root(); + void __handle_register(); + void __handle_delete(); + void __handle_set(); +#if !DISABLE_EEPROM_BUTTONS + void __handle_eeprom(); +#endif + void __handle_config(); + void __handle_feedback(); +#if !DISABLE_RESTORE_BUTTONS + void __handle_restore(); +#endif +#if !DISABLE_REBOOT_BUTTONS + void __handle_reboot(); +#endif + + void __config_set_flags(config_id_t id, config_flags_t flags); + + void __config_set_string(config_id_t id, String &val); + void __config_set_int(config_id_t id, int32_t val); + void __config_set_bool(config_id_t id, bool val); + void __config_set_options(config_id_t id, uint8_t val); + void __config_set_ga(config_id_t id, address_t const &val); + + bool __callback_is_id_valid(callback_id_t id); + + callback_assignment_id_t __callback_register_assignment(address_t address, callback_id_t id); + void __callback_delete_assignment(callback_assignment_id_t id); + + ESP8266WebServer *server; + address_t physaddr; + WiFiUDP udp; + + callback_assignment_id_t registered_callback_assignments; + callback_assignment_id_t free_callback_assignment_slots; + callback_assignment_t callback_assignments[MAX_CALLBACK_ASSIGNMENTS]; + + callback_id_t registered_callbacks; + callback_id_t free_callback_slots; + callback_t callbacks[MAX_CALLBACKS]; + + config_id_t registered_configs; + uint8_t custom_config_data[MAX_CONFIG_SPACE]; + uint8_t custom_config_default_data[MAX_CONFIG_SPACE]; + config_t custom_configs[MAX_CONFIGS]; + + feedback_id_t registered_feedbacks; + feedback_t feedbacks[MAX_FEEDBACKS]; + + uint16_t __ntohs(uint16_t); +}; + +// Global "singleton" object +extern ESPKNXIP knx; + +#endif diff --git a/lib/esp-knx-ip-0.5.0/examples/environment-sensor/environment-sensor.ino b/lib/esp-knx-ip-0.5.0/examples/environment-sensor/environment-sensor.ino new file mode 100644 index 000000000..02621bbc6 --- /dev/null +++ b/lib/esp-knx-ip-0.5.0/examples/environment-sensor/environment-sensor.ino @@ -0,0 +1,159 @@ +/* + * This is an example showing a simple environment sensor based on a BME280 attached via I2C. + * This sketch was tested on a WeMos D1 mini + */ + +#include +#include + +// WiFi config here +const char* ssid = "myssid"; +const char* pass = "mypassword"; + +#define LED_PIN D4 +#define UPDATE_INTERVAL 10000 + +unsigned long next_change = 0; + +float last_temp = 0.0; +float last_hum = 0.0; +float last_pres = 0.0; + +config_id_t temp_ga, hum_ga, pres_ga; +config_id_t hostname_id; +config_id_t update_rate_id, send_rate_id; +config_id_t enable_sending_id; +config_id_t enable_reading_id; + +Adafruit_BME280 bme; + +void setup() { + pinMode(LED_PIN, OUTPUT); + Serial.begin(115200); + + hostname_id = knx.config_register_string("Hostname", 20, String("env")); + enable_sending_id = knx.config_register_bool("Send on update", true); + update_rate_id = knx.config_register_int("Update rate (ms)", UPDATE_INTERVAL); + temp_ga = knx.config_register_ga("Temperature", show_periodic_options); + hum_ga = knx.config_register_ga("Humidity", show_periodic_options); + pres_ga = knx.config_register_ga("Pressure", show_periodic_options); + + knx.callback_register("Read Temperature", temp_cb); + knx.callback_register("Read Humidity", hum_cb); + knx.callback_register("Read Pressure", pres_cb); + + knx.feedback_register_float("Temperature (°C)", &last_temp); + knx.feedback_register_float("Humidity (%)", &last_hum); + knx.feedback_register_float("Pressure (hPa)", &last_pres, 0); + + // Load previous config from EEPROM + knx.load(); + + // Init sensor + if (!bme.begin(0x76)) { + Serial.println("Could not find a valid BME280 sensor, check wiring!"); + } + + // Init WiFi + WiFi.hostname(knx.config_get_string(hostname_id)); + WiFi.begin(ssid, pass); + + Serial.println(""); + Serial.print("[Connecting]"); + Serial.print(ssid); + + digitalWrite(LED_PIN, LOW); + while (WiFi.status() != WL_CONNECTED) { + digitalWrite(LED_PIN, HIGH); + delay(250); + Serial.print("."); + digitalWrite(LED_PIN, LOW); + delay(250); + } + digitalWrite(LED_PIN, HIGH); + + // Start knx + knx.start(); + + Serial.println(); + Serial.println("Connected to wifi"); + Serial.println(WiFi.localIP()); +} + +void loop() { + knx.loop(); + + unsigned long now = millis(); + + if (next_change < now) + { + next_change = now + knx.config_get_int(update_rate_id); + + last_temp = bme.readTemperature(); + last_hum = bme.readHumidity(); + last_pres = bme.readPressure()/100.0f; + + Serial.print("T: "); + Serial.print(last_temp); + Serial.print("°C H: "); + Serial.print(last_hum); + Serial.print("% P: "); + Serial.print(last_pres); + Serial.println("hPa"); + + if (knx.config_get_bool(enable_sending_id)) + { + knx.write_2byte_float(knx.config_get_ga(temp_ga), last_temp); + knx.write_2byte_float(knx.config_get_ga(hum_ga), last_hum); + knx.write_2byte_float(knx.config_get_ga(pres_ga), last_pres); + } + } + + delay(50); +} + +bool show_periodic_options() +{ + return knx.config_get_bool(enable_sending_id); +} + +bool enable_reading_callback() +{ + return knx.config_get_bool(enable_reading_id); +} + +void temp_cb(message_t const &msg, void *arg) +{ + switch (msg.ct) + { + case KNX_CT_READ: + { + knx.answer_2byte_float(msg.received_on, last_temp); + break; + } + } +} + +void hum_cb(message_t const &msg, void *arg) +{ + switch (msg.ct) + { + case KNX_CT_READ: + { + knx.answer_2byte_float(msg.received_on, last_hum); + break; + } + } +} + +void pres_cb(message_t const &msg, void *arg) +{ + switch (msg.ct) + { + case KNX_CT_READ: + { + knx.answer_2byte_float(msg.received_on, last_pres); + break; + } + } +} diff --git a/lib/esp-knx-ip-0.5.0/examples/sonoff/sonoff.ino b/lib/esp-knx-ip-0.5.0/examples/sonoff/sonoff.ino new file mode 100644 index 000000000..fc2400b7b --- /dev/null +++ b/lib/esp-knx-ip-0.5.0/examples/sonoff/sonoff.ino @@ -0,0 +1,183 @@ +#include + +// WiFi config here +const char* ssid = "ssid"; +const char* pass = "pass"; + +// Common +#define LED_PIN 13 + +// For Basic and S20 +#define BTN1_PIN 0 +#define CH1_PIN 12 + +// For 4CH +#define BTN2_PIN 9 +#define CH2_PIN 5 +#define BTN3_PIN 10 +#define CH3_PIN 4 +#define BTN4_PIN 14 +#define CH4_PIN 15 + +typedef enum __type_option +{ + SONOFF_TYPE_NONE = 0, + SONOFF_TYPE_BASIC = 1, + SONOFF_TYPE_S20 = 2, + SONOFF_TYPE_4CH = 3, + SONOFF_TYPE_4CH_PRO = 4, +} type_option_t; + +option_entry_t type_options[] = { + {"Sonoff Basic", SONOFF_TYPE_BASIC}, + {"Sonoff S20", SONOFF_TYPE_S20}, + {"Sonoff 4CH", SONOFF_TYPE_4CH}, + {"Sonoff 4CH Pro", SONOFF_TYPE_4CH_PRO}, + {nullptr, 0} +}; + +config_id_t hostname_id; +config_id_t type_id; + +typedef struct __sonoff_channel +{ + int pin; + int btn_pin; + config_id_t status_ga_id; + bool state; + bool last_btn_state; +} sonoff_channel_t; + +sonoff_channel_t channels[] = { + {CH1_PIN, BTN1_PIN, 0, false, false}, + {CH2_PIN, BTN2_PIN, 0, false, false}, + {CH3_PIN, BTN3_PIN, 0, false, false}, + {CH4_PIN, BTN4_PIN, 0, false, false}, +}; + +void setup() +{ + pinMode(LED_PIN, OUTPUT); + pinMode(BTN1_PIN, INPUT_PULLUP); + pinMode(BTN2_PIN, INPUT_PULLUP); + pinMode(BTN3_PIN, INPUT_PULLUP); + pinMode(BTN4_PIN, INPUT_PULLUP); + pinMode(CH1_PIN, OUTPUT); + pinMode(CH2_PIN, OUTPUT); + pinMode(CH3_PIN, OUTPUT); + pinMode(CH4_PIN, OUTPUT); + Serial.begin(115200); + + // Register the config options + hostname_id = knx.config_register_string("Hostname", 20, String("sonoff")); + type_id = knx.config_register_options("Type", type_options, SONOFF_TYPE_BASIC); + + channels[0].status_ga_id = knx.config_register_ga("Channel 1 Status GA"); + channels[1].status_ga_id = knx.config_register_ga("Channel 2 Status GA", is_4ch_or_4ch_pro); + channels[2].status_ga_id = knx.config_register_ga("Channel 3 Status GA", is_4ch_or_4ch_pro); + channels[3].status_ga_id = knx.config_register_ga("Channel 4 Status GA", is_4ch_or_4ch_pro); + + knx.callback_register("Channel 1", channel_cb, &channels[0]); + knx.callback_register("Channel 2", channel_cb, &channels[1], is_4ch_or_4ch_pro); + knx.callback_register("Channel 3", channel_cb, &channels[2], is_4ch_or_4ch_pro); + knx.callback_register("Channel 4", channel_cb, &channels[3], is_4ch_or_4ch_pro); + + knx.feedback_register_bool("Channel 1 is on", &(channels[0].state)); + knx.feedback_register_action("Toogle channel 1", toggle_chan, &channels[0]); + knx.feedback_register_bool("Channel 2 is on", &(channels[1].state), is_4ch_or_4ch_pro); + knx.feedback_register_action("Toogle channel 2", toggle_chan, &channels[1], is_4ch_or_4ch_pro); + knx.feedback_register_bool("Channel 3 is on", &(channels[2].state), is_4ch_or_4ch_pro); + knx.feedback_register_action("Toogle channel 3", toggle_chan, &channels[2], is_4ch_or_4ch_pro); + knx.feedback_register_bool("Channel 4 is on", &(channels[3].state), is_4ch_or_4ch_pro); + knx.feedback_register_action("Toogle channel 4", toggle_chan, &channels[3], is_4ch_or_4ch_pro); + + knx.load(); + + // Init WiFi + WiFi.hostname(knx.config_get_string(hostname_id)); + WiFi.begin(ssid, pass); + + Serial.println(""); + Serial.print("[Connecting]"); + Serial.print(ssid); + + digitalWrite(LED_PIN, LOW); + while (WiFi.status() != WL_CONNECTED) { + digitalWrite(LED_PIN, HIGH); + delay(500); + Serial.print("."); + digitalWrite(LED_PIN, LOW); + } + digitalWrite(LED_PIN, HIGH); + + // Start knx + knx.start(); + + Serial.println(); + Serial.println("Connected to wifi"); + Serial.println(WiFi.localIP()); +} + +void loop() +{ + knx.loop(); + + // Check local buttons + check_button(&channels[0]); + if (is_4ch_or_4ch_pro()) + { + check_button(&channels[1]); + check_button(&channels[2]); + check_button(&channels[3]); + } + + delay(50); +} + +bool is_basic_or_s20() +{ + uint8_t type = knx.config_get_options(type_id); + return type == SONOFF_TYPE_BASIC || type == SONOFF_TYPE_S20; +} + +bool is_4ch_or_4ch_pro() +{ + uint8_t type = knx.config_get_options(type_id); + return type == SONOFF_TYPE_4CH ||type == SONOFF_TYPE_4CH_PRO; +} + +void check_button(sonoff_channel_t *chan) +{ + bool state_now = digitalRead(chan->btn_pin) == HIGH ? true : false; + if (state_now != chan->last_btn_state && state_now == LOW) + { + chan->state = !chan->state; + digitalWrite(chan->pin, chan->state ? HIGH : LOW); + knx.write_1bit(knx.config_get_ga(chan->status_ga_id), chan->state); + } + chan->last_btn_state = state_now; +} + +void toggle_chan(void *arg) +{ + sonoff_channel_t *chan = (sonoff_channel_t *)arg; + chan->state = !chan->state; + digitalWrite(chan->pin, chan->state ? HIGH : LOW); + knx.write_1bit(knx.config_get_ga(chan->status_ga_id), chan->state); +} + +void channel_cb(message_t const &msg, void *arg) +{ + sonoff_channel_t *chan = (sonoff_channel_t *)arg; + switch (msg.ct) + { + case KNX_CT_WRITE: + chan->state = msg.data[0]; + Serial.println(chan->state ? "Toggle on" : "Toggle off"); + digitalWrite(chan->pin, chan->state ? HIGH : LOW); + knx.write_1bit(knx.config_get_ga(chan->status_ga_id), chan->state); + break; + case KNX_CT_READ: + knx.answer_1bit(msg.received_on, chan->state); + } +} diff --git a/lib/esp-knx-ip-0.5.0/examples/static-config/static-config.ino b/lib/esp-knx-ip-0.5.0/examples/static-config/static-config.ino new file mode 100644 index 000000000..bea5093f3 --- /dev/null +++ b/lib/esp-knx-ip-0.5.0/examples/static-config/static-config.ino @@ -0,0 +1,142 @@ +/* + * This is an example showing a simple environment sensor based on a BME280 attached via I2C. + * It shows, how the library can used to statically configure a device without a webserver for config. + * This sketch was tested on a WeMos D1 mini + */ + +#include +#include + +// WiFi config here +const char* ssid = "myssid"; +const char* pass = "mypassword"; + +#define LED_PIN D4 +#define UPDATE_INTERVAL 10000 + +unsigned long next_change = 0; + +float last_temp = 0.0; +float last_hum = 0.0; +float last_pres = 0.0; + +Adafruit_BME280 bme; + +// Group addresses to send to (1/1/1, 1/1/2 and 1/1/3) +address_t temp_ga = knx.GA_to_address(1, 1, 1); +address_t hum_ga = knx.GA_to_address(1, 1, 2); +address_t pres_ga = knx.GA_to_address(1, 1, 3); + +void setup() { + pinMode(LED_PIN, OUTPUT); + Serial.begin(115200); + + callback_id_t temp_cb = knx.callback_register("Read Temperature", temp_cb); + callback_id_t hum_cb =knx.callback_register("Read Humidity", hum_cb); + callback_id_t pres_cb =knx.callback_register("Read Pressure", pres_cb); + + // Assign callbacks to group addresses (2/1/1, 2/1/2, 2/1/3) + knx.callback_assign(temp_cb, knx.GA_to_address(2, 1, 1)); + knx.callback_assign(hum_cb, knx.GA_to_address(2, 1, 2)); + knx.callback_assign(pres_cb, knx.GA_to_address(2, 1, 3)); + + // Set physical address (1.1.1) + knx.physical_address_set(knx.PA_to_address(1, 1, 1)); + + // Do not call knx.load() for static config, it will try to load config from EEPROM which we don't have here + + // Init sensor + if (!bme.begin(0x76)) { + Serial.println("Could not find a valid BME280 sensor, check wiring!"); + } + + // Init WiFi + WiFi.hostname("env"); + WiFi.begin(ssid, pass); + + Serial.println(""); + Serial.print("[Connecting]"); + Serial.print(ssid); + + digitalWrite(LED_PIN, LOW); + while (WiFi.status() != WL_CONNECTED) { + digitalWrite(LED_PIN, HIGH); + delay(250); + Serial.print("."); + digitalWrite(LED_PIN, LOW); + delay(250); + } + digitalWrite(LED_PIN, HIGH); + + // Start knx, disable webserver by passing nullptr + knx.start(nullptr); + + Serial.println(); + Serial.println("Connected to wifi"); + Serial.println(WiFi.localIP()); +} + +void loop() { + knx.loop(); + + unsigned long now = millis(); + + if (next_change < now) + { + next_change = now + UPDATE_INTERVAL; + + last_temp = bme.readTemperature(); + last_hum = bme.readHumidity(); + last_pres = bme.readPressure()/100.0f; + + Serial.print("T: "); + Serial.print(last_temp); + Serial.print("°C H: "); + Serial.print(last_hum); + Serial.print("% P: "); + Serial.print(last_pres); + Serial.println("hPa"); + + knx.write_2byte_float(temp_ga, last_temp); + knx.write_2byte_float(hum_ga, last_hum); + knx.write_2byte_float(pres_ga, last_pres); + } + + delay(50); +} + +void temp_cb(message_t const &msg, void *arg) +{ + switch (msg.ct) + { + case KNX_CT_READ: + { + knx.answer_2byte_float(msg.received_on, last_temp); + break; + } + } +} + +void hum_cb(message_t const &msg, void *arg) +{ + switch (msg.ct) + { + case KNX_CT_READ: + { + knx.answer_2byte_float(msg.received_on, last_hum); + break; + } + } +} + +void pres_cb(message_t const &msg, void *arg) +{ + switch (msg.ct) + { + case KNX_CT_READ: + { + knx.answer_2byte_float(msg.received_on, last_pres); + break; + } + } +} diff --git a/lib/esp-knx-ip-0.5.0/keywords.txt b/lib/esp-knx-ip-0.5.0/keywords.txt new file mode 100644 index 000000000..bc4989bd4 --- /dev/null +++ b/lib/esp-knx-ip-0.5.0/keywords.txt @@ -0,0 +1,104 @@ +# datatypes +address_t DATA_TYPE +message_t DATA_TYPE +callback_id_t DATA_TYPE +callback_assignment_id_t DATA_TYPE +option_entry_t DATA_TYPE +config_id_t DATA_TYPE +enable_condition_t DATA_TYPE +callback_fptr_t DATA_TYPE +feedback_action_fptr_t DATA_TYPE +knx_command_type_t DATA_TYPE + +# methods +setup KEYWORD2 +loop KEYWORD2 +GA_to_address KEYWORD2 +PA_to_address KEYWORD2 +callback_register KEYWORD2 +callback_assign KEYWORD2 +callback_deregister KEYWORD2 +callback_unassign KEYWORD2 +physical_address_set KEYWORD2 +physical_address_get KEYWORD2 +config_register_string KEYWORD2 +config_register_int KEYWORD2 +config_register_bool KEYWORD2 +config_register_options KEYWORD2 +config_register_ga KEYWORD2 +config_get_string KEYWORD2 +config_get_int KEYWORD2 +config_get_bool KEYWORD2 +config_get_options KEYWORD2 +config_get_ga KEYWORD2 +config_set_string KEYWORD2 +config_set_int KEYWORD2 +config_set_bool KEYWORD2 +config_set_options KEYWORD2 +config_set_ga KEYWORD2 +feedback_register_int KEYWORD2 +feedback_register_float KEYWORD2 +feedback_register_bool KEYWORD2 +feedback_register_action KEYWORD2 +send_1bit KEYWORD2 +send_2bit KEYWORD2 +send_4bit KEYWORD2 +send_1byte_int KEYWORD2 +send_1byte_uint KEYWORD2 +send_2byte_int KEYWORD2 +send_2byte_uint KEYWORD2 +send_2byte_float KEYWORD2 +send_3byte_time KEYWORD2 +send_3byte_time KEYWORD2 +send_3byte_date KEYWORD2 +send_3byte_date KEYWORD2 +send_3byte_color KEYWORD2 +send_3byte_color KEYWORD2 +send_4byte_int KEYWORD2 +send_4byte_uint KEYWORD2 +send_4byte_float KEYWORD2 +write_1bit KEYWORD2 +write_2bit KEYWORD2 +write_4bit KEYWORD2 +write_1byte_int KEYWORD2 +write_1byte_uint KEYWORD2 +write_2byte_int KEYWORD2 +write_2byte_uint KEYWORD2 +write_2byte_float KEYWORD2 +write_3byte_time KEYWORD2 +write_3byte_time KEYWORD2 +write_3byte_date KEYWORD2 +write_3byte_date KEYWORD2 +write_3byte_color KEYWORD2 +write_3byte_color KEYWORD2 +write_4byte_int KEYWORD2 +write_4byte_uint KEYWORD2 +write_4byte_float KEYWORD2 +answer_1bit KEYWORD2 +answer_2bit KEYWORD2 +answer_4bit KEYWORD2 +answer_1byte_int KEYWORD2 +answer_1byte_uint KEYWORD2 +answer_2byte_int KEYWORD2 +answer_2byte_uint KEYWORD2 +answer_2byte_float KEYWORD2 +answer_3byte_time KEYWORD2 +answer_3byte_time KEYWORD2 +answer_3byte_date KEYWORD2 +answer_3byte_date KEYWORD2 +answer_3byte_color KEYWORD2 +answer_3byte_color KEYWORD2 +answer_4byte_int KEYWORD2 +answer_4byte_uint KEYWORD2 +answer_4byte_float KEYWORD2 + +data_to_1byte_int KEYWORD 2 +data_to_2byte_int KEYWORD 2 +data_to_2byte_float KEYWORD 2 +data_to_4byte_float KEYWORD 2 +data_to_3byte_color KEYWORD 2 +data_to_3byte_time KEYWORD 2 +data_to_3byte_data KEYWORD 2 + +# constants +knx LITERAL1 \ No newline at end of file diff --git a/lib/esp-knx-ip-0.5.0/library.properties b/lib/esp-knx-ip-0.5.0/library.properties new file mode 100644 index 000000000..57cad993c --- /dev/null +++ b/lib/esp-knx-ip-0.5.0/library.properties @@ -0,0 +1,10 @@ +name=ESP KNX IP Library +version=0.5 +author=Nico Weichbrodt +maintainer=Nico Weichbrodt +sentence=ESP8266 library for KNX/IP communication. +paragraph=Build your own IoT devices with KNX/IP connectivity! +category=Communication +url=https://github.com/envy/esp-knx-ip +architectures=esp8266 +includes=esp-knx-ip.h diff --git a/lib/esp-mqtt-arduino-1.0.1.02.1/.gitignore b/lib/esp-mqtt-arduino-1.0.1.02.1/.gitignore new file mode 100644 index 000000000..2ee75414c --- /dev/null +++ b/lib/esp-mqtt-arduino-1.0.1.02.1/.gitignore @@ -0,0 +1,28 @@ +# C++ objects and libs + +*.slo +*.lo +*.o +#*.a +*.la +*.lai +*.so +*.dll +*.dylib + +#Makefile +*-build-* +build-* +*.autosave + +# .log files (usually created by QtTest - thanks to VestniK) +*.log + + +# Editors temporary files +*~ + + +#OSX +.DS_Store +._* diff --git a/lib/esp-mqtt-arduino-1.0.1.02.1/README.md b/lib/esp-mqtt-arduino-1.0.1.02.1/README.md new file mode 100644 index 000000000..a7ddbecac --- /dev/null +++ b/lib/esp-mqtt-arduino-1.0.1.02.1/README.md @@ -0,0 +1,15 @@ +MQTT +==== + +A Wrapper around mqtt for Arduino to be used with esp8266 modules. + +It wraps a slightly modified version of mqtt for esp8266 ported by Tuan PM. +Original code for esp: https://github.com/tuanpmt/esp_mqtt +Original code for contiki: https://github.com/esar/contiki-mqtt + + +==== + +**secure libssl:** + +If you want to use secure communication, please use the `secure`-branch! diff --git a/lib/esp-mqtt-arduino-1.0.1.02.1/examples/mqtt_pub/mqtt_pub.ino b/lib/esp-mqtt-arduino-1.0.1.02.1/examples/mqtt_pub/mqtt_pub.ino new file mode 100644 index 000000000..17b3be8db --- /dev/null +++ b/lib/esp-mqtt-arduino-1.0.1.02.1/examples/mqtt_pub/mqtt_pub.ino @@ -0,0 +1,102 @@ +#include +#include + +void myDataCb(String& topic, String& data); +void myPublishedCb(); +void myDisconnectedCb(); +void myConnectedCb(); + +#define CLIENT_ID "client1" + +// create MQTT object +MQTT myMqtt(CLIENT_ID, "192.168.0.1", 1883); + +// +const char* ssid = "ssid"; +const char* password = "ssid_password"; + + +// +void setup() { + Serial.begin(115200); + delay(1000); + + Serial.println(); + Serial.println(); + Serial.print("Connecting to "); + Serial.println(ssid); + + WiFi.begin(ssid, password); + + while (WiFi.status() != WL_CONNECTED) { + delay(500); + Serial.print("."); + } + + Serial.println(""); + Serial.println("WiFi connected"); + Serial.println("IP address: "); + Serial.println(WiFi.localIP()); + + Serial.println("Connecting to MQTT server"); + + // setup callbacks + myMqtt.onConnected(myConnectedCb); + myMqtt.onDisconnected(myDisconnectedCb); + myMqtt.onPublished(myPublishedCb); + myMqtt.onData(myDataCb); + + Serial.println("connect mqtt..."); + myMqtt.connect(); + + delay(10); +} + +// +void loop() { + + int value = analogRead(A0); + + String topic("/"); + topic += CLIENT_ID; + topic += "/value"; + + String valueStr(value); + + // publish value to topic + boolean result = myMqtt.publish(topic, valueStr); + + delay(1000); +} + + +/* + * + */ +void myConnectedCb() +{ + Serial.println("connected to MQTT server"); +} + +void myDisconnectedCb() +{ + Serial.println("disconnected. try to reconnect..."); + delay(500); + myMqtt.connect(); +} + +void myPublishedCb() +{ + //Serial.println("published."); +} + +void myDataCb(String& topic, String& data) +{ + + Serial.print(topic); + Serial.print(": "); + Serial.println(data); +} + + + diff --git a/lib/esp-mqtt-arduino-1.0.1.02.1/examples/mqtt_sub/mqtt_sub.ino b/lib/esp-mqtt-arduino-1.0.1.02.1/examples/mqtt_sub/mqtt_sub.ino new file mode 100644 index 000000000..1f7591617 --- /dev/null +++ b/lib/esp-mqtt-arduino-1.0.1.02.1/examples/mqtt_sub/mqtt_sub.ino @@ -0,0 +1,95 @@ +#include +#include + +void myDataCb(String& topic, String& data); +void myPublishedCb(); +void myDisconnectedCb(); +void myConnectedCb(); + +#define CLIENT_ID "client3" +#define TOPIC "/client1/value" + + +// create MQTT +MQTT myMqtt(CLIENT_ID, "192.168.0.1", 1883); + + +const char* ssid = "ssid"; +const char* password = "ssid_password"; + + +// +void setup() { + Serial.begin(115200); + delay(1000); + + Serial.println(); + Serial.println(); + Serial.print("Connecting to "); + Serial.println(ssid); + + WiFi.begin(ssid, password); + + while (WiFi.status() != WL_CONNECTED) { + delay(500); + Serial.print("."); + } + + Serial.println(""); + Serial.println("WiFi connected"); + Serial.println("IP address: "); + Serial.println(WiFi.localIP()); + + + Serial.println("Connecting to MQTT server"); + + // setup callbacks + myMqtt.onConnected(myConnectedCb); + myMqtt.onDisconnected(myDisconnectedCb); + myMqtt.onPublished(myPublishedCb); + myMqtt.onData(myDataCb); + + Serial.println("connect mqtt..."); + myMqtt.connect(); + + Serial.println("subscribe to topic..."); + myMqtt.subscribe(TOPIC); + + delay(10); +} + +// +void loop() { +} + + +/* + * + */ +void myConnectedCb() +{ + Serial.println("connected to MQTT server"); +} + +void myDisconnectedCb() +{ + Serial.println("disconnected. try to reconnect..."); + delay(500); + myMqtt.connect(); +} + +void myPublishedCb() +{ + //Serial.println("published."); +} + +void myDataCb(String& topic, String& data) +{ + + Serial.print(topic); + Serial.print(": "); + Serial.println(data); +} + + + diff --git a/lib/esp-mqtt-arduino-1.0.1.02.1/keywords.txt b/lib/esp-mqtt-arduino-1.0.1.02.1/keywords.txt new file mode 100644 index 000000000..527b5bf0c --- /dev/null +++ b/lib/esp-mqtt-arduino-1.0.1.02.1/keywords.txt @@ -0,0 +1,43 @@ +####################################### +# Syntax Coloring Map For Test +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +MQTT.h KEYWORD1 + +MQTT KEYWORD1 + + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +setClientId KEYWORD2 +setUserPwd KEYWORD2 + +connect KEYWORD2 +disconnect KEYWORD2 +isConnected KEYWORD2 + +publish KEYWORD2 +subscribe KEYWORD2 + +getState KEYWORD2 + +#general +onConnected KEYWORD2 +onDisconnected KEYWORD2 +onPublished KEYWORD2 +onData KEYWORD2 + +####################################### +# Instances (KEYWORD2) +####################################### + +####################################### +# Constants (LITERAL1) +####################################### + diff --git a/lib/esp-mqtt-arduino-1.0.1.02.1/library.properties b/lib/esp-mqtt-arduino-1.0.1.02.1/library.properties new file mode 100644 index 000000000..110da0ac4 --- /dev/null +++ b/lib/esp-mqtt-arduino-1.0.1.02.1/library.properties @@ -0,0 +1,9 @@ +name=ESP MQTT +version=1.0.1 +author=Ingo Randolf +maintainer=Ingo Randolf +sentence=A Wrapper around mqtt for Arduino to be used with esp8266 modules. +paragraph=It wraps a slightly modified version of mqtt for esp8266 ported by Tuan PM. Original code for esp: https://github.com/tuanpmt/esp_mqtt (7ec2ef8e1df0422b77348fe1da7885568e0c9d01) Original code for contiki: https://github.com/esar/contiki-mqtt +category=Communication +url=https://github.com/i-n-g-o/esp-mqtt-arduino +architectures=esp8266 \ No newline at end of file diff --git a/lib/esp-mqtt-arduino-1.0.1.02.1/src/MQTT.cpp b/lib/esp-mqtt-arduino-1.0.1.02.1/src/MQTT.cpp new file mode 100644 index 000000000..b330bad4b --- /dev/null +++ b/lib/esp-mqtt-arduino-1.0.1.02.1/src/MQTT.cpp @@ -0,0 +1,269 @@ +/*//------------------------------------------------------------------------------- + * MQTT.cpp + * + * Implementation file for MQTT Wrapper + * + * Wrapper for Arduino written by Ingo Randolf during + * eTextiles Summercamp 2015. + * + * This library is intended to be used with esp8266 modules. + * + * + * This class wraps a slightly modified version of mqtt + * for esp8266 written by Tuan PM. + * Original code: https://github.com/tuanpmt/esp_mqtt + * + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + //-------------------------------------------------------------------------------*/ +#include "MQTT.h" + +#include "user_interface.h" +#include "osapi.h" +#include "os_type.h" +#include "mqtt/debug.h" + + +//------------------------------------------------------------------------------------ +// mqtt internal callbacks +//------------------------------------------------------------------------------------ +static void mqttConnectedCb(uint32_t *args) +{ + MQTT_Client* client = (MQTT_Client*)args; + + MQTT* _this = (MQTT*)client->user_data; + + if (_this && _this->onMqttConnectedCb) { + _this->onMqttConnectedCb(); + } +} + +static void mqttDisconnectedCb(uint32_t *args) +{ + MQTT_Client* client = (MQTT_Client*)args; + + MQTT* _this = (MQTT*)client->user_data; + + if (_this && _this->onMqttDisconnectedCb) { + _this->onMqttDisconnectedCb(); + } +} + +static void mqttPublishedCb(uint32_t *args) +{ + MQTT_Client* client = (MQTT_Client*)args; + + MQTT* _this = (MQTT*)client->user_data; + + if (_this && _this->onMqttPublishedCb) { + _this->onMqttPublishedCb(); + } +} + +static void mqttDataCb(uint32_t *args, const char* topic, uint32_t topic_len, const char *data, uint32_t data_len) +{ + MQTT_Client* client = (MQTT_Client*)args; + + MQTT* _this = (MQTT*)client->user_data; + + if (_this) { + + _this->_onMqttDataCb(topic, topic_len, data, data_len); + } +} + +static void mqttTimeoutCb(uint32_t *args) +{ + MQTT_Client* client = (MQTT_Client*)args; + + MQTT* _this = (MQTT*)client->user_data; + +// if (_this && _this->onMqttTimeoutCb) { +// _this->onMqttTimeoutCb(); +// } +} + + +//------------------------------------------------------------------------------------ +// MQTT class implementation +//------------------------------------------------------------------------------------ + +//MQTT::MQTT(const char* client_id, const char* host, uint32_t port) : +MQTT::MQTT(const char* client_id, const char* host, uint32_t port, const char* willTopic, uint8_t willQos, boolean willRetain, const char* willMessage) : + onMqttConnectedCb(0) + ,onMqttDisconnectedCb(0) + ,onMqttPublishedCb(0) + ,onMqttDataCb(0) + ,onMqttDataRawCb(0) +{ + // init connections + MQTT_InitConnection(&mqttClient, (uint8_t*)host, port, 0); + + // init client + if ( !MQTT_InitClient(&mqttClient, (uint8_t*)client_id, (uint8_t*)"", (uint8_t*)"", 15, 1) ) { + MQTT_INFO("Failed to initialize properly. Check MQTT version.\r\n"); + } + + // init LWT +// MQTT_InitLWT(&mqttClient, (uint8_t*)"/lwt", (uint8_t*)"offline", 0, 0); + MQTT_InitLWT(&mqttClient, (uint8_t*)willTopic, (uint8_t*)willMessage, willQos, (uint8_t)willRetain); + + // set user data + mqttClient.user_data = (void*)this; + + // setup callbacks + MQTT_OnConnected(&mqttClient, mqttConnectedCb); + MQTT_OnDisconnected(&mqttClient, mqttDisconnectedCb); + MQTT_OnPublished(&mqttClient, mqttPublishedCb); + MQTT_OnData(&mqttClient, mqttDataCb); + + MQTT_OnTimeout(&mqttClient, mqttTimeoutCb); +} + + +MQTT::~MQTT() +{ + MQTT_DeleteClient(&mqttClient); +} + + +/* + */ +void MQTT::setClientId(const char* client_id) +{ + MQTT_SetUserId(&mqttClient, client_id); +} + +void MQTT::setUserPwd(const char* user, const char* pwd) +{ + MQTT_SetUserPwd(&mqttClient, user, pwd); +} + + +/* + */ +void MQTT::connect() +{ + MQTT_Connect(&mqttClient); +} + +void MQTT::disconnect() +{ + MQTT_Disconnect(&mqttClient); +} + +bool MQTT::isConnected() +{ + return (mqttClient.connState >= TCP_CONNECTED); +} + +/* + */ +bool MQTT::publish(const char* topic, const char* buf, uint32_t buf_len, int qos, int retain) +{ + return MQTT_Publish(&mqttClient, topic, buf, buf_len, qos, retain); +} + +bool MQTT::publish(String& topic, String& data, int qos, int retain) +{ + return publish(topic.c_str(), data.c_str(), data.length(), qos, retain); +} + +bool MQTT::publish(String& topic, const char* buf, uint32_t buf_len, int qos, int retain) +{ + return publish(topic.c_str(), buf, buf_len, qos, retain); +} + +bool MQTT::publish(const char* topic, String& data, int qos, int retain) +{ + return publish(topic, data.c_str(), data.length(), qos, retain); +} + + +/* + */ +bool MQTT::subscribe(const char* topic, uint8_t qos) +{ + return MQTT_Subscribe(&mqttClient, (char*)topic, qos); +} + +bool MQTT::subscribe(const String& topic, uint8_t qos) +{ + return MQTT_Subscribe(&mqttClient, (char*)topic.c_str(), qos); +} + + + +//------------------------------------------------------------------------------- +// set user callback functions +//------------------------------------------------------------------------------- +void MQTT::onConnected( void (*function)(void) ) +{ + onMqttConnectedCb = function; +} + +void MQTT::onDisconnected( void (*function)(void) ) +{ + onMqttDisconnectedCb = function; +} + +void MQTT::onPublished( void (*function)(void) ) +{ + onMqttPublishedCb = function; +} + +void MQTT::onData( void (*function)(String&, String&) ) +{ + onMqttDataCb = function; +} + +void MQTT::onData( void (*function)(const char*, uint32_t, const char*, uint32_t) ) +{ + onMqttDataRawCb = function; +} + + +// internal callback, calling user CB +void MQTT::_onMqttDataCb(const char* topic, uint32_t topic_len, const char* buf, uint32_t buf_len) +{ + if (onMqttDataRawCb) { + onMqttDataRawCb(topic, topic_len, buf, buf_len); + } + + if (onMqttDataCb) { + + char* topicCpy = (char*)malloc(topic_len+1); + memcpy(topicCpy, topic, topic_len); + topicCpy[topic_len] = 0; + // string it + String topicStr(topicCpy); + + char* bufCpy = (char*)malloc(buf_len+1); + memcpy(bufCpy, buf, buf_len); + bufCpy[buf_len] = 0; + // string it + String bufStr(bufCpy); + + onMqttDataCb(topicStr, bufStr); + + free(topicCpy); + free(bufCpy); + } +} + + + + + + + + + diff --git a/lib/esp-mqtt-arduino-1.0.1.02.1/src/MQTT.h b/lib/esp-mqtt-arduino-1.0.1.02.1/src/MQTT.h new file mode 100644 index 000000000..8838ef482 --- /dev/null +++ b/lib/esp-mqtt-arduino-1.0.1.02.1/src/MQTT.h @@ -0,0 +1,93 @@ +/*//------------------------------------------------------------------------------- + * MQTT.h + * + * Header file for MQTT Wrapper + * + * Wrapper for Arduino written by Ingo Randolf during + * eTextiles Summercamp 2015. + * + * This library is intended to be used with esp8266 modules. + * + * + * This class wraps a slightly modified version of mqtt + * for esp8266 written by Tuan PM. + * Original code: https://github.com/tuanpmt/esp_mqtt + * + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + //-------------------------------------------------------------------------------*/ +#ifndef MQTT_WRAPPER_H +#define MQTT_WRAPPER_H + +#include + +#include +#include +#include +#include +#include + +extern "C" { + #include + #include "mqtt/mqtt.h" +} + +class MQTT +{ +public: +// MQTT(const char* client_id, const char* host, uint32_t port); + MQTT(const char* client_id, const char* host, uint32_t port, const char* willTopic, uint8_t willQos, boolean willRetain, const char* willMessage); + + ~MQTT(); + + void setClientId(const char* client_id); + void setUserPwd(const char* user, const char* pwd); + + void connect(); + void disconnect(); + bool isConnected(); + + bool publish(const char* topic, const char* buf, uint32_t buf_len, int qos = 0, int retain = 0); + bool publish(String& topic, String& data, int qos = 0, int retain = 0); + bool publish(String& topic, const char* buf, uint32_t buf_len, int qos = 0, int retain = 0); + bool publish(const char* topic, String& data, int qos = 0, int retain = 0); + + bool subscribe(const char* topic, uint8_t qos = 0); + bool subscribe(const String& topic, uint8_t qos = 0); + + int getState() { return mqttClient.connState; }; + + // set callbacks + void onConnected( void (*)(void) ); + void onDisconnected( void (*)(void) ); + void onPublished( void (*)(void) ); + void onData( void (*)(String&, String&) ); + void onData( void (*)(const char*, uint32_t, const char*, uint32_t) ); + + // user callbacks + void (*onMqttConnectedCb)(void); + void (*onMqttDisconnectedCb)(void); + void (*onMqttPublishedCb)(void); + void (*onMqttDataCb) (String&, String&); + void (*onMqttDataRawCb) (const char*, uint32_t, const char*, uint32_t); + + // internal callback + void _onMqttDataCb(const char*, uint32_t, const char*, uint32_t); + +private: + MQTT_Client mqttClient; + +}; + + + + +#endif \ No newline at end of file diff --git a/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/debug.h b/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/debug.h new file mode 100644 index 000000000..f45dd6d8d --- /dev/null +++ b/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/debug.h @@ -0,0 +1,19 @@ +/* + * debug.h + * + * Created on: Dec 4, 2014 + * Author: Minh + */ + +#ifndef USER_DEBUG_H_ +#define USER_DEBUG_H_ + + +#if defined(MQTT_DEBUG_ON) +#define MQTT_INFO( format, ... ) os_printf( format, ## __VA_ARGS__ ) +#else +#define MQTT_INFO( format, ... ) +#endif + + +#endif /* USER_DEBUG_H_ */ diff --git a/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/mqtt.c b/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/mqtt.c new file mode 100644 index 000000000..ed63d713a --- /dev/null +++ b/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/mqtt.c @@ -0,0 +1,1048 @@ +/* mqtt.c +* Protocol: http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html +* +* Copyright (c) 2014-2015, Tuan PM +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* +* * Redistributions of source code must retain the above copyright notice, +* this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of Redis nor the names of its contributors may be used +* to endorse or promote products derived from this software without +* specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +* POSSIBILITY OF SUCH DAMAGE. +*/ + +#include "user_interface.h" +#include "osapi.h" +#include "espconn.h" +#include "os_type.h" +#include "mem.h" +#include "mqtt_msg.h" +#include "debug.h" +#include "user_config.h" +#include "mqtt.h" +#include "queue.h" + +#define MQTT_TASK_PRIO 1 +#define MQTT_TASK_QUEUE_SIZE 1 +#define MQTT_SEND_TIMOUT 5 + +#ifndef MQTT_SSL_SIZE +#define MQTT_SSL_SIZE 5120 +#endif + +#ifndef QUEUE_BUFFER_SIZE +#define QUEUE_BUFFER_SIZE 2048 +#endif + + +os_event_t mqtt_procTaskQueue[MQTT_TASK_QUEUE_SIZE]; + +#ifdef PROTOCOL_NAMEv311 +LOCAL uint8_t zero_len_id[2] = { 0, 0 }; +#endif + +LOCAL void ICACHE_FLASH_ATTR +mqtt_dns_found(const char *name, ip_addr_t *ipaddr, void *arg) +{ + struct espconn *pConn = (struct espconn *)arg; + MQTT_Client* client = (MQTT_Client *)pConn->reverse; + + + if (ipaddr == NULL) + { + MQTT_INFO("DNS: Found, but got no ip, try to reconnect\r\n"); + client->connState = TCP_RECONNECT_REQ; + return; + } + + MQTT_INFO("DNS: found ip %d.%d.%d.%d\n", + *((uint8 *) &ipaddr->addr), + *((uint8 *) &ipaddr->addr + 1), + *((uint8 *) &ipaddr->addr + 2), + *((uint8 *) &ipaddr->addr + 3)); + + if (client->ip.addr == 0 && ipaddr->addr != 0) + { + os_memcpy(client->pCon->proto.tcp->remote_ip, &ipaddr->addr, 4); + if (client->security) { +#ifdef MQTT_SSL_ENABLE + espconn_secure_set_size(ESPCONN_CLIENT, MQTT_SSL_SIZE); + espconn_secure_connect(client->pCon); +#else + MQTT_INFO("TCP: Do not support SSL\r\n"); +#endif + } + else { + espconn_connect(client->pCon); + } + + client->connState = TCP_CONNECTING; + MQTT_INFO("TCP: connecting...\r\n"); + } + + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); +} + + + +LOCAL void ICACHE_FLASH_ATTR +deliver_publish(MQTT_Client* client, uint8_t* message, int length) +{ + mqtt_event_data_t event_data; + + event_data.topic_length = length; + event_data.topic = mqtt_get_publish_topic(message, &event_data.topic_length); + event_data.data_length = length; + event_data.data = mqtt_get_publish_data(message, &event_data.data_length); + + if (client->dataCb) + client->dataCb((uint32_t*)client, event_data.topic, event_data.topic_length, event_data.data, event_data.data_length); + +} + +void ICACHE_FLASH_ATTR +mqtt_send_keepalive(MQTT_Client *client) +{ + MQTT_INFO("\r\nMQTT: Send keepalive packet to %s:%d!\r\n", client->host, client->port); + client->mqtt_state.outbound_message = mqtt_msg_pingreq(&client->mqtt_state.mqtt_connection); + client->mqtt_state.pending_msg_type = MQTT_MSG_TYPE_PINGREQ; + client->mqtt_state.pending_msg_type = mqtt_get_type(client->mqtt_state.outbound_message->data); + client->mqtt_state.pending_msg_id = mqtt_get_id(client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length); + + + client->sendTimeout = MQTT_SEND_TIMOUT; + MQTT_INFO("MQTT: Sending, type: %d, id: %04X\r\n", client->mqtt_state.pending_msg_type, client->mqtt_state.pending_msg_id); + err_t result = ESPCONN_OK; + if (client->security) { +#ifdef MQTT_SSL_ENABLE + result = espconn_secure_send(client->pCon, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length); +#else + MQTT_INFO("TCP: Do not support SSL\r\n"); +#endif + } + else { + result = espconn_send(client->pCon, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length); + } + + client->mqtt_state.outbound_message = NULL; + if (ESPCONN_OK == result) { + client->keepAliveTick = 0; + client->connState = MQTT_DATA; + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); + } + else { + client->connState = TCP_RECONNECT_DISCONNECTING; + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); + } +} + +/** + * @brief Delete tcp client and free all memory + * @param mqttClient: The mqtt client which contain TCP client + * @retval None + */ +void ICACHE_FLASH_ATTR +mqtt_tcpclient_delete(MQTT_Client *mqttClient) +{ + if (mqttClient->pCon != NULL) { + MQTT_INFO("TCP: Free memory\r\n"); + // Force abort connections + espconn_abort(mqttClient->pCon); + // Delete connections + espconn_delete(mqttClient->pCon); + + if (mqttClient->pCon->proto.tcp) { + os_free(mqttClient->pCon->proto.tcp); + mqttClient->pCon->proto.tcp = NULL; + } + os_free(mqttClient->pCon); + mqttClient->pCon = NULL; + } +} + +/** + * @brief Delete MQTT client and free all memory + * @param mqttClient: The mqtt client + * @retval None + */ +void ICACHE_FLASH_ATTR +mqtt_client_delete(MQTT_Client *mqttClient) +{ + if (mqttClient == NULL) + return; + + if (mqttClient->pCon != NULL) { + mqtt_tcpclient_delete(mqttClient); + } + + if (mqttClient->host != NULL) { + os_free(mqttClient->host); + mqttClient->host = NULL; + } + + if (mqttClient->user_data != NULL) { + os_free(mqttClient->user_data); + mqttClient->user_data = NULL; + } + + if (mqttClient->mqtt_state.in_buffer != NULL) { + os_free(mqttClient->mqtt_state.in_buffer); + mqttClient->mqtt_state.in_buffer = NULL; + } + + if (mqttClient->mqtt_state.out_buffer != NULL) { + os_free(mqttClient->mqtt_state.out_buffer); + mqttClient->mqtt_state.out_buffer = NULL; + } + + if (mqttClient->mqtt_state.outbound_message != NULL) { + if (mqttClient->mqtt_state.outbound_message->data != NULL) + { + os_free(mqttClient->mqtt_state.outbound_message->data); + mqttClient->mqtt_state.outbound_message->data = NULL; + } + } + + if (mqttClient->mqtt_state.mqtt_connection.buffer != NULL) { + // Already freed but not NULL + mqttClient->mqtt_state.mqtt_connection.buffer = NULL; + } + + if (mqttClient->connect_info.client_id != NULL) { +#ifdef PROTOCOL_NAMEv311 + /* Don't attempt to free if it's the zero_len array */ + if ( ((uint8_t*)mqttClient->connect_info.client_id) != zero_len_id ) + os_free(mqttClient->connect_info.client_id); +#else + os_free(mqttClient->connect_info.client_id); +#endif + mqttClient->connect_info.client_id = NULL; + } + + if (mqttClient->connect_info.username != NULL) { + os_free(mqttClient->connect_info.username); + mqttClient->connect_info.username = NULL; + } + + if (mqttClient->connect_info.password != NULL) { + os_free(mqttClient->connect_info.password); + mqttClient->connect_info.password = NULL; + } + + if (mqttClient->connect_info.will_topic != NULL) { + os_free(mqttClient->connect_info.will_topic); + mqttClient->connect_info.will_topic = NULL; + } + + if (mqttClient->connect_info.will_message != NULL) { + os_free(mqttClient->connect_info.will_message); + mqttClient->connect_info.will_message = NULL; + } + + if (mqttClient->msgQueue.buf != NULL) { + os_free(mqttClient->msgQueue.buf); + mqttClient->msgQueue.buf = NULL; + } + + // Initialize state + mqttClient->connState = WIFI_INIT; + // Clear callback functions to avoid abnormal callback + mqttClient->connectedCb = NULL; + mqttClient->disconnectedCb = NULL; + mqttClient->publishedCb = NULL; + mqttClient->timeoutCb = NULL; + mqttClient->dataCb = NULL; + + MQTT_INFO("MQTT: client already deleted\r\n"); +} + + +/** + * @brief Client received callback function. + * @param arg: contain the ip link information + * @param pdata: received data + * @param len: the lenght of received data + * @retval None + */ +void ICACHE_FLASH_ATTR +mqtt_tcpclient_recv(void *arg, char *pdata, unsigned short len) +{ + uint8_t msg_type; + uint8_t msg_qos; + uint16_t msg_id; + uint8_t msg_conn_ret; + + struct espconn *pCon = (struct espconn*)arg; + MQTT_Client *client = (MQTT_Client *)pCon->reverse; + +READPACKET: + MQTT_INFO("TCP: data received %d bytes\r\n", len); + // MQTT_INFO("STATE: %d\r\n", client->connState); + if (len < MQTT_BUF_SIZE && len > 0) { + os_memcpy(client->mqtt_state.in_buffer, pdata, len); + + msg_type = mqtt_get_type(client->mqtt_state.in_buffer); + msg_qos = mqtt_get_qos(client->mqtt_state.in_buffer); + msg_id = mqtt_get_id(client->mqtt_state.in_buffer, client->mqtt_state.in_buffer_length); + switch (client->connState) { + case MQTT_CONNECT_SENDING: + if (msg_type == MQTT_MSG_TYPE_CONNACK) { + if (client->mqtt_state.pending_msg_type != MQTT_MSG_TYPE_CONNECT) { + MQTT_INFO("MQTT: Invalid packet\r\n"); + if (client->security) { +#ifdef MQTT_SSL_ENABLE + espconn_secure_disconnect(client->pCon); +#else + MQTT_INFO("TCP: Do not support SSL\r\n"); +#endif + } + else { + espconn_disconnect(client->pCon); + } + } else { + msg_conn_ret = mqtt_get_connect_return_code(client->mqtt_state.in_buffer); + switch (msg_conn_ret) { + case CONNECTION_ACCEPTED: + MQTT_INFO("MQTT: Connected to %s:%d\r\n", client->host, client->port); + client->connState = MQTT_DATA; + if (client->connectedCb) + client->connectedCb((uint32_t*)client); + break; + case CONNECTION_REFUSE_PROTOCOL: + case CONNECTION_REFUSE_SERVER_UNAVAILABLE: + case CONNECTION_REFUSE_BAD_USERNAME: + case CONNECTION_REFUSE_NOT_AUTHORIZED: + MQTT_INFO("MQTT: Connection refuse, reason code: %d\r\n", msg_conn_ret); + default: + if (client->security) { +#ifdef MQTT_SSL_ENABLE + espconn_secure_disconnect(client->pCon); +#else + MQTT_INFO("TCP: Do not support SSL\r\n"); +#endif + } + else { + espconn_disconnect(client->pCon); + } + + } + + } + + } + break; + case MQTT_DATA: + case MQTT_KEEPALIVE_SEND: + client->mqtt_state.message_length_read = len; + client->mqtt_state.message_length = mqtt_get_total_length(client->mqtt_state.in_buffer, client->mqtt_state.message_length_read); + + + switch (msg_type) + { + + case MQTT_MSG_TYPE_SUBACK: + if (client->mqtt_state.pending_msg_type == MQTT_MSG_TYPE_SUBSCRIBE && client->mqtt_state.pending_msg_id == msg_id) + MQTT_INFO("MQTT: Subscribe successful\r\n"); + break; + case MQTT_MSG_TYPE_UNSUBACK: + if (client->mqtt_state.pending_msg_type == MQTT_MSG_TYPE_UNSUBSCRIBE && client->mqtt_state.pending_msg_id == msg_id) + MQTT_INFO("MQTT: UnSubscribe successful\r\n"); + break; + case MQTT_MSG_TYPE_PUBLISH: + if (msg_qos == 1) + client->mqtt_state.outbound_message = mqtt_msg_puback(&client->mqtt_state.mqtt_connection, msg_id); + else if (msg_qos == 2) + client->mqtt_state.outbound_message = mqtt_msg_pubrec(&client->mqtt_state.mqtt_connection, msg_id); + if (msg_qos == 1 || msg_qos == 2) { + MQTT_INFO("MQTT: Queue response QoS: %d\r\n", msg_qos); + if (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) { + MQTT_INFO("MQTT: Queue full\r\n"); + } + } + + deliver_publish(client, client->mqtt_state.in_buffer, client->mqtt_state.message_length_read); + break; + case MQTT_MSG_TYPE_PUBACK: + if (client->mqtt_state.pending_msg_type == MQTT_MSG_TYPE_PUBLISH && client->mqtt_state.pending_msg_id == msg_id) { + MQTT_INFO("MQTT: received MQTT_MSG_TYPE_PUBACK, finish QoS1 publish\r\n"); + } + + break; + case MQTT_MSG_TYPE_PUBREC: + client->mqtt_state.outbound_message = mqtt_msg_pubrel(&client->mqtt_state.mqtt_connection, msg_id); + if (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) { + MQTT_INFO("MQTT: Queue full\r\n"); + } + break; + case MQTT_MSG_TYPE_PUBREL: + client->mqtt_state.outbound_message = mqtt_msg_pubcomp(&client->mqtt_state.mqtt_connection, msg_id); + if (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) { + MQTT_INFO("MQTT: Queue full\r\n"); + } + break; + case MQTT_MSG_TYPE_PUBCOMP: + if (client->mqtt_state.pending_msg_type == MQTT_MSG_TYPE_PUBLISH && client->mqtt_state.pending_msg_id == msg_id) { + MQTT_INFO("MQTT: receive MQTT_MSG_TYPE_PUBCOMP, finish QoS2 publish\r\n"); + } + break; + case MQTT_MSG_TYPE_PINGREQ: + client->mqtt_state.outbound_message = mqtt_msg_pingresp(&client->mqtt_state.mqtt_connection); + if (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) { + MQTT_INFO("MQTT: Queue full\r\n"); + } + break; + case MQTT_MSG_TYPE_PINGRESP: + // Ignore + break; + } + // NOTE: this is done down here and not in the switch case above + // because the PSOCK_READBUF_LEN() won't work inside a switch + // statement due to the way protothreads resume. + if (msg_type == MQTT_MSG_TYPE_PUBLISH) + { + len = client->mqtt_state.message_length_read; + + if (client->mqtt_state.message_length < client->mqtt_state.message_length_read) + { + //client->connState = MQTT_PUBLISH_RECV; + //Not Implement yet + len -= client->mqtt_state.message_length; + pdata += client->mqtt_state.message_length; + + MQTT_INFO("Get another published message\r\n"); + goto READPACKET; + } + + } + break; + } + } else { + MQTT_INFO("ERROR: Message too long\r\n"); + } + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); +} + +/** + * @brief Client send over callback function. + * @param arg: contain the ip link information + * @retval None + */ +void ICACHE_FLASH_ATTR +mqtt_tcpclient_sent_cb(void *arg) +{ + struct espconn *pCon = (struct espconn *)arg; + MQTT_Client* client = (MQTT_Client *)pCon->reverse; + MQTT_INFO("TCP: Sent\r\n"); + client->sendTimeout = 0; + client->keepAliveTick = 0; + + if ((client->connState == MQTT_DATA || client->connState == MQTT_KEEPALIVE_SEND) + && client->mqtt_state.pending_msg_type == MQTT_MSG_TYPE_PUBLISH) { + if (client->publishedCb) + client->publishedCb((uint32_t*)client); + } + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); +} + +void ICACHE_FLASH_ATTR mqtt_timer(void *arg) +{ + MQTT_Client* client = (MQTT_Client*)arg; + + if (client->connState == MQTT_DATA) { + client->keepAliveTick ++; + if (client->keepAliveTick > (client->mqtt_state.connect_info->keepalive / 2)) { + client->connState = MQTT_KEEPALIVE_SEND; + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); + } + + } else if (client->connState == TCP_RECONNECT_REQ) { + client->reconnectTick ++; + if (client->reconnectTick > MQTT_RECONNECT_TIMEOUT) { + client->reconnectTick = 0; + client->connState = TCP_RECONNECT; + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); + if (client->timeoutCb) + client->timeoutCb((uint32_t*)client); + } + } + if (client->sendTimeout > 0) + client->sendTimeout --; +} + +void ICACHE_FLASH_ATTR +mqtt_tcpclient_discon_cb(void *arg) +{ + + struct espconn *pespconn = (struct espconn *)arg; + MQTT_Client* client = (MQTT_Client *)pespconn->reverse; + MQTT_INFO("TCP: Disconnected callback\r\n"); + if (TCP_DISCONNECTING == client->connState) { + client->connState = TCP_DISCONNECTED; + } + else if (MQTT_DELETING == client->connState) { + client->connState = MQTT_DELETED; + } + else { + client->connState = TCP_RECONNECT_REQ; + } + if (client->disconnectedCb) + client->disconnectedCb((uint32_t*)client); + + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); +} + + + +/** + * @brief Tcp client connect success callback function. + * @param arg: contain the ip link information + * @retval None + */ +void ICACHE_FLASH_ATTR +mqtt_tcpclient_connect_cb(void *arg) +{ + struct espconn *pCon = (struct espconn *)arg; + MQTT_Client* client = (MQTT_Client *)pCon->reverse; + + espconn_regist_disconcb(client->pCon, mqtt_tcpclient_discon_cb); + espconn_regist_recvcb(client->pCon, mqtt_tcpclient_recv);//////// + espconn_regist_sentcb(client->pCon, mqtt_tcpclient_sent_cb);/////// + MQTT_INFO("MQTT: Connected to broker %s:%d\r\n", client->host, client->port); + + mqtt_msg_init(&client->mqtt_state.mqtt_connection, client->mqtt_state.out_buffer, client->mqtt_state.out_buffer_length); + client->mqtt_state.outbound_message = mqtt_msg_connect(&client->mqtt_state.mqtt_connection, client->mqtt_state.connect_info); + client->mqtt_state.pending_msg_type = mqtt_get_type(client->mqtt_state.outbound_message->data); + client->mqtt_state.pending_msg_id = mqtt_get_id(client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length); + + + client->sendTimeout = MQTT_SEND_TIMOUT; + MQTT_INFO("MQTT: Sending, type: %d, id: %04X\r\n", client->mqtt_state.pending_msg_type, client->mqtt_state.pending_msg_id); + if (client->security) { +#ifdef MQTT_SSL_ENABLE + espconn_secure_send(client->pCon, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length); +#else + MQTT_INFO("TCP: Do not support SSL\r\n"); +#endif + } + else { + espconn_send(client->pCon, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length); + } + + client->mqtt_state.outbound_message = NULL; + client->connState = MQTT_CONNECT_SENDING; + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); +} + +/** + * @brief Tcp client connect repeat callback function. + * @param arg: contain the ip link information + * @retval None + */ +void ICACHE_FLASH_ATTR +mqtt_tcpclient_recon_cb(void *arg, sint8 errType) +{ + struct espconn *pCon = (struct espconn *)arg; + MQTT_Client* client = (MQTT_Client *)pCon->reverse; + + MQTT_INFO("TCP: Reconnect to %s:%d\r\n", client->host, client->port); + + client->connState = TCP_RECONNECT_REQ; + + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); + +} + +/** + * @brief MQTT publish function. + * @param client: MQTT_Client reference + * @param topic: string topic will publish to + * @param data: buffer data send point to + * @param data_length: length of data + * @param qos: qos + * @param retain: retain + * @retval TRUE if success queue + */ +BOOL ICACHE_FLASH_ATTR +MQTT_Publish(MQTT_Client *client, const char* topic, const char* data, int data_length, int qos, int retain) +{ + uint8_t dataBuffer[MQTT_BUF_SIZE]; + uint16_t dataLen; + client->mqtt_state.outbound_message = mqtt_msg_publish(&client->mqtt_state.mqtt_connection, + topic, data, data_length, + qos, retain, + &client->mqtt_state.pending_msg_id); + if (client->mqtt_state.outbound_message->length == 0) { + MQTT_INFO("MQTT: Queuing publish failed\r\n"); + return FALSE; + } + MQTT_INFO("MQTT: queuing publish, length: %d, queue size(%d/%d)\r\n", client->mqtt_state.outbound_message->length, client->msgQueue.rb.fill_cnt, client->msgQueue.rb.size); + while (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) { + MQTT_INFO("MQTT: Queue full\r\n"); + if (QUEUE_Gets(&client->msgQueue, dataBuffer, &dataLen, MQTT_BUF_SIZE) == -1) { + MQTT_INFO("MQTT: Serious buffer error\r\n"); + return FALSE; + } + } + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); + return TRUE; +} + +/** + * @brief MQTT subscibe function. + * @param client: MQTT_Client reference + * @param topic: string topic will subscribe + * @param qos: qos + * @retval TRUE if success queue + */ +BOOL ICACHE_FLASH_ATTR +MQTT_Subscribe(MQTT_Client *client, char* topic, uint8_t qos) +{ + uint8_t dataBuffer[MQTT_BUF_SIZE]; + uint16_t dataLen; + + client->mqtt_state.outbound_message = mqtt_msg_subscribe(&client->mqtt_state.mqtt_connection, + topic, qos, + &client->mqtt_state.pending_msg_id); + MQTT_INFO("MQTT: queue subscribe, topic\"%s\", id: %d\r\n", topic, client->mqtt_state.pending_msg_id); + while (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) { + MQTT_INFO("MQTT: Queue full\r\n"); + if (QUEUE_Gets(&client->msgQueue, dataBuffer, &dataLen, MQTT_BUF_SIZE) == -1) { + MQTT_INFO("MQTT: Serious buffer error\r\n"); + return FALSE; + } + } + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); + + return TRUE; +} + +/** + * @brief MQTT un-subscibe function. + * @param client: MQTT_Client reference + * @param topic: String topic will un-subscribe + * @retval TRUE if success queue + */ +BOOL ICACHE_FLASH_ATTR +MQTT_UnSubscribe(MQTT_Client *client, char* topic) +{ + uint8_t dataBuffer[MQTT_BUF_SIZE]; + uint16_t dataLen; + client->mqtt_state.outbound_message = mqtt_msg_unsubscribe(&client->mqtt_state.mqtt_connection, + topic, + &client->mqtt_state.pending_msg_id); + MQTT_INFO("MQTT: queue un-subscribe, topic\"%s\", id: %d\r\n", topic, client->mqtt_state.pending_msg_id); + while (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) { + MQTT_INFO("MQTT: Queue full\r\n"); + if (QUEUE_Gets(&client->msgQueue, dataBuffer, &dataLen, MQTT_BUF_SIZE) == -1) { + MQTT_INFO("MQTT: Serious buffer error\r\n"); + return FALSE; + } + } + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); + return TRUE; +} + +/** + * @brief MQTT ping function. + * @param client: MQTT_Client reference + * @retval TRUE if success queue + */ +BOOL ICACHE_FLASH_ATTR +MQTT_Ping(MQTT_Client *client) +{ + uint8_t dataBuffer[MQTT_BUF_SIZE]; + uint16_t dataLen; + client->mqtt_state.outbound_message = mqtt_msg_pingreq(&client->mqtt_state.mqtt_connection); + if (client->mqtt_state.outbound_message->length == 0) { + MQTT_INFO("MQTT: Queuing publish failed\r\n"); + return FALSE; + } + MQTT_INFO("MQTT: queuing publish, length: %d, queue size(%d/%d)\r\n", client->mqtt_state.outbound_message->length, client->msgQueue.rb.fill_cnt, client->msgQueue.rb.size); + while (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) { + MQTT_INFO("MQTT: Queue full\r\n"); + if (QUEUE_Gets(&client->msgQueue, dataBuffer, &dataLen, MQTT_BUF_SIZE) == -1) { + MQTT_INFO("MQTT: Serious buffer error\r\n"); + return FALSE; + } + } + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); + return TRUE; +} + +void ICACHE_FLASH_ATTR +MQTT_Task(os_event_t *e) +{ + MQTT_Client* client = (MQTT_Client*)e->par; + uint8_t dataBuffer[MQTT_BUF_SIZE]; + uint16_t dataLen; + if (e->par == 0) + return; + switch (client->connState) { + + case TCP_RECONNECT_REQ: + break; + case TCP_RECONNECT: + mqtt_tcpclient_delete(client); + MQTT_Connect(client); + MQTT_INFO("TCP: Reconnect to: %s:%d\r\n", client->host, client->port); + client->connState = TCP_CONNECTING; + break; + case MQTT_DELETING: + case TCP_DISCONNECTING: + case TCP_RECONNECT_DISCONNECTING: + if (client->security) { +#ifdef MQTT_SSL_ENABLE + espconn_secure_disconnect(client->pCon); +#else + MQTT_INFO("TCP: Do not support SSL\r\n"); +#endif + } + else { + espconn_disconnect(client->pCon); + } + break; + case TCP_DISCONNECTED: + MQTT_INFO("MQTT: Disconnected\r\n"); + mqtt_tcpclient_delete(client); + break; + case MQTT_DELETED: + MQTT_INFO("MQTT: Deleted client\r\n"); + mqtt_client_delete(client); + break; + case MQTT_KEEPALIVE_SEND: + mqtt_send_keepalive(client); + break; + case MQTT_DATA: + if (QUEUE_IsEmpty(&client->msgQueue) || client->sendTimeout != 0) { + break; + } + if (QUEUE_Gets(&client->msgQueue, dataBuffer, &dataLen, MQTT_BUF_SIZE) == 0) { + client->mqtt_state.pending_msg_type = mqtt_get_type(dataBuffer); + client->mqtt_state.pending_msg_id = mqtt_get_id(dataBuffer, dataLen); + + + client->sendTimeout = MQTT_SEND_TIMOUT; + MQTT_INFO("MQTT: Sending, type: %d, id: %04X\r\n", client->mqtt_state.pending_msg_type, client->mqtt_state.pending_msg_id); + client->keepAliveTick = 0; + if (client->security) { +#ifdef MQTT_SSL_ENABLE + espconn_secure_send(client->pCon, dataBuffer, dataLen); +#else + MQTT_INFO("TCP: Do not support SSL\r\n"); +#endif + } + else { + espconn_send(client->pCon, dataBuffer, dataLen); + } + + client->mqtt_state.outbound_message = NULL; + break; + } + break; + } +} + +/** + * @brief MQTT initialization connection function + * @param client: MQTT_Client reference + * @param host: Domain or IP string + * @param port: Port to connect + * @param security: 1 for ssl, 0 for none + * @retval None + */ +void ICACHE_FLASH_ATTR +MQTT_InitConnection(MQTT_Client *mqttClient, uint8_t* host, uint32_t port, uint8_t security) +{ + uint32_t temp; + MQTT_INFO("MQTT:InitConnection\r\n"); + os_memset(mqttClient, 0, sizeof(MQTT_Client)); + temp = os_strlen(host); + mqttClient->host = (uint8_t*)os_zalloc(temp + 1); + os_strcpy(mqttClient->host, host); + mqttClient->host[temp] = 0; + mqttClient->port = port; + mqttClient->security = security; + +} + +/** + * @brief MQTT initialization mqtt client function + * @param client: MQTT_Client reference + * @param clientid: MQTT client id + * @param client_user:MQTT client user + * @param client_pass:MQTT client password + * @param client_pass:MQTT keep alive timer, in second + * @retval None + */ +BOOL ICACHE_FLASH_ATTR +MQTT_InitClient(MQTT_Client *mqttClient, uint8_t* client_id, uint8_t* client_user, uint8_t* client_pass, uint32_t keepAliveTime, uint8_t cleanSession) +{ + uint32_t temp; + MQTT_INFO("MQTT:InitClient\r\n"); + + os_memset(&mqttClient->connect_info, 0, sizeof(mqtt_connect_info_t)); + + if ( !client_id ) + { + /* Should be allowed by broker, but clean session flag must be set. */ + #ifdef PROTOCOL_NAMEv311 + if (cleanSession) + { + mqttClient->connect_info.client_id = zero_len_id; + } else { + MQTT_INFO("cleanSession must be set to use 0 length client_id\r\n"); + return false; + } + /* Not supported. Return. */ + #else + MQTT_INFO("Client ID required for MQTT < 3.1.1!\r\n"); + return false; + #endif + } + + /* If connect_info's client_id is still NULL and we get here, we can * + * assume the passed client_id is non-NULL. */ + if ( !(mqttClient->connect_info.client_id) ) + { + temp = os_strlen(client_id); + mqttClient->connect_info.client_id = (uint8_t*)os_zalloc(temp + 1); + os_strcpy(mqttClient->connect_info.client_id, client_id); + mqttClient->connect_info.client_id[temp] = 0; + } + + if (client_user) + { + temp = os_strlen(client_user); + mqttClient->connect_info.username = (uint8_t*)os_zalloc(temp + 1); + os_strcpy(mqttClient->connect_info.username, client_user); + mqttClient->connect_info.username[temp] = 0; + } + + if (client_pass) + { + temp = os_strlen(client_pass); + mqttClient->connect_info.password = (uint8_t*)os_zalloc(temp + 1); + os_strcpy(mqttClient->connect_info.password, client_pass); + mqttClient->connect_info.password[temp] = 0; + } + + + mqttClient->connect_info.keepalive = keepAliveTime; + mqttClient->connect_info.clean_session = cleanSession; + + mqttClient->mqtt_state.in_buffer = (uint8_t *)os_zalloc(MQTT_BUF_SIZE); + mqttClient->mqtt_state.in_buffer_length = MQTT_BUF_SIZE; + mqttClient->mqtt_state.out_buffer = (uint8_t *)os_zalloc(MQTT_BUF_SIZE); + mqttClient->mqtt_state.out_buffer_length = MQTT_BUF_SIZE; + mqttClient->mqtt_state.connect_info = &mqttClient->connect_info; + + mqtt_msg_init(&mqttClient->mqtt_state.mqtt_connection, mqttClient->mqtt_state.out_buffer, mqttClient->mqtt_state.out_buffer_length); + + QUEUE_Init(&mqttClient->msgQueue, QUEUE_BUFFER_SIZE); + + system_os_task(MQTT_Task, MQTT_TASK_PRIO, mqtt_procTaskQueue, MQTT_TASK_QUEUE_SIZE); + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)mqttClient); + return true; +} +void ICACHE_FLASH_ATTR +MQTT_InitLWT(MQTT_Client *mqttClient, uint8_t* will_topic, uint8_t* will_msg, uint8_t will_qos, uint8_t will_retain) +{ + uint32_t temp; + temp = os_strlen(will_topic); + mqttClient->connect_info.will_topic = (uint8_t*)os_zalloc(temp + 1); + os_strcpy(mqttClient->connect_info.will_topic, will_topic); + mqttClient->connect_info.will_topic[temp] = 0; + + temp = os_strlen(will_msg); + mqttClient->connect_info.will_message = (uint8_t*)os_zalloc(temp + 1); + os_strcpy(mqttClient->connect_info.will_message, will_msg); + mqttClient->connect_info.will_message[temp] = 0; + + + mqttClient->connect_info.will_qos = will_qos; + mqttClient->connect_info.will_retain = will_retain; +} +/** + * @brief Begin connect to MQTT broker + * @param client: MQTT_Client reference + * @retval None + */ +void ICACHE_FLASH_ATTR +MQTT_Connect(MQTT_Client *mqttClient) +{ + if (mqttClient->pCon) { + // Clean up the old connection forcefully - using MQTT_Disconnect + // does not actually release the old connection until the + // disconnection callback is invoked. + mqtt_tcpclient_delete(mqttClient); + } + mqttClient->pCon = (struct espconn *)os_zalloc(sizeof(struct espconn)); + mqttClient->pCon->type = ESPCONN_TCP; + mqttClient->pCon->state = ESPCONN_NONE; + mqttClient->pCon->proto.tcp = (esp_tcp *)os_zalloc(sizeof(esp_tcp)); + mqttClient->pCon->proto.tcp->local_port = espconn_port(); + mqttClient->pCon->proto.tcp->remote_port = mqttClient->port; + mqttClient->pCon->reverse = mqttClient; + espconn_regist_connectcb(mqttClient->pCon, mqtt_tcpclient_connect_cb); + espconn_regist_reconcb(mqttClient->pCon, mqtt_tcpclient_recon_cb); + + mqttClient->keepAliveTick = 0; + mqttClient->reconnectTick = 0; + + + os_timer_disarm(&mqttClient->mqttTimer); + os_timer_setfn(&mqttClient->mqttTimer, (os_timer_func_t *)mqtt_timer, mqttClient); + os_timer_arm(&mqttClient->mqttTimer, 1000, 1); + + if (UTILS_StrToIP(mqttClient->host, &mqttClient->pCon->proto.tcp->remote_ip)) { + MQTT_INFO("TCP: Connect to ip %s:%d\r\n", mqttClient->host, mqttClient->port); + if (mqttClient->security) + { +#ifdef MQTT_SSL_ENABLE + espconn_secure_set_size(ESPCONN_CLIENT, MQTT_SSL_SIZE); + espconn_secure_connect(mqttClient->pCon); +#else + MQTT_INFO("TCP: Do not support SSL\r\n"); +#endif + } + else + { + espconn_connect(mqttClient->pCon); + } + } + else { + MQTT_INFO("TCP: Connect to domain %s:%d\r\n", mqttClient->host, mqttClient->port); + espconn_gethostbyname(mqttClient->pCon, mqttClient->host, &mqttClient->ip, mqtt_dns_found); + } + mqttClient->connState = TCP_CONNECTING; +} + +void ICACHE_FLASH_ATTR +MQTT_Disconnect(MQTT_Client *mqttClient) +{ + mqttClient->connState = TCP_DISCONNECTING; + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)mqttClient); + os_timer_disarm(&mqttClient->mqttTimer); +} + +void ICACHE_FLASH_ATTR +MQTT_DeleteClient(MQTT_Client *mqttClient) +{ + if (NULL == mqttClient) + return; + + mqttClient->connState = MQTT_DELETED; + // if(TCP_DISCONNECTED == mqttClient->connState) { + // mqttClient->connState = MQTT_DELETED; + // } else if(MQTT_DELETED != mqttClient->connState) { + // mqttClient->connState = MQTT_DELETING; + // } + + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)mqttClient); + os_timer_disarm(&mqttClient->mqttTimer); +} + +void ICACHE_FLASH_ATTR +MQTT_OnConnected(MQTT_Client *mqttClient, MqttCallback connectedCb) +{ + mqttClient->connectedCb = connectedCb; +} + +void ICACHE_FLASH_ATTR +MQTT_OnDisconnected(MQTT_Client *mqttClient, MqttCallback disconnectedCb) +{ + mqttClient->disconnectedCb = disconnectedCb; +} + +void ICACHE_FLASH_ATTR +MQTT_OnData(MQTT_Client *mqttClient, MqttDataCallback dataCb) +{ + mqttClient->dataCb = dataCb; +} + +void ICACHE_FLASH_ATTR +MQTT_OnPublished(MQTT_Client *mqttClient, MqttCallback publishedCb) +{ + mqttClient->publishedCb = publishedCb; +} + +void ICACHE_FLASH_ATTR +MQTT_OnTimeout(MQTT_Client *mqttClient, MqttCallback timeoutCb) +{ + mqttClient->timeoutCb = timeoutCb; +} + + + +void ICACHE_FLASH_ATTR +MQTT_SetUserId(MQTT_Client *mqttClient, const char* client_id) +{ + if (mqttClient->connect_info.client_id != 0) { + os_free(mqttClient->connect_info.client_id); + mqttClient->connect_info.client_id = 0; + } + + + uint32_t len = os_strlen(client_id); + + mqttClient->connect_info.client_id = (uint8_t*)os_zalloc(len + 1); + if (len) { + os_strcpy(mqttClient->connect_info.client_id, client_id); + } + mqttClient->connect_info.client_id[len] = 0; +} + +void ICACHE_FLASH_ATTR +MQTT_SetUserPwd(MQTT_Client *mqttClient, const char* user, const char* pwd) +{ + uint32_t len; + + // free username + if (mqttClient->connect_info.username != 0) { + os_free(mqttClient->connect_info.username); + mqttClient->connect_info.username = 0; + } + // free password + if (mqttClient->connect_info.password != 0) { + os_free(mqttClient->connect_info.password); + mqttClient->connect_info.password = 0; + } + + + // copy username + len = os_strlen(user); + mqttClient->connect_info.username = (uint8_t*)os_zalloc(len + 1); + if (len) { + os_strcpy(mqttClient->connect_info.username, user); + } + mqttClient->connect_info.username[len] = 0; + + + // copy password + len = os_strlen(pwd); + mqttClient->connect_info.password = (uint8_t*)os_zalloc(len + 1); + if (len) { + os_strcpy(mqttClient->connect_info.password, pwd); + } + mqttClient->connect_info.password[len] = 0; + +} + diff --git a/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/mqtt.h b/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/mqtt.h new file mode 100644 index 000000000..6ef619433 --- /dev/null +++ b/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/mqtt.h @@ -0,0 +1,152 @@ +/* mqtt.h +* +* Copyright (c) 2014-2015, Tuan PM +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* +* * Redistributions of source code must retain the above copyright notice, +* this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of Redis nor the names of its contributors may be used +* to endorse or promote products derived from this software without +* specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +* POSSIBILITY OF SUCH DAMAGE. +*/ +#ifndef USER_AT_MQTT_H_ +#define USER_AT_MQTT_H_ +#include "mqtt_config.h" +#include "mqtt_msg.h" +#include "user_interface.h" + +#include "queue.h" +typedef struct mqtt_event_data_t +{ + uint8_t type; + const char* topic; + const char* data; + uint16_t topic_length; + uint16_t data_length; + uint16_t data_offset; +} mqtt_event_data_t; + +typedef struct mqtt_state_t +{ + uint16_t port; + int auto_reconnect; + mqtt_connect_info_t* connect_info; + uint8_t* in_buffer; + uint8_t* out_buffer; + int in_buffer_length; + int out_buffer_length; + uint16_t message_length; + uint16_t message_length_read; + mqtt_message_t* outbound_message; + mqtt_connection_t mqtt_connection; + uint16_t pending_msg_id; + int pending_msg_type; + int pending_publish_qos; +} mqtt_state_t; + +typedef enum { + WIFI_INIT, + WIFI_CONNECTING, + WIFI_CONNECTING_ERROR, + WIFI_CONNECTED, + DNS_RESOLVE, + TCP_DISCONNECTING, + TCP_DISCONNECTED, + TCP_RECONNECT_DISCONNECTING, + TCP_RECONNECT_REQ, + TCP_RECONNECT, + TCP_CONNECTING, + TCP_CONNECTING_ERROR, + TCP_CONNECTED, + MQTT_CONNECT_SEND, + MQTT_CONNECT_SENDING, + MQTT_SUBSCIBE_SEND, + MQTT_SUBSCIBE_SENDING, + MQTT_DATA, + MQTT_KEEPALIVE_SEND, + MQTT_PUBLISH_RECV, + MQTT_PUBLISHING, + MQTT_DELETING, + MQTT_DELETED, +} tConnState; + +typedef void (*MqttCallback)(uint32_t *args); +typedef void (*MqttDataCallback)(uint32_t *args, const char* topic, uint32_t topic_len, const char *data, uint32_t lengh); + +typedef struct { + struct espconn *pCon; + uint8_t security; + uint8_t* host; + uint32_t port; + ip_addr_t ip; + mqtt_state_t mqtt_state; + mqtt_connect_info_t connect_info; + MqttCallback connectedCb; + MqttCallback disconnectedCb; + MqttCallback publishedCb; + MqttCallback timeoutCb; + MqttDataCallback dataCb; + ETSTimer mqttTimer; + uint32_t keepAliveTick; + uint32_t reconnectTick; + uint32_t sendTimeout; + tConnState connState; + QUEUE msgQueue; + void* user_data; +} MQTT_Client; + +#define SEC_NONSSL 0 +#define SEC_SSL 1 + +#define MQTT_FLAG_CONNECTED 1 +#define MQTT_FLAG_READY 2 +#define MQTT_FLAG_EXIT 4 + +#define MQTT_EVENT_TYPE_NONE 0 +#define MQTT_EVENT_TYPE_CONNECTED 1 +#define MQTT_EVENT_TYPE_DISCONNECTED 2 +#define MQTT_EVENT_TYPE_SUBSCRIBED 3 +#define MQTT_EVENT_TYPE_UNSUBSCRIBED 4 +#define MQTT_EVENT_TYPE_PUBLISH 5 +#define MQTT_EVENT_TYPE_PUBLISHED 6 +#define MQTT_EVENT_TYPE_EXITED 7 +#define MQTT_EVENT_TYPE_PUBLISH_CONTINUATION 8 + +void ICACHE_FLASH_ATTR MQTT_InitConnection(MQTT_Client *mqttClient, uint8_t* host, uint32_t port, uint8_t security); +bool ICACHE_FLASH_ATTR MQTT_InitClient(MQTT_Client *mqttClient, uint8_t* client_id, uint8_t* client_user, uint8_t* client_pass, uint32_t keepAliveTime, uint8_t cleanSession); +void ICACHE_FLASH_ATTR MQTT_DeleteClient(MQTT_Client *mqttClient); +void ICACHE_FLASH_ATTR MQTT_InitLWT(MQTT_Client *mqttClient, uint8_t* will_topic, uint8_t* will_msg, uint8_t will_qos, uint8_t will_retain); + +void ICACHE_FLASH_ATTR MQTT_SetUserId(MQTT_Client *mqttClient, const char* client_id); +void ICACHE_FLASH_ATTR MQTT_SetUserPwd(MQTT_Client *mqttClient, const char* user_id, const char* pwd); + +void ICACHE_FLASH_ATTR MQTT_OnConnected(MQTT_Client *mqttClient, MqttCallback connectedCb); +void ICACHE_FLASH_ATTR MQTT_OnDisconnected(MQTT_Client *mqttClient, MqttCallback disconnectedCb); +void ICACHE_FLASH_ATTR MQTT_OnPublished(MQTT_Client *mqttClient, MqttCallback publishedCb); +void ICACHE_FLASH_ATTR MQTT_OnTimeout(MQTT_Client *mqttClient, MqttCallback timeoutCb); +void ICACHE_FLASH_ATTR MQTT_OnData(MQTT_Client *mqttClient, MqttDataCallback dataCb); +bool ICACHE_FLASH_ATTR MQTT_Subscribe(MQTT_Client *client, char* topic, uint8_t qos); +bool ICACHE_FLASH_ATTR MQTT_UnSubscribe(MQTT_Client *client, char* topic); +void ICACHE_FLASH_ATTR MQTT_Connect(MQTT_Client *mqttClient); +void ICACHE_FLASH_ATTR MQTT_Disconnect(MQTT_Client *mqttClient); +bool ICACHE_FLASH_ATTR MQTT_Publish(MQTT_Client *client, const char* topic, const char* data, int data_length, int qos, int retain); + +#endif /* USER_AT_MQTT_H_ */ diff --git a/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/mqtt_config.h b/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/mqtt_config.h new file mode 100644 index 000000000..5332f82ee --- /dev/null +++ b/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/mqtt_config.h @@ -0,0 +1,19 @@ +#ifndef __MQTT_CONFIG_H__ +#define __MQTT_CONFIG_H__ + +//#define MQTT_SSL_ENABLE + +/*DEFAULT CONFIGURATIONS*/ + +#define MQTT_BUF_SIZE 1024 +//#define MQTT_KEEPALIVE 120 /*second*/ +#define MQTT_KEEPALIVE 15 /*second*/ + +#define MQTT_RECONNECT_TIMEOUT 5 /*second*/ + +#define QUEUE_BUFFER_SIZE 2048 + +//#define PROTOCOL_NAMEv31 /*MQTT version 3.1 compatible with Mosquitto v0.15*/ +#define PROTOCOL_NAMEv311 /*MQTT version 3.11 compatible with https://eclipse.org/paho/clients/testing/*/ + +#endif // __MQTT_CONFIG_H__ \ No newline at end of file diff --git a/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/mqtt_msg.c b/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/mqtt_msg.c new file mode 100644 index 000000000..c2b320311 --- /dev/null +++ b/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/mqtt_msg.c @@ -0,0 +1,487 @@ +/* +* Copyright (c) 2014, Stephen Robinson +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions +* are met: +* +* 1. Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* 2. Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* 3. Neither the name of the copyright holder nor the names of its +* contributors may be used to endorse or promote products derived +* from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +* POSSIBILITY OF SUCH DAMAGE. +* +*/ + +#include +#include "mqtt_msg.h" +#include "mqtt_config.h" +#define MQTT_MAX_FIXED_HEADER_SIZE 3 + +enum mqtt_connect_flag +{ + MQTT_CONNECT_FLAG_USERNAME = 1 << 7, + MQTT_CONNECT_FLAG_PASSWORD = 1 << 6, + MQTT_CONNECT_FLAG_WILL_RETAIN = 1 << 5, + MQTT_CONNECT_FLAG_WILL = 1 << 2, + MQTT_CONNECT_FLAG_CLEAN_SESSION = 1 << 1 +}; + +struct __attribute((__packed__)) mqtt_connect_variable_header +{ + uint8_t lengthMsb; + uint8_t lengthLsb; +#if defined(PROTOCOL_NAMEv31) + uint8_t magic[6]; +#elif defined(PROTOCOL_NAMEv311) + uint8_t magic[4]; +#else +#error "Please define protocol name" +#endif + uint8_t version; + uint8_t flags; + uint8_t keepaliveMsb; + uint8_t keepaliveLsb; +}; + +static int ICACHE_FLASH_ATTR append_string(mqtt_connection_t* connection, const char* string, int len) +{ + if (connection->message.length + len + 2 > connection->buffer_length) + return -1; + + connection->buffer[connection->message.length++] = len >> 8; + connection->buffer[connection->message.length++] = len & 0xff; + memcpy(connection->buffer + connection->message.length, string, len); + connection->message.length += len; + + return len + 2; +} + +static uint16_t ICACHE_FLASH_ATTR append_message_id(mqtt_connection_t* connection, uint16_t message_id) +{ + // If message_id is zero then we should assign one, otherwise + // we'll use the one supplied by the caller + while (message_id == 0) + message_id = ++connection->message_id; + + if (connection->message.length + 2 > connection->buffer_length) + return 0; + + connection->buffer[connection->message.length++] = message_id >> 8; + connection->buffer[connection->message.length++] = message_id & 0xff; + + return message_id; +} + +static int ICACHE_FLASH_ATTR init_message(mqtt_connection_t* connection) +{ + connection->message.length = MQTT_MAX_FIXED_HEADER_SIZE; + return MQTT_MAX_FIXED_HEADER_SIZE; +} + +static mqtt_message_t* ICACHE_FLASH_ATTR fail_message(mqtt_connection_t* connection) +{ + connection->message.data = connection->buffer; + connection->message.length = 0; + return &connection->message; +} + +static mqtt_message_t* ICACHE_FLASH_ATTR fini_message(mqtt_connection_t* connection, int type, int dup, int qos, int retain) +{ + int remaining_length = connection->message.length - MQTT_MAX_FIXED_HEADER_SIZE; + + if (remaining_length > 127) + { + connection->buffer[0] = ((type & 0x0f) << 4) | ((dup & 1) << 3) | ((qos & 3) << 1) | (retain & 1); + connection->buffer[1] = 0x80 | (remaining_length % 128); + connection->buffer[2] = remaining_length / 128; + connection->message.length = remaining_length + 3; + connection->message.data = connection->buffer; + } + else + { + connection->buffer[1] = ((type & 0x0f) << 4) | ((dup & 1) << 3) | ((qos & 3) << 1) | (retain & 1); + connection->buffer[2] = remaining_length; + connection->message.length = remaining_length + 2; + connection->message.data = connection->buffer + 1; + } + + return &connection->message; +} + +void ICACHE_FLASH_ATTR mqtt_msg_init(mqtt_connection_t* connection, uint8_t* buffer, uint16_t buffer_length) +{ + memset(connection, 0, sizeof(mqtt_connection_t)); + connection->buffer = buffer; + connection->buffer_length = buffer_length; +} + +int ICACHE_FLASH_ATTR mqtt_get_total_length(uint8_t* buffer, uint16_t length) +{ + int i; + int totlen = 0; + + for (i = 1; i < length; ++i) + { + totlen += (buffer[i] & 0x7f) << (7 * (i - 1)); + if ((buffer[i] & 0x80) == 0) + { + ++i; + break; + } + } + totlen += i; + + return totlen; +} + +const char* ICACHE_FLASH_ATTR mqtt_get_publish_topic(uint8_t* buffer, uint16_t* length) +{ + int i; + int totlen = 0; + int topiclen; + + for (i = 1; i < *length; ++i) + { + totlen += (buffer[i] & 0x7f) << (7 * (i - 1)); + if ((buffer[i] & 0x80) == 0) + { + ++i; + break; + } + } + totlen += i; + + if (i + 2 >= *length) + return NULL; + topiclen = buffer[i++] << 8; + topiclen |= buffer[i++]; + + if (i + topiclen > *length) + return NULL; + + *length = topiclen; + return (const char*)(buffer + i); +} + +const char* ICACHE_FLASH_ATTR mqtt_get_publish_data(uint8_t* buffer, uint16_t* length) +{ + int i; + int totlen = 0; + int topiclen; + int blength = *length; + *length = 0; + + for (i = 1; i < blength; ++i) + { + totlen += (buffer[i] & 0x7f) << (7 * (i - 1)); + if ((buffer[i] & 0x80) == 0) + { + ++i; + break; + } + } + totlen += i; + + if (i + 2 >= blength) + return NULL; + topiclen = buffer[i++] << 8; + topiclen |= buffer[i++]; + + if (i + topiclen >= blength) + return NULL; + + i += topiclen; + + if (mqtt_get_qos(buffer) > 0) + { + if (i + 2 >= blength) + return NULL; + i += 2; + } + + if (totlen < i) + return NULL; + + if (totlen <= blength) + *length = totlen - i; + else + *length = blength - i; + return (const char*)(buffer + i); +} + +uint16_t ICACHE_FLASH_ATTR mqtt_get_id(uint8_t* buffer, uint16_t length) +{ + if (length < 1) + return 0; + + switch (mqtt_get_type(buffer)) + { + case MQTT_MSG_TYPE_PUBLISH: + { + int i; + int topiclen; + + for (i = 1; i < length; ++i) + { + if ((buffer[i] & 0x80) == 0) + { + ++i; + break; + } + } + + if (i + 2 >= length) + return 0; + topiclen = buffer[i++] << 8; + topiclen |= buffer[i++]; + + if (i + topiclen >= length) + return 0; + i += topiclen; + + if (mqtt_get_qos(buffer) > 0) + { + if (i + 2 >= length) + return 0; + //i += 2; + } else { + return 0; + } + + return (buffer[i] << 8) | buffer[i + 1]; + } + case MQTT_MSG_TYPE_PUBACK: + case MQTT_MSG_TYPE_PUBREC: + case MQTT_MSG_TYPE_PUBREL: + case MQTT_MSG_TYPE_PUBCOMP: + case MQTT_MSG_TYPE_SUBACK: + case MQTT_MSG_TYPE_UNSUBACK: + case MQTT_MSG_TYPE_SUBSCRIBE: + { + // This requires the remaining length to be encoded in 1 byte, + // which it should be. + if (length >= 4 && (buffer[1] & 0x80) == 0) + return (buffer[2] << 8) | buffer[3]; + else + return 0; + } + + default: + return 0; + } +} + +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_connect(mqtt_connection_t* connection, mqtt_connect_info_t* info) +{ + struct mqtt_connect_variable_header* variable_header; + + init_message(connection); + + if (connection->message.length + sizeof(*variable_header) > connection->buffer_length) + return fail_message(connection); + variable_header = (void*)(connection->buffer + connection->message.length); + connection->message.length += sizeof(*variable_header); + + variable_header->lengthMsb = 0; +#if defined(PROTOCOL_NAMEv31) + variable_header->lengthLsb = 6; + memcpy(variable_header->magic, "MQIsdp", 6); + variable_header->version = 3; +#elif defined(PROTOCOL_NAMEv311) + variable_header->lengthLsb = 4; + memcpy(variable_header->magic, "MQTT", 4); + variable_header->version = 4; +#else +#error "Please define protocol name" +#endif + + variable_header->flags = 0; + variable_header->keepaliveMsb = info->keepalive >> 8; + variable_header->keepaliveLsb = info->keepalive & 0xff; + + if (info->clean_session) + variable_header->flags |= MQTT_CONNECT_FLAG_CLEAN_SESSION; + + if (info->client_id == NULL) + { + /* Never allowed */ + return fail_message(connection); + } + else if (info->client_id[0] == '\0') + { +#ifdef PROTOCOL_NAMEv311 + /* Allowed. Format 0 Length ID */ + append_string(connection, info->client_id, 2) ; +#else + /* 0 Length not allowed */ + return fail_message(connection); +#endif + } + else + { + /* No 0 data and at least 1 long. Good to go. */ + if(append_string(connection, info->client_id, strlen(info->client_id)) < 0) + return fail_message(connection); + } + + if (info->will_topic != NULL && info->will_topic[0] != '\0') + { + if (append_string(connection, info->will_topic, strlen(info->will_topic)) < 0) + return fail_message(connection); + + if (append_string(connection, info->will_message, strlen(info->will_message)) < 0) + return fail_message(connection); + + variable_header->flags |= MQTT_CONNECT_FLAG_WILL; + if (info->will_retain) + variable_header->flags |= MQTT_CONNECT_FLAG_WILL_RETAIN; + variable_header->flags |= (info->will_qos & 3) << 3; + } + + if (info->username != NULL && info->username[0] != '\0') + { + if (append_string(connection, info->username, strlen(info->username)) < 0) + return fail_message(connection); + + variable_header->flags |= MQTT_CONNECT_FLAG_USERNAME; + } + + if (info->password != NULL && info->password[0] != '\0') + { + if (append_string(connection, info->password, strlen(info->password)) < 0) + return fail_message(connection); + + variable_header->flags |= MQTT_CONNECT_FLAG_PASSWORD; + } + + return fini_message(connection, MQTT_MSG_TYPE_CONNECT, 0, 0, 0); +} + +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_publish(mqtt_connection_t* connection, const char* topic, const char* data, int data_length, int qos, int retain, uint16_t* message_id) +{ + init_message(connection); + + if (topic == NULL || topic[0] == '\0') + return fail_message(connection); + + if (append_string(connection, topic, strlen(topic)) < 0) + return fail_message(connection); + + if (qos > 0) + { + if ((*message_id = append_message_id(connection, 0)) == 0) + return fail_message(connection); + } + else + *message_id = 0; + + if (connection->message.length + data_length > connection->buffer_length) + return fail_message(connection); + memcpy(connection->buffer + connection->message.length, data, data_length); + connection->message.length += data_length; + + return fini_message(connection, MQTT_MSG_TYPE_PUBLISH, 0, qos, retain); +} + +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_puback(mqtt_connection_t* connection, uint16_t message_id) +{ + init_message(connection); + if (append_message_id(connection, message_id) == 0) + return fail_message(connection); + return fini_message(connection, MQTT_MSG_TYPE_PUBACK, 0, 0, 0); +} + +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pubrec(mqtt_connection_t* connection, uint16_t message_id) +{ + init_message(connection); + if (append_message_id(connection, message_id) == 0) + return fail_message(connection); + return fini_message(connection, MQTT_MSG_TYPE_PUBREC, 0, 0, 0); +} + +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pubrel(mqtt_connection_t* connection, uint16_t message_id) +{ + init_message(connection); + if (append_message_id(connection, message_id) == 0) + return fail_message(connection); + return fini_message(connection, MQTT_MSG_TYPE_PUBREL, 0, 1, 0); +} + +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pubcomp(mqtt_connection_t* connection, uint16_t message_id) +{ + init_message(connection); + if (append_message_id(connection, message_id) == 0) + return fail_message(connection); + return fini_message(connection, MQTT_MSG_TYPE_PUBCOMP, 0, 0, 0); +} + +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_subscribe(mqtt_connection_t* connection, const char* topic, int qos, uint16_t* message_id) +{ + init_message(connection); + + if (topic == NULL || topic[0] == '\0') + return fail_message(connection); + + if ((*message_id = append_message_id(connection, 0)) == 0) + return fail_message(connection); + + if (append_string(connection, topic, strlen(topic)) < 0) + return fail_message(connection); + + if (connection->message.length + 1 > connection->buffer_length) + return fail_message(connection); + connection->buffer[connection->message.length++] = qos; + + return fini_message(connection, MQTT_MSG_TYPE_SUBSCRIBE, 0, 1, 0); +} + +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_unsubscribe(mqtt_connection_t* connection, const char* topic, uint16_t* message_id) +{ + init_message(connection); + + if (topic == NULL || topic[0] == '\0') + return fail_message(connection); + + if ((*message_id = append_message_id(connection, 0)) == 0) + return fail_message(connection); + + if (append_string(connection, topic, strlen(topic)) < 0) + return fail_message(connection); + + return fini_message(connection, MQTT_MSG_TYPE_UNSUBSCRIBE, 0, 1, 0); +} + +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pingreq(mqtt_connection_t* connection) +{ + init_message(connection); + return fini_message(connection, MQTT_MSG_TYPE_PINGREQ, 0, 0, 0); +} + +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pingresp(mqtt_connection_t* connection) +{ + init_message(connection); + return fini_message(connection, MQTT_MSG_TYPE_PINGRESP, 0, 0, 0); +} + +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_disconnect(mqtt_connection_t* connection) +{ + init_message(connection); + return fini_message(connection, MQTT_MSG_TYPE_DISCONNECT, 0, 0, 0); +} diff --git a/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/mqtt_msg.h b/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/mqtt_msg.h new file mode 100644 index 000000000..be3cc55cb --- /dev/null +++ b/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/mqtt_msg.h @@ -0,0 +1,141 @@ +/* + * File: mqtt_msg.h + * Author: Minh Tuan + * + * Created on July 12, 2014, 1:05 PM + */ + +#ifndef MQTT_MSG_H +#define MQTT_MSG_H +#include "user_config.h" +#include "c_types.h" +#ifdef __cplusplus +extern "C" { +#endif + +/* +* Copyright (c) 2014, Stephen Robinson +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions +* are met: +* +* 1. Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* 2. Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* 3. Neither the name of the copyright holder nor the names of its +* contributors may be used to endorse or promote products derived +* from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +* POSSIBILITY OF SUCH DAMAGE. +* +*/ +/* 7 6 5 4 3 2 1 0*/ +/*| --- Message Type---- | DUP Flag | QoS Level | Retain | +/* Remaining Length */ + + +enum mqtt_message_type +{ + MQTT_MSG_TYPE_CONNECT = 1, + MQTT_MSG_TYPE_CONNACK = 2, + MQTT_MSG_TYPE_PUBLISH = 3, + MQTT_MSG_TYPE_PUBACK = 4, + MQTT_MSG_TYPE_PUBREC = 5, + MQTT_MSG_TYPE_PUBREL = 6, + MQTT_MSG_TYPE_PUBCOMP = 7, + MQTT_MSG_TYPE_SUBSCRIBE = 8, + MQTT_MSG_TYPE_SUBACK = 9, + MQTT_MSG_TYPE_UNSUBSCRIBE = 10, + MQTT_MSG_TYPE_UNSUBACK = 11, + MQTT_MSG_TYPE_PINGREQ = 12, + MQTT_MSG_TYPE_PINGRESP = 13, + MQTT_MSG_TYPE_DISCONNECT = 14 +}; + +enum mqtt_connect_return_code +{ + CONNECTION_ACCEPTED = 0, + CONNECTION_REFUSE_PROTOCOL, + CONNECTION_REFUSE_ID_REJECTED, + CONNECTION_REFUSE_SERVER_UNAVAILABLE, + CONNECTION_REFUSE_BAD_USERNAME, + CONNECTION_REFUSE_NOT_AUTHORIZED +}; + +typedef struct mqtt_message +{ + uint8_t* data; + uint16_t length; + +} mqtt_message_t; + +typedef struct mqtt_connection +{ + mqtt_message_t message; + + uint16_t message_id; + uint8_t* buffer; + uint16_t buffer_length; + +} mqtt_connection_t; + +typedef struct mqtt_connect_info +{ + char* client_id; + char* username; + char* password; + char* will_topic; + char* will_message; + uint32_t keepalive; + int will_qos; + int will_retain; + int clean_session; + +} mqtt_connect_info_t; + + +static inline int ICACHE_FLASH_ATTR mqtt_get_type(uint8_t* buffer) { return (buffer[0] & 0xf0) >> 4; } +static inline int ICACHE_FLASH_ATTR mqtt_get_connect_return_code(uint8_t* buffer) { return buffer[3]; } +static inline int ICACHE_FLASH_ATTR mqtt_get_dup(uint8_t* buffer) { return (buffer[0] & 0x08) >> 3; } +static inline int ICACHE_FLASH_ATTR mqtt_get_qos(uint8_t* buffer) { return (buffer[0] & 0x06) >> 1; } +static inline int ICACHE_FLASH_ATTR mqtt_get_retain(uint8_t* buffer) { return (buffer[0] & 0x01); } + +void ICACHE_FLASH_ATTR mqtt_msg_init(mqtt_connection_t* connection, uint8_t* buffer, uint16_t buffer_length); +int ICACHE_FLASH_ATTR mqtt_get_total_length(uint8_t* buffer, uint16_t length); +const char* ICACHE_FLASH_ATTR mqtt_get_publish_topic(uint8_t* buffer, uint16_t* length); +const char* ICACHE_FLASH_ATTR mqtt_get_publish_data(uint8_t* buffer, uint16_t* length); +uint16_t ICACHE_FLASH_ATTR mqtt_get_id(uint8_t* buffer, uint16_t length); + +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_connect(mqtt_connection_t* connection, mqtt_connect_info_t* info); +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_publish(mqtt_connection_t* connection, const char* topic, const char* data, int data_length, int qos, int retain, uint16_t* message_id); +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_puback(mqtt_connection_t* connection, uint16_t message_id); +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pubrec(mqtt_connection_t* connection, uint16_t message_id); +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pubrel(mqtt_connection_t* connection, uint16_t message_id); +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pubcomp(mqtt_connection_t* connection, uint16_t message_id); +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_subscribe(mqtt_connection_t* connection, const char* topic, int qos, uint16_t* message_id); +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_unsubscribe(mqtt_connection_t* connection, const char* topic, uint16_t* message_id); +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pingreq(mqtt_connection_t* connection); +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pingresp(mqtt_connection_t* connection); +mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_disconnect(mqtt_connection_t* connection); + + +#ifdef __cplusplus +} +#endif + +#endif /* MQTT_MSG_H */ + diff --git a/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/proto.c b/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/proto.c new file mode 100644 index 000000000..84078b233 --- /dev/null +++ b/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/proto.c @@ -0,0 +1,129 @@ +#include "proto.h" +#include "ringbuf.h" +I8 ICACHE_FLASH_ATTR PROTO_Init(PROTO_PARSER *parser, PROTO_PARSE_CALLBACK *completeCallback, U8 *buf, U16 bufSize) +{ + parser->buf = buf; + parser->bufSize = bufSize; + parser->dataLen = 0; + parser->callback = completeCallback; + parser->isEsc = 0; + return 0; +} + +I8 ICACHE_FLASH_ATTR PROTO_ParseByte(PROTO_PARSER *parser, U8 value) +{ + switch (value) { + case 0x7D: + parser->isEsc = 1; + break; + + case 0x7E: + parser->dataLen = 0; + parser->isEsc = 0; + parser->isBegin = 1; + break; + + case 0x7F: + if (parser->callback != NULL) + parser->callback(); + parser->isBegin = 0; + return 0; + break; + + default: + if (parser->isBegin == 0) break; + + if (parser->isEsc) { + value ^= 0x20; + parser->isEsc = 0; + } + + if (parser->dataLen < parser->bufSize) + parser->buf[parser->dataLen++] = value; + + break; + } + return -1; +} + +I8 ICACHE_FLASH_ATTR PROTO_Parse(PROTO_PARSER *parser, U8 *buf, U16 len) +{ + while (len--) + PROTO_ParseByte(parser, *buf++); + + return 0; +} +I16 ICACHE_FLASH_ATTR PROTO_ParseRb(RINGBUF* rb, U8 *bufOut, U16* len, U16 maxBufLen) +{ + U8 c; + + PROTO_PARSER proto; + PROTO_Init(&proto, NULL, bufOut, maxBufLen); + while (RINGBUF_Get(rb, &c) == 0) { + if (PROTO_ParseByte(&proto, c) == 0) { + *len = proto.dataLen; + return 0; + } + } + return -1; +} +I16 ICACHE_FLASH_ATTR PROTO_Add(U8 *buf, const U8 *packet, I16 bufSize) +{ + U16 i = 2; + U16 len = *(U16*) packet; + + if (bufSize < 1) return -1; + + *buf++ = 0x7E; + bufSize--; + + while (len--) { + switch (*packet) { + case 0x7D: + case 0x7E: + case 0x7F: + if (bufSize < 2) return -1; + *buf++ = 0x7D; + *buf++ = *packet++ ^ 0x20; + i += 2; + bufSize -= 2; + break; + default: + if (bufSize < 1) return -1; + *buf++ = *packet++; + i++; + bufSize--; + break; + } + } + + if (bufSize < 1) return -1; + *buf++ = 0x7F; + + return i; +} + +I16 ICACHE_FLASH_ATTR PROTO_AddRb(RINGBUF *rb, const U8 *packet, I16 len) +{ + U16 i = 2; + if (RINGBUF_Put(rb, 0x7E) == -1) return -1; + while (len--) { + switch (*packet) { + case 0x7D: + case 0x7E: + case 0x7F: + if (RINGBUF_Put(rb, 0x7D) == -1) return -1; + if (RINGBUF_Put(rb, *packet++ ^ 0x20) == -1) return -1; + i += 2; + break; + default: + if (RINGBUF_Put(rb, *packet++) == -1) return -1; + i++; + break; + } + } + if (RINGBUF_Put(rb, 0x7F) == -1) return -1; + + return i; +} + diff --git a/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/proto.h b/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/proto.h new file mode 100644 index 000000000..a405bcb95 --- /dev/null +++ b/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/proto.h @@ -0,0 +1,32 @@ +/* + * File: proto.h + * Author: ThuHien + * + * Created on November 23, 2012, 8:57 AM + */ + +#ifndef _PROTO_H_ +#define _PROTO_H_ +#include +#include "typedef.h" +#include "ringbuf.h" + +typedef void(PROTO_PARSE_CALLBACK)(); + +typedef struct { + U8 *buf; + U16 bufSize; + U16 dataLen; + U8 isEsc; + U8 isBegin; + PROTO_PARSE_CALLBACK* callback; +} PROTO_PARSER; + +I8 ICACHE_FLASH_ATTR PROTO_Init(PROTO_PARSER *parser, PROTO_PARSE_CALLBACK *completeCallback, U8 *buf, U16 bufSize); +I8 ICACHE_FLASH_ATTR PROTO_Parse(PROTO_PARSER *parser, U8 *buf, U16 len); +I16 ICACHE_FLASH_ATTR PROTO_Add(U8 *buf, const U8 *packet, I16 bufSize); +I16 ICACHE_FLASH_ATTR PROTO_AddRb(RINGBUF *rb, const U8 *packet, I16 len); +I8 ICACHE_FLASH_ATTR PROTO_ParseByte(PROTO_PARSER *parser, U8 value); +I16 ICACHE_FLASH_ATTR PROTO_ParseRb(RINGBUF *rb, U8 *bufOut, U16* len, U16 maxBufLen); +#endif + diff --git a/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/queue.c b/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/queue.c new file mode 100644 index 000000000..95bbec0cd --- /dev/null +++ b/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/queue.c @@ -0,0 +1,75 @@ +/* str_queue.c +* +* Copyright (c) 2014-2015, Tuan PM +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* +* * Redistributions of source code must retain the above copyright notice, +* this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of Redis nor the names of its contributors may be used +* to endorse or promote products derived from this software without +* specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +* POSSIBILITY OF SUCH DAMAGE. +*/ +#include "queue.h" + +#include "user_interface.h" +#include "osapi.h" +#include "os_type.h" +#include "mem.h" +#include "proto.h" + +uint8_t *last_rb_p_r; +uint8_t *last_rb_p_w; +uint32_t last_fill_cnt; + +void ICACHE_FLASH_ATTR QUEUE_Init(QUEUE *queue, int bufferSize) +{ + queue->buf = (uint8_t*)os_zalloc(bufferSize); + RINGBUF_Init(&queue->rb, queue->buf, bufferSize); +} +int32_t ICACHE_FLASH_ATTR QUEUE_Puts(QUEUE *queue, uint8_t* buffer, uint16_t len) +{ + uint32_t ret; + + last_rb_p_r = queue->rb.p_r; + last_rb_p_w = queue->rb.p_w; + last_fill_cnt = queue->rb.fill_cnt; + + ret = PROTO_AddRb(&queue->rb, buffer, len); + if (ret == -1) { + // rolling ring buffer back + queue->rb.p_r = last_rb_p_r; + queue->rb.p_w = last_rb_p_w; + queue->rb.fill_cnt = last_fill_cnt; + } + return ret; +} +int32_t ICACHE_FLASH_ATTR QUEUE_Gets(QUEUE *queue, uint8_t* buffer, uint16_t* len, uint16_t maxLen) +{ + + return PROTO_ParseRb(&queue->rb, buffer, len, maxLen); +} + +BOOL ICACHE_FLASH_ATTR QUEUE_IsEmpty(QUEUE *queue) +{ + if (queue->rb.fill_cnt <= 0) + return TRUE; + return FALSE; +} diff --git a/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/queue.h b/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/queue.h new file mode 100644 index 000000000..79107f2d5 --- /dev/null +++ b/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/queue.h @@ -0,0 +1,44 @@ +/* str_queue.h -- +* +* Copyright (c) 2014-2015, Tuan PM +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* +* * Redistributions of source code must retain the above copyright notice, +* this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of Redis nor the names of its contributors may be used +* to endorse or promote products derived from this software without +* specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +* POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifndef USER_QUEUE_H_ +#define USER_QUEUE_H_ +#include "os_type.h" +#include "ringbuf.h" +typedef struct { + uint8_t *buf; + RINGBUF rb; +} QUEUE; + +void ICACHE_FLASH_ATTR QUEUE_Init(QUEUE *queue, int bufferSize); +int32_t ICACHE_FLASH_ATTR QUEUE_Puts(QUEUE *queue, uint8_t* buffer, uint16_t len); +int32_t ICACHE_FLASH_ATTR QUEUE_Gets(QUEUE *queue, uint8_t* buffer, uint16_t* len, uint16_t maxLen); +bool ICACHE_FLASH_ATTR QUEUE_IsEmpty(QUEUE *queue); +#endif /* USER_QUEUE_H_ */ diff --git a/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/ringbuf.c b/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/ringbuf.c new file mode 100644 index 000000000..fc882fd5c --- /dev/null +++ b/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/ringbuf.c @@ -0,0 +1,67 @@ +/** +* \file +* Ring Buffer library +*/ + +#include "ringbuf.h" + + +/** +* \brief init a RINGBUF object +* \param r pointer to a RINGBUF object +* \param buf pointer to a byte array +* \param size size of buf +* \return 0 if successfull, otherwise failed +*/ +I16 ICACHE_FLASH_ATTR RINGBUF_Init(RINGBUF *r, U8* buf, I32 size) +{ + if (r == NULL || buf == NULL || size < 2) return -1; + + r->p_o = r->p_r = r->p_w = buf; + r->fill_cnt = 0; + r->size = size; + + return 0; +} +/** +* \brief put a character into ring buffer +* \param r pointer to a ringbuf object +* \param c character to be put +* \return 0 if successfull, otherwise failed +*/ +I16 ICACHE_FLASH_ATTR RINGBUF_Put(RINGBUF *r, U8 c) +{ + if (r->fill_cnt >= r->size)return -1; // ring buffer is full, this should be atomic operation + + + r->fill_cnt++; // increase filled slots count, this should be atomic operation + + + *r->p_w++ = c; // put character into buffer + + if (r->p_w >= r->p_o + r->size) // rollback if write pointer go pass + r->p_w = r->p_o; // the physical boundary + + return 0; +} +/** +* \brief get a character from ring buffer +* \param r pointer to a ringbuf object +* \param c read character +* \return 0 if successfull, otherwise failed +*/ +I16 ICACHE_FLASH_ATTR RINGBUF_Get(RINGBUF *r, U8* c) +{ + if (r->fill_cnt <= 0)return -1; // ring buffer is empty, this should be atomic operation + + + r->fill_cnt--; // decrease filled slots count + + + *c = *r->p_r++; // get the character out + + if (r->p_r >= r->p_o + r->size) // rollback if write pointer go pass + r->p_r = r->p_o; // the physical boundary + + return 0; +} diff --git a/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/ringbuf.h b/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/ringbuf.h new file mode 100644 index 000000000..f1a4f7e8b --- /dev/null +++ b/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/ringbuf.h @@ -0,0 +1,19 @@ +#ifndef _RING_BUF_H_ +#define _RING_BUF_H_ + +#include +#include +#include "typedef.h" + +typedef struct { + U8* p_o; /**< Original pointer */ + U8* volatile p_r; /**< Read pointer */ + U8* volatile p_w; /**< Write pointer */ + volatile I32 fill_cnt; /**< Number of filled slots */ + I32 size; /**< Buffer size */ +} RINGBUF; + +I16 ICACHE_FLASH_ATTR RINGBUF_Init(RINGBUF *r, U8* buf, I32 size); +I16 ICACHE_FLASH_ATTR RINGBUF_Put(RINGBUF *r, U8 c); +I16 ICACHE_FLASH_ATTR RINGBUF_Get(RINGBUF *r, U8* c); +#endif diff --git a/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/typedef.h b/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/typedef.h new file mode 100644 index 000000000..887001ace --- /dev/null +++ b/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/typedef.h @@ -0,0 +1,17 @@ +/** +* \file +* Standard Types definition +*/ + +#ifndef _TYPE_DEF_H_ +#define _TYPE_DEF_H_ + +typedef char I8; +typedef unsigned char U8; +typedef short I16; +typedef unsigned short U16; +typedef long I32; +typedef unsigned long U32; +typedef unsigned long long U64; + +#endif diff --git a/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/utils.c b/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/utils.c new file mode 100644 index 000000000..ac4c9272b --- /dev/null +++ b/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/utils.c @@ -0,0 +1,149 @@ +/* +* Copyright (c) 2014, Tuan PM +* Email: tuanpm@live.com +* +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions +* are met: +* +* 1. Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* 2. Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* 3. Neither the name of the copyright holder nor the names of its +* contributors may be used to endorse or promote products derived +* from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +* POSSIBILITY OF SUCH DAMAGE. +* +*/ +#include +#include +#include +#include +#include +#include "utils.h" + + +uint8_t ICACHE_FLASH_ATTR UTILS_IsIPV4 (int8_t *str) +{ + uint8_t segs = 0; /* Segment count. */ + uint8_t chcnt = 0; /* Character count within segment. */ + uint8_t accum = 0; /* Accumulator for segment. */ + /* Catch NULL pointer. */ + if (str == 0) + return 0; + /* Process every character in string. */ + + while (*str != '\0') { + /* Segment changeover. */ + + if (*str == '.') { + /* Must have some digits in segment. */ + if (chcnt == 0) + return 0; + /* Limit number of segments. */ + if (++segs == 4) + return 0; + /* Reset segment values and restart loop. */ + chcnt = accum = 0; + str++; + continue; + } + + /* Check numeric. */ + if ((*str < '0') || (*str > '9')) + return 0; + + /* Accumulate and check segment. */ + + if ((accum = accum * 10 + *str - '0') > 255) + return 0; + /* Advance other segment specific stuff and continue loop. */ + + chcnt++; + str++; + } + + /* Check enough segments and enough characters in last segment. */ + + if (segs != 3) + return 0; + if (chcnt == 0) + return 0; + /* Address okay. */ + + return 1; +} +uint8_t ICACHE_FLASH_ATTR UTILS_StrToIP(const int8_t* str, void *ip) +{ + + /* The count of the number of bytes processed. */ + int i; + /* A pointer to the next digit to process. */ + const char * start; + + start = str; + for (i = 0; i < 4; i++) { + /* The digit being processed. */ + char c; + /* The value of this byte. */ + int n = 0; + while (1) { + c = * start; + start++; + if (c >= '0' && c <= '9') { + n *= 10; + n += c - '0'; + } + /* We insist on stopping at "." if we are still parsing + the first, second, or third numbers. If we have reached + the end of the numbers, we will allow any character. */ + else if ((i < 3 && c == '.') || i == 3) { + break; + } + else { + return 0; + } + } + if (n >= 256) { + return 0; + } + ((uint8_t*)ip)[i] = n; + } + return 1; + +} +uint32_t ICACHE_FLASH_ATTR UTILS_Atoh(const int8_t *s) +{ + uint32_t value = 0, digit; + int8_t c; + + while ((c = *s++)) { + if ('0' <= c && c <= '9') + digit = c - '0'; + else if ('A' <= c && c <= 'F') + digit = c - 'A' + 10; + else if ('a' <= c && c <= 'f') + digit = c - 'a' + 10; + else break; + + value = (value << 4) | digit; + } + + return value; +} + diff --git a/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/utils.h b/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/utils.h new file mode 100644 index 000000000..fe2874803 --- /dev/null +++ b/lib/esp-mqtt-arduino-1.0.1.02.1/src/mqtt/utils.h @@ -0,0 +1,9 @@ +#ifndef _UTILS_H_ +#define _UTILS_H_ + +#include "c_types.h" + +uint32_t ICACHE_FLASH_ATTR UTILS_Atoh(const int8_t *s); +uint8_t ICACHE_FLASH_ATTR UTILS_StrToIP(const int8_t* str, void *ip); +uint8_t ICACHE_FLASH_ATTR UTILS_IsIPV4 (int8_t *str); +#endif diff --git a/platformio.ini b/platformio.ini index 6c1189860..6dcb92d54 100644 --- a/platformio.ini +++ b/platformio.ini @@ -12,34 +12,56 @@ src_dir = sonoff ; *** Uncomment one of the lines below to build/upload only one environment ;env_default = sonoff +;env_default = sonoff-minimal +;env_default = sonoff-classic +;env_default = sonoff-knx +;env_default = sonoff-allsensors +;env_default = sonoff-BG ;env_default = sonoff-CN +;env_default = sonoff-CZ ;env_default = sonoff-DE ;env_default = sonoff-ES ;env_default = sonoff-FR +;env_default = sonoff-GR +;env_default = sonoff-HU ;env_default = sonoff-IT ;env_default = sonoff-NL ;env_default = sonoff-PL -;env_default = sonoff-minimal -;env_default = sonoff-ds18x20 +;env_default = sonoff-PT +;env_default = sonoff-RU +;env_default = sonoff-TW -[env:sonoff] +[common] ; ************************************************************ +; *** Esp8266 core for Arduino version ;platform = espressif8266@1.5.0 ; v2.3.0 -;platform = espressif8266@1.6.0 ; v2.4.0 -platform = espressif8266 +platform = espressif8266@1.6.0 ; v2.4.0 +;platform = espressif8266@1.7.0 ; v2.4.1 +;platform = espressif8266 + framework = arduino board = esp01_1m board_flash_mode = dout -build_flags = -Wl,-Tesp8266.flash.1m0.ld -DMQTT_MAX_PACKET_SIZE=1000 -lib_deps = PubSubClient, NeoPixelBus, IRremoteESP8266, ArduinoJSON + +; *** Fix espressif8266@1.7.0 induced undesired all warnings +build_unflags = -Wall + +build_flags = + -Wl,-Tesp8266.flash.1m0.ld + -DVTABLES_IN_FLASH + -DPIO_FRAMEWORK_ARDUINO_LWIP2_LOW_MEMORY +; -DUSE_CONFIG_OVERRIDE + +; *** Fix Esp/Arduino core 2.4.x induced Tasmota unused floating point includes extra_scripts = pio/strip-floats.py ; *** Serial Monitor options monitor_baud = 115200 ; *** Upload Serial reset method for Wemos and NodeMCU -;upload_resetmethod = nodemcu -;upload_port = COM6 ;upload_speed = 115200 +upload_speed = 512000 +upload_resetmethod = nodemcu +upload_port = COM5 ; *** Upload file to OTA server using SCP ;upload_port = user@host:/path @@ -49,101 +71,233 @@ monitor_baud = 115200 ;upload_port = domus1:80/api/upload-arduino.php ;extra_scripts = pio/strip-floats.py, pio/http-uploader.py -[env:sonoff-CN] -;platform = espressif8266@1.5.0 ; v2.3.0 -;platform = espressif8266@1.6.0 ; v2.4.0 -platform = espressif8266 -framework = arduino -board = esp01_1m -board_flash_mode = dout -build_flags = -Wl,-Tesp8266.flash.1m0.ld -DMQTT_MAX_PACKET_SIZE=1000 -DMY_LANGUAGE=zh-CN -lib_deps = PubSubClient, NeoPixelBus, IRremoteESP8266, ArduinoJSON -extra_scripts = pio/strip-floats.py +; ********************************************************************* -[env:sonoff-DE] -;platform = espressif8266@1.5.0 ; v2.3.0 -;platform = espressif8266@1.6.0 ; v2.4.0 -platform = espressif8266 -framework = arduino -board = esp01_1m -board_flash_mode = dout -build_flags = -Wl,-Tesp8266.flash.1m0.ld -DMQTT_MAX_PACKET_SIZE=1000 -DMY_LANGUAGE=de-DE -lib_deps = PubSubClient, NeoPixelBus, IRremoteESP8266, ArduinoJSON -extra_scripts = pio/strip-floats.py - -[env:sonoff-ES] -;platform = espressif8266@1.5.0 ; v2.3.0 -;platform = espressif8266@1.6.0 ; v2.4.0 -platform = espressif8266 -framework = arduino -board = esp01_1m -board_flash_mode = dout -build_flags = -Wl,-Tesp8266.flash.1m0.ld -DMQTT_MAX_PACKET_SIZE=1000 -DMY_LANGUAGE=es-AR -lib_deps = PubSubClient, NeoPixelBus, IRremoteESP8266, ArduinoJSON -extra_scripts = pio/strip-floats.py - -[env:sonoff-FR] -;platform = espressif8266@1.5.0 ; v2.3.0 -;platform = espressif8266@1.6.0 ; v2.4.0 -platform = espressif8266 -framework = arduino -board = esp01_1m -board_flash_mode = dout -build_flags = -Wl,-Tesp8266.flash.1m0.ld -DMQTT_MAX_PACKET_SIZE=1000 -DMY_LANGUAGE=fr-FR -lib_deps = PubSubClient, NeoPixelBus, IRremoteESP8266, ArduinoJSON -extra_scripts = pio/strip-floats.py - -[env:sonoff-IT] -;platform = espressif8266@1.5.0 ; v2.3.0 -;platform = espressif8266@1.6.0 ; v2.4.0 -platform = espressif8266 -framework = arduino -board = esp01_1m -board_flash_mode = dout -build_flags = -Wl,-Tesp8266.flash.1m0.ld -DMQTT_MAX_PACKET_SIZE=1000 -DMY_LANGUAGE=it-IT -lib_deps = PubSubClient, NeoPixelBus, IRremoteESP8266, ArduinoJSON -extra_scripts = pio/strip-floats.py - -[env:sonoff-NL] -;platform = espressif8266@1.5.0 ; v2.3.0 -;platform = espressif8266@1.6.0 ; v2.4.0 -platform = espressif8266 -framework = arduino -board = esp01_1m -board_flash_mode = dout -build_flags = -Wl,-Tesp8266.flash.1m0.ld -DMQTT_MAX_PACKET_SIZE=1000 -DMY_LANGUAGE=nl-NL -lib_deps = PubSubClient, NeoPixelBus, IRremoteESP8266, ArduinoJSON -extra_scripts = pio/strip-floats.py - -[env:sonoff-PL] -;platform = espressif8266@1.5.0 ; v2.3.0 -;platform = espressif8266@1.6.0 ; v2.4.0 -platform = espressif8266 -framework = arduino -board = esp01_1m -board_flash_mode = dout -build_flags = -Wl,-Tesp8266.flash.1m0.ld -DMQTT_MAX_PACKET_SIZE=1000 -DMY_LANGUAGE=pl-PL -lib_deps = PubSubClient, NeoPixelBus, IRremoteESP8266, ArduinoJSON -extra_scripts = pio/strip-floats.py +[env:sonoff] +platform = ${common.platform} +framework = ${common.framework} +board = ${common.board} +board_flash_mode = ${common.board_flash_mode} +build_unflags = ${common.build_unflags} +build_flags = ${common.build_flags} +monitor_baud = ${common.monitor_baud} +upload_speed = ${common.upload_speed} +upload_resetmethod = ${common.upload_resetmethod} +upload_port = ${common.upload_port} +extra_scripts = ${common.extra_scripts} [env:sonoff-minimal] -platform = espressif8266@1.5.0 ; v2.3.0 -;platform = espressif8266@1.6.0 ; v2.4.0 -;platform = espressif8266 -framework = arduino -board = esp01_1m -board_flash_mode = dout -build_flags = -Wl,-Tesp8266.flash.1m0.ld -DMQTT_MAX_PACKET_SIZE=1000 -DBE_MINIMAL -lib_deps = PubSubClient, NeoPixelBus, IRremoteESP8266, ArduinoJSON -extra_scripts = pio/strip-floats.py +platform = ${common.platform} +framework = ${common.framework} +board = ${common.board} +board_flash_mode = ${common.board_flash_mode} +build_unflags = ${common.build_unflags} +build_flags = ${common.build_flags} -DBE_MINIMAL +monitor_baud = ${common.monitor_baud} +upload_speed = ${common.upload_speed} +upload_port = ${common.upload_port} +extra_scripts = ${common.extra_scripts} -[env:sonoff-ds18x20] -;platform = espressif8266@1.5.0 ; v2.3.0 -;platform = espressif8266@1.6.0 ; v2.4.0 -platform = espressif8266 -framework = arduino -board = esp01_1m -board_flash_mode = dout -build_flags = -Wl,-Tesp8266.flash.1m0.ld -DMQTT_MAX_PACKET_SIZE=1000 -DUSE_DS18x20 -lib_deps = PubSubClient, NeoPixelBus, IRremoteESP8266, ArduinoJSON -extra_scripts = pio/strip-floats.py +[env:sonoff-classic] +platform = ${common.platform} +framework = ${common.framework} +board = ${common.board} +board_flash_mode = ${common.board_flash_mode} +build_unflags = ${common.build_unflags} +build_flags = ${common.build_flags} -DUSE_CLASSIC +monitor_baud = ${common.monitor_baud} +upload_speed = ${common.upload_speed} +upload_port = ${common.upload_port} +extra_scripts = ${common.extra_scripts} + +[env:sonoff-knx] +platform = ${common.platform} +framework = ${common.framework} +board = ${common.board} +board_flash_mode = ${common.board_flash_mode} +build_unflags = ${common.build_unflags} +build_flags = ${common.build_flags} -DUSE_KNX_NO_EMULATION +monitor_baud = ${common.monitor_baud} +upload_speed = ${common.upload_speed} +upload_port = ${common.upload_port} +extra_scripts = ${common.extra_scripts} + +[env:sonoff-allsensors] +platform = ${common.platform} +framework = ${common.framework} +board = ${common.board} +board_flash_mode = ${common.board_flash_mode} +build_unflags = ${common.build_unflags} +build_flags = ${common.build_flags} -DUSE_ALL_SENSORS +monitor_baud = ${common.monitor_baud} +upload_speed = ${common.upload_speed} +upload_port = ${common.upload_port} +extra_scripts = ${common.extra_scripts} + +[env:sonoff-BG] +platform = ${common.platform} +framework = ${common.framework} +board = ${common.board} +board_flash_mode = ${common.board_flash_mode} +build_unflags = ${common.build_unflags} +build_flags = ${common.build_flags} -DMY_LANGUAGE=bg-BG +monitor_baud = ${common.monitor_baud} +upload_speed = ${common.upload_speed} +upload_port = ${common.upload_port} +extra_scripts = ${common.extra_scripts} + +[env:sonoff-CN] +platform = ${common.platform} +framework = ${common.framework} +board = ${common.board} +board_flash_mode = ${common.board_flash_mode} +build_unflags = ${common.build_unflags} +build_flags = ${common.build_flags} -DMY_LANGUAGE=zh-CN +monitor_baud = ${common.monitor_baud} +upload_speed = ${common.upload_speed} +upload_port = ${common.upload_port} +extra_scripts = ${common.extra_scripts} + +[env:sonoff-CZ] +platform = ${common.platform} +framework = ${common.framework} +board = ${common.board} +board_flash_mode = ${common.board_flash_mode} +build_unflags = ${common.build_unflags} +build_flags = ${common.build_flags} -DMY_LANGUAGE=cs-CZ +monitor_baud = ${common.monitor_baud} +upload_speed = ${common.upload_speed} +upload_port = ${common.upload_port} +extra_scripts = ${common.extra_scripts} + +[env:sonoff-DE] +platform = ${common.platform} +framework = ${common.framework} +board = ${common.board} +board_flash_mode = ${common.board_flash_mode} +build_unflags = ${common.build_unflags} +build_flags = ${common.build_flags} -DMY_LANGUAGE=de-DE +monitor_baud = ${common.monitor_baud} +upload_speed = ${common.upload_speed} +upload_port = ${common.upload_port} +extra_scripts = ${common.extra_scripts} + +[env:sonoff-ES] +platform = ${common.platform} +framework = ${common.framework} +board = ${common.board} +board_flash_mode = ${common.board_flash_mode} +build_unflags = ${common.build_unflags} +build_flags = ${common.build_flags} -DMY_LANGUAGE=es-AR +monitor_baud = ${common.monitor_baud} +upload_speed = ${common.upload_speed} +upload_port = ${common.upload_port} +extra_scripts = ${common.extra_scripts} + +[env:sonoff-FR] +platform = ${common.platform} +framework = ${common.framework} +board = ${common.board} +board_flash_mode = ${common.board_flash_mode} +build_unflags = ${common.build_unflags} +build_flags = ${common.build_flags} -DMY_LANGUAGE=fr-FR +monitor_baud = ${common.monitor_baud} +upload_speed = ${common.upload_speed} +upload_port = ${common.upload_port} +extra_scripts = ${common.extra_scripts} + +[env:sonoff-GR] +platform = ${common.platform} +framework = ${common.framework} +board = ${common.board} +board_flash_mode = ${common.board_flash_mode} +build_unflags = ${common.build_unflags} +build_flags = ${common.build_flags} -DMY_LANGUAGE=el-GR +monitor_baud = ${common.monitor_baud} +upload_speed = ${common.upload_speed} +upload_port = ${common.upload_port} +extra_scripts = ${common.extra_scripts} + +[env:sonoff-HU] +platform = ${common.platform} +framework = ${common.framework} +board = ${common.board} +board_flash_mode = ${common.board_flash_mode} +build_unflags = ${common.build_unflags} +build_flags = ${common.build_flags} -DMY_LANGUAGE=hu-HU +monitor_baud = ${common.monitor_baud} +upload_speed = ${common.upload_speed} +upload_port = ${common.upload_port} +extra_scripts = ${common.extra_scripts} + +[env:sonoff-IT] +platform = ${common.platform} +framework = ${common.framework} +board = ${common.board} +board_flash_mode = ${common.board_flash_mode} +build_unflags = ${common.build_unflags} +build_flags = ${common.build_flags} -DMY_LANGUAGE=it-IT +monitor_baud = ${common.monitor_baud} +upload_speed = ${common.upload_speed} +upload_port = ${common.upload_port} +extra_scripts = ${common.extra_scripts} + +[env:sonoff-NL] +platform = ${common.platform} +framework = ${common.framework} +board = ${common.board} +board_flash_mode = ${common.board_flash_mode} +build_unflags = ${common.build_unflags} +build_flags = ${common.build_flags} -DMY_LANGUAGE=nl-NL +monitor_baud = ${common.monitor_baud} +upload_speed = ${common.upload_speed} +upload_port = ${common.upload_port} +extra_scripts = ${common.extra_scripts} + +[env:sonoff-PL] +platform = ${common.platform} +framework = ${common.framework} +board = ${common.board} +board_flash_mode = ${common.board_flash_mode} +build_unflags = ${common.build_unflags} +build_flags = ${common.build_flags} -DMY_LANGUAGE=pl-PL +monitor_baud = ${common.monitor_baud} +upload_speed = ${common.upload_speed} +upload_port = ${common.upload_port} +extra_scripts = ${common.extra_scripts} + +[env:sonoff-PT] +platform = ${common.platform} +framework = ${common.framework} +board = ${common.board} +board_flash_mode = ${common.board_flash_mode} +build_unflags = ${common.build_unflags} +build_flags = ${common.build_flags} -DMY_LANGUAGE=pt-PT +monitor_baud = ${common.monitor_baud} +upload_speed = ${common.upload_speed} +upload_port = ${common.upload_port} +extra_scripts = ${common.extra_scripts} + +[env:sonoff-RU] +platform = ${common.platform} +framework = ${common.framework} +board = ${common.board} +board_flash_mode = ${common.board_flash_mode} +build_unflags = ${common.build_unflags} +build_flags = ${common.build_flags} -DMY_LANGUAGE=ru-RU +monitor_baud = ${common.monitor_baud} +upload_speed = ${common.upload_speed} +upload_port = ${common.upload_port} +extra_scripts = ${common.extra_scripts} + +[env:sonoff-TW] +platform = ${common.platform} +framework = ${common.framework} +board = ${common.board} +board_flash_mode = ${common.board_flash_mode} +build_unflags = ${common.build_unflags} +build_flags = ${common.build_flags} -DMY_LANGUAGE=zh-TW +monitor_baud = ${common.monitor_baud} +upload_speed = ${common.upload_speed} +upload_port = ${common.upload_port} +extra_scripts = ${common.extra_scripts} diff --git a/sonoff/_releasenotes.ino b/sonoff/_releasenotes.ino index ee3a01c5c..d08e1bb39 100644 --- a/sonoff/_releasenotes.ino +++ b/sonoff/_releasenotes.ino @@ -1,4 +1,100 @@ -/* 5.12.0 20180209 +/* 5.13.0 20180430 + * Change platformio option sonoff-ds18x20 to sonoff-allsensors enabling ds18x20 and all other sensors in one image + * Change status display of Ssid and SetOption + * Change default option SetOption15 from 0 to 1 providing better initial PWM experience + * Change webpage parameter communication + * Change max number of commands in Backlog from 15 to 30 and ignore commands overflowing + * Change TSL2561 driver to joba library and delete Adafruit library (#1644) + * Change default parameters in user_config.h to undefined for easy installation (#1851) + * Change max user configurable hold time from 10 to 25 seconds (#1851) + * Change Sonoff SC JSON format (#1939) + * Change Polish language to using Diacritics (#2005) + * Change user_config_override usage by providing user_config_override_sample.h (#2228) + * Change MQTT response topic for Energy changes from ENERGY to SENSOR (#2229, #2251) + * Change default Reset configuration time from 4 seconds to 40 seconds on Button hold (#2268) + * Change ESP8266 Analog JSON message from {"Analog0:123"} to {"ANALOG":{"A0:123"}} to accomodate rules (#2560) + * Change Counter JSON message from {"Counter1":0,"Counter3":0} to {"COUNTER":{"C1":0,"C3":0}} to accomodate rules + * Change ADS1115 JSON message from {"ADS1115":{"Analog0":123,"Analog1":123}} to {"ADS1115":{"A0":123,"A1":123}} + * Fix intermittent exception when dns lookup is used while sleep is enabled + * Fix 5.4.0 regression turning off single press after button hold during 4x hold time + * Fix possible wifi connection problem by erasing sdk configuration parameters + * Fix NTP sync to Thu Jan 01 08:00:10 1970 results in uptime 17651+ days (core2.4.1/sdk2.2.1) + * Fix MAX31850 higher temperatures (#1269) + * Fix freeing more code space when emulation is disabled (#1592) + * Fix providing web page configuratin option for Friendly Name when no device (relay or light) is configured (#1850) + * Fix compile error when define HOME_ASSISTANT_DISCOVERY_ENABLE is not set (#1937) + * Fix MQTT TLS fingerprint validation (#2033) + * Fix update temperature on DS18x20 drivers (#2328) + * Fix compile error when not defined USE_TIMERS (#2400) + * Fix configuration filename truncation when it contains spaces (#2484, #2490) + * Fix Energy Today and Yesterday overflow (#2543) + * Add serial debug info + * Add Portuguese language file + * Add Czech language file + * Add Bulgarian language file + * Add Domoticz dust (custom) sensors to PMS5003 and NovaFitness SDS drivers as PM1, PM2.5 and PM10 + * Add commands Publish, Rule, RuleTimer and Event. See Wiki about Rule restriction, usage and examples + * Add sonoff-classic, sonoff-allsensors and sonoff-knx + * Add some coloring to important web buttons + * Add support for sensor HC-SR04 ultrasonic (#113, #1964, #2444) + * Add define MQTT_TELE_RETAIN compile option default set to 0 (#1071) + * Add 16 timers using commands Timer and Timers (#1091) + * Add optional Timer configuration webpage to be enabled in user_config.h with define USE_TIMERS_WEB + * Add Multichannel Gas sensor using MultiChannel_Gas_Sensor library (#1245) + * Add Domoticz Battery and RSSI Quality (#1604) + * Add command HSBColor Hue,Sat,Bri (#1642, #2203) + * Add compile time support for WS2812 BRG and RBG led configurations to be defined in user_config.h (#1690) + * Add optional usage of %d or %X suffices in MQTT client to append chipid (#1871) + * Add optional usage of %d or %X suffices in MQTT topic to append chipid (#1871) + * Add optional usage of %d or %04d in ota url to be replaced with chipid (#1871) + * Add Sonoff Bridge command RfKey 5 to show current RF key values either default or learned (#1884) + * Add user configurable serial GPIOs to MagicHome and Arilux modules (#1887) + * Add Russian language file (#1909) + * Add Webserver upload preflight request support (#1927) + * Add Home Assistant clear other device (#1931) + * Add Restart time to Status 1 (#1938) + * Add optional TSL2561 driver using library Joba_Tsl2561 to be enabled in user_config.h with define USE_TSL2561_JOBA (#1951) + * Add support for sensor SHTC3 (#1967) + * Add compiler check for stable lwIP version v1.4 (#1940) + * Add support for multiple SHT3X sensors (#1949, #2110) + * Add always suffix with device number in Mqtt discovery topic (#1962) + * Add support for optional MQTT drivers to be selected in user_config.h (#1992) + * Add optional Arduino OTA support to be enabled in user_config.h (#1998) + * Add diacritics to Polish language file (#2005) + * Add Hungarian language file (#2024) + * Add support for Nova Fitness SDS011 and possibly SDS021 particle concentration sensor (#2070) + * Add single decimal precision to Nova Fitness SDS0x1 sensor values (#2093) + * Add Chinese (Traditional) in Taiwan language file (#2108) + * Add Sonoff SC domoticz support for Sound level as Counter and Air quality (#2118) + * Add a second TLS fingerprint to allow switching keys in TLS mode (#2033, #2102) + * Add display of remaining pulse time to command PulseTime (#2085) + * Add additional time offset to Wifi Retry based on device mac address (#2089) + * Add command Color6 RRGGBB for Clock hour marker color and command Rotation pixels for Clock rotation (#2092) + * Add HTML language header in local language (#2123) + * Add command PowerDelta 0..100 (percentage) to Energy monitoring devices to report on active power load change (#2157) + * Add Restart Reason to Status 1 report (#2161) + * Add command Channel 0..100 to control dimmer value for individual color channels (#2111, #2203) + * Add support for Hardware Serial bridge using commands SerialDelimiter, Baudrate and SerialSend. Supports 8N1 and text only (#2182) + * Add support for Software Serial bridge using commands SerialDelimiter, SBaudrate and SSerialSend. Supports 8N1 and text only (#2190) + * Add support for Zengge WF017 PWM Led strip controller (#2202) + * Add PWM status to command State if PWM enabled (#2203) + * Add all FriendlyNames to Status information (#2208) + * Add Channel status information (#2211) + * Add hexadecimal Data entry to command IrSend using 0x notation (#1290, #2314) + * Add Home Assistant MQTT Discovery for Buttons and change SetOption19 response (#2277) + * Add multiple color entry support for command Led like Led2 120000 001200 000012 setting led2 as Red, Led3 as Green and Led4 as Blue (#2303) + * Add hexadecimal RGB color entry on RGBCW leds (#2304) + * Add support for SGP30 gas and air quality sensor (#2307) + * Add optional Sunrise and Sunset timers with commands Latitide and Longitude to be enabled with define USE_SUNRISE in user_config.h (#2317) + * Add timer sunrise and sunset offset (#2378) + * Add user selectable defines for Sunrise/set Dawn option (#2378) + * Add optional KNX IP Protocol Support (#2402) + * Add random window to timers (#2447) + * Add Greek language file (#2491) + * Add support for Sonoff Pow R2 (#2340) + * Add GPIO_User to GPIO02 for all Sonoff T1 (#2524) + * + * 5.12.0 20180209 * Change library PubSubClient.h define MQTT_MAX_PACKET_SIZE from 512 to 1000 for Home Assistant support * Change relation of define MESSZ being dependent on PubSubClient.h define MQTT_MAX_PACKET_SIZE * Change command color parameter input checks to less strict for Home Assistant support diff --git a/sonoff/i18n.h b/sonoff/i18n.h index e9cbab9ef..f50242d86 100644 --- a/sonoff/i18n.h +++ b/sonoff/i18n.h @@ -46,8 +46,10 @@ #define D_JSON_COUNTER "Counter" #define D_JSON_CURRENT "Current" // As in Voltage and Current #define D_JSON_DATA "Data" +#define D_JSON_DISTANCE "Distance" #define D_JSON_DNSSERVER "DNSServer" #define D_JSON_DONE "Done" +#define D_JSON_ECO2 "eCO2" #define D_JSON_EMPTY "Empty" #define D_JSON_ENDDST "EndDST" // End Daylight Savings Time #define D_JSON_ERASE "Erase" @@ -63,6 +65,7 @@ #define D_JSON_GATEWAY "Gateway" #define D_JSON_HEAPSIZE "Heap" #define D_JSON_HIGH "High" +#define D_JSON_HSBCOLOR "HSBColor" #define D_JSON_HUMIDITY "Humidity" #define D_JSON_I2CSCAN_DEVICES_FOUND_AT "Device(s) found at" #define D_JSON_I2CSCAN_UNKNOWN_ERROR_AT "Unknown error at" @@ -96,11 +99,15 @@ #define D_JSON_SAVESTATE "SaveState" #define D_JSON_SDKVERSION "SDK" #define D_JSON_SELECTED "selected" +#define D_JSON_SERIALRECEIVED "SerialReceived" #define D_JSON_SSID "SSId" #define D_JSON_STARTDST "StartDST" // Start Daylight Savings Time #define D_JSON_STARTED "Started" +#define D_JSON_STARTUPUTC "StartupUTC" #define D_JSON_SUBNETMASK "Subnetmask" #define D_JSON_SUCCESSFUL "Successful" +#define D_JSON_SUNRISE "Sunrise" +#define D_JSON_SUNSET "Sunset" #define D_JSON_SWITCH "Switch" #define D_JSON_SYNC "Sync" #define D_JSON_TEMPERATURE "Temperature" @@ -108,6 +115,7 @@ #define D_JSON_TIME "Time" #define D_JSON_TODAY "Today" #define D_JSON_TOTAL "Total" +#define D_JSON_TVOC "TVOC" #define D_JSON_TYPE "Type" #define D_JSON_UPTIME "Uptime" #define D_JSON_UTC_TIME "UTC" @@ -131,28 +139,6 @@ #define D_RSLT_WARNING "WARNING" // Commands sonoff.ino -#define D_CMND_MQTTHOST "MqttHost" -#define D_CMND_MQTTPORT "MqttPort" -#define D_CMND_MQTTRETRY "MqttRetry" -#define D_CMND_STATETEXT "StateText" -#define D_CMND_MQTTFINGERPRINT "MqttFingerprint" -#define D_CMND_MQTTCLIENT "MqttClient" -#define D_CMND_MQTTUSER "MqttUser" -#define D_CMND_MQTTPASSWORD "MqttPassword" -#define D_CMND_FULLTOPIC "FullTopic" -#define D_CMND_PREFIX "Prefix" - #define PRFX_MAX_STRING_LENGTH 5 - #define D_CMND "cmnd" - #define D_STAT "stat" - #define D_TELE "tele" -#define D_CMND_GROUPTOPIC "GroupTopic" -#define D_CMND_TOPIC "Topic" -#define D_CMND_BUTTONTOPIC "ButtonTopic" -#define D_CMND_SWITCHTOPIC "SwitchTopic" -#define D_CMND_BUTTONRETAIN "ButtonRetain" -#define D_CMND_SWITCHRETAIN "SwitchRetain" -#define D_CMND_POWERRETAIN "PowerRetain" -#define D_CMND_SENSORRETAIN "SensorRetain" #define D_CMND_BACKLOG "Backlog" #define D_CMND_DELAY "Delay" #define D_CMND_STATUS "Status" @@ -237,18 +223,47 @@ #define D_CMND_ALTITUDE "Altitude" #define D_CMND_LEDPOWER "LedPower" #define D_CMND_LEDSTATE "LedState" -#define D_CMND_CFGDUMP "CfgDump" #define D_CMND_I2CSCAN "I2CScan" -#define D_CMND_EXCEPTION "Exception" +#define D_CMND_SERIALSEND "SerialSend" +#define D_CMND_SERIALDELIMITER "SerialDelimiter" +#define D_CMND_BAUDRATE "Baudrate" + +// Commands xdrv_00_mqtt.ino +#define D_CMND_MQTTHOST "MqttHost" +#define D_CMND_MQTTPORT "MqttPort" +#define D_CMND_MQTTRETRY "MqttRetry" +#define D_CMND_STATETEXT "StateText" +#define D_CMND_MQTTFINGERPRINT "MqttFingerprint" +#define D_CMND_MQTTCLIENT "MqttClient" +#define D_CMND_MQTTUSER "MqttUser" +#define D_CMND_MQTTPASSWORD "MqttPassword" +#define D_CMND_FULLTOPIC "FullTopic" +#define D_CMND_PREFIX "Prefix" + #define PRFX_MAX_STRING_LENGTH 5 + #define D_CMND "cmnd" + #define D_STAT "stat" + #define D_TELE "tele" +#define D_CMND_GROUPTOPIC "GroupTopic" +#define D_CMND_TOPIC "Topic" +#define D_CMND_BUTTONTOPIC "ButtonTopic" +#define D_CMND_SWITCHTOPIC "SwitchTopic" +#define D_CMND_BUTTONRETAIN "ButtonRetain" +#define D_CMND_SWITCHRETAIN "SwitchRetain" +#define D_CMND_POWERRETAIN "PowerRetain" +#define D_CMND_SENSORRETAIN "SensorRetain" +#define D_CMND_PUBLISH "Publish" // Commands xdrv_01_light.ino +#define D_CMND_CHANNEL "Channel" #define D_CMND_COLOR "Color" #define D_CMND_COLORTEMPERATURE "CT" #define D_CMND_DIMMER "Dimmer" +#define D_CMND_HSBCOLOR "HSBColor" #define D_CMND_LED "Led" #define D_CMND_LEDTABLE "LedTable" #define D_CMND_FADE "Fade" #define D_CMND_PIXELS "Pixels" +#define D_CMND_ROTATION "Rotation" #define D_CMND_SCHEME "Scheme" #define D_CMND_SPEED "Speed" #define D_CMND_WAKEUP "Wakeup" @@ -259,9 +274,9 @@ #define D_CMND_IRSEND "IRSend" #define D_JSON_INVALID_JSON "Invalid JSON" #define D_JSON_PROTOCOL_NOT_SUPPORTED "Protocol not supported" - #define D_JSON_IR_PROTOCOL "PROTOCOL" - #define D_JSON_IR_BITS "BITS" - #define D_JSON_IR_DATA "DATA" + #define D_JSON_IR_PROTOCOL "Protocol" + #define D_JSON_IR_BITS "Bits" + #define D_JSON_IR_DATA "Data" #define D_CMND_IRHVAC "IRHVAC" #define D_JSON_IRHVAC_VENDOR "VENDOR" #define D_JSON_IRHVAC_POWER "POWER" @@ -273,6 +288,7 @@ // Commands xdrv_03_energy.ino #define D_CMND_POWERLOW "PowerLow" #define D_CMND_POWERHIGH "PowerHigh" +#define D_CMND_POWERDELTA "PowerDelta" #define D_CMND_VOLTAGELOW "VoltageLow" #define D_CMND_VOLTAGEHIGH "VoltageHigh" #define D_CMND_CURRENTLOW "CurrentLow" @@ -334,8 +350,30 @@ #define D_CMND_DISP_SIZE "Size" #define D_CMND_DISP_TEXT "Text" +// Commands xdrv_08_serial_bridge.ino +#define D_CMND_SSERIALSEND "SSerialSend" +#define D_CMND_SBAUDRATE "SBaudrate" + #define D_JSON_SSERIALRECEIVED "SSerialReceived" + +// Commands xdrv_09_timers.ino +#define D_CMND_TIMER "Timer" + #define D_JSON_TIMER_ARM "Arm" + #define D_JSON_TIMER_MODE "Mode" + #define D_JSON_TIMER_TIME "Time" + #define D_JSON_TIMER_WINDOW "Window" + #define D_JSON_TIMER_DAYS "Days" + #define D_JSON_TIMER_REPEAT "Repeat" + #define D_JSON_TIMER_OUTPUT "Output" + #define D_JSON_TIMER_ACTION "Action" + #define D_JSON_TIMER_NO_DEVICE "No GPIO as output configured" +#define D_CMND_TIMERS "Timers" +#define D_CMND_LATITUDE "Latitude" +#define D_CMND_LONGITUDE "Longitude" + /********************************************************************************************/ +#define D_ASTERIX "********" + #ifndef MY_LANGUAGE #include "language/en-GB.h" #else @@ -356,7 +394,10 @@ enum UnitNames { UNIT_MILLIAMPERE, UNIT_MILLISECOND, UNIT_MINUTE, + UNIT_PPB, + UNIT_PPD, UNIT_PPM, + UNIT_PERCENTAGE, UNIT_PRESSURE, UNIT_SECOND, UNIT_SECTORS, @@ -373,7 +414,10 @@ const char kUnitNames[] PROGMEM = D_UNIT_MILLIAMPERE "|" D_UNIT_MILLISECOND "|" D_UNIT_MINUTE "|" + D_UNIT_PARTS_PER_BILLION "|" + D_UNIT_PARTS_PER_DECILITER "|" D_UNIT_PARTS_PER_MILLION "|" + "%|" D_UNIT_PRESSURE "|" D_UNIT_SECOND "|" D_UNIT_SECTORS "|" @@ -393,12 +437,15 @@ const char S_JSON_COMMAND_NVALUE_ACTIVE_NVALUE[] PROGMEM = "{\"%s\":\"%d (" D const char S_JSON_COMMAND_NVALUE[] PROGMEM = "{\"%s\":%d}"; const char S_JSON_COMMAND_LVALUE[] PROGMEM = "{\"%s\":%lu}"; const char S_JSON_COMMAND_SVALUE[] PROGMEM = "{\"%s\":\"%s\"}"; +const char S_JSON_COMMAND_ASTERIX[] PROGMEM = "{\"%s\":\"" D_ASTERIX "\"}"; const char S_JSON_COMMAND_XVALUE[] PROGMEM = "{\"%s\":%s}"; // %s must provide quotes on non-number const char S_JSON_COMMAND_INDEX_NVALUE[] PROGMEM = "{\"%s%d\":%d}"; const char S_JSON_COMMAND_INDEX_LVALUE[] PROGMEM = "{\"%s%d\":%lu}"; const char S_JSON_COMMAND_INDEX_SVALUE[] PROGMEM = "{\"%s%d\":\"%s\"}"; +const char S_JSON_COMMAND_INDEX_ASTERIX[] PROGMEM = "{\"%s%d\":\"" D_ASTERIX "\"}"; const char S_JSON_COMMAND_INDEX_SVALUE_SVALUE[] PROGMEM = "{\"%s%d\":\"%s%s\"}"; +const char S_JSON_COMMAND_INDEX_NVALUE_ACTIVE_NVALUE[] PROGMEM = "{\"%s%d\":\"%d (" D_JSON_ACTIVE " %d)\"}"; const char S_JSON_SENSOR_INDEX_NVALUE[] PROGMEM = "{\"" D_CMND_SENSOR "%d\":%d}"; const char S_JSON_SENSOR_INDEX_SVALUE[] PROGMEM = "{\"" D_CMND_SENSOR "%d\":\"%s\"}"; @@ -448,7 +495,7 @@ const char HTTP_SNS_SEAPRESSURE[] PROGMEM = "%s{s}%s " D_PRESSUREATSEALEVEL "{m} const char HTTP_SNS_ANALOG[] PROGMEM = "%s{s}%s " D_ANALOG_INPUT "%d{m}%d{e}"; // {s} = , {m} = , {e} = #if defined(USE_MHZ19) || defined(USE_SENSEAIR) -const char HTTP_SNS_CO2[] PROGMEM = "%s{s}%s " D_CO2 "{m}%d " D_UNIT_PARTS_PER_MILLION "{e}"; // {s} = , {m} = , {e} = +const char HTTP_SNS_CO2[] PROGMEM = "%s{s}%s " D_CO2 "{m}%d " D_UNIT_PARTS_PER_MILLION "{e}"; // {s} = , {m} = , {e} = #endif // USE_WEBSERVER const char S_MAIN_MENU[] PROGMEM = D_MAIN_MENU; @@ -468,4 +515,4 @@ const char S_INFORMATION[] PROGMEM = D_INFORMATION; const char S_RESTART[] PROGMEM = D_RESTART; #endif // USE_WEBSERVER -#endif // _I18N_H_ \ No newline at end of file +#endif // _I18N_H_ diff --git a/sonoff/language/bg-BG.h b/sonoff/language/bg-BG.h new file mode 100644 index 000000000..7f30252ec --- /dev/null +++ b/sonoff/language/bg-BG.h @@ -0,0 +1,505 @@ +/* + bg-BG.h - localization for Bulgaria - Bulgarian for Sonoff-Tasmota + + Copyright (C) 2018 Theo Arends + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifndef _LANGUAGE_BG_BG_H_ +#define _LANGUAGE_BG_BG_H_ + +/*************************** ATTENTION *******************************\ + * + * Due to memory constraints only UTF-8 is supported. + * To save code space keep text as short as possible. + * Time and Date provided by SDK can not be localized (yet). + * Use online command StateText to translate ON, OFF, HOLD and TOGGLE. + * Use online command Prefix to translate cmnd, stat and tele. + * + * Updated until v5.12.0m +\*********************************************************************/ + +//#define LANGUAGE_MODULE_NAME // Enable to display "Module Generic" (ie Spanish), Disable to display "Generic Module" (ie English) + +// HTML (ISO 639-1) Language Code +#define D_HTML_LANGUAGE "bg" + +// "2017-03-07T11:08:02" - ISO8601:2004 +#define D_YEAR_MONTH_SEPARATOR "-" +#define D_MONTH_DAY_SEPARATOR "-" +#define D_DATE_TIME_SEPARATOR "T" +#define D_HOUR_MINUTE_SEPARATOR ":" +#define D_MINUTE_SECOND_SEPARATOR ":" + +#define D_DAY3LIST "НедПонВтрСрдЧетПетСъб" +#define D_MONTH3LIST "ЯнуФевМарАпрМайЮниЮлиАвгСепОктНоеДек" + +// Non JSON decimal separator +#define D_DECIMAL_SEPARATOR "," + +// Common +#define D_ADMIN "Admin" +#define D_AIR_QUALITY "Качество на въздуха" +#define D_AP "Точка за достъп" // Access Point +#define D_AS "като" +#define D_AUTO "АВТОМАТИЧНО" +#define D_BLINK "Мигане вкл." +#define D_BLINKOFF "Мигане изкл." +#define D_BOOT_COUNT "Брой на стартиранията" +#define D_BRIGHTLIGHT "Яркост" +#define D_BUTTON "Бутон" +#define D_BY "от" // Written by me +#define D_BYTES "Байт" +#define D_CELSIUS "Целзий" +#define D_CO2 "Въглероден диоксид" +#define D_CODE "код" // Button code +#define D_COLDLIGHT "Хладна" +#define D_COMMAND "Команда" +#define D_CONNECTED "Свързан" +#define D_COUNT "Брой" +#define D_COUNTER "Брояч" +#define D_CURRENT "Ток" // As in Voltage and Current +#define D_DATA "Данни" +#define D_DARKLIGHT "Тъмна" +#define D_DEBUG "Дебъгване" +#define D_DISABLED "Деактивиран" +#define D_DISTANCE "Distance" +#define D_DNS_SERVER "DNS Сървър" +#define D_DONE "Изпълнено" +#define D_DST_TIME "DST" +#define D_ECO2 "eCO2" +#define D_EMULATION "Емулация" +#define D_ENABLED "Активиран" +#define D_ERASE "Изтриване" +#define D_ERROR "Грешка" +#define D_FAHRENHEIT "Фаренхайт" +#define D_FAILED "Неуспешно" +#define D_FALLBACK "Обратна връзка" +#define D_FALLBACK_TOPIC "Топик на обратната връзка" +#define D_FALSE "Невярно" +#define D_FILE "Файл" +#define D_FREE_MEMORY "Свободна памет" +#define D_GAS "Газ" +#define D_GATEWAY "Шлюз" +#define D_GROUP "Група" +#define D_HOST "Хост" +#define D_HOSTNAME "Име на хоста" +#define D_HUMIDITY "Влажност" +#define D_ILLUMINANCE "Осветеност" +#define D_IMMEDIATE "моментален" // Button immediate +#define D_INDEX "Индекс" +#define D_INFO "Информация" +#define D_INITIALIZED "Инициализирано" +#define D_IP_ADDRESS "IP адрес" +#define D_LIGHT "Светлина" +#define D_LWT "LWT" +#define D_MODULE "Модул" +#define D_MQTT "MQTT" +#define D_MULTI_PRESS "многократно натискане" +#define D_NOISE "Шум" +#define D_NONE "Няма" +#define D_OFF "Изкл." +#define D_OFFLINE "Офлайн" +#define D_OK "Ок" +#define D_ON "Вкл." +#define D_ONLINE "Онлайн" +#define D_PASSWORD "Парола" +#define D_PORT "Порт" +#define D_POWER_FACTOR "Фактор на мощността" +#define D_POWERUSAGE "Мощност" +#define D_PRESSURE "Налягане" +#define D_PRESSUREATSEALEVEL "Налягане на морското ниво" +#define D_PROGRAM_FLASH_SIZE "Размер на флаш паметта за програми" +#define D_PROGRAM_SIZE "Размер на програмата" +#define D_PROJECT "Проект" +#define D_RECEIVED "Получено" +#define D_RESTART "Рестарт" +#define D_RESTARTING "Рестартиране" +#define D_RESTART_REASON "Причина за рестарта" +#define D_RESTORE "възстановяване" +#define D_RETAINED "запазено" +#define D_RULE "Правило" +#define D_SAVE "Запис" +#define D_SENSOR "Датчик" +#define D_SSID "SSId" +#define D_START "Старт" +#define D_STD_TIME "STD" +#define D_STOP "Стоп" +#define D_SUBNET_MASK "Маска на подмрежата" +#define D_SUBSCRIBE_TO "Записване за" +#define D_SUCCESSFUL "Успешно" +#define D_SUNRISE "Изгрев" +#define D_SUNSET "Залез" +#define D_TEMPERATURE "Температура" +#define D_TO "към" +#define D_TOGGLE "Превключване" +#define D_TOPIC "Топик" +#define D_TRANSMIT "Предаване" +#define D_TRUE "Вярно" +#define D_TVOC "TVOC" +#define D_UPGRADE "Обновяване" +#define D_UPLOAD "Зареждане" +#define D_UPTIME "Време от стартирането" +#define D_USER "Потребител" +#define D_UTC_TIME "UTC" +#define D_UV_LEVEL "Ниво на ултравиолетово излъчване" +#define D_VERSION "Версия" +#define D_VOLTAGE "Напрежение" +#define D_WARMLIGHT "Топла" +#define D_WEB_SERVER "Уеб сървър" + +// sonoff.ino +#define D_WARNING_MINIMAL_VERSION "ПРЕДУПРЕЖДЕНИЕ Тази версия не поддържа постоянни настройки" +#define D_LEVEL_10 "ниво 1-0" +#define D_LEVEL_01 "ниво 0-1" +#define D_SERIAL_LOGGING_DISABLED "Серийния логинг изключен" +#define D_SYSLOG_LOGGING_REENABLED "Системния логинг активиран" + +#define D_SET_BAUDRATE_TO "Задаване скорост на предаване (Baudrate)" +#define D_RECEIVED_TOPIC "Получен топик" +#define D_DATA_SIZE "Размер на данните" +#define D_ANALOG_INPUT "Аналогов вход" + +// support.ino +#define D_OSWATCH "osWatch" +#define D_BLOCKED_LOOP "Блокиран цикъл" +#define D_WPS_FAILED_WITH_STATUS "WPS конфигурацията е НЕУСПЕШНА със статус" +#define D_ACTIVE_FOR_3_MINUTES "активно в течение на 3 минути" +#define D_FAILED_TO_START "неуспешно стартиране" +#define D_PATCH_ISSUE_2186 "Проблем с патч 2186" +#define D_CONNECTING_TO_AP "Свързване към точка за достъп" +#define D_IN_MODE "в режим" +#define D_CONNECT_FAILED_NO_IP_ADDRESS "Грешка при свързването, не е получен IP адрес" +#define D_CONNECT_FAILED_AP_NOT_REACHED "Грешка при свързването, точката за достъп е недостижима" +#define D_CONNECT_FAILED_WRONG_PASSWORD "Грешка при свързването, грешна парола към точката за достъп" +#define D_CONNECT_FAILED_AP_TIMEOUT "Грешка при свързването, превишено време за изчакване" +#define D_ATTEMPTING_CONNECTION "Опитва свързване..." +#define D_CHECKING_CONNECTION "Проверка на свързването..." +#define D_QUERY_DONE "Запитването е изпълнено. Намерена е услуга MQTT" +#define D_MQTT_SERVICE_FOUND "MQTT услуга е намерена на" +#define D_FOUND_AT "намерена в" +#define D_SYSLOG_HOST_NOT_FOUND "Хостът на системния лог не е намерен" + +// settings.ino +#define D_SAVED_TO_FLASH_AT "Запазено във флаш паметта на" +#define D_LOADED_FROM_FLASH_AT "Заредено от флаш паметта от" +#define D_USE_DEFAULTS "Използване на параметри по подразбиране" +#define D_ERASED_SECTOR "Изтрит сектор" + +// webserver.ino +#define D_MINIMAL_FIRMWARE_PLEASE_UPGRADE "Фърмуеър MINIMAL - моля надградете го" +#define D_WEBSERVER_ACTIVE_ON "Уеб сървърът е активен на" +#define D_WITH_IP_ADDRESS "с IP адрес" +#define D_WEBSERVER_STOPPED "Уеб сървърът е спрян" +#define D_FILE_NOT_FOUND "Файлът не е намерен" +#define D_REDIRECTED "Пренасочено към адаптивния портал" +#define D_WIFIMANAGER_SET_ACCESSPOINT_AND_STATION "Wifi мениджърът настройва точка за достъп и запомня станцията" +#define D_WIFIMANAGER_SET_ACCESSPOINT "Wifi мениджърът настрои точката за достъп" +#define D_TRYING_TO_CONNECT "Опит за свързване на устройството към мрежата" + +#define D_RESTART_IN "Рестарт след" +#define D_SECONDS "секунди" +#define D_DEVICE_WILL_RESTART "Устройството ще се рестартира след няколко секунди" +#define D_BUTTON_TOGGLE "Превключване" +#define D_CONFIGURATION "Конфигурация" +#define D_INFORMATION "Информация" +#define D_FIRMWARE_UPGRADE "Обновяване на фърмуеъра" +#define D_CONSOLE "Конзола" +#define D_CONFIRM_RESTART "Подтвърдете рестартирането" + +#define D_CONFIGURE_MODULE "Конфигурация на модула" +#define D_CONFIGURE_WIFI "Конфигурация на WiFi" +#define D_CONFIGURE_MQTT "Конфигурация на MQTT" +#define D_CONFIGURE_DOMOTICZ "Конфигурация на Domoticz" +#define D_CONFIGURE_LOGGING "Конфигурация на логинга" +#define D_CONFIGURE_OTHER "Драги конфигурации" +#define D_CONFIRM_RESET_CONFIGURATION "Потвърдете изчистването" +#define D_RESET_CONFIGURATION "Изчистване на конфигурацията" +#define D_BACKUP_CONFIGURATION "Запазване на конфигурацията" +#define D_RESTORE_CONFIGURATION "Възстановяване на конфигурацията" +#define D_MAIN_MENU "Основно меню" + +#define D_MODULE_PARAMETERS "Параметри на модула" +#define D_MODULE_TYPE "Тип на модула" +#define D_GPIO "GPIO" +#define D_SERIAL_IN "Сериен вход" +#define D_SERIAL_OUT "Сериен изход" + +#define D_WIFI_PARAMETERS "Wifi параметри" +#define D_SCAN_FOR_WIFI_NETWORKS "Сканиране за безжични мрежи" +#define D_SCAN_DONE "Сканирането приключи" +#define D_NO_NETWORKS_FOUND "Не бяха открити мрежи" +#define D_REFRESH_TO_SCAN_AGAIN "Обновяване за повторно сканиране" +#define D_DUPLICATE_ACCESSPOINT "Дублиране на точката за достъп (AP)" +#define D_SKIPPING_LOW_QUALITY "Пропускане поради лошо качество" +#define D_RSSI "RSSI" +#define D_WEP "WEP" +#define D_WPA_PSK "WPA PSK" +#define D_WPA2_PSK "WPA2 PSK" +#define D_AP1_SSID "AP1 SSId" +#define D_AP1_PASSWORD "AP1 Парола" +#define D_AP2_SSID "AP2 SSId" +#define D_AP2_PASSWORD "AP2 Парола" + +#define D_MQTT_PARAMETERS "Параметри на MQTT" +#define D_CLIENT "Клиент" +#define D_FULL_TOPIC "Пълен топик" + +#define D_LOGGING_PARAMETERS "Параметри на логинга" +#define D_SERIAL_LOG_LEVEL "Степен на серийния лог" +#define D_WEB_LOG_LEVEL "Степен на Уеб лога" +#define D_SYS_LOG_LEVEL "Степен на системния лог" +#define D_MORE_DEBUG "Още дебъгване" +#define D_SYSLOG_HOST "Хост на системния лог" +#define D_SYSLOG_PORT "Порт на системния лог" +#define D_TELEMETRY_PERIOD "Период на телеметрия" + +#define D_OTHER_PARAMETERS "Други параметри" +#define D_WEB_ADMIN_PASSWORD "Парола на уеб администратора" +#define D_MQTT_ENABLE "активиране на MQTT" +#define D_FRIENDLY_NAME "приятелско име" +#define D_BELKIN_WEMO "Belkin WeMo" +#define D_HUE_BRIDGE "Hue Bridge" +#define D_SINGLE_DEVICE "единично" +#define D_MULTI_DEVICE "мулти" + +#define D_SAVE_CONFIGURATION "Запазване на конфигурацията" +#define D_CONFIGURATION_SAVED "Конфигурацията е запазена" +#define D_CONFIGURATION_RESET "Конфигурацията е изчистена" + +#define D_PROGRAM_VERSION "Версия на програмата" +#define D_BUILD_DATE_AND_TIME "Дата и час на компилацията" +#define D_CORE_AND_SDK_VERSION "Версия на Core/SDK" +#define D_FLASH_WRITE_COUNT "Брой на записите във флаш паметта" +#define D_MAC_ADDRESS "MAC адрес" +#define D_MQTT_HOST "MQTT хост" +#define D_MQTT_PORT "MQTT порт" +#define D_MQTT_CLIENT "MQTT ID на клиент" +#define D_MQTT_USER "MQTT потребител" +#define D_MQTT_TOPIC "MQTT топик" +#define D_MQTT_GROUP_TOPIC "MQTT групов топик" +#define D_MQTT_FULL_TOPIC "MQTT пълен топик" +#define D_MDNS_DISCOVERY "mDNS откриване" +#define D_MDNS_ADVERTISE "mDNS транслация" +#define D_ESP_CHIP_ID "ID на чипа ESP" +#define D_FLASH_CHIP_ID "ID на чипа на флаш паметта" +#define D_FLASH_CHIP_SIZE "Размер на флаш паметта" +#define D_FREE_PROGRAM_SPACE "Свободно пространство за програми" + +#define D_UPGRADE_BY_WEBSERVER "Обновяване чрез уеб сървър" +#define D_OTA_URL "OTA Url" +#define D_START_UPGRADE "Започване на обновяване" +#define D_UPGRADE_BY_FILE_UPLOAD "Обновяване чрез зареждане на файл" +#define D_UPLOAD_STARTED "Зареждането започна" +#define D_UPGRADE_STARTED "Обновяването започна" +#define D_UPLOAD_DONE "Зареждането завърши" +#define D_UPLOAD_ERR_1 "Не е избран файл" +#define D_UPLOAD_ERR_2 "Недостатъчно свободно място" +#define D_UPLOAD_ERR_3 "Magic байтът не е 0xE9" +#define D_UPLOAD_ERR_4 "Размерът на програмата е по-голям от реалния размер на флаш паметта" +#define D_UPLOAD_ERR_5 "Грешка при зареждането в буфера" +#define D_UPLOAD_ERR_6 "Грешка пр зареждането. Включено е ниво 3 на лога" +#define D_UPLOAD_ERR_7 "Зареждането е прекъснато" +#define D_UPLOAD_ERR_8 "Файлът е невалиден" +#define D_UPLOAD_ERR_9 "Файлът е прекалено голям" +#define D_UPLOAD_ERROR_CODE "Код на грешка при зареждането" + +#define D_ENTER_COMMAND "Въвеждане на команда" +#define D_ENABLE_WEBLOG_FOR_RESPONSE "Включете ниво 2 на лога, ако очаквате отговор" +#define D_NEED_USER_AND_PASSWORD "Очаква user=&password=" + +// xdrv_00_mqtt.ino +#define D_FINGERPRINT "Проверка на TLS отпечатък..." +#define D_TLS_CONNECT_FAILED_TO "Неуспешно TLS свързване към" +#define D_RETRY_IN "Повторно след" +#define D_VERIFIED "Проверен отпечтък" +#define D_INSECURE "Нешифрована връзка, недействителен отпечатък" +#define D_CONNECT_FAILED_TO "Грешка при свързването към" + +// xdrv_wemohue.ino +#define D_MULTICAST_DISABLED "Multicast е изключен" +#define D_MULTICAST_REJOINED "Multicast е повторно съединен" +#define D_MULTICAST_JOIN_FAILED "Multicast грешка при присъединяването" +#define D_FAILED_TO_SEND_RESPONSE "Не се получи изпращането на отговор" + +#define D_WEMO "WeMo" +#define D_WEMO_BASIC_EVENT "WeMo главно събитие" +#define D_WEMO_EVENT_SERVICE "WeMo услуга за събитията" +#define D_WEMO_META_SERVICE "WeMo мета-услуга" +#define D_WEMO_SETUP "WeMo настройка" +#define D_RESPONSE_SENT "Отговорът е изпратен" + +#define D_HUE "Hue" +#define D_HUE_BRIDGE_SETUP "Hue мост настройка" +#define D_HUE_API_NOT_IMPLEMENTED "Hue API не е внедрено" +#define D_HUE_API "Hue API" +#define D_HUE_POST_ARGS "Hue POST аргументи" +#define D_3_RESPONSE_PACKETS_SENT "Изпратени са 3 пакета за отговор" + +// xdrv_05_domoticz.ino +#define D_DOMOTICZ_PARAMETERS "Domoticz параметри" +#define D_DOMOTICZ_IDX "Idx" +#define D_DOMOTICZ_KEY_IDX "Key idx" +#define D_DOMOTICZ_SWITCH_IDX "Switch idx" +#define D_DOMOTICZ_SENSOR_IDX "Sensor idx" + #define D_DOMOTICZ_TEMP "Temp" + #define D_DOMOTICZ_TEMP_HUM "Temp,Hum" + #define D_DOMOTICZ_TEMP_HUM_BARO "Temp,Hum,Baro" + #define D_DOMOTICZ_POWER_ENERGY "Power,Energy" + #define D_DOMOTICZ_ILLUMINANCE "Illuminance" + #define D_DOMOTICZ_COUNT "Count/PM1" + #define D_DOMOTICZ_VOLTAGE "Voltage/PM2,5" + #define D_DOMOTICZ_CURRENT "Current/PM10" + #define D_DOMOTICZ_AIRQUALITY "AirQuality" +#define D_DOMOTICZ_UPDATE_TIMER "Update timer" + +// xdrv_09_timers.ino +#define D_CONFIGURE_TIMER "Конфигуриране на таймер" +#define D_TIMER_PARAMETERS "Параметри на таймера" +#define D_TIMER_ARM "Arm" +#define D_TIMER_TIME "Време" +#define D_TIMER_DAYS "Дни" +#define D_TIMER_REPEAT "Повтори" +#define D_TIMER_OUTPUT "Изход" +#define D_TIMER_ACTION "Действие" + +// xdrv_10_knx.ino +#define D_CONFIGURE_KNX "Конфигуриране на KNX" +#define D_KNX_PARAMETERS "KNX параметри" +#define D_KNX_GENERAL_CONFIG "Основни" +#define D_KNX_PHYSICAL_ADDRESS "Физически адрес" +#define D_KNX_PHYSICAL_ADDRESS_NOTE "( Трябва да е уникален в KNX мрежата )" +#define D_KNX_ENABLE "Активиране на KNX" +#define D_KNX_GROUP_ADDRESS_TO_WRITE "Групови адреси за изпращане на данни" +#define D_ADD "Добаване" +#define D_DELETE "Изтриване" +#define D_REPLY "Отговор" +#define D_KNX_GROUP_ADDRESS_TO_READ "Групови адреси за получаване на данни" +#define D_LOG_KNX "KNX: " +#define D_RECEIVED_FROM "Получен от" +#define D_KNX_COMMAND_WRITE "Писане" +#define D_KNX_COMMAND_READ "Четене" +#define D_KNX_COMMAND_OTHER "Друго" +#define D_SENT_TO "изпратен до" +#define D_KNX_WARNING "Груповият адрес ( 0 / 0 / 0 ) е резервиран и не може да бъде използван." + +// xdrv_03_energy.ino +#define D_ENERGY_TODAY "Използвана енергия днес" +#define D_ENERGY_YESTERDAY "Използвана енергия вчера" +#define D_ENERGY_TOTAL "Използвана енергия общо" + +// xsns_05_ds18b20.ino +#define D_SENSOR_BUSY "Датчикът DS18x20 е зает" +#define D_SENSOR_CRC_ERROR "Датчик DS18x20 - грешка CRC" +#define D_SENSORS_FOUND "Намерен е датчик DS18x20" + +// xsns_06_dht.ino +#define D_TIMEOUT_WAITING_FOR "Изтекло време за очакване на" +#define D_START_SIGNAL_LOW "стартов сигнал нисък" +#define D_START_SIGNAL_HIGH "стартов сигнал висок" +#define D_PULSE "импулс" +#define D_CHECKSUM_FAILURE "Грешка в контролната сума" + +// xsns_07_sht1x.ino +#define D_SENSOR_DID_NOT_ACK_COMMAND "Датчикът не прие команда ACK" +#define D_SHT1X_FOUND "Намерен е SHT1X" + +// xsns_18_pms5003.ino +#define D_STANDARD_CONCENTRATION "CF-1 PM" // Standard Particle CF-1 Particle Matter +#define D_ENVIRONMENTAL_CONCENTRATION "PM" // Environmetal Particle Matter +#define D_PARTICALS_BEYOND "Particals" + +// sonoff_template.h +#define D_SENSOR_NONE "няма" +#define D_SENSOR_DHT11 "DHT11" +#define D_SENSOR_AM2301 "AM2301" +#define D_SENSOR_SI7021 "SI7021" +#define D_SENSOR_DS18X20 "DS18x20" +#define D_SENSOR_I2C_SCL "I2C SCL" +#define D_SENSOR_I2C_SDA "I2C SDA" +#define D_SENSOR_WS2812 "WS2812" +#define D_SENSOR_IRSEND "IRsend" +#define D_SENSOR_SWITCH "Ключ" // Suffix "1" +#define D_SENSOR_BUTTON "Бутон" // Suffix "1" +#define D_SENSOR_RELAY "Реле" // Suffix "1i" +#define D_SENSOR_LED "Led" // Suffix "1i" +#define D_SENSOR_PWM "PWM" // Suffix "1" +#define D_SENSOR_COUNTER "Брояч" // Suffix "1" +#define D_SENSOR_IRRECV "IRrecv" +#define D_SENSOR_MHZ_RX "MHZ Rx" +#define D_SENSOR_MHZ_TX "MHZ Tx" +#define D_SENSOR_PZEM_RX "PZEM Rx" +#define D_SENSOR_PZEM_TX "PZEM Tx" +#define D_SENSOR_SAIR_RX "SAir Rx" +#define D_SENSOR_SAIR_TX "SAir Tx" +#define D_SENSOR_SPI_CS "SPI CS" +#define D_SENSOR_SPI_DC "SPI DC" +#define D_SENSOR_BACKLIGHT "Подсветка" +#define D_SENSOR_PMS5003 "PMS5003" +#define D_SENSOR_SDS0X1 "SDS0X1" +#define D_SENSOR_SBR_RX "SerBr Rx" +#define D_SENSOR_SBR_TX "SerBr Tx" +#define D_SENSOR_SR04_TRIG "SR04 Tri" +#define D_SENSOR_SR04_ECHO "SR04 Ech" + +// Units +#define D_UNIT_AMPERE "А" +#define D_UNIT_CENTIMETER "см" +#define D_UNIT_HOUR "ч" +#define D_UNIT_KILOOHM "кОм" +#define D_UNIT_KILOWATTHOUR "кВт/ч" +#define D_UNIT_LUX "лукс" +#define D_UNIT_MICROGRAM_PER_CUBIC_METER "микрограм/м3" +#define D_UNIT_MICROMETER "микрометър" +#define D_UNIT_MICROSECOND "микросек" +#define D_UNIT_MILLIAMPERE "мА" +#define D_UNIT_MILLISECOND "мсек" +#define D_UNIT_MINUTE "мин" +#define D_UNIT_PARTS_PER_BILLION "ppb" +#define D_UNIT_PARTS_PER_DECILITER "ppd" +#define D_UNIT_PARTS_PER_MILLION "ppm" +#define D_UNIT_PRESSURE "хПа" +#define D_UNIT_SECOND "сек" +#define D_UNIT_SECTORS "сектори" +#define D_UNIT_VOLT "В" +#define D_UNIT_WATT "Вт" +#define D_UNIT_WATTHOUR "Вт/ч" + +// Log message prefix +#define D_LOG_APPLICATION "APP: " // Application +#define D_LOG_BRIDGE "BRG: " // Bridge +#define D_LOG_CONFIG "CFG: " // Settings +#define D_LOG_COMMAND "CMD: " // Command +#define D_LOG_DEBUG "DBG: " // Debug +#define D_LOG_DHT "DHT: " // DHT sensor +#define D_LOG_DOMOTICZ "DOM: " // Domoticz +#define D_LOG_DSB "DSB: " // DS18xB20 sensor +#define D_LOG_HTTP "HTP: " // HTTP webserver +#define D_LOG_I2C "I2C: " // I2C +#define D_LOG_IRR "IRR: " // Infra Red Received +#define D_LOG_LOG "LOG: " // Logging +#define D_LOG_MODULE "MOD: " // Module +#define D_LOG_MDNS "DNS: " // mDNS +#define D_LOG_MQTT "MQT: " // MQTT +#define D_LOG_OTHER "OTH: " // Other +#define D_LOG_RESULT "RSL: " // Result +#define D_LOG_RFR "RFR: " // RF Received +#define D_LOG_SERIAL "SER: " // Serial +#define D_LOG_SHT1 "SHT: " // SHT1x sensor +#define D_LOG_UPLOAD "UPL: " // Upload +#define D_LOG_UPNP "UPP: " // UPnP +#define D_LOG_WIFI "WIF: " // Wifi + +#endif // _LANGUAGE_BG_BG_H_ diff --git a/sonoff/language/cs-CZ.h b/sonoff/language/cs-CZ.h new file mode 100644 index 000000000..a52f31901 --- /dev/null +++ b/sonoff/language/cs-CZ.h @@ -0,0 +1,505 @@ +/* + cs-CZ.h - localization for Czech with diacritics - Czech for Sonoff-Tasmota + + Copyright (C) 2018 Vladimír Synek + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifndef _LANGUAGE_CS_CZ_H_ +#define _LANGUAGE_CS_CZ_H_ + +/*************************** ATTENTION *******************************\ + * + * Due to memory constraints only UTF-8 is supported. + * To save code space keep text as short as possible. + * Time and Date provided by SDK can not be localized (yet). + * Use online command StateText to translate ON, OFF, HOLD and TOGGLE. + * Use online command Prefix to translate cmnd, stat and tele. + * + * Updated until v5.12.0n +\*********************************************************************/ + +//#define LANGUAGE_MODULE_NAME // Enable to display "Module Generic" (ie Spanish), Disable to display "Generic Module" (ie English) + +// HTML (ISO 639-1) Language Code +#define D_HTML_LANGUAGE "cs" + +// "2017-03-07T11:08:02" - ISO8601:2004 +#define D_YEAR_MONTH_SEPARATOR "-" +#define D_MONTH_DAY_SEPARATOR "-" +#define D_DATE_TIME_SEPARATOR "T" +#define D_HOUR_MINUTE_SEPARATOR ":" +#define D_MINUTE_SECOND_SEPARATOR ":" + +#define D_DAY3LIST "Ne Po Út St Čt Pá So " +#define D_MONTH3LIST "LedÚnoBřeDubKvěČvnČvcSrpZářŘíjLisPro" + +// Non JSON decimal separator +#define D_DECIMAL_SEPARATOR "," + +// Common +#define D_ADMIN "Admin" +#define D_AIR_QUALITY "Kvalita vzduchu" +#define D_AP "AP" // Access Point +#define D_AS "jako" +#define D_AUTO "AUTO" +#define D_BLINK "Blikání" +#define D_BLINKOFF "BlikáníVyp" +#define D_BOOT_COUNT "Počítadlo spuštění" +#define D_BRIGHTLIGHT "Světlý" +#define D_BUTTON "Tlačítko" +#define D_BY "by" // Written by me +#define D_BYTES "Bytů" +#define D_CELSIUS "°C" +#define D_CO2 "CO2" +#define D_CODE "kód" // Button code +#define D_COLDLIGHT "Studené světlo" +#define D_COMMAND "Příkaz" +#define D_CONNECTED "...připojeno" +#define D_COUNT "Počítej" +#define D_COUNTER "Počítadlo" +#define D_CURRENT "Proud" // As in Voltage and Current +#define D_DATA "Data" +#define D_DARKLIGHT "Tmavý" +#define D_DEBUG "Debug" +#define D_DISABLED "Zablokováno" +#define D_DISTANCE "Distance" +#define D_DNS_SERVER "Server DNS" +#define D_DONE "Provedeno" +#define D_DST_TIME "DST" +#define D_ECO2 "eCO2" +#define D_EMULATION "Emulace" +#define D_ENABLED "Otevřený" +#define D_ERASE "Smaž" +#define D_ERROR "Chyba" +#define D_FAHRENHEIT "Fahrenheita" +#define D_FAILED "chyba" +#define D_FALLBACK "Záložní" +#define D_FALLBACK_TOPIC "Záložní topic" +#define D_FALSE "Nepravda" +#define D_FILE "Soubor" +#define D_FREE_MEMORY "Volná paměť" +#define D_GAS "Plyn" +#define D_GATEWAY "Výchozí brána" +#define D_GROUP "Skupina" +#define D_HOST "Server" +#define D_HOSTNAME "Název serveru" +#define D_HUMIDITY "Vlhkost" +#define D_ILLUMINANCE "Osvětlení" +#define D_IMMEDIATE "Okamžité" // Button immediate +#define D_INDEX "Index" +#define D_INFO "Informace" +#define D_INITIALIZED "Inicializovaný" +#define D_IP_ADDRESS "Adresa IP" +#define D_LIGHT "Světlo" +#define D_LWT "LWT" +#define D_MODULE "Modul" +#define D_MQTT "MQTT" +#define D_MULTI_PRESS "několikeré-stisknutí" +#define D_NOISE "Hluk" +#define D_NONE "Žádný" +#define D_OFF "Vyp." +#define D_OFFLINE "Neaktivní" +#define D_OK "OK" +#define D_ON "Zap." +#define D_ONLINE "Aktivní" +#define D_PASSWORD "Heslo" +#define D_PORT "Port" +#define D_POWER_FACTOR "Účiník" +#define D_POWERUSAGE "Příkon" +#define D_PRESSURE "Tlak" +#define D_PRESSUREATSEALEVEL "Tlak na úrovni hladiny moře" +#define D_PROGRAM_FLASH_SIZE "Velikost paměti flash" +#define D_PROGRAM_SIZE "Velikost programu" +#define D_PROJECT "Projekt" +#define D_RECEIVED "Přijatý" +#define D_RESTART "Restart" +#define D_RESTARTING "Restartování" +#define D_RESTART_REASON "Příčina restartu" +#define D_RESTORE "Obnovit" +#define D_RETAINED "Zachováno" +#define D_RULE "Rule" +#define D_SAVE "Ulož" +#define D_SENSOR "Sensor" +#define D_SSID "SSID" +#define D_START "Start" +#define D_STD_TIME "STD" +#define D_STOP "Stop" +#define D_SUBNET_MASK "Maska podsítě" +#define D_SUBSCRIBE_TO "Přihlaš se do" +#define D_SUCCESSFUL "úspěšné." +#define D_SUNRISE "Svítání" +#define D_SUNSET "Soumrak" +#define D_TEMPERATURE "Teplota" +#define D_TO "do" +#define D_TOGGLE "Přepni" +#define D_TOPIC "Topic" +#define D_TRANSMIT "Odešli" +#define D_TRUE "Pravda" +#define D_TVOC "TVOC" +#define D_UPGRADE "aktualizace" +#define D_UPLOAD "Nahrání..." +#define D_UPTIME "Uptime" +#define D_USER "Uživatel" +#define D_UTC_TIME "UTC" +#define D_UV_LEVEL "úroveň UV" +#define D_VERSION "Verze" +#define D_VOLTAGE "Napětí" +#define D_WARMLIGHT "Teplé světlo" +#define D_WEB_SERVER "Web Server" + +// sonoff.ino +#define D_WARNING_MINIMAL_VERSION "UPOZORNĚNÍ Tato verze nepodporuje trvalé nastavení" +#define D_LEVEL_10 "úroveň 1-0" +#define D_LEVEL_01 "úroveň 0-1" +#define D_SERIAL_LOGGING_DISABLED "Logování na sériovém portu ukončeno" +#define D_SYSLOG_LOGGING_REENABLED "Obnoven zápis do Syslog" + +#define D_SET_BAUDRATE_TO "Nastavení rychlosti přenosu na" +#define D_RECEIVED_TOPIC "Přijatý topic" +#define D_DATA_SIZE "Velikost dat" +#define D_ANALOG_INPUT "Analogový vstup" + +// support.ino +#define D_OSWATCH "osWatch" +#define D_BLOCKED_LOOP "Zablokování smyčky" +#define D_WPS_FAILED_WITH_STATUS "Chyba WPSconfig se statusem" +#define D_ACTIVE_FOR_3_MINUTES "aktivní 3 minuty" +#define D_FAILED_TO_START "nepodařilo se spustit" +#define D_PATCH_ISSUE_2186 "Chyba 2186" +#define D_CONNECTING_TO_AP "Připojování k AP" +#define D_IN_MODE "v módu" +#define D_CONNECT_FAILED_NO_IP_ADDRESS "Chyba připojení, nebyla obdržena IP adresa" +#define D_CONNECT_FAILED_AP_NOT_REACHED "Chyba připojení, nedostupný AP" +#define D_CONNECT_FAILED_WRONG_PASSWORD "Chyba připojení, nesprávné heslo pro AP" +#define D_CONNECT_FAILED_AP_TIMEOUT "Chyba připojení, uplynul AP timeout" +#define D_ATTEMPTING_CONNECTION "Připojování..." +#define D_CHECKING_CONNECTION "Zkouška spojení..." +#define D_QUERY_DONE "Vyslání dotazu. Nalezena služba MQTT" +#define D_MQTT_SERVICE_FOUND "Služba MQTT byla nalezena" +#define D_FOUND_AT "znalezeno v" +#define D_SYSLOG_HOST_NOT_FOUND "Syslog Host nebyl nalezen" + +// settings.ino +#define D_SAVED_TO_FLASH_AT "Uloženo do paměti flash v" +#define D_LOADED_FROM_FLASH_AT "Staženo z paměti flash z" +#define D_USE_DEFAULTS "Použij defaultní hodnoty" +#define D_ERASED_SECTOR "Smazaný sektor" + +// webserver.ino +#define D_MINIMAL_FIRMWARE_PLEASE_UPGRADE "Firmware MINIMÁLNÍ - prosím zaktualizujte" +#define D_WEBSERVER_ACTIVE_ON "Aktivní Web server" +#define D_WITH_IP_ADDRESS "na IP adrese" +#define D_WEBSERVER_STOPPED "Web server zastaven" +#define D_FILE_NOT_FOUND "Soubor nebyl nalezen" +#define D_REDIRECTED "Přesměrování na vlastní portál" +#define D_WIFIMANAGER_SET_ACCESSPOINT_AND_STATION "Wi-Fi manager nastaví AP a zachová STA" +#define D_WIFIMANAGER_SET_ACCESSPOINT "Wi-Fi manager nastaví Access Point" +#define D_TRYING_TO_CONNECT "Zkouším připojit zařízení k síti" + +#define D_RESTART_IN "Restart" +#define D_SECONDS "sekund" +#define D_DEVICE_WILL_RESTART "Zařízení bude zrestartováno během několika sekund" +#define D_BUTTON_TOGGLE "Přepínač" +#define D_CONFIGURATION "Nastavení" +#define D_INFORMATION "Informace" +#define D_FIRMWARE_UPGRADE "Aktualizace firmware" +#define D_CONSOLE "Konzole" +#define D_CONFIRM_RESTART "Potvrzení restartu" + +#define D_CONFIGURE_MODULE "Nastavení modulu" +#define D_CONFIGURE_WIFI "Nastavení WiFi" +#define D_CONFIGURE_MQTT "Nastavení MQTT" +#define D_CONFIGURE_DOMOTICZ "Nastavení Domoticz" +#define D_CONFIGURE_LOGGING "Nastavení logování" +#define D_CONFIGURE_OTHER "Jiná nastavení" +#define D_CONFIRM_RESET_CONFIGURATION "Potvrzení resetu nastavení" +#define D_RESET_CONFIGURATION "Reset nastavení" +#define D_BACKUP_CONFIGURATION "Záloha nastavení" +#define D_RESTORE_CONFIGURATION "Obnovení nastavení" +#define D_MAIN_MENU "Hlavní menu" + +#define D_MODULE_PARAMETERS "Nastavení modulu" +#define D_MODULE_TYPE "Typ modulu" +#define D_GPIO "GPIO" +#define D_SERIAL_IN "Serial In" +#define D_SERIAL_OUT "Serial Out" + +#define D_WIFI_PARAMETERS "Nastavení WiFi" +#define D_SCAN_FOR_WIFI_NETWORKS "Scan sítí WiFi" +#define D_SCAN_DONE "Scan dokončen" +#define D_NO_NETWORKS_FOUND "Síť nebyla nalezena" +#define D_REFRESH_TO_SCAN_AGAIN "Zopakovat scan" +#define D_DUPLICATE_ACCESSPOINT "Kopie AP" +#define D_SKIPPING_LOW_QUALITY "Přeskočení z důvodu kvality signálu" +#define D_RSSI "RSSI" +#define D_WEP "WEP" +#define D_WPA_PSK "WPA PSK" +#define D_WPA2_PSK "WPA2 PSK" +#define D_AP1_SSID "AP1 SSID" +#define D_AP1_PASSWORD "Heslo AP1" +#define D_AP2_SSID "AP2 SSID" +#define D_AP2_PASSWORD "Heslo AP2" + +#define D_MQTT_PARAMETERS "Nastavení MQTT" +#define D_CLIENT "Klient" +#define D_FULL_TOPIC "Celý topic" + +#define D_LOGGING_PARAMETERS "Volba logování" +#define D_SERIAL_LOG_LEVEL "Seriová úroveň logu" +#define D_WEB_LOG_LEVEL "Webová úroveň logu" +#define D_SYS_LOG_LEVEL "Systemová úroveň logu" +#define D_MORE_DEBUG "Více debug informací" +#define D_SYSLOG_HOST "Syslog host" +#define D_SYSLOG_PORT "Syslog port" +#define D_TELEMETRY_PERIOD "Interval telemetrie" + +#define D_OTHER_PARAMETERS "Další nastavení" +#define D_WEB_ADMIN_PASSWORD "Heslo Web administrátora" +#define D_MQTT_ENABLE "MQTT aktivní" +#define D_FRIENDLY_NAME "Friendly Name" +#define D_BELKIN_WEMO "Belkin WeMo" +#define D_HUE_BRIDGE "Hue Bridge" +#define D_SINGLE_DEVICE "single device" +#define D_MULTI_DEVICE "multi device" + +#define D_SAVE_CONFIGURATION "Ulož nastavení" +#define D_CONFIGURATION_SAVED "Nastavení uloženo" +#define D_CONFIGURATION_RESET "Nastavení resetováno" + +#define D_PROGRAM_VERSION "Verze programu" +#define D_BUILD_DATE_AND_TIME "Datum a čas kompilace" +#define D_CORE_AND_SDK_VERSION "Verze Core/SDK" +#define D_FLASH_WRITE_COUNT "Počet zápisů do paměti" +#define D_MAC_ADDRESS "Adresa MAC" +#define D_MQTT_HOST "Host MQTT" +#define D_MQTT_PORT "Port MQTT" +#define D_MQTT_CLIENT "Klient MQTT" +#define D_MQTT_USER "Uživatel MQTT" +#define D_MQTT_TOPIC "Topic MQTT" +#define D_MQTT_GROUP_TOPIC "Topic skupiny MQTT" +#define D_MQTT_FULL_TOPIC "Celý topic MQTT" +#define D_MDNS_DISCOVERY "Získávání mDNS" +#define D_MDNS_ADVERTISE "Rozesílání mDNS" +#define D_ESP_CHIP_ID "ID systému ESP" +#define D_FLASH_CHIP_ID "ID systému paměti flash" +#define D_FLASH_CHIP_SIZE "Velikost flash" +#define D_FREE_PROGRAM_SPACE "Volné místo pro program" + +#define D_UPGRADE_BY_WEBSERVER "Aktualizace z Web serveru" +#define D_OTA_URL "URL OTA" +#define D_START_UPGRADE "Start aktualizace" +#define D_UPGRADE_BY_FILE_UPLOAD "Aktualizace nahráním souboru" +#define D_UPLOAD_STARTED "Nahrávání zahájeno" +#define D_UPGRADE_STARTED "Zahájení aktualizace" +#define D_UPLOAD_DONE "Nahrávání ukončeno" +#define D_UPLOAD_ERR_1 "Soubor nebyl vybrán" +#define D_UPLOAD_ERR_2 "Málo místa" +#define D_UPLOAD_ERR_3 "Magický byte má hodnotu jinou než 0xE9" +#define D_UPLOAD_ERR_4 "Velikost programu je větší než skutečná velikost paměti flash" +#define D_UPLOAD_ERR_5 "Chyba nahrávání, nesouhlasí porovnávané bity" +#define D_UPLOAD_ERR_6 "Chyba nahrávání. Spuštěn zápis do logu na úrovni 3" +#define D_UPLOAD_ERR_7 "Nahrávání přerušeno" +#define D_UPLOAD_ERR_8 "Špatný soubor" +#define D_UPLOAD_ERR_9 "Soubor je příliš velký" +#define D_UPLOAD_ERROR_CODE "Chyba nahrávání" + +#define D_ENTER_COMMAND "Vlož příkaz" +#define D_ENABLE_WEBLOG_FOR_RESPONSE "Zapni úroveň 2 zápisu Weblog, pokud je očekávána odpověď" +#define D_NEED_USER_AND_PASSWORD "Vyžadován uživatel=&heslo=" + +// xdrv_00_mqtt.ino +#define D_FINGERPRINT "Verifikuj otisk TLS..." +#define D_TLS_CONNECT_FAILED_TO "Nepřipojeno TLS do" +#define D_RETRY_IN "Zopakuji za" +#define D_VERIFIED "Ověřeno otisk " +#define D_INSECURE "Nesprávné připojení z důvodu chybného otisku TLS" +#define D_CONNECT_FAILED_TO "Spojení se nepodařilo navázat" + +// xdrv_wemohue.ino +#define D_MULTICAST_DISABLED "Multicast je vypnutý" +#define D_MULTICAST_REJOINED "Multicast opět připojený" +#define D_MULTICAST_JOIN_FAILED "Multicast neúspěšný" +#define D_FAILED_TO_SEND_RESPONSE "Nepodařilo se odeslat odpověď" + +#define D_WEMO "WeMo" +#define D_WEMO_BASIC_EVENT "WeMo základní událost" +#define D_WEMO_EVENT_SERVICE "WeMo servisní událost" +#define D_WEMO_META_SERVICE "WeMo meta událost" +#define D_WEMO_SETUP "WeMo setup" +#define D_RESPONSE_SENT "Odpověď odeslána" + +#define D_HUE "Hue" +#define D_HUE_BRIDGE_SETUP "Hue setup" +#define D_HUE_API_NOT_IMPLEMENTED "Hue API není implementováno" +#define D_HUE_API "Hue API" +#define D_HUE_POST_ARGS "Hue POST args" +#define D_3_RESPONSE_PACKETS_SENT "3 pakety odpovědi odeslány" + +// xdrv_05_domoticz.ino +#define D_DOMOTICZ_PARAMETERS "Nastavení Domoticz" +#define D_DOMOTICZ_IDX "Idx" +#define D_DOMOTICZ_KEY_IDX "Key idx" +#define D_DOMOTICZ_SWITCH_IDX "Spinac idx" +#define D_DOMOTICZ_SENSOR_IDX "Sensor idx" + #define D_DOMOTICZ_TEMP "Temp" + #define D_DOMOTICZ_TEMP_HUM "Temp,Vlhk" + #define D_DOMOTICZ_TEMP_HUM_BARO "Temp,Vlhk,Tlak" + #define D_DOMOTICZ_POWER_ENERGY "Příkon,Energie" + #define D_DOMOTICZ_ILLUMINANCE "Osvětlení" + #define D_DOMOTICZ_COUNT "Počítadlo/PM1" + #define D_DOMOTICZ_VOLTAGE "Napětí/PM2,5" + #define D_DOMOTICZ_CURRENT "Proud/PM10" + #define D_DOMOTICZ_AIRQUALITY "AirQuality" +#define D_DOMOTICZ_UPDATE_TIMER "Aktualizace stopek" + +// xdrv_09_timers.ino +#define D_CONFIGURE_TIMER "Nastavení Časovače" +#define D_TIMER_PARAMETERS "Časovač" +#define D_TIMER_ARM "Aktivní" +#define D_TIMER_TIME "Čas" +#define D_TIMER_DAYS "Dny" +#define D_TIMER_REPEAT "Opakovat" +#define D_TIMER_OUTPUT "Výstup" +#define D_TIMER_ACTION "Napájení" + +// xdrv_10_knx.ino +#define D_CONFIGURE_KNX "Nastavení KNX" +#define D_KNX_PARAMETERS "KNX parametry" +#define D_KNX_GENERAL_CONFIG "Obecné" +#define D_KNX_PHYSICAL_ADDRESS "Fyzická adresa" +#define D_KNX_PHYSICAL_ADDRESS_NOTE "( Musí být jedinečná v síti KNX )" +#define D_KNX_ENABLE "Povol KNX" +#define D_KNX_GROUP_ADDRESS_TO_WRITE "Data k odeslání na skupinové adresy" +#define D_ADD "Přidej" +#define D_DELETE "Smaž" +#define D_REPLY "Odpověď" +#define D_KNX_GROUP_ADDRESS_TO_READ "Skupinové adresy pro příjem dat z" +#define D_LOG_KNX "KNX: " +#define D_RECEIVED_FROM "Přijato z" +#define D_KNX_COMMAND_WRITE "Zapiš" +#define D_KNX_COMMAND_READ "Čti" +#define D_KNX_COMMAND_OTHER "Jiné" +#define D_SENT_TO "pošli" +#define D_KNX_WARNING "Skupinová adresa ( 0 / 0 / 0 ) je rezervována a nemůže být použita." + +// xdrv_03_energy.ino +#define D_ENERGY_TODAY "Spotřeba Dnes" +#define D_ENERGY_YESTERDAY "Spotřeba Včera" +#define D_ENERGY_TOTAL "Celková spotřeba" + +// xsns_05_ds18b20.ino +#define D_SENSOR_BUSY "Sensor DS18x20 obsazen" +#define D_SENSOR_CRC_ERROR "Sensor DS18x20 chyba CRC" +#define D_SENSORS_FOUND "Nalezen sensor DS18x20" + +// xsns_06_dht.ino +#define D_TIMEOUT_WAITING_FOR "Čekání na" +#define D_START_SIGNAL_LOW "nízký startovní signál" +#define D_START_SIGNAL_HIGH "vysoký startovní signál" +#define D_PULSE "impuls" +#define D_CHECKSUM_FAILURE "Chybný kontrolní součet" + +// xsns_07_sht1x.ino +#define D_SENSOR_DID_NOT_ACK_COMMAND "Sensor neobdržel příkaz ACK" +#define D_SHT1X_FOUND "SHT1X nalezen" + +// xsns_18_pms5003.ino +#define D_STANDARD_CONCENTRATION "CF-1 PM" // Standard Particle CF-1 Particle Matter +#define D_ENVIRONMENTAL_CONCENTRATION "PM" // Environmetal Particle Matter +#define D_PARTICALS_BEYOND "částic" + +// sonoff_template.h +#define D_SENSOR_NONE "Není" +#define D_SENSOR_DHT11 "DHT11" +#define D_SENSOR_AM2301 "AM2301" +#define D_SENSOR_SI7021 "SI7021" +#define D_SENSOR_DS18X20 "DS18x20" +#define D_SENSOR_I2C_SCL "I2C SCL" +#define D_SENSOR_I2C_SDA "I2C SDA" +#define D_SENSOR_WS2812 "WS2812" +#define D_SENSOR_IRSEND "IRsend" +#define D_SENSOR_SWITCH "Spínač" // Suffix "1" +#define D_SENSOR_BUTTON "Tlačítko" // Suffix "1" +#define D_SENSOR_RELAY "Relé" // Suffix "1i" +#define D_SENSOR_LED "Led" // Suffix "1i" +#define D_SENSOR_PWM "PWM" // Suffix "1", +#define D_SENSOR_COUNTER "Počítadlo" // Suffix "1" +#define D_SENSOR_IRRECV "IRrecv" +#define D_SENSOR_MHZ_RX "MHZ Rx" +#define D_SENSOR_MHZ_TX "MHZ Tx" +#define D_SENSOR_PZEM_RX "PZEM Rx" +#define D_SENSOR_PZEM_TX "PZEM Tx" +#define D_SENSOR_SAIR_RX "SAir Rx" +#define D_SENSOR_SAIR_TX "SAir Tx" +#define D_SENSOR_SPI_CS "SPI CS" +#define D_SENSOR_SPI_DC "SPI DC" +#define D_SENSOR_BACKLIGHT "BkLight" +#define D_SENSOR_PMS5003 "PMS5003" +#define D_SENSOR_SDS0X1 "SDS0X1" +#define D_SENSOR_SBR_RX "SerBr Rx" +#define D_SENSOR_SBR_TX "SerBr Tx" +#define D_SENSOR_SR04_TRIG "SR04 Tri" +#define D_SENSOR_SR04_ECHO "SR04 Ech" + +// Units +#define D_UNIT_AMPERE "A" +#define D_UNIT_CENTIMETER "cm" +#define D_UNIT_HOUR "hod" +#define D_UNIT_KILOOHM "kOhm" +#define D_UNIT_KILOWATTHOUR "kWh" +#define D_UNIT_LUX "lx" +#define D_UNIT_MICROGRAM_PER_CUBIC_METER "ug/m3" +#define D_UNIT_MICROMETER "um" +#define D_UNIT_MICROSECOND "us" +#define D_UNIT_MILLIAMPERE "mA" +#define D_UNIT_MILLISECOND "ms" +#define D_UNIT_MINUTE "min" +#define D_UNIT_PARTS_PER_BILLION "ppb" +#define D_UNIT_PARTS_PER_DECILITER "ppd" +#define D_UNIT_PARTS_PER_MILLION "ppm" +#define D_UNIT_PRESSURE "hPa" +#define D_UNIT_SECOND "sec" +#define D_UNIT_SECTORS "sektory" +#define D_UNIT_VOLT "V" +#define D_UNIT_WATT "W" +#define D_UNIT_WATTHOUR "Wh" + +// Log message prefix +#define D_LOG_APPLICATION "APP: " // Application +#define D_LOG_BRIDGE "BRG: " // Bridge +#define D_LOG_CONFIG "CFG: " // Settings +#define D_LOG_COMMAND "CMD: " // Command +#define D_LOG_DEBUG "DBG: " // Debug +#define D_LOG_DHT "DHT: " // DHT sensor +#define D_LOG_DOMOTICZ "DOM: " // Domoticz +#define D_LOG_DSB "DSB: " // DS18xB20 sensor +#define D_LOG_HTTP "HTP: " // HTTP webserver +#define D_LOG_I2C "I2C: " // I2C +#define D_LOG_IRR "IRR: " // Infra Red Received +#define D_LOG_LOG "LOG: " // Logging +#define D_LOG_MODULE "MOD: " // Module +#define D_LOG_MDNS "DNS: " // mDNS +#define D_LOG_MQTT "MQT: " // MQTT +#define D_LOG_OTHER "OTH: " // Other +#define D_LOG_RESULT "RSL: " // Result +#define D_LOG_RFR "RFR: " // RF Received +#define D_LOG_SERIAL "SER: " // Serial +#define D_LOG_SHT1 "SHT: " // SHT1x sensor +#define D_LOG_UPLOAD "UPL: " // Upload +#define D_LOG_UPNP "UPP: " // UPnP +#define D_LOG_WIFI "WIF: " // Wifi + +#endif // _LANGUAGE_CS_CZ_H_ diff --git a/sonoff/language/de-DE.h b/sonoff/language/de-DE.h index 09877893c..b2ade5e2b 100644 --- a/sonoff/language/de-DE.h +++ b/sonoff/language/de-DE.h @@ -28,10 +28,14 @@ * Use online command StateText to translate ON, OFF, HOLD and TOGGLE. * Use online command Prefix to translate cmnd, stat and tele. * + * Updated until v5.12.0l \*********************************************************************/ //#define LANGUAGE_MODULE_NAME // Enable to display "Module Generic" (ie Spanish), Disable to display "Generic Module" (ie English) +// HTML (ISO 639-1) Language Code +#define D_HTML_LANGUAGE "de" + // "2017-03-07T11:08:02" - ISO8601:2004 #define D_YEAR_MONTH_SEPARATOR "." #define D_MONTH_DAY_SEPARATOR "." @@ -39,8 +43,8 @@ #define D_HOUR_MINUTE_SEPARATOR ":" #define D_MINUTE_SECOND_SEPARATOR ":" -#define D_DAY3LIST "SonMonDieMitDonFriSam" -#define D_MONTH3LIST "JanFebMaeAprMaiJunJulAugSepOktNovDez" +#define D_DAY3LIST "So Mo Di Mi Do Fr Sa " +#define D_MONTH3LIST "JanFebMärAprMaiJunJulAugSepOktNovDez" // Non JSON decimal separator #define D_DECIMAL_SEPARATOR "." @@ -71,9 +75,11 @@ #define D_DARKLIGHT "dunkel" #define D_DEBUG "debug" #define D_DISABLED "deaktiviert" -#define D_DNS_SERVER "DNS Server" +#define D_DISTANCE "Abstand" +#define D_DNS_SERVER "DNS-Server" #define D_DONE "erledigt" #define D_DST_TIME "DST" +#define D_ECO2 "eCO2" #define D_EMULATION "Emulation" #define D_ENABLED "aktiviert" #define D_ERASE "löschen" @@ -81,7 +87,7 @@ #define D_FAHRENHEIT "Fahrenheit" #define D_FAILED "fehlgeschlagen" #define D_FALLBACK "Fallback" -#define D_FALLBACK_TOPIC "Fallback topic" +#define D_FALLBACK_TOPIC "Fallback-Topic" #define D_FALSE "falsch" #define D_FILE "Datei" #define D_FREE_MEMORY "Freier Arbeitsspeicher" @@ -96,7 +102,7 @@ #define D_INDEX "Index" #define D_INFO "Info" #define D_INITIALIZED "initialisiert" -#define D_IP_ADDRESS "IP-Addresse" +#define D_IP_ADDRESS "IP-Adresse" #define D_LIGHT "Licht" #define D_LWT "LWT" #define D_MODULE "Modul" @@ -113,8 +119,8 @@ #define D_PORT "Port" #define D_POWER_FACTOR "Leistungsfaktor" #define D_POWERUSAGE "Leistung" -#define D_PRESSURE "Druck" -#define D_PRESSUREATSEALEVEL "MeeresDruck" +#define D_PRESSURE "Luftdruck" +#define D_PRESSUREATSEALEVEL "Luftdruck auf Meereshöhe" #define D_PROGRAM_FLASH_SIZE "Ges. Flash Speicher" #define D_PROGRAM_SIZE "Ben. Flash Speicher" #define D_PROJECT "Projekt" @@ -124,6 +130,7 @@ #define D_RESTART_REASON "Grund für Neustart" #define D_RESTORE "Wiederherstellung" #define D_RETAINED "beibehalten" +#define D_RULE "Regel" #define D_SAVE "Speichern" #define D_SENSOR "Sensor" #define D_SSID "SSID" @@ -131,63 +138,59 @@ #define D_STD_TIME "STD" #define D_STOP "Stop" #define D_SUBNET_MASK "Subnetzmaske" -#define D_SUBSCRIBE_TO "subscribe to" +#define D_SUBSCRIBE_TO "abonniere" #define D_SUCCESSFUL "erfolgreich" +#define D_SUNRISE "Sonnenaufgang" +#define D_SUNSET "Sonnenuntergang" #define D_TEMPERATURE "Temperatur" #define D_TO "zu" #define D_TOGGLE "An/Aus" #define D_TOPIC "topic" #define D_TRANSMIT "Übertragen" #define D_TRUE "wahr" +#define D_TVOC "TVOC" #define D_UPGRADE "update" #define D_UPLOAD "Upload" #define D_UPTIME "Laufzeit" #define D_USER "Benutzer" #define D_UTC_TIME "UTC" -#define D_UV_LEVEL "UV Level" +#define D_UV_LEVEL "UV-Level" #define D_VERSION "Version" #define D_VOLTAGE "Spannung" #define D_WARMLIGHT "warm" #define D_WEB_SERVER "Web-Server" // sonoff.ino -#define D_WARNING_MINIMAL_VERSION "WARNING This version does not support persistent settings" +#define D_WARNING_MINIMAL_VERSION "ACHTUNG: Diese Version unterstützt keine persistenten Einstellungen" #define D_LEVEL_10 "level 1-0" #define D_LEVEL_01 "level 0-1" -#define D_SERIAL_LOGGING_DISABLED "Serielles logging deaktiviert" -#define D_SYSLOG_LOGGING_REENABLED "Syslog logging reaktiviert" +#define D_SERIAL_LOGGING_DISABLED "Serielles Logging deaktiviert" +#define D_SYSLOG_LOGGING_REENABLED "Syslog-Logging aktiviert" -#define D_SET_BAUDRATE_TO "Baudrate eingestellt auf" +#define D_SET_BAUDRATE_TO "Setze Baudrate auf" #define D_RECEIVED_TOPIC "empfangenes topic" #define D_DATA_SIZE "Datengröße" #define D_ANALOG_INPUT "Analog" -#define D_FINGERPRINT "TLS-Fingerabdruck wird verifiziert..." -#define D_TLS_CONNECT_FAILED_TO "TLS-Verbindung fehlgeschlagen an" -#define D_RETRY_IN "Wiederversuch in" -#define D_VERIFIED "verifiziert" -#define D_INSECURE "unsichere Verbindung aufgrund ungültigen Fingerabdrucks" -#define D_CONNECT_FAILED_TO "Verbindung fehlgeschlagen aufgrund von" - // support.ino #define D_OSWATCH "osWatch" -#define D_BLOCKED_LOOP "Blocked Loop" +#define D_BLOCKED_LOOP "Schleife blockiert." #define D_WPS_FAILED_WITH_STATUS "WPS fehlgeschlagen mit Status" #define D_ACTIVE_FOR_3_MINUTES "aktiv für 3 Minuten" #define D_FAILED_TO_START "Starten fehlgeschlagen" -#define D_PATCH_ISSUE_2186 "Patch-Problem 2186" +#define D_PATCH_ISSUE_2186 "Repariere Problem #2186" #define D_CONNECTING_TO_AP "verbinden mit AP" #define D_IN_MODE "in Modus" -#define D_CONNECT_FAILED_NO_IP_ADDRESS "Verbindung fehlgeschlagen da keine IP-Adresse zugeteilt wurde" -#define D_CONNECT_FAILED_AP_NOT_REACHED "Verbindung fehlgeschlagen da AP nicht erreicht werden konnte" -#define D_CONNECT_FAILED_WRONG_PASSWORD "Verbindung fehlgeschlagen mit AP weil das Passwort falsch ist" -#define D_CONNECT_FAILED_AP_TIMEOUT "Verbindung fehlgeschlagen da der AP nicht antwortet (timeout)" +#define D_CONNECT_FAILED_NO_IP_ADDRESS "Verbindung fehlgeschlagen, da keine IP-Adresse zugeteilt wurde" +#define D_CONNECT_FAILED_AP_NOT_REACHED "Verbindung fehlgeschlagen, da AP nicht erreicht werden konnte" +#define D_CONNECT_FAILED_WRONG_PASSWORD "Verbindung fehlgeschlagen, da das Passwort falsch ist" +#define D_CONNECT_FAILED_AP_TIMEOUT "Verbindung fehlgeschlagen, da der AP nicht antwortet (timeout)" #define D_ATTEMPTING_CONNECTION "Verbindungsversuch..." #define D_CHECKING_CONNECTION "Prüfe Verbindung..." #define D_QUERY_DONE "Suchanfrage abgeschlossen. MQTT-Services gefunden" #define D_MQTT_SERVICE_FOUND "MQTT-Service gefunden bei" #define D_FOUND_AT "gefunden bei" -#define D_SYSLOG_HOST_NOT_FOUND "Syslog Host nicht gefunden" +#define D_SYSLOG_HOST_NOT_FOUND "Syslog-Host nicht gefunden" // settings.ino #define D_SAVED_TO_FLASH_AT "in Flash gespeichert am" @@ -228,40 +231,40 @@ #define D_RESTORE_CONFIGURATION "Konfiguration wiederherstellen" #define D_MAIN_MENU "Hauptmenü" -#define D_MODULE_PARAMETERS "Geräte Einstellungen" -#define D_MODULE_TYPE "Geräte Typ" +#define D_MODULE_PARAMETERS "Geräte-Einstellungen" +#define D_MODULE_TYPE "Gerätetyp" #define D_GPIO "GPIO" #define D_SERIAL_IN "serieller Eingang [serial in]" #define D_SERIAL_OUT "serieller Ausgang [serial out]" -#define D_WIFI_PARAMETERS "WLAN Einstellungen" +#define D_WIFI_PARAMETERS "WLAN-Einstellungen" #define D_SCAN_FOR_WIFI_NETWORKS "WLAN-Netzwerk suchen und auswählen" #define D_SCAN_DONE "Suche abgeschlossen" #define D_NO_NETWORKS_FOUND "Keine Netzwerke gefunden" -#define D_REFRESH_TO_SCAN_AGAIN "Aktualisieren um erneut zu suchen" +#define D_REFRESH_TO_SCAN_AGAIN "Aktualisieren, um erneut zu suchen" #define D_DUPLICATE_ACCESSPOINT "AccessPoint duplizieren" #define D_SKIPPING_LOW_QUALITY "überspringe wegen niedriger Qualität" #define D_RSSI "RSSI" #define D_WEP "WEP" -#define D_WPA_PSK "WPA PSK" -#define D_WPA2_PSK "WPA2 PSK" +#define D_WPA_PSK "WPA-PSK" +#define D_WPA2_PSK "WPA2-PSK" #define D_AP1_SSID "WLAN 1 - SSID" #define D_AP1_PASSWORD "WLAN 1 - Passwort" #define D_AP2_SSID "WLAN 2 - SSID" #define D_AP2_PASSWORD "WLAN 2 - Passwort" -#define D_MQTT_PARAMETERS "MQTT Einstellungen" +#define D_MQTT_PARAMETERS "MQTT-Einstellungen" #define D_CLIENT "client" #define D_FULL_TOPIC "full topic" -#define D_LOGGING_PARAMETERS "Logging Einstellungen" -#define D_SERIAL_LOG_LEVEL "Seriell Log level" -#define D_WEB_LOG_LEVEL "Web Log level" -#define D_SYS_LOG_LEVEL "Sys Log level" +#define D_LOGGING_PARAMETERS "Logging-Einstellungen" +#define D_SERIAL_LOG_LEVEL "Seriell-Log Level" +#define D_WEB_LOG_LEVEL "Web-Log Level" +#define D_SYS_LOG_LEVEL "Sys-Log Level" #define D_MORE_DEBUG "More debug" -#define D_SYSLOG_HOST "Sys Log Host" -#define D_SYSLOG_PORT "Sys Log Port" -#define D_TELEMETRY_PERIOD "Telemetry period" +#define D_SYSLOG_HOST "Sys-Log Host" +#define D_SYSLOG_PORT "Sys-Log Port" +#define D_TELEMETRY_PERIOD "Telemetrieperiode" #define D_OTHER_PARAMETERS "Sonstige Einstellungen" #define D_WEB_ADMIN_PASSWORD "Passwort für Web Oberfläche" @@ -298,7 +301,7 @@ #define D_UPGRADE_BY_WEBSERVER "Update über Web-Server" #define D_OTA_URL "OTA-URL" #define D_START_UPGRADE "Update starten" -#define D_UPGRADE_BY_FILE_UPLOAD "Update Datei hochladen" +#define D_UPGRADE_BY_FILE_UPLOAD "Update-Datei hochladen" #define D_UPLOAD_STARTED "Upload gestartet" #define D_UPGRADE_STARTED "Update gestartet" #define D_UPLOAD_DONE "Upload abgeschlossen" @@ -315,7 +318,15 @@ #define D_ENTER_COMMAND "Befehl eingeben" #define D_ENABLE_WEBLOG_FOR_RESPONSE "Aktivere Web Log Level 2 falls Reaktion erwartet" -#define D_NEED_USER_AND_PASSWORD "Benutzer benötigt=&password=" +#define D_NEED_USER_AND_PASSWORD "Benötige user=&password=" + +// xdrv_00_mqtt.ino +#define D_FINGERPRINT "TLS-Fingerabdruck wird verifiziert..." +#define D_TLS_CONNECT_FAILED_TO "TLS-Verbindung fehlgeschlagen an" +#define D_RETRY_IN "Wiederversuch in" +#define D_VERIFIED "verifiziert mit Fingerabdruck" +#define D_INSECURE "unsichere Verbindung aufgrund ungültigen Fingerabdrucks" +#define D_CONNECT_FAILED_TO "Verbindung fehlgeschlagen aufgrund von" // xdrv_wemohue.ino #define D_MULTICAST_DISABLED "Multicast deaktiviert" @@ -332,13 +343,13 @@ #define D_HUE "Hue" #define D_HUE_BRIDGE_SETUP "Hue-Setup" -#define D_HUE_API_NOT_IMPLEMENTED "Hue API nicht implementiert" -#define D_HUE_API "Hue API" -#define D_HUE_POST_ARGS "Hue POST args" +#define D_HUE_API_NOT_IMPLEMENTED "Hue-API nicht implementiert" +#define D_HUE_API "Hue-API" +#define D_HUE_POST_ARGS "Hue POST-Argumente" #define D_3_RESPONSE_PACKETS_SENT "3 Antwortpakete gesendet" // xdrv_05_domoticz.ino -#define D_DOMOTICZ_PARAMETERS "Domoticz parameters" +#define D_DOMOTICZ_PARAMETERS "Domoticz-Parameter" #define D_DOMOTICZ_IDX "Idx" #define D_DOMOTICZ_KEY_IDX "Key idx" #define D_DOMOTICZ_SWITCH_IDX "Switch idx" @@ -348,11 +359,41 @@ #define D_DOMOTICZ_TEMP_HUM_BARO "Temp,Hum,Baro" #define D_DOMOTICZ_POWER_ENERGY "Power,Energy" #define D_DOMOTICZ_ILLUMINANCE "Illuminance" - #define D_DOMOTICZ_COUNT "Count" - #define D_DOMOTICZ_VOLTAGE "Voltage" - #define D_DOMOTICZ_CURRENT "Current" + #define D_DOMOTICZ_COUNT "Count/PM1" + #define D_DOMOTICZ_VOLTAGE "Voltage/PM2.5" + #define D_DOMOTICZ_CURRENT "Current/PM10" #define D_DOMOTICZ_AIRQUALITY "AirQuality" -#define D_DOMOTICZ_UPDATE_TIMER "Update timer" + #define D_DOMOTICZ_UPDATE_TIMER "Update Zeitplan" + +// xdrv_09_timers.ino +#define D_CONFIGURE_TIMER "Zeitplan konfigurieren" +#define D_TIMER_PARAMETERS "Zeitplan-Einstellungen" +#define D_TIMER_ARM "Aktiv" +#define D_TIMER_TIME "Uhrzeit" +#define D_TIMER_DAYS "Wochentage" +#define D_TIMER_REPEAT "Wiederholen" +#define D_TIMER_OUTPUT "Ausgang" +#define D_TIMER_ACTION "Aktion" + +// xdrv_10_knx.ino +#define D_CONFIGURE_KNX "Configure KNX" +#define D_KNX_PARAMETERS "KNX Parameters" +#define D_KNX_GENERAL_CONFIG "General" +#define D_KNX_PHYSICAL_ADDRESS "Physical Address" +#define D_KNX_PHYSICAL_ADDRESS_NOTE "( Must be unique on the KNX network )" +#define D_KNX_ENABLE "Enable KNX" +#define D_KNX_GROUP_ADDRESS_TO_WRITE "Data to Send to Group Addresses" +#define D_ADD "Add" +#define D_DELETE "Delete" +#define D_REPLY "Reply" +#define D_KNX_GROUP_ADDRESS_TO_READ "Group Addresses to Receive Data from" +#define D_LOG_KNX "KNX: " +#define D_RECEIVED_FROM "Received from" +#define D_KNX_COMMAND_WRITE "Write" +#define D_KNX_COMMAND_READ "Read" +#define D_KNX_COMMAND_OTHER "Other" +#define D_SENT_TO "sent to" +#define D_KNX_WARNING "The group address ( 0 / 0 / 0 ) is reserved and can not be used." // xdrv_03_energy.ino #define D_ENERGY_TODAY "Energie heute" @@ -365,7 +406,7 @@ #define D_SENSORS_FOUND "Sensor gefunden" // xsns_06_dht.ino -#define D_TIMEOUT_WAITING_FOR "Timeout wartet auf" +#define D_TIMEOUT_WAITING_FOR "Timeout während Warten auf" #define D_START_SIGNAL_LOW "Startausschlag niedrig" #define D_START_SIGNAL_HIGH "Startausschlag hoch" #define D_PULSE "pulse" @@ -407,9 +448,15 @@ #define D_SENSOR_SPI_DC "SPI DC" #define D_SENSOR_BACKLIGHT "BkLight" #define D_SENSOR_PMS5003 "PMS5003" +#define D_SENSOR_SDS0X1 "SDS0X1" +#define D_SENSOR_SBR_RX "SerBr Rx" +#define D_SENSOR_SBR_TX "SerBr Tx" +#define D_SENSOR_SR04_TRIG "SR04 Tri" +#define D_SENSOR_SR04_ECHO "SR04 Ech" // Units #define D_UNIT_AMPERE "A" +#define D_UNIT_CENTIMETER "cm" #define D_UNIT_HOUR "h" #define D_UNIT_KILOOHM "kOhm" #define D_UNIT_KILOWATTHOUR "kWh" @@ -420,6 +467,7 @@ #define D_UNIT_MILLIAMPERE "mA" #define D_UNIT_MILLISECOND "ms" #define D_UNIT_MINUTE "min" +#define D_UNIT_PARTS_PER_BILLION "ppb" #define D_UNIT_PARTS_PER_DECILITER "ppd" #define D_UNIT_PARTS_PER_MILLION "ppm" #define D_UNIT_PRESSURE "hPa" diff --git a/sonoff/language/el-GR.h b/sonoff/language/el-GR.h new file mode 100644 index 000000000..e4280b092 --- /dev/null +++ b/sonoff/language/el-GR.h @@ -0,0 +1,505 @@ +/* + el-GR.h - localization for Greek - Greece for Sonoff-Tasmota + + Copyright (C) 2018 Kan3Nas + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifndef _LANGUAGE_EL_GR_H_ +#define _LANGUAGE_EL_GR_H_ + +/*************************** ATTENTION *******************************\ + * + * Due to memory constraints only UTF-8 is supported. + * To save code space keep text as short as possible. + * Time and Date provided by SDK can not be localized (yet). + * Use online command StateText to translate ON, OFF, HOLD and TOGGLE. + * Use online command Prefix to translate cmnd, stat and tele. + * + * Updated until v5.12.0n +\*********************************************************************/ + +//#define LANGUAGE_MODULE_NAME // Enable to display "Module Generic" (ie Spanish), Disable to display "Generic Module" (ie English) + +// HTML (ISO 639-1) Language Code +#define D_HTML_LANGUAGE "el" + +// "2017-03-07T11:08:02" - ISO8601:2004 +#define D_YEAR_MONTH_SEPARATOR "-" +#define D_MONTH_DAY_SEPARATOR "-" +#define D_DATE_TIME_SEPARATOR "T" +#define D_HOUR_MINUTE_SEPARATOR ":" +#define D_MINUTE_SECOND_SEPARATOR ":" + +#define D_DAY3LIST "ΚυρΔευΤριΤετΠεμΠαρΣαβ" +#define D_MONTH3LIST "ΙανΦεβΜαρΑπρΜαϊΙονΙολΑυγΣεπΟκτΝοεΔεκ" + +// Non JSON decimal separator +#define D_DECIMAL_SEPARATOR "," + +// Common +#define D_ADMIN "Admin" +#define D_AIR_QUALITY "Ποιότητα Αέρα" +#define D_AP "AP" // Access Point +#define D_AS "as" +#define D_AUTO "ΑΥΤΟΜΑΤΟ" +#define D_BLINK "Αναβοσβήνει" +#define D_BLINKOFF "Δεν αναβοσβήνει" +#define D_BOOT_COUNT "Αριθμός εκκινήσεων" +#define D_BRIGHTLIGHT "Λαμπερό" +#define D_BUTTON "Κουμπί" +#define D_BY "από" // Written by me +#define D_BYTES "Bytes" +#define D_CELSIUS "Κελσίου" +#define D_CO2 "Διοξείδιο του άνθρακα" +#define D_CODE "κώδικας" // Button code +#define D_COLDLIGHT "Ψυχρός" +#define D_COMMAND "Εντολή" +#define D_CONNECTED "Συνδεδεμένο" +#define D_COUNT "Μέτρημα" +#define D_COUNTER "Μετρητής" +#define D_CURRENT "Τάση ρεύματος" // As in Voltage and Current +#define D_DATA "Δεδομένα" +#define D_DARKLIGHT "Σκούρο" +#define D_DEBUG "Debug" +#define D_DISABLED "Απενεργοποιημένο" +#define D_DISTANCE "Distance" +#define D_DNS_SERVER "Διακομιστής DNS" +#define D_DONE "Εγινε" +#define D_DST_TIME "DST" +#define D_ECO2 "eCO2" +#define D_EMULATION "Emulation" +#define D_ENABLED "Ενεργό" +#define D_ERASE "Σβήσιμο" +#define D_ERROR "Σφάλμα" +#define D_FAHRENHEIT "Φαρενάιτ" +#define D_FAILED "Αποτυχία" +#define D_FALLBACK "Εφεδρικό" +#define D_FALLBACK_TOPIC "Εφεδρικό θέμα" +#define D_FALSE "Λάθος" +#define D_FILE "Αρχείο" +#define D_FREE_MEMORY "Ελεύθερη Μνήμη" +#define D_GAS "Γκάζι" +#define D_GATEWAY "Πύλη" +#define D_GROUP "Ομάδα" +#define D_HOST "Host" +#define D_HOSTNAME "Hostname" +#define D_HUMIDITY "Υγρασία" +#define D_ILLUMINANCE "Illuminance" +#define D_IMMEDIATE "Φωτεινότητα" // Button immediate +#define D_INDEX "Κατάλογος" +#define D_INFO "Πληροφορίες" +#define D_INITIALIZED "Αρχικό" +#define D_IP_ADDRESS "IP Address" +#define D_LIGHT "Light" +#define D_LWT "LWT" +#define D_MODULE "Module" +#define D_MQTT "MQTT" +#define D_MULTI_PRESS "πολλαπλή πίεση" +#define D_NOISE "θόρυβος" +#define D_NONE "Κανένα" +#define D_OFF "Κλειστό" +#define D_OFFLINE "Offline" +#define D_OK "Ok" +#define D_ON "Ανοιχτό" +#define D_ONLINE "Online" +#define D_PASSWORD "ΚωδικόςPassword" +#define D_PORT "Πόρτα" +#define D_POWER_FACTOR "Παράγοντας ισχύος" +#define D_POWERUSAGE "Ισχύης" +#define D_PRESSURE "Πίεση" +#define D_PRESSUREATSEALEVEL "Πίεση στην επιφάνεια της Θάλασσας" +#define D_PROGRAM_FLASH_SIZE "Μέγεθος Προγράμματος Flash" +#define D_PROGRAM_SIZE "Μέγεθος Προγράμματος" +#define D_PROJECT "Έργο" +#define D_RECEIVED "Λήψη" +#define D_RESTART "Επανεκκίνηση" +#define D_RESTARTING "Επανεκκίνηση" +#define D_RESTART_REASON "Λόγος Επανεκκίνησης" +#define D_RESTORE "επαναφορά" +#define D_RETAINED "διατηρούνται" +#define D_RULE "Κανόνας" +#define D_SAVE "Αποθήκευση" +#define D_SENSOR "Σένσορας" +#define D_SSID "SSId" +#define D_START "Έναρξη" +#define D_STD_TIME "STD" +#define D_STOP "Στοπ" +#define D_SUBNET_MASK "Μάσκα υποδικτύου" +#define D_SUBSCRIBE_TO "Εγγραφή στο" +#define D_SUCCESSFUL "Επιτυχής" +#define D_SUNRISE "Σούρουπο" +#define D_SUNSET "Ηλιοβασίλεμα" +#define D_TEMPERATURE "Θερμοκρασία" +#define D_TO "στο" +#define D_TOGGLE "Εναλλαγή" +#define D_TOPIC "Θέμα" +#define D_TRANSMIT "Μετάδοση" +#define D_TRUE "Σωστό" +#define D_TVOC "TVOC" +#define D_UPGRADE "αναβάθμιση" +#define D_UPLOAD "Ανέβασμα" +#define D_UPTIME "Uptime" +#define D_USER "Χρήστης" +#define D_UTC_TIME "UTC" +#define D_UV_LEVEL "Επίπεδο UV" +#define D_VERSION "Έκδοση" +#define D_VOLTAGE "Τάση" +#define D_WARMLIGHT "Ζεστό" +#define D_WEB_SERVER "Web διακομιστής" + +// sonoff.ino +#define D_WARNING_MINIMAL_VERSION "ΠΡΟΕΙΔΟΠΟΙΗΣΗ Αυτή η έκδοση δεν αποθηκεύει τις ρυθμίσεις" +#define D_LEVEL_10 "επίπεδο 1-0" +#define D_LEVEL_01 "επίπεδο 0-1" +#define D_SERIAL_LOGGING_DISABLED "Η σειριακής καταγραφή απενεργοποιήθηκε" +#define D_SYSLOG_LOGGING_REENABLED "Η καταγραφή Syslog είναι ενεργοποιημένη" + +#define D_SET_BAUDRATE_TO "Ρύθμιση Baudrate σε" +#define D_RECEIVED_TOPIC "Λήψη θεμάτων" +#define D_DATA_SIZE "Μέγεθος δεδομένων" +#define D_ANALOG_INPUT "Αναλογικό" + +// support.ino +#define D_OSWATCH "osWatch" +#define D_BLOCKED_LOOP "Blocked Loop" +#define D_WPS_FAILED_WITH_STATUS "WPSconfig FAILED with status" +#define D_ACTIVE_FOR_3_MINUTES "active for 3 minutes" +#define D_FAILED_TO_START "failed to start" +#define D_PATCH_ISSUE_2186 "Patch issue 2186" +#define D_CONNECTING_TO_AP "Connecting to AP" +#define D_IN_MODE "in mode" +#define D_CONNECT_FAILED_NO_IP_ADDRESS "Connect failed as no IP address received" +#define D_CONNECT_FAILED_AP_NOT_REACHED "Connect failed as AP cannot be reached" +#define D_CONNECT_FAILED_WRONG_PASSWORD "Connect failed with AP incorrect password" +#define D_CONNECT_FAILED_AP_TIMEOUT "Connect failed with AP timeout" +#define D_ATTEMPTING_CONNECTION "Attempting connection..." +#define D_CHECKING_CONNECTION "Checking connection..." +#define D_QUERY_DONE "Query done. MQTT services found" +#define D_MQTT_SERVICE_FOUND "MQTT service found on" +#define D_FOUND_AT "found at" +#define D_SYSLOG_HOST_NOT_FOUND "Syslog Host not found" + +// settings.ino +#define D_SAVED_TO_FLASH_AT "Εγινε flash στην θέση" +#define D_LOADED_FROM_FLASH_AT "Φορτώθηκε από την flash στην θέση" +#define D_USE_DEFAULTS "Χρήση προεπιλογών" +#define D_ERASED_SECTOR "Διαγραμμένος τομέας" + +// webserver.ino +#define D_MINIMAL_FIRMWARE_PLEASE_UPGRADE "MINIMAL firmware - παρακαλώ αναβαθμήστε" +#define D_WEBSERVER_ACTIVE_ON "Web διακομιστής ενεργός" +#define D_WITH_IP_ADDRESS "με διεύθυνση IP" +#define D_WEBSERVER_STOPPED "Web διακομιστής σταμάτησε" +#define D_FILE_NOT_FOUND "Το αρχείο δεν βρέθηκε" +#define D_REDIRECTED "Ανακατεύθυνση σε captive portal" +#define D_WIFIMANAGER_SET_ACCESSPOINT_AND_STATION "Wifimanager set AccessPoint and keep Station" +#define D_WIFIMANAGER_SET_ACCESSPOINT "Wifimanager set AccessPoint" +#define D_TRYING_TO_CONNECT "Προσπάθεια σύνδεσης της συσκευής στο δίκτυο" + +#define D_RESTART_IN "Επανεκκίνηση σε" +#define D_SECONDS "δευτερόλεπτα" +#define D_DEVICE_WILL_RESTART "Η συσκευή θα ξεκινήσει ξανά σε λίγα δευτερόλεπτα" +#define D_BUTTON_TOGGLE "Εναλλαγή" +#define D_CONFIGURATION "Ρύθμιση" +#define D_INFORMATION "Πληροφορίες" +#define D_FIRMWARE_UPGRADE "Αναβάθμιση Firmware" +#define D_CONSOLE "Κονσόλα" +#define D_CONFIRM_RESTART "Επιβεβαίωση Επανεκκίνησης" + +#define D_CONFIGURE_MODULE "Ρύθμιση Module" +#define D_CONFIGURE_WIFI "Ρύθμιση WiFi" +#define D_CONFIGURE_MQTT "Ρύθμιση MQTT" +#define D_CONFIGURE_DOMOTICZ "Ρύθμιση Domoticz" +#define D_CONFIGURE_LOGGING "Ρύθμιση καταγραφής" +#define D_CONFIGURE_OTHER "Άλλες Ρυθμίσεις" +#define D_CONFIRM_RESET_CONFIGURATION "Confirm Reset Configuration" +#define D_RESET_CONFIGURATION "Επαναφορά Ρυθμίσεων" +#define D_BACKUP_CONFIGURATION "Αντίγραφα Ασφαλείας Ρυθμίσεων" +#define D_RESTORE_CONFIGURATION "Επαναφορά Ρυθμίσεων" +#define D_MAIN_MENU "Κεντρικό Μενού" + +#define D_MODULE_PARAMETERS "Παράμετροι Module" +#define D_MODULE_TYPE "Είδος Module" +#define D_GPIO "GPIO" +#define D_SERIAL_IN "Serial In" +#define D_SERIAL_OUT "Serial Out" + +#define D_WIFI_PARAMETERS "Παράμετροι Wifi" +#define D_SCAN_FOR_WIFI_NETWORKS "Σάρωση για δίκτυα wifi" +#define D_SCAN_DONE "Ολοκλήρωση σάρωσης" +#define D_NO_NETWORKS_FOUND "Δεν βρέθηκαν δίκτυα" +#define D_REFRESH_TO_SCAN_AGAIN "Ανανέωση για επανάληψη σάρωσης" +#define D_DUPLICATE_ACCESSPOINT "Duplicate AccessPoint" +#define D_SKIPPING_LOW_QUALITY "Παράλειψη λόγω χαμηλού σήματος" +#define D_RSSI "RSSI" +#define D_WEP "WEP" +#define D_WPA_PSK "WPA PSK" +#define D_WPA2_PSK "WPA2 PSK" +#define D_AP1_SSID "AP1 SSId" +#define D_AP1_PASSWORD "AP1 Κωδικός" +#define D_AP2_SSID "AP2 SSId" +#define D_AP2_PASSWORD "AP2 Κωδικός" + +#define D_MQTT_PARAMETERS "MQTT Παράμετροι" +#define D_CLIENT "Πελάτης" +#define D_FULL_TOPIC "Full Topic" + +#define D_LOGGING_PARAMETERS "Παράμετροι καταγραφής" +#define D_SERIAL_LOG_LEVEL "Επίπεδο καταγραφής Serial" +#define D_WEB_LOG_LEVEL "Επίπεδο καταγραφής Web" +#define D_SYS_LOG_LEVEL "Επίπεδο καταγραφής Syslog" +#define D_MORE_DEBUG "Επιπλέον debug" +#define D_SYSLOG_HOST "Υπολογιστής Syslog" +#define D_SYSLOG_PORT "Πόρτα Syslog" +#define D_TELEMETRY_PERIOD "Χρόνος τηλεμετρίας" + +#define D_OTHER_PARAMETERS "Άλλες Παράμετροι" +#define D_WEB_ADMIN_PASSWORD "Web Admin Κωδικός" +#define D_MQTT_ENABLE "MQTT Ενεργό" +#define D_FRIENDLY_NAME "Φιλικό Όνομα" +#define D_BELKIN_WEMO "Belkin WeMo" +#define D_HUE_BRIDGE "Hue Bridge" +#define D_SINGLE_DEVICE "μονή συσκευή" +#define D_MULTI_DEVICE "πολλαπλή συσκευή" + +#define D_SAVE_CONFIGURATION "Αποθήκευση Ρυθμίσεων" +#define D_CONFIGURATION_SAVED "Οι ρυθμίσεις αποθηκεύτηκαν" +#define D_CONFIGURATION_RESET "Επαναφορά ρυθμίσεων" + +#define D_PROGRAM_VERSION "Εκδοση προγράμματος" +#define D_BUILD_DATE_AND_TIME "Ημερομηνία και Ώρα Build" +#define D_CORE_AND_SDK_VERSION "Core/SDK Version" +#define D_FLASH_WRITE_COUNT "Μετρητής εγγραφών Flash" +#define D_MAC_ADDRESS "MAC Address" +#define D_MQTT_HOST "MQTT Host" +#define D_MQTT_PORT "MQTT Port" +#define D_MQTT_CLIENT "MQTT Client" +#define D_MQTT_USER "MQTT User" +#define D_MQTT_TOPIC "MQTT Topic" +#define D_MQTT_GROUP_TOPIC "MQTT Group Topic" +#define D_MQTT_FULL_TOPIC "MQTT Full Topic" +#define D_MDNS_DISCOVERY "mDNS Discovery" +#define D_MDNS_ADVERTISE "mDNS Advertise" +#define D_ESP_CHIP_ID "ESP Chip Id" +#define D_FLASH_CHIP_ID "Flash Chip Id" +#define D_FLASH_CHIP_SIZE "Μέγεθος Flash" +#define D_FREE_PROGRAM_SPACE "Ελεύθερος Χώρος Προγράμματος" + +#define D_UPGRADE_BY_WEBSERVER "αναβάθμιση από τον διακομιστή web" +#define D_OTA_URL "OTA Url" +#define D_START_UPGRADE "Εκκίνηση αναβάθμισης" +#define D_UPGRADE_BY_FILE_UPLOAD "Αναβάθμιση με ανέβασμα αρχείου" +#define D_UPLOAD_STARTED "Το ανέβασμα ξεκίνησε" +#define D_UPGRADE_STARTED "Η αναβάθμιση ξεκίνησε" +#define D_UPLOAD_DONE "Το ανέβασμα ολοκληρώθηκε" +#define D_UPLOAD_ERR_1 "Δεν έχει επιλεγεί αρχείο" +#define D_UPLOAD_ERR_2 "Δεν υπάρχει αρκετός χώρος" +#define D_UPLOAD_ERR_3 "Magic byte δεν είναι 0xE9" +#define D_UPLOAD_ERR_4 "Το μέγεθος του προγράμματος flash είναι μεγαλύτερο από το πραγματικό μέγεθος του flash" +#define D_UPLOAD_ERR_5 "Upload buffer miscompare" +#define D_UPLOAD_ERR_6 "Το ανέβασμα απέτυχε. Επιλέξτε επίπεδο καταγραφής 3" +#define D_UPLOAD_ERR_7 "Το ανεβάσμα διακόπηκε" +#define D_UPLOAD_ERR_8 "Μη έγκυρο αρχείο" +#define D_UPLOAD_ERR_9 "Το αρχείο είναι πολύ μεγάλο" +#define D_UPLOAD_ERROR_CODE "Κωδικός λάθους ανεβάσματος" + +#define D_ENTER_COMMAND "Εισαγωγή εντολής" +#define D_ENABLE_WEBLOG_FOR_RESPONSE "Ενεργοποιήστε το weblog 2 αν περιμένετε απάντηση" +#define D_NEED_USER_AND_PASSWORD "Χρειάζεστε user=<όνομα χρήστη>&password=<κωδικό χρήστη>" + +// xdrv_00_mqtt.ino +#define D_FINGERPRINT "Επαλήθευση TLS fingerprint..." +#define D_TLS_CONNECT_FAILED_TO "Αποτυχία TLS σύνδεσης" +#define D_RETRY_IN "Επανάληψη σε" +#define D_VERIFIED "Επαλήθευση με Fingerprint" +#define D_INSECURE "Μη ασφαλής σύνδεση λόγο ακατάλληλου Fingerprint" +#define D_CONNECT_FAILED_TO "Αποτυχία σύνδεσης στο" + +// xdrv_wemohue.ino +#define D_MULTICAST_DISABLED "Multicast απενεργοποιημένο" +#define D_MULTICAST_REJOINED "Multicast επανασύνδεση" +#define D_MULTICAST_JOIN_FAILED "Αποτυχία σύνδεσης Multicast" +#define D_FAILED_TO_SEND_RESPONSE "Αποτυχία αποστολής απάντησης" + +#define D_WEMO "WeMo" +#define D_WEMO_BASIC_EVENT "WeMo βασικό event" +#define D_WEMO_EVENT_SERVICE "WeMo υπηρεσία event" +#define D_WEMO_META_SERVICE "WeMo υπηρεσία meta" +#define D_WEMO_SETUP "WeMo ρυθμίσεις" +#define D_RESPONSE_SENT "Αποστολή απάντησης" + +#define D_HUE "Hue" +#define D_HUE_BRIDGE_SETUP "Hue ρυθμίσεις" +#define D_HUE_API_NOT_IMPLEMENTED "Hue API δεν έχει υλοποιηθεί" +#define D_HUE_API "Hue API" +#define D_HUE_POST_ARGS "Hue POST args" +#define D_3_RESPONSE_PACKETS_SENT "3πλο πακέτο απάντησεης στάλθηκε" + +// xdrv_05_domoticz.ino +#define D_DOMOTICZ_PARAMETERS "Domoticz παράμετροι" +#define D_DOMOTICZ_IDX "Idx" +#define D_DOMOTICZ_KEY_IDX "Key idx" +#define D_DOMOTICZ_SWITCH_IDX "Switch idx" +#define D_DOMOTICZ_SENSOR_IDX "Sensor idx" + #define D_DOMOTICZ_TEMP "Temp" + #define D_DOMOTICZ_TEMP_HUM "Temp,Hum" + #define D_DOMOTICZ_TEMP_HUM_BARO "Temp,Hum,Baro" + #define D_DOMOTICZ_POWER_ENERGY "Power,Energy" + #define D_DOMOTICZ_ILLUMINANCE "Illuminance" + #define D_DOMOTICZ_COUNT "Count/PM1" + #define D_DOMOTICZ_VOLTAGE "Voltage/PM2.5" + #define D_DOMOTICZ_CURRENT "Current/PM10" + #define D_DOMOTICZ_AIRQUALITY "Ποιότητα Αέρα" +#define D_DOMOTICZ_UPDATE_TIMER "Ενημέρωση" + +// xdrv_09_timers.ino +#define D_CONFIGURE_TIMER "Ρυθμίσεις Χρόνου" +#define D_TIMER_PARAMETERS "Χρονικοί παράμετροι" +#define D_TIMER_ARM "Arm" +#define D_TIMER_TIME "Ωρα" +#define D_TIMER_DAYS "Μέρες" +#define D_TIMER_REPEAT "Επανάληψη" +#define D_TIMER_OUTPUT "Αποτέλεσμα" +#define D_TIMER_ACTION "Εντολή" + +// xdrv_10_knx.ino +#define D_CONFIGURE_KNX "Ρυθμίσεις KNX" +#define D_KNX_PARAMETERS "KNX Παράμετροι" +#define D_KNX_GENERAL_CONFIG "Γενικά" +#define D_KNX_PHYSICAL_ADDRESS "Διεύθυνση Μνήμης" +#define D_KNX_PHYSICAL_ADDRESS_NOTE "( Πρέπει να είναι μοναδική στο KNX δίκτυο )" +#define D_KNX_ENABLE "Ενεργοποιημένο KNX" +#define D_KNX_GROUP_ADDRESS_TO_WRITE "Αποστολή δεδομένων σε Ομάδα Διευθύνσεων" +#define D_ADD "Προσθήκη" +#define D_DELETE "Διαγραφή" +#define D_REPLY "Επανάληψη" +#define D_KNX_GROUP_ADDRESS_TO_READ "Ομάδα Διευθύνσεων που θα λάβει τα Δεδομένα" +#define D_LOG_KNX "KNX: " +#define D_RECEIVED_FROM "Στάλθηκε από" +#define D_KNX_COMMAND_WRITE "Εγγραφή" +#define D_KNX_COMMAND_READ "Ανάγνωση" +#define D_KNX_COMMAND_OTHER "Αλλο" +#define D_SENT_TO "αποστολή σε" +#define D_KNX_WARNING "Η Ομάδα Διευθύνσεων ( 0 / 0 / 0 ) είναι δεσμευμένη και δεν μπορεί να χρησιμοποιηθεί." + +// xdrv_03_energy.ino +#define D_ENERGY_TODAY "Energy Σήμερα" +#define D_ENERGY_YESTERDAY "Energy Χτες" +#define D_ENERGY_TOTAL "Energy Συνολικά" + +// xsns_05_ds18b20.ino +#define D_SENSOR_BUSY "Απασχολημένος Σένσορας" +#define D_SENSOR_CRC_ERROR "CRC λάθος σένσορα" +#define D_SENSORS_FOUND "Βρέθηκε σένσορας" + +// xsns_06_dht.ino +#define D_TIMEOUT_WAITING_FOR "Timeout περιμένετε για" +#define D_START_SIGNAL_LOW "εκκίνηση με χαμηλό σήμα" +#define D_START_SIGNAL_HIGH "εκκίνηση με υψηλό σήμα" +#define D_PULSE "παλμός" +#define D_CHECKSUM_FAILURE "Αποτυχία Checksum" + +// xsns_07_sht1x.ino +#define D_SENSOR_DID_NOT_ACK_COMMAND "Ο σένσορας δεν έλαβε την εντολή ACK" +#define D_SHT1X_FOUND "Βρέθηκε SHT1X" + +// xsns_18_pms5003.ino +#define D_STANDARD_CONCENTRATION "CF-1 PM" // Standard Particle CF-1 Particle Matter +#define D_ENVIRONMENTAL_CONCENTRATION "PM" // Environmetal Particle Matter +#define D_PARTICALS_BEYOND "Particals" + +// sonoff_template.h +#define D_SENSOR_NONE "Κανένας" +#define D_SENSOR_DHT11 "DHT11" +#define D_SENSOR_AM2301 "AM2301" +#define D_SENSOR_SI7021 "SI7021" +#define D_SENSOR_DS18X20 "DS18x20" +#define D_SENSOR_I2C_SCL "I2C SCL" +#define D_SENSOR_I2C_SDA "I2C SDA" +#define D_SENSOR_WS2812 "WS2812" +#define D_SENSOR_IRSEND "IRsend" +#define D_SENSOR_SWITCH "Διακόπτης" // Suffix "1" +#define D_SENSOR_BUTTON "Κουμπί" // Suffix "1" +#define D_SENSOR_RELAY "Ρελέ" // Suffix "1i" +#define D_SENSOR_LED "Led" // Suffix "1i" +#define D_SENSOR_PWM "PWM" // Suffix "1" +#define D_SENSOR_COUNTER "Μετρητής" // Suffix "1" +#define D_SENSOR_IRRECV "IRrecv" +#define D_SENSOR_MHZ_RX "MHZ Rx" +#define D_SENSOR_MHZ_TX "MHZ Tx" +#define D_SENSOR_PZEM_RX "PZEM Rx" +#define D_SENSOR_PZEM_TX "PZEM Tx" +#define D_SENSOR_SAIR_RX "SAir Rx" +#define D_SENSOR_SAIR_TX "SAir Tx" +#define D_SENSOR_SPI_CS "SPI CS" +#define D_SENSOR_SPI_DC "SPI DC" +#define D_SENSOR_BACKLIGHT "BkLight" +#define D_SENSOR_PMS5003 "PMS5003" +#define D_SENSOR_SDS0X1 "SDS0X1" +#define D_SENSOR_SBR_RX "SerBr Rx" +#define D_SENSOR_SBR_TX "SerBr Tx" +#define D_SENSOR_SR04_TRIG "SR04 Tri" +#define D_SENSOR_SR04_ECHO "SR04 Ech" + +// Units +#define D_UNIT_AMPERE "A" +#define D_UNIT_CENTIMETER "cm" +#define D_UNIT_HOUR "Hr" +#define D_UNIT_KILOOHM "kOhm" +#define D_UNIT_KILOWATTHOUR "kWh" +#define D_UNIT_LUX "lx" +#define D_UNIT_MICROGRAM_PER_CUBIC_METER "ug/m3" +#define D_UNIT_MICROMETER "um" +#define D_UNIT_MICROSECOND "us" +#define D_UNIT_MILLIAMPERE "mA" +#define D_UNIT_MILLISECOND "ms" +#define D_UNIT_MINUTE "Min" +#define D_UNIT_PARTS_PER_BILLION "ppb" +#define D_UNIT_PARTS_PER_DECILITER "ppd" +#define D_UNIT_PARTS_PER_MILLION "ppm" +#define D_UNIT_PRESSURE "hPa" +#define D_UNIT_SECOND "sec" +#define D_UNIT_SECTORS "sectors" +#define D_UNIT_VOLT "V" +#define D_UNIT_WATT "W" +#define D_UNIT_WATTHOUR "Wh" + +// Log message prefix +#define D_LOG_APPLICATION "APP: " // Application +#define D_LOG_BRIDGE "BRG: " // Bridge +#define D_LOG_CONFIG "CFG: " // Settings +#define D_LOG_COMMAND "CMD: " // Command +#define D_LOG_DEBUG "DBG: " // Debug +#define D_LOG_DHT "DHT: " // DHT sensor +#define D_LOG_DOMOTICZ "DOM: " // Domoticz +#define D_LOG_DSB "DSB: " // DS18xB20 sensor +#define D_LOG_HTTP "HTP: " // HTTP webserver +#define D_LOG_I2C "I2C: " // I2C +#define D_LOG_IRR "IRR: " // Infra Red Received +#define D_LOG_LOG "LOG: " // Logging +#define D_LOG_MODULE "MOD: " // Module +#define D_LOG_MDNS "DNS: " // mDNS +#define D_LOG_MQTT "MQT: " // MQTT +#define D_LOG_OTHER "OTH: " // Other +#define D_LOG_RESULT "RSL: " // Result +#define D_LOG_RFR "RFR: " // RF Received +#define D_LOG_SERIAL "SER: " // Serial +#define D_LOG_SHT1 "SHT: " // SHT1x sensor +#define D_LOG_UPLOAD "UPL: " // Upload +#define D_LOG_UPNP "UPP: " // UPnP +#define D_LOG_WIFI "WIF: " // Wifi + +#endif // _LANGUAGE_EN_GB_H_ diff --git a/sonoff/language/en-GB.h b/sonoff/language/en-GB.h index 77db37009..ade787b9e 100644 --- a/sonoff/language/en-GB.h +++ b/sonoff/language/en-GB.h @@ -28,10 +28,14 @@ * Use online command StateText to translate ON, OFF, HOLD and TOGGLE. * Use online command Prefix to translate cmnd, stat and tele. * + * Updated until v5.12.0n \*********************************************************************/ //#define LANGUAGE_MODULE_NAME // Enable to display "Module Generic" (ie Spanish), Disable to display "Generic Module" (ie English) +// HTML (ISO 639-1) Language Code +#define D_HTML_LANGUAGE "en" + // "2017-03-07T11:08:02" - ISO8601:2004 #define D_YEAR_MONTH_SEPARATOR "-" #define D_MONTH_DAY_SEPARATOR "-" @@ -71,9 +75,11 @@ #define D_DARKLIGHT "Dark" #define D_DEBUG "Debug" #define D_DISABLED "Disabled" +#define D_DISTANCE "Distance" #define D_DNS_SERVER "DNS Server" #define D_DONE "Done" #define D_DST_TIME "DST" +#define D_ECO2 "eCO2" #define D_EMULATION "Emulation" #define D_ENABLED "Enabled" #define D_ERASE "Erase" @@ -124,6 +130,7 @@ #define D_RESTART_REASON "Restart Reason" #define D_RESTORE "restore" #define D_RETAINED "retained" +#define D_RULE "Rule" #define D_SAVE "Save" #define D_SENSOR "Sensor" #define D_SSID "SSId" @@ -133,12 +140,15 @@ #define D_SUBNET_MASK "Subnet Mask" #define D_SUBSCRIBE_TO "Subscribe to" #define D_SUCCESSFUL "Successful" +#define D_SUNRISE "Sunrise" +#define D_SUNSET "Sunset" #define D_TEMPERATURE "Temperature" #define D_TO "to" #define D_TOGGLE "Toggle" #define D_TOPIC "Topic" #define D_TRANSMIT "Transmit" #define D_TRUE "True" +#define D_TVOC "TVOC" #define D_UPGRADE "upgrade" #define D_UPLOAD "Upload" #define D_UPTIME "Uptime" @@ -162,13 +172,6 @@ #define D_DATA_SIZE "Data Size" #define D_ANALOG_INPUT "Analog" -#define D_FINGERPRINT "Verify TLS fingerprint..." -#define D_TLS_CONNECT_FAILED_TO "TLS Connect failed to" -#define D_RETRY_IN "Retry in" -#define D_VERIFIED "Verified" -#define D_INSECURE "Insecure connection due to invalid Fingerprint" -#define D_CONNECT_FAILED_TO "Connect failed to" - // support.ino #define D_OSWATCH "osWatch" #define D_BLOCKED_LOOP "Blocked Loop" @@ -317,6 +320,14 @@ #define D_ENABLE_WEBLOG_FOR_RESPONSE "Enable weblog 2 if response expected" #define D_NEED_USER_AND_PASSWORD "Need user=&password=" +// xdrv_00_mqtt.ino +#define D_FINGERPRINT "Verify TLS fingerprint..." +#define D_TLS_CONNECT_FAILED_TO "TLS Connect failed to" +#define D_RETRY_IN "Retry in" +#define D_VERIFIED "Verified using Fingerprint" +#define D_INSECURE "Insecure connection due to invalid Fingerprint" +#define D_CONNECT_FAILED_TO "Connect failed to" + // xdrv_wemohue.ino #define D_MULTICAST_DISABLED "Multicast disabled" #define D_MULTICAST_REJOINED "Multicast (re)joined" @@ -348,12 +359,42 @@ #define D_DOMOTICZ_TEMP_HUM_BARO "Temp,Hum,Baro" #define D_DOMOTICZ_POWER_ENERGY "Power,Energy" #define D_DOMOTICZ_ILLUMINANCE "Illuminance" - #define D_DOMOTICZ_COUNT "Count" - #define D_DOMOTICZ_VOLTAGE "Voltage" - #define D_DOMOTICZ_CURRENT "Current" + #define D_DOMOTICZ_COUNT "Count/PM1" + #define D_DOMOTICZ_VOLTAGE "Voltage/PM2.5" + #define D_DOMOTICZ_CURRENT "Current/PM10" #define D_DOMOTICZ_AIRQUALITY "AirQuality" #define D_DOMOTICZ_UPDATE_TIMER "Update timer" +// xdrv_09_timers.ino +#define D_CONFIGURE_TIMER "Configure Timer" +#define D_TIMER_PARAMETERS "Timer parameters" +#define D_TIMER_ARM "Arm" +#define D_TIMER_TIME "Time" +#define D_TIMER_DAYS "Days" +#define D_TIMER_REPEAT "Repeat" +#define D_TIMER_OUTPUT "Output" +#define D_TIMER_ACTION "Action" + +// xdrv_10_knx.ino +#define D_CONFIGURE_KNX "Configure KNX" +#define D_KNX_PARAMETERS "KNX Parameters" +#define D_KNX_GENERAL_CONFIG "General" +#define D_KNX_PHYSICAL_ADDRESS "Physical Address" +#define D_KNX_PHYSICAL_ADDRESS_NOTE "( Must be unique on the KNX network )" +#define D_KNX_ENABLE "Enable KNX" +#define D_KNX_GROUP_ADDRESS_TO_WRITE "Data to Send to Group Addresses" +#define D_ADD "Add" +#define D_DELETE "Delete" +#define D_REPLY "Reply" +#define D_KNX_GROUP_ADDRESS_TO_READ "Group Addresses to Receive Data from" +#define D_LOG_KNX "KNX: " +#define D_RECEIVED_FROM "Received from" +#define D_KNX_COMMAND_WRITE "Write" +#define D_KNX_COMMAND_READ "Read" +#define D_KNX_COMMAND_OTHER "Other" +#define D_SENT_TO "sent to" +#define D_KNX_WARNING "The group address ( 0 / 0 / 0 ) is reserved and can not be used." + // xdrv_03_energy.ino #define D_ENERGY_TODAY "Energy Today" #define D_ENERGY_YESTERDAY "Energy Yesterday" @@ -407,9 +448,15 @@ #define D_SENSOR_SPI_DC "SPI DC" #define D_SENSOR_BACKLIGHT "BkLight" #define D_SENSOR_PMS5003 "PMS5003" +#define D_SENSOR_SDS0X1 "SDS0X1" +#define D_SENSOR_SBR_RX "SerBr Rx" +#define D_SENSOR_SBR_TX "SerBr Tx" +#define D_SENSOR_SR04_TRIG "SR04 Tri" +#define D_SENSOR_SR04_ECHO "SR04 Ech" // Units #define D_UNIT_AMPERE "A" +#define D_UNIT_CENTIMETER "cm" #define D_UNIT_HOUR "Hr" #define D_UNIT_KILOOHM "kOhm" #define D_UNIT_KILOWATTHOUR "kWh" @@ -420,6 +467,7 @@ #define D_UNIT_MILLIAMPERE "mA" #define D_UNIT_MILLISECOND "ms" #define D_UNIT_MINUTE "Min" +#define D_UNIT_PARTS_PER_BILLION "ppb" #define D_UNIT_PARTS_PER_DECILITER "ppd" #define D_UNIT_PARTS_PER_MILLION "ppm" #define D_UNIT_PRESSURE "hPa" diff --git a/sonoff/language/es-AR.h b/sonoff/language/es-AR.h index e54098edf..ded21e8e7 100644 --- a/sonoff/language/es-AR.h +++ b/sonoff/language/es-AR.h @@ -28,10 +28,14 @@ * Use online command StateText to translate ON, OFF, HOLD and TOGGLE. * Use online command Prefix to translate cmnd, stat and tele. * + * Updated until v5.12.0m \*********************************************************************/ #define LANGUAGE_MODULE_NAME // Enable to display "Module Generic" (ie Spanish), Disable to display "Generic Module" (ie English) +// HTML (ISO 639-1) Language Code +#define D_HTML_LANGUAGE "es" + // "2017-03-07T11:08:02" - ISO8601:2004 #define D_YEAR_MONTH_SEPARATOR "-" #define D_MONTH_DAY_SEPARATOR "-" @@ -71,9 +75,11 @@ #define D_DARKLIGHT "Oscura" #define D_DEBUG "Debug" #define D_DISABLED "Deshabilitado" +#define D_DISTANCE "Distancia" #define D_DNS_SERVER "DNS Server" #define D_DONE "Listo" #define D_DST_TIME "DST" +#define D_ECO2 "eCO2" #define D_EMULATION "Emulación" #define D_ENABLED "Habilitado" #define D_ERASE "Borrar" @@ -124,6 +130,7 @@ #define D_RESTART_REASON "Causa Reinicio" #define D_RESTORE "Restauración" #define D_RETAINED "Grabado" +#define D_RULE "Rule" #define D_SAVE "Grabar" #define D_SENSOR "Sensor" #define D_SSID "SSId" @@ -133,12 +140,15 @@ #define D_SUBNET_MASK "Máscara Subred" #define D_SUBSCRIBE_TO "Suscribir a" #define D_SUCCESSFUL "Exitosa" +#define D_SUNRISE "Salida del Sol" +#define D_SUNSET "Puesta del Sol" #define D_TEMPERATURE "Temperatura" #define D_TO "a" #define D_TOGGLE "Conmutar" #define D_TOPIC "Topic" #define D_TRANSMIT "Transmitir" #define D_TRUE "Verdadero" +#define D_TVOC "TVOC" #define D_UPGRADE "Actualización" #define D_UPLOAD "Carga" #define D_UPTIME "Tiempo Encendido" @@ -162,13 +172,6 @@ #define D_DATA_SIZE "Tamaño de Datos" #define D_ANALOG_INPUT "Entrada Analógica" -#define D_FINGERPRINT "Verificar TLS fingerprint..." -#define D_TLS_CONNECT_FAILED_TO "Falló Conección TLS a" -#define D_RETRY_IN "Reintentando" -#define D_VERIFIED "Verificado" -#define D_INSECURE "Conección insegura por Fingerprint no válido" -#define D_CONNECT_FAILED_TO "Falló Conección a" - // support.ino #define D_OSWATCH "osWatch" #define D_BLOCKED_LOOP "Ciclo Bloqueado" @@ -317,6 +320,14 @@ #define D_ENABLE_WEBLOG_FOR_RESPONSE "Habilitar weblog 2 si desea respuesta" #define D_NEED_USER_AND_PASSWORD "Se necesita user=&password=" +// xdrv_00_mqtt.ino +#define D_FINGERPRINT "Verificar TLS fingerprint..." +#define D_TLS_CONNECT_FAILED_TO "Falló Conección TLS a" +#define D_RETRY_IN "Reintentando" +#define D_VERIFIED "Verificado Fingerprint" +#define D_INSECURE "Conección insegura por Fingerprint no válido" +#define D_CONNECT_FAILED_TO "Falló Conección a" + // xdrv_wemohue.ino #define D_MULTICAST_DISABLED "Multicast deshabilitado" #define D_MULTICAST_REJOINED "Multicast (re)conectado" @@ -348,12 +359,42 @@ #define D_DOMOTICZ_TEMP_HUM_BARO "Temp,Hum,Baro" #define D_DOMOTICZ_POWER_ENERGY "Potencia,Energía" #define D_DOMOTICZ_ILLUMINANCE "Luminancia" - #define D_DOMOTICZ_COUNT "Contador" - #define D_DOMOTICZ_VOLTAGE "Voltaje" - #define D_DOMOTICZ_CURRENT "Corriente" + #define D_DOMOTICZ_COUNT "Contador/PM1" + #define D_DOMOTICZ_VOLTAGE "Voltaje/PM2,5" + #define D_DOMOTICZ_CURRENT "Corriente/PM10" #define D_DOMOTICZ_AIRQUALITY "Calidad del Aire" #define D_DOMOTICZ_UPDATE_TIMER "Intervalo de refresco" +// xdrv_09_timers.ino +#define D_CONFIGURE_TIMER "Configuración Temporizadores" +#define D_TIMER_PARAMETERS "Parámetros de Temporizadores" +#define D_TIMER_ARM "Activo" +#define D_TIMER_TIME "Hora" +#define D_TIMER_DAYS "Días" +#define D_TIMER_REPEAT "Repetir" +#define D_TIMER_OUTPUT "Salida" +#define D_TIMER_ACTION "Estado" + +// xdrv_10_knx.ino +#define D_CONFIGURE_KNX "Configuración de KNX" +#define D_KNX_PARAMETERS "Parámetros de KNX" +#define D_KNX_GENERAL_CONFIG "General" +#define D_KNX_PHYSICAL_ADDRESS "Dirección Física" +#define D_KNX_PHYSICAL_ADDRESS_NOTE "( Debe ser única en la red KNX )" +#define D_KNX_ENABLE "Habilitar KNX" +#define D_KNX_GROUP_ADDRESS_TO_WRITE "Datos a Enviar a las Direcciones de Grupo" +#define D_ADD "Agregar" +#define D_DELETE "Eliminar" +#define D_REPLY "Responder" +#define D_KNX_GROUP_ADDRESS_TO_READ "Direcciones de Grupo para Recibir Datos" +#define D_LOG_KNX "KNX: " +#define D_RECEIVED_FROM "Recibido desde" +#define D_KNX_COMMAND_WRITE "Escribir" +#define D_KNX_COMMAND_READ "Leer" +#define D_KNX_COMMAND_OTHER "Otro" +#define D_SENT_TO "enviada a" +#define D_KNX_WARNING "La dirección de grupo ( 0 / 0 / 0 ) está reservada y no puede ser utilizada." + // xdrv_03_energy.ino #define D_ENERGY_TODAY "Energía Hoy" #define D_ENERGY_YESTERDAY "Energía Ayer" @@ -407,9 +448,15 @@ #define D_SENSOR_SPI_DC "SPI DC" #define D_SENSOR_BACKLIGHT "BkLight" #define D_SENSOR_PMS5003 "PMS5003" +#define D_SENSOR_SDS0X1 "SDS0X1" +#define D_SENSOR_SBR_RX "SerBr Rx" +#define D_SENSOR_SBR_TX "SerBr Tx" +#define D_SENSOR_SR04_TRIG "SR04 Tri" +#define D_SENSOR_SR04_ECHO "SR04 Ech" // Units #define D_UNIT_AMPERE "A" +#define D_UNIT_CENTIMETER "cm" #define D_UNIT_HOUR "Hr" #define D_UNIT_KILOOHM "kOhm" #define D_UNIT_KILOWATTHOUR "kWh" @@ -420,6 +467,7 @@ #define D_UNIT_MILLIAMPERE "mA" #define D_UNIT_MILLISECOND "ms" #define D_UNIT_MINUTE "Min" +#define D_UNIT_PARTS_PER_BILLION "ppb" #define D_UNIT_PARTS_PER_DECILITER "ppd" #define D_UNIT_PARTS_PER_MILLION "ppm" #define D_UNIT_PRESSURE "hPa" diff --git a/sonoff/language/fr-FR.h b/sonoff/language/fr-FR.h index 78afc0677..a9211dab1 100644 --- a/sonoff/language/fr-FR.h +++ b/sonoff/language/fr-FR.h @@ -28,10 +28,14 @@ * Use online command StateText to translate ON, OFF, HOLD and TOGGLE. * Use online command Prefix to translate cmnd, stat and tele. * + * Updated until v5.12.0m \*********************************************************************/ #define LANGUAGE_MODULE_NAME // Enable to display "Module Generic" (ie Spanish), Disable to display "Generic Module" (ie English) +// HTML (ISO 639-1) Language Code +#define D_HTML_LANGUAGE "fr" + // "2017-03-07T11:08:02" - ISO8601:2004 #define D_YEAR_MONTH_SEPARATOR "-" #define D_MONTH_DAY_SEPARATOR "-" @@ -55,7 +59,7 @@ #define D_BLINKOFF "BlinkOff" #define D_BOOT_COUNT "Nombre de boot" #define D_BRIGHTLIGHT "Luminosité" -#define D_BUTTON "Boutton" +#define D_BUTTON "Bouton" #define D_BY "par" // Written by me #define D_BYTES "Bytes" #define D_CELSIUS "Celsius" @@ -66,25 +70,27 @@ #define D_CONNECTED "Connecté" #define D_COUNT "Compte" #define D_COUNTER "Compteur" -#define D_CURRENT "Courrant" // As in Voltage and Current -#define D_DATA "Data" +#define D_CURRENT "Courant" // As in Voltage and Current +#define D_DATA "Donnée" #define D_DARKLIGHT "Sombre" #define D_DEBUG "Debug" #define D_DISABLED "Désactivé" +#define D_DISTANCE "Distance" #define D_DNS_SERVER "Serveur DNS" #define D_DONE "Fait" #define D_DST_TIME "DST" -#define D_EMULATION "Emulation" +#define D_ECO2 "eCO2" +#define D_EMULATION "Émulation" #define D_ENABLED "Activé" #define D_ERASE "Effacer" #define D_ERROR "Erreur" #define D_FAHRENHEIT "Fahrenheit" -#define D_FAILED "Echoué" -#define D_FALLBACK "Fallback" -#define D_FALLBACK_TOPIC "Fallback Topic" +#define D_FAILED "Échoué" +#define D_FALLBACK "Secours" +#define D_FALLBACK_TOPIC "Topic de secours" #define D_FALSE "Faux" #define D_FILE "Fichier" -#define D_FREE_MEMORY "Memoire libre" +#define D_FREE_MEMORY "Mémoire libre" #define D_GAS "Gaz" #define D_GATEWAY "Passerelle" #define D_GROUP "Groupe" @@ -92,7 +98,7 @@ #define D_HOSTNAME "Hostname" #define D_HUMIDITY "Humidité" #define D_ILLUMINANCE "Éclairement" -#define D_IMMEDIATE "immediat" // Button immediate +#define D_IMMEDIATE "immédiat" // Button immediate #define D_INDEX "Index" #define D_INFO "Info" #define D_INITIALIZED "Initialisé" @@ -103,11 +109,11 @@ #define D_MQTT "MQTT" #define D_MULTI_PRESS "multi-pression" #define D_NOISE "Bruit" -#define D_NONE "None" -#define D_OFF "Off" +#define D_NONE "Aucun" +#define D_OFF "Arrêt" #define D_OFFLINE "Déconnecté" #define D_OK "Ok" -#define D_ON "On" +#define D_ON "Marche" #define D_ONLINE "Connecté" #define D_PASSWORD "Mot de passe" #define D_PORT "Port" @@ -120,33 +126,37 @@ #define D_PROJECT "Projet" #define D_RECEIVED "Reçu" #define D_RESTART "Redémarrage" -#define D_RESTARTING "Redémarrage" -#define D_RESTART_REASON "Raison redémarrage" -#define D_RESTORE "restorer" +#define D_RESTARTING "Redémarre" +#define D_RESTART_REASON "Raison du redémarrage" +#define D_RESTORE "restaurer" #define D_RETAINED "retenu" -#define D_SAVE "Enregister" +#define D_RULE "Règle" +#define D_SAVE "Enregistrer" #define D_SENSOR "Capteur" #define D_SSID "SSID" -#define D_START "Start" +#define D_START "Lancer" // "Lancer la mise à jour" #define D_STD_TIME "STD" #define D_STOP "Stop" -#define D_SUBNET_MASK "Masque sous réseau" +#define D_SUBNET_MASK "Masque sous-réseau" #define D_SUBSCRIBE_TO "Souscrire à" #define D_SUCCESSFUL "Réussi" -#define D_TEMPERATURE "Temperature" +#define D_SUNRISE "Lever du jour" +#define D_SUNSET "Tombée de la nuit" +#define D_TEMPERATURE "Température" #define D_TO "à" -#define D_TOGGLE "Bascule" -#define D_TOPIC "Topic" +#define D_TOGGLE "Inverser" +#define D_TOPIC "Topic" // Keep MQTT keyword #define D_TRANSMIT "Transmettre" #define D_TRUE "Vrai" -#define D_UPGRADE "upgrade" -#define D_UPLOAD "Upload" -#define D_UPTIME "Uptime" +#define D_TVOC "TVOC" +#define D_UPGRADE "la mise à jour" // "Lancer la mise à jour" +#define D_UPLOAD "Upload" // Not better in french +#define D_UPTIME "Durée d'activité" #define D_USER "Utilisateur" #define D_UTC_TIME "UTC" #define D_UV_LEVEL "Niveau UV" #define D_VERSION "Version" -#define D_VOLTAGE "Voltage" +#define D_VOLTAGE "Tension" #define D_WARMLIGHT "Chaud" #define D_WEB_SERVER "Serveur web" @@ -154,43 +164,36 @@ #define D_WARNING_MINIMAL_VERSION "ATTENTION Cette version ne supporte pas les réglages persistants" #define D_LEVEL_10 "level 1-0" #define D_LEVEL_01 "level 0-1" -#define D_SERIAL_LOGGING_DISABLED "Journalisation série désactivé" -#define D_SYSLOG_LOGGING_REENABLED "Jounalisation syslog réactivé" +#define D_SERIAL_LOGGING_DISABLED "Journalisation série désactivée" +#define D_SYSLOG_LOGGING_REENABLED "Jounalisation syslog réactivée" -#define D_SET_BAUDRATE_TO "Definir baudrate à" -#define D_RECEIVED_TOPIC "Topic reçu" +#define D_SET_BAUDRATE_TO "Définir baudrate à" +#define D_RECEIVED_TOPIC "Topic reçu" // Terme MQTT #define D_DATA_SIZE "Taille données" #define D_ANALOG_INPUT "Analogique" -#define D_FINGERPRINT "Verification empreinte TLS ..." -#define D_TLS_CONNECT_FAILED_TO "Echec de connexion TLS à" -#define D_RETRY_IN "Nouvelle tentative dans" -#define D_VERIFIED "Verifié" -#define D_INSECURE "Connexion non sécurisée car empreinte non vérifée" -#define D_CONNECT_FAILED_TO "Echec de connexion à" - // support.ino #define D_OSWATCH "osWatch" #define D_BLOCKED_LOOP "Boucle bloquée" -#define D_WPS_FAILED_WITH_STATUS "WPSconfig ECHOUÉ avec status" +#define D_WPS_FAILED_WITH_STATUS "WPSconfig ÉCHOUÉ avec status" #define D_ACTIVE_FOR_3_MINUTES "actif pour 3 minutes" -#define D_FAILED_TO_START "Echec de démarrage" -#define D_PATCH_ISSUE_2186 "Patch issue 2186" +#define D_FAILED_TO_START "Échec de démarrage" +#define D_PATCH_ISSUE_2186 "Correction 2186" #define D_CONNECTING_TO_AP "Connexion à l'AP" #define D_IN_MODE "en mode" -#define D_CONNECT_FAILED_NO_IP_ADDRESS "Echec de connexion car aucune adresse IP n'a été reçue" -#define D_CONNECT_FAILED_AP_NOT_REACHED "Echec de connexion car l'AP ne peut-être contacté" -#define D_CONNECT_FAILED_WRONG_PASSWORD "Echec de connexion car le mot de passe de l'AP est incorrect" -#define D_CONNECT_FAILED_AP_TIMEOUT "Echec de connexion avec l'AP, expiré" +#define D_CONNECT_FAILED_NO_IP_ADDRESS "Échec de connexion car aucune adresse IP n'a été reçue" +#define D_CONNECT_FAILED_AP_NOT_REACHED "Échec de connexion car l'AP ne peut-être contacté" +#define D_CONNECT_FAILED_WRONG_PASSWORD "Échec de connexion car le mot de passe de l'AP est incorrect" +#define D_CONNECT_FAILED_AP_TIMEOUT "Échec de connexion avec l'AP, expiré" #define D_ATTEMPTING_CONNECTION "Tentative de connexion..." -#define D_CHECKING_CONNECTION "Verification connexion..." -#define D_QUERY_DONE "Requête terminé. Services MQTT trouvés" +#define D_CHECKING_CONNECTION "Vérification connexion..." +#define D_QUERY_DONE "Requête terminée. Services MQTT trouvés" #define D_MQTT_SERVICE_FOUND "Service MQTT trouvé sur" #define D_FOUND_AT "trouvé à" #define D_SYSLOG_HOST_NOT_FOUND "Host syslog introuvable" // settings.ino -#define D_SAVED_TO_FLASH_AT "Enregistré dans la flash à" +#define D_SAVED_TO_FLASH_AT "Enregistré en flash à" #define D_LOADED_FROM_FLASH_AT "Chargé de la flash à" #define D_USE_DEFAULTS "Utiliser par défaut" #define D_ERASED_SECTOR "Secteur effacé" @@ -202,8 +205,8 @@ #define D_WEBSERVER_STOPPED "Serveur web éteint" #define D_FILE_NOT_FOUND "Fichier introuvable" #define D_REDIRECTED "Redirection sur le portail captif" -#define D_WIFIMANAGER_SET_ACCESSPOINT_AND_STATION "Wifimanager defini AccessPoint et garde station" -#define D_WIFIMANAGER_SET_ACCESSPOINT "Wifimanager defini AccessPoint" +#define D_WIFIMANAGER_SET_ACCESSPOINT_AND_STATION "Wifimanager définit AccessPoint et garde station" +#define D_WIFIMANAGER_SET_ACCESSPOINT "Wifimanager définit AccessPoint" #define D_TRYING_TO_CONNECT "Tentative de connexion du module au réseau" #define D_RESTART_IN "Redémarrage dans" @@ -212,24 +215,24 @@ #define D_BUTTON_TOGGLE "on/off" #define D_CONFIGURATION "Configuration" #define D_INFORMATION "Information" -#define D_FIRMWARE_UPGRADE "Mise à jour Firmware" +#define D_FIRMWARE_UPGRADE "Mise à jour du Firmware" #define D_CONSOLE "Console" #define D_CONFIRM_RESTART "Confirmer redémarrage" -#define D_CONFIGURE_MODULE "Configuration Module" +#define D_CONFIGURE_MODULE "Configuration du Module" #define D_CONFIGURE_WIFI "Configuration WiFi" #define D_CONFIGURE_MQTT "Configuration MQTT" #define D_CONFIGURE_DOMOTICZ "Configuration Domoticz" -#define D_CONFIGURE_LOGGING "Configuration Logging" +#define D_CONFIGURE_LOGGING "Configuration du journal" #define D_CONFIGURE_OTHER "Autre configuration" #define D_CONFIRM_RESET_CONFIGURATION "Confirmer réinitialisation configuration" -#define D_RESET_CONFIGURATION "Réinitialisation Configuration" -#define D_BACKUP_CONFIGURATION "Sauvegarde Configuration" -#define D_RESTORE_CONFIGURATION "Restauration Configuration" +#define D_RESET_CONFIGURATION "Configuration par défaut" +#define D_BACKUP_CONFIGURATION "Sauvegarde de la config." +#define D_RESTORE_CONFIGURATION "Restauration de la config." #define D_MAIN_MENU "Menu principal" #define D_MODULE_PARAMETERS "Paramètres module" -#define D_MODULE_TYPE "Type module" +#define D_MODULE_TYPE "Type de module" #define D_GPIO "GPIO" #define D_SERIAL_IN "Serial In" #define D_SERIAL_OUT "Serial Out" @@ -238,9 +241,9 @@ #define D_SCAN_FOR_WIFI_NETWORKS "Scan des réseaux wifi" #define D_SCAN_DONE "Scan terminé" #define D_NO_NETWORKS_FOUND "Aucun réseau trouvé" -#define D_REFRESH_TO_SCAN_AGAIN "Rafraichir pour scanner à nouveau" -#define D_DUPLICATE_ACCESSPOINT "AccessPoint dupliqué" -#define D_SKIPPING_LOW_QUALITY "Passe car mauvaise qualité" +#define D_REFRESH_TO_SCAN_AGAIN "Rafraîchir pour scanner à nouveau" +#define D_DUPLICATE_ACCESSPOINT "Point d'Accès dupliqué" +#define D_SKIPPING_LOW_QUALITY "Évité car de mauvaise qualité" #define D_RSSI "RSSI" #define D_WEP "WEP" #define D_WPA_PSK "WPA PSK" @@ -254,14 +257,14 @@ #define D_CLIENT "Client" #define D_FULL_TOPIC "topic complet" -#define D_LOGGING_PARAMETERS "Paramètres journalisation" +#define D_LOGGING_PARAMETERS "Paramètres du journal" #define D_SERIAL_LOG_LEVEL "Niveau de journalisation série" #define D_WEB_LOG_LEVEL "Niveau de journalisation web" -#define D_SYS_LOG_LEVEL "Niveau syslog" +#define D_SYS_LOG_LEVEL "Niveau Syslog" #define D_MORE_DEBUG "Plus de debug" -#define D_SYSLOG_HOST "Host syslog" -#define D_SYSLOG_PORT "Host syslog" -#define D_TELEMETRY_PERIOD "Période télémetrie" +#define D_SYSLOG_HOST "Hôte Syslog" +#define D_SYSLOG_PORT "Port Syslog" +#define D_TELEMETRY_PERIOD "Période télémétrie" #define D_OTHER_PARAMETERS "Autres paramètres" #define D_WEB_ADMIN_PASSWORD "Mot de passe Web Admin" @@ -272,11 +275,11 @@ #define D_SINGLE_DEVICE "module unique" #define D_MULTI_DEVICE "multi module" -#define D_SAVE_CONFIGURATION "Enregistrer configuration" -#define D_CONFIGURATION_SAVED "Configuration enregistré" -#define D_CONFIGURATION_RESET "Configuration réinitialisé" +#define D_SAVE_CONFIGURATION "Enregistrer la configuration" +#define D_CONFIGURATION_SAVED "Configuration enregistrée" +#define D_CONFIGURATION_RESET "Configuration réinitialisée" -#define D_PROGRAM_VERSION "Version Programme" +#define D_PROGRAM_VERSION "Version du programme" #define D_BUILD_DATE_AND_TIME "Date & Heure de build" #define D_CORE_AND_SDK_VERSION "Version Core/SDK" #define D_FLASH_WRITE_COUNT "Compteur écriture flash" @@ -300,42 +303,50 @@ #define D_START_UPGRADE "Lancer la mise à jour" #define D_UPGRADE_BY_FILE_UPLOAD "Mise à jour par téléchargement fichier" #define D_UPLOAD_STARTED "Téléchargement lancé" -#define D_UPGRADE_STARTED "Mise à jour lancé" +#define D_UPGRADE_STARTED "Mise à jour lancée" #define D_UPLOAD_DONE "Téléchargement terminé" #define D_UPLOAD_ERR_1 "Aucun fichier sélectionné" #define D_UPLOAD_ERR_2 "Espace insuffisant" -#define D_UPLOAD_ERR_3 "Magic byte n'est pas 0xE9" -#define D_UPLOAD_ERR_4 "La taille de la flash programme est plus grande que la taille réelle de la flash" -#define D_UPLOAD_ERR_5 "Erreur comparaison buffer de téléchargement" -#define D_UPLOAD_ERR_6 "Téléchargement échoué. Activation logging 3" +#define D_UPLOAD_ERR_3 "L'octet magique n'est pas 0xE9" +#define D_UPLOAD_ERR_4 "La taille du programme à flasher est plus grande que la taille réelle de la mémoire flash" +#define D_UPLOAD_ERR_5 "Erreur de comparaison du buffer de téléchargement" +#define D_UPLOAD_ERR_6 "Téléchargement échoué. Activer Weblog 3" #define D_UPLOAD_ERR_7 "Téléchargement annulé" #define D_UPLOAD_ERR_8 "Fichier invalide" #define D_UPLOAD_ERR_9 "Fichier trop grand" #define D_UPLOAD_ERROR_CODE "Code d'erreur téléchargement" -#define D_ENTER_COMMAND "Saisir commande" -#define D_ENABLE_WEBLOG_FOR_RESPONSE "Activer weblog 2 si response attendue" +#define D_ENTER_COMMAND "Saisir une commande" +#define D_ENABLE_WEBLOG_FOR_RESPONSE "Activer Weblog 2 si une réponse est attendue" #define D_NEED_USER_AND_PASSWORD "Nécessite utilisateur=&password=" +// xdrv_00_mqtt.ino +#define D_FINGERPRINT "Vérification d'empreinte TLS ..." +#define D_TLS_CONNECT_FAILED_TO "Échec de connexion TLS à" +#define D_RETRY_IN "Nouvelle tentative dans" +#define D_VERIFIED "Vérifié par empreinte " +#define D_INSECURE "Connexion non sécurisée car empreinte non vérifiée" +#define D_CONNECT_FAILED_TO "Échec de connexion à" + // xdrv_wemohue.ino #define D_MULTICAST_DISABLED "Multicast désactivé" #define D_MULTICAST_REJOINED "Multicast (re)joint" -#define D_MULTICAST_JOIN_FAILED "Multicast echec abonnement" -#define D_FAILED_TO_SEND_RESPONSE "Echec d'envoi réponse" +#define D_MULTICAST_JOIN_FAILED "Multicast échec abonnement" +#define D_FAILED_TO_SEND_RESPONSE "Échec d'envoi réponse" #define D_WEMO "WeMo" #define D_WEMO_BASIC_EVENT "WeMo basic event" #define D_WEMO_EVENT_SERVICE "WeMo event service" #define D_WEMO_META_SERVICE "WeMo meta service" #define D_WEMO_SETUP "Réglage WeMo" -#define D_RESPONSE_SENT "Response envoyé" +#define D_RESPONSE_SENT "Réponse envoyée" #define D_HUE "Hue" #define D_HUE_BRIDGE_SETUP "Réglage Hue" #define D_HUE_API_NOT_IMPLEMENTED "API Hue non implémentée" #define D_HUE_API "Hue API" #define D_HUE_POST_ARGS "Hue POST args" -#define D_3_RESPONSE_PACKETS_SENT "3 paquets response envoyés" +#define D_3_RESPONSE_PACKETS_SENT "3 paquets de réponse envoyés" // xdrv_05_domoticz.ino #define D_DOMOTICZ_PARAMETERS "Paramètres Domoticz" @@ -346,18 +357,48 @@ #define D_DOMOTICZ_TEMP "Temp" #define D_DOMOTICZ_TEMP_HUM "Temp,Hum" #define D_DOMOTICZ_TEMP_HUM_BARO "Temp,Hum,Baro" - #define D_DOMOTICZ_POWER_ENERGY "Power,Energy" + #define D_DOMOTICZ_POWER_ENERGY "Puissance,Énergie" #define D_DOMOTICZ_ILLUMINANCE "Illuminance" - #define D_DOMOTICZ_COUNT "Count" - #define D_DOMOTICZ_VOLTAGE "Voltage" - #define D_DOMOTICZ_CURRENT "Current" - #define D_DOMOTICZ_AIRQUALITY "AirQuality" -#define D_DOMOTICZ_UPDATE_TIMER "Update timer" + #define D_DOMOTICZ_COUNT "Compteur/PM1" + #define D_DOMOTICZ_VOLTAGE "Tension/PM2,5" + #define D_DOMOTICZ_CURRENT "Courant/PM10" + #define D_DOMOTICZ_AIRQUALITY "Qualité de l'air" +#define D_DOMOTICZ_UPDATE_TIMER "Durée de rafraichissement" + +// xdrv_09_timers.ino +#define D_CONFIGURE_TIMER "Configuration des Timers" +#define D_TIMER_PARAMETERS "Paramètres Timer" +#define D_TIMER_ARM "Armer" +#define D_TIMER_TIME "Temps" +#define D_TIMER_DAYS "Jours" +#define D_TIMER_REPEAT "Répéter" +#define D_TIMER_OUTPUT "Sortie" +#define D_TIMER_ACTION "Action" + +// xdrv_10_knx.ino +#define D_CONFIGURE_KNX "Configuration de KNX" +#define D_KNX_PARAMETERS "Paramètres KNX" +#define D_KNX_GENERAL_CONFIG "Général" +#define D_KNX_PHYSICAL_ADDRESS "Adresse individuelle" // Backbone/Line/Device -> Zone/Ligne/Participant +#define D_KNX_PHYSICAL_ADDRESS_NOTE "(Doit être unique sur le réseau KNX)" +#define D_KNX_ENABLE "Activer KNX" +#define D_KNX_GROUP_ADDRESS_TO_WRITE "Données à envoyer aux Adresses de Groupe" +#define D_ADD "Ajoûter" +#define D_DELETE "Supprimer" +#define D_REPLY "Répondre" +#define D_KNX_GROUP_ADDRESS_TO_READ "Données à recevoir des Adresses de Groupe" +#define D_LOG_KNX "KNX: " +#define D_RECEIVED_FROM "Reçu de" +#define D_KNX_COMMAND_WRITE "Écrire" +#define D_KNX_COMMAND_READ "Lire" +#define D_KNX_COMMAND_OTHER "Autre" +#define D_SENT_TO "envoyé à" +#define D_KNX_WARNING "L'Adresse de Groupe ( 0 / 0 / 0 ) est réservée et ne peut être utilisée." // xsns_03_energy.ino -#define D_ENERGY_TODAY "Energie aujourd'hui" -#define D_ENERGY_YESTERDAY "Energie hier" -#define D_ENERGY_TOTAL "Energie totale" +#define D_ENERGY_TODAY "Énergie aujourd'hui" +#define D_ENERGY_YESTERDAY "Énergie hier" +#define D_ENERGY_TOTAL "Énergie totale" // xsns_05_ds18b20.ino #define D_SENSOR_BUSY "Capteur occupé" @@ -365,14 +406,14 @@ #define D_SENSORS_FOUND "Capteur trouvé" // xsns_06_dht.ino -#define D_TIMEOUT_WAITING_FOR "Expiré attend pour" -#define D_START_SIGNAL_LOW "Signal démarrage bas" -#define D_START_SIGNAL_HIGH "Signal démarrage haut" -#define D_PULSE "pulse" -#define D_CHECKSUM_FAILURE "Echec checksum" +#define D_TIMEOUT_WAITING_FOR "Expiration du délai" +#define D_START_SIGNAL_LOW "Signal Start bas" +#define D_START_SIGNAL_HIGH "Signal Start haut" +#define D_PULSE "Impulsion" +#define D_CHECKSUM_FAILURE "Erreur checksum" // xsns_07_sht1x.ino -#define D_SENSOR_DID_NOT_ACK_COMMAND "Le capteur n'a pas ACK la commande" +#define D_SENSOR_DID_NOT_ACK_COMMAND "Le capteur n'a pas acquitté la commande" #define D_SHT1X_FOUND "SHT1X found" // xsns_18_pms5003.ino @@ -381,7 +422,7 @@ #define D_PARTICALS_BEYOND "Particules" // sonoff_template.h -#define D_SENSOR_NONE "None" +#define D_SENSOR_NONE "Aucun" #define D_SENSOR_DHT11 "DHT11" #define D_SENSOR_AM2301 "AM2301" #define D_SENSOR_SI7021 "SI7021" @@ -389,14 +430,14 @@ #define D_SENSOR_I2C_SCL "I2C SCL" #define D_SENSOR_I2C_SDA "I2C SDA" #define D_SENSOR_WS2812 "WS2812" -#define D_SENSOR_IRSEND "IRsend" -#define D_SENSOR_SWITCH "Switch" // Suffix "1" -#define D_SENSOR_BUTTON "Button" // Suffix "1" -#define D_SENSOR_RELAY "Relay" // Suffix "1i" -#define D_SENSOR_LED "LED" // Suffix "1i" -#define D_SENSOR_PWM "PWM" // Suffix "1" -#define D_SENSOR_COUNTER "Counter" // Suffix "1" -#define D_SENSOR_IRRECV "IRrecv" +#define D_SENSOR_IRSEND "ÉmetIR" +#define D_SENSOR_SWITCH "Inter." // Suffix "1" +#define D_SENSOR_BUTTON "Bouton" // Suffix "1" +#define D_SENSOR_RELAY "Relais" // Suffix "1i" +#define D_SENSOR_LED "LED" // Suffix "1i" +#define D_SENSOR_PWM "PWM" // Suffix "1" +#define D_SENSOR_COUNTER "Compteur" // Suffix "1" +#define D_SENSOR_IRRECV "RécptIR" #define D_SENSOR_MHZ_RX "MHZ Rx" #define D_SENSOR_MHZ_TX "MHZ Tx" #define D_SENSOR_PZEM_RX "PZEM Rx" @@ -405,21 +446,28 @@ #define D_SENSOR_SAIR_TX "SAir Tx" #define D_SENSOR_SPI_CS "SPI CS" #define D_SENSOR_SPI_DC "SPI DC" -#define D_SENSOR_BACKLIGHT "BkLight" +#define D_SENSOR_BACKLIGHT "RétroÉcl" #define D_SENSOR_PMS5003 "PMS5003" +#define D_SENSOR_SDS0X1 "SDS0X1" +#define D_SENSOR_SBR_RX "SerBr Rx" +#define D_SENSOR_SBR_TX "SerBr Tx" +#define D_SENSOR_SR04_TRIG "SR04 Tri" +#define D_SENSOR_SR04_ECHO "SR04 Ech" // Units #define D_UNIT_AMPERE "A" +#define D_UNIT_CENTIMETER "cm" #define D_UNIT_HOUR "h" -#define D_UNIT_KILOOHM "kOhm" +#define D_UNIT_KILOOHM "kΩ" #define D_UNIT_KILOWATTHOUR "kWh" #define D_UNIT_LUX "lx" -#define D_UNIT_MICROGRAM_PER_CUBIC_METER "ug/m3" -#define D_UNIT_MICROMETER "um" -#define D_UNIT_MICROSECOND "us" +#define D_UNIT_MICROGRAM_PER_CUBIC_METER "µg/m3" +#define D_UNIT_MICROMETER "µm" +#define D_UNIT_MICROSECOND "µs" #define D_UNIT_MILLIAMPERE "mA" #define D_UNIT_MILLISECOND "ms" #define D_UNIT_MINUTE "Min" +#define D_UNIT_PARTS_PER_BILLION "ppb" #define D_UNIT_PARTS_PER_DECILITER "ppd" #define D_UNIT_PARTS_PER_MILLION "ppm" #define D_UNIT_PRESSURE "hPa" diff --git a/sonoff/language/hu-HU.h b/sonoff/language/hu-HU.h new file mode 100644 index 000000000..51d9e146f --- /dev/null +++ b/sonoff/language/hu-HU.h @@ -0,0 +1,505 @@ +/* + hu-HU.h - localization for Hungarian in Hungary for Sonoff-Tasmota + + Copyright (C) 2018 Theo Arends + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifndef _LANGUAGE_HU_HU_H_ +#define _LANGUAGE_HU_HU_H_ + +/*************************** ATTENTION *******************************\ + * + * Due to memory constraints only UTF-8 is supported. + * To save code space keep text as short as possible. + * Time and Date provided by SDK can not be localized (yet). + * Use online command StateText to translate ON, OFF, HOLD and TOGGLE. + * Use online command Prefix to translate cmnd, stat and tele. + * + * Updated until v5.12.0e +\*********************************************************************/ + +//#define LANGUAGE_MODULE_NAME // Enable to display "Module Generic" (ie Spanish), Disable to display "Generic Module" (ie English) + +// HTML (ISO 639-1) Language Code +#define D_HTML_LANGUAGE "hu" + +// "2017-03-07T11:08:02" - ISO8601:2004 +#define D_YEAR_MONTH_SEPARATOR "." +#define D_MONTH_DAY_SEPARATOR "." +#define D_DATE_TIME_SEPARATOR " " +#define D_HOUR_MINUTE_SEPARATOR ":" +#define D_MINUTE_SECOND_SEPARATOR ":" + +#define D_DAY3LIST "VasHétKedSzeCsüPénSzo" +#define D_MONTH3LIST "JanFebMárÁprMájJúnJúlAugSzeOktNovDec" + +// Non JSON decimal separator +#define D_DECIMAL_SEPARATOR "." + +// Common +#define D_ADMIN "Admin" +#define D_AIR_QUALITY "Levegő minőség" +#define D_AP "AP" // Access Point +#define D_AS "mint" +#define D_AUTO "AUTO" +#define D_BLINK "Villogás" +#define D_BLINKOFF "Villogás Ki" +#define D_BOOT_COUNT "Bootolások száma" +#define D_BRIGHTLIGHT "Max. fényerő" +#define D_BUTTON "Gomb" +#define D_BY "tőle:" // Written by me +#define D_BYTES "Byte-ok" +#define D_CELSIUS "Celsius" +#define D_CO2 "Szén-dioxid" +#define D_CODE "kód" // Button code +#define D_COLDLIGHT "Hideg" +#define D_COMMAND "Parancs" +#define D_CONNECTED "Csatlakozva" +#define D_COUNT "Szám" +#define D_COUNTER "Számláló" +#define D_CURRENT "Áram" // As in Voltage and Current +#define D_DATA "Adat" +#define D_DARKLIGHT "Min. fényerő" +#define D_DEBUG "Debug" +#define D_DISABLED "Letiltva" +#define D_DISTANCE "Distance" +#define D_DNS_SERVER "DNS Szerver" +#define D_DONE "Kész" +#define D_DST_TIME "DST" +#define D_ECO2 "eCO2" +#define D_EMULATION "Emuláció" +#define D_ENABLED "Engedélyezve" +#define D_ERASE "Törlés" +#define D_ERROR "Hiba" +#define D_FAHRENHEIT "Fahrenheit" +#define D_FAILED "Sikertelen" +#define D_FALLBACK "Fallback" +#define D_FALLBACK_TOPIC "Fallback Téma" +#define D_FALSE "Hamis" +#define D_FILE "File" +#define D_FREE_MEMORY "Szabad Memória" +#define D_GAS "Gáz" +#define D_GATEWAY "Gateway" +#define D_GROUP "Csoport" +#define D_HOST "Host" +#define D_HOSTNAME "Hostname" +#define D_HUMIDITY "Páratartalom" +#define D_ILLUMINANCE "Megvilágítás" +#define D_IMMEDIATE "azonnali" // Button immediate +#define D_INDEX "Index" +#define D_INFO "Info" +#define D_INITIALIZED "Inicializálva" +#define D_IP_ADDRESS "IP Cím" +#define D_LIGHT "Fény" +#define D_LWT "LWT" +#define D_MODULE "Modul" +#define D_MQTT "MQTT" +#define D_MULTI_PRESS "több lenyomás" +#define D_NOISE "Zaj" +#define D_NONE "nincs" +#define D_OFF "Ki" +#define D_OFFLINE "Offline" +#define D_OK "Ok" +#define D_ON "Be" +#define D_ONLINE "Online" +#define D_PASSWORD "Jelszó" +#define D_PORT "Port" +#define D_POWER_FACTOR "Teljesítmény tényező" +#define D_POWERUSAGE "Energiafelhasználás" +#define D_PRESSURE "Nyomás" +#define D_PRESSUREATSEALEVEL "Tengerszinti nyomás" +#define D_PROGRAM_FLASH_SIZE "Program Flash Méret" +#define D_PROGRAM_SIZE "Program Méret" +#define D_PROJECT "Projekt" +#define D_RECEIVED "Érkezett" +#define D_RESTART "Újraindítás" +#define D_RESTARTING "Újraindítás" +#define D_RESTART_REASON "Újraindítás oka:" +#define D_RESTORE "Visszaállítás" +#define D_RETAINED "mentve" +#define D_RULE "Rule" +#define D_SAVE "Mentés" +#define D_SENSOR "Szenzor" +#define D_SSID "SSId" +#define D_START "" +#define D_STD_TIME "STD" +#define D_STOP "Leállítás" +#define D_SUBNET_MASK "Subnet Mask" +#define D_SUBSCRIBE_TO "Feliratkozás a" +#define D_SUCCESSFUL "Sikeres" +#define D_SUNRISE "Sunrise" +#define D_SUNSET "Sunset" +#define D_TEMPERATURE "Hőmérséklet" +#define D_TO "-nak" +#define D_TOGGLE "Toggle" +#define D_TOPIC "Téma" +#define D_TRANSMIT "Továbbít" +#define D_TRUE "Igaz" +#define D_TVOC "TVOC" +#define D_UPGRADE "frissítés" +#define D_UPLOAD "Feltöltés" +#define D_UPTIME "Üzemidő" +#define D_USER "Felhasználó" +#define D_UTC_TIME "UTC" +#define D_UV_LEVEL "UV Szint" +#define D_VERSION "Verzió" +#define D_VOLTAGE "Feszültség" +#define D_WARMLIGHT "Meleg" +#define D_WEB_SERVER "Web Szerver" + +// sonoff.ino +#define D_WARNING_MINIMAL_VERSION "VIGYÁZZ Ez a verzió nem támogat tartós beállításokat" +#define D_LEVEL_10 "szint 1-0" +#define D_LEVEL_01 "szint 0-1" +#define D_SERIAL_LOGGING_DISABLED "Serial logolás kikapcsolva" +#define D_SYSLOG_LOGGING_REENABLED "Syslog logolás újra-engedélyezve" + +#define D_SET_BAUDRATE_TO "Baudrate beállítása" +#define D_RECEIVED_TOPIC "Érkezett Téma" +#define D_DATA_SIZE "Adat Méret" +#define D_ANALOG_INPUT "Analóg" + +// support.ino +#define D_OSWATCH "osWatch" +#define D_BLOCKED_LOOP "Blocked Loop" +#define D_WPS_FAILED_WITH_STATUS "WPSconfig SIKERTELEN státusz:" +#define D_ACTIVE_FOR_3_MINUTES "aktválás 3 percre" +#define D_FAILED_TO_START "sikertelen indítás" +#define D_PATCH_ISSUE_2186 "Patch issue 2186" +#define D_CONNECTING_TO_AP "Csatlakozás az (AP): " +#define D_IN_MODE "be mód" +#define D_CONNECT_FAILED_NO_IP_ADDRESS "Sikertelen csatlakozás, nincs kiosztott IP cím" +#define D_CONNECT_FAILED_AP_NOT_REACHED "Sikertelen csatlakozás, AP nem elérhető" +#define D_CONNECT_FAILED_WRONG_PASSWORD "Sikertelen csatlakozás, hibás AP jelszó" +#define D_CONNECT_FAILED_AP_TIMEOUT "Sikertelen csatlakozás AP időtúllépés miatt" +#define D_ATTEMPTING_CONNECTION "Csatlakozás..." +#define D_CHECKING_CONNECTION "Kapcsolat ellenőrzése..." +#define D_QUERY_DONE "Lekérés kész. MQTT szolgáltatás aktív" +#define D_MQTT_SERVICE_FOUND "élő MQTT szolgáltatás a" +#define D_FOUND_AT "a" +#define D_SYSLOG_HOST_NOT_FOUND "Syslog Host nem található" + +// settings.ino +#define D_SAVED_TO_FLASH_AT "Flash-re mentve a" +#define D_LOADED_FROM_FLASH_AT "Flash-ről betöltve a" +#define D_USE_DEFAULTS "Alapértelmezett beáll. használata" +#define D_ERASED_SECTOR "Szektor törlése" + +// webserver.ino +#define D_MINIMAL_FIRMWARE_PLEASE_UPGRADE "MINIMAL firmware - frissítsd!" +#define D_WEBSERVER_ACTIVE_ON "Web szerver aktív a" +#define D_WITH_IP_ADDRESS "IP címe:" +#define D_WEBSERVER_STOPPED "Webs zerver leállítva" +#define D_FILE_NOT_FOUND "File Nem Található" +#define D_REDIRECTED "Átírányítás captive portálra" +#define D_WIFIMANAGER_SET_ACCESSPOINT_AND_STATION "Wifimanager AccessPoint(AP) és Station(ST) beállítása" +#define D_WIFIMANAGER_SET_ACCESSPOINT "Wifimanager AccessPoint(AP) beállítása" +#define D_TRYING_TO_CONNECT "Csatlakozás a hálózatra..." + +#define D_RESTART_IN "Újraindítás..." +#define D_SECONDS "másodperc" +#define D_DEVICE_WILL_RESTART "Az eszköz hamarosan újraindul" +#define D_BUTTON_TOGGLE "Toggle" +#define D_CONFIGURATION "Konfigurációk" +#define D_INFORMATION "Információ" +#define D_FIRMWARE_UPGRADE "Firmware Frissítés" +#define D_CONSOLE "Konzol" +#define D_CONFIRM_RESTART "Újraindítás megerősítése" + +#define D_CONFIGURE_MODULE "Eszköz konfiguráció" +#define D_CONFIGURE_WIFI "WiFi konfiguráció" +#define D_CONFIGURE_MQTT "MQTT konfiguráció" +#define D_CONFIGURE_DOMOTICZ "Domoticz konfiguráció" +#define D_CONFIGURE_LOGGING "Logolás konfiguráció" +#define D_CONFIGURE_OTHER "Egyéb konfiguráció" +#define D_CONFIRM_RESET_CONFIGURATION "Konfig resetelés megerősítve?" +#define D_RESET_CONFIGURATION "Konfiguráció reset" +#define D_BACKUP_CONFIGURATION "Konfiguráció backup" +#define D_RESTORE_CONFIGURATION "Konfiguráció visszaállítás" +#define D_MAIN_MENU "Menü" + +#define D_MODULE_PARAMETERS "Modul paraméterek" +#define D_MODULE_TYPE "Modul típus" +#define D_GPIO "GPIO" +#define D_SERIAL_IN "Serial In" +#define D_SERIAL_OUT "Serial Out" + +#define D_WIFI_PARAMETERS "Wifi paraméterek" +#define D_SCAN_FOR_WIFI_NETWORKS "Wifi hálózat keresése" +#define D_SCAN_DONE "Keresés kész" +#define D_NO_NETWORKS_FOUND "Nincs elérhető hálózat" +#define D_REFRESH_TO_SCAN_AGAIN "Frissíts az újra kereséshez" +#define D_DUPLICATE_ACCESSPOINT "Duplicate AccessPoint" +#define D_SKIPPING_LOW_QUALITY "Kihagyás, alacsony jelminőség" +#define D_RSSI "RSSI" +#define D_WEP "WEP" +#define D_WPA_PSK "WPA PSK" +#define D_WPA2_PSK "WPA2 PSK" +#define D_AP1_SSID "AP1 SSID" +#define D_AP1_PASSWORD "AP1 Jelszó" +#define D_AP2_SSID "AP2 SSID" +#define D_AP2_PASSWORD "AP2 Jelszó" + +#define D_MQTT_PARAMETERS "MQTT paraméterek" +#define D_CLIENT "Kliens" +#define D_FULL_TOPIC "Teljes téma" + +#define D_LOGGING_PARAMETERS "Logolás paraméterek" +#define D_SERIAL_LOG_LEVEL "Serial logolás szint" +#define D_WEB_LOG_LEVEL "Web logolás szint" +#define D_SYS_LOG_LEVEL "Syslog szint" +#define D_MORE_DEBUG "Részletes debug" +#define D_SYSLOG_HOST "Syslog host" +#define D_SYSLOG_PORT "Syslog port" +#define D_TELEMETRY_PERIOD "Telemetria (sec)" + +#define D_OTHER_PARAMETERS "Egyéb paraméterek" +#define D_WEB_ADMIN_PASSWORD "Web Admin Jelszó" +#define D_MQTT_ENABLE "MQTT engedélyezés" +#define D_FRIENDLY_NAME "Név" +#define D_BELKIN_WEMO "Belkin WeMo" +#define D_HUE_BRIDGE "Hue Bridge" +#define D_SINGLE_DEVICE "single device" +#define D_MULTI_DEVICE "multi device" + +#define D_SAVE_CONFIGURATION "Konfiguráció mentése" +#define D_CONFIGURATION_SAVED "Konfiguráció elmentve" +#define D_CONFIGURATION_RESET "Konfiguráció visszaállítása" + +#define D_PROGRAM_VERSION "Program Verzió" +#define D_BUILD_DATE_AND_TIME "Build Dátum & Idő" +#define D_CORE_AND_SDK_VERSION "Core/SDK Verzió" +#define D_FLASH_WRITE_COUNT "Flashelések száma" +#define D_MAC_ADDRESS "MAC Cím" +#define D_MQTT_HOST "MQTT Host" +#define D_MQTT_PORT "MQTT Port" +#define D_MQTT_CLIENT "MQTT Cliens" +#define D_MQTT_USER "MQTT Felhasználó" +#define D_MQTT_TOPIC "MQTT Téma" +#define D_MQTT_GROUP_TOPIC "MQTT Csoport Téma" +#define D_MQTT_FULL_TOPIC "MQTT Teljes téma" +#define D_MDNS_DISCOVERY "mDNS Láthatóság" +#define D_MDNS_ADVERTISE "mDNS Hírdetés" +#define D_ESP_CHIP_ID "ESP Chip Id" +#define D_FLASH_CHIP_ID "Flash Chip Id" +#define D_FLASH_CHIP_SIZE "Flash Méret" +#define D_FREE_PROGRAM_SPACE "Szabad Program Hely" + +#define D_UPGRADE_BY_WEBSERVER "Frissítés web szerverrel" +#define D_OTA_URL "OTA Url" +#define D_START_UPGRADE "Frissítés" +#define D_UPGRADE_BY_FILE_UPLOAD "Frissítés file feltöltéssel" +#define D_UPLOAD_STARTED "Feltöltés elindítva" +#define D_UPGRADE_STARTED "Frissítés elindítva" +#define D_UPLOAD_DONE "Feltöltés kész" +#define D_UPLOAD_ERR_1 "Nincs file kijelölve" +#define D_UPLOAD_ERR_2 "Nincs elég memória" +#define D_UPLOAD_ERR_3 "Magic byte is not 0xE9" +#define D_UPLOAD_ERR_4 "Program flash méret nagyobb a valós flash méretnél" +#define D_UPLOAD_ERR_5 "Feltöltés buffer hiba" +#define D_UPLOAD_ERR_6 "Feltöltés sikertelen. Endegélyezz 3-mas logolást" +#define D_UPLOAD_ERR_7 "Feltöltés megszakítva" +#define D_UPLOAD_ERR_8 "Érvénytelen file" +#define D_UPLOAD_ERR_9 "File túl nagy" +#define D_UPLOAD_ERROR_CODE "Feltöltés hiba kód" + +#define D_ENTER_COMMAND "Parancsolj" +#define D_ENABLE_WEBLOG_FOR_RESPONSE "Engedélyezz 2-es weblogolást több információért" +#define D_NEED_USER_AND_PASSWORD "Kell felhasználó=&jelszó=" + +// xdrv_00_mqtt.ino +#define D_FINGERPRINT "TLS fingerprint hitelesítése..." +#define D_TLS_CONNECT_FAILED_TO "TLS Csatlakozás sikertelen a" +#define D_RETRY_IN "Újrapróbálás" +#define D_VERIFIED "Hitelesítve Fingerprint" +#define D_INSECURE "Nem biztonságos kapcsolat érvénytelen Fingerprint miatt" +#define D_CONNECT_FAILED_TO "Sikertelen csatlakozás a" + +// xdrv_wemohue.ino +#define D_MULTICAST_DISABLED "Multicast kikapcsolva" +#define D_MULTICAST_REJOINED "Multicast (újra)csatlakozás" +#define D_MULTICAST_JOIN_FAILED "Multicast csatlakozás sikertelen" +#define D_FAILED_TO_SEND_RESPONSE "Nem sikerült választ küldeni" + +#define D_WEMO "WeMo" +#define D_WEMO_BASIC_EVENT "WeMo basic event" +#define D_WEMO_EVENT_SERVICE "WeMo event service" +#define D_WEMO_META_SERVICE "WeMo meta service" +#define D_WEMO_SETUP "WeMo beállítás" +#define D_RESPONSE_SENT "Válasz elküldve" + +#define D_HUE "Hue" +#define D_HUE_BRIDGE_SETUP "Hue beállítás" +#define D_HUE_API_NOT_IMPLEMENTED "Hue API nincs implementálva" +#define D_HUE_API "Hue API" +#define D_HUE_POST_ARGS "Hue POST args" +#define D_3_RESPONSE_PACKETS_SENT "3 válaszcsomagok elküldve" + +// xdrv_05_domoticz.ino +#define D_DOMOTICZ_PARAMETERS "Domoticz paraméterek" +#define D_DOMOTICZ_IDX "Idx" +#define D_DOMOTICZ_KEY_IDX "Key idx" +#define D_DOMOTICZ_SWITCH_IDX "Kapcsoló idx" +#define D_DOMOTICZ_SENSOR_IDX "Szenzor idx" + #define D_DOMOTICZ_TEMP "Temp" + #define D_DOMOTICZ_TEMP_HUM "Hőm,Párat" + #define D_DOMOTICZ_TEMP_HUM_BARO "Hőm,Párat,Légny" + #define D_DOMOTICZ_POWER_ENERGY "Teljesítmény,Energia" + #define D_DOMOTICZ_ILLUMINANCE "Fényerő" + #define D_DOMOTICZ_COUNT "Szám/PM1" + #define D_DOMOTICZ_VOLTAGE "Feszültség/PM2.5" + #define D_DOMOTICZ_CURRENT "Áram/PM10" + #define D_DOMOTICZ_AIRQUALITY "Légminőség" +#define D_DOMOTICZ_UPDATE_TIMER "Update időzítő" + +// xdrv_09_timers.ino +#define D_CONFIGURE_TIMER "Configure Timer" +#define D_TIMER_PARAMETERS "Timer parameters" +#define D_TIMER_ARM "Arm" +#define D_TIMER_TIME "Time" +#define D_TIMER_DAYS "Days" +#define D_TIMER_REPEAT "Repeat" +#define D_TIMER_OUTPUT "Output" +#define D_TIMER_ACTION "Action" + +// xdrv_10_knx.ino +#define D_CONFIGURE_KNX "Configure KNX" +#define D_KNX_PARAMETERS "KNX Parameters" +#define D_KNX_GENERAL_CONFIG "General" +#define D_KNX_PHYSICAL_ADDRESS "Physical Address" +#define D_KNX_PHYSICAL_ADDRESS_NOTE "( Must be unique on the KNX network )" +#define D_KNX_ENABLE "Enable KNX" +#define D_KNX_GROUP_ADDRESS_TO_WRITE "Data to Send to Group Addresses" +#define D_ADD "Add" +#define D_DELETE "Delete" +#define D_REPLY "Reply" +#define D_KNX_GROUP_ADDRESS_TO_READ "Group Addresses to Receive Data from" +#define D_LOG_KNX "KNX: " +#define D_RECEIVED_FROM "Received from" +#define D_KNX_COMMAND_WRITE "Write" +#define D_KNX_COMMAND_READ "Read" +#define D_KNX_COMMAND_OTHER "Other" +#define D_SENT_TO "sent to" +#define D_KNX_WARNING "The group address ( 0 / 0 / 0 ) is reserved and can not be used." + +// xdrv_03_energy.ino +#define D_ENERGY_TODAY "Mai Energia" +#define D_ENERGY_YESTERDAY "Tegnapi Energia" +#define D_ENERGY_TOTAL "Összes Energia" + +// xsns_05_ds18b20.ino +#define D_SENSOR_BUSY "Szenzor elfoglalt" +#define D_SENSOR_CRC_ERROR "Szenzor CRC hiba" +#define D_SENSORS_FOUND "Szenzorok megtalálva" + +// xsns_06_dht.ino +#define D_TIMEOUT_WAITING_FOR "Timeout waiting for" +#define D_START_SIGNAL_LOW "start signal low" +#define D_START_SIGNAL_HIGH "start signal high" +#define D_PULSE "pulse" +#define D_CHECKSUM_FAILURE "Checksum failure" + +// xsns_07_sht1x.ino +#define D_SENSOR_DID_NOT_ACK_COMMAND "Szenzor nem ismerte el(ACK) a parancsot" +#define D_SHT1X_FOUND "SHT1X found" + +// xsns_18_pms5003.ino +#define D_STANDARD_CONCENTRATION "CF-1 PM" // Standard Particle CF-1 Particle Matter +#define D_ENVIRONMENTAL_CONCENTRATION "PM" // Environmetal Particle Matter +#define D_PARTICALS_BEYOND "Részecskék" + +// sonoff_template.h +#define D_SENSOR_NONE "Nincs" +#define D_SENSOR_DHT11 "DHT11" +#define D_SENSOR_AM2301 "AM2301" +#define D_SENSOR_SI7021 "SI7021" +#define D_SENSOR_DS18X20 "DS18x20" +#define D_SENSOR_I2C_SCL "I2C SCL" +#define D_SENSOR_I2C_SDA "I2C SDA" +#define D_SENSOR_WS2812 "WS2812" +#define D_SENSOR_IRSEND "IRadó" +#define D_SENSOR_SWITCH "Kapcsoló" // Suffix "1" +#define D_SENSOR_BUTTON "Gomb" // Suffix "1" +#define D_SENSOR_RELAY "Relé" // Suffix "1i" +#define D_SENSOR_LED "Led" // Suffix "1i" +#define D_SENSOR_PWM "PWM" // Suffix "1" +#define D_SENSOR_COUNTER "Számláló" // Suffix "1" +#define D_SENSOR_IRRECV "IRvevő" +#define D_SENSOR_MHZ_RX "MHZ Rx" +#define D_SENSOR_MHZ_TX "MHZ Tx" +#define D_SENSOR_PZEM_RX "PZEM Rx" +#define D_SENSOR_PZEM_TX "PZEM Tx" +#define D_SENSOR_SAIR_RX "SAir Rx" +#define D_SENSOR_SAIR_TX "SAir Tx" +#define D_SENSOR_SPI_CS "SPI CS" +#define D_SENSOR_SPI_DC "SPI DC" +#define D_SENSOR_BACKLIGHT "Háttérvil" +#define D_SENSOR_PMS5003 "PMS5003" +#define D_SENSOR_SDS0X1 "SDS0X1" +#define D_SENSOR_SBR_RX "SerBr Rx" +#define D_SENSOR_SBR_TX "SerBr Tx" +#define D_SENSOR_SR04_TRIG "SR04 Tri" +#define D_SENSOR_SR04_ECHO "SR04 Ech" + +// Units +#define D_UNIT_AMPERE "A" +#define D_UNIT_CENTIMETER "cm" +#define D_UNIT_HOUR "ó" +#define D_UNIT_KILOOHM "kOhm" +#define D_UNIT_KILOWATTHOUR "kWh" +#define D_UNIT_LUX "lx" +#define D_UNIT_MICROGRAM_PER_CUBIC_METER "ug/m3" +#define D_UNIT_MICROMETER "um" +#define D_UNIT_MICROSECOND "µs" +#define D_UNIT_MILLIAMPERE "mA" +#define D_UNIT_MILLISECOND "ms" +#define D_UNIT_MINUTE "p" +#define D_UNIT_PARTS_PER_BILLION "ppb" +#define D_UNIT_PARTS_PER_DECILITER "ppd" +#define D_UNIT_PARTS_PER_MILLION "ppm" +#define D_UNIT_PRESSURE "hPa" +#define D_UNIT_SECOND "m" +#define D_UNIT_SECTORS "szektorok" +#define D_UNIT_VOLT "V" +#define D_UNIT_WATT "W" +#define D_UNIT_WATTHOUR "Wh" + +// Log message prefix +#define D_LOG_APPLICATION "APP: " // Application +#define D_LOG_BRIDGE "BRG: " // Bridge +#define D_LOG_CONFIG "CFG: " // Settings +#define D_LOG_COMMAND "CMD: " // Command +#define D_LOG_DEBUG "DBG: " // Debug +#define D_LOG_DHT "DHT: " // DHT sensor +#define D_LOG_DOMOTICZ "DOM: " // Domoticz +#define D_LOG_DSB "DSB: " // DS18xB20 sensor +#define D_LOG_HTTP "HTP: " // HTTP webserver +#define D_LOG_I2C "I2C: " // I2C +#define D_LOG_IRR "IRR: " // Infra Red Received +#define D_LOG_LOG "LOG: " // Logging +#define D_LOG_MODULE "MOD: " // Module +#define D_LOG_MDNS "DNS: " // mDNS +#define D_LOG_MQTT "MQT: " // MQTT +#define D_LOG_OTHER "OTH: " // Other +#define D_LOG_RESULT "RSL: " // Result +#define D_LOG_RFR "RFR: " // RF Received +#define D_LOG_SERIAL "SER: " // Serial +#define D_LOG_SHT1 "SHT: " // SHT1x sensor +#define D_LOG_UPLOAD "UPL: " // Upload +#define D_LOG_UPNP "UPP: " // UPnP +#define D_LOG_WIFI "WIF: " // Wifi + +#endif // _LANGUAGE_HU_HU_H_ diff --git a/sonoff/language/it-IT.h b/sonoff/language/it-IT.h index 6ab442ca1..7bd6b65b5 100644 --- a/sonoff/language/it-IT.h +++ b/sonoff/language/it-IT.h @@ -28,10 +28,14 @@ * Use online command StateText to translate ON, OFF, HOLD and TOGGLE. * Use online command Prefix to translate cmnd, stat and tele. * + * Updated until v5.12.0 \*********************************************************************/ #define LANGUAGE_MODULE_NAME // Enable to display "Module Generic" (ie Spanish), Disable to display "Generic Module" (ie English) +// HTML (ISO 639-1) Language Code +#define D_HTML_LANGUAGE "it" + // "2017-03-07T11:08:02" - ISO8601:2004 #define D_YEAR_MONTH_SEPARATOR "-" #define D_MONTH_DAY_SEPARATOR "-" @@ -71,9 +75,11 @@ #define D_DARKLIGHT "Scuro" #define D_DEBUG "Debug" #define D_DISABLED "Disabilitato" +#define D_DISTANCE "Distance" #define D_DNS_SERVER "DNS Server" #define D_DONE "Fatto" #define D_DST_TIME "DST" +#define D_ECO2 "eCO2" #define D_EMULATION "Emulazione" #define D_ENABLED "Abilitato" #define D_ERASE "Cancellare" @@ -124,6 +130,7 @@ #define D_RESTART_REASON "Causa Riavvio" #define D_RESTORE "ripristino" #define D_RETAINED "salvato" +#define D_RULE "Rule" #define D_SAVE "Salva" #define D_SENSOR "Sensore" #define D_SSID "SSId" @@ -133,12 +140,15 @@ #define D_SUBNET_MASK "Maschera sottorete" #define D_SUBSCRIBE_TO "Sottoscrivi a" #define D_SUCCESSFUL "Riuscito" +#define D_SUNRISE "Sunrise" +#define D_SUNSET "Sunset" #define D_TEMPERATURE "Temperatura" #define D_TO "a" #define D_TOGGLE "Toggle" #define D_TOPIC "Topic" #define D_TRANSMIT "Trasmesso" #define D_TRUE "True" +#define D_TVOC "TVOC" #define D_UPGRADE "aggiornamento" #define D_UPLOAD "Invio" #define D_UPTIME "Uptime" @@ -162,13 +172,6 @@ #define D_DATA_SIZE "Dimensione Dati" #define D_ANALOG_INPUT "Ingresso Analogico" -#define D_FINGERPRINT "Verifica TLS fingerprint..." -#define D_TLS_CONNECT_FAILED_TO "Connessione TLS fallita a" -#define D_RETRY_IN "Nuovo tentativo in" -#define D_VERIFIED "Verificato" -#define D_INSECURE "Connessione insicura a causa di Fingerprint non valido" -#define D_CONNECT_FAILED_TO "Connessione Fallita a" - // support.ino #define D_OSWATCH "osWatch" #define D_BLOCKED_LOOP "Ciclo Bloccato" @@ -317,6 +320,14 @@ #define D_ENABLE_WEBLOG_FOR_RESPONSE "Abilitare weblog 2 se e' attesa una risposta" #define D_NEED_USER_AND_PASSWORD "Richiesto user=&password=" +// xdrv_00_mqtt.ino +#define D_FINGERPRINT "Verifica TLS fingerprint..." +#define D_TLS_CONNECT_FAILED_TO "Connessione TLS fallita a" +#define D_RETRY_IN "Nuovo tentativo in" +#define D_VERIFIED "Verificato Fingerprint" +#define D_INSECURE "Connessione insicura a causa di Fingerprint non valido" +#define D_CONNECT_FAILED_TO "Connessione Fallita a" + // xdrv_wemohue.ino #define D_MULTICAST_DISABLED "Multicast disabilitato" #define D_MULTICAST_REJOINED "Multicast (ri)associato" @@ -348,12 +359,42 @@ #define D_DOMOTICZ_TEMP_HUM_BARO "Temp,Hum,Baro" #define D_DOMOTICZ_POWER_ENERGY "Power,Energy" #define D_DOMOTICZ_ILLUMINANCE "Illuminance" - #define D_DOMOTICZ_COUNT "Count" - #define D_DOMOTICZ_VOLTAGE "Voltage" - #define D_DOMOTICZ_CURRENT "Current" + #define D_DOMOTICZ_COUNT "Count/PM1" + #define D_DOMOTICZ_VOLTAGE "Voltage/PM2.5" + #define D_DOMOTICZ_CURRENT "Current/PM10" #define D_DOMOTICZ_AIRQUALITY "AirQuality" #define D_DOMOTICZ_UPDATE_TIMER "Intervallo di aggiornamento" +// xdrv_09_timers.ino +#define D_CONFIGURE_TIMER "Configure Timer" +#define D_TIMER_PARAMETERS "Timer parameters" +#define D_TIMER_ARM "Arm" +#define D_TIMER_TIME "Time" +#define D_TIMER_DAYS "Days" +#define D_TIMER_REPEAT "Repeat" +#define D_TIMER_OUTPUT "Output" +#define D_TIMER_ACTION "Action" + +// xdrv_10_knx.ino +#define D_CONFIGURE_KNX "Configure KNX" +#define D_KNX_PARAMETERS "KNX Parameters" +#define D_KNX_GENERAL_CONFIG "General" +#define D_KNX_PHYSICAL_ADDRESS "Physical Address" +#define D_KNX_PHYSICAL_ADDRESS_NOTE "( Must be unique on the KNX network )" +#define D_KNX_ENABLE "Enable KNX" +#define D_KNX_GROUP_ADDRESS_TO_WRITE "Data to Send to Group Addresses" +#define D_ADD "Add" +#define D_DELETE "Delete" +#define D_REPLY "Reply" +#define D_KNX_GROUP_ADDRESS_TO_READ "Group Addresses to Receive Data from" +#define D_LOG_KNX "KNX: " +#define D_RECEIVED_FROM "Received from" +#define D_KNX_COMMAND_WRITE "Write" +#define D_KNX_COMMAND_READ "Read" +#define D_KNX_COMMAND_OTHER "Other" +#define D_SENT_TO "sent to" +#define D_KNX_WARNING "The group address ( 0 / 0 / 0 ) is reserved and can not be used." + // xdrv_03_energy.ino #define D_ENERGY_TODAY "Energia Oggi" #define D_ENERGY_YESTERDAY "Energia Ieri" @@ -407,9 +448,15 @@ #define D_SENSOR_SPI_DC "SPI DC" #define D_SENSOR_BACKLIGHT "BkLight" #define D_SENSOR_PMS5003 "PMS5003" +#define D_SENSOR_SDS0X1 "SDS0X1" +#define D_SENSOR_SBR_RX "SerBr Rx" +#define D_SENSOR_SBR_TX "SerBr Tx" +#define D_SENSOR_SR04_TRIG "SR04 Tri" +#define D_SENSOR_SR04_ECHO "SR04 Ech" // Units #define D_UNIT_AMPERE "A" +#define D_UNIT_CENTIMETER "cm" #define D_UNIT_HOUR "Hr" #define D_UNIT_KILOOHM "kOhm" #define D_UNIT_KILOWATTHOUR "kWh" @@ -420,6 +467,7 @@ #define D_UNIT_MILLIAMPERE "mA" #define D_UNIT_MILLISECOND "ms" #define D_UNIT_MINUTE "Min" +#define D_UNIT_PARTS_PER_BILLION "ppb" #define D_UNIT_PARTS_PER_DECILITER "ppd" #define D_UNIT_PARTS_PER_MILLION "ppm" #define D_UNIT_PRESSURE "hPa" diff --git a/sonoff/language/nl-NL.h b/sonoff/language/nl-NL.h index 6f9d39f72..5d3bcb959 100644 --- a/sonoff/language/nl-NL.h +++ b/sonoff/language/nl-NL.h @@ -28,10 +28,14 @@ * Use online command StateText to translate ON, OFF, HOLD and TOGGLE. * Use online command Prefix to translate cmnd, stat and tele. * + * Updated until v5.12.0l \*********************************************************************/ //#define LANGUAGE_MODULE_NAME // Enable to display "Module Generic" (ie Spanish), Disable to display "Generic Module" (ie English) +// HTML (ISO 639-1) Language Code +#define D_HTML_LANGUAGE "nl" + // "2017-03-07T11:08:02" - ISO8601:2004 #define D_YEAR_MONTH_SEPARATOR "-" #define D_MONTH_DAY_SEPARATOR "-" @@ -71,9 +75,11 @@ #define D_DARKLIGHT "Donker" #define D_DEBUG "Debug" #define D_DISABLED "Uitgeschakeld" +#define D_DISTANCE "Afstand" #define D_DNS_SERVER "DNS Server" #define D_DONE "Klaar" #define D_DST_TIME "ZT" +#define D_ECO2 "eCO2" #define D_EMULATION "Emulatie" #define D_ENABLED "Geactiveerd" #define D_ERASE "Wissen" @@ -107,7 +113,7 @@ #define D_OFF "Uit" #define D_OFFLINE "Offline" #define D_OK "Ok" -#define D_ON "Ann" +#define D_ON "Aan" #define D_ONLINE "Online" #define D_PASSWORD "Wachtwoord" #define D_PORT "Poort" @@ -124,6 +130,7 @@ #define D_RESTART_REASON "Reden herstart" #define D_RESTORE "herstellen" #define D_RETAINED "retained" +#define D_RULE "Regel" #define D_SAVE "Opslaan" #define D_SENSOR "Sensor" #define D_SSID "SSId" @@ -133,12 +140,15 @@ #define D_SUBNET_MASK "Subnet Masker" #define D_SUBSCRIBE_TO "Abonneer op" #define D_SUCCESSFUL "Gelukt" +#define D_SUNRISE "Zonsopgang" +#define D_SUNSET "Zonsondergang" #define D_TEMPERATURE "Temperatuur" #define D_TO "naar" #define D_TOGGLE "Toggle" // Wissel, Tuimel #define D_TOPIC "Topic" // Onderwerp #define D_TRANSMIT "Verzend" #define D_TRUE "Waar" +#define D_TVOC "TVOC" #define D_UPGRADE "opwaarderen" #define D_UPLOAD "Verzenden" #define D_UPTIME "Bedrijfstijd" @@ -162,13 +172,6 @@ #define D_DATA_SIZE "Data lengte" #define D_ANALOG_INPUT "Analoog" -#define D_FINGERPRINT "Controleer TLS vingerafdruk..." -#define D_TLS_CONNECT_FAILED_TO "TLS Verbinding mislukt naar" -#define D_RETRY_IN "Opnieuw proberen over" -#define D_VERIFIED "Gecontroleerd" -#define D_INSECURE "Door ongeldige vingerafdruk een onveilige verbinding" -#define D_CONNECT_FAILED_TO "Verbinding mislukt naar" - // support.ino #define D_OSWATCH "osWatch" #define D_BLOCKED_LOOP "Blocked Loop" @@ -317,6 +320,14 @@ #define D_ENABLE_WEBLOG_FOR_RESPONSE "Schakel weblog 2 in indien antwoord verwacht" #define D_NEED_USER_AND_PASSWORD "Benodig user=&password=" +// xdrv_00_mqtt.ino +#define D_FINGERPRINT "Controleer TLS vingerafdruk..." +#define D_TLS_CONNECT_FAILED_TO "TLS Verbinding mislukt naar" +#define D_RETRY_IN "Opnieuw proberen over" +#define D_VERIFIED "Gecontroleerd met vingerafdruk" +#define D_INSECURE "Door ongeldige vingerafdruk een onveilige verbinding" +#define D_CONNECT_FAILED_TO "Verbinding mislukt naar" + // xdrv_wemohue.ino #define D_MULTICAST_DISABLED "Multicast uitgeschakeld" #define D_MULTICAST_REJOINED "Multicast verbonden" @@ -348,12 +359,42 @@ #define D_DOMOTICZ_TEMP_HUM_BARO "Temp,Hum,Baro" #define D_DOMOTICZ_POWER_ENERGY "Power,Energy" #define D_DOMOTICZ_ILLUMINANCE "Illuminance" - #define D_DOMOTICZ_COUNT "Count" - #define D_DOMOTICZ_VOLTAGE "Spanning" - #define D_DOMOTICZ_CURRENT "Stroom" + #define D_DOMOTICZ_COUNT "Count/PM1" + #define D_DOMOTICZ_VOLTAGE "Spanning/PM2,5" + #define D_DOMOTICZ_CURRENT "Stroom/PM10" #define D_DOMOTICZ_AIRQUALITY "AirQuality" #define D_DOMOTICZ_UPDATE_TIMER "Bijwerk timer" +// xdrv_09_timers.ino +#define D_CONFIGURE_TIMER "Configureer Tijdschakelaar" +#define D_TIMER_PARAMETERS "Tijdschakelaar parameters" +#define D_TIMER_ARM "Actief" +#define D_TIMER_TIME "Tijd" +#define D_TIMER_DAYS "Dagen" +#define D_TIMER_REPEAT "Herhaal" +#define D_TIMER_OUTPUT "Uitgang" +#define D_TIMER_ACTION "Actie" + +// xdrv_10_knx.ino +#define D_CONFIGURE_KNX "Configure KNX" +#define D_KNX_PARAMETERS "KNX Parameters" +#define D_KNX_GENERAL_CONFIG "General" +#define D_KNX_PHYSICAL_ADDRESS "Physical Address" +#define D_KNX_PHYSICAL_ADDRESS_NOTE "( Must be unique on the KNX network )" +#define D_KNX_ENABLE "Enable KNX" +#define D_KNX_GROUP_ADDRESS_TO_WRITE "Data to Send to Group Addresses" +#define D_ADD "Add" +#define D_DELETE "Delete" +#define D_REPLY "Reply" +#define D_KNX_GROUP_ADDRESS_TO_READ "Group Addresses to Receive Data from" +#define D_LOG_KNX "KNX: " +#define D_RECEIVED_FROM "Received from" +#define D_KNX_COMMAND_WRITE "Write" +#define D_KNX_COMMAND_READ "Read" +#define D_KNX_COMMAND_OTHER "Other" +#define D_SENT_TO "sent to" +#define D_KNX_WARNING "The group address ( 0 / 0 / 0 ) is reserved and can not be used." + // xdrv_03_energy.ino #define D_ENERGY_TODAY "Verbruik vandaag" #define D_ENERGY_YESTERDAY "Verbruik gisteren" @@ -407,9 +448,15 @@ #define D_SENSOR_SPI_DC "SPI DC" #define D_SENSOR_BACKLIGHT "BkLight" #define D_SENSOR_PMS5003 "PMS5003" +#define D_SENSOR_SDS0X1 "SDS0X1" +#define D_SENSOR_SBR_RX "SerBr Rx" +#define D_SENSOR_SBR_TX "SerBr Tx" +#define D_SENSOR_SR04_TRIG "SR04 Tri" +#define D_SENSOR_SR04_ECHO "SR04 Ech" // Units #define D_UNIT_AMPERE "A" +#define D_UNIT_CENTIMETER "cm" #define D_UNIT_HOUR "h" #define D_UNIT_KILOOHM "kOhm" #define D_UNIT_KILOWATTHOUR "kWh" @@ -420,6 +467,7 @@ #define D_UNIT_MILLIAMPERE "mA" #define D_UNIT_MILLISECOND "ms" #define D_UNIT_MINUTE "Min" +#define D_UNIT_PARTS_PER_BILLION "ppb" #define D_UNIT_PARTS_PER_DECILITER "ppd" #define D_UNIT_PARTS_PER_MILLION "ppm" #define D_UNIT_PRESSURE "hPa" diff --git a/sonoff/language/pl-PL.h b/sonoff/language/pl-PL.h index 97c0bf51f..19a27ebeb 100644 --- a/sonoff/language/pl-PL.h +++ b/sonoff/language/pl-PL.h @@ -1,7 +1,7 @@ /* - pl-PL.h - localization for Polish without fonetick - Poland for Sonoff-Tasmota + pl-PL-d.h - localization for Polish with diacritics - Poland for Sonoff-Tasmota - Copyright (C) 2018 Theo Arends (translated by roblad - Robert L.) + Copyright (C) 2018 Theo Arends (translated by roblad - Robert L., upgraded by R. Turala) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -17,8 +17,8 @@ along with this program. If not, see . */ -#ifndef _LANGUAGE_PL_PL_H_ -#define _LANGUAGE_PL_PL_H_ +#ifndef _LANGUAGE_PL_PL_D_H_ +#define _LANGUAGE_PL_PL_D_H_ /*************************** ATTENTION *******************************\ * @@ -28,10 +28,14 @@ * Use online command StateText to translate ON, OFF, HOLD and TOGGLE. * Use online command Prefix to translate cmnd, stat and tele. * + * Updated until v5.12.0d \*********************************************************************/ //#define LANGUAGE_MODULE_NAME // Enable to display "Module Generic" (ie Spanish), Disable to display "Generic Module" (ie English) +// HTML (ISO 639-1) Language Code +#define D_HTML_LANGUAGE "pl" + // "2017-03-07T11:08:02" - ISO8601:2004 #define D_YEAR_MONTH_SEPARATOR "-" #define D_MONTH_DAY_SEPARATOR "-" @@ -39,20 +43,20 @@ #define D_HOUR_MINUTE_SEPARATOR ":" #define D_MINUTE_SECOND_SEPARATOR ":" -#define D_DAY3LIST "PonWtoSroCzwPiaSobNie" -#define D_MONTH3LIST "StyLutMarKwiMajCzeLipSieWrzPazLisGru" +#define D_DAY3LIST "PonWtoŚroCzwPiąSobNie" +#define D_MONTH3LIST "StyLutMarKwiMajCzeLipSieWrzPaźLisGru" // Non JSON decimal separator #define D_DECIMAL_SEPARATOR "," // Common #define D_ADMIN "Admin" -#define D_AIR_QUALITY "Jakosc powietrza" +#define D_AIR_QUALITY "Jakość powietrza" #define D_AP "AP" // Access Point #define D_AS "jak" #define D_AUTO "AUTO" #define D_BLINK "Miganie" -#define D_BLINKOFF "MiganieWyl" +#define D_BLINKOFF "MiganieWył" #define D_BOOT_COUNT "Licznik uruchomienia" #define D_BRIGHTLIGHT "Jasny" #define D_BUTTON "Przycisk" @@ -63,60 +67,62 @@ #define D_CODE "kod" // Button code #define D_COLDLIGHT "Zimny" #define D_COMMAND "Komenda" -#define D_CONNECTED "Polaczony" +#define D_CONNECTED "Połączony" #define D_COUNT "Licz" #define D_COUNTER "Licznik" -#define D_CURRENT "Biezacy" // As in Voltage and Current +#define D_CURRENT "Bieżący" // As in Voltage and Current #define D_DATA "Data" #define D_DARKLIGHT "Ciemny" #define D_DEBUG "Debug" #define D_DISABLED "Zablokowany" +#define D_DISTANCE "Distance" #define D_DNS_SERVER "Server DNS" #define D_DONE "Wykonane" #define D_DST_TIME "DST" +#define D_ECO2 "eCO2" #define D_EMULATION "Emulacja" #define D_ENABLED "Otwarty" #define D_ERASE "Nadpisz" -#define D_ERROR "Blad" +#define D_ERROR "Błąd" #define D_FAHRENHEIT "Fahrenheita" -#define D_FAILED "Bledny" +#define D_FAILED "Błędny" #define D_FALLBACK "Awaryjny" -#define D_FALLBACK_TOPIC "Zastepczy temat" -#define D_FALSE "Falsz" +#define D_FALLBACK_TOPIC "Zastępczy temat" +#define D_FALSE "Fałsz" #define D_FILE "Plik" -#define D_FREE_MEMORY "Wolna pamiec" +#define D_FREE_MEMORY "Wolna pamięć" #define D_GAS "Gas" #define D_GATEWAY "Brama" #define D_GROUP "Grupa" #define D_HOST "Serwer" #define D_HOSTNAME "Nazwa serwera" -#define D_HUMIDITY "Wilgotnosc" -#define D_ILLUMINANCE "Oswietlenie" +#define D_HUMIDITY "Wilgotność" +#define D_ILLUMINANCE "Oświetlenie" #define D_IMMEDIATE "Natychmiastowe" // Button immediate #define D_INDEX "Indeks" #define D_INFO "Informacja" #define D_INITIALIZED "Zainicjowany" #define D_IP_ADDRESS "Adres IP" -#define D_LIGHT "Swiatlo" +#define D_LIGHT "Światło" #define D_LWT "LWT" -#define D_MODULE "Modul" +#define D_MODULE "Moduł" #define D_MQTT "MQTT" -#define D_MULTI_PRESS "wielokrotne-nacisniecie" -#define D_NOISE "Halas" +#define D_MULTI_PRESS "wielokrotne-naciśnięcie" +#define D_NOISE "Hałas" #define D_NONE "Brak" -#define D_OFF "Wylaczony" +#define D_OFF "Wyłączony" #define D_OFFLINE "Nieaktywny" #define D_OK "Ok" -#define D_ON "Wlaczony" +#define D_ON "Włączony" #define D_ONLINE "Aktywny" -#define D_PASSWORD "Haslo" +#define D_PASSWORD "Hasło" #define D_PORT "Port" -#define D_POWER_FACTOR "Wspolczynik mocy" +#define D_POWER_FACTOR "Współczynik mocy" #define D_POWERUSAGE "Moc" -#define D_PRESSURE "Cisnienie" -#define D_PRESSUREATSEALEVEL "Cisnienie na poziomie morza" -#define D_PROGRAM_FLASH_SIZE "Wielkosc programu flash" -#define D_PROGRAM_SIZE "Wielkosc programu" +#define D_PRESSURE "Ciśnienie" +#define D_PRESSUREATSEALEVEL "Ciśnienie na poziomie morza" +#define D_PROGRAM_FLASH_SIZE "Wielkość programu flash" +#define D_PROGRAM_SIZE "Wielkość programu" #define D_PROJECT "Projekt" #define D_RECEIVED "Otrzymany" #define D_RESTART "Restart" @@ -124,6 +130,7 @@ #define D_RESTART_REASON "Przyczyna restartu" #define D_RESTORE "Przywracanie" #define D_RETAINED "Zachowane" +#define D_RULE "Rule" #define D_SAVE "Zapisz" #define D_SENSOR "Czujnik" #define D_SSID "SSID" @@ -133,20 +140,23 @@ #define D_SUBNET_MASK "Maska podsieci" #define D_SUBSCRIBE_TO "Subskrybuj do" #define D_SUCCESSFUL "Powodzenie" +#define D_SUNRISE "Sunrise" +#define D_SUNSET "Sunset" #define D_TEMPERATURE "Temperatura" #define D_TO "do" -#define D_TOGGLE "Przelacz" +#define D_TOGGLE "Przełącz" #define D_TOPIC "Temat" -#define D_TRANSMIT "Wyslij" +#define D_TRANSMIT "Wyślij" #define D_TRUE "Prawda" +#define D_TVOC "TVOC" #define D_UPGRADE "aktualizacji" #define D_UPLOAD "Wgraj" #define D_UPTIME "Uptime" -#define D_USER "Uzytkownik" +#define D_USER "Użytkownik" #define D_UTC_TIME "UTC" #define D_UV_LEVEL "Poziom UV" #define D_VERSION "Wersja" -#define D_VOLTAGE "Napiecie" +#define D_VOLTAGE "Napięcie" #define D_WARMLIGHT "Nagrzanie" #define D_WEB_SERVER "Web Server" @@ -154,82 +164,75 @@ #define D_WARNING_MINIMAL_VERSION "WARNING This version does not support persistent settings" #define D_LEVEL_10 "poziom 1-0" #define D_LEVEL_01 "poziom 0-1" -#define D_SERIAL_LOGGING_DISABLED "Wylaczony dziennik na porcie szeregowym" +#define D_SERIAL_LOGGING_DISABLED "Wyłączony dziennik na porcie szeregowym" #define D_SYSLOG_LOGGING_REENABLED "Wznowiono zapis do Syslog" -#define D_SET_BAUDRATE_TO "Ustaw szybkosc transmisji na" +#define D_SET_BAUDRATE_TO "Ustaw szybkość transmisji na" #define D_RECEIVED_TOPIC "Otrzymany temat" -#define D_DATA_SIZE "Wielkosc danych" +#define D_DATA_SIZE "Wielkość danych" #define D_ANALOG_INPUT "Wej_analogowe" -#define D_FINGERPRINT "Weryfikuj odcisk TLS..." -#define D_TLS_CONNECT_FAILED_TO "Nieudane polaczenie TLS do" -#define D_RETRY_IN "Sprobuj ponownie" -#define D_VERIFIED "Zweryfikowano" -#define D_INSECURE "Nieprawidlowe polaczenie z powodu blednego odcisku TLS" -#define D_CONNECT_FAILED_TO "Nie udalo sie nawiazac polaczenia" - // support.ino #define D_OSWATCH "osWatch" -#define D_BLOCKED_LOOP "Petla zablokowana" -#define D_WPS_FAILED_WITH_STATUS "Blad WPSconfig ze statusem" +#define D_BLOCKED_LOOP "Pętla zablokowana" +#define D_WPS_FAILED_WITH_STATUS "Błąd WPSconfig ze statusem" #define D_ACTIVE_FOR_3_MINUTES "aktywny 3 minuty" -#define D_FAILED_TO_START "nie udalo sie uruchomic" -#define D_PATCH_ISSUE_2186 "Blad latki 2186" -#define D_CONNECTING_TO_AP "Laczenie z AP" +#define D_FAILED_TO_START "nie udało się uruchomić" +#define D_PATCH_ISSUE_2186 "Błąd łatki 2186" +#define D_CONNECTING_TO_AP "Łączenie z AP" #define D_IN_MODE "w trybie" -#define D_CONNECT_FAILED_NO_IP_ADDRESS "Polaczenie nie powiodlo sie, poniewaz nie otrzymano adresu IP" -#define D_CONNECT_FAILED_AP_NOT_REACHED "Polaczenie nie powiodlo sie jako AP nie mozna osiagnac" -#define D_CONNECT_FAILED_WRONG_PASSWORD "Polaczenie nie powiodlo sie z nieprawidlowym haslem dostepu AP" -#define D_CONNECT_FAILED_AP_TIMEOUT "Nie udalo sie nawiazac polaczenia, limit czasu AP przekroczony" -#define D_ATTEMPTING_CONNECTION "Proba polaczenia..." -#define D_CHECKING_CONNECTION "Sprawdzanie polaczenia..." +#define D_CONNECT_FAILED_NO_IP_ADDRESS "Połączenie nie powiodło sie, ponieważ nie otrzymano adresu IP" +#define D_CONNECT_FAILED_AP_NOT_REACHED "Połączenie nie powiodło sie jako AP nie można osiągnać" +#define D_CONNECT_FAILED_WRONG_PASSWORD "Połączenie nie powiodło sie z nieprawidlowym hasłem dostepu AP" +#define D_CONNECT_FAILED_AP_TIMEOUT "Nie udało się nawiązac połączenia, limit czasu AP przekroczony" +#define D_ATTEMPTING_CONNECTION "Próba połączenia..." +#define D_CHECKING_CONNECTION "Sprawdzanie połączenia..." #define D_QUERY_DONE "Wykonano zapytanie. Znaleziono uslugi MQTT" -#define D_MQTT_SERVICE_FOUND "Usluga MQTT została znaleziona" +#define D_MQTT_SERVICE_FOUND "Usługa MQTT została znaleziona" #define D_FOUND_AT "znalezione w" #define D_SYSLOG_HOST_NOT_FOUND "Syslog Host nie znaleziony" // settings.ino -#define D_SAVED_TO_FLASH_AT "Zapisane do pamieci flash w" -#define D_LOADED_FROM_FLASH_AT "Wczytane z pamieci flash z" -#define D_USE_DEFAULTS "Uzyj domyslnych" +#define D_SAVED_TO_FLASH_AT "Zapisane do pamięci flash w" +#define D_LOADED_FROM_FLASH_AT "Wczytane z pamięci flash z" +#define D_USE_DEFAULTS "Użyj domyślnych" #define D_ERASED_SECTOR "Wymazany sektor" // webserver.ino -#define D_MINIMAL_FIRMWARE_PLEASE_UPGRADE "Oprogramowanie MINIMAL - prosze uaktualnic" +#define D_MINIMAL_FIRMWARE_PLEASE_UPGRADE "Oprogramowanie MINIMAL - proszę uaktualnić" #define D_WEBSERVER_ACTIVE_ON "Aktywny serwer Web" #define D_WITH_IP_ADDRESS "z adresem IP" #define D_WEBSERVER_STOPPED "Serwer Web zatrzymany" #define D_FILE_NOT_FOUND "Plik nie odnaleziony" -#define D_REDIRECTED "Przekierowano do wlasnego portalu" -#define D_WIFIMANAGER_SET_ACCESSPOINT_AND_STATION "Menedzer Wifi ustawia punkt dostepowy i zachowuje stacje" -#define D_WIFIMANAGER_SET_ACCESSPOINT "Menedzer sieci Wi-Fi Access Point" -#define D_TRYING_TO_CONNECT "Probuje polaczyc urzadzenie z siecia" +#define D_REDIRECTED "Przekierowano do własnego portalu" +#define D_WIFIMANAGER_SET_ACCESSPOINT_AND_STATION "Menedżer Wifi ustawia punkt dostępowy i zachowuje stacje" +#define D_WIFIMANAGER_SET_ACCESSPOINT "Menedżer sieci Wi-Fi Access Point" +#define D_TRYING_TO_CONNECT "Próbuję połączyć urzadzenie z siecią" #define D_RESTART_IN "Zrestartuj" #define D_SECONDS "sekund" -#define D_DEVICE_WILL_RESTART "Urzadzenie zrestartuje sie za kilka sekund" -#define D_BUTTON_TOGGLE "Przelacznik" +#define D_DEVICE_WILL_RESTART "Urządzenie zrestartuje sie za kilka sekund" +#define D_BUTTON_TOGGLE "Przełącznik" #define D_CONFIGURATION "Konfiguracja" #define D_INFORMATION "Informacje" #define D_FIRMWARE_UPGRADE "Uaktualnienie oprogramowania" #define D_CONSOLE "Konsola" -#define D_CONFIRM_RESTART "Potwierdz restart" +#define D_CONFIRM_RESTART "Potwierdź restart" -#define D_CONFIGURE_MODULE "Konfiguruj modul" +#define D_CONFIGURE_MODULE "Konfiguruj moduł" #define D_CONFIGURE_WIFI "Konfiguruj WiFi" #define D_CONFIGURE_MQTT "Konfiguruj MQTT" #define D_CONFIGURE_DOMOTICZ "Konfiguruj Domoticz" #define D_CONFIGURE_LOGGING "Konfiguruj zapis dziennika" #define D_CONFIGURE_OTHER "Konfiguruj inne" -#define D_CONFIRM_RESET_CONFIGURATION "Potwierdz reset ustawien" -#define D_RESET_CONFIGURATION "Reset ustawien" -#define D_BACKUP_CONFIGURATION "Kopia ustawien" -#define D_RESTORE_CONFIGURATION "Przywrocenie ustawien" -#define D_MAIN_MENU "Menu glowne" +#define D_CONFIRM_RESET_CONFIGURATION "Potwierdź reset ustawień" +#define D_RESET_CONFIGURATION "Reset ustawień" +#define D_BACKUP_CONFIGURATION "Kopia ustawień" +#define D_RESTORE_CONFIGURATION "Przywrócenie ustawień" +#define D_MAIN_MENU "Menu główne" -#define D_MODULE_PARAMETERS "Parametery modulu" -#define D_MODULE_TYPE "Typ modulu" +#define D_MODULE_PARAMETERS "Parametery modułu" +#define D_MODULE_TYPE "Typ modułu" #define D_GPIO "GPIO" #define D_SERIAL_IN "Serial In" #define D_SERIAL_OUT "Serial Out" @@ -238,33 +241,33 @@ #define D_SCAN_FOR_WIFI_NETWORKS "Skanuj sieci WiFi" #define D_SCAN_DONE "Skan wykonany" #define D_NO_NETWORKS_FOUND "Nie znaleziono sieci" -#define D_REFRESH_TO_SCAN_AGAIN "Odswiez aby ponownie zeskanowac" +#define D_REFRESH_TO_SCAN_AGAIN "Odswież aby ponownie zeskanowac" #define D_DUPLICATE_ACCESSPOINT "Kopiuj AP" -#define D_SKIPPING_LOW_QUALITY "Pominieto z powodu niskiej jakości sygnalu" +#define D_SKIPPING_LOW_QUALITY "Pominięto z powodu niskiej jakości sygnału" #define D_RSSI "RSSI" #define D_WEP "WEP" #define D_WPA_PSK "WPA PSK" #define D_WPA2_PSK "WPA2 PSK" #define D_AP1_SSID "AP1 SSID" -#define D_AP1_PASSWORD "Haslo AP1" +#define D_AP1_PASSWORD "Hasło AP1" #define D_AP2_SSID "AP2 SSID" -#define D_AP2_PASSWORD "Haslo AP2" +#define D_AP2_PASSWORD "Hasło AP2" #define D_MQTT_PARAMETERS "Parametery MQTT" #define D_CLIENT "Klient" -#define D_FULL_TOPIC "Pelen temat" +#define D_FULL_TOPIC "Pełen temat" #define D_LOGGING_PARAMETERS "Opcje dziennika" #define D_SERIAL_LOG_LEVEL "Serial poziom dziennika" #define D_WEB_LOG_LEVEL "Web poziom dziennika" #define D_SYS_LOG_LEVEL "System poziom dziennika" -#define D_MORE_DEBUG "Wiecej informacji debugujacych" +#define D_MORE_DEBUG "Więcej informacji debugujacych" #define D_SYSLOG_HOST "Syslog host" #define D_SYSLOG_PORT "Syslog port" #define D_TELEMETRY_PERIOD "Okres telemetrii" #define D_OTHER_PARAMETERS "Inne parametery" -#define D_WEB_ADMIN_PASSWORD "Haslo administratora Web" +#define D_WEB_ADMIN_PASSWORD "Hasło administratora Web" #define D_MQTT_ENABLE "MQTT aktywne" #define D_FRIENDLY_NAME "Przyjazna nazwa" #define D_BELKIN_WEMO "Belkin WeMo" @@ -277,9 +280,9 @@ #define D_CONFIGURATION_RESET "Ustawienia zresetowane" #define D_PROGRAM_VERSION "Wersja programu" -#define D_BUILD_DATE_AND_TIME "Dzien i godzina kompilacji" +#define D_BUILD_DATE_AND_TIME "Dzień i godzina kompilacji" #define D_CORE_AND_SDK_VERSION "Wersja Core/SDK" -#define D_FLASH_WRITE_COUNT "Liczba zapisow do pamieci" +#define D_FLASH_WRITE_COUNT "Liczba zapisów do pamięci" #define D_MAC_ADDRESS "Adres Mac" #define D_MQTT_HOST "Host MQTT" #define D_MQTT_PORT "Port MQTT" @@ -287,11 +290,11 @@ #define D_MQTT_USER "Uzytkownik MQTT" #define D_MQTT_TOPIC "Temat MQTT" #define D_MQTT_GROUP_TOPIC "Temat grupy MQTT" -#define D_MQTT_FULL_TOPIC "Pelen temat MQTT" +#define D_MQTT_FULL_TOPIC "Pełen temat MQTT" #define D_MDNS_DISCOVERY "Wykrywanie mDNS" -#define D_MDNS_ADVERTISE "Rozglaszanie mDNS" +#define D_MDNS_ADVERTISE "Rozgłaszanie mDNS" #define D_ESP_CHIP_ID "ID ukladu ESP" -#define D_FLASH_CHIP_ID "ID ukladu pamieci flash" +#define D_FLASH_CHIP_ID "ID układu pamięci flash" #define D_FLASH_CHIP_SIZE "Rozmiar flash" #define D_FREE_PROGRAM_SPACE "Wolne miejsce programu" @@ -299,69 +302,107 @@ #define D_OTA_URL "URL OTA" #define D_START_UPGRADE "Start aktualizacji" #define D_UPGRADE_BY_FILE_UPLOAD "Aktualizacja poprzez wgranie pliku" -#define D_UPLOAD_STARTED "Wgrywanie rozpoczete" -#define D_UPGRADE_STARTED "Aktualizacja rozpoczeta" -#define D_UPLOAD_DONE "Wgrywanie zakonczone" +#define D_UPLOAD_STARTED "Wgrywanie rozpoczęte" +#define D_UPGRADE_STARTED "Aktualizacja rozpoczęta" +#define D_UPLOAD_DONE "Wgrywanie zakończone" #define D_UPLOAD_ERR_1 "Nie wybrano pliku" -#define D_UPLOAD_ERR_2 "Niewystarczajaca ilosc miejsca" +#define D_UPLOAD_ERR_2 "Niewystarczająca ilość miejsca" #define D_UPLOAD_ERR_3 "Magiczny bajt jest inny niz 0xE9" -#define D_UPLOAD_ERR_4 "Rozmiar programu jest wiekszy niz rzeczywisty rozmiar pamieci flash" -#define D_UPLOAD_ERR_5 "Wgrywanie, bufor niezgodnosci stanu porownywanych bitow" -#define D_UPLOAD_ERR_6 "Blad wgrywania. Uruchomiono zapis do dziennika na poziomie 3" +#define D_UPLOAD_ERR_4 "Rozmiar programu jest większy niż rzeczywisty rozmiar pamieci flash" +#define D_UPLOAD_ERR_5 "Wgrywanie, bufor niezgodnosci stanu porównywanych bitow" +#define D_UPLOAD_ERR_6 "Błąd wgrywania. Uruchomiono zapis do dziennika na poziomie 3" #define D_UPLOAD_ERR_7 "Wgrywanie przerwane" -#define D_UPLOAD_ERR_8 "Bledny plik" -#define D_UPLOAD_ERR_9 "Plik jest za duzy" -#define D_UPLOAD_ERROR_CODE "Blad wgrywania" +#define D_UPLOAD_ERR_8 "Błędny plik" +#define D_UPLOAD_ERR_9 "Plik jest za duży" +#define D_UPLOAD_ERROR_CODE "Błąd wgrywania" -#define D_ENTER_COMMAND "Wprowadz polecenie" -#define D_ENABLE_WEBLOG_FOR_RESPONSE "Wlacz poziom 2 zapisu Weblog, jesli oczekiwana jest odpowiedz" -#define D_NEED_USER_AND_PASSWORD "Wymagany uzytkownik=&haslo=" +#define D_ENTER_COMMAND "Wprowadź polecenie" +#define D_ENABLE_WEBLOG_FOR_RESPONSE "Włącz poziom 2 zapisu Weblog, jeśli oczekiwana jest odpowiedź" +#define D_NEED_USER_AND_PASSWORD "Wymagany użytkownik=&hasło=" + +// xdrv_00_mqtt.ino +#define D_FINGERPRINT "Weryfikuj odcisk TLS..." +#define D_TLS_CONNECT_FAILED_TO "Nieudane połączenie TLS do" +#define D_RETRY_IN "Spróbuj ponownie" +#define D_VERIFIED "Zweryfikowano odcisku" +#define D_INSECURE "Nieprawidłowe połączenie z powodu błędnego odcisku TLS" +#define D_CONNECT_FAILED_TO "Nie udało się nawiązać połączenia" // xdrv_wemohue.ino -#define D_MULTICAST_DISABLED "Multicast jest wylaczony" -#define D_MULTICAST_REJOINED "Multicast (re)dolaczony" -#define D_MULTICAST_JOIN_FAILED "Multicast nie powiodlo sie" -#define D_FAILED_TO_SEND_RESPONSE "Nie udalo sie wyslac odpowiedzi" +#define D_MULTICAST_DISABLED "Multicast jest wyłączony" +#define D_MULTICAST_REJOINED "Multicast (re)dołączony" +#define D_MULTICAST_JOIN_FAILED "Multicast nie powiodło się" +#define D_FAILED_TO_SEND_RESPONSE "Nie udało się wysłać odpowiedzi" #define D_WEMO "WeMo" #define D_WEMO_BASIC_EVENT "WeMo podstawowe zdarzenie" #define D_WEMO_EVENT_SERVICE "WeMo zdarzenie service" #define D_WEMO_META_SERVICE "WeMo meta service" #define D_WEMO_SETUP "WeMo setup" -#define D_RESPONSE_SENT "Odpowiedz wyslana" +#define D_RESPONSE_SENT "Odpowiedź wysłana" #define D_HUE "Hue" #define D_HUE_BRIDGE_SETUP "Hue setup" #define D_HUE_API_NOT_IMPLEMENTED "Hue API nie zaimplementowane" #define D_HUE_API "Hue API" #define D_HUE_POST_ARGS "Hue POST args" -#define D_3_RESPONSE_PACKETS_SENT "3 pakiety odpowiedzi wysylane" +#define D_3_RESPONSE_PACKETS_SENT "3 pakiety odpowiedzi wysyłane" // xdrv_05_domoticz.ino #define D_DOMOTICZ_PARAMETERS "Parametry Domoticz" #define D_DOMOTICZ_IDX "Idx" #define D_DOMOTICZ_KEY_IDX "Key idx" -#define D_DOMOTICZ_SWITCH_IDX "Przelacznik idx" +#define D_DOMOTICZ_SWITCH_IDX "Przełącznik idx" #define D_DOMOTICZ_SENSOR_IDX "Sensor idx" #define D_DOMOTICZ_TEMP "Temp" #define D_DOMOTICZ_TEMP_HUM "Temp,Wilg" #define D_DOMOTICZ_TEMP_HUM_BARO "Temp,Wilg,Cis" #define D_DOMOTICZ_POWER_ENERGY "Moc,Energia" - #define D_DOMOTICZ_ILLUMINANCE "Oswietl." - #define D_DOMOTICZ_COUNT "Licznik" - #define D_DOMOTICZ_VOLTAGE "Napiecie" - #define D_DOMOTICZ_CURRENT "Prad" + #define D_DOMOTICZ_ILLUMINANCE "Oświetl." + #define D_DOMOTICZ_COUNT "Licznik/PM1" + #define D_DOMOTICZ_VOLTAGE "Napięcie/PM2,5" + #define D_DOMOTICZ_CURRENT "Prąd/PM10" #define D_DOMOTICZ_AIRQUALITY "AirQuality" #define D_DOMOTICZ_UPDATE_TIMER "Zaktualizuj czasomierz" +// xdrv_09_timers.ino +#define D_CONFIGURE_TIMER "Configure Timer" +#define D_TIMER_PARAMETERS "Timer parameters" +#define D_TIMER_ARM "Arm" +#define D_TIMER_TIME "Time" +#define D_TIMER_DAYS "Days" +#define D_TIMER_REPEAT "Repeat" +#define D_TIMER_OUTPUT "Output" +#define D_TIMER_ACTION "Action" + +// xdrv_10_knx.ino +#define D_CONFIGURE_KNX "Configure KNX" +#define D_KNX_PARAMETERS "KNX Parameters" +#define D_KNX_GENERAL_CONFIG "General" +#define D_KNX_PHYSICAL_ADDRESS "Physical Address" +#define D_KNX_PHYSICAL_ADDRESS_NOTE "( Must be unique on the KNX network )" +#define D_KNX_ENABLE "Enable KNX" +#define D_KNX_GROUP_ADDRESS_TO_WRITE "Data to Send to Group Addresses" +#define D_ADD "Add" +#define D_DELETE "Delete" +#define D_REPLY "Reply" +#define D_KNX_GROUP_ADDRESS_TO_READ "Group Addresses to Receive Data from" +#define D_LOG_KNX "KNX: " +#define D_RECEIVED_FROM "Received from" +#define D_KNX_COMMAND_WRITE "Write" +#define D_KNX_COMMAND_READ "Read" +#define D_KNX_COMMAND_OTHER "Other" +#define D_SENT_TO "sent to" +#define D_KNX_WARNING "The group address ( 0 / 0 / 0 ) is reserved and can not be used." + // xdrv_03_energy.ino #define D_ENERGY_TODAY "Energia Dzisiaj" #define D_ENERGY_YESTERDAY "Energia Wczoraj" #define D_ENERGY_TOTAL "Energia suma" // xsns_05_ds18b20.ino -#define D_SENSOR_BUSY "Czujnik DS18x20 zajety" -#define D_SENSOR_CRC_ERROR "Czujnik DS18x20 blad CRC" +#define D_SENSOR_BUSY "Czujnik DS18x20 zajęty" +#define D_SENSOR_CRC_ERROR "Czujnik DS18x20 błąd CRC" #define D_SENSORS_FOUND "Znaleziono Czujnik DS18x20" // xsns_06_dht.ino @@ -369,10 +410,10 @@ #define D_START_SIGNAL_LOW "sygnał startowy niski" #define D_START_SIGNAL_HIGH "sygnał startowy wysoki" #define D_PULSE "pulse" -#define D_CHECKSUM_FAILURE "Bledna suma kontrolmna" +#define D_CHECKSUM_FAILURE "Błędna suma kontrolna" // xsns_07_sht1x.ino -#define D_SENSOR_DID_NOT_ACK_COMMAND "Czujnik nie otrzymal komendy ACK" +#define D_SENSOR_DID_NOT_ACK_COMMAND "Czujnik nie otrzymał komendy ACK" #define D_SHT1X_FOUND "SHT1X znaleziony" // xsns_18_pms5003.ino @@ -407,9 +448,15 @@ #define D_SENSOR_SPI_DC "SPI DC" #define D_SENSOR_BACKLIGHT "BkLight" #define D_SENSOR_PMS5003 "PMS5003" +#define D_SENSOR_SDS0X1 "SDS0X1" +#define D_SENSOR_SBR_RX "SerBr Rx" +#define D_SENSOR_SBR_TX "SerBr Tx" +#define D_SENSOR_SR04_TRIG "SR04 Tri" +#define D_SENSOR_SR04_ECHO "SR04 Ech" // Units #define D_UNIT_AMPERE "A" +#define D_UNIT_CENTIMETER "cm" #define D_UNIT_HOUR "Godz" #define D_UNIT_KILOOHM "kOhm" #define D_UNIT_KILOWATTHOUR "kWh" @@ -420,6 +467,7 @@ #define D_UNIT_MILLIAMPERE "mA" #define D_UNIT_MILLISECOND "ms" #define D_UNIT_MINUTE "Min" +#define D_UNIT_PARTS_PER_BILLION "ppb" #define D_UNIT_PARTS_PER_DECILITER "ppd" #define D_UNIT_PARTS_PER_MILLION "ppm" #define D_UNIT_PRESSURE "hPa" @@ -454,4 +502,4 @@ #define D_LOG_UPNP "UPP: " // UPnP #define D_LOG_WIFI "WIF: " // Wifi -#endif // _LANGUAGE_PL_PL_H_ +#endif // _LANGUAGE_PL_PL_D_H_ diff --git a/sonoff/language/pt-PT.h b/sonoff/language/pt-PT.h new file mode 100644 index 000000000..55ccf37a6 --- /dev/null +++ b/sonoff/language/pt-PT.h @@ -0,0 +1,505 @@ +/* + pt-PT.h - localization for Portuguese - Portugal for Sonoff-Tasmota + + Copyright (C) 2018 Theo Arends and Paulo Paiva + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifndef _LANGUAGE_PT_PT_H_ +#define _LANGUAGE_PT_PT_H_ + +/*************************** ATTENTION *******************************\ + * + * Due to memory constraints only UTF-8 is supported. + * To save code space keep text as short as possible. + * Time and Date provided by SDK can not be localized (yet). + * Use online command StateText to translate ON, OFF, HOLD and TOGGLE. + * Use online command Prefix to translate cmnd, stat and tele. + * + * Updated until v5.12.0 +\*********************************************************************/ + +//#define LANGUAGE_MODULE_NAME // Enable to display "Module Generic" (ie Spanish), Disable to display "Generic Module" (ie English) + +// HTML (ISO 639-1) Language Code +#define D_HTML_LANGUAGE "pt" + +// "2017-03-07T11:08:02" - ISO8601:2004 +#define D_YEAR_MONTH_SEPARATOR "-" +#define D_MONTH_DAY_SEPARATOR "-" +#define D_DATE_TIME_SEPARATOR "T" +#define D_HOUR_MINUTE_SEPARATOR ":" +#define D_MINUTE_SECOND_SEPARATOR ":" + +#define D_DAY3LIST "DomSegTerQuaQuiSexSab" +#define D_MONTH3LIST "JanFevMarAbrMaiJunJulAgoSepOutNovDez" + +// Non JSON decimal separator +#define D_DECIMAL_SEPARATOR "." + +// Common +#define D_ADMIN "Admin" +#define D_AIR_QUALITY "Qualidade do Ar" +#define D_AP "AP" // Ponto de Acesso +#define D_AS "como" +#define D_AUTO "AUTO" +#define D_BLINK "Piscar" +#define D_BLINKOFF "Piscar desligado" +#define D_BOOT_COUNT "Contagem de Inicialização" +#define D_BRIGHTLIGHT "Brilho" +#define D_BUTTON "Botão" +#define D_BY "por" // Write by me +#define D_BYTES "Bytes" +#define D_CELSIUS "Celsius" +#define D_CO2 "Dioxido de Carbono" +#define D_CODE "Código" // Button code +#define D_COLDLIGHT "Luz Fria" +#define D_COMMAND "Comando" +#define D_CONNECTED "Ligado" +#define D_COUNT "Contagem" +#define D_COUNTER "Contador" +#define D_CURRENT "Corrente" // As in Voltage and Current +#define D_DATA "Dados" +#define D_DARKLIGHT "Luz Escura" +#define D_DEBUG "Depurar" +#define D_DISABLED "Disabilitado" +#define D_DISTANCE "Distance" +#define D_DNS_SERVER "Servidor DNS" +#define D_DONE "Concluído" +#define D_DST_TIME "DST" +#define D_ECO2 "eCO2" +#define D_EMULATION "Emulação" +#define D_ENABLED "Habilitado" +#define D_ERASE "Apagar" +#define D_ERROR "Erro" +#define D_FAHRENHEIT "Fahrenheit" +#define D_FAILED "Falha" +#define D_FALLBACK "Retornar" +#define D_FALLBACK_TOPIC "Tópico para retornar" +#define D_FALSE "Falso" +#define D_FILE "Ficheiro" +#define D_FREE_MEMORY "Memoria Livre" +#define D_GAS "Gás" +#define D_GATEWAY "Gateway" +#define D_GROUP "Grupo" +#define D_HOST "Anfitrião" +#define D_HOSTNAME "Nome Anfitrião" +#define D_HUMIDITY "Humidade" +#define D_ILLUMINANCE "Luminâcia" +#define D_IMMEDIATE "Immediato" // Button immediate +#define D_INDEX "Indíce" +#define D_INFO "Info" +#define D_INITIALIZED "Inicializado" +#define D_IP_ADDRESS "Endereço IP" +#define D_LIGHT "Luz" +#define D_LWT "LWT" +#define D_MODULE "Módulo" +#define D_MQTT "MQTT" +#define D_MULTI_PRESS "multi-pressão" +#define D_NOISE "Ruído" +#define D_NONE "Nenhum" +#define D_OFF "Off" +#define D_OFFLINE "Desconetado" +#define D_OK "Ok" +#define D_ON "On" +#define D_ONLINE "Conetado" +#define D_PASSWORD "Palavra Chave" +#define D_PORT "Porta" +#define D_POWER_FACTOR "Factor de Potência" +#define D_POWERUSAGE "Potência" +#define D_PRESSURE "Pressão" +#define D_PRESSUREATSEALEVEL "Pressão ao nível do Mar" +#define D_PROGRAM_FLASH_SIZE "Tamanho do Programa na Flash" +#define D_PROGRAM_SIZE "Tamanho do Programa" +#define D_PROJECT "Projeto" +#define D_RECEIVED "Recebido" +#define D_RESTART "Reiniciar" +#define D_RESTARTING "A reiniciar" +#define D_RESTART_REASON "Razão do reinicio" +#define D_RESTORE "Restauro" +#define D_RETAINED "Manter" +#define D_RULE "Rule" +#define D_SAVE "Salvar" +#define D_SENSOR "Sensor" +#define D_SSID "SSId" +#define D_START "Início" +#define D_STD_TIME "STD" +#define D_STOP "Parar" +#define D_SUBNET_MASK "Mascara sub rede" +#define D_SUBSCRIBE_TO "Subescrever para" +#define D_SUCCESSFUL "Successo" +#define D_SUNRISE "Sunrise" +#define D_SUNSET "Sunset" +#define D_TEMPERATURE "Temperatura" +#define D_TO "para" +#define D_TOGGLE "Pressionar" +#define D_TOPIC "Tópico" +#define D_TRANSMIT "Transmitir" +#define D_TRUE "Verdadeiro" +#define D_TVOC "TVOC" +#define D_UPGRADE "Atualizar" +#define D_UPLOAD "Enviar" +#define D_UPTIME "Tempo de Atividade" +#define D_USER "Utilizador" +#define D_UTC_TIME "UTC" +#define D_UV_LEVEL "Nível UV" +#define D_VERSION "Versão" +#define D_VOLTAGE "Voltagem" +#define D_WARMLIGHT "Luz Quente" +#define D_WEB_SERVER "servidor WEB" + +// sonoff.ino +#define D_WARNING_MINIMAL_VERSION "AVISO esta versão não supporta configurações persistentes" +#define D_LEVEL_10 "nível 1-0" +#define D_LEVEL_01 "nível 0-1" +#define D_SERIAL_LOGGING_DISABLED "Registro em serie desabilitado" +#define D_SYSLOG_LOGGING_REENABLED "Registro do Syslog reativado" + +#define D_SET_BAUDRATE_TO "Ajuste da velocidade para" +#define D_RECEIVED_TOPIC "Topico Recebido" +#define D_DATA_SIZE "Tamanho de dados" +#define D_ANALOG_INPUT "Entrada Analógica" + +// support.ino +#define D_OSWATCH "osWatch" +#define D_BLOCKED_LOOP "Loop Bloqueado" +#define D_WPS_FAILED_WITH_STATUS "WPSconfig Falha de estado" +#define D_ACTIVE_FOR_3_MINUTES "ativo por 3 minutes" +#define D_FAILED_TO_START "Falha ao iníciar" +#define D_PATCH_ISSUE_2186 "Questão 2186" +#define D_CONNECTING_TO_AP "Ligando ao AP" +#define D_IN_MODE "em modo" +#define D_CONNECT_FAILED_NO_IP_ADDRESS "A ligação falhou porque nenhum endereço IP foi recebido" +#define D_CONNECT_FAILED_AP_NOT_REACHED "A ligação falhou porque o AP não pode ser alcançado" +#define D_CONNECT_FAILED_WRONG_PASSWORD "A ligação falhou porque a palavra chave está incorreta" +#define D_CONNECT_FAILED_AP_TIMEOUT "A ligação falhou porque o tempo excedeu" +#define D_ATTEMPTING_CONNECTION "A ligar..." +#define D_CHECKING_CONNECTION "A verificar ligação..." +#define D_QUERY_DONE "Consulta finalizada. Serviço MQTT não encontrado" +#define D_MQTT_SERVICE_FOUND "Serviço MQTT encontrado em" +#define D_FOUND_AT "encontrado em" +#define D_SYSLOG_HOST_NOT_FOUND "Syslog anfitrião não encontrado" + +// settings.ino +#define D_SAVED_TO_FLASH_AT "Guardado na flash em" +#define D_LOADED_FROM_FLASH_AT "Lido da flash em" +#define D_USE_DEFAULTS "Usar predefinições" +#define D_ERASED_SECTOR "Apagar setores" + +// webserver.ino +#define D_MINIMAL_FIRMWARE_PLEASE_UPGRADE "MINIMO firmware - Atualizar Por favor" +#define D_WEBSERVER_ACTIVE_ON "Servidor WEB ativo em" +#define D_WITH_IP_ADDRESS "com o endereço IP" +#define D_WEBSERVER_STOPPED "Servitor WEB parou" +#define D_FILE_NOT_FOUND "Ficheiro não encontrado" +#define D_REDIRECTED "Redirecionado para o portal ativo" +#define D_WIFIMANAGER_SET_ACCESSPOINT_AND_STATION "Wifimanager configura o Ponto de Acesso e mantem a Estação" +#define D_WIFIMANAGER_SET_ACCESSPOINT "Wifimanager configura o Ponto de Acesso" +#define D_TRYING_TO_CONNECT "A tentar ligar o dispositivo à rede" + +#define D_RESTART_IN "Reinicia em" +#define D_SECONDS "segundos" +#define D_DEVICE_WILL_RESTART "O dispositivo irá reiniciar dentro de alguns segundos" +#define D_BUTTON_TOGGLE "Pressionar" +#define D_CONFIGURATION "Configuração" +#define D_INFORMATION "Informação" +#define D_FIRMWARE_UPGRADE "Atualização de Firmware" +#define D_CONSOLE "Consola" +#define D_CONFIRM_RESTART "Confirmar o reinicio" + +#define D_CONFIGURE_MODULE "Configurar Módulo" +#define D_CONFIGURE_WIFI "Configurar WiFi" +#define D_CONFIGURE_MQTT "Configurar MQTT" +#define D_CONFIGURE_DOMOTICZ "Configurar Domoticz" +#define D_CONFIGURE_LOGGING "Configurar Logging" +#define D_CONFIGURE_OTHER "Configurar outras opções" +#define D_CONFIRM_RESET_CONFIGURATION "Apagar configuração Confirmar" +#define D_RESET_CONFIGURATION "Apagar configuração" +#define D_BACKUP_CONFIGURATION "Guardar configuração" +#define D_RESTORE_CONFIGURATION "Repor configuração" +#define D_MAIN_MENU "Menu Principal" + +#define D_MODULE_PARAMETERS "Parametros do Módulo" +#define D_MODULE_TYPE "Tipo de Módulo" +#define D_GPIO "GPIO" +#define D_SERIAL_IN "Serial Entrada" +#define D_SERIAL_OUT "Serial Saída" + +#define D_WIFI_PARAMETERS "Parametros Wifi" +#define D_SCAN_FOR_WIFI_NETWORKS "Em busca de redes wifi" +#define D_SCAN_DONE "Busca finalizada" +#define D_NO_NETWORKS_FOUND "Sem redes" +#define D_REFRESH_TO_SCAN_AGAIN "Nova busca" +#define D_DUPLICATE_ACCESSPOINT "Ponto de Acesso duplicado" +#define D_SKIPPING_LOW_QUALITY "Ignorado devido a baixa qualidade do sinal" +#define D_RSSI "RSSI" +#define D_WEP "WEP" +#define D_WPA_PSK "WPA PSK" +#define D_WPA2_PSK "WPA2 PSK" +#define D_AP1_SSID "AP1 SSId" +#define D_AP1_PASSWORD "AP1 Palavra Chave" +#define D_AP2_SSID "AP2 SSId" +#define D_AP2_PASSWORD "AP2 Palavra Chave" + +#define D_MQTT_PARAMETERS "Parametros MQTT" +#define D_CLIENT "Cliente" +#define D_FULL_TOPIC "Tópico completo" + +#define D_LOGGING_PARAMETERS "Parametros Logging" +#define D_SERIAL_LOG_LEVEL "Nível de registro serial" +#define D_WEB_LOG_LEVEL "Nível de registro WEB" +#define D_SYS_LOG_LEVEL "Nível de registro Syslog" +#define D_MORE_DEBUG "Depurar mais" +#define D_SYSLOG_HOST "Syslog anfitrião" +#define D_SYSLOG_PORT "Porta Syslog" +#define D_TELEMETRY_PERIOD "Periodo de Telemetria" + +#define D_OTHER_PARAMETERS "Outros parametros" +#define D_WEB_ADMIN_PASSWORD "Palavra Chave de WEB Admin" +#define D_MQTT_ENABLE "MQTT habilitado" +#define D_FRIENDLY_NAME "Nome amigável" +#define D_BELKIN_WEMO "Belkin WeMo" +#define D_HUE_BRIDGE "Hue Bridge" +#define D_SINGLE_DEVICE "dispositivo único" +#define D_MULTI_DEVICE "multiplos dispositivos" + +#define D_SAVE_CONFIGURATION "Salvar configuração" +#define D_CONFIGURATION_SAVED "Configuração guardada" +#define D_CONFIGURATION_RESET "Reinicialização da configuração" + +#define D_PROGRAM_VERSION "Versão do Programa" +#define D_BUILD_DATE_AND_TIME "Data e Hora da construção" +#define D_CORE_AND_SDK_VERSION "Versão Core/SDK" +#define D_FLASH_WRITE_COUNT "contagem de gravação flash" +#define D_MAC_ADDRESS "Endereço MAC" +#define D_MQTT_HOST "MQTT Servidor" +#define D_MQTT_PORT "MQTT Porta" +#define D_MQTT_CLIENT "MQTT Cliente" +#define D_MQTT_USER "MQTT Utilizador" +#define D_MQTT_TOPIC "MQTT Tópico" +#define D_MQTT_GROUP_TOPIC "MQTT Tópico Grupo" +#define D_MQTT_FULL_TOPIC "MQTT Tópico Completo" +#define D_MDNS_DISCOVERY "Descobrir mDNS" +#define D_MDNS_ADVERTISE "Anunciar mDNS" +#define D_ESP_CHIP_ID "ESP Chip Id" +#define D_FLASH_CHIP_ID "Flash Chip Id" +#define D_FLASH_CHIP_SIZE "Flash Size" +#define D_FREE_PROGRAM_SPACE "Espaço Livre Programa" + +#define D_UPGRADE_BY_WEBSERVER "Atualizar pelo servidor WEB" +#define D_OTA_URL "OTA Url" +#define D_START_UPGRADE "Iniciar atualização" +#define D_UPGRADE_BY_FILE_UPLOAD "Atualização por envio de ficheiro" +#define D_UPLOAD_STARTED "Início do envio" +#define D_UPGRADE_STARTED "Atualização Iniciada" +#define D_UPLOAD_DONE "Atualização Finalizada" +#define D_UPLOAD_ERR_1 "Nenhum ficheiro selecionado" +#define D_UPLOAD_ERR_2 "Nao existe espaço disponível" +#define D_UPLOAD_ERR_3 "Byte mágico não é 0xE9" +#define D_UPLOAD_ERR_4 "O tamanho do programa e maior do que o tamanho real da flash" +#define D_UPLOAD_ERR_5 "Envio buffer miscompare" +#define D_UPLOAD_ERR_6 "Falha no envio. Hablitar logging 3" +#define D_UPLOAD_ERR_7 "Envio cancelado" +#define D_UPLOAD_ERR_8 "Ficheiro inválido" +#define D_UPLOAD_ERR_9 "Ficheiro demasiado grande" +#define D_UPLOAD_ERROR_CODE "Código de erro do envio" + +#define D_ENTER_COMMAND "Inserir comando" +#define D_ENABLE_WEBLOG_FOR_RESPONSE "Habilitar weblog 2 se resposta esperada" +#define D_NEED_USER_AND_PASSWORD "Necessário user=&password=" + +// xdrv_00_mqtt.ino +#define D_FINGERPRINT "Verifique a impressão digital TLS..." +#define D_TLS_CONNECT_FAILED_TO "TLS não conseguiu ligar" +#define D_RETRY_IN "Tentativa em" +#define D_VERIFIED "Verificado impressão digital " +#define D_INSECURE "Ligação insegura devido à impressão digital inválida" +#define D_CONNECT_FAILED_TO "A ligação falhou ao" + +// xdrv_wemohue.ino +#define D_MULTICAST_DISABLED "Multicast desabilitado" +#define D_MULTICAST_REJOINED "Multicast (re)ingressou" +#define D_MULTICAST_JOIN_FAILED "Multicast falha no reingresso" +#define D_FAILED_TO_SEND_RESPONSE "Falha no envio de reposta" + +#define D_WEMO "WeMo" +#define D_WEMO_BASIC_EVENT "WeMo evento básico" +#define D_WEMO_EVENT_SERVICE "WeMo evento de serviço" +#define D_WEMO_META_SERVICE "WeMo serviço meta" +#define D_WEMO_SETUP "WeMo configuração" +#define D_RESPONSE_SENT "Rsposta enviada" + +#define D_HUE "Hue" +#define D_HUE_BRIDGE_SETUP "Hue setup" +#define D_HUE_API_NOT_IMPLEMENTED "Hue API nao implementada" +#define D_HUE_API "Hue API" +#define D_HUE_POST_ARGS "Hue POST args" +#define D_3_RESPONSE_PACKETS_SENT "3 pacotes de resposta enviados" + +// xdrv_05_domoticz.ino +#define D_DOMOTICZ_PARAMETERS "Parametros Domoticz" +#define D_DOMOTICZ_IDX "Idx" +#define D_DOMOTICZ_KEY_IDX "Chave idx" +#define D_DOMOTICZ_SWITCH_IDX "Interruptor idx" +#define D_DOMOTICZ_SENSOR_IDX "Sensor idx" + #define D_DOMOTICZ_TEMP "Temp" + #define D_DOMOTICZ_TEMP_HUM "Temp,Hum" + #define D_DOMOTICZ_TEMP_HUM_BARO "Temp,Hum,Baro" + #define D_DOMOTICZ_POWER_ENERGY "Potência,Energia" + #define D_DOMOTICZ_ILLUMINANCE "Luminâcia" + #define D_DOMOTICZ_COUNT "Contagem/PM1" + #define D_DOMOTICZ_VOLTAGE "Voltagem/PM2.5" + #define D_DOMOTICZ_CURRENT "Corrente/PM10" + #define D_DOMOTICZ_AIRQUALITY "Qualidade do Ar" +#define D_DOMOTICZ_UPDATE_TIMER "Tempo de atualização" + +// xdrv_09_timers.ino +#define D_CONFIGURE_TIMER "Configure Timer" +#define D_TIMER_PARAMETERS "Timer parameters" +#define D_TIMER_ARM "Arm" +#define D_TIMER_TIME "Time" +#define D_TIMER_DAYS "Days" +#define D_TIMER_REPEAT "Repeat" +#define D_TIMER_OUTPUT "Output" +#define D_TIMER_ACTION "Action" + +// xdrv_10_knx.ino +#define D_CONFIGURE_KNX "Configure KNX" +#define D_KNX_PARAMETERS "KNX Parameters" +#define D_KNX_GENERAL_CONFIG "General" +#define D_KNX_PHYSICAL_ADDRESS "Physical Address" +#define D_KNX_PHYSICAL_ADDRESS_NOTE "( Must be unique on the KNX network )" +#define D_KNX_ENABLE "Enable KNX" +#define D_KNX_GROUP_ADDRESS_TO_WRITE "Data to Send to Group Addresses" +#define D_ADD "Add" +#define D_DELETE "Delete" +#define D_REPLY "Reply" +#define D_KNX_GROUP_ADDRESS_TO_READ "Group Addresses to Receive Data from" +#define D_LOG_KNX "KNX: " +#define D_RECEIVED_FROM "Received from" +#define D_KNX_COMMAND_WRITE "Write" +#define D_KNX_COMMAND_READ "Read" +#define D_KNX_COMMAND_OTHER "Other" +#define D_SENT_TO "sent to" +#define D_KNX_WARNING "The group address ( 0 / 0 / 0 ) is reserved and can not be used." + +// xdrv_03_energy.ino +#define D_ENERGY_TODAY "Consumo energético de hoje" +#define D_ENERGY_YESTERDAY "Consumo energético de ontem" +#define D_ENERGY_TOTAL "Consumo total de energial" + +// xsns_05_ds18b20.ino +#define D_SENSOR_BUSY "Sensor ocupado" +#define D_SENSOR_CRC_ERROR "Erro Sensor CRC" +#define D_SENSORS_FOUND "Sensors encontrados" + +// xsns_06_dht.ino +#define D_TIMEOUT_WAITING_FOR "Fim do tempo de espera" +#define D_START_SIGNAL_LOW "Sinal de início baixo" +#define D_START_SIGNAL_HIGH "Sinal de início elevado" +#define D_PULSE "pulse" +#define D_CHECKSUM_FAILURE "Falha Checksum" + +// xsns_07_sht1x.ino +#define D_SENSOR_DID_NOT_ACK_COMMAND "Sensor não aceitou o comando ACK" +#define D_SHT1X_FOUND "SHT1X encontrado" + +// xsns_18_pms5003.ino +#define D_STANDARD_CONCENTRATION "CF-1 PM" // Standard Particle CF-1 Particle Matter +#define D_ENVIRONMENTAL_CONCENTRATION "PM" // Environmetal Particle Matter +#define D_PARTICALS_BEYOND "Partículas" + +// sonoff_template.h +#define D_SENSOR_NONE "Nenhum" +#define D_SENSOR_DHT11 "DHT11" +#define D_SENSOR_AM2301 "AM2301" +#define D_SENSOR_SI7021 "SI7021" +#define D_SENSOR_DS18X20 "DS18x20" +#define D_SENSOR_I2C_SCL "I2C SCL" +#define D_SENSOR_I2C_SDA "I2C SDA" +#define D_SENSOR_WS2812 "WS2812" +#define D_SENSOR_IRSEND "IRsend" +#define D_SENSOR_SWITCH "Interruptor" // Suffix "1" +#define D_SENSOR_BUTTON "Botão" // Suffix "1" +#define D_SENSOR_RELAY "Relé" // Suffix "1i" +#define D_SENSOR_LED "Led" // Suffix "1i" +#define D_SENSOR_PWM "PWM" // Suffix "1" +#define D_SENSOR_COUNTER "Contador" // Suffix "1" +#define D_SENSOR_IRRECV "IRrecv" +#define D_SENSOR_MHZ_RX "MHZ Rx" +#define D_SENSOR_MHZ_TX "MHZ Tx" +#define D_SENSOR_PZEM_RX "PZEM Rx" +#define D_SENSOR_PZEM_TX "PZEM Tx" +#define D_SENSOR_SAIR_RX "SAir Rx" +#define D_SENSOR_SAIR_TX "SAir Tx" +#define D_SENSOR_SPI_CS "SPI CS" +#define D_SENSOR_SPI_DC "SPI DC" +#define D_SENSOR_BACKLIGHT "Luz negra" +#define D_SENSOR_PMS5003 "PMS5003" +#define D_SENSOR_SDS0X1 "SDS0X1" +#define D_SENSOR_SBR_RX "SerBr Rx" +#define D_SENSOR_SBR_TX "SerBr Tx" +#define D_SENSOR_SR04_TRIG "SR04 Tri" +#define D_SENSOR_SR04_ECHO "SR04 Ech" + +// Units +#define D_UNIT_AMPERE "A" +#define D_UNIT_CENTIMETER "cm" +#define D_UNIT_HOUR "Hr" +#define D_UNIT_KILOOHM "kOhm" +#define D_UNIT_KILOWATTHOUR "kWh" +#define D_UNIT_LUX "lx" +#define D_UNIT_MICROGRAM_PER_CUBIC_METER "ug/m3" +#define D_UNIT_MICROMETER "um" +#define D_UNIT_MICROSECOND "us" +#define D_UNIT_MILLIAMPERE "mA" +#define D_UNIT_MILLISECOND "ms" +#define D_UNIT_MINUTE "Min" +#define D_UNIT_PARTS_PER_BILLION "ppb" +#define D_UNIT_PARTS_PER_DECILITER "ppd" +#define D_UNIT_PARTS_PER_MILLION "ppm" +#define D_UNIT_PRESSURE "hPa" +#define D_UNIT_SECOND "sec" +#define D_UNIT_SECTORS "sectors" +#define D_UNIT_VOLT "V" +#define D_UNIT_WATT "W" +#define D_UNIT_WATTHOUR "Wh" + +// Log message prefix +#define D_LOG_APPLICATION "APP: " // Application +#define D_LOG_BRIDGE "BRG: " // Bridge +#define D_LOG_CONFIG "CFG: " // Settings +#define D_LOG_COMMAND "CMD: " // Command +#define D_LOG_DEBUG "DBG: " // Debug +#define D_LOG_DHT "DHT: " // DHT sensor +#define D_LOG_DOMOTICZ "DOM: " // Domoticz +#define D_LOG_DSB "DSB: " // DS18xB20 sensor +#define D_LOG_HTTP "HTP: " // HTTP webserver +#define D_LOG_I2C "I2C: " // I2C +#define D_LOG_IRR "IRR: " // Infra Red Received +#define D_LOG_LOG "LOG: " // Logging +#define D_LOG_MODULE "MOD: " // Module +#define D_LOG_MDNS "DNS: " // mDNS +#define D_LOG_MQTT "MQT: " // MQTT +#define D_LOG_OTHER "OTH: " // Other +#define D_LOG_RESULT "RSL: " // Result +#define D_LOG_RFR "RFR: " // RF Received +#define D_LOG_SERIAL "SER: " // Serial +#define D_LOG_SHT1 "SHT: " // SHT1x sensor +#define D_LOG_UPLOAD "UPL: " // Upload +#define D_LOG_UPNP "UPP: " // UPnP +#define D_LOG_WIFI "WIF: " // Wifi + +#endif // _LANGUAGE_PT_PT_H_ diff --git a/sonoff/language/ru-RU.h b/sonoff/language/ru-RU.h new file mode 100644 index 000000000..96ad631ab --- /dev/null +++ b/sonoff/language/ru-RU.h @@ -0,0 +1,505 @@ +/* + ru-RU.h - localization for Russian - Rissia for Sonoff-Tasmota + + Copyright (C) 2018 Theo Arends / roman-vn + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifndef _LANGUAGE_RU_RU_H_ +#define _LANGUAGE_RU_RU_H_ + +/*************************** ATTENTION *******************************\ + * + * Due to memory constraints only UTF-8 is supported. + * To save code space keep text as short as possible. + * Time and Date provided by SDK can not be localized (yet). + * Use online command StateText to translate ON, OFF, HOLD and TOGGLE. + * Use online command Prefix to translate cmnd, stat and tele. + * + * Updated until v5.12.0b +\*********************************************************************/ + +//#define LANGUAGE_MODULE_NAME // Enable to display "Module Generic" (ie Spanish), Disable to display "Generic Module" (ie English) + +// HTML (ISO 639-1) Language Code +#define D_HTML_LANGUAGE "ru" + +// "2017-03-07T11:08:02" - ISO8601:2004 +#define D_YEAR_MONTH_SEPARATOR "-" +#define D_MONTH_DAY_SEPARATOR "-" +#define D_DATE_TIME_SEPARATOR "T" +#define D_HOUR_MINUTE_SEPARATOR ":" +#define D_MINUTE_SECOND_SEPARATOR ":" + +#define D_DAY3LIST "ВскПонВтрСрдЧетПятСуб" +#define D_MONTH3LIST "ЯнвФевМарАпрМайИюнИюлАвгСенОктНояДек" + +// Non JSON decimal separator +#define D_DECIMAL_SEPARATOR "," + +// Common +#define D_ADMIN "Admin" +#define D_AIR_QUALITY "Качество воздуха" +#define D_AP "AP" // Access Point +#define D_AS "как" +#define D_AUTO "АВТО" +#define D_BLINK "Мигать" +#define D_BLINKOFF "Не Мигать" +#define D_BOOT_COUNT "Количество загрузок" +#define D_BRIGHTLIGHT "Яркость" +#define D_BUTTON "Кнопка" +#define D_BY "by" // Written by me +#define D_BYTES "Байт" +#define D_CELSIUS "Цельсия" +#define D_CO2 "Углекислый газ" +#define D_CODE "код" // Button code +#define D_COLDLIGHT "Холодный" +#define D_COMMAND "Команда" +#define D_CONNECTED "Соединен" +#define D_COUNT "Подсчет" +#define D_COUNTER "Счетчик" +#define D_CURRENT "Ток" // As in Voltage and Current +#define D_DATA "Данные" +#define D_DARKLIGHT "Темный" +#define D_DEBUG "Отладка" +#define D_DISABLED "Блокирован" +#define D_DISTANCE "Distance" +#define D_DNS_SERVER "DNS Сервер" +#define D_DONE "Выполнено" +#define D_DST_TIME "DST" +#define D_ECO2 "eCO2" +#define D_EMULATION "Эмуляция" +#define D_ENABLED "Активно" +#define D_ERASE "Стирать" +#define D_ERROR "Ошибка" +#define D_FAHRENHEIT "Фаренгейт" +#define D_FAILED "Неудачно" +#define D_FALLBACK "Обратная связь" +#define D_FALLBACK_TOPIC "Топик обратной связи" +#define D_FALSE "Ложно" +#define D_FILE "Файл" +#define D_FREE_MEMORY "Свободная память" +#define D_GAS "Газ" +#define D_GATEWAY "Шлюз" +#define D_GROUP "Группа" +#define D_HOST "Хост" +#define D_HOSTNAME "Имя Хоста" +#define D_HUMIDITY "Влажность" +#define D_ILLUMINANCE "Освещенность" +#define D_IMMEDIATE "немедленно" // Button immediate +#define D_INDEX "Индекс" +#define D_INFO "Инфо" +#define D_INITIALIZED "Инициализировано" +#define D_IP_ADDRESS "IP Адрес" +#define D_LIGHT "Свет" +#define D_LWT "LWT" +#define D_MODULE "Модуль" +#define D_MQTT "MQTT" +#define D_MULTI_PRESS "многократное нажатие" +#define D_NOISE "Шум" +#define D_NONE "Нет" +#define D_OFF "Выкл" +#define D_OFFLINE "Офф-лайн" +#define D_OK "Ок" +#define D_ON "Вкл" +#define D_ONLINE "Он-лайн" +#define D_PASSWORD "Пароль" +#define D_PORT "Порт" +#define D_POWER_FACTOR "Коэффициент Мощности" +#define D_POWERUSAGE "Мощность" +#define D_PRESSURE "Давление" +#define D_PRESSUREATSEALEVEL "Давление на уровне моря" +#define D_PROGRAM_FLASH_SIZE "Размер Flash для программ" +#define D_PROGRAM_SIZE "Размер программы " +#define D_PROJECT "Проект" +#define D_RECEIVED "Получено" +#define D_RESTART "Перезапуск" +#define D_RESTARTING "Перезапуск" +#define D_RESTART_REASON "Причина перезагрузки" +#define D_RESTORE "восстановление" +#define D_RETAINED "нераспред." +#define D_RULE "Rule" +#define D_SAVE "Сохранить" +#define D_SENSOR "Датчик" +#define D_SSID "SSId" +#define D_START "Старт" +#define D_STD_TIME "STD" +#define D_STOP "Стоп" +#define D_SUBNET_MASK "Маска Подсети" +#define D_SUBSCRIBE_TO "Подписаться на" +#define D_SUCCESSFUL "Успешно" +#define D_SUNRISE "Sunrise" +#define D_SUNSET "Sunset" +#define D_TEMPERATURE "Температура" +#define D_TO "до" +#define D_TOGGLE "Переключить" +#define D_TOPIC "Топик" +#define D_TRANSMIT "Передать" +#define D_TRUE "Истина" +#define D_TVOC "TVOC" +#define D_UPGRADE "обновление" +#define D_UPLOAD "Загрузить" +#define D_UPTIME "Uptime" +#define D_USER "Пользователь" +#define D_UTC_TIME "UTC" +#define D_UV_LEVEL "УФ уровень" +#define D_VERSION "Версия" +#define D_VOLTAGE "Напряжение" +#define D_WARMLIGHT "Тепло" +#define D_WEB_SERVER "Web сервер" + +// sonoff.ino +#define D_WARNING_MINIMAL_VERSION "ПРЕДУПРЕЖДЕНИЕ Эта версия не поддерживает персистентные настройки" +#define D_LEVEL_10 "уровень 1-0" +#define D_LEVEL_01 "уровень 0-1" +#define D_SERIAL_LOGGING_DISABLED "Serial logging отключен" +#define D_SYSLOG_LOGGING_REENABLED "Syslog logging включен" + +#define D_SET_BAUDRATE_TO "Установить скорость передачи (Baudrate)" +#define D_RECEIVED_TOPIC "Полученный Топик" +#define D_DATA_SIZE "Размер данных" +#define D_ANALOG_INPUT "Аналоговый вход" + +// support.ino +#define D_OSWATCH "osWatch" +#define D_BLOCKED_LOOP "Блокирующий цикл" +#define D_WPS_FAILED_WITH_STATUS "WPS конфигурация НЕУДАЧНА со статусом" +#define D_ACTIVE_FOR_3_MINUTES "активен в течение 3 минут" +#define D_FAILED_TO_START "не удалось запустить" +#define D_PATCH_ISSUE_2186 "Проблема с исправлением 2186" +#define D_CONNECTING_TO_AP "Подключение к AP" +#define D_IN_MODE "в режиме" +#define D_CONNECT_FAILED_NO_IP_ADDRESS "Ошибка подключения, IP-адрес не получен" +#define D_CONNECT_FAILED_AP_NOT_REACHED "Ошибка соединения, AP не может быть достигнута" +#define D_CONNECT_FAILED_WRONG_PASSWORD "Ошибка соединения, неверный пароль к AP" +#define D_CONNECT_FAILED_AP_TIMEOUT "Ошибка соединения с AP по тайм-ауту" +#define D_ATTEMPTING_CONNECTION "Попытка подключения..." +#define D_CHECKING_CONNECTION "Проверка соединения..." +#define D_QUERY_DONE "Запрос выполнен. Обнаружены службы MQTT" +#define D_MQTT_SERVICE_FOUND "MQTT сервис service найдено" +#define D_FOUND_AT "найдено в" +#define D_SYSLOG_HOST_NOT_FOUND "System лог хост не найден" + +// settings.ino +#define D_SAVED_TO_FLASH_AT "Сохранено во флэш-память" +#define D_LOADED_FROM_FLASH_AT "Загружено из флэш-памяти" +#define D_USE_DEFAULTS "Использовать значение по умолчанию" +#define D_ERASED_SECTOR "Стереть сектор" + +// webserver.ino +#define D_MINIMAL_FIRMWARE_PLEASE_UPGRADE "Прошивка MINIMAL - пожалуйста обновите" +#define D_WEBSERVER_ACTIVE_ON "Веб-сервер активен" +#define D_WITH_IP_ADDRESS "с IP-адресом" +#define D_WEBSERVER_STOPPED "Веб-сервер остановлен" +#define D_FILE_NOT_FOUND "Файл не найден" +#define D_REDIRECTED "Перенаправлено на адаптивный портал" +#define D_WIFIMANAGER_SET_ACCESSPOINT_AND_STATION "Wifi менеджер устанавливает Точку Доступа и сохраняет станцию" +#define D_WIFIMANAGER_SET_ACCESSPOINT "Wifi менеджер установил Точку Доступа" +#define D_TRYING_TO_CONNECT "Попытка подключения устройства к сети" + +#define D_RESTART_IN "Перезапуск" +#define D_SECONDS "секунд" +#define D_DEVICE_WILL_RESTART "Устройство будет перезапущено через несколько секунд" +#define D_BUTTON_TOGGLE "Переключить" +#define D_CONFIGURATION "Конфигурация" +#define D_INFORMATION "Информация" +#define D_FIRMWARE_UPGRADE "Обновление прошивки" +#define D_CONSOLE "Консоль" +#define D_CONFIRM_RESTART "Подтвердить перезагрузку" + +#define D_CONFIGURE_MODULE "Конфигурация Модуля" +#define D_CONFIGURE_WIFI "Конфигурация WiFi" +#define D_CONFIGURE_MQTT "Конфигурация MQTT" +#define D_CONFIGURE_DOMOTICZ "Конфигурация Domoticz" +#define D_CONFIGURE_LOGGING "Конфигурация Logging" +#define D_CONFIGURE_OTHER "Конфигурация прочее" +#define D_CONFIRM_RESET_CONFIGURATION "Подтвердить Сброс Конфигурации" +#define D_RESET_CONFIGURATION "Сброс Конфигурации" +#define D_BACKUP_CONFIGURATION "Резервное копирование Конфигурации" +#define D_RESTORE_CONFIGURATION "Восстановление Конфигурации" +#define D_MAIN_MENU "Главное Меню" + +#define D_MODULE_PARAMETERS "Параметры модуля" +#define D_MODULE_TYPE "Тип модуля" +#define D_GPIO "GPIO" +#define D_SERIAL_IN "Serial вход" +#define D_SERIAL_OUT "Serial выход" + +#define D_WIFI_PARAMETERS "Параметры Wifi" +#define D_SCAN_FOR_WIFI_NETWORKS "Сканирование беспроводных сетей Wifi" +#define D_SCAN_DONE "Сканирование завершено" +#define D_NO_NETWORKS_FOUND "Не найдено сетей" +#define D_REFRESH_TO_SCAN_AGAIN "Обновить для повторного сканирования" +#define D_DUPLICATE_ACCESSPOINT "Дублировать Точку Доступа (AP)" +#define D_SKIPPING_LOW_QUALITY "Пропущено из-за низкого качества" +#define D_RSSI "RSSI" +#define D_WEP "WEP" +#define D_WPA_PSK "WPA PSK" +#define D_WPA2_PSK "WPA2 PSK" +#define D_AP1_SSID "AP1 SSId" +#define D_AP1_PASSWORD "AP1 Пароль" +#define D_AP2_SSID "AP2 SSId" +#define D_AP2_PASSWORD "AP2 Пароль" + +#define D_MQTT_PARAMETERS "Параметры MQTT" +#define D_CLIENT "Клиент" +#define D_FULL_TOPIC "Полный Топик" + +#define D_LOGGING_PARAMETERS "Параметры Logging" +#define D_SERIAL_LOG_LEVEL "Serial лог уровень" +#define D_WEB_LOG_LEVEL "Web лог уровень" +#define D_SYS_LOG_LEVEL "System лог уровень" +#define D_MORE_DEBUG "Дополнительная информация для отладки" +#define D_SYSLOG_HOST "System лог хост" +#define D_SYSLOG_PORT "System лог порт" +#define D_TELEMETRY_PERIOD "Период телеметрии" + +#define D_OTHER_PARAMETERS "Параметры Прочие" +#define D_WEB_ADMIN_PASSWORD "Пароль Web администратора" +#define D_MQTT_ENABLE "MQTT активен" +#define D_FRIENDLY_NAME "Дружественное Имя" +#define D_BELKIN_WEMO "Belkin WeMo" +#define D_HUE_BRIDGE "Hue Bridge" +#define D_SINGLE_DEVICE "одиночное" +#define D_MULTI_DEVICE "мульти" + +#define D_SAVE_CONFIGURATION "Сохранить конфигурацию" +#define D_CONFIGURATION_SAVED "Конфигурация сохранена " +#define D_CONFIGURATION_RESET "Конфигурация сброшена" + +#define D_PROGRAM_VERSION "Версия программы" +#define D_BUILD_DATE_AND_TIME "Дата & Время сборки" +#define D_CORE_AND_SDK_VERSION "Версия Core/SDK" +#define D_FLASH_WRITE_COUNT "Кол-во записей Flash" +#define D_MAC_ADDRESS "MAC Адрес" +#define D_MQTT_HOST "MQTT Хост" +#define D_MQTT_PORT "MQTT Порт" +#define D_MQTT_CLIENT "MQTT Клиент ID" +#define D_MQTT_USER "MQTT Пользователь" +#define D_MQTT_TOPIC "MQTT Топик" +#define D_MQTT_GROUP_TOPIC "MQTT Топик группы" +#define D_MQTT_FULL_TOPIC "MQTT Топик полный" +#define D_MDNS_DISCOVERY "mDNS Обнаружение" +#define D_MDNS_ADVERTISE "mDNS Транcляция" +#define D_ESP_CHIP_ID "ID чипа ESP" +#define D_FLASH_CHIP_ID "ID чипа Flash памяти" +#define D_FLASH_CHIP_SIZE "Размер Flash памяти" +#define D_FREE_PROGRAM_SPACE "Свободное пространство программ" + +#define D_UPGRADE_BY_WEBSERVER "Обновление через Веб-сервер" +#define D_OTA_URL "OTA Url" +#define D_START_UPGRADE "Начать обновление" +#define D_UPGRADE_BY_FILE_UPLOAD "Обновление путем загрузки файлов" +#define D_UPLOAD_STARTED "Загрузка началась" +#define D_UPGRADE_STARTED "Обновление началось" +#define D_UPLOAD_DONE "Загрузка завершена" +#define D_UPLOAD_ERR_1 "Файл не выбран" +#define D_UPLOAD_ERR_2 "Недостаточно места" +#define D_UPLOAD_ERR_3 "Magic байт не 0xE9" +#define D_UPLOAD_ERR_4 "Размер прошивки больше, чем реальный размер флеш памяти" +#define D_UPLOAD_ERR_5 "Ошибка загрузки буфера" +#define D_UPLOAD_ERR_6 "Ошибка загрузки. Включено лог уровня 3" +#define D_UPLOAD_ERR_7 "Загрузка прервана" +#define D_UPLOAD_ERR_8 "Файл неверный" +#define D_UPLOAD_ERR_9 "Слишком большой файл" +#define D_UPLOAD_ERROR_CODE "Код ошибки загрузки" + +#define D_ENTER_COMMAND "Введите команду" +#define D_ENABLE_WEBLOG_FOR_RESPONSE "Включить Веб лог уровня 2 если ожидается ответ" +#define D_NEED_USER_AND_PASSWORD "Ожидается user=&password=" + +// xdrv_00_mqtt.ino +#define D_FINGERPRINT "Проверка TLS Fingerprint..." +#define D_TLS_CONNECT_FAILED_TO "Сбой подключения TLS к" +#define D_RETRY_IN "Повторить" +#define D_VERIFIED "Проверено Fingerprint" +#define D_INSECURE "Небезопасное соединение, недействительный Fingerprint" +#define D_CONNECT_FAILED_TO "Ошибка подключения к" + +// xdrv_wemohue.ino +#define D_MULTICAST_DISABLED "Multicast отключен" +#define D_MULTICAST_REJOINED "Multicast (ре)соединился" +#define D_MULTICAST_JOIN_FAILED "Multicast ошибка соединения" +#define D_FAILED_TO_SEND_RESPONSE "Не удалось отправить ответ" + +#define D_WEMO "WeMo" +#define D_WEMO_BASIC_EVENT "WeMo основное событие" +#define D_WEMO_EVENT_SERVICE "WeMo служба событий" +#define D_WEMO_META_SERVICE "WeMo мета-сервис" +#define D_WEMO_SETUP "WeMo настройка" +#define D_RESPONSE_SENT "Ответ отправлен" + +#define D_HUE "Hue" +#define D_HUE_BRIDGE_SETUP "Hue настройка" +#define D_HUE_API_NOT_IMPLEMENTED "Hue API не реализовано" +#define D_HUE_API "Hue API" +#define D_HUE_POST_ARGS "Hue POST args" +#define D_3_RESPONSE_PACKETS_SENT "3 ответных пакета получено" + +// xdrv_05_domoticz.ino +#define D_DOMOTICZ_PARAMETERS "Domoticz parameters" +#define D_DOMOTICZ_IDX "Idx" +#define D_DOMOTICZ_KEY_IDX "Key idx" +#define D_DOMOTICZ_SWITCH_IDX "Switch idx" +#define D_DOMOTICZ_SENSOR_IDX "Sensor idx" + #define D_DOMOTICZ_TEMP "Temp" + #define D_DOMOTICZ_TEMP_HUM "Temp,Hum" + #define D_DOMOTICZ_TEMP_HUM_BARO "Temp,Hum,Baro" + #define D_DOMOTICZ_POWER_ENERGY "Power,Energy" + #define D_DOMOTICZ_ILLUMINANCE "Illuminance" + #define D_DOMOTICZ_COUNT "Count/PM1" + #define D_DOMOTICZ_VOLTAGE "Voltage/PM2,5" + #define D_DOMOTICZ_CURRENT "Current/PM10" + #define D_DOMOTICZ_AIRQUALITY "AirQuality" +#define D_DOMOTICZ_UPDATE_TIMER "Update timer" + +// xdrv_09_timers.ino +#define D_CONFIGURE_TIMER "Configure Timer" +#define D_TIMER_PARAMETERS "Timer parameters" +#define D_TIMER_ARM "Arm" +#define D_TIMER_TIME "Time" +#define D_TIMER_DAYS "Days" +#define D_TIMER_REPEAT "Repeat" +#define D_TIMER_OUTPUT "Output" +#define D_TIMER_ACTION "Action" + +// xdrv_10_knx.ino +#define D_CONFIGURE_KNX "Configure KNX" +#define D_KNX_PARAMETERS "KNX Parameters" +#define D_KNX_GENERAL_CONFIG "General" +#define D_KNX_PHYSICAL_ADDRESS "Physical Address" +#define D_KNX_PHYSICAL_ADDRESS_NOTE "( Must be unique on the KNX network )" +#define D_KNX_ENABLE "Enable KNX" +#define D_KNX_GROUP_ADDRESS_TO_WRITE "Data to Send to Group Addresses" +#define D_ADD "Add" +#define D_DELETE "Delete" +#define D_REPLY "Reply" +#define D_KNX_GROUP_ADDRESS_TO_READ "Group Addresses to Receive Data from" +#define D_LOG_KNX "KNX: " +#define D_RECEIVED_FROM "Received from" +#define D_KNX_COMMAND_WRITE "Write" +#define D_KNX_COMMAND_READ "Read" +#define D_KNX_COMMAND_OTHER "Other" +#define D_SENT_TO "sent to" +#define D_KNX_WARNING "The group address ( 0 / 0 / 0 ) is reserved and can not be used." + +// xdrv_03_energy.ino +#define D_ENERGY_TODAY "Энергия Сегодня" +#define D_ENERGY_YESTERDAY "Энергия Вчера" +#define D_ENERGY_TOTAL "Энергия Всего" + +// xsns_05_ds18b20.ino +#define D_SENSOR_BUSY "Датчик DS18x20 занят" +#define D_SENSOR_CRC_ERROR "Датчик DS18x20 - ошибка CRC" +#define D_SENSORS_FOUND "Датчик DS18x20 найден" + +// xsns_06_dht.ino +#define D_TIMEOUT_WAITING_FOR "Тайм-аут, в ожидании" +#define D_START_SIGNAL_LOW "сигнал старт низкий" +#define D_START_SIGNAL_HIGH "сигнал старт высокий" +#define D_PULSE "пульс" +#define D_CHECKSUM_FAILURE "Ошибка контрольной суммы" + +// xsns_07_sht1x.ino +#define D_SENSOR_DID_NOT_ACK_COMMAND "Датчик не получил команду ACK" +#define D_SHT1X_FOUND "SHT1X найден" + +// xsns_18_pms5003.ino +#define D_STANDARD_CONCENTRATION "CF-1 PM" // Standard Particle CF-1 Particle Matter +#define D_ENVIRONMENTAL_CONCENTRATION "PM" // Environmetal Particle Matter +#define D_PARTICALS_BEYOND "Particals" + +// sonoff_template.h +#define D_SENSOR_NONE "-нет-" +#define D_SENSOR_DHT11 "DHT11" +#define D_SENSOR_AM2301 "AM2301" +#define D_SENSOR_SI7021 "SI7021" +#define D_SENSOR_DS18X20 "DS18x20" +#define D_SENSOR_I2C_SCL "I2C SCL" +#define D_SENSOR_I2C_SDA "I2C SDA" +#define D_SENSOR_WS2812 "WS2812" +#define D_SENSOR_IRSEND "IRsend" +#define D_SENSOR_SWITCH "Свич" // Suffix "1" +#define D_SENSOR_BUTTON "Кнопка" // Suffix "1" +#define D_SENSOR_RELAY "Реле" // Suffix "1i" +#define D_SENSOR_LED "Led" // Suffix "1i" +#define D_SENSOR_PWM "PWM" // Suffix "1" +#define D_SENSOR_COUNTER "Счетчик" // Suffix "1" +#define D_SENSOR_IRRECV "IRrecv" +#define D_SENSOR_MHZ_RX "MHZ Rx" +#define D_SENSOR_MHZ_TX "MHZ Tx" +#define D_SENSOR_PZEM_RX "PZEM Rx" +#define D_SENSOR_PZEM_TX "PZEM Tx" +#define D_SENSOR_SAIR_RX "SAir Rx" +#define D_SENSOR_SAIR_TX "SAir Tx" +#define D_SENSOR_SPI_CS "SPI CS" +#define D_SENSOR_SPI_DC "SPI DC" +#define D_SENSOR_BACKLIGHT "BkLight" +#define D_SENSOR_PMS5003 "PMS5003" +#define D_SENSOR_SDS0X1 "SDS0X1" +#define D_SENSOR_SBR_RX "SerBr Rx" +#define D_SENSOR_SBR_TX "SerBr Tx" +#define D_SENSOR_SR04_TRIG "SR04 Tri" +#define D_SENSOR_SR04_ECHO "SR04 Ech" + +// Units +#define D_UNIT_AMPERE "А" +#define D_UNIT_CENTIMETER "cm" +#define D_UNIT_HOUR "Ч" +#define D_UNIT_KILOOHM "кОм" +#define D_UNIT_KILOWATTHOUR "кВт" +#define D_UNIT_LUX "лк" +#define D_UNIT_MICROGRAM_PER_CUBIC_METER "мкг/м3" +#define D_UNIT_MICROMETER "мкм" +#define D_UNIT_MICROSECOND "мкс" +#define D_UNIT_MILLIAMPERE "мА" +#define D_UNIT_MILLISECOND "мс" +#define D_UNIT_MINUTE "мин" +#define D_UNIT_PARTS_PER_BILLION "ppb" +#define D_UNIT_PARTS_PER_DECILITER "ppd" +#define D_UNIT_PARTS_PER_MILLION "ppm" +#define D_UNIT_PRESSURE "гПа" +#define D_UNIT_SECOND "сек" +#define D_UNIT_SECTORS "секторов" +#define D_UNIT_VOLT "В" +#define D_UNIT_WATT "Вт" +#define D_UNIT_WATTHOUR "ВтЧ" + +// Log message prefix +#define D_LOG_APPLICATION "APP: " // Application +#define D_LOG_BRIDGE "BRG: " // Bridge +#define D_LOG_CONFIG "CFG: " // Settings +#define D_LOG_COMMAND "CMD: " // Command +#define D_LOG_DEBUG "DBG: " // Debug +#define D_LOG_DHT "DHT: " // DHT sensor +#define D_LOG_DOMOTICZ "DOM: " // Domoticz +#define D_LOG_DSB "DSB: " // DS18xB20 sensor +#define D_LOG_HTTP "HTP: " // HTTP webserver +#define D_LOG_I2C "I2C: " // I2C +#define D_LOG_IRR "IRR: " // Infra Red Received +#define D_LOG_LOG "LOG: " // Logging +#define D_LOG_MODULE "MOD: " // Module +#define D_LOG_MDNS "DNS: " // mDNS +#define D_LOG_MQTT "MQT: " // MQTT +#define D_LOG_OTHER "OTH: " // Other +#define D_LOG_RESULT "RSL: " // Result +#define D_LOG_RFR "RFR: " // RF Received +#define D_LOG_SERIAL "SER: " // Serial +#define D_LOG_SHT1 "SHT: " // SHT1x sensor +#define D_LOG_UPLOAD "UPL: " // Upload +#define D_LOG_UPNP "UPP: " // UPnP +#define D_LOG_WIFI "WIF: " // Wifi + +#endif // _LANGUAGE_RU_RU_H_ diff --git a/sonoff/language/zh-CN.h b/sonoff/language/zh-CN.h index 76c271ee9..b90ab7b1d 100644 --- a/sonoff/language/zh-CN.h +++ b/sonoff/language/zh-CN.h @@ -28,10 +28,14 @@ * Use online command StateText to translate ON, OFF, HOLD and TOGGLE. * Use online command Prefix to translate cmnd, stat and tele. * + * Updated until v5.12.0d \*********************************************************************/ //#define LANGUAGE_MODULE_NAME // Enable to display "Module Generic" (ie Spanish), Disable to display "Generic Module" (ie English) +// HTML (ISO 639-1) Language Code +#define D_HTML_LANGUAGE "zh" + // "2017-03-07T11:08:02" - ISO8601:2004 #define D_YEAR_MONTH_SEPARATOR "-" #define D_MONTH_DAY_SEPARATOR "-" @@ -71,9 +75,11 @@ #define D_DARKLIGHT "Dark" #define D_DEBUG "调试" #define D_DISABLED "禁用" +#define D_DISTANCE "Distance" #define D_DNS_SERVER "DNS服务器" #define D_DONE "完成" #define D_DST_TIME "DST" +#define D_ECO2 "eCO2" #define D_EMULATION "设备模拟" #define D_ENABLED "启用" #define D_ERASE "擦除" @@ -124,6 +130,7 @@ #define D_RESTART_REASON "重启原因" #define D_RESTORE "恢复" #define D_RETAINED "已保留" +#define D_RULE "Rule" #define D_SAVE "保存" #define D_SENSOR "传感器" #define D_SSID "名称" @@ -133,12 +140,15 @@ #define D_SUBNET_MASK "子网掩码" #define D_SUBSCRIBE_TO "订阅" #define D_SUCCESSFUL "成功" +#define D_SUNRISE "Sunrise" +#define D_SUNSET "Sunset" #define D_TEMPERATURE "温度" #define D_TO "to" #define D_TOGGLE "切换" #define D_TOPIC "主题" #define D_TRANSMIT "发送" #define D_TRUE "True" +#define D_TVOC "TVOC" #define D_UPGRADE "升级" #define D_UPLOAD "上传" #define D_UPTIME "运行时间" @@ -162,13 +172,6 @@ #define D_DATA_SIZE "数据大小:" #define D_ANALOG_INPUT "Analog" -#define D_FINGERPRINT "验证 TLS 指纹..." -#define D_TLS_CONNECT_FAILED_TO "TLS 连接失败" -#define D_RETRY_IN "重试倒计时:" -#define D_VERIFIED "验证成功" -#define D_INSECURE "指纹无效导致连接不安全" -#define D_CONNECT_FAILED_TO "连接失败:" - // support.ino #define D_OSWATCH "osWatch" #define D_BLOCKED_LOOP "Blocked Loop" @@ -317,6 +320,14 @@ #define D_ENABLE_WEBLOG_FOR_RESPONSE "如果预期响应,则启用Weblog 2" #define D_NEED_USER_AND_PASSWORD "需要 user=<用户名>&password=<密码>" +// xdrv_00_mqtt.ino +#define D_FINGERPRINT "验证 TLS 指纹..." +#define D_TLS_CONNECT_FAILED_TO "TLS 连接失败" +#define D_RETRY_IN "重试倒计时:" +#define D_VERIFIED "验证成功" +#define D_INSECURE "指纹无效导致连接不安全" +#define D_CONNECT_FAILED_TO "连接失败:" + // xdrv_wemohue.ino #define D_MULTICAST_DISABLED "组播已禁用" #define D_MULTICAST_REJOINED "组播已(重新)加入" @@ -348,12 +359,42 @@ #define D_DOMOTICZ_TEMP_HUM_BARO "温度,湿度,气压" #define D_DOMOTICZ_POWER_ENERGY "功率,电量" #define D_DOMOTICZ_ILLUMINANCE "照度" - #define D_DOMOTICZ_COUNT "数值" - #define D_DOMOTICZ_VOLTAGE "电压" - #define D_DOMOTICZ_CURRENT "电流" + #define D_DOMOTICZ_COUNT "数值/PM1" + #define D_DOMOTICZ_VOLTAGE "电压/PM2.5" + #define D_DOMOTICZ_CURRENT "电流/PM10" #define D_DOMOTICZ_AIRQUALITY "空气质量" #define D_DOMOTICZ_UPDATE_TIMER "更新计时器" +// xdrv_09_timers.ino +#define D_CONFIGURE_TIMER "Configure Timer" +#define D_TIMER_PARAMETERS "Timer parameters" +#define D_TIMER_ARM "Arm" +#define D_TIMER_TIME "Time" +#define D_TIMER_DAYS "Days" +#define D_TIMER_REPEAT "Repeat" +#define D_TIMER_OUTPUT "Output" +#define D_TIMER_ACTION "Action" + +// xdrv_10_knx.ino +#define D_CONFIGURE_KNX "Configure KNX" +#define D_KNX_PARAMETERS "KNX Parameters" +#define D_KNX_GENERAL_CONFIG "General" +#define D_KNX_PHYSICAL_ADDRESS "Physical Address" +#define D_KNX_PHYSICAL_ADDRESS_NOTE "( Must be unique on the KNX network )" +#define D_KNX_ENABLE "Enable KNX" +#define D_KNX_GROUP_ADDRESS_TO_WRITE "Data to Send to Group Addresses" +#define D_ADD "Add" +#define D_DELETE "Delete" +#define D_REPLY "Reply" +#define D_KNX_GROUP_ADDRESS_TO_READ "Group Addresses to Receive Data from" +#define D_LOG_KNX "KNX: " +#define D_RECEIVED_FROM "Received from" +#define D_KNX_COMMAND_WRITE "Write" +#define D_KNX_COMMAND_READ "Read" +#define D_KNX_COMMAND_OTHER "Other" +#define D_SENT_TO "sent to" +#define D_KNX_WARNING "The group address ( 0 / 0 / 0 ) is reserved and can not be used." + // xdrv_03_energy.ino #define D_ENERGY_TODAY "今日用电量" #define D_ENERGY_YESTERDAY "昨日用电量" @@ -407,9 +448,15 @@ #define D_SENSOR_SPI_DC "SPI DC" #define D_SENSOR_BACKLIGHT "BkLight" #define D_SENSOR_PMS5003 "PMS5003" +#define D_SENSOR_SDS0X1 "SDS0X1" +#define D_SENSOR_SBR_RX "SerBr Rx" +#define D_SENSOR_SBR_TX "SerBr Tx" +#define D_SENSOR_SR04_TRIG "SR04 Tri" +#define D_SENSOR_SR04_ECHO "SR04 Ech" // Units #define D_UNIT_AMPERE "安" +#define D_UNIT_CENTIMETER "cm" #define D_UNIT_HOUR "时" #define D_UNIT_KILOOHM "千欧" #define D_UNIT_KILOWATTHOUR "千瓦时" @@ -420,6 +467,7 @@ #define D_UNIT_MILLIAMPERE "毫安" #define D_UNIT_MILLISECOND "毫秒" #define D_UNIT_MINUTE "分" +#define D_UNIT_PARTS_PER_BILLION "ppb" #define D_UNIT_PARTS_PER_DECILITER "每分升" #define D_UNIT_PARTS_PER_MILLION "ppm" #define D_UNIT_PRESSURE "百帕" diff --git a/sonoff/language/zh-TW.h b/sonoff/language/zh-TW.h new file mode 100644 index 000000000..b13f0ba04 --- /dev/null +++ b/sonoff/language/zh-TW.h @@ -0,0 +1,505 @@ +/* + zh-TW.h - localization for Chinese (Traditional) - Taiwan for Sonoff-Tasmota + + Copyright (C) 2018 Theo Arends (translated by dannydu) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifndef _LANGUAGE_ZH_TW_H_ +#define _LANGUAGE_ZH_TW_H_ + +/*************************** ATTENTION *******************************\ + * + * Due to memory constraints only UTF-8 is supported. + * To save code space keep text as short as possible. + * Time and Date provided by SDK can not be localized (yet). + * Use online command StateText to translate ON, OFF, HOLD and TOGGLE. + * Use online command Prefix to translate cmnd, stat and tele. + * + * Updated until v5.12.0d +\*********************************************************************/ + +//#define LANGUAGE_MODULE_NAME // Enable to display "Module Generic" (ie Spanish), Disable to display "Generic Module" (ie English) + +// HTML (ISO 639-1) Language Code +#define D_HTML_LANGUAGE "zh" + +// "2017-03-07T11:08:02" - ISO8601:2004 +#define D_YEAR_MONTH_SEPARATOR "-" +#define D_MONTH_DAY_SEPARATOR "-" +#define D_DATE_TIME_SEPARATOR "T" +#define D_HOUR_MINUTE_SEPARATOR ":" +#define D_MINUTE_SECOND_SEPARATOR ":" + +#define D_DAY3LIST "SunMonTueWedThuFriSat" +#define D_MONTH3LIST "JanFebMarAprMayJunJulAugSepOctNovDec" + +// Non JSON decimal separator +#define D_DECIMAL_SEPARATOR "." + +// Common +#define D_ADMIN "Admin" +#define D_AIR_QUALITY "空氣品質" +#define D_AP "AP" // Access Point +#define D_AS "名稱:" +#define D_AUTO "自動" +#define D_BLINK "閃爍" +#define D_BLINKOFF "閃爍關" +#define D_BOOT_COUNT "啟動次數" +#define D_BRIGHTLIGHT "亮度" +#define D_BUTTON "按鈕" +#define D_BY "by" // Written by me +#define D_BYTES "大小:" +#define D_CELSIUS "攝氏" +#define D_CO2 "二氧化碳" +#define D_CODE "代碼" // Button code +#define D_COLDLIGHT "冷" +#define D_COMMAND "命令:" +#define D_CONNECTED "已連接" +#define D_COUNT "數量:" +#define D_COUNTER "Counter" +#define D_CURRENT "電流" // As in Voltage and Current +#define D_DATA "數據:" +#define D_DARKLIGHT "Dark" +#define D_DEBUG "除錯" +#define D_DISABLED "停用" +#define D_DISTANCE "Distance" +#define D_DNS_SERVER "DNS伺服器" +#define D_DONE "完成" +#define D_DST_TIME "DST" +#define D_ECO2 "eCO2" +#define D_EMULATION "設備模擬" +#define D_ENABLED "啟用" +#define D_ERASE "刪除" +#define D_ERROR "錯誤" +#define D_FAHRENHEIT "華氏" +#define D_FAILED "失敗" +#define D_FALLBACK "Fallback" +#define D_FALLBACK_TOPIC "Fallback Topic" +#define D_FALSE "False" +#define D_FILE "文件:" +#define D_FREE_MEMORY "可用記憶體" +#define D_GAS "氣體" +#define D_GATEWAY "網關" +#define D_GROUP "組:" +#define D_HOST "主機" +#define D_HOSTNAME "主機名" +#define D_HUMIDITY "濕度" +#define D_ILLUMINANCE "照度" +#define D_IMMEDIATE "immediate" // Button immediate +#define D_INDEX "索引:" +#define D_INFO "信息" +#define D_INITIALIZED "初始化完成" +#define D_IP_ADDRESS "IP地址" +#define D_LIGHT "燈" +#define D_LWT "LWT" +#define D_MODULE "模組" +#define D_MQTT "MQTT" +#define D_MULTI_PRESS "多次按鍵" +#define D_NOISE "雜訊" +#define D_NONE "無" +#define D_OFF "關" +#define D_OFFLINE "離線" +#define D_OK "好" +#define D_ON "開" +#define D_ONLINE "在線" +#define D_PASSWORD "密碼" +#define D_PORT "端口" +#define D_POWER_FACTOR "功率因數" +#define D_POWERUSAGE "功率" +#define D_PRESSURE "氣壓" +#define D_PRESSUREATSEALEVEL "海平面氣壓" +#define D_PROGRAM_FLASH_SIZE "韌體 Flash 大小" +#define D_PROGRAM_SIZE "韌體大小" +#define D_PROJECT "項目:" +#define D_RECEIVED "已接收" +#define D_RESTART "重啟" +#define D_RESTARTING "正在重啟" +#define D_RESTART_REASON "重啟原因" +#define D_RESTORE "恢覆" +#define D_RETAINED "已保留" +#define D_RULE "Rule" +#define D_SAVE "存檔" +#define D_SENSOR "感測器" +#define D_SSID "名稱" +#define D_START "開始" +#define D_STD_TIME "STD" +#define D_STOP "停止" +#define D_SUBNET_MASK "子網遮罩" +#define D_SUBSCRIBE_TO "訂閱" +#define D_SUCCESSFUL "成功" +#define D_SUNRISE "Sunrise" +#define D_SUNSET "Sunset" +#define D_TEMPERATURE "溫度" +#define D_TO "to" +#define D_TOGGLE "切換" +#define D_TOPIC "主題" +#define D_TRANSMIT "發送" +#define D_TRUE "True" +#define D_TVOC "TVOC" +#define D_UPGRADE "升級" +#define D_UPLOAD "上傳" +#define D_UPTIME "運行時間" +#define D_USER "用戶名" +#define D_UTC_TIME "UTC" +#define D_UV_LEVEL "紫外線等級" +#define D_VERSION "版本" +#define D_VOLTAGE "電壓" +#define D_WARMLIGHT "暖" +#define D_WEB_SERVER "Web Server" + +// sonoff.ino +#define D_WARNING_MINIMAL_VERSION "警告:精簡產品不支持配置寫入保存" +#define D_LEVEL_10 "level 1-0" +#define D_LEVEL_01 "level 0-1" +#define D_SERIAL_LOGGING_DISABLED "串口日誌已禁用" +#define D_SYSLOG_LOGGING_REENABLED "Syslog 日誌已開啟" + +#define D_SET_BAUDRATE_TO "設置波特率為:" +#define D_RECEIVED_TOPIC "接收到的主題:" +#define D_DATA_SIZE "數據大小:" +#define D_ANALOG_INPUT "Analog" + +// support.ino +#define D_OSWATCH "osWatch" +#define D_BLOCKED_LOOP "Blocked Loop" +#define D_WPS_FAILED_WITH_STATUS "WPSconfig FAILED with status" +#define D_ACTIVE_FOR_3_MINUTES "active for 3 minutes" +#define D_FAILED_TO_START "未能啟動" +#define D_PATCH_ISSUE_2186 "Patch issue 2186" +#define D_CONNECTING_TO_AP "連接到 AP" +#define D_IN_MODE "模式:" +#define D_CONNECT_FAILED_NO_IP_ADDRESS "連接失敗,因為沒有獲取到IP地址" +#define D_CONNECT_FAILED_AP_NOT_REACHED "連接失敗,無法連接AP" +#define D_CONNECT_FAILED_WRONG_PASSWORD "連接失敗,AP密碼不正確" +#define D_CONNECT_FAILED_AP_TIMEOUT "連接失敗,AP超時" +#define D_ATTEMPTING_CONNECTION "嘗試連接..." +#define D_CHECKING_CONNECTION "檢查連接..." +#define D_QUERY_DONE "查詢完成。 發現MQTT服務" +#define D_MQTT_SERVICE_FOUND "發現MQTT服務:" +#define D_FOUND_AT "found at" +#define D_SYSLOG_HOST_NOT_FOUND "Syslog主機未找到" + +// settings.ino +#define D_SAVED_TO_FLASH_AT "保存到 flash:" +#define D_LOADED_FROM_FLASH_AT "從 flash 載入" +#define D_USE_DEFAULTS "使用默認設置" +#define D_ERASED_SECTOR "擦除刪除" + +// webserver.ino +#define D_MINIMAL_FIRMWARE_PLEASE_UPGRADE "固件版本過低 - 請升級" +#define D_WEBSERVER_ACTIVE_ON "Web服務器:" +#define D_WITH_IP_ADDRESS "IP地址:" +#define D_WEBSERVER_STOPPED "Web 服務器已停止" +#define D_FILE_NOT_FOUND "文件未找到" +#define D_REDIRECTED "重定向到認證頁面" +#define D_WIFIMANAGER_SET_ACCESSPOINT_AND_STATION "Wifimanager set AccessPoint and keep Station" +#define D_WIFIMANAGER_SET_ACCESSPOINT "Wifimanager 設置接入點" +#define D_TRYING_TO_CONNECT "嘗試將設備連接到網絡" + +#define D_RESTART_IN "重啟需要" +#define D_SECONDS "秒" +#define D_DEVICE_WILL_RESTART "設備將在幾分鐘內重啟" +#define D_BUTTON_TOGGLE "狀態切換" +#define D_CONFIGURATION "設置" +#define D_INFORMATION "信息" +#define D_FIRMWARE_UPGRADE "固件升級" +#define D_CONSOLE "控制台" +#define D_CONFIRM_RESTART "確認重啟" + +#define D_CONFIGURE_MODULE "模塊設置" +#define D_CONFIGURE_WIFI "WiFi設置" +#define D_CONFIGURE_MQTT "MQTT設置" +#define D_CONFIGURE_DOMOTICZ "Domoticz設置" +#define D_CONFIGURE_LOGGING "日志設置" +#define D_CONFIGURE_OTHER "其他設置" +#define D_CONFIRM_RESET_CONFIGURATION "確認重置配置" +#define D_RESET_CONFIGURATION "重置配置" +#define D_BACKUP_CONFIGURATION "備份配置" +#define D_RESTORE_CONFIGURATION "還原配置" +#define D_MAIN_MENU "主菜單" + +#define D_MODULE_PARAMETERS "模塊設置" +#define D_MODULE_TYPE "模塊類型" +#define D_GPIO "GPIO" +#define D_SERIAL_IN "串口輸入(RX)" +#define D_SERIAL_OUT "串口輸出(TX)" + +#define D_WIFI_PARAMETERS "Wifi設置" +#define D_SCAN_FOR_WIFI_NETWORKS "掃描無線網絡" +#define D_SCAN_DONE "掃描完畢" +#define D_NO_NETWORKS_FOUND "未找到任何網絡" +#define D_REFRESH_TO_SCAN_AGAIN "刷新並重試" +#define D_DUPLICATE_ACCESSPOINT "重覆AP" +#define D_SKIPPING_LOW_QUALITY "忽略弱信號網絡" +#define D_RSSI "RSSI" +#define D_WEP "WEP" +#define D_WPA_PSK "WPA PSK" +#define D_WPA2_PSK "WPA2 PSK" +#define D_AP1_SSID "AP1 名稱" +#define D_AP1_PASSWORD "AP1 密碼" +#define D_AP2_SSID "AP2 名稱" +#define D_AP2_PASSWORD "AP2 密碼" + +#define D_MQTT_PARAMETERS "MQTT設置" +#define D_CLIENT "客戶端" +#define D_FULL_TOPIC "完整主題" + +#define D_LOGGING_PARAMETERS "日志設置" +#define D_SERIAL_LOG_LEVEL "串口日志級別" +#define D_WEB_LOG_LEVEL "Web 日志級別" +#define D_SYS_LOG_LEVEL "Syslog 日志級別" +#define D_MORE_DEBUG "全部調試" +#define D_SYSLOG_HOST "Syslog 主機地址" +#define D_SYSLOG_PORT "Syslog 端口" +#define D_TELEMETRY_PERIOD "上報周期" + +#define D_OTHER_PARAMETERS "其他設置" +#define D_WEB_ADMIN_PASSWORD "WEB管理密碼" +#define D_MQTT_ENABLE "啟用MQTT" +#define D_FRIENDLY_NAME "昵稱" +#define D_BELKIN_WEMO "貝爾金 WeMo" +#define D_HUE_BRIDGE "飛利浦 Hue 網橋" +#define D_SINGLE_DEVICE "單設備" +#define D_MULTI_DEVICE "多設備" + +#define D_SAVE_CONFIGURATION "保存設置" +#define D_CONFIGURATION_SAVED "設置已保存" +#define D_CONFIGURATION_RESET "設置已重置" + +#define D_PROGRAM_VERSION "固件版本" +#define D_BUILD_DATE_AND_TIME "編譯時間" +#define D_CORE_AND_SDK_VERSION "內核版本" +#define D_FLASH_WRITE_COUNT "刷機次數" +#define D_MAC_ADDRESS "MAC地址" +#define D_MQTT_HOST "MQTT主機" +#define D_MQTT_PORT "MQTT端口" +#define D_MQTT_CLIENT "MQTT客戶端" +#define D_MQTT_USER "MQTT用戶名" +#define D_MQTT_TOPIC "MQTT 主題(Topic)" +#define D_MQTT_GROUP_TOPIC "MQTT 主題組(Group Topic)" +#define D_MQTT_FULL_TOPIC "MQTT 完整主題(Full Topic)" +#define D_MDNS_DISCOVERY "mDNS 發現" +#define D_MDNS_ADVERTISE "mDNS 廣播" +#define D_ESP_CHIP_ID "ESP芯片ID" +#define D_FLASH_CHIP_ID "Flash芯片ID" +#define D_FLASH_CHIP_SIZE "Flash大小" +#define D_FREE_PROGRAM_SPACE "空閑程序空間" + +#define D_UPGRADE_BY_WEBSERVER "通過Web升級" +#define D_OTA_URL "OTA地址" +#define D_START_UPGRADE "開始升級" +#define D_UPGRADE_BY_FILE_UPLOAD "通過文件升級" +#define D_UPLOAD_STARTED "開始上傳" +#define D_UPGRADE_STARTED "開始升級" +#define D_UPLOAD_DONE "上傳完成" +#define D_UPLOAD_ERR_1 "沒有選擇文件" +#define D_UPLOAD_ERR_2 "沒有足夠空間" +#define D_UPLOAD_ERR_3 "固件頭不是 0xE9" +#define D_UPLOAD_ERR_4 "固件太大" +#define D_UPLOAD_ERR_5 "上傳緩沖區不匹配" +#define D_UPLOAD_ERR_6 "上傳失敗。 啟用日志記錄 3" +#define D_UPLOAD_ERR_7 "上傳取消" +#define D_UPLOAD_ERR_8 "錯誤的固件" +#define D_UPLOAD_ERR_9 "固件太大" +#define D_UPLOAD_ERROR_CODE "上傳錯誤代碼" + +#define D_ENTER_COMMAND "輸入命令" +#define D_ENABLE_WEBLOG_FOR_RESPONSE "如果預期響應,則啟用Weblog 2" +#define D_NEED_USER_AND_PASSWORD "需要 user=<用戶名>&password=<密碼>" + +// xdrv_00_mqtt.ino +#define D_FINGERPRINT "驗證 TLS 指紋..." +#define D_TLS_CONNECT_FAILED_TO "TLS 連接失敗" +#define D_RETRY_IN "重試倒計時:" +#define D_VERIFIED "驗證成功" +#define D_INSECURE "指紋無效導致連接不安全" +#define D_CONNECT_FAILED_TO "連接失敗:" + +// xdrv_wemohue.ino +#define D_MULTICAST_DISABLED "組播已禁用" +#define D_MULTICAST_REJOINED "組播已(重新)加入" +#define D_MULTICAST_JOIN_FAILED "組播加入失敗" +#define D_FAILED_TO_SEND_RESPONSE "請求發送失敗" + +#define D_WEMO "WeMo" +#define D_WEMO_BASIC_EVENT "WeMo 基礎事件" +#define D_WEMO_EVENT_SERVICE "WeMo 事件服務" +#define D_WEMO_META_SERVICE "WeMo meta 服務" +#define D_WEMO_SETUP "WeMo 設置" +#define D_RESPONSE_SENT "發送請求" + +#define D_HUE "Hue" +#define D_HUE_BRIDGE_SETUP "Hue 設置" +#define D_HUE_API_NOT_IMPLEMENTED "Hue API 未實現" +#define D_HUE_API "Hue API" +#define D_HUE_POST_ARGS "Hue POST 參數" +#define D_3_RESPONSE_PACKETS_SENT "3 請求包發送" + +// xdrv_05_domoticz.ino +#define D_DOMOTICZ_PARAMETERS "Domoticz 設置" +#define D_DOMOTICZ_IDX "Idx" +#define D_DOMOTICZ_KEY_IDX "Key idx" +#define D_DOMOTICZ_SWITCH_IDX "開關 idx" +#define D_DOMOTICZ_SENSOR_IDX "傳感器 idx" + #define D_DOMOTICZ_TEMP "溫度" + #define D_DOMOTICZ_TEMP_HUM "溫度,濕度" + #define D_DOMOTICZ_TEMP_HUM_BARO "溫度,濕度,氣壓" + #define D_DOMOTICZ_POWER_ENERGY "功率,電量" + #define D_DOMOTICZ_ILLUMINANCE "照度" + #define D_DOMOTICZ_COUNT "數值/PM1" + #define D_DOMOTICZ_VOLTAGE "電壓/PM2.5" + #define D_DOMOTICZ_CURRENT "電流/PM10" + #define D_DOMOTICZ_AIRQUALITY "空氣品質" +#define D_DOMOTICZ_UPDATE_TIMER "更新計時器" + +// xdrv_09_timers.ino +#define D_CONFIGURE_TIMER "Configure Timer" +#define D_TIMER_PARAMETERS "Timer parameters" +#define D_TIMER_ARM "Arm" +#define D_TIMER_TIME "Time" +#define D_TIMER_DAYS "Days" +#define D_TIMER_REPEAT "Repeat" +#define D_TIMER_OUTPUT "Output" +#define D_TIMER_ACTION "Action" + +// xdrv_10_knx.ino +#define D_CONFIGURE_KNX "Configure KNX" +#define D_KNX_PARAMETERS "KNX Parameters" +#define D_KNX_GENERAL_CONFIG "General" +#define D_KNX_PHYSICAL_ADDRESS "Physical Address" +#define D_KNX_PHYSICAL_ADDRESS_NOTE "( Must be unique on the KNX network )" +#define D_KNX_ENABLE "Enable KNX" +#define D_KNX_GROUP_ADDRESS_TO_WRITE "Data to Send to Group Addresses" +#define D_ADD "Add" +#define D_DELETE "Delete" +#define D_REPLY "Reply" +#define D_KNX_GROUP_ADDRESS_TO_READ "Group Addresses to Receive Data from" +#define D_LOG_KNX "KNX: " +#define D_RECEIVED_FROM "Received from" +#define D_KNX_COMMAND_WRITE "Write" +#define D_KNX_COMMAND_READ "Read" +#define D_KNX_COMMAND_OTHER "Other" +#define D_SENT_TO "sent to" +#define D_KNX_WARNING "The group address ( 0 / 0 / 0 ) is reserved and can not be used." + +// xdrv_03_energy.ino +#define D_ENERGY_TODAY "今日用電量" +#define D_ENERGY_YESTERDAY "昨日用電量" +#define D_ENERGY_TOTAL "總用電量" + +// xsns_05_ds18b20.ino +#define D_SENSOR_BUSY "傳感器正忙" +#define D_SENSOR_CRC_ERROR "傳感器 CRC 校驗錯誤" +#define D_SENSORS_FOUND "發現傳感器" + +// xsns_06_dht.ino +#define D_TIMEOUT_WAITING_FOR "等待超時" +#define D_START_SIGNAL_LOW "開始低電平" +#define D_START_SIGNAL_HIGH "開始高電平" +#define D_PULSE "pulse" +#define D_CHECKSUM_FAILURE "校驗失敗" + +// xsns_07_sht1x.ino +#define D_SENSOR_DID_NOT_ACK_COMMAND "傳感器沒有確認命令" +#define D_SHT1X_FOUND "發現 SHT1X 傳感器" + +// xsns_18_pms5003.ino +#define D_STANDARD_CONCENTRATION "CF-1 PM" // Standard Particle CF-1 Particle Matter +#define D_ENVIRONMENTAL_CONCENTRATION "PM" // Environmetal Particle Matter +#define D_PARTICALS_BEYOND "顆粒物直徑大於" + +// sonoff_template.h +#define D_SENSOR_NONE "None" +#define D_SENSOR_DHT11 "DHT11" +#define D_SENSOR_AM2301 "AM2301" +#define D_SENSOR_SI7021 "SI7021" +#define D_SENSOR_DS18X20 "DS18x20" +#define D_SENSOR_I2C_SCL "I2C SCL" +#define D_SENSOR_I2C_SDA "I2C SDA" +#define D_SENSOR_WS2812 "WS2812" +#define D_SENSOR_IRSEND "IRsend" +#define D_SENSOR_SWITCH "Switch" // Suffix "1" +#define D_SENSOR_BUTTON "Button" // Suffix "1" +#define D_SENSOR_RELAY "Relay" // Suffix "1i" +#define D_SENSOR_LED "Led" // Suffix "1i" +#define D_SENSOR_PWM "PWM" // Suffix "1" +#define D_SENSOR_COUNTER "Counter" // Suffix "1" +#define D_SENSOR_IRRECV "IRrecv" +#define D_SENSOR_MHZ_RX "MHZ Rx" +#define D_SENSOR_MHZ_TX "MHZ Tx" +#define D_SENSOR_PZEM_RX "PZEM Rx" +#define D_SENSOR_PZEM_TX "PZEM Tx" +#define D_SENSOR_SAIR_RX "SAir Rx" +#define D_SENSOR_SAIR_TX "SAir Tx" +#define D_SENSOR_SPI_CS "SPI CS" +#define D_SENSOR_SPI_DC "SPI DC" +#define D_SENSOR_BACKLIGHT "BkLight" +#define D_SENSOR_PMS5003 "PMS5003" +#define D_SENSOR_SDS0X1 "SDS0X1" +#define D_SENSOR_SBR_RX "SerBr Rx" +#define D_SENSOR_SBR_TX "SerBr Tx" +#define D_SENSOR_SR04_TRIG "SR04 Tri" +#define D_SENSOR_SR04_ECHO "SR04 Ech" + +// Units +#define D_UNIT_AMPERE "安" +#define D_UNIT_CENTIMETER "cm" +#define D_UNIT_HOUR "時" +#define D_UNIT_KILOOHM "千歐" +#define D_UNIT_KILOWATTHOUR "千瓦時" +#define D_UNIT_LUX "勒克斯" +#define D_UNIT_MICROGRAM_PER_CUBIC_METER "微克/立方米" +#define D_UNIT_MICROMETER "微米" +#define D_UNIT_MICROSECOND "微秒" +#define D_UNIT_MILLIAMPERE "毫安" +#define D_UNIT_MILLISECOND "毫秒" +#define D_UNIT_MINUTE "分" +#define D_UNIT_PARTS_PER_BILLION "ppb" +#define D_UNIT_PARTS_PER_DECILITER "每分升" +#define D_UNIT_PARTS_PER_MILLION "ppm" +#define D_UNIT_PRESSURE "百帕" +#define D_UNIT_SECOND "秒" +#define D_UNIT_SECTORS "扇區" +#define D_UNIT_VOLT "伏" +#define D_UNIT_WATT "瓦" +#define D_UNIT_WATTHOUR "瓦時" + +// Log message prefix +#define D_LOG_APPLICATION "APP: " // Application +#define D_LOG_BRIDGE "BRG: " // Bridge +#define D_LOG_CONFIG "CFG: " // Settings +#define D_LOG_COMMAND "CMD: " // Command +#define D_LOG_DEBUG "DBG: " // Debug +#define D_LOG_DHT "DHT: " // DHT sensor +#define D_LOG_DOMOTICZ "DOM: " // Domoticz +#define D_LOG_DSB "DSB: " // DS18xB20 sensor +#define D_LOG_HTTP "HTP: " // HTTP webserver +#define D_LOG_I2C "I2C: " // I2C +#define D_LOG_IRR "IRR: " // Infra Red Received +#define D_LOG_LOG "LOG: " // Logging +#define D_LOG_MODULE "MOD: " // Module +#define D_LOG_MDNS "DNS: " // mDNS +#define D_LOG_MQTT "MQT: " // MQTT +#define D_LOG_OTHER "OTH: " // Other +#define D_LOG_RESULT "RSL: " // Result +#define D_LOG_RFR "RFR: " // RF Received +#define D_LOG_SERIAL "SER: " // Serial +#define D_LOG_SHT1 "SHT: " // SHT1x sensor +#define D_LOG_UPLOAD "UPL: " // Upload +#define D_LOG_UPNP "UPP: " // UPnP +#define D_LOG_WIFI "WIF: " // Wifi + +#endif // _LANGUAGE_ZH_TW_H_ diff --git a/sonoff/settings.h b/sonoff/settings.h index 4fe5f77d5..313ca3c6f 100644 --- a/sonoff/settings.h +++ b/sonoff/settings.h @@ -47,10 +47,10 @@ typedef union { // Restricted by MISRA-C Rule 18.4 bu uint32_t hass_discovery : 1; // bit 19 (v5.11.1a) uint32_t not_power_linked : 1; // bit 20 (v5.11.1f) uint32_t no_power_on_check : 1; // bit 21 (v5.11.1i) - uint32_t spare22 : 1; - uint32_t spare23 : 1; - uint32_t spare24 : 1; - uint32_t spare25 : 1; + uint32_t mqtt_serial : 1; // bit 22 (v5.12.0f) + uint32_t rules_enabled : 1; // bit 23 (v5.12.0j) + uint32_t rules_once : 1; // bit 24 (v5.12.0k) + uint32_t knx_enabled : 1; // bit 25 (v5.12.0l) KNX uint32_t spare26 : 1; uint32_t spare27 : 1; uint32_t spare28 : 1; @@ -89,6 +89,20 @@ typedef union { }; } SysBitfield2; +typedef union { + uint32_t data; + struct { + uint32_t time : 11; // bits 0 - 10 = minutes in a day + uint32_t window : 4; // bits 11 - 14 = minutes random window + uint32_t repeat : 1; // bit 15 + uint32_t days : 7; // bits 16 - 22 = week day mask + uint32_t device : 4; // bits 23 - 26 = 16 devices + uint32_t power : 2; // bits 27 - 28 = 4 power states - Off, On, Toggle, Blink or Rule + uint32_t mode : 2; // bits 29 - 30 = timer modes - 0 = Scheduler, 1 = Sunrise, 2 = Sunset + uint32_t arm : 1; // bit 31 + }; +} Timer; + struct SYSCFG { unsigned long cfg_holder; // 000 unsigned long save_flag; // 004 @@ -99,9 +113,7 @@ struct SYSCFG { int8_t timezone; // 016 char ota_url[101]; // 017 char mqtt_prefix[3][11]; // 07C - - byte free_09D[1]; // 09D - + uint8_t baudrate; // 09D byte seriallog_level; // 09E uint8_t sta_config; // 09F byte sta_active; // 0A0 @@ -116,7 +128,10 @@ struct SYSCFG { byte syslog_level; // 1AA uint8_t webserver; // 1AB byte weblog_level; // 1AC - char mqtt_fingerprint[60]; // 1AD To be freed by binary fingerprint + uint8_t mqtt_fingerprint[2][20]; // 1AD + + byte free_1D5[20]; // 1D5 Free since 5.12.0e + char mqtt_host[33]; // 1E9 uint16_t mqtt_port; // 20A char mqtt_client[33]; // 20C @@ -125,7 +140,6 @@ struct SYSCFG { char mqtt_topic[33]; // 26F char button_topic[33]; // 290 char mqtt_grptopic[33]; // 2B1 - uint8_t display_model; // 2D2 uint8_t display_mode; // 2D3 uint8_t display_refresh; // 2D4 @@ -134,27 +148,23 @@ struct SYSCFG { uint8_t display_address[8]; // 2D8 uint8_t display_dimmer; // 2E0 uint8_t display_size; // 2E1 + uint8_t free_2E2[4]; // 2E2 uint16_t pwm_frequency; // 2E6 power_t power; // 2E8 uint16_t pwm_value[MAX_PWMS]; // 2EC - int16_t altitude; // 2F6 Add since 5.8.0i uint16_t tele_period; // 2F8 uint8_t ex_power; // 2FA Not used since 5.8.0j uint8_t ledstate; // 2FB uint8_t param[PARAM8_SIZE]; // 2FC was domoticz_in_topic until 5.1.6 char state_text[4][11]; // 313 - - byte free_33F[1]; // 33F - + uint8_t energy_power_delta; // 33F uint16_t domoticz_update_timer; // 340 uint16_t pwm_range; // 342 - unsigned long domoticz_relay_idx[MAX_DOMOTICZ_IDX]; // 344 unsigned long domoticz_key_idx[MAX_DOMOTICZ_IDX]; // 354 - unsigned long energy_power_calibration; // 364 unsigned long energy_voltage_calibration; // 368 unsigned long energy_current_calibration; // 36C @@ -178,10 +188,9 @@ struct SYSCFG { uint16_t mqtt_retry; // 396 uint8_t poweronstate; // 398 uint8_t last_module; // 399 - uint16_t blinktime; // 39A uint16_t blinkcount; // 39C - uint16_t ws_pixels; // 39E Not used since 5.8.0 + uint16_t light_rotation; // 39E uint8_t ws_red; // 3A0 Not used since 5.8.0 uint8_t ws_green; // 3A1 Not used since 5.8.0 uint8_t ws_blue; // 3A2 Not used since 5.8.0 @@ -197,17 +206,14 @@ struct SYSCFG { uint16_t ws_wakeup; // 3AA Not used since 5.8.0 char friendlyname[MAX_FRIENDLYNAMES][33]; // 3AC char switch_topic[33]; // 430 - - byte free_451[2]; // 451 - + char serial_delimiter; // 451 + uint8_t sbaudrate; // 452 uint8_t sleep; // 453 uint16_t domoticz_switch_idx[MAX_DOMOTICZ_IDX]; // 454 uint16_t domoticz_sensor_idx[MAX_DOMOTICZ_SNS_IDX]; // 45C uint8_t module; // 474 - uint8_t ws_color[4][3]; // 475 uint8_t ws_width[3]; // 481 - myio my_gp; // 484 uint16_t light_pixels; // 496 uint8_t light_color[5]; // 498 @@ -220,19 +226,13 @@ struct SYSCFG { uint8_t light_speed; // 4A2 uint8_t light_scheme; // 4A3 uint8_t light_width; // 4A4 - - byte free_4A5[1]; // 4A5 - + byte knx_GA_registered; // 4A5 Number of Group Address to read uint16_t light_wakeup; // 4A6 - - byte free_4A8[1]; // 4A8 - + byte knx_CB_registered; // 4A8 Number of Group Address to write char web_password[33]; // 4A9 uint8_t switchmode[MAX_SWITCHES]; // 4CA char ntp_server[3][33]; // 4CE - byte ina219_mode; // 531 - uint16_t pulse_timer[MAX_PULSETIMERS]; // 532 byte free_542[2]; // 542 @@ -240,14 +240,29 @@ struct SYSCFG { uint32_t ip_address[4]; // 544 unsigned long energy_kWhtotal; // 554 char mqtt_fulltopic[100]; // 558 - SysBitfield2 flag2; // 5BC Add flag2 since 5.9.2 - unsigned long pulse_counter[MAX_COUNTERS]; // 5C0 uint16_t pulse_counter_type; // 5D0 uint16_t pulse_counter_debounce; // 5D2 uint8_t rf_code[17][9]; // 5D4 + byte free_66d[3]; // 66D + + Timer timer[MAX_TIMERS]; // 670 + int latitude; // 6B0 + int longitude; // 6B4 + + uint16_t knx_physsical_addr; // 6B8 (address_t is a uint16_t) + uint16_t knx_GA_addr[MAX_KNX_GA]; // 6BA (address_t is a uint16_t) x KNX_max_GA + uint16_t knx_CB_addr[MAX_KNX_CB]; // 6CE (address_t is a uint16_t) x KNX_max_CB + byte knx_GA_param[MAX_KNX_GA]; // 6E2 Type of Input (relay changed, button pressed, sensor read <-teleperiod) + byte knx_CB_param[MAX_KNX_CB]; // 6EC Type of Output (set relay, toggle relay, reply sensor value) + + byte free_6f6[266]; // 6F6 + + char rules[MAX_RULE_SIZE]; // 800 uses 512 bytes in v5.12.0m + + // A00 - FFF free locations } Settings; struct RTCMEM { @@ -291,7 +306,10 @@ struct XDRVMAILBOX { uint16_t valid; uint16_t index; uint16_t data_len; + uint16_t payload16; int16_t payload; + uint8_t grpflg; + uint8_t notused; char *topic; char *data; } XdrvMailbox; diff --git a/sonoff/settings.ino b/sonoff/settings.ino index 46f16f688..059383d72 100644 --- a/sonoff/settings.ino +++ b/sonoff/settings.ino @@ -50,6 +50,17 @@ #define MTX_ADDRESS8 0 #endif +#ifndef HOME_ASSISTANT_DISCOVERY_ENABLE +#define HOME_ASSISTANT_DISCOVERY_ENABLE 0 +#endif + +#ifndef LATITUDE +#define LATITUDE 48.858360 // [Latitude] Your location to be used with sunrise and sunset +#endif +#ifndef LONGITUDE +#define LONGITUDE 2.294442 // [Longitude] Your location to be used with sunrise and sunset +#endif + /*********************************************************************************************\ * RTC memory \*********************************************************************************************/ @@ -108,41 +119,6 @@ boolean RtcSettingsValid() return (RTC_MEM_VALID == RtcSettings.valid); } -#ifdef DEBUG_THEO -void RtcSettingsDump() -{ - #define CFG_COLS 16 - - uint16_t idx; - uint16_t maxrow; - uint16_t row; - uint16_t col; - - uint8_t *buffer = (uint8_t *) &RtcSettings; - maxrow = ((sizeof(RTCMEM)+CFG_COLS)/CFG_COLS); - - for (row = 0; row < maxrow; row++) { - idx = row * CFG_COLS; - snprintf_P(log_data, sizeof(log_data), PSTR("%03X:"), idx); - for (col = 0; col < CFG_COLS; col++) { - if (!(col%4)) { - snprintf_P(log_data, sizeof(log_data), PSTR("%s "), log_data); - } - snprintf_P(log_data, sizeof(log_data), PSTR("%s %02X"), log_data, buffer[idx + col]); - } - snprintf_P(log_data, sizeof(log_data), PSTR("%s |"), log_data); - for (col = 0; col < CFG_COLS; col++) { -// if (!(col%4)) { -// snprintf_P(log_data, sizeof(log_data), PSTR("%s "), log_data); -// } - snprintf_P(log_data, sizeof(log_data), PSTR("%s%c"), log_data, ((buffer[idx + col] > 0x20) && (buffer[idx + col] < 0x7F)) ? (char)buffer[idx + col] : ' '); - } - snprintf_P(log_data, sizeof(log_data), PSTR("%s|"), log_data); - AddLog(LOG_LEVEL_INFO); - } -} -#endif // DEBUG_THEO - /*********************************************************************************************\ * Config - Flash \*********************************************************************************************/ @@ -154,6 +130,7 @@ extern "C" { extern "C" uint32_t _SPIFFS_end; +// From libraries/EEPROM/EEPROM.cpp EEPROMClass #define SPIFFS_END ((uint32_t)&_SPIFFS_end - 0x40200000) / SPI_FLASH_SEC_SIZE // Version 3.x config @@ -180,14 +157,11 @@ void SetFlashModeDout() eboot_command_read(&ebcmd); address = ebcmd.args[0]; _buffer = new uint8_t[FLASH_SECTOR_SIZE]; - if (SPI_FLASH_RESULT_OK == spi_flash_read(address, (uint32_t*)_buffer, FLASH_SECTOR_SIZE)) { + + if (ESP.flashRead(address, (uint32_t*)_buffer, FLASH_SECTOR_SIZE)) { if (_buffer[2] != 3) { // DOUT _buffer[2] = 3; - noInterrupts(); - if (SPI_FLASH_RESULT_OK == spi_flash_erase_sector(address / FLASH_SECTOR_SIZE)) { - spi_flash_write(address, (uint32_t*)_buffer, FLASH_SECTOR_SIZE); - } - interrupts(); + if (ESP.flashEraseSector(address / FLASH_SECTOR_SIZE)) ESP.flashWrite(address, (uint32_t*)_buffer, FLASH_SECTOR_SIZE); } } delete[] _buffer; @@ -251,15 +225,11 @@ void SettingsSave(byte rotate) } } Settings.save_flag++; - noInterrupts(); - spi_flash_erase_sector(settings_location); - spi_flash_write(settings_location * SPI_FLASH_SEC_SIZE, (uint32*)&Settings, sizeof(SYSCFG)); - interrupts(); + ESP.flashEraseSector(settings_location); + ESP.flashWrite(settings_location * SPI_FLASH_SEC_SIZE, (uint32*)&Settings, sizeof(SYSCFG)); if (!stop_flash_rotate && rotate) { for (byte i = 1; i < CFG_ROTATES; i++) { - noInterrupts(); - spi_flash_erase_sector(settings_location -i); // Delete previous configurations by resetting to 0xFF - interrupts(); + ESP.flashEraseSector(settings_location -i); // Delete previous configurations by resetting to 0xFF delay(1); } } @@ -284,10 +254,8 @@ void SettingsLoad() settings_location = SETTINGS_LOCATION +1; for (byte i = 0; i < CFG_ROTATES; i++) { settings_location--; - noInterrupts(); - spi_flash_read(settings_location * SPI_FLASH_SEC_SIZE, (uint32*)&Settings, sizeof(SYSCFG)); - spi_flash_read((settings_location -1) * SPI_FLASH_SEC_SIZE, (uint32*)&_SettingsH, sizeof(SYSCFGH)); - interrupts(); + ESP.flashRead(settings_location * SPI_FLASH_SEC_SIZE, (uint32*)&Settings, sizeof(SYSCFG)); + ESP.flashRead((settings_location -1) * SPI_FLASH_SEC_SIZE, (uint32*)&_SettingsH, sizeof(SYSCFGH)); // snprintf_P(log_data, sizeof(log_data), PSTR("Cnfg: Check at %X with count %d and holder %X"), settings_location -1, _SettingsH.save_flag, _SettingsH.cfg_holder); // AddLog(LOG_LEVEL_DEBUG); @@ -302,15 +270,10 @@ void SettingsLoad() AddLog(LOG_LEVEL_DEBUG); if (Settings.cfg_holder != CFG_HOLDER) { // Auto upgrade - noInterrupts(); - spi_flash_read((SETTINGS_LOCATION_3) * SPI_FLASH_SEC_SIZE, (uint32*)&Settings, sizeof(SYSCFG)); - spi_flash_read((SETTINGS_LOCATION_3 + 1) * SPI_FLASH_SEC_SIZE, (uint32*)&_SettingsH, sizeof(SYSCFGH)); - if (Settings.save_flag < _SettingsH.save_flag) - spi_flash_read((SETTINGS_LOCATION_3 + 1) * SPI_FLASH_SEC_SIZE, (uint32*)&Settings, sizeof(SYSCFG)); - interrupts(); - if ((Settings.cfg_holder != CFG_HOLDER) || (Settings.version >= 0x04020000)) { - SettingsDefault(); - } + ESP.flashRead((SETTINGS_LOCATION_3) * SPI_FLASH_SEC_SIZE, (uint32*)&Settings, sizeof(SYSCFG)); + ESP.flashRead((SETTINGS_LOCATION_3 + 1) * SPI_FLASH_SEC_SIZE, (uint32*)&_SettingsH, sizeof(SYSCFGH)); + if (Settings.save_flag < _SettingsH.save_flag) ESP.flashRead((SETTINGS_LOCATION_3 + 1) * SPI_FLASH_SEC_SIZE, (uint32*)&Settings, sizeof(SYSCFG)); + if ((Settings.cfg_holder != CFG_HOLDER) || (Settings.version >= 0x04020000)) SettingsDefault(); } settings_hash = GetSettingsHash(); @@ -318,25 +281,33 @@ void SettingsLoad() RtcSettingsLoad(); } -void SettingsErase() +void SettingsErase(uint8_t type) { - SpiFlashOpResult result; + /* + 0 = Erase from program end until end of physical flash + 1 = Erase SDK parameter area at end of linker memory model (0x0FDxxx - 0x0FFFFF) solving possible wifi errors + */ + + bool result; uint32_t _sectorStart = (ESP.getSketchSize() / SPI_FLASH_SEC_SIZE) + 1; uint32_t _sectorEnd = ESP.getFlashChipRealSize() / SPI_FLASH_SEC_SIZE; + if (1 == type) { + _sectorStart = SETTINGS_LOCATION +2; // SDK parameter area above EEPROM area (0x0FDxxx - 0x0FFFFF) + _sectorEnd = SETTINGS_LOCATION +5; + } + boolean _serialoutput = (LOG_LEVEL_DEBUG_MORE <= seriallog_level); snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_APPLICATION D_ERASE " %d " D_UNIT_SECTORS), _sectorEnd - _sectorStart); AddLog(LOG_LEVEL_DEBUG); for (uint32_t _sector = _sectorStart; _sector < _sectorEnd; _sector++) { - noInterrupts(); - result = spi_flash_erase_sector(_sector); - interrupts(); + result = ESP.flashEraseSector(_sector); if (_serialoutput) { Serial.print(F(D_LOG_APPLICATION D_ERASED_SECTOR " ")); Serial.print(_sector); - if (SPI_FLASH_RESULT_OK == result) { + if (result) { Serial.println(F(" " D_OK)); } else { Serial.println(F(" " D_ERROR)); @@ -347,55 +318,25 @@ void SettingsErase() } } -void SettingsDump(char* parms) +// Copied from 2.4.0 as 2.3.0 is incomplete +bool SettingsEraseConfig(void) { + const size_t cfgSize = 0x4000; + size_t cfgAddr = ESP.getFlashChipSize() - cfgSize; + + for (size_t offset = 0; offset < cfgSize; offset += SPI_FLASH_SEC_SIZE) { + if (!ESP.flashEraseSector((cfgAddr + offset) / SPI_FLASH_SEC_SIZE)) { + return false; + } + } + return true; +} + +void SettingsSdkErase() { - #define CFG_COLS 16 - - uint16_t idx; - uint16_t maxrow; - uint16_t row; - uint16_t col; - char *p; - - uint8_t *buffer = (uint8_t *) &Settings; - maxrow = ((sizeof(SYSCFG)+CFG_COLS)/CFG_COLS); - - uint16_t srow = strtol(parms, &p, 16) / CFG_COLS; - uint16_t mrow = strtol(p, &p, 10); - -// snprintf_P(log_data, sizeof(log_data), PSTR("Cnfg: Parms %s, Start row %d, rows %d"), parms, srow, mrow); -// AddLog(LOG_LEVEL_DEBUG); - - if (0 == mrow) { // Default only 8 lines - mrow = 8; - } - if (srow > maxrow) { - srow = maxrow - mrow; - } - if (mrow < (maxrow - srow)) { - maxrow = srow + mrow; - } - - for (row = srow; row < maxrow; row++) { - idx = row * CFG_COLS; - snprintf_P(log_data, sizeof(log_data), PSTR("%03X:"), idx); - for (col = 0; col < CFG_COLS; col++) { - if (!(col%4)) { - snprintf_P(log_data, sizeof(log_data), PSTR("%s "), log_data); - } - snprintf_P(log_data, sizeof(log_data), PSTR("%s %02X"), log_data, buffer[idx + col]); - } - snprintf_P(log_data, sizeof(log_data), PSTR("%s |"), log_data); - for (col = 0; col < CFG_COLS; col++) { -// if (!(col%4)) { -// snprintf_P(log_data, sizeof(log_data), PSTR("%s "), log_data); -// } - snprintf_P(log_data, sizeof(log_data), PSTR("%s%c"), log_data, ((buffer[idx + col] > 0x20) && (buffer[idx + col] < 0x7F)) ? (char)buffer[idx + col] : ' '); - } - snprintf_P(log_data, sizeof(log_data), PSTR("%s|"), log_data); - AddLog(LOG_LEVEL_INFO); - delay(1); - } + WiFi.disconnect(true); // Delete SDK wifi config + SettingsErase(1); + SettingsEraseConfig(); + delay(1000); } /********************************************************************************************/ @@ -430,6 +371,7 @@ void SettingsDefaultSet2() Settings.flag.mqtt_power_retain = MQTT_POWER_RETAIN; Settings.flag.mqtt_button_retain = MQTT_BUTTON_RETAIN; Settings.flag.mqtt_switch_retain = MQTT_SWITCH_RETAIN; + Settings.flag.pwm_control = 1; Settings.flag.hass_discovery = HOME_ASSISTANT_DISCOVERY_ENABLE; Settings.flag2.emulation = EMULATION; @@ -437,6 +379,9 @@ void SettingsDefaultSet2() Settings.save_data = SAVE_DATA; Settings.timezone = APP_TIMEZONE; strlcpy(Settings.ota_url, OTA_URL, sizeof(Settings.ota_url)); + Settings.baudrate = APP_BAUDRATE / 1200; + Settings.sbaudrate = SOFT_BAUDRATE / 1200; + Settings.serial_delimiter = 0xff; Settings.seriallog_level = SERIAL_LOG_LEVEL; // Settings.sta_active = 0; @@ -452,7 +397,18 @@ void SettingsDefaultSet2() Settings.webserver = WEB_SERVER; Settings.weblog_level = WEB_LOG_LEVEL; - strlcpy(Settings.mqtt_fingerprint, MQTT_FINGERPRINT, sizeof(Settings.mqtt_fingerprint)); + char fingerprint[60]; + strlcpy(fingerprint, MQTT_FINGERPRINT1, sizeof(fingerprint)); + char *p = fingerprint; + for (byte i = 0; i < 20; i++) { + Settings.mqtt_fingerprint[0][i] = strtol(p, &p, 16); + } + strlcpy(fingerprint, MQTT_FINGERPRINT2, sizeof(fingerprint)); + p = fingerprint; + for (byte i = 0; i < 20; i++) { + Settings.mqtt_fingerprint[1][i] = strtol(p, &p, 16); + } + strlcpy(Settings.mqtt_host, MQTT_HOST, sizeof(Settings.mqtt_host)); Settings.mqtt_port = MQTT_PORT; strlcpy(Settings.mqtt_client, MQTT_CLIENT_ID, sizeof(Settings.mqtt_client)); @@ -478,6 +434,7 @@ void SettingsDefaultSet2() // Settings.domoticz_switch_idx[i] = 0; } + Settings.energy_power_delta = DEFAULT_POWER_DELTA; Settings.energy_power_calibration = HLW_PREF_PULSE; Settings.energy_voltage_calibration = HLW_UREF_PULSE; Settings.energy_current_calibration = HLW_IREF_PULSE; @@ -490,14 +447,14 @@ void SettingsDefaultSet2() // Settings.energy_max_voltage = 0; // Settings.energy_min_current = 0; // Settings.energy_max_current = 0; -// Settings.energy_max_power_limit = 0; // MaxPowerLimit +// Settings.energy_max_power_limit = 0; // MaxPowerLimit Settings.energy_max_power_limit_hold = MAX_POWER_HOLD; Settings.energy_max_power_limit_window = MAX_POWER_WINDOW; -// Settings.energy_max_power_safe_limit = 0; // MaxSafePowerLimit +// Settings.energy_max_power_safe_limit = 0; // MaxSafePowerLimit Settings.energy_max_power_safe_limit_hold = SAFE_POWER_HOLD; Settings.energy_max_power_safe_limit_window = SAFE_POWER_WINDOW; -// Settings.energy_max_energy = 0; // MaxEnergy -// Settings.energy_max_energy_start = 0; // MaxEnergyStart +// Settings.energy_max_energy = 0; // MaxEnergy +// Settings.energy_max_energy_start = 0; // MaxEnergyStart SettingsDefaultSet_3_2_4(); @@ -548,6 +505,7 @@ void SettingsDefaultSet2() // 5.8.0 Settings.light_pixels = WS2812_LEDS; +// Settings.light_rotation = 0; // 5.8.1 // Settings.altitude = 0; @@ -560,13 +518,15 @@ void SettingsDefaultSet2() // 5.10.1 SettingsDefaultSet_5_10_1(); + + Settings.latitude = (int)((double)LATITUDE * 1000000); + Settings.longitude = (int)((double)LONGITUDE * 1000000); } /********************************************************************************************/ void SettingsDefaultSet_3_2_4() { - Settings.ws_pixels = WS2812_LEDS; Settings.ws_red = 255; Settings.ws_green = 0; Settings.ws_blue = 0; @@ -594,6 +554,7 @@ void SettingsDefaultSet_3_9_3() } Settings.light_pixels = WS2812_LEDS; + Settings.light_rotation = 0; for (byte i = 0; i < MAX_PWMS; i++) { Settings.light_color[i] = 255; } @@ -707,7 +668,7 @@ void SettingsDelta() SettingsDefaultSet_3_2_4(); } if (Settings.version < 0x03020500) { // 3.2.5 - Add parameter - GetMqttClient(Settings.friendlyname[0], Settings.mqtt_client, sizeof(Settings.friendlyname[0])); + Format(Settings.friendlyname[0], Settings.mqtt_client, sizeof(Settings.friendlyname[0])); strlcpy(Settings.friendlyname[1], FRIENDLY_NAME"2", sizeof(Settings.friendlyname[1])); strlcpy(Settings.friendlyname[2], FRIENDLY_NAME"3", sizeof(Settings.friendlyname[2])); strlcpy(Settings.friendlyname[3], FRIENDLY_NAME"4", sizeof(Settings.friendlyname[3])); @@ -804,7 +765,7 @@ void SettingsDelta() } } if (!Settings.light_pixels && cfg_wsflg) { - Settings.light_pixels = Settings.ws_pixels; + Settings.light_pixels = WS2812_LEDS; Settings.light_color[0] = Settings.ws_red; Settings.light_color[1] = Settings.ws_green; Settings.light_color[2] = Settings.ws_blue; @@ -855,11 +816,47 @@ void SettingsDelta() if (Settings.version < 0x050B0107) { Settings.flag.not_power_linked = 0; } - - + if (Settings.version < 0x050C0005) { + Settings.light_rotation = 0; + Settings.energy_power_delta = DEFAULT_POWER_DELTA; + char fingerprint[60]; + memcpy(fingerprint, Settings.mqtt_fingerprint, sizeof(fingerprint)); + char *p = fingerprint; + for (byte i = 0; i < 20; i++) { + Settings.mqtt_fingerprint[0][i] = strtol(p, &p, 16); + Settings.mqtt_fingerprint[1][i] = Settings.mqtt_fingerprint[0][i]; + } + } + if (Settings.version < 0x050C0007) { + Settings.baudrate = APP_BAUDRATE / 1200; + } + if (Settings.version < 0x050C0008) { + Settings.sbaudrate = SOFT_BAUDRATE / 1200; + Settings.serial_delimiter = 0xff; + } +// if (Settings.version < 0x050C0009) { +// memset(&Settings.timer, 0x00, sizeof(Timer) * MAX_TIMERS); +// } + if (Settings.version < 0x050C000A) { + Settings.latitude = (int)((double)LATITUDE * 1000000); + Settings.longitude = (int)((double)LONGITUDE * 1000000); + } + if (Settings.version < 0x050C000B) { + memset(&Settings.rules, 0x00, sizeof(Settings.rules)); + } + if (Settings.version < 0x050C000D) { + memmove(Settings.rules, Settings.rules -256, sizeof(Settings.rules)); // move rules up by 256 bytes + memset(&Settings.timer, 0x00, sizeof(Timer) * MAX_TIMERS); // Reset timers as layout has changed from v5.12.0i + Settings.knx_GA_registered = 0; + Settings.knx_CB_registered = 0; + memset(&Settings.knx_physsical_addr, 0x00, 0x800 - 0x6b8); // Reset until 0x800 for future use + } + if (Settings.version < 0x050C000F) { + Settings.energy_kWhtoday /= 1000; + Settings.energy_kWhyesterday /= 1000; + RtcSettings.energy_kWhtoday /= 1000; + } Settings.version = VERSION; SettingsSave(1); } } - - diff --git a/sonoff/sonoff.h b/sonoff/sonoff.h index 834ba3f40..296046c85 100644 --- a/sonoff/sonoff.h +++ b/sonoff/sonoff.h @@ -43,10 +43,14 @@ typedef unsigned long power_t; // Power (Relay) type #define MAX_SWITCHES 4 // Max number of switches #define MAX_PWMS 5 // Max number of PWM channels #define MAX_COUNTERS 4 // Max number of counter sensors +#define MAX_TIMERS 16 // Max number of Timers #define MAX_PULSETIMERS 8 // Max number of supported pulse timers #define MAX_FRIENDLYNAMES 4 // Max number of Friendly names #define MAX_DOMOTICZ_IDX 4 // Max number of Domoticz device, key and switch indices #define MAX_DOMOTICZ_SNS_IDX 12 // Max number of Domoticz sensors indices +#define MAX_KNX_GA 10 // Max number of KNX Group Addresses to read that can be set +#define MAX_KNX_CB 10 // Max number of KNX Group Addresses to write that can be set +#define MAX_RULE_SIZE 512 // Max number of characters in rules #define MODULE SONOFF_BASIC // [Module] Select default model @@ -71,21 +75,23 @@ typedef unsigned long power_t; // Power (Relay) type //#define PWM_FREQ 910 // 100..1000 Hz led refresh (iTead value) #define PWM_FREQ 880 // 100..1000 Hz led refresh (BN-SZ01 value) -#define MAX_POWER_HOLD 10 // Time in SECONDS to allow max agreed power (Pow) -#define MAX_POWER_WINDOW 30 // Time in SECONDS to disable allow max agreed power (Pow) -#define SAFE_POWER_HOLD 10 // Time in SECONDS to allow max unit safe power (Pow) -#define SAFE_POWER_WINDOW 30 // Time in MINUTES to disable allow max unit safe power (Pow) -#define MAX_POWER_RETRY 5 // Retry count allowing agreed power limit overflow (Pow) +#define DEFAULT_POWER_DELTA 80 // Power change percentage +#define MAX_POWER_HOLD 10 // Time in SECONDS to allow max agreed power +#define MAX_POWER_WINDOW 30 // Time in SECONDS to disable allow max agreed power +#define SAFE_POWER_HOLD 10 // Time in SECONDS to allow max unit safe power +#define SAFE_POWER_WINDOW 30 // Time in MINUTES to disable allow max unit safe power +#define MAX_POWER_RETRY 5 // Retry count allowing agreed power limit overflow #define STATES 20 // State loops per second +#define IMMINENT_RESET_FACTOR 10 // Factor to extent button hold time for imminent Reset to default 40 seconds using KEY_HOLD_TIME of 40 #define SYSLOG_TIMER 600 // Seconds to restore syslog_level #define SERIALLOG_TIMER 600 // Seconds to disable SerialLog #define OTA_ATTEMPTS 5 // Number of times to try fetching the new firmware -#define INPUT_BUFFER_SIZE 255 // Max number of characters in (serial) command buffer +#define INPUT_BUFFER_SIZE 512 // Max number of characters in (serial and http) command buffer #define CMDSZ 24 // Max number of characters in command #define TOPSZ 100 // Max number of characters in topic string -#define LOGSZ 400 // Max number of characters in log +#define LOGSZ 512 // Max number of characters in log #define MIN_MESSZ 893 // Min number of characters in MQTT message #ifdef USE_MQTT_TLS @@ -94,10 +100,12 @@ typedef unsigned long power_t; // Power (Relay) type #define WEB_LOG_SIZE 4000 // Max number of characters in weblog #endif -#define MAX_BACKLOG 16 // Max number of commands in backlog (chk backlog_index and backlog_pointer code) +#define MAX_BACKLOG 30 // Max number of commands in backlog #define MIN_BACKLOG_DELAY 2 // Minimal backlog delay in 0.1 seconds +#define SOFT_BAUDRATE 9600 // Default software serial baudrate #define APP_BAUDRATE 115200 // Default serial baudrate +#define SERIAL_POLLING 100 // Serial receive polling in ms #define MAX_STATUS 11 // Max number of status lines /* @@ -106,6 +114,25 @@ typedef unsigned long power_t; // Power (Relay) type #define max(a,b) ((a)>(b)?(a):(b)) */ +//enum ws2812NeopixelbusFeature { NEO_RGB, NEO_GRB, NEO_BRG, NEO_RBG, NEO_3LED, NEO_RGBW, NEO_GRBW }; // Doesn't work +#define NEO_RGB 0 // Neopixel RGB leds +#define NEO_GRB 1 // Neopixel GRB leds +#define NEO_BRG 2 // Neopixel BRG leds +#define NEO_RBG 3 // Neopixel RBG leds +#define NEO_3LED 4 // Placeholder to test for 4 led types +#define NEO_RGBW 5 // Neopixel RGBW leds +#define NEO_GRBW 6 // Neopixel GRBW leds + +#define MQTT_PUBSUBCLIENT 1 // Mqtt PubSubClient library +#define MQTT_TASMOTAMQTT 2 // Mqtt TasmotaMqtt library based on esp-mqtt-arduino +#define MQTT_ESPMQTTARDUINO 3 // Mqtt esp-mqtt-arduino library by Ingo Randolf + +// Sunrise and Sunset DawnType +#define DAWN_NORMAL -0.8333 +#define DAWN_CIVIL -6.0 +#define DAWN_NAUTIC -12.0 +#define DAWN_ASTRONOMIC -18.0 + /*********************************************************************************************\ * Enumeration \*********************************************************************************************/ @@ -114,6 +141,7 @@ enum WeekInMonthOptions {Last, First, Second, Third, Fourth}; enum DayOfTheWeekOptions {Sun=1, Mon, Tue, Wed, Thu, Fri, Sat}; enum MonthNamesOptions {Jan=1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec}; enum HemisphereOptions {North, South}; +enum GetDateAndTimeOptions { DT_LOCAL, DT_UTC, DT_RESTART, DT_UPTIME }; enum LoggingLevels {LOG_LEVEL_NONE, LOG_LEVEL_ERROR, LOG_LEVEL_INFO, LOG_LEVEL_DEBUG, LOG_LEVEL_DEBUG_MORE, LOG_LEVEL_ALL}; @@ -137,13 +165,13 @@ enum SettingsParmaIndex {P_HOLD_TIME, P_MAX_POWER_RETRY, P_MAX_PARAM8}; enum DomoticzSensors {DZ_TEMP, DZ_TEMP_HUM, DZ_TEMP_HUM_BARO, DZ_POWER_ENERGY, DZ_ILLUMINANCE, DZ_COUNT, DZ_VOLTAGE, DZ_CURRENT, DZ_AIRQUALITY, DZ_MAX_SENSORS}; -enum Ws2812ClockIndex {WS_SECOND, WS_MINUTE, WS_HOUR}; -enum Ws2812Color {WS_RED, WS_GREEN, WS_BLUE}; +enum Ws2812ClockIndex { WS_SECOND, WS_MINUTE, WS_HOUR, WS_MARKER }; +enum Ws2812Color { WS_RED, WS_GREEN, WS_BLUE }; enum LightTypes {LT_BASIC, LT_PWM1, LT_PWM2, LT_PWM3, LT_PWM4, LT_PWM5, LT_PWM6, LT_PWM7, LT_NU8, LT_NU9, LT_NU10, LT_WS2812, LT_RGBW, LT_RGBWC}; enum LichtSubtypes {LST_NONE, LST_SINGLE, LST_COLDWARM, LST_RGB, LST_RGBW, LST_RGBWC}; enum LichtSchemes {LS_POWER, LS_WAKEUP, LS_CYCLEUP, LS_CYCLEDN, LS_RANDOM, LS_MAX}; -enum XsnsFunctions {FUNC_INIT, FUNC_EVERY_50_MSECOND, FUNC_EVERY_SECOND, FUNC_PREP_BEFORE_TELEPERIOD, FUNC_JSON_APPEND, FUNC_WEB_APPEND, FUNC_SAVE_BEFORE_RESTART, +enum XsnsFunctions {FUNC_INIT, FUNC_LOOP, FUNC_EVERY_50_MSECOND, FUNC_EVERY_SECOND, FUNC_PREP_BEFORE_TELEPERIOD, FUNC_JSON_APPEND, FUNC_WEB_APPEND, FUNC_SAVE_BEFORE_RESTART, FUNC_COMMAND, FUNC_MQTT_SUBSCRIBE, FUNC_MQTT_INIT, FUNC_MQTT_DATA, FUNC_SET_POWER, FUNC_SHOW_SENSOR}; const uint8_t kDefaultRfCode[9] PROGMEM = { 0x21, 0x16, 0x01, 0x0E, 0x03, 0x48, 0x2E, 0x1A, 0x00 }; diff --git a/sonoff/sonoff.ino b/sonoff/sonoff.ino index 71aeb90cb..a3f7b2866 100644 --- a/sonoff/sonoff.ino +++ b/sonoff/sonoff.ino @@ -25,25 +25,27 @@ - Select IDE Tools - Flash Size: "1M (no SPIFFS)" ====================================================*/ -#define VERSION 0x050C0000 // 5.12.0 +#define VERSION 0x050D0000 // 5.13.0 // Location specific includes #include // Arduino_Esp8266 version information (ARDUINO_ESP8266_RELEASE and ARDUINO_ESP8266_RELEASE_2_3_0) #include "sonoff.h" // Enumeration used in user_config.h #include "user_config.h" // Fixed user configurable options -#include "user_config_override.h" // Configuration overrides for user_config.h +#ifdef USE_CONFIG_OVERRIDE + #include "user_config_override.h" // Configuration overrides for user_config.h +#endif +#include "sonoff_post.h" // Configuration overrides for all previous includes #include "i18n.h" // Language support configured by user_config.h #include "sonoff_template.h" // Hardware configuration -#include "sonoff_post.h" // Configuration overrides for all previous includes -// Libraries -#include // MQTT - -// Max message size calculated by PubSubClient is (MQTT_MAX_PACKET_SIZE < 5 + 2 + strlen(topic) + plength) -#if (MQTT_MAX_PACKET_SIZE -TOPSZ -7) < MIN_MESSZ // If the max message size is too small, throw an error at compile time. See PubSubClient.cpp line 359 - #error "MQTT_MAX_PACKET_SIZE is too small in libraries/PubSubClient/src/PubSubClient.h, increase it to at least 1000" +#ifdef ARDUINO_ESP8266_RELEASE_2_4_0 +#include "lwip/init.h" +#if LWIP_VERSION_MAJOR != 1 + #error Please use stable lwIP v1.4 +#endif #endif +// Libraries #include // RTC, Energy, OSWatch #include // MQTT, Ota, WifiManager #include // MQTT, Ota @@ -54,8 +56,14 @@ #include // WifiManager, Webserver #include // WifiManager #endif // USE_WEBSERVER +#ifdef USE_ARDUINO_OTA + #include // Arduino OTA + #ifndef USE_DISCOVERY + #define USE_DISCOVERY + #endif +#endif // USE_ARDUINO_OTA #ifdef USE_DISCOVERY - #include // MQTT, Webserver + #include // MQTT, Webserver, Arduino OTA #endif // USE_DISCOVERY #ifdef USE_I2C #include // I2C support library @@ -76,7 +84,7 @@ enum TasmotaCommands { CMND_LOGHOST, CMND_LOGPORT, CMND_IPADDRESS, CMND_NTPSERVER, CMND_AP, CMND_SSID, CMND_PASSWORD, CMND_HOSTNAME, CMND_WIFICONFIG, CMND_FRIENDLYNAME, CMND_SWITCHMODE, CMND_WEBSERVER, CMND_WEBPASSWORD, CMND_WEBLOG, CMND_EMULATION, CMND_TELEPERIOD, CMND_RESTART, CMND_RESET, CMND_TIMEZONE, CMND_ALTITUDE, CMND_LEDPOWER, CMND_LEDSTATE, - CMND_CFGDUMP, CMND_I2CSCAN, CMND_EXCEPTION }; + CMND_I2CSCAN, CMND_SERIALSEND, CMND_BAUDRATE, CMND_SERIALDELIMITER }; const char kTasmotaCommands[] PROGMEM = D_CMND_BACKLOG "|" D_CMND_DELAY "|" D_CMND_POWER "|" D_CMND_STATUS "|" D_CMND_STATE "|" D_CMND_POWERONSTATE "|" D_CMND_PULSETIME "|" D_CMND_BLINKTIME "|" D_CMND_BLINKCOUNT "|" D_CMND_SENSOR "|" D_CMND_SAVEDATA "|" D_CMND_SETOPTION "|" D_CMND_TEMPERATURE_RESOLUTION "|" D_CMND_HUMIDITY_RESOLUTION "|" @@ -86,20 +94,7 @@ const char kTasmotaCommands[] PROGMEM = D_CMND_LOGHOST "|" D_CMND_LOGPORT "|" D_CMND_IPADDRESS "|" D_CMND_NTPSERVER "|" D_CMND_AP "|" D_CMND_SSID "|" D_CMND_PASSWORD "|" D_CMND_HOSTNAME "|" D_CMND_WIFICONFIG "|" D_CMND_FRIENDLYNAME "|" D_CMND_SWITCHMODE "|" D_CMND_WEBSERVER "|" D_CMND_WEBPASSWORD "|" D_CMND_WEBLOG "|" D_CMND_EMULATION "|" D_CMND_TELEPERIOD "|" D_CMND_RESTART "|" D_CMND_RESET "|" D_CMND_TIMEZONE "|" D_CMND_ALTITUDE "|" D_CMND_LEDPOWER "|" D_CMND_LEDSTATE "|" - D_CMND_CFGDUMP "|" D_CMND_I2CSCAN -#ifdef DEBUG_THEO - "|" D_CMND_EXCEPTION -#endif - ; - -enum MqttCommands { - CMND_MQTTHOST, CMND_MQTTPORT, CMND_MQTTRETRY, CMND_STATETEXT, CMND_MQTTFINGERPRINT, CMND_MQTTCLIENT, - CMND_MQTTUSER, CMND_MQTTPASSWORD, CMND_FULLTOPIC, CMND_PREFIX, CMND_GROUPTOPIC, CMND_TOPIC, - CMND_BUTTONTOPIC, CMND_SWITCHTOPIC, CMND_BUTTONRETAIN, CMND_SWITCHRETAIN, CMND_POWERRETAIN, CMND_SENSORRETAIN }; -const char kMqttCommands[] PROGMEM = - D_CMND_MQTTHOST "|" D_CMND_MQTTPORT "|" D_CMND_MQTTRETRY "|" D_CMND_STATETEXT "|" D_CMND_MQTTFINGERPRINT "|" D_CMND_MQTTCLIENT "|" - D_CMND_MQTTUSER "|" D_CMND_MQTTPASSWORD "|" D_CMND_FULLTOPIC "|" D_CMND_PREFIX "|" D_CMND_GROUPTOPIC "|" D_CMND_TOPIC "|" - D_CMND_BUTTONTOPIC "|" D_CMND_SWITCHTOPIC "|" D_CMND_BUTTONRETAIN "|" D_CMND_SWITCHRETAIN "|" D_CMND_POWERRETAIN "|" D_CMND_SENSORRETAIN ; + D_CMND_I2CSCAN "|" D_CMND_SERIALSEND "|" D_CMND_BAUDRATE "|" D_CMND_SERIALDELIMITER; const char kOptionOff[] PROGMEM = "OFF|" D_OFF "|" D_FALSE "|" D_STOP "|" D_CELSIUS ; const char kOptionOn[] PROGMEM = "ON|" D_ON "|" D_TRUE "|" D_START "|" D_FAHRENHEIT "|" D_USER ; @@ -111,22 +106,20 @@ const char kOptionBlinkOff[] PROGMEM = "BLINKOFF|" D_BLINKOFF ; int baudrate = APP_BAUDRATE; // Serial interface baud rate SerialConfig serial_config = SERIAL_8N1; // Serial interface configuration 8 data bits, No parity, 1 stop bit byte serial_in_byte; // Received byte +unsigned long serial_polling_window = 0; // Serial polling window int serial_in_byte_counter = 0; // Index in receive buffer byte dual_hex_code = 0; // Sonoff dual input flag uint16_t dual_button_code = 0; // Sonoff dual received code int16_t save_data_counter; // Counter and flag for config save to Flash -uint8_t mqtt_retry_counter = 0; // MQTT connection retry counter uint8_t fallback_topic_flag = 0; // Use Topic or FallbackTopic unsigned long state_loop_timer = 0; // State loop timer int state = 0; // State per second flag -int mqtt_connection_flag = 2; // MQTT connection messages flag int ota_state_flag = 0; // OTA state flag int ota_result = 0; // OTA result byte ota_retry_counter = OTA_ATTEMPTS; // OTA retry counter char *ota_url; // OTA url string int restart_flag = 0; // Sonoff restart flag int wifi_state_flag = WIFI_RESTART; // Wifi state flag -//int uptime = 0; // Current uptime in hours uint32_t uptime = 0; // Counting every second until 4294967295 = 130 year boolean latest_uptime_flag = true; // Signal latest uptime int tele_period = 0; // Tele period timer @@ -154,7 +147,7 @@ uint8_t interlock_mutex = 0; // Interlock power command pending #else WiFiClient EspClient; // Wifi Client #endif -PubSubClient MqttClient(EspClient); // MQTT Client + WiFiUDP PortUdp; // UDP Syslog and Alexa power_t power = 0; // Current copy of Settings.power @@ -170,7 +163,7 @@ uint8_t blinkstate = 0; // LED state uint8_t blockgpio0 = 4; // Block GPIO0 for 4 seconds after poweron to workaround Wemos D1 RTS circuit uint8_t lastbutton[MAX_KEYS] = { NOT_PRESSED, NOT_PRESSED, NOT_PRESSED, NOT_PRESSED }; // Last button states -uint8_t holdbutton[MAX_KEYS] = { 0 }; // Timer for button hold +uint16_t holdbutton[MAX_KEYS] = { 0 }; // Timer for button hold uint8_t multiwindow[MAX_KEYS] = { 0 }; // Max time between button presses to record press count uint8_t multipress[MAX_KEYS] = { 0 }; // Number of button presses within multiwindow uint8_t lastwallswitch[MAX_SWITCHES]; // Last wall switch states @@ -187,12 +180,13 @@ uint8_t i2c_flg = 0; // I2C configured uint8_t spi_flg = 0; // SPI configured uint8_t light_type = 0; // Light types bool pwm_present = false; // Any PWM channel configured with SetOption15 0 - boolean mdns_begun = false; +unsigned long features = 0UL; char my_version[33]; // Composed version string char my_hostname[33]; // Composed Wifi hostname char mqtt_client[33]; // Composed MQTT Clientname +char mqtt_topic[33]; // Composed MQTT topic char serial_in_buffer[INPUT_BUFFER_SIZE]; // Receive buffer char mqtt_data[MESSZ]; // MQTT publish buffer and web page ajax buffer char log_data[LOGSZ]; // Logging @@ -201,7 +195,7 @@ String backlog[MAX_BACKLOG]; // Command backlog /********************************************************************************************/ -void GetMqttClient(char* output, const char* input, byte size) +char* Format(char* output, const char* input, int size) { char *token; uint8_t digits = 0; @@ -217,14 +211,37 @@ void GetMqttClient(char* output, const char* input, byte size) if (token != NULL) { digits = atoi(token); if (digits) { - snprintf_P(output, size, PSTR("%s%c0%dX"), output, '%', digits); - snprintf_P(output, size, output, ESP.getChipId()); + if (strchr(token, 'd')) { + snprintf_P(output, size, PSTR("%s%c0%dd"), output, '%', digits); + snprintf_P(output, size, output, ESP.getChipId() & 0x1fff); // %04d - short chip ID in dec, like in hostname + } else { + snprintf_P(output, size, PSTR("%s%c0%dX"), output, '%', digits); + snprintf_P(output, size, output, ESP.getChipId()); // %06X - full chip ID in hex + } + } else { + if (strchr(token, 'd')) { + snprintf_P(output, size, PSTR("%s%d"), output, ESP.getChipId()); // %d - full chip ID in dec + digits = 8; + } } } } - if (!digits) { - strlcpy(output, input, size); + if (!digits) strlcpy(output, input, size); + return output; +} + +char* GetOtaUrl(char *otaurl, size_t otaurl_size) +{ + if (strstr(Settings.ota_url, "%04d") != NULL) { // OTA url contains placeholder for chip ID + snprintf(otaurl, otaurl_size, Settings.ota_url, ESP.getChipId() & 0x1fff); } + else if (strstr(Settings.ota_url, "%d") != NULL) { // OTA url contains placeholder for chip ID + snprintf_P(otaurl, otaurl_size, Settings.ota_url, ESP.getChipId()); + } + else { + snprintf(otaurl, otaurl_size, Settings.ota_url); + } + return otaurl; } void GetTopic_P(char *stopic, byte prefix, char *topic, const char* subtopic) @@ -256,17 +273,13 @@ void GetTopic_P(char *stopic, byte prefix, char *topic, const char* subtopic) } fulltopic.replace(F("#"), ""); fulltopic.replace(F("//"), "/"); - if (!fulltopic.endsWith("/")) { - fulltopic += "/"; - } + if (!fulltopic.endsWith("/")) fulltopic += "/"; snprintf_P(stopic, TOPSZ, PSTR("%s%s"), fulltopic.c_str(), romram); } char* GetStateText(byte state) { - if (state > 3) { - state = 1; - } + if (state > 3) state = 1; return Settings.state_text[state]; } @@ -301,9 +314,7 @@ void SetDevicePower(power_t rpower) power_t mask = 1; uint8_t count = 0; for (byte i = 0; i < devices_present; i++) { - if (rpower & mask) { - count++; - } + if (rpower & mask) count++; mask <<= 1; } if (count > 1) { @@ -338,447 +349,13 @@ void SetDevicePower(power_t rpower) void SetLedPower(uint8_t state) { - if (state) { - state = 1; - } + if (state) state = 1; digitalWrite(pin[GPIO_LED1], (bitRead(led_inverted, 0)) ? !state : state); } /********************************************************************************************/ -void MqttSubscribe(char *topic) -{ - snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_MQTT D_SUBSCRIBE_TO " %s"), topic); - AddLog(LOG_LEVEL_DEBUG); - MqttClient.subscribe(topic); - MqttClient.loop(); // Solve LmacRxBlk:1 messages -} - -void MqttPublishDirect(const char* topic, boolean retained) -{ - char sretained[CMDSZ]; - char slog_type[10]; - - sretained[0] = '\0'; - snprintf_P(slog_type, sizeof(slog_type), PSTR(D_LOG_RESULT)); - - if (Settings.flag.mqtt_enabled) { - if (MqttClient.publish(topic, mqtt_data, retained)) { - snprintf_P(slog_type, sizeof(slog_type), PSTR(D_LOG_MQTT)); - if (retained) { - snprintf_P(sretained, sizeof(sretained), PSTR(" (" D_RETAINED ")")); - } - } - } - - snprintf_P(log_data, sizeof(log_data), PSTR("%s%s = %s"), slog_type, (Settings.flag.mqtt_enabled) ? topic : strrchr(topic,'/')+1, mqtt_data); - if (strlen(log_data) >= (sizeof(log_data) - strlen(sretained) -1)) { - log_data[sizeof(log_data) - strlen(sretained) -5] = '\0'; - snprintf_P(log_data, sizeof(log_data), PSTR("%s ..."), log_data); - } - snprintf_P(log_data, sizeof(log_data), PSTR("%s%s"), log_data, sretained); - - AddLog(LOG_LEVEL_INFO); - if (Settings.ledstate &0x04) { - blinks++; - } -} - -void MqttPublish(const char* topic, boolean retained) -{ - char *me; - - if (!strcmp(Settings.mqtt_prefix[0],Settings.mqtt_prefix[1])) { - me = strstr(topic,Settings.mqtt_prefix[0]); - if (me == topic) { - mqtt_cmnd_publish += 8; - } - } - MqttPublishDirect(topic, retained); -} - -void MqttPublish(const char* topic) -{ - MqttPublish(topic, false); -} - -void MqttPublishPrefixTopic_P(uint8_t prefix, const char* subtopic, boolean retained) -{ -/* prefix 0 = cmnd using subtopic - * prefix 1 = stat using subtopic - * prefix 2 = tele using subtopic - * prefix 4 = cmnd using subtopic or RESULT - * prefix 5 = stat using subtopic or RESULT - * prefix 6 = tele using subtopic or RESULT - */ - char romram[33]; - char stopic[TOPSZ]; - - snprintf_P(romram, sizeof(romram), ((prefix > 3) && !Settings.flag.mqtt_response) ? S_RSLT_RESULT : subtopic); - for (byte i = 0; i < strlen(romram); i++) { - romram[i] = toupper(romram[i]); - } - prefix &= 3; - GetTopic_P(stopic, prefix, Settings.mqtt_topic, romram); - MqttPublish(stopic, retained); -} - -void MqttPublishPrefixTopic_P(uint8_t prefix, const char* subtopic) -{ - MqttPublishPrefixTopic_P(prefix, subtopic, false); -} - -void MqttPublishPowerState(byte device) -{ - char stopic[TOPSZ]; - char scommand[33]; - - if ((device < 1) || (device > devices_present)) { - device = 1; - } - GetPowerDevice(scommand, device, sizeof(scommand)); - GetTopic_P(stopic, STAT, Settings.mqtt_topic, (Settings.flag.mqtt_response) ? scommand : S_RSLT_RESULT); - snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, scommand, GetStateText(bitRead(power, device -1))); - MqttPublish(stopic); - - GetTopic_P(stopic, STAT, Settings.mqtt_topic, scommand); - snprintf_P(mqtt_data, sizeof(mqtt_data), GetStateText(bitRead(power, device -1))); - MqttPublish(stopic, Settings.flag.mqtt_power_retain); -} - -void MqttPublishPowerBlinkState(byte device) -{ - char scommand[33]; - - if ((device < 1) || (device > devices_present)) { - device = 1; - } - snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"%s\":\"" D_JSON_BLINK " %s\"}"), - GetPowerDevice(scommand, device, sizeof(scommand)), GetStateText(bitRead(blink_mask, device -1))); - - MqttPublishPrefixTopic_P(RESULT_OR_STAT, S_RSLT_POWER); -} - -void MqttConnected() -{ - char stopic[TOPSZ]; - - if (Settings.flag.mqtt_enabled) { - - // Satisfy iobroker (#299) - mqtt_data[0] = '\0'; - MqttPublishPrefixTopic_P(CMND, S_RSLT_POWER); - - GetTopic_P(stopic, CMND, Settings.mqtt_topic, PSTR("#")); - MqttSubscribe(stopic); - if (strstr(Settings.mqtt_fulltopic, MQTT_TOKEN_TOPIC) != NULL) { - GetTopic_P(stopic, CMND, Settings.mqtt_grptopic, PSTR("#")); - MqttSubscribe(stopic); - fallback_topic_flag = 1; - GetTopic_P(stopic, CMND, mqtt_client, PSTR("#")); - fallback_topic_flag = 0; - MqttSubscribe(stopic); - } - - XdrvCall(FUNC_MQTT_SUBSCRIBE); - } - - if (mqtt_connection_flag) { - snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_CMND_MODULE "\":\"%s\",\"" D_JSON_VERSION "\":\"%s\",\"" D_JSON_FALLBACKTOPIC "\":\"%s\",\"" D_CMND_GROUPTOPIC "\":\"%s\"}"), - my_module.name, my_version, mqtt_client, Settings.mqtt_grptopic); - MqttPublishPrefixTopic_P(TELE, PSTR(D_RSLT_INFO "1")); -#ifdef USE_WEBSERVER - if (Settings.webserver) { - snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_JSON_WEBSERVER_MODE "\":\"%s\",\"" D_CMND_HOSTNAME "\":\"%s\",\"" D_CMND_IPADDRESS "\":\"%s\"}"), - (2 == Settings.webserver) ? D_ADMIN : D_USER, my_hostname, WiFi.localIP().toString().c_str()); - MqttPublishPrefixTopic_P(TELE, PSTR(D_RSLT_INFO "2")); - } -#endif // USE_WEBSERVER - snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_JSON_RESTARTREASON "\":\"%s\"}"), - (GetResetReason() == "Exception") ? ESP.getResetInfo().c_str() : GetResetReason().c_str()); - MqttPublishPrefixTopic_P(TELE, PSTR(D_RSLT_INFO "3")); - if (Settings.tele_period) { - tele_period = Settings.tele_period -9; - } - status_update_timer = 2; - - XdrvCall(FUNC_MQTT_INIT); - } - mqtt_connection_flag = 0; -} - -void MqttReconnect() -{ - char stopic[TOPSZ]; - - mqtt_retry_counter = Settings.mqtt_retry; - - if (!Settings.flag.mqtt_enabled) { - MqttConnected(); - return; - } -#ifdef USE_EMULATION - UdpDisconnect(); -#endif // USE_EMULATION - if (mqtt_connection_flag > 1) { -#ifdef USE_MQTT_TLS - AddLog_P(LOG_LEVEL_INFO, S_LOG_MQTT, PSTR(D_FINGERPRINT)); - if (!EspClient.connect(Settings.mqtt_host, Settings.mqtt_port)) { - snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_MQTT D_TLS_CONNECT_FAILED_TO " %s:%d. " D_RETRY_IN " %d " D_UNIT_SECOND), - Settings.mqtt_host, Settings.mqtt_port, mqtt_retry_counter); - AddLog(LOG_LEVEL_DEBUG); - return; - } - if (EspClient.verify(Settings.mqtt_fingerprint, Settings.mqtt_host)) { - AddLog_P(LOG_LEVEL_INFO, S_LOG_MQTT, PSTR(D_VERIFIED)); - } else { - AddLog_P(LOG_LEVEL_DEBUG, S_LOG_MQTT, PSTR(D_INSECURE)); - } - EspClient.stop(); - yield(); -#endif // USE_MQTT_TLS - MqttClient.setCallback(MqttDataCallback); - mqtt_connection_flag = 1; - mqtt_retry_counter = 1; - return; - } - - AddLog_P(LOG_LEVEL_INFO, S_LOG_MQTT, PSTR(D_ATTEMPTING_CONNECTION)); -#ifndef USE_MQTT_TLS -#ifdef USE_DISCOVERY -#ifdef MQTT_HOST_DISCOVERY - if (!strlen(Settings.mqtt_host)) { - MdnsDiscoverMqttServer(); - } -#endif // MQTT_HOST_DISCOVERY -#endif // USE_DISCOVERY -#endif // USE_MQTT_TLS - MqttClient.setServer(Settings.mqtt_host, Settings.mqtt_port); - - GetTopic_P(stopic, TELE, Settings.mqtt_topic, S_LWT); - snprintf_P(mqtt_data, sizeof(mqtt_data), S_OFFLINE); - - char *mqtt_user = NULL; - char *mqtt_pwd = NULL; - if (strlen(Settings.mqtt_user) > 0) { - mqtt_user = Settings.mqtt_user; - } - if (strlen(Settings.mqtt_pwd) > 0) { - mqtt_pwd = Settings.mqtt_pwd; - } - if (MqttClient.connect(mqtt_client, mqtt_user, mqtt_pwd, stopic, 1, true, mqtt_data)) { - AddLog_P(LOG_LEVEL_INFO, S_LOG_MQTT, PSTR(D_CONNECTED)); - mqtt_retry_counter = 0; - snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR(D_ONLINE)); - MqttPublish(stopic, true); - MqttConnected(); - } else { - snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_MQTT D_CONNECT_FAILED_TO " %s:%d, rc %d. " D_RETRY_IN " %d " D_UNIT_SECOND), - Settings.mqtt_host, Settings.mqtt_port, MqttClient.state(), mqtt_retry_counter); //status codes are documented here http://pubsubclient.knolleary.net/api.html#state - AddLog(LOG_LEVEL_INFO); - } -} - -/********************************************************************************************/ - -boolean MqttCommand(boolean grpflg, char *type, uint16_t index, char *dataBuf, uint16_t data_len, int16_t payload, uint16_t payload16) -{ - char command [CMDSZ]; - boolean serviced = true; - char stemp1[TOPSZ]; - char scommand[CMDSZ]; - uint16_t i; - - int command_code = GetCommandCode(command, sizeof(command), type, kMqttCommands); - if (CMND_MQTTHOST == command_code) { - if ((data_len > 0) && (data_len < sizeof(Settings.mqtt_host))) { - strlcpy(Settings.mqtt_host, (!strcmp(dataBuf,"0")) ? "" : (1 == payload) ? MQTT_HOST : dataBuf, sizeof(Settings.mqtt_host)); - restart_flag = 2; - } - snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, Settings.mqtt_host); - } - else if (CMND_MQTTPORT == command_code) { - if (payload16 > 0) { - Settings.mqtt_port = (1 == payload16) ? MQTT_PORT : payload16; - restart_flag = 2; - } - snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE, command, Settings.mqtt_port); - } - else if (CMND_MQTTRETRY == command_code) { - if ((payload >= MQTT_RETRY_SECS) && (payload < 32001)) { - Settings.mqtt_retry = payload; - mqtt_retry_counter = Settings.mqtt_retry; - } - snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE, command, Settings.mqtt_retry); - } - else if ((CMND_STATETEXT == command_code) && (index > 0) && (index <= 4)) { - if ((data_len > 0) && (data_len < sizeof(Settings.state_text[0]))) { - for(i = 0; i <= data_len; i++) { - if (dataBuf[i] == ' ') { - dataBuf[i] = '_'; - } - } - strlcpy(Settings.state_text[index -1], dataBuf, sizeof(Settings.state_text[0])); - } - snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_SVALUE, command, index, GetStateText(index -1)); - } -#ifdef USE_MQTT_TLS - else if (CMND_MQTTFINGERPRINT == command_code) { - if ((data_len > 0) && (data_len < sizeof(Settings.mqtt_fingerprint))) { - strlcpy(Settings.mqtt_fingerprint, (!strcmp(dataBuf,"0")) ? "" : (1 == payload) ? MQTT_FINGERPRINT : dataBuf, sizeof(Settings.mqtt_fingerprint)); - restart_flag = 2; - } - snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, Settings.mqtt_fingerprint); - } -#endif - else if ((CMND_MQTTCLIENT == command_code) && !grpflg) { - if ((data_len > 0) && (data_len < sizeof(Settings.mqtt_client))) { - strlcpy(Settings.mqtt_client, (1 == payload) ? MQTT_CLIENT_ID : dataBuf, sizeof(Settings.mqtt_client)); - restart_flag = 2; - } - snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, Settings.mqtt_client); - } - else if (CMND_MQTTUSER == command_code) { - if ((data_len > 0) && (data_len < sizeof(Settings.mqtt_user))) { - strlcpy(Settings.mqtt_user, (!strcmp(dataBuf,"0")) ? "" : (1 == payload) ? MQTT_USER : dataBuf, sizeof(Settings.mqtt_user)); - restart_flag = 2; - } - snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, Settings.mqtt_user); - } - else if (CMND_MQTTPASSWORD == command_code) { - if ((data_len > 0) && (data_len < sizeof(Settings.mqtt_pwd))) { - strlcpy(Settings.mqtt_pwd, (!strcmp(dataBuf,"0")) ? "" : (1 == payload) ? MQTT_PASS : dataBuf, sizeof(Settings.mqtt_pwd)); - restart_flag = 2; - } - snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, Settings.mqtt_pwd); - } - else if (CMND_FULLTOPIC == command_code) { - if ((data_len > 0) && (data_len < sizeof(Settings.mqtt_fulltopic))) { - MakeValidMqtt(1, dataBuf); - if (!strcmp(dataBuf, mqtt_client)) { - payload = 1; - } - strlcpy(stemp1, (1 == payload) ? MQTT_FULLTOPIC : dataBuf, sizeof(stemp1)); - if (strcmp(stemp1, Settings.mqtt_fulltopic)) { - snprintf_P(mqtt_data, sizeof(mqtt_data), (Settings.flag.mqtt_offline) ? S_OFFLINE : ""); - MqttPublishPrefixTopic_P(TELE, PSTR(D_LWT), true); // Offline or remove previous retained topic - strlcpy(Settings.mqtt_fulltopic, stemp1, sizeof(Settings.mqtt_fulltopic)); - restart_flag = 2; - } - } - snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, Settings.mqtt_fulltopic); - } - else if ((CMND_PREFIX == command_code) && (index > 0) && (index <= 3)) { - if ((data_len > 0) && (data_len < sizeof(Settings.mqtt_prefix[0]))) { - MakeValidMqtt(0, dataBuf); - strlcpy(Settings.mqtt_prefix[index -1], (1 == payload) ? (1==index)?SUB_PREFIX:(2==index)?PUB_PREFIX:PUB_PREFIX2 : dataBuf, sizeof(Settings.mqtt_prefix[0])); -// if (Settings.mqtt_prefix[index -1][strlen(Settings.mqtt_prefix[index -1])] == '/') Settings.mqtt_prefix[index -1][strlen(Settings.mqtt_prefix[index -1])] = 0; - restart_flag = 2; - } - snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_SVALUE, command, index, Settings.mqtt_prefix[index -1]); - } - else if (CMND_GROUPTOPIC == command_code) { - if ((data_len > 0) && (data_len < sizeof(Settings.mqtt_grptopic))) { - MakeValidMqtt(0, dataBuf); - if (!strcmp(dataBuf, mqtt_client)) { - payload = 1; - } - strlcpy(Settings.mqtt_grptopic, (1 == payload) ? MQTT_GRPTOPIC : dataBuf, sizeof(Settings.mqtt_grptopic)); - restart_flag = 2; - } - snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, Settings.mqtt_grptopic); - } - else if ((CMND_TOPIC == command_code) && !grpflg) { - if ((data_len > 0) && (data_len < sizeof(Settings.mqtt_topic))) { - MakeValidMqtt(0, dataBuf); - if (!strcmp(dataBuf, mqtt_client)) { - payload = 1; - } - strlcpy(stemp1, (1 == payload) ? MQTT_TOPIC : dataBuf, sizeof(stemp1)); - if (strcmp(stemp1, Settings.mqtt_topic)) { - snprintf_P(mqtt_data, sizeof(mqtt_data), (Settings.flag.mqtt_offline) ? S_OFFLINE : ""); - MqttPublishPrefixTopic_P(TELE, PSTR(D_LWT), true); // Offline or remove previous retained topic - strlcpy(Settings.mqtt_topic, stemp1, sizeof(Settings.mqtt_topic)); - restart_flag = 2; - } - } - snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, Settings.mqtt_topic); - } - else if ((CMND_BUTTONTOPIC == command_code) && !grpflg) { - if ((data_len > 0) && (data_len < sizeof(Settings.button_topic))) { - MakeValidMqtt(0, dataBuf); - if (!strcmp(dataBuf, mqtt_client)) { - payload = 1; - } - strlcpy(Settings.button_topic, (!strcmp(dataBuf,"0")) ? "" : (1 == payload) ? Settings.mqtt_topic : dataBuf, sizeof(Settings.button_topic)); - } - snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, Settings.button_topic); - } - else if (CMND_SWITCHTOPIC == command_code) { - if ((data_len > 0) && (data_len < sizeof(Settings.switch_topic))) { - MakeValidMqtt(0, dataBuf); - if (!strcmp(dataBuf, mqtt_client)) { - payload = 1; - } - strlcpy(Settings.switch_topic, (!strcmp(dataBuf,"0")) ? "" : (1 == payload) ? Settings.mqtt_topic : dataBuf, sizeof(Settings.switch_topic)); - } - snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, Settings.switch_topic); - } - else if (CMND_BUTTONRETAIN == command_code) { - if ((payload >= 0) && (payload <= 1)) { - strlcpy(Settings.button_topic, Settings.mqtt_topic, sizeof(Settings.button_topic)); - if (!payload) { - for(i = 1; i <= MAX_KEYS; i++) { - send_button_power(0, i, 9); // Clear MQTT retain in broker - } - } - Settings.flag.mqtt_button_retain = payload; - } - snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, GetStateText(Settings.flag.mqtt_button_retain)); - } - else if (CMND_SWITCHRETAIN == command_code) { - if ((payload >= 0) && (payload <= 1)) { - strlcpy(Settings.button_topic, Settings.mqtt_topic, sizeof(Settings.button_topic)); - if (!payload) { - for(i = 1; i <= MAX_SWITCHES; i++) { - send_button_power(1, i, 9); // Clear MQTT retain in broker - } - } - Settings.flag.mqtt_switch_retain = payload; - } - snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, GetStateText(Settings.flag.mqtt_switch_retain)); - } - else if (CMND_POWERRETAIN == command_code) { - if ((payload >= 0) && (payload <= 1)) { - if (!payload) { - for(i = 1; i <= devices_present; i++) { // Clear MQTT retain in broker - GetTopic_P(stemp1, STAT, Settings.mqtt_topic, GetPowerDevice(scommand, i, sizeof(scommand))); - mqtt_data[0] = '\0'; - MqttPublish(stemp1, Settings.flag.mqtt_power_retain); - } - } - Settings.flag.mqtt_power_retain = payload; - } - snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, GetStateText(Settings.flag.mqtt_power_retain)); - } - else if (CMND_SENSORRETAIN == command_code) { - if ((payload >= 0) && (payload <= 1)) { - if (!payload) { - mqtt_data[0] = '\0'; - MqttPublishPrefixTopic_P(TELE, PSTR(D_RSLT_SENSOR), Settings.flag.mqtt_sensor_retain); - MqttPublishPrefixTopic_P(TELE, PSTR(D_RSLT_ENERGY), Settings.flag.mqtt_sensor_retain); - } - Settings.flag.mqtt_sensor_retain = payload; - } - snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, GetStateText(Settings.flag.mqtt_sensor_retain)); - } - else serviced = false; - return serviced; -} - -/********************************************************************************************/ - -void MqttDataCallback(char* topic, byte* data, unsigned int data_len) +void MqttDataHandler(char* topic, byte* data, unsigned int data_len) { char *str; @@ -803,16 +380,14 @@ void MqttDataCallback(char* topic, byte* data, unsigned int data_len) byte ptype = 0; byte jsflg = 0; byte lines = 1; + uint8_t grpflg = 0; uint16_t i = 0; - uint16_t grpflg = 0; uint16_t index; uint32_t address; strncpy(topicBuf, topic, sizeof(topicBuf)); for (i = 0; i < data_len; i++) { - if (!isspace(data[i])) { - break; - } + if (!isspace(data[i])) break; } data_len -= i; memcpy(dataBuf, data +i, sizeof(dataBuf)); @@ -823,9 +398,7 @@ void MqttDataCallback(char* topic, byte* data, unsigned int data_len) AddLog(LOG_LEVEL_DEBUG_MORE); // if (LOG_LEVEL_DEBUG_MORE <= seriallog_level) Serial.println(dataBuf); - if (XdrvMqttData(topicBuf, sizeof(topicBuf), dataBuf, sizeof(dataBuf))) { - return; - } + if (XdrvMqttData(topicBuf, sizeof(topicBuf), dataBuf, sizeof(dataBuf))) return; grpflg = (strstr(topicBuf, Settings.mqtt_grptopic) != NULL); fallback_topic_flag = (strstr(topicBuf, mqtt_client) != NULL); @@ -839,9 +412,7 @@ void MqttDataCallback(char* topic, byte* data, unsigned int data_len) while (isdigit(type[i-1])) { i--; } - if (i < strlen(type)) { - index = atoi(type +i); - } + if (i < strlen(type)) index = atoi(type +i); type[i] = '\0'; } @@ -851,19 +422,17 @@ void MqttDataCallback(char* topic, byte* data, unsigned int data_len) if (type != NULL) { snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_JSON_COMMAND "\":\"" D_JSON_ERROR "\"}")); - if (Settings.ledstate &0x02) { - blinks++; - } + if (Settings.ledstate &0x02) blinks++; - if (!strcmp(dataBuf,"?")) { - data_len = 0; - } + if (!strcmp(dataBuf,"?")) data_len = 0; int16_t payload = -99; // No payload uint16_t payload16 = 0; - long lnum = strtol(dataBuf, &p, 10); + long payload32 = strtol(dataBuf, &p, 10); if (p != dataBuf) { - payload = (int16_t) lnum; // -32766 - 32767 - payload16 = (uint16_t) lnum; // 0 - 65535 + payload = (int16_t) payload32; // -32766 - 32767 + payload16 = (uint16_t) payload32; // 0 - 65535 + } else { + payload32 = 0; } backlog_delay = MIN_BACKLOG_DELAY; // Reset backlog delay @@ -889,16 +458,13 @@ void MqttDataCallback(char* topic, byte* data, unsigned int data_len) int command_code = GetCommandCode(command, sizeof(command), type, kTasmotaCommands); if (CMND_BACKLOG == command_code) { if (data_len) { + uint8_t bl_pointer = (!backlog_pointer) ? MAX_BACKLOG -1 : backlog_pointer; + bl_pointer--; char *blcommand = strtok(dataBuf, ";"); - while (blcommand != NULL) { + while ((blcommand != NULL) && (backlog_index != bl_pointer)) { backlog[backlog_index] = String(blcommand); backlog_index++; -/* - if (backlog_index >= MAX_BACKLOG) { - backlog_index = 0; - } -*/ - backlog_index &= 0xF; + if (backlog_index >= MAX_BACKLOG) backlog_index = 0; blcommand = strtok(NULL, ";"); } snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, D_JSON_APPENDED); @@ -909,23 +475,17 @@ void MqttDataCallback(char* topic, byte* data, unsigned int data_len) } } else if (CMND_DELAY == command_code) { - if ((payload >= MIN_BACKLOG_DELAY) && (payload <= 3600)) { - backlog_delay = payload; - } + if ((payload >= MIN_BACKLOG_DELAY) && (payload <= 3600)) backlog_delay = payload; snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE, command, backlog_delay); } else if ((CMND_POWER == command_code) && (index > 0) && (index <= devices_present)) { - if ((payload < 0) || (payload > 4)) { - payload = 9; - } + if ((payload < 0) || (payload > 4)) payload = 9; ExecuteCommandPower(index, payload); fallback_topic_flag = 0; return; } else if (CMND_STATUS == command_code) { - if ((payload < 0) || (payload > MAX_STATUS)) { - payload = 99; - } + if ((payload < 0) || (payload > MAX_STATUS)) payload = 99; PublishStatus(payload); fallback_topic_flag = 0; return; @@ -957,23 +517,19 @@ void MqttDataCallback(char* topic, byte* data, unsigned int data_len) Settings.pulse_timer[index -1] = payload16; // 0 - 65535 pulse_timer[index -1] = 0; } - snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_NVALUE, command, index, Settings.pulse_timer[index -1]); + snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_NVALUE_ACTIVE_NVALUE, command, index, Settings.pulse_timer[index -1], pulse_timer[index -1]); } else if (CMND_BLINKTIME == command_code) { if ((payload > 2) && (payload <= 3600)) { Settings.blinktime = payload; - if (blink_timer) { - blink_timer = Settings.blinktime; - } + if (blink_timer) blink_timer = Settings.blinktime; } snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE, command, Settings.blinktime); } else if (CMND_BLINKCOUNT == command_code) { if (data_len > 0) { Settings.blinkcount = payload16; // 0 - 65535 - if (blink_counter) { - blink_counter = Settings.blinkcount *2; - } + if (blink_counter) blink_counter = Settings.blinkcount *2; } snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE, command, Settings.blinkcount); } @@ -989,15 +545,15 @@ void MqttDataCallback(char* topic, byte* data, unsigned int data_len) snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, (Settings.save_data > 1) ? stemp1 : GetStateText(Settings.save_data)); } else if (CMND_SENSOR == command_code) { - XdrvMailbox.topic = command; XdrvMailbox.index = index; - XdrvMailbox.payload = payload; XdrvMailbox.data_len = data_len; + XdrvMailbox.payload16 = payload16; + XdrvMailbox.payload = payload; + XdrvMailbox.grpflg = grpflg; + XdrvMailbox.topic = command; XdrvMailbox.data = dataBuf; XsnsCall(FUNC_COMMAND); -// if (!XsnsCall(FUNC_COMMAND)) { -// type = NULL; -// } +// if (!XsnsCall(FUNC_COMMAND)) type = NULL; } else if ((CMND_SETOPTION == command_code) && ((index <= 21) || ((index > 31) && (index <= P_MAX_PARAM8 + 31)))) { if (index <= 31) { @@ -1012,7 +568,6 @@ void MqttDataCallback(char* topic, byte* data, unsigned int data_len) switch (index) { case 3: // mqtt case 15: // pwm_control - case 19: // hass_discovery restart_flag = 2; case 0: // save_state case 1: // button_restrict @@ -1027,20 +582,28 @@ void MqttDataCallback(char* topic, byte* data, unsigned int data_len) case 16: // ws_clock_reverse case 17: // decimal_text case 18: // light_signal + case 19: // hass_discovery case 20: // not_power_linked case 21: // no_power_on_check +// case 22: // mqtt_serial - use commands SerialSend and SerialLog +// case 23: // rules_enabled - use command Rule bitWrite(Settings.flag.data, index, payload); } if (12 == index) { // stop_flash_rotate stop_flash_rotate = payload; SettingsSave(2); } +#ifdef USE_HOME_ASSISTANT + if (19 == index) { // hass_discovery + HAssDiscovery(1); + } +#endif // USE_HOME_ASSISTANT } } else { // SetOption32 .. switch (index) { case P_HOLD_TIME: - if ((payload >= 1) && (payload <= 100)) { + if ((payload >= 1) && (payload <= 250)) { Settings.param[P_HOLD_TIME] = payload; } break; @@ -1052,9 +615,7 @@ void MqttDataCallback(char* topic, byte* data, unsigned int data_len) } } } - if (ptype) { - snprintf_P(stemp1, sizeof(stemp1), PSTR("%d"), Settings.param[index]); - } + if (ptype) snprintf_P(stemp1, sizeof(stemp1), PSTR("%d"), Settings.param[index]); snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_SVALUE, command, (ptype) ? index +32 : index, (ptype) ? stemp1 : GetStateText(bitRead(Settings.flag.data, index))); } else if (CMND_TEMPERATURE_RESOLUTION == command_code) { @@ -1149,9 +710,7 @@ void MqttDataCallback(char* topic, byte* data, unsigned int data_len) byte jsflg = 0; for (byte i = 0; i < MAX_GPIO_PIN; i++) { if (GPIO_USER == cmodule.gp.io[i]) { - if (jsflg) { - snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,"), mqtt_data); - } + if (jsflg) snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,"), mqtt_data); jsflg = 1; snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s\"" D_CMND_GPIO "%d\":\"%d (%s)\""), mqtt_data, i, Settings.my_gp.io[i], GetTextIndexed(stemp1, sizeof(stemp1), Settings.my_gp.io[i], kSensorNames)); @@ -1186,15 +745,9 @@ void MqttDataCallback(char* topic, byte* data, unsigned int data_len) Settings.pwm_value[index -1] = payload; analogWrite(pin[GPIO_PWM1 + index -1], bitRead(pwm_inverted, index -1) ? Settings.pwm_range - payload : payload); } - snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_CMND_PWM "\":{")); - bool first = true; - for (byte i = 0; i < MAX_PWMS; i++) { - if(pin[GPIO_PWM1 + i] < 99) { - snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s%s\"" D_CMND_PWM "%d\":%d"), mqtt_data, first ? "" : ",", i+1, Settings.pwm_value[i]); - first = false; - } - } - snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s}}"),mqtt_data); + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{")); + MqttShowPWMState(); // Render the PWM status to MQTT + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s}"), mqtt_data); } else if (CMND_PWMFREQUENCY == command_code) { if ((1 == payload) || ((payload >= 100) && (payload <= 4000))) { @@ -1238,9 +791,7 @@ void MqttDataCallback(char* topic, byte* data, unsigned int data_len) } else if (CMND_SLEEP == command_code) { if ((payload >= 0) && (payload < 251)) { - if ((!Settings.sleep && payload) || (Settings.sleep && !payload)) { - restart_flag = 2; - } + if ((!Settings.sleep && payload) || (Settings.sleep && !payload)) restart_flag = 2; Settings.sleep = payload; sleep = payload; } @@ -1253,7 +804,8 @@ void MqttDataCallback(char* topic, byte* data, unsigned int data_len) // We also need at least 3 chars to make a valid version number string. if (((1 == data_len) && (1 == payload)) || ((data_len >= 3) && NewerVersion(dataBuf))) { ota_state_flag = 3; - snprintf_P(mqtt_data, sizeof(mqtt_data), "{\"%s\":\"" D_JSON_VERSION " %s " D_JSON_FROM " %s\"}", command, my_version, Settings.ota_url); +// snprintf_P(mqtt_data, sizeof(mqtt_data), "{\"%s\":\"" D_JSON_VERSION " %s " D_JSON_FROM " %s\"}", command, my_version, Settings.ota_url); + snprintf_P(mqtt_data, sizeof(mqtt_data), "{\"%s\":\"" D_JSON_VERSION " %s " D_JSON_FROM " %s\"}", command, my_version, GetOtaUrl(stemp1, sizeof(stemp1))); } else { snprintf_P(mqtt_data, sizeof(mqtt_data), "{\"%s\":\"" D_JSON_ONE_OR_GT "\"}", command, my_version); } @@ -1263,11 +815,47 @@ void MqttDataCallback(char* topic, byte* data, unsigned int data_len) strlcpy(Settings.ota_url, (1 == payload) ? OTA_URL : dataBuf, sizeof(Settings.ota_url)); snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, Settings.ota_url); } + else if (CMND_BAUDRATE == command_code) { + if (payload32 > 0) { + payload32 /= 1200; // Make it a valid baudrate + baudrate = (1 == payload) ? APP_BAUDRATE : payload32 * 1200; + SetSerialBaudrate(baudrate); + } + snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE, command, Settings.baudrate * 1200); + } + else if ((CMND_SERIALSEND == command_code) && (index > 0) && (index <= 3)) { + SetSeriallog(LOG_LEVEL_NONE); + Settings.flag.mqtt_serial = 1; + if (data_len > 0) { + if (1 == index) { + Serial.printf("%s\n", dataBuf); + } + else if (2 == index) { + Serial.printf("%s", dataBuf); + } + else if (3 == index) { + uint16_t dat_len = data_len; + Serial.printf("%s", Unescape(dataBuf, &dat_len)); + } + snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, D_JSON_DONE); + } + } + else if (CMND_SERIALDELIMITER == command_code) { + if ((data_len > 0) && (payload < 256)) { + if (payload > 0) { + Settings.serial_delimiter = payload; + } else { + uint16_t dat_len = data_len; + Unescape(dataBuf, &dat_len); + Settings.serial_delimiter = dataBuf[0]; + } + } + snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE, command, Settings.serial_delimiter); + } else if (CMND_SERIALLOG == command_code) { if ((payload >= LOG_LEVEL_NONE) && (payload <= LOG_LEVEL_ALL)) { - Settings.seriallog_level = payload; - seriallog_level = payload; - seriallog_timer = 0; + Settings.flag.mqtt_serial = 0; + SetSeriallog(payload); } snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE_ACTIVE_NVALUE, command, Settings.seriallog_level, seriallog_level); } @@ -1286,9 +874,7 @@ void MqttDataCallback(char* topic, byte* data, unsigned int data_len) snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, Settings.syslog_host); } else if (CMND_LOGPORT == command_code) { - if (payload16 > 0) { - Settings.syslog_port = (1 == payload16) ? SYS_LOG_PORT : payload16; - } + if (payload16 > 0) Settings.syslog_port = (1 == payload16) ? SYS_LOG_PORT : payload16; snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE, command, Settings.syslog_port); } else if ((CMND_IPADDRESS == command_code) && (index > 0) && (index <= 4)) { @@ -1303,9 +889,7 @@ void MqttDataCallback(char* topic, byte* data, unsigned int data_len) if ((data_len > 0) && (data_len < sizeof(Settings.ntp_server[0]))) { strlcpy(Settings.ntp_server[index -1], (!strcmp(dataBuf,"0")) ? "" : (1 == payload) ? (1==index)?NTP_SERVER1:(2==index)?NTP_SERVER2:NTP_SERVER3 : dataBuf, sizeof(Settings.ntp_server[0])); for (i = 0; i < strlen(Settings.ntp_server[index -1]); i++) { - if (Settings.ntp_server[index -1][i] == ',') { - Settings.ntp_server[index -1][i] = '.'; - } + if (Settings.ntp_server[index -1][i] == ',') Settings.ntp_server[index -1][i] = '.'; } restart_flag = 2; } @@ -1338,8 +922,10 @@ void MqttDataCallback(char* topic, byte* data, unsigned int data_len) strlcpy(Settings.sta_pwd[index -1], (1 == payload) ? (1 == index) ? STA_PASS1 : STA_PASS2 : dataBuf, sizeof(Settings.sta_pwd[0])); Settings.sta_active = index -1; restart_flag = 2; + snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_SVALUE, command, index, Settings.sta_pwd[index -1]); + } else { + snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_ASTERIX, command, index); } - snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_SVALUE, command, index, Settings.sta_pwd[index -1]); } else if ((CMND_HOSTNAME == command_code) && !grpflg) { if ((data_len > 0) && (data_len < sizeof(Settings.hostname))) { @@ -1378,16 +964,12 @@ void MqttDataCallback(char* topic, byte* data, unsigned int data_len) snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_SVALUE, command, index, Settings.friendlyname[index -1]); } else if ((CMND_SWITCHMODE == command_code) && (index > 0) && (index <= MAX_SWITCHES)) { - if ((payload >= 0) && (payload < MAX_SWITCH_OPTION)) { - Settings.switchmode[index -1] = payload; - } + if ((payload >= 0) && (payload < MAX_SWITCH_OPTION)) Settings.switchmode[index -1] = payload; snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_NVALUE, command, index, Settings.switchmode[index-1]); } #ifdef USE_WEBSERVER else if (CMND_WEBSERVER == command_code) { - if ((payload >= 0) && (payload <= 2)) { - Settings.webserver = payload; - } + if ((payload >= 0) && (payload <= 2)) Settings.webserver = payload; if (Settings.webserver) { snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_CMND_WEBSERVER "\":\"" D_JSON_ACTIVE_FOR " %s " D_JSON_ON_DEVICE " %s " D_JSON_WITH_IP_ADDRESS " %s\"}"), (2 == Settings.webserver) ? D_ADMIN : D_USER, my_hostname, WiFi.localIP().toString().c_str()); @@ -1398,13 +980,13 @@ void MqttDataCallback(char* topic, byte* data, unsigned int data_len) else if (CMND_WEBPASSWORD == command_code) { if ((data_len > 0) && (data_len < sizeof(Settings.web_password))) { strlcpy(Settings.web_password, (!strcmp(dataBuf,"0")) ? "" : (1 == payload) ? WEB_PASSWORD : dataBuf, sizeof(Settings.web_password)); + snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, Settings.web_password); + } else { + snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_ASTERIX, command); } - snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, Settings.web_password); } else if (CMND_WEBLOG == command_code) { - if ((payload >= LOG_LEVEL_NONE) && (payload <= LOG_LEVEL_ALL)) { - Settings.weblog_level = payload; - } + if ((payload >= LOG_LEVEL_NONE) && (payload <= LOG_LEVEL_ALL)) Settings.weblog_level = payload; snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE, command, Settings.weblog_level); } #ifdef USE_EMULATION @@ -1420,9 +1002,7 @@ void MqttDataCallback(char* topic, byte* data, unsigned int data_len) else if (CMND_TELEPERIOD == command_code) { if ((payload >= 0) && (payload < 3601)) { Settings.tele_period = (1 == payload) ? TELE_PERIOD : payload; - if ((Settings.tele_period > 0) && (Settings.tele_period < 10)) { - Settings.tele_period = 10; // Do not allow periods < 10 seconds - } + if ((Settings.tele_period > 0) && (Settings.tele_period < 10)) Settings.tele_period = 10; // Do not allow periods < 10 seconds tele_period = Settings.tele_period; } snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE_UNIT, command, Settings.tele_period, (Settings.flag.value_units) ? " " D_UNIT_SECOND : ""); @@ -1448,7 +1028,8 @@ void MqttDataCallback(char* topic, byte* data, unsigned int data_len) snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command , D_JSON_RESET_AND_RESTARTING); break; case 2: - restart_flag = 212; + case 3: + restart_flag = 210 + payload; snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_CMND_RESET "\":\"" D_JSON_ERASE ", " D_JSON_RESET_AND_RESTARTING "\"}")); break; default: @@ -1456,15 +1037,11 @@ void MqttDataCallback(char* topic, byte* data, unsigned int data_len) } } else if (CMND_TIMEZONE == command_code) { - if ((data_len > 0) && (((payload >= -13) && (payload <= 13)) || (99 == payload))) { - Settings.timezone = payload; - } + if ((data_len > 0) && (((payload >= -13) && (payload <= 14)) || (99 == payload))) Settings.timezone = payload; snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE, command, Settings.timezone); } else if (CMND_ALTITUDE == command_code) { - if ((data_len > 0) && ((payload >= -30000) && (payload <= 30000))) { - Settings.altitude = payload; - } + if ((data_len > 0) && ((payload >= -30000) && (payload <= 30000))) Settings.altitude = payload; snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE, command, Settings.altitude); } else if (CMND_LEDPOWER == command_code) { @@ -1484,38 +1061,21 @@ void MqttDataCallback(char* topic, byte* data, unsigned int data_len) } snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, GetStateText(bitRead(Settings.ledstate, 3))); } - else if (CMND_LEDSTATE ==command_code) { + else if (CMND_LEDSTATE == command_code) { if ((payload >= 0) && (payload < MAX_LED_OPTION)) { Settings.ledstate = payload; - if (!Settings.ledstate) { - SetLedPower(0); - } + if (!Settings.ledstate) SetLedPower(0); } snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE, command, Settings.ledstate); } - else if (CMND_CFGDUMP == command_code) { - SettingsDump(dataBuf); - snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, D_JSON_DONE); - } #ifdef USE_I2C else if ((CMND_I2CSCAN == command_code) && i2c_flg) { I2cScan(mqtt_data, sizeof(mqtt_data)); } #endif // USE_I2C - else if (Settings.flag.mqtt_enabled && MqttCommand(grpflg, type, index, dataBuf, data_len, payload, payload16)) { + else if (XdrvCommand(grpflg, type, index, dataBuf, data_len, payload, payload16)) { // Serviced } - else if (XdrvCommand(type, index, dataBuf, data_len, payload)) { - // Serviced - } -#ifdef DEBUG_THEO - else if (CMND_EXCEPTION == command_code) { - if (data_len > 0) { - ExceptionTest(payload); - } - snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, D_JSON_DONE); - } -#endif // DEBUG_THEO else { type = NULL; } @@ -1526,15 +1086,13 @@ void MqttDataCallback(char* topic, byte* data, unsigned int data_len) snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_JSON_COMMAND "\":\"" D_JSON_UNKNOWN "\"}")); type = (char*)topicBuf; } - if (mqtt_data[0] != '\0') { - MqttPublishPrefixTopic_P(RESULT_OR_STAT, type); - } + if (mqtt_data[0] != '\0') MqttPublishPrefixTopic_P(RESULT_OR_STAT, type); fallback_topic_flag = 0; } /********************************************************************************************/ -boolean send_button_power(byte key, byte device, byte state) +boolean SendKey(byte key, byte device, byte state) { // key 0 = button_topic // key 1 = switch_topic @@ -1546,31 +1104,39 @@ boolean send_button_power(byte key, byte device, byte state) char stopic[TOPSZ]; char scommand[CMDSZ]; + char key_topic[sizeof(Settings.button_topic)]; boolean result = false; - char *key_topic = (key) ? Settings.switch_topic : Settings.button_topic; - if (Settings.flag.mqtt_enabled && MqttClient.connected() && (strlen(key_topic) != 0) && strcmp(key_topic, "0")) { - if (!key && (device > devices_present)) { - device = 1; - } + char *tmp = (key) ? Settings.switch_topic : Settings.button_topic; + Format(key_topic, tmp, sizeof(key_topic)); + if (Settings.flag.mqtt_enabled && MqttIsConnected() && (strlen(key_topic) != 0) && strcmp(key_topic, "0")) { + if (!key && (device > devices_present)) device = 1; GetTopic_P(stopic, CMND, key_topic, GetPowerDevice(scommand, device, sizeof(scommand), key)); if (9 == state) { mqtt_data[0] = '\0'; } else { - if ((!strcmp(Settings.mqtt_topic, key_topic) || !strcmp(Settings.mqtt_grptopic, key_topic)) && (2 == state)) { + if ((!strcmp(mqtt_topic, key_topic) || !strcmp(Settings.mqtt_grptopic, key_topic)) && (2 == state)) { state = ~(power >> (device -1)) &1; } snprintf_P(mqtt_data, sizeof(mqtt_data), GetStateText(state)); } #ifdef USE_DOMOTICZ - if (!(DomoticzButton(key, device, state, strlen(mqtt_data)))) { + if (!(DomoticzSendKey(key, device, state, strlen(mqtt_data)))) { MqttPublishDirect(stopic, (key) ? Settings.flag.mqtt_switch_retain : Settings.flag.mqtt_button_retain); } #else MqttPublishDirect(stopic, (key) ? Settings.flag.mqtt_switch_retain : Settings.flag.mqtt_button_retain); #endif // USE_DOMOTICZ result = true; +#ifdef USE_RULES + } else { + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"%s%d\":{\"State\":%d}}"), (key) ? "Switch" : "Button", device, state); + result = RulesProcess(); +#endif // USE_RULES } +#ifdef USE_KNX + KnxSendButtonPower(key, device, state); +#endif // USE_KNX return result; } @@ -1591,12 +1157,8 @@ void ExecuteCommandPower(byte device, byte state) state &= 1; publish_power = 0; } - if ((device < 1) || (device > devices_present)) { - device = 1; - } - if (device <= MAX_PULSETIMERS) { - pulse_timer[(device -1)] = 0; - } + if ((device < 1) || (device > devices_present)) device = 1; + if (device <= MAX_PULSETIMERS) pulse_timer[(device -1)] = 0; power_t mask = 1 << (device -1); if (state <= POWER_TOGGLE) { if ((blink_mask & mask)) { @@ -1607,9 +1169,7 @@ void ExecuteCommandPower(byte device, byte state) interlock_mutex = 1; for (byte i = 0; i < devices_present; i++) { power_t imask = 1 << i; - if ((power & imask) && (mask != imask)) { - ExecuteCommandPower(i +1, POWER_OFF); - } + if ((power & imask) && (mask != imask)) ExecuteCommandPower(i +1, POWER_OFF); } interlock_mutex = 0; } @@ -1627,6 +1187,9 @@ void ExecuteCommandPower(byte device, byte state) #ifdef USE_DOMOTICZ DomoticzUpdatePowerState(device); #endif // USE_DOMOTICZ +#ifdef USE_KNX + KnxUpdatePowerState(device, power); +#endif // USE_KNX if (device <= MAX_PULSETIMERS) { // pulse_timer[(device -1)] = (power & mask) ? Settings.pulse_timer[(device -1)] : 0; pulse_timer[(device -1)] = (((POWER_ALL_OFF_PULSETIME_ON == Settings.poweronstate) ? ~power : power) & mask) ? Settings.pulse_timer[(device -1)] : 0; @@ -1647,14 +1210,10 @@ void ExecuteCommandPower(byte device, byte state) byte flag = (blink_mask & mask); blink_mask &= (POWER_MASK ^ mask); // Clear device mask MqttPublishPowerBlinkState(device); - if (flag) { - ExecuteCommandPower(device, (blink_powersave >> (device -1))&1); // Restore state - } + if (flag) ExecuteCommandPower(device, (blink_powersave >> (device -1))&1); // Restore state return; } - if (publish_power) { - MqttPublishPowerState(device); - } + if (publish_power) MqttPublishPowerState(device); } void StopAllPowerBlink() @@ -1681,42 +1240,40 @@ void ExecuteCommand(char *cmnd) token = strtok(cmnd, " "); if (token != NULL) { start = strrchr(token, '/'); // Skip possible cmnd/sonoff/ preamble - if (start) { - token = start +1; - } + if (start) token = start +1; } snprintf_P(stopic, sizeof(stopic), PSTR("/%s"), (token == NULL) ? "" : token); token = strtok(NULL, ""); // snprintf_P(svalue, sizeof(svalue), (token == NULL) ? "" : token); // Fails with command FullTopic home/%prefix%/%topic% as it processes %p of %prefix% strlcpy(svalue, (token == NULL) ? "" : token, sizeof(svalue)); // Fixed 5.8.0b - MqttDataCallback(stopic, (byte*)svalue, strlen(svalue)); + MqttDataHandler(stopic, (byte*)svalue, strlen(svalue)); } void PublishStatus(uint8_t payload) { uint8_t option = 1; + char stemp[MAX_FRIENDLYNAMES * (sizeof(Settings.friendlyname[0]) +4)]; // Workaround MQTT - TCP/IP stack queueing when SUB_PREFIX = PUB_PREFIX - if (!strcmp(Settings.mqtt_prefix[0],Settings.mqtt_prefix[1]) && (!payload)) { - option++; - } + if (!strcmp(Settings.mqtt_prefix[0],Settings.mqtt_prefix[1]) && (!payload)) option++; - if ((!Settings.flag.mqtt_enabled) && (6 == payload)) { - payload = 99; - } - if (!energy_flg && (9 == payload)) { - payload = 99; - } + if ((!Settings.flag.mqtt_enabled) && (6 == payload)) payload = 99; + if (!energy_flg && (9 == payload)) payload = 99; if ((0 == payload) || (99 == payload)) { - snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_CMND_STATUS "\":{\"" D_CMND_MODULE "\":%d,\"" D_CMND_FRIENDLYNAME "\":\"%s\",\"" D_CMND_TOPIC "\":\"%s\",\"" D_CMND_BUTTONTOPIC "\":\"%s\",\"" D_CMND_POWER "\":%d,\"" D_CMND_POWERONSTATE "\":%d,\"" D_CMND_LEDSTATE "\":%d,\"" D_CMND_SAVEDATA "\":%d,\"" D_JSON_SAVESTATE "\":%d,\"" D_CMND_BUTTONRETAIN "\":%d,\"" D_CMND_POWERRETAIN "\":%d}}"), - Settings.module +1, Settings.friendlyname[0], Settings.mqtt_topic, Settings.button_topic, power, Settings.poweronstate, Settings.ledstate, Settings.save_data, Settings.flag.save_state, Settings.flag.mqtt_button_retain, Settings.flag.mqtt_power_retain); + uint8_t maxfn = (devices_present > MAX_FRIENDLYNAMES) ? MAX_FRIENDLYNAMES : (!devices_present) ? 1 : devices_present; + stemp[0] = '\0'; + for (byte i = 0; i < maxfn; i++) { + snprintf_P(stemp, sizeof(stemp), PSTR("%s%s\"%s\"" ), stemp, (i > 0 ? "," : ""), Settings.friendlyname[i]); + } + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_CMND_STATUS "\":{\"" D_CMND_MODULE "\":%d,\"" D_CMND_FRIENDLYNAME "\":[%s],\"" D_CMND_TOPIC "\":\"%s\",\"" D_CMND_BUTTONTOPIC "\":\"%s\",\"" D_CMND_POWER "\":%d,\"" D_CMND_POWERONSTATE "\":%d,\"" D_CMND_LEDSTATE "\":%d,\"" D_CMND_SAVEDATA "\":%d,\"" D_JSON_SAVESTATE "\":%d,\"" D_CMND_BUTTONRETAIN "\":%d,\"" D_CMND_POWERRETAIN "\":%d}}"), + Settings.module +1, stemp, mqtt_topic, Settings.button_topic, power, Settings.poweronstate, Settings.ledstate, Settings.save_data, Settings.flag.save_state, Settings.flag.mqtt_button_retain, Settings.flag.mqtt_power_retain); MqttPublishPrefixTopic_P(option, PSTR(D_CMND_STATUS)); } if ((0 == payload) || (1 == payload)) { - snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_CMND_STATUS D_STATUS1_PARAMETER "\":{\"" D_JSON_BAUDRATE "\":%d,\"" D_CMND_GROUPTOPIC "\":\"%s\",\"" D_CMND_OTAURL "\":\"%s\",\"" D_JSON_UPTIME "\":\"%s\",\"" D_CMND_SLEEP "\":%d,\"" D_JSON_BOOTCOUNT "\":%d,\"" D_JSON_SAVECOUNT "\":%d,\"" D_JSON_SAVEADDRESS "\":\"%X\"}}"), - baudrate, Settings.mqtt_grptopic, Settings.ota_url, GetUptime().c_str(), Settings.sleep, Settings.bootcount, Settings.save_flag, GetSettingsAddress()); + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_CMND_STATUS D_STATUS1_PARAMETER "\":{\"" D_JSON_BAUDRATE "\":%d,\"" D_CMND_GROUPTOPIC "\":\"%s\",\"" D_CMND_OTAURL "\":\"%s\",\"" D_JSON_RESTARTREASON "\":\"%s\",\"" D_JSON_UPTIME "\":\"%s\",\"" D_JSON_STARTUPUTC "\":\"%s\",\"" D_CMND_SLEEP "\":%d,\"" D_JSON_BOOTCOUNT "\":%d,\"" D_JSON_SAVECOUNT "\":%d,\"" D_JSON_SAVEADDRESS "\":\"%X\"}}"), + baudrate, Settings.mqtt_grptopic, Settings.ota_url, GetResetReason().c_str(), GetDateAndTime(DT_UPTIME).c_str(), GetDateAndTime(DT_RESTART).c_str(), Settings.sleep, Settings.bootcount, Settings.save_flag, GetSettingsAddress()); MqttPublishPrefixTopic_P(option, PSTR(D_CMND_STATUS "1")); } @@ -1727,8 +1284,8 @@ void PublishStatus(uint8_t payload) } if ((0 == payload) || (3 == payload)) { - snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_CMND_STATUS D_STATUS3_LOGGING "\":{\"" D_CMND_SERIALLOG "\":%d,\"" D_CMND_WEBLOG "\":%d,\"" D_CMND_SYSLOG "\":%d,\"" D_CMND_LOGHOST "\":\"%s\",\"" D_CMND_LOGPORT "\":%d,\"" D_CMND_SSID "1\":\"%s\",\"" D_CMND_SSID "2\":\"%s\",\"" D_CMND_TELEPERIOD "\":%d,\"" D_CMND_SETOPTION "\":\"%08X\"}}"), - Settings.seriallog_level, Settings.weblog_level, Settings.syslog_level, Settings.syslog_host, Settings.syslog_port, Settings.sta_ssid[0], Settings.sta_ssid[1], Settings.tele_period, Settings.flag.data); + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_CMND_STATUS D_STATUS3_LOGGING "\":{\"" D_CMND_SERIALLOG "\":%d,\"" D_CMND_WEBLOG "\":%d,\"" D_CMND_SYSLOG "\":%d,\"" D_CMND_LOGHOST "\":\"%s\",\"" D_CMND_LOGPORT "\":%d,\"" D_CMND_SSID "\":[\"%s\",\"%s\"],\"" D_CMND_TELEPERIOD "\":%d,\"" D_CMND_SETOPTION "\":[\"%08X\",\"%08X\"]}}"), + Settings.seriallog_level, Settings.weblog_level, Settings.syslog_level, Settings.syslog_host, Settings.syslog_port, Settings.sta_ssid[0], Settings.sta_ssid[1], Settings.tele_period, Settings.flag.data, Settings.flag2.data); MqttPublishPrefixTopic_P(option, PSTR(D_CMND_STATUS "3")); } @@ -1746,21 +1303,26 @@ void PublishStatus(uint8_t payload) } if (((0 == payload) || (6 == payload)) && Settings.flag.mqtt_enabled) { - snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_CMND_STATUS D_STATUS6_MQTT "\":{\"" D_CMND_MQTTHOST "\":\"%s\",\"" D_CMND_MQTTPORT "\":%d,\"" D_CMND_MQTTCLIENT D_JSON_MASK "\":\"%s\",\"" D_CMND_MQTTCLIENT "\":\"%s\",\"" D_CMND_MQTTUSER "\":\"%s\",\"MAX_PACKET_SIZE\":%d,\"KEEPALIVE\":%d}}"), - Settings.mqtt_host, Settings.mqtt_port, Settings.mqtt_client, mqtt_client, Settings.mqtt_user, MQTT_MAX_PACKET_SIZE, MQTT_KEEPALIVE); + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_CMND_STATUS D_STATUS6_MQTT "\":{\"" D_CMND_MQTTHOST "\":\"%s\",\"" D_CMND_MQTTPORT "\":%d,\"" D_CMND_MQTTCLIENT D_JSON_MASK "\":\"%s\",\"" D_CMND_MQTTCLIENT "\":\"%s\",\"" D_CMND_MQTTUSER "\":\"%s\",\"MqttType\":%d,\"MAX_PACKET_SIZE\":%d,\"KEEPALIVE\":%d}}"), + Settings.mqtt_host, Settings.mqtt_port, Settings.mqtt_client, mqtt_client, Settings.mqtt_user, MqttLibraryType(), MQTT_MAX_PACKET_SIZE, MQTT_KEEPALIVE); MqttPublishPrefixTopic_P(option, PSTR(D_CMND_STATUS "6")); } if ((0 == payload) || (7 == payload)) { +#if defined(USE_TIMERS) && defined(USE_SUNRISE) + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_CMND_STATUS D_STATUS7_TIME "\":{\"" D_JSON_UTC_TIME "\":\"%s\",\"" D_JSON_LOCAL_TIME "\":\"%s\",\"" D_JSON_STARTDST "\":\"%s\",\"" D_JSON_ENDDST "\":\"%s\",\"" D_CMND_TIMEZONE "\":%d,\"" D_JSON_SUNRISE "\":\"%s\",\"" D_JSON_SUNSET "\":\"%s\"}}"), + GetTime(0).c_str(), GetTime(1).c_str(), GetTime(2).c_str(), GetTime(3).c_str(), Settings.timezone, GetSun(0).c_str(), GetSun(1).c_str()); +#else snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_CMND_STATUS D_STATUS7_TIME "\":{\"" D_JSON_UTC_TIME "\":\"%s\",\"" D_JSON_LOCAL_TIME "\":\"%s\",\"" D_JSON_STARTDST "\":\"%s\",\"" D_JSON_ENDDST "\":\"%s\",\"" D_CMND_TIMEZONE "\":%d}}"), GetTime(0).c_str(), GetTime(1).c_str(), GetTime(2).c_str(), GetTime(3).c_str(), Settings.timezone); +#endif // USE_TIMERS and USE_SUNRISE MqttPublishPrefixTopic_P(option, PSTR(D_CMND_STATUS "7")); } if (energy_flg) { if ((0 == payload) || (9 == payload)) { - snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_CMND_STATUS D_STATUS9_MARGIN "\":{\"" D_CMND_POWERLOW "\":%d,\"" D_CMND_POWERHIGH "\":%d,\"" D_CMND_VOLTAGELOW "\":%d,\"" D_CMND_VOLTAGEHIGH "\":%d,\"" D_CMND_CURRENTLOW "\":%d,\"" D_CMND_CURRENTHIGH "\":%d}}"), - Settings.energy_min_power, Settings.energy_max_power, Settings.energy_min_voltage, Settings.energy_max_voltage, Settings.energy_min_current, Settings.energy_max_current); + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_CMND_STATUS D_STATUS9_MARGIN "\":{\"" D_CMND_POWERDELTA "\":%d,\"" D_CMND_POWERLOW "\":%d,\"" D_CMND_POWERHIGH "\":%d,\"" D_CMND_VOLTAGELOW "\":%d,\"" D_CMND_VOLTAGEHIGH "\":%d,\"" D_CMND_CURRENTLOW "\":%d,\"" D_CMND_CURRENTHIGH "\":%d}}"), + Settings.energy_power_delta, Settings.energy_min_power, Settings.energy_max_power, Settings.energy_min_voltage, Settings.energy_max_voltage, Settings.energy_min_current, Settings.energy_max_current); MqttPublishPrefixTopic_P(option, PSTR(D_CMND_STATUS "9")); } } @@ -1785,11 +1347,24 @@ void PublishStatus(uint8_t payload) } +void MqttShowPWMState() +{ + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s\"" D_CMND_PWM "\":{"), mqtt_data); + bool first = true; + for (byte i = 0; i < MAX_PWMS; i++) { + if (pin[GPIO_PWM1 + i] < 99) { + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s%s\"" D_CMND_PWM "%d\":%d"), mqtt_data, first ? "" : ",", i+1, Settings.pwm_value[i]); + first = false; + } + } + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s}"), mqtt_data); +} + void MqttShowState() { char stemp1[33]; - snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s{\"" D_JSON_TIME "\":\"%s\",\"" D_JSON_UPTIME "\":\"%s\""), mqtt_data, GetDateAndTime().c_str(), GetUptime().c_str()); + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s{\"" D_JSON_TIME "\":\"%s\",\"" D_JSON_UPTIME "\":\"%s\""), mqtt_data, GetDateAndTime(DT_LOCAL).c_str(), GetDateAndTime(DT_UPTIME).c_str()); #ifdef USE_ADC_VCC dtostrfd((double)ESP.getVcc()/1000, 3, stemp1); snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"" D_JSON_VCC "\":%s"), mqtt_data, stemp1); @@ -1803,13 +1378,18 @@ void MqttShowState() } } + if (pwm_present) { + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,"), mqtt_data); + MqttShowPWMState(); + } + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"" D_JSON_WIFI "\":{\"" D_JSON_AP "\":%d,\"" D_JSON_SSID "\":\"%s\",\"" D_JSON_RSSI "\":%d,\"" D_JSON_APMAC_ADDRESS "\":\"%s\"}}"), mqtt_data, Settings.sta_active +1, Settings.sta_ssid[Settings.sta_active], WifiGetRssiAsQuality(WiFi.RSSI()), WiFi.BSSIDstr().c_str()); } boolean MqttShowSensor() { - snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s{\"" D_JSON_TIME "\":\"%s\""), mqtt_data, GetDateAndTime().c_str()); + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s{\"" D_JSON_TIME "\":\"%s\""), mqtt_data, GetDateAndTime(DT_LOCAL).c_str()); int json_data_start = strlen(mqtt_data); for (byte i = 0; i < MAX_SWITCHES; i++) { if (pin[GPIO_SWT1 +i] < 99) { @@ -1824,9 +1404,7 @@ boolean MqttShowSensor() } snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s}"), mqtt_data); - if (json_data_available) { - XdrvCall(FUNC_SHOW_SENSOR); - } + if (json_data_available) XdrvCall(FUNC_SHOW_SENSOR); return json_data_available; } @@ -1836,14 +1414,10 @@ void PerformEverySecond() { uptime++; - if (blockgpio0) { - blockgpio0--; - } + if (blockgpio0) blockgpio0--; for (byte i = 0; i < MAX_PULSETIMERS; i++) { - if (pulse_timer[i] > 111) { - pulse_timer[i]--; - } + if (pulse_timer[i] > 111) pulse_timer[i]--; } if (seriallog_timer) { @@ -1885,13 +1459,15 @@ void PerformEverySecond() mqtt_data[0] = '\0'; MqttShowState(); - MqttPublishPrefixTopic_P(TELE, PSTR(D_RSLT_STATE)); + MqttPublishPrefixTopic_P(TELE, PSTR(D_RSLT_STATE), MQTT_TELE_RETAIN); mqtt_data[0] = '\0'; if (MqttShowSensor()) { MqttPublishPrefixTopic_P(TELE, PSTR(D_RSLT_SENSOR), Settings.flag.mqtt_sensor_retain); +#ifdef USE_RULES + RulesTeleperiod(); // Allow rule based HA messages +#endif // USE_RULES } - } } @@ -1900,12 +1476,10 @@ void PerformEverySecond() if ((2 == RtcTime.minute) && latest_uptime_flag) { latest_uptime_flag = false; - snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_JSON_TIME "\":\"%s\",\"" D_JSON_UPTIME "\":\"%s\"}"), GetDateAndTime().c_str(), GetUptime().c_str()); + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_JSON_TIME "\":\"%s\",\"" D_JSON_UPTIME "\":\"%s\"}"), GetDateAndTime(DT_LOCAL).c_str(), GetDateAndTime(DT_UPTIME).c_str()); MqttPublishPrefixTopic_P(TELE, PSTR(D_RSLT_UPTIME)); } - if ((3 == RtcTime.minute) && !latest_uptime_flag) { - latest_uptime_flag = true; - } + if ((3 == RtcTime.minute) && !latest_uptime_flag) latest_uptime_flag = true; } /*********************************************************************************************\ @@ -1916,6 +1490,7 @@ void ButtonHandler() { uint8_t button = NOT_PRESSED; uint8_t button_present = 0; + uint8_t hold_time_extent = IMMINENT_RESET_FACTOR; // Extent hold time factor in case of iminnent Reset command char scmnd[20]; uint8_t maxdev = (devices_present > MAX_KEYS) ? MAX_KEYS : devices_present; @@ -1931,6 +1506,7 @@ void ButtonHandler() button = PRESSED; if (0xF500 == dual_button_code) { // Button hold holdbutton[button_index] = (Settings.param[P_HOLD_TIME] * (STATES / 10)) -1; + hold_time_extent = 1; } dual_button_code = 0; } @@ -1943,9 +1519,7 @@ void ButtonHandler() if (button_present) { if (SONOFF_4CHPRO == Settings.module) { - if (holdbutton[button_index]) { - holdbutton[button_index]--; - } + if (holdbutton[button_index]) holdbutton[button_index]--; boolean button_pressed = false; if ((PRESSED == button) && (NOT_PRESSED == lastbutton[button_index])) { @@ -1957,12 +1531,10 @@ void ButtonHandler() if ((NOT_PRESSED == button) && (PRESSED == lastbutton[button_index])) { snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_APPLICATION D_BUTTON "%d " D_LEVEL_01), button_index +1); AddLog(LOG_LEVEL_DEBUG); - if (!holdbutton[button_index]) { // Do not allow within 1 second - button_pressed = true; - } + if (!holdbutton[button_index]) button_pressed = true; // Do not allow within 1 second } if (button_pressed) { - if (!send_button_power(0, button_index +1, POWER_TOGGLE)) { // Execute Toggle command via MQTT if ButtonTopic is set + if (!SendKey(0, button_index +1, POWER_TOGGLE)) { // Execute Toggle command via MQTT if ButtonTopic is set ExecuteCommandPower(button_index +1, POWER_TOGGLE); // Execute Toggle command internally } } @@ -1971,7 +1543,7 @@ void ButtonHandler() if (Settings.flag.button_single) { // Allow only single button press for immediate action snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_APPLICATION D_BUTTON "%d " D_IMMEDIATE), button_index +1); AddLog(LOG_LEVEL_DEBUG); - if (!send_button_power(0, button_index +1, POWER_TOGGLE)) { // Execute Toggle command via MQTT if ButtonTopic is set + if (!SendKey(0, button_index +1, POWER_TOGGLE)) { // Execute Toggle command via MQTT if ButtonTopic is set ExecuteCommandPower(button_index +1, POWER_TOGGLE); // Execute Toggle command internally } } else { @@ -1987,20 +1559,23 @@ void ButtonHandler() holdbutton[button_index] = 0; } else { holdbutton[button_index]++; - if (Settings.flag.button_single) { // Allow only single button press for immediate action - if (holdbutton[button_index] == Settings.param[P_HOLD_TIME] * (STATES / 10) * 4) { // Button hold for four times longer + if (Settings.flag.button_single) { // Allow only single button press for immediate action + if (holdbutton[button_index] == Settings.param[P_HOLD_TIME] * (STATES / 10) * hold_time_extent) { // Button held for factor times longer // Settings.flag.button_single = 0; snprintf_P(scmnd, sizeof(scmnd), PSTR(D_CMND_SETOPTION "13 0")); // Disable single press only ExecuteCommand(scmnd); } } else { - if (holdbutton[button_index] == Settings.param[P_HOLD_TIME] * (STATES / 10)) { // Button hold - multipress[button_index] = 0; - if (!Settings.flag.button_restrict) { // No button restriction + if (Settings.flag.button_restrict) { // Button restriction + if (holdbutton[button_index] == Settings.param[P_HOLD_TIME] * (STATES / 10)) { // Button hold + multipress[button_index] = 0; + SendKey(0, button_index +1, 3); // Execute Hold command via MQTT if ButtonTopic is set + } + } else { + if (holdbutton[button_index] == (Settings.param[P_HOLD_TIME] * (STATES / 10)) * hold_time_extent) { // Button held for factor times longer + multipress[button_index] = 0; snprintf_P(scmnd, sizeof(scmnd), PSTR(D_CMND_RESET " 1")); ExecuteCommand(scmnd); - } else { - send_button_power(0, button_index +1, 3); // Execute Hold command via MQTT if ButtonTopic is set } } } @@ -2020,7 +1595,7 @@ void ButtonHandler() multipress[button_index] = 1; } } - if (single_press && send_button_power(0, button_index + multipress[button_index], POWER_TOGGLE)) { // Execute Toggle command via MQTT if ButtonTopic is set + if (single_press && SendKey(0, button_index + multipress[button_index], POWER_TOGGLE)) { // Execute Toggle command via MQTT if ButtonTopic is set // Success } else { if (multipress[button_index] < 3) { // Single or Double press @@ -2061,7 +1636,7 @@ void SwitchHandler() if (holdwallswitch[i]) { holdwallswitch[i]--; if (0 == holdwallswitch[i]) { - send_button_power(1, i +1, 3); // Execute command via MQTT + SendKey(1, i +1, 3); // Execute command via MQTT } } @@ -2114,7 +1689,7 @@ void SwitchHandler() } if (switchflag < 3) { - if (!send_button_power(1, i +1, switchflag)) { // Execute command via MQTT + if (!SendKey(1, i +1, switchflag)) { // Execute command via MQTT ExecuteCommandPower(i +1, switchflag); // Execute command internally (if i < devices_present) } } @@ -2151,15 +1726,11 @@ void StateLoop() if (!(state % (STATES/10))) { - if (mqtt_cmnd_publish) { - mqtt_cmnd_publish--; // Clean up - } + if (mqtt_cmnd_publish) mqtt_cmnd_publish--; // Clean up if (latching_relay_pulse) { latching_relay_pulse--; - if (!latching_relay_pulse) { - SetLatchingRelay(0, 0); - } + if (!latching_relay_pulse) SetLatchingRelay(0, 0); } for (byte i = 0; i < MAX_PULSETIMERS; i++) { @@ -2188,20 +1759,13 @@ void StateLoop() } // Backlog - if (backlog_delay) { - backlog_delay--; - } + if (backlog_delay) backlog_delay--; if ((backlog_pointer != backlog_index) && !backlog_delay && !backlog_mutex) { backlog_mutex = 1; ExecuteCommand((char*)backlog[backlog_pointer].c_str()); backlog_mutex = 0; backlog_pointer++; -/* - if (backlog_pointer >= MAX_BACKLOG) { - backlog_pointer = 0; - } -*/ - backlog_pointer &= 0xF; + if (backlog_pointer >= MAX_BACKLOG) backlog_pointer = 0; } } @@ -2231,9 +1795,7 @@ void StateLoop() } if (!blinkstate) { blinks--; - if (200 == blinks) { - blinks = 0; - } + if (200 == blinks) blinks = 0; } } else { if (Settings.ledstate &1) { @@ -2263,9 +1825,7 @@ void StateLoop() } if (ota_state_flag <= 0) { #ifdef USE_WEBSERVER - if (Settings.webserver) { - StopWebserver(); - } + if (Settings.webserver) StopWebserver(); #endif // USE_WEBSERVER #ifdef USE_ARILUX_RF AriluxRfDisable(); // Prevent restart exception on Arilux Interrupt routine @@ -2274,23 +1834,22 @@ void StateLoop() ota_result = 0; ota_retry_counter--; if (ota_retry_counter) { + strlcpy(mqtt_data, GetOtaUrl(log_data, sizeof(log_data)), sizeof(mqtt_data)); #ifndef BE_MINIMAL if (RtcSettings.ota_loader) { - char *pch = strrchr(Settings.ota_url, '-'); // Change from filename-DE.bin into filename-minimal.bin - char *ech = strrchr(Settings.ota_url, '.'); // Change from filename.bin into filename-minimal.bin - if (!pch) { - pch = ech; - } + char *pch = strrchr(mqtt_data, '-'); // Change from filename-DE.bin into filename-minimal.bin + char *ech = strrchr(mqtt_data, '.'); // Change from filename.bin into filename-minimal.bin + if (!pch) pch = ech; if (pch) { - strlcpy(mqtt_data, Settings.ota_url, pch - Settings.ota_url +1); + mqtt_data[pch - mqtt_data] = '\0'; + char *ech = strrchr(Settings.ota_url, '.'); // Change from filename.bin into filename-minimal.bin snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s-" D_JSON_MINIMAL "%s"), mqtt_data, ech); // Minimal filename must be filename-minimal - ota_url = mqtt_data; // Try minimal image } } #endif // BE_MINIMAL - snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_UPLOAD "%s"), ota_url); + snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_UPLOAD "%s"), mqtt_data); AddLog(LOG_LEVEL_DEBUG); - ota_result = (HTTP_UPDATE_FAILED != ESPhttpUpdate.update(ota_url)); + ota_result = (HTTP_UPDATE_FAILED != ESPhttpUpdate.update(mqtt_data)); if (!ota_result) { #ifndef BE_MINIMAL int ota_error = ESPhttpUpdate.getLastError(); @@ -2318,9 +1877,7 @@ void StateLoop() } break; case (STATES/10)*4: - if (MidnightNow()) { - CounterSaveState(); - } + if (MidnightNow()) CounterSaveState(); if (save_data_counter && (backlog_pointer == backlog_index)) { save_data_counter--; if (save_data_counter <= 0) { @@ -2342,9 +1899,12 @@ void StateLoop() } } if (restart_flag && (backlog_pointer == backlog_index)) { - if (212 == restart_flag) { - SettingsErase(); - restart_flag--; + if (213 == restart_flag) { + SettingsSdkErase(); // Erase flash SDK parameters + restart_flag = 2; + } else if (212 == restart_flag) { + SettingsErase(0); // Erase all flash from program end to end of physical flash + restart_flag = 211; } if (211 == restart_flag) { SettingsDefault(); @@ -2363,25 +1923,91 @@ void StateLoop() wifi_state_flag = WIFI_RESTART; break; case (STATES/10)*8: - if (WL_CONNECTED == WiFi.status()) { - if (Settings.flag.mqtt_enabled) { - if (!MqttClient.connected()) { - if (!mqtt_retry_counter) { - MqttReconnect(); - } else { - mqtt_retry_counter--; - } - } - } else { - if (!mqtt_retry_counter) { - MqttReconnect(); - } - } - } + if (WL_CONNECTED == WiFi.status()) MqttCheck(); break; } } +#ifdef USE_ARDUINO_OTA +/*********************************************************************************************\ + * Allow updating via the Arduino OTA-protocol. + * + * - Once started disables current wifi clients and udp + * - Perform restart when done to re-init wifi clients +\*********************************************************************************************/ + +bool arduino_ota_triggered = false; +uint16_t arduino_ota_progress_dot_count = 0; + +void ArduinoOTAInit() +{ + ArduinoOTA.setPort(8266); + ArduinoOTA.setHostname(Settings.hostname); + if (Settings.web_password[0] !=0) ArduinoOTA.setPassword(Settings.web_password); + + ArduinoOTA.onStart([]() + { + SettingsSave(1); // Free flash for OTA update +#ifdef USE_WEBSERVER + if (Settings.webserver) StopWebserver(); +#endif // USE_WEBSERVER +#ifdef USE_ARILUX_RF + AriluxRfDisable(); // Prevent restart exception on Arilux Interrupt routine +#endif // USE_ARILUX_RF + if (Settings.flag.mqtt_enabled) MqttDisconnect(); + snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_UPLOAD "Arduino OTA " D_UPLOAD_STARTED)); + AddLog(LOG_LEVEL_INFO); + arduino_ota_triggered = true; + arduino_ota_progress_dot_count = 0; + delay(100); // Allow time for message xfer + }); + + ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) + { + if ((LOG_LEVEL_DEBUG <= seriallog_level)) { + arduino_ota_progress_dot_count++; + Serial.printf("."); + if (!(arduino_ota_progress_dot_count % 80)) Serial.println(); + } + }); + + ArduinoOTA.onError([](ota_error_t error) + { + /* + From ArduinoOTA.h: + typedef enum { OTA_AUTH_ERROR, OTA_BEGIN_ERROR, OTA_CONNECT_ERROR, OTA_RECEIVE_ERROR, OTA_END_ERROR } ota_error_t; + */ + char error_str[100]; + + if ((LOG_LEVEL_DEBUG <= seriallog_level) && arduino_ota_progress_dot_count) Serial.println(); + switch (error) { + case OTA_BEGIN_ERROR: strncpy_P(error_str, PSTR(D_UPLOAD_ERR_2), sizeof(error_str)); break; + case OTA_RECEIVE_ERROR: strncpy_P(error_str, PSTR(D_UPLOAD_ERR_5), sizeof(error_str)); break; + case OTA_END_ERROR: strncpy_P(error_str, PSTR(D_UPLOAD_ERR_7), sizeof(error_str)); break; + default: + snprintf_P(error_str, sizeof(error_str), PSTR(D_UPLOAD_ERROR_CODE " %d"), error); + } + snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_UPLOAD "Arduino OTA %s. " D_RESTARTING), error_str); + AddLog(LOG_LEVEL_INFO); + delay(100); // Allow time for message xfer + ESP.restart(); + }); + + ArduinoOTA.onEnd([]() + { + if ((LOG_LEVEL_DEBUG <= seriallog_level)) Serial.println(); + snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_UPLOAD "Arduino OTA " D_SUCCESSFUL ". " D_RESTARTING)); + AddLog(LOG_LEVEL_INFO); + delay(100); // Allow time for message xfer + ESP.restart(); + }); + + ArduinoOTA.begin(); + snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_UPLOAD "Arduino OTA " D_ENABLED " " D_PORT " 8266")); + AddLog(LOG_LEVEL_INFO); +} +#endif // USE_ARDUINO_OTA + /********************************************************************************************/ void SerialInput() @@ -2424,9 +2050,9 @@ void SerialInput() } /*-------------------------------------------------------------------------------------------*\ - * Sonoff S31 4800 baud serial interface + * Sonoff S31 and Sonoff Pow R2 4800 baud serial interface \*-------------------------------------------------------------------------------------------*/ - if (SONOFF_S31 == Settings.module) { + if ((SONOFF_S31 == Settings.module) || (SONOFF_POW_R2 == Settings.module)) { if (CseSerialInput()) { serial_in_byte_counter = 0; Serial.flush(); @@ -2441,38 +2067,60 @@ void SerialInput() Serial.flush(); return; } - if (isprint(serial_in_byte)) { - if (serial_in_byte_counter < INPUT_BUFFER_SIZE) { // add char to string if it still fits - serial_in_buffer[serial_in_byte_counter++] = serial_in_byte; - } else { - serial_in_byte_counter = 0; + if (!Settings.flag.mqtt_serial) { + if (isprint(serial_in_byte)) { + if (serial_in_byte_counter < INPUT_BUFFER_SIZE -1) { // add char to string if it still fits + serial_in_buffer[serial_in_byte_counter++] = serial_in_byte; + } else { + serial_in_byte_counter = 0; + } + } + } else { + if (serial_in_byte) { + if ((serial_in_byte_counter < INPUT_BUFFER_SIZE -1) && (serial_in_byte != Settings.serial_delimiter)) { // add char to string if it still fits + serial_in_buffer[serial_in_byte_counter++] = serial_in_byte; + serial_polling_window = millis(); + } else { + serial_polling_window = 0; + break; + } } } /*-------------------------------------------------------------------------------------------*\ * Sonoff SC 19200 baud serial interface \*-------------------------------------------------------------------------------------------*/ - if (serial_in_byte == '\x1B') { // Sonoff SC status from ATMEGA328P - serial_in_buffer[serial_in_byte_counter] = 0; // serial data completed - SonoffScSerialInput(serial_in_buffer); - serial_in_byte_counter = 0; - Serial.flush(); - return; + if (SONOFF_SC == Settings.module) { + if (serial_in_byte == '\x1B') { // Sonoff SC status from ATMEGA328P + serial_in_buffer[serial_in_byte_counter] = 0; // serial data completed + SonoffScSerialInput(serial_in_buffer); + serial_in_byte_counter = 0; + Serial.flush(); + return; + } } /*-------------------------------------------------------------------------------------------*/ - else if (serial_in_byte == '\n') { + else if (!Settings.flag.mqtt_serial && (serial_in_byte == '\n')) { serial_in_buffer[serial_in_byte_counter] = 0; // serial data completed seriallog_level = (Settings.seriallog_level < LOG_LEVEL_INFO) ? (byte)LOG_LEVEL_INFO : Settings.seriallog_level; snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_COMMAND "%s"), serial_in_buffer); AddLog(LOG_LEVEL_INFO); ExecuteCommand(serial_in_buffer); serial_in_byte_counter = 0; + serial_polling_window = 0; Serial.flush(); return; } } + + if (Settings.flag.mqtt_serial && serial_in_byte_counter && (millis() > (serial_polling_window + SERIAL_POLLING))) { + serial_in_buffer[serial_in_byte_counter] = 0; // serial data completed + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_JSON_SERIALRECEIVED "\":\"%s\"}"), serial_in_buffer); + MqttPublishPrefixTopic_P(RESULT_OR_TELE, PSTR(D_JSON_SERIALRECEIVED)); + serial_in_byte_counter = 0; + } } /********************************************************************************************/ @@ -2531,14 +2179,10 @@ void GpioInit() } #endif // USE_DHT } - if (mpin) { - pin[mpin] = i; - } + if (mpin) pin[mpin] = i; } - if (2 == pin[GPIO_TXD]) { - Serial.set_tx(2); - } + if (2 == pin[GPIO_TXD]) Serial.set_tx(2); analogWriteRange(Settings.pwm_range); // Default is 1023 (Arduino.h) analogWriteFreq(Settings.pwm_frequency); // Default is 1000 (core_esp8266_wiring_pwm.c) @@ -2547,9 +2191,7 @@ void GpioInit() spi_flg = ((((pin[GPIO_SPI_CS] < 99) && (pin[GPIO_SPI_CS] > 14)) || (pin[GPIO_SPI_CS] < 12)) || (((pin[GPIO_SPI_DC] < 99) && (pin[GPIO_SPI_DC] > 14)) || (pin[GPIO_SPI_DC] < 12))); if (spi_flg) { for (byte i = 0; i < GPIO_MAX; i++) { - if ((pin[i] >= 12) && (pin[i] <=14)) { - pin[i] = 99; - } + if ((pin[i] >= 12) && (pin[i] <=14)) pin[i] = 99; } my_module.gp.io[12] = GPIO_SPI_MISO; pin[GPIO_SPI_MISO] = 12; @@ -2562,9 +2204,7 @@ void GpioInit() #ifdef USE_I2C i2c_flg = ((pin[GPIO_I2C_SCL] < 99) && (pin[GPIO_I2C_SDA] < 99)); - if (i2c_flg) { - Wire.begin(pin[GPIO_I2C_SDA], pin[GPIO_I2C_SCL]); - } + if (i2c_flg) Wire.begin(pin[GPIO_I2C_SDA], pin[GPIO_I2C_SCL]); #endif // USE_I2C devices_present = 1; @@ -2572,25 +2212,27 @@ void GpioInit() light_type = LT_BASIC; // Use basic PWM control if SetOption15 = 0 if (Settings.flag.pwm_control) { for (byte i = 0; i < MAX_PWMS; i++) { - if (pin[GPIO_PWM1 +i] < 99) { - light_type++; // Use Dimmer/Color control for all PWM as SetOption15 = 1 - } + if (pin[GPIO_PWM1 +i] < 99) light_type++; // Use Dimmer/Color control for all PWM as SetOption15 = 1 } } if (SONOFF_BRIDGE == Settings.module) { + Settings.flag.mqtt_serial = 0; baudrate = 19200; } if (SONOFF_DUAL == Settings.module) { + Settings.flag.mqtt_serial = 0; devices_present = 2; baudrate = 19200; } else if (CH4 == Settings.module) { + Settings.flag.mqtt_serial = 0; devices_present = 4; baudrate = 19200; } else if (SONOFF_SC == Settings.module) { + Settings.flag.mqtt_serial = 0; devices_present = 0; baudrate = 19200; } @@ -2607,9 +2249,7 @@ void GpioInit() light_type = LT_RGBWC; } else { - if (!light_type) { - devices_present = 0; - } + if (!light_type) devices_present = 0; for (byte i = 0; i < MAX_RELAYS; i++) { if (pin[GPIO_REL1 +i] < 99) { pinMode(pin[GPIO_REL1 +i], OUTPUT); @@ -2689,6 +2329,7 @@ void setup() OsWatchInit(); + baudrate = Settings.baudrate * 1200; seriallog_level = Settings.seriallog_level; seriallog_timer = SERIALLOG_TIMER; #ifndef USE_EMULATION @@ -2707,19 +2348,18 @@ void setup() SetSerialBaudrate(baudrate); + Format(mqtt_client, Settings.mqtt_client, sizeof(mqtt_client)); + Format(mqtt_topic, Settings.mqtt_topic, sizeof(mqtt_topic)); + if (strstr(Settings.hostname, "%")) { strlcpy(Settings.hostname, WIFI_HOSTNAME, sizeof(Settings.hostname)); - snprintf_P(my_hostname, sizeof(my_hostname)-1, Settings.hostname, Settings.mqtt_topic, ESP.getChipId() & 0x1FFF); + snprintf_P(my_hostname, sizeof(my_hostname)-1, Settings.hostname, mqtt_topic, ESP.getChipId() & 0x1FFF); } else { snprintf_P(my_hostname, sizeof(my_hostname)-1, Settings.hostname); } WifiConnect(); - GetMqttClient(mqtt_client, Settings.mqtt_client, sizeof(mqtt_client)); - - if (MOTOR == Settings.module) { - Settings.poweronstate = POWER_ALL_ON; // Needs always on else in limbo! - } + if (MOTOR == Settings.module) Settings.poweronstate = POWER_ALL_ON; // Needs always on else in limbo! if (POWER_ALL_ALWAYS_ON == Settings.poweronstate) { SetDevicePower(1); } else { @@ -2767,8 +2407,8 @@ void setup() blink_powersave = power; - snprintf_P(log_data, sizeof(log_data), PSTR(D_PROJECT " %s %s (" D_CMND_TOPIC " %s, " D_FALLBACK " %s, " D_CMND_GROUPTOPIC " %s) " D_VERSION " %s"), - PROJECT, Settings.friendlyname[0], Settings.mqtt_topic, mqtt_client, Settings.mqtt_grptopic, my_version); + snprintf_P(log_data, sizeof(log_data), PSTR(D_PROJECT " %s %s (" D_CMND_TOPIC " %s, " D_FALLBACK " %s, " D_CMND_GROUPTOPIC " %s) " D_VERSION " %s-" ARDUINO_ESP8266_RELEASE), + PROJECT, Settings.friendlyname[0], mqtt_topic, mqtt_client, Settings.mqtt_grptopic, my_version); AddLog(LOG_LEVEL_INFO); #ifdef BE_MINIMAL snprintf_P(log_data, sizeof(log_data), PSTR(D_WARNING_MINIMAL_VERSION)); @@ -2776,32 +2416,36 @@ void setup() #endif // BE_MINIMAL RtcInit(); + +#ifdef USE_ARDUINO_OTA + ArduinoOTAInit(); +#endif // USE_ARDUINO_OTA + XsnsCall(FUNC_INIT); } void loop() { + XdrvCall(FUNC_LOOP); + OsWatchLoop(); #ifdef USE_WEBSERVER PollDnsWebserver(); +#ifdef USE_EMULATION + if (Settings.flag2.emulation) PollUdp(); +#endif // USE_EMULATION #endif // USE_WEBSERVER -#ifdef USE_EMULATION - if (Settings.flag2.emulation) { - PollUdp(); - } -#endif // USE_EMULATION + if (millis() >= state_loop_timer) StateLoop(); - if (millis() >= state_loop_timer) { - StateLoop(); - } - if (Settings.flag.mqtt_enabled) { - MqttClient.loop(); - } - if (Serial.available()){ - SerialInput(); - } + SerialInput(); + +#ifdef USE_ARDUINO_OTA + ArduinoOTA.handle(); + // Once OTA is triggered, only handle that and dont do other stuff. (otherwise it fails) + while (arduino_ota_triggered) ArduinoOTA.handle(); +#endif // USE_ARDUINO_OTA // yield(); // yield == delay(0), delay contains yield, auto yield in loop delay(sleep); // https://github.com/esp8266/Arduino/issues/2021 diff --git a/sonoff/sonoff_post.h b/sonoff/sonoff_post.h index 18e603ea8..1d6ba7878 100644 --- a/sonoff/sonoff_post.h +++ b/sonoff/sonoff_post.h @@ -20,6 +20,10 @@ #ifndef _SONOFF_POST_H_ #define _SONOFF_POST_H_ +/*********************************************************************************************\ + * Function declarations +\*********************************************************************************************/ + #ifdef __cplusplus extern "C" { #endif @@ -33,85 +37,239 @@ void WifiWpsStatusCallback(wps_cb_status status); } #endif -#define USE_DHT // Default DHT11 sensor needs no external library +//#ifdef USE_KNX // Enabling this will fail compilation. It has no impact if not used. (20180417) +#include +void KNX_CB_Action(message_t const &msg, void *arg); +//#endif // USE_KNX + +/*********************************************************************************************\ + * Default global defines +\*********************************************************************************************/ + +#define USE_DHT // Default DHT11 sensor needs no external library + +/*********************************************************************************************\ + * [sonoff-allsensors.bin] + * Provide an image with all supported sensors enabled +\*********************************************************************************************/ + +#ifdef USE_ALL_SENSORS +#define USE_ADC_VCC // Display Vcc in Power status. Disable for use as Analog input on selected devices +#define USE_DS18x20 // For more than one DS18x20 sensors with id sort, single scan and read retry (+1k3 code) +//#define USE_DS18x20_LEGACY // For more than one DS18x20 sensors with dynamic scan using library OneWire (+1k5 code) +#define USE_I2C // I2C using library wire (+10k code, 0k2 mem, 124 iram) +#define USE_SHT // Add I2C emulating code for SHT1X sensor (+1k4 code) +#define USE_SHT3X // Add I2C code for SHT3x sensor (+0k6 code) +#define USE_HTU // Add I2C code for HTU21/SI7013/SI7020/SI7021 sensor (+1k5 code) +#define USE_BMP // Add I2C code for BMP085/BMP180/BMP280/BME280 sensor (+4k code) + #define USE_BME680 // Add additional support for BME680 sensor using Adafruit Sensor and BME680 libraries (+6k code) +#define USE_SGP30 // Add I2C code for SGP30 sensor (+1k1 code) +#define USE_BH1750 // Add I2C code for BH1750 sensor (+0k5 code) +#define USE_VEML6070 // Add I2C code for VEML6070 sensor (+0k5 code) +#define USE_TSL2561 // Add I2C code for TSL2561 sensor using library Adafruit TSL2561 Arduino (+1k2 code) +#define USE_ADS1115 // Add I2C code for ADS1115 16 bit A/D converter based on Adafruit ADS1x15 library (no library needed) (+0k7 code) +//#define USE_ADS1115_I2CDEV // Add I2C code for ADS1115 16 bit A/D converter using library i2cdevlib-Core and i2cdevlib-ADS1115 (+2k code) +#define USE_INA219 // Add I2C code for INA219 Low voltage and current sensor (+1k code) +#define USE_MGS // Add I2C code for Xadow and Grove Mutichannel Gas sensor using library Multichannel_Gas_Sensor (+10k code) +#define USE_MHZ19 // Add support for MH-Z19 CO2 sensor (+2k code) +#define USE_SENSEAIR // Add support for SenseAir K30, K70 and S8 CO2 sensor (+2k3 code) +#ifndef CO2_LOW + #define CO2_LOW 800 // Below this CO2 value show green light (needs PWM or WS2812 RG(B) led and enable with SetOption18 1) +#endif +#ifndef CO2_HIGH + #define CO2_HIGH 1200 // Above this CO2 value show red light (needs PWM or WS2812 RG(B) led and enable with SetOption18 1) +#endif +#define USE_PMS5003 // Add support for PMS5003 and PMS7003 particle concentration sensor (+1k3 code) +#define USE_NOVA_SDS // Add support for SDS011 and SDS021 particle concentration sensor (+0k7 code) +#define USE_PZEM004T // Add support for PZEM004T Energy monitor (+2k code) +#define USE_SERIAL_BRIDGE // Add support for software Serial Bridge (+0k8 code) +#define USE_IR_REMOTE // Send IR remote commands using library IRremoteESP8266 and ArduinoJson (+4k code, 0k3 mem, 48 iram) + #define USE_IR_HVAC // Support for HVAC system using IR (+2k code) + #define USE_IR_RECEIVE // Support for IR receiver (+5k5 code, 264 iram) +#define USE_WS2812 // WS2812 Led string using library NeoPixelBus (+5k code, +1k mem, 232 iram) - Disable by // +#ifndef USE_WS2812_CTYPE + #define USE_WS2812_CTYPE NEO_GRB // WS2812 Color type (NEO_RGB, NEO_GRB, NEO_BRG, NEO_RBG, NEO_RGBW, NEO_GRBW) +#endif +// #define USE_WS2812_DMA // DMA supports only GPIO03 (= Serial RXD) (+1k mem). When USE_WS2812_DMA is enabled expect Exceptions on Pow +#define USE_ARILUX_RF // Add support for Arilux RF remote controller (+0k8 code, 252 iram (non 2.3.0)) +#define USE_SR04 // Add support for HC-SR04 ultrasonic devices (+1k code) +#endif // USE_ALL_SENSORS + +/*********************************************************************************************\ + * [sonoff-classic.bin] + * Provide an image close to version 5.12.0 but still within 499k program space to allow one time OTA +\*********************************************************************************************/ + +#ifdef USE_CLASSIC +#ifdef USE_KNX +#undef USE_KNX +#endif +#ifdef USE_TIMERS +#undef USE_TIMERS +#endif +#ifdef USE_TIMERS_WEB +#undef USE_TIMERS_WEB +#endif +#ifdef USE_SUNRISE +#undef USE_SUNRISE +#endif +#ifdef USE_RULES +#undef USE_RULES +#endif +#ifdef USE_SGP30 +#undef USE_SGP30 +#endif +#ifdef USE_NOVA_SDS +#undef USE_NOVA_SDS +#endif +#ifdef USE_IR_RECEIVE +#undef USE_IR_RECEIVE +#endif +#ifdef USE_SERIAL_BRIDGE +#undef USE_SERIAL_BRIDGE +#endif +#ifdef USE_SR04 +#undef USE_SR04 +#endif +#endif // USE_CLASSIC + +/*********************************************************************************************\ + * [sonoff-knx.bin] + * Provide a dedicated KNX image allowing enough code and memory space +\*********************************************************************************************/ + +#ifdef USE_KNX_NO_EMULATION +#ifndef USE_KNX +#define USE_KNX // Enable KNX IP Protocol Support (+23k code, +3k3 mem) +#endif +#ifdef USE_EMULATION +#undef USE_EMULATION // Disable Belkin WeMo and Hue Bridge emulation for Alexa (-16k code, -2k mem) +#endif +#endif // USE_KNX_NO_EMULATION + +/*********************************************************************************************\ + * Mandatory define for DS18x20 if changed by above image selections +\*********************************************************************************************/ #if defined(USE_DS18x20) || defined(USE_DS18x20_LEGACY) #else -#define USE_DS18B20 // Default DS18B20 sensor needs no external library +#define USE_DS18B20 // Default DS18B20 sensor needs no external library #endif -//#define DEBUG_THEO // Add debug code +/*********************************************************************************************\ + * [sonoff-minimal.bin] + * Provide the smallest image possible while still enabling a webserver for intermediate image load +\*********************************************************************************************/ #ifdef BE_MINIMAL #ifdef USE_MQTT_TLS -#undef USE_MQTT_TLS // Disable TLS support won't work as the MQTTHost is not set +#undef USE_MQTT_TLS // Disable TLS support won't work as the MQTTHost is not set #endif #ifdef USE_DISCOVERY -#undef USE_DISCOVERY // Disable Discovery services for both MQTT and web server +#undef USE_DISCOVERY // Disable Discovery services for both MQTT and web server #endif #ifdef USE_DOMOTICZ -#undef USE_DOMOTICZ // Disable Domoticz +#undef USE_DOMOTICZ // Disable Domoticz #endif #ifdef USE_HOME_ASSISTANT -#undef USE_HOME_ASSISTANT // Disable Home Assistant +#undef USE_HOME_ASSISTANT // Disable Home Assistant +#endif +#ifdef USE_KNX +#undef USE_KNX // Disable KNX IP Protocol Support #endif //#ifdef USE_WEBSERVER -//#undef USE_WEBSERVER // Disable Webserver +//#undef USE_WEBSERVER // Disable Webserver //#endif #ifdef USE_EMULATION -#undef USE_EMULATION // Disable Wemo or Hue emulation +#undef USE_EMULATION // Disable Wemo or Hue emulation #endif -#ifdef USE_PZEM004T -#undef USE_PZEM004T // Disable PZEM004T energy sensor +#ifdef USE_TIMERS +#undef USE_TIMERS // Disable support for up to 16 timers #endif -#ifdef USE_DS18x20 -#undef USE_DS18x20 // Disable DS18x20 sensor +#ifdef USE_SUNRISE +#undef USE_SUNRISE // Disable support for Sunrise and sunset tools #endif -#ifdef USE_I2C -#undef USE_I2C // Disable all I2C sensors and devices -#endif -#ifdef USE_SPI -#undef USE_SPI // Disable all SPI devices -#endif -#ifdef USE_WS2812 -#undef USE_WS2812 // Disable WS2812 Led string -#endif -#ifdef USE_DS18B20 -#undef USE_DS18B20 // Disable internal DS18B20 sensor +#ifdef USE_RULES +#undef USE_RULES // Disable support for rules #endif #ifdef USE_DHT -#undef USE_DHT // Disable internal DHT sensor +#undef USE_DHT // Disable internal DHT sensor +#endif +#ifdef USE_DS18x20 +#undef USE_DS18x20 // Disable DS18x20 sensor +#endif +#ifdef USE_DS18B20 +#undef USE_DS18B20 // Disable internal DS18B20 sensor +#endif +#ifdef USE_I2C +#undef USE_I2C // Disable all I2C sensors and devices +#endif +#ifdef USE_SPI +#undef USE_SPI // Disable all SPI devices #endif #ifdef USE_DISPLAY -#undef USE_DISPLAY // Disable Display support +#undef USE_DISPLAY // Disable Display support #endif #ifdef USE_MHZ19 -#undef USE_MHZ19 // Disable support for MH-Z19 CO2 sensor +#undef USE_MHZ19 // Disable support for MH-Z19 CO2 sensor #endif #ifdef USE_SENSEAIR -#undef USE_SENSEAIR // Disable support for SenseAir K30, K70 and S8 CO2 sensor +#undef USE_SENSEAIR // Disable support for SenseAir K30, K70 and S8 CO2 sensor +#endif +#ifdef USE_PMS5003 +#undef USE_PMS5003 // Disable support for PMS5003 and PMS7003 particle concentration sensor +#endif +#ifdef USE_NOVA_SDS +#undef USE_NOVA_SDS // Disable support for SDS011 and SDS021 particle concentration sensor +#endif +#ifdef USE_PZEM004T +#undef USE_PZEM004T // Disable PZEM004T energy sensor +#endif +#ifdef USE_SERIAL_BRIDGE +#undef USE_SERIAL_BRIDGE // Disable support for software Serial Bridge #endif #ifdef USE_IR_REMOTE -#undef USE_IR_REMOTE // Disable IR driver +#undef USE_IR_REMOTE // Disable IR driver +#endif +#ifdef USE_WS2812 +#undef USE_WS2812 // Disable WS2812 Led string #endif #ifdef USE_ARILUX_RF -#undef USE_ARILUX_RF // Disable support for Arilux RF remote controller +#undef USE_ARILUX_RF // Disable support for Arilux RF remote controller +#endif +#ifdef USE_SR04 +#undef USE_SR04 // Disable support for for HC-SR04 ultrasonic devices #endif #ifdef DEBUG_THEO -#undef DEBUG_THEO // Disable debug code +#undef DEBUG_THEO // Disable debug code #endif #endif // BE_MINIMAL +/*********************************************************************************************\ + * Mandatory defines satisfying possible disabled defines +\*********************************************************************************************/ + #ifndef SWITCH_MODE -#define SWITCH_MODE TOGGLE // TOGGLE, FOLLOW or FOLLOW_INV (the wall switch state) +#define SWITCH_MODE TOGGLE // TOGGLE, FOLLOW or FOLLOW_INV (the wall switch state) #endif -#ifndef MQTT_FINGERPRINT -#define MQTT_FINGERPRINT "A5 02 FF 13 99 9F 8B 39 8E F1 83 4F 11 23 65 0B 32 36 FC 07" +#ifndef MQTT_FINGERPRINT1 +#define MQTT_FINGERPRINT1 "A5 02 FF 13 99 9F 8B 39 8E F1 83 4F 11 23 65 0B 32 36 FC 07" +#endif + +#ifndef MQTT_FINGERPRINT2 +#define MQTT_FINGERPRINT2 "A5 02 FF 13 99 9F 8B 39 8E F1 83 4F 11 23 65 0B 32 36 FC 07" #endif #ifndef WS2812_LEDS -#define WS2812_LEDS 30 // [Pixels] Number of LEDs +#define WS2812_LEDS 30 // [Pixels] Number of LEDs +#endif + +#ifndef MQTT_MAX_PACKET_SIZE +#define MQTT_MAX_PACKET_SIZE 1000 +#endif +#ifndef MQTT_KEEPALIVE +#define MQTT_KEEPALIVE 15 #endif #ifndef MESSZ @@ -122,7 +280,7 @@ void WifiWpsStatusCallback(wps_cb_status status); //#include // Arduino_Esp8266 version information (ARDUINO_ESP8266_RELEASE and ARDUINO_ESP8266_RELEASE_2_3_0) #ifndef ARDUINO_ESP8266_RELEASE -#define ARDUINO_ESP8266_RELEASE "STAGED" +#define ARDUINO_ESP8266_RELEASE "STAGE" #endif -#endif // _SONOFF_POST_H_ \ No newline at end of file +#endif // _SONOFF_POST_H_ diff --git a/sonoff/sonoff_template.h b/sonoff/sonoff_template.h index fcc041537..dc0746ec7 100644 --- a/sonoff/sonoff_template.h +++ b/sonoff/sonoff_template.h @@ -88,6 +88,11 @@ enum UserSelectablePins { GPIO_SPI_DC, // SPI Data Direction GPIO_BACKLIGHT, // Display backlight control GPIO_PMS5003, // Plantower PMS5003 Serial interface + GPIO_SDS0X1, // Nova Fitness SDS011 Serial interface + GPIO_SBR_TX, // Serial Bridge Serial interface + GPIO_SBR_RX, // Serial Bridge Serial interface + GPIO_SR04_TRIG, // SR04 Trigger pin + GPIO_SR04_ECHO, // SR04 Echo pin GPIO_SENSOR_END }; // Programmer selectable GPIO functionality offset by user selectable GPIOs @@ -129,7 +134,9 @@ const char kSensorNames[] PROGMEM = D_SENSOR_PZEM_TX "|" D_SENSOR_PZEM_RX "|" D_SENSOR_SAIR_TX "|" D_SENSOR_SAIR_RX "|" D_SENSOR_SPI_CS "|" D_SENSOR_SPI_DC "|" D_SENSOR_BACKLIGHT "|" - D_SENSOR_PMS5003; + D_SENSOR_PMS5003 "|" D_SENSOR_SDS0X1 "|" + D_SENSOR_SBR_TX "|" D_SENSOR_SBR_RX "|" + D_SENSOR_SR04_TRIG "|" D_SENSOR_SR04_ECHO; /********************************************************************************************/ @@ -176,6 +183,8 @@ enum SupportedModules { SONOFF_DUAL_R2, ARILUX_LC06, SONOFF_S31, + ZENGGE_ZF_WF017, + SONOFF_POW_R2, MAXMODULE }; /********************************************************************************************/ @@ -200,6 +209,7 @@ const uint8_t kNiceList[MAXMODULE] PROGMEM = { SONOFF_DUAL, SONOFF_DUAL_R2, SONOFF_POW, + SONOFF_POW_R2, SONOFF_S31, SONOFF_4CH, SONOFF_4CHPRO, @@ -230,6 +240,7 @@ const uint8_t kNiceList[MAXMODULE] PROGMEM = { ARILUX_LC01, ARILUX_LC06, ARILUX_LC11, + ZENGGE_ZF_WF017, HUAFAN_SS, KMC_70011, AILIGHT, @@ -312,7 +323,7 @@ const mytmplt kModules[MAXMODULE] PROGMEM = { GPIO_USER, // GPIO14 Optional sensor 0, 0, 0 }, - { "Sonoff Pow", // Sonoff Pow (ESP8266) + { "Sonoff Pow", // Sonoff Pow (ESP8266 - HLW8012) GPIO_KEY1, // GPIO00 Button 0, 0, 0, 0, GPIO_HLW_SEL, // GPIO05 HLW8012 Sel output @@ -320,7 +331,7 @@ const mytmplt kModules[MAXMODULE] PROGMEM = { GPIO_REL1, // GPIO12 Red Led and Relay (0 = Off, 1 = On) GPIO_HLW_CF1, // GPIO13 HLW8012 CF1 voltage / current GPIO_HLW_CF, // GPIO14 HLW8012 CF power - GPIO_LED1, // GPIO15 Green Led (0 = On, 1 = Off) + GPIO_LED1, // GPIO15 Blue Led (0 = On, 1 = Off) 0, 0 }, { "Sonoff 4CH", // Sonoff 4CH (ESP8285) @@ -481,23 +492,23 @@ const mytmplt kModules[MAXMODULE] PROGMEM = { GPIO_USER, // GPIO05 Optional sensor 0, 0, 0, 0, 0, 0, // Flash connection GPIO_USER, // GPIO12 - GPIO_LED1_INV, // GPIO13 BLUE LED + GPIO_USER, // GPIO13 BLUE LED GPIO_USER, // GPIO14 Optional sensor 0, // GPIO15 0, // GPIO16 GPIO_ADC0 // ADC0 A0 Analog input }, { "H801", // Lixada H801 Wifi (ESP8266) - GPIO_KEY1, // GPIO00 E-FW Button + GPIO_USER, // GPIO00 E-FW Button GPIO_LED1, // GPIO01 Green LED GPIO_TXD, // GPIO02 RX - Pin next to TX on the PCB GPIO_RXD, // GPIO03 TX - Pin next to GND on the PCB - GPIO_USER, // GPIO04 W2 - PWM5 + GPIO_PWM5, // GPIO04 W2 - PWM5 GPIO_LED2_INV, // GPIO05 Red LED 0, 0, 0, 0, 0, 0, // Flash connection GPIO_PWM3, // GPIO12 Blue GPIO_PWM2, // GPIO13 Green - GPIO_USER, // GPIO14 W1 - PWM4 + GPIO_PWM4, // GPIO14 W1 - PWM4 GPIO_PWM1, // GPIO15 Red 0, 0 }, @@ -597,7 +608,7 @@ const mytmplt kModules[MAXMODULE] PROGMEM = { { "Sonoff T1 1CH", // Sonoff T1 1CH (ESP8285) GPIO_KEY1, // GPIO00 Button 1 GPIO_USER, // GPIO01 Serial RXD and Optional sensor - 0, + GPIO_USER, // GPIO02 Optional Sensor (J3 Pin 5) GPIO_USER, // GPIO03 Serial TXD and Optional sensor 0, 0, 0, 0, 0, // Flash connection @@ -610,7 +621,7 @@ const mytmplt kModules[MAXMODULE] PROGMEM = { { "Sonoff T1 2CH", // Sonoff T1 2CH (ESP8285) GPIO_KEY1, // GPIO00 Button 1 GPIO_USER, // GPIO01 Serial RXD and Optional sensor - 0, + GPIO_USER, // GPIO02 Optional Sensor (J3 Pin 5) GPIO_USER, // GPIO03 Serial TXD and Optional sensor 0, GPIO_REL2, // GPIO05 Blue Led and Relay 2 (0 = Off, 1 = On) @@ -625,7 +636,7 @@ const mytmplt kModules[MAXMODULE] PROGMEM = { { "Sonoff T1 3CH", // Sonoff T1 3CH (ESP8285) GPIO_KEY1, // GPIO00 Button 1 GPIO_USER, // GPIO01 Serial RXD and Optional sensor - 0, + GPIO_USER, // GPIO02 Optional Sensor (J3 Pin 5) GPIO_USER, // GPIO03 Serial TXD and Optional sensor GPIO_REL3, // GPIO04 Blue Led and Relay 3 (0 = Off, 1 = On) GPIO_REL2, // GPIO05 Blue Led and Relay 2 (0 = Off, 1 = On) @@ -679,9 +690,10 @@ const mytmplt kModules[MAXMODULE] PROGMEM = { 0, 0, 0, 0, 0 }, { "MagicHome", // Magic Home (aka Flux-light) (ESP8266) - https://www.aliexpress.com/item/Magic-Home-Mini-RGB-RGBW-Wifi-Controller-For-Led-Strip-Panel-light-Timing-Function-16million-colors/32686853650.html - 0, 0, - GPIO_LED1_INV, // GPIO02 Blue onboard LED 0, + GPIO_USER, // GPIO01 Serial RXD and Optional sensor + GPIO_LED1_INV, // GPIO02 Blue onboard LED + GPIO_USER, // GPIO03 Serial TXD and Optional sensor GPIO_USER, // GPIO04 IR receiver (optional) GPIO_PWM2, // GPIO05 RGB LED Green 0, 0, 0, 0, 0, 0, // Flash connection @@ -719,9 +731,9 @@ const mytmplt kModules[MAXMODULE] PROGMEM = { { "Arilux LC01", // Arilux AL-LC01 (ESP8285) - https://www.banggood.com/nl/ARILUX-AL-LC01-Super-Mini-LED-WIFI-Smart-RGB-Controller-For-RGB-LED-Strip-Light-DC-9-12V-p-1058603.html // (PwmFrequency 1111Hz) GPIO_KEY1, // GPIO00 Optional Button - 0, + GPIO_USER, // GPIO01 Serial RXD and Optional sensor GPIO_LED2_INV, // GPIO02 RF receiver control - 0, + GPIO_USER, // GPIO03 Serial TXD and Optional sensor GPIO_ARIRFRCV, // GPIO04 IR or RF receiver (optional) GPIO_PWM1, // GPIO05 RGB LED Red 0, 0, 0, 0, 0, 0, // Flash connection @@ -733,9 +745,9 @@ const mytmplt kModules[MAXMODULE] PROGMEM = { { "Arilux LC11", // Arilux AL-LC11 (ESP8266) - https://www.banggood.com/nl/ARILUX-AL-LC11-Super-Mini-LED-WIFI-APP-Controller-RF-Remote-Control-For-RGBWW-LED-Strip-DC9-28V-p-1085112.html // (PwmFrequency 540Hz) GPIO_KEY1, // GPIO00 Optional Button - 0, + GPIO_USER, // GPIO01 Serial RXD and Optional sensor GPIO_LED2_INV, // GPIO02 RF receiver control - 0, + GPIO_USER, // GPIO03 Serial TXD and Optional sensor GPIO_PWM2, // GPIO04 RGB LED Green GPIO_PWM1, // GPIO05 RGB LED Red 0, 0, 0, 0, 0, 0, // Flash connection @@ -762,9 +774,9 @@ const mytmplt kModules[MAXMODULE] PROGMEM = { }, { "Arilux LC06", // Arilux AL-LC06 (ESP8285) - https://www.banggood.com/ARILUX-AL-LC06-LED-WIFI-Smartphone-Controller-Romote-5-Channels-DC12-24V-For-RGBWW-Strip-light-p-1061476.html GPIO_KEY1, // GPIO00 Optional Button - 0, + GPIO_USER, // GPIO01 Serial RXD and Optional sensor GPIO_USER, // GPIO02 Empty pad - 0, + GPIO_USER, // GPIO03 Serial TXD and Optional sensor GPIO_USER, // GPIO04 W2 - PWM5 0, 0, 0, 0, 0, 0, 0, // Flash connection @@ -774,7 +786,7 @@ const mytmplt kModules[MAXMODULE] PROGMEM = { GPIO_USER, // GPIO15 RGBW LED White 0, 0 }, - { "Sonoff S31", // Sonoff S31 (ESP8266) + { "Sonoff S31", // Sonoff S31 (ESP8266 - CSE7766) GPIO_KEY1, // GPIO00 Button 0, // GPIO01 Serial RXD 4800 baud 8E1 CSE7766 energy sensor 0, @@ -784,6 +796,30 @@ const mytmplt kModules[MAXMODULE] PROGMEM = { GPIO_REL1, // GPIO12 Red Led and Relay (0 = Off, 1 = On) GPIO_LED1_INV, // GPIO13 Green Led (0 = On, 1 = Off) 0, 0, 0, 0 + }, + { "Zengge WF017", // Zenggee ZJ-WF017-A (ESP12S)) - https://www.ebay.com/p/Smartphone-Android-IOS-WiFi-Music-Controller-for-RGB-5050-3528-LED-Strip-Light/534446632?_trksid=p2047675.l2644 + GPIO_KEY1, // GPIO00 Optional Button + 0, + GPIO_USER, // GPIO02 Empty pad + 0, + GPIO_USER, // GPIO04 W2 - PWM5 + 0, + 0, 0, 0, 0, 0, 0, // Flash connection + GPIO_PWM2, // GPIO12 RGB LED Green + GPIO_PWM1, // GPIO13 RGB LED Red + GPIO_PWM3, // GPIO14 RGB LED Blue + 0, 0, 0 + }, + { "Sonoff Pow R2", // Sonoff Pow R2 (ESP8285 - CSE7766) + GPIO_KEY1, // GPIO00 Button + 0, // GPIO01 Serial RXD 4800 baud 8E1 CSE7766 energy sensor + 0, + 0, // GPIO03 Serial TXD + 0, 0, + 0, 0, 0, 0, 0, 0, // Flash connection + GPIO_REL1, // GPIO12 Red Led and Relay (0 = Off, 1 = On) + GPIO_LED1_INV, // GPIO13 Blue Led (0 = On, 1 = Off) + 0, 0, 0, 0 } }; @@ -814,20 +850,6 @@ const mytmplt kModules[MAXMODULE] PROGMEM = { 0, 0 } - { "Zengge WF017", // Zenggee ZJ-WF017-A (ESP12S)) - https://www.ebay.com/p/Smartphone-Android-IOS-WiFi-Music-Controller-for-RGB-5050-3528-LED-Strip-Light/534446632?_trksid=p2047675.l2644 - GPIO_KEY1, // GPIO00 Optional Button - 0, - GPIO_USER, // GPIO02 Empty pad - 0, - GPIO_USER, // GPIO04 W2 - PWM5 - 0, - 0, 0, 0, 0, 0, 0, // Flash connection - GPIO_PWM2, // GPIO12 RGB LED Green - GPIO_PWM1, // GPIO13 RGB LED Red - GPIO_PWM3, // GPIO14 RGB LED Blue - 0, 0, 0 - } - { "SMPW701E", // SM-PW701E WLAN Socket (#1190) 0, 0, 0, 0, GPIO_LED1_INV, // GPIO04 Blue Led (0 = On, 1 = Off) @@ -864,6 +886,22 @@ const mytmplt kModules[MAXMODULE] PROGMEM = { 0, GPIO_PWM4, // GPIO15 RGBW LED White 0, 0 + } + + { "Ledunia", // Ledunia (ESP8266) - http://ledunia.de/ + GPIO_USER, // GPIO00 (D0) + GPIO_USER, // GPIO01 (D7) Serial RXD + GPIO_USER, // GPIO02 (D2) + GPIO_USER, // GPIO03 (D8) Serial TXD + GPIO_USER, // GPIO04 (D4) 4 x WS2812 Leds, (DOUT) Extents WS2812 string + GPIO_USER, // GPIO05 (D5) Blue Led + 0, 0, 0, 0, 0, 0, // Flash connection + GPIO_USER, // GPIO12 (D12) + GPIO_USER, // GPIO13 (D13) + GPIO_USER, // GPIO14 (D14) + GPIO_USER, // GPIO15 (D15) + GPIO_USER, // GPIO16 (D16) + 0 // ADC0 Analog input (A0) }, */ diff --git a/sonoff/support.ino b/sonoff/support.ino index b1196f7f1..a33c81a1a 100644 --- a/sonoff/support.ino +++ b/sonoff/support.ino @@ -17,8 +17,8 @@ along with this program. If not, see . */ -IPAddress syslog_host_addr; // Syslog host IP address -unsigned long syslog_host_refresh = 0; +IPAddress syslog_host_addr; // Syslog host IP address +uint32_t syslog_host_hash = 0; // Syslog host name hash /*********************************************************************************************\ * Watchdog extension (https://github.com/esp8266/Arduino/issues/1532) @@ -78,72 +78,6 @@ String GetResetReason() } } -#ifdef DEBUG_THEO -void ExceptionTest(byte type) -{ -/* -Exception (28): -epc1=0x4000bf64 epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000007 depc=0x00000000 - -ctx: cont -sp: 3fff1f30 end: 3fff2840 offset: 01a0 - ->>>stack>>> -3fff20d0: 202c3573 756f7247 2c302070 646e4920 -3fff20e0: 40236a6e 7954202c 45206570 00454358 -3fff20f0: 00000010 00000007 00000000 3fff2180 -3fff2100: 3fff2190 40107bfc 3fff3e4c 3fff22c0 -3fff2110: 40261934 000000f0 3fff22c0 401004d8 -3fff2120: 40238fcf 00000050 3fff2100 4021fc10 -3fff2130: 3fff32bc 4021680c 3ffeade1 4021ff7d -3fff2140: 3fff2190 3fff2180 0000000c 7fffffff -3fff2150: 00000019 00000000 00000000 3fff21c0 -3fff2160: 3fff23f3 3ffe8e08 00000000 4021ffb4 -3fff2170: 3fff2190 3fff2180 0000000c 40201118 -3fff2180: 3fff21c0 0000003c 3ffef840 00000007 -3fff2190: 00000000 00000000 00000000 40201128 -3fff21a0: 3fff23f3 000000f1 3fff23ec 4020fafb -3fff21b0: 3fff23f3 3fff21c0 3fff21d0 3fff23f6 -3fff21c0: 00000000 3fff23fb 4022321b 00000000 - -Exception 28: LoadProhibited: A load referenced a page mapped with an attribute that does not permit loads -Decoding 14 results -0x40236a6e: ets_vsnprintf at ?? line ? -0x40107bfc: vsnprintf at C:\Data2\Arduino\arduino-1.8.1-esp-2.3.0\portable\packages\esp8266\hardware\esp8266\2.3.0\cores\esp8266/libc_replacements.c line 387 -0x40261934: bignum_exptmod at ?? line ? -0x401004d8: malloc at C:\Data2\Arduino\arduino-1.8.1-esp-2.3.0\portable\packages\esp8266\hardware\esp8266\2.3.0\cores\esp8266\umm_malloc/umm_malloc.c line 1664 -0x40238fcf: wifi_station_get_connect_status at ?? line ? -0x4021fc10: operator new[](unsigned int) at C:\Data2\Arduino\arduino-1.8.1-esp-2.3.0\portable\packages\esp8266\hardware\esp8266\2.3.0\cores\esp8266/abi.cpp line 57 -0x4021680c: ESP8266WiFiSTAClass::status() at C:\Data2\Arduino\arduino-1.8.1-esp-2.3.0\portable\packages\esp8266\hardware\esp8266\2.3.0\libraries\ESP8266WiFi\src/ESP8266WiFiSTA.cpp line 569 -0x4021ff7d: vsnprintf_P(char*, unsigned int, char const*, __va_list_tag) at C:\Data2\Arduino\arduino-1.8.1-esp-2.3.0\portable\packages\esp8266\hardware\esp8266\2.3.0\cores\esp8266/pgmspace.cpp line 146 -0x4021ffb4: snprintf_P(char*, unsigned int, char const*, ...) at C:\Data2\Arduino\arduino-1.8.1-esp-2.3.0\portable\packages\esp8266\hardware\esp8266\2.3.0\cores\esp8266/pgmspace.cpp line 146 -0x40201118: atol at C:\Data2\Arduino\arduino-1.8.1-esp-2.3.0\portable\packages\esp8266\hardware\esp8266\2.3.0\cores\esp8266/core_esp8266_noniso.c line 45 -0x40201128: atoi at C:\Data2\Arduino\arduino-1.8.1-esp-2.3.0\portable\packages\esp8266\hardware\esp8266\2.3.0\cores\esp8266/core_esp8266_noniso.c line 45 -0x4020fafb: MqttDataCallback(char*, unsigned char*, unsigned int) at R:\Arduino\Work-ESP8266\Theo\sonoff\sonoff-4\sonoff/sonoff.ino line 679 (discriminator 1) -0x4022321b: pp_attach at ?? line ? - -00:00:08 MQTT: tele/sonoff/INFO3 = {"Started":"Fatal exception:28 flag:2 (EXCEPTION) epc1:0x4000bf64 epc2:0x00000000 epc3:0x00000000 excvaddr:0x00000007 depc:0x00000000"} -*/ - if (1 == type) { - char svalue[10]; - snprintf_P(svalue, sizeof(svalue), PSTR("%s"), 7); // Exception 28 as number in string (7 in excvaddr) - } -/* -14:50:52 osWatch: FreeRam 25896, rssi 68, last_run 0 -14:51:02 osWatch: FreeRam 25896, rssi 58, last_run 0 -14:51:03 CMND: exception 2 -14:51:12 osWatch: FreeRam 25360, rssi 60, last_run 8771 -14:51:22 osWatch: FreeRam 25360, rssi 62, last_run 18771 -14:51:32 osWatch: FreeRam 25360, rssi 62, last_run 28771 -14:51:42 osWatch: FreeRam 25360, rssi 62, last_run 38771 -14:51:42 osWatch: Warning, loop blocked. Restart now -*/ - if (2 == type) { - while(1) delay(1000); // this will trigger the os watch - } -} -#endif // DEBUG_THEO - /*********************************************************************************************\ * Miscellaneous \*********************************************************************************************/ @@ -192,11 +126,125 @@ size_t strchrspn(const char *str1, int character) return ret; } +double CharToDouble(char *str) +{ + // simple ascii to double, because atof or strtod are too large + char strbuf[24]; + + strcpy(strbuf, str); + char *pt; + double left = atoi(strbuf); + double right = 0; + short len = 0; + pt = strtok (strbuf, "."); + if (pt) { + pt = strtok (NULL, "."); + if (pt) { + right = atoi(pt); + len = strlen(pt); + double fac = 1; + while (len) { + fac /= 10.0; + len--; + } + // pow is also very large + //double fac=pow(10,-len); + right *= fac; + } + } + double result = left + right; + if (left < 0) { result = left - right; } + return result; +} + char* dtostrfd(double number, unsigned char prec, char *s) { return dtostrf(number, 1, prec, s); } +char* Unescape(char* buffer, uint16_t* size) +{ + uint8_t* read = (uint8_t*)buffer; + uint8_t* write = (uint8_t*)buffer; + uint16_t start_size = *size; + uint16_t end_size = *size; + uint8_t che = 0; + + while (start_size > 0) { + uint8_t ch = *read++; + start_size--; + if (ch != '\\') { + *write++ = ch; + } else { + if (start_size > 0) { + uint8_t chi = *read++; + start_size--; + end_size--; + switch (chi) { + case '\\': che = '\\'; break; // 5C Backslash + case 'a': che = '\a'; break; // 07 Bell (Alert) + case 'b': che = '\b'; break; // 08 Backspace + case 'e': che = '\e'; break; // 1B Escape + case 'f': che = '\f'; break; // 0C Formfeed + case 'n': che = '\n'; break; // 0A Linefeed (Newline) + case 'r': che = '\r'; break; // 0D Carriage return + case 's': che = ' '; break; // 20 Space + case 't': che = '\t'; break; // 09 Horizontal tab + case 'v': che = '\v'; break; // 0B Vertical tab +// case '?': che = '\?'; break; // 3F Question mark + default : { + che = chi; + *write++ = ch; + end_size++; + } + } + *write++ = che; + } + } + } + *size = end_size; + return buffer; +} + +char* UpperCase(char* dest, const char* source) +{ + char* write = dest; + const char* read = source; + char ch = '.'; + + while (ch != '\0') { + ch = *read++; + *write++ = toupper(ch); + } + return dest; +} + +char* UpperCase_P(char* dest, const char* source) +{ + char* write = dest; + const char* read = source; + char ch = '.'; + + while (ch != '\0') { + ch = pgm_read_byte(read++); + *write++ = toupper(ch); + } + return dest; +} + +char* NoAlNumToUnderscore(char* dest, const char* source) +{ + char* write = dest; + const char* read = source; + char ch = '.'; + + while (ch != '\0') { + ch = *read++; + *write++ = (isalnum(ch) || ('\0' == ch)) ? ch : '_'; + } + return dest; +} + boolean ParseIp(uint32_t* addr, const char* str) { uint8_t *part = (uint8_t*)addr; @@ -401,6 +449,7 @@ int GetCommandCode(char* destination, size_t destination_size, const char* needl void SetSerialBaudrate(int baudrate) { + Settings.baudrate = baudrate / 1200; if (Serial.baudRate() != baudrate) { if (seriallog_level) { snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_APPLICATION D_SET_BAUDRATE_TO " %d"), baudrate); @@ -414,15 +463,25 @@ void SetSerialBaudrate(int baudrate) } } +uint32_t GetHash(const char *buffer, size_t size) +{ + uint32_t hash = 0; + for (uint16_t i = 0; i <= size; i++) { + hash += (uint8_t)*buffer++ * (i +1); + } + return hash; +} + /*********************************************************************************************\ * Wifi \*********************************************************************************************/ -#define WIFI_CONFIG_SEC 180 // seconds before restart -#define WIFI_CHECK_SEC 20 // seconds -#define WIFI_RETRY_SEC 30 // seconds +#define WIFI_CONFIG_SEC 180 // seconds before restart +#define WIFI_CHECK_SEC 20 // seconds +#define WIFI_RETRY_OFFSET_SEC 20 // seconds uint8_t wifi_counter; +uint8_t wifi_retry_init; uint8_t wifi_retry; uint8_t wifi_status; uint8_t wps_result; @@ -507,7 +566,7 @@ void WifiConfig(uint8_t type) if (type >= WIFI_RETRY) { // WIFI_RETRY and WIFI_WAIT return; } -#ifdef USE_EMULATION +#if defined(USE_WEBSERVER) && defined(USE_EMULATION) UdpDisconnect(); #endif // USE_EMULATION WiFi.disconnect(); // Solve possible Wifi hangs @@ -519,20 +578,20 @@ void WifiConfig(uint8_t type) restart_flag = 2; } else if (WIFI_SMARTCONFIG == wifi_config_type) { - AddLog_P(LOG_LEVEL_INFO, S_LOG_WIFI, PSTR(D_WCFG_1_SMARTCONFIG D_ACTIVE_FOR_3_MINUTES)); + AddLog_P(LOG_LEVEL_INFO, S_LOG_WIFI, PSTR(D_WCFG_1_SMARTCONFIG " " D_ACTIVE_FOR_3_MINUTES)); WiFi.beginSmartConfig(); } else if (WIFI_WPSCONFIG == wifi_config_type) { if (WifiWpsConfigBegin()) { - AddLog_P(LOG_LEVEL_INFO, S_LOG_WIFI, PSTR(D_WCFG_3_WPSCONFIG D_ACTIVE_FOR_3_MINUTES)); + AddLog_P(LOG_LEVEL_INFO, S_LOG_WIFI, PSTR(D_WCFG_3_WPSCONFIG " " D_ACTIVE_FOR_3_MINUTES)); } else { - AddLog_P(LOG_LEVEL_INFO, S_LOG_WIFI, PSTR(D_WCFG_3_WPSCONFIG D_FAILED_TO_START)); + AddLog_P(LOG_LEVEL_INFO, S_LOG_WIFI, PSTR(D_WCFG_3_WPSCONFIG " " D_FAILED_TO_START)); wifi_config_counter = 3; } } #ifdef USE_WEBSERVER else if (WIFI_MANAGER == wifi_config_type) { - AddLog_P(LOG_LEVEL_INFO, S_LOG_WIFI, PSTR(D_WCFG_2_WIFIMANAGER D_ACTIVE_FOR_3_MINUTES)); + AddLog_P(LOG_LEVEL_INFO, S_LOG_WIFI, PSTR(D_WCFG_2_WIFIMANAGER " " D_ACTIVE_FOR_3_MINUTES)); WifiManagerBegin(); } #endif // USE_WEBSERVER @@ -543,19 +602,22 @@ void WifiBegin(uint8_t flag) { const char kWifiPhyMode[] = " BGN"; -#ifdef USE_EMULATION +#if defined(USE_WEBSERVER) && defined(USE_EMULATION) UdpDisconnect(); #endif // USE_EMULATION #ifdef ARDUINO_ESP8266_RELEASE_2_3_0 // (!strncmp_P(ESP.getSdkVersion(),PSTR("1.5.3"),5)) AddLog_P(LOG_LEVEL_DEBUG, S_LOG_WIFI, PSTR(D_PATCH_ISSUE_2186)); - WiFi.mode(WIFI_OFF); // See https://github.com/esp8266/Arduino/issues/2186 + WiFi.mode(WIFI_OFF); // See https://github.com/esp8266/Arduino/issues/2186 #endif - WiFi.disconnect(); + WiFi.disconnect(true); // Delete SDK wifi config + delay(200); WiFi.mode(WIFI_STA); // Disable AP mode if (Settings.sleep) { +#ifndef ARDUINO_ESP8266_RELEASE_2_4_1 // See https://github.com/arendst/Sonoff-Tasmota/issues/2559 WiFi.setSleepMode(WIFI_LIGHT_SLEEP); // Allow light sleep during idle times +#endif } // if (WiFi.getPhyMode() != WIFI_PHY_MODE_11N) { // WiFi.setPhyMode(WIFI_PHY_MODE_11N); @@ -589,7 +651,7 @@ void WifiCheckIp() { if ((WL_CONNECTED == WiFi.status()) && (static_cast(WiFi.localIP()) != 0)) { wifi_counter = WIFI_CHECK_SEC; - wifi_retry = WIFI_RETRY_SEC; + wifi_retry = wifi_retry_init; AddLog_P((wifi_status != WL_CONNECTED) ? LOG_LEVEL_INFO : LOG_LEVEL_DEBUG_MORE, S_LOG_WIFI, PSTR(D_CONNECTED)); if (wifi_status != WL_CONNECTED) { // AddLog_P(LOG_LEVEL_INFO, PSTR("Wifi: Set IP addresses")); @@ -604,15 +666,15 @@ void WifiCheckIp() case WL_CONNECTED: AddLog_P(LOG_LEVEL_INFO, S_LOG_WIFI, PSTR(D_CONNECT_FAILED_NO_IP_ADDRESS)); wifi_status = 0; - wifi_retry = WIFI_RETRY_SEC; + wifi_retry = wifi_retry_init; break; case WL_NO_SSID_AVAIL: AddLog_P(LOG_LEVEL_INFO, S_LOG_WIFI, PSTR(D_CONNECT_FAILED_AP_NOT_REACHED)); if (WIFI_WAIT == Settings.sta_config) { - wifi_retry = WIFI_RETRY_SEC; + wifi_retry = wifi_retry_init; } else { - if (wifi_retry > (WIFI_RETRY_SEC / 2)) { - wifi_retry = WIFI_RETRY_SEC / 2; + if (wifi_retry > (wifi_retry_init / 2)) { + wifi_retry = wifi_retry_init / 2; } else if (wifi_retry) { wifi_retry = 0; @@ -621,25 +683,25 @@ void WifiCheckIp() break; case WL_CONNECT_FAILED: AddLog_P(LOG_LEVEL_INFO, S_LOG_WIFI, PSTR(D_CONNECT_FAILED_WRONG_PASSWORD)); - if (wifi_retry > (WIFI_RETRY_SEC / 2)) { - wifi_retry = WIFI_RETRY_SEC / 2; + if (wifi_retry > (wifi_retry_init / 2)) { + wifi_retry = wifi_retry_init / 2; } else if (wifi_retry) { wifi_retry = 0; } break; default: // WL_IDLE_STATUS and WL_DISCONNECTED - if (!wifi_retry || ((WIFI_RETRY_SEC / 2) == wifi_retry)) { + if (!wifi_retry || ((wifi_retry_init / 2) == wifi_retry)) { AddLog_P(LOG_LEVEL_INFO, S_LOG_WIFI, PSTR(D_CONNECT_FAILED_AP_TIMEOUT)); } else { AddLog_P(LOG_LEVEL_DEBUG, S_LOG_WIFI, PSTR(D_ATTEMPTING_CONNECTION)); } } if (wifi_retry) { - if (WIFI_RETRY_SEC == wifi_retry) { + if (wifi_retry_init == wifi_retry) { WifiBegin(3); // Select default SSID } - if ((Settings.sta_config != WIFI_WAIT) && ((WIFI_RETRY_SEC / 2) == wifi_retry)) { + if ((Settings.sta_config != WIFI_WAIT) && ((wifi_retry_init / 2) == wifi_retry)) { WifiBegin(2); // Select alternate SSID } wifi_counter = 1; @@ -647,7 +709,7 @@ void WifiCheckIp() } else { WifiConfig(Settings.sta_config); wifi_counter = 1; - wifi_retry = WIFI_RETRY_SEC; + wifi_retry = wifi_retry_init; } } } @@ -680,7 +742,7 @@ void WifiCheck(uint8_t param) strlcpy(Settings.sta_pwd[0], WiFi.psk().c_str(), sizeof(Settings.sta_pwd[0])); } Settings.sta_active = 0; - snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_WIFI D_WCFG_1_SMARTCONFIG D_CMND_SSID "1 %s, " D_CMND_PASSWORD "1 %s"), Settings.sta_ssid[0], Settings.sta_pwd[0]); + snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_WIFI D_WCFG_1_SMARTCONFIG D_CMND_SSID "1 %s"), Settings.sta_ssid[0]); AddLog(LOG_LEVEL_INFO); } } @@ -688,6 +750,7 @@ void WifiCheck(uint8_t param) if (WIFI_SMARTCONFIG == wifi_config_type) { WiFi.stopSmartConfig(); } + SettingsSdkErase(); restart_flag = 2; } } else { @@ -728,7 +791,7 @@ void WifiCheck(uint8_t param) #endif // USE_EMULATION #endif // USE_WEBSERVER } else { -#ifdef USE_EMULATION +#if defined(USE_WEBSERVER) && defined(USE_EMULATION) UdpDisconnect(); #endif // USE_EMULATION mdns_begun = false; @@ -754,7 +817,8 @@ void WifiConnect() { WiFi.persistent(false); // Solve possible wifi init errors wifi_status = 0; - wifi_retry = WIFI_RETRY_SEC; + wifi_retry_init = WIFI_RETRY_OFFSET_SEC + ((ESP.getChipId() & 0xF) * 2); + wifi_retry = wifi_retry_init; wifi_counter = 1; } @@ -992,6 +1056,8 @@ uint32_t daylight_saving_time = 0; uint32_t standard_time = 0; uint32_t ntp_time = 0; uint32_t midnight = 1451602800; +uint32_t restart_time = 0; +int16_t time_timezone = 0; // Timezone * 10 uint8_t midnight_now = 0; uint8_t ntp_sync_minute = 0; @@ -1024,27 +1090,44 @@ String GetBuildDateAndTime() return String(bdt); } -String GetDateAndTime() +String GetDateAndTime(byte time_type) { + // enum GetDateAndTimeOptions { DT_LOCAL, DT_UTC, DT_RESTART, DT_UPTIME }; // "2017-03-07T11:08:02" - ISO8601:2004 char dt[21]; - - snprintf_P(dt, sizeof(dt), PSTR("%04d" D_YEAR_MONTH_SEPARATOR "%02d" D_MONTH_DAY_SEPARATOR "%02d" D_DATE_TIME_SEPARATOR "%02d" D_HOUR_MINUTE_SEPARATOR "%02d" D_MINUTE_SECOND_SEPARATOR "%02d"), - RtcTime.year, RtcTime.month, RtcTime.day_of_month, RtcTime.hour, RtcTime.minute, RtcTime.second); - return String(dt); -} - -String GetUtcDateAndTime() -{ - // "2017-03-07T11:08:02" - ISO8601:2004 - char dt[21]; - TIME_T tmpTime; - BreakTime(utc_time, tmpTime); - tmpTime.year += 1970; - snprintf_P(dt, sizeof(dt), PSTR("%04d" D_YEAR_MONTH_SEPARATOR "%02d" D_MONTH_DAY_SEPARATOR "%02d" D_DATE_TIME_SEPARATOR "%02d" D_HOUR_MINUTE_SEPARATOR "%02d" D_MINUTE_SECOND_SEPARATOR "%02d"), - tmpTime.year, tmpTime.month, tmpTime.day_of_month, tmpTime.hour, tmpTime.minute, tmpTime.second); + if (DT_UPTIME == time_type) { + if (restart_time) { + BreakTime(utc_time - restart_time, tmpTime); + } else { + BreakTime(uptime, tmpTime); + } + // "P128DT14H35M44S" - ISO8601:2004 - https://en.wikipedia.org/wiki/ISO_8601 Durations + // snprintf_P(dt, sizeof(dt), PSTR("P%dDT%02dH%02dM%02dS"), ut.days, ut.hour, ut.minute, ut.second); + // "128 14:35:44" - OpenVMS + // "128T14:35:44" - Tasmota + snprintf_P(dt, sizeof(dt), PSTR("%dT%02d:%02d:%02d"), + tmpTime.days, tmpTime.hour, tmpTime.minute, tmpTime.second); + } else { + switch (time_type) { + case DT_UTC: + BreakTime(utc_time, tmpTime); + tmpTime.year += 1970; + break; + case DT_RESTART: + if (restart_time == 0) { + return ""; + } + BreakTime(restart_time, tmpTime); + tmpTime.year += 1970; + break; + default: + tmpTime = RtcTime; + } + snprintf_P(dt, sizeof(dt), PSTR("%04d-%02d-%02dT%02d:%02d:%02d"), + tmpTime.year, tmpTime.month, tmpTime.day_of_month, tmpTime.hour, tmpTime.minute, tmpTime.second); + } return String(dt); } @@ -1053,14 +1136,20 @@ String GetUptime() char dt[16]; TIME_T ut; - BreakTime(uptime, ut); + + if (restart_time) { + BreakTime(utc_time - restart_time, ut); + } else { + BreakTime(uptime, ut); + } // "P128DT14H35M44S" - ISO8601:2004 - https://en.wikipedia.org/wiki/ISO_8601 Durations // snprintf_P(dt, sizeof(dt), PSTR("P%dDT%02dH%02dM%02dS"), ut.days, ut.hour, ut.minute, ut.second); // "128 14:35:44" - OpenVMS // "128T14:35:44" - Tasmota - snprintf_P(dt, sizeof(dt), PSTR("%d" D_DATE_TIME_SEPARATOR "%02d" D_HOUR_MINUTE_SEPARATOR "%02d" D_MINUTE_SECOND_SEPARATOR "%02d"), ut.days, ut.hour, ut.minute, ut.second); + snprintf_P(dt, sizeof(dt), PSTR("%dT%02d:%02d:%02d"), + ut.days, ut.hour, ut.minute, ut.second); return String(dt); } @@ -1217,17 +1306,20 @@ boolean MidnightNow() void RtcSecond() { - uint32_t stdoffset; - uint32_t dstoffset; + int32_t stdoffset; + int32_t dstoffset; TIME_T tmpTime; - if ((ntp_sync_minute > 59) && (3 == RtcTime.minute)) ntp_sync_minute = 1; // If sync prepare for a new cycle + if ((ntp_sync_minute > 59) && (RtcTime.minute > 2)) ntp_sync_minute = 1; // If sync prepare for a new cycle uint8_t offset = (uptime < 30) ? RtcTime.second : (((ESP.getChipId() & 0xF) * 3) + 3) ; // First try ASAP to sync. If fails try once every 60 seconds based on chip id if ((WL_CONNECTED == WiFi.status()) && (offset == RtcTime.second) && ((RtcTime.year < 2016) || (ntp_sync_minute == RtcTime.minute))) { ntp_time = sntp_get_current_timestamp(); - if (ntp_time) { + if (ntp_time > 1451602800) { // Fix NTP bug in core 2.4.1/SDK 2.2.1 (returns Thu Jan 01 08:00:10 1970 after power on) utc_time = ntp_time; ntp_sync_minute = 60; // Sync so block further requests + if (restart_time == 0) { + restart_time = utc_time - uptime; // save first ntp time as restart time + } BreakTime(utc_time, tmpTime); RtcTime.year = tmpTime.year + 1970; daylight_saving_time = RuleToTime(DaylightSavingTime, RtcTime.year); @@ -1235,6 +1327,14 @@ void RtcSecond() snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_APPLICATION "(" D_UTC_TIME ") %s, (" D_DST_TIME ") %s, (" D_STD_TIME ") %s"), GetTime(0).c_str(), GetTime(2).c_str(), GetTime(3).c_str()); AddLog(LOG_LEVEL_DEBUG); +#ifdef USE_RULES + if (local_time < 1451602800) { // 2016-01-01 + strncpy_P(mqtt_data, PSTR("{\"Time\":{\"Initialized\":1}}"), sizeof(mqtt_data)); + } else { + strncpy_P(mqtt_data, PSTR("{\"Time\":{\"Set\":1}}"), sizeof(mqtt_data)); + } + RulesProcess(); +#endif // USE_RULES } else { ntp_sync_minute++; // Try again in next minute } @@ -1242,6 +1342,7 @@ void RtcSecond() utc_time++; local_time = utc_time; if (local_time > 1451602800) { // 2016-01-01 + int32_t time_offset = Settings.timezone * SECS_PER_HOUR; if (99 == Settings.timezone) { if (DaylightSavingTime.hemis) { dstoffset = StandardTime.offset * SECS_PER_MIN; // Southern hemisphere @@ -1251,13 +1352,13 @@ void RtcSecond() stdoffset = StandardTime.offset * SECS_PER_MIN; } if ((utc_time >= (daylight_saving_time - stdoffset)) && (utc_time < (standard_time - dstoffset))) { - local_time += dstoffset; // Daylight Saving Time + time_offset = dstoffset; // Daylight Saving Time } else { - local_time += stdoffset; // Standard Time + time_offset = stdoffset; // Standard Time } - } else { - local_time += Settings.timezone * SECS_PER_HOUR; } + local_time += time_offset; + time_timezone = time_offset / 360; // (SECS_PER_HOUR / 10) fails as it is defined as UL } BreakTime(local_time, RtcTime); if (!RtcTime.hour && !RtcTime.minute && !RtcTime.second && RtcTime.valid) { @@ -1285,7 +1386,10 @@ void RtcInit() * ADC support \*********************************************************************************************/ -void AdcShow(boolean json) +uint8_t adc_counter = 0; +uint16_t adc_last_value = 0; + +uint16_t AdcRead() { uint16_t analog = 0; for (byte i = 0; i < 32; i++) { @@ -1293,9 +1397,29 @@ void AdcShow(boolean json) delay(1); } analog >>= 5; + return analog; +} + +void AdcEvery50ms() +{ + adc_counter++; + if (!(adc_counter % 4)) { + uint16_t new_value = AdcRead(); + if ((new_value < adc_last_value -10) || (new_value > adc_last_value +10)) { + adc_last_value = new_value; + uint16_t value = adc_last_value / 10; + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"ANALOG\":{\"A0div10\":%d}}"), (value > 99) ? 100 : value); + RulesProcess(); + } + } +} + +void AdcShow(boolean json) +{ + uint16_t analog = AdcRead(); if (json) { - snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"" D_JSON_ANALOG_INPUT "0\":%d"), mqtt_data, analog); + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"ANALOG\":{\"A0\":%d}"), mqtt_data, analog); #ifdef USE_WEBSERVER } else { snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_SNS_ANALOG, mqtt_data, "", 0, analog); @@ -1315,6 +1439,9 @@ boolean Xsns02(byte function) if (pin[GPIO_ADC0] < 99) { switch (function) { + case FUNC_EVERY_50_MSECOND: + AdcEvery50ms(); + break; case FUNC_JSON_APPEND: AdcShow(1); break; @@ -1338,6 +1465,13 @@ boolean Xsns02(byte function) * \*********************************************************************************************/ +void SetSeriallog(byte loglevel) +{ + Settings.seriallog_level = loglevel; + seriallog_level = loglevel; + seriallog_timer = 0; +} + #ifdef USE_WEBSERVER void GetLog(byte idx, char** entry_pp, size_t* len_p) { @@ -1369,9 +1503,9 @@ void Syslog() // Destroys log_data char syslog_preamble[64]; // Hostname + Id - if ((static_cast(syslog_host_addr) == 0) || ((millis() - syslog_host_refresh) > 60000)) { - WiFi.hostByName(Settings.syslog_host, syslog_host_addr); - syslog_host_refresh = millis(); + if (syslog_host_hash != GetHash(Settings.syslog_host, strlen(Settings.syslog_host))) { + syslog_host_hash = GetHash(Settings.syslog_host, strlen(Settings.syslog_host)); + WiFi.hostByName(Settings.syslog_host, syslog_host_addr); // If sleep enabled this might result in exception so try to do it once using hash } if (PortUdp.beginPacket(syslog_host_addr, Settings.syslog_port)) { snprintf_P(syslog_preamble, sizeof(syslog_preamble), PSTR("%s ESP-"), my_hostname); @@ -1436,15 +1570,20 @@ void AddLog_P(byte loglevel, const char *formatP, const char *formatP2) AddLog(loglevel); } -void AddLogSerial(byte loglevel) +void AddLogSerial(byte loglevel, uint8_t *buffer, int count) { snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_SERIAL D_RECEIVED)); - for (byte i = 0; i < serial_in_byte_counter; i++) { - snprintf_P(log_data, sizeof(log_data), PSTR("%s %02X"), log_data, serial_in_buffer[i]); + for (int i = 0; i < count; i++) { + snprintf_P(log_data, sizeof(log_data), PSTR("%s %02X"), log_data, *(buffer++)); } AddLog(loglevel); } +void AddLogSerial(byte loglevel) +{ + AddLogSerial(loglevel, (uint8_t*)serial_in_buffer, serial_in_byte_counter); +} + /*********************************************************************************************\ * \*********************************************************************************************/ diff --git a/sonoff/user_config.h b/sonoff/user_config.h index fde332a2c..6bfa6e1cd 100644 --- a/sonoff/user_config.h +++ b/sonoff/user_config.h @@ -21,28 +21,34 @@ #define _USER_CONFIG_H_ /*********************************************************************************************\ - * ATTENTION: Changes to most PARAMETER defines will only override flash settings if you change - * define CFG_HOLDER. - * Most parameters can be changed online using commands via MQTT, WebConsole or serial + * This file consists of TWO sections. * - * Corresponding MQTT/Serial/Console commands in [brackets] + * SECTION 1: + * The first section contains PARAMETERS overriding flash settings if define CFG_HOLDER is CHANGED. + * All parameters can be persistent changed online using commands via MQTT, WebConsole or Serial. + * Corresponding MQTT/Serial/Console commands are shown in [brackets] + * + * SECTION 2: + * The second section contains Enabled and Disabled FEATURES allowing different program size. + * Changes in this section do NOT need a change of define CFG_HOLDER. + * + * ATTENTION: + * Users are advised to use the user_config_override.h file for most changes. \*********************************************************************************************/ -// -- Localization -------------------------------- -//#define MY_LANGUAGE de-DE // German in Germany -//#define MY_LANGUAGE en-GB // English in Great Britain. Enabled by Default -//#define MY_LANGUAGE es-AR // Spanish in Argentina -//#define MY_LANGUAGE fr-FR // French in France -//#define MY_LANGUAGE it-IT // Italian in Italy -//#define MY_LANGUAGE nl-NL // Dutch in the Netherlands -//#define MY_LANGUAGE pl-PL // Polish in Poland -//#define MY_LANGUAGE zh-CN // Chinese (Simplified) in China +//#define USE_CONFIG_OVERRIDE // Uncomment to use user_config_override.h file. See README.md + +/*********************************************************************************************\ + * SECTION 1 + * - After initial load any change here only take effect if CFG_HOLDER is changed too +\*********************************************************************************************/ + +// -- Master parameter control -------------------- +#define CFG_HOLDER 0x20161209 // [Reset 1] Change this value to load SECTION1 configuration parameters to flash // -- Project ------------------------------------- -#define PROJECT "sonoff" // PROJECT is used as the default topic delimiter and OTA file name - // As an IDE restriction it needs to be the same as the main .ino file +#define PROJECT "sonoff" // PROJECT is used as the default topic delimiter -#define CFG_HOLDER 0x20161209 // [Reset 1] Change this value to load following default configuration parameters #define SAVE_DATA 1 // [SaveData] Save changed parameters to Flash (0 = disable, 1 - 3600 seconds) #define SAVE_STATE 1 // [SetOption0] Save changed power state to Flash (0 = disable, 1 = enable) @@ -52,40 +58,32 @@ #define WIFI_SUBNETMASK "255.255.255.0" // [IpAddress3] If not using DHCP set Network mask #define WIFI_DNS "192.168.2.27" // [IpAddress4] If not using DHCP set DNS IP address (might be equal to WIFI_GATEWAY) -#define STA_SSID1 "indebuurt1" // [Ssid1] Wifi SSID -#define STA_PASS1 "VnsqrtnrsddbrN" // [Password1] Wifi password -#define STA_SSID2 "indebuurt2" // [Ssid2] Optional alternate AP Wifi SSID -#define STA_PASS2 "VnsqrtnrsddbrN" // [Password2] Optional alternate AP Wifi password +#define STA_SSID1 "" // [Ssid1] Wifi SSID +#define STA_PASS1 "" // [Password1] Wifi password +#define STA_SSID2 "" // [Ssid2] Optional alternate AP Wifi SSID +#define STA_PASS2 "" // [Password2] Optional alternate AP Wifi password #define WIFI_CONFIG_TOOL WIFI_WPSCONFIG // [WifiConfig] Default tool if wifi fails to connect // (WIFI_RESTART, WIFI_SMARTCONFIG, WIFI_MANAGER, WIFI_WPSCONFIG, WIFI_RETRY, WIFI_WAIT) // -- Syslog -------------------------------------- -#define SYS_LOG_HOST "domus1" // [LogHost] (Linux) syslog host +#define SYS_LOG_HOST "" // [LogHost] (Linux) syslog host #define SYS_LOG_PORT 514 // [LogPort] default syslog UDP port -#define SYS_LOG_LEVEL LOG_LEVEL_NONE // [SysLog] -#define SERIAL_LOG_LEVEL LOG_LEVEL_INFO // [SerialLog] -#define WEB_LOG_LEVEL LOG_LEVEL_INFO // [WebLog] +#define SYS_LOG_LEVEL LOG_LEVEL_NONE // [SysLog] (LOG_LEVEL_NONE, LOG_LEVEL_ERROR, LOG_LEVEL_INFO, LOG_LEVEL_DEBUG, LOG_LEVEL_DEBUG_MORE) +#define SERIAL_LOG_LEVEL LOG_LEVEL_INFO // [SerialLog] (LOG_LEVEL_NONE, LOG_LEVEL_ERROR, LOG_LEVEL_INFO, LOG_LEVEL_DEBUG, LOG_LEVEL_DEBUG_MORE) +#define WEB_LOG_LEVEL LOG_LEVEL_INFO // [WebLog] (LOG_LEVEL_NONE, LOG_LEVEL_ERROR, LOG_LEVEL_INFO, LOG_LEVEL_DEBUG, LOG_LEVEL_DEBUG_MORE) // -- Ota ----------------------------------------- -#define OTA_URL "http://domus1:80/api/arduino/" PROJECT ".ino.bin" // [OtaUrl] +#define OTA_URL "http://sonoff.maddox.co.uk/tasmota/sonoff.ino.bin" // [OtaUrl] // -- MQTT ---------------------------------------- #define MQTT_USE 1 // [SetOption3] Select default MQTT use (0 = Off, 1 = On) -// !!! TLS uses a LOT OF MEMORY (20k) so be careful to enable other options at the same time !!! -//#define USE_MQTT_TLS // EXPERIMENTAL Use TLS for MQTT connection (+53k code, +20k mem) - Disable by // - // Needs Fingerprint, TLS Port, UserId and Password -#ifdef USE_MQTT_TLS - #define MQTT_HOST "m20.cloudmqtt.com" // [MqttHost] - #define MQTT_FINGERPRINT "A5 02 FF 13 99 9F 8B 39 8E F1 83 4F 11 23 65 0B 32 36 FC 07" // [MqttFingerprint] - #define MQTT_PORT 20123 // [MqttPort] MQTT TLS port - #define MQTT_USER "cloudmqttuser" // [MqttUser] Mandatory user - #define MQTT_PASS "cloudmqttpassword" // [MqttPassword] Mandatory password -#else - #define MQTT_HOST "domus1" // [MqttHost] - #define MQTT_PORT 1883 // [MqttPort] MQTT port (10123 on CloudMQTT) - #define MQTT_USER "DVES_USER" // [MqttUser] Optional user - #define MQTT_PASS "DVES_PASS" // [MqttPassword] Optional password -#endif + +#define MQTT_HOST "" // [MqttHost] +#define MQTT_FINGERPRINT1 "A5 02 FF 13 99 9F 8B 39 8E F1 83 4F 11 23 65 0B 32 36 FC 07" // [MqttFingerprint1] +#define MQTT_FINGERPRINT2 "A5 02 FF 13 99 9F 8B 39 8E F1 83 4F 11 23 65 0B 32 36 FC 07" // [MqttFingerprint2] +#define MQTT_PORT 1883 // [MqttPort] MQTT port (10123 on CloudMQTT) +#define MQTT_USER "DVES_USER" // [MqttUser] MQTT user +#define MQTT_PASS "DVES_PASS" // [MqttPassword] MQTT password #define MQTT_BUTTON_RETAIN 0 // [ButtonRetain] Button may send retain flag (0 = off, 1 = on) #define MQTT_POWER_RETAIN 0 // [PowerRetain] Power status message may send retain flag (0 = off, 1 = on) @@ -97,7 +95,7 @@ #define MQTT_CMND_HOLD "HOLD" // [StateText4] Command to send when button is kept down for over KEY_HOLD_TIME * 0.1 seconds (needs to be a string like "HOLD") // -- MQTT topics --------------------------------- -//#define MQTT_FULLTOPIC "tasmota/bedroom/%topic%/%prefix%/" // Up to max 80 characers + // Example "tasmota/bedroom/%topic%/%prefix%/" up to 80 characers #define MQTT_FULLTOPIC "%prefix%/%topic%/" // [FullTopic] Subscribe and Publish full topic name - Legacy topic // %prefix% token options @@ -114,54 +112,40 @@ #define TELE_PERIOD 300 // [TelePeriod] Telemetry (0 = disable, 10 - 3600 seconds) // -- MQTT - Domoticz ----------------------------- -#define USE_DOMOTICZ // Enable Domoticz (+6k code, +0.3k mem) - Disable by // - #define DOMOTICZ_IN_TOPIC "domoticz/in" // Domoticz Input Topic - #define DOMOTICZ_OUT_TOPIC "domoticz/out" // Domoticz Output Topic - #define DOMOTICZ_UPDATE_TIMER 0 // [DomoticzUpdateTimer] Send relay status (0 = disable, 1 - 3600 seconds) (Optional) +#define DOMOTICZ_UPDATE_TIMER 0 // [DomoticzUpdateTimer] Send relay status (0 = disable, 1 - 3600 seconds) // -- MQTT - Home Assistant Discovery ------------- -#define USE_HOME_ASSISTANT // Enable Home Assistant Discovery Support (+1k4 code) - #define HOME_ASSISTANT_DISCOVERY_PREFIX "homeassistant" // Home Assistant discovery prefix - #define HOME_ASSISTANT_DISCOVERY_ENABLE 0 // [SetOption19] Home Assistant Discovery (0 = Disable, 1 = Enable) +#define HOME_ASSISTANT_DISCOVERY_ENABLE 0 // [SetOption19] Home Assistant Discovery (0 = Disable, 1 = Enable) // -- HTTP ---------------------------------------- -#define USE_WEBSERVER // Enable web server and wifi manager (+66k code, +8k mem) - Disable by // - #define WEB_SERVER 2 // [WebServer] Web server (0 = Off, 1 = Start as User, 2 = Start as Admin) - #define WEB_PORT 80 // Web server Port for User and Admin mode - #define WEB_USERNAME "admin" // Web server Admin mode user name - #define WEB_PASSWORD "" // [WebPassword] Web server Admin mode Password for WEB_USERNAME (empty string = Disable) - #define FRIENDLY_NAME "Sonoff" // [FriendlyName] Friendlyname up to 32 characters used by webpages and Alexa - #define USE_EMULATION // Enable Belkin WeMo and Hue Bridge emulation for Alexa (+16k code, +2k mem) - #define EMULATION EMUL_NONE // [Emulation] Select Belkin WeMo (single relay/light) or Hue Bridge emulation (multi relay/light) (EMUL_NONE, EMUL_WEMO or EMUL_HUE) - -// -- mDNS ---------------------------------------- -#define USE_DISCOVERY // Enable mDNS for the following services (+8k code, +0.3k mem) - Disable by // - #define WEBSERVER_ADVERTISE // Provide access to webserver by name .local/ - #define MQTT_HOST_DISCOVERY // Find MQTT host server (overrides MQTT_HOST if found) +#define WEB_SERVER 2 // [WebServer] Web server (0 = Off, 1 = Start as User, 2 = Start as Admin) +#define WEB_PASSWORD "" // [WebPassword] Web server Admin mode Password for WEB_USERNAME (empty string = Disable) +#define FRIENDLY_NAME "Sonoff" // [FriendlyName] Friendlyname up to 32 characters used by webpages and Alexa +#define EMULATION EMUL_NONE // [Emulation] Select Belkin WeMo (single relay/light) or Hue Bridge emulation (multi relay/light) (EMUL_NONE, EMUL_WEMO or EMUL_HUE) // -- Time - Up to three NTP servers in your region #define NTP_SERVER1 "pool.ntp.org" // [NtpServer1] Select first NTP server by name or IP address (129.250.35.250) #define NTP_SERVER2 "nl.pool.ntp.org" // [NtpServer2] Select second NTP server by name or IP address (5.39.184.5) #define NTP_SERVER3 "0.nl.pool.ntp.org" // [NtpServer3] Select third NTP server by name or IP address (93.94.224.67) -// -- Time - Start Daylight Saving Time and timezone offset from UTC in minutes -#define TIME_DST North, Last, Sun, Mar, 2, +120 // Northern Hemisphere, Last sunday in march at 02:00 +120 minutes - -// -- Time - Start Standard Time and timezone offset from UTC in minutes -#define TIME_STD North, Last, Sun, Oct, 3, +60 // Northern Hemisphere, Last sunday in october 02:00 +60 minutes +// -- Location ------------------------------------ +#define LATITUDE 48.858360 // [Latitude] Your location to be used with sunrise and sunset +#define LONGITUDE 2.294442 // [Longitude] Your location to be used with sunrise and sunset // -- Application --------------------------------- -#define APP_TIMEZONE 1 // [Timezone] +1 hour (Amsterdam) (-12 .. 12 = hours from UTC, 99 = use TIME_DST/TIME_STD) -#define APP_LEDSTATE LED_POWER // [LedState] Function of led (LED_OFF, LED_POWER, LED_MQTTSUB, LED_POWER_MQTTSUB, LED_MQTTPUB, LED_POWER_MQTTPUB, LED_MQTT, LED_POWER_MQTT) +#define APP_TIMEZONE 1 // [Timezone] +1 hour (Amsterdam) (-13 .. 14 = hours from UTC, 99 = use TIME_DST/TIME_STD) +#define APP_LEDSTATE LED_POWER // [LedState] Function of led + // (LED_OFF, LED_POWER, LED_MQTTSUB, LED_POWER_MQTTSUB, LED_MQTTPUB, LED_POWER_MQTTPUB, LED_MQTT, LED_POWER_MQTT) #define APP_PULSETIME 0 // [PulseTime] Time in 0.1 Sec to turn off power for relay 1 (0 = disabled) -#define APP_POWERON_STATE 3 // [PowerOnState] Power On Relay state (0 = Off, 1 = On, 2 = Toggle Saved state, 3 = Saved state) +#define APP_POWERON_STATE POWER_ALL_SAVED // [PowerOnState] Power On Relay state + // (POWER_ALL_OFF, POWER_ALL_ON, POWER_ALL_SAVED_TOGGLE, POWER_ALL_SAVED, POWER_ALL_ALWAYS_ON, POWER_ALL_OFF_PULSETIME_ON) #define APP_BLINKTIME 10 // [BlinkTime] Time in 0.1 Sec to blink/toggle power for relay 1 #define APP_BLINKCOUNT 10 // [BlinkCount] Number of blinks (0 = 32000) #define APP_SLEEP 0 // [Sleep] Sleep time to lower energy consumption (0 = Off, 1 - 250 mSec) #define KEY_HOLD_TIME 40 // [SetOption32] Number of 0.1 seconds to hold Button or external Pushbutton before sending HOLD message -#define SWITCH_MODE TOGGLE // [SwitchMode] TOGGLE, FOLLOW, FOLLOW_INV, PUSHBUTTON, PUSHBUTTON_INV, PUSHBUTTONHOLD, PUSHBUTTONHOLD_INV or PUSHBUTTON_TOGGLE (the wall switch state) -#define WS2812_LEDS 30 // [Pixels] Number of WS2812 LEDs to start with +#define SWITCH_MODE TOGGLE // [SwitchMode] TOGGLE, FOLLOW, FOLLOW_INV, PUSHBUTTON, PUSHBUTTON_INV, PUSHBUTTONHOLD, PUSHBUTTONHOLD_INV, PUSHBUTTON_TOGGLE (the wall switch state) +#define WS2812_LEDS 30 // [Pixels] Number of WS2812 LEDs to start with (max is 512) #define TEMP_CONVERSION 0 // [SetOption8] Return temperature in (0 = Celsius or 1 = Fahrenheit) #define TEMP_RESOLUTION 1 // [TempRes] Maximum number of decimals (0 - 3) showing sensor Temperature @@ -169,6 +153,89 @@ #define PRESSURE_RESOLUTION 1 // [PressRes] Maximum number of decimals (0 - 3) showing sensor Pressure #define ENERGY_RESOLUTION 3 // [EnergyRes] Maximum number of decimals (0 - 5) showing energy usage in kWh +/*********************************************************************************************\ + * END OF SECTION 1 + * + * SECTION 2 + * - Enable a feature by removing both // in front of it + * - Disable a feature by preceding it with // +\*********************************************************************************************/ + +//#define USE_ARDUINO_OTA // Add optional support for Arduino OTA (+4k5 code) + +// -- Localization -------------------------------- + // If non selected the default en-GB will be used +//#define MY_LANGUAGE bg-BG // Bulgarian in Bulgaria +//#define MY_LANGUAGE cs-CZ // Czech in Czech +//#define MY_LANGUAGE de-DE // German in Germany +//#define MY_LANGUAGE el-GR // Greek in Greece +//#define MY_LANGUAGE en-GB // English in Great Britain. Enabled by Default +//#define MY_LANGUAGE es-AR // Spanish in Argentina +//#define MY_LANGUAGE fr-FR // French in France +//#define MY_LANGUAGE hu-HU // Hungarian in Hungary +//#define MY_LANGUAGE it-IT // Italian in Italy +//#define MY_LANGUAGE nl-NL // Dutch in the Netherlands +//#define MY_LANGUAGE pl-PL // Polish in Poland +//#define MY_LANGUAGE pt-PT // Portuguese in Portugal +//#define MY_LANGUAGE ru-RU // Russian in Russia +//#define MY_LANGUAGE zh-CN // Chinese (Simplified) in China +//#define MY_LANGUAGE zh-TW // Chinese (Traditional) in Taiwan + +/*-------------------------------------------------------------------------------------------*\ + * Select ONE of possible three MQTT library types below +\*-------------------------------------------------------------------------------------------*/ + // Default MQTT driver for both non-TLS and TLS connections. Blocks network if MQTT server is unavailable. +#define MQTT_LIBRARY_TYPE MQTT_PUBSUBCLIENT // Use PubSubClient library + // Alternative MQTT driver does not block network when MQTT server is unavailable. No TLS support +//#define MQTT_LIBRARY_TYPE MQTT_TASMOTAMQTT // Use TasmotaMqtt library (+4k4 code, +4k mem) - non-TLS only + // Alternative MQTT driver does not block network when MQTT server is unavailable. No TLS support +//#define MQTT_LIBRARY_TYPE MQTT_ESPMQTTARDUINO // Use (patched) esp-mqtt-arduino library (+4k8 code, +4k mem) - non-TLS only + +// -- MQTT ---------------------------------------- +#define MQTT_TELE_RETAIN 0 // Tele messages may send retain flag (0 = off, 1 = on) + +// -- MQTT - Domoticz ----------------------------- +#define USE_DOMOTICZ // Enable Domoticz (+6k code, +0.3k mem) + #define DOMOTICZ_IN_TOPIC "domoticz/in" // Domoticz Input Topic + #define DOMOTICZ_OUT_TOPIC "domoticz/out" // Domoticz Output Topic + +// -- MQTT - Home Assistant Discovery ------------- +#define USE_HOME_ASSISTANT // Enable Home Assistant Discovery Support (+2k code) + #define HOME_ASSISTANT_DISCOVERY_PREFIX "homeassistant" // Home Assistant discovery prefix + +// -- MQTT - TLS ---------------------------------- + // !!! TLS uses a LOT OF MEMORY so be careful to enable other options at the same time !!! +//#define USE_MQTT_TLS // Use TLS for MQTT connection (+53k code, +15k mem) + +// -- KNX IP Protocol ----------------------------- +//#define USE_KNX // Enable KNX IP Protocol Support (+23k code, +3k3 mem) + +// -- HTTP ---------------------------------------- +#define USE_WEBSERVER // Enable web server and wifi manager (+66k code, +8k mem) + #define WEB_PORT 80 // Web server Port for User and Admin mode + #define WEB_USERNAME "admin" // Web server Admin mode user name + #define USE_EMULATION // Enable Belkin WeMo and Hue Bridge emulation for Alexa (+16k code, +2k mem) + +// -- mDNS ---------------------------------------- +#define USE_DISCOVERY // Enable mDNS for the following services (+8k code, +0.3k mem) + #define WEBSERVER_ADVERTISE // Provide access to webserver by name .local/ + #define MQTT_HOST_DISCOVERY // Find MQTT host server (overrides MQTT_HOST if found) + +// -- Time - Start Daylight Saving Time and timezone offset from UTC in minutes +#define TIME_DST North, Last, Sun, Mar, 2, +120 // Northern Hemisphere, Last sunday in march at 02:00 +120 minutes + +// -- Time - Start Standard Time and timezone offset from UTC in minutes +#define TIME_STD North, Last, Sun, Oct, 3, +60 // Northern Hemisphere, Last sunday in october 02:00 +60 minutes + +// -- Time ---------------------------------------- +#define USE_TIMERS // Add support for up to 16 timers (+2k2 code) + #define USE_TIMERS_WEB // Add timer webpage support (+4k5 code) + #define USE_SUNRISE // Add support for Sunrise and sunset tools (+16k) + #define SUNRISE_DAWN_ANGLE DAWN_NORMAL // Select desired Dawn Angle from (DAWN_NORMAL, DAWN_CIVIL, DAWN_NAUTIC, DAWN_ASTRONOMIC) + +// -- Rules --------------------------------------- +#define USE_RULES // Add support for rules (+4k4 code) + // -- Internal Analog input ----------------------- #define USE_ADC_VCC // Display Vcc in Power status. Disable for use as Analog input on selected devices @@ -181,25 +248,36 @@ #define USE_I2C // I2C using library wire (+10k code, 0k2 mem, 124 iram) #ifdef USE_I2C #define USE_SHT // Add I2C emulating code for SHT1X sensor (+1k4 code) - #define USE_SHT3X // Add I2C code for SHT3x sensor (+0k6 code) + #define USE_SHT3X // Add I2C code for SHT3x or SHTC3 sensor (+0k7 code) #define USE_HTU // Add I2C code for HTU21/SI7013/SI7020/SI7021 sensor (+1k5 code) #define USE_BMP // Add I2C code for BMP085/BMP180/BMP280/BME280 sensor (+4k code) // #define USE_BME680 // Add additional support for BME680 sensor using Adafruit Sensor and BME680 libraries (+6k code) + #define USE_SGP30 // Add I2C code for SGP30 sensor (+1k1 code) #define USE_BH1750 // Add I2C code for BH1750 sensor (+0k5 code) // #define USE_VEML6070 // Add I2C code for VEML6070 sensor (+0k5 code) -// #define USE_TSL2561 // Add I2C code for TSL2561 sensor using library Adafruit TSL2561 Arduino (+1k2 code) +// #define USE_TSL2561 // Add I2C code for TSL2561 sensor using library Joba_Tsl2561 (+2k3 code) // #define USE_ADS1115 // Add I2C code for ADS1115 16 bit A/D converter based on Adafruit ADS1x15 library (no library needed) (+0k7 code) // #define USE_ADS1115_I2CDEV // Add I2C code for ADS1115 16 bit A/D converter using library i2cdevlib-Core and i2cdevlib-ADS1115 (+2k code) // #define USE_INA219 // Add I2C code for INA219 Low voltage and current sensor (+1k code) +// #define USE_MGS // Add I2C code for Xadow and Grove Mutichannel Gas sensor using library Multichannel_Gas_Sensor (+10k code) + #define MGS_SENSOR_ADDR 0x04 // Default Mutichannel Gas sensor i2c address #endif // USE_I2C +// -- SPI sensors --------------------------------- +//#define USE_SPI // SPI using default library +#ifdef USE_SPI + +#endif // USE_SPI + // -- Serial sensors ------------------------------ #define USE_MHZ19 // Add support for MH-Z19 CO2 sensor (+2k code) #define USE_SENSEAIR // Add support for SenseAir K30, K70 and S8 CO2 sensor (+2k3 code) #define CO2_LOW 800 // Below this CO2 value show green light (needs PWM or WS2812 RG(B) led and enable with SetOption18 1) #define CO2_HIGH 1200 // Above this CO2 value show red light (needs PWM or WS2812 RG(B) led and enable with SetOption18 1) #define USE_PMS5003 // Add support for PMS5003 and PMS7003 particle concentration sensor (+1k3 code) +#define USE_NOVA_SDS // Add support for SDS011 and SDS021 particle concentration sensor (+0k7 code) #define USE_PZEM004T // Add support for PZEM004T Energy monitor (+2k code) +#define USE_SERIAL_BRIDGE // Add support for software Serial Bridge (+0k8 code) // -- Low level interface devices ----------------- #define USE_IR_REMOTE // Send IR remote commands using library IRremoteESP8266 and ArduinoJson (+4k code, 0k3 mem, 48 iram) @@ -207,16 +285,35 @@ #define USE_IR_RECEIVE // Support for IR receiver (+5k5 code, 264 iram) #define USE_WS2812 // WS2812 Led string using library NeoPixelBus (+5k code, +1k mem, 232 iram) - Disable by // - #define USE_WS2812_CTYPE 1 // WS2812 Color type (0 - RGB, 1 - GRB, 2 - RGBW, 3 - GRBW) + #define USE_WS2812_CTYPE NEO_GRB // WS2812 Color type (NEO_RGB, NEO_GRB, NEO_BRG, NEO_RBG, NEO_RGBW, NEO_GRBW) // #define USE_WS2812_DMA // DMA supports only GPIO03 (= Serial RXD) (+1k mem). When USE_WS2812_DMA is enabled expect Exceptions on Pow #define USE_ARILUX_RF // Add support for Arilux RF remote controller (+0k8 code, 252 iram (non 2.3.0)) +#define USE_SR04 // Add support for HC-SR04 ultrasonic devices (+1k code) + +/*********************************************************************************************\ + * Select features and sensors enabled in previous version saving space +\*********************************************************************************************/ + +//#define USE_CLASSIC // Create sonoff-classic (See sonoff_post.h for selected features) + +/*********************************************************************************************\ + * Select all sensors - overrides above undefines!! +\*********************************************************************************************/ + +//#define USE_ALL_SENSORS // Create sonoff-allsensors with all sensors enabled (See sonoff_post.h for selected sensors) + +/*********************************************************************************************\ + * Select KNX without Emulation to save space +\*********************************************************************************************/ + +//#define USE_KNX_NO_EMULATION // Create sonoff-knx with KNX but without Emulation (See sonoff_post.h) + /*********************************************************************************************\ * Compile a minimal version if upgrade memory gets tight ONLY TO BE USED FOR UPGRADE STEP 1! * To be used as step 1 during upgrade. * Step 2 is re-compile with option BE_MINIMAL commented out. - * !!! Needed for next release of Arduino/ESP8266 (+22k code, +2k mem) !!! \*********************************************************************************************/ //#define BE_MINIMAL // Minimal version if upgrade memory gets tight (-45k code, -2k mem) diff --git a/sonoff/user_config_override.h b/sonoff/user_config_override.h deleted file mode 100644 index 1008faf72..000000000 --- a/sonoff/user_config_override.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - user_config_override.h - user configuration overrides user_config.h for Sonoff-Tasmota - - Copyright (C) 2018 Theo Arends - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . -*/ - -#ifndef _USER_CONFIG_OVERRIDE_H_ -#define _USER_CONFIG_OVERRIDE_H_ - -/*****************************************************************************************************\ - * ATTENTION: - Changes to most PARAMETER defines will only override flash settings if you change - * define CFG_HOLDER. - * - Expect compiler warnings when no ifdef/undef/endif sequence is used. - * - You still need to update user_config.h for major defines MODULE and USE_MQTT_TLS. - * - Changing MODULE defines are not being tested for validity as they are in user_config.h. - * - Most parameters can be changed online using commands via MQTT, WebConsole or serial. - * - So I see no use in this but anyway, your on your own. -\*****************************************************************************************************/ - -// Examples -//#ifdef CFG_HOLDER -//#undef CFG_HOLDER -//#endif -//#define CFG_HOLDER 0x20161210 - -//#ifdef STA_SSID1 -//#undef STA_SSID1 -//#endif -//#define STA_SSID1 "yourssid1" - -#endif // _USER_CONFIG_OVERRIDE_H_ \ No newline at end of file diff --git a/sonoff/user_config_override_sample.h b/sonoff/user_config_override_sample.h new file mode 100644 index 000000000..acd66cebe --- /dev/null +++ b/sonoff/user_config_override_sample.h @@ -0,0 +1,96 @@ +/* + user_config_override.h - user configuration overrides user_config.h for Sonoff-Tasmota + + Copyright (C) 2018 Theo Arends + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifndef _USER_CONFIG_OVERRIDE_H_ +#define _USER_CONFIG_OVERRIDE_H_ + +// force the compiler to show a warning to confirm that this file is inlcuded +#warning **** user_config_override.h: Using Settings from this File **** + +/*****************************************************************************************************\ + * USAGE: + * To modify the stock configuration without changing the user_config.h file: + * (1) copy this file to "user_config_override.h" (It will be ignored by Git) + * (2) define your own settings below + * (3) for platformio: + * define USE_CONFIG_OVERRIDE as a build flags. + * ie1 : export PLATFORMIO_BUILD_FLAGS='-DUSE_CONFIG_OVERRIDE' + * ie2 : enable in file platformio.ini "build_flags = -Wl,-Tesp8266.flash.1m0.ld -DUSE_CONFIG_OVERRIDE" + * for Arduino IDE: + * enable define USE_CONFIG_OVERRIDE in user_config.h + ****************************************************************************************************** + * ATTENTION: + * - Changes to SECTION1 PARAMETER defines will only override flash settings if you change define CFG_HOLDER. + * - Expect compiler warnings when no ifdef/undef/endif sequence is used. + * - You still need to update user_config.h for major define USE_MQTT_TLS. + * - All parameters can be persistent changed online using commands via MQTT, WebConsole or Serial. +\*****************************************************************************************************/ + +/* +Examples : + +// -- Master parameter control -------------------- +#undef CFG_HOLDER +#define CFG_HOLDER 0x20161209 // [Reset 1] Change this value to load SECTION1 configuration parameters to flash + +// -- Setup your own Wifi settings --------------- +#undef STA_SSID1 +#define STA_SSID1 "YourSSID" // [Ssid1] Wifi SSID + +#undef STA_PASS1 +#define STA_PASS1 "YourWifiPassword" // [Password1] Wifi password + +// -- Setup your own MQTT settings --------------- +#undef MQTT_HOST +#define MQTT_HOST "your-mqtt-server.com" // [MqttHost] + +#undef MQTT_PORT +#define MQTT_PORT 1883 // [MqttPort] MQTT port (10123 on CloudMQTT) + +#undef MQTT_USER +#define MQTT_USER "YourMqttUser" // [MqttUser] Optional user + +#undef MQTT_PASS +#define MQTT_PASS "YourMqttPass" // [MqttPassword] Optional password + +// You might even pass some parameters from the command line ---------------------------- +// Ie: export PLATFORMIO_BUILD_FLAGS='-DUSE_CONFIG_OVERRIDE -DMY_IP="192.168.1.99" -DMY_GW="192.168.1.1" -DMY_DNS="192.168.1.1"' + +#ifdef MY_IP +#undef WIFI_IP_ADDRESS +#define WIFI_IP_ADDRESS MY_IP // Set to 0.0.0.0 for using DHCP or IP address +#endif + +#ifdef MY_GW +#undef WIFI_GATEWAY +#define WIFI_GATEWAY MY_GW // if not using DHCP set Gateway IP address +#endif + +#ifdef MY_DNS +#undef WIFI_DNS +#define WIFI_DNS MY_DNS // If not using DHCP set DNS IP address (might be equal to WIFI_GATEWAY) +#endif + +*/ + + + + + +#endif // _USER_CONFIG_OVERRIDE_H_ \ No newline at end of file diff --git a/sonoff/webserver.ino b/sonoff/webserver.ino index a1fef74e9..f82fa2e6d 100644 --- a/sonoff/webserver.ino +++ b/sonoff/webserver.ino @@ -29,7 +29,7 @@ #define STR(x) STR_HELPER(x) const char HTTP_HEAD[] PROGMEM = - "" + "" "" "" "" @@ -39,16 +39,19 @@ const char HTTP_HEAD[] PROGMEM = "var cn,x,lt;" "cn=180;" "x=null;" // Allow for abortion + "function eb(s){" + "return document.getElementById(s);" // Save code space + "}" "function u(){" "if(cn>=0){" - "document.getElementById('t').innerHTML='" D_RESTART_IN " '+cn+' " D_SECONDS "';" + "eb('t').innerHTML='" D_RESTART_IN " '+cn+' " D_SECONDS "';" "cn--;" "setTimeout(u,1000);" "}" "}" "function c(l){" - "document.getElementById('s1').value=l.innerText||l.textContent;" - "document.getElementById('p1').focus();" + "eb('s1').value=l.innerText||l.textContent;" + "eb('p1').focus();" "}" "function la(p){" "var a='';" @@ -61,7 +64,7 @@ const char HTTP_HEAD[] PROGMEM = "x.onreadystatechange=function(){" "if(x.readyState==4&&x.status==200){" "var s=x.responseText.replace(/{t}/g,\"\").replace(/{s}/g,\"\").replace(/{c}/g,\"%'>
"); byte idx = 0; for (byte i = 0; i < 4; i++) { - if (idx > 0) { - page += F(""); - } + if (idx > 0) { page += F(""); } for (byte j = 0; j < 4; j++) { idx++; snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR(""), idx, idx); @@ -599,26 +614,28 @@ void HandleAjaxStatusRefresh() boolean HttpUser() { boolean status = (HTTP_USER == webserver_state); - if (status) { - HandleRoot(); - } + if (status) { HandleRoot(); } return status; } void HandleConfiguration() { - if (HttpUser()) { - return; - } + if (HttpUser()) { return; } AddLog_P(LOG_LEVEL_DEBUG, S_LOG_HTTP, S_CONFIGURATION); String page = FPSTR(HTTP_HEAD); page.replace(F("{v}"), FPSTR(S_CONFIGURATION)); page += FPSTR(HTTP_HEAD_STYLE); - page += FPSTR(HTTP_BTN_MENU2); - if (Settings.flag.mqtt_enabled) { - page += FPSTR(HTTP_BTN_MENU3); - } + page += FPSTR(HTTP_BTN_MENU_MODULE); +#if defined(USE_TIMERS) && defined(USE_TIMERS_WEB) +#ifdef USE_RULES + page += FPSTR(HTTP_BTN_MENU_TIMER); +#else + if (devices_present) { page += FPSTR(HTTP_BTN_MENU_TIMER); } +#endif // USE_RULES +#endif // USE_TIMERS and USE_TIMERS_WEB + page += FPSTR(HTTP_BTN_MENU_WIFI); + if (Settings.flag.mqtt_enabled) { page += FPSTR(HTTP_BTN_MENU_MQTT); } page += FPSTR(HTTP_BTN_MENU4); page += FPSTR(HTTP_BTN_MAIN); ShowPage(page); @@ -628,26 +645,20 @@ boolean GetUsedInModule(byte val, uint8_t *arr) { int offset = 0; - if (!val) { - return false; // None - } + if (!val) { return false; } // None #ifndef USE_I2C - if (GPIO_I2C_SCL == val) { - return true; - } - if (GPIO_I2C_SDA == val) { - return true; - } + if (GPIO_I2C_SCL == val) { return true; } + if (GPIO_I2C_SDA == val) { return true; } +#endif +#ifndef USE_SR04 + if (GPIO_SR04_TRIG == val) { return true; } + if (GPIO_SR04_ECHO == val) { return true; } #endif #ifndef USE_WS2812 - if (GPIO_WS2812 == val) { - return true; - } + if (GPIO_WS2812 == val) { return true; } #endif #ifndef USE_IR_REMOTE - if (GPIO_IRSEND == val) { - return true; - } + if (GPIO_IRSEND == val) { return true; } #endif if ((val >= GPIO_REL1) && (val < GPIO_REL1 + MAX_RELAYS)) { offset = (GPIO_REL1_INV - GPIO_REL1); @@ -670,21 +681,15 @@ boolean GetUsedInModule(byte val, uint8_t *arr) offset = -(GPIO_PWM1_INV - GPIO_PWM1); } for (byte i = 0; i < MAX_GPIO_PIN; i++) { - if (arr[i] == val) { - return true; - } - if (arr[i] == val + offset) { - return true; - } + if (arr[i] == val) { return true; } + if (arr[i] == val + offset) { return true; } } return false; } void HandleModuleConfiguration() { - if (HttpUser()) { - return; - } + if (HttpUser()) { return; } char stemp[20]; uint8_t midx; @@ -754,9 +759,7 @@ void HandleWifiConfiguration() void HandleWifi(boolean scan) { - if (HttpUser()) { - return; - } + if (HttpUser()) { return; } AddLog_P(LOG_LEVEL_DEBUG, S_LOG_HTTP, S_CONFIGURE_WIFI); @@ -795,15 +798,13 @@ void HandleWifi(boolean scan) if (remove_duplicate_access_points) { String cssid; for (int i = 0; i < n; i++) { - if (-1 == indices[i]) { - continue; - } + if (-1 == indices[i]) { continue; } cssid = WiFi.SSID(indices[i]); for (int j = i + 1; j < n; j++) { if (cssid == WiFi.SSID(indices[j])) { snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_WIFI D_DUPLICATE_ACCESSPOINT " %s"), WiFi.SSID(indices[j]).c_str()); AddLog(LOG_LEVEL_DEBUG); - indices[j] = -1; // set dup aps to index -1 + indices[j] = -1; // set dup aps to index -1 } } } @@ -811,9 +812,7 @@ void HandleWifi(boolean scan) //display networks in page for (int i = 0; i < n; i++) { - if (-1 == indices[i]) { - continue; // skip dups - } + if (-1 == indices[i]) { continue; } // skip dups snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_WIFI D_SSID " %s, " D_RSSI " %d"), WiFi.SSID(indices[i]).c_str(), WiFi.RSSI(indices[i])); AddLog(LOG_LEVEL_DEBUG); int quality = WifiGetRssiAsQuality(WiFi.RSSI(indices[i])); @@ -855,9 +854,7 @@ void HandleWifi(boolean scan) void HandleMqttConfiguration() { - if (HttpUser()) { - return; - } + if (HttpUser()) { return; } AddLog_P(LOG_LEVEL_DEBUG, S_LOG_HTTP, S_CONFIGURE_MQTT); String page = FPSTR(HTTP_HEAD); @@ -865,8 +862,7 @@ void HandleMqttConfiguration() page += FPSTR(HTTP_HEAD_STYLE); page += FPSTR(HTTP_FORM_MQTT); char str[sizeof(Settings.mqtt_client)]; - GetMqttClient(str, MQTT_CLIENT_ID, sizeof(Settings.mqtt_client)); - page.replace(F("{m0"), str); + page.replace(F("{m0"), Format(str, MQTT_CLIENT_ID, sizeof(Settings.mqtt_client))); page.replace(F("{m1"), Settings.mqtt_host); page.replace(F("{m2"), String(Settings.mqtt_port)); page.replace(F("{m3"), Settings.mqtt_client); @@ -881,9 +877,7 @@ void HandleMqttConfiguration() void HandleLoggingConfiguration() { - if (HttpUser()) { - return; - } + if (HttpUser()) { return; } AddLog_P(LOG_LEVEL_DEBUG, S_LOG_HTTP, S_CONFIGURE_LOGGING); String page = FPSTR(HTTP_HEAD); @@ -930,9 +924,7 @@ void HandleLoggingConfiguration() void HandleOtherConfiguration() { - if (HttpUser()) { - return; - } + if (HttpUser()) { return; } AddLog_P(LOG_LEVEL_DEBUG, S_LOG_HTTP, S_CONFIGURE_OTHER); char stemp[40]; @@ -941,7 +933,7 @@ void HandleOtherConfiguration() page += FPSTR(HTTP_HEAD_STYLE); page += FPSTR(HTTP_FORM_OTHER); page.replace(F("{r1"), (Settings.flag.mqtt_enabled) ? F(" checked") : F("")); - uint8_t maxfn = (devices_present > MAX_FRIENDLYNAMES) ? MAX_FRIENDLYNAMES : devices_present; + uint8_t maxfn = (devices_present > MAX_FRIENDLYNAMES) ? MAX_FRIENDLYNAMES : (!devices_present) ? 1 : devices_present; for (byte i = 0; i < maxfn; i++) { page += FPSTR(HTTP_FORM_OTHER2); page.replace(F("{1"), String(i +1)); @@ -968,9 +960,7 @@ void HandleOtherConfiguration() void HandleBackupConfiguration() { - if (HttpUser()) { - return; - } + if (HttpUser()) { return; } AddLog_P(LOG_LEVEL_DEBUG, PSTR(D_LOG_HTTP D_BACKUP_CONFIGURATION)); uint8_t buffer[sizeof(Settings)]; @@ -979,7 +969,8 @@ void HandleBackupConfiguration() WebServer->setContentLength(sizeof(buffer)); char attachment[100]; - snprintf_P(attachment, sizeof(attachment), PSTR("attachment; filename=Config_%s_%s.dmp"), Settings.friendlyname[0], my_version); + char friendlyname[sizeof(Settings.friendlyname[0])]; + snprintf_P(attachment, sizeof(attachment), PSTR("attachment; filename=Config_%s_%s.dmp"), NoAlNumToUnderscore(friendlyname, Settings.friendlyname[0]), my_version); WebServer->sendHeader(F("Content-Disposition"), attachment); WebServer->send(200, FPSTR(HDR_CTYPE_STREAM), ""); memcpy(buffer, &Settings, sizeof(buffer)); @@ -995,23 +986,20 @@ void HandleBackupConfiguration() void HandleSaveSettings() { - if (HttpUser()) { - return; - } + if (HttpUser()) { return; } char stemp[TOPSZ]; char stemp2[TOPSZ]; - byte what = 0; - byte restart; String result = ""; AddLog_P(LOG_LEVEL_DEBUG, S_LOG_HTTP, S_SAVE_CONFIGURATION); char tmp[100]; - WebGetArg("w", tmp, sizeof(tmp)); - if (strlen(tmp)) { - what = atoi(tmp); - } + WebGetArg("w", tmp, sizeof(tmp)); // Returns "5,1" where 5 is config type and 1 is restart flag + char *p = tmp; + uint8_t what = strtol(p, &p, 10); + p++; // Skip comma + uint8_t restart = strtol(p, &p, 10); switch (what) { case 1: WebGetArg("h", tmp, sizeof(tmp)); @@ -1031,8 +1019,8 @@ void HandleSaveSettings() strlcpy(Settings.sta_pwd[0], (!strlen(tmp)) ? "" : (strchr(tmp,'*')) ? Settings.sta_pwd[0] : tmp, sizeof(Settings.sta_pwd[0])); WebGetArg("p2", tmp, sizeof(tmp)); strlcpy(Settings.sta_pwd[1], (!strlen(tmp)) ? "" : (strchr(tmp,'*')) ? Settings.sta_pwd[1] : tmp, sizeof(Settings.sta_pwd[1])); - snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_WIFI D_CMND_HOSTNAME " %s, " D_CMND_SSID "1 %s, " D_CMND_PASSWORD "1 %s, " D_CMND_SSID "2 %s, " D_CMND_PASSWORD "2 %s"), - Settings.hostname, Settings.sta_ssid[0], Settings.sta_pwd[0], Settings.sta_ssid[1], Settings.sta_pwd[1]); + snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_WIFI D_CMND_HOSTNAME " %s, " D_CMND_SSID "1 %s, " D_CMND_SSID "2 %s"), + Settings.hostname, Settings.sta_ssid[0], Settings.sta_ssid[1]); AddLog(LOG_LEVEL_INFO); result += F("
" D_TRYING_TO_CONNECT "
"); break; @@ -1085,6 +1073,11 @@ void HandleSaveSettings() Settings.seriallog_level, Settings.weblog_level, Settings.syslog_level, Settings.syslog_host, Settings.syslog_port, Settings.tele_period); AddLog(LOG_LEVEL_INFO); break; +#if defined(USE_TIMERS) && defined(USE_TIMERS_WEB) + case 7: + TimerSaveSettings(); + break; +#endif // USE_TIMERS and USE_TIMERS_WEB #ifdef USE_DOMOTICZ case 4: DomoticzSaveSettings(); @@ -1136,8 +1129,6 @@ void HandleSaveSettings() break; } - WebGetArg("r", tmp, sizeof(tmp)); - restart = (!strlen(tmp)) ? 1 : atoi(tmp); if (restart) { String page = FPSTR(HTTP_HEAD); page.replace(F("{v}"), FPSTR(S_SAVE_CONFIGURATION)); @@ -1161,9 +1152,7 @@ void HandleSaveSettings() void HandleResetConfiguration() { - if (HttpUser()) { - return; - } + if (HttpUser()) { return; } char svalue[33]; @@ -1183,9 +1172,7 @@ void HandleResetConfiguration() void HandleRestoreConfiguration() { - if (HttpUser()) { - return; - } + if (HttpUser()) { return; } AddLog_P(LOG_LEVEL_DEBUG, S_LOG_HTTP, S_RESTORE_CONFIGURATION); String page = FPSTR(HTTP_HEAD); @@ -1203,9 +1190,7 @@ void HandleRestoreConfiguration() void HandleUpgradeFirmware() { - if (HttpUser()) { - return; - } + if (HttpUser()) { return; } AddLog_P(LOG_LEVEL_DEBUG, S_LOG_HTTP, S_FIRMWARE_UPGRADE); String page = FPSTR(HTTP_HEAD); @@ -1224,9 +1209,7 @@ void HandleUpgradeFirmware() void HandleUpgradeFirmwareStart() { - if (HttpUser()) { - return; - } + if (HttpUser()) { return; } char svalue[100]; AddLog_P(LOG_LEVEL_DEBUG, PSTR(D_LOG_HTTP D_UPGRADE_STARTED)); @@ -1253,16 +1236,14 @@ void HandleUpgradeFirmwareStart() void HandleUploadDone() { - if (HttpUser()) { - return; - } + if (HttpUser()) { return; } AddLog_P(LOG_LEVEL_DEBUG, PSTR(D_LOG_HTTP D_UPLOAD_DONE)); char error[100]; WifiConfigCounter(); restart_flag = 0; - mqtt_retry_counter = 0; + MqttRetryCounter(0); String page = FPSTR(HTTP_HEAD); page.replace(F("{v}"), FPSTR(S_INFORMATION)); @@ -1302,13 +1283,9 @@ void HandleUploadLoop() // Based on ESP8266HTTPUpdateServer.cpp uses ESP8266WebServer Parsing.cpp and Cores Updater.cpp (Update) boolean _serialoutput = (LOG_LEVEL_DEBUG <= seriallog_level); - if (HTTP_USER == webserver_state) { - return; - } + if (HTTP_USER == webserver_state) { return; } if (upload_error) { - if (!upload_file_type) { - Update.end(); - } + if (!upload_file_type) { Update.end(); } return; } @@ -1324,16 +1301,14 @@ void HandleUploadLoop() snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_UPLOAD D_FILE " %s ..."), upload.filename.c_str()); AddLog(LOG_LEVEL_INFO); if (!upload_file_type) { - mqtt_retry_counter = 60; + MqttRetryCounter(60); #ifdef USE_EMULATION UdpDisconnect(); #endif // USE_EMULATION #ifdef USE_ARILUX_RF AriluxRfDisable(); // Prevent restart exception on Arilux Interrupt routine #endif // USE_ARILUX_RF - if (Settings.flag.mqtt_enabled) { - MqttClient.disconnect(); - } + if (Settings.flag.mqtt_enabled) MqttDisconnect(); uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000; if (!Update.begin(maxSketchSpace)) { //start with max available size upload_error = 2; @@ -1385,9 +1360,7 @@ void HandleUploadLoop() if (_serialoutput) { Serial.printf("."); upload_progress_dot_count++; - if (!(upload_progress_dot_count % 80)) { - Serial.println(); - } + if (!(upload_progress_dot_count % 80)) { Serial.println(); } } } } else if(!upload_error && (UPLOAD_FILE_END == upload.status)) { @@ -1396,9 +1369,7 @@ void HandleUploadLoop() } if (!upload_file_type) { if (!Update.end(true)) { // true to set the size to the current progress - if (_serialoutput) { - Update.printError(Serial); - } + if (_serialoutput) { Update.printError(Serial); } upload_error = 6; return; } @@ -1409,20 +1380,24 @@ void HandleUploadLoop() } } else if (UPLOAD_FILE_ABORTED == upload.status) { restart_flag = 0; - mqtt_retry_counter = 0; + MqttRetryCounter(0); upload_error = 7; - if (!upload_file_type) { - Update.end(); - } + if (!upload_file_type) { Update.end(); } } delay(0); } +void HandlePreflightRequest() +{ + WebServer->sendHeader(F("Access-Control-Allow-Origin"), F("*")); + WebServer->sendHeader(F("Access-Control-Allow-Methods"), F("GET, POST")); + WebServer->sendHeader(F("Access-Control-Allow-Headers"), F("authorization")); + WebServer->send(200, FPSTR(HDR_CTYPE_HTML), ""); +} + void HandleHttpCommand() { - if (HttpUser()) { - return; - } + if (HttpUser()) { return; } char svalue[INPUT_BUFFER_SIZE]; // big to serve Backlog AddLog_P(LOG_LEVEL_DEBUG, PSTR(D_LOG_HTTP D_COMMAND)); @@ -1442,12 +1417,7 @@ void HandleHttpCommand() if (valid) { byte curridx = web_log_index; WebGetArg("cmnd", svalue, sizeof(svalue)); - if (strlen(svalue)) { -// byte syslog_now = syslog_level; -// syslog_level = 0; // Disable UDP syslog to not trigger hardware WDT - Seems to work fine since 5.7.1d (global logging) - ExecuteCommand(svalue); -// syslog_level = syslog_now; - } + if (strlen(svalue)) { ExecuteCommand(svalue); } if (web_log_index != curridx) { byte counter = curridx; @@ -1460,9 +1430,7 @@ void HandleHttpCommand() // [14:49:36 MQTT: stat/wemos5/RESULT = {"POWER":"OFF"}] > [{"POWER":"OFF"}] char* JSON = (char*)memchr(tmp, '{', len); if (JSON) { // Is it a JSON message (and not only [15:26:08 MQT: stat/wemos5/POWER = O]) - if (message.length() > 1) { - message += F(","); - } + if (message.length() > 1) { message += F(","); } size_t JSONlen = len - (JSON - tmp); strlcpy(mqtt_data, JSON +1, JSONlen -2); message += mqtt_data; @@ -1484,10 +1452,7 @@ void HandleHttpCommand() void HandleConsole() { - if (HttpUser()) { - return; - } - + if (HttpUser()) { return; } AddLog_P(LOG_LEVEL_DEBUG, S_LOG_HTTP, S_CONSOLE); String page = FPSTR(HTTP_HEAD); @@ -1502,9 +1467,7 @@ void HandleConsole() void HandleAjaxConsoleRefresh() { - if (HttpUser()) { - return; - } + if (HttpUser()) { return; } char svalue[INPUT_BUFFER_SIZE]; // big to serve Backlog byte cflg = 1; byte counter = 0; // Initial start, should never be 0 again @@ -1513,16 +1476,11 @@ void HandleAjaxConsoleRefresh() if (strlen(svalue)) { snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_COMMAND "%s"), svalue); AddLog(LOG_LEVEL_INFO); -// byte syslog_now = syslog_level; -// syslog_level = 0; // Disable UDP syslog to not trigger hardware WDT - Seems to work fine since 5.7.1d (global logging) ExecuteCommand(svalue); -// syslog_level = syslog_now; } WebGetArg("c2", svalue, sizeof(svalue)); - if (strlen(svalue)) { - counter = atoi(svalue); - } + if (strlen(svalue)) { counter = atoi(svalue); } byte last_reset_web_log_flag = reset_web_log_flag; String message = F("}9"); // Cannot load mqtt_data here as <> will be encoded by replacements below @@ -1549,7 +1507,7 @@ void HandleAjaxConsoleRefresh() message += mqtt_data; } counter++; - if (!counter) counter++; // Skip 0 as it is not allowed + if (!counter) { counter++; } // Skip 0 as it is not allowed } while (counter != web_log_index); // XML encoding to fix blank console log in concert with javascript decodeURIComponent message.replace(F("%"), F("%25")); // Needs to be done first as otherwise the % in %26 will also be converted @@ -1565,9 +1523,7 @@ void HandleAjaxConsoleRefresh() void HandleInformation() { - if (HttpUser()) { - return; - } + if (HttpUser()) { return; } AddLog_P(LOG_LEVEL_DEBUG, S_LOG_HTTP, S_INFORMATION); char stopic[TOPSZ]; @@ -1590,7 +1546,7 @@ void HandleInformation() func += F(D_PROGRAM_VERSION "}2"); func += my_version; func += F("}1" D_BUILD_DATE_AND_TIME "}2"); func += GetBuildDateAndTime(); func += F("}1" D_CORE_AND_SDK_VERSION "}2" ARDUINO_ESP8266_RELEASE "/"); func += String(ESP.getSdkVersion()); - func += F("}1" D_UPTIME "}2"); func += GetUptime(); + func += F("}1" D_UPTIME "}2"); func += GetDateAndTime(DT_UPTIME); snprintf_P(stopic, sizeof(stopic), PSTR(" at %X"), GetSettingsAddress()); func += F("}1" D_FLASH_WRITE_COUNT "}2"); func += String(Settings.save_flag); func += stopic; func += F("}1" D_BOOT_COUNT "}2"); func += String(Settings.bootcount); @@ -1625,7 +1581,7 @@ void HandleInformation() func += F("}1" D_MQTT_USER "}2"); func += Settings.mqtt_user; func += F("}1" D_MQTT_TOPIC "}2"); func += Settings.mqtt_topic; func += F("}1" D_MQTT_GROUP_TOPIC "}2"); func += Settings.mqtt_grptopic; - GetTopic_P(stopic, CMND, Settings.mqtt_topic, ""); + GetTopic_P(stopic, CMND, mqtt_topic, ""); func += F("}1" D_MQTT_FULL_TOPIC "}2"); func += stopic; } else { @@ -1681,9 +1637,7 @@ void HandleInformation() void HandleRestart() { - if (HttpUser()) { - return; - } + if (HttpUser()) { return; } AddLog_P(LOG_LEVEL_DEBUG, S_LOG_HTTP, S_RESTART); String page = FPSTR(HTTP_HEAD); @@ -1707,9 +1661,7 @@ void HandleNotFound() // snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_HTTP "Not fount (%s)"), WebServer->uri().c_str()); // AddLog(LOG_LEVEL_DEBUG); - if (CaptivePortal()) { // If captive portal redirect instead of displaying the error page. - return; - } + if (CaptivePortal()) { return; } // If captive portal redirect instead of displaying the error page. #ifdef USE_EMULATION String path = WebServer->uri(); @@ -1747,9 +1699,7 @@ boolean ValidIpAddress(String str) { for (uint16_t i = 0; i < str.length(); i++) { int c = str.charAt(i); - if (c != '.' && (c < '0' || c > '9')) { - return false; - } + if (c != '.' && (c < '0' || c > '9')) { return false; } } return true; } diff --git a/sonoff/xdrv_00_mqtt.ino b/sonoff/xdrv_00_mqtt.ino new file mode 100644 index 000000000..8328cef82 --- /dev/null +++ b/sonoff/xdrv_00_mqtt.ino @@ -0,0 +1,768 @@ +/* + xdrv_00_mqtt.ino - mqtt support for Sonoff-Tasmota + + Copyright (C) 2018 Theo Arends + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +/*********************************************************************************************\ + * Select ONE of possible MQTT library types below +\*********************************************************************************************/ +// Default MQTT driver for both non-TLS and TLS connections. Blocks network if MQTT server is unavailable. +//#define MQTT_LIBRARY_TYPE MQTT_PUBSUBCLIENT // Use PubSubClient library +// Alternative MQTT driver does not block network when MQTT server is unavailable. No TLS support +//#define MQTT_LIBRARY_TYPE MQTT_TASMOTAMQTT // Use TasmotaMqtt library (+4k4 code, +4k mem) - non-TLS only +// Alternative MQTT driver does not block network when MQTT server is unavailable. No TLS support +//#define MQTT_LIBRARY_TYPE MQTT_ESPMQTTARDUINO // Use (patched) esp-mqtt-arduino library (+4k8 code, +4k mem) - non-TLS only + +#ifdef USE_MQTT_TLS +#ifdef MQTT_LIBRARY_TYPE +#undef MQTT_LIBRARY_TYPE +#endif +#define MQTT_LIBRARY_TYPE MQTT_PUBSUBCLIENT // Use PubSubClient library as it only supports TLS +#else +#ifndef MQTT_LIBRARY_TYPE +#define MQTT_LIBRARY_TYPE MQTT_PUBSUBCLIENT // Use PubSubClient library as default +#endif +#endif + +/*********************************************************************************************/ + +enum MqttCommands { + CMND_MQTTHOST, CMND_MQTTPORT, CMND_MQTTRETRY, CMND_STATETEXT, CMND_MQTTFINGERPRINT, CMND_MQTTCLIENT, + CMND_MQTTUSER, CMND_MQTTPASSWORD, CMND_FULLTOPIC, CMND_PREFIX, CMND_GROUPTOPIC, CMND_TOPIC, CMND_PUBLISH, + CMND_BUTTONTOPIC, CMND_SWITCHTOPIC, CMND_BUTTONRETAIN, CMND_SWITCHRETAIN, CMND_POWERRETAIN, CMND_SENSORRETAIN }; +const char kMqttCommands[] PROGMEM = + D_CMND_MQTTHOST "|" D_CMND_MQTTPORT "|" D_CMND_MQTTRETRY "|" D_CMND_STATETEXT "|" D_CMND_MQTTFINGERPRINT "|" D_CMND_MQTTCLIENT "|" + D_CMND_MQTTUSER "|" D_CMND_MQTTPASSWORD "|" D_CMND_FULLTOPIC "|" D_CMND_PREFIX "|" D_CMND_GROUPTOPIC "|" D_CMND_TOPIC "|" D_CMND_PUBLISH "|" + D_CMND_BUTTONTOPIC "|" D_CMND_SWITCHTOPIC "|" D_CMND_BUTTONRETAIN "|" D_CMND_SWITCHRETAIN "|" D_CMND_POWERRETAIN "|" D_CMND_SENSORRETAIN ; + +uint8_t mqtt_retry_counter = 1; // MQTT connection retry counter +uint8_t mqtt_initial_connection_state = 2; // MQTT connection messages state +bool mqtt_connected = false; // MQTT virtual connection status + +/*********************************************************************************************\ + * MQTT driver specific code need to provide the following functions: + * + * bool MqttIsConnected() + * void MqttDisconnect() + * void MqttSubscribeLib(char *topic) + * bool MqttPublishLib(const char* topic, boolean retained) + * void MqttLoop() +\*********************************************************************************************/ + +#if (MQTT_LIBRARY_TYPE == MQTT_PUBSUBCLIENT) /***********************************************/ + +#include + +// Max message size calculated by PubSubClient is (MQTT_MAX_PACKET_SIZE < 5 + 2 + strlen(topic) + plength) +#if (MQTT_MAX_PACKET_SIZE -TOPSZ -7) < MIN_MESSZ // If the max message size is too small, throw an error at compile time. See PubSubClient.cpp line 359 + #error "MQTT_MAX_PACKET_SIZE is too small in libraries/PubSubClient/src/PubSubClient.h, increase it to at least 1000" +#endif + +PubSubClient MqttClient(EspClient); + +bool MqttIsConnected() +{ + return MqttClient.connected(); +} + +void MqttDisconnect() +{ + MqttClient.disconnect(); +} + +void MqttSubscribeLib(char *topic) +{ + MqttClient.subscribe(topic); + MqttClient.loop(); // Solve LmacRxBlk:1 messages +} + +bool MqttPublishLib(const char* topic, boolean retained) +{ + return MqttClient.publish(topic, mqtt_data, retained); +} + +void MqttLoop() +{ + MqttClient.loop(); +} + +#elif (MQTT_LIBRARY_TYPE == MQTT_TASMOTAMQTT) /**********************************************/ + +#include +TasmotaMqtt MqttClient; + +bool MqttIsConnected() +{ + return mqtt_connected; +} + +void MqttDisconnect() +{ + MqttClient.Disconnect(); +} + +void MqttDisconnectedCb() +{ + MqttDisconnected(MqttClient.State()); // status codes are documented in file mqtt.h as tConnState +} + +void MqttSubscribeLib(char *topic) +{ + MqttClient.Subscribe(topic, 0); +} + +bool MqttPublishLib(const char* topic, boolean retained) +{ + return MqttClient.Publish(topic, mqtt_data, strlen(mqtt_data), 0, retained); +} + +void MqttLoop() +{ +} + +#elif (MQTT_LIBRARY_TYPE == MQTT_ESPMQTTARDUINO) /*******************************************/ + +#include +MQTT *MqttClient = NULL; + +bool MqttIsConnected() +{ + return mqtt_connected; +} + +void MqttDisconnect() +{ + if (MqttClient) MqttClient->disconnect(); +} + +void MqttDisconnectedCb() +{ + MqttDisconnected(MqttClient->getState()); // status codes are documented in file mqtt.h as tConnState +} + +void MqttMyDataCb(const char* topic, uint32_t topic_len, const char* data, uint32_t data_len) +{ + char topic_copy[topic_len +1]; + + memcpy(topic_copy, topic, topic_len); + topic_copy[topic_len] = 0; + if (0 == data_len) data = (const char*)&topic_copy + topic_len; + MqttDataHandler((char*)topic_copy, (byte*)data, data_len); +} + +void MqttSubscribeLib(char *topic) +{ + MqttClient->subscribe(topic); +} + +bool MqttPublishLib(const char* topic, boolean retained) +{ + return MqttClient->publish(topic, mqtt_data, strlen(mqtt_data), 0, retained); +} + +void MqttLoop() +{ +} + +#endif // MQTT_LIBRARY_TYPE + +/*********************************************************************************************/ + +int MqttLibraryType() +{ + return (int)MQTT_LIBRARY_TYPE; +} + +void MqttRetryCounter(uint8_t value) +{ + mqtt_retry_counter = value; +} + +void MqttSubscribe(char *topic) +{ + snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_MQTT D_SUBSCRIBE_TO " %s"), topic); + AddLog(LOG_LEVEL_DEBUG); + MqttSubscribeLib(topic); +} + +void MqttPublishDirect(const char* topic, boolean retained) +{ + char sretained[CMDSZ]; + char slog_type[10]; + + sretained[0] = '\0'; + snprintf_P(slog_type, sizeof(slog_type), PSTR(D_LOG_RESULT)); + + if (Settings.flag.mqtt_enabled) { + if (MqttIsConnected()) { + if (MqttPublishLib(topic, retained)) { + snprintf_P(slog_type, sizeof(slog_type), PSTR(D_LOG_MQTT)); + if (retained) { + snprintf_P(sretained, sizeof(sretained), PSTR(" (" D_RETAINED ")")); + } + } + } + } + + snprintf_P(log_data, sizeof(log_data), PSTR("%s%s = %s"), slog_type, (Settings.flag.mqtt_enabled) ? topic : strrchr(topic,'/')+1, mqtt_data); + if (strlen(log_data) >= (sizeof(log_data) - strlen(sretained) -1)) { + log_data[sizeof(log_data) - strlen(sretained) -5] = '\0'; + snprintf_P(log_data, sizeof(log_data), PSTR("%s ..."), log_data); + } + snprintf_P(log_data, sizeof(log_data), PSTR("%s%s"), log_data, sretained); + + AddLog(LOG_LEVEL_INFO); + if (Settings.ledstate &0x04) { + blinks++; + } +} + +void MqttPublish(const char* topic, boolean retained) +{ + char *me; + + if (!strcmp(Settings.mqtt_prefix[0],Settings.mqtt_prefix[1])) { + me = strstr(topic,Settings.mqtt_prefix[0]); + if (me == topic) { + mqtt_cmnd_publish += 8; + } + } + MqttPublishDirect(topic, retained); +} + +void MqttPublish(const char* topic) +{ + MqttPublish(topic, false); +} + +void MqttPublishPrefixTopic_P(uint8_t prefix, const char* subtopic, boolean retained) +{ +/* prefix 0 = cmnd using subtopic + * prefix 1 = stat using subtopic + * prefix 2 = tele using subtopic + * prefix 4 = cmnd using subtopic or RESULT + * prefix 5 = stat using subtopic or RESULT + * prefix 6 = tele using subtopic or RESULT + */ + char romram[33]; + char stopic[TOPSZ]; + + snprintf_P(romram, sizeof(romram), ((prefix > 3) && !Settings.flag.mqtt_response) ? S_RSLT_RESULT : subtopic); + for (byte i = 0; i < strlen(romram); i++) { + romram[i] = toupper(romram[i]); + } + prefix &= 3; + GetTopic_P(stopic, prefix, mqtt_topic, romram); + MqttPublish(stopic, retained); +} + +void MqttPublishPrefixTopic_P(uint8_t prefix, const char* subtopic) +{ + MqttPublishPrefixTopic_P(prefix, subtopic, false); +} + +void MqttPublishPowerState(byte device) +{ + char stopic[TOPSZ]; + char scommand[33]; + + if ((device < 1) || (device > devices_present)) { + device = 1; + } + GetPowerDevice(scommand, device, sizeof(scommand)); + GetTopic_P(stopic, STAT, mqtt_topic, (Settings.flag.mqtt_response) ? scommand : S_RSLT_RESULT); + snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, scommand, GetStateText(bitRead(power, device -1))); + MqttPublish(stopic); + + GetTopic_P(stopic, STAT, mqtt_topic, scommand); + snprintf_P(mqtt_data, sizeof(mqtt_data), GetStateText(bitRead(power, device -1))); + MqttPublish(stopic, Settings.flag.mqtt_power_retain); +} + +void MqttPublishPowerBlinkState(byte device) +{ + char scommand[33]; + + if ((device < 1) || (device > devices_present)) { + device = 1; + } + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"%s\":\"" D_JSON_BLINK " %s\"}"), + GetPowerDevice(scommand, device, sizeof(scommand)), GetStateText(bitRead(blink_mask, device -1))); + + MqttPublishPrefixTopic_P(RESULT_OR_STAT, S_RSLT_POWER); +} + +/*********************************************************************************************/ + +void MqttDisconnected(int state) +{ + mqtt_connected = false; + mqtt_retry_counter = Settings.mqtt_retry; + + snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_MQTT D_CONNECT_FAILED_TO " %s:%d, rc %d. " D_RETRY_IN " %d " D_UNIT_SECOND), + Settings.mqtt_host, Settings.mqtt_port, state, mqtt_retry_counter); + AddLog(LOG_LEVEL_INFO); +#ifdef USE_RULES + strncpy_P(mqtt_data, PSTR("{\"MQTT\":{\"Disconnected\":1}}"), sizeof(mqtt_data)); + RulesProcess(); +#endif // USE_RULES +} + +void MqttConnected() +{ + char stopic[TOPSZ]; + + if (Settings.flag.mqtt_enabled) { + AddLog_P(LOG_LEVEL_INFO, S_LOG_MQTT, PSTR(D_CONNECTED)); + mqtt_connected = true; + mqtt_retry_counter = 0; + + GetTopic_P(stopic, TELE, mqtt_topic, S_LWT); + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR(D_ONLINE)); + MqttPublish(stopic, true); + + // Satisfy iobroker (#299) + mqtt_data[0] = '\0'; + MqttPublishPrefixTopic_P(CMND, S_RSLT_POWER); + + GetTopic_P(stopic, CMND, mqtt_topic, PSTR("#")); + MqttSubscribe(stopic); + if (strstr(Settings.mqtt_fulltopic, MQTT_TOKEN_TOPIC) != NULL) { + GetTopic_P(stopic, CMND, Settings.mqtt_grptopic, PSTR("#")); + MqttSubscribe(stopic); + fallback_topic_flag = 1; + GetTopic_P(stopic, CMND, mqtt_client, PSTR("#")); + fallback_topic_flag = 0; + MqttSubscribe(stopic); + } + + XdrvCall(FUNC_MQTT_SUBSCRIBE); + } + + if (mqtt_initial_connection_state) { + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_CMND_MODULE "\":\"%s\",\"" D_JSON_VERSION "\":\"%s\",\"" D_JSON_FALLBACKTOPIC "\":\"%s\",\"" D_CMND_GROUPTOPIC "\":\"%s\"}"), + my_module.name, my_version, mqtt_client, Settings.mqtt_grptopic); + MqttPublishPrefixTopic_P(TELE, PSTR(D_RSLT_INFO "1")); +#ifdef USE_WEBSERVER + if (Settings.webserver) { + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_JSON_WEBSERVER_MODE "\":\"%s\",\"" D_CMND_HOSTNAME "\":\"%s\",\"" D_CMND_IPADDRESS "\":\"%s\"}"), + (2 == Settings.webserver) ? D_ADMIN : D_USER, my_hostname, WiFi.localIP().toString().c_str()); + MqttPublishPrefixTopic_P(TELE, PSTR(D_RSLT_INFO "2")); + } +#endif // USE_WEBSERVER + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_JSON_RESTARTREASON "\":\"%s\"}"), + (GetResetReason() == "Exception") ? ESP.getResetInfo().c_str() : GetResetReason().c_str()); + MqttPublishPrefixTopic_P(TELE, PSTR(D_RSLT_INFO "3")); + if (Settings.tele_period) { + tele_period = Settings.tele_period -9; + } + status_update_timer = 2; +#ifdef USE_RULES + strncpy_P(mqtt_data, PSTR("{\"System\":{\"Boot\":1}}"), sizeof(mqtt_data)); + RulesProcess(); +#endif // USE_RULES + XdrvCall(FUNC_MQTT_INIT); + } + mqtt_initial_connection_state = 0; +#ifdef USE_RULES + strncpy_P(mqtt_data, PSTR("{\"MQTT\":{\"Connected\":1}}"), sizeof(mqtt_data)); + RulesProcess(); +#endif // USE_RULES +} + +#ifdef USE_MQTT_TLS +boolean MqttCheckTls() +{ + char fingerprint1[60]; + char fingerprint2[60]; + boolean result = false; + + fingerprint1[0] = '\0'; + fingerprint2[0] = '\0'; + for (byte i = 0; i < sizeof(Settings.mqtt_fingerprint[0]); i++) { + snprintf_P(fingerprint1, sizeof(fingerprint1), PSTR("%s%s%02X"), fingerprint1, (i) ? " " : "", Settings.mqtt_fingerprint[0][i]); + snprintf_P(fingerprint2, sizeof(fingerprint2), PSTR("%s%s%02X"), fingerprint2, (i) ? " " : "", Settings.mqtt_fingerprint[1][i]); + } + + AddLog_P(LOG_LEVEL_INFO, S_LOG_MQTT, PSTR(D_FINGERPRINT)); + +//#ifdef ARDUINO_ESP8266_RELEASE_2_4_1 + EspClient = WiFiClientSecure(); // Wifi Secure Client reconnect issue 4497 (https://github.com/esp8266/Arduino/issues/4497) +//#endif + + if (!EspClient.connect(Settings.mqtt_host, Settings.mqtt_port)) { + snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_MQTT D_TLS_CONNECT_FAILED_TO " %s:%d. " D_RETRY_IN " %d " D_UNIT_SECOND), + Settings.mqtt_host, Settings.mqtt_port, mqtt_retry_counter); + AddLog(LOG_LEVEL_DEBUG); + } else { + if (EspClient.verify(fingerprint1, Settings.mqtt_host)) { + AddLog_P(LOG_LEVEL_INFO, S_LOG_MQTT, PSTR(D_VERIFIED "1")); + result = true; + } + else if (EspClient.verify(fingerprint2, Settings.mqtt_host)) { + AddLog_P(LOG_LEVEL_INFO, S_LOG_MQTT, PSTR(D_VERIFIED "2")); + result = true; + } + } + if (!result) AddLog_P(LOG_LEVEL_INFO, S_LOG_MQTT, PSTR(D_FAILED)); + EspClient.stop(); + yield(); + return result; +} +#endif // USE_MQTT_TLS + +void MqttReconnect() +{ + char stopic[TOPSZ]; + + if (!Settings.flag.mqtt_enabled) { + MqttConnected(); + return; + } + +#if defined(USE_WEBSERVER) && defined(USE_EMULATION) + UdpDisconnect(); +#endif // USE_EMULATION + + AddLog_P(LOG_LEVEL_INFO, S_LOG_MQTT, PSTR(D_ATTEMPTING_CONNECTION)); + + mqtt_connected = false; + mqtt_retry_counter = Settings.mqtt_retry; + +#ifndef USE_MQTT_TLS +#ifdef USE_DISCOVERY +#ifdef MQTT_HOST_DISCOVERY + if (!strlen(Settings.mqtt_host)) { + MdnsDiscoverMqttServer(); + } +#endif // MQTT_HOST_DISCOVERY +#endif // USE_DISCOVERY +#endif // USE_MQTT_TLS + + char *mqtt_user = NULL; + char *mqtt_pwd = NULL; + if (strlen(Settings.mqtt_user) > 0) mqtt_user = Settings.mqtt_user; + if (strlen(Settings.mqtt_pwd) > 0) mqtt_pwd = Settings.mqtt_pwd; + + GetTopic_P(stopic, TELE, mqtt_topic, S_LWT); + snprintf_P(mqtt_data, sizeof(mqtt_data), S_OFFLINE); + + if (2 == mqtt_initial_connection_state) { // Executed once just after power on and wifi is connected +#ifdef USE_MQTT_TLS + if (!MqttCheckTls()) return; +#endif // USE_MQTT_TLS + +#if (MQTT_LIBRARY_TYPE == MQTT_TASMOTAMQTT) + MqttClient.InitConnection(Settings.mqtt_host, Settings.mqtt_port); + MqttClient.InitClient(mqtt_client, mqtt_user, mqtt_pwd, MQTT_KEEPALIVE); + MqttClient.InitLWT(stopic, mqtt_data, 1, true); + MqttClient.OnConnected(MqttConnected); + MqttClient.OnDisconnected(MqttDisconnectedCb); + MqttClient.OnData(MqttDataHandler); +#elif (MQTT_LIBRARY_TYPE == MQTT_ESPMQTTARDUINO) + MqttClient = new MQTT(mqtt_client, Settings.mqtt_host, Settings.mqtt_port, stopic, 1, true, mqtt_data); + MqttClient->setUserPwd(mqtt_user, mqtt_pwd); + MqttClient->onConnected(MqttConnected); + MqttClient->onDisconnected(MqttDisconnectedCb); + MqttClient->onData(MqttMyDataCb); +#endif + + mqtt_initial_connection_state = 1; + } + +//#ifdef ARDUINO_ESP8266_RELEASE_2_4_1 +#ifdef USE_MQTT_TLS + EspClient = WiFiClientSecure(); // Wifi Secure Client reconnect issue 4497 (https://github.com/esp8266/Arduino/issues/4497) +#else + EspClient = WiFiClient(); // Wifi Client reconnect issue 4497 (https://github.com/esp8266/Arduino/issues/4497) +#endif +//#endif + +#if (MQTT_LIBRARY_TYPE == MQTT_PUBSUBCLIENT) + MqttClient.setCallback(MqttDataHandler); + MqttClient.setServer(Settings.mqtt_host, Settings.mqtt_port); + if (MqttClient.connect(mqtt_client, mqtt_user, mqtt_pwd, stopic, 1, true, mqtt_data)) { + MqttConnected(); + } else { + MqttDisconnected(MqttClient.state()); // status codes are documented here http://pubsubclient.knolleary.net/api.html#state + } +#elif (MQTT_LIBRARY_TYPE == MQTT_TASMOTAMQTT) + MqttClient.Connect(); +#elif (MQTT_LIBRARY_TYPE == MQTT_ESPMQTTARDUINO) + MqttClient->connect(); +#endif // MQTT_LIBRARY_TYPE +} + +void MqttCheck() +{ + if (Settings.flag.mqtt_enabled) { + if (!MqttIsConnected()) { + if (!mqtt_retry_counter) { + MqttReconnect(); + } else { + mqtt_retry_counter--; + } + } + } else { + if (mqtt_initial_connection_state) MqttReconnect(); + } +} + +/*********************************************************************************************/ + +bool MqttCommand() +{ + char command [CMDSZ]; + bool serviced = true; + char stemp1[TOPSZ]; + char scommand[CMDSZ]; + uint16_t i; + + uint16_t index = XdrvMailbox.index; + uint16_t data_len = XdrvMailbox.data_len; + uint16_t payload16 = XdrvMailbox.payload16; + int16_t payload = XdrvMailbox.payload; + uint8_t grpflg = XdrvMailbox.grpflg; + char *type = XdrvMailbox.topic; + char *dataBuf = XdrvMailbox.data; + + int command_code = GetCommandCode(command, sizeof(command), type, kMqttCommands); + if (CMND_MQTTHOST == command_code) { + if ((data_len > 0) && (data_len < sizeof(Settings.mqtt_host))) { + strlcpy(Settings.mqtt_host, (!strcmp(dataBuf,"0")) ? "" : (1 == payload) ? MQTT_HOST : dataBuf, sizeof(Settings.mqtt_host)); + restart_flag = 2; + } + snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, Settings.mqtt_host); + } + else if (CMND_MQTTPORT == command_code) { + if (payload16 > 0) { + Settings.mqtt_port = (1 == payload16) ? MQTT_PORT : payload16; + restart_flag = 2; + } + snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE, command, Settings.mqtt_port); + } + else if (CMND_MQTTRETRY == command_code) { + if ((payload >= MQTT_RETRY_SECS) && (payload < 32001)) { + Settings.mqtt_retry = payload; + mqtt_retry_counter = Settings.mqtt_retry; + } + snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE, command, Settings.mqtt_retry); + } + else if ((CMND_STATETEXT == command_code) && (index > 0) && (index <= 4)) { + if ((data_len > 0) && (data_len < sizeof(Settings.state_text[0]))) { + for(i = 0; i <= data_len; i++) { + if (dataBuf[i] == ' ') dataBuf[i] = '_'; + } + strlcpy(Settings.state_text[index -1], dataBuf, sizeof(Settings.state_text[0])); + } + snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_SVALUE, command, index, GetStateText(index -1)); + } +#ifdef USE_MQTT_TLS + else if ((CMND_MQTTFINGERPRINT == command_code) && (index > 0) && (index <= 2)) { + char fingerprint[60]; + if ((data_len > 0) && (data_len < sizeof(fingerprint))) { + strlcpy(fingerprint, (!strcmp(dataBuf,"0")) ? "" : (1 == payload) ? (1 == index) ? MQTT_FINGERPRINT1 : MQTT_FINGERPRINT2 : dataBuf, sizeof(fingerprint)); + char *p = fingerprint; + for (byte i = 0; i < 20; i++) { + Settings.mqtt_fingerprint[index -1][i] = strtol(p, &p, 16); + } + restart_flag = 2; + } + + fingerprint[0] = '\0'; + for (byte i = 0; i < sizeof(Settings.mqtt_fingerprint[index -1]); i++) { + snprintf_P(fingerprint, sizeof(fingerprint), PSTR("%s%s%02X"), fingerprint, (i) ? " " : "", Settings.mqtt_fingerprint[index -1][i]); + } + snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_SVALUE, command, index, fingerprint); + } +#endif + else if ((CMND_MQTTCLIENT == command_code) && !grpflg) { + if ((data_len > 0) && (data_len < sizeof(Settings.mqtt_client))) { + strlcpy(Settings.mqtt_client, (1 == payload) ? MQTT_CLIENT_ID : dataBuf, sizeof(Settings.mqtt_client)); + restart_flag = 2; + } + snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, Settings.mqtt_client); + } + else if (CMND_MQTTUSER == command_code) { + if ((data_len > 0) && (data_len < sizeof(Settings.mqtt_user))) { + strlcpy(Settings.mqtt_user, (!strcmp(dataBuf,"0")) ? "" : (1 == payload) ? MQTT_USER : dataBuf, sizeof(Settings.mqtt_user)); + restart_flag = 2; + } + snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, Settings.mqtt_user); + } + else if (CMND_MQTTPASSWORD == command_code) { + if ((data_len > 0) && (data_len < sizeof(Settings.mqtt_pwd))) { + strlcpy(Settings.mqtt_pwd, (!strcmp(dataBuf,"0")) ? "" : (1 == payload) ? MQTT_PASS : dataBuf, sizeof(Settings.mqtt_pwd)); + snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, Settings.mqtt_pwd); + restart_flag = 2; + } else { + snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_ASTERIX, command); + } + } + else if (CMND_FULLTOPIC == command_code) { + if ((data_len > 0) && (data_len < sizeof(Settings.mqtt_fulltopic))) { + MakeValidMqtt(1, dataBuf); + if (!strcmp(dataBuf, mqtt_client)) payload = 1; + strlcpy(stemp1, (1 == payload) ? MQTT_FULLTOPIC : dataBuf, sizeof(stemp1)); + if (strcmp(stemp1, Settings.mqtt_fulltopic)) { + snprintf_P(mqtt_data, sizeof(mqtt_data), (Settings.flag.mqtt_offline) ? S_OFFLINE : ""); + MqttPublishPrefixTopic_P(TELE, PSTR(D_LWT), true); // Offline or remove previous retained topic + strlcpy(Settings.mqtt_fulltopic, stemp1, sizeof(Settings.mqtt_fulltopic)); + restart_flag = 2; + } + } + snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, Settings.mqtt_fulltopic); + } + else if ((CMND_PREFIX == command_code) && (index > 0) && (index <= 3)) { + if ((data_len > 0) && (data_len < sizeof(Settings.mqtt_prefix[0]))) { + MakeValidMqtt(0, dataBuf); + strlcpy(Settings.mqtt_prefix[index -1], (1 == payload) ? (1==index)?SUB_PREFIX:(2==index)?PUB_PREFIX:PUB_PREFIX2 : dataBuf, sizeof(Settings.mqtt_prefix[0])); +// if (Settings.mqtt_prefix[index -1][strlen(Settings.mqtt_prefix[index -1])] == '/') Settings.mqtt_prefix[index -1][strlen(Settings.mqtt_prefix[index -1])] = 0; + restart_flag = 2; + } + snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_SVALUE, command, index, Settings.mqtt_prefix[index -1]); + } + else if (CMND_PUBLISH == command_code) { + if (data_len > 0) { + char *mqtt_part = strtok(dataBuf, " "); + if (mqtt_part) { + snprintf(stemp1, sizeof(stemp1), mqtt_part); + mqtt_part = strtok(NULL, " "); + if (mqtt_part) { + snprintf(mqtt_data, sizeof(mqtt_data), mqtt_part); + } else { + mqtt_data[0] = '\0'; + } + MqttPublishDirect(stemp1, false); +// snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, D_JSON_DONE); + mqtt_data[0] = '\0'; + } + } + } + else if (CMND_GROUPTOPIC == command_code) { + if ((data_len > 0) && (data_len < sizeof(Settings.mqtt_grptopic))) { + MakeValidMqtt(0, dataBuf); + if (!strcmp(dataBuf, mqtt_client)) payload = 1; + strlcpy(Settings.mqtt_grptopic, (1 == payload) ? MQTT_GRPTOPIC : dataBuf, sizeof(Settings.mqtt_grptopic)); + restart_flag = 2; + } + snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, Settings.mqtt_grptopic); + } + else if ((CMND_TOPIC == command_code) && !grpflg) { + if ((data_len > 0) && (data_len < sizeof(Settings.mqtt_topic))) { + MakeValidMqtt(0, dataBuf); + if (!strcmp(dataBuf, mqtt_client)) payload = 1; + strlcpy(stemp1, (1 == payload) ? MQTT_TOPIC : dataBuf, sizeof(stemp1)); + if (strcmp(stemp1, Settings.mqtt_topic)) { + snprintf_P(mqtt_data, sizeof(mqtt_data), (Settings.flag.mqtt_offline) ? S_OFFLINE : ""); + MqttPublishPrefixTopic_P(TELE, PSTR(D_LWT), true); // Offline or remove previous retained topic + strlcpy(Settings.mqtt_topic, stemp1, sizeof(Settings.mqtt_topic)); + restart_flag = 2; + } + } + snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, Settings.mqtt_topic); + } + else if ((CMND_BUTTONTOPIC == command_code) && !grpflg) { + if ((data_len > 0) && (data_len < sizeof(Settings.button_topic))) { + MakeValidMqtt(0, dataBuf); + if (!strcmp(dataBuf, mqtt_client)) payload = 1; + strlcpy(Settings.button_topic, (!strcmp(dataBuf,"0")) ? "" : (1 == payload) ? mqtt_topic : dataBuf, sizeof(Settings.button_topic)); + } + snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, Settings.button_topic); + } + else if (CMND_SWITCHTOPIC == command_code) { + if ((data_len > 0) && (data_len < sizeof(Settings.switch_topic))) { + MakeValidMqtt(0, dataBuf); + if (!strcmp(dataBuf, mqtt_client)) payload = 1; + strlcpy(Settings.switch_topic, (!strcmp(dataBuf,"0")) ? "" : (1 == payload) ? mqtt_topic : dataBuf, sizeof(Settings.switch_topic)); + } + snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, Settings.switch_topic); + } + else if (CMND_BUTTONRETAIN == command_code) { + if ((payload >= 0) && (payload <= 1)) { + strlcpy(Settings.button_topic, mqtt_topic, sizeof(Settings.button_topic)); + if (!payload) { + for(i = 1; i <= MAX_KEYS; i++) { + SendKey(0, i, 9); // Clear MQTT retain in broker + } + } + Settings.flag.mqtt_button_retain = payload; + } + snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, GetStateText(Settings.flag.mqtt_button_retain)); + } + else if (CMND_SWITCHRETAIN == command_code) { + if ((payload >= 0) && (payload <= 1)) { + strlcpy(Settings.button_topic, mqtt_topic, sizeof(Settings.button_topic)); + if (!payload) { + for(i = 1; i <= MAX_SWITCHES; i++) { + SendKey(1, i, 9); // Clear MQTT retain in broker + } + } + Settings.flag.mqtt_switch_retain = payload; + } + snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, GetStateText(Settings.flag.mqtt_switch_retain)); + } + else if (CMND_POWERRETAIN == command_code) { + if ((payload >= 0) && (payload <= 1)) { + if (!payload) { + for(i = 1; i <= devices_present; i++) { // Clear MQTT retain in broker + GetTopic_P(stemp1, STAT, mqtt_topic, GetPowerDevice(scommand, i, sizeof(scommand))); + mqtt_data[0] = '\0'; + MqttPublish(stemp1, Settings.flag.mqtt_power_retain); + } + } + Settings.flag.mqtt_power_retain = payload; + } + snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, GetStateText(Settings.flag.mqtt_power_retain)); + } + else if (CMND_SENSORRETAIN == command_code) { + if ((payload >= 0) && (payload <= 1)) { + if (!payload) { + mqtt_data[0] = '\0'; + MqttPublishPrefixTopic_P(TELE, PSTR(D_RSLT_SENSOR), Settings.flag.mqtt_sensor_retain); + MqttPublishPrefixTopic_P(TELE, PSTR(D_RSLT_ENERGY), Settings.flag.mqtt_sensor_retain); + } + Settings.flag.mqtt_sensor_retain = payload; + } + snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, GetStateText(Settings.flag.mqtt_sensor_retain)); + } + else serviced = false; + return serviced; +} + +/*********************************************************************************************\ + * Interface +\*********************************************************************************************/ + +#define XDRV_00 + +boolean Xdrv00(byte function) +{ + boolean result = false; + + if (Settings.flag.mqtt_enabled) { + switch (function) { + case FUNC_LOOP: + MqttLoop(); + break; + case FUNC_COMMAND: + result = MqttCommand(); + break; + } + } + return result; +} diff --git a/sonoff/xdrv_01_light.ino b/sonoff/xdrv_01_light.ino index 432788878..9230c1529 100644 --- a/sonoff/xdrv_01_light.ino +++ b/sonoff/xdrv_01_light.ino @@ -55,10 +55,12 @@ enum LightCommands { CMND_COLOR, CMND_COLORTEMPERATURE, CMND_DIMMER, CMND_LED, CMND_LEDTABLE, CMND_FADE, - CMND_PIXELS, CMND_SCHEME, CMND_SPEED, CMND_WAKEUP, CMND_WAKEUPDURATION, CMND_WIDTH, CMND_UNDOCA }; + CMND_PIXELS, CMND_ROTATION, CMND_SCHEME, CMND_SPEED, CMND_WAKEUP, CMND_WAKEUPDURATION, + CMND_WIDTH, CMND_CHANNEL, CMND_HSBCOLOR, CMND_UNDOCA }; const char kLightCommands[] PROGMEM = D_CMND_COLOR "|" D_CMND_COLORTEMPERATURE "|" D_CMND_DIMMER "|" D_CMND_LED "|" D_CMND_LEDTABLE "|" D_CMND_FADE "|" - D_CMND_PIXELS "|" D_CMND_SCHEME "|" D_CMND_SPEED "|" D_CMND_WAKEUP "|" D_CMND_WAKEUPDURATION "|" D_CMND_WIDTH "|UNDOCA" ; + D_CMND_PIXELS "|" D_CMND_ROTATION "|" D_CMND_SCHEME "|" D_CMND_SPEED "|" D_CMND_WAKEUP "|" D_CMND_WAKEUPDURATION "|" + D_CMND_WIDTH "|" D_CMND_CHANNEL "|" D_CMND_HSBCOLOR "|UNDOCA" ; struct LRgbColor { uint8_t R, G, B; @@ -376,7 +378,7 @@ void LightInit() } #ifdef USE_WS2812 // ************************************************************************ else if (LT_WS2812 == light_type) { -#if (USE_WS2812_CTYPE > 1) +#if (USE_WS2812_CTYPE > NEO_3LED) light_subtype++; // from RGB to RGBW #endif Ws2812Init(); @@ -535,6 +537,8 @@ void LightState(uint8_t append) { char scolor[25]; char scommand[33]; + float hsb[3]; + int16_t h,s,b; if (append) { snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,"), mqtt_data); @@ -546,6 +550,19 @@ void LightState(uint8_t append) mqtt_data, scommand, GetStateText(light_power), Settings.light_dimmer); if (light_subtype > LST_SINGLE) { snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"" D_CMND_COLOR "\":\"%s\""), mqtt_data, LightGetColor(0, scolor)); + // Add status for HSB + LightGetHsb(&hsb[0],&hsb[1],&hsb[2]); + // Scale these percentages up to the numbers expected byt he client + h = round(hsb[0] * 360); + s = round(hsb[1] * 100); + b = round(hsb[2] * 100); + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"" D_CMND_HSBCOLOR "\":\"%d,%d,%d\""), mqtt_data, h,s,b); + // Add status for each channel + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"" D_CMND_CHANNEL "\":[" ), mqtt_data); + for (byte i = 0; i < light_subtype; i++) { + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s%s%d" ), mqtt_data, (i > 0 ? "," : ""), round(light_current_color[i]/2.55)); + } + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s]" ), mqtt_data); } if ((LST_COLDWARM == light_subtype) || (LST_RGBWC == light_subtype)) { snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"" D_CMND_COLORTEMPERATURE "\":%d"), mqtt_data, LightGetColorTemp()); @@ -974,11 +991,10 @@ boolean LightColorEntry(char *buffer, uint8_t buffer_length) light_entry_color[i++] = atoi(str); } } -// entry_type = (light_subtype == i) ? 2 : 0; // Decimal entry_type = 2; // Decimal } - else if ((2 * light_subtype) == buffer_length) { // Hexadecimal entry - for (byte i = 0; i < light_subtype; i++) { + else if (((2 * light_subtype) == buffer_length) || (buffer_length > 3)) { // Hexadecimal entry + for (byte i = 0; i < buffer_length / 2; i++) { strlcpy(scolor, buffer + (i *2), 3); light_entry_color[i] = (uint8_t)strtol(scolor, &p, 16); } @@ -1018,7 +1034,7 @@ boolean LightCommand() char option = (1 == XdrvMailbox.data_len) ? XdrvMailbox.data[0] : '\0'; int command_code = GetCommandCode(command, sizeof(command), XdrvMailbox.topic, kLightCommands); - if ((CMND_COLOR == command_code) && (light_subtype > LST_SINGLE) && (XdrvMailbox.index > 0) && (XdrvMailbox.index <= 5)) { + if ((CMND_COLOR == command_code) && (light_subtype > LST_SINGLE) && (XdrvMailbox.index > 0) && (XdrvMailbox.index <= 6)) { if (XdrvMailbox.data_len > 0) { valid_entry = LightColorEntry(XdrvMailbox.data, XdrvMailbox.data_len); if (valid_entry) { @@ -1031,7 +1047,7 @@ boolean LightCommand() } Settings.light_scheme = 0; coldim = true; - } else { // Color3, 4 and 5 + } else { // Color3, 4, 5 and 6 for (byte i = 0; i < LST_RGB; i++) { Settings.ws_color[XdrvMailbox.index -3][i] = light_entry_color[i]; } @@ -1053,11 +1069,60 @@ boolean LightCommand() snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_SVALUE, command, XdrvMailbox.index, scolor); } } + else if ((CMND_CHANNEL == command_code) && (XdrvMailbox.index > 0) && (XdrvMailbox.index <= light_subtype ) ) { + // Set "Channel" directly - this allows Color and Direct PWM control to coexist + if ((XdrvMailbox.payload >= 0) && (XdrvMailbox.payload <= 100)) { + uint8_t level = XdrvMailbox.payload; + light_current_color[XdrvMailbox.index-1] = round(level * 2.55); + LightSetColor(); + coldim = true; + } + snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_NVALUE, command, XdrvMailbox.index, round(light_current_color[XdrvMailbox.index -1] / 2.55)); + } + else if ((CMND_HSBCOLOR == command_code) && ( light_subtype >= LST_RGB)) { + // Implement method to "direct set" color by HSB (HSB is passed comma separated, 0360) ? (HSB[0] % 360) : HSB[0] ) /360.0, + ( (HSB[1]>100) ? (HSB[1] % 100) : HSB[1] ) /100.0, + ( (HSB[2]>100) ? (HSB[2] % 100) : HSB[2] ) /100.0, + 0); + } else { + LightState(0); + } + } #ifdef USE_WS2812 // *********************************************************************** else if ((CMND_LED == command_code) && (LT_WS2812 == light_type) && (XdrvMailbox.index > 0) && (XdrvMailbox.index <= Settings.light_pixels)) { if (XdrvMailbox.data_len > 0) { - if (LightColorEntry(XdrvMailbox.data, XdrvMailbox.data_len)) { - Ws2812SetColor(XdrvMailbox.index, light_entry_color[0], light_entry_color[1], light_entry_color[2], light_entry_color[3]); + char *p; + uint16_t idx = XdrvMailbox.index; + for (char *color = strtok_r(XdrvMailbox.data, " ", &p); color; color = strtok_r(NULL, " ", &p)) { + if (LightColorEntry(color, strlen(color))) { + Ws2812SetColor(idx, light_entry_color[0], light_entry_color[1], light_entry_color[2], light_entry_color[3]); + idx++; + if (idx >= Settings.light_pixels) break; + } else { + break; + } } } snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_SVALUE, command, XdrvMailbox.index, Ws2812GetColor(XdrvMailbox.index, scolor)); @@ -1065,11 +1130,18 @@ boolean LightCommand() else if ((CMND_PIXELS == command_code) && (LT_WS2812 == light_type)) { if ((XdrvMailbox.payload > 0) && (XdrvMailbox.payload <= WS2812_MAX_LEDS)) { Settings.light_pixels = XdrvMailbox.payload; + Settings.light_rotation = 0; Ws2812Clear(); light_update = 1; } snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE, command, Settings.light_pixels); } + else if ((CMND_ROTATION == command_code) && (LT_WS2812 == light_type)) { + if ((XdrvMailbox.payload >= 0) && (XdrvMailbox.payload < Settings.light_pixels)) { + Settings.light_rotation = XdrvMailbox.payload; + } + snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE, command, Settings.light_rotation); + } else if ((CMND_WIDTH == command_code) && (LT_WS2812 == light_type) && (XdrvMailbox.index > 0) && (XdrvMailbox.index <= 4)) { if (1 == XdrvMailbox.index) { if ((XdrvMailbox.payload >= 0) && (XdrvMailbox.payload <= 4)) { diff --git a/sonoff/xdrv_02_irremote.ino b/sonoff/xdrv_02_irremote.ino index 94f57baae..896faa37a 100644 --- a/sonoff/xdrv_02_irremote.ino +++ b/sonoff/xdrv_02_irremote.ino @@ -284,26 +284,25 @@ boolean IrSendCommand() uint32_t bits = 0; uint32_t data = 0; - for (uint16_t i = 0; i <= sizeof(dataBufUc); i++) { - dataBufUc[i] = toupper(XdrvMailbox.data[i]); - } + UpperCase(dataBufUc, XdrvMailbox.data); if (!strcasecmp_P(XdrvMailbox.topic, PSTR(D_CMND_IRSEND))) { if (XdrvMailbox.data_len) { StaticJsonBuffer<128> jsonBuf; - JsonObject &ir_json = jsonBuf.parseObject(dataBufUc); - if (!ir_json.success()) { + JsonObject &root = jsonBuf.parseObject(dataBufUc); + if (!root.success()) { snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_CMND_IRSEND "\":\"" D_JSON_INVALID_JSON "\"}")); // JSON decode failed } else { snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_CMND_IRSEND "\":\"" D_JSON_DONE "\"}")); - protocol = ir_json[D_JSON_IR_PROTOCOL]; - bits = ir_json[D_JSON_IR_BITS]; - data = ir_json[D_JSON_IR_DATA]; + char parm_uc[10]; + protocol = root[UpperCase_P(parm_uc, PSTR(D_JSON_IR_PROTOCOL))]; + bits = root[UpperCase_P(parm_uc, PSTR(D_JSON_IR_BITS))]; + data = strtoul(root[UpperCase_P(parm_uc, PSTR(D_JSON_IR_DATA))], NULL, 0); if (protocol && bits && data) { int protocol_code = GetCommandCode(protocol_text, sizeof(protocol_text), protocol, kIrRemoteProtocols); - snprintf_P(log_data, sizeof(log_data), PSTR("IRS: protocol_text %s, protocol %s, bits %d, data %d, protocol_code %d"), - protocol_text, protocol, bits, data, protocol_code); + snprintf_P(log_data, sizeof(log_data), PSTR("IRS: protocol_text %s, protocol %s, bits %d, data %u (0x%lX), protocol_code %d"), + protocol_text, protocol, bits, data, data, protocol_code); AddLog(LOG_LEVEL_DEBUG); switch (protocol_code) { diff --git a/sonoff/xdrv_03_energy.ino b/sonoff/xdrv_03_energy.ino index 838f93dfa..264613429 100644 --- a/sonoff/xdrv_03_energy.ino +++ b/sonoff/xdrv_03_energy.ino @@ -29,12 +29,14 @@ enum EnergyHardware { ENERGY_NONE, ENERGY_HLW8012, ENERGY_CSE7766, ENERGY_PZEM004T }; enum EnergyCommands { + CMND_POWERDELTA, CMND_POWERLOW, CMND_POWERHIGH, CMND_VOLTAGELOW, CMND_VOLTAGEHIGH, CMND_CURRENTLOW, CMND_CURRENTHIGH, CMND_POWERCAL, CMND_POWERSET, CMND_VOLTAGECAL, CMND_VOLTAGESET, CMND_CURRENTCAL, CMND_CURRENTSET, CMND_ENERGYRESET, CMND_MAXENERGY, CMND_MAXENERGYSTART, CMND_MAXPOWER, CMND_MAXPOWERHOLD, CMND_MAXPOWERWINDOW, CMND_SAFEPOWER, CMND_SAFEPOWERHOLD, CMND_SAFEPOWERWINDOW }; const char kEnergyCommands[] PROGMEM = + D_CMND_POWERDELTA "|" D_CMND_POWERLOW "|" D_CMND_POWERHIGH "|" D_CMND_VOLTAGELOW "|" D_CMND_VOLTAGEHIGH "|" D_CMND_CURRENTLOW "|" D_CMND_CURRENTHIGH "|" D_CMND_POWERCAL "|" D_CMND_POWERSET "|" D_CMND_VOLTAGECAL "|" D_CMND_VOLTAGESET "|" D_CMND_CURRENTCAL "|" D_CMND_CURRENTSET "|" D_CMND_ENERGYRESET "|" D_CMND_MAXENERGY "|" D_CMND_MAXENERGYSTART "|" @@ -45,11 +47,15 @@ float energy_voltage = 0; // 123.1 V float energy_current = 0; // 123.123 A float energy_power = 0; // 123.1 W float energy_power_factor = 0; // 0.12 -float energy_daily = 0; // 12.123 kWh +float energy_daily = 0; // 123.123 kWh float energy_total = 0; // 12345.12345 kWh float energy_start = 0; // 12345.12345 kWh total previous -unsigned long energy_kWhtoday; // 1212312345 Wh * 10^-5 (deca micro Watt hours) - 5763924 = 0.05763924 kWh = 0.058 kWh = energy_daily -unsigned long energy_period = 0; // 1212312345 Wh * 10^-5 (deca micro Watt hours) - 5763924 = 0.05763924 kWh = 0.058 kWh = energy_daily +unsigned long energy_kWhtoday_delta = 0; // 1212312345 Wh 10^-5 (deca micro Watt hours) - Overflows to energy_kWhtoday (HLW and CSE only) +unsigned long energy_kWhtoday; // 12312312 Wh * 10^-2 (deca milli Watt hours) - 5764 = 0.05764 kWh = 0.058 kWh = energy_daily +unsigned long energy_period = 0; // 12312312 Wh * 10^-2 (deca milli Watt hours) - 5764 = 0.05764 kWh = 0.058 kWh = energy_daily + +float energy_power_last[3] = { 0 }; +uint8_t energy_power_delta = 0; bool energy_power_on = true; @@ -76,9 +82,14 @@ Ticker ticker_energy; void EnergyUpdateToday() { + if (energy_kWhtoday_delta > 1000) { + unsigned long delta = energy_kWhtoday_delta / 1000; + energy_kWhtoday_delta -= (delta * 1000); + energy_kWhtoday += delta; + } RtcSettings.energy_kWhtoday = energy_kWhtoday; - energy_daily = (float)energy_kWhtoday / 100000000; - energy_total = (float)(RtcSettings.energy_kWhtotal + (energy_kWhtoday / 1000)) / 100000; + energy_daily = (float)energy_kWhtoday / 100000; + energy_total = (float)(RtcSettings.energy_kWhtotal + energy_kWhtoday) / 100000; } /*********************************************************************************************\ @@ -151,7 +162,7 @@ void HlwEverySecond() hlw_len = 10000 / hlw_energy_period_counter; hlw_energy_period_counter = 0; if (hlw_len) { - energy_kWhtoday += ((HLW_PREF * Settings.energy_power_calibration) / hlw_len) / 36; + energy_kWhtoday_delta += ((HLW_PREF * Settings.energy_power_calibration) / hlw_len) / 36; EnergyUpdateToday(); } } @@ -247,7 +258,7 @@ void HlwInit() } /*********************************************************************************************\ - * CSE7766 - Energy (Sonoff S31) + * CSE7766 - Energy (Sonoff S31 and Sonoff Pow R2) * * Based on datasheet from http://www.chipsea.com/UploadFiles/2017/08/11144342F01B5662.pdf \*********************************************************************************************/ @@ -264,6 +275,7 @@ uint8_t cse_receive_flag = 0; long voltage_cycle = 0; long current_cycle = 0; long power_cycle = 0; +unsigned long power_cycle_first = 0; long cf_pulses = 0; long cf_pulses_last_time = CSE_PULSES_NOT_INITIALIZED; @@ -314,9 +326,6 @@ void CseReceived() power_cycle = serial_in_buffer[17] << 16 | serial_in_buffer[18] << 8 | serial_in_buffer[19]; cf_pulses = serial_in_buffer[21] << 8 | serial_in_buffer[22]; -// if (adjustement & 0x80) { // CF overflow -// cf_pulses += 0x10000; -// } if (energy_power_on) { // Powered on if (adjustement & 0x40) { // Voltage valid energy_voltage = (float)(Settings.energy_voltage_calibration * CSE_UREF) / (float)voltage_cycle; @@ -325,9 +334,16 @@ void CseReceived() if ((header & 0xF2) == 0xF2) { // Power cycle exceeds range energy_power = 0; } else { - energy_power = (float)(Settings.energy_power_calibration * CSE_PREF) / (float)power_cycle; + if (0 == power_cycle_first) power_cycle_first = power_cycle; // Skip first incomplete power_cycle + if (power_cycle_first != power_cycle) { + power_cycle_first = -1; + energy_power = (float)(Settings.energy_power_calibration * CSE_PREF) / (float)power_cycle; + } else { + energy_power = 0; + } } } else { + power_cycle_first = 0; energy_power = 0; // Powered on but no load } if (adjustement & 0x20) { // Current valid @@ -338,6 +354,7 @@ void CseReceived() } } } else { // Powered off + power_cycle_first = 0; energy_voltage = 0; energy_power = 0; energy_current = 0; @@ -379,7 +396,7 @@ void CseEverySecond() } if (cf_frequency && energy_power) { cf_pulses_last_time = cf_pulses; - energy_kWhtoday += (cf_frequency * Settings.energy_power_calibration) / 36; + energy_kWhtoday_delta += (cf_frequency * Settings.energy_power_calibration) / 36; EnergyUpdateToday(); } } @@ -469,6 +486,8 @@ bool PzemRecieve(uint8_t resp, float *data) } } + AddLogSerial(LOG_LEVEL_DEBUG_MORE, buffer, len); + if (len != sizeof(PZEMCommand)) { // AddLog_P(LOG_LEVEL_DEBUG, PSTR(D_LOG_DEBUG "Pzem comms timeout")); return false; @@ -526,7 +545,7 @@ void PzemEvery200ms() break; case 4: // Total energy as 99999Wh if (!energy_start || (value < energy_start)) energy_start = value; // Init after restart and hanlde roll-over if any - energy_kWhtoday += (value - energy_start) * 100000; + energy_kWhtoday += (value - energy_start) * 100; energy_start = value; EnergyUpdateToday(); break; @@ -566,9 +585,10 @@ void Energy200ms() if (RtcTime.valid) { if (LocalTime() == Midnight()) { Settings.energy_kWhyesterday = energy_kWhtoday; - Settings.energy_kWhtotal += (energy_kWhtoday / 1000); + Settings.energy_kWhtotal += energy_kWhtoday; RtcSettings.energy_kWhtotal = Settings.energy_kWhtotal; energy_kWhtoday = 0; + energy_kWhtoday_delta = 0; energy_period = energy_kWhtoday; EnergyUpdateToday(); energy_max_energy_state = 3; @@ -636,6 +656,20 @@ void EnergyMarginCheck() return; } + if (Settings.energy_power_delta) { + float delta = abs(energy_power_last[0] - energy_power); + // Any delta compared to minimal delta + float min_power = (energy_power_last[0] > energy_power) ? energy_power : energy_power_last[0]; + if (((delta / min_power) * 100) > Settings.energy_power_delta) { + energy_power_delta = 1; + energy_power_last[1] = energy_power; // We only want one report so reset history + energy_power_last[2] = energy_power; + } + } + energy_power_last[0] = energy_power_last[1]; // Shift in history every second allowing power changes to settle for up to three seconds + energy_power_last[1] = energy_power_last[2]; + energy_power_last[2] = energy_power; + if (energy_power_on && (Settings.energy_min_power || Settings.energy_max_power || Settings.energy_min_voltage || Settings.energy_max_voltage || Settings.energy_min_current || Settings.energy_max_current)) { energy_power_u = (uint16_t)(energy_power); energy_voltage_u = (uint16_t)(energy_voltage); @@ -741,15 +775,18 @@ void EnergyMarginCheck() } } #endif // FEATURE_POWER_LIMIT + + if (energy_power_delta) EnergyMqttShow(); } void EnergyMqttShow() { // {"Time":"2017-12-16T11:48:55","ENERGY":{"Total":0.212,"Yesterday":0.000,"Today":0.014,"Period":2.0,"Power":22.0,"Factor":1.00,"Voltage":213.6,"Current":0.100}} - snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_JSON_TIME "\":\"%s\""), GetDateAndTime().c_str()); + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_JSON_TIME "\":\"%s\""), GetDateAndTime(DT_LOCAL).c_str()); EnergyShow(1); snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s}"), mqtt_data); - MqttPublishPrefixTopic_P(TELE, PSTR(D_RSLT_ENERGY), Settings.flag.mqtt_sensor_retain); + MqttPublishPrefixTopic_P(TELE, PSTR(D_RSLT_SENSOR), Settings.flag.mqtt_sensor_retain); + energy_power_delta = 0; } /*********************************************************************************************\ @@ -766,7 +803,14 @@ boolean EnergyCommand() unsigned long nvalue = 0; int command_code = GetCommandCode(command, sizeof(command), XdrvMailbox.topic, kEnergyCommands); - if (CMND_POWERLOW == command_code) { + if (CMND_POWERDELTA == command_code) { + if ((XdrvMailbox.payload >= 0) && (XdrvMailbox.payload < 101)) { + Settings.energy_power_delta = (1 == XdrvMailbox.payload) ? DEFAULT_POWER_DELTA : XdrvMailbox.payload; + } + nvalue = Settings.energy_power_delta; + unit = UNIT_PERCENTAGE; + } + else if (CMND_POWERLOW == command_code) { if ((XdrvMailbox.payload >= 0) && (XdrvMailbox.payload < 3601)) { Settings.energy_min_power = XdrvMailbox.payload; } @@ -814,14 +858,15 @@ boolean EnergyCommand() if (p != XdrvMailbox.data) { switch (XdrvMailbox.index) { case 1: - energy_kWhtoday = lnum *100000; + energy_kWhtoday = lnum *100; + energy_kWhtoday_delta = 0; energy_period = energy_kWhtoday; Settings.energy_kWhtoday = energy_kWhtoday; RtcSettings.energy_kWhtoday = energy_kWhtoday; - energy_daily = (float)energy_kWhtoday / 100000000; + energy_daily = (float)energy_kWhtoday / 100000; break; case 2: - Settings.energy_kWhyesterday = lnum *100000; + Settings.energy_kWhyesterday = lnum *100; break; case 3: RtcSettings.energy_kWhtotal = lnum *100; @@ -832,9 +877,9 @@ boolean EnergyCommand() char energy_yesterday_chr[10]; char stoday_energy[10]; char energy_total_chr[10]; - dtostrfd((float)Settings.energy_kWhyesterday / 100000000, Settings.flag2.energy_resolution, energy_yesterday_chr); - dtostrfd((float)RtcSettings.energy_kWhtoday / 100000000, Settings.flag2.energy_resolution, stoday_energy); - dtostrfd((float)(RtcSettings.energy_kWhtotal + (energy_kWhtoday / 1000)) / 100000, Settings.flag2.energy_resolution, energy_total_chr); + dtostrfd((float)Settings.energy_kWhyesterday / 100000, Settings.flag2.energy_resolution, energy_yesterday_chr); + dtostrfd((float)RtcSettings.energy_kWhtoday / 100000, Settings.flag2.energy_resolution, stoday_energy); + dtostrfd((float)(RtcSettings.energy_kWhtotal + energy_kWhtoday) / 100000, Settings.flag2.energy_resolution, energy_total_chr); snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"%s\":{\"" D_JSON_TOTAL "\":%s,\"" D_JSON_YESTERDAY "\":%s,\"" D_JSON_TODAY "\":%s}}"), command, energy_total_chr, energy_yesterday_chr, stoday_energy); status_flag = 1; @@ -978,9 +1023,9 @@ boolean EnergyCommand() void EnergyDrvInit() { energy_flg = ENERGY_NONE; - if ((pin[GPIO_HLW_SEL] < 99) && (pin[GPIO_HLW_CF1] < 99) && (pin[GPIO_HLW_CF] < 99)) { // Sonoff Pow + if ((pin[GPIO_HLW_SEL] < 99) && (pin[GPIO_HLW_CF1] < 99) && (pin[GPIO_HLW_CF] < 99)) { // Sonoff Pow or any HLW8012 based device energy_flg = ENERGY_HLW8012; - } else if (SONOFF_S31 == Settings.module) { // Sonoff S31 + } else if ((SONOFF_S31 == Settings.module) || (SONOFF_POW_R2 == Settings.module)) { // Sonoff S31 or Sonoff Pow R2 baudrate = 4800; serial_config = SERIAL_8E1; energy_flg = ENERGY_CSE7766; @@ -1003,6 +1048,7 @@ void EnergySnsInit() if (energy_flg) { energy_kWhtoday = (RtcSettingsValid()) ? RtcSettings.energy_kWhtoday : (RtcTime.day_of_year == Settings.energy_kWhdoy) ? Settings.energy_kWhtoday : 0; + energy_kWhtoday_delta = 0; energy_period = energy_kWhtoday; EnergyUpdateToday(); ticker_energy.attach_ms(200, Energy200ms); @@ -1036,7 +1082,7 @@ void EnergyShow(boolean json) float energy = 0; if (show_energy_period) { - if (energy_period) energy = (float)(energy_kWhtoday - energy_period) / 100000; + if (energy_period) energy = (float)(energy_kWhtoday - energy_period) / 100; energy_period = energy_kWhtoday; } @@ -1047,7 +1093,7 @@ void EnergyShow(boolean json) dtostrfd(energy_voltage, Settings.flag2.voltage_resolution, energy_voltage_chr); dtostrfd(energy_current, Settings.flag2.current_resolution, energy_current_chr); dtostrfd(energy_power_factor, 2, energy_power_factor_chr); - dtostrfd((float)Settings.energy_kWhyesterday / 100000000, Settings.flag2.energy_resolution, energy_yesterday_chr); + dtostrfd((float)Settings.energy_kWhyesterday / 100000, Settings.flag2.energy_resolution, energy_yesterday_chr); if (json) { snprintf_P(speriod, sizeof(speriod), PSTR(",\"" D_JSON_PERIOD "\":%s"), energy_period_chr); diff --git a/sonoff/xdrv_04_snfbridge.ino b/sonoff/xdrv_04_snfbridge.ino index 4e1166e09..a17558ca1 100644 --- a/sonoff/xdrv_04_snfbridge.ino +++ b/sonoff/xdrv_04_snfbridge.ino @@ -109,15 +109,15 @@ boolean SonoffBridgeSerialInput() { // iTead Rf Universal Transceiver Module Serial Protocol Version 1.0 (20170420) if (sonoff_bridge_receive_flag) { - if (!((serial_in_byte_counter == 0) && (serial_in_byte == 0))) { // Skip leading 0 - if (!serial_in_byte_counter) { + if (!((0 == serial_in_byte_counter) && (0 == serial_in_byte))) { // Skip leading 0 + if (0 == serial_in_byte_counter) { sonoff_bridge_expected_bytes = 2; // 0xA0, 0xA1, 0xA2 if (serial_in_byte >= 0xA3) { sonoff_bridge_expected_bytes = 11; // 0xA3, 0xA4, 0xA5 } } serial_in_buffer[serial_in_byte_counter++] = serial_in_byte; - if ((sonoff_bridge_expected_bytes == serial_in_byte_counter) && (0x55 == serial_in_byte)) { // 0x55 - End of text + if ((sonoff_bridge_expected_bytes == serial_in_byte_counter) && (0x55 == serial_in_byte)) { // 0x55 - End of text SonoffBridgeReceived(); sonoff_bridge_receive_flag = 0; return 1; @@ -252,7 +252,7 @@ boolean SonoffBridgeCommand() snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_SVALUE, command, XdrvMailbox.index, D_JSON_START_LEARNING); } else if (3 == XdrvMailbox.payload) { // Unlearn RF data - Settings.rf_code[XdrvMailbox.index][0] = 0; + Settings.rf_code[XdrvMailbox.index][0] = 0; // Reset sync_time MSB snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_SVALUE, command, XdrvMailbox.index, D_JSON_SET_TO_DEFAULT); } else if (4 == XdrvMailbox.payload) { // Save RF data provided by RFSync, RfLow, RfHigh and last RfCode @@ -263,8 +263,23 @@ boolean SonoffBridgeCommand() Settings.rf_code[XdrvMailbox.index][7] = (sonoff_bridge_last_send_code >> 8) & 0xff; Settings.rf_code[XdrvMailbox.index][8] = sonoff_bridge_last_send_code & 0xff; snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_SVALUE, command, XdrvMailbox.index, D_JSON_SAVED); + } else if (5 == XdrvMailbox.payload) { // Show default or learned RF data + uint8_t key = XdrvMailbox.index; + uint8_t index = (0 == Settings.rf_code[key][0]) ? 0 : key; // Use default if sync_time MSB = 0 + uint16_t sync_time = (Settings.rf_code[index][0] << 8) | Settings.rf_code[index][1]; + uint16_t low_time = (Settings.rf_code[index][2] << 8) | Settings.rf_code[index][3]; + uint16_t high_time = (Settings.rf_code[index][4] << 8) | Settings.rf_code[index][5]; + uint32_t code = (Settings.rf_code[index][6] << 16) | (Settings.rf_code[index][7] << 8); + if (0 == index) { + key--; + code |= (uint8_t)((0x10 << (key >> 2)) | (1 << (key & 3))); + } else { + code |= Settings.rf_code[index][8]; + } + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"%s%d\":{\"" D_JSON_SYNC "\":%d,\"" D_JSON_LOW "\":%d,\"" D_JSON_HIGH "\":%d,\"" D_JSON_DATA "\":\"%06X\"}}"), + command, XdrvMailbox.index, sync_time, low_time, high_time, code); } else { - if ((1 == XdrvMailbox.payload) || (0 == Settings.rf_code[XdrvMailbox.index][0])) { + if ((1 == XdrvMailbox.payload) || (0 == Settings.rf_code[XdrvMailbox.index][0])) { // Test sync_time MSB SonoffBridgeSend(0, XdrvMailbox.index); // Send default RF data snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_SVALUE, command, XdrvMailbox.index, D_JSON_DEFAULT_SENT); } else { diff --git a/sonoff/xdrv_05_domoticz.ino b/sonoff/xdrv_05_domoticz.ino index 3e1dfdc49..38a979916 100644 --- a/sonoff/xdrv_05_domoticz.ino +++ b/sonoff/xdrv_05_domoticz.ino @@ -22,7 +22,7 @@ #ifdef USE_WEBSERVER const char HTTP_FORM_DOMOTICZ[] PROGMEM = "
 " D_DOMOTICZ_PARAMETERS " 
" - "" + "" "
\").replace(/{m}/g,\"\").replace(/{e}/g,\"
\").replace(/}2/g,\"\");" - "document.getElementById('i').innerHTML=s;" + "eb('i').innerHTML=s;" "}" ""; const char HTTP_MSG_SLIDER1[] PROGMEM = @@ -177,21 +184,29 @@ const char HTTP_BTN_MENU1[] PROGMEM = "
" "
"; const char HTTP_BTN_RSTRT[] PROGMEM = - "
"; -const char HTTP_BTN_MENU2[] PROGMEM = - "
" + "
"; +const char HTTP_BTN_MENU_MODULE[] PROGMEM = + "
"; +#if defined(USE_TIMERS) && defined(USE_TIMERS_WEB) +const char HTTP_BTN_MENU_TIMER[] PROGMEM = + "
"; +#endif // USE_TIMERS and USE_TIMERS_WEB +const char HTTP_BTN_MENU_WIFI[] PROGMEM = "
"; -const char HTTP_BTN_MENU3[] PROGMEM = +const char HTTP_BTN_MENU_MQTT[] PROGMEM = "
" #ifdef USE_DOMOTICZ "
" #endif // USE_DOMOTICZ ""; const char HTTP_BTN_MENU4[] PROGMEM = +#ifdef USE_KNX + "
" +#endif // USE_KNX "
" "
" "
" - "
" + "
" "
" "
"; const char HTTP_BTN_MAIN[] PROGMEM = @@ -206,7 +221,7 @@ const char HTTP_BTN_CONF[] PROGMEM = "

"; const char HTTP_FORM_MODULE[] PROGMEM = "
 " D_MODULE_PARAMETERS " 
" - "" + "" "
" D_MODULE_TYPE " ({mt)

"; const char HTTP_LNK_ITEM[] PROGMEM = "
{v} {i} {r}%
"; @@ -214,15 +229,15 @@ const char HTTP_LNK_SCAN[] PROGMEM = "
"; const char HTTP_FORM_WIFI[] PROGMEM = "
 " D_WIFI_PARAMETERS " " - "" + "" "
" D_AP1_SSID " (" STA_SSID1 ")

" - "
" D_AP1_PASSWORD "

" + "
" D_AP1_PASSWORD "

" "
" D_AP2_SSID " (" STA_SSID2 ")

" - "
" D_AP2_PASSWORD "

" + "
" D_AP2_PASSWORD "

" "
" D_HOSTNAME " (" WIFI_HOSTNAME ")

"; const char HTTP_FORM_MQTT[] PROGMEM = "
 " D_MQTT_PARAMETERS " " - "" + "" "
" D_HOST " (" MQTT_HOST ")

" "
" D_PORT " (" STR(MQTT_PORT) ")

" "
" D_CLIENT " ({m0)

" @@ -232,7 +247,7 @@ const char HTTP_FORM_MQTT[] PROGMEM = "
" D_FULL_TOPIC " (" MQTT_FULLTOPIC ")

"; const char HTTP_FORM_LOG1[] PROGMEM = "
 " D_LOGGING_PARAMETERS " " - ""; + ""; const char HTTP_FORM_LOG2[] PROGMEM = "
{b0 ({b1)

"; const char HTTP_FORM_OTHER[] PROGMEM = "
 " D_OTHER_PARAMETERS " " - "" - "
" D_WEB_ADMIN_PASSWORD "

" + "" + "
" D_WEB_ADMIN_PASSWORD "

" "
" D_MQTT_ENABLE "
"; const char HTTP_FORM_OTHER2[] PROGMEM = "
" D_FRIENDLY_NAME " {1 ({2)

"; @@ -259,7 +274,7 @@ const char HTTP_FORM_OTHER3b[] PROGMEM = "
{3{4"; // Different id only used for labels #endif // USE_EMULATION const char HTTP_FORM_END[] PROGMEM = - "
"; + "
"; const char HTTP_FORM_RST[] PROGMEM = "
" "
 " D_RESTORE_CONFIGURATION " "; @@ -274,7 +289,7 @@ const char HTTP_FORM_UPG[] PROGMEM = const char HTTP_FORM_RST_UPG[] PROGMEM = "
" "

" - "
" + "
" "
" "
" ""; @@ -330,6 +345,9 @@ void StartWebserver(int type, IPAddress ipweb) WebServer->on("/", HandleRoot); WebServer->on("/cn", HandleConfiguration); WebServer->on("/md", HandleModuleConfiguration); +#if defined(USE_TIMERS) && defined(USE_TIMERS_WEB) + WebServer->on("/tm", HandleTimerConfiguration); +#endif // USE_TIMERS and USE_TIMERS_WEB WebServer->on("/w1", HandleWifiConfigurationWithScan); WebServer->on("/w0", HandleWifiConfiguration); if (Settings.flag.mqtt_enabled) { @@ -338,6 +356,9 @@ void StartWebserver(int type, IPAddress ipweb) WebServer->on("/dm", HandleDomoticzConfiguration); #endif // USE_DOMOTICZ } +#ifdef USE_KNX + WebServer->on("/kn", HandleKNXConfiguration); +#endif // USE_KNX WebServer->on("/lg", HandleLoggingConfiguration); WebServer->on("/co", HandleOtherConfiguration); WebServer->on("/dl", HandleBackupConfiguration); @@ -347,6 +368,7 @@ void StartWebserver(int type, IPAddress ipweb) WebServer->on("/up", HandleUpgradeFirmware); WebServer->on("/u1", HandleUpgradeFirmwareStart); // OTA WebServer->on("/u2", HTTP_POST, HandleUploadDone, HandleUploadLoop); + WebServer->on("/u2", HTTP_OPTIONS, HandlePreflightRequest); WebServer->on("/cm", HandleHttpCommand); WebServer->on("/cs", HandleConsole); WebServer->on("/ax", HandleAjaxConsoleRefresh); @@ -366,6 +388,9 @@ void StartWebserver(int type, IPAddress ipweb) } #endif // USE_EMULATION WebServer->onNotFound(HandleNotFound); +#ifdef USE_KNX + KNXStart(); +#endif // USE_KNX } reset_web_log_flag = 0; WebServer->begin(); // Web server start @@ -375,9 +400,7 @@ void StartWebserver(int type, IPAddress ipweb) my_hostname, (mdns_begun) ? ".local" : "", ipweb.toString().c_str()); AddLog(LOG_LEVEL_INFO); } - if (type) { - webserver_state = type; - } + if (type) { webserver_state = type; } } void StopWebserver() @@ -414,12 +437,8 @@ void WifiManagerBegin() void PollDnsWebserver() { - if (DnsServer) { - DnsServer->processNextRequest(); - } - if (WebServer) { - WebServer->handleClient(); - } + if (DnsServer) { DnsServer->processNextRequest(); } + if (WebServer) { WebServer->handleClient(); } } /*********************************************************************************************/ @@ -474,9 +493,7 @@ void HandleRoot() { AddLog_P(LOG_LEVEL_DEBUG, S_LOG_HTTP, S_MAIN_MENU); - if (CaptivePortal()) { // If captive portal redirect instead of displaying the page. - return; - } + if (CaptivePortal()) { return; } // If captive portal redirect instead of displaying the page. if (HTTP_MANAGER == webserver_state) { if ((Settings.web_password[0] != 0) && !(WebServer->hasArg("USER1")) && !(WebServer->hasArg("PASS1"))) { @@ -528,9 +545,7 @@ void HandleRoot() page += F("
"; const char HTTP_FORM_DOMOTICZ_RELAY[] PROGMEM = "" @@ -35,6 +35,8 @@ const char HTTP_FORM_DOMOTICZ_TIMER[] PROGMEM = ""; #endif // USE_WEBSERVER +const char DOMOTICZ_MESSAGE[] PROGMEM = "{\"idx\":%d,\"nvalue\":%d,\"svalue\":\"%s\",\"Battery\":%d,\"RSSI\":%d}"; + enum DomoticzCommands { CMND_IDX, CMND_KEYIDX, CMND_SWITCHIDX, CMND_SENSORIDX, CMND_UPDATETIMER }; const char kDomoticzCommands[] PROGMEM = D_CMND_IDX "|" D_CMND_KEYIDX "|" D_CMND_SWITCHIDX "|" D_CMND_SENSORIDX "|" D_CMND_UPDATETIMER ; @@ -57,6 +59,32 @@ boolean domoticz_subscribe = false; int domoticz_update_timer = 0; byte domoticz_update_flag = 1; +int DomoticzBatteryQuality() +{ + // Battery 0%: ESP 2.6V (minimum operating voltage is 2.5) + // Battery 100%: ESP 3.6V (maximum operating voltage is 3.6) + // Battery 101% to 200%: ESP over 3.6V (means over maximum operating voltage) + + int quality = 0; // Voltage range from 2,6V > 0% to 3,6V > 100% + + uint16_t voltage = ESP.getVcc(); + if (voltage <= 2600) { + quality = 0; + } else if (voltage >= 4600) { + quality = 200; + } else { + quality = (voltage - 2600) / 10; + } + return quality; +} + +int DomoticzRssiQuality() +{ + // RSSI range: 0% to 10% (12 means disable RSSI in Domoticz) + + return WifiGetRssiAsQuality(WiFi.RSSI()) / 10; +} + void MqttPublishDomoticzPowerState(byte device) { char sdimmer[8]; @@ -66,8 +94,8 @@ void MqttPublishDomoticzPowerState(byte device) } if (Settings.flag.mqtt_enabled && Settings.domoticz_relay_idx[device -1]) { snprintf_P(sdimmer, sizeof(sdimmer), PSTR("%d"), Settings.light_dimmer); - snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"idx\":%d,\"nvalue\":%d,\"svalue\":\"%s\"}"), - Settings.domoticz_relay_idx[device -1], (power & (1 << (device -1))) ? 1 : 0, (light_type) ? sdimmer : ""); + snprintf_P(mqtt_data, sizeof(mqtt_data), DOMOTICZ_MESSAGE, + Settings.domoticz_relay_idx[device -1], (power & (1 << (device -1))) ? 1 : 0, (light_type) ? sdimmer : "", DomoticzBatteryQuality(), DomoticzRssiQuality()); MqttPublish(domoticz_in_topic); } } @@ -237,7 +265,7 @@ boolean DomoticzCommand() return serviced; } -boolean DomoticzButton(byte key, byte device, byte state, byte svalflg) +boolean DomoticzSendKey(byte key, byte device, byte state, byte svalflg) { if ((Settings.domoticz_key_idx[device -1] || Settings.domoticz_switch_idx[device -1]) && (svalflg)) { snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"command\":\"switchlight\",\"idx\":%d,\"switchcmd\":\"%s\"}"), @@ -275,13 +303,15 @@ uint8_t DomoticzHumidityState(char *hum) void DomoticzSensor(byte idx, char *data) { if (Settings.domoticz_sensor_idx[idx]) { - char dmess[64]; + char dmess[90]; memcpy(dmess, mqtt_data, sizeof(dmess)); if (DZ_AIRQUALITY == idx) { - snprintf_P(mqtt_data, sizeof(dmess), PSTR("{\"idx\":%d,\"nvalue\":%s}"), Settings.domoticz_sensor_idx[idx], data); + snprintf_P(mqtt_data, sizeof(dmess), PSTR("{\"idx\":%d,\"nvalue\":%s,\"Battery\":%d,\"RSSI\":%d}"), + Settings.domoticz_sensor_idx[idx], data, DomoticzBatteryQuality(), DomoticzRssiQuality()); } else { - snprintf_P(mqtt_data, sizeof(dmess), PSTR("{\"idx\":%d,\"nvalue\":0,\"svalue\":\"%s\"}"), Settings.domoticz_sensor_idx[idx], data); + snprintf_P(mqtt_data, sizeof(dmess), DOMOTICZ_MESSAGE, + Settings.domoticz_sensor_idx[idx], 0, data, DomoticzBatteryQuality(), DomoticzRssiQuality()); } MqttPublish(domoticz_in_topic); memcpy(mqtt_data, dmess, sizeof(dmess)); diff --git a/sonoff/xdrv_07_home_assistant.ino b/sonoff/xdrv_07_home_assistant.ino index f11c3023b..3f8e001be 100644 --- a/sonoff/xdrv_07_home_assistant.ino +++ b/sonoff/xdrv_07_home_assistant.ino @@ -31,6 +31,16 @@ const char HASS_DISCOVER_SWITCH[] PROGMEM = "\"payload_available\":\"" D_ONLINE "\"," // Online "\"payload_not_available\":\"" D_OFFLINE "\""; // Offline +const char HASS_DISCOVER_BUTTON[] PROGMEM = + "{\"name\":\"%s\"," // dualr2 1 BTN + "\"state_topic\":\"%s\"," // cmnd/dualr2/POWER (implies "\"optimistic\":\"false\",") +// "\"value_template\":\"{{value_json.%s}}\"," // POWER2 + "\"payload_on\":\"%s\"," // TOGGLE +// "\"optimistic\":\"false\"," // false is Hass default when state_topic is set + "\"availability_topic\":\"%s\"," // tele/dualr2/LWT + "\"payload_available\":\"" D_ONLINE "\"," // Online + "\"payload_not_available\":\"" D_OFFLINE "\""; // Offline + const char HASS_DISCOVER_LIGHT_DIMMER[] PROGMEM = "%s,\"brightness_command_topic\":\"%s\"," // cmnd/led2/Dimmer "\"brightness_state_topic\":\"%s\"," // stat/led2/RESULT @@ -53,47 +63,28 @@ const char HASS_DISCOVER_LIGHT_SCHEME[] PROGMEM = "%s,\"effect_command_topic\":\"%s\"," // cmnd/led2/Scheme "\"effect_state_topic\":\"%s\"," // stat/led2/RESULT "\"effect_value_template\":\"{{value_json." D_CMND_SCHEME "}}\"," - "\"effect_list\":\"[0, 1, 2, 3, 4]\""; // Needs to be a Python string list providing Scheme parameter values (Unable to get this functional) + "\"effect_list\":[\"0\",\"1\",\"2\",\"3\",\"4\"]"; // string list with reference to scheme parameter. Currently only supports numbers 0 to 11 as it make the mqtt string too long */ -/* -#1690 - investigate -effect_list: -- 0 -- 1 -- 2 -- 3 -- 4 -- 5 -- 6 -- 7 -- 8 -- 9 -- 10 -- 11 -- 12 -*/ -void HAssDiscovery() + +void HAssDiscoverRelay() { char sidx[8]; char stopic[TOPSZ]; bool is_light = false; - // Configure Tasmota for default Home Assistant parameters to keep discovery message as short as possible - if (Settings.flag.hass_discovery) { - Settings.flag.mqtt_response = 0; // Response always as RESULT and not as uppercase command - Settings.flag.decimal_text = 1; // Respond with decimal color values -// Settings.light_scheme = 0; // To just control color it needs to be Scheme 0 -// strncpy_P(Settings.mqtt_fulltopic, PSTR("%prefix%/%topic%/"), sizeof(Settings.mqtt_fulltopic)); // Make MQTT topic as short as possible to make this process posible within MQTT_MAX_PACKET_SIZE - } - - for (int i = 1; i <= devices_present; i++) { + for (int i = 1; i <= MAX_RELAYS; i++) { is_light = ((i == devices_present) && (light_type)); - snprintf_P(sidx, sizeof(sidx), PSTR("_%d"), i); - snprintf_P(stopic, sizeof(stopic), PSTR(HOME_ASSISTANT_DISCOVERY_PREFIX "/%s/%s%s/config"), (is_light) ? "light" : "switch", Settings.mqtt_topic, (1 == devices_present) ? "" : sidx); + mqtt_data[0] = '\0'; // Clear retained message - mqtt_data[0] = '\0'; - if (Settings.flag.hass_discovery) { + snprintf_P(sidx, sizeof(sidx), PSTR("_%d"), i); + // Clear "other" topic first in case the device has been reconfigured + snprintf_P(stopic, sizeof(stopic), PSTR(HOME_ASSISTANT_DISCOVERY_PREFIX "/%s/%s%s/config"), (is_light) ? "switch" : "light", mqtt_topic, sidx); + MqttPublish(stopic, true); + // Clear or Set topic + snprintf_P(stopic, sizeof(stopic), PSTR(HOME_ASSISTANT_DISCOVERY_PREFIX "/%s/%s%s/config"), (is_light) ? "light" : "switch", mqtt_topic, sidx); + + if (Settings.flag.hass_discovery && (i <= devices_present)) { char name[33]; char value_template[33]; char command_topic[TOPSZ]; @@ -106,33 +97,33 @@ void HAssDiscovery() snprintf_P(name, sizeof(name), Settings.friendlyname[i -1]); } GetPowerDevice(value_template, i, sizeof(value_template)); - GetTopic_P(command_topic, CMND, Settings.mqtt_topic, value_template); - GetTopic_P(state_topic, STAT, Settings.mqtt_topic, S_RSLT_RESULT); - GetTopic_P(availability_topic, TELE, Settings.mqtt_topic, S_LWT); + GetTopic_P(command_topic, CMND, mqtt_topic, value_template); + GetTopic_P(state_topic, STAT, mqtt_topic, S_RSLT_RESULT); + GetTopic_P(availability_topic, TELE, mqtt_topic, S_LWT); snprintf_P(mqtt_data, sizeof(mqtt_data), HASS_DISCOVER_SWITCH, name, command_topic, state_topic, value_template, Settings.state_text[0], Settings.state_text[1], availability_topic); if (is_light) { char brightness_command_topic[TOPSZ]; - GetTopic_P(brightness_command_topic, CMND, Settings.mqtt_topic, D_CMND_DIMMER); + GetTopic_P(brightness_command_topic, CMND, mqtt_topic, D_CMND_DIMMER); snprintf_P(mqtt_data, sizeof(mqtt_data), HASS_DISCOVER_LIGHT_DIMMER, mqtt_data, brightness_command_topic, state_topic); if (light_subtype >= LST_RGB) { char rgb_command_topic[TOPSZ]; - GetTopic_P(rgb_command_topic, CMND, Settings.mqtt_topic, D_CMND_COLOR); + GetTopic_P(rgb_command_topic, CMND, mqtt_topic, D_CMND_COLOR); snprintf_P(mqtt_data, sizeof(mqtt_data), HASS_DISCOVER_LIGHT_COLOR, mqtt_data, rgb_command_topic, state_topic); /* char effect_command_topic[TOPSZ]; - GetTopic_P(effect_command_topic, CMND, Settings.mqtt_topic, D_CMND_SCHEME); + GetTopic_P(effect_command_topic, CMND, mqtt_topic, D_CMND_SCHEME); snprintf_P(mqtt_data, sizeof(mqtt_data), HASS_DISCOVER_LIGHT_SCHEME, mqtt_data, effect_command_topic, state_topic); */ } if ((LST_COLDWARM == light_subtype) || (LST_RGBWC == light_subtype)) { char color_temp_command_topic[TOPSZ]; - GetTopic_P(color_temp_command_topic, CMND, Settings.mqtt_topic, D_CMND_COLORTEMPERATURE); + GetTopic_P(color_temp_command_topic, CMND, mqtt_topic, D_CMND_COLORTEMPERATURE); snprintf_P(mqtt_data, sizeof(mqtt_data), HASS_DISCOVER_LIGHT_CT, mqtt_data, color_temp_command_topic, state_topic); } } @@ -142,6 +133,77 @@ void HAssDiscovery() } } +void HAssDiscoverButton() +{ + char sidx[8]; + char stopic[TOPSZ]; + char key_topic[sizeof(Settings.button_topic)]; + + // Send info about buttons + char *tmp = Settings.button_topic; + Format(key_topic, tmp, sizeof(key_topic)); + if ((strlen(key_topic) != 0) && strcmp(key_topic, "0")) { + for (byte button_index = 0; button_index < MAX_KEYS; button_index++) { + uint8_t button_present = 0; + + if (!button_index && ((SONOFF_DUAL == Settings.module) || (CH4 == Settings.module))) { + button_present = 1; + } else { + if (pin[GPIO_KEY1 + button_index] < 99) { + button_present = 1; + } + } + + mqtt_data[0] = '\0'; // Clear retained message + + // Clear or Set topic + snprintf_P(sidx, sizeof(sidx), PSTR("_%d"), button_index+1); + snprintf_P(stopic, sizeof(stopic), PSTR(HOME_ASSISTANT_DISCOVERY_PREFIX "/%s/%s%s/config"), "binary_sensor", key_topic, sidx); + + if (Settings.flag.hass_discovery && button_present) { + char name[33]; + char value_template[33]; + char state_topic[TOPSZ]; + char availability_topic[TOPSZ]; + + if (button_index+1 > MAX_FRIENDLYNAMES) { + snprintf_P(name, sizeof(name), PSTR("%s %d BTN"), Settings.friendlyname[0], button_index+1); + } else { + snprintf_P(name, sizeof(name), PSTR("%s BTN"), Settings.friendlyname[button_index]); + } + GetPowerDevice(value_template, button_index+1, sizeof(value_template)); + GetTopic_P(state_topic, CMND, key_topic, value_template); // State of button is sent as CMND TOGGLE + GetTopic_P(availability_topic, TELE, mqtt_topic, S_LWT); + snprintf_P(mqtt_data, sizeof(mqtt_data), HASS_DISCOVER_BUTTON, name, state_topic, Settings.state_text[2], availability_topic); + + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s}"), mqtt_data); + } + MqttPublish(stopic, true); + } + } +} + +void HAssDiscovery(uint8_t mode) +{ + // Configure Tasmota for default Home Assistant parameters to keep discovery message as short as possible + if (Settings.flag.hass_discovery) { + Settings.flag.mqtt_response = 0; // Response always as RESULT and not as uppercase command + Settings.flag.decimal_text = 1; // Respond with decimal color values +// Settings.light_scheme = 0; // To just control color it needs to be Scheme 0 +// strncpy_P(Settings.mqtt_fulltopic, PSTR("%prefix%/%topic%/"), sizeof(Settings.mqtt_fulltopic)); // Make MQTT topic as short as possible to make this process posible within MQTT_MAX_PACKET_SIZE + } + + if (Settings.flag.hass_discovery || (1 == mode)) { + // Send info about relays and lights + HAssDiscoverRelay(); + // Send info about buttons + HAssDiscoverButton(); + // TODO: Send info about switches + + // TODO: Send info about sensors + } +} + /*********************************************************************************************\ * Interface \*********************************************************************************************/ @@ -155,7 +217,7 @@ boolean Xdrv07(byte function) if (Settings.flag.mqtt_enabled) { switch (function) { case FUNC_MQTT_INIT: - HAssDiscovery(); + HAssDiscovery(0); break; } } diff --git a/sonoff/xdrv_08_serial_bridge.ino b/sonoff/xdrv_08_serial_bridge.ino new file mode 100644 index 000000000..428dc5e35 --- /dev/null +++ b/sonoff/xdrv_08_serial_bridge.ino @@ -0,0 +1,149 @@ +/* + xdrv_08_serial_bridge.ino - serial bridge support for Sonoff-Tasmota + + Copyright (C) 2018 Theo Arends and Dániel Zoltán Tolnai + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifdef USE_SERIAL_BRIDGE +/*********************************************************************************************\ + * Serial Bridge using Software Serial library (TasmotaSerial) +\*********************************************************************************************/ +#define SERIAL_BRIDGE_BUFFER_SIZE 130 + +#include + +enum SerialBridgeCommands { CMND_SSERIALSEND, CMND_SBAUDRATE }; +const char kSerialBridgeCommands[] PROGMEM = D_CMND_SSERIALSEND "|" D_CMND_SBAUDRATE; + +TasmotaSerial *SerialBridgeSerial; + +uint8_t serial_bridge_active = 1; +uint8_t serial_bridge_in_byte_counter = 0; +unsigned long serial_bridge_polling_window = 0; +char serial_bridge_buffer[SERIAL_BRIDGE_BUFFER_SIZE]; + +void SerialBridgeInput() +{ + while (SerialBridgeSerial->available()) { + yield(); + uint8_t serial_in_byte = SerialBridgeSerial->read(); + + if (serial_in_byte > 127) { // binary data... + serial_bridge_in_byte_counter = 0; + SerialBridgeSerial->flush(); + return; + } + if (serial_in_byte) { + if ((serial_in_byte_counter < sizeof(serial_bridge_buffer) -1) && (serial_in_byte != Settings.serial_delimiter)) { // add char to string if it still fits + serial_bridge_buffer[serial_bridge_in_byte_counter++] = serial_in_byte; + serial_bridge_polling_window = millis(); // Wait for more data + } else { + serial_bridge_polling_window = 0; // Publish now + break; + } + } + } + + if (serial_bridge_in_byte_counter && (millis() > (serial_bridge_polling_window + SERIAL_POLLING))) { + serial_bridge_buffer[serial_bridge_in_byte_counter] = 0; // serial data completed + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_JSON_SSERIALRECEIVED "\":\"%s\"}"), serial_bridge_buffer); + MqttPublishPrefixTopic_P(RESULT_OR_TELE, PSTR(D_JSON_SSERIALRECEIVED)); + serial_bridge_in_byte_counter = 0; + } +} + +/********************************************************************************************/ + +void SerialBridgeInit(void) +{ + serial_bridge_active = 0; + if ((pin[GPIO_SBR_RX] < 99) && (pin[GPIO_SBR_TX] < 99)) { + SerialBridgeSerial = new TasmotaSerial(pin[GPIO_SBR_RX], pin[GPIO_SBR_TX]); + if (SerialBridgeSerial->begin(Settings.sbaudrate * 1200)) { // Baud rate is stored div 1200 so it fits into one byte + serial_bridge_active = 1; + SerialBridgeSerial->flush(); + } + } +} + +/*********************************************************************************************\ + * Commands +\*********************************************************************************************/ + +boolean SerialBridgeCommand() +{ + char command [CMDSZ]; + boolean serviced = true; + + int command_code = GetCommandCode(command, sizeof(command), XdrvMailbox.topic, kSerialBridgeCommands); + if ((CMND_SSERIALSEND == command_code) && (XdrvMailbox.index > 0) && (XdrvMailbox.index <= 3)) { + if (XdrvMailbox.data_len > 0) { + if (1 == XdrvMailbox.index) { + SerialBridgeSerial->write(XdrvMailbox.data, XdrvMailbox.data_len); + SerialBridgeSerial->write("\n"); + } + else if (2 == XdrvMailbox.index) { + SerialBridgeSerial->write(XdrvMailbox.data, XdrvMailbox.data_len); + } + else if (3 == XdrvMailbox.index) { + SerialBridgeSerial->write(Unescape(XdrvMailbox.data, &XdrvMailbox.data_len), XdrvMailbox.data_len); + } + snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, D_JSON_DONE); + } + } + else if (CMND_SBAUDRATE == command_code) { + char *p; + int baud = strtol(XdrvMailbox.data, &p, 10); + if (baud > 0) { + baud /= 1200; // Make it a valid baudrate + Settings.sbaudrate = (1 == XdrvMailbox.payload) ? SOFT_BAUDRATE / 1200 : baud; + SerialBridgeSerial->begin(Settings.sbaudrate * 1200); // Reinitialize serial port with new baud rate + } + snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_LVALUE, command, Settings.sbaudrate * 1200); + } + else { + serviced = false; // Unknown command + } + return serviced; +} + +/*********************************************************************************************\ + * Interface +\*********************************************************************************************/ + +#define XDRV_08 + +boolean Xdrv08(byte function) +{ + boolean result = false; + + if (serial_bridge_active) { + switch (function) { + case FUNC_INIT: + SerialBridgeInit(); + break; + case FUNC_LOOP: + SerialBridgeInput(); + break; + case FUNC_COMMAND: + result = SerialBridgeCommand(); + break; + } + } + return result; +} + +#endif // USE_SERIAL_BRIDGE diff --git a/sonoff/xdrv_09_timers.ino b/sonoff/xdrv_09_timers.ino new file mode 100644 index 000000000..aa1287f20 --- /dev/null +++ b/sonoff/xdrv_09_timers.ino @@ -0,0 +1,731 @@ +/* + xdrv_09_timers.ino - timer support for Sonoff-Tasmota + + Copyright (C) 2018 Theo Arends + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifdef USE_TIMERS +/*********************************************************************************************\ + * Timers + * + * Arm a timer using one or all of the following JSON values: + * {"Arm":1,"Mode":0,"Time":"09:23","Window":0,"Days":"--TW--S","Repeat":1,"Output":1,"Action":1} + * + * Arm 0 = Off, 1 = On + * Mode 0 = Schedule, 1 = Sunrise, 2 = Sunset + * Time hours:minutes + * Window minutes (0..15) + * Days 7 day character mask starting with Sunday (SMTWTFS). 0 or - = Off, any other value = On + * Repeat 0 = Execute once, 1 = Execute again + * Output 1..16 + * Action 0 = Off, 1 = On, 2 = Toggle, 3 = Blink or Rule if USE_RULES enabled + * +\*********************************************************************************************/ + +enum TimerCommands { CMND_TIMER, CMND_TIMERS +#ifdef USE_SUNRISE +, CMND_LATITUDE, CMND_LONGITUDE +#endif + }; +const char kTimerCommands[] PROGMEM = D_CMND_TIMER "|" D_CMND_TIMERS +#ifdef USE_SUNRISE +"|" D_CMND_LATITUDE "|" D_CMND_LONGITUDE +#endif +; + +uint16_t timer_last_minute = 60; +int8_t timer_window[MAX_TIMERS] = { 0 }; + +#ifdef USE_SUNRISE +/*********************************************************************************************\ + * Sunrise and sunset (+13k code) + * + * https://forum.arduino.cc/index.php?topic=218280.0 + * Source: C-Programm von http://lexikon.astronomie.info/zeitgleichung/neu.html + * Rewrite for Arduino by 'jurs' for German Arduino forum +\*********************************************************************************************/ + +const double pi2 = TWO_PI; +const double pi = PI; +const double RAD = DEG_TO_RAD; + +double JulianischesDatum() +{ + // Gregorianischer Kalender + int Gregor; + int Jahr = RtcTime.year; + int Monat = RtcTime.month; + int Tag = RtcTime.day_of_month; + + if (Monat <= 2) { + Monat += 12; + Jahr -= 1; + } + Gregor = (Jahr / 400) - (Jahr / 100) + (Jahr / 4); // Gregorianischer Kalender + return 2400000.5 + 365.0*Jahr - 679004.0 + Gregor + (int)(30.6001 * (Monat +1)) + Tag + 0.5; +} + +double InPi(double x) +{ + int n = (int)(x / pi2); + x = x - n*pi2; + if (x < 0) x += pi2; + return x; +} + +double eps(double T) +{ + // Neigung der Erdachse + return RAD * (23.43929111 + (-46.8150*T - 0.00059*T*T + 0.001813*T*T*T)/3600.0); +} + +double BerechneZeitgleichung(double *DK,double T) +{ + double RA_Mittel = 18.71506921 + 2400.0513369*T +(2.5862e-5 - 1.72e-9*T)*T*T; + double M = InPi(pi2 * (0.993133 + 99.997361*T)); + double L = InPi(pi2 * (0.7859453 + M/pi2 + (6893.0*sin(M)+72.0*sin(2.0*M)+6191.2*T) / 1296.0e3)); + double e = eps(T); + double RA = atan(tan(L)*cos(e)); + if (RA < 0.0) RA += pi; + if (L > pi) RA += pi; + RA = 24.0*RA/pi2; + *DK = asin(sin(e)*sin(L)); + // Damit 0<=RA_Mittel<24 + RA_Mittel = 24.0 * InPi(pi2*RA_Mittel/24.0)/pi2; + double dRA = RA_Mittel - RA; + if (dRA < -12.0) dRA += 24.0; + if (dRA > 12.0) dRA -= 24.0; + dRA = dRA * 1.0027379; + return dRA; +} + +void DuskTillDawn(uint8_t *hour_up,uint8_t *minute_up, uint8_t *hour_down, uint8_t *minute_down) +{ + double JD2000 = 2451545.0; + double JD = JulianischesDatum(); + double T = (JD - JD2000) / 36525.0; + double DK; + /* + h (D) = -0.8333 normaler SA & SU-Gang + h (D) = -6.0 civile Dämmerung + h (D) = -12.0 nautische Dämmerung + h (D) = -18.0 astronomische Dämmerung + */ +// double h = -50/60.0*RAD; + double h = SUNRISE_DAWN_ANGLE *RAD; + double B = (((double)Settings.latitude)/1000000) * RAD; // geographische Breite + double GeographischeLaenge = ((double)Settings.longitude)/1000000; +// double Zeitzone = 0; //Weltzeit +// double Zeitzone = 1; //Winterzeit +// double Zeitzone = 2.0; //Sommerzeit + double Zeitzone = ((double)time_timezone) / 10; + double Zeitgleichung = BerechneZeitgleichung(&DK, T); + double Minuten = Zeitgleichung * 60.0; + double Zeitdifferenz = 12.0*acos((sin(h) - sin(B)*sin(DK)) / (cos(B)*cos(DK)))/pi; + double AufgangOrtszeit = 12.0 - Zeitdifferenz - Zeitgleichung; + double UntergangOrtszeit = 12.0 + Zeitdifferenz - Zeitgleichung; + double AufgangWeltzeit = AufgangOrtszeit - GeographischeLaenge / 15.0; + double UntergangWeltzeit = UntergangOrtszeit - GeographischeLaenge / 15.0; + double Aufgang = AufgangWeltzeit + Zeitzone; // In Stunden + if (Aufgang < 0.0) { + Aufgang += 24.0; + } else { + if (Aufgang >= 24.0) Aufgang -= 24.0; + } + double Untergang = UntergangWeltzeit + Zeitzone; + if (Untergang < 0.0) { + Untergang += 24.0; + } else { + if (Untergang >= 24.0) Untergang -= 24.0; + } + int AufgangMinuten = (int)(60.0*(Aufgang - (int)Aufgang)+0.5); + int AufgangStunden = (int)Aufgang; + if (AufgangMinuten >= 60.0) { + AufgangMinuten -= 60.0; + AufgangStunden++; + } else { + if (AufgangMinuten < 0.0) { + AufgangMinuten += 60.0; + AufgangStunden--; + if (AufgangStunden < 0.0) AufgangStunden += 24.0; + } + } + int UntergangMinuten = (int)(60.0*(Untergang - (int)Untergang)+0.5); + int UntergangStunden = (int)Untergang; + if (UntergangMinuten >= 60.0) { + UntergangMinuten -= 60.0; + UntergangStunden++; + } else { + if (UntergangMinuten<0) { + UntergangMinuten += 60.0; + UntergangStunden--; + if (UntergangStunden < 0.0) UntergangStunden += 24.0; + } + } + *hour_up = AufgangStunden; + *minute_up = AufgangMinuten; + *hour_down = UntergangStunden; + *minute_down = UntergangMinuten; +} + +void ApplyTimerOffsets(Timer *duskdawn) +{ + uint8_t hour[2]; + uint8_t minute[2]; + Timer stored = (Timer)*duskdawn; + + // replace hours, minutes by sunrise + DuskTillDawn(&hour[0], &minute[0], &hour[1], &minute[1]); + uint8_t mode = (duskdawn->mode -1) &1; + duskdawn->time = (hour[mode] *60) + minute[mode]; + + // apply offsets, check for over- and underflows + uint16_t timeBuffer; + if ((uint16_t)stored.time > 720) { + // negative offset, time after 12:00 + timeBuffer = (uint16_t)stored.time - 720; + // check for underflow + if (timeBuffer > (uint16_t)duskdawn->time) { + timeBuffer = 1440 - (timeBuffer - (uint16_t)duskdawn->time); + duskdawn->days = duskdawn->days >> 1; + duskdawn->days |= (stored.days << 6); + } else { + timeBuffer = (uint16_t)duskdawn->time - timeBuffer; + } + } else { + // positive offset + timeBuffer = (uint16_t)duskdawn->time + (uint16_t)stored.time; + // check for overflow + if (timeBuffer > 1440) { + timeBuffer -= 1440; + duskdawn->days = duskdawn->days << 1; + duskdawn->days |= (stored.days >> 6); + } + } + duskdawn->time = timeBuffer; +} + +String GetSun(byte dawn) +{ + char stime[6]; + + uint8_t hour[2]; + uint8_t minute[2]; + + DuskTillDawn(&hour[0], &minute[0], &hour[1], &minute[1]); + dawn &= 1; + snprintf_P(stime, sizeof(stime), PSTR("%02d:%02d"), hour[dawn], minute[dawn]); + return String(stime); +} + +uint16_t GetSunMinutes(byte dawn) +{ + uint8_t hour[2]; + uint8_t minute[2]; + + DuskTillDawn(&hour[0], &minute[0], &hour[1], &minute[1]); + dawn &= 1; + return (hour[dawn] *60) + minute[dawn]; +} + +#endif // USE_SUNRISE + +/*******************************************************************************************/ + +void TimerSetRandomWindow(byte index) +{ + timer_window[index] = 0; + if (Settings.timer[index].window) { + timer_window[index] = (random(0, (Settings.timer[index].window << 1) +1)) - Settings.timer[index].window; // -15 .. 15 + } +} + +void TimerSetRandomWindows() +{ + for (byte i = 0; i < MAX_TIMERS; i++) { TimerSetRandomWindow(i); } +} + +void TimerEverySecond() +{ + if (RtcTime.valid) { + if (!RtcTime.hour && !RtcTime.minute && !RtcTime.second) { TimerSetRandomWindows(); } // Midnight + if (RtcTime.minute != timer_last_minute) { // Execute every minute only once + timer_last_minute = RtcTime.minute; + int16_t time = (RtcTime.hour *60) + RtcTime.minute; + uint8_t days = 1 << (RtcTime.day_of_week -1); + + for (byte i = 0; i < MAX_TIMERS; i++) { +// if (Settings.timer[i].device >= devices_present) Settings.timer[i].data = 0; // Reset timer due to change in devices present + Timer xtimer = Settings.timer[i]; + uint16_t set_time = xtimer.time; +#ifdef USE_SUNRISE + if ((1 == xtimer.mode) || (2 == xtimer.mode)) { // Sunrise or Sunset + ApplyTimerOffsets(&xtimer); + set_time = xtimer.time; + } +#endif + if (xtimer.arm) { + set_time += timer_window[i]; // Add random time offset + if (set_time < 0) { set_time = 0; } // Stay today; + if (set_time > 1439) { set_time = 1439; } + if (time == set_time) { + if (xtimer.days & days) { + Settings.timer[i].arm = xtimer.repeat; +#ifdef USE_RULES + if (3 == xtimer.power) { // Blink becomes Rule disregarding device and allowing use of Backlog commands + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"Clock\":{\"Timer\":%d}}"), i +1); + RulesProcess(); + } else +#endif // USE_RULES + if (devices_present) { ExecuteCommandPower(xtimer.device +1, xtimer.power); } + } + } + } + } + } + } +} + +void PrepShowTimer(uint8_t index) +{ + char days[8] = { 0 }; + char soutput[80]; + + Timer xtimer = Settings.timer[index -1]; + + for (byte i = 0; i < 7; i++) { + uint8_t mask = 1 << i; + snprintf(days, sizeof(days), "%s%d", days, ((xtimer.days & mask) > 0)); + } + + soutput[0] = '\0'; + if (devices_present) { + snprintf_P(soutput, sizeof(soutput), PSTR(",\"" D_JSON_TIMER_OUTPUT "\":%d"), xtimer.device +1); + } +#ifdef USE_SUNRISE + int16_t hour = xtimer.time / 60; + if ((1 == xtimer.mode) || (2 == xtimer.mode)) { // Sunrise or Sunset + if (hour > 11) { hour = (hour -12) * -1; } + } + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s\"" D_CMND_TIMER "%d\":{\"" D_JSON_TIMER_ARM "\":%d,\"" D_JSON_TIMER_MODE "\":%d,\"" D_JSON_TIMER_TIME "\":\"%02d:%02d\",\"" D_JSON_TIMER_WINDOW "\":%d,\"" D_JSON_TIMER_DAYS "\":\"%s\",\"" D_JSON_TIMER_REPEAT "\":%d%s,\"" D_JSON_TIMER_ACTION "\":%d}"), + mqtt_data, index, xtimer.arm, xtimer.mode, hour, xtimer.time % 60, xtimer.window, days, xtimer.repeat, soutput, xtimer.power); +#else + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s\"" D_CMND_TIMER "%d\":{\"" D_JSON_TIMER_ARM "\":%d,\"" D_JSON_TIMER_TIME "\":\"%02d:%02d\",\"" D_JSON_TIMER_WINDOW "\":%d,\"" D_JSON_TIMER_DAYS "\":\"%s\",\"" D_JSON_TIMER_REPEAT "\":%d%s,\"" D_JSON_TIMER_ACTION "\":%d}"), + mqtt_data, index, xtimer.arm, xtimer.time / 60, xtimer.time % 60, xtimer.window, days, xtimer.repeat, soutput, xtimer.power); +#endif // USE_SUNRISE +} + +/*********************************************************************************************\ + * Commands +\*********************************************************************************************/ + +boolean TimerCommand() +{ + char command[CMDSZ]; + char dataBufUc[XdrvMailbox.data_len]; + boolean serviced = true; + uint8_t index = XdrvMailbox.index; + + UpperCase(dataBufUc, XdrvMailbox.data); + int command_code = GetCommandCode(command, sizeof(command), XdrvMailbox.topic, kTimerCommands); + if ((CMND_TIMER == command_code) && (index > 0) && (index <= MAX_TIMERS)) { + uint8_t error = 0; + if (XdrvMailbox.data_len) { + if ((XdrvMailbox.payload >= 0) && (XdrvMailbox.payload <= MAX_TIMERS)) { + if (XdrvMailbox.payload == 0) { + Settings.timer[index -1].data = 0; // Clear timer + } else { + Settings.timer[index -1].data = Settings.timer[XdrvMailbox.payload -1].data; // Copy timer + } + } else { +#ifndef USE_RULES + if (devices_present) { +#endif + StaticJsonBuffer<200> jsonBuffer; + JsonObject& root = jsonBuffer.parseObject(dataBufUc); + if (!root.success()) { + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_CMND_TIMER "%d\":\"" D_JSON_INVALID_JSON "\"}"), index); // JSON decode failed + error = 1; + } + else { + char parm_uc[10]; + index--; + if (root[UpperCase_P(parm_uc, PSTR(D_JSON_TIMER_ARM))].success()) { + Settings.timer[index].arm = (root[parm_uc] != 0); + } +#ifdef USE_SUNRISE + if (root[UpperCase_P(parm_uc, PSTR(D_JSON_TIMER_MODE))].success()) { + Settings.timer[index].mode = (uint8_t)root[parm_uc] & 0x03; + } +#endif + if (root[UpperCase_P(parm_uc, PSTR(D_JSON_TIMER_TIME))].success()) { + uint16_t itime = 0; + int8_t value = 0; + char time_str[10]; + + snprintf(time_str, sizeof(time_str), root[parm_uc]); + const char *substr = strtok(time_str, ":"); + if (substr != NULL) { + value = atoi(substr); + if (value < 0) { value = abs(value) +12; } // Allow entering timer offset from -11:59 to -00:01 converted to 12:01 to 23:59 + if (value > 23) { value = 23; } + itime = value * 60; + substr = strtok(NULL, ":"); + if (substr != NULL) { + value = atoi(substr); + if (value < 0) { value = 0; } + if (value > 59) { value = 59; } + itime += value; + } + } + Settings.timer[index].time = itime; + } + if (root[UpperCase_P(parm_uc, PSTR(D_JSON_TIMER_WINDOW))].success()) { + Settings.timer[index].window = (uint8_t)root[parm_uc] & 0x0F; + TimerSetRandomWindow(index); + } + if (root[UpperCase_P(parm_uc, PSTR(D_JSON_TIMER_DAYS))].success()) { + // SMTWTFS = 1234567 = 0011001 = 00TW00S = --TW--S + Settings.timer[index].days = 0; + const char *tday = root[parm_uc]; + char ch = '.'; + + uint8_t i = 0; + while ((ch != '\0') && (i < 7)) { + ch = *tday++; + if (ch == '-') { ch = '0'; } + uint8_t mask = 1 << i++; + Settings.timer[index].days |= (ch == '0') ? 0 : mask; + } + } + if (root[UpperCase_P(parm_uc, PSTR(D_JSON_TIMER_REPEAT))].success()) { + Settings.timer[index].repeat = (root[parm_uc] != 0); + } + if (root[UpperCase_P(parm_uc, PSTR(D_JSON_TIMER_OUTPUT))].success()) { + uint8_t device = ((uint8_t)root[parm_uc] -1) & 0x0F; + Settings.timer[index].device = (device < devices_present) ? device : 0; + } + if (root[UpperCase_P(parm_uc, PSTR(D_JSON_TIMER_ACTION))].success()) { + uint8_t action = ((uint8_t)root[parm_uc] -1) & 0x03; + Settings.timer[index].power = (devices_present) ? action : 3; // If no devices than only allow rules + } + + index++; + } +#ifndef USE_RULES + } else { + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_CMND_TIMER "%d\":\"" D_JSON_TIMER_NO_DEVICE "\"}"), index); // No outputs defined so nothing to control + error = 1; + } +#endif + } + } + if (!error) { + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{")); + PrepShowTimer(index); + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s}"), mqtt_data); + } + } + else if (CMND_TIMERS == command_code) { + byte jsflg = 0; + byte lines = 1; + for (byte i = 0; i < MAX_TIMERS; i++) { + if (!jsflg) { + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_CMND_TIMERS "%d\":{"), lines++); + } else { + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,"), mqtt_data); + } + jsflg++; + PrepShowTimer(i +1); + if (jsflg > 3) { + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s}}"), mqtt_data); + MqttPublishPrefixTopic_P(RESULT_OR_STAT, PSTR(D_CMND_TIMERS)); + jsflg = 0; + } + } + mqtt_data[0] = '\0'; + } +#ifdef USE_SUNRISE + else if (CMND_LONGITUDE == command_code) { + if (XdrvMailbox.data_len) { + Settings.longitude = (int)(CharToDouble(XdrvMailbox.data) *1000000); + } + char lbuff[32]; + dtostrfd(((double)Settings.longitude) /1000000, 6, lbuff); + snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, lbuff); + } + else if (CMND_LATITUDE == command_code) { + if (XdrvMailbox.data_len) { + Settings.latitude = (int)(CharToDouble(XdrvMailbox.data) *1000000); + } + char lbuff[32]; + dtostrfd(((double)Settings.latitude) /1000000, 6, lbuff); + snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, lbuff); + } +#endif + else serviced = false; + + return serviced; +} + +/*********************************************************************************************\ + * Presentation +\*********************************************************************************************/ + +#ifdef USE_WEBSERVER +#ifdef USE_TIMERS_WEB +const char HTTP_TIMER_SCRIPT[] PROGMEM = + "var pt=[],ct=99;" + "function qs(s){" // Alias to save code space + "return document.querySelector(s);" + "}" + "function ce(i,q){" // Create select option + "var o=document.createElement('option');" + "o.textContent=i;" + "q.appendChild(o);" + "}" +#ifdef USE_SUNRISE + "function gt(){" // Set hours and minutes according to mode + "var m,p,q;" + "m=qs('input[name=\"rd\"]:checked').value;" // Get mode + "p=pt[ct]&0x7FF;" // Get time + "if(m==0){" // Time is set + "so(0);" // Hide offset span and allow Hour 00..23 + "q=Math.floor(p/60);if(q<10){q='0'+q;}qs('#ho').value=q;" // Set hours + "q=p%60;if(q<10){q='0'+q;}qs('#mi').value=q;" // Set minutes + "}" + "if((m==1)||(m==2)){" // Sunrise or sunset is set + "so(1);" // Show offset span and allow Hour 00..11 + "q=Math.floor(p/60);" // Parse hours + "if(q>=12){q-=12;qs('#dr').selectedIndex=1;}" // Negative offset + "else{qs('#dr').selectedIndex=0;}" + "if(q<10){q='0'+q;}qs('#ho').value=q;" // Set offset hours + "q=p%60;if(q<10){q='0'+q;}qs('#mi').value=q;" // Set offset minutes + "}" + "}" + "function so(b){" // Hide or show offset items + "o=qs('#ho');" + "e=o.childElementCount;" + "if(b==1){" + "qs('#dr').disabled='';" + "if(e>12){for(i=12;i<=23;i++){o.removeChild(o.lastElementChild);}}" // Create offset hours select options + "}else{" + "qs('#dr').disabled='disabled';" + "if(e<23){for(i=12;i<=23;i++){ce(i,o);}}" // Create hours select options + "}" + "}" +#endif + "function st(){" // Save parameters to hidden area + "var i,l,m,n,p,s;" + "m=0;s=0;" + "n=1<<31;if(eb('a0').checked){s|=n;}" // Get arm + "n=1<<15;if(eb('r0').checked){s|=n;}" // Get repeat + "for(i=0;i<7;i++){n=1<<(16+i);if(eb('w'+i).checked){s|=n;}}" // Get weekdays +#ifdef USE_SUNRISE + "m=qs('input[name=\"rd\"]:checked').value;" // Check mode + "s|=(qs('input[name=\"rd\"]:checked').value<<29);" // Get mode +#endif + "if(}1>0){" + "i=qs('#d1').selectedIndex;if(i>=0){s|=(i<<23);}" // Get output + "s|=(qs('#p1').selectedIndex<<27);" // Get action + "}else{" + "s|=3<<27;" // Get action (rule) + "}" + "l=((qs('#ho').selectedIndex*60)+qs('#mi').selectedIndex)&0x7FF;" + "if(m==0){s|=l;}" // Get time +#ifdef USE_SUNRISE + "if((m==1)||(m==2)){" + "if(qs('#dr').selectedIndex>0){l+=720;}" // If negative offset, add 12h to given offset time + "s|=l&0x7FF;" // Save offset instead of time + "}" +#endif + "s|=((qs('#mw').selectedIndex)&0x0F)<<11;" // Get window minutes + "pt[ct]=s;" + "eb('t0').value=pt.join();" // Save parameters from array to hidden area + "}" + "function ot(t,e){" // Select tab and update elements + "var i,n,o,p,q,s;" + "if(ct<99){st();}" // Save changes + "ct=t;" + "o=document.getElementsByClassName('tl');" // Restore style to all tabs/buttons + "for(i=0;i>29)&3;eb('b'+p).checked=1;" // Set mode + "gt();" // Set hours and minutes according to mode +#else + "p=s&0x7FF;" // Get time + "q=Math.floor(p/60);if(q<10){q='0'+q;}qs('#ho').value=q;" // Set hours + "q=p%60;if(q<10){q='0'+q;}qs('#mi').value=q;" // Set minutes +#endif + "q=(s>>11)&0xF;if(q<10){q='0'+q;}qs('#mw').value=q;" // Set window minutes + "for(i=0;i<7;i++){p=(s>>(16+i))&1;eb('w'+i).checked=p;}" // Set weekdays + "if(}1>0){" + "p=(s>>23)&0xF;qs('#d1').value=p+1;" // Set output + "p=(s>>27)&3;qs('#p1').selectedIndex=p;" // Set action + "}" + "p=(s>>15)&1;eb('r0').checked=p;" // Set repeat + "p=(s>>31)&1;eb('a0').checked=p;" // Set arm + "}" + "function it(){" // Initialize elements and select first tab + "var b,i,o,s;" + "pt=eb('t0').value.split(',').map(Number);" // Get parameters from hidden area to array + "s='';for(i=0;i<" STR(MAX_TIMERS) ";i++){b='';if(0==i){b=\" id='dP'\";}s+=\"\"}" + "eb('bt').innerHTML=s;" // Create tabs + "if(}1>0){" // Create Output and Action drop down boxes + "eb('oa').innerHTML=\"" D_TIMER_OUTPUT " " D_TIMER_ACTION " \";" + "o=qs('#p1');ce('" D_OFF "',o);ce('" D_ON "',o);ce('" D_TOGGLE "',o);" // Create offset direction select options +#ifdef USE_RULES + "ce('" D_RULE "',o);" +#else + "ce('" D_BLINK "',o);" +#endif + "}else{" + "eb('oa').innerHTML=\"" D_TIMER_ACTION " " D_RULE "\";" // No outputs but rule is allowed + "}" +#ifdef USE_SUNRISE + "o=qs('#dr');ce('+',o);ce('-',o);" // Create offset direction select options +#endif + "o=qs('#ho');for(i=0;i<=23;i++){ce((i<10)?('0'+i):i,o);}" // Create hours select options + "o=qs('#mi');for(i=0;i<=59;i++){ce((i<10)?('0'+i):i,o);}" // Create minutes select options + "o=qs('#mw');for(i=0;i<=15;i++){ce((i<10)?('0'+i):i,o);}" // Create window minutes select options + "o=qs('#d1');for(i=0;i<}1;i++){ce(i+1,o);}" // Create outputs + "var a='" D_DAY3LIST "';" + "s='';for(i=0;i<7;i++){s+=\"\"+a.substring(i*3,(i*3)+3)+\"\"}" + "eb('ds').innerHTML=s;" // Create weekdays + "eb('dP').click();" // Get the element with id='dP' and click on it + "}"; +const char HTTP_TIMER_STYLE[] PROGMEM = + ".tl{float:left;border-radius:0;border:1px solid #fff;padding:1px;width:6.25%;}" +#ifdef USE_SUNRISE + "input[type='radio']{width:13px;height:24px;margin-top:-1px;margin-right:8px;vertical-align:middle;}" +#endif + ""; +const char HTTP_FORM_TIMER[] PROGMEM = + "
 " D_TIMER_PARAMETERS " " + "



" + "

" + "
" + "" D_TIMER_ARM " " + "" D_TIMER_REPEAT "" + "

" + "
" +#ifdef USE_SUNRISE + "
" + "" D_TIMER_TIME "
" + "" D_SUNRISE " (}8)
" + "" D_SUNSET " (}9)
" + "
" + "" + " " +#else + "" D_TIMER_TIME " " +#endif // USE_SUNRISE + "" + " " D_HOUR_MINUTE_SEPARATOR " " + "" + " +/- " + "" + "

" + "
"; +const char HTTP_FORM_TIMER2[] PROGMEM = + "type='submit' onclick='st();this.form.submit();'"; + +const char S_CONFIGURE_TIMER[] PROGMEM = D_CONFIGURE_TIMER; + +void HandleTimerConfiguration() +{ + if (HTTP_USER == webserver_state) { + HandleRoot(); + return; + } + AddLog_P(LOG_LEVEL_DEBUG, S_LOG_HTTP, S_CONFIGURE_TIMER); + + String page = FPSTR(HTTP_HEAD); + page.replace(F("{v}"), FPSTR(S_CONFIGURE_TIMER)); + page += FPSTR(HTTP_TIMER_SCRIPT); + page += FPSTR(HTTP_HEAD_STYLE); + page.replace(F(""), FPSTR(HTTP_TIMER_STYLE)); + page += FPSTR(HTTP_FORM_TIMER); + for (byte i = 0; i < MAX_TIMERS; i++) { + if (i > 0) { page += F(","); } + page += String(Settings.timer[i].data); + } + page += FPSTR(HTTP_FORM_TIMER1); + page.replace(F("}1"), String(devices_present)); +#ifdef USE_SUNRISE + page.replace(F("}8"), GetSun(0)); // Add Sunrise + page.replace(F("}9"), GetSun(1)); // Add Sunset + page.replace(F("299"), String(100 + (strlen(D_SUNSET) *12))); // Fix string length to keep radios centered +#endif // USE_SUNRISE + page += FPSTR(HTTP_FORM_END); + page.replace(F("type='submit'"), FPSTR(HTTP_FORM_TIMER2)); + page += F(""); // Init elements and select first tab/button + page += FPSTR(HTTP_BTN_CONF); + ShowPage(page); +} + +void TimerSaveSettings() +{ + char tmp[MAX_TIMERS *12]; // Need space for MAX_TIMERS x 10 digit numbers separated by a comma + Timer timer; + + WebGetArg("t0", tmp, sizeof(tmp)); + char *p = tmp; + snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_MQTT D_CMND_TIMERS " ")); + for (byte i = 0; i < MAX_TIMERS; i++) { + timer.data = strtol(p, &p, 10); + p++; // Skip comma + if (timer.time < 1440) { + bool flag = (timer.window != Settings.timer[i].window); + Settings.timer[i].data = timer.data; + if (flag) TimerSetRandomWindow(i); + } + snprintf_P(log_data, sizeof(log_data), PSTR("%s%s0x%08X"), log_data, (i > 0)?",":"", Settings.timer[i].data); + } + AddLog(LOG_LEVEL_DEBUG); +} +#endif // USE_TIMERS_WEB +#endif // USE_WEBSERVER + +/*********************************************************************************************\ + * Interface +\*********************************************************************************************/ + +#define XDRV_09 + +boolean Xdrv09(byte function) +{ + boolean result = false; + + switch (function) { + case FUNC_INIT: + TimerSetRandomWindows(); + break; + case FUNC_EVERY_SECOND: + TimerEverySecond(); + break; + case FUNC_COMMAND: + result = TimerCommand(); + break; + } + return result; +} + +#endif // USE_TIMERS \ No newline at end of file diff --git a/sonoff/xdrv_10_rules.ino b/sonoff/xdrv_10_rules.ino new file mode 100644 index 000000000..f92edcf55 --- /dev/null +++ b/sonoff/xdrv_10_rules.ino @@ -0,0 +1,478 @@ +/* + xdrv_10_rules.ino - rule support for Sonoff-Tasmota + + Copyright (C) 2018 ESP Easy Group and Theo Arends + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifdef USE_RULES +/*********************************************************************************************\ + * Rules based heavily on ESP Easy implementation + * + * Inspiration: https://github.com/letscontrolit/ESPEasy + * + * Add rules using the following, case insensitive, format: + * on do endon on do endon .. + * + * Examples: + * on System#Boot do Color 001000 endon + * on INA219#Current>0.100 do Dimmer 10 endon + * on INA219#Current>0.100 do Backlog Dimmer 10;Color 10,0,0 endon + * on INA219#Current>0.100 do Backlog Dimmer 10;Color 100000 endon on System#Boot do color 001000 endon + * on ds18b20#temperature>23 do power off endon on ds18b20#temperature<22 do power on endon + * on mqtt#connected do color 000010 endon + * on mqtt#disconnected do color 00100C endon + * on time#initialized do color 001000 endon + * on time#set do color 001008 endon + * on clock#timer=3 do color 080800 endon + * on rules#timer=1 do color 080800 endon + * on mqtt#connected do color 000010 endon on mqtt#disconnected do color 001010 endon on time#initialized do color 001000 endon on time#set do backlog color 000810;ruletimer1 10 endon on rules#timer=1 do color 080800 endon + * on event#anyname do color 100000 endon + * on event#anyname do color %value% endon + * on power1#state=1 do color 001000 endon + * on button1#state do publish cmnd/ring2/power %value% endon on button2#state do publish cmnd/strip1/power %value% endon + * on switch1#state do power2 %value% endon + * + * Notes: + * Spaces after , around and before are mandatory + * System#Boot is initiated after MQTT is connected due to command handling preparation + * Control rule triggering with command: + * Rule 0 = Rules disabled (Off) + * Rule 1 = Rules enabled (On) + * Rule 2 = Toggle rules state + * Rule 4 = Perform commands as long as trigger is met (Once OFF) + * Rule 5 = Perform commands once until trigger is not met (Once ON) + * Rule 6 = Toggle Once state + * Execute an event like: + * Event anyname=001000 + * Set a RuleTimer to 100 seconds like: + * RuleTimer2 100 +\*********************************************************************************************/ + +#define MAX_RULE_TIMERS 8 +#define RULES_MAX_VARS 5 + +#ifndef ULONG_MAX +#define ULONG_MAX 0xffffffffUL +#endif + +#define D_CMND_RULE "Rule" +#define D_CMND_RULETIMER "RuleTimer" +#define D_CMND_EVENT "Event" + +#define D_JSON_INITIATED "Initiated" + +enum RulesCommands { CMND_RULE, CMND_RULETIMER, CMND_EVENT }; +const char kRulesCommands[] PROGMEM = D_CMND_RULE "|" D_CMND_RULETIMER "|" D_CMND_EVENT ; + +String rules_event_value; +unsigned long rules_timer[MAX_RULE_TIMERS] = { 0 }; +uint8_t rules_quota = 0; +long rules_power = -1; + +uint32_t rules_triggers = 0; +uint8_t rules_trigger_count = 0; +uint8_t rules_teleperiod = 0; + +/*******************************************************************************************/ + +long TimeDifference(unsigned long prev, unsigned long next) +{ + // Return the time difference as a signed value, taking into account the timers may overflow. + // Returned timediff is between -24.9 days and +24.9 days. + // Returned value is positive when "next" is after "prev" + long signed_diff = 0; + // To cast a value to a signed long, the difference may not exceed half the ULONG_MAX + const unsigned long half_max_unsigned_long = 2147483647u; // = 2^31 -1 + if (next >= prev) { + const unsigned long diff = next - prev; + if (diff <= half_max_unsigned_long) { // Normal situation, just return the difference. + signed_diff = static_cast(diff); // Difference is a positive value. + } else { + // prev has overflow, return a negative difference value + signed_diff = static_cast((ULONG_MAX - next) + prev + 1u); + signed_diff = -1 * signed_diff; + } + } else { + // next < prev + const unsigned long diff = prev - next; + if (diff <= half_max_unsigned_long) { // Normal situation, return a negative difference value + signed_diff = static_cast(diff); + signed_diff = -1 * signed_diff; + } else { + // next has overflow, return a positive difference value + signed_diff = static_cast((ULONG_MAX - prev) + next + 1u); + } + } + return signed_diff; +} + +long TimePassedSince(unsigned long timestamp) +{ + // Compute the number of milliSeconds passed since timestamp given. + // Note: value can be negative if the timestamp has not yet been reached. + return TimeDifference(timestamp, millis()); +} + +bool TimeReached(unsigned long timer) +{ + // Check if a certain timeout has been reached. + const long passed = TimePassedSince(timer); + return (passed >= 0); +} + +/*******************************************************************************************/ + +bool RulesRuleMatch(String &event, String &rule) +{ + // event = {"INA219":{"Voltage":4.494,"Current":0.020,"Power":0.089}} + // event = {"System":{"Boot":1}} + // rule = "INA219#CURRENT>0.100" + + bool match = false; + + // Step1: Analyse rule + int pos = rule.indexOf('#'); + if (pos == -1) { return false; } // No # sign in rule + + String rule_task = rule.substring(0, pos); // "INA219" or "SYSTEM" + if (rules_teleperiod) { + int ppos = rule_task.indexOf("TELE-"); // "TELE-INA219" or "INA219" + if (ppos == -1) { return false; } // No pre-amble in rule + rule_task = rule.substring(5, pos); // "INA219" or "SYSTEM" + } + + String rule_name = rule.substring(pos +1); // "CURRENT>0.100" or "BOOT" + + char compare = ' '; + pos = rule_name.indexOf(">"); + if (pos > 0) { + compare = '>'; + } else { + pos = rule_name.indexOf("<"); + if (pos > 0) { + compare = '<'; + } else { + pos = rule_name.indexOf("="); + if (pos > 0) { + compare = '='; + } + } + } + + String tmp_value = "none"; + double rule_value = 0; + if (pos > 0) { + tmp_value = rule_name.substring(pos + 1); // "0.100" + rule_value = CharToDouble((char*)tmp_value.c_str()); // 0.1 - This saves 9k code over toFLoat()! + rule_name = rule_name.substring(0, pos); // "CURRENT" + } + + // Step2: Search rule_task and rule_name + StaticJsonBuffer<400> jsonBuf; + JsonObject &root = jsonBuf.parseObject(event); + if (!root.success()) { return false; } // No valid JSON data + + double value = 0; + const char* str_value = root[rule_task][rule_name]; + +// snprintf_P(log_data, sizeof(log_data), PSTR("RUL: Task %s, Name %s, Value %s, TrigCnt %d, TrigSt %d, Source %s, Json %s"), +// rule_task.c_str(), rule_name.c_str(), tmp_value.c_str(), rules_trigger_count, bitRead(rules_triggers, rules_trigger_count), event.c_str(), (str_value) ? str_value : "none"); +// AddLog(LOG_LEVEL_DEBUG); + + if (!root[rule_task][rule_name].success()) { return false; } + // No value but rule_name is ok + + rules_event_value = str_value; // Prepare %value% + + // Step 3: Compare rule (value) + if (str_value) { + value = CharToDouble((char*)str_value); + switch (compare) { + case '>': + if (value > rule_value) match = true; + break; + case '<': + if (value < rule_value) match = true; + break; + case '=': + if (value == rule_value) match = true; + break; + case ' ': + match = true; // Json value but not needed + break; + } + } else match = true; + + if (Settings.flag.rules_once) { + if (match) { // Only allow match state changes + if (!bitRead(rules_triggers, rules_trigger_count)) { + bitSet(rules_triggers, rules_trigger_count); + } else { + match = false; + } + } else { + bitClear(rules_triggers, rules_trigger_count); + } + } + + return match; +} + +/*******************************************************************************************/ + +bool RulesProcess() +{ + bool serviced = false; + char vars[RULES_MAX_VARS][10] = { 0 }; + char stemp[10]; + + if (!Settings.flag.rules_enabled) { return serviced; } // Not enabled + if (!strlen(Settings.rules)) { return serviced; } // No rules + + String event_saved = mqtt_data; + event_saved.toUpperCase(); + String rules = Settings.rules; + + rules_trigger_count = 0; + int plen = 0; + while (true) { + rules = rules.substring(plen); // Select relative to last rule + rules.trim(); + if (!rules.length()) { return serviced; } // No more rules + + String rule = rules; + rule.toUpperCase(); // "ON INA219#CURRENT>0.100 DO BACKLOG DIMMER 10;COLOR 100000 ENDON" + if (!rule.startsWith("ON ")) { return serviced; } // Bad syntax - Nothing to start on + + int pevt = rule.indexOf(" DO "); + if (pevt == -1) { return serviced; } // Bad syntax - Nothing to do + String event_trigger = rule.substring(3, pevt); // "INA219#CURRENT>0.100" + + plen = rule.indexOf(" ENDON"); + if (plen == -1) { return serviced; } // Bad syntax - No endon + String commands = rules.substring(pevt +4, plen); // "Backlog Dimmer 10;Color 100000" + plen += 6; + +// snprintf_P(log_data, sizeof(log_data), PSTR("RUL: Trigger |%s|, Commands |%s|"), event_trigger.c_str(), commands.c_str()); +// AddLog(LOG_LEVEL_DEBUG); + + rules_event_value = ""; + String event = event_saved; + if (RulesRuleMatch(event, event_trigger)) { + commands.trim(); + String ucommand = commands; + ucommand.toUpperCase(); + if (ucommand.startsWith("VAR")) { + uint8_t idx = ucommand.charAt(3) - '1'; +// idx -= '1'; + if ((idx >= 0) && (idx < RULES_MAX_VARS)) { snprintf(vars[idx], sizeof(vars[idx]), rules_event_value.c_str()); } + } else { + commands.replace(F("%value%"), rules_event_value); + for (byte i = 0; i < RULES_MAX_VARS; i++) { + if (strlen(vars[i])) { + snprintf_P(stemp, sizeof(stemp), PSTR("%%var%d%%"), i +1); + commands.replace(stemp, vars[i]); + } + } + char command[commands.length() +1]; + snprintf(command, sizeof(command), commands.c_str()); + + snprintf_P(log_data, sizeof(log_data), PSTR("RUL: %s performs \"%s\""), event_trigger.c_str(), command); + AddLog(LOG_LEVEL_INFO); + +// snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, D_CMND_RULE, D_JSON_INITIATED); +// MqttPublishPrefixTopic_P(RESULT_OR_STAT, PSTR(D_CMND_RULE)); + + ExecuteCommand(command); + } + serviced = true; + } + rules_trigger_count++; + } + return serviced; +} + +/*******************************************************************************************/ + +void RulesInit() +{ + if (Settings.rules[0] == '\0') { + Settings.flag.rules_enabled = 0; + Settings.flag.rules_once = 0; + } + rules_teleperiod = 0; +} + +void RulesSetPower() +{ + if (Settings.flag.rules_enabled) { + uint16_t new_power = XdrvMailbox.index; + if (rules_power == -1) rules_power = new_power; + uint16_t old_power = rules_power; + rules_power = new_power; + for (byte i = 0; i < devices_present; i++) { + uint8_t new_state = new_power &1; + uint8_t old_state = old_power &1; + if (new_state != old_state) { + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"Power%d\":{\"State\":%d}}"), i +1, new_state); + RulesProcess(); + } + new_power >>= 1; + old_power >>= 1; + } + } +} + +void RulesEvery50ms() +{ + if (Settings.flag.rules_enabled) { + rules_quota++; + if (rules_quota &1) { // Every 100 ms + mqtt_data[0] = '\0'; + uint16_t tele_period_save = tele_period; + tele_period = 2; // Do not allow HA updates during next function call + XsnsNextCall(FUNC_JSON_APPEND); // ,"INA219":{"Voltage":4.494,"Current":0.020,"Power":0.089} + tele_period = tele_period_save; + if (strlen(mqtt_data)) { + mqtt_data[0] = '{'; // {"INA219":{"Voltage":4.494,"Current":0.020,"Power":0.089} + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s}"), mqtt_data); + RulesProcess(); + } + } + } +} + +void RulesEverySecond() +{ + if (Settings.flag.rules_enabled) { + for (byte i = 0; i < MAX_RULE_TIMERS; i++) { + if (rules_timer[i] != 0L) { // Timer active? + if (TimeReached(rules_timer[i])) { // Timer finished? + rules_timer[i] = 0L; // Turn off this timer + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"Rules\":{\"Timer\":%d}}"), i +1); + RulesProcess(); + } + } + } + } +} + +void RulesTeleperiod() +{ + rules_teleperiod = 1; + RulesProcess(); + rules_teleperiod = 0; +} + +boolean RulesCommand() +{ + char command[CMDSZ]; + boolean serviced = true; + uint8_t index = XdrvMailbox.index; + + int command_code = GetCommandCode(command, sizeof(command), XdrvMailbox.topic, kRulesCommands); + if (CMND_RULE == command_code) { + if ((XdrvMailbox.data_len > 0) && (XdrvMailbox.data_len < sizeof(Settings.rules))) { + if ((XdrvMailbox.payload >= 0) && (XdrvMailbox.payload <= 6)) { + switch (XdrvMailbox.payload) { + case 0: // Off + case 1: // On + Settings.flag.rules_enabled = XdrvMailbox.payload; + break; + case 2: // Toggle + Settings.flag.rules_enabled ^= 1; + break; + case 4: // Off + case 5: // On + Settings.flag.rules_once = XdrvMailbox.payload &1; + break; + case 6: // Toggle + Settings.flag.rules_once ^= 1; + break; + } + } else { +/* + String uc_data = XdrvMailbox.data; // Do not allow Rule to be used within a rule + uc_data.toUpperCase(); + String uc_command = command; + uc_command += " "; // Distuingish from RuleTimer + uc_command.toUpperCase(); + if (!uc_data.indexOf(uc_command)) { strlcpy(Settings.rules, XdrvMailbox.data, sizeof(Settings.rules)); } +*/ + strlcpy(Settings.rules, XdrvMailbox.data, sizeof(Settings.rules)); + } + rules_triggers = 0; // Reset once flag + } + snprintf_P (mqtt_data, sizeof(mqtt_data), PSTR("{\"%s\":\"%s\",\"Once\":\"%s\",\"Rules\":\"%s\"}"), command, GetStateText(Settings.flag.rules_enabled), GetStateText(Settings.flag.rules_once), Settings.rules); + } + else if ((CMND_RULETIMER == command_code) && (index > 0) && (index <= MAX_RULE_TIMERS)) { + if (XdrvMailbox.data_len > 0) { + rules_timer[index -1] = (XdrvMailbox.payload > 0) ? millis() + (1000 * XdrvMailbox.payload) : 0; + } + snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_LVALUE, command, index, (rules_timer[index -1]) ? (rules_timer[index -1] - millis()) / 1000 : 0); + } + else if (CMND_EVENT == command_code) { + if (XdrvMailbox.data_len > 0) { + String event = XdrvMailbox.data; + String parameter = ""; + int pos = event.indexOf('='); + if (pos > 0) { + parameter = event.substring(pos +1); + parameter.trim(); + event = event.substring(0, pos); + } + event.trim(); + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"Event\":{\"%s\":\"%s\"}}"), event.c_str(), parameter.c_str()); + RulesProcess(); + } + snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, D_JSON_DONE); + } + else serviced = false; + + return serviced; +} + +/*********************************************************************************************\ + * Interface +\*********************************************************************************************/ + +#define XDRV_10 + +boolean Xdrv10(byte function) +{ + boolean result = false; + + switch (function) { + case FUNC_INIT: + RulesInit(); + break; + case FUNC_SET_POWER: + RulesSetPower(); + break; + case FUNC_EVERY_50_MSECOND: + RulesEvery50ms(); + break; + case FUNC_EVERY_SECOND: + RulesEverySecond(); + break; + case FUNC_COMMAND: + result = RulesCommand(); + break; + } + return result; +} + +#endif // USE_RULES \ No newline at end of file diff --git a/sonoff/xdrv_11_knx.ino b/sonoff/xdrv_11_knx.ino new file mode 100644 index 000000000..3853284a2 --- /dev/null +++ b/sonoff/xdrv_11_knx.ino @@ -0,0 +1,888 @@ +/* + xdrv_11_knx.ino - KNX IP Protocol support for Sonoff-Tasmota + + Copyright (C) 2018 Adrian Scillato (https://github.com/ascillato) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifdef USE_KNX +/*********************************************************************************************\ + * KNX support + * + * Using libraries: + * ESP KNX IP library (https://github.com/envy/esp-knx-ip) + +Constants in sonoff.h +----------------------- + +#define MAX_KNX_GA 10 Max number of KNX Group Addresses to read that can be set +#define MAX_KNX_CB 10 Max number of KNX Group Addresses to write that can be set + If you change MAX_KNX_CB you also have to change on the esp-knx-ip.h file the following: + #define MAX_CALLBACK_ASSIGNMENTS 10 + #define MAX_CALLBACKS 10 + Both to MAX_KNX_CB + +Variables in settings.h +----------------------- + +bool Settings.flag.knx_enabled Enable/Disable KNX Protocol +uint16_t Settings.knx_physsical_addr Physical KNX address of this device +byte Settings.knx_GA_registered Number of group address to read +byte Settings.knx_CB_registered Number of group address to write +uint16_t Settings.knx_GA_addr[MAX_KNX_GA] Group address to read +uint16_t Settings.knx_CB_addr[MAX_KNX_CB] Group address to write +byte Settings.knx_GA_param[MAX_KNX_GA] Type of Input (relay changed, button pressed, sensor read) +byte Settings.knx_CB_param[MAX_KNX_CB] Type of Output (set relay, toggle relay, reply sensor value) + +\*********************************************************************************************/ + +#include + +//void KNX_CB_Action(message_t const &msg, void *arg); // Define function (action callback) to be called by the KNX_IP Library + // when an action is requested by another KNX Device + +address_t KNX_physs_addr; // Physical KNX address of this device +address_t KNX_addr; // KNX Address converter variable + +#define KNX_Empty 255 +#define KNX_TEMPERATURE 17 +#define KNX_HUMIDITY 18 +#define KNX_MAX_device_param 18 + +float last_temp; +float last_hum; + +typedef struct __device_parameters +{ + byte type; // PARAMETER_ID. Used as type of GA = relay, button, sensor, etc, (INPUTS) + // used when an action on device triggers a MSG to send on KNX + // Needed because this is the value that the ESP_KNX_IP library will pass as parameter + // to identify the action to perform when a MSG is received + + bool show; // HARDWARE related. to identify if the parameter exists on the device. + + bool last_state; // LAST_STATE of relays + + callback_id_t CB_id; // ACTION_ID. To store the ID value of Registered_CB to the library. + // The ESP_KNX_IP requires to register the callbacks, and then, to assign an address to the registered callback + // So CB_id is needed to store the ID of the callback to then, assign multiple addresses to the same ID (callback) + // It is used as type of CB = set relay, toggle relay, reply sensor, etc, (OUTPUTS) + // used when a MSG receive KNX triggers an action on the device + // - Multiples address to the same callback (i.e. Set Relay 1 Status) are used on scenes for example +} device_parameters_t; + +// device parameters (information that can be sent) +device_parameters_t device_param[] = { + { 1, false, false, KNX_Empty }, // device_param[ 0] = Relay 1 + { 2, false, false, KNX_Empty }, // device_param[ 1] = Relay 2 + { 3, false, false, KNX_Empty }, // device_param[ 2] = Relay 3 + { 4, false, false, KNX_Empty }, // device_param[ 3] = Relay 4 + { 5, false, false, KNX_Empty }, // device_param[ 4] = Relay 5 + { 6, false, false, KNX_Empty }, // device_param[ 5] = Relay 6 + { 7, false, false, KNX_Empty }, // device_param[ 6] = Relay 7 + { 8, false, false, KNX_Empty }, // device_param[ 7] = Relay 8 + { 9, false, false, KNX_Empty }, // device_param[ 8] = Button 1 + { 10, false, false, KNX_Empty }, // device_param[ 9] = Button 2 + { 11, false, false, KNX_Empty }, // device_param[10] = Button 3 + { 12, false, false, KNX_Empty }, // device_param[11] = Button 4 + { 13, false, false, KNX_Empty }, // device_param[12] = Button 5 + { 14, false, false, KNX_Empty }, // device_param[13] = Button 6 + { 15, false, false, KNX_Empty }, // device_param[14] = Button 7 + { 16, false, false, KNX_Empty }, // device_param[15] = Button 8 + { KNX_TEMPERATURE, false, false, KNX_Empty }, // device_param[16] = Temperature + { KNX_HUMIDITY , false, false, KNX_Empty }, // device_param[17] = humidity + { KNX_Empty, false, false, KNX_Empty} +}; + +// device parameters (information that can be sent) +const char * device_param_ga[] = { + D_SENSOR_RELAY " 1", // Relay 1 + D_SENSOR_RELAY " 2", // Relay 2 + D_SENSOR_RELAY " 3", // Relay 3 + D_SENSOR_RELAY " 4", // Relay 4 + D_SENSOR_RELAY " 5", // Relay 5 + D_SENSOR_RELAY " 6", // Relay 6 + D_SENSOR_RELAY " 7", // Relay 7 + D_SENSOR_RELAY " 8", // Relay 8 + D_SENSOR_BUTTON " 1", // Button 1 + D_SENSOR_BUTTON " 2", // Button 2 + D_SENSOR_BUTTON " 3", // Button 3 + D_SENSOR_BUTTON " 4", // Button 4 + D_SENSOR_BUTTON " 5", // Button 5 + D_SENSOR_BUTTON " 6", // Button 6 + D_SENSOR_BUTTON " 7", // Button 7 + D_SENSOR_BUTTON " 8", // Button 8 + D_TEMPERATURE , // Temperature + D_HUMIDITY , // Humidity + nullptr +}; + +// device actions (posible actions to be performed on the device) +const char *device_param_cb[] = { + D_SENSOR_RELAY " 1", // Set Relay 1 (1-On or 0-OFF) + D_SENSOR_RELAY " 2", + D_SENSOR_RELAY " 3", + D_SENSOR_RELAY " 4", + D_SENSOR_RELAY " 5", + D_SENSOR_RELAY " 6", + D_SENSOR_RELAY " 7", + D_SENSOR_RELAY " 8", + D_SENSOR_RELAY " 1 " D_BUTTON_TOGGLE, // Relay 1 Toggle (1 or 0 will toggle) + D_SENSOR_RELAY " 2 " D_BUTTON_TOGGLE, + D_SENSOR_RELAY " 3 " D_BUTTON_TOGGLE, + D_SENSOR_RELAY " 4 " D_BUTTON_TOGGLE, + D_SENSOR_RELAY " 5 " D_BUTTON_TOGGLE, + D_SENSOR_RELAY " 6 " D_BUTTON_TOGGLE, + D_SENSOR_RELAY " 7 " D_BUTTON_TOGGLE, + D_SENSOR_RELAY " 8 " D_BUTTON_TOGGLE, + D_REPLY " " D_TEMPERATURE, // Reply Temperature + D_REPLY " " D_HUMIDITY, // Reply Humidity + nullptr +}; + + +byte KNX_GA_Search( byte param, byte start = 0 ) +{ + for (byte i = start; i < Settings.knx_GA_registered; ++i) + { + if ( Settings.knx_GA_param[i] == param ) + { + if ( Settings.knx_GA_addr[i] != 0 ) // Relay has group address set? GA=0/0/0 can not be used as KNX address, so it is used here as a: not set value + { + if ( i >= start ) { return i; } + } + } + } + return KNX_Empty; +} + + +byte KNX_CB_Search( byte param, byte start = 0 ) +{ + for (byte i = start; i < Settings.knx_CB_registered; ++i) + { + if ( Settings.knx_CB_param[i] == param ) + { + if ( Settings.knx_CB_addr[i] != 0 ) + { + if ( i >= start ) { return i; } + } + } + } + return KNX_Empty; +} + + +void KNX_ADD_GA( byte GAop, byte GA_FNUM, byte GA_AREA, byte GA_FDEF ) +{ + // Check if all GA were assigned. If yes-> return + if ( Settings.knx_GA_registered >= MAX_KNX_GA ) { return; } + if ( GA_FNUM == 0 && GA_AREA == 0 && GA_FDEF == 0 ) { return; } + + // Assign a GA to that address + Settings.knx_GA_param[Settings.knx_GA_registered] = GAop; + KNX_addr.ga.area = GA_FNUM; + KNX_addr.ga.line = GA_AREA; + KNX_addr.ga.member = GA_FDEF; + Settings.knx_GA_addr[Settings.knx_GA_registered] = KNX_addr.value; + + Settings.knx_GA_registered++; + + snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_KNX D_ADD " GA #%d: %s " D_TO " %d/%d/%d"), + Settings.knx_GA_registered, + device_param_ga[GAop-1], + GA_FNUM, GA_AREA, GA_FDEF ); + AddLog(LOG_LEVEL_DEBUG); +} + + +void KNX_DEL_GA( byte GAnum ) +{ + + byte dest_offset = 0; + byte src_offset = 0; + byte len = 0; + + // Delete GA + Settings.knx_GA_param[GAnum-1] = 0; + + if (GAnum == 1) + { + // start of array, so delete first entry + src_offset = 1; + // Settings.knx_GA_registered will be 1 in case of only one entry + // Settings.knx_GA_registered will be 2 in case of two entries, etc.. + // so only copy anything, if there is it at least more then one element + len = (Settings.knx_GA_registered - 1); + } + else if (GAnum == Settings.knx_GA_registered) + { + // last element, don't do anything, simply decrement counter + } + else + { + // somewhere in the middle + // need to calc offsets + + // skip all prev elements + dest_offset = GAnum -1 ; // GAnum -1 is equal to how many element are in front of it + src_offset = dest_offset + 1; // start after the current element + len = (Settings.knx_GA_registered - GAnum); + } + + if (len > 0) + { + memmove(Settings.knx_GA_param + dest_offset, Settings.knx_GA_param + src_offset, len * sizeof(byte)); + memmove(Settings.knx_GA_addr + dest_offset, Settings.knx_GA_addr + src_offset, len * sizeof(uint16_t)); + } + + Settings.knx_GA_registered--; + + snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_KNX D_DELETE " GA #%d"), + GAnum ); + AddLog(LOG_LEVEL_DEBUG); +} + + +void KNX_ADD_CB( byte CBop, byte CB_FNUM, byte CB_AREA, byte CB_FDEF ) +{ + // Check if all callbacks were assigned. If yes-> return + if ( Settings.knx_CB_registered >= MAX_KNX_CB ) { return; } + if ( CB_FNUM == 0 && CB_AREA == 0 && CB_FDEF == 0 ) { return; } + + // Check if a CB for CBop was registered on the ESP-KNX-IP Library + if ( device_param[CBop-1].CB_id == KNX_Empty ) + { + // if no, register the CB for CBop + device_param[CBop-1].CB_id = knx.callback_register("", KNX_CB_Action, &device_param[CBop-1]); + // KNX IP Library requires a parameter + // to identify which action was requested on the KNX network + // to be performed on this device (set relay, etc.) + // Is going to be used device_param[j].type that stores the type number (1: relay 1, etc) + } + // Assign a callback to CB address + Settings.knx_CB_param[Settings.knx_CB_registered] = CBop; + KNX_addr.ga.area = CB_FNUM; + KNX_addr.ga.line = CB_AREA; + KNX_addr.ga.member = CB_FDEF; + Settings.knx_CB_addr[Settings.knx_CB_registered] = KNX_addr.value; + + knx.callback_assign( device_param[CBop-1].CB_id, KNX_addr ); + + Settings.knx_CB_registered++; + + snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_KNX D_ADD " CB #%d: %d/%d/%d " D_TO " %s"), + Settings.knx_CB_registered, + CB_FNUM, CB_AREA, CB_FDEF, + device_param_cb[CBop-1] ); + AddLog(LOG_LEVEL_DEBUG); +} + + +void KNX_DEL_CB( byte CBnum ) +{ + byte oldparam = Settings.knx_CB_param[CBnum-1]; + byte dest_offset = 0; + byte src_offset = 0; + byte len = 0; + + // Delete assigment + knx.callback_unassign(CBnum-1); + Settings.knx_CB_param[CBnum-1] = 0; + + if (CBnum == 1) + { + // start of array, so delete first entry + src_offset = 1; + // Settings.knx_CB_registered will be 1 in case of only one entry + // Settings.knx_CB_registered will be 2 in case of two entries, etc.. + // so only copy anything, if there is it at least more then one element + len = (Settings.knx_CB_registered - 1); + } + else if (CBnum == Settings.knx_CB_registered) + { + // last element, don't do anything, simply decrement counter + } + else + { + // somewhere in the middle + // need to calc offsets + + // skip all prev elements + dest_offset = CBnum -1 ; // GAnum -1 is equal to how many element are in front of it + src_offset = dest_offset + 1; // start after the current element + len = (Settings.knx_CB_registered - CBnum); + } + + if (len > 0) + { + memmove(Settings.knx_CB_param + dest_offset, Settings.knx_CB_param + src_offset, len * sizeof(byte)); + memmove(Settings.knx_CB_addr + dest_offset, Settings.knx_CB_addr + src_offset, len * sizeof(uint16_t)); + } + + Settings.knx_CB_registered--; + + // Check if there is no other assigment to that callback. If there is not. delete that callback register + if ( KNX_CB_Search( oldparam ) == KNX_Empty ) { + knx.callback_deregister( device_param[oldparam-1].CB_id ); + device_param[oldparam-1].CB_id = KNX_Empty; + } + + snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_KNX D_DELETE " CB #%d"), CBnum ); + AddLog(LOG_LEVEL_DEBUG); +} + + +bool KNX_CONFIG_NOT_MATCH() +{ + for (int i = 0; i < KNX_MAX_device_param; ++i) + { + if ( !device_param[i].show ) { // device has this parameter ? + // if not, search for all registered group address to this parameter for deletion + if ( KNX_GA_Search(i+1) != KNX_Empty ) { return true; } + if ( (i < 8) || (i > 15) ) // check relays and sensors (i from 8 to 16 are toggle relays parameters) + { + if ( KNX_CB_Search(i+1) != KNX_Empty ) { return true; } + if ( KNX_CB_Search(i+8) != KNX_Empty ) { return true; } + } + } + } + return false; +} + + +void KNXStart() +{ + knx.start(nullptr); + snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_KNX D_START)); + AddLog(LOG_LEVEL_DEBUG); +} + + +void KNX_INIT() +{ + // Check for incompatible config + if (Settings.knx_GA_registered > MAX_KNX_GA) { Settings.knx_GA_registered = MAX_KNX_GA; } + if (Settings.knx_CB_registered > MAX_KNX_CB) { Settings.knx_CB_registered = MAX_KNX_CB; } + + // Set Physical KNX Address of the device + KNX_physs_addr.value = Settings.knx_physsical_addr; + knx.physical_address_set( KNX_physs_addr ); + + // Read Configuration + // Check which relays, buttons and sensors where configured for this device + // and activate options according to the hardware + for (int i = GPIO_REL1; i < GPIO_REL8 + 1; ++i) + { + if (GetUsedInModule(i, my_module.gp.io)) { device_param[i - GPIO_REL1].show = true; } + } + for (int i = GPIO_REL1_INV; i < GPIO_REL8_INV + 1; ++i) + { + if (GetUsedInModule(i, my_module.gp.io)) { device_param[i - GPIO_REL1_INV].show = true; } + } + for (int i = GPIO_SWT1; i < GPIO_SWT4 + 1; ++i) + { + if (GetUsedInModule(i, my_module.gp.io)) { device_param[i - GPIO_SWT1 + 8].show = true; } + } + for (int i = GPIO_KEY1; i < GPIO_KEY4 + 1; ++i) + { + if (GetUsedInModule(i, my_module.gp.io)) { device_param[i - GPIO_KEY1 + 8].show = true; } + } + if (GetUsedInModule(GPIO_DHT11, my_module.gp.io)) { device_param[KNX_TEMPERATURE-1].show = true; } + if (GetUsedInModule(GPIO_DHT22, my_module.gp.io)) { device_param[KNX_TEMPERATURE-1].show = true; } + if (GetUsedInModule(GPIO_SI7021, my_module.gp.io)) { device_param[KNX_TEMPERATURE-1].show = true; } + if (GetUsedInModule(GPIO_DHT11, my_module.gp.io)) { device_param[KNX_HUMIDITY-1].show = true; } + if (GetUsedInModule(GPIO_DHT22, my_module.gp.io)) { device_param[KNX_HUMIDITY-1].show = true; } + if (GetUsedInModule(GPIO_SI7021, my_module.gp.io)) { device_param[KNX_HUMIDITY-1].show = true; } + + // Delete from KNX settings all configuration is not anymore related to this device + if (KNX_CONFIG_NOT_MATCH()) { + Settings.knx_GA_registered = 0; + Settings.knx_CB_registered = 0; + snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_KNX D_DELETE " " D_KNX_PARAMETERS )); + AddLog(LOG_LEVEL_DEBUG); + } + + // Register Group Addresses to listen to + // Search on the settings if there is a group address set for receive KNX messages for the type: device_param[j].type + // If there is, register the group address on the KNX_IP Library to Receive data for Executing Callbacks + byte j; + for (byte i = 0; i < Settings.knx_CB_registered; ++i) + { + j = Settings.knx_CB_param[i]; + if ( j > 0 ) + { + device_param[j-1].CB_id = knx.callback_register("", KNX_CB_Action, &device_param[j-1]); // KNX IP Library requires a parameter + // to identify which action was requested on the KNX network + // to be performed on this device (set relay, etc.) + // Is going to be used device_param[j].type that stores the type number (1: relay 1, etc) + KNX_addr.value = Settings.knx_CB_addr[i]; + knx.callback_assign( device_param[j-1].CB_id, KNX_addr ); + } + } +} + + +void KNX_CB_Action(message_t const &msg, void *arg) +{ + device_parameters_t *chan = (device_parameters_t *)arg; + + if (!(Settings.flag.knx_enabled)) { return; } + + snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_KNX D_RECEIVED_FROM " %d.%d.%d " D_COMMAND " %s: %d " D_TO " %s"), + msg.received_on.ga.area, msg.received_on.ga.line, msg.received_on.ga.member, + (msg.ct == KNX_CT_WRITE) ? D_KNX_COMMAND_WRITE : (msg.ct == KNX_CT_READ) ? D_KNX_COMMAND_READ : D_KNX_COMMAND_OTHER, + msg.data[0], + device_param_cb[(chan->type)-1]); + AddLog(LOG_LEVEL_INFO); + + switch (msg.ct) + { + case KNX_CT_WRITE: + if (chan->type < 9) // Set Relays + { + ExecuteCommandPower(chan->type, msg.data[0]); + } + else if (chan->type < 17) // Toggle Relays + { + ExecuteCommandPower((chan->type) -8, 2); + } + break; + case KNX_CT_READ: + if (chan->type < 9) // reply Relays status + { + knx.answer_1bit(msg.received_on, chan->last_state); + } + else if (chan->type = KNX_TEMPERATURE) // Reply Temperature + { + knx.answer_2byte_float(msg.received_on, last_temp); + } + else if (chan->type = KNX_HUMIDITY) // Reply Humidity + { + knx.answer_2byte_float(msg.received_on, last_hum); + } + break; + } +} + + +void KnxUpdatePowerState(byte device, power_t state) +{ + if (!(Settings.flag.knx_enabled)) { return; } + + device_param[device -1].last_state = bitRead(state, device -1); // power state (on/off) + + // Search all the registered GA that has that output (variable: device) as parameter + byte i = KNX_GA_Search(device); + while ( i != KNX_Empty ) { + KNX_addr.value = Settings.knx_GA_addr[i]; + knx.write_1bit(KNX_addr, device_param[device -1].last_state); + + snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_KNX "%s = %d " D_SENT_TO " %d.%d.%d"), + device_param_ga[device -1], device_param[device -1].last_state, + KNX_addr.ga.area, KNX_addr.ga.line, KNX_addr.ga.member); + AddLog(LOG_LEVEL_INFO); + + i = KNX_GA_Search(device, i + 1); + } +} + + +void KnxSendButtonPower(byte key, byte device, byte state) +{ +// key 0 = button_topic +// key 1 = switch_topic +// state 0 = off +// state 1 = on +// state 2 = toggle +// state 3 = hold +// state 9 = clear retain flag + if (!(Settings.flag.knx_enabled)) { return; } +// if (key) +// { + +// Search all the registered GA that has that output (variable: device) as parameter + byte i = KNX_GA_Search(device + 8); + while ( i != KNX_Empty ) { + KNX_addr.value = Settings.knx_GA_addr[i]; + knx.write_1bit(KNX_addr, !(state == 0)); + + snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_KNX "%s = %d " D_SENT_TO " %d.%d.%d"), + device_param_ga[device + 8], !(state == 0), + KNX_addr.ga.area, KNX_addr.ga.line, KNX_addr.ga.member); + AddLog(LOG_LEVEL_INFO); + + i = KNX_GA_Search(device + 8, i + 1); + } +// } +} + + +void KnxSensor(byte sensor_type, float value) +{ + if (sensor_type == KNX_TEMPERATURE) + { + last_temp = value; + } else if (sensor_type == KNX_HUMIDITY) + { + last_hum = value; + } + + if (!(Settings.flag.knx_enabled)) { return; } + + byte i = KNX_GA_Search(sensor_type); + while ( i != KNX_Empty ) { + KNX_addr.value = Settings.knx_GA_addr[i]; + knx.write_2byte_float(KNX_addr, value); + + snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_KNX "%s " D_SENT_TO " %d.%d.%d "), + device_param_ga[sensor_type -1], + KNX_addr.ga.area, KNX_addr.ga.line, KNX_addr.ga.member); + AddLog(LOG_LEVEL_INFO); + + i = KNX_GA_Search(sensor_type, i+1); + } +} + + +/*********************************************************************************************\ + * Presentation +\*********************************************************************************************/ + +#ifdef USE_WEBSERVER +const char S_CONFIGURE_KNX[] PROGMEM = D_CONFIGURE_KNX; + +const char HTTP_FORM_KNX[] PROGMEM = + "
 " D_KNX_PARAMETERS " " + "
" + "" D_KNX_PHYSICAL_ADDRESS " " + " . " + " . " + "" + "

" D_KNX_PHYSICAL_ADDRESS_NOTE "

" + "" D_KNX_ENABLE "

" + + "
" + "" D_KNX_GROUP_ADDRESS_TO_WRITE "
" + + " / " + " / " + " "; + +const char HTTP_FORM_KNX_ADD_BTN[] PROGMEM = + "

" + "
" D_DOMOTICZ_IDX " {1
" D_DOMOTICZ_UPDATE_TIMER " (" STR(DOMOTICZ_UPDATE_TIMER) ")
"; + +const char HTTP_FORM_KNX_ADD_TABLE_ROW[] PROGMEM = + "" +// ""; + ""; + +const char HTTP_FORM_KNX3[] PROGMEM = + "
{optex} -> GAfnum / GAarea / GAfdef

" + "
" + "" D_KNX_GROUP_ADDRESS_TO_READ "
"; + +const char HTTP_FORM_KNX4[] PROGMEM = + "-> -> "); + page += FPSTR(HTTP_FORM_KNX_GA); + page.replace(F("GAfnum"), F("GA_FNUM")); + page.replace(F("GAarea"), F("GA_AREA")); + page.replace(F("GAfdef"), F("GA_FDEF")); + page.replace(F("GAfnum"), F("GA_FNUM")); + page.replace(F("GAarea"), F("GA_AREA")); + page.replace(F("GAfdef"), F("GA_FDEF")); + page += FPSTR(HTTP_FORM_KNX_ADD_BTN); + page.replace(F("{btnval}"), String(1)); + if (Settings.knx_GA_registered < MAX_KNX_GA) { + page.replace(F("btndis"), F(" ")); + } + else + { + page.replace(F("btndis"), F("disabled")); + } + page.replace(F("fncbtnadd"), F("GAwarning")); + for (byte i = 0; i < Settings.knx_GA_registered ; ++i) + { + if ( Settings.knx_GA_param[i] ) + { + page += FPSTR(HTTP_FORM_KNX_ADD_TABLE_ROW); + page.replace(F("{opval}"), String(i+1)); + page.replace(F("{optex}"), String(device_param_ga[Settings.knx_GA_param[i]-1])); + KNX_addr.value = Settings.knx_GA_addr[i]; + page.replace(F("GAfnum"), String(KNX_addr.ga.area)); + page.replace(F("GAarea"), String(KNX_addr.ga.line)); + page.replace(F("GAfdef"), String(KNX_addr.ga.member)); + } + } + page += FPSTR(HTTP_FORM_KNX3); + page += FPSTR(HTTP_FORM_KNX_GA); + page.replace(F("GAfnum"), F("CB_FNUM")); + page.replace(F("GAarea"), F("CB_AREA")); + page.replace(F("GAfdef"), F("CB_FDEF")); + page.replace(F("GAfnum"), F("CB_FNUM")); + page.replace(F("GAarea"), F("CB_AREA")); + page.replace(F("GAfdef"), F("CB_FDEF")); + page += FPSTR(HTTP_FORM_KNX4); + byte j; + for (byte i = 0; i < KNX_MAX_device_param ; i++) + { + // Check How many Relays are available and add: RelayX and TogleRelayX + if ( (i > 8) && (i < 16) ) { j=i-8; } else { j=i; } + if ( i == 8 ) { j = 0; } + if ( device_param[j].show ) + { + page += FPSTR(HTTP_FORM_KNX_OPT); + page.replace(F("{vop}"), String(device_param[i].type)); + page.replace(F("{nop}"), String(device_param_cb[i])); + } + } + page += F(" "); + page += FPSTR(HTTP_FORM_KNX_ADD_BTN); + page.replace(F("{btnval}"), String(2)); + if (Settings.knx_CB_registered < MAX_KNX_CB) { + page.replace(F("btndis"), F(" ")); + } + else + { + page.replace(F("btndis"), F("disabled")); + } + page.replace(F("fncbtnadd"), F("CBwarning")); + for (byte i = 0; i < Settings.knx_CB_registered ; ++i) + { + if ( Settings.knx_CB_param[i] ) + { + page += FPSTR(HTTP_FORM_KNX_ADD_TABLE_ROW2); + page.replace(F("{opval}"), String(i+1)); + page.replace(F("{optex}"), String(device_param_cb[Settings.knx_CB_param[i]-1])); + KNX_addr.value = Settings.knx_CB_addr[i]; + page.replace(F("GAfnum"), String(KNX_addr.ga.area)); + page.replace(F("GAarea"), String(KNX_addr.ga.line)); + page.replace(F("GAfdef"), String(KNX_addr.ga.member)); + } + } + page += F("
"); + page += F("
"); + page += FPSTR(HTTP_BTN_CONF); + + page.replace( F(""), + F("function GAwarning()" + "{" + "var GA_FNUM = document.getElementById('GA_FNUM');" + "var GA_AREA = document.getElementById('GA_AREA');" + "var GA_FDEF = document.getElementById('GA_FDEF');" + "if ( GA_FNUM != null && GA_FNUM.value == '0' && GA_AREA.value == '0' && GA_FDEF.value == '0' ) {" + "alert('" D_KNX_WARNING "');" + "}" + "}" + "function CBwarning()" + "{" + "var CB_FNUM = document.getElementById('CB_FNUM');" + "var CB_AREA = document.getElementById('CB_AREA');" + "var CB_FDEF = document.getElementById('CB_FDEF');" + "if ( CB_FNUM != null && CB_FNUM.value == '0' && CB_AREA.value == '0' && CB_FDEF.value == '0' ) {" + "alert('" D_KNX_WARNING "');" + "}" + "}" + "") ); + ShowPage(page); + } + +} + + +void KNX_Save_Settings() +{ + String stmp; + address_t KNX_addr; + byte i; + + Settings.flag.knx_enabled = WebServer->hasArg("b1"); + snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_KNX D_ENABLED ": %d "), + Settings.flag.knx_enabled); + AddLog(LOG_LEVEL_DEBUG); + + stmp = WebServer->arg("area"); + KNX_addr.pa.area = stmp.toInt(); + stmp = WebServer->arg("line"); + KNX_addr.pa.line = stmp.toInt(); + stmp = WebServer->arg("member"); + KNX_addr.pa.member = stmp.toInt(); + Settings.knx_physsical_addr = KNX_addr.value; + knx.physical_address_set( KNX_addr ); // Set Physical KNX Address of the device + snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_KNX D_KNX_PHYSICAL_ADDRESS ": %d.%d.%d "), + KNX_addr.pa.area, KNX_addr.pa.line, KNX_addr.pa.member ); + AddLog(LOG_LEVEL_DEBUG); + + snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_KNX "GA: %d"), + Settings.knx_GA_registered ); + AddLog(LOG_LEVEL_DEBUG); + for (i = 0; i < Settings.knx_GA_registered ; ++i) + { + KNX_addr.value = Settings.knx_GA_addr[i]; + snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_KNX "GA #%d: %s " D_TO " %d/%d/%d"), + i+1, device_param_ga[Settings.knx_GA_param[i]-1], + KNX_addr.ga.area, KNX_addr.ga.line, KNX_addr.ga.member ); + AddLog(LOG_LEVEL_DEBUG); + } + + snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_KNX "CB: %d"), + Settings.knx_CB_registered ); + AddLog(LOG_LEVEL_DEBUG); + for (i = 0; i < Settings.knx_CB_registered ; ++i) + { + KNX_addr.value = Settings.knx_CB_addr[i]; + snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_KNX "CB #%d: %d/%d/%d " D_TO " %s"), + i+1, + KNX_addr.ga.area, KNX_addr.ga.line, KNX_addr.ga.member, + device_param_cb[Settings.knx_CB_param[i]-1] ); + AddLog(LOG_LEVEL_DEBUG); + } +} + +#endif // USE_WEBSERVER + + +/*********************************************************************************************\ + * Interface +\*********************************************************************************************/ + +#define XDRV_11 + +boolean Xdrv11(byte function) +{ + boolean result = false; + switch (function) { + case FUNC_INIT: + KNX_INIT(); + break; + case FUNC_LOOP: + knx.loop(); // Process knx events + break; +// case FUNC_COMMAND: +// result = KNXCommand(); +// break; +// case FUNC_SET_POWER: +// break; + } + return result; +} + +#endif // USE_KNX diff --git a/sonoff/xdrv_interface.ino b/sonoff/xdrv_interface.ino index bf65ed4f1..09f056ece 100644 --- a/sonoff/xdrv_interface.ino +++ b/sonoff/xdrv_interface.ino @@ -18,6 +18,10 @@ */ boolean (* const xdrv_func_ptr[])(byte) PROGMEM = { // Driver Function Pointers +#ifdef XDRV_00 + &Xdrv00, +#endif + #ifdef XDRV_01 &Xdrv01, #endif @@ -139,12 +143,14 @@ boolean (* const xdrv_func_ptr[])(byte) PROGMEM = { // Driver Function Pointer const uint8_t xdrv_present = sizeof(xdrv_func_ptr) / sizeof(xdrv_func_ptr[0]); // Number of drivers found -boolean XdrvCommand(char *type, uint16_t index, char *dataBuf, uint16_t data_len, int16_t payload) +boolean XdrvCommand(uint8_t grpflg, char *type, uint16_t index, char *dataBuf, uint16_t data_len, int16_t payload, uint16_t payload16) { // XdrvMailbox.valid = 1; XdrvMailbox.index = index; XdrvMailbox.data_len = data_len; + XdrvMailbox.payload16 = payload16; XdrvMailbox.payload = payload; + XdrvMailbox.grpflg = grpflg; XdrvMailbox.topic = type; XdrvMailbox.data = dataBuf; @@ -173,6 +179,7 @@ boolean XdrvMqttData(char *topicBuf, uint16_t stopicBuf, char *dataBuf, uint16_t * Function call to all xdrv * * FUNC_INIT + * FUNC_LOOP * FUNC_MQTT_SUBSCRIBE * FUNC_MQTT_INIT * return FUNC_MQTT_DATA @@ -189,9 +196,7 @@ boolean XdrvCall(byte Function) for (byte x = 0; x < xdrv_present; x++) { result = xdrv_func_ptr[x](Function); - if (result) { - break; - } + if (result) break; } return result; diff --git a/sonoff/xplg_wemohue.ino b/sonoff/xplg_wemohue.ino index ce189a32c..965fd7483 100644 --- a/sonoff/xplg_wemohue.ino +++ b/sonoff/xplg_wemohue.ino @@ -17,7 +17,7 @@ along with this program. If not, see . */ -#ifdef USE_EMULATION +#if defined(USE_WEBSERVER) && defined(USE_EMULATION) /*********************************************************************************************\ * Belkin WeMo and Philips Hue bridge emulation \*********************************************************************************************/ @@ -266,7 +266,6 @@ void PollUdp() } } -#ifdef USE_WEBSERVER /*********************************************************************************************\ * Wemo web server additions \*********************************************************************************************/ @@ -544,7 +543,7 @@ void HueConfigResponse(String *response) response->replace("{ms", WiFi.subnetMask().toString()); response->replace("{gw", WiFi.gatewayIP().toString()); response->replace("{br", HueBridgeId()); - response->replace("{dt", GetUtcDateAndTime()); + response->replace("{dt", GetDateAndTime(DT_UTC)); response->replace("{id", GetHueUserId()); } @@ -814,6 +813,4 @@ void HandleHueApi(String *path) else if (path->endsWith("/rules")) HueNotImplemented(path); else HueGlobalConfig(path); } -#endif // USE_WEBSERVER -#endif // USE_EMULATION - +#endif // USE_WEBSERVER && USE_EMULATION diff --git a/sonoff/xplg_ws2812.ino b/sonoff/xplg_ws2812.ino index d8d085085..4d6410f90 100644 --- a/sonoff/xplg_ws2812.ino +++ b/sonoff/xplg_ws2812.ino @@ -25,21 +25,29 @@ #include #ifdef USE_WS2812_DMA -#if (USE_WS2812_CTYPE == 1) +#if (USE_WS2812_CTYPE == NEO_GRB) NeoPixelBus *strip = NULL; -#elif (USE_WS2812_CTYPE == 2) +#elif (USE_WS2812_CTYPE == NEO_BRG) + NeoPixelBus *strip = NULL; +#elif (USE_WS2812_CTYPE == NEO_RBG) + NeoPixelBus *strip = NULL; +#elif (USE_WS2812_CTYPE == NEO_RGBW) NeoPixelBus *strip = NULL; -#elif (USE_WS2812_CTYPE == 3) +#elif (USE_WS2812_CTYPE == NEO_GRBW) NeoPixelBus *strip = NULL; #else // USE_WS2812_CTYPE NeoPixelBus *strip = NULL; #endif // USE_WS2812_CTYPE #else // USE_WS2812_DMA -#if (USE_WS2812_CTYPE == 1) +#if (USE_WS2812_CTYPE == NEO_GRB) NeoPixelBus *strip = NULL; -#elif (USE_WS2812_CTYPE == 2) +#elif (USE_WS2812_CTYPE == NEO_BRG) + NeoPixelBus *strip = NULL; +#elif (USE_WS2812_CTYPE == NEO_RBG) + NeoPixelBus *strip = NULL; +#elif (USE_WS2812_CTYPE == NEO_RGBW) NeoPixelBus *strip = NULL; -#elif (USE_WS2812_CTYPE == 3) +#elif (USE_WS2812_CTYPE == NEO_GRBW) NeoPixelBus *strip = NULL; #else // USE_WS2812_CTYPE NeoPixelBus *strip = NULL; @@ -90,7 +98,7 @@ uint8_t ws_show_next = 1; void Ws2812StripShow() { -#if (USE_WS2812_CTYPE > 1) +#if (USE_WS2812_CTYPE > NEO_3LED) RgbwColor c; #else RgbColor c; @@ -102,7 +110,7 @@ void Ws2812StripShow() c.R = ledTable[c.R]; c.G = ledTable[c.G]; c.B = ledTable[c.B]; -#if (USE_WS2812_CTYPE > 1) +#if (USE_WS2812_CTYPE > NEO_3LED) c.W = ledTable[c.W]; #endif strip->SetPixelColor(i, c); @@ -114,9 +122,7 @@ void Ws2812StripShow() int mod(int a, int b) { int ret = a % b; - if (ret < 0) { - ret += b; - } + if (ret < 0) ret += b; return ret; } @@ -124,7 +130,7 @@ int mod(int a, int b) void Ws2812UpdatePixelColor(int position, struct WsColor hand_color, float offset) { -#if (USE_WS2812_CTYPE > 1) +#if (USE_WS2812_CTYPE > NEO_3LED) RgbwColor color; #else RgbColor color; @@ -142,13 +148,15 @@ void Ws2812UpdatePixelColor(int position, struct WsColor hand_color, float offse void Ws2812UpdateHand(int position, uint8_t index) { - if (Settings.flag.ws_clock_reverse) { - position = Settings.light_pixels -position; - } + position = (position + Settings.light_rotation) % Settings.light_pixels; + + if (Settings.flag.ws_clock_reverse) position = Settings.light_pixels -position; WsColor hand_color = { Settings.ws_color[index][WS_RED], Settings.ws_color[index][WS_GREEN], Settings.ws_color[index][WS_BLUE] }; Ws2812UpdatePixelColor(position, hand_color, 1); - uint8_t range = ((Settings.ws_width[index] -1) / 2) +1; + + uint8_t range = 1; + if (index < WS_MARKER) range = ((Settings.ws_width[index] -1) / 2) +1; for (uint8_t h = 1; h < range; h++) { float offset = (float)(range - h) / (float)range; Ws2812UpdatePixelColor(position -h, hand_color, offset); @@ -160,9 +168,15 @@ void Ws2812Clock() { strip->ClearTo(0); // Reset strip int clksize = 60000 / (int)Settings.light_pixels; + Ws2812UpdateHand((RtcTime.second * 1000) / clksize, WS_SECOND); Ws2812UpdateHand((RtcTime.minute * 1000) / clksize, WS_MINUTE); Ws2812UpdateHand(((RtcTime.hour % 12) * (5000 / clksize)) + ((RtcTime.minute * 1000) / (12 * clksize)), WS_HOUR); + if (Settings.ws_color[WS_MARKER][WS_RED] + Settings.ws_color[WS_MARKER][WS_GREEN] + Settings.ws_color[WS_MARKER][WS_BLUE]) { + for (byte i = 0; i < 12; i++) { + Ws2812UpdateHand((i * 5000) / clksize, WS_MARKER); + } + } Ws2812StripShow(); } @@ -199,7 +213,7 @@ void Ws2812Gradient(uint8_t schemenr) * Display a gradient of colors for the current color scheme. * Repeat is the number of repetitions of the gradient (pick a multiple of 2 for smooth looping of the gradient). */ -#if (USE_WS2812_CTYPE > 1) +#if (USE_WS2812_CTYPE > NEO_3LED) RgbwColor c; c.W = 0; #else @@ -207,9 +221,7 @@ void Ws2812Gradient(uint8_t schemenr) #endif ColorScheme scheme = kSchemes[schemenr]; - if (scheme.count < 2) { - return; - } + if (scheme.count < 2) return; uint8_t repeat = kRepeat[Settings.light_width]; // number of scheme.count per ledcount uint16_t range = (uint16_t)ceil((float)Settings.light_pixels / (float)repeat); @@ -249,7 +261,7 @@ void Ws2812Bars(uint8_t schemenr) * Display solid bars of color for the current color scheme. * Width is the width of each bar in pixels/lights. */ -#if (USE_WS2812_CTYPE > 1) +#if (USE_WS2812_CTYPE > NEO_3LED) RgbwColor c; c.W = 0; #else @@ -260,9 +272,7 @@ void Ws2812Bars(uint8_t schemenr) ColorScheme scheme = kSchemes[schemenr]; uint16_t maxSize = Settings.light_pixels / scheme.count; - if (kWidth[Settings.light_width] > maxSize) { - maxSize = 0; - } + if (kWidth[Settings.light_width] > maxSize) maxSize = 0; uint16_t speed = ((Settings.light_speed * 2) -1) * (STATES / 10); uint8_t offset = speed > 0 ? strip_timer_counter / speed : 0; @@ -280,9 +290,7 @@ void Ws2812Bars(uint8_t schemenr) } uint8_t colorIndex = offset % scheme.count; for (i = 0; i < Settings.light_pixels; i++) { - if (maxSize) { - colorIndex = ((i + offset) % (scheme.count * kWidth[Settings.light_width])) / kWidth[Settings.light_width]; - } + if (maxSize) colorIndex = ((i + offset) % (scheme.count * kWidth[Settings.light_width])) / kWidth[Settings.light_width]; c.R = mcolor[colorIndex].red; c.G = mcolor[colorIndex].green; c.B = mcolor[colorIndex].blue; @@ -298,21 +306,29 @@ void Ws2812Bars(uint8_t schemenr) void Ws2812Init() { #ifdef USE_WS2812_DMA -#if (USE_WS2812_CTYPE == 1) +#if (USE_WS2812_CTYPE == NEO_GRB) strip = new NeoPixelBus(WS2812_MAX_LEDS); // For Esp8266, the Pin is omitted and it uses GPIO3 due to DMA hardware use. -#elif (USE_WS2812_CTYPE == 2) +#elif (USE_WS2812_CTYPE == NEO_BRG) + strip = new NeoPixelBus(WS2812_MAX_LEDS); // For Esp8266, the Pin is omitted and it uses GPIO3 due to DMA hardware use. +#elif (USE_WS2812_CTYPE == NEO_RBG) + strip = new NeoPixelBus(WS2812_MAX_LEDS); // For Esp8266, the Pin is omitted and it uses GPIO3 due to DMA hardware use. +#elif (USE_WS2812_CTYPE == NEO_RGBW) strip = new NeoPixelBus(WS2812_MAX_LEDS); // For Esp8266, the Pin is omitted and it uses GPIO3 due to DMA hardware use. -#elif (USE_WS2812_CTYPE == 3) +#elif (USE_WS2812_CTYPE == NEO_GRBW) strip = new NeoPixelBus(WS2812_MAX_LEDS); // For Esp8266, the Pin is omitted and it uses GPIO3 due to DMA hardware use. #else // USE_WS2812_CTYPE strip = new NeoPixelBus(WS2812_MAX_LEDS); // For Esp8266, the Pin is omitted and it uses GPIO3 due to DMA hardware use. #endif // USE_WS2812_CTYPE #else // USE_WS2812_DMA -#if (USE_WS2812_CTYPE == 1) +#if (USE_WS2812_CTYPE == NEO_GRB) strip = new NeoPixelBus(WS2812_MAX_LEDS, pin[GPIO_WS2812]); -#elif (USE_WS2812_CTYPE == 2) +#elif (USE_WS2812_CTYPE == NEO_BRG) + strip = new NeoPixelBus(WS2812_MAX_LEDS, pin[GPIO_WS2812]); +#elif (USE_WS2812_CTYPE == NEO_RBG) + strip = new NeoPixelBus(WS2812_MAX_LEDS, pin[GPIO_WS2812]); +#elif (USE_WS2812_CTYPE == NEO_RGBW) strip = new NeoPixelBus(WS2812_MAX_LEDS, pin[GPIO_WS2812]); -#elif (USE_WS2812_CTYPE == 3) +#elif (USE_WS2812_CTYPE == NEO_GRBW) strip = new NeoPixelBus(WS2812_MAX_LEDS, pin[GPIO_WS2812]); #else // USE_WS2812_CTYPE strip = new NeoPixelBus(WS2812_MAX_LEDS, pin[GPIO_WS2812]); @@ -331,7 +347,7 @@ void Ws2812Clear() void Ws2812SetColor(uint16_t led, uint8_t red, uint8_t green, uint8_t blue, uint8_t white) { -#if (USE_WS2812_CTYPE > 1) +#if (USE_WS2812_CTYPE > NEO_3LED) RgbwColor lcolor; lcolor.W = white; #else @@ -357,7 +373,7 @@ char* Ws2812GetColor(uint16_t led, char* scolor) { uint8_t sl_ledcolor[4]; - #if (USE_WS2812_CTYPE > 1) + #if (USE_WS2812_CTYPE > NEO_3LED) RgbwColor lcolor = strip->GetPixelColor(led -1); sl_ledcolor[3] = lcolor.W; #else diff --git a/sonoff/xsns_01_counter.ino b/sonoff/xsns_01_counter.ino index 68cc418d0..d1cb5da5b 100644 --- a/sonoff/xsns_01_counter.ino +++ b/sonoff/xsns_01_counter.ino @@ -90,9 +90,11 @@ const char HTTP_SNS_COUNTER[] PROGMEM = void CounterShow(boolean json) { + char stemp[10]; char counter[16]; byte dsxflg = 0; + byte header = 0; for (byte i = 0; i < MAX_COUNTERS; i++) { if (pin[GPIO_CNTR1 +i] < 99) { if (bitRead(Settings.pulse_counter_type, i)) { @@ -103,9 +105,15 @@ void CounterShow(boolean json) } if (json) { - snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"" D_JSON_COUNTER "%d\":%s"), mqtt_data, i +1, counter); + if (!header) { + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"COUNTER\":{"), mqtt_data); + stemp[0] = '\0'; + } + header++; + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s%s\"C%d\":%s"), mqtt_data, stemp, i +1, counter); + strcpy(stemp, ","); #ifdef USE_DOMOTICZ - if (1 == dsxflg) { + if ((0 == tele_period) && (1 == dsxflg)) { DomoticzSensor(DZ_COUNT, RtcSettings.pulse_counter[i]); dsxflg++; } @@ -117,6 +125,11 @@ void CounterShow(boolean json) } } } + if (json) { + if (header) { + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s}"), mqtt_data); + } + } } /*********************************************************************************************\ diff --git a/sonoff/xsns_04_snfsc.ino b/sonoff/xsns_04_snfsc.ino index f8c9eeef0..1628e9abf 100644 --- a/sonoff/xsns_04_snfsc.ino +++ b/sonoff/xsns_04_snfsc.ino @@ -120,12 +120,24 @@ void SonoffScShow(boolean json) dtostrfd(h, Settings.flag2.humidity_resolution, humidity); if (json) { - snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"" D_JSON_TEMPERATURE "\":%s,\"" D_JSON_HUMIDITY "\":%s,\"" D_JSON_LIGHT "\":%d,\"" D_JSON_NOISE "\":%d,\"" D_JSON_AIRQUALITY "\":%d"), + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"SonoffSC\":{\"" D_JSON_TEMPERATURE "\":%s,\"" D_JSON_HUMIDITY "\":%s,\"" D_JSON_LIGHT "\":%d,\"" D_JSON_NOISE "\":%d,\"" D_JSON_AIRQUALITY "\":%d}"), mqtt_data, temperature, humidity, sc_value[2], sc_value[3], sc_value[4]); #ifdef USE_DOMOTICZ - DomoticzTempHumSensor(temperature, humidity); - DomoticzSensor(DZ_ILLUMINANCE, sc_value[2]); + if (0 == tele_period) { + DomoticzTempHumSensor(temperature, humidity); + DomoticzSensor(DZ_ILLUMINANCE, sc_value[2]); + DomoticzSensor(DZ_COUNT, sc_value[3]); + DomoticzSensor(DZ_AIRQUALITY, 500 + ((100 - sc_value[4]) * 20)); + } #endif // USE_DOMOTICZ + +#ifdef USE_KNX + if (0 == tele_period) { + KnxSensor(KNX_TEMPERATURE, t); + KnxSensor(KNX_HUMIDITY, h); + } +#endif // USE_KNX + #ifdef USE_WEBSERVER } else { snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_SNS_TEMP, mqtt_data, "", temperature, TempUnit()); diff --git a/sonoff/xsns_05_ds18b20.ino b/sonoff/xsns_05_ds18b20.ino index bec747c45..753fafeca 100644 --- a/sonoff/xsns_05_ds18b20.ino +++ b/sonoff/xsns_05_ds18b20.ino @@ -197,7 +197,7 @@ void Ds18b20Show(boolean json) if(json) { snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"DS18B20\":{\"" D_JSON_TEMPERATURE "\":%s}"), mqtt_data, temperature); #ifdef USE_DOMOTICZ - DomoticzSensor(DZ_TEMP, temperature); + if (0 == tele_period) DomoticzSensor(DZ_TEMP, temperature); #endif // USE_DOMOTICZ #ifdef USE_WEBSERVER } else { @@ -205,6 +205,7 @@ void Ds18b20Show(boolean json) #endif // USE_WEBSERVER } } + Ds18x20Convert(); // Start conversion, takes up to one second } /*********************************************************************************************\ @@ -231,7 +232,6 @@ boolean Xsns05(byte function) #ifdef USE_WEBSERVER case FUNC_WEB_APPEND: Ds18b20Show(0); - Ds18x20Convert(); // Start conversion, takes up to one second break; #endif // USE_WEBSERVER } diff --git a/sonoff/xsns_05_ds18x20.ino b/sonoff/xsns_05_ds18x20.ino index 234c1869b..b99c71298 100644 --- a/sonoff/xsns_05_ds18x20.ino +++ b/sonoff/xsns_05_ds18x20.ino @@ -287,6 +287,8 @@ boolean Ds18x20Read(uint8_t sensor, float &t) { uint8_t data[9]; int8_t sign = 1; + uint16_t temp12 = 0; + int16_t temp14 = 0; float temp9 = 0.0; t = NAN; @@ -315,23 +317,26 @@ boolean Ds18x20Read(uint8_t sensor, float &t) case DS1822_CHIPID: case DS18B20_CHIPID: if (data[4] != 0x7F) { - data[4] = 0x7F; // Set resolution to 12-bit + data[4] = 0x7F; // Set resolution to 12-bit OneWireReset(); OneWireSelect(ds18x20_address[ds18x20_index[sensor]]); OneWireWrite(W1_WRITE_SCRATCHPAD); - OneWireWrite(data[2]); // Th Register - OneWireWrite(data[3]); // Tl Register - OneWireWrite(data[4]); // Configuration Register + OneWireWrite(data[2]); // Th Register + OneWireWrite(data[3]); // Tl Register + OneWireWrite(data[4]); // Configuration Register OneWireSelect(ds18x20_address[ds18x20_index[sensor]]); - OneWireWrite(W1_WRITE_EEPROM); // Save scratchpad to EEPROM + OneWireWrite(W1_WRITE_EEPROM); // Save scratchpad to EEPROM } - case MAX31850_CHIPID: - uint16_t temp12 = (data[1] << 8) + data[0]; + temp12 = (data[1] << 8) + data[0]; if (temp12 > 2047) { temp12 = (~temp12) +1; sign = -1; } - t = ConvertTemp(sign * temp12 * 0.0625); + t = ConvertTemp(sign * temp12 * 0.0625); // Divide by 16 + break; + case MAX31850_CHIPID: + temp14 = (data[1] << 8) + (data[0] & 0xFC); + t = ConvertTemp(temp14 * 0.0625); // Divide by 16 break; } } @@ -375,7 +380,7 @@ void Ds18x20Show(boolean json) snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"%s\":{\"" D_JSON_ID "\":\"%s\",\"" D_JSON_TEMPERATURE "\":%s}"), mqtt_data, stemp, address, temperature); } #ifdef USE_DOMOTICZ - if (domoticz_flag) { + if ((0 == tele_period) && domoticz_flag) { DomoticzSensor(DZ_TEMP, temperature); domoticz_flag = false; } @@ -387,6 +392,7 @@ void Ds18x20Show(boolean json) } } } + Ds18x20Convert(); // Start conversion, takes up to one second } /*********************************************************************************************\ @@ -404,11 +410,6 @@ boolean Xsns05(byte function) case FUNC_INIT: Ds18x20Init(); break; -// case FUNC_EVERY_SECOND: -// if ((Settings.tele_period - tele_period) &3 == 3) { -// Ds18x20Convert(); // Start conversion every four seconds, takes up to one second -// } -// break; case FUNC_PREP_BEFORE_TELEPERIOD: Ds18x20Convert(); // Start conversion, takes up to one second break; @@ -418,7 +419,6 @@ boolean Xsns05(byte function) #ifdef USE_WEBSERVER case FUNC_WEB_APPEND: Ds18x20Show(0); - Ds18x20Convert(); // Start conversion, takes up to one second break; #endif // USE_WEBSERVER } diff --git a/sonoff/xsns_05_ds18x20_legacy.ino b/sonoff/xsns_05_ds18x20_legacy.ino index cf083d766..885ce7540 100644 --- a/sonoff/xsns_05_ds18x20_legacy.ino +++ b/sonoff/xsns_05_ds18x20_legacy.ino @@ -103,6 +103,8 @@ boolean Ds18x20Read(uint8_t sensor, float &t) { byte data[12]; int8_t sign = 1; + uint16_t temp12 = 0; + int16_t temp14 = 0; float temp9 = 0.0; uint8_t present = 0; @@ -117,7 +119,7 @@ boolean Ds18x20Read(uint8_t sensor, float &t) } if (OneWire::crc8(data, 8) == data[8]) { switch(ds18x20_address[ds18x20_index[sensor]][0]) { - case DS18S20_CHIPID: // DS18S20 + case DS18S20_CHIPID: if (data[1] > 0x80) { data[0] = (~data[0]) +1; sign = -1; // App-Note fix possible sign error @@ -129,14 +131,17 @@ boolean Ds18x20Read(uint8_t sensor, float &t) } t = ConvertTemp((temp9 - 0.25) + ((16.0 - data[6]) / 16.0)); break; - case DS18B20_CHIPID: // DS18B20 - case MAX31850_CHIPID: // MAX31850 - uint16_t temp12 = (data[1] << 8) + data[0]; + case DS18B20_CHIPID: + temp12 = (data[1] << 8) + data[0]; if (temp12 > 2047) { temp12 = (~temp12) +1; sign = -1; } - t = ConvertTemp(sign * temp12 * 0.0625); + t = ConvertTemp(sign * temp12 * 0.0625); // Divide by 16 + break; + case MAX31850_CHIPID: + temp14 = (data[1] << 8) + (data[0] & 0xFC); + t = ConvertTemp(temp14 * 0.0625); // Divide by 16 break; } } @@ -183,7 +188,7 @@ void Ds18x20Show(boolean json) mqtt_data, stemp, i +1, ds18x20_types, Ds18x20Addresses(i).c_str(), temperature); strcpy(stemp, ","); #ifdef USE_DOMOTICZ - if (1 == dsxflg) { + if ((0 == tele_period) && (1 == dsxflg)) { DomoticzSensor(DZ_TEMP, temperature); } #endif // USE_DOMOTICZ @@ -199,12 +204,9 @@ void Ds18x20Show(boolean json) if (dsxflg) { snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s}"), mqtt_data); } -#ifdef USE_WEBSERVER - } else { - Ds18x20Search(); // Check for changes in sensors number - Ds18x20Convert(); // Start Conversion, takes up to one second -#endif // USE_WEBSERVER } + Ds18x20Search(); // Check for changes in sensors number + Ds18x20Convert(); // Start Conversion, takes up to one second } /*********************************************************************************************\ diff --git a/sonoff/xsns_06_dht.ino b/sonoff/xsns_06_dht.ino index e23d1989f..91a154169 100644 --- a/sonoff/xsns_06_dht.ino +++ b/sonoff/xsns_06_dht.ino @@ -226,11 +226,19 @@ void DhtShow(boolean json) if (json) { snprintf_P(mqtt_data, sizeof(mqtt_data), JSON_SNS_TEMPHUM, mqtt_data, Dht[i].stype, temperature, humidity); #ifdef USE_DOMOTICZ - if (!dsxflg) { + if ((0 == tele_period) && !dsxflg) { DomoticzTempHumSensor(temperature, humidity); dsxflg++; } #endif // USE_DOMOTICZ + +#ifdef USE_KNX + if (0 == tele_period) { + KnxSensor(KNX_TEMPERATURE, t); + KnxSensor(KNX_HUMIDITY, h); + } +#endif // USE_KNX + #ifdef USE_WEBSERVER } else { snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_SNS_TEMP, mqtt_data, Dht[i].stype, temperature, TempUnit()); diff --git a/sonoff/xsns_07_sht1x.ino b/sonoff/xsns_07_sht1x.ino index 6ff557aff..98837471b 100644 --- a/sonoff/xsns_07_sht1x.ino +++ b/sonoff/xsns_07_sht1x.ino @@ -199,8 +199,16 @@ void ShtShow(boolean json) if (json) { snprintf_P(mqtt_data, sizeof(mqtt_data), JSON_SNS_TEMPHUM, mqtt_data, "SHT1X", temperature, humidity); #ifdef USE_DOMOTICZ - DomoticzTempHumSensor(temperature, humidity); + if (0 == tele_period) DomoticzTempHumSensor(temperature, humidity); #endif // USE_DOMOTICZ + +#ifdef USE_KNX + if (0 == tele_period) { + KnxSensor(KNX_TEMPERATURE, t); + KnxSensor(KNX_HUMIDITY, h); + } +#endif // USE_KNX + #ifdef USE_WEBSERVER } else { snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_SNS_TEMP, mqtt_data, "SHT1X", temperature, TempUnit()); diff --git a/sonoff/xsns_08_htu21.ino b/sonoff/xsns_08_htu21.ino index d4d52a6e3..3d9e21d3b 100644 --- a/sonoff/xsns_08_htu21.ino +++ b/sonoff/xsns_08_htu21.ino @@ -262,8 +262,16 @@ void HtuShow(boolean json) if (json) { snprintf_P(mqtt_data, sizeof(mqtt_data), JSON_SNS_TEMPHUM, mqtt_data, htu_types, temperature, humidity); #ifdef USE_DOMOTICZ - DomoticzTempHumSensor(temperature, humidity); + if (0 == tele_period) DomoticzTempHumSensor(temperature, humidity); #endif // USE_DOMOTICZ + +#ifdef USE_KNX + if (0 == tele_period) { + KnxSensor(KNX_TEMPERATURE, t); + KnxSensor(KNX_HUMIDITY, h); + } +#endif // USE_KNX + #ifdef USE_WEBSERVER } else { snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_SNS_TEMP, mqtt_data, htu_types, temperature, TempUnit()); diff --git a/sonoff/xsns_09_bmp.ino b/sonoff/xsns_09_bmp.ino index abfe2e582..e6b4e03fd 100644 --- a/sonoff/xsns_09_bmp.ino +++ b/sonoff/xsns_09_bmp.ino @@ -465,8 +465,21 @@ void BmpShow(boolean json) mqtt_data, bmp_name, temperature, (bmp_model >= 2) ? json_humidity : "", pressure, (Settings.altitude != 0) ? json_sealevel : ""); #endif // USE_BME680 #ifdef USE_DOMOTICZ - DomoticzTempHumPressureSensor(temperature, humidity, pressure); + if (0 == tele_period) { + DomoticzTempHumPressureSensor(temperature, humidity, pressure); +#ifdef USE_BME680 + if (bmp_model >= 3) { DomoticzSensor(DZ_AIRQUALITY, (uint32_t)g); } +#endif // USE_BME680 + } #endif // USE_DOMOTICZ + +#ifdef USE_KNX + if (0 == tele_period) { + KnxSensor(KNX_TEMPERATURE, t); + KnxSensor(KNX_HUMIDITY, h); + } +#endif // USE_KNX + #ifdef USE_WEBSERVER } else { snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_SNS_TEMP, mqtt_data, bmp_name, temperature, TempUnit()); diff --git a/sonoff/xsns_10_bh1750.ino b/sonoff/xsns_10_bh1750.ino index f39833fc4..9c02f02e0 100644 --- a/sonoff/xsns_10_bh1750.ino +++ b/sonoff/xsns_10_bh1750.ino @@ -77,7 +77,7 @@ void Bh1750Show(boolean json) if (json) { snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"BH1750\":{\"" D_JSON_ILLUMINANCE "\":%d}"), mqtt_data, illuminance); #ifdef USE_DOMOTICZ - DomoticzSensor(DZ_ILLUMINANCE, illuminance); + if (0 == tele_period) DomoticzSensor(DZ_ILLUMINANCE, illuminance); #endif // USE_DOMOTICZ #ifdef USE_WEBSERVER } else { diff --git a/sonoff/xsns_11_veml6070.ino b/sonoff/xsns_11_veml6070.ino index aa5dba112..557f615f3 100644 --- a/sonoff/xsns_11_veml6070.ino +++ b/sonoff/xsns_11_veml6070.ino @@ -82,7 +82,7 @@ void Veml6070Show(boolean json) if (json) { snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"VEML6070\":{\"" D_JSON_UV_LEVEL "\":%d}"), mqtt_data, uvlevel); #ifdef USE_DOMOTICZ - DomoticzSensor(DZ_ILLUMINANCE, uvlevel); + if (0 == tele_period) DomoticzSensor(DZ_ILLUMINANCE, uvlevel); #endif // USE_DOMOTICZ #ifdef USE_WEBSERVER } else { diff --git a/sonoff/xsns_12_ads1115.ino b/sonoff/xsns_12_ads1115.ino index 19c3ccf8a..f1279a732 100644 --- a/sonoff/xsns_12_ads1115.ino +++ b/sonoff/xsns_12_ads1115.ino @@ -190,7 +190,7 @@ void Ads1115Show(boolean json) stemp[0] = '\0'; } dsxflg++; - snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s%s\"" D_JSON_ANALOG_INPUT "%d\":%d"), mqtt_data, stemp, i, adc_value); + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s%s\"A%d\":%d"), mqtt_data, stemp, i, adc_value); strcpy(stemp, ","); #ifdef USE_WEBSERVER } else { diff --git a/sonoff/xsns_12_ads1115_i2cdev.ino b/sonoff/xsns_12_ads1115_i2cdev.ino index 692040743..d3748ec7a 100644 --- a/sonoff/xsns_12_ads1115_i2cdev.ino +++ b/sonoff/xsns_12_ads1115_i2cdev.ino @@ -110,7 +110,7 @@ void Ads1115Show(boolean json) stemp[0] = '\0'; } dsxflg++; - snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s%s\"" D_JSON_ANALOG_INPUT "%d\":%d"), mqtt_data, stemp, i, adc_value); + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s%s\"A%d\":%d"), mqtt_data, stemp, i, adc_value); strcpy(stemp, ","); #ifdef USE_WEBSERVER } else { diff --git a/sonoff/xsns_13_ina219.ino b/sonoff/xsns_13_ina219.ino index 8fb4e2f1b..50bcb1642 100644 --- a/sonoff/xsns_13_ina219.ino +++ b/sonoff/xsns_13_ina219.ino @@ -216,8 +216,10 @@ void Ina219Show(boolean json) snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"INA219\":{\"" D_JSON_VOLTAGE "\":%s,\"" D_JSON_CURRENT "\":%s,\"" D_JSON_POWERUSAGE "\":%s}"), mqtt_data, voltage, current, power); #ifdef USE_DOMOTICZ - DomoticzSensor(DZ_VOLTAGE, voltage); - DomoticzSensor(DZ_CURRENT, current); + if (0 == tele_period) { + DomoticzSensor(DZ_VOLTAGE, voltage); + DomoticzSensor(DZ_CURRENT, current); + } #endif // USE_DOMOTICZ #ifdef USE_WEBSERVER } else { diff --git a/sonoff/xsns_14_sht3x.ino b/sonoff/xsns_14_sht3x.ino index 60d35c787..bef289aa3 100644 --- a/sonoff/xsns_14_sht3x.ino +++ b/sonoff/xsns_14_sht3x.ino @@ -20,19 +20,27 @@ #ifdef USE_I2C #ifdef USE_SHT3X /*********************************************************************************************\ - * SHT3X - Temperature and Humidy + * SHT3X and SHTC3 - Temperature and Humidity * - * I2C Address: 0x44 or 0x45 + * I2C Address: 0x44, 0x45 or 0x70 (SHTC3) \*********************************************************************************************/ #define SHT3X_ADDR_GND 0x44 // address pin low (GND) #define SHT3X_ADDR_VDD 0x45 // address pin high (VDD) +#define SHTC3_ADDR 0x70 // address for shtc3 sensor -uint8_t sht3x_type = 0; -uint8_t sht3x_address; -uint8_t sht3x_addresses[] = { SHT3X_ADDR_GND, SHT3X_ADDR_VDD }; +#define SHT3X_MAX_SENSORS 3 -bool Sht3xRead(float &t, float &h) +const char kShtTypes[] PROGMEM = "SHT3X|SHT3X|SHTC3"; +uint8_t sht3x_addresses[] = { SHT3X_ADDR_GND, SHT3X_ADDR_VDD, SHTC3_ADDR }; + +uint8_t sht3x_count = 0; +struct SHT3XSTRUCT { + uint8_t address; // I2C bus address + char types[6]; // Sensor type name and address - "SHT3X-0xXX" +} sht3x_sensors[SHT3X_MAX_SENSORS]; + +bool Sht3xRead(float &t, float &h, uint8_t sht3x_address) { unsigned int data[6]; @@ -40,8 +48,17 @@ bool Sht3xRead(float &t, float &h) h = NAN; Wire.beginTransmission(sht3x_address); - Wire.write(0x2C); // Enable clock stretching - Wire.write(0x06); // High repeatability + if (SHTC3_ADDR == sht3x_address) { + Wire.write(0x35); // Wake from + Wire.write(0x17); // sleep + Wire.endTransmission(); + Wire.beginTransmission(sht3x_address); + Wire.write(0x78); // Disable clock stretching ( I don't think that wire library support clock stretching ) + Wire.write(0x66); // High resolution + } else { + Wire.write(0x2C); // Enable clock stretching + Wire.write(0x06); // High repeatability + } if (Wire.endTransmission() != 0) { // Stop I2C transmission return false; } @@ -59,45 +76,55 @@ bool Sht3xRead(float &t, float &h) void Sht3xDetect() { - if (sht3x_type) { - return; - } + if (sht3x_count) return; float t; float h; - sht3x_type = 1; - for (byte i = 0; i < sizeof(sht3x_addresses); i++) { - sht3x_address = sht3x_addresses[i]; - if (Sht3xRead(t, h)) { - snprintf_P(log_data, sizeof(log_data), S_LOG_I2C_FOUND_AT, "SHT3X", sht3x_address); + for (byte i = 0; i < SHT3X_MAX_SENSORS; i++) { + if (Sht3xRead(t, h, sht3x_addresses[i])) { + sht3x_sensors[sht3x_count].address = sht3x_addresses[i]; + GetTextIndexed(sht3x_sensors[sht3x_count].types, sizeof(sht3x_sensors[sht3x_count].types), i, kShtTypes); + snprintf_P(log_data, sizeof(log_data), S_LOG_I2C_FOUND_AT, sht3x_sensors[sht3x_count].types, sht3x_sensors[sht3x_count].address); AddLog(LOG_LEVEL_DEBUG); - return; + sht3x_count++; } } - sht3x_type = 0; } void Sht3xShow(boolean json) { - if (sht3x_type) { + if (sht3x_count) { float t; float h; - if (Sht3xRead(t, h)) { - char temperature[10]; - char humidity[10]; - dtostrfd(t, Settings.flag2.temperature_resolution, temperature); - dtostrfd(h, Settings.flag2.humidity_resolution, humidity); - - if (json) { - snprintf_P(mqtt_data, sizeof(mqtt_data), JSON_SNS_TEMPHUM, mqtt_data, "SHT3X", temperature, humidity); + char temperature[10]; + char humidity[10]; + char types[11]; + for (byte i = 0; i < sht3x_count; i++) { + if (Sht3xRead(t, h, sht3x_sensors[i].address)) { + dtostrfd(t, Settings.flag2.temperature_resolution, temperature); + dtostrfd(h, Settings.flag2.humidity_resolution, humidity); + snprintf_P(types, sizeof(types), PSTR("%s-0x%02X"), sht3x_sensors[i].types, sht3x_sensors[i].address); // "SHT3X-0xXX" + if (json) { + snprintf_P(mqtt_data, sizeof(mqtt_data), JSON_SNS_TEMPHUM, mqtt_data, types, temperature, humidity); #ifdef USE_DOMOTICZ - DomoticzTempHumSensor(temperature, humidity); + if ((0 == tele_period) && (0 == i)) { // We want the same first sensor to report to Domoticz in case a read is missed + DomoticzTempHumSensor(temperature, humidity); + } #endif // USE_DOMOTICZ + +#ifdef USE_KNX + if (0 == tele_period) { + KnxSensor(KNX_TEMPERATURE, t); + KnxSensor(KNX_HUMIDITY, h); + } +#endif // USE_KNX + #ifdef USE_WEBSERVER - } else { - snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_SNS_TEMP, mqtt_data, "SHT3X", temperature, TempUnit()); - snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_SNS_HUM, mqtt_data, "SHT3X", humidity); + } else { + snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_SNS_TEMP, mqtt_data, types, temperature, TempUnit()); + snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_SNS_HUM, mqtt_data, types, humidity); #endif // USE_WEBSERVER + } } } } diff --git a/sonoff/xsns_15_mhz19.ino b/sonoff/xsns_15_mhz19.ino index 79c427ca9..4cbf88c9e 100644 --- a/sonoff/xsns_15_mhz19.ino +++ b/sonoff/xsns_15_mhz19.ino @@ -158,6 +158,9 @@ void Mhz50ms() mhz_response[counter++] = MhzSerial->read(); } } + + AddLogSerial(LOG_LEVEL_DEBUG_MORE, mhz_response, counter); + if (counter < 9) { // AddLog_P(LOG_LEVEL_DEBUG, PSTR(D_LOG_DEBUG "MH-Z19 comms timeout")); return; @@ -262,7 +265,7 @@ void MhzShow(boolean json) if (json) { snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"%s\":{\"" D_JSON_CO2 "\":%d,\"" D_JSON_TEMPERATURE "\":%s}"), mqtt_data, mhz_types, mhz_last_ppm, temperature); #ifdef USE_DOMOTICZ - DomoticzSensor(DZ_AIRQUALITY, mhz_last_ppm); + if (0 == tele_period) DomoticzSensor(DZ_AIRQUALITY, mhz_last_ppm); #endif // USE_DOMOTICZ #ifdef USE_WEBSERVER } else { diff --git a/sonoff/xsns_16_tsl2561.ino b/sonoff/xsns_16_tsl2561.ino index 79f112dda..6fe09a88f 100644 --- a/sonoff/xsns_16_tsl2561.ino +++ b/sonoff/xsns_16_tsl2561.ino @@ -1,7 +1,7 @@ /* xsns_16_tsl2561.ino - TSL2561 light sensor support for Sonoff-Tasmota - Copyright (C) 2018 Theo Arends + Copyright (C) 2018 Theo Arends and Joachim Banzhaf This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -24,75 +24,62 @@ * * I2C Addresses: 0x29 (low), 0x39 (float) or 0x49 (high) * - * Using library https://github.com/adafruit/TSL2561-Arduino-Library + * Using library https://github.com/joba-1/Joba_Tsl2561 \*********************************************************************************************/ -#include +#include -uint8_t tsl2561_address; -uint8_t tsl2561_addresses[] = { TSL2561_ADDR_LOW, TSL2561_ADDR_FLOAT, TSL2561_ADDR_HIGH }; - -//TSL2561 tsl(TSL2561_ADDR_FLOAT); -TSL2561 *tsl = 0; +Tsl2561 Tsl(Wire); void Tsl2561Detect() { - if (tsl) { - return; - } - - for (byte i = 0; i < sizeof(tsl2561_addresses); i++) { - tsl2561_address = tsl2561_addresses[i]; - if (I2cDevice(tsl2561_address)) { - tsl = new TSL2561(tsl2561_address); - if (tsl->begin()) { - tsl->setGain(TSL2561_GAIN_16X); - tsl->setTiming(TSL2561_INTEGRATIONTIME_101MS); - snprintf_P(log_data, sizeof(log_data), S_LOG_I2C_FOUND_AT, "TSL2561", tsl2561_address); - AddLog(LOG_LEVEL_DEBUG); - break; - } else { - delete tsl; - tsl = 0; - } + if (!Tsl.available()) { + Tsl.begin(); + if (Tsl.available()) { + snprintf_P(log_data, sizeof(log_data), S_LOG_I2C_FOUND_AT, "TSL2561", Tsl.address()); + AddLog(LOG_LEVEL_DEBUG); } } } #ifdef USE_WEBSERVER const char HTTP_SNS_TSL2561[] PROGMEM = - "%s{s}TSL2561 " D_ILLUMINANCE "{m}%d " D_UNIT_LUX "{e}"; // {s} = , {m} = , {e} = + "%s{s}TSL2561 " D_ILLUMINANCE "{m}%u.%03u " D_UNIT_LUX "{e}"; // {s} = , {m} = , {e} = #endif // USE_WEBSERVER void Tsl2561Show(boolean json) { - if (tsl) { - union { - uint32_t full; - struct { uint16_t both, ir; }; - } light; - light.full = tsl->getFullLuminosity(); - uint32_t illuminance = 0; - if ((light.full == 0 || light.full == 0xffffffff)) { - if (!I2cDevice(tsl2561_address)) { - delete tsl; - tsl = 0; - } - } else { - illuminance = tsl->calculateLux(light.both, light.ir); - } - snprintf(log_data, sizeof(log_data), PSTR(D_ILLUMINANCE " 0x%08lx = b 0x%04x, i 0x%04x -> %lu " D_UNIT_LUX), light.full, light.both, light.ir, illuminance); - AddLog(LOG_LEVEL_DEBUG); + uint8_t id; + bool gain; + Tsl2561::exposure_t exposure; + uint16_t scaledFull, scaledIr; + uint32_t full, ir; + uint32_t milliLux; - if (json) { - snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"TSL2561\":{\"" D_JSON_ILLUMINANCE "\":%d}"), mqtt_data, illuminance); + if (Tsl.available()) { + if (Tsl.on()) { + if( Tsl.id(id) + && Tsl2561Util::autoGain(Tsl, gain, exposure, scaledFull, scaledIr) + && Tsl2561Util::normalizedLuminosity(gain, exposure, full = scaledFull, ir = scaledIr) + && Tsl2561Util::milliLux(full, ir, milliLux, Tsl2561::packageCS(id))) { + + snprintf_P(log_data, sizeof(log_data), PSTR(D_ILLUMINANCE " g:%d, e:%d, f:%u, i:%u -> %u.%03u " D_UNIT_LUX), + gain, exposure, full, ir, milliLux/1000, milliLux%1000); + AddLog(LOG_LEVEL_DEBUG); + + if (json) { + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"TSL2561\":{\"" D_JSON_ILLUMINANCE "\":%u.%03u}"), + mqtt_data, milliLux/1000, milliLux%1000); #ifdef USE_DOMOTICZ - DomoticzSensor(DZ_ILLUMINANCE, illuminance); + if (0 == tele_period) DomoticzSensor(DZ_ILLUMINANCE, (milliLux+500)/1000); #endif // USE_DOMOTICZ #ifdef USE_WEBSERVER - } else { - snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_SNS_TSL2561, mqtt_data, illuminance); + } else { + snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_SNS_TSL2561, mqtt_data, milliLux/1000, milliLux%1000); #endif // USE_WEBSERVER + } + } + Tsl.off(); } } } @@ -125,5 +112,5 @@ boolean Xsns16(byte function) return result; } -#endif // USE_TSL2561 -#endif // USE_I2C \ No newline at end of file +#endif // USE_TSL2561_JOBA +#endif // USE_I2C diff --git a/sonoff/xsns_17_senseair.ino b/sonoff/xsns_17_senseair.ino index 86026a1bd..3e938bdea 100644 --- a/sonoff/xsns_17_senseair.ino +++ b/sonoff/xsns_17_senseair.ino @@ -96,6 +96,9 @@ uint8_t ModbusReceive(uint16_t *value) } } } + + AddLogSerial(LOG_LEVEL_DEBUG_MORE, buffer, len); + if (len != sizeof(buffer)) { return 9; // 9 = Unexpected result } @@ -210,7 +213,7 @@ void SenseairShow(boolean json) } snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s}"), mqtt_data); #ifdef USE_DOMOTICZ - DomoticzSensor(DZ_AIRQUALITY, senseair_co2); + if (0 == tele_period) DomoticzSensor(DZ_AIRQUALITY, senseair_co2); #endif // USE_DOMOTICZ #ifdef USE_WEBSERVER } else { diff --git a/sonoff/xsns_18_pms5003.ino b/sonoff/xsns_18_pms5003.ino index ab000eab2..55a3b134e 100644 --- a/sonoff/xsns_18_pms5003.ino +++ b/sonoff/xsns_18_pms5003.ino @@ -56,6 +56,8 @@ boolean PmsReadData() PmsSerial->readBytes(buffer, 32); PmsSerial->flush(); // Make room for another burst + AddLogSerial(LOG_LEVEL_DEBUG_MORE, buffer, 32); + // get checksum ready for (uint8_t i = 0; i < 30; i++) { sum += buffer[i]; @@ -128,6 +130,13 @@ void PmsShow(boolean json) pms_data.pm10_standard, pms_data.pm25_standard, pms_data.pm100_standard, pms_data.pm10_env, pms_data.pm25_env, pms_data.pm100_env, pms_data.particles_03um, pms_data.particles_05um, pms_data.particles_10um, pms_data.particles_25um, pms_data.particles_50um, pms_data.particles_100um); +#ifdef USE_DOMOTICZ + if (0 == tele_period) { + DomoticzSensor(DZ_COUNT, pms_data.pm10_env); // PM1 + DomoticzSensor(DZ_VOLTAGE, pms_data.pm25_env); // PM2.5 + DomoticzSensor(DZ_CURRENT, pms_data.pm100_env); // PM10 + } +#endif // USE_DOMOTICZ #ifdef USE_WEBSERVER } else { snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_PMS5003_SNS, mqtt_data, diff --git a/sonoff/xsns_19_mgs.ino b/sonoff/xsns_19_mgs.ino new file mode 100644 index 000000000..f27b734fd --- /dev/null +++ b/sonoff/xsns_19_mgs.ino @@ -0,0 +1,121 @@ +/* + xsns_19_mgs.ino - Xadow and Grove Mutichannel Gas sensor support for Sonoff-Tasmota + + Copyright (C) 2018 Palich2000 and Theo Arends + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifdef USE_I2C +#ifdef USE_MGS +/*********************************************************************************************\ + * Grove - Multichannel Gas Sensor + * http://wiki.seeed.cc/Grove-Multichannel_Gas_Sensor/ + * + * https://github.com/Seeed-Studio/Mutichannel_Gas_Sensor.git +\*********************************************************************************************/ + +#ifndef MGS_SENSOR_ADDR +#define MGS_SENSOR_ADDR 0x04 // Default Mutichannel Gas sensor i2c address +#endif + +#include "MutichannelGasSensor.h" + +void MGSInit() { + gas.begin(MGS_SENSOR_ADDR); +} + +boolean MGSPrepare() +{ + gas.begin(MGS_SENSOR_ADDR); + if (!gas.isError()) { + snprintf_P(log_data, sizeof(log_data), S_LOG_I2C_FOUND_AT, "MultiGasSensor", MGS_SENSOR_ADDR); + AddLog(LOG_LEVEL_DEBUG); + return true; + } else { + return false; + } +} + +char* measure_gas(int gas_type, char* buffer) +{ + float f = gas.calcGas(gas_type); + dtostrfd(f, 2, buffer); + return buffer; +} + +#ifdef USE_WEBSERVER +const char HTTP_MGS_GAS[] PROGMEM = "%s{s}MGS %s{m}%s " D_UNIT_PARTS_PER_MILLION "{e}"; // {s} = , {m} = , {e} = +#endif // USE_WEBSERVER + +void MGSShow(boolean json) +{ + char buffer[25]; + if (json) { + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"MGS\":{\"NH3\":%s"), mqtt_data, measure_gas(NH3, buffer)); + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"CO\":%s"), mqtt_data, measure_gas(CO, buffer)); + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"NO2\":%s"), mqtt_data, measure_gas(NO2, buffer)); + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"C3H8\":%s"), mqtt_data, measure_gas(C3H8, buffer)); + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"C4H10\":%s"), mqtt_data, measure_gas(C4H10, buffer)); + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"CH4\":%s"), mqtt_data, measure_gas(GAS_CH4, buffer)); + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"H2\":%s"), mqtt_data, measure_gas(H2, buffer)); + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"C2H5OH\":%s}"), mqtt_data, measure_gas(C2H5OH, buffer)); +#ifdef USE_WEBSERVER + } else { + snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_MGS_GAS, mqtt_data, "NH3", measure_gas(NH3, buffer)); + snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_MGS_GAS, mqtt_data, "CO", measure_gas(CO, buffer)); + snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_MGS_GAS, mqtt_data, "NO2", measure_gas(NO2, buffer)); + snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_MGS_GAS, mqtt_data, "C3H8", measure_gas(C3H8, buffer)); + snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_MGS_GAS, mqtt_data, "C4H10", measure_gas(C4H10, buffer)); + snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_MGS_GAS, mqtt_data, "CH4", measure_gas(GAS_CH4, buffer)); + snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_MGS_GAS, mqtt_data, "H2", measure_gas(H2, buffer)); + snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_MGS_GAS, mqtt_data, "C2H5OH", measure_gas(C2H5OH, buffer)); +#endif // USE_WEBSERVER + } +} + +/*********************************************************************************************\ + * Interface +\*********************************************************************************************/ + +#define XSNS_19 + +boolean Xsns19(byte function) +{ + boolean result = false; + static int detected = false; + + if (i2c_flg) { + switch (function) { + case FUNC_INIT: +// MGSInit(); + break; + case FUNC_PREP_BEFORE_TELEPERIOD: + detected = MGSPrepare(); + break; + case FUNC_JSON_APPEND: + if (detected) MGSShow(1); + break; +#ifdef USE_WEBSERVER + case FUNC_WEB_APPEND: + if (detected) MGSShow(0); + break; +#endif // USE_WEBSERVER + } + } + return result; +} + +#endif // USE_MGS +#endif // USE_I2C diff --git a/sonoff/xsns_20_novasds.ino b/sonoff/xsns_20_novasds.ino new file mode 100644 index 000000000..5c38ff0f5 --- /dev/null +++ b/sonoff/xsns_20_novasds.ino @@ -0,0 +1,155 @@ +/* + xsns_20_novasds.ino - Nova SDS011/SDS021 particle concentration sensor support for Sonoff-Tasmota + + Copyright (C) 2018 Theo Arends + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifdef USE_NOVA_SDS +/*********************************************************************************************\ + * Nova Fitness SDS011 (and possibly SDS021) particle concentration sensor + * For background information see http://aqicn.org/sensor/sds011/ +\*********************************************************************************************/ + +#include + +TasmotaSerial *NovaSdsSerial; + +uint8_t novasds_type = 1; +uint8_t novasds_valid = 0; + +struct sds011data { + uint16_t pm100; + uint16_t pm25; +} novasds_data; + +bool NovaSdsReadData() +{ + if (! NovaSdsSerial->available()) return false; + + while ((NovaSdsSerial->peek() != 0xAA) && NovaSdsSerial->available()) { + NovaSdsSerial->read(); + } + + byte d[8] = { 0 }; + NovaSdsSerial->read(); // skip 0xAA + NovaSdsSerial->readBytes(d, 8); + NovaSdsSerial->flush(); + + AddLogSerial(LOG_LEVEL_DEBUG_MORE, d, 8); + + if (d[7] == ((d[1] + d[2] + d[3] + d[4] + d[5] + d[6]) & 0xFF)) { + novasds_data.pm25 = (d[1] + 256 * d[2]); + novasds_data.pm100 = (d[3] + 256 * d[4]); + } else { + AddLog_P(LOG_LEVEL_DEBUG, PSTR("SDS: " D_CHECKSUM_FAILURE)); + return false; + } + + novasds_valid = 10; + + return true; +} + +/*********************************************************************************************/ + +void NovaSdsSecond() // Every second +{ + if (NovaSdsReadData()) { + novasds_valid = 10; + } else { + if (novasds_valid) { + novasds_valid--; + } + } +} + +/*********************************************************************************************/ + +void NovaSdsInit() +{ + novasds_type = 0; + + if (pin[GPIO_SDS0X1] < 99) { + NovaSdsSerial = new TasmotaSerial(pin[GPIO_SDS0X1], -1); + if (NovaSdsSerial->begin()) { + novasds_type = 1; + } + } +} + +#ifdef USE_WEBSERVER +const char HTTP_SDS0X1_SNS[] PROGMEM = "%s" + "{s}SDS0X1 " D_ENVIRONMENTAL_CONCENTRATION " 2.5 " D_UNIT_MICROMETER "{m}%s " D_UNIT_MICROGRAM_PER_CUBIC_METER "{e}" + "{s}SDS0X1 " D_ENVIRONMENTAL_CONCENTRATION " 10 " D_UNIT_MICROMETER "{m}%s " D_UNIT_MICROGRAM_PER_CUBIC_METER "{e}"; // {s} = , {m} = , {e} = +#endif // USE_WEBSERVER + +void NovaSdsShow(boolean json) +{ + if (novasds_valid) { + char pm10[10]; + char pm2_5[10]; + float pm10f = (float)(novasds_data.pm100) / 10.0f; + float pm2_5f = (float)(novasds_data.pm25) / 10.0f; + dtostrfd(pm10f, 1, pm10); + dtostrfd(pm2_5f, 1, pm2_5); + if (json) { + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"SDS0X1\":{\"PM2.5\":%s,\"PM10\":%s}"), mqtt_data, pm2_5, pm10); +#ifdef USE_DOMOTICZ + if (0 == tele_period) { + DomoticzSensor(DZ_VOLTAGE, pm2_5); // PM2.5 + DomoticzSensor(DZ_CURRENT, pm10); // PM10 + } +#endif // USE_DOMOTICZ +#ifdef USE_WEBSERVER + } else { + snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_SDS0X1_SNS, mqtt_data, pm2_5, pm10); +#endif // USE_WEBSERVER + } + } +} + +/*********************************************************************************************\ + * Interface +\*********************************************************************************************/ + +#define XSNS_20 + +boolean Xsns20(byte function) +{ + boolean result = false; + + if (novasds_type) { + switch (function) { + case FUNC_INIT: + NovaSdsInit(); + break; + case FUNC_EVERY_SECOND: + NovaSdsSecond(); + break; + case FUNC_JSON_APPEND: + NovaSdsShow(1); + break; +#ifdef USE_WEBSERVER + case FUNC_WEB_APPEND: + NovaSdsShow(0); + break; +#endif // USE_WEBSERVER + } + } + return result; +} + +#endif // USE_NOVA_SDS \ No newline at end of file diff --git a/sonoff/xsns_21_sgp30.ino b/sonoff/xsns_21_sgp30.ino new file mode 100644 index 000000000..d30281155 --- /dev/null +++ b/sonoff/xsns_21_sgp30.ino @@ -0,0 +1,116 @@ +/* + xsns_21_sgp30.ino - SGP30 gas and air quality sensor support for Sonoff-Tasmota + + Copyright (C) 2018 Theo Arends + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifdef USE_I2C +#ifdef USE_SGP30 +/*********************************************************************************************\ + * SGP30 - Gas (TVOC - Total Volatile Organic Compounds) and Air Quality (CO2) + * + * Source: Gerhard Mutz and Adafruit Industries + * + * I2C Address: 0x58 +\*********************************************************************************************/ + +#include "Adafruit_SGP30.h" +Adafruit_SGP30 sgp; + +uint8_t sgp30_type = 0; +uint8_t sgp30_ready = 0; +uint8_t sgp30_counter = 0; + +/********************************************************************************************/ + +void Sgp30Update() // Perform every second to ensure proper operation of the baseline compensation algorithm +{ + sgp30_ready = 0; + if (!sgp30_type) { + if (sgp.begin()) { + sgp30_type = 1; +// snprintf_P(log_data, sizeof(log_data), PSTR("SGP: Serialnumber 0x%04X-0x%04X-0x%04X"), sgp.serialnumber[0], sgp.serialnumber[1], sgp.serialnumber[2]); +// AddLog(LOG_LEVEL_DEBUG); + snprintf_P(log_data, sizeof(log_data), S_LOG_I2C_FOUND_AT, "SGP30", 0x58); + AddLog(LOG_LEVEL_DEBUG); + } + } else { + if (!sgp.IAQmeasure()) return; // Measurement failed + sgp30_counter++; + if (30 == sgp30_counter) { + sgp30_counter = 0; + + uint16_t TVOC_base; + uint16_t eCO2_base; + + if (!sgp.getIAQBaseline(&eCO2_base, &TVOC_base)) return; // Failed to get baseline readings +// snprintf_P(log_data, sizeof(log_data), PSTR("SGP: Baseline values eCO2 0x%04X, TVOC 0x%04X"), eCO2_base, TVOC_base); +// AddLog(LOG_LEVEL_DEBUG); + } + sgp30_ready = 1; + } +} + +const char HTTP_SNS_SGP30[] PROGMEM = "%s" + "{s}SGP30 " D_ECO2 "{m}%d " D_UNIT_PARTS_PER_MILLION "{e}" // {s} = , {m} = , {e} = + "{s}SGP30 " D_TVOC "{m}%d " D_UNIT_PARTS_PER_BILLION "{e}"; + +void Sgp30Show(boolean json) +{ + if (sgp30_ready) { + if (json) { + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"SGP30\":{\"" D_JSON_ECO2 "\":%d,\"" D_JSON_TVOC "\":%d}"), mqtt_data, sgp.eCO2, sgp.TVOC); +#ifdef USE_DOMOTICZ + if (0 == tele_period) DomoticzSensor(DZ_AIRQUALITY, sgp.eCO2); +#endif // USE_DOMOTICZ + } else { +#ifdef USE_WEBSERVER + snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_SNS_SGP30, mqtt_data, sgp.eCO2, sgp.TVOC); +#endif + } + } +} + +/*********************************************************************************************\ + * Interface +\*********************************************************************************************/ + +#define XSNS_21 + +boolean Xsns21(byte function) +{ + boolean result = false; + + if (i2c_flg) { + switch (function) { + case FUNC_EVERY_SECOND: + Sgp30Update(); + break; + case FUNC_JSON_APPEND: + Sgp30Show(1); + break; +#ifdef USE_WEBSERVER + case FUNC_WEB_APPEND: + Sgp30Show(0); + break; +#endif // USE_WEBSERVER + } + } + return result; +} + +#endif // USE_SGP30 +#endif // USE_I2C \ No newline at end of file diff --git a/sonoff/xsns_22_sr04.ino b/sonoff/xsns_22_sr04.ino new file mode 100644 index 000000000..59781cb0e --- /dev/null +++ b/sonoff/xsns_22_sr04.ino @@ -0,0 +1,175 @@ +/* + xsns_22_sr04.ino - SR04 ultrasonic sensor support for Sonoff-Tasmota + + Copyright (C) 2018 Nuno Ferreira and Theo Arends + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifdef USE_SR04 +/*********************************************************************************************\ + * HC-SR04, HC-SR04+, JSN-SR04T - Ultrasonic distance sensor + * + * Code for SR04 family of ultrasonic distance sensors + * References: + * - https://www.dfrobot.com/wiki/index.php/Weather-proof_Ultrasonic_Sensor_SKU_:_SEN0207 +\*********************************************************************************************/ +#define max(a,b) ((a)>(b)?(a):(b)) +#define min(a,b) ((a)<(b)?(a):(b)) + +uint8_t sr04_echo_pin = 0; +uint8_t sr04_trig_pin = 0; + +/*********************************************************************************************\ + * Embedded stripped and tuned NewPing library from Tim Eckel - teckel@leethost.com + * https://bitbucket.org/teckel12/arduino-new-ping +\*********************************************************************************************/ +#define US_ROUNDTRIP_CM 58 // Microseconds (uS) it takes sound to travel round-trip 1cm (2cm total), uses integer to save compiled code space. Default: 58 +#define US_ROUNDTRIP_IN 148 // Microseconds (uS) it takes sound to travel round-trip 1 inch (2 inches total), uses integer to save compiled code space. Default: 148 +#define PING_MEDIAN_DELAY 29000 +#define MAX_SENSOR_DISTANCE 500 +#define PING_OVERHEAD 5 + +// Conversion from uS to distance (round result to nearest cm or inch). +#define EchoConvert(echoTime, conversionFactor) (max(((unsigned int)echoTime + conversionFactor / 2) / conversionFactor, (echoTime ? 1 : 0))) + +/********************************************************************************************/ + +void Sr04Init() +{ + sr04_echo_pin = pin[GPIO_SR04_ECHO]; + sr04_trig_pin = pin[GPIO_SR04_TRIG]; + pinMode(sr04_trig_pin, OUTPUT); + pinMode(sr04_echo_pin, INPUT_PULLUP); +} + +boolean Sr04Read(uint16_t *distance) +{ + uint16_t duration = 0; + + *distance = 0; + + /* Send ping and get delay */ + duration = Sr04GetSamples(9, 250); + + /* Calculate the distance (in cm) based on the speed of sound. */ + *distance = EchoConvert(duration, US_ROUNDTRIP_CM); + + return 1; +} + +uint16_t Sr04Ping(uint16_t max_cm_distance) +{ + uint16_t duration = 0; + uint16_t maxEchoTime; + + maxEchoTime = min(max_cm_distance + 1, (uint16_t) MAX_SENSOR_DISTANCE + 1) * US_ROUNDTRIP_CM; + + /* The following trigPin/echoPin cycle is used to determine the + distance of the nearest object by bouncing soundwaves off of it. */ + digitalWrite(sr04_trig_pin, LOW); + delayMicroseconds(2); + digitalWrite(sr04_trig_pin, HIGH); + delayMicroseconds(10); + digitalWrite(sr04_trig_pin, LOW); + + /* Wait for the echo */ + duration = pulseIn(sr04_echo_pin, HIGH, 26000) - PING_OVERHEAD; + + return (duration > maxEchoTime) ? 0 : duration; +} + +uint16_t Sr04GetSamples(uint8_t it, uint16_t max_cm_distance) +{ + uint16_t uS[it]; + uint16_t last; + uint8_t j; + uint8_t i = 0; + uint16_t t; + uS[0] = 0; + + while (i < it) { + t = micros(); + last = Sr04Ping(max_cm_distance); + + if (last != 0) { + if (i > 0) { + for (j = i; j > 0 && uS[j - 1] < last; j--) { + uS[j] = uS[j - 1]; + } + } else { + j = 0; + } + uS[j] = last; + i++; + } else { + it--; + } + if (i < it && micros() - t < PING_MEDIAN_DELAY) { + delay((PING_MEDIAN_DELAY + t - micros()) / 1000); + } + } + + return (uS[1]); // Return the ping distance from the 2nd highest reading +} + +#ifdef USE_WEBSERVER +const char HTTP_SNS_DISTANCE[] PROGMEM = + "%s{s}SR04 " D_DISTANCE "{m}%d" D_UNIT_CENTIMETER "{e}"; // {s} = , {m} = , {e} = +#endif // USE_WEBSERVER + +void Sr04Show(boolean json) +{ + uint16_t distance; + + if (Sr04Read(&distance)) { // Check if read failed + if(json) { + snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"SR04\":{\"" D_JSON_DISTANCE "\":%d}"), mqtt_data, distance); +#ifdef USE_WEBSERVER + } else { + snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_SNS_DISTANCE, mqtt_data, distance); +#endif // USE_WEBSERVER + } + } +} + +/*********************************************************************************************\ + * Interface +\*********************************************************************************************/ + +#define XSNS_22 + +boolean Xsns22(byte function) +{ + boolean result = false; + + if ((pin[GPIO_SR04_ECHO] < 99) && (pin[GPIO_SR04_TRIG] < 99)) { + switch (function) { + case FUNC_INIT: + Sr04Init(); + break; + case FUNC_JSON_APPEND: + Sr04Show(1); + break; +#ifdef USE_WEBSERVER + case FUNC_WEB_APPEND: + Sr04Show(0); + break; +#endif // USE_WEBSERVER + } + } + return result; +} + +#endif // USE_SR04 diff --git a/sonoff/xsns_interface.ino b/sonoff/xsns_interface.ino index 02e380a95..19cd86bb3 100644 --- a/sonoff/xsns_interface.ino +++ b/sonoff/xsns_interface.ino @@ -186,6 +186,7 @@ boolean (* const xsns_func_ptr[])(byte) PROGMEM = { // Sensor Function Pointers }; const uint8_t xsns_present = sizeof(xsns_func_ptr) / sizeof(xsns_func_ptr[0]); // Number of External Sensors found +uint8_t xsns_index = 0; /*********************************************************************************************\ * Function call to all xsns @@ -200,15 +201,25 @@ const uint8_t xsns_present = sizeof(xsns_func_ptr) / sizeof(xsns_func_ptr[0]); * FUNC_EVERY_50_MSECOND \*********************************************************************************************/ +uint8_t XsnsPresent() +{ + return xsns_present; +} + +boolean XsnsNextCall(byte Function) +{ + xsns_index++; + if (xsns_index == xsns_present) xsns_index = 0; + return xsns_func_ptr[xsns_index](Function); +} + boolean XsnsCall(byte Function) { boolean result = false; for (byte x = 0; x < xsns_present; x++) { result = xsns_func_ptr[x](Function); - if (result) { - break; - } + if (result) break; } return result;