|
| 1 | +/* |
| 2 | + * Copyright (c) 2010-2026 Contributors to the openHAB project |
| 3 | + * |
| 4 | + * See the NOTICE file(s) distributed with this work for additional |
| 5 | + * information. |
| 6 | + * |
| 7 | + * This program and the accompanying materials are made available under the |
| 8 | + * terms of the Eclipse Public License 2.0 which is available at |
| 9 | + * http://www.eclipse.org/legal/epl-2.0 |
| 10 | + * |
| 11 | + * SPDX-License-Identifier: EPL-2.0 |
| 12 | + */ |
| 13 | +package org.openhab.binding.dirigera.internal.handler.light; |
| 14 | + |
| 15 | +import static org.openhab.binding.dirigera.internal.interfaces.Model.*; |
| 16 | + |
| 17 | +import java.util.ArrayList; |
| 18 | +import java.util.Collections; |
| 19 | +import java.util.List; |
| 20 | +import java.util.Map; |
| 21 | +import java.util.concurrent.ConcurrentHashMap; |
| 22 | + |
| 23 | +import org.eclipse.jdt.annotation.NonNullByDefault; |
| 24 | +import org.json.JSONObject; |
| 25 | +import org.openhab.binding.dirigera.internal.DirigeraStateDescriptionProvider; |
| 26 | +import org.openhab.core.thing.Thing; |
| 27 | +import org.openhab.core.thing.ThingStatus; |
| 28 | +import org.openhab.core.thing.ThingStatusDetail; |
| 29 | +import org.slf4j.Logger; |
| 30 | +import org.slf4j.LoggerFactory; |
| 31 | + |
| 32 | +/** |
| 33 | + * {@link LightSetHandler} controls a DIRIGERA light set (multiple lights as one logical unit). |
| 34 | + * Commands are sent to the hub via the /devices/set/{id} endpoint instead of /devices/{id}. |
| 35 | + * All four light capabilities are supported: on/off, brightness, color temperature, and color. |
| 36 | + * |
| 37 | + * The handler registers under the set ID (config.id) as well as each member device ID so the |
| 38 | + * gateway routes websocket updates to handleUpdate for both set-level and member-level events. |
| 39 | + * The set is ONLINE if at least one member reports isReachable=true. |
| 40 | + * |
| 41 | + * @author Bernd Weymann - Initial contribution |
| 42 | + * @author Bernd Weymann - add device set handling |
| 43 | + */ |
| 44 | +@NonNullByDefault |
| 45 | +public class LightSetHandler extends ColorLightHandler { |
| 46 | + private final Logger logger = LoggerFactory.getLogger(LightSetHandler.class); |
| 47 | + |
| 48 | + /** |
| 49 | + * Tracks per-member reachability: memberId -> isReachable. |
| 50 | + * ConcurrentHashMap because handleUpdate() is called from the WebSocket thread |
| 51 | + * while initializeDevice() / dispose() run on the openHAB framework thread. |
| 52 | + */ |
| 53 | + private final Map<String, Boolean> memberReachability = new ConcurrentHashMap<>(); |
| 54 | + /** |
| 55 | + * Member device IDs belonging to this set. |
| 56 | + * Wrapped for thread-safety (see memberReachability note above). |
| 57 | + */ |
| 58 | + private final List<String> memberDeviceIds = Collections.synchronizedList(new ArrayList<>()); |
| 59 | + |
| 60 | + public LightSetHandler(Thing thing, Map<String, String> mapping, DirigeraStateDescriptionProvider stateProvider) { |
| 61 | + super(thing, mapping, stateProvider); |
| 62 | + super.setChildHandler(this); |
| 63 | + } |
| 64 | + |
| 65 | + @Override |
| 66 | + public void initializeDevice() { |
| 67 | + // 1) Get all member device IDs for this set from the model |
| 68 | + memberDeviceIds.clear(); |
| 69 | + memberDeviceIds.addAll(gateway().model().getMemberDeviceIds(config.id)); |
| 70 | + if (memberDeviceIds.isEmpty()) { |
| 71 | + logger.warn("DIRIGERA LIGHT_SET {} no member devices found for set id {}", thing.getLabel(), config.id); |
| 72 | + updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, |
| 73 | + "No member devices found for light set"); |
| 74 | + return; |
| 75 | + } |
| 76 | + if (customDebug) { |
| 77 | + logger.info("DIRIGERA LIGHT_SET {} member devices: {}", thing.getLabel(), memberDeviceIds); |
| 78 | + } |
| 79 | + |
| 80 | + // initialize all members as not reachable |
| 81 | + memberReachability.clear(); |
| 82 | + memberDeviceIds.forEach(id -> memberReachability.put(id, false)); |
| 83 | + |
| 84 | + updateProperties(); |
| 85 | + |
| 86 | + // 2) Initialize the set's own customName from the model so that subsequent member |
| 87 | + // updates (which carry the member's own customName) cannot overwrite it. |
| 88 | + // getPropertiesFor() returns a map with ATTRIBUTES_KEY_CUSTOM_NAME = set name for light sets. |
| 89 | + Object setName = gateway().model().getPropertiesFor(config.id).get(ATTRIBUTES_KEY_CUSTOM_NAME); |
| 90 | + if (setName instanceof String nameStr && !nameStr.isBlank()) { |
| 91 | + JSONObject nameInit = new JSONObject(); |
| 92 | + JSONObject attributes = new JSONObject(); |
| 93 | + attributes.put(ATTRIBUTES_KEY_CUSTOM_NAME, nameStr); |
| 94 | + nameInit.put(JSON_KEY_ATTRIBUTES, attributes); |
| 95 | + super.handleUpdate(nameInit); |
| 96 | + } |
| 97 | + |
| 98 | + // 3) Register under the set ID itself (for future set-level events from the hub) |
| 99 | + // and under each member device ID so the gateway routes member websocket updates. |
| 100 | + // registerDevice() does not throw checked exceptions; any gateway NPE is prevented |
| 101 | + // by the null-guard in BaseHandler.gateway(), so no try-catch is needed here. |
| 102 | + gateway().registerDevice(child, config.id); |
| 103 | + memberDeviceIds.forEach(memberId -> gateway().registerDevice(child, memberId)); |
| 104 | + |
| 105 | + // 4) Poll current state for each reachable member so the handler reaches ONLINE |
| 106 | + // immediately without waiting for the first websocket event. |
| 107 | + // Only call handleUpdate for reachable members — unreachable ones stay false in |
| 108 | + // memberReachability (initialized above) and must not overwrite channel state. |
| 109 | + for (String memberId : memberDeviceIds) { |
| 110 | + JSONObject deviceState = gateway().api().readDevice(memberId); |
| 111 | + if (deviceState.optBoolean(JSON_KEY_REACHABLE, false)) { |
| 112 | + handleUpdate(deviceState); |
| 113 | + } |
| 114 | + } |
| 115 | + |
| 116 | + // 5) If no member reported isReachable=true, go OFFLINE explicitly. |
| 117 | + // This covers the case where readDevice returned empty/error for all members. |
| 118 | + boolean anyReachable = memberReachability.values().stream().anyMatch(r -> r); |
| 119 | + if (!anyReachable) { |
| 120 | + updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, |
| 121 | + "@text/dirigera.device.status.not-reachable"); |
| 122 | + } |
| 123 | + } |
| 124 | + |
| 125 | + /** |
| 126 | + * Receives websocket updates from all registered member devices. |
| 127 | + * Aggregates isReachable across all members: ONLINE if at least one is reachable. |
| 128 | + * Delegates attribute updates (brightness, color, etc.) to the parent only when online. |
| 129 | + */ |
| 130 | + @Override |
| 131 | + public void handleUpdate(JSONObject update) { |
| 132 | + if (customDebug) { |
| 133 | + logger.info("DIRIGERA LIGHT_SET {} handleUpdate {}", thing.getLabel(), update); |
| 134 | + } |
| 135 | + JSONObject stripped = new JSONObject(update, update.keySet().toArray(new String[0])); |
| 136 | + |
| 137 | + // strip customName for each member update |
| 138 | + if (update.has(JSON_KEY_ATTRIBUTES)) { |
| 139 | + stripped.getJSONObject(JSON_KEY_ATTRIBUTES).remove(ATTRIBUTES_KEY_CUSTOM_NAME); |
| 140 | + } |
| 141 | + |
| 142 | + // handle reachable flag for deviceSet |
| 143 | + if (update.has(JSON_KEY_REACHABLE)) { |
| 144 | + // identify which member sent this update and track its reachability |
| 145 | + String sourceId = update.optString(JSON_KEY_DEVICE_ID, ""); |
| 146 | + if (memberReachability.containsKey(sourceId)) { |
| 147 | + memberReachability.put(sourceId, update.getBoolean(JSON_KEY_REACHABLE)); |
| 148 | + } |
| 149 | + |
| 150 | + boolean anyReachable = memberReachability.values().stream().anyMatch(r -> r); |
| 151 | + if (anyReachable) { |
| 152 | + online = true; |
| 153 | + updateStatus(ThingStatus.ONLINE); |
| 154 | + } else { |
| 155 | + online = false; |
| 156 | + updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, |
| 157 | + "@text/dirigera.device.status.not-reachable"); |
| 158 | + } |
| 159 | + |
| 160 | + // Strip isReachable so the parent handleUpdate does not override our status. |
| 161 | + // Shallow copy via keySet() avoids the expensive toString()/parse round-trip. |
| 162 | + stripped.remove(JSON_KEY_REACHABLE); |
| 163 | + // Also strip customName from member attributes: each member carries its own |
| 164 | + // device name, which must not overwrite the set name initialized in initializeDevice(). |
| 165 | + if (stripped.has(JSON_KEY_ATTRIBUTES)) { |
| 166 | + stripped.getJSONObject(JSON_KEY_ATTRIBUTES).remove(ATTRIBUTES_KEY_CUSTOM_NAME); |
| 167 | + } |
| 168 | + } |
| 169 | + super.handleUpdate(stripped); |
| 170 | + } |
| 171 | + |
| 172 | + /** |
| 173 | + * Unregister from all member device IDs on dispose. |
| 174 | + * The set ID (config.id) is unregistered by super.dispose(). |
| 175 | + * |
| 176 | + * Ordering rationale: member IDs are unregistered BEFORE super.dispose() so that |
| 177 | + * no further WebSocket events are routed to this handler while BaseHandler tears down. |
| 178 | + * super.dispose() is called last to ensure config.id is also unregistered cleanly. |
| 179 | + */ |
| 180 | + @Override |
| 181 | + public void dispose() { |
| 182 | + memberDeviceIds.forEach(memberId -> { |
| 183 | + try { |
| 184 | + gateway().unregisterDevice(child, memberId); |
| 185 | + } catch (Exception e) { |
| 186 | + logger.debug("DIRIGERA LIGHT_SET {} unregister {} failed: {}", thing.getLabel(), memberId, |
| 187 | + e.getMessage()); |
| 188 | + } |
| 189 | + }); |
| 190 | + memberDeviceIds.clear(); |
| 191 | + memberReachability.clear(); |
| 192 | + super.dispose(); |
| 193 | + } |
| 194 | + |
| 195 | + /** |
| 196 | + * Override sendAttributes to route all commands to /devices/set/{id}. |
| 197 | + */ |
| 198 | + @Override |
| 199 | + protected int sendAttributes(JSONObject attributes) { |
| 200 | + logger.trace("DIRIGERA LIGHT_SET {} sending set attributes {}", thing.getLabel(), attributes); |
| 201 | + return super.sendSetAttributes(attributes); |
| 202 | + } |
| 203 | +} |
0 commit comments