2 * Copyright (c) 2010-2023 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.List;
27 import java.util.stream.Collectors;
28 import java.util.stream.Stream;
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;
64 * The {@link KM200ThingHandler} is responsible for handling commands, which are
65 * sent to one of the channels.
67 * @author Markus Eckhardt - Initial contribution
70 public class KM200ThingHandler extends BaseThingHandler {
72 private final Logger logger = LoggerFactory.getLogger(KM200ThingHandler.class);
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()));
80 private final KM200ChannelTypeProvider channelTypeProvider;
82 public KM200ThingHandler(Thing thing, KM200ChannelTypeProvider channelTypeProvider) {
84 this.channelTypeProvider = channelTypeProvider;
88 public void handleCommand(ChannelUID channelUID, Command command) {
89 Bridge bridge = this.getBridge();
93 KM200GatewayHandler gateway = (KM200GatewayHandler) bridge.getHandler();
94 if (gateway == null) {
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);
105 logger.warn("Unsupported Command: {} Class: {}", command.toFullString(), command.getClass());
111 * Choose a category for a channel
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;
120 category = "Temperature";
122 category = "Heating";
125 } else if (unitOfMeasure.indexOf("kW") == 0 || unitOfMeasure.indexOf("kWh") == 0) {
127 } else if (unitOfMeasure.indexOf("l/min") == 0 || unitOfMeasure.indexOf("l/h") == 0) {
129 } else if (unitOfMeasure.indexOf("Pascal") == 0 || unitOfMeasure.indexOf("bar") == 0) {
130 category = "Pressure";
131 } else if (unitOfMeasure.indexOf("rpm") == 0) {
133 } else if (unitOfMeasure.indexOf("mins") == 0 || unitOfMeasure.indexOf("minutes") == 0) {
135 } else if (unitOfMeasure.indexOf("kg/l") == 0) {
137 } else if (unitOfMeasure.indexOf("%%") == 0) {
140 category = topCategory;
146 * Creates a new channel
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)) {
159 } else if (CoreItemFactory.STRING.equals(type)) {
162 logger.info("Channeltype {} not supported", type);
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();
179 channelTypeProvider.addChannelType(channelType);
181 chProperties.put("root", KM200Utils.translatesPathToName(root));
182 if (null != currentPathName && switchProgram) {
183 chProperties.put(SWITCH_PROGRAM_CURRENT_PATH_NAME, currentPathName);
186 newChannel = ChannelBuilder.create(channelUID, type).withType(channelTypeUID).withDescription(description)
187 .withLabel(label).withKind(ChannelKind.STATE).withProperties(chProperties).build();
189 newChannel = ChannelBuilder.create(channelUID, type).withType(channelTypeUID).withDescription(description)
190 .withLabel(label).withKind(ChannelKind.STATE).build();
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);
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);
210 String service = KM200Utils.translatesNameToPath(thing.getProperties().get("root"));
211 if (service == null) {
212 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "root property missing");
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);
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, "");
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,
236 if (null == newChannel) {
237 logger.warn("Creation of the channel {} was not possible", thing.getUID());
239 subChannels.add(newChannel);
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,
248 if (null == newChannel) {
249 logger.warn("Creation of the channel {} was not possible", thing.getUID());
251 subChannels.add(newChannel);
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());
262 subChannels.add(newChannel);
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) {
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,
276 if (null == newChannel) {
277 logger.warn("Creation of the channel {} was not possible", thing.getUID());
279 subChannels.add(newChannel);
282 String negName = thing.getProperties().get(SWITCH_PROGRAM_NEGATIVE);
283 if (negName == null) {
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,
291 if (null == newChannel) {
292 logger.warn("Creation of the channel {} was not possible", thing.getUID());
294 subChannels.add(newChannel);
297 ThingBuilder thingBuilder = editThing();
298 List<Channel> actChannels = thing.getChannels();
299 for (Channel channel : actChannels) {
300 thingBuilder.withoutChannel(channel.getUID());
302 thingBuilder.withChannels(subChannels);
303 updateThing(thingBuilder.build());
304 updateStatus(ThingStatus.ONLINE);
309 public void dispose() {
310 channelTypeProvider.removeChannelTypesForThing(getThing().getUID());
314 * Checks whether a channel is linked to an item
316 public boolean checkLinked(Channel channel) {
317 return isLinked(channel.getUID().getId());
321 * Search for services and add them to a list
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();
337 for (String subKey : subKeys) {
338 if (asProperties != null) {
339 if (asProperties.contains(subKey)) {
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();
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) {
359 if ("temperatures".compareTo(thing.getUID().getId()) == 0) {
360 unitOfMeasure = "°C";
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);
379 StateDescriptionFragmentBuilder builder = StateDescriptionFragmentBuilder.create().withPattern("%s")
380 .withReadOnly(readOnly);
381 if (options != null && !options.isEmpty()) {
382 builder.withOptions(options);
384 state = builder.build();
385 newChannel = createChannel(channelTypeUID, channelUID, root, CoreItemFactory.STRING, null, subKey,
386 subKey, true, false, state, unitOfMeasure);
388 case DATA_TYPE_FLOAT_VALUE:
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.
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) {
401 /* Check whether the value is a dummy (e.g. not connected sensor) */
402 val = (BigDecimal) serObj.serviceTreeMap.get(subKey).getValue();
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)) {
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";
425 step = BigDecimal.valueOf(0.5);
428 builder = StateDescriptionFragmentBuilder.create().withPattern("%.1f " + unitOfMeasure)
429 .withReadOnly(readOnly);
430 if (minVal != null) {
431 builder.withMinimum(minVal);
433 if (maxVal != null) {
434 builder.withMaximum(maxVal);
437 builder.withStep(step);
439 state = builder.build();
440 newChannel = createChannel(channelTypeUID, channelUID, root, CoreItemFactory.NUMBER, null, subKey,
441 subKey, true, false, state, unitOfMeasure);
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)) {
458 /* Search for new services in sub path */
459 KM200ServiceObject obj = serObj.serviceTreeMap.get(subKey);
461 addChannels(obj, thing, subChannels, subKey + "_");
464 case DATA_TYPE_ERROR_LIST:
465 if ("nbrErrors".equals(subKey) || "error".equals(subKey)) {
466 state = StateDescriptionFragmentBuilder.create().withPattern("%.0f").withReadOnly(readOnly)
468 newChannel = createChannel(new ChannelTypeUID(thing.getUID().getAsString() + ":" + subKey),
469 channelUID, root, CoreItemFactory.NUMBER, null, subKey, subKey, true, false, state,
471 } else if ("errorString".equals(subKey)) {
472 state = StateDescriptionFragmentBuilder.create().withPattern("%s").withReadOnly(readOnly)
474 newChannel = createChannel(new ChannelTypeUID(thing.getUID().getAsString() + ":" + subKey),
475 channelUID, root, CoreItemFactory.STRING, null, "Error message", "Text", true, false,
476 state, unitOfMeasure);
480 if (newChannel != null && state != null) {
481 subChannels.add(newChannel);