Skip to content

Commit 01d12d4

Browse files
committed
log,tests
1 parent 8f5d89e commit 01d12d4

32 files changed

Lines changed: 122 additions & 151 deletions

‎src/ha_addon_sunsynk_multi/__main__.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,17 +21,17 @@
2121
)
2222
from .timer_schedule import init_schedules
2323

24-
_LOGGER = logging.getLogger(__name__)
24+
_LOG = logging.getLogger(__name__)
2525

2626

2727
async def main_loop() -> int:
2828
"""Entry point."""
2929
await init_options()
3030
try:
31-
_LOGGER.info("sunsynk library version: %s", VERSION)
31+
_LOG.info("sunsynk library version: %s", VERSION)
3232
init_driver(OPT)
3333
except (TypeError, ValueError) as err:
34-
_LOGGER.critical(str(err))
34+
_LOG.critical(str(err))
3535
return 1
3636
init_schedules(OPT.schedules)
3737
SOPT.init_sensors()
@@ -55,7 +55,7 @@ async def main_loop() -> int:
5555
CALLBACKS.append(ist.cb)
5656
except (ConnectionError, ValueError) as err:
5757
ist.log_bold(str(err))
58-
_LOGGER.critical(
58+
_LOG.critical(
5959
"This Add-On will terminate in 30 seconds, use the Supervisor Watchdog to restart automatically."
6060
)
6161
return 2

‎src/ha_addon_sunsynk_multi/a_inverter.py‎

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
from .sensor_options import DEFS, SOPT
1818
from .timer_callback import Callback
1919

20-
_LOGGER = logging.getLogger(__name__)
20+
_LOG = logging.getLogger(__name__)
2121

2222

2323
@attrs.define(slots=True, kw_only=True)
@@ -76,25 +76,25 @@ async def read_sensors_retry(self, *, sensors: list[Sensor], msg: str = "") -> b
7676
await self.read_sensors(sensors=sensors, msg=msg)
7777
return True
7878
except asyncio.exceptions.CancelledError as err:
79-
_LOGGER.error("Timeout %s", err)
79+
_LOG.error("Timeout %s", err)
8080
except Exception as err:
81-
_LOGGER.error("%s", err)
81+
_LOG.error("%s", err)
8282
await asyncio.sleep(0.1)
8383
if self.read_errors > 2:
8484
break
8585

8686
if len(sensors) == 1:
8787
return False
8888

89-
_LOGGER.warning("Retrying individual sensors: %s", [s.id for s in sensors])
89+
_LOG.warning("Retrying individual sensors: %s", [s.id for s in sensors])
9090
errs = []
9191
for sen in sensors:
9292
await asyncio.sleep(0.02)
9393
if not await self.read_sensors_retry(sensors=[sen], msg=sen.name):
9494
errs.append(sen.name)
9595

9696
if errs:
97-
_LOGGER.critical("Could not read sensors: %s", errs)
97+
_LOG.critical("Could not read sensors: %s", errs)
9898
return False
9999
return True
100100

@@ -111,7 +111,7 @@ async def publish_sensors(self, *, states: dict[ASensor, ValType]) -> None:
111111

112112
async def connect(self) -> None:
113113
"""Connect."""
114-
_LOGGER.info("Connecting to %s", self.inv.port)
114+
_LOG.info("Connecting to %s", self.inv.port)
115115
try:
116116
await self.inv.connect()
117117
except ConnectionError as exc:
@@ -120,7 +120,7 @@ async def connect(self) -> None:
120120
) from exc
121121

122122
sensors = list(SOPT.startup)
123-
_LOGGER.info("Reading startup sensors %s", ", ".join(s.name for s in sensors))
123+
_LOG.info("Reading startup sensors %s", ", ".join(s.name for s in sensors))
124124

125125
if not await self.read_sensors_retry(sensors=sensors):
126126
raise ConnectionError(
@@ -135,17 +135,17 @@ async def connect(self) -> None:
135135
)
136136
self.log_bold(f"Inverter serial number '****{actual_ser[-4:]}'")
137137

