Thread network diagnostics tool, anyone using it yet?

I think it is worth investing the time to go through adding friendly device names in the Thread Tools app, though the app needs to make more use of them. It’s all very well having a map and listing with nice names, but if you then look at the Topology section for a particular device you are flying blind again.

Early days yet, but hope the map has more to come. It would be nice to be able to highlight a node’s links as they aren’t always clear when the node has sixteen links and another dozen are passing under the icon.

It would also be good to be able to visualise usage. Yes, I am sure the link between one of my TBRs and a smart plug at the other end of my home through a few brick walls is relatively weak, but should I really care?

The winner of the SmartThings Innovation Challenge came up with the idea of a standardized smart home mapping format:

Sounds good on paper.

You can get a JSON of the map easily enough. I haven’t looked to see if that includes the devices or if you have to get the info for those from the devices endpoint.

@orangebucket Hm are you sure we can get JSON of the map?

I am not able to find anything in the API mapping out how rooms are arranged in a location. I see lots of information from the API using the SmartThings CLI, but crucial information is missing to recreate a map, including

  • Basic room coordinates like x,y,width,height
  • Room floor (could be stored as ‘z’ coordinate, or 1st/2nd/etc floor)
  • Room intersection or shape details – SmartThings Map View permits more room shapes than just rectangular. E.g. the hallways between rooms, and the yard outside.

