Files
SE-UGW/tests/native_bacnet_test.py
jhartworks 98c48d9d78 Add comprehensive smoke and feature tests for Gateway API
- Introduced LtdFeatureTests to validate BACnet and OPC UA point updates, trend logging, and alarm rule functionality.
- Added OpcUaClientTests to ensure proper OPC UA client configuration, point value synchronization, and session management.
- Created OpcUaFeatureTests to test OPC UA server capabilities, including browsing, reading, writing, and subscription notifications.
- Implemented native_bacnet_test.py for isolated BACnet wire testing, covering discovery, read/write operations, and command processing.
- Added ui-theme-tabs.test.cjs to verify theme switching, tab interactions, and protocol form accessibility in the UI.
2026-11-19 16:06:54 +01:00

150 lines
8.5 KiB
Python

"""Isolated wire test: only loopback, a temporary DB, no building-network writes."""
import json
import os
import socket
from pathlib import Path
import sqlite3
import subprocess
import sys
import tempfile
import time
runtime = Path(sys.argv[1]) / "bin"
work = Path(tempfile.mkdtemp(prefix="seiugw-bacnet-wire-"))
db = sqlite3.connect(work / "seiugw.db")
# Share the exact schema with the application rather than maintaining a fixture copy.
source = Path(__file__).resolve().parents[1] / "src/Gateway.Api/Services/GatewayDatabase.cs"
schema = source.read_text().split('command.CommandText = """', 1)[1].split('""";', 1)[0]
db.executescript(schema)
config = {"deviceInstance": 900023, "deviceName": "SE-UGW-Wire-Test", "bacnet": {"interface": "lo", "ipPort": 47828, "bbmdMode": "Disabled"}}
db.execute("INSERT INTO settings VALUES(?,?)", ("gateway.configuration", json.dumps(config)))
types = [("AnalogInput", 0), ("AnalogOutput", 1), ("AnalogValue", 2), ("BinaryInput", 3), ("BinaryOutput", 4), ("BinaryValue", 5),
("MultiStateInput", 13), ("MultiStateOutput", 14), ("MultiStateValue", 19), ("Schedule", 17), ("Calendar", 6)]
for i, (kind, number) in enumerate(types, 1):
db.execute("INSERT INTO points VALUES(?,?,?,?,?,?,?,?,?,?,?,?,NULL)", (f"00000000-0000-0000-0000-{i:012}", kind, "Bacnet", "Gateway", "Real", 1, 1,
None, '{"units":62,"numberOfStates":16}', "2026-10-09T00:00:00Z", kind, 77))
db.commit()
environment = {**os.environ, "LC_ALL": "C", "BACNET_DATALINK": "bip", "BACNET_IFACE": "lo", "BACNET_IP_PORT": "47829", "BACNET_IP_BROADCAST_PORT": "47828", "BACNET_APDU_TIMEOUT": "1000"}
log = open(work / "server.log", "w")
server = None
cov = None
def start():
global server
server = subprocess.Popen([runtime / "bacserv", "900023"], cwd=work, env={**environment, "SEIUGW_DATABASE": str(work / "seiugw.db")}, stdout=log, stderr=log)
time.sleep(1.5)
assert server.poll() is None, (work / "server.log").read_text()
def call(tool, args, success=True):
result = subprocess.run([runtime / tool, "900023", *map(str, args), "--mac", "127.0.0.1:47828", "--dnet", "0"], env=environment, cwd=work, text=True, capture_output=True, timeout=10)
assert (result.returncode == 0) == success, (args, result.stdout, result.stderr)
return result.stdout.strip()
def read(obj, prop=85, index=None):
return call("bacrp", [obj, 77 if obj != 8 else 900023, prop, *([] if index is None else [index])])
def write(obj, tag, value, priority=16, prop=85, success=True):
return call("bacwp", [obj, 77, prop, priority, -1, tag, value], success)
def command(i, value, priority=16):
cursor = db.execute("INSERT INTO bacnet_commands(point_id,value_json,priority,created_ms) VALUES(?,?,?,?)",
(f"00000000-0000-0000-0000-{i:012}", json.dumps(value), priority, int(time.time()*1000)))
db.commit()
limit = time.monotonic()+5
while time.monotonic() < limit:
row = db.execute("SELECT state,result FROM bacnet_commands WHERE id=?", (cursor.lastrowid,)).fetchone()
if row[0] != "pending" and row[0] != "claimed":
assert row[0] == "done", row
return
time.sleep(.05)
raise AssertionError("Command was not processed")
try:
start()
# Field devices may send I-Am to the BACnet port, as a broadcast or unicast.
# The native socket must receive these while its normal ReadProperty service stays available.
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as broadcast, socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as peer:
broadcast.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
broadcast.bind(("127.255.255.255", 47828))
broadcast.settimeout(5)
peer.bind(("127.0.0.2", 47828))
peer.settimeout(5)
peer.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
for target in (None, "127.0.0.2"):
scan_id = "wire-broadcast" if target is None else "wire-direct"
db.execute("INSERT OR REPLACE INTO bacnet_discovery VALUES(1,?,?,?,?,0)",
(scan_id, target, 47828, int((time.time()+7)*1000)))
db.commit()
request, origin = (broadcast if target is None else peer).recvfrom(512)
assert origin == ("127.0.0.1", 47828) and request.endswith(b"\x10\x08"), (request.hex(), origin)
payload = bytes.fromhex("01001000c4") + ((8 << 22) | 1975).to_bytes(4, "big") + bytes.fromhex("2205c4910022032f")
function = 0x0b if target is None else 0x0a
peer.sendto(bytes([0x81, function, 0, len(payload)+4]) + payload,
("127.255.255.255" if target is None else "127.0.0.1", 47828))
if target is None:
routed = bytes.fromhex("01080014012a")
routed += payload[2:5] + ((8 << 22) | 1976).to_bytes(4, "big") + payload[9:]
peer.sendto(bytes([0x81, 0x0b, 0, len(routed)+4]) + routed, ("127.255.255.255", 47828))
for _ in range(30):
results = db.execute("SELECT device_instance,address,port,vendor,max_apdu,network,mac FROM bacnet_discovered_devices WHERE scan_id=? ORDER BY device_instance", (scan_id,)).fetchall()
if len(results) == (2 if target is None else 1):
break
time.sleep(.1)
assert results[0] == (1975, "127.0.0.2", 47828, 815, 1476, 0, None), results
if target is None:
assert results[1] == (1976, "127.0.0.2", 47828, 815, 1476, 20, "2A"), results
print("Native BACnet discovery passed: source port, broadcast and direct I-Am")
assert read(8, 120) == "815", read(8, 120)
object_list = read(8, 76)
for _, number in types: assert read(number, 75), number
assert "analog-value" in object_list.lower(), object_list
write(0, 4, 10, success=False) # AI Present_Value is not externally writable while in service.
write(2, 4, 21.5)
assert float(read(2)) == 21.5
write(2, 4, 30, 14)
command(3, 22, 16)
assert float(read(2)) == 30 and float(read(2, 87, 16)) == 22
write(2, 0, 0, 14)
assert float(read(2)) == 22
write(2, 4, 31, 14)
server.terminate(); server.wait(timeout=5); start()
assert float(read(2)) == 31 and float(read(2, 87, 16)) == 22, "Priority slots must survive a native service restart"
write(2, 0, 0, 14)
assert float(read(2)) == 22
write(2, 4, 99, 6, success=False)
command(1, 18.75)
assert float(read(0)) == 18.75
command(6, True)
assert "active" in read(5).lower() or read(5) == "1", read(5)
command(9, 3)
assert int(read(19)) == 3
# Use the upstream COV client with an explicit loopback-only address cache.
(work / "address_cache").write_text("900023 7F:00:00:01:BA:D4 0 0 1476\n")
cov_log = open(work / "cov.log", "w")
cov = subprocess.Popen(["stdbuf", "-oL", str(runtime / "bacscov"), "900023", "2", "77", "17", "unconfirmed", "30"],
cwd=work, env={**environment, "BACNET_IP_PORT": "47830"}, stdout=cov_log, stderr=cov_log)
time.sleep(1)
write(2, 4, 42.5)
time.sleep(2)
cov_log.flush()
cov_text = (work / "cov.log").read_text()
assert "Acknowledged" in cov_text and cov_text.count("Received Notification!") >= 2 and float(read(2)) == 42.5, cov_text
latest = db.execute("SELECT value_json,status FROM bacnet_observations WHERE point_id LIKE '%000000000003' ORDER BY id DESC LIMIT 1").fetchone()
assert float(latest[0]) == 42.5 and latest[1] == "Good", latest
# A new object appears without restarting the server.
db.execute("INSERT INTO points SELECT '00000000-0000-0000-0000-000000000099','Late AV',protocol,scope,value_type,readable,writable,NULL,address_json,created_at_utc,bacnet_object_kind,99,NULL FROM points WHERE bacnet_object_kind='AnalogValue'")
db.commit(); time.sleep(1.3)
assert "99" in read(8, 76)
db.execute("UPDATE points SET display_name='Renamed AV' WHERE bacnet_object_kind='AnalogValue' AND bacnet_object_instance=77")
db.commit(); time.sleep(1.3)
assert "Renamed AV" in read(2, 77) and float(read(2)) == 42.5
db.execute("UPDATE points SET deleted_at_utc='2026-11-19T00:00:00Z' WHERE id LIKE '%000000000099'")
db.commit(); time.sleep(1.3)
assert "99" not in read(8, 76)
print("BACnet wire tests passed: native Object_List, AI/AO/AV/BI/BO/BV/MSI/MSO/MSV/Schedule/Calendar, priority 16/14/NULL, persistence, COV, live creation, command/observation bridge.")
finally:
if cov is not None: cov.terminate(); cov.wait(timeout=5)
if server is not None and server.poll() is None: server.terminate(); server.wait(timeout=5)
db.close(); log.close()
print(f"Isolated test evidence: {work}")