Skip to content

Commit d78a33e

Browse files
authored
Merge pull request #3340 from SmartThingsCommunity/bugfix/hue-button-migration
philips-hue: Keep a replaced bridge's devices off the new bridge
2 parents db6277e + 1b7ef8a commit d78a33e

19 files changed

Lines changed: 1042 additions & 152 deletions

‎drivers/SmartThings/philips-hue/src/disco/init.lua‎

Lines changed: 46 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -26,19 +26,56 @@ local DOMAIN = "local"
2626
---@class HueDiscovery
2727
---@field public api_keys table<string,string>
2828
---@field public disco_api_instances table<string,PhilipsHueApi>
29-
---@field public device_state_disco_cache table<string,table<string,any>>
29+
---@field public device_state_disco_cache_by_bridge table<string,table<string,table<string,any>>>
3030
---@field public ServiceType string
3131
---@field public Domain string
3232
---@field public discovery_active boolean
3333
local HueDiscovery = {
3434
api_keys = {},
3535
disco_api_instances = {},
36-
device_state_disco_cache = {},
36+
device_state_disco_cache_by_bridge = {},
3737
ServiceType = SERVICE_TYPE,
3838
Domain = DOMAIN,
3939
discovery_active = false
4040
}
4141

42+
--- The cached state of the devices on one bridge, keyed by Hue resource ID (and, for some device
43+
--- types, also by v1 ID), creating it if needed. The cache is kept per bridge because a Hue Bridge
44+
--- Pro keeps the resource IDs of the devices migrated to it, so two bridges can report state for the
45+
--- same resource ID, and a device must only ever be set up from its own bridge's state.
46+
---@param bridge_network_id string? the bridge's device network ID
47+
---@return table<string,table<string,any>>? cache nil if no bridge network ID was given
48+
function HueDiscovery.state_cache_for_bridge(bridge_network_id)
49+
if not bridge_network_id then return nil end
50+
local cache = HueDiscovery.device_state_disco_cache_by_bridge[bridge_network_id]
51+
if not cache then
52+
cache = {}
53+
HueDiscovery.device_state_disco_cache_by_bridge[bridge_network_id] = cache
54+
end
55+
return cache
56+
end
57+
58+
--- The state cache of the bridge a child device belongs to (see `state_cache_for_bridge`).
59+
---@param driver HueDriver
60+
---@param device HueDevice
61+
---@param parent_device_id string? the device's parent, if known, as for `utils.get_hue_bridge_for_device`
62+
---@return table<string,table<string,any>>? cache nil if the device's bridge isn't known
63+
function HueDiscovery.state_cache_for_device(driver, device, parent_device_id)
64+
local bridge = utils.get_hue_bridge_for_device(driver, device, parent_device_id, true)
65+
return bridge and HueDiscovery.state_cache_for_bridge(bridge.device_network_id)
66+
end
67+
68+
--- The cached state of resource `rid` on the bridge `device` belongs to.
69+
---@param driver HueDriver
70+
---@param device HueDevice
71+
---@param rid string?
72+
---@param parent_device_id string?
73+
---@return table<string,any>?
74+
function HueDiscovery.cached_state_for_device(driver, device, rid, parent_device_id)
75+
local cache = rid and HueDiscovery.state_cache_for_device(driver, device, parent_device_id)
76+
return cache and cache[rid]
77+
end
78+
4279
-- Lazy-load the discovered device handlers so we only load the code we need
4380
---@type table<string,DiscoveredChildDeviceHandler>
4481
local discovered_device_handlers = utils.lazy_handler_loader("disco")
@@ -251,7 +288,10 @@ function HueDiscovery.search_bridge_for_supported_devices(driver, bridge_network
251288
for _, device in ipairs(driver:get_devices()) do
252289
-- We're only interested in processing child/non-bridge devices here.
253290
if utils.is_bridge(driver, device) then goto continue end
254-
local not_known_to_bridge = device_is_joined_to_bridge[device:get_field(Fields.HUE_DEVICE_ID) or ""]
291+
-- A device without a Hue device ID has not completed `added` (or lost its stored fields), so
292+
-- there is nothing to compare against the bridge. Never delete a device on that basis.
293+
if not device:get_field(Fields.HUE_DEVICE_ID) then goto continue end
294+
local not_known_to_bridge = device_is_joined_to_bridge[device:get_field(Fields.HUE_DEVICE_ID)]
255295
local parent_device_id = device.parent_device_id or device:get_field(Fields.PARENT_DEVICE_ID) or ""
256296
local parent_bridge_device = utils.get_hue_bridge_for_device(driver, device, parent_device_id)
257297
local is_child_of_bridge = parent_bridge_device and (parent_bridge_device:get_field(Fields.BRIDGE_ID) == bridge_network_id)
@@ -357,7 +397,7 @@ function HueDiscovery.handle_discovered_child_device(driver, bridge_network_id,
357397
api_instance,
358398
primary_services,
359399
device_info,
360-
HueDiscovery.device_state_disco_cache,
400+
HueDiscovery.state_cache_for_bridge(bridge_network_id),
361401
driver.try_create_device
362402
)
363403
end
@@ -411,7 +451,7 @@ function HueDiscovery.do_mdns_scan(driver)
411451
(rest_err or "unexpected nil in error position")
412452
)
413453
)
414-
return
454+
goto continue
415455
end
416456
-- '-' and ':' or '::' are the accepted separators used for MAC address segments, so
417457
-- we strip thoes out and make the string uppercase
@@ -421,7 +461,7 @@ function HueDiscovery.do_mdns_scan(driver)
421461
"No MAC address in returned Bridge Info for IP %s.", ip_addr
422462
)
423463
)
424-
return
464+
goto continue
425465
end
426466

427467
bridge_info.ip = ip_addr

‎drivers/SmartThings/philips-hue/src/handlers/lifecycle_handlers/button.lua‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ function ButtonLifecycleHandlers.added(driver, device, parent_device_id, resourc
3535
return
3636
end
3737

38-
local button_info = Discovery.device_state_disco_cache[device_button_resource_id]
38+
local button_info = Discovery.cached_state_for_device(driver, device, device_button_resource_id)
3939
if not button_info then
4040
log.error(
4141
string.format(
@@ -120,6 +120,15 @@ function ButtonLifecycleHandlers.init(driver, device)
120120
hue_id_to_device[device_button_resource_id] = device
121121
end
122122

123+
if not hue_device_id then
124+
-- `added` hasn't completed for this device (e.g. its bridge isn't ready), so there is nothing
125+
-- to initialize yet. The stray device resolver will run `added` and `init` again later.
126+
log.warn(string.format(
127+
"Button %s has no Hue device ID, skipping init until it has been added", (device and device.label) or "unknown button"
128+
))
129+
return
130+
end
131+
123132
local maybe_idx_map = device:get_field(Fields.BUTTON_INDEX_MAP)
124133
local svc_rids_for_device = driver.services_for_device_rid[hue_device_id] or {}
125134

@@ -139,7 +148,7 @@ function ButtonLifecycleHandlers.init(driver, device)
139148
driver.services_for_device_rid[hue_device_id] = svc_rids_for_device
140149

141150
local button_info, err
142-
button_info = Discovery.device_state_disco_cache[device_button_resource_id]
151+
button_info = Discovery.cached_state_for_device(driver, device, device_button_resource_id)
143152
if not button_info then
144153
log.debug("no button info")
145154
local parent_bridge = utils.get_hue_bridge_for_device(
@@ -153,7 +162,7 @@ function ButtonLifecycleHandlers.init(driver, device)
153162
api_instance,
154163
hue_device_id,
155164
parent_bridge.device_network_id,
156-
Discovery.device_state_disco_cache
165+
Discovery.state_cache_for_bridge(parent_bridge.device_network_id)
157166
)
158167
if err then
159168
log.error(

‎drivers/SmartThings/philips-hue/src/handlers/lifecycle_handlers/contact.lua‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ function ContactLifecycleHandlers.added(driver, device, parent_device_id, resour
3535
return
3636
end
3737

38-
local sensor_info = Discovery.device_state_disco_cache[device_sensor_resource_id]
38+
local sensor_info = Discovery.cached_state_for_device(driver, device, device_sensor_resource_id)
3939
if not sensor_info then
4040
log.error(
4141
string.format(
@@ -78,12 +78,20 @@ function ContactLifecycleHandlers.init(driver, device)
7878
log.debug("resource id " .. tostring(device_sensor_resource_id))
7979

8080
local hue_device_id = device:get_field(Fields.HUE_DEVICE_ID)
81+
if not hue_device_id then
82+
-- `added` hasn't completed for this device (e.g. its bridge isn't ready), so there is nothing
83+
-- to initialize yet. The stray device resolver will run `added` and `init` again later.
84+
log.warn(string.format(
85+
"Contact Sensor %s has no Hue device ID, skipping init until it has been added", (device and device.label) or "unknown sensor"
86+
))
87+
return
88+
end
8189
local hue_id_to_device = utils.get_hue_id_to_device_table_by_bridge(driver, device) or {}
8290
if not hue_id_to_device[device_sensor_resource_id] then
8391
hue_id_to_device[device_sensor_resource_id] = device
8492
end
8593
local sensor_info, err
86-
sensor_info = Discovery.device_state_disco_cache[device_sensor_resource_id]
94+
sensor_info = Discovery.cached_state_for_device(driver, device, device_sensor_resource_id)
8795
if not sensor_info then
8896
log.debug("no sensor info")
8997
local parent_bridge = utils.get_hue_bridge_for_device(
@@ -97,7 +105,7 @@ function ContactLifecycleHandlers.init(driver, device)
97105
api_instance,
98106
hue_device_id,
99107
parent_bridge.device_network_id,
100-
Discovery.device_state_disco_cache
108+
Discovery.state_cache_for_bridge(parent_bridge.device_network_id)
101109
)
102110
if err then
103111
log.error(

‎drivers/SmartThings/philips-hue/src/handlers/lifecycle_handlers/init.lua‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,13 +98,16 @@ function LifecycleHandlers.device_added(driver, device, ...)
9898
hue_id_to_device[resource_id] = device
9999
end
100100

101-
local resource_state_known = (Discovery.device_state_disco_cache[resource_id] ~= nil)
102101
log.info(
103102
string.format("Querying device info for parent of %s", (device.label or device.id or "unknown device")))
104103

105104
local parent_bridge = utils.get_hue_bridge_for_device(
106105
driver, device, device.parent_device_id or device:get_field(Fields.PARENT_DEVICE_ID)
107106
)
107+
-- Only the device's own bridge's state counts: another bridge may report the same resource ID.
108+
local bridge_state_cache = parent_bridge and Discovery.state_cache_for_bridge(parent_bridge.device_network_id)
109+
local resource_state_known = (bridge_state_cache ~= nil and resource_id ~= nil
110+
and bridge_state_cache[resource_id] ~= nil)
108111

109112
local key = parent_bridge and parent_bridge:get_field(HueApi.APPLICATION_KEY_HEADER)
110113
local bridge_ip = parent_bridge and parent_bridge:get_field(Fields.IPV4)
@@ -188,6 +191,27 @@ function LifecycleHandlers.initialize_device(driver, device, event, _args, ...)
188191
"_ADDED for device %s not set while _initialize is handling %s, performing added lifecycle operations",
189192
(device.label or device.id or "unknown device"), event))
190193
LifecycleHandlers.device_added(driver, device, ...)
194+
195+
-- `added` can defer a child device (e.g. its bridge isn't ready, so it is queued as a "stray")
196+
-- without having recorded anything about it. Initializing a child in that state would act on
197+
-- fields that were never populated, so wait for the stray resolver to run `added` again.
198+
-- Devices that have a Hue device ID were added by an earlier driver run and still need `init`.
199+
-- Lights are exempt: their `init` copes with the missing fields, and a light's `added` can also
200+
-- fail (e.g. on a REST error) without queuing it for a retry, so deferring would leave it
201+
-- uninitialized.
202+
if not device:get_field(Fields._ADDED)
203+
and not device:get_field(Fields.HUE_DEVICE_ID)
204+
and not utils.is_bridge(driver, device)
205+
and utils.determine_device_type(device) ~= HueDeviceTypes.LIGHT
206+
then
207+
log.warn(
208+
string.format(
209+
"Device %s has not completed `added`, deferring init until it has been added",
210+
(device.label or device.id or "unknown device")
211+
)
212+
)
213+
return
214+
end
191215
end
192216

193217
if not device:get_field(Fields._INIT) then

‎drivers/SmartThings/philips-hue/src/handlers/lifecycle_handlers/light.lua‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,9 @@ function LightLifecycleHandlers.added(driver, device, parent_device_id, resource
3636
return
3737
end
3838

39-
local light_info_known = (Discovery.device_state_disco_cache[device_light_resource_id] ~= nil)
39+
-- The state cached for this light's own bridge (another bridge may report the same resource ID).
40+
local light_state_cache = Discovery.state_cache_for_device(driver, device, parent_device_id) or {}
41+
local light_info_known = (light_state_cache[device_light_resource_id] ~= nil)
4042
if not light_info_known then
4143
log.info(
4244
string.format("Querying device info for parent of %s", (device.label or device.id or "unknown device")))
@@ -88,7 +90,7 @@ function LightLifecycleHandlers.added(driver, device, parent_device_id, resource
8890

8991
local light_resource, err, _ = api_instance:get_light_by_id(device_light_resource_id)
9092
if err ~= nil or not light_resource then
91-
log.error_with({ hub_logs = true }, "Error getting light info: ", error)
93+
log.error_with({ hub_logs = true }, "Error getting light info: ", err)
9294
return
9395
end
9496

@@ -102,7 +104,7 @@ function LightLifecycleHandlers.added(driver, device, parent_device_id, resource
102104

103105
for _, light in ipairs(light_resource.data or {}) do
104106
if device_light_resource_id == light.id then
105-
Discovery.device_state_disco_cache[light.id] = {
107+
light_state_cache[light.id] = {
106108
hue_provided_name = light.metadata.name,
107109
id = light.id,
108110
on = light.on,
@@ -140,7 +142,7 @@ function LightLifecycleHandlers.added(driver, device, parent_device_id, resource
140142
end
141143

142144
---@type HueLightInfo
143-
local light_info = Discovery.device_state_disco_cache[device_light_resource_id]
145+
local light_info = light_state_cache[device_light_resource_id]
144146

145147
-- Remembering that mirek are reciprocal to kelvin, note the following:
146148
-- ** Minimum Mirek -> _Maximum_ Kelvin

‎drivers/SmartThings/philips-hue/src/handlers/lifecycle_handlers/motion.lua‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ function MotionLifecycleHandlers.added(driver, device, parent_device_id, resourc
3535
return
3636
end
3737

38-
local sensor_info = Discovery.device_state_disco_cache[device_sensor_resource_id]
38+
local sensor_info = Discovery.cached_state_for_device(driver, device, device_sensor_resource_id)
3939
if not sensor_info then
4040
log.error(
4141
string.format(
@@ -79,12 +79,20 @@ function MotionLifecycleHandlers.init(driver, device)
7979
log.debug("resource id " .. tostring(device_sensor_resource_id))
8080

8181
local hue_device_id = device:get_field(Fields.HUE_DEVICE_ID)
82+
if not hue_device_id then
83+
-- `added` hasn't completed for this device (e.g. its bridge isn't ready), so there is nothing
84+
-- to initialize yet. The stray device resolver will run `added` and `init` again later.
85+
log.warn(string.format(
86+
"Motion Sensor %s has no Hue device ID, skipping init until it has been added", (device and device.label) or "unknown sensor"
87+
))
88+
return
89+
end
8290
local hue_id_to_device = utils.get_hue_id_to_device_table_by_bridge(driver, device) or {}
8391
if not hue_id_to_device[device_sensor_resource_id] then
8492
hue_id_to_device[device_sensor_resource_id] = device
8593
end
8694
local sensor_info, err
87-
sensor_info = Discovery.device_state_disco_cache[device_sensor_resource_id]
95+
sensor_info = Discovery.cached_state_for_device(driver, device, device_sensor_resource_id)
8896
if not sensor_info then
8997
log.debug("no sensor info")
9098
local parent_bridge = utils.get_hue_bridge_for_device(
@@ -99,7 +107,7 @@ function MotionLifecycleHandlers.init(driver, device)
99107
api_instance,
100108
hue_device_id,
101109
parent_bridge.device_network_id,
102-
Discovery.device_state_disco_cache
110+
Discovery.state_cache_for_bridge(parent_bridge.device_network_id)
103111
)
104112
log.debug("--------------------- update all complete")
105113
if err then

‎drivers/SmartThings/philips-hue/src/handlers/migration_handlers/light.lua‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ st_utils.stringify_table = st_utils.stringify_table
77

88
local Discovery = require "disco"
99
local Fields = require "fields"
10+
local LightLifecycleHandlers = require "handlers.lifecycle_handlers.light"
1011
local StrayDeviceHelper = require "stray_device_helper"
1112

1213
local utils = require "utils"
@@ -18,8 +19,14 @@ local LightMigrationHandler = {}
1819
---@param device HueChildDevice
1920
---@param lifecycle_handlers LifecycleHandlers
2021
---@param parent_device_id string?
21-
---@param hue_light_description HueLightInfo?
22+
---@param hue_light_description HueLightInfo|string|nil the light's state, or its resource ID (as the
23+
--- stray resolver passes) to look its state up in the bridge's cache
2224
function LightMigrationHandler.migrate(driver, device, lifecycle_handlers, parent_device_id, hue_light_description)
25+
local light_rid = utils.get_hue_rid(device)
26+
if type(hue_light_description) ~= "table" then
27+
light_rid = type(hue_light_description) == "string" and hue_light_description or light_rid
28+
hue_light_description = nil
29+
end
2330
local api_key = device.data.username
2431
local v1_id = device.data.bulbId
2532
local bridge_id = driver.api_key_to_bridge_id[api_key]
@@ -43,7 +50,9 @@ function LightMigrationHandler.migrate(driver, device, lifecycle_handlers, paren
4350
local api_instance = (bridge_device and bridge_device:get_field(Fields.BRIDGE_API))
4451
or (bridge_device and Discovery.disco_api_instances[bridge_device.device_network_id])
4552
local light_resource = hue_light_description or
46-
Discovery.device_state_disco_cache[utils.get_hue_rid(device) or v1_id] --[[@as HueLightInfo]]
53+
(bridge_device and (Discovery.state_cache_for_bridge(bridge_device.device_network_id) or {})[
54+
light_rid or v1_id
55+
]) --[[@as HueLightInfo]]
4756

4857
if not (api_instance and bridge_device and bridge_device:get_field(Fields._INIT)
4958
and driver.joined_bridges[bridge_id] and light_resource) then
@@ -152,7 +161,9 @@ function LightMigrationHandler.migrate(driver, device, lifecycle_handlers, paren
152161
log.debug(string.format(
153162
"Re-requesting added handler for %s after migrating", (device.label or device.id or "unknown device")
154163
))
155-
lifecycle_handlers.device_added(driver, device, bridge_device.id, light_resource.id)
164+
-- The light's own `added`, not `lifecycle_handlers.device_added`: the device still looks like a
165+
-- DTH light (its DTH data remains), so that would send it back here.
166+
LightLifecycleHandlers.added(driver, device, bridge_device.id, light_resource.id)
156167
log.debug(string.format(
157168
"Re-requesting init handler for %s after migrating", (device.label or device.id or "unknown device")
158169
))

‎drivers/SmartThings/philips-hue/src/hue_debug/init.lua‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,8 @@ local function _setup_forced_strays(forced_stray_types)
8585
if device_rid and type_map[device_type] and not forced_devices[device.id] then
8686
_log(string.format("Forcing device [%s] as stray by removing its device state disco cache", device.label))
8787
forced_devices[device.id] = true
88-
Discovery.device_state_disco_cache[device_rid] = nil
88+
local cache = Discovery.state_cache_for_device(driver, device)
89+
if cache then cache[device_rid] = nil end
8990
added(driver, device, ...)
9091
end
9192
end

‎drivers/SmartThings/philips-hue/src/hue_driver_template.lua‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ local function _remove(driver, device)
3838
-- This operation will be committed to the datastore
3939
-- immediately, see the note in init.lua#L57
4040
Discovery.api_keys[device.device_network_id] = nil
41+
Discovery.device_state_disco_cache_by_bridge[device.device_network_id] = nil
4142
end
4243
end
4344

0 commit comments

Comments
 (0)