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