SMcommonHA 0.0.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
SMcommonHA/__init__.py ADDED
@@ -0,0 +1,16 @@
1
+ """Shared Home Assistant support for Sequent Microsystems cards."""
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Any
5
+
6
+
7
+ @dataclass
8
+ class Card:
9
+ """Card-specific configuration and hardware API."""
10
+
11
+ domain: str
12
+ legacy_domain: str
13
+ name_prefix: str
14
+ full_name: str
15
+ entity_map: dict[str, Any]
16
+ api: Any
@@ -0,0 +1,144 @@
1
+ DEFAULT_ICONS = {
2
+ "on": "mdi:numeric-1",
3
+ "off": "mdi:numeric-0",
4
+ }
5
+
6
+ import inspect
7
+ import logging
8
+ import time
9
+ import types
10
+ from datetime import datetime, timedelta
11
+ from inspect import signature
12
+
13
+ from homeassistant.components.binary_sensor import BinarySensorEntity
14
+ from homeassistant.helpers.entity import generate_entity_id
15
+ from homeassistant.helpers.event import async_track_time_interval
16
+
17
+ from . import Card
18
+ from .config_support import async_setup_entities
19
+ from .const import (
20
+ CONF_CHAN,
21
+ CONF_NAME,
22
+ CONF_STACK,
23
+ CONF_TYPE,
24
+ CONF_UPDATE_INTERVAL,
25
+ )
26
+
27
+ _LOGGER = logging.getLogger(__name__)
28
+
29
+
30
+ async def async_setup_entry(hass, entry, async_add_entities, card: Card):
31
+ def create(config):
32
+ return BinarySensor(
33
+ hass=hass,
34
+ name=config[CONF_NAME],
35
+ stack=config[CONF_STACK],
36
+ type=config[CONF_TYPE],
37
+ chan=config[CONF_CHAN],
38
+ update_interval=config.get(CONF_UPDATE_INTERVAL, 30),
39
+ card=card,
40
+ )
41
+
42
+ await async_setup_entities(
43
+ hass, entry, async_add_entities, "binary_sensor", create, card
44
+ )
45
+
46
+
47
+ class BinarySensor(BinarySensorEntity):
48
+ _attr_should_poll = False
49
+
50
+ def __init__(self, name, stack, type, chan, hass, update_interval, card: Card):
51
+ self._card = card
52
+ sm_map = card.entity_map["binary_sensor"]
53
+ generated_name = card.domain + str(stack) + "_" + type + "_" + str(chan)
54
+ self._attr_unique_id = generate_entity_id(
55
+ "binary_sensor.{}", generated_name, current_ids=[]
56
+ )
57
+ self._attr_name = name or generated_name
58
+ self._stack = int(stack)
59
+ self._type = type
60
+ self._chan = int(chan)
61
+ self._update_interval = float(update_interval)
62
+ self._short_timeout = 0.05
63
+ self._icons = DEFAULT_ICONS | sm_map[self._type].get("icon", {})
64
+ self._attr_icon = self._icons["off"]
65
+ self._uom = sm_map[self._type].get("uom", "")
66
+ self._attr_is_on = False
67
+ self._remove_hooks = []
68
+ self.__SM__init()
69
+ ### __CUSTOM_SETUP__ START
70
+ ### __CUSTOM_SETUP__ END
71
+
72
+ def __SM__init(self):
73
+ com = self._card.entity_map["binary_sensor"][self._type]["com"]
74
+ self._SM = self._card.api
75
+ if inspect.isclass(self._SM):
76
+ self._SM = self._card.api(self._stack)
77
+ self._SM_get = getattr(self._SM, com["get"])
78
+ if len(signature(self._SM_get).parameters) == 0:
79
+
80
+ def _aux2_SM_get(self, _):
81
+ return getattr(self, com["get"])()
82
+
83
+ self._SM_get = types.MethodType(_aux2_SM_get, self._SM)
84
+ else:
85
+ _SM_get = getattr(self._SM, com["get"])
86
+ if len(signature(_SM_get).parameters) == 1:
87
+
88
+ def _aux3_SM_get(_, *args):
89
+ return _SM_get(self._stack, *args)
90
+
91
+ self._SM_get = _aux3_SM_get
92
+ else:
93
+
94
+ def _aux_SM_get(*args):
95
+ return _SM_get(self._stack, *args)
96
+
97
+ self._SM_get = _aux_SM_get
98
+
99
+ async def async_added_to_hass(self):
100
+ async def update_state(_now: datetime) -> None:
101
+ await self.async_update_ha_state(True)
102
+
103
+ new_hook = async_track_time_interval(
104
+ self.hass, update_state, timedelta(seconds=self._update_interval)
105
+ )
106
+ self._remove_hooks.append(new_hook)
107
+
108
+ async def async_will_remove_from_hass(self):
109
+ for remove_hook in self._remove_hooks:
110
+ remove_hook()
111
+
112
+ def update(self):
113
+ time.sleep(self._short_timeout)
114
+ try:
115
+ value = self._SM_get(self._chan)
116
+ except Exception as ex:
117
+ _LOGGER.error(
118
+ self._card.domain + " %s update() failed, %s, %s, %s",
119
+ self._type,
120
+ ex,
121
+ str(self._stack),
122
+ str(self._chan),
123
+ )
124
+ return
125
+ if not isinstance(value, int) or value not in (0, 1):
126
+ _LOGGER.error(
127
+ self._card.domain + " %s invalid reading %r, %s, %s",
128
+ self._type,
129
+ value,
130
+ str(self._stack),
131
+ str(self._chan),
132
+ )
133
+ self._attr_is_on = None
134
+ self._attr_icon = None
135
+ return
136
+ self._attr_is_on = bool(value)
137
+ if self._attr_is_on:
138
+ self._attr_icon = self._icons["on"]
139
+ else:
140
+ self._attr_icon = self._icons["off"]
141
+
142
+ @property
143
+ def native_unit_of_measurement(self):
144
+ return self._uom
SMcommonHA/button.py ADDED
@@ -0,0 +1,60 @@
1
+ """Buttons shared by Sequent card integrations."""
2
+
3
+ import inspect
4
+ import logging
5
+ from functools import partial
6
+
7
+ from homeassistant.components.button import ButtonEntity
8
+ from homeassistant.const import CONF_NAME
9
+ from homeassistant.helpers.entity import generate_entity_id
10
+
11
+ from . import Card
12
+ from .config_support import async_setup_entities
13
+ from .const import CONF_CHAN, CONF_STACK, CONF_TYPE
14
+
15
+ DEFAULT_ICON = "mdi:button-pointer"
16
+ _LOGGER = logging.getLogger(__name__)
17
+
18
+
19
+ async def async_setup_entry(hass, entry, async_add_entities, card: Card):
20
+ def create(config):
21
+ return Button(
22
+ name=config[CONF_NAME],
23
+ stack=config[CONF_STACK],
24
+ type=config[CONF_TYPE],
25
+ chan=config[CONF_CHAN],
26
+ card=card,
27
+ )
28
+
29
+ await async_setup_entities(hass, entry, async_add_entities, "button", create, card)
30
+
31
+
32
+ class Button(ButtonEntity):
33
+ def __init__(self, name, stack, type, chan, card: Card):
34
+ self._card = card
35
+ generated_name = card.domain + str(stack) + "_" + type + "_" + str(chan)
36
+ self._attr_unique_id = generate_entity_id(
37
+ "button.{}", generated_name, current_ids=[]
38
+ )
39
+ self._attr_name = name or generated_name
40
+ self._stack = int(stack)
41
+ self._type = type
42
+ self._chan = int(chan)
43
+ metadata = card.entity_map["button"][type]
44
+ self._attr_icon = metadata.get("icon", {}).get("off", DEFAULT_ICON)
45
+
46
+ api = card.api
47
+ if inspect.isclass(api):
48
+ self._SM_set = getattr(card.api(self._stack), metadata["com"]["set"])
49
+ else:
50
+ self._SM_set = partial(getattr(api, metadata["com"]["set"]), self._stack)
51
+ self._has_channel = bool(inspect.signature(self._SM_set).parameters)
52
+
53
+ def press(self, **kwargs):
54
+ try:
55
+ if self._has_channel:
56
+ self._SM_set(self._chan)
57
+ else:
58
+ self._SM_set()
59
+ except Exception as ex:
60
+ _LOGGER.error("%s %s press failed, %s", self._card.domain, self._type, ex)
@@ -0,0 +1,132 @@
1
+ """UI configuration for a Sequent card."""
2
+
3
+ import math
4
+
5
+ import probatio as p
6
+ from homeassistant import config_entries
7
+ from homeassistant.helpers import selector
8
+
9
+ from . import Card
10
+ from .config_support import (
11
+ available_entities,
12
+ import_yaml_card,
13
+ )
14
+ from .const import (
15
+ CONF_ENTITIES,
16
+ CONF_INTERVALS,
17
+ CONF_STACK,
18
+ CONF_UPDATE_INTERVAL,
19
+ DEFAULT_INTERVAL,
20
+ )
21
+
22
+
23
+ def valid_interval(value):
24
+ """Reject intervals that cannot be used with a timer."""
25
+ value = float(value)
26
+ if not math.isfinite(value) or value <= 0:
27
+ raise p.Invalid("update interval must be finite and positive")
28
+ return value
29
+
30
+
31
+ class SequentConfigFlow(config_entries.ConfigFlow):
32
+ """Create one config entry per card address."""
33
+
34
+ VERSION = 1
35
+ card: Card
36
+
37
+ async def async_step_user(self, user_input=None):
38
+ if user_input is not None:
39
+ return await self._create_card(import_yaml_card(self.card, user_input))
40
+ return self.async_show_form(
41
+ step_id="user",
42
+ data_schema=p.Schema(
43
+ {
44
+ p.Required(CONF_STACK, default=0): p.All(
45
+ p.Coerce(int), p.Range(min=0, max=7)
46
+ )
47
+ }
48
+ ),
49
+ )
50
+
51
+ async def async_step_import(self, user_input):
52
+ return await self._create_card(user_input)
53
+
54
+ async def _create_card(self, card):
55
+ stack = card[CONF_STACK]
56
+ await self.async_set_unique_id(str(stack))
57
+ self._abort_if_unique_id_configured()
58
+ return self.async_create_entry(
59
+ title=f"{self.card.full_name} - stack {stack}", data=card
60
+ )
61
+
62
+
63
+ class SequentOptionsFlow(config_entries.OptionsFlowWithReload):
64
+ """Select entities and configure their update intervals."""
65
+
66
+ def __init__(self, card: Card):
67
+ self.card = card
68
+
69
+ async def async_step_init(self, user_input=None):
70
+ if user_input is not None:
71
+ self._selected = user_input[CONF_ENTITIES]
72
+ return await self.async_step_intervals()
73
+
74
+ available = available_entities(self.card, self.config_entry.data[CONF_STACK])
75
+ selected = self.config_entry.options.get(
76
+ CONF_ENTITIES, list(self.config_entry.data[CONF_ENTITIES])
77
+ )
78
+ return self.async_show_form(
79
+ step_id="init",
80
+ data_schema=p.Schema(
81
+ {
82
+ p.Required(
83
+ CONF_ENTITIES, default=selected
84
+ ): selector.SelectSelector(
85
+ selector.SelectSelectorConfig(
86
+ options=[
87
+ selector.SelectOptionDict(value=key, label=key)
88
+ for key in available
89
+ ],
90
+ multiple=True,
91
+ mode=selector.SelectSelectorMode.DROPDOWN,
92
+ )
93
+ )
94
+ }
95
+ ),
96
+ )
97
+
98
+ async def async_step_intervals(self, user_input=None):
99
+ available = available_entities(self.card, self.config_entry.data[CONF_STACK])
100
+ selected = self._selected
101
+ if user_input is not None:
102
+ return self.async_create_entry(
103
+ title="", data={CONF_ENTITIES: selected, CONF_INTERVALS: user_input}
104
+ )
105
+ imported = self.config_entry.data[CONF_ENTITIES]
106
+ intervals = self.config_entry.options.get(CONF_INTERVALS, {})
107
+ interval_entities = [
108
+ key
109
+ for key in selected
110
+ if available[key]["platform"] in ("sensor", "binary_sensor", "datetime")
111
+ ]
112
+ if not interval_entities:
113
+ return self.async_create_entry(
114
+ title="", data={CONF_ENTITIES: selected, CONF_INTERVALS: {}}
115
+ )
116
+ return self.async_show_form(
117
+ step_id="intervals",
118
+ data_schema=p.Schema(
119
+ {
120
+ p.Required(
121
+ key,
122
+ default=intervals.get(
123
+ key,
124
+ imported.get(key, {}).get(
125
+ CONF_UPDATE_INTERVAL, DEFAULT_INTERVAL
126
+ ),
127
+ ),
128
+ ): p.All(p.Coerce(float), valid_interval)
129
+ for key in interval_entities
130
+ }
131
+ ),
132
+ )
@@ -0,0 +1,159 @@
1
+ """Configuration helpers shared by the Sequent card integrations."""
2
+
3
+ import logging
4
+ import math
5
+
6
+ from homeassistant.exceptions import ConfigEntryError, PlatformNotReady
7
+ from homeassistant.helpers import entity_registry as er
8
+ from homeassistant.helpers.entity import generate_entity_id
9
+
10
+ from . import Card
11
+ from .const import (
12
+ CONF_CHAN,
13
+ CONF_CHAN_RANGE,
14
+ CONF_CHANNELS,
15
+ CONF_ENTITIES,
16
+ CONF_INTERVALS,
17
+ CONF_NAME,
18
+ CONF_STACK,
19
+ CONF_TYPE,
20
+ CONF_UPDATE_INTERVAL,
21
+ )
22
+
23
+ _LOGGER = logging.getLogger(__name__)
24
+
25
+
26
+ def available_entities(card: Card, stack):
27
+ """Return all entities supported by a card, indexed by type and channel."""
28
+ entities = {}
29
+ for platform, types in card.entity_map.items():
30
+ for entity_type, metadata in types.items():
31
+ for channel in range(1, int(metadata["chan_no"]) + 1):
32
+ key = f"{entity_type}_{channel}"
33
+ if key in entities:
34
+ raise ValueError(f"Duplicate entity configuration key: {key}")
35
+ entities[key] = {
36
+ CONF_NAME: f"{card.name_prefix}{stack}_{key}",
37
+ CONF_STACK: stack,
38
+ CONF_TYPE: entity_type,
39
+ CONF_CHAN: channel,
40
+ "platform": platform,
41
+ "optional": metadata.get("optional", False),
42
+ }
43
+ return entities
44
+
45
+
46
+ def import_yaml_card(card: Card, config):
47
+ """Convert one legacy YAML card into a config-entry configuration."""
48
+ stack = int(config.get(CONF_STACK, 0))
49
+ available = available_entities(card, stack)
50
+ configured = {key: value for key, value in config.items() if key != CONF_STACK}
51
+ if not configured:
52
+ selected = {
53
+ key: entity for key, entity in available.items() if not entity["optional"]
54
+ }
55
+ else:
56
+ selected = {}
57
+ for name, options in configured.items():
58
+ options = options or {}
59
+ try:
60
+ channels = options.get(CONF_CHANNELS)
61
+ channel_range = options.get(CONF_CHAN_RANGE)
62
+ if channels is not None:
63
+ if not isinstance(channels, str):
64
+ raise ValueError("channels must be a comma-separated string")
65
+ channel_numbers = [int(channel) for channel in channels.split(",")]
66
+ if len(channel_numbers) != len(set(channel_numbers)):
67
+ raise ValueError("duplicate channels")
68
+ entity_type = name
69
+ elif channel_range is not None:
70
+ if not isinstance(channel_range, str):
71
+ raise ValueError("chan_range must be a start..end string")
72
+ start, end = (int(channel) for channel in channel_range.split(".."))
73
+ if end < start:
74
+ raise ValueError("end must not be less than start")
75
+ channel_numbers = range(start, end + 1)
76
+ entity_type = name
77
+ else:
78
+ entity_type, channel = name.rsplit("_", 1)
79
+ channel_numbers = [int(channel)]
80
+ interval = options.get(CONF_UPDATE_INTERVAL)
81
+ if interval is not None and (
82
+ not math.isfinite(float(interval)) or float(interval) <= 0
83
+ ):
84
+ raise ValueError("update_interval must be finite and positive")
85
+ keys = [f"{entity_type}_{channel}" for channel in channel_numbers]
86
+ if any(key not in available for key in keys):
87
+ raise ValueError("unknown entity type or channel")
88
+ except (AttributeError, TypeError, ValueError) as err:
89
+ _LOGGER.error("Invalid YAML entity %s: %s", name, err)
90
+ continue
91
+ for key in keys:
92
+ entity = available[key].copy()
93
+ if interval is not None:
94
+ entity[CONF_UPDATE_INTERVAL] = float(interval)
95
+ selected[key] = entity
96
+ return {CONF_STACK: stack, CONF_ENTITIES: selected}
97
+
98
+
99
+ def entry_entities(card: Card, entry):
100
+ """Return selected entities, preserving imported settings and applying options."""
101
+ available = available_entities(card, entry.data[CONF_STACK])
102
+ imported = entry.data[CONF_ENTITIES]
103
+ selected = entry.options.get(CONF_ENTITIES, list(imported))
104
+ intervals = entry.options.get(CONF_INTERVALS, {})
105
+ entities = []
106
+ for key in selected:
107
+ entity = {**available[key], **imported.get(key, {})}
108
+ if key in intervals:
109
+ entity[CONF_UPDATE_INTERVAL] = intervals[key]
110
+ entities.append(entity)
111
+ return entities
112
+
113
+
114
+ async def async_setup_entities(
115
+ hass, entry, async_add_entities, platform, factory, card: Card
116
+ ):
117
+ """Create one platform's entities without blocking the event loop."""
118
+ configs = [item for item in entry.runtime_data if item["platform"] == platform]
119
+ registry = er.async_get(hass)
120
+ entities = []
121
+ for config in configs:
122
+ base_id = generate_entity_id(
123
+ f"{platform}.{{}}",
124
+ f"{card.domain}{config[CONF_STACK]}_{config[CONF_TYPE]}_{config[CONF_CHAN]}",
125
+ current_ids=[],
126
+ )
127
+ unique_id = base_id
128
+ if not registry.async_get_entity_id(platform, card.domain, base_id):
129
+ matches = [
130
+ item.unique_id
131
+ for item in registry.entities.values()
132
+ if item.domain == platform
133
+ and item.platform == card.domain
134
+ and item.config_entry_id in (None, entry.entry_id)
135
+ and item.original_name == config[CONF_NAME]
136
+ and item.unique_id.startswith(base_id + "_")
137
+ and item.unique_id[len(base_id) + 1 :].isdigit()
138
+ ]
139
+ if len(matches) > 1:
140
+ raise ConfigEntryError(
141
+ f"Ambiguous legacy entity for {config[CONF_NAME]}"
142
+ )
143
+ if matches:
144
+ unique_id = matches[0]
145
+ try:
146
+ entity = await hass.async_add_executor_job(factory, config)
147
+ except OSError as err:
148
+ raise PlatformNotReady(
149
+ f"Cannot initialize {config[CONF_NAME]}: {err}"
150
+ ) from err
151
+ entity._unique_id = unique_id
152
+ entity._attr_unique_id = unique_id
153
+ entity._attr_device_info = {
154
+ "identifiers": {(entry.domain, str(config[CONF_STACK]))},
155
+ "manufacturer": "Sequent Microsystems",
156
+ "model": card.full_name,
157
+ }
158
+ entities.append(entity)
159
+ async_add_entities(entities)
SMcommonHA/const.py ADDED
@@ -0,0 +1,14 @@
1
+ """Shared card configuration keys."""
2
+
3
+ from homeassistant.const import CONF_NAME
4
+
5
+ CONF_STACK = "stack"
6
+ CONF_TYPE = "type"
7
+ CONF_CHAN = "chan"
8
+ CONF_CHAN_RANGE = "chan_range"
9
+ CONF_CHANNELS = "channels"
10
+ CONF_UPDATE_INTERVAL = "update_interval"
11
+ CONF_ENTITIES = "entities"
12
+ CONF_INTERVALS = "intervals"
13
+ DEFAULT_INTERVAL = 30
14
+ COM_NOGET = "__NOGET__"
SMcommonHA/datetime.py ADDED
@@ -0,0 +1,133 @@
1
+ """RTC datetime entities for Sequent card integrations."""
2
+
3
+ import inspect
4
+ import logging
5
+ from datetime import datetime, timedelta, timezone
6
+ from functools import partial
7
+
8
+ from homeassistant.components.datetime import DateTimeEntity
9
+ from homeassistant.helpers.entity import generate_entity_id
10
+ from homeassistant.helpers.event import async_track_time_interval
11
+
12
+ from . import Card
13
+ from .config_support import async_setup_entities
14
+ from .const import CONF_CHAN, CONF_NAME, CONF_STACK, CONF_TYPE, CONF_UPDATE_INTERVAL
15
+
16
+ _LOGGER = logging.getLogger(__name__)
17
+ DEFAULT_ICONS = {"on": "mdi:clock", "off": "mdi:clock-alert"}
18
+
19
+
20
+ async def async_setup_entry(hass, entry, async_add_entities, card: Card):
21
+ def create(config):
22
+ return CardDateTime(
23
+ name=config[CONF_NAME],
24
+ stack=config[CONF_STACK],
25
+ type=config[CONF_TYPE],
26
+ chan=config[CONF_CHAN],
27
+ update_interval=config.get(CONF_UPDATE_INTERVAL, 30),
28
+ card=card,
29
+ )
30
+
31
+ await async_setup_entities(
32
+ hass, entry, async_add_entities, "datetime", create, card
33
+ )
34
+
35
+
36
+ class CardDateTime(DateTimeEntity):
37
+ """A card RTC whose calendar fields represent UTC."""
38
+
39
+ _attr_should_poll = False
40
+
41
+ def __init__(self, name, stack, type, chan, update_interval, card: Card):
42
+ self._card = card
43
+ self._stack = int(stack)
44
+ self._type = type
45
+ self._chan = int(chan)
46
+ self._update_interval = float(update_interval)
47
+ generated_name = card.domain + str(stack) + "_" + type + "_" + str(chan)
48
+ self._attr_unique_id = generate_entity_id(
49
+ "datetime.{}", generated_name, current_ids=[]
50
+ )
51
+ self._attr_name = name or generated_name
52
+ metadata = card.entity_map["datetime"][type]
53
+ self._icons = DEFAULT_ICONS | metadata.get("icon", {})
54
+
55
+ api = card.api
56
+ if inspect.isclass(api):
57
+ api = card.api(self._stack)
58
+ self._get_rtc = getattr(api, metadata["com"]["get"])
59
+ self._set_rtc = getattr(api, metadata["com"]["set"])
60
+ else:
61
+ self._get_rtc = partial(getattr(api, metadata["com"]["get"]), self._stack)
62
+ self._set_rtc = partial(getattr(api, metadata["com"]["set"]), self._stack)
63
+
64
+ self._attr_native_value = self._read_rtc()
65
+ self._attr_icon = self._icons["on" if self._attr_native_value else "off"]
66
+
67
+ def _read_rtc(self):
68
+ try:
69
+ value = self._get_rtc()
70
+ if (
71
+ not isinstance(value, (tuple, list))
72
+ or len(value) != 6
73
+ or any(
74
+ not isinstance(part, int) or isinstance(part, bool)
75
+ for part in value
76
+ )
77
+ ):
78
+ raise ValueError(f"expected six integer fields, got {value!r}")
79
+ return datetime(*value, tzinfo=timezone.utc)
80
+ except (TypeError, ValueError, OverflowError) as err:
81
+ _LOGGER.error(
82
+ "%s %s invalid RTC reading for stack %s: %s",
83
+ self._card.domain,
84
+ self._type,
85
+ self._stack,
86
+ err,
87
+ )
88
+ return None
89
+
90
+ async def async_added_to_hass(self):
91
+ await super().async_added_to_hass()
92
+
93
+ async def update_state(_now: datetime) -> None:
94
+ await self.async_update_ha_state(True)
95
+
96
+ self.async_on_remove(
97
+ async_track_time_interval(
98
+ self.hass, update_state, timedelta(seconds=self._update_interval)
99
+ )
100
+ )
101
+
102
+ def update(self):
103
+ try:
104
+ self._attr_native_value = self._read_rtc()
105
+ except OSError as err:
106
+ _LOGGER.error(
107
+ "%s %s RTC read failed for stack %s: %s",
108
+ self._card.domain,
109
+ self._type,
110
+ self._stack,
111
+ err,
112
+ )
113
+ self._attr_native_value = None
114
+ self._attr_icon = self._icons["on" if self._attr_native_value else "off"]
115
+
116
+ def set_value(self, value: datetime) -> None:
117
+ if value.tzinfo is None or value.utcoffset() is None:
118
+ raise ValueError("RTC datetime must include a time zone")
119
+ utc_value = value.astimezone(timezone.utc).replace(microsecond=0)
120
+ self._set_rtc(
121
+ utc_value.year,
122
+ utc_value.month,
123
+ utc_value.day,
124
+ utc_value.hour,
125
+ utc_value.minute,
126
+ utc_value.second,
127
+ )
128
+ self._attr_native_value = utc_value
129
+ self._attr_icon = self._icons["on"]
130
+
131
+ async def async_set_value(self, value: datetime) -> None:
132
+ await super().async_set_value(value)
133
+ self.async_write_ha_state()