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