Metadata-Version: 2.4
Name: franklinwh-direct-connect-bridge
Version: 0.5.56
Summary: Home Assistant add-on / REST + MQTT bridge for the FranklinWH aGate local (sendMqtt) API
Author-email: david2069 <david2069@users.noreply.github.com>
License: MIT
Project-URL: Homepage, https://github.com/david2069/franklinwh-direct-connect-bridge
Project-URL: Documentation, https://david2069.github.io/franklinwh-direct-connect-bridge/
Project-URL: Issues, https://github.com/david2069/franklinwh-direct-connect-bridge/issues
Project-URL: Changelog, https://github.com/david2069/franklinwh-direct-connect-bridge/blob/main/CHANGELOG.md
Classifier: Development Status :: 3 - Alpha
Classifier: Framework :: FastAPI
Classifier: Intended Audience :: End Users/Desktop
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Home Automation
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: franklinwh-direct-connect-api>=0.6
Requires-Dist: franklinwh-modbus==0.13.0
Requires-Dist: franklinwh-system-view==0.5.1
Requires-Dist: franklinwh-ha-notify==0.1.4
Requires-Dist: hems==0.2.0
Requires-Dist: fastapi>=0.111
Requires-Dist: uvicorn>=0.29
Requires-Dist: jinja2>=3.1
Requires-Dist: pydantic>=2.0
Requires-Dist: pydantic-settings>=2.0
Requires-Dist: paho-mqtt>=2.0
Requires-Dist: croniter>=2.0
Requires-Dist: rainflow==3.2.0
Requires-Dist: cryptography>=42
Requires-Dist: argon2-cffi>=23.1
Provides-Extra: test
Requires-Dist: pytest>=8.0; extra == "test"
Requires-Dist: httpx>=0.27; extra == "test"
Provides-Extra: cloud
Requires-Dist: franklinwh-cloud==0.6.5; extra == "cloud"
Requires-Dist: franklinwh-ha-cloud-analytics==0.1.27; extra == "cloud"
Dynamic: license-file

# FranklinWH Direct Connect Bridge

