thomluther / anker-solix-api

Python library for Anker Solix API
MIT License
36 stars 10 forks source link
anker python
Solarbank E1600 Logo

Anker Solix Api

github licence python badge

This is an experimental Python library for Anker Solix Power devices (Solarbank, Inverter etc).

🚨 This is by no means an official Anker Api. 🚨

🚨 It can break at any time, or Api request can be removed/added/changed and break some of the endpoint methods used in this Api.🚨

Python Versions

The library is currently supported on

Required libraries

This project uses pipenv for Python dependency management

pip install pipenv
pipenv sync -d
pipenv run python [...]

Anker Account Information

Because of the way the Anker Solix Api works, one account with email/password cannot be used for the Anker mobile App and this Api in parallel. The Anker Cloud allows only one request token per account at any time. Each new authentication request by a client will create a new token and drop a previous token. Therefore usage of this Api may kick out your account login in the mobile app. However, starting with Anker mobile app release 2.0, you can share your defined system(s) with 'family members'. Therefore it is recommended to create a second Anker account with a different email address and share your defined system(s) with the second account. Attention: A shared account is only a member of the shared system, and as such currently has no permissions to access or query device details of the shared system. Therefore an Api homepage query will neither display any data for a shared account. However, a shared account can receive Api scene/site details of shared systems (App system = Api site), which is equivalent to what is displayed in the mobile app on the home screen for the selected system.

Usage

Everything starts with an: aiohttp ClientSession:

import logging, json
import asyncio
from aiohttp import ClientSession
from api import api, errors
import common

_LOGGER: logging.Logger = logging.getLogger(__name__)
# _LOGGER.setLevel(logging.DEBUG)    # enable for detailed Api output

async def main() -> None:
    """Create the aiohttp session and run the example."""
    async with ClientSession() as websession:
        """put your code here, example"""
        myapi = api.AnkerSolixApi(
            common.user(), common.password(), common.country(), websession, _LOGGER
        )
        await myapi.update_sites()
        await myapi.update_site_details()
        await myapi.update_device_details()
        await myapi.update_device_energy()
        print("System Overview:")
        print(json.dumps(myapi.sites, indent=2))
        print("Device Overview:")
        print(json.dumps(myapi.devices, indent=2))

# run async main
if __name__ == "__main__":
    try:
        asyncio.run(main())
    except Exception as err:
        print(f"{type(err)}: {err}")

The AnkerSolixApi class provides 4 main methods to query data and cache them into internal dictionaries:

Check out test_api.py and other python executable tools that may help to leverage and explore the Api for your Anker power system. The subfolder examples contains actual or older example exports with json files using anonymized responses of the export_system.py module giving you an idea of how various Api responses look like. Those json files can also be used to develop/debug the Api for system constellations not available to the developper.

AnkerSolixApi Tools

test_api.py

> pipenv run ./test_api.py

Example exec module that can be used to explore and test AnkerSolixApi methods or direct enpoint requests with parameters. You can modify this module as required. Optionally you can create your own test file called client.py which is not indexed and added to gitignore, so your local changes are not tracked for git updates/commits. This allows you to code your credentials in the local file if you do not want to utilize the environment variables:

_CREDENTIALS = {
    "USER": os.getenv("ANKERUSER"),
    "PASSWORD": os.getenv("ANKERPASSWORD"),
    "COUNTRY": os.getenv("ANKERCOUNTRY"),
}

export_system.py

> pipenv run ./export_system.py

Example exec module to use the Anker Api for export of defined system data and device details. This module will prompt for the Anker account details if not pre-set in the header or defined in environment variables. Upon successfull authentication, you can specify a subfolder for the exported JSON files received as Api query response, defaulting to your nick name Optionally you can specify whether personalized information in the response data should be randomized in the files, like SNs, Site IDs, Trace IDs etc. You can review the response files afterwards. They can be used as examples for dedicated data extraction from the devices. Optionally the AnkerSolixApi class can use the json files for debugging and testing on various system outputs.

Note:

You should preferrably run the export_system with the owner account of the site. Otherwise only limited information can be exported by shared accounts due to access permissions.

solarbank_monitor.py

> pipenv run ./solarbank_monitor.py

Example exec module to use the Anker Api for continously querying and displaying important solarbank parameters. This module will can use real time data from your Anker account, or optionally use json files from your local examples or export folder. When using the real time option, it will prompt for the Anker account details if not pre-set in the header or defined in environment variables. Upon successfull authentication, you will see the solarbank parameters displayed and refreshed at reqular interval. When using monitoring from local json file folder, they values will not change. But this option is useful to validate the api parsing with various system constellations.

Note: When the system owning account is used, more details for the solarbank can be queried and displayed.

Attention: When executing this module with real time data from your Anker account, the used account cannot be used in the Anker App since it will be kicked out on each refresh.

energy_csv.py

> pipenv run ./energy_csv.py

Example exec module to use the Anker Api for export of daily Energy Data. This method will prompt for the Anker account details if not pre-set in the header. Then you can specify a start day and the number of days for data extraction from the Anker Cloud. Note: The Solar production, Solarbank discharge, Smartmeter and Home usage can be queried across the full range each. The solarbank charge as well as smartmeter totals however can be queried only as total for an interval (e.g. day). Therefore when daily total data is also selected for export, 1-2 additional Api queries per day are required. The received daily values will be exported into a csv file.

Contributing

github contributors last commit Community Discussion

Github is used to host code, to track issues and feature requests, as well as accept pull requests.

Pull requests are the best way to propose changes to the codebase.

  1. Check for open features/bugs or initiate a discussion on one.
  2. Fork the repository.
  3. Fork the repo and create your branch from main.
  4. If you've changed something, update the documentation.
  5. Test your contribution.
  6. Issue that pull request!

Acknowledgements / Credits

Showing Your Appreciation

"Buy Me A Coffee"

If you like this project, please give it a star on GitHub