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.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.JablotronControlResponse;
36 import org.openhab.binding.jablotron.internal.model.JablotronDataUpdateResponse;
37 import org.openhab.binding.jablotron.internal.model.JablotronDiscoveredService;
38 import org.openhab.binding.jablotron.internal.model.JablotronGetEventHistoryResponse;
39 import org.openhab.binding.jablotron.internal.model.JablotronGetServiceResponse;
40 import org.openhab.binding.jablotron.internal.model.JablotronHistoryDataEvent;
41 import org.openhab.binding.jablotron.internal.model.JablotronLoginResponse;
42 import org.openhab.binding.jablotron.internal.model.ja100f.JablotronGetPGResponse;
43 import org.openhab.binding.jablotron.internal.model.ja100f.JablotronGetSectionsResponse;
44 import org.openhab.core.thing.Bridge;
45 import org.openhab.core.thing.ChannelUID;
46 import org.openhab.core.thing.Thing;
47 import org.openhab.core.thing.ThingStatus;
48 import org.openhab.core.thing.ThingStatusDetail;
49 import org.openhab.core.thing.binding.BaseBridgeHandler;
50 import org.openhab.core.thing.binding.ThingHandlerService;
51 import org.openhab.core.types.Command;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
55 import com.google.gson.Gson;
56 import com.google.gson.JsonSyntaxException;
59 * The {@link JablotronBridgeHandler} is responsible for handling commands, which are
60 * sent to one of the channels.
62 * @author Ondrej Pecta - Initial contribution
65 public class JablotronBridgeHandler extends BaseBridgeHandler {
67 private final Logger logger = LoggerFactory.getLogger(JablotronBridgeHandler.class);
69 private final Gson gson = new Gson();
71 final HttpClient httpClient;
73 private @Nullable ScheduledFuture<?> future = null;
78 public JablotronBridgeConfig bridgeConfig = new JablotronBridgeConfig();
80 public JablotronBridgeHandler(Bridge thing, HttpClient httpClient) {
82 this.httpClient = httpClient;
86 public Collection<Class<? extends ThingHandlerService>> getServices() {
87 return Collections.singleton(JablotronDiscoveryService.class);
91 public void handleCommand(ChannelUID channelUID, Command command) {
95 public void initialize() {
96 bridgeConfig = getConfigAs(JablotronBridgeConfig.class);
97 scheduler.execute(this::login);
98 future = scheduler.scheduleWithFixedDelay(this::updateAlarmThings, 30, bridgeConfig.getRefresh(),
102 private void updateAlarmThings() {
103 logger.debug("Updating overall alarm's statuses...");
105 List<JablotronDiscoveredService> services = discoverServices();
106 if (services != null) {
107 Bridge localBridge = getThing();
108 if (localBridge != null && ThingStatus.ONLINE != localBridge.getStatus()) {
109 updateStatus(ThingStatus.ONLINE);
111 for (JablotronDiscoveredService service : services) {
112 updateAlarmThing(service);
117 private void updateAlarmThing(JablotronDiscoveredService service) {
118 for (Thing th : getThing().getThings()) {
119 if (ThingStatus.ONLINE != th.getStatus()) {
120 logger.debug("Thing {} is not online", th.getUID());
124 JablotronAlarmHandler handler = (JablotronAlarmHandler) th.getHandler();
126 if (handler == null) {
127 logger.debug("Thing handler is null");
131 if (String.valueOf(service.getId()).equals(handler.thingConfig.getServiceId())) {
132 if ("ENABLED".equals(service.getStatus())) {
133 if (!service.getWarning().isEmpty()) {
134 logger.debug("Alarm with service id: {} warning: {}", service.getId(), service.getWarning());
136 handler.setStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE, service.getWarning());
137 if ("ALARM".equals(service.getWarning()) || "TAMPER".equals(service.getWarning())) {
138 handler.triggerAlarm(service);
140 handler.setInService("SERVICE".equals(service.getWarning()));
142 logger.debug("Alarm with service id: {} is offline", service.getId());
143 handler.setStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, service.getStatus());
150 public void dispose() {
152 ScheduledFuture<?> localFuture = future;
153 if (localFuture != null) {
154 localFuture.cancel(true);
159 private @Nullable <T> T sendJsonMessage(String url, String urlParameters, Class<T> classOfT) {
160 return sendMessage(url, urlParameters, classOfT, APPLICATION_JSON, true);
163 private @Nullable <T> T sendJsonMessage(String url, String urlParameters, Class<T> classOfT, boolean relogin) {
164 return sendMessage(url, urlParameters, classOfT, APPLICATION_JSON, relogin);
167 private @Nullable <T> T sendUrlEncodedMessage(String url, String urlParameters, Class<T> classOfT) {
168 return sendMessage(url, urlParameters, classOfT, WWW_FORM_URLENCODED, true);
171 private @Nullable <T> T sendMessage(String url, String urlParameters, Class<T> classOfT, String encoding,
175 ContentResponse resp = createRequest(url).content(new StringContentProvider(urlParameters), encoding)
178 logger.trace("Request: {} with data: {}", url, urlParameters);
179 line = resp.getContentAsString();
180 logger.trace("Response: {}", line);
181 return gson.fromJson(line, classOfT);
182 } catch (TimeoutException e) {
183 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
184 "Timeout during calling url: " + url);
185 } catch (InterruptedException e) {
186 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
187 "Interrupt during calling url: " + url);
188 Thread.currentThread().interrupt();
189 } catch (JsonSyntaxException e) {
190 logger.debug("Invalid JSON received: {}", line);
191 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
192 "Syntax error during calling url: " + url);
193 } catch (ExecutionException e) {
195 if (e.getMessage().contains(AUTHENTICATION_CHALLENGE)) {
200 logger.debug("Error during calling url: {}", url, e);
201 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
202 "Error during calling url: " + url);
207 protected synchronized void login() {
208 String url = JABLOTRON_API_URL + "userAuthorize.json";
209 String urlParameters = "{\"login\":\"" + bridgeConfig.getLogin() + "\", \"password\":\""
210 + bridgeConfig.getPassword() + "\"}";
211 JablotronLoginResponse response = sendJsonMessage(url, urlParameters, JablotronLoginResponse.class, false);
213 if (response == null) {
217 if (response.getHttpCode() != 200) {
218 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
219 "Http error: " + response.getHttpCode());
221 updateStatus(ThingStatus.ONLINE);
225 protected void logout() {
226 String url = JABLOTRON_API_URL + "logout.json";
227 String urlParameters = "system=" + SYSTEM;
230 ContentResponse resp = createRequest(url)
231 .content(new StringContentProvider(urlParameters), WWW_FORM_URLENCODED).send();
233 if (logger.isTraceEnabled()) {
234 String line = resp.getContentAsString();
235 logger.trace("logout response: {}", line);
237 } catch (ExecutionException | TimeoutException | InterruptedException e) {
242 public @Nullable List<JablotronDiscoveredService> discoverServices() {
243 String url = JABLOTRON_API_URL + "serviceListGet.json";
244 String urlParameters = "{\"list-type\": \"EXTENDED\",\"visibility\": \"VISIBLE\"}";
245 JablotronGetServiceResponse response = sendJsonMessage(url, urlParameters, JablotronGetServiceResponse.class);
247 if (response == null) {
251 if (response.getHttpCode() != 200) {
252 logger.debug("Error during service discovery, got http code: {}", response.getHttpCode());
255 return response.getData().getServices();
258 protected @Nullable JablotronControlResponse sendUserCode(Thing th, String section, String key, String status,
260 JablotronAlarmHandler handler = (JablotronAlarmHandler) th.getHandler();
262 if (handler == null) {
263 logger.debug("Thing handler is null");
267 if (handler.isInService()) {
268 logger.debug("Cannot send command because the alarm is in the service mode");
272 String url = JABLOTRON_API_URL + "controlSegment.json";
273 String urlParameters = "service=" + th.getThingTypeUID().getId() + "&serviceId="
274 + handler.thingConfig.getServiceId() + "&segmentId=" + section + "&segmentKey=" + key
275 + "&expected_status=" + status + "&control_time=0&control_code=" + code + "&system=" + SYSTEM;
277 JablotronControlResponse response = sendUrlEncodedMessage(url, urlParameters, JablotronControlResponse.class);
279 if (response == null) {
283 if (!response.isStatus()) {
284 logger.debug("Error during sending user code: {}", response.getErrorMessage());
289 protected @Nullable List<JablotronHistoryDataEvent> sendGetEventHistory(Thing th, String alarm) {
290 String url = JABLOTRON_API_URL + alarm + "/eventHistoryGet.json";
291 JablotronAlarmHandler handler = (JablotronAlarmHandler) th.getHandler();
293 if (handler == null) {
294 logger.debug("Thing handler is null");
298 String urlParameters = "{\"limit\":1, \"service-id\":" + handler.thingConfig.getServiceId() + "}";
299 JablotronGetEventHistoryResponse response = sendJsonMessage(url, urlParameters,
300 JablotronGetEventHistoryResponse.class);
302 if (response == null) {
306 if (200 != response.getHttpCode()) {
307 logger.debug("Got error while getting history with http code: {}", response.getHttpCode());
309 return response.getData().getEvents();
312 protected @Nullable JablotronDataUpdateResponse sendGetStatusRequest(Thing th) {
313 String url = JABLOTRON_API_URL + "dataUpdate.json";
314 JablotronAlarmHandler handler = (JablotronAlarmHandler) th.getHandler();
316 if (handler == null) {
317 logger.debug("Thing handler is null");
321 String urlParameters = "data=[{ \"filter_data\":[{\"data_type\":\"section\"},{\"data_type\":\"pgm\"},{\"data_type\":\"thermometer\"},{\"data_type\":\"thermostat\"}],\"service_type\":\""
322 + th.getThingTypeUID().getId() + "\",\"service_id\":" + handler.thingConfig.getServiceId()
323 + ",\"data_group\":\"serviceData\"}]&system=" + SYSTEM;
325 return sendUrlEncodedMessage(url, urlParameters, JablotronDataUpdateResponse.class);
328 protected @Nullable JablotronGetPGResponse sendGetProgrammableGates(Thing th, String alarm) {
329 String url = JABLOTRON_API_URL + alarm + "/programmableGatesGet.json";
330 JablotronAlarmHandler handler = (JablotronAlarmHandler) th.getHandler();
332 if (handler == null) {
333 logger.debug("Thing handler is null");
337 String urlParameters = "{\"connect-device\":false,\"list-type\":\"FULL\",\"service-id\":"
338 + handler.thingConfig.getServiceId() + ",\"service-states\":true}";
340 return sendJsonMessage(url, urlParameters, JablotronGetPGResponse.class);
343 protected @Nullable JablotronGetSectionsResponse sendGetSections(Thing th, String alarm) {
344 String url = JABLOTRON_API_URL + alarm + "/sectionsGet.json";
345 JablotronAlarmHandler handler = (JablotronAlarmHandler) th.getHandler();
347 if (handler == null) {
348 logger.debug("Thing handler is null");
352 String urlParameters = "{\"connect-device\":false,\"list-type\":\"FULL\",\"service-id\":"
353 + handler.thingConfig.getServiceId() + ",\"service-states\":true}";
355 return sendJsonMessage(url, urlParameters, JablotronGetSectionsResponse.class);
358 protected @Nullable JablotronGetSectionsResponse controlComponent(Thing th, String code, String action,
359 String value, String componentId) throws SecurityException {
360 JablotronAlarmHandler handler = (JablotronAlarmHandler) th.getHandler();
362 if (handler == null) {
363 logger.debug("Thing handler is null");
367 if (handler.isInService()) {
368 logger.debug("Cannot control component because the alarm is in the service mode");
372 String url = JABLOTRON_API_URL + handler.getAlarmName() + "/controlComponent.json";
373 String urlParameters = "{\"authorization\":{\"authorization-code\":\"" + code
374 + "\"},\"control-components\":[{\"actions\":{\"action\":\"" + action + "\",\"value\":\"" + value
375 + "\"},\"component-id\":\"" + componentId + "\"}],\"service-id\":" + handler.thingConfig.getServiceId()
378 return sendJsonMessage(url, urlParameters, JablotronGetSectionsResponse.class);
381 private Request createRequest(String url) {
382 return httpClient.newRequest(url).method(HttpMethod.POST).header(HttpHeader.ACCEPT, APPLICATION_JSON)
383 .header(HttpHeader.ACCEPT_LANGUAGE, bridgeConfig.getLang()).header(HttpHeader.ACCEPT_ENCODING, "*")
384 .header("x-vendor-id", VENDOR).agent(AGENT).timeout(TIMEOUT_SEC, TimeUnit.SECONDS);
387 private void relogin() {
388 logger.debug("doing relogin");