Skip to content

Commit

Permalink
Merge pull request #62 from KiraPC/dev
Browse files Browse the repository at this point in the history
Merge dev in main
  • Loading branch information
KiraPC authored Dec 17, 2024
2 parents e013350 + c1ff313 commit 17e9856
Show file tree
Hide file tree
Showing 4 changed files with 71 additions and 36 deletions.
8 changes: 6 additions & 2 deletions custom_components/switchbotremote/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from .client import SwitchBot
from .client import SwitchBot, switchbot_host

from .const import DOMAIN
from homeassistant.helpers import (
Expand All @@ -32,7 +32,11 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:

entry.add_update_listener(update_listener)

switchbot = SwitchBot(token=entry.data["token"], secret=entry.data["secret"])
switchbot = SwitchBot(
token=entry.data["token"],
secret=entry.data["secret"],
host=entry.data.get("host", switchbot_host)
)
remotes = await hass.async_add_executor_job(switchbot.remotes)

_LOGGER.debug(f"Configuring remotes: {remotes}")
Expand Down
6 changes: 3 additions & 3 deletions custom_components/switchbotremote/client/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import uuid
from typing import List

from .client import SwitchBotClient
from .client import SwitchBotClient, switchbot_host
from .remote import Remote

from homeassistant.exceptions import ServiceValidationError
Expand All @@ -10,8 +10,8 @@


class SwitchBot:
def __init__(self, token: str, secret: str):
self.client = SwitchBotClient(token, secret, nonce=str(uuid.uuid4()))
def __init__(self, token: str, secret: str, host=switchbot_host):
self.client = SwitchBotClient(token, secret, nonce=str(uuid.uuid4()), host=host)

def remotes(self) -> List[Remote]:
response = self.client.get("devices")
Expand Down
10 changes: 6 additions & 4 deletions custom_components/switchbotremote/client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,15 @@
from homeassistant.exceptions import HomeAssistantError

_LOGGER = logging.getLogger(__name__)
switchbot_host = "https://api.switch-bot.com/v1.1"
switchbot_host = "https://api.switch-bot.com"
api_version = "v1.1"

MAX_TRIES = 5
DELAY_BETWEEN_TRIES_MS = 500

class SwitchBotClient:
def __init__(self, token: str, secret: str, nonce: str):
def __init__(self, token: str, secret: str, nonce: str, host=switchbot_host):
self._host = host
self._token = token
self._secret = secret
self._nonce = nonce
Expand All @@ -45,7 +47,7 @@ def headers(self):
return headers

def __request(self, method: str, path: str, **kwargs) -> Any:
url = f"{switchbot_host}/{path}"
url = f"{self._host}/{api_version}/{path}"
_LOGGER.debug(f"Calling service {url}")
response = request(method, url, headers=self.headers, **kwargs)

Expand All @@ -63,7 +65,7 @@ def __request(self, method: str, path: str, **kwargs) -> Any:

_LOGGER.debug(f"Call service {url} OK")
return response_in_json

def request(self, method: str, path: str, maxNumberOfTrials: int = MAX_TRIES, delayMSBetweenTrials: int = DELAY_BETWEEN_TRIES_MS, **kwargs) -> Any:
"""Try to send the request.
If the server returns a 500 Internal error status, will retry until it succeeds or it passes a threshold of max number of tries.
Expand Down
83 changes: 56 additions & 27 deletions custom_components/switchbotremote/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,43 +7,40 @@
import voluptuous as vol

from homeassistant import config_entries
from homeassistant.components.climate.const import HVACMode
from homeassistant.core import HomeAssistant, callback
from homeassistant.data_entry_flow import FlowResult
from homeassistant.exceptions import HomeAssistantError
from homeassistant.exceptions import ConfigEntryAuthFailed, HomeAssistantError
from homeassistant.helpers.selector import selector
from homeassistant.components.climate.const import HVACMode
from homeassistant.exceptions import ConfigEntryAuthFailed
from .client import SwitchBot

from .client import SwitchBot, switchbot_host
from .const import (
DOMAIN,
CLASS_BY_TYPE,

AIR_CONDITIONER_CLASS,
FAN_CLASS,
LIGHT_CLASS,
MEDIA_CLASS,
CAMERA_CLASS,
VACUUM_CLASS,
WATER_HEATER_CLASS,
OTHERS_CLASS,

CONF_POWER_SENSOR,
CONF_TEMPERATURE_SENSOR,
CLASS_BY_TYPE,
CONF_CUSTOMIZE_COMMANDS,
CONF_HUMIDITY_SENSOR,
CONF_TEMP_MIN,
CONF_HVAC_MODES,
CONF_OFF_COMMAND,
CONF_ON_COMMAND,
CONF_OVERRIDE_OFF_COMMAND,
CONF_POWER_SENSOR,
CONF_TEMP_MAX,
CONF_TEMP_MIN,
CONF_TEMP_STEP,
CONF_HVAC_MODES,
CONF_CUSTOMIZE_COMMANDS,
CONF_WITH_SPEED,
CONF_WITH_ION,
CONF_WITH_TIMER,
CONF_TEMPERATURE_SENSOR,
CONF_WITH_BRIGHTNESS,
CONF_WITH_ION,
CONF_WITH_SPEED,
CONF_WITH_TEMPERATURE,
CONF_ON_COMMAND,
CONF_OFF_COMMAND,
CONF_OVERRIDE_OFF_COMMAND,
CONF_WITH_TIMER,
DOMAIN,
FAN_CLASS,
LIGHT_CLASS,
MEDIA_CLASS,
OTHERS_CLASS,
VACUUM_CLASS,
WATER_HEATER_CLASS,
)

DEFAULT_HVAC_MODES = [
Expand All @@ -68,6 +65,7 @@

STEP_USER_DATA_SCHEMA = vol.Schema(
{
vol.Required("host", default=switchbot_host): str,
vol.Required("name"): str,
vol.Required("token"): str,
vol.Required("secret"): str,
Expand Down Expand Up @@ -126,7 +124,11 @@


async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str, Any]:
switchbot = SwitchBot(token=data["token"], secret=data["secret"])
switchbot = SwitchBot(
token=data["token"],
secret=data["secret"],
host=data.get("host", switchbot_host)
)

try:
remotes = await hass.async_add_executor_job(switchbot.remotes)
Expand All @@ -147,6 +149,30 @@ def async_get_options_flow(config_entry):
"""Get options flow for this handler."""
return OptionsFlowHandler(config_entry)

async def async_step_reconfigure(self, user_input: dict[str, Any] | None = None):
if user_input is not None:
name = user_input["name"]
uniq_id = f"switchbot_remote_{name}"
await self.async_set_unique_id(uniq_id)
return self.async_update_reload_and_abort(
self._get_reconfigure_entry(),
data_updates=user_input,
)

old_entry = self._get_reconfigure_entry()

return self.async_show_form(
step_id="reconfigure",
data_schema=vol.Schema(
{
vol.Required("host", default=old_entry.data.get('host', switchbot_host)): str,
vol.Required("name", default=old_entry.data['name']): str,
vol.Required("token", default=old_entry.data['token']): str,
vol.Required("secret", default=old_entry.data['secret']): str,
}
)
)

async def async_step_user(self, user_input: dict[str, Any] | None = None) -> FlowResult:
"""Handle the initial step."""
errors: dict[str, str] = {}
Expand Down Expand Up @@ -178,7 +204,10 @@ def __init__(self, config_entry: config_entries.ConfigEntry) -> None:

self.data = config_entry.data
self.sb = SwitchBot(
token=self.data["token"], secret=self.data["secret"])
token=self.data["token"],
secret=self.data["secret"],
host=self.data.get("host", switchbot_host)
)
self.discovered_devices = []
self.selected_device = None

Expand Down

0 comments on commit 17e9856

Please sign in to comment.