Skip to content

Commit

Permalink
Merge pull request #21 from nergal/develop
Browse files Browse the repository at this point in the history
Add platform configuration
  • Loading branch information
nergal authored Feb 4, 2022
2 parents 57a43b8 + 69de49d commit 5b39eb7
Show file tree
Hide file tree
Showing 19 changed files with 690 additions and 130 deletions.
4 changes: 3 additions & 1 deletion .github/workflows/workflow.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@ jobs:
- name: Run lint checks
run: make lint
- name: Run unit tests
run: make test
run: make coverage
- name: Upload Coverage to Codecov
uses: codecov/codecov-action@v1

analyze:
name: Analyze CodeQL
Expand Down
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,7 @@
.vscode/
__pycache__/
.idea/
.coverage
.DS_Store
*.tmp
*.log
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,4 @@ test:
$(POETRY) run pytest $(TEST_FOLDER)

coverage:
$(POETRY) run pytest --cov-report term $(TEST_FOLDER)
$(POETRY) run pytest --cov-report xml --cov=custom_components.xiaomi_viomi $(TEST_FOLDER)
14 changes: 13 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Homeassistant Vacuum Viomi integration for HACS

[![hacs_badge](https://img.shields.io/badge/HACS-Custom-orange.svg)](https://github.com/custom-components/hacs)
[![codecov](https://codecov.io/gh/nergal/homeassistant-vacuum-viomi/branch/master/graph/badge.svg?token=MUHLPCJY2G)](https://codecov.io/gh/nergal/homeassistant-vacuum-viomi)
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
![GitHub](https://img.shields.io/github/license/nergal/homeassistant-vacuum-viomi)
[![Validation flow](https://github.com/nergal/homeassistant-vacuum-viomi/actions/workflows/workflow.yaml/badge.svg)](https://github.com/nergal/homeassistant-vacuum-viomi/actions/workflows/workflow.yaml)
Expand All @@ -14,7 +15,18 @@ Xiaomi Viomi vacuum robot integration for Home Assistant.
### HACS
Install it through HACS by adding this as a custom repository: https://github.com/nergal/homeassistant-vacuum-viomi, go to the integrations page in your configuration, click on the `Add Integration` button in the bottom right corner of a screen, and search for `Xiaomi Viomi Vacuum`.

Manual installation currently not supported.
### Manual
Copy contents of `custom_components` folder to your Home Assistant `config/custom_components` folder. Restart Home Assistant, and then the integration can be added and configured through the native integration setup. If you don't see it in the native integrations list, press Ctrl+F5 to refresh the browser while you're on that page and retry.

Also you may add the manual configuration to `configuration.yaml` file, like the example below:

```
vacuum:
- platform: xiaomi_viomi
host: 192.168.1.1
token: !secret vacuum
name: Vacuum V8
```

## Tested models
| Model | Device ID | Aliases | Status |
Expand Down
Empty file added codecov.yml
Empty file.
14 changes: 14 additions & 0 deletions custom_components/xiaomi_viomi/__init__.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,25 @@
"""Xiaomi Viomi integration."""
import asyncio

import voluptuous as vol
from homeassistant.components.vacuum import PLATFORM_SCHEMA
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_HOST, CONF_NAME, CONF_TOKEN, DEVICE_DEFAULT_NAME
from homeassistant.core import HomeAssistant
from homeassistant.helpers import config_validation as cv

from .const import DOMAIN # noqa: F401

PLATFORMS = ["vacuum"]

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_NAME, default=DEVICE_DEFAULT_NAME): cv.string,
vol.Required(CONF_TOKEN): cv.string,
vol.Required(CONF_HOST): cv.string,
}
)


async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Xiaomi Viomi from a config entry."""
Expand Down
21 changes: 18 additions & 3 deletions custom_components/xiaomi_viomi/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,15 @@
import voluptuous as vol
from construct.core import ChecksumError
from homeassistant import config_entries
from homeassistant.const import CONF_HOST, CONF_TOKEN
from homeassistant.components.xiaomi_miio import CONF_MODEL
from homeassistant.const import (
CONF_HOST,
CONF_MAC,
CONF_NAME,
CONF_PLATFORM,
CONF_TOKEN,
DEVICE_DEFAULT_NAME,
)
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResult
from homeassistant.exceptions import ConfigEntryAuthFailed, HomeAssistantError
Expand All @@ -14,14 +22,15 @@
from miio.device import DeviceInfo
from miio.integrations.vacuum.viomi.viomivacuum import ViomiVacuum

from .const import CONF_MAC, CONF_MODEL, DOMAIN
from .const import DOMAIN

_LOGGER = logging.getLogger(__name__)

DEVICE_CONFIG = vol.Schema(
{
vol.Required(CONF_HOST): str,
vol.Required(CONF_TOKEN): vol.All(str, vol.Length(min=32, max=32)),
vol.Optional(CONF_NAME, default=DEVICE_DEFAULT_NAME): str,
}
)

Expand Down Expand Up @@ -76,10 +85,15 @@ async def validate_input(hass: HomeAssistant, data: Dict[str, Any]) -> Dict[str,
if not await hub.async_device_is_connectable(data[CONF_HOST], data[CONF_TOKEN]):
raise InvalidAuth

DEVICE_CONFIG.extend({vol.Optional(CONF_PLATFORM): str})(data)

name = data[CONF_NAME] if CONF_NAME in data else hub.device_info.model

return {
CONF_HOST: data[CONF_HOST],
CONF_TOKEN: data[CONF_TOKEN],
CONF_MODEL: hub.device_info.model,
CONF_NAME: name,
CONF_MAC: format_mac(hub.device_info.mac_address),
}

Expand Down Expand Up @@ -116,12 +130,13 @@ async def async_step_user(
data = existing_entry.data.copy()
data[CONF_HOST] = info[CONF_HOST]
data[CONF_TOKEN] = info[CONF_TOKEN]
data[CONF_NAME] = info[CONF_NAME]

self.hass.config_entries.async_update_entry(existing_entry, data=data)
await self.hass.config_entries.async_reload(existing_entry.entry_id)
return self.async_abort(reason="already_configured")

return self.async_create_entry(title=info[CONF_MODEL], data=info)
return self.async_create_entry(title=info[CONF_NAME], data=info)

return self.async_show_form(
step_id="user", data_schema=DEVICE_CONFIG, errors=errors
Expand Down
63 changes: 58 additions & 5 deletions custom_components/xiaomi_viomi/const.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,24 @@
"""Constants for Xiaomi Viomi integration."""

from homeassistant.components.vacuum import (
STATE_CLEANING,
STATE_DOCKED,
STATE_IDLE,
STATE_RETURNING,
SUPPORT_BATTERY,
SUPPORT_FAN_SPEED,
SUPPORT_LOCATE,
SUPPORT_PAUSE,
SUPPORT_RETURN_HOME,
SUPPORT_SEND_COMMAND,
SUPPORT_START,
SUPPORT_STATE,
SUPPORT_STOP,
)

DOMAIN = "xiaomi_viomi"
CONF_DEVICE = "device"
CONF_MODEL = "model"
CONF_MAC = "mac"
CONF_FLOW_TYPE = "config_flow_device"

MODELS_VACUUM = ["viomi.vacuum.v8"]

DEVICE_PROPERTIES = [
"battary_life",
"box_type",
Expand Down Expand Up @@ -46,3 +57,45 @@
"hypa_hours",
"hypa_life",
]

ATTR_CLEANING_TIME = "cleaning_time"
ATTR_DO_NOT_DISTURB = "do_not_disturb"
ATTR_DO_NOT_DISTURB_START = "do_not_disturb_start"
ATTR_DO_NOT_DISTURB_END = "do_not_disturb_end"
ATTR_MAIN_BRUSH_LEFT = "main_brush_left"
ATTR_SIDE_BRUSH_LEFT = "side_brush_left"
ATTR_FILTER_LEFT = "filter_left"
ATTR_MOP_LEFT = "mop_left"
ATTR_ERROR = "error"
ATTR_STATUS = "status"
ATTR_MOP_ATTACHED = "mop_attached"

ERRORS_FALSE_POSITIVE = (
0, # Sleeping and not charging,
2103, # Charging
2104, # ? Returning
2105, # Fully charged
2110, # ? Cleaning
)

SUPPORT_VIOMI = (
SUPPORT_PAUSE
| SUPPORT_STOP
| SUPPORT_RETURN_HOME
| SUPPORT_FAN_SPEED
| SUPPORT_BATTERY
| SUPPORT_SEND_COMMAND
| SUPPORT_LOCATE
| SUPPORT_STATE
| SUPPORT_START
)

STATE_CODE_TO_STATE = {
0: STATE_IDLE, # IdleNotDocked
1: STATE_IDLE, # Idle
2: STATE_IDLE, # Idle2
3: STATE_CLEANING, # Cleaning
4: STATE_RETURNING, # Returning
5: STATE_DOCKED, # Docked
6: STATE_CLEANING, # VacuumingAndMopping
}
2 changes: 1 addition & 1 deletion custom_components/xiaomi_viomi/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,5 @@
"construct==2.10.67",
"python-miio==0.5.9"
],
"version": "0.0.3"
"version": "0.0.4"
}
6 changes: 4 additions & 2 deletions custom_components/xiaomi_viomi/strings.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"error": {
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]",
"invalid_auth": "[%key:common::config_flow::error::invalid_auth%]",
"invalid_parameters": "[%key:common::config_flow::error::invalid_auth%]",
"unknown": "[%key:common::config_flow::error::unknown%]"
},
"abort": {
Expand All @@ -13,10 +14,11 @@
"user": {
"data": {
"host": "[%key:common::config_flow::data::host%]",
"token": "[%key:common::config_flow::data::api_token%]"
"token": "[%key:common::config_flow::data::api_token%]",
"name": "[%key:common::config_flow::data::name%]"
},
"description": "You will need the 32 character [%key:common::config_flow::data::api_token%], see https://www.home-assistant.io/integrations/xiaomi_miio#retrieving-the-access-token for instructions. Please note, that this [%key:common::config_flow::data::api_token%] is different from the key used by the Xiaomi Aqara integration.",
"title": "Connect to a Xiaomi Viomi Device2"
"title": "Connect to a Xiaomi Viomi Device"
}
}
}
Expand Down
4 changes: 3 additions & 1 deletion custom_components/xiaomi_viomi/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,16 @@
"error": {
"invalid_auth": "Incomplete information to setup device, no host or token supplied",
"cannot_connect": "Failed to connect",
"invalid_parameters": "Invalid parameters were provided",
"unknown": "Unknown error occurred"
},
"flow_title": "{name}",
"step": {
"user": {
"data": {
"host": "IP Address",
"token": "API Token"
"token": "API Token",
"name": "Name of a device"
},
"description": "You will need the 32 character API Token, see https://www.home-assistant.io/integrations/xiaomi_miio#retrieving-the-access-token for instructions. Please note, that this API Token is different from the key used by the Xiaomi Aqara integration.",
"title": "Connect to a Xiaomi Viomi Device"
Expand Down
4 changes: 3 additions & 1 deletion custom_components/xiaomi_viomi/translations/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"error": {
"invalid_auth": "Неполная информация для настройки устройства, не указан хост или токен",
"cannot_connect": "Не удалось подключиться",
"invalid_parameters": "Предоставлены неверные параметры устройства",
"unknown": "Произошла неизвесная ошибка"
},
"abort": {
Expand All @@ -13,7 +14,8 @@
"user": {
"data": {
"host": "IP-адрес",
"token": "Токен API"
"token": "Токен API",
"name": "Имя устройства"
},
"description": "Для подключения требуется 32-х значный Токен API. О том, как получить токен, Вы можете узнать здесь:\nhttps://www.home-assistant.io/integrations/xiaomi_miio#retrieving-the-access-token.\nОбратите внимание, что этот токен отличается от ключа, используемого при интеграции Xiaomi Aqara.",
"title": "Подключение к устройству Xiaomi Viomi"
Expand Down
4 changes: 3 additions & 1 deletion custom_components/xiaomi_viomi/translations/uk.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"error": {
"invalid_auth": "Неповна інформація для налагодження пристрою, не зазначений хост чи токен",
"cannot_connect": "Не вдалося під'єднатися",
"invalid_parameters": "Надані невірні параметри пристрою",
"unknown": "Трапилась невідома помилка"
},
"abort": {
Expand All @@ -13,7 +14,8 @@
"user": {
"data": {
"host": "IP-адреса",
"token": "Токен API"
"token": "Токен API",
"name": "Ім'я пристрою"
},
"description": "Для підключення потрібно 32-х значний Токен API. Про те, як отримати токен, Ви можете дізнатися тут:\nhttps://www.home-assistant.io/integrations/vacuum.xiaomi_miio/#retrieving-the-access-token.\nЗверніть увагу, що цей токен відрізняється від ключа, який використовується при інтеграції Xiaomi Aqara.",
"title": "Підключення до пристрою Xiaomi Viomi"
Expand Down
Loading

0 comments on commit 5b39eb7

Please sign in to comment.