Skip to content

Commit

Permalink
Merge pull request #241 from g4bri3lDev/fix
Browse files Browse the repository at this point in the history
Add deep sleep button, tag alias textbox
  • Loading branch information
g4bri3lDev authored Feb 19, 2025
2 parents 0330d30 + 9fb9179 commit 0230936
Show file tree
Hide file tree
Showing 6 changed files with 178 additions and 6 deletions.
32 changes: 32 additions & 0 deletions custom_components/open_epaper_link/button.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ async def async_add_tag_buttons(tag_mac: str) -> None:
ForceRefreshButton(hass, tag_mac, hub),
RebootTagButton(hass, tag_mac, hub),
ScanChannelsButton(hass, tag_mac, hub),
DeepSleepButton(hass, tag_mac, hub),
]
async_add_entities(new_buttons)

Expand Down Expand Up @@ -227,6 +228,37 @@ def available(self) -> bool:
async def async_press(self) -> None:
await send_tag_cmd(self.hass, self._entity_id, "scan")

class DeepSleepButton(ButtonEntity):
def __init__(self, hass: HomeAssistant, tag_mac: str, hub) -> None:
"""Initialize the button."""
self.hass = hass
self._tag_mac = tag_mac
self._entity_id = f"{DOMAIN}.{tag_mac}"
self._hub = hub
self._attr_has_entity_name = True
self._attr_translation_key = "deep_sleep"
# self._attr_name = f"{hub._data[tag_mac]['tag_name']} Scan Channels"
self._attr_unique_id = f"{tag_mac}_deep_sleep"
self._attr_entity_category = EntityCategory.DIAGNOSTIC
self._attr_icon = "mdi:sleep"

@property
def device_info(self):
"""Return device info."""
tag_name = self._hub._data[self._tag_mac]['tag_name']
return {
"identifiers": {(DOMAIN, self._tag_mac)},
"name": tag_name,
}

@property
def available(self) -> bool:
"""Return if entity is available."""
return self._tag_mac not in self._hub.get_blacklisted_tags()

async def async_press(self) -> None:
await send_tag_cmd(self.hass, self._entity_id, "deepsleep")

class RebootAPButton(ButtonEntity):
def __init__(self, hass: HomeAssistant, hub) -> None:
"""Initialize the button."""
Expand Down
15 changes: 15 additions & 0 deletions custom_components/open_epaper_link/hub.py
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,21 @@ async def _handle_tag_message(self, tag_data: dict) -> None:
# Get existing data to calculate runtime and update counters
existing_data = self._data.get(tag_mac, {})

# Check if name has changed
old_name = existing_data.get("tag_name")
if old_name and old_name != tag_name:
_LOGGER.debug("Tag name changed from '%s' to '%s'", old_name, tag_name)
# Update device name in device registry
device_registry = dr.async_get(self.hass)
device = device_registry.async_get_device(
identifiers={(DOMAIN, tag_mac)}
)
if device:
device_registry.async_update_device(
device.id,
name=tag_name
)

# Calculate runtime delta
runtime_delta = self._calculate_runtime_delta(tag_data, existing_data)
runtime_total = existing_data.get("runtime", 0) + runtime_delta
Expand Down
3 changes: 2 additions & 1 deletion custom_components/open_epaper_link/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@
"requirements": [
"qrcode[pil]==7.4.2",
"requests_toolbelt==1.0.0",
"websocket-client==1.7.0"
"websocket-client==1.7.0",
"websockets==14.2"
],
"single_config_entry": true,
"version": "1.0.0"
Expand Down
122 changes: 117 additions & 5 deletions custom_components/open_epaper_link/text.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from __future__ import annotations

from homeassistant.components.text import TextEntity
import requests

from homeassistant.components.text import TextEntity, TextMode
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
Expand All @@ -15,7 +17,7 @@
_LOGGER = logging.getLogger(__name__)

# Define text field configurations
TEXT_ENTITIES = [
AP_TEXT_ENTITIES = [
{
"key": "alias",
"name": "Alias",
Expand All @@ -29,6 +31,14 @@
"description": "GitHub repository for tag type definitions"
}
]
TAG_TEXT_ENTITIES = [
{
"key": "alias",
"name": "Alias",
"icon": "mdi:rename-box",
"description": "Tag display name"
}
]

class APConfigText(TextEntity):
"""Text entity for AP configuration."""
Expand Down Expand Up @@ -104,6 +114,89 @@ async def async_added_to_hass(self):
self._handle_connection_status,
)
)
class TagNameText(TextEntity):
"""Text entity for tag name/alias."""

