]> git.basschouten.com Git - openhab-addons.git/blob
254904df7c78893eb2b6e10276913fea544938a9
[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.time.Instant;
18 import java.time.ZoneId;
19 import java.time.ZonedDateTime;
20 import java.time.format.DateTimeFormatter;
21 import java.util.List;
22 import java.util.concurrent.ScheduledFuture;
23 import java.util.concurrent.TimeUnit;
24
25 import org.eclipse.jdt.annotation.NonNullByDefault;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.openhab.binding.jablotron.internal.config.JablotronDeviceConfig;
28 import org.openhab.binding.jablotron.internal.model.*;
29 import org.openhab.core.cache.ExpiringCache;
30 import org.openhab.core.library.types.DateTimeType;
31 import org.openhab.core.library.types.StringType;
32 import org.openhab.core.thing.*;
33 import org.openhab.core.thing.binding.BaseThingHandler;
34 import org.openhab.core.types.State;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37
38 import com.google.gson.Gson;
39
40 /**
41  * The {@link JablotronAlarmHandler} is responsible for handling commands, which are
42  * sent to one of the channels.
43  *
44  * @author Ondrej Pecta - Initial contribution
45  */
46 @NonNullByDefault
47 public abstract class JablotronAlarmHandler extends BaseThingHandler {
48
49     private final Logger logger = LoggerFactory.getLogger(getClass());
50
51     protected final Gson gson = new Gson();
52
53     protected JablotronDeviceConfig thingConfig = new JablotronDeviceConfig();
54
55     private String lastWarningTime = "";
56
57     protected String alarmName = "";
58
59     private boolean inService = false;
60
61     protected @Nullable ScheduledFuture<?> future = null;
62
63     protected @Nullable ExpiringCache<JablotronDataUpdateResponse> dataCache;
64     protected ExpiringCache<List<JablotronHistoryDataEvent>> eventCache;
65
66     public JablotronAlarmHandler(Thing thing, String alarmName) {
67         super(thing);
68         this.alarmName = alarmName;
69         eventCache = new ExpiringCache<>(CACHE_TIMEOUT_MS, this::sendGetEventHistory);
70     }
71
72     @Override
73     public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
74         super.bridgeStatusChanged(bridgeStatusInfo);
75         if (ThingStatus.UNINITIALIZED == bridgeStatusInfo.getStatus()) {
76             cleanup();
77         }
78     }
79
80     @Override
81     public void dispose() {
82         super.dispose();
83         cleanup();
84     }
85
86     @Override
87     public void initialize() {
88         thingConfig = getConfigAs(JablotronDeviceConfig.class);
89         future = scheduler.scheduleWithFixedDelay(this::updateAlarmStatus, 1, thingConfig.getRefresh(),
90                 TimeUnit.SECONDS);
91         updateStatus(ThingStatus.ONLINE);
92     }
93
94     public boolean isInService() {
95         return inService;
96     }
97
98     public String getAlarmName() {
99         return alarmName;
100     }
101
102     protected abstract void updateSegmentStatus(JablotronServiceDetailSegment segment);
103
104     protected void updateSegmentStatus(String segmentName, @Nullable JablotronDataUpdateResponse dataUpdate) {
105         if (dataUpdate == null || !dataUpdate.isStatus()) {
106             return;
107         }
108         List<JablotronServiceData> serviceData = dataUpdate.getData().getServiceData();
109         for (JablotronServiceData data : serviceData) {
110             if (!thingConfig.getServiceId().equals(data.getServiceId())) {
111                 continue;
112             }
113             List<JablotronService> services = data.getData();
114             for (JablotronService service : services) {
115                 JablotronServiceDetail detail = service.getData();
116                 for (JablotronServiceDetailSegment segment : detail.getSegments()) {
117                     if (segmentName.toUpperCase().equals(segment.getSegmentId())) {
118                         updateSegmentStatus(segment);
119                     }
120                 }
121             }
122         }
123     }
124
125     private void cleanup() {
126         logger.debug("doing cleanup...");
127         ScheduledFuture<?> localFuture = future;
128         if (localFuture != null) {
129             localFuture.cancel(true);
130         }
131     }
132
133     protected State getCheckTime() {
134         ZonedDateTime zdt = ZonedDateTime.ofInstant(Instant.now(), ZoneId.systemDefault());
135         return new DateTimeType(zdt);
136     }
137
138     protected synchronized @Nullable JablotronDataUpdateResponse sendGetStatusRequest() {
139         JablotronBridgeHandler handler = getBridgeHandler();
140         if (handler != null) {
141             return handler.sendGetStatusRequest(getThing());
142         }
143         return null;
144     }
145
146     protected synchronized boolean updateAlarmStatus() {
147         JablotronDataUpdateResponse dataUpdate = sendGetStatusRequest();
148         if (dataUpdate == null) {
149             return false;
150         }
151
152         if (dataUpdate.isStatus()) {
153             updateState(CHANNEL_LAST_CHECK_TIME, getCheckTime());
154             List<JablotronServiceData> serviceData = dataUpdate.getData().getServiceData();
155             for (JablotronServiceData data : serviceData) {
156                 if (!thingConfig.getServiceId().equals(data.getServiceId())) {
157                     continue;
158                 }
159                 List<JablotronService> services = data.getData();
160                 for (JablotronService service : services) {
161                     JablotronServiceDetail detail = service.getData();
162                     for (JablotronServiceDetailSegment segment : detail.getSegments()) {
163                         updateSegmentStatus(segment);
164                     }
165                 }
166
167             }
168         } else {
169             logger.debug("Error during alarm status update: {}", dataUpdate.getErrorMessage());
170         }
171
172         List<JablotronHistoryDataEvent> events = sendGetEventHistory();
173         if (events != null && events.size() > 0) {
174             JablotronHistoryDataEvent event = events.get(0);
175             updateLastEvent(event);
176         }
177
178         return true;
179     }
180
181     protected @Nullable List<JablotronHistoryDataEvent> sendGetEventHistory() {
182         return sendGetEventHistory(alarmName);
183     }
184
185     private @Nullable List<JablotronHistoryDataEvent> sendGetEventHistory(String alarm) {
186         JablotronBridgeHandler handler = getBridgeHandler();
187         if (handler != null) {
188             return handler.sendGetEventHistory(getThing(), alarm);
189         }
190         return null;
191     }
192
193     protected void updateLastEvent(JablotronHistoryDataEvent event) {
194         updateState(CHANNEL_LAST_EVENT_TIME, new DateTimeType(getZonedDateTime(event.getDate())));
195         updateState(CHANNEL_LAST_EVENT, new StringType(event.getEventText()));
196         updateState(CHANNEL_LAST_EVENT_CLASS, new StringType(event.getIconType()));
197         updateState(CHANNEL_LAST_EVENT_INVOKER, new StringType(event.getInvokerName()));
198
199         // oasis does not have sections
200         if (getThing().getChannel(CHANNEL_LAST_EVENT_SECTION) != null) {
201             updateState(CHANNEL_LAST_EVENT_SECTION, new StringType(event.getSectionName()));
202         }
203     }
204
205     protected void updateEventChannel(String channel) {
206         List<JablotronHistoryDataEvent> events = eventCache.getValue();
207         if (events != null && events.size() > 0) {
208             JablotronHistoryDataEvent event = events.get(0);
209             switch (channel) {
210                 case CHANNEL_LAST_EVENT_TIME:
211                     updateState(CHANNEL_LAST_EVENT_TIME, new DateTimeType(getZonedDateTime(event.getDate())));
212                     break;
213                 case CHANNEL_LAST_EVENT:
214                     updateState(CHANNEL_LAST_EVENT, new StringType(event.getEventText()));
215                     break;
216                 case CHANNEL_LAST_EVENT_CLASS:
217                     updateState(CHANNEL_LAST_EVENT_CLASS, new StringType(event.getIconType()));
218                     break;
219                 case CHANNEL_LAST_EVENT_INVOKER:
220                     updateState(CHANNEL_LAST_EVENT_INVOKER, new StringType(event.getInvokerName()));
221                     break;
222                 case CHANNEL_LAST_EVENT_SECTION:
223                     updateState(CHANNEL_LAST_EVENT_SECTION, new StringType(event.getSectionName()));
224                     break;
225             }
226         }
227     }
228
229     public ZonedDateTime getZonedDateTime(String date) {
230         return ZonedDateTime.parse(date.substring(0, 22) + ":" + date.substring(22, 24),
231                 DateTimeFormatter.ISO_DATE_TIME);
232     }
233
234     protected @Nullable JablotronControlResponse sendUserCode(String section, String key, String status, String code) {
235         JablotronBridgeHandler handler = getBridgeHandler();
236         if (handler != null) {
237             return handler.sendUserCode(getThing(), section, key, status, code);
238         }
239         return null;
240     }
241
242     protected @Nullable JablotronBridgeHandler getBridgeHandler() {
243         Bridge br = getBridge();
244         if (br != null && br.getHandler() != null) {
245             return (JablotronBridgeHandler) br.getHandler();
246         }
247         return null;
248     }
249
250     public void setStatus(ThingStatus status, ThingStatusDetail detail, String message) {
251         updateStatus(status, detail, message);
252     }
253
254     public void triggerAlarm(JablotronDiscoveredService service) {
255         if (!service.getWarningTime().equals(lastWarningTime)) {
256             logger.debug("Service id: {} is triggering an alarm: {}", thing.getUID().getId(), service.getWarning());
257             lastWarningTime = service.getWarningTime();
258             triggerChannel(CHANNEL_ALARM, service.getWarning());
259         }
260     }
261
262     public void setInService(boolean inService) {
263         this.inService = inService;
264     }
265 }