homeassistant-config/custom_components/sysdweb/binary_sensor.py

68 lines
2.1 KiB
Python

from . import DATA_SYSDWEB
import logging
from homeassistant.components.binary_sensor import BinarySensorDevice
from homeassistant.helpers import aiohttp_client
_LOGGER = logging.getLogger(__name__)
class ServiceStateSensor(BinarySensorDevice):
def __init__(self, name, url, auth):
self._on = None
self._name = name
self._available = False
self._url = url
self._auth = auth
self._status = 'unknown'
@property
def device_state_attributes(self):
return {'status': self._state}
@property
def name(self):
return self._name
@property
def available(self) -> bool:
return self._available
@property
def is_on(self):
return self._on
async def async_update(self):
session = aiohttp_client.async_get_clientsession(self.hass)
async with session.get(self._url, auth=self._auth) as resp:
resp_json = await resp.json()
status_result = resp_json["status"]
self._state = status_result
if resp.status == 200:
if status_result == 'active':
self._on = True
self._available = True
elif status_result == 'not-found':
self._on = None
self._available = False
else:
self._on = False
self._available = True
else:
self._available = False
self._state = "unknown"
_LOGGER.error(f"Error calling service sysdweb status {self._url}: {resp_json}")
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
data = hass.data[DATA_SYSDWEB]
sensors = []
for (host, service_name), (url, auth) in data.items():
host_simple = host
if '.' in host_simple:
host_simple = host_simple.split('.')[0]
sensor_name = f"sysdweb_{host_simple}_{service_name}"
sensors.append(ServiceStateSensor(sensor_name, url + "status", auth))
async_add_entities(sensors)