Skip to content

Add classic-auth AC charge/discharge time writes for Growatt Mix - #176603

Open
albertteoh wants to merge 26 commits into
home-assistant:devfrom
albertteoh:growatt-classic-auth-writes
Open

albertteoh wants to merge 26 commits into
home-assistant:devfrom
albertteoh:growatt-classic-auth-writes

Conversation

@albertteoh

@albertteoh albertteoh commented Jul 16, 2026 •

Copy link
Copy Markdown

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_times works but growatt_server.write_ac_charge_times fails with Growatt 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 positional param1-18 payload for update_mix_inverter_setting (classic writes), surfacing library errors, transport failures, and non-success responses as HomeAssistantError.
  • coordinator: classic reads fetch get_mix_inverter_settings (getMixSetParams) on demand and parse the same forcedChargeTime*/forcedDischargeTime*/chargePowerCommand/acChargeEnable/etc. fields the V1 SPH path already uses, plus the classic-specific wchargeSOCLowLimit2/wdisChargeSOCLowLimit2 stop-SOC fields (confirmed against a real device — the classic API exposes two SOC-limit variants per direction; 2 is 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 raising token_auth_required.
  • services/strings: the AC schedule actions get their own translated no_ac_schedule_devices_configured and ac_schedule_device_not_configured errors, which name the supported device and authentication combinations in the translated text. The MIN actions keep the existing no_devices_configured/device_not_configured messages. 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 in test_services.py that drive the classic read/write paths through hass.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

  • Dependency upgrade
  • Bugfix (non-breaking change which fixes an issue)
  • New integration (thank you!)
  • New feature (which adds functionality to an existing integration)
  • Deprecation (breaking change to happen in the future)
  • Breaking change (fix/feature causing existing functionality to break)
  • Code quality improvements to existing code or addition of tests

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_times were confirmed to push AC charge/discharge schedules (power %, stop-SOC, and time periods) to the device via the classic mixSet endpoint. Existing V1 (token-auth) SPH behaviour is unchanged and remains covered by unit tests.

Checklist

  • I understand the code I am submitting and can explain how it works.
  • The code change is tested and works locally.
  • Local tests pass. Your PR cannot be merged unless tests pass
  • There is no commented out code in this PR.
  • I have followed the development checklist
  • I have followed the perfect PR recommendations
  • The code has been formatted using Ruff (ruff format homeassistant tests)
  • Tests have been added to verify that the new code works.
  • Any generated code has been carefully reviewed for correctness and compliance with project standards.

If user exposed functionality or configuration variables are added/changed:

If the code communicates with devices, web services, or third-party tools:

  • The manifest file has all fields filled out correctly.
    Updated and included derived files by running: python3 -m script.hassfest.
  • New or updated dependencies have been added to requirements_all.txt.
    Updated by running python3 -m script.gen_requirements_all.
  • For the updated dependencies a diff between library versions and ideally a link to the changelog/release notes is added to the PR description.

To help with the load of incoming pull requests:

Copilot AI balanced review requested due to automatic review settings July 16, 2026 10:08

@home-assistant home-assistant Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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!

@home-assistant
home-assistant Bot marked this pull request as draft July 16, 2026 10:08
@home-assistant

Copy link
Copy Markdown
Contributor

Please take a look at the requested changes, and use the Ready for review button when you are done, thanks 👍

Learn more about our pull request process.

@home-assistant

home-assistant Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Hey there @johanzander, mind taking a look at this pull request as it has been labeled with an integration (growatt_server) you are listed as a code owner for? Thanks!

Code owner commands

Reply with @home-assistant <command>:

  • update — Re-runs the bot's checks on the issue or pull request.
  • ignore — Waives a dashboard check: ignore "<check name>" "<reason>". (author) — e.g. @home-assistant ignore "Merge conflicts" "Broken rule, no merge conflicts present"
  • unignore — Restores a waived dashboard check: unignore "<check name>". (author) — e.g. @home-assistant unignore "Merge conflicts"
  • unassign — Removes the given integration domain's label and its code owners from the assignees. (author or code owners) — e.g. @home-assistant unassign "opensky"
  • close — Closes the issue or pull request. (code owners)
  • reopen — Reopens the issue or pull request. (code owners)
  • rename — Renames the issue or pull request: rename "<new title>". (code owners) — e.g. @home-assistant rename "A more descriptive title"
  • add-label — Adds a label (needs-more-information, problem in dependency, problem in custom component, problem in config, problem in device, feature-request) to the issue or pull request. (code owners) — e.g. @home-assistant add-label "needs-more-information"
  • remove-label — Removes a label (needs-more-information, problem in dependency, problem in custom component, problem in config, problem in device, feature-request) from the issue or pull request. (code owners) — e.g. @home-assistant remove-label "needs-more-information"
  • mark-draft — Marks the pull request as draft. (code owners)
  • update-branch — Updates the pull request branch with the base branch. (code owners)

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot AI review requested due to automatic review settings July 16, 2026 10:14

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 5 changed files in this pull request and generated 7 comments.

Copilot AI review requested due to automatic review settings July 16, 2026 11:28
@albertteoh
albertteoh force-pushed the growatt-classic-auth-writes branch from 1e22130 to 6787520 Compare July 16, 2026 11:30
@albertteoh

Copy link
Copy Markdown
Author

Pushed a follow-up commit addressing the Copilot review feedback:

  • Added a real classic-auth read path for AC charge/discharge times (parses the coordinator's already-cached mix_detail data), and switched the write handlers to always read-merge-write for both auth types — partial writes no longer reset unspecified fields to fixed defaults.
  • Restricted service device lookup to explicit (device_type, api_version) pairs so a write can't be routed to the wrong device-specific endpoint.
  • Classic API responses now require an explicit success: True; missing/malformed responses are treated as failures.
  • Broadened exception handling around the classic mixSet call to include RequestException/json.JSONDecodeError, not just GrowattError.
  • Fixed the classic discharge-write path to update the coordinator cache on success (it previously only did this for charge).
  • Made the no_devices_configured message auth-neutral and updated the write/read service descriptions to mention Mix devices.

Replied inline on each thread with details. One item I left open: the suggestion to move the param1-param18 protocol encoding into the growattServer library. I agree with the guideline it's citing, but that requires a change to the separate PyPI package plus a version bump here, which isn't something I can land in this PR — happy to follow up separately, or block on it if you'd prefer.

All tests, ruff, mypy, and pylint pass locally (164 tests in tests/components/growatt_server).

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 growattServer and 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}"

Copilot AI review requested due to automatic review settings July 16, 2026 11:35

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 6 out of 6 changed files in this pull request and generated 6 comments.

Copilot AI review requested due to automatic review settings July 16, 2026 11:43

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 6 out of 6 changed files in this pull request and generated 2 comments.

albertteoh and others added 21 commits November 6, 2026 22:31
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.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Concurrent classic Mix schedule updates can silently overwrite charge or discharge changes because the complete per-device read–merge–write transaction is not serialized.

3 open issues

Review effort: Balanced

# 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()
Comment on lines +650 to +651
async def _fetch_classic_mix_settings(self, required_keys: list[str]) -> dict:
"""Fetch classic Mix settings (getMixSetParams) for the AC read services."""
@home-assistant

home-assistant Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

👋 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 dashboard

This 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 apply

If you think a check doesn't apply to your PR (or the rule is bugged), comment @home-assistant ignore "<check name>" "<reason>". The check name as shown in the table above. This will mark the check as ignored and let you put your PR in 'Ready for review'; @home-assistant unignore "<check name>" restores the rule.

Bot commands

Reply with @home-assistant <command>. Several commands can be stacked, one per line:

  • update — Re-runs the bot's checks on the issue or pull request.
  • ignore — Waives a dashboard check: ignore "<check name>" "<reason>". (author) — e.g. @home-assistant ignore "Merge conflicts" "Broken rule, no merge conflicts present"
  • unignore — Restores a waived dashboard check: unignore "<check name>". (author) — e.g. @home-assistant unignore "Merge conflicts"
  • unassign — Removes the given integration domain's label and its code owners from the assignees. (author or code owners) — e.g. @home-assistant unassign "opensky"
  • close — Closes the issue or pull request. (code owners)
  • reopen — Reopens the issue or pull request. (code owners)
  • rename — Renames the issue or pull request: rename "<new title>". (code owners) — e.g. @home-assistant rename "A more descriptive title"
  • add-label — Adds a label (needs-more-information, problem in dependency, problem in custom component, problem in config, problem in device, feature-request) to the issue or pull request. (code owners) — e.g. @home-assistant add-label "needs-more-information"
  • remove-label — Removes a label (needs-more-information, problem in dependency, problem in custom component, problem in config, problem in device, feature-request) from the issue or pull request. (code owners) — e.g. @home-assistant remove-label "needs-more-information"
  • mark-draft — Marks the pull request as draft. (code owners)
  • update-branch — Updates the pull request branch with the base branch. (code owners)

Checks

✨ Everything's in order!

6 checks passed (5 skipped)
Status Check Details
✅ Forbidden files No forbidden files.
✅ Belongs together Belongs together with home-assistant/home-assistant.io#48991.
✅ Merge conflicts No merge conflicts.
✅ Merge target This PR targets dev.
✅ Type of change Type of change: new-feature
✅ CLA Everyone involved has signed the CLA.
➖ New integration validation Not a new-integration PR.
➖ Single new platform No new platforms added.
➖ Documentation Not a new integration or platform — no documentation PR required.
➖ Code owner approval Touches no platinum integration — no code-owner approval required.
➖ Blocking: awaiting-frontend awaiting-frontend label not set — nothing to block.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.

@albertteoh

Copy link
Copy Markdown
Author

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!

@github-actions

Copy link
Copy Markdown
Contributor

Quality scale review

✅ No issues found at 72374b2. Checked action-exceptions, exception-translations, and test-coverage for growatt_server; none are violated by the changed lines.

Generated by quality-scale-reviewer · copilot · auto · 49.7 AIC · ⌖ 8.61 AIC · ⊞ 8.3K · ◷

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants