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.radiothermostat.internal.handler;
15 import static org.openhab.binding.radiothermostat.internal.RadioThermostatBindingConstants.*;
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;
29 import javax.measure.quantity.Temperature;
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;
66 import com.google.gson.Gson;
69 * The {@link RadioThermostatHandler} is responsible for handling commands, which are
70 * sent to one of the channels.
72 * Based on the 'airquality' binding by Kuba Wolanin
74 * @author Michael Lobstein - Initial contribution
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;
81 private final RadioThermostatStateDescriptionProvider stateDescriptionProvider;
82 private final Logger logger = LoggerFactory.getLogger(RadioThermostatHandler.class);
84 private final Gson gson;
85 private final RadioThermostatConnector connector;
86 private final RadioThermostatDTO rthermData = new RadioThermostatDTO();
88 private @Nullable ScheduledFuture<?> refreshJob;
89 private @Nullable ScheduledFuture<?> logRefreshJob;
90 private @Nullable ScheduledFuture<?> clockSyncJob;
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_";
99 public RadioThermostatHandler(Thing thing, RadioThermostatStateDescriptionProvider stateDescriptionProvider,
100 HttpClient httpClient) {
102 this.stateDescriptionProvider = stateDescriptionProvider;
104 connector = new RadioThermostatConnector(httpClient);
108 public void initialize() {
109 logger.debug("Initializing RadioThermostat handler.");
110 RadioThermostatConfiguration config = getConfigAs(RadioThermostatConfiguration.class);
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;
119 if (hostName == null || "".equals(hostName)) {
120 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
121 "Thermostat Host Name must be specified");
125 if (refresh != null) {
126 this.refreshPeriod = refresh;
129 if (logRefresh != null) {
130 this.logRefreshPeriod = logRefresh;
133 connector.setThermostatHostName(hostName);
134 connector.addEventListener(this);
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_";
142 // populate fan mode options based on thermostat model
143 stateDescriptionProvider.setStateOptions(new ChannelUID(getThing().getUID(), FAN_MODE), getFanModeOptions());
145 // if we are not a CT-80, remove the humidity & program mode channel
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());
153 updateStatus(ThingStatus.UNKNOWN);
155 startAutomaticRefresh();
157 if (!this.disableLogs || this.isCT80) {
158 startAutomaticLogRefresh();
161 if (this.clockSync) {
162 scheduleClockSyncJob();
167 public Collection<Class<? extends ThingHandlerService>> getServices() {
168 return Collections.singletonList(RadioThermostatThingActions.class);
172 * Start the job to periodically update data from the thermostat
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);
183 this.refreshJob = scheduler.scheduleWithFixedDelay(runnable, 0, refreshPeriod, TimeUnit.MINUTES);
188 * Schedule the clock sync job
190 private void scheduleClockSyncJob() {
191 ScheduledFuture<?> clockSyncJob = this.clockSyncJob;
192 if (clockSyncJob == null || clockSyncJob.isCancelled()) {
194 this.clockSyncJob = scheduler.scheduleWithFixedDelay(this::syncThermostatClock, 1, 60, TimeUnit.MINUTES);
199 * Sync the thermostat's clock with the host system clock
201 private void syncThermostatClock() {
202 Calendar c = Calendar.getInstance();
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) {
211 connector.sendCommand(null, null,
212 String.format(JSON_TIME, thermDayOfWeek, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE)),
217 * Start the job to periodically update humidity and runtime date from the thermostat
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
225 // send an async call to the thermostat to get the humidity data
226 connector.getAsyncThermostatData(HUMIDITY_RESOURCE);
229 if (!this.disableLogs) {
230 // send an async call to the thermostat to get the runtime data
231 connector.getAsyncThermostatData(RUNTIME_RESOURCE);
235 logRefreshJob = null;
236 this.logRefreshJob = scheduler.scheduleWithFixedDelay(runnable, 1, logRefreshPeriod, TimeUnit.MINUTES);
241 public void dispose() {
242 logger.debug("Disposing the RadioThermostat handler.");
243 connector.removeEventListener(this);
245 ScheduledFuture<?> refreshJob = this.refreshJob;
246 if (refreshJob != null) {
247 refreshJob.cancel(true);
248 this.refreshJob = null;
251 ScheduledFuture<?> logRefreshJob = this.logRefreshJob;
252 if (logRefreshJob != null) {
253 logRefreshJob.cancel(true);
254 this.logRefreshJob = null;
257 ScheduledFuture<?> clockSyncJob = this.clockSyncJob;
258 if (clockSyncJob != null) {
259 clockSyncJob.cancel(true);
260 this.clockSyncJob = null;
264 public void handleRawCommand(@Nullable String rawCommand) {
265 connector.sendCommand(null, null, rawCommand, DEFAULT_RESOURCE);
269 public void handleCommand(ChannelUID channelUID, Command command) {
270 if (command instanceof RefreshType) {
271 updateChannel(channelUID.getId(), rthermData);
274 String cmdStr = command.toString();
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);
283 switch (channelUID.getId()) {
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);
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);
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);
306 rthermData.getThermostatData().setFanMode(cmdInt);
307 connector.sendCommand("fmode", cmdStr, DEFAULT_RESOURCE);
310 rthermData.getThermostatData().setProgramMode(cmdInt);
311 connector.sendCommand("program_mode", cmdStr, DEFAULT_RESOURCE);
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);
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);
331 // don't do anything if we are not in heat or cool mode
334 connector.sendCommand(cmdKey, cmdInt.toString(), DEFAULT_RESOURCE);
338 QuantityType<?> remoteTemp = ((QuantityType<Temperature>) command)
339 .toUnit(ImperialUnits.FAHRENHEIT);
340 connector.sendCommand("rem_temp", String.valueOf(remoteTemp.intValue()), REMOTE_TEMP_RESOURCE);
342 connector.sendCommand("rem_mode", "0", REMOTE_TEMP_RESOURCE);
346 logger.warn("Unsupported command: {}", command.toString());
352 * Handle a RadioThermostat event received from the listeners
354 * @param event the event received from the listeners
357 public void onNewMessageEvent(RadioThermostatEvent event) {
358 logger.debug("onNewMessageEvent: key {} = {}", event.getKey(), event.getValue());
360 String evtKey = event.getKey();
361 String evtVal = event.getValue();
363 if (KEY_ERROR.equals(evtKey)) {
364 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR,
365 "Error retrieving data from Thermostat ");
367 updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE);
369 // Map the JSON response to the correct object and update appropriate channels
371 case DEFAULT_RESOURCE:
372 rthermData.setThermostatData(gson.fromJson(evtVal, RadioThermostatTstatDTO.class));
375 case HUMIDITY_RESOURCE:
376 RadioThermostatHumidityDTO dto = gson.fromJson(evtVal, RadioThermostatHumidityDTO.class);
378 rthermData.setHumidity(dto.getHumidity());
380 updateChannel(HUMIDITY, rthermData);
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);
394 * Update the channel from the last Thermostat data retrieved
396 * @param channelId the id identifying the channel to be updated
398 private void updateChannel(String channelId, RadioThermostatDTO rthermData) {
399 if (isLinked(channelId)) {
402 value = getValue(channelId, rthermData);
403 } catch (Exception e) {
404 logger.debug("Error setting {} value", channelId.toUpperCase());
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;
426 logger.warn("Update channel {}: Unsupported value type {}", channelId,
427 value.getClass().getSimpleName());
429 logger.debug("Update channel {} with state {} ({})", channelId, (state == null) ? "null" : state.toString(),
430 (value == null) ? "null" : value.getClass().getSimpleName());
432 // Update the channel
434 updateState(channelId, state);
440 * Update a given channelId from the thermostat data
442 * @param the channel id to be updated
443 * @param data the RadioThermostat dto
444 * @return the value to be set in the state
446 public static @Nullable Object getValue(String channelId, RadioThermostatDTO data) {
449 if (data.getThermostatData().getTemperature() != null) {
450 return new QuantityType<Temperature>(data.getThermostatData().getTemperature(),
451 API_TEMPERATURE_UNIT);
456 if (data.getHumidity() != null) {
457 return new QuantityType<>(data.getHumidity(), API_HUMIDITY_UNIT);
462 return data.getThermostatData().getMode();
464 return data.getThermostatData().getFanMode();
466 return data.getThermostatData().getProgramMode();
468 if (data.getThermostatData().getSetpoint() != 0) {
469 return new QuantityType<Temperature>(data.getThermostatData().getSetpoint(), API_TEMPERATURE_UNIT);
474 return data.getThermostatData().getOverride();
476 return OnOffType.from(data.getThermostatData().getHold() == 1);
478 return data.getThermostatData().getStatus();
480 return data.getThermostatData().getFanStatus();
482 return data.getThermostatData().getTime().getDayOfWeek();
484 return data.getThermostatData().getTime().getHour();
486 return data.getThermostatData().getTime().getMinute();
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(),
496 case YESTERDAY_COOL_RUNTIME:
497 return new QuantityType<>(data.getRuntime().getYesterday().getCoolTime().getRuntime(),
504 * Updates all channels from rthermData
506 private void updateAllChannels() {
507 // Update all channels from rthermData
508 for (Channel channel : getThing().getChannels()) {
509 updateChannel(channel.getUID().getId(), rthermData);
514 * Build a list of fan modes based on what model thermostat is used
516 * @return list of state options for thermostat fan modes
518 private List<StateOption> getFanModeOptions() {
519 List<StateOption> fanModeOptions = new ArrayList<>();
521 fanModeOptions.add(new StateOption("0", "Auto"));
523 fanModeOptions.add(new StateOption("1", "Auto/Circulate"));
525 fanModeOptions.add(new StateOption("2", "On"));
527 return fanModeOptions;