2 * Copyright (c) 2010-2020 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.jablotron.internal.handler;
15 import static org.openhab.binding.jablotron.JablotronBindingConstants.*;
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;
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;
45 import com.google.gson.Gson;
46 import com.google.gson.JsonSyntaxException;
49 * The {@link JablotronBridgeHandler} is responsible for handling commands, which are
50 * sent to one of the channels.
52 * @author Ondrej Pecta - Initial contribution
55 public class JablotronBridgeHandler extends BaseBridgeHandler {
57 private final Logger logger = LoggerFactory.getLogger(JablotronBridgeHandler.class);
59 private final Gson gson = new Gson();
61 final HttpClient httpClient;
63 private @Nullable ScheduledFuture<?> future = null;
68 public JablotronBridgeConfig bridgeConfig = new JablotronBridgeConfig();
70 public JablotronBridgeHandler(Bridge thing, HttpClient httpClient) {
72 this.httpClient = httpClient;
76 public Collection<Class<? extends ThingHandlerService>> getServices() {
77 return Collections.singleton(JablotronDiscoveryService.class);
81 public void handleCommand(ChannelUID channelUID, Command command) {
85 public void initialize() {
86 bridgeConfig = getConfigAs(JablotronBridgeConfig.class);
87 scheduler.execute(this::login);
88 future = scheduler.scheduleWithFixedDelay(this::updateAlarmThings, 30, bridgeConfig.getRefresh(),
92 private void updateAlarmThings() {
94 List<JablotronDiscoveredService> services = discoverServices();
95 if (services != null) {
96 for (JablotronDiscoveredService service : services) {
97 updateAlarmThing(service);
102 private void updateAlarmThing(JablotronDiscoveredService service) {
103 for (Thing th : getThing().getThings()) {
104 JablotronAlarmHandler handler = (JablotronAlarmHandler) th.getHandler();
106 if (handler == null) {
107 logger.debug("Thing handler is null");
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());
116 handler.setStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE, service.getWarning());
117 if ("ALARM".equals(service.getWarning()) || "TAMPER".equals(service.getWarning())) {
118 handler.triggerAlarm(service);
120 handler.setInService("SERVICE".equals(service.getWarning()));
122 logger.debug("Alarm with service id: {} is offline", service.getId());
123 handler.setStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, service.getStatus());
130 public void dispose() {
132 ScheduledFuture<?> localFuture = future;
133 if (localFuture != null) {
134 localFuture.cancel(true);
139 private @Nullable <T> T sendJsonMessage(String url, String urlParameters, Class<T> classOfT) {
140 return sendMessage(url, urlParameters, classOfT, APPLICATION_JSON, true);
143 private @Nullable <T> T sendJsonMessage(String url, String urlParameters, Class<T> classOfT, boolean relogin) {
144 return sendMessage(url, urlParameters, classOfT, APPLICATION_JSON, relogin);
147 private @Nullable <T> T sendUrlEncodedMessage(String url, String urlParameters, Class<T> classOfT) {
148 return sendMessage(url, urlParameters, classOfT, WWW_FORM_URLENCODED, true);
151 private @Nullable <T> T sendMessage(String url, String urlParameters, Class<T> classOfT, String encoding,
154 ContentResponse resp = createRequest(url).content(new StringContentProvider(urlParameters), encoding)
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) {
173 if (e.getMessage().contains(AUTHENTICATION_CHALLENGE)) {
178 logger.debug("Error during calling url: {}", url, e);
179 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
180 "Error during calling url: " + url);
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);
191 if (response == null) {
195 if (response.getHttpCode() != 200) {
196 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
197 "Http error: " + response.getHttpCode());
199 updateStatus(ThingStatus.ONLINE);
203 protected void logout() {
204 String url = JABLOTRON_API_URL + "logout.json";
205 String urlParameters = "system=" + SYSTEM;
208 ContentResponse resp = createRequest(url)
209 .content(new StringContentProvider(urlParameters), WWW_FORM_URLENCODED).send();
211 if (logger.isTraceEnabled()) {
212 String line = resp.getContentAsString();
213 logger.trace("logout response: {}", line);
215 } catch (ExecutionException | TimeoutException | InterruptedException e) {
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);
225 if (response == null) {
229 if (response.getHttpCode() != 200) {
230 logger.debug("Error during service discovery, got http code: {}", response.getHttpCode());
233 return response.getData().getServices();
236 protected @Nullable JablotronControlResponse sendUserCode(Thing th, String section, String key, String status,
238 JablotronAlarmHandler handler = (JablotronAlarmHandler) th.getHandler();
240 if (handler == null) {
241 logger.debug("Thing handler is null");
245 if (handler.isInService()) {
246 logger.debug("Cannot send command because the alarm is in the service mode");
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;
255 JablotronControlResponse response = sendUrlEncodedMessage(url, urlParameters, JablotronControlResponse.class);
257 if (response == null) {
261 if (!response.isStatus()) {
262 logger.debug("Error during sending user code: {}", response.getErrorMessage());
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();
271 if (handler == null) {
272 logger.debug("Thing handler is null");
276 String urlParameters = "{\"limit\":1, \"service-id\":" + handler.thingConfig.getServiceId() + "}";
277 JablotronGetEventHistoryResponse response = sendJsonMessage(url, urlParameters,
278 JablotronGetEventHistoryResponse.class);
280 if (response == null) {
284 if (200 != response.getHttpCode()) {
285 logger.debug("Got error while getting history with http code: {}", response.getHttpCode());
287 return response.getData().getEvents();
290 protected @Nullable JablotronDataUpdateResponse sendGetStatusRequest(Thing th) {
291 String url = JABLOTRON_API_URL + "dataUpdate.json";
292 JablotronAlarmHandler handler = (JablotronAlarmHandler) th.getHandler();
294 if (handler == null) {
295 logger.debug("Thing handler is null");
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;
303 return sendUrlEncodedMessage(url, urlParameters, JablotronDataUpdateResponse.class);
306 protected @Nullable JablotronGetPGResponse sendGetProgrammableGates(Thing th, String alarm) {
307 String url = JABLOTRON_API_URL + alarm + "/programmableGatesGet.json";
308 JablotronAlarmHandler handler = (JablotronAlarmHandler) th.getHandler();
310 if (handler == null) {
311 logger.debug("Thing handler is null");
315 String urlParameters = "{\"connect-device\":false,\"list-type\":\"FULL\",\"service-id\":"
316 + handler.thingConfig.getServiceId() + ",\"service-states\":true}";
318 return sendJsonMessage(url, urlParameters, JablotronGetPGResponse.class);
321 protected @Nullable JablotronGetSectionsResponse sendGetSections(Thing th, String alarm) {
322 String url = JABLOTRON_API_URL + alarm + "/sectionsGet.json";
323 JablotronAlarmHandler handler = (JablotronAlarmHandler) th.getHandler();
325 if (handler == null) {
326 logger.debug("Thing handler is null");
330 String urlParameters = "{\"connect-device\":false,\"list-type\":\"FULL\",\"service-id\":"
331 + handler.thingConfig.getServiceId() + ",\"service-states\":true}";
333 return sendJsonMessage(url, urlParameters, JablotronGetSectionsResponse.class);
336 protected @Nullable JablotronGetSectionsResponse controlComponent(Thing th, String code, String action,
337 String value, String componentId) throws SecurityException {
338 JablotronAlarmHandler handler = (JablotronAlarmHandler) th.getHandler();
340 if (handler == null) {
341 logger.debug("Thing handler is null");
345 if (handler.isInService()) {
346 logger.debug("Cannot control component because the alarm is in the service mode");
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()
356 return sendJsonMessage(url, urlParameters, JablotronGetSectionsResponse.class);
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);
365 private void relogin() {
366 logger.debug("doing relogin");