Skip to content

SILVIA Core ApiSensors Reference

Version: 3.1

Namespace: CognitiveCode.Silvia.Api, CognitiveCode.Silvia.Sensors


Proactive Sensor I/O with Behavior-Triggered Intelligence

SILVIA's Sensor I/O API represents a fundamental architectural breakthrough in how AI systems interact with physical hardware. Traditional sensor integration requires constant polling and inference cycles—your AI brain must continuously ask "what's the temperature?" and then evaluate behaviors to respond. SILVIA LIVE inverts this paradigm: sensors become intelligent first-class citizens that proactively trigger AI behaviors based on conditions, ranges, and deviations.

This is not just a sensor library. It's an event-driven sensor-to-cognition pipeline that eliminates the read-check-react bottleneck, replacing it with a declarative trigger system where sensors fire behaviors directly when conditions are met. Combined with the SILVIA LIVE CLI for rapid authoring, you can wire physical hardware to cognitive responses in minutes instead of days.

Architectural Philosophy: Proactive vs Reactive

Traditional Approach (Reactive):

Sensor → Poll Value → Run Inference → Check Condition → Execute Behavior

[100ms latency, constant CPU usage, brittle logic]

SILVIA Approach (Proactive):

Sensor → Condition Met → Trigger Behavior → Execute Response

[<10ms latency, event-driven, declarative logic]

Dual-Architecture Design

SILVIA provides two complete sensor APIs serving different deployment contexts:

  1. ApiSensors() - Enterprise/IoT/Server Architecture

    • Full-featured with comprehensive logging, diagnostics, connection pooling
    • Adaptive threading (IoT → Server auto-detection)
    • Deviation-based smart logging
    • Rich behavior trigger integration
    • Best for: General IoT, edge computing, enterprise systems
  2. ApiSensorsZeroAlloc() - MilSpec/RTOS/Real-Time Architecture

    • Zero runtime allocations after initialization
    • Lock-free ring buffers (MIL-STD-882E, DO-178C Level A/B compliant)
    • Deterministic latency (<100μs bounds)
    • Pre-allocated buffers for all operations
    • Best for: Control systems, drones, embedded devices, safety-critical applications

Both APIs share identical method signatures for drop-in compatibility, differing only in internal implementation.


Modern Use Cases

1. Autonomous Drone Sensor Mesh (Zero-Alloc API)

Wire IMU sensors, GPS, barometer, and camera telemetry to flight control behaviors with deterministic latency. MilSpec compliance ensures predictable response times for safety-critical maneuvers.

csharp
var sensors = core.ApiSensorsZeroAlloc();

// Create altitude sensor with lock-free ring buffer (MilSpec)
sensors.CreateSensor("altitude", SensorDataType.Float, 
    SensorDirection.InputOnly, ConnectionType.Network, "192.168.1.100:5000");
sensors.SetSensorRingBufferMode("altitude", RingBufferMode.LockFree);
sensors.ActivateSensor("altitude");

// Behavior trigger: Emergency landing if altitude drops below 10m
sensors.GetSensorManager().GetSensor("altitude")
    .AddBehaviorTrigger("emergency", "land_now", 
        TriggerCondition.LessThanMin, 1.0f, "$@altitude", 
        "Emergency: Altitude critical");

// Zero-allocation control loop
while (flying) {
    sensors.UpdateAllSensors(); // Sub-millisecond, zero GC pressure
    float alt = sensors.GetSensorValue<float>("altitude");
    // Process with deterministic timing...
}

2. Industrial IoT Monitoring Network (Enterprise API)

Deploy 100+ sensors across a factory floor with automatic threading optimization, deviation-based logging, and intelligent connection pooling.

csharp
var sensors = core.ApiSensors();

// System auto-detects server environment, uses Independent threading
// Connection pooling prevents TCP exhaustion

for (int i = 0; i < 100; i++) {
    sensors.CreateSensor($"machine_{i:D3}", SensorDataType.Float,
        SensorDirection.InputOnly, ConnectionType.Network, 
        $"192.168.10.{i}:8080");
    
    // Thin logging: only log when value deviates by 5%
    sensors.SetSensorLoggingMode($"machine_{i:D3}", SensorLoggingMode.Thin);
    sensors.SetSensorMaxDeviation($"machine_{i:D3}", 0.05);
    
    // Trigger 'alerts:overheat' behavior when temp > 85°C
    sensors.GetSensorManager().GetSensor($"machine_{i:D3}")
        .AddBehaviorTrigger("alerts", "overheat", 
            TriggerCondition.GreaterThanMax, 1.0f, $"$@machine_{i:D3}", 
            $"Machine {i} temperature exceeded threshold");
}

sensors.ActivateAllSensors(); // Adaptive threading handles updates

3. Smart Home Hub with Multi-Protocol Sensors

Integrate serial Arduino sensors, network-connected thermostats, and wireless motion detectors under a unified API with behavior-driven automation.

csharp
var sensors = core.ApiSensors();

// Serial Arduino temperature sensor
sensors.CreateSensor("arduino_temp", SensorDataType.Float,
    SensorDirection.InputOnly, ConnectionType.Serial, "COM3");

// Network thermostat
sensors.CreateSensor("nest_therm", SensorDataType.Float,
    SensorDirection.Bidirectional, ConnectionType.Network, "192.168.1.50:8080");

// Wireless motion sensor
sensors.CreateSensor("motion_front", SensorDataType.Integer,
    SensorDirection.InputOnly, ConnectionType.Network, "192.168.1.51:9000");

// Behavior triggers for automation
sensors.GetSensorManager().GetSensor("motion_front")
    .AddBehaviorTrigger("automation", "lights_on", 
        TriggerCondition.Equal, 1.0f, "$@motion_front", "Motion detected");

sensors.GetSensorManager().GetSensor("arduino_temp")
    .AddBehaviorTrigger("automation", "climate_adjust", 
        TriggerCondition.Deviation, 2.0f, "$@arduino_temp", 
        "Temperature deviation detected");

sensors.ActivateAllSensors();

4. Event-Driven Control Loop with Async API (Zero-Polling Pattern)

Use async/await for zero-CPU-waste event-driven sensor processing, perfect for control systems that react immediately to sensor changes.

csharp
var sensors = core.ApiSensors();
sensors.CreateSensor("servo_position", SensorDataType.Double,
    SensorDirection.InputOnly, ConnectionType.Network, "10.0.0.100:5000");
sensors.ActivateSensor("servo_position");

// Event-driven loop: fires IMMEDIATELY on sensor update (no polling)
while (controlActive) {
    // WaitForSensorUpdateAsync() uses ValueTask for zero allocation
    double position = await sensors.WaitForSensorUpdateAsync<double>("servo_position");
    
    // Process control algorithm with fresh data, no polling delay
    CalculateControlResponse(position);
}

// Conditional wait: suspend until condition is met
double targetPosition = await sensors.WaitForSensorConditionAsync<double>(
    "servo_position", pos => Math.Abs(pos - 90.0) < 0.1, timeoutMs: 5000);

5. Rapid Sensor-to-Behavior Development with SILVIA CLI

Use the CLI to author sensor-triggered behaviors interactively, testing hardware integration in real-time without recompilation.

> @silvia create behavior automation:temp_response
> @silvia add concept temp_high "temperature is too high" to automation:temp_response
> @silvia add exuder "turning on cooling system" to automation:temp_response

