REAL CODE
All code below is taken directly from the repositories. These are actual parts of the 9-repo codebase.
Backend API
EVSE Firmware
Hodet Security
Yocto BSP
Dashboard UI
Test Infrastructure
backend-api/ Project Structure
src/
├── api/ — REST endpoint definitions
├── application/ — CQRS command/query handlers
├── config/ — environment, settings
├── core/ — event bus, circuit breaker, saga
├── domain/ — entities, value objects, services
└── infrastructure/ — repos, adapters, external
routers/ — 32 router files
├── auth.py, chargers.py, evse.py
├── ocpp.py, iso15118.py, iso15118_v2.py
├── ota.py, ota_v2.py, payments.py
├── pqc.py, sentinel.py, hodet.py
├── smart_charging.py, load_balancing.py
├── metrics.py, notifications.py, ocpi.py
└── admin/ — 11 admin routers
services/ — 20 service files
├── evse_service.py, ota_service.py
├── payment_service.py, audit_service.py
├── hodet_service.py, iso15118.py
└── smart_charging.py, websocket_manager.py
tests/ — 169 test files, 4,888 tests
main.py — FastAPI entry point
Domain-Driven Design Layers
Domain Layer
entities/ Charger, Session, User, Station
value_objects/ Energy, Money, EVSE_ID
services/ ChargingService, PricingService
events/ SessionStarted, MeterUpdated
Application Layer (CQRS)
commands/ StartChargingCmd, StopChargingCmd
queries/ GetSessionQuery, ListChargersQuery
handlers/ CommandHandler, QueryHandler
Infrastructure Layer
repositories/ SQLAlchemy implementations
adapters/ OCPP, ISO15118, OCPI gateways
messaging/ Redis pub/sub, WebSocket
Core (Enterprise Patterns)
event_bus.py In-process event bus
circuit_breaker.py Resilience pattern
saga.py Distributed transactions
rate_limiter.py Token bucket algo
main.py FastAPI Entry Point
backend-api/main.py """
CYBER QUANTA BACKEND API
========================
EV Charging Station & Industrial IoT Management Platform
Features:
-----------
- WebSocket: Real-time metric streaming
- REST API: Historical data queries + 287 endpoints
- JWT Authentication: Secure access control
- CORS: Cross-Origin request support
- OpenTelemetry: Distributed tracing and observability
- Redis Cache: High-performance caching
- Enterprise Architecture: CQRS, Event Bus, Circuit Breaker
Architecture:
-------
- Routers: API endpoint definitions (32 files)
- Services: Business logic layer (20 services)
- Models: Database models (SQLAlchemy)
- Core: Infrastructure components (security, cache, telemetry)
- src/core: Enterprise patterns (CQRS, Event Sourcing, Saga)
"""
import os, asyncio
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
routers/evse.py Real API Endpoint
backend-api/routers/evse.py from fastapi import APIRouter, Depends, HTTPException, Query, Request, WebSocket
from sqlalchemy.orm import Session
from auth import TokenData, get_current_user, verify_websocket_token
from core.security import limiter
from core.database import get_db
from services.evse_service import get_evse_metrics_history_from_db, log_command
router = APIRouter ()
evse_api_router = APIRouter (prefix ="/api/evse" , tags =["EVSE" ])
# Local data cache to reduce generation overhead
CACHE_TTL_EVSE = 1.0
_data_cache : dict [str , dict [str , Any ]] = {
"evse" : {"data" : None , "timestamp" : 0.0 },
}
@evse_api_router.get ("/metrics" , response_model =list [dict ])
@limiter.limit ("60/minute" )
async def get_evse_metrics_history (request : Request , ...):
"""EVSE metric history — rate limited, JWT protected"""
...
evse-firmware/ Module Structure
src/
├── charging/ — IEC 61851 state machine
├── protocol/ — OCPP 2.0.1 client
├── drivers/ — control pilot, relay, GFI
├── security/ — HSM, crypto, secure boot
├── metering/ — MID energy measurement
├── comms/ — CAN, UART, SPI, I2C
├── v2g/ — ISO 15118 stack
├── core/ — watchdog, timer, memory
├── main.c — main entry point
└── hsm_atecc608b_stubs.c
include/
├── crypto.h, hsm_driver.h
├── mid_metering.h, transparency.h
├── exi_codec.h, exi_types.h, v2g_types.h
├── plc_driver.h, slac.h
├── websocket_client.h, timer.h
└── evse/ — charger-specific headers
tests/ — Unity test framework
CMakeLists.txt — professional build system
Hardware Target
Primary: NXP i.MX8M Plus
CPU Quad Cortex-A53 @ 1.8GHz
NPU 2.3 TOPS ML accelerator
GPU GC7000UL (3D) + GC520L (2D)
ISP Dual camera pipeline
DDR 4GB LPDDR4 @ 4000MT/s
Safety MCU: STM32G474RE
CPU Cortex-M4F @ 170MHz
Flash 512KB + 32KB data
SRAM 128KB + 32KB CCM
ADC 5x 12-bit 5Msps
PWM HRTIM — CP pilot signal gen
Security Chips
HSM ATECC608B — ECDSA P-256
TPM SLB9672 — TPM 2.0
SP MH1905 — SM2/SM3/SM4
main.c EVSE Controller Entry Point
evse-firmware/src/main.c /**
* @file main.c
* @brief EVSE Controller Main Entry Point
*
* @details Production EVSE firmware entry point that initializes all subsystems
* and runs the main control loop. Designed for NXP i.MX8M Plus platform
* with Cortex-A53 (Linux) + Cortex-M7 (RTOS) architecture.
*
* @standards
* - IEC 61851-1:2017 Mode 3 charging
* - ISO 15118-2:2014 / ISO 15118-20:2022
* - OCPP 2.0.1
* - Eichrecht (German calibration law)
* - EU CRA (Cyber Resilience Act)
* - SIL-2 safety requirements
*
* @version 1.0.0
* @copyright Copyright (c) 2026 Cyber Quanta
*/
control_pilot.c IEC 61851-1 Control Pilot Driver
evse-firmware/src/drivers/control_pilot.c /**
* @file control_pilot.c
* @brief IEC 61851-1 Control Pilot Signal Driver Implementation
*
* @details
* Production-grade Control Pilot implementation for EVSE Mode 3 charging.
* Implements complete state machine per IEC 61851-1:2017 with:
* - PWM generation for current advertisement
* - Voltage monitoring for state detection
* - Vehicle diode verification
* - Contactor control with feedback verification
* - State D ventilation support
* - Fault detection and handling
*/
#include "control_pilot.h"
#include <string.h>
ocpp_client.c OCPP 2.0.1 Protocol Implementation
evse-firmware/src/protocol/ocpp_client.c /**
* @file ocpp_client.c
* @brief OCPP 2.0.1 Client Implementation
*
* Full WebSocket JSON-RPC client implementing 42 OCPP 2.0.1 message types.
* Connection management, message queue, automatic reconnection.
*/
#include "ocpp_client.h"
#include "ocpp_json_helpers.h"
#include "core/watchdog.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
hsm_atecc608b_stubs.c Hardware Security Module Driver
evse-firmware/src/hsm_atecc608b_stubs.c /**
* @file hsm_atecc608b_stubs.c
* @brief ATECC608B-style HSM Driver Stub Implementations (Mock-Aware)
*
* Provides mock-aware stub implementations for the ATECC608B hardware security
* module API. In the test environment, these stubs consume mock SPI expectations
* to return data matching test expectations, enabling full coverage without
* real HSM hardware.
*
* @note For production, replace with actual ATECC608B I2C/SPI driver code.
*/
#include "../include/hsm_driver.h"
#include "mock_spi.h"
#include "mock_timer.h"
#include <string.h>
CMakeLists.txt Build System
evse-firmware/CMakeLists.txt # =============================================================================
# EVSE Firmware - Professional CMake Build System
# =============================================================================
# Target: NXP i.MX8M Plus (ARM Cortex-A53) / STM32G474RE (ARM Cortex-M4F)
# Standards: ISO 15118, OCPP 2.0.1, IEC 61851-1, MID/Eichrecht
# =============================================================================
cmake_minimum_required (VERSION 3.16 )
project (evse-firmware
VERSION 2.1.0
DESCRIPTION "Cyber Quanta EVSE Firmware"
LANGUAGES C
)
option (EVSE_BUILD_TESTS "Build unit tests" ON)
sentinel-firmware/include/hodet/ Security Module Headers
include/hodet/
├── hodet_assert.h — assert handler
├── hodet_audit.h — security audit log
├── hodet_config.h — build configuration
├── hodet_cra.h — EU CRA compliance
├── hodet_crypto.h — crypto engine API
├── hodet_hal.h — hardware abstraction
├── hodet_network.h — network security
├── hodet_ota.h — OTA manager
├── hodet_pool.h — memory pool alloc
├── hodet_power.h — power management
├── hodet_provisioning.h — device provisioning
├── hodet_sbom.h — SBOM generation
├── hodet_secure_boot.h — secure boot chain
├── hodet_storage.h — encrypted storage
├── hodet_tpm.h — TPM 2.0 interface
├── hodet_types.h — common types
├── hodet_update.h — firmware updater
└── hodet_watchdog.h — watchdog timer
Test Suites (17)
test_assert_handler PASS
test_audit PASS
test_cra PASS
test_crypto PASS
test_hal PASS
test_network PASS
test_ota PASS
test_pool PASS
test_power PASS
test_provisioning PASS
test_sbom PASS
test_secure_boot PASS
test_storage PASS
test_system_init PASS
test_tpm PASS
test_update PASS
test_watchdog PASS
crypto_engine.c Cryptographic Engine
sentinel-firmware/src/crypto/crypto_engine.c /**
* @file crypto_engine.c
* @brief Cryptographic engine implementation
*
* Uses EFR32FG28 Secure Vault hardware acceleration for crypto ops.
* Simulation mode uses OpenSSL-compatible software fallback.
*
* Copyright (c) 2026 Cyber Quanta Ltd. All rights reserved.
*/
#include "hodet/hodet_crypto.h"
#include "hodet/hodet_hal.h"
#include "hodet/hodet_config.h"
#include <string.h>
/* Module State */
static bool s_crypto_initialized = false ;
static uint32_t s_next_key_handle = 1 ;
/* Simple key storage for simulation (real impl uses SE/TPM) */
#define MAX_KEYS 32
typedef struct {
uint32_t handle ;
hodet_key_type_t type ;
uint8_t material [64 ];
size_t material_len ;
bool in_use ;
} key_slot_t ;
evse-secure.conf Distribution Configuration
yocto-evse/meta-evse-secure/conf/distro/evse-secure.conf # EVSE Secure Distribution Configuration
# Copyright (c) 2026 Cyber Quanta
# Yocto Poky-based distro for EVSE charging station
DISTRO = "evse-secure"
DISTRO_NAME = "EVSE Secure Linux"
DISTRO_VERSION = "3.2.0"
DISTRO_CODENAME = "volta"
SDK_VENDOR = "-cyberquanta"
MAINTAINER = "Cyber Quanta <engineering@cyberquanta.io>"
require conf/distro/poky.conf
# Security features
DISTRO_FEATURES:append = " systemd pam selinux ima tpm2 seccomp"
DISTRO_FEATURES:remove = "x11 wayland pulseaudio bluetooth nfs zeroconf 3g"
# Hardened compiler flags
SECURITY_CFLAGS = "-fstack-protector-strong -D_FORTIFY_SOURCE=2 -fPIE -Wformat"
SECURITY_LDFLAGS = "-Wl,-z,relro,-z,now -pie"
# IMA (Integrity Measurement Architecture)
IMA_ENABLED = "1"
IMA_POLICY = "evse_ima_policy"
IMA_SIGN_KEY = "${TOPDIR}/keys/ima/ima-privkey.pem"
# dm-verity (root filesystem integrity)
DM_VERITY_ENABLED = "1"
DM_VERITY_ALGORITHM = "sha256"
# Secure Boot (NXP HAB)
SECURE_BOOT_ENABLED = "1"
HAB_KEY_DIR = "${TOPDIR}/keys/hab"
# Kernel
PREFERRED_PROVIDER_virtual/kernel = "linux-evse-secure"
PREFERRED_VERSION_linux-evse-secure = "6.6.%"
imx8mp-evse.conf Machine Configuration
yocto-evse/meta-evse-secure/conf/machine/imx8mp-evse.conf # NXP i.MX8M Plus EVSE Machine Configuration
# Target: Quad Cortex-A53 + Cortex-M7, 4GB LPDDR4, 32GB eMMC
SOC_FAMILY = "imx8mp"
DEFAULTTUNE = "cortexa53-crypto"
KERNEL_DEVICETREE = " \
freescale/imx8mp-evse.dtb \
freescale/imx8mp-evse-pilot.dtb \
"
# Custom kernel modules for EVSE
MACHINE_EXTRA_RRECOMMENDS += " \
kernel-module-evse-rpmsg \
kernel-module-evse-metering \
kernel-module-evse-pilot \
"
# U-Boot configuration
UBOOT_CONFIG [evse] = "imx8mp_evse_defconfig,sdcard"
# M7 co-processor firmware (Safety MCU comm)
M7_FIRMWARE = "evse-sentinel-m7.bin"
M7_FIRMWARE_DEPLOY_DIR = "/lib/firmware"
# eMMC Storage Layout:
# Boot: 64MB | Root A: 2GB | Root B: 2GB | Data: 8GB | Metrology: 4GB | Log: 2GB
MENDER_STORAGE_DEVICE = "/dev/mmcblk2"
MENDER_BOOT_PART_SIZE_MB = "64"
MENDER_DATA_PART_SIZE_MB = "8192"
MENDER_STORAGE_TOTAL_SIZE_MB = "30720"
# Machine features
MACHINE_FEATURES = " \
apm usbgadget usbhost vfat ext2 alsa serial wifi \
pci can optee tpm2 \
"
cyber-quanta-proto_2.0.0.bb BitBake Recipe
yocto-evse/meta-evse-secure/recipes-protocols/cyber-quanta-proto/cyber-quanta-proto_2.0.0.bb # Cyber Quanta EVSE - Protocol Buffers Recipe
SUMMARY = "Cyber Quanta EVSE Protocol Buffer Types"
DESCRIPTION = "Generated Protocol Buffer types for C, Python, TypeScript"
LICENSE = "MIT"
SRC_URI = " \
file://evse.proto \
file://generate_proto.py \
"
DEPENDS = "protobuf protobuf-c protobuf-native"
RDEPENDS :${PN} = "python3-protobuf protobuf"
inherit allarch
do_compile () {
cd ${WORKDIR}
# Generate Python types
python3 generate_proto.py --output ${WORKDIR} /generated
# Generate C headers with protoc
protoc --c_out=${WORKDIR} /generated evse.proto
protoc --python_out=${WORKDIR} /generated evse.proto
}
do_install () {
install -d ${D}${PROTO_DIR}
install -m 0644 ${WORKDIR} /evse.proto ${D}${PROTO_DIR} /
...
}
main.tsx React Application Entry
evse-dashboard/src/main.tsx import React , { Suspense } from 'react'
import ReactDOM from 'react-dom/client'
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'
import { AuthProvider, useAuth } from './contexts/AuthContext'
import { ToastProvider } from './contexts/ToastContext'
import { ErrorBoundary } from './components/ErrorBoundary'
import { AppLayout } from './layouts/AppLayout'
import Login from './pages/Login'
// Code splitting: lazy-load route pages
const Dashboard = React .lazy (() => import ('./pages/Dashboard' ))
const Chargers = React .lazy (() => import ('./pages/Chargers' ))
const Sessions = React .lazy (() => import ('./pages/Sessions' ))
const Users = React .lazy (() => import ('./pages/Users' ))
const Settings = React .lazy (() => import ('./pages/Settings' ))
const Logs = React .lazy (() => import ('./pages/Logs' ))
const TestPanel = React .lazy (() => import ('./pages/TestPanel' ))
Dashboard.tsx Real-time Metrics Page
evse-dashboard/src/pages/Dashboard.tsx import React , { useEffect, useRef } from 'react'
import {
Zap, TrendingUp, Gauge, BatteryCharging,
Activity, ArrowUpRight, ArrowDownRight,
Clock, CheckCircle2,
Wifi, WifiOff, ShieldCheck, Thermometer, Loader2
} from 'lucide-react'
import {
AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip,
ResponsiveContainer, PieChart, Pie, Cell
} from 'recharts'
import { useEVSEData } from '../hooks/useEVSEData'
import { useAuth } from '../contexts/AuthContext'
// Real-time WebSocket data + Recharts visualization
// All data comes from backend /api/evse/metrics endpoint
Chargers.tsx Station Management
evse-dashboard/src/pages/Chargers.tsx import React , { useState } from 'react'
import { Zap, MapPin, Activity, Settings, Power, AlertTriangle,
CheckCircle, XCircle, MoreVertical, Plus, Search, Filter } from 'lucide-react'
const chargers = [
{ id : 'CQ-001' , name : 'Ana Istasyon #1' ,
location : 'Kadikoy, Istanbul' ,
status : 'active' , power : 150 ,
type : 'DC Fast' , connector : 'CCS2' ,
currentSession : {
user : 'Ahmet Y.' , progress : 72 ,
kWh : 28.4 , timeLeft : '12 min'
}
},
...
]
conftest.py Backend Test Configuration
backend-api/tests/conftest.py '''
Sentinel EVSE API - Test Configuration
Pytest fixtures and configuration for integration testing.
'''
import os
# CRITICAL: Set test mode BEFORE ANY import
# This must happen before Python loads any other module
os .environ ["TESTING" ] = "true"
os .environ ["RATE_LIMIT_ENABLED" ] = "false"
# Now import other modules
from collections.abc import AsyncGenerator
import pytest
import pytest_asyncio
from fastapi.testclient import TestClient
from httpx import ASGITransport, AsyncClient
Test Distribution
Backend API — 4,888 tests
tests/core/ architecture, middleware, CQRS
tests/unit/ domain, repository, auth
tests/routers/ all 32 router test files
tests/services/ all 20 service tests
tests/integration/ e2e flows (need PostgreSQL)
tests/compliance/ 112 standards compliance
tests/admin/ admin panel tests
EVSE Firmware — 1,792 tests
Unity framework C11 unit tests
OCPP, ISO 15118 protocol tests
Metering, Drivers hardware abstraction
Security, Crypto HSM stub tests
Hodet Security — 189 tests
17 test suites all PASS
crypto, tpm, ota security modules
audit, cra, sbom compliance modules
429 STM32 tests (19 suites)
Dashboard — 213 tests
Vitest + RTL React Testing Library
14 component tests + 16 a11y tests
Context, hooks state management
Other UI — 113 tests
sentinel-ui 56 tests
lite-wallbox 40 tests
control-center 17 tests
XFAIL (Known Issues)
integration/ SQLite / PostgreSQL UUID
ota_v2 TokenData.get() bug
payments KeyError: 'currency'