Skip to content
Snippets Groups Projects
Commit 6eaa34f3 authored by jkerdreu's avatar jkerdreu
Browse files

- Drop the core.py file

- Added support for TTS.

git-svn-id: https://redmine.imt-atlantique.fr/svn/xaal/code/Python/branches/0.7@3019 b32b6428-25c9-4566-ad07-03861ab6144f
parent fdb8448a
No related branches found
No related tags found
No related merge requests found
......@@ -9,7 +9,7 @@ from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.components.binary_sensor import BinarySensorEntity, BinarySensorDeviceClass
from homeassistant.const import STATE_ON, STATE_OFF
from .core import XAALEntity, EntityFactory, MonitorDevice, async_setup_factory
from .bridge import XAALEntity, EntityFactory, async_setup_factory
from xaal.lib import Message
_LOGGER = logging.getLogger(__name__)
......
......@@ -3,18 +3,21 @@ import asyncio
import functools
from typing import Dict, List, Any, Type
from .const import DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity import Entity, DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.config_entries import ConfigEntry
from xaal.lib import AsyncEngine, tools, Device, Message, bindings
from xaal.schemas import devices as schemas
from .core import EntityFactory, XAALEntity, MonitorDevice
from xaal.monitor import Monitor, Notification
from xaal.monitor.monitor import Device as MonitorDevice
import logging
_LOGGER = logging.getLogger(__name__)
UNSUPPORTED_TYPES = ['cli','hmi','windgauge',]
......@@ -25,6 +28,101 @@ def filter_msg(msg: Message) -> bool:
return True
class XAALEntity(Entity):
#_attr_has_entity_name = True
_attr_available: bool = False
def __init__(self, dev: MonitorDevice, bridge: "Bridge") -> None:
self._dev = dev
self._bridge = bridge
self.setup()
def setup(self):
pass
@property
def device_info(self) -> DeviceInfo | None :
dev = self._dev
ident = "dev:" + str(dev.address)
group_id = dev.description.get('group_id', None)
if group_id:
ident = "grp:" + str(group_id)
return {
"identifiers": {(DOMAIN, ident)},
"name": dev.display_name,
"model": dev.description.get("product_id", None),
"manufacturer": dev.description.get("vendor_id", None),
"sw_version": dev.description.get("version", None),
"hw_version": dev.description.get("hw_id", None),
"suggested_area" : dev.db.get("location",None)
}
def send_request(self, action: str, body: Dict[str, Any] | None =None) -> None:
_LOGGER.debug(f"{self} {action} {body}")
self._bridge.send_request([self._dev.address, ], action, body)
def get_attribute(self, name: str, default: Dict[str, Any] =None) -> Any:
""" return a attribute for xAAL device"""
return self._dev.attributes.get(name, default)
def short_type(self) -> str:
""" return a fake device class for entity that doesn't have one """
# this apply for light, button
# NOTE: I don't know why some entities don't have a device class
return self._dev.dev_type.split('.')[0]
@property
def should_poll(self) -> bool:
"""No polling needed."""
return False
@property
def name(self) -> str | None:
force_name = getattr(self,'_force_name',None)
dev_class = force_name or self.device_class or self.short_type()
return f"{dev_class} {self._dev.display_name}"
@property
def unique_id(self) -> str:
addr = str(self._dev.address).replace('-', '_')
if hasattr(self,'_xaal_attribute'):
return f"xaal.{addr}.{self._xaal_attribute}"
return f"xaal.{addr}"
async def async_added_to_hass(self) -> None:
"""call by HASS when entity is ready"""
self._attr_available = True
class EntityFactory(object):
def __init__(self, bridge: "Bridge", async_add_entitites: AddEntitiesCallback) -> None:
self._bridge = bridge
self._async_add_entitites = async_add_entitites
self._bridge.add_factory(self)
def build_entities(self, device: MonitorDevice) -> bool:
""" return True if this factory managed to build some entities"""
result = []
for type_ in self.mapping.keys():
if device.dev_type.startswith(type_):
for k in self.mapping[type_]:
entity = k(device, self._bridge)
result.append(entity)
# an factory can match only one dev_type
self._async_add_entitites(result)
self._bridge.add_entities(device.address, result)
return True
return False
@property
def mapping(self) -> dict:
"""return an ordered dict containing dev_type to platform class"""
return {}
class Bridge(object):
def __init__(self, hass: HomeAssistant, db_server) -> None:
......@@ -163,3 +261,17 @@ class Bridge(object):
@functools.lru_cache(maxsize=128)
def warm_once(self, msg: str):
_LOGGER.warning(msg)
def async_setup_factory(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
factory_class: EntityFactory
) -> None:
bridge = hass.data[DOMAIN][config_entry.entry_id]
factory = factory_class(bridge, async_add_entities)
for dev in bridge._mon.devices:
if dev.is_ready():
factory.new_entity(dev)
......@@ -6,7 +6,7 @@ from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.components.cover import CoverEntity, CoverDeviceClass, CoverEntityFeature, ATTR_POSITION
from .core import XAALEntity, EntityFactory, MonitorDevice, async_setup_factory
from .bridge import XAALEntity, EntityFactory, async_setup_factory
_LOGGER = logging.getLogger(__name__)
......
......@@ -6,7 +6,7 @@ from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.components.light import LightEntity, ColorMode, ATTR_BRIGHTNESS, ATTR_HS_COLOR, ATTR_COLOR_TEMP
from homeassistant.util import color as color_util
from .core import XAALEntity, EntityFactory, MonitorDevice, async_setup_factory
from .bridge import XAALEntity, EntityFactory, async_setup_factory
_LOGGER = logging.getLogger(__name__)
......
......@@ -7,7 +7,7 @@ from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.components.sensor import SensorDeviceClass, SensorEntity
from homeassistant import const
from .core import XAALEntity, EntityFactory, MonitorDevice, async_setup_factory
from .bridge import XAALEntity, EntityFactory, async_setup_factory
_LOGGER = logging.getLogger(__name__)
......@@ -32,7 +32,9 @@ class Factory(EntityFactory):
'luxmeter.' : [LuxMeter],
'co2meter.' : [CO2Meter],
'soundmeter.' : [SoundMeter],
'gateway.' : [Gateway], }
'gateway.' : [Gateway],
'tts.' : [TTS],
}
class XAALSensorEntity(XAALEntity, SensorEntity):
......@@ -120,3 +122,22 @@ class Gateway(XAALEntity, SensorEntity):
@property
def name(self) -> str | None:
return self._dev.description.get('product_id','gateway')
class TTS(XAALEntity,SensorEntity):
_attr_native_value = 1
def setup(self):
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
XAAL_NOTIF_SCHEMA = vol.Schema(
{
vol.Required("message"): cv.template,
vol.Optional("title"): cv.template,
}
)
self._bridge._hass.services.async_register("notify",self._dev.display_name, self.notify, schema=XAAL_NOTIF_SCHEMA)
def notify(self, service):
msg = service.data['message'].template
self.send_request('say',{'msg':msg})
\ No newline at end of file
......@@ -7,7 +7,7 @@ from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.components.siren import SirenEntity, SirenEntityFeature, ATTR_DURATION
from .core import XAALEntity, EntityFactory, async_setup_factory
from .bridge import XAALEntity, EntityFactory, async_setup_factory
_LOGGER = logging.getLogger(__name__)
......
......@@ -5,7 +5,7 @@ from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.components.switch import SwitchEntity, DEVICE_CLASS_OUTLET
from .core import EntityFactory, XAALEntity, MonitorDevice, async_setup_factory
from .bridge import EntityFactory, XAALEntity, async_setup_factory
_LOGGER = logging.getLogger(__name__)
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment