Skip to content

Commit 88eb54d

Browse files
Hide replaced & Ignore Devices (#173)
* Disable replaced config option * WIP * Revert disabling the existing sensors * Update readme * Added optional user library pre-pended to device library * Allow discovery ignore
1 parent 7b8a507 commit 88eb54d

File tree

8 files changed

+108
-103
lines changed

8 files changed

+108
-103
lines changed

README.md

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -92,14 +92,21 @@ Go into Settings -> Integrations -> Battery Notes and click Configure on the dev
9292
By default Battery Notes filters the device list to only devices with a battery, if you want to add a battery note to a random device then you can disable this filtering by adding the following configuration to your `configuration.yaml` and restart Home Assistant to see all devices.
9393
```
9494
battery_notes:
95-
show_all_devices: true
95+
show_all_devices: True
9696
```
9797

9898
* I only want to add notes to a few devices, can I disable auto discovery?
9999
If you want to disable this functionality you can add the following to your `configuration.yaml`, after a restart of Home Assistant you will not see discovered battery notes.
100100
```
101101
battery_notes:
102-
enable_autodiscovery: false
102+
enable_autodiscovery: False
103+
```
104+
105+
* I don't want to track battery replacement, can I disable this?
106+
Yes, you can add the following to your `configuration.yaml`, after a restart of Home Assistant *new* devices added to battery notes will have the battery replaced sensor and button disabled. Any devices you have previously added to Battery Notes you will have to disable/enable these sensors manually, which also means you can just enable specific sensors of important ones you want to track.
107+
```
108+
battery_notes:
109+
enable_replaced: False
103110
```
104111

105112
* How can I show my support?

custom_components/battery_notes/__init__.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,10 @@
3434
DOMAIN_CONFIG,
3535
PLATFORMS,
3636
CONF_ENABLE_AUTODISCOVERY,
37-
CONF_LIBRARY,
37+
CONF_USER_LIBRARY,
3838
DATA_UPDATE_COORDINATOR,
3939
CONF_SHOW_ALL_DEVICES,
40+
CONF_ENABLE_REPLACED,
4041
SERVICE_BATTERY_REPLACED,
4142
SERVICE_BATTERY_REPLACED_SCHEMA,
4243
DATA_COORDINATOR,
@@ -53,8 +54,9 @@
5354
vol.Schema(
5455
{
5556
vol.Optional(CONF_ENABLE_AUTODISCOVERY, default=True): cv.boolean,
56-
vol.Optional(CONF_LIBRARY, default="library.json"): cv.string,
57+
vol.Optional(CONF_USER_LIBRARY, default=""): cv.string,
5758
vol.Optional(CONF_SHOW_ALL_DEVICES, default=False): cv.boolean,
59+
vol.Optional(CONF_ENABLE_REPLACED, default=True): cv.boolean,
5860
},
5961
),
6062
),
@@ -79,6 +81,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
7981
domain_config: ConfigType = config.get(DOMAIN) or {
8082
CONF_ENABLE_AUTODISCOVERY: True,
8183
CONF_SHOW_ALL_DEVICES: False,
84+
CONF_ENABLE_REPLACED: True,
8285
}
8386

8487
hass.data[DOMAIN] = {

custom_components/battery_notes/button.py

Lines changed: 24 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -26,21 +26,19 @@
2626
)
2727

2828
from homeassistant.helpers.reload import async_setup_reload_service
29-
from homeassistant.helpers.typing import (
30-
ConfigType,
31-
)
3229

3330
from homeassistant.const import (
3431
CONF_NAME,
35-
CONF_UNIQUE_ID,
3632
CONF_DEVICE_ID,
3733
)
3834

3935
from . import PLATFORMS
4036

4137
from .const import (
4238
DOMAIN,
39+
DOMAIN_CONFIG,
4340
DATA_COORDINATOR,
41+
CONF_ENABLE_REPLACED,
4442
)
4543

4644
from .entity import (
@@ -65,6 +63,7 @@ class BatteryNotesButtonEntityDescription(
6563
translation_key="battery_replaced",
6664
icon="mdi:battery-sync",
6765
entity_category=EntityCategory.DIAGNOSTIC,
66+
entity_registry_enabled_default = False,
6867
),
6968
)
7069

