Skip to content

Source files: 3 | Classes: 23 | Methods: 7 | Enums: 12


GTOS.Sensors

DatabaseFieldMeta

struct

Database field metadata. Parallel arrays avoid Dictionary overhead.

Source: SensorsProtocols.cs

Constants and Fields

Index

int

Name

char[]

NameLen

int

Type

SensorDataType

DatabaseResultSet

struct

Complete database result set. Zero-allocation with parallel arrays.

Source: SensorsProtocols.cs

Constants and Fields

Affected

int

ErrCode

int

ErrLen

int

ErrMsg

char[]

ExecMs

long

FieldCount

int

Fields

DatabaseFieldMeta[]

RowCount

int

Rows

DatabaseRow[]

TxId

int

Methods

Error

DatabaseResultSet Error ( int code, string msg, int txId )

DatabaseRow

struct

Database row using parallel arrays for zero-allocation access.

Source: SensorsProtocols.cs

Constants and Fields

Count

int

IsNull

int[]

Lengths

int[]

Values

byte[][]

ModbusFrame

struct

Parsed Modbus frame (RTU or TCP)

Source: SensorsProtocols.cs

Constants and Fields

CoilDataByteCount

int

ExceptionCode

int

FunctionCode

ModbusFunctionCode

Quantity

int

RegisterData

int[]

RegisterDataCount

int

StartingAddress

int

MQTTMessage

struct

Parsed MQTT message

Source: SensorsProtocols.cs

Enumerations

SQLAttackPattern

SQL attack pattern types for injection detection.
Based on OWASP Top 10 and MITRE CWE database attack patterns.

Values: None, UnionBasedInjection, StackedQueries, CommentInjection, TautologyInjection, BlindSQLInjection, TimingAttack, BatchedCommands, SubqueryNesting, StoredProcedureAbuse, ErrorBasedExtraction, OutOfBandExtraction, AuthenticationBypass, PrivilegeEscalation, HexEncoding, UnicodeEvasion, WhitespaceEvasion, CaseEvasion, OracleSpecific, MySQLSpecific, SQLServerSpecific, PostgreSQLSpecific, InvalidParameter

SQLKeywordCategory

Standard SQL keywords by category. Used for sentinel pattern matching.
Organized by function to enable fine-grained permission control.

Values: SelectKeywords, InsertKeywords, UpdateKeywords, DeleteKeywords, CreateKeywords, AlterKeywords, DropKeywords, TruncateKeywords, GrantKeywords, RevokeKeywords, TransactionKeywords, ConditionalKeywords, AggregateKeywords, SetOperationKeywords, SubqueryKeywords, SystemFunctions, FileFunctions, NetworkFunctions, CommentMarkers, StringDelimiters, LogicalOperators, ComparisonOperators, InvalidParameter

SQLOperationType

SQL operation types for database query classification.
Used by sensor routing layer to validate behavior permissions.

Values: Unknown, Select, Insert, Update, Delete, Create, Drop, Alter, Truncate, Execute, Call, Grant, Revoke, InvalidParameter

Constants and Fields

Duplicate

int

MessageId

int

MessageType

MQTTMessageType

Payload

byte[]

PayloadLength

int

QoS

int

Retain

int

Topic

char[]

TopicLength

int

ProtocolHTTPResponse

struct

Parsed HTTP response from raw byte stream

Source: SensorsProtocols.cs

Constants and Fields

BodyByteCount

int

BodyBytes

byte[]

ResponseTimeMs

long

StatusCode

int

SensorsProtocolParser

static class

Protocol parsing calculations (Sensors.Protocols subdomain)
Converts raw bytes from SensorIO into structured protocol frames.
FOR MANUFACTURERS:
To integrate your sensor/device protocol:
1. Define your protocol frame struct (see ProtocolHTTPResponse, ModbusFrame examples)
2. Write a parser method: public static YourFrame ParseYourProtocol(byte[] rawBytes, int byteCount)
3. Use for loops with explicit bounds (NO while loops without safety valves)
4. Document start/stop bits, framing, checksums in XML comments
5. Return structured data (ints, floats, enums) - NOT strings or dynamic types
EXAMPLE MANUFACTURER INTEGRATION:
Your device sends: [0x02][DataLength][Data...][Checksum][0x03]
public struct YourDeviceFrame {
public int DataLength;
public byte[] Data;
public int Checksum;
public int ChecksumValid; // 1 = valid, 0 = invalid
}
public static YourDeviceFrame ParseYourProtocol(byte[] rawBytes, int byteCount) {
// Validate start byte (0x02)
if (rawBytes[0] != 0x02) { return new YourDeviceFrame { ChecksumValid = 0 }; }
// Parse data length
int dataLength = rawBytes[1];
// Copy data - safety valve: max dataLength or remaining bytes
byte[] data = new byte[dataLength];
int maxCopy = (dataLength < byteCount - 3) ? dataLength : (byteCount - 3);
for (int i = 0; i < maxCopy; i++) {
data[i] = rawBytes[2 + i];
}
// Validate checksum and stop byte
int checksum = rawBytes[2 + dataLength];
int stopByte = rawBytes[3 + dataLength];
int checksumValid = (stopByte == 0x03) ? 1 : 0;
return new YourDeviceFrame {
DataLength = dataLength,
Data = data,
Checksum = checksum,
ChecksumValid = checksumValid
};
}
KEY RULES:
- Use for loops with explicit max iterations (safety valves)
- Return structs, not classes (zero allocation)
- Use int for success/failure flags (1/0, not bool for MIL-SPEC)
- Document byte positions, bit fields, endianness in XML comments
- No exceptions, no string parsing, no dynamic types

Source: SensorsProtocols.cs

Methods

