-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy path__init__.py
More file actions
843 lines (759 loc) · 29.5 KB
/
Copy path__init__.py
File metadata and controls
843 lines (759 loc) · 29.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
# Copyright 2026 Andreas Schneider
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""E-ink dashboard Home Assistant integration setup."""
from __future__ import annotations
import datetime as dt
import json
import logging
from datetime import timedelta
from functools import partial
from pathlib import Path
from typing import TYPE_CHECKING, Any, cast
import voluptuous as vol
from homeassistant.components import websocket_api
from homeassistant.components.frontend import add_extra_js_url
from homeassistant.components.http import StaticPathConfig
from homeassistant.helpers import area_registry as ar
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers import device_registry as dr
if TYPE_CHECKING:
from collections.abc import Mapping
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from .battery import resolve_battery_level
from .const import (
DEFAULT_DISPLAY_LEVELS,
DEFAULT_EXPOSURE,
DEFAULT_HEIGHT,
DEFAULT_SATURATION,
DEFAULT_WIDTH,
DEVICE_PRESETS,
DOMAIN,
DateFormat,
NumberFormat,
TimeFormat,
WidgetType,
resolve_display,
)
from .http import EinkLayoutView, EinkPublicImageView
from .store import EinkDashboardStore
from .svg_render import render_widget_svg
_LOGGER = logging.getLogger(__name__)
PLATFORMS = ["image", "sensor"]
CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN)
def _area_name(hass: HomeAssistant, area_id: str | None) -> str | None:
"""Return the area name for the given area_id, or None."""
if not area_id:
return None
area_reg = ar.async_get(hass)
area_entry = area_reg.async_get_area(area_id)
return area_entry.name if area_entry else None
def _register_device(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Create or update the HA device registry entry for this config entry."""
preset = DEVICE_PRESETS.get(entry.options.get("device_model", "custom"))
device_reg = dr.async_get(hass)
device_reg.async_get_or_create(
config_entry_id=entry.entry_id,
identifiers={(DOMAIN, entry.entry_id)},
name=entry.title,
manufacturer=(
preset.manufacturer if preset and preset.manufacturer else None
),
model=preset.label if preset else "Custom",
suggested_area=_area_name(hass, entry.options.get("area_id")),
)
async def _async_update_listener(
hass: HomeAssistant, entry: ConfigEntry
) -> None:
"""Re-register the device when options are updated."""
_register_device(hass, entry)
async def _async_get_locale(
hass: HomeAssistant,
options: Mapping[str, Any] | None = None,
) -> tuple[str, str, str, str, str]:
"""Return locale settings for server-side rendering.
Returns a 5-tuple
``(number_format, language, first_weekday, date_format,
time_format)``.
Reads the owner's frontend locale preferences (the ``language``
key stored via ``frontend/set_user_data``) and falls back to
``hass.config.language`` when the owner cannot be determined or
when the frontend component is not available. Per-device
overrides in ``options`` (``locale_number_format``,
``locale_language``, ``locale_first_weekday``,
``locale_date_format``, ``locale_time_format``) take precedence
over the owner's preferences when non-empty.
Args:
hass: Home Assistant instance.
options: Config entry options dict, used to apply per-device
locale overrides. ``None`` means no overrides.
Returns:
A 5-tuple suitable for passing into a ``DisplayConfig`` dict:
``number_format`` (a ``NumberFormat`` string value),
``language`` (BCP 47 tag),
``first_weekday`` (e.g. ``"monday"``),
``date_format`` (a ``DateFormat`` string value),
``time_format`` (a ``TimeFormat`` string value).
"""
fallback_language = hass.config.language
number_format: str = NumberFormat.LANGUAGE
language: str = fallback_language
first_weekday: str = "language"
date_format: str = DateFormat.LANGUAGE
time_format: str = TimeFormat.LANGUAGE
try:
from homeassistant.components.frontend.storage import (
async_user_store,
)
except ImportError:
pass
else:
try:
owner = await hass.auth.async_get_owner()
if owner is not None:
store = await async_user_store(hass, owner.id)
locale_data = store.data.get("language")
if isinstance(locale_data, dict):
number_format = str(
locale_data.get("number_format", NumberFormat.LANGUAGE)
)
language = str(
locale_data.get("language", fallback_language)
)
first_weekday = str(
locale_data.get("first_weekday", "language")
)
date_format = str(
locale_data.get("date_format", DateFormat.LANGUAGE)
)
time_format = str(
locale_data.get("time_format", TimeFormat.LANGUAGE)
)
except (AttributeError, KeyError, TypeError) as exc:
# Owner lookup or store access failed — log and fall back.
_LOGGER.debug(
"Could not read owner locale from frontend storage: %s",
exc,
)
# Apply per-device overrides from the config entry options.
# Reject unrecognised values so stale or hand-edited configs
# cannot inject garbage into the renderer.
_valid_fw = {
"language",
"monday",
"tuesday",
"wednesday",
"thursday",
"friday",
"saturday",
"sunday",
}
if options is not None:
override_nf = options.get("locale_number_format", "")
if override_nf:
if override_nf in NumberFormat._value2member_map_:
number_format = override_nf
else:
_LOGGER.warning(
"Ignoring unrecognised locale_number_format %r",
override_nf,
)
override_lang = options.get("locale_language", "")
if override_lang:
language = override_lang
override_fw = options.get("locale_first_weekday", "")
if override_fw:
if override_fw in _valid_fw:
first_weekday = override_fw
else:
_LOGGER.warning(
"Ignoring unrecognised locale_first_weekday %r",
override_fw,
)
override_df = options.get("locale_date_format", "")
if override_df:
if override_df in DateFormat._value2member_map_:
date_format = override_df
else:
_LOGGER.warning(
"Ignoring unrecognised locale_date_format %r",
override_df,
)
override_tf = options.get("locale_time_format", "")
if override_tf:
if override_tf in TimeFormat._value2member_map_:
time_format = override_tf
else:
_LOGGER.warning(
"Ignoring unrecognised locale_time_format %r",
override_tf,
)
return number_format, language, first_weekday, date_format, time_format
async def _build_display_config(
hass: HomeAssistant, entry_id: str
) -> dict[str, Any]:
"""Build a DisplayConfig for rendering a widget preview.
Snapshots current HA entity states, reads display dimensions from
the config entry options, and reads the owner's locale preferences
via :func:`_async_get_locale`. Caller must ensure
``entry_id`` exists in ``hass.data[DOMAIN]``.
Args:
hass: Home Assistant instance.
entry_id: Config entry ID present in ``hass.data[DOMAIN]``.
Returns:
Dict with ``width``, ``height``, ``display_levels``,
``number_format``, ``language``, ``first_weekday``,
``date_format``, ``time_format``, ``states``, and (when
battery data is available) ``device_battery_level`` and
``device_battery_charging`` keys suitable for
``render_widget_svg()``.
"""
entry_data = hass.data[DOMAIN][entry_id]
entry = entry_data["entry"]
states: dict[str, Any] = {}
for state in hass.states.async_all():
states[state.entity_id] = {
"state": state.state,
# Shallow copy: _fetch_forecasts adds a "forecast"
# key to this dict. A shallow copy is sufficient
# because it only assigns new keys, never mutates
# existing nested values.
"attributes": dict(state.attributes),
}
(
number_format,
language,
first_weekday,
date_format,
time_format,
) = await _async_get_locale(hass, entry.options)
config: dict[str, Any] = {
"width": entry.options.get("width", DEFAULT_WIDTH),
"height": entry.options.get("height", DEFAULT_HEIGHT),
"display_levels": entry.options.get(
"display_levels", DEFAULT_DISPLAY_LEVELS
),
"color_scheme": entry.options.get("color_scheme"),
"number_format": number_format,
"language": language,
"first_weekday": first_weekday,
"date_format": date_format,
"time_format": time_format,
"states": states,
}
level, is_charging = resolve_battery_level(
entry.options.get("battery_entity_id"),
states,
entry_data.get("battery_sensor"),
)
if level is not None:
config["device_battery_level"] = level
config["device_battery_charging"] = is_charging
return config
async def _fetch_forecasts(
hass: HomeAssistant,
widgets: list[dict[str, Any]],
states: dict[str, Any],
) -> None:
"""Fetch daily forecasts for weather widgets and inject into states.
Calls the ``weather.get_forecasts`` service for each unique
weather entity referenced by ``widgets`` and writes the forecast
list into ``states[entity_id]["attributes"]["forecast"]`` so
``render_widget_svg`` sees the same data as the scheduled image
render path.
Args:
hass: Home Assistant instance.
widgets: Widget dicts to scan for weather entity IDs.
states: Mutable states dict built by ``_build_display_config``.
"""
weather_entities: set[str] = set()
for w in widgets:
# WidgetType is a StrEnum: wire-format strings compare equal.
if w.get("type") == WidgetType.WEATHER:
eid = w.get("entity", "")
if eid and eid in states:
weather_entities.add(eid)
for entity_id in weather_entities:
try:
result = await hass.services.async_call(
"weather",
"get_forecasts",
{"entity_id": entity_id, "type": "daily"},
blocking=True,
return_response=True,
)
if result is None:
continue
entity_data = result.get(entity_id)
forecast = (
entity_data.get("forecast")
if isinstance(entity_data, dict)
else None
) or []
states[entity_id]["attributes"]["forecast"] = forecast
except Exception: # noqa: BLE001
_LOGGER.debug("Could not fetch forecast for %s", entity_id)
async def _fetch_history(
hass: HomeAssistant,
widgets: list[dict[str, Any]],
states: dict[str, Any],
) -> None:
"""Fetch state history for sensor and graph widgets.
Scans ``widgets`` for sensor widgets with ``graph == "line"``
and for graph widgets, then fetches compressed state history
from the recorder component for each referenced entity and
writes it into ``states[entity_id]["history"]`` as a list of
``{"s": state_str, "lu": unix_timestamp_float}`` dicts so the
context builders can compute graph coordinates without real-time
HA access.
Silently skips if the recorder is not loaded or if fetching fails
for any individual entity. Tests inject history data directly
into the states dict and never call this function.
Args:
hass: Home Assistant instance.
widgets: Widget dicts to scan for widgets needing history
data.
states: Mutable states dict built by ``_build_display_config``.
"""
# Build a map of entity_id → maximum hours_to_show across all
# widgets that require history data.
sensor_entities: dict[str, int] = {}
for w in widgets:
needs_history = (
w.get("type") == WidgetType.SENSOR and w.get("graph") == "line"
) or w.get("type") == WidgetType.GRAPH
if needs_history:
# Collect all entity IDs from the entities list,
# single entity= key, and flat editor keys entity_2/3.
# Entities configured with data_source="attribute" read
# a forecast-style attribute instead, so they are
# skipped here to avoid an unnecessary recorder query.
eids: list[str] = []
entities_list = w.get("entities")
if isinstance(entities_list, list):
for e in entities_list:
if isinstance(e, dict):
eid = str(e.get("entity", ""))
if eid and e.get("data_source") != "attribute":
eids.append(eid)
if not eids:
if w.get("data_source") != "attribute":
eid = str(w.get("entity", ""))
if eid:
eids.append(eid)
for suffix in ("_2", "_3"):
eid2 = str(w.get(f"entity{suffix}", ""))
if eid2:
eids.append(eid2)
for eid in eids:
if eid in states:
try:
hours = max(1, int(w.get("hours_to_show", 24)))
except (ValueError, TypeError):
hours = 24
if hours > sensor_entities.get(eid, 0):
sensor_entities[eid] = hours
if not sensor_entities:
return
if "recorder" not in hass.config.components:
_LOGGER.debug("_fetch_history: recorder not loaded, skipping history")
return
from homeassistant.components.recorder import get_instance
from homeassistant.components.recorder.history import (
get_significant_states,
)
now = dt.datetime.now(dt.UTC)
for entity_id, hours in sensor_entities.items():
start_time = now - timedelta(hours=hours)
try:
result = await get_instance(hass).async_add_executor_job(
partial(
get_significant_states,
hass,
start_time,
end_time=None,
entity_ids=[entity_id],
filters=None,
include_start_time_state=True,
significant_changes_only=True,
minimal_response=False,
no_attributes=True,
compressed_state_format=True,
),
)
except Exception: # noqa: BLE001
_LOGGER.debug(
"_fetch_history: could not fetch history for %s",
entity_id,
)
continue
raw = cast("list[dict[str, Any]]", result.get(entity_id, []))
entries: list[dict[str, object]] = [
{"s": str(e.get("s", "")), "lu": float(e.get("lu", 0.0))}
for e in raw
]
if entries:
states[entity_id]["history"] = entries
async def _fetch_calendar_events(
hass: HomeAssistant,
widgets: list[dict[str, Any]],
states: dict[str, Any],
) -> None:
"""Fetch upcoming events for calendar widgets and inject into states.
Calls the ``calendar.get_events`` service for each unique calendar
entity referenced by ``widgets`` and writes the event list into
``states[entity_id]["attributes"]["events"]`` so the widget
context builder can access multiple events without real-time HA
access at render time.
The fetch window starts at the current time and extends to the
maximum ``days_ahead`` configured across all calendar widgets that
reference the same entity. Silently skips any entity where the
service call fails (entity offline, integration not loaded, etc.).
Args:
hass: Home Assistant instance.
widgets: Widget dicts to scan for calendar entity IDs.
states: Mutable states dict; events are injected in-place
under ``states[entity_id]["attributes"]["events"]``.
"""
calendar_entities: dict[str, int] = {}
for w in widgets:
if w.get("type") == WidgetType.CALENDAR:
eid = w.get("entity", "")
if not eid:
continue
if eid not in states:
_LOGGER.warning(
"Calendar entity %r is not in the states snapshot; "
"events will not be fetched and the widget will render "
"blank. Check that the entity exists in Home Assistant.",
eid,
)
continue
try:
days = max(1, int(w.get("days_ahead", 7)))
except (ValueError, TypeError):
days = 7
if days > calendar_entities.get(eid, 0):
calendar_entities[eid] = days
if not calendar_entities:
return
now = dt.datetime.now(dt.UTC)
for entity_id, days in calendar_entities.items():
end_dt = now + timedelta(days=days)
try:
result = await hass.services.async_call(
"calendar",
"get_events",
{
"entity_id": entity_id,
"start_date_time": now.isoformat(),
"end_date_time": end_dt.isoformat(),
},
blocking=True,
return_response=True,
)
if result is None:
continue
entity_data = result.get(entity_id)
raw = (
entity_data.get("events")
if isinstance(entity_data, dict)
else None
)
events: list[dict[str, Any]] = cast(
"list[dict[str, Any]]",
raw if isinstance(raw, list) else [],
)
states[entity_id]["attributes"]["events"] = events
except Exception: # noqa: BLE001
_LOGGER.debug("Could not fetch calendar events for %s", entity_id)
@websocket_api.websocket_command(
{
vol.Required("type"): "eink_dashboard/render_widget",
vol.Required("entry_id"): str,
vol.Required("widget_index"): vol.All(int, vol.Range(min=0)),
vol.Optional("widget"): dict,
}
)
@websocket_api.async_response
async def ws_render_widget(
hass: HomeAssistant,
connection: websocket_api.ActiveConnection,
msg: dict[str, Any],
) -> None:
"""Return the SVG string for a single widget.
When ``widget`` is provided it is used as-is instead of the
stored widget at ``widget_index``. This allows the frontend
editor to preview unsaved local changes.
Args:
hass: Home Assistant instance.
connection: Active WebSocket connection.
msg: Validated message dict containing ``entry_id`` (str),
``widget_index`` (int), and an optional ``widget``
(dict) override.
"""
entry_id = msg["entry_id"]
entry_data = hass.data.get(DOMAIN, {}).get(entry_id)
if entry_data is None:
connection.send_error(
msg["id"],
websocket_api.ERR_NOT_FOUND,
f"Config entry not found: {entry_id}",
)
return
widget = msg.get("widget")
if widget is None:
widgets = list(entry_data["widgets"])
idx = msg["widget_index"]
if idx < 0 or idx >= len(widgets):
connection.send_error(
msg["id"],
websocket_api.ERR_NOT_FOUND,
f"Widget index out of range: {idx}",
)
return
widget = widgets[idx]
config = await _build_display_config(hass, entry_id)
await _fetch_forecasts(hass, [widget], config["states"])
await _fetch_history(hass, [widget], config["states"])
await _fetch_calendar_events(hass, [widget], config["states"])
try:
svg = await hass.async_add_executor_job(
render_widget_svg, widget, config
)
except KeyError as exc:
connection.send_error(
msg["id"],
websocket_api.ERR_NOT_FOUND,
f"Unknown widget type: {exc}",
)
return
except Exception as exc: # noqa: BLE001
connection.send_error(
msg["id"],
websocket_api.ERR_UNKNOWN_ERROR,
str(exc),
)
return
connection.send_result(msg["id"], {"svg": svg})
@websocket_api.websocket_command(
{
vol.Required("type"): "eink_dashboard/render_widgets",
vol.Required("entry_id"): str,
vol.Optional("widgets"): [dict],
}
)
@websocket_api.async_response
async def ws_render_widgets(
hass: HomeAssistant,
connection: websocket_api.ActiveConnection,
msg: dict[str, Any],
) -> None:
"""Return SVG strings for all widgets in one call.
Renders every widget for the given config entry and returns
their SVG strings as a list in widget-list order. Use this
command on initial load or full refresh to avoid N sequential
round-trips.
When ``widgets`` is provided it overrides the stored widget
list. This allows the frontend editor to preview unsaved
local changes without saving first.
Args:
hass: Home Assistant instance.
connection: Active WebSocket connection.
msg: Validated message dict containing ``entry_id`` (str)
and an optional ``widgets`` (list) override.
"""
entry_id = msg["entry_id"]
entry_data = hass.data.get(DOMAIN, {}).get(entry_id)
if entry_data is None:
connection.send_error(
msg["id"],
websocket_api.ERR_NOT_FOUND,
f"Config entry not found: {entry_id}",
)
return
widgets = msg.get("widgets") or list(entry_data["widgets"])
config = await _build_display_config(hass, entry_id)
await _fetch_forecasts(hass, widgets, config["states"])
await _fetch_history(hass, widgets, config["states"])
await _fetch_calendar_events(hass, widgets, config["states"])
# Render all widgets in a single executor job: render_widget_svg
# is CPU-bound (Jinja2 + resvg), and one thread per widget would
# add overhead without parallelism gains under the GIL. If any
# widget fails the entire batch errors out -- partial results are
# not returned.
def _render_all() -> list[str]:
return [render_widget_svg(w, config) for w in widgets]
try:
svgs = await hass.async_add_executor_job(_render_all)
except KeyError as exc:
connection.send_error(
msg["id"],
websocket_api.ERR_NOT_FOUND,
f"Unknown widget type: {exc}",
)
return
except Exception as exc: # noqa: BLE001
connection.send_error(
msg["id"],
websocket_api.ERR_UNKNOWN_ERROR,
str(exc),
)
return
connection.send_result(msg["id"], {"svgs": svgs})
_FRONTEND_DIR = Path(__file__).parent / "frontend"
_FONTS_DIR = Path(__file__).parent / "fonts"
_ICONS_DIR = Path(__file__).parent / "icons"
_MANIFEST = json.loads(
(Path(__file__).parent / "manifest.json").read_text(encoding="utf-8")
)
_VERSION = _MANIFEST["version"]
async def async_setup(hass: HomeAssistant, config: dict[str, Any]) -> bool:
"""Register HTTP views and static paths for the integration."""
_LOGGER.debug("async_setup: registering HTTP views and static paths")
hass.data.setdefault(DOMAIN, {})
hass.http.register_view(EinkPublicImageView())
hass.http.register_view(EinkLayoutView())
await hass.http.async_register_static_paths(
[
StaticPathConfig(
"/eink_dashboard/frontend",
str(_FRONTEND_DIR),
False,
),
StaticPathConfig(
"/eink_dashboard/fonts",
str(_FONTS_DIR),
True,
),
StaticPathConfig(
"/eink_dashboard/icons",
str(_ICONS_DIR),
True,
),
]
)
add_extra_js_url(
hass,
f"/eink_dashboard/frontend/eink-dashboard-card.js?v={_VERSION}",
)
websocket_api.async_register_command(hass, ws_render_widget)
websocket_api.async_register_command(hass, ws_render_widgets)
_LOGGER.debug("async_setup: complete")
return True
async def async_migrate_entry(
hass: HomeAssistant, config_entry: ConfigEntry
) -> bool:
"""Migrate a config entry to the current schema version.
Version 1.1 → 1.2: replace ``sharpness`` and ``contrast`` with
``exposure`` and ``saturation``. ``sharpness`` has no equivalent
in epaper-dithering; ``contrast`` is superseded by ``exposure``.
Both new keys default to 1.0 (no change).
Version 1.2 → 1.3: rename ``grayscale_levels`` to
``display_levels`` so the option name also fits future color
e-ink displays.
Version 1.3 → 1.4: recompute ``width``, ``height``, and
``rotation`` for ``reterminal_e1003`` entries. The device's
native orientation preset was previously wrong, so entries
created before the fix have a stale ``rotation`` baked in that
produces a 90°-rotated image.
Args:
hass: Home Assistant instance.
config_entry: The config entry to migrate.
Returns:
``True`` if migration succeeded or was not needed.
"""
if config_entry.minor_version == 1:
_LOGGER.debug(
"Migrating %s from minor version %d to 2",
config_entry.entry_id,
config_entry.minor_version,
)
new_options = dict(config_entry.options)
new_options.pop("sharpness", None)
new_options.pop("contrast", None)
new_options.setdefault("exposure", DEFAULT_EXPOSURE)
new_options.setdefault("saturation", DEFAULT_SATURATION)
hass.config_entries.async_update_entry(
config_entry,
options=new_options,
minor_version=2,
)
if config_entry.minor_version == 2:
_LOGGER.debug(
"Migrating %s from minor version %d to 3",
config_entry.entry_id,
config_entry.minor_version,
)
new_options = dict(config_entry.options)
if "grayscale_levels" in new_options:
new_options["display_levels"] = new_options.pop("grayscale_levels")
hass.config_entries.async_update_entry(
config_entry,
options=new_options,
minor_version=3,
)
if config_entry.minor_version == 3:
_LOGGER.debug(
"Migrating %s from minor version %d to 4",
config_entry.entry_id,
config_entry.minor_version,
)
new_options = dict(config_entry.options)
if new_options.get("device_model") == "reterminal_e1003":
orientation = new_options.get("orientation", "landscape")
width, height, rotation, _preset = resolve_display(
"reterminal_e1003", orientation
)
new_options["width"] = width
new_options["height"] = height
new_options["rotation"] = rotation
hass.config_entries.async_update_entry(
config_entry,
options=new_options,
minor_version=4,
)
return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Load persisted widgets and forward setup to the image platform."""
_LOGGER.debug(
"async_setup_entry: entry_id=%s title=%r", entry.entry_id, entry.title
)
store = EinkDashboardStore(hass, entry.entry_id)
widgets = await store.async_load()
_LOGGER.debug(
"async_setup_entry: loaded %d widgets for %s",
len(widgets),
entry.entry_id,
)
hass.data[DOMAIN][entry.entry_id] = {
"store": store,
"widgets": widgets,
"entry": entry,
}
_register_device(hass, entry)
entry.async_on_unload(entry.add_update_listener(_async_update_listener))
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
_LOGGER.debug(
"async_setup_entry: platforms forwarded for %s", entry.entry_id
)
return True
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload platforms and clean up runtime data for the entry."""
_LOGGER.debug("async_unload_entry: %s", entry.entry_id)
ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if ok:
hass.data[DOMAIN].pop(entry.entry_id)
_LOGGER.debug("async_unload_entry: %s ok=%s", entry.entry_id, ok)
return ok