]> git.basschouten.com Git - openhab-addons.git/blob
97e7890f53bb4806d4bfcdaf31e8f712ab2903f3
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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.luftdateninfo.internal.handler;
14
15 import java.time.LocalDateTime;
16 import java.util.concurrent.ScheduledFuture;
17 import java.util.concurrent.TimeUnit;
18
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.eclipse.jdt.annotation.Nullable;
21 import org.openhab.binding.luftdateninfo.internal.LuftdatenInfoConfiguration;
22 import org.openhab.binding.luftdateninfo.internal.utils.DateTimeUtils;
23 import org.openhab.core.thing.ChannelUID;
24 import org.openhab.core.thing.Thing;
25 import org.openhab.core.thing.ThingStatus;
26 import org.openhab.core.thing.ThingStatusDetail;
27 import org.openhab.core.thing.binding.BaseThingHandler;
28 import org.openhab.core.types.Command;
29 import org.openhab.core.types.RefreshType;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32
33 /**
34  * The {@link PMHandler} is responsible for handling commands, which are
35  * sent to one of the channels.
36  *
37  * @author Bernd Weymann - Initial contribution
38  */
39 @NonNullByDefault
40 public abstract class BaseSensorHandler extends BaseThingHandler {
41     private static final LuftdatenInfoConfiguration DEFAULT_CONFIG = new LuftdatenInfoConfiguration();
42     private static final String EMPTY = "";
43
44     protected static final int REFRESH_INTERVAL_MIN = 5;
45     protected final Logger logger = LoggerFactory.getLogger(BaseSensorHandler.class);
46     protected LuftdatenInfoConfiguration config = DEFAULT_CONFIG;
47     protected ConfigStatus configStatus = ConfigStatus.UNKNOWN;
48     protected ThingStatus myThingStatus = ThingStatus.UNKNOWN;
49     protected UpdateStatus lastUpdateStatus = UpdateStatus.UNKNOWN;
50     protected @Nullable ScheduledFuture<?> refreshJob;
51
52     public enum ConfigStatus {
53         OK,
54         IS_NULL,
55         SENSOR_IS_NULL,
56         SENSOR_ID_NEGATIVE,
57         UNKNOWN
58     };
59
60     public enum UpdateStatus {
61         OK,
62         CONNECTION_ERROR,
63         CONNECTION_EXCEPTION,
64         VALUE_ERROR,
65         VALUE_EMPTY,
66         UNKNOWN
67     }
68
69     protected LifecycleStatus lifecycleStatus = LifecycleStatus.UNKNOWN;
70
71     public enum LifecycleStatus {
72         UNKNOWN,
73         RUNNING,
74         INITIALIZING,
75         DISPOSED
76     }
77
78     public BaseSensorHandler(Thing thing) {
79         super(thing);
80     }
81
82     @Override
83     public void handleCommand(ChannelUID channelUID, Command command) {
84         if (command instanceof RefreshType) {
85             updateFromCache();
86         }
87     }
88
89     @Override
90     public void initialize() {
91         lifecycleStatus = LifecycleStatus.INITIALIZING;
92         scheduler.execute(this::startUp);
93     }
94
95     private void startUp() {
96         config = getConfigAs(LuftdatenInfoConfiguration.class);
97         configStatus = checkConfig(config);
98         if (configStatus == ConfigStatus.OK) {
99             // start getting values
100             dataUpdate();
101         } else {
102             // config error, no further actions triggered - Thing Status visible in UI
103             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
104                     "Configuration not valid. Sensor ID as a number is mandatory!");
105         }
106         lifecycleStatus = LifecycleStatus.RUNNING;
107     }
108
109     private void startSchedule() {
110         ScheduledFuture<?> localRefreshJob = refreshJob;
111         if (localRefreshJob != null) {
112             if (localRefreshJob.isCancelled()) {
113                 refreshJob = scheduler.scheduleWithFixedDelay(this::dataUpdate, 5, REFRESH_INTERVAL_MIN,
114                         TimeUnit.MINUTES);
115             } // else - scheduler is already running!
116         } else {
117             refreshJob = scheduler.scheduleWithFixedDelay(this::dataUpdate, 5, REFRESH_INTERVAL_MIN, TimeUnit.MINUTES);
118         }
119     }
120
121     @Override
122     public void dispose() {
123         ScheduledFuture<?> localRefreshJob = refreshJob;
124         if (localRefreshJob != null) {
125             localRefreshJob.cancel(true);
126         }
127         lifecycleStatus = LifecycleStatus.DISPOSED;
128     }
129
130     /**
131      * Checks if config is valid - a) not null and b) sensorid is a number
132      *
133      * @param c
134      * @return
135      */
136     private ConfigStatus checkConfig(@Nullable LuftdatenInfoConfiguration c) {
137         if (c != null) {
138             if (c.sensorid >= 0) {
139                 return ConfigStatus.OK;
140             } else {
141                 return ConfigStatus.SENSOR_ID_NEGATIVE;
142             }
143         } else {
144             return ConfigStatus.IS_NULL;
145         }
146     }
147
148     public LifecycleStatus getLifecycleStatus() {
149         return lifecycleStatus;
150     }
151
152     protected void dataUpdate() {
153         HTTPHandler.getHandler().request(config.sensorid, this);
154     }
155
156     public void onResponse(String data) {
157         lastUpdateStatus = updateChannels(data);
158         statusUpdate(lastUpdateStatus, EMPTY);
159     }
160
161     public void onError(String errorReason) {
162         statusUpdate(UpdateStatus.CONNECTION_EXCEPTION,
163                 errorReason + " / " + LocalDateTime.now().format(DateTimeUtils.DTF));
164     }
165
166     protected void statusUpdate(UpdateStatus updateStatus, String details) {
167         if (updateStatus == UpdateStatus.OK) {
168             updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE, null);
169             startSchedule();
170         } else {
171             switch (updateStatus) {
172                 case CONNECTION_ERROR:
173                     // start job even first update delivers no data - recovery is possible
174                     startSchedule();
175                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
176                             "Update failed due to Connection error. Trying to recover in next refresh");
177                     break;
178                 case CONNECTION_EXCEPTION:
179                     // start job even first update delivers a Connection Exception - recovery is possible
180                     startSchedule();
181                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, details);
182                     break;
183                 case VALUE_EMPTY:
184                     // start job even if first update delivers no values - recovery possible
185                     startSchedule();
186                     updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE,
187                             "No values delivered by Sensor. Trying to recover in next refresh");
188                     break;
189                 case VALUE_ERROR:
190                     // final status - values from sensor are wrong and manual check is needed
191                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
192                             "Sensor values doesn't match - please check if Sensor ID is delivering the correct Thing channel values");
193                     break;
194                 default:
195                     // final status - Configuration is wrong
196                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
197                             "Error during update - please check your config data");
198                     break;
199             }
200         }
201     }
202
203     @Override
204     protected void updateStatus(ThingStatus status, ThingStatusDetail statusDetail, @Nullable String description) {
205         myThingStatus = status;
206         super.updateStatus(status, statusDetail, description);
207     }
208
209     protected abstract UpdateStatus updateChannels(@Nullable String json);
210
211     protected abstract void updateFromCache();
212 }