]> git.basschouten.com Git - openhab-addons.git/blob
3fbdf4310ff3dded15ab1230da90fcdcaae36aca
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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.digitalstrom.internal.handler;
14
15 import static org.openhab.binding.digitalstrom.internal.DigitalSTROMBindingConstants.BINDING_ID;
16
17 import java.util.ArrayList;
18 import java.util.Arrays;
19 import java.util.HashSet;
20 import java.util.List;
21 import java.util.Map;
22 import java.util.Set;
23
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;
56
57 /**
58  * The {@link ZoneTemperatureControlHandler} is responsible for handling the configuration, to load the supported
59  * channel of a
60  * digitalSTROM zone, which has a temperature control configured, and handling commands, which are sent to the channel.
61  * <br>
62  * <br>
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.
67  *
68  * @author Michael Ochel - Initial contribution
69  * @author Matthias Siegele - Initial contribution
70  */
71 public class ZoneTemperatureControlHandler extends BaseThingHandler implements TemperatureControlStatusListener {
72
73     /**
74      * Contains all supported thing types of this handler
75      */
76     public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = new HashSet<>(
77             Arrays.asList(DigitalSTROMBindingConstants.THING_TYPE_ZONE_TEMERATURE_CONTROL));
78
79     private final Logger logger = LoggerFactory.getLogger(ZoneTemperatureControlHandler.class);
80
81     private TemperatureControlSensorTransmitter temperatureSensorTransmitter;
82
83     private BridgeHandler dssBridgeHandler;
84     private Integer zoneID;
85     private String currentChannelID;
86     private Float currentValue = 0f;
87     private final Float step = 1f;
88
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;
93
94     /**
95      * Creates a new {@link ZoneTemperatureControlHandler}.
96      *
97      * @param thing must not be null
98      */
99     public ZoneTemperatureControlHandler(Thing thing) {
100         super(thing);
101     }
102
103     @Override
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());
110             } else {
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!");
114             }
115         } else {
116             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "zoneID is missing");
117         }
118     }
119
120     /**
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.
123      *
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
127      */
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;
131         }
132         if (bridge == null) {
133             return BRIDGE_IS_NULL;
134         }
135         String configZoneID = config.get(DigitalSTROMBindingConstants.ZONE_ID).toString();
136         int zoneID;
137         StructureManager strucMan = bridge.getStructureManager();
138         if (strucMan != null) {
139             try {
140                 zoneID = Integer.parseInt(configZoneID);
141                 if (!strucMan.checkZoneID(zoneID)) {
142                     zoneID = ZONE_ID_NOT_EXISTS;
143                 }
144             } catch (NumberFormatException e) {
145                 zoneID = strucMan.getZoneId(configZoneID);
146             }
147             return zoneID;
148         }
149         return ZONE_ID_NOT_EXISTS;
150     }
151
152     @Override
153     public void dispose() {
154         logger.debug("Handler disposed... unregister DeviceStatusListener");
155         if (zoneID != null) {
156             if (dssBridgeHandler != null) {
157                 dssBridgeHandler.unregisterTemperatureControlStatusListener(this);
158             }
159             temperatureSensorTransmitter = null;
160         }
161     }
162
163     @Override
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.");
171             } else {
172                 this.zoneID = tempZoneID;
173             }
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");
179                 } else {
180                     updateStatus(ThingStatus.ONLINE);
181                 }
182             } else {
183                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "No zoneID is set!");
184             }
185         }
186         if (bridgeStatusInfo.getStatus().equals(ThingStatus.OFFLINE)) {
187             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
188         }
189         logger.debug("Set status to {}", getThing().getStatusInfo());
190     }
191
192     @Override
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.");
197             return;
198         }
199         if (temperatureSensorTransmitter == null && zoneID != null) {
200             logger.debug(
201                     "Device not known on TemperationControlManager or temperatureSensorTransreciver is not registerd. Cannot handle command.");
202             return;
203         }
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);
211                     } else {
212                         sendCommandAndUpdateChannel(TemperatureControlSensorTransmitter.MAX_CONTROLL_VALUE);
213                     }
214                 } else {
215                     if (isTemperature()) {
216                         sendCommandAndUpdateChannel(0f);
217                     } else {
218                         sendCommandAndUpdateChannel(TemperatureControlSensorTransmitter.MIN_CONTROLL_VALUE);
219                     }
220                 }
221             } else if (command instanceof IncreaseDecreaseType) {
222                 if (IncreaseDecreaseType.INCREASE.equals(command)) {
223                     sendCommandAndUpdateChannel(currentValue + step);
224                 } else {
225                     sendCommandAndUpdateChannel(currentValue - step);
226                 }
227             }
228         } else {
229             logger.debug("Command sent to an unknown channel id: {}", channelUID);
230         }
231     }
232
233     private boolean isTemperature() {
234         return currentChannelID.contains(DsChannelTypeProvider.TEMPERATURE_CONTROLLED);
235     }
236
237     private void sendCommandAndUpdateChannel(Float newValue) {
238         if (isTemperature()) {
239             if (temperatureSensorTransmitter.pushTargetTemperature(zoneID, newValue)) {
240                 currentValue = newValue;
241                 updateState(currentChannelID, new DecimalType(newValue));
242             }
243         } else {
244             if (temperatureSensorTransmitter.pushControlValue(zoneID, newValue)) {
245                 currentValue = newValue;
246                 updateState(currentChannelID, new PercentType(newValue.intValue()));
247             }
248         }
249     }
250
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");
256                 return null;
257             }
258             ThingHandler handler = bridge.getHandler();
259
260             if (handler instanceof BridgeHandler) {
261                 dssBridgeHandler = (BridgeHandler) handler;
262             } else {
263                 return null;
264             }
265         }
266         return dssBridgeHandler;
267     }
268
269     @Override
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;
278                     loadChannel();
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>());
285                     loadChannel();
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>());
291                     loadChannel();
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.");
297                     }
298                 }
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);
304             }
305         } else {
306             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
307                     "digitalSTROM temperature control is for this zone not configured in.");
308         }
309     }
310
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());
318         }
319         ThingBuilder thingBuilder = editThing();
320         thingBuilder.withChannels(newChannelList);
321         updateThing(thingBuilder.build());
322         logger.debug("load channel: {} with item: {}", currentChannelID,
323                 DsChannelTypeProvider.getItemType(currentChannelID));
324     }
325
326     @Override
327     public synchronized void onTargetTemperatureChanged(Float newValue) {
328         if (isTemperature()) {
329             updateState(currentChannelID, new DecimalType(newValue));
330         }
331     }
332
333     @Override
334     public synchronized void onControlValueChanged(Integer newValue) {
335         if (!isTemperature()) {
336             updateState(currentChannelID, new PercentType(fixPercent(newValue)));
337         }
338     }
339
340     private int fixPercent(int value) {
341         return value < 0 ? 0 : value > 100 ? 100 : value;
342     }
343
344     @Override
345     public void registerTemperatureSensorTransmitter(
346             TemperatureControlSensorTransmitter temperatureSensorTransreciver) {
347         updateStatus(ThingStatus.ONLINE);
348         this.temperatureSensorTransmitter = temperatureSensorTransreciver;
349     }
350
351     @Override
352     public Integer getTemperationControlStatusListenrID() {
353         return zoneID;
354     }
355 }