Skip to content

SILVIA Core ApiMeshNet Reference

Version: 3.1

Namespace: CognitiveCode.Silvia.Api, Cognitivecode.Silvia.MeshNet


Transport-Agnostic Tactical Mesh Networking with Zero-Allocation Atomic Operations

SILVIA's MeshNet API is a MIL-STD compliant, transport-agnostic mesh networking protocol designed for tactical edge networks, IoT swarms, and distributed AI deployments. It implements zero-allocation atomic operations with tiered encryption (None/Basic/Tactical/Classified) and supports multiple physical transports including WiFi Direct, WiFi HaLow (802.11ah), Bluetooth LE, LoRa, and cellular D2D—all under a unified API.

This is not just a networking library. It's a combat-ready mesh networking stack that enables SILVIA cores to form self-healing, self-organizing networks across heterogeneous hardware platforms, from soldier-worn radios to UAV swarms to industrial IoT deployments. The architecture prioritizes deterministic performance, cryptographic security, and platform portability while maintaining the zero-allocation guarantees required for real-time systems.

Architectural Philosophy: Transport Abstraction with Security First

Traditional mesh networking forces you to choose between performance, security, and transport compatibility. SILVIA MeshNet unifies all three:

Transport Abstraction:

  • Single API works across WiFi, HaLow, BLE, LoRa, Cellular, Serial radios
  • Automatic transport discovery and registration
  • Transparent failover between transport types
  • Per-transport metrics (RSSI, LQI, latency)

Tiered Security Architecture:

  • SecurityLevel.None (0) - Clear-text for public broadcast
  • SecurityLevel.Basic (1) - XOR stream cipher for IoT/embedded
  • SecurityLevel.Tactical (2) - AES-128-CBC for field operations
  • SecurityLevel.Classified (3) - AES-256-CBC for high-value assets

Zero-Allocation Design:

  • Pre-allocated 256-byte packet buffers
  • Span<T> and stackalloc for hot paths
  • Atomic operations for all counters
  • No GC pressure in transmit/receive paths

NIST & MIL-STD Compliance

NIST Compliance:

  • FIPS 197 - AES encryption (128-bit & 256-bit)
  • SP 800-38A - CBC mode with proper IV generation
  • SP 800-57 - Key management (128/256-bit strength)
  • SP 800-90A - CSPRNG for all cryptographic operations
  • FIPS 140-2 - Approved algorithms, key zeroization, self-test capability

MIL-STD Compliance:

  • MIL-STD-188-220D - Interoperability standards (atomic packets, quality metrics)
  • MIL-STD-882E - System safety (zero-allocation, bounded execution)
  • MIL-STD-1553 - Data bus principles (command/response, sequence validation)
  • MIL-STD-2045-47001D - IP security (authenticated encryption, key rotation)

Additional Standards:

  • IEEE 802.11ah - HaLow compatibility (MTU-aware, power-efficient)
  • IETF RFC 3561 - AODV routing (on-demand discovery, loop prevention)
  • Common Criteria EAL4+ - Security policy, audit, enforcement

Modern Use Cases

1. Tactical Edge Network: Soldier-Worn Mesh Radios

Deploy encrypted mesh network for squad-level communications with automatic routing and transport failover.

csharp
var meshNet = core.ApiMeshNet();

// Initialize with Tactical encryption (AES-128)
var config = new MeshNetConfiguration {
    SecurityLevel = SecurityLevel.Tactical,
    MaxHops = 8,
    HeartbeatInterval = 30000, // 30 seconds
    RouteTimeout = 300000,     // 5 minutes
    EnableAutoDiscovery = true
};
meshNet.Initialize(config);

// Auto-discovers and registers available transports (WiFi Direct, BLE, etc.)
// Each SILVIA core becomes a mesh node

// Send encrypted message to squad leader (node 1)
string message = "Enemy contact, grid 123456";
byte[] payload = System.Text.Encoding.UTF8.GetBytes(message);
meshNet.SendData(1, payload);

// Receive incoming messages
Span<MeshNetPacket> buffer = stackalloc MeshNetPacket[16];
int received = meshNet.ReceivePackets(buffer);

for (int i = 0; i < received; i++) {
    byte sourceNode = buffer[i].Header.SourceNodeId;
    // Process packet payload...
}

2. UAV Swarm Coordination with Multi-Transport Failover

Enable drone swarm to communicate using WiFi HaLow for long-range, falling back to WiFi Direct for close-proximity coordination.

csharp
var meshNet = core.ApiMeshNet();

// Initialize with Classified encryption for sensitive ops
var config = new MeshNetConfiguration {
    SecurityLevel = SecurityLevel.Classified, // AES-256
    MaxHops = 16,
    EnableAutoDiscovery = true
};
meshNet.Initialize(config);

// Register primary transport: WiFi HaLow (long-range, low-power)
var halowTransport = new WiFiHaLowTransport(); // User-implemented
var halowConfig = new TransportConfig {
    Type = TransportType.WiFiHaLow,
    Channel = 6,
    TransmitPower = 20, // dBm
    MTU = 256
};
meshNet.RegisterTransport(halowTransport, halowConfig);

// WiFi Direct auto-registered as fallback

// Broadcast swarm formation command
string command = "FORMATION:V_SHAPE:ALTITUDE:500";
byte[] cmdBytes = System.Text.Encoding.UTF8.GetBytes(command);
meshNet.BroadcastData(cmdBytes);

// Monitor mesh health
var stats = meshNet.GetStatistics();
Console.WriteLine($"Swarm nodes: {stats.NodeCount}");
Console.WriteLine($"Packet loss: {stats.PacketLoss:P2}");

3. Industrial IoT Sensor Mesh with Lock-Free Performance

