2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.digitalstrom.internal.handler;
15 import static org.openhab.binding.digitalstrom.internal.DigitalSTROMBindingConstants.BINDING_ID;
17 import java.util.ArrayList;
18 import java.util.Arrays;
19 import java.util.HashSet;
20 import java.util.List;
24 import org.openhab.binding.digitalstrom.internal.DigitalSTROMBindingConstants;
25 import org.openhab.binding.digitalstrom.internal.lib.climate.TemperatureControlSensorTransmitter;
26 import org.openhab.binding.digitalstrom.internal.lib.climate.constants.ControlModes;
27 import org.openhab.binding.digitalstrom.internal.lib.climate.constants.ControlStates;
28 import org.openhab.binding.digitalstrom.internal.lib.climate.jsonresponsecontainer.impl.TemperatureControlStatus;
29 import org.openhab.binding.digitalstrom.internal.lib.listener.TemperatureControlStatusListener;
30 import org.openhab.binding.digitalstrom.internal.lib.manager.StructureManager;
31 import org.openhab.binding.digitalstrom.internal.lib.structure.devices.deviceparameters.constants.ApplicationGroup;
32 import org.openhab.binding.digitalstrom.internal.lib.structure.devices.deviceparameters.constants.OutputChannelEnum;
33 import org.openhab.binding.digitalstrom.internal.lib.structure.devices.deviceparameters.constants.OutputModeEnum;
34 import org.openhab.binding.digitalstrom.internal.providers.DsChannelTypeProvider;
35 import org.openhab.core.config.core.Configuration;
36 import org.openhab.core.library.types.DecimalType;
37 import org.openhab.core.library.types.IncreaseDecreaseType;
38 import org.openhab.core.library.types.OnOffType;
39 import org.openhab.core.library.types.PercentType;
40 import org.openhab.core.thing.Bridge;
41 import org.openhab.core.thing.Channel;
42 import org.openhab.core.thing.ChannelUID;
43 import org.openhab.core.thing.Thing;
44 import org.openhab.core.thing.ThingStatus;
45 import org.openhab.core.thing.ThingStatusDetail;
46 import org.openhab.core.thing.ThingStatusInfo;
47 import org.openhab.core.thing.ThingTypeUID;
48 import org.openhab.core.thing.binding.BaseThingHandler;
49 import org.openhab.core.thing.binding.ThingHandler;
50 import org.openhab.core.thing.binding.builder.ChannelBuilder;
51 import org.openhab.core.thing.binding.builder.ThingBuilder;
52 import org.openhab.core.thing.type.ChannelTypeUID;
53 import org.openhab.core.types.Command;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
58 * The {@link ZoneTemperatureControlHandler} is responsible for handling the configuration, to load the supported
60 * digitalSTROM zone, which has a temperature control configured, and handling commands, which are sent to the channel.
63 * For that it uses the {@link BridgeHandler} to register itself as {@link TemperatureControlStatusListener} at the
64 * {@link TemperatureControlManager} to get informed by status changes. Through the registration as
65 * {@link TemperatureControlStatusListener} a {@link TemperatureControlSensorTransmitter} will be registered to this
66 * {@link ZoneTemperatureControlHandler}, which is needed to set the temperature or the control value of a zone.
68 * @author Michael Ochel - Initial contribution
69 * @author Matthias Siegele - Initial contribution
71 public class ZoneTemperatureControlHandler extends BaseThingHandler implements TemperatureControlStatusListener {
74 * Contains all supported thing types of this handler
76 public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = new HashSet<>(
77 Arrays.asList(DigitalSTROMBindingConstants.THING_TYPE_ZONE_TEMERATURE_CONTROL));
79 private final Logger logger = LoggerFactory.getLogger(ZoneTemperatureControlHandler.class);
81 private TemperatureControlSensorTransmitter temperatureSensorTransmitter;
83 private BridgeHandler dssBridgeHandler;
84 private Integer zoneID;
85 private String currentChannelID;
86 private Float currentValue = 0f;
87 private final Float step = 1f;
89 // check zoneID error codes
90 public static final int ZONE_ID_NOT_EXISTS = -1;
91 public static final int ZONE_ID_NOT_SET = -2;
92 public static final int BRIDGE_IS_NULL = -3;
95 * Creates a new {@link ZoneTemperatureControlHandler}.
97 * @param thing must not be null
99 public ZoneTemperatureControlHandler(Thing thing) {
104 public void initialize() {
105 logger.debug("Initializing DeviceHandler.");
106 if (getConfig().get(DigitalSTROMBindingConstants.ZONE_ID) != null) {
107 final Bridge bridge = getBridge();
108 if (bridge != null) {
109 bridgeStatusChanged(bridge.getStatusInfo());
111 // Set status to OFFLINE, if no bridge is available e.g. because the bridge has been removed and the
112 // Thing was reinitialized.
113 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE, "Bridge is missing!");
116 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "zoneID is missing");
121 * Returns the configured zoneID of the given {@link Configuration}. If the zoneID does't exist or can't be checked
122 * {@link #ZONE_ID_NOT_EXISTS}, {@link #ZONE_ID_NOT_SET} or {@link #BRIDGE_IS_NULL} will be returned.
124 * @param config the {@link Configuration} to be checked
125 * @param bridge the responsible {@link BridgeHandler}
126 * @return zoneID the existing dS zoneID or an error constant
128 public static int getZoneID(Configuration config, BridgeHandler bridge) {
129 if (config == null || config.get(DigitalSTROMBindingConstants.ZONE_ID) == null) {
130 return ZONE_ID_NOT_SET;
132 if (bridge == null) {
133 return BRIDGE_IS_NULL;
135 String configZoneID = config.get(DigitalSTROMBindingConstants.ZONE_ID).toString();
137 StructureManager strucMan = bridge.getStructureManager();
138 if (strucMan != null) {
140 zoneID = Integer.parseInt(configZoneID);
141 if (!strucMan.checkZoneID(zoneID)) {
142 zoneID = ZONE_ID_NOT_EXISTS;
144 } catch (NumberFormatException e) {
145 zoneID = strucMan.getZoneId(configZoneID);
149 return ZONE_ID_NOT_EXISTS;
153 public void dispose() {
154 logger.debug("Handler disposed... unregister DeviceStatusListener");
155 if (zoneID != null) {
156 if (dssBridgeHandler != null) {
157 dssBridgeHandler.unregisterTemperatureControlStatusListener(this);
159 temperatureSensorTransmitter = null;
164 public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
165 if (bridgeStatusInfo.getStatus().equals(ThingStatus.ONLINE)) {
166 int tempZoneID = getZoneID(getConfig(), getDssBridgeHandler());
167 if (tempZoneID == ZONE_ID_NOT_EXISTS) {
168 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
169 "Configured zone '" + getConfig().get(DigitalSTROMBindingConstants.ZONE_ID)
170 + "' does not exist, please check the configuration.");
172 this.zoneID = tempZoneID;
174 if (zoneID != null) {
175 if (getDssBridgeHandler() != null && temperatureSensorTransmitter == null) {
176 dssBridgeHandler.registerTemperatureControlStatusListener(this);
177 updateStatus(ThingStatus.ONLINE, ThingStatusDetail.CONFIGURATION_PENDING,
178 "waiting for listener registration");
180 updateStatus(ThingStatus.ONLINE);
183 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "No zoneID is set!");
186 if (bridgeStatusInfo.getStatus().equals(ThingStatus.OFFLINE)) {
187 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
189 logger.debug("Set status to {}", getThing().getStatusInfo());
193 public void handleCommand(ChannelUID channelUID, Command command) {
194 BridgeHandler dssBridgeHandler = getDssBridgeHandler();
195 if (dssBridgeHandler == null) {
196 logger.debug("BridgeHandler not found. Cannot handle command without bridge.");
199 if (temperatureSensorTransmitter == null && zoneID != null) {
201 "Device not known on TemperationControlManager or temperatureSensorTransreciver is not registerd. Cannot handle command.");
204 if (channelUID.getId().equals(currentChannelID)) {
205 if (command instanceof PercentType || command instanceof DecimalType) {
206 sendCommandAndUpdateChannel(((DecimalType) command).floatValue());
207 } else if (command instanceof OnOffType) {
208 if (OnOffType.ON.equals(command)) {
209 if (isTemperature()) {
210 sendCommandAndUpdateChannel(TemperatureControlSensorTransmitter.MAX_TEMP);
212 sendCommandAndUpdateChannel(TemperatureControlSensorTransmitter.MAX_CONTROLL_VALUE);
215 if (isTemperature()) {
216 sendCommandAndUpdateChannel(0f);
218 sendCommandAndUpdateChannel(TemperatureControlSensorTransmitter.MIN_CONTROLL_VALUE);
221 } else if (command instanceof IncreaseDecreaseType) {
222 if (IncreaseDecreaseType.INCREASE.equals(command)) {
223 sendCommandAndUpdateChannel(currentValue + step);
225 sendCommandAndUpdateChannel(currentValue - step);
229 logger.debug("Command sent to an unknown channel id: {}", channelUID);
233 private boolean isTemperature() {
234 return currentChannelID.contains(DsChannelTypeProvider.TEMPERATURE_CONTROLLED);
237 private void sendCommandAndUpdateChannel(Float newValue) {
238 if (isTemperature()) {
239 if (temperatureSensorTransmitter.pushTargetTemperature(zoneID, newValue)) {
240 currentValue = newValue;
241 updateState(currentChannelID, new DecimalType(newValue));
244 if (temperatureSensorTransmitter.pushControlValue(zoneID, newValue)) {
245 currentValue = newValue;
246 updateState(currentChannelID, new PercentType(newValue.intValue()));
251 private synchronized BridgeHandler getDssBridgeHandler() {
252 if (this.dssBridgeHandler == null) {
253 Bridge bridge = getBridge();
254 if (bridge == null) {
255 logger.debug("Bride cannot be found");
258 ThingHandler handler = bridge.getHandler();
260 if (handler instanceof BridgeHandler) {
261 dssBridgeHandler = (BridgeHandler) handler;
266 return dssBridgeHandler;
270 public synchronized void configChanged(TemperatureControlStatus tempControlStatus) {
271 if (tempControlStatus != null && tempControlStatus.isNotSetOff()) {
272 ControlModes controlMode = ControlModes.getControlMode(tempControlStatus.getControlMode());
273 ControlStates controlState = ControlStates.getControlState(tempControlStatus.getControlState());
274 if (controlMode != null && controlState != null) {
275 logger.debug("config changed: {}", tempControlStatus.toString());
276 if (controlMode.equals(ControlModes.OFF) && currentChannelID != null) {
277 currentChannelID = null;
279 } else if (controlMode.equals(ControlModes.PID_CONTROL)
280 && (currentChannelID == null
281 || !currentChannelID.contains(DsChannelTypeProvider.TEMPERATURE_CONTROLLED))
282 && !controlState.equals(ControlStates.EMERGENCY)) {
283 currentChannelID = DsChannelTypeProvider.getOutputChannelTypeID(ApplicationGroup.Color.BLUE,
284 OutputModeEnum.TEMPRETURE_PWM, new ArrayList<OutputChannelEnum>());
286 currentValue = tempControlStatus.getNominalValue();
287 updateState(currentChannelID, new DecimalType(currentValue.doubleValue()));
288 } else if (!controlMode.equals(ControlModes.PID_CONTROL) && !controlMode.equals(ControlModes.OFF)) {
289 currentChannelID = DsChannelTypeProvider.getOutputChannelTypeID(ApplicationGroup.Color.BLUE,
290 OutputModeEnum.HEATING_PWM, new ArrayList<OutputChannelEnum>());
292 currentValue = tempControlStatus.getControlValue();
293 updateState(currentChannelID, new PercentType(fixPercent(currentValue.intValue())));
294 if (controlState.equals(ControlStates.EMERGENCY)) {
295 updateStatus(ThingStatus.ONLINE, ThingStatusDetail.COMMUNICATION_ERROR,
296 "The communication with temperation sensor fails. Temperature control state emergency (temperature control though the control value) is active.");
299 Map<String, String> properties = editProperties();
300 properties.put("controlDSUID", tempControlStatus.getControlDSUID());
301 properties.put("controlMode", controlMode.getKey());
302 properties.put("controlState", controlState.getKey());
303 updateProperties(properties);
306 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
307 "digitalSTROM temperature control is for this zone not configured in.");
311 private synchronized void loadChannel() {
312 List<Channel> newChannelList = new ArrayList<>(1);
313 if (currentChannelID != null) {
314 newChannelList.add(ChannelBuilder
315 .create(new ChannelUID(this.getThing().getUID(), currentChannelID),
316 DsChannelTypeProvider.getItemType(currentChannelID))
317 .withType(new ChannelTypeUID(BINDING_ID, currentChannelID)).build());
319 ThingBuilder thingBuilder = editThing();
320 thingBuilder.withChannels(newChannelList);
321 updateThing(thingBuilder.build());
322 logger.debug("load channel: {} with item: {}", currentChannelID,
323 DsChannelTypeProvider.getItemType(currentChannelID));
327 public synchronized void onTargetTemperatureChanged(Float newValue) {
328 if (isTemperature()) {
329 updateState(currentChannelID, new DecimalType(newValue));
334 public synchronized void onControlValueChanged(Integer newValue) {
335 if (!isTemperature()) {
336 updateState(currentChannelID, new PercentType(fixPercent(newValue)));
340 private int fixPercent(int value) {
341 return value < 0 ? 0 : value > 100 ? 100 : value;
345 public void registerTemperatureSensorTransmitter(
346 TemperatureControlSensorTransmitter temperatureSensorTransreciver) {
347 updateStatus(ThingStatus.ONLINE);
348 this.temperatureSensorTransmitter = temperatureSensorTransreciver;
352 public Integer getTemperationControlStatusListenrID() {