-
-
Notifications
You must be signed in to change notification settings - Fork 150
Expand file tree
/
Copy pathcomponent_base.py
More file actions
404 lines (333 loc) · 15.3 KB
/
Copy pathcomponent_base.py
File metadata and controls
404 lines (333 loc) · 15.3 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
# -----------------------------------------------------------------------------
# Predbat Home Battery System
# Copyright Trefor Southwell 2026 - All Rights Reserved
# This application maybe used for personal use only and not for commercial use
# -----------------------------------------------------------------------------
# fmt off
# pylint: disable=consider-using-f-string
# pylint: disable=line-too-long
# pylint: disable=attribute-defined-outside-init
"""Abstract base class for all PredBat components.
Provides standardised lifecycle management (initialise, start, stop),
health monitoring with exponential backoff on startup failures, error
counting, and delegation to the main PredBat instance for HA operations.
All component types (HAInterface, WebInterface, SolarAPI, etc.) inherit
from this class.
"""
from abc import ABC, abstractmethod
from datetime import datetime, timezone
import asyncio
import time
import traceback
class ComponentBase(ABC):
"""
Base class for all Predbat components.
This class defines a standard interface that all components should implement,
providing consistent lifecycle management, health monitoring, and event handling.
Components can inherit from this class to gain:
- Standardized startup/shutdown interface
- Health check and monitoring capabilities
- Event handling framework
- Common logging infrastructure
Attributes:
base: Reference to the main Predbat base object
log: Logging function from the base object
api_started: Flag indicating whether the component has successfully started
api_stop: Flag to signal the component to stop
last_success_timestamp: Timestamp of the last successful operation
"""
def __init__(self, base, **kwargs):
"""
Initialise the component base.
Args:
base: The main Predbat base object providing system-wide services
"""
self.base = base
self.log = base.log
self.api_started = False
self.api_stop = False
self.last_success_timestamp = None
self.local_tz = base.local_tz
self.prefix = base.prefix
self.args = base.args
self.count_errors = 0
self.run_timeout = 60 * 60 # Default run time in seconds, can be overridden by subclasses
self.initialize(**kwargs)
@abstractmethod
def initialize(self, **kwargs):
"""
Additional initialisation for subclasses.
Subclasses can override this method to perform any additional setup
required during initialisation.
"""
pass
def dashboard_item(self, entity, state, attributes, app=None):
"""
Create a dashboard item representation.
"""
return self.base.dashboard_item(entity, state, attributes, app=app)
def get_ha_config(self, name, default):
"""
Retrieve a Home Assistant configuration value from the base system.
"""
return self.base.get_ha_config(name, default)
def set_arg(self, arg, value):
"""
Set a configuration argument in the base system.
"""
return self.base.set_arg(arg, value)
def set_arg_auto(self, arg, value):
"""
Like set_arg(), but for auto-discovery code (typically automatic_config()) binding an
apps.yaml key to an auto-discovered entity/value. Auto-discovery still always wins - this
does not change that - but if the user had already set this key explicitly in apps.yaml,
silently discarding it left no way to notice (issue #4494 follow-up discussion, PR #4500).
Logs a one-time note per key when that happens, then behaves exactly like set_arg().
"""
raw_args = getattr(self.base, "args_from_apps_yaml", None) or {}
raw_value = raw_args.get(arg)
warned = getattr(self.base, "apps_yaml_override_warned", None)
if raw_value is not None and raw_value != value and warned is not None and arg not in warned:
warned.add(arg)
self.log(f"Note: apps.yaml sets '{arg}: {raw_value}' but auto-discovery is using '{value}' instead - auto-discovery always wins currently; remove the apps.yaml entry to avoid this message")
return self.set_arg(arg, value)
def get_arg(self, arg, default=None, indirect=True, combine=False, attribute=None, index=None, domain=None, can_override=True, required_unit=None):
"""
Retrieve a configuration argument from the base system.
"""
return self.base.get_arg(arg, default=default, indirect=indirect, combine=combine, attribute=attribute, index=index, domain=domain, can_override=can_override, required_unit=required_unit)
def update_success_timestamp(self):
"""Update the last success timestamp to the current time"""
self.last_success_timestamp = datetime.now(timezone.utc)
@property
def currency_symbols(self):
"""Get the currency symbols from the base system"""
return self.base.currency_symbols
@property
def arg_errors(self):
"""Get the argument errors from the base system"""
return self.base.arg_errors
@property
def now_utc(self):
"""Get the current time in UTC"""
return self.base.now_utc
@property
def midnight_utc(self):
"""Get today's midnight time in UTC"""
return self.base.midnight_utc
@property
def now_utc_exact(self):
"""Get the current time in the local timezone"""
return datetime.now(self.local_tz)
@property
def minutes_now(self):
"""Get the current time in minutes since midnight"""
return self.base.minutes_now
@property
def plan_interval_minutes(self):
"""Get the plan interval in minutes"""
return self.base.plan_interval_minutes
@property
def num_cars(self):
"""Get the number of cars configured in the system"""
return self.base.num_cars
@property
def config_root(self):
"""Get the configuration root directory"""
return self.base.config_root
@property
def storage(self):
"""Get the storage component for save/load operations"""
if hasattr(self, "base") and hasattr(self.base, "components") and self.base.components:
return self.base.components.get_component("storage")
return None
def get_error_count(self):
"""Get the number of errors that have occurred in this component"""
return self.count_errors
def is_calculating(self):
"""Return whether the component is currently performing a long-running calculation."""
return False
async def start(self):
"""
Start the component's main operation loop.
This method should:
- Initialise any required resources
- Set api_started to True when ready
- Run the main processing loop until api_stop is True
- Clean up resources before exiting
"""
seconds = 0
first = True
next_retry = 0 # When to next attempt self.run() during startup backoff
backoff_interval = 60 # Start with 60 seconds between attempts
max_backoff = 128 * 60 # Maximum 128 minutes between attempts
while not self.api_stop and not self.fatal_error:
try:
# Check if it's time to run
should_run = False
if first:
# During startup, only run when we've reached the next retry time
if seconds >= next_retry:
should_run = True
backoff_interval = min(backoff_interval * 2, max_backoff)
next_retry = seconds + backoff_interval
else:
# After startup, run every 60 seconds
if seconds % 60 == 0:
should_run = True
if should_run:
task = asyncio.ensure_future(self.run(seconds, first))
try:
run_result = await asyncio.wait_for(asyncio.shield(task), timeout=self.run_timeout)
except asyncio.TimeoutError:
stack = task.get_stack()
tb_lines = ["Traceback of timed-out run():"] + [' File "{}", line {}, in {}'.format(frame.f_code.co_filename, frame.f_lineno, frame.f_code.co_name) for frame in stack]
self.log("Error: {}: run() exceeded {}s timeout:\n{}".format(self.__class__.__name__, self.run_timeout, "\n".join(tb_lines)))
task.cancel()
try:
await task
except (asyncio.CancelledError, Exception):
pass
run_result = False
if run_result:
if not self.api_started:
self.api_started = True
self.log(f"{self.__class__.__name__}: Started")
# Clear first flag once started. This must happen even when a
# component sets api_started itself from a background task (e.g.
# the gateway's MQTT loop): otherwise first stays True forever and
# start() keeps re-running the first=True startup path on backoff,
# never reaching the steady-state housekeeping run().
first = False
else:
self.count_errors += 1
self.non_fatal_error_occurred()
self.log("Warn: " + f"{self.__class__.__name__}: run() returned False")
except Exception as e:
self.log(f"Error: {self.__class__.__name__}: {e}")
self.log("Error: " + traceback.format_exc())
self.non_fatal_error_occurred()
self.count_errors += 1
seconds += 5
await asyncio.sleep(5)
self.log(f"{self.__class__.__name__}: Finalizing...")
await self.final()
self.api_started = False
self.log(f"{self.__class__.__name__}: Stopped")
async def final(self):
"""
Final cleanup before stopping.
Subclasses can override this method to perform any necessary cleanup
before the component stops.
"""
pass
async def stop(self):
"""
Stop the component gracefully.
This method:
- Sets api_stop to True to signal the main loop to exit
- Waits briefly to allow ongoing operations to complete
- Releases any held resources as needed
Subclasses may override this method if additional cleanup is required.
"""
self.api_stop = True
self.api_started = False
await asyncio.sleep(0.1) # Allow time for the main loop to exit
def non_fatal_error_occurred(self):
"""
Notify the base system that a non-fatal error has occurred.
This method increments the non_fatal_error_count in the base object,
which can be used for monitoring and logging purposes.
"""
self.base.had_errors = True
def fatal_error_occurred(self):
"""
Notify the base system that a fatal error has occurred.
This method sets the fatal_error flag in the base object,
which can trigger system-wide error handling procedures.
"""
self.base.fatal_error = True
@property
def fatal_error(self):
"""
Check if a fatal error has occurred in the base system.
Returns:
bool: True if a fatal error has occurred, False otherwise
"""
return self.base.fatal_error
def get_history_wrapper(self, entity_id, days=30, required=True, tracked=True):
return self.base.get_history_wrapper(entity_id, days=days, required=required, tracked=tracked)
def get_state_wrapper(self, entity_id=None, default=None, attribute=None, refresh=False, required_unit=None, raw=False):
return self.base.get_state_wrapper(entity_id, default=default, attribute=attribute, refresh=refresh, required_unit=required_unit, raw=raw)
def set_state_wrapper(self, entity_id, state, attributes={}, required_unit=None):
return self.base.set_state_wrapper(entity_id, state, attributes=attributes, required_unit=required_unit)
async def set_state_external(self, entity_id, state, attributes={}):
"""Change one of Predbat's OWN entities as if a user had, updating its CONFIG_ITEMS value.
Distinct from set_state_wrapper, which only writes the entity state: components use this when
auto-discovery has to change a Predbat setting (e.g. teslemetry turning inverter_hybrid off
for an AC-coupled Powerwall), where writing the state alone would move the displayed entity
without changing the value the planner reads.
"""
return await self.base.ha_interface.set_state_external(entity_id, state, attributes=attributes)
def call_notify(self, message):
return self.base.call_notify(message)
def wait_api_started(self, timeout=10 * 60):
"""
Wait for the component to start.
Args:
timeout: Maximum time to wait in seconds (default: 10*60)
Returns:
bool: True if component started successfully, False if timeout
"""
self.log(f"{self.__class__.__name__}: Waiting for API to start")
count = 0
while not self.api_started and count < timeout:
time.sleep(1)
count += 1
if not self.api_started:
self.log(f"Warn: {self.__class__.__name__}: Failed to start")
return False
return True
def is_alive(self):
"""
Check if the component is alive and functioning.
Default implementation checks if the component has started.
Subclasses can override to add additional health checks.
Returns:
bool: True if component is alive and healthy, False otherwise
"""
return self.api_started
def last_updated_time(self):
"""
Get the timestamp of the last successful operation.
Returns:
datetime: Timestamp of last successful operation, or None if never succeeded
"""
return self.last_success_timestamp
async def select_event(self, entity_id, value):
"""
Handle select entity state changes from Home Assistant.
Args:
entity_id: The entity ID that changed
value: The new selected value
Default implementation does nothing. Override in subclasses that handle select events.
"""
pass
async def number_event(self, entity_id, value):
"""
Handle number entity value changes from Home Assistant.
Args:
entity_id: The entity ID that changed
value: The new numeric value
Default implementation does nothing. Override in subclasses that handle number events.
"""
pass
async def switch_event(self, entity_id, service):
"""
Handle switch entity service calls from Home Assistant.
Args:
entity_id: The entity ID being controlled
service: The service being called (e.g., 'turn_on', 'turn_off')
Default implementation does nothing. Override in subclasses that handle switch events.
"""
pass