alice-edge 0.1.0

Embedded Model Generator - Don't send data, send the law
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
# ALICE-Edge

[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
[![Rust](https://img.shields.io/badge/rust-1.70%2B-orange.svg)](https://www.rust-lang.org)
[![Tests](https://img.shields.io/badge/tests-249_passing-brightgreen.svg)](#quality)
[![no_std](https://img.shields.io/badge/no__std-compatible-green.svg)](#supported-platforms)

> Part of **[ALICE-Eco-System]https://github.com/ext-sakamoro/ALICE-Eco-System** — 260+ crate Edge-to-Cloud data pipeline (SDF / Physics / LLM / Motion / Font / TTS)

**Embedded Model Generator** - "Don't send data. Send the law."

<p align="center">
  <em>Ultra-lightweight procedural compression for IoT and embedded systems.<br/>
  1000 sensor samples → 8 bytes. Runs on Raspberry Pi 5 to bare-metal MCU.</em>
</p>

## Installation

Add to your `Cargo.toml`:

```toml
[dependencies]
alice-edge = "0.1"

# With sensor drivers and MQTT:
alice-edge = { version = "0.1", features = ["sensors", "mqtt"] }

# Full edge pipeline (depth camera → SDF → ML → streaming):
alice-edge = { version = "0.1", features = ["edge-pipeline"] }
```

**Minimum Supported Rust Version (MSRV):** 1.70+ (edition 2021)

## The Philosophy

Raw sensor data **never leaves the device**. Instead, we fit a mathematical model on-device and transmit only the coefficients.

```
Traditional IoT:  1000 samples × 4 bytes = 4,000 bytes transmitted
ALICE-Edge:       1000 samples → y = ax + b → 8 bytes transmitted
                  Compression: 500x
                  Privacy: raw data discarded on-device
```

## Benchmark: Raspberry Pi 5 (Cortex-A76, Criterion --release)

| Operation | 10 samples | 100 samples | 1000 samples | 4096 samples |
|-----------|-----------|-------------|-------------|-------------|
| **fit_linear_fixed** | 20 ns | 91 ns | **751 ns** | 3.0 µs |
| **fit_constant_fixed** | 8.4 ns | 33 ns | **218 ns** | 870 ns |
| **full_pipeline** || 90 ns | **752 ns** ||

| Single Operation | Measured |
|-----------------|----------|
| evaluate_linear (1000-point reconstruct) | 2.1 µs |
| compute_residual_error (1000 samples) | 619 ns |
| should_use_linear (model selection) | 3.4 µs |
| Q16 conversion (1000×) | 1.1 µs |

| Metric | Value |
|--------|-------|
| **Throughput** | **1.33M models/sec** (1000 samples each) |
| **Compression ratio** | **500x** (4000 B → 8 B per sensor) |
| **Multi-sensor hub** (8 sensors × 1000) | **571x** (32 KB → 56 B) |
| **Dashboard throughput** | 11,943 models/sec with HLL + CMS |
| **Stack usage** | 48 bytes |
| **Binary size** (no_std core) | < 1 KB |
| **Dependencies** (no_std) | **Zero** |

## Architecture

```
 ┌───────────────────────────────────────────────────────────────────────┐
 │  ALICE-Edge on Raspberry Pi 5                                        │
 │                                                                       │
 │  ┌──────────┐  I2C/SPI/GPIO/UART  ┌──────────────┐                  │
 │  │ BME280   │─────────────────────▶│              │   ┌──────────┐   │
 │  │ DHT22    │                      │ fit_linear   │──▶│ 8 bytes  │   │
 │  │ ADXL345  │                      │ _fixed()     │   │ (slope,  │   │
 │  │ GPS      │                      │              │   │ intercept│   │
 │  └──────────┘                      │ Q16.16       │   └────┬─────┘   │
 │                                    │ Fixed-Point  │        │         │
 │  ┌──────────────┐                  └──────────────┘        │         │
 │  │ ALICE-       │                                          ▼         │
 │  │ Analytics    │◀──latency, compression stats    ┌──────────────┐   │
 │  │ Dashboard    │                                 │ MQTT Publish │   │
 │  │ (HLL, CMS)  │                                 │ AWS IoT Core │   │
 │  └──────────────┘                                 │ Azure IoT Hub│   │
 │                                                   │ Mosquitto    │   │
 │  Raw data → DISCARDED (privacy by design)         └──────────────┘   │
 └───────────────────────────────────────────────────────────────────────┘
```

## Quick Start

### 1. Simulated Sensors (any platform)

```bash
git clone https://github.com/ext-sakamoro/ALICE-Edge.git
cd ALICE-Edge

# Run simulated sensor demo (no hardware required)
cargo run --example simulate_sensors --features sensors

# Multi-sensor hub with compression table
cargo run --example multi_sensor_hub --features sensors
```

### 2. Real Hardware on Raspberry Pi 5

```bash
# BME280 (I2C) + DHT22 (GPIO) + ADXL345 (SPI)
cargo run --example bme280_compress --features sensors-hw
```

### 3. MQTT to Cloud

```bash
# Local Mosquitto
cargo run --example mqtt_local --features "sensors,mqtt"

# AWS IoT Core
export AWS_IOT_ENDPOINT="<account>-ats.iot.<region>.amazonaws.com"
cargo run --example mqtt_aws_iot --features "sensors,mqtt"
```

### 4. Dashboard

```bash
cargo run --example dashboard_demo --features "sensors,dashboard"
```

## Wiring Guide (Raspberry Pi 5)

### BME280 (Temperature / Humidity / Pressure) — I2C

```
BME280          Pi 5
──────          ────
VIN  ────────── 3.3V (Pin 1)
GND  ────────── GND  (Pin 6)
SDA  ────────── GPIO 2 / SDA1 (Pin 3)
SCL  ────────── GPIO 3 / SCL1 (Pin 5)
```

### DHT22 (Temperature / Humidity) — GPIO

```
DHT22           Pi 5
──────          ────
VCC  ────────── 3.3V (Pin 1)
GND  ────────── GND  (Pin 9)
DATA ────────── GPIO 4 (Pin 7)
     (10kΩ pull-up between DATA and VCC)
```

### ADXL345 (3-Axis Accelerometer) — SPI

```
ADXL345         Pi 5
──────          ────
VCC  ────────── 3.3V (Pin 17)
GND  ────────── GND  (Pin 20)
CS   ────────── GPIO 8 / CE0 (Pin 24)
SDO  ────────── GPIO 9 / MISO (Pin 21)
SDA  ────────── GPIO 10 / MOSI (Pin 19)
SCL  ────────── GPIO 11 / SCLK (Pin 23)
```

### GPS Module (NEO-6M / NEO-7M) — UART

```
GPS             Pi 5
──────          ────
VCC  ────────── 3.3V (Pin 1)
GND  ────────── GND  (Pin 14)
TX   ────────── GPIO 15 / RXD (Pin 10)
RX   ────────── GPIO 14 / TXD (Pin 8)
```

## API

### Core (no_std, zero dependencies)

```rust
use alice_edge::{fit_linear_fixed, evaluate_linear_fixed, q16_to_int};

// Sensor readings (e.g., temperature × 100)
let samples = [2500, 2510, 2520, 2530, 2540]; // 25.00°C rising

// Fit model ON DEVICE — raw data never leaves!
let (slope, intercept) = fit_linear_fixed(&samples);

// Transmit only 8 bytes
transmit(&slope.to_le_bytes());
transmit(&intercept.to_le_bytes());

// On receiver: reconstruct any point
let temp_at_10 = evaluate_linear_fixed(slope, intercept, 10);
let celsius = q16_to_int(temp_at_10) as f32 / 100.0;
```

### Sensor Drivers (feature: `sensors` / `sensors-hw`)

```rust
use alice_edge::sensors::{Bme280Sensor, SensorDriver};

let mut sensor = Bme280Sensor::new(1, 0x76); // I2C bus 1
sensor.init()?;

let batch = sensor.read_samples(1000)?;
let (slope, intercept) = fit_linear_fixed(&batch.temperature);
// 4000 bytes → 8 bytes (500x compression)
```

### MQTT Bridge (feature: `mqtt`)

```rust
use alice_edge::mqtt_bridge::{MqttConfig, MqttPublisher, CoefficientPayload};

let config = MqttConfig::local("alice-edge-pi5");
let mut publisher = MqttPublisher::new(config)?;

publisher.publish_coefficients("bme280/temperature", &payload)?;
publisher.publish_binary("bme280/temperature/bin", &payload)?;  // 24 bytes
```

### Dashboard (feature: `dashboard`)

```rust
use alice_edge::dashboard::EdgeDashboard;

let mut dashboard = EdgeDashboard::new();
dashboard.record_compression("bme280", 4000, 8, latency_us);

dashboard.print_dashboard();  // Terminal output
let json = dashboard.to_json();  // JSON for API
```

## Feature Flags

| Feature | Dependencies | Description |
|---------|-------------|-------------|
| *(default)* | None | `no_std` core: fit/evaluate/Q16.16 |
| `sensors` | serde, serde_json | Sensor drivers (simulated) |
| `sensors-hw` | rppal, serialport | Real GPIO/I2C/SPI/UART on Pi |
| `mqtt` | rumqttc | MQTT publish to cloud |
| `dashboard` | alice-analytics | HLL/CMS/latency dashboard |
| `pyo3` | pyo3, numpy | Python bindings (zero-copy NumPy) |
| `zip` | alice-zip | ALICE-Zip compression bridge |
| `codec` | alice-codec | Wavelet denoising bridge |
| `db` | alice-db | Coefficient persistence bridge |
| `ml` | alice-ml | 1.58-bit ternary classification |
| `depth-camera` | rusb | Dolphin D5 Lite depth camera |
| `sdf` | alice-sdf | SDF point cloud compression |
| `asp` | libasp | ALICE Streaming Protocol bridge |
| `edge-pipeline` | (all above) | Full depth → SDF → ML pipeline |

## Q16.16 Fixed-Point Format

ALICE-Edge uses Q16.16 fixed-point arithmetic (no FPU required):

```
16 bits integer | 16 bits fraction
Range: -32768.0 to +32767.99998

Value 25.50°C (as 2550 raw):
  Q16.16 = 2550 × 65536 = 167,116,800

  Convert back: 167,116,800 / 65536 = 2550 → 25.50°C
```

## Memory & Stack Usage

| Function | Stack | Description |
|----------|-------|-------------|
| `fit_linear_fixed` | 48 B | O(N) loop, O(1) x-sums |
| `evaluate_linear_fixed` | 16 B | Single MLA instruction |
| `fit_constant_fixed` | 24 B | Mean value |
| `compute_residual_error` | 32 B | Sum of squared errors |

## Project Structure

```
ALICE-Edge/
├── Cargo.toml
├── src/
│   ├── lib.rs              # Core: fit_linear_fixed, Q16.16 (no_std)
│   ├── sensors.rs          # BME280, DHT22, ADXL345, GPS drivers
│   ├── mqtt_bridge.rs      # MQTT publish (AWS IoT, Azure, Mosquitto)
│   ├── dashboard.rs        # ALICE-Analytics dashboard (HLL, CMS)
│   ├── python.rs           # PyO3 bindings (zero-copy NumPy)
│   ├── zip_bridge.rs       # ALICE-Zip compression
│   ├── codec_bridge.rs     # Wavelet denoising
│   ├── db_bridge.rs        # Coefficient persistence
│   ├── ml_bridge.rs        # Ternary neural network (~80 B model)
│   ├── depth_capture.rs    # Dolphin D5 Lite depth camera
│   ├── sdf_compress.rs     # SDF point cloud compression
│   ├── object_classifier.rs # Edge object classification
│   ├── asp_bridge.rs       # ALICE Streaming Protocol
│   └── edge_pipeline.rs    # Full depth → SDF → ML pipeline
├── examples/
│   ├── simulate_sensors.rs # Simulated sensor demo (any platform)
│   ├── bme280_compress.rs  # BME280 compression (Pi or simulated)
│   ├── multi_sensor_hub.rs # Multi-sensor compression table
│   ├── mqtt_local.rs       # MQTT to local Mosquitto
│   ├── mqtt_aws_iot.rs     # MQTT to AWS IoT Core
│   ├── dashboard_demo.rs   # ALICE-Analytics dashboard
│   └── python_batch.py     # Python + NumPy batch processing
├── benches/
│   └── pi5_bench.rs        # Criterion benchmarks
└── README.md
```

## Bindings

ALICE-Edge provides cross-language bindings via C-ABI FFI:

### C/C++

```c
#include "alice_edge.h"

int32_t data[] = {2500, 2510, 2520, 2530, 2540};
AliceLinearResult r = alice_fit_linear(data, 5);
int32_t predicted = alice_evaluate_linear(r.slope, r.intercept, 10);
float celsius = alice_q16_to_f32(predicted) / 100.0f;
```

Build: `cargo build --release --features ffi` → `libalice_edge.dylib` / `.so` / `.dll`

Header: [`bindings/alice_edge.h`](bindings/alice_edge.h)

### Unity (C#)

```csharp
using AliceEdge;

int[] samples = {2500, 2510, 2520, 2530, 2540};
var (slope, intercept) = AliceModel.FitLinear(samples);
float temp = AliceModel.Q16ToFloat(
    AliceModel.EvaluateLinear(slope, intercept, 10)) / 100f;
```

DllImport wrapper: [`bindings/AliceEdge.cs`](bindings/AliceEdge.cs)

### Python (PyO3 + NumPy)

```python
import alice_edge
import numpy as np

data = np.array([2500, 2510, 2520, 2530, 2540], dtype=np.int32)
slope, intercept = alice_edge.fit_linear(data)
temp_f = alice_edge.q16_to_f32(alice_edge.evaluate_linear(slope, intercept, 10))
```

Build: `maturin develop --features pyo3`

## Quality

| Metric | Value |
|--------|-------|
| **Tests** | 249 (243 lib + 6 doc), 0 failures |
| **clippy pedantic** | 0 warnings |
| **cargo doc** | 0 warnings |
| **cargo fmt** | clean |
| **FFI functions** | 19 (fitting, evaluate, robust, SIMD, filter, delta, zeroize) |
| **Bindings** | C/C++ header, Unity C#, Python PyO3 |

## Security Model

```
┌──────────────────────────────────────────────────────────────────┐
│                      EDGE DEVICE                                  │
│  ┌────────────┐    ┌────────────┐    ┌──────────────┐            │
│  │   Sensor   │───▶│ fit_linear │───▶│ Coefficients │───▶ Network│
│  │   (raw)    │    │  _fixed()  │    │   (8 bytes)  │            │
│  └────────────┘    └────────────┘    └──────────────┘            │
│        │                                                          │
│        ▼                                                          │
│   [DISCARDED]  ← Raw data NEVER leaves device                    │
└──────────────────────────────────────────────────────────────────┘
```

**Privacy by Design**: Raw sensor data is processed and immediately discarded. Only mathematical coefficients (8 bytes) are transmitted. Ideal for:

- Medical devices (HIPAA compliance)
- Industrial sensors (trade secrets)
- Smart home (user privacy)

## ALICE Ecosystem Integration

| Bridge | Source Crate | Usage |
|--------|-------------|-------|
| Sensor compression | **ALICE-Edge** (core) | Q16.16 linear regression |
| Model storage | **ALICE-DB** | Coefficient time-series |
| Wavelet denoising | **ALICE-Codec** | Pre-processing sensor data |
| Binary compression | **ALICE-Zip** | Artifact packaging |
| Analytics | **ALICE-Analytics** | HLL, CMS, latency tracking |
| Neural classification | **ALICE-ML** | 1.58-bit ternary inference |
| SDF compression | **ALICE-SDF** | Point cloud → SDF |
| Streaming | **ALICE-Streaming-Protocol** | Low-bandwidth video |

## Build

### On Raspberry Pi 5 (recommended)

```bash
# Install Rust (one-time)
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
source ~/.cargo/env

# Clone
git clone https://github.com/ext-sakamoro/ALICE-Edge.git
git clone https://github.com/ext-sakamoro/ALICE-Analytics.git

# Build (release)
cd ALICE-Edge
cargo build --release --features sensors-hw,mqtt,dashboard

# Run benchmarks
cargo bench
```

### Cross-compile (macOS → aarch64 Linux)

```bash
rustup target add aarch64-unknown-linux-gnu
cargo build --release --target aarch64-unknown-linux-gnu --features sensors,mqtt,dashboard
scp target/aarch64-unknown-linux-gnu/release/examples/* pi@raspberrypi:~/
```

## Supported Platforms

| Platform | no_std Core | Sensors (HW) | MQTT | Dashboard |
|----------|:-----------:|:------------:|:----:|:---------:|
| **Raspberry Pi 5** | Y | Y | Y | Y |
| **Raspberry Pi 4/3** | Y | Y | Y | Y |
| Raspberry Pi Pico (RP2040) | Y | - | - | - |
| ARM Cortex-M (M0/M3/M4/M7) | Y | - | - | - |
| ESP32 / ESP8266 | Y | - | - | - |
| RISC-V | Y | - | - | - |
| macOS / Linux (x86_64) | Y | sim | Y | Y |

## Troubleshooting (Raspberry Pi)

**"Permission denied" on GPIO**:
```bash
sudo usermod -aG gpio $USER && newgrp gpio
```

**"I2C device not found (0x76)"**:
```bash
sudo raspi-config  # Enable I2C under Interface Options
i2cdetect -y 1     # Verify BME280 appears at 0x76
```

**"SPI bus not available"**:
```bash
sudo raspi-config  # Enable SPI under Interface Options
ls /dev/spidev*    # Verify SPI devices exist
```

## Contributing

See [CONTRIBUTING.md](CONTRIBUTING.md) for build, test, and lint instructions.

## Changelog

See [CHANGELOG.md](CHANGELOG.md) for version history.

## License

MIT (Core)

*Note: The core `no_std` library is licensed under MIT. However, enabling certain feature flags (e.g., `dashboard`, `db`, `ml`) links against AGPL-3.0 components from the broader ALICE ecosystem. Binaries built with these features enabled are subject to the terms of the AGPL-3.0 license.*

## Author

Moroya Sakamoto

---

*"The best sensor network is one where data never travels."*