]> git.basschouten.com Git - openhab-addons.git/blob
8bfdd12c1bc920e745a45b92daba7308abe6c521
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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.somfytahoma.internal.handler;
14
15 import static org.openhab.binding.somfytahoma.internal.SomfyTahomaBindingConstants.*;
16
17 import java.io.UnsupportedEncodingException;
18 import java.net.URLEncoder;
19 import java.nio.charset.StandardCharsets;
20 import java.time.Duration;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.HashMap;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.concurrent.ConcurrentLinkedQueue;
27 import java.util.concurrent.ExecutionException;
28 import java.util.concurrent.ScheduledFuture;
29 import java.util.concurrent.TimeUnit;
30 import java.util.concurrent.TimeoutException;
31
32 import org.eclipse.jdt.annotation.NonNullByDefault;
33 import org.eclipse.jdt.annotation.Nullable;
34 import org.eclipse.jetty.client.HttpClient;
35 import org.eclipse.jetty.client.api.ContentResponse;
36 import org.eclipse.jetty.client.api.Request;
37 import org.eclipse.jetty.client.util.StringContentProvider;
38 import org.eclipse.jetty.http.HttpHeader;
39 import org.eclipse.jetty.http.HttpMethod;
40 import org.openhab.binding.somfytahoma.internal.config.SomfyTahomaConfig;
41 import org.openhab.binding.somfytahoma.internal.discovery.SomfyTahomaItemDiscoveryService;
42 import org.openhab.binding.somfytahoma.internal.model.SomfyTahomaAction;
43 import org.openhab.binding.somfytahoma.internal.model.SomfyTahomaActionGroup;
44 import org.openhab.binding.somfytahoma.internal.model.SomfyTahomaApplyResponse;
45 import org.openhab.binding.somfytahoma.internal.model.SomfyTahomaDevice;
46 import org.openhab.binding.somfytahoma.internal.model.SomfyTahomaEvent;
47 import org.openhab.binding.somfytahoma.internal.model.SomfyTahomaLoginResponse;
48 import org.openhab.binding.somfytahoma.internal.model.SomfyTahomaRegisterEventsResponse;
49 import org.openhab.binding.somfytahoma.internal.model.SomfyTahomaSetup;
50 import org.openhab.binding.somfytahoma.internal.model.SomfyTahomaState;
51 import org.openhab.binding.somfytahoma.internal.model.SomfyTahomaStatus;
52 import org.openhab.binding.somfytahoma.internal.model.SomfyTahomaStatusResponse;
53 import org.openhab.core.cache.ExpiringCache;
54 import org.openhab.core.io.net.http.HttpClientFactory;
55 import org.openhab.core.thing.Bridge;
56 import org.openhab.core.thing.ChannelUID;
57 import org.openhab.core.thing.Thing;
58 import org.openhab.core.thing.ThingStatus;
59 import org.openhab.core.thing.ThingStatusDetail;
60 import org.openhab.core.thing.ThingStatusInfo;
61 import org.openhab.core.thing.binding.BaseBridgeHandler;
62 import org.openhab.core.thing.binding.ThingHandlerService;
63 import org.openhab.core.types.Command;
64 import org.slf4j.Logger;
65 import org.slf4j.LoggerFactory;
66
67 import com.google.gson.Gson;
68 import com.google.gson.JsonElement;
69 import com.google.gson.JsonSyntaxException;
70
71 /**
72  * The {@link SomfyTahomaBridgeHandler} is responsible for handling commands, which are
73  * sent to one of the channels.
74  *
75  * @author Ondrej Pecta - Initial contribution
76  */
77 @NonNullByDefault
78 public class SomfyTahomaBridgeHandler extends BaseBridgeHandler {
79
80     private final Logger logger = LoggerFactory.getLogger(SomfyTahomaBridgeHandler.class);
81
82     /**
83      * The shared HttpClient
84      */
85     private final HttpClient httpClient;
86
87     /**
88      * Future to poll for updates
89      */
90     private @Nullable ScheduledFuture<?> pollFuture;
91
92     /**
93      * Future to poll for status
94      */
95     private @Nullable ScheduledFuture<?> statusFuture;
96
97     /**
98      * Future to set reconciliation flag
99      */
100     private @Nullable ScheduledFuture<?> reconciliationFuture;
101
102     // List of futures used for command retries
103     private Collection<ScheduledFuture<?>> retryFutures = new ConcurrentLinkedQueue<ScheduledFuture<?>>();
104
105     /**
106      * List of executions
107      */
108     private Map<String, String> executions = new HashMap<>();
109
110     // Too many requests flag
111     private boolean tooManyRequests = false;
112
113     // Silent relogin flag
114     private boolean reLoginNeeded = false;
115
116     // Reconciliation flag
117     private boolean reconciliation = false;
118
119     /**
120      * Our configuration
121      */
122     protected SomfyTahomaConfig thingConfig = new SomfyTahomaConfig();
123
124     /**
125      * Id of registered events
126      */
127     private String eventsId = "";
128
129     private Map<String, SomfyTahomaDevice> devicePlaces = new HashMap<>();
130
131     private ExpiringCache<List<SomfyTahomaDevice>> cachedDevices = new ExpiringCache<>(Duration.ofSeconds(30),
132             this::getDevices);
133
134     // Gson & parser
135     private final Gson gson = new Gson();
136
137     public SomfyTahomaBridgeHandler(Bridge thing, HttpClientFactory httpClientFactory) {
138         super(thing);
139         this.httpClient = httpClientFactory.createHttpClient("somfy_" + thing.getUID().getId());
140     }
141
142     @Override
143     public void handleCommand(ChannelUID channelUID, Command command) {
144     }
145
146     @Override
147     public void initialize() {
148         thingConfig = getConfigAs(SomfyTahomaConfig.class);
149
150         try {
151             httpClient.start();
152         } catch (Exception e) {
153             logger.debug("Cannot start http client for: {}", thing.getBridgeUID().getId(), e);
154             return;
155         }
156
157         scheduler.execute(() -> {
158             login();
159             initPolling();
160             logger.debug("Initialize done...");
161         });
162     }
163
164     /**
165      * starts this things polling future
166      */
167     private void initPolling() {
168         stopPolling();
169         scheduleGetUpdates(10);
170
171         statusFuture = scheduler.scheduleWithFixedDelay(() -> {
172             refreshTahomaStates();
173         }, 60, thingConfig.getStatusTimeout(), TimeUnit.SECONDS);
174
175         reconciliationFuture = scheduler.scheduleWithFixedDelay(() -> {
176             enableReconciliation();
177         }, RECONCILIATION_TIME, RECONCILIATION_TIME, TimeUnit.SECONDS);
178     }
179
180     private void scheduleGetUpdates(long delay) {
181         pollFuture = scheduler.schedule(() -> {
182             getTahomaUpdates();
183             scheduleNextGetUpdates();
184         }, delay, TimeUnit.SECONDS);
185     }
186
187     private void scheduleNextGetUpdates() {
188         ScheduledFuture<?> localPollFuture = pollFuture;
189         if (localPollFuture != null) {
190             localPollFuture.cancel(false);
191         }
192         scheduleGetUpdates(executions.isEmpty() ? thingConfig.getRefresh() : 2);
193     }
194
195     public synchronized void login() {
196         String url;
197
198         if (thingConfig.getEmail().isEmpty() || thingConfig.getPassword().isEmpty()) {
199             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
200                     "Can not access device as username and/or password are null");
201             return;
202         }
203
204         if (tooManyRequests) {
205             logger.debug("Skipping login due to too many requests");
206             return;
207         }
208
209         if (ThingStatus.ONLINE == thing.getStatus() && !reLoginNeeded) {
210             logger.debug("No need to log in, because already logged in");
211             return;
212         }
213
214         reLoginNeeded = false;
215
216         try {
217             url = TAHOMA_API_URL + "login";
218             String urlParameters = "userId=" + urlEncode(thingConfig.getEmail()) + "&userPassword="
219                     + urlEncode(thingConfig.getPassword());
220
221             ContentResponse response = sendRequestBuilder(url, HttpMethod.POST)
222                     .content(new StringContentProvider(urlParameters),
223                             "application/x-www-form-urlencoded; charset=UTF-8")
224                     .send();
225
226             if (logger.isTraceEnabled()) {
227                 logger.trace("Login response: {}", response.getContentAsString());
228             }
229
230             SomfyTahomaLoginResponse data = gson.fromJson(response.getContentAsString(),
231                     SomfyTahomaLoginResponse.class);
232             if (data == null) {
233                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
234                         "Received invalid data (login)");
235             } else if (data.isSuccess()) {
236                 logger.debug("SomfyTahoma version: {}", data.getVersion());
237                 String id = registerEvents();
238                 if (id != null && !id.equals(UNAUTHORIZED)) {
239                     eventsId = id;
240                     logger.debug("Events id: {}", eventsId);
241                     updateStatus(ThingStatus.ONLINE);
242                 } else {
243                     logger.debug("Events id error: {}", id);
244                 }
245             } else {
246                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
247                         "Error logging in: " + data.getError());
248                 if (data.getError().startsWith(TOO_MANY_REQUESTS)) {
249                     setTooManyRequests();
250                 }
251             }
252         } catch (JsonSyntaxException e) {
253             logger.debug("Received invalid data (login)", e);
254             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Received invalid data (login)");
255         } catch (InterruptedException | ExecutionException | TimeoutException e) {
256             if (e instanceof ExecutionException) {
257                 if (isAuthenticationChallenge(e)) {
258                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
259                             "Authentication challenge");
260                     setTooManyRequests();
261                     return;
262                 }
263             }
264             logger.debug("Cannot get login cookie!", e);
265             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Cannot get login cookie");
266             if (e instanceof InterruptedException) {
267                 Thread.currentThread().interrupt();
268             }
269         }
270     }
271
272     private void setTooManyRequests() {
273         logger.debug("Too many requests error, suspending activity for {} seconds", SUSPEND_TIME);
274         tooManyRequests = true;
275         scheduler.schedule(this::enableLogin, SUSPEND_TIME, TimeUnit.SECONDS);
276     }
277
278     private @Nullable String registerEvents() {
279         SomfyTahomaRegisterEventsResponse response = invokeCallToURL(TAHOMA_EVENTS_URL + "register", "",
280                 HttpMethod.POST, SomfyTahomaRegisterEventsResponse.class);
281         return response != null ? response.getId() : null;
282     }
283
284     private String urlEncode(String text) {
285         try {
286             return URLEncoder.encode(text, StandardCharsets.UTF_8.toString());
287         } catch (UnsupportedEncodingException e) {
288             return text;
289         }
290     }
291
292     private void enableLogin() {
293         tooManyRequests = false;
294     }
295
296     private List<SomfyTahomaEvent> getEvents() {
297         SomfyTahomaEvent[] response = invokeCallToURL(TAHOMA_API_URL + "events/" + eventsId + "/fetch", "",
298                 HttpMethod.POST, SomfyTahomaEvent[].class);
299         return response != null ? List.of(response) : List.of();
300     }
301
302     @Override
303     public void handleRemoval() {
304         super.handleRemoval();
305         logout();
306     }
307
308     @Override
309     public Collection<Class<? extends ThingHandlerService>> getServices() {
310         return Collections.singleton(SomfyTahomaItemDiscoveryService.class);
311     }
312
313     @Override
314     public void dispose() {
315         cleanup();
316         super.dispose();
317     }
318
319     private void cleanup() {
320         logger.debug("Doing cleanup");
321         stopPolling();
322         executions.clear();
323         // cancel all scheduled retries
324         retryFutures.forEach(x -> x.cancel(false));
325
326         try {
327             httpClient.stop();
328         } catch (Exception e) {
329             logger.debug("Error during http client stopping", e);
330         }
331     }
332
333     @Override
334     public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
335         super.bridgeStatusChanged(bridgeStatusInfo);
336         if (ThingStatus.UNINITIALIZED == bridgeStatusInfo.getStatus()) {
337             cleanup();
338         }
339     }
340
341     /**
342      * Stops this thing's polling future
343      */
344     private void stopPolling() {
345         ScheduledFuture<?> localPollFuture = pollFuture;
346         if (localPollFuture != null && !localPollFuture.isCancelled()) {
347             localPollFuture.cancel(true);
348         }
349         ScheduledFuture<?> localStatusFuture = statusFuture;
350         if (localStatusFuture != null && !localStatusFuture.isCancelled()) {
351             localStatusFuture.cancel(true);
352         }
353         ScheduledFuture<?> localReconciliationFuture = reconciliationFuture;
354         if (localReconciliationFuture != null && !localReconciliationFuture.isCancelled()) {
355             localReconciliationFuture.cancel(true);
356         }
357     }
358
359     public List<SomfyTahomaActionGroup> listActionGroups() {
360         SomfyTahomaActionGroup[] list = invokeCallToURL(TAHOMA_API_URL + "actionGroups", "", HttpMethod.GET,
361                 SomfyTahomaActionGroup[].class);
362         return list != null ? List.of(list) : List.of();
363     }
364
365     public @Nullable SomfyTahomaSetup getSetup() {
366         SomfyTahomaSetup setup = invokeCallToURL(TAHOMA_API_URL + "setup", "", HttpMethod.GET, SomfyTahomaSetup.class);
367         if (setup != null) {
368             saveDevicePlaces(setup.getDevices());
369         }
370         return setup;
371     }
372
373     public List<SomfyTahomaDevice> getDevices() {
374         SomfyTahomaDevice[] response = invokeCallToURL(SETUP_URL + "devices", "", HttpMethod.GET,
375                 SomfyTahomaDevice[].class);
376         List<SomfyTahomaDevice> devices = response != null ? List.of(response) : List.of();
377         saveDevicePlaces(devices);
378         return devices;
379     }
380
381     public synchronized @Nullable SomfyTahomaDevice getCachedDevice(String url) {
382         List<SomfyTahomaDevice> devices = cachedDevices.getValue();
383         if (devices != null) {
384             for (SomfyTahomaDevice device : devices) {
385                 if (url.equals(device.getDeviceURL())) {
386                     return device;
387                 }
388             }
389         }
390         return null;
391     }
392
393     private void saveDevicePlaces(List<SomfyTahomaDevice> devices) {
394         devicePlaces.clear();
395         for (SomfyTahomaDevice device : devices) {
396             if (!device.getPlaceOID().isEmpty()) {
397                 SomfyTahomaDevice newDevice = new SomfyTahomaDevice();
398                 newDevice.setPlaceOID(device.getPlaceOID());
399                 newDevice.setWidget(device.getWidget());
400                 devicePlaces.put(device.getDeviceURL(), newDevice);
401             }
402         }
403     }
404
405     private void getTahomaUpdates() {
406         logger.debug("Getting Tahoma Updates...");
407         if (ThingStatus.OFFLINE == thing.getStatus() && !reLogin()) {
408             return;
409         }
410
411         List<SomfyTahomaEvent> events = getEvents();
412         logger.trace("Got total of {} events", events.size());
413         for (SomfyTahomaEvent event : events) {
414             processEvent(event);
415         }
416     }
417
418     private void processEvent(SomfyTahomaEvent event) {
419         logger.debug("Got event: {}", event.getName());
420         switch (event.getName()) {
421             case "ExecutionRegisteredEvent":
422                 processExecutionRegisteredEvent(event);
423                 break;
424             case "ExecutionStateChangedEvent":
425                 processExecutionChangedEvent(event);
426                 break;
427             case "DeviceStateChangedEvent":
428                 processStateChangedEvent(event);
429                 break;
430             case "RefreshAllDevicesStatesCompletedEvent":
431                 scheduler.schedule(this::updateThings, 1, TimeUnit.SECONDS);
432                 break;
433             case "GatewayAliveEvent":
434             case "GatewayDownEvent":
435                 processGatewayEvent(event);
436                 break;
437             default:
438                 // ignore other states
439         }
440     }
441
442     private synchronized void updateThings() {
443         boolean needsUpdate = reconciliation;
444
445         for (Thing th : getThing().getThings()) {
446             if (ThingStatus.ONLINE != th.getStatus()) {
447                 needsUpdate = true;
448             }
449         }
450
451         // update all states only if necessary
452         if (needsUpdate) {
453             updateAllStates();
454             reconciliation = false;
455         }
456     }
457
458     private void processExecutionRegisteredEvent(SomfyTahomaEvent event) {
459         boolean invalidData = false;
460         try {
461             JsonElement el = event.getAction();
462             if (el.isJsonArray()) {
463                 SomfyTahomaAction[] actions = gson.fromJson(el, SomfyTahomaAction[].class);
464                 if (actions == null) {
465                     invalidData = true;
466                 } else {
467                     for (SomfyTahomaAction action : actions) {
468                         registerExecution(action.getDeviceURL(), event.getExecId());
469                     }
470                 }
471             } else {
472                 SomfyTahomaAction action = gson.fromJson(el, SomfyTahomaAction.class);
473                 if (action == null) {
474                     invalidData = true;
475                 } else {
476                     registerExecution(action.getDeviceURL(), event.getExecId());
477                 }
478             }
479         } catch (JsonSyntaxException e) {
480             invalidData = true;
481         }
482         if (invalidData) {
483             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
484                     "Received invalid data (execution registered)");
485         }
486     }
487
488     private void processExecutionChangedEvent(SomfyTahomaEvent event) {
489         if (FAILED_EVENT.equals(event.getNewState()) || COMPLETED_EVENT.equals(event.getNewState())) {
490             logger.debug("Removing execution id: {}", event.getExecId());
491             unregisterExecution(event.getExecId());
492         }
493     }
494
495     private void registerExecution(String url, String execId) {
496         if (executions.containsKey(url)) {
497             executions.remove(url);
498             logger.debug("Previous execution exists for url: {}", url);
499         }
500         executions.put(url, execId);
501     }
502
503     private void unregisterExecution(String execId) {
504         if (executions.containsValue(execId)) {
505             executions.values().removeAll(Collections.singleton(execId));
506         } else {
507             logger.debug("Cannot remove execution id: {}, because it is not registered", execId);
508         }
509     }
510
511     private void processGatewayEvent(SomfyTahomaEvent event) {
512         // update gateway status
513         for (Thing th : getThing().getThings()) {
514             if (THING_TYPE_GATEWAY.equals(th.getThingTypeUID())) {
515                 SomfyTahomaGatewayHandler gatewayHandler = (SomfyTahomaGatewayHandler) th.getHandler();
516                 if (gatewayHandler != null && gatewayHandler.getGateWayId().equals(event.getGatewayId())) {
517                     gatewayHandler.refresh(STATUS);
518                 }
519             }
520         }
521     }
522
523     private synchronized void updateAllStates() {
524         logger.debug("Updating all states");
525         getDevices().forEach(device -> updateDevice(device));
526     }
527
528     private void updateDevice(SomfyTahomaDevice device) {
529         String url = device.getDeviceURL();
530         List<SomfyTahomaState> states = device.getStates();
531         updateDevice(url, states);
532     }
533
534     private void updateDevice(String url, List<SomfyTahomaState> states) {
535         Thing th = getThingByDeviceUrl(url);
536         if (th == null) {
537             return;
538         }
539         SomfyTahomaBaseThingHandler handler = (SomfyTahomaBaseThingHandler) th.getHandler();
540         if (handler != null) {
541             handler.updateThingStatus(states);
542             handler.updateThingChannels(states);
543         }
544     }
545
546     private void processStateChangedEvent(SomfyTahomaEvent event) {
547         String deviceUrl = event.getDeviceUrl();
548         List<SomfyTahomaState> states = event.getDeviceStates();
549         logger.debug("States for device {} : {}", deviceUrl, states);
550         Thing thing = getThingByDeviceUrl(deviceUrl);
551
552         if (thing != null) {
553             logger.debug("Updating status of thing: {}", thing.getLabel());
554             SomfyTahomaBaseThingHandler handler = (SomfyTahomaBaseThingHandler) thing.getHandler();
555
556             if (handler != null) {
557                 // update thing status
558                 handler.updateThingStatus(states);
559                 handler.updateThingChannels(states);
560             }
561         } else {
562             logger.debug("Thing handler is null, probably not bound thing.");
563         }
564     }
565
566     private void enableReconciliation() {
567         logger.debug("Enabling reconciliation");
568         reconciliation = true;
569     }
570
571     private void refreshTahomaStates() {
572         logger.debug("Refreshing Tahoma states...");
573         if (ThingStatus.OFFLINE == thing.getStatus() && !reLogin()) {
574             return;
575         }
576
577         // force Tahoma to ask for actual states
578         forceGatewaySync();
579     }
580
581     private @Nullable Thing getThingByDeviceUrl(String deviceUrl) {
582         for (Thing th : getThing().getThings()) {
583             String url = (String) th.getConfiguration().get("url");
584             if (deviceUrl.equals(url)) {
585                 return th;
586             }
587         }
588         return null;
589     }
590
591     private void logout() {
592         try {
593             eventsId = "";
594             sendGetToTahomaWithCookie(TAHOMA_API_URL + "logout");
595         } catch (InterruptedException | ExecutionException | TimeoutException e) {
596             logger.debug("Cannot send logout command!", e);
597             if (e instanceof InterruptedException) {
598                 Thread.currentThread().interrupt();
599             }
600         }
601     }
602
603     private String sendPostToTahomaWithCookie(String url, String urlParameters)
604             throws InterruptedException, ExecutionException, TimeoutException {
605         return sendMethodToTahomaWithCookie(url, HttpMethod.POST, urlParameters);
606     }
607
608     private String sendGetToTahomaWithCookie(String url)
609             throws InterruptedException, ExecutionException, TimeoutException {
610         return sendMethodToTahomaWithCookie(url, HttpMethod.GET);
611     }
612
613     private String sendPutToTahomaWithCookie(String url)
614             throws InterruptedException, ExecutionException, TimeoutException {
615         return sendMethodToTahomaWithCookie(url, HttpMethod.PUT);
616     }
617
618     private String sendDeleteToTahomaWithCookie(String url)
619             throws InterruptedException, ExecutionException, TimeoutException {
620         return sendMethodToTahomaWithCookie(url, HttpMethod.DELETE);
621     }
622
623     private String sendMethodToTahomaWithCookie(String url, HttpMethod method)
624             throws InterruptedException, ExecutionException, TimeoutException {
625         return sendMethodToTahomaWithCookie(url, method, "");
626     }
627
628     private String sendMethodToTahomaWithCookie(String url, HttpMethod method, String urlParameters)
629             throws InterruptedException, ExecutionException, TimeoutException {
630         logger.trace("Sending {} to url: {} with data: {}", method.asString(), url, urlParameters);
631         Request request = sendRequestBuilder(url, method);
632         if (!urlParameters.isEmpty()) {
633             request = request.content(new StringContentProvider(urlParameters), "application/json;charset=UTF-8");
634         }
635
636         ContentResponse response = request.send();
637
638         if (logger.isTraceEnabled()) {
639             logger.trace("Response: {}", response.getContentAsString());
640         }
641
642         if (response.getStatus() < 200 || response.getStatus() >= 300) {
643             logger.debug("Received unexpected status code: {}", response.getStatus());
644         }
645         return response.getContentAsString();
646     }
647
648     private Request sendRequestBuilder(String url, HttpMethod method) {
649         return httpClient.newRequest(url).method(method).header(HttpHeader.ACCEPT_LANGUAGE, "en-US,en")
650                 .header(HttpHeader.ACCEPT_ENCODING, "gzip, deflate").header("X-Requested-With", "XMLHttpRequest")
651                 .timeout(TAHOMA_TIMEOUT, TimeUnit.SECONDS).agent(TAHOMA_AGENT);
652     }
653
654     public void sendCommand(String io, String command, String params, String url) {
655         if (ThingStatus.OFFLINE == thing.getStatus() && !reLogin()) {
656             return;
657         }
658
659         removeFinishedRetries();
660
661         boolean result = sendCommandInternal(io, command, params, url);
662         if (!result) {
663             scheduleRetry(io, command, params, url, thingConfig.getRetries());
664         }
665     }
666
667     private void repeatSendCommandInternal(String io, String command, String params, String url, int retries) {
668         logger.debug("Retrying command, retries left: {}", retries);
669         boolean result = sendCommandInternal(io, command, params, url);
670         if (!result && (retries > 0)) {
671             scheduleRetry(io, command, params, url, retries - 1);
672         }
673     }
674
675     private boolean sendCommandInternal(String io, String command, String params, String url) {
676         String value = params.equals("[]") ? command : command + " " + params.replace("\"", "");
677         String urlParameters = "{\"label\":\"" + getThingLabelByURL(io) + " - " + value
678                 + " - openHAB\",\"actions\":[{\"deviceURL\":\"" + io + "\",\"commands\":[{\"name\":\"" + command
679                 + "\",\"parameters\":" + params + "}]}]}";
680         SomfyTahomaApplyResponse response = invokeCallToURL(url, urlParameters, HttpMethod.POST,
681                 SomfyTahomaApplyResponse.class);
682         if (response != null) {
683             if (!response.getExecId().isEmpty()) {
684                 logger.debug("Exec id: {}", response.getExecId());
685                 registerExecution(io, response.getExecId());
686                 scheduleNextGetUpdates();
687             } else {
688                 logger.debug("ExecId is empty!");
689                 return false;
690             }
691             return true;
692         }
693         return false;
694     }
695
696     private void removeFinishedRetries() {
697         retryFutures.removeIf(x -> x.isDone());
698         logger.debug("Currently {} retries are scheduled.", retryFutures.size());
699     }
700
701     private void scheduleRetry(String io, String command, String params, String url, int retries) {
702         retryFutures.add(scheduler.schedule(() -> {
703             repeatSendCommandInternal(io, command, params, url, retries);
704         }, thingConfig.getRetryDelay(), TimeUnit.MILLISECONDS));
705     }
706
707     public void sendCommandToSameDevicesInPlace(String io, String command, String params, String url) {
708         SomfyTahomaDevice device = devicePlaces.get(io);
709         if (device != null && !device.getPlaceOID().isEmpty()) {
710             devicePlaces.forEach((deviceUrl, devicePlace) -> {
711                 if (device.getPlaceOID().equals(devicePlace.getPlaceOID())
712                         && device.getWidget().equals(devicePlace.getWidget())) {
713                     sendCommand(deviceUrl, command, params, url);
714                 }
715             });
716         } else {
717             sendCommand(io, command, params, url);
718         }
719     }
720
721     private String getThingLabelByURL(String io) {
722         Thing th = getThingByDeviceUrl(io);
723         if (th != null) {
724             if (th.getProperties().containsKey(NAME_STATE)) {
725                 // Return label from Tahoma
726                 return th.getProperties().get(NAME_STATE).replace("\"", "");
727             }
728             // Return label from the thing
729             String label = th.getLabel();
730             return label != null ? label.replace("\"", "") : "";
731         }
732         return "null";
733     }
734
735     public @Nullable String getCurrentExecutions(String io) {
736         if (executions.containsKey(io)) {
737             return executions.get(io);
738         }
739         return null;
740     }
741
742     public void cancelExecution(String executionId) {
743         invokeCallToURL(DELETE_URL + executionId, "", HttpMethod.DELETE, null);
744     }
745
746     public void executeActionGroup(String id) {
747         if (ThingStatus.OFFLINE == thing.getStatus() && !reLogin()) {
748             return;
749         }
750         String execId = executeActionGroupInternal(id);
751         if (execId == null) {
752             execId = executeActionGroupInternal(id);
753         }
754         if (execId != null) {
755             registerExecution(id, execId);
756             scheduleNextGetUpdates();
757         }
758     }
759
760     private boolean reLogin() {
761         logger.debug("Doing relogin");
762         reLoginNeeded = true;
763         login();
764         return ThingStatus.OFFLINE != thing.getStatus();
765     }
766
767     public @Nullable String executeActionGroupInternal(String id) {
768         SomfyTahomaApplyResponse response = invokeCallToURL(EXEC_URL + id, "", HttpMethod.POST,
769                 SomfyTahomaApplyResponse.class);
770         if (response != null) {
771             if (response.getExecId().isEmpty()) {
772                 logger.debug("Got empty exec response");
773                 return null;
774             }
775             return response.getExecId();
776         }
777         return null;
778     }
779
780     public void forceGatewaySync() {
781         invokeCallToURL(REFRESH_URL, "", HttpMethod.PUT, null);
782     }
783
784     public SomfyTahomaStatus getTahomaStatus(String gatewayId) {
785         SomfyTahomaStatusResponse data = invokeCallToURL(GATEWAYS_URL + gatewayId, "", HttpMethod.GET,
786                 SomfyTahomaStatusResponse.class);
787         if (data != null) {
788             logger.debug("Tahoma status: {}", data.getConnectivity().getStatus());
789             logger.debug("Tahoma protocol version: {}", data.getConnectivity().getProtocolVersion());
790             return data.getConnectivity();
791         }
792         return new SomfyTahomaStatus();
793     }
794
795     private boolean isAuthenticationChallenge(Exception ex) {
796         String msg = ex.getMessage();
797         return msg != null && msg.contains(AUTHENTICATION_CHALLENGE);
798     }
799
800     @Override
801     public void handleConfigurationUpdate(Map<String, Object> configurationParameters) {
802         super.handleConfigurationUpdate(configurationParameters);
803         if (configurationParameters.containsKey("email")) {
804             thingConfig.setEmail(configurationParameters.get("email").toString());
805         }
806         if (configurationParameters.containsKey("password")) {
807             thingConfig.setPassword(configurationParameters.get("password").toString());
808         }
809     }
810
811     public synchronized void refresh(String url, String stateName) {
812         SomfyTahomaState state = invokeCallToURL(DEVICES_URL + urlEncode(url) + "/states/" + stateName, "",
813                 HttpMethod.GET, SomfyTahomaState.class);
814         if (state != null && !state.getName().isEmpty()) {
815             updateDevice(url, List.of(state));
816         }
817     }
818
819     private @Nullable <T> T invokeCallToURL(String url, String urlParameters, HttpMethod method,
820             @Nullable Class<T> classOfT) {
821         String response = "";
822         try {
823             switch (method) {
824                 case GET:
825                     response = sendGetToTahomaWithCookie(url);
826                     break;
827                 case PUT:
828                     response = sendPutToTahomaWithCookie(url);
829                     break;
830                 case POST:
831                     response = sendPostToTahomaWithCookie(url, urlParameters);
832                     break;
833                 case DELETE:
834                     response = sendDeleteToTahomaWithCookie(url);
835                 default:
836             }
837             return classOfT != null ? gson.fromJson(response, classOfT) : null;
838         } catch (JsonSyntaxException e) {
839             logger.debug("Received data: {} is not JSON", response, e);
840             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Received invalid data");
841         } catch (ExecutionException e) {
842             if (isAuthenticationChallenge(e)) {
843                 reLogin();
844             } else {
845                 logger.debug("Cannot call url: {} with params: {}!", url, urlParameters, e);
846                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
847             }
848         } catch (InterruptedException | TimeoutException e) {
849             logger.debug("Cannot call url: {} with params: {}!", url, urlParameters, e);
850             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
851             if (e instanceof InterruptedException) {
852                 Thread.currentThread().interrupt();
853             }
854         }
855         return null;
856     }
857 }