Deploy 100+ sensors in a factory with lock-free ring buffers for deterministic latency.

csharp
var meshNet = core.ApiMeshNet();

// Basic encryption for IoT (lightweight XOR cipher)
var config = new MeshNetConfiguration {
    SecurityLevel = SecurityLevel.Basic,
    MaxHops = 10,
    HeartbeatInterval = 60000 // 1 minute
};
meshNet.Initialize(config);

// Send sensor telemetry to gateway (node 0)
float temperature = sensors.GetSensorValue<float>("temp01");
byte[] telemetry = BitConverter.GetBytes(temperature);
meshNet.SendData(0, telemetry);

// Check route to gateway
if (!meshNet.HasRoute(0)) {
    meshNet.DiscoverRoute(0); // Initiate AODV route discovery
}

// Get neighbor information for mesh health monitoring
byte[] neighbors = meshNet.GetActiveNeighbors();
foreach (byte nodeId in neighbors) {
    meshNet.GetNeighborInfo(nodeId, out MeshNetNeighbor neighbor);
    Console.WriteLine($"Node {nodeId}: Signal={neighbor.SignalStrength}dBm, " +
                     $"Quality={neighbor.LinkQuality}, Loss={neighbor.PacketLossRatio():P2}");
}

4. Emergency Communications: Disaster Recovery Network

Deploy resilient mesh network for first responders using multiple transport types.

csharp
var meshNet = core.ApiMeshNet();

// No encryption for emergency broadcasts (speed priority)
var config = new MeshNetConfiguration {
    SecurityLevel = SecurityLevel.None,
    MaxHops = 20, // Wide area coverage
    EnableAutoDiscovery = true
};
meshNet.Initialize(config);

// Send emergency alert
var packet = meshNet.CreatePacket(
    PacketType.Emergency, 
    255, // Broadcast
    System.Text.Encoding.UTF8.GetBytes("MEDICAL EMERGENCY: Grid 456789")
);
meshNet.TransmitPacket(packet);

// Monitor network topology changes
meshNet.OnNetworkChanged += () => {
    Console.WriteLine("Network topology updated");
    var stats = meshNet.GetStatistics();
    Console.WriteLine($"Reachable nodes: {stats.NodeCount}");
};

meshNet.OnNeighborDiscovered += (nodeId) => {
    Console.WriteLine($"New responder joined mesh: Node {nodeId}");
};

5. Hybrid Network: WiFi Backbone + LoRa Long-Range

Combine WiFi Direct for high-bandwidth local mesh with LoRa for long-range links.

csharp
var meshNet = core.ApiMeshNet();

var config = new MeshNetConfiguration {
    SecurityLevel = SecurityLevel.Tactical,
    MaxHops = 12,
    EnableAutoDiscovery = true
};
meshNet.Initialize(config);

// WiFi Direct auto-registered

// Add LoRa for long-range links
var loraTransport = new LoRaTransport(); // User-implemented
var loraConfig = new TransportConfig {
    Type = TransportType.LoRa,
    Channel = 915, // MHz
    TransmitPower = 14, // dBm
    MTU = 256
};
meshNet.RegisterTransport(loraTransport, loraConfig);

// Send data - MeshNet automatically selects best transport
meshNet.SendData(5, payload);

// Get route details
meshNet.GetRouteInfo(5, out MeshNetRoute route);
Console.WriteLine($"Route to node 5: Hops={route.HopCount}, Quality={route.Quality}");

Core Concepts

1. Transport-Agnostic Architecture

MeshNet abstracts physical transport layers behind a unified interface, enabling seamless multi-radio operation.

Supported Transport Types:

  • TransportType.WiFiDirect - 802.11 P2P or Ad-Hoc mode
  • TransportType.WiFiHaLow - 802.11ah (long-range, low-power)
  • TransportType.BluetoothLE - BLE mesh advertising
  • TransportType.LoRa - LoRaWAN or raw LoRa frames
  • TransportType.Cellular - LTE/5G D2D sidelink
  • TransportType.Ethernet - Wired backhaul
  • TransportType.SerialRadio - UART-connected transceivers (nRF24, HC-12)
  • TransportType.Mock - Testing without hardware
  • TransportType.Custom - User-defined transports

Auto-Discovery:

csharp
// MeshNet automatically discovers available transports on initialization
var meshNet = core.ApiMeshNet();
// Auto-discovers: WiFi Direct (UDP broadcast on port 11235)
// Additional transports can be registered manually

Manual Transport Registration:

csharp
// Register custom transport (e.g., HaLow radio)
var halowTransport = new WiFiHaLowTransport();
var config = new TransportConfig {
    Type = TransportType.WiFiHaLow,
    Channel = 6,
    TransmitPower = 20,
    MTU = 1400
};
meshNet.RegisterTransport(halowTransport, config);

2. Tiered Security Architecture

Security Level Specifications:

SecurityLevel.None (0) - Clear-Text:

  • Algorithm: No encryption
  • Use Case: Public broadcast, non-sensitive telemetry
  • Performance: Zero overhead
  • Security: None - casual eavesdropping possible

SecurityLevel.Basic (1) - XOR Stream Cipher:

  • Algorithm: XOR with 128-bit network key
  • Key Generation: CSPRNG (RandomNumberGenerator.Fill)
  • Use Case: IoT devices, low-power embedded, casual privacy
  • Performance: Minimal CPU (~1-5% on embedded ARM)
  • Security: Prevents casual eavesdropping, not adversarial-resistant

