Coverage for src/signalk_cli/net.py: 94%

53 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-22 09:25 +0000

1"""SignalK server discovery (mDNS) and the on-disk host cache.""" 

2 

3from __future__ import annotations 

4 

5import time 

6from pathlib import Path 

7from typing import TYPE_CHECKING 

8 

9try: 

10 from zeroconf import ServiceBrowser, ServiceStateChange, Zeroconf 

11except ImportError: # slim/Pyodide installs ship without zeroconf 

12 Zeroconf = None # type: ignore[assignment,misc] 

13 

14if TYPE_CHECKING: 

15 from zeroconf import Zeroconf as ZeroconfInstance 

16 

17 

18def mdns_available() -> bool: 

19 """True if zeroconf is installed, so mDNS discovery can run.""" 

20 return Zeroconf is not None 

21 

22 

23CACHE_DIR = Path.home() / ".cache" / "signalk-cli" 

24_SIGNALK_TYPE = "_signalk-ws._tcp.local." 

25_HOST_CACHE_FILE = CACHE_DIR / "host.cache" 

26 

27 

28def get_cached_host() -> str | None: 

29 try: 

30 if _HOST_CACHE_FILE.exists(): 

31 return _HOST_CACHE_FILE.read_text().strip() or None 

32 except OSError: 

33 pass 

34 return None 

35 

36 

37def save_cached_host(host: str) -> None: 

38 try: 

39 CACHE_DIR.mkdir(parents=True, exist_ok=True) 

40 _HOST_CACHE_FILE.write_text(host) 

41 except OSError: 

42 pass 

43 

44 

45def discover_host(timeout: float = 5.0) -> str | None: 

46 """Browse mDNS for a SignalK server and return its base URL, or None.""" 

47 if Zeroconf is None: 

48 return None 

49 found: list[str] = [] 

50 

51 def _on_change( 

52 zeroconf: ZeroconfInstance, 

53 service_type: str, 

54 name: str, 

55 state_change: ServiceStateChange, 

56 ) -> None: 

57 if state_change is not ServiceStateChange.Added: 

58 return 

59 info = zeroconf.get_service_info(service_type, name) 

60 if info is None: 

61 return 

62 addrs = info.parsed_addresses() 

63 if not addrs: 

64 return 

65 host = f"http://{addrs[0]}:{info.port}" 

66 found.append(host) 

67 

68 zc = Zeroconf() 

69 try: 

70 ServiceBrowser(zc, _SIGNALK_TYPE, handlers=[_on_change]) 

71 deadline = time.monotonic() + timeout 

72 while not found and time.monotonic() < deadline: 

73 time.sleep(0.1) 

74 finally: 

75 zc.close() 

76 

77 return found[0] if found else None 

78 

79 

80def normalise_host(host: str) -> str: 

81 """Prepend http:// if the host has no scheme.""" 

82 if "://" not in host: 

83 return f"http://{host}" 

84 return host