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() {
93 logger.debug("Updating overall alarm's statuses...");
95 List<JablotronDiscoveredService> services = discoverServices();
96 if (services != null) {
97 Bridge localBridge = getThing();
98 if (localBridge != null && ThingStatus.ONLINE != localBridge.getStatus()) {
99 updateStatus(ThingStatus.ONLINE);
101 for (JablotronDiscoveredService service : services) {
102 updateAlarmThing(service);
107 private void updateAlarmThing(JablotronDiscoveredService service) {
108 for (Thing th : getThing().getThings()) {
109 if (ThingStatus.ONLINE != th.getStatus()) {
110 logger.debug("Thing {} is not online", th.getUID());
114 JablotronAlarmHandler handler = (JablotronAlarmHandler) th.getHandler();
116 if (handler == null) {
117 logger.debug("Thing handler is null");
121 if (String.valueOf(service.getId()).equals(handler.thingConfig.getServiceId())) {
122 if ("ENABLED".equals(service.getStatus())) {
123 if (!service.getWarning().isEmpty()) {
124 logger.debug("Alarm with service id: {} warning: {}", service.getId(), service.getWarning());
126 handler.setStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE, service.getWarning());
127 if ("ALARM".equals(service.getWarning()) || "TAMPER".equals(service.getWarning())) {
128 handler.triggerAlarm(service);
130 handler.setInService("SERVICE".equals(service.getWarning()));
132 logger.debug("Alarm with service id: {} is offline", service.getId());
133 handler.setStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, service.getStatus());
140 public void dispose() {
142 ScheduledFuture<?> localFuture = future;
143 if (localFuture != null) {
144 localFuture.cancel(true);
149 private @Nullable <T> T sendJsonMessage(String url, String urlParameters, Class<T> classOfT) {
150 return sendMessage(url, urlParameters, classOfT, APPLICATION_JSON, true);
153 private @Nullable <T> T sendJsonMessage(String url, String urlParameters, Class<T> classOfT, boolean relogin) {
154 return sendMessage(url, urlParameters, classOfT, APPLICATION_JSON, relogin);
157 private @Nullable <T> T sendUrlEncodedMessage(String url, String urlParameters, Class<T> classOfT) {
158 return sendMessage(url, urlParameters, classOfT, WWW_FORM_URLENCODED, true);
161 private @Nullable <T> T sendMessage(String url, String urlParameters, Class<T> classOfT, String encoding,
165 ContentResponse resp = createRequest(url).content(new StringContentProvider(urlParameters), encoding)
168 logger.trace("Request: {} with data: {}", url, urlParameters);
169 line = resp.getContentAsString();
170 logger.trace("Response: {}", line);
171 return gson.fromJson(line, classOfT);
172 } catch (TimeoutException e) {
173 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
174 "Timeout during calling url: " + url);
175 } catch (InterruptedException e) {
176 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
177 "Interrupt during calling url: " + url);
178 Thread.currentThread().interrupt();
179 } catch (JsonSyntaxException e) {
180 logger.debug("Invalid JSON received: {}", line);
181 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
182 "Syntax error during calling url: " + url);
183 } catch (ExecutionException e) {
185 if (e.getMessage().contains(AUTHENTICATION_CHALLENGE)) {
190 logger.debug("Error during calling url: {}", url, e);
191 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
192 "Error during calling url: " + url);
197 protected synchronized void login() {
198 String url = JABLOTRON_API_URL + "userAuthorize.json";
199 String urlParameters = "{\"login\":\"" + bridgeConfig.getLogin() + "\", \"password\":\""
200 + bridgeConfig.getPassword() + "\"}";
201 JablotronLoginResponse response = sendJsonMessage(url, urlParameters, JablotronLoginResponse.class, false);
203 if (response == null) {
207 if (response.getHttpCode() != 200) {
208 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
209 "Http error: " + response.getHttpCode());
211 updateStatus(ThingStatus.ONLINE);
215 protected void logout() {
216 String url = JABLOTRON_API_URL + "logout.json";
217 String urlParameters = "system=" + SYSTEM;
220 ContentResponse resp = createRequest(url)
221 .content(new StringContentProvider(urlParameters), WWW_FORM_URLENCODED).send();
223 if (logger.isTraceEnabled()) {
224 String line = resp.getContentAsString();
225 logger.trace("logout response: {}", line);
227 } catch (ExecutionException | TimeoutException | InterruptedException e) {
232 public @Nullable List<JablotronDiscoveredService> discoverServices() {
233 String url = JABLOTRON_API_URL + "serviceListGet.json";
234 String urlParameters = "{\"list-type\": \"EXTENDED\",\"visibility\": \"VISIBLE\"}";
235 JablotronGetServiceResponse response = sendJsonMessage(url, urlParameters, JablotronGetServiceResponse.class);
237 if (response == null) {
241 if (response.getHttpCode() != 200) {
242 logger.debug("Error during service discovery, got http code: {}", response.getHttpCode());
245 return response.getData().getServices();
248 protected @Nullable JablotronControlResponse sendUserCode(Thing th, String section, String key, String status,
250 JablotronAlarmHandler handler = (JablotronAlarmHandler) th.getHandler();
252 if (handler == null) {
253 logger.debug("Thing handler is null");
257 if (handler.isInService()) {
258 logger.debug("Cannot send command because the alarm is in the service mode");
262 String url = JABLOTRON_API_URL + "controlSegment.json";
263 String urlParameters = "service=" + th.getThingTypeUID().getId() + "&serviceId="
264 + handler.thingConfig.getServiceId() + "&segmentId=" + section + "&segmentKey=" + key
265 + "&expected_status=" + status + "&control_time=0&control_code=" + code + "&system=" + SYSTEM;
267 JablotronControlResponse response = sendUrlEncodedMessage(url, urlParameters, JablotronControlResponse.class);
269 if (response == null) {
273 if (!response.isStatus()) {
274 logger.debug("Error during sending user code: {}", response.getErrorMessage());
279 protected @Nullable List<JablotronHistoryDataEvent> sendGetEventHistory(Thing th, String alarm) {
280 String url = JABLOTRON_API_URL + alarm + "/eventHistoryGet.json";
281 JablotronAlarmHandler handler = (JablotronAlarmHandler) th.getHandler();
283 if (handler == null) {
284 logger.debug("Thing handler is null");
288 String urlParameters = "{\"limit\":1, \"service-id\":" + handler.thingConfig.getServiceId() + "}";
289 JablotronGetEventHistoryResponse response = sendJsonMessage(url, urlParameters,
290 JablotronGetEventHistoryResponse.class);
292 if (response == null) {
296 if (200 != response.getHttpCode()) {
297 logger.debug("Got error while getting history with http code: {}", response.getHttpCode());
299 return response.getData().getEvents();
302 protected @Nullable JablotronDataUpdateResponse sendGetStatusRequest(Thing th) {
303 String url = JABLOTRON_API_URL + "dataUpdate.json";
304 JablotronAlarmHandler handler = (JablotronAlarmHandler) th.getHandler();
306 if (handler == null) {
307 logger.debug("Thing handler is null");
311 String urlParameters = "data=[{ \"filter_data\":[{\"data_type\":\"section\"},{\"data_type\":\"pgm\"},{\"data_type\":\"thermometer\"},{\"data_type\":\"thermostat\"}],\"service_type\":\""
312 + th.getThingTypeUID().getId() + "\",\"service_id\":" + handler.thingConfig.getServiceId()
313 + ",\"data_group\":\"serviceData\"}]&system=" + SYSTEM;
315 return sendUrlEncodedMessage(url, urlParameters, JablotronDataUpdateResponse.class);
318 protected @Nullable JablotronGetPGResponse sendGetProgrammableGates(Thing th, String alarm) {
319 String url = JABLOTRON_API_URL + alarm + "/programmableGatesGet.json";
320 JablotronAlarmHandler handler = (JablotronAlarmHandler) th.getHandler();
322 if (handler == null) {
323 logger.debug("Thing handler is null");
327 String urlParameters = "{\"connect-device\":false,\"list-type\":\"FULL\",\"service-id\":"
328 + handler.thingConfig.getServiceId() + ",\"service-states\":true}";
330 return sendJsonMessage(url, urlParameters, JablotronGetPGResponse.class);
333 protected @Nullable JablotronGetSectionsResponse sendGetSections(Thing th, String alarm) {
334 String url = JABLOTRON_API_URL + alarm + "/sectionsGet.json";
335 JablotronAlarmHandler handler = (JablotronAlarmHandler) th.getHandler();
337 if (handler == null) {
338 logger.debug("Thing handler is null");
342 String urlParameters = "{\"connect-device\":false,\"list-type\":\"FULL\",\"service-id\":"
343 + handler.thingConfig.getServiceId() + ",\"service-states\":true}";
345 return sendJsonMessage(url, urlParameters, JablotronGetSectionsResponse.class);
348 protected @Nullable JablotronGetSectionsResponse controlComponent(Thing th, String code, String action,
349 String value, String componentId) throws SecurityException {
350 JablotronAlarmHandler handler = (JablotronAlarmHandler) th.getHandler();
352 if (handler == null) {
353 logger.debug("Thing handler is null");
357 if (handler.isInService()) {
358 logger.debug("Cannot control component because the alarm is in the service mode");
362 String url = JABLOTRON_API_URL + handler.getAlarmName() + "/controlComponent.json";
363 String urlParameters = "{\"authorization\":{\"authorization-code\":\"" + code
364 + "\"},\"control-components\":[{\"actions\":{\"action\":\"" + action + "\",\"value\":\"" + value
365 + "\"},\"component-id\":\"" + componentId + "\"}],\"service-id\":" + handler.thingConfig.getServiceId()
368 return sendJsonMessage(url, urlParameters, JablotronGetSectionsResponse.class);
371 private Request createRequest(String url) {
372 return httpClient.newRequest(url).method(HttpMethod.POST).header(HttpHeader.ACCEPT, APPLICATION_JSON)
373 .header(HttpHeader.ACCEPT_LANGUAGE, bridgeConfig.getLang()).header(HttpHeader.ACCEPT_ENCODING, "*")
374 .header("x-vendor-id", VENDOR).agent(AGENT).timeout(TIMEOUT_SEC, TimeUnit.SECONDS);
377 private void relogin() {
378 logger.debug("doing relogin");