SecurityLevel.Tactical (2) - AES-128-CBC:

  • Algorithm: AES-128-CBC with HMAC
  • Key Size: 128 bits (16 bytes)
  • IV: 128-bit random IV prepended to each packet
  • Block Cipher: FIPS 197 compliant
  • Use Case: Field operations, tactical comms, commercial security
  • Performance: ~10-20% CPU overhead
  • Standards: NIST SP 800-38A compliant

SecurityLevel.Classified (3) - AES-256-CBC:

  • Algorithm: AES-256-CBC with HMAC
  • Key Size: 256 bits (32 bytes)
  • IV: 128-bit random IV prepended to each packet
  • Block Cipher: FIPS 197 compliant
  • Use Case: Classified ops, high-value asset protection
  • Performance: ~15-25% CPU overhead
  • Standards: NSA Suite B Cryptography (Top Secret capable with Type 1 products)

Encryption Example:

csharp
// Create config with desired security level
var config = new MeshNetConfiguration {
    SecurityLevel = SecurityLevel.Classified, // AES-256
    MaxHops = 8
};
meshNet.Initialize(config);

// All packets automatically encrypted/decrypted
// No application-level crypto needed

3. Atomic Packet Structure

Packet Layout (256 bytes total):

Header (8 bytes):

  • SourceNodeId (1 byte) - 0-255 nodes per mesh
  • DestinationNodeId (1 byte) - 255 = broadcast
  • SequenceNumber (2 bytes) - Rollover at 65535
  • HopCount (1 byte) - Current hop count
  • MaxHops (1 byte) - TTL equivalent
  • PayloadLength (1 byte) - 0-248 bytes
  • PacketType (1 byte) - Data, RouteDiscovery, etc.

Payload (0-248 bytes):

  • SecurityLevel.None: Raw payload data (248 bytes max)
  • SecurityLevel.Basic: XOR-encrypted payload (248 bytes max)
  • SecurityLevel.Tactical: [IV 16B][AES-128 encrypted data] (232 bytes max)
  • SecurityLevel.Classified: [IV 16B][AES-256 encrypted data] (232 bytes max)

Packet Types:

  • PacketType.Data (0) - Application data
  • PacketType.RouteDiscovery (1) - AODV route request
  • PacketType.RouteReply (2) - AODV route response
  • PacketType.Heartbeat (3) - Keepalive/presence
  • PacketType.Emergency (4) - High-priority emergency
  • PacketType.Command (5) - Control commands

4. Hybrid AODV Routing Protocol

Routing Algorithm: On-demand route discovery with proactive neighbor detection

Route Discovery:

csharp
// Check if route exists
if (!meshNet.HasRoute(targetNodeId)) {
    // Initiate AODV route discovery
    meshNet.DiscoverRoute(targetNodeId);
}

// Get detailed route information
meshNet.GetRouteInfo(targetNodeId, out MeshNetRoute route);
Console.WriteLine($"Destination: {route.DestinationNodeId}");
Console.WriteLine($"Next hop: {route.NextHopNodeId}");
Console.WriteLine($"Hop count: {route.HopCount}");
Console.WriteLine($"Quality: {route.Quality}/255");
Console.WriteLine($"Valid: {route.IsValid()}");
Console.WriteLine($"Direct: {route.IsDirectRoute()}");

Route Metrics:

  • HopCount - Primary metric (lower is better)
  • Quality - Link quality score 0-255 (higher is better)
  • SignalStrength - RSSI from transport layer
  • LastValidated - Age of route (timeout: 5 minutes default)

Route Flags:

  • RouteFlags.Validated - Route has been confirmed
  • RouteFlags.Preferred - Marked as preferred route
  • RouteFlags.Backup - Backup route available
  • RouteFlags.Encrypted - Requires encryption
  • RouteFlags.HighPriority - High-priority route

5. Neighbor Discovery & Management

Automatic Neighbor Detection:

csharp
// Get all active neighbors
byte[] neighbors = meshNet.GetActiveNeighbors();

foreach (byte nodeId in neighbors) {
    if (meshNet.GetNeighborInfo(nodeId, out MeshNetNeighbor neighbor)) {
        Console.WriteLine($"Node {nodeId}:");
        Console.WriteLine($"  Signal: {neighbor.SignalStrength}dBm");
        Console.WriteLine($"  Link quality: {neighbor.LinkQuality}/255");
        Console.WriteLine($"  Packets sent: {neighbor.PacketsSent}");
        Console.WriteLine($"  Packets received: {neighbor.PacketsReceived}");
        Console.WriteLine($"  Packet loss: {neighbor.PacketLossRatio():P2}");
        Console.WriteLine($"  Last seen: {Environment.TickCount - neighbor.LastSeen}ms ago");
        Console.WriteLine($"  State: {neighbor.State}");
        Console.WriteLine($"  Alive: {neighbor.IsAlive()}");
    }
}

Neighbor States:

  • NeighborState.Unknown (0) - Initial state
  • NeighborState.Discovering (1) - Discovery in progress
  • NeighborState.Active (2) - Actively communicating
  • NeighborState.Degraded (3) - Poor link quality
  • NeighborState.Lost (4) - No recent contact

Link Quality Calculation:

csharp
// Link quality = (success rate) × (signal strength factor)
// Success rate = 1.0 - (packets lost / packets sent)
// Signal factor = max(0, (RSSI + 100) / 100)
// Result scaled to 0-255

6. Heartbeat & Presence System

Automatic Heartbeat:

csharp
// Configure heartbeat interval
var config = new MeshNetConfiguration {
    HeartbeatInterval = 30000, // 30 seconds
    EnableAutoDiscovery = true
};

// Manual heartbeat trigger
meshNet.SendHeartbeat(); // Broadcast to all neighbors

Heartbeat Processing:

  • Maintains neighbor liveness
  • Updates signal strength metrics
  • Triggers network topology events
  • Enables automatic route maintenance

