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(); }