DEV Community

Cover image for Agentic engineering a smart home energy system with Antigravity and Gemini 4
Remigiusz Samborski for Google AI

Posted on Originally published at x.com

Agentic engineering a smart home energy system with Antigravity and Gemini 4

Running rooftop solar, a home battery, two electric vehicles (EVs), and dynamic hourly electricity tariffs requires tight coordination. Without automation, these systems work against each other.

At home, I run dual east/west solar panels feeding a hybrid inverter with a 10 kWh battery, alongside a plug-in hybrid, an EV, and dynamic tariffs from my electricity provider. On sunny days, you should never buy grid power when solar can charge the battery for free. On dark, cloudy days, you want to buy grid power only during the cheapest hourly windows. Moreover, if you charge the home battery from the grid before plugging in an EV, the car drains your charged home battery right away.

Last weekend, in a couple of hours of hands-on work starting Saturday evening, I engineered cheap-watts to automate this workflow and open-sourced it on GitHub, complete with a full offline unit test suite across more than 25 commits.

The best part? I almost never touched the code myself.

By pairing Gemini 4 Hydrogen and Gemini 4 Carbon inside Google Antigravity, I practiced agentic engineering and stayed focused on high-level architecture. Here are the three main takeaways from the weekend build:

  • Dual-model workflow. Use Gemini 4 Hydrogen for fast interactive specs and Gemini 4 Carbon for multi-file coding and testing.
  • Clean hardware abstractions. Isolate physical inverter and vehicle APIs behind interfaces so hardware surprises take one commit to fix.
  • Automated safety gates. Pair secret scanning, pull request (PR) checks, and a --dry-run flag so agents move fast without risking live keys or hardware.

Split the workflow: Gemini 4 Hydrogen for specs, Gemini 4 Carbon for code

Most developers rely on one AI model for every task. Either you wait on a heavy reasoning model while bouncing early ideas back and forth, or you ask a fast model to handle multi-file refactors where edge cases slip through.

Inside Antigravity, I split my workflow across two models based on what each does best:

  • Gemini 4 Hydrogen for brainstorming and requirements. Early architecture work is a fast conversation. You test assumptions, weigh trade-offs, and define edge cases. Hydrogen responds fast and uses quota well, which fits interactive discovery. On Saturday evening, before generating a single .py file, I worked with Hydrogen to draft three planning files under docs/planning/. I created an Architecture Decision Record (adr-001-initial-architecture.md), a five-phase execution plan (execution-plan.md), and a task backlog (tasks.md).
  • Gemini 4 Carbon for coding. Once the specs were ready, I switched to Carbon for implementation. Carbon is built for long-horizon software engineering. I pointed it at a phase in tasks.md and ADR-001. Carbon scaffolded the modules, wrote binary protocol bitmasks, generated offline JSON fixtures, and ran pytest until every test passed.

This split changed how I spent my weekend. Instead of debugging OAuth token rotation or counting Modbus register offsets by hand, I worked as the system architect. I defined rules, tested hardware connectivity on my local network, and reviewed PRs.

Inside the cheap-watts system architecture

Architecture diagram: solar forecasts, dynamic tariffs, and battery and EV state of charge feed a 30-minute planner that updates the inverter over local LAN Modbus and emails EV charging windows.

During Saturday's brainstorming session with Gemini 4 Hydrogen, I ruled out building a web dashboard. Dashboards add frontend maintenance for a service that should run unattended in the background.

Instead, I designed cheap-watts as a headless Python 3.12 command-line interface (CLI) managed with uv and triggered every 30 minutes via cron. Running 48 times per day keeps the planner responsive to weather shifts and plugged-in cars while staying under the vehicle telematics API's 50 requests/day quota per account.

Reviewing the git history from Saturday night through Tuesday highlights four key architecture decisions.

Pivot from cloud APIs to local LAN Modbus

