]> git.basschouten.com Git - openhab-addons.git/blob
1134310e850a6dbbc02279c4b7157dc6ce921c99
[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.smartmeter.internal;
14
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;
21 import java.util.Map;
22 import java.util.Objects;
23 import java.util.function.Supplier;
24
25 import javax.measure.Quantity;
26 import javax.measure.Unit;
27
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;
58
59 import io.reactivex.disposables.Disposable;
60
61 /**
62  * The {@link SmartMeterHandler} is responsible for handling commands, which are
63  * sent to one of the channels.
64  *
65  * @author Matthias Steigenberger - Initial contribution
66  */
67 @NonNullByDefault({ DefaultLocation.ARRAY_CONTENTS, DefaultLocation.PARAMETER, DefaultLocation.RETURN_TYPE,
68         DefaultLocation.TYPE_ARGUMENT })
69 public class SmartMeterHandler extends BaseThingHandler {
70
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;
80
81     public SmartMeterHandler(Thing thing, SmartMeterChannelTypeProvider channelProvider,
82             Supplier<SerialPortManager> serialPortManagerSupplier) {
83         super(thing);
84         Objects.requireNonNull(channelProvider, "SmartMeterChannelTypeProvider must not be null");
85         this.channelTypeProvider = channelProvider;
86         this.serialPortManagerSupplier = serialPortManagerSupplier;
87     }
88
89     @Override
90     public void initialize() {
91         logger.debug("Initializing Smartmeter handler.");
92         cancelRead();
93
94         SmartMeterConfiguration config = getConfigAs(SmartMeterConfiguration.class);
95
96         String port = config.port;
97         logger.debug("config port = {}", port);
98
99         if (port == null || port.isBlank()) {
100             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
101                     "Parameter 'port' is mandatory and must be configured");
102         } else {
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");
112
113             smlDevice.addValueChangeListener(channelTypeProvider);
114
115             updateOBISValue();
116         }
117     }
118
119     @Override
120     public void dispose() {
121         super.dispose();
122         cancelRead();
123         if (this.valueChangeListener != null) {
124             this.smlDevice.removeValueChangeListener(valueChangeListener);
125         }
126         if (this.channelTypeProvider != null) {
127             this.smlDevice.removeValueChangeListener(channelTypeProvider);
128         }
129     }
130
131     private void cancelRead() {
132         if (this.valueReader != null) {
133             this.valueReader.dispose();
134         }
135     }
136
137     @Override
138     public void handleCommand(ChannelUID channelUID, Command command) {
139         if (command instanceof RefreshType) {
140             updateOBISChannel(channelUID);
141         } else {
142             logger.debug("The SML reader binding is read-only and can not handle command {}", command);
143         }
144     }
145
146     /**
147      * Get new data the device
148      *
149      */
150     private void updateOBISValue() {
151         cancelRead();
152
153         valueChangeListener = new MeterValueListener() {
154             @Override
155             public <Q extends @NonNull Quantity<Q>> void valueChanged(MeterValue<Q> value) {
156                 ThingBuilder thingBuilder = editThing();
157
158                 String obis = value.getObisCode();
159
160                 String obisChannelString = SmartMeterBindingConstants.getObisChannelId(obis);
161                 Channel channel = thing.getChannel(obisChannelString);
162                 ChannelTypeUID channelTypeId = channelTypeProvider.getChannelTypeIdForObis(obis);
163
164                 ChannelType channelType = channelTypeProvider.getChannelType(channelTypeId, null);
165                 if (channelType != null) {
166                     String itemType = channelType.getItemType();
167
168                     State state = getStateForObisValue(value, channel);
169                     if (channel == null) {
170                         logger.debug("Adding channel: {} with item type: {}", obisChannelString, itemType);
171
172                         // channel has not been created yet
173                         ChannelBuilder channelBuilder = ChannelBuilder
174                                 .create(new ChannelUID(thing.getUID(), obisChannelString), itemType)
175                                 .withType(channelTypeId);
176
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();
188
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());
195                         }
196                     }
197
198                     if (!channel.getProperties().containsKey(SmartMeterBindingConstants.CHANNEL_PROPERTY_OBIS)) {
199                         addObisPropertyToChannel(obis, channel);
200                     }
201                     if (state != null) {
202                         updateState(channel.getUID(), state);
203                     }
204
205                     updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE);
206                 } else {
207                     logger.warn("No ChannelType found for OBIS {}", obis);
208                 }
209             }
210
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());
222             }
223
224             @Override
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());
232             }
233
234             @Override
235             public void errorOccurred(Throwable e) {
236                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getLocalizedMessage());
237             }
238         };
239         this.smlDevice.addValueChangeListener(valueChangeListener);
240
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));
244     }
245
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);
251                 if (obis != null) {
252                     MeterValue<?> value = this.smlDevice.getMeterValue(obis);
253                     if (value != null) {
254                         State state = getStateForObisValue(value, channel);
255                         if (state != null) {
256                             updateState(channel.getUID(), state);
257                         }
258                     }
259                 }
260             }
261         }
262     }
263
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();
269         if (unit != null) {
270             valueString += " " + value.getUnit();
271         }
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()));
279             }
280         }
281         return state;
282     }
283
284     private <Q extends Quantity<Q>> State applyConformity(Channel channel, QuantityType<Q> currentState) {
285         try {
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);
289         }
290         return currentState;
291     }
292 }