I was able to get a list of rooms per location and device coordinates, but that’s not quite enough info. (Note format below is YAML for conciseness in this forum post, but I see no additional info presented in JSON format.

> smartthings locations:rooms --yaml
...
  roomId: 12b7c814-09d0-4ace-b5bf-63e13fead3ad
  locationId: e588a9ef-05e5-40ac-b1c3-43275b1de137
  name: Parlor
  indoorMap:
    mapRoomId: b813e188-20dd-48aa-8ba6-8935fed6c55e
    color: null
  location: My home
...


> smartthings devices 4d98e875-4ba0-4c47-a85a-f722288b78b8 --yaml
...
deviceId: 4d98e875-4ba0-4c47-a85a-f722288b78b8
label: Bilresa buttons WH 8974
locationId: e588a9ef-05e5-40ac-b1c3-43275b1de137
roomId: c005ddce-8ceb-4143-88e9-3009a02b3f77
indoorMap:
  coordinates:
    - 37
    - 0
    - 110
  rotation:
    - 0
    - 0
    - 0
  visible: true
...

I found I can view my home on a computer with the Windows Store SmartThings app, and can see a generic home in the browser at https://virtual.smartthings.com and also https://mapview.smartthings.com. But I see no obvious way to extract additional mapping data from the app, and the websites don’t seem to be using the API. They just seem to be loading a big binary blob from http://mapview.smartthings.com/Build/renderer.data.unityweb

Well something appears on https://client.smartthings.com/blueprint/indoormaps/locations/{locationId} when a map is created and disappears when it is deleted. However I can’t bear to have a map view existing for more than about a minute, such is my low regard for them, so I have only skimmed it.

As ever, it’s the Client API so not intended for the oiks, unsupported, could be blocked tomorrow etc.

Sure enough, AI was able to gather the information from smartthings locations:rooms, smartthings devices, and https://client.smartthings.com/blueprint/indoormaps/locations/{locationId}, and then export SVG and Blender results for each floor including devices, walls, windows, and doors.

It is clear to me that this is possible. I am happy to DM my results to anyone if they’re interested in taking it farther, but I guess I’m content for now at replicating what’s already within SmartThings.

Wanting a clearer view of the Thread network inside SmartThings makes sense. “Connected” is not the same as “healthy mesh.”

What I’d look for in any Thread diagnostics view:

  • which border router is active
  • whether devices are routing through expected parents
  • whether drops correlate with a specific node or area

Until that visibility is good, keep changes small: one device at a time, and note what breaks after each change.

I wanted to lose the Wi-Fi on one of my V3 hubs, largely because it annoys me that it seems to end up using the Wi-Fi IP even though it is on ethernet. So I did a soft reset to clear the network settings.

Coincidence or not, since then Thread Tools has been determinedly refusing to connect to my secondary Thread network. Not complaining about a lack of credentials but displaying the info about the TBRs and then failing to connect to the mesh.

There are two V3 hubs on this mesh which are now in a hub group. I noticed that when either was rebooted they dropped the custom Thread network name and reverted to the hub default name. Which is odd. However I thought I’d change the name anyway.

The odd thing is that despite the name changes, both wanted and unwanted, Thread Tools keeps discovering the mesh with the old custom name. The ST app, the AWA, the Nanoleaf app, and the Thread Networks settings in Google Home and Android all show the new custom name, and before that showed the unwanted changes. The only thing that sees the old custom name is Thread Tools, and it makes no claim to not have the credentials and allows a connection attempt.

Beats me.

I think that’s because they think that the network name is significant. It’s just a label. I reported about this issue back in April of this year and submitted feedback to their support email address. Crickets…

I have had the issue where the network name has changed and it can’t find the credentials, as if they are stored with the extended PAN ID and the last known label and they try to look them up with an out of date label rather than the ID. However in that case it has always known the current network name and reported that it can’t find the credentials, just as it would if they genuinely aren’t there and it disabled any attempt to connect to the mesh. It could be worked around by pairing another device which seemed to update the credentials.

For me it is displaying an old network name with the extended PAN ID but it is happy that it has the credentials and to allow me to connect to the mesh. It is at that point it says connection failed. That is new behaviour for me.

What I don’t understand is where it is getting an old network name from. Everything else is displaying the current name and working.

Just to add to the fun, the app can go for hours and days finding the meshes as:

Current Name A which works fine.
Old Name B which allows a ‘connect mesh’ then fails.

Then it will suddenly throw in a one off:

Current Name A and
Current Name B which both have missing credentials.

I didn’t have any Thread devices yet and stuff like this is one of the reasons for that…

Edited 2026-11-02 per @h0ckeysk8er’s comments below

Grok got it working cross-platform (tested on Windows and Linux) without Bonjour, DNS-SD, etc., by using python-zeroconf, installed using pip install zeroconf.

matter-map-cross-platform-pip-zeroconf.py
#!/usr/bin/env python3
"""
matter-map for cross-platform, tested on Windows and Linux.

Requires:
  pip install zeroconf
  smartthings CLI in PATH
"""

import ipaddress
import json
import sys
import time
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor, as_completed

from zeroconf import IPVersion, ServiceBrowser, Zeroconf

# ---------------- configuration ----------------
CACHE_TTL = 300          # seconds for hostname cache
MAX_THREADS = 10         # max parallel DNS resolution threads
BROWSE_TIMEOUT = 15      # max seconds to browse for _matter._tcp
BROWSE_QUIET = 2.5       # stop early once this long passes with no new service
# Matter operational ads (especially Thread) arrive on IPv6. Zeroconf's
# default is IPv4-only, which sees none of them on this network.

# ---------------- helpers ----------------

def run(cmd):
    import subprocess
    return subprocess.check_output(cmd, text=True, stderr=subprocess.DEVNULL)

def get_locations():
    locations = json.loads(run(["smartthings", "locations", "-j"]))
    id_to_name = {}
    name_to_id = {}
    for loc in locations:
        id_to_name[loc["locationId"]] = loc["name"]
        name_to_id[loc["name"]] = loc["locationId"]
    return id_to_name, name_to_id

def get_matter_devices(location_id=None):
    cmd = ["smartthings", "devices", "--type", "MATTER", "-j"]
    if location_id:
        cmd += ["--location", location_id]
    devices = json.loads(run(cmd))
    results = []
    for d in devices:
        network_id = d.get("matter", {}).get("networkId")
        if not network_id:
            continue
        results.append({
            "label": d.get("label", "UNKNOWN"),
            "instance": network_id,
            "locationId": d.get("locationId"),
            "hostname": "",  # will be filled by DNS
            "ipv4": "",
            "ipv6": "",
        })
    return results

# ---------------- mDNS via zeroconf (no Bonjour) ----------------

def _instance_from_service_name(name):
    """CC55...-DB25...._matter._tcp.local. -> CC55...-DB25..."""
    suffix = "._matter._tcp.local."
    if name.endswith(suffix):
        return name[: -len(suffix)]
    return name.split("._matter._tcp.")[0]


def _pick_addresses(addr_strings):
    """Choose one IPv4 and one IPv6, matching what dns-sd tends to surface.

    Prefer a global IPv6 address, then a unique-local (Thread) address, then
    link-local. info.addresses is often IPv4-only even when AAAA records were
    received; callers should pass ServiceInfo.parsed_addresses().
    """
    ipv4 = ""
    v6_global = []
    v6_ula = []
    v6_link = []
    for raw in addr_strings:
        try:
            ip = ipaddress.ip_address(raw.split("%", 1)[0])
        except ValueError:
            continue
        if ip.version == 4:
            if not ipv4:
                ipv4 = str(ip)
        elif ip.is_link_local:
            v6_link.append(ip)
        elif ip.is_private:
            v6_ula.append(ip)
        else:
            v6_global.append(ip)
    chosen = (v6_global or v6_ula or v6_link or [None])[0]
    ipv6 = chosen.compressed if chosen is not None else ""
    return ipv4, ipv6


def get_dns_sd_data(debug_dns=False):
    """Discover _matter._tcp services using pure-Python zeroconf."""
    data = defaultdict(dict)
    names = []
    last_add = time.time()

    class Listener:
        def add_service(self, zc, type_, name):
            nonlocal last_add
            if debug_dns:
                print(f"[DEBUG] Found: {name}")
            if name not in names:
                names.append(name)
                last_add = time.time()

        def remove_service(self, zc, type_, name):
            pass

        def update_service(self, zc, type_, name):
            pass

    # Do not resolve inside the listener: get_service_info takes the zeroconf
    # lock and deadlocks if called from a ServiceBrowser callback.
    # A fixed short sleep drops Thread devices when the first query is late.
    zc = Zeroconf(ip_version=IPVersion.All)
    browser = ServiceBrowser(zc, "_matter._tcp.local.", Listener())

    if debug_dns:
        print(f"[DEBUG] Browsing _matter._tcp for up to {BROWSE_TIMEOUT}s...")
    started = time.time()
    while time.time() - started < BROWSE_TIMEOUT:
        time.sleep(0.25)
        if names and time.time() - last_add >= BROWSE_QUIET:
            break
    if debug_dns:
        print(f"[DEBUG] Browse saw {len(names)} services")

    for name in names:
        info = zc.get_service_info("_matter._tcp.local.", name, timeout=3000)
        if not info:
            if debug_dns:
                print(f"[DEBUG] No service info for {name}")
            continue
        instance = _instance_from_service_name(name)
        hostname = info.server.rstrip(".") if info.server else ""
        data[instance]["hostname"] = hostname
        ipv4, ipv6 = _pick_addresses(info.parsed_addresses())
        if ipv4:
            data[instance]["ipv4"] = ipv4
        if ipv6:
            data[instance]["ipv6"] = ipv6
        if debug_dns:
            print(f"[DEBUG] {instance} {hostname} {ipv6} {ipv4}")

    browser.cancel()
    zc.close()
    return data

# ---------------- hostname cache (kept for compatibility) ----------------
hostname_cache = {}  # hostname -> (ipv4, ipv6, timestamp)

def resolve_hostname_cached(hostname, debug_dns=False):
    """Fallback resolution if zeroconf didn't already give addresses.
    On modern Windows the native resolver often works for .local names
    without Bonjour, so we try it first.
    """
    now = time.time()
    if hostname in hostname_cache:
        ipv4, ipv6, ts = hostname_cache[hostname]
        if now - ts < CACHE_TTL:
            return ipv4, ipv6  # use cached

    ipv4, ipv6 = "", ""
    try:
        import socket
        # getaddrinfo works for .local on Windows 10 1703+ without Bonjour
        results = socket.getaddrinfo(hostname, None, socket.AF_UNSPEC, socket.SOCK_STREAM)
        for res in results:
            family, _, _, _, sockaddr = res
            ip = sockaddr[0]
            if family == socket.AF_INET and not ipv4:
                ipv4 = ip
            elif family == socket.AF_INET6 and not ipv6:
                # skip link-local scope id if present
                ipv6 = ip.split("%")[0]
    except Exception as e:
        if debug_dns:
            print(f"[DEBUG] getaddrinfo failed for {hostname}: {e}")

    hostname_cache[hostname] = (ipv4, ipv6, now)
    return ipv4, ipv6

# ---------------- help ----------------
def print_help():
    print("""Usage: matter-map [LOCATION] [OPTIONS]

Positional arguments:
  LOCATION          Filter devices by location name

Options:
  --help            Show this help message and exit
  --sort=FIELD      Sort by field: label, location, instance, hostname, ipv4, ipv6
  --reverse         Reverse sort order
  --debug-dns       Print debug info for mDNS queries""")

# ---------------- main ----------------
def main():
    sort_key = "label"
    reverse = False
    location_arg = None
    debug_dns = False

    args = sys.argv[1:]
    positional_args = []

    for arg in args:
        if arg == "--help":
            print_help()
            sys.exit(0)
        elif arg == "--reverse":
            reverse = True
        elif arg == "--debug-dns":
            debug_dns = True
        elif arg.startswith("--sort="):
            sort_key = arg.split("=", 1)[1]
        elif arg.startswith("-"):
            print(f"Unknown option: {arg}", file=sys.stderr)
            sys.exit(1)
        else:
            positional_args.append(arg)

    if len(positional_args) > 1:
        print("Error: only one location name may be specified", file=sys.stderr)
        sys.exit(1)
    if positional_args:
        location_arg = positional_args[0]

    valid_sorts = {"label", "location", "instance", "hostname", "ipv4", "ipv6"}
    if sort_key not in valid_sorts:
        print(f"Invalid sort key: {sort_key}", file=sys.stderr)
        print(f"Valid options: {', '.join(sorted(valid_sorts))}", file=sys.stderr)
        sys.exit(1)

    id_to_name, name_to_id = get_locations()
    location_id = None
    if location_arg:
        location_id = name_to_id.get(location_arg)
        if not location_id:
            print("Unknown location", file=sys.stderr)
            sys.exit(1)

    devices = get_matter_devices(location_id)
    dns_data = get_dns_sd_data(debug_dns)

    # Merge DNS-SD data into devices
    for d in devices:
        dns = dns_data.get(d["instance"], {})
        d["hostname"] = dns.get("hostname", "UNKNOWN")
        d["ipv4"] = dns.get("ipv4", "")
        d["ipv6"] = dns.get("ipv6", "")
        d["location"] = id_to_name.get(d.get("locationId"), "UNKNOWN")

    # Resolve hostnames that mDNS did not already give an address for.
    # Windows getaddrinfo can answer .local without Bonjour, but it is slower
    # and often returns a different address than the Matter SRV record.
    to_resolve = [
        d for d in devices
        if d["hostname"] not in ("", "UNKNOWN") and not (d["ipv4"] or d["ipv6"])
    ]
    with ThreadPoolExecutor(max_workers=MAX_THREADS) as executor:
        future_to_device = {
            executor.submit(resolve_hostname_cached, d["hostname"], debug_dns): d
            for d in to_resolve
        }
        for future in as_completed(future_to_device):
            d = future_to_device[future]
            try:
                ipv4, ipv6 = future.result()
                d["ipv4"] = ipv4 or d["ipv4"]
                d["ipv6"] = ipv6 or d["ipv6"]
            except Exception:
                pass

    # Sort and group
    devices.sort(key=lambda r: r.get(sort_key, ""), reverse=reverse)
    grouped = defaultdict(list)
    for r in devices:
        grouped[r.get("location", "UNKNOWN")].append(r)

    # Print output (same format as original)
    print(
        f"{'DEVICE LABEL':<25} {'LOCATION':<15} {'INSTANCE NAME/NETWORK ID':<40} "
        f"{'HOSTNAME':<30} {'IPv6 ADDRESS':<40} {'IPv4 ADDRESS':<20}"
    )
    print("-" * 180)

    for location in sorted(grouped):
        for r in grouped[location]:
            print(
                f"{r['label']:<25} "
                f"{location:<15} "
                f"{r['instance']:<40} "
                f"{r['hostname']:<30} "
                f"{r['ipv6']:<40} "
                f"{r['ipv4']:<20}"
            )

if __name__ == "__main__":
    main()

Grok also got it working using zero dependencies, using built-in Windows dnsapi.dll, but apparently it’s brittle because it’s “laying Python ctypes structures on top of memory that dnsapi.dll allocated… Windows does not return one tidy service object… The built-in discovery path is a hand-written binding to an undocumented callback layout.” So you’re welcome to try it, but if it breaks you’ll probably need zeroconf or Bonjour or something else to re-make the undocumented hand-written bindings.

matter-map-windows-built-in.py
#!/usr/bin/env python3
"""
matter-map for Windows — native DNS-SD via ctypes (no Bonjour, no extra packages).

Uses DnsServiceBrowse / DnsServiceResolve from dnsapi.dll.
Browse answers often include SRV, A, and AAAA records for Wi-Fi devices.
Thread devices frequently arrive as PTR only, so those are resolved separately.

Requires Windows 10 1703+ / Windows 11 and the smartthings CLI in PATH.
"""

import ctypes
import ipaddress
import json
import socket
import sys
import threading
import time
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor, as_completed
from ctypes import wintypes

# ---------------- Windows DNS-SD bindings ----------------

dnsapi = ctypes.WinDLL("dnsapi")

DNS_QUERY_REQUEST_VERSION1 = 1
DNS_REQUEST_PENDING = 9506
ERROR_CANCELLED = 1223
DNS_TYPE_A = 1
DNS_TYPE_PTR = 12
DNS_TYPE_AAAA = 28
DNS_TYPE_SRV = 33

class DNS_SERVICE_CANCEL(ctypes.Structure):
    _fields_ = [("reserved", ctypes.c_void_p)]

class DNS_SERVICE_BROWSE_REQUEST(ctypes.Structure):
    _fields_ = [
        ("Version", wintypes.ULONG),
        ("InterfaceIndex", wintypes.ULONG),
        ("QueryName", wintypes.LPCWSTR),
        ("pBrowseCallback", ctypes.c_void_p),
        ("pQueryContext", ctypes.c_void_p),
    ]

class DNS_SERVICE_RESOLVE_REQUEST(ctypes.Structure):
    _fields_ = [
        ("Version", wintypes.ULONG),
        ("InterfaceIndex", wintypes.ULONG),
        ("QueryName", wintypes.LPWSTR),
        ("pResolveCompletionCallback", ctypes.c_void_p),
        ("pQueryContext", ctypes.c_void_p),
    ]

class DNS_SERVICE_INSTANCE(ctypes.Structure):
    _fields_ = [
        ("pszInstanceName", wintypes.LPWSTR),
        ("pszHostName", wintypes.LPWSTR),
        ("ip4Address", ctypes.POINTER(wintypes.DWORD)),
        ("ip6Address", ctypes.POINTER(ctypes.c_ubyte * 16)),
        ("wPort", wintypes.WORD),
        ("wPriority", wintypes.WORD),
        ("wWeight", wintypes.WORD),
        ("dwPropertyCount", wintypes.DWORD),
        ("keys", ctypes.POINTER(wintypes.LPWSTR)),
        ("values", ctypes.POINTER(wintypes.LPWSTR)),
        ("dwInterfaceIndex", wintypes.DWORD),
    ]

class DNS_RECORD(ctypes.Structure):
    pass

# Fixed header is 32 bytes on 64-bit Windows. The Data union starts there.
# pData aliases the first pointer of PTR (pNameHost) and SRV (pNameTarget).
DNS_RECORD._fields_ = [
    ("pNext", ctypes.POINTER(DNS_RECORD)),
    ("pName", wintypes.LPWSTR),
    ("wType", wintypes.WORD),
    ("wDataLength", wintypes.WORD),
    ("Flags", wintypes.DWORD),
    ("dwTtl", wintypes.DWORD),
    ("dwReserved", wintypes.DWORD),
    ("pData", wintypes.LPWSTR),
]

BROWSE_CALLBACK = ctypes.WINFUNCTYPE(
    None, wintypes.DWORD, ctypes.c_void_p, ctypes.POINTER(DNS_RECORD)
)
RESOLVE_CALLBACK = ctypes.WINFUNCTYPE(
    None, wintypes.DWORD, ctypes.c_void_p, ctypes.POINTER(DNS_SERVICE_INSTANCE)
)

dnsapi.DnsServiceBrowse.argtypes = [
    ctypes.POINTER(DNS_SERVICE_BROWSE_REQUEST),
    ctypes.POINTER(DNS_SERVICE_CANCEL),
]
dnsapi.DnsServiceBrowse.restype = wintypes.DWORD
dnsapi.DnsServiceBrowseCancel.argtypes = [ctypes.POINTER(DNS_SERVICE_CANCEL)]
dnsapi.DnsServiceBrowseCancel.restype = wintypes.DWORD

dnsapi.DnsServiceResolve.argtypes = [
    ctypes.POINTER(DNS_SERVICE_RESOLVE_REQUEST),
    ctypes.POINTER(DNS_SERVICE_CANCEL),
]
dnsapi.DnsServiceResolve.restype = wintypes.DWORD
dnsapi.DnsServiceResolveCancel.argtypes = [ctypes.POINTER(DNS_SERVICE_CANCEL)]
dnsapi.DnsServiceResolveCancel.restype = wintypes.DWORD

dnsapi.DnsServiceFreeInstance.argtypes = [ctypes.POINTER(DNS_SERVICE_INSTANCE)]
dnsapi.DnsServiceFreeInstance.restype = None

# ---------------- configuration ----------------
CACHE_TTL = 300
MAX_THREADS = 10
BROWSE_TIMEOUT = 15
BROWSE_QUIET = 2.5
RESOLVE_TIMEOUT = 8

# ---------------- helpers ----------------

def run(cmd):
    import subprocess
    return subprocess.check_output(cmd, text=True, stderr=subprocess.DEVNULL)

def get_locations():
    locations = json.loads(run(["smartthings", "locations", "-j"]))
    id_to_name = {}
    name_to_id = {}
    for loc in locations:
        id_to_name[loc["locationId"]] = loc["name"]
        name_to_id[loc["name"]] = loc["locationId"]
    return id_to_name, name_to_id

def get_matter_devices(location_id=None):
    cmd = ["smartthings", "devices", "--type", "MATTER", "-j"]
    if location_id:
        cmd += ["--location", location_id]
    devices = json.loads(run(cmd))
    results = []
    for d in devices:
        network_id = d.get("matter", {}).get("networkId")
        if not network_id:
            continue
        results.append({
            "label": d.get("label", "UNKNOWN"),
            "instance": network_id,
            "locationId": d.get("locationId"),
            "hostname": "",
            "ipv4": "",
            "ipv6": "",
        })
    return results

def _instance_from_service_name(name):
    suffix = "._matter._tcp.local"
    lower = name.lower()
    idx = lower.find(suffix)
    if idx >= 0:
        return name[:idx]
    return name.split("._matter._tcp.")[0]

def _record_data(record, size):
    return ctypes.string_at(ctypes.addressof(record) + 32, size)

def _pick_addresses(addr_strings):
    """Prefer a global IPv6 address, then unique-local, then link-local."""
    ipv4 = ""
    v6_global = []
    v6_ula = []
    v6_link = []
    for raw in addr_strings:
        try:
            ip = ipaddress.ip_address(str(raw).split("%", 1)[0])
        except ValueError:
            continue
        if ip.version == 4:
            if not ipv4:
                ipv4 = str(ip)
        elif ip.is_link_local:
            v6_link.append(ip)
        elif ip.is_private:
            v6_ula.append(ip)
        else:
            v6_global.append(ip)
    chosen = (v6_global or v6_ula or v6_link or [None])[0]
    ipv6 = chosen.exploded.upper() if chosen is not None else ""
    return ipv4, ipv6

def _format_ipv6(text):
    if not text:
        return ""
    try:
        return ipaddress.IPv6Address(text.split("%", 1)[0]).exploded.upper()
    except ValueError:
        return text

# ---------------- native DNS-SD discovery ----------------

class _ContextBox(ctypes.Structure):
    _fields_ = [("obj", ctypes.py_object)]

def _context_from_ptr(context_ptr):
    if not context_ptr:
        return None
    return ctypes.cast(context_ptr, ctypes.POINTER(_ContextBox)).contents.obj

class DiscoveryContext:
    def __init__(self):
        self.services = {}  # instance -> {"hostname", "ipv4": set, "ipv6": set}
        self.lock = threading.Lock()
        self.last_add = time.time()
        self.resolve_done = threading.Event()
        self.pending_resolves = 0

def _service(ctx, instance):
    entry = ctx.services.get(instance)
    if entry is None:
        entry = {"hostname": "", "ipv4": set(), "ipv6": set()}
        ctx.services[instance] = entry
        ctx.last_add = time.time()
    return entry

def browse_callback(status, context_ptr, record):
    if status not in (0, ERROR_CANCELLED) or not record or not context_ptr:
        return
    ctx = _context_from_ptr(context_ptr)
    if ctx is None:
        return
    rec = record
    current = None
    try:
        while rec:
            item = rec.contents
            if item.wType == DNS_TYPE_PTR and item.pData:
                current = _instance_from_service_name(ctypes.wstring_at(item.pData))
                with ctx.lock:
                    _service(ctx, current)
            elif current and item.wType == DNS_TYPE_SRV and item.pData:
                hostname = ctypes.wstring_at(item.pData).rstrip(".")
                with ctx.lock:
                    entry = _service(ctx, current)
                    if hostname:
                        entry["hostname"] = hostname
            elif current and item.wType == DNS_TYPE_A and item.wDataLength >= 4:
                ipv4 = socket.inet_ntoa(_record_data(item, 4))
                with ctx.lock:
                    _service(ctx, current)["ipv4"].add(ipv4)
            elif current and item.wType == DNS_TYPE_AAAA and item.wDataLength >= 16:
                ipv6 = socket.inet_ntop(socket.AF_INET6, _record_data(item, 16))
                with ctx.lock:
                    _service(ctx, current)["ipv6"].add(ipv6)
            rec = item.pNext
    except Exception:
        return

def resolve_callback(status, context_ptr, instance_ptr):
    ctx = _context_from_ptr(context_ptr)
    try:
        if status == 0 and instance_ptr and ctx is not None:
            inst = instance_ptr.contents
            full_name = inst.pszInstanceName or ""
            instance = _instance_from_service_name(full_name) if full_name else ""
            hostname = (inst.pszHostName or "").rstrip(".")
            ipv4 = ""
            ipv6 = ""
            if inst.ip4Address:
                raw = inst.ip4Address.contents
                ipv4 = socket.inet_ntoa(raw.to_bytes(4, "little"))
            if inst.ip6Address:
                ipv6 = socket.inet_ntop(socket.AF_INET6, bytes(inst.ip6Address.contents))
            if instance:
                with ctx.lock:
                    entry = _service(ctx, instance)
                    if hostname:
                        entry["hostname"] = hostname
                    if ipv4:
                        entry["ipv4"].add(ipv4)
                    if ipv6:
                        entry["ipv6"].add(ipv6)
    except Exception:
        pass
    finally:
        if instance_ptr:
            dnsapi.DnsServiceFreeInstance(instance_ptr)
        if ctx is not None:
            with ctx.lock:
                ctx.pending_resolves -= 1
                if ctx.pending_resolves <= 0:
                    ctx.resolve_done.set()

def get_dns_sd_data(debug_dns=False):
    """Discover _matter._tcp services using dnsapi.dll."""
    ctx = DiscoveryContext()
    # py_object plus an explicit keepalive. The browse request only stores the address.
    ctx_obj = _ContextBox(ctx)
    ctx_ref = ctypes.pointer(ctx_obj)
    ctx_ptr = ctypes.cast(ctx_ref, ctypes.c_void_p)

    browse_cb = BROWSE_CALLBACK(browse_callback)
    resolve_cb = RESOLVE_CALLBACK(resolve_callback)
    query = ctypes.create_unicode_buffer("_matter._tcp.local")

    req = DNS_SERVICE_BROWSE_REQUEST()
    req.Version = DNS_QUERY_REQUEST_VERSION1
    req.InterfaceIndex = 0
    req.QueryName = ctypes.cast(query, wintypes.LPCWSTR)
    req.pBrowseCallback = ctypes.cast(browse_cb, ctypes.c_void_p)
    req.pQueryContext = ctx_ptr

    cancel = DNS_SERVICE_CANCEL()
    status = dnsapi.DnsServiceBrowse(ctypes.byref(req), ctypes.byref(cancel))
    if status not in (0, DNS_REQUEST_PENDING):
        print(f"DnsServiceBrowse failed: {status}", file=sys.stderr)
        return {}

    if debug_dns:
        print(f"[DEBUG] Browsing _matter._tcp for up to {BROWSE_TIMEOUT}s...", flush=True)

    started = time.time()
    while time.time() - started < BROWSE_TIMEOUT:
        time.sleep(0.25)
        with ctx.lock:
            count = len(ctx.services)
            last_add = ctx.last_add
        if count and time.time() - last_add >= BROWSE_QUIET:
            break

    dnsapi.DnsServiceBrowseCancel(ctypes.byref(cancel))

    with ctx.lock:
        missing = [name for name, entry in ctx.services.items() if not entry["hostname"]]

    if debug_dns:
        print(f"[DEBUG] Browse saw {len(ctx.services)} services, resolving {len(missing)}", flush=True)

    resolve_names = []
    resolve_requests = []
    resolve_cancels = []
    if missing:
        with ctx.lock:
            ctx.pending_resolves = len(missing)
            ctx.resolve_done.clear()
        for instance in missing:
            buf = ctypes.create_unicode_buffer(f"{instance}._matter._tcp.local")
            rreq = DNS_SERVICE_RESOLVE_REQUEST()
            rreq.Version = DNS_QUERY_REQUEST_VERSION1
            rreq.InterfaceIndex = 0
            rreq.QueryName = ctypes.cast(buf, wintypes.LPWSTR)
            rreq.pResolveCompletionCallback = ctypes.cast(resolve_cb, ctypes.c_void_p)
            rreq.pQueryContext = ctx_ptr
            rcancel = DNS_SERVICE_CANCEL()
            rc = dnsapi.DnsServiceResolve(ctypes.byref(rreq), ctypes.byref(rcancel))
            if rc not in (0, DNS_REQUEST_PENDING):
                with ctx.lock:
                    ctx.pending_resolves -= 1
                if debug_dns:
                    print(f"[DEBUG] DnsServiceResolve failed for {instance}: {rc}", flush=True)
                continue
            resolve_names.append(buf)
            resolve_requests.append(rreq)
            resolve_cancels.append(rcancel)
        with ctx.lock:
            if ctx.pending_resolves <= 0:
                ctx.resolve_done.set()
        ctx.resolve_done.wait(RESOLVE_TIMEOUT)
        for rcancel in resolve_cancels:
            dnsapi.DnsServiceResolveCancel(ctypes.byref(rcancel))

    # Keep callback and request objects alive until the cancels above have run.
    _keepalive = (browse_cb, resolve_cb, ctx_obj, ctx_ref, query, req, resolve_names, resolve_requests)

    data = {}
    with ctx.lock:
        items = list(ctx.services.items())
    for instance, entry in items:
        ipv4, ipv6 = _pick_addresses(list(entry["ipv4"]) + list(entry["ipv6"]))
        data[instance] = {
            "hostname": entry["hostname"],
            "ipv4": ipv4,
            "ipv6": ipv6,
        }
        if debug_dns:
            print(f"[DEBUG] {instance} {entry['hostname']} {ipv6} {ipv4}", flush=True)
    return data

# ---------------- hostname cache ----------------
hostname_cache = {}

def resolve_hostname_cached(hostname, debug_dns=False):
    now = time.time()
    if hostname in hostname_cache:
        ipv4, ipv6, ts = hostname_cache[hostname]
        if now - ts < CACHE_TTL:
            return ipv4, ipv6

    ipv4, ipv6 = "", ""
    try:
        results = socket.getaddrinfo(hostname, None, socket.AF_UNSPEC, socket.SOCK_STREAM)
        for res in results:
            family, _, _, _, sockaddr = res
            ip = sockaddr[0]
            if family == socket.AF_INET and not ipv4:
                ipv4 = ip
            elif family == socket.AF_INET6 and not ipv6:
                ipv6 = _format_ipv6(ip)
    except Exception as e:
        if debug_dns:
            print(f"[DEBUG] getaddrinfo failed for {hostname}: {e}")

    hostname_cache[hostname] = (ipv4, ipv6, now)
    return ipv4, ipv6

# ---------------- help ----------------
def print_help():
    print("""Usage: matter-map [LOCATION] [OPTIONS]

Positional arguments:
  LOCATION          Filter devices by location name

Options:
  --help            Show this help message and exit
  --sort=FIELD      Sort by field: label, location, instance, hostname, ipv4, ipv6
  --reverse         Reverse sort order
  --debug-dns       Print debug info for DNS-SD queries""")

# ---------------- main ----------------
def main():
    sort_key = "label"
    reverse = False
    location_arg = None
    debug_dns = False

    args = sys.argv[1:]
    positional_args = []

    for arg in args:
        if arg == "--help":
            print_help()
            sys.exit(0)
        elif arg == "--reverse":
            reverse = True
        elif arg == "--debug-dns":
            debug_dns = True
        elif arg.startswith("--sort="):
            sort_key = arg.split("=", 1)[1]
        elif arg.startswith("-"):
            print(f"Unknown option: {arg}", file=sys.stderr)
            sys.exit(1)
        else:
            positional_args.append(arg)

    if len(positional_args) > 1:
        print("Error: only one location name may be specified", file=sys.stderr)
        sys.exit(1)
    if positional_args:
        location_arg = positional_args[0]

    valid_sorts = {"label", "location", "instance", "hostname", "ipv4", "ipv6"}
    if sort_key not in valid_sorts:
        print(f"Invalid sort key: {sort_key}", file=sys.stderr)
        print(f"Valid options: {', '.join(sorted(valid_sorts))}", file=sys.stderr)
        sys.exit(1)

    id_to_name, name_to_id = get_locations()
    location_id = None
    if location_arg:
        location_id = name_to_id.get(location_arg)
        if not location_id:
            print("Unknown location", file=sys.stderr)
            sys.exit(1)

    devices = get_matter_devices(location_id)
    dns_data = get_dns_sd_data(debug_dns)

    for d in devices:
        dns = dns_data.get(d["instance"], {})
        d["hostname"] = dns.get("hostname", "UNKNOWN") or "UNKNOWN"
        d["ipv4"] = dns.get("ipv4", "")
        d["ipv6"] = dns.get("ipv6", "")
        d["location"] = id_to_name.get(d.get("locationId"), "UNKNOWN")

    to_resolve = [
        d for d in devices
        if d["hostname"] not in ("", "UNKNOWN") and not (d["ipv4"] or d["ipv6"])
    ]
    with ThreadPoolExecutor(max_workers=MAX_THREADS) as executor:
        future_to_device = {
            executor.submit(resolve_hostname_cached, d["hostname"], debug_dns): d
            for d in to_resolve
        }
        for future in as_completed(future_to_device):
            d = future_to_device[future]
            try:
                ipv4, ipv6 = future.result()
                d["ipv4"] = ipv4 or d["ipv4"]
                d["ipv6"] = ipv6 or d["ipv6"]
            except Exception:
                pass

    devices.sort(key=lambda r: r.get(sort_key, ""), reverse=reverse)
    grouped = defaultdict(list)
    for r in devices:
        grouped[r.get("location", "UNKNOWN")].append(r)

    print(
        f"{'DEVICE LABEL':<25} {'LOCATION':<15} {'INSTANCE NAME/NETWORK ID':<40} "
        f"{'HOSTNAME':<30} {'IPv6 ADDRESS':<40} {'IPv4 ADDRESS':<20}"
    )
    print("-" * 180)

    for location in sorted(grouped):
        for r in grouped[location]:
            print(
                f"{r['label']:<25} "
                f"{location:<15} "
                f"{r['instance']:<40} "
                f"{r['hostname']:<30} "
                f"{r['ipv6']:<40} "
                f"{r['ipv4']:<20}"
            )

if __name__ == "__main__":
    main()

I would change this line:

ipv6 = chosen.exploded.upper() if chosen is not None else ""

to

ipv6 = chosen.compressed if chosen is not None else ""

to output lowercase IPv6 addresses like my original Linux version did.

Does that mean you can confirm the zeroconf version worked for you on Linux?

No, I just compared my original Matter map using dns-sd to your ported one with zeroconf. I would have to try it out with zeroconf on Linux.

Ok, tried the zeroconf version on my Debian Linux VM and it worked successfully and was about 18% faster than dns-sd.

Lovely! I’ve edited my comment above accordingly, including reverting to your original lowercase format and restoring a few of your original comments.

I managed to restore sanity to Thread Tools on one phone by disabling saving credentials to the Google cloud and then pairing a device on the problematic mesh. Thread tools then picked up the current mesh name and was able to connect to it.

My new Android phone cannot find the Thread credentials.

Thread Tools discovers Border Routers

Is there a solution for fixing this?