Decentralized energy sharing network implementing virtual Collective Self-Consumption for Local Energy Communities (LEC). Matches rooftop solar surplus to nearby EV charging load over the public DSO distribution feeder every ~5 seconds, pricing trades at a community mid-rate with micro-cent protocol fees, high-speed time-series integration in QuestDB, and cryptographically verified on-chain settlements.
Rooftop solar and electric vehicle chargers already sit on the exact same low-voltage public feeder. Physics mixes their electrons instantly. Billing, however, is structurally broken:
Unlike theoretical microgrid science-fiction, this platform does not dig private trenches or string rogue wires between rooftops. It operates directly under established Collective Self-Consumption frameworks (EU Renewable Energy Directive RED II, UK Local Energy Markets, Australian Virtual Energy Networks, Swiss LEGs):
PRODUCER (injection only). EV chargers are
strictly registered as CONSUMER (load only). The matcher never allows a device to
synthesize opposite flows.Explore interactive captures of the live Local Energy Community NOC, smart meter telemetry, and Solana settlements.
Citizen landing page presenting the economic model, mid-rate tariffs, and community participation overview.
Real-time geographic map showing active meters, live generation/consumption kW gauges, and peer matching volume.
Tabular overview of provisioned and verified meters, hardware IDs, pure roles (Producer/Consumer), and output status.
High-resolution inspection of a solar meter: Ed25519 public key, NATS channel, live chart, and credit payouts.
Consumer telemetry view showcasing active charging power draw, hardware twin status, and automated debit transactions.
5-second interval settlement audit ledger displaying peer splits, utility residuals, transaction signatures, and SHA-256 proofs.
Participant configuration view linking on-chain Solana public keys, balance monitoring, and automated prepaid credit.
Operator workflow to onboard new hardware: region binding, role selection (Producer vs Consumer), and GPS coordinate pinning.
Hardware editing form to update display labels, coordinates, wallet addresses, and staff verification state.
Role-based login portal securing administrative controls, staff meter verifications, and user audit trails.
Registration portal allowing neighborhood residents to create accounts and join virtual Local Energy Communities.
The system separates high-frequency physical telemetry from financial settlement. Watts stream into a persistent time-series engine, while 5-second window settlements and cryptographic proofs anchor onto the Solana ledger.
+----------------------------------------------------------------------------------------------------+
| PHYSICAL ASSETS and EDGE TELEMETRY LAYER |
| [Rooftop PV Meter] [EV Charger Load Meter] [Lab Modbus TCP Meter HR0-3] |
| (Ed25519 Private Key) (Ed25519 Private Key) (Multi-Meter Python Bridge / ESP32) |
+----------------------------------------------------------------------------------------------------+
│
Ed25519 Signed Canonical Envelopes
telemetry.energy.{region_id}.{meter_id}
│
+----------------------------------------------------------------------------------------------------+
| EVENT BUS and INGESTION PIPELINE (NATS JetStream) |
| Stream: telemetry_stream | Subject: telemetry.energy.*.* | Durable Consumer: questdb_ingestors |
| - Drops unverified serials and role mismatches (PRODUCER cannot draw, CONSUMER cannot inject) |
+----------------------------------------------------------------------------------------------------+
│ │
ILP Stream │ EventSource │ Auth Ticket Check
Port 9009 │ Port 8001 │
+-----------------------------------+ +--------------------------------------------------+
| TIME-SERIES ENGINE (QuestDB) | | SSE GATEWAY (services/sse_gateway) |
| - High-freq sample ingestion | | - Live push of real-time watts to browser |
| - Symbols: meter_id, region, role | | - Zero credentials exposed in frontend |
| - Columns: kw_generated, kw_cons | +--------------------------------------------------+
+-----------------------------------+ │
│ │
Window Integral Queries │
(kWh += kW * dt / 3600) +------------------------------------------+
│ | WEB CLIENT and OPERATOR NOC |
│ | - Leaflet/MapLibre Neighborhood Map |
+----------------------------------------------------+ | - Real-time generation / consumption SVG |
| SETTLEMENT DAEMON (Every ~5s per Region) | | - Meter provisioning and staff verify |
| 1. Reads unpaid energy past settlement cursor | | - Payout audit log and interval proofs |
| 2. Greedy matching: Hungry EV loads first | +------------------------------------------+
| 3. Haversine distance ranking (within 8km radius) | │
| 4. Canonical SHA-256 Interval Energy Proof | │ Django ORM
| 5. Dual Ledger Execution: | │
| - Emulator: Redis balances and split payout | │
| - Live Solana: SPL transfer_checked + Anchor | +------------------------------------------+
| 6. Residual clearing: FiT export and Retail import |──-───| RELATIONAL STORE (PostgreSQL) |
+----------------------------------------------------+ | - SmartMeter registry and credentials |
| - Regions, Currencies and Tariffs |
| - EnergyTrades and OnChainPayouts |
+------------------------------------------+
| Service / Container | Protocol / Port | Core Responsibility | Scaling and Reliability Strategy |
|---|---|---|---|
| web | HTTP 8000 (ASGI) | Django 5 ASGI + Uvicorn: admin, authentication, hardware provisioning, Leaflet NOC, payouts log. | Horizontal stateless replicas behind Nginx load balancer; PostgreSQL connection pooling. |
| sse_gateway | HTTP 8001 (SSE) | Standalone ASGI EventSource server streaming live meter readings directly to the browser. | Subscribes to NATS; validates short-lived Django auth tickets; zero NATS credentials in client. |
| nats | TCP 4222 / 8222 | NATS JetStream 2.10 message bus buffering encrypted telemetry subjects
(telemetry.energy.*.*). |
File-backed persistent stream telemetry_stream; handles broker reboots with zero lost
samples. |
| telemetry_ingestion | Internal Worker | Asyncio JetStream subscriber verifying Ed25519 signatures and pushing Influx Line Protocol (ILP) rows. | Durable consumer questdb_ingestors; auto-scaled via KEDA based on JetStream queue lag.
|
| questdb | TCP 9009 (ILP), 9000 (SQL) | Columnar time-series store ingesting sub-second watts and calculating rectangle window integrals. | High-throughput memory-mapped append log; native SQL window queries partitioned by day. |
| settlement_worker | Internal Daemon | 5-second matching daemon: pulls new kWh, runs greedy nearest-neighbor matching, signs payouts. | Redis distributed locks (settle_lock:region:{slug}) preventing duplicate payout
execution. |
| redis | TCP 6379 | Low-latency cache for meter metadata, settlement cursors, locks, and lab token ledger emulator. | In-memory key-value store with AOF persistence; sub-millisecond cursor updates. |
| modbus_bridge | TCP 1502 / Host | Multi-meter Python gateway polling Modbus TCP holding registers (HR0-3) and publishing signed envelopes. | Translates industrial physical meter registers into JSON Ed25519 envelopes on field gateways. |
Explore the primary algorithms powering the platform: Ed25519 signature enforcement, strict role physical sanitization, time-weighted rectangle energy integration, greedy nearest-neighbor matching, and canonical SHA-256 proofs.
def canonical_payload_bytes(payload: dict) -> bytes:
# Deterministic sorting ensures signature matches across devices
return json.dumps(payload, sort_keys=True).encode("utf-8")
def verify_envelope(payload: dict, sig_str: str, pubkey_str: str) -> bool:
try:
signature = Signature.from_string(str(sig_str or ""))
pubkey = Pubkey.from_string(str(pubkey_str or ""))
return signature.verify(pubkey, canonical_payload_bytes(payload))
except Exception:
return False
def power_columns_for_role(role: str, payload: dict) -> tuple[float, float]:
"""Persist only the physical flow matching verified hardware role."""
gen = max(0.0, float(payload.get("kw_generated") or 0))
con = max(0.0, float(payload.get("kw_consumed") or 0))
if role == "CONSUMER":
return 0.0, con # Consumer cannot inject watts
return gen, 0.0 # Producer cannot consume watts
def calculate_unpaid_kwh(samples: list[tuple], max_gap_sec: float = 30.0) -> Decimal:
"""Integrate power over time (rectangle rule).
Caps sample gaps to prevent offline meters from claiming false energy.
"""
total_kwh = Decimal("0.0")
if len(samples) < 2:
return total_kwh
for i in range(1, len(samples)):
ts_prev, kw_prev = samples[i - 1]
ts_curr, kw_curr = samples[i]
dt = (ts_curr - ts_prev).total_seconds()
if 0 < dt <= max_gap_sec:
# Energy = Average Power (kW) * Time (hours)
avg_kw = Decimal(str((kw_prev + kw_curr) / 2.0))
kwh = avg_kw * (Decimal(str(dt)) / Decimal("3600.0"))
total_kwh += kwh
return total_kwh
def match_local_energy(offers: list[EnergyOffer], radius_m: float = 8000.0) -> list[EnergyFill]:
producers = [o for o in offers if o.role == "PRODUCER" and o.remaining > 0]
consumers = [o for o in offers if o.role == "CONSUMER" and o.remaining > 0]
consumers.sort(key=lambda c: c.remaining, reverse=True) # Hungry chargers first
fills = []
for consumer in consumers:
if consumer.remaining <= 0:
continue
# Rank producers by Haversine distance if coordinates exist
eligible = []
for prod in producers:
if prod.remaining <= 0:
continue
dist = haversine_m(consumer.lat, consumer.lng, prod.lat, prod.lng) if consumer.lat and prod.lat else 0.0
if radius_m is None or dist <= radius_m:
eligible.append((dist, prod))
eligible.sort(key=lambda x: x[0])
for dist, prod in eligible:
fill_kwh = min(consumer.remaining, prod.remaining)
consumer.remaining -= fill_kwh
prod.remaining -= fill_kwh
fills.append(build_fill(prod, consumer, fill_kwh, dist))
return fills
def energy_proof_hash(prod_id: str, cons_id: str, kwh: Decimal, start: str, end: str) -> str:
"""Canonical SHA-256 of matched interval bound to on-chain payment."""
canonical_json = json.dumps({
"consumer": str(cons_id),
"interval_end": str(end),
"interval_start": str(start),
"kwh": format(kwh, "f"),
"producer": str(prod_id),
}, separators=(",", ":"), sort_keys=True)
return hashlib.sha256(canonical_json.encode("utf-8")).hexdigest()
def execute_split_payout(consumer_wallet: str, producer_wallet: str, mid_rate_amount: Decimal, fee: Decimal):
# Consumer wallet executes transfer split: producer receives mid-rate, treasury receives 0.1¢ fee
return transfer_token_split(
source=consumer_wallet,
dest_producer=producer_wallet,
amount_producer=mid_rate_amount,
dest_treasury=TREASURY_PUBKEY,
amount_treasury=fee
)