├── components └── device_groups │ ├── esp_idf_compatibility.h │ ├── __init__.py │ ├── device_groups_WiFiUdp.h │ ├── device_groups.h │ ├── device_groups_WiFiUdp.cpp │ └── device_groups.cpp ├── README.md └── LICENSE /components/device_groups/esp_idf_compatibility.h: -------------------------------------------------------------------------------- 1 | #ifndef ESP_IDF_COMPATIBILITY_H 2 | #define ESP_IDF_COMPATIBILITY_H 3 | 4 | #if defined(USE_ESP_IDF) 5 | 6 | // ESP-IDF compatibility for Arduino PROGMEM functions 7 | #define PSTR(str) (str) 8 | 9 | // ESP-IDF compatibility for sprintf_P (PROGMEM version of sprintf) 10 | #define sprintf_P sprintf 11 | 12 | // ESP-IDF compatibility for snprintf_P (PROGMEM version of snprintf) 13 | #define snprintf_P snprintf 14 | 15 | // ESP-IDF compatibility for strncmp_P (PROGMEM version of strncmp) 16 | #define strncmp_P strncmp 17 | 18 | #endif // USE_ESP_IDF 19 | 20 | #endif // ESP_IDF_COMPATIBILITY_H 21 | -------------------------------------------------------------------------------- /components/device_groups/__init__.py: -------------------------------------------------------------------------------- 1 | from esphome.const import ( 2 | CONF_ID, 3 | ) 4 | import esphome.codegen as cg 5 | import esphome.config_validation as cv 6 | from esphome.components import switch, light 7 | from esphome.core import CORE 8 | 9 | CODEOWNERS = ["@Cossid"] 10 | DEPENDENCIES = ["network"] 11 | 12 | device_groups_ns = cg.esphome_ns.namespace("device_groups") 13 | device_groups = device_groups_ns.class_("device_groups", cg.Component) 14 | 15 | MULTI_CONF = True 16 | CONF_GROUP_NAME = "group_name" 17 | CONF_SWITCHES = "switches" 18 | CONF_LIGHTS = "lights" 19 | CONF_SEND_MASK = "send_mask" 20 | CONF_RECEIVE_MASK = "receive_mask" 21 | 22 | CONFIG_SCHEMA = cv.Schema( 23 | { 24 | cv.GenerateID(CONF_ID): cv.declare_id(device_groups), 25 | cv.Required(CONF_GROUP_NAME): cv.string, 26 | cv.Optional(CONF_SWITCHES): cv.All(cv.ensure_list(cv.use_id(switch.Switch)), cv.Length(min=1)), 27 | cv.Optional(CONF_LIGHTS): cv.All(cv.ensure_list(cv.use_id(light.LightState)), cv.Length(min=1)), 28 | cv.Optional(CONF_SEND_MASK, default=0xFFFFFFFF): cv.hex_uint32_t, 29 | cv.Optional(CONF_RECEIVE_MASK, default=0xFFFFFFFF): cv.hex_uint32_t, 30 | }, cv.has_at_least_one_key(CONF_SWITCHES, CONF_LIGHTS) 31 | ).extend(cv.COMPONENT_SCHEMA) 32 | 33 | 34 | async def to_code(config): 35 | var = cg.new_Pvariable(config[CONF_ID]) 36 | await cg.register_component(var, config) 37 | cg.add(var.register_device_group_name(str(config[CONF_GROUP_NAME]))) 38 | cg.add(var.register_send_mask(config[CONF_SEND_MASK])) 39 | cg.add(var.register_receive_mask(config[CONF_RECEIVE_MASK])) 40 | 41 | if CONF_SWITCHES in config: 42 | switches = [] 43 | for switch in config[CONF_SWITCHES]: 44 | new_switch = await cg.get_variable(switch) 45 | switches.append(new_switch) 46 | cg.add(var.register_switches(switches)) 47 | 48 | if CONF_LIGHTS in config: 49 | lights = [] 50 | for light in config[CONF_LIGHTS]: 51 | new_light = await cg.get_variable(light) 52 | lights.append(new_light) 53 | cg.add(var.register_lights(lights)) 54 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Tasmota Device Groups for ESPHome 2 | 3 | This repository is for an external component for ESPHome to add (limited) Tasmota device groups compatibility. Since the majority of the code is taken directly from Tasmota, the license from Tasmota (GNU GPL v3.0) also follows. 4 | 5 | ## Configuration 6 | 7 | Configuration for ESPHome is opt-in instead of automatic. The reason for this is detached entities are not a special flag, and we don't want to attach to anything meant to be detached. 8 | 9 | ```yaml 10 | external_components: 11 | - source: github://cossid/tasmotadevicegroupsforesphome@main 12 | components: [ device_groups ] 13 | refresh: 10 min 14 | 15 | device_groups: 16 | - group_name: "testgroup1" # Tasmota device group name 17 | send_mask: 0xFFFFFFFF # Optional, defaults to 0xFFFFFFFF (send everything). Can be integer or hex 18 | receive_mask: 0xFFFFFFFF # Optional, defaults to 0xFFFFFFFF (receive everything). Can be integer or hex 19 | switches: 20 | - gpio_switch # ESPHome entity id 21 | - template_switch # ESPHome entity id 22 | lights: 23 | - light_rgbww1 # ESPHome entity id 24 | - light_rgbww2 # ESPHome entity id 25 | - group_name: "testgroup2" # Tasmota device group name 26 | switches: 27 | - gpio_switch2 # ESPHome entity id 28 | ``` 29 | 30 | ### Send/Receive masking 31 | 32 | Masks can be set as integer or hex values. Integer will work better when you want specific combinations, hex will work better when you want all categories set to be processed. 33 | 34 | ```yaml 35 | 0 / 0x0 = Deny all 36 | 1 = Power 37 | 2 = Light brightness 38 | 4 = Light fade/speed 39 | 8 = Light scheme 40 | 16 = Light color 41 | 32 = Dimmer settings (presets) 42 | 64 = Event 43 | 127 / 0x7F = Process all (shorthand, subject to expansion) 44 | 4294967295 / 0xFFFFFFFF = Process all (default) 45 | ``` 46 | 47 | If you want combinations, you just add them together, same as Tasmota. For example, Power + Light Color = 17 48 | 49 | ### Supported 50 | 51 | * Power States 52 | * Light States 53 | * On/Off 54 | * Brightness (color_interlock: true required for RGBW, or you will not get RGB brightness control) 55 | * Color channels 56 | * Send/Receive masking 57 | 58 | ### Not yet supported 59 | 60 | * Color Brightness on RGBW lights without color_interlock 61 | * Fade/Transitions/Speed 62 | * Schemes 63 | * Commands (ESPHome doesn't have a direct equivalent) 64 | * Similar can be accomplished with template devices, see [Command alternative](#command-alternative) below 65 | 66 | ### Command alternative 67 | 68 | Since commands are not implemented, the suggested workaround is to make internal matching entites backed by templates to what you want to change, add that internal entity to your group, and set the desired state on that entity. 69 | 70 | For example, if you have a switch with a button and would like to control a light entity, you could use: 71 | 72 | ```yaml 73 | output: 74 | - platform: template 75 | id: dummy_output 76 | type: float 77 | write_action: 78 | - lambda: return; 79 | 80 | light: 81 | - platform: rgbww 82 | id: internal_light 83 | color_interlock: true 84 | cold_white_color_temperature: 6500 K 85 | warm_white_color_temperature: 2700 K 86 | red: dummy_output 87 | green: dummy_output 88 | blue: dummy_output 89 | cold_white: dummy_output 90 | warm_white: dummy_output 91 | 92 | button: 93 | - platform: template 94 | name: "Set light to red" 95 | on_press: 96 | - light.control: 97 | id: internal_light 98 | state: on 99 | red: 100% 100 | green: 0% 101 | blue: 0% 102 | 103 | device_groups: 104 | - group_name: "light_group" # Tasmota device group name 105 | lights: 106 | - internal_light # ESPHome entity id 107 | ``` 108 | 109 | Button is just an example, but you could hook into any of the `on_` events for `binary_sensor`, `button`, `switch`, etc. 110 | 111 | ## Framework Support 112 | 113 | ### ESP-IDF Support 114 | 115 | This component now includes full ESP-IDF support through a custom WiFiUDP implementation (`device_groups_WiFiUdp.h` and `device_groups_WiFiUdp.cpp`). The implementation provides ESPHome-compatible UDP functionality using ESP-IDF's native socket API, allowing the component to work seamlessly with ESP-IDF without requiring Arduino framework dependencies. 116 | 117 | **Features of the ESP-IDF WiFiUDP implementation:** 118 | - Full ESPHome WiFiUDP API compatibility 119 | - Multicast support for device group communication 120 | - Native ESP-IDF socket operations 121 | - Automatic conditional compilation (uses local WiFiUdp.h when `USE_ESP_IDF` is defined) 122 | 123 | **ESP-IDF Compilation Fix:** 124 | - Fixed `ifaddrs.h` dependency issue by replacing `getifaddrs()` with ESP-IDF's `esp_netif_get_ip_info()` API 125 | - Added proper ESP-IDF includes (`esp_wifi.h`, `esp_netif.h`) with conditional compilation 126 | - Updated `localIP()` method to use ESP-IDF network interface API instead of POSIX ifaddrs 127 | 128 | **Troubleshooting ESP-IDF Issues:** 129 | If you experience intermittent behavior with ESP-IDF builds, the enhanced logging will help identify the root cause: 130 | - Check for "Network not ready" messages indicating WiFi connectivity issues 131 | - Look for "Socket error detected" messages indicating socket state problems 132 | - Monitor "Socket would block" messages during high network load 133 | - Verify buffer allocation success in memory-constrained environments 134 | 135 | ### Arduino Framework Support 136 | 137 | The component continues to support Arduino-based frameworks (ESP32 Arduino, ESP8266 Arduino) using the standard WiFiUDP libraries. 138 | 139 | ### Known Issues 140 | 141 | * Multiple relays in the same group cannot currently be individually addressed, so an action against the group will apply to all entities in the group on ESPHome. [Issue #2](https://github.com/Cossid/TasmotaDeviceGroupsForESPHome/issues/2) will track the potential resolution for this. As a workaround, you can enable SetOption88 on Tasmota and assign individual groups. While Tasmota by default is limited to 4 groups, ESPHome has no limit. 142 | * ESPHome handles brightness between RGB and White channels differently, and both modes cannot be supported at the same time. As a result, RGB brightness cannot currently be supported for RGBW bulbs without color_interlock. 143 | 144 | ### Misc 145 | 146 | You may see a notice about blocking for too long. This should not really be a problem, it is a generic ESPHome notice about performance. Delays are mostly caused by waiting on network traffic. The notice will look like this: 147 | 148 | ```text 149 | [W][component:204]: Component device_groups took a long time for an operation (0.15 s). 150 | [W][component:205]: Components should block for at most 20-30ms. 151 | ``` 152 | -------------------------------------------------------------------------------- /components/device_groups/device_groups_WiFiUdp.h: -------------------------------------------------------------------------------- 1 | #if defined(USE_ESP_IDF) 2 | 3 | #pragma once 4 | 5 | #include "esphome/components/network/ip_address.h" 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | class IPAddress { 16 | public: 17 | uint8_t bytes[4]; 18 | IPAddress() : bytes{0,0,0,0} {} 19 | IPAddress(uint8_t a, uint8_t b, uint8_t c, uint8_t d) : bytes{a,b,c,d} {} 20 | uint8_t& operator[](int i) { return bytes[i]; } 21 | const uint8_t& operator[](int i) const { return bytes[i]; } 22 | bool operator==(const IPAddress& other) const { 23 | return bytes[0] == other.bytes[0] && bytes[1] == other.bytes[1] && 24 | bytes[2] == other.bytes[2] && bytes[3] == other.bytes[3]; 25 | } 26 | bool operator!=(const IPAddress& other) const { return !(*this == other); } 27 | }; 28 | 29 | #ifdef __cplusplus 30 | extern "C" { 31 | #endif 32 | 33 | /** 34 | * @brief device_groups_WiFiUDP class that provides ESPHome-compatible UDP functionality for ESP-IDF 35 | * 36 | * This wrapper implements the ESPHome WiFiUDP interface using ESP-IDF's native 37 | * socket API, allowing components that depend on ESPHome's WiFiUdp.h to work 38 | * with ESP-IDF without modification. 39 | */ 40 | class device_groups_WiFiUDP { 41 | private: 42 | int sock_fd; 43 | struct sockaddr_in remote_addr; 44 | struct sockaddr_in sender_addr; // Store sender info for received packets 45 | bool is_connected; 46 | char* send_buffer; // Separate buffer for sending packets 47 | char* recv_buffer; // Separate buffer for receiving packets 48 | size_t send_buffer_size; 49 | size_t recv_buffer_size; 50 | size_t send_data_length; 51 | size_t recv_data_length; 52 | size_t recv_read_position; 53 | 54 | // Packet deduplication to prevent storms 55 | uint32_t last_packet_hash; 56 | uint32_t last_packet_time; 57 | static const uint32_t DEDUP_WINDOW_MS = 100; // 100ms window for deduplication 58 | 59 | public: 60 | /** 61 | * @brief Default constructor 62 | */ 63 | device_groups_WiFiUDP(); 64 | 65 | /** 66 | * @brief Copy constructor (deleted to prevent copying) 67 | */ 68 | device_groups_WiFiUDP(const device_groups_WiFiUDP&) = delete; 69 | 70 | /** 71 | * @brief Assignment operator (deleted to prevent copying) 72 | */ 73 | device_groups_WiFiUDP& operator=(const device_groups_WiFiUDP&) = delete; 74 | 75 | /** 76 | * @brief Destructor 77 | */ 78 | ~device_groups_WiFiUDP(); 79 | 80 | /** 81 | * @brief Check if network is ready for UDP operations 82 | * @return true if network is ready, false otherwise 83 | */ 84 | bool isNetworkReady(); 85 | 86 | /** 87 | * @brief Validate socket state and reinitialize if needed 88 | * @return true if socket is valid, false otherwise 89 | */ 90 | bool validateSocket(); 91 | 92 | /** 93 | * @brief Begin UDP communication on specified port 94 | * @param port The port number to bind to 95 | * @return true if successful, false otherwise 96 | */ 97 | bool begin(uint16_t port); 98 | 99 | /** 100 | * @brief Begin UDP communication with multicast support 101 | * @param port The port number to bind to 102 | * @param multicast_ip The multicast IP address 103 | * @param interface_ip The interface IP address 104 | * @return true if successful, false otherwise 105 | */ 106 | bool beginMulticast(uint16_t port, const char* multicast_ip, const char* interface_ip); 107 | 108 | /** 109 | * @brief Begin UDP communication with multicast support (IPAddress overload) 110 | * @param multicast_ip The multicast IP address as IPAddress 111 | * @param port The port number to bind to 112 | * @return true if successful, false otherwise 113 | */ 114 | bool beginMulticast(const IPAddress& multicast_ip, uint16_t port); 115 | 116 | /** 117 | * @brief Stop UDP communication and close socket 118 | */ 119 | void stop(); 120 | 121 | /** 122 | * @brief Begin packet transmission to specified IP and port 123 | * @param ip The destination IP address 124 | * @param port The destination port 125 | * @return true if successful, false otherwise 126 | */ 127 | bool beginPacket(const char* ip, uint16_t port); 128 | 129 | /** 130 | * @brief Begin packet transmission to specified IP and port 131 | * @param ip The destination IP address as uint32_t 132 | * @param port The destination port 133 | * @return true if successful, false otherwise 134 | */ 135 | bool beginPacket(uint32_t ip, uint16_t port); 136 | 137 | /** 138 | * @brief Begin packet transmission to specified IP and port 139 | * @param ip The destination IP address as IPAddress 140 | * @param port The destination port 141 | * @return true if successful, false otherwise 142 | */ 143 | bool beginPacket(const IPAddress& ip, uint16_t port); 144 | 145 | /** 146 | * @brief End packet transmission and send data 147 | * @return true if successful, false otherwise 148 | */ 149 | bool endPacket(); 150 | 151 | /** 152 | * @brief Write a single byte to the packet 153 | * @param byte The byte to write 154 | * @return Number of bytes written (1 if successful, 0 otherwise) 155 | */ 156 | size_t write(uint8_t byte); 157 | 158 | /** 159 | * @brief Write data to the packet 160 | * @param buffer Pointer to the data buffer 161 | * @param size Size of the data to write 162 | * @return Number of bytes written 163 | */ 164 | size_t write(const uint8_t* buffer, size_t size); 165 | 166 | /** 167 | * @brief Write a string to the packet 168 | * @param str The string to write 169 | * @return Number of bytes written 170 | */ 171 | size_t write(const char* str); 172 | 173 | /** 174 | * @brief Parse incoming packet 175 | * @return Size of the received packet, 0 if no packet available 176 | */ 177 | int parsePacket(); 178 | 179 | /** 180 | * @brief Get the size of the received packet 181 | * @return Size of the packet in bytes 182 | */ 183 | int available(); 184 | 185 | /** 186 | * @brief Read a single byte from the received packet 187 | * @return The byte read, or -1 if no data available 188 | */ 189 | int read(); 190 | 191 | /** 192 | * @brief Read data from the received packet 193 | * @param buffer Pointer to the buffer to store the data 194 | * @param size Maximum number of bytes to read 195 | * @return Number of bytes read 196 | */ 197 | int read(uint8_t* buffer, size_t size); 198 | 199 | /** 200 | * @brief Read data from the received packet 201 | * @param buffer Pointer to the buffer to store the data 202 | * @param size Maximum number of bytes to read 203 | * @return Number of bytes read 204 | */ 205 | int read(char* buffer, size_t size); 206 | 207 | /** 208 | * @brief Peek at the next byte without removing it from the buffer 209 | * @return The next byte, or -1 if no data available 210 | */ 211 | int peek(); 212 | 213 | /** 214 | * @brief Flush the receive buffer 215 | */ 216 | void flush(); 217 | 218 | /** 219 | * @brief Get the remote IP address of the received packet 220 | * @return IP address as IPAddress object 221 | */ 222 | IPAddress remoteIP(); 223 | 224 | /** 225 | * @brief Get the remote port of the received packet 226 | * @return Port number 227 | */ 228 | uint16_t remotePort(); 229 | 230 | /** 231 | * @brief Check if UDP connection is active 232 | * @return true if connected, false otherwise 233 | */ 234 | bool connected(); 235 | 236 | /** 237 | * @brief Set socket timeout 238 | * @param timeout_ms Timeout in milliseconds 239 | */ 240 | void setTimeout(int timeout_ms); 241 | 242 | /** 243 | * @brief Get the local port number 244 | * @return Local port number, 0 if not bound 245 | */ 246 | uint16_t localPort(); 247 | 248 | /** 249 | * @brief Get the local IP address 250 | * @return Local IP address as string 251 | */ 252 | const char* localIP(); 253 | 254 | /** 255 | * @brief Initialize socket with proper options 256 | * @return true if successful, false otherwise 257 | */ 258 | bool initSocket(); 259 | 260 | /** 261 | * @brief Set socket options for non-blocking operation 262 | * @return true if successful, false otherwise 263 | */ 264 | bool setSocketOptions(); 265 | 266 | /** 267 | * @brief Convert IP address to string 268 | * @param ip IP address as uint32_t 269 | * @return IP address as string 270 | */ 271 | static const char* ipToString(uint32_t ip); 272 | }; 273 | 274 | #ifdef __cplusplus 275 | } 276 | #endif 277 | 278 | #endif // USE_ESP_IDF 279 | -------------------------------------------------------------------------------- /components/device_groups/device_groups.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "esphome/core/application.h" 4 | #include "esphome/core/component.h" 5 | #include 6 | #include "esphome/components/network/ip_address.h" 7 | 8 | #if defined(USE_ESP32) 9 | #include 10 | #if defined(USE_ESP_IDF) 11 | #include "device_groups_WiFiUdp.h" // Use local device_groups_WiFiUdp.h for ESP-IDF 12 | #include "esp_idf_compatibility.h" 13 | #else 14 | #include // Use system WiFiUdp.h for Arduino framework 15 | #endif 16 | #elif USE_ESP8266 17 | #include 18 | #include 19 | #else 20 | #include 21 | #endif 22 | 23 | #ifdef USE_SWITCH 24 | #include "esphome/components/switch/switch.h" 25 | #endif 26 | #ifdef USE_LIGHT 27 | #include "esphome/components/light/light_state.h" 28 | #include "esphome/components/light/color_mode.h" 29 | #endif 30 | 31 | namespace esphome { 32 | namespace device_groups { 33 | 34 | // #define DEVICE_GROUPS_DEBUG 35 | #define DGR_MULTICAST_REPEAT_COUNT 1 // Number of times to re-send each multicast 36 | #define DGR_ACK_WAIT_TIME 150 // Initial ms to wait for ack's 37 | #define DGR_MEMBER_TIMEOUT 45000 // ms to wait for ack's before removing a member 38 | #define DGR_ANNOUNCEMENT_INTERVAL 60000 // ms between announcements 39 | #define DEVICE_GROUP_MESSAGE "TASMOTA_DGR" 40 | #define DEVICE_GROUPS_ADDRESS 239, 255, 250, 250 // Device groups multicast address 41 | #define DEVICE_GROUPS_PORT 4447 // Device groups multicast port 42 | #define USE_DEVICE_GROUPS_SEND // Add support for the DevGroupSend command (+0k6 code) 43 | #define D_CMND_DEVGROUPSTATUS "DevGroupStatus" 44 | 45 | const uint8_t MAX_DEV_GROUP_NAMES = 4; // Max number of Device Group names 46 | const uint16_t TOPSZ = 151; // Max number of characters in topic string 47 | const char kDeviceGroupMessage[] = DEVICE_GROUP_MESSAGE; 48 | 49 | typedef uint32_t power_t; // Power (Relay) type 50 | const uint32_t POWER_MASK = 0xFFFFFFFFUL; // Power (Relay) full mask 51 | const uint32_t POWER_SIZE = 32; // Power (relay) bit count 52 | const uint8_t SET_DEV_GROUP_NAME1 = 72; 53 | 54 | enum DevGroupState { DGR_STATE_UNINTIALIZED, DGR_STATE_INITIALIZING, DGR_STATE_INITIALIZED }; 55 | 56 | enum DevGroupMessageType { 57 | DGR_MSGTYP_FULL_STATUS, 58 | DGR_MSGTYP_PARTIAL_UPDATE, 59 | DGR_MSGTYP_UPDATE, 60 | DGR_MSGTYP_UPDATE_MORE_TO_COME, 61 | DGR_MSGTYP_UPDATE_DIRECT, 62 | DGR_MSGTYPE_UPDATE_COMMAND, 63 | DGR_MSGTYPFLAG_WITH_LOCAL = 128 64 | }; 65 | 66 | enum DevGroupMessageFlag { 67 | DGR_FLAG_RESET = 1, 68 | DGR_FLAG_STATUS_REQUEST = 2, 69 | DGR_FLAG_FULL_STATUS = 4, 70 | DGR_FLAG_ACK = 8, 71 | DGR_FLAG_MORE_TO_COME = 16, 72 | DGR_FLAG_DIRECT = 32, 73 | DGR_FLAG_ANNOUNCEMENT = 64, 74 | DGR_FLAG_LOCAL = 128 75 | }; 76 | 77 | enum DevGroupItem { 78 | DGR_ITEM_EOL, 79 | DGR_ITEM_STATUS, 80 | DGR_ITEM_FLAGS, 81 | DGR_ITEM_LIGHT_FADE, 82 | DGR_ITEM_LIGHT_SPEED, 83 | DGR_ITEM_LIGHT_BRI, 84 | DGR_ITEM_LIGHT_SCHEME, 85 | DGR_ITEM_LIGHT_FIXED_COLOR, 86 | DGR_ITEM_BRI_PRESET_LOW, 87 | DGR_ITEM_BRI_PRESET_HIGH, 88 | DGR_ITEM_BRI_POWER_ON, 89 | // Add new 8-bit items before this line 90 | DGR_ITEM_LAST_8BIT, 91 | DGR_ITEM_MAX_8BIT = 63, 92 | 93 | // 16-bit items (aggiungi qui eventuali altri) 94 | DGR_ITEM_ANALOG1, 95 | 96 | DGR_ITEM_LAST_16BIT, 97 | DGR_ITEM_MAX_16BIT = 127, 98 | DGR_ITEM_POWER, 99 | DGR_ITEM_NO_STATUS_SHARE, 100 | // Add new 32-bit items before this line 101 | DGR_ITEM_LAST_32BIT, 102 | DGR_ITEM_MAX_32BIT = 191, 103 | DGR_ITEM_EVENT, 104 | DGR_ITEM_COMMAND, 105 | // Add new string items before this line 106 | DGR_ITEM_LAST_STRING, 107 | DGR_ITEM_MAX_STRING = 223, 108 | DGR_ITEM_LIGHT_CHANNELS 109 | }; 110 | 111 | enum DevGroupItemFlag { DGR_ITEM_FLAG_NO_SHARE = 1 }; 112 | 113 | enum DevGroupShareItem { 114 | DGR_SHARE_POWER = 1, 115 | DGR_SHARE_LIGHT_BRI = 2, 116 | DGR_SHARE_LIGHT_FADE = 4, 117 | DGR_SHARE_LIGHT_SCHEME = 8, 118 | DGR_SHARE_LIGHT_COLOR = 16, 119 | DGR_SHARE_DIMMER_SETTINGS = 32, 120 | DGR_SHARE_EVENT = 64 121 | }; 122 | 123 | enum XsnsFunctions { FUNC_DEVICE_GROUP_ITEM = 41 }; 124 | 125 | enum ExecuteCommandPowerOptions { 126 | POWER_OFF, 127 | POWER_ON, 128 | POWER_TOGGLE, 129 | POWER_BLINK, 130 | POWER_BLINK_STOP, 131 | POWER_OFF_NO_STATE = 8, 132 | POWER_ON_NO_STATE, 133 | POWER_TOGGLE_NO_STATE, 134 | POWER_SHOW_STATE = 16 135 | }; 136 | 137 | enum CommandSource { 138 | SRC_IGNORE, 139 | SRC_MQTT, 140 | SRC_RESTART, 141 | SRC_BUTTON, 142 | SRC_SWITCH, 143 | SRC_BACKLOG, 144 | SRC_SERIAL, 145 | SRC_WEBGUI, 146 | SRC_WEBCOMMAND, 147 | SRC_WEBCONSOLE, 148 | SRC_PULSETIMER, 149 | SRC_TIMER, 150 | SRC_RULE, 151 | SRC_MAXPOWER, 152 | SRC_MAXENERGY, 153 | SRC_OVERTEMP, 154 | SRC_LIGHT, 155 | SRC_KNX, 156 | SRC_DISPLAY, 157 | SRC_WEMO, 158 | SRC_HUE, 159 | SRC_RETRY, 160 | SRC_REMOTE, 161 | SRC_SHUTTER, 162 | SRC_THERMOSTAT, 163 | SRC_CHAT, 164 | SRC_TCL, 165 | SRC_BERRY, 166 | SRC_FILE, 167 | SRC_SSERIAL, 168 | SRC_USBCONSOLE, 169 | SRC_SO47, 170 | SRC_MAX 171 | }; 172 | 173 | enum LoggingLevels { 174 | LOG_LEVEL_NONE, 175 | LOG_LEVEL_ERROR, 176 | LOG_LEVEL_INFO, 177 | LOG_LEVEL_DEBUG, 178 | LOG_LEVEL_DEBUG_MORE, 179 | LOG_LEVEL_ALL 180 | }; 181 | 182 | enum ProcessGroupMessageResult { 183 | PROCESS_GROUP_MESSAGE_ERROR, 184 | PROCESS_GROUP_MESSAGE_SUCCESS, 185 | PROCESS_GROUP_MESSAGE_UNMATCHED 186 | }; 187 | 188 | struct device_group_member { 189 | struct device_group_member *flink; 190 | IPAddress ip_address; 191 | uint16_t received_sequence; 192 | uint16_t acked_sequence; 193 | uint32_t unicast_count; 194 | }; 195 | 196 | struct device_group { 197 | uint32_t next_announcement_time; 198 | uint32_t next_ack_check_time; 199 | uint32_t member_timeout_time; 200 | uint32_t no_status_share; 201 | uint16_t outgoing_sequence; 202 | uint16_t last_full_status_sequence; 203 | uint16_t message_length; 204 | uint16_t ack_check_interval; 205 | uint8_t message_header_length; 206 | uint8_t initial_status_requests_remaining; 207 | uint8_t multicasts_remaining; 208 | char group_name[TOPSZ]; 209 | uint8_t message[128]; 210 | struct device_group_member *device_group_members; 211 | #ifdef USE_DEVICE_GROUPS_SEND 212 | uint8_t values_8bit[DGR_ITEM_LAST_8BIT]; 213 | uint16_t values_16bit[DGR_ITEM_LAST_16BIT - DGR_ITEM_MAX_8BIT - 1]; 214 | uint32_t values_32bit[DGR_ITEM_LAST_32BIT - DGR_ITEM_MAX_16BIT - 1]; 215 | #endif // USE_DEVICE_GROUPS_SEND 216 | }; 217 | 218 | struct TasmotaGlobal_t { 219 | bool skip_light_fade = false; // Temporarily skip light fading 220 | uint8_t devices_present = 20; // Max number of devices supported 221 | power_t power; // Current copy of Settings->power 222 | uint8_t restart_flag = 0; // Tasmota restart flag 223 | int32_t fade = -1; 224 | int32_t speed = -1; 225 | int32_t scheme = -1; 226 | bool processing_light_transition = false; 227 | }; 228 | 229 | struct XDRVMAILBOX { 230 | bool grpflg; 231 | bool usridx; 232 | uint16_t command_code; 233 | uint32_t index; 234 | uint32_t data_len; 235 | int32_t payload; 236 | char *topic; 237 | char *data; 238 | char *command; 239 | }; 240 | 241 | typedef union { 242 | uint32_t data; // Allow bit manipulation using SetOption 243 | struct { // SetOption82 .. SetOption113 244 | uint32_t device_groups_enabled : 1; // bit 3 (v8.1.0.9) - SetOption85 - (DevGroups) Enable Device Groups (1) 245 | uint32_t multiple_device_groups : 1; // bit 6 (v8.1.0.9) - SetOption88 - (DevGroups) Enable relays in separate 246 | // device groups/PWM Dimmer Buttons control remote devices (1) 247 | }; 248 | } SOBitfield4; 249 | 250 | typedef struct { 251 | SOBitfield4 flag4; // EF8 252 | uint8_t device_group_tie[4]; // FB0 253 | uint32_t device_group_share_in; // FCC Bitmask of device group items imported 254 | uint32_t device_group_share_out; // FD0 Bitmask of device group items exported 255 | } TSettings; 256 | 257 | struct multicast_packet { 258 | uint32_t id; 259 | int length; 260 | uint8_t payload[512]; 261 | IPAddress remoteIP; 262 | }; 263 | 264 | #if defined(ESP8266) 265 | static WiFiUDP device_groups_udp; 266 | static std::vector received_packets{}; 267 | static std::vector registered_group_names{}; 268 | static uint32_t packetId = 0; 269 | #endif 270 | 271 | #if defined(USE_LIGHT) 272 | class device_groups : public Component, public light::LightRemoteValuesListener { 273 | #else 274 | class device_groups : public Component { 275 | #endif 276 | public: 277 | void register_device_group_name(std::string group_name) { this->device_group_name_ = std::move(group_name); } 278 | #ifdef USE_SWITCH 279 | void register_switches(const std::vector &switches) { this->switches_ = switches; } 280 | #endif 281 | #ifdef USE_LIGHT 282 | void register_lights(const std::vector &lights) { this->lights_ = lights; } 283 | // LightRemoteValuesListener interface 284 | void on_light_remote_values_update() override; 285 | #endif 286 | void register_send_mask(uint32_t send_mask) { this->send_mask_ = send_mask; } 287 | void register_receive_mask(uint32_t receive_mask) { this->receive_mask_ = receive_mask; } 288 | void setup() override; 289 | void dump_config() override; 290 | float get_setup_priority() const override { return setup_priority::AFTER_WIFI; } 291 | 292 | /// Send new values if they were updated. 293 | void loop() override; 294 | 295 | protected: 296 | void SendReceiveDeviceGroupMessage(struct device_group *device_group, struct device_group_member *device_group_member, 297 | uint8_t *message, int message_length, bool received); 298 | bool _SendDeviceGroupMessage(int32_t device, DevGroupMessageType message_type, ...); 299 | #define SendDeviceGroupMessage(DEVICE_INDEX, REQUEST_TYPE, ...) \ 300 | _SendDeviceGroupMessage(DEVICE_INDEX, REQUEST_TYPE, ##__VA_ARGS__, 0) 301 | ProcessGroupMessageResult ProcessDeviceGroupMessage(multicast_packet); 302 | bool XdrvCall(uint8_t Function); 303 | void ExecuteCommandPower(uint32_t device, uint32_t state, uint32_t source); 304 | void ExecuteCommand(const char *cmnd, uint32_t source); 305 | void InitTasmotaCompatibility(); 306 | void DeviceGroupsInit(); 307 | bool DeviceGroupsStart(); 308 | void DeviceGroupsLoop(); 309 | void DeviceGroupsStop(); 310 | void DeviceGroupStatus(uint8_t device_group_index); 311 | 312 | std::string device_group_name_; 313 | bool update_{true}; 314 | uint32_t send_mask_{0xffffffff}; 315 | uint32_t receive_mask_{0xffffffff}; 316 | 317 | #ifdef USE_SWITCH 318 | std::vector switches_{}; 319 | #endif 320 | #ifdef USE_LIGHT 321 | std::vector lights_{}; 322 | #endif 323 | 324 | 325 | #if defined(USE_ESP_IDF) 326 | device_groups_WiFiUDP device_groups_udp; 327 | #elif !defined(ESP8266) 328 | WiFiUDP device_groups_udp; 329 | #endif 330 | 331 | struct device_group *device_groups_; 332 | uint32_t next_check_time; 333 | bool device_groups_initialized = false; 334 | bool device_groups_up = false; 335 | bool building_status_message = false; 336 | bool ignore_dgr_sends = false; 337 | TSettings *Settings = nullptr; 338 | TasmotaGlobal_t TasmotaGlobal; 339 | XDRVMAILBOX XdrvMailbox; 340 | DevGroupState dgr_state = DGR_STATE_UNINTIALIZED; 341 | bool setup_complete = false; 342 | 343 | uint8_t device_group_count = 0; 344 | bool first_device_group_is_local = true; 345 | 346 | #ifdef USE_LIGHT 347 | void get_light_values(light::LightState *obj, bool &power_state, float &brightness, float &color_brightness, float &red, float &green, float &blue, float &cold_white, float &warm_white, esphome::light::ColorMode &color_mode); 348 | void set_light_intial_values(light::LightState *obj); 349 | bool previous_power_state = false; 350 | float previous_brightness = 0.0f; 351 | float previous_color_brightness = 0.0f; 352 | float previous_red = 0.0f; 353 | float previous_green = 0.0f; 354 | float previous_blue = 0.0f; 355 | float previous_warm_white = 0.0f; 356 | float previous_cold_white = 0.0f; 357 | float previous_color_temperature = 0.0f; 358 | esphome::light::ColorMode previous_color_mode = esphome::light::ColorMode::UNKNOWN; 359 | #endif 360 | }; 361 | 362 | } // namespace device_groups 363 | } // namespace esphome 364 | -------------------------------------------------------------------------------- /components/device_groups/device_groups_WiFiUdp.cpp: -------------------------------------------------------------------------------- 1 | #if defined(USE_ESP_IDF) 2 | 3 | #include "device_groups_WiFiUdp.h" 4 | #include 5 | #include 6 | 7 | #include "esp_wifi.h" 8 | #include "esp_netif.h" 9 | #include "esp_log.h" 10 | #include "esp_timer.h" 11 | #include "esphome/core/log.h" 12 | 13 | // Default buffer size for UDP packets 14 | #define DEFAULT_BUFFER_SIZE 1024 15 | #define MAX_RETRIES 3 16 | #define RETRY_DELAY_MS 10 17 | 18 | static const char *const TAG = "dgr"; 19 | 20 | device_groups_WiFiUDP::device_groups_WiFiUDP() : sock_fd(-1), is_connected(false), 21 | send_buffer(nullptr), recv_buffer(nullptr), 22 | send_buffer_size(0), recv_buffer_size(0), 23 | send_data_length(0), recv_data_length(0), recv_read_position(0), 24 | last_packet_hash(0), last_packet_time(0) { 25 | memset(&remote_addr, 0, sizeof(remote_addr)); 26 | memset(&sender_addr, 0, sizeof(sender_addr)); 27 | remote_addr.sin_family = AF_INET; 28 | sender_addr.sin_family = AF_INET; 29 | ESP_LOGCONFIG(TAG, "ESP-IDF WiFiUDP implementation initialized"); 30 | } 31 | 32 | device_groups_WiFiUDP::~device_groups_WiFiUDP() { 33 | stop(); 34 | if (send_buffer) { 35 | free(send_buffer); 36 | send_buffer = nullptr; 37 | } 38 | if (recv_buffer) { 39 | free(recv_buffer); 40 | recv_buffer = nullptr; 41 | } 42 | ESP_LOGCONFIG(TAG, "ESP-IDF WiFiUDP implementation destroyed"); 43 | } 44 | 45 | bool device_groups_WiFiUDP::isNetworkReady() { 46 | esp_netif_t* netif = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF"); 47 | if (netif == nullptr) { 48 | ESP_LOGW(TAG, "No WiFi STA interface found"); 49 | return false; 50 | } 51 | 52 | esp_netif_ip_info_t ip_info; 53 | if (esp_netif_get_ip_info(netif, &ip_info) != ESP_OK) { 54 | ESP_LOGW(TAG, "Failed to get IP info"); 55 | return false; 56 | } 57 | 58 | if (ip_info.ip.addr == 0) { 59 | ESP_LOGW(TAG, "No valid IP address"); 60 | return false; 61 | } 62 | 63 | return true; 64 | } 65 | 66 | bool device_groups_WiFiUDP::initSocket() { 67 | if (sock_fd >= 0) { 68 | close(sock_fd); 69 | sock_fd = -1; // Ensure it's reset 70 | } 71 | 72 | sock_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); 73 | if (sock_fd < 0) { 74 | ESP_LOGE(TAG, "Failed to create UDP socket: %s", strerror(errno)); 75 | return false; 76 | } 77 | 78 | return setSocketOptions(); 79 | } 80 | 81 | bool device_groups_WiFiUDP::setSocketOptions() { 82 | // Set socket to non-blocking mode 83 | int flags = fcntl(sock_fd, F_GETFL, 0); 84 | if (flags < 0) { 85 | ESP_LOGE(TAG, "Failed to get socket flags: %s", strerror(errno)); 86 | return false; 87 | } 88 | 89 | if (fcntl(sock_fd, F_SETFL, flags | O_NONBLOCK) < 0) { 90 | ESP_LOGE(TAG, "Failed to set socket non-blocking: %s", strerror(errno)); 91 | return false; 92 | } 93 | 94 | // Allow address reuse 95 | int opt = 1; 96 | if (setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0) { 97 | ESP_LOGE(TAG, "Failed to set SO_REUSEADDR: %s", strerror(errno)); 98 | return false; 99 | } 100 | 101 | // Set receive timeout 102 | struct timeval tv; 103 | tv.tv_sec = 1; // 1 second timeout 104 | tv.tv_usec = 0; 105 | if (setsockopt(sock_fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0) { 106 | ESP_LOGW(TAG, "Failed to set receive timeout: %s", strerror(errno)); 107 | } 108 | 109 | return true; 110 | } 111 | 112 | bool device_groups_WiFiUDP::validateSocket() { 113 | if (sock_fd < 0) { 114 | return false; 115 | } 116 | 117 | // Only check socket validity if we haven't checked recently 118 | // This reduces overhead and prevents excessive socket recreation 119 | static uint32_t last_validation_time = 0; 120 | uint32_t current_time = esp_timer_get_time() / 1000; // Convert to milliseconds 121 | 122 | // Only validate every 5 seconds to reduce overhead 123 | if (current_time - last_validation_time < 5000) { 124 | return true; 125 | } 126 | 127 | last_validation_time = current_time; 128 | 129 | // Check if socket is still valid 130 | int error = 0; 131 | socklen_t len = sizeof(error); 132 | if (getsockopt(sock_fd, SOL_SOCKET, SO_ERROR, &error, &len) < 0 || error != 0) { 133 | ESP_LOGW(TAG, "Socket error detected (error: %d), reinitializing", error); 134 | return false; 135 | } 136 | 137 | return true; 138 | } 139 | 140 | bool device_groups_WiFiUDP::begin(uint16_t port) { 141 | ESP_LOGCONFIG(TAG, "=== WiFiUDP begin called for port %d ===", port); 142 | 143 | if (!isNetworkReady()) { 144 | ESP_LOGCONFIG(TAG, "Network not ready for UDP begin on port %d", port); 145 | return false; 146 | } 147 | 148 | if (!initSocket()) { 149 | return false; 150 | } 151 | 152 | struct sockaddr_in local_addr; 153 | memset(&local_addr, 0, sizeof(local_addr)); 154 | local_addr.sin_family = AF_INET; 155 | local_addr.sin_addr.s_addr = INADDR_ANY; 156 | local_addr.sin_port = htons(port); 157 | 158 | if (bind(sock_fd, (struct sockaddr*)&local_addr, sizeof(local_addr)) < 0) { 159 | ESP_LOGCONFIG(TAG, "Failed to bind UDP socket to port %d: %s", port, strerror(errno)); 160 | close(sock_fd); 161 | sock_fd = -1; 162 | return false; 163 | } 164 | 165 | is_connected = true; 166 | ESP_LOGVV(TAG, "UDP socket bound to port %d", port); 167 | ESP_LOGCONFIG(TAG, "=== WiFiUDP begin successful for port %d ===", port); 168 | return true; 169 | } 170 | 171 | bool device_groups_WiFiUDP::beginMulticast(uint16_t port, const char* multicast_ip, const char* interface_ip) { 172 | if (!isNetworkReady()) { 173 | ESP_LOGE(TAG, "Network not ready for multicast begin"); 174 | return false; 175 | } 176 | 177 | if (!initSocket()) { 178 | return false; 179 | } 180 | 181 | struct sockaddr_in local_addr; 182 | memset(&local_addr, 0, sizeof(local_addr)); 183 | local_addr.sin_family = AF_INET; 184 | local_addr.sin_addr.s_addr = INADDR_ANY; 185 | local_addr.sin_port = htons(port); 186 | 187 | if (bind(sock_fd, (struct sockaddr*)&local_addr, sizeof(local_addr)) < 0) { 188 | ESP_LOGE(TAG, "Failed to bind UDP socket to port %d: %s", port, strerror(errno)); 189 | close(sock_fd); 190 | sock_fd = -1; 191 | return false; 192 | } 193 | 194 | // Join multicast group 195 | struct ip_mreq mreq; 196 | mreq.imr_multiaddr.s_addr = inet_addr(multicast_ip); 197 | mreq.imr_interface.s_addr = inet_addr(interface_ip); 198 | 199 | if (setsockopt(sock_fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) { 200 | ESP_LOGE(TAG, "Failed to join multicast group: %s", strerror(errno)); 201 | close(sock_fd); 202 | sock_fd = -1; 203 | return false; 204 | } 205 | 206 | is_connected = true; 207 | ESP_LOGVV(TAG, "Joined multicast group %s on port %d", multicast_ip, port); 208 | return true; 209 | } 210 | 211 | bool device_groups_WiFiUDP::beginMulticast(const IPAddress& multicast_ip, uint16_t port) { 212 | if (!isNetworkReady()) { 213 | ESP_LOGE(TAG, "Network not ready for multicast begin"); 214 | return false; 215 | } 216 | 217 | if (!initSocket()) { 218 | return false; 219 | } 220 | 221 | struct sockaddr_in local_addr; 222 | memset(&local_addr, 0, sizeof(local_addr)); 223 | local_addr.sin_family = AF_INET; 224 | local_addr.sin_addr.s_addr = INADDR_ANY; 225 | local_addr.sin_port = htons(port); 226 | 227 | if (bind(sock_fd, (struct sockaddr*)&local_addr, sizeof(local_addr)) < 0) { 228 | ESP_LOGE(TAG, "Failed to bind UDP socket to port %d: %s", port, strerror(errno)); 229 | close(sock_fd); 230 | sock_fd = -1; 231 | return false; 232 | } 233 | 234 | // Join multicast group 235 | struct ip_mreq mreq; 236 | mreq.imr_multiaddr.s_addr = htonl((multicast_ip[0] << 24) | (multicast_ip[1] << 16) | (multicast_ip[2] << 8) | multicast_ip[3]); 237 | mreq.imr_interface.s_addr = INADDR_ANY; // Use default interface 238 | 239 | if (setsockopt(sock_fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) { 240 | ESP_LOGE(TAG, "Failed to join multicast group: %s", strerror(errno)); 241 | close(sock_fd); 242 | sock_fd = -1; 243 | return false; 244 | } 245 | 246 | is_connected = true; 247 | ESP_LOGVV(TAG, "Joined multicast group on port %d", port); 248 | return true; 249 | } 250 | 251 | void device_groups_WiFiUDP::stop() { 252 | if (sock_fd >= 0) { 253 | close(sock_fd); 254 | sock_fd = -1; 255 | } 256 | is_connected = false; 257 | 258 | if (send_buffer) { 259 | free(send_buffer); 260 | send_buffer = nullptr; 261 | send_buffer_size = 0; 262 | } 263 | if (recv_buffer) { 264 | free(recv_buffer); 265 | recv_buffer = nullptr; 266 | recv_buffer_size = 0; 267 | } 268 | send_data_length = 0; 269 | recv_data_length = 0; 270 | recv_read_position = 0; 271 | ESP_LOGVV(TAG, "UDP socket stopped"); 272 | } 273 | 274 | bool device_groups_WiFiUDP::beginPacket(const char* ip, uint16_t port) { 275 | if (!validateSocket()) { 276 | if (!initSocket()) { 277 | ESP_LOGE(TAG, "Failed to initialize socket for packet to %s:%d", ip, port); 278 | return false; 279 | } 280 | } 281 | 282 | remote_addr.sin_addr.s_addr = inet_addr(ip); 283 | remote_addr.sin_port = htons(port); 284 | 285 | return true; 286 | } 287 | 288 | bool device_groups_WiFiUDP::beginPacket(uint32_t ip, uint16_t port) { 289 | if (!validateSocket()) { 290 | if (!initSocket()) { 291 | ESP_LOGE(TAG, "Failed to initialize socket for packet to %u:%d", ip, port); 292 | return false; 293 | } 294 | } 295 | 296 | remote_addr.sin_addr.s_addr = htonl(ip); 297 | remote_addr.sin_port = htons(port); 298 | 299 | return true; 300 | } 301 | 302 | bool device_groups_WiFiUDP::beginPacket(const IPAddress& ip, uint16_t port) { 303 | // Don't recreate socket unnecessarily - just validate existing one 304 | if (sock_fd < 0) { 305 | ESP_LOGE(TAG, "No socket available for packet to %u.%u.%u.%u:%d", 306 | ip[0], ip[1], ip[2], ip[3], port); 307 | return false; 308 | } 309 | 310 | remote_addr.sin_addr.s_addr = htonl((ip[0] << 24) | (ip[1] << 16) | (ip[2] << 8) | ip[3]); 311 | remote_addr.sin_port = htons(port); 312 | 313 | ESP_LOGVV(TAG, "Prepared packet for %u.%u.%u.%u:%d", ip[0], ip[1], ip[2], ip[3], port); 314 | return true; 315 | } 316 | 317 | bool device_groups_WiFiUDP::endPacket() { 318 | if (sock_fd < 0) { 319 | ESP_LOGE(TAG, "No valid socket for packet transmission"); 320 | return false; 321 | } 322 | 323 | if (send_data_length == 0) { 324 | ESP_LOGW(TAG, "Attempting to send empty packet"); 325 | return false; 326 | } 327 | 328 | ESP_LOGVV(TAG, "Attempting to send UDP packet: %d bytes to %s:%d", 329 | send_data_length, inet_ntoa(remote_addr.sin_addr), ntohs(remote_addr.sin_port)); 330 | 331 | int retries = MAX_RETRIES; 332 | while (retries-- > 0) { 333 | ssize_t sent = sendto(sock_fd, send_buffer, send_data_length, 0, 334 | (struct sockaddr*)&remote_addr, sizeof(remote_addr)); 335 | 336 | if (sent >= 0) { 337 | // Reduced logging verbosity to prevent performance issues during packet storms 338 | // ESP_LOGD(TAG, "UDP packet sent successfully (%d bytes)", (int)sent); 339 | // Clear the send buffer completely 340 | send_data_length = 0; 341 | if (send_buffer) { 342 | memset(send_buffer, 0, send_buffer_size); 343 | } 344 | return true; 345 | } 346 | 347 | if (errno == EAGAIN || errno == EWOULDBLOCK) { 348 | // Non-blocking socket would block, try again 349 | // Reduced logging verbosity 350 | // ESP_LOGD(TAG, "Socket would block, retrying... (%d retries left)", retries); 351 | vTaskDelay(pdMS_TO_TICKS(RETRY_DELAY_MS)); 352 | continue; 353 | } 354 | 355 | ESP_LOGE(TAG, "Failed to send UDP packet: %s (retries left: %d)", strerror(errno), retries); 356 | break; 357 | } 358 | 359 | ESP_LOGE(TAG, "All retry attempts failed for UDP packet transmission"); 360 | return false; 361 | } 362 | 363 | size_t device_groups_WiFiUDP::write(uint8_t byte) { 364 | if (!send_buffer) { 365 | send_buffer = (char*)malloc(DEFAULT_BUFFER_SIZE); 366 | send_buffer_size = DEFAULT_BUFFER_SIZE; 367 | if (!send_buffer) { 368 | ESP_LOGE(TAG, "Failed to allocate send buffer for UDP write"); 369 | return 0; 370 | } 371 | memset(send_buffer, 0, send_buffer_size); 372 | } 373 | 374 | if (send_data_length >= send_buffer_size) { 375 | // Resize buffer if needed 376 | size_t new_size = send_buffer_size * 2; 377 | char* new_buffer = (char*)realloc(send_buffer, new_size); 378 | if (!new_buffer) { 379 | ESP_LOGE(TAG, "Failed to resize send buffer from %d to %d bytes", send_buffer_size, new_size); 380 | return 0; 381 | } 382 | send_buffer = new_buffer; 383 | send_buffer_size = new_size; 384 | ESP_LOGVV(TAG, "Send buffer resized to %d bytes", new_size); 385 | } 386 | 387 | send_buffer[send_data_length++] = byte; 388 | return 1; 389 | } 390 | 391 | size_t device_groups_WiFiUDP::write(const uint8_t* data, size_t size) { 392 | if (!send_buffer) { 393 | send_buffer = (char*)malloc(DEFAULT_BUFFER_SIZE); 394 | send_buffer_size = DEFAULT_BUFFER_SIZE; 395 | if (!send_buffer) { 396 | ESP_LOGE(TAG, "Failed to allocate send buffer for UDP write"); 397 | return 0; 398 | } 399 | memset(send_buffer, 0, send_buffer_size); 400 | } 401 | 402 | // Ensure buffer is large enough 403 | while (send_data_length + size > send_buffer_size) { 404 | size_t new_size = send_buffer_size * 2; 405 | char* new_buffer = (char*)realloc(send_buffer, new_size); 406 | if (!new_buffer) { 407 | ESP_LOGE(TAG, "Failed to resize send buffer from %d to %d bytes", send_buffer_size, new_size); 408 | return 0; 409 | } 410 | send_buffer = new_buffer; 411 | send_buffer_size = new_size; 412 | ESP_LOGVV(TAG, "Send buffer resized to %d bytes", new_size); 413 | } 414 | 415 | memcpy(send_buffer + send_data_length, data, size); 416 | send_data_length += size; 417 | // Reduced logging verbosity to prevent performance issues during packet storms 418 | // ESP_LOGD(TAG, "Wrote %d bytes to send buffer (total: %d)", size, send_data_length); 419 | return size; 420 | } 421 | 422 | size_t device_groups_WiFiUDP::write(const char* str) { 423 | return write((const uint8_t*)str, strlen(str)); 424 | } 425 | 426 | int device_groups_WiFiUDP::parsePacket() { 427 | if (sock_fd < 0) { 428 | return 0; 429 | } 430 | 431 | // Allocate receive buffer if not already done 432 | if (!recv_buffer) { 433 | recv_buffer = (char*)malloc(DEFAULT_BUFFER_SIZE); 434 | recv_buffer_size = DEFAULT_BUFFER_SIZE; 435 | if (!recv_buffer) { 436 | ESP_LOGE(TAG, "Failed to allocate receive buffer for parsePacket"); 437 | return 0; 438 | } 439 | memset(recv_buffer, 0, recv_buffer_size); 440 | } 441 | 442 | // Clear any previous packet data 443 | recv_data_length = 0; 444 | recv_read_position = 0; 445 | memset(recv_buffer, 0, recv_buffer_size); 446 | 447 | struct sockaddr_in temp_sender_addr; 448 | socklen_t sender_len = sizeof(temp_sender_addr); 449 | 450 | ssize_t received = recvfrom(sock_fd, recv_buffer, recv_buffer_size - 1, MSG_DONTWAIT, 451 | (struct sockaddr*)&temp_sender_addr, &sender_len); 452 | 453 | if (received > 0) { 454 | // Simple packet deduplication to prevent storms 455 | uint32_t current_time = esp_timer_get_time() / 1000; // Convert to milliseconds 456 | uint32_t packet_hash = 0; 457 | 458 | // Simple hash of packet content and sender 459 | for (int i = 0; i < received && i < 16; i++) { // Hash first 16 bytes 460 | packet_hash = ((packet_hash << 5) + packet_hash) + recv_buffer[i]; 461 | } 462 | packet_hash ^= temp_sender_addr.sin_addr.s_addr; 463 | packet_hash ^= temp_sender_addr.sin_port; 464 | 465 | // Check if this is a duplicate packet within the deduplication window 466 | if (packet_hash == last_packet_hash && 467 | (current_time - last_packet_time) < DEDUP_WINDOW_MS) { 468 | ESP_LOGVV(TAG, "Dropping duplicate packet (hash: 0x%08x, time: %d ms)", 469 | packet_hash, current_time - last_packet_time); 470 | return 0; 471 | } 472 | 473 | // Update deduplication tracking 474 | last_packet_hash = packet_hash; 475 | last_packet_time = current_time; 476 | 477 | recv_data_length = received; 478 | recv_read_position = 0; 479 | recv_buffer[recv_data_length] = '\0'; // Null-terminate for string operations 480 | 481 | // Store sender info separately - DON'T overwrite remote_addr! 482 | sender_addr = temp_sender_addr; 483 | 484 | ESP_LOGVV(TAG, "Received UDP packet: %d bytes from %s:%d (hash: 0x%08x)", 485 | (int)received, inet_ntoa(sender_addr.sin_addr), ntohs(sender_addr.sin_port), packet_hash); 486 | 487 | return recv_data_length; 488 | } else if (received < 0 && errno != EAGAIN && errno != EWOULDBLOCK) { 489 | ESP_LOGE(TAG, "Error receiving UDP packet: %s", strerror(errno)); 490 | } 491 | 492 | return 0; 493 | } 494 | 495 | int device_groups_WiFiUDP::read() { 496 | if (recv_read_position >= recv_data_length) { 497 | return -1; 498 | } 499 | return (int)(unsigned char)recv_buffer[recv_read_position++]; 500 | } 501 | 502 | int device_groups_WiFiUDP::read(uint8_t* data, size_t size) { 503 | if (recv_read_position >= recv_data_length) { 504 | return -1; 505 | } 506 | 507 | size_t available = recv_data_length - recv_read_position; 508 | size_t to_read = (size < available) ? size : available; 509 | 510 | memcpy(data, recv_buffer + recv_read_position, to_read); 511 | recv_read_position += to_read; 512 | 513 | return to_read; 514 | } 515 | 516 | int device_groups_WiFiUDP::read(char* data, size_t size) { 517 | return read((uint8_t*)data, size); 518 | } 519 | 520 | int device_groups_WiFiUDP::peek() { 521 | if (recv_read_position >= recv_data_length) { 522 | return -1; 523 | } 524 | return (int)(unsigned char)recv_buffer[recv_read_position]; 525 | } 526 | 527 | void device_groups_WiFiUDP::flush() { 528 | // Clear the receive buffer 529 | recv_data_length = 0; 530 | recv_read_position = 0; 531 | if (recv_buffer) { 532 | memset(recv_buffer, 0, recv_buffer_size); 533 | } 534 | } 535 | 536 | IPAddress device_groups_WiFiUDP::remoteIP() { 537 | // Use sender_addr for received packets, remote_addr for sent packets 538 | uint32_t ip = ntohl(sender_addr.sin_addr.s_addr); 539 | return IPAddress((ip >> 24) & 0xFF, (ip >> 16) & 0xFF, (ip >> 8) & 0xFF, ip & 0xFF); 540 | } 541 | 542 | uint16_t device_groups_WiFiUDP::remotePort() { 543 | // Use sender_addr for received packets, remote_addr for sent packets 544 | return ntohs(sender_addr.sin_port); 545 | } 546 | 547 | bool device_groups_WiFiUDP::connected() { 548 | return is_connected && sock_fd >= 0 && validateSocket(); 549 | } 550 | 551 | void device_groups_WiFiUDP::setTimeout(int timeout_ms) { 552 | if (sock_fd >= 0) { 553 | struct timeval tv; 554 | tv.tv_sec = timeout_ms / 1000; 555 | tv.tv_usec = (timeout_ms % 1000) * 1000; 556 | if (setsockopt(sock_fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0) { 557 | ESP_LOGW(TAG, "Failed to set socket timeout: %s", strerror(errno)); 558 | } 559 | } 560 | } 561 | 562 | uint16_t device_groups_WiFiUDP::localPort() { 563 | if (sock_fd < 0) { 564 | return 0; 565 | } 566 | 567 | struct sockaddr_in addr; 568 | socklen_t len = sizeof(addr); 569 | if (getsockname(sock_fd, (struct sockaddr*)&addr, &len) < 0) { 570 | ESP_LOGW(TAG, "Failed to get local port: %s", strerror(errno)); 571 | return 0; 572 | } 573 | return ntohs(addr.sin_port); 574 | } 575 | 576 | const char* device_groups_WiFiUDP::localIP() { 577 | static char ip_str[16]; 578 | 579 | // Get the default network interface (usually WiFi STA) 580 | esp_netif_t* netif = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF"); 581 | if (netif == nullptr) { 582 | // Try to get any available network interface 583 | esp_netif_t* netif_list[4]; // Use a reasonable default size 584 | int netif_count = esp_netif_get_nr_of_ifs(); 585 | if (netif_count > 0 && netif_count <= 4) { 586 | // Get the first available interface 587 | esp_netif_t* default_netif = esp_netif_get_default_netif(); 588 | if (default_netif != nullptr) { 589 | netif = default_netif; 590 | } else { 591 | // Fallback: try to get any interface 592 | esp_netif_t* current_netif = nullptr; 593 | esp_netif_t* temp_netif = esp_netif_next_unsafe(nullptr); 594 | if (temp_netif != nullptr) { 595 | netif = temp_netif; 596 | } 597 | } 598 | } 599 | } 600 | 601 | if (netif != nullptr) { 602 | esp_netif_ip_info_t ip_info; 603 | if (esp_netif_get_ip_info(netif, &ip_info) == ESP_OK) { 604 | inet_ntop(AF_INET, &ip_info.ip.addr, ip_str, sizeof(ip_str)); 605 | return ip_str; 606 | } 607 | } 608 | 609 | ESP_LOGW(TAG, "Failed to get local IP address"); 610 | return "0.0.0.0"; 611 | } 612 | 613 | int device_groups_WiFiUDP::available() { 614 | return recv_data_length - recv_read_position; 615 | } 616 | 617 | const char* device_groups_WiFiUDP::ipToString(uint32_t ip) { 618 | static char ip_str[16]; 619 | struct in_addr addr; 620 | addr.s_addr = htonl(ip); 621 | inet_ntop(AF_INET, &addr, ip_str, sizeof(ip_str)); 622 | return ip_str; 623 | } 624 | 625 | #endif // USE_ESP_IDF 626 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /components/device_groups/device_groups.cpp: -------------------------------------------------------------------------------- 1 | #include "device_groups.h" 2 | #include "esphome/core/helpers.h" 3 | #include "esphome/core/log.h" 4 | #include "esphome/components/network/ip_address.h" 5 | #include "esphome/components/network/util.h" 6 | 7 | namespace esphome { 8 | namespace device_groups { 9 | 10 | static const char *const TAG = "dgr"; 11 | 12 | char *IPAddressToString(const IPAddress &ip_address) { 13 | static char buffer[16]; 14 | sprintf_P(buffer, PSTR("%u.%u.%u.%u"), ip_address[0], ip_address[1], ip_address[2], ip_address[3]); 15 | return buffer; 16 | } 17 | 18 | uint8_t *BeginDeviceGroupMessage(struct device_group *device_group, uint16_t flags, bool hold_sequence = false) { 19 | uint8_t *message_ptr = &device_group->message[device_group->message_header_length]; 20 | if (!hold_sequence && !++device_group->outgoing_sequence) 21 | device_group->outgoing_sequence = 1; 22 | *message_ptr++ = device_group->outgoing_sequence & 0xff; 23 | *message_ptr++ = device_group->outgoing_sequence >> 8; 24 | *message_ptr++ = flags & 0xff; 25 | *message_ptr++ = flags >> 8; 26 | return message_ptr; 27 | } 28 | 29 | uint32_t DeviceGroupSharedMask(uint8_t item) { 30 | uint32_t mask = 0; 31 | if (item == DGR_ITEM_LIGHT_BRI || item == DGR_ITEM_BRI_POWER_ON) 32 | mask = DGR_SHARE_LIGHT_BRI; 33 | else if (item == DGR_ITEM_POWER) 34 | mask = DGR_SHARE_POWER; 35 | else if (item == DGR_ITEM_LIGHT_SCHEME) 36 | mask = DGR_SHARE_LIGHT_SCHEME; 37 | else if (item == DGR_ITEM_LIGHT_FIXED_COLOR || item == DGR_ITEM_LIGHT_CHANNELS) 38 | mask = DGR_SHARE_LIGHT_COLOR; 39 | else if (item == DGR_ITEM_LIGHT_FADE || item == DGR_ITEM_LIGHT_SPEED) 40 | mask = DGR_SHARE_LIGHT_FADE; 41 | else if (item == DGR_ITEM_BRI_PRESET_LOW || item == DGR_ITEM_BRI_PRESET_HIGH) 42 | mask = DGR_SHARE_DIMMER_SETTINGS; 43 | else if (item == DGR_ITEM_EVENT) 44 | mask = DGR_SHARE_EVENT; 45 | return mask; 46 | } 47 | 48 | void device_groups::setup() { 49 | ESP_LOGCONFIG(TAG, "Setting up Device Groups Component for group %s", this->device_group_name_.c_str()); 50 | 51 | std::string registered_group_name = this->device_group_name_; 52 | #if defined(ESP8266) 53 | registered_group_names.push_back(registered_group_name); 54 | #endif 55 | 56 | #ifdef USE_SWITCH 57 | for (switch_::Switch *obj : this->switches_) { 58 | obj->add_on_state_callback([this, obj](bool state) { 59 | ExecuteCommandPower(1, state, SRC_SWITCH); 60 | }); 61 | } 62 | #endif 63 | #ifdef USE_LIGHT 64 | for (light::LightState *obj : this->lights_) { 65 | set_light_intial_values(obj); 66 | 67 | obj->add_remote_values_listener(this); 68 | } 69 | #endif 70 | } 71 | 72 | #ifdef USE_LIGHT 73 | void device_groups::on_light_remote_values_update() { 74 | for (light::LightState *obj : this->lights_) { 75 | bool power_state; 76 | float brightness, color_brightness, red, green, blue, cold_white, warm_white; 77 | esphome::light::ColorMode color_mode; 78 | 79 | get_light_values(obj, power_state, brightness, color_brightness, red, green, blue, cold_white, warm_white, color_mode); 80 | 81 | if (power_state != previous_power_state) { 82 | ExecuteCommandPower(1, power_state, SRC_LIGHT); 83 | } 84 | 85 | if (power_state != previous_power_state 86 | ||red != previous_red 87 | || green != previous_green 88 | || blue != previous_blue 89 | || warm_white != previous_warm_white 90 | || cold_white != previous_cold_white 91 | || brightness != previous_brightness 92 | || color_brightness != previous_color_brightness 93 | || color_mode != previous_color_mode 94 | ) { 95 | uint8_t light_channels[6] = { 96 | (uint8_t)(red * 255), 97 | (uint8_t)(green * 255), 98 | (uint8_t)(blue * 255), 99 | (uint8_t)(cold_white * 255), 100 | (uint8_t)(warm_white * 255), 101 | 0 102 | }; 103 | 104 | SendDeviceGroupMessage(1, (DevGroupMessageType) (DGR_MSGTYP_UPDATE), 105 | DGR_ITEM_LIGHT_CHANNELS, light_channels); 106 | } 107 | 108 | if (brightness != previous_brightness) { 109 | SendDeviceGroupMessage(1, (DevGroupMessageType) (DGR_MSGTYP_UPDATE + DGR_MSGTYPFLAG_WITH_LOCAL), 110 | DGR_ITEM_LIGHT_BRI, (uint8_t)(brightness * 255)); 111 | } 112 | 113 | previous_power_state = power_state; 114 | previous_brightness = brightness; 115 | previous_color_brightness = color_brightness; 116 | previous_red = red; 117 | previous_green = green; 118 | previous_blue = blue; 119 | previous_cold_white = cold_white; 120 | previous_warm_white = warm_white; 121 | previous_color_mode = color_mode; 122 | } 123 | } 124 | 125 | void device_groups::get_light_values(light::LightState *obj, bool &power_state, float &brightness, float &color_brightness, float &red, float &green, float &blue, float &cold_white, float &warm_white, esphome::light::ColorMode &color_mode) { 126 | power_state = obj->remote_values.is_on(); 127 | brightness = obj->remote_values.get_brightness(); 128 | color_brightness = obj->remote_values.get_color_brightness(); 129 | 130 | if (obj->get_traits().supports_color_capability(light::ColorCapability::COLOR_TEMPERATURE)) { 131 | float min_mireds = 0.0f, max_mireds = 0.0f, color_temperature = 0.0f; 132 | color_temperature = obj->remote_values.get_color_temperature(); 133 | min_mireds = obj->get_traits().get_min_mireds(); 134 | max_mireds = obj->get_traits().get_max_mireds(); 135 | warm_white = (color_temperature - min_mireds) / (max_mireds - min_mireds); 136 | cold_white = 1.0f - warm_white; 137 | } else if (obj->get_traits().supports_color_capability(light::ColorCapability::COLD_WARM_WHITE)) { 138 | cold_white = obj->remote_values.get_cold_white(); 139 | warm_white = obj->remote_values.get_warm_white(); 140 | } else if (obj->get_traits().supports_color_capability(light::ColorCapability::WHITE)) { 141 | warm_white = cold_white = obj->remote_values.get_white(); 142 | } 143 | 144 | if (obj->get_traits().supports_color_capability(light::ColorCapability::RGB) && color_brightness > 0) { 145 | red = obj->remote_values.get_red(); 146 | green = obj->remote_values.get_green(); 147 | blue = obj->remote_values.get_blue(); 148 | } 149 | 150 | color_mode = obj->remote_values.get_color_mode(); 151 | 152 | bool has_rgb_mode = color_mode & light::ColorCapability::RGB; 153 | bool has_white_mode = color_mode & light::ColorCapability::WHITE 154 | || color_mode & light::ColorCapability::COLOR_TEMPERATURE 155 | || color_mode & light::ColorCapability::COLD_WARM_WHITE; 156 | bool has_rgb_values = red > 0 || green > 0 || blue > 0; 157 | bool has_white_values = warm_white > 0 || cold_white > 0; 158 | 159 | if ((!has_rgb_mode && has_rgb_values) || (has_rgb_mode && !has_rgb_values)) { 160 | red = green = blue = 0; 161 | color_brightness = 0; 162 | color_mode = (light::ColorMode)(static_cast(color_mode) ^ static_cast(light::ColorCapability::RGB)); 163 | has_rgb_mode = has_rgb_values = false; 164 | } 165 | 166 | if ((!has_white_mode && has_white_values) || (has_white_mode && !has_white_values)) { 167 | warm_white = cold_white = 0; 168 | color_mode = (light::ColorMode)(static_cast(color_mode) ^ static_cast(light::ColorCapability::WHITE)); 169 | color_mode = (light::ColorMode)(static_cast(color_mode) ^ static_cast(light::ColorCapability::COLOR_TEMPERATURE)); 170 | color_mode = (light::ColorMode)(static_cast(color_mode) ^ static_cast(light::ColorCapability::COLD_WARM_WHITE)); 171 | has_white_mode = has_white_values = false; 172 | } 173 | } 174 | 175 | void device_groups::set_light_intial_values(light::LightState *obj) { 176 | bool power_state; 177 | float brightness, color_brightness, red, green, blue, cold_white, warm_white; 178 | esphome::light::ColorMode color_mode = esphome::light::ColorMode::UNKNOWN; 179 | get_light_values(obj, power_state, brightness, color_brightness, red, green, blue, cold_white, warm_white, color_mode); 180 | 181 | previous_power_state = power_state; 182 | previous_brightness = brightness; 183 | previous_color_brightness = color_brightness; 184 | previous_red = red; 185 | previous_green = green; 186 | previous_blue = blue; 187 | previous_cold_white = cold_white; 188 | previous_warm_white = warm_white; 189 | previous_color_mode = color_mode; 190 | } 191 | #endif 192 | 193 | void device_groups::dump_config() { 194 | ESP_LOGCONFIG(TAG, "Device Group %s configuration:", this->device_group_name_.c_str()); 195 | ESP_LOGCONFIG(TAG, " - Send Mask: 0x%08x", send_mask_); 196 | ESP_LOGCONFIG(TAG, " - Receive Mask: 0x%08x", receive_mask_); 197 | #ifdef USE_SWITCH 198 | ESP_LOGCONFIG(TAG, "Switches:"); 199 | if (this->switches_.empty()) { 200 | ESP_LOGCONFIG(TAG, " - No switches mapped"); 201 | } else { 202 | for (switch_::Switch *obj : this->switches_) { 203 | ESP_LOGCONFIG(TAG, " - %s (%s)", obj->get_object_id().c_str(), obj->get_name().c_str()); 204 | } 205 | } 206 | #else 207 | ESP_LOGCONFIG(TAG, "Switches not configured"); 208 | #endif 209 | #ifdef USE_LIGHT 210 | ESP_LOGCONFIG(TAG, "Lights:"); 211 | if (this->lights_.empty()) { 212 | ESP_LOGCONFIG(TAG, " - No lights mapped"); 213 | } else { 214 | for (light::LightState *obj : this->lights_) { 215 | ESP_LOGCONFIG(TAG, " - %s (%s)", obj->get_object_id().c_str(), obj->get_name().c_str()); 216 | } 217 | } 218 | #else 219 | ESP_LOGCONFIG(TAG, "Lights not configured"); 220 | #endif 221 | 222 | setup_complete = true; 223 | } 224 | 225 | void device_groups::loop() { 226 | if (!this->update_) 227 | return; 228 | 229 | if (!network::is_connected()) { 230 | DeviceGroupsStop(); 231 | dgr_state = DGR_STATE_UNINTIALIZED; 232 | return; 233 | } 234 | 235 | if (!setup_complete) { 236 | return; 237 | } 238 | 239 | if (dgr_state == DGR_STATE_UNINTIALIZED) { 240 | dgr_state = DGR_STATE_INITIALIZING; 241 | InitTasmotaCompatibility(); 242 | // DeviceGroupsInit(); // automatically called by DeviceGrupsStart() 243 | if (DeviceGroupsStart()) { 244 | dgr_state = DGR_STATE_INITIALIZED; 245 | } else { 246 | dgr_state = DGR_STATE_UNINTIALIZED; 247 | } 248 | } 249 | 250 | if (dgr_state != DGR_STATE_INITIALIZED) { 251 | return; 252 | } 253 | 254 | DeviceGroupsLoop(); 255 | } 256 | 257 | void device_groups::DeviceGroupsInit() { 258 | // If no module set the device group count, ... 259 | if (!device_group_count) { 260 | // If relays in separate device groups is enabled, set the device group count to highest numbered 261 | // button. 262 | /*if (Settings->flag4.multiple_device_groups) { // SetOption88 - Enable relays in separate device groups 263 | for (uint32_t relay_index = 0; relay_index < MAX_RELAYS; relay_index++) { 264 | if (PinUsed(GPIO_REL1, relay_index)) device_group_count = relay_index + 1; 265 | } 266 | }*/ 267 | 268 | // Set up a minimum of one device group. 269 | if (!device_group_count) 270 | device_group_count = 1; 271 | else if (device_group_count > MAX_DEV_GROUP_NAMES) 272 | device_group_count = MAX_DEV_GROUP_NAMES; 273 | } 274 | 275 | // If there are more device group names set than the number of device groups needed by the 276 | // module, use the device group name count as the device group count. 277 | /*for (; device_group_count < MAX_DEV_GROUP_NAMES; device_group_count++) { 278 | if (!*SettingsText(SET_DEV_GROUP_NAME1 + device_group_count)) break; 279 | }*/ 280 | 281 | // Initialize the device information for each device group. 282 | device_groups_ = (struct device_group *) calloc(device_group_count, sizeof(struct device_group)); 283 | if (!device_groups_) { 284 | ESP_LOGE(TAG, "Error allocating %u-element array", device_group_count); 285 | return; 286 | } 287 | 288 | struct device_group *device_group = device_groups_; 289 | for (uint32_t device_group_index = 0; device_group_index < device_group_count; device_group_index++, device_group++) { 290 | /*strcpy(device_group->group_name, SettingsText(SET_DEV_GROUP_NAME1 + device_group_index)); 291 | 292 | // If the device group name is not set, use the MQTT group topic (with the device group index + 293 | // 1 appended for device group indices > 0). 294 | if (!device_group->group_name[0]) { 295 | strcpy(device_group->group_name, SettingsText(SET_MQTT_GRP_TOPIC)); 296 | if (device_group_index) { 297 | snprintf_P(device_group->group_name, sizeof(device_group->group_name), PSTR("%s%u"), device_group->group_name, 298 | device_group_index + 1); 299 | } 300 | }*/ 301 | strcpy(device_group->group_name, this->device_group_name_.c_str()); 302 | device_group->message_header_length = 303 | sprintf_P((char *) device_group->message, PSTR("%s%s"), kDeviceGroupMessage, device_group->group_name) + 1; 304 | device_group->no_status_share = 0; 305 | device_group->last_full_status_sequence = -1; 306 | } 307 | 308 | // If both in and out shared items masks are 0, assume they're unitialized and initialize them. 309 | if (!Settings->device_group_share_in && !Settings->device_group_share_out) { 310 | Settings->device_group_share_in = Settings->device_group_share_out = 0xffffffff; 311 | } 312 | 313 | device_groups_initialized = true; 314 | } 315 | 316 | bool device_groups::DeviceGroupsStart() { 317 | if (Settings->flag4.device_groups_enabled && !device_groups_up && !TasmotaGlobal.restart_flag) { 318 | // If we haven't successfuly initialized device groups yet, attempt to do it now. 319 | if (!device_groups_initialized) { 320 | DeviceGroupsInit(); 321 | if (!device_groups_initialized) 322 | return false; 323 | } 324 | 325 | // Subscribe to device groups multicasts. 326 | #ifdef ESP8266 327 | if (!device_groups_udp.beginMulticast(WiFi.localIP(), IPAddress(DEVICE_GROUPS_ADDRESS), DEVICE_GROUPS_PORT)) { 328 | ESP_LOGE(TAG, "Error subscribing"); 329 | return false; 330 | } 331 | #else 332 | if (!device_groups_udp.beginMulticast(IPAddress(DEVICE_GROUPS_ADDRESS), DEVICE_GROUPS_PORT)) { 333 | ESP_LOGE(TAG, "Error subscribing"); 334 | return false; 335 | } 336 | #endif 337 | device_groups_up = true; 338 | 339 | // The WiFi was down but now it's up and device groups is initialized. (Re-)discover devices in 340 | // our device group(s). Load the status request message for all device groups. This message will 341 | // be multicast 10 times at 200ms intervals. 342 | next_check_time = millis() + 2000; 343 | struct device_group *device_group = device_groups_; 344 | for (uint32_t device_group_index = 0; device_group_index < device_group_count; 345 | device_group_index++, device_group++) { 346 | device_group->next_announcement_time = -1; 347 | device_group->message_length = 348 | BeginDeviceGroupMessage(device_group, DGR_FLAG_RESET | DGR_FLAG_STATUS_REQUEST) - device_group->message; 349 | device_group->initial_status_requests_remaining = 10; 350 | device_group->next_ack_check_time = next_check_time; 351 | } 352 | ESP_LOGD(TAG, "%s (Re)discovering members", this->device_group_name_.c_str()); 353 | } 354 | 355 | return true; 356 | } 357 | 358 | void device_groups::DeviceGroupsStop() { 359 | device_groups_udp.flush(); 360 | device_groups_up = false; 361 | } 362 | 363 | void device_groups::SendReceiveDeviceGroupMessage(struct device_group *device_group, 364 | struct device_group_member *device_group_member, uint8_t *message, 365 | int message_length, bool received) { 366 | bool item_processed = false; 367 | uint16_t message_sequence; 368 | uint16_t flags; 369 | int device_group_index = device_group - device_groups_; 370 | int log_length; 371 | int log_remaining; 372 | char *log_ptr; 373 | 374 | // Find the end and start of the actual message (after the header). 375 | uint8_t *message_end_ptr = message + message_length; 376 | uint8_t *message_ptr = message + strlen((char *) message) + 1; 377 | 378 | // Get the message sequence and flags. 379 | if (message_ptr + 4 > message_end_ptr) 380 | return; // Malformed message - must be at least 16-bit sequence, 16-bit flags left 381 | message_sequence = *message_ptr++; 382 | message_sequence |= *message_ptr++ << 8; 383 | flags = *message_ptr++; 384 | flags |= *message_ptr++ << 8; 385 | 386 | // Initialize the log buffer. 387 | char *log_buffer = (char *) malloc(512); 388 | log_length = sprintf(log_buffer, PSTR("%s %s message %s %s: seq=%u, flags=%u"), 389 | (received ? PSTR("Received") : PSTR("Sending")), device_group->group_name, 390 | (received ? PSTR("from") : PSTR("to")), 391 | (device_group_member ? IPAddressToString(device_group_member->ip_address) 392 | : received ? PSTR("local") 393 | : PSTR("network")), 394 | message_sequence, flags); 395 | log_ptr = log_buffer + log_length; 396 | log_remaining = 512 - log_length; 397 | 398 | // If this is an announcement, just log it. 399 | if (flags == DGR_FLAG_ANNOUNCEMENT) 400 | goto write_log; 401 | 402 | // If this is a received ack message, save the message sequence if it's newer than the last ack we 403 | // received from this member. 404 | if (flags == DGR_FLAG_ACK) { 405 | if (received && device_group_member && 406 | (message_sequence > device_group_member->acked_sequence || 407 | device_group_member->acked_sequence - message_sequence < 64536)) { 408 | device_group_member->acked_sequence = message_sequence; 409 | } 410 | goto write_log; 411 | } 412 | 413 | // If this is a received message, send an ack message to the sender. 414 | if (device_group_member) { 415 | if (received) { 416 | if (!(flags & DGR_FLAG_MORE_TO_COME)) { 417 | *(message_ptr - 2) = DGR_FLAG_ACK; 418 | *(message_ptr - 1) = 0; 419 | SendReceiveDeviceGroupMessage(device_group, device_group_member, message, message_ptr - message, false); 420 | } 421 | } 422 | 423 | // If we're sending this message directly to a member, it's a resend. 424 | else { 425 | log_length = snprintf(log_ptr, log_remaining, PSTR(", last ack=%u"), device_group_member->acked_sequence); 426 | log_ptr += log_length; 427 | log_remaining -= log_length; 428 | goto write_log; 429 | } 430 | } 431 | 432 | // If this is a status request message, skip item processing. 433 | if ((flags & DGR_FLAG_STATUS_REQUEST)) 434 | goto write_log; 435 | 436 | // If this is a received message, ... 437 | if (received) { 438 | // If we already processed this or a later message from this group member, ignore this message. 439 | if (device_group_member) { 440 | if (message_sequence <= device_group_member->received_sequence) { 441 | if (message_sequence == device_group_member->received_sequence || 442 | device_group_member->received_sequence - message_sequence > 64536) { 443 | log_length = snprintf(log_ptr, log_remaining, PSTR(" (old)")); 444 | log_ptr += log_length; 445 | log_remaining -= log_length; 446 | goto write_log; 447 | } 448 | } 449 | device_group_member->received_sequence = message_sequence; 450 | } 451 | 452 | /* 453 | XdrvMailbox 454 | bool grpflg 455 | bool usridx 456 | uint16_t command_code Item code 457 | uint32_t index 0:15 Flags, 16:31 Message sequence 458 | uint32_t data_len String item value length 459 | int32_t payload Integer item value 460 | char *topic Pointer to device group index 461 | char *data Pointer to non-integer item value 462 | char *command nullptr 463 | */ 464 | XdrvMailbox.command = nullptr; // Indicates the source is a device group update 465 | XdrvMailbox.index = flags | message_sequence << 16; 466 | if (device_group_index == 0 && first_device_group_is_local) 467 | XdrvMailbox.index |= DGR_FLAG_LOCAL; 468 | XdrvMailbox.topic = (char *) &device_group_index; 469 | if (flags & (DGR_FLAG_MORE_TO_COME | DGR_FLAG_DIRECT)) 470 | TasmotaGlobal.skip_light_fade = true; 471 | 472 | // Set the flag to ignore device group send message request so callbacks from the drivers do not 473 | // send updates. 474 | ignore_dgr_sends = true; 475 | } 476 | 477 | uint8_t item; 478 | uint8_t item_flags; 479 | int32_t value; 480 | uint32_t mask; 481 | item_flags = 0; 482 | for (;;) { 483 | if (message_ptr >= message_end_ptr) 484 | goto badmsg; // Malformed message 485 | item = *message_ptr++; 486 | if (!item) 487 | break; // Done 488 | 489 | #ifdef DEVICE_GROUPS_DEBUG 490 | switch (item) { 491 | case DGR_ITEM_FLAGS: 492 | case DGR_ITEM_LIGHT_FADE: 493 | case DGR_ITEM_LIGHT_SPEED: 494 | case DGR_ITEM_LIGHT_BRI: 495 | case DGR_ITEM_LIGHT_SCHEME: 496 | case DGR_ITEM_LIGHT_FIXED_COLOR: 497 | case DGR_ITEM_BRI_PRESET_LOW: 498 | case DGR_ITEM_BRI_PRESET_HIGH: 499 | case DGR_ITEM_BRI_POWER_ON: 500 | case DGR_ITEM_POWER: 501 | case DGR_ITEM_NO_STATUS_SHARE: 502 | case DGR_ITEM_EVENT: 503 | case DGR_ITEM_LIGHT_CHANNELS: 504 | break; 505 | default: 506 | ESP_LOGE(TAG, "*** Invalid item=%u", item); 507 | } 508 | #endif // DEVICE_GROUPS_DEBUG 509 | 510 | log_length = snprintf(log_ptr, log_remaining, ", %u=", item); 511 | log_ptr += log_length; 512 | log_remaining -= log_length; 513 | log_length = 0; 514 | if (item <= DGR_ITEM_LAST_32BIT) { 515 | value = *message_ptr++; 516 | if (item > DGR_ITEM_MAX_8BIT) { 517 | value |= *message_ptr++ << 8; 518 | if (item > DGR_ITEM_MAX_16BIT) { 519 | value |= *message_ptr++ << 16; 520 | value |= *message_ptr++ << 24; 521 | #ifdef USE_DEVICE_GROUPS_SEND 522 | if (item < DGR_ITEM_LAST_32BIT) 523 | device_group->values_32bit[item - DGR_ITEM_MAX_16BIT - 1] = 524 | (item == DGR_ITEM_POWER ? value & 0xffffff : value); 525 | #endif // USE_DEVICE_GROUPS_SEND 526 | } 527 | #ifdef USE_DEVICE_GROUPS_SEND 528 | else { 529 | if (item < DGR_ITEM_LAST_16BIT) 530 | device_group->values_16bit[item - DGR_ITEM_MAX_8BIT - 1] = value; 531 | } 532 | #endif // USE_DEVICE_GROUPS_SEND 533 | } 534 | #ifdef USE_DEVICE_GROUPS_SEND 535 | else { 536 | if (item < DGR_ITEM_LAST_8BIT) 537 | device_group->values_8bit[item] = value; 538 | } 539 | #endif // USE_DEVICE_GROUPS_SEND 540 | log_length = snprintf(log_ptr, log_remaining, "%i", value); 541 | } else { 542 | value = *message_ptr++; 543 | if (received) 544 | XdrvMailbox.data = (char *) message_ptr; 545 | if (message_ptr + value >= message_end_ptr) 546 | goto badmsg; // Malformed message 547 | if (item <= DGR_ITEM_MAX_STRING) { 548 | log_length = snprintf(log_ptr, log_remaining, PSTR("'%s'"), message_ptr); 549 | } else { 550 | switch (item) { 551 | case DGR_ITEM_LIGHT_CHANNELS: 552 | log_length = snprintf(log_ptr, log_remaining, PSTR("%u,%u,%u,%u,%u,%u"), *message_ptr, *(message_ptr + 1), 553 | *(message_ptr + 2), *(message_ptr + 3), *(message_ptr + 4), *(message_ptr + 5)); 554 | break; 555 | } 556 | } 557 | message_ptr += value; 558 | } 559 | log_ptr += log_length; 560 | log_remaining -= log_length; 561 | 562 | if (received) { 563 | if (item == DGR_ITEM_FLAGS) { 564 | item_flags = value; 565 | continue; 566 | } 567 | 568 | mask = DeviceGroupSharedMask(item); 569 | if (item_flags & DGR_ITEM_FLAG_NO_SHARE) 570 | device_group->no_status_share |= mask; 571 | else 572 | device_group->no_status_share &= ~mask; 573 | 574 | if ((!(device_group->no_status_share & mask) || device_group_member == nullptr) && 575 | (!mask || (mask & Settings->device_group_share_in))) { 576 | item_processed = true; 577 | XdrvMailbox.command_code = item; 578 | XdrvMailbox.payload = value; 579 | XdrvMailbox.data_len = value; 580 | *log_ptr++ = '*'; 581 | log_remaining--; 582 | switch (item) { 583 | case DGR_ITEM_POWER: 584 | if (Settings->flag4.multiple_device_groups) { // SetOption88 - Enable relays in separate device groups 585 | uint32_t device = Settings->device_group_tie[device_group_index]; 586 | if (device && device <= TasmotaGlobal.devices_present) { 587 | bool on = (value & 1); 588 | if (on != ((TasmotaGlobal.power >> (device - 1)) & 1)) 589 | ExecuteCommandPower(device, (on ? POWER_ON : POWER_OFF), SRC_REMOTE); 590 | } 591 | } else if (XdrvMailbox.index & DGR_FLAG_LOCAL) { 592 | uint8_t mask_devices = value >> 24; 593 | if (mask_devices > TasmotaGlobal.devices_present) 594 | mask_devices = TasmotaGlobal.devices_present; 595 | for (uint32_t i = 0; i < mask_devices; i++) { 596 | uint32_t mask = 1 << i; 597 | bool on = (value & mask); 598 | if (on != (TasmotaGlobal.power & mask)) 599 | ExecuteCommandPower(i + 1, (on ? POWER_ON : POWER_OFF), SRC_REMOTE); 600 | } 601 | } 602 | break; 603 | case DGR_ITEM_NO_STATUS_SHARE: 604 | device_group->no_status_share = value; 605 | break; 606 | #ifdef USE_RULES 607 | case DGR_ITEM_EVENT: 608 | CmndEvent(); 609 | break; 610 | #endif 611 | case DGR_ITEM_COMMAND: 612 | ExecuteCommand(XdrvMailbox.data, SRC_REMOTE); 613 | break; 614 | case DGR_ITEM_LIGHT_FADE: 615 | TasmotaGlobal.fade = XdrvMailbox.payload; 616 | break; 617 | case DGR_ITEM_LIGHT_SPEED: 618 | TasmotaGlobal.speed = XdrvMailbox.payload; 619 | break; 620 | case DGR_ITEM_LIGHT_SCHEME: 621 | TasmotaGlobal.scheme = XdrvMailbox.payload; 622 | break; 623 | case DGR_ITEM_LIGHT_FIXED_COLOR: 624 | break; 625 | case DGR_ITEM_LIGHT_BRI: 626 | #ifdef USE_LIGHT 627 | for (light::LightState *obj : this->lights_) { 628 | auto call = obj->make_call(); 629 | if (obj->remote_values.get_color_mode() & light::ColorCapability::RGB) { 630 | call.set_color_brightness_if_supported(XdrvMailbox.payload / 255.0f); 631 | } else { 632 | call.set_brightness_if_supported(XdrvMailbox.payload / 255.0f); 633 | call.set_color_brightness_if_supported(0); 634 | } 635 | call.perform(); 636 | } 637 | #endif 638 | break; 639 | case DGR_ITEM_LIGHT_CHANNELS: 640 | #ifdef USE_LIGHT 641 | for (light::LightState *obj : this->lights_) { 642 | auto call = obj->make_call(); 643 | const float red = (uint8_t) XdrvMailbox.data[0] / 255.0f; 644 | const float green = (uint8_t) XdrvMailbox.data[1] / 255.0f; 645 | const float blue = (uint8_t) XdrvMailbox.data[2] / 255.0f; 646 | const float cold_white = (uint8_t) XdrvMailbox.data[3] / 255.0f; 647 | const float warm_white = (uint8_t) XdrvMailbox.data[4] / 255.0f; 648 | const bool has_rgb = red + green + blue > 0.0f; 649 | const bool has_white = cold_white + warm_white > 0.0f; 650 | light::ColorMode color_mode = light::ColorMode::ON_OFF | light::ColorMode::BRIGHTNESS; 651 | 652 | if (has_rgb && obj->get_traits().supports_color_capability(light::ColorCapability::RGB)) { 653 | color_mode = color_mode | light::ColorCapability::RGB; 654 | } 655 | 656 | if (has_white && obj->get_traits().supports_color_capability(light::ColorCapability::COLOR_TEMPERATURE)) { 657 | color_mode = color_mode | light::ColorCapability::COLOR_TEMPERATURE; 658 | } else if (has_white && obj->get_traits().supports_color_capability(light::ColorCapability::COLD_WARM_WHITE)) { 659 | color_mode = color_mode | light::ColorCapability::COLD_WARM_WHITE; 660 | } else if (has_white && obj->get_traits().supports_color_capability(light::ColorCapability::WHITE)) { 661 | color_mode = color_mode | light::ColorCapability::WHITE; 662 | } 663 | 664 | call.set_color_mode_if_supported(color_mode); 665 | 666 | if (color_mode & light::ColorCapability::RGB) { 667 | call.set_red_if_supported(red); 668 | call.set_green_if_supported(green); 669 | call.set_blue_if_supported(blue); 670 | } else { 671 | call.set_red_if_supported(0); 672 | call.set_green_if_supported(0); 673 | call.set_blue_if_supported(0); 674 | call.set_color_brightness_if_supported(0); 675 | } 676 | 677 | if (has_white && color_mode & light::ColorCapability::COLOR_TEMPERATURE) { 678 | call.set_color_temperature_if_supported((warm_white * obj->get_traits().get_max_mireds()) + (cold_white * obj->get_traits().get_min_mireds())); 679 | } else if (has_white && color_mode & light::ColorCapability::COLD_WARM_WHITE) { 680 | call.set_cold_white_if_supported(cold_white); 681 | call.set_warm_white_if_supported(warm_white); 682 | } else if (has_white) { 683 | call.set_white_if_supported(cold_white > warm_white ? cold_white : warm_white); 684 | } else { 685 | call.set_white_if_supported(0); 686 | } 687 | 688 | call.perform(); 689 | } 690 | #endif 691 | break; 692 | case DGR_ITEM_STATUS: 693 | #ifdef USE_SWITCH 694 | for (switch_::Switch *obj : this->switches_) { 695 | SendDeviceGroupMessage(1, (DevGroupMessageType) (DGR_MSGTYP_UPDATE), DGR_ITEM_POWER, obj->state); 696 | } 697 | #endif 698 | #ifdef USE_LIGHT 699 | for (light::LightState *obj : this->lights_) { 700 | float red = 0.0f, green = 0.0f, blue = 0.0f, cold_white = 0.0f, warm_white = 0.0f, brightness = 0.0f, color_brightness = 0.0f; 701 | brightness = obj->remote_values.get_brightness(); 702 | color_brightness = obj->remote_values.get_color_brightness(); 703 | 704 | if (obj->get_traits().supports_color_capability(light::ColorCapability::COLOR_TEMPERATURE)) { 705 | float min_mireds = 0.0f, max_mireds = 0.0f, color_temperature = 0.0f; 706 | color_temperature = obj->remote_values.get_color_temperature(); 707 | min_mireds = obj->get_traits().get_min_mireds(); 708 | max_mireds = obj->get_traits().get_max_mireds(); 709 | warm_white = (color_temperature - min_mireds) / (max_mireds - min_mireds); 710 | cold_white = 1.0f - warm_white; 711 | } else if (obj->get_traits().supports_color_capability(light::ColorCapability::COLD_WARM_WHITE)) { 712 | cold_white = obj->remote_values.get_cold_white(); 713 | warm_white = obj->remote_values.get_warm_white(); 714 | } else if (obj->get_traits().supports_color_capability(light::ColorCapability::WHITE)) { 715 | warm_white = cold_white = obj->remote_values.get_white(); 716 | } 717 | 718 | if (color_brightness > 0 && obj->get_traits().supports_color_capability(light::ColorCapability::RGB)) { 719 | red = obj->remote_values.get_red(); 720 | green = obj->remote_values.get_green(); 721 | blue = obj->remote_values.get_blue(); 722 | } 723 | 724 | auto color_mode = obj->remote_values.get_color_mode(); 725 | 726 | if (color_mode == light::ColorMode::RGB) { 727 | cold_white = warm_white = 0; 728 | } else if (color_mode == light::ColorMode::WHITE 729 | || color_mode == light::ColorMode::COLOR_TEMPERATURE 730 | || color_mode == light::ColorMode::COLD_WARM_WHITE) { 731 | red = green = blue = 0; 732 | color_brightness = 0; 733 | } 734 | 735 | uint8_t light_channels[6] = { 736 | (uint8_t)(red * 255), 737 | (uint8_t)(green * 255), 738 | (uint8_t)(blue * 255), 739 | (uint8_t)(cold_white * 255), 740 | (uint8_t)(warm_white * 255), 741 | 0 742 | }; 743 | SendDeviceGroupMessage(1, (DevGroupMessageType) (DGR_MSGTYP_UPDATE_MORE_TO_COME), 744 | DGR_ITEM_POWER, obj->remote_values.is_on()); 745 | // If the light is turning off, don't send channel data, as ESPHome will have 0 for all channels in shut-off mode. 746 | if (obj->remote_values.is_on()) { 747 | SendDeviceGroupMessage(1, (DevGroupMessageType) (DGR_MSGTYP_UPDATE_MORE_TO_COME), 748 | DGR_ITEM_LIGHT_CHANNELS, light_channels); 749 | } 750 | SendDeviceGroupMessage(1, (DevGroupMessageType) (DGR_MSGTYP_UPDATE), 751 | DGR_ITEM_LIGHT_BRI, (uint8_t)(brightness * 255)); 752 | } 753 | #endif 754 | break; 755 | } 756 | XdrvCall(FUNC_DEVICE_GROUP_ITEM); 757 | } 758 | item_flags = 0; 759 | } 760 | 761 | if (item_processed) { 762 | XdrvMailbox.command_code = DGR_ITEM_EOL; 763 | XdrvCall(FUNC_DEVICE_GROUP_ITEM); 764 | } 765 | } 766 | 767 | write_log: 768 | *log_ptr++ = 0; 769 | ESP_LOGD(TAG, "%s", log_buffer); 770 | 771 | // If this is a received status request message, then if the requestor didn't just ack our 772 | // previous full status update, send a full status update. 773 | if (received) { 774 | if ((flags & DGR_FLAG_STATUS_REQUEST)) { 775 | if ((flags & DGR_FLAG_RESET) || device_group_member->acked_sequence != device_group->last_full_status_sequence) { 776 | _SendDeviceGroupMessage(-device_group_index, DGR_MSGTYP_FULL_STATUS); 777 | } 778 | } 779 | } 780 | 781 | // If this is a message being sent, send it. 782 | else { 783 | int attempt; 784 | IPAddress ip_address = (device_group_member ? device_group_member->ip_address : IPAddress(DEVICE_GROUPS_ADDRESS)); 785 | for (attempt = 1; attempt <= 5; attempt++) { 786 | if (device_groups_udp.beginPacket(ip_address, DEVICE_GROUPS_PORT)) { 787 | device_groups_udp.write(message, message_length); 788 | if (device_groups_udp.endPacket()) 789 | break; 790 | } 791 | delay(10); 792 | } 793 | if (attempt > 5) { 794 | ESP_LOGE(TAG, "Error sending message"); 795 | } 796 | } 797 | goto cleanup; 798 | 799 | badmsg: 800 | ESP_LOGE(TAG, "%s ** incorrect length", log_buffer); 801 | 802 | cleanup: 803 | free(log_buffer); 804 | if (received) { 805 | TasmotaGlobal.skip_light_fade = false; 806 | ignore_dgr_sends = false; 807 | } 808 | } 809 | 810 | bool device_groups::_SendDeviceGroupMessage(int32_t device, DevGroupMessageType message_type, ...) { 811 | // If device groups is not up, ignore this request. 812 | if (!device_groups_up) 813 | return 1; 814 | 815 | // Extract the flags from the message type. 816 | bool with_local = ((message_type & DGR_MSGTYPFLAG_WITH_LOCAL) != 0); 817 | message_type = (DevGroupMessageType) (message_type & 0x7F); 818 | 819 | // If we're currently processing a remote device message, ignore this request. 820 | if (ignore_dgr_sends && message_type != DGR_MSGTYPE_UPDATE_COMMAND) 821 | return 0; 822 | 823 | // If device is < 0, the device group index is the device negated. If not, get the device group 824 | // index for this device. 825 | uint8_t device_group_index = -device; 826 | if (device > 0) { 827 | device_group_index = 0; 828 | if (Settings->flag4.multiple_device_groups) { // SetOption88 - Enable relays in separate device groups 829 | for (; device_group_index < device_group_count; device_group_index++) { 830 | if (Settings->device_group_tie[device_group_index] == device) 831 | break; 832 | } 833 | } 834 | } 835 | if (device_group_index >= device_group_count) 836 | return 0; 837 | 838 | // Get a pointer to the device information for this device. 839 | struct device_group *device_group = &device_groups_[device_group_index]; 840 | 841 | // If we're still sending initial status requests, ignore this request. 842 | if (device_group->initial_status_requests_remaining) 843 | return 1; 844 | 845 | // Load the message header, sequence and flags. 846 | #ifdef DEVICE_GROUPS_DEBUG 847 | ESP_LOGD(TAG, "Building %s %spacket", device_group->group_name, 848 | (message_type == DGR_MSGTYP_FULL_STATUS ? "full status " : "")); 849 | #endif // DEVICE_GROUPS_DEBUG 850 | uint16_t original_sequence = device_group->outgoing_sequence; 851 | uint16_t flags = 0; 852 | if (message_type == DGR_MSGTYP_UPDATE_MORE_TO_COME) 853 | flags = DGR_FLAG_MORE_TO_COME; 854 | else if (message_type == DGR_MSGTYP_UPDATE_DIRECT) 855 | flags = DGR_FLAG_DIRECT; 856 | uint8_t *message_ptr = BeginDeviceGroupMessage(device_group, flags, 857 | building_status_message || message_type == DGR_MSGTYP_PARTIAL_UPDATE); 858 | 859 | // A full status request is a request from a remote device for the status of every item we 860 | // control. As long as we're building it, we may as well multicast the status update to all 861 | // device group members. 862 | if (message_type == DGR_MSGTYP_FULL_STATUS) { 863 | device_group->last_full_status_sequence = device_group->outgoing_sequence; 864 | device_group->message_length = 0; 865 | 866 | // Set the flag indicating we're currently building a status message. SendDeviceGroupMessage 867 | // will build but not send messages while this flag is set. 868 | building_status_message = true; 869 | 870 | // Call the drivers to build the status update. 871 | power_t power = TasmotaGlobal.power; 872 | if (Settings->flag4.multiple_device_groups) { // SetOption88 - Enable relays in separate device groups 873 | power = (power >> (Settings->device_group_tie[device_group_index] - 1)) & 1; 874 | } 875 | SendDeviceGroupMessage(-device_group_index, DGR_MSGTYP_PARTIAL_UPDATE, DGR_ITEM_NO_STATUS_SHARE, 876 | device_group->no_status_share, DGR_ITEM_POWER, power); 877 | XdrvMailbox.index = 0; 878 | if (device_group_index == 0 && first_device_group_is_local) 879 | XdrvMailbox.index = DGR_FLAG_LOCAL; 880 | XdrvMailbox.command_code = DGR_ITEM_STATUS; 881 | XdrvMailbox.topic = (char *) &device_group_index; 882 | XdrvCall(FUNC_DEVICE_GROUP_ITEM); 883 | building_status_message = false; 884 | 885 | // Set the status update flag in the outgoing message. 886 | *(message_ptr - 2) |= DGR_FLAG_FULL_STATUS; 887 | 888 | // If we have nothing to share with the other members, just send the EOL item. 889 | if (!device_group->message_length) { 890 | *message_ptr++ = 0; 891 | device_group->message_length = message_ptr - device_group->message; 892 | } 893 | } 894 | 895 | else { 896 | #ifdef USE_DEVICE_GROUPS_SEND 897 | uint8_t out_buffer[128]; 898 | bool escaped; 899 | char chr; 900 | char oper; 901 | uint32_t old_value; 902 | uint8_t *out_ptr = out_buffer; 903 | #endif // USE_DEVICE_GROUPS_SEND 904 | struct item { 905 | uint8_t item; 906 | uint8_t flags; 907 | uint32_t value; 908 | void *value_ptr; 909 | } item_array[32]; 910 | bool shared; 911 | uint8_t item; 912 | uint32_t mask; 913 | uint32_t value = 0; 914 | uint8_t *value_ptr; 915 | uint8_t *first_item_ptr = message_ptr; 916 | struct item *item_ptr; 917 | va_list ap; 918 | 919 | // Build an array of all the items and values in this update. 920 | item_ptr = item_array; 921 | #ifdef USE_DEVICE_GROUPS_SEND 922 | if (message_type == DGR_MSGTYPE_UPDATE_COMMAND) { 923 | value_ptr = (uint8_t *) XdrvMailbox.data; 924 | while ((item = strtoul((char *) value_ptr, (char **) &value_ptr, 0))) { 925 | item_ptr->item = item; 926 | if (*value_ptr == '=') 927 | value_ptr++; 928 | 929 | // If flags were specified for this item, save them. 930 | item_ptr->flags = 0; 931 | if (toupper(*value_ptr) == 'N') { 932 | value_ptr++; 933 | item_ptr->flags = DGR_ITEM_FLAG_NO_SHARE; 934 | } 935 | 936 | if (item <= DGR_ITEM_MAX_32BIT) { 937 | oper = 0; 938 | if (*value_ptr == '@') { 939 | oper = value_ptr[1]; 940 | value_ptr += 2; 941 | } 942 | value = (isdigit(*value_ptr) ? strtoul((char *) value_ptr, (char **) &value_ptr, 0) 943 | : oper == '^' ? 0xffffffff 944 | : 1); 945 | if (oper) { 946 | old_value = (item <= DGR_ITEM_MAX_8BIT ? device_group->values_8bit[item] 947 | : (item <= DGR_ITEM_MAX_16BIT 948 | ? device_group->values_16bit[item - DGR_ITEM_MAX_8BIT - 1] 949 | : device_group->values_32bit[item - DGR_ITEM_MAX_16BIT - 1])); 950 | value = (oper == '+' ? old_value + value 951 | : oper == '-' ? old_value - value 952 | : oper == '^' ? old_value ^ value 953 | : oper == '|' ? old_value | value 954 | : old_value == '&' ? old_value & value 955 | : old_value); 956 | } 957 | item_ptr->value = value; 958 | 959 | if (item == DGR_ITEM_STATUS) { 960 | if (!(item_ptr->flags & DGR_ITEM_FLAG_NO_SHARE)) 961 | device_group->no_status_share = 0; 962 | _SendDeviceGroupMessage(-device_group_index, DGR_MSGTYP_FULL_STATUS); 963 | item_ptr--; 964 | } 965 | } else { 966 | item_ptr->value_ptr = out_ptr; 967 | if (item <= DGR_ITEM_MAX_STRING) { 968 | escaped = false; 969 | while ((chr = *value_ptr++)) { 970 | if (chr == ' ' && !escaped) 971 | break; 972 | if (!(escaped = (chr == '\\' && !escaped))) 973 | *out_ptr++ = chr; 974 | } 975 | *out_ptr++ = 0; 976 | } else { 977 | switch (item) { 978 | case DGR_ITEM_LIGHT_CHANNELS: { 979 | bool hex = false; 980 | char *endptr; 981 | if (*value_ptr == '#') { 982 | value_ptr++; 983 | hex = true; 984 | } 985 | for (int i = 0; i < 6; i++) { 986 | *out_ptr = 0; 987 | if (*value_ptr != ' ') { 988 | if (hex) { 989 | endptr = (char *) value_ptr + 2; 990 | chr = *endptr; 991 | *endptr = 0; 992 | *out_ptr = strtoul((char *) value_ptr, (char **) &value_ptr, 16); 993 | *endptr = chr; 994 | } else { 995 | *out_ptr = strtoul((char *) value_ptr, (char **) &value_ptr, 10); 996 | if (*value_ptr == ',') 997 | value_ptr++; 998 | } 999 | } 1000 | out_ptr++; 1001 | } 1002 | } break; 1003 | } 1004 | } 1005 | } 1006 | item_ptr++; 1007 | } 1008 | } else { 1009 | #endif // USE_DEVICE_GROUPS_SEND 1010 | va_start(ap, message_type); 1011 | while ((item = va_arg(ap, int))) { 1012 | item_ptr->item = item; 1013 | item_ptr->flags = 0; 1014 | if (item <= DGR_ITEM_MAX_32BIT) 1015 | item_ptr->value = va_arg(ap, int); 1016 | else if (item <= DGR_ITEM_MAX_STRING) 1017 | item_ptr->value_ptr = va_arg(ap, char *); 1018 | else { 1019 | item_ptr->value_ptr = va_arg(ap, uint8_t *); 1020 | } 1021 | item_ptr++; 1022 | } 1023 | va_end(ap); 1024 | #ifdef USE_DEVICE_GROUPS_SEND 1025 | } 1026 | #endif // USE_DEVICE_GROUPS_SEND 1027 | item_ptr->item = 0; 1028 | 1029 | // If we're still building this update or all group members haven't acknowledged the previous 1030 | // update yet, update the message to include these new updates. First we need to rebuild the 1031 | // previous update message to remove any items and their values that are included in this new 1032 | // update. 1033 | if (device_group->message_length) { 1034 | uint8_t item_flags = 0; 1035 | int kept_item_count = 0; 1036 | 1037 | // Rebuild the previous update message, removing any items whose values are included in this 1038 | // new update. 1039 | uint8_t *previous_message_ptr = message_ptr; 1040 | while ((item = *previous_message_ptr++)) { 1041 | // If this is the flags item, save the flags. 1042 | if (item == DGR_ITEM_FLAGS) { 1043 | item_flags = *previous_message_ptr++; 1044 | } 1045 | 1046 | // Otherwise, determine the length of this item's value. 1047 | else { 1048 | if (item <= DGR_ITEM_MAX_32BIT) { 1049 | value = 1; 1050 | if (item > DGR_ITEM_MAX_8BIT) { 1051 | value = 2; 1052 | if (item > DGR_ITEM_MAX_16BIT) { 1053 | value = 4; 1054 | } 1055 | } 1056 | } else { 1057 | value = *previous_message_ptr + 1; 1058 | } 1059 | 1060 | // Search for this item in the new update. 1061 | for (item_ptr = item_array; item_ptr->item; item_ptr++) { 1062 | if (item_ptr->item == item) 1063 | break; 1064 | } 1065 | 1066 | // If this item was not found in the new update, copy it to the new update message. If the 1067 | // item has flags, first copy the flags item to the new update message. 1068 | if (!item_ptr->item) { 1069 | kept_item_count++; 1070 | if (item_flags) { 1071 | *message_ptr++ = DGR_ITEM_FLAGS; 1072 | *message_ptr++ = item_flags; 1073 | } 1074 | *message_ptr++ = item; 1075 | memmove(message_ptr, previous_message_ptr, value); 1076 | message_ptr += value; 1077 | } 1078 | item_flags = 0; 1079 | } 1080 | 1081 | // Advance past the item value. 1082 | previous_message_ptr += value; 1083 | } 1084 | #ifdef DEVICE_GROUPS_DEBUG 1085 | ESP_LOGD(TAG, "%u items carried over", kept_item_count); 1086 | #endif // DEVICE_GROUPS_DEBUG 1087 | } 1088 | 1089 | // Itertate through the passed items adding them and their values to the message. 1090 | for (item_ptr = item_array; (item = item_ptr->item); item_ptr++) { 1091 | // If this item is shared with the group add it to the message. 1092 | shared = true; 1093 | if ((mask = DeviceGroupSharedMask(item))) { 1094 | if (item_ptr->flags & DGR_ITEM_FLAG_NO_SHARE) 1095 | device_group->no_status_share |= mask; 1096 | else if (!building_status_message) 1097 | device_group->no_status_share &= ~mask; 1098 | if (message_type != DGR_MSGTYPE_UPDATE_COMMAND) { 1099 | shared = (!(mask & device_group->no_status_share) && 1100 | (device_group_index || (mask & Settings->device_group_share_out))); 1101 | } 1102 | } 1103 | if (shared) { 1104 | if (item_ptr->flags) { 1105 | *message_ptr++ = DGR_ITEM_FLAGS; 1106 | *message_ptr++ = item_ptr->flags; 1107 | } 1108 | *message_ptr++ = item; 1109 | 1110 | // For integer items, add the value to the message. 1111 | if (item <= DGR_ITEM_MAX_32BIT) { 1112 | value = item_ptr->value; 1113 | *message_ptr++ = value & 0xff; 1114 | if (item > DGR_ITEM_MAX_8BIT) { 1115 | value >>= 8; 1116 | *message_ptr++ = value & 0xff; 1117 | if (item > DGR_ITEM_MAX_16BIT) { 1118 | value >>= 8; 1119 | *message_ptr++ = value & 0xff; 1120 | value >>= 8; 1121 | // For the power item, the device count is overlayed onto the highest 8 bits. 1122 | if (item == DGR_ITEM_POWER && !value) 1123 | value = 1124 | (!Settings->flag4.multiple_device_groups && device_group_index == 0 && first_device_group_is_local 1125 | ? TasmotaGlobal.devices_present 1126 | : 1); 1127 | *message_ptr++ = value; 1128 | } 1129 | } 1130 | } 1131 | 1132 | // For string items and special items, get the value length. 1133 | else { 1134 | if (item <= DGR_ITEM_MAX_STRING) { 1135 | value = strlen((const char *) item_ptr->value_ptr) + 1; 1136 | } else { 1137 | switch (item) { 1138 | case DGR_ITEM_LIGHT_CHANNELS: 1139 | value = 6; 1140 | break; 1141 | } 1142 | } 1143 | 1144 | // Load the length and copy the value. 1145 | *message_ptr++ = value; 1146 | memcpy(message_ptr, item_ptr->value_ptr, value); 1147 | message_ptr += value; 1148 | } 1149 | } 1150 | } 1151 | 1152 | // If we added any items, add the EOL item code and calculate the message length. 1153 | if (message_ptr != first_item_ptr) { 1154 | *message_ptr++ = 0; 1155 | device_group->message_length = message_ptr - device_group->message; 1156 | } 1157 | 1158 | // If there's going to be more items added to this message, return. 1159 | if (building_status_message || message_type == DGR_MSGTYP_PARTIAL_UPDATE) 1160 | return 0; 1161 | } 1162 | 1163 | // If there is no message, restore the sequence number and return. 1164 | if (!device_group->message_length) { 1165 | device_group->outgoing_sequence = original_sequence; 1166 | return 0; 1167 | } 1168 | 1169 | // Multicast the packet. 1170 | device_group->multicasts_remaining = DGR_MULTICAST_REPEAT_COUNT; 1171 | SendReceiveDeviceGroupMessage(device_group, nullptr, device_group->message, device_group->message_length, false); 1172 | 1173 | #ifdef USE_DEVICE_GROUPS_SEND 1174 | // If requested, handle this updated locally as well. 1175 | if (with_local) { 1176 | struct XDRVMAILBOX save_XdrvMailbox = XdrvMailbox; 1177 | SendReceiveDeviceGroupMessage(device_group, nullptr, device_group->message, device_group->message_length, true); 1178 | XdrvMailbox = save_XdrvMailbox; 1179 | } 1180 | #endif // USE_DEVICE_GROUPS_SEND 1181 | 1182 | uint32_t now = millis(); 1183 | if (message_type == DGR_MSGTYP_UPDATE_MORE_TO_COME) { 1184 | device_group->message_length = 0; 1185 | device_group->next_ack_check_time = 0; 1186 | } else { 1187 | device_group->ack_check_interval = DGR_ACK_WAIT_TIME; 1188 | device_group->next_ack_check_time = now + device_group->ack_check_interval; 1189 | if ((int32_t) (next_check_time - device_group->next_ack_check_time) > 0) 1190 | next_check_time = device_group->next_ack_check_time; 1191 | device_group->member_timeout_time = now + DGR_MEMBER_TIMEOUT; 1192 | } 1193 | 1194 | device_group->next_announcement_time = now + DGR_ANNOUNCEMENT_INTERVAL; 1195 | if ((int32_t) (next_check_time - device_group->next_announcement_time) > 0) 1196 | next_check_time = device_group->next_announcement_time; 1197 | return 0; 1198 | } 1199 | 1200 | ProcessGroupMessageResult device_groups::ProcessDeviceGroupMessage(multicast_packet packet) { 1201 | // Search for a device group with the target group name. If one isn't found, return. 1202 | uint8_t device_group_index = 0; 1203 | struct device_group *device_group = device_groups_; 1204 | char *message_group_name = (char *) packet.payload + sizeof(DEVICE_GROUP_MESSAGE) - 1; 1205 | for (;;) { 1206 | if (!strcmp(message_group_name, device_group->group_name)) 1207 | break; 1208 | if (++device_group_index >= device_group_count) 1209 | return PROCESS_GROUP_MESSAGE_UNMATCHED; 1210 | device_group++; 1211 | } 1212 | 1213 | // Find the group member. If this is a new group member, add it. 1214 | struct device_group_member *device_group_member; 1215 | struct device_group_member **flink = &device_group->device_group_members; 1216 | for (;;) { 1217 | device_group_member = *flink; 1218 | if (!device_group_member) { 1219 | device_group_member = (struct device_group_member *) calloc(1, sizeof(struct device_group_member)); 1220 | if (device_group_member == nullptr) { 1221 | ESP_LOGE(TAG, "Error allocating member block"); 1222 | return PROCESS_GROUP_MESSAGE_ERROR; 1223 | } 1224 | device_group_member->ip_address = packet.remoteIP; 1225 | device_group_member->acked_sequence = device_group->outgoing_sequence; 1226 | device_group->member_timeout_time = millis() + DGR_MEMBER_TIMEOUT; 1227 | *flink = device_group_member; 1228 | ESP_LOGD(TAG, "%s Member %s added", device_group->group_name, IPAddressToString(packet.remoteIP)); 1229 | break; 1230 | } else if (device_group_member->ip_address == packet.remoteIP) { 1231 | break; 1232 | } 1233 | flink = &device_group_member->flink; 1234 | } 1235 | 1236 | SendReceiveDeviceGroupMessage(device_group, device_group_member, packet.payload, packet.length, true); 1237 | return PROCESS_GROUP_MESSAGE_SUCCESS; 1238 | } 1239 | 1240 | void device_groups::DeviceGroupStatus(uint8_t device_group_index) { 1241 | if (Settings->flag4.device_groups_enabled && device_group_index < device_group_count) { 1242 | char buffer[1024]; 1243 | int member_count = 0; 1244 | struct device_group *device_group = &device_groups_[device_group_index]; 1245 | buffer[0] = buffer[1] = 0; 1246 | for (struct device_group_member *device_group_member = device_group->device_group_members; device_group_member; 1247 | device_group_member = device_group_member->flink) { 1248 | snprintf_P(buffer, sizeof(buffer), 1249 | PSTR("%s,{\"IPAddress\":\"%s\",\"ResendCount\":%u,\"LastRcvdSeq\":%u,\"LastAckedSeq\":%u}"), buffer, 1250 | IPAddressToString(device_group_member->ip_address), device_group_member->unicast_count, 1251 | device_group_member->received_sequence, device_group_member->acked_sequence); 1252 | member_count++; 1253 | } 1254 | ESP_LOGI(TAG, 1255 | "{\"" D_CMND_DEVGROUPSTATUS 1256 | "\":{\"Index\":%u,\"GroupName\":\"%s\",\"MessageSeq\":%u,\"MemberCount\":%d,\"Members\":[%s]}}", 1257 | device_group_index, device_group->group_name, device_group->outgoing_sequence, member_count, &buffer[1]); 1258 | } 1259 | } 1260 | 1261 | void device_groups::DeviceGroupsLoop(void) { 1262 | if (!device_groups_up || TasmotaGlobal.restart_flag) 1263 | return; 1264 | 1265 | #if defined(ESP8266) 1266 | while (device_groups_udp.parsePacket()) { 1267 | struct multicast_packet packet; 1268 | int length = device_groups_udp.read(packet.payload, sizeof(packet.payload) - 1); 1269 | if (length > 0) { 1270 | packet.id = packetId++; 1271 | packet.payload[length] = 0; 1272 | packet.length = length; 1273 | packet.remoteIP = device_groups_udp.remoteIP(); 1274 | received_packets.push_back(packet); 1275 | } 1276 | } 1277 | 1278 | for (multicast_packet packet : received_packets) { 1279 | std::string identifier(std::string(kDeviceGroupMessage) + this->device_group_name_ + '\0'); 1280 | if (!strncmp_P((char *) packet.payload, identifier.c_str(), identifier.length())) { 1281 | ProcessGroupMessageResult status = ProcessDeviceGroupMessage(packet); 1282 | if (status != PROCESS_GROUP_MESSAGE_UNMATCHED) { 1283 | received_packets.erase(std::remove_if(received_packets.begin(), received_packets.end(), 1284 | [&](multicast_packet const &mcp) { return mcp.id == packet.id; }), 1285 | received_packets.end()); 1286 | } 1287 | } else { 1288 | bool isRegistered = false; 1289 | for (std::string registered_group_name : registered_group_names) { 1290 | std::string identifier_registered(std::string(kDeviceGroupMessage) + registered_group_name + '\0'); 1291 | if (!strncmp_P((char *) packet.payload, identifier_registered.c_str(), identifier_registered.length())) { 1292 | isRegistered = true; 1293 | break; 1294 | } 1295 | } 1296 | if (!isRegistered) { 1297 | ESP_LOGVV(TAG, "Removing unregistered packet identifier, %s", packet.payload); 1298 | received_packets.erase(std::remove_if(received_packets.begin(), received_packets.end(), 1299 | [&](multicast_packet const &mcp) { return mcp.id == packet.id; }), 1300 | received_packets.end()); 1301 | } 1302 | } 1303 | } 1304 | #else 1305 | while (device_groups_udp.parsePacket()) { 1306 | struct multicast_packet packet; 1307 | int length = device_groups_udp.read(packet.payload, sizeof(packet.payload) - 1); 1308 | if (length > 0) { 1309 | packet.id = 0; // Not used. 1310 | packet.payload[length] = 0; 1311 | packet.length = length; 1312 | packet.remoteIP = device_groups_udp.remoteIP(); 1313 | if (!strncmp_P((char *)packet.payload, kDeviceGroupMessage, sizeof(DEVICE_GROUP_MESSAGE) - 1)) { 1314 | ProcessDeviceGroupMessage(packet); 1315 | } 1316 | } 1317 | } 1318 | #endif 1319 | 1320 | uint32_t now = millis(); 1321 | 1322 | // If it's time to check on things, iterate through the device groups. 1323 | if ((int32_t) (now - next_check_time) >= 0) { 1324 | #ifdef DEVICE_GROUPS_DEBUG 1325 | ESP_LOGD(TAG, "Checking next_check_time=%u, now=%u", next_check_time, now); 1326 | #endif // DEVICE_GROUPS_DEBUG 1327 | next_check_time = now + DGR_ANNOUNCEMENT_INTERVAL * 2; 1328 | 1329 | struct device_group *device_group = device_groups_; 1330 | for (uint32_t device_group_index = 0; device_group_index < device_group_count; 1331 | device_group_index++, device_group++) { 1332 | // If we're still waiting for acks to the last update from this device group, ... 1333 | if (device_group->next_ack_check_time) { 1334 | // If it's time to check for acks, ... 1335 | if ((int32_t) (now - device_group->next_ack_check_time) >= 0) { 1336 | // If we're still sending the initial status request message, send it. 1337 | if (device_group->initial_status_requests_remaining) { 1338 | if (--device_group->initial_status_requests_remaining) { 1339 | #ifdef DEVICE_GROUPS_DEBUG 1340 | ESP_LOGD(TAG, "Sending initial status request for group %s", device_group->group_name); 1341 | #endif // DEVICE_GROUPS_DEBUG 1342 | SendReceiveDeviceGroupMessage(device_group, nullptr, device_group->message, device_group->message_length, 1343 | false); 1344 | device_group->message[device_group->message_header_length + 2] = 1345 | DGR_FLAG_STATUS_REQUEST; // The reset flag is on only for the first packet - turn it off now 1346 | next_check_time = device_group->next_ack_check_time = now + 200; 1347 | continue; 1348 | } 1349 | 1350 | // If we've sent the initial status request message the set number of times, send our 1351 | // status to all the members. 1352 | else { 1353 | _SendDeviceGroupMessage(-device_group_index, DGR_MSGTYP_FULL_STATUS); 1354 | } 1355 | } 1356 | 1357 | // If we're done initializing, iterate through the group memebers, ... 1358 | else { 1359 | #ifdef DEVICE_GROUPS_DEBUG 1360 | ESP_LOGD(TAG, "Checking for %s ack's", device_group->group_name); 1361 | #endif // DEVICE_GROUPS_DEBUG 1362 | bool acked = true; 1363 | struct device_group_member **flink = &device_group->device_group_members; 1364 | struct device_group_member *device_group_member; 1365 | while ((device_group_member = *flink)) { 1366 | // If we have not received an ack to our last message from this member, ... 1367 | if (device_group_member->acked_sequence != device_group->outgoing_sequence) { 1368 | // If we haven't receive an ack from this member in DGR_MEMBER_TIMEOUT ms, assume 1369 | // they're offline and remove them from the group. 1370 | if ((int32_t) (now - device_group->member_timeout_time) >= 0) { 1371 | *flink = device_group_member->flink; 1372 | free(device_group_member); 1373 | ESP_LOGD(TAG, "%s Member %s removed", device_group->group_name, 1374 | IPAddressToString(device_group_member->ip_address)); 1375 | continue; 1376 | } 1377 | 1378 | // If we have more multicasts to do, multicast the packet to all members again; 1379 | // otherwise, unicast the message directly to this member. 1380 | if (device_group->multicasts_remaining) 1381 | device_group_member = nullptr; 1382 | SendReceiveDeviceGroupMessage(device_group, device_group_member, device_group->message, 1383 | device_group->message_length, false); 1384 | acked = false; 1385 | if (device_group->multicasts_remaining) { 1386 | device_group->multicasts_remaining--; 1387 | break; 1388 | } 1389 | device_group_member->unicast_count++; 1390 | } 1391 | flink = &device_group_member->flink; 1392 | } 1393 | 1394 | // If we've received an ack to the last message from all members, clear the ack check 1395 | // time and zero-out the message length. 1396 | if (acked) { 1397 | device_group->next_ack_check_time = 0; 1398 | device_group->message_length = 0; // Let _SendDeviceGroupMessage know we're done with this update 1399 | } 1400 | 1401 | // If there are still members we haven't received an ack from, set the next ack check 1402 | // time. We start at DGR_ACK_WAIT_TIME ms and add 100ms each pass with a maximum 1403 | // interval of 2 seconds. 1404 | else { 1405 | device_group->ack_check_interval += 100; 1406 | if (device_group->ack_check_interval > 2000) 1407 | device_group->ack_check_interval = 2000; 1408 | device_group->next_ack_check_time = now + device_group->ack_check_interval; 1409 | } 1410 | } 1411 | } 1412 | 1413 | if (device_group->next_ack_check_time && (int32_t) (next_check_time - device_group->next_ack_check_time) > 0) 1414 | next_check_time = device_group->next_ack_check_time; 1415 | } 1416 | 1417 | // If we're not still waiting for acks and it's time to send a multicast announcement for this 1418 | // group, send it. This is to announce ourself to any members that have somehow not heard 1419 | // about us. We send it at the announcement interval plus a random number of milliseconds so 1420 | // that even if all the devices booted at the same time, they don't all multicast their 1421 | // announcements at the same time. 1422 | else { 1423 | #ifdef DEVICE_GROUPS_DEBUG 1424 | ESP_LOGD(TAG, "next_announcement_time=%u, now=%u", device_group->next_announcement_time, now); 1425 | #endif // DEVICE_GROUPS_DEBUG 1426 | if ((int32_t) (now - device_group->next_announcement_time) >= 0) { 1427 | SendReceiveDeviceGroupMessage( 1428 | device_group, nullptr, device_group->message, 1429 | BeginDeviceGroupMessage(device_group, DGR_FLAG_ANNOUNCEMENT, true) - device_group->message, false); 1430 | device_group->next_announcement_time = now + DGR_ANNOUNCEMENT_INTERVAL + (random_uint32() % 10000); 1431 | } 1432 | if ((int32_t) (next_check_time - device_group->next_announcement_time) > 0) 1433 | next_check_time = device_group->next_announcement_time; 1434 | } 1435 | } 1436 | } 1437 | } 1438 | 1439 | bool device_groups::XdrvCall(uint8_t Function) { 1440 | bool result = true; 1441 | return result; 1442 | } 1443 | 1444 | void device_groups::ExecuteCommandPower(uint32_t device, uint32_t state, uint32_t source) { 1445 | power_t mask = 1 << (device - 1); // Device to control 1446 | power_t old_power = TasmotaGlobal.power; 1447 | if (state <= POWER_TOGGLE) { 1448 | switch (state) { 1449 | case POWER_OFF: { 1450 | TasmotaGlobal.power &= (POWER_MASK ^ mask); 1451 | break; 1452 | } 1453 | case POWER_ON: 1454 | TasmotaGlobal.power |= mask; 1455 | break; 1456 | case POWER_TOGGLE: 1457 | TasmotaGlobal.power ^= mask; 1458 | } 1459 | } 1460 | 1461 | if (TasmotaGlobal.power != old_power && SRC_REMOTE != source && SRC_RETRY != source) { 1462 | power_t dgr_power = TasmotaGlobal.power; 1463 | if (Settings->flag4.multiple_device_groups) { // SetOption88 - Enable relays in separate device groups 1464 | dgr_power = (dgr_power >> (device - 1)) & 1; 1465 | } 1466 | SendDeviceGroupMessage(device, DGR_MSGTYP_UPDATE, DGR_ITEM_POWER, dgr_power); 1467 | } 1468 | 1469 | if (dgr_state < DGR_STATE_INITIALIZED) { 1470 | return; 1471 | } 1472 | 1473 | if (SRC_REMOTE == source) { 1474 | #ifdef USE_SWITCH 1475 | for (switch_::Switch *obj : this->switches_) { 1476 | if (TasmotaGlobal.power > 0) { 1477 | obj->turn_on(); 1478 | } else { 1479 | obj->turn_off(); 1480 | } 1481 | } 1482 | #endif 1483 | #ifdef USE_LIGHT 1484 | for (light::LightState *obj : this->lights_) { 1485 | auto call = TasmotaGlobal.power > 0 ? obj->turn_on() : obj->turn_off(); 1486 | call.perform(); 1487 | } 1488 | #endif 1489 | } 1490 | } 1491 | 1492 | void device_groups::ExecuteCommand(const char *cmnd, uint32_t source) { return; } 1493 | 1494 | void device_groups::InitTasmotaCompatibility() { 1495 | Settings = (TSettings *) malloc(sizeof(TSettings)); 1496 | Settings->device_group_share_in = receive_mask_; 1497 | Settings->device_group_share_out = send_mask_; 1498 | Settings->flag4.device_groups_enabled = 1; 1499 | Settings->flag4.multiple_device_groups = 0; 1500 | } 1501 | 1502 | } // namespace device_groups 1503 | } // namespace esphome 1504 | --------------------------------------------------------------------------------