Add XML support to RESTful binary sensor (#110062)

* Add XML support to RESTful binary sensor

* Add test for binary sensor with XML input data

* Address mypy validation results by handling None returns

* Use proper incorrect XML instead of blank

* Change failure condition to match the behavior of the library method

* Change error handling for bad XML to expect ExpatError

* Parametrize bad XML test to catch both empty and invalid XML

* Move exception handling out of the shared method

---------

Co-authored-by: Erik Montnemery <erik@montnemery.com>
This commit is contained in:
Oleg Kurapov 2024-05-30 16:29:50 +02:00 committed by GitHub
parent 4b95ea864f
commit 2cc38b426a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 107 additions and 18 deletions

View file

@ -4,6 +4,7 @@ from __future__ import annotations
import logging
import ssl
from xml.parsers.expat import ExpatError
import voluptuous as vol
@ -149,24 +150,31 @@ class RestBinarySensor(ManualTriggerEntity, RestEntity, BinarySensorEntity):
self._attr_is_on = False
return
response = self.rest.data
try:
response = self.rest.data_without_xml()
except ExpatError as err:
self._attr_is_on = False
_LOGGER.warning(
"REST xml result could not be parsed and converted to JSON: %s", err
)
return
raw_value = response
if self._value_template is not None:
if response is not None and self._value_template is not None:
response = self._value_template.async_render_with_possible_json_value(
self.rest.data, False
response, False
)
try:
self._attr_is_on = bool(int(response))
self._attr_is_on = bool(int(str(response)))
except ValueError:
self._attr_is_on = {
"true": True,
"on": True,
"open": True,
"yes": True,
}.get(response.lower(), False)
}.get(str(response).lower(), False)
self._process_manual_data(raw_value)
self.async_write_ha_state()