]> git.basschouten.com Git - openhab-addons.git/blob
daa3b4c417d6dac1d6284e0a81e9a4d0a4f421ac
[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 (ExecutionException e) {
256             if (isAuthenticationChallenge(e)) {
257                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Authentication challenge");
258                 setTooManyRequests();
259             } else {
260                 logger.debug("Cannot get login cookie", e);
261                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Cannot get login cookie");
262             }
263         } catch (TimeoutException e) {
264             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Getting login cookie timeout");
265         } catch (InterruptedException e) {
266             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
267                     "Getting login cookie interrupted");
268             Thread.currentThread().interrupt();
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 (ExecutionException | TimeoutException e) {
596             logger.debug("Cannot send logout command!", e);
597         } catch (InterruptedException e) {
598             Thread.currentThread().interrupt();
599         }
600     }
601
602     private String sendPostToTahomaWithCookie(String url, String urlParameters)
603             throws InterruptedException, ExecutionException, TimeoutException {
604         return sendMethodToTahomaWithCookie(url, HttpMethod.POST, urlParameters);
605     }
606
607     private String sendGetToTahomaWithCookie(String url)
608             throws InterruptedException, ExecutionException, TimeoutException {
609         return sendMethodToTahomaWithCookie(url, HttpMethod.GET);
610     }
611
612     private String sendPutToTahomaWithCookie(String url)
613             throws InterruptedException, ExecutionException, TimeoutException {
614         return sendMethodToTahomaWithCookie(url, HttpMethod.PUT);
615     }
616
617     private String sendDeleteToTahomaWithCookie(String url)
618             throws InterruptedException, ExecutionException, TimeoutException {
619         return sendMethodToTahomaWithCookie(url, HttpMethod.DELETE);
620     }
621
622     private String sendMethodToTahomaWithCookie(String url, HttpMethod method)
623             throws InterruptedException, ExecutionException, TimeoutException {
624         return sendMethodToTahomaWithCookie(url, method, "");
625     }
626
627     private String sendMethodToTahomaWithCookie(String url, HttpMethod method, String urlParameters)
628             throws InterruptedException, ExecutionException, TimeoutException {
629         logger.trace("Sending {} to url: {} with data: {}", method.asString(), url, urlParameters);
630         Request request = sendRequestBuilder(url, method);
631         if (!urlParameters.isEmpty()) {
632             request = request.content(new StringContentProvider(urlParameters), "application/json;charset=UTF-8");
633         }
634
635         ContentResponse response = request.send();
636
637         if (logger.isTraceEnabled()) {
638             logger.trace("Response: {}", response.getContentAsString());
639         }
640
641         if (response.getStatus() < 200 || response.getStatus() >= 300) {
642             logger.debug("Received unexpected status code: {}", response.getStatus());
643         }
644         return response.getContentAsString();
645     }
646
647     private Request sendRequestBuilder(String url, HttpMethod method) {
648         return httpClient.newRequest(url).method(method).header(HttpHeader.ACCEPT_LANGUAGE, "en-US,en")
649                 .header(HttpHeader.ACCEPT_ENCODING, "gzip, deflate").header("X-Requested-With", "XMLHttpRequest")
650                 .timeout(TAHOMA_TIMEOUT, TimeUnit.SECONDS).agent(TAHOMA_AGENT);
651     }
652
653     public void sendCommand(String io, String command, String params, String url) {
654         if (ThingStatus.OFFLINE == thing.getStatus() && !reLogin()) {
655             return;
656         }
657
658         removeFinishedRetries();
659
660         boolean result = sendCommandInternal(io, command, params, url);
661         if (!result) {
662             scheduleRetry(io, command, params, url, thingConfig.getRetries());
663         }
664     }
665
666     private void repeatSendCommandInternal(String io, String command, String params, String url, int retries) {
667         logger.debug("Retrying command, retries left: {}", retries);
668         boolean result = sendCommandInternal(io, command, params, url);
669         if (!result && (retries > 0)) {
670             scheduleRetry(io, command, params, url, retries - 1);
671         }
672     }
673
674     private boolean sendCommandInternal(String io, String command, String params, String url) {
675         String value = params.equals("[]") ? command : command + " " + params.replace("\"", "");
676         String urlParameters = "{\"label\":\"" + getThingLabelByURL(io) + " - " + value
677                 + " - openHAB\",\"actions\":[{\"deviceURL\":\"" + io + "\",\"commands\":[{\"name\":\"" + command
678                 + "\",\"parameters\":" + params + "}]}]}";
679         SomfyTahomaApplyResponse response = invokeCallToURL(url, urlParameters, HttpMethod.POST,
680                 SomfyTahomaApplyResponse.class);
681         if (response != null) {
682             if (!response.getExecId().isEmpty()) {
683                 logger.debug("Exec id: {}", response.getExecId());
684                 registerExecution(io, response.getExecId());
685                 scheduleNextGetUpdates();
686             } else {
687                 logger.debug("ExecId is empty!");
688                 return false;
689             }
690             return true;
691         }
692         return false;
693     }
694
695     private void removeFinishedRetries() {
696         retryFutures.removeIf(x -> x.isDone());
697         logger.debug("Currently {} retries are scheduled.", retryFutures.size());
698     }
699
700     private void scheduleRetry(String io, String command, String params, String url, int retries) {
701         retryFutures.add(scheduler.schedule(() -> {
702             repeatSendCommandInternal(io, command, params, url, retries);
703         }, thingConfig.getRetryDelay(), TimeUnit.MILLISECONDS));
704     }
705
706     public void sendCommandToSameDevicesInPlace(String io, String command, String params, String url) {
707         SomfyTahomaDevice device = devicePlaces.get(io);
708         if (device != null && !device.getPlaceOID().isEmpty()) {
709             devicePlaces.forEach((deviceUrl, devicePlace) -> {
710                 if (device.getPlaceOID().equals(devicePlace.getPlaceOID())
711                         && device.getWidget().equals(devicePlace.getWidget())) {
712                     sendCommand(deviceUrl, command, params, url);
713                 }
714             });
715         } else {
716             sendCommand(io, command, params, url);
717         }
718     }
719
720     private String getThingLabelByURL(String io) {
721         Thing th = getThingByDeviceUrl(io);
722         if (th != null) {
723             if (th.getProperties().containsKey(NAME_STATE)) {
724                 // Return label from Tahoma
725                 return th.getProperties().get(NAME_STATE).replace("\"", "");
726             }
727             // Return label from the thing
728             String label = th.getLabel();
729             return label != null ? label.replace("\"", "") : "";
730         }
731         return "null";
732     }
733
734     public @Nullable String getCurrentExecutions(String io) {
735         if (executions.containsKey(io)) {
736             return executions.get(io);
737         }
738         return null;
739     }
740
741     public void cancelExecution(String executionId) {
742         invokeCallToURL(DELETE_URL + executionId, "", HttpMethod.DELETE, null);
743     }
744
745     public void executeActionGroup(String id) {
746         if (ThingStatus.OFFLINE == thing.getStatus() && !reLogin()) {
747             return;
748         }
749         String execId = executeActionGroupInternal(id);
750         if (execId == null) {
751             execId = executeActionGroupInternal(id);
752         }
753         if (execId != null) {
754             registerExecution(id, execId);
755             scheduleNextGetUpdates();
756         }
757     }
758
759     private boolean reLogin() {
760         logger.debug("Doing relogin");
761         reLoginNeeded = true;
762         login();
763         return ThingStatus.OFFLINE != thing.getStatus();
764     }
765
766     public @Nullable String executeActionGroupInternal(String id) {
767         SomfyTahomaApplyResponse response = invokeCallToURL(EXEC_URL + id, "", HttpMethod.POST,
768                 SomfyTahomaApplyResponse.class);
769         if (response != null) {
770             if (response.getExecId().isEmpty()) {
771                 logger.debug("Got empty exec response");
772                 return null;
773             }
774             return response.getExecId();
775         }
776         return null;
777     }
778
779     public void forceGatewaySync() {
780         invokeCallToURL(REFRESH_URL, "", HttpMethod.PUT, null);
781     }
782
783     public SomfyTahomaStatus getTahomaStatus(String gatewayId) {
784         SomfyTahomaStatusResponse data = invokeCallToURL(GATEWAYS_URL + gatewayId, "", HttpMethod.GET,
785                 SomfyTahomaStatusResponse.class);
786         if (data != null) {
787             logger.debug("Tahoma status: {}", data.getConnectivity().getStatus());
788             logger.debug("Tahoma protocol version: {}", data.getConnectivity().getProtocolVersion());
789             return data.getConnectivity();
790         }
791         return new SomfyTahomaStatus();
792     }
793
794     private boolean isAuthenticationChallenge(Exception ex) {
795         String msg = ex.getMessage();
796         return msg != null && msg.contains(AUTHENTICATION_CHALLENGE);
797     }
798
799     @Override
800     public void handleConfigurationUpdate(Map<String, Object> configurationParameters) {
801         super.handleConfigurationUpdate(configurationParameters);
802         if (configurationParameters.containsKey("email")) {
803             thingConfig.setEmail(configurationParameters.get("email").toString());
804         }
805         if (configurationParameters.containsKey("password")) {
806             thingConfig.setPassword(configurationParameters.get("password").toString());
807         }
808     }
809
810     public synchronized void refresh(String url, String stateName) {
811         SomfyTahomaState state = invokeCallToURL(DEVICES_URL + urlEncode(url) + "/states/" + stateName, "",
812                 HttpMethod.GET, SomfyTahomaState.class);
813         if (state != null && !state.getName().isEmpty()) {
814             updateDevice(url, List.of(state));
815         }
816     }
817
818     private @Nullable <T> T invokeCallToURL(String url, String urlParameters, HttpMethod method,
819             @Nullable Class<T> classOfT) {
820         String response = "";
821         try {
822             switch (method) {
823                 case GET:
824                     response = sendGetToTahomaWithCookie(url);
825                     break;
826                 case PUT:
827                     response = sendPutToTahomaWithCookie(url);
828                     break;
829                 case POST:
830                     response = sendPostToTahomaWithCookie(url, urlParameters);
831                     break;
832                 case DELETE:
833                     response = sendDeleteToTahomaWithCookie(url);
834                 default:
835             }
836             return classOfT != null ? gson.fromJson(response, classOfT) : null;
837         } catch (JsonSyntaxException e) {
838             logger.debug("Received data: {} is not JSON", response, e);
839             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Received invalid data");
840         } catch (ExecutionException e) {
841             if (isAuthenticationChallenge(e)) {
842                 reLogin();
843             } else {
844                 logger.debug("Cannot call url: {} with params: {}!", url, urlParameters, e);
845                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
846             }
847         } catch (TimeoutException e) {
848             logger.debug("Timeout when calling url: {} with params: {}!", url, urlParameters, e);
849             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
850         } catch (InterruptedException e) {
851             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
852             Thread.currentThread().interrupt();
853         }
854         return null;
855     }
856 }