Skip to content

Commit 19f1ad6

Browse files
authored
Merge pull request #441 from ColtHub/feature/low-voltage-thermostat-support
feat: support low voltage (24 V) thermostats
2 parents 3512d2b + a9cd236 commit 19f1ad6

6 files changed

Lines changed: 548 additions & 2 deletions

File tree

‎pyhilo/api.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -591,6 +591,18 @@ async def _set_device_attribute(
591591
LOG.debug("Device Attribute URL is %s", url)
592592
await self.async_request("put", url, json={key.hilo_attribute: value})
593593

594+
async def _set_device_attributes(
595+
self,
596+
device: HiloDevice,
597+
attributes: dict[str, Union[str, float, int, None]],
598+
) -> None:
599+
"""Sets several device attributes in a single request."""
600+
url = self._get_url(
601+
f"Devices/{device.id}/Attributes", location_id=device.location_id
602+
)
603+
LOG.debug("Device Attributes URL is %s", url)
604+
await self.async_request("put", url, json=attributes)
605+
594606
async def get_event_notifications(self, location_id: int) -> dict[str, Any]:
595607
"""This will return events notifications
596608
Event types:

‎pyhilo/const.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,15 +219,21 @@
219219
"BatteryPercent": "Percentage",
220220
"Co2": "PPM",
221221
"ColorTemperature": "Integer",
222+
"CoolTemperatureSet": "Celsius",
223+
"CurrentState": "null",
222224
"CurrentTemperature": "Celsius",
223225
"Disconnected": "null",
224226
"DrmsState": "OnOff",
227+
"FanMode": "null",
228+
"FanSpeed": "null",
225229
"firmwareVersion": "null",
226230
"Heating": "Percentage",
227231
"Hue": "Integer",
228232
"Humidity": "Percentage",
229233
"Intensity": "Percentage",
234+
"MaxCoolSetpoint": "Celsius",
230235
"MaxTempSetpoint": "Celsius",
236+
"MinCoolSetpoint": "Celsius",
231237
"MinTempSetpoint": "Celsius",
232238
"Noise": "DB",
233239
"onlineStatus": "null",
@@ -237,6 +243,9 @@
237243
"Saturation": "Integer",
238244
"Status": "OnOff",
239245
"TargetTemperature": "Celsius",
246+
"Thermostat24VAllowedFanMode": "null",
247+
"Thermostat24VAllowedMode": "null",
248+
"Thermostat24VMode": "null",
240249
"Unpaired": "null",
241250
"WifiStatus": "Integer",
242251
"zigBeePairingActivated": "OnOff",

‎pyhilo/device/__init__.py‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,40 @@ async def _set_attribute(
136136
else:
137137
LOG.warning("%s Invalid attribute %s for device", self._tag, attribute)
138138

139+
async def set_attributes(
140+
self, attributes: Dict[str, Union[str, int, float, None]]
141+
) -> None:
142+
"""Send several attributes to the device in a single request.
143+
144+
Some devices reject partial writes: 24 V thermostats require the mode
145+
and both setpoints to be sent together, even when only one of them
146+
changed.
147+
148+
This differs from set_attribute() on two deliberate points:
149+
150+
- it does not check settable_attributes. Hilo advertises only
151+
['Disconnected'] as settable on those thermostats, while the API does
152+
accept and apply the write.
153+
- it does not update the readings optimistically. The new values come
154+
back through the normal read path, which makes a read-back an actual
155+
confirmation rather than an echo.
156+
"""
157+
payload: Dict[str, Union[str, int, float, None]] = {}
158+
for attribute, value in attributes.items():
159+
dev_attribute = self._api.dev_atts(attribute)
160+
if not isinstance(dev_attribute, DeviceAttribute):
161+
LOG.warning(
162+
"%s Unable to set attribute %s: Unknown attribute",
163+
self._tag,
164+
attribute,
165+
)
166+
continue
167+
payload[dev_attribute.hilo_attribute] = value
168+
if not payload:
169+
return
170+
LOG.debug("%s Setting attributes %s", self._tag, payload)
171+
await self._api._set_device_attributes(self, payload)
172+
139173
def get_attribute(self, attribute: str) -> Union[DeviceReading, None]:
140174
if dev_attribute := cast(DeviceAttribute, self._api.dev_atts(attribute)):
141175
return self._get_attribute(dev_attribute)

‎pyhilo/device/climate.py‎

Lines changed: 148 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,29 @@
55
from typing import Any, cast
66

77
from pyhilo import API
8-
from pyhilo.const import LOG
8+
from pyhilo.const import LOG, STATE_UNKNOWN
99
from pyhilo.device import HiloDevice
1010

11+
# Attributes reported only by low voltage (24 V) thermostats. Thermostat24VMode
12+
# is emitted solely by GraphqlValueMapper._build_lowvoltage_thermostat(), which
13+
# makes its presence an exact discriminator.
14+
LOW_VOLTAGE_MODE = "thermostat24_v_mode"
15+
LOW_VOLTAGE_ALLOWED_MODES = "thermostat24_v_allowed_mode"
16+
LOW_VOLTAGE_ALLOWED_FAN_MODES = "thermostat24_v_allowed_fan_mode"
17+
18+
19+
def as_list(value: Any) -> list[str]:
20+
"""Return a list of strings from a Hilo list attribute.
21+
22+
Hilo sends those either as a real list or as a comma separated string
23+
depending on the transport, so accept both.
24+
"""
25+
if value is None or value in ("", STATE_UNKNOWN):
26+
return []
27+
if isinstance(value, (list, tuple, set)):
28+
return [str(v).strip() for v in value if str(v).strip()]
29+
return [v.strip() for v in str(value).split(",") if v.strip()]
30+
1131

1232
class Climate(HiloDevice):
1333
"""
@@ -95,6 +115,133 @@ async def async_set_temperature(self, temperature: float) -> None:
95115
Args:
96116
temperature: The desired target temperature.
97117
"""
118+
if self.is_low_voltage:
119+
await self.async_set_low_voltage_state(target_temperature=temperature)
120+
return
98121
if temperature != self.target_temperature:
99122
LOG.info("%s Setting temperature to %s", self._tag, temperature)
100123
await self.set_attribute("target_temperature", str(temperature))
124+
125+
def _optional_float(self, attribute: str) -> float | None:
126+
"""Return a numeric reading, or None when absent or unusable."""
127+
value = self.get_value(attribute, None)
128+
if value is None or value == STATE_UNKNOWN:
129+
return None
130+
try:
131+
return float(value)
132+
except (TypeError, ValueError):
133+
return None
134+
135+
def _optional_str(self, attribute: str) -> str | None:
136+
"""Return a textual reading, or None when absent or unusable."""
137+
value = self.get_value(attribute, None)
138+
if value is None or value == STATE_UNKNOWN:
139+
return None
140+
return str(value)
141+
142+
@property
143+
def is_low_voltage(self) -> bool:
144+
"""Whether this is a low voltage (24 V) thermostat.
145+
146+
Baseboard thermostats report none of the 24 V attributes and therefore
147+
keep their heat-only behaviour.
148+
"""
149+
return self.low_voltage_mode is not None
150+
151+
@property
152+
def low_voltage_mode(self) -> str | None:
153+
"""Operating mode reported by a 24 V thermostat, in Hilo's vocabulary."""
154+
return self._optional_str(LOW_VOLTAGE_MODE)
155+
156+
@property
157+
def allowed_modes(self) -> list[str]:
158+
"""Mode vocabulary advertised by a 24 V thermostat."""
159+
return as_list(self.get_value(LOW_VOLTAGE_ALLOWED_MODES, None))
160+
161+
@property
162+
def fan_mode(self) -> str | None:
163+
"""Current fan mode, when the device reports one."""
164+
return self._optional_str("fan_mode")
165+
166+
@property
167+
def allowed_fan_modes(self) -> list[str]:
168+
"""Fan mode vocabulary advertised by a 24 V thermostat."""
169+
return as_list(self.get_value(LOW_VOLTAGE_ALLOWED_FAN_MODES, None))
170+
171+
@property
172+
def current_state(self) -> str | None:
173+
"""Raw running state reported by a 24 V thermostat.
174+
175+
Exposed for consumers, but deliberately not mapped to hvac_action yet:
176+
its vocabulary has not been observed in enough operating conditions.
177+
"""
178+
return self._optional_str("current_state")
179+
180+
@property
181+
def cool_setpoint(self) -> float | None:
182+
"""Cooling setpoint of a 24 V thermostat."""
183+
return self._optional_float("cool_temperature_set")
184+
185+
@property
186+
def min_cool_setpoint(self) -> float | None:
187+
"""Lowest cooling setpoint allowed by a 24 V thermostat."""
188+
return self._optional_float("min_cool_setpoint")
189+
190+
@property
191+
def max_cool_setpoint(self) -> float | None:
192+
"""Highest cooling setpoint allowed by a 24 V thermostat."""
193+
return self._optional_float("max_cool_setpoint")
194+
195+
@property
196+
def current_humidity(self) -> int | None:
197+
"""Ambient humidity, rounded to the nearest percent.
198+
199+
GraphqlValueMapper reports 0 for a device without a humidity sensor,
200+
not None, so a reading of 0 is a real (if degenerate) value rather
201+
than an absent one.
202+
"""
203+
value = self._optional_float("humidity")
204+
return None if value is None else round(value)
205+
206+
async def async_set_low_voltage_state(
207+
self,
208+
mode: str | None = None,
209+
target_temperature: float | None = None,
210+
cool_setpoint: float | None = None,
211+
fan_mode: str | None = None,
212+
) -> None:
213+
"""Write the mode and both setpoints together.
214+
215+
24 V thermostats reject partial writes: the mode and both setpoints
216+
have to be sent in one request even when only one of them changed.
217+
Arguments left out keep their current value; values the device does
218+
not report at all are omitted from the payload.
219+
220+
Raises:
221+
ValueError: The mode isn't given and the device hasn't reported
222+
one either. Silently dropping Thermostat24VMode from the
223+
payload in that case would send setpoints without a mode,
224+
exactly the partial write this method exists to prevent.
225+
"""
226+
resolved_mode = mode if mode is not None else self.low_voltage_mode
227+
if resolved_mode is None:
228+
raise ValueError(
229+
f"{self._tag} Cannot set low voltage state: no mode was given "
230+
"and the device has not reported one. Pass mode explicitly."
231+
)
232+
payload: dict[str, str | int | float | None] = {
233+
"Thermostat24VMode": resolved_mode,
234+
"TargetTemperature": (
235+
target_temperature
236+
if target_temperature is not None
237+
else self._optional_float("target_temperature")
238+
),
239+
"CoolTemperatureSet": (
240+
cool_setpoint if cool_setpoint is not None else self.cool_setpoint
241+
),
242+
}
243+
if fan_mode is not None:
244+
payload["FanMode"] = fan_mode
245+
payload = {k: v for k, v in payload.items() if v is not None}
246+
LOG.info("%s Setting low voltage state to %s", self._tag, payload)
247+
await self.set_attributes(payload)

0 commit comments

Comments
 (0)