Hardware Abstraction Layer
Low-level hardware access — GPIO, UART, SPI, I²C, Timer, Interrupts
HAL Initialization
Initialize the HAL layer. Must be called before any peripheral API.
0 on success, negative error code.
if (eos_hal_init() != 0) panic("HAL init failed");Shut down all HAL peripherals and release resources.
void
eos_hal_deinit(); // clean shutdownBlock the calling task for at least ms milliseconds.
void
eos_delay_ms(1000); // 1 second delayReturn the number of milliseconds since HAL initialization.
Tick count in milliseconds.
uint32_t t0 = eos_get_tick_ms();
// ... work ...
uint32_t elapsed = eos_get_tick_ms() - t0;GPIO
eos_gpio_config_t| Field | Type | Description |
|---|---|---|
| pin | uint16_t | Pin number |
| mode | eos_gpio_mode_t | INPUT, OUTPUT, INPUT_PULLUP, INPUT_PULLDOWN, ANALOG |
| pull | eos_gpio_pull_t | PULL_NONE, PULL_UP, PULL_DOWN |
| speed | eos_gpio_speed_t | SPEED_LOW, SPEED_MEDIUM, SPEED_HIGH, SPEED_VERY_HIGH |
Initialize a GPIO pin. Must be called before read/write/toggle.
0 on success, negative error code.
eos_gpio_config_t led = {
.pin=13, .mode=EOS_GPIO_OUTPUT,
.pull=EOS_GPIO_PULL_NONE, .speed=EOS_GPIO_SPEED_LOW
};
eos_gpio_init(&led);Release a GPIO pin, resetting it to default state.
void
eos_gpio_deinit(13);Set GPIO output pin high or low.
void
eos_gpio_write(13, true); // LED on
eos_delay_ms(1000);
eos_gpio_write(13, false); // LED offRead current state of a GPIO pin. Works for input and output pins.
true if high, false if low.
eos_gpio_config_t btn = { .pin=2, .mode=EOS_GPIO_INPUT, .pull=EOS_GPIO_PULL_UP };
eos_gpio_init(&btn);
if (!eos_gpio_read(2)) printf("Button pressed!\n");Toggle a GPIO output pin (high→low or low→high).
void
while (1) { eos_gpio_toggle(13); eos_delay_ms(500); } // 1 Hz blinkAttach interrupt callback to a GPIO pin on specified edge(s).
0 on success, negative error code.
void on_btn(uint16_t pin, void *ctx) { *(int*)ctx += 1; }
int count = 0;
eos_gpio_set_irq(2, EOS_GPIO_EDGE_FALLING, on_btn, &count);UART
eos_uart_config_t| Field | Type | Description |
|---|---|---|
| port | uint8_t | UART port number |
| baudrate | uint32_t | Baud rate (9600, 115200, etc.) |
| data_bits | uint8_t | Data bits (7 or 8) |
| parity | eos_uart_parity_t | NONE, EVEN, ODD |
| stop_bits | eos_uart_stop_t | STOP_1, STOP_2 |
Initialize a UART port with baud rate, parity, and stop bits.
0 on success, negative error code.
eos_uart_config_t uart = { .port=0, .baudrate=115200,
.data_bits=8, .parity=EOS_UART_PARITY_NONE, .stop_bits=EOS_UART_STOP_1 };
eos_uart_init(&uart);Write bytes to a UART port. Blocks until all bytes are transmitted.
Number of bytes written, or negative error code.
const char *msg = "Hello EoS!\r\n";
eos_uart_write(0, (uint8_t*)msg, strlen(msg));Read up to len bytes from UART. Returns when data available or timeout.
Number of bytes read, 0 on timeout, negative on error.
uint8_t buf[64];
int n = eos_uart_read(0, buf, sizeof(buf), 100);
if (n > 0) process(buf, n);Disable UART port and release its pins.
void
eos_uart_deinit(0);Register async receive callback. Called from ISR context on each received byte.
0 on success, negative error code.
void on_rx(uint8_t port, uint8_t byte, void *ctx) {
ring_buf_push(ctx, byte);
}
eos_uart_set_rx_callback(0, on_rx, &my_buf);SPI
eos_spi_config_t| Field | Type | Description |
|---|---|---|
| port | uint8_t | SPI port number |
| mode | eos_spi_mode_t | MODE_0..3 (CPOL/CPHA) |
| freq_hz | uint32_t | Clock frequency in Hz |
| cs_pin | uint16_t | Chip select GPIO pin |
| msb_first | bool | true=MSB first, false=LSB first |
Initialize SPI controller with given configuration.
0 on success, negative error code.
eos_spi_config_t spi = { .port=0, .mode=EOS_SPI_MODE_0,
.freq_hz=1000000, .cs_pin=10, .msb_first=true };
eos_spi_init(&spi);Full-duplex SPI transfer. tx and rx may be NULL for half-duplex.
0 on success, negative error code.
uint8_t cmd[2] = {0x03, 0x00};
uint8_t data[4];
eos_spi_transfer(0, cmd, NULL, 2);
eos_spi_transfer(0, NULL, data, 4);Write-only SPI transfer (MISO ignored).
0 on success, negative error code.
uint8_t reg_write[] = {0x80 | REG_CTRL, 0x07};
eos_spi_write(0, reg_write, 2);Read-only SPI transfer (MOSI sends 0xFF).
0 on success, negative error code.
uint8_t status;
eos_spi_read(0, &status, 1);Disable SPI controller and release pins.
void
eos_spi_deinit(0);I2C
eos_i2c_config_t| Field | Type | Description |
|---|---|---|
| port | uint8_t | I2C port number |
| speed | eos_i2c_speed_t | SPEED_100K, SPEED_400K, SPEED_1M |
| scl_pin | uint16_t | SCL GPIO pin |
| sda_pin | uint16_t | SDA GPIO pin |
Initialize I2C bus controller.
0 on success, negative error code.
eos_i2c_config_t i2c = { .port=0, .speed=EOS_I2C_SPEED_400K,
.scl_pin=22, .sda_pin=21 };
eos_i2c_init(&i2c);Write bytes to I2C device at 7-bit address.
0 on success, negative error code (EOS_ERR_NACK if device not present).
uint8_t reg_val[] = {0x01, 0x60}; // reg 0x01, value 0x60
eos_i2c_write(0, 0x48, reg_val, 2);Read bytes from I2C device at 7-bit address.
0 on success, negative error code.
uint8_t result[2];
eos_i2c_read(0, 0x48, result, 2);
int16_t temp_raw = (result[0] << 8) | result[1];Write to a specific register of an I2C device (write reg byte then data).
0 on success, negative error code.
uint8_t config = 0x60;
eos_i2c_write_reg(0, 0x48, 0x01, &config, 1);Read from a specific register of an I2C device (write reg, then read).
0 on success, negative error code.
uint8_t raw[2];
eos_i2c_read_reg(0, 0x48, 0x00, raw, 2);Scan I2C bus and return addresses of responding devices.
Number of devices found.
uint8_t found[16];
int n = eos_i2c_scan(0, found, 16);
for (int i=0;i<n;i++) printf("Device at 0x%02X\n", found[i]);Disable I2C controller and release pins.
void
eos_i2c_deinit(0);Timer
Initialize a hardware timer with microsecond period and callback.
0 on success, negative error code.
void on_tick(uint8_t id, void *ctx) { *(uint32_t*)ctx += 1; }
uint32_t ticks = 0;
eos_timer_init(0, 1000, on_tick, &ticks); // 1 kHzStart a previously initialized hardware timer.
void
eos_timer_start(0);Stop a running hardware timer. Callback will no longer fire.
void
eos_timer_stop(0);Change the period of a running or stopped timer.
void
eos_timer_set_period(0, 500); // 2 kHzRelease hardware timer resources.
void
eos_timer_deinit(0);Kernel (RTOS)
Task management, mutexes, semaphores, message queues, software timers
Lifecycle
Start the RTOS scheduler. Never returns. All tasks must be created before this call.
Never returns.
eos_task_create(&main_task, main_fn, NULL, 2048, 5);
eos_kernel_start();Return the current RTOS tick count (increments at configTICK_RATE_HZ).
Current tick count.
uint32_t t = eos_kernel_get_tick();Suspend the scheduler. All tasks freeze. Use for atomic multi-step operations.
void
eos_kernel_suspend();
// atomic update
eos_kernel_resume();Resume the scheduler after eos_kernel_suspend().
void
eos_kernel_resume();Task Management
eos_task_t| Field | Type | Description |
|---|---|---|
| handle | void * | Opaque task handle |
| name | const char * | Task name (for debugging) |
| stack_size | uint32_t | Stack size in bytes |
| priority | uint8_t | Priority 0 (lowest) to 31 (highest) |
Create a new RTOS task. The task starts running immediately if priority > current task.
0 on success, EOS_ERR_NOMEM if stack allocation fails.
void blink_task(void *arg) {
while(1) { eos_gpio_toggle(13); eos_delay_ms(500); }
}
eos_task_t blink;
eos_task_create(&blink, blink_task, NULL, 512, 3);Delete a task and free its stack. Pass NULL to delete the calling task.
void
eos_task_delete(&blink); // delete from another task
eos_task_delete(NULL); // self-deleteSuspend a task. It will not run until eos_task_resume() is called.
void
eos_task_suspend(&sensor_task);Resume a previously suspended task.
void
eos_task_resume(&sensor_task);Yield CPU to any equal or higher priority task.
void
while (!data_ready) eos_task_yield();Block the calling task for a number of RTOS ticks.
void
eos_task_delay(pdMS_TO_TICKS(100)); // 100 msPrecise periodic delay. Compensates for task execution time to maintain exact period.
void
uint32_t last = eos_kernel_get_tick();
while(1) {
eos_task_delay_until(&last, pdMS_TO_TICKS(10)); // 100 Hz
read_sensor();
}Get the current priority of a task.
Task priority (0–31).
uint8_t p = eos_task_get_priority(&my_task);Change the priority of a running task.
void
eos_task_set_priority(&my_task, 10);Return the high-water mark of stack usage in bytes. Useful for sizing stacks.
Minimum free stack bytes ever recorded.
printf("Stack HWM: %u bytes\n", eos_task_get_stack_hwm(&my_task));Mutex
Initialize a mutex. Supports priority inheritance.
0 on success.
eos_mutex_t uart_lock;
eos_mutex_init(&uart_lock);Acquire mutex. Blocks until available or timeout expires.
0 on success, EOS_ERR_TIMEOUT if timed out.
if (eos_mutex_lock(&uart_lock, 100) == 0) {
eos_uart_write(0, data, len);
eos_mutex_unlock(&uart_lock);
}Release a mutex held by the calling task.
void
eos_mutex_unlock(&uart_lock);Try to acquire mutex without blocking.
true if acquired, false if already held.
if (eos_mutex_try_lock(&m)) { /* got it */ }Destroy a mutex and release its resources.
void
eos_mutex_destroy(&uart_lock);Semaphore
Initialize a counting semaphore with initial and maximum count.
0 on success.
eos_sem_t slots;
eos_sem_init(&slots, 0, 10); // 0 available, max 10Decrement semaphore. Blocks if count is 0.
0 on success, EOS_ERR_TIMEOUT if timed out.
eos_sem_wait(&data_ready, EOS_WAIT_FOREVER);
process_data();Increment semaphore count. May unblock a waiting task.
void
// From ISR:
void dma_done_isr(void) { eos_sem_post_from_isr(&data_ready); }Increment semaphore from interrupt context. Uses deferred task wakeup.
void
void adc_isr(void) { eos_sem_post_from_isr(&adc_done); }Return current semaphore count without blocking.
Current count.
printf("Available: %u\n", eos_sem_get_count(&slots));Destroy semaphore and release resources.
void
eos_sem_destroy(&slots);Message Queue
Create a message queue with fixed item size and depth.
0 on success, EOS_ERR_NOMEM if allocation fails.
eos_queue_t sensor_q;
eos_queue_create(&sensor_q, sizeof(sensor_reading_t), 32);Copy item into queue. Blocks if queue is full.
0 on success, EOS_ERR_TIMEOUT if timed out.
sensor_reading_t r = { .temp=25.3f, .ts=eos_get_tick_ms() };
eos_queue_send(&sensor_q, &r, 10);Remove and copy item from queue. Blocks if queue is empty.
0 on success, EOS_ERR_TIMEOUT if timed out.
sensor_reading_t r;
if (eos_queue_recv(&sensor_q, &r, 100) == 0) process(&r);Copy front item without removing it from the queue.
0 on success, EOS_ERR_TIMEOUT if timed out.
sensor_reading_t r;
eos_queue_peek(&sensor_q, &r, 0);Return number of items currently in the queue.
Item count.
printf("%u items waiting\n", eos_queue_count(&sensor_q));Remove all items from the queue.
void
eos_queue_flush(&sensor_q);Delete queue and free memory.
void
eos_queue_delete(&sensor_q);Software Timers
Create a software timer backed by the RTOS timer task.
0 on success.
void heartbeat(uint8_t id, void *ctx) { eos_gpio_toggle(LED); }
eos_sw_timer_t hb;
eos_sw_timer_create(&hb, "heartbeat", 500, true, heartbeat, NULL);Start or restart a software timer.
void
eos_sw_timer_start(&hb);Stop a running software timer.
void
eos_sw_timer_stop(&hb);Reset timer period (restart from zero).
void
eos_sw_timer_reset(&watchdog); // pet the watchdogDelete software timer and free resources.
void
eos_sw_timer_delete(&hb);Multicore Framework
Core management, spinlocks, IPI, shared memory, atomics, task affinity
Core Management
Return the ID of the currently executing core (0 = core 0, 1 = core 1, etc.).
Core ID.
printf("Running on core %d\n", eos_core_get_id());Return the total number of available cores.
Core count.
printf("%d cores available\n", eos_core_get_count());Launch a function on a specific core. Used for SMP initialization.
0 on success.
eos_core_launch(1, core1_main, NULL);Synchronize all cores at this point. All cores must call this before any proceeds.
void
eos_core_sync_barrier(); // all cores readySpinlocks
Initialize a spinlock for cross-core mutual exclusion.
void
eos_spinlock_t shared_lock;
eos_spinlock_init(&shared_lock);Acquire spinlock. Busy-waits. Disables interrupts on the acquiring core.
void
eos_spinlock_acquire(&shared_lock);
shared_counter++;
eos_spinlock_release(&shared_lock);Release spinlock and re-enable interrupts.
void
eos_spinlock_release(&shared_lock);Shared Memory
Cryptographic Services
SHA-256, CRC, AES-256-GCM, RSA, ECC, TRNG
SHA-256
Compute SHA-256 hash of data in one call.
void
uint8_t hash[32];
eos_sha256(firmware_buf, firmware_len, hash);Initialize incremental SHA-256 context.
void
eos_sha256_ctx_t ctx;
eos_sha256_init(&ctx);Feed data into incremental SHA-256 context.
void
eos_sha256_update(&ctx, chunk, chunk_len);Finalize SHA-256 and write 32-byte digest.
void
eos_sha256_final(&ctx, hash);AES
Encrypt data with AES-256-GCM. Produces ciphertext + 16-byte authentication tag.
0 on success.
uint8_t cipher[len], tag[16];
eos_aes256_gcm_encrypt(key, iv, plain, len, cipher, tag);Decrypt and verify AES-256-GCM ciphertext. Fails if tag does not match.
0 on success, EOS_ERR_AUTH if tag mismatch.
if (eos_aes256_gcm_decrypt(key, iv, cipher, len, tag, plain) != 0)
panic("Authentication failed");TRNG
Read cryptographically secure random bytes from the hardware TRNG.
0 on success.
uint8_t nonce[16];
eos_trng_read(nonce, sizeof(nonce));OTA Updates
A/B slot management, verified boot, rollback protection, delta updates
OTA Management
Begin an OTA update session. Selects the inactive slot for writing.
0 on success, EOS_ERR_BUSY if update already in progress.
eos_ota_handle_t ota;
eos_ota_begin(&ota, firmware_size);Write a chunk of firmware data to the inactive OTA slot.
0 on success, negative error code.
while (recv_chunk(&buf, &chunk_len))
eos_ota_write(&ota, buf, chunk_len);Finalize OTA write, verify SHA-256 hash, and mark slot as pending.
0 on success, EOS_ERR_VERIFY if hash mismatch.
if (eos_ota_end(&ota) == 0)
eos_ota_set_boot_partition(EOS_OTA_NEXT);Abort an in-progress OTA update and erase the partial write.
0 on success.
eos_ota_abort(&ota); // on network errorSet which partition boots next: EOS_OTA_CURRENT, EOS_OTA_NEXT, or EOS_OTA_FACTORY.
0 on success.
eos_ota_set_boot_partition(EOS_OTA_NEXT);
eos_restart();Return which OTA partition is currently running.
EOS_OTA_PARTITION_0, _1, or _FACTORY.
printf("Running slot: %d\n", eos_ota_get_running_partition());Mark the current partition as valid. Must be called after successful boot to prevent rollback.
0 on success.
// After verifying app works:
eos_ota_mark_valid();Sensor Framework
Unified sensor registration, calibration, fusion, and streaming
Sensor API
Register a sensor driver with the sensor framework.
0 on success, negative error code.
extern const eos_sensor_ops_t bme280_ops;
eos_sensor_t bme280;
eos_sensor_register(&bme280, &bme280_ops);Open and power on a registered sensor.
0 on success.
eos_sensor_open(&bme280);Read latest sensor data. Returns immediately with most recent sample.
0 on success, EOS_ERR_NOT_READY if no data yet.
eos_sensor_data_t d;
eos_sensor_read(&bme280, &d);
printf("Temp: %.1f°C\n", d.temperature);Set sensor sampling rate in Hz.
0 on success, EOS_ERR_UNSUPPORTED if rate not available.
eos_sensor_set_rate(&imu, 200); // 200 Hz IMUSubscribe to sensor data via callback. Called at the sensor's configured rate.
0 on success.
void on_imu(eos_sensor_t *s, eos_sensor_data_t *d, void *ctx) {
attitude_update(d->accel, d->gyro);
}
eos_sensor_subscribe(&imu, on_imu, NULL);Run sensor calibration routine (offset, scale, or full factory cal).
0 on success.
eos_sensor_calibrate(&imu, EOS_CALIB_OFFSET);Power off and close sensor.
void
eos_sensor_close(&bme280);Filesystem
POSIX-compatible file I/O, directory operations, flash wear leveling
File Operations
Mount a filesystem at the given path. Supports LittleFS, FAT, and SPIFFS.
0 on success.
eos_fs_config_t cfg = { .flash_base=0x200000, .flash_size=0x100000 };
eos_fs_mount("/data", EOS_FS_LITTLEFS, &cfg);Open a file. Mode: "r", "w", "a", "r+", "w+".
File handle, or NULL on error.
eos_file_t *f = eos_fs_open("/data/log.txt", "a");Write bytes to an open file.
Number of bytes written, or negative error code.
eos_fs_write(f, line, strlen(line));Read bytes from an open file.
Number of bytes read, 0 at EOF, negative on error.
char buf[256];
int n = eos_fs_read(f, buf, sizeof(buf));Seek to position. whence: SEEK_SET, SEEK_CUR, SEEK_END.
0 on success.
eos_fs_seek(f, 0, SEEK_SET); // rewindReturn current file position.
Current position in bytes.
long pos = eos_fs_tell(f);Close file and flush any buffered writes.
void
eos_fs_close(f);Delete a file or empty directory.
0 on success.
eos_fs_remove("/data/old.log");Rename or move a file.
0 on success.
eos_fs_rename("/tmp/new.bin", "/app/firmware.bin");Get file metadata (size, type, timestamps).
0 on success.
eos_fs_stat_t st;
eos_fs_stat("/data/log.txt", &st);
printf("Size: %lu\n", st.size);Power Management
Sleep modes, wake sources, voltage scaling, battery monitoring
Power API
Enter low-power sleep mode. Returns when a wake source fires.
void
eos_power_sleep(EOS_SLEEP_LIGHT); // ~1 mA
eos_power_sleep(EOS_SLEEP_DEEP); // ~10 µAConfigure a wake source (GPIO, RTC, UART, timer).
0 on success.
eos_rtc_alarm_t alarm = { .seconds=30 };
eos_power_set_wake_source(EOS_WAKE_RTC, &alarm);Read battery voltage in volts.
Battery voltage.
printf("Battery: %.2fV\n", eos_power_get_vbat());Estimate battery state of charge (0–100%).
SOC percentage.
printf("Battery: %d%%\n", eos_power_get_soc());Set CPU clock frequency for power/performance tradeoff.
void
eos_power_set_cpu_freq(48000000); // 48 MHz low power
eos_power_set_cpu_freq(240000000); // 240 MHz full speedNetworking
TCP/UDP sockets, HTTP client, MQTT, mDNS, TLS
Sockets
Create a network socket. Mirrors POSIX socket().
Socket fd, or negative error code.
int fd = eos_socket(AF_INET, SOCK_STREAM, 0);Connect TCP socket to remote address.
0 on success.
eos_sockaddr_t addr = { .ip="192.168.1.1", .port=80 };
eos_connect(fd, &addr);Send data on a connected socket.
Bytes sent, or negative error code.
eos_send(fd, request, strlen(request), 0);Receive data from a connected socket.
Bytes received, 0 on close, negative on error.
char resp[1024];
int n = eos_recv(fd, resp, sizeof(resp), 0);Close socket and release resources.
void
eos_close(fd);HTTP Client
Perform HTTP GET request. Follows redirects, supports HTTPS.
HTTP status code, or negative error code.
eos_http_resp_t r;
eos_http_get("https://api.example.com/data", &r);
printf("%s\n", r.body);Perform HTTP POST request with body.
HTTP status code, or negative error code.
eos_http_resp_t r;
eos_http_post("https://api.example.com/log",
"{\"temp\":25.3}", "application/json", &r);MQTT Client
Connect to MQTT broker with optional TLS and authentication.
0 on success.
eos_mqtt_config_t cfg = { .host="broker.example.com",
.port=8883, .tls=true, .client_id="device-001" };
eos_mqtt_connect(&mqtt, &cfg);Publish message to MQTT topic at QoS 0, 1, or 2.
0 on success.
eos_mqtt_publish(&mqtt, "sensors/temp",
&temp_f32, sizeof(float), 1);Subscribe to MQTT topic with callback.
0 on success.
void on_cmd(const char *topic, const uint8_t *payload, size_t len, void *ctx) {
handle_command(payload, len);
}
eos_mqtt_subscribe(&mqtt, "device/cmd", 1, on_cmd, NULL);Disconnect from MQTT broker.
void
eos_mqtt_disconnect(&mqtt);Debug Tools
GDB stub, core dump, stack canary, trace, profiler
GDB Stub
Initialize GDB remote stub on UART. Allows GDB to attach and debug.
void
eos_gdb_init(0, 115200); // GDB on UART0Trigger a software breakpoint. Halts execution and waits for GDB.
void
if (error_condition) eos_gdb_breakpoint();Core Dump
Enable automatic core dump to filesystem on crash.
void
eos_coredump_enable("/data/crash.bin");Manually trigger a core dump of the current state.
void
eos_coredump_trigger();Parse a core dump file and extract crash information.
0 on success.
eos_coredump_info_t info;
eos_coredump_analyze("/data/crash.bin", &info);
printf("Crash at PC=0x%08X\n", info.pc);Logging
Structured logging with levels, tags, backends, and ring buffer
Log API
Log a message with level and tag. Printf-style format string.
void
eos_log(EOS_LOG_INFO, "SENSOR", "Temp: %.1f°C", temp);
eos_log(EOS_LOG_ERROR, "NET", "Connect failed: %d", err);Set minimum log level for a specific tag (or "*" for all).
void
eos_log_set_level("*", EOS_LOG_WARN); // silence all below WARN
eos_log_set_level("SENSOR", EOS_LOG_DEBUG); // verbose for SENSORAdd a log backend (UART, filesystem, network, custom).
void
extern eos_log_backend_t uart_backend;
eos_log_add_backend(&uart_backend);Flush all pending log messages to all backends.
void
eos_log_flush(); // before sleep or rebootService Manager
Service lifecycle, dependency resolution, health monitoring, restart policies
Service API
Register a service with the service manager.
0 on success.
extern const eos_service_ops_t mqtt_service_ops;
eos_service_t mqtt_svc;
eos_service_register(&mqtt_svc, &mqtt_service_ops);Start a registered service. Resolves dependencies first.
0 on success, EOS_ERR_DEP if dependency start failed.
eos_service_start(&mqtt_svc);Stop a running service gracefully.
0 on success.
eos_service_stop(&mqtt_svc);Return current service state: STOPPED, STARTING, RUNNING, STOPPING, FAILED.
Service state enum.
if (eos_service_get_state(&mqtt_svc) == EOS_SVC_RUNNING)
eos_mqtt_publish(...);Set restart policy: NEVER, ON_FAILURE, ALWAYS.
void
eos_service_set_restart_policy(&mqtt_svc, EOS_RESTART_ON_FAILURE);EAI — Embedded AI Runtime
On-device LLM inference, ReAct agents, LoRA fine-tuning, and federated learning
Configuration API
Initialize config struct with safe defaults (INT4 quantization, CPU backend).
void
eai_config_t cfg;
eai_config_init(&cfg);Load YAML config from filesystem. Merges over defaults.
EAI_OK on success, EAI_ERR_IO on file error.
if (eai_config_load_file(&cfg, "/etc/eai/config.yml") != EAI_OK) EOS_WARN("Config load failed");Print current config to EoS log at INFO level.
void
eai_config_dump(&cfg); // print loaded configTool Registry API
Register a named tool the agent can call. schema_json is a JSON Schema string.
EAI_OK on success.
eai_tool_register("gpio_write", gpio_exec, GPIO_SCHEMA);Remove a previously registered tool.
EAI_OK on success.
eai_tool_unregister("gpio_write");Agent API
Create a new EAI-Min agent instance with given config.
Pointer to agent, or NULL on OOM.
eai_agent_t *agent = eai_agent_create(&cfg);Run the ReAct agent loop with the given prompt. Blocks until completion or max_steps.
EAI_OK on success, EAI_ERR_TIMEOUT if max steps exceeded.
eai_result_t res;
eai_agent_run(agent, "Turn on LED 13", &res);
printf("%s\n", res.text);Free all resources associated with an agent instance.
void
eai_agent_destroy(agent);Model Registry
Load a quantized model from filesystem into the model registry.
EAI_OK on success.
eai_model_t *m;
eai_model_load("/models/llm-350m-int4.bin", &m);Unload a model and free its memory.
EAI_OK on success.
eai_model_unload(m);List all loaded models. Returns count.
Number of models loaded.
eai_model_info_t models[8];
int n = eai_model_list(models, 8);ENI — Embedded Neural Interface
Configuration-specific neural-recording and spike-sorting research API design
Event System
Subscribe to neural events (spike, epoch, impedance, saturation).
Subscription handle, or negative on error.
int h = eni_event_subscribe(ENI_EVENT_SPIKE, on_spike, NULL);Remove an event subscription.
void
eni_event_unsubscribe(h);Provider Contract API
Register a hardware provider (analog front-end driver).
Provider ID, or negative on error.
extern const eni_provider_ops_t openbci_ops;
eni_provider_register(&openbci_ops, NULL);Start acquisition on a registered provider.
0 on success.
eni_provider_start(0);Stop acquisition and flush buffers.
0 on success.
eni_provider_stop(0);Safety Policy Engine
Set global safety policy (max amplitude, max duration, kill-switch threshold).
0 on success.
eni_safety_policy_t p = { .max_amplitude_uv = 500, .kill_switch_ms = 5 };
eni_safety_set_policy(&p);Immediately halt all acquisition and stimulation. Wired to kernel scheduler.
void
eni_safety_trigger_kill_switch(); // emergency stopCalibration Workflow
Begin per-user calibration session. Collects baseline impedance and noise floor.
0 on success.
eni_cal_config_t cal = { .duration_s = 30, .paradigm = ENI_CAL_MOTOR };
eni_calibration_start(0, &cal);Save calibration profile to filesystem for later reload.
0 on success.
eni_calibration_save(0, "/cal/user1.cal");Load a previously saved calibration profile.
0 on success.
eni_calibration_load(0, "/cal/user1.cal");EIPC — Secure IPC Fabric
Capability-secured IPC with HMAC-SHA256 authentication and zero-copy fast paths
Client API
Connect to a named channel. Returns an unforgeable capability handle.
Handle on success, EIPC_INVALID_HANDLE on error.
eipc_handle_t h = eipc_connect("sensor.accel", EIPC_FLAG_RDONLY);Send a message. HMAC-signed automatically. Blocks if queue is full.
0 on success, negative on error.
eipc_send(h, &reading, sizeof(reading));Receive next message. Verifies HMAC before returning.
Bytes received, 0 on timeout, negative on error.
sensor_reading_t r;
eipc_recv(h, &r, sizeof(r), 100);Close a channel handle and release the capability.
void
eipc_close(h);Server API
Create and bind a named channel server.
Server handle, or NULL on error.
eipc_server_t *srv = eipc_server_create("sensor.accel", &cfg);Accept next incoming connection. Blocks until client connects.
0 on success.
eipc_handle_t client;
eipc_server_accept(srv, &client);Destroy server and reject all pending connections.
void
eipc_server_destroy(srv);Frame Codec API
Encode a frame to wire format with HMAC. Returns encoded length.
Encoded length, or negative on error.
uint8_t wire[256];
int n = eipc_frame_encode(&frame, wire, sizeof(wire));Decode and verify a wire-format frame. Rejects tampered frames.
0 on success, EIPC_ERR_HMAC if authentication fails.
eipc_frame_t frame;
if (eipc_frame_decode(wire, n, &frame) != 0) reject();eDB — Embedded Database
SQL, document, and key-value in one engine with REST API and AES-256 encryption
Database Initialization
Open or create a database at path. cfg may be NULL for defaults.
Database handle, or NULL on error.
edb_t *db = edb_open("/data/app.edb", NULL);Flush and close a database handle.
void
edb_close(db);Enable AES-256-XTS encryption with the given 256-bit key.
0 on success.
uint8_t key[32]; // from eBoot chain-of-trust
edb_encrypt(db, key);SQL Engine
Compile a SQL statement for repeated execution.
Statement handle, or NULL on syntax error.
edb_stmt_t *s = edb_prepare(db, "SELECT * FROM sensors WHERE ts > ?");Execute a SQL statement that returns no rows.
0 on success, negative on error.
edb_exec(db, "CREATE TABLE sensors (ts INTEGER, val REAL)");Advance statement to next row. Returns EDB_ROW or EDB_DONE.
EDB_ROW if row available, EDB_DONE when finished.
while (edb_step(s) == EDB_ROW) { double v = edb_column_double(s, 1); }Release a prepared statement.
void
edb_finalize(s);Document Store
Insert a JSON document into a collection. Generates a UUID id.
0 on success.
char id[37];
edb_doc_insert(db, "readings", "{\"temp\":23.5}", id, sizeof(id));Fetch a document by ID.
0 on success, EDB_NOT_FOUND if missing.
char doc[512];
edb_doc_get(db, "readings", id, doc, sizeof(doc));Delete a document by ID.
0 on success.
edb_doc_delete(db, "readings", id);Key-Value Store
Set a key-value pair in a named bucket.
0 on success.
edb_kv_set(db, "config", "wifi_ssid", "MyNet", 6);Get a value by key. Returns actual length.
Bytes read, or EDB_NOT_FOUND.
char ssid[64];
edb_kv_get(db, "config", "wifi_ssid", ssid, sizeof(ssid));Delete a key-value pair.
0 on success.
edb_kv_delete(db, "config", "old_key");eBootloader — Secure Multi-Architecture Bootloader
A/B update slots, Ed25519 signed images, measured boot, and TPM 2.0 support
Boot Control API
Return the currently active boot slot (0 = A, 1 = B).
0 or 1.
int slot = eboot_get_active_slot();
printf("Active: %s\n", slot ? "B" : "A");Mark the current boot as healthy. Prevents automatic rollback.
0 on success.
// Call early in app startup after self-test
eboot_mark_healthy();Stage a firmware image for update on next reboot.
0 on success.
eboot_request_update(1, "/ota/firmware_v2.bin");Immediately switch to the other slot and reboot.
Does not return on success.
if (self_test_failed()) eboot_rollback();Slot Manager API
Get version, CRC, and health status for a slot.
0 on success.
eboot_slot_info_t info;
eboot_slot_get_info(0, &info);
printf("v%u\n", info.version);Erase a firmware slot (use before writing new image).
0 on success.
eboot_slot_erase(1); // prepare slot BWrite data to a firmware slot at given offset.
0 on success.
eboot_slot_write(1, 0, img_buf, img_len);Boot Log API
Read boot log entries (reason, slot, timestamp, flags).
Number of entries read.
eboot_log_entry_t log[8];
int n = eboot_log_get(log, 8);Clear the boot log ring buffer.
void
eboot_log_clear();eBuild — Build System & SDK Generator
18-command CLI, 14 SDK targets, profile composition, and reproducible builds
CLI Commands
Initialize a new EoS project in the current directory. Downloads BSP and toolchain.
Exit 0 on success.
ebuild init --board stm32h7 --profile sensor-nodeBuild the project. --release enables LTO and size optimization.
Exit 0 on success.
ebuild build --target eos --releaseFlash the built firmware to connected hardware.
Exit 0 on success.
ebuild flash --port /dev/ttyUSB0 --slot bOpen serial monitor to connected device.
Exit 0 on success.
ebuild monitor --port /dev/ttyUSB0 --baud 115200Run unit tests via EoSim. Produces JUnit XML output.
Exit 0 if all tests pass.
ebuild test --filter 'gpio_*'Generate SDK (headers, libs, CMake config) for a component.
Exit 0 on success.
ebuild sdk --target eaiSign a firmware image with Ed25519 private key.
Exit 0 on success.
ebuild sign --key prod.key firmware.binRemove build artifacts and generated files.
Exit 0 on success.
ebuild cleanSDK Structure
Generate EoS kernel SDK with HAL headers, libeos.a, and CMake package config.
Exit 0 on success.
ebuild sdk --target eos # outputs sdk/eos/Generate EAI runtime SDK with model headers and inference library.
Exit 0 on success.
ebuild sdk --target eaiGenerate EIPC client/server SDK with capability headers.
Exit 0 on success.
ebuild sdk --target eipcEoSim — Embedded Systems Simulator
150 virtual platforms, QEMU + Renode, HIL bridge, and scriptable Python scenarios
CLI Commands
List all available virtual platforms. Filter by architecture.
Exit 0 on success.
eosim list --arch cortex-mRun firmware on a virtual platform. Optionally attach a Python scenario script.
Exit code from firmware or script.
eosim run stm32h743 firmware.elf --script test_gpio.pyShow performance statistics for the last simulation run.
Exit 0 on success.
eosim stats stm32h743Launch the graphical simulation UI with live peripheral state.
Exit 0 on success.
eosim gui rpi4 firmware.elfPython Scenario API
Drive a GPIO pin from the test script.
None
sim.gpio_write(13, True) # assert LED pinRead current GPIO pin state.
bool
assert sim.gpio_read(2) == False # button releasedInject bytes into a UART port.
None
sim.uart_send(0, b'AT+RST\r\n')Advance simulation clock by ms milliseconds without real-time delay.
None
sim.advance_time(5000) # skip 5 secondsInject a fault (bit_flip, brown_out, peripheral_fail) at target.
None
sim.inject_fault('brown_out', 'vcc')EoStudio — Embedded IDE
Visual board picker, profile composer, HAL configurator, and integrated EoSim debugger
Workspace API (Plug-in)
Programmatically select a board in the Board Picker panel.
Promise resolving when board is loaded.
await studio.board.select('stm32h743');Enable or disable a feature flag in the Profile Composer.
void
studio.profile.set('EOS_FEATURE_MQTT', true);Configure a peripheral in the HAL Configurator.
void
studio.hal.configure('UART0', { baudrate: 115200 });Launch EoSim with the given firmware file.
Promise resolving to a SimSession handle.
const sess = await studio.sim.run('./build/firmware.elf');Debug API
Set a source-level breakpoint.
void
studio.debug.setBreakpoint('main.c', 42);Read device memory at address.
Promise resolving to byte array.
const mem = await studio.debug.readMemory(0x20000000, 64);Evaluate a C expression in the current debug context.
Promise resolving to string representation.
const val = await studio.debug.evalExpression('sensor.temp');eOffice — Embedded Office Suite
11-app suite: eDocs, eSheets, eSlides, eMail, eDrive, and more — built in Flutter
eDocs API
Open a document file (DOCX, ODT, MD). Returns document handle.
Document handle, or NULL on error.
eoffice_doc_t *doc = edocs_open("/docs/report.docx");Insert text at byte offset. CRDT-safe for concurrent edits.
0 on success.
edocs_insert_text(doc, 0, "Hello EoS!\n");Export document to PDF via the eDB print pipeline.
0 on success.
edocs_export_pdf(doc, "/tmp/report.pdf");Save and close a document handle.
void
edocs_close(doc);eSheets API
Open a spreadsheet file (XLSX, ODS, CSV).
Sheet handle, or NULL on error.
eoffice_sheet_t *s = esheets_open("/data/sensors.xlsx");Set a cell value (number, string, or formula starting with '=').
0 on success.
esheets_set_cell(s, 0, 0, "=SUM(B1:B10)");Get computed cell value as string.
Pointer to value string (valid until next call).
printf("%s\n", esheets_get_cell(s, 0, 0));eBrowser — Embedded Web Browser Engine
HTML5 + CSS3 + HTTP/HTTPS browser engine for kiosks, IoT dashboards, and EoS devices
Core Engine
Create a browser instance with given config (width, height, flags).
Browser handle, or EB_INVALID_HANDLE on error.
eb_config_t cfg = { .width=1024, .height=768, .flags=EB_FLAG_RESIZABLE };
eb_handle_t b = eb_create(&cfg);Navigate to a URL. Asynchronous — use eb_on_load to get notified.
void
eb_navigate(b, "https://embeddedos.org");Enter the browser event loop. Blocks until window is closed.
void
eb_run(b);Destroy browser instance and free all resources.
void
eb_destroy(b);DOM Query API
Find first element matching CSS selector.
Node handle, or EB_NULL_NODE if not found.
eb_node_t btn = eb_query_selector(b, "#submit");Find all elements matching CSS selector.
Count of matching nodes.
eb_node_t items[64];
int n = eb_query_selector_all(b, ".item", items, 64);Get text content of a DOM node.
Pointer to text (valid until next DOM mutation).
printf("%s\n", eb_get_text(btn));Set an attribute on a DOM node.
0 on success.
eb_set_attr(btn, "disabled", "true");eOSuite — 43 Cross-Platform Applications
CLI and GUI apps for productivity, media, games, connectivity, and security — running on EoS, Desktop (SDL2), and Web (WASM)
Productivity CLI
Open or create a markdown note file in the terminal editor.
Exit code 0 on save.
enote meeting-notes.txtEvaluate a mathematical expression including unit conversions.
Numeric result printed to stdout.
ecalc "2+3*4" # → 14List upcoming calendar events from the local CalDAV store.
Formatted event list.
ecal --list --days 7Open the dual-pane file manager at the given path.
Exits when window is closed.
efiles /home/eosConvert between units (length, weight, temperature, data).
Converted value with unit.
econverter 5 km mi # → 3.107 miStart a countdown timer (e.g. 5m, 1h30m).
Exits when timer expires.
eclock --timer 25mConnectivity CLI
Send a message to the default eChat channel.
0 on success.
echat send "Build passed!"Open an SSH session to a remote host.
Exit code of remote shell.
essh root@192.168.1.10Fetch a URL and dump the page text to stdout.
Page text on stdout.
eweb --dump https://embeddedos.orgOpen a serial terminal on the given device.
Exits on Ctrl+C.
eserial /dev/ttyUSB0 115200Connect to an eVPN server.
0 on successful connection.
evpn connect us-1Build System
Configure the eOSuite build for an EoS embedded target.
CMake configure exit code.
cmake -B build-eos -DEAPPS_PORT=eos -DCMAKE_TOOLCHAIN_FILE=cmake/eos.cmake -DEOS_TARGET=stm32f4Configure the eOSuite build for WebAssembly (Emscripten).
CMake configure exit code.
source ~/emsdk/emsdk_env.sh && cmake -B build-web -DEAPPS_PORT=web ...List all installed eOSuite applications and their versions.
Formatted app list.
suite --listeServiceApps — Flutter Mobile Super App
Dart 3 + Flutter 3.x multi-module super app: eSocial, eRide, eTravel, eTrack, eWallet — powered by Firebase + Riverpod
Social Module
Ride Module
Request a ride from pickup to destination.
BookingModel with booking ID and estimated fare.
final booking = await rideService.requestRide(
LatLng(37.78, -122.41), LatLng(37.33, -121.89)
);Stream real-time driver location for an active booking.
Stream of DriverLocation updates.
final stream = rideService.trackDriver(booking.id);Travel Module
Search travel destinations by name or country.
List of matching DestinationModel objects.
final results = await travelService.searchDestinations('Tokyo');Book a flight for a passenger.
BookingModel with confirmation code.
final booking = await travelService.bookFlight(flight, passenger);Wallet Module
Send a payment to another user.
Completes when transaction is confirmed.
await walletService.sendPayment('user123', 25.00, 'USD');Stream transaction history for a user.
Stream of transaction lists.
final txStream = walletService.getTransactions(userId);MapView Widget
Flutter widget wrapping google_maps_flutter with eServiceApps styling and marker clustering.
Widget — renders a Google Map with EmbeddedOS theme.
MapView(
center: LatLng(37.78, -122.41),
zoom: 15,
markers: [Marker(markerId: MarkerId('pickup'), position: pickup)],
)Get the current center coordinates of the map.
LatLng of the current viewport center.
final center = await mapController.getCenter();Smoothly animate the camera to a target position.
Completes when animation finishes.
await mapController.animateTo(LatLng(37.78, -122.41), zoom: 16);AuthGuard & AppTheme
Route guard widget that redirects unauthenticated users to the login screen.
Widget — renders child if authenticated, redirects otherwise.
AuthGuard(
child: DashboardScreen(),
redirectTo: '/login',
)Check if the current user is authenticated via Firebase Auth.
true if a Firebase user session exists.
if (AuthGuard.isAuthenticated(context)) { ... }Get the current eServiceApps theme (light/dark/system).
AppThemeData with color scheme, typography, and spacing tokens.
final theme = AppTheme.of(context);
return Text('Hello', style: theme.titleLarge);Toggle between light and dark theme, persisting the preference.
void — triggers widget rebuild with new theme.
AppTheme.toggle(context);