# push (client certificate):
git remote set-url --push origin https://coredump.ws:8443/repos/solar-relay.git
Branches and tags
Files at HEAD (3ee6f8e7cd) · download zip
| .gitignore | 184 B |
| config.example.h | 1.1 KB |
| LICENSE | 34.3 KB |
| README.md | 17.0 KB |
| relay.ino | 74.3 KB |
Recent commits · all
| 3ee6f8e7 | Add HAS_SOLAR for sites without solar panels | no-body-in-particular | 25 days ago |
| c4564302 | Point the forecast at the shed roof: 39 degrees tilt, 16 degrees east of south | no-body-in-particular | 25 days ago |
| a50b7ba1 | Stop the charger cycling: detect full at the end voltage, steady the solar rule | no-body-in-particular | 25 days ago |
| 7f64002b | Prefer the home network over phone hotspots; keep the radio awake | no-body-in-particular | 25 days ago |
| dc5145f5 | Hear the Shine stick over ESP-NOW as well as UDP | no-body-in-particular | 25 days ago |
| c1bce3a6 | Charge on low battery only after a sustained drop, and for 30 minutes | no-body-in-particular | 25 days ago |
| 8d9e17e4 | License under GPL-3.0-or-later | no-body-in-particular | 27 days ago |
| d9765e45 | Plan charging so the battery stays above a floor until the cheap slots | no-body-in-particular | 2026-10-09 |
| 2dcf6a10 | Use the solar forecast until the inverter is heard | no-body-in-particular | 2026-10-08 |
| 5dac7dd9 | Drop the DinMeter's own clamp; solar comes from the inverter | no-body-in-particular | 2026-10-08 |
README.md
solar-relay
Charges a 28 V battery bank when it is cheapest, on an M5Stack DinMeter.
The DinMeter switches the battery charger with a relay. It decides when from three things:
- the dynamic electricity price per 15 minutes, from stroomperuur.nl;
- the solar forecast per 15 minutes, from Open-Meteo;
- the solar power the inverter is producing right now, read from the inverter itself by a reflashed Growatt ShineWiFi-X stick (see
shine-stick), or else from a Bluetooth clamp meter.
The two solar inputs are optional: with HAS_SOLAR 0 in config.h, for a site without panels, it plans on prices alone (see Without solar panels).
It learns how much charging a day needs, and how much power your panels give per unit of forecast sunlight. It shows its state on the DinMeter's screen. Readings and a log go to a CTracker server, so you can follow it from anywhere.
Hardware
| Part | Notes |
|---|---|
| M5Stack DinMeter (ESP32-S3) | 2.4 GHz WiFi only. |
| Relay on G1 | Switches the battery charger's mains supply. High = charger on. |
| Battery voltage divider on G2 | 27 kΩ from battery + to G2, 1.5 kΩ from G2 to ground (ratio 1:19). Optionally 100 nF across the 1.5 kΩ. The DinMeter's ground must be the battery's minus. |
| Battery | Written for a 28 V LTO bank (10 cells, 2.8 V each when full) with a 28 V / 45 A charger. |
The battery voltage is read with the ESP32's calibrated analogReadMilliVolts. The divider puts 28 V at 1.47 V on the pin, well inside the ADC's linear range.
How the relay decides
Checked in this order, every pass of the loop:
- USB override.
relay on,relay offorrelay autoover the serial port; see Serial commands. - Forced on. Turn the encoder to toggle. The screen confirms with "Force on : On/Off".
- Low battery. Only a sustained drop counts: below
MIN_BATT_VOLTAGE(20 V) for 15 minutes without a break (LOW_BATT_HOLD_MS). Boiling water can pull the voltage under for 10–15 minutes and then recover. Then the charger runs for 30 minutes (LOW_BATT_CHARGE_MS), not to full, and the plan takes over again. It keeps running those 30 minutes even though charging lifts the voltage over the limit straight away. - Full. The battery is full when the charger has brought it to its end voltage and it has stopped rising there: at least
BATT_FULL_MIN_V(27.5 V) under charge, and less than 0.05 V higher than 5 minutes earlier. Below that, only a voltage that has been flat for a whole hour counts (a hot battery or a heavy load can keep it lower). Voltages are compared as 1-minute means, and the first 2 minutes after switch-on are ignored, because the voltage jumps.
With the charger on, the voltage reads about 2 V above rest. Mid-charge it creeps up only 0.01–0.02 V a minute with ±0.1 V of jitter, so the old test (no 0.01 V rise in 5 minutes) called the battery full at around 23.4 V and stopped almost every charge early. Real fulls level off at 27.9–28.0 V.
Charging is allowed again once the voltage has stayed 0.8 V below where it settled 10 minutes after the full (charger off) for 5 minutes, and at least 30 minutes after it got full. Measured from the under-charge voltage instead, the 2 V the charger adds counted as a drop the moment it stopped.
- Planned. The current quarter is one the plan picked; see Planning.
- Solar. The solar power (measured by the inverter, or else expected by the forecast; see Where solar power comes from) is
SOLAR_ON_W(960 W) or more. The rule looks at a smoothed figure (3-minute time constant), switches off again only belowSOLAR_OFF_W(800 W), and once switched stays on for at least 10 minutes or off for at least 5, so passing clouds don't make it chatter. With neither a measurement nor a forecast, or withHAS_SOLAR 0, this rule does nothing.
The screen shows which rule decided, for example Relay: On plan.
Planning
Every quarter is priced as price per kWh × the share of the charger's power that must come from the grid. The grid share is the charger's power from the wall (CHARGE_POWER_W, 1100 W here) minus the solar expected in that quarter, never below zero. Expected solar is the forecast irradiance × the learned power factor. Negative-price quarters keep their negative cost and are always picked.
- The window runs from now to the end of the last day with known prices. Tomorrow's prices are published after 13:00, so in the afternoon and evening tonight is weighed against tomorrow's midday.
- How many quarters, and which: once a charge has run to full, the planner knows the battery: its resting voltage, how many quarters of charging a volt takes, what full rests at, and the daily use. It then follows the battery's charge through the whole window, in quarters of charging above a floor of 20.5 V (
PLAN_FLOOR_V). Each planned quarter adds one; each quarter of time takes the daily use ÷ 96; it can't go above full. - Cheapest quarters first. Each is kept only if it still adds charge at the end of the window; one that a later full battery would swallow is no use. It stops once the window ends with 12 hours of use in hand, or full. A quarter that would start a new block counts
PLAN_BLOCK_START_COST(0.03 per kWh) dearer than one that extends a block, so nearly equal prices give one longer run instead of the charger switching on and off every few quarters. - Then the floor. Wherever the charge would still drop below the floor before then, the cheapest quarter before that point is added. A cheap stretch tomorrow can't leave the battery flat tonight; it gets just enough tonight to bridge the gap.
Until the first full charge has been learned from, and for 15 minutes after a restart (the resting voltage needs the charger off that long), it uses the learned daily need instead, plus 25% and two quarters, scaled to the window's length.
- When it replans: every quarter, when new prices come in, and when the forecast is refreshed (every 3 hours).
- Without prices (no WiFi, or before the first fetch), it falls back to charging from 13:00 for
NUM_CHARGE_HOURS.
Without solar panels
Set HAS_SOLAR 0 in config.h. The planner then counts every quarter at its full price per kWh, so it picks the cheapest quarters, with the same floor, block cost and learned charge need as above. Nothing about the sun is fetched or used:
- no forecast is requested, and
SOLAR_LATandSOLAR_LONcan be left out; - the inverter's Shine stick and the Bluetooth clamp aren't listened for;
- the solar rule never switches the charger, and no power factor is learned;
- the screen shows
Sun:-,Solar: no panelsandNeed …hinstead ofPV …W need …h; the status log sayssolar none (no panels).
A config.h without HAS_SOLAR counts as having panels, so existing setups keep working unchanged.
Prices come from https://www.stroomperuur.nl/ajax/tarieven.php?leverancier=17&kwartier=1&datum=YYYY-MM-DD. The total per quarter is the market price, plus energy tax and VAT, plus the supplier's purchase fee. leverancier picks the supplier whose fee is added. On the two daylight-saving days the site returns 93 or 95 values; each is placed by its real time.
The forecast is Open-Meteo's global_tilted_irradiance per 15 minutes, for the panel tilt and azimuth set in relay.ino. Each value is the mean of the 15 minutes before its timestamp.
What it learns
Both values are kept in flash (NVS namespace relay) and survive restarts and uploads.
- Charge per volt (
q_per_volt,soc_samples) and full resting voltage (full_rest_v). Once the charger has been off for 15 minutes, the battery voltage counts as its resting voltage. That's a fair measure of charge for LTO, whose voltage climbs steadily with it. - Each charge that runs to full records the resting voltage it started from and the quarters it took. That teaches how many quarters one volt takes.
- Half an hour after each full, the resting voltage shows what full looks like at rest. It starts at a guess of 24.5 V, which is where the battery rested half an hour after the real fulls of 10 and 11 October.
- The values learned before the full detection was fixed (full resting at 22 V, 2.9 quarters per volt) came from false fulls. They are cleared once, on the first start of this version (
soc_basisin NVS), and the daily average is used until a real full has been learned from. - The battery's current need is then (full resting voltage − current resting voltage) × quarters per volt, minus whatever has been charged since that reading.
- The screen shows it as
need …h. While it's still the daily average, it shows asneed ~…h. - Daily charging need (
charge_need, in quarters), used until the above has been learned. At midnight it moves 30% of the way towards what the day actually charged until full. A day that ended without getting full counts as needing an hour more. It starts at 4 hours. - Power factor (
pv_factor, shown asPV …W). This is the watts your panels give at 1000 W/m² of forecast irradiance, about your system's effective peak. It is a least-squares fit through zero of measured watts against forecast irradiance, over roughly the last 150 usable quarters (older ones fade out): Σ(measured × forecast) ÷ Σ(forecast²). Bright quarters, the ones that decide whether the charger runs on sun, weigh most. Averaging single-quarter ratios, as before, overshot whenever a cloudy forecast turned out sunny. - A quarter is used when it had at least 100 W/m² forecast and the inverter was heard for at least 75% of it. Its mean is time-weighted, so it matches the forecast's mean over the quarter.
- At boot, the stored factor counts as about 8 bright quarters, so a restart doesn't throw away what it knew. It starts at 2000 W and is saved at most once an hour.
- Shape check: at midnight the log gets a
solar fitline: measured ÷ expected for the morning, midday and afternoon, and whether the forecast matches better shifted in time (e.g.forecast runs 45 min late). One factor can only scale the forecast. If mornings come out low and afternoons high (or the other way round), or the best match is shifted, checkPANEL_AZIMUTHandPANEL_TILTagainst the panels' real direction. They are set from the shed roof's laser-measured model in the 3D BAG: 39° tilt, 16° east of south (-16). Mornings still come out low (0.5 of the forecast early on 14 October): the house just east of the shed shades the panels until the sun is higher. That is shade, not direction, so don't turn the azimuth west to make up for it.
The screen
WiFi:Y Price:Y Sun:Y connected / today's prices / forecast in
Err: None last fetch error, if any
Time: 14:03:27
Next: 13:15-15:30 next planned block ("tm" = tomorrow)
Relay: On plan relay state and the rule that decided
Bat 26.41V full battery voltage, "full" once detected
Solar: 1240W (inv) solar power, and where it came from: "inv" or "fcst"
PV 2150W need 4.5h power factor and learned daily need
Controls
| Action | Effect |
|---|---|
| Turn the encoder | Toggle forced on |
| Hold the button 5 s | Save the power factor and power off |
Remote logging and chart
The device reports to a CTracker server (LOG_HOST, port 9000) using its plain-text "basic" phone protocol, under the made-up IMEI in config.h. Add that IMEI to your account on the tracker's website.
Every minute it sends:
BASIC;<imei>;<battery %>;;<macs>!first. The server recognises the protocol by this message. Every 10 minutes it includes a WiFi scan, so the map can place the device. Phone hotspots, which have random MACs, are left out.STAT;<imei>;<name>;<value>!forbattery_volts,solar_w,charging(0/1) andplanned(0/1), all under "Other" on the chart. Alsobattery_level(20 V = 0%, 28 V = 100%), under "Device".LOG;<imei>;<text>!for queued log lines, which appear under "Server logging":- startup;
- a status line every 5 minutes (solar power and its source, battery, relay, WiFi);
plan:lines with each block's average price and expected sun, when the plan changes and at least hourly;- battery full and resume;
- the midnight learning result and the
solar fitline; - fetch errors.
It also sends EVENT;<imei>;<text>! for the tracker's Events list, for things worth seeing at a glance:
- the charging plan, whenever a quarter is added to it or dropped from it (not when a planned quarter merely passes);
- battery full;
- charging allowed again.
This needs a CTracker server with EVENT support in its basic protocol. An older server just puts them in its log as unknown messages.
The server takes one message per pass of its loop (about 100 ms) and discards whatever is unprocessed once the connection closes. So messages are sent 150 ms apart, and each connection is closed half a second after its last message. At most 20 log lines go per connection; the rest wait for the next minute.
The tracker protocol has no authentication: anyone who knows the IMEI can send data under it.
WiFi and lost internet
At startup, and whenever it's offline, the device scans and joins the strongest network from WIFI_NETWORKS that's in range. It joins that exact access point, so a router and its extender with the same name are told apart.
Being connected isn't the same as being online, so every request that gets through (tracker, prices, forecast) counts as proof that the network works:
- Dead network: after 5 minutes without any, the device logs a diagnosis. That covers the network, signal, IP, gateway and DNS servers, and whether the DNS lookup or the TCP connection is what fails. It then drops the network for 30 minutes and joins the next one. It retries every 15 seconds. If everything in range is blocked, it uses the strongest anyway.
- Spare DNS: 1.1.1.1 is set as fallback DNS, for networks whose own DNS fails.
- Last resort: after an hour without internet on any network, it restarts. The learned values are in flash.
- While offline: log lines are kept in a 4 KB buffer and delivered when it's back. When the buffer is full the oldest lines go first. Readings for the chart aren't kept.
Serial commands
Over USB at 115200 baud, one command per line:
| Command | Effect |
|---|---|
relay on / relay off | Override the relay |
relay auto | Back to normal operation |
adc | Battery voltage over one second, and the current solar power and its source |
net | Test the connection now: network, IP, DNS lookup of the tracker, TCP to its port |
wifi <n> / wifi auto | Use only network n from config.h (0 = first), or any of them again |
Configuration
- Copy
config.example.htoconfig.hand fill in: WIFI_NETWORKS(2.4 GHz only; names must match exactly, including trailing spaces);HAS_SOLAR: 1 with solar panels, 0 without (prices only);SOLAR_LATandSOLAR_LON(only with panels);LOG_IMEI.
config.h is in .gitignore.
- Check the settings at the top of
relay.ino: - pins;
SOLAR_ON_WandSOLAR_OFF_W;CHARGE_POWER_W;- the divider resistors;
PANEL_TILTandPANEL_AZIMUTH(0 = south, −90 = east, 90 = west).- Calibrate the battery voltage: measure the battery with a multimeter while reading
Baton the screen. SetBATT_CALIBRATIONto multimeter ÷ screen, times its current value.
Building
Arduino core esp32 3.3.x, with the libraries M5DinMeter, M5Unified, M5GFX and ArduinoJson 7.
arduino-cli compile --upload -p COM8 --fqbn esp32:esp32:m5stack_dinmeter:PartitionScheme=huge_app relay
Replace COM8 with your port. The "Huge APP" layout is required: with Bluetooth the build is about 1.5 MB, too big for the default layout. The settings area stays where it was, so learned values survive switching.
Where solar power comes from
The DinMeter has no clamp of its own. The first of these that's available is used:
- The inverter itself (shown as
(inv)on the screen). A Growatt ShineWiFi-X stick running theshine-stickfirmware broadcastsGW … pac=<W> … src=shineover UDP port 47800 every 5 seconds. A reading counts as fresh for 30 seconds. It's only heard while the DinMeter is on the same network as the stick. - The forecast (
(fcst)): this quarter's forecast irradiance × the power factor. - A Bluetooth "SolarClamp" clamp meter (
(BT), manufacturer dataFF FF 'S' 'C' <W lo> <W hi> <seq>) can go before the forecast again by settingUSE_BT_CLAMP 1. It's off by default: clamps proved unreliable, and without it the DinMeter doesn't scan Bluetooth at all.
Only measured watts (the inverter, or the clamp meter if enabled) teach the power factor and are charted as solar_w. Learning from the forecast would only compare it with itself. The forecast's expectation is charted separately as solar_fcst_w. With neither a measurement nor a forecast, solar is unknown, and the charger isn't run on solar.
The 5-minute status line in the log says which source is in use.
License
GPL-3.0-or-later, see LICENSE.