]> git.basschouten.com Git - openhab-addons.git/blob
340f6a342be44b7a3b8c04ed60313d003b410938
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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.openwebnet.internal.handler;
14
15 import static org.openhab.binding.openwebnet.internal.OpenWebNetBindingConstants.CHANNEL_ACTUATORS;
16 import static org.openhab.binding.openwebnet.internal.OpenWebNetBindingConstants.CHANNEL_CONDITIONING_VALVES;
17 import static org.openhab.binding.openwebnet.internal.OpenWebNetBindingConstants.CHANNEL_CU_BATTERY_STATUS;
18 import static org.openhab.binding.openwebnet.internal.OpenWebNetBindingConstants.CHANNEL_CU_REMOTE_CONTROL;
19 import static org.openhab.binding.openwebnet.internal.OpenWebNetBindingConstants.CHANNEL_CU_SCENARIO_PROGRAM_NUMBER;
20 import static org.openhab.binding.openwebnet.internal.OpenWebNetBindingConstants.CHANNEL_CU_WEEKLY_PROGRAM_NUMBER;
21 import static org.openhab.binding.openwebnet.internal.OpenWebNetBindingConstants.CHANNEL_FAN_SPEED;
22 import static org.openhab.binding.openwebnet.internal.OpenWebNetBindingConstants.CHANNEL_FUNCTION;
23 import static org.openhab.binding.openwebnet.internal.OpenWebNetBindingConstants.CHANNEL_HEATING_VALVES;
24 import static org.openhab.binding.openwebnet.internal.OpenWebNetBindingConstants.CHANNEL_LOCAL_OFFSET;
25 import static org.openhab.binding.openwebnet.internal.OpenWebNetBindingConstants.CHANNEL_MODE;
26 import static org.openhab.binding.openwebnet.internal.OpenWebNetBindingConstants.CHANNEL_TEMPERATURE;
27 import static org.openhab.binding.openwebnet.internal.OpenWebNetBindingConstants.CHANNEL_TEMP_SETPOINT;
28
29 import java.util.Set;
30
31 import org.eclipse.jdt.annotation.NonNullByDefault;
32 import org.openhab.binding.openwebnet.internal.OpenWebNetBindingConstants;
33 import org.openhab.core.library.types.DecimalType;
34 import org.openhab.core.library.types.QuantityType;
35 import org.openhab.core.library.types.StringType;
36 import org.openhab.core.library.unit.SIUnits;
37 import org.openhab.core.thing.ChannelUID;
38 import org.openhab.core.thing.Thing;
39 import org.openhab.core.thing.ThingStatus;
40 import org.openhab.core.thing.ThingStatusDetail;
41 import org.openhab.core.thing.ThingStatusInfo;
42 import org.openhab.core.thing.ThingTypeUID;
43 import org.openhab.core.types.Command;
44 import org.openhab.core.types.UnDefType;
45 import org.openwebnet4j.communication.OWNException;
46 import org.openwebnet4j.message.BaseOpenMessage;
47 import org.openwebnet4j.message.FrameException;
48 import org.openwebnet4j.message.MalformedFrameException;
49 import org.openwebnet4j.message.Thermoregulation;
50 import org.openwebnet4j.message.Thermoregulation.WhatThermo;
51 import org.openwebnet4j.message.Where;
52 import org.openwebnet4j.message.WhereThermo;
53 import org.openwebnet4j.message.Who;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56
57 /**
58  * The {@link OpenWebNetThermoregulationHandler} is responsible for handling commands/messages for Thermoregulation
59  * Things. It extends the abstract {@link OpenWebNetThingHandler}.
60  *
61  * @author Massimo Valla - Initial contribution
62  * @author Andrea Conte - Thermoregulation
63  * @author Gilberto Cocchi - Thermoregulation
64  */
65 @NonNullByDefault
66 public class OpenWebNetThermoregulationHandler extends OpenWebNetThingHandler {
67
68     private final Logger logger = LoggerFactory.getLogger(OpenWebNetThermoregulationHandler.class);
69
70     public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = OpenWebNetBindingConstants.THERMOREGULATION_SUPPORTED_THING_TYPES;
71
72     private double currentSetPointTemp = 11.5d; // 11.5 is the default setTemp used in MyHomeUP mobile app
73
74     private Thermoregulation.Function currentFunction = Thermoregulation.Function.GENERIC;
75
76     private boolean isStandAlone = false;
77
78     private boolean isCentralUnit = false;
79
80     private String programNumber = "";
81
82     private static final String CU_REMOTE_CONTROL_ENABLED = "ENABLED";
83     private static final String CU_REMOTE_CONTROL_DISABLED = "DISABLED";
84     private static final String CU_BATTERY_OK = "OK";
85     private static final String CU_BATTERY_KO = "KO";
86
87     public OpenWebNetThermoregulationHandler(Thing thing) {
88         super(thing);
89     }
90
91     @Override
92     public void initialize() {
93         super.initialize();
94
95         ThingTypeUID thingType = thing.getThingTypeUID();
96         isCentralUnit = OpenWebNetBindingConstants.THING_TYPE_BUS_THERMO_CU.equals(thingType);
97
98         if (!isCentralUnit) {
99             Object standAloneConfig = getConfig().get(OpenWebNetBindingConstants.CONFIG_PROPERTY_STANDALONE);
100             if (standAloneConfig != null) {
101                 // null in case of thermo_sensor
102                 isStandAlone = Boolean.parseBoolean(standAloneConfig.toString());
103             }
104         } else {
105             // central unit must have WHERE=0
106             if (!deviceWhere.value().equals("0")) {
107                 logger.warn("initialize() Invalid WHERE={} for Central Unit.", deviceWhere.value());
108
109                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
110                         "@text/offline.conf-error-where");
111             }
112         }
113     }
114
115     @Override
116     public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
117         super.bridgeStatusChanged(bridgeStatusInfo);
118         // when the bridge is ONLINE request for thing states (temp, setTemp, fanSpeed...)
119         if (bridgeStatusInfo.getStatus().equals(ThingStatus.ONLINE)) {
120             refreshDevice(false);
121         }
122     }
123
124     @Override
125     protected void handleChannelCommand(ChannelUID channel, Command command) {
126         switch (channel.getId()) {
127             case CHANNEL_TEMP_SETPOINT:
128                 handleSetpoint(command);
129                 break;
130             case CHANNEL_FUNCTION:
131                 handleFunction(command);
132                 break;
133             case CHANNEL_MODE:
134                 handleMode(command);
135                 break;
136             case CHANNEL_FAN_SPEED:
137                 handleSetFanSpeed(command);
138                 break;
139             case CHANNEL_CU_WEEKLY_PROGRAM_NUMBER:
140             case CHANNEL_CU_SCENARIO_PROGRAM_NUMBER:
141                 handleSetProgramNumber(command);
142                 break;
143             default: {
144                 logger.warn("handleChannelCommand() Unsupported ChannelUID {}", channel.getId());
145             }
146         }
147     }
148
149     @Override
150     protected void requestChannelState(ChannelUID channel) {
151         super.requestChannelState(channel);
152         refreshDevice(false);
153     }
154
155     @Override
156     protected Where buildBusWhere(String wStr) throws IllegalArgumentException {
157         return new WhereThermo(wStr);
158     }
159
160     @Override
161     protected String ownIdPrefix() {
162         return Who.THERMOREGULATION.value().toString();
163     }
164
165     private void handleSetFanSpeed(Command command) {
166         if (command instanceof StringType) {
167             Where w = deviceWhere;
168             if (w != null) {
169                 try {
170                     Thermoregulation.FanCoilSpeed speed = Thermoregulation.FanCoilSpeed.valueOf(command.toString());
171                     send(Thermoregulation.requestWriteFanCoilSpeed(w.value(), speed));
172                 } catch (OWNException e) {
173                     logger.warn("handleSetFanSpeed() {}", e.getMessage());
174                 } catch (IllegalArgumentException e) {
175                     logger.warn("handleSetFanSpeed() Unsupported command {} for thing {}", command,
176                             getThing().getUID());
177                     return;
178                 }
179             }
180         } else {
181             logger.warn("handleSetFanSpeed() Unsupported command {} for thing {}", command, getThing().getUID());
182         }
183     }
184
185     private void handleSetProgramNumber(Command command) {
186         if (command instanceof DecimalType) {
187             if (!isCentralUnit) {
188                 logger.warn("handleSetProgramNumber() This command can be sent only for a Central Unit.");
189                 return;
190             }
191
192             programNumber = command.toString();
193             logger.debug("handleSetProgramNumber() Program number set to {}", programNumber);
194
195         } else {
196             logger.warn("handleSetProgramNumber() Unsupported command {} for thing {}", command, getThing().getUID());
197         }
198     }
199
200     private void handleSetpoint(Command command) {
201         if (command instanceof QuantityType || command instanceof DecimalType) {
202             Where w = deviceWhere;
203             if (w != null) {
204                 double newTemp = 0;
205                 if (command instanceof QuantityType) {
206                     QuantityType<?> tempCelsius = ((QuantityType<?>) command).toUnit(SIUnits.CELSIUS);
207                     if (tempCelsius != null) {
208                         newTemp = tempCelsius.doubleValue();
209                     }
210                 } else {
211                     newTemp = ((DecimalType) command).doubleValue();
212                 }
213                 try {
214                     send(Thermoregulation.requestWriteSetpointTemperature(getWhere(w.value()), newTemp,
215                             currentFunction));
216                 } catch (MalformedFrameException | OWNException e) {
217                     logger.warn("handleSetpoint() {}", e.getMessage());
218                 }
219             }
220         } else {
221             logger.warn("handleSetpoint() Unsupported command {} for thing {}", command, getThing().getUID());
222         }
223     }
224
225     private void handleMode(Command command) {
226         if (command instanceof StringType) {
227             Where w = deviceWhere;
228             if (w != null) {
229                 try {
230                     Thermoregulation.OperationMode new_mode = Thermoregulation.OperationMode.OFF;
231
232                     if (isCentralUnit && WhatThermo.isComplex(command.toString()))
233                         new_mode = Thermoregulation.OperationMode.valueOf(command.toString() + "_" + programNumber);
234                     else
235                         new_mode = Thermoregulation.OperationMode.valueOf(command.toString());
236
237                     send(Thermoregulation.requestWriteMode(getWhere(w.value()), new_mode, currentFunction,
238                             currentSetPointTemp));
239                 } catch (OWNException e) {
240                     logger.warn("handleMode() {}", e.getMessage());
241                 } catch (IllegalArgumentException e) {
242                     logger.warn("handleMode() Unsupported command {} for thing {}", command, getThing().getUID());
243                     return;
244                 }
245             }
246         } else {
247             logger.warn("handleMode() Unsupported command {} for thing {}", command, getThing().getUID());
248         }
249     }
250
251     private String getWhere(String where) {
252         if (isCentralUnit) {
253             return "#0";
254         } else {
255             return isStandAlone ? where : "#" + where;
256         }
257     }
258
259     private void handleFunction(Command command) {
260         if (command instanceof StringType) {
261             Where w = deviceWhere;
262             if (w != null) {
263                 try {
264                     Thermoregulation.Function function = Thermoregulation.Function.valueOf(command.toString());
265                     send(Thermoregulation.requestWriteFunction(w.value(), function));
266                 } catch (OWNException e) {
267                     logger.warn("handleFunction() {}", e.getMessage());
268                 } catch (IllegalArgumentException e) {
269                     logger.warn("handleFunction() Unsupported command {} for thing {}", command, getThing().getUID());
270                     return;
271                 }
272             }
273         } else {
274             logger.warn("handleFunction() Unsupported command {} for thing {}", command, getThing().getUID());
275         }
276     }
277
278     @Override
279     protected void handleMessage(BaseOpenMessage msg) {
280         super.handleMessage(msg);
281
282         if (isCentralUnit) {
283             if (msg.isCommand()) {
284                 updateModeAndFunction((Thermoregulation) msg);
285             }
286
287             if (msg.getWhat() == Thermoregulation.WhatThermo.REMOTE_CONTROL_DISABLED) {
288                 updateCURemoteControlStatus(CU_REMOTE_CONTROL_DISABLED);
289             } else if (msg.getWhat() == Thermoregulation.WhatThermo.REMOTE_CONTROL_ENABLED) {
290                 updateCURemoteControlStatus(CU_REMOTE_CONTROL_ENABLED);
291             } else if (msg.getWhat() == Thermoregulation.WhatThermo.BATTERY_KO) {
292                 updateCUBatteryStatus(CU_BATTERY_KO);
293             }
294
295             return;
296         }
297
298         if (msg.isCommand()) {
299             updateModeAndFunction((Thermoregulation) msg);
300         } else {
301             if (msg.getDim() == null) {
302                 return;
303             }
304             if (msg.getDim() == Thermoregulation.DimThermo.TEMPERATURE
305                     || msg.getDim() == Thermoregulation.DimThermo.PROBE_TEMPERATURE) {
306                 updateTemperature((Thermoregulation) msg);
307             } else if (msg.getDim() == Thermoregulation.DimThermo.TEMP_SETPOINT
308                     || msg.getDim() == Thermoregulation.DimThermo.COMPLETE_PROBE_STATUS) {
309                 updateSetpoint((Thermoregulation) msg);
310             } else if (msg.getDim() == Thermoregulation.DimThermo.VALVES_STATUS) {
311                 updateValveStatus((Thermoregulation) msg);
312             } else if (msg.getDim() == Thermoregulation.DimThermo.ACTUATOR_STATUS) {
313                 updateActuatorStatus((Thermoregulation) msg);
314             } else if (msg.getDim() == Thermoregulation.DimThermo.FAN_COIL_SPEED) {
315                 updateFanCoilSpeed((Thermoregulation) msg);
316             } else if (msg.getDim() == Thermoregulation.DimThermo.OFFSET) {
317                 updateLocalOffset((Thermoregulation) msg);
318             } else {
319                 logger.debug("handleMessage() Ignoring unsupported DIM {} for thing {}. Frame={}", msg.getDim(),
320                         getThing().getUID(), msg);
321             }
322         }
323     }
324
325     private void updateModeAndFunction(Thermoregulation tmsg) {
326         if (tmsg.getWhat() == null) {
327             logger.debug("updateModeAndFunction() Could not parse Mode or Function from {} (what is null)",
328                     tmsg.getFrameValue());
329             return;
330         }
331         Thermoregulation.WhatThermo w = Thermoregulation.WhatThermo.fromValue(tmsg.getWhat().value());
332
333         if (w.getMode() == null) {
334             logger.debug("updateModeAndFunction() Could not parse Mode from: {}", tmsg.getFrameValue());
335             return;
336         }
337         if (w.getFunction() == null) {
338             logger.debug("updateModeAndFunction() Could not parse Function from: {}", tmsg.getFrameValue());
339             return;
340         }
341
342         Thermoregulation.OperationMode mode = w.getMode();
343         Thermoregulation.Function function = w.getFunction();
344
345         updateState(CHANNEL_FUNCTION, new StringType(function.toString()));
346         updateState(CHANNEL_MODE, new StringType(mode.toString()));
347
348         // store current function
349         currentFunction = function;
350     }
351
352     private void updateTemperature(Thermoregulation tmsg) {
353         try {
354             double temp = Thermoregulation.parseTemperature(tmsg);
355             updateState(CHANNEL_TEMPERATURE, getAsQuantityTypeOrNull(temp, SIUnits.CELSIUS));
356         } catch (FrameException e) {
357             logger.warn("updateTemperature() FrameException on frame {}: {}", tmsg, e.getMessage());
358             updateState(CHANNEL_TEMPERATURE, UnDefType.UNDEF);
359         }
360     }
361
362     private void updateSetpoint(Thermoregulation tmsg) {
363         try {
364             double temp = Thermoregulation.parseTemperature(tmsg);
365             updateState(CHANNEL_TEMP_SETPOINT, getAsQuantityTypeOrNull(temp, SIUnits.CELSIUS));
366             currentSetPointTemp = temp;
367         } catch (FrameException e) {
368             logger.warn("updateSetpoint() FrameException on frame {}: {}", tmsg, e.getMessage());
369             updateState(CHANNEL_TEMP_SETPOINT, UnDefType.UNDEF);
370         }
371     }
372
373     private void updateFanCoilSpeed(Thermoregulation tmsg) {
374         try {
375             Thermoregulation.FanCoilSpeed speed = Thermoregulation.parseFanCoilSpeed(tmsg);
376             updateState(CHANNEL_FAN_SPEED, new StringType(speed.toString()));
377         } catch (FrameException e) {
378             logger.warn("updateFanCoilSpeed() FrameException on frame {}: {}", tmsg, e.getMessage());
379             updateState(CHANNEL_FAN_SPEED, UnDefType.UNDEF);
380         }
381     }
382
383     private void updateValveStatus(Thermoregulation tmsg) {
384         try {
385             Thermoregulation.ValveOrActuatorStatus cv = Thermoregulation.parseValveStatus(tmsg,
386                     Thermoregulation.WhatThermo.CONDITIONING);
387             updateState(CHANNEL_CONDITIONING_VALVES, new StringType(cv.toString()));
388
389             Thermoregulation.ValveOrActuatorStatus hv = Thermoregulation.parseValveStatus(tmsg,
390                     Thermoregulation.WhatThermo.HEATING);
391             updateState(CHANNEL_HEATING_VALVES, new StringType(hv.toString()));
392         } catch (FrameException e) {
393             logger.warn("updateValveStatus() FrameException on frame {}: {}", tmsg, e.getMessage());
394             updateState(CHANNEL_CONDITIONING_VALVES, UnDefType.UNDEF);
395             updateState(CHANNEL_HEATING_VALVES, UnDefType.UNDEF);
396         }
397     }
398
399     private void updateActuatorStatus(Thermoregulation tmsg) {
400         try {
401             Thermoregulation.ValveOrActuatorStatus hv = Thermoregulation.parseActuatorStatus(tmsg);
402             updateState(CHANNEL_ACTUATORS, new StringType(hv.toString()));
403         } catch (FrameException e) {
404             logger.warn("updateActuatorStatus() FrameException on frame {}: {}", tmsg, e.getMessage());
405             updateState(CHANNEL_ACTUATORS, UnDefType.UNDEF);
406         }
407     }
408
409     private void updateLocalOffset(Thermoregulation tmsg) {
410         try {
411             Thermoregulation.LocalOffset offset = Thermoregulation.parseLocalOffset(tmsg);
412             updateState(CHANNEL_LOCAL_OFFSET, new StringType(offset.toString()));
413             logger.debug("updateLocalOffset() {}: {}", tmsg, offset.toString());
414
415         } catch (FrameException e) {
416             logger.warn("updateLocalOffset() FrameException on frame {}: {}", tmsg, e.getMessage());
417             updateState(CHANNEL_LOCAL_OFFSET, UnDefType.UNDEF);
418         }
419     }
420
421     private void updateCURemoteControlStatus(String status) {
422         updateState(CHANNEL_CU_REMOTE_CONTROL, new StringType(status));
423         logger.debug("updateCURemoteControlStatus(): {}", status);
424     }
425
426     private void updateCUBatteryStatus(String status) {
427         updateState(CHANNEL_CU_BATTERY_STATUS, new StringType(status));
428         logger.debug("updateCUBatteryStatus(): {}", status);
429     }
430
431     private Boolean channelExists(String channelID) {
432         return thing.getChannel("openwebnet:" + channelID) != null;
433     }
434
435     @Override
436     protected void refreshDevice(boolean refreshAll) {
437         logger.debug("--- refreshDevice() : refreshing SINGLE... ({})", thing.getUID());
438         if (isCentralUnit) {
439             // TODO: 4 zone central -> zone #0 CAN be also a zone with its temp.. with 99-zones central no!
440             // let's assume it's a 99 zone
441             try {
442                 // there isn't a message used for setting OK for battery status so let's assume
443                 // it's OK and then change to KO if according message is received
444                 updateCUBatteryStatus(CU_BATTERY_OK);
445                 send(Thermoregulation.requestStatus("#0"));
446             } catch (OWNException e) {
447                 logger.warn("refreshDevice() central unit returned OWNException {}", e.getMessage());
448             }
449
450             return;
451         }
452
453         if (deviceWhere != null) {
454
455             String w = deviceWhere.value();
456             try {
457                 send(Thermoregulation.requestTemperature(w));
458
459                 if (!((WhereThermo) deviceWhere).isProbe()) {
460                     // for bus_thermo_zone request also other single channels updates
461                     send(Thermoregulation.requestSetPointTemperature(w));
462                     send(Thermoregulation.requestMode(w));
463
464                     // refresh ONLY subscribed channels
465                     if (channelExists(CHANNEL_FAN_SPEED)) {
466                         send(Thermoregulation.requestFanCoilSpeed(w));
467                     }
468
469                     if (channelExists(CHANNEL_CONDITIONING_VALVES) || channelExists(CHANNEL_HEATING_VALVES)) {
470                         send(Thermoregulation.requestValvesStatus(w));
471                     }
472
473                     if (channelExists(CHANNEL_ACTUATORS)) {
474                         send(Thermoregulation.requestActuatorsStatus(w));
475                     }
476
477                     if (channelExists(CHANNEL_LOCAL_OFFSET)) {
478                         send(Thermoregulation.requestLocalOffset(w));
479                     }
480                 }
481             } catch (OWNException e) {
482                 logger.warn("refreshDevice() where='{}' returned OWNException {}", w, e.getMessage());
483             }
484         }
485     }
486 }