Skip to content

Commit

Permalink
reformat files
Browse files Browse the repository at this point in the history
  • Loading branch information
al-one committed Dec 27, 2020
1 parent b5c40e3 commit 24a36e5
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 62 deletions.
45 changes: 23 additions & 22 deletions custom_components/xiaomi_miot/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
"""Support for Xiaomi Miot."""
import logging
import asyncio
from math import ceil
from datetime import timedelta
from functools import partial
import voluptuous as vol
Expand All @@ -20,25 +19,25 @@
)

from miio import (
Device,
Device as MiioDevice,
DeviceException,
)
from miio.miot_device import MiotDevice

_LOGGER = logging.getLogger(__name__)

DOMAIN = 'xiaomi_miot'
SCAN_INTERVAL = timedelta(seconds = 60)
SCAN_INTERVAL = timedelta(seconds=60)
DEFAULT_NAME = 'Xiaomi Miot'
CONF_MODEL = 'model'

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_HOST): cv.string,
vol.Required(CONF_TOKEN): vol.All(cv.string, vol.Length(min=32, max=32)),
vol.Optional(CONF_NAME, default = DEFAULT_NAME): cv.string,
vol.Optional(CONF_MODEL, default = ''): cv.string,
vol.Optional(CONF_MODE, default = ''): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_MODEL, default=''): cv.string,
vol.Optional(CONF_MODE, default=''): cv.string,
}
)

Expand All @@ -54,7 +53,7 @@
'schema': XIAOMI_MIIO_SERVICE_SCHEMA.extend(
{
vol.Required('method'): cv.string,
vol.Optional('params', default = []): cv.ensure_list,
vol.Optional('params', default=[]): cv.ensure_list,
},
),
},
Expand All @@ -79,6 +78,7 @@ async def async_setup(hass, config: dict):
bind_services_to_entries(hass, SERVICE_TO_METHOD_BASE)
return True


async def async_setup_entry(hass: core.HomeAssistant, config_entry: config_entries.ConfigEntry):
hass.data[DOMAIN].setdefault('configs', {})
entry_id = config_entry.entry_id
Expand All @@ -103,11 +103,11 @@ async def async_setup_entry(hass: core.HomeAssistant, config_entry: config_entri
plats = []
hass.data[DOMAIN]['configs'][unique_id] = config
_LOGGER.debug('Xiaomi Miot async_setup_entry %s', {
'entry_id' : entry_id,
'unique_id' : unique_id,
'config' : config,
'plats' : plats,
'miio' : info,
'entry_id': entry_id,
'unique_id': unique_id,
'config': config,
'plats': plats,
'miio': info,
})
for plat in plats:
hass.async_create_task(hass.config_entries.async_forward_entry_setup(config_entry, plat))
Expand All @@ -132,9 +132,9 @@ async def async_service_handler(service):
if dvc.entity_id in entity_ids
]
_LOGGER.debug('Xiaomi Miot async_service_handler %s', {
'targets' : [ dvc.entity_id for dvc in target_devices ],
'method' : fun,
'params' : params,
'targets': [dvc.entity_id for dvc in target_devices],
'method': fun,
'params': params,
})
update_tasks = []
for dvc in target_devices:
Expand All @@ -145,9 +145,10 @@ async def async_service_handler(service):
update_tasks.append(dvc.async_update_ha_state(True))
if update_tasks:
await asyncio.wait(update_tasks)

for srv, obj in services.items():
schema = obj.get('schema', XIAOMI_MIIO_SERVICE_SCHEMA)
hass.services.async_register(DOMAIN, srv, async_service_handler, schema = schema)
hass.services.async_register(DOMAIN, srv, async_service_handler, schema=schema)


class MiioEntity(ToggleEntity):
Expand Down Expand Up @@ -206,7 +207,7 @@ def device_info(self):
'identifiers': {(DOMAIN, self._unique_did)},
'name': self._name,
'model': self._model,
'manufacturer': (self._model or 'Xiaomi').split('.',1)[0],
'manufacturer': (self._model or 'Xiaomi').split('.', 1)[0],
'sw_version': self._miio_info.firmware_version,
}

Expand All @@ -221,12 +222,12 @@ async def _try_command(self, mask_error, func, *args, **kwargs):
self._available = False
return False

