Skip to content

Commit df3faea

Browse files
authored
feat: set the cover closed position (#1242)
* feat: add the cover closed position configure option * feat: estimate the cover entity's is_closed property by the cover closed position (#944) * fix: translations * feat: set max cover closed position as 5 * docs: modify README * fix: remove useless spaces
1 parent e096766 commit df3faea

17 files changed

Lines changed: 78 additions & 29 deletions

File tree

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -293,7 +293,7 @@ The value of the event instance name indicates `_attr_device_class` of the Home
293293

294294
`spec_filter.yaml` is used to filter out the MIoT-Spec-V2 instance that will not be converted to Home Assistant entity.
295295

296-
The format of `spec_filter.json` is as follows.
296+
The format of `spec_filter.yaml` is as follows.
297297

298298
```yaml
299299
<MIoT-Spec-V2 device instance urn without the version field>:

custom_components/xiaomi_home/config_flow.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,9 @@
7575
DEFAULT_CLOUD_SERVER,
7676
DEFAULT_CTRL_MODE,
7777
DEFAULT_INTEGRATION_LANGUAGE,
78+
DEFAULT_COVER_CLOSED_POSITION,
79+
MIN_COVER_CLOSED_POSITION,
80+
MAX_COVER_CLOSED_POSITION,
7881
DEFAULT_NICK_NAME,
7982
DEFAULT_OAUTH2_API_HOST,
8083
DOMAIN,
@@ -129,6 +132,7 @@ class XiaomiMihomeConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
129132

130133
_cloud_server: str
131134
_integration_language: str
135+
_cover_closed_position: int
132136
_auth_info: dict
133137
_nick_name: str
134138
_home_selected: dict
@@ -151,6 +155,7 @@ def __init__(self) -> None:
151155
self._main_loop = asyncio.get_running_loop()
152156
self._cloud_server = DEFAULT_CLOUD_SERVER
153157
self._integration_language = DEFAULT_INTEGRATION_LANGUAGE
158+
self._cover_closed_position = DEFAULT_COVER_CLOSED_POSITION
154159
self._storage_path = ''
155160
self._virtual_did = ''
156161
self._uid = ''
@@ -951,6 +956,7 @@ async def config_flow_done(self):
951956
'action_debug': self._action_debug,
952957
'hide_non_standard_entities':
953958
self._hide_non_standard_entities,
959+
'cover_closed_position': self._cover_closed_position,
954960
'display_binary_mode': self._display_binary_mode,
955961
'display_devices_changed_notify':
956962
self._display_devices_changed_notify
@@ -995,6 +1001,7 @@ class OptionsFlowHandler(config_entries.OptionsFlow):
9951001
_hide_non_standard_entities: bool
9961002
_display_binary_mode: list[str]
9971003
_display_devs_notify: list[str]
1004+
_cover_closed_position: int
9981005

9991006
_oauth_redirect_url_full: str
10001007
_auth_info: dict
@@ -1015,6 +1022,7 @@ class OptionsFlowHandler(config_entries.OptionsFlow):
10151022
_opt_lan_ctrl_cfg: bool
10161023
_opt_network_detect_cfg: bool
10171024
_opt_check_network_deps: bool
1025+
_cover_pos_new: int
10181026

10191027
_trans_rules_count: int
10201028
_trans_rules_count_success: int
@@ -1043,6 +1051,8 @@ def __init__(self, config_entry: config_entries.ConfigEntry):
10431051
self._ctrl_mode = self._entry_data.get('ctrl_mode', DEFAULT_CTRL_MODE)
10441052
self._integration_language = self._entry_data.get(
10451053
'integration_language', DEFAULT_INTEGRATION_LANGUAGE)
1054+
self._cover_closed_position = self._entry_data.get(
1055+
'cover_closed_position', DEFAULT_COVER_CLOSED_POSITION)
10461056
self._nick_name = self._entry_data.get('nick_name', DEFAULT_NICK_NAME)
10471057
self._action_debug = self._entry_data.get('action_debug', False)
10481058
self._hide_non_standard_entities = self._entry_data.get(
@@ -1068,6 +1078,7 @@ def __init__(self, config_entry: config_entries.ConfigEntry):
10681078
self._action_debug_new = False
10691079
self._hide_non_standard_entities_new = False
10701080
self._display_binary_mode_new = []
1081+
self._cover_pos_new = self._cover_closed_position
10711082
self._update_user_info = False
10721083
self._update_devices = False
10731084
self._update_trans_rules = False
@@ -1340,6 +1351,12 @@ async def async_step_config_options(self, user_input=None):
13401351
): cv.multi_select(
13411352
self._miot_i18n.translate(
13421353
'config.binary_mode')), # type: ignore
1354+
vol.Optional(
1355+
'cover_closed_position',
1356+
default=self._cover_closed_position # type: ignore
1357+
): vol.All(vol.Coerce(int), vol.Range(
1358+
min=MIN_COVER_CLOSED_POSITION,
1359+
max=MAX_COVER_CLOSED_POSITION)),
13431360
vol.Required(
13441361
'update_trans_rules',
13451362
default=self._update_trans_rules # type: ignore
@@ -1378,6 +1395,8 @@ async def async_step_config_options(self, user_input=None):
13781395
'update_lan_ctrl_config', self._opt_lan_ctrl_cfg)
13791396
self._opt_network_detect_cfg = user_input.get(
13801397
'network_detect_config', self._opt_network_detect_cfg)
1398+
self._cover_pos_new = user_input.get(
1399+
'cover_closed_position', self._cover_closed_position)
13811400

13821401
return await self.async_step_update_user_info()
13831402

@@ -1926,6 +1945,7 @@ async def async_step_config_confirm(self, user_input=None):
19261945
'nick_name': self._nick_name,
19271946
'lang_new': INTEGRATION_LANGUAGES[self._lang_new],
19281947
'nick_name_new': self._nick_name_new,
1948+
'cover_pos_new': self._cover_pos_new,
19291949
'devices_add': len(self._devices_add),
19301950
'devices_remove': len(self._devices_remove),
19311951
'trans_rules_count': self._trans_rules_count,
@@ -1952,6 +1972,9 @@ async def async_step_config_confirm(self, user_input=None):
19521972
if self._lang_new != self._integration_language:
19531973
self._entry_data['integration_language'] = self._lang_new
19541974
self._need_reload = True
1975+
if self._cover_pos_new != self._cover_closed_position:
1976+
self._entry_data['cover_closed_position'] = self._cover_pos_new
1977+
self._need_reload = True
19551978
if self._update_user_info:
19561979
self._entry_data['nick_name'] = self._nick_name_new
19571980
if self._update_devices:

custom_components/xiaomi_home/cover.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,7 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry,
9191
class Cover(MIoTServiceEntity, CoverEntity):
9292
"""Cover entities for Xiaomi Home."""
9393
# pylint: disable=unused-argument
94+
_cover_closed_position: int
9495
_prop_motor_control: Optional[MIoTSpecProperty]
9596
_prop_motor_value_open: Optional[int]
9697
_prop_motor_value_close: Optional[int]
@@ -115,6 +116,9 @@ def __init__(self, miot_device: MIoTDevice,
115116
self._attr_supported_color_modes = set()
116117
self._attr_supported_features = CoverEntityFeature(0)
117118

119+
self._cover_closed_position = (
120+
miot_device.miot_client.cover_closed_position)
121+
118122
self._prop_motor_control = None
119123
self._prop_motor_value_open = None
120124
self._prop_motor_value_close = None
@@ -297,7 +301,7 @@ def is_closing(self) -> Optional[bool]:
297301
def is_closed(self) -> Optional[bool]:
298302
"""Return if the cover is closed."""
299303
if self.current_cover_position is not None:
300-
return self.current_cover_position == 0
304+
return self.current_cover_position <= self._cover_closed_position
301305
# The current position is prior to the status when determining
302306
# whether the cover is closed.
303307
if self._prop_status and self._prop_status_closed:

custom_components/xiaomi_home/miot/const.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,10 @@
120120
'zh-Hant': '繁體中文'
121121
}
122122

123+
DEFAULT_COVER_CLOSED_POSITION: int = 0
124+
MIN_COVER_CLOSED_POSITION: int = 0
125+
MAX_COVER_CLOSED_POSITION: int = 5
126+
123127
DEFAULT_CTRL_MODE: str = 'auto'
124128

125129
# Registered in Xiaomi OAuth 2.0 Service

custom_components/xiaomi_home/miot/miot_client.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,8 @@
6363
from .const import (
6464
DEFAULT_CTRL_MODE, DEFAULT_INTEGRATION_LANGUAGE, DEFAULT_NICK_NAME, DOMAIN,
6565
MIHOME_CERT_EXPIRE_MARGIN, NETWORK_REFRESH_INTERVAL,
66-
OAUTH2_CLIENT_ID, SUPPORT_CENTRAL_GATEWAY_CTRL)
66+
OAUTH2_CLIENT_ID, SUPPORT_CENTRAL_GATEWAY_CTRL,
67+
DEFAULT_COVER_CLOSED_POSITION)
6768
from .miot_cloud import MIoTHttpClient, MIoTOauthClient
6869
from .miot_error import MIoTClientError, MIoTErrorCode
6970
from .miot_mips import (
@@ -486,6 +487,11 @@ def display_binary_text(self) -> bool:
486487
def display_binary_bool(self) -> bool:
487488
return self._display_binary_bool
488489

490+
@property
491+
def cover_closed_position(self) -> int:
492+
return self._entry_data.get('cover_closed_position',
493+
DEFAULT_COVER_CLOSED_POSITION)
494+
489495
@display_devices_changed_notify.setter
490496
def display_devices_changed_notify(self, value: list[str]) -> None:
491497
if set(value) == set(self._display_devs_notify):

custom_components/xiaomi_home/translations/de.json

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
"step": {
55
"eula": {
66
"title": "Risikohinweis",
7-
"description": "1. Ihre **Xiaomi-Benutzerinformationen und Geräteinformationen** werden in Ihrem Home Assistant-System gespeichert. **Xiaomi kann die Sicherheit des Home Assistant-Speichermechanismus nicht garantieren**. Sie sind dafür verantwortlich, Ihre Informationen vor Diebstahl zu schützen.\r\n2. Diese Integration wird von der Open-Source-Community unterstützt und gewartet. Es können jedoch Stabilitätsprobleme oder andere Probleme auftreten. Wenn Sie auf ein Problem stoßen, das mit dieser Integration zusammenhängt, sollten Sie **die Open-Source-Community um Hilfe bitten, anstatt sich an den Xiaomi Home Kundendienst zu wenden**.\r\n3. Sie benötigen bestimmte technische Fähigkeiten, um Ihre lokale Laufzeitumgebung zu warten. Diese Integration ist für Anfänger nicht geeignet. \r\n4. Bevor Sie diese Integration verwenden, lesen Sie bitte die **README-Datei sorgfältig durch**.\r\n5. Um eine stabile Nutzung der Integration zu gewährleisten und Missbrauch der Schnittstelle zu verhindern, **darf diese Integration nur in Home Assistant verwendet werden. Weitere Informationen finden Sie in der LICENSE**.",
7+
"description": "1. Ihre **Xiaomi-Benutzerinformationen und Geräteinformationen** werden in Ihrem Home Assistant-System gespeichert. **Xiaomi kann die Sicherheit des Home Assistant-Speichermechanismus nicht garantieren**. Sie sind dafür verantwortlich, Ihre Informationen vor Diebstahl zu schützen.\r\n2. Diese Integration wird von der Open-Source-Community unterstützt und gewartet. Es können jedoch Stabilitätsprobleme oder andere Probleme auftreten. Wenn Sie auf ein Problem stoßen, das mit dieser Integration zusammenhängt, sollten Sie **die Open-Source-Community um Hilfe bitten, anstatt sich an den Xiaomi Home Kundendienst zu wenden**.\r\n3. Sie benötigen bestimmte technische Fähigkeiten, um Ihre lokale Laufzeitumgebung zu warten. Diese Integration ist für Anfänger nicht geeignet.\r\n4. Bevor Sie diese Integration verwenden, lesen Sie bitte die **README-Datei sorgfältig durch**.\r\n5. Um eine stabile Nutzung der Integration zu gewährleisten und Missbrauch der Schnittstelle zu verhindern, **darf diese Integration nur in Home Assistant verwendet werden. Weitere Informationen finden Sie in der LICENSE**.",
88
"data": {
99
"eula": "Ich habe das oben genannte Risiko zur Kenntnis genommen und übernehme freiwillig die damit verbundenen Risiken durch die Verwendung der Integration."
1010
}
@@ -124,7 +124,8 @@
124124
"display_devices_changed_notify": "Gerätestatusänderungen anzeigen",
125125
"update_trans_rules": "Entitätskonvertierungsregeln aktualisieren",
126126
"update_lan_ctrl_config": "LAN-Steuerungskonfiguration aktualisieren",
127-
"network_detect_config": "Integrierte Netzwerkkonfiguration"
127+
"network_detect_config": "Integrierte Netzwerkkonfiguration",
128+
"cover_closed_position": "Die Position der geschlossenen Vorhänge"
128129
}
129130
},
130131
"update_user_info": {
@@ -183,7 +184,7 @@
183184
},
184185
"config_confirm": {
185186
"title": "Bestätigen Sie die Konfiguration",
186-
"description": "**{nick_name}**, bitte bestätigen Sie die neuesten Konfigurationsinformationen und klicken Sie dann auf \"Senden\". Die Integration wird mit den aktualisierten Konfigurationen erneut geladen.\r\n\r\nIntegrationsprache:\t{lang_new}\r\nBenutzername:\t{nick_name_new}\r\nAction-Debug-Modus:\t{action_debug}\r\nVerstecke Nicht-Standard-Entitäten:\t{hide_non_standard_entities}\r\nGerätestatusänderungen anzeigen:\t{display_devices_changed_notify}\r\nGeräteänderungen:\t{devices_add} neue Geräte hinzufügen, {devices_remove} Geräte entfernen\r\nKonvertierungsregeländerungen:\tInsgesamt {trans_rules_count} Regeln, aktualisiert {trans_rules_count_success} Regeln",
187+
"description": "**{nick_name}**, bitte bestätigen Sie die neuesten Konfigurationsinformationen und klicken Sie dann auf \"Senden\". Die Integration wird mit den aktualisierten Konfigurationen erneut geladen.\r\n\r\nIntegrationsprache:\t{lang_new}\r\nBenutzername:\t{nick_name_new}\r\nAction-Debug-Modus:\t{action_debug}\r\nVerstecke Nicht-Standard-Entitäten:\t{hide_non_standard_entities}\r\nDie Position der geschlossenen Vorhänge:\t{cover_pos_new}\r\nGerätestatusänderungen anzeigen:\t{display_devices_changed_notify}\r\nGeräteänderungen:\t{devices_add} neue Geräte hinzufügen, {devices_remove} Geräte entfernen\r\nKonvertierungsregeländerungen:\tInsgesamt {trans_rules_count} Regeln, aktualisiert {trans_rules_count_success} Regeln",
187188
"data": {
188189
"confirm": "Änderungen bestätigen"
189190
}

custom_components/xiaomi_home/translations/en.json

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,8 @@
124124
"display_devices_changed_notify": "Display device status change notifications",
125125
"update_trans_rules": "Update entity conversion rules",
126126
"update_lan_ctrl_config": "Update LAN control configuration",
127-
"network_detect_config": "Integrated Network Configuration"
127+
"network_detect_config": "Integrated network configuration",
128+
"cover_closed_position": "Cover closed position"
128129
}
129130
},
130131
"update_user_info": {
@@ -183,7 +184,7 @@
183184
},
184185
"config_confirm": {
185186
"title": "Confirm Configuration",
186-
"description": "Hello **{nick_name}**, please confirm the latest configuration information and then Click SUBMIT.\r\nThe integration will reload using the updated configuration.\r\n\r\nIntegration Language: \t{lang_new}\r\nNickname: \t{nick_name_new}\r\nDebug mode for action: \t{action_debug}\r\nHide non-standard created entities: \t{hide_non_standard_entities}\r\nDisplay device status change notifications:\t{display_devices_changed_notify}\r\nDevice Changes: \tAdd **{devices_add}** devices, Remove **{devices_remove}** devices\r\nTransformation rules change: \tThere are a total of **{trans_rules_count}** rules, and updated **{trans_rules_count_success}** rules",
187+
"description": "Hello **{nick_name}**, please confirm the latest configuration information and then Click SUBMIT.\r\nThe integration will reload using the updated configuration.\r\n\r\nIntegration Language:\t{lang_new}\r\nNickname:\t{nick_name_new}\r\nDebug mode for action:\t{action_debug}\r\nHide non-standard created entities:\t{hide_non_standard_entities}\r\nCover closed position:\t{cover_pos_new}\r\nDisplay device status change notifications:\t{display_devices_changed_notify}\r\nDevice Changes:\tAdd **{devices_add}** devices, Remove **{devices_remove}** devices\r\nTransformation rules change:\tThere are a total of **{trans_rules_count}** rules, and updated **{trans_rules_count_success}** rules",
187188
"data": {
188189
"confirm": "Confirm the change"
189190
}

custom_components/xiaomi_home/translations/es.json

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
"step": {
55
"eula": {
66
"title": "Aviso de riesgo",
7-
"description": "1. Su **información de usuario de Xiaomi e información del dispositivo** se almacenará en su sistema Home Assistant. **Xiaomi no puede garantizar la seguridad del mecanismo de almacenamiento de Home Assistant**. Usted es responsable de evitar que su información sea robada.\r\n2. Esta integración es mantenida por la comunidad de código abierto y puede haber problemas de estabilidad u otros problemas. Cuando tenga problemas relacionados con el uso de esta integración, **busque ayuda en la comunidad de código abierto en lugar de contactar al servicio al cliente de Xiaomi**.\r\n3. Es necesario tener ciertas habilidades técnicas para mantener su entorno de ejecución local, esta integración no es amigable para los usuarios novatos.\r\n4. Antes de utilizar esta integración, por favor **lea detenidamente el archivo README**. \r\n5. Para garantizar el uso estable de la integración y prevenir el abuso de la interfaz, **esta integración solo está permitida en Home Assistant. Para más detalles, consulte la LICENSE**.",
7+
"description": "1. Su **información de usuario de Xiaomi e información del dispositivo** se almacenará en su sistema Home Assistant. **Xiaomi no puede garantizar la seguridad del mecanismo de almacenamiento de Home Assistant**. Usted es responsable de evitar que su información sea robada.\r\n2. Esta integración es mantenida por la comunidad de código abierto y puede haber problemas de estabilidad u otros problemas. Cuando tenga problemas relacionados con el uso de esta integración, **busque ayuda en la comunidad de código abierto en lugar de contactar al servicio al cliente de Xiaomi**.\r\n3. Es necesario tener ciertas habilidades técnicas para mantener su entorno de ejecución local, esta integración no es amigable para los usuarios novatos.\r\n4. Antes de utilizar esta integración, por favor **lea detenidamente el archivo README**.\r\n5. Para garantizar el uso estable de la integración y prevenir el abuso de la interfaz, **esta integración solo está permitida en Home Assistant. Para más detalles, consulte la LICENSE**.",
88
"data": {
99
"eula": "He leído y entiendo los riesgos anteriores, y estoy dispuesto a asumir cualquier riesgo relacionado con el uso de esta integración."
1010
}
@@ -124,7 +124,8 @@
124124
"display_devices_changed_notify": "Mostrar notificaciones de cambio de estado del dispositivo",
125125
"update_trans_rules": "Actualizar reglas de conversión de entidad",
126126
"update_lan_ctrl_config": "Actualizar configuración de control LAN",
127-
"network_detect_config": "Configuración de Red Integrada"
127+
"network_detect_config": "Configuración de Red Integrada",
128+
"cover_closed_position": "La posición de las cortinas cerradas"
128129
}
129130
},
130131
"update_user_info": {
@@ -183,7 +184,7 @@
183184
},
184185
"config_confirm": {
185186
"title": "Confirmar configuración",
186-
"description": "¡Hola, **{nick_name}**! Por favor, confirme la última información de configuración y haga clic en \"Enviar\" para finalizar la configuración.\r\nLa integración se volverá a cargar con la nueva configuración.\r\n\r\nIdioma de la integración:\t{lang_new}\r\nApodo de usuario:\t{nick_name_new}\r\nModo de depuración de Action:\t{action_debug}\r\nOcultar entidades generadas no estándar:\t{hide_non_standard_entities}\r\nMostrar notificaciones de cambio de estado del dispositivo:\t{display_devices_changed_notify}\r\nCambios de dispositivos:\t{devices_add} dispositivos agregados, {devices_remove} dispositivos eliminados\r\nCambios en las reglas de conversión:\t{trans_rules_count} reglas en total, {trans_rules_count_success} reglas actualizadas",
187+
"description": "¡Hola, **{nick_name}**! Por favor, confirme la última información de configuración y haga clic en \"Enviar\" para finalizar la configuración.\r\nLa integración se volverá a cargar con la nueva configuración.\r\n\r\nIdioma de la integración:\t{lang_new}\r\nApodo de usuario:\t{nick_name_new}\r\nModo de depuración de Action:\t{action_debug}\r\nOcultar entidades generadas no estándar:\t{hide_non_standard_entities}\r\nLa posición de las cortinas cerradas:\t{cover_pos_new}\r\nMostrar notificaciones de cambio de estado del dispositivo:\t{display_devices_changed_notify}\r\nCambios de dispositivos:\t{devices_add} dispositivos agregados, {devices_remove} dispositivos eliminados\r\nCambios en las reglas de conversión:\t{trans_rules_count} reglas en total, {trans_rules_count_success} reglas actualizadas",
187188
"data": {
188189
"confirm": "Confirmar modificación"
189190
}

0 commit comments

Comments
 (0)