]> git.basschouten.com Git - openhab-addons.git/blob
aabef9d2e77400b3ac631af889efa44dc6cae5fd
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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.dsmr.internal.handler;
14
15 import java.util.Collections;
16 import java.util.List;
17 import java.util.Map.Entry;
18 import java.util.concurrent.ScheduledFuture;
19 import java.util.concurrent.TimeUnit;
20
21 import org.eclipse.jdt.annotation.NonNullByDefault;
22 import org.eclipse.jdt.annotation.Nullable;
23 import org.openhab.binding.dsmr.internal.device.cosem.CosemObject;
24 import org.openhab.binding.dsmr.internal.device.p1telegram.P1Telegram;
25 import org.openhab.binding.dsmr.internal.device.p1telegram.P1TelegramListener;
26 import org.openhab.binding.dsmr.internal.meter.DSMRMeter;
27 import org.openhab.binding.dsmr.internal.meter.DSMRMeterConfiguration;
28 import org.openhab.binding.dsmr.internal.meter.DSMRMeterConstants;
29 import org.openhab.binding.dsmr.internal.meter.DSMRMeterDescriptor;
30 import org.openhab.binding.dsmr.internal.meter.DSMRMeterType;
31 import org.openhab.core.thing.ChannelUID;
32 import org.openhab.core.thing.Thing;
33 import org.openhab.core.thing.ThingStatus;
34 import org.openhab.core.thing.ThingStatusDetail;
35 import org.openhab.core.thing.ThingStatusInfo;
36 import org.openhab.core.thing.binding.BaseThingHandler;
37 import org.openhab.core.types.Command;
38 import org.openhab.core.types.RefreshType;
39 import org.openhab.core.types.State;
40 import org.openhab.core.types.UnDefType;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 /**
45  * The MeterHandler will create logic DSMR meter ThingTypes
46  *
47  * @author M. Volaart - Initial contribution
48  * @author Hilbrand Bouwkamp - Separated thing state update cycle from meter values received cycle
49  */
50 @NonNullByDefault
51 public class DSMRMeterHandler extends BaseThingHandler implements P1TelegramListener {
52
53     private final Logger logger = LoggerFactory.getLogger(DSMRMeterHandler.class);
54
55     /**
56      * The DSMRMeter instance.
57      */
58     private @NonNullByDefault({}) DSMRMeter meter;
59
60     /**
61      * Last received cosem objects.
62      */
63     private List<CosemObject> lastReceivedValues = Collections.emptyList();
64
65     /**
66      * Reference to the meter watchdog.
67      */
68     private @NonNullByDefault({}) ScheduledFuture<?> meterWatchdog;
69
70     /**
71      * The M-bus channel this meter is on, or if the channel is irrelevant is set to unknown channel
72      */
73     private int channel = DSMRMeterConstants.UNKNOWN_CHANNEL;
74
75     /**
76      * Creates a new MeterHandler for the given Thing.
77      *
78      * @param thing {@link Thing} to create the MeterHandler for
79      */
80     public DSMRMeterHandler(Thing thing) {
81         super(thing);
82     }
83
84     /**
85      * DSMR Meter don't support handling commands
86      */
87     @Override
88     public void handleCommand(ChannelUID channelUID, Command command) {
89         if (command == RefreshType.REFRESH) {
90             updateState();
91         }
92     }
93
94     /**
95      * Initializes a DSMR Meter
96      *
97      * This method will load the corresponding configuration
98      */
99     @Override
100     public void initialize() {
101         logger.debug("Initialize MeterHandler for Thing {}", getThing().getUID());
102         DSMRMeterType meterType;
103
104         try {
105             meterType = DSMRMeterType.valueOf(getThing().getThingTypeUID().getId().toUpperCase());
106         } catch (IllegalArgumentException iae) {
107             logger.warn(
108                     "{} could not be initialized due to an invalid meterType {}. Delete this Thing if the problem persists.",
109                     getThing(), getThing().getThingTypeUID().getId().toUpperCase());
110             updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_ERROR,
111                     "@text/error.configuration.invalidmetertype");
112             return;
113         }
114         DSMRMeterConfiguration meterConfig = getConfigAs(DSMRMeterConfiguration.class);
115         channel = meterType.meterKind.isChannelRelevant() ? meterConfig.channel : DSMRMeterConstants.UNKNOWN_CHANNEL;
116         DSMRMeterDescriptor meterDescriptor = new DSMRMeterDescriptor(meterType, channel);
117         meter = new DSMRMeter(meterDescriptor);
118         meterWatchdog = scheduler.scheduleWithFixedDelay(this::updateState, meterConfig.refresh, meterConfig.refresh,
119                 TimeUnit.SECONDS);
120         updateStatus(ThingStatus.UNKNOWN);
121     }
122
123     @Override
124     public void dispose() {
125         if (meterWatchdog != null) {
126             meterWatchdog.cancel(false);
127             meterWatchdog = null;
128         }
129     }
130
131     /**
132      * Updates the state of all channels from the last received Cosem values from the meter. The lastReceivedValues are
133      * cleared after processing here so when it does contain values the next time this method is called and it contains
134      * values those are new values.
135      */
136     private synchronized void updateState() {
137         logger.trace("Update state for device: {}", getThing().getThingTypeUID().getId());
138         if (!lastReceivedValues.isEmpty()) {
139             for (CosemObject cosemObject : lastReceivedValues) {
140                 String channel = cosemObject.getType().name().toLowerCase();
141
142                 for (Entry<String, ? extends State> entry : cosemObject.getCosemValues().entrySet()) {
143                     if (!entry.getKey().isEmpty()) {
144                         /* CosemObject has a specific sub channel */
145                         channel += "_" + entry.getKey();
146                     }
147                     State newState = entry.getValue();
148                     logger.debug("Updating state for channel {} to value {}", channel, newState);
149                     updateState(channel, newState);
150                 }
151             }
152             if (getThing().getStatus() != ThingStatus.ONLINE) {
153                 updateStatus(ThingStatus.ONLINE);
154             }
155             lastReceivedValues = Collections.emptyList();
156         }
157     }
158
159     /**
160      * Callback for received meter values. When this method is called but the telegram has no values for this meter this
161      * meter is set to offline because something is wrong, possible the meter has been removed.
162      *
163      * @param telegram The received telegram
164      */
165     @Override
166     public void telegramReceived(P1Telegram telegram) {
167         lastReceivedValues = Collections.emptyList();
168         final DSMRMeter localMeter = meter;
169
170         if (localMeter == null) {
171             return;
172         }
173         List<CosemObject> filteredValues = localMeter.filterMeterValues(telegram.getCosemObjects(), channel);
174
175         if (filteredValues.isEmpty()) {
176             if (getThing().getStatus() == ThingStatus.ONLINE) {
177                 setDeviceOffline(ThingStatusDetail.COMMUNICATION_ERROR, "@text/error.thing.nodata");
178             }
179         } else {
180             if (logger.isTraceEnabled()) {
181                 logger.trace("Received {} objects for {}", filteredValues.size(), getThing().getThingTypeUID().getId());
182             }
183             lastReceivedValues = filteredValues;
184             if (getThing().getStatus() != ThingStatus.ONLINE) {
185                 updateState();
186             }
187         }
188     }
189
190     @Override
191     public synchronized void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
192         if (bridgeStatusInfo.getStatus() == ThingStatus.ONLINE
193                 && getThing().getStatusInfo().getStatusDetail() == ThingStatusDetail.BRIDGE_OFFLINE) {
194             // Set status to offline --> Thing will become online after receiving meter values
195             setDeviceOffline(ThingStatusDetail.NONE, null);
196         } else if (bridgeStatusInfo.getStatus() == ThingStatus.OFFLINE) {
197             setDeviceOffline(ThingStatusDetail.BRIDGE_OFFLINE, null);
198         }
199     }
200
201     /**
202      * @return Returns the {@link DSMRMeterDescriptor} this object is configured with
203      */
204     public @Nullable DSMRMeterDescriptor getMeterDescriptor() {
205         return meter == null ? null : meter.getMeterDescriptor();
206     }
207
208     /**
209      * Convenience method to set the meter off line.
210      *
211      * @param status off line status
212      * @param details off line detailed message
213      */
214     private void setDeviceOffline(ThingStatusDetail status, @Nullable String details) {
215         updateStatus(ThingStatus.OFFLINE, status, details);
216         getThing().getChannels().forEach(c -> updateState(c.getUID(), UnDefType.NULL));
217     }
218 }