]> git.basschouten.com Git - openhab-addons.git/blob
20867209653c66b245185a2b363b61f1526e6bb8
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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.ecobee.internal.handler;
14
15 import static org.openhab.binding.ecobee.internal.EcobeeBindingConstants.*;
16
17 import java.lang.reflect.Field;
18 import java.util.Collection;
19 import java.util.Collections;
20 import java.util.HashMap;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.concurrent.ConcurrentHashMap;
24 import java.util.concurrent.CopyOnWriteArrayList;
25
26 import javax.measure.Unit;
27
28 import org.eclipse.jdt.annotation.NonNullByDefault;
29 import org.eclipse.jdt.annotation.Nullable;
30 import org.openhab.binding.ecobee.internal.action.EcobeeActions;
31 import org.openhab.binding.ecobee.internal.api.EcobeeApi;
32 import org.openhab.binding.ecobee.internal.config.EcobeeThermostatConfiguration;
33 import org.openhab.binding.ecobee.internal.dto.SelectionDTO;
34 import org.openhab.binding.ecobee.internal.dto.thermostat.AlertDTO;
35 import org.openhab.binding.ecobee.internal.dto.thermostat.ClimateDTO;
36 import org.openhab.binding.ecobee.internal.dto.thermostat.EventDTO;
37 import org.openhab.binding.ecobee.internal.dto.thermostat.HouseDetailsDTO;
38 import org.openhab.binding.ecobee.internal.dto.thermostat.LocationDTO;
39 import org.openhab.binding.ecobee.internal.dto.thermostat.ManagementDTO;
40 import org.openhab.binding.ecobee.internal.dto.thermostat.ProgramDTO;
41 import org.openhab.binding.ecobee.internal.dto.thermostat.RemoteSensorDTO;
42 import org.openhab.binding.ecobee.internal.dto.thermostat.RuntimeDTO;
43 import org.openhab.binding.ecobee.internal.dto.thermostat.SettingsDTO;
44 import org.openhab.binding.ecobee.internal.dto.thermostat.TechnicianDTO;
45 import org.openhab.binding.ecobee.internal.dto.thermostat.ThermostatDTO;
46 import org.openhab.binding.ecobee.internal.dto.thermostat.ThermostatUpdateRequestDTO;
47 import org.openhab.binding.ecobee.internal.dto.thermostat.VersionDTO;
48 import org.openhab.binding.ecobee.internal.dto.thermostat.WeatherDTO;
49 import org.openhab.binding.ecobee.internal.dto.thermostat.WeatherForecastDTO;
50 import org.openhab.binding.ecobee.internal.function.AbstractFunction;
51 import org.openhab.binding.ecobee.internal.function.FunctionRequest;
52 import org.openhab.binding.ecobee.internal.util.StringUtils;
53 import org.openhab.core.i18n.TimeZoneProvider;
54 import org.openhab.core.library.types.DecimalType;
55 import org.openhab.core.library.types.OnOffType;
56 import org.openhab.core.library.types.QuantityType;
57 import org.openhab.core.library.types.StringType;
58 import org.openhab.core.library.unit.ImperialUnits;
59 import org.openhab.core.library.unit.SIUnits;
60 import org.openhab.core.library.unit.Units;
61 import org.openhab.core.thing.Bridge;
62 import org.openhab.core.thing.Channel;
63 import org.openhab.core.thing.ChannelUID;
64 import org.openhab.core.thing.Thing;
65 import org.openhab.core.thing.ThingStatus;
66 import org.openhab.core.thing.ThingStatusDetail;
67 import org.openhab.core.thing.ThingStatusInfo;
68 import org.openhab.core.thing.binding.BaseBridgeHandler;
69 import org.openhab.core.thing.binding.ThingHandler;
70 import org.openhab.core.thing.binding.ThingHandlerService;
71 import org.openhab.core.thing.type.ChannelType;
72 import org.openhab.core.thing.type.ChannelTypeRegistry;
73 import org.openhab.core.thing.type.ChannelTypeUID;
74 import org.openhab.core.types.Command;
75 import org.openhab.core.types.RefreshType;
76 import org.openhab.core.types.State;
77 import org.slf4j.Logger;
78 import org.slf4j.LoggerFactory;
79
80 /**
81  * The {@link EcobeeThermostatBridgeHandler} is the handler for an Ecobee thermostat.
82  *
83  * @author Mark Hilbush - Initial contribution
84  */
85 @NonNullByDefault
86 public class EcobeeThermostatBridgeHandler extends BaseBridgeHandler {
87
88     private final Logger logger = LoggerFactory.getLogger(EcobeeThermostatBridgeHandler.class);
89
90     private TimeZoneProvider timeZoneProvider;
91     private ChannelTypeRegistry channelTypeRegistry;
92
93     private @NonNullByDefault({}) String thermostatId;
94
95     private final Map<String, EcobeeSensorThingHandler> sensorHandlers = new ConcurrentHashMap<>();
96
97     private @Nullable ThermostatDTO savedThermostat;
98     private @Nullable List<RemoteSensorDTO> savedSensors;
99     private List<String> validClimateRefs = new CopyOnWriteArrayList<>();
100     private Map<String, State> stateCache = new ConcurrentHashMap<>();
101     private Map<ChannelUID, Boolean> channelReadOnlyMap = new HashMap<>();
102     private Map<Integer, String> symbolMap = new HashMap<>();
103     private Map<Integer, String> skyMap = new HashMap<>();
104
105     public EcobeeThermostatBridgeHandler(Bridge bridge, TimeZoneProvider timeZoneProvider,
106             ChannelTypeRegistry channelTypeRegistry) {
107         super(bridge);
108         this.timeZoneProvider = timeZoneProvider;
109         this.channelTypeRegistry = channelTypeRegistry;
110     }
111
112     @Override
113     public void initialize() {
114         thermostatId = getConfigAs(EcobeeThermostatConfiguration.class).thermostatId;
115         logger.debug("ThermostatBridge: Initializing thermostat '{}'", thermostatId);
116         initializeWeatherMaps();
117         initializeReadOnlyChannels();
118         clearSavedState();
119         updateStatus(EcobeeUtils.isBridgeOnline(getBridge()) ? ThingStatus.ONLINE : ThingStatus.OFFLINE);
120     }
121
122     @Override
123     public void dispose() {
124         logger.debug("ThermostatBridge: Disposing thermostat '{}'", thermostatId);
125     }
126
127     @Override
128     public void childHandlerInitialized(ThingHandler sensorHandler, Thing sensorThing) {
129         String sensorId = (String) sensorThing.getConfiguration().get(CONFIG_SENSOR_ID);
130         sensorHandlers.put(sensorId, (EcobeeSensorThingHandler) sensorHandler);
131         logger.debug("ThermostatBridge: Saving sensor handler for {} with id {}", sensorThing.getUID(), sensorId);
132     }
133
134     @Override
135     public void childHandlerDisposed(ThingHandler sensorHandler, Thing sensorThing) {
136         String sensorId = (String) sensorThing.getConfiguration().get(CONFIG_SENSOR_ID);
137         sensorHandlers.remove(sensorId);
138         logger.debug("ThermostatBridge: Removing sensor handler for {} with id {}", sensorThing.getUID(), sensorId);
139     }
140
141     @Override
142     public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
143         if (bridgeStatusInfo.getStatus() == ThingStatus.ONLINE) {
144             updateStatus(ThingStatus.ONLINE);
145         } else {
146             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
147         }
148     }
149
150     @SuppressWarnings("null")
151     @Override
152     public void handleCommand(ChannelUID channelUID, Command command) {
153         if (command instanceof RefreshType) {
154             State state = stateCache.get(channelUID.getId());
155             if (state != null) {
156                 updateState(channelUID.getId(), state);
157             }
158             return;
159         }
160         if (isChannelReadOnly(channelUID)) {
161             logger.debug("Can't apply command '{}' to '{}' because channel is readonly", command, channelUID.getId());
162             return;
163         }
164         scheduler.execute(() -> {
165             handleThermostatCommand(channelUID, command);
166         });
167     }
168
169     /**
170      * Called by the AccountBridgeHandler to create a Selection that
171      * includes only the Ecobee objects for which there's at least one
172      * item linked to one of that object's channels.
173      *
174      * @return Selection
175      */
176     public SelectionDTO getSelection() {
177         final SelectionDTO selection = new SelectionDTO();
178         for (String group : CHANNEL_GROUPS) {
179             for (Channel channel : thing.getChannelsOfGroup(group)) {
180                 if (isLinked(channel.getUID())) {
181                     try {
182                         Field field = selection.getClass().getField("include" + StringUtils.capitalizeWords(group));
183                         logger.trace("ThermostatBridge: Thermostat thing '{}' including object '{}' in selection",
184                                 thing.getUID(), field.getName());
185                         field.set(selection, Boolean.TRUE);
186                         break;
187                     } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException
188                             | SecurityException e) {
189                         logger.debug("ThermostatBridge: Exception setting selection for group '{}'", group, e);
190                     }
191                 }
192             }
193         }
194         return selection;
195     }
196
197     public List<RemoteSensorDTO> getSensors() {
198         List<RemoteSensorDTO> localSavedSensors = savedSensors;
199         return localSavedSensors == null ? EMPTY_SENSORS : localSavedSensors;
200     }
201
202     public @Nullable String getAlerts() {
203         ThermostatDTO thermostat = savedThermostat;
204         if (thermostat != null && thermostat.alerts != null) {
205             return EcobeeApi.getGson().toJson(thermostat.alerts);
206         }
207         return null;
208     }
209
210     public @Nullable String getEvents() {
211         ThermostatDTO thermostat = savedThermostat;
212         if (thermostat != null && thermostat.events != null) {
213             return EcobeeApi.getGson().toJson(thermostat.events);
214         }
215         return null;
216     }
217
218     public @Nullable String getClimates() {
219         ThermostatDTO thermostat = savedThermostat;
220         if (thermostat != null && thermostat.program != null && thermostat.program.climates != null) {
221             return EcobeeApi.getGson().toJson(thermostat.program.climates);
222         }
223         return null;
224     }
225
226     public boolean isValidClimateRef(String climateRef) {
227         return validClimateRefs.contains(climateRef);
228     }
229
230     public String getThermostatId() {
231         return thermostatId;
232     }
233
234     /*
235      * Called by EcobeeActions to perform a thermostat function
236      */
237     public boolean actionPerformFunction(AbstractFunction function) {
238         logger.debug("ThermostatBridge: Perform function '{}' on thermostat {}", function.type, thermostatId);
239         SelectionDTO selection = new SelectionDTO();
240         selection.setThermostats(Collections.singleton(thermostatId));
241         FunctionRequest request = new FunctionRequest(selection);
242         request.functions = Collections.singletonList(function);
243         EcobeeAccountBridgeHandler handler = getBridgeHandler();
244         if (handler != null) {
245             return handler.performThermostatFunction(request);
246         }
247         return false;
248     }
249
250     @Override
251     public Collection<Class<? extends ThingHandlerService>> getServices() {
252         return Collections.singletonList(EcobeeActions.class);
253     }
254
255     public void updateChannels(ThermostatDTO thermostat) {
256         logger.debug("ThermostatBridge: Updating channels for thermostat id {}", thermostat.identifier);
257         savedThermostat = thermostat;
258         updateAlert(thermostat.alerts);
259         updateHouseDetails(thermostat.houseDetails);
260         updateInfo(thermostat);
261         updateEquipmentStatus(thermostat);
262         updateLocation(thermostat.location);
263         updateManagement(thermostat.management);
264         updateProgram(thermostat.program);
265         updateEvent(thermostat.events);
266         updateRemoteSensors(thermostat.remoteSensors);
267         updateRuntime(thermostat.runtime);
268         updateSettings(thermostat.settings);
269         updateTechnician(thermostat.technician);
270         updateVersion(thermostat.version);
271         updateWeather(thermostat.weather);
272         savedSensors = thermostat.remoteSensors;
273     }
274
275     private void handleThermostatCommand(ChannelUID channelUID, Command command) {
276         logger.debug("Got command '{}' for channel '{}' of thing '{}'", command, channelUID, getThing().getUID());
277         String channelId = channelUID.getIdWithoutGroup();
278         String groupId = channelUID.getGroupId();
279         if (groupId == null) {
280             logger.info("Can't handle command '{}' because channel's groupId is null", command);
281             return;
282         }
283         ThermostatDTO thermostat = new ThermostatDTO();
284         Field field;
285         try {
286             switch (groupId) {
287                 case CHGRP_INFO:
288                     field = thermostat.getClass().getField(channelId);
289                     setField(field, thermostat, command);
290                     break;
291                 case CHGRP_SETTINGS:
292                     SettingsDTO settings = new SettingsDTO();
293                     field = settings.getClass().getField(channelId);
294                     setField(field, settings, command);
295                     thermostat.settings = settings;
296                     break;
297                 case CHGRP_LOCATION:
298                     LocationDTO location = new LocationDTO();
299                     field = location.getClass().getField(channelId);
300                     setField(field, location, command);
301                     thermostat.location = location;
302                     break;
303                 case CHGRP_HOUSE_DETAILS:
304                     HouseDetailsDTO houseDetails = new HouseDetailsDTO();
305                     field = houseDetails.getClass().getField(channelId);
306                     setField(field, houseDetails, command);
307                     thermostat.houseDetails = houseDetails;
308                     break;
309                 default:
310                     // All other groups contain only read-only fields
311                     return;
312             }
313             performThermostatUpdate(thermostat);
314         } catch (NoSuchFieldException | SecurityException e) {
315             logger.info("Unable to get field for '{}.{}'", groupId, channelId);
316         }
317     }
318
319     private void setField(Field field, Object object, Command command) {
320         logger.debug("Setting field '{}.{}' to value '{}'", object.getClass().getSimpleName().toLowerCase(),
321                 field.getName(), command);
322         Class<?> fieldClass = field.getType();
323         try {
324             boolean success = false;
325             if (String.class.isAssignableFrom(fieldClass)) {
326                 if (command instanceof StringType) {
327                     logger.debug("Set field of type String to value of StringType");
328                     field.set(object, command.toString());
329                     success = true;
330                 }
331             } else if (Integer.class.isAssignableFrom(fieldClass)) {
332                 if (command instanceof DecimalType) {
333                     logger.debug("Set field of type Integer to value of DecimalType");
334                     field.set(object, Integer.valueOf(((DecimalType) command).intValue()));
335                     success = true;
336                 } else if (command instanceof QuantityType) {
337                     Unit<?> unit = ((QuantityType<?>) command).getUnit();
338                     logger.debug("Set field of type Integer to value of QuantityType with unit {}", unit);
339                     if (unit.equals(ImperialUnits.FAHRENHEIT) || unit.equals(SIUnits.CELSIUS)) {
340                         QuantityType<?> quantity = ((QuantityType<?>) command).toUnit(ImperialUnits.FAHRENHEIT);
341                         if (quantity != null) {
342                             field.set(object, quantity.intValue() * 10);
343                             success = true;
344                         }
345                     }
346                 }
347             } else if (Boolean.class.isAssignableFrom(fieldClass)) {
348                 if (command instanceof OnOffType) {
349                     logger.debug("Set field of type Boolean to value of OnOffType");
350                     field.set(object, command == OnOffType.ON);
351                     success = true;
352                 }
353             }
354             if (!success) {
355                 logger.info("Don't know how to convert command of type '{}' to {}.{}",
356                         command.getClass().getSimpleName(), object.getClass().getSimpleName(), field.getName());
357             }
358         } catch (IllegalArgumentException | IllegalAccessException e) {
359             logger.info("Unable to set field '{}.{}' to value '{}'", object.getClass().getSimpleName(), field.getName(),
360                     command, e);
361         }
362     }
363
364     private void updateInfo(ThermostatDTO thermostat) {
365         final String grp = CHGRP_INFO + "#";
366         updateChannel(grp + CH_IDENTIFIER, EcobeeUtils.undefOrString(thermostat.identifier));
367         updateChannel(grp + CH_NAME, EcobeeUtils.undefOrString(thermostat.name));
368         updateChannel(grp + CH_THERMOSTAT_REV, EcobeeUtils.undefOrString(thermostat.thermostatRev));
369         updateChannel(grp + CH_IS_REGISTERED, EcobeeUtils.undefOrOnOff(thermostat.isRegistered));
370         updateChannel(grp + CH_MODEL_NUMBER, EcobeeUtils.undefOrString(thermostat.modelNumber));
371         updateChannel(grp + CH_BRAND, EcobeeUtils.undefOrString(thermostat.brand));
372         updateChannel(grp + CH_FEATURES, EcobeeUtils.undefOrString(thermostat.features));
373         updateChannel(grp + CH_LAST_MODIFIED, EcobeeUtils.undefOrDate(thermostat.lastModified, timeZoneProvider));
374         updateChannel(grp + CH_THERMOSTAT_TIME, EcobeeUtils.undefOrDate(thermostat.thermostatTime, timeZoneProvider));
375     }
376
377     private void updateEquipmentStatus(ThermostatDTO thermostat) {
378         final String grp = CHGRP_EQUIPMENT_STATUS + "#";
379         updateChannel(grp + CH_EQUIPMENT_STATUS, EcobeeUtils.undefOrString(thermostat.equipmentStatus));
380     }
381
382     private void updateRuntime(@Nullable RuntimeDTO runtime) {
383         if (runtime == null) {
384             return;
385         }
386         final String grp = CHGRP_RUNTIME + "#";
387         updateChannel(grp + CH_RUNTIME_REV, EcobeeUtils.undefOrString(runtime.runtimeRev));
388         updateChannel(grp + CH_CONNECTED, EcobeeUtils.undefOrOnOff(runtime.connected));
389         updateChannel(grp + CH_FIRST_CONNECTED, EcobeeUtils.undefOrDate(runtime.firstConnected, timeZoneProvider));
390         updateChannel(grp + CH_CONNECT_DATE_TIME, EcobeeUtils.undefOrDate(runtime.connectDateTime, timeZoneProvider));
391         updateChannel(grp + CH_DISCONNECT_DATE_TIME,
392                 EcobeeUtils.undefOrDate(runtime.disconnectDateTime, timeZoneProvider));
393         updateChannel(grp + CH_RT_LAST_MODIFIED, EcobeeUtils.undefOrDate(runtime.lastModified, timeZoneProvider));
394         updateChannel(grp + CH_RT_LAST_STATUS_MODIFIED,
395                 EcobeeUtils.undefOrDate(runtime.lastStatusModified, timeZoneProvider));
396         updateChannel(grp + CH_RUNTIME_DATE, EcobeeUtils.undefOrString(runtime.runtimeDate));
397         updateChannel(grp + CH_RUNTIME_INTERVAL, EcobeeUtils.undefOrDecimal(runtime.runtimeInterval));
398         updateChannel(grp + CH_ACTUAL_TEMPERATURE, EcobeeUtils.undefOrTemperature(runtime.actualTemperature));
399         updateChannel(grp + CH_ACTUAL_HUMIDITY, EcobeeUtils.undefOrQuantity(runtime.actualHumidity, Units.PERCENT));
400         updateChannel(grp + CH_RAW_TEMPERATURE, EcobeeUtils.undefOrTemperature(runtime.rawTemperature));
401         updateChannel(grp + CH_SHOW_ICON_MODE, EcobeeUtils.undefOrDecimal(runtime.showIconMode));
402         updateChannel(grp + CH_DESIRED_HEAT, EcobeeUtils.undefOrTemperature(runtime.desiredHeat));
403         updateChannel(grp + CH_DESIRED_COOL, EcobeeUtils.undefOrTemperature(runtime.desiredCool));
404         updateChannel(grp + CH_DESIRED_HUMIDITY, EcobeeUtils.undefOrQuantity(runtime.desiredHumidity, Units.PERCENT));
405         updateChannel(grp + CH_DESIRED_DEHUMIDITY,
406                 EcobeeUtils.undefOrQuantity(runtime.desiredDehumidity, Units.PERCENT));
407         updateChannel(grp + CH_DESIRED_FAN_MODE, EcobeeUtils.undefOrString(runtime.desiredFanMode));
408         if (runtime.desiredHeatRange != null && runtime.desiredHeatRange.size() == 2) {
409             updateChannel(grp + CH_DESIRED_HEAT_RANGE_LOW,
410                     EcobeeUtils.undefOrTemperature(runtime.desiredHeatRange.get(0)));
411             updateChannel(grp + CH_DESIRED_HEAT_RANGE_HIGH,
412                     EcobeeUtils.undefOrTemperature(runtime.desiredHeatRange.get(1)));
413         }
414         if (runtime.desiredCoolRange != null && runtime.desiredCoolRange.size() == 2) {
415             updateChannel(grp + CH_DESIRED_COOL_RANGE_LOW,
416                     EcobeeUtils.undefOrTemperature(runtime.desiredCoolRange.get(0)));
417             updateChannel(grp + CH_DESIRED_COOL_RANGE_HIGH,
418                     EcobeeUtils.undefOrTemperature(runtime.desiredCoolRange.get(1)));
419         }
420         updateChannel(grp + CH_ACTUAL_AQ_ACCURACY, EcobeeUtils.undefOrLong(runtime.actualAQAccuracy));
421         updateChannel(grp + CH_ACTUAL_AQ_SCORE, EcobeeUtils.undefOrLong(runtime.actualAQScore));
422         updateChannel(grp + CH_ACTUAL_CO2, EcobeeUtils.undefOrQuantity(runtime.actualCO2, Units.PARTS_PER_MILLION));
423         updateChannel(grp + CH_ACTUAL_VOC, EcobeeUtils.undefOrQuantity(runtime.actualVOC, Units.PARTS_PER_BILLION));
424     }
425
426     private void updateSettings(@Nullable SettingsDTO settings) {
427         if (settings == null) {
428             return;
429         }
430         final String grp = CHGRP_SETTINGS + "#";
431         updateChannel(grp + CH_HVAC_MODE, EcobeeUtils.undefOrString(settings.hvacMode));
432         updateChannel(grp + CH_LAST_SERVICE_DATE, EcobeeUtils.undefOrString(settings.lastServiceDate));
433         updateChannel(grp + CH_SERVICE_REMIND_ME, EcobeeUtils.undefOrOnOff(settings.serviceRemindMe));
434         updateChannel(grp + CH_MONTHS_BETWEEN_SERVICE, EcobeeUtils.undefOrDecimal(settings.monthsBetweenService));
435         updateChannel(grp + CH_REMIND_ME_DATE, EcobeeUtils.undefOrString(settings.remindMeDate));
436         updateChannel(grp + CH_VENT, EcobeeUtils.undefOrString(settings.vent));
437         updateChannel(grp + CH_VENTILATOR_MIN_ON_TIME, EcobeeUtils.undefOrDecimal(settings.ventilatorMinOnTime));
438         updateChannel(grp + CH_SERVICE_REMIND_TECHNICIAN, EcobeeUtils.undefOrOnOff(settings.serviceRemindTechnician));
439         updateChannel(grp + CH_EI_LOCATION, EcobeeUtils.undefOrString(settings.eiLocation));
440         updateChannel(grp + CH_COLD_TEMP_ALERT, EcobeeUtils.undefOrTemperature(settings.coldTempAlert));
441         updateChannel(grp + CH_COLD_TEMP_ALERT_ENABLED, EcobeeUtils.undefOrOnOff(settings.coldTempAlertEnabled));
442         updateChannel(grp + CH_HOT_TEMP_ALERT, EcobeeUtils.undefOrTemperature(settings.hotTempAlert));
443         updateChannel(grp + CH_HOT_TEMP_ALERT_ENABLED, EcobeeUtils.undefOrOnOff(settings.hotTempAlertEnabled));
444         updateChannel(grp + CH_COOL_STAGES, EcobeeUtils.undefOrDecimal(settings.coolStages));
445         updateChannel(grp + CH_HEAT_STAGES, EcobeeUtils.undefOrDecimal(settings.heatStages));
446         updateChannel(grp + CH_MAX_SET_BACK, EcobeeUtils.undefOrDecimal(settings.maxSetBack));
447         updateChannel(grp + CH_MAX_SET_FORWARD, EcobeeUtils.undefOrDecimal(settings.maxSetForward));
448         updateChannel(grp + CH_QUICK_SAVE_SET_BACK, EcobeeUtils.undefOrDecimal(settings.quickSaveSetBack));
449         updateChannel(grp + CH_QUICK_SAVE_SET_FORWARD, EcobeeUtils.undefOrDecimal(settings.quickSaveSetForward));
450         updateChannel(grp + CH_HAS_HEAT_PUMP, EcobeeUtils.undefOrOnOff(settings.hasHeatPump));
451         updateChannel(grp + CH_HAS_FORCED_AIR, EcobeeUtils.undefOrOnOff(settings.hasForcedAir));
452         updateChannel(grp + CH_HAS_BOILER, EcobeeUtils.undefOrOnOff(settings.hasBoiler));
453         updateChannel(grp + CH_HAS_HUMIDIFIER, EcobeeUtils.undefOrOnOff(settings.hasHumidifier));
454         updateChannel(grp + CH_HAS_ERV, EcobeeUtils.undefOrOnOff(settings.hasErv));
455         updateChannel(grp + CH_HAS_HRV, EcobeeUtils.undefOrOnOff(settings.hasHrv));
456         updateChannel(grp + CH_CONDENSATION_AVOID, EcobeeUtils.undefOrOnOff(settings.condensationAvoid));
457         updateChannel(grp + CH_USE_CELSIUS, EcobeeUtils.undefOrOnOff(settings.useCelsius));
458         updateChannel(grp + CH_USE_TIME_FORMAT_12, EcobeeUtils.undefOrOnOff(settings.useTimeFormat12));
459         updateChannel(grp + CH_LOCALE, EcobeeUtils.undefOrString(settings.locale));
460         updateChannel(grp + CH_HUMIDITY, EcobeeUtils.undefOrString(settings.humidity));
461         updateChannel(grp + CH_HUMIDIFIER_MODE, EcobeeUtils.undefOrString(settings.humidifierMode));
462         updateChannel(grp + CH_BACKLIGHT_ON_INTENSITY, EcobeeUtils.undefOrDecimal(settings.backlightOnIntensity));
463         updateChannel(grp + CH_BACKLIGHT_SLEEP_INTENSITY, EcobeeUtils.undefOrDecimal(settings.backlightSleepIntensity));
464         updateChannel(grp + CH_BACKLIGHT_OFF_TIME, EcobeeUtils.undefOrDecimal(settings.backlightOffTime));
465         updateChannel(grp + CH_SOUND_TICK_VOLUME, EcobeeUtils.undefOrDecimal(settings.soundTickVolume));
466         updateChannel(grp + CH_SOUND_ALERT_VOLUME, EcobeeUtils.undefOrDecimal(settings.soundAlertVolume));
467         updateChannel(grp + CH_COMPRESSOR_PROTECTION_MIN_TIME,
468                 EcobeeUtils.undefOrDecimal(settings.compressorProtectionMinTime));
469         updateChannel(grp + CH_COMPRESSOR_PROTECTION_MIN_TEMP,
470                 EcobeeUtils.undefOrTemperature(settings.compressorProtectionMinTemp));
471         updateChannel(grp + CH_STAGE1_HEATING_DIFFERENTIAL_TEMP,
472                 EcobeeUtils.undefOrDecimal(settings.stage1HeatingDifferentialTemp));
473         updateChannel(grp + CH_STAGE1_COOLING_DIFFERENTIAL_TEMP,
474                 EcobeeUtils.undefOrDecimal(settings.stage1CoolingDifferentialTemp));
475         updateChannel(grp + CH_STAGE1_HEATING_DISSIPATION_TIME,
476                 EcobeeUtils.undefOrDecimal(settings.stage1HeatingDissipationTime));
477         updateChannel(grp + CH_STAGE1_COOLING_DISSIPATION_TIME,
478                 EcobeeUtils.undefOrDecimal(settings.stage1CoolingDissipationTime));
479         updateChannel(grp + CH_HEAT_PUMP_REVERSAL_ON_COOL, EcobeeUtils.undefOrOnOff(settings.heatPumpReversalOnCool));
480         updateChannel(grp + CH_FAN_CONTROLLER_REQUIRED, EcobeeUtils.undefOrOnOff(settings.fanControlRequired));
481         updateChannel(grp + CH_FAN_MIN_ON_TIME, EcobeeUtils.undefOrDecimal(settings.fanMinOnTime));
482         updateChannel(grp + CH_HEAT_COOL_MIN_DELTA, EcobeeUtils.undefOrDecimal(settings.heatCoolMinDelta));
483         updateChannel(grp + CH_TEMP_CORRECTION, EcobeeUtils.undefOrDecimal(settings.tempCorrection));
484         updateChannel(grp + CH_HOLD_ACTION, EcobeeUtils.undefOrString(settings.holdAction));
485         updateChannel(grp + CH_HEAT_PUMP_GROUND_WATER, EcobeeUtils.undefOrOnOff(settings.heatPumpGroundWater));
486         updateChannel(grp + CH_HAS_ELECTRIC, EcobeeUtils.undefOrOnOff(settings.hasElectric));
487         updateChannel(grp + CH_HAS_DEHUMIDIFIER, EcobeeUtils.undefOrOnOff(settings.hasDehumidifier));
488         updateChannel(grp + CH_DEHUMIDIFIER_MODE, EcobeeUtils.undefOrString(settings.dehumidifierMode));
489         updateChannel(grp + CH_DEHUMIDIFIER_LEVEL, EcobeeUtils.undefOrDecimal(settings.dehumidifierLevel));
490         updateChannel(grp + CH_DEHUMIDIFY_WITH_AC, EcobeeUtils.undefOrOnOff(settings.dehumidifyWithAC));
491         updateChannel(grp + CH_DEHUMIDIFY_OVERCOOL_OFFSET,
492                 EcobeeUtils.undefOrDecimal(settings.dehumidifyOvercoolOffset));
493         updateChannel(grp + CH_AUTO_HEAT_COOL_FEATURE_ENABLED,
494                 EcobeeUtils.undefOrOnOff(settings.autoHeatCoolFeatureEnabled));
495         updateChannel(grp + CH_WIFI_OFFLINE_ALERT, EcobeeUtils.undefOrOnOff(settings.wifiOfflineAlert));
496         updateChannel(grp + CH_HEAT_MIN_TEMP, EcobeeUtils.undefOrTemperature(settings.heatMinTemp));
497         updateChannel(grp + CH_HEAT_MAX_TEMP, EcobeeUtils.undefOrTemperature(settings.heatMaxTemp));
498         updateChannel(grp + CH_COOL_MIN_TEMP, EcobeeUtils.undefOrTemperature(settings.coolMinTemp));
499         updateChannel(grp + CH_COOL_MAX_TEMP, EcobeeUtils.undefOrTemperature(settings.coolMaxTemp));
500         updateChannel(grp + CH_HEAT_RANGE_HIGH, EcobeeUtils.undefOrTemperature(settings.heatRangeHigh));
501         updateChannel(grp + CH_HEAT_RANGE_LOW, EcobeeUtils.undefOrTemperature(settings.heatRangeLow));
502         updateChannel(grp + CH_COOL_RANGE_HIGH, EcobeeUtils.undefOrTemperature(settings.coolRangeHigh));
503         updateChannel(grp + CH_COOL_RANGE_LOW, EcobeeUtils.undefOrTemperature(settings.coolRangeLow));
504         updateChannel(grp + CH_USER_ACCESS_CODE, EcobeeUtils.undefOrString(settings.userAccessCode));
505         updateChannel(grp + CH_USER_ACCESS_SETTING, EcobeeUtils.undefOrDecimal(settings.userAccessSetting));
506         updateChannel(grp + CH_AUX_RUNTIME_ALERT, EcobeeUtils.undefOrDecimal(settings.auxRuntimeAlert));
507         updateChannel(grp + CH_AUX_OUTDOOR_TEMP_ALERT, EcobeeUtils.undefOrTemperature(settings.auxOutdoorTempAlert));
508         updateChannel(grp + CH_AUX_MAX_OUTDOOR_TEMP, EcobeeUtils.undefOrTemperature(settings.auxMaxOutdoorTemp));
509         updateChannel(grp + CH_AUX_RUNTIME_ALERT_NOTIFY, EcobeeUtils.undefOrOnOff(settings.auxRuntimeAlertNotify));
510         updateChannel(grp + CH_AUX_OUTDOOR_TEMP_ALERT_NOTIFY,
511                 EcobeeUtils.undefOrOnOff(settings.auxOutdoorTempAlertNotify));
512         updateChannel(grp + CH_AUX_RUNTIME_ALERT_NOTIFY_TECHNICIAN,
513                 EcobeeUtils.undefOrOnOff(settings.auxRuntimeAlertNotifyTechnician));
514         updateChannel(grp + CH_AUX_OUTDOOR_TEMP_ALERT_NOTIFY_TECHNICIAN,
515                 EcobeeUtils.undefOrOnOff(settings.auxOutdoorTempAlertNotifyTechnician));
516         updateChannel(grp + CH_DISABLE_PREHEATING, EcobeeUtils.undefOrOnOff(settings.disablePreHeating));
517         updateChannel(grp + CH_DISABLE_PRECOOLING, EcobeeUtils.undefOrOnOff(settings.disablePreCooling));
518         updateChannel(grp + CH_INSTALLER_CODE_REQUIRED, EcobeeUtils.undefOrOnOff(settings.installerCodeRequired));
519         updateChannel(grp + CH_DR_ACCEPT, EcobeeUtils.undefOrString(settings.drAccept));
520         updateChannel(grp + CH_IS_RENTAL_PROPERTY, EcobeeUtils.undefOrOnOff(settings.isRentalProperty));
521         updateChannel(grp + CH_USE_ZONE_CONTROLLER, EcobeeUtils.undefOrOnOff(settings.useZoneController));
522         updateChannel(grp + CH_RANDOM_START_DELAY_COOL, EcobeeUtils.undefOrDecimal(settings.randomStartDelayCool));
523         updateChannel(grp + CH_RANDOM_START_DELAY_HEAT, EcobeeUtils.undefOrDecimal(settings.randomStartDelayHeat));
524         updateChannel(grp + CH_HUMIDITY_HIGH_ALERT,
525                 EcobeeUtils.undefOrQuantity(settings.humidityHighAlert, Units.PERCENT));
526         updateChannel(grp + CH_HUMIDITY_LOW_ALERT,
527                 EcobeeUtils.undefOrQuantity(settings.humidityLowAlert, Units.PERCENT));
528         updateChannel(grp + CH_DISABLE_HEAT_PUMP_ALERTS, EcobeeUtils.undefOrOnOff(settings.disableHeatPumpAlerts));
529         updateChannel(grp + CH_DISABLE_ALERTS_ON_IDT, EcobeeUtils.undefOrOnOff(settings.disableAlertsOnIdt));
530         updateChannel(grp + CH_HUMIDITY_ALERT_NOTIFY, EcobeeUtils.undefOrOnOff(settings.humidityAlertNotify));
531         updateChannel(grp + CH_HUMIDITY_ALERT_NOTIFY_TECHNICIAN,
532                 EcobeeUtils.undefOrOnOff(settings.humidityAlertNotifyTechnician));
533         updateChannel(grp + CH_TEMP_ALERT_NOTIFY, EcobeeUtils.undefOrOnOff(settings.tempAlertNotify));
534         updateChannel(grp + CH_TEMP_ALERT_NOTIFY_TECHNICIAN,
535                 EcobeeUtils.undefOrOnOff(settings.tempAlertNotifyTechnician));
536         updateChannel(grp + CH_MONTHLY_ELECTRICITY_BILL_LIMIT,
537                 EcobeeUtils.undefOrDecimal(settings.monthlyElectricityBillLimit));
538         updateChannel(grp + CH_ENABLE_ELECTRICITY_BILL_ALERT,
539                 EcobeeUtils.undefOrOnOff(settings.enableElectricityBillAlert));
540         updateChannel(grp + CH_ENABLE_PROJECTED_ELECTRICITY_BILL_ALERT,
541                 EcobeeUtils.undefOrOnOff(settings.enableProjectedElectricityBillAlert));
542         updateChannel(grp + CH_ELECTRICITY_BILLING_DAY_OF_MONTH,
543                 EcobeeUtils.undefOrDecimal(settings.electricityBillingDayOfMonth));
544         updateChannel(grp + CH_ELECTRICITY_BILL_CYCLE_MONTHS,
545                 EcobeeUtils.undefOrDecimal(settings.electricityBillCycleMonths));
546         updateChannel(grp + CH_ELECTRICITY_BILL_START_MONTH,
547                 EcobeeUtils.undefOrDecimal(settings.electricityBillStartMonth));
548         updateChannel(grp + CH_VENTILATOR_MIN_ON_TIME_HOME,
549                 EcobeeUtils.undefOrDecimal(settings.ventilatorMinOnTimeHome));
550         updateChannel(grp + CH_VENTILATOR_MIN_ON_TIME_AWAY,
551                 EcobeeUtils.undefOrDecimal(settings.ventilatorMinOnTimeAway));
552         updateChannel(grp + CH_BACKLIGHT_OFF_DURING_SLEEP, EcobeeUtils.undefOrOnOff(settings.backlightOffDuringSleep));
553         updateChannel(grp + CH_AUTO_AWAY, EcobeeUtils.undefOrOnOff(settings.autoAway));
554         updateChannel(grp + CH_SMART_CIRCULATION, EcobeeUtils.undefOrOnOff(settings.smartCirculation));
555         updateChannel(grp + CH_FOLLOW_ME_COMFORT, EcobeeUtils.undefOrOnOff(settings.followMeComfort));
556         updateChannel(grp + CH_VENTILATOR_TYPE, EcobeeUtils.undefOrString(settings.ventilatorType));
557         updateChannel(grp + CH_IS_VENTILATOR_TIMER_ON, EcobeeUtils.undefOrOnOff(settings.isVentilatorTimerOn));
558         updateChannel(grp + CH_VENTILATOR_OFF_DATE_TIME, EcobeeUtils.undefOrString(settings.ventilatorOffDateTime));
559         updateChannel(grp + CH_HAS_UV_FILTER, EcobeeUtils.undefOrOnOff(settings.hasUVFilter));
560         updateChannel(grp + CH_COOLING_LOCKOUT, EcobeeUtils.undefOrOnOff(settings.coolingLockout));
561         updateChannel(grp + CH_VENTILATOR_FREE_COOLING, EcobeeUtils.undefOrOnOff(settings.ventilatorFreeCooling));
562         updateChannel(grp + CH_DEHUMIDIFY_WHEN_HEATING, EcobeeUtils.undefOrOnOff(settings.dehumidifyWhenHeating));
563         updateChannel(grp + CH_VENTILATOR_DEHUMIDIFY, EcobeeUtils.undefOrOnOff(settings.ventilatorDehumidify));
564         updateChannel(grp + CH_GROUP_REF, EcobeeUtils.undefOrString(settings.groupRef));
565         updateChannel(grp + CH_GROUP_NAME, EcobeeUtils.undefOrString(settings.groupName));
566         updateChannel(grp + CH_GROUP_SETTING, EcobeeUtils.undefOrDecimal(settings.groupSetting));
567     }
568
569     private void updateProgram(@Nullable ProgramDTO program) {
570         if (program == null) {
571             return;
572         }
573         final String grp = CHGRP_PROGRAM + "#";
574         updateChannel(grp + CH_PROGRAM_CURRENT_CLIMATE_REF, EcobeeUtils.undefOrString(program.currentClimateRef));
575         if (program.climates != null) {
576             saveValidClimateRefs(program.climates);
577         }
578     }
579
580     private void saveValidClimateRefs(List<ClimateDTO> climates) {
581         validClimateRefs.clear();
582         for (ClimateDTO climate : climates) {
583             validClimateRefs.add(climate.climateRef);
584         }
585     }
586
587     private void updateAlert(@Nullable List<AlertDTO> alerts) {
588         AlertDTO firstAlert;
589         if (alerts == null || alerts.isEmpty()) {
590             firstAlert = EMPTY_ALERT;
591         } else {
592             firstAlert = alerts.get(0);
593         }
594         final String grp = CHGRP_ALERT + "#";
595         updateChannel(grp + CH_ALERT_ACKNOWLEDGE_REF, EcobeeUtils.undefOrString(firstAlert.acknowledgeRef));
596         updateChannel(grp + CH_ALERT_DATE, EcobeeUtils.undefOrString(firstAlert.date));
597         updateChannel(grp + CH_ALERT_TIME, EcobeeUtils.undefOrString(firstAlert.time));
598         updateChannel(grp + CH_ALERT_SEVERITY, EcobeeUtils.undefOrString(firstAlert.severity));
599         updateChannel(grp + CH_ALERT_TEXT, EcobeeUtils.undefOrString(firstAlert.text));
600         updateChannel(grp + CH_ALERT_ALERT_NUMBER, EcobeeUtils.undefOrDecimal(firstAlert.alertNumber));
601         updateChannel(grp + CH_ALERT_ALERT_TYPE, EcobeeUtils.undefOrString(firstAlert.alertType));
602         updateChannel(grp + CH_ALERT_IS_OPERATOR_ALERT, EcobeeUtils.undefOrOnOff(firstAlert.isOperatorAlert));
603         updateChannel(grp + CH_ALERT_REMINDER, EcobeeUtils.undefOrString(firstAlert.reminder));
604         updateChannel(grp + CH_ALERT_SHOW_IDT, EcobeeUtils.undefOrOnOff(firstAlert.showIdt));
605         updateChannel(grp + CH_ALERT_SHOW_WEB, EcobeeUtils.undefOrOnOff(firstAlert.showWeb));
606         updateChannel(grp + CH_ALERT_SEND_EMAIL, EcobeeUtils.undefOrOnOff(firstAlert.sendEmail));
607         updateChannel(grp + CH_ALERT_ACKNOWLEDGEMENT, EcobeeUtils.undefOrString(firstAlert.acknowledgement));
608         updateChannel(grp + CH_ALERT_REMIND_ME_LATER, EcobeeUtils.undefOrOnOff(firstAlert.remindMeLater));
609         updateChannel(grp + CH_ALERT_THERMOSTAT_IDENTIFIER, EcobeeUtils.undefOrString(firstAlert.thermostatIdentifier));
610         updateChannel(grp + CH_ALERT_NOTIFICATION_TYPE, EcobeeUtils.undefOrString(firstAlert.notificationType));
611     }
612
613     private void updateEvent(@Nullable List<EventDTO> events) {
614         EventDTO runningEvent = EMPTY_EVENT;
615         if (events != null && !events.isEmpty()) {
616             for (EventDTO event : events) {
617                 if (event.running) {
618                     runningEvent = event;
619                     break;
620                 }
621             }
622         }
623         final String grp = CHGRP_EVENT + "#";
624         updateChannel(grp + CH_EVENT_NAME, EcobeeUtils.undefOrString(runningEvent.name));
625         updateChannel(grp + CH_EVENT_TYPE, EcobeeUtils.undefOrString(runningEvent.type));
626         updateChannel(grp + CH_EVENT_RUNNING, EcobeeUtils.undefOrOnOff(runningEvent.running));
627         updateChannel(grp + CH_EVENT_START_DATE, EcobeeUtils.undefOrString(runningEvent.startDate));
628         updateChannel(grp + CH_EVENT_START_TIME, EcobeeUtils.undefOrString(runningEvent.startTime));
629         updateChannel(grp + CH_EVENT_END_DATE, EcobeeUtils.undefOrString(runningEvent.endDate));
630         updateChannel(grp + CH_EVENT_END_TIME, EcobeeUtils.undefOrString(runningEvent.endTime));
631         updateChannel(grp + CH_EVENT_IS_OCCUPIED, EcobeeUtils.undefOrOnOff(runningEvent.isOccupied));
632         updateChannel(grp + CH_EVENT_IS_COOL_OFF, EcobeeUtils.undefOrOnOff(runningEvent.isCoolOff));
633         updateChannel(grp + CH_EVENT_IS_HEAT_OFF, EcobeeUtils.undefOrOnOff(runningEvent.isHeatOff));
634         updateChannel(grp + CH_EVENT_COOL_HOLD_TEMP, EcobeeUtils.undefOrTemperature(runningEvent.coolHoldTemp));
635         updateChannel(grp + CH_EVENT_HEAT_HOLD_TEMP, EcobeeUtils.undefOrTemperature(runningEvent.heatHoldTemp));
636         updateChannel(grp + CH_EVENT_FAN, EcobeeUtils.undefOrString(runningEvent.fan));
637         updateChannel(grp + CH_EVENT_VENT, EcobeeUtils.undefOrString(runningEvent.vent));
638         updateChannel(grp + CH_EVENT_VENTILATOR_MIN_ON_TIME,
639                 EcobeeUtils.undefOrDecimal(runningEvent.ventilatorMinOnTime));
640         updateChannel(grp + CH_EVENT_IS_OPTIONAL, EcobeeUtils.undefOrOnOff(runningEvent.isOptional));
641         updateChannel(grp + CH_EVENT_IS_TEMPERATURE_RELATIVE,
642                 EcobeeUtils.undefOrOnOff(runningEvent.isTemperatureRelative));
643         updateChannel(grp + CH_EVENT_COOL_RELATIVE_TEMP, EcobeeUtils.undefOrDecimal(runningEvent.coolRelativeTemp));
644         updateChannel(grp + CH_EVENT_HEAT_RELATIVE_TEMP, EcobeeUtils.undefOrDecimal(runningEvent.heatRelativeTemp));
645         updateChannel(grp + CH_EVENT_IS_TEMPERATURE_ABSOLUTE,
646                 EcobeeUtils.undefOrOnOff(runningEvent.isTemperatureAbsolute));
647         updateChannel(grp + CH_EVENT_DUTY_CYCLE_PERCENTAGE,
648                 EcobeeUtils.undefOrDecimal(runningEvent.dutyCyclePercentage));
649         updateChannel(grp + CH_EVENT_FAN_MIN_ON_TIME, EcobeeUtils.undefOrDecimal(runningEvent.fanMinOnTime));
650         updateChannel(grp + CH_EVENT_OCCUPIED_SENSOR_ACTIVE,
651                 EcobeeUtils.undefOrOnOff(runningEvent.occupiedSensorActive));
652         updateChannel(grp + CH_EVENT_UNOCCUPIED_SENSOR_ACTIVE,
653                 EcobeeUtils.undefOrOnOff(runningEvent.unoccupiedSensorActive));
654         updateChannel(grp + CH_EVENT_DR_RAMP_UP_TEMP, EcobeeUtils.undefOrDecimal(runningEvent.drRampUpTemp));
655         updateChannel(grp + CH_EVENT_DR_RAMP_UP_TIME, EcobeeUtils.undefOrDecimal(runningEvent.drRampUpTime));
656         updateChannel(grp + CH_EVENT_LINK_REF, EcobeeUtils.undefOrString(runningEvent.linkRef));
657         updateChannel(grp + CH_EVENT_HOLD_CLIMATE_REF, EcobeeUtils.undefOrString(runningEvent.holdClimateRef));
658     }
659
660     private void updateWeather(@Nullable WeatherDTO weather) {
661         if (weather == null || weather.forecasts == null) {
662             return;
663         }
664         final String weatherGrp = CHGRP_WEATHER + "#";
665
666         updateChannel(weatherGrp + CH_WEATHER_TIMESTAMP, EcobeeUtils.undefOrDate(weather.timestamp, timeZoneProvider));
667         updateChannel(weatherGrp + CH_WEATHER_WEATHER_STATION, EcobeeUtils.undefOrString(weather.weatherStation));
668
669         for (int index = 0; index < weather.forecasts.size(); index++) {
670             final String grp = CHGRP_FORECAST + String.format("%d", index) + "#";
671             WeatherForecastDTO forecast = weather.forecasts.get(index);
672             if (forecast != null) {
673                 updateChannel(grp + CH_FORECAST_WEATHER_SYMBOL, EcobeeUtils.undefOrDecimal(forecast.weatherSymbol));
674                 updateChannel(grp + CH_FORECAST_WEATHER_SYMBOL_TEXT,
675                         EcobeeUtils.undefOrString(symbolMap.get(forecast.weatherSymbol)));
676                 updateChannel(grp + CH_FORECAST_DATE_TIME,
677                         EcobeeUtils.undefOrDate(forecast.dateTime, timeZoneProvider));
678                 updateChannel(grp + CH_FORECAST_CONDITION, EcobeeUtils.undefOrString(forecast.condition));
679                 updateChannel(grp + CH_FORECAST_TEMPERATURE, EcobeeUtils.undefOrTemperature(forecast.temperature));
680                 updateChannel(grp + CH_FORECAST_PRESSURE,
681                         EcobeeUtils.undefOrQuantity(forecast.pressure, Units.MILLIBAR));
682                 updateChannel(grp + CH_FORECAST_RELATIVE_HUMIDITY,
683                         EcobeeUtils.undefOrQuantity(forecast.relativeHumidity, Units.PERCENT));
684                 updateChannel(grp + CH_FORECAST_DEWPOINT, EcobeeUtils.undefOrTemperature(forecast.dewpoint));
685                 updateChannel(grp + CH_FORECAST_VISIBILITY,
686                         EcobeeUtils.undefOrQuantity(forecast.visibility, SIUnits.METRE));
687                 updateChannel(grp + CH_FORECAST_WIND_SPEED,
688                         EcobeeUtils.undefOrQuantity(forecast.windSpeed, ImperialUnits.MILES_PER_HOUR));
689                 updateChannel(grp + CH_FORECAST_WIND_GUST,
690                         EcobeeUtils.undefOrQuantity(forecast.windGust, ImperialUnits.MILES_PER_HOUR));
691                 updateChannel(grp + CH_FORECAST_WIND_DIRECTION, EcobeeUtils.undefOrString(forecast.windDirection));
692                 updateChannel(grp + CH_FORECAST_WIND_BEARING,
693                         EcobeeUtils.undefOrQuantity(forecast.windBearing, Units.DEGREE_ANGLE));
694                 updateChannel(grp + CH_FORECAST_POP, EcobeeUtils.undefOrQuantity(forecast.pop, Units.PERCENT));
695                 updateChannel(grp + CH_FORECAST_TEMP_HIGH, EcobeeUtils.undefOrTemperature(forecast.tempHigh));
696                 updateChannel(grp + CH_FORECAST_TEMP_LOW, EcobeeUtils.undefOrTemperature(forecast.tempLow));
697                 updateChannel(grp + CH_FORECAST_SKY, EcobeeUtils.undefOrDecimal(forecast.sky));
698                 updateChannel(grp + CH_FORECAST_SKY_TEXT, EcobeeUtils.undefOrString(skyMap.get(forecast.sky)));
699             }
700         }
701     }
702
703     private void updateVersion(@Nullable VersionDTO version) {
704         if (version == null) {
705             return;
706         }
707         final String grp = CHGRP_VERSION + "#";
708         updateChannel(grp + CH_THERMOSTAT_FIRMWARE_VERSION,
709                 EcobeeUtils.undefOrString(version.thermostatFirmwareVersion));
710     }
711
712     private void updateLocation(@Nullable LocationDTO loc) {
713         LocationDTO location = EMPTY_LOCATION;
714         if (loc != null) {
715             location = loc;
716         }
717         final String grp = CHGRP_LOCATION + "#";
718         updateChannel(grp + CH_TIME_ZONE_OFFSET_MINUTES, EcobeeUtils.undefOrDecimal(location.timeZoneOffsetMinutes));
719         updateChannel(grp + CH_TIME_ZONE, EcobeeUtils.undefOrString(location.timeZone));
720         updateChannel(grp + CH_IS_DAYLIGHT_SAVING, EcobeeUtils.undefOrOnOff(location.isDaylightSaving));
721         updateChannel(grp + CH_STREET_ADDRESS, EcobeeUtils.undefOrString(location.streetAddress));
722         updateChannel(grp + CH_CITY, EcobeeUtils.undefOrString(location.city));
723         updateChannel(grp + CH_PROVINCE_STATE, EcobeeUtils.undefOrString(location.provinceState));
724         updateChannel(grp + CH_COUNTRY, EcobeeUtils.undefOrString(location.country));
725         updateChannel(grp + CH_POSTAL_CODE, EcobeeUtils.undefOrString(location.postalCode));
726         updateChannel(grp + CH_PHONE_NUMBER, EcobeeUtils.undefOrString(location.phoneNumber));
727         updateChannel(grp + CH_MAP_COORDINATES, EcobeeUtils.undefOrPoint(location.mapCoordinates));
728     }
729
730     private void updateHouseDetails(@Nullable HouseDetailsDTO hd) {
731         HouseDetailsDTO houseDetails = EMPTY_HOUSEDETAILS;
732         if (hd != null) {
733             houseDetails = hd;
734         }
735         final String grp = CHGRP_HOUSE_DETAILS + "#";
736         updateChannel(grp + CH_HOUSEDETAILS_STYLE, EcobeeUtils.undefOrString(houseDetails.style));
737         updateChannel(grp + CH_HOUSEDETAILS_SIZE, EcobeeUtils.undefOrDecimal(houseDetails.size));
738         updateChannel(grp + CH_HOUSEDETAILS_NUMBER_OF_FLOORS, EcobeeUtils.undefOrDecimal(houseDetails.numberOfFloors));
739         updateChannel(grp + CH_HOUSEDETAILS_NUMBER_OF_ROOMS, EcobeeUtils.undefOrDecimal(houseDetails.numberOfRooms));
740         updateChannel(grp + CH_HOUSEDETAILS_NUMBER_OF_OCCUPANTS,
741                 EcobeeUtils.undefOrDecimal(houseDetails.numberOfOccupants));
742         updateChannel(grp + CH_HOUSEDETAILS_AGE, EcobeeUtils.undefOrDecimal(houseDetails.age));
743         updateChannel(grp + CH_HOUSEDETAILS_WINDOW_EFFICIENCY,
744                 EcobeeUtils.undefOrDecimal(houseDetails.windowEfficiency));
745     }
746
747     private void updateManagement(@Nullable ManagementDTO mgmt) {
748         ManagementDTO management = EMPTY_MANAGEMENT;
749         if (mgmt != null) {
750             management = mgmt;
751         }
752         final String grp = CHGRP_MANAGEMENT + "#";
753         updateChannel(grp + CH_MANAGEMENT_ADMIN_CONTACT, EcobeeUtils.undefOrString(management.administrativeContact));
754         updateChannel(grp + CH_MANAGEMENT_BILLING_CONTACT, EcobeeUtils.undefOrString(management.billingContact));
755         updateChannel(grp + CH_MANAGEMENT_NAME, EcobeeUtils.undefOrString(management.name));
756         updateChannel(grp + CH_MANAGEMENT_PHONE, EcobeeUtils.undefOrString(management.phone));
757         updateChannel(grp + CH_MANAGEMENT_EMAIL, EcobeeUtils.undefOrString(management.email));
758         updateChannel(grp + CH_MANAGEMENT_WEB, EcobeeUtils.undefOrString(management.web));
759         updateChannel(grp + CH_MANAGEMENT_SHOW_ALERT_IDT, EcobeeUtils.undefOrOnOff(management.showAlertIdt));
760         updateChannel(grp + CH_MANAGEMENT_SHOW_ALERT_WEB, EcobeeUtils.undefOrOnOff(management.showAlertWeb));
761     }
762
763     private void updateTechnician(@Nullable TechnicianDTO tech) {
764         TechnicianDTO technician = EMPTY_TECHNICIAN;
765         if (tech != null) {
766             technician = tech;
767         }
768         final String grp = CHGRP_TECHNICIAN + "#";
769         updateChannel(grp + CH_TECHNICIAN_CONTRACTOR_REF, EcobeeUtils.undefOrString(technician.contractorRef));
770         updateChannel(grp + CH_TECHNICIAN_NAME, EcobeeUtils.undefOrString(technician.name));
771         updateChannel(grp + CH_TECHNICIAN_PHONE, EcobeeUtils.undefOrString(technician.phone));
772         updateChannel(grp + CH_TECHNICIAN_STREET_ADDRESS, EcobeeUtils.undefOrString(technician.streetAddress));
773         updateChannel(grp + CH_TECHNICIAN_CITY, EcobeeUtils.undefOrString(technician.city));
774         updateChannel(grp + CH_TECHNICIAN_PROVINCE_STATE, EcobeeUtils.undefOrString(technician.provinceState));
775         updateChannel(grp + CH_TECHNICIAN_COUNTRY, EcobeeUtils.undefOrString(technician.country));
776         updateChannel(grp + CH_TECHNICIAN_POSTAL_CODE, EcobeeUtils.undefOrString(technician.postalCode));
777         updateChannel(grp + CH_TECHNICIAN_EMAIL, EcobeeUtils.undefOrString(technician.email));
778         updateChannel(grp + CH_TECHNICIAN_WEB, EcobeeUtils.undefOrString(technician.web));
779     }
780
781     private void updateChannel(String channelId, State state) {
782         updateState(channelId, state);
783         stateCache.put(channelId, state);
784     }
785
786     @SuppressWarnings("null")
787     private void updateRemoteSensors(@Nullable List<RemoteSensorDTO> remoteSensors) {
788         if (remoteSensors == null) {
789             return;
790         }
791         logger.debug("ThermostatBridge: Thermostat '{}' has {} remote sensors", thermostatId, remoteSensors.size());
792         for (RemoteSensorDTO sensor : remoteSensors) {
793             EcobeeSensorThingHandler handler = sensorHandlers.get(sensor.id);
794             if (handler != null) {
795                 logger.debug("ThermostatBridge: Sending data to sensor handler '{}({})' of type '{}'", sensor.id,
796                         sensor.name, sensor.type);
797                 handler.updateChannels(sensor);
798             }
799         }
800     }
801
802     private void performThermostatUpdate(ThermostatDTO thermostat) {
803         SelectionDTO selection = new SelectionDTO();
804         selection.setThermostats(Collections.singleton(thermostatId));
805         ThermostatUpdateRequestDTO request = new ThermostatUpdateRequestDTO(selection);
806         request.thermostat = thermostat;
807         EcobeeAccountBridgeHandler handler = getBridgeHandler();
808         if (handler != null) {
809             handler.performThermostatUpdate(request);
810         }
811     }
812
813     private @Nullable EcobeeAccountBridgeHandler getBridgeHandler() {
814         EcobeeAccountBridgeHandler handler = null;
815         Bridge bridge = getBridge();
816         if (bridge != null) {
817             handler = (EcobeeAccountBridgeHandler) bridge.getHandler();
818         }
819         return handler;
820     }
821
822     @SuppressWarnings("null")
823     private boolean isChannelReadOnly(ChannelUID channelUID) {
824         Boolean isReadOnly = channelReadOnlyMap.get(channelUID);
825         return isReadOnly != null ? isReadOnly : true;
826     }
827
828     private void clearSavedState() {
829         savedThermostat = null;
830         savedSensors = null;
831         stateCache.clear();
832     }
833
834     private void initializeReadOnlyChannels() {
835         channelReadOnlyMap.clear();
836         for (Channel channel : thing.getChannels()) {
837             ChannelTypeUID channelTypeUID = channel.getChannelTypeUID();
838             if (channelTypeUID != null) {
839                 ChannelType channelType = channelTypeRegistry.getChannelType(channelTypeUID, null);
840                 if (channelType != null) {
841                     channelReadOnlyMap.putIfAbsent(channel.getUID(), channelType.getState().isReadOnly());
842                 }
843             }
844         }
845     }
846
847     private void initializeWeatherMaps() {
848         initializeSymbolMap();
849         initializeSkyMap();
850     }
851
852     private void initializeSymbolMap() {
853         symbolMap.clear();
854         symbolMap.put(-2, "NO SYMBOL");
855         symbolMap.put(0, "SUNNY");
856         symbolMap.put(1, "FEW CLOUDS");
857         symbolMap.put(2, "PARTLY CLOUDY");
858         symbolMap.put(3, "MOSTLY CLOUDY");
859         symbolMap.put(4, "OVERCAST");
860         symbolMap.put(5, "DRIZZLE");
861         symbolMap.put(6, "RAIN");
862         symbolMap.put(7, "FREEZING RAIN");
863         symbolMap.put(8, "SHOWERS");
864         symbolMap.put(9, "HAIL");
865         symbolMap.put(10, "SNOW");
866         symbolMap.put(11, "FLURRIES");
867         symbolMap.put(12, "FREEZING SNOW");
868         symbolMap.put(13, "BLIZZARD");
869         symbolMap.put(14, "PELLETS");
870         symbolMap.put(15, "THUNDERSTORM");
871         symbolMap.put(16, "WINDY");
872         symbolMap.put(17, "TORNADO");
873         symbolMap.put(18, "FOG");
874         symbolMap.put(19, "HAZE");
875         symbolMap.put(20, "SMOKE");
876         symbolMap.put(21, "DUST");
877     }
878
879     private void initializeSkyMap() {
880         skyMap.clear();
881         skyMap.put(1, "SUNNY");
882         skyMap.put(2, "CLEAR");
883         skyMap.put(3, "MOSTLY SUNNY");
884         skyMap.put(4, "MOSTLY CLEAR");
885         skyMap.put(5, "HAZY SUNSHINE");
886         skyMap.put(6, "HAZE");
887         skyMap.put(7, "PASSING CLOUDS");
888         skyMap.put(8, "MORE SUN THAN CLOUDS");
889         skyMap.put(9, "SCATTERED CLOUDS");
890         skyMap.put(10, "PARTLY CLOUDY");
891         skyMap.put(11, "A MIXTURE OF SUN AND CLOUDS");
892         skyMap.put(12, "HIGH LEVEL CLOUDS");
893         skyMap.put(13, "MORE CLOUDS THAN SUN");
894         skyMap.put(14, "PARTLY SUNNY");
895         skyMap.put(15, "BROKEN CLOUDS");
896         skyMap.put(16, "MOSTLY CLOUDY");
897         skyMap.put(17, "CLOUDY");
898         skyMap.put(18, "OVERCAST");
899         skyMap.put(19, "LOW CLOUDS");
900         skyMap.put(20, "LIGHT FOG");
901         skyMap.put(21, "FOG");
902         skyMap.put(22, "DENSE FOG");
903         skyMap.put(23, "ICE FOG");
904         skyMap.put(24, "SANDSTORM");
905         skyMap.put(25, "DUSTSTORM");
906         skyMap.put(26, "INCREASING CLOUDINESS");
907         skyMap.put(27, "DECREASING CLOUDINESS");
908         skyMap.put(28, "CLEARING SKIES");
909         skyMap.put(29, "BREAKS OF SUN LATE");
910         skyMap.put(30, "EARLY FOG FOLLOWED BY SUNNY SKIES");
911         skyMap.put(31, "AFTERNOON CLOUDS");
912         skyMap.put(32, "MORNING CLOUDS");
913         skyMap.put(33, "SMOKE");
914         skyMap.put(34, "LOW LEVEL HAZE");
915     }
916 }