2 * Copyright (c) 2010-2023 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.text.NumberFormat;
18 import java.text.ParseException;
19 import java.time.ZonedDateTime;
20 import java.util.ArrayList;
21 import java.util.Calendar;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.List;
25 import java.util.concurrent.ScheduledFuture;
26 import java.util.concurrent.TimeUnit;
28 import javax.measure.quantity.Temperature;
30 import org.eclipse.jdt.annotation.NonNullByDefault;
31 import org.eclipse.jdt.annotation.Nullable;
32 import org.eclipse.jetty.client.HttpClient;
33 import org.openhab.binding.radiothermostat.internal.RadioThermostatConfiguration;
34 import org.openhab.binding.radiothermostat.internal.RadioThermostatStateDescriptionProvider;
35 import org.openhab.binding.radiothermostat.internal.RadioThermostatThingActions;
36 import org.openhab.binding.radiothermostat.internal.communication.RadioThermostatConnector;
37 import org.openhab.binding.radiothermostat.internal.communication.RadioThermostatEvent;
38 import org.openhab.binding.radiothermostat.internal.communication.RadioThermostatEventListener;
39 import org.openhab.binding.radiothermostat.internal.dto.RadioThermostatDTO;
40 import org.openhab.binding.radiothermostat.internal.dto.RadioThermostatHumidityDTO;
41 import org.openhab.binding.radiothermostat.internal.dto.RadioThermostatRuntimeDTO;
42 import org.openhab.binding.radiothermostat.internal.dto.RadioThermostatTstatDTO;
43 import org.openhab.binding.radiothermostat.internal.util.RadioThermostatScheduleJson;
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_";
98 private String heatProgramJson = BLANK;
99 private String coolProgramJson = BLANK;
101 public RadioThermostatHandler(Thing thing, RadioThermostatStateDescriptionProvider stateDescriptionProvider,
102 HttpClient httpClient) {
104 this.stateDescriptionProvider = stateDescriptionProvider;
106 connector = new RadioThermostatConnector(httpClient);
110 public void initialize() {
111 logger.debug("Initializing RadioThermostat handler.");
112 RadioThermostatConfiguration config = getConfigAs(RadioThermostatConfiguration.class);
114 final String hostName = config.hostName;
115 final Integer refresh = config.refresh;
116 final Integer logRefresh = config.logRefresh;
117 this.isCT80 = config.isCT80;
118 this.disableLogs = config.disableLogs;
119 this.clockSync = config.clockSync;
121 if (hostName == null || hostName.isBlank()) {
122 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
123 "@text/offline.configuration-error-hostname");
127 if (refresh != null) {
128 this.refreshPeriod = refresh;
131 if (logRefresh != null) {
132 this.logRefreshPeriod = logRefresh;
135 connector.setThermostatHostName(hostName);
136 connector.addEventListener(this);
138 // The setpoint mode is controlled by the name of setpoint attribute sent to the thermostat.
139 // Temporary mode uses setpoint names prefixed with "t_" while absolute mode uses "a_"
140 if (config.setpointMode.equals("absolute")) {
141 this.setpointCmdKeyPrefix = "a_";
144 // populate fan mode options based on thermostat model
145 stateDescriptionProvider.setStateOptions(new ChannelUID(getThing().getUID(), FAN_MODE), getFanModeOptions());
147 // if we are not a CT-80, remove the humidity & program mode channel
149 List<Channel> channels = new ArrayList<>(this.getThing().getChannels());
150 channels.removeIf(c -> (c.getUID().getId().equals(HUMIDITY)));
151 channels.removeIf(c -> (c.getUID().getId().equals(PROGRAM_MODE)));
152 updateThing(editThing().withChannels(channels).build());
155 final RadioThermostatScheduleJson thermostatSchedule = new RadioThermostatScheduleJson(config);
158 heatProgramJson = thermostatSchedule.getHeatProgramJson();
159 } catch (IllegalStateException e) {
160 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
161 "@text/offline.configuration-error-heating-program");
166 coolProgramJson = thermostatSchedule.getCoolProgramJson();
167 } catch (IllegalStateException e) {
168 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
169 "@text/offline.configuration-error-cooling-program");
173 updateStatus(ThingStatus.UNKNOWN);
175 startAutomaticRefresh();
177 if (!this.disableLogs || this.isCT80) {
178 startAutomaticLogRefresh();
181 if (this.clockSync) {
182 scheduleClockSyncJob();
187 public Collection<Class<? extends ThingHandlerService>> getServices() {
188 return Collections.singletonList(RadioThermostatThingActions.class);
192 * Start the job to periodically update data from the thermostat
194 private void startAutomaticRefresh() {
195 ScheduledFuture<?> refreshJob = this.refreshJob;
196 if (refreshJob == null || refreshJob.isCancelled()) {
197 Runnable runnable = () -> {
198 // populate the heat and cool programs on the thermostat from the user configuration,
199 // the commands will be sent each time the refresh job runs until a success response is seen
200 if (!heatProgramJson.isEmpty()) {
201 final String response = connector.sendCommand(null, null, heatProgramJson, HEAT_PROGRAM_RESOURCE);
202 if (response.contains("success")) {
203 heatProgramJson = BLANK;
207 if (!coolProgramJson.isEmpty()) {
208 final String response = connector.sendCommand(null, null, coolProgramJson, COOL_PROGRAM_RESOURCE);
209 if (response.contains("success")) {
210 coolProgramJson = BLANK;
214 // send an async call to the thermostat to get the 'tstat' data
215 connector.getAsyncThermostatData(DEFAULT_RESOURCE);
219 this.refreshJob = scheduler.scheduleWithFixedDelay(runnable, 0, refreshPeriod, TimeUnit.MINUTES);
224 * Schedule the clock sync job
226 private void scheduleClockSyncJob() {
227 ScheduledFuture<?> clockSyncJob = this.clockSyncJob;
228 if (clockSyncJob == null || clockSyncJob.isCancelled()) {
230 this.clockSyncJob = scheduler.schedule(this::syncThermostatClock, 1, TimeUnit.MINUTES);
235 * Sync the thermostat's clock with the host system clock
237 private void syncThermostatClock() {
238 Calendar c = Calendar.getInstance();
240 // The thermostat week starts as Monday = 0, subtract 2 since in standard DoW Monday = 2
241 int thermDayOfWeek = c.get(Calendar.DAY_OF_WEEK) - 2;
242 // Sunday will be -1, so add 7 to make it 6
243 if (thermDayOfWeek < 0) {
247 final String response = connector.sendCommand(null, null,
248 String.format(JSON_TIME, thermDayOfWeek, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE)),
251 // if sync call was successful run again in one hour, if un-successful try again in one minute
252 this.clockSyncJob = scheduler.schedule(this::syncThermostatClock, (response.contains("success") ? 60 : 1),
257 * Start the job to periodically update humidity and runtime date from the thermostat
259 private void startAutomaticLogRefresh() {
260 ScheduledFuture<?> logRefreshJob = this.logRefreshJob;
261 if (logRefreshJob == null || logRefreshJob.isCancelled()) {
262 Runnable runnable = () -> {
263 // Request humidity data from the thermostat if we are a CT80
265 // send an async call to the thermostat to get the humidity data
266 connector.getAsyncThermostatData(HUMIDITY_RESOURCE);
269 if (!this.disableLogs) {
270 // send an async call to the thermostat to get the runtime data
271 connector.getAsyncThermostatData(RUNTIME_RESOURCE);
275 logRefreshJob = null;
276 this.logRefreshJob = scheduler.scheduleWithFixedDelay(runnable, (!this.clockSync ? 1 : 2), logRefreshPeriod,
282 public void dispose() {
283 logger.debug("Disposing the RadioThermostat handler.");
284 connector.removeEventListener(this);
286 ScheduledFuture<?> refreshJob = this.refreshJob;
287 if (refreshJob != null) {
288 refreshJob.cancel(true);
289 this.refreshJob = null;
292 ScheduledFuture<?> logRefreshJob = this.logRefreshJob;
293 if (logRefreshJob != null) {
294 logRefreshJob.cancel(true);
295 this.logRefreshJob = null;
298 ScheduledFuture<?> clockSyncJob = this.clockSyncJob;
299 if (clockSyncJob != null) {
300 clockSyncJob.cancel(true);
301 this.clockSyncJob = null;
305 public void handleRawCommand(@Nullable String rawCommand) {
306 connector.sendCommand(null, null, rawCommand, DEFAULT_RESOURCE);
309 public void handleRawCommand(@Nullable String rawCommand, String resource) {
310 connector.sendCommand(null, null, rawCommand, resource);
314 public void handleCommand(ChannelUID channelUID, Command command) {
315 if (command instanceof RefreshType) {
316 updateChannel(channelUID.getId(), rthermData);
319 String cmdStr = command.toString();
321 // parse out an Integer from the string
322 // ie '70.5 F' becomes 70, also handles negative numbers
323 cmdInt = NumberFormat.getInstance().parse(cmdStr).intValue();
324 } catch (ParseException e) {
325 logger.debug("Command: {} -> Not an integer", cmdStr);
328 switch (channelUID.getId()) {
330 // only do if commanded mode is different than current mode
331 if (!cmdInt.equals(rthermData.getThermostatData().getMode())) {
332 connector.sendCommand("tmode", cmdStr, DEFAULT_RESOURCE);
334 // set the new operating mode, reset everything else,
335 // because refreshing the tstat data below is really slow.
336 rthermData.getThermostatData().setMode(cmdInt);
337 rthermData.getThermostatData().setHeatTarget(Double.valueOf(0));
338 rthermData.getThermostatData().setCoolTarget(Double.valueOf(0));
339 updateChannel(SET_POINT, rthermData);
340 rthermData.getThermostatData().setHold(0);
341 updateChannel(HOLD, rthermData);
342 rthermData.getThermostatData().setProgramMode(-1);
343 updateChannel(PROGRAM_MODE, rthermData);
345 // now just trigger a refresh of the thermostat to get the new active setpoint
346 // this takes a while for the JSON request to complete (async).
347 connector.getAsyncThermostatData(DEFAULT_RESOURCE);
351 rthermData.getThermostatData().setFanMode(cmdInt);
352 connector.sendCommand("fmode", cmdStr, DEFAULT_RESOURCE);
355 rthermData.getThermostatData().setProgramMode(cmdInt);
356 connector.sendCommand("program_mode", cmdStr, DEFAULT_RESOURCE);
359 if (command instanceof OnOffType && command == OnOffType.ON) {
360 rthermData.getThermostatData().setHold(1);
361 connector.sendCommand("hold", "1", DEFAULT_RESOURCE);
362 } else if (command instanceof OnOffType && command == OnOffType.OFF) {
363 rthermData.getThermostatData().setHold(0);
364 connector.sendCommand("hold", "0", DEFAULT_RESOURCE);
368 String cmdKey = null;
369 if (rthermData.getThermostatData().getMode() == 1) {
370 cmdKey = this.setpointCmdKeyPrefix + "heat";
371 rthermData.getThermostatData().setHeatTarget(Double.valueOf(cmdInt));
372 } else if (rthermData.getThermostatData().getMode() == 2) {
373 cmdKey = this.setpointCmdKeyPrefix + "cool";
374 rthermData.getThermostatData().setCoolTarget(Double.valueOf(cmdInt));
376 // don't do anything if we are not in heat or cool mode
379 connector.sendCommand(cmdKey, cmdInt.toString(), DEFAULT_RESOURCE);
383 QuantityType<?> remoteTemp = ((QuantityType<Temperature>) command)
384 .toUnit(ImperialUnits.FAHRENHEIT);
385 connector.sendCommand("rem_temp", String.valueOf(remoteTemp.intValue()), REMOTE_TEMP_RESOURCE);
387 connector.sendCommand("rem_mode", "0", REMOTE_TEMP_RESOURCE);
391 if (!cmdStr.isEmpty()) {
392 connector.sendCommand(null, null, String.format(JSON_PMA, cmdStr), PMA_RESOURCE);
394 connector.sendCommand("mode", "0", PMA_RESOURCE);
398 logger.warn("Unsupported command: {}", command.toString());
404 * Handle a RadioThermostat event received from the listeners
406 * @param event the event received from the listeners
409 public void onNewMessageEvent(RadioThermostatEvent event) {
410 logger.debug("onNewMessageEvent: key {} = {}", event.getKey(), event.getValue());
412 String evtKey = event.getKey();
413 String evtVal = event.getValue();
415 if (KEY_ERROR.equals(evtKey)) {
416 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR,
417 "@text/offline.communication-error-get-data");
419 updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE);
421 // Map the JSON response to the correct object and update appropriate channels
423 case DEFAULT_RESOURCE:
424 rthermData.setThermostatData(gson.fromJson(evtVal, RadioThermostatTstatDTO.class));
425 // if thermostat returned -1 for temperature, skip this update
426 if (rthermData.getThermostatData().getTemperature() >= 0) {
430 case HUMIDITY_RESOURCE:
431 RadioThermostatHumidityDTO dto = gson.fromJson(evtVal, RadioThermostatHumidityDTO.class);
432 // if thermostat returned -1 for humidity, skip this update
433 if (dto != null && dto.getHumidity() >= 0) {
434 rthermData.setHumidity(dto.getHumidity());
435 updateChannel(HUMIDITY, rthermData);
438 case RUNTIME_RESOURCE:
439 rthermData.setRuntime(gson.fromJson(evtVal, RadioThermostatRuntimeDTO.class));
440 updateChannel(TODAY_HEAT_RUNTIME, rthermData);
441 updateChannel(TODAY_COOL_RUNTIME, rthermData);
442 updateChannel(YESTERDAY_HEAT_RUNTIME, rthermData);
443 updateChannel(YESTERDAY_COOL_RUNTIME, rthermData);
450 * Update the channel from the last Thermostat data retrieved
452 * @param channelId the id identifying the channel to be updated
454 private void updateChannel(String channelId, RadioThermostatDTO rthermData) {
455 if (isLinked(channelId)) {
458 value = getValue(channelId, rthermData);
459 } catch (Exception e) {
460 logger.debug("Error setting {} value", channelId.toUpperCase());
466 state = UnDefType.UNDEF;
467 } else if (value instanceof PointType) {
468 state = (PointType) value;
469 } else if (value instanceof ZonedDateTime) {
470 state = new DateTimeType((ZonedDateTime) value);
471 } else if (value instanceof QuantityType<?>) {
472 state = (QuantityType<?>) value;
473 } else if (value instanceof Number) {
474 state = new DecimalType((Number) value);
475 } else if (value instanceof String) {
476 state = new StringType(value.toString());
477 } else if (value instanceof OnOffType) {
478 state = (OnOffType) value;
480 logger.warn("Update channel {}: Unsupported value type {}", channelId,
481 value.getClass().getSimpleName());
483 logger.debug("Update channel {} with state {} ({})", channelId, (state == null) ? "null" : state.toString(),
484 (value == null) ? "null" : value.getClass().getSimpleName());
486 // Update the channel
488 updateState(channelId, state);
494 * Update a given channelId from the thermostat data
496 * @param the channel id to be updated
497 * @param data the RadioThermostat dto
498 * @return the value to be set in the state
500 public static @Nullable Object getValue(String channelId, RadioThermostatDTO data) {
503 if (data.getThermostatData().getTemperature() != null) {
504 return new QuantityType<Temperature>(data.getThermostatData().getTemperature(),
505 API_TEMPERATURE_UNIT);
510 if (data.getHumidity() != null) {
511 return new QuantityType<>(data.getHumidity(), API_HUMIDITY_UNIT);
516 return data.getThermostatData().getMode();
518 return data.getThermostatData().getFanMode();
520 return data.getThermostatData().getProgramMode();
522 if (data.getThermostatData().getSetpoint() != 0) {
523 return new QuantityType<Temperature>(data.getThermostatData().getSetpoint(), API_TEMPERATURE_UNIT);
528 return data.getThermostatData().getOverride();
530 return OnOffType.from(data.getThermostatData().getHold() == 1);
532 return data.getThermostatData().getStatus();
534 // workaround for some thermostats that don't report that the fan is on during heating or cooling
535 if (data.getThermostatData().getStatus() > 0) {
538 return data.getThermostatData().getFanStatus();
541 return data.getThermostatData().getTime().getDayOfWeek();
543 return data.getThermostatData().getTime().getHour();
545 return data.getThermostatData().getTime().getMinute();
547 return data.getThermostatData().getTime().getThemostatDateTime();
548 case TODAY_HEAT_RUNTIME:
549 return new QuantityType<>(data.getRuntime().getToday().getHeatTime().getRuntime(), API_MINUTES_UNIT);
550 case TODAY_COOL_RUNTIME:
551 return new QuantityType<>(data.getRuntime().getToday().getCoolTime().getRuntime(), API_MINUTES_UNIT);
552 case YESTERDAY_HEAT_RUNTIME:
553 return new QuantityType<>(data.getRuntime().getYesterday().getHeatTime().getRuntime(),
555 case YESTERDAY_COOL_RUNTIME:
556 return new QuantityType<>(data.getRuntime().getYesterday().getCoolTime().getRuntime(),
563 * Updates all channels from rthermData
565 private void updateAllChannels() {
566 // Update all channels from rthermData
567 getThing().getChannels().forEach(channel -> {
568 if (!NO_UPDATE_CHANNEL_IDS.contains(channel.getUID().getId())) {
569 updateChannel(channel.getUID().getId(), rthermData);
575 * Build a list of fan modes based on what model thermostat is used
577 * @return list of state options for thermostat fan modes
579 private List<StateOption> getFanModeOptions() {
580 List<StateOption> fanModeOptions = new ArrayList<>();
582 fanModeOptions.add(new StateOption("0", "@text/options.fan-option-auto"));
584 fanModeOptions.add(new StateOption("1", "@text/options.fan-option-circulate"));
586 fanModeOptions.add(new StateOption("2", "@text/options.fan-option-on"));
588 return fanModeOptions;