Metadata-Version: 2.4
Name: eco-edge
Version: 0.1.0
Summary: eco.edge — governance-first embedded AI runtime for constrained hardware
Project-URL: Source, https://github.com/jj-ervin/eco
Project-URL: Issue Tracker, https://github.com/jj-ervin/eco/issues
License-Expression: Apache-2.0
Keywords: edge,embedded,governance,iot,mqtt,raspberry-pi,telemetry
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Embedded Systems
Classifier: Topic :: System :: Hardware
Classifier: Topic :: System :: Monitoring
Requires-Python: >=3.11
Provides-Extra: all
Requires-Dist: asyncua>=1.0; extra == 'all'
Requires-Dist: paho-mqtt>=2.0; extra == 'all'
Requires-Dist: pymodbus>=3.0; extra == 'all'
Provides-Extra: modbus
Requires-Dist: pymodbus>=3.0; extra == 'modbus'
Provides-Extra: mqtt
Requires-Dist: paho-mqtt>=2.0; extra == 'mqtt'
Provides-Extra: opcua
Requires-Dist: asyncua>=1.0; extra == 'opcua'
Description-Content-Type: text/markdown

# eco.edge

**Governance-first embedded AI runtime for constrained hardware.**

eco.edge runs on Raspberry Pi, embedded Linux, and resource-constrained devices.
It provides a governed execution kernel, hardware abstraction layer (HAL),
CAPS pack executor, telemetry emitter, and cloud receiver — packaged as a
single pip-installable library with no mandatory hardware dependencies.