async def async_command(self, method, params = [], mask_error = None):
async def async_command(self, method, params=[], mask_error=None):
_LOGGER.debug('Send miio command to %s: %s(%s)', self._name, method, params)
if mask_error is None:
mask_error = f'Send miio command to {self._name}: {method} failed: %s'
result = await self._try_command(mask_error, self._device.send, method, params)
if result == False:
if not result:
_LOGGER.info('Send miio command to %s failed: %s(%s)', self._name, method, params)
return result

Expand Down Expand Up @@ -262,19 +263,19 @@ async def _try_command(self, mask_error, func, *args, **kwargs):
for result in results:
break
_LOGGER.debug('Response received from miot %s: %s', self._name, result)
return result.get('code',1) == self._success_result
return result.get('code', 1) == self._success_result
except DeviceException as exc:
if self._available:
_LOGGER.error(mask_error, exc)
self._available = False
return False

async def async_command(self, method, params = [], mask_error = None):
async def async_command(self, method, params=[], mask_error=None):
_LOGGER.debug('Send miot command to %s: %s(%s)', self._name, method, params)
if mask_error is None:
mask_error = f'Send miot command to {self._name}: {method} failed: %s'
result = await self._try_command(mask_error, self._device.send, method, params)
if result == False:
if not result:
_LOGGER.info('Send miot command to %s failed: %s(%s)', self._name, method, params)
return result

Expand Down
85 changes: 45 additions & 40 deletions custom_components/xiaomi_miot/climate.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,13 @@

SERVICE_TO_METHOD = {}


async def async_setup_entry(hass, config_entry, async_add_entities):
config = hass.data[DOMAIN]['configs'].get(config_entry.entry_id,config_entry.data)
config = hass.data[DOMAIN]['configs'].get(config_entry.entry_id, config_entry.data)
await async_setup_platform(hass, config, async_add_entities)

async def async_setup_platform(hass, config, async_add_entities, discovery_info = None):

async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
if DATA_KEY not in hass.data:
hass.data[DATA_KEY] = {}
host = config[CONF_HOST]
Expand All @@ -46,42 +48,45 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info
entities.append(entity)
for entity in entities:
hass.data[DOMAIN]['entities'][entity.unique_id] = entity
async_add_entities(entities, update_before_add = True)
async_add_entities(entities, update_before_add=True)
bind_services_to_entries(hass, SERVICE_TO_METHOD)


