aingle_minimal/
lib.rs

1#![doc = include_str!("../README.md")]
2#![allow(rustdoc::bare_urls)]
3#![allow(rustdoc::invalid_html_tags)]
4//! # AIngle Minimal - Ultra-Lightweight IoT Node
5//!
6//! Minimal AIngle node implementation optimized for resource-constrained IoT devices.
7//!
8//! ## Overview
9//!
10//! This crate provides a complete AIngle node that runs on devices with **less than 1MB RAM**,
11//! making it suitable for ESP32, Arduino, Raspberry Pi Pico, and similar embedded systems.
12//!
13//! ## Features
14//!
15//! - **Ultra-light footprint**: Target <512KB RAM, <5MB storage
16//! - **Sub-second confirmation**: Configurable publish intervals (default 5s)
17//! - **Zero-fee transactions**: No staking or gas fees required
18//! - **Mesh networking**: WiFi Direct, BLE, LoRa, Zigbee support
19//! - **Battery-aware**: Adaptive power modes (deep sleep, light sleep, active)
20//! - **CoAP Protocol**: Lightweight alternative to HTTP for IoT
21//! - **DTLS Security**: Encrypted communications with PSK or certificates
22//! - **OTA Updates**: Secure over-the-air firmware updates
23//! - **Smart Agents**: Optional AI capabilities for edge intelligence
24//!
25//! ## Quick Start
26//!
27//! ```rust,ignore
28//! use aingle_minimal::{MinimalNode, Config};
29//!
30//! fn main() -> Result<(), Box<dyn std::error::Error>> {
31//!     // Create node with IoT-optimized config
32//!     let config = Config::iot_mode();
33//!     let mut node = MinimalNode::new(config)?;
34//!
35//!     // Run the node
36//!     smol::block_on(node.run())?;
37//!     Ok(())
38//! }
39//! ```
40//!
41//! ## Advanced Examples
42//!
43//! ### Sensor Integration
44//!
45//! ```rust,ignore
46//! use aingle_minimal::{MinimalNode, SensorManager, SensorType, Config};
47//!
48//! fn main() -> Result<(), Box<dyn std::error::Error>> {
49//!     let mut node = MinimalNode::new(Config::iot_mode())?;
50//!     let mut sensors = SensorManager::new();
51//!
52//!     // Add temperature sensor
53//!     sensors.add_sensor(SensorType::Temperature, 0x48)?;
54//!
55//!     // Read and publish sensor data
56//!     let reading = sensors.read(SensorType::Temperature)?;
57//!     node.publish_sensor_data(reading)?;
58//!     Ok(())
59//! }
60//! ```
61//!
62//! ### CoAP Server
63//!
64//! ```rust,ignore
65//! use aingle_minimal::{CoapServer, CoapConfig};
66//!
67//! async fn run() -> Result<(), Box<dyn std::error::Error>> {
68//!     let config = CoapConfig::default();
69//!     let server = CoapServer::new(config).await?;
70//!
71//!     // Register resource handlers
72//!     server.register_resource("/temperature", |req| {
73//!         // Handle GET /temperature
74//!         Ok("23.5".into())
75//!     });
76//!
77//!     server.run().await?;
78//!     Ok(())
79//! }
80//! ```
81//!
82//! ### Power Management
83//!
84//! ```rust,ignore
85//! use aingle_minimal::{PowerManager, PowerProfile, BatteryInfo};
86//!
87//! fn main() -> Result<(), Box<dyn std::error::Error>> {
88//!     let mut power = PowerManager::new();
89//!
90//!     // Check battery and adjust power mode
91//!     let battery = power.battery_info()?;
92//!     if battery.percentage < 20.0 {
93//!         power.set_profile(PowerProfile::PowerSave)?;
94//!     }
95//!
96//!     // Sleep when idle
97//!     power.sleep(std::time::Duration::from_secs(10))?;
98//!     Ok(())
99//! }
100//! ```
101//!
102//! ### Smart Agent (Edge AI)
103//!
104//! ```rust,ignore
105//! use aingle_minimal::{SmartNode, SmartNodeConfig, SensorAdapter};
106//!
107//! let config = SmartNodeConfig::default();
108//! let mut smart_node = SmartNode::new(config)?;
109//!
110//! // Agent learns from sensor patterns
111//! let adapter = SensorAdapter::new();
112//! smart_node.attach_sensor(adapter);
113//!
114//! // Run agent loop
115//! loop {
116//!     smart_node.step()?;
117//!     smol::Timer::after(std::time::Duration::from_secs(1)).await;
118//! }
119//! ```
120//!
121//! ## Memory Budget
122//!
123//! | Component | Budget |
124//! |-----------|--------|
125//! | Runtime | 128KB |
126//! | Crypto | 64KB |
127//! | Network | 128KB |
128//! | Storage | 128KB |
129//! | App | 64KB |
130//! | **Total** | **512KB** |
131//!
132//! ## Feature Flags
133//!
134//! | Feature | Description | Dependencies |
135//! |---------|-------------|--------------|
136//! | `coap` | CoAP server and client (default) | coap-lite |
137//! | `sqlite` | SQLite storage backend | rusqlite |
138//! | `rocksdb` | RocksDB storage backend (faster) | rocksdb |
139//! | `webrtc` | WebRTC transport for browsers | webrtc, bytes |
140//! | `ble` | Bluetooth LE for Desktop (macOS/Linux/Windows) | btleplug, uuid |
141//! | `ble-esp32` | Bluetooth LE for ESP32 devices | esp32-nimble |
142//! | `hw_wallet` | Hardware wallet support (Ledger/Trezor) | ledger-transport-hid |
143//! | `ai_memory` | Titans memory system for agents | titans_memory |
144//! | `smart_agents` | HOPE agents integration | hope_agents |
145//! | `no_std` | Compile without standard library | - |
146//!
147//! ## Platform Support
148//!
149//! | Platform | Target | BLE Feature |
150//! |----------|--------|-------------|
151//! | macOS | x86_64-apple-darwin, aarch64-apple-darwin | `ble` |
152//! | Linux | x86_64-unknown-linux-gnu | `ble` |
153//! | Windows | x86_64-pc-windows-msvc | `ble` |
154//! | ESP32 | xtensa-esp32-espidf | `ble-esp32` |
155//! | ESP32-C3 | riscv32imc-esp-espidf | `ble-esp32` |
156//! | ESP32-S3 | xtensa-esp32s3-espidf | `ble-esp32` |
157//! | Raspberry Pi Pico | thumbv6m-none-eabi | - |
158//!
159//! ## ESP32 Setup (ble-esp32 feature)
160//!
161//! To compile for ESP32 with Bluetooth LE support:
162//!
163//! ### 1. Install ESP-IDF Toolchain
164//! ```bash
165//! # Install espup (ESP Rust toolchain installer)
166//! cargo install espup
167//! espup install
168//!
169//! # Source the environment
170//! . $HOME/export-esp.sh
171//! ```
172//!
173//! ### 2. Create sdkconfig.defaults
174//! ```text
175//! CONFIG_BT_ENABLED=y
176//! CONFIG_BT_BLE_ENABLED=y
177//! CONFIG_BT_BLUEDROID_ENABLED=n
178//! CONFIG_BT_NIMBLE_ENABLED=y
179//! CONFIG_BT_NIMBLE_NVS_PERSIST=y
180//! ```
181//!
182//! ### 3. Build for ESP32
183//! ```bash
184//! cargo build --target xtensa-esp32-espidf --features ble-esp32
185//! ```
186
187#![cfg_attr(feature = "no_std", no_std)]
188
189#[cfg(feature = "no_std")]
190extern crate alloc;
191
192#[cfg(feature = "ble")]
193pub mod bluetooth;
194#[cfg(feature = "coap")]
195pub mod coap;
196pub mod config;
197pub mod crypto;
198pub mod discovery;
199#[cfg(feature = "coap")]
200pub mod dtls;
201pub mod error;
202pub mod gossip;
203pub mod graph;
204#[cfg(feature = "ai_memory")]
205pub mod memory;
206pub mod network;
207pub mod node;
208pub mod ota;
209pub mod power;
210#[cfg(feature = "quic")]
211pub mod quic;
212pub mod sensors;
213#[cfg(feature = "smart_agents")]
214pub mod smart;
215pub mod sync;
216pub mod types;
217#[cfg(feature = "hw_wallet")]
218pub mod wallet;
219#[cfg(feature = "webrtc")]
220pub mod webrtc;
221
222// REST API server for SDK integration
223#[cfg(feature = "rest")]
224pub mod rest;
225
226// Storage - trait is always available
227pub mod storage_trait;
228
229// Storage backends (feature-gated)
230#[cfg(feature = "rocksdb")]
231pub mod rocks_storage;
232#[cfg(feature = "sqlite")]
233pub mod storage;
234
235// Storage factory for dynamic backend selection
236#[cfg(any(feature = "sqlite", feature = "rocksdb"))]
237pub mod storage_factory;
238
239// Re-export storage types
240pub use config::StorageBackendType;
241#[cfg(any(feature = "sqlite", feature = "rocksdb"))]
242pub use storage_factory::DynamicStorage;
243pub use storage_trait::{StorageBackend, StorageStats};
244
245// Re-exports
246#[cfg(feature = "ble")]
247pub use bluetooth::{BleConfig, BleManager, BlePeer, BleState, BleStats};
248#[cfg(feature = "coap")]
249pub use coap::{CoapConfig, CoapServer};
250pub use config::{Config, GossipConfig, MeshMode, PowerMode, StorageConfig, TransportConfig};
251pub use discovery::{DiscoveredPeer, Discovery};
252#[cfg(feature = "coap")]
253pub use dtls::{DtlsConfig, DtlsSession, SecureCoap, SecurityMode};
254pub use error::{CryptoError, Error, GossipError, NetworkError, Result, StorageError, SyncError};
255pub use gossip::{BloomFilter, GossipManager, GossipStats, MessagePriority, TokenBucket};
256pub use graph::{
257    GraphStats as SemanticGraphStats, SemanticGraph, SemanticQuery, SemanticTriple, TripleObject,
258};
259#[cfg(feature = "ai_memory")]
260pub use memory::IoTMemory;
261pub use node::{MinimalNode, PeerRecord};
262pub use ota::{OtaManager, UpdateChannel, UpdateInfo, UpdateState};
263pub use power::{BatteryInfo, PowerManager, PowerProfile};
264#[cfg(feature = "quic")]
265pub use quic::{QuicConfig, QuicServer};
266pub use sensors::{CalibrationParams, Sensor, SensorManager, SensorReading, SensorType};
267#[cfg(feature = "smart_agents")]
268pub use smart::{IoTPolicyBuilder, SensorAdapter, SmartNode, SmartNodeConfig, SmartNodeStats};
269pub use sync::{PeerSyncState, SyncManager, SyncResult, SyncStats};
270pub use types::*;
271#[cfg(feature = "hw_wallet")]
272pub use wallet::{
273    ApduCommand, ApduResponse, DerivationPath, HwPublicKey, HwSignature, WalletConfig, WalletInfo,
274    WalletManager, WalletState, WalletStats, WalletType,
275};
276#[cfg(feature = "webrtc")]
277pub use webrtc::{
278    ConnectionState, PeerConnection, SignalingClient, SignalingConfig, SignalingMessage,
279    SignalingServer, WebRtcConfig, WebRtcServer, WebRtcStats,
280};
281#[cfg(feature = "rest")]
282pub use rest::{RestConfig, RestServer};
283
284/// Version information for the crate.
285///
286/// # Examples
287///
288/// ```
289/// # use aingle_minimal::VERSION;
290/// println!("AIngle Minimal version: {}", VERSION);
291/// ```
292pub const VERSION: &str = env!("CARGO_PKG_VERSION");
293
294/// Minimum supported Rust version.
295///
296/// This crate requires at least Rust 1.85 to compile.
297pub const MSRV: &str = "1.85";
298
299/// Target memory budget in bytes (512KB).
300///
301/// This is the design goal for the node's total memory footprint,
302/// making it suitable for resource-constrained IoT devices.
303///
304/// See [`Config::memory_limit`](crate::Config::memory_limit) to configure
305/// the actual memory limit for a node.
306pub const MEMORY_BUDGET: usize = 512 * 1024; // 512KB
307
308/// Environment variable for configuring publish interval.
309///
310/// Set this to a number of milliseconds to override the default publish interval.
311///
312/// # Examples
313///
314/// ```bash
315/// # Set publish interval to 1 second
316/// export AINGLE_PUBLISH_INTERVAL_MS=1000
317/// ```
318pub const ENV_PUBLISH_INTERVAL: &str = "AINGLE_PUBLISH_INTERVAL_MS";
319
320/// Environment variable for enabling IoT mode.
321///
322/// When set (to any value), the node will use [`Config::iot_mode()`] as its base
323/// configuration instead of the default.
324///
325/// # Examples
326///
327/// ```bash
328/// # Enable IoT mode
329/// export AINGLE_IOT_MODE=1
330/// ```
331pub const ENV_IOT_MODE: &str = "AINGLE_IOT_MODE";