From 7c857b0feb5178595301040d8b25a1fc808c9a50 Mon Sep 17 00:00:00 2001 From: Luis Teixeira Date: Wed, 4 Dec 2019 22:51:21 +0000 Subject: [PATCH 01/20] Added the command SerialConfig with the capability of changing the data bits/parity/stop bits setting in the hardware serial port. --- tasmota/i18n.h | 1 + tasmota/language/en-GB.h | 1 + tasmota/language/pt-PT.h | 1 + tasmota/settings.h | 22 ++++++++++++- tasmota/settings.ino | 35 +++++++++++++++++++-- tasmota/support.ino | 62 ++++++++++++++++++++++++++++++++++--- tasmota/support_command.ino | 50 ++++++++++++++++++++++++------ tasmota/tasmota.ino | 4 ++- 8 files changed, 158 insertions(+), 18 deletions(-) diff --git a/tasmota/i18n.h b/tasmota/i18n.h index 5de4b7a1d..65f9887a3 100644 --- a/tasmota/i18n.h +++ b/tasmota/i18n.h @@ -284,6 +284,7 @@ #define D_CMND_I2CDRIVER "I2CDriver" #define D_CMND_SERIALSEND "SerialSend" #define D_CMND_SERIALDELIMITER "SerialDelimiter" +#define D_CMND_SERIALCONFIG "SerialConfig" #define D_CMND_BAUDRATE "Baudrate" #define D_CMND_TEMPLATE "Template" #define D_JSON_NAME "NAME" diff --git a/tasmota/language/en-GB.h b/tasmota/language/en-GB.h index a98087a18..15e880600 100644 --- a/tasmota/language/en-GB.h +++ b/tasmota/language/en-GB.h @@ -190,6 +190,7 @@ #define D_SYSLOG_LOGGING_REENABLED "Syslog logging re-enabled" #define D_SET_BAUDRATE_TO "Set Baudrate to" +#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "Received Topic" #define D_DATA_SIZE "Data Size" #define D_ANALOG_INPUT "Analog" diff --git a/tasmota/language/pt-PT.h b/tasmota/language/pt-PT.h index 46bafdef6..27987acf0 100644 --- a/tasmota/language/pt-PT.h +++ b/tasmota/language/pt-PT.h @@ -190,6 +190,7 @@ #define D_SYSLOG_LOGGING_REENABLED "Registro do Syslog reativado" #define D_SET_BAUDRATE_TO "Ajuste da velocidade para" +#define D_SET_SERIAL_CONFIG_TO "Ajuste do modo da porta série" #define D_RECEIVED_TOPIC "Topico Recebido" #define D_DATA_SIZE "Tamanho de Dados" #define D_ANALOG_INPUT "Entrada Analógica" diff --git a/tasmota/settings.h b/tasmota/settings.h index 554711cad..61359226b 100644 --- a/tasmota/settings.h +++ b/tasmota/settings.h @@ -231,6 +231,26 @@ typedef struct { const uint8_t MAX_TUYA_FUNCTIONS = 16; +/** + * Structure used for holding the hardware serial port settings. + * + * Description of the fields: + * + * baudrate - the baud rate multiplier, which can range from 0 - 15360 (multiply by 300 to obtain the actual baud rate) + * mode - encodes a selection of the main serial port settings. + * + * The mode field can take the following values: + * + * 0 - 7N1 (7 data bits / no parity / 1 stop bit) + * 1 - 7E1 (7 data bits / even parity / 1 stop bit) + * 2 - 8N1 (8 data bits / no parity / 1 stop bit) + * 3 - 8E1 (8 data bits / even parity / 1 stop bit) + */ +typedef struct { + uint16_t baudrate; // the baud rate multiplier, which can range from 0 - 15360 (multiply by 300 to obtain the actual baud rate) + uint8_t mode; // encodes a selection of the main serial port settings: 8E1, 8N1, 7E1 and 7N1 +} SerialCfg; + /* struct SYSCFG { unsigned long cfg_holder; // 000 Pre v6 header @@ -397,7 +417,7 @@ struct SYSCFG { uint8_t web_color[18][3]; // 73E uint16_t display_width; // 774 uint16_t display_height; // 776 - uint16_t baudrate; // 778 + uint16_t serial_config; // 778 - 11 MSB's define the baud rate; 5 LSB's define the serial config (e.g. 8N1). Maps to the SerialCfg struct. uint16_t sbaudrate; // 77A EnergyUsage energy_usage; // 77C // uint32_t drivers[3]; // 794 - 6.5.0.12 replaced by below three entries diff --git a/tasmota/settings.ino b/tasmota/settings.ino index 9ca979b45..3f6621495 100644 --- a/tasmota/settings.ino +++ b/tasmota/settings.ino @@ -670,8 +670,13 @@ void SettingsDefaultSet2(void) // for (uint32_t i = 1; i < MAX_PULSETIMERS; i++) { Settings.pulse_timer[i] = 0; } // Serial - Settings.baudrate = APP_BAUDRATE / 300; + + SerialCfg config = SettingToSerialCfg(Settings.serial_config); + config.baudrate = APP_BAUDRATE / 300; + Settings.serial_config = SerialCfgToSetting(config); + Settings.sbaudrate = SOFT_BAUDRATE / 300; + //Settings.serial_config = SERIAL_8N1; Settings.serial_delimiter = 0xff; Settings.seriallog_level = SERIAL_LOG_LEVEL; @@ -1059,7 +1064,10 @@ void SettingsDelta(void) } } if (Settings.version < 0x06060009) { - Settings.baudrate = Settings.ex_baudrate * 4; + SerialCfg config = SettingToSerialCfg(Settings.serial_config); + config.baudrate = Settings.ex_baudrate * 4; + Settings.serial_config = SerialCfgToSetting(config); + Settings.sbaudrate = Settings.ex_sbaudrate * 4; } if (Settings.version < 0x0606000A) { @@ -1160,3 +1168,26 @@ void SettingsDelta(void) SettingsSave(1); } } + +/* Performs the bitwise operations needed for translating the serial port settings 16-bit word + to the SerialCfg struct: */ +SerialCfg SettingToSerialCfg(uint16_t setting) +{ + SerialCfg serial_config; + + serial_config.baudrate = (uint16_t) (setting >> 2) & 0x3FFF; + serial_config.mode = (uint8_t) (setting) & 0x3; + + return serial_config; +} + +/* Performs the bitwise operations needed for translating from the SerialCfg struct + to the serial port settings 16-bit word: */ +uint16_t SerialCfgToSetting(SerialCfg serial_config) +{ + uint16_t setting; + + setting = (uint16_t) ((uint16_t) (serial_config.baudrate << 2 & 0xFFFC)) | (serial_config.mode & 0x3); + + return setting; +} diff --git a/tasmota/support.ino b/tasmota/support.ino index 55c01b71d..8f1ba2862 100644 --- a/tasmota/support.ino +++ b/tasmota/support.ino @@ -738,16 +738,42 @@ int GetStateNumber(char *state_text) return state_number; } -void SetSerialBaudrate(int baudrate) +void SetSerialConfig(uint8_t mode) { - Settings.baudrate = baudrate / 300; + SerialCfg config = SettingToSerialCfg(Settings.serial_config); + config.mode = mode; + Settings.serial_config = SerialCfgToSetting(config); + + SerialConfig hardware_serial_config = ConvertSettingByteToSerialConfig(mode); + + if (seriallog_level) { + AddLog_P2(LOG_LEVEL_INFO, PSTR(D_LOG_APPLICATION D_SET_SERIAL_CONFIG_TO " %d"), mode); + } + + delay(100); + Serial.flush(); + + Serial.begin(Serial.baudRate(), hardware_serial_config); + delay(10); + Serial.println(); +} + +void SetSerialBaudrate(uint32_t baudrate) +{ + SerialCfg config = SettingToSerialCfg(Settings.serial_config); + config.baudrate = ((baudrate / 300) & 0x3FFF); + Settings.serial_config = SerialCfgToSetting(config); + + SerialConfig hardware_serial_config = ConvertSettingByteToSerialConfig(config.mode); + if (Serial.baudRate() != baudrate) { if (seriallog_level) { AddLog_P2(LOG_LEVEL_INFO, PSTR(D_LOG_APPLICATION D_SET_BAUDRATE_TO " %d"), baudrate); } delay(100); Serial.flush(); - Serial.begin(baudrate, serial_config); + + Serial.begin(baudrate, hardware_serial_config); delay(10); Serial.println(); } @@ -759,7 +785,10 @@ void ClaimSerial(void) AddLog_P(LOG_LEVEL_INFO, PSTR("SNS: Hardware Serial")); SetSeriallog(LOG_LEVEL_NONE); baudrate = Serial.baudRate(); - Settings.baudrate = baudrate / 300; + + SerialCfg config = SettingToSerialCfg(Settings.serial_config); + config.baudrate = baudrate / 300; + Settings.serial_config = SerialCfgToSetting(config); } void SerialSendRaw(char *codes) @@ -1647,3 +1676,28 @@ void AddLogMissed(char *sensor, uint32_t misses) { AddLog_P2(LOG_LEVEL_DEBUG, PSTR("SNS: %s missed %d"), sensor, SENSOR_MAX_MISS - misses); } + +SerialConfig ConvertSettingByteToSerialConfig(uint8_t setting_byte) +{ + SerialConfig hardware_serial_config; + + switch(setting_byte) { + case 0: + hardware_serial_config = SERIAL_7N1; + break; + case 1: + hardware_serial_config = SERIAL_7E1; + break; + case 2: + hardware_serial_config = SERIAL_8N1; + break; + case 3: + hardware_serial_config = SERIAL_8E1; + break; + default: + hardware_serial_config = SERIAL_8N1; + break; + } + + return hardware_serial_config; +} \ No newline at end of file diff --git a/tasmota/support_command.ino b/tasmota/support_command.ino index fe8640045..f0a5ba87d 100644 --- a/tasmota/support_command.ino +++ b/tasmota/support_command.ino @@ -23,10 +23,10 @@ const char kTasmotaCommands[] PROGMEM = "|" // No prefix D_CMND_SETOPTION "|" D_CMND_TEMPERATURE_RESOLUTION "|" D_CMND_HUMIDITY_RESOLUTION "|" D_CMND_PRESSURE_RESOLUTION "|" D_CMND_POWER_RESOLUTION "|" D_CMND_VOLTAGE_RESOLUTION "|" D_CMND_FREQUENCY_RESOLUTION "|" D_CMND_CURRENT_RESOLUTION "|" D_CMND_ENERGY_RESOLUTION "|" D_CMND_WEIGHT_RESOLUTION "|" D_CMND_MODULE "|" D_CMND_MODULES "|" D_CMND_GPIO "|" D_CMND_GPIOS "|" D_CMND_TEMPLATE "|" D_CMND_PWM "|" D_CMND_PWMFREQUENCY "|" D_CMND_PWMRANGE "|" - D_CMND_BUTTONDEBOUNCE "|" D_CMND_SWITCHDEBOUNCE "|" D_CMND_SYSLOG "|" D_CMND_LOGHOST "|" D_CMND_LOGPORT "|" D_CMND_SERIALSEND "|" D_CMND_BAUDRATE "|" - D_CMND_SERIALDELIMITER "|" 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_INTERLOCK "|" D_CMND_TELEPERIOD "|" D_CMND_RESET "|" D_CMND_TIME "|" D_CMND_TIMEZONE "|" D_CMND_TIMESTD "|" - D_CMND_TIMEDST "|" D_CMND_ALTITUDE "|" D_CMND_LEDPOWER "|" D_CMND_LEDSTATE "|" D_CMND_LEDMASK "|" D_CMND_WIFIPOWER "|" D_CMND_TEMPOFFSET "|" + D_CMND_BUTTONDEBOUNCE "|" D_CMND_SWITCHDEBOUNCE "|" D_CMND_SYSLOG "|" D_CMND_LOGHOST "|" D_CMND_LOGPORT "|" D_CMND_SERIALSEND "|" D_CMND_SERIALCONFIG "|" + D_CMND_BAUDRATE "|" D_CMND_SERIALDELIMITER "|" 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_INTERLOCK "|" D_CMND_TELEPERIOD "|" D_CMND_RESET "|" D_CMND_TIME "|" D_CMND_TIMEZONE "|" + D_CMND_TIMESTD "|" D_CMND_TIMEDST "|" D_CMND_ALTITUDE "|" D_CMND_LEDPOWER "|" D_CMND_LEDSTATE "|" D_CMND_LEDMASK "|" D_CMND_WIFIPOWER "|" D_CMND_TEMPOFFSET "|" #ifdef USE_I2C D_CMND_I2CSCAN "|" D_CMND_I2CDRIVER "|" #endif @@ -38,7 +38,7 @@ void (* const TasmotaCommand[])(void) PROGMEM = { &CmndSetoption, &CmndTemperatureResolution, &CmndHumidityResolution, &CmndPressureResolution, &CmndPowerResolution, &CmndVoltageResolution, &CmndFrequencyResolution, &CmndCurrentResolution, &CmndEnergyResolution, &CmndWeightResolution, &CmndModule, &CmndModules, &CmndGpio, &CmndGpios, &CmndTemplate, &CmndPwm, &CmndPwmfrequency, &CmndPwmrange, - &CmndButtonDebounce, &CmndSwitchDebounce, &CmndSyslog, &CmndLoghost, &CmndLogport, &CmndSerialSend, &CmndBaudrate, + &CmndButtonDebounce, &CmndSwitchDebounce, &CmndSyslog, &CmndLoghost, &CmndLogport, &CmndSerialSend, &CmndSerialConfig, &CmndBaudrate, &CmndSerialDelimiter, &CmndIpAddress, &CmndNtpServer, &CmndAp, &CmndSsid, &CmndPassword, &CmndHostname, &CmndWifiConfig, &CmndFriendlyname, &CmndSwitchMode, &CmndInterlock, &CmndTeleperiod, &CmndReset, &CmndTime, &CmndTimezone, &CmndTimeStd, &CmndTimeDst, &CmndAltitude, &CmndLedPower, &CmndLedState, &CmndLedMask, &CmndWifiPower, &CmndTempOffset, @@ -1072,14 +1072,44 @@ void CmndSwitchDebounce(void) ResponseCmndNumber(Settings.switch_debounce); } +/** + * Changes the Serial port number of bits, parity and stop bits. + * For the time being this command only has effect on the hardware + * serial port (GPIO1 and GPIO3) + * + * Meaning of the values: + * + * 0 - 7N1 (7 data bits / no parity / 1 stop bit) + * 1 - 7E1 (7 data bits / even parity / 1 stop bit) + * 2 - 8N1 (8 data bits / no parity / 1 stop bit) + * 3 - 8E1 (8 data bits / even parity / 1 stop bit) + * + */ + +void CmndSerialConfig(void) +{ + // a frugal validation to check if the provided serial port mode is valid: + + if (XdrvMailbox.payload >= 0 && XdrvMailbox.payload <= 3) { + uint8_t mode = (uint8_t) (XdrvMailbox.payload & 3); + + SetSerialConfig(mode); + } + + SerialCfg config = SettingToSerialCfg(Settings.serial_config); + + ResponseCmndNumber(config.mode); +} + void CmndBaudrate(void) { - if (XdrvMailbox.payload >= 300) { - XdrvMailbox.payload /= 300; // Make it a valid baudrate - baudrate = (XdrvMailbox.payload & 0xFFFF) * 300; - SetSerialBaudrate(baudrate); + if (XdrvMailbox.payload >= 300) { + SetSerialBaudrate(XdrvMailbox.payload); } - ResponseCmndNumber(Settings.baudrate * 300); + + SerialCfg config = SettingToSerialCfg(Settings.serial_config); + + ResponseCmndNumber(config.baudrate * 300); } void CmndSerialSend(void) diff --git a/tasmota/tasmota.ino b/tasmota/tasmota.ino index 64a1125c6..e6511eb04 100644 --- a/tasmota/tasmota.ino +++ b/tasmota/tasmota.ino @@ -1535,7 +1535,9 @@ void setup(void) XdrvCall(FUNC_SETTINGS_OVERRIDE); } - baudrate = Settings.baudrate * 300; + SerialCfg config = SettingToSerialCfg(Settings.serial_config); + + baudrate = config.baudrate * 300; // mdns_delayed_start = Settings.param[P_MDNS_DELAYED_START]; seriallog_level = Settings.seriallog_level; seriallog_timer = SERIALLOG_TIMER; From 83f9c7b588f64d74e3d3fec09eb5dd5f9538bfc5 Mon Sep 17 00:00:00 2001 From: Luis Teixeira Date: Wed, 4 Dec 2019 23:03:52 +0000 Subject: [PATCH 02/20] Fixed comment (bits for each field) --- tasmota/settings.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tasmota/settings.h b/tasmota/settings.h index 61359226b..a3f5fd63e 100644 --- a/tasmota/settings.h +++ b/tasmota/settings.h @@ -417,7 +417,7 @@ struct SYSCFG { uint8_t web_color[18][3]; // 73E uint16_t display_width; // 774 uint16_t display_height; // 776 - uint16_t serial_config; // 778 - 11 MSB's define the baud rate; 5 LSB's define the serial config (e.g. 8N1). Maps to the SerialCfg struct. + uint16_t serial_config; // 778 - 14 MSB's define the baud rate; 2 LSB's define the serial config (e.g. 8N1). Maps to the SerialCfg struct. uint16_t sbaudrate; // 77A EnergyUsage energy_usage; // 77C // uint32_t drivers[3]; // 794 - 6.5.0.12 replaced by below three entries From 871fd1f60db02209218037589def86294d3e835c Mon Sep 17 00:00:00 2001 From: Luis Teixeira Date: Thu, 5 Dec 2019 01:18:59 +0000 Subject: [PATCH 03/20] Added the new text field D_SET_SERIAL_CONFIG_TO (used in the logs) to the internationalized resource files. --- tasmota/language/bg-BG.h | 1 + tasmota/language/cs-CZ.h | 1 + tasmota/language/de-DE.h | 1 + tasmota/language/el-GR.h | 1 + tasmota/language/es-ES.h | 1 + tasmota/language/fr-FR.h | 1 + tasmota/language/he-HE.h | 1 + tasmota/language/hu-HU.h | 1 + tasmota/language/it-IT.h | 1 + tasmota/language/ko-KO.h | 1 + tasmota/language/nl-NL.h | 1 + tasmota/language/pl-PL.h | 1 + tasmota/language/pt-BR.h | 1 + tasmota/language/ru-RU.h | 1 + tasmota/language/sk-SK.h | 1 + tasmota/language/sv-SE.h | 1 + tasmota/language/tr-TR.h | 1 + tasmota/language/uk-UK.h | 1 + tasmota/language/zh-CN.h | 1 + tasmota/language/zh-TW.h | 1 + 20 files changed, 20 insertions(+) diff --git a/tasmota/language/bg-BG.h b/tasmota/language/bg-BG.h index 4bc5feebd..10f13b786 100644 --- a/tasmota/language/bg-BG.h +++ b/tasmota/language/bg-BG.h @@ -190,6 +190,7 @@ #define D_SYSLOG_LOGGING_REENABLED "Системният лог активиран" #define D_SET_BAUDRATE_TO "Задаване скорост на предаване (Baudrate)" +#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "Получен топик" #define D_DATA_SIZE "Размер на данните" #define D_ANALOG_INPUT "Аналогов вход" diff --git a/tasmota/language/cs-CZ.h b/tasmota/language/cs-CZ.h index 8800368a3..639a0a184 100644 --- a/tasmota/language/cs-CZ.h +++ b/tasmota/language/cs-CZ.h @@ -190,6 +190,7 @@ #define D_SYSLOG_LOGGING_REENABLED "Obnoven zápis do Syslog" #define D_SET_BAUDRATE_TO "Nastavení rychlosti přenosu na" +#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "Přijatý topic" #define D_DATA_SIZE "Velikost dat" #define D_ANALOG_INPUT "Analogový vstup" diff --git a/tasmota/language/de-DE.h b/tasmota/language/de-DE.h index c50de823f..75bf51435 100644 --- a/tasmota/language/de-DE.h +++ b/tasmota/language/de-DE.h @@ -190,6 +190,7 @@ #define D_SYSLOG_LOGGING_REENABLED "Syslog-Logging aktiviert" #define D_SET_BAUDRATE_TO "Setze Baudrate auf" +#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "empfangenes topic" #define D_DATA_SIZE "Datengröße" #define D_ANALOG_INPUT "Analog" diff --git a/tasmota/language/el-GR.h b/tasmota/language/el-GR.h index 4fe47ae6d..0583c17e8 100644 --- a/tasmota/language/el-GR.h +++ b/tasmota/language/el-GR.h @@ -190,6 +190,7 @@ #define D_SYSLOG_LOGGING_REENABLED "Η καταγραφή Syslog επαναενεργοποιήθηκε" #define D_SET_BAUDRATE_TO "Ορισμός Baudrate σε" +#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "Received Topic" #define D_DATA_SIZE "Μέγεθος δεδομένων" #define D_ANALOG_INPUT "Αναλογικό" diff --git a/tasmota/language/es-ES.h b/tasmota/language/es-ES.h index 014d822a9..7f1ac36d6 100644 --- a/tasmota/language/es-ES.h +++ b/tasmota/language/es-ES.h @@ -190,6 +190,7 @@ #define D_SYSLOG_LOGGING_REENABLED "Syslog re-habilitado" #define D_SET_BAUDRATE_TO "Baudrate a" +#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "Topic Recibido" #define D_DATA_SIZE "Tamaño de Datos" #define D_ANALOG_INPUT "Entrada Analógica" diff --git a/tasmota/language/fr-FR.h b/tasmota/language/fr-FR.h index 4704c49e7..446485462 100644 --- a/tasmota/language/fr-FR.h +++ b/tasmota/language/fr-FR.h @@ -190,6 +190,7 @@ #define D_SYSLOG_LOGGING_REENABLED "Jounalisation SysLog réactivée" #define D_SET_BAUDRATE_TO "Définir le débit à" +#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "Topic reçu" // Terme MQTT #define D_DATA_SIZE "Taille données" #define D_ANALOG_INPUT "Analogique" diff --git a/tasmota/language/he-HE.h b/tasmota/language/he-HE.h index 69387ceca..1c9eed40a 100644 --- a/tasmota/language/he-HE.h +++ b/tasmota/language/he-HE.h @@ -190,6 +190,7 @@ #define D_SYSLOG_LOGGING_REENABLED "הופעל מחדש Syslog רישום" #define D_SET_BAUDRATE_TO "הגדר קצב שידור ל" +#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "Topic התקבל" #define D_DATA_SIZE "גודל נתונים" #define D_ANALOG_INPUT "אנלוגי" diff --git a/tasmota/language/hu-HU.h b/tasmota/language/hu-HU.h index 58f85eb22..f34b2cbb3 100644 --- a/tasmota/language/hu-HU.h +++ b/tasmota/language/hu-HU.h @@ -190,6 +190,7 @@ #define D_SYSLOG_LOGGING_REENABLED "Syslog logolás újraengedélyezve" #define D_SET_BAUDRATE_TO "Baudrate beállítása" +#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "Érkezett topic" #define D_DATA_SIZE "Adatméret" #define D_ANALOG_INPUT "Analóg" diff --git a/tasmota/language/it-IT.h b/tasmota/language/it-IT.h index 3029f37da..5de100fee 100644 --- a/tasmota/language/it-IT.h +++ b/tasmota/language/it-IT.h @@ -190,6 +190,7 @@ #define D_SYSLOG_LOGGING_REENABLED "Syslog ri-abilitato" #define D_SET_BAUDRATE_TO "Baudrate impostato a" +#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "Topic Ricevuto" #define D_DATA_SIZE "Dimensione Dati" #define D_ANALOG_INPUT "Ingresso Analogico" diff --git a/tasmota/language/ko-KO.h b/tasmota/language/ko-KO.h index c6236a05f..65c045f3f 100644 --- a/tasmota/language/ko-KO.h +++ b/tasmota/language/ko-KO.h @@ -190,6 +190,7 @@ #define D_SYSLOG_LOGGING_REENABLED "Syslog log 다시 사용" #define D_SET_BAUDRATE_TO "Set Baudrate to" +#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "Received Topic" #define D_DATA_SIZE "데이터 용량" #define D_ANALOG_INPUT "아날로그" diff --git a/tasmota/language/nl-NL.h b/tasmota/language/nl-NL.h index da20ff1d7..541b9bdc6 100644 --- a/tasmota/language/nl-NL.h +++ b/tasmota/language/nl-NL.h @@ -190,6 +190,7 @@ #define D_SYSLOG_LOGGING_REENABLED "Syslog logging weer ingeschakeld" #define D_SET_BAUDRATE_TO "Zet baudrate op" +#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "Ontvangen topic" #define D_DATA_SIZE "Data lengte" #define D_ANALOG_INPUT "Analoog" diff --git a/tasmota/language/pl-PL.h b/tasmota/language/pl-PL.h index 7a631f95f..dbb7339d3 100644 --- a/tasmota/language/pl-PL.h +++ b/tasmota/language/pl-PL.h @@ -190,6 +190,7 @@ #define D_SYSLOG_LOGGING_REENABLED "Wznowiono zapis do Syslog" #define D_SET_BAUDRATE_TO "Ustaw szybkość transmisji na" +#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "Otrzymany temat" #define D_DATA_SIZE "Wielkość danych" #define D_ANALOG_INPUT "Wejście analogowe" diff --git a/tasmota/language/pt-BR.h b/tasmota/language/pt-BR.h index 2eb81f294..774514152 100644 --- a/tasmota/language/pt-BR.h +++ b/tasmota/language/pt-BR.h @@ -190,6 +190,7 @@ #define D_SYSLOG_LOGGING_REENABLED "Registro do Syslog reativado" #define D_SET_BAUDRATE_TO "Ajuste da velocidade para" +#define D_SET_SERIAL_CONFIG_TO "Ajuste do modo da porta série" #define D_RECEIVED_TOPIC "Tópico recebido" #define D_DATA_SIZE "Tamanho de dados" #define D_ANALOG_INPUT "Entrada analógica" diff --git a/tasmota/language/ru-RU.h b/tasmota/language/ru-RU.h index 5ff9bff50..cd734a575 100644 --- a/tasmota/language/ru-RU.h +++ b/tasmota/language/ru-RU.h @@ -190,6 +190,7 @@ #define D_SYSLOG_LOGGING_REENABLED "Syslog logging включен" #define D_SET_BAUDRATE_TO "Установить скорость передачи (Baudrate)" +#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "Полученный Топик" #define D_DATA_SIZE "Размер данных" #define D_ANALOG_INPUT "Аналоговый вход" diff --git a/tasmota/language/sk-SK.h b/tasmota/language/sk-SK.h index 57ec74f8a..0accdc407 100644 --- a/tasmota/language/sk-SK.h +++ b/tasmota/language/sk-SK.h @@ -190,6 +190,7 @@ #define D_SYSLOG_LOGGING_REENABLED "Obnovený zápis do Syslog" #define D_SET_BAUDRATE_TO "Nastaviť rýchlosti prenosu na" +#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "Prijatý topic" #define D_DATA_SIZE "Veľkosť dát" #define D_ANALOG_INPUT "Analógový vstup" diff --git a/tasmota/language/sv-SE.h b/tasmota/language/sv-SE.h index aee8fd25d..30de42797 100644 --- a/tasmota/language/sv-SE.h +++ b/tasmota/language/sv-SE.h @@ -190,6 +190,7 @@ #define D_SYSLOG_LOGGING_REENABLED "Syslog återaktiverad" #define D_SET_BAUDRATE_TO "Ange Baudrate till" +#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "Mottaget ämne" #define D_DATA_SIZE "Datastorlek" #define D_ANALOG_INPUT "Analog" diff --git a/tasmota/language/tr-TR.h b/tasmota/language/tr-TR.h index 78612dace..cea928af7 100644 --- a/tasmota/language/tr-TR.h +++ b/tasmota/language/tr-TR.h @@ -190,6 +190,7 @@ #define D_SYSLOG_LOGGING_REENABLED "Sistem loglaması tekrar aktif" #define D_SET_BAUDRATE_TO "Baud hızını şu şekilde değiştir" +#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "Alınan Başlık" #define D_DATA_SIZE "Veri Büyüklüğü" #define D_ANALOG_INPUT "Analog" diff --git a/tasmota/language/uk-UK.h b/tasmota/language/uk-UK.h index f16d66648..890c40b9c 100644 --- a/tasmota/language/uk-UK.h +++ b/tasmota/language/uk-UK.h @@ -190,6 +190,7 @@ #define D_SYSLOG_LOGGING_REENABLED "Syslog журнал увімкнений" #define D_SET_BAUDRATE_TO "Встановити швидкість передачі (Baudrate)" +#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "Отриманий Топік" #define D_DATA_SIZE "Розмір даних" #define D_ANALOG_INPUT "Напруга" diff --git a/tasmota/language/zh-CN.h b/tasmota/language/zh-CN.h index 2c8610400..178497a88 100644 --- a/tasmota/language/zh-CN.h +++ b/tasmota/language/zh-CN.h @@ -190,6 +190,7 @@ #define D_SYSLOG_LOGGING_REENABLED "Syslog 日志已开启" #define D_SET_BAUDRATE_TO "设置波特率为:" +#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "接收到的主题:" #define D_DATA_SIZE "数据大小:" #define D_ANALOG_INPUT "Analog" diff --git a/tasmota/language/zh-TW.h b/tasmota/language/zh-TW.h index e5ef8926a..5862f4b5b 100644 --- a/tasmota/language/zh-TW.h +++ b/tasmota/language/zh-TW.h @@ -190,6 +190,7 @@ #define D_SYSLOG_LOGGING_REENABLED "Syslog 日誌已開啟" #define D_SET_BAUDRATE_TO "設置波特率為:" +#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "接收到的主題:" #define D_DATA_SIZE "數據大小:" #define D_ANALOG_INPUT "Analog" From 39088654739c2e42dee504508f3d6bf8462d5682 Mon Sep 17 00:00:00 2001 From: Luis Teixeira Date: Sun, 8 Mar 2020 20:54:28 +0000 Subject: [PATCH 04/20] Added the hdc1080 device driver. --- BUILDS.md | 1 + I2CDEVICES.md | 1 + tasmota/my_user_config.h | 2 + tasmota/support_command.ino | 29 --- tasmota/support_features.ino | 4 + tasmota/tasmota_post.h | 3 + tasmota/xsns_92_hdc1080.ino | 358 +++++++++++++++++++++++++++++++++++ tools/decode-status.py | 2 +- 8 files changed, 370 insertions(+), 30 deletions(-) create mode 100644 tasmota/xsns_92_hdc1080.ino diff --git a/BUILDS.md b/BUILDS.md index 53ebba456..18f25042b 100644 --- a/BUILDS.md +++ b/BUILDS.md @@ -113,6 +113,7 @@ | USE_DHT12 | - | - | - | - | x | - | - | | USE_DS1624 | - | - | - | - | x | - | - | | USE_AHT1x | - | - | - | - | - | - | - | +| USE_HDC1080 | - | - | - | - | - | - | - | | USE_WEMOS_MOTOR_V1 | - | - | - | - | x | - | - | | | | | | | | | | | Feature or Sensor | minimal | lite | tasmota | knx | sensors | ir | display | Remarks diff --git a/I2CDEVICES.md b/I2CDEVICES.md index f9cf5b0e3..2a89ba8aa 100644 --- a/I2CDEVICES.md +++ b/I2CDEVICES.md @@ -66,3 +66,4 @@ Index | Define | Driver | Device | Address(es) | Description 42 | USE_DS1624 | xsns_59 | DS1624 | 0x48 - 0x4F | Temperature sensor 43 | USE_AHT1x | xsns_63 | AHT10/15 | 0x38 | Temperature and humidity sensor 44 | USE_WEMOS_MOTOR_V1 | xdrv_34 | | 0x2D - 0x30 | WEMOS motor shield v1.0.0 (6612FNG) + 92 | USE_HDC1080 | xsns_92 | HDC1080 | 0x40 | Digital Humidity Sensor with Temperature Sensor diff --git a/tasmota/my_user_config.h b/tasmota/my_user_config.h index a62c6d191..40cbb5ce4 100644 --- a/tasmota/my_user_config.h +++ b/tasmota/my_user_config.h @@ -494,6 +494,8 @@ // #define USE_DS1624 // [I2cDriver42] Enable DS1624, DS1621 temperature sensor (I2C addresses 0x48 - 0x4F) (+1k2 code) // #define USE_AHT1x // [I2cDriver43] Enable AHT10/15 humidity and temperature sensor (I2C address 0x38) (+0k8 code) // #define USE_WEMOS_MOTOR_V1 // [I2cDriver44] Enable Wemos motor driver V1 (I2C addresses 0x2D - 0x30) (+0k7 code) +// #define USE_HDC1080 // [I2cDriver92] Enable HDC1080 temperature/humidity sensor + // #define WEMOS_MOTOR_V1_ADDR 0x30 // Default I2C address 0x30 // #define WEMOS_MOTOR_V1_FREQ 1000 // Default frequency diff --git a/tasmota/support_command.ino b/tasmota/support_command.ino index c881e5db1..43db86430 100644 --- a/tasmota/support_command.ino +++ b/tasmota/support_command.ino @@ -1113,35 +1113,6 @@ void CmndSwitchDebounce(void) ResponseCmndNumber(Settings.switch_debounce); } -/** - * Changes the Serial port number of bits, parity and stop bits. - * For the time being this command only has effect on the hardware - * serial port (GPIO1 and GPIO3) - * - * Meaning of the values: - * - * 0 - 7N1 (7 data bits / no parity / 1 stop bit) - * 1 - 7E1 (7 data bits / even parity / 1 stop bit) - * 2 - 8N1 (8 data bits / no parity / 1 stop bit) - * 3 - 8E1 (8 data bits / even parity / 1 stop bit) - * - */ - -void CmndSerialConfig(void) -{ - // a frugal validation to check if the provided serial port mode is valid: - - if (XdrvMailbox.payload >= 0 && XdrvMailbox.payload <= 3) { - uint8_t mode = (uint8_t) (XdrvMailbox.payload & 3); - - SetSerialConfig(mode); - } - - SerialCfg config = SettingToSerialCfg(Settings.serial_config); - - ResponseCmndNumber(config.mode); -} - void CmndBaudrate(void) { if (XdrvMailbox.payload >= 300) { diff --git a/tasmota/support_features.ino b/tasmota/support_features.ino index 961dd1091..906442f9e 100644 --- a/tasmota/support_features.ino +++ b/tasmota/support_features.ino @@ -257,6 +257,10 @@ void GetFeatures(void) #ifdef USE_HTU feature_sns1 |= 0x00000200; // xsns_08_htu21.ino #endif +// TODO not sure if is the correct feature setting for this sensor: +#ifdef USE_HDC1080 + feature_sns1 |= 0x00000200; // xsns_92_hdc1080.ino +#endif #ifdef USE_BMP feature_sns1 |= 0x00000400; // xsns_09_bmp.ino #endif diff --git a/tasmota/tasmota_post.h b/tasmota/tasmota_post.h index 7cf0fff75..119ec70e4 100644 --- a/tasmota/tasmota_post.h +++ b/tasmota/tasmota_post.h @@ -182,6 +182,9 @@ extern "C" void custom_crash_callback(struct rst_info * rst_info, uint32_t stack #define USE_DHT12 // Add I2C code for DHT12 temperature and humidity sensor (+0k7 code) #define USE_DS1624 // Add I2C code for DS1624, DS1621 sensor //#define USE_AHT1x // Enable AHT10/15 humidity and temperature sensor (I2C address 0x38) (+0k8 code) +#define USE_HDC1080 // Enable HDC1080 temperature/humidity sensor + + #define USE_WEMOS_MOTOR_V1 // Enable Wemos motor driver V1 (I2C addresses 0x2D - 0x30) (+0k7 code) #define WEMOS_MOTOR_V1_ADDR 0x30 // Default I2C address 0x30 #define WEMOS_MOTOR_V1_FREQ 1000 // Default frequency diff --git a/tasmota/xsns_92_hdc1080.ino b/tasmota/xsns_92_hdc1080.ino new file mode 100644 index 000000000..7cfb9873e --- /dev/null +++ b/tasmota/xsns_92_hdc1080.ino @@ -0,0 +1,358 @@ +/* + xsns_92_hdc1080.ino - Texas Instruments HDC1080 temperature and humidity sensor support for Tasmota + + Copyright (C) 2020 Luis Teixeira + + 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_HDC1080 +/*********************************************************************************************\ + * HDC1080 - Temperature and Humidy sensor + * + * Source: Luis Teixeira + * + * I2C Address: 0x40 +\*********************************************************************************************/ + +#define XSNS_92 92 +#define XI2C_92 92 // See I2CDEVICES.md + +#define HDC1080_ADDR 0x40 + +// Registers: + +#define HDC_REG_TEMP 0x00 // Temperature register +#define HDC_REG_RH 0x01 // Humidity register +#define HDC_REG_CONFIG 0x02 // Configuration register +#define HDC_REG_SERIAL1 0xFB // First 2 bytes of the serial ID +#define HDC_REG_SERIAL2 0xFC // Mid 2 bytes of the serial ID +#define HDC_REG_SERIAL3 0xFD // Last bits of the serial ID +#define HDC_REG_MAN_ID 0xFE // Manufacturer ID +#define HDC_REG_DEV_ID 0xFF // Device ID + +// Expected constant values of some of the registers: + +#define HDC1080_MAN_ID 0x5449 // Manufacturer ID (Texas Instruments) +#define HDC1080_DEV_ID 0x1050 // Device ID (valid for the HDC1080) + +// Possible values for the configuration register fields: + +#define HDC1080_HEAT_OFF 0x00 +#define HDC1080_HEAT_ON 0x01 +#define HDC1080_ACQ_SEQ_ON 1 +#define HDC1080_ACQ_SEQ_OFF 0 +#define HDC1080_MEAS_RES_14 0x00 +#define HDC1080_MEAS_RES_11 0x01 +#define HDC1080_MEAS_RES_8 0x02 + +#define HDC1080_CONV_TIME 15 // Assume 6.50 + 6.35 ms + x of conversion delay for this device +#define HDC1080_TEMP_MULT 0.0025177 +#define HDC1080_RH_MULT 0.0025177 +#define HDC1080_TEMP_OFFSET 40 + +const char kHdcTypes[] PROGMEM = "HDC1080"; + +uint8_t hdc_address; +uint8_t hdc_type = 0; + +float hdc_temperature = 0; +float hdc_humidity = 0; +uint8_t hdc_valid = 0; +char hdc_types[1]; + +/** + * Reads the device ID register. + * + */ +uint16_t HdcReadDeviceId(void) { + uint16_t deviceID = 0; + + deviceID = I2cRead16(HDC1080_ADDR, HDC_REG_DEV_ID); + + return deviceID; +} + +/** + * Configures the acquisition mode of the sensor. The + * HDC1080 supports the acquisition of temperature + * and humidity in a single I2C transaction. + * + * MODE = 0 -> Temperature or Humidity is acquired. + * MODE = 1 -> Temperature and Humidity are acquired in sequence, Temperature first + * + */ +void HdcSetAcqMode(bool mode) { + uint16_t current = I2cRead16(HDC1080_ADDR, HDC_REG_CONFIG); + + // bit 12 of the register contains the MODE field + // so we shift our value to that position and + // apply the bit mask to preserve the remaining bits + // of the register: + + current &= (uint16_t) ((mode << 12) | 0xEFFF); + + I2cWrite16(HDC1080_ADDR, HDC_REG_CONFIG, current); +} + +/** + * Configures the temperature sampling resolution of the sensor. + * + * This particular device provides two options: + * + * TRES = 0 -> 14 bit resolution + * TRES = 1 -> 11 bit resolution + * + */ +void HdcSetTemperatureResolution(uint8_t resolution) { + uint16_t current = I2cRead16(HDC1080_ADDR, HDC_REG_CONFIG); + + // bit 10 of the register contains the TRES field + // so we shift our value to that position and + // apply the bit mask to preserve the remaining bits + // of the register: + + current &= (uint16_t) ((resolution << 10) | 0xFBFF); + + I2cWrite16(HDC1080_ADDR, HDC_REG_CONFIG, current); +} + +/** + * Configures the humidity sampling resolution of the sensor. + * + * This particular device provides three options: + * + * HRES = 0 -> 14 bit resolution + * HRES = 1 -> 11 bit resolution + * HRES = 2 -> 8 bit resolution + * + */ +void HdcSetHumidityResolution(uint8_t resolution) { + uint16_t current = I2cRead16(HDC1080_ADDR, HDC_REG_CONFIG); + + // bits 9:8 of the register contain the HRES field + // so we shift our value to that position and + // apply the bit mask to preserve the remaining bits + // of the register: + + current &= (uint16_t) ((resolution << 8) | 0xFCFF); + + I2cWrite16(HDC1080_ADDR, HDC_REG_CONFIG, current); +} + +/** + * Performs a soft reset on the device. + * + * RST = 1 -> software reset + * + */ +void HdcReset(void) { + uint16_t current = I2cRead16(HDC1080_ADDR, HDC_REG_CONFIG); + + // bits 9:8 of the register contain the RST flag + // so we set it to 1: + + current |= 0x8000; + + I2cWrite16(HDC1080_ADDR, HDC_REG_CONFIG, current); + + delay(15); // Not sure how long it takes to reset. Assuming 15ms +} + +/** + * Runs the heater in order to reduce the accumulated + * offset when the sensor is exposed for long periods + * at high humidity levels. + * + * HEAT = 0 -> heater off + * HEAT = 1 -> heater on + * + */ +void HdcHeater(uint8_t heater) { + uint16_t current = I2cRead16(HDC1080_ADDR, HDC_REG_CONFIG); + + // bits 13 of the register contain the HEAT flag + // so we set it according to the value of the heater argument: + + current &= (uint16_t) ((heater << 13) | 0xDFFF); + + I2cWrite16(HDC1080_ADDR, HDC_REG_CONFIG, current); +} + +void HdcInit(void) +{ + HdcReset(); + HdcHeater(HDC1080_HEAT_OFF); + HdcSetAcqMode(HDC1080_ACQ_SEQ_ON); + HdcSetTemperatureResolution(HDC1080_MEAS_RES_14); + HdcSetHumidityResolution(HDC1080_MEAS_RES_14); +} + +/** + * Performs a temperature and humidity measurement, and calls + * the conversion function providing the results in the correct + * unit according to the device settings. + * + */ +bool HdcRead(void) { + int8_t status = 0; + uint16_t sensor_data[2]; + + // In this sensor we must start by performing a write to the + // temperature register. This signals the sensor to begin a + // measurement: + + // TODO initialize the measurement mode and + // read both registers in a single transaction: + + Wire.beginTransmission(HDC1080_ADDR); + Wire.write(HDC_REG_TEMP); + + if (Wire.endTransmission() != 0) { // In case of error + AddLog_P(LOG_LEVEL_DEBUG, PSTR("HdcRead: failed to write to device for performing acquisition.")); + + return false; + } + + delay(HDC1080_CONV_TIME); // Sensor time at max resolution + + // reads the temperature and humidity in a single transaction: + + status = I2cReadBuffer(HDC1080_ADDR, HDC_REG_TEMP, (uint8_t*) sensor_data, 4); + + if(status != 0) { + AddLog_P2(LOG_LEVEL_DEBUG, PSTR("HdcRead: failed to read HDC_REG_TEMP. Status = %d"), status); + + return false; + } + + // read the temperature from the first 16 bits of the result + + hdc_temperature = ConvertTemp(HDC1080_TEMP_MULT * (float) (sensor_data[0]) - HDC1080_TEMP_OFFSET); + + AddLog_P2(LOG_LEVEL_DEBUG, PSTR("HdcRead: temperature successfully converted. Value = %f"), hdc_temperature); + + // read the humidity from the last 16 bits of the result + + hdc_humidity = HDC1080_RH_MULT * (float) (sensor_data[1]); + + AddLog_P2(LOG_LEVEL_DEBUG, PSTR("HdcRead: humidity successfully converted. Value = %f"), hdc_humidity); + + if (hdc_humidity > 100) { hdc_humidity = 100.0; } + + if (hdc_humidity < 0) { hdc_humidity = 0.01; } + + ConvertHumidity(hdc_humidity); // Set global humidity + + hdc_valid = SENSOR_MAX_MISS; + + return true; +} + +/********************************************************************************************/ + +void HdcDetect(void) +{ + hdc_address = HDC1080_ADDR; + + if (I2cActive(hdc_address)) { + AddLog_P2(LOG_LEVEL_DEBUG, PSTR("HdcDetect: Address = 0x%02X already in use."), hdc_address); + + return; + } + + hdc_type = HdcReadDeviceId(); + + AddLog_P2(LOG_LEVEL_DEBUG, PSTR("HdcDetect: detected device with id = 0x%04X"), hdc_type); + + if (hdc_type == HDC1080_DEV_ID) { + HdcInit(); + GetTextIndexed(hdc_types, sizeof(hdc_types), 0, kHdcTypes); + I2cSetActiveFound(hdc_address, hdc_types); + } +} + +void HdcEverySecond(void) { + if (uptime &1) { // Every 2 seconds + if (!HdcRead()) { + AddLogMissed(hdc_types, hdc_valid); + } + } +} + +void HdcShow(bool json) { + if (hdc_valid) { + char temperature[33]; + + dtostrfd(hdc_temperature, Settings.flag2.temperature_resolution, temperature); + char humidity[33]; + dtostrfd(hdc_humidity, Settings.flag2.humidity_resolution, humidity); + + if (json) { + ResponseAppend_P(JSON_SNS_TEMPHUM, hdc_type, temperature, humidity); +#ifdef USE_DOMOTICZ + if (0 == tele_period) { + DomoticzTempHumSensor(temperature, humidity); + } +#endif // USE_DOMOTICZ +#ifdef USE_KNX + if (0 == tele_period) { + KnxSensor(KNX_TEMPERATURE, hdc_temperature); + KnxSensor(KNX_HUMIDITY, hdc_humidity); + } +#endif // USE_KNX +#ifdef USE_WEBSERVER + } else { + WSContentSend_PD(HTTP_SNS_TEMP, hdc_types, temperature, TempUnit()); + WSContentSend_PD(HTTP_SNS_HUM, hdc_types, humidity); +#endif // USE_WEBSERVER + } + } +} + +/*********************************************************************************************\ + * Interface +\*********************************************************************************************/ + +bool Xsns92(uint8_t function) +{ + if (!I2cEnabled(XI2C_92)) { return false; } + + bool result = false; + + if (FUNC_INIT == function) { + HdcDetect(); + } + else if (hdc_type) { + switch (function) { + case FUNC_EVERY_SECOND: + HdcEverySecond(); + break; + case FUNC_JSON_APPEND: + HdcShow(1); + break; +#ifdef USE_WEBSERVER + case FUNC_WEB_SENSOR: + HdcShow(0); + break; +#endif // USE_WEBSERVER + } + } + return result; +} + +#endif // USE_HDC1080 +#endif // USE_I2C + diff --git a/tools/decode-status.py b/tools/decode-status.py index fe80630cc..232cebc07 100755 --- a/tools/decode-status.py +++ b/tools/decode-status.py @@ -178,7 +178,7 @@ a_features = [[ "USE_INA219","USE_SHT3X","USE_MHZ19","USE_TSL2561", "USE_SENSEAIR","USE_PMS5003","USE_MGS","USE_NOVA_SDS", "USE_SGP30","USE_SR04","USE_SDM120","USE_SI1145", - "USE_SDM630","USE_LM75AD","USE_APDS9960","USE_TM1638" + "USE_SDM630","USE_LM75AD","USE_APDS9960","USE_TM1638", "USE_HDC1080" ],[ "USE_MCP230xx","USE_MPR121","USE_CCS811","USE_MPU6050", "USE_MCP230xx_OUTPUT","USE_MCP230xx_DISPLAYOUTPUT","USE_HLW8012","USE_CSE7766", From cb2cc9bbb182335408ce4655afc6476d65867759 Mon Sep 17 00:00:00 2001 From: Luis Teixeira Date: Mon, 9 Mar 2020 23:02:03 +0000 Subject: [PATCH 05/20] More intermediate changes and troubleshooting. --- tasmota/support_features.ino | 9 +- tasmota/xsns_92_hdc1080.ino | 188 +++++++++++++++++++++-------------- 2 files changed, 116 insertions(+), 81 deletions(-) diff --git a/tasmota/support_features.ino b/tasmota/support_features.ino index 906442f9e..213219621 100644 --- a/tasmota/support_features.ino +++ b/tasmota/support_features.ino @@ -257,10 +257,6 @@ void GetFeatures(void) #ifdef USE_HTU feature_sns1 |= 0x00000200; // xsns_08_htu21.ino #endif -// TODO not sure if is the correct feature setting for this sensor: -#ifdef USE_HDC1080 - feature_sns1 |= 0x00000200; // xsns_92_hdc1080.ino -#endif #ifdef USE_BMP feature_sns1 |= 0x00000400; // xsns_09_bmp.ino #endif @@ -327,7 +323,10 @@ void GetFeatures(void) #ifdef USE_TM1638 feature_sns1 |= 0x80000000; // xsns_28_tm1638.ino #endif - +// TODO not sure if is the correct feature setting for this sensor: +#ifdef USE_HDC1080 + feature_sns1 |= 0x00000200; // xsns_92_hdc1080.ino +#endif /*********************************************************************************************/ feature_sns2 = 0x00000000; diff --git a/tasmota/xsns_92_hdc1080.ino b/tasmota/xsns_92_hdc1080.ino index 7cfb9873e..24a714055 100644 --- a/tasmota/xsns_92_hdc1080.ino +++ b/tasmota/xsns_92_hdc1080.ino @@ -50,41 +50,47 @@ // Possible values for the configuration register fields: -#define HDC1080_HEAT_OFF 0x00 -#define HDC1080_HEAT_ON 0x01 -#define HDC1080_ACQ_SEQ_ON 1 -#define HDC1080_ACQ_SEQ_OFF 0 -#define HDC1080_MEAS_RES_14 0x00 -#define HDC1080_MEAS_RES_11 0x01 -#define HDC1080_MEAS_RES_8 0x02 +#define HDC1080_RST_ON 0x8000 +#define HDC1080_HEAT_ON 0x2000 +#define HDC1080_MODE_ON 0x1000 // acquision mode (temperature + humidity) +#define HDC1080_TRES_11 0x400 +#define HDC1080_HRES_11 0x100 +#define HDC1080_HRES_8 0x80 -#define HDC1080_CONV_TIME 15 // Assume 6.50 + 6.35 ms + x of conversion delay for this device +// Constants: + +#define HDC1080_CONV_TIME 25 // Assume 6.50 + 6.35 ms + x of conversion delay for this device #define HDC1080_TEMP_MULT 0.0025177 #define HDC1080_RH_MULT 0.0025177 -#define HDC1080_TEMP_OFFSET 40 - -const char kHdcTypes[] PROGMEM = "HDC1080"; +#define HDC1080_TEMP_OFFSET 40.0 +const char* hdc_type_name = "HDC1080"; uint8_t hdc_address; -uint8_t hdc_type = 0; +uint16_t hdc_manufacturer_id = 0; +uint16_t hdc_device_id = 0; + +float hdc_temperature = 0.0; +float hdc_humidity = 0.0; -float hdc_temperature = 0; -float hdc_humidity = 0; uint8_t hdc_valid = 0; -char hdc_types[1]; /** * Reads the device ID register. * */ uint16_t HdcReadDeviceId(void) { - uint16_t deviceID = 0; - - deviceID = I2cRead16(HDC1080_ADDR, HDC_REG_DEV_ID); - - return deviceID; + return I2cRead16(HDC1080_ADDR, HDC_REG_DEV_ID); } +/** + * Reads the manufacturer ID register. + * + */ +uint16_t HdcReadManufacturerId(void) { + return I2cRead16(HDC1080_ADDR, HDC_REG_MAN_ID); +} + + /** * Configures the acquisition mode of the sensor. The * HDC1080 supports the acquisition of temperature @@ -94,7 +100,7 @@ uint16_t HdcReadDeviceId(void) { * MODE = 1 -> Temperature and Humidity are acquired in sequence, Temperature first * */ -void HdcSetAcqMode(bool mode) { +void HdcSetAcqMode(uint8_t mode) { uint16_t current = I2cRead16(HDC1080_ADDR, HDC_REG_CONFIG); // bit 12 of the register contains the MODE field @@ -102,7 +108,7 @@ void HdcSetAcqMode(bool mode) { // apply the bit mask to preserve the remaining bits // of the register: - current &= (uint16_t) ((mode << 12) | 0xEFFF); + current = (current & 0xEFFF) | ((uint16_t) (mode << 12)); I2cWrite16(HDC1080_ADDR, HDC_REG_CONFIG, current); } @@ -124,7 +130,7 @@ void HdcSetTemperatureResolution(uint8_t resolution) { // apply the bit mask to preserve the remaining bits // of the register: - current &= (uint16_t) ((resolution << 10) | 0xFBFF); + current = (current & 0xFBFF) | ((uint16_t) (resolution << 10)); I2cWrite16(HDC1080_ADDR, HDC_REG_CONFIG, current); } @@ -147,30 +153,11 @@ void HdcSetHumidityResolution(uint8_t resolution) { // apply the bit mask to preserve the remaining bits // of the register: - current &= (uint16_t) ((resolution << 8) | 0xFCFF); + current = (current & 0xFCFF) | ((uint16_t) (resolution << 8)); I2cWrite16(HDC1080_ADDR, HDC_REG_CONFIG, current); } -/** - * Performs a soft reset on the device. - * - * RST = 1 -> software reset - * - */ -void HdcReset(void) { - uint16_t current = I2cRead16(HDC1080_ADDR, HDC_REG_CONFIG); - - // bits 9:8 of the register contain the RST flag - // so we set it to 1: - - current |= 0x8000; - - I2cWrite16(HDC1080_ADDR, HDC_REG_CONFIG, current); - - delay(15); // Not sure how long it takes to reset. Assuming 15ms -} - /** * Runs the heater in order to reduce the accumulated * offset when the sensor is exposed for long periods @@ -183,21 +170,54 @@ void HdcReset(void) { void HdcHeater(uint8_t heater) { uint16_t current = I2cRead16(HDC1080_ADDR, HDC_REG_CONFIG); - // bits 13 of the register contain the HEAT flag + // bits 13 of the configuration register contains the HEAT flag // so we set it according to the value of the heater argument: - current &= (uint16_t) ((heater << 13) | 0xDFFF); + current = (current | 0xDFFF) | ((uint16_t) (heater << 13)); I2cWrite16(HDC1080_ADDR, HDC_REG_CONFIG, current); } -void HdcInit(void) -{ +/** + * Overwrites the configuration register with the provided config + */ +void HdcConfig(uint16_t config) { + I2cWrite16(HDC1080_ADDR, HDC_REG_CONFIG, config); +} + +/** + * Performs a soft reset on the device. + * + * RST = 1 -> software reset + * + */ +void HdcReset(void) { + uint16_t current = I2cRead16(HDC1080_ADDR, HDC_REG_CONFIG); + + // bit 15 of the configuration register contains the RST flag + // so we set it to 1: + + current |= 0x8000; + + I2cWrite16(HDC1080_ADDR, HDC_REG_CONFIG, current); + + delay(30); // Not sure how long it takes to reset. Assuming 15ms +} + + +/** + * The various initialization steps for this sensor. + * + */ +void HdcInit(void) { HdcReset(); - HdcHeater(HDC1080_HEAT_OFF); - HdcSetAcqMode(HDC1080_ACQ_SEQ_ON); - HdcSetTemperatureResolution(HDC1080_MEAS_RES_14); - HdcSetHumidityResolution(HDC1080_MEAS_RES_14); + //HdcHeater(HDC1080_HEAT_OFF); + //HdcSetAcqMode(HDC1080_ACQ_SEQ_ON); + //HdcSetAcqMode(HDC1080_ACQ_SEQ_OFF); + //HdcSetTemperatureResolution(HDC1080_MEAS_RES_14); + //HdcSetHumidityResolution(HDC1080_MEAS_RES_14); + + HdcConfig(0); } /** @@ -208,15 +228,14 @@ void HdcInit(void) */ bool HdcRead(void) { int8_t status = 0; - uint16_t sensor_data[2]; + //uint16_t sensor_data[2]; + + uint16_t sensor_data = 0; // In this sensor we must start by performing a write to the // temperature register. This signals the sensor to begin a // measurement: - // TODO initialize the measurement mode and - // read both registers in a single transaction: - Wire.beginTransmission(HDC1080_ADDR); Wire.write(HDC_REG_TEMP); @@ -226,32 +245,46 @@ bool HdcRead(void) { return false; } - delay(HDC1080_CONV_TIME); // Sensor time at max resolution + delay(HDC1080_CONV_TIME); // Apply sensor conversion time at max resolution // reads the temperature and humidity in a single transaction: - status = I2cReadBuffer(HDC1080_ADDR, HDC_REG_TEMP, (uint8_t*) sensor_data, 4); + //status = I2cReadBuffer(HDC1080_ADDR, HDC_REG_TEMP, (uint8_t*) sensor_data, 4); + sensor_data = I2cRead16(HDC1080_ADDR, HDC_REG_TEMP); + + AddLog_P2(LOG_LEVEL_DEBUG, PSTR("HdcRead: temperature raw data: 0x%04x"), sensor_data); + + // status = I2cReadBuffer(HDC1080_ADDR, HDC_REG_TEMP, (uint8_t*) &sensor_data, 2); + +/* if(status != 0) { AddLog_P2(LOG_LEVEL_DEBUG, PSTR("HdcRead: failed to read HDC_REG_TEMP. Status = %d"), status); return false; } - +*/ // read the temperature from the first 16 bits of the result - hdc_temperature = ConvertTemp(HDC1080_TEMP_MULT * (float) (sensor_data[0]) - HDC1080_TEMP_OFFSET); + //hdc_temperature = ConvertTemp(HDC1080_TEMP_MULT * (float) (sensor_data[0]) - HDC1080_TEMP_OFFSET); - AddLog_P2(LOG_LEVEL_DEBUG, PSTR("HdcRead: temperature successfully converted. Value = %f"), hdc_temperature); + hdc_temperature = ConvertTemp(HDC1080_TEMP_MULT * (float) (sensor_data) - HDC1080_TEMP_OFFSET); + + //AddLog_P2(LOG_LEVEL_DEBUG, PSTR("HdcRead: temperature successfully converted. Value = %f"), hdc_temperature); // read the humidity from the last 16 bits of the result - hdc_humidity = HDC1080_RH_MULT * (float) (sensor_data[1]); + sensor_data = I2cRead16(HDC1080_ADDR, HDC_REG_RH); - AddLog_P2(LOG_LEVEL_DEBUG, PSTR("HdcRead: humidity successfully converted. Value = %f"), hdc_humidity); + AddLog_P2(LOG_LEVEL_DEBUG, PSTR("HdcRead: humidity raw data: 0x%04x"), sensor_data); + + //hdc_humidity = HDC1080_RH_MULT * (float) (sensor_data[1]); + + hdc_humidity = HDC1080_RH_MULT * (float) (sensor_data); + + //AddLog_P2(LOG_LEVEL_DEBUG, PSTR("HdcRead: humidity successfully converted. Value = %f"), hdc_humidity); if (hdc_humidity > 100) { hdc_humidity = 100.0; } - if (hdc_humidity < 0) { hdc_humidity = 0.01; } ConvertHumidity(hdc_humidity); // Set global humidity @@ -263,8 +296,7 @@ bool HdcRead(void) { /********************************************************************************************/ -void HdcDetect(void) -{ +void HdcDetect(void) { hdc_address = HDC1080_ADDR; if (I2cActive(hdc_address)) { @@ -273,21 +305,21 @@ void HdcDetect(void) return; } - hdc_type = HdcReadDeviceId(); + hdc_manufacturer_id = HdcReadManufacturerId(); + hdc_device_id = HdcReadDeviceId(); - AddLog_P2(LOG_LEVEL_DEBUG, PSTR("HdcDetect: detected device with id = 0x%04X"), hdc_type); + AddLog_P2(LOG_LEVEL_DEBUG, PSTR("HdcDetect: detected device with manufacturerId = 0x%04X and deviceId = 0x%04X"), hdc_manufacturer_id, hdc_device_id); - if (hdc_type == HDC1080_DEV_ID) { + if (hdc_device_id == HDC1080_DEV_ID) { HdcInit(); - GetTextIndexed(hdc_types, sizeof(hdc_types), 0, kHdcTypes); - I2cSetActiveFound(hdc_address, hdc_types); + I2cSetActiveFound(hdc_address, hdc_type_name); } } void HdcEverySecond(void) { if (uptime &1) { // Every 2 seconds if (!HdcRead()) { - AddLogMissed(hdc_types, hdc_valid); + AddLogMissed((char*) hdc_type_name, hdc_valid); } } } @@ -301,7 +333,7 @@ void HdcShow(bool json) { dtostrfd(hdc_humidity, Settings.flag2.humidity_resolution, humidity); if (json) { - ResponseAppend_P(JSON_SNS_TEMPHUM, hdc_type, temperature, humidity); + ResponseAppend_P(JSON_SNS_TEMPHUM, hdc_device_id, temperature, humidity); #ifdef USE_DOMOTICZ if (0 == tele_period) { DomoticzTempHumSensor(temperature, humidity); @@ -315,8 +347,8 @@ void HdcShow(bool json) { #endif // USE_KNX #ifdef USE_WEBSERVER } else { - WSContentSend_PD(HTTP_SNS_TEMP, hdc_types, temperature, TempUnit()); - WSContentSend_PD(HTTP_SNS_HUM, hdc_types, humidity); + WSContentSend_PD(HTTP_SNS_TEMP, hdc_type_name, temperature, TempUnit()); + WSContentSend_PD(HTTP_SNS_HUM, hdc_type_name, humidity); #endif // USE_WEBSERVER } } @@ -328,14 +360,18 @@ void HdcShow(bool json) { bool Xsns92(uint8_t function) { - if (!I2cEnabled(XI2C_92)) { return false; } + if (!I2cEnabled(XI2C_92)) { + AddLog_P(LOG_LEVEL_DEBUG, PSTR("Xsns92: I2C driver not enabled for this device.")); + + return false; + } bool result = false; if (FUNC_INIT == function) { HdcDetect(); } - else if (hdc_type) { + else if (hdc_device_id) { switch (function) { case FUNC_EVERY_SECOND: HdcEverySecond(); From 2a06a6bc5a1949fd92a578dd55d6f2819c37fa2e Mon Sep 17 00:00:00 2001 From: Luis Teixeira Date: Tue, 10 Mar 2020 00:15:42 +0000 Subject: [PATCH 06/20] Fixed issue when reading temperature and humidity in the same transaction. --- tasmota/xsns_92_hdc1080.ino | 192 ++++++++---------------------------- 1 file changed, 43 insertions(+), 149 deletions(-) diff --git a/tasmota/xsns_92_hdc1080.ino b/tasmota/xsns_92_hdc1080.ino index 24a714055..d1a5175b0 100644 --- a/tasmota/xsns_92_hdc1080.ino +++ b/tasmota/xsns_92_hdc1080.ino @@ -59,13 +59,13 @@ // Constants: -#define HDC1080_CONV_TIME 25 // Assume 6.50 + 6.35 ms + x of conversion delay for this device +#define HDC1080_CONV_TIME 50 // Assume 6.50 + 6.35 ms + x of conversion delay for this device #define HDC1080_TEMP_MULT 0.0025177 #define HDC1080_RH_MULT 0.0025177 #define HDC1080_TEMP_OFFSET 40.0 -const char* hdc_type_name = "HDC1080"; -uint8_t hdc_address; + +char* hdc_type_name = "HDC1080"; uint16_t hdc_manufacturer_id = 0; uint16_t hdc_device_id = 0; @@ -90,94 +90,6 @@ uint16_t HdcReadManufacturerId(void) { return I2cRead16(HDC1080_ADDR, HDC_REG_MAN_ID); } - -/** - * Configures the acquisition mode of the sensor. The - * HDC1080 supports the acquisition of temperature - * and humidity in a single I2C transaction. - * - * MODE = 0 -> Temperature or Humidity is acquired. - * MODE = 1 -> Temperature and Humidity are acquired in sequence, Temperature first - * - */ -void HdcSetAcqMode(uint8_t mode) { - uint16_t current = I2cRead16(HDC1080_ADDR, HDC_REG_CONFIG); - - // bit 12 of the register contains the MODE field - // so we shift our value to that position and - // apply the bit mask to preserve the remaining bits - // of the register: - - current = (current & 0xEFFF) | ((uint16_t) (mode << 12)); - - I2cWrite16(HDC1080_ADDR, HDC_REG_CONFIG, current); -} - -/** - * Configures the temperature sampling resolution of the sensor. - * - * This particular device provides two options: - * - * TRES = 0 -> 14 bit resolution - * TRES = 1 -> 11 bit resolution - * - */ -void HdcSetTemperatureResolution(uint8_t resolution) { - uint16_t current = I2cRead16(HDC1080_ADDR, HDC_REG_CONFIG); - - // bit 10 of the register contains the TRES field - // so we shift our value to that position and - // apply the bit mask to preserve the remaining bits - // of the register: - - current = (current & 0xFBFF) | ((uint16_t) (resolution << 10)); - - I2cWrite16(HDC1080_ADDR, HDC_REG_CONFIG, current); -} - -/** - * Configures the humidity sampling resolution of the sensor. - * - * This particular device provides three options: - * - * HRES = 0 -> 14 bit resolution - * HRES = 1 -> 11 bit resolution - * HRES = 2 -> 8 bit resolution - * - */ -void HdcSetHumidityResolution(uint8_t resolution) { - uint16_t current = I2cRead16(HDC1080_ADDR, HDC_REG_CONFIG); - - // bits 9:8 of the register contain the HRES field - // so we shift our value to that position and - // apply the bit mask to preserve the remaining bits - // of the register: - - current = (current & 0xFCFF) | ((uint16_t) (resolution << 8)); - - I2cWrite16(HDC1080_ADDR, HDC_REG_CONFIG, current); -} - -/** - * Runs the heater in order to reduce the accumulated - * offset when the sensor is exposed for long periods - * at high humidity levels. - * - * HEAT = 0 -> heater off - * HEAT = 1 -> heater on - * - */ -void HdcHeater(uint8_t heater) { - uint16_t current = I2cRead16(HDC1080_ADDR, HDC_REG_CONFIG); - - // bits 13 of the configuration register contains the HEAT flag - // so we set it according to the value of the heater argument: - - current = (current | 0xDFFF) | ((uint16_t) (heater << 13)); - - I2cWrite16(HDC1080_ADDR, HDC_REG_CONFIG, current); -} - /** * Overwrites the configuration register with the provided config */ @@ -201,9 +113,32 @@ void HdcReset(void) { I2cWrite16(HDC1080_ADDR, HDC_REG_CONFIG, current); - delay(30); // Not sure how long it takes to reset. Assuming 15ms + delay(HDC1080_CONV_TIME); // Not sure how long it takes to reset. Assuming this value. } +/** + * Performs the single transaction read of the HDC1080, providing the + * adequate delay for the acquisition. + * + */ +int8_t HdcReadBuffer(uint8_t addr, uint8_t reg, uint8_t *reg_data, uint16_t len) { + Wire.beginTransmission((uint8_t)addr); + Wire.write((uint8_t)reg); + Wire.endTransmission(); + + delay(HDC1080_CONV_TIME); + + if (len != Wire.requestFrom((uint8_t)addr, (uint8_t)len)) { + return 1; + } + + while (len--) { + *reg_data = (uint8_t)Wire.read(); + reg_data++; + } + + return 0; +} /** * The various initialization steps for this sensor. @@ -211,13 +146,7 @@ void HdcReset(void) { */ void HdcInit(void) { HdcReset(); - //HdcHeater(HDC1080_HEAT_OFF); - //HdcSetAcqMode(HDC1080_ACQ_SEQ_ON); - //HdcSetAcqMode(HDC1080_ACQ_SEQ_OFF); - //HdcSetTemperatureResolution(HDC1080_MEAS_RES_14); - //HdcSetHumidityResolution(HDC1080_MEAS_RES_14); - - HdcConfig(0); + HdcConfig(HDC1080_MODE_ON); } /** @@ -228,61 +157,28 @@ void HdcInit(void) { */ bool HdcRead(void) { int8_t status = 0; - //uint16_t sensor_data[2]; + uint8_t sensor_data[4]; + uint16_t temp_data = 0; + uint16_t rh_data = 0; - uint16_t sensor_data = 0; + status = HdcReadBuffer(HDC1080_ADDR, HDC_REG_TEMP, sensor_data, 4); - // In this sensor we must start by performing a write to the - // temperature register. This signals the sensor to begin a - // measurement: + temp_data = (uint16_t) ((sensor_data[0] << 8) | sensor_data[1]); + rh_data = (uint16_t) ((sensor_data[2] << 8) | sensor_data[3]); - Wire.beginTransmission(HDC1080_ADDR); - Wire.write(HDC_REG_TEMP); - - if (Wire.endTransmission() != 0) { // In case of error - AddLog_P(LOG_LEVEL_DEBUG, PSTR("HdcRead: failed to write to device for performing acquisition.")); - - return false; - } - - delay(HDC1080_CONV_TIME); // Apply sensor conversion time at max resolution - - // reads the temperature and humidity in a single transaction: - - //status = I2cReadBuffer(HDC1080_ADDR, HDC_REG_TEMP, (uint8_t*) sensor_data, 4); - - sensor_data = I2cRead16(HDC1080_ADDR, HDC_REG_TEMP); - - AddLog_P2(LOG_LEVEL_DEBUG, PSTR("HdcRead: temperature raw data: 0x%04x"), sensor_data); - - // status = I2cReadBuffer(HDC1080_ADDR, HDC_REG_TEMP, (uint8_t*) &sensor_data, 2); - -/* + AddLog_P2(LOG_LEVEL_DEBUG, PSTR("HdcRead: temperature raw data: 0x%04x; humidity raw data: 0x%04x"), temp_data, rh_data); + if(status != 0) { AddLog_P2(LOG_LEVEL_DEBUG, PSTR("HdcRead: failed to read HDC_REG_TEMP. Status = %d"), status); return false; } -*/ + // read the temperature from the first 16 bits of the result - //hdc_temperature = ConvertTemp(HDC1080_TEMP_MULT * (float) (sensor_data[0]) - HDC1080_TEMP_OFFSET); + hdc_temperature = ConvertTemp(HDC1080_TEMP_MULT * (float) (temp_data) - HDC1080_TEMP_OFFSET); - hdc_temperature = ConvertTemp(HDC1080_TEMP_MULT * (float) (sensor_data) - HDC1080_TEMP_OFFSET); - - //AddLog_P2(LOG_LEVEL_DEBUG, PSTR("HdcRead: temperature successfully converted. Value = %f"), hdc_temperature); - - // read the humidity from the last 16 bits of the result - - sensor_data = I2cRead16(HDC1080_ADDR, HDC_REG_RH); - - AddLog_P2(LOG_LEVEL_DEBUG, PSTR("HdcRead: humidity raw data: 0x%04x"), sensor_data); - - //hdc_humidity = HDC1080_RH_MULT * (float) (sensor_data[1]); - - hdc_humidity = HDC1080_RH_MULT * (float) (sensor_data); - - //AddLog_P2(LOG_LEVEL_DEBUG, PSTR("HdcRead: humidity successfully converted. Value = %f"), hdc_humidity); + hdc_humidity = HDC1080_RH_MULT * (float) (rh_data); if (hdc_humidity > 100) { hdc_humidity = 100.0; } if (hdc_humidity < 0) { hdc_humidity = 0.01; } @@ -297,10 +193,8 @@ bool HdcRead(void) { /********************************************************************************************/ void HdcDetect(void) { - hdc_address = HDC1080_ADDR; - - if (I2cActive(hdc_address)) { - AddLog_P2(LOG_LEVEL_DEBUG, PSTR("HdcDetect: Address = 0x%02X already in use."), hdc_address); + if (I2cActive(HDC1080_ADDR)) { + AddLog_P2(LOG_LEVEL_DEBUG, PSTR("HdcDetect: Address = 0x%02X already in use."), HDC1080_ADDR); return; } @@ -312,14 +206,14 @@ void HdcDetect(void) { if (hdc_device_id == HDC1080_DEV_ID) { HdcInit(); - I2cSetActiveFound(hdc_address, hdc_type_name); + I2cSetActiveFound(HDC1080_ADDR, hdc_type_name); } } void HdcEverySecond(void) { if (uptime &1) { // Every 2 seconds if (!HdcRead()) { - AddLogMissed((char*) hdc_type_name, hdc_valid); + AddLogMissed(hdc_type_name, hdc_valid); } } } From e9d201a2c3af9d34aa62fd258d9806e008467683 Mon Sep 17 00:00:00 2001 From: Luis Teixeira Date: Tue, 10 Mar 2020 00:26:24 +0000 Subject: [PATCH 07/20] Fixed issue during the call to ResponseAppend_P (was passing a primitive instead of pointer to the expected string) --- tasmota/xsns_92_hdc1080.ino | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tasmota/xsns_92_hdc1080.ino b/tasmota/xsns_92_hdc1080.ino index d1a5175b0..1e045c9a8 100644 --- a/tasmota/xsns_92_hdc1080.ino +++ b/tasmota/xsns_92_hdc1080.ino @@ -227,7 +227,7 @@ void HdcShow(bool json) { dtostrfd(hdc_humidity, Settings.flag2.humidity_resolution, humidity); if (json) { - ResponseAppend_P(JSON_SNS_TEMPHUM, hdc_device_id, temperature, humidity); + ResponseAppend_P(JSON_SNS_TEMPHUM, hdc_type_name, temperature, humidity); #ifdef USE_DOMOTICZ if (0 == tele_period) { DomoticzTempHumSensor(temperature, humidity); From 725b9898c5309c1738c429b76b9a57d351301ee5 Mon Sep 17 00:00:00 2001 From: Luis Teixeira Date: Tue, 10 Mar 2020 22:53:49 +0000 Subject: [PATCH 08/20] Added cast to properly deal with the AddLogMissed function prototype. --- tasmota/xsns_92_hdc1080.ino | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tasmota/xsns_92_hdc1080.ino b/tasmota/xsns_92_hdc1080.ino index 1e045c9a8..f5cd385b1 100644 --- a/tasmota/xsns_92_hdc1080.ino +++ b/tasmota/xsns_92_hdc1080.ino @@ -65,7 +65,7 @@ #define HDC1080_TEMP_OFFSET 40.0 -char* hdc_type_name = "HDC1080"; +const char* hdc_type_name = "HDC1080"; uint16_t hdc_manufacturer_id = 0; uint16_t hdc_device_id = 0; @@ -213,7 +213,7 @@ void HdcDetect(void) { void HdcEverySecond(void) { if (uptime &1) { // Every 2 seconds if (!HdcRead()) { - AddLogMissed(hdc_type_name, hdc_valid); + AddLogMissed((char*) hdc_type_name, hdc_valid); } } } From 78a608dd449f349cae56f15c5554892954bd0c15 Mon Sep 17 00:00:00 2001 From: Luis Teixeira Date: Tue, 10 Mar 2020 23:01:51 +0000 Subject: [PATCH 09/20] Synched with resources from original repo --- tasmota/i18n.h | 1 - tasmota/language/bg-BG.h | 1 - tasmota/language/cs-CZ.h | 1 - tasmota/language/de-DE.h | 1 - tasmota/language/el-GR.h | 1 - tasmota/language/en-GB.h | 1 - tasmota/language/es-ES.h | 1 - tasmota/language/fr-FR.h | 1 - tasmota/language/he-HE.h | 1 - tasmota/language/hu-HU.h | 1 - tasmota/language/it-IT.h | 1 - tasmota/language/ko-KO.h | 1 - tasmota/language/nl-NL.h | 1 - tasmota/language/pl-PL.h | 1 - tasmota/language/pt-BR.h | 1 - tasmota/language/pt-PT.h | 1 - tasmota/language/ru-RU.h | 1 - tasmota/language/sk-SK.h | 1 - tasmota/language/sv-SE.h | 1 - tasmota/language/tr-TR.h | 1 - tasmota/language/uk-UA.h | 1 - tasmota/language/zh-CN.h | 1 - tasmota/language/zh-TW.h | 1 - 23 files changed, 23 deletions(-) diff --git a/tasmota/i18n.h b/tasmota/i18n.h index 09485cff6..f36f37977 100644 --- a/tasmota/i18n.h +++ b/tasmota/i18n.h @@ -295,7 +295,6 @@ #define D_CMND_DEVGROUP_SHARE "DevGroupShare" #define D_CMND_SERIALSEND "SerialSend" #define D_CMND_SERIALDELIMITER "SerialDelimiter" -#define D_CMND_SERIALCONFIG "SerialConfig" #define D_CMND_BAUDRATE "Baudrate" #define D_CMND_SERIALCONFIG "SerialConfig" #define D_CMND_TEMPLATE "Template" diff --git a/tasmota/language/bg-BG.h b/tasmota/language/bg-BG.h index 589e74a90..9323c9174 100644 --- a/tasmota/language/bg-BG.h +++ b/tasmota/language/bg-BG.h @@ -194,7 +194,6 @@ #define D_SYSLOG_LOGGING_REENABLED "Системният лог активиран" #define D_SET_BAUDRATE_TO "Задаване скорост на предаване (Baudrate)" -#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "Получен топик" #define D_DATA_SIZE "Размер на данните" #define D_ANALOG_INPUT "Аналогов вход" diff --git a/tasmota/language/cs-CZ.h b/tasmota/language/cs-CZ.h index d663724b7..6303708de 100644 --- a/tasmota/language/cs-CZ.h +++ b/tasmota/language/cs-CZ.h @@ -194,7 +194,6 @@ #define D_SYSLOG_LOGGING_REENABLED "Obnoven zápis do Syslog" #define D_SET_BAUDRATE_TO "Nastavení rychlosti přenosu na" -#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "Přijatý topic" #define D_DATA_SIZE "Velikost dat" #define D_ANALOG_INPUT "Analogový vstup" diff --git a/tasmota/language/de-DE.h b/tasmota/language/de-DE.h index 7f59a6b16..8cf6d8def 100644 --- a/tasmota/language/de-DE.h +++ b/tasmota/language/de-DE.h @@ -194,7 +194,6 @@ #define D_SYSLOG_LOGGING_REENABLED "Syslog-Logging aktiviert" #define D_SET_BAUDRATE_TO "Setze Baudrate auf" -#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "empfangenes topic" #define D_DATA_SIZE "Datengröße" #define D_ANALOG_INPUT "Analog" diff --git a/tasmota/language/el-GR.h b/tasmota/language/el-GR.h index ddd34c944..4a59d87b8 100644 --- a/tasmota/language/el-GR.h +++ b/tasmota/language/el-GR.h @@ -194,7 +194,6 @@ #define D_SYSLOG_LOGGING_REENABLED "Η καταγραφή Syslog επαναενεργοποιήθηκε" #define D_SET_BAUDRATE_TO "Ορισμός Baudrate σε" -#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "Received Topic" #define D_DATA_SIZE "Μέγεθος δεδομένων" #define D_ANALOG_INPUT "Αναλογικό" diff --git a/tasmota/language/en-GB.h b/tasmota/language/en-GB.h index c10378d94..e28e153e9 100644 --- a/tasmota/language/en-GB.h +++ b/tasmota/language/en-GB.h @@ -194,7 +194,6 @@ #define D_SYSLOG_LOGGING_REENABLED "Syslog logging re-enabled" #define D_SET_BAUDRATE_TO "Set Baudrate to" -#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "Received Topic" #define D_DATA_SIZE "Data Size" #define D_ANALOG_INPUT "Analog" diff --git a/tasmota/language/es-ES.h b/tasmota/language/es-ES.h index dde47b382..69c91c693 100644 --- a/tasmota/language/es-ES.h +++ b/tasmota/language/es-ES.h @@ -194,7 +194,6 @@ #define D_SYSLOG_LOGGING_REENABLED "Syslog re-habilitado" #define D_SET_BAUDRATE_TO "Baudrate a" -#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "Topic Recibido" #define D_DATA_SIZE "Tamaño de Datos" #define D_ANALOG_INPUT "Entrada Analógica" diff --git a/tasmota/language/fr-FR.h b/tasmota/language/fr-FR.h index 243ae74c3..8b71a8067 100644 --- a/tasmota/language/fr-FR.h +++ b/tasmota/language/fr-FR.h @@ -194,7 +194,6 @@ #define D_SYSLOG_LOGGING_REENABLED "Jounalisation SysLog réactivée" #define D_SET_BAUDRATE_TO "Définir le débit à" -#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "Topic reçu" // Terme MQTT #define D_DATA_SIZE "Taille données" #define D_ANALOG_INPUT "Analogique" diff --git a/tasmota/language/he-HE.h b/tasmota/language/he-HE.h index 87614e04f..09a803be6 100644 --- a/tasmota/language/he-HE.h +++ b/tasmota/language/he-HE.h @@ -194,7 +194,6 @@ #define D_SYSLOG_LOGGING_REENABLED "הופעל מחדש Syslog רישום" #define D_SET_BAUDRATE_TO "הגדר קצב שידור ל" -#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "Topic התקבל" #define D_DATA_SIZE "גודל נתונים" #define D_ANALOG_INPUT "אנלוגי" diff --git a/tasmota/language/hu-HU.h b/tasmota/language/hu-HU.h index 280a617f7..551d81014 100644 --- a/tasmota/language/hu-HU.h +++ b/tasmota/language/hu-HU.h @@ -194,7 +194,6 @@ #define D_SYSLOG_LOGGING_REENABLED "Syslog logolás újraengedélyezve" #define D_SET_BAUDRATE_TO "Baudrate beállítása" -#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "Érkezett topic" #define D_DATA_SIZE "Adatméret" #define D_ANALOG_INPUT "Analóg" diff --git a/tasmota/language/it-IT.h b/tasmota/language/it-IT.h index d52b9de02..e23c86757 100644 --- a/tasmota/language/it-IT.h +++ b/tasmota/language/it-IT.h @@ -194,7 +194,6 @@ #define D_SYSLOG_LOGGING_REENABLED "Syslog ri-abilitato" #define D_SET_BAUDRATE_TO "Baudrate impostato a" -#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "Topic Ricevuto" #define D_DATA_SIZE "Dimensione Dati" #define D_ANALOG_INPUT "Ingresso Analogico" diff --git a/tasmota/language/ko-KO.h b/tasmota/language/ko-KO.h index 5c015f09b..ddc815de5 100644 --- a/tasmota/language/ko-KO.h +++ b/tasmota/language/ko-KO.h @@ -194,7 +194,6 @@ #define D_SYSLOG_LOGGING_REENABLED "Syslog log 다시 사용" #define D_SET_BAUDRATE_TO "Set Baudrate to" -#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "Received Topic" #define D_DATA_SIZE "데이터 용량" #define D_ANALOG_INPUT "아날로그" diff --git a/tasmota/language/nl-NL.h b/tasmota/language/nl-NL.h index 624bef70f..46e29e1fd 100644 --- a/tasmota/language/nl-NL.h +++ b/tasmota/language/nl-NL.h @@ -194,7 +194,6 @@ #define D_SYSLOG_LOGGING_REENABLED "Syslog logging weer ingeschakeld" #define D_SET_BAUDRATE_TO "Zet baudrate op" -#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "Ontvangen topic" #define D_DATA_SIZE "Data lengte" #define D_ANALOG_INPUT "Analoog" diff --git a/tasmota/language/pl-PL.h b/tasmota/language/pl-PL.h index a7fa58199..2a75d6f46 100644 --- a/tasmota/language/pl-PL.h +++ b/tasmota/language/pl-PL.h @@ -194,7 +194,6 @@ #define D_SYSLOG_LOGGING_REENABLED "Wznowiono zapis do Syslog" #define D_SET_BAUDRATE_TO "Ustaw szybkość transmisji na" -#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "Otrzymany temat" #define D_DATA_SIZE "Wielkość danych" #define D_ANALOG_INPUT "Wejście analogowe" diff --git a/tasmota/language/pt-BR.h b/tasmota/language/pt-BR.h index 9d6daa244..f1b8fdbc5 100644 --- a/tasmota/language/pt-BR.h +++ b/tasmota/language/pt-BR.h @@ -194,7 +194,6 @@ #define D_SYSLOG_LOGGING_REENABLED "Registro do Syslog reativado" #define D_SET_BAUDRATE_TO "Ajuste da velocidade para" -#define D_SET_SERIAL_CONFIG_TO "Ajuste do modo da porta série" #define D_RECEIVED_TOPIC "Tópico recebido" #define D_DATA_SIZE "Tamanho de dados" #define D_ANALOG_INPUT "Entrada analógica" diff --git a/tasmota/language/pt-PT.h b/tasmota/language/pt-PT.h index d7260ca6a..36188994d 100644 --- a/tasmota/language/pt-PT.h +++ b/tasmota/language/pt-PT.h @@ -194,7 +194,6 @@ #define D_SYSLOG_LOGGING_REENABLED "Registro do Syslog reativado" #define D_SET_BAUDRATE_TO "Ajuste da velocidade para" -#define D_SET_SERIAL_CONFIG_TO "Ajuste do modo da porta série" #define D_RECEIVED_TOPIC "Topico Recebido" #define D_DATA_SIZE "Tamanho de Dados" #define D_ANALOG_INPUT "Entrada Analógica" diff --git a/tasmota/language/ru-RU.h b/tasmota/language/ru-RU.h index ed3fe87be..5690f9209 100644 --- a/tasmota/language/ru-RU.h +++ b/tasmota/language/ru-RU.h @@ -194,7 +194,6 @@ #define D_SYSLOG_LOGGING_REENABLED "Syslog logging включен" #define D_SET_BAUDRATE_TO "Установить скорость передачи (Baudrate)" -#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "Полученный Топик" #define D_DATA_SIZE "Размер данных" #define D_ANALOG_INPUT "Аналоговый вход" diff --git a/tasmota/language/sk-SK.h b/tasmota/language/sk-SK.h index 585052498..b7bd30f25 100644 --- a/tasmota/language/sk-SK.h +++ b/tasmota/language/sk-SK.h @@ -194,7 +194,6 @@ #define D_SYSLOG_LOGGING_REENABLED "Obnovený zápis do Syslog" #define D_SET_BAUDRATE_TO "Nastaviť rýchlosti prenosu na" -#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "Prijatý topic" #define D_DATA_SIZE "Veľkosť dát" #define D_ANALOG_INPUT "Analógový vstup" diff --git a/tasmota/language/sv-SE.h b/tasmota/language/sv-SE.h index 58ea66d3b..483633ae1 100644 --- a/tasmota/language/sv-SE.h +++ b/tasmota/language/sv-SE.h @@ -194,7 +194,6 @@ #define D_SYSLOG_LOGGING_REENABLED "Syslog återaktiverad" #define D_SET_BAUDRATE_TO "Ange Baudrate till" -#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "Mottaget ämne" #define D_DATA_SIZE "Datastorlek" #define D_ANALOG_INPUT "Analog" diff --git a/tasmota/language/tr-TR.h b/tasmota/language/tr-TR.h index e92a9584b..62990d5aa 100644 --- a/tasmota/language/tr-TR.h +++ b/tasmota/language/tr-TR.h @@ -194,7 +194,6 @@ #define D_SYSLOG_LOGGING_REENABLED "Sistem loglaması tekrar aktif" #define D_SET_BAUDRATE_TO "Baud hızını şu şekilde değiştir" -#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "Alınan Başlık" #define D_DATA_SIZE "Veri Büyüklüğü" #define D_ANALOG_INPUT "Analog" diff --git a/tasmota/language/uk-UA.h b/tasmota/language/uk-UA.h index 45a5621af..fbeb0f782 100644 --- a/tasmota/language/uk-UA.h +++ b/tasmota/language/uk-UA.h @@ -194,7 +194,6 @@ #define D_SYSLOG_LOGGING_REENABLED "Syslog журнал увімкнений" #define D_SET_BAUDRATE_TO "Встановити швидкість передачі (Baudrate)" -#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "Отриманий Топік" #define D_DATA_SIZE "Розмір даних" #define D_ANALOG_INPUT "Аналоговий вхід" diff --git a/tasmota/language/zh-CN.h b/tasmota/language/zh-CN.h index 3e7e108bc..95ba59358 100644 --- a/tasmota/language/zh-CN.h +++ b/tasmota/language/zh-CN.h @@ -194,7 +194,6 @@ #define D_SYSLOG_LOGGING_REENABLED "Syslog 日志已开启" #define D_SET_BAUDRATE_TO "设置波特率为:" -#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "接收到的主题:" #define D_DATA_SIZE "数据大小:" #define D_ANALOG_INPUT "Analog" diff --git a/tasmota/language/zh-TW.h b/tasmota/language/zh-TW.h index c7416df0e..b2ebcddd5 100644 --- a/tasmota/language/zh-TW.h +++ b/tasmota/language/zh-TW.h @@ -194,7 +194,6 @@ #define D_SYSLOG_LOGGING_REENABLED "Syslog 日誌已開啟" #define D_SET_BAUDRATE_TO "設置波特率為:" -#define D_SET_SERIAL_CONFIG_TO "Set serial port mode to" #define D_RECEIVED_TOPIC "接收到的主題:" #define D_DATA_SIZE "數據大小:" #define D_ANALOG_INPUT "Analog" From 292698123bfada13d37f491ccf7cf970f47a1772 Mon Sep 17 00:00:00 2001 From: Luis Teixeira Date: Tue, 10 Mar 2020 23:33:09 +0000 Subject: [PATCH 10/20] Minor correction to the description. Slightly simplified declaration of the sensor in the support_features.ino. --- I2CDEVICES.md | 2 +- tasmota/support_features.ino | 8 ++------ 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/I2CDEVICES.md b/I2CDEVICES.md index 2a89ba8aa..7c1e4d772 100644 --- a/I2CDEVICES.md +++ b/I2CDEVICES.md @@ -66,4 +66,4 @@ Index | Define | Driver | Device | Address(es) | Description 42 | USE_DS1624 | xsns_59 | DS1624 | 0x48 - 0x4F | Temperature sensor 43 | USE_AHT1x | xsns_63 | AHT10/15 | 0x38 | Temperature and humidity sensor 44 | USE_WEMOS_MOTOR_V1 | xdrv_34 | | 0x2D - 0x30 | WEMOS motor shield v1.0.0 (6612FNG) - 92 | USE_HDC1080 | xsns_92 | HDC1080 | 0x40 | Digital Humidity Sensor with Temperature Sensor + 92 | USE_HDC1080 | xsns_92 | HDC1080 | 0x40 | Temperature and Humidity sensor diff --git a/tasmota/support_features.ino b/tasmota/support_features.ino index 213219621..0dd97f76f 100644 --- a/tasmota/support_features.ino +++ b/tasmota/support_features.ino @@ -254,8 +254,8 @@ void GetFeatures(void) #ifdef USE_SHT feature_sns1 |= 0x00000100; // xsns_07_sht1x.ino #endif -#ifdef USE_HTU - feature_sns1 |= 0x00000200; // xsns_08_htu21.ino +#if defined(USE_HTU) || defined(USE_HDC1080) + feature_sns1 |= 0x00000200; // xsns_08_htu21.ino or xsns_92_hdc1080.ino #endif #ifdef USE_BMP feature_sns1 |= 0x00000400; // xsns_09_bmp.ino @@ -323,10 +323,6 @@ void GetFeatures(void) #ifdef USE_TM1638 feature_sns1 |= 0x80000000; // xsns_28_tm1638.ino #endif -// TODO not sure if is the correct feature setting for this sensor: -#ifdef USE_HDC1080 - feature_sns1 |= 0x00000200; // xsns_92_hdc1080.ino -#endif /*********************************************************************************************/ feature_sns2 = 0x00000000; From b758699e39e9f1ee88f006b021d1fd2b249499e1 Mon Sep 17 00:00:00 2001 From: Luis Teixeira Date: Fri, 13 Mar 2020 00:46:25 +0000 Subject: [PATCH 11/20] Some corrections based on feedback from the project leads contributors. Improved runtime impact by replacing the sleep between the I2C operations with separate code triggered by timer events. --- I2CDEVICES.md | 2 +- tasmota/support_features.ino | 4 +- tasmota/tasmota_post.h | 2 +- ...sns_92_hdc1080.ino => xsns_65_hdc1080.ino} | 109 ++++++++++++++---- tools/decode-status.py | 2 +- 5 files changed, 90 insertions(+), 29 deletions(-) rename tasmota/{xsns_92_hdc1080.ino => xsns_65_hdc1080.ino} (73%) diff --git a/I2CDEVICES.md b/I2CDEVICES.md index 7c1e4d772..75c0a1a9a 100644 --- a/I2CDEVICES.md +++ b/I2CDEVICES.md @@ -66,4 +66,4 @@ Index | Define | Driver | Device | Address(es) | Description 42 | USE_DS1624 | xsns_59 | DS1624 | 0x48 - 0x4F | Temperature sensor 43 | USE_AHT1x | xsns_63 | AHT10/15 | 0x38 | Temperature and humidity sensor 44 | USE_WEMOS_MOTOR_V1 | xdrv_34 | | 0x2D - 0x30 | WEMOS motor shield v1.0.0 (6612FNG) - 92 | USE_HDC1080 | xsns_92 | HDC1080 | 0x40 | Temperature and Humidity sensor + 45 | USE_HDC1080 | xsns_65 | HDC1080 | 0x40 | Temperature and Humidity sensor diff --git a/tasmota/support_features.ino b/tasmota/support_features.ino index 0dd97f76f..410ae7bee 100644 --- a/tasmota/support_features.ino +++ b/tasmota/support_features.ino @@ -254,8 +254,8 @@ void GetFeatures(void) #ifdef USE_SHT feature_sns1 |= 0x00000100; // xsns_07_sht1x.ino #endif -#if defined(USE_HTU) || defined(USE_HDC1080) - feature_sns1 |= 0x00000200; // xsns_08_htu21.ino or xsns_92_hdc1080.ino +#ifdef USE_HTU + feature_sns1 |= 0x00000200; // xsns_08_htu21.ino #endif #ifdef USE_BMP feature_sns1 |= 0x00000400; // xsns_09_bmp.ino diff --git a/tasmota/tasmota_post.h b/tasmota/tasmota_post.h index 119ec70e4..dea6b1ca3 100644 --- a/tasmota/tasmota_post.h +++ b/tasmota/tasmota_post.h @@ -182,7 +182,7 @@ extern "C" void custom_crash_callback(struct rst_info * rst_info, uint32_t stack #define USE_DHT12 // Add I2C code for DHT12 temperature and humidity sensor (+0k7 code) #define USE_DS1624 // Add I2C code for DS1624, DS1621 sensor //#define USE_AHT1x // Enable AHT10/15 humidity and temperature sensor (I2C address 0x38) (+0k8 code) -#define USE_HDC1080 // Enable HDC1080 temperature/humidity sensor +//#define USE_HDC1080 // Enable HDC1080 temperature/humidity sensor #define USE_WEMOS_MOTOR_V1 // Enable Wemos motor driver V1 (I2C addresses 0x2D - 0x30) (+0k7 code) diff --git a/tasmota/xsns_92_hdc1080.ino b/tasmota/xsns_65_hdc1080.ino similarity index 73% rename from tasmota/xsns_92_hdc1080.ino rename to tasmota/xsns_65_hdc1080.ino index f5cd385b1..8e5538b9d 100644 --- a/tasmota/xsns_92_hdc1080.ino +++ b/tasmota/xsns_65_hdc1080.ino @@ -19,6 +19,7 @@ #ifdef USE_I2C #ifdef USE_HDC1080 + /*********************************************************************************************\ * HDC1080 - Temperature and Humidy sensor * @@ -27,8 +28,8 @@ * I2C Address: 0x40 \*********************************************************************************************/ -#define XSNS_92 92 -#define XI2C_92 92 // See I2CDEVICES.md +#define XSNS_65 65 +#define XI2C_45 45 // See I2CDEVICES.md #define HDC1080_ADDR 0x40 @@ -59,7 +60,7 @@ // Constants: -#define HDC1080_CONV_TIME 50 // Assume 6.50 + 6.35 ms + x of conversion delay for this device +#define HDC1080_CONV_TIME 80 // Assume 6.50 + 6.35 ms + x of conversion delay for this device #define HDC1080_TEMP_MULT 0.0025177 #define HDC1080_RH_MULT 0.0025177 #define HDC1080_TEMP_OFFSET 40.0 @@ -74,6 +75,9 @@ float hdc_humidity = 0.0; uint8_t hdc_valid = 0; +bool is_reading = false; +uint32_t timer = millis() + HDC1080_CONV_TIME; + /** * Reads the device ID register. * @@ -117,18 +121,32 @@ void HdcReset(void) { } /** - * Performs the single transaction read of the HDC1080, providing the - * adequate delay for the acquisition. + * Performs the write portion of the HDC1080 sensor transaction. This + * action of writing to a register signals the beginning of the operation + * (e.g. data acquisition). * + * addr: the address of the I2C device we are talking to. + * reg: the register where we are writing to. + * + * returns: 0 if the transmission was successfully completed, != 0 otherwise. */ -int8_t HdcReadBuffer(uint8_t addr, uint8_t reg, uint8_t *reg_data, uint16_t len) { - Wire.beginTransmission((uint8_t)addr); - Wire.write((uint8_t)reg); - Wire.endTransmission(); +int8_t HdcTransactionOpen(uint8_t addr, uint8_t reg) { + Wire.beginTransmission((uint8_t) addr); + Wire.write((uint8_t) reg); + return Wire.endTransmission(); +} - delay(HDC1080_CONV_TIME); - - if (len != Wire.requestFrom((uint8_t)addr, (uint8_t)len)) { +/** + * Performs the read portion of the HDC1080 sensor transaction. + * + * addr: the address of the I2C device we are talking to. + * reg_data: the pointer to the memory location where we will place the bytes that were read from the device + * len: the number of bytes we expect to read + * + * returns: if the read operation was successful. != 0 otherwise. + */ +int8_t HdcTransactionClose(uint8_t addr, uint8_t *reg_data, uint16_t len) { + if (len != Wire.requestFrom((uint8_t) addr, (uint8_t) len)) { return 1; } @@ -149,11 +167,31 @@ void HdcInit(void) { HdcConfig(HDC1080_MODE_ON); } +/** + * Triggers the single transaction read of the T/RH sensor. + * + */ +bool HdcTriggerRead(void) { + int8_t status = HdcTransactionOpen(HDC1080_ADDR, HDC_REG_TEMP); + + if(status) { + AddLog_P2(LOG_LEVEL_DEBUG, PSTR("HdcTriggerRead: failed to open the transaction for HDC_REG_TEMP. Status = %d"), status); + + return false; + } + + is_reading = true; + + return true; +} + /** * Performs a temperature and humidity measurement, and calls * the conversion function providing the results in the correct * unit according to the device settings. * + * returns: false if something failed during the read process. + * */ bool HdcRead(void) { int8_t status = 0; @@ -161,18 +199,20 @@ bool HdcRead(void) { uint16_t temp_data = 0; uint16_t rh_data = 0; - status = HdcReadBuffer(HDC1080_ADDR, HDC_REG_TEMP, sensor_data, 4); + is_reading = false; + + status = HdcTransactionClose(HDC1080_ADDR, sensor_data, 4); + + if(status) { + AddLog_P2(LOG_LEVEL_DEBUG, PSTR("HdcRead: failed to read HDC_REG_TEMP. Status = %d"), status); + + return false; + } temp_data = (uint16_t) ((sensor_data[0] << 8) | sensor_data[1]); rh_data = (uint16_t) ((sensor_data[2] << 8) | sensor_data[3]); AddLog_P2(LOG_LEVEL_DEBUG, PSTR("HdcRead: temperature raw data: 0x%04x; humidity raw data: 0x%04x"), temp_data, rh_data); - - if(status != 0) { - AddLog_P2(LOG_LEVEL_DEBUG, PSTR("HdcRead: failed to read HDC_REG_TEMP. Status = %d"), status); - - return false; - } // read the temperature from the first 16 bits of the result @@ -190,7 +230,10 @@ bool HdcRead(void) { return true; } -/********************************************************************************************/ +/** + * Performs the detection of the HTC1080 sensor. + * + */ void HdcDetect(void) { if (I2cActive(HDC1080_ADDR)) { @@ -210,14 +253,24 @@ void HdcDetect(void) { } } +/** + * As the name suggests, this function is called every second + * for performing driver related logic. + * + */ void HdcEverySecond(void) { if (uptime &1) { // Every 2 seconds - if (!HdcRead()) { + if (!HdcTriggerRead()) { AddLogMissed((char*) hdc_type_name, hdc_valid); } } } +/** + * Tasmota boilerplate for presenting the sensor data in the web UI, JSON for + * the MQTT messages, and so on. + * + */ void HdcShow(bool json) { if (hdc_valid) { char temperature[33]; @@ -252,10 +305,10 @@ void HdcShow(bool json) { * Interface \*********************************************************************************************/ -bool Xsns92(uint8_t function) +bool Xsns65(uint8_t function) { - if (!I2cEnabled(XI2C_92)) { - AddLog_P(LOG_LEVEL_DEBUG, PSTR("Xsns92: I2C driver not enabled for this device.")); + if (!I2cEnabled(XI2C_45)) { + AddLog_P(LOG_LEVEL_DEBUG, PSTR("Xsns65: I2C driver not enabled for this device.")); return false; } @@ -267,6 +320,14 @@ bool Xsns92(uint8_t function) } else if (hdc_device_id) { switch (function) { + case FUNC_EVERY_50_MSECOND: + if(is_reading && TimeReached(timer)) { + if(!HdcRead()) { + AddLogMissed((char*) hdc_type_name, hdc_valid); + } + timer = millis() + HDC1080_CONV_TIME; + } + break; case FUNC_EVERY_SECOND: HdcEverySecond(); break; diff --git a/tools/decode-status.py b/tools/decode-status.py index 232cebc07..c9ba04f6d 100755 --- a/tools/decode-status.py +++ b/tools/decode-status.py @@ -178,7 +178,7 @@ a_features = [[ "USE_INA219","USE_SHT3X","USE_MHZ19","USE_TSL2561", "USE_SENSEAIR","USE_PMS5003","USE_MGS","USE_NOVA_SDS", "USE_SGP30","USE_SR04","USE_SDM120","USE_SI1145", - "USE_SDM630","USE_LM75AD","USE_APDS9960","USE_TM1638", "USE_HDC1080" + "USE_SDM630","USE_LM75AD","USE_APDS9960","USE_TM1638", ],[ "USE_MCP230xx","USE_MPR121","USE_CCS811","USE_MPU6050", "USE_MCP230xx_OUTPUT","USE_MCP230xx_DISPLAYOUTPUT","USE_HLW8012","USE_CSE7766", From 50d63f867808daf453d644d7035a59771f792d1a Mon Sep 17 00:00:00 2001 From: Paul C Diem Date: Fri, 13 Mar 2020 16:53:27 -0500 Subject: [PATCH 12/20] Only set power for devices included in updates --- tasmota/support_device_groups.ino | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tasmota/support_device_groups.ino b/tasmota/support_device_groups.ino index d0844de7a..f90e07c94 100644 --- a/tasmota/support_device_groups.ino +++ b/tasmota/support_device_groups.ino @@ -333,7 +333,7 @@ void _SendDeviceGroupMessage(uint8_t device_group_index, DeviceGroupMessageType if (item > DGR_ITEM_MAX_16BIT) { value >>= 8; *message_ptr++ = value & 0xff; - *message_ptr++ = value >> 8; + *message_ptr++ = (item == DGR_ITEM_POWER ? devices_present : value >> 8); } } } @@ -590,6 +590,8 @@ void ProcessDeviceGroupMessage(char * packet, int packet_length) if (DeviceGroupItemShared(true, item)) { if (item == DGR_ITEM_POWER) { + uint8_t mask_devices = value >> 24; + if (mask_devices > devices_present) mask_devices = devices_present; for (uint32_t i = 0; i < devices_present; i++) { uint32_t mask = 1 << i; bool on = (value & mask); From 2441acdc023484529e38fef6f6c383690d557690 Mon Sep 17 00:00:00 2001 From: Luis Teixeira Date: Fri, 13 Mar 2020 22:40:33 +0000 Subject: [PATCH 13/20] Fixed the sensor read errors that were due to misplaced timer variable initializations. --- tasmota/xsns_65_hdc1080.ino | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/tasmota/xsns_65_hdc1080.ino b/tasmota/xsns_65_hdc1080.ino index 8e5538b9d..74de68383 100644 --- a/tasmota/xsns_65_hdc1080.ino +++ b/tasmota/xsns_65_hdc1080.ino @@ -60,12 +60,11 @@ // Constants: -#define HDC1080_CONV_TIME 80 // Assume 6.50 + 6.35 ms + x of conversion delay for this device +#define HDC1080_CONV_TIME 15 // Assume 6.50 + 6.35 ms + x of conversion delay for this device #define HDC1080_TEMP_MULT 0.0025177 #define HDC1080_RH_MULT 0.0025177 #define HDC1080_TEMP_OFFSET 40.0 - const char* hdc_type_name = "HDC1080"; uint16_t hdc_manufacturer_id = 0; uint16_t hdc_device_id = 0; @@ -76,7 +75,7 @@ float hdc_humidity = 0.0; uint8_t hdc_valid = 0; bool is_reading = false; -uint32_t timer = millis() + HDC1080_CONV_TIME; +uint32_t hdc_next_read; /** * Reads the device ID register. @@ -174,6 +173,8 @@ void HdcInit(void) { bool HdcTriggerRead(void) { int8_t status = HdcTransactionOpen(HDC1080_ADDR, HDC_REG_TEMP); + hdc_next_read = millis() + HDC1080_CONV_TIME; + if(status) { AddLog_P2(LOG_LEVEL_DEBUG, PSTR("HdcTriggerRead: failed to open the transaction for HDC_REG_TEMP. Status = %d"), status); @@ -321,11 +322,10 @@ bool Xsns65(uint8_t function) else if (hdc_device_id) { switch (function) { case FUNC_EVERY_50_MSECOND: - if(is_reading && TimeReached(timer)) { + if(is_reading && TimeReached(hdc_next_read)) { if(!HdcRead()) { AddLogMissed((char*) hdc_type_name, hdc_valid); } - timer = millis() + HDC1080_CONV_TIME; } break; case FUNC_EVERY_SECOND: From a5ebdd34759dc65d4cbf5943ae686db2953653eb Mon Sep 17 00:00:00 2001 From: Theo Arends <11044339+arendst@users.noreply.github.com> Date: Sat, 14 Mar 2020 09:52:33 +0100 Subject: [PATCH 14/20] Update decode-status.py --- tools/decode-status.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/decode-status.py b/tools/decode-status.py index c9ba04f6d..fe80630cc 100755 --- a/tools/decode-status.py +++ b/tools/decode-status.py @@ -178,7 +178,7 @@ a_features = [[ "USE_INA219","USE_SHT3X","USE_MHZ19","USE_TSL2561", "USE_SENSEAIR","USE_PMS5003","USE_MGS","USE_NOVA_SDS", "USE_SGP30","USE_SR04","USE_SDM120","USE_SI1145", - "USE_SDM630","USE_LM75AD","USE_APDS9960","USE_TM1638", + "USE_SDM630","USE_LM75AD","USE_APDS9960","USE_TM1638" ],[ "USE_MCP230xx","USE_MPR121","USE_CCS811","USE_MPU6050", "USE_MCP230xx_OUTPUT","USE_MCP230xx_DISPLAYOUTPUT","USE_HLW8012","USE_CSE7766", From 0f157caa0532f6811c8e58a5cff3579829182167 Mon Sep 17 00:00:00 2001 From: Leonid Muravjev Date: Sat, 14 Mar 2020 13:41:57 +0300 Subject: [PATCH 15/20] switch: New mode PUSHON (13) Just turn it on, if the switch is on. Switch off by PulseTime. For a simple implementation processing of PIR sensors. --- tasmota/support_switch.ino | 5 ++++- tasmota/tasmota.h | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/tasmota/support_switch.ino b/tasmota/support_switch.ino index e873ea200..e0be915e9 100644 --- a/tasmota/support_switch.ino +++ b/tasmota/support_switch.ino @@ -188,7 +188,7 @@ void SwitchHandler(uint8_t mode) } } -// enum SwitchModeOptions {TOGGLE, FOLLOW, FOLLOW_INV, PUSHBUTTON, PUSHBUTTON_INV, PUSHBUTTONHOLD, PUSHBUTTONHOLD_INV, PUSHBUTTON_TOGGLE, TOGGLEMULTI, FOLLOWMULTI, FOLLOWMULTI_INV, PUSHHOLDMULTI, PUSHHOLDMULTI_INV, MAX_SWITCH_OPTION}; +// enum SwitchModeOptions {TOGGLE, FOLLOW, FOLLOW_INV, PUSHBUTTON, PUSHBUTTON_INV, PUSHBUTTONHOLD, PUSHBUTTONHOLD_INV, PUSHBUTTON_TOGGLE, TOGGLEMULTI, FOLLOWMULTI, FOLLOWMULTI_INV, PUSHHOLDMULTI, PUSHHOLDMULTI_INV, PUSHON, MAX_SWITCH_OPTION}; if (button != Switch.last_state[i]) { switch (Settings.switchmode[i]) { @@ -276,6 +276,9 @@ void SwitchHandler(uint8_t mode) Switch.hold_timer[i] = loops_per_second * Settings.param[P_HOLD_TIME] / 10; } break; + case PUSHON: + if (PRESSED == button) switchflag = POWER_ON; // Power ON with pushbutton to Gnd + break; } Switch.last_state[i] = button; } diff --git a/tasmota/tasmota.h b/tasmota/tasmota.h index 664446502..919193f09 100644 --- a/tasmota/tasmota.h +++ b/tasmota/tasmota.h @@ -233,7 +233,7 @@ enum LoggingLevels {LOG_LEVEL_NONE, LOG_LEVEL_ERROR, LOG_LEVEL_INFO, LOG_LEVEL_D enum WifiConfigOptions {WIFI_RESTART, EX_WIFI_SMARTCONFIG, WIFI_MANAGER, EX_WIFI_WPSCONFIG, WIFI_RETRY, WIFI_WAIT, WIFI_SERIAL, WIFI_MANAGER_RESET_ONLY, MAX_WIFI_OPTION}; enum SwitchModeOptions {TOGGLE, FOLLOW, FOLLOW_INV, PUSHBUTTON, PUSHBUTTON_INV, PUSHBUTTONHOLD, PUSHBUTTONHOLD_INV, PUSHBUTTON_TOGGLE, TOGGLEMULTI, - FOLLOWMULTI, FOLLOWMULTI_INV, PUSHHOLDMULTI, PUSHHOLDMULTI_INV, MAX_SWITCH_OPTION}; + FOLLOWMULTI, FOLLOWMULTI_INV, PUSHHOLDMULTI, PUSHHOLDMULTI_INV, PUSHON, MAX_SWITCH_OPTION}; enum LedStateOptions {LED_OFF, LED_POWER, LED_MQTTSUB, LED_POWER_MQTTSUB, LED_MQTTPUB, LED_POWER_MQTTPUB, LED_MQTT, LED_POWER_MQTT, MAX_LED_OPTION}; From 5235ad1757ef5a584b8e71e39aed7bab9770795c Mon Sep 17 00:00:00 2001 From: Theo Arends <11044339+arendst@users.noreply.github.com> Date: Sat, 14 Mar 2020 12:43:02 +0100 Subject: [PATCH 16/20] Add support for HDC1080 Add support for HDC1080 Temperature and Humidity sensor by Luis Teixeira (#7888) --- RELEASENOTES.md | 1 + tasmota/CHANGELOG.md | 1 + tasmota/my_user_config.h | 3 +-- tasmota/support_features.ino | 5 +++- tasmota/tasmota_post.h | 4 +-- tasmota/xsns_65_hdc1080.ino | 50 ++++++++++++++++++------------------ tools/decode-status.py | 4 +-- 7 files changed, 35 insertions(+), 33 deletions(-) diff --git a/RELEASENOTES.md b/RELEASENOTES.md index 0a6e1fbcb..c318212f9 100644 --- a/RELEASENOTES.md +++ b/RELEASENOTES.md @@ -117,3 +117,4 @@ The following binary downloads have been compiled with ESP8266/Arduino library c - Add support for MaxBotix HRXL-MaxSonar ultrasonic range finders by Jon Little (#7814) - Add support for Romanian language translations by Augustin Marti - Add HAss Discovery support for Button and Switch triggers by Federico Leoni (#7901) +- Add support for HDC1080 Temperature and Humidity sensor by Luis Teixeira (#7888) diff --git a/tasmota/CHANGELOG.md b/tasmota/CHANGELOG.md index 11d730543..cf8694d55 100644 --- a/tasmota/CHANGELOG.md +++ b/tasmota/CHANGELOG.md @@ -3,6 +3,7 @@ ### 8.1.0.11 20200313 - Add HAss Discovery support for Button and Switch triggers by Federico Leoni (#7901) +- Add support for HDC1080 Temperature and Humidity sensor by Luis Teixeira (#7888) ### 8.1.0.10 20200227 diff --git a/tasmota/my_user_config.h b/tasmota/my_user_config.h index 40cbb5ce4..a65924cdf 100644 --- a/tasmota/my_user_config.h +++ b/tasmota/my_user_config.h @@ -494,10 +494,9 @@ // #define USE_DS1624 // [I2cDriver42] Enable DS1624, DS1621 temperature sensor (I2C addresses 0x48 - 0x4F) (+1k2 code) // #define USE_AHT1x // [I2cDriver43] Enable AHT10/15 humidity and temperature sensor (I2C address 0x38) (+0k8 code) // #define USE_WEMOS_MOTOR_V1 // [I2cDriver44] Enable Wemos motor driver V1 (I2C addresses 0x2D - 0x30) (+0k7 code) -// #define USE_HDC1080 // [I2cDriver92] Enable HDC1080 temperature/humidity sensor - // #define WEMOS_MOTOR_V1_ADDR 0x30 // Default I2C address 0x30 // #define WEMOS_MOTOR_V1_FREQ 1000 // Default frequency +// #define USE_HDC1080 // [I2cDriver45] Enable HDC1080 temperature/humidity sensor (I2C address 0x40) (+1k5 code) // #define USE_DISPLAY // Add I2C Display Support (+2k code) #define USE_DISPLAY_MODES1TO5 // Enable display mode 1 to 5 in addition to mode 0 diff --git a/tasmota/support_features.ino b/tasmota/support_features.ino index 410ae7bee..201711e48 100644 --- a/tasmota/support_features.ino +++ b/tasmota/support_features.ino @@ -323,6 +323,7 @@ void GetFeatures(void) #ifdef USE_TM1638 feature_sns1 |= 0x80000000; // xsns_28_tm1638.ino #endif + /*********************************************************************************************/ feature_sns2 = 0x00000000; @@ -538,7 +539,9 @@ void GetFeatures(void) #ifdef USE_SONOFF_D1 feature6 |= 0x00000004; // xdrv_37_sonoff_d1.ino #endif -// feature6 |= 0x00000008; +#ifdef USE_HDC1080 + feature6 |= 0x00000008; // xsns_65_hdc1080.ino +#endif // feature6 |= 0x00000010; // feature6 |= 0x00000020; diff --git a/tasmota/tasmota_post.h b/tasmota/tasmota_post.h index dea6b1ca3..1abd371ff 100644 --- a/tasmota/tasmota_post.h +++ b/tasmota/tasmota_post.h @@ -182,12 +182,10 @@ extern "C" void custom_crash_callback(struct rst_info * rst_info, uint32_t stack #define USE_DHT12 // Add I2C code for DHT12 temperature and humidity sensor (+0k7 code) #define USE_DS1624 // Add I2C code for DS1624, DS1621 sensor //#define USE_AHT1x // Enable AHT10/15 humidity and temperature sensor (I2C address 0x38) (+0k8 code) -//#define USE_HDC1080 // Enable HDC1080 temperature/humidity sensor - - #define USE_WEMOS_MOTOR_V1 // Enable Wemos motor driver V1 (I2C addresses 0x2D - 0x30) (+0k7 code) #define WEMOS_MOTOR_V1_ADDR 0x30 // Default I2C address 0x30 #define WEMOS_MOTOR_V1_FREQ 1000 // Default frequency +//#define USE_HDC1080 // Enable HDC1080 temperature/humidity sensor #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) diff --git a/tasmota/xsns_65_hdc1080.ino b/tasmota/xsns_65_hdc1080.ino index 74de68383..59f0f75f2 100644 --- a/tasmota/xsns_65_hdc1080.ino +++ b/tasmota/xsns_65_hdc1080.ino @@ -1,5 +1,5 @@ /* - xsns_92_hdc1080.ino - Texas Instruments HDC1080 temperature and humidity sensor support for Tasmota + xsns_65_hdc1080.ino - Texas Instruments HDC1080 temperature and humidity sensor support for Tasmota Copyright (C) 2020 Luis Teixeira @@ -79,7 +79,7 @@ uint32_t hdc_next_read; /** * Reads the device ID register. - * + * */ uint16_t HdcReadDeviceId(void) { return I2cRead16(HDC1080_ADDR, HDC_REG_DEV_ID); @@ -87,7 +87,7 @@ uint16_t HdcReadDeviceId(void) { /** * Reads the manufacturer ID register. - * + * */ uint16_t HdcReadManufacturerId(void) { return I2cRead16(HDC1080_ADDR, HDC_REG_MAN_ID); @@ -102,13 +102,13 @@ void HdcConfig(uint16_t config) { /** * Performs a soft reset on the device. - * + * * RST = 1 -> software reset - * + * */ void HdcReset(void) { uint16_t current = I2cRead16(HDC1080_ADDR, HDC_REG_CONFIG); - + // bit 15 of the configuration register contains the RST flag // so we set it to 1: @@ -120,13 +120,13 @@ void HdcReset(void) { } /** - * Performs the write portion of the HDC1080 sensor transaction. This + * Performs the write portion of the HDC1080 sensor transaction. This * action of writing to a register signals the beginning of the operation * (e.g. data acquisition). - * + * * addr: the address of the I2C device we are talking to. * reg: the register where we are writing to. - * + * * returns: 0 if the transmission was successfully completed, != 0 otherwise. */ int8_t HdcTransactionOpen(uint8_t addr, uint8_t reg) { @@ -137,11 +137,11 @@ int8_t HdcTransactionOpen(uint8_t addr, uint8_t reg) { /** * Performs the read portion of the HDC1080 sensor transaction. - * + * * addr: the address of the I2C device we are talking to. * reg_data: the pointer to the memory location where we will place the bytes that were read from the device * len: the number of bytes we expect to read - * + * * returns: if the read operation was successful. != 0 otherwise. */ int8_t HdcTransactionClose(uint8_t addr, uint8_t *reg_data, uint16_t len) { @@ -159,7 +159,7 @@ int8_t HdcTransactionClose(uint8_t addr, uint8_t *reg_data, uint16_t len) { /** * The various initialization steps for this sensor. - * + * */ void HdcInit(void) { HdcReset(); @@ -168,7 +168,7 @@ void HdcInit(void) { /** * Triggers the single transaction read of the T/RH sensor. - * + * */ bool HdcTriggerRead(void) { int8_t status = HdcTransactionOpen(HDC1080_ADDR, HDC_REG_TEMP); @@ -190,9 +190,9 @@ bool HdcTriggerRead(void) { * Performs a temperature and humidity measurement, and calls * the conversion function providing the results in the correct * unit according to the device settings. - * + * * returns: false if something failed during the read process. - * + * */ bool HdcRead(void) { int8_t status = 0; @@ -233,14 +233,14 @@ bool HdcRead(void) { /** * Performs the detection of the HTC1080 sensor. - * + * */ void HdcDetect(void) { - if (I2cActive(HDC1080_ADDR)) { - AddLog_P2(LOG_LEVEL_DEBUG, PSTR("HdcDetect: Address = 0x%02X already in use."), HDC1080_ADDR); + if (I2cActive(HDC1080_ADDR)) { +// AddLog_P2(LOG_LEVEL_DEBUG, PSTR("HdcDetect: Address = 0x%02X already in use."), HDC1080_ADDR); - return; + return; } hdc_manufacturer_id = HdcReadManufacturerId(); @@ -257,7 +257,7 @@ void HdcDetect(void) { /** * As the name suggests, this function is called every second * for performing driver related logic. - * + * */ void HdcEverySecond(void) { if (uptime &1) { // Every 2 seconds @@ -268,9 +268,9 @@ void HdcEverySecond(void) { } /** - * Tasmota boilerplate for presenting the sensor data in the web UI, JSON for + * Tasmota boilerplate for presenting the sensor data in the web UI, JSON for * the MQTT messages, and so on. - * + * */ void HdcShow(bool json) { if (hdc_valid) { @@ -308,10 +308,10 @@ void HdcShow(bool json) { bool Xsns65(uint8_t function) { - if (!I2cEnabled(XI2C_45)) { - AddLog_P(LOG_LEVEL_DEBUG, PSTR("Xsns65: I2C driver not enabled for this device.")); + if (!I2cEnabled(XI2C_45)) { +// AddLog_P(LOG_LEVEL_DEBUG, PSTR("Xsns65: I2C driver not enabled for this device.")); - return false; + return false; } bool result = false; diff --git a/tools/decode-status.py b/tools/decode-status.py index fe80630cc..25af64a97 100755 --- a/tools/decode-status.py +++ b/tools/decode-status.py @@ -198,7 +198,7 @@ a_features = [[ "USE_NRF24","USE_MIBLE","USE_HM10","USE_LE01MR", "USE_AHT1x","USE_WEMOS_MOTOR_V1","USE_DEVICE_GROUPS","USE_PWM_DIMMER" ],[ - "USE_KEELOQ","USE_HRXL","USE_SONOFF_D1","", + "USE_KEELOQ","USE_HRXL","USE_SONOFF_D1","USE_HDC1080", "","","","", "","","","", "","","","", @@ -239,7 +239,7 @@ else: obj = json.load(fp) def StartDecode(): - print ("\n*** decode-status.py v20200305 by Theo Arends and Jacek Ziolkowski ***") + print ("\n*** decode-status.py v20200314 by Theo Arends and Jacek Ziolkowski ***") # print("Decoding\n{}".format(obj)) From d043ac770d47801dc20a59066ee96e30250c54d4 Mon Sep 17 00:00:00 2001 From: Theo Arends <11044339+arendst@users.noreply.github.com> Date: Sat, 14 Mar 2020 13:13:33 +0100 Subject: [PATCH 17/20] Refactor support_switche.ino - Add commands ``SwitchMode 13`` PushOn and ``SwitchMode 14`` PushOnInverted (#7912) - Refactor support_switche.ino --- RELEASENOTES.md | 1 + tasmota/CHANGELOG.md | 1 + tasmota/support_switch.ino | 73 ++++++++++++++++++++++++-------------- tasmota/tasmota.h | 4 +-- 4 files changed, 50 insertions(+), 29 deletions(-) diff --git a/RELEASENOTES.md b/RELEASENOTES.md index c318212f9..a2757b96f 100644 --- a/RELEASENOTES.md +++ b/RELEASENOTES.md @@ -87,6 +87,7 @@ The following binary downloads have been compiled with ESP8266/Arduino library c - Add command ``ShutterButton `` to control shutter(s) by to-scho (#7403) - Add commands ``SwitchMode 8`` ToggleMulti, ``SwitchMode 9`` FollowMulti and ``SwitchMode 10`` FollowMultiInverted (#7522) - Add commands ``SwitchMode 11`` PushHoldMulti and ``SwitchMode 12`` PushHoldInverted (#7603) +- Add commands ``SwitchMode 13`` PushOn and ``SwitchMode 14`` PushOnInverted (#7912) - Add command ``Buzzer -1`` for infinite mode and command ``Buzzer -2`` for following led mode (#7623) - Add SerialConfig to ``Status 1`` - Add WifiPower to ``Status 5`` diff --git a/tasmota/CHANGELOG.md b/tasmota/CHANGELOG.md index cf8694d55..2c23efc42 100644 --- a/tasmota/CHANGELOG.md +++ b/tasmota/CHANGELOG.md @@ -4,6 +4,7 @@ - Add HAss Discovery support for Button and Switch triggers by Federico Leoni (#7901) - Add support for HDC1080 Temperature and Humidity sensor by Luis Teixeira (#7888) +- Add commands ``SwitchMode 13`` PushOn and ``SwitchMode 14`` PushOnInverted (#7912) ### 8.1.0.10 20200227 diff --git a/tasmota/support_switch.ino b/tasmota/support_switch.ino index e0be915e9..7acdda409 100644 --- a/tasmota/support_switch.ino +++ b/tasmota/support_switch.ino @@ -17,8 +17,8 @@ along with this program. If not, see . */ -#define SWITCH_V2 -#ifdef SWITCH_V2 +#define SWITCH_V3 +#ifdef SWITCH_V3 /*********************************************************************************************\ * Switch support with input filter * @@ -166,20 +166,20 @@ void SwitchHandler(uint8_t mode) switchflag = ~button &1; // Follow inverted wall switch state after hold break; case PUSHHOLDMULTI: - if (NOT_PRESSED == button){ + if (NOT_PRESSED == button) { Switch.hold_timer[i] = loops_per_second * Settings.param[P_HOLD_TIME] / 25; SendKey(KEY_SWITCH, i +1, POWER_INCREMENT); // Execute command via MQTT - } - else + } else { SendKey(KEY_SWITCH, i +1, POWER_CLEAR); // Execute command via MQTT + } break; case PUSHHOLDMULTI_INV: - if (PRESSED == button){ + if (PRESSED == button) { Switch.hold_timer[i] = loops_per_second * Settings.param[P_HOLD_TIME] / 25; SendKey(KEY_SWITCH, i +1, POWER_INCREMENT); // Execute command via MQTT - } - else + } else { SendKey(KEY_SWITCH, i +1, POWER_CLEAR); // Execute command via MQTT + } break; default: SendKey(KEY_SWITCH, i +1, POWER_HOLD); // Execute command via MQTT @@ -188,9 +188,7 @@ void SwitchHandler(uint8_t mode) } } -// enum SwitchModeOptions {TOGGLE, FOLLOW, FOLLOW_INV, PUSHBUTTON, PUSHBUTTON_INV, PUSHBUTTONHOLD, PUSHBUTTONHOLD_INV, PUSHBUTTON_TOGGLE, TOGGLEMULTI, FOLLOWMULTI, FOLLOWMULTI_INV, PUSHHOLDMULTI, PUSHHOLDMULTI_INV, PUSHON, MAX_SWITCH_OPTION}; - - if (button != Switch.last_state[i]) { + if (button != Switch.last_state[i]) { // This implies if ((PRESSED == button) then (NOT_PRESSED == Switch.last_state[i])) switch (Settings.switchmode[i]) { case TOGGLE: case PUSHBUTTON_TOGGLE: @@ -203,29 +201,35 @@ void SwitchHandler(uint8_t mode) switchflag = ~button &1; // Follow inverted wall switch state break; case PUSHBUTTON: - if ((PRESSED == button) && (NOT_PRESSED == Switch.last_state[i])) { +// if ((PRESSED == button) && (NOT_PRESSED == Switch.last_state[i])) { + if (PRESSED == button) { switchflag = POWER_TOGGLE; // Toggle with pushbutton to Gnd } break; case PUSHBUTTON_INV: - if ((NOT_PRESSED == button) && (PRESSED == Switch.last_state[i])) { +// if ((NOT_PRESSED == button) && (PRESSED == Switch.last_state[i])) { + if (NOT_PRESSED == button) { switchflag = POWER_TOGGLE; // Toggle with releasing pushbutton from Gnd } break; case PUSHBUTTONHOLD: - if ((PRESSED == button) && (NOT_PRESSED == Switch.last_state[i])) { +// if ((PRESSED == button) && (NOT_PRESSED == Switch.last_state[i])) { + if (PRESSED == button) { Switch.hold_timer[i] = loops_per_second * Settings.param[P_HOLD_TIME] / 10; // Start timer on button press } - if ((NOT_PRESSED == button) && (PRESSED == Switch.last_state[i]) && (Switch.hold_timer[i])) { +// if ((NOT_PRESSED == button) && (PRESSED == Switch.last_state[i]) && (Switch.hold_timer[i])) { + if ((NOT_PRESSED == button) && (Switch.hold_timer[i])) { Switch.hold_timer[i] = 0; // Button released and hold timer not expired : stop timer... switchflag = POWER_TOGGLE; // ...and Toggle } break; case PUSHBUTTONHOLD_INV: - if ((NOT_PRESSED == button) && (PRESSED == Switch.last_state[i])) { +// if ((NOT_PRESSED == button) && (PRESSED == Switch.last_state[i])) { + if (NOT_PRESSED == button) { Switch.hold_timer[i] = loops_per_second * Settings.param[P_HOLD_TIME] / 10; // Start timer on button press... } - if ((PRESSED == button) && (NOT_PRESSED == Switch.last_state[i]) && (Switch.hold_timer[i])) { +// if ((PRESSED == button) && (NOT_PRESSED == Switch.last_state[i]) && (Switch.hold_timer[i])) { + if ((PRESSED == button) && (Switch.hold_timer[i])) { Switch.hold_timer[i] = 0; // Button released and hold timer not expired : stop timer. switchflag = POWER_TOGGLE; // ...and Toggle } @@ -253,31 +257,46 @@ void SwitchHandler(uint8_t mode) } break; case PUSHHOLDMULTI: - if ((NOT_PRESSED == button) && (PRESSED == Switch.last_state[i])) { - if(Switch.hold_timer[i]!=0) +// if ((NOT_PRESSED == button) && (PRESSED == Switch.last_state[i])) { + if (NOT_PRESSED == button) { + if (Switch.hold_timer[i] != 0) { SendKey(KEY_SWITCH, i +1, POWER_INV); // Execute command via MQTT + } Switch.hold_timer[i] = loops_per_second * Settings.param[P_HOLD_TIME] / 10; } - if ((PRESSED == button) && (NOT_PRESSED == Switch.last_state[i])) { - if(Switch.hold_timer[i] > loops_per_second * Settings.param[P_HOLD_TIME] / 25) +// if ((PRESSED == button) && (NOT_PRESSED == Switch.last_state[i])) { + if (PRESSED == button) { + if (Switch.hold_timer[i] > loops_per_second * Settings.param[P_HOLD_TIME] / 25) { switchflag = POWER_TOGGLE; // Toggle with pushbutton + } Switch.hold_timer[i] = loops_per_second * Settings.param[P_HOLD_TIME] / 10; } break; case PUSHHOLDMULTI_INV: - if ((PRESSED == button) && (NOT_PRESSED == Switch.last_state[i])) { - if(Switch.hold_timer[i]!=0) +// if ((PRESSED == button) && (NOT_PRESSED == Switch.last_state[i])) { + if (PRESSED == button) { + if (Switch.hold_timer[i] != 0) { SendKey(KEY_SWITCH, i +1, POWER_INV); // Execute command via MQTT + } Switch.hold_timer[i] = loops_per_second * Settings.param[P_HOLD_TIME] / 10; } - if ((NOT_PRESSED == button) && (PRESSED == Switch.last_state[i])) { - if(Switch.hold_timer[i] > loops_per_second * Settings.param[P_HOLD_TIME] / 25) +// if ((NOT_PRESSED == button) && (PRESSED == Switch.last_state[i])) { + if (NOT_PRESSED == button) { + if (Switch.hold_timer[i] > loops_per_second * Settings.param[P_HOLD_TIME] / 25) { switchflag = POWER_TOGGLE; // Toggle with pushbutton + } Switch.hold_timer[i] = loops_per_second * Settings.param[P_HOLD_TIME] / 10; } break; case PUSHON: - if (PRESSED == button) switchflag = POWER_ON; // Power ON with pushbutton to Gnd + if (PRESSED == button) { + switchflag = POWER_ON; // Power ON with pushbutton to Gnd + } + break; + case PUSHON_INV: + if (NOT_PRESSED == button) { + switchflag = POWER_ON; // Power ON with releasing pushbutton from Gnd + } break; } Switch.last_state[i] = button; @@ -301,4 +320,4 @@ void SwitchLoop(void) } } -#endif // SWITCH_V2 +#endif // SWITCH_V3 diff --git a/tasmota/tasmota.h b/tasmota/tasmota.h index 919193f09..6e9c8ac29 100644 --- a/tasmota/tasmota.h +++ b/tasmota/tasmota.h @@ -233,7 +233,7 @@ enum LoggingLevels {LOG_LEVEL_NONE, LOG_LEVEL_ERROR, LOG_LEVEL_INFO, LOG_LEVEL_D enum WifiConfigOptions {WIFI_RESTART, EX_WIFI_SMARTCONFIG, WIFI_MANAGER, EX_WIFI_WPSCONFIG, WIFI_RETRY, WIFI_WAIT, WIFI_SERIAL, WIFI_MANAGER_RESET_ONLY, MAX_WIFI_OPTION}; enum SwitchModeOptions {TOGGLE, FOLLOW, FOLLOW_INV, PUSHBUTTON, PUSHBUTTON_INV, PUSHBUTTONHOLD, PUSHBUTTONHOLD_INV, PUSHBUTTON_TOGGLE, TOGGLEMULTI, - FOLLOWMULTI, FOLLOWMULTI_INV, PUSHHOLDMULTI, PUSHHOLDMULTI_INV, PUSHON, MAX_SWITCH_OPTION}; + FOLLOWMULTI, FOLLOWMULTI_INV, PUSHHOLDMULTI, PUSHHOLDMULTI_INV, PUSHON, PUSHON_INV, MAX_SWITCH_OPTION}; enum LedStateOptions {LED_OFF, LED_POWER, LED_MQTTSUB, LED_POWER_MQTTSUB, LED_MQTTPUB, LED_POWER_MQTTPUB, LED_MQTT, LED_POWER_MQTT, MAX_LED_OPTION}; @@ -317,7 +317,7 @@ enum DeviceGroupItem { DGR_ITEM_EOL, DGR_ITEM_STATUS, DGR_ITEM_LAST_16BIT, DGR_ITEM_MAX_16BIT = 127, DGR_ITEM_POWER, DGR_ITEM_DIMMER_RANGE, // Add new 32-bit items before this line - DGR_ITEM_LAST_32BIT, DGR_ITEM_MAX_32BIT = 191, + DGR_ITEM_LAST_32BIT, DGR_ITEM_MAX_32BIT = 191, // Add new string items before this line DGR_ITEM_LAST_STRING, DGR_ITEM_MAX_STRING = 223, DGR_ITEM_LIGHT_CHANNELS }; From 13dde44eb7fc2dc2963b986b66e578df81d20e28 Mon Sep 17 00:00:00 2001 From: Stephan Hadinger Date: Sat, 14 Mar 2020 14:17:30 +0100 Subject: [PATCH 18/20] Add Zigbee support for Hue emulation --- tasmota/CHANGELOG.md | 1 + tasmota/i18n.h | 4 +- tasmota/support_udp.ino | 2 +- tasmota/xdrv_20_hue.ino | 87 +-- tasmota/xdrv_23_zigbee_0_constants.ino | 12 +- tasmota/xdrv_23_zigbee_1_headers.ino | 13 +- ...vices.ino => xdrv_23_zigbee_2_devices.ino} | 500 +++++++++++++----- tasmota/xdrv_23_zigbee_3_hue.ino | 299 +++++++++++ tasmota/xdrv_23_zigbee_4_persistence.ino | 58 +- tasmota/xdrv_23_zigbee_5_converters.ino | 77 ++- tasmota/xdrv_23_zigbee_6_commands.ino | 59 ++- tasmota/xdrv_23_zigbee_7_statemachine.ino | 79 +-- tasmota/xdrv_23_zigbee_8_parsers.ino | 97 +++- tasmota/xdrv_23_zigbee_9_impl.ino | 214 +++++--- 14 files changed, 1127 insertions(+), 375 deletions(-) rename tasmota/{xdrv_23_zigbee_3_devices.ino => xdrv_23_zigbee_2_devices.ino} (62%) create mode 100644 tasmota/xdrv_23_zigbee_3_hue.ino diff --git a/tasmota/CHANGELOG.md b/tasmota/CHANGELOG.md index 2c23efc42..89c4103b9 100644 --- a/tasmota/CHANGELOG.md +++ b/tasmota/CHANGELOG.md @@ -5,6 +5,7 @@ - Add HAss Discovery support for Button and Switch triggers by Federico Leoni (#7901) - Add support for HDC1080 Temperature and Humidity sensor by Luis Teixeira (#7888) - Add commands ``SwitchMode 13`` PushOn and ``SwitchMode 14`` PushOnInverted (#7912) +- Add Zigbee support for Hue emulation ### 8.1.0.10 20200227 diff --git a/tasmota/i18n.h b/tasmota/i18n.h index 8a0b210a8..abb9fccd8 100644 --- a/tasmota/i18n.h +++ b/tasmota/i18n.h @@ -476,7 +476,6 @@ #define D_ZIGBEE_NOT_STARTED "Zigbee not started (yet)" #define D_CMND_ZIGBEE_PERMITJOIN "PermitJoin" #define D_CMND_ZIGBEE_STATUS "Status" - #define D_JSON_ZIGBEE_Status "Status" #define D_CMND_ZIGBEE_RESET "Reset" #define D_JSON_ZIGBEE_CC2530 "CC2530" #define D_CMND_ZIGBEEZNPRECEIVE "ZNPReceive" // only for debug @@ -488,6 +487,7 @@ #define D_JSON_ZIGBEEZCL_RAW_RECEIVED "ZbZCLRawReceived" #define D_JSON_ZIGBEE_DEVICE "Device" #define D_JSON_ZIGBEE_NAME "Name" + #define D_JSON_ZIGBEE_CONFIRM "ZbConfirm" #define D_CMND_ZIGBEE_NAME "Name" #define D_CMND_ZIGBEE_MODELID "ModelId" #define D_JSON_ZIGBEE_MODELID "ModelId" @@ -510,6 +510,8 @@ #define D_JSON_ZIGBEE_CMD "Command" #define D_JSON_ZIGBEE_STATUS "Status" #define D_JSON_ZIGBEE_STATUS_MSG "StatusMessage" +#define D_CMND_ZIGBEE_LIGHT "Light" + #define D_JSON_ZIGBEE_LIGHT "Light" // Commands xdrv_25_A4988_Stepper.ino #define D_CMND_MOTOR "MOTOR" diff --git a/tasmota/support_udp.ino b/tasmota/support_udp.ino index d638c162a..701abee66 100644 --- a/tasmota/support_udp.ino +++ b/tasmota/support_udp.ino @@ -86,7 +86,7 @@ void PollUdp(void) // Simple Service Discovery Protocol (SSDP) if (Settings.flag2.emulation) { -#ifdef USE_SCRIPT_HUE +#if defined(USE_SCRIPT_HUE) || defined(USE_ZIGBEE) if (!udp_response_mutex && (strstr_P(packet_buffer, PSTR("M-SEARCH")) != nullptr)) { #else if (devices_present && !udp_response_mutex && (strstr_P(packet_buffer, PSTR("M-SEARCH")) != nullptr)) { diff --git a/tasmota/xdrv_20_hue.ino b/tasmota/xdrv_20_hue.ino index a1a64c09e..afae0dbd3 100644 --- a/tasmota/xdrv_20_hue.ino +++ b/tasmota/xdrv_20_hue.ino @@ -179,7 +179,7 @@ const char HUE_ERROR_JSON[] PROGMEM = /********************************************************************************************/ -String GetHueDeviceId(uint8_t id) +String GetHueDeviceId(uint16_t id) { String deviceid = WiFi.macAddress(); deviceid += F(":00:11-"); @@ -322,7 +322,6 @@ void HueLightStatus1(uint8_t device, String *response) const size_t buf_size = 256; char * buf = (char*) malloc(buf_size); // temp buffer for strings, avoid stack - //String resp; snprintf_P(buf, buf_size, PSTR("{\"on\":%s,"), (power & (1 << (device-1))) ? "true" : "false"); // Brightness for all devices with PWM if ((1 == echo_gen) || (LST_SINGLE <= local_light_subtype)) { // force dimmer for 1st gen Echo @@ -386,11 +385,11 @@ void HueLightStatus2(uint8_t device, String *response) // it is limited to 32 devices. // last 24 bits of Mac address + 4 bits of local light + high bit for relays 16-31, relay 32 is mapped to 0 // Zigbee extension: bit 29 = 1, and last 16 bits = short address of Zigbee device -// #ifndef USE_ZIGBEE +#ifndef USE_ZIGBEE uint32_t EncodeLightId(uint8_t relay_id) -// #else -// uint32_t EncodeLightId(uint8_t relay_id, uint16_t z_shortaddr = 0) -// #endif +#else +uint32_t EncodeLightId(uint8_t relay_id, uint16_t z_shortaddr = 0) +#endif { uint8_t mac[6]; WiFi.macAddress(mac); @@ -403,12 +402,12 @@ uint32_t EncodeLightId(uint8_t relay_id) id |= (1 << 28); } id |= (relay_id & 0xF); -// #ifdef USE_ZIGBEE -// if ((z_shortaddr) && (!relay_id)) { -// // fror Zigbee devices, we have relay_id == 0 and shortaddr != 0 -// id = (1 << 29) | z_shortaddr; -// } -// #endif +#ifdef USE_ZIGBEE + if ((z_shortaddr) && (!relay_id)) { + // fror Zigbee devices, we have relay_id == 0 and shortaddr != 0 + id = (1 << 29) | z_shortaddr; + } +#endif return id; } @@ -419,11 +418,11 @@ uint32_t EncodeLightId(uint8_t relay_id) // Zigbee: // If the Id encodes a Zigbee device (meaning bit 29 is set) // it returns 0 and sets the 'shortaddr' to the device short address -// #ifndef USE_ZIGBEE +#ifndef USE_ZIGBEE uint32_t DecodeLightId(uint32_t hue_id) -// #else -// uint32_t DecodeLightId(uint32_t hue_id, uint16_t * shortaddr = nullptr) -// #endif +#else +uint32_t DecodeLightId(uint32_t hue_id, uint16_t * shortaddr = nullptr) +#endif { uint8_t relay_id = hue_id & 0xF; if (hue_id & (1 << 28)) { // check if bit 25 is set, if so we have @@ -432,13 +431,13 @@ uint32_t DecodeLightId(uint32_t hue_id) if (0 == relay_id) { // special value 0 is actually relay #32 relay_id = 32; } -// #ifdef USE_ZIGBEE -// if (hue_id & (1 << 29)) { -// // this is actually a Zigbee ID -// if (shortaddr) { *shortaddr = hue_id & 0xFFFF; } -// relay_id = 0; -// } -// #endif // USE_ZIGBEE +#ifdef USE_ZIGBEE + if (hue_id & (1 << 29)) { + // this is actually a Zigbee ID + if (shortaddr) { *shortaddr = hue_id & 0xFFFF; } + relay_id = 0; + } +#endif // USE_ZIGBEE return relay_id; } @@ -474,9 +473,9 @@ void HueGlobalConfig(String *path) { response = F("{\"lights\":{"); bool appending = false; // do we need to add a comma to append CheckHue(&response, appending); -// #ifdef USE_ZIGBEE -// ZigbeeCheckHue(&response, appending); -// #endif // USE_ZIGBEE +#ifdef USE_ZIGBEE + ZigbeeCheckHue(&response, appending); +#endif // USE_ZIGBEE response += F("},\"groups\":{},\"schedules\":{},\"config\":"); HueConfigResponse(&response); response += "}"; @@ -546,10 +545,8 @@ void HueLightsCommand(uint8_t device, uint32_t device_id, String &response) { switch(on) { case false : ExecuteCommandPower(device, POWER_OFF, SRC_HUE); - //response.replace("{re", "false"); break; case true : ExecuteCommandPower(device, POWER_ON, SRC_HUE); - //response.replace("{re", "true"); break; } response += buf; @@ -713,9 +710,9 @@ void HueLights(String *path) response = "{"; bool appending = false; CheckHue(&response, appending); -// #ifdef USE_ZIGBEE -// ZigbeeCheckHue(&response, appending); -// #endif // USE_ZIGBEE +#ifdef USE_ZIGBEE + ZigbeeCheckHue(&response, appending); +#endif // USE_ZIGBEE #ifdef USE_SCRIPT_HUE Script_Check_Hue(&response); #endif @@ -726,13 +723,13 @@ void HueLights(String *path) path->remove(path->indexOf("/state")); // Remove /state device_id = atoi(path->c_str()); device = DecodeLightId(device_id); -// #ifdef USE_ZIGBEE -// uint16_t shortaddr; -// device = DecodeLightId(device_id, &shortaddr); -// if (shortaddr) { -// return ZigbeeHandleHue(shortaddr, device_id, response); -// } -// #endif // USE_ZIGBEE +#ifdef USE_ZIGBEE + uint16_t shortaddr; + device = DecodeLightId(device_id, &shortaddr); + if (shortaddr) { + return ZigbeeHandleHue(shortaddr, device_id, response); + } +#endif // USE_ZIGBEE #ifdef USE_SCRIPT_HUE if (device > devices_present) { @@ -749,6 +746,14 @@ void HueLights(String *path) path->remove(0,8); // Remove /lights/ device_id = atoi(path->c_str()); device = DecodeLightId(device_id); +#ifdef USE_ZIGBEE + uint16_t shortaddr; + device = DecodeLightId(device_id, &shortaddr); + if (shortaddr) { + ZigbeeHueStatus(&response, shortaddr); + goto exit; + } +#endif // USE_ZIGBEE #ifdef USE_SCRIPT_HUE if (device > devices_present) { @@ -791,9 +796,9 @@ void HueGroups(String *path) lights += "\""; } -// #ifdef USE_ZIGBEE -// ZigbeeHueGroups(&response); -// #endif // USE_ZIGBEE +#ifdef USE_ZIGBEE + ZigbeeHueGroups(&response); +#endif // USE_ZIGBEE response.replace("{l1", lights); HueLightStatus1(1, &response); response += F("}"); diff --git a/tasmota/xdrv_23_zigbee_0_constants.ino b/tasmota/xdrv_23_zigbee_0_constants.ino index cc88fadc2..c4e76c136 100644 --- a/tasmota/xdrv_23_zigbee_0_constants.ino +++ b/tasmota/xdrv_23_zigbee_0_constants.ino @@ -171,12 +171,12 @@ enum Z_configuration { // enum Z_Status { - Z_Success = 0x00, - Z_Failure = 0x01, - Z_InvalidParameter = 0x02, - Z_MemError = 0x03, - Z_Created = 0x09, - Z_BufferFull = 0x11 + Z_SUCCESS = 0x00, + Z_FAILURE = 0x01, + Z_INVALIDPARAMETER = 0x02, + Z_MEMERROR = 0x03, + Z_CREATED = 0x09, + Z_BUFFERFULL = 0x11 }; enum Z_App_Profiles { diff --git a/tasmota/xdrv_23_zigbee_1_headers.ino b/tasmota/xdrv_23_zigbee_1_headers.ino index 0bc592266..50e028dc1 100644 --- a/tasmota/xdrv_23_zigbee_1_headers.ino +++ b/tasmota/xdrv_23_zigbee_1_headers.ino @@ -21,7 +21,7 @@ // contains some definitions for functions used before their declarations -void ZigbeeZCLSend(uint16_t dtsAddr, uint16_t clusterId, uint8_t endpoint, uint8_t cmdId, bool clusterSpecific, const uint8_t *msg, size_t len, bool needResponse, uint8_t transacId); +void ZigbeeZCLSend_Raw(uint16_t dtsAddr, uint16_t groupaddr, uint16_t clusterId, uint8_t endpoint, uint8_t cmdId, bool clusterSpecific, const uint8_t *msg, size_t len, bool needResponse, uint8_t transacId); // Get an JSON attribute, with case insensitive key search @@ -43,4 +43,15 @@ JsonVariant &getCaseInsensitive(const JsonObject &json, const char *needle) { return *(JsonVariant*)nullptr; } +uint32_t parseHex(const char **data, size_t max_len = 8) { + uint32_t ret = 0; + for (uint32_t i = 0; i < max_len; i++) { + int8_t v = hexValue(**data); + if (v < 0) { break; } // non hex digit, we stop parsing + ret = (ret << 4) | v; + *data += 1; + } + return ret; +} + #endif // USE_ZIGBEE diff --git a/tasmota/xdrv_23_zigbee_3_devices.ino b/tasmota/xdrv_23_zigbee_2_devices.ino similarity index 62% rename from tasmota/xdrv_23_zigbee_3_devices.ino rename to tasmota/xdrv_23_zigbee_2_devices.ino index 121961eda..c7167e090 100644 --- a/tasmota/xdrv_23_zigbee_3_devices.ino +++ b/tasmota/xdrv_23_zigbee_2_devices.ino @@ -20,39 +20,62 @@ #ifdef USE_ZIGBEE #include -#include #ifndef ZIGBEE_SAVE_DELAY_SECONDS -#define ZIGBEE_SAVE_DELAY_SECONDS 10; // wait for 10s before saving Zigbee info +#define ZIGBEE_SAVE_DELAY_SECONDS 2; // wait for 2s before saving Zigbee info #endif const uint16_t kZigbeeSaveDelaySeconds = ZIGBEE_SAVE_DELAY_SECONDS; // wait for x seconds -typedef int32_t (*Z_DeviceTimer)(uint16_t shortaddr, uint16_t cluster, uint16_t endpoint, uint32_t value); +typedef int32_t (*Z_DeviceTimer)(uint16_t shortaddr, uint16_t groupaddr, uint16_t cluster, uint8_t endpoint, uint32_t value); typedef struct Z_Device { - uint16_t shortaddr; // unique key if not null, or unspecified if null uint64_t longaddr; // 0x00 means unspecified - uint32_t firstSeen; // date when the device was first seen - uint32_t lastSeen; // date when the device was last seen - String manufacturerId; - String modelId; - String friendlyName; + char * manufacturerId; + char * modelId; + char * friendlyName; std::vector endpoints; // encoded as high 16 bits is endpoint, low 16 bits is ProfileId std::vector clusters_in; // encoded as high 16 bits is endpoint, low 16 bits is cluster number std::vector clusters_out; // encoded as high 16 bits is endpoint, low 16 bits is cluster number - // below are per device timers, used for example to query the new state of the device - uint32_t timer; // millis() when to fire the timer, 0 if no timer - uint16_t cluster; // cluster to use for the timer - uint16_t endpoint; // endpoint to use for timer - uint32_t value; // any raw value to use for the timer - Z_DeviceTimer func; // function to call when timer occurs // json buffer used for attribute reporting DynamicJsonBuffer *json_buffer; JsonObject *json; // sequence number for Zigbee frames - uint8_t seqNumber; + uint16_t shortaddr; // unique key if not null, or unspecified if null + uint8_t seqNumber; + // Light information for Hue integration integration, last known values + int8_t bulbtype; // number of channel for the bulb: 0-5, or 0xFF if no Hue integration + uint8_t power; // power state (boolean) + uint8_t colormode; // 0x00: Hue/Sat, 0x01: XY, 0x02: CT + uint8_t dimmer; // last Dimmer value: 0-254 + uint8_t sat; // last Sat: 0..254 + uint16_t ct; // last CT: 153-500 + uint16_t hue; // last Hue: 0..359 + uint16_t x, y; // last color [x,y] } Z_Device; +// Category for Deferred actions, this allows to selectively remove active deferred or update them +typedef enum Z_Def_Category { + Z_CAT_NONE = 0, // no category, it will happen anyways + Z_CAT_READ_ATTR, // Attribute reporting, either READ_ATTRIBUTE or REPORT_ATTRIBUTE, we coalesce all attributes reported if we can + Z_CAT_VIRTUAL_ATTR, // Creation of a virtual attribute, typically after a time-out. Ex: Aqara presence sensor + Z_CAT_READ_0006, // Read 0x0006 cluster + Z_CAT_READ_0008, // Read 0x0008 cluster + Z_CAT_READ_0102, // Read 0x0300 cluster + Z_CAT_READ_0300, // Read 0x0300 cluster +} Z_Def_Category; + +typedef struct Z_Deferred { + // below are per device timers, used for example to query the new state of the device + uint32_t timer; // millis() when to fire the timer, 0 if no timer + uint16_t shortaddr; // identifier of the device + uint16_t groupaddr; // group address (if needed) + uint16_t cluster; // cluster to use for the timer + uint8_t endpoint; // endpoint to use for timer + uint8_t category; // which category of deferred is it + uint32_t value; // any raw value to use for the timer + Z_DeviceTimer func; // function to call when timer occurs +} Z_Deferred; + // All devices are stored in a Vector // Invariants: // - shortaddr is unique if not null @@ -93,21 +116,33 @@ public: void setManufId(uint16_t shortaddr, const char * str); void setModelId(uint16_t shortaddr, const char * str); void setFriendlyName(uint16_t shortaddr, const char * str); - const String * getFriendlyName(uint16_t shortaddr) const; - const String * getModelId(uint16_t shortaddr) const; - - // device just seen on the network, update the lastSeen field - void updateLastSeen(uint16_t shortaddr); + const char * getFriendlyName(uint16_t shortaddr) const; + const char * getModelId(uint16_t shortaddr) const; // get next sequence number for (increment at each all) uint8_t getNextSeqNumber(uint16_t shortaddr); // Dump json + String dumpLightState(uint16_t shortaddr) const; String dump(uint32_t dump_mode, uint16_t status_shortaddr = 0) const; + // Hue support + void setHueBulbtype(uint16_t shortaddr, int8_t bulbtype); + int8_t getHueBulbtype(uint16_t shortaddr) const ; + void updateHueState(uint16_t shortaddr, + const uint8_t *power, const uint8_t *colormode, + const uint8_t *dimmer, const uint8_t *sat, + const uint16_t *ct, const uint16_t *hue, + const uint16_t *x, const uint16_t *y); + bool getHueState(uint16_t shortaddr, + uint8_t *power, uint8_t *colormode, + uint8_t *dimmer, uint8_t *sat, + uint16_t *ct, uint16_t *hue, + uint16_t *x, uint16_t *y) const ; + // Timers - void resetTimer(uint32_t shortaddr); - void setTimer(uint32_t shortaddr, uint32_t wait_ms, uint16_t cluster, uint16_t endpoint, uint32_t value, Z_DeviceTimer func); + void resetTimersForDevice(uint16_t shortaddr, uint16_t groupaddr, uint8_t category); + void setTimer(uint16_t shortaddr, uint16_t groupaddr, uint32_t wait_ms, uint16_t cluster, uint8_t endpoint, uint8_t category, uint32_t value, Z_DeviceTimer func); void runTimer(void); // Append or clear attributes Json structure @@ -123,7 +158,7 @@ public: return _devices.size(); } const Z_Device &devicesAt(size_t i) const { - return _devices.at(i); + return *(_devices.at(i)); } // Remove device from list @@ -132,14 +167,18 @@ public: // Mark data as 'dirty' and requiring to save in Flash void dirty(void); void clean(void); // avoid writing to flash the last changes + void shrinkToFit(uint16_t shortaddr); // Find device by name, can be short_addr, long_addr, number_in_array or name uint16_t parseDeviceParam(const char * param, bool short_must_be_known = false) const; private: - std::vector _devices = {}; - uint32_t _saveTimer = 0; - uint8_t _seqNumber = 0; // global seqNumber if device is unknown + std::vector _devices = {}; + std::vector _deferred = {}; // list of deferred calls + // std::vector _devices = std::vector(4); + // std::vector _deferred = std::vector(4); // list of deferred calls + uint32_t _saveTimer = 0; + uint8_t _seqNumber = 0; // global seqNumber if device is unknown template < typename T> static bool findInVector(const std::vector & vecOfElements, const T & element); @@ -158,14 +197,9 @@ private: int32_t findLongAddr(uint64_t longaddr) const; int32_t findFriendlyName(const char * name) const; - void _updateLastSeen(Z_Device &device) { - if (&device != nullptr) { - device.lastSeen = Rtc.utc_time; - } - }; - // Create a new entry in the devices list - must be called if it is sure it does not already exist Z_Device & createDeviceEntry(uint16_t shortaddr, uint64_t longaddr = 0); + void freeDeviceEntry(Z_Device *device); }; Z_Devices zigbee_devices = Z_Devices(); @@ -223,23 +257,47 @@ int32_t Z_Devices::findClusterEndpoint(const std::vector & vecOfEleme // Z_Device & Z_Devices::createDeviceEntry(uint16_t shortaddr, uint64_t longaddr) { if (!shortaddr && !longaddr) { return *(Z_Device*) nullptr; } // it is not legal to create an enrty with both short/long addr null - Z_Device device = { shortaddr, longaddr, - Rtc.utc_time, Rtc.utc_time, - String(), // ManufId - String(), // DeviceId - String(), // FriendlyName - std::vector(), - std::vector(), - std::vector(), - 0,0,0,0, - nullptr, + //Z_Device* device_alloc = (Z_Device*) malloc(sizeof(Z_Device)); + Z_Device* device_alloc = new Z_Device{ + longaddr, + nullptr, // ManufId + nullptr, // DeviceId + nullptr, // FriendlyName + std::vector(), // at least one endpoint + std::vector(), // try not to allocate if not needed + std::vector(), // try not to allocate if not needed nullptr, nullptr, + shortaddr, 0, // seqNumber - }; - device.json_buffer = new DynamicJsonBuffer(); - _devices.push_back(device); + // Hue support + -1, // no Hue support + 0, // power + 0, // colormode + 0, // dimmer + 0, // sat + 200, // ct + 0, // hue + 0, 0, // x, y + }; + + device_alloc->json_buffer = new DynamicJsonBuffer(16); + _devices.push_back(device_alloc); dirty(); - return _devices.back(); + return *(_devices.back()); +} + +void Z_Devices::freeDeviceEntry(Z_Device *device) { + if (device->manufacturerId) { free(device->manufacturerId); } + if (device->modelId) { free(device->modelId); } + if (device->friendlyName) { free(device->friendlyName); } + free(device); +} + +void Z_Devices::shrinkToFit(uint16_t shortaddr) { + Z_Device & device = getShortAddr(shortaddr); + device.endpoints.shrink_to_fit(); + device.clusters_in.shrink_to_fit(); + device.clusters_out.shrink_to_fit(); } // @@ -255,7 +313,7 @@ int32_t Z_Devices::findShortAddr(uint16_t shortaddr) const { int32_t found = 0; if (shortaddr) { for (auto &elem : _devices) { - if (elem.shortaddr == shortaddr) { return found; } + if (elem->shortaddr == shortaddr) { return found; } found++; } } @@ -274,7 +332,7 @@ int32_t Z_Devices::findLongAddr(uint64_t longaddr) const { int32_t found = 0; if (longaddr) { for (auto &elem : _devices) { - if (elem.longaddr == longaddr) { return found; } + if (elem->longaddr == longaddr) { return found; } found++; } } @@ -294,7 +352,9 @@ int32_t Z_Devices::findFriendlyName(const char * name) const { int32_t found = 0; if (name_len) { for (auto &elem : _devices) { - if (elem.friendlyName == name) { return found; } + if (elem->friendlyName) { + if (strcmp(elem->friendlyName, name) == 0) { return found; } + } found++; } } @@ -353,7 +413,7 @@ Z_Device & Z_Devices::getShortAddr(uint16_t shortaddr) { if (!shortaddr) { return *(Z_Device*) nullptr; } // this is not legal int32_t found = findShortAddr(shortaddr); if (found >= 0) { - return _devices[found]; + return *(_devices[found]); } //Serial.printf("Device entry created for shortaddr = 0x%02X, found = %d\n", shortaddr, found); return createDeviceEntry(shortaddr, 0); @@ -363,7 +423,7 @@ const Z_Device & Z_Devices::getShortAddrConst(uint16_t shortaddr) const { if (!shortaddr) { return *(Z_Device*) nullptr; } // this is not legal int32_t found = findShortAddr(shortaddr); if (found >= 0) { - return _devices[found]; + return *(_devices[found]); } return *((Z_Device*)nullptr); } @@ -373,7 +433,7 @@ Z_Device & Z_Devices::getLongAddr(uint64_t longaddr) { if (!longaddr) { return *(Z_Device*) nullptr; } int32_t found = findLongAddr(longaddr); if (found > 0) { - return _devices[found]; + return *(_devices[found]); } return createDeviceEntry(0, longaddr); } @@ -382,6 +442,7 @@ Z_Device & Z_Devices::getLongAddr(uint64_t longaddr) { bool Z_Devices::removeDevice(uint16_t shortaddr) { int32_t found = findShortAddr(shortaddr); if (found >= 0) { + freeDeviceEntry(_devices.at(found)); _devices.erase(_devices.begin() + found); dirty(); return true; @@ -400,24 +461,22 @@ void Z_Devices::updateDevice(uint16_t shortaddr, uint64_t longaddr) { if ((s_found >= 0) && (l_found >= 0)) { // both shortaddr and longaddr are already registered if (s_found == l_found) { - updateLastSeen(shortaddr); // short/long addr match, all good } else { // they don't match // the device with longaddr got a new shortaddr - _devices[l_found].shortaddr = shortaddr; // update the shortaddr corresponding to the longaddr + _devices[l_found]->shortaddr = shortaddr; // update the shortaddr corresponding to the longaddr // erase the previous shortaddr + freeDeviceEntry(_devices.at(s_found)); _devices.erase(_devices.begin() + s_found); - updateLastSeen(shortaddr); dirty(); } } else if (s_found >= 0) { // shortaddr already exists but longaddr not // add the longaddr to the entry - _devices[s_found].longaddr = longaddr; - updateLastSeen(shortaddr); + _devices[s_found]->longaddr = longaddr; dirty(); } else if (l_found >= 0) { // longaddr entry exists, update shortaddr - _devices[l_found].shortaddr = shortaddr; + _devices[l_found]->shortaddr = shortaddr; dirty(); } else { // neither short/lonf addr are found. @@ -432,10 +491,10 @@ void Z_Devices::updateDevice(uint16_t shortaddr, uint64_t longaddr) { // void Z_Devices::addEndoint(uint16_t shortaddr, uint8_t endpoint) { if (!shortaddr) { return; } + if (0x00 == endpoint) { return; } uint32_t ep_profile = (endpoint << 16); Z_Device &device = getShortAddr(shortaddr); if (&device == nullptr) { return; } // don't crash if not found - _updateLastSeen(device); if (findEndpointInVector(device.endpoints, endpoint) < 0) { device.endpoints.push_back(ep_profile); dirty(); @@ -444,10 +503,10 @@ void Z_Devices::addEndoint(uint16_t shortaddr, uint8_t endpoint) { void Z_Devices::addEndointProfile(uint16_t shortaddr, uint8_t endpoint, uint16_t profileId) { if (!shortaddr) { return; } + if (0x00 == endpoint) { return; } uint32_t ep_profile = (endpoint << 16) | profileId; Z_Device &device = getShortAddr(shortaddr); if (&device == nullptr) { return; } // don't crash if not found - _updateLastSeen(device); int32_t found = findEndpointInVector(device.endpoints, endpoint); if (found < 0) { device.endpoints.push_back(ep_profile); @@ -464,7 +523,6 @@ void Z_Devices::addCluster(uint16_t shortaddr, uint8_t endpoint, uint16_t cluste if (!shortaddr) { return; } Z_Device & device = getShortAddr(shortaddr); if (&device == nullptr) { return; } // don't crash if not found - _updateLastSeen(device); uint32_t ep_cluster = (endpoint << 16) | cluster; if (!out) { if (!findInVector(device.clusters_in, ep_cluster)) { @@ -494,64 +552,93 @@ uint8_t Z_Devices::findClusterEndpointIn(uint16_t shortaddr, uint16_t cluster){ } } - void Z_Devices::setManufId(uint16_t shortaddr, const char * str) { Z_Device & device = getShortAddr(shortaddr); if (&device == nullptr) { return; } // don't crash if not found - _updateLastSeen(device); - if (!device.manufacturerId.equals(str)) { - dirty(); + size_t str_len = str ? strlen(str) : 0; // len, handle both null ptr and zero length string + + if ((!device.manufacturerId) && (0 == str_len)) { return; } // if both empty, don't do anything + if (device.manufacturerId) { + // we already have a value + if (strcmp(device.manufacturerId, str) != 0) { + // new value + free(device.manufacturerId); // free previous value + device.manufacturerId = nullptr; + } else { + return; // same value, don't change anything + } } - device.manufacturerId = str; + if (str_len) { + device.manufacturerId = (char*) malloc(str_len + 1); + strlcpy(device.manufacturerId, str, str_len + 1); + } + dirty(); } + void Z_Devices::setModelId(uint16_t shortaddr, const char * str) { Z_Device & device = getShortAddr(shortaddr); if (&device == nullptr) { return; } // don't crash if not found - _updateLastSeen(device); - if (!device.modelId.equals(str)) { - dirty(); + size_t str_len = str ? strlen(str) : 0; // len, handle both null ptr and zero length string + + if ((!device.modelId) && (0 == str_len)) { return; } // if both empty, don't do anything + if (device.modelId) { + // we already have a value + if (strcmp(device.modelId, str) != 0) { + // new value + free(device.modelId); // free previous value + device.modelId = nullptr; + } else { + return; // same value, don't change anything + } } - device.modelId = str; + if (str_len) { + device.modelId = (char*) malloc(str_len + 1); + strlcpy(device.modelId, str, str_len + 1); + } + dirty(); } + void Z_Devices::setFriendlyName(uint16_t shortaddr, const char * str) { Z_Device & device = getShortAddr(shortaddr); if (&device == nullptr) { return; } // don't crash if not found - _updateLastSeen(device); - if (!device.friendlyName.equals(str)) { - dirty(); + size_t str_len = str ? strlen(str) : 0; // len, handle both null ptr and zero length string + + if ((!device.friendlyName) && (0 == str_len)) { return; } // if both empty, don't do anything + if (device.friendlyName) { + // we already have a value + if (strcmp(device.friendlyName, str) != 0) { + // new value + free(device.friendlyName); // free previous value + device.friendlyName = nullptr; + } else { + return; // same value, don't change anything + } } - device.friendlyName = str; + if (str_len) { + device.friendlyName = (char*) malloc(str_len + 1); + strlcpy(device.friendlyName, str, str_len + 1); + } + dirty(); } -const String * Z_Devices::getFriendlyName(uint16_t shortaddr) const { +const char * Z_Devices::getFriendlyName(uint16_t shortaddr) const { int32_t found = findShortAddr(shortaddr); if (found >= 0) { const Z_Device & device = devicesAt(found); - if (device.friendlyName.length() > 0) { - return &device.friendlyName; - } + return device.friendlyName; } return nullptr; } -const String * Z_Devices::getModelId(uint16_t shortaddr) const { +const char * Z_Devices::getModelId(uint16_t shortaddr) const { int32_t found = findShortAddr(shortaddr); if (found >= 0) { const Z_Device & device = devicesAt(found); - if (device.modelId.length() > 0) { - return &device.modelId; - } + return device.modelId; } return nullptr; } -// device just seen on the network, update the lastSeen field -void Z_Devices::updateLastSeen(uint16_t shortaddr) { - Z_Device & device = getShortAddr(shortaddr); - if (&device == nullptr) { return; } // don't crash if not found - _updateLastSeen(device); -} - // get the next sequance number for the device, or use the global seq number if device is unknown uint8_t Z_Devices::getNextSeqNumber(uint16_t shortaddr) { int32_t short_found = findShortAddr(shortaddr); @@ -565,48 +652,120 @@ uint8_t Z_Devices::getNextSeqNumber(uint16_t shortaddr) { } } -// Per device timers -// -// Reset the timer for a specific device -void Z_Devices::resetTimer(uint32_t shortaddr) { - Z_Device & device = getShortAddr(shortaddr); - if (&device == nullptr) { return; } // don't crash if not found - device.timer = 0; - device.func = nullptr; + +// Hue support +void Z_Devices::setHueBulbtype(uint16_t shortaddr, int8_t bulbtype) { + Z_Device &device = getShortAddr(shortaddr); + if (bulbtype != device.bulbtype) { + device.bulbtype = bulbtype; + dirty(); + } +} +int8_t Z_Devices::getHueBulbtype(uint16_t shortaddr) const { + int32_t found = findShortAddr(shortaddr); + if (found >= 0) { + return _devices[found]->bulbtype; + } else { + return -1; // Hue not activated + } +} + +// Hue support +void Z_Devices::updateHueState(uint16_t shortaddr, + const uint8_t *power, const uint8_t *colormode, + const uint8_t *dimmer, const uint8_t *sat, + const uint16_t *ct, const uint16_t *hue, + const uint16_t *x, const uint16_t *y) { + Z_Device &device = getShortAddr(shortaddr); + if (power) { device.power = *power; } + if (colormode){ device.colormode = *colormode; } + if (dimmer) { device.dimmer = *dimmer; } + if (sat) { device.sat = *sat; } + if (ct) { device.ct = *ct; } + if (hue) { device.hue = *hue; } + if (x) { device.x = *x; } + if (y) { device.y = *y; } +} + +// return true if ok +bool Z_Devices::getHueState(uint16_t shortaddr, + uint8_t *power, uint8_t *colormode, + uint8_t *dimmer, uint8_t *sat, + uint16_t *ct, uint16_t *hue, + uint16_t *x, uint16_t *y) const { + int32_t found = findShortAddr(shortaddr); + if (found >= 0) { + const Z_Device &device = *(_devices[found]); + if (power) { *power = device.power; } + if (colormode){ *colormode = device.colormode; } + if (dimmer) { *dimmer = device.dimmer; } + if (sat) { *sat = device.sat; } + if (ct) { *ct = device.ct; } + if (hue) { *hue = device.hue; } + if (x) { *x = device.x; } + if (y) { *y = device.y; } + return true; + } else { + return false; + } +} + +// Deferred actions +// Parse for a specific category, of all deferred for a device if category == 0xFF +void Z_Devices::resetTimersForDevice(uint16_t shortaddr, uint16_t groupaddr, uint8_t category) { + // iterate the list of deferred, and remove any linked to the shortaddr + for (auto it = _deferred.begin(); it != _deferred.end(); it++) { + // Notice that the iterator is decremented after it is passed + // to erase() but before erase() is executed + // see https://www.techiedelight.com/remove-elements-vector-inside-loop-cpp/ + if ((it->shortaddr == shortaddr) && (it->groupaddr == groupaddr)) { + if ((0xFF == category) || (it->category == category)) { + _deferred.erase(it--); + } + } + } } // Set timer for a specific device -void Z_Devices::setTimer(uint32_t shortaddr, uint32_t wait_ms, uint16_t cluster, uint16_t endpoint, uint32_t value, Z_DeviceTimer func) { - Z_Device & device = getShortAddr(shortaddr); - if (&device == nullptr) { return; } // don't crash if not found +void Z_Devices::setTimer(uint16_t shortaddr, uint16_t groupaddr, uint32_t wait_ms, uint16_t cluster, uint8_t endpoint, uint8_t category, uint32_t value, Z_DeviceTimer func) { + // First we remove any existing timer for same device in same category, except for category=0x00 (they need to happen anyway) + if (category) { // if category == 0, we leave all previous + resetTimersForDevice(shortaddr, groupaddr, category); // remove any cluster + } - device.cluster = cluster; - device.endpoint = endpoint; - device.value = value; - device.func = func; - device.timer = wait_ms + millis(); + // Now create the new timer + Z_Deferred deferred = { wait_ms + millis(), // timer + shortaddr, + groupaddr, + cluster, + endpoint, + category, + value, + func }; + _deferred.push_back(deferred); } // Run timer at each tick void Z_Devices::runTimer(void) { - for (std::vector::iterator it = _devices.begin(); it != _devices.end(); ++it) { - Z_Device &device = *it; - uint16_t shortaddr = device.shortaddr; + // visit all timers + for (auto it = _deferred.begin(); it != _deferred.end(); it++) { + Z_Deferred &defer = *it; - uint32_t timer = device.timer; - if ((timer) && TimeReached(timer)) { - device.timer = 0; // cancel the timer before calling, so the callback can set another timer - // trigger the timer - (*device.func)(device.shortaddr, device.cluster, device.endpoint, device.value); + uint32_t timer = defer.timer; + if (TimeReached(timer)) { + (*defer.func)(defer.shortaddr, defer.groupaddr, defer.cluster, defer.endpoint, defer.value); + _deferred.erase(it--); // remove from list } } - // save timer + + // check if we need to save to Flash if ((_saveTimer) && TimeReached(_saveTimer)) { saveZigbeeDevices(); _saveTimer = 0; } } +// Clear the JSON buffer for coalesced and deferred attributes void Z_Devices::jsonClear(uint16_t shortaddr) { Z_Device & device = getShortAddr(shortaddr); if (&device == nullptr) { return; } // don't crash if not found @@ -615,23 +774,26 @@ void Z_Devices::jsonClear(uint16_t shortaddr) { device.json_buffer->clear(); } +// Copy JSON from one object to another, this helps preserving the order of attributes void CopyJsonVariant(JsonObject &to, const String &key, const JsonVariant &val) { + // first remove the potentially existing key in the target JSON, so new adds will be at the end of the list to.remove(key); // force remove to have metadata like LinkQuality at the end if (val.is()) { - String sval = val.as(); // force a copy of the String value + String sval = val.as(); // force a copy of the String value, avoiding crash to.set(key, sval); } else if (val.is()) { JsonArray &nested_arr = to.createNestedArray(key); - CopyJsonArray(nested_arr, val.as()); + CopyJsonArray(nested_arr, val.as()); // deep copy } else if (val.is()) { JsonObject &nested_obj = to.createNestedObject(key); - CopyJsonObject(nested_obj, val.as()); + CopyJsonObject(nested_obj, val.as()); // deep copy } else { - to.set(key, val); + to.set(key, val); // general case for non array, object or string } } +// Shallow copy of array, we skip any sub-array or sub-object. It may be added in the future void CopyJsonArray(JsonArray &to, const JsonArray &arr) { for (auto v : arr) { if (v.is()) { @@ -645,6 +807,7 @@ void CopyJsonArray(JsonArray &to, const JsonArray &arr) { } } +// Deep copy of object void CopyJsonObject(JsonObject &to, const JsonObject &from) { for (auto kv : from) { String key_string = kv.key; @@ -655,6 +818,8 @@ void CopyJsonObject(JsonObject &to, const JsonObject &from) { } // does the new payload conflicts with the existing payload, i.e. values would be overwritten +// true - one attribute (except LinkQuality) woudl be lost, there is conflict +// false - new attributes can be safely added bool Z_Devices::jsonIsConflict(uint16_t shortaddr, const JsonObject &values) { Z_Device & device = getShortAddr(shortaddr); if (&device == nullptr) { return false; } // don't crash if not found @@ -665,14 +830,14 @@ bool Z_Devices::jsonIsConflict(uint16_t shortaddr, const JsonObject &values) { } // compare groups - uint16_t group1 = 0; - uint16_t group2 = 0; - if (device.json->containsKey(D_CMND_ZIGBEE_GROUP)) { - group1 = device.json->get(D_CMND_ZIGBEE_GROUP); - } - if (values.containsKey(D_CMND_ZIGBEE_GROUP)) { - group2 = values.get(D_CMND_ZIGBEE_GROUP); - } + // Special case for group addresses. Group attribute is only present if the target + // address is a group address, so just comparing attributes will not work. + // Eg: if the first packet has no group attribute, and the second does, conflict would not be detected + // Here we explicitly compute the group address of both messages, and compare them. No group means group=0x0000 + // (we use the property of an missing attribute returning 0) + // (note: we use .get() here which is case-sensitive. We know however that the attribute was set with the exact syntax D_CMND_ZIGBEE_GROUP, so we don't need a case-insensitive get()) + uint16_t group1 = device.json->get(D_CMND_ZIGBEE_GROUP); + uint16_t group2 = values.get(D_CMND_ZIGBEE_GROUP); if (group1 != group2) { return true; // if group addresses differ, then conflict } @@ -712,9 +877,9 @@ void Z_Devices::jsonAppend(uint16_t shortaddr, const JsonObject &values) { snprintf_P(sa, sizeof(sa), PSTR("0x%04X"), shortaddr); device.json->set(F(D_JSON_ZIGBEE_DEVICE), sa); // Prepend Friendly Name if it has one - const String * fname = zigbee_devices.getFriendlyName(shortaddr); + const char * fname = zigbee_devices.getFriendlyName(shortaddr); if (fname) { - device.json->set(F(D_JSON_ZIGBEE_NAME), (char*)fname->c_str()); // (char*) forces ArduinoJson to make a copy of the cstring + device.json->set(F(D_JSON_ZIGBEE_NAME), (char*) fname); // (char*) forces ArduinoJson to make a copy of the cstring } // copy all values from 'values' to 'json' @@ -733,18 +898,9 @@ void Z_Devices::jsonPublishFlush(uint16_t shortaddr) { JsonObject * json = device.json; if (json == nullptr) { return; } // abort if nothing in buffer - const String * fname = zigbee_devices.getFriendlyName(shortaddr); + const char * fname = zigbee_devices.getFriendlyName(shortaddr); bool use_fname = (Settings.flag4.zigbee_use_names) && (fname); // should we replace shortaddr with friendlyname? - // if (use_fname) { - // // we need to add the Device short_addr inside the JSON - // char sa[8]; - // snprintf_P(sa, sizeof(sa), PSTR("0x%04X"), shortaddr); - // json->set(F(D_JSON_ZIGBEE_DEVICE), sa); - // } else if (fname) { - // json->set(F(D_JSON_NAME), (char*) fname); - // } - // Remove redundant "Name" or "Device" if (use_fname) { json->remove(F(D_JSON_ZIGBEE_NAME)); @@ -757,7 +913,7 @@ void Z_Devices::jsonPublishFlush(uint16_t shortaddr) { zigbee_devices.jsonClear(shortaddr); if (use_fname) { - Response_P(PSTR("{\"" D_JSON_ZIGBEE_RECEIVED "\":{\"%s\":%s}}"), fname->c_str(), msg.c_str()); + Response_P(PSTR("{\"" D_JSON_ZIGBEE_RECEIVED "\":{\"%s\":%s}}"), fname, msg.c_str()); } else { Response_P(PSTR("{\"" D_JSON_ZIGBEE_RECEIVED "\":{\"0x%04X\":%s}}"), shortaddr, msg.c_str()); } @@ -824,6 +980,58 @@ uint16_t Z_Devices::parseDeviceParam(const char * param, bool short_must_be_know return shortaddr; } +// Display the tracked status for a light +String Z_Devices::dumpLightState(uint16_t shortaddr) const { + DynamicJsonBuffer jsonBuffer; + JsonObject& json = jsonBuffer.createObject(); + char hex[8]; + + int32_t found = findShortAddr(shortaddr); + if (found >= 0) { + const Z_Device & device = devicesAt(found); + const char * fname = getFriendlyName(shortaddr); + + bool use_fname = (Settings.flag4.zigbee_use_names) && (fname); // should we replace shortaddr with friendlyname? + + snprintf_P(hex, sizeof(hex), PSTR("0x%04X"), shortaddr); + + JsonObject& dev = use_fname ? json.createNestedObject((char*) fname) // casting (char*) forces a copy + : json.createNestedObject(hex); + if (use_fname) { + dev[F(D_JSON_ZIGBEE_DEVICE)] = hex; + } else if (fname) { + dev[F(D_JSON_ZIGBEE_NAME)] = (char*) fname; + } + + // expose the last known status of the bulb, for Hue integration + dev[F(D_JSON_ZIGBEE_LIGHT)] = device.bulbtype; // sign extend, 0xFF changed as -1 + if (0 <= device.bulbtype) { + // bulbtype is defined + dev[F("Power")] = device.power; + if (1 <= device.bulbtype) { + dev[F("Dimmer")] = device.dimmer; + } + if (2 <= device.bulbtype) { + dev[F("Colormode")] = device.colormode; + } + if ((2 == device.bulbtype) || (5 == device.bulbtype)) { + dev[F("CT")] = device.ct; + } + if (3 <= device.bulbtype) { + dev[F("Sat")] = device.sat; + dev[F("Hue")] = device.hue; + dev[F("X")] = device.x; + dev[F("Y")] = device.y; + } + } + } + + String payload = ""; + payload.reserve(200); + json.printTo(payload); + return payload; +} + // Dump the internal memory of Zigbee devices // Mode = 1: simple dump of devices addresses // Mode = 2: simple dump of devices addresses and names @@ -833,8 +1041,8 @@ String Z_Devices::dump(uint32_t dump_mode, uint16_t status_shortaddr) const { JsonArray& json = jsonBuffer.createArray(); JsonArray& devices = json; - for (std::vector::const_iterator it = _devices.begin(); it != _devices.end(); ++it) { - const Z_Device& device = *it; + for (std::vector::const_iterator it = _devices.begin(); it != _devices.end(); ++it) { + const Z_Device &device = **it; uint16_t shortaddr = device.shortaddr; char hex[22]; @@ -846,8 +1054,8 @@ String Z_Devices::dump(uint32_t dump_mode, uint16_t status_shortaddr) const { snprintf_P(hex, sizeof(hex), PSTR("0x%04X"), shortaddr); dev[F(D_JSON_ZIGBEE_DEVICE)] = hex; - if (device.friendlyName.length() > 0) { - dev[F(D_JSON_ZIGBEE_NAME)] = device.friendlyName; + if (device.friendlyName > 0) { + dev[F(D_JSON_ZIGBEE_NAME)] = (char*) device.friendlyName; } if (2 <= dump_mode) { @@ -855,10 +1063,10 @@ String Z_Devices::dump(uint32_t dump_mode, uint16_t status_shortaddr) const { hex[1] = 'x'; Uint64toHex(device.longaddr, &hex[2], 64); dev[F("IEEEAddr")] = hex; - if (device.modelId.length() > 0) { + if (device.modelId) { dev[F(D_JSON_MODEL D_JSON_ID)] = device.modelId; } - if (device.manufacturerId.length() > 0) { + if (device.manufacturerId) { dev[F("Manufacturer")] = device.manufacturerId; } } diff --git a/tasmota/xdrv_23_zigbee_3_hue.ino b/tasmota/xdrv_23_zigbee_3_hue.ino new file mode 100644 index 000000000..bb3fce2dd --- /dev/null +++ b/tasmota/xdrv_23_zigbee_3_hue.ino @@ -0,0 +1,299 @@ +/* + xdrv_23_zigbee.ino - zigbee support for Tasmota + + Copyright (C) 2020 Theo Arends and Stephan Hadinger + + 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_ZIGBEE + +// Add global functions for Hue Emulation + +// idx: index in the list of zigbee_devices +void HueLightStatus1Zigbee(uint16_t shortaddr, uint8_t local_light_subtype, String *response) { + uint8_t power, colormode, bri, sat; + uint16_t ct, hue; + uint16_t x, y; + String light_status = ""; + uint32_t echo_gen = findEchoGeneration(); // 1 for 1st gen =+ Echo Dot 2nd gen, 2 for 2nd gen and above + + zigbee_devices.getHueState(shortaddr, &power, &colormode, &bri, &sat, &ct, &hue, &x, &y); + + if (bri > 254) bri = 254; // Philips Hue bri is between 1 and 254 + if (bri < 1) bri = 1; + if (sat > 254) sat = 254; // Philips Hue only accepts 254 as max hue + uint8_t hue8 = changeUIntScale(hue, 0, 360, 0, 254); // default hue is 0..254, we don't use extended hue + + const size_t buf_size = 256; + char * buf = (char*) malloc(buf_size); // temp buffer for strings, avoid stack + + snprintf_P(buf, buf_size, PSTR("{\"on\":%s,"), (power & 1) ? "true" : "false"); + // Brightness for all devices with PWM + if ((1 == echo_gen) || (LST_SINGLE <= local_light_subtype)) { // force dimmer for 1st gen Echo + snprintf_P(buf, buf_size, PSTR("%s\"bri\":%d,"), buf, bri); + } + if (LST_COLDWARM <= local_light_subtype) { + snprintf_P(buf, buf_size, PSTR("%s\"colormode\":\"%s\","), buf, (0 == colormode) ? "hs" : (1 == colormode) ? "xy" : "ct"); + } + if (LST_RGB <= local_light_subtype) { // colors + if (prev_x_str[0] && prev_y_str[0]) { + snprintf_P(buf, buf_size, PSTR("%s\"xy\":[%s,%s],"), buf, prev_x_str, prev_y_str); + } else { + float x_f = x / 65536.0f; + float y_f = y / 65536.0f; + snprintf_P(buf, buf_size, PSTR("%s\"xy\":[%s,%s],"), buf, String(x, 5).c_str(), String(y, 5).c_str()); + } + snprintf_P(buf, buf_size, PSTR("%s\"hue\":%d,\"sat\":%d,"), buf, hue, sat); + } + if (LST_COLDWARM == local_light_subtype || LST_RGBW <= local_light_subtype) { // white temp + snprintf_P(buf, buf_size, PSTR("%s\"ct\":%d,"), buf, ct > 0 ? ct : 284); + } + snprintf_P(buf, buf_size, HUE_LIGHTS_STATUS_JSON1_SUFFIX, buf); + + *response += buf; + free(buf); +} + +void HueLightStatus2Zigbee(uint16_t shortaddr, String *response) +{ + const size_t buf_size = 192; + char * buf = (char*) malloc(buf_size); + + const char * friendlyName = zigbee_devices.getFriendlyName(shortaddr); + char shortaddrname[8]; + snprintf_P(shortaddrname, sizeof(shortaddrname), PSTR("0x%04X"), shortaddr); + + snprintf_P(buf, buf_size, HUE_LIGHTS_STATUS_JSON2, + (friendlyName) ? friendlyName : shortaddrname, + GetHueDeviceId(shortaddr).c_str()); + *response += buf; + free(buf); +} + +void ZigbeeHueStatus(String * response, uint16_t shortaddr) { + *response += F("{\"state\":"); + HueLightStatus1Zigbee(shortaddr, zigbee_devices.getHueBulbtype(shortaddr), response); + HueLightStatus2Zigbee(shortaddr, response); +} + +void ZigbeeCheckHue(String * response, bool &appending) { + uint32_t zigbee_num = zigbee_devices.devicesSize(); + for (uint32_t i = 0; i < zigbee_num; i++) { + int8_t bulbtype = zigbee_devices.devicesAt(i).bulbtype; + + if (bulbtype >= 0) { + uint16_t shortaddr = zigbee_devices.devicesAt(i).shortaddr; + // this bulb is advertized + if (appending) { *response += ","; } + *response += "\""; + *response += EncodeLightId(0, shortaddr); + *response += F("\":{\"state\":"); + HueLightStatus1Zigbee(shortaddr, bulbtype, response); // TODO + HueLightStatus2Zigbee(shortaddr, response); + appending = true; + } + } +} + +void ZigbeeHueGroups(String * lights) { + uint32_t zigbee_num = zigbee_devices.devicesSize(); + for (uint32_t i = 0; i < zigbee_num; i++) { + int8_t bulbtype = zigbee_devices.devicesAt(i).bulbtype; + + if (bulbtype >= 0) { + *lights += ",\""; + *lights += EncodeLightId(i); + *lights += "\""; + } + } +} + +// Send commands +// Power On/Off +void ZigbeeHuePower(uint16_t shortaddr, uint8_t power) { + zigbeeZCLSendStr(shortaddr, 0, 0, true, 0x0006, power, ""); + zigbee_devices.updateHueState(shortaddr, &power, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); +} + +// Dimmer +void ZigbeeHueDimmer(uint16_t shortaddr, uint8_t dimmer) { + char param[8]; + snprintf_P(param, sizeof(param), PSTR("%02X0A00"), dimmer); + zigbeeZCLSendStr(shortaddr, 0, 0, true, 0x0008, 0x04, param); + zigbee_devices.updateHueState(shortaddr, nullptr, nullptr, &dimmer, nullptr, nullptr, nullptr, nullptr, nullptr); +} + +// CT +void ZigbeeHueCT(uint16_t shortaddr, uint16_t ct) { + AddLog_P2(LOG_LEVEL_INFO, PSTR("ZigbeeHueCT 0x%04X - %d"), shortaddr, ct); + char param[12]; + snprintf_P(param, sizeof(param), PSTR("%02X%02X0A00"), ct & 0xFF, ct >> 8); + uint8_t colormode = 2; // "ct" + zigbeeZCLSendStr(shortaddr, 0, 0, true, 0x0300, 0x0A, param); + zigbee_devices.updateHueState(shortaddr, nullptr, &colormode, nullptr, nullptr, &ct, nullptr, nullptr, nullptr); +} + +// XY +void ZigbeeHueXY(uint16_t shortaddr, uint16_t x, uint16_t y) { + char param[16]; + snprintf_P(param, sizeof(param), PSTR("%02X%02X%02X%02X0A00"), x & 0xFF, x >> 8, y & 0xFF, y >> 8); + uint8_t colormode = 1; // "xy" + zigbeeZCLSendStr(shortaddr, 0, 0, true, 0x0300, 0x07, param); + zigbee_devices.updateHueState(shortaddr, nullptr, &colormode, nullptr, nullptr, nullptr, nullptr, &x, &y); +} + +// HueSat +void ZigbeeHueHS(uint16_t shortaddr, uint16_t hue, uint8_t sat) { + char param[16]; + uint8_t hue8 = changeUIntScale(hue, 0, 360, 0, 254); + snprintf_P(param, sizeof(param), PSTR("%02X%02X0A00"), hue8, sat); + uint8_t colormode = 0; // "hs" + zigbeeZCLSendStr(shortaddr, 0, 0, true, 0x0300, 0x06, param); + zigbee_devices.updateHueState(shortaddr, nullptr, &colormode, nullptr, &sat, nullptr, &hue, nullptr, nullptr); +} + +void ZigbeeHandleHue(uint16_t shortaddr, uint32_t device_id, String &response) { + uint8_t power, colormode, bri, sat; + uint16_t ct, hue; + float x, y; + int code = 200; + + bool resp = false; // is the response non null (add comma between parameters) + bool on = false; + + uint8_t bulbtype = zigbee_devices.getHueBulbtype(shortaddr); + + const size_t buf_size = 100; + char * buf = (char*) malloc(buf_size); + + if (WebServer->args()) { + response = "["; + + StaticJsonBuffer<300> jsonBuffer; + JsonObject &hue_json = jsonBuffer.parseObject(WebServer->arg((WebServer->args())-1)); + if (hue_json.containsKey("on")) { + on = hue_json["on"]; + snprintf_P(buf, buf_size, + PSTR("{\"success\":{\"/lights/%d/state/on\":%s}}"), + device_id, on ? "true" : "false"); + + switch(on) + { + case false : ZigbeeHuePower(shortaddr, 0x00); + break; + case true : ZigbeeHuePower(shortaddr, 0x01); + break; + } + response += buf; + resp = true; + } + + if (hue_json.containsKey("bri")) { // Brightness is a scale from 1 (the minimum the light is capable of) to 254 (the maximum). Note: a brightness of 1 is not off. + bri = hue_json["bri"]; + prev_bri = bri; // store command value + if (resp) { response += ","; } + snprintf_P(buf, buf_size, + PSTR("{\"success\":{\"/lights/%d/state/%s\":%d}}"), + device_id, "bri", bri); + response += buf; + if (LST_SINGLE <= bulbtype) { + // extend bri value if set to max + if (254 <= bri) { bri = 255; } + ZigbeeHueDimmer(shortaddr, bri); + } + resp = true; + } + // handle xy before Hue/Sat + // If the request contains both XY and HS, we wan't to give priority to HS + if (hue_json.containsKey("xy")) { + float x = hue_json["xy"][0]; + float y = hue_json["xy"][1]; + const String &x_str = hue_json["xy"][0]; + const String &y_str = hue_json["xy"][1]; + x_str.toCharArray(prev_x_str, sizeof(prev_x_str)); + y_str.toCharArray(prev_y_str, sizeof(prev_y_str)); + if (resp) { response += ","; } + snprintf_P(buf, buf_size, + PSTR("{\"success\":{\"/lights/%d/state/xy\":[%s,%s]}}"), + device_id, prev_x_str, prev_y_str); + response += buf; + resp = true; + uint16_t xi = x * 65536.0f; + uint16_t yi = y * 65536.0f; + ZigbeeHueXY(shortaddr, xi, yi); + } + bool huesat_changed = false; + if (hue_json.containsKey("hue")) { // The hue value is a wrapping value between 0 and 65535. Both 0 and 65535 are red, 25500 is green and 46920 is blue. + hue = hue_json["hue"]; + prev_hue = hue; + if (resp) { response += ","; } + snprintf_P(buf, buf_size, + PSTR("{\"success\":{\"/lights/%d/state/%s\":%d}}"), + device_id, "hue", hue); + response += buf; + if (LST_RGB <= bulbtype) { + // change range from 0..65535 to 0..359 + hue = changeUIntScale(hue, 0, 65535, 0, 359); + huesat_changed = true; + } + resp = true; + } + if (hue_json.containsKey("sat")) { // Saturation of the light. 254 is the most saturated (colored) and 0 is the least saturated (white). + sat = hue_json["sat"]; + prev_sat = sat; // store command value + if (resp) { response += ","; } + snprintf_P(buf, buf_size, + PSTR("{\"success\":{\"/lights/%d/state/%s\":%d}}"), + device_id, "sat", sat); + response += buf; + if (LST_RGB <= bulbtype) { + // extend sat value if set to max + if (254 <= sat) { sat = 255; } + huesat_changed = true; + } + if (huesat_changed) { + ZigbeeHueHS(shortaddr, hue, sat); + } + resp = true; + } + if (hue_json.containsKey("ct")) { // Color temperature 153 (Cold) to 500 (Warm) + ct = hue_json["ct"]; + prev_ct = ct; // store commande value + if (resp) { response += ","; } + snprintf_P(buf, buf_size, + PSTR("{\"success\":{\"/lights/%d/state/%s\":%d}}"), + device_id, "ct", ct); + response += buf; + if ((LST_COLDWARM == bulbtype) || (LST_RGBW <= bulbtype)) { + ZigbeeHueCT(shortaddr, ct); + } + resp = true; + } + + response += "]"; + if (2 == response.length()) { + response = FPSTR(HUE_ERROR_JSON); + } + } + else { + response = FPSTR(HUE_ERROR_JSON); + } + AddLog_P2(LOG_LEVEL_DEBUG_MORE, PSTR(D_LOG_HTTP D_HUE " Result (%s)"), response.c_str()); + WSSend(code, CT_JSON, response); + + free(buf); +} + +#endif // USE_ZIGBEE diff --git a/tasmota/xdrv_23_zigbee_4_persistence.ino b/tasmota/xdrv_23_zigbee_4_persistence.ino index a45ce6709..b85b296b1 100644 --- a/tasmota/xdrv_23_zigbee_4_persistence.ino +++ b/tasmota/xdrv_23_zigbee_4_persistence.ino @@ -45,6 +45,8 @@ // str - Manuf (null terminated C string, 32 chars max) // str - FriendlyName (null terminated C string, 32 chars max) // reserved for extensions +// -- V2 -- +// int8_t - bulbtype // Memory footprint const static uint16_t z_spi_start_sector = 0xFF; // Force last bank of first MB @@ -141,23 +143,32 @@ class SBuffer hibernateDevice(const struct Z_Device &device) { } // ModelID - size_t model_len = device.modelId.length(); - if (model_len > 32) { model_len = 32; } // max 32 chars - buf.addBuffer(device.modelId.c_str(), model_len); + if (device.modelId) { + size_t model_len = strlen(device.modelId); + if (model_len > 32) { model_len = 32; } // max 32 chars + buf.addBuffer(device.modelId, model_len); + } buf.add8(0x00); // end of string marker // ManufID - size_t manuf_len = device.manufacturerId.length(); - if (manuf_len > 32) {manuf_len = 32; } // max 32 chars - buf.addBuffer(device.manufacturerId.c_str(), manuf_len); + if (device.manufacturerId) { + size_t manuf_len = strlen(device.manufacturerId); + if (manuf_len > 32) { manuf_len = 32; } // max 32 chars + buf.addBuffer(device.manufacturerId, manuf_len); + } buf.add8(0x00); // end of string marker // FriendlyName - size_t frname_len = device.friendlyName.length(); - if (frname_len > 32) {frname_len = 32; } // max 32 chars - buf.addBuffer(device.friendlyName.c_str(), frname_len); + if (device.friendlyName) { + size_t frname_len = strlen(device.friendlyName); + if (frname_len > 32) {frname_len = 32; } // max 32 chars + buf.addBuffer(device.friendlyName, frname_len); + } buf.add8(0x00); // end of string marker + // Hue Bulbtype + buf.add8(device.bulbtype); + // update overall length buf.set8(0, buf.len()); @@ -193,18 +204,28 @@ class SBuffer hibernateDevices(void) { return buf; } -void hidrateDevices(const SBuffer &buf) { +void hydrateDevices(const SBuffer &buf) { uint32_t buf_len = buf.len(); if (buf_len <= 10) { return; } uint32_t k = 0; uint32_t num_devices = buf.get8(k++); - +//size_t before = 0; for (uint32_t i = 0; (i < num_devices) && (k < buf_len); i++) { uint32_t dev_record_len = buf.get8(k); +// AddLog_P2(LOG_LEVEL_INFO, PSTR(D_LOG_ZIGBEE "Device %d Before Memory = %d // DIFF %d // record_len %d"), i, ESP.getFreeHeap(), before - ESP.getFreeHeap(), dev_record_len); +// before = ESP.getFreeHeap(); + SBuffer buf_d = buf.subBuffer(k, dev_record_len); +// char *hex_char = (char*) malloc((dev_record_len * 2) + 2); +// if (hex_char) { +// AddLog_P2(LOG_LEVEL_INFO, PSTR(D_LOG_ZIGBEE "/// SUB %s"), +// ToHex_P(buf_d.getBuffer(), dev_record_len, hex_char, (dev_record_len * 2) + 2)); +// free(hex_char); +// } + uint32_t d = 1; // index in device buffer uint16_t shortaddr = buf_d.get16(d); d += 2; uint64_t longaddr = buf_d.get64(d); d += 8; @@ -229,7 +250,9 @@ void hidrateDevices(const SBuffer &buf) { zigbee_devices.addCluster(shortaddr, ep, fromClusterCode(ep_cluster), true); } } - + zigbee_devices.shrinkToFit(shortaddr); +//AddLog_P2(LOG_LEVEL_INFO, PSTR(D_LOG_ZIGBEE "Device 0x%04X Memory3.shrink = %d"), shortaddr, ESP.getFreeHeap()); + // parse 3 strings char empty[] = ""; @@ -251,14 +274,22 @@ void hidrateDevices(const SBuffer &buf) { zigbee_devices.setFriendlyName(shortaddr, ptr); d += s_len + 1; + // Hue bulbtype - if present + if (d < dev_record_len) { + zigbee_devices.setHueBulbtype(shortaddr, buf_d.get8(d)); + d++; + } + // next iteration k += dev_record_len; +//AddLog_P2(LOG_LEVEL_INFO, PSTR(D_LOG_ZIGBEE "Device %d After Memory = %d"), i, ESP.getFreeHeap()); } } void loadZigbeeDevices(void) { z_flashdata_t flashdata; memcpy_P(&flashdata, z_dev_start, sizeof(z_flashdata_t)); +// AddLog_P2(LOG_LEVEL_DEBUG, PSTR(D_LOG_ZIGBEE "Memory %d"), ESP.getFreeHeap()); AddLog_P2(LOG_LEVEL_DEBUG, PSTR(D_LOG_ZIGBEE "Zigbee signature in Flash: %08X - %d"), flashdata.name, flashdata.len); // Check the signature @@ -268,11 +299,12 @@ void loadZigbeeDevices(void) { SBuffer buf(buf_len); buf.addBuffer(z_dev_start + sizeof(z_flashdata_t), buf_len); AddLog_P2(LOG_LEVEL_INFO, PSTR(D_LOG_ZIGBEE "Zigbee devices data in Flash (%d bytes)"), buf_len); - hidrateDevices(buf); + hydrateDevices(buf); zigbee_devices.clean(); // don't write back to Flash what we just loaded } else { AddLog_P2(LOG_LEVEL_INFO, PSTR(D_LOG_ZIGBEE "No zigbee devices data in Flash")); } +// AddLog_P2(LOG_LEVEL_DEBUG, PSTR(D_LOG_ZIGBEE "Memory %d"), ESP.getFreeHeap()); } void saveZigbeeDevices(void) { diff --git a/tasmota/xdrv_23_zigbee_5_converters.ino b/tasmota/xdrv_23_zigbee_5_converters.ino index 6d71d5ccf..1893ba671 100644 --- a/tasmota/xdrv_23_zigbee_5_converters.ino +++ b/tasmota/xdrv_23_zigbee_5_converters.ino @@ -39,13 +39,13 @@ class ZCLFrame { public: ZCLFrame(uint8_t frame_control, uint16_t manuf_code, uint8_t transact_seq, uint8_t cmd_id, - const char *buf, size_t buf_len, uint16_t clusterid, uint16_t groupid, + const char *buf, size_t buf_len, uint16_t clusterid, uint16_t groupaddr, uint16_t srcaddr, uint8_t srcendpoint, uint8_t dstendpoint, uint8_t wasbroadcast, uint8_t linkquality, uint8_t securityuse, uint8_t seqnumber, uint32_t timestamp): _cmd_id(cmd_id), _manuf_code(manuf_code), _transact_seq(transact_seq), _payload(buf_len ? buf_len : 250), // allocate the data frame from source or preallocate big enough - _cluster_id(clusterid), _group_id(groupid), + _cluster_id(clusterid), _groupaddr(groupaddr), _srcaddr(srcaddr), _srcendpoint(srcendpoint), _dstendpoint(dstendpoint), _wasbroadcast(wasbroadcast), _linkquality(linkquality), _securityuse(securityuse), _seqnumber(seqnumber), _timestamp(timestamp) @@ -65,7 +65,7 @@ public: "\"timestamp\":%d," "\"fc\":\"0x%02X\",\"manuf\":\"0x%04X\",\"transact\":%d," "\"cmdid\":\"0x%02X\",\"payload\":\"%s\"}}"), - _group_id, _cluster_id, _srcaddr, + _groupaddr, _cluster_id, _srcaddr, _srcendpoint, _dstendpoint, _wasbroadcast, _linkquality, _securityuse, _seqnumber, _timestamp, @@ -117,7 +117,7 @@ public: void postProcessAttributes(uint16_t shortaddr, JsonObject& json); inline void setGroupId(uint16_t groupid) { - _group_id = groupid; + _groupaddr = groupid; } inline void setClusterId(uint16_t clusterid) { @@ -150,7 +150,7 @@ private: uint8_t _transact_seq = 0; // transaction sequence number uint8_t _cmd_id = 0; uint16_t _cluster_id = 0; - uint16_t _group_id = 0; + uint16_t _groupaddr = 0; SBuffer _payload; // information from decoded ZCL frame uint16_t _srcaddr; @@ -210,6 +210,7 @@ uint32_t parseSingleAttribute(JsonObject& json, char *attrid_str, class SBuffer } break; case 0x20: // uint8 + case 0x30: // enum8 { uint8_t uint8_val = buf.get8(i); i += 1; @@ -219,6 +220,7 @@ uint32_t parseSingleAttribute(JsonObject& json, char *attrid_str, class SBuffer } break; case 0x21: // uint16 + case 0x31: // enum16 { uint16_t uint16_val = buf.get16(i); i += 2; @@ -358,11 +360,6 @@ uint32_t parseSingleAttribute(JsonObject& json, char *attrid_str, class SBuffer json[attrid_str] = uint32_val; } break; - // enum - case 0x30: // enum8 - case 0x31: // enum16 - i += attrtype - 0x2F; - break; // TODO case 0x39: // float @@ -499,9 +496,9 @@ void ZCLFrame::parseResponse(void) { snprintf_P(s, sizeof(s), PSTR("0x%04X"), _srcaddr); json[F(D_JSON_ZIGBEE_DEVICE)] = s; // "Name" - const String * friendlyName = zigbee_devices.getFriendlyName(_srcaddr); + const char * friendlyName = zigbee_devices.getFriendlyName(_srcaddr); if (friendlyName) { - json[F(D_JSON_ZIGBEE_NAME)] = *friendlyName; + json[F(D_JSON_ZIGBEE_NAME)] = (char*) friendlyName; } // "Command" snprintf_P(s, sizeof(s), PSTR("%04X!%02X"), _cluster_id, cmd); @@ -516,8 +513,8 @@ void ZCLFrame::parseResponse(void) { // Add Endpoint json[F(D_CMND_ZIGBEE_ENDPOINT)] = _srcendpoint; // Add Group if non-zero - if (_group_id) { - json[F(D_CMND_ZIGBEE_GROUP)] = _group_id; + if (_groupaddr) { + json[F(D_CMND_ZIGBEE_GROUP)] = _groupaddr; } // Add linkquality json[F(D_CMND_ZIGBEE_LINKQUALITY)] = _linkquality; @@ -534,6 +531,7 @@ void ZCLFrame::parseResponse(void) { // Parse non-normalized attributes void ZCLFrame::parseClusterSpecificCommand(JsonObject& json, uint8_t offset) { convertClusterSpecific(json, _cluster_id, _cmd_id, _frame_control.b.direction, _payload); + sendHueUpdate(_srcaddr, _groupaddr, _cluster_id, _cmd_id, _frame_control.b.direction); } // return value: @@ -566,7 +564,7 @@ const Z_AttributeConverter Z_PostProcess[] PROGMEM = { { 0x0001, 0x0000, "MainsVoltage", &Z_Copy }, { 0x0001, 0x0001, "MainsFrequency", &Z_Copy }, { 0x0001, 0x0020, "BatteryVoltage", &Z_FloatDiv10 }, - { 0x0001, 0x0021, "BatteryPercentageRemaining",&Z_Copy }, + { 0x0001, 0x0021, "BatteryPercentage", &Z_Copy }, // Device Temperature Configuration cluster { 0x0002, 0x0000, "CurrentTemperature", &Z_Copy }, @@ -924,7 +922,7 @@ int32_t Z_FloatDiv2(const class ZCLFrame *zcl, uint16_t shortaddr, JsonObject& j } // Publish a message for `"Occupancy":0` when the timer expired -int32_t Z_OccupancyCallback(uint16_t shortaddr, uint16_t cluster, uint16_t endpoint, uint32_t value) { +int32_t Z_OccupancyCallback(uint16_t shortaddr, uint16_t groupaddr, uint16_t cluster, uint8_t endpoint, uint32_t value) { DynamicJsonBuffer jsonBuffer; JsonObject& json = jsonBuffer.createObject(); json[F(OCCUPANCY)] = 0; @@ -1050,7 +1048,8 @@ int32_t Z_AqaraSensor(const class ZCLFrame *zcl, uint16_t shortaddr, JsonObject& char tmp[] = "tmp"; // for obscure reasons, it must be converted from const char* to char*, otherwise ArduinoJson gets confused JsonVariant sub_value; - const String * modelId = zigbee_devices.getModelId(shortaddr); // null if unknown + const char * modelId_c = zigbee_devices.getModelId(shortaddr); // null if unknown + String modelId((char*) modelId_c); while (len - i >= 2) { uint8_t attrid = buf2.get8(i++); @@ -1064,8 +1063,8 @@ int32_t Z_AqaraSensor(const class ZCLFrame *zcl, uint16_t shortaddr, JsonObject& json[F("Battery")] = toPercentageCR2032(val); } else if ((nullptr != modelId) && (0 == zcl->getManufCode())) { translated = true; - if (modelId->startsWith(F("lumi.sensor_ht")) || - modelId->startsWith(F("lumi.weather"))) { // Temp sensor + if (modelId.startsWith(F("lumi.sensor_ht")) || + modelId.startsWith(F("lumi.weather"))) { // Temp sensor // Filter according to prefix of model name // onla Aqara Temp/Humidity has manuf_code of zero. If non-zero we skip the parameters if (0x64 == attrid) { @@ -1076,11 +1075,11 @@ int32_t Z_AqaraSensor(const class ZCLFrame *zcl, uint16_t shortaddr, JsonObject& json[F(D_JSON_PRESSURE)] = val / 100.0f; json[F(D_JSON_PRESSURE_UNIT)] = F(D_UNIT_PRESSURE); // hPa } - } else if (modelId->startsWith(F("lumi.sensor_smoke"))) { // gas leak + } else if (modelId.startsWith(F("lumi.sensor_smoke"))) { // gas leak if (0x64 == attrid) { json[F("SmokeDensity")] = val; } - } else if (modelId->startsWith(F("lumi.sensor_natgas"))) { // gas leak + } else if (modelId.startsWith(F("lumi.sensor_natgas"))) { // gas leak if (0x64 == attrid) { json[F("GasDensity")] = val; } @@ -1121,6 +1120,42 @@ void ZCLFrame::postProcessAttributes(uint16_t shortaddr, JsonObject& json) { suffix = strtoul(delimiter2+1, nullptr, 10); } + // see if we need to update the Hue bulb status + if ((cluster == 0x0006) && ((attribute == 0x0000) || (attribute == 0x8000))) { + uint8_t power = value; + zigbee_devices.updateHueState(shortaddr, &power, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr); + } else if ((cluster == 0x0008) && (attribute == 0x0000)) { + uint8_t dimmer = value; + zigbee_devices.updateHueState(shortaddr, nullptr, nullptr, &dimmer, nullptr, + nullptr, nullptr, nullptr, nullptr); + } else if ((cluster == 0x0300) && (attribute == 0x0000)) { + uint16_t hue8 = value; + uint16_t hue = changeUIntScale(hue8, 0, 254, 0, 360); // change range from 0..254 to 0..360 + zigbee_devices.updateHueState(shortaddr, nullptr, nullptr, nullptr, nullptr, + nullptr, &hue, nullptr, nullptr); + } else if ((cluster == 0x0300) && (attribute == 0x0001)) { + uint8_t sat = value; + zigbee_devices.updateHueState(shortaddr, nullptr, nullptr, nullptr, &sat, + nullptr, nullptr, nullptr, nullptr); + } else if ((cluster == 0x0300) && (attribute == 0x0003)) { + uint16_t x = value; + zigbee_devices.updateHueState(shortaddr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, &x, nullptr); + } else if ((cluster == 0x0300) && (attribute == 0x0004)) { + uint16_t y = value; + zigbee_devices.updateHueState(shortaddr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, &y); + } else if ((cluster == 0x0300) && (attribute == 0x0007)) { + uint16_t ct = value; + zigbee_devices.updateHueState(shortaddr, nullptr, nullptr, nullptr, nullptr, + &ct, nullptr, nullptr, nullptr); + } else if ((cluster == 0x0300) && (attribute == 0x0008)) { + uint8_t colormode = value; + zigbee_devices.updateHueState(shortaddr, nullptr, &colormode, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr); + } + // Iterate on filter for (uint32_t i = 0; i < sizeof(Z_PostProcess) / sizeof(Z_PostProcess[0]); i++) { const Z_AttributeConverter *converter = &Z_PostProcess[i]; diff --git a/tasmota/xdrv_23_zigbee_6_commands.ino b/tasmota/xdrv_23_zigbee_6_commands.ino index 3d8d378b0..a61270a9c 100644 --- a/tasmota/xdrv_23_zigbee_6_commands.ino +++ b/tasmota/xdrv_23_zigbee_6_commands.ino @@ -51,6 +51,13 @@ const Z_CommandConverter Z_Commands[] PROGMEM = { { "GetAllGroups", 0x0004, 0x02, 0x01, "00" }, // Get all groups membership { "RemoveGroup", 0x0004, 0x03, 0x01, "xxxx" }, // Remove one group { "RemoveAllGroups",0x0004, 0x04, 0x01, "" }, // Remove all groups + // Scenes + //{ "AddScene", 0x0005, 0x00, 0x01, "xxxxyy0100" }, + { "ViewScene", 0x0005, 0x01, 0x01, "xxxxyy" }, + { "RemoveScene", 0x0005, 0x02, 0x01, "xxxxyy" }, + { "RemoveAllScenes",0x0005, 0x03, 0x01, "xxxx" }, + { "RecallScene", 0x0005, 0x05, 0x01, "xxxxyy" }, + { "GetSceneMembership",0x0005, 0x06, 0x01, "xxxx" }, // Light & Shutter commands { "Power", 0x0006, 0xFF, 0x01, "" }, // 0=Off, 1=On, 2=Toggle { "Dimmer", 0x0008, 0x04, 0x01, "xx0A00" }, // Move to Level with On/Off, xx=0..254 (255 is invalid) @@ -97,6 +104,13 @@ const Z_CommandConverter Z_Commands[] PROGMEM = { { "ViewGroup", 0x0004, 0x01, 0x82, "xxyyyy" }, // xx = status, yy = group id, name ignored { "GetGroup", 0x0004, 0x02, 0x82, "xxyyzzzz" }, // xx = capacity, yy = count, zzzz = first group id, following groups ignored { "RemoveGroup", 0x0004, 0x03, 0x82, "xxyyyy" }, // xx = status, yy = group id + // responses for Scene cluster commands + { "AddScene", 0x0005, 0x00, 0x82, "xxyyyyzz" }, // xx = status, yyyy = group id, zz = scene id + { "ViewScene", 0x0005, 0x01, 0x82, "xxyyyyzz" }, // xx = status, yyyy = group id, zz = scene id + { "RemoveScene", 0x0005, 0x02, 0x82, "xxyyyyzz" }, // xx = status, yyyy = group id, zz = scene id + { "RemoveAllScenes",0x0005, 0x03, 0x82, "xxyyyy" }, // xx = status, yyyy = group id + { "StoreScene", 0x0005, 0x04, 0x82, "xxyyyyzz" }, // xx = status, yyyy = group id, zz = scene id + { "GetSceneMembership",0x0005, 0x06, 0x82, "" }, // specific }; #define ZLE(x) ((x) & 0xFF), ((x) >> 8) // Little Endian @@ -105,10 +119,10 @@ const Z_CommandConverter Z_Commands[] PROGMEM = { const uint8_t CLUSTER_0006[] = { ZLE(0x0000) }; // Power const uint8_t CLUSTER_0008[] = { ZLE(0x0000) }; // CurrentLevel const uint8_t CLUSTER_0009[] = { ZLE(0x0000) }; // AlarmCount -const uint8_t CLUSTER_0300[] = { ZLE(0x0000), ZLE(0x0001), ZLE(0x0003), ZLE(0x0004), ZLE(0x0007) }; // Hue, Sat, X, Y, CT +const uint8_t CLUSTER_0300[] = { ZLE(0x0000), ZLE(0x0001), ZLE(0x0003), ZLE(0x0004), ZLE(0x0007), ZLE(0x0008) }; // Hue, Sat, X, Y, CT, ColorMode // This callback is registered after a cluster specific command and sends a read command for the same cluster -int32_t Z_ReadAttrCallback(uint16_t shortaddr, uint16_t cluster, uint16_t endpoint, uint32_t value) { +int32_t Z_ReadAttrCallback(uint16_t shortaddr, uint16_t groupaddr, uint16_t cluster, uint8_t endpoint, uint32_t value) { size_t attrs_len = 0; const uint8_t* attrs = nullptr; @@ -131,12 +145,12 @@ int32_t Z_ReadAttrCallback(uint16_t shortaddr, uint16_t cluster, uint16_t endpoi break; } if (attrs) { - ZigbeeZCLSend(shortaddr, cluster, endpoint, ZCL_READ_ATTRIBUTES, false, attrs, attrs_len, true /* we do want a response */, zigbee_devices.getNextSeqNumber(shortaddr)); + ZigbeeZCLSend_Raw(shortaddr, groupaddr, cluster, endpoint, ZCL_READ_ATTRIBUTES, false, attrs, attrs_len, true /* we do want a response */, zigbee_devices.getNextSeqNumber(shortaddr)); } } // set a timer to read back the value in the future -void zigbeeSetCommandTimer(uint16_t shortaddr, uint16_t cluster, uint16_t endpoint) { +void zigbeeSetCommandTimer(uint16_t shortaddr, uint16_t groupaddr, uint16_t cluster, uint8_t endpoint) { uint32_t wait_ms = 0; switch (cluster) { @@ -153,7 +167,7 @@ void zigbeeSetCommandTimer(uint16_t shortaddr, uint16_t cluster, uint16_t endpoi break; } if (wait_ms) { - zigbee_devices.setTimer(shortaddr, wait_ms, cluster, endpoint, 0 /* value */, &Z_ReadAttrCallback); + zigbee_devices.setTimer(shortaddr, groupaddr, wait_ms, cluster, endpoint, Z_CAT_NONE, 0 /* value */, &Z_ReadAttrCallback); } } @@ -229,7 +243,42 @@ void parseXYZ(const char *model, const SBuffer &payload, struct Z_XYZ_Var *xyz) // - cluster number // - command number or 0xFF if command is part of the variable part // - the payload in the form of a HEX string with x/y/z variables +void sendHueUpdate(uint16_t shortaddr, uint16_t groupaddr, uint16_t cluster, uint8_t cmd, bool direction) { + if (direction) { return; } // no need to update if server->client + int32_t z_cat = -1; + uint32_t wait_ms = 0; + + switch (cluster) { + case 0x0006: + z_cat = Z_CAT_READ_0006; + wait_ms = 200; // wait 0.2 s + break; + case 0x0008: + z_cat = Z_CAT_READ_0008; + wait_ms = 1050; // wait 1.0 s + break; + case 0x0102: + z_cat = Z_CAT_READ_0102; + wait_ms = 10000; // wait 10.0 s + break; + case 0x0300: + z_cat = Z_CAT_READ_0300; + wait_ms = 1050; // wait 1.0 s + break; + default: + break; + } + if (z_cat >= 0) { + uint8_t endpoint = 0; + if (!groupaddr) { + endpoint = zigbee_devices.findClusterEndpointIn(shortaddr, cluster); + } + if ((endpoint) || (groupaddr)) { // send only if we know the endpoint + zigbee_devices.setTimer(shortaddr, groupaddr, wait_ms, cluster, endpoint, z_cat, 0 /* value */, &Z_ReadAttrCallback); + } + } +} // Parse a cluster specific command, and try to convert into human readable diff --git a/tasmota/xdrv_23_zigbee_7_statemachine.ino b/tasmota/xdrv_23_zigbee_7_statemachine.ino index 015a07ab4..4f54c1b9c 100644 --- a/tasmota/xdrv_23_zigbee_7_statemachine.ino +++ b/tasmota/xdrv_23_zigbee_7_statemachine.ino @@ -165,28 +165,28 @@ ZBM(ZBR_VERSION, Z_SRSP | Z_SYS, SYS_VERSION ) // 6102 Z_SYS:versio // Check if ZNP_HAS_CONFIGURED is set ZBM(ZBS_ZNPHC, Z_SREQ | Z_SYS, SYS_OSAL_NV_READ, ZNP_HAS_CONFIGURED & 0xFF, ZNP_HAS_CONFIGURED >> 8, 0x00 /* offset */ ) // 2108000F00 - 6108000155 -ZBM(ZBR_ZNPHC, Z_SRSP | Z_SYS, SYS_OSAL_NV_READ, Z_Success, 0x01 /* len */, 0x55) // 6108000155 -// If not set, the response is 61-08-02-00 = Z_SRSP | Z_SYS, SYS_OSAL_NV_READ, Z_InvalidParameter, 0x00 /* len */ +ZBM(ZBR_ZNPHC, Z_SRSP | Z_SYS, SYS_OSAL_NV_READ, Z_SUCCESS, 0x01 /* len */, 0x55) // 6108000155 +// If not set, the response is 61-08-02-00 = Z_SRSP | Z_SYS, SYS_OSAL_NV_READ, Z_INVALIDPARAMETER, 0x00 /* len */ ZBM(ZBS_PAN, Z_SREQ | Z_SAPI, SAPI_READ_CONFIGURATION, CONF_PANID ) // 260483 -ZBM(ZBR_PAN, Z_SRSP | Z_SAPI, SAPI_READ_CONFIGURATION, Z_Success, CONF_PANID, 0x02 /* len */, +ZBM(ZBR_PAN, Z_SRSP | Z_SAPI, SAPI_READ_CONFIGURATION, Z_SUCCESS, CONF_PANID, 0x02 /* len */, Z_B0(USE_ZIGBEE_PANID), Z_B1(USE_ZIGBEE_PANID) ) // 6604008302xxxx ZBM(ZBS_EXTPAN, Z_SREQ | Z_SAPI, SAPI_READ_CONFIGURATION, CONF_EXTENDED_PAN_ID ) // 26042D -ZBM(ZBR_EXTPAN, Z_SRSP | Z_SAPI, SAPI_READ_CONFIGURATION, Z_Success, CONF_EXTENDED_PAN_ID, +ZBM(ZBR_EXTPAN, Z_SRSP | Z_SAPI, SAPI_READ_CONFIGURATION, Z_SUCCESS, CONF_EXTENDED_PAN_ID, 0x08 /* len */, Z_B0(USE_ZIGBEE_EXTPANID), Z_B1(USE_ZIGBEE_EXTPANID), Z_B2(USE_ZIGBEE_EXTPANID), Z_B3(USE_ZIGBEE_EXTPANID), Z_B4(USE_ZIGBEE_EXTPANID), Z_B5(USE_ZIGBEE_EXTPANID), Z_B6(USE_ZIGBEE_EXTPANID), Z_B7(USE_ZIGBEE_EXTPANID), ) // 6604002D08xxxxxxxxxxxxxxxx ZBM(ZBS_CHANN, Z_SREQ | Z_SAPI, SAPI_READ_CONFIGURATION, CONF_CHANLIST ) // 260484 -ZBM(ZBR_CHANN, Z_SRSP | Z_SAPI, SAPI_READ_CONFIGURATION, Z_Success, CONF_CHANLIST, +ZBM(ZBR_CHANN, Z_SRSP | Z_SAPI, SAPI_READ_CONFIGURATION, Z_SUCCESS, CONF_CHANLIST, 0x04 /* len */, Z_B0(USE_ZIGBEE_CHANNEL_MASK), Z_B1(USE_ZIGBEE_CHANNEL_MASK), Z_B2(USE_ZIGBEE_CHANNEL_MASK), Z_B3(USE_ZIGBEE_CHANNEL_MASK), ) // 6604008404xxxxxxxx ZBM(ZBS_PFGK, Z_SREQ | Z_SAPI, SAPI_READ_CONFIGURATION, CONF_PRECFGKEY ) // 260462 -ZBM(ZBR_PFGK, Z_SRSP | Z_SAPI, SAPI_READ_CONFIGURATION, Z_Success, CONF_PRECFGKEY, +ZBM(ZBR_PFGK, Z_SRSP | Z_SAPI, SAPI_READ_CONFIGURATION, Z_SUCCESS, CONF_PRECFGKEY, 0x10 /* len */, Z_B0(USE_ZIGBEE_PRECFGKEY_L), Z_B1(USE_ZIGBEE_PRECFGKEY_L), Z_B2(USE_ZIGBEE_PRECFGKEY_L), Z_B3(USE_ZIGBEE_PRECFGKEY_L), Z_B4(USE_ZIGBEE_PRECFGKEY_L), Z_B5(USE_ZIGBEE_PRECFGKEY_L), Z_B6(USE_ZIGBEE_PRECFGKEY_L), Z_B7(USE_ZIGBEE_PRECFGKEY_L), @@ -196,13 +196,13 @@ ZBM(ZBR_PFGK, Z_SRSP | Z_SAPI, SAPI_READ_CONFIGURATION, Z_Success, CONF_PRECFGKE 0x00, 0x02, 0x04, 0x06, 0x08, 0x0A, 0x0C, 0x0D*/ ) // 660400621001030507090B0D0F00020406080A0C0D ZBM(ZBS_PFGKEN, Z_SREQ | Z_SAPI, SAPI_READ_CONFIGURATION, CONF_PRECFGKEYS_ENABLE ) // 260463 -ZBM(ZBR_PFGKEN, Z_SRSP | Z_SAPI, SAPI_READ_CONFIGURATION, Z_Success, CONF_PRECFGKEYS_ENABLE, +ZBM(ZBR_PFGKEN, Z_SRSP | Z_SAPI, SAPI_READ_CONFIGURATION, Z_SUCCESS, CONF_PRECFGKEYS_ENABLE, 0x01 /* len */, 0x00 ) // 660400630100 // commands to "format" the device // Write configuration - write success -ZBM(ZBR_W_OK, Z_SRSP | Z_SAPI, SAPI_WRITE_CONFIGURATION, Z_Success ) // 660500 - Write Configuration -ZBM(ZBR_WNV_OK, Z_SRSP | Z_SYS, SYS_OSAL_NV_WRITE, Z_Success ) // 610900 - NV Write +ZBM(ZBR_W_OK, Z_SRSP | Z_SAPI, SAPI_WRITE_CONFIGURATION, Z_SUCCESS ) // 660500 - Write Configuration +ZBM(ZBR_WNV_OK, Z_SRSP | Z_SYS, SYS_OSAL_NV_WRITE, Z_SUCCESS ) // 610900 - NV Write // Factory reset ZBM(ZBS_FACTRES, Z_SREQ | Z_SAPI, SAPI_WRITE_CONFIGURATION, CONF_STARTUP_OPTION, 0x01 /* len */, 0x02 ) // 2605030102 @@ -243,7 +243,7 @@ ZBM(ZBS_W_ZDODCB, Z_SREQ | Z_SAPI, SAPI_WRITE_CONFIGURATION, CONF_ZDO_DIRECT_CB, ZBM(ZBS_WNV_INITZNPHC, Z_SREQ | Z_SYS, SYS_OSAL_NV_ITEM_INIT, ZNP_HAS_CONFIGURED & 0xFF, ZNP_HAS_CONFIGURED >> 8, 0x01, 0x00 /* InitLen 16 bits */, 0x01 /* len */, 0x00 ) // 2107000F01000100 - 610709 // Init succeeded -//ZBM(ZBR_WNV_INIT_OK, Z_SRSP | Z_SYS, SYS_OSAL_NV_ITEM_INIT, Z_Created ) // 610709 - NV Write +//ZBM(ZBR_WNV_INIT_OK, Z_SRSP | Z_SYS, SYS_OSAL_NV_ITEM_INIT, Z_CREATED ) // 610709 - NV Write ZBM(ZBR_WNV_INIT_OK, Z_SRSP | Z_SYS, SYS_OSAL_NV_ITEM_INIT ) // 6107xx, Success if 610700 or 610709 - NV Write // Write ZNP Has Configured @@ -255,7 +255,7 @@ ZBM(ZBR_STARTUPFROMAPP, Z_SRSP | Z_ZDO, ZDO_STARTUP_FROM_APP ) // 6540 + 01 fo ZBM(AREQ_STARTUPFROMAPP, Z_AREQ | Z_ZDO, ZDO_STATE_CHANGE_IND, ZDO_DEV_ZB_COORD ) // 45C009 + 08 = starting, 09 = started // GetDeviceInfo ZBM(ZBS_GETDEVICEINFO, Z_SREQ | Z_UTIL, Z_UTIL_GET_DEVICE_INFO ) // 2700 -ZBM(ZBR_GETDEVICEINFO, Z_SRSP | Z_UTIL, Z_UTIL_GET_DEVICE_INFO, Z_Success ) // Ex= 6700.00.6263151D004B1200.0000.07.09.00 +ZBM(ZBR_GETDEVICEINFO, Z_SRSP | Z_UTIL, Z_UTIL_GET_DEVICE_INFO, Z_SUCCESS ) // Ex= 6700.00.6263151D004B1200.0000.07.09.00 // IEEE Adr (8 bytes) = 6263151D004B1200 // Short Addr (2 bytes) = 0000 // Device Type (1 byte) = 07 (coord?) @@ -267,7 +267,7 @@ ZBM(ZBR_GETDEVICEINFO, Z_SRSP | Z_UTIL, Z_UTIL_GET_DEVICE_INFO, Z_Success ) // // Z_ZDO:nodeDescReq ZBM(ZBS_ZDO_NODEDESCREQ, Z_SREQ | Z_ZDO, ZDO_NODE_DESC_REQ, 0x00, 0x00 /* dst addr */, 0x00, 0x00 /* NWKAddrOfInterest */) // 250200000000 -ZBM(ZBR_ZDO_NODEDESCREQ, Z_SRSP | Z_ZDO, ZDO_NODE_DESC_REQ, Z_Success ) // 650200 +ZBM(ZBR_ZDO_NODEDESCREQ, Z_SRSP | Z_ZDO, ZDO_NODE_DESC_REQ, Z_SUCCESS ) // 650200 // Async resp ex: 4582.0000.00.0000.00.40.8F.0000.50.A000.0100.A000.00 ZBM(AREQ_ZDO_NODEDESCRSP, Z_AREQ | Z_ZDO, ZDO_NODE_DESC_RSP) // 4582 // SrcAddr (2 bytes) 0000 @@ -285,32 +285,25 @@ ZBM(AREQ_ZDO_NODEDESCRSP, Z_AREQ | Z_ZDO, ZDO_NODE_DESC_RSP) // 4582 // Z_ZDO:activeEpReq ZBM(ZBS_ZDO_ACTIVEEPREQ, Z_SREQ | Z_ZDO, ZDO_ACTIVE_EP_REQ, 0x00, 0x00, 0x00, 0x00) // 250500000000 -ZBM(ZBR_ZDO_ACTIVEEPREQ, Z_SRSP | Z_ZDO, ZDO_ACTIVE_EP_REQ, Z_Success) // 65050000 -ZBM(ZBR_ZDO_ACTIVEEPRSP_NONE, Z_AREQ | Z_ZDO, ZDO_ACTIVE_EP_RSP, 0x00, 0x00 /* srcAddr */, Z_Success, +ZBM(ZBR_ZDO_ACTIVEEPREQ, Z_SRSP | Z_ZDO, ZDO_ACTIVE_EP_REQ, Z_SUCCESS) // 65050000 +ZBM(ZBR_ZDO_ACTIVEEPRSP_NONE, Z_AREQ | Z_ZDO, ZDO_ACTIVE_EP_RSP, 0x00, 0x00 /* srcAddr */, Z_SUCCESS, 0x00, 0x00 /* nwkaddr */, 0x00 /* activeepcount */) // 45050000 - no Ep running -ZBM(ZBR_ZDO_ACTIVEEPRSP_OK, Z_AREQ | Z_ZDO, ZDO_ACTIVE_EP_RSP, 0x00, 0x00 /* srcAddr */, Z_Success, +ZBM(ZBR_ZDO_ACTIVEEPRSP_OK, Z_AREQ | Z_ZDO, ZDO_ACTIVE_EP_RSP, 0x00, 0x00 /* srcAddr */, Z_SUCCESS, 0x00, 0x00 /* nwkaddr */, 0x02 /* activeepcount */, 0x0B, 0x01 /* the actual endpoints */) // 25050000 - no Ep running // Z_AF:register profile:104, ep:01 ZBM(ZBS_AF_REGISTER01, Z_SREQ | Z_AF, AF_REGISTER, 0x01 /* endpoint */, Z_B0(Z_PROF_HA), Z_B1(Z_PROF_HA), // 24000401050000000000 0x05, 0x00 /* AppDeviceId */, 0x00 /* AppDevVer */, 0x00 /* LatencyReq */, 0x00 /* AppNumInClusters */, 0x00 /* AppNumInClusters */) -ZBM(ZBR_AF_REGISTER, Z_SRSP | Z_AF, AF_REGISTER, Z_Success) // 640000 +ZBM(ZBR_AF_REGISTER, Z_SRSP | Z_AF, AF_REGISTER, Z_SUCCESS) // 640000 ZBM(ZBS_AF_REGISTER0B, Z_SREQ | Z_AF, AF_REGISTER, 0x0B /* endpoint */, Z_B0(Z_PROF_HA), Z_B1(Z_PROF_HA), // 2400040B050000000000 0x05, 0x00 /* AppDeviceId */, 0x00 /* AppDevVer */, 0x00 /* LatencyReq */, 0x00 /* AppNumInClusters */, 0x00 /* AppNumInClusters */) // Z_ZDO:mgmtPermitJoinReq ZBM(ZBS_PERMITJOINREQ_CLOSE, Z_SREQ | Z_ZDO, ZDO_MGMT_PERMIT_JOIN_REQ, 0x02 /* AddrMode */, // 25360200000000 0x00, 0x00 /* DstAddr */, 0x00 /* Duration */, 0x00 /* TCSignificance */) -ZBM(ZBS_PERMITJOINREQ_OPEN_60, Z_SREQ | Z_ZDO, ZDO_MGMT_PERMIT_JOIN_REQ, 0x0F /* AddrMode */, // 25360FFFFC3C00 - 0xFC, 0xFF /* DstAddr */, 60 /* Duration */, 0x00 /* TCSignificance */) -ZBM(ZBS_PERMITJOINREQ_OPEN_XX, Z_SREQ | Z_ZDO, ZDO_MGMT_PERMIT_JOIN_REQ, 0x0F /* AddrMode */, // 25360FFFFCFF00 - 0xFC, 0xFF /* DstAddr */, 0xFF /* Duration */, 0x00 /* TCSignificance */) -ZBM(ZBR_PERMITJOINREQ, Z_SRSP | Z_ZDO, ZDO_MGMT_PERMIT_JOIN_REQ, Z_Success) // 653600 -ZBM(ZBR_PERMITJOIN_AREQ_CLOSE, Z_AREQ | Z_ZDO, ZDO_PERMIT_JOIN_IND, 0x00 /* Duration */) // 45CB00 -ZBM(ZBR_PERMITJOIN_AREQ_OPEN_60, Z_AREQ | Z_ZDO, ZDO_PERMIT_JOIN_IND, 60 /* Duration */) // 45CB3C -ZBM(ZBR_PERMITJOIN_AREQ_OPEN_FF, Z_AREQ | Z_ZDO, ZDO_PERMIT_JOIN_IND, 0xFF /* Duration */) // 45CBFF -ZBM(ZBR_PERMITJOIN_AREQ_RSP, Z_AREQ | Z_ZDO, ZDO_MGMT_PERMIT_JOIN_RSP, 0x00, 0x00 /* srcAddr*/, Z_Success ) // 45B6000000 +ZBM(ZBR_PERMITJOINREQ, Z_SRSP | Z_ZDO, ZDO_MGMT_PERMIT_JOIN_REQ, Z_SUCCESS) // 653600 +ZBM(ZBR_PERMITJOIN_AREQ_RSP, Z_AREQ | Z_ZDO, ZDO_MGMT_PERMIT_JOIN_RSP, 0x00, 0x00 /* srcAddr*/, Z_SUCCESS ) // 45B6000000 static const Zigbee_Instruction zb_prog[] PROGMEM = { ZI_LABEL(0) @@ -346,7 +339,6 @@ static const Zigbee_Instruction zb_prog[] PROGMEM = { ZI_LABEL(ZIGBEE_LABEL_START) // START ZNP App ZI_MQTT_STATE(ZIGBEE_STATUS_STARTING, "Configured, starting coordinator") - //ZI_CALL(&Z_State_Ready, 1) // Now accept incoming messages ZI_ON_ERROR_GOTO(ZIGBEE_LABEL_ABORT) // Z_ZDO:startupFromApp //ZI_LOG(LOG_LEVEL_INFO, D_LOG_ZIGBEE "starting zigbee coordinator") @@ -366,53 +358,24 @@ ZI_SEND(ZBS_STARTUPFROMAPP) // start coordinator ZI_WAIT_RECV(1000, ZBR_AF_REGISTER) ZI_SEND(ZBS_AF_REGISTER0B) // Z_AF register for endpoint 0B, profile 0x0104 Home Automation ZI_WAIT_RECV(1000, ZBR_AF_REGISTER) - // Z_ZDO:nodeDescReq ?? Is is useful to redo it? TODO // redo Z_ZDO:activeEpReq to check that Ep are available ZI_SEND(ZBS_ZDO_ACTIVEEPREQ) // Z_ZDO:activeEpReq ZI_WAIT_RECV(1000, ZBR_ZDO_ACTIVEEPREQ) ZI_WAIT_UNTIL(1000, ZBR_ZDO_ACTIVEEPRSP_OK) ZI_SEND(ZBS_PERMITJOINREQ_CLOSE) // Closing the Permit Join ZI_WAIT_RECV(1000, ZBR_PERMITJOINREQ) - ZI_WAIT_UNTIL(1000, ZBR_PERMITJOIN_AREQ_RSP) // not sure it's useful - //ZI_WAIT_UNTIL(500, ZBR_PERMITJOIN_AREQ_CLOSE) - //ZI_SEND(ZBS_PERMITJOINREQ_OPEN_XX) // Opening Permit Join, normally through command - //ZI_WAIT_RECV(1000, ZBR_PERMITJOINREQ) - //ZI_WAIT_UNTIL(1000, ZBR_PERMITJOIN_AREQ_RSP) // not sure it's useful - //ZI_WAIT_UNTIL(500, ZBR_PERMITJOIN_AREQ_OPEN_FF) - + ZI_WAIT_UNTIL(1000, ZBR_PERMITJOIN_AREQ_RSP) + ZI_LABEL(ZIGBEE_LABEL_READY) ZI_MQTT_STATE(ZIGBEE_STATUS_OK, "Started") ZI_LOG(LOG_LEVEL_INFO, D_LOG_ZIGBEE "Zigbee started") ZI_CALL(&Z_State_Ready, 1) // Now accept incoming messages ZI_CALL(&Z_Load_Devices, 0) + ZI_CALL(&Z_Query_Bulbs, 0) ZI_LABEL(ZIGBEE_LABEL_MAIN_LOOP) ZI_WAIT_FOREVER() ZI_GOTO(ZIGBEE_LABEL_READY) - ZI_LABEL(ZIGBEE_LABEL_PERMIT_JOIN_CLOSE) - //ZI_MQTT_STATE(ZIGBEE_STATUS_PERMITJOIN_CLOSE, "Disable Pairing mode") - ZI_SEND(ZBS_PERMITJOINREQ_CLOSE) // Closing the Permit Join - ZI_WAIT_RECV(1000, ZBR_PERMITJOINREQ) - //ZI_WAIT_UNTIL(1000, ZBR_PERMITJOIN_AREQ_RSP) // not sure it's useful - //ZI_WAIT_UNTIL(500, ZBR_PERMITJOIN_AREQ_CLOSE) - ZI_GOTO(ZIGBEE_LABEL_MAIN_LOOP) - - ZI_LABEL(ZIGBEE_LABEL_PERMIT_JOIN_OPEN_60) - //ZI_MQTT_STATE(ZIGBEE_STATUS_PERMITJOIN_OPEN_60, "Enable Pairing mode for 60 seconds") - ZI_SEND(ZBS_PERMITJOINREQ_OPEN_60) - ZI_WAIT_RECV(1000, ZBR_PERMITJOINREQ) - //ZI_WAIT_UNTIL(1000, ZBR_PERMITJOIN_AREQ_RSP) // not sure it's useful - //ZI_WAIT_UNTIL(500, ZBR_PERMITJOIN_AREQ_OPEN_60) - ZI_GOTO(ZIGBEE_LABEL_MAIN_LOOP) - - ZI_LABEL(ZIGBEE_LABEL_PERMIT_JOIN_OPEN_XX) - //ZI_MQTT_STATE(ZIGBEE_STATUS_PERMITJOIN_OPEN_XX, "Enable Pairing mode until next boot") - ZI_SEND(ZBS_PERMITJOINREQ_OPEN_XX) - ZI_WAIT_RECV(1000, ZBR_PERMITJOINREQ) - //ZI_WAIT_UNTIL(1000, ZBR_PERMITJOIN_AREQ_RSP) // not sure it's useful - //ZI_WAIT_UNTIL(500, ZBR_PERMITJOIN_AREQ_OPEN_FF) - ZI_GOTO(ZIGBEE_LABEL_MAIN_LOOP) - ZI_LABEL(50) // reformat device ZI_MQTT_STATE(ZIGBEE_STATUS_RESET_CONF, "Reseting configuration") //ZI_LOG(LOG_LEVEL_INFO, D_LOG_ZIGBEE "zigbee bad configuration of device, doing a factory reset") diff --git a/tasmota/xdrv_23_zigbee_8_parsers.ino b/tasmota/xdrv_23_zigbee_8_parsers.ino index 859351438..c1935bf0f 100644 --- a/tasmota/xdrv_23_zigbee_8_parsers.ino +++ b/tasmota/xdrv_23_zigbee_8_parsers.ino @@ -223,8 +223,6 @@ int32_t Z_ReceiveNodeDesc(int32_t res, const class SBuffer &buf) { uint8_t descriptorCapabilities = buf.get8(19); if (0 == status) { - zigbee_devices.updateLastSeen(nwkAddr); - uint8_t deviceType = logicalType & 0x7; // 0=coordinator, 1=router, 2=end device if (deviceType > 3) { deviceType = 3; } bool complexDescriptorAvailable = (logicalType & 0x08) ? 1 : 0; @@ -364,11 +362,11 @@ int32_t Z_ReceiveIEEEAddr(int32_t res, const class SBuffer &buf) { // MqttPublishPrefixTopic_P(RESULT_OR_TELE, PSTR(D_JSON_ZIGBEEZCL_RECEIVED)); // XdrvRulesProcess(); // Ping response - const String * friendlyName = zigbee_devices.getFriendlyName(nwkAddr); + const char * friendlyName = zigbee_devices.getFriendlyName(nwkAddr); if (friendlyName) { Response_P(PSTR("{\"" D_JSON_ZIGBEE_PING "\":{\"" D_JSON_ZIGBEE_DEVICE "\":\"0x%04X\"" ",\"" D_JSON_ZIGBEE_IEEE "\":\"0x%s\"" - ",\"" D_JSON_ZIGBEE_NAME "\":\"%s\"}}"), nwkAddr, hex, friendlyName->c_str()); + ",\"" D_JSON_ZIGBEE_NAME "\":\"%s\"}}"), nwkAddr, hex, friendlyName); } else { Response_P(PSTR("{\"" D_JSON_ZIGBEE_PING "\":{\"" D_JSON_ZIGBEE_DEVICE "\":\"0x%04X\"" ",\"" D_JSON_ZIGBEE_IEEE "\":\"0x%s\"" @@ -384,17 +382,23 @@ int32_t Z_ReceiveIEEEAddr(int32_t res, const class SBuffer &buf) { int32_t Z_BindRsp(int32_t res, const class SBuffer &buf) { Z_ShortAddress nwkAddr = buf.get16(2); uint8_t status = buf.get8(4); + char status_message[32]; - const String * friendlyName = zigbee_devices.getFriendlyName(nwkAddr); + strncpy_P(status_message, (const char*) getZigbeeStatusMessage(status), sizeof(status_message)); + status_message[sizeof(status_message)-1] = 0; // truncate if needed, strlcpy is safer but strlcpy_P does not exist + + const char * friendlyName = zigbee_devices.getFriendlyName(nwkAddr); if (friendlyName) { Response_P(PSTR("{\"" D_JSON_ZIGBEE_BIND "\":{\"" D_JSON_ZIGBEE_DEVICE "\":\"0x%04X\"" ",\"" D_JSON_ZIGBEE_NAME "\":\"%s\"" - ",\"" D_JSON_ZIGBEE_Status "\":%d" - "}}"), nwkAddr, friendlyName->c_str(), status); + ",\"" D_JSON_ZIGBEE_STATUS "\":%d" + ",\"" D_JSON_ZIGBEE_STATUS_MSG "\":\"%s\"" + "}}"), nwkAddr, friendlyName, status, status_message); } else { Response_P(PSTR("{\"" D_JSON_ZIGBEE_BIND "\":{\"" D_JSON_ZIGBEE_DEVICE "\":\"0x%04X\"" - ",\"" D_JSON_ZIGBEE_Status "\":%d" - "}}"), nwkAddr, status); + ",\"" D_JSON_ZIGBEE_STATUS "\":%d" + ",\"" D_JSON_ZIGBEE_STATUS_MSG "\":\"%s\"" + "}}"), nwkAddr, status, status_message); } MqttPublishPrefixTopic_P(RESULT_OR_TELE, PSTR(D_JSON_ZIGBEEZCL_RECEIVED)); XdrvRulesProcess(); @@ -402,6 +406,31 @@ int32_t Z_BindRsp(int32_t res, const class SBuffer &buf) { return -1; } +// +// Report any AF_DATA_CONFIRM message +// Ex: {"ZbConfirm":{"Endpoint":1,"Status":0,"StatusMessage":"SUCCESS"}} +// +int32_t Z_DataConfirm(int32_t res, const class SBuffer &buf) { + uint8_t status = buf.get8(2); + uint8_t endpoint = buf.get8(3); + //uint8_t transId = buf.get8(4); + char status_message[32]; + + if (status) { // only report errors + strncpy_P(status_message, (const char*) getZigbeeStatusMessage(status), sizeof(status_message)); + status_message[sizeof(status_message)-1] = 0; // truncate if needed, strlcpy is safer but strlcpy_P does not exist + + Response_P(PSTR("{\"" D_JSON_ZIGBEE_CONFIRM "\":{\"" D_CMND_ZIGBEE_ENDPOINT "\":%d" + ",\"" D_JSON_ZIGBEE_STATUS "\":%d" + ",\"" D_JSON_ZIGBEE_STATUS_MSG "\":\"%s\"" + "}}"), endpoint, status, status_message); + MqttPublishPrefixTopic_P(RESULT_OR_TELE, PSTR(D_JSON_ZIGBEEZCL_RECEIVED)); + XdrvRulesProcess(); + } + + return -1; +} + int32_t Z_ReceiveEndDeviceAnnonce(int32_t res, const class SBuffer &buf) { Z_ShortAddress srcAddr = buf.get16(2); Z_ShortAddress nwkAddr = buf.get16(4); @@ -453,21 +482,21 @@ int32_t Z_ReceiveTCDevInd(int32_t res, const class SBuffer &buf) { // Here we add a timer so if we don't receive a Occupancy event for 90 seconds, we send Occupancy:false const uint32_t OCCUPANCY_TIMEOUT = 90 * 1000; // 90 s -void Z_AqaraOccupancy(uint16_t shortaddr, uint16_t cluster, uint16_t endpoint, const JsonObject *json) { +void Z_AqaraOccupancy(uint16_t shortaddr, uint16_t cluster, uint8_t endpoint, const JsonObject *json) { // Read OCCUPANCY value if any const JsonVariant &val_endpoint = getCaseInsensitive(*json, PSTR(OCCUPANCY)); if (nullptr != &val_endpoint) { uint32_t occupancy = strToUInt(val_endpoint); if (occupancy) { - zigbee_devices.setTimer(shortaddr, OCCUPANCY_TIMEOUT, cluster, endpoint, 0, &Z_OccupancyCallback); + zigbee_devices.setTimer(shortaddr, 0 /* groupaddr */, OCCUPANCY_TIMEOUT, cluster, endpoint, Z_CAT_VIRTUAL_ATTR, 0, &Z_OccupancyCallback); } } } // Publish the received values once they have been coalesced -int32_t Z_PublishAttributes(uint16_t shortaddr, uint16_t cluster, uint16_t endpoint, uint32_t value) { +int32_t Z_PublishAttributes(uint16_t shortaddr, uint16_t groupaddr, uint16_t cluster, uint8_t endpoint, uint32_t value) { const JsonObject *json = zigbee_devices.jsonGet(shortaddr); if (json == nullptr) { return 0; } // don't crash if not found // Post-provess for Aqara Presence Senson @@ -491,7 +520,6 @@ int32_t Z_ReceiveAfIncomingMessage(int32_t res, const class SBuffer &buf) { bool defer_attributes = false; // do we defer attributes reporting to coalesce - zigbee_devices.updateLastSeen(srcaddr); ZCLFrame zcl_received = ZCLFrame::parseRawFrame(buf, 19, buf.get8(18), clusterid, groupid, srcaddr, srcendpoint, dstendpoint, wasbroadcast, @@ -503,7 +531,7 @@ int32_t Z_ReceiveAfIncomingMessage(int32_t res, const class SBuffer &buf) { DynamicJsonBuffer jsonBuffer; JsonObject& json = jsonBuffer.createObject(); - + if ( (!zcl_received.isClusterSpecificCommand()) && (ZCL_DEFAULT_RESPONSE == zcl_received.getCmdId())) { zcl_received.parseResponse(); } else { @@ -513,6 +541,7 @@ int32_t Z_ReceiveAfIncomingMessage(int32_t res, const class SBuffer &buf) { if (clusterid) { defer_attributes = true; } // don't defer system Cluster=0 messages } else if ( (!zcl_received.isClusterSpecificCommand()) && (ZCL_READ_ATTRIBUTES_RESPONSE == zcl_received.getCmdId())) { zcl_received.parseReadAttributes(json); + if (clusterid) { defer_attributes = true; } // don't defer system Cluster=0 messages } else if (zcl_received.isClusterSpecificCommand()) { zcl_received.parseClusterSpecificCommand(json); } @@ -538,7 +567,7 @@ int32_t Z_ReceiveAfIncomingMessage(int32_t res, const class SBuffer &buf) { zigbee_devices.jsonPublishFlush(srcaddr); } zigbee_devices.jsonAppend(srcaddr, json); - zigbee_devices.setTimer(srcaddr, USE_ZIGBEE_COALESCE_ATTR_TIMER, clusterid, srcendpoint, 0, &Z_PublishAttributes); + zigbee_devices.setTimer(srcaddr, 0 /* groupaddr */, USE_ZIGBEE_COALESCE_ATTR_TIMER, clusterid, srcendpoint, Z_CAT_READ_ATTR, 0, &Z_PublishAttributes); } else { // Publish immediately zigbee_devices.jsonPublishNow(srcaddr, json); @@ -553,6 +582,7 @@ typedef struct Z_Dispatcher { } Z_Dispatcher; // Filters for ZCL frames +ZBM(AREQ_AF_DATA_CONFIRM, Z_AREQ | Z_AF, AF_DATA_CONFIRM) // 4480 ZBM(AREQ_AF_INCOMING_MESSAGE, Z_AREQ | Z_AF, AF_INCOMING_MSG) // 4481 ZBM(AREQ_END_DEVICE_ANNCE_IND, Z_AREQ | Z_ZDO, ZDO_END_DEVICE_ANNCE_IND) // 45C1 ZBM(AREQ_END_DEVICE_TC_DEV_IND, Z_AREQ | Z_ZDO, ZDO_TC_DEV_IND) // 45CA @@ -563,6 +593,7 @@ ZBM(AREQ_ZDO_IEEE_ADDR_RSP, Z_AREQ | Z_ZDO, ZDO_IEEE_ADDR_RSP) // 4581 ZBM(AREQ_ZDO_BIND_RSP, Z_AREQ | Z_ZDO, ZDO_BIND_RSP) // 45A1 const Z_Dispatcher Z_DispatchTable[] PROGMEM = { + { AREQ_AF_DATA_CONFIRM, &Z_DataConfirm }, { AREQ_AF_INCOMING_MESSAGE, &Z_ReceiveAfIncomingMessage }, { AREQ_END_DEVICE_ANNCE_IND, &Z_ReceiveEndDeviceAnnonce }, { AREQ_END_DEVICE_TC_DEV_IND, &Z_ReceiveTCDevInd }, @@ -595,6 +626,42 @@ int32_t Z_Load_Devices(uint8_t value) { return 0; // continue } +int32_t Z_Query_Bulbs(uint8_t value) { + // Scan all devices and send deferred requests to know the state of bulbs + uint32_t wait_ms = 1000; // start with 1.0 s delay + const uint32_t inter_message_ms = 100; // wait 100ms between messages + for (uint32_t i = 0; i < zigbee_devices.devicesSize(); i++) { + const Z_Device &device = zigbee_devices.devicesAt(i); + + if (0 <= device.bulbtype) { + uint16_t cluster; + uint8_t endpoint; + + cluster = 0x0006; + endpoint = zigbee_devices.findClusterEndpointIn(device.shortaddr, cluster); + if (endpoint) { // send only if we know the endpoint + zigbee_devices.setTimer(device.shortaddr, 0 /* groupaddr */, wait_ms, cluster, endpoint, Z_CAT_NONE, 0 /* value */, &Z_ReadAttrCallback); + wait_ms += inter_message_ms; + } + + cluster = 0x0008; + endpoint = zigbee_devices.findClusterEndpointIn(device.shortaddr, cluster); + if (endpoint) { // send only if we know the endpoint + zigbee_devices.setTimer(device.shortaddr, 0 /* groupaddr */, wait_ms, cluster, endpoint, Z_CAT_NONE, 0 /* value */, &Z_ReadAttrCallback); + wait_ms += inter_message_ms; + } + + cluster = 0x0300; + endpoint = zigbee_devices.findClusterEndpointIn(device.shortaddr, cluster); + if (endpoint) { // send only if we know the endpoint + zigbee_devices.setTimer(device.shortaddr, 0 /* groupaddr */, wait_ms, cluster, endpoint, Z_CAT_NONE, 0 /* value */, &Z_ReadAttrCallback); + wait_ms += inter_message_ms; + } + } + } + return 0; // continue +} + int32_t Z_State_Ready(uint8_t value) { zigbee.init_phase = false; // initialization phase complete return 0; // continue diff --git a/tasmota/xdrv_23_zigbee_9_impl.ino b/tasmota/xdrv_23_zigbee_9_impl.ino index 3ed971b0e..a42beb7c7 100644 --- a/tasmota/xdrv_23_zigbee_9_impl.ino +++ b/tasmota/xdrv_23_zigbee_9_impl.ino @@ -34,7 +34,8 @@ const char kZbCommands[] PROGMEM = D_PRFX_ZB "|" // prefix D_CMND_ZIGBEE_STATUS "|" D_CMND_ZIGBEE_RESET "|" D_CMND_ZIGBEE_SEND "|" D_CMND_ZIGBEE_PROBE "|" D_CMND_ZIGBEE_READ "|" D_CMND_ZIGBEEZNPRECEIVE "|" D_CMND_ZIGBEE_FORGET "|" D_CMND_ZIGBEE_SAVE "|" D_CMND_ZIGBEE_NAME "|" - D_CMND_ZIGBEE_BIND "|" D_CMND_ZIGBEE_PING "|" D_CMND_ZIGBEE_MODELID + D_CMND_ZIGBEE_BIND "|" D_CMND_ZIGBEE_PING "|" D_CMND_ZIGBEE_MODELID "|" + D_CMND_ZIGBEE_LIGHT ; void (* const ZigbeeCommand[])(void) PROGMEM = { @@ -43,6 +44,7 @@ void (* const ZigbeeCommand[])(void) PROGMEM = { &CmndZbProbe, &CmndZbRead, &CmndZbZNPReceive, &CmndZbForget, &CmndZbSave, &CmndZbName, &CmndZbBind, &CmndZbPing, &CmndZbModelId, + &CmndZbLight, }; int32_t ZigbeeProcessInput(class SBuffer &buf) { @@ -106,7 +108,7 @@ int32_t ZigbeeProcessInput(class SBuffer &buf) { res = (*zigbee.recv_unexpected)(res, buf); } } - AddLog_P2(LOG_LEVEL_DEBUG_MORE, PSTR(D_LOG_ZIGBEE "ZbProcessInput: res = %d"), res); + //AddLog_P2(LOG_LEVEL_DEBUG_MORE, PSTR(D_LOG_ZIGBEE "ZbProcessInput: res = %d"), res); // change state accordingly if (0 == res) { @@ -341,30 +343,40 @@ void ZigbeeZNPSend(const uint8_t *msg, size_t len) { ToHex_P(msg, len, hex_char, sizeof(hex_char))); } -void ZigbeeZCLSend(uint16_t dtsAddr, uint16_t clusterId, uint8_t endpoint, uint8_t cmdId, bool clusterSpecific, const uint8_t *msg, size_t len, bool needResponse, uint8_t transacId) { - SBuffer buf(25+len); - buf.add8(Z_SREQ | Z_AF); // 24 - buf.add8(AF_DATA_REQUEST); // 01 - buf.add16(dtsAddr); - buf.add8(endpoint); // dest endpoint - buf.add8(0x01); // source endpoint +void ZigbeeZCLSend_Raw(uint16_t shortaddr, uint16_t groupaddr, uint16_t clusterId, uint8_t endpoint, uint8_t cmdId, bool clusterSpecific, const uint8_t *msg, size_t len, bool needResponse, uint8_t transacId) { + + SBuffer buf(32+len); + buf.add8(Z_SREQ | Z_AF); // 24 + buf.add8(AF_DATA_REQUEST_EXT); // 02 + if (groupaddr) { + buf.add8(Z_Addr_Group); // 01 + buf.add64(groupaddr); // group address, only 2 LSB, upper 6 MSB are discarded + buf.add8(0xFF); // dest endpoint is not used for group addresses + } else { + buf.add8(Z_Addr_ShortAddress); // 02 + buf.add64(shortaddr); // dest address, only 2 LSB, upper 6 MSB are discarded + buf.add8(endpoint); // dest endpoint + } + buf.add16(0x0000); // dest Pan ID, 0x0000 = intra-pan + buf.add8(0x01); // source endpoint buf.add16(clusterId); - buf.add8(transacId); // transacId - buf.add8(0x30); // 30 options - buf.add8(0x1E); // 1E radius + buf.add8(transacId); // transacId + buf.add8(0x30); // 30 options + buf.add8(0x1E); // 1E radius - buf.add8(3 + len); + buf.add16(3 + len); buf.add8((needResponse ? 0x00 : 0x10) | (clusterSpecific ? 0x01 : 0x00)); // Frame Control Field - buf.add8(transacId); // Transaction Sequance Number + buf.add8(transacId); // Transaction Sequance Number buf.add8(cmdId); if (len > 0) { - buf.addBuffer(msg, len); // add the payload + buf.addBuffer(msg, len); // add the payload } ZigbeeZNPSend(buf.getBuffer(), buf.len()); } -void zigbeeZCLSendStr(uint16_t dstAddr, uint8_t endpoint, bool clusterSpecific, +// Send a command specified as an HEX string for the workload +void zigbeeZCLSendStr(uint16_t shortaddr, uint16_t groupaddr, uint8_t endpoint, bool clusterSpecific, uint16_t cluster, uint8_t cmd, const char *param) { size_t size = param ? strlen(param) : 0; SBuffer buf((size+2)/2); // actual bytes buffer for data @@ -376,26 +388,25 @@ void zigbeeZCLSendStr(uint16_t dstAddr, uint8_t endpoint, bool clusterSpecific, } } - if (0 == endpoint) { - // endpoint is not specified, let's try to find it from shortAddr - endpoint = zigbee_devices.findClusterEndpointIn(dstAddr, cluster); + if ((0 == endpoint) && (shortaddr)) { + // endpoint is not specified, let's try to find it from shortAddr, unless it's a group address + endpoint = zigbee_devices.findClusterEndpointIn(shortaddr, cluster); AddLog_P2(LOG_LEVEL_DEBUG, PSTR("ZbSend: guessing endpoint 0x%02X"), endpoint); } - AddLog_P2(LOG_LEVEL_DEBUG, PSTR("ZbSend: dstAddr 0x%04X, cluster 0x%04X, endpoint 0x%02X, cmd 0x%02X, data %s"), - dstAddr, cluster, endpoint, cmd, param); + AddLog_P2(LOG_LEVEL_DEBUG, PSTR("ZbSend: shortaddr 0x%04X, groupaddr 0x%04X, cluster 0x%04X, endpoint 0x%02X, cmd 0x%02X, data %s"), + shortaddr, groupaddr, cluster, endpoint, cmd, param); - if (0 == endpoint) { + if ((0 == endpoint) && (shortaddr)) { AddLog_P2(LOG_LEVEL_INFO, PSTR("ZbSend: unspecified endpoint")); return; - } + } // endpoint null is ok for group address // everything is good, we can send the command - ZigbeeZCLSend(dstAddr, cluster, endpoint, cmd, clusterSpecific, buf.getBuffer(), buf.len(), false, zigbee_devices.getNextSeqNumber(dstAddr)); + ZigbeeZCLSend_Raw(shortaddr, groupaddr, cluster, endpoint, cmd, clusterSpecific, buf.getBuffer(), buf.len(), true, zigbee_devices.getNextSeqNumber(shortaddr)); // now set the timer, if any, to read back the state later if (clusterSpecific) { - zigbeeSetCommandTimer(dstAddr, cluster, endpoint); + zigbeeSetCommandTimer(shortaddr, groupaddr, cluster, endpoint); } - ResponseCmndDone(); } void CmndZbSend(void) { @@ -417,20 +428,27 @@ void CmndZbSend(void) { // params static char delim[] = ", "; // delimiters for parameters - uint16_t device = 0xFFFF; // 0xFFFF is broadcast, so considered valid + uint16_t device = 0x0000; // 0xFFFF is broadcast, so considered valid + uint16_t groupaddr = 0x0000; // ignore group address if 0x0000 uint8_t endpoint = 0x00; // 0x00 is invalid for the dst endpoint // Command elements uint16_t cluster = 0; uint8_t cmd = 0; String cmd_str = ""; // the actual low-level command, either specified or computed + const char *cmd_s; // pointer to payload string + bool clusterSpecific = true; // parse JSON - const JsonVariant &val_device = getCaseInsensitive(json, PSTR("Device")); - if (nullptr != &val_device) { - device = zigbee_devices.parseDeviceParam(val_device.as()); - if (0xFFFF == device) { ResponseCmndChar("Invalid parameter"); return; } + const JsonVariant &val_group = getCaseInsensitive(json, PSTR("Group")); + if (nullptr != &val_group) { groupaddr = strToUInt(val_group); } + if (0x0000 == groupaddr) { // if no group address, we need a device address + const JsonVariant &val_device = getCaseInsensitive(json, PSTR("Device")); + if (nullptr != &val_device) { + device = zigbee_devices.parseDeviceParam(val_device.as()); + if (0xFFFF == device) { ResponseCmndChar("Invalid parameter"); return; } + } + if ((nullptr == &val_device) || (0x0000 == device)) { ResponseCmndChar("Unknown device"); return; } } - if ((nullptr == &val_device) || (0x000 == device)) { ResponseCmndChar("Unknown device"); return; } const JsonVariant &val_endpoint = getCaseInsensitive(json, PSTR("Endpoint")); if (nullptr != &val_endpoint) { endpoint = strToUInt(val_endpoint); } @@ -500,19 +518,44 @@ void CmndZbSend(void) { } cmd_str = zigbeeCmdAddParams(cmd_str.c_str(), x, y, z); // fill in parameters //AddLog_P2(LOG_LEVEL_DEBUG, PSTR("ZbSend: command_final = %s"), cmd_str.c_str()); + cmd_s = cmd_str.c_str(); } else { // we have zero command, pass through until last error for missing command } } else if (val_cmd.is()) { // low-level command cmd_str = val_cmd.as(); + // Now parse the string to extract cluster, command, and payload + // Parse 'cmd' in the form "AAAA_BB/CCCCCCCC" or "AAAA!BB/CCCCCCCC" + // where AA is the cluster number, BBBB the command number, CCCC... the payload + // First delimiter is '_' for a global command, or '!' for a cluster specific command + const char * data = cmd_str.c_str(); + cluster = parseHex(&data, 4); + + // delimiter + if (('_' == *data) || ('!' == *data)) { + if ('_' == *data) { clusterSpecific = false; } + data++; + } else { + ResponseCmndChar("Wrong delimiter for payload"); + return; + } + // parse cmd number + cmd = parseHex(&data, 2); + + // move to end of payload + // delimiter is optional + if ('/' == *data) { data++; } // skip delimiter + + cmd_s = data; } else { // we have an unsupported command type, just ignore it and fallback to missing command } - AddLog_P2(LOG_LEVEL_DEBUG, PSTR("ZbCmd_actual: ZigbeeZCLSend {\"device\":\"0x%04X\",\"endpoint\":%d,\"send\":\"%04X!%02X/%s\"}"), - device, endpoint, cluster, cmd, cmd_str.c_str()); - zigbeeZCLSendStr(device, endpoint, true, cluster, cmd, cmd_str.c_str()); + AddLog_P2(LOG_LEVEL_DEBUG, PSTR("ZigbeeZCLSend device: 0x%04X, group: 0x%04X, endpoint:%d, cluster:0x%04X, cmd:0x%02X, send:\"%s\""), + device, groupaddr, endpoint, cluster, cmd, cmd_s); + zigbeeZCLSendStr(device, groupaddr, endpoint, clusterSpecific, cluster, cmd, cmd_s); + ResponseCmndDone(); } else { Response_P(PSTR("Missing zigbee 'Send'")); return; @@ -520,16 +563,6 @@ void CmndZbSend(void) { } -ZBM(ZBS_BIND_REQ, Z_SREQ | Z_ZDO, ZDO_BIND_REQ, - 0,0, // dstAddr - 16 bits, device to send the bind to - 0,0,0,0,0,0,0,0, // srcAddr - 64 bits, IEEE binding source - 0x00, // source endpoint - 0x00, 0x00, // cluster - 0x03, // DstAddrMode - 0x03 = ADDRESS_64_BIT - 0,0,0,0,0,0,0,0, // dstAddr - 64 bits, IEEE binding destination, i.e. coordinator - 0x01 // dstEndpoint - 0x01 for coordinator -) - void CmndZbBind(void) { // ZbBind { "device":"0x1234", "endpoint":1, "cluster":6 } @@ -595,7 +628,7 @@ void CmndZbBind(void) { if (toGroup && dstLongAddr) { ResponseCmndChar("Cannot have both \"ToDevice\" and \"ToGroup\""); return; } if (!toGroup && !dstLongAddr) { ResponseCmndChar("Missing \"ToDevice\" or \"ToGroup\""); return; } - SBuffer buf(sizeof(ZBS_BIND_REQ)); + SBuffer buf(34); buf.add8(Z_SREQ | Z_ZDO); buf.add8(ZDO_BIND_REQ); buf.add16(srcDevice); @@ -661,8 +694,8 @@ void CmndZbName(void) { if (0xFFFF == shortaddr) { ResponseCmndChar("Invalid parameter"); return; } if (p == nullptr) { - const String * friendlyName = zigbee_devices.getFriendlyName(shortaddr); - Response_P(PSTR("{\"0x%04X\":{\"" D_JSON_ZIGBEE_NAME "\":\"%s\"}}"), shortaddr, friendlyName ? friendlyName->c_str() : ""); + const char * friendlyName = zigbee_devices.getFriendlyName(shortaddr); + Response_P(PSTR("{\"0x%04X\":{\"" D_JSON_ZIGBEE_NAME "\":\"%s\"}}"), shortaddr, friendlyName ? friendlyName : ""); } else { zigbee_devices.setFriendlyName(shortaddr, p); Response_P(PSTR("{\"0x%04X\":{\"" D_JSON_ZIGBEE_NAME "\":\"%s\"}}"), shortaddr, p); @@ -690,14 +723,45 @@ void CmndZbModelId(void) { if (0xFFFF == shortaddr) { ResponseCmndChar("Invalid parameter"); return; } if (p == nullptr) { - const String * modelId = zigbee_devices.getModelId(shortaddr); - Response_P(PSTR("{\"0x%04X\":{\"" D_JSON_ZIGBEE_MODELID "\":\"%s\"}}"), shortaddr, modelId ? modelId->c_str() : ""); + const char * modelId = zigbee_devices.getModelId(shortaddr); + Response_P(PSTR("{\"0x%04X\":{\"" D_JSON_ZIGBEE_MODELID "\":\"%s\"}}"), shortaddr, modelId ? modelId : ""); } else { zigbee_devices.setModelId(shortaddr, p); Response_P(PSTR("{\"0x%04X\":{\"" D_JSON_ZIGBEE_MODELID "\":\"%s\"}}"), shortaddr, p); } } +// Specify, read or erase a Light type for Hue/Alexa integration +void CmndZbLight(void) { + // Syntax is: + // ZbLight , - assign a bulb type 0-5 + // ZbLight - display the current bulb type and status + // + // Where can be: short_addr, long_addr, device_index, friendly_name + + if (zigbee.init_phase) { ResponseCmndChar(D_ZIGBEE_NOT_STARTED); return; } + + // check if parameters contain a comma ',' + char *p; + char *str = strtok_r(XdrvMailbox.data, ", ", &p); + + // parse first part, + uint16_t shortaddr = zigbee_devices.parseDeviceParam(XdrvMailbox.data, true); // in case of short_addr, it must be already registered + if (0x0000 == shortaddr) { ResponseCmndChar("Unknown device"); return; } + if (0xFFFF == shortaddr) { ResponseCmndChar("Invalid parameter"); return; } + + if (p) { + int8_t bulbtype = strtol(p, nullptr, 10); + zigbee_devices.setHueBulbtype(shortaddr, bulbtype); + } + String dump = zigbee_devices.dumpLightState(shortaddr); + Response_P(PSTR("{\"" D_PRFX_ZB D_CMND_ZIGBEE_LIGHT "\":%s}"), dump.c_str()); + + MqttPublishPrefixTopic_P(RESULT_OR_STAT, PSTR(D_PRFX_ZB D_CMND_ZIGBEE_LIGHT)); + XdrvRulesProcess(); + ResponseCmndDone(); +} + // Remove an old Zigbee device from the list of known devices, use ZigbeeStatus to know all registered devices void CmndZbForget(void) { if (zigbee.init_phase) { ResponseCmndChar(D_ZIGBEE_NOT_STARTED); return; } @@ -734,17 +798,22 @@ void CmndZbRead(void) { // params uint16_t device = 0xFFFF; // 0xFFFF is braodcast, so considered valid + uint16_t groupaddr = 0x0000; // if 0x0000 ignore group adress uint16_t cluster = 0x0000; // default to general cluster uint8_t endpoint = 0x00; // 0x00 is invalid for the dst endpoint size_t attrs_len = 0; uint8_t* attrs = nullptr; // empty string is valid - const JsonVariant &val_device = getCaseInsensitive(json, PSTR("Device")); - if (nullptr != &val_device) { - device = zigbee_devices.parseDeviceParam(val_device.as()); - if (0xFFFF == device) { ResponseCmndChar("Invalid parameter"); return; } + const JsonVariant &val_group = getCaseInsensitive(json, PSTR("Group")); + if (nullptr != &val_group) { groupaddr = strToUInt(val_group); } + if (0x0000 == groupaddr) { // if no group address, we need a device address + const JsonVariant &val_device = getCaseInsensitive(json, PSTR("Device")); + if (nullptr != &val_device) { + device = zigbee_devices.parseDeviceParam(val_device.as()); + if (0xFFFF == device) { ResponseCmndChar("Invalid parameter"); return; } + } + if ((nullptr == &val_device) || (0x0000 == device)) { ResponseCmndChar("Unknown device"); return; } } - if ((nullptr == &val_device) || (0x000 == device)) { ResponseCmndChar("Unknown device"); return; } const JsonVariant &val_cluster = getCaseInsensitive(json, PSTR("Cluster")); if (nullptr != &val_cluster) { cluster = strToUInt(val_cluster); } @@ -773,13 +842,16 @@ void CmndZbRead(void) { } } - if (0 == endpoint) { // try to compute the endpoint + if ((0 == endpoint) && (device)) { // try to compute the endpoint endpoint = zigbee_devices.findClusterEndpointIn(device, cluster); AddLog_P2(LOG_LEVEL_DEBUG, PSTR("ZbSend: guessing endpoint 0x%02X"), endpoint); } + if (groupaddr) { + endpoint = 0xFF; // endpoint not used for group addresses + } if ((0 != endpoint) && (attrs_len > 0)) { - ZigbeeZCLSend(device, cluster, endpoint, ZCL_READ_ATTRIBUTES, false, attrs, attrs_len, true /* we do want a response */, zigbee_devices.getNextSeqNumber(device)); + ZigbeeZCLSend_Raw(device, groupaddr, cluster, endpoint, ZCL_READ_ATTRIBUTES, false, attrs, attrs_len, true /* we do want a response */, zigbee_devices.getNextSeqNumber(device)); ResponseCmndDone(); } else { ResponseCmndChar("Missing parameters"); @@ -789,20 +861,28 @@ void CmndZbRead(void) { } // Allow or Deny pairing of new Zigbee devices -void CmndZbPermitJoin(void) -{ +void CmndZbPermitJoin(void) { if (zigbee.init_phase) { ResponseCmndChar(D_ZIGBEE_NOT_STARTED); return; } uint32_t payload = XdrvMailbox.payload; - if (payload < 0) { payload = 0; } - if ((99 != payload) && (payload > 1)) { payload = 1; } + uint16_t dstAddr = 0xFFFC; // default addr + uint8_t duration = 60; // default 60s - if (1 == payload) { - ZigbeeGotoLabel(ZIGBEE_LABEL_PERMIT_JOIN_OPEN_60); - } else if (99 == payload){ - ZigbeeGotoLabel(ZIGBEE_LABEL_PERMIT_JOIN_OPEN_XX); - } else { - ZigbeeGotoLabel(ZIGBEE_LABEL_PERMIT_JOIN_CLOSE); + if (payload <= 0) { + duration = 0; + } else if (99 == payload) { + duration = 0xFF; // unlimited time } + + SBuffer buf(34); + buf.add8(Z_SREQ | Z_ZDO); // 25 + buf.add8(ZDO_MGMT_PERMIT_JOIN_REQ); // 36 + buf.add8(0x0F); // AddrMode + buf.add16(0xFFFC); // DstAddr + buf.add8(duration); + buf.add8(0x00); // TCSignificance + + ZigbeeZNPSend(buf.getBuffer(), buf.len()); + ResponseCmndDone(); } From 100acc5664eacb1cf709eb7d7bb4c45e43bfd6c6 Mon Sep 17 00:00:00 2001 From: Theo Arends <11044339+arendst@users.noreply.github.com> Date: Sat, 14 Mar 2020 14:54:11 +0100 Subject: [PATCH 19/20] Fix switch status --- tasmota/support_switch.ino | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tasmota/support_switch.ino b/tasmota/support_switch.ino index 7acdda409..f1d5c7ea2 100644 --- a/tasmota/support_switch.ino +++ b/tasmota/support_switch.ino @@ -70,7 +70,8 @@ bool SwitchState(uint32_t index) (PUSHBUTTON_INV == switchmode) || (PUSHBUTTONHOLD_INV == switchmode) || (FOLLOWMULTI_INV == switchmode) || - (PUSHHOLDMULTI_INV == switchmode) + (PUSHHOLDMULTI_INV == switchmode) || + (PUSHON_INV == switchmode) ) ^ Switch.last_state[index]; } From 5d944829cdd80da527d94be7cac8ab7ec7bb5c96 Mon Sep 17 00:00:00 2001 From: Theo Arends <11044339+arendst@users.noreply.github.com> Date: Sat, 14 Mar 2020 15:24:22 +0100 Subject: [PATCH 20/20] Update changelog and release notes --- RELEASENOTES.md | 60 +++++++++++++++++++++++--------------------- tasmota/CHANGELOG.md | 2 +- 2 files changed, 32 insertions(+), 30 deletions(-) diff --git a/RELEASENOTES.md b/RELEASENOTES.md index a2757b96f..c96effd80 100644 --- a/RELEASENOTES.md +++ b/RELEASENOTES.md @@ -54,28 +54,28 @@ The following binary downloads have been compiled with ESP8266/Arduino library c ### Version 8.1.0.11 -- Change default my_user_config.h driver and sensor support removing most sensors and adding most drivers +- Change default my_user_config.h driver and sensor support removing most sensors and adding most drivers to tasmota.bin - Change DHT driver (#7468, #7717) - Change Lights: simplified gamma correction and 10 bits internal computation - Change commands ``Prefix``, ``Ssid``, ``StateText``, ``NTPServer``, and ``FriendlyName`` displaying all items -- Change IRremoteESP8266 library updated to v2.7.4 - Change Zigbee command prefix from ``Zigbee*`` to ``Zb*`` - Change MQTT message size with additional 200 characters - Change display of some date and time messages from "Wed Feb 19 10:45:12 2020" to "2020-02-19T10:45:12" -- Fix Sonoff Bridge, Sc, L1, iFan03 and CSE7766 serial interface to forced speed, config and disable logging -- Fix commands ``Display`` and ``Counter`` from overruling command processing (#7322) +- Change IRremoteESP8266 library updated to v2.7.4 +- Fix ``PowerDelta`` zero power detection (#7515) - Fix ``White`` added to light status (#7142) +- Fix ``WakeUp `` ignores provided value (#7473) +- Fix ``RGBWWTable`` ignored (#7572) +- Fix commands ``Display`` and ``Counter`` from overruling command processing (#7322) +- Fix Sonoff Bridge, Sc, L1, iFan03 and CSE7766 serial interface to forced speed, config and disable logging - Fix Improved fade linearity with gamma correction +- Fix PWM flickering at low levels (#7415) - Fix LCD line and column positioning (#7387) - Fix Display handling of hexadecimal escape characters (#7387) -- Fix ``WakeUp `` ignores provided value (#7473) - Fix exception 9 restart on log message in Ticker interrupt service routines NTP, Wemos and Hue emulation (#7496) -- Fix ``PowerDelta`` zero power detection (#7515) -- Fix ``RGBWWTable`` ignored (#7572) -- Fix PWM flickering at low levels (#7415) -- Fix Hass sensor discovery part 1/4 by Federico Leoni (#7582, #7548) +- Fix Hass sensor discovery by Federico Leoni (#7582, #7548) - Fix MaxPower functionality (#7647) -- Fix relation between RSSI and signal strength +- Fix relation between Wifi RSSI and signal strength - Add command ``SetOption79 0/1`` to enable reset of counters at teleperiod time by Andre Thomas (#7355) - Add command ``SetOption82 0/1`` to limit the CT range for Alexa to 200..380 - Add command ``SetOption84 0/1`` to send AWS IoT device shadow updates (alternative to retained) @@ -89,33 +89,35 @@ The following binary downloads have been compiled with ESP8266/Arduino library c - Add commands ``SwitchMode 11`` PushHoldMulti and ``SwitchMode 12`` PushHoldInverted (#7603) - Add commands ``SwitchMode 13`` PushOn and ``SwitchMode 14`` PushOnInverted (#7912) - Add command ``Buzzer -1`` for infinite mode and command ``Buzzer -2`` for following led mode (#7623) -- Add SerialConfig to ``Status 1`` -- Add WifiPower to ``Status 5`` -- Add support for DS1624, DS1621 Temperature sensor by Leonid Myravjev -- Add Zigbee attribute decoder for Xiaomi Aqara Cube - Add support for ``AdcParam`` parameters to control ADC0 Current Transformer Apparent Power formula by Jodi Dillon (#7100) -- Add optional support for Prometheus using file xsns_91_prometheus.ino (#7216) -- Add experimental support for NRF24L01 as BLE-bridge for Mijia Bluetooth sensors by Christian Baars (#7394) -- Add support to BMP driver to enter reset state (sleep enable) when deep sleep is used in Tasmota -- Add support for gzipped binaries -- Add web page sliders when ``SetOption37 128`` is active allowing control of white(s) -- Add most SetOptions as defines to my_user_config.h -- Add SoftwareSerial to CSE7766 driver allowing different GPIOs (#7563) - Add optional parameter to command ``Scheme , `` to control initial start color -- Add rule trigger on one level deeper using syntax with two ``#`` like ``on zigbeereceived#vibration_sensor#aqaracubeside=0 do ...`` -- Add support for sensors DS18x20 and DHT family on Shelly 1 and Shelly 1PM using Shelly Add-On adapter (#7469) -- Add support for MI-BLE sensors using HM-10 Bluetooth 4.0 module by Christian Staars (#7683) +- Add web page sliders when ``SetOption37 128`` is active allowing control of white(s) +- Add SerialConfig to ``Status 1`` - Add BootCount Reset Time as BCResetTime to ``Status 1`` -- Add ``ZbZNPReceived``and ``ZbZCLReceived`` being published to MQTT when ``SetOption66 1`` +- Add WifiPower to ``Status 5`` +- Add most SetOptions as defines to my_user_config.h - Add optional Wifi AccessPoint passphrase define WIFI_AP_PASSPHRASE in my_user_config.h (#7690) -- Add support for FiF LE-01MR energy meter by saper-2 (#7584) -- Add initial support for Sensors AHT10 and AHT15 by Martin Wagner (#7596) -- Add support for Wemos Motor Shield V1 by Denis Sborets (#7764) +- Add SoftwareSerial to CSE7766 driver allowing different GPIOs (#7563) +- Add rule trigger on one level deeper using syntax with two ``#`` like ``on zbreceived#vibration_sensor#aqaracubeside=0 do ...`` +- Add Zigbee attribute decoder for Xiaomi Aqara Cube +- Add ``ZbZNPReceived``and ``ZbZCLReceived`` being published to MQTT when ``SetOption66 1`` - Add Zigbee enhanced commands decoding, added ``ZbPing`` - Add Zigbee features and improvements +- Add Zigbee support for Hue emulation by Stefan Hadinger +- Add HAss Discovery support for Button and Switch triggers by Federico Leoni (#7901) +- Add optional support for Prometheus using file xsns_91_prometheus.ino (#7216) +- Add support to BMP driver to enter reset state (sleep enable) when deep sleep is used in Tasmota +- Add support for DS1624, DS1621 Temperature sensor by Leonid Myravjev +- Add support for NRF24L01 as BLE-bridge for Mijia Bluetooth sensors by Christian Baars (#7394) +- Add support for gzipped binaries +- Add support for sensors DS18x20 and DHT family on Shelly 1 and Shelly 1PM using Shelly Add-On adapter (#7469) +- Add support for MI-BLE sensors using HM-10 Bluetooth 4.0 module by Christian Staars (#7683) +- Add support for FiF LE-01MR energy meter by saper-2 (#7584) +- Add support for Sensors AHT10 and AHT15 by Martin Wagner (#7596) +- Add support for Wemos Motor Shield V1 by Denis Sborets (#7764) - Add support for Martin Jerry/acenx/Tessan/NTONPOWER SD0x PWM dimmer switches by Paul Diem (#7791) +- Add support for UDP Group control without MQTT by Paul Diem (#7790) - Add support for Jarolift rollers by Keeloq algorithm - Add support for MaxBotix HRXL-MaxSonar ultrasonic range finders by Jon Little (#7814) - Add support for Romanian language translations by Augustin Marti -- Add HAss Discovery support for Button and Switch triggers by Federico Leoni (#7901) - Add support for HDC1080 Temperature and Humidity sensor by Luis Teixeira (#7888) diff --git a/tasmota/CHANGELOG.md b/tasmota/CHANGELOG.md index 89c4103b9..52c592e4c 100644 --- a/tasmota/CHANGELOG.md +++ b/tasmota/CHANGELOG.md @@ -5,7 +5,7 @@ - Add HAss Discovery support for Button and Switch triggers by Federico Leoni (#7901) - Add support for HDC1080 Temperature and Humidity sensor by Luis Teixeira (#7888) - Add commands ``SwitchMode 13`` PushOn and ``SwitchMode 14`` PushOnInverted (#7912) -- Add Zigbee support for Hue emulation +- Add Zigbee support for Hue emulation by Stefan Hadinger ### 8.1.0.10 20200227