]> git.basschouten.com Git - openhab-addons.git/blob
087b939ba7d188708396907c7e37cfa674b2c23a
[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.hydrawise.internal.handler;
14
15 import static org.openhab.binding.hydrawise.internal.HydrawiseBindingConstants.*;
16
17 import java.time.Instant;
18 import java.time.OffsetDateTime;
19 import java.time.ZoneOffset;
20 import java.time.ZonedDateTime;
21 import java.time.format.DateTimeFormatter;
22 import java.time.temporal.ChronoUnit;
23 import java.util.Collections;
24 import java.util.HashMap;
25 import java.util.List;
26 import java.util.Locale;
27 import java.util.Map;
28 import java.util.concurrent.atomic.AtomicReference;
29
30 import javax.measure.quantity.Speed;
31 import javax.measure.quantity.Temperature;
32 import javax.measure.quantity.Volume;
33
34 import org.eclipse.jdt.annotation.NonNullByDefault;
35 import org.eclipse.jdt.annotation.Nullable;
36 import org.openhab.binding.hydrawise.internal.HydrawiseControllerListener;
37 import org.openhab.binding.hydrawise.internal.api.HydrawiseAuthenticationException;
38 import org.openhab.binding.hydrawise.internal.api.HydrawiseCommandException;
39 import org.openhab.binding.hydrawise.internal.api.HydrawiseConnectionException;
40 import org.openhab.binding.hydrawise.internal.api.graphql.HydrawiseGraphQLClient;
41 import org.openhab.binding.hydrawise.internal.api.graphql.dto.Controller;
42 import org.openhab.binding.hydrawise.internal.api.graphql.dto.Forecast;
43 import org.openhab.binding.hydrawise.internal.api.graphql.dto.Sensor;
44 import org.openhab.binding.hydrawise.internal.api.graphql.dto.UnitValue;
45 import org.openhab.binding.hydrawise.internal.api.graphql.dto.Zone;
46 import org.openhab.binding.hydrawise.internal.api.graphql.dto.ZoneRun;
47 import org.openhab.binding.hydrawise.internal.config.HydrawiseControllerConfiguration;
48 import org.openhab.core.library.types.DateTimeType;
49 import org.openhab.core.library.types.DecimalType;
50 import org.openhab.core.library.types.OnOffType;
51 import org.openhab.core.library.types.QuantityType;
52 import org.openhab.core.library.types.StringType;
53 import org.openhab.core.library.unit.ImperialUnits;
54 import org.openhab.core.library.unit.SIUnits;
55 import org.openhab.core.library.unit.Units;
56 import org.openhab.core.thing.Bridge;
57 import org.openhab.core.thing.ChannelUID;
58 import org.openhab.core.thing.Thing;
59 import org.openhab.core.thing.ThingStatus;
60 import org.openhab.core.thing.ThingStatusDetail;
61 import org.openhab.core.thing.binding.BaseThingHandler;
62 import org.openhab.core.thing.binding.BridgeHandler;
63 import org.openhab.core.types.Command;
64 import org.openhab.core.types.RefreshType;
65 import org.openhab.core.types.State;
66 import org.openhab.core.types.UnDefType;
67 import org.slf4j.Logger;
68 import org.slf4j.LoggerFactory;
69
70 /**
71  * The {@link HydrawiseControllerHandler} is responsible for handling commands, which are
72  * sent to one of the channels.
73  *
74  * @author Dan Cunningham - Initial contribution
75  */
76
77 @NonNullByDefault
78 public class HydrawiseControllerHandler extends BaseThingHandler implements HydrawiseControllerListener {
79     private final Logger logger = LoggerFactory.getLogger(HydrawiseControllerHandler.class);
80     private static final int DEFAULT_SUSPEND_TIME_HOURS = 24;
81     private static final int DEFAULT_REFRESH_SECONDS = 15;
82     // All responses use US local time formats
83     private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("EEE, dd MMM uu HH:mm:ss Z",
84             Locale.US);
85     private final Map<String, @Nullable State> stateMap = Collections
86             .synchronizedMap(new HashMap<String, @Nullable State>());
87     private final Map<String, @Nullable Zone> zoneMaps = Collections
88             .synchronizedMap(new HashMap<String, @Nullable Zone>());
89     private int controllerId;
90
91     public HydrawiseControllerHandler(Thing thing) {
92         super(thing);
93     }
94
95     @Override
96     public void initialize() {
97         HydrawiseControllerConfiguration config = getConfigAs(HydrawiseControllerConfiguration.class);
98         controllerId = config.controllerId;
99         Bridge bridge = getBridge();
100         if (bridge != null) {
101             HydrawiseAccountHandler handler = (HydrawiseAccountHandler) bridge.getHandler();
102             if (handler != null) {
103                 handler.addControllerListeners(this);
104                 if (bridge.getStatus() == ThingStatus.ONLINE) {
105                     updateStatus(ThingStatus.ONLINE);
106                 } else {
107                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
108                 }
109             }
110         }
111     }
112
113     @Override
114     public void handleCommand(ChannelUID channelUID, Command command) {
115         logger.debug("handleCommand channel {} Command {}", channelUID.getAsString(), command.toFullString());
116         if (getThing().getStatus() != ThingStatus.ONLINE) {
117             logger.debug("Controller is NOT ONLINE and is not responding to commands");
118             return;
119         }
120
121         // remove our cached state for this, will be safely updated on next poll
122         stateMap.remove(channelUID.getAsString());
123
124         if (command instanceof RefreshType) {
125             // we already removed this from the cache
126             return;
127         }
128
129         HydrawiseGraphQLClient client = apiClient();
130         if (client == null) {
131             logger.debug("API client not found");
132             return;
133         }
134
135         String group = channelUID.getGroupId();
136         String channelId = channelUID.getIdWithoutGroup();
137         boolean allCommand = CHANNEL_GROUP_ALLZONES.equals(group);
138         Zone zone = zoneMaps.get(group);
139
140         if (!allCommand && zone == null) {
141             logger.debug("Zone not found {}", group);
142             return;
143         }
144
145         try {
146             switch (channelId) {
147                 case CHANNEL_ZONE_RUN_CUSTOM:
148                     if (!(command instanceof QuantityType<?>)) {
149                         logger.warn("Invalid command type for run custom {}", command.getClass().getName());
150                         return;
151                     }
152                     QuantityType<?> time = ((QuantityType<?>) command).toUnit(Units.SECOND);
153
154                     if (time == null) {
155                         return;
156                     }
157
158                     if (allCommand) {
159                         client.runAllRelays(controllerId, time.intValue());
160                     } else if (zone != null) {
161                         client.runRelay(zone.id, time.intValue());
162                     }
163                     break;
164                 case CHANNEL_ZONE_RUN:
165                     if (!(command instanceof OnOffType)) {
166                         logger.warn("Invalid command type for run {}", command.getClass().getName());
167                         return;
168                     }
169                     if (allCommand) {
170                         if (command == OnOffType.ON) {
171                             client.runAllRelays(controllerId);
172                         } else {
173                             client.stopAllRelays(controllerId);
174                         }
175                     } else if (zone != null) {
176                         if (command == OnOffType.ON) {
177                             client.runRelay(zone.id);
178                         } else {
179                             client.stopRelay(zone.id);
180                         }
181                     }
182                     break;
183                 case CHANNEL_ZONE_SUSPEND:
184                     if (!(command instanceof OnOffType)) {
185                         logger.warn("Invalid command type for suspend {}", command.getClass().getName());
186                         return;
187                     }
188                     if (allCommand) {
189                         if (command == OnOffType.ON) {
190                             client.suspendAllRelays(controllerId, OffsetDateTime.now(ZoneOffset.UTC)
191                                     .plus(DEFAULT_SUSPEND_TIME_HOURS, ChronoUnit.HOURS).format(DATE_FORMATTER));
192                         } else {
193                             client.resumeAllRelays(controllerId);
194                         }
195                     } else if (zone != null) {
196                         if (command == OnOffType.ON) {
197                             client.suspendRelay(zone.id, OffsetDateTime.now(ZoneOffset.UTC)
198                                     .plus(DEFAULT_SUSPEND_TIME_HOURS, ChronoUnit.HOURS).format(DATE_FORMATTER));
199                         } else {
200                             client.resumeRelay(zone.id);
201                         }
202                     }
203                     break;
204                 case CHANNEL_ZONE_SUSPENDUNTIL:
205                     if (!(command instanceof DateTimeType)) {
206                         logger.warn("Invalid command type for suspend {}", command.getClass().getName());
207                         return;
208                     }
209                     if (allCommand) {
210                         client.suspendAllRelays(controllerId,
211                                 ((DateTimeType) command).getZonedDateTime().format(DATE_FORMATTER));
212                     } else if (zone != null) {
213                         client.suspendRelay(zone.id,
214                                 ((DateTimeType) command).getZonedDateTime().format(DATE_FORMATTER));
215                     }
216                     break;
217                 default:
218                     logger.warn("Uknown channelId {}", channelId);
219                     return;
220             }
221             HydrawiseAccountHandler handler = getAccountHandler();
222             if (handler != null) {
223                 handler.refreshData(DEFAULT_REFRESH_SECONDS);
224             }
225         } catch (HydrawiseCommandException | HydrawiseConnectionException e) {
226             logger.debug("Could not issue command", e);
227         } catch (HydrawiseAuthenticationException e) {
228             logger.debug("Credentials not valid");
229         }
230     }
231
232     @Override
233     public void onData(List<Controller> controllers) {
234         logger.trace("onData my controller id {}", controllerId);
235         controllers.stream().filter(c -> c.id == controllerId).findFirst().ifPresent(controller -> {
236             logger.trace("Updating Controller {} sensors {} forecast {} ", controller.id, controller.sensors,
237                     controller.location.forecast);
238             updateController(controller);
239             if (controller.sensors != null) {
240                 updateSensors(controller.sensors);
241             }
242             if (controller.location != null && controller.location.forecast != null) {
243                 updateForecast(controller.location.forecast);
244             }
245             if (controller.zones != null) {
246                 updateZones(controller.zones);
247             }
248
249             // update values with what the cloud tells us even though the controller may be offline
250             if (!controller.status.online) {
251                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
252                         String.format("Controller Offline: %s last seen %s", controller.status.summary,
253                                 secondsToDateTime(controller.status.lastContact.timestamp)));
254             } else if (getThing().getStatus() != ThingStatus.ONLINE) {
255                 updateStatus(ThingStatus.ONLINE);
256             }
257         });
258     }
259
260     @Override
261     public void channelLinked(ChannelUID channelUID) {
262         // clear our cached value so the new channel gets updated on the next poll
263         stateMap.remove(channelUID.getId());
264     }
265
266     private void updateController(Controller controller) {
267         updateGroupState(CHANNEL_GROUP_CONTROLLER_SYSTEM, CHANNEL_CONTROLLER_NAME, new StringType(controller.name));
268         updateGroupState(CHANNEL_GROUP_CONTROLLER_SYSTEM, CHANNEL_CONTROLLER_SUMMARY,
269                 new StringType(controller.status.summary));
270         updateGroupState(CHANNEL_GROUP_CONTROLLER_SYSTEM, CHANNEL_CONTROLLER_LAST_CONTACT,
271                 secondsToDateTime(controller.status.lastContact.timestamp));
272     }
273
274     private void updateZones(List<Zone> zones) {
275         AtomicReference<Boolean> anyRunning = new AtomicReference<Boolean>(false);
276         AtomicReference<Boolean> anySuspended = new AtomicReference<Boolean>(false);
277         for (Zone zone : zones) {
278             // there are 12 relays per expander, expanders will have a zoneNumber like:
279             // 10 for expander 0, relay 10 = zone10
280             // 101 for expander 1, relay 1 = zone13
281             // 212 for expander 2, relay 12 = zone36
282             // division of integers in Java give whole numbers, not remainders FYI
283             int zoneNumber = ((zone.number.value / 100) * 12) + (zone.number.value % 100);
284
285             String group = "zone" + zoneNumber;
286             zoneMaps.put(group, zone);
287             logger.trace("Updateing Zone {} {} ", group, zone.name);
288             updateGroupState(group, CHANNEL_ZONE_NAME, new StringType(zone.name));
289             updateGroupState(group, CHANNEL_ZONE_ICON, new StringType(BASE_IMAGE_URL + zone.icon.fileName));
290             if (zone.scheduledRuns != null) {
291                 updateGroupState(group, CHANNEL_ZONE_SUMMARY,
292                         zone.scheduledRuns.summary != null ? new StringType(zone.scheduledRuns.summary)
293                                 : UnDefType.UNDEF);
294                 ZoneRun nextRun = zone.scheduledRuns.nextRun;
295                 if (nextRun != null) {
296                     updateGroupState(group, CHANNEL_ZONE_DURATION, new QuantityType<>(nextRun.duration, Units.MINUTE));
297                     updateGroupState(group, CHANNEL_ZONE_NEXT_RUN_TIME_TIME,
298                             secondsToDateTime(nextRun.startTime.timestamp));
299                 } else {
300                     updateGroupState(group, CHANNEL_ZONE_DURATION, UnDefType.UNDEF);
301                     updateGroupState(group, CHANNEL_ZONE_NEXT_RUN_TIME_TIME, UnDefType.UNDEF);
302                 }
303                 ZoneRun currRunn = zone.scheduledRuns.currentRun;
304                 if (currRunn != null) {
305                     updateGroupState(group, CHANNEL_ZONE_RUN, OnOffType.ON);
306                     updateGroupState(group, CHANNEL_ZONE_TIME_LEFT, new QuantityType<>(
307                             currRunn.endTime.timestamp - Instant.now().getEpochSecond(), Units.SECOND));
308                     anyRunning.set(true);
309                 } else {
310                     updateGroupState(group, CHANNEL_ZONE_RUN, OnOffType.OFF);
311                     updateGroupState(group, CHANNEL_ZONE_TIME_LEFT, new QuantityType<>(0, Units.MINUTE));
312                 }
313             }
314             if (zone.status.suspendedUntil != null) {
315                 updateGroupState(group, CHANNEL_ZONE_SUSPEND, OnOffType.ON);
316                 updateGroupState(group, CHANNEL_ZONE_SUSPENDUNTIL,
317                         secondsToDateTime(zone.status.suspendedUntil.timestamp));
318                 anySuspended.set(true);
319             } else {
320                 updateGroupState(group, CHANNEL_ZONE_SUSPEND, OnOffType.OFF);
321                 updateGroupState(group, CHANNEL_ZONE_SUSPENDUNTIL, UnDefType.UNDEF);
322             }
323         }
324         updateGroupState(CHANNEL_GROUP_ALLZONES, CHANNEL_ZONE_RUN, anyRunning.get() ? OnOffType.ON : OnOffType.OFF);
325         updateGroupState(CHANNEL_GROUP_ALLZONES, CHANNEL_ZONE_SUSPEND,
326                 anySuspended.get() ? OnOffType.ON : OnOffType.OFF);
327         updateGroupState(CHANNEL_GROUP_ALLZONES, CHANNEL_ZONE_SUSPENDUNTIL, UnDefType.UNDEF);
328     }
329
330     private void updateSensors(List<Sensor> sensors) {
331         int i = 1;
332         for (Sensor sensor : sensors) {
333             String group = "sensor" + (i++);
334             updateGroupState(group, CHANNEL_SENSOR_NAME, new StringType(sensor.name));
335             if (sensor.model.offTimer != null) {
336                 updateGroupState(group, CHANNEL_SENSOR_OFFTIMER,
337                         new QuantityType<>(sensor.model.offTimer, Units.SECOND));
338             }
339             if (sensor.model.delay != null) {
340                 updateGroupState(group, CHANNEL_SENSOR_DELAY, new QuantityType<>(sensor.model.delay, Units.SECOND));
341             }
342             if (sensor.model.offLevel != null) {
343                 updateGroupState(group, CHANNEL_SENSOR_OFFLEVEL, new DecimalType(sensor.model.offLevel));
344             }
345             if (sensor.status.active != null) {
346                 updateGroupState(group, CHANNEL_SENSOR_ACTIVE, sensor.status.active ? OnOffType.ON : OnOffType.OFF);
347             }
348             if (sensor.status.waterFlow != null) {
349                 updateGroupState(group, CHANNEL_SENSOR_WATERFLOW,
350                         waterFlowToQuantityType(sensor.status.waterFlow.value, sensor.status.waterFlow.unit));
351             }
352         }
353     }
354
355     private void updateForecast(List<Forecast> forecasts) {
356         int i = 1;
357         for (Forecast forecast : forecasts) {
358             String group = "forecast" + (i++);
359             updateGroupState(group, CHANNEL_FORECAST_TIME, stringToDateTime(forecast.time));
360             updateGroupState(group, CHANNEL_FORECAST_CONDITIONS, new StringType(forecast.conditions));
361             updateGroupState(group, CHANNEL_FORECAST_HUMIDITY, new DecimalType(forecast.averageHumidity.intValue()));
362             updateTemperature(forecast.highTemperature, group, CHANNEL_FORECAST_TEMPERATURE_HIGH);
363             updateTemperature(forecast.lowTemperature, group, CHANNEL_FORECAST_TEMPERATURE_LOW);
364             updateWindspeed(forecast.averageWindSpeed, group, CHANNEL_FORECAST_WIND);
365             // this seems to sometimes be optional
366             if (forecast.evapotranspiration != null) {
367                 updateGroupState(group, CHANNEL_FORECAST_EVAPOTRANSPRIATION,
368                         new DecimalType(forecast.evapotranspiration.value.floatValue()));
369             }
370             updateGroupState(group, CHANNEL_FORECAST_PRECIPITATION,
371                     new DecimalType(forecast.precipitation.value.floatValue()));
372             updateGroupState(group, CHANNEL_FORECAST_PROBABILITYOFPRECIPITATION,
373                     new DecimalType(forecast.probabilityOfPrecipitation));
374
375         }
376     }
377
378     private void updateTemperature(UnitValue temperature, String group, String channel) {
379         logger.debug("TEMP {} {} {} {}", group, channel, temperature.unit, temperature.value);
380         updateGroupState(group, channel, new QuantityType<Temperature>(temperature.value,
381                 "\\u00b0F".equals(temperature.unit) ? ImperialUnits.FAHRENHEIT : SIUnits.CELSIUS));
382     }
383
384     private void updateWindspeed(UnitValue wind, String group, String channel) {
385         updateGroupState(group, channel, new QuantityType<Speed>(wind.value,
386                 "mph".equals(wind.unit) ? ImperialUnits.MILES_PER_HOUR : SIUnits.KILOMETRE_PER_HOUR));
387     }
388
389     private void updateGroupState(String group, String channelID, State state) {
390         String channelName = group + "#" + channelID;
391         State oldState = stateMap.put(channelName, state);
392         if (!state.equals(oldState)) {
393             ChannelUID channelUID = new ChannelUID(this.getThing().getUID(), channelName);
394             logger.debug("updateState updating {} {}", channelUID, state);
395             updateState(channelUID, state);
396         }
397     }
398
399     @Nullable
400     private HydrawiseAccountHandler getAccountHandler() {
401         Bridge bridge = getBridge();
402         if (bridge == null) {
403             logger.warn("No bridge found for thing");
404             return null;
405         }
406         BridgeHandler handler = bridge.getHandler();
407         if (handler == null) {
408             logger.warn("No handler found for bridge");
409             return null;
410         }
411         return ((HydrawiseAccountHandler) handler);
412     }
413
414     @Nullable
415     private HydrawiseGraphQLClient apiClient() {
416         HydrawiseAccountHandler handler = getAccountHandler();
417         if (handler == null) {
418             return null;
419         } else {
420             return handler.graphQLClient();
421         }
422     }
423
424     private DateTimeType secondsToDateTime(Integer seconds) {
425         Instant instant = Instant.ofEpochSecond(seconds);
426         ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, ZoneOffset.UTC);
427         return new DateTimeType(zdt);
428     }
429
430     private DateTimeType stringToDateTime(String date) {
431         ZonedDateTime zdt = ZonedDateTime.parse(date, DATE_FORMATTER);
432         return new DateTimeType(zdt);
433     }
434
435     private QuantityType<Volume> waterFlowToQuantityType(Number flow, String units) {
436         double waterFlow = flow.doubleValue();
437         if ("gals".equals(units)) {
438             waterFlow = waterFlow * 3.785;
439         }
440         return new QuantityType<>(waterFlow, Units.LITRE);
441     }
442 }