7. Zero-Allocation Design

Performance Characteristics:

Memory Footprint:

  • Core Instance: ~16KB (dictionaries + state)
  • Per Route: ~16 bytes
  • Per Neighbor: ~32 bytes
  • Per Radio: ~16 bytes
  • Security Keys: ~64 bytes (fixed)

Hot Path Operations:

  • All transmit/receive use Span<T> and stackalloc
  • No GC allocations in packet processing
  • Atomic operations (Interlocked) for all counters
  • Pre-allocated 256-byte packet buffers

Example - Zero Allocation Receive:

csharp
// Stack-allocated receive buffer
Span<MeshNetPacket> buffer = stackalloc MeshNetPacket[16];

// Receive packets (zero heap allocations)
int count = meshNet.ReceivePackets(buffer);

for (int i = 0; i < count; i++) {
    // Process packet on stack
    MeshNetPacket packet = buffer[i];
    // ...
}

API Reference: ApiMeshNet

Initialization

Initialize(config)

Initializes MeshNet with custom configuration.

Parameters:

  • config (MeshNetConfiguration) - Configuration settings

Returns: bool - True if initialization successful

Configuration Fields:

  • SecurityLevel (SecurityLevel) - Encryption level (None/Basic/Tactical/Classified)
  • MaxHops (byte) - Maximum hop count for routing (default: 8)
  • HeartbeatInterval (uint) - Heartbeat interval in milliseconds (default: 30000)
  • RouteTimeout (uint) - Route aging timeout in milliseconds (default: 300000)
  • EnableAutoDiscovery (bool) - Auto-discover transports (default: true)

Example:

csharp
var config = new MeshNetConfiguration {
    SecurityLevel = SecurityLevel.Tactical,
    MaxHops = 12,
    HeartbeatInterval = 30000,
    RouteTimeout = 300000,
    EnableAutoDiscovery = true
};

bool success = meshNet.Initialize(config);

Transport Management

RegisterTransport(transport, config)

Registers a custom transport backend.

Parameters:

  • transport (MeshTransport) - Transport instance
  • config (TransportConfig) - Transport configuration

Returns: bool - True if registration successful

Transport Configuration:

  • Type (TransportType) - Transport type identifier
  • Channel (ushort) - Radio channel or frequency
  • TransmitPower (sbyte) - Transmit power in dBm
  • MTU (ushort) - Maximum transmission unit

Example:

csharp
var loraTransport = new LoRaTransport();
var loraConfig = new TransportConfig {
    Type = TransportType.LoRa,
    Channel = 915,
    TransmitPower = 14,
    MTU = 256
};

bool registered = meshNet.RegisterTransport(loraTransport, loraConfig);

AddRadio(radioId, channel = 868, signalStrength = -50, transmitPower = 100)

Adds a legacy radio transceiver (creates default transport).

Parameters:

  • radioId (byte) - Unique radio identifier
  • channel (ushort, optional) - Radio channel (default: 868)
  • signalStrength (sbyte, optional) - Initial signal strength (default: -50)
  • transmitPower (byte, optional) - Transmit power (default: 100)

Returns: bool - True if radio was added successfully

Example:

csharp
bool added = meshNet.AddRadio(0, channel: 915, transmitPower: 20);

Packet Transmission

SendData(destinationNodeId, data)

Sends data to a specific node.

Parameters:

  • destinationNodeId (byte) - Target node ID (0-254)
  • data (ReadOnlySpan<byte>) - Payload data (max 248 bytes)

Returns: bool - True if packet was sent successfully

Behavior:

  • Automatically finds route to destination
  • Encrypts based on security level
  • Uses first available radio/transport

Example:

csharp
string message = "Hello from node 0";
byte[] payload = System.Text.Encoding.UTF8.GetBytes(message);
bool sent = meshNet.SendData(5, payload);

SendPacket(destinationNodeId, packetType, data = default)

Sends a packet with custom packet type.

Parameters:

  • destinationNodeId (byte) - Target node ID
  • packetType (PacketType) - Packet type (Data/RouteDiscovery/etc.)
  • data (ReadOnlySpan<byte>, optional) - Payload data

Returns: bool - True if packet was sent successfully

Example:

csharp
// Send emergency packet
byte[] emergencyData = System.Text.Encoding.UTF8.GetBytes("EVAC NOW");
bool sent = meshNet.SendPacket(255, PacketType.Emergency, emergencyData);

BroadcastData(data)

Broadcasts data to all reachable nodes.

Parameters:

  • data (ReadOnlySpan<byte>) - Payload data (max 248 bytes)

Returns: bool - True if broadcast was successful

Behavior:

  • Uses broadcast address (255)
  • Transmitted via all active radios
  • Respects MaxHops limit

Example:

csharp
string announcement = "Network maintenance in 5 minutes";
byte[] payload = System.Text.Encoding.UTF8.GetBytes(announcement);
meshNet.BroadcastData(payload);

CreatePacket(type, destinationId, payload = default)

Creates a MeshNet packet for custom use.

Parameters:

  • type (PacketType) - Packet type
  • destinationId (byte) - Destination node ID
  • payload (ReadOnlySpan<byte>, optional) - Payload data

Returns: MeshNetPacket - Constructed packet

Example:

csharp
byte[] data = new byte[] { 0x01, 0x02, 0x03 };
MeshNetPacket packet = meshNet.CreatePacket(PacketType.Data, 10, data);

// Inspect packet
Console.WriteLine($"Source: {packet.Header.SourceNodeId}");
Console.WriteLine($"Destination: {packet.Header.DestinationNodeId}");
Console.WriteLine($"Sequence: {packet.Header.SequenceNumber}");
Console.WriteLine($"Payload length: {packet.Header.PayloadLength}");

