2 * Copyright (c) 2010-2021 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.somfytahoma.internal.handler;
15 import static org.openhab.binding.somfytahoma.internal.SomfyTahomaBindingConstants.*;
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;
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;
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;
67 import com.google.gson.Gson;
68 import com.google.gson.JsonElement;
69 import com.google.gson.JsonSyntaxException;
72 * The {@link SomfyTahomaBridgeHandler} is responsible for handling commands, which are
73 * sent to one of the channels.
75 * @author Ondrej Pecta - Initial contribution
78 public class SomfyTahomaBridgeHandler extends BaseBridgeHandler {
80 private final Logger logger = LoggerFactory.getLogger(SomfyTahomaBridgeHandler.class);
83 * The shared HttpClient
85 private final HttpClient httpClient;
88 * Future to poll for updates
90 private @Nullable ScheduledFuture<?> pollFuture;
93 * Future to poll for status
95 private @Nullable ScheduledFuture<?> statusFuture;
98 * Future to set reconciliation flag
100 private @Nullable ScheduledFuture<?> reconciliationFuture;
102 // List of futures used for command retries
103 private Collection<ScheduledFuture<?>> retryFutures = new ConcurrentLinkedQueue<ScheduledFuture<?>>();
108 private Map<String, String> executions = new HashMap<>();
110 // Too many requests flag
111 private boolean tooManyRequests = false;
113 // Silent relogin flag
114 private boolean reLoginNeeded = false;
116 // Reconciliation flag
117 private boolean reconciliation = false;
122 protected SomfyTahomaConfig thingConfig = new SomfyTahomaConfig();
125 * Id of registered events
127 private String eventsId = "";
129 private Map<String, SomfyTahomaDevice> devicePlaces = new HashMap<>();
131 private ExpiringCache<List<SomfyTahomaDevice>> cachedDevices = new ExpiringCache<>(Duration.ofSeconds(30),
135 private final Gson gson = new Gson();
137 public SomfyTahomaBridgeHandler(Bridge thing, HttpClientFactory httpClientFactory) {
139 this.httpClient = httpClientFactory.createHttpClient("somfy_" + thing.getUID().getId());
143 public void handleCommand(ChannelUID channelUID, Command command) {
147 public void initialize() {
148 thingConfig = getConfigAs(SomfyTahomaConfig.class);
152 } catch (Exception e) {
153 logger.debug("Cannot start http client for: {}", thing.getBridgeUID().getId(), e);
157 scheduler.execute(() -> {
160 logger.debug("Initialize done...");
165 * starts this things polling future
167 private void initPolling() {
169 scheduleGetUpdates(10);
171 statusFuture = scheduler.scheduleWithFixedDelay(() -> {
172 refreshTahomaStates();
173 }, 60, thingConfig.getStatusTimeout(), TimeUnit.SECONDS);
175 reconciliationFuture = scheduler.scheduleWithFixedDelay(() -> {
176 enableReconciliation();
177 }, RECONCILIATION_TIME, RECONCILIATION_TIME, TimeUnit.SECONDS);
180 private void scheduleGetUpdates(long delay) {
181 pollFuture = scheduler.schedule(() -> {
183 scheduleNextGetUpdates();
184 }, delay, TimeUnit.SECONDS);
187 private void scheduleNextGetUpdates() {
188 ScheduledFuture<?> localPollFuture = pollFuture;
189 if (localPollFuture != null) {
190 localPollFuture.cancel(false);
192 scheduleGetUpdates(executions.isEmpty() ? thingConfig.getRefresh() : 2);
195 public synchronized void login() {
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");
204 if (tooManyRequests) {
205 logger.debug("Skipping login due to too many requests");
209 if (ThingStatus.ONLINE == thing.getStatus() && !reLoginNeeded) {
210 logger.debug("No need to log in, because already logged in");
214 reLoginNeeded = false;
217 url = TAHOMA_API_URL + "login";
218 String urlParameters = "userId=" + urlEncode(thingConfig.getEmail()) + "&userPassword="
219 + urlEncode(thingConfig.getPassword());
221 ContentResponse response = sendRequestBuilder(url, HttpMethod.POST)
222 .content(new StringContentProvider(urlParameters),
223 "application/x-www-form-urlencoded; charset=UTF-8")
226 if (logger.isTraceEnabled()) {
227 logger.trace("Login response: {}", response.getContentAsString());
230 SomfyTahomaLoginResponse data = gson.fromJson(response.getContentAsString(),
231 SomfyTahomaLoginResponse.class);
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)) {
240 logger.debug("Events id: {}", eventsId);
241 updateStatus(ThingStatus.ONLINE);
243 logger.debug("Events id error: {}", id);
246 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
247 "Error logging in: " + data.getError());
248 if (data.getError().startsWith(TOO_MANY_REQUESTS)) {
249 setTooManyRequests();
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();
260 logger.debug("Cannot get login cookie", e);
261 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Cannot get login cookie");
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();
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);
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;
284 private String urlEncode(String text) {
286 return URLEncoder.encode(text, StandardCharsets.UTF_8.toString());
287 } catch (UnsupportedEncodingException e) {
292 private void enableLogin() {
293 tooManyRequests = false;
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();
303 public void handleRemoval() {
304 super.handleRemoval();
309 public Collection<Class<? extends ThingHandlerService>> getServices() {
310 return Collections.singleton(SomfyTahomaItemDiscoveryService.class);
314 public void dispose() {
319 private void cleanup() {
320 logger.debug("Doing cleanup");
323 // cancel all scheduled retries
324 retryFutures.forEach(x -> x.cancel(false));
328 } catch (Exception e) {
329 logger.debug("Error during http client stopping", e);
334 public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
335 super.bridgeStatusChanged(bridgeStatusInfo);
336 if (ThingStatus.UNINITIALIZED == bridgeStatusInfo.getStatus()) {
342 * Stops this thing's polling future
344 private void stopPolling() {
345 ScheduledFuture<?> localPollFuture = pollFuture;
346 if (localPollFuture != null && !localPollFuture.isCancelled()) {
347 localPollFuture.cancel(true);
349 ScheduledFuture<?> localStatusFuture = statusFuture;
350 if (localStatusFuture != null && !localStatusFuture.isCancelled()) {
351 localStatusFuture.cancel(true);
353 ScheduledFuture<?> localReconciliationFuture = reconciliationFuture;
354 if (localReconciliationFuture != null && !localReconciliationFuture.isCancelled()) {
355 localReconciliationFuture.cancel(true);
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();
365 public @Nullable SomfyTahomaSetup getSetup() {
366 SomfyTahomaSetup setup = invokeCallToURL(TAHOMA_API_URL + "setup", "", HttpMethod.GET, SomfyTahomaSetup.class);
368 saveDevicePlaces(setup.getDevices());
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);
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())) {
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);
405 private void getTahomaUpdates() {
406 logger.debug("Getting Tahoma Updates...");
407 if (ThingStatus.OFFLINE == thing.getStatus() && !reLogin()) {
411 List<SomfyTahomaEvent> events = getEvents();
412 logger.trace("Got total of {} events", events.size());
413 for (SomfyTahomaEvent event : events) {
418 private void processEvent(SomfyTahomaEvent event) {
419 logger.debug("Got event: {}", event.getName());
420 switch (event.getName()) {
421 case "ExecutionRegisteredEvent":
422 processExecutionRegisteredEvent(event);
424 case "ExecutionStateChangedEvent":
425 processExecutionChangedEvent(event);
427 case "DeviceStateChangedEvent":
428 processStateChangedEvent(event);
430 case "RefreshAllDevicesStatesCompletedEvent":
431 scheduler.schedule(this::updateThings, 1, TimeUnit.SECONDS);
433 case "GatewayAliveEvent":
434 case "GatewayDownEvent":
435 processGatewayEvent(event);
438 // ignore other states
442 private synchronized void updateThings() {
443 boolean needsUpdate = reconciliation;
445 for (Thing th : getThing().getThings()) {
446 if (ThingStatus.ONLINE != th.getStatus()) {
451 // update all states only if necessary
454 reconciliation = false;
458 private void processExecutionRegisteredEvent(SomfyTahomaEvent event) {
459 boolean invalidData = false;
461 JsonElement el = event.getAction();
462 if (el.isJsonArray()) {
463 SomfyTahomaAction[] actions = gson.fromJson(el, SomfyTahomaAction[].class);
464 if (actions == null) {
467 for (SomfyTahomaAction action : actions) {
468 registerExecution(action.getDeviceURL(), event.getExecId());
472 SomfyTahomaAction action = gson.fromJson(el, SomfyTahomaAction.class);
473 if (action == null) {
476 registerExecution(action.getDeviceURL(), event.getExecId());
479 } catch (JsonSyntaxException e) {
483 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
484 "Received invalid data (execution registered)");
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());
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);
500 executions.put(url, execId);
503 private void unregisterExecution(String execId) {
504 if (executions.containsValue(execId)) {
505 executions.values().removeAll(Collections.singleton(execId));
507 logger.debug("Cannot remove execution id: {}, because it is not registered", execId);
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);
523 private synchronized void updateAllStates() {
524 logger.debug("Updating all states");
525 getDevices().forEach(device -> updateDevice(device));
528 private void updateDevice(SomfyTahomaDevice device) {
529 String url = device.getDeviceURL();
530 List<SomfyTahomaState> states = device.getStates();
531 updateDevice(url, states);
534 private void updateDevice(String url, List<SomfyTahomaState> states) {
535 Thing th = getThingByDeviceUrl(url);
539 SomfyTahomaBaseThingHandler handler = (SomfyTahomaBaseThingHandler) th.getHandler();
540 if (handler != null) {
541 handler.updateThingStatus(states);
542 handler.updateThingChannels(states);
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);
553 logger.debug("Updating status of thing: {}", thing.getLabel());
554 SomfyTahomaBaseThingHandler handler = (SomfyTahomaBaseThingHandler) thing.getHandler();
556 if (handler != null) {
557 // update thing status
558 handler.updateThingStatus(states);
559 handler.updateThingChannels(states);
562 logger.debug("Thing handler is null, probably not bound thing.");
566 private void enableReconciliation() {
567 logger.debug("Enabling reconciliation");
568 reconciliation = true;
571 private void refreshTahomaStates() {
572 logger.debug("Refreshing Tahoma states...");
573 if (ThingStatus.OFFLINE == thing.getStatus() && !reLogin()) {
577 // force Tahoma to ask for actual states
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)) {
591 private void logout() {
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();
602 private String sendPostToTahomaWithCookie(String url, String urlParameters)
603 throws InterruptedException, ExecutionException, TimeoutException {
604 return sendMethodToTahomaWithCookie(url, HttpMethod.POST, urlParameters);
607 private String sendGetToTahomaWithCookie(String url)
608 throws InterruptedException, ExecutionException, TimeoutException {
609 return sendMethodToTahomaWithCookie(url, HttpMethod.GET);
612 private String sendPutToTahomaWithCookie(String url)
613 throws InterruptedException, ExecutionException, TimeoutException {
614 return sendMethodToTahomaWithCookie(url, HttpMethod.PUT);
617 private String sendDeleteToTahomaWithCookie(String url)
618 throws InterruptedException, ExecutionException, TimeoutException {
619 return sendMethodToTahomaWithCookie(url, HttpMethod.DELETE);
622 private String sendMethodToTahomaWithCookie(String url, HttpMethod method)
623 throws InterruptedException, ExecutionException, TimeoutException {
624 return sendMethodToTahomaWithCookie(url, method, "");
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");
635 ContentResponse response = request.send();
637 if (logger.isTraceEnabled()) {
638 logger.trace("Response: {}", response.getContentAsString());
641 if (response.getStatus() < 200 || response.getStatus() >= 300) {
642 logger.debug("Received unexpected status code: {}", response.getStatus());
644 return response.getContentAsString();
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);
653 public void sendCommand(String io, String command, String params, String url) {
654 if (ThingStatus.OFFLINE == thing.getStatus() && !reLogin()) {
658 removeFinishedRetries();
660 boolean result = sendCommandInternal(io, command, params, url);
662 scheduleRetry(io, command, params, url, thingConfig.getRetries());
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);
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();
687 logger.debug("ExecId is empty!");
695 private void removeFinishedRetries() {
696 retryFutures.removeIf(x -> x.isDone());
697 logger.debug("Currently {} retries are scheduled.", retryFutures.size());
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));
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);
716 sendCommand(io, command, params, url);
720 private String getThingLabelByURL(String io) {
721 Thing th = getThingByDeviceUrl(io);
723 if (th.getProperties().containsKey(NAME_STATE)) {
724 // Return label from Tahoma
725 return th.getProperties().get(NAME_STATE).replace("\"", "");
727 // Return label from the thing
728 String label = th.getLabel();
729 return label != null ? label.replace("\"", "") : "";
734 public @Nullable String getCurrentExecutions(String io) {
735 if (executions.containsKey(io)) {
736 return executions.get(io);
741 public void cancelExecution(String executionId) {
742 invokeCallToURL(DELETE_URL + executionId, "", HttpMethod.DELETE, null);
745 public void executeActionGroup(String id) {
746 if (ThingStatus.OFFLINE == thing.getStatus() && !reLogin()) {
749 String execId = executeActionGroupInternal(id);
750 if (execId == null) {
751 execId = executeActionGroupInternal(id);
753 if (execId != null) {
754 registerExecution(id, execId);
755 scheduleNextGetUpdates();
759 private boolean reLogin() {
760 logger.debug("Doing relogin");
761 reLoginNeeded = true;
763 return ThingStatus.OFFLINE != thing.getStatus();
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");
774 return response.getExecId();
779 public void forceGatewaySync() {
780 invokeCallToURL(REFRESH_URL, "", HttpMethod.PUT, null);
783 public SomfyTahomaStatus getTahomaStatus(String gatewayId) {
784 SomfyTahomaStatusResponse data = invokeCallToURL(GATEWAYS_URL + gatewayId, "", HttpMethod.GET,
785 SomfyTahomaStatusResponse.class);
787 logger.debug("Tahoma status: {}", data.getConnectivity().getStatus());
788 logger.debug("Tahoma protocol version: {}", data.getConnectivity().getProtocolVersion());
789 return data.getConnectivity();
791 return new SomfyTahomaStatus();
794 private boolean isAuthenticationChallenge(Exception ex) {
795 String msg = ex.getMessage();
796 return msg != null && msg.contains(AUTHENTICATION_CHALLENGE);
800 public void handleConfigurationUpdate(Map<String, Object> configurationParameters) {
801 super.handleConfigurationUpdate(configurationParameters);
802 if (configurationParameters.containsKey("email")) {
803 thingConfig.setEmail(configurationParameters.get("email").toString());
805 if (configurationParameters.containsKey("password")) {
806 thingConfig.setPassword(configurationParameters.get("password").toString());
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));
818 private @Nullable <T> T invokeCallToURL(String url, String urlParameters, HttpMethod method,
819 @Nullable Class<T> classOfT) {
820 String response = "";
824 response = sendGetToTahomaWithCookie(url);
827 response = sendPutToTahomaWithCookie(url);
830 response = sendPostToTahomaWithCookie(url, urlParameters);
833 response = sendDeleteToTahomaWithCookie(url);
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)) {
844 logger.debug("Cannot call url: {} with params: {}!", url, urlParameters, e);
845 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
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();