Skip to content

Commit

Permalink
Merge pull request #30 from KiraPC/dev
Browse files Browse the repository at this point in the history
add debug logs
  • Loading branch information
KiraPC committed Jan 2, 2024
2 parents beb7e97 + eda54f5 commit 5e1aa9c
Show file tree
Hide file tree
Showing 7 changed files with 37 additions and 19 deletions.
5 changes: 5 additions & 0 deletions custom_components/switchbotremote/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""The SwitchBot Remote IR integration."""
from __future__ import annotations

import logging
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
Expand All @@ -19,6 +20,8 @@
Platform.WATER_HEATER,
]

_LOGGER = logging.getLogger(__name__)


async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up SwitchBot Remote IR from a config entry."""
Expand All @@ -28,6 +31,8 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:

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

_LOGGER.debug(f"Configuring remotes: {remotes}")
hass.data[DOMAIN][entry.entry_id] = remotes

await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
Expand Down
9 changes: 8 additions & 1 deletion custom_components/switchbotremote/button.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import humps
import humps, logging
from typing import List
from homeassistant.components.button import ButtonEntity
from homeassistant.core import HomeAssistant
Expand All @@ -19,6 +19,8 @@
CONF_WITH_TEMPERATURE,
)

_LOGGER = logging.getLogger(__name__)