TransmitPacket(packet)

Transmits a custom packet.

Parameters:

  • packet (MeshNetPacket) - Packet to transmit (passed by reference)

Returns: bool - True if transmission successful

Example:

csharp
var packet = meshNet.CreatePacket(PacketType.Command, 5);
bool sent = meshNet.TransmitPacket(packet);

Packet Reception

ReceivePackets(buffer)

Receives available packets into a buffer.

Parameters:

  • buffer (Span<MeshNetPacket>) - Receive buffer (typically stack-allocated)

Returns: int - Number of packets received

Behavior:

  • Zero-allocation using span
  • Pulls from all active transports
  • Automatically decrypts based on security level
  • Updates neighbor metrics

Example:

csharp
// Stack-allocated buffer for 16 packets
Span<MeshNetPacket> buffer = stackalloc MeshNetPacket[16];

int received = meshNet.ReceivePackets(buffer);

for (int i = 0; i < received; i++) {
    MeshNetPacket packet = buffer[i];
    
    Console.WriteLine($"From node {packet.Header.SourceNodeId}");
    Console.WriteLine($"Type: {packet.Header.Type}");
    Console.WriteLine($"Hops: {packet.Header.HopCount}");
    
    // Extract payload
    unsafe {
        fixed (byte* payloadPtr = packet.Payload) {
            Span<byte> payload = new Span<byte>(payloadPtr, packet.Header.PayloadLength);
            string text = System.Text.Encoding.UTF8.GetString(payload);
            Console.WriteLine($"Message: {text}");
        }
    }
}

Routing

HasRoute(nodeId)

Checks if a route exists to the specified node.

Parameters:

  • nodeId (byte) - Target node ID

Returns: bool - True if route exists and is valid

Example:

csharp
if (meshNet.HasRoute(10)) {
    meshNet.SendData(10, payload);
} else {
    meshNet.DiscoverRoute(10);
}

GetRouteInfo(nodeId, out route)

Gets detailed route information.

Parameters:

  • nodeId (byte) - Target node ID
  • route (out MeshNetRoute) - Output route structure

Returns: bool - True if route exists

Route Fields:

  • DestinationNodeId (byte) - Final destination
  • NextHopNodeId (byte) - Next hop in route
  • HopCount (byte) - Number of hops to destination
  • Quality (byte) - Link quality (0-255)
  • LastValidated (uint) - Timestamp of last validation
  • Flags (RouteFlags) - Route flags

Example:

csharp
if (meshNet.GetRouteInfo(5, out MeshNetRoute route)) {
    Console.WriteLine($"Route to node 5:");
    Console.WriteLine($"  Next hop: {route.NextHopNodeId}");
    Console.WriteLine($"  Hop count: {route.HopCount}");
    Console.WriteLine($"  Quality: {route.Quality}/255");
    Console.WriteLine($"  Direct: {route.IsDirectRoute()}");
    Console.WriteLine($"  Valid: {route.IsValid()}");
}

DiscoverRoute(nodeId)

Initiates AODV route discovery for unreachable node.

Parameters:

  • nodeId (byte) - Target node ID to discover route to

Behavior:

  • Broadcasts RouteDiscovery packet
  • Waits for RouteReply from destination
  • Establishes bidirectional route
  • Respects MaxHops limit

Example:

csharp
// Discover route to node 15
meshNet.DiscoverRoute(15);

// Wait for route establishment (async in real implementation)
System.Threading.Thread.Sleep(1000);

if (meshNet.HasRoute(15)) {
    Console.WriteLine("Route established");
    meshNet.SendData(15, payload);
}

Neighbor Management

IsNeighbor(nodeId)

Checks if a node is a known neighbor.

Parameters:

  • nodeId (byte) - Node ID to check

Returns: bool - True if node is an active neighbor

Example:

csharp
if (meshNet.IsNeighbor(3)) {
    Console.WriteLine("Node 3 is a direct neighbor");
}

GetNeighborInfo(nodeId, out neighbor)

Gets detailed neighbor information.

Parameters:

  • nodeId (byte) - Neighbor node ID
  • neighbor (out MeshNetNeighbor) - Output neighbor structure

Returns: bool - True if neighbor exists

Neighbor Fields:

  • NodeId (byte) - Neighbor node ID
  • SignalStrength (sbyte) - RSSI in dBm
  • LinkQuality (byte) - Calculated quality (0-255)
  • LastSeen (uint) - Timestamp of last contact
  • PacketsSent (uint) - Total packets sent to neighbor
  • PacketsReceived (uint) - Total packets received
  • PacketsLost (uint) - Total packets lost
  • State (NeighborState) - Neighbor state

Example:

csharp
if (meshNet.GetNeighborInfo(3, out MeshNetNeighbor neighbor)) {
    Console.WriteLine($"Neighbor 3:");
    Console.WriteLine($"  Signal: {neighbor.SignalStrength}dBm");
    Console.WriteLine($"  Quality: {neighbor.LinkQuality}/255");
    Console.WriteLine($"  Loss rate: {neighbor.PacketLossRatio():P2}");
    Console.WriteLine($"  State: {neighbor.State}");
    Console.WriteLine($"  Alive: {neighbor.IsAlive()}");
}

GetActiveNeighbors()

Gets array of all active neighbor node IDs.

Returns: byte[] - Array of active neighbor IDs

Example:

csharp
byte[] neighbors = meshNet.GetActiveNeighbors();
Console.WriteLine($"Active neighbors: {neighbors.Length}");

foreach (byte nodeId in neighbors) {
    Console.WriteLine($"  Node {nodeId}");
}