@@ -131,38 +130,38 @@ async def async_registry_updated(event: Event) -> None:
131130

132131
device_id = async_add_to_device(hass, config_entry)
133132

133+
enable_replaced = True
134+
if DOMAIN_CONFIG in hass.data[DOMAIN]:
135+
domain_config = hass.data[DOMAIN][DOMAIN_CONFIG]
136+
enable_replaced = domain_config.get(CONF_ENABLE_REPLACED, True)
137+
138+
description = BatteryNotesButtonEntityDescription(
139+
unique_id_suffix="_battery_replaced_button",
140+
key="battery_replaced",
141+
translation_key="battery_replaced",
142+
icon="mdi:battery-sync",
143+
entity_category=EntityCategory.DIAGNOSTIC,
144+
entity_registry_enabled_default = enable_replaced,
145+
)
146+
134147
async_add_entities(
135-
BatteryNotesButton(
148+
[
149+
BatteryNotesButton(
136150
hass,
137151
description,
138152
f"{config_entry.entry_id}{description.unique_id_suffix}",
139153
device_id,
140-
)
141-
for description in ENTITY_DESCRIPTIONS
154+
)
155+
]
142156
)
143157

144-
145158
async def async_setup_platform(
146159
hass: HomeAssistant,
147-
config: ConfigType,
148-
async_add_entities: AddEntitiesCallback,
149160
) -> None:
150-
"""Set up the battery type button."""
151-
device_id: str = config[CONF_DEVICE_ID]
161+
"""Set up the battery note sensor."""
152162

153163
await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
154164

155-
async_add_entities(
156-
BatteryNotesButton(
157-
hass,
158-
description,
159-
f"{config.get(CONF_UNIQUE_ID)}{description.unique_id_suffix}",
160-
device_id,
161-
)
162-
for description in ENTITY_DESCRIPTIONS
163-
)
164-
165-
166165
class BatteryNotesButton(ButtonEntity):
167166
"""Represents a battery replaced button."""
168167

@@ -185,7 +184,6 @@ def __init__(
185184
self._attr_has_entity_name = True
186185
self._device_id = device_id
187186

188-
self._device_id = device_id
189187
if device_id and (device := device_registry.async_get(device_id)):
190188
self._attr_device_info = DeviceInfo(
191189
connections=device.connections,
@@ -194,29 +192,15 @@ def __init__(
194192

195193
async def async_added_to_hass(self) -> None:
196194
"""Handle added to Hass."""
197-
# Update entity options
198195
registry = er.async_get(self.hass)
199196
if registry.async_get(self.entity_id) is not None:
197+
200198
registry.async_update_entity_options(
201199
self.entity_id,
202200
DOMAIN,
203201
{"entity_id": self._attr_unique_id},
204202
)
205203

206-
async def update_battery_last_replaced(self):
207-
"""Handle sensor state changes."""
208-
209-
# device_id = self._device_id
210-
211-
# device_entry = {
212-
# "battery_last_replaced" : datetime.utcnow()
213-
# }
214-
215-
# coordinator = self.hass.data[DOMAIN][DATA_COORDINATOR]
216-
# coordinator.async_update_device_config(device_id = device_id, data = device_entry)
217-
218-
self.async_write_ha_state()
219-
220204
async def async_press(self) -> None:
221205
"""Press the button."""
222206
device_id = self._device_id
@@ -227,3 +211,4 @@ async def async_press(self) -> None:
227211
coordinator.async_update_device_config(device_id=device_id, data=device_entry)
228212
await coordinator._async_update_data()
229213
await coordinator.async_request_refresh()
214+

custom_components/battery_notes/config_flow.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,10 @@ async def async_step_integration_discovery(
9191
"""Handle integration discovery."""
9292
_LOGGER.debug("Starting discovery flow: %s", discovery_info)
9393

94+
unique_id = f"bn_{discovery_info[CONF_DEVICE_ID]}"
95+
await self.async_set_unique_id(unique_id)
96+
self._abort_if_unique_id_configured()
97+
9498
self.context["title_placeholders"] = {
9599
"name": discovery_info[CONF_DEVICE_NAME],
96100
"manufacturer": discovery_info[CONF_MANUFACTURER],

custom_components/battery_notes/const.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,13 @@
2727
CONF_BATTERY_TYPE = "battery_type"
2828
CONF_SENSORS = "sensors"
2929
CONF_ENABLE_AUTODISCOVERY = "enable_autodiscovery"
30-
CONF_LIBRARY = "library"
30+
CONF_USER_LIBRARY = "user_library"
3131
CONF_MODEL = "model"
3232
CONF_MANUFACTURER = "manufacturer"
3333
CONF_DEVICE_NAME = "device_name"
3434
CONF_LIBRARY_URL = "https://raw.githubusercontent.com/andrew-codechimp/HA-Battery-Notes/main/custom_components/battery_notes/data/library.json" # pylint: disable=line-too-long
3535
CONF_SHOW_ALL_DEVICES = "show_all_devices"
36+
CONF_ENABLE_REPLACED = "enable_replaced"
3637

3738
DATA_CONFIGURED_ENTITIES = "configured_entities"
3839
DATA_DISCOVERED_ENTITIES = "discovered_entities"

custom_components/battery_notes/library.py

Lines changed: 35 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
DOMAIN,
1313
DATA_LIBRARY,
1414
DOMAIN_CONFIG,
15-
CONF_LIBRARY,
15+
CONF_USER_LIBRARY,
1616
)
1717

1818
BUILT_IN_DATA_DIRECTORY = os.path.join(os.path.dirname(__file__), "data")
@@ -23,29 +23,47 @@
2323
class Library: # pylint: disable=too-few-public-methods
2424
"""Hold all known battery types."""
2525

26-
_devices = None
26+
_devices = []
2727

2828
def __init__(self, hass: HomeAssistant) -> None:
2929
"""Init."""
3030

31-
if DOMAIN_CONFIG not in hass.data[DOMAIN]:
32-
json_path = os.path.join(
33-
BUILT_IN_DATA_DIRECTORY,
34-
"library.json",
35-
)
36-
else:
37-
json_path = os.path.join(
38-
BUILT_IN_DATA_DIRECTORY,
39-
hass.data[DOMAIN][DOMAIN_CONFIG].get(CONF_LIBRARY, "library.json"),
40-
)
31+
# User Library
32+
if DOMAIN_CONFIG in hass.data[DOMAIN]:
33+
if CONF_USER_LIBRARY in hass.data[DOMAIN][DOMAIN_CONFIG]:
34+
user_library_filename = hass.data[DOMAIN][DOMAIN_CONFIG].get(CONF_USER_LIBRARY)
35+
if user_library_filename != "":
36+
json_user_path = os.path.join(
37+
BUILT_IN_DATA_DIRECTORY,
38+
user_library_filename,
39+
)
40+
_LOGGER.debug("Using user library file at %s", json_user_path)
41+
42+
try:
43+
with open(json_user_path, encoding="utf-8") as user_file:
44+
user_json_data = json.load(user_file)
45+
self._devices = user_json_data["devices"]
46+
user_file.close()
47+
48+
except FileNotFoundError:
49+
_LOGGER.error(
50+
"User library file not found at %s",
51+
json_user_path,
52+
)
53+
54+
# Default Library
55+
json_default_path = os.path.join(
56+
BUILT_IN_DATA_DIRECTORY,
57+
"library.json",)
4158

42-
_LOGGER.debug("Using library file at %s", json_path)
59+
_LOGGER.debug("Using library file at %s", json_default_path)
4360

4461
try:
45-
with open(json_path, encoding="utf-8") as myfile:
46-
json_data = json.load(myfile)
47-
self._devices = json_data["devices"]
48-
myfile.close()
62+
with open(json_default_path, encoding="utf-8") as default_file:
63+
default_json_data = json.load(default_file)
64+
for i in default_json_data["devices"]:
65+
self._devices.append(i)
66+
default_file.close()
4967

5068
except FileNotFoundError:
5169
_LOGGER.error(

custom_components/battery_notes/manifest.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,5 @@
99
"integration_type": "device",
1010
"iot_class": "calculated",
1111
"issue_tracker": "https://github.com/andrew-codechimp/ha-battery-notes/issues",
12-
"version": "1.3.3"
12+
"version": "1.3.4"
1313
}

0 commit comments

Comments
 (0)