In Phase 2 on Saturday evening, Gemini 4 Carbon built read-only clients for electricity provider tariffs, Open-Meteo solar forecasts, vehicle telematics, and the inverter vendor's cloud API. The solar forecast client supports dual east (-90°) and west (90°) roof planes without requiring an API key. Right after that, I added a read-only cheap-watts probe CLI command to test live credentials.

Running probe on Sunday exposed my first hardware constraint. My inverter's Wi-Fi stick logger connects to a third-party mobile app rather than the inverter manufacturer's cloud. That platform lacked self-service developer keys and public charging schedule write endpoints.

Because I had isolated inverter operations behind a Python Protocol (InverterClient), pivoting took a single commit. I asked Gemini 4 Carbon to build a local LAN adapter behind that same protocol. Carbon implemented a Modbus-over-TCP client over local port 8899. It reads live registers and writes the inverter's 6-slot charging schedule while keeping weekday and generator bitmasks intact. Local LAN control removed cloud rate limits, required zero external API keys, and left the mobile app untouched.

Solar-first battery math and post-EV ordering

Decision flowchart for each 30-minute cron run: sunny forecasts turn grid charging off for free solar and slow EV charging, while low-sun forecasts schedule the EV window first before locked cheap grid battery charging.

Coordinating a home battery with two EVs requires clear ordering rules in src/engine/planner.py:

  • Sunny forecast. cheap-watts turns grid-charging OFF for the whole day, so rooftop solar fills the battery for free. If a car has low charge, it emails me a reminder to plug it in for a slow daytime charge using excess solar.
  • Cloudy forecast (low sun). The planner calculates the grid deficit needed to cover typical daily usage plus a configurable buffer. It then turns grid-charging ON to meet that deficit during the cheapest tariff hours.
  • Vehicles first, battery second. Vehicle state of charge comes from the car manufacturer's telematics API, authorized once via an interactive OAuth 2.0 Device Code CLI flow. When the EV or plug-in hybrid is charging or needs a charging window, cheap-watts blocks those hours from inverter grid-charging. It schedules the cheapest battery charging windows after the vehicle window ends, so the car charger doesn't immediately drain grid-bought kWhs from the home battery.

Prevent mid-charge churn with a sticky daily charging plan

Once the pipeline ran every 30 minutes on live feeds, a subtle stateful scheduling bug appeared.

Suppose the electricity provider publishes next-day prices and cheap-watts schedules battery grid-charging from 02:00 to 04:00. At 02:30, cron runs again. Because the battery now holds more charge, a stateless planner calculates a smaller deficit and rewrites the active charging plan mid-charge. Rolling the 24-hour lookahead forward also risked 25-hour wrap collisions on the inverter's 6-slot 00:00..24:00 schedule ring.

I described this symptom to Antigravity without editing planner.py. Gemini 4 Carbon added a sticky schedule guard, locking the daily charging plan to the electricity provider's active day-ahead tariff horizon. The schedule stays locked across 30-minute runs and unlocks early only if:

  • An EV plugs in or creates a charging conflict (ev_conflict_override).
  • The electricity provider publishes a new day-ahead price horizon (new_tariff_horizon).
  • The weather forecast flips between sunny and low-sun regimes (solar_regime_changed).

Signal-only alerts and resilient mini PC deployment

Nobody wants 48 status emails per day. cheap-watts stores its last applied schedule and alert timestamps in data/state.json. It sends SMTP emails only when the battery charging plan changes or a new EV recommendation triggers outside a 12-hour cooldown.

For deployment on my home mini PC, I worked with Gemini 4 Hydrogen to compare local uv runs against GitHub Container Registry (ghcr.io). I chose ghcr.io with a decoupled crontab setup:

# Run optimization every 30 minutes using the cached local image:
*/30 * * * * docker run --rm --network host --env-file /opt/cheap-watts/.env -v /opt/cheap-watts/data:/app/data -v /opt/cheap-watts/logs:/app/logs ghcr.io/rsamborski/cheap-watts:latest run >> /opt/cheap-watts/logs/cron.log 2>&1

