# Sigenergy API Agent

A Claude-powered conversational assistant with **complete Sigenergy knowledge — Cloud OpenAPI/MQTT plus the local Modbus protocol (RS485 RTU + Modbus TCP)**. Ask questions in plain English, get accurate answers, and optionally make live API calls directly to your Sigenergy system.

> **Modbus note:** the local Modbus register map is **not** in the developer portal (portal is Cloud OpenAPI only). The agent's Modbus knowledge comes from the official *Sigenergy Modbus Protocol V2.7* doc (`API/Modbus/`). Key fact: plant-level data (SOC, PV, grid, ESS power) is read at **slave address 247** over RS485 (9600 8N1) or TCP (port 502), using the full `30xxx` register numbers.

---

## What it does

- **Answers any question** about the Sigenergy developer API — endpoints, authentication, data formats, error codes, rate limits, operating modes, MQTT subscriptions, and more
- **Answers local Modbus questions** — RS485 RTU vs TCP, slave addressing (plant 247 / device 1-246 / broadcast 0), the plant register map, framing (9600 8N1), and function codes
- **Guides portal setup** — developer registration, invitation flow, App Key/Secret generation, and dashboard navigation
- **Makes live API calls** on your behalf — authenticate, fetch real-time energy flow, query your system list, and more
- **Helps you write integration code** — Shelly scripts, Python clients, REST calls, MQTT subscribers
- **Explains errors** — paste an error code or response and the agent will diagnose it

All Sigenergy documentation (API reference + developer portal user guide) is compiled into the agent's knowledge base and cached efficiently using Anthropic's prompt caching, so repeated questions are fast and cheap.

---

## Prerequisites

- Python 3.8+
- An [Anthropic API key](https://console.anthropic.com) (Claude access)
- A Sigenergy developer account with App Key & App Secret

---

## Installation

```bash
pip install anthropic requests
```

---

## Configuration

Set the following environment variables before running:

| Variable | Required | Description |
|---|---|---|
| `ANTHROPIC_API_KEY` | **Yes** | Your Anthropic API key (`sk-ant-...`) |
| `SIGEN_APP_KEY` | For live calls | Your Sigenergy App Key |
| `SIGEN_APP_SECRET` | For live calls | Your Sigenergy App Secret |
| `SIGEN_SYSTEM_ID` | For live calls | Your power station system ID |
| `SIGEN_REGION` | No (default: `eu`) | `eu` or `cn` |

**Windows (PowerShell):**
```powershell
$env:ANTHROPIC_API_KEY  = "sk-ant-..."
$env:SIGEN_APP_KEY      = "sigenXXXXXXX"
$env:SIGEN_APP_SECRET   = "yoursecret"
$env:SIGEN_SYSTEM_ID    = "YOURSYSTEMID"
```

**Linux / macOS:**
```bash
export ANTHROPIC_API_KEY="sk-ant-..."
export SIGEN_APP_KEY="sigenXXXXXXX"
export SIGEN_APP_SECRET="yoursecret"
export SIGEN_SYSTEM_ID="YOURSYSTEMID"
```

> **Where to find your credentials:**
> - **App Key**: Developer Portal → Control Center → Settings → App Settings
> - **App Secret**: Same page — click **Generate** (shown **only once** — store it immediately)
> - **System ID**: MySigen app → Settings → ⋮ (three dots) → Basic Info

> **New to the developer portal?**
> - **Device owners / installers**: sign in at `developer.sigencloud.com` with your MySigen account — no registration needed
> - **Third-party platforms / VPP providers**: contact Sigenergy for an invitation code, then register — approval takes 3–5 business days

---

## Usage

```bash
python sigen_agent.py
```

The agent starts an interactive chat session:

```
╔══════════════════════════════════════════════════════╗
║         Sigenergy API Agent  (Claude-powered)        ║
╠══════════════════════════════════════════════════════╣
║  Region    : eu                                      ║
║  System ID : YOURSYSTEMID                            ║
║  Base URL  : https://api-eu.sigencloud.com           ║
╚══════════════════════════════════════════════════════╝

You: fetch my current energy flow
Agent: [calls /openapi/systems/.../energyFlow live]
  PV Power    :  4.2 kW
  Battery     : -1.8 kW  (charging)
  Grid        :  0.0 kW
  Load        :  2.4 kW
  Battery SOC :  78 %
```

---

## Example prompts

| Prompt | What happens |
|---|---|
| `authenticate with my key` | Calls `/openapi/auth/login/key` and shows the token |
| `fetch my energy flow` | Live real-time power values for PV, grid, battery, load |
| `what is error 1502?` | Sigenergy system internal error — explains causes |
| `explain key-based vs account auth` | Detailed explanation with the onboard requirement |
| `write a Shelly script that polls energy flow every 30s` | Generates complete Shelly JS script |
| `what operating modes exist?` | MSC, FFG, VPP, NBI with full descriptions |
| `how do I subscribe to MQTT telemetry?` | Step-by-step subscription guide |
| `list all telemetry data fields` | Full list with units |
| `how do I register on the developer portal?` | Explains invitation-based registration vs MySigen sign-in |
| `where do I find my AppSecret?` | Dashboard navigation guide — App Settings → Generate |
| `how do I set up MQTT data push?` | Portal dashboard → Data Subscription setup walkthrough |
| `what is error 1604?` | Developer not yet approved — explains the review process |

---

## Known API quirks

These are documented inside the agent so it always gives correct answers:

1. **Auth `data` is a JSON string** — the response field `data` is a serialized JSON string, not an object. You must `JSON.parse()` it to get `accessToken`.
2. **Energy flow values are in kW** — not watts. Multiply by 1000 if your integration expects watts.
3. **Key-based auth requires onboard** — account & password auth does NOT need onboard.
4. **Energy flow `systemId` goes in the request body** — not just the URL path.

---

## How it works

```
User question
     │
     ▼
Claude (claude-opus-4-6) with full Sigenergy docs as cached system prompt
     │
     ├── Text answer ──────────────────────────► printed to console
     │
     └── Tool call: call_sigen_api ────────────► HTTP request to api-eu.sigencloud.com
                                                         │
                                                         └── result fed back to Claude
                                                                  │
                                                                  └── final answer
```

The complete Sigenergy documentation is loaded as a **cached system prompt** using Anthropic's prompt caching feature. This means:
- First call includes full doc cost
- Subsequent calls reuse the cache (~90% cheaper per query)

---

## Files

| File | Description |
|---|---|
| `sigen_agent.py` | The agent script |
| `README.md` | This file |

---

## Security note

Never commit your `ANTHROPIC_API_KEY`, `SIGEN_APP_KEY`, or `SIGEN_APP_SECRET` to version control. Always use environment variables or a `.env` file (add `.env` to `.gitignore`).

---

## License

MIT
