From 938c7c5f5e41db941e7f69ba8922c2faecf83b92 Mon Sep 17 00:00:00 2001 From: Jan Romann Date: Mon, 22 Jan 2024 03:16:22 +0100 Subject: [PATCH] fixup! feat: implement unicast DNS-SD --- .../core/implementation/thing_discovery.dart | 42 +++++++++++++------ 1 file changed, 29 insertions(+), 13 deletions(-) diff --git a/lib/src/core/implementation/thing_discovery.dart b/lib/src/core/implementation/thing_discovery.dart index a513b350..fbec95f9 100644 --- a/lib/src/core/implementation/thing_discovery.dart +++ b/lib/src/core/implementation/thing_discovery.dart @@ -243,7 +243,7 @@ class ThingDiscovery extends Stream ); } - Map _parseTxtRecords(String txtRecords) { + Map _parseMdnsTxtRecords(String txtRecords) { final recordsList = txtRecords .split("\n") .map((property) => property.split("=")) @@ -253,6 +253,29 @@ class ThingDiscovery extends Stream return Map.fromEntries(recordsList); } + static String _trimTxtRecord(String txtRecord) { + final startIndex = txtRecord.startsWith('"') ? 1 : 0; + + final length = txtRecord.length; + final endIndex = txtRecord.endsWith('"') ? length - 1 : length; + + return txtRecord.substring(startIndex, endIndex); + } + + Map _parseTxtRecords(List? txtRecords) { + final entries = txtRecords + ?.map((txtRecord) => txtRecord.data) + .map(_trimTxtRecord) + .map((e) => e.split("=")) + .where((element) => element.length == 2) + .map((txtRecord) { + return MapEntry(txtRecord[0], txtRecord[1]); + }) ?? + []; + + return Map.fromEntries(entries); + } + Future?> _lookupTxtRecords( MDnsClient client, String domainName, @@ -267,7 +290,7 @@ class ThingDiscovery extends Stream return null; } - return _parseTxtRecords(firstTxtRecord); + return _parseMdnsTxtRecords(firstTxtRecord); } Stream _discoverUsingDnsSd(String name) async* { @@ -309,20 +332,13 @@ class ThingDiscovery extends Stream ) ?? []; - final txtRecord = txtRecords.firstOrNull; - - if (txtRecord == null) { - continue; - } - - // FIXME: Add parsing of multiple TXT records - final parsedTxtRecord = _parseTxtRecords(txtRecord.data); + final parsedTxtRecords = _parseTxtRecords(txtRecords); final uri = Uri( host: target, port: port, - path: parsedTxtRecord["td"], - scheme: parsedTxtRecord["scheme"] ?? defaultScheme, + path: parsedTxtRecords["td"], + scheme: parsedTxtRecords["scheme"] ?? defaultScheme, ); final duplicate = !discoveredUris.add(uri); @@ -331,7 +347,7 @@ class ThingDiscovery extends Stream continue; } - final type = parsedTxtRecord["type"] ?? defaultType; + final type = parsedTxtRecords["type"] ?? defaultType; switch (type) { case "Thing":