ParseHTTPProtocol

ProtocolHTTPResponse ParseHTTPProtocol ( byte[] rawBytes, int byteCount )

Parse HTTP protocol from raw byte stream.
PROTOCOL SPECIFICATION:
HTTP/1.1 response format:
- Status line: "HTTP/1.1 [StatusCode] [ReasonPhrase]\r\n"
- Headers: "[Key]: [Value]\r\n" (repeated)
- Empty line: "\r\n"
- Body: Raw bytes (length determined by Content-Length header or connection close)
PARSING STRATEGY:
1. Parse status line to extract status code (200, 404, 500, etc.)
2. Skip all headers (not parsed in this simplified version)
3. Extract body bytes
SAFETY VALVES:
- HTTP version string: max 20 characters
- Status code: max 3 digits
- Status line: max 100 characters
- Header count: max 100 headers
- Header line length: max 8192 characters (per HTTP spec)
BYTE POSITIONS:
- Bytes 0-8: "HTTP/1.1 " (or similar version)
- Bytes 9-11: Status code (e.g., "200")
- Bytes 12+: Reason phrase + headers + body
EXAMPLE INPUT:
"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<html>...</html>"
EXAMPLE OUTPUT:
StatusCode = 200
BodyBytes = "<html>...</html>"
BodyByteCount = [length of body]
PERFORMANCE:
- Zero allocation (except body byte array)
- O(n) time complexity where n = byteCount
- Typical parse time: ~5 μs for 1KB response
ERROR HANDLING:
- Returns StatusCode = -1 for invalid input
- Returns empty BodyBytes array for malformed responses
- No exceptions thrown
Raw HTTP response bytes from network
Number of valid bytes in rawBytes array
Parsed HTTP response with status code and body
This parser is simplified and does NOT extract headers.
For full header parsing, use CommsCoreAtomics.ParseHTML() after this.
MANUFACTURER NOTES:
If your device uses HTTP-like framing but custom headers:
1. Copy this method as a template
2. Modify header parsing section to extract your custom headers
3. Add header fields to your custom response struct
4. Document your header format in XML comments

SQLKeywordLibrary

struct

SQL keyword library for all major database protocols.
Used by sentinel for fine-grained permission validation.
Organized by category (DQL, DML, DDL, DCL) per SQL standard.

Source: SensorsProtocols.cs

Methods

Initialize

void Initialize ( )

Initialize keyword library. Call once at startup.

SQLQueryFrame

struct

SQL query frame for database sensors. Universal structure for all database protocols.
Designed for zero-allocation routing through sensor API.
USAGE:
SQLQueryFrame frame = SQLQueryFrame.Create(
ProtocolType.Oracle_TNS,
"SELECT * FROM customers WHERE id = @id",
"Server=localhost;Database=mydb;",
5000, // timeout ms
12345, // behavior ID
67890 // transaction ID
);
SECURITY:
Connection strings are automatically masked for logging (passwords replaced with asterisks).
Behavior ID is embedded for validation through SILVIA security layer.

Source: SensorsProtocols.cs

Constants and Fields

BehaviorId

int

ConnectionStringLength

int

OperationType

SQLOperationType

ParameterCount

int

Protocol

GTProtocolType

QueryLength

int

TimeoutMs

int

TransactionId

int

UniversalDatabaseHandler

static class

Universal database handler. Replaces Dapper entirely.
Supports Oracle, PostgreSQL, MySQL, SQL Server via ADO.NET.
Provider-aware column name normalization (Oracle=UPPER, Postgres=lower).

Source: SensorsProtocols.cs

Methods

Execute

DatabaseResultSet Execute ( SQLQueryFrame frame, SilviaCore core )

GTOS.Sensors.CoreAtomics

ConnectionResult

readonly struct

Result of a connection attempt with diagnostic information.

Source: SensorsCoreAtomics.cs

Constants and Fields

ConnectionId

readonly string

ConnectTimeMs

readonly double

ErrorMessage

readonly string

Success

readonly bool

Type

readonly ConnectionType

HTTPRequestData

struct

HTTP request data returned by Read()

Source: SensorsCoreAtomics.cs

Constants and Fields

BodyBytes

byte[]

BodyLength

int

Context

System.Net.HttpListenerContext

Method

string

SensorId

int

Url

string

HTTPResponseData

struct

HTTP response data for Write()
Call SerializeHTTPResponseData() to convert to byte[] for WriteSensor()

Source: SensorsCoreAtomics.cs

Constants and Fields

BodyBytes

byte[]

BodyLength

int

ContentType

string

Context

System.Net.HttpListenerContext

StatusCode

int

Methods

Serialize

byte[] Serialize ( )

Serialize to byte array for WriteSensor()

SensorBehaviorTrigger

struct

