]> git.basschouten.com Git - openhab-addons.git/blob
3c854a353a326cd04e02fb4a245c33a79805a918
[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.iaqualink.internal.handler;
14
15 import static org.openhab.core.library.unit.ImperialUnits.FAHRENHEIT;
16 import static org.openhab.core.library.unit.SIUnits.CELSIUS;
17
18 import java.io.IOException;
19 import java.math.BigDecimal;
20 import java.math.RoundingMode;
21 import java.util.ArrayList;
22 import java.util.Arrays;
23 import java.util.Collections;
24 import java.util.HashMap;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Objects;
28 import java.util.Optional;
29 import java.util.concurrent.ScheduledFuture;
30 import java.util.concurrent.TimeUnit;
31
32 import javax.measure.Unit;
33 import javax.measure.quantity.Temperature;
34
35 import org.eclipse.jdt.annotation.NonNullByDefault;
36 import org.eclipse.jdt.annotation.Nullable;
37 import org.eclipse.jetty.client.HttpClient;
38 import org.openhab.binding.iaqualink.internal.IAqualinkBindingConstants;
39 import org.openhab.binding.iaqualink.internal.api.IAqualinkClient;
40 import org.openhab.binding.iaqualink.internal.api.IAqualinkClient.NotAuthorizedException;
41 import org.openhab.binding.iaqualink.internal.api.dto.AccountInfo;
42 import org.openhab.binding.iaqualink.internal.api.dto.Auxiliary;
43 import org.openhab.binding.iaqualink.internal.api.dto.Device;
44 import org.openhab.binding.iaqualink.internal.api.dto.Home;
45 import org.openhab.binding.iaqualink.internal.api.dto.OneTouch;
46 import org.openhab.binding.iaqualink.internal.config.IAqualinkConfiguration;
47 import org.openhab.core.library.types.DecimalType;
48 import org.openhab.core.library.types.OnOffType;
49 import org.openhab.core.library.types.PercentType;
50 import org.openhab.core.library.types.QuantityType;
51 import org.openhab.core.library.types.StringType;
52 import org.openhab.core.thing.Channel;
53 import org.openhab.core.thing.ChannelUID;
54 import org.openhab.core.thing.Thing;
55 import org.openhab.core.thing.ThingStatus;
56 import org.openhab.core.thing.ThingStatusDetail;
57 import org.openhab.core.thing.binding.BaseThingHandler;
58 import org.openhab.core.thing.binding.builder.ChannelBuilder;
59 import org.openhab.core.thing.binding.builder.ThingBuilder;
60 import org.openhab.core.thing.type.ChannelTypeUID;
61 import org.openhab.core.types.Command;
62 import org.openhab.core.types.RefreshType;
63 import org.openhab.core.types.State;
64 import org.openhab.core.types.UnDefType;
65 import org.slf4j.Logger;
66 import org.slf4j.LoggerFactory;
67
68 /**
69  *
70  * iAquaLink Control Binding
71  *
72  * iAquaLink controllers allow remote access to Jandy/Zodiac pool systems. This
73  * binding allows openHAB to both monitor and control a pool system through
74  * these controllers.
75  *
76  * The {@link IAqualinkHandler} is responsible for handling commands, which
77  * are sent to one of the channels.
78  *
79  * @author Dan Cunningham - Initial contribution
80  */
81 @NonNullByDefault
82 public class IAqualinkHandler extends BaseThingHandler {
83
84     private final Logger logger = LoggerFactory.getLogger(IAqualinkHandler.class);
85
86     /**
87      * Minimum amount of time we can poll for updates
88      */
89     private static final int MIN_REFRESH_SECONDS = 5;
90
91     /**
92      * Minimum amount of time we can poll after a command
93      */
94     private static final int COMMAND_REFRESH_SECONDS = 5;
95
96     /**
97      * Default iAqulink key used by existing clients in the marketplace
98      */
99     private static final String DEFAULT_API_KEY = "EOOEMOW4YR6QNB07";
100
101     /**
102      * Local cache of iAqualink states
103      */
104     private Map<String, State> stateMap = Collections.synchronizedMap(new HashMap<>());
105
106     /**
107      * Our poll rate
108      */
109     private int refresh;
110
111     /**
112      * fixed API key provided by iAqualink clients (Android, IOS), unknown if this will change in the future.
113      */
114
115     private @Nullable String apiKey;
116
117     /**
118      * Optional serial number of the pool controller to connect to, only useful if you have more then one controller
119      */
120     private @Nullable String serialNumber;
121
122     /**
123      * Server issued sessionId
124      */
125     private @Nullable String sessionId;
126
127     /**
128      * When we first connect we will dynamically create channels based on what the controller is configured for
129      */
130     private boolean firstRun;
131
132     /**
133      * Future to poll for updated
134      */
135     private @Nullable ScheduledFuture<?> pollFuture;
136
137     /**
138      * The client interface to the iAqualink Service
139      */
140     private IAqualinkClient client;
141
142     /**
143      * Temperature unit, will be set based on user setting
144      */
145     private Unit<Temperature> temperatureUnit = CELSIUS;
146
147     /**
148      * Constructs a new {@link IAqualinkHandler}
149      *
150      * @param thing
151      * @param httpClient
152      */
153     public IAqualinkHandler(Thing thing, HttpClient httpClient) {
154         super(thing);
155         client = new IAqualinkClient(httpClient);
156     }
157
158     @Override
159     public void initialize() {
160         // don't hold up initialize
161         scheduler.schedule(this::configure, 0, TimeUnit.SECONDS);
162     }
163
164     @Override
165     public void dispose() {
166         logger.debug("Handler disposed.");
167         clearPolling();
168     }
169
170     @Override
171     public void channelLinked(ChannelUID channelUID) {
172         // clear our cached value so the new channel gets updated on the next poll
173         stateMap.remove(channelUID.getAsString());
174     }
175
176     @Override
177     public void handleCommand(ChannelUID channelUID, Command command) {
178         logger.debug("handleCommand channel: {} command: {}", channelUID, command);
179
180         if (getThing().getStatus() != ThingStatus.ONLINE) {
181             logger.warn("Controller is not ONLINE and is not responding to commands");
182             return;
183         }
184
185         clearPolling();
186
187         String channelName = channelUID.getIdWithoutGroup();
188         // remove the current state to ensure we send an update
189         stateMap.remove(channelUID.getAsString());
190         try {
191             if (command instanceof RefreshType) {
192                 logger.debug("Channel {} state has been cleared", channelName);
193             } else if (channelName.startsWith("aux_")) {
194                 // Auxiliary Commands
195                 String auxId = channelName.replaceFirst("aux_", "");
196                 if (command instanceof PercentType) {
197                     client.dimmerCommand(serialNumber, sessionId, auxId, command.toString());
198                 } else if (command instanceof StringType) {
199                     String cmd = "off".equals(command.toString()) ? "0"
200                             : "on".equals(command.toString()) ? "1" : command.toString();
201                     client.lightCommand(serialNumber, sessionId, auxId, cmd,
202                             AuxiliaryType.fromChannelTypeUID(getChannelTypeUID(channelUID)).getSubType());
203                 } else if (command instanceof OnOffType onOffCommand) {
204                     // these are toggle commands and require we have the current state to turn on/off
205                     Auxiliary[] auxs = client.getAux(serialNumber, sessionId);
206                     Optional<Auxiliary> optional = Arrays.stream(auxs).filter(o -> o.getName().equals(channelName))
207                             .findFirst();
208                     if (optional.isPresent()) {
209                         State currentState = toState(channelName, "Switch", optional.get().getState());
210                         if (!currentState.equals(onOffCommand)) {
211                             client.auxSetCommand(serialNumber, sessionId, channelName);
212                         }
213                     }
214                 }
215             } else if (channelName.endsWith("_set_point")) {
216                 // Set Point Commands
217                 if ("spa_set_point".equals(channelName)) {
218                     BigDecimal value = commandToRoundedTemperature(command, temperatureUnit);
219                     if (value != null) {
220                         client.setSpaTemp(serialNumber, sessionId, value.floatValue());
221                     }
222                 } else if ("pool_set_point".equals(channelName)) {
223                     BigDecimal value = commandToRoundedTemperature(command, temperatureUnit);
224                     if (value != null) {
225                         client.setPoolTemp(serialNumber, sessionId, value.floatValue());
226                     }
227                 }
228             } else if (command instanceof OnOffType onOffCommand) {
229                 // these are toggle commands and require we have the current state to turn on/off
230                 if (channelName.startsWith("onetouch_")) {
231                     OneTouch[] ota = client.getOneTouch(serialNumber, sessionId);
232                     Optional<OneTouch> optional = Arrays.stream(ota).filter(o -> o.getName().equals(channelName))
233                             .findFirst();
234                     if (optional.isPresent()) {
235                         State currentState = toState(channelName, "Switch", optional.get().getState());
236                         if (!currentState.equals(onOffCommand)) {
237                             logger.debug("Sending command {} to {}", command, channelName);
238                             client.oneTouchSetCommand(serialNumber, sessionId, channelName);
239                         }
240                     }
241                 } else if (channelName.endsWith("heater") || channelName.endsWith("pump")) {
242                     String value = client.getHome(serialNumber, sessionId).getSerializedMap().get(channelName);
243                     State currentState = toState(channelName, "Switch", value);
244                     if (!currentState.equals(onOffCommand)) {
245                         logger.debug("Sending command {} to {}", command, channelName);
246                         client.homeScreenSetCommand(serialNumber, sessionId, channelName);
247                     }
248                 }
249             }
250             initPolling(COMMAND_REFRESH_SECONDS);
251         } catch (IOException e) {
252             logger.debug("Exception executing command", e);
253             initPolling(COMMAND_REFRESH_SECONDS);
254         } catch (NotAuthorizedException e) {
255             logger.debug("Authorization Exception sending command", e);
256             configure();
257         }
258     }
259
260     /**
261      * Configures this thing
262      */
263     private void configure() {
264         clearPolling();
265         firstRun = true;
266
267         IAqualinkConfiguration configuration = getConfig().as(IAqualinkConfiguration.class);
268         String username = configuration.userName;
269         String password = configuration.password;
270         String confSerialId = configuration.serialId;
271         String confApiKey = configuration.apiKey;
272
273         if (confApiKey != null && !confApiKey.isBlank()) {
274             this.apiKey = confApiKey;
275         } else {
276             this.apiKey = DEFAULT_API_KEY;
277         }
278
279         this.refresh = Math.max(configuration.refresh, MIN_REFRESH_SECONDS);
280
281         try {
282             AccountInfo accountInfo = client.login(username, password, apiKey);
283             sessionId = accountInfo.getSessionId();
284             if (sessionId == null) {
285                 throw new IOException("Response from controller not valid");
286             }
287             logger.debug("SessionID {}", sessionId);
288
289             Device[] devices = client.getDevices(apiKey, accountInfo.getAuthenticationToken(), accountInfo.getId());
290
291             if (devices.length == 0) {
292                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "No registered devices found");
293                 return;
294             }
295
296             if (confSerialId != null && !confSerialId.isBlank()) {
297                 serialNumber = confSerialId.replaceAll("[^a-zA-Z0-9]", "").toUpperCase();
298                 if (!Arrays.stream(devices).anyMatch(device -> device.getSerialNumber().equals(serialNumber))) {
299                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
300                             "No Device for given serialId found");
301                     return;
302                 }
303             } else {
304                 serialNumber = devices[0].getSerialNumber();
305             }
306
307             logger.debug("Using serial number {}", serialNumber);
308
309             initPolling(COMMAND_REFRESH_SECONDS);
310         } catch (IOException e) {
311             logger.debug("Could not connect to service {}", e.getMessage());
312             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
313         } catch (NotAuthorizedException e) {
314             logger.debug("Credentials not valid");
315             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Credentials not valid");
316         }
317     }
318
319     /**
320      * Starts/Restarts polling with an initial delay. This allows changes in the poll cycle for when commands are sent
321      * and we need to poll sooner then the next refresh cycle.
322      */
323     private synchronized void initPolling(int initialDelay) {
324         clearPolling();
325         pollFuture = scheduler.scheduleWithFixedDelay(this::pollController, initialDelay, refresh, TimeUnit.SECONDS);
326     }
327
328     /**
329      * Stops/clears this thing's polling future
330      */
331     private void clearPolling() {
332         ScheduledFuture<?> localFuture = pollFuture;
333         if (isFutureValid(localFuture)) {
334             if (localFuture != null) {
335                 localFuture.cancel(true);
336             }
337         }
338     }
339
340     private boolean isFutureValid(@Nullable ScheduledFuture<?> future) {
341         return future != null && !future.isCancelled();
342     }
343
344     /**
345      * Poll the controller for updates.
346      */
347     private void pollController() {
348         ScheduledFuture<?> localFuture = pollFuture;
349         try {
350             Home home = client.getHome(serialNumber, sessionId);
351
352             if ("Error".equals(home.getResponse())) {
353                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
354                         "Service reports controller status as: " + home.getStatus());
355                 return;
356             }
357
358             Map<String, String> map = home.getSerializedMap();
359             if (map != null) {
360                 temperatureUnit = "F".equalsIgnoreCase(map.get("temp_scale")) ? FAHRENHEIT : CELSIUS;
361                 map.forEach((k, v) -> {
362                     updatedState(k, v);
363                     if (k.endsWith("_heater")) {
364                         HeaterState hs = HeaterState.fromValue(v);
365                         updatedState(k + "_status", hs == null ? null : hs.getLabel());
366                     }
367                 });
368             }
369
370             OneTouch[] oneTouches = client.getOneTouch(serialNumber, sessionId);
371             Auxiliary[] auxes = client.getAux(serialNumber, sessionId);
372
373             if (firstRun) {
374                 firstRun = false;
375                 updateChannels(auxes, oneTouches);
376             }
377
378             for (OneTouch ot : oneTouches) {
379                 updatedState(ot.getName(), ot.getState());
380             }
381
382             for (Auxiliary aux : auxes) {
383                 switch (aux.getType()) {
384                     // dimmer uses subType for value
385                     case "1":
386                         updatedState(aux.getName(), aux.getSubtype());
387                         break;
388                     // Color lights do not report the color value, only on/off
389                     case "2":
390                         updatedState(aux.getName(), "0".equals(aux.getState()) ? "off" : "on");
391                         break;
392                     // all else are switches
393                     default:
394                         updatedState(aux.getName(), aux.getState());
395                 }
396             }
397
398             if (getThing().getStatus() != ThingStatus.ONLINE) {
399                 updateStatus(ThingStatus.ONLINE);
400             }
401         } catch (IOException e) {
402             // poller will continue to run, set offline until next run
403             logger.debug("Exception polling", e);
404             if (isFutureValid(localFuture)) {
405                 // only valid futures should set state, otherwise this exception was do to being canceled.
406                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
407             }
408         } catch (NotAuthorizedException e) {
409             // if are creds are not valid, we need to try re authorizing again
410             logger.debug("Authorization Exception during polling", e);
411             clearPolling();
412             configure();
413         }
414     }
415
416     /**
417      * Update a channel state only if the value of the channel has changed since our last poll.
418      *
419      * @param name
420      * @param value
421      */
422     private void updatedState(String name, @Nullable String value) {
423         logger.trace("updatedState {} : {}", name, value);
424         Channel channel = getThing().getChannel(name);
425         if (channel != null) {
426             State state = toState(name, channel.getAcceptedItemType(), value);
427             State oldState = stateMap.put(channel.getUID().getAsString(), state);
428             if (!state.equals(oldState)) {
429                 logger.trace("updating channel {} with state {} (old state {})", channel.getUID(), state, oldState);
430                 updateState(channel.getUID(), state);
431             }
432         }
433     }
434
435     /**
436      * Converts a {@link String} value to a {@link State} for a given
437      * {@link String} accepted type
438      *
439      * @param itemType
440      * @param value
441      * @return {@link State}
442      */
443     private State toState(String name, @Nullable String type, @Nullable String value) {
444         try {
445             if (value == null || value.isBlank()) {
446                 return UnDefType.UNDEF;
447             }
448
449             if (type == null) {
450                 return StringType.valueOf(value);
451             }
452
453             switch (type) {
454                 case "Number:Temperature":
455                     return new QuantityType<>(Float.parseFloat(value), temperatureUnit);
456                 case "Number":
457                     return new DecimalType(value);
458                 case "Dimmer":
459                     return new PercentType(value);
460                 case "Switch":
461                     return Integer.parseInt(value) > 0 ? OnOffType.ON : OnOffType.OFF;
462                 default:
463                     return StringType.valueOf(value);
464             }
465         } catch (IllegalArgumentException e) {
466             return UnDefType.UNDEF;
467         }
468     }
469
470     /**
471      * Creates channels based on what is supported by the controller.
472      */
473     private void updateChannels(Auxiliary[] auxes, OneTouch[] oneTouches) {
474         List<Channel> channels = new ArrayList<>(getThing().getChannels());
475         for (Auxiliary aux : auxes) {
476             ChannelUID channelUID = new ChannelUID(getThing().getUID(), aux.getName());
477             logger.debug("Add channel Aux Name: {} Label: {} Type: {} Subtype: {}", aux.getName(), aux.getLabel(),
478                     aux.getType(), aux.getSubtype());
479             switch (aux.getType()) {
480                 case "1":
481                     addNewChannelToList(channels, channelUID, "Dimmer",
482                             IAqualinkBindingConstants.CHANNEL_TYPE_UID_AUX_DIMMER, aux.getLabel());
483                     break;
484                 case "2": {
485                     addNewChannelToList(channels, channelUID, "String",
486                             AuxiliaryType.fromSubType(aux.getSubtype()).getChannelTypeUID(), aux.getLabel());
487                 }
488                     break;
489                 default:
490                     addNewChannelToList(channels, channelUID, "Switch",
491                             IAqualinkBindingConstants.CHANNEL_TYPE_UID_AUX_SWITCH, aux.getLabel());
492             }
493         }
494
495         for (OneTouch oneTouch : oneTouches) {
496             if ("0".equals(oneTouch.getStatus())) {
497                 // OneTouch is not enabled
498                 continue;
499             }
500
501             ChannelUID channelUID = new ChannelUID(getThing().getUID(), oneTouch.getName());
502             addNewChannelToList(channels, channelUID, "Switch", IAqualinkBindingConstants.CHANNEL_TYPE_UID_ONETOUCH,
503                     oneTouch.getLabel());
504         }
505
506         ThingBuilder thingBuilder = editThing();
507         thingBuilder.withChannels(channels);
508         updateThing(thingBuilder.build());
509     }
510
511     /**
512      * Adds a channel to the list of channels if the channel does not exist or is of a different type
513      *
514      */
515     private void addNewChannelToList(List<Channel> list, ChannelUID channelUID, String itemType,
516             ChannelTypeUID channelType, String label) {
517         // if there is no entry, add it
518         if (!list.stream().anyMatch(c -> c.getUID().equals(channelUID))) {
519             list.add(ChannelBuilder.create(channelUID, itemType).withType(channelType).withLabel(label).build());
520         } else if (list.removeIf(c -> c.getUID().equals(channelUID) && !channelType.equals(c.getChannelTypeUID()))) {
521             // this channel uid exists, but has a different type so remove and add our new one
522             list.add(ChannelBuilder.create(channelUID, itemType).withType(channelType).withLabel(label).build());
523         }
524     }
525
526     /**
527      * inspired by the openHAB Nest thermostat binding
528      */
529     @SuppressWarnings("unchecked")
530     private @Nullable BigDecimal commandToRoundedTemperature(Command command, Unit<Temperature> unit)
531             throws IllegalArgumentException {
532         QuantityType<Temperature> quantity;
533         if (command instanceof QuantityType) {
534             quantity = (QuantityType<Temperature>) command;
535         } else {
536             quantity = new QuantityType<>(new BigDecimal(command.toString()), unit);
537         }
538
539         QuantityType<Temperature> temparatureQuantity = quantity.toUnit(unit);
540         if (temparatureQuantity == null) {
541             return null;
542         }
543
544         BigDecimal value = temparatureQuantity.toBigDecimal();
545         BigDecimal increment = CELSIUS == unit ? new BigDecimal("0.5") : new BigDecimal("1");
546         BigDecimal divisor = value.divide(increment, 0, RoundingMode.HALF_UP);
547         return divisor.multiply(increment);
548     }
549
550     private ChannelTypeUID getChannelTypeUID(ChannelUID channelUID) {
551         Channel channel = getThing().getChannel(channelUID.getId());
552         Objects.requireNonNull(channel);
553         ChannelTypeUID channelTypeUID = channel.getChannelTypeUID();
554         Objects.requireNonNull(channelTypeUID);
555         return channelTypeUID;
556     }
557 }