Skip to content

Commit

Permalink
🗂 clean up codes
Browse files Browse the repository at this point in the history
  • Loading branch information
al-one committed Feb 10, 2025
1 parent 134941c commit f339013
Show file tree
Hide file tree
Showing 7 changed files with 1 addition and 278 deletions.
61 changes: 0 additions & 61 deletions custom_components/xiaomi_miot/button.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,9 @@
XIAOMI_CONFIG_SCHEMA as PLATFORM_SCHEMA, # noqa: F401
HassEntry,
XEntity,
MiotPropertySubEntity,
BaseSubEntity,
async_setup_config_entry,
)
from .core.miot_spec import (
MiotProperty,
MiotAction,
)

_LOGGER = logging.getLogger(__name__)
DATA_KEY = f'{ENTITY_DOMAIN}.{DOMAIN}'
Expand Down Expand Up @@ -53,62 +48,6 @@ async def async_press(self):
XEntity.CLS[ENTITY_DOMAIN] = ButtonEntity


class MiotButtonSubEntity(MiotPropertySubEntity, BaseEntity):
def __init__(self, parent, miot_property: MiotProperty, value, option=None):
super().__init__(parent, miot_property, option, domain=ENTITY_DOMAIN)
self._miot_property_value = value
self._miot_property_desc = None
if miot_property.value_list:
self._miot_property_desc = miot_property.list_description(value)
if self._miot_property_desc is None:
self._miot_property_desc = value
self._name = f'{self._name} {self._miot_property_desc}'.strip()
self.entity_id = f'{self.entity_id}_{self._miot_property_value}'.strip()
self._unique_id = f'{self._unique_id}-value{self._miot_property_value}'.strip()
self._extra_attrs.update({
'property_value': self._miot_property_value,
'value_description': self._miot_property_desc,
})
self._available = True

def update(self, data=None):
if data:
self.update_attrs(data, update_parent=False)

def press(self):
"""Press the button."""
return self.set_parent_property(self._miot_property_value)


class MiotButtonActionSubEntity(BaseSubEntity, BaseEntity):
def __init__(self, parent, miot_action: MiotAction, option=None):
self._miot_action = miot_action
super().__init__(parent, miot_action.full_name, option, domain=ENTITY_DOMAIN)
self._name = f'{parent.device_name} {miot_action.friendly_desc}'.strip()
self._unique_id = f'{parent.unique_did}-{miot_action.unique_name}'
self.entity_id = miot_action.service.spec.generate_entity_id(self, miot_action.name)
self._extra_attrs.update({
'service_description': miot_action.service.description,
'action_description': miot_action.description,
})
self._available = True

def update(self, data=None):
if data:
self.update_attrs(data, update_parent=False)

def press(self):
"""Press the button."""
pms = []
for pid in self._miot_action.ins:
prop = self._miot_action.service.properties.get(pid)
val = self.custom_config(prop.name)
if prop.is_integer and val is not None:
val = int(val)
pms.append(val)
return self.call_parent('call_action', self._miot_action, pms)


class ButtonSubEntity(BaseEntity, BaseSubEntity):
def __init__(self, parent, attr, option=None):
BaseSubEntity.__init__(self, parent, attr, option)
Expand Down
18 changes: 0 additions & 18 deletions custom_components/xiaomi_miot/device_tracker.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,12 @@
HassEntry,
XEntity,
MiotEntity,
MiotPropertySubEntity,
async_setup_config_entry,
bind_services_to_entries,
)
from .core.miot_spec import (
MiotSpec,
MiotService,
MiotProperty,
)
from .core.coord_transform import gcj02_to_wgs84, bd09_to_wgs84

Expand Down Expand Up @@ -247,19 +245,3 @@ async def update_location(self):
self.update_attrs({
'timestamp': f'{tim[0:4]}-{tim[4:6]}-{tim[6:8]} {tim[8:10]}:{tim[10:12]}:{tim[12:14]}',
})


class MiotScannerSubEntity(MiotPropertySubEntity, BaseScannerEntity):

def __init__(self, parent, miot_property: MiotProperty, option=None):
super().__init__(parent, miot_property, option, domain=ENTITY_DOMAIN)

@property
def source_type(self):
"""Return the source type, eg gps or router, of the device."""
return SourceType.ROUTER

@property
def is_connected(self):
"""Return true if the device is connected to the network."""
return self._attr_state in [True, 1]
12 changes: 0 additions & 12 deletions custom_components/xiaomi_miot/media_player.py
Original file line number Diff line number Diff line change
Expand Up @@ -990,18 +990,6 @@ def __init__(self, config: dict, miot_service: MiotService):
self._supported_features |= MediaPlayerEntityFeature.SELECT_SOURCE
self._attr_source_list = self._miot_actions

