1 """Support for sensor value(s) stored in local files."""
3 from __future__
import annotations
8 from file_read_backwards
import FileReadBackwards
15 CONF_UNIT_OF_MEASUREMENT,
22 from .const
import DEFAULT_NAME, FILE_ICON
24 _LOGGER = logging.getLogger(__name__)
30 async_add_entities: AddEntitiesCallback,
32 """Set up the file sensor."""
33 config =
dict(entry.data)
34 options =
dict(entry.options)
35 file_path: str = config[CONF_FILE_PATH]
36 unique_id: str = entry.entry_id
37 name: str = config.get(CONF_NAME, DEFAULT_NAME)
38 unit: str |
None = options.get(CONF_UNIT_OF_MEASUREMENT)
39 value_template: Template |
None =
None
41 if CONF_VALUE_TEMPLATE
in options:
42 value_template =
Template(options[CONF_VALUE_TEMPLATE], hass)
45 [
FileSensor(unique_id, name, file_path, unit, value_template)],
True
50 """Implementation of a file sensor."""
52 _attr_icon = FILE_ICON
59 unit_of_measurement: str |
None,
60 value_template: Template |
None,
62 """Initialize the file sensor."""
70 """Get the latest entry from a file and updates the state."""
72 with FileReadBackwards(self.
_file_path_file_path, encoding=
"utf-8")
as file_data:
73 for line
in file_data:
77 except (IndexError, FileNotFoundError, IsADirectoryError, UnboundLocalError):
79 "File or data not present at the moment: %s",
84 if self.
_val_tpl_val_tpl
is not None:
86 self.
_val_tpl_val_tpl.async_render_with_possible_json_value(data,
None)
_attr_native_unit_of_measurement
None __init__(self, str unique_id, str name, str file_path, str|None unit_of_measurement, Template|None value_template)
None async_setup_entry(HomeAssistant hass, ConfigEntry entry, AddEntitiesCallback async_add_entities)