Network Maintenance

SendHeartbeat()

Sends heartbeat to maintain network presence.

Returns: bool - True if heartbeat was sent successfully

Behavior:

  • Broadcasts heartbeat packet
  • Updates neighbor liveness
  • Maintains route freshness

Example:

csharp
// Manual heartbeat (usually automatic)
meshNet.SendHeartbeat();

Cleanup()

Forces cleanup of stale routes and dead neighbors.

Behavior:

  • Removes neighbors not seen in 10+ seconds
  • Removes routes older than timeout (default 5 minutes)
  • Triggers OnNetworkChanged event

Example:

csharp
// Periodic cleanup
meshNet.Cleanup();
Console.WriteLine("Stale entries removed");

Statistics & Monitoring

GetStatistics()

Gets current network statistics.

Returns: MeshNetStatistics - Network statistics structure

Statistics Fields:

  • NodeCount (byte) - Total nodes in mesh (including self)
  • RouteCount (ushort) - Number of active routes
  • RadioCount (byte) - Number of registered radios/transports
  • Uptime (uint) - System uptime in milliseconds
  • PacketsSent (uint) - Total packets sent
  • PacketsReceived (uint) - Total packets received
  • PacketLoss (float) - Overall packet loss ratio (0.0 to 1.0)

Example:

csharp
var stats = meshNet.GetStatistics();

Console.WriteLine($"Mesh Network Statistics:");
Console.WriteLine($"  Nodes: {stats.NodeCount}");
Console.WriteLine($"  Routes: {stats.RouteCount}");
Console.WriteLine($"  Radios: {stats.RadioCount}");
Console.WriteLine($"  Uptime: {TimeSpan.FromMilliseconds(stats.Uptime)}");
Console.WriteLine($"  Packets sent: {stats.PacketsSent}");
Console.WriteLine($"  Packets received: {stats.PacketsReceived}");
Console.WriteLine($"  Packet loss: {stats.PacketLoss:P2}");

GetLocalNodeId()

Gets the local node ID.

Returns: byte - Local node ID (0-255)

Behavior:

  • Derived from SILVIA core UID (modulo 256)
  • Unique within local mesh network

Example:

csharp
byte nodeId = meshNet.GetLocalNodeId();
Console.WriteLine($"This node ID: {nodeId}");

IsOperational()

Checks if MeshNet is operational.

Returns: bool - True if operational (has at least one radio/transport)

Example:

csharp
if (meshNet.IsOperational()) {
    Console.WriteLine("MeshNet is ready");
} else {
    Console.WriteLine("No transports available");
}

Events

OnPacketReceived

Event raised when a data packet is received.

Signature: event Action<MeshNetPacket>

Example:

csharp
meshNet.OnPacketReceived += (packet) => {
    Console.WriteLine($"Received packet from node {packet.Header.SourceNodeId}");
    
    // Extract payload
    unsafe {
        fixed (byte* ptr = packet.Payload) {
            Span<byte> payload = new Span<byte>(ptr, packet.Header.PayloadLength);
            string message = System.Text.Encoding.UTF8.GetString(payload);
            Console.WriteLine($"Message: {message}");
        }
    }
};

OnNetworkChanged

Event raised when network topology changes.

Signature: event Action

Triggers:

  • Route discovered or invalidated
  • Neighbor added or removed
  • Heartbeat received

Example:

csharp
meshNet.OnNetworkChanged += () => {
    var stats = meshNet.GetStatistics();
    Console.WriteLine($"Network changed: {stats.NodeCount} nodes, {stats.RouteCount} routes");
};

OnNeighborDiscovered

Event raised when a new neighbor is discovered.

Signature: event Action<byte>

Example:

csharp
meshNet.OnNeighborDiscovered += (nodeId) => {
    Console.WriteLine($"New neighbor discovered: Node {nodeId}");
    
    if (meshNet.GetNeighborInfo(nodeId, out MeshNetNeighbor neighbor)) {
        Console.WriteLine($"  Signal: {neighbor.SignalStrength}dBm");
        Console.WriteLine($"  Quality: {neighbor.LinkQuality}/255");
    }
};

Transport Layer Reference

MeshTransport (Abstract Base Class)

Custom transports must inherit from MeshTransport and implement:

csharp
public abstract class MeshTransport {
    public TransportType Type { get; }
    public ushort MTU { get; }
    public TransportState State { get; }
    
    public abstract bool Initialize(TransportConfig config);
    public abstract bool Send(ReadOnlySpan<byte> frame, out TransportMetadata metadata);
    public abstract int Receive(Span<MeshFrame> frames, Span<TransportMetadata> metadata);
    public virtual bool GetMetrics(out TransportMetrics metrics);
    public virtual void Shutdown();
    
    public event Action<TransportState> OnStateChanged;
}

Transport States:

  • TransportState.Offline - Not initialized
  • TransportState.Initializing - Initialization in progress
  • TransportState.Ready - Ready for operation
  • TransportState.Active - Actively transmitting/receiving
  • TransportState.Error - Error state

Transport Metadata:

  • RSSI (sbyte) - Received signal strength indicator
  • LQI (byte) - Link quality indicator
  • Timestamp (uint) - Reception timestamp
  • SourceType (TransportType) - Transport type
  • TransportId (byte) - Transport identifier

Transport Metrics:

  • FramesSent (uint) - Total frames sent
  • FramesReceived (uint) - Total frames received
  • FramesDropped (uint) - Total frames dropped
  • AverageRSSI (sbyte) - Average signal strength
  • AverageLQI (byte) - Average link quality
  • PacketLoss (float) - Packet loss ratio

Built-In Transports

WiFiDirectTransport

UDP broadcast transport using WiFi Direct or Ad-Hoc mode.

