-
Notifications
You must be signed in to change notification settings - Fork 108
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Bugfix/revert and add more logging for issues #412
Open
maslyankov
wants to merge
4
commits into
kellerza:main
Choose a base branch
from
maslyankov:bugfix/revert-and-attempt-spikes-fix
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
|
@@ -3,18 +3,29 @@ | |||||
import asyncio | ||||||
import logging | ||||||
import time | ||||||
from typing import Iterable, Sequence, TypedDict | ||||||
from typing import Iterable, Sequence, TypedDict, Union | ||||||
|
||||||
import attrs | ||||||
|
||||||
from sunsynk.helpers import hex_str, patch_bitmask | ||||||
from sunsynk.rwsensors import RWSensor | ||||||
from sunsynk.sensors import Sensor, ValType | ||||||
from sunsynk.sensors import ( | ||||||
BinarySensor, | ||||||
EnumSensor, | ||||||
InverterStateSensor, | ||||||
SDStatusSensor, | ||||||
Sensor, | ||||||
ValType, | ||||||
) | ||||||
from sunsynk.state import InverterState, group_sensors, register_map | ||||||
|
||||||
_LOGGER = logging.getLogger(__name__) | ||||||
|
||||||
|
||||||
class RegisterReadError(Exception): | ||||||
"""Exception raised when there are errors reading registers.""" | ||||||
|
||||||
|
||||||
@attrs.define | ||||||
class Sunsynk: | ||||||
"""Sunsync Modbus class.""" | ||||||
|
@@ -75,12 +86,19 @@ | |||||
|
||||||
async def read_sensors(self, sensors: Iterable[Sensor]) -> None: | ||||||
"""Read a list of sensors - Sunsynk supports function code 0x03.""" | ||||||
# pylint: disable=too-many-locals,too-many-branches | ||||||
# Check if state is ok & tracking the sensors being read | ||||||
assert self.state is not None | ||||||
for sen in sensors: | ||||||
if sen not in self.state.values: | ||||||
_LOGGER.warning("sensor %s not being tracked", sen.id) | ||||||
|
||||||
# Create a map of register addresses to their corresponding sensors | ||||||
reg_to_sensor: dict[int, Union[Sensor, None]] = {} | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
for sensor in sensors: | ||||||
for addr in sensor.address: | ||||||
reg_to_sensor[addr] = sensor | ||||||
|
||||||
new_regs: dict[int, int] = {} | ||||||
errs: list[str] = [] | ||||||
groups = group_sensors( | ||||||
|
@@ -92,19 +110,39 @@ | |||||
glen = grp[-1] - grp[0] + 1 | ||||||
try: | ||||||
perf = time.perf_counter() | ||||||
_LOGGER.debug("Starting read of %s registers from %s", glen, grp[0]) | ||||||
|
||||||
r_r = await asyncio.wait_for( | ||||||
self.read_holding_registers(grp[0], glen), timeout=self.timeout + 1 | ||||||
) | ||||||
perf = time.perf_counter() - perf | ||||||
|
||||||
# Log performance metrics | ||||||
_LOGGER.debug( | ||||||
"Time taken to fetch %s registers starting at %s : %ss", | ||||||
glen, | ||||||
grp[0], | ||||||
f"{perf:.2f}", | ||||||
) | ||||||
|
||||||
# Check for potential communication issues based on timing | ||||||
if perf > self.timeout * 0.8: # If taking more than 80% of timeout | ||||||
_LOGGER.warning( | ||||||
"Slow register read detected: %ss for %s registers from %s", | ||||||
f"{perf:.2f}", | ||||||
glen, | ||||||
grp[0], | ||||||
) | ||||||
|
||||||
except asyncio.TimeoutError: | ||||||
errs.append(f"timeout reading {glen} registers from {grp[0]}") | ||||||
self.timeouts += 1 | ||||||
# Log consecutive timeouts | ||||||
if self.timeouts > 3: | ||||||
_LOGGER.error( | ||||||
"Multiple consecutive timeouts detected: %s. Consider checking connection.", | ||||||
self.timeouts, | ||||||
) | ||||||
continue | ||||||
except Exception as err: # pylint: disable=broad-except | ||||||
errs.append( | ||||||
|
@@ -117,21 +155,61 @@ | |||||
|
||||||
if len(r_r) != glen: | ||||||
_LOGGER.warning( | ||||||
"Did not complete read, only read %s/%s", len(r_r), glen | ||||||
"Did not complete read, only read %s/%s registers. This may cause value spikes.", | ||||||
len(r_r), | ||||||
glen, | ||||||
) | ||||||
|
||||||
# Log register values for debugging | ||||||
_LOGGER.debug( | ||||||
"Request registers: %s glen=%d. Response %s len=%d. regs=%s", | ||||||
grp, | ||||||
glen, | ||||||
r_r, | ||||||
[hex(r) for r in r_r], # Convert to hex for better debugging | ||||||
len(r_r), | ||||||
regs, | ||||||
{ | ||||||
k: hex(v) for k, v in regs.items() | ||||||
}, # Convert to hex for better debugging | ||||||
) | ||||||
|
||||||
self.state.update(new_regs) | ||||||
# Check for potentially invalid register values | ||||||
for reg_addr, reg_val in regs.items(): | ||||||
maybe_sensor: Union[Sensor, None] = reg_to_sensor.get(reg_addr) | ||||||
if maybe_sensor is None: | ||||||
continue | ||||||
|
||||||
current_sensor: Sensor = maybe_sensor | ||||||
if reg_val == 0xFFFF: | ||||||
_LOGGER.warning( | ||||||
"Potentially invalid register value detected: addr=%s value=0xFFFF sensor=%s", | ||||||
reg_addr, | ||||||
current_sensor.name, | ||||||
) | ||||||
# Only check zeros for status/enum type sensors | ||||||
elif reg_val == 0 and any( | ||||||
isinstance(current_sensor, t) | ||||||
for t in ( | ||||||
BinarySensor, | ||||||
EnumSensor, | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can’t 0 be a vlid state for Binary/Enum? |
||||||
InverterStateSensor, | ||||||
SDStatusSensor, | ||||||
) | ||||||
): | ||||||
_LOGGER.debug( | ||||||
"Zero value detected in status sensor: addr=%s sensor=%s", | ||||||
reg_addr, | ||||||
current_sensor.name, | ||||||
) | ||||||
|
||||||
if errs: | ||||||
raise IOError("; ".join(errs)) | ||||||
_LOGGER.warning("Errors during sensor read: %s", ", ".join(errs)) | ||||||
raise RegisterReadError(", ".join(errs)) | ||||||
|
||||||
# Reset timeout counter if successful | ||||||
if not errs: | ||||||
self.timeouts = 0 | ||||||
|
||||||
self.state.update(new_regs) | ||||||
|
||||||
|
||||||
class SunsynkInitParameters(TypedDict): | ||||||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can we remove this outer general exception handler?
you already log 1&2 register exceptions above