2 * Copyright (c) 2010-2020 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.km200.internal.handler;
15 import static org.openhab.binding.km200.internal.KM200BindingConstants.*;
17 import java.math.BigDecimal;
18 import java.math.RoundingMode;
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;
28 import java.util.stream.Collectors;
29 import java.util.stream.Stream;
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;
65 * The {@link KM200ThingHandler} is responsible for handling commands, which are
66 * sent to one of the channels.
68 * @author Markus Eckhardt - Initial contribution
71 public class KM200ThingHandler extends BaseThingHandler {
73 private final Logger logger = LoggerFactory.getLogger(KM200ThingHandler.class);
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()));
81 private final KM200ChannelTypeProvider channelTypeProvider;
83 public KM200ThingHandler(Thing thing, KM200ChannelTypeProvider channelTypeProvider) {
85 this.channelTypeProvider = channelTypeProvider;
89 public void handleCommand(ChannelUID channelUID, Command command) {
90 Bridge bridge = this.getBridge();
94 KM200GatewayHandler gateway = (KM200GatewayHandler) bridge.getHandler();
95 if (gateway == null) {
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);
106 logger.warn("Unsupported Command: {} Class: {}", command.toFullString(), command.getClass());
112 * Choose a tag for a channel
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) {
119 tags.add("CurrentTemperature");
121 tags.add("TargetTemperature");
129 * Choose a category for a channel
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;
138 category = "Temperature";
140 category = "Heating";
143 } else if (unitOfMeasure.indexOf("kW") == 0 || unitOfMeasure.indexOf("kWh") == 0) {
145 } else if (unitOfMeasure.indexOf("l/min") == 0 || unitOfMeasure.indexOf("l/h") == 0) {
147 } else if (unitOfMeasure.indexOf("Pascal") == 0 || unitOfMeasure.indexOf("bar") == 0) {
148 category = "Pressure";
149 } else if (unitOfMeasure.indexOf("rpm") == 0) {
151 } else if (unitOfMeasure.indexOf("mins") == 0 || unitOfMeasure.indexOf("minutes") == 0) {
153 } else if (unitOfMeasure.indexOf("kg/l") == 0) {
155 } else if (unitOfMeasure.indexOf("%%") == 0) {
158 category = topCategory;
164 * Creates a new channel
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";
179 } else if (CoreItemFactory.STRING.equals(type)) {
180 itemType = "StringType";
183 logger.info("Channeltype {} not supported", type);
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();
202 channelTypeProvider.addChannelType(channelType);
204 chProperties.put("root", KM200Utils.translatesPathToName(root));
205 if (null != currentPathName && switchProgram) {
206 chProperties.put(SWITCH_PROGRAM_CURRENT_PATH_NAME, currentPathName);
209 newChannel = ChannelBuilder.create(channelUID, type).withType(channelTypeUID).withDescription(description)
210 .withLabel(label).withKind(ChannelKind.STATE).withProperties(chProperties).build();
212 newChannel = ChannelBuilder.create(channelUID, type).withType(channelTypeUID).withDescription(description)
213 .withLabel(label).withKind(ChannelKind.STATE).build();
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);
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);
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);
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, "");
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,
255 if (null == newChannel) {
256 logger.warn("Creation of the channel {} was not possible", thing.getUID());
258 subChannels.add(newChannel);
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,
267 if (null == newChannel) {
268 logger.warn("Creation of the channel {} was not possible", thing.getUID());
270 subChannels.add(newChannel);
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());
281 subChannels.add(newChannel);
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,
291 if (null == newChannel) {
292 logger.warn("Creation of the channel {} was not possible", thing.getUID());
294 subChannels.add(newChannel);
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,
302 if (null == newChannel) {
303 logger.warn("Creation of the channel {} was not possible", thing.getUID());
305 subChannels.add(newChannel);
308 ThingBuilder thingBuilder = editThing();
309 List<Channel> actChannels = thing.getChannels();
310 for (Channel channel : actChannels) {
311 thingBuilder.withoutChannel(channel.getUID());
313 thingBuilder.withChannels(subChannels);
314 updateThing(thingBuilder.build());
315 updateStatus(ThingStatus.ONLINE);
320 public void dispose() {
321 channelTypeProvider.removeChannelTypesForThing(getThing().getUID());
325 * Checks whether a channel is linked to an item
327 public boolean checkLinked(Channel channel) {
328 return isLinked(channel.getUID().getId());
332 * Search for services and add them to a list
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();
348 for (String subKey : subKeys) {
349 if (asProperties != null) {
350 if (asProperties.contains(subKey)) {
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();
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) {
370 if ("temperatures".compareTo(thing.getUID().getId()) == 0) {
371 unitOfMeasure = "°C";
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);
390 StateDescriptionFragmentBuilder builder = StateDescriptionFragmentBuilder.create().withPattern("%s")
391 .withReadOnly(readOnly);
392 if (options != null && !options.isEmpty()) {
393 builder.withOptions(options);
395 state = builder.build();
396 newChannel = createChannel(channelTypeUID, channelUID, root, CoreItemFactory.STRING, null, subKey,
397 subKey, true, false, state, unitOfMeasure);
399 case DATA_TYPE_FLOAT_VALUE:
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.
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) {
412 /* Check whether the value is a dummy (e.g. not connected sensor) */
413 val = (BigDecimal) serObj.serviceTreeMap.get(subKey).getValue();
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)) {
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";
436 step = BigDecimal.valueOf(0.5);
439 builder = StateDescriptionFragmentBuilder.create().withPattern("%.1f " + unitOfMeasure)
440 .withReadOnly(readOnly);
441 if (minVal != null) {
442 builder.withMinimum(minVal);
444 if (maxVal != null) {
445 builder.withMaximum(maxVal);
448 builder.withStep(step);
450 state = builder.build();
451 newChannel = createChannel(channelTypeUID, channelUID, root, CoreItemFactory.NUMBER, null, subKey,
452 subKey, true, false, state, unitOfMeasure);
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)) {
469 /* Search for new services in sub path */
470 KM200ServiceObject obj = serObj.serviceTreeMap.get(subKey);
472 addChannels(obj, thing, subChannels, subKey + "_");
475 case DATA_TYPE_ERROR_LIST:
476 if ("nbrErrors".equals(subKey) || "error".equals(subKey)) {
477 state = StateDescriptionFragmentBuilder.create().withPattern("%.0f").withReadOnly(readOnly)
479 newChannel = createChannel(new ChannelTypeUID(thing.getUID().getAsString() + ":" + subKey),
480 channelUID, root, CoreItemFactory.NUMBER, null, subKey, subKey, true, false, state,
482 } else if ("errorString".equals(subKey)) {
483 state = StateDescriptionFragmentBuilder.create().withPattern("%s").withReadOnly(readOnly)
485 newChannel = createChannel(new ChannelTypeUID(thing.getUID().getAsString() + ":" + subKey),
486 channelUID, root, CoreItemFactory.STRING, null, "Error message", "Text", true, false,
487 state, unitOfMeasure);
491 if (newChannel != null && state != null) {
492 subChannels.add(newChannel);