class SwitchBotRemoteButton(ButtonEntity):
_attr_has_entity_name = False
Expand All @@ -32,6 +34,9 @@ def __init__(self, hass: HomeAssistant, sb: SupportedRemote, command_name: str,
self._command_name = command_name
self._command_icon = command_icon

def __repr__(self):
return f"SwitchBotRemoteButton(command={self._command_name}&device={self.device_info})"

async def send_command(self, *args):
await self._hass.async_add_executor_job(self.sb.command, *args)

Expand Down Expand Up @@ -106,6 +111,8 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry, async_add_e
entities.append(SwitchBotRemoteButton(
hass, remote, command, "mdi:remote"))


_LOGGER.debug(f'Adding buttons {entities}')
async_add_entities(entities)

return True
6 changes: 4 additions & 2 deletions custom_components/switchbotremote/client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,17 +41,19 @@ def headers(self):

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

if response.status_code != 200:
_LOGGER.debug("Received error", response.text)
_LOGGER.debug(f"Received http error {response.status_code} {response.text}")
raise RuntimeError(f"SwitchBot API server returns status {response.status_code}")

response_in_json = humps.decamelize(response.json())
if response_in_json["status_code"] != 100:
_LOGGER.debug("Received error", response_in_json)
_LOGGER.debug(f"Received error in response {response_in_json}")
raise RuntimeError(f'An error occurred: {response_in_json["message"]}')

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

def get(self, path: str, **kwargs) -> Any:
Expand Down
8 changes: 5 additions & 3 deletions custom_components/switchbotremote/client/remote.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
from __future__ import annotations

from typing import ClassVar, Dict, Optional, Type

import logging
import humps

from typing import ClassVar, Dict, Optional, Type
from .client import SwitchBotClient

_LOGGER = logging.getLogger(__name__)

class Remote:
remote_type_for: ClassVar[Optional[str]] = None
Expand Down Expand Up @@ -38,6 +38,7 @@ def command(
parameter: Optional[str] = None,
customize: Optional[bool] = False
):
_LOGGER.debug(f"Sending command {action}")
parameter = "default" if parameter is None else parameter
command_type = "customize" if customize else "command"
payload = humps.camelize(
Expand All @@ -48,6 +49,7 @@ def command(
}
)

_LOGGER.debug(f"Command payload {payload}")
self.client.post(f"devices/{self.id}/commands", json=payload)

def __repr__(self):
Expand Down
1 change: 1 addition & 0 deletions custom_components/switchbotremote/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str,

try:
remotes = await hass.async_add_executor_job(switchbot.remotes)
_LOGGER.debug(f"Found remotes: {remotes}")
return {"title": data["name"], "remotes": remotes}
except:
raise InvalidAuth()
Expand Down
26 changes: 13 additions & 13 deletions custom_components/switchbotremote/media_player.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,22 +111,22 @@ async def async_turn_off(self):
self._state = STATE_OFF
self._source = None

await self.async_update_ha_state()
self.async_write_ha_state()

async def async_turn_on(self):
"""Turn the media player off."""
await self.send_command("turnOn")

self._state = STATE_IDLE if self.sb.type in IR_TRACK_TYPES else STATE_ON
await self.async_update_ha_state()
self.async_write_ha_state()

async def async_media_previous_track(self):
"""Send previous track command."""
if self.sb.type in IR_TRACK_TYPES:
await self.send_command("Previous")
else:
await self.send_command("channelSub")
await self.async_update_ha_state()
self.async_write_ha_state()

async def async_media_next_track(self):
"""Send next track command."""
Expand All @@ -135,7 +135,7 @@ async def async_media_next_track(self):
await self.send_command("Next")
else:
await self.send_command("channelAdd")
await self.async_update_ha_state()
self.async_write_ha_state()

async def async_volume_down(self):
"""Turn volume down for media player."""
Expand All @@ -144,7 +144,7 @@ async def async_volume_down(self):
else:
await self.send_command("volumeSub")

await self.async_update_ha_state()
self.async_write_ha_state()

async def async_volume_up(self):
"""Turn volume up for media player."""
Expand All @@ -153,7 +153,7 @@ async def async_volume_up(self):
else:
await self.send_command("volumeAdd")

await self.async_update_ha_state()
self.async_write_ha_state()

async def async_mute_volume(self, mute):
"""Mute the volume."""
Expand All @@ -162,7 +162,7 @@ async def async_mute_volume(self, mute):
else:
await self.send_command("setMute")

await self.async_update_ha_state()
self.async_write_ha_state()

async def async_media_play(self):
"""Play/Resume media"""
Expand All @@ -173,7 +173,7 @@ async def async_media_play(self):
else:
await self.send_command("Play")

await self.async_update_ha_state()
self.async_write_ha_state()

async def async_media_pause(self):
"""Pause media"""
Expand All @@ -184,19 +184,19 @@ async def async_media_pause(self):
else:
await self.send_command("Pause")

await self.async_update_ha_state()
self.async_write_ha_state()

async def async_media_play_pause(self):
"""Play/Pause media"""
self._state = STATE_PLAYING
await self.send_command("Play")
await self.async_update_ha_state()
self.async_write_ha_state()

async def async_media_stop(self):
"""Stop media"""
self._state = STATE_IDLE
await self.send_command("Stop")
await self.async_update_ha_state()
self.async_write_ha_state()

async def async_play_media(self, media_type, media_id, **kwargs):
"""Support channel change through play_media service."""
Expand All @@ -210,7 +210,7 @@ async def async_play_media(self, media_type, media_id, **kwargs):
self._source = "Channel {}".format(media_id)
for digit in media_id:
await self.send_command("SetChannel", digit, True)
await self.async_update_ha_state()
self.async_write_ha_state()

@callback
def _async_update_power(self, state):
Expand All @@ -232,7 +232,7 @@ async def _async_power_sensor_changed(self, entity_id, old_state, new_state):
return

self._async_update_power(new_state)
await self.async_update_ha_state()
self.async_write_ha_state()

async def async_added_to_hass(self):
"""Run when entity about to be added."""
Expand Down
1 change: 1 addition & 0 deletions custom_components/switchbotremote/remote.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry, async_add_e
if (remote.type == OTHERS_TYPE and options.get("on_command", None)):
entities.append(SwitchBotRemoteOther(remote, options))

_LOGGER.debug(f'Adding remotes {entities}')
async_add_entities(entities)

return True

0 comments on commit 5e1aa9c

Please sign in to comment.