HvacModes = Enum('HvacModes',{
HVAC_MODE_OFF : 0,
HVAC_MODE_COOL : 2,
HVAC_MODE_DRY : 3,
HVAC_MODE_FAN_ONLY : 4,
HVAC_MODE_HEAT : 5,
HvacModes = Enum('HvacModes', {
HVAC_MODE_OFF: 0,
HVAC_MODE_COOL: 2,
HVAC_MODE_DRY: 3,
HVAC_MODE_FAN_ONLY: 4,
HVAC_MODE_HEAT: 5,
})


class SwingModes(Enum):
Off = 0
Vertical = 1
Off = 0
Vertical = 1
Horizontal = 2
Steric = 3
Steric = 3


class AirConditionerMiotDevice(AirConditionerMiot):
def __init__(
self,
ip: str = None,
token: str = None,
start_id: int = 0,
debug: int = 0,
lazy_discover: bool = True,
self,
ip: str = None,
token: str = None,
start_id: int = 0,
debug: int = 0,
lazy_discover: bool = True,
) -> None:
super().__init__(ip, token, start_id, debug, lazy_discover)
self.mapping.update({
'horizontal_swing': {'siid': 3, 'piid': 3},
})


class MiotClimateEntity(MiotEntity, ClimateEntity):
def __init__(self, config):
name = config[CONF_NAME]
host = config[CONF_HOST]
name = config[CONF_NAME]
host = config[CONF_HOST]
token = config[CONF_TOKEN]
model = config.get(CONF_MODEL)
_LOGGER.info('Initializing with host %s (token %s...)', host, token[:5])
Expand All @@ -98,11 +103,11 @@ async def async_update(self):
await super().async_update()
if self._available:
self._state_attrs.update({
'current_temperature' : self._state_attrs.get('temperature',0),
'temperature' : self._state_attrs.get('target_temperature',0),
'current_temperature': self._state_attrs.get('temperature', 0),
'temperature': self._state_attrs.get('target_temperature', 0),
})
attrs = self._state_attrs
self._fan_speed = FanSpeed(attrs.get('fan_speed',0))
self._fan_speed = FanSpeed(attrs.get('fan_speed', 0))

@property
def state(self) -> str:
Expand All @@ -112,7 +117,7 @@ def state(self) -> str:
def hvac_mode(self):
self._hvac_mode = HVAC_MODE_OFF
if self._state:
self._hvac_mode = HvacModes(int(self._state_attrs.get('mode',0))).name
self._hvac_mode = HvacModes(int(self._state_attrs.get('mode', 0))).name
return self._hvac_mode

@property
Expand All @@ -132,11 +137,11 @@ def set_hvac_mode(self, hvac_mode: str):
else:
if not self._state:
self._device.on()
ret = self._device.set_property('mode',HvacModes[hvac_mode].value)
ret = self._device.set_property('mode', HvacModes[hvac_mode].value)
if ret:
self._hvac_mode = hvac_mode
self._state_attrs.update({
'mode' : HvacModes[hvac_mode].value,
'mode': HvacModes[hvac_mode].value,
})
return ret

Expand All @@ -146,7 +151,7 @@ def temperature_unit(self) -> str:

@property
def current_temperature(self) -> Optional[float]:
return float(self._state_attrs.get('temperature',0))
return float(self._state_attrs.get('temperature', 0))

@property
def min_temp(self) -> float:
Expand All @@ -158,7 +163,7 @@ def max_temp(self) -> float:

@property
def target_temperature(self) -> Optional[float]:
return float(self._state_attrs.get('target_temperature',0))
return float(self._state_attrs.get('target_temperature', 0))

@property
def target_temperature_step(self) -> Optional[float]:
Expand All @@ -184,7 +189,7 @@ def set_temperature(self, **kwargs):
ret = self._device.set_target_temperature(val)
if ret:
self._state_attrs.update({
'target_temperature' : val,
'target_temperature': val,
})
return ret

Expand All @@ -206,24 +211,24 @@ def set_fan_mode(self, fan_mode: str):
@property
def swing_mode(self) -> Optional[str]:
val = 0
if self._state_attrs.get('vertical_swing',False):
if self._state_attrs.get('vertical_swing', False):
val |= 1
if self._state_attrs.get('horizontal_swing',False):
if self._state_attrs.get('horizontal_swing', False):
val |= 2
return SwingModes(val).name

@property
def swing_modes(self) -> Optional[List[str]]:
lst = [v.name for v in SwingModes]
if not self._model in ['xiaomi.aircondition.mt5']:
lst = ['Off','Vertical']
lst = ['Off', 'Vertical']
return lst

def set_swing_mode(self, swing_mode: str) -> None:
mod = SwingModes[swing_mode]
val = mod.value
ver = self._state_attrs.get('vertical_swing',False)
hor = self._state_attrs.get('horizontal_swing',False)
ver = self._state_attrs.get('vertical_swing', False)
hor = self._state_attrs.get('horizontal_swing', False)
ret = None
if val & 1:
ver = True
Expand All @@ -236,16 +241,16 @@ def set_swing_mode(self, swing_mode: str) -> None:
if val == 0:
ver = False
hor = False
if not ver == self._state_attrs.get('vertical_swing',False):
ret = self._device.set_property('vertical_swing',ver)
if not ver == self._state_attrs.get('vertical_swing', False):
ret = self._device.set_property('vertical_swing', ver)
if ret:
self._state_attrs.update({
'vertical_swing' : ver,
'vertical_swing': ver,
})
if not hor == self._state_attrs.get('horizontal_swing',False):
ret = self._device.set_property('horizontal_swing',hor)
if not hor == self._state_attrs.get('horizontal_swing', False):
ret = self._device.set_property('horizontal_swing', hor)
if ret:
self._state_attrs.update({
'horizontal_swing' : hor,
'horizontal_swing': hor,
})
return ret

0 comments on commit 24a36e5

Please sign in to comment.