# Pull image updates on a separate hourly schedule:
15 * * * * docker pull --quiet ghcr.io/rsamborski/cheap-watts:latest >> /opt/cheap-watts/logs/cron.log 2>&1
Enter fullscreen mode Exit fullscreen mode

Separating docker pull from docker run ensures a temporary internet or GitHub outage never blocks local LAN Modbus control of the inverter.

Keep agentic engineering safe with the romin-security skill and PR gates

Pipeline diagram: an Agent PR passes five automated checks (romin-security, Gitleaks, Ruff and Black, Pytest over 90% coverage, and Docker smoke test) before publishing a container image to GitHub Container Registry for the mini PC.

Letting an AI coding agent move fast in a repository with utility API tokens, vehicle OAuth credentials, and physical inverter registers carries real risk. One bad commit to a public GitHub repository can expose live keys to automated scanners within seconds.

Before writing a single line of application code on Saturday evening, I ran the romin-security skill, codified by Riccardo Carlesso based on Romin Irani's security guide. Designed to prevent secret leaks during fast agentic builds, the skill protected the repository from the start:

  • Zero hardcoded secrets. All credentials load from .env (left blank in .env.example) and wrap in Pydantic SecretStr fields so keys never appear in stack traces or logs. Rotated vehicle OAuth refresh tokens use 0600 file permissions.
  • Custom Gitleaks rules. I added .gitleaks.toml with custom patterns, including sk- personal API tokens from the electricity provider. Gitleaks runs in local pre-commit hooks and in GitHub Actions with fetch-depth: 0 to scan the full commit history.
  • Least-privilege CI and open-source scrub. Every continuous integration (CI) workflow sets permissions: {} and pins third-party actions to full commit SHAs. Before opening the repository to the public I scrubbed personal data, generalized vehicle settings, and added SECURITY.md.

Enforce quality with an AGENTS.md file and protected PRs

Once the core engine worked, I protected the main branch on GitHub and codified agent rules in AGENTS.md. Neither I nor Antigravity can push straight to main. Every bug fix, refactor, or feature uses a branch and must pass five PR gates before merge:

  • Gitleaks: Scans the full commit history for secrets.
  • Ruff: Runs static Python linting.
  • Black: Verifies consistent code formatting.
  • Pytest: Runs the offline fixture suite and enforces > 90% branch coverage (fail_under = 90 in pyproject.toml).
  • Docker build and CLI smoke test: Verifies the container image starts cleanly before merges publish :latest to ghcr.io.

These gates keep Gemini 4 Carbon in check during autonomous runs. When a change drops test coverage below 90% or trips a linter rule, pre-commit and CI block the merge. The agent fixes the failure on its own before I review the PR.

Real-world testing: Move from the dry-run flag to production

Unit tests check math, not live weather forecasts or inverter firmware quirks. Because cheap-watts writes Modbus holding registers to a 10 kW grid-tied hybrid inverter, I built --dry-run as a strict hardware safety gate from the start.

In --dry-run mode, the container queries all live inputs: electricity provider tariffs, dual-string solar forecasts, vehicle telemetry, and local inverter Modbus registers. It runs the full planner, skips every Modbus write call, and prefixes change emails with [DRY-RUN].

Before going live, I ran cheap-watts in --dry-run mode on my mini PC for several days and monitored its [DRY-RUN] alerts. So far, every decision was accurate, from recommending the cheapest vehicle charging windows to sizing battery grid-charging right after the cars finished. Each time an alert arrived, I verified the plan and applied those exact settings by hand.

After that testing period, I dropped --dry-run from crontab and switched cheap-watts to production mode. Whenever I ship a major update, I turn --dry-run back on first to verify nothing broke before re-enabling live inverter writes.

Next steps

Ready to explore the project or try an agentic engineering workflow on your next weekend build? Here is where to go next:

Connect with me

I'm always curious how others are using agentic engineering in their projects. Share your setups and questions with me on social media:

Top comments (0)