[![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)
[![Python](https://img.shields.io/badge/python-3.11%2B-blue.svg)](https://python.org)

---

## Install

```bash
# Core — no hardware dependencies (stdlib only)
pip install eco-edge

# With MQTT support (paho-mqtt)
pip install eco-edge[mqtt]

# With Modbus RTU/TCP (pymodbus)
pip install eco-edge[modbus]

# With OPC-UA client (asyncua)
pip install eco-edge[opcua]

# Everything
pip install eco-edge[all]
```

Python 3.11+ required.

---

## 5-Minute Quickstart

```python
from eco.core.edge.kernel import EdgeKernel, EdgeRunRequest
from eco.core.edge.hal import SimulatedHalContext
from eco.core.edge.telemetry import TelemetryEmitter

# Simulated HAL — no hardware required for development and testing
hal = SimulatedHalContext(device_id="my-device-001")
emitter = TelemetryEmitter(device_id="my-device-001", hal_context=hal)

kernel = EdgeKernel(
    device_id="my-device-001",
    hal_context=hal,
    telemetry_emitter=emitter,
)

# Submit a run
request = EdgeRunRequest(
    run_id="run-001",
    caps_pack_id="caps.sensor.env",
    command_name="read_sensors",
    inputs={"hal_context": hal},
)

result = kernel.submit_run(request)
print(result.success, result.outputs)
```

See [docs/edge/quickstart.md](docs/edge/quickstart.md) for the full Pi + MQTT broker walkthrough.

---

## Core Concepts

### EdgeKernel

The main entry point. Accepts `EdgeRunRequest`, runs the named CAPS pack,
emits telemetry, and returns `EdgeRunResult`.

```python
kernel = EdgeKernel(
    device_id="pi-field-001",
    hal_context=hal,
    telemetry_emitter=emitter,
    anomaly_detector=AnomalyDetector(),  # optional
)
result = kernel.submit_run(request)
```

### HalContext

Hardware Abstraction Layer — injected into every CAPS pack `run()`. All hardware
I/O (GPIO, UART, MQTT, CAN, I2C, SPI) goes through the HAL. CAPS packs never
call hardware libraries directly.

```python
# Real hardware (Pi)
from eco.core.edge.hal import HalContext
hal = HalContext(device_id="pi-001", mqtt_adapter=PahoMqttTlsAdapter(...))

# Testing / development
from eco.core.edge.hal import SimulatedHalContext
hal = SimulatedHalContext(device_id="test-001")
```

### CAPS Packs

Capability packs are the unit of device-specific logic. Each pack is a Python
module with a `run(request, hal)` function and a declared `SAFETY_CLASS`.

```python
# src/eco/caps/myapp/temperature.py
CAPS_PACK_ID = "caps.myapp.temperature"
SAFETY_CLASS = "OBSERVE"

def run(request, hal):
    temp = hal.i2c_adapter.read_register(0x48, 0x00)
    return {"temperature_c": temp / 256.0}
```

**Safety classes:**

- `OBSERVE` — read-only; records and logs, no side effects on hardware
- `ACTUATE` — advisory output (e.g. ISOBUS recommendation); operator retains override
- `INTERLOCK` — hard gate; requires `__safety_token__` in inputs; blocked without it

### TelemetryEmitter

Publishes run records, escalations, and heartbeats to MQTT.
Offline-queue when no broker is reachable; flushes on reconnect.

```python
from eco.core.edge.telemetry import TelemetryEmitter
emitter = TelemetryEmitter(
    device_id="pi-001",
    hal_context=hal,
    broker_host="mqtt.myserver.com",
    broker_port=8883,
)
emitter.emit_run_record(result)
emitter.emit_heartbeat()
```

### Cloud Components

```python
from eco.cloud.device_registry import DeviceRegistry
from eco.cloud.edge_receiver import EdgeCloudReceiver
from eco.cloud.command_dispatcher import EdgeCommandDispatcher
from eco.cloud.audit_trail import AuditTrailVerifier

# Device registry (SQLite-backed; cloud-side)
registry = DeviceRegistry("devices.db")
registry.register_device("pi-001", public_key_pem="...")

# MQTT cloud receiver
receiver = EdgeCloudReceiver(
    registry=registry,
    escalation_handler=lambda device_id, payload: print(f"Escalation: {payload}"),
)
receiver.start()

# IEC 62443 SR 6.1 compliance check
verifier = AuditTrailVerifier()
result = verifier.check(run_record)
print(result.compliant, result.violations)
```

---

## HAL Adapters

All adapters are available in `eco.core.edge.hal`. Simulated versions have no
hardware dependencies and work in any environment.

| Adapter | Real | Simulated | Optional dep |
| --- | --- | --- | --- |
| `MqttAdapter` / `PahoMqttAdapter` | Pi + broker | `SimulatedMqttAdapter` | `eco-edge[mqtt]` |
| `PahoMqttTlsAdapter` | Pi + TLS broker | — | `eco-edge[mqtt]` |
| `GpsAdapter` | UART NMEA device | `SimulatedGpsAdapter` | none |
| `CellularAdapter` | USB LTE modem | `SimulatedCellularAdapter` | none |
| `BleAdapter` | BlueZ / Pi | `SimulatedBleAdapter` | none |
| `CanAdapter` | SocketCAN / MCP2515 | `SimulatedCanAdapter` | none |
| `Elm327Adapter` | ELM327 USB | `SimulatedElm327Adapter` | none |
| `PymodbusRtuAdapter` | RS-485 serial | — | `eco-edge[modbus]` |
| `PymodbusTcpAdapter` | TCP Modbus | — | `eco-edge[modbus]` |
| `AsyncUaOpcUaAdapter` | OPC-UA server | — | `eco-edge[opcua]` |

---

## CAPS Pack Library

eco.edge ships with ready-to-use CAPS packs for common hardware:

| Pack ID | Description | HAL |
| --- | --- | --- |
| `caps.sensor.env` | DHT22 / BME280 / BME680 — temp, humidity, pressure, air quality | I2C/GPIO |
| `caps.sensor.adc` | MCP3008 ADC via SPI — voltage, current, load cell | SPI |
| `caps.io.relay` | 4/8-channel GPIO relay control | GPIO |
| `caps.ui.display` | SSD1306 OLED / ILI9341 TFT | I2C/SPI |
| `caps.geo.resolve` | GPS + reverse geocode → time.loc geo fields | UART/MQTT |
| `caps.modbus.rtu` | Modbus RTU device read/write | UART + pymodbus |
| `caps.modbus.tcp` | Modbus TCP device read/write | TCP + pymodbus |
| `caps.opcua.client` | OPC-UA node read | asyncua |
| `caps.sparkplug.b` | Sparkplug B MQTT payload encoder/decoder | paho-mqtt |
| `caps.j1939.telemetry` | J1939/CAN ingestion (engine hours, RPM, fault codes) | CanAdapter |
| `caps.j1939.operator` | Operator session recording (ignition, PTO, load events) | CanAdapter |

---

## Telemetry & Signing

Every run record is:

- Timestamped with `time.loc` (device-local + UTC ISO-8601)
- Signed with HMAC-SHA256 using the device's signing key
- Sequenced with a monotonic `run_seq` counter
- Stored locally first; uploaded on connectivity

The `AuditTrailVerifier` checks each record for IEC 62443 SR 6.1 compliance:
`eco_sig` present, `run_seq` present, `time_loc` valid.

---

## AI Lite (eco.ai lite)

`EcoAiLite` is a constrained advisory module (CPM-003). It detects anomalies
in run outputs without a model API call — purely rule-based variance detection.

```python
from eco.core.edge.ai_lite import EcoAiLite, RunContext

ai = EcoAiLite()
advice = ai.advise(RunContext(
    device_id="pi-001",
    caps_pack_id="caps.sensor.env",
    outputs={"temperature_c": 97.3},
    recent_runs=[...],
))
print(advice.anomaly_detected, advice.reason)
```

---

## Anomaly Detection

`AnomalyDetector` flags consecutive failures and sequence gaps before `EcoAiLite`
runs. Anomalies are routed to `TelemetryEmitter.emit_escalation()`.

```python
from eco.core.edge.anomaly import AnomalyDetector

detector = AnomalyDetector(
    consecutive_failure_threshold=3,
    sequence_gap_threshold=10,
)
kernel = EdgeKernel(..., anomaly_detector=detector)
```

---

## eco.service (Agrilogik)

eco.service is a tamper-evident machine health logger for agricultural dealers
and OEM service departments. It uses `caps.j1939.telemetry` and `caps.j1939.operator`
to produce a hash-chained, signed evidence package for warranty dispute resolution.

```python
from eco.cloud.eco_service import EcoServiceEvidencePackage
from eco.cloud.device_registry import DeviceRegistry

registry = DeviceRegistry("farm.db")
pkg = EcoServiceEvidencePackage(registry)

evidence = pkg.generate(
    device_id="tractor-jd-6400-001",
    window_start_time_loc="2026-04-01T06:00:00Z|...",
    window_end_time_loc="2026-04-01T18:00:00Z|...",
)
pkg.export_json(evidence, "warranty_evidence_2026-04-01.json")
print(pkg.verify(evidence))  # True
```

---

## Public API Stability

eco.edge v0.1.x follows semver (pre-1.0 rules):

| Tier | Description |
| --- | --- |
| **STABLE** | `EdgeKernel`, `HalContext`, `SimulatedHalContext`, `TelemetryEmitter`, `EcoAiLite`, `AnomalyDetector`, `DeviceRegistry`, `EdgeCloudReceiver`, `EdgeCommandDispatcher`, `EdgeCommandListener`, `AuditTrailVerifier` |
| **BETA** | `CapsExecutor`, `TimeLoc`, all production HAL adapters |
| **INTERNAL** | Private methods (`_check_ai_lite`, `_record_run`, etc.) — no stability guarantee |

Pin to `eco-edge~=0.1.0` and test before upgrading to 0.2.x.
Full API declaration: [passes/edge/REL-EDGE.00.md](passes/edge/REL-EDGE.00.md)

---

## License

Apache 2.0 — see [LICENSE](LICENSE).
eco.edge is free for commercial deployment, industrial integration, and hardware product distribution.