[![version](https://img.shields.io/badge/dynamic/toml?url=https%3A%2F%2Fraw.githubusercontent.com%2Fdavid2069/franklinwh-direct-connect-bridge%2Fmain%2Fpyproject.toml&query=%24.project.version&label=version&color=blue)](https://github.com/david2069/franklinwh-direct-connect-bridge/blob/main/CHANGELOG.md)
[![Install smoke](https://img.shields.io/github/actions/workflow/status/david2069/franklinwh-direct-connect-bridge/install-smoke.yml?branch=main&label=build)](https://github.com/david2069/franklinwh-direct-connect-bridge/actions/workflows/install-smoke.yml)
[![Docs](https://img.shields.io/github/actions/workflow/status/david2069/franklinwh-direct-connect-bridge/docs.yml?branch=main&label=docs)](https://github.com/david2069/franklinwh-direct-connect-bridge/actions/workflows/docs.yml)
[![Add-on image](https://img.shields.io/github/actions/workflow/status/david2069/franklinwh-direct-connect-bridge/publish-image.yml?branch=main&label=image)](https://github.com/david2069/franklinwh-direct-connect-bridge/actions/workflows/publish-image.yml)
[![Release](https://img.shields.io/github/actions/workflow/status/david2069/franklinwh-direct-connect-bridge/release.yml?label=packaging)](https://github.com/david2069/franklinwh-direct-connect-bridge/actions/workflows/release.yml)

[![Home Assistant add-on](https://img.shields.io/badge/Home%20Assistant-add--on-41BDF5?logo=homeassistant&logoColor=white)](https://github.com/david2069/franklinwh-direct-connect-bridge/blob/main/INSTALL.md)
[![python](https://img.shields.io/badge/python-3.11%2B-blue?logo=python&logoColor=white)](https://github.com/david2069/franklinwh-direct-connect-bridge/blob/main/pyproject.toml)
[![license](https://img.shields.io/badge/license-MIT-green)](https://github.com/david2069/franklinwh-direct-connect-bridge/blob/main/LICENSE)
[![installs](https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fanalytics.home-assistant.io%2Faddons.json&query=%24%5B%274a12892f_franklinwh_local_bridge%27%5D.total&label=installs&logo=homeassistant&logoColor=white&color=41BDF5)](https://analytics.home-assistant.io/)
[![commit activity](https://img.shields.io/github/commit-activity/y/david2069/franklinwh-direct-connect-bridge)](https://github.com/david2069/franklinwh-direct-connect-bridge/commits/main)

**Install in Home Assistant:** click to add this repository to your add-on store, then install
**FranklinWH Direct Connect Bridge** from it ([full steps](https://github.com/david2069/franklinwh-direct-connect-bridge/blob/main/INSTALL.md)).

[![Add repository to Home Assistant](https://my.home-assistant.io/badges/supervisor_add_addon_repository.svg)](https://my.home-assistant.io/redirect/supervisor_add_addon_repository/?repository_url=https%3A%2F%2Fgithub.com%2Fdavid2069%2Ffranklinwh-direct-connect-bridge)

This integration is a proof-of-concept demonstration of how to integrate with a FranklinWH aGate gateway over the (undocumented, unofficial) FranklinWH Direct Connect local API.

> **On the names.** **Direct Connect** is FranklinWH's own term for the gateway's local
> protocol, implemented by the library
> [`franklinwh-direct-connect-api`](https://github.com/david2069/franklinwh-direct-connect-api).
> **This** is the application built on top of it. The repo, the Python package and the CLI are
> still called `franklinwh-direct-connect-bridge`, and the Home Assistant add-on slug is still
> `franklinwh_local_bridge` — renaming those would break existing installs, so only the
> display names changed.

It is not intended for production use, and there is no guarantee it is compatible with your FranklinWH gateway(s), aPower(s) or connectivity — now or in the future. FranklinWH may block or deprecate this interface at any time. It has been tested on a local area network against my own single aGate X and aPower X.

Point it at your own gateway, or add one or more **emulated (mock) gateways** and see the
whole thing work before you connect real hardware.

**At a glance:** why the Bridge exists, how it grew, the ways to install it, and what each
transport can do. [Interactive page](https://david2069.github.io/franklinwh-direct-connect-bridge/overview/bridge-overview.html)
· [high-res image](https://github.com/david2069/franklinwh-direct-connect-bridge/blob/main/docs/overview/bridge-overview.png) ([dark](https://github.com/david2069/franklinwh-direct-connect-bridge/blob/main/docs/overview/bridge-overview-dark.png)).

**Use cases:** what you want to do, from "I use Home Assistant OS" to "charge my car only on
solar", with a short how-to and links to the guides: [I want to…](https://david2069.github.io/franklinwh-direct-connect-bridge/guide/use-cases/)

**Quick install:** three routes on one page: the command line on a spare Windows, Mac or Linux
computer, a new Home Assistant OS, or an App in the one you have. [Pick your route](https://david2069.github.io/franklinwh-direct-connect-bridge/guide/quick-install/)
· [image](https://github.com/david2069/franklinwh-direct-connect-bridge/blob/main/docs/overview/quick-install.png).

## Running it

- As a **Home Assistant add-on** (served through ingress, MQTT auto-configured)
- In **Docker**, or any container runtime
- **Standalone** in a Python virtual environment, on any platform with Python 3.11+

## Interfaces

- A **web UI** — responsive for desktop, tablet and phone, with show/hide and reorder on
  the dashboard cards and the topbar
- The built-in **REST API** (`/docs` for the live OpenAPI inventory)
- **MQTT**, as Home Assistant entities via discovery

## Highlights

- **[Setup wizard](https://github.com/david2069/franklinwh-direct-connect-bridge/blob/main/docs/guide/tour.md#first-run-the-setup-wizard)**: Automatic, Mock or Custom setup: links Home Assistant, finds your aGate, offers the FranklinWH cloud and the Modbus client, and checks for an existing FranklinWH integration in Home Assistant.
- **[Scheduler](https://github.com/david2069/franklinwh-direct-connect-bridge/blob/main/docs/guide/scheduler/index.md)**: Daily, interval and cron triggers; entry and exit conditions over any sensor; priorities and conflict policy; and an explain view of why a window did or did not fire.
- **[Analytics](https://github.com/david2069/franklinwh-direct-connect-bridge/blob/main/docs/guide/energy-and-costs.md#analytics)**: Energy flows, battery use and self-sufficiency by day, week, month, year and lifetime, from the bridge's own store or the FranklinWH cloud, with CSV export.
- **[Health](https://github.com/david2069/franklinwh-direct-connect-bridge/blob/main/docs/guide/health-report.md)**: A daily health report with a colour, unusual changes flagged, a weekly battery report, and battery warranty and wear.
- **[Network monitoring](https://github.com/david2069/franklinwh-direct-connect-bridge/blob/main/docs/guide/tour.md#the-tabs)**: The connection end to end: latency to the aGate, MQTT, AWS IoT, the CloudFront edge your cloud calls reach (with a map), cloud errors and retries, and link history.
- **[Notifications](https://github.com/david2069/franklinwh-direct-connect-bridge/blob/main/docs/guide/ha-setup-and-notifications.md)**: Optional: alerts and schedule notifications pushed to your phones through Home Assistant, including actionable ones that ask before acting.
- **[HEMS](https://github.com/david2069/franklinwh-direct-connect-bridge/blob/main/docs/guide/hems/index.md)**: Energy planning: a calibrated solar forecast, a load forecast, the wear cost of each kWh through the battery, and a description of your home that planning works from.

## What it does

**Monitor**
- Discovers gateways on the LAN and runs **several at once** from one install
- Live power flow, state of charge, operating mode and run status
- **Per-cell BMS telemetry** — cell voltages and temperatures per aPower, with recorded
  sessions you can replay and compare
- Local history in a SQLite store, with charts for both real-time and historical views,
  an Analytics tab and CSV export

**Control** — all writes gated off until you enable them
- Operating mode, off-grid / reconnect, reboot
- **Generator**: enable, mode, exercise schedule, start SoC
- **Smart circuits**: switch a circuit, set its schedule
- **Battery dispatch**: force charge or discharge at a given power, with an optional
  target SoC (over Modbus — see [Transports](#transports))
- Reserved SoC (over the Cloud API, which is the only path that works — see
  [Transports](#transports))

**Automate**
- A **scheduler** with daily, interval and cron triggers; entry and exit conditions over
  any sensor; priority and conflict policy; templates; and an explain view for why a
  window did or did not fire
- **Home Assistant actions** — fire a notification or call a service
- **Solar forecast** and weather from Open-Meteo, including forecast-vs-actual

**Account for it** (optional)
- Sites, meters, utilities and tariffs as first-class records, with effective dates
- Billing periods with cost tracking, and tariff import/export shared with the Modbus
  bridge. Informational only — it does not bill anyone

**Administer**
- Database backup, restore and storage metrics
- An audit trail of every control write
- Home Assistant notifications on events

This integration requires the unofficial FranklinWH Direct Connect API library:
[`franklinwh-direct-connect-api`](https://github.com/david2069/franklinwh-direct-connect-api) 

The integration has been modelled on [`energipays-bridge`](https://github.com/david2069/energipays-bridge): dual-target
Dockerfile (slim standalone / alpine HA base), ingress web UI, `mqtt:want` broker
auto-discovery, `read_only` by default.

> **Status: in service.** 180 REST paths (206 operations), the full UI, MQTT / Home Assistant
> discovery, and a SQLite metrics store are all live and running against real hardware.
> See the [**User Guide**](https://github.com/david2069/franklinwh-direct-connect-bridge/blob/main/docs/guide/README.md) for the UI, the Scheduler, Home Assistant
> and the control gates, and [`docs/API_COMPARISON.md`](https://github.com/david2069/franklinwh-direct-connect-bridge/blob/main/docs/API_COMPARISON.md) for how the
> three transports compare.

## ⚖️ Disclaimer

> **UNOFFICIAL SOFTWARE — NOT AFFILIATED WITH OR ENDORSED BY FRANKLINWH.**
>
> This bridge talks to FranklinWH's undocumented **Direct Connect** (local) API and its **cloud** API —
> technically the **same private API the official FranklinWH mobile app** uses (FleetView, the installer
> portal, runs on the same backend), intended for those apps and not for third-party use — plus the
> standard **SunSpec Modbus TCP** API (with undocumented FranklinWH extensions). Any of these may change,
> break, or become unavailable without notice. It is provided **AS-IS**, without warranty of any kind,
> express or implied — use entirely at your own risk. The authors accept no liability for service
> interruptions, data loss, equipment damage, or any other consequences of using this software.
>
> **Do NOT contact FranklinWH support** about this app. Raise issues, defects, or feature requests on
> GitHub instead: <https://github.com/david2069/franklinwh-direct-connect-bridge/issues>
>
> **MIT License.** The disclaimer is also logged once at startup and shown as a one-time
> acknowledgement modal on first connection (recorded for the audit trail).

### Compliance & anti-circumvention

> You agree to keep your gateway and battery settings, controls, and operation compliant with the
> configuration set through the official FranklinWH Mobile App and the installer/support FleetView portal.
>
> FranklinWH-managed settings may exist to, among other things: protect the **safety and longevity** of the
> battery and gateway; apply **automatic software updates** and restrict your ability to view or change
> battery, grid-import, or grid-export controls; enforce your **local grid profile** and any import/export
> limits or prohibitions; and enforce restrictions tied to **contractual incentives, subsidies, or VPP/grid
> programmes**.
>
> If you use this software to bypass or override any such control, restriction, or compliance measure —
> deliberately or inadvertently — you do so **entirely at your own risk**. This is neither condoned nor
> encouraged by the authors or any other party.
>
> This software is provided for **informational and educational purposes**, **AS-IS**, with no warranty of
> fitness for any purpose. Any use — personal or commercial — is permitted under the MIT Licence and is
> entirely at your own risk.
>
> As the MIT Licence requires, the copyright notice and this notice (including the Additional Terms) should
> be included in copies or substantial portions of the software — in forks, derivatives, and AI-assisted
> works alike, so the unofficial-app and compliance context travels with the code. See [`LICENSE`](https://github.com/david2069/franklinwh-direct-connect-bridge/blob/main/LICENSE)
> (Additional Terms) for the authoritative text.

**SunSpec Modbus conformance.** Unlike FranklinWH's Direct Connect and cloud APIs, the Modbus TCP surface
is a documented open standard. FranklinWH's implementation is published by the SunSpec Alliance:
- [Modbus PICS](https://sunspec.org/wp-content/uploads/2009/03/UPDATED_FranklinWH_Modbus_PICS_SM-000028.xlsx)
  (Protocol Implementation Conformance Statement, SM-000028)
- [IEEE 1547 certificate](https://sunspec.org/wp-content/uploads/2009/03/UPDATED_FranklinWH_Modbus_1547_Certificate_SM-000028.pdf)

(FranklinWH layers some **undocumented** registers on top of the standard — those extensions are not in the PICS.)

## Install

**[INSTALL.md](https://github.com/david2069/franklinwh-direct-connect-bridge/blob/main/INSTALL.md)** covers all three paths — Home Assistant add-on, Docker, and a
development checkout — with prerequisites, upgrading and troubleshooting. The add-on summary
below is the short version.

## Install as a Home Assistant add-on

1. In Home Assistant, go to **Settings → Add-ons → Add-on Store**.
2. Open the **⋮** menu (top-right) → **Repositories**, add
   `https://github.com/david2069/franklinwh-direct-connect-bridge`, then close.
3. Find **FranklinWH Direct Connect Bridge** in the store and click **Install**.
4. On the **Configuration** tab set `fwh_host` to your aGate's IP, and enable
   `mqtt_enabled` to publish the battery as Home Assistant entities. **Save.**
5. **Start** the add-on, then open its sidebar panel (served over HA ingress).

Notes:

- **MQTT** auto-configures from the official **Mosquitto** add-on — no host/credentials
  needed (the Supervisor provides them; the `mqtt:want` service discovers the broker).
- **Local history** (the SQLite metrics store) is **off by default** in the add-on when
  MQTT is on — Home Assistant's own recorder already stores the published MQTT entities,
  so a second copy is redundant. Set `metrics_enabled: true` to force it on.
- The Supervisor **watchdog** restarts the add-on if the web app stops serving (it probes
  `/api/live`, which does no gateway I/O, so a down aGate never triggers a restart).
- Control writes (mode / off-grid) stay **off** until you enable `allow_writes`; you can
  flip it live from the **Settings** tab in the UI.

## Layout

```
config.yaml build.yaml repository.json   # HA add-on manifest + arch bases
Dockerfile docker-entrypoint.sh docker-compose.yml
src/franklinwh_direct_connect_bridge/
  app.py cli.py config.py client.py ha_options.py
  templates/  static/
tests/
```

## Run it yourself (standalone)

Nothing here needs a checkout of any other FranklinWH repository. The Direct Connect API
library is an ordinary dependency and installs from PyPI like any other.

**With pip:**

```bash
python3 -m venv .venv && source .venv/bin/activate
pip install ".[cloud]"            # pulls franklinwh-direct-connect-api from PyPI
FWH_HOST=192.0.2.110 franklinwh-direct-connect-bridge run   # → http://localhost:8101
```

**From PyPI** (from 0.5.55), no clone needed:

```bash
python3 -m venv .venv && source .venv/bin/activate
pip install "franklinwh-direct-connect-bridge[cloud]"
FWH_HOST=192.0.2.110 franklinwh-direct-connect-bridge run   # → http://localhost:8101
```

**With Docker:**

```bash
docker build -t franklinwh-direct-connect-bridge:dev .
docker compose up -d
```

A plain `docker build` resolves every dependency from PyPI, including
[`franklinwh-direct-connect-api`](https://pypi.org/project/franklinwh-direct-connect-api/).
The **Home Assistant add-on builds exactly this way**, on your HA host, with no sibling
repositories involved.

> **Do not use `docker compose up --build`.** `docker-compose.yml` has no `build:` section
> (see below), so the `--build` flag is silently ignored and any existing container keeps
> running. Build the image first, as above.

> **The cloud transport is an optional extra.** Install without `[cloud]` and the app still
> runs, but every cloud-backed capability — including reserve-SoC write — reports
> `available: false, reason: "library not installed"` (see `GET /api/providers`). That is
> the same mechanism by which Modbus dispatch reports unavailable, so do not read one as
> evidence of the other.

## Develop

Only this part involves sibling checkouts, and only so an **unreleased** library can be
tested before it ships.

```bash
python3 -m venv .venv && source .venv/bin/activate
pip install -e ".[test,cloud]"
pip install -e ../franklinwh-direct-connect-api   # optional: the library, editable
tools/dev.sh                                 # build image, restart container, VERIFY it
```

`tools/build_image.sh` builds wheels from the sibling repos into `wheels/`, and the
Dockerfile prefers anything it finds there over PyPI. An empty `wheels/` — which is what a
clean clone has — simply means everything comes from PyPI. That is why `wheels/.gitkeep` is
committed: the Dockerfile `COPY`s the directory, so it has to exist.

`tools/dev.sh` then checks that the running container is actually built from your working
tree, and **exits non-zero if it is not**. `GET /api/version` reports the same stamp as
`source_sha`. Use it before trusting any measurement taken against the running bridge — see
`CLAUDE.md`, "Verifying against the running bridge".

## Demo / no-hardware mode

Run the whole UI with **live-looking data and no aGate** — handy for a demo, screenshots,
or UI work:

```bash
tools/demo.sh            # build image + start; then open http://localhost:8102
tools/demo.sh --down     # tear it down
```

It starts **two seeded mock aGates** (the `franklinwh-direct-connect emulate --seed N` emulator, on port 19000
bundled in the image — each a distinct virtual device with a solar/battery/load curve that
follows the time of day) plus a bridge pointed at mock-1. Values move between polls, control
buttons are enabled against the mock, and it is fully isolated from the real deployment
(own port `8102`, own `./data-demo` volume, MQTT off — the real container on `8101` is
untouched). `mock-agate-2` is already running and ready for **multi-gateway** testing.

## Endpoints

**180 paths / 206 operations**, as served by the running app. `/docs` (OpenAPI) is the live
inventory — prefer it over this table, which is a snapshot. The shape:

| Group | Paths | What |
|---|---|---|
| `/api/cmd/*` | 37 | the library's local cmdType read surface, registered 1:1 from it |
| `/api/cloud/*` | 16 | cloud reads + the cloud-only writes (reserve, mode, smart-circuit) |
| `/api/ha/*` | 11 | Home Assistant topology, entities and WebSocket status |
| `/api/schedules/*` | 11 | the automation engine: CRUD, templates, explain, import/export |
| `/api/generator/*` | 7 | generator config and metrics (hidden when none is installed) |
| `/api/battery/*` | 7 | BMS telemetry, recorder sessions, direct-Modbus dispatch |
| `/api/mqtt/*` | 7 | config, entities, discovery, republish / unpublish, broker scan |
| `/api/admin/*` | 7 | backup / restore, storage metrics, vacuum, exports |
| `/api/gateways/*`, `/api/tariffs/*`, `/api/billing/*`, `/api/circuits/*` | 5 each | multi-gateway roster, tariffs, billing periods, smart circuits |
| rest | 58 | `/api/health`, `/api/power`, `/api/summary`, `/api/site/status`, `/api/settings`, `/api/der-comms`, `/api/firmware`, `/api/providers`, `/api/dispatch`, `/api/modbus`, `/api/sites`, `/api/meters`, `/api/utilities`, `/api/solar`, `/api/notify`, `/api/constants`, `/api/metrics`, `/api/logs`, `/api/call/{cmd}`, … |

Plus `/` (UI) and `/api/live` (the watchdog probe that does no gateway I/O).

## Transports

All three are wired, each used only where it is the right one.

- **Local sendMqtt (TCP/9000)** — the baseline. Everything under `/api/cmd/*`, plus the
  hardware-verified mode / off-grid / der-comms / reboot writes. Gated **off by default**
  (`read_only: true`).
- **Cloud API** — used only where the local transport physically cannot reach: **reserve-SoC
  write** (the aGate silently discards the local write) and the cloud-native mode /
  smart-circuit setters. `GET /api/providers` reports, per capability, which transport is
  active and why.
- **Modbus TCP (SunSpec)** — used for the one thing neither of the others can do:
  **battery power dispatch**. `battery_control.py` drives the aGate's WSet setpoint
  (SunSpec Model 704) over TCP/502 through the `franklinwh-modbus` library, so force
  charge/discharge with a power and an optional target-SoC runs from this bridge
  (`POST /api/dispatch`) — it does *not* require the separate Modbus Bridge service.
  Gated behind a master switch in Settings, with reachability reported as `modbus_502` in
  `/api/health` and testable at `/api/modbus/test`.

  > **Force writes move the battery.** On this firmware the hardware revert timer
  > (`WSetRvrtTms`) is cosmetic, and the bridge gives the library no duration, so the
  > bridge's own watchdog is the only safety — always release when done. That watchdog
  > and a global Release stop a dropped connection from leaving the battery dispatched.

  The SunSpec **enable toggle** (`/api/der-comms`, cmd 1205) is a separate thing and rides
  the *local* API, not Modbus. See [`docs/API_COMPARISON.md`](https://github.com/david2069/franklinwh-direct-connect-bridge/blob/main/docs/API_COMPARISON.md).