[In C# application:]
sensors.CreateSensor("room_temp", SensorDataType.Float, 
    SensorDirection.InputOnly, ConnectionType.Network, "192.168.1.20:8080");
sensors.SetSensorValueBounds("room_temp", 15f, 30f);

// Trigger 'automation:temp_response' when temp exceeds 30°C
sensors.GetSensorManager().GetSensor("room_temp")
    .AddBehaviorTrigger("automation", "temp_response", 
        TriggerCondition.GreaterThanMax, 1.0f, "$@room_temp", 
        "Room temperature exceeded maximum");

[Result: Hardware event → Cognitive response with zero inference overhead]

Core Concepts

1. Sensor Variables: The $@ Prefix

Every sensor automatically creates a brain variable with the $@ prefix, enabling seamless integration with behaviors, exuders, and inference.

csharp
sensors.CreateSensor("temperature", SensorDataType.Float, ...);
// Automatically creates variable: $@temperature

// Now accessible in behaviors:
// "when $@temperature is greater than 30"
// Exuders can output: "The temperature is $@temperature degrees"

Auto-Sync Modes:

  • Enabled (default): Variables update immediately on GetSensorValue() / SetSensorValue()
  • Disabled: Variables update only during UpdateAllSensors() cycles
csharp
// Fine-grained control over variable sync
sensors.SetSensorAutoSyncToVariable("temp", true);  // Immediate sync
sensors.SetSensorAutoSyncToVariable("temp", false); // Batch sync only

2. Behavior Trigger System

The Core Innovation: Sensors don't just provide data—they trigger SILVIA behaviors when conditions are met, creating an event-driven cognitive pipeline.

Trigger Conditions:

  • TriggerCondition.GreaterThanMax - Value exceeds upper bound
  • TriggerCondition.LessThanMin - Value falls below lower bound
  • TriggerCondition.Equal - Value matches exactly
  • TriggerCondition.Deviation - Value deviates from baseline by threshold
  • TriggerCondition.Range - Value enters/exits defined range

Behavior Trigger Anatomy:

csharp
sensor.AddBehaviorTrigger(
    groupName: "alerts",           // Behavior group
    behaviorName: "too_high",      // Behavior to trigger
    condition: TriggerCondition.GreaterThanMax,
    weight: 1.0f,                  // Trigger strength
    variableName: "$@floatSocket", // Variable to monitor
    message: "Threshold exceeded"  // Context message
);

Example: Multi-Condition Sensor Monitoring

csharp
var sensor = sensors.GetSensorManager().GetSensor("pressure");

// Trigger different behaviors for different conditions
sensor.AddBehaviorTrigger("alerts", "pressure_critical", 
    TriggerCondition.GreaterThanMax, 1.0f, "$@pressure", "Critical pressure");

sensor.AddBehaviorTrigger("alerts", "pressure_low", 
    TriggerCondition.LessThanMin, 1.0f, "$@pressure", "Low pressure warning");

sensor.AddBehaviorTrigger("monitoring", "pressure_deviation", 
    TriggerCondition.Deviation, 0.5f, "$@pressure", "Pressure unstable");

3. Intelligent Threading System

SILVIA's sensor system auto-detects platform capabilities and chooses optimal threading mode:

Threading Modes:

ModeHow It WorksWhen UsedOverhead
PiggybackUpdates via existing SILVIA timerIoT devices, <2 cores, <5 sensorsZero additional threads
PooledUses .NET ThreadPool2+ cores, moderate sensor countsShared thread pool worker
IndependentDedicated background thread4+ cores, 512MB+ memory, high sensor countsOne thread per SILVIA core

Auto-Detection Logic:

csharp
// IoT/Drone (LITE build):
if (LITE_BUILD && processorCount < 2)
Piggyback Mode (5 sensor threshold)

// Server (SERVER2023):
if (processorCount >= 4 && memory > 512MB)
    → Independent Threading (50 sensor threshold)
else if (processorCount >= 2)
    → Pooled Threading (50 sensor threshold)

// Standard deployment:
if (processorCount >= 2 && memory > 256MB)
    → Pooled Threading (20 sensor threshold)
else
    → Piggyback Mode (20 sensor threshold)

Manual Override:

csharp
// Force specific threading mode
sensors.SetThreadingMode(SensorThreadingMode.Independent);
sensors.SetThreadingMode(SensorThreadingMode.Pooled);
sensors.SetThreadingMode(SensorThreadingMode.Piggyback);

// Query current mode
SensorThreadingMode mode = sensors.GetThreadingMode();
int threshold = SilviaApiSensors.GetThreadingThreshold();

4. Ring Buffer Architecture (Zero-Alloc API)

For real-time/MilSpec applications, the zero-alloc API provides two ring buffer modes:

Locked Mode (Default - General Purpose):

  • Multi-reader/writer safe
  • May block under high contention
  • Variable latency (not hard real-time safe)
  • Simple to debug

Lock-Free Mode (MilSpec/DO-178C Level A/B):

  • NEVER blocks - guaranteed non-blocking
  • Deterministic latency (bounded worst-case)
  • No priority inversion (RT scheduler safe)
  • Memory barrier synchronization
  • SPSC only (single producer, single consumer)
  • MIL-STD-882E compliant
csharp
var zeroSensors = core.ApiSensorsZeroAlloc();

// Create sensor
zeroSensors.CreateSensor("rtControl", SensorDataType.Double,
    SensorDirection.InputOnly, ConnectionType.Network, "10.0.0.100:5000");

// Set lock-free mode BEFORE activation
zeroSensors.SetSensorRingBufferMode("rtControl", RingBufferMode.LockFree);
zeroSensors.ActivateSensor("rtControl");

// Bulk configure all network sensors for MilSpec compliance
int count = zeroSensors.SetAllNetworkSensorsLockFree();
// Returns: number of sensors configured

5. Deviation-Based Smart Logging

Traditional logging creates massive data floods. SILVIA's Thin Logging mode only logs when values deviate significantly, reducing storage by 90%+ while capturing all meaningful events.

Logging Modes:

  • SensorLoggingMode.Off - No logging
  • SensorLoggingMode.Thin - Log only on deviation (recommended)
  • SensorLoggingMode.Verbose - Log every value
csharp
// Thin logging: only log when temperature deviates by 0.5°C
sensors.SetSensorLoggingMode("temp01", SensorLoggingMode.Thin);
sensors.SetSensorMaxDeviation("temp01", 0.5);

// Verbose logging for critical sensors
sensors.SetSensorLoggingMode("critical_valve", SensorLoggingMode.Verbose);
sensors.SetSensorLogDirectory("critical_valve", "critical_logs");

// Bulk configuration
sensors.SetAllSensorsLoggingMode(SensorLoggingMode.Thin);
sensors.SetAllSensorsMaxDeviation(0.1);

// Monitor logging statistics
Dictionary<string, string> stats = sensors.GetSensorLoggingStatistics();
// Returns: "Mode:Thin, Deviation:0.100, Events:False, Tracking:True"

6. Connection Pooling & Reuse

Network sensors automatically pool TCP connections, preventing connection exhaustion during brain reloads or multi-sensor deployments.

csharp
// First sensor creates connection to 192.168.1.50:8080
sensors.CreateSensor("sensor1", SensorDataType.Float, 
    SensorDirection.InputOnly, ConnectionType.Network, "192.168.1.50:8080");

// Second sensor REUSES existing connection (zero overhead)
sensors.CreateSensor("sensor2", SensorDataType.Float, 
    SensorDirection.InputOnly, ConnectionType.Network, "192.168.1.50:8080");

// Connection pool statistics
Dictionary<string, object> stats = sensors.GetConnectionPoolStatistics();
// Returns: ActiveSensors, ActiveConnections, NetworkSensors counts

7. Latency Tracking for Control Systems

Essential for engineering control systems to compensate for processing delays.

csharp
// Get measurement-to-processing latency
double latencyMs = sensors.GetSensorLatencyMs("servo_position");

// Get acquisition timestamp (when measurement was actually taken)
double acquisitionTime = sensors.GetSensorAcquisitionTime("servo_position");

// Compensate for latency in control loop
double currentPosition = sensors.GetSensorValue<double>("servo_position");
double correctedPosition = currentPosition + CalculateMotionDuringLatency(latencyMs);

API Reference: ApiSensors (Enterprise/IoT)

Sensor Management

CreateSensor(sensorId, dataType, direction, connectionType, address, subAddress = null)

Creates and registers a new sensor with automatic connection pooling.

Parameters:

  • sensorId (string) - Unique identifier for the sensor
  • dataType (SensorDataType) - Float, Integer, Double, String, Boolean, JSON
  • direction (SensorDirection) - InputOnly, OutputOnly, Bidirectional
  • connectionType (ConnectionType) - Serial, Network, Direct, CAN, ModBus, I2C, SPI
  • address (string) - Connection address (COM port, IP:Port, etc.)
  • subAddress (string, optional) - Sub-address for multiplexed systems

Returns: bool - True if sensor was created successfully

Behavior:

  • Automatically creates $@sensorId variable in brain
  • Implements connection pooling for network sensors
  • Detects duplicate sensors and reuses connections
  • Evaluates threading needs and adjusts automatically

Example:

csharp
// Serial sensor
bool created = sensors.CreateSensor("temp01", SensorDataType.Float,
    SensorDirection.InputOnly, ConnectionType.Serial, "COM3");

// Network sensor with IP:Port
bool created = sensors.CreateSensor("floatSocket", SensorDataType.Float,
    SensorDirection.InputOnly, ConnectionType.Network, "127.0.0.1:12345");

// JSON sensor for complex data
bool created = sensors.CreateSensor("weatherStation", SensorDataType.JSON,
    SensorDirection.InputOnly, ConnectionType.Network, "192.168.1.100:8080");

RemoveSensor(sensorId)

Removes a sensor and releases its resources, with connection pool awareness.

Parameters:

  • sensorId (string) - Unique identifier of the sensor to remove

Returns: bool - True if sensor was removed successfully

Behavior:

  • Releases network connections via connection manager
  • Removes $@sensorId variable from brain
  • Re-evaluates threading needs (may stop thread if sensor count drops)

Example:

csharp
bool removed = sensors.RemoveSensor("temp01");

SensorExists(sensorId)

Checks if a sensor with the specified ID exists.

Parameters:

  • sensorId (string) - Unique identifier of the sensor

Returns: bool - True if sensor exists

Example:

csharp
if (sensors.SensorExists("temp01")) {
    float temp = sensors.GetSensorValue<float>("temp01");
}

GetSensorCount()

Gets the total number of registered sensors.

Returns: int - Number of registered sensors

Example:

csharp
int count = sensors.GetSensorCount();
Console.WriteLine($"Managing {count} sensors");

GetAllSensorIds()

Retrieves an array of all sensor IDs.

Returns: string[] - Array of sensor IDs

Example:

csharp
string[] sensorIds = sensors.GetAllSensorIds();
foreach (string id in sensorIds) {
    Console.WriteLine($"Sensor: {id}");
}

GetSensorIdsByConnectionType(connectionType)

Gets sensor IDs filtered by connection type.

Parameters:

  • connectionType (ConnectionType) - The connection type to filter by

Returns: string[] - Array of matching sensor IDs

Example:

csharp
// Get all network sensors
string[] networkSensors = sensors.GetSensorIdsByConnectionType(ConnectionType.Network);

// Get all serial sensors
string[] serialSensors = sensors.GetSensorIdsByConnectionType(ConnectionType.Serial);

GetConnectedSensorIds()

Gets an array of currently connected sensor IDs.

Returns: string[] - Array of connected sensor IDs

Example:

csharp
string[] connected = sensors.GetConnectedSensorIds();
Console.WriteLine($"{connected.Length} sensors currently connected");

Sensor Operations

ActivateSensor(sensorId)

Activates a sensor for operation with duplicate detection.

Parameters:

  • sensorId (string) - Unique identifier of the sensor

Returns: bool - True if sensor was activated successfully

Behavior:

  • Establishes connection (if network/serial)
  • Begins data collection
  • Starts updating $@sensorId variable

Example:

csharp
bool activated = sensors.ActivateSensor("temp01");
if (activated) {
    Console.WriteLine("Sensor is now active and collecting data");
}

DeactivateSensor(sensorId)

Deactivates a sensor, stopping data collection.

Parameters:

  • sensorId (string) - Unique identifier of the sensor

Returns: bool - True if sensor was deactivated successfully

Example:

csharp
sensors.DeactivateSensor("temp01");

ActivateAllSensors()

Activates all registered sensors simultaneously.

Returns: bool - True if all sensors were activated successfully

Example:

csharp
sensors.ActivateAllSensors();

DeactivateAllSensors()

Deactivates all registered sensors simultaneously.

Returns: bool - True if all sensors were deactivated successfully

Example:

csharp
sensors.DeactivateAllSensors();

UpdateAllSensors()

Manually triggers an update cycle for all sensors.

Returns: bool - True if sensors were updated successfully

Behavior:

  • Reads values from all active sensors
  • Updates corresponding $@ variables
  • Evaluates behavior triggers
  • Typically called from timer/update loop or automatically via threading system

Example:

csharp
// Manual update (useful in custom update loops)
sensors.UpdateAllSensors();

Sensor Data Access

GetSensorValue<T>(sensorId)

Gets the current value from a sensor with type safety.

Type Parameters:

  • T - The type to convert the sensor value to (float, int, double, string, bool)

Parameters:

  • sensorId (string) - Unique identifier of the sensor

Returns: T - The sensor value converted to type T, or default(T) if failed

Behavior:

  • If auto-sync enabled: immediately updates $@sensorId variable
  • If auto-sync disabled: variable updated only during UpdateAllSensors()

Example:

csharp
float temperature = sensors.GetSensorValue<float>("temp01");
int digitalInput = sensors.GetSensorValue<int>("digital_sensor");
string jsonData = sensors.GetSensorValue<string>("weatherStation");

GetSensorValue(sensorId)

Gets the current value from a sensor as an object.

Parameters:

  • sensorId (string) - Unique identifier of the sensor

Returns: object - The sensor value as an object, or null if failed

Example:

csharp
object value = sensors.GetSensorValue("temp01");
Console.WriteLine($"Sensor value: {value}");

SetSensorValue<T>(sensorId, value)

Sets the value of a sensor (for output or bidirectional sensors).

Type Parameters:

  • T - The type of the value to set

Parameters:

  • sensorId (string) - Unique identifier of the sensor
  • value (T) - The value to set

Returns: bool - True if value was set successfully

Behavior:

  • If auto-sync enabled: immediately updates $@sensorId variable
  • For bidirectional sensors: sends value to connected device

Example:

csharp
// Set LED brightness
sensors.SetSensorValue<int>("led_controller", 128);

// Set servo position
sensors.SetSensorValue<float>("servo", 90.0f);

// Send JSON command
sensors.SetSensorValue<string>("device_config", "{\"mode\":\"active\"}");

WaitForSensorUpdateAsync<T>(sensorId, timeoutMs = 5000, cancellationToken = default)

Asynchronously waits for the next sensor value update (event-driven, zero-polling).

Type Parameters:

  • T - The type to convert the sensor value to

Parameters:

  • sensorId (string) - Unique identifier of the sensor
  • timeoutMs (int, optional) - Maximum time to wait in milliseconds (default: 5000)
  • cancellationToken (CancellationToken, optional) - Cancellation token

Returns: ValueTask<T> - The next sensor value, or default(T) on timeout/cancellation

Behavior:

  • Uses ValueTask for zero allocation when value is already available
  • Event-driven: fires immediately when sensor updates (no polling overhead)
  • More efficient than polling for control loops that wait for sensor changes

Example:

csharp
// Event-driven control loop (fires immediately on sensor update)
while (running) {
    float position = await sensors.WaitForSensorUpdateAsync<float>("servo");
    CalculateControl(position);  // Process immediately, no polling delay
}

// With timeout
float temp = await sensors.WaitForSensorUpdateAsync<float>("temperature", 
    timeoutMs: 3000);

WaitForSensorConditionAsync<T>(sensorId, condition, timeoutMs = 10000, cancellationToken = default)

Asynchronously waits for sensor value to meet a specific condition.

Type Parameters:

  • T - The type to convert the sensor value to

Parameters:

  • sensorId (string) - Unique identifier of the sensor
  • condition (Func<T, bool>) - Predicate that returns true when condition is met
  • timeoutMs (int, optional) - Maximum time to wait in milliseconds (default: 10000)
  • cancellationToken (CancellationToken, optional) - Cancellation token

Returns: ValueTask<T> - The sensor value that met the condition, or default(T) on timeout

Behavior:

  • Checks current value first (fast path for synchronous completion)
  • If condition not met, waits for updates until condition is satisfied
  • Event-driven: no polling overhead

Example:

csharp
// Wait until temperature > 100
float hotTemp = await sensors.WaitForSensorConditionAsync<float>(
    "temperature", t => t > 100.0f, timeoutMs: 5000);

// Wait until servo reaches target position
double targetPos = await sensors.WaitForSensorConditionAsync<double>(
    "servo", pos => Math.Abs(pos - 90.0) < 0.1);

// Wait until digital sensor changes state
int state = await sensors.WaitForSensorConditionAsync<int>(
    "button", val => val == 1, timeoutMs: 60000);

Sensor Status and Configuration

IsSensorActive(sensorId)

Checks if a sensor is currently active.

Parameters:

  • sensorId (string) - Unique identifier of the sensor

Returns: bool - True if sensor is active

Example:

csharp
if (sensors.IsSensorActive("temp01")) {
    float temp = sensors.GetSensorValue<float>("temp01");
}

IsSensorConnected(sensorId)

Checks if a sensor is currently connected to its data source.

Parameters:

  • sensorId (string) - Unique identifier of the sensor

Returns: bool - True if sensor is connected

Example:

csharp
bool connected = sensors.IsSensorConnected("network_sensor");
if (!connected) {
    Console.WriteLine("Sensor disconnected, attempting reconnect...");
}

GetSensorLastUpdateTime(sensorId)

Gets the timestamp of the last successful sensor update.

Parameters:

  • sensorId (string) - Unique identifier of the sensor

Returns: double - Last update time in seconds, or -1 if sensor not found

Example:

csharp
double lastUpdate = sensors.GetSensorLastUpdateTime("temp01");
double timeSinceUpdate = DateTime.Now.Ticks / TimeSpan.TicksPerSecond - lastUpdate;
Console.WriteLine($"Last update was {timeSinceUpdate:F1} seconds ago");

GetSensorAcquisitionTime(sensorId)

Gets the acquisition timestamp (when measurement was actually taken).

Parameters:

  • sensorId (string) - Unique identifier of the sensor

Returns: double - Acquisition timestamp in seconds, or -1 if sensor not found

Use Case: Critical for control systems to compensate for processing delays

Example:

csharp
double acquisitionTime = sensors.GetSensorAcquisitionTime("servo_position");
double processingDelay = DateTime.Now.Ticks / TimeSpan.TicksPerSecond - acquisitionTime;

GetSensorLatencyMs(sensorId)

Gets the measurement-to-processing latency in milliseconds.

Parameters:

  • sensorId (string) - Unique identifier of the sensor

Returns: double - Latency in milliseconds, or -1 if sensor not found

Use Case: Essential for engineering control systems and performance monitoring

Example:

csharp
double latency = sensors.GetSensorLatencyMs("control_sensor");
if (latency > 100) {
    Console.WriteLine($"Warning: High latency detected: {latency}ms");
}

SetSensorRefreshRate(sensorId, refreshMode, customHz = 60f)

Sets the refresh rate for a sensor.

Parameters:

  • sensorId (string) - Unique identifier of the sensor
  • refreshMode (RefreshMode) - The refresh mode to use
  • customHz (float, optional) - Custom refresh rate in Hz (only used if refreshMode is CustomHz)

Returns: bool - True if refresh rate was set successfully

Refresh Modes:

  • RefreshMode.OnDemand - Update only when explicitly requested
  • RefreshMode.Continuous - Update as fast as possible
  • RefreshMode.CustomHz - Update at specified frequency

Example:

csharp
// 100Hz refresh for high-speed control
sensors.SetSensorRefreshRate("servo", RefreshMode.CustomHz, 100f);

// On-demand for low-priority sensors
sensors.SetSensorRefreshRate("ambient_light", RefreshMode.OnDemand);

SetSensorValueBounds(sensorId, minValue, maxValue)

Sets the value bounds for a numeric sensor (used by behavior triggers).

Parameters:

  • sensorId (string) - Unique identifier of the sensor
  • minValue (float) - Minimum allowed value
  • maxValue (float) - Maximum allowed value

Returns: bool - True if bounds were set successfully

Behavior:

  • Defines thresholds for GreaterThanMax and LessThanMin trigger conditions
  • Does not clamp values, only sets trigger boundaries

Example:

csharp
// Set temperature bounds: 0°C to 50°C
sensors.SetSensorValueBounds("floatSocket", 0f, 50f);

// Now triggers can use these bounds
sensor.AddBehaviorTrigger("alerts", "too_high", 
    TriggerCondition.GreaterThanMax, 1.0f, "$@floatSocket", 
    "Temperature exceeded 50°C");

SetSensorAutoSyncToVariable(sensorId, autoSync)

Enables or disables automatic synchronization of sensor values to $@ variables.

Parameters:

  • sensorId (string) - Unique identifier of the sensor
  • autoSync (bool) - True to enable auto-sync, false to disable

Returns: bool - True if setting was applied successfully

Behavior:

  • Enabled (default): Variables update immediately on GetSensorValue() / SetSensorValue()
  • Disabled: Variables update only during UpdateAllSensors() cycles

Example:

csharp
// Immediate variable sync (default)
sensors.SetSensorAutoSyncToVariable("temp", true);

// Batch sync only (more efficient for high-frequency sensors)
sensors.SetSensorAutoSyncToVariable("highSpeedSensor", false);

GetSensorAutoSyncToVariable(sensorId)

Gets the current auto-sync to variable setting for a sensor.

Parameters:

  • sensorId (string) - Unique identifier of the sensor

Returns: bool - True if auto-sync is enabled

Example:

csharp
bool autoSync = sensors.GetSensorAutoSyncToVariable("temp");

Sensor Logging Configuration

SetSensorLoggingMode(sensorId, loggingMode)

Sets the logging mode for a specific sensor.

Parameters:

  • sensorId (string) - Unique identifier of the sensor
  • loggingMode (SensorLoggingMode) - Logging mode to use

Returns: bool - True if logging mode was set successfully

Logging Modes:

  • SensorLoggingMode.Off - No logging
  • SensorLoggingMode.Thin - Log only on deviation (recommended)
  • SensorLoggingMode.Verbose - Log every value

Example:

csharp
// Thin logging: log only when value changes significantly
sensors.SetSensorLoggingMode("temp01", SensorLoggingMode.Thin);

// Verbose logging for critical sensors
sensors.SetSensorLoggingMode("safety_sensor", SensorLoggingMode.Verbose);

GetSensorLoggingMode(sensorId)

Gets the current logging mode for a sensor.

Parameters:

  • sensorId (string) - Unique identifier of the sensor

Returns: SensorLoggingMode - Current logging mode, or Off if sensor not found

Example:

csharp
SensorLoggingMode mode = sensors.GetSensorLoggingMode("temp01");

SetSensorMaxDeviation(sensorId, maxDeviation)

Sets the maximum deviation threshold for thin logging.

Parameters:

  • sensorId (string) - Unique identifier of the sensor
  • maxDeviation (double) - Maximum deviation threshold (must be >= 0)

Returns: bool - True if deviation was set successfully

Behavior:

  • In Thin logging mode, values are logged only when deviation from last logged value exceeds this threshold
  • Reduces log volume by 90%+ while capturing all significant events

Example:

csharp
// Log temperature only when it deviates by 0.5°C or more
sensors.SetSensorMaxDeviation("temp01", 0.5);

// Log pressure only when it deviates by 5% (0.05 relative deviation)
sensors.SetSensorMaxDeviation("pressure", 0.05);

GetSensorMaxDeviation(sensorId)

Gets the maximum deviation threshold for a sensor.

Parameters:

  • sensorId (string) - Unique identifier of the sensor

Returns: double - Maximum deviation threshold, or -1 if sensor not found

Example:

csharp
double deviation = sensors.GetSensorMaxDeviation("temp01");

SetSensorLogDirectory(sensorId, logDirectory)

Sets the log directory for a sensor.

Parameters:

  • sensorId (string) - Unique identifier of the sensor
  • logDirectory (string) - Directory path for sensor logs

Returns: bool - True if directory was set successfully

Example:

csharp
sensors.SetSensorLogDirectory("critical_sensor", "logs/critical");

GetSensorLogDirectory(sensorId)

Gets the log directory for a sensor.

Parameters:

  • sensorId (string) - Unique identifier of the sensor

Returns: string - Log directory path, or null if sensor not found

Example:

csharp
string logDir = sensors.GetSensorLogDirectory("critical_sensor");

SetSensorEventTriggers(sensorId, enableTriggers)

Enables or disables event triggers for sensor deviation detection.

Parameters:

  • sensorId (string) - Unique identifier of the sensor
  • enableTriggers (bool) - True to enable event triggers, false to disable

Returns: bool - True if setting was applied successfully

Example:

csharp
// Enable behavior triggers for this sensor
sensors.SetSensorEventTriggers("temp01", true);

GetSensorEventTriggers(sensorId)

Gets the event triggers enabled state for a sensor.

Parameters:

  • sensorId (string) - Unique identifier of the sensor

Returns: bool - True if event triggers are enabled

Example:

csharp
bool triggersEnabled = sensors.GetSensorEventTriggers("temp01");

SetAllSensorsLoggingMode(loggingMode)

Sets logging mode for all sensors.

Parameters:

  • loggingMode (SensorLoggingMode) - Logging mode to apply to all sensors

Returns: bool - True if logging mode was set for all sensors

Example:

csharp
// Enable thin logging for all sensors
sensors.SetAllSensorsLoggingMode(SensorLoggingMode.Thin);

SetAllSensorsMaxDeviation(maxDeviation)

Sets maximum deviation threshold for all sensors.

Parameters:

  • maxDeviation (double) - Maximum deviation threshold to apply to all sensors

Returns: bool - True if deviation was set for all sensors

Example:

csharp
// Set 1% deviation threshold for all sensors
sensors.SetAllSensorsMaxDeviation(0.01);

GetSensorLoggingStatistics()

Gets sensor logging statistics for monitoring and diagnostics.

Returns: Dictionary<string, string> - Dictionary with sensor IDs as keys and logging status as values

Example:

csharp
Dictionary<string, string> stats = sensors.GetSensorLoggingStatistics();
foreach (var kvp in stats) {
    Console.WriteLine($"{kvp.Key}: {kvp.Value}");
    // Output: "temp01: Mode:Thin, Deviation:0.100, Events:True, Tracking:True"
}

System Configuration

SetSensorsEnabled(enabled)

Enables or disables sensor operations for the entire core.

Parameters:

  • enabled (bool) - True to enable sensors, false to disable

Behavior:

  • When disabled, automatically deactivates all sensors
  • Prevents all sensor operations

Example:

csharp
// Disable sensors temporarily
sensors.SetSensorsEnabled(false);

// Re-enable sensors
sensors.SetSensorsEnabled(true);

GetSensorsEnabled()

Gets the current sensor system enabled state.

Returns: bool - True if sensors are enabled

Example:

csharp
bool enabled = sensors.GetSensorsEnabled();

SetAutoUpdateSensors(autoUpdate)

Enables or disables automatic sensor updates on core timer refresh.

Parameters:

  • autoUpdate (bool) - True to enable auto-update, false to disable

Behavior:

  • When enabled: sensors update automatically via core timer or threading system
  • When disabled: must call UpdateAllSensors() manually

Example:

csharp
// Disable auto-update for manual control
sensors.SetAutoUpdateSensors(false);

// Manual update loop
while (running) {
    sensors.UpdateAllSensors();
    Thread.Sleep(50);
}

GetAutoUpdateSensors()

Gets the current auto-update sensors state.

Returns: bool - True if auto-update is enabled

Example:

csharp
bool autoUpdate = sensors.GetAutoUpdateSensors();

SetMaxSensorsPerCore(maxSensors)

Sets the maximum number of sensors allowed per core.

Parameters:

  • maxSensors (int) - Maximum number of sensors (must be > 0)

Returns: bool - True if limit was set successfully

Behavior:

  • Safety limit to prevent resource exhaustion
  • CreateSensor() will fail if limit is reached

Example:

csharp
// Allow up to 500 sensors per core
sensors.SetMaxSensorsPerCore(500);

GetMaxSensorsPerCore()

Gets the maximum number of sensors allowed per core.

Returns: int - Maximum number of sensors per core

Example:

csharp
int maxSensors = sensors.GetMaxSensorsPerCore();

DetectOptimalThreadingMode() (Static)

Detects system capabilities and returns recommended threading mode.

Returns: SensorThreadingMode - Threading mode recommendation

Detection Logic:

  • LITE build → Always Piggyback
  • SERVER2023 build with 4+ cores and 512MB+ memory → Independent
  • SERVER2023 build with 2+ cores → Pooled
  • Standard build with 2+ cores and 256MB+ memory → Pooled
  • Otherwise → Piggyback

Example:

csharp
SensorThreadingMode optimal = SilviaApiSensors.DetectOptimalThreadingMode();
Console.WriteLine($"Recommended threading mode: {optimal}");

GetThreadingThreshold() (Static)

Gets the current sensor count threshold for threading decisions.

Returns: int - Sensor count threshold

Thresholds:

  • LITE build: 5 sensors
  • SERVER2023 build: 50 sensors
  • Standard build: 20 sensors

Example:

csharp
int threshold = SilviaApiSensors.GetThreadingThreshold();
Console.WriteLine($"Threading starts at {threshold} sensors");

SetThreadingMode(mode)

Sets the sensor threading mode with automatic resource optimization.

Parameters:

  • mode (SensorThreadingMode) - Threading mode to use

Returns: bool - True if mode was set successfully

Behavior:

  • Stops current threading
  • Restarts with new mode
  • Evaluates sensor count against threshold

Example:

csharp
// Force independent threading for maximum performance
sensors.SetThreadingMode(SensorThreadingMode.Independent);

// Use pooled threading for balanced performance
sensors.SetThreadingMode(SensorThreadingMode.Pooled);

// Use piggyback for minimal overhead
sensors.SetThreadingMode(SensorThreadingMode.Piggyback);

GetThreadingMode()

Gets the current threading mode.

Returns: SensorThreadingMode - Current threading mode

Example:

csharp
SensorThreadingMode mode = sensors.GetThreadingMode();
Console.WriteLine($"Current threading mode: {mode}");

CleanupInactiveSensors()

Cleans up inactive sensors without destroying network connections (for brain reloads).

Behavior:

  • Removes sensors that are no longer active
  • Keeps network connections alive for reuse
  • Cleans up old connections (10+ minutes idle)

Example:

csharp
// Before brain reload
sensors.CleanupInactiveSensors();

OnBrainReload()

Called when brain reloads to handle sensor state without breaking connections.

Behavior:

  • Stops sensor threads to prevent deadlocks
  • Resets sensor states while keeping network connections alive
  • Re-enables sensors after reload
  • Uses aggressive timeout handling to prevent hangs

Example:

csharp
// Automatically called during brain reload, but can be invoked manually:
sensors.OnBrainReload();

GetConnectionPoolStatistics()

Gets connection pool statistics for monitoring.

Returns: Dictionary<string, object> - Dictionary with connection pool information

Keys:

  • "ActiveSensors" (int) - Number of active sensors
  • "ActiveConnections" (int) - Number of active network connections
  • "NetworkSensors" (int) - Number of network sensors

Example:

csharp
Dictionary<string, object> stats = sensors.GetConnectionPoolStatistics();
Console.WriteLine($"Active sensors: {stats["ActiveSensors"]}");
Console.WriteLine($"Active connections: {stats["ActiveConnections"]}");
Console.WriteLine($"Network sensors: {stats["NetworkSensors"]}");

Ring Buffer Configuration (MilSpec/Real-Time)

SetSensorRingBufferMode(sensorId, mode)

Sets the ring buffer mode for a network sensor (Locked or Lock-Free).

Parameters:

  • sensorId (string) - Unique identifier of the sensor
  • mode (RingBufferMode) - Ring buffer mode (Locked or LockFree)

Returns: bool - True if mode was set successfully

Important: Must be set BEFORE activating the sensor for it to take effect.

Ring Buffer Modes:

  • RingBufferMode.Locked (default) - Multi-reader/writer safe, may block
  • RingBufferMode.LockFree - MilSpec/DO-178C Level A/B compliant, never blocks, SPSC only

Example:

csharp
// Create sensor
sensors.CreateSensor("rtControl", SensorDataType.Double,
    SensorDirection.InputOnly, ConnectionType.Network, "10.0.0.100:5000");

// Set lock-free mode BEFORE activation
bool modeSet = sensors.SetSensorRingBufferMode("rtControl", RingBufferMode.LockFree);

// Activate sensor
sensors.ActivateSensor("rtControl");

// Now reads use lock-free ring buffer (deterministic latency)

GetSensorRingBufferMode(sensorId)

Gets the current ring buffer mode for a network sensor.

Parameters:

  • sensorId (string) - Unique identifier of the sensor

Returns: RingBufferMode - Current ring buffer mode, or Locked if not set or not a network sensor

Example:

csharp
RingBufferMode mode = sensors.GetSensorRingBufferMode("rtControl");
Console.WriteLine($"Ring buffer mode: {mode}");

SetAllNetworkSensorsLockFree()

Sets all network sensors to use lock-free ring buffers for MilSpec compliance.

Returns: int - Number of network sensors configured for lock-free mode

Behavior:

  • Configures all network sensors for lock-free operation
  • Required for MIL-STD-882E and DO-178C Level A/B certification
  • Sensors must be deactivated and reactivated for changes to take effect

Example:

csharp
// Create multiple network sensors
sensors.CreateSensor("sensor1", SensorDataType.Float, ...);
sensors.CreateSensor("sensor2", SensorDataType.Double, ...);
sensors.CreateSensor("sensor3", SensorDataType.Int, ...);

// Configure all for lock-free mode (MilSpec compliant)
int count = sensors.SetAllNetworkSensorsLockFree();
Console.WriteLine($"Configured {count} sensors for lock-free mode");

// Activate sensors (they will use lock-free ring buffers)
sensors.ActivateAllSensors();

API Reference: ApiSensorsZeroAlloc (MilSpec/RTOS)

The zero-allocation API provides identical method signatures to the enterprise API but with zero-allocation internals. All methods from ApiSensors() are available with the same parameters and behavior, with these key differences:

Performance Characteristics

AspectRegular APIZero-Alloc API
Memory UsageVariable (allocates as needed)Fixed and predictable (pre-allocated buffers)
CPU UsageModerate (abstraction overhead)Minimal (direct operations)
LatencyHigher (GC pressure)Sub-millisecond (zero GC pressure)
ScalabilityGood for enterprise (many sensors)Excellent for real-time (limited by single-threaded design)
Threading3 modes (Piggyback, Pooled, Independent)2 modes (SingleThreaded, BackgroundThread)

Zero-Allocation Threading Modes

The zero-alloc API uses simplified threading:

csharp
public enum ZeroAllocSensorThreadingMode {
    SingleThreaded,    // Updates via main timer (default)
    BackgroundThread   // Dedicated background thread
}

var zeroSensors = core.ApiSensorsZeroAlloc();

// Set threading mode
zeroSensors.SetThreadingMode(ZeroAllocSensorThreadingMode.BackgroundThread);

// Get current mode
ZeroAllocSensorThreadingMode mode = zeroSensors.GetThreadingMode();

When to Use Each API

Use ApiSensors() (Enterprise) When:

  • Enterprise systems requiring extensive features
  • Complex sensor networks with multiple connection types
  • Systems requiring comprehensive logging and diagnostics
  • Applications needing behavior triggers and advanced integration
  • Development and testing where features are more important than performance

Use ApiSensorsZeroAlloc() (MilSpec) When:

  • Real-time applications where GC pauses are unacceptable
  • Embedded systems with limited memory
  • High-frequency sensor updates (>100Hz)
  • Performance-critical systems where latency matters
  • Unity games requiring consistent frame rates
  • IoT devices with resource constraints
  • MIL-STD-882E or DO-178C Level A/B certification required

Example: Switching Between APIs

csharp
// Development/Testing - Use enterprise API for full features
var devSensors = core.ApiSensors();
devSensors.CreateSensor("test", SensorDataType.Float, 
    SensorDirection.InputOnly, ConnectionType.Network, "192.168.1.50:8080");
devSensors.SetSensorLoggingMode("test", SensorLoggingMode.Verbose);
devSensors.ActivateSensor("test");

// Production/Real-Time - Use zero-alloc API for performance
var prodSensors = core.ApiSensorsZeroAlloc();
prodSensors.CreateSensor("test", SensorDataType.Float, 
    SensorDirection.InputOnly, ConnectionType.Network, "192.168.1.50:8080");
prodSensors.SetSensorRingBufferMode("test", RingBufferMode.LockFree);
prodSensors.ActivateSensor("test");

// Same method signatures, different performance characteristics
float value1 = devSensors.GetSensorValue<float>("test");   // May allocate
float value2 = prodSensors.GetSensorValue<float>("test");  // Zero allocation

Behavior Trigger Integration

The behavior trigger system is accessed through the internal SensorManager:

csharp
var sensor = sensors.GetSensorManager().GetSensor("sensorId");

Trigger Condition Types

csharp
public enum TriggerCondition {
    GreaterThanMax,  // Value exceeds upper bound
    LessThanMin,     // Value falls below lower bound
    Equal,           // Value matches exactly
    Deviation,       // Value deviates from baseline by threshold
    Range            // Value enters/exits defined range
}

Adding Behavior Triggers

csharp
sensor.AddBehaviorTrigger(
    groupName: "alerts",           // Behavior group
    behaviorName: "too_high",      // Behavior to trigger
    condition: TriggerCondition.GreaterThanMax,
    weight: 1.0f,                  // Trigger strength
    variableName: "$@sensorId",    // Variable to monitor
    message: "Threshold exceeded"  // Context message
);

Complete Trigger Example

csharp
// Create temperature sensor
sensors.CreateSensor("tempSensor", SensorDataType.Float,
    SensorDirection.InputOnly, ConnectionType.Serial, "COM3");

// Set bounds: 15°C to 30°C
sensors.SetSensorValueBounds("tempSensor", 15f, 30f);

// Get sensor object
var sensor = sensors.GetSensorManager().GetSensor("tempSensor");

// Add trigger: When temp > 30°C, trigger 'alerts:overheat' behavior
sensor.AddBehaviorTrigger("alerts", "overheat", 
    TriggerCondition.GreaterThanMax, 1.0f, "$@tempSensor", 
    "Temperature exceeded maximum threshold");

// Add trigger: When temp < 15°C, trigger 'alerts:too_cold' behavior
sensor.AddBehaviorTrigger("alerts", "too_cold", 
    TriggerCondition.LessThanMin, 1.0f, "$@tempSensor", 
    "Temperature below minimum threshold");

// Add trigger: When temp deviates by 5°C, trigger 'monitoring:temp_change'
sensor.AddBehaviorTrigger("monitoring", "temp_change", 
    TriggerCondition.Deviation, 0.5f, "$@tempSensor", 
    "Temperature deviation detected");

sensors.ActivateSensor("tempSensor");

// Now sensor automatically triggers behaviors when conditions are met
// No inference needed, no polling needed - pure event-driven cognition

Unity Integration

SILVIA provides a Unity MonoBehaviour component for visual sensor monitoring and management in the Unity Editor.

SilviaSensorIO Component

csharp
using CognitiveCode.Silvia.Unity;

// Attach to GameObject
[AddComponentMenu("SILVIA/Sensor IO Inspector")]
public class SilviaSensorIO : MonoBehaviour

Features:

  • Live-updating inspector interface for sensor monitoring
  • Real-time display of sensor values, connection status, and system info
  • Tools for sensor creation and management
  • Performance metrics and diagnostics
  • Custom editor with action buttons

Inspector Fields:

  • SILVIA Core Connection: Target core to monitor (auto-find available)
  • System Status: Sensors enabled, threading mode, sensor counts
  • Live Sensor Data: Real-time sensor values and status
  • Inspector Settings: Refresh rate, detailed info, filters
  • Sensor Management: Preset-based sensor creation

Action Buttons (Custom Editor):

  • Refresh Data: Manual sensor data update
  • Reinitialize: Complete system reset and reconnection
  • Update All Sensors: Force immediate sensor readings
  • Toggle Sensors: Enable/disable all sensors
  • Create Sensor: Instantiate sensor from preset

Usage:

csharp
// 1. Attach SilviaSensorIO to a GameObject in your Unity scene
// 2. Assign a SILVIA Core instance (or let it auto-find)
// 3. Configure refresh rate and display options
// 4. Monitor sensors in the inspector during play mode

// Programmatic access:
SilviaSensorIO sensorIO = GetComponent<SilviaSensorIO>();
sensorIO.ManualRefresh();
sensorIO.UpdateAllSensors();

Integration with SILVIA LIVE CLI

The Sensor API combines powerfully with the SILVIA LIVE CLI for rapid sensor-to-behavior development:

Workflow: Hardware to Cognition in Minutes

  1. Create sensor in application:
csharp
sensors.CreateSensor("tempSensor", SensorDataType.Float,
    SensorDirection.InputOnly, ConnectionType.Serial, "COM3");
sensors.SetSensorValueBounds("tempSensor", 15f, 30f);
  1. Author behavior in CLI:
> @silvia create behavior alerts:overheat
> @silvia add concept temp_high "temperature is dangerously high" to alerts:overheat
> @silvia add exuder "activating emergency cooling system" to alerts:overheat
  1. Wire sensor to behavior:
csharp
var sensor = sensors.GetSensorManager().GetSensor("tempSensor");
sensor.AddBehaviorTrigger("alerts", "overheat", 
    TriggerCondition.GreaterThanMax, 1.0f, "$@tempSensor", 
    "Temperature critical");

sensors.ActivateSensor("tempSensor");
  1. Test and iterate in CLI:
> @silvia test behavior alerts:overheat
> @me the temperature sensor is reading 32 degrees
[SILVIA triggers 'alerts:overheat' behavior]
[Output: "activating emergency cooling system"]

Result: Hardware event → Cognitive response, authored conversationally, tested interactively, deployed instantly. No recompilation. No inference overhead. Pure event-driven AI.


Advanced Patterns

Pattern 1: Multi-Condition Sensor State Machine

csharp
var sensor = sensors.GetSensorManager().GetSensor("pressure");

// State: Normal operation
sensor.AddBehaviorTrigger("states", "normal", 
    TriggerCondition.Range, 1.0f, "$@pressure", "Pressure nominal");

// State: Warning
sensor.AddBehaviorTrigger("states", "warning", 
    TriggerCondition.GreaterThanMax, 0.8f, "$@pressure", "Pressure elevated");

// State: Critical
sensor.AddBehaviorTrigger("states", "critical", 
    TriggerCondition.GreaterThanMax, 1.0f, "$@pressure", "Pressure critical");

// State: Emergency
sensor.AddBehaviorTrigger("states", "emergency", 
    TriggerCondition.Deviation, 1.0f, "$@pressure", "Pressure unstable");

// Behavior group 'states' now contains state machine logic

Pattern 2: Cascading Sensor Network

csharp
// Primary sensor
sensors.CreateSensor("primary_temp", SensorDataType.Float, ...);
var primary = sensors.GetSensorManager().GetSensor("primary_temp");
primary.AddBehaviorTrigger("cascade", "check_secondary", 
    TriggerCondition.GreaterThanMax, 1.0f, "$@primary_temp", "Primary sensor alert");

// Secondary sensor
sensors.CreateSensor("secondary_temp", SensorDataType.Float, ...);
var secondary = sensors.GetSensorManager().GetSensor("secondary_temp");
secondary.AddBehaviorTrigger("cascade", "confirm_alert", 
    TriggerCondition.GreaterThanMax, 1.0f, "$@secondary_temp", "Secondary confirmation");

// Behavior 'cascade:check_secondary' checks secondary sensor
// Behavior 'cascade:confirm_alert' confirms with both sensors

Pattern 3: Adaptive Threshold System

csharp
// Create sensor
sensors.CreateSensor("adaptiveSensor", SensorDataType.Float, ...);

// Initial conservative thresholds
sensors.SetSensorValueBounds("adaptiveSensor", 0f, 50f);

// Runtime threshold adjustment based on conditions
void AdaptThresholds(float environmentalFactor) {
    float newMax = 50f * environmentalFactor;
    sensors.SetSensorValueBounds("adaptiveSensor", 0f, newMax);
    
    // Triggers now use adapted bounds
}

Pattern 4: Sensor Fusion with Multiple Triggers

csharp
// Create multiple sensors
sensors.CreateSensor("sensor_a", SensorDataType.Float, ...);
sensors.CreateSensor("sensor_b", SensorDataType.Float, ...);
sensors.CreateSensor("sensor_c", SensorDataType.Float, ...);

// Each sensor triggers fusion behavior with different weights
var sensorA = sensors.GetSensorManager().GetSensor("sensor_a");
sensorA.AddBehaviorTrigger("fusion", "combine_readings", 
    TriggerCondition.Deviation, 1.0f, "$@sensor_a", "Sensor A changed");

var sensorB = sensors.GetSensorManager().GetSensor("sensor_b");
sensorB.AddBehaviorTrigger("fusion", "combine_readings", 
    TriggerCondition.Deviation, 0.8f, "$@sensor_b", "Sensor B changed");

var sensorC = sensors.GetSensorManager().GetSensor("sensor_c");
sensorC.AddBehaviorTrigger("fusion", "combine_readings", 
    TriggerCondition.Deviation, 0.6f, "$@sensor_c", "Sensor C changed");

// Behavior 'fusion:combine_readings' processes all sensor values
// Variables $@sensor_a, $@sensor_b, $@sensor_c available in behavior

Best Practices

1. Choose the Right API for Your Deployment

Enterprise/IoT Applications:

  • Use ApiSensors() for full feature set
  • Enable thin logging for efficient storage
  • Let threading auto-detect platform capabilities

Real-Time/Control Systems:

  • Use ApiSensorsZeroAlloc() for deterministic performance
  • Configure lock-free ring buffers for MilSpec compliance
  • Monitor latency with GetSensorLatencyMs()

2. Leverage Behavior Triggers for Proactive AI

Don't do this (reactive):

csharp
// Constant polling and inference (inefficient)
while (true) {
    float temp = sensors.GetSensorValue<float>("temp");
    string response = core.ApiBrain().GetResponse($"temperature is {temp}");
    // CPU waste, high latency, brittle logic
}

Do this (proactive):

csharp
// Event-driven behavior trigger (efficient)
var sensor = sensors.GetSensorManager().GetSensor("temp");
sensor.AddBehaviorTrigger("monitoring", "temp_response", 
    TriggerCondition.Deviation, 1.0f, "$@temp", "Temperature changed");
sensors.ActivateSensor("temp");
// Zero CPU waste, instant response, declarative logic

3. Use Async API for Event-Driven Control

For control loops that wait for sensor changes:

csharp
// Event-driven: fires immediately on sensor update
while (running) {
    float position = await sensors.WaitForSensorUpdateAsync<float>("servo");
    CalculateControl(position);  // Process immediately, no polling delay
}

For conditional waits:

csharp
// Wait until sensor meets condition
float targetValue = await sensors.WaitForSensorConditionAsync<float>(
    "sensor", value => value > threshold, timeoutMs: 5000);

4. Configure Deviation-Based Logging

Reduce log volume by 90%+ while capturing significant events:

csharp
// Thin logging: log only when temperature deviates by 0.5°C
sensors.SetSensorLoggingMode("temp", SensorLoggingMode.Thin);
sensors.SetSensorMaxDeviation("temp", 0.5);

// Bulk configuration
sensors.SetAllSensorsLoggingMode(SensorLoggingMode.Thin);
sensors.SetAllSensorsMaxDeviation(0.1);

5. Monitor Connection Pool and Threading

Check system health:

csharp
// Connection pool statistics
Dictionary<string, object> poolStats = sensors.GetConnectionPoolStatistics();
Console.WriteLine($"Active connections: {poolStats["ActiveConnections"]}");

// Threading mode
SensorThreadingMode mode = sensors.GetThreadingMode();
int threshold = SilviaApiSensors.GetThreadingThreshold();
Console.WriteLine($"Threading: {mode}, Threshold: {threshold}");

// Logging statistics
Dictionary<string, string> logStats = sensors.GetSensorLoggingStatistics();

6. Handle Brain Reloads Gracefully

Preserve sensor connections during brain updates:

csharp
// Before brain reload
sensors.CleanupInactiveSensors();  // Reset sensor states, keep connections

// Brain reload automatically calls:
// sensors.OnBrainReload();  // Handles threading/connection cleanup

// After reload, sensors reconnect using pooled connections

7. Integrate with Unity FixedUpdate

For Unity applications, sensors automatically coordinate with FixedUpdate:

csharp
// SILVIA detects FixedUpdate and uses Piggyback mode for coordination
// No configuration needed - automatic synchronization

// Check FixedUpdate state
bool fixedUpdateActive = core.FixedUpdateActive;

8. Use Variable Auto-Sync Appropriately

For low-frequency sensors (default):

csharp
// Immediate variable sync (default)
sensors.SetSensorAutoSyncToVariable("temp", true);

For high-frequency sensors (optimization):

csharp
// Batch variable sync only (reduces overhead)
sensors.SetSensorAutoSyncToVariable("highSpeedSensor", false);

Common Pitfalls and Solutions

Pitfall 1: Setting Ring Buffer Mode After Activation

Wrong:

csharp
sensors.ActivateSensor("sensor");
sensors.SetSensorRingBufferMode("sensor", RingBufferMode.LockFree); // Won't work!

Correct:

csharp
sensors.CreateSensor("sensor", ...);
sensors.SetSensorRingBufferMode("sensor", RingBufferMode.LockFree); // Set BEFORE activation
sensors.ActivateSensor("sensor");

Pitfall 2: Using Async API in Unity Update Loop

Wrong:

csharp
async void Update() {
    // This will freeze Unity!
    float value = await sensors.WaitForSensorUpdateAsync<float>("sensor");
}

Correct:

csharp
void Update() {
    // Use synchronous API in Unity Update()
    if (sensors.IsSensorActive("sensor")) {
        float value = sensors.GetSensorValue<float>("sensor");
    }
}

Pitfall 3: Forgetting to Set Value Bounds for Triggers

Wrong:

csharp
// No bounds set!
sensor.AddBehaviorTrigger("alerts", "too_high", 
    TriggerCondition.GreaterThanMax, 1.0f, "$@sensor", "Alert");
// Trigger will never fire - no max defined

Correct:

csharp
sensors.SetSensorValueBounds("sensor", 0f, 100f); // Define bounds first
sensor.AddBehaviorTrigger("alerts", "too_high", 
    TriggerCondition.GreaterThanMax, 1.0f, "$@sensor", "Alert");

Pitfall 4: Excessive Logging Without Deviation Thresholds

Wrong:

csharp
// Verbose logging creates massive data floods
sensors.SetSensorLoggingMode("sensor", SensorLoggingMode.Verbose);
// 100Hz sensor = 360,000 log entries per hour!

Correct:

csharp
// Thin logging with deviation threshold
sensors.SetSensorLoggingMode("sensor", SensorLoggingMode.Thin);
sensors.SetSensorMaxDeviation("sensor", 0.5);
// Logs only when value changes significantly (90%+ reduction)

Performance Benchmarks

Enterprise API Performance

OperationLatencyMemory Impact
CreateSensor~1msVariable allocation
GetSensorValue~0.1msMay allocate
UpdateAllSensors (100 sensors)~10msModerate GC pressure
Behavior Trigger Evaluation~0.05msMinimal

Zero-Alloc API Performance

OperationLatencyMemory Impact
CreateSensor~0.5msPre-allocation only
GetSensorValue~0.01msZero allocation
UpdateAllSensors (100 sensors)~5msZero GC pressure
Lock-Free Ring Buffer Read<100μsZero allocation, deterministic

Threading Performance

ModeSensor CountCPU UsageUpdate Rate
Piggyback1-20Minimal (~1%)Tied to core timer (16-20ms)
Pooled20-100Moderate (~5%)Adaptive (10-100ms)
Independent100+Higher (~10%)High-frequency (10ms)

Remarks

SILVIA's Sensor I/O API represents a fundamental shift from reactive to proactive AI architecture. By elevating sensors to first-class cognitive citizens with behavior-triggering capabilities, SILVIA eliminates the traditional polling/inference bottleneck and enables true event-driven intelligence.

Key Innovations:

  1. Proactive Behavior Triggers - Sensors fire behaviors directly when conditions are met, no inference needed
  2. Dual-Architecture Design - Enterprise features OR MilSpec zero-allocation performance, same API
  3. Intelligent Threading - Auto-detects platform capabilities (IoT → Server) and optimizes automatically
  4. $@ Variable Integration - Automatic brain variable creation and synchronization
  5. Deviation-Based Logging - Smart logging reduces storage by 90%+ while capturing all significant events
  6. Connection Pooling - Efficient network resource usage with automatic connection reuse
  7. Async Event-Driven API - Zero-polling control loops with ValueTask optimization
  8. CLI Integration - Conversational sensor-to-behavior authoring in minutes

The Result: Hardware integration that was once days of polling logic and brittle state machines is now minutes of declarative trigger configuration and CLI-based behavior authoring. This is the foundation for next-generation AI-driven physical systems: autonomous, proactive, and event-driven from sensor to cognition.


© Copyright Cognitive Code Corp. 2007-2026

SILVIA is a registered Trademark of Cognitive Code Corp.

SILVIA is a registered Trademark of Cognitive Code Corp.