]> git.basschouten.com Git - openhab-addons.git/blob
698efe76ef8fc6cdebf428ae01eedbdaa46e861f
[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.radiothermostat.internal.handler;
14
15 import static org.openhab.binding.radiothermostat.internal.RadioThermostatBindingConstants.*;
16
17 import java.math.BigDecimal;
18 import java.text.NumberFormat;
19 import java.text.ParseException;
20 import java.time.ZonedDateTime;
21 import java.util.ArrayList;
22 import java.util.Calendar;
23 import java.util.Collection;
24 import java.util.Collections;
25 import java.util.List;
26 import java.util.concurrent.ScheduledFuture;
27 import java.util.concurrent.TimeUnit;
28
29 import javax.measure.quantity.Temperature;
30
31 import org.eclipse.jdt.annotation.NonNullByDefault;
32 import org.eclipse.jdt.annotation.Nullable;
33 import org.eclipse.jetty.client.HttpClient;
34 import org.openhab.binding.radiothermostat.internal.RadioThermostatConfiguration;
35 import org.openhab.binding.radiothermostat.internal.RadioThermostatStateDescriptionProvider;
36 import org.openhab.binding.radiothermostat.internal.RadioThermostatThingActions;
37 import org.openhab.binding.radiothermostat.internal.communication.RadioThermostatConnector;
38 import org.openhab.binding.radiothermostat.internal.communication.RadioThermostatEvent;
39 import org.openhab.binding.radiothermostat.internal.communication.RadioThermostatEventListener;
40 import org.openhab.binding.radiothermostat.internal.dto.RadioThermostatDTO;
41 import org.openhab.binding.radiothermostat.internal.dto.RadioThermostatHumidityDTO;
42 import org.openhab.binding.radiothermostat.internal.dto.RadioThermostatRuntimeDTO;
43 import org.openhab.binding.radiothermostat.internal.dto.RadioThermostatTstatDTO;
44 import org.openhab.core.library.types.DateTimeType;
45 import org.openhab.core.library.types.DecimalType;
46 import org.openhab.core.library.types.OnOffType;
47 import org.openhab.core.library.types.PointType;
48 import org.openhab.core.library.types.QuantityType;
49 import org.openhab.core.library.types.StringType;
50 import org.openhab.core.library.unit.ImperialUnits;
51 import org.openhab.core.thing.Channel;
52 import org.openhab.core.thing.ChannelUID;
53 import org.openhab.core.thing.Thing;
54 import org.openhab.core.thing.ThingStatus;
55 import org.openhab.core.thing.ThingStatusDetail;
56 import org.openhab.core.thing.binding.BaseThingHandler;
57 import org.openhab.core.thing.binding.ThingHandlerService;
58 import org.openhab.core.types.Command;
59 import org.openhab.core.types.RefreshType;
60 import org.openhab.core.types.State;
61 import org.openhab.core.types.StateOption;
62 import org.openhab.core.types.UnDefType;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
65
66 import com.google.gson.Gson;
67
68 /**
69  * The {@link RadioThermostatHandler} is responsible for handling commands, which are
70  * sent to one of the channels.
71  *
72  * Based on the 'airquality' binding by Kuba Wolanin
73  *
74  * @author Michael Lobstein - Initial contribution
75  */
76 @NonNullByDefault
77 public class RadioThermostatHandler extends BaseThingHandler implements RadioThermostatEventListener {
78     private static final int DEFAULT_REFRESH_PERIOD = 2;
79     private static final int DEFAULT_LOG_REFRESH_PERIOD = 10;
80
81     private final RadioThermostatStateDescriptionProvider stateDescriptionProvider;
82     private final Logger logger = LoggerFactory.getLogger(RadioThermostatHandler.class);
83
84     private final Gson gson;
85     private final RadioThermostatConnector connector;
86     private final RadioThermostatDTO rthermData = new RadioThermostatDTO();
87
88     private @Nullable ScheduledFuture<?> refreshJob;
89     private @Nullable ScheduledFuture<?> logRefreshJob;
90     private @Nullable ScheduledFuture<?> clockSyncJob;
91
92     private int refreshPeriod = DEFAULT_REFRESH_PERIOD;
93     private int logRefreshPeriod = DEFAULT_LOG_REFRESH_PERIOD;
94     private boolean isCT80 = false;
95     private boolean disableLogs = false;
96     private boolean clockSync = false;
97     private String setpointCmdKeyPrefix = "t_";
98
99     public RadioThermostatHandler(Thing thing, RadioThermostatStateDescriptionProvider stateDescriptionProvider,
100             HttpClient httpClient) {
101         super(thing);
102         this.stateDescriptionProvider = stateDescriptionProvider;
103         gson = new Gson();
104         connector = new RadioThermostatConnector(httpClient);
105     }
106
107     @Override
108     public void initialize() {
109         logger.debug("Initializing RadioThermostat handler.");
110         RadioThermostatConfiguration config = getConfigAs(RadioThermostatConfiguration.class);
111
112         final String hostName = config.hostName;
113         final Integer refresh = config.refresh;
114         final Integer logRefresh = config.logRefresh;
115         this.isCT80 = config.isCT80;
116         this.disableLogs = config.disableLogs;
117         this.clockSync = config.clockSync;
118
119         if (hostName == null || "".equals(hostName)) {
120             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
121                     "Thermostat Host Name must be specified");
122             return;
123         }
124
125         if (refresh != null) {
126             this.refreshPeriod = refresh;
127         }
128
129         if (logRefresh != null) {
130             this.logRefreshPeriod = logRefresh;
131         }
132
133         connector.setThermostatHostName(hostName);
134         connector.addEventListener(this);
135
136         // The setpoint mode is controlled by the name of setpoint attribute sent to the thermostat.
137         // Temporary mode uses setpoint names prefixed with "t_" while absolute mode uses "a_"
138         if (config.setpointMode.equals("absolute")) {
139             this.setpointCmdKeyPrefix = "a_";
140         }
141
142         // populate fan mode options based on thermostat model
143         stateDescriptionProvider.setStateOptions(new ChannelUID(getThing().getUID(), FAN_MODE), getFanModeOptions());
144
145         // if we are not a CT-80, remove the humidity & program mode channel
146         if (!this.isCT80) {
147             List<Channel> channels = new ArrayList<>(this.getThing().getChannels());
148             channels.removeIf(c -> (c.getUID().getId().equals(HUMIDITY)));
149             channels.removeIf(c -> (c.getUID().getId().equals(PROGRAM_MODE)));
150             updateThing(editThing().withChannels(channels).build());
151         }
152
153         updateStatus(ThingStatus.UNKNOWN);
154
155         startAutomaticRefresh();
156
157         if (!this.disableLogs || this.isCT80) {
158             startAutomaticLogRefresh();
159         }
160
161         if (this.clockSync) {
162             scheduleClockSyncJob();
163         }
164     }
165
166     @Override
167     public Collection<Class<? extends ThingHandlerService>> getServices() {
168         return Collections.singletonList(RadioThermostatThingActions.class);
169     }
170
171     /**
172      * Start the job to periodically update data from the thermostat
173      */
174     private void startAutomaticRefresh() {
175         ScheduledFuture<?> refreshJob = this.refreshJob;
176         if (refreshJob == null || refreshJob.isCancelled()) {
177             Runnable runnable = () -> {
178                 // send an async call to the thermostat to get the 'tstat' data
179                 connector.getAsyncThermostatData(DEFAULT_RESOURCE);
180             };
181
182             refreshJob = null;
183             this.refreshJob = scheduler.scheduleWithFixedDelay(runnable, 0, refreshPeriod, TimeUnit.MINUTES);
184         }
185     }
186
187     /**
188      * Schedule the clock sync job
189      */
190     private void scheduleClockSyncJob() {
191         ScheduledFuture<?> clockSyncJob = this.clockSyncJob;
192         if (clockSyncJob == null || clockSyncJob.isCancelled()) {
193             clockSyncJob = null;
194             this.clockSyncJob = scheduler.scheduleWithFixedDelay(this::syncThermostatClock, 1, 60, TimeUnit.MINUTES);
195         }
196     }
197
198     /**
199      * Sync the thermostat's clock with the host system clock
200      */
201     private void syncThermostatClock() {
202         Calendar c = Calendar.getInstance();
203
204         // The thermostat week starts as Monday = 0, subtract 2 since in standard DoW Monday = 2
205         int thermDayOfWeek = c.get(Calendar.DAY_OF_WEEK) - 2;
206         // Sunday will be -1, so add 7 to make it 6
207         if (thermDayOfWeek < 0) {
208             thermDayOfWeek += 7;
209         }
210
211         connector.sendCommand(null, null,
212                 String.format(JSON_TIME, thermDayOfWeek, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE)),
213                 TIME_RESOURCE);
214     }
215
216     /**
217      * Start the job to periodically update humidity and runtime date from the thermostat
218      */
219     private void startAutomaticLogRefresh() {
220         ScheduledFuture<?> logRefreshJob = this.logRefreshJob;
221         if (logRefreshJob == null || logRefreshJob.isCancelled()) {
222             Runnable runnable = () -> {
223                 // Request humidity data from the thermostat if we are a CT80
224                 if (this.isCT80) {
225                     // send an async call to the thermostat to get the humidity data
226                     connector.getAsyncThermostatData(HUMIDITY_RESOURCE);
227                 }
228
229                 if (!this.disableLogs) {
230                     // send an async call to the thermostat to get the runtime data
231                     connector.getAsyncThermostatData(RUNTIME_RESOURCE);
232                 }
233             };
234
235             logRefreshJob = null;
236             this.logRefreshJob = scheduler.scheduleWithFixedDelay(runnable, 1, logRefreshPeriod, TimeUnit.MINUTES);
237         }
238     }
239
240     @Override
241     public void dispose() {
242         logger.debug("Disposing the RadioThermostat handler.");
243         connector.removeEventListener(this);
244
245         ScheduledFuture<?> refreshJob = this.refreshJob;
246         if (refreshJob != null) {
247             refreshJob.cancel(true);
248             this.refreshJob = null;
249         }
250
251         ScheduledFuture<?> logRefreshJob = this.logRefreshJob;
252         if (logRefreshJob != null) {
253             logRefreshJob.cancel(true);
254             this.logRefreshJob = null;
255         }
256
257         ScheduledFuture<?> clockSyncJob = this.clockSyncJob;
258         if (clockSyncJob != null) {
259             clockSyncJob.cancel(true);
260             this.clockSyncJob = null;
261         }
262     }
263
264     public void handleRawCommand(@Nullable String rawCommand) {
265         connector.sendCommand(null, null, rawCommand, DEFAULT_RESOURCE);
266     }
267
268     @Override
269     public void handleCommand(ChannelUID channelUID, Command command) {
270         if (command instanceof RefreshType) {
271             updateChannel(channelUID.getId(), rthermData);
272         } else {
273             Integer cmdInt = -1;
274             String cmdStr = command.toString();
275             try {
276                 // parse out an Integer from the string
277                 // ie '70.5 F' becomes 70, also handles negative numbers
278                 cmdInt = NumberFormat.getInstance().parse(cmdStr).intValue();
279             } catch (ParseException e) {
280                 logger.debug("Command: {} -> Not an integer", cmdStr);
281             }
282
283             switch (channelUID.getId()) {
284                 case MODE:
285                     // only do if commanded mode is different than current mode
286                     if (!cmdInt.equals(rthermData.getThermostatData().getMode())) {
287                         connector.sendCommand("tmode", cmdStr, DEFAULT_RESOURCE);
288
289                         // set the new operating mode, reset everything else,
290                         // because refreshing the tstat data below is really slow.
291                         rthermData.getThermostatData().setMode(cmdInt);
292                         rthermData.getThermostatData().setHeatTarget(0);
293                         rthermData.getThermostatData().setCoolTarget(0);
294                         updateChannel(SET_POINT, rthermData);
295                         rthermData.getThermostatData().setHold(0);
296                         updateChannel(HOLD, rthermData);
297                         rthermData.getThermostatData().setProgramMode(-1);
298                         updateChannel(PROGRAM_MODE, rthermData);
299
300                         // now just trigger a refresh of the thermostat to get the new active setpoint
301                         // this takes a while for the JSON request to complete (async).
302                         connector.getAsyncThermostatData(DEFAULT_RESOURCE);
303                     }
304                     break;
305                 case FAN_MODE:
306                     rthermData.getThermostatData().setFanMode(cmdInt);
307                     connector.sendCommand("fmode", cmdStr, DEFAULT_RESOURCE);
308                     break;
309                 case PROGRAM_MODE:
310                     rthermData.getThermostatData().setProgramMode(cmdInt);
311                     connector.sendCommand("program_mode", cmdStr, DEFAULT_RESOURCE);
312                     break;
313                 case HOLD:
314                     if (command instanceof OnOffType && command == OnOffType.ON) {
315                         rthermData.getThermostatData().setHold(1);
316                         connector.sendCommand("hold", "1", DEFAULT_RESOURCE);
317                     } else if (command instanceof OnOffType && command == OnOffType.OFF) {
318                         rthermData.getThermostatData().setHold(0);
319                         connector.sendCommand("hold", "0", DEFAULT_RESOURCE);
320                     }
321                     break;
322                 case SET_POINT:
323                     String cmdKey = null;
324                     if (rthermData.getThermostatData().getMode() == 1) {
325                         cmdKey = this.setpointCmdKeyPrefix + "heat";
326                         rthermData.getThermostatData().setHeatTarget(cmdInt);
327                     } else if (rthermData.getThermostatData().getMode() == 2) {
328                         cmdKey = this.setpointCmdKeyPrefix + "cool";
329                         rthermData.getThermostatData().setCoolTarget(cmdInt);
330                     } else {
331                         // don't do anything if we are not in heat or cool mode
332                         break;
333                     }
334                     connector.sendCommand(cmdKey, cmdInt.toString(), DEFAULT_RESOURCE);
335                     break;
336                 case REMOTE_TEMP:
337                     if (cmdInt != -1) {
338                         QuantityType<?> remoteTemp = ((QuantityType<Temperature>) command)
339                                 .toUnit(ImperialUnits.FAHRENHEIT);
340                         connector.sendCommand("rem_temp", String.valueOf(remoteTemp.intValue()), REMOTE_TEMP_RESOURCE);
341                     } else {
342                         connector.sendCommand("rem_mode", "0", REMOTE_TEMP_RESOURCE);
343                     }
344                     break;
345                 default:
346                     logger.warn("Unsupported command: {}", command.toString());
347             }
348         }
349     }
350
351     /**
352      * Handle a RadioThermostat event received from the listeners
353      *
354      * @param event the event received from the listeners
355      */
356     @Override
357     public void onNewMessageEvent(RadioThermostatEvent event) {
358         logger.debug("onNewMessageEvent: key {} = {}", event.getKey(), event.getValue());
359
360         String evtKey = event.getKey();
361         String evtVal = event.getValue();
362
363         if (KEY_ERROR.equals(evtKey)) {
364             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR,
365                     "Error retrieving data from Thermostat ");
366         } else {
367             updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE);
368
369             // Map the JSON response to the correct object and update appropriate channels
370             switch (evtKey) {
371                 case DEFAULT_RESOURCE:
372                     rthermData.setThermostatData(gson.fromJson(evtVal, RadioThermostatTstatDTO.class));
373                     updateAllChannels();
374                     break;
375                 case HUMIDITY_RESOURCE:
376                     RadioThermostatHumidityDTO dto = gson.fromJson(evtVal, RadioThermostatHumidityDTO.class);
377                     if (dto != null) {
378                         rthermData.setHumidity(dto.getHumidity());
379                     }
380                     updateChannel(HUMIDITY, rthermData);
381                     break;
382                 case RUNTIME_RESOURCE:
383                     rthermData.setRuntime(gson.fromJson(evtVal, RadioThermostatRuntimeDTO.class));
384                     updateChannel(TODAY_HEAT_RUNTIME, rthermData);
385                     updateChannel(TODAY_COOL_RUNTIME, rthermData);
386                     updateChannel(YESTERDAY_HEAT_RUNTIME, rthermData);
387                     updateChannel(YESTERDAY_COOL_RUNTIME, rthermData);
388                     break;
389             }
390         }
391     }
392
393     /**
394      * Update the channel from the last Thermostat data retrieved
395      *
396      * @param channelId the id identifying the channel to be updated
397      */
398     private void updateChannel(String channelId, RadioThermostatDTO rthermData) {
399         if (isLinked(channelId)) {
400             Object value;
401             try {
402                 value = getValue(channelId, rthermData);
403             } catch (Exception e) {
404                 logger.debug("Error setting {} value", channelId.toUpperCase());
405                 return;
406             }
407
408             State state = null;
409             if (value == null) {
410                 state = UnDefType.UNDEF;
411             } else if (value instanceof PointType) {
412                 state = (PointType) value;
413             } else if (value instanceof ZonedDateTime) {
414                 state = new DateTimeType((ZonedDateTime) value);
415             } else if (value instanceof QuantityType<?>) {
416                 state = (QuantityType<?>) value;
417             } else if (value instanceof BigDecimal) {
418                 state = new DecimalType((BigDecimal) value);
419             } else if (value instanceof Integer) {
420                 state = new DecimalType(BigDecimal.valueOf(((Integer) value).longValue()));
421             } else if (value instanceof String) {
422                 state = new StringType(value.toString());
423             } else if (value instanceof OnOffType) {
424                 state = (OnOffType) value;
425             } else {
426                 logger.warn("Update channel {}: Unsupported value type {}", channelId,
427                         value.getClass().getSimpleName());
428             }
429             logger.debug("Update channel {} with state {} ({})", channelId, (state == null) ? "null" : state.toString(),
430                     (value == null) ? "null" : value.getClass().getSimpleName());
431
432             // Update the channel
433             if (state != null) {
434                 updateState(channelId, state);
435             }
436         }
437     }
438
439     /**
440      * Update a given channelId from the thermostat data
441      *
442      * @param the channel id to be updated
443      * @param data the RadioThermostat dto
444      * @return the value to be set in the state
445      */
446     public static @Nullable Object getValue(String channelId, RadioThermostatDTO data) {
447         switch (channelId) {
448             case TEMPERATURE:
449                 if (data.getThermostatData().getTemperature() != null) {
450                     return new QuantityType<Temperature>(data.getThermostatData().getTemperature(),
451                             API_TEMPERATURE_UNIT);
452                 } else {
453                     return null;
454                 }
455             case HUMIDITY:
456                 if (data.getHumidity() != null) {
457                     return new QuantityType<>(data.getHumidity(), API_HUMIDITY_UNIT);
458                 } else {
459                     return null;
460                 }
461             case MODE:
462                 return data.getThermostatData().getMode();
463             case FAN_MODE:
464                 return data.getThermostatData().getFanMode();
465             case PROGRAM_MODE:
466                 return data.getThermostatData().getProgramMode();
467             case SET_POINT:
468                 if (data.getThermostatData().getSetpoint() != 0) {
469                     return new QuantityType<Temperature>(data.getThermostatData().getSetpoint(), API_TEMPERATURE_UNIT);
470                 } else {
471                     return null;
472                 }
473             case OVERRIDE:
474                 return data.getThermostatData().getOverride();
475             case HOLD:
476                 return OnOffType.from(data.getThermostatData().getHold() == 1);
477             case STATUS:
478                 return data.getThermostatData().getStatus();
479             case FAN_STATUS:
480                 return data.getThermostatData().getFanStatus();
481             case DAY:
482                 return data.getThermostatData().getTime().getDayOfWeek();
483             case HOUR:
484                 return data.getThermostatData().getTime().getHour();
485             case MINUTE:
486                 return data.getThermostatData().getTime().getMinute();
487             case DATE_STAMP:
488                 return data.getThermostatData().getTime().getThemostatDateTime();
489             case TODAY_HEAT_RUNTIME:
490                 return new QuantityType<>(data.getRuntime().getToday().getHeatTime().getRuntime(), API_MINUTES_UNIT);
491             case TODAY_COOL_RUNTIME:
492                 return new QuantityType<>(data.getRuntime().getToday().getCoolTime().getRuntime(), API_MINUTES_UNIT);
493             case YESTERDAY_HEAT_RUNTIME:
494                 return new QuantityType<>(data.getRuntime().getYesterday().getHeatTime().getRuntime(),
495                         API_MINUTES_UNIT);
496             case YESTERDAY_COOL_RUNTIME:
497                 return new QuantityType<>(data.getRuntime().getYesterday().getCoolTime().getRuntime(),
498                         API_MINUTES_UNIT);
499         }
500         return null;
501     }
502
503     /**
504      * Updates all channels from rthermData
505      */
506     private void updateAllChannels() {
507         // Update all channels from rthermData
508         for (Channel channel : getThing().getChannels()) {
509             updateChannel(channel.getUID().getId(), rthermData);
510         }
511     }
512
513     /**
514      * Build a list of fan modes based on what model thermostat is used
515      *
516      * @return list of state options for thermostat fan modes
517      */
518     private List<StateOption> getFanModeOptions() {
519         List<StateOption> fanModeOptions = new ArrayList<>();
520
521         fanModeOptions.add(new StateOption("0", "Auto"));
522         if (this.isCT80) {
523             fanModeOptions.add(new StateOption("1", "Auto/Circulate"));
524         }
525         fanModeOptions.add(new StateOption("2", "On"));
526
527         return fanModeOptions;
528     }
529 }