Specifications:

  • Port: 11235
  • MTU: 1400 bytes
  • Platform: Windows, Linux, macOS, Android, iOS
  • Auto-discovered: Yes

Example:

csharp
// Auto-registered during initialization
// Manual registration:
var wifiTransport = new WiFiDirectTransport();
var config = new TransportConfig {
    Type = TransportType.WiFiDirect,
    MTU = 1400
};
meshNet.RegisterTransport(wifiTransport, config);

MockTransport

Testing transport simulating perfect radio link.

Specifications:

  • MTU: 256 bytes
  • Simulated RSSI: -40dBm
  • Simulated LQI: 255 (perfect)
  • Use: Testing, development, simulation

Example:

csharp
var mockTransport = new MockTransport();
var config = new TransportConfig {
    Type = TransportType.Mock,
    MTU = 256
};
meshNet.RegisterTransport(mockTransport, config);

// Inject test frame
byte[] testFrame = new byte[] { /* packet data */ };
mockTransport.InjectFrame(testFrame);

Advanced Patterns

Pattern 1: Multi-Hop Tactical Network with Encryption

csharp
// Squad-level mesh with AES-256
var config = new MeshNetConfiguration {
    SecurityLevel = SecurityLevel.Classified,
    MaxHops = 10,
    HeartbeatInterval = 30000,
    RouteTimeout = 300000
};
meshNet.Initialize(config);

// Send to command post (node 0) through intermediaries
string sitrep = "SITREP: Objective secured, 2 casualties";
meshNet.SendData(0, System.Text.Encoding.UTF8.GetBytes(sitrep));

// Monitor multi-hop routing
meshNet.GetRouteInfo(0, out MeshNetRoute route);
Console.WriteLine($"Hops to command: {route.HopCount}");

Pattern 2: IoT Sensor Mesh with Basic Encryption

csharp
// Lightweight encryption for sensors
var config = new MeshNetConfiguration {
    SecurityLevel = SecurityLevel.Basic, // XOR cipher
    MaxHops = 8,
    HeartbeatInterval = 60000
};
meshNet.Initialize(config);

// Periodic telemetry broadcast
void SendTelemetry() {
    float temp = sensors.GetSensorValue<float>("temp01");
    float humidity = sensors.GetSensorValue<float>("humidity01");
    
    byte[] telemetry = new byte[8];
    BitConverter.GetBytes(temp).CopyTo(telemetry, 0);
    BitConverter.GetBytes(humidity).CopyTo(telemetry, 4);
    
    meshNet.BroadcastData(telemetry);
}

Pattern 3: Hybrid Transport with Automatic Failover

csharp
// Primary: WiFi HaLow (long-range)
var halowTransport = new WiFiHaLowTransport();
var halowConfig = new TransportConfig {
    Type = TransportType.WiFiHaLow,
    Channel = 6,
    TransmitPower = 20,
    MTU = 256
};
meshNet.RegisterTransport(halowTransport, halowConfig);

// Fallback: WiFi Direct (auto-registered)

// MeshNet automatically uses best available transport
meshNet.SendData(targetNode, payload);

// Monitor transport health
halowTransport.GetMetrics(out TransportMetrics metrics);
Console.WriteLine($"HaLow packet loss: {metrics.PacketLoss:P2}");

Pattern 4: Event-Driven Mesh Coordination

csharp
// Setup event handlers for distributed coordination
meshNet.OnNeighborDiscovered += (nodeId) => {
    Console.WriteLine($"New drone joined swarm: {nodeId}");
    
    // Send formation assignment
    string command = $"FORMATION:{nodeId}:V_SHAPE:OFFSET:10,0,0";
    meshNet.SendData(nodeId, System.Text.Encoding.UTF8.GetBytes(command));
};

meshNet.OnNetworkChanged += () => {
    byte[] neighbors = meshNet.GetActiveNeighbors();
    
    if (neighbors.Length < 3) {
        Console.WriteLine("WARNING: Swarm fragmented");
        // Trigger formation recovery
    }
};

meshNet.OnPacketReceived += (packet) => {
    if (packet.Header.Type == PacketType.Emergency) {
        Console.WriteLine("EMERGENCY RECEIVED");
        // Trigger emergency procedures
    }
};

Pattern 5: Route Quality Monitoring

csharp
void MonitorRouteQuality(byte targetNode) {
    if (meshNet.GetRouteInfo(targetNode, out MeshNetRoute route)) {
        // Check route quality
        if (route.Quality < 100) { // Poor quality
            Console.WriteLine("Route degraded, initiating rediscovery");
            route.Invalidate();
            meshNet.DiscoverRoute(targetNode);
        }
        
        // Check if route is stale
        if (!route.IsValid()) {
            Console.WriteLine("Route expired");
            meshNet.DiscoverRoute(targetNode);
        }
        
        // Prefer direct routes
        if (!route.IsDirectRoute() && route.HopCount > 1) {
            Console.WriteLine($"Multi-hop route: {route.HopCount} hops");
        }
    }
}

Best Practices

1. Choose Appropriate Security Level

SecurityLevel.None:

  • Use for: Public broadcasts, non-sensitive telemetry
  • Performance: Zero overhead
  • Security: None

SecurityLevel.Basic:

  • Use for: IoT sensors, casual privacy
  • Performance: <5% overhead
  • Security: Prevents casual eavesdropping

SecurityLevel.Tactical:

  • Use for: Field operations, commercial applications
  • Performance: ~15% overhead
  • Security: Military-grade (NIST compliant)

SecurityLevel.Classified:

  • Use for: Classified operations, high-value assets
  • Performance: ~20% overhead
  • Security: NSA Suite B capable

