Skip to content

Commit 2d5bf56

Browse files
committed
Reconfigure improvements, custom translation strings
1 parent d547834 commit 2d5bf56

File tree

4 files changed

+56
-78
lines changed

4 files changed

+56
-78
lines changed

custom_components/powersensor/PowersensorSensorEntity.py

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,14 @@
77
from .PowersensorEntity import PowersensorEntity
88
from .SensorMeasurements import SensorMeasurements
99
from .const import DOMAIN
10+
from .custom_translations import translate
1011

1112
import logging
1213
_LOGGER = logging.getLogger(__name__)
1314

1415

1516
_config = {
17+
# TODO: change names to translation keys
1618
SensorMeasurements.Battery: {
1719
"name": "Battery Level",
1820
"device_class": SensorDeviceClass.BATTERY,
@@ -77,20 +79,12 @@ def _ensure_matching_prefix(self):
7779

7880
def _rename_based_on_role(self):
7981
if self._device_name == self._default_device_name():
80-
if self.role =='house-net':
81-
self._device_name = "Powersensor Mains Sensor ⚡"
82-
self._ensure_matching_prefix()
83-
return True
84-
elif self.role == 'water':
85-
self._device_name = "Powersensor Water Sensor ⚡"
86-
self._ensure_matching_prefix()
87-
return True
88-
elif self.role == 'solar':
89-
self._device_name = "Powersensor Solar Sensor ⚡"
82+
if self.role =='house-net' or self.role == "water" or self.role == "solar":
83+
self._device_name = translate(f"sensor_types.{self.role}")
9084
self._ensure_matching_prefix()
9185
return True
9286
return False
9387

9488
def _default_device_name(self):
95-
return f'Powersensor Sensor (ID: {self._mac}) ⚡'
89+
return translate("formats.sensor") % self._mac
9690

custom_components/powersensor/config_flow.py

Lines changed: 26 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -7,17 +7,18 @@
77
from homeassistant.data_entry_flow import FlowResult
88
from homeassistant.helpers.dispatcher import async_dispatcher_send
99
from homeassistant.helpers.service_info import zeroconf
10-
from homeassistant.const import CONF_HOST, CONF_PORT
1110
from homeassistant.helpers.selector import selector
1211

1312
from .const import DEFAULT_PORT, DOMAIN
13+
from .custom_translations import translate
1414

1515
def _extract_device_name(discovery_info) -> str:
1616
"""Extract a user-friendly device name from zeroconf info."""
1717
properties = discovery_info.properties or {}
1818

1919
if "id" in properties:
20-
return f'🔌 Mac({properties["id"].strip()})'
20+
return translate("formats.discovery_name") % properties["id"].strip()
21+
2122
# Fall back to cleaning up the service name
2223
name = discovery_info.name or ""
2324

@@ -42,13 +43,6 @@ def _extract_device_name(discovery_info) -> str:
4243

4344
_LOGGER = logging.getLogger(__name__)
4445

45-
STEP_USER_DATA_SCHEMA = vol.Schema(
46-
{
47-
vol.Required(CONF_HOST): str,
48-
vol.Required(CONF_PORT, default=DEFAULT_PORT): int,
49-
}
50-
)
51-
5246

5347
class PowersensorConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
5448
"""Handle a config flow."""
@@ -58,69 +52,36 @@ class PowersensorConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
5852
def __init__(self):
5953
"""Initialize the config flow."""
6054

61-
# async def async_step_user(self, user_input=None) -> ConfigFlowResult:
62-
# """Handle manual user setup."""
63-
# errors = {}
64-
#
65-
# if user_input is not None:
66-
# # Validate the host/connection here if needed
67-
# try:
68-
# # Set unique ID based on host to prevent duplicates
69-
# await self.async_set_unique_id(user_input[CONF_HOST])
70-
# self._abort_if_unique_id_configured()
71-
#
72-
# return self.async_create_entry(
73-
# title=user_input[CONF_NAME],
74-
# data=user_input
75-
# )
76-
# except Exception as ex:
77-
# _LOGGER.error("Error validating configuration: %s", ex)
78-
# errors["base"] = "cannot_connect"
79-
#
80-
# data_schema = vol.Schema(
81-
# {
82-
# vol.Required(CONF_NAME): cv.string,
83-
# vol.Required(CONF_HOST): cv.string,
84-
# vol.Optional(CONF_PORT, default=80): cv.port,
85-
# }
86-
# )
87-
#
88-
# return self.async_show_form(
89-
# step_id="user",
90-
# data_schema=data_schema,
91-
# errors=errors
92-
# )
9355
async def async_step_reconfigure(self, user_input: dict | None = None)->FlowResult:
9456
entry = self.hass.config_entries.async_get_entry(self.context["entry_id"])
57+
dispatcher = entry.runtime_data["dispatcher"]
9558

59+
mac2name = { mac: translate("formats.sensor") % mac for mac in dispatcher.sensors }
60+
61+
unknown = "<unknown>"
9662
if user_input is not None:
97-
# @todo: better handling of mac association
98-
for key, role in user_input.items():
99-
mac= key[33:-2]
100-
_LOGGER.debug(f"Sending {mac}, {role} to {DOMAIN}_update_role")
101-
async_dispatcher_send(self.hass, f"{DOMAIN}_update_role",
102-
mac, role) # default role
103-
await self.hass.config_entries.async_reload(entry.entry_id)
104-
return self.async_abort(reason="Powersensor role updates successful!")
63+
name2mac = { name: mac for mac, name in mac2name.items() }
64+
for name, role in user_input.items():
65+
mac = name2mac.get(name)
66+
if role == unknown:
67+
role = None
68+
_LOGGER.debug(f"Applying {role} to {mac}")
69+
async_dispatcher_send(self.hass, f"{DOMAIN}_update_role", mac, role)
70+
return self.async_abort(reason="Roles successfully applied!")
10571

106-
dispatcher = entry.runtime_data["dispatcher"]
10772
sensor_roles = {}
10873
for sensor_mac in dispatcher.sensors:
109-
role = entry.data.get('roles', {}).get(sensor_mac, None)
110-
if not role:
111-
sensor_roles[vol.Optional(f"Powersensor Sensor [Mac Address: {sensor_mac}]")] = vol.In(
112-
["house-net", "solar", "water", "appliance", "none"]
113-
)
114-
else:
115-
sensor_roles[vol.Optional(f"Powersensor Sensor [Mac Address: {sensor_mac}]", description={"suggested_value": role})] = selector({
116-
"select" : {
117-
"options" : ["house-net", "solar", "water", "appliance", "none"] ,
118-
"mode" : "dropdown"
119-
}
120-
})
121-
122-
# if not sensor_roles:
123-
# return self.async_abort(reason="no_sensors_found_without_roles")
74+
role = entry.data.get('roles', {}).get(sensor_mac, unknown)
75+
sel = selector({
76+
"select": {
77+
"options": [
78+
# Note: these strings are NOT subject to translation
79+
"house-net", "solar", "water", "appliance", unknown
80+
],
81+
"mode": "dropdown",
82+
}
83+
})
84+
sensor_roles[vol.Optional(mac2name[sensor_mac], description={"suggested_value": role})] = sel
12485

12586
return self.async_show_form(
12687
step_id="reconfigure",
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import logging
2+
3+
from homeassistant.core import async_get_hass
4+
from homeassistant.helpers.translation import async_get_cached_translations
5+
6+
from .const import DOMAIN
7+
8+
9+
def translate(key: str) -> str:
10+
hass = async_get_hass()
11+
translations = async_get_cached_translations(hass, hass.config.language, "custom", DOMAIN)
12+
key = f"component.{DOMAIN}.custom.{key}"
13+
return translations.get(key, f"🚨 UNTRANSLATED:{key} 🚨")

custom_components/powersensor/translations/en.json

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,18 @@
2626
"no_devices_found": "No devices found on the network",
2727
"single_instance_allowed": "Already configured. Only a single configuration possible.",
2828
"already_configured": "Device is already configured",
29-
"cannot_connect": "Failed to connect",
30-
"no_sensors_found_without_roles": "All sensors have roles provided!"
29+
"cannot_connect": "Failed to connect"
30+
}
31+
},
32+
"custom": {
33+
"formats": {
34+
"sensor": "Powersensor Sensor (ID: %s) ⚡",
35+
"discovery_name": "🔌 Mac(%s)"
36+
},
37+
"sensor_types": {
38+
"house-net": "Powersensor Mains Sensor ⚡",
39+
"solar": "Powersensor Solar Sensor ⚡",
40+
"water": "Powersensor Water Sensor 💧"
3141
}
3242
}
3343
}

0 commit comments

Comments
 (0)