using System.Text.Json; using Gateway.Api.Domain; using Gateway.Api.Services; using Microsoft.Extensions.Logging.Abstractions; internal static class BacnetBridgeTests { public static async Task RunAsync(GatewayStore store, GatewayDatabase database) { var point = store.CreatePoint(new CreatePointRequest("Native priority bridge AV", PointProtocol.Bacnet, PointScope.Gateway, "Real", true, true, null, JsonSerializer.SerializeToElement(new { }), BacnetObjectKind.AnalogValue)); var trend = store.CreateTrendLog(new CreateTrendLogRequest(point.Id, "Native observed trend", 902, 1, 100, true)); store.SetPointValue(point.Id, JsonSerializer.SerializeToElement(22), PointProtocol.Internal, DateTimeOffset.UtcNow, "Good", bacnetPriority: 16); Check(store.ListPointValues().All(value => value.PointId != point.Id), "A BACnet command must not become an effective value before native arbitration."); Check(store.ListTrendRecords(trend.Id, 100).Count == 0, "Commands must not be trended as actual values."); using var connection = database.OpenConnection(); using var command = connection.CreateCommand(); command.CommandText = "SELECT priority FROM bacnet_commands WHERE point_id=$id"; command.Parameters.AddWithValue("$id", point.Id.ToString()); Check((long)command.ExecuteScalar()! == 16, "BACnet priority must reach the native queue."); command.CommandText = "INSERT OR REPLACE INTO bacnet_runtime VALUES(1,$time,'Test'); INSERT INTO bacnet_observations(point_id,value_json,status,observed_ms) VALUES($id,'30','Good',$time)"; command.Parameters.AddWithValue("$time", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()); command.ExecuteNonQuery(); using var bridge = new BacnetNativeBridgeService(database, store, NullLogger.Instance); await bridge.StartAsync(CancellationToken.None); try { var deadline = DateTime.UtcNow.AddSeconds(3); while (store.ListPointValues().All(value => value.PointId != point.Id)) { if (DateTime.UtcNow > deadline) throw new InvalidOperationException("Native observation timed out."); await Task.Delay(25); } Check(store.ListPointValues().Single(value => value.PointId == point.Id).Value.GetInt32() == 30, "Native arbitration must determine the effective value."); Check(store.ListTrendRecords(trend.Id, 100).Count == 1, "Native observations must feed the trend once."); command.CommandText = "SELECT COUNT(*) FROM bacnet_commands WHERE point_id=$id"; Check((long)command.ExecuteScalar()! == 1, "Native feedback must not enqueue another write."); } finally { await bridge.StopAsync(CancellationToken.None); } Console.WriteLine("BACnet bridge tests passed: command/observation separation, priority transport, effective-value trend, no echo."); } private static void Check(bool condition, string message) { if (!condition) throw new InvalidOperationException(message); } }