]> git.basschouten.com Git - openhab-addons.git/blob
c0a3e97bd9270e64e326b9acd89607b5d4525a98
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.netatmo.internal.handler;
14
15 import static org.openhab.binding.netatmo.internal.NetatmoBindingConstants.*;
16 import static org.openhab.core.library.unit.MetricPrefix.*;
17
18 import java.util.List;
19 import java.util.Map;
20 import java.util.Optional;
21
22 import javax.measure.Unit;
23 import javax.measure.quantity.Angle;
24 import javax.measure.quantity.Dimensionless;
25 import javax.measure.quantity.Length;
26 import javax.measure.quantity.Pressure;
27 import javax.measure.quantity.Speed;
28 import javax.measure.quantity.Temperature;
29
30 import org.eclipse.jdt.annotation.NonNullByDefault;
31 import org.eclipse.jdt.annotation.Nullable;
32 import org.openhab.binding.netatmo.internal.channelhelper.BatteryHelper;
33 import org.openhab.binding.netatmo.internal.channelhelper.RadioHelper;
34 import org.openhab.core.config.core.Configuration;
35 import org.openhab.core.i18n.TimeZoneProvider;
36 import org.openhab.core.library.unit.SIUnits;
37 import org.openhab.core.library.unit.SmartHomeUnits;
38 import org.openhab.core.thing.Bridge;
39 import org.openhab.core.thing.ChannelUID;
40 import org.openhab.core.thing.Thing;
41 import org.openhab.core.thing.ThingStatus;
42 import org.openhab.core.thing.ThingStatusDetail;
43 import org.openhab.core.thing.ThingStatusInfo;
44 import org.openhab.core.thing.binding.BaseThingHandler;
45 import org.openhab.core.thing.binding.BridgeHandler;
46 import org.openhab.core.thing.type.ChannelKind;
47 import org.openhab.core.types.Command;
48 import org.openhab.core.types.RefreshType;
49 import org.openhab.core.types.State;
50 import org.openhab.core.types.UnDefType;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53
54 /**
55  * {@link AbstractNetatmoThingHandler} is the abstract class that handles
56  * common behaviors of all netatmo things
57  *
58  * @author GaĆ«l L'hopital - Initial contribution OH2 version
59  * @author Rob Nielsen - Added day, week, and month measurements to the weather station and modules
60  *
61  */
62 @NonNullByDefault
63 public abstract class AbstractNetatmoThingHandler extends BaseThingHandler {
64     // Units of measurement of the data delivered by the API
65     public static final Unit<Temperature> API_TEMPERATURE_UNIT = SIUnits.CELSIUS;
66     public static final Unit<Dimensionless> API_HUMIDITY_UNIT = SmartHomeUnits.PERCENT;
67     public static final Unit<Pressure> API_PRESSURE_UNIT = HECTO(SIUnits.PASCAL);
68     public static final Unit<Speed> API_WIND_SPEED_UNIT = SIUnits.KILOMETRE_PER_HOUR;
69     public static final Unit<Angle> API_WIND_DIRECTION_UNIT = SmartHomeUnits.DEGREE_ANGLE;
70     public static final Unit<Length> API_RAIN_UNIT = MILLI(SIUnits.METRE);
71     public static final Unit<Dimensionless> API_CO2_UNIT = SmartHomeUnits.PARTS_PER_MILLION;
72     public static final Unit<Dimensionless> API_NOISE_UNIT = SmartHomeUnits.DECIBEL;
73
74     private final Logger logger = LoggerFactory.getLogger(AbstractNetatmoThingHandler.class);
75
76     protected final TimeZoneProvider timeZoneProvider;
77     private @Nullable RadioHelper radioHelper;
78     private @Nullable BatteryHelper batteryHelper;
79     protected @Nullable Configuration config;
80     private @Nullable NetatmoBridgeHandler bridgeHandler;
81
82     AbstractNetatmoThingHandler(Thing thing, final TimeZoneProvider timeZoneProvider) {
83         super(thing);
84         this.timeZoneProvider = timeZoneProvider;
85     }
86
87     @Override
88     public void initialize() {
89         logger.debug("initializing handler for thing {}", getThing().getUID());
90         Bridge bridge = getBridge();
91         initializeThing(bridge != null ? bridge.getStatus() : null);
92     }
93
94     @Override
95     public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
96         logger.debug("bridgeStatusChanged {} for thing {}", bridgeStatusInfo, getThing().getUID());
97         initializeThing(bridgeStatusInfo.getStatus());
98     }
99
100     private void initializeThing(@Nullable ThingStatus bridgeStatus) {
101         Bridge bridge = getBridge();
102         BridgeHandler bridgeHandler = bridge != null ? bridge.getHandler() : null;
103         if (bridgeHandler != null && bridgeStatus != null) {
104             if (bridgeStatus == ThingStatus.ONLINE) {
105                 config = getThing().getConfiguration();
106
107                 String signalLevel = thing.getProperties().get(PROPERTY_SIGNAL_LEVELS);
108                 radioHelper = signalLevel != null ? new RadioHelper(signalLevel) : null;
109                 String batteryLevel = thing.getProperties().get(PROPERTY_BATTERY_LEVELS);
110                 batteryHelper = batteryLevel != null ? new BatteryHelper(batteryLevel) : null;
111                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE, "Pending parent object initialization");
112
113                 initializeThing();
114             } else {
115                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
116             }
117         } else {
118             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_UNINITIALIZED);
119         }
120     }
121
122     protected abstract void initializeThing();
123
124     protected State getNAThingProperty(String channelId) {
125         Optional<State> result;
126
127         result = getBatteryHelper().flatMap(helper -> helper.getNAThingProperty(channelId));
128         if (result.isPresent()) {
129             return result.get();
130         }
131         result = getRadioHelper().flatMap(helper -> helper.getNAThingProperty(channelId));
132         if (result.isPresent()) {
133             return result.get();
134         }
135         return UnDefType.UNDEF;
136     }
137
138     protected void updateChannels() {
139         if (thing.getStatus() != ThingStatus.ONLINE) {
140             return;
141         }
142
143         updateDataChannels();
144
145         triggerEventChannels();
146     }
147
148     private void updateDataChannels() {
149         getThing().getChannels().stream().filter(channel -> !channel.getKind().equals(ChannelKind.TRIGGER))
150                 .forEach(channel -> {
151
152                     String channelId = channel.getUID().getId();
153                     if (isLinked(channelId)) {
154                         State state = getNAThingProperty(channelId);
155                         updateState(channel.getUID(), state);
156                     }
157                 });
158     }
159
160     /**
161      * Triggers all event/trigger channels
162      * (when a channel is triggered, a rule can get all other information from the updated non-trigger channels)
163      */
164     private void triggerEventChannels() {
165         getThing().getChannels().stream().filter(channel -> channel.getKind().equals(ChannelKind.TRIGGER))
166                 .forEach(channel -> triggerChannelIfRequired(channel.getUID().getId()));
167     }
168
169     /**
170      * Triggers the trigger channel with the given channel id when required (when an update is available)
171      *
172      * @param channelId channel id
173      */
174     protected void triggerChannelIfRequired(String channelId) {
175     }
176
177     @Override
178     public void handleCommand(ChannelUID channelUID, Command command) {
179         if (command == RefreshType.REFRESH) {
180             logger.debug("Refreshing {}", channelUID);
181             updateChannels();
182         }
183     }
184
185     protected Optional<NetatmoBridgeHandler> getBridgeHandler() {
186         if (bridgeHandler == null) {
187             Bridge bridge = getBridge();
188             if (bridge != null) {
189                 bridgeHandler = (NetatmoBridgeHandler) bridge.getHandler();
190             }
191         }
192         NetatmoBridgeHandler handler = bridgeHandler;
193         return handler != null ? Optional.of(handler) : Optional.empty();
194     }
195
196     protected Optional<AbstractNetatmoThingHandler> findNAThing(@Nullable String searchedId) {
197         return getBridgeHandler().flatMap(handler -> handler.findNAThing(searchedId));
198     }
199
200     public boolean matchesId(@Nullable String searchedId) {
201         return searchedId != null && searchedId.equalsIgnoreCase(getId());
202     }
203
204     protected @Nullable String getId() {
205         Configuration conf = config;
206         Object equipmentId = conf != null ? conf.get(EQUIPMENT_ID) : null;
207         if (equipmentId instanceof String) {
208             return ((String) equipmentId).toLowerCase();
209         }
210         return null;
211     }
212
213     protected void updateProperties(@Nullable Integer firmware, @Nullable String modelId) {
214         Map<String, String> properties = editProperties();
215         if (firmware != null || modelId != null) {
216             properties.put(Thing.PROPERTY_VENDOR, VENDOR);
217         }
218         if (firmware != null) {
219             properties.put(Thing.PROPERTY_FIRMWARE_VERSION, firmware.toString());
220         }
221         if (modelId != null) {
222             properties.put(Thing.PROPERTY_MODEL_ID, modelId);
223         }
224         updateProperties(properties);
225     }
226
227     protected Optional<RadioHelper> getRadioHelper() {
228         RadioHelper helper = radioHelper;
229         return helper != null ? Optional.of(helper) : Optional.empty();
230     }
231
232     protected Optional<BatteryHelper> getBatteryHelper() {
233         BatteryHelper helper = batteryHelper;
234         return helper != null ? Optional.of(helper) : Optional.empty();
235     }
236
237     public void updateMeasurements() {
238     }
239
240     public void getMeasurements(@Nullable String device, @Nullable String module, String scale, List<String> types,
241             List<String> channels, Map<String, Float> channelMeasurements) {
242         Optional<NetatmoBridgeHandler> handler = getBridgeHandler();
243         if (!handler.isPresent() || device == null) {
244             return;
245         }
246
247         if (types.size() != channels.size()) {
248             throw new IllegalArgumentException("types and channels lists are different sizes.");
249         }
250
251         List<Float> measurements = handler.get().getStationMeasureResponses(device, module, scale, types);
252         if (measurements.size() != types.size()) {
253             throw new IllegalArgumentException("types and measurements lists are different sizes.");
254         }
255
256         int i = 0;
257         for (Float measurement : measurements) {
258             channelMeasurements.put(channels.get(i++), measurement);
259         }
260     }
261
262     public void addMeasurement(List<String> channels, List<String> types, String channel, String type) {
263         if (isLinked(channel)) {
264             channels.add(channel);
265             types.add(type);
266         }
267     }
268
269     protected boolean isReachable() {
270         return true;
271     }
272 }