2. Manage Route Discovery Efficiently

csharp
// Check route before sending
if (!meshNet.HasRoute(targetNode)) {
    meshNet.DiscoverRoute(targetNode);
    // Wait or queue packet for later
} else {
    meshNet.SendData(targetNode, payload);
}

// Periodic route validation
void ValidateRoutes() {
    byte[] knownNodes = GetKnownNodeIds();
    
    foreach (byte nodeId in knownNodes) {
        if (meshNet.GetRouteInfo(nodeId, out MeshNetRoute route)) {
            if (!route.IsValid()) {
                meshNet.DiscoverRoute(nodeId);
            }
        }
    }
}

3. Monitor Neighbor Health

csharp
void CheckNeighborHealth() {
    byte[] neighbors = meshNet.GetActiveNeighbors();
    
    foreach (byte nodeId in neighbors) {
        meshNet.GetNeighborInfo(nodeId, out MeshNetNeighbor neighbor);
        
        // Check signal strength
        if (neighbor.SignalStrength < -80) {
            Console.WriteLine($"Warning: Weak signal to node {nodeId}");
        }
        
        // Check packet loss
        if (neighbor.PacketLossRatio() > 0.1f) {
            Console.WriteLine($"Warning: High packet loss to node {nodeId}");
        }
        
        // Check staleness
        if (!neighbor.IsAlive()) {
            Console.WriteLine($"Node {nodeId} appears offline");
        }
    }
}

4. Use Zero-Allocation Patterns

csharp
// Stack-allocate receive buffer
Span<MeshNetPacket> rxBuffer = stackalloc MeshNetPacket[16];

// Receive loop (zero heap allocations)
int count = meshNet.ReceivePackets(rxBuffer);

for (int i = 0; i < count; i++) {
    ProcessPacket(rxBuffer[i]); // Pass by value on stack
}

// Avoid boxing
unsafe void ProcessPacket(MeshNetPacket packet) {
    fixed (byte* ptr = packet.Payload) {
        Span<byte> payload = new Span<byte>(ptr, packet.Header.PayloadLength);
        // Process payload without allocations
    }
}

5. Implement Robust Error Handling

csharp
bool SendWithRetry(byte targetNode, byte[] payload, int maxRetries = 3) {
    for (int attempt = 0; attempt < maxRetries; attempt++) {
        if (meshNet.HasRoute(targetNode)) {
            if (meshNet.SendData(targetNode, payload)) {
                return true;
            }
        } else {
            meshNet.DiscoverRoute(targetNode);
            System.Threading.Thread.Sleep(1000); // Wait for route
        }
    }
    
    Console.WriteLine($"Failed to send to node {targetNode} after {maxRetries} attempts");
    return false;
}

6. Cleanup Stale Entries Periodically

csharp
// Periodic cleanup task
void MaintenanceLoop() {
    while (running) {
        System.Threading.Thread.Sleep(60000); // Every minute
        
        meshNet.Cleanup(); // Remove stale routes and dead neighbors
        
        var stats = meshNet.GetStatistics();
        Console.WriteLine($"Active: {stats.NodeCount} nodes, {stats.RouteCount} routes");
    }
}

Performance Characteristics

Throughput (Single Transport)

Security LevelPackets/SecOverhead
None100-5000%
Basic (XOR)90-450~10%
Tactical (AES-128)70-400~20%
Classified (AES-256)60-350~25%

Latency (End-to-End, 1 Hop)

TransportLatency
WiFi Direct5-20ms
WiFi HaLow10-50ms
Bluetooth LE50-200ms
LoRa500-2000ms

Memory Footprint

ComponentSize
Core Instance~16KB
Per Route16 bytes
Per Neighbor32 bytes
Per Radio16 bytes
Security Keys64 bytes

Compliance & Standards

NIST Compliance Summary

  • FIPS 197 - AES encryption (128/256-bit)
  • SP 800-38A - CBC mode with IV generation
  • SP 800-57 - Key management (128/256-bit strength)
  • SP 800-90A - CSPRNG (RandomNumberGenerator)
  • FIPS 140-2 - Approved algorithms, key zeroization

MIL-STD Compliance Summary

  • MIL-STD-188-220D - Interoperability standards
  • MIL-STD-882E - System safety (zero-allocation, bounded execution)
  • MIL-STD-1553 - Data bus principles
  • MIL-STD-2045-47001D - IP security

Additional Standards

  • IEEE 802.11ah - HaLow compatibility
  • IETF RFC 3561 - AODV routing protocol
  • Common Criteria EAL4+ - Security enforcement

Conclusion

SILVIA's MeshNet API delivers military-grade mesh networking with transport abstraction, tiered encryption, and zero-allocation performance. Whether you're deploying tactical edge networks, UAV swarms, or industrial IoT meshes, MeshNet provides the cryptographic security, deterministic routing, and platform portability required for mission-critical distributed systems.

Key Advantages:

  1. Transport Agnostic - Single API for WiFi, HaLow, BLE, LoRa, Cellular
  2. Tiered Security - XOR to AES-256, NIST/MIL-STD compliant
  3. Zero-Allocation - Pre-allocated buffers, Span<T>, no GC pressure
  4. AODV Routing - Self-healing, self-organizing mesh topology
  5. Atomic Packets - 256-byte fixed structure, statically typed
  6. Multi-Platform - Windows, Linux, macOS, embedded systems

From IoT sensor networks to classified tactical operations, SILVIA MeshNet provides the distributed communication backbone for next-generation edge AI systems.


© Copyright Cognitive Code Corp. 2007-2026

SILVIA is a registered Trademark of Cognitive Code Corp.

SILVIA is a registered Trademark of Cognitive Code Corp.