]> git.basschouten.com Git - openhab-addons.git/blob
98b330aae9b61dbee8c1546bdb5d10c8d2cffc92
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.km200.internal.handler;
14
15 import static org.openhab.binding.km200.internal.KM200BindingConstants.*;
16
17 import java.math.BigDecimal;
18 import java.math.RoundingMode;
19 import java.net.URI;
20 import java.net.URISyntaxException;
21 import java.util.ArrayList;
22 import java.util.Collections;
23 import java.util.HashMap;
24 import java.util.HashSet;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Set;
28 import java.util.stream.Collectors;
29 import java.util.stream.Stream;
30
31 import org.eclipse.jdt.annotation.NonNullByDefault;
32 import org.eclipse.jdt.annotation.Nullable;
33 import org.openhab.binding.km200.internal.KM200ChannelTypeProvider;
34 import org.openhab.binding.km200.internal.KM200ServiceObject;
35 import org.openhab.binding.km200.internal.KM200ThingType;
36 import org.openhab.binding.km200.internal.KM200Utils;
37 import org.openhab.core.library.CoreItemFactory;
38 import org.openhab.core.library.types.DateTimeType;
39 import org.openhab.core.library.types.DecimalType;
40 import org.openhab.core.library.types.OnOffType;
41 import org.openhab.core.library.types.StringType;
42 import org.openhab.core.thing.Bridge;
43 import org.openhab.core.thing.Channel;
44 import org.openhab.core.thing.ChannelUID;
45 import org.openhab.core.thing.Thing;
46 import org.openhab.core.thing.ThingStatus;
47 import org.openhab.core.thing.ThingStatusDetail;
48 import org.openhab.core.thing.ThingTypeUID;
49 import org.openhab.core.thing.binding.BaseThingHandler;
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.ChannelKind;
53 import org.openhab.core.thing.type.ChannelType;
54 import org.openhab.core.thing.type.ChannelTypeBuilder;
55 import org.openhab.core.thing.type.ChannelTypeUID;
56 import org.openhab.core.types.Command;
57 import org.openhab.core.types.RefreshType;
58 import org.openhab.core.types.StateDescriptionFragment;
59 import org.openhab.core.types.StateDescriptionFragmentBuilder;
60 import org.openhab.core.types.StateOption;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
63
64 /**
65  * The {@link KM200ThingHandler} is responsible for handling commands, which are
66  * sent to one of the channels.
67  *
68  * @author Markus Eckhardt - Initial contribution
69  */
70 @NonNullByDefault
71 public class KM200ThingHandler extends BaseThingHandler {
72
73     private final Logger logger = LoggerFactory.getLogger(KM200ThingHandler.class);
74
75     public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.unmodifiableSet(Stream
76             .of(THING_TYPE_DHW_CIRCUIT, THING_TYPE_HEATING_CIRCUIT, THING_TYPE_SOLAR_CIRCUIT, THING_TYPE_HEAT_SOURCE,
77                     THING_TYPE_SYSTEM_APPLIANCE, THING_TYPE_SYSTEM_HOLIDAYMODES, THING_TYPE_SYSTEM_SENSOR,
78                     THING_TYPE_GATEWAY, THING_TYPE_NOTIFICATION, THING_TYPE_SYSTEM, THING_TYPE_SYSTEMSTATES)
79             .collect(Collectors.toSet()));
80
81     private final KM200ChannelTypeProvider channelTypeProvider;
82
83     public KM200ThingHandler(Thing thing, KM200ChannelTypeProvider channelTypeProvider) {
84         super(thing);
85         this.channelTypeProvider = channelTypeProvider;
86     }
87
88     @Override
89     public void handleCommand(ChannelUID channelUID, Command command) {
90         Bridge bridge = this.getBridge();
91         if (bridge == null) {
92             return;
93         }
94         KM200GatewayHandler gateway = (KM200GatewayHandler) bridge.getHandler();
95         if (gateway == null) {
96             return;
97         }
98         Channel channel = getThing().getChannel(channelUID.getId());
99         if (null != channel) {
100             if (command instanceof DateTimeType || command instanceof DecimalType || command instanceof StringType
101                     || command instanceof OnOffType) {
102                 gateway.prepareMessage(this.getThing(), channel, command);
103             } else if (command instanceof RefreshType) {
104                 gateway.refreshChannel(channel);
105             } else {
106                 logger.warn("Unsupported Command: {} Class: {}", command.toFullString(), command.getClass());
107             }
108         }
109     }
110
111     /**
112      * Choose a tag for a channel
113      */
114     Set<String> checkTags(String unitOfMeasure, @Nullable Boolean readOnly) {
115         Set<String> tags = new HashSet<>();
116         if (unitOfMeasure.indexOf("°C") == 0 || unitOfMeasure.indexOf("K") == 0) {
117             if (null != readOnly) {
118                 if (readOnly) {
119                     tags.add("CurrentTemperature");
120                 } else {
121                     tags.add("TargetTemperature");
122                 }
123             }
124         }
125         return tags;
126     }
127
128     /**
129      * Choose a category for a channel
130      */
131     String checkCategory(String unitOfMeasure, String topCategory, @Nullable Boolean readOnly) {
132         String category = null;
133         if (unitOfMeasure.indexOf("°C") == 0 || unitOfMeasure.indexOf("K") == 0) {
134             if (null == readOnly) {
135                 category = topCategory;
136             } else {
137                 if (readOnly) {
138                     category = "Temperature";
139                 } else {
140                     category = "Heating";
141                 }
142             }
143         } else if (unitOfMeasure.indexOf("kW") == 0 || unitOfMeasure.indexOf("kWh") == 0) {
144             category = "Energy";
145         } else if (unitOfMeasure.indexOf("l/min") == 0 || unitOfMeasure.indexOf("l/h") == 0) {
146             category = "Flow";
147         } else if (unitOfMeasure.indexOf("Pascal") == 0 || unitOfMeasure.indexOf("bar") == 0) {
148             category = "Pressure";
149         } else if (unitOfMeasure.indexOf("rpm") == 0) {
150             category = "Flow";
151         } else if (unitOfMeasure.indexOf("mins") == 0 || unitOfMeasure.indexOf("minutes") == 0) {
152             category = "Time";
153         } else if (unitOfMeasure.indexOf("kg/l") == 0) {
154             category = "Oil";
155         } else if (unitOfMeasure.indexOf("%%") == 0) {
156             category = "Number";
157         } else {
158             category = topCategory;
159         }
160         return category;
161     }
162
163     /**
164      * Creates a new channel
165      */
166     @Nullable
167     Channel createChannel(ChannelTypeUID channelTypeUID, ChannelUID channelUID, String root, String type,
168             @Nullable String currentPathName, String description, String label, boolean addProperties,
169             boolean switchProgram, StateDescriptionFragment state, String unitOfMeasure) {
170         URI configDescriptionUriChannel = null;
171         Channel newChannel = null;
172         ChannelType channelType = null;
173         Map<String, String> chProperties = new HashMap<>();
174         String itemType = "";
175         String category = null;
176         if (CoreItemFactory.NUMBER.equals(type)) {
177             itemType = "NumberType";
178             category = "Number";
179         } else if (CoreItemFactory.STRING.equals(type)) {
180             itemType = "StringType";
181             category = "Text";
182         } else {
183             logger.info("Channeltype {} not supported", type);
184             return null;
185         }
186         try {
187             configDescriptionUriChannel = new URI(CONFIG_DESCRIPTION_URI_CHANNEL);
188             channelType = ChannelTypeBuilder.state(channelTypeUID, label, itemType) //
189                     .withDescription(description) //
190                     .withCategory(checkCategory(unitOfMeasure, category, state.isReadOnly())) //
191                     .withTags(checkTags(unitOfMeasure, state.isReadOnly())) //
192                     .withStateDescription(state.toStateDescription()) //
193                     .withConfigDescriptionURI(configDescriptionUriChannel).build();
194         } catch (URISyntaxException ex) {
195             logger.warn("Can't create ConfigDescription URI '{}', ConfigDescription for channels not avilable!",
196                     CONFIG_DESCRIPTION_URI_CHANNEL);
197             channelType = ChannelTypeBuilder.state(channelTypeUID, label, itemType) //
198                     .withDescription(description) //
199                     .withCategory(checkCategory(unitOfMeasure, category, state.isReadOnly())) //
200                     .withTags(checkTags(unitOfMeasure, state.isReadOnly())).build();
201         }
202         channelTypeProvider.addChannelType(channelType);
203
204         chProperties.put("root", KM200Utils.translatesPathToName(root));
205         if (null != currentPathName && switchProgram) {
206             chProperties.put(SWITCH_PROGRAM_CURRENT_PATH_NAME, currentPathName);
207         }
208         if (addProperties) {
209             newChannel = ChannelBuilder.create(channelUID, type).withType(channelTypeUID).withDescription(description)
210                     .withLabel(label).withKind(ChannelKind.STATE).withProperties(chProperties).build();
211         } else {
212             newChannel = ChannelBuilder.create(channelUID, type).withType(channelTypeUID).withDescription(description)
213                     .withLabel(label).withKind(ChannelKind.STATE).build();
214         }
215         return newChannel;
216     }
217
218     @Override
219     public void initialize() {
220         Bridge bridge = this.getBridge();
221         if (bridge == null) {
222             logger.debug("Bridge not existing");
223             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
224             return;
225         }
226         logger.debug("initialize, Bridge: {}", bridge);
227         KM200GatewayHandler gateway = (KM200GatewayHandler) bridge.getHandler();
228         if (gateway == null) {
229             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
230             logger.debug("Gateway not existing: {}", bridge);
231             return;
232         }
233         String service = KM200Utils.translatesNameToPath(thing.getProperties().get("root"));
234         synchronized (gateway.getDevice()) {
235             updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING);
236             if (!gateway.getDevice().getInited()) {
237                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_UNINITIALIZED);
238                 logger.debug("Bridge: not initialized: {}", bridge);
239                 return;
240             }
241             List<Channel> subChannels = new ArrayList<>();
242             if (gateway.getDevice().containsService(service)) {
243                 KM200ServiceObject serObj = gateway.getDevice().getServiceObject(service);
244                 if (null != serObj) {
245                     addChannels(serObj, thing, subChannels, "");
246                 }
247             } else if (service.contains(SWITCH_PROGRAM_PATH_NAME)) {
248                 String currentPathName = thing.getProperties().get(SWITCH_PROGRAM_CURRENT_PATH_NAME);
249                 StateDescriptionFragment state = StateDescriptionFragmentBuilder.create().withPattern("%s")
250                         .withOptions(KM200SwitchProgramServiceHandler.daysList).build();
251                 Channel newChannel = createChannel(new ChannelTypeUID(thing.getUID().getAsString() + ":" + "weekday"),
252                         new ChannelUID(thing.getUID(), "weekday"), service + "/" + "weekday", CoreItemFactory.STRING,
253                         currentPathName, "Current selected weekday for cycle selection", "Weekday", true, true, state,
254                         "");
255                 if (null == newChannel) {
256                     logger.warn("Creation of the channel {} was not possible", thing.getUID());
257                 } else {
258                     subChannels.add(newChannel);
259                 }
260
261                 state = StateDescriptionFragmentBuilder.create().withMinimum(BigDecimal.ZERO).withStep(BigDecimal.ONE)
262                         .withPattern("%d").withReadOnly(true).build();
263                 newChannel = createChannel(new ChannelTypeUID(thing.getUID().getAsString() + ":" + "nbrCycles"),
264                         new ChannelUID(thing.getUID(), "nbrCycles"), service + "/" + "nbrCycles",
265                         CoreItemFactory.NUMBER, currentPathName, "Number of switching cycles", "Number", true, true,
266                         state, "");
267                 if (null == newChannel) {
268                     logger.warn("Creation of the channel {} was not possible", thing.getUID());
269                 } else {
270                     subChannels.add(newChannel);
271                 }
272
273                 state = StateDescriptionFragmentBuilder.create().withMinimum(BigDecimal.ZERO).withStep(BigDecimal.ONE)
274                         .withPattern("%d").build();
275                 newChannel = createChannel(new ChannelTypeUID(thing.getUID().getAsString() + ":" + "cycle"),
276                         new ChannelUID(thing.getUID(), "cycle"), service + "/" + "cycle", CoreItemFactory.NUMBER,
277                         currentPathName, "Current selected cycle", "Cycle", true, true, state, "");
278                 if (null == newChannel) {
279                     logger.warn("Creation of the channel {} was not possible", thing.getUID());
280                 } else {
281                     subChannels.add(newChannel);
282                 }
283
284                 state = StateDescriptionFragmentBuilder.create().withMinimum(BigDecimal.ZERO).withStep(BigDecimal.ONE)
285                         .withPattern("%d minutes").build();
286                 String posName = thing.getProperties().get(SWITCH_PROGRAM_POSITIVE);
287                 newChannel = createChannel(new ChannelTypeUID(thing.getUID().getAsString() + ":" + posName),
288                         new ChannelUID(thing.getUID(), posName), service + "/" + posName, CoreItemFactory.NUMBER,
289                         currentPathName, "Positive switch of the cycle, like 'Day' 'On'", posName, true, true, state,
290                         "minutes");
291                 if (null == newChannel) {
292                     logger.warn("Creation of the channel {} was not possible", thing.getUID());
293                 } else {
294                     subChannels.add(newChannel);
295                 }
296
297                 String negName = thing.getProperties().get(SWITCH_PROGRAM_NEGATIVE);
298                 newChannel = createChannel(new ChannelTypeUID(thing.getUID().getAsString() + ":" + negName),
299                         new ChannelUID(thing.getUID(), negName), service + "/" + negName, CoreItemFactory.NUMBER,
300                         currentPathName, "Negative switch of the cycle, like 'Night' 'Off'", negName, true, true, state,
301                         "minutes");
302                 if (null == newChannel) {
303                     logger.warn("Creation of the channel {} was not possible", thing.getUID());
304                 } else {
305                     subChannels.add(newChannel);
306                 }
307             }
308             ThingBuilder thingBuilder = editThing();
309             List<Channel> actChannels = thing.getChannels();
310             for (Channel channel : actChannels) {
311                 thingBuilder.withoutChannel(channel.getUID());
312             }
313             thingBuilder.withChannels(subChannels);
314             updateThing(thingBuilder.build());
315             updateStatus(ThingStatus.ONLINE);
316         }
317     }
318
319     @Override
320     public void dispose() {
321         channelTypeProvider.removeChannelTypesForThing(getThing().getUID());
322     }
323
324     /**
325      * Checks whether a channel is linked to an item
326      */
327     public boolean checkLinked(Channel channel) {
328         return isLinked(channel.getUID().getId());
329     }
330
331     /**
332      * Search for services and add them to a list
333      */
334     private void addChannels(KM200ServiceObject serObj, Thing thing, List<Channel> subChannels, String subNameAddon) {
335         String service = serObj.getFullServiceName();
336         Set<String> subKeys = serObj.serviceTreeMap.keySet();
337         List<String> asProperties = null;
338         /* Some defines for dummy values, we will ignore such services */
339         final BigDecimal maxInt16AsFloat = new BigDecimal(+3276.8).setScale(6, RoundingMode.HALF_UP);
340         final BigDecimal minInt16AsFloat = new BigDecimal(-3276.8).setScale(6, RoundingMode.HALF_UP);
341         final BigDecimal maxInt16AsInt = new BigDecimal(3200).setScale(4, RoundingMode.HALF_UP);
342         for (KM200ThingType tType : KM200ThingType.values()) {
343             String root = tType.getRootPath();
344             if (root.compareTo(service) == 0) {
345                 asProperties = tType.asBridgeProperties();
346             }
347         }
348         for (String subKey : subKeys) {
349             if (asProperties != null) {
350                 if (asProperties.contains(subKey)) {
351                     continue;
352                 }
353             }
354             Map<String, String> properties = new HashMap<>(1);
355             String root = service + "/" + subKey;
356             properties.put("root", KM200Utils.translatesPathToName(root));
357             String subKeyType = serObj.serviceTreeMap.get(subKey).getServiceType();
358             boolean readOnly;
359             String unitOfMeasure = "";
360             StateDescriptionFragment state = null;
361             ChannelTypeUID channelTypeUID = new ChannelTypeUID(
362                     thing.getUID().getAsString() + ":" + subNameAddon + subKey);
363             Channel newChannel = null;
364             ChannelUID channelUID = new ChannelUID(thing.getUID(), subNameAddon + subKey);
365             if (serObj.serviceTreeMap.get(subKey).getWriteable() > 0) {
366                 readOnly = false;
367             } else {
368                 readOnly = true;
369             }
370             if ("temperatures".compareTo(thing.getUID().getId()) == 0) {
371                 unitOfMeasure = "°C";
372             }
373             logger.trace("Create things: {} id: {} channel: {}", thing.getUID(), subKey, thing.getUID().getId());
374             switch (subKeyType) {
375                 case DATA_TYPE_STRING_VALUE:
376                     /* Creating an new channel type with capabilities from service */
377                     List<StateOption> options = null;
378                     if (serObj.serviceTreeMap.get(subKey).getValueParameter() != null) {
379                         options = new ArrayList<>();
380                         // The type is definitely correct here
381                         @SuppressWarnings("unchecked")
382                         List<String> subValParas = (List<String>) serObj.serviceTreeMap.get(subKey).getValueParameter();
383                         if (null != subValParas) {
384                             for (String para : subValParas) {
385                                 StateOption stateOption = new StateOption(para, para);
386                                 options.add(stateOption);
387                             }
388                         }
389                     }
390                     StateDescriptionFragmentBuilder builder = StateDescriptionFragmentBuilder.create().withPattern("%s")
391                             .withReadOnly(readOnly);
392                     if (options != null && !options.isEmpty()) {
393                         builder.withOptions(options);
394                     }
395                     state = builder.build();
396                     newChannel = createChannel(channelTypeUID, channelUID, root, CoreItemFactory.STRING, null, subKey,
397                             subKey, true, false, state, unitOfMeasure);
398                     break;
399                 case DATA_TYPE_FLOAT_VALUE:
400                     /*
401                      * Check whether the value is a NaN. Usually all floats are BigDecimal. If it's a double then it's
402                      * Double.NaN. In this case we are ignoring this channel.
403                      */
404                     BigDecimal minVal = null;
405                     BigDecimal maxVal = null;
406                     BigDecimal step = null;
407                     final BigDecimal val;
408                     Object tmpVal = serObj.serviceTreeMap.get(subKey).getValue();
409                     if (tmpVal instanceof Double) {
410                         continue;
411                     }
412                     /* Check whether the value is a dummy (e.g. not connected sensor) */
413                     val = (BigDecimal) serObj.serviceTreeMap.get(subKey).getValue();
414                     if (val != null) {
415                         if (val.setScale(6, RoundingMode.HALF_UP).equals(maxInt16AsFloat)
416                                 || val.setScale(6, RoundingMode.HALF_UP).equals(minInt16AsFloat)
417                                 || val.setScale(4, RoundingMode.HALF_UP).equals(maxInt16AsInt)) {
418                             continue;
419                         }
420                     }
421                     /* Check the capabilities of this service */
422                     if (serObj.serviceTreeMap.get(subKey).getValueParameter() != null) {
423                         /* Creating an new channel type with capabilities from service */
424                         // The type is definitely correct here
425                         @SuppressWarnings("unchecked")
426                         List<Object> subValParas = (List<Object>) serObj.serviceTreeMap.get(subKey).getValueParameter();
427                         if (null != subValParas) {
428                             minVal = (BigDecimal) subValParas.get(0);
429                             maxVal = (BigDecimal) subValParas.get(1);
430                             if (subValParas.size() > 2) {
431                                 unitOfMeasure = (String) subValParas.get(2);
432                                 if ("C".equals(unitOfMeasure)) {
433                                     unitOfMeasure = "°C";
434                                 }
435                             }
436                             step = BigDecimal.valueOf(0.5);
437                         }
438                     }
439                     builder = StateDescriptionFragmentBuilder.create().withPattern("%.1f " + unitOfMeasure)
440                             .withReadOnly(readOnly);
441                     if (minVal != null) {
442                         builder.withMinimum(minVal);
443                     }
444                     if (maxVal != null) {
445                         builder.withMaximum(maxVal);
446                     }
447                     if (step != null) {
448                         builder.withStep(step);
449                     }
450                     state = builder.build();
451                     newChannel = createChannel(channelTypeUID, channelUID, root, CoreItemFactory.NUMBER, null, subKey,
452                             subKey, true, false, state, unitOfMeasure);
453                     break;
454                 case DATA_TYPE_REF_ENUM:
455                     /* Check whether the sub service should be ignored */
456                     boolean ignoreIt = false;
457                     for (KM200ThingType tType : KM200ThingType.values()) {
458                         if (tType.getThingTypeUID().equals(thing.getThingTypeUID())) {
459                             for (String ignore : tType.ignoreSubService()) {
460                                 if (ignore.equals(subKey)) {
461                                     ignoreIt = true;
462                                 }
463                             }
464                         }
465                     }
466                     if (ignoreIt) {
467                         continue;
468                     }
469                     /* Search for new services in sub path */
470                     KM200ServiceObject obj = serObj.serviceTreeMap.get(subKey);
471                     if (obj != null) {
472                         addChannels(obj, thing, subChannels, subKey + "_");
473                     }
474                     break;
475                 case DATA_TYPE_ERROR_LIST:
476                     if ("nbrErrors".equals(subKey) || "error".equals(subKey)) {
477                         state = StateDescriptionFragmentBuilder.create().withPattern("%.0f").withReadOnly(readOnly)
478                                 .build();
479                         newChannel = createChannel(new ChannelTypeUID(thing.getUID().getAsString() + ":" + subKey),
480                                 channelUID, root, CoreItemFactory.NUMBER, null, subKey, subKey, true, false, state,
481                                 unitOfMeasure);
482                     } else if ("errorString".equals(subKey)) {
483                         state = StateDescriptionFragmentBuilder.create().withPattern("%s").withReadOnly(readOnly)
484                                 .build();
485                         newChannel = createChannel(new ChannelTypeUID(thing.getUID().getAsString() + ":" + subKey),
486                                 channelUID, root, CoreItemFactory.STRING, null, "Error message", "Text", true, false,
487                                 state, unitOfMeasure);
488                     }
489                     break;
490             }
491             if (newChannel != null && state != null) {
492                 subChannels.add(newChannel);
493             }
494         }
495     }
496 }