From 287c2e7e870f5418707b3006dd0c8b6f22fa2244 Mon Sep 17 00:00:00 2001 From: Teppo Kurki Date: Tue, 6 Apr 2021 22:00:13 +0300 Subject: [PATCH] feature: use vessel name as mdns serviceName https://tools.ietf.org/html/rfc6763#section-4.1.1 For the http service prefix the vessel name with SK. For the SK service types just use the vessel name. --- src/mdns.js | 49 ++++++++++++++++++++++++++++++++++++------------- 1 file changed, 36 insertions(+), 13 deletions(-) diff --git a/src/mdns.js b/src/mdns.js index ee7a6f100..7dcb57e1e 100644 --- a/src/mdns.js +++ b/src/mdns.js @@ -89,27 +89,31 @@ module.exports = function mdnsResponder(app) { txt: txtRecord } - const host = app.config.getExternalHostname() + const instanceName = getInstanceName(app.signalk) + const host = app.config.getExternalHostname() if (host !== require('os').hostname()) { options.host = host } - debug(options) const ads = [] - // tslint:disable-next-line: forin - for (const i in types) { - const type = types[i] + types.forEach((type, i) => { debug( 'Starting mDNS ad: ' + - type.type + - ' ' + - app.config.getExternalHostname() + - ':' + - type.port + type.type + + ' ' + + app.config.getExternalHostname() + + ':' + + type.port ) - const ad = new mdns.Advertisement(type.type, type.port, options) + let name + if (instanceName) { + name = toUtfMaxLength(i === 0 ? `SK ${instanceName}` : instanceName) + } + const optionsForType = {name, ...options} + debug(optionsForType) + const ad = new mdns.Advertisement(type.type, type.port, optionsForType) ad.on('error', err => { console.log(type.type.name) console.error(err) @@ -119,11 +123,30 @@ module.exports = function mdnsResponder(app) { } return { - stop: function() { - ads.forEach(function(ad) { + stop: function () { + ads.forEach(function (ad) { debug('Stopping mDNS advertisement...') ad.stop() }) } } } + +const AD_NAME_MAX_UTF_LENGTH = 63 - 3 //allow prefix 'SK ' for http + +function getInstanceName(signalk) { + const full = signalk.retrieve() + return _.get(full, `${_.get(full, 'self')}.name`) +} + +function toUtfMaxLength(s) { + let result = s + while (utfLength(result) > AD_NAME_MAX_UTF_LENGTH) { + result = result.slice(0, result.length - 1) + } + return result +} + +function utfLength(s) { + return ~-encodeURI(s).split(/%..|./).length +} \ No newline at end of file