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