Skip to content

Commit

Permalink
Clean-up of code (part 1)
Browse files Browse the repository at this point in the history
  • Loading branch information
theneweinstein committed Jan 6, 2024
1 parent 5dc8707 commit 79796a4
Show file tree
Hide file tree
Showing 14 changed files with 200 additions and 172 deletions.
73 changes: 49 additions & 24 deletions .devcontainer.json
Original file line number Diff line number Diff line change
@@ -1,47 +1,72 @@
{
"name": "ludeeus/integration_blueprint",
"image": "mcr.microsoft.com/vscode/devcontainers/python:0-3.11",
"image": "mcr.microsoft.com/vscode/devcontainers/python:3.11",
"postCreateCommand": "scripts/setup",
// "forwardPorts": [
// 8123,
// 5353,
// 1900
// ],
"forwardPorts": [
8123
],
"portsAttributes": {
"8123": {
"label": "Home Assistant",
"onAutoForward": "notify"
}
},
"runArgs": [
"--network=host"
],
"customizations": {
"vscode": {
"extensions": [
"ms-python.python",
"github.vscode-pull-request-github",
"ryanluker.vscode-coverage-gutters",
"ms-python.vscode-pylance"
//"ms-python.python",
//"github.vscode-pull-request-github",
//"ryanluker.vscode-coverage-gutters",
//"ms-python.vscode-pylance",
"charliermarsh.ruff",
"ms-python.pylint",
"ms-python.vscode-pylance",
"visualstudioexptteam.vscodeintellicode",
"redhat.vscode-yaml",
"esbenp.prettier-vscode",
"GitHub.vscode-pull-request-github"
],
"settings": {
"files.eol": "\n",
"editor.tabSize": 4,
"python.pythonPath": "/usr/bin/python3",
"python.analysis.autoSearchPaths": false,
"python.linting.pylintEnabled": true,
"python.linting.enabled": true,
"python.formatting.provider": "black",
"python.formatting.blackPath": "/usr/local/py-utils/bin/black",
//"files.eol": "\n",
//"editor.tabSize": 4,
//"python.pythonPath": "/usr/bin/python3",
//"python.analysis.autoSearchPaths": false,
//"pylint.enabled": true,
//"python.linting.enabled": true,
//"python.formatting.provider": "black",
//"python.formatting.blackPath": "/usr/local/py-utils/bin/black",
//"editor.formatOnPaste": false,
//"editor.formatOnSave": true,
//"editor.formatOnType": true,
//"files.trimTrailingWhitespace": true
"python.pythonPath": "/usr/local/bin/python",
"python.testing.pytestArgs": ["--no-cov"],
"editor.formatOnPaste": false,
"editor.formatOnSave": true,
"editor.formatOnType": true,
"files.trimTrailingWhitespace": true
"files.trimTrailingWhitespace": true,
"terminal.integrated.profiles.linux": {
"zsh": {
"path": "/usr/bin/zsh"
}
},
"terminal.integrated.defaultProfile.linux": "zsh",
"yaml.customTags": [
"!input scalar",
"!secret scalar",
"!include_dir_named scalar",
"!include_dir_list scalar",
"!include_dir_merge_list scalar",
"!include_dir_merge_named scalar"
],
"[python]": {
"editor.defaultFormatter": "charliermarsh.ruff"
}
}
}
},
},
"remoteUser": "vscode",
"features": {
"ghcr.io/devcontainers/features/rust:1": {}
}
}
}
87 changes: 37 additions & 50 deletions custom_components/somneo/__init__.py
Original file line number Diff line number Diff line change
@@ -1,39 +1,38 @@
""" Support for Philips Somneo devices."""
"""Support for Philips Somneo devices."""
from __future__ import annotations

import asyncio
from datetime import timedelta, time
import functools as ft
import logging

from pysomneo import Somneo, SOURCES
from datetime import time, timedelta

from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_HOST, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers.debounce import Debouncer
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
from pysomneo import SOURCES, Somneo

from .const import DOMAIN

_LOGGER = logging.getLogger(__name__)

