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.smartmeter.internal;
15 import java.math.BigDecimal;
16 import java.text.MessageFormat;
17 import java.time.Duration;
18 import java.util.ArrayList;
19 import java.util.HashMap;
20 import java.util.List;
22 import java.util.Objects;
23 import java.util.function.Supplier;
25 import javax.measure.Quantity;
26 import javax.measure.Unit;
28 import org.apache.commons.lang3.StringUtils;
29 import org.eclipse.jdt.annotation.DefaultLocation;
30 import org.eclipse.jdt.annotation.NonNull;
31 import org.eclipse.jdt.annotation.NonNullByDefault;
32 import org.eclipse.jdt.annotation.Nullable;
33 import org.openhab.binding.smartmeter.SmartMeterBindingConstants;
34 import org.openhab.binding.smartmeter.SmartMeterConfiguration;
35 import org.openhab.binding.smartmeter.internal.conformity.Conformity;
36 import org.openhab.binding.smartmeter.internal.helper.Baudrate;
37 import org.openhab.core.config.core.Configuration;
38 import org.openhab.core.io.transport.serial.SerialPortManager;
39 import org.openhab.core.library.types.QuantityType;
40 import org.openhab.core.library.types.StringType;
41 import org.openhab.core.thing.Channel;
42 import org.openhab.core.thing.ChannelUID;
43 import org.openhab.core.thing.Thing;
44 import org.openhab.core.thing.ThingStatus;
45 import org.openhab.core.thing.ThingStatusDetail;
46 import org.openhab.core.thing.binding.BaseThingHandler;
47 import org.openhab.core.thing.binding.builder.ChannelBuilder;
48 import org.openhab.core.thing.binding.builder.ThingBuilder;
49 import org.openhab.core.thing.type.ChannelType;
50 import org.openhab.core.thing.type.ChannelTypeUID;
51 import org.openhab.core.types.Command;
52 import org.openhab.core.types.RefreshType;
53 import org.openhab.core.types.State;
54 import org.openhab.core.types.TypeParser;
55 import org.openhab.core.util.HexUtils;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
59 import io.reactivex.disposables.Disposable;
62 * The {@link SmartMeterHandler} is responsible for handling commands, which are
63 * sent to one of the channels.
65 * @author Matthias Steigenberger - Initial contribution
67 @NonNullByDefault({ DefaultLocation.ARRAY_CONTENTS, DefaultLocation.PARAMETER, DefaultLocation.RETURN_TYPE,
68 DefaultLocation.TYPE_ARGUMENT })
69 public class SmartMeterHandler extends BaseThingHandler {
71 private static final long DEFAULT_TIMEOUT = 30000;
72 private static final int DEFAULT_REFRESH_PERIOD = 30;
73 private Logger logger = LoggerFactory.getLogger(SmartMeterHandler.class);
74 private MeterDevice<?> smlDevice;
75 private Disposable valueReader;
76 private Conformity conformity;
77 private MeterValueListener valueChangeListener;
78 private SmartMeterChannelTypeProvider channelTypeProvider;
79 private @NonNull Supplier<SerialPortManager> serialPortManagerSupplier;
81 public SmartMeterHandler(Thing thing, SmartMeterChannelTypeProvider channelProvider,
82 Supplier<SerialPortManager> serialPortManagerSupplier) {
84 Objects.requireNonNull(channelProvider, "SmartMeterChannelTypeProvider must not be null");
85 this.channelTypeProvider = channelProvider;
86 this.serialPortManagerSupplier = serialPortManagerSupplier;
90 public void initialize() {
91 logger.debug("Initializing Smartmeter handler.");
94 SmartMeterConfiguration config = getConfigAs(SmartMeterConfiguration.class);
96 String port = config.port;
97 logger.debug("config port = {}", port);
99 if (port == null || port.isBlank()) {
100 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
101 "Parameter 'port' is mandatory and must be configured");
103 byte[] pullSequence = config.initMessage == null ? null
104 : HexUtils.hexToBytes(StringUtils.deleteWhitespace(config.initMessage));
105 int baudrate = config.baudrate == null ? Baudrate.AUTO.getBaudrate()
106 : Baudrate.fromString(config.baudrate).getBaudrate();
107 this.conformity = config.conformity == null ? Conformity.NONE : Conformity.valueOf(config.conformity);
108 this.smlDevice = MeterDeviceFactory.getDevice(serialPortManagerSupplier, config.mode,
109 this.thing.getUID().getAsString(), port, pullSequence, baudrate, config.baudrateChangeDelay);
110 updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.HANDLER_CONFIGURATION_PENDING,
111 "Waiting for messages from device");
113 smlDevice.addValueChangeListener(channelTypeProvider);
120 public void dispose() {
123 if (this.valueChangeListener != null) {
124 this.smlDevice.removeValueChangeListener(valueChangeListener);
126 if (this.channelTypeProvider != null) {
127 this.smlDevice.removeValueChangeListener(channelTypeProvider);
131 private void cancelRead() {
132 if (this.valueReader != null) {
133 this.valueReader.dispose();
138 public void handleCommand(ChannelUID channelUID, Command command) {
139 if (command instanceof RefreshType) {
140 updateOBISChannel(channelUID);
142 logger.debug("The SML reader binding is read-only and can not handle command {}", command);
147 * Get new data the device
150 private void updateOBISValue() {
153 valueChangeListener = new MeterValueListener() {
155 public <Q extends @NonNull Quantity<Q>> void valueChanged(MeterValue<Q> value) {
156 ThingBuilder thingBuilder = editThing();
158 String obis = value.getObisCode();
160 String obisChannelString = SmartMeterBindingConstants.getObisChannelId(obis);
161 Channel channel = thing.getChannel(obisChannelString);
162 ChannelTypeUID channelTypeId = channelTypeProvider.getChannelTypeIdForObis(obis);
164 ChannelType channelType = channelTypeProvider.getChannelType(channelTypeId, null);
165 if (channelType != null) {
166 String itemType = channelType.getItemType();
168 State state = getStateForObisValue(value, channel);
169 if (channel == null) {
170 logger.debug("Adding channel: {} with item type: {}", obisChannelString, itemType);
172 // channel has not been created yet
173 ChannelBuilder channelBuilder = ChannelBuilder
174 .create(new ChannelUID(thing.getUID(), obisChannelString), itemType)
175 .withType(channelTypeId);
177 Configuration configuration = new Configuration();
178 configuration.put(SmartMeterBindingConstants.CONFIGURATION_CONVERSION, 1);
179 channelBuilder.withConfiguration(configuration);
180 channelBuilder.withLabel(obis);
181 Map<String, String> channelProps = new HashMap<>();
182 channelProps.put(SmartMeterBindingConstants.CHANNEL_PROPERTY_OBIS, obis);
183 channelBuilder.withProperties(channelProps);
184 channelBuilder.withDescription(
185 MessageFormat.format("Value for OBIS code: {0} with Unit: {1}", obis, value.getUnit()));
186 channel = channelBuilder.build();
187 ChannelUID channelId = channel.getUID();
189 // add all valid channels to the thing builder
190 List<Channel> channels = new ArrayList<>(getThing().getChannels());
191 if (channels.stream().filter((element) -> element.getUID().equals(channelId)).count() == 0) {
192 channels.add(channel);
193 thingBuilder.withChannels(channels);
194 updateThing(thingBuilder.build());
198 if (!channel.getProperties().containsKey(SmartMeterBindingConstants.CHANNEL_PROPERTY_OBIS)) {
199 addObisPropertyToChannel(obis, channel);
202 updateState(channel.getUID(), state);
205 updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE);
207 logger.warn("No ChannelType found for OBIS {}", obis);
211 private void addObisPropertyToChannel(String obis, Channel channel) {
212 String description = channel.getDescription();
213 String label = channel.getLabel();
214 ChannelBuilder newChannel = ChannelBuilder.create(channel.getUID(), channel.getAcceptedItemType())
215 .withDefaultTags(channel.getDefaultTags()).withConfiguration(channel.getConfiguration())
216 .withDescription(description == null ? "" : description).withKind(channel.getKind())
217 .withLabel(label == null ? "" : label).withType(channel.getChannelTypeUID());
218 Map<String, String> properties = new HashMap<>(channel.getProperties());
219 properties.put(SmartMeterBindingConstants.CHANNEL_PROPERTY_OBIS, obis);
220 newChannel.withProperties(properties);
221 updateThing(editThing().withoutChannel(channel.getUID()).withChannel(newChannel.build()).build());
225 public <Q extends @NonNull Quantity<Q>> void valueRemoved(MeterValue<Q> value) {
226 // channels that are not available are removed
227 String obisChannelId = SmartMeterBindingConstants.getObisChannelId(value.getObisCode());
228 logger.debug("Removing channel: {}", obisChannelId);
229 ThingBuilder thingBuilder = editThing();
230 thingBuilder.withoutChannel(new ChannelUID(thing.getUID(), obisChannelId));
231 updateThing(thingBuilder.build());
235 public void errorOccurred(Throwable e) {
236 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getLocalizedMessage());
239 this.smlDevice.addValueChangeListener(valueChangeListener);
241 SmartMeterConfiguration config = getConfigAs(SmartMeterConfiguration.class);
242 int delay = config.refresh != null ? config.refresh : DEFAULT_REFRESH_PERIOD;
243 valueReader = this.smlDevice.readValues(DEFAULT_TIMEOUT, this.scheduler, Duration.ofSeconds(delay));
246 private void updateOBISChannel(ChannelUID channelId) {
247 if (isLinked(channelId.getId())) {
248 Channel channel = this.thing.getChannel(channelId.getId());
249 if (channel != null) {
250 String obis = channel.getProperties().get(SmartMeterBindingConstants.CHANNEL_PROPERTY_OBIS);
252 MeterValue<?> value = this.smlDevice.getMeterValue(obis);
254 State state = getStateForObisValue(value, channel);
256 updateState(channel.getUID(), state);
264 @SuppressWarnings("unchecked")
265 private @Nullable <Q extends Quantity<Q>> State getStateForObisValue(MeterValue<?> value,
266 @Nullable Channel channel) {
267 Unit<?> unit = value.getUnit();
268 String valueString = value.getValue();
270 valueString += " " + value.getUnit();
272 State state = TypeParser.parseState(List.of(QuantityType.class, StringType.class), valueString);
273 if (channel != null && state instanceof QuantityType) {
274 state = applyConformity(channel, (QuantityType<Q>) state);
275 Number conversionRatio = (Number) channel.getConfiguration()
276 .get(SmartMeterBindingConstants.CONFIGURATION_CONVERSION);
277 if (conversionRatio != null) {
278 state = ((QuantityType<?>) state).divide(BigDecimal.valueOf(conversionRatio.doubleValue()));
284 private <Q extends Quantity<Q>> State applyConformity(Channel channel, QuantityType<Q> currentState) {
286 return this.conformity.apply(channel, currentState, getThing(), this.smlDevice);
287 } catch (Exception e) {
288 logger.warn("Failed to apply negation for channel: {}", channel.getUID(), e);