138-
_LOGGER.info(
138+
_LOG.info(
139139
"Device type: %s, using the %s sensor definitions",
140140
self.inv.state[DEFS.device_type],
141141
OPT.sensor_definitions,
142142
)
143143

144-
_LOGGER.info("Protocol version: %s", self.inv.state[DEFS.protocol])
144+
_LOG.info("Protocol version: %s", self.inv.state[DEFS.protocol])
145145

146146
# Initial read for all sensors
147147
sensors = list(SOPT)
148-
_LOGGER.info("Reading all sensors %s", ", ".join(s.name for s in sensors))
148+
_LOG.info("Reading all sensors %s", ", ".join(s.name for s in sensors))
149149
await self.read_sensors(sensors=sensors)
150150

151151
@property
@@ -158,9 +158,9 @@ def rated_power(self) -> float:
158158

159159
def log_bold(self, msg: str) -> None:
160160
"""Log a message."""
161-
_LOGGER.info("#" * 60)
162-
_LOGGER.info(f"{msg:^60}".rstrip())
163-
_LOGGER.info("#" * 60)
161+
_LOG.info("#" * 60)
162+
_LOG.info(f"{msg:^60}".rstrip())
163+
_LOG.info("#" * 60)
164164

165165
def hass_create_discovery_info(self) -> None:
166166
"""Create discovery info for the inverter."""
@@ -191,7 +191,7 @@ def hass_create_discovery_info(self) -> None:
191191
s.entity = s.create_entity(self)
192192
self.mqtt_dev.components[s.opt.sensor.id] = s.entity
193193
except Exception as err:
194-
_LOGGER.error("Could not create MQTT entity for %s: %s", s, err)
194+
_LOG.error("Could not create MQTT entity for %s: %s", s, err)
195195

196196
if hasattr(s.opt.sensor, "rated_power"):
197197
s.opt.sensor.rated_power = int(self.rated_power) # type:ignore[]

‎src/ha_addon_sunsynk_multi/a_sensor.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@
4444

4545

4646
SS_TOPIC = "SS"
47-
_LOGGER = logging.getLogger(__name__)
47+
_LOG = logging.getLogger(__name__)
4848
"""An array of the Sunsynk driver instances."""
4949
MQTT = MQTTClient(devs=[], origin_name="Sunsynk Add-on")
5050
"""The MQTTClient instance."""
@@ -79,10 +79,10 @@ def value(self) -> ValType:
7979
async def publish(self, val: ValType) -> None:
8080
"""Set the value through MQTT."""
8181
if self.entity is None:
82-
_LOGGER.error("no entity %s", self.name)
82+
_LOG.error("no entity %s", self.name)
8383
return
8484
if val is None:
85-
_LOGGER.debug("Cannot publish %s: value is None", self.name)
85+
_LOG.debug("Cannot publish %s: value is None", self.name)
8686
return
8787
if self._last == val and self.retain:
8888
return
@@ -156,7 +156,7 @@ def on_change_factory() -> TopicCallback:
156156

157157
async def on_change(val: float | str | bool) -> None:
158158
"""On change callback."""
159-
_LOGGER.info("Queue update %s=%s", sensor.id, val)
159+
_LOG.info("Queue update %s=%s", sensor.id, val)
160160
ist.write_queue.update({sensor: val})
161161
await self.publish(val)
162162

‎src/ha_addon_sunsynk_multi/driver.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
from .options import Options
1212
from .sensor_options import SOPT
1313

14-
_LOGGER = logging.getLogger(":")
14+
_LOG = logging.getLogger(":")
1515

1616

1717
HASS_DISCOVERY_INFO_UPDATE_QUEUE: set[Sensor] = set()
@@ -37,7 +37,7 @@ def sensor_on_update(sen: Sensor, _new: ValType, _old: ValType) -> None:
3737
"""React to sensor updates."""
3838
if sen not in SOPT or not SOPT[sen].affects:
3939
return
40-
_LOGGER.debug(
40+
_LOG.debug(
4141
"%s changed: Enqueue discovery info updates for %s",
4242
sen.name,
4343
", ".join(s.id for s in SOPT[sen].affects),
@@ -81,7 +81,7 @@ def init_driver(opt: Options) -> None:
8181
)
8282
if hasattr(suns, "dongle_serial_number"):
8383
suns.dongle_serial_number = inv.dongle_serial_number # type: ignore[]
84-
_LOGGER.debug("Driver: %s - inv:%s", suns, inv)
84+
_LOG.debug("Driver: %s - inv:%s", suns, inv)
8585
suns.state.onchange = sensor_on_update
8686

8787
STATE.append(AInverter(inv=suns, ss={}, opt=inv, index=idx))

‎src/ha_addon_sunsynk_multi/errors.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from traceback import format_exception
66

77
ERRLIST: dict[str, int] = defaultdict(int)
8-
_LOGGER = logging.getLogger(__name__)
8+
_LOG = logging.getLogger(__name__)
99

1010

1111
def log_error(msg: str, exc: Exception | None = None) -> None:
@@ -14,9 +14,9 @@ def log_error(msg: str, exc: Exception | None = None) -> None:
1414
if ERRLIST[msg] > 1:
1515
return
1616
if exc:
17-
_LOGGER.error("%s\n%s", msg, "\n".join(format_exception(exc)))
17+
_LOG.error("%s\n%s", msg, "\n".join(format_exception(exc)))
1818
else:
19-
_LOGGER.error(msg)
19+
_LOG.error(msg)
2020

2121

2222
def print_errors(_: int) -> None:
@@ -26,7 +26,7 @@ def print_errors(_: int) -> None:
2626
errs = [(c, m) for m, c in ERRLIST.items() if c > 1]
2727
errs.sort(reverse=True)
2828
for count, msg in errs:
29-
_LOGGER.error("(%s in 5 min) %s", count - 1, msg)
29+
_LOG.error("(%s in 5 min) %s", count - 1, msg)
3030

3131
for key in ERRLIST:
3232
ERRLIST[key] = 1

‎src/ha_addon_sunsynk_multi/helpers.py‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
from sunsynk.utils import import_module
1010

11-
_LOGGER = logging.getLogger(__name__)
11+
_LOG = logging.getLogger(__name__)
1212

1313

1414
def get_root(create: bool = False) -> Path:
@@ -30,20 +30,20 @@ def import_mysensors() -> dict[str, Any] | None:
3030
pth = root / f"{modn}.py"
3131
if not pth.exists():
3232
return None
33-
_LOGGER.info("Importing %s...", pth)
33+
_LOG.info("Importing %s...", pth)
3434
try:
3535
mod = import_module("mysensors", str(root))
3636
except Exception as err:
3737
traceback.print_exc()
38-
_LOGGER.error("Error importing %s: %s", pth, err)
38+
_LOG.error("Error importing %s: %s", pth, err)
3939
return None
4040
sensors = getattr(mod, "SENSORS", None)
4141
if not sensors:
42-
_LOGGER.error("No SENSORS variable found in mysensors.py")
42+
_LOG.error("No SENSORS variable found in mysensors.py")
4343
return None
4444
res: dict[str, Any] = getattr(sensors, "all", {})
4545
if res:
46-
_LOGGER.info(" custom sensors: %s", ", ".join(res))
46+
_LOG.info(" custom sensors: %s", ", ".join(res))
4747
else:
48-
_LOGGER.warning(" no custom sensors")
48+
_LOG.warning(" no custom sensors")
4949
return res

‎src/ha_addon_sunsynk_multi/options.py‎

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,13 @@
11
"""Addon options."""
22

33
import logging
4-
import typing as t
54

65
import attrs
76
from mqtt_entity.options import MQTTOptions
87

98
from .timer_schedule import Schedule
109

11-
_LOGGER = logging.getLogger(__name__)
12-
13-
14-
T = t.TypeVar("T", str, int, list)
10+
_LOG = logging.getLogger(__name__)
1511

1612

1713
@attrs.define()
@@ -29,20 +25,18 @@ def __attrs_post_init__(self) -> None:
2925
self.ha_prefix = self.ha_prefix.lower().strip()
3026
if self.dongle_serial_number:
3127
if self.port:
32-
_LOGGER.warning(
33-
"%s: No port expected when you specify a serial number."
34-
)
28+
_LOG.warning("%s: No port expected when you specify a serial number.")
3529
return
3630
if self.port == "":
37-
_LOGGER.warning(
31+
_LOG.warning(
3832
"%s: Using port from debug_device: %s", self.serial_nr, OPT.debug_device
3933
)
4034
self.port = OPT.debug_device
4135
ddev = self.port == ""
4236
if ddev:
43-
_LOGGER.warning("Empty port, will use the debug device")
37+
_LOG.warning("Empty port, will use the debug device")
4438
if ddev or self.port.lower().startswith(("serial:", "/dev")):
45-
_LOGGER.warning("Use mbusd instead of connecting directly to a serial port")
39+
_LOG.warning("Use mbusd instead of connecting directly to a serial port")
4640

4741

4842
@attrs.define()

‎src/ha_addon_sunsynk_multi/sensor_callback.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
from .sensor_options import SOPT
1717
from .timer_callback import AsyncCallback
1818

19-
_LOGGER = logging.getLogger(__name__)
19+
_LOG = logging.getLogger(__name__)
2020

2121

2222
@attrs.define(slots=True)
@@ -76,7 +76,7 @@ def _print_table(
7676
tab.add_row([key, wrapped[0]])
7777
for more in wrapped[1:]:
7878
tab.add_row(["", more])
79-
_LOGGER.info("%s\n%s", title, tab.get_string())
79+
_LOG.info("%s\n%s", title, tab.get_string())
8080

8181

8282
def build_callback_schedule(ist: AInverter) -> AsyncCallback: # noqa: PLR0915
@@ -109,7 +109,7 @@ async def callback_sensor(now: int) -> None: # noqa: PLR0915 PLR0912
109109
srun.next_run = now + sec
110110
# perform the read
111111
if sensors_to_read:
112-
_LOGGER.debug("Read: %s", len(sensors_to_read))
112+
_LOG.debug("Read: %s", len(sensors_to_read))
113113
await ist.read_sensors(
114114
sensors=sensors_to_read,
115115
msg="poll_need_to_read",
@@ -163,7 +163,7 @@ async def callback_sensor(now: int) -> None: # noqa: PLR0915 PLR0912
163163
try:
164164
pub[asen] = ist.inv.state.history_average(sensor)
165165
except ValueError:
166-
_LOGGER.warning("No history for %s", sensor)
166+
_LOG.warning("No history for %s", sensor)
167167
srun.next_run = now + sec
168168

169169
if pub:

‎src/ha_addon_sunsynk_multi/sensor_options.py‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
from .options import OPT
1616
from .timer_schedule import SCHEDULES, Schedule, get_schedule
1717

18-
_LOGGER = logging.getLogger(__name__)
18+
_LOG = logging.getLogger(__name__)
1919

2020
DEFS = SensorDefinitions()
2121
"""Sensor definitions (1ph / 3ph)."""
@@ -100,7 +100,7 @@ def init_sensors(self) -> None:
100100

101101
# Display hidden sensors
102102
if hidden := [s.sensor.name for s in self.values() if not s.visible]:
103-
_LOGGER.info(
103+
_LOG.info(
104104
"Added hidden sensors as other sensors depend on it: %s",
105105
", ".join(hidden),
106106
)
@@ -125,7 +125,7 @@ def import_definitions() -> None:
125125
DEFS.all.update(mysensors)
126126
SENSOR_GROUPS["mysensors"] = list(mysensors)
127127
except ImportError:
128-
_LOGGER.error("Unable to import import mysensors.py")
128+
_LOG.error("Unable to import import mysensors.py")
129129
traceback.print_exc()
130130

131131

@@ -331,7 +331,7 @@ def get_sensors(
331331

332332
for sensor_def in names:
333333
if ":" in sensor_def:
334-
_LOGGER.error("Modifiers was replaced by schedules: %s", sensor_def)
334+
_LOG.error("Modifiers was replaced by schedules: %s", sensor_def)
335335
continue
336336

337337
name = slug(sensor_def)
@@ -344,21 +344,21 @@ def get_sensors(
344344
# Warn on deprecated
345345
if name in DEFS.deprecated:
346346
if warn:
347-
_LOGGER.error(
347+
_LOG.error(
348348
"Your config includes deprecated sensors. Replace %s with %s",
349349
name,
350350
DEFS.deprecated[name],
351351
)
352352
continue
353353

354354
if name in [t.name for t in target] and warn:
355-
_LOGGER.warning("Sensor %s only allowed once", name)
355+
_LOG.warning("Sensor %s only allowed once", name)
356356
continue
357357

358358
sen = DEFS.all.get(name)
359359
if not isinstance(sen, Sensor):
360360
if warn:
361-
_LOGGER.error("Unknown sensor specified: %s", name)
361+
_LOG.error("Unknown sensor specified: %s", name)
362362
continue
363363

364364
yield sen

0 commit comments

Comments
 (0)