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