Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions .github/workflows/docker.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,13 @@ jobs:
packages: write
steps:
- name: Checkout
uses: actions/checkout@v3
uses: actions/checkout@v4

- name: Metadata
id: meta
uses: docker/metadata-action@v4
uses: docker/metadata-action@v5
with:
images: ghcr.io/MarcusWichelmann/energy-exporter
images: ghcr.io/${{ github.repository_owner }}/energy-exporter
tags: |
type=schedule
type=ref,event=branch
Expand All @@ -36,21 +36,21 @@ jobs:
type=sha

- name: Set up QEMU
uses: docker/setup-qemu-action@v2
uses: docker/setup-qemu-action@v3

- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
uses: docker/setup-buildx-action@v3

- name: Login to GHCR
if: github.event_name != 'pull_request'
uses: docker/login-action@v2
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}

- name: Build and push
uses: docker/build-push-action@v3
uses: docker/build-push-action@v6
with:
context: .
platforms: linux/amd64,linux/arm64
Expand Down
111 changes: 111 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
# CLAUDE.md

Context for working on this repository. This is a fork of
[MarcusWichelmann/EnergyExporter](https://github.com/MarcusWichelmann/EnergyExporter), maintained at
[jamesvarty/EnergyExporter](https://github.com/jamesvarty/EnergyExporter).

## What it does

ASP.NET Core service (.NET 10) that polls energy devices over Modbus TCP and exposes the readings as:

- a management UI at `/` (static page in `src/EnergyExporter/wwwroot/index.html`, backed by `/api/status`)
- Prometheus metrics at `/metrics`
- a REST API at `/devices` (JSON, or XML via `Accept: application/xml`), documented at `/swagger` (`/openapi/v1.json`)
- optional pushes to InfluxDB 2 and MQTT (`Export` section of `appsettings.json`)

Supported devices: SolarEdge inverters, meters and batteries (SunSpec registers) and Janitza power analyzers.

## Layout

| Path | Purpose |
| --- | --- |
| `Devices/` | One class per device type. Properties carry `[ModbusRegister]` / `[ScaledModbusRegister]` / `[StringModbusRegister]` (where to read), `[PrometheusMetric]` and `[InfluxDbMetric]` (how to export). Adding a value means adding an attributed property, nothing else. |
| `Modbus/ModbusReader.cs` | One reader per `host:port`, shared by all devices on that endpoint and serialized with a lock. Groups registers into chunks of at most 125, enforces connect/read timeouts, retries once only if a *reused* connection failed. |
| `Modbus/ScaledModbusRegisterAttribute.cs` | SunSpec `value * 10^sf`. "Not implemented" markers (0xFFFF uint16, 0x8000 int16/scale factor, 0x80000000 int32) become `double.NaN`. uint32 values are acc32 counters, where 0 is valid, so they are never treated as markers. |
| `Services/DeviceService.cs` | Polls all configured devices, tracks a `DeviceStatus` per device (online, failures, last error, last reading) and logs once per outage. |
| `Services/DevicePollingService.cs` | `BackgroundService` loop: no overlapping polls, `PollNow()` trigger, runs each exporter independently and tracks its health. |
| `Controllers/StatusController.cs` | `/api/status`, `POST /api/poll`, `POST /api/reconnect`, `POST /api/devices/{id}/reconnect`. No authentication: LAN use only. |
| `Prometheus/MetricsWriter.cs` | Device metrics (NaN skipped) plus `energy_exporter_device_{up,polls_total,poll_failures_total,poll_duration_seconds}`. |

NaN handling must stay consistent: Prometheus, InfluxDB and MQTT skip NaN values, and JSON writes them as `null`
(`Utils/NaNAsNullDoubleConverter.cs`; System.Text.Json throws on NaN otherwise).

## Building and testing

The .NET SDK is **not installed** on the dev laptop; build and run everything through Docker.

```bash
docker build -t energy-exporter:dev .
# Package checks
docker run --rm -v $PWD/src/EnergyExporter:/w -w /w mcr.microsoft.com/dotnet/sdk:10.0 \
bash -c 'dotnet list package --vulnerable --include-transitive; dotnet list package --outdated'
# Run against the real inverter (the env var avoids the laptop's inotify limit)
docker run --rm -p 14560:14552 -e DOTNET_hostBuilder__reloadConfigOnChange=false \
-v /path/to/appsettings.json:/app/appsettings.json:ro energy-exporter:dev
```

There are no unit tests. Changes have been verified end to end by running the container against the real
inverter, and the InfluxDB and MQTT exporters against throwaway `influxdb:2.7` and `eclipse-mosquitto:2` containers.
For offline-device behaviour, configure an extra device at `127.0.0.1:1` (connection refused) or
`10.255.255.1:1502` (connect timeout).

The Dockerfile cross-compiles on the build platform and defaults `BUILDPLATFORM`/`TARGETARCH`/`TARGETOS`, so it also
works with the legacy (non-BuildKit) builder. CI (`.github/workflows/docker.yml`) publishes multi-arch images to
`ghcr.io/<repository owner>/energy-exporter`. GitHub Actions must be enabled on the fork, and new GHCR packages are
private by default.

## Deployment (home lab)

- Host `docker0.localdomain` (10.0.0.183, Ubuntu 22.04, Docker 29, only the legacy `docker-compose` v1). SSH alias
`docker0` (user `james` in the `docker` group, key `~/.ssh/id_ed25519_docker0`).
- Plain `docker run`, no compose file. The image is built on the host from the committed tree:
```bash
git archive --format=tar HEAD | ssh docker0 'rm -rf ~/src/EnergyExporter && mkdir -p ~/src/EnergyExporter && tar -x -C ~/src/EnergyExporter'
ssh docker0 'cd ~/src/EnergyExporter && docker build -t energy-exporter:local --label org.opencontainers.image.revision=<sha> . \
&& docker rm -f energy-exporter \
&& docker run -d --name energy-exporter --restart=always -p 14552:14552 \
-v /usr/energyexporter/appsettings.json:/app/appsettings.json:ro energy-exporter:local'
```
Tag the running image first (e.g. `docker tag energy-exporter:local energy-exporter:<previous>`) to keep a rollback.
- Config: `/usr/energyexporter/appsettings.json` (backup `appsettings.json.bak-20261108`). `Urls` is
`http://*:14552`, so the port mapping is `14552:14552`.
- Devices: SolarEdge SE10000H single-phase inverter at `10.0.0.95:1502`, unit 1, plus meter index 0
(SE-MTR-3Y-400V-B). The inverter accepts multiple Modbus TCP connections at once.
- Rollback images: `energy-exporter:net8` (fork on .NET 8, commit `e276c76`) and the original upstream
`ghcr.io/marcuswichelmann/energy-exporter:3` (container `energy-exporter-old`, stopped, `restart=no`).

## History of this fork (November 2026)

1. **Diagnosis.** The upstream container had logged 82,530 failed polls, each with a stack trace: mostly
`No route to host` (inverter offline, e.g. at night), plus `Connection refused` and connection resets. The code
had no connect timeout (hangs of about 2 minutes), let polls overlap via an `async void` timer, blocked startup
on the first poll and never retried.
2. **`e276c76` Reliability and management UI.** Timeouts, non-overlapping polls, stale-connection retry, one log
line per outage, independent exporters, device health metrics and the management UI. Data fixes: SunSpec
"not implemented" values (previously exported as 655.35 A / 6553.5 V on unused phases), floating-point
artifacts from negative scale factors, register chunking that could skip an isolated trailing register, and
startup validation of `Index` and `Port`.
3. **`13efdb5` .NET 10.** .NET 8 support ended on 2026-11-10. All packages were updated to their latest versions,
which removed vulnerable transitive `System.Text.Json` 7.0.2 and `RestSharp` 110.1.0. Swashbuckle was replaced
by the built-in `Microsoft.AspNetCore.OpenApi` plus `Swashbuckle.AspNetCore.SwaggerUI`, and the MQTT exporter
was adapted to MQTTnet 5 (`MqttClientFactory`, no `MQTTnet.Client` namespace).
4. **Result.** In the first week on `13efdb5`, 34 of 45,805 polls failed (0.07%) across 16 short outages, each
logged once.
5. **docker0 housekeeping.** Removed the unused `portainer_agent` (crash-looping: its Docker API 1.42 is below
Docker 29's minimum of 1.44), 17 stopped containers (stray `cloudflared` runs, the `mcp-grafana` test stack,
Node-RED, a Bitbucket runner) and their images, freeing about 4.3 GB. The `node_red_data` volume was kept.

Language decision: staying on C#/.NET. Go was considered (smaller image, single binary) but rejected for now;
a rewrite would not improve behaviour.

## Open items

- `SerialNumberOverride` for the meter is still the sample value `123456789`. It should be the meter's real serial,
which labels its metrics; changing it starts new series.
- Upstream PR: the branch `improve-reliability-and-ui` could be offered upstream (drop the CI image-name change).
- docker0: 54+ pending apt updates and a reboot to load newer kernels (running 5.15.0-176), `grafana/pdc-agent`
runs a 2-year-old `:latest` image, and `docker-compose` v1 is end-of-life (Ubuntu package `docker-compose-v2`).
Unused images still on the host include `grafana/otel-lgtm`, `mongo`, `unifi-network-application`,
`otel/opentelemetry-collector-contrib` and the locally built `unraid_apps_restarter` (not re-pullable).
- `purestorage-health-monitor` on docker0 stopped (exit 0) around 2026-11-10. This was not part of the work above;
check whether it was stopped on purpose.
14 changes: 8 additions & 6 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
# The .NET SDK is broken on arm64, so we have to cross-compile instead.
FROM mcr.microsoft.com/dotnet/sdk:7.0-bullseye-slim-amd64 AS publish
# Build on the native platform and cross-compile for the target architecture.
# This avoids running the .NET SDK under QEMU emulation, which is slow and unreliable on arm64.
# Defaults for the legacy (non-BuildKit) builder; BuildKit/buildx set these automatically.
ARG BUILDPLATFORM=linux/amd64
FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:10.0 AS publish

# Workaround from: https://github.com/dotnet/sdk/issues/28971#issuecomment-1308881150
ARG TARGETARCH
ARG TARGETOS
ARG TARGETARCH=amd64
ARG TARGETOS=linux
RUN arch=$TARGETARCH \
&& if [ "$arch" = "amd64" ]; then arch="x64"; fi \
&& echo $TARGETOS-$arch > /tmp/rid \
Expand All @@ -16,7 +18,7 @@ RUN dotnet restore EnergyExporter.csproj -r $(cat /tmp/rid)
COPY src/EnergyExporter/ .
RUN dotnet publish EnergyExporter.csproj -r $(cat /tmp/rid) -c Release -o /app/publish --no-self-contained --no-restore

FROM mcr.microsoft.com/dotnet/aspnet:7.0
FROM mcr.microsoft.com/dotnet/aspnet:10.0
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "EnergyExporter.dll"]
33 changes: 29 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,16 +47,16 @@ If needed, you can enable extended logging by setting the default log level in `
#### Using Docker

This repository provides Docker images using the GitHub Container Registry to get things running
easily: [Images](https://github.com/users/MarcusWichelmann/packages/container/package/energy-exporter)
easily: [Images](https://github.com/users/jamesvarty/packages/container/package/energy-exporter)

Sample docker-compose.yml:

```yaml
energy-exporter:
image: ghcr.io/marcuswichelmann/energy-exporter:3
image: ghcr.io/jamesvarty/energy-exporter:master
container_name: energy-exporter
ports:
- "14552:80"
- "14552:14552"
volumes:
- /path/to/appsettings.json:/app/appsettings.json
restart: always
Expand All @@ -74,14 +74,39 @@ You can also install the [.NET SDK](https://dotnet.microsoft.com/) on your syste

While the exporter is running and has access to the Modbus TCP interface, it will query all data for the available devices in a regular interval (`IntervalSeconds`).

Now visit the IP address and port (`14552` by default) of the running exporter to see the queried device data.
Now visit the IP address and port (`14552` by default) of the running exporter to open the management UI.

The available URLs are:

- `/`: Management UI showing whether each device is online, its live values, the last error, the state of the
InfluxDB/MQTT exporters and recent events. It also has buttons to poll immediately or force a reconnect.
- `/api/status`: The data behind the management UI as JSON (`POST /api/poll`, `POST /api/reconnect` and
`POST /api/devices/{id}/reconnect` trigger the actions)
- `/metrics`: Prometheus metrics
- `/devices`: REST API (see Swagger documentation)
- `/swagger`: Interactive API documentation

Besides the device values, `/metrics` contains `energy_exporter_device_up`, `energy_exporter_device_polls_total`,
`energy_exporter_device_poll_failures_total` and `energy_exporter_device_poll_duration_seconds` for every configured
device, so you can alert on a device that stopped responding.

Registers that a SunSpec device reports as "not implemented" (e.g. phase 2 and 3 values on a single-phase inverter)
are left out of the metrics, InfluxDB and MQTT, and show up as `null` in the REST API.

### Connection handling

All settings in the `Polling` section are optional:

| Setting | Default | Description |
| --- | --- | --- |
| `IntervalSeconds` | `5` | Time between polls. A poll never overlaps with the previous one. |
| `ConnectTimeoutSeconds` | `5` | How long to wait for the TCP connection to a device. |
| `ReadTimeoutSeconds` | `5` | How long to wait for a single Modbus response. |
| `Retries` | `1` | How often a read on an existing connection is retried with a fresh connection, e.g. after the inverter dropped it. |

When a device stops responding (for example a SolarEdge inverter at night), a single warning is logged and the
device is marked offline in the UI. Further failures are only logged at `Debug` level until the device comes back.

The REST API will export the data in a readable JSON format. If you prefer XML, just set the HTTP `Accept` header to `application/xml` and you will get the response as XML.

## Vendors
Expand Down
102 changes: 102 additions & 0 deletions src/EnergyExporter/Controllers/StatusController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
using System;
using System.Collections.Generic;
using System.Linq;
using EnergyExporter.Modbus;
using EnergyExporter.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace EnergyExporter.Controllers;

/// <summary>
/// Backs the management UI: exporter health, per-device status and simple controls.
/// </summary>
[ApiController]
[Route("api")]
public class StatusController : ControllerBase
{
private readonly DeviceService _deviceService;
private readonly DevicePollingService _pollingService;
private readonly ModbusReaderPool _readerPool;
private readonly StatusEventLog _eventLog;

public StatusController(
DeviceService deviceService,
DevicePollingService pollingService,
ModbusReaderPool readerPool,
StatusEventLog eventLog)
{
_deviceService = deviceService;
_pollingService = pollingService;
_readerPool = readerPool;
_eventLog = eventLog;
}

public record ConnectionInfo(string Endpoint, bool Connected);

public record DeviceStatusDto(DeviceStatus Status, object? LastReading);

public record StatusDto(
string Version,
DateTimeOffset StartedAt,
double PollingIntervalSeconds,
bool IsPolling,
DateTimeOffset? LastPoll,
DateTimeOffset? NextPoll,
IEnumerable<DeviceStatusDto> Devices,
IEnumerable<ConnectionInfo> Connections,
IEnumerable<ExporterStatus> Exporters,
IEnumerable<StatusEvent> Events);

[HttpGet("status")]
public StatusDto GetStatus() =>
new(
typeof(StatusController).Assembly.GetName().Version?.ToString() ?? "unknown",
_pollingService.StartedAt,
_pollingService.Interval.TotalSeconds,
_pollingService.IsPolling,
_deviceService.LastPoll,
_pollingService.NextPoll,
// Cast the reading to object, so polymorphic serialization includes all device properties.
_deviceService.GetStatuses().Select(s => new DeviceStatusDto(s, s.LastReading)),
_readerPool.Readers.Select(r => new ConnectionInfo(r.Endpoint, r.IsConnected)),
_pollingService.ExporterStatuses.OrderBy(e => e.Name),
_eventLog.Recent);

/// <summary>
/// Polls all devices immediately.
/// </summary>
[HttpPost("poll")]
[ProducesResponseType(StatusCodes.Status202Accepted)]
public IActionResult PollNow()
{
_pollingService.PollNow();
return Accepted();
}

/// <summary>
/// Drops the modbus connection of every device; the next poll reconnects.
/// </summary>
[HttpPost("reconnect")]
[ProducesResponseType(StatusCodes.Status202Accepted)]
public IActionResult ReconnectAll()
{
_deviceService.RequestReconnect();
_pollingService.PollNow();
return Accepted();
}

/// <summary>
/// Drops the modbus connection used by one device; the next poll reconnects.
/// </summary>
[HttpPost("devices/{id:int}/reconnect")]
[ProducesResponseType(StatusCodes.Status202Accepted)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IActionResult Reconnect(int id)
{
if (!_deviceService.RequestReconnect(id))
return NotFound();
_pollingService.PollNow();
return Accepted();
}
}
16 changes: 8 additions & 8 deletions src/EnergyExporter/EnergyExporter.csproj
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<LangVersion>11</LangVersion>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="FluentModbus" Version="5.0.2"/>
<PackageReference Include="InfluxDB.Client" Version="4.12.0"/>
<PackageReference Include="Microsoft.Extensions.Hosting.Systemd" Version="7.0.0"/>
<PackageReference Include="MQTTnet" Version="4.2.0.706" />
<PackageReference Include="RecursiveDataAnnotationsValidation" Version="2.0.0"/>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0"/>
<PackageReference Include="FluentModbus" Version="5.3.2" />
<PackageReference Include="InfluxDB.Client" Version="5.1.0" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.14" />
<PackageReference Include="Microsoft.Extensions.Hosting.Systemd" Version="10.0.14" />
<PackageReference Include="MQTTnet" Version="5.2.0.1603" />
<PackageReference Include="RecursiveDataAnnotationsValidation" Version="2.3.3" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="10.3.1" />
</ItemGroup>

</Project>
4 changes: 4 additions & 0 deletions src/EnergyExporter/InfluxDb/InfluxDbExporter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ public InfluxDbExporter(
_influxDbClient = new InfluxDBClient(influxDbOptions.Url, influxDbOptions.Token);
}

public bool Enabled => _influxDbClient != null;

public async Task PushMetricsAsync()
{
if (_influxDbClient == null)
Expand Down Expand Up @@ -75,6 +77,8 @@ private PointData GetDeviceMeasurement(IDevice device, DateTime timestamp)
continue;

object? value = property.GetValue(device);
if (value is double.NaN or float.NaN)
continue; // Not implemented by the device; InfluxDB rejects NaN fields.
if (value != null && value.GetType().IsEnum)
value = value.ToString();

Expand Down
Loading