PLATFORMS = [
Platform.BUTTON,
Platform.LIGHT,
Platform.MEDIA_PLAYER,
Platform.NUMBER,
Platform.SELECT,
Platform.SENSOR,
Platform.SWITCH,
Platform.TEXT,
Platform.TIME,
Platform.BUTTON,
Platform.MEDIA_PLAYER,
Platform.TEXT
]
SCAN_INTERVAL = timedelta(seconds=60)


async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Setup the Somneo component."""
"""Set up the Somneo component."""
host = entry.data[CONF_HOST]

coordinator = SomneoCoordinator(hass, host)
Expand Down Expand Up @@ -85,7 +84,7 @@ async def async_migrate_entry(hass, config_entry: ConfigEntry):

if config_entry.version == 3:
new = {**config_entry.data}
new['options'].pop('use_session')
new["options"].pop("use_session")

config_entry.version = 4
hass.config_entries.async_update_entry(config_entry, data=new)
Expand All @@ -98,11 +97,7 @@ async def async_migrate_entry(hass, config_entry: ConfigEntry):
class SomneoCoordinator(DataUpdateCoordinator[None]):
"""Representation of a Somneo Coordinator."""

def __init__(
self,
hass: HomeAssistant,
host: str
) -> None:
def __init__(self, hass: HomeAssistant, host: str) -> None:
"""Initialize Somneo client."""
self.somneo = Somneo(host)
self.state_lock = asyncio.Lock()
Expand All @@ -125,22 +120,22 @@ async def _async_update(self):

return await self.hass.async_add_executor_job(self.somneo.fetch_data)

async def async_toggle_light(self, state: bool, brightness: int | None = None) -> None:
async def async_toggle_light(
self, state: bool, brightness: int | None = None
) -> None:
"""Toggle the main light."""
async with self.state_lock:
await self.hass.async_add_executor_job(
ft.partial(
self.somneo.toggle_light,
state,
brightness = brightness
)
ft.partial(self.somneo.toggle_light, state, brightness=brightness)
)
await self.async_request_refresh()

async def async_toggle_nightlight(self, state: bool) -> None:
"""Toggle the night light."""
async with self.state_lock:
await self.hass.async_add_executor_job(self.somneo.toggle_night_light, state)
await self.hass.async_add_executor_job(
self.somneo.toggle_night_light, state
)
await self.async_request_refresh()

async def async_toggle_alarm(self, alarm: str, state: bool) -> None:
Expand All @@ -158,17 +153,12 @@ async def async_dismiss_alarm(self) -> None:
await self.async_request_refresh()

async def async_set_alarm(
self, alarm: str, time: time | None = None, days: str | list | None = None
self, alarm: str, alarm_time: time | None = None, days: str | list | None = None
):
"""Set alarm time."""
async with self.state_lock:
await self.hass.async_add_executor_job(
ft.partial(
self.somneo.set_alarm,
alarm,
time = time,
days = days
)
ft.partial(self.somneo.set_alarm, alarm, time=alarm_time, days=days)
)
await self.async_request_refresh()

Expand All @@ -177,10 +167,7 @@ async def async_toggle_alarm_powerwake(self, alarm: str, state: bool):
async with self.state_lock:
await self.hass.async_add_executor_job(
ft.partial(
self.somneo.set_alarm_powerwake,
alarm,
onoff = state,
delta = 10
self.somneo.set_alarm_powerwake, alarm, onoff=state, delta=10
)
)
await self.async_request_refresh()
Expand All @@ -192,8 +179,8 @@ async def async_set_alarm_powerwake(self, alarm: str, delta: int = 0):
ft.partial(
self.somneo.set_alarm_powerwake,
alarm,
onoff = bool(delta),
delta = delta
onoff=bool(delta),
delta=delta,
)
)
await self.async_request_refresh()
Expand All @@ -204,11 +191,11 @@ async def async_snooze_alarm(self) -> None:
await self.hass.async_add_executor_job(self.somneo.snooze_alarm)
await self.async_request_refresh()

async def async_set_snooze_time(self, time):
async def async_set_snooze_time(self, snooze_time):
"""Set snooze time."""
async with self.state_lock:
await self.hass.async_add_executor_job(
self.somneo.set_snooze_time, int(time)
self.somneo.set_snooze_time, int(snooze_time)
)
await self.async_request_refresh()

Expand All @@ -221,9 +208,9 @@ async def async_set_alarm_light(
ft.partial(
self.somneo.set_alarm_light,
alarm,
curve = curve,
level = level,
duration = duration
curve=curve,
level=level,
duration=duration,
)
)
await self.async_request_refresh()
Expand All @@ -237,20 +224,20 @@ async def async_set_alarm_sound(
ft.partial(
self.somneo.set_alarm_sound,
alarm,
source = source,
level = level,
channel = channel
source=source,
level=level,
channel=channel,
)
)
await self.async_request_refresh()

async def async_remove_alarm(self, alarm: str):
"""Function to remove alarm from list in Somneo app."""
"""Remove alarm from list in Somneo app."""
async with self.state_lock:
await self.hass.async_add_executor_job(self.somneo.remove_alarm, alarm)

async def async_add_alarm(self, alarm: str):
"""Function to add alarm to list in Somneo app."""
"""Add alarm to list in Somneo app."""
async with self.state_lock:
await self.hass.async_add_executor_job(self.somneo.add_alarm, alarm)

Expand Down Expand Up @@ -288,18 +275,18 @@ async def async_set_sunset(
level: int | None = None,
duration: int | None = None,
sound: str | None = None,
volume: int | None = None
volume: int | None = None,
):
"""Adjust the sunset settings."""
async with self.state_lock:
await self.hass.async_add_executor_job(
ft.partial(
self.somneo.set_sunset,
curve = curve,
level = level,
duration = duration,
sound = sound,
volume = volume
curve=curve,
level=level,
duration=duration,
sound=sound,
volume=volume,
)
)
await self.async_request_refresh()
4 changes: 2 additions & 2 deletions custom_components/somneo/button.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
"""Button entities for Somneo."""
import logging

from homeassistant.config_entries import ConfigEntry
from homeassistant.components.button import ButtonEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_NAME
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback

from .const import DOMAIN, DISMISS_ICON, SNOOZE_ICON
from .const import DISMISS_ICON, DOMAIN, SNOOZE_ICON
from .entity import SomneoEntity

_LOGGER = logging.getLogger(__name__)
Expand Down
16 changes: 6 additions & 10 deletions custom_components/somneo/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,20 @@
from __future__ import annotations

import ipaddress
import re
import logging
import re
from contextlib import suppress
from typing import Any
from urllib.parse import urlparse

from contextlib import suppress
import voluptuous as vol

from pysomneo import Somneo

from homeassistant import config_entries, exceptions
from homeassistant.components.ssdp import SsdpServiceInfo
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_HOST, CONF_NAME
from homeassistant.core import callback
from homeassistant.data_entry_flow import FlowResult
from pysomneo import Somneo

from .const import DOMAIN, DEFAULT_NAME, CONF_SESSION
from .const import DEFAULT_NAME, DOMAIN

_LOGGER = logging.getLogger(__name__)

Expand Down Expand Up @@ -62,7 +58,7 @@ class SomneoConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
dev_info: dict | None = None

async def get_device_info(self):
"""Get device info"""
"""Get device info."""
somneo = Somneo(self.host)
dev_info = await self.hass.async_add_executor_job(somneo.get_device_info)

Expand All @@ -74,7 +70,7 @@ async def async_step_ssdp(self, discovery_info: SsdpServiceInfo) -> FlowResult:

self.discovery_info = discovery_info

serial_number = discovery_info.upnp['cppId']
serial_number = discovery_info.upnp["cppId"]
self.host = urlparse(discovery_info.ssdp_location).hostname

await self.async_set_unique_id(serial_number)
Expand Down
4 changes: 2 additions & 2 deletions custom_components/somneo/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
from typing import Final

from homeassistant.const import (
UnitOfTemperature,
PERCENTAGE,
LIGHT_LUX,
PERCENTAGE,
UnitOfSoundPressure,
UnitOfTemperature,
)

DOMAIN: Final = "somneo"
Expand Down
Loading

0 comments on commit 79796a4

Please sign in to comment.