Skip to content

Commit

Permalink
Fix import on File config entry and other improvements (#117210)
Browse files Browse the repository at this point in the history
* Address comments

* Remove Name option for File based sensor

* Make sure platform schema is applied
  • Loading branch information
jbouwh committed May 12, 2024
1 parent c971d08 commit 606a284
Show file tree
Hide file tree
Showing 6 changed files with 22 additions and 15 deletions.
15 changes: 12 additions & 3 deletions homeassistant/components/file/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,13 @@
from homeassistant.helpers.typing import ConfigType

from .const import DOMAIN
from .notify import PLATFORM_SCHEMA as NOTIFY_PLATFORM_SCHEMA
from .sensor import PLATFORM_SCHEMA as SENSOR_PLATFORM_SCHEMA

IMPORT_SCHEMA = {
Platform.SENSOR: SENSOR_PLATFORM_SCHEMA,
Platform.NOTIFY: NOTIFY_PLATFORM_SCHEMA,
}

CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN)

Expand All @@ -23,6 +30,7 @@
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up the file integration."""

hass.data[DOMAIN] = config
if hass.config_entries.async_entries(DOMAIN):
# We skip import in case we already have config entries
return True
Expand Down Expand Up @@ -51,12 +59,13 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
for domain, items in platforms_config.items():
for item in items:
if item[CONF_PLATFORM] == DOMAIN:
item[CONF_PLATFORM] = domain
file_config_item = IMPORT_SCHEMA[domain](item)
file_config_item[CONF_PLATFORM] = domain
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data=item,
data=file_config_item,
)
)

Expand Down Expand Up @@ -90,7 +99,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
Platform.NOTIFY,
DOMAIN,
config,
{},
hass.data[DOMAIN],
)
)

Expand Down
4 changes: 1 addition & 3 deletions homeassistant/components/file/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@

FILE_SENSOR_SCHEMA = vol.Schema(
{
vol.Optional(CONF_NAME, default=DEFAULT_NAME): TEXT_SELECTOR,
vol.Required(CONF_FILE_PATH): TEXT_SELECTOR,
vol.Optional(CONF_VALUE_TEMPLATE): TEMPLATE_SELECTOR,
vol.Optional(CONF_UNIT_OF_MEASUREMENT): TEXT_SELECTOR,
Expand Down Expand Up @@ -99,8 +98,7 @@ async def async_step_sensor(
if not await self.validate_file_path(user_input[CONF_FILE_PATH]):
errors[CONF_FILE_PATH] = "not_allowed"
else:
name: str = user_input.get(CONF_NAME, DEFAULT_NAME)
title = f"{name} [{user_input[CONF_FILE_PATH]}]"
title = f"{DEFAULT_NAME} [{user_input[CONF_FILE_PATH]}]"
return self.async_create_entry(data=user_input, title=title)

return self.async_show_form(
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/file/notify.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def send_message(self, message: str = "", **kwargs: Any) -> None:
else:
text = f"{message}\n"
file.write(text)
except Exception as exc:
except OSError as exc:
raise ServiceValidationError(
translation_domain=DOMAIN,
translation_key="write_access_failed",
Expand Down
11 changes: 7 additions & 4 deletions homeassistant/components/file/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.template import Template
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from homeassistant.util import slugify

from .const import DEFAULT_NAME, FILE_ICON

Expand Down Expand Up @@ -59,14 +58,17 @@ async def async_setup_entry(
"""Set up the file sensor."""
config = dict(entry.data)
file_path: str = config[CONF_FILE_PATH]
name: str = config[CONF_NAME]
unique_id: str = entry.entry_id
name: str = config.get(CONF_NAME, DEFAULT_NAME)
unit: str | None = config.get(CONF_UNIT_OF_MEASUREMENT)
value_template: Template | None = None

if CONF_VALUE_TEMPLATE in config:
value_template = Template(config[CONF_VALUE_TEMPLATE], hass)

async_add_entities([FileSensor(name, file_path, unit, value_template)], True)
async_add_entities(
[FileSensor(unique_id, name, file_path, unit, value_template)], True
)


class FileSensor(SensorEntity):
Expand All @@ -76,6 +78,7 @@ class FileSensor(SensorEntity):

def __init__(
self,
unique_id: str,
name: str,
file_path: str,
unit_of_measurement: str | None,
Expand All @@ -86,7 +89,7 @@ def __init__(
self._file_path = file_path
self._attr_native_unit_of_measurement = unit_of_measurement
self._val_tpl = value_template
self._attr_unique_id = slugify(f"{name}_{file_path}")
self._attr_unique_id = unique_id

def update(self) -> None:
"""Get the latest entry from a file and updates the state."""
Expand Down
4 changes: 1 addition & 3 deletions homeassistant/components/file/strings.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,11 @@
"title": "File sensor",
"description": "Set up a file based sensor",
"data": {
"name": "Name",
"file_path": "File path",
"value_template": "Value template",
"unit_of_measurement": "Unit of measurement"
},
"data_description": {
"name": "Name of the file based sensor",
"file_path": "The local file path to retrieve the sensor value from",
"value_template": "A template to render the the sensors value based on the file content",
"unit_of_measurement": "Unit of measurement for the sensor"
Expand All @@ -29,7 +27,7 @@
"description": "Set up a service that allows to write notification to a file.",
"data": {
"file_path": "[%key:component::file::config::step::sensor::data::file_path%]",
"name": "[%key:component::file::config::step::sensor::data::name%]",
"name": "Name",
"timestamp": "Timestamp"
},
"data_description": {
Expand Down
1 change: 0 additions & 1 deletion tests/components/file/test_config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
"platform": "sensor",
"file_path": "some/path",
"value_template": "{{ value | round(1) }}",
"name": "File",
}

pytestmark = pytest.mark.usefixtures("mock_setup_entry")
Expand Down

0 comments on commit 606a284

Please sign in to comment.