Metadata-Version: 2.4
Name: sonnenbatterie
Version: 0.8.0
Summary: "Access Sonnenbatterie REST API"
Home-page: https://github.com/weltmeyer/python_sonnenbatterie
Author: Jan Weltmeyer
License: GPLv3
Project-URL: Issue Tracker, https://github.com/weltmeyer/python_sonnenbatterie/issues
Classifier: Development Status :: 4 - Beta
Classifier: Programming Language :: Python :: 3.10
Classifier: Operating System :: OS Independent
Classifier: Environment :: Console
Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests
Requires-Dist: aiohttp
Dynamic: license-file

# python_sonnenbatterie

Python module to access the REST API of a [Sonnenbatterie](https://sonnenusa.com/en/products/).

This modules contains two distinct sets of APIs:
- the original sonnen API (v1)
- the new v2 API

Both are available in a synchronous and an asynchronous version:
- `sonnenbatterie` - SonnenAPI v1, synchronous
- `AsyncSonnenBatterie` - SonnenAPI v1, asynchronous
- `SonnenBatterieV2` - SonnenAPI v2, synchronous
- `AsyncSonnenBatterieV2` - SonnenAPI v2, asynchronous

The major difference between those two is the method to authenticate. With API v1 you need
to login using a username and a password. The newer API requires a token that can be found
in the web UI of your Sonnenbatterie.
Also, the v2 API provides a unified view across the different Sonnenbatterie models wheres
the v1 API may provide more details in specific setups.

When using the v1 API you'll autmatically get access to the v2 API by using the `sb2` 
attribute of the v1 client object.

## Installation

### Using `pip`

``` bash
pip3 install sonnenbatterie
```

### Manual installation
[Download the archive from pypi.org](https://pypi.org/project/sonnenbatterie/#files) and unpack where needed ;)

## Usage

### SonnenAPI v1 - sync
``` python
# API v1
from sonnenbatterie import sonnenbatterie

sb_host = '192.168.1.2'
sb_user = 'User'
sb_pass = 'Password'

# Init class, establish connection
sb = sonnenbatterie(sb_host, sb_user, sb_pass)

print(sb.get_status())	                # retrieve general information
print(sb.get_powermeter())              # retrieive power meter details
print(sb.get_batterysystem())           # retrieve battery system data
print(sb.get_inverter())                # retrieve inverter status
print(sb.get_systemdata())              # retrieve system data
print(sb.get_battery())                 # get battery information
print(sb.get_api_configuration())       # get api configuration
print(sb.get_commissioning_settings())  # get commissioning settings
```

### SonnenAPI v1 - async
``` python
# API v1
from sonnenbatterie import AsyncSonnenBatterie

sb_host = '192.168.1.2'
sb_user = 'User'
sb_pass = 'Password'

# Init class, establish connection
sb = AsyncSonnenBatterie(sb_host, sb_user, sb_pass)

print(await sb.get_status())	              # retrieve general information
print(await sb.get_powermeter())              # retrieive power meter details
print(await sb.get_batterysystem())           # retrieve battery system data
print(await sb.get_inverter())                # retrieve inverter status
print(await sb.get_systemdata())              # retrieve system data
print(await sb.get_battery())                 # get battery information
print(await sb.get_api_configuration())       # get api configuration
print(await sb.get_commissioning_settings())  # get commissioning settings
# Async needs to close the connection!
await sb.logout()
```

### SonnenAPI v2 - sync
``` python
# API v2
# can either be access directly, see below, or
# via sb.sb2 (gets initialiazed automatically when creating a V1 object)

from sonnebatterie2 import SonnenBatterieV2

sb_host = '192.168.1.2'
sb_token = 'SeCrEtToKeN'        # retrieve via Web UI of SonnenBatterie

sb2 = SonnenBatterieV2(sb_host, sb_token)
print(sb2.get_configurations())         # retrieve configuration overview
print(sb2.get_battery_module_data())    # get battery module data
print(sb2.get_inverter_data())          # retrieve inverter data
print(sb2.get_latest_data())            # get latest date from sonnenbatterie
print(sb2.get_powermeter_data())        # get data from power meters
print(sb2.get_status())                 # get overall status information
print(sb2.get_io_data())                # get io status
```

### SonnenAPI v2 - async
``` python
# API v2
# can either be access directly, see below, or
# via sb.sb2 (gets initialiazed automatically when creating a V1 object)

from sonnebatterie2 import AsyncSonnenBatterieV2

sb_host = '192.168.1.2'
sb_token = 'SeCrEtToKeN'        # retrieve via Web UI of SonnenBatterie

sb2 = AsyncSonnenBatterieV2(sb_host, sb_token)
print(await sb2.get_configurations())         # retrieve configuration overview
print(await sb2.get_battery_module_data())    # get battery module data
print(await sb2.get_inverter_data())          # retrieve inverter data
print(await sb2.get_latest_data())            # get latest date from sonnenbatterie
print(await sb2.get_powermeter_data())        # get data from power meters
print(await sb2.get_status())                 # get overall status information
print(await sb2.get_io_data())                # get io status
# Async needs to close the connection!
await sb.logout()
```

### Login errors

A rejected login raises `sonnenbatterie.LoginError` (a `requests.HTTPError`,
sync) or `sonnenbatterie.AsyncLoginError` (an `aiohttp.ClientResponseError`,
async); the HTTP status tells a wrong password (401) from a busy battery
(502/503). After too many failed attempts the battery blocks logins for a
while and reports the duration in minutes; it is available as `block_time`
on the exception (`None` if the battery did not report one). While such a
block is active the client does not contact the battery again and raises
`sonnenbatterie.LoginBlockedError` (with `retry_after` in seconds) instead, so
that the block is not extended.

```python
from sonnenbatterie import sonnenbatterie, LoginError, LoginBlockedError

try:
    sb = sonnenbatterie(SONNEN_USERNAME, SONNEN_PASSWORD, SONNEN_IP)
except LoginBlockedError as e:
    print(f"blocked, retry in {e.retry_after:.0f} s")
except LoginError as e:
    print(f"login failed with HTTP {e.response.status_code}, block_time={e.block_time}")
```

### Unofficial endpoints (experimental)

The battery's own web dashboard uses a few endpoints that aren't part of the
documented API. They are read-only, and they need the session from the
username/password login (the static API token of the v2 API can't read them).
Their responses on a cascade (several batteries acting as one system) have
been checked on two real cascades so far (two and three units, firmware
1.40.5, masters and slaves), so the parsing may still change. Only the master
lists the cascade's members; a slave reports just its role.

```python
# serial number (DE_Ticket_Number) and the other configuration items
print(sb.get_serial_number())
print(sb.get_configs())                   # or sb.get_config("DE_Ticket_Number")

# cascade: role ("none", "master", "slave", "unknown") and, if the endpoints
# list them, the members, merged by serial number across the endpoints
info = sb.get_cascade_info()              # async: await sb.get_cascade_info()
print(info.role, info.is_cascade)
for member in info.members:
    # status ("WORKING") from stacking_status; raw also has e.g. ip,
    # backup_buffer and protect_active
    print(member.role, member.serial, member.status, member.raw)
print(info.members_sources)               # endpoints the members came from
print(info.raw)                           # raw responses, None = not available

# the raw endpoints
sb.get_stacking_status()                  # {"role": ..., "data": {"master": {serial: {...}}, "slaves": {serial: {...}}}, ...}
sb.get_stacking_protect()                 # HTTP 400 "not a stack" on a single battery
sb.get_inverter_stacking_status()         # needs a role above User (HTTP 401 for User, works for Installer)
```

`get_cascade_info()` treats "not a stack" (400), "role not permitted"
(401/403) and "endpoint unknown" (404) as not available; other errors are
raised. A 401 of `get_inverter_stacking_status()` doesn't trigger a new login,
as it means the role isn't permitted rather than an expired session.
