]> git.basschouten.com Git - openhab-addons.git/blob
c0650efcf3850681f95791122477c931719af5bc
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.jablotron.internal.handler;
14
15 import static org.openhab.binding.jablotron.JablotronBindingConstants.*;
16
17 import java.util.Collection;
18 import java.util.Collections;
19 import java.util.List;
20 import java.util.concurrent.ExecutionException;
21 import java.util.concurrent.ScheduledFuture;
22 import java.util.concurrent.TimeUnit;
23 import java.util.concurrent.TimeoutException;
24
25 import org.eclipse.jdt.annotation.NonNullByDefault;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.eclipse.jetty.client.HttpClient;
28 import org.eclipse.jetty.client.api.ContentResponse;
29 import org.eclipse.jetty.client.api.Request;
30 import org.eclipse.jetty.client.util.StringContentProvider;
31 import org.eclipse.jetty.http.HttpHeader;
32 import org.eclipse.jetty.http.HttpMethod;
33 import org.openhab.binding.jablotron.internal.config.JablotronBridgeConfig;
34 import org.openhab.binding.jablotron.internal.discovery.JablotronDiscoveryService;
35 import org.openhab.binding.jablotron.internal.model.*;
36 import org.openhab.binding.jablotron.internal.model.ja100f.JablotronGetPGResponse;
37 import org.openhab.binding.jablotron.internal.model.ja100f.JablotronGetSectionsResponse;
38 import org.openhab.core.thing.*;
39 import org.openhab.core.thing.binding.BaseBridgeHandler;
40 import org.openhab.core.thing.binding.ThingHandlerService;
41 import org.openhab.core.types.Command;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 import com.google.gson.Gson;
46 import com.google.gson.JsonSyntaxException;
47
48 /**
49  * The {@link JablotronBridgeHandler} is responsible for handling commands, which are
50  * sent to one of the channels.
51  *
52  * @author Ondrej Pecta - Initial contribution
53  */
54 @NonNullByDefault
55 public class JablotronBridgeHandler extends BaseBridgeHandler {
56
57     private final Logger logger = LoggerFactory.getLogger(JablotronBridgeHandler.class);
58
59     private final Gson gson = new Gson();
60
61     final HttpClient httpClient;
62
63     private @Nullable ScheduledFuture<?> future = null;
64
65     /**
66      * Our configuration
67      */
68     public JablotronBridgeConfig bridgeConfig = new JablotronBridgeConfig();
69
70     public JablotronBridgeHandler(Bridge thing, HttpClient httpClient) {
71         super(thing);
72         this.httpClient = httpClient;
73     }
74
75     @Override
76     public Collection<Class<? extends ThingHandlerService>> getServices() {
77         return Collections.singleton(JablotronDiscoveryService.class);
78     }
79
80     @Override
81     public void handleCommand(ChannelUID channelUID, Command command) {
82     }
83
84     @Override
85     public void initialize() {
86         bridgeConfig = getConfigAs(JablotronBridgeConfig.class);
87         scheduler.execute(this::login);
88         future = scheduler.scheduleWithFixedDelay(this::updateAlarmThings, 30, bridgeConfig.getRefresh(),
89                 TimeUnit.SECONDS);
90     }
91
92     private void updateAlarmThings() {
93         @Nullable
94         List<JablotronDiscoveredService> services = discoverServices();
95         if (services != null) {
96             for (JablotronDiscoveredService service : services) {
97                 updateAlarmThing(service);
98             }
99         }
100     }
101
102     private void updateAlarmThing(JablotronDiscoveredService service) {
103         for (Thing th : getThing().getThings()) {
104             JablotronAlarmHandler handler = (JablotronAlarmHandler) th.getHandler();
105
106             if (handler == null) {
107                 logger.debug("Thing handler is null");
108                 continue;
109             }
110
111             if (String.valueOf(service.getId()).equals(handler.thingConfig.getServiceId())) {
112                 if ("ENABLED".equals(service.getStatus())) {
113                     if (!service.getWarning().isEmpty()) {
114                         logger.debug("Alarm with service id: {} warning: {}", service.getId(), service.getWarning());
115                     }
116                     handler.setStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE, service.getWarning());
117                     if ("ALARM".equals(service.getWarning()) || "TAMPER".equals(service.getWarning())) {
118                         handler.triggerAlarm(service);
119                     }
120                     handler.setInService("SERVICE".equals(service.getWarning()));
121                 } else {
122                     logger.debug("Alarm with service id: {} is offline", service.getId());
123                     handler.setStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, service.getStatus());
124                 }
125             }
126         }
127     }
128
129     @Override
130     public void dispose() {
131         super.dispose();
132         ScheduledFuture<?> localFuture = future;
133         if (localFuture != null) {
134             localFuture.cancel(true);
135         }
136         logout();
137     }
138
139     private @Nullable <T> T sendJsonMessage(String url, String urlParameters, Class<T> classOfT) {
140         return sendMessage(url, urlParameters, classOfT, APPLICATION_JSON, true);
141     }
142
143     private @Nullable <T> T sendJsonMessage(String url, String urlParameters, Class<T> classOfT, boolean relogin) {
144         return sendMessage(url, urlParameters, classOfT, APPLICATION_JSON, relogin);
145     }
146
147     private @Nullable <T> T sendUrlEncodedMessage(String url, String urlParameters, Class<T> classOfT) {
148         return sendMessage(url, urlParameters, classOfT, WWW_FORM_URLENCODED, true);
149     }
150
151     private @Nullable <T> T sendMessage(String url, String urlParameters, Class<T> classOfT, String encoding,
152             boolean relogin) {
153         try {
154             ContentResponse resp = createRequest(url).content(new StringContentProvider(urlParameters), encoding)
155                     .send();
156
157             logger.trace("Request: {} with data: {}", url, urlParameters);
158             String line = resp.getContentAsString();
159             logger.trace("Response: {}", line);
160             return gson.fromJson(line, classOfT);
161         } catch (TimeoutException e) {
162             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
163                     "Timeout during calling url: " + url);
164         } catch (InterruptedException e) {
165             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
166                     "Interrupt during calling url: " + url);
167             Thread.currentThread().interrupt();
168         } catch (JsonSyntaxException e) {
169             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
170                     "Syntax error during calling url: " + url);
171         } catch (ExecutionException e) {
172             if (relogin) {
173                 if (e.getMessage().contains(AUTHENTICATION_CHALLENGE)) {
174                     relogin();
175                     return null;
176                 }
177             }
178             logger.debug("Error during calling url: {}", url, e);
179             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
180                     "Error during calling url: " + url);
181         }
182         return null;
183     }
184
185     protected synchronized void login() {
186         String url = JABLOTRON_API_URL + "userAuthorize.json";
187         String urlParameters = "{\"login\":\"" + bridgeConfig.getLogin() + "\", \"password\":\""
188                 + bridgeConfig.getPassword() + "\"}";
189         JablotronLoginResponse response = sendJsonMessage(url, urlParameters, JablotronLoginResponse.class, false);
190
191         if (response == null) {
192             return;
193         }
194
195         if (response.getHttpCode() != 200) {
196             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
197                     "Http error: " + response.getHttpCode());
198         } else {
199             updateStatus(ThingStatus.ONLINE);
200         }
201     }
202
203     protected void logout() {
204         String url = JABLOTRON_API_URL + "logout.json";
205         String urlParameters = "system=" + SYSTEM;
206
207         try {
208             ContentResponse resp = createRequest(url)
209                     .content(new StringContentProvider(urlParameters), WWW_FORM_URLENCODED).send();
210
211             if (logger.isTraceEnabled()) {
212                 String line = resp.getContentAsString();
213                 logger.trace("logout response: {}", line);
214             }
215         } catch (ExecutionException | TimeoutException | InterruptedException e) {
216             // Silence
217         }
218     }
219
220     public @Nullable List<JablotronDiscoveredService> discoverServices() {
221         String url = JABLOTRON_API_URL + "serviceListGet.json";
222         String urlParameters = "{\"list-type\": \"EXTENDED\",\"visibility\": \"VISIBLE\"}";
223         JablotronGetServiceResponse response = sendJsonMessage(url, urlParameters, JablotronGetServiceResponse.class);
224
225         if (response == null) {
226             return null;
227         }
228
229         if (response.getHttpCode() != 200) {
230             logger.debug("Error during service discovery, got http code: {}", response.getHttpCode());
231         }
232
233         return response.getData().getServices();
234     }
235
236     protected @Nullable JablotronControlResponse sendUserCode(Thing th, String section, String key, String status,
237             String code) {
238         JablotronAlarmHandler handler = (JablotronAlarmHandler) th.getHandler();
239
240         if (handler == null) {
241             logger.debug("Thing handler is null");
242             return null;
243         }
244
245         if (handler.isInService()) {
246             logger.debug("Cannot send command because the alarm is in the service mode");
247             return null;
248         }
249
250         String url = JABLOTRON_API_URL + "controlSegment.json";
251         String urlParameters = "service=" + th.getThingTypeUID().getId() + "&serviceId="
252                 + handler.thingConfig.getServiceId() + "&segmentId=" + section + "&segmentKey=" + key
253                 + "&expected_status=" + status + "&control_time=0&control_code=" + code + "&system=" + SYSTEM;
254
255         JablotronControlResponse response = sendUrlEncodedMessage(url, urlParameters, JablotronControlResponse.class);
256
257         if (response == null) {
258             return null;
259         }
260
261         if (!response.isStatus()) {
262             logger.debug("Error during sending user code: {}", response.getErrorMessage());
263         }
264         return response;
265     }
266
267     protected @Nullable List<JablotronHistoryDataEvent> sendGetEventHistory(Thing th, String alarm) {
268         String url = JABLOTRON_API_URL + alarm + "/eventHistoryGet.json";
269         JablotronAlarmHandler handler = (JablotronAlarmHandler) th.getHandler();
270
271         if (handler == null) {
272             logger.debug("Thing handler is null");
273             return null;
274         }
275
276         String urlParameters = "{\"limit\":1, \"service-id\":" + handler.thingConfig.getServiceId() + "}";
277         JablotronGetEventHistoryResponse response = sendJsonMessage(url, urlParameters,
278                 JablotronGetEventHistoryResponse.class);
279
280         if (response == null) {
281             return null;
282         }
283
284         if (200 != response.getHttpCode()) {
285             logger.debug("Got error while getting history with http code: {}", response.getHttpCode());
286         }
287         return response.getData().getEvents();
288     }
289
290     protected @Nullable JablotronDataUpdateResponse sendGetStatusRequest(Thing th) {
291         String url = JABLOTRON_API_URL + "dataUpdate.json";
292         JablotronAlarmHandler handler = (JablotronAlarmHandler) th.getHandler();
293
294         if (handler == null) {
295             logger.debug("Thing handler is null");
296             return null;
297         }
298
299         String urlParameters = "data=[{ \"filter_data\":[{\"data_type\":\"section\"},{\"data_type\":\"pgm\"},{\"data_type\":\"thermometer\"},{\"data_type\":\"thermostat\"}],\"service_type\":\""
300                 + th.getThingTypeUID().getId() + "\",\"service_id\":" + handler.thingConfig.getServiceId()
301                 + ",\"data_group\":\"serviceData\"}]&system=" + SYSTEM;
302
303         return sendUrlEncodedMessage(url, urlParameters, JablotronDataUpdateResponse.class);
304     }
305
306     protected @Nullable JablotronGetPGResponse sendGetProgrammableGates(Thing th, String alarm) {
307         String url = JABLOTRON_API_URL + alarm + "/programmableGatesGet.json";
308         JablotronAlarmHandler handler = (JablotronAlarmHandler) th.getHandler();
309
310         if (handler == null) {
311             logger.debug("Thing handler is null");
312             return null;
313         }
314
315         String urlParameters = "{\"connect-device\":false,\"list-type\":\"FULL\",\"service-id\":"
316                 + handler.thingConfig.getServiceId() + ",\"service-states\":true}";
317
318         return sendJsonMessage(url, urlParameters, JablotronGetPGResponse.class);
319     }
320
321     protected @Nullable JablotronGetSectionsResponse sendGetSections(Thing th, String alarm) {
322         String url = JABLOTRON_API_URL + alarm + "/sectionsGet.json";
323         JablotronAlarmHandler handler = (JablotronAlarmHandler) th.getHandler();
324
325         if (handler == null) {
326             logger.debug("Thing handler is null");
327             return null;
328         }
329
330         String urlParameters = "{\"connect-device\":false,\"list-type\":\"FULL\",\"service-id\":"
331                 + handler.thingConfig.getServiceId() + ",\"service-states\":true}";
332
333         return sendJsonMessage(url, urlParameters, JablotronGetSectionsResponse.class);
334     }
335
336     protected @Nullable JablotronGetSectionsResponse controlComponent(Thing th, String code, String action,
337             String value, String componentId) throws SecurityException {
338         JablotronAlarmHandler handler = (JablotronAlarmHandler) th.getHandler();
339
340         if (handler == null) {
341             logger.debug("Thing handler is null");
342             return null;
343         }
344
345         if (handler.isInService()) {
346             logger.debug("Cannot control component because the alarm is in the service mode");
347             return null;
348         }
349
350         String url = JABLOTRON_API_URL + handler.getAlarmName() + "/controlComponent.json";
351         String urlParameters = "{\"authorization\":{\"authorization-code\":\"" + code
352                 + "\"},\"control-components\":[{\"actions\":{\"action\":\"" + action + "\",\"value\":\"" + value
353                 + "\"},\"component-id\":\"" + componentId + "\"}],\"service-id\":" + handler.thingConfig.getServiceId()
354                 + "}";
355
356         return sendJsonMessage(url, urlParameters, JablotronGetSectionsResponse.class);
357     }
358
359     private Request createRequest(String url) {
360         return httpClient.newRequest(url).method(HttpMethod.POST).header(HttpHeader.ACCEPT, APPLICATION_JSON)
361                 .header(HttpHeader.ACCEPT_LANGUAGE, bridgeConfig.getLang()).header(HttpHeader.ACCEPT_ENCODING, "*")
362                 .header("x-vendor-id", VENDOR).agent(AGENT).timeout(TIMEOUT_SEC, TimeUnit.SECONDS);
363     }
364
365     private void relogin() {
366         logger.debug("doing relogin");
367         login();
368     }
369 }