Skip to content

Commit

Permalink
Merge pull request #563 from MTrab/Add-more-buttons
Browse files Browse the repository at this point in the history
Migrate restart and edgecut services to buttons
  • Loading branch information
MTrab authored Apr 15, 2024
2 parents 0da5e6a + 7df1527 commit a83b4ed
Show file tree
Hide file tree
Showing 6 changed files with 86 additions and 51 deletions.
3 changes: 2 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,6 @@
"--profile",
"black"
],
"python.formatting.provider": "black"
"python.formatting.provider": "black",
"python.analysis.autoImportCompletions": true
}
43 changes: 14 additions & 29 deletions custom_components/landroid_cloud/button.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,23 +19,27 @@
LandroidButtonTypes,
LandroidFeatureSupport,
)
from .utils.entity_setup import vendor_to_device
from .device_base import LandroidButton, LandroidButtonEntityDescription
from .utils.logger import LandroidLogger, LoggerType

# Tuple containing buttons to create
BUTTONS = [
ButtonEntityDescription(
LandroidButtonEntityDescription(
key=LandroidButtonTypes.RESTART,
name="NAME - Restart",
name="Restart baseboard",
icon="mdi:restart",
entity_category=EntityCategory.DIAGNOSTIC,
entity_category=EntityCategory.CONFIG,
device_class=ButtonDeviceClass.RESTART,
required_feature=LandroidFeatureSupport.RESTART,
press_action=lambda api, serial: api.cloud.restart(serial),
),
ButtonEntityDescription(
LandroidButtonEntityDescription(
key=LandroidButtonTypes.EDGECUT,
name="NAME - Start cutting edge",
name="Start cutting edge",
icon="mdi:map-marker-path",
entity_category=None,
required_feature=LandroidFeatureSupport.EDGECUT,
press_action=lambda api, serial: api.cloud.ots(serial, True, 0),
),
]

Expand All @@ -47,34 +51,15 @@ async def async_setup_entry(
) -> None:
"""Set up Landroid buttons for specific service."""
entities = []
for name, info in hass.data[DOMAIN][config.entry_id][ATTR_DEVICES].items():
for _, info in hass.data[DOMAIN][config.entry_id][ATTR_DEVICES].items():
api: LandroidAPI = info["api"]
device = vendor_to_device(api.config["type"])
logger = LandroidLogger(name=__name__, api=api, log_level=LOGLEVEL)

await api.async_await_features()

logger.log(
LoggerType.FEATURE_ASSESSMENT,
"Features fully loaded, feature bit: %s -- assessing available button entities",
api.features,
)

for button in BUTTONS:
constructor = None
if (
button.key == LandroidButtonTypes.RESTART
and api.features & LandroidFeatureSupport.RESTART
) or (
button.key == LandroidButtonTypes.EDGECUT
and api.features & LandroidFeatureSupport.EDGECUT
):
if (api.features & button.required_feature):
logger.log(LoggerType.FEATURE, "Adding %s button", button.key)
out = deepcopy(button)
out.name = out.name.replace("NAME", api.friendly_name)
constructor = device.Button
entity = LandroidButton(hass, button, api, config)

if not isinstance(constructor, type(None)):
entities.append(constructor(out, hass, api))
entities.append(entity)

async_add_entities(entities, True)
2 changes: 1 addition & 1 deletion custom_components/landroid_cloud/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
DEFAULT_NAME = "landroid"
DOMAIN = "landroid_cloud"
PLATFORMS_SECONDARY = []
PLATFORMS_PRIMARY = ["lawn_mower", "sensor", "switch", "binary_sensor"]
PLATFORMS_PRIMARY = ["lawn_mower", "sensor", "switch", "binary_sensor", "button"]
UPDATE_SIGNAL = "landroid_cloud_update"
LOGLEVEL = LogLevel.DEBUG
ENTITY_ID_FORMAT = DOMAIN + ".{}"
Expand Down
69 changes: 69 additions & 0 deletions custom_components/landroid_cloud/device_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -909,6 +909,13 @@ class LandroidBaseEntityDescriptionMixin:

value_fn: Callable[[WorxCloud], bool | str | int | float]

@dataclass
class LandroidButtonEntityDescription(ButtonEntityDescription):
"""Describes a Landroid button entity."""

press_action: Callable[[LandroidAPI, str], None] = None,
required_feature: LandroidFeatureSupport | None = None


@dataclass
class LandroidSensorEntityDescription(
Expand Down Expand Up @@ -937,6 +944,68 @@ class LandroidSwitchEntityDescription(
icon_on: str | None = None
icon_off: str | None = None

class LandroidButton(ButtonEntity):
"""Representation of a Landroid button."""

_attr_has_entity_name = True

def __init__(
self,
hass: HomeAssistant,
description: LandroidButtonEntityDescription,
api: LandroidAPI,
config: ConfigEntry
) -> None:
"""Initialize a Landroid button."""
super().__init__()

self.entity_description = description
self.hass = hass
self.device = api.device
self._api = api
self._config = config

self._attr_name = self.entity_description.name

_LOGGER.debug(
"(%s, Setup) Added sensor '%s'", self._api.friendly_name, self._attr_name
)

self._attr_unique_id = util_slugify(
f"{self._attr_name}_{self._config.entry_id}_{self._api.device.serial_number}"
)
self._attr_should_poll = False

self._attr_device_info = {
"identifiers": {
(
DOMAIN,
self._api.unique_id,
self._api.entry_id,
self._api.device.serial_number,
)
},
"name": str(f"{self._api.friendly_name}"),
"sw_version": self._api.device.firmware["version"],
"manufacturer": self._api.config["type"].capitalize(),
"model": self._api.device.model,
"serial_number": self._api.device.serial_number,
}

if self.device.mac_address != "__UUID__":
_connections = {(dr.CONNECTION_NETWORK_MAC, self.device.mac_address)}
self._attr_device_info.update({"connections": _connections})

self._attr_extra_state_attributes = {}

@property
def available(self) -> bool:
"""Return if the entity is available."""
return self._api.device.online

def press(self) -> None:
"""Press the button."""
self.entity_description.press_action(self._api, self.device.serial_number)

class LandroidSensor(SensorEntity):
"""Representation of a Landroid sensor."""
Expand Down
6 changes: 0 additions & 6 deletions custom_components/landroid_cloud/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,12 +60,6 @@ class LandroidServiceDescription:
schema=SET_ZONE_SCHEME,
feature=LandroidFeatureSupport.SETZONE,
),
LandroidServiceDescription(
key=SERVICE_RESTART, feature=LandroidFeatureSupport.RESTART
),
LandroidServiceDescription(
key=SERVICE_EDGECUT, feature=LandroidFeatureSupport.EDGECUT
),
LandroidServiceDescription(
key=SERVICE_OTS, schema=OTS_SCHEME, feature=LandroidFeatureSupport.OTS
),
Expand Down
14 changes: 0 additions & 14 deletions custom_components/landroid_cloud/services.yaml
Original file line number Diff line number Diff line change
@@ -1,17 +1,3 @@
restart:
description: Restart device
target:
entity:
integration: landroid_cloud
domain: lawn_mower

edgecut:
description: Start edgecut (if supported)
target:
entity:
integration: landroid_cloud
domain: lawn_mower

setzone:
description: Set which zone to be mowed next
target:
Expand Down

0 comments on commit a83b4ed

Please sign in to comment.