]> git.basschouten.com Git - openhab-addons.git/blob
3b24fc5818f99371cad301a19cbe4a951e6a2a0e
[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         int i = 1;
278         for (Zone zone : zones) {
279             String group = "zone" + (i++);
280             zoneMaps.put(group, zone);
281             logger.trace("Updateing Zone {} {} ", group, zone.name);
282             updateGroupState(group, CHANNEL_ZONE_NAME, new StringType(zone.name));
283             updateGroupState(group, CHANNEL_ZONE_ICON, new StringType(BASE_IMAGE_URL + zone.icon.fileName));
284             if (zone.scheduledRuns != null) {
285                 updateGroupState(group, CHANNEL_ZONE_SUMMARY,
286                         zone.scheduledRuns.summary != null ? new StringType(zone.scheduledRuns.summary)
287                                 : UnDefType.UNDEF);
288                 ZoneRun nextRun = zone.scheduledRuns.nextRun;
289                 if (nextRun != null) {
290                     updateGroupState(group, CHANNEL_ZONE_DURATION, new QuantityType<>(nextRun.duration, Units.MINUTE));
291                     updateGroupState(group, CHANNEL_ZONE_NEXT_RUN_TIME_TIME,
292                             secondsToDateTime(nextRun.startTime.timestamp));
293                 } else {
294                     updateGroupState(group, CHANNEL_ZONE_DURATION, UnDefType.UNDEF);
295                     updateGroupState(group, CHANNEL_ZONE_NEXT_RUN_TIME_TIME, UnDefType.UNDEF);
296                 }
297                 ZoneRun currRunn = zone.scheduledRuns.currentRun;
298                 if (currRunn != null) {
299                     updateGroupState(group, CHANNEL_ZONE_RUN, OnOffType.ON);
300                     updateGroupState(group, CHANNEL_ZONE_TIME_LEFT, new QuantityType<>(
301                             currRunn.endTime.timestamp - Instant.now().getEpochSecond(), Units.SECOND));
302                     anyRunning.set(true);
303                 } else {
304                     updateGroupState(group, CHANNEL_ZONE_RUN, OnOffType.OFF);
305                     updateGroupState(group, CHANNEL_ZONE_TIME_LEFT, new QuantityType<>(0, Units.MINUTE));
306                 }
307             }
308             if (zone.status.suspendedUntil != null) {
309                 updateGroupState(group, CHANNEL_ZONE_SUSPEND, OnOffType.ON);
310                 updateGroupState(group, CHANNEL_ZONE_SUSPENDUNTIL,
311                         secondsToDateTime(zone.status.suspendedUntil.timestamp));
312                 anySuspended.set(true);
313             } else {
314                 updateGroupState(group, CHANNEL_ZONE_SUSPEND, OnOffType.OFF);
315                 updateGroupState(group, CHANNEL_ZONE_SUSPENDUNTIL, UnDefType.UNDEF);
316             }
317         }
318         updateGroupState(CHANNEL_GROUP_ALLZONES, CHANNEL_ZONE_RUN, anyRunning.get() ? OnOffType.ON : OnOffType.OFF);
319         updateGroupState(CHANNEL_GROUP_ALLZONES, CHANNEL_ZONE_SUSPEND,
320                 anySuspended.get() ? OnOffType.ON : OnOffType.OFF);
321         updateGroupState(CHANNEL_GROUP_ALLZONES, CHANNEL_ZONE_SUSPENDUNTIL, UnDefType.UNDEF);
322     }
323
324     private void updateSensors(List<Sensor> sensors) {
325         int i = 1;
326         for (Sensor sensor : sensors) {
327             String group = "sensor" + (i++);
328             updateGroupState(group, CHANNEL_SENSOR_NAME, new StringType(sensor.name));
329             if (sensor.model.offTimer != null) {
330                 updateGroupState(group, CHANNEL_SENSOR_OFFTIMER,
331                         new QuantityType<>(sensor.model.offTimer, Units.SECOND));
332             }
333             if (sensor.model.delay != null) {
334                 updateGroupState(group, CHANNEL_SENSOR_DELAY, new QuantityType<>(sensor.model.delay, Units.SECOND));
335             }
336             if (sensor.model.offLevel != null) {
337                 updateGroupState(group, CHANNEL_SENSOR_OFFLEVEL, new DecimalType(sensor.model.offLevel));
338             }
339             if (sensor.status.active != null) {
340                 updateGroupState(group, CHANNEL_SENSOR_ACTIVE, sensor.status.active ? OnOffType.ON : OnOffType.OFF);
341             }
342             if (sensor.status.waterFlow != null) {
343                 updateGroupState(group, CHANNEL_SENSOR_WATERFLOW,
344                         waterFlowToQuantityType(sensor.status.waterFlow.value, sensor.status.waterFlow.unit));
345             }
346         }
347     }
348
349     private void updateForecast(List<Forecast> forecasts) {
350         int i = 1;
351         for (Forecast forecast : forecasts) {
352             String group = "forecast" + (i++);
353             updateGroupState(group, CHANNEL_FORECAST_TIME, stringToDateTime(forecast.time));
354             updateGroupState(group, CHANNEL_FORECAST_CONDITIONS, new StringType(forecast.conditions));
355             updateGroupState(group, CHANNEL_FORECAST_HUMIDITY, new DecimalType(forecast.averageHumidity.intValue()));
356             updateTemperature(forecast.highTemperature, group, CHANNEL_FORECAST_TEMPERATURE_HIGH);
357             updateTemperature(forecast.lowTemperature, group, CHANNEL_FORECAST_TEMPERATURE_LOW);
358             updateWindspeed(forecast.averageWindSpeed, group, CHANNEL_FORECAST_WIND);
359             // this seems to sometimes be optional
360             if (forecast.evapotranspiration != null) {
361                 updateGroupState(group, CHANNEL_FORECAST_EVAPOTRANSPRIATION,
362                         new DecimalType(forecast.evapotranspiration.value.floatValue()));
363             }
364             updateGroupState(group, CHANNEL_FORECAST_PRECIPITATION,
365                     new DecimalType(forecast.precipitation.value.floatValue()));
366             updateGroupState(group, CHANNEL_FORECAST_PROBABILITYOFPRECIPITATION,
367                     new DecimalType(forecast.probabilityOfPrecipitation));
368
369         }
370     }
371
372     private void updateTemperature(UnitValue temperature, String group, String channel) {
373         logger.debug("TEMP {} {} {} {}", group, channel, temperature.unit, temperature.value);
374         updateGroupState(group, channel, new QuantityType<Temperature>(temperature.value,
375                 "\\u00b0F".equals(temperature.unit) ? ImperialUnits.FAHRENHEIT : SIUnits.CELSIUS));
376     }
377
378     private void updateWindspeed(UnitValue wind, String group, String channel) {
379         updateGroupState(group, channel, new QuantityType<Speed>(wind.value,
380                 "mph".equals(wind.unit) ? ImperialUnits.MILES_PER_HOUR : SIUnits.KILOMETRE_PER_HOUR));
381     }
382
383     private void updateGroupState(String group, String channelID, State state) {
384         String channelName = group + "#" + channelID;
385         State oldState = stateMap.put(channelName, state);
386         if (!state.equals(oldState)) {
387             ChannelUID channelUID = new ChannelUID(this.getThing().getUID(), channelName);
388             logger.debug("updateState updating {} {}", channelUID, state);
389             updateState(channelUID, state);
390         }
391     }
392
393     @Nullable
394     private HydrawiseAccountHandler getAccountHandler() {
395         Bridge bridge = getBridge();
396         if (bridge == null) {
397             logger.warn("No bridge found for thing");
398             return null;
399         }
400         BridgeHandler handler = bridge.getHandler();
401         if (handler == null) {
402             logger.warn("No handler found for bridge");
403             return null;
404         }
405         return ((HydrawiseAccountHandler) handler);
406     }
407
408     @Nullable
409     private HydrawiseGraphQLClient apiClient() {
410         HydrawiseAccountHandler handler = getAccountHandler();
411         if (handler == null) {
412             return null;
413         } else {
414             return handler.graphQLClient();
415         }
416     }
417
418     private DateTimeType secondsToDateTime(Integer seconds) {
419         Instant instant = Instant.ofEpochSecond(seconds);
420         ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, ZoneOffset.UTC);
421         return new DateTimeType(zdt);
422     }
423
424     private DateTimeType stringToDateTime(String date) {
425         ZonedDateTime zdt = ZonedDateTime.parse(date, DATE_FORMATTER);
426         return new DateTimeType(zdt);
427     }
428
429     private QuantityType<Volume> waterFlowToQuantityType(Number flow, String units) {
430         double waterFlow = flow.doubleValue();
431         if ("gals".equals(units)) {
432             waterFlow = waterFlow * 3.785;
433         }
434         return new QuantityType<>(waterFlow, Units.LITRE);
435     }
436 }