def __init__(self, hub, tag_mac: str) -> None:
"""Initialize the text entity."""
self._hub = hub
self._tag_mac = tag_mac
self._attr_unique_id = f"{tag_mac}_alias"
self._attr_has_entity_name = True
self._attr_translation_key = "tag_alias"
self._attr_native_min = 0
self._attr_mode = TextMode.TEXT
self._attr_icon = "mdi:rename"

@property
def device_info(self):
"""Return device info."""
tag_data = self._hub.get_tag_data(self._tag_mac)
return {
"identifiers": {(DOMAIN, self._tag_mac)},
"name": tag_data.get("tag_name", self._tag_mac),
}

@property
def available(self) -> bool:
"""Return if entity is available."""
return (
self._hub.online and
self._tag_mac in self._hub.tags and
self._tag_mac not in self._hub.get_blacklisted_tags()
)

@property
def native_value(self) -> str | None:
"""Return the current value."""
if not self.available:
return None
tag_data = self._hub.get_tag_data(self._tag_mac)
return tag_data.get("tag_name", "")

async def async_set_value(self, value: str) -> None:
"""Set the text value."""
if not value:
value = self._tag_mac

if value != self.native_value:
url = f"http://{self._hub.host}/save_cfg"
data = {
'mac': self._tag_mac,
'alias': value
}
try:
result = await self.hass.async_add_executor_job(
lambda: requests.post(url, data=data)
)
if result.status_code != 200:
_LOGGER.error(
"Failed to update tag name %s: HTTP %s",
self._tag_mac,
result.status_code
)
except Exception as err:
_LOGGER.error(
"Error updating tag name for %s: %s",
self._tag_mac,
str(err)
)

@callback
def _handle_tag_update(self):
"""Handle tag updates."""
self.async_write_ha_state()

async def async_added_to_hass(self):
"""Register callbacks."""
# Listen for tag updates
self.async_on_remove(
async_dispatcher_connect(
self.hass,
f"{DOMAIN}_tag_update_{self._tag_mac}",
self._handle_tag_update,
)
)

async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback) -> None:
"""Set up text entities for AP configuration."""
Expand All @@ -115,8 +208,8 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry, async_add_e

entities = []

# Create text entities from configuration
for config in TEXT_ENTITIES:
# Create AP text entities from configuration
for config in AP_TEXT_ENTITIES:
entities.append(
APConfigText(
hub,
Expand All @@ -127,4 +220,23 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry, async_add_e
)
)

async_add_entities(entities)
# Add tag name/alias text entities
for tag_mac in hub.tags:
if tag_mac not in hub.get_blacklisted_tags():
entities.append(TagNameText(hub, tag_mac))

async_add_entities(entities)

# Set up callback for new tag discovery
async def async_add_tag_text(tag_mac: str) -> None:
"""Add text entities for a newly discovered tag."""
if tag_mac not in hub.get_blacklisted_tags():
async_add_entities([TagNameText(hub, tag_mac)])

entry.async_on_unload(
async_dispatcher_connect(
hass,
f"{DOMAIN}_tag_discovered",
async_add_tag_text
)
)
6 changes: 6 additions & 0 deletions custom_components/open_epaper_link/translations/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@
},
"repo": {
"name": "Repository"
},
"tag_alias": {
"name": "Alias"
}
},
"select": {
Expand Down Expand Up @@ -238,6 +241,9 @@
"scan_channels": {
"name": "Kanäle scannen"
},
"deep_sleep": {
"name": "Tiefschlaf"
},
"reboot_ap": {
"name": "AP neu starten"
},
Expand Down
6 changes: 6 additions & 0 deletions custom_components/open_epaper_link/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@
},
"repo": {
"name": "Repository"
},
"tag_alias": {
"name": "Alias"
}
},
"select": {
Expand Down Expand Up @@ -195,6 +198,9 @@
"scan_channels": {
"name": "Scan Channels"
},
"deep_sleep": {
"name": "Deep Sleep"
},
"reboot_ap": {
"name": "Reboot AP"
},
Expand Down

0 comments on commit 0230936

Please sign in to comment.