From 9cb2d67b4037bc7a980b0ed8d3ff7ccd1cc33291 Mon Sep 17 00:00:00 2001 From: Christian Gleissner Date: Wed, 14 Oct 2026 19:28:04 +0100 Subject: [PATCH 1/8] Resolve a unicast stream destination on the wired port --- software/io/network/data_streamer.cc | 30 +++-------------------- software/io/network/data_streamer.h | 1 - software/io/network/debug_streamer_u2p.cc | 30 +++-------------------- software/io/network/debug_streamer_u2p.h | 1 - software/io/network/network_interface.cc | 10 ++++++++ software/io/network/network_interface.h | 1 + 6 files changed, 17 insertions(+), 56 deletions(-) diff --git a/software/io/network/data_streamer.cc b/software/io/network/data_streamer.cc index 16582b9e6..317320bf0 100644 --- a/software/io/network/data_streamer.cc +++ b/software/io/network/data_streamer.cc @@ -202,7 +202,9 @@ SubsysResultCode_e DataStreamer :: startStream(SubsysCommand *cmd) } else { bool ok = false; for(int i=0;i<10;i++) { - send_udp_packet(query_ip, stream->dest_port); + // Ask on the wired port itself: lwIP routes by destination, which picks WiFi + // on a unit that has both, and the answer would land in WiFi's ARP table. + intf->sendArpRequest(query_ip); vTaskDelay(20); if (intf->peekArpTable(query_ip, stream->dest_mac)) { ok = true; @@ -280,32 +282,6 @@ void DataStreamer :: update_task_items(bool writablePath) myActions.stopDbg->setHidden(streams[2].enable == 0); } -void DataStreamer :: send_udp_packet(uint32_t ip, uint16_t port) -{ - int sockfd; - static struct sockaddr_in server; - - sockfd = socket(AF_INET, SOCK_DGRAM, 0); - if (sockfd < 0) - { - printf("Error opening socket to send UDP packet\n"); - return; - } - - memset((char*)&server, 0, sizeof(server)); - server.sin_family = AF_INET; - server.sin_addr.s_addr = ip; - server.sin_port = htons(port); - - uint8_t buffer[2] = { 0, 0 }; - printf("Send UDP data...\n"); - if (sendto(sockfd, buffer, 2, 0, (const struct sockaddr*)&server, sizeof(server)) < 0) { - printf("Error in sendto()\n"); - } - // close the socket again - lwip_close(sockfd); -} - void DataStreamer :: calculate_udp_headers(int id) { diff --git a/software/io/network/data_streamer.h b/software/io/network/data_streamer.h index a09093c34..052ff04f9 100644 --- a/software/io/network/data_streamer.h +++ b/software/io/network/data_streamer.h @@ -52,7 +52,6 @@ class DataStreamer : public ObjectWithMenu SubsysResultCode_e stopStream(SubsysCommand *cmd); void calculate_udp_headers(int id); - void send_udp_packet(uint32_t ip, uint16_t port); public: DataStreamer(); virtual ~DataStreamer(); diff --git a/software/io/network/debug_streamer_u2p.cc b/software/io/network/debug_streamer_u2p.cc index 767f768d4..8bab8546c 100644 --- a/software/io/network/debug_streamer_u2p.cc +++ b/software/io/network/debug_streamer_u2p.cc @@ -194,7 +194,9 @@ SubsysResultCode_e DataStreamer :: startStream(SubsysCommand *cmd) } else { bool ok = false; for(int i=0;i<10;i++) { - send_udp_packet(query_ip, stream->dest_port); + // Ask on the wired port itself: lwIP routes by destination, which picks WiFi + // on a unit that has both, and the answer would land in WiFi's ARP table. + intf->sendArpRequest(query_ip); vTaskDelay(20); if (intf->peekArpTable(query_ip, stream->dest_mac)) { ok = true; @@ -265,32 +267,6 @@ void DataStreamer :: update_task_items(bool writablePath) } } -void DataStreamer :: send_udp_packet(uint32_t ip, uint16_t port) -{ - int sockfd; - static struct sockaddr_in server; - - sockfd = socket(AF_INET, SOCK_DGRAM, 0); - if (sockfd < 0) - { - printf("Error opening socket to send UDP packet\n"); - return; - } - - bzero((char*)&server, sizeof(server)); - server.sin_family = AF_INET; - server.sin_addr.s_addr = ip; - server.sin_port = htons(port); - - uint8_t buffer[2] = { 0, 0 }; - printf("Send UDP data...\n"); - if (sendto(sockfd, buffer, 2, 0, (const struct sockaddr*)&server, sizeof(server)) < 0) { - printf("Error in sendto()\n"); - } - // close the socket again - lwip_close(sockfd); -} - void DataStreamer :: calculate_udp_headers(int id) { diff --git a/software/io/network/debug_streamer_u2p.h b/software/io/network/debug_streamer_u2p.h index cef69013c..3e9323988 100644 --- a/software/io/network/debug_streamer_u2p.h +++ b/software/io/network/debug_streamer_u2p.h @@ -49,7 +49,6 @@ class DataStreamer : public ObjectWithMenu SubsysResultCode_e stopStream(SubsysCommand *cmd); void calculate_udp_headers(int id); - void send_udp_packet(uint32_t ip, uint16_t port); public: DataStreamer(); virtual ~DataStreamer(); diff --git a/software/io/network/network_interface.cc b/software/io/network/network_interface.cc index c495c3c88..506e4f076 100644 --- a/software/io/network/network_interface.cc +++ b/software/io/network/network_interface.cc @@ -492,6 +492,16 @@ bool NetworkInterface :: peekArpTable(uint32_t ipToQuery, uint8_t *mac) return ret; } +void NetworkInterface :: sendArpRequest(uint32_t ipToQuery) +{ + ip4_addr_t query_ip; + query_ip.addr = ipToQuery; + + LOCK_TCPIP_CORE(); + etharp_request(&my_net_if, &query_ip); + UNLOCK_TCPIP_CORE(); +} + void NetworkInterface :: on_edit() { uint8_t mac[8]; diff --git a/software/io/network/network_interface.h b/software/io/network/network_interface.h index 5d763ef58..25367f11f 100644 --- a/software/io/network/network_interface.h +++ b/software/io/network/network_interface.h @@ -139,6 +139,7 @@ class NetworkInterface : protected ConfigurableObject void setIpAddr(uint8_t *a); char *getIpAddrString(char *buf, int buflen); bool peekArpTable(uint32_t ipToQuery, uint8_t *mac); + void sendArpRequest(uint32_t ipToQuery); // callbacks static void statusCallback(struct netif *); From c9e77248b02b9936480e6e411a67f09d0f87c9b3 Mon Sep 17 00:00:00 2001 From: Christian Gleissner Date: Wed, 14 Oct 2026 19:39:26 +0100 Subject: [PATCH 2/8] Test stream start and stop over either interface --- run-tests | 5 + tests/e2e/network/stream_routing_test.py | 183 +++++++++++++++++++++++ 2 files changed, 188 insertions(+) create mode 100755 tests/e2e/network/stream_routing_test.py diff --git a/run-tests b/run-tests index d38352a6c..2edb9fef2 100755 --- a/run-tests +++ b/run-tests @@ -416,6 +416,11 @@ SUITES: Sequence[Suite] = ( # a static one, and the device uses the "Static DNS" server. Suite("e2e", "stream-wired-link", "tests/e2e/network/stream_wired_link_test.py", "-H @HOST@ -p @PASS@ -t @TIMEOUT@", manual=True), + # Streams leave through the wired port whichever interface asked for them: + # every pairing of the interface that starts a stream with the one that + # stops it, unicast and multicast. + Suite("e2e", "stream-routing", "tests/e2e/network/stream_routing_test.py", + "-H @HOST@ -p @PASS@ -t @TIMEOUT@"), # Drives the machine's online file search (Assembly 64, or CommoServe on a # C64 Ultimate), mostly with negative cases. Skips when it is unreachable. Suite("e2e", "assembly64", "tests/e2e/io/c64/assembly64_test.py", diff --git a/tests/e2e/network/stream_routing_test.py b/tests/e2e/network/stream_routing_test.py new file mode 100755 index 000000000..d0145fa00 --- /dev/null +++ b/tests/e2e/network/stream_routing_test.py @@ -0,0 +1,183 @@ +#!/usr/bin/env python3 +"""E2E: the streams start and stop over either interface, and leave by the wired one. + +For video and audio to a unicast port on this host, and for video to its +multicast group, every pairing of the interface that starts the stream with the +interface that stops it. Each started stream has to arrive from the wired +address with the stream's own source port and packet size, with nothing from +the WiFi address, and each stopped stream has to fall silent. A device that +answers on only one address runs the one pairing it has and skips the rest. + +A unicast start needs the destination's hardware address on the wired port. +The pairings started over WiFi run first, and the wired address is found from +a multicast start, which needs no ARP, so the first unicast check meets a wired +port that has not resolved this host since it booted or since this host last +addressed it. A lookup routed through WiFi fails that check with 404. + + ./run-tests --suite stream-routing u64 +""" + +import argparse +import socket +import sys +import time +from collections import Counter +from pathlib import Path + +# The one stanza that puts the shared library on sys.path; see tests/lib/bootstrap.py. +sys.path.insert(0, str(next(p for p in Path(__file__).resolve().parents + if (p / "tests" / "lib").is_dir()) / "tests" / "lib")) +import bootstrap # noqa: E402,F401 +import cli # noqa: E402 +sys.path.insert(0, bootstrap.directory("e2e", "network")) + +import machine as machine_lib # noqa: E402 +import streams # noqa: E402 +import targets # noqa: E402 +from api import UltimateApi # noqa: E402 +from report import (Failure, check, check_skip, check_start, detail, # noqa: E402 + format_exception, suite_fail, suite_ok, suite_skip, + teardown_step) +from stream_wired_link_test import (collect, expect_refusal, ident_addresses, # noqa: E402 + local_address, senders_on_groups, start_video, + stream_sender) + +SUITE = "stream_routing_test" + +# Source port and datagram size of each stream, from DataStreamer. +STREAM_SOURCE = {"video": (53248, streams.VIDEO_PACKET_BYTES), + "audio": (54272, streams.AUDIO_PACKET_BYTES)} +# A quarter of the roughly 3400 video and 250 audio packets one second carries. +MIN_PACKETS = {"video": 800, "audio": 60} + +LISTEN_SECONDS = 1.0 +# Packets already on the wire when the stop was answered. +DRAIN_SECONDS = 0.3 + + +def receiver(group: str | None) -> tuple[socket.socket, int]: + """A socket on a free unicast port, or on the video group's port.""" + if group is None: + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + sock.bind(("", 0)) + sock.settimeout(0.1) + return sock, sock.getsockname()[1] + return streams.stream_socket(group, streams.VIDEO_PORT, timeout=0.1), streams.VIDEO_PORT + + +def expect_stream(seen: Counter, stream: str, wired: str, wireless: set[str]) -> str: + """Raise unless `stream` arrived from the wired address and none of it + from the wireless one. Another device on the group is ignored.""" + port, size = STREAM_SOURCE[stream] + ours = sum(n for (sender, sport, length), n in seen.items() + if sender == wired and sport == port and length == size) + stray = {key: n for key, n in seen.items() if key[0] in wireless} + if stray: + raise Failure(f"packets from the wireless address: {stray}") + if ours < MIN_PACKETS[stream]: + raise Failure(f"{ours} {stream} packets from {wired}:{port} in " + f"{LISTEN_SECONDS:.1f}s, expected at least {MIN_PACKETS[stream]}; " + f"saw {dict(seen)}") + return f"{ours} packets from {wired}:{port}" + + +def expect_silence(sock: socket.socket, wired: str) -> None: + time.sleep(DRAIN_SECONDS) + sock.setblocking(False) + try: + while True: + sock.recvfrom(2048) + except OSError: + pass + finally: + sock.settimeout(0.1) + late = sum(n for key, n in collect(sock, LISTEN_SECONDS).items() if key[0] == wired) + if late: + raise Failure(f"{late} packets from {wired} after the stop") + + +def routing(apis: dict[str, UltimateApi], wired: str, wireless: set[str], + local: str) -> None: + # WiFi first, so the first unicast start meets a wired port that has not + # resolved this host. + names = sorted(apis, reverse=True) + pairs = [(a, b) for a in names for b in names] + for stream, group in (("video", None), ("audio", None), + ("video", streams.VIDEO_GROUP)): + where = "multicast" if group else "unicast" + for via_start, via_stop in pairs: + sock, port = receiver(group) + try: + with check(f"{stream} {where}: start over {via_start}, stop over {via_stop}"): + code, _, body = apis[via_start].rest.request( + "PUT", f"/v1/streams/{stream}:start", + params={"ip": f"{group or local}:{port}"}) + if code != 200: + raise Failure(f"start returned HTTP {code}: {body[:160]!r}") + detail(expect_stream(collect(sock, LISTEN_SECONDS), stream, + wired, wireless)) + apis[via_stop].streams.stop(stream) + expect_silence(sock, wired) + finally: + sock.close() + teardown_step(f"stop {stream}", lambda: apis[via_stop].streams.stop(stream)) + if len(names) == 1: + check_start(f"{stream} {where}: start and stop over different interfaces") + check_skip("the device answers on one address only") + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + cli.add_device_arguments(parser) + args = parser.parse_args() + password = args.password or None + + host = targets.device_of(args.host) + api = UltimateApi(args.host, password, args.timeout) + info = api.info() + machine = machine_lib.identify(host, lambda: (str(info.product), + str(info.firmware_version))) + if not machine.has_data_streams: + suite_skip(SUITE, f"{machine.described} has no data streams") + return 0 + + failure = "" + running: set[str] = set() + try: + before = senders_on_groups() + code, body, seen = start_video(api) + if code != 200: + expect_refusal(code, body) + suite_skip(SUITE, "the device has no wired address, which the streams need") + return 0 + api.streams.stop("video") + wired = stream_sender(seen, before["video"]) + running = {name for name, senders in before.items() if wired in senders} + local = local_address(socket.gethostbyname(host)) + found = ident_addresses(str(info.extra.get("unique_id", "")), local) + wireless = (found | {socket.gethostbyname(host)}) - {wired} + detail(f"wired {wired}, wireless {sorted(wireless) or 'none'}, this host {local}") + apis = {"Ethernet": UltimateApi(wired, password, args.timeout)} + if wireless: + apis["WiFi"] = UltimateApi(min(wireless), password, args.timeout) + routing(apis, wired, wireless, local) + except Failure as exc: + failure = str(exc) + except Exception as exc: # noqa: BLE001 + failure = format_exception(exc) + finally: + # Leave the standard streams as they were found, for a recorder. + for name in sorted(running): + teardown_step(f"restart {name}", lambda name=name: api.streams.start( + name, ip=streams.Arming(api, args.host).address(name))) + + if failure: + suite_fail(SUITE, failure) + return 1 + suite_ok(SUITE) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) From 88ff872fb61b683bcae1f9c12571a55032ca1458 Mon Sep 17 00:00:00 2001 From: Christian Gleissner Date: Wed, 14 Oct 2026 19:45:31 +0100 Subject: [PATCH 3/8] Print the refused start's answer as text --- tests/e2e/network/stream_routing_test.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/e2e/network/stream_routing_test.py b/tests/e2e/network/stream_routing_test.py index d0145fa00..481928221 100755 --- a/tests/e2e/network/stream_routing_test.py +++ b/tests/e2e/network/stream_routing_test.py @@ -113,7 +113,8 @@ def routing(apis: dict[str, UltimateApi], wired: str, wireless: set[str], "PUT", f"/v1/streams/{stream}:start", params={"ip": f"{group or local}:{port}"}) if code != 200: - raise Failure(f"start returned HTTP {code}: {body[:160]!r}") + raise Failure(f"start returned HTTP {code}: " + f"{' '.join(body.decode('utf-8', 'replace').split())}") detail(expect_stream(collect(sock, LISTEN_SECONDS), stream, wired, wireless)) apis[via_stop].streams.stop(stream) From f236a092059f4847525aad5df554d8b94cae57a8 Mon Sep 17 00:00:00 2001 From: Christian Gleissner Date: Wed, 14 Oct 2026 20:00:27 +0100 Subject: [PATCH 4/8] Address review: comment wording, document the resolve error, test helpers --- doc/api/rest_api_openapi_u64.yaml | 6 ++ software/api/route_streams.cc | 5 ++ software/io/network/data_streamer.cc | 4 +- software/io/network/debug_streamer_u2p.cc | 4 +- tests/e2e/network/stream_routing_test.py | 92 ++++++++++++----------- 5 files changed, 64 insertions(+), 47 deletions(-) diff --git a/doc/api/rest_api_openapi_u64.yaml b/doc/api/rest_api_openapi_u64.yaml index 5a4901078..e05c13c45 100644 --- a/doc/api/rest_api_openapi_u64.yaml +++ b/doc/api/rest_api_openapi_u64.yaml @@ -3354,6 +3354,8 @@ paths: `ip` may be an address or a host name, and may carry a port as `address:port`. Without a port the stream goes to 11000 for video, 11001 for audio and 11002 for debug. A multicast group from 232.0.0.0 to 239.255.255.255 is accepted in place of a single host, in which case every listener that joined the group receives the stream. + To send to a single host the device looks up that host's hardware address on the wired port, or the gateway's when the host is on another subnet. When the name cannot be resolved, or that address does not answer, the call fails with 404. + Video and debug share hardware and cannot both run, so starting video stops debug first. The streams leave through the wired Ethernet port only, whichever interface carried this request. Without an Ethernet link that has an IP address the call fails, even when WiFi is connected. @@ -3397,6 +3399,10 @@ paths: value: errors: - 'Unrecognized stream name ''screen''' + Network Host Resolve Error: + value: + errors: + - Network Host Resolve Error '500': description: Internal server error content: diff --git a/software/api/route_streams.cc b/software/api/route_streams.cc index ab8482983..9b501dd9c 100644 --- a/software/api/route_streams.cc +++ b/software/api/route_streams.cc @@ -26,6 +26,10 @@ API_DOC(PUT, streams, start, "of a single host, in which case every listener that joined the group receives " "the stream.\n" "\n" + "To send to a single host the device looks up that host's hardware address on the " + "wired port, or the gateway's when the host is on another subnet. When the name " + "cannot be resolved, or that address does not answer, the call fails with 404.\n" + "\n" "Video and debug share hardware and cannot both run, so starting video stops " "debug first.\n" "\n" @@ -38,6 +42,7 @@ API_DOC(PUT, streams, start, PARAM("ip", "string", "Where to send the stream. An address, optionally followed by a port.", "", "192.168.1.10:11000") RESPONSE("200", "application/json", "ErrorResponse", "The stream is running.", "") RESPONSE_ERROR("404", "Unrecognized stream name 'screen'", "") + RESPONSE_ERROR("404", "Network Host Resolve Error", "") RESPONSE_ERROR("500", "Wired Ethernet link is down or has no IP address", "") ) API_CALL(PUT, streams, start, NULL, ARRAY ( { { "ip", P_REQUIRED } })) diff --git a/software/io/network/data_streamer.cc b/software/io/network/data_streamer.cc index 317320bf0..2c7d5968a 100644 --- a/software/io/network/data_streamer.cc +++ b/software/io/network/data_streamer.cc @@ -202,8 +202,8 @@ SubsysResultCode_e DataStreamer :: startStream(SubsysCommand *cmd) } else { bool ok = false; for(int i=0;i<10;i++) { - // Ask on the wired port itself: lwIP routes by destination, which picks WiFi - // on a unit that has both, and the answer would land in WiFi's ARP table. + // Ask on the wired port itself. lwIP sends by the first netif on the destination's + // subnet, which is WiFi when both share one, and the answer would land in its table. intf->sendArpRequest(query_ip); vTaskDelay(20); if (intf->peekArpTable(query_ip, stream->dest_mac)) { diff --git a/software/io/network/debug_streamer_u2p.cc b/software/io/network/debug_streamer_u2p.cc index 8bab8546c..301188c04 100644 --- a/software/io/network/debug_streamer_u2p.cc +++ b/software/io/network/debug_streamer_u2p.cc @@ -194,8 +194,8 @@ SubsysResultCode_e DataStreamer :: startStream(SubsysCommand *cmd) } else { bool ok = false; for(int i=0;i<10;i++) { - // Ask on the wired port itself: lwIP routes by destination, which picks WiFi - // on a unit that has both, and the answer would land in WiFi's ARP table. + // Ask on the wired port itself. lwIP sends by the first netif on the destination's + // subnet, which is WiFi when both share one, and the answer would land in its table. intf->sendArpRequest(query_ip); vTaskDelay(20); if (intf->peekArpTable(query_ip, stream->dest_mac)) { diff --git a/tests/e2e/network/stream_routing_test.py b/tests/e2e/network/stream_routing_test.py index 481928221..c570bc180 100755 --- a/tests/e2e/network/stream_routing_test.py +++ b/tests/e2e/network/stream_routing_test.py @@ -9,10 +9,12 @@ answers on only one address runs the one pairing it has and skips the rest. A unicast start needs the destination's hardware address on the wired port. -The pairings started over WiFi run first, and the wired address is found from -a multicast start, which needs no ARP, so the first unicast check meets a wired -port that has not resolved this host since it booted or since this host last -addressed it. A lookup routed through WiFi fails that check with 404. +The wired address is found from a multicast start, which needs no ARP, and the +pairings started over WiFi run first. A lookup sent through WiFi shows in one +of two ways. When the wired port has not resolved this host, which is the case +after the device starts and until this host next addresses the wired port, the +start fails with 404. When it has, the probe the lookup sends arrives on the +receiving port from the WiFi address. ./run-tests --suite stream-routing u64 """ @@ -38,9 +40,9 @@ from report import (Failure, check, check_skip, check_start, detail, # noqa: E402 format_exception, suite_fail, suite_ok, suite_skip, teardown_step) -from stream_wired_link_test import (collect, expect_refusal, ident_addresses, # noqa: E402 - local_address, senders_on_groups, start_video, - stream_sender) +from stream_wired_link_test import (collect, expect_refusal, local_address, # noqa: E402 + senders_on_groups, standard_groups, start_video, + stream_sender, wireless_address) SUITE = "stream_routing_test" @@ -56,22 +58,23 @@ def receiver(group: str | None) -> tuple[socket.socket, int]: - """A socket on a free unicast port, or on the video group's port.""" - if group is None: - sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - sock.bind(("", 0)) - sock.settimeout(0.1) - return sock, sock.getsockname()[1] - return streams.stream_socket(group, streams.VIDEO_PORT, timeout=0.1), streams.VIDEO_PORT - - -def expect_stream(seen: Counter, stream: str, wired: str, wireless: set[str]) -> str: - """Raise unless `stream` arrived from the wired address and none of it - from the wireless one. Another device on the group is ignored.""" + """A socket on a free port, joined to `group` when one is given.""" + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + sock.bind(("", 0)) + if group is not None: + sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, + socket.inet_aton(group) + socket.inet_aton("0.0.0.0")) + sock.settimeout(0.1) + return sock, sock.getsockname()[1] + + +def expect_stream(seen: Counter, stream: str, wired: str, wireless: str | None) -> str: + """Raise unless `stream` arrived from the wired address, and nothing from + the wireless one.""" port, size = STREAM_SOURCE[stream] ours = sum(n for (sender, sport, length), n in seen.items() if sender == wired and sport == port and length == size) - stray = {key: n for key, n in seen.items() if key[0] in wireless} + stray = {key: n for key, n in seen.items() if key[0] == wireless} if stray: raise Failure(f"packets from the wireless address: {stray}") if ours < MIN_PACKETS[stream]: @@ -96,22 +99,21 @@ def expect_silence(sock: socket.socket, wired: str) -> None: raise Failure(f"{late} packets from {wired} after the stop") -def routing(apis: dict[str, UltimateApi], wired: str, wireless: set[str], - local: str) -> None: +def routing(apis: dict[str, UltimateApi], wired: str, wireless: str | None, + local: str, group: str) -> None: # WiFi first, so the first unicast start meets a wired port that has not # resolved this host. - names = sorted(apis, reverse=True) + names = [name for name in ("WiFi", "Ethernet") if name in apis] pairs = [(a, b) for a in names for b in names] - for stream, group in (("video", None), ("audio", None), - ("video", streams.VIDEO_GROUP)): - where = "multicast" if group else "unicast" + for stream, joined in (("video", None), ("audio", None), ("video", group)): + where = "multicast" if joined else "unicast" for via_start, via_stop in pairs: - sock, port = receiver(group) + sock, port = receiver(joined) try: with check(f"{stream} {where}: start over {via_start}, stop over {via_stop}"): code, _, body = apis[via_start].rest.request( "PUT", f"/v1/streams/{stream}:start", - params={"ip": f"{group or local}:{port}"}) + params={"ip": f"{joined or local}:{port}"}) if code != 200: raise Failure(f"start returned HTTP {code}: " f"{' '.join(body.decode('utf-8', 'replace').split())}") @@ -134,11 +136,11 @@ def main() -> int: args = parser.parse_args() password = args.password or None - host = targets.device_of(args.host) + target = targets.resolve(args.host) api = UltimateApi(args.host, password, args.timeout) info = api.info() - machine = machine_lib.identify(host, lambda: (str(info.product), - str(info.firmware_version))) + machine = machine_lib.identify(target.device, lambda: (str(info.product), + str(info.firmware_version))) if not machine.has_data_streams: suite_skip(SUITE, f"{machine.described} has no data streams") return 0 @@ -146,23 +148,26 @@ def main() -> int: failure = "" running: set[str] = set() try: - before = senders_on_groups() - code, body, seen = start_video(api) + before = senders_on_groups(target) + code, body, seen = start_video(api, target.video_group) if code != 200: expect_refusal(code, body) suite_skip(SUITE, "the device has no wired address, which the streams need") return 0 - api.streams.stop("video") - wired = stream_sender(seen, before["video"]) + try: + wired = stream_sender(seen) + except Failure: + api.streams.stop("video") + raise running = {name for name, senders in before.items() if wired in senders} - local = local_address(socket.gethostbyname(host)) - found = ident_addresses(str(info.extra.get("unique_id", "")), local) - wireless = (found | {socket.gethostbyname(host)}) - {wired} - detail(f"wired {wired}, wireless {sorted(wireless) or 'none'}, this host {local}") + api.streams.stop("video") + local = local_address(socket.gethostbyname(target.device)) + wireless = wireless_address(api, info, wired, local) + detail(f"wired {wired}, wireless {wireless or 'none'}, this host {local}") apis = {"Ethernet": UltimateApi(wired, password, args.timeout)} if wireless: - apis["WiFi"] = UltimateApi(min(wireless), password, args.timeout) - routing(apis, wired, wireless, local) + apis["WiFi"] = UltimateApi(wireless, password, args.timeout) + routing(apis, wired, wireless, local, target.video_group) except Failure as exc: failure = str(exc) except Exception as exc: # noqa: BLE001 @@ -170,8 +175,9 @@ def main() -> int: finally: # Leave the standard streams as they were found, for a recorder. for name in sorted(running): - teardown_step(f"restart {name}", lambda name=name: api.streams.start( - name, ip=streams.Arming(api, args.host).address(name))) + group_port = standard_groups(target)[name] + teardown_step(f"restart {name}", lambda name=name, group_port=group_port: + api.streams.start(name, ip=f"{group_port[0]}:{group_port[1]}")) if failure: suite_fail(SUITE, failure) From 974a2f6b6915397d448ada7f1a369296530f1973 Mon Sep 17 00:00:00 2001 From: Christian Gleissner Date: Wed, 14 Oct 2026 20:02:35 +0100 Subject: [PATCH 5/8] State only the observed failure in the routing suite's description --- tests/e2e/network/stream_routing_test.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/tests/e2e/network/stream_routing_test.py b/tests/e2e/network/stream_routing_test.py index c570bc180..07391944e 100755 --- a/tests/e2e/network/stream_routing_test.py +++ b/tests/e2e/network/stream_routing_test.py @@ -10,11 +10,10 @@ A unicast start needs the destination's hardware address on the wired port. The wired address is found from a multicast start, which needs no ARP, and the -pairings started over WiFi run first. A lookup sent through WiFi shows in one -of two ways. When the wired port has not resolved this host, which is the case -after the device starts and until this host next addresses the wired port, the -start fails with 404. When it has, the probe the lookup sends arrives on the -receiving port from the WiFi address. +pairings started over WiFi run first. After the device starts, the wired port +has no ARP entry for this host until this host sends it an ARP request, so the +first unicast start depends on the lookup going out through the wired port; +one sent through WiFi fails it with 404. ./run-tests --suite stream-routing u64 """ From f4434b21098093a9193750b49428a7c6ede14019 Mon Sep 17 00:00:00 2001 From: Christian Gleissner Date: Sat, 17 Oct 2026 18:16:19 +0100 Subject: [PATCH 6/8] Bound stream test drain and clarify ARP lookup documentation --- doc/api/rest_api_openapi_u64.yaml | 2 +- software/api/route_streams.cc | 4 ++-- tests/e2e/network/stream_routing_test.py | 23 +++++++---------------- 3 files changed, 10 insertions(+), 19 deletions(-) diff --git a/doc/api/rest_api_openapi_u64.yaml b/doc/api/rest_api_openapi_u64.yaml index e05c13c45..26039f685 100644 --- a/doc/api/rest_api_openapi_u64.yaml +++ b/doc/api/rest_api_openapi_u64.yaml @@ -3354,7 +3354,7 @@ paths: `ip` may be an address or a host name, and may carry a port as `address:port`. Without a port the stream goes to 11000 for video, 11001 for audio and 11002 for debug. A multicast group from 232.0.0.0 to 239.255.255.255 is accepted in place of a single host, in which case every listener that joined the group receives the stream. - To send to a single host the device looks up that host's hardware address on the wired port, or the gateway's when the host is on another subnet. When the name cannot be resolved, or that address does not answer, the call fails with 404. + To send to a single host the device looks up that host's hardware address on the wired port, or the gateway's when the host is on another subnet. When name resolution or the hardware-address lookup fails, the call fails with 404. Video and debug share hardware and cannot both run, so starting video stops debug first. diff --git a/software/api/route_streams.cc b/software/api/route_streams.cc index 9b501dd9c..b50513767 100644 --- a/software/api/route_streams.cc +++ b/software/api/route_streams.cc @@ -27,8 +27,8 @@ API_DOC(PUT, streams, start, "the stream.\n" "\n" "To send to a single host the device looks up that host's hardware address on the " - "wired port, or the gateway's when the host is on another subnet. When the name " - "cannot be resolved, or that address does not answer, the call fails with 404.\n" + "wired port, or the gateway's when the host is on another subnet. When name " + "resolution or the hardware-address lookup fails, the call fails with 404.\n" "\n" "Video and debug share hardware and cannot both run, so starting video stops " "debug first.\n" diff --git a/tests/e2e/network/stream_routing_test.py b/tests/e2e/network/stream_routing_test.py index 07391944e..ec70523e9 100755 --- a/tests/e2e/network/stream_routing_test.py +++ b/tests/e2e/network/stream_routing_test.py @@ -10,10 +10,10 @@ A unicast start needs the destination's hardware address on the wired port. The wired address is found from a multicast start, which needs no ARP, and the -pairings started over WiFi run first. After the device starts, the wired port -has no ARP entry for this host until this host sends it an ARP request, so the -first unicast start depends on the lookup going out through the wired port; -one sent through WiFi fails it with 404. +pairings started over WiFi run first. To exercise an uncached lookup, run after +a fresh device boot and address the suite to WiFi, without prior traffic to +the wired address. A successful start with a warm wired ARP entry does not by +itself prove that an uncached lookup uses the wired port. ./run-tests --suite stream-routing u64 """ @@ -21,7 +21,6 @@ import argparse import socket import sys -import time from collections import Counter from pathlib import Path @@ -84,15 +83,8 @@ def expect_stream(seen: Counter, stream: str, wired: str, wireless: str | None) def expect_silence(sock: socket.socket, wired: str) -> None: - time.sleep(DRAIN_SECONDS) - sock.setblocking(False) - try: - while True: - sock.recvfrom(2048) - except OSError: - pass - finally: - sock.settimeout(0.1) + # Bound the drain even when a broken stop leaves the stream running. + collect(sock, DRAIN_SECONDS) late = sum(n for key, n in collect(sock, LISTEN_SECONDS).items() if key[0] == wired) if late: raise Failure(f"{late} packets from {wired} after the stop") @@ -100,8 +92,7 @@ def expect_silence(sock: socket.socket, wired: str) -> None: def routing(apis: dict[str, UltimateApi], wired: str, wireless: str | None, local: str, group: str) -> None: - # WiFi first, so the first unicast start meets a wired port that has not - # resolved this host. + # WiFi first to avoid warming the wired ARP entry through a REST connection. names = [name for name in ("WiFi", "Ethernet") if name in apis] pairs = [(a, b) for a in names for b in names] for stream, joined in (("video", None), ("audio", None), ("video", group)): From 4be12571022faa2907e9064dddd3825493aa27e7 Mon Sep 17 00:00:00 2001 From: Christian Gleissner Date: Sat, 17 Oct 2026 19:15:02 +0100 Subject: [PATCH 7/8] Cover stream control entry points and debug packet delivery Exercise video, audio and debug to unicast and multicast receivers across all REST/DMA and wired/WiFi start-stop pairs. Check retargeting, defaults, DMA timers, DNS and broadcast, stream interactions, invalid requests, all debug modes and menu cancellation/start/stop using existing helpers. Keep drains bounded and restore stream configuration during cleanup. Validated 141/141 checks on U64 firmware 69f3c7c26, including the latest upstream master merge. U2+L runs the same merged build and passes health checks; its cached FPGA has no debug-stream block. --- tests/e2e/network/stream_routing_test.py | 328 +++++++++++++++++++++-- 1 file changed, 304 insertions(+), 24 deletions(-) diff --git a/tests/e2e/network/stream_routing_test.py b/tests/e2e/network/stream_routing_test.py index ec70523e9..3814b9d12 100755 --- a/tests/e2e/network/stream_routing_test.py +++ b/tests/e2e/network/stream_routing_test.py @@ -1,12 +1,16 @@ #!/usr/bin/env python3 """E2E: the streams start and stop over either interface, and leave by the wired one. -For video and audio to a unicast port on this host, and for video to its -multicast group, every pairing of the interface that starts the stream with the -interface that stops it. Each started stream has to arrive from the wired -address with the stream's own source port and packet size, with nothing from +For video, audio and debug to unicast and multicast receivers, every pairing +of REST/DMA and Ethernet/WiFi controls that starts and stops the stream. +Each started stream has to arrive from the wired address with the stream's +own source port and packet size, with nothing from the WiFi address, and each stopped stream has to fall silent. A device that -answers on only one address runs the one pairing it has and skips the rest. +answers on only one address runs the available pairings and skips the rest. + +Also checks retargeting, default ports, DMA timers and configured destinations, +simultaneous streams, invalid requests, every debug mode, and menu start/stop +and cancellation. Pass --receiver-name to exercise DNS on the receiving host. A unicast start needs the destination's hardware address on the wired port. The wired address is found from a multicast start, which needs no ARP, and the @@ -19,8 +23,11 @@ """ import argparse +import ipaddress import socket +import struct import sys +import time from collections import Counter from pathlib import Path @@ -30,11 +37,16 @@ import bootstrap # noqa: E402,F401 import cli # noqa: E402 sys.path.insert(0, bootstrap.directory("e2e", "network")) +sys.path.insert(0, bootstrap.directory("soak", "network")) +import dma_probe # noqa: E402 import machine as machine_lib # noqa: E402 import streams # noqa: E402 import targets # noqa: E402 from api import UltimateApi # noqa: E402 +from stream_monitor import (DEBUG_PACKET_SIZE, STREAM_IDS, StreamKind, # noqa: E402 + StreamPacketTracker) +from ui_backend import MODE_OVERLAY, make_browser # noqa: E402 from report import (Failure, check, check_skip, check_start, detail, # noqa: E402 format_exception, suite_fail, suite_ok, suite_skip, teardown_step) @@ -46,19 +58,22 @@ # Source port and datagram size of each stream, from DataStreamer. STREAM_SOURCE = {"video": (53248, streams.VIDEO_PACKET_BYTES), - "audio": (54272, streams.AUDIO_PACKET_BYTES)} + "audio": (54272, streams.AUDIO_PACKET_BYTES), + "debug": (6510, DEBUG_PACKET_SIZE)} # A quarter of the roughly 3400 video and 250 audio packets one second carries. -MIN_PACKETS = {"video": 800, "audio": 60} +MIN_PACKETS = {"video": 800, "audio": 60, "debug": 1} LISTEN_SECONDS = 1.0 # Packets already on the wire when the stop was answered. DRAIN_SECONDS = 0.3 -def receiver(group: str | None) -> tuple[socket.socket, int]: +def receiver(group: str | None, port: int = 0) -> tuple[socket.socket, int]: """A socket on a free port, joined to `group` when one is given.""" sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - sock.bind(("", 0)) + if port: + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + sock.bind(("", port)) if group is not None: sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(group) + socket.inet_aton("0.0.0.0")) @@ -66,7 +81,27 @@ def receiver(group: str | None) -> tuple[socket.socket, int]: return sock, sock.getsockname()[1] -def expect_stream(seen: Counter, stream: str, wired: str, wireless: str | None) -> str: +def control(api: UltimateApi, protocol: str, stream: str, action: str, + destination: str | None = None, ticks: int = 0) -> None: + """Issue one control command; a DMA identify reply fences its execution.""" + if protocol == "REST": + if action == "start": + api.streams.start(stream, ip=destination) + else: + api.streams.stop(stream) + return + start = action == "start" + payload = (struct.pack(" str: """Raise unless `stream` arrived from the wired address, and nothing from the wireless one.""" port, size = STREAM_SOURCE[stream] @@ -75,9 +110,10 @@ def expect_stream(seen: Counter, stream: str, wired: str, wireless: str | None) stray = {key: n for key, n in seen.items() if key[0] == wireless} if stray: raise Failure(f"packets from the wireless address: {stray}") - if ours < MIN_PACKETS[stream]: + minimum = max(1, int(MIN_PACKETS[stream] * seconds / LISTEN_SECONDS)) + if ours < minimum: raise Failure(f"{ours} {stream} packets from {wired}:{port} in " - f"{LISTEN_SECONDS:.1f}s, expected at least {MIN_PACKETS[stream]}; " + f"{seconds:.1f}s, expected at least {minimum}; " f"saw {dict(seen)}") return f"{ours} packets from {wired}:{port}" @@ -90,26 +126,43 @@ def expect_silence(sock: socket.socket, wired: str) -> None: raise Failure(f"{late} packets from {wired} after the stop") +def expect_debug_data(sock: socket.socket, wired: str, wireless: str | None) -> str: + tracker = StreamPacketTracker(StreamKind.DEBUG, logger=lambda *_: None) + deadline = time.monotonic() + LISTEN_SECONDS + while time.monotonic() < deadline: + try: + data, sender = sock.recvfrom(2048) + except TimeoutError: + continue + if sender[0] == wireless: + raise Failure("debug data arrived from WiFi") + if sender == (wired, STREAM_SOURCE["debug"][0]): + tracker.note_packet(data) + result = tracker.snapshot() + if not result.packets_received or result.size_errors or result.header_errors or result.structure_errors: + raise Failure(f"invalid debug trace: {result}") + return f"{result.packets_received} trace packets with valid headers and bus-record lengths" + + def routing(apis: dict[str, UltimateApi], wired: str, wireless: str | None, local: str, group: str) -> None: # WiFi first to avoid warming the wired ARP entry through a REST connection. names = [name for name in ("WiFi", "Ethernet") if name in apis] - pairs = [(a, b) for a in names for b in names] - for stream, joined in (("video", None), ("audio", None), ("video", group)): + controllers = [(name, protocol) for name in names for protocol in ("REST", "DMA")] + pairs = [(a, b) for a in controllers for b in controllers] + cases = [(stream, joined) for stream in STREAM_SOURCE for joined in (None, group)] + for stream, joined in cases: where = "multicast" if joined else "unicast" - for via_start, via_stop in pairs: + for (via_start, start_protocol), (via_stop, stop_protocol) in pairs: sock, port = receiver(joined) try: - with check(f"{stream} {where}: start over {via_start}, stop over {via_stop}"): - code, _, body = apis[via_start].rest.request( - "PUT", f"/v1/streams/{stream}:start", - params={"ip": f"{joined or local}:{port}"}) - if code != 200: - raise Failure(f"start returned HTTP {code}: " - f"{' '.join(body.decode('utf-8', 'replace').split())}") + with check(f"{stream} {where}: {start_protocol}/{via_start} start, " + f"{stop_protocol}/{via_stop} stop"): + control(apis[via_start], start_protocol, stream, "start", + f"{joined or local}:{port}") detail(expect_stream(collect(sock, LISTEN_SECONDS), stream, wired, wireless)) - apis[via_stop].streams.stop(stream) + control(apis[via_stop], stop_protocol, stream, "stop") expect_silence(sock, wired) finally: sock.close() @@ -119,10 +172,228 @@ def routing(apis: dict[str, UltimateApi], wired: str, wireless: str | None, check_skip("the device answers on one address only") +def lifecycle(api: UltimateApi, wired: str, wireless: str | None, + local: str, group: str, receiver_name: str | None) -> None: + for stream in STREAM_SOURCE: + for protocol in ("REST", "DMA"): + first, first_port = receiver(None) + second, second_port = receiver(group) + try: + with check(f"{stream}: {protocol} repeated starts/stops and retargeting"): + control(api, protocol, stream, "stop") + control(api, protocol, stream, "stop") + for _ in range(2): + control(api, protocol, stream, "start", f"{local}:{first_port}") + detail(expect_stream(collect(first, LISTEN_SECONDS), stream, wired, wireless)) + control(api, protocol, stream, "start", f"{group}:{second_port}") + expect_silence(first, wired) + detail(expect_stream(collect(second, LISTEN_SECONDS), stream, wired, wireless)) + control(api, protocol, stream, "stop") + control(api, protocol, stream, "stop") + expect_silence(second, wired) + finally: + first.close() + second.close() + teardown_step(f"stop {stream}", lambda: api.streams.stop(stream)) + + # The default port is independent of the control transport. + sock, _ = receiver(None, 11000 + STREAM_IDS[stream]) + try: + with check(f"{stream}: default UDP port and case-insensitive REST name"): + api.streams.start(stream.upper(), ip=local) + detail(expect_stream(collect(sock, LISTEN_SECONDS), stream, wired, wireless)) + api.streams.stop(stream.upper()) + expect_silence(sock, wired) + finally: + sock.close() + teardown_step(f"stop {stream}", lambda: api.streams.stop(stream)) + + sock, port = receiver(None) + item = {"video": "Stream VIC to", "audio": "Stream Audio to", + "debug": "Stream Debug to"}[stream] + original = api.configs.current("Data Streams", item) + try: + with check(f"{stream}: DMA configured destination and timed stop"): + api.configs.set("Data Streams", item, f"{local}:{port}") + control(api, "DMA", stream, "start") + detail(expect_stream(collect(sock, LISTEN_SECONDS), stream, wired, wireless)) + control(api, "DMA", stream, "stop") + expect_silence(sock, wired) + # FreeRTOSConfig.h defines 200 ticks/second: two seconds. + control(api, "DMA", stream, "start", ticks=400) + detail(expect_stream(collect(sock, LISTEN_SECONDS), stream, wired, wireless)) + time.sleep(1.2) + expect_silence(sock, wired) + finally: + sock.close() + teardown_step(f"stop {stream}", lambda: api.streams.stop(stream)) + teardown_step(f"restore {item}", lambda: api.configs.set("Data Streams", item, original)) + + sock, port = receiver(None) + try: + with check(f"{stream}: broadcast destination"): + # Broadcast floods the AP too; fence this bounded burst over Ethernet. + wired_api = UltimateApi(wired, api.rest.password, api.rest.timeout) + control(wired_api, "DMA", stream, "start", f"255.255.255.255:{port}", ticks=40) + detail(expect_stream(collect(sock, LISTEN_SECONDS), stream, wired, wireless, 0.1)) + expect_silence(sock, wired) + with check(f"{stream}: DNS receiver name"): + if receiver_name is None: + check_skip("provide --receiver-name for a name the device's DNS resolves to this host") + else: + api.streams.start(stream, ip=f"{receiver_name}:{port}") + detail(expect_stream(collect(sock, LISTEN_SECONDS), stream, wired, wireless)) + api.streams.stop(stream) + expect_silence(sock, wired) + finally: + sock.close() + teardown_step(f"stop {stream}", lambda: api.streams.stop(stream)) + + +def interactions(api: UltimateApi, wired: str, wireless: str | None, local: str) -> None: + sockets = {name: receiver(None) for name in STREAM_SOURCE} + + def start(stream: str, protocol: str = "REST") -> None: + control(api, protocol, stream, "start", f"{local}:{sockets[stream][1]}") + + def arrives(stream: str) -> None: + detail(expect_stream(collect(sockets[stream][0], LISTEN_SECONDS), stream, wired, wireless)) + + try: + with check("audio and video coexist; stopping either leaves the other running"): + start("audio") + start("video") + arrives("audio") + arrives("video") + api.streams.stop("video") + expect_silence(sockets["video"][0], wired) + arrives("audio") + start("video") + api.streams.stop("audio") + expect_silence(sockets["audio"][0], wired) + arrives("video") + api.streams.stop("video") + with check("REST video start stops debug and leaves audio running"): + start("audio") + start("debug") + arrives("debug") + start("video") + expect_silence(sockets["debug"][0], wired) + arrives("video") + arrives("audio") + with check("DMA debug/video starts replace each other and leave audio running"): + start("debug", "DMA") + expect_silence(sockets["video"][0], wired) + arrives("debug") + arrives("audio") + start("video", "DMA") + expect_silence(sockets["debug"][0], wired) + arrives("video") + arrives("audio") + finally: + for name, (sock, _) in sockets.items(): + sock.close() + teardown_step(f"stop {name}", lambda name=name: api.streams.stop(name)) + + +def refusals(api: UltimateApi) -> None: + for action in ("start", "stop"): + with check(f"REST refuses unknown stream on {action}"): + code, _, body = api.rest.request("PUT", f"/v1/streams/not-a-stream:{action}", + params={"ip": "127.0.0.1"} if action == "start" else None) + if code != 404 or b"Unrecognized stream name" not in body: + raise Failure(f"HTTP {code}: {body!r}") + for stream in STREAM_SOURCE: + for params, expected in ((None, 400), ({"ip": "127.0.0.1:0"}, 400), + ({"ip": "no-stream-receiver.invalid"}, 404)): + with check(f"REST {stream}: refuses {params or 'missing ip'}"): + code, _, body = api.rest.request("PUT", f"/v1/streams/{stream}:start", + params=params, timeout=20) + if code != expected: + raise Failure(f"HTTP {code}, expected {expected}: {body!r}") + + +def debug_modes(api: UltimateApi, wired: str, wireless: str | None, local: str) -> None: + item = api.configs.item("Data Streams", "Debug Stream Mode") + original = str(item["current"]) + sock, port = receiver(None) + try: + for mode in item["values"]: + with check(f"debug packets and stop in {mode} mode"): + api.configs.set("Data Streams", "Debug Stream Mode", mode) + api.streams.start("debug", ip=f"{local}:{port}") + detail(expect_debug_data(sock, wired, wireless)) + api.streams.stop("debug") + expect_silence(sock, wired) + finally: + sock.close() + teardown_step("stop debug", lambda: api.streams.stop("debug")) + teardown_step("restore debug mode", + lambda: api.configs.set("Data Streams", "Debug Stream Mode", original)) + + +def menu_controls(api: UltimateApi, wired: str, wireless: str | None, local: str) -> None: + # Accept the configured address unchanged: the string box persists it. + for stream, label, item in (("video", "VIC Stream", "Stream VIC to"), + ("audio", "Audio Stream", "Stream Audio to"), + ("debug", "Debug Stream", "Stream Debug to")): + destination = api.configs.current("Data Streams", item) + host, colon, port_text = destination.partition(":") + address = socket.gethostbyname(host) + joined = address if ipaddress.ip_address(address).is_multicast else None + if joined is None and address not in (local, "255.255.255.255"): + check_start(f"{stream}: menu controls") + check_skip("the configured receiver is another host; leave the saved destination intact") + continue + port = int(port_text) if colon else 11000 + STREAM_IDS[stream] + sock, _ = receiver(joined, port) + + def action(start: bool, cancel: bool = False) -> None: + browser = make_browser(MODE_OVERLAY, api.host, api.rest.password, api.rest.timeout) + + try: + browser.backend.ensure_ready() + categories = browser.open_task_menu() + before = browser.rows() + browser.choose_overlay_item(categories, "Developer" if stream == "debug" else "Streams") + choices = browser.wait_for_overlay(before) + matches = [choice for choice in choices if choice.endswith(label)] + if len(matches) != 1: + raise Failure(f"expected one {label!r} entry, got {choices}") + # These actions sit at the menu edges; paging skips disabled rows. + edge = 0 if stream == "video" else -1 + if choices[edge] != matches[0]: + raise Failure(f"{label!r} is no longer at the expected menu edge: {choices}") + browser.press(browser.backend.machine.page_up_key if edge == 0 + else browser.backend.machine.page_down_key) + browser.press("ENTER") + if start: + if "Send to" not in browser.screen(): + raise Failure(f"no destination dialog: {browser.screen()}") + browser.press("ESC" if cancel else "ENTER") + finally: + browser.close() + + try: + api.streams.stop(stream) + with check(f"{stream}: cancelling the menu destination starts nothing"): + action(True, cancel=True) + expect_silence(sock, wired) + with check(f"{stream}: menu start and stop deliver packets, then silence"): + action(True) + detail(expect_stream(collect(sock, LISTEN_SECONDS), stream, wired, wireless)) + action(False) + expect_silence(sock, wired) + finally: + sock.close() + teardown_step(f"stop {stream}", lambda: api.streams.stop(stream)) + + def main() -> int: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) cli.add_device_arguments(parser) + parser.add_argument("--receiver-name", help="DNS name that resolves to this test host on the device") args = parser.parse_args() password = args.password or None @@ -137,6 +408,7 @@ def main() -> int: failure = "" running: set[str] = set() + cleanup_api = api try: before = senders_on_groups(target) code, body, seen = start_video(api, target.video_group) @@ -155,19 +427,27 @@ def main() -> int: wireless = wireless_address(api, info, wired, local) detail(f"wired {wired}, wireless {wireless or 'none'}, this host {local}") apis = {"Ethernet": UltimateApi(wired, password, args.timeout)} + cleanup_api = apis["Ethernet"] if wireless: apis["WiFi"] = UltimateApi(wireless, password, args.timeout) routing(apis, wired, wireless, local, target.video_group) + lifecycle(api, wired, wireless, local, target.video_group, args.receiver_name) + interactions(api, wired, wireless, local) + refusals(api) + debug_modes(api, wired, wireless, local) + menu_controls(api, wired, wireless, local) except Failure as exc: failure = str(exc) except Exception as exc: # noqa: BLE001 failure = format_exception(exc) finally: + for name in STREAM_SOURCE: + teardown_step(f"stop {name}", lambda name=name: cleanup_api.streams.stop(name)) # Leave the standard streams as they were found, for a recorder. for name in sorted(running): group_port = standard_groups(target)[name] teardown_step(f"restart {name}", lambda name=name, group_port=group_port: - api.streams.start(name, ip=f"{group_port[0]}:{group_port[1]}")) + cleanup_api.streams.start(name, ip=f"{group_port[0]}:{group_port[1]}")) if failure: suite_fail(SUITE, failure) From 5d42e1db8c8e608dcf267a2f329fba18bab84708 Mon Sep 17 00:00:00 2001 From: Christian Gleissner Date: Sat, 17 Oct 2026 23:39:06 +0100 Subject: [PATCH 8/8] Bind stream primer sockets to the wired interface Keep the existing UDP primer and lwIP cache and retry behavior. Bind its socket with SO_BINDTODEVICE so address resolution uses the same interface as FPGA stream output. --- software/io/network/data_streamer.cc | 37 +++++++++++++++++++++-- software/io/network/data_streamer.h | 1 + software/io/network/debug_streamer_u2p.cc | 37 +++++++++++++++++++++-- software/io/network/debug_streamer_u2p.h | 1 + software/io/network/network_interface.cc | 12 +++++--- software/io/network/network_interface.h | 2 +- 6 files changed, 79 insertions(+), 11 deletions(-) diff --git a/software/io/network/data_streamer.cc b/software/io/network/data_streamer.cc index 2c7d5968a..3ce8a6cfa 100644 --- a/software/io/network/data_streamer.cc +++ b/software/io/network/data_streamer.cc @@ -202,9 +202,7 @@ SubsysResultCode_e DataStreamer :: startStream(SubsysCommand *cmd) } else { bool ok = false; for(int i=0;i<10;i++) { - // Ask on the wired port itself. lwIP sends by the first netif on the destination's - // subnet, which is WiFi when both share one, and the answer would land in its table. - intf->sendArpRequest(query_ip); + send_udp_packet(query_ip, stream->dest_port); vTaskDelay(20); if (intf->peekArpTable(query_ip, stream->dest_mac)) { ok = true; @@ -282,6 +280,39 @@ void DataStreamer :: update_task_items(bool writablePath) myActions.stopDbg->setHidden(streams[2].enable == 0); } +void DataStreamer :: send_udp_packet(uint32_t ip, uint16_t port) +{ + int sockfd; + static struct sockaddr_in server; + + sockfd = socket(AF_INET, SOCK_DGRAM, 0); + if (sockfd < 0) + { + printf("Error opening socket to send UDP packet\n"); + return; + } + + // The FPGA uses the wired port, regardless of lwIP's default route. + if (!NetworkInterface::getInterface(0)->bindSocket(sockfd)) { + printf("Error binding stream socket to wired interface\n"); + lwip_close(sockfd); + return; + } + + memset((char*)&server, 0, sizeof(server)); + server.sin_family = AF_INET; + server.sin_addr.s_addr = ip; + server.sin_port = htons(port); + + uint8_t buffer[2] = { 0, 0 }; + printf("Send UDP data...\n"); + if (sendto(sockfd, buffer, 2, 0, (const struct sockaddr*)&server, sizeof(server)) < 0) { + printf("Error in sendto()\n"); + } + // close the socket again + lwip_close(sockfd); +} + void DataStreamer :: calculate_udp_headers(int id) { diff --git a/software/io/network/data_streamer.h b/software/io/network/data_streamer.h index 052ff04f9..a09093c34 100644 --- a/software/io/network/data_streamer.h +++ b/software/io/network/data_streamer.h @@ -52,6 +52,7 @@ class DataStreamer : public ObjectWithMenu SubsysResultCode_e stopStream(SubsysCommand *cmd); void calculate_udp_headers(int id); + void send_udp_packet(uint32_t ip, uint16_t port); public: DataStreamer(); virtual ~DataStreamer(); diff --git a/software/io/network/debug_streamer_u2p.cc b/software/io/network/debug_streamer_u2p.cc index 301188c04..a7449537f 100644 --- a/software/io/network/debug_streamer_u2p.cc +++ b/software/io/network/debug_streamer_u2p.cc @@ -194,9 +194,7 @@ SubsysResultCode_e DataStreamer :: startStream(SubsysCommand *cmd) } else { bool ok = false; for(int i=0;i<10;i++) { - // Ask on the wired port itself. lwIP sends by the first netif on the destination's - // subnet, which is WiFi when both share one, and the answer would land in its table. - intf->sendArpRequest(query_ip); + send_udp_packet(query_ip, stream->dest_port); vTaskDelay(20); if (intf->peekArpTable(query_ip, stream->dest_mac)) { ok = true; @@ -267,6 +265,39 @@ void DataStreamer :: update_task_items(bool writablePath) } } +void DataStreamer :: send_udp_packet(uint32_t ip, uint16_t port) +{ + int sockfd; + static struct sockaddr_in server; + + sockfd = socket(AF_INET, SOCK_DGRAM, 0); + if (sockfd < 0) + { + printf("Error opening socket to send UDP packet\n"); + return; + } + + // The FPGA uses the wired port, regardless of lwIP's default route. + if (!NetworkInterface::getInterface(0)->bindSocket(sockfd)) { + printf("Error binding stream socket to wired interface\n"); + lwip_close(sockfd); + return; + } + + bzero((char*)&server, sizeof(server)); + server.sin_family = AF_INET; + server.sin_addr.s_addr = ip; + server.sin_port = htons(port); + + uint8_t buffer[2] = { 0, 0 }; + printf("Send UDP data...\n"); + if (sendto(sockfd, buffer, 2, 0, (const struct sockaddr*)&server, sizeof(server)) < 0) { + printf("Error in sendto()\n"); + } + // close the socket again + lwip_close(sockfd); +} + void DataStreamer :: calculate_udp_headers(int id) { diff --git a/software/io/network/debug_streamer_u2p.h b/software/io/network/debug_streamer_u2p.h index 3e9323988..cef69013c 100644 --- a/software/io/network/debug_streamer_u2p.h +++ b/software/io/network/debug_streamer_u2p.h @@ -49,6 +49,7 @@ class DataStreamer : public ObjectWithMenu SubsysResultCode_e stopStream(SubsysCommand *cmd); void calculate_udp_headers(int id); + void send_udp_packet(uint32_t ip, uint16_t port); public: DataStreamer(); virtual ~DataStreamer(); diff --git a/software/io/network/network_interface.cc b/software/io/network/network_interface.cc index 506e4f076..56c9cafcb 100644 --- a/software/io/network/network_interface.cc +++ b/software/io/network/network_interface.cc @@ -6,6 +6,7 @@ #include #include "lwip/dhcp.h" #include "lwip/dns.h" +#include "lwip/sockets.h" #include "lwip/apps/mdns.h" #include "filemanager.h" @@ -492,14 +493,17 @@ bool NetworkInterface :: peekArpTable(uint32_t ipToQuery, uint8_t *mac) return ret; } -void NetworkInterface :: sendArpRequest(uint32_t ipToQuery) +bool NetworkInterface :: bindSocket(int socket) { - ip4_addr_t query_ip; - query_ip.addr = ipToQuery; + struct ifreq request; + memset(&request, 0, sizeof(request)); LOCK_TCPIP_CORE(); - etharp_request(&my_net_if, &query_ip); + char *name = netif_index_to_name(netif_get_index(&my_net_if), request.ifr_name); UNLOCK_TCPIP_CORE(); + + return name && lwip_setsockopt(socket, SOL_SOCKET, SO_BINDTODEVICE, + &request, sizeof(request)) == 0; } void NetworkInterface :: on_edit() diff --git a/software/io/network/network_interface.h b/software/io/network/network_interface.h index 25367f11f..581cc6e02 100644 --- a/software/io/network/network_interface.h +++ b/software/io/network/network_interface.h @@ -139,7 +139,7 @@ class NetworkInterface : protected ConfigurableObject void setIpAddr(uint8_t *a); char *getIpAddrString(char *buf, int buflen); bool peekArpTable(uint32_t ipToQuery, uint8_t *mac); - void sendArpRequest(uint32_t ipToQuery); + bool bindSocket(int socket); // callbacks static void statusCallback(struct netif *);