Behavior trigger configuration for sensor-driven SILVIA behaviors.
WHAT IT IS:
A struct that defines when and how a SILVIA behavior should be triggered
based on sensor readings. Connects the platform-agnostic sensor core
to SILVIA's cognitive behavior system.
WHY IT EXISTS:
Traditional automation systems use "ladder logic" or scripting for triggers.
These are prone to:
- Code injection attacks (arbitrary script execution)
- Undefined behavior (script errors crash the system)
- Performance unpredictability (interpreted scripts)
- Maintenance nightmares (spaghetti logic across hundreds of PLCs)
This system uses:
✓ Type-safe enums (no code injection possible)
✓ Compile-time validation (no runtime script errors)
✓ Deterministic performance (no interpretation overhead)
✓ Centralized management (all triggers in one API)
ARCHITECTURE:
Sensors (Platform-Agnostic) → Triggers (This File) → SILVIA Behaviors (Cognitive)
This separation allows:
- Sensors to run standalone (no SILVIA dependency)
- Behaviors to be optional (pure data collection mode)
- Different behavior engines to be swapped (SILVIA, custom, etc.)
FIELDS:
- BehaviorGroup: Target behavior group (e.g., "sensors", "alarms", "safety")
- BehaviorName: Target behavior name (e.g., "temperatureTooHigh", "doorOpened")
- Condition: Safe predefined condition from TriggerCondition enum
- CustomCondition: Advanced function pointer (MISSION_LOGIC builds only)
- Probability: Jump probability 0.0-1.0 (1.0 = always, 0.5 = 50% chance)
- VariableToSet: Optional SILVIA variable to set with sensor value ($@sensorId)
- TriggerDescription: Human-readable description for logging
- ExecutionMode: How trigger fires (EveryTime, OnceUntilReset, OnEnterOnly, OnExitOnly)
- DesiredValue: Target value for comparison conditions
- DeviationThreshold: Allowed deviation from desired value
- PercentThreshold: Percent change threshold
- ExpectedString: Expected string value for string conditions
- LastConditionState: Previous condition evaluation (for edge detection)
- HasTriggered: Has triggered since last reset (for OnceUntilReset mode)
- LastTriggerTime: When trigger last fired
- LastTriggerLatencyMs: Latency at last trigger (for control system timing)
- LastValue: Previous value (for change detection)
EXAMPLES:
Overpressure Alarm (Simple Threshold):
<br>var trigger = new SensorBehaviorTrigger(<br>group: "safety",<br>name: "overpressureAlarm",<br>condition: TriggerCondition.GreaterThanMax,<br>probability: 1.0f,<br>variableToSet: "$@pressure",<br>description: "Pressure exceeds maximum safe limit"<br>);<br>
Temperature Control (Deviation from Setpoint):
<br>var trigger = new SensorBehaviorTrigger(<br>group: "control",<br>name: "temperatureDeviation",<br>condition: TriggerCondition.OutsideDesiredRange,<br>probability: 1.0f,<br>variableToSet: "$@temperature",<br>description: "Temperature deviation from setpoint",<br>executionMode: TriggerExecutionMode.EveryTime,<br>desiredValue: 72.0, // 72°F setpoint<br>deviationThreshold: 2.0 // ±2°F tolerance<br>);<br>
Door Opened Alert (Edge Detection):
<br>var trigger = new SensorBehaviorTrigger(<br>group: "security",<br>name: "doorOpened",<br>condition: TriggerCondition.IsTrue,<br>probability: 1.0f,<br>variableToSet: "$@doorState",<br>description: "Security door opened",<br>executionMode: TriggerExecutionMode.OnEnterOnly // Fire once on open<br>);<br>
Critical Fault Latch (One-Shot):
<br>var trigger = new SensorBehaviorTrigger(<br>group: "safety",<br>name: "criticalFault",<br>condition: TriggerCondition.GreaterThanMax,<br>probability: 1.0f,<br>variableToSet: "$@faultCode",<br>description: "Critical fault detected - requires manual reset",<br>executionMode: TriggerExecutionMode.OnceUntilReset // Latch until reset<br>);<br>
SECURITY:
✓ No code injection - all conditions are compile-time enums
✓ No reflection or eval() - type-safe only
✓ CustomFunction gated by #if MISSION_LOGIC (development builds only)
✓ Probability prevents deterministic attacks (1.0 = always, <1.0 = probabilistic)
✓ All execution paths validated at compile-time
PERFORMANCE:
- Struct (value type) - allocated on stack, no GC
- Size: ~120 bytes per trigger
- Evaluation: <1 microsecond typical
- Zero allocations in hot path
MILSPEC COMPLIANCE:
✓ Deterministic execution time
✓ No unbounded loops
✓ No dynamic allocation
✓ No blocking operations
✓ Safe for real-time control loops

Source: SensorsCoreAtomics.cs

Constants and Fields

BehaviorGroup

string

BehaviorName

string

Condition

TriggerCondition

DesiredValue

double

DeviationThreshold

double

ExecutionMode

TriggerExecutionMode

ExpectedString

string

HasTriggered

bool

LastConditionState

bool

LastTriggerLatencyMs

double

LastTriggerTime

DateTime

LastValue

object

PercentThreshold

double

Probability

float

TriggerDescription

string

VariableToSet

string

SensorCalculations

static class

Core atomic calculations for industrial sensor networks.
DESIGN PRINCIPLES:
- Zero allocation: No heap allocations in hot paths
- Inline optimization: All methods use AggressiveInlining
- MIL-SPEC compliant: Deterministic, bounded execution time
- Platform-agnostic: No OS or framework dependencies
- Thread-safe: Pure functions, no shared state
REPLACES:
- Siemens TIA Portal math blocks
- Allen-Bradley RSLogix instructions
- LabVIEW math nodes
- SCADA formula engines
ADVANTAGES OVER LEGACY SYSTEMS:
✓ 10-100x faster than interpreted ladder logic
✓ Type-safe (compile-time validation)
✓ No licensing fees (Siemens charges $10K+ per seat)
✓ Open, auditable code (no vendor black boxes)
✓ Cross-platform (Windows, Linux, embedded)

Source: SensorsCoreAtomics.cs

SensorConstants

static class

MIL-SPEC Constants for sensor calculations and validation.
WHAT IT PROVIDES:
Universal constants for sensor math, timing, latency calculations, and validation.
These are the bedrock values used throughout the sensor system for consistency.
CONSTANTS:
- EPSILON: Floating-point comparison tolerance (0.000001)
- MAX_LATENCY_MS: Maximum acceptable sensor latency (1000ms)
- RING_BUFFER_SIZE: Default ring buffer capacity (64 readings)
- MAX_SENSOR_VALUE_SIZE: Maximum sensor value byte size (4096 bytes)
- TIMEOUT_DEFAULT_MS: Default connection timeout (5000ms)
STANDARDS:
- MIL-STD-882E: Safety-critical system standards
- NIST SP 800-53: Cybersecurity controls
- IEC 61508: Functional safety for industrial systems

Source: SensorsCoreAtomics.cs

Enumerations

ConnectionType

Connection types for different hardware architectures.
WHAT IT DEFINES:
The physical/logical connection method between sensor and controller.
Each type has different protocols, latency, and reliability characteristics.
TYPES:
- Direct: Memory-mapped I/O, GPIO, registers (embedded systems)
- Serial: RS-232, RS-485, UART (legacy/industrial)
- Network: TCP/UDP, Ethernet, Wi-Fi (modern/IoT)
- CAN: Controller Area Network (automotive, industrial)
- ModBus: Modbus RTU/TCP (industrial automation standard)
- Custom: User-defined protocol handlers
USE CASES:
- Direct: Embedded sensors on same PCB, FPGA I/O, microcontroller GPIO
- Serial: Legacy PLCs, Arduino, older industrial sensors
- Network: IoT devices, distributed sensors, cloud logging
- CAN: Vehicles, robotics, distributed control systems
- ModBus: Factory automation, SCADA systems, building management
- Custom: Proprietary protocols, research equipment, specialized hardware
LATENCY CHARACTERISTICS:
- Direct: <1 μs (nanosecond-scale for memory-mapped)
- Serial: 1-10 ms (depends on baud rate)
- Network: 1-100 ms (depends on network congestion)
- CAN: <1 ms (priority-based arbitration)
- ModBus: 10-100 ms (polling-based protocol)
- Custom: Application-specific
RELIABILITY:
- Direct: Highest (hardware failure only)
- Serial: High (CRC checksums typical)
- Network: Medium (packet loss possible)
- CAN: Very High (bit stuffing, CRC, ACK)
- ModBus: High (CRC checksums)
- Custom: Application-specific

Values: Direct, Serial, Network, CAN, ModBus, Custom

RefreshMode

Refresh timing synchronization options for sensor updates.
WHAT IT DEFINES:
How frequently sensors are polled and when updates occur.
Critical for real-time systems, control loops, and performance tuning.
MODES:
- MilSpec: Military specification timing (deterministic, highest priority)
- FixedUpdate: Synchronized to physics/control loop (50-60 Hz typical)
- CustomHz: User-defined frequency (0.1 Hz to 10 kHz)
USE CASES:
- MilSpec: Safety-critical systems, flight controls, medical devices
- FixedUpdate: PID controllers, motion control, robotics
- CustomHz: Data logging, slow sensors (temperature), high-speed ADC
PERFORMANCE:
- MilSpec: Guaranteed deterministic latency, no jitter
- FixedUpdate: Low jitter, synchronized with system clock
- CustomHz: Configurable trade-off between latency and CPU usage
TIMING GUARANTEES:
- MilSpec: ±10 μs jitter max (with lock-free ring buffer)
- FixedUpdate: ±1 ms jitter typical
- CustomHz: Best-effort, depends on system load

Values: MilSpec, FixedUpdate, CustomHz

RingBufferMode

Ring buffer mode selection for sensor I/O.
WHAT IT DEFINES:
Whether to use locked (simple) or lock-free (MIL-SPEC) ring buffers.
This is THE critical choice for real-time systems.
MODES:
- Locked: Uses mutex/lock for thread safety (simple, safe)
- LockFree: Uses atomic operations and memory barriers (MIL-SPEC)
LOCKED MODE:
Pros:
✓ Simple implementation, easy to verify
✓ Supports multiple readers and writers
✓ No thread restrictions
✓ Accurate count tracking
Cons:
✗ May block threads under contention
✗ Variable latency due to lock acquisition
✗ Priority inversion risk in RT systems
✗ Not suitable for hard real-time (DO-178C Level A)
Use Cases:
- General-purpose sensor systems
- Development and testing
- Systems without hard real-time requirements
- Multiple reader/writer scenarios
LOCK-FREE MODE:
Pros:
✓ NEVER blocks - guaranteed non-blocking operation
✓ Deterministic latency - bounded worst-case timing
✓ No priority inversion - safe for RT schedulers
✓ Memory barrier synchronization - correct ordering
Cons:
✗ SPSC only - single producer, single consumer required
✗ More complex implementation
✗ Count may be slightly inaccurate (lock-free read)
Use Cases:
- MIL-STD-882E systems
- DO-178C Level A/B aviation software
- Hard real-time control loops
- Safety-critical medical devices
- High-frequency trading (low latency critical)
SELECTION STRATEGY:
- Default: Locked mode (safe for all scenarios)
- MIL-SPEC: Lock-free mode (for certification)
- High-frequency: Lock-free mode (for performance)
- Multi-reader/writer: Locked mode (only option)
PERFORMANCE COMPARISON:
- Locked: ~100-500ns per operation (with contention: 1-10μs)
- Lock-free: ~50-100ns per operation (deterministic)
CERTIFICATION:
- Locked: Suitable for most commercial applications
- Lock-free: Required for DO-178C Level A/B, MIL-STD-882E

Values: Locked, LockFree

SensorDataType

Data types supported by the sensor I/O system.
WHAT IT DEFINES:
The fundamental data types that sensors can read or actuators can write.
Each type has specific serialization, validation, and processing rules.
TYPES:
- Bit: Boolean on/off, true/false (1 bit, serialized as 1 byte)
- Byte: Single byte value 0-255 (8 bits)
- ByteStream: Array of bytes, any length (variable size)
- Int: 32-bit signed integer (-2.1B to +2.1B)
- Float: 32-bit IEEE 754 floating point (±3.4E+38, 7 digits precision)
- Double: 64-bit IEEE 754 floating point (±1.7E+308, 15 digits precision)
- BigInt: Arbitrary precision integer (unlimited size)
- String: UTF-8 text data (variable length)
USE CASES:
- Bit: Switches, relays, digital I/O, door sensors, limit switches
- Byte: Low-resolution sensors, status codes, enum values
- ByteStream: Images, binary protocols, raw data buffers
- Int: Counters, timers, discrete measurements
- Float: Temperature, pressure, voltage, current (most common)
- Double: High-precision scientific measurements, GPS coordinates
- BigInt: Cryptographic operations, large counters
- String: JSON data, text commands, human-readable status
SERIALIZATION:
Each type has defined binary serialization for network transmission:
- Bit → 1 byte (0x00 or 0x01)
- Byte → 1 byte
- Int → 4 bytes (little-endian)
- Float → 4 bytes (IEEE 754)
- Double → 8 bytes (IEEE 754)
- String → UTF-8 bytes + null terminator
- ByteStream → Raw bytes (length-prefixed in protocols)
PERFORMANCE:
Enum comparison is O(1), faster than string-based type systems.
Type validation happens at compile-time, not runtime.

Values: Bit, Byte, ByteStream, Int, Float, Double, BigInt, String

SensorDirection

Data flow direction for sensor I/O.
WHAT IT DEFINES:
Whether a device reads data (sensor), writes data (actuator), or both.
Enforces access control and prevents invalid operations.
DIRECTIONS:
- InputOnly: Read-only sensor (thermometer, pressure gauge, switch)
- OutputOnly: Write-only actuator (LED, motor, valve)
- InputOutput: Bidirectional device (servo with position feedback, smart display)
USE CASES:
- InputOnly: Temperature sensors, pressure transducers, flow meters, limit switches
- OutputOnly: LEDs, relays, solenoids, heaters, simple motors
- InputOutput: Servos, VFDs, smart actuators, displays with touch input
SECURITY:
Direction enforcement prevents:
- Reading from write-only devices (security breach attempt)
- Writing to read-only devices (safety violation)
- Unauthorized control of critical actuators
PERFORMANCE:
Direction checks are compile-time validated where possible.
Runtime checks are single enum comparison (nanoseconds).

Values: InputOnly, OutputOnly, InputOutput

SensorLoggingMode

Sensor logging modes for data capture and analysis.
WHAT IT DEFINES:
How much data is logged and when logging occurs.
Critical for compliance, debugging, and performance optimization.
MODES:
- Off: No logging (production default for high-performance systems)
- Thin: Deviation-based logging (log only significant changes)
- Verbose: Log all sensor updates (debugging, compliance, forensics)
USE CASES:
- Off: Real-time control systems, high-frequency sensors
- Thin: Production monitoring, slow-changing sensors (temperature)
- Verbose: Commissioning, debugging, regulatory compliance (FDA, FAA)
STORAGE IMPACT:
- Off: 0 bytes/sensor
- Thin: ~10-100 bytes/hour (depends on deviation threshold)
- Verbose: ~1-10 MB/hour (depends on sensor frequency)
PERFORMANCE:
- Off: Zero overhead
- Thin: Minimal overhead (deviation calculation + occasional write)
- Verbose: High overhead (write every update)
COMPLIANCE:
Many industries require logging:
- FDA 21 CFR Part 11: Pharmaceutical manufacturing
- FAA DO-178C: Aviation software
- ISO 13485: Medical device manufacturing
- IEC 61508: Functional safety

Values: Off, Thin, Verbose

SensorType

Sensor types for the unified sensor interface.
WHAT IT DEFINES:
All sensor types in the SILVIA ecosystem, both physical and logical.
Network protocols and storage devices are treated as "sensors" that provide data.
PHYSICAL SENSORS (0-99):
- Temperature, Pressure, Flow, Level, Weight, Humidity, Light, Sound, etc.
- Real-world measurements from physical transducers
NETWORK PROTOCOL "SENSORS" (100-199):
- HTTP, HTTPS, FTP, SMTP, WebSocket, MQTT, etc.
- Network connections that provide data streams
STORAGE "SENSORS" (200-299):
- LocalDisk, NetworkDrive, CloudStorage, RAMDisk, etc.
- Storage devices that provide file data
KEY INSIGHT:
A web server, hard drive, and temperature sensor all provide data through
the same unified interface: ReadSensor(sensorId) returns byte stream.
This abstraction enables CommsNetworks to work seamlessly across all data sources.

Values: Temperature, Pressure, Flow, Level, Weight, Humidity, Light, Sound, Vibration, Position, Velocity, Acceleration, Force, Torque, Voltage, Current, Power, Frequency, pH, Conductivity, HTTP, HTTPS, WebSocket, FTP, FTPS, SFTP, SMTP, POP3, IMAP, MQTT ...+56 more

TriggerCondition

Safe, predefined trigger conditions that eliminate code injection risks.
WHAT IT DEFINES:
All possible condition checks for sensor-driven triggers.
These are compile-time safe - NO eval(), NO reflection, NO code injection.
WHY THIS EXISTS:
Legacy systems allow arbitrary code execution for triggers:
- Siemens: Allows scripting in triggers (security nightmare)
- Allen-Bradley: Ladder logic can execute arbitrary code
- LabVIEW: VisualBasic scripting in events
This system uses ONLY pre-defined, type-safe conditions.
Impossible to inject malicious code or crash the system.
CONDITION CATEGORIES:
Threshold Comparisons (against MinValue/MaxValue):
- GreaterThanMax: value > MaxValue (over-limit alarm)
- LessThanMin: value < MinValue (under-limit alarm)
- EqualToMax: value == MaxValue (at maximum)
- EqualToMin: value == MinValue (at minimum)
- OutsideMinMax: value < MinValue OR value > MaxValue (out of bounds)
- InsideMinMax: value >= MinValue AND value <= MaxValue (within bounds)
Desired Value Comparisons (against DesiredValue setpoint):
- GreaterThanDesired: value > DesiredValue (above target)
- LessThanDesired: value < DesiredValue (below target)
- EqualToDesired: value == DesiredValue (at target)
- OutsideDesiredRange: |value - DesiredValue| > DeviationThreshold (off-target)
- InsideDesiredRange: |value - DesiredValue| <= DeviationThreshold (on-target)
Boolean Conditions (for digital I/O):
- IsTrue: value == true (switch closed, sensor active)
- IsFalse: value == false (switch open, sensor inactive)
String Conditions (for text/JSON data):
- StringEquals: value == ExpectedString (exact match)
- StringNotEquals: value != ExpectedString (mismatch)
- StringContains: value.Contains(ExpectedString) (substring)
- StringEmpty: string.IsNullOrEmpty(value) (no data)
- StringNotEmpty: !string.IsNullOrEmpty(value) (has data)
Change Detection (rate-of-change monitoring):
- DeviationExceeds: |value - DesiredValue| > DeviationThreshold (absolute change)
- PercentChangeExceeds: |(value - PreviousValue) / PreviousValue| > PercentThreshold
USE CASES:
- GreaterThanMax: Overpressure alarm, overtemperature shutdown
- LessThanMin: Low pressure warning, low fuel alert
- OutsideMinMax: Process control alarm (out of tolerance)
- InsideDesiredRange: PID controller stability verification
- PercentChangeExceeds: Sudden change detection (fault, crash, spike)
- StringContains: Error message detection in device responses
SECURITY:
✓ No dynamic code execution
✓ No reflection or eval()
✓ No string-to-code compilation
✓ All conditions validated at compile-time
✓ Impossible to inject malicious code
✓ Safe for use with untrusted sensor data
PERFORMANCE:
Each condition evaluates in O(1) time.
No allocations, no string parsing, no interpretation.
Typical evaluation time: <100 nanoseconds.
EXTENSIBILITY:
For advanced users requiring custom logic:
- CustomFunction available in MISSION_LOGIC builds only
- Requires code review and security audit
- Not available in production builds

Values: GreaterThanMax, LessThanMin, EqualToMax, EqualToMin, OutsideMinMax, InsideMinMax, GreaterThanDesired, LessThanDesired, EqualToDesired, OutsideDesiredRange, InsideDesiredRange, IsTrue, IsFalse, StringEquals, StringNotEquals, StringContains, StringEmpty, StringNotEmpty, DeviationExceeds, PercentChangeExceeds, CustomFunction

TriggerExecutionMode

Trigger execution modes for event-driven behavior.
WHAT IT DEFINES:
How often a trigger fires when its condition is met.
Critical for avoiding trigger spam and implementing state machines.
MODES:
- EveryTime: Fire on every evaluation where condition is true (default)
- OnceUntilReset: Fire once, then not again until condition becomes false (latch)
- OnEnterOnly: Fire only on false→true transition (edge detection)
- OnExitOnly: Fire only on true→false transition (exit detection)
USE CASES:
- EveryTime: Continuous monitoring, alarms, real-time tracking
- OnceUntilReset: Fault detection, one-shot alarms, state machines
- OnEnterOnly: Event detection (door opened, button pressed)
- OnExitOnly: Event completion (door closed, process finished)
EXAMPLE SCENARIOS:
- Temperature alarm (EveryTime): Alert every second while over limit
- Overheat shutdown (OnceUntilReset): Shutdown once, require manual reset
- Door opened (OnEnterOnly): Trigger security alert once when door opens
- Process complete (OnExitOnly): Start next step when current completes
STATE MACHINE PATTERNS:
OnEnterOnly + OnExitOnly enable clean state transitions:
- Enter State A: OnEnterOnly trigger fires
- Stay in State A: No triggers fire
- Exit State A: OnExitOnly trigger fires
- Enter State B: Next OnEnterOnly trigger fires
PERFORMANCE:
State tracking adds minimal overhead (~8 bytes per trigger).
Evaluation is still O(1) comparison.

Values: EveryTime, OnceUntilReset, OnEnterOnly, OnExitOnly

Constants and Fields

EPSILON

const double

MAX_LATENCY_MS

const double

MAX_RECONNECT_ATTEMPTS

const int

MAX_SENSOR_VALUE_SIZE

const int

RECONNECT_INTERVAL_MS

const int

RING_BUFFER_SIZE

const int

TIMEOUT_DEFAULT_MS

const int

SensorPort

struct

Port configuration for sensor addressing.
WHAT IT IS:
Complete connection configuration for a sensor or actuator.
Defines how to connect (protocol, address, parameters).
FIELDS:
- Address: Primary address (IP:port, COM3, 0x40A0, etc.)
- SubAddress: Sub-address for multiplexed systems (register, channel, etc.)
- Type: Connection type (Serial, Network, CAN, ModBus, etc.)
- Parameters: Protocol-specific configuration (baud rate, timeout, etc.)
EXAMPLES:
Serial Connection:
<br>SensorPort port = new SensorPort("COM3", ConnectionType.Serial);<br>port.SetBaudRate(9600);<br>port.SetTimeout(1000);<br>
Network Connection:
<br>SensorPort port = new SensorPort("192.168.1.100:502", ConnectionType.ModBus);<br>port.SetTimeout(5000);<br>port.SetRegisterAddress(40001);<br>
CAN Bus:
<br>SensorPort port = new SensorPort("can0", ConnectionType.CAN);<br>port.SetCanId(0x123);<br>
PARAMETERS:
Common parameter keys:
- "BaudRate": Serial baud rate (9600, 115200, etc.)
- "Timeout": Connection timeout (milliseconds)
- "Register": ModBus register address
- "CanId": CAN bus identifier
- "Protocol": Network protocol (TCP/UDP)
- "DataFormat": Data format (Binary/JSON/XML)
SERIALIZATION:
Struct is marked [Serializable] for persistence and network transmission.

Source: SensorsCoreAtomics.cs

Constants and Fields

Address

string

SubAddress

string

Type

ConnectionType

SensorReadResult

readonly struct

Result of a sensor read operation with full telemetry.
WHAT IT CONTAINS:
Complete information about a sensor reading including value, timing, and status.
Enables full observability and debugging without separate logging calls.
FIELDS:
- Value: The actual sensor reading (object for flexibility)
- AcquisitionTime: When measurement was taken (Unix epoch seconds)
- ProcessingTime: When measurement was processed (Unix epoch seconds)
- LatencyMs: Acquisition-to-processing latency (milliseconds)
- IsValid: Whether reading is valid (false if timeout, error, etc.)
- ErrorMessage: Description of error if IsValid=false
USE CASES:
- Latency monitoring for control loop tuning
- Quality metrics for sensor network health
- Compliance logging (timestamp everything)
- Debugging timing issues
EXAMPLE:
<br>SensorReadResult result = ReadSensor(sensorId);<br>if (result.IsValid) {<br>float temperature = (float)result.Value;<br>if (result.LatencyMs > 10.0) {<br>// Latency too high, log warning<br>}<br>} else {<br>// Handle error: result.ErrorMessage<br>}<br>
PERFORMANCE:
Struct (value type) - allocated on stack, no GC pressure.
Total size: ~40 bytes (fits in single cache line).

Source: SensorsCoreAtomics.cs

Constants and Fields

AcquisitionTime

readonly double

ErrorMessage

readonly string

IsValid

readonly bool

LatencyMs

readonly double

ProcessingTime

readonly double

Value

readonly object

SensorsIO

static class

Universal sensor I/O dispatch system.
Routes sensor operations to platform-specific drivers via function pointers.
ARCHITECTURE:
This is the missing link between generic sensor API and platform-specific implementations.
Uses driver registry pattern with function pointer dispatch for zero-overhead routing.
DESIGN PRINCIPLES:
- Zero allocation: Function pointer arrays allocated once at startup
- Platform-agnostic: Conditional compilation selects appropriate drivers
- Type-safe: All drivers must implement defined delegates
- Extensible: New drivers registered without modifying core code
EXAMPLE FLOW:
1. Application calls: ReadSensor(42, SensorType.HTTP, port)
2. Dispatcher looks up: _readDrivers[(int)SensorType.HTTP]
3. Function pointer invoked: NetworkHTTPDriver.Read(42, port)
4. Driver implementation makes HTTP request
5. Result returned to application
PERFORMANCE:
- Array lookup: O(1) - single memory access
- Function pointer dispatch: ~1-2 CPU cycles
- Total overhead: <10 nanoseconds
PLATFORM INDEPENDENCE:
Different drivers registered via conditional compilation:
- Windows: WindowsGPIODriver, WindowsSerialDriver, etc.
- Linux: LinuxGPIODriver, LinuxSerialDriver, etc.
- Unity: UnityMouseDriver, UnityKeyboardDriver, etc.
- Network: Platform-agnostic (NetworkHTTPDriver works everywhere)

Source: SensorsCoreAtomics.cs

Methods

InitializeDrivers

void InitializeDrivers ( )

Initialize driver registry. Call once at startup.
Registers platform-specific drivers via conditional compilation.

SQLAttackDetector

static class

SQL attack pattern detector - GTOS 3-layer defense architecture.
LAYER 1: Command Enum Validation (Fast path - O(1) switch)
Check if SQL keywords are valid commands in dialect-specific enum
Flag dangerous categories (DDL/DCL) even if valid
LAYER 2: Symbolic Pattern Scan (Char-level, zero-alloc)
Detect injection punctuation: ; ' " -- /* union or 1=1
Static readonly patterns, no string allocation
LAYER 3: SILVIA Semantic (Optional - context-aware)
Pass to SILVIA absorber for semantic rejection
Loaded with attack vocabulary concepts
PERFORMANCE: 50-1800% faster than string.Contains() scanning
ACCURACY: Database-aware, fewer false positives
USAGE: DetectAttack(sql.AsSpan(), GTProtocolType.PostgreSQL_Wire)

Source: SQLCoreAtomics.cs

SQLVocabularyLoader

static class

SQL Command Vocabulary Loader - Dumps database-specific command enums into SILVIA's concept/binding system.
DESIGN PHILOSOPHY:
The SQL command enums (PostgreSQLCommand, OracleCommand, etc.) represent structured knowledge about
database query languages. By loading these into SILVIA's semantic network, we enable:
1. QUERY CONSTRUCTION: Build type-safe queries using bound concepts
2. SEMANTIC UNDERSTANDING: SILVIA can reason about database operations
3. SECURITY VALIDATION: Permission checks via concept bindings
4. CONVERSATIONAL INTERFACE: Natural language to SQL
SILVIA DEFAULT BINDING TYPES (Reference from SilviaBindings.cs):
HIERARCHICAL:
"root" - Root concept (weight: 0.0, invisible)
"trunk" - Main branch (weight: 0.0, visible)
"branch" - Sub-branch (weight: 0.0, invisible)
"child" - Child relationship (weight: 0.7, visible)
"parent" - Parent relationship (weight: 0.7, inverse of child)
"sibling" - Sibling relationship (weight: 0.35, visible)
SEMANTIC SIMILARITY:
"synonym" - Exact synonym (weight: 0.95, visible)
"synonymSibling" - Related synonym (weight: 0.9, invisible)
"antonym" - Opposite meaning (weight: -0.6, visible)
"similar" - Similar concept (weight: 0.8, visible)
"similarSibling" - Related similar (weight: 0.6, invisible)
"different" - Different concept (weight: -0.4, visible)
"related" - Related concept (weight: 0.5, visible)
"relatedSibling" - Related variation (weight: 0.25, invisible)
"unrelated" - Unrelated concept (weight: -0.2, visible)
LINGUISTIC:
"plural" - Plural form (weight: 0.90, visible)
"singular" - Singular form (weight: 0.90, inverse of plural)
"misspelling" - Common misspelling (weight: 0.0, visible)
"correction" - Spelling correction (weight: 0.75, inverse of misspelling)
"verbal" - Spoken form (weight: 0.0, visible)
"written" - Written form (weight: 0.0, invisible)
"narrative" - Narrative form (weight: 0.0, invisible)
CONCEPTUAL RELATIONSHIPS (weight: 0.0 for all - semantic only):
"relatedTo" - General relation
"thematic" - Thematic grouping
"superThematic" - Meta-theme grouping
"isA" - Type classification ⭐ USE FOR COMMAND → DIALECT
"propertyOf" - Property relation
"partOf" - Part-whole relation ⭐ USE FOR COMMAND → CATEGORY
"madeOf" - Composition relation
"definedAs" - Definition relation ⭐ USE FOR COMMAND → PURPOSE
CAPABILITY/ACTION:
"capableOf" - Capability relation ⭐ USE FOR FEATURES
"usedFor" - Purpose relation ⭐ USE FOR COMMAND USAGE
"action" - Action relation
EVENT/TEMPORAL:
"prerequisite" - Prerequisite relation ⭐ USE FOR DEPENDENCIES
"firstEvent" - First in sequence
"eventOf" - Event relation
"lastEvent" - Last in sequence
EFFECTS/MOTIVATION:
"location" - Location relation
"effect" - Effect relation
"desirousEffect" - Desired effect
"motivation" - Motivation relation
"desire" - Desire relation
⭐ = RECOMMENDED FOR SQL VOCABULARY BINDING

Source: SQLCoreAtomics.cs

Methods

LoadVocabularyForProtocol

int LoadVocabularyForProtocol ( CognitiveCode.Silvia.Api.SilviaCore core, GTProtocolType protocol )

Load SQL vocabulary for specific database protocol into SILVIA's concept system. Dispatches to appropriate loader based on protocol type.
SILVIA core instance
Database protocol type
Number of concepts loaded, or -1 on error
USAGE: <c>SQLVocabularyLoader.LoadVocabularyForProtocol(core, GTProtocolType.PostgreSQL_Wire);</c>

ValidationResult

readonly struct

Result of data validation with detailed failure reasons.

Source: SensorsCoreAtomics.cs

Constants and Fields

FailureReason

readonly string

IsValid

readonly bool

MaxAllowed

readonly double

MinAllowed

readonly double

ValidatedValue

readonly double

ZeroAllocSensorData

struct

Zero-allocation sensor data for ultra-high-performance systems.
WHAT IT IS:
Struct-based sensor state with fixed size for zero-allocation operation.
Used in high-frequency systems where GC pauses are unacceptable.
FIELDS:
- SensorId: Unique sensor identifier
- DataType: Type of sensor data
- Direction: Input/Output/Bidirectional
- Address: Connection address (IP, COM port, etc.)
- Port: Network port (if applicable)
- IsActive: Sensor is enabled
- IsConnected: Connection is established
- LastUpdateTime: Last successful reading (Unix epoch seconds)
- LatencyMs: Most recent reading latency
- AcquisitionTimestamp: When last measurement was taken
- CurrentValue: Latest sensor reading
- PreviousValue: Previous reading (for change detection)
- MinValue: Minimum allowed value
- MaxValue: Maximum allowed value
- AlertThreshold: Threshold for automatic alerts
- AlertTriggered: Alert has been raised
- LastAlertTime: When last alert fired
USE CASES:
- High-frequency trading (nanosecond latency)
- Hard real-time control (no GC pauses allowed)
- Embedded systems (limited heap)
- Safety-critical systems (deterministic memory)
PERFORMANCE:
- Struct (value type) - stack allocated, no GC
- Total size: ~128 bytes (2 cache lines)
- Zero allocations in hot path
- Predictable memory layout
LIMITATIONS:
- Fixed structure (can't add fields dynamically)
- Reference types (string, object) still allocate
- Larger memory footprint than class-based design
TRADEOFFS:
Zero-allocation design sacrifices flexibility for performance.
For most applications, the standard SilviaSensors class is preferred.
Use this only when GC pauses are unacceptable.

Source: SensorsCoreAtomics.cs

Constants and Fields

AcquisitionTimestamp

double

Address

string

AlertThreshold

float

AlertTriggered

bool

CurrentValue

object

DataType

SensorDataType

Direction

SensorDirection

IsActive

bool

IsConnected

bool

LastAlertTime

double

LastUpdateTime

double

LatencyMs

double

MaxValue

float

MinValue

float

Port

int

PreviousValue

object

SensorId

string


Generated from GTOS Savants source -- 2026-03-22

SILVIA is a registered Trademark of Cognitive Code Corp.