Repository navigation
Add classic-auth AC charge/discharge time writes for Growatt Mix - #176603
albertteoh wants to merge 26 commits into
Conversation
There was a problem hiding this comment.
Hi @albertteoh
It seems you haven't yet signed a CLA. Please do so here.
Once you do that we will be able to review and accept this pull request.
Thanks!
|
Please take a look at the requested changes, and use the Ready for review button when you are done, thanks 👍 |
|
Hey there @johanzander, mind taking a look at this pull request as it has been labeled with an integration ( Code owner commandsReply with
|
There was a problem hiding this comment.
Pull request overview
Adds classic-auth Growatt Mix AC charge/discharge schedule writes alongside existing V1 SPH support.
Changes:
- Adds classic Mix payload encoding and API calls.
- Expands service device matching and classic defaults.
- Adds coordinator and service tests.
Reviewed changes
Copilot reviewed 5 out of 5 changed files in this pull request and generated 10 comments.
Show a summary per file
| File | Description |
|---|---|
coordinator.py |
Implements classic schedule writes. |
services.py |
Routes Mix devices and handles defaults. |
conftest.py |
Mocks classic write responses. |
test_coordinator.py |
Tests encoding and errors. |
test_services.py |
Tests classic service behavior. |
1e22130 to
6787520
Compare
|
Pushed a follow-up commit addressing the Copilot review feedback:
Replied inline on each thread with details. One item I left open: the suggestion to move the All tests, ruff, mypy, and pylint pass locally (164 tests in |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 6 out of 6 changed files in this pull request and generated 5 comments.
Comments suppressed due to low confidence (1)
homeassistant/components/growatt_server/coordinator.py:624
- Move the classic Mix protocol implementation into
growattServerand call a library helper here. This positional endpoint encoding is device protocol logic and duplicates the library's SPH implementation; Home Assistant integrations should remain thin wrappers rather than carry temporary library workarounds.
return "00:00"
else:
return f"{hour:02d}:{minute:02d}"
The classic write path builds a fixed-length positional param list from the caller's periods list with no length check, so a caller supplying other than 3 periods would silently misalign every param after it. Raise ValueError up front instead, matching the V1 SPH library's own validation for the same constraint. Also corrected the discharge path's comment, which claimed param1-18 (that's the charge path's count; the discharge payload is 2 header params + 15 period params = param1-17). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
get_mix_inverter_settings() failure responses (e.g. {"success": false})
have no obj.mixBean, which previously fell through to {} and was read
as all-zero/disabled settings. Combined with the write handlers'
read-merge-write pattern, a failed settings fetch could silently merge
in 0/100/disabled defaults and overwrite every field the caller didn't
specify, instead of aborting the write.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The V1 branches of update_ac_charge_times/update_ac_discharge_times wrapped GrowattV1ApiError with str(err), which drops the server-provided error_code and error_msg. Switch to the api_error_with_code translation key so the actual rejection reason and code reach the user instead of a generic message. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
mix_settings_read_failed and mix_settings_empty previously gave no
indication of the actual cause (network error, bad session, rate
limit, etc.), unlike login_failed which already includes {message}.
Every AC charge/discharge write does a read-merge-write internally, so
this read failure surfaces on writes too — without the detail it was
undiagnosable from the HA UI or automation logs.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Today's outage traced back to the Pi silently running a snapshot from 40 commits behind HEAD (predating classic-auth Mix support entirely) after a partial/failed deploy — with no way to tell from inside HA that it wasn't running the current code, only SSH log archaeology. deploy_growatt_server.sh now stages the component in a temp dir (never touching the tracked source), generates _build_info.py there with the current commit (suffixed -dirty if the working tree has uncommitted growatt_server changes) and a deploy timestamp, and wipes the remote custom_components/growatt_server directory before extracting — so a half-finished deploy can't leave stale files mixed with new ones. __init__.py logs the build commit/timestamp once at startup, and diagnostics.py includes it in the downloadable diagnostics dump, so "what's actually running" is answerable from HA itself. _build_info is an optional guarded import — absent in the source tree and tests, where diagnostics reports build: None (see updated snapshots). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
test_coordinator.py called coordinator.update_ac_charge_times() and friends directly, bypassing config entry setup and the write/read services a real caller goes through. Move that coverage into test_services.py as hass.services.async_call() tests (matching the integration's existing service-test convention), keeping only the two period-count ValueError guards in test_coordinator.py since services.py always builds exactly 3 periods and can never reach them. Also fixes the "0:0" classic-settings fallback to "00:00" to match the HH:MM format _format_time produces everywhere else. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01T8mbu4rqLHf3e7iWFmi4qn
dev's device_registry.async_get_device() is now deprecated in favor of async_get_device_by_identifier(); the rest of this file was migrated already, but the tests added in this branch predated that migration and still called the old API, which raises in tests. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01T8mbu4rqLHf3e7iWFmi4qn
diagnostics.py is only ever imported after __init__.py, which already sets _build_info (to the generated module or None) as a package attribute. from . import _build_info here can therefore never raise ImportError, so the except branch was dead code that also tripped codecov's 100%-patch-coverage requirement for diagnostics.py. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01T8mbu4rqLHf3e7iWFmi4qn
Reverts 79923a9. The _build_info module is generated by a local, untracked deploy script and gitignored, so it never exists in an official Core install — diagnostics would only ever report build: null there. That makes it local deploy tooling rather than part of this integration, and it does not belong in Core. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01T8mbu4rqLHf3e7iWFmi4qn
The test reached into services.py for a private helper and fabricated config entries and runtime data with SimpleNamespace, coupling it to internals. The pairings it checked (classic+sph, v1+mix) cannot arise from real device discovery, and the filtering that can be reached is already covered through the service layer by test_service_with_non_min_growatt_device and test_sph_service_with_non_sph_growatt_device. services.py stays at 100% coverage without it. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01T8mbu4rqLHf3e7iWFmi4qn
mix_settings_read_failed and mix_settings_empty had their {error} and
{response} placeholders reinstated by 25659f3 after review feedback
had them removed, and the two classic write-rejection paths interpolated
str(result), putting a raw Python dict repr in a user-facing string.
Untranslated API text inside a translated message cannot be localised.
All four now use static messages, with the underlying detail logged at
debug level instead. The write rejection gets its own mix_write_rejected
key rather than reusing api_error, which exists to carry an error string.
Tests assert the translation key and that no placeholders are attached,
so a placeholder cannot be reintroduced unnoticed.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01T8mbu4rqLHf3e7iWFmi4qn
_fetch_classic_mix_settings only rejected an entirely empty mixBean. A non-empty payload missing one field still passed, and the read then supplied a 0/100/disabled default for it. Because every write is a read-merge-write, that default was written straight back: a call setting only period_1_start could silently write charge power 0 and disable AC charging. Callers now declare the keys they need, a payload missing any of them is rejected, and the reads index the settings directly instead of defaulting. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01T8mbu4rqLHf3e7iWFmi4qn
get_mix_inverter_settings returns response.json() without validating its shape, so a failure payload could make response, obj or mixBean a string or list. Calling .get() on one raised AttributeError out of the service instead of the translated mix_settings_empty error. Each level is now checked before it is indexed. The previous falsiness check happened to cover empty lists, so the regression test uses truthy non-objects, which are the shapes that actually raised. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01T8mbu4rqLHf3e7iWFmi4qn
Three places still let a malformed API response through as either synthetic data or an untranslated exception: - _format_time maps an unparsable time to 00:00, so a read-merge-write would write midnight over a period the caller never mentioned. The classic AC path now parses strictly and range-checks, and the period switch is parsed the same way rather than calling int() bare. - Both classic write paths called result.get() on the raw response, so a JSON string, list or null raised AttributeError instead of mix_write_rejected. Same fault as the read envelope, missed when that one was fixed. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01T8mbu4rqLHf3e7iWFmi4qn
…errors Malformed charge/discharge power, stop SOC and mains-enable values from the classic Mix settings read raised a raw ValueError; they now go through _parse_ac_int like the period fields and raise mix_settings_invalid. The no-devices and device-not-configured errors listed only device types, so a configured SPH on classic auth was told no SPH device existed. They now list the supported device/authentication pairs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Keep V1 SPH write errors on the existing api_error key; the api_error_with_code change and the V1-only period-encoding test are out of scope for this PR. - Drop the len(periods) != 3 guards (services.py always builds three periods) and the coordinator tests that existed only to reach them. - Share the classic period encoding in _encode_periods() and index period["enabled"] directly. - Give the AC schedule actions their own translated "no devices" and "device not configured" messages instead of building English labels in code; MIN actions keep the existing messages. - Move NULL_SENTINELS into coordinator.py and drop the cached_periods alias. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An unauthenticated getMixSetParams returns HTTP 200 with an empty body on both openapi.growatt.com and openapi-au.growatt.com, so response.json() raises JSONDecodeError and the read fails with mix_settings_read_failed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Classic Mix charge/discharge writes interpolated str(err) into the translated api_error message, which could expose a URL containing the inverter serial. Raise a static mix_write_failed key and log the detail at debug instead. Also collapse _parse_ac_time's docstring to one line.
| # The underlying API requires all 3 periods in every write call. Read | ||
| # current settings first so any period not supplied by the caller is | ||
| # filled from the cache instead of overwritten with zeros. | ||
| current = await coordinator.read_ac_charge_times() |
| async def _fetch_classic_mix_settings(self, required_keys: list[str]) -> dict: | ||
| """Fetch classic Mix settings (getMixSetParams) for the AC read services.""" |
|
👋 Hi! Thanks for contributing to Home Assistant. This is your PR dashboard which flags anything you need to address before your PR can be reviewed. Once everything is green, you can press the 'Ready for review' button at the bottom of the page to notify reviewers to take a look. More information about this dashboardThis dashboard automatically updates on every change to this PR and reevaluates the rules as you go. Until everything has been addressed, the bot will keep the PR in draft. Skip a check that doesn't applyIf you think a check doesn't apply to your PR (or the rule is bugged), comment Bot commandsReply with
Checks✨ Everything's in order! 6 checks passed (5 skipped)
|
|
Hey @erwindouna @joostlek, I've fixed the merge conflict with dev and replied to all your threads. Do your change requests still stand, or is this good to go? Thanks! |
Quality scale review✅ No issues found at 72374b2. Checked
|


Breaking change
Proposed change
Adds support for reading and writing AC charge and discharge time periods on classic (username/password) auth Growatt Mix devices, alongside the existing V1 (token) SPH read/write path.
This is a workaround for #166817: with token-based auth,
growatt_server.read_ac_charge_timesworks butgrowatt_server.write_ac_charge_timesfails withGrowatt API error: Error during writing AC charge time periods. Inspecting the ShinePhone app's traffic with mitmproxy showed those writes are performed over classic username/password auth, so this PR enables the classic auth path for Mix devices until the token-based writes are fixed.coordinator: encodes charge/discharge periods as the positionalparam1-18payload forupdate_mix_inverter_setting(classic writes), surfacing library errors, transport failures, and non-success responses asHomeAssistantError.coordinator: classic reads fetchget_mix_inverter_settings(getMixSetParams) on demand and parse the sameforcedChargeTime*/forcedDischargeTime*/chargePowerCommand/acChargeEnable/etc. fields the V1 SPH path already uses, plus the classic-specificwchargeSOCLowLimit2/wdisChargeSOCLowLimit2stop-SOC fields (confirmed against a real device — the classic API exposes two SOC-limit variants per direction;2is the one the app displays for the AC schedule).services: write handlers now match{("sph", "v1"), ("mix", "classic")}explicitly (rather than a flat device-type set) so a write can never be routed to the wrong device-specific endpoint, and always read-merge-write against real cached/fetched state for both auth types — a partial write no longer resets unspecified fields to fixed defaults.services: read handlers match the same explicit pairs and now return real classic Mix settings instead of raisingtoken_auth_required.services/strings: the AC schedule actions get their own translatedno_ac_schedule_devices_configuredandac_schedule_device_not_configurederrors, which name the supported device and authentication combinations in the translated text. The MIN actions keep the existingno_devices_configured/device_not_configuredmessages. This changes the text SPH (token) users see when a device isn't configured: the old "No SPH devices…" message becomes the new AC schedule one. The write/read service descriptions mention Mix devices.tests: service-layer tests intest_services.pythat drive the classic read/write paths throughhass.services.async_call, covering positional param encoding, read-merge-write preservation of omitted fields, transport failures, and malformed, incomplete or unparsable responses.Type of change
Additional information
Tested on real hardware. The classic (username/password) auth path was verified end-to-end against a physical Growatt Mix inverter: this branch was deployed as a custom component on a Raspberry Pi (Home Assistant OS) install, and
write_ac_charge_times/write_ac_discharge_timeswere confirmed to push AC charge/discharge schedules (power %, stop-SOC, and time periods) to the device via the classicmixSetendpoint. Existing V1 (token-auth) SPH behaviour is unchanged and remains covered by unit tests.Checklist
ruff format homeassistant tests)If user exposed functionality or configuration variables are added/changed:
If the code communicates with devices, web services, or third-party tools:
Updated and included derived files by running:
python3 -m script.hassfest.requirements_all.txt.Updated by running
python3 -m script.gen_requirements_all.To help with the load of incoming pull requests: