Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add switch platform to IronOS integration #133691

Merged
merged 7 commits into from
Dec 28, 2024
Merged
Show file tree
Hide file tree
Changes from 6 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 homeassistant/components/iron_os/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
Platform.NUMBER,
Platform.SELECT,
Platform.SENSOR,
Platform.SWITCH,
Platform.UPDATE,
]

Expand Down
21 changes: 21 additions & 0 deletions homeassistant/components/iron_os/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@
from dataclasses import dataclass
from datetime import timedelta
import logging
from typing import cast

from pynecil import (
CharSetting,
CommunicationError,
DeviceInfoResponse,
IronOSUpdate,
Expand All @@ -19,6 +21,7 @@

from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ServiceValidationError
from homeassistant.helpers.debounce import Debouncer
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed

Expand Down Expand Up @@ -147,3 +150,21 @@ async def _async_update_data(self) -> SettingsDataResponse:
_LOGGER.debug("Failed to fetch settings", exc_info=e)

return self.data or SettingsDataResponse()

async def write(self, characteristic: CharSetting, value: bool) -> None:
"""Write value to the settings characteristic."""

try:
await self.device.write(characteristic, value)
except CommunicationError as e:
raise ServiceValidationError(
translation_domain=DOMAIN,
translation_key="submit_setting_failed",
) from e
else:
# prevent switch bouncing while waiting for coordinator to finish refresh
self.data.update(
cast(SettingsDataResponse, {characteristic.name.lower(): value})
)
self.async_update_listeners()
await self.async_request_refresh()
tr4nt0r marked this conversation as resolved.
Show resolved Hide resolved
38 changes: 38 additions & 0 deletions homeassistant/components/iron_os/icons.json
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,44 @@
"estimated_power": {
"default": "mdi:flash"
}
},
"switch": {
"animation_loop": {
"default": "mdi:play-box",
"state": {
"on": "mdi:animation-play"
}
},
"calibrate_cjc": {
"default": "mdi:tune-vertical"
},
"cooling_temp_blink": {
"default": "mdi:alarm-light-outline",
"state": {
"off": "mdi:alarm-light-off-outline"
}
},
"display_invert": {
"default": "mdi:invert-colors"
},
"invert_buttons": {
"default": "mdi:plus-minus-variant"
},
"usb_pd_mode": {
"default": "mdi:meter-electric-outline"
},
"idle_screen_details": {
"default": "mdi:card-bulleted-outline",
"state": {
"off": "mdi:card-bulleted-off-outline"
}
},
"solder_screen_details": {
"default": "mdi:card-bulleted-outline",
"state": {
"off": "mdi:card-bulleted-off-outline"
}
}
}
}
}
26 changes: 26 additions & 0 deletions homeassistant/components/iron_os/strings.json
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,32 @@
"estimated_power": {
"name": "Estimated power"
}
},
"switch": {
"animation_loop": {
"name": "Animation loop"
},
"cooling_temp_blink": {
"name": "Cool down screen flashing"
},
"idle_screen_details": {
"name": "Detailed idle screen"
},
"solder_screen_details": {
"name": "Detailed solder screen"
},
"invert_buttons": {
"name": "Swap +/- buttons"
},
"display_invert": {
"name": "Invert screen"
},
"calibrate_cjc": {
"name": "Calibrate CJC"
},
"usb_pd_mode": {
"name": "Power Delivery 3.1 EPR"
}
}
},
"exceptions": {
Expand Down
163 changes: 163 additions & 0 deletions homeassistant/components/iron_os/switch.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
"""Switch platform for IronOS integration."""

from __future__ import annotations

from collections.abc import Callable
from dataclasses import dataclass
from enum import StrEnum
from typing import Any

from pynecil import CharSetting, SettingsDataResponse

from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback

from . import IronOSConfigEntry
from .coordinator import IronOSCoordinators
from .entity import IronOSBaseEntity

PARALLEL_UPDATES = 0
tr4nt0r marked this conversation as resolved.
Show resolved Hide resolved


@dataclass(frozen=True, kw_only=True)
class IronOSSwitchEntityDescription(SwitchEntityDescription):
"""Describes IronOS switch entity."""

is_on_fn: Callable[[SettingsDataResponse], bool | None]
characteristic: CharSetting


class IronOSSwitch(StrEnum):
"""Switch controls for IronOS device."""

ANIMATION_LOOP = "animation_loop"
COOLING_TEMP_BLINK = "cooling_temp_blink"
IDLE_SCREEN_DETAILS = "idle_screen_details"
SOLDER_SCREEN_DETAILS = "solder_screen_details"
INVERT_BUTTONS = "invert_buttons"
DISPLAY_INVERT = "display_invert"
CALIBRATE_CJC = "calibrate_cjc"
USB_PD_MODE = "usb_pd_mode"


SWITCH_DESCRIPTIONS: tuple[IronOSSwitchEntityDescription, ...] = (
IronOSSwitchEntityDescription(
key=IronOSSwitch.ANIMATION_LOOP,
translation_key=IronOSSwitch.ANIMATION_LOOP,
characteristic=CharSetting.ANIMATION_LOOP,
is_on_fn=lambda x: x.get("animation_loop"),
entity_registry_enabled_default=False,
entity_category=EntityCategory.CONFIG,
),
IronOSSwitchEntityDescription(
key=IronOSSwitch.COOLING_TEMP_BLINK,
translation_key=IronOSSwitch.COOLING_TEMP_BLINK,
characteristic=CharSetting.COOLING_TEMP_BLINK,
is_on_fn=lambda x: x.get("cooling_temp_blink"),
entity_category=EntityCategory.CONFIG,
),
IronOSSwitchEntityDescription(
key=IronOSSwitch.IDLE_SCREEN_DETAILS,
translation_key=IronOSSwitch.IDLE_SCREEN_DETAILS,
characteristic=CharSetting.IDLE_SCREEN_DETAILS,
is_on_fn=lambda x: x.get("idle_screen_details"),
entity_category=EntityCategory.CONFIG,
),
IronOSSwitchEntityDescription(
key=IronOSSwitch.SOLDER_SCREEN_DETAILS,
translation_key=IronOSSwitch.SOLDER_SCREEN_DETAILS,
characteristic=CharSetting.SOLDER_SCREEN_DETAILS,
is_on_fn=lambda x: x.get("solder_screen_details"),
entity_category=EntityCategory.CONFIG,
),
IronOSSwitchEntityDescription(
key=IronOSSwitch.INVERT_BUTTONS,
translation_key=IronOSSwitch.INVERT_BUTTONS,
characteristic=CharSetting.INVERT_BUTTONS,
is_on_fn=lambda x: x.get("invert_buttons"),
entity_category=EntityCategory.CONFIG,
),
IronOSSwitchEntityDescription(
key=IronOSSwitch.DISPLAY_INVERT,
translation_key=IronOSSwitch.DISPLAY_INVERT,
characteristic=CharSetting.DISPLAY_INVERT,
is_on_fn=lambda x: x.get("display_invert"),
entity_registry_enabled_default=False,
entity_category=EntityCategory.CONFIG,
),
IronOSSwitchEntityDescription(
key=IronOSSwitch.CALIBRATE_CJC,
translation_key=IronOSSwitch.CALIBRATE_CJC,
characteristic=CharSetting.CALIBRATE_CJC,
is_on_fn=lambda x: x.get("calibrate_cjc"),
entity_registry_enabled_default=False,
entity_category=EntityCategory.CONFIG,
),
IronOSSwitchEntityDescription(
key=IronOSSwitch.USB_PD_MODE,
translation_key=IronOSSwitch.USB_PD_MODE,
characteristic=CharSetting.USB_PD_MODE,
is_on_fn=lambda x: x.get("usb_pd_mode"),
entity_registry_enabled_default=False,
entity_category=EntityCategory.CONFIG,
),
)


async def async_setup_entry(
hass: HomeAssistant,
entry: IronOSConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up switches from a config entry."""

coordinators = entry.runtime_data

async_add_entities(
IronOSSwitchEntity(coordinators, description)
for description in SWITCH_DESCRIPTIONS
)


class IronOSSwitchEntity(IronOSBaseEntity, SwitchEntity):
"""Representation of a IronOS Switch."""

entity_description: IronOSSwitchEntityDescription

def __init__(
self,
coordinators: IronOSCoordinators,
entity_description: IronOSSwitchEntityDescription,
) -> None:
"""Initialize the switch entity."""
super().__init__(coordinators.live_data, entity_description)

self.settings = coordinators.settings

@property
def is_on(self) -> bool | None:
"""Return the state of the device."""
return self.entity_description.is_on_fn(
self.settings.data,
)

async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the entity on."""
await self.settings.write(self.entity_description.characteristic, True)
tr4nt0r marked this conversation as resolved.
Show resolved Hide resolved

async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the entity on."""
await self.settings.write(self.entity_description.characteristic, False)

async def async_added_to_hass(self) -> None:
"""Run when entity about to be added to hass."""

await super().async_added_to_hass()
self.async_on_remove(
self.settings.async_add_listener(
self._handle_coordinator_update, self.entity_description.characteristic
)
)
await self.settings.async_request_refresh()
8 changes: 8 additions & 0 deletions tests/components/iron_os/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,14 @@ def mock_pynecil() -> Generator[AsyncMock]:
desc_scroll_speed=ScrollSpeed.FAST,
logo_duration=LogoDuration.LOOP,
locking_mode=LockingMode.FULL_LOCKING,
animation_loop=True,
cooling_temp_blink=True,
idle_screen_details=True,
solder_screen_details=True,
invert_buttons=True,
display_invert=True,
calibrate_cjc=True,
usb_pd_mode=True,
)
client.get_live_data.return_value = LiveDataResponse(
live_temp=298,
Expand Down
Loading