async def async_added_to_hass(self):
await super().async_added_to_hass()

if act := self._miot_service.get_action('set_channel_number'):
prop = self._miot_service.get_property('channel_number')
add_numbers = self._add_entities.get('number')
if prop and add_numbers:
from .number import MiotNumberActionSubEntity
fnm = prop.unique_name
self._subs[fnm] = MiotNumberActionSubEntity(self, prop, act)
add_numbers([self._subs[fnm]], update_before_add=True)

@property
def state(self):
"""State of the player."""
Expand Down
97 changes: 0 additions & 97 deletions custom_components/xiaomi_miot/number.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,12 @@

from . import (
DOMAIN,
CONF_MODEL,
XIAOMI_CONFIG_SCHEMA as PLATFORM_SCHEMA, # noqa: F401
HassEntry,
XEntity,
MiotEntity,
MiotPropertySubEntity,
async_setup_config_entry,
bind_services_to_entries,
)
from .core.miot_spec import (
MiotSpec,
MiotService,
MiotProperty,
MiotAction,
)

_LOGGER = logging.getLogger(__name__)
DATA_KEY = f'{ENTITY_DOMAIN}.{DOMAIN}'
Expand All @@ -38,20 +29,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):


async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
hass.data.setdefault(DATA_KEY, {})
hass.data[DOMAIN]['add_entities'][ENTITY_DOMAIN] = async_add_entities
config['hass'] = hass
model = str(config.get(CONF_MODEL) or '')
spec = hass.data[DOMAIN]['miot_specs'].get(model)
entities = []
if isinstance(spec, MiotSpec):
for srv in spec.get_services('none_service'):
if not srv.get_property('none_property'):
continue
entities.append(MiotNumberEntity(config, srv))
for entity in entities:
hass.data[DOMAIN]['entities'][entity.unique_id] = entity
async_add_entities(entities, update_before_add=True)
bind_services_to_entries(hass, SERVICE_TO_METHOD)


Expand Down Expand Up @@ -82,78 +60,3 @@ async def async_set_native_value(self, value: float):
async_call_later(self.hass, 0.5, self.schedule_update_ha_state)

XEntity.CLS[ENTITY_DOMAIN] = NumberEntity


class MiotNumberEntity(MiotEntity, RestoreNumber):

def __init__(self, config, miot_service: MiotService):
super().__init__(miot_service, config=config, logger=_LOGGER)
self._attr_native_value = 0
self._attr_native_unit_of_measurement = None


class MiotNumberSubEntity(MiotPropertySubEntity, RestoreNumber):

def __init__(self, parent, miot_property: MiotProperty, option=None):
super().__init__(parent, miot_property, option, domain=ENTITY_DOMAIN)
self._attr_native_max_value = self._miot_property.range_max()
self._attr_native_min_value = self._miot_property.range_min()
self._attr_native_step = self._miot_property.range_step()
self._attr_native_value = 0
self._attr_native_unit_of_measurement = self._miot_property.unit_of_measurement
self._is_restore = False

async def async_added_to_hass(self):
await super().async_added_to_hass()
self._is_restore = self.custom_config_bool('restore_state')
if self._is_restore:
if restored := await self.async_get_last_number_data():
self._attr_native_value = restored.native_value

def update(self, data=None):
super().update(data)
val = self.native_value
if val is not None:
self._attr_native_value = val

@property
def native_value(self):
val = self._miot_property.from_device(self.device)
return val

def cast_value(self, val, default=None):
try:
val = round(float(val), 6)
if self._miot_property.is_integer:
val = int(val)
except (TypeError, ValueError):
val = default
return val

def set_native_value(self, value):
"""Set new value."""
if self._miot_property.is_integer:
value = int(value)
return self.set_parent_property(value)


class MiotNumberActionSubEntity(MiotNumberSubEntity):
def __init__(self, parent, miot_property: MiotProperty, miot_action: MiotAction, option=None):
super().__init__(parent, miot_property, option)
self._miot_action = miot_action
self._state_attrs.update({
'miot_action': miot_action.full_name,
})

def update(self, data=None):
self._available = True
self._attr_native_value = 0

def set_native_value(self, value):
"""Set new value."""
val = int(value)
ret = self.call_parent('call_action', self._miot_action, [val])
if ret:
self._attr_native_value = val
self.schedule_update_ha_state()
return ret
35 changes: 1 addition & 34 deletions custom_components/xiaomi_miot/select.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,10 @@
XEntity,
MiotEntity,
BaseSubEntity,
MiotPropertySubEntity,
async_setup_config_entry,
bind_services_to_entries,
)
from .core.miot_spec import (
MiotService,
MiotProperty,
)
from .core.miot_spec import MiotService

_LOGGER = logging.getLogger(__name__)
DATA_KEY = f'{ENTITY_DOMAIN}.{DOMAIN}'
Expand Down Expand Up @@ -87,35 +83,6 @@ def select_option(self, option):
raise NotImplementedError()


class MiotSelectSubEntity(BaseEntity, MiotPropertySubEntity):
def __init__(self, parent, miot_property: MiotProperty, option=None):
MiotPropertySubEntity.__init__(self, parent, miot_property, option, domain=ENTITY_DOMAIN)
self._attr_options = miot_property.list_descriptions()

def update(self, data=None):
super().update(data)
if not self._available:
return
val = self._miot_property.from_device(self.device)
if val is None:
self._attr_current_option = None
else:
des = self._miot_property.list_description(val)
stp = self._miot_property.range_step()
if stp and stp % 1 > 0:
des = float(des)
self._attr_current_option = str(des)

def select_option(self, option):
"""Change the selected option."""
val = self._miot_property.list_value(option)
if val is not None:
if bfs := self._option.get('before_select'):
bfs(self._miot_property, option)
return self.set_parent_property(val)
return False


class SelectSubEntity(BaseEntity, BaseSubEntity):
def __init__(self, parent, attr, option=None):
BaseSubEntity.__init__(self, parent, attr, option)
Expand Down
2 changes: 0 additions & 2 deletions custom_components/xiaomi_miot/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,13 @@
MiotEntity,
BaseSubEntity,
MiCoordinatorEntity,
MiotPropertySubEntity,
MiotCloud,
async_setup_config_entry,
bind_services_to_entries,
)
from .core.miot_spec import (
MiotSpec,
MiotService,
MiotProperty,
)
from .core.utils import local_zone, get_translation

Expand Down
54 changes: 0 additions & 54 deletions custom_components/xiaomi_miot/text.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
"""Support text entity for Xiaomi Miot."""
import logging
import time

from homeassistant.components.text import (
DOMAIN as ENTITY_DOMAIN,
Expand All @@ -12,11 +11,8 @@
XIAOMI_CONFIG_SCHEMA as PLATFORM_SCHEMA, # noqa: F401
HassEntry,
XEntity,
MiotPropertySubEntity,
BaseSubEntity,
async_setup_config_entry,
)
from .core.miot_spec import MiotAction

_LOGGER = logging.getLogger(__name__)
DATA_KEY = f'{ENTITY_DOMAIN}.{DOMAIN}'
Expand Down Expand Up @@ -97,53 +93,3 @@ async def async_set_value(self, value: str):
self.schedule_update_ha_state()

XEntity.CLS[ENTITY_DOMAIN] = TextEntity


class MiotTextSubEntity(MiotPropertySubEntity, BaseEntity):
_attr_native_value = ''

def update(self, data=None):
super().update(data)
if not self._available:
return
self._attr_native_value = self._attr_state

def set_value(self, value):
"""Change the value."""
self._attr_native_value = value
return self.set_parent_property(value)


class MiotTextActionSubEntity(BaseSubEntity, BaseEntity):
_attr_native_value = ''

def __init__(self, parent, miot_action: MiotAction, option=None):
self._miot_action = miot_action
super().__init__(parent, miot_action.full_name, option, domain=ENTITY_DOMAIN)
self._name = f'{parent.device_name} {miot_action.friendly_desc}'.strip()
self._unique_id = f'{parent.unique_did}-{miot_action.unique_name}'
self.entity_id = miot_action.service.spec.generate_entity_id(self, miot_action.name)
self._extra_attrs.update({
'service_description': miot_action.service.description,
'action_description': miot_action.description,
})
self._available = True

def update(self, data=None):
if data:
self.update_attrs(data, update_parent=False)

def set_value(self, value):
"""Change the value."""
if self._miot_action.name in ['execute_text_directive']:
silent = self.custom_config_integer('silent_execution', 0)
ret = self.call_parent('intelligent_speaker', value, True, silent)
else:
ret = self.call_parent('call_action', self._miot_action, [value])

if ret:
self._attr_native_value = value
self.schedule_update_ha_state()
time.sleep(0.5)
self._attr_native_value = ''
return ret

0 comments on commit f339013

Please sign in to comment.