Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .coveragerc
Original file line number Diff line number Diff line change
Expand Up @@ -1256,6 +1256,7 @@ omit =
homeassistant/components/switchbot/light.py
homeassistant/components/switchbot/sensor.py
homeassistant/components/switchbot/switch.py
homeassistant/components/switchbot/lock.py
homeassistant/components/switchmate/switch.py
homeassistant/components/syncthing/__init__.py
homeassistant/components/syncthing/sensor.py
Expand Down
27 changes: 22 additions & 5 deletions homeassistant/components/switchbot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
from homeassistant.helpers import device_registry as dr

from .const import (
CONF_ENCRYPTION_KEY,
CONF_KEY_ID,
CONF_RETRY_COUNT,
CONNECTABLE_SUPPORTED_MODEL_TYPES,
DEFAULT_RETRY_COUNT,
Expand All @@ -43,6 +45,7 @@
SupportedModels.CONTACT.value: [Platform.BINARY_SENSOR, Platform.SENSOR],
SupportedModels.MOTION.value: [Platform.BINARY_SENSOR, Platform.SENSOR],
SupportedModels.HUMIDIFIER.value: [Platform.HUMIDIFIER, Platform.SENSOR],
SupportedModels.LOCK.value: [Platform.BINARY_SENSOR, Platform.LOCK],
}
CLASS_BY_DEVICE = {
SupportedModels.CEILING_LIGHT.value: switchbot.SwitchbotCeilingLight,
Expand All @@ -52,6 +55,7 @@
SupportedModels.BULB.value: switchbot.SwitchbotBulb,
SupportedModels.LIGHT_STRIP.value: switchbot.SwitchbotLightStrip,
SupportedModels.HUMIDIFIER.value: switchbot.SwitchbotHumidifier,
SupportedModels.LOCK.value: switchbot.SwitchbotLock,
}


Expand Down Expand Up @@ -94,11 +98,24 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:

await switchbot.close_stale_connections(ble_device)
cls = CLASS_BY_DEVICE.get(sensor_type, switchbot.SwitchbotDevice)
device = cls(
device=ble_device,
password=entry.data.get(CONF_PASSWORD),
retry_count=entry.options[CONF_RETRY_COUNT],
)
if cls is switchbot.SwitchbotLock:
try:
device = switchbot.SwitchbotLock(
device=ble_device,
key_id=entry.data.get(CONF_KEY_ID),
encryption_key=entry.data.get(CONF_ENCRYPTION_KEY),
retry_count=entry.options[CONF_RETRY_COUNT],
)
except ValueError as error:
raise ConfigEntryNotReady(
"Invalid encryption configuration provided"
) from error
Comment thread
bdraco marked this conversation as resolved.
else:
device = cls(
device=ble_device,
password=entry.data.get(CONF_PASSWORD),
retry_count=entry.options[CONF_RETRY_COUNT],
)

coordinator = hass.data[DOMAIN][entry.entry_id] = SwitchbotDataUpdateCoordinator(
hass,
Expand Down
22 changes: 22 additions & 0 deletions homeassistant/components/switchbot/binary_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,28 @@
name="Light",
device_class=BinarySensorDeviceClass.LIGHT,
),
"door_open": BinarySensorEntityDescription(
key="door_status",
name="Door status",
device_class=BinarySensorDeviceClass.DOOR,
),
"unclosed_alarm": BinarySensorEntityDescription(
key="unclosed_alarm",
name="Door unclosed alarm",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=BinarySensorDeviceClass.PROBLEM,
),
"unlocked_alarm": BinarySensorEntityDescription(
key="unlocked_alarm",
name="Door unlocked alarm",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=BinarySensorDeviceClass.PROBLEM,
),
"auto_lock_paused": BinarySensorEntityDescription(
key="auto_lock_paused",
name="Door auto-lock paused",
entity_category=EntityCategory.DIAGNOSTIC,
),
}


Expand Down
46 changes: 45 additions & 1 deletion homeassistant/components/switchbot/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@
import logging
from typing import Any

from switchbot import SwitchBotAdvertisement, parse_advertisement_data
from switchbot import (
SwitchBotAdvertisement,
SwitchbotLock,
SwitchbotModel,
parse_advertisement_data,
)
import voluptuous as vol

from homeassistant.components.bluetooth import (
Expand All @@ -17,6 +22,8 @@
from homeassistant.data_entry_flow import AbortFlow, FlowResult

from .const import (
CONF_ENCRYPTION_KEY,
CONF_KEY_ID,
CONF_RETRY_COUNT,
CONNECTABLE_SUPPORTED_MODEL_TYPES,
DEFAULT_RETRY_COUNT,
Expand Down Expand Up @@ -144,6 +151,39 @@ async def async_step_password(
},
)

async def async_step_lock_key(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Handle the encryption key step."""
errors = {}
assert self._discovered_adv is not None
if user_input is not None:
if not await SwitchbotLock.verify_encryption_key(
self._discovered_adv.device,
user_input.get(CONF_KEY_ID),
user_input.get(CONF_ENCRYPTION_KEY),
):
errors = {
CONF_KEY_ID: "key_id_invalid",
CONF_ENCRYPTION_KEY: "encryption_key_invalid",
}
else:
return await self._async_create_entry_from_discovery(user_input)

return self.async_show_form(
step_id="lock_key",
errors=errors,
data_schema=vol.Schema(
{
vol.Required(CONF_KEY_ID): str,
vol.Required(CONF_ENCRYPTION_KEY): str,
}
),
description_placeholders={
"name": name_from_discovery(self._discovered_adv),
},
)

@callback
def _async_discover_devices(self) -> None:
current_addresses = self._async_current_ids()
Expand Down Expand Up @@ -188,6 +228,8 @@ async def async_step_user(
if user_input is not None:
device_adv = self._discovered_advs[user_input[CONF_ADDRESS]]
await self._async_set_device(device_adv)
if device_adv.data.get("modelName") == SwitchbotModel.LOCK:
return await self.async_step_lock_key()
Comment thread
bdraco marked this conversation as resolved.
if device_adv.data["isEncrypted"]:
return await self.async_step_password()
return await self._async_create_entry_from_discovery(user_input)
Expand All @@ -198,6 +240,8 @@ async def async_step_user(
# or simply confirm it
device_adv = list(self._discovered_advs.values())[0]
await self._async_set_device(device_adv)
if device_adv.data.get("modelName") == SwitchbotModel.LOCK:
return await self.async_step_lock_key()
if device_adv.data["isEncrypted"]:
return await self.async_step_password()
return await self.async_step_confirm()
Expand Down
4 changes: 4 additions & 0 deletions homeassistant/components/switchbot/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ class SupportedModels(StrEnum):
PLUG = "plug"
MOTION = "motion"
HUMIDIFIER = "humidifier"
LOCK = "lock"


CONNECTABLE_SUPPORTED_MODEL_TYPES = {
Expand All @@ -34,6 +35,7 @@ class SupportedModels(StrEnum):
SwitchbotModel.LIGHT_STRIP: SupportedModels.LIGHT_STRIP,
SwitchbotModel.CEILING_LIGHT: SupportedModels.CEILING_LIGHT,
SwitchbotModel.HUMIDIFIER: SupportedModels.HUMIDIFIER,
SwitchbotModel.LOCK: SupportedModels.LOCK,
}

NON_CONNECTABLE_SUPPORTED_MODEL_TYPES = {
Expand All @@ -56,6 +58,8 @@ class SupportedModels(StrEnum):

# Config Options
CONF_RETRY_COUNT = "retry_count"
CONF_KEY_ID = "key_id"
CONF_ENCRYPTION_KEY = "encryption_key"

# Deprecated config Entry Options to be removed in 2023.4
CONF_TIME_BETWEEN_UPDATE_COMMAND = "update_time"
Expand Down
55 changes: 55 additions & 0 deletions homeassistant/components/switchbot/lock.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
"""Support for SwitchBot lock platform."""
from typing import Any

import switchbot
from switchbot.const import LockStatus

from homeassistant.components.lock import LockEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback

from .const import DOMAIN
from .coordinator import SwitchbotDataUpdateCoordinator
from .entity import SwitchbotEntity


async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
"""Set up Switchbot lock based on a config entry."""
coordinator: SwitchbotDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id]
async_add_entities([(SwitchBotLock(coordinator))])


# noinspection PyAbstractClass
class SwitchBotLock(SwitchbotEntity, LockEntity):
"""Representation of a Switchbot lock."""

_device: switchbot.SwitchbotLock

def __init__(self, coordinator: SwitchbotDataUpdateCoordinator) -> None:
"""Initialize the entity."""
super().__init__(coordinator)
self._async_update_attrs()

def _async_update_attrs(self) -> None:
"""Update the entity attributes."""
status = self._device.get_lock_status()
self._attr_is_locked = status is LockStatus.LOCKED
self._attr_is_locking = status is LockStatus.LOCKING
self._attr_is_unlocking = status is LockStatus.UNLOCKING
self._attr_is_jammed = status in {
LockStatus.LOCKING_STOP,
LockStatus.UNLOCKING_STOP,
}

async def async_lock(self, **kwargs: Any) -> None:
"""Lock the lock."""
self._last_run_success = await self._device.lock()
self.async_write_ha_state()

async def async_unlock(self, **kwargs: Any) -> None:
"""Unlock the lock."""
self._last_run_success = await self._device.unlock()
self.async_write_ha_state()
2 changes: 1 addition & 1 deletion homeassistant/components/switchbot/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"domain": "switchbot",
"name": "SwitchBot",
"documentation": "https://www.home-assistant.io/integrations/switchbot",
"requirements": ["PySwitchbot==0.31.0"],
"requirements": ["PySwitchbot==0.33.0"],
"config_flow": true,
"dependencies": ["bluetooth"],
"codeowners": [
Expand Down
12 changes: 11 additions & 1 deletion homeassistant/components/switchbot/strings.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,19 @@
"data": {
"password": "[%key:common::config_flow::data::password%]"
}
},
"lock_key": {
"description": "The {name} device requires encryption key, details on how to obtain it can be found in the documentation.",
"data": {
"key_id": "Key ID",
"encryption_key": "Encryption key"
}
}
},
"error": {},
"error": {
"key_id_invalid": "Key ID or Encryption key is invalid",
"encryption_key_invalid": "Key ID or Encryption key is invalid"
},
"abort": {
"already_configured_device": "[%key:common::config_flow::abort::already_configured_device%]",
"no_unconfigured_devices": "No unconfigured devices found.",
Expand Down
11 changes: 11 additions & 0 deletions homeassistant/components/switchbot/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,18 @@
"data": {
"address": "Device address"
}
},
"lock_key": {
"description": "The {name} device requires encryption key, details on how to obtain it can be found in the documentation.",
"data": {
"key_id": "Key ID",
"encryption_key": "Encryption key"
}
}
},
"error": {
"key_id_invalid": "Key ID or Encryption key is invalid",
"encryption_key_invalid": "Key ID or Encryption key is invalid"
}
},
"options": {
Expand Down
2 changes: 1 addition & 1 deletion requirements_all.txt
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ PyRMVtransport==0.3.3
PySocks==1.7.1

# homeassistant.components.switchbot
PySwitchbot==0.31.0
PySwitchbot==0.33.0

# homeassistant.components.transport_nsw
PyTransportNSW==0.1.1
Expand Down
2 changes: 1 addition & 1 deletion requirements_test_all.txt
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ PyRMVtransport==0.3.3
PySocks==1.7.1

# homeassistant.components.switchbot
PySwitchbot==0.31.0
PySwitchbot==0.33.0

# homeassistant.components.transport_nsw
PyTransportNSW==0.1.1
Expand Down
20 changes: 20 additions & 0 deletions tests/components/switchbot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,26 @@ async def init_integration(
connectable=False,
)


WOLOCK_SERVICE_INFO = BluetoothServiceInfoBleak(
name="WoLock",
manufacturer_data={2409: b"\xf1\t\x9fE\x1a]\xda\x83\x00 "},
service_data={"0000fd3d-0000-1000-8000-00805f9b34fb": b"o\x80d"},
service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"],
address="798A8547-2A3D-C609-55FF-73FA824B923B",
rssi=-60,
source="local",
advertisement=generate_advertisement_data(
local_name="WoLock",
manufacturer_data={2409: b"\xf1\t\x9fE\x1a]\xda\x83\x00 "},
service_data={"00000d00-0000-1000-8000-00805f9b34fb": b"o\x80d"},
service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"],
),
device=BLEDevice("798A8547-2A3D-C609-55FF-73FA824B923B", "WoLock"),
time=0,
connectable=True,
)

NOT_SWITCHBOT_INFO = BluetoothServiceInfoBleak(
name="unknown",
service_uuids=[],
Expand Down
Loading