diff options
-rw-r--r-- | custom_components/skykettle/ble_scan.py | 57 | ||||
-rw-r--r-- | custom_components/skykettle/config_flow.py | 20 | ||||
-rw-r--r-- | custom_components/skykettle/translations/en.json | 5 | ||||
-rw-r--r-- | custom_components/skykettle/translations/ru.json | 5 |
4 files changed, 3 insertions, 84 deletions
diff --git a/custom_components/skykettle/ble_scan.py b/custom_components/skykettle/ble_scan.py deleted file mode 100644 index 7f9a11d..0000000 --- a/custom_components/skykettle/ble_scan.py +++ /dev/null @@ -1,57 +0,0 @@ -import subprocess -import asyncio -import shlex -import re -from collections import namedtuple - -REGEX_MAC = r"^(([0-9a-fA-F]){2}[:-]?){5}[0-9a-fA-F]{2}$" - -BleDevice = namedtuple("BleDevice", ["mac", "name"]) -BleAdapter = namedtuple("BleAdapter", ["name", "mac"]) - - -async def ble_scan(device, scan_time=3): - devopt = "" - if device: devopt = f"-i {shlex.quote(device)}" - proc = await asyncio.create_subprocess_shell( - f"timeout -s INT {int(scan_time)}s hcitool {devopt} lescan", - stdout=asyncio.subprocess.PIPE, - stderr=asyncio.subprocess.PIPE) - stdout, stderr = await proc.communicate() - out_lines = stdout.decode('utf-8').split('\n') - err = stderr.decode('utf-8') - - res = [] - for l in out_lines: - cols = l.split(maxsplit=2) - if len(cols) >= 2 and re.match(REGEX_MAC, cols[0]): - mac = cols[0] - name = cols[1].replace('_',' ') - if name == "(unknown)": name = None - if len([l for l in res if l.mac == mac]) == 0: - res.append(BleDevice(mac, name)) - - if err and not res: - if "Operation not permitted" in err: - raise PermissionError(err) - else: - raise Exception(err) - - return res - -async def ble_get_adapters(): - proc = await asyncio.create_subprocess_shell( - "hcitool dev", - stdout=asyncio.subprocess.PIPE, - stderr=asyncio.subprocess.PIPE) - stdout, stderr = await proc.communicate() - out_lines = stdout.decode('utf-8').split('\n') - err = stderr.decode('utf-8') - if err: raise Exception(err) - - devices = [] - for line in out_lines: - cols = line.split() - if len(cols) >= 2 and re.match(REGEX_MAC, cols[1]): - devices.append(BleAdapter(cols[0], cols[1])) - return devices diff --git a/custom_components/skykettle/config_flow.py b/custom_components/skykettle/config_flow.py index 32e6bc1..93c45cc 100644 --- a/custom_components/skykettle/config_flow.py +++ b/custom_components/skykettle/config_flow.py @@ -6,15 +6,13 @@ import traceback import sys import asyncio import subprocess -from homeassistant.components import bluetooth import voluptuous as vol +from homeassistant.components import bluetooth from homeassistant.const import * -import homeassistant.helpers.config_validation as cv from homeassistant import config_entries from homeassistant.core import callback +import homeassistant.helpers.config_validation as cv from .const import * -from .ble_scan import ble_scan -from .ble_scan import ble_get_adapters from .kettle_connection import KettleConnection from .skykettle import SkyKettle @@ -52,17 +50,8 @@ class SkyKettleConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): async def async_step_user(self, user_input=None): """Handle the user step.""" - return await self.async_step_scan_message() + return await self.async_step_scan() - async def async_step_scan_message(self, user_input=None): - """Handle the scan_message step.""" - if user_input is not None: - return await self.async_step_scan() - return self.async_show_form( - step_id="scan_message", - data_schema=vol.Schema({}) - ) - async def async_step_scan(self, user_input=None): """Handle the scan step.""" errors = {} @@ -82,9 +71,6 @@ class SkyKettleConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): try: scanner = bluetooth.async_get_scanner(self.hass) - await scanner.start() - await asyncio.sleep(5) - await scanner.stop() for device in scanner.discovered_devices: _LOGGER.debug(f"Device found: {device.address} - {device.name}") devices_filtered = [device for device in scanner.discovered_devices if device.name and (device.name.startswith("RK-") or device.name.startswith("RFS-"))] diff --git a/custom_components/skykettle/translations/en.json b/custom_components/skykettle/translations/en.json index bf22998..284efdb 100644 --- a/custom_components/skykettle/translations/en.json +++ b/custom_components/skykettle/translations/en.json @@ -4,11 +4,6 @@ "abort": { "kettle_not_found": "Can't find any supported kettle. Please make sure that your kettle is in the list of supported devices and it's on the stand.", "already_configured": "Integration for this kettle is already configured.", - "linux_not_found": "Sorry, Linux-based system required.", - "hcitool_not_found": "hcitool binary not found.", - "hatttool_not_found": "hatttool binary not found.", - "timeout_not_found": "\"timeout\" binary not found.", - "permission_error": "Permission error, make sure that hcitool and hatttool are granted with privileges (check instructions).", "unknown_model": "Your kettle model is not yet supported by this integration. But you can help add support for it! Contact the author via the 'issues' section on GitHub ('report an issue' in HACS).", "unknown": "Unknown error, please check logs." }, diff --git a/custom_components/skykettle/translations/ru.json b/custom_components/skykettle/translations/ru.json index de21347..9732312 100644 --- a/custom_components/skykettle/translations/ru.json +++ b/custom_components/skykettle/translations/ru.json @@ -4,11 +4,6 @@ "abort": { "kettle_not_found": "Не могу найти чайник. Пожалуйста, убедитесь, что модель вашего чайника есть в списке поддерживаемых, и что он стоит на подставке.", "already_configured": "Для этого чайника интеграция уже настроена.", - "linux_not_found": "Извините, эта интеграция может работать только под Linux.", - "hcitool_not_found": "Утилита \"hcitool\" не найдена.", - "hatttool_not_found": "Утилита \"hatttool\" не найдена.", - "timeout_not_found": "Утилита \"timeout\" не найдена.", - "permission_error": "Отсутствуют права доступа, убедитесь в том, что утилитам \"hcitool\" и \"hatttool\" предоставлены права на доступ к BLE (смотрите инструкцию).", "unknown_model": "Модель вашего чайника пока что не поддерживается этой интеграцией. Но вы можете помочь добавить его поддержку! Свяжитесь с автором через раздел 'issues' на GitHub ('сообщить о проблеме' в HACS).", "unknown": "Неизвестная ошибка, смотрите логи." }, |