Skip to content

Commit

Permalink
feature: use vessel name as mdns serviceName
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
tkurki committed Apr 7, 2021
1 parent 4fdd292 commit d21ad32
Showing 1 changed file with 31 additions and 8 deletions.
39 changes: 31 additions & 8 deletions src/mdns.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,18 +89,15 @@ 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 +
Expand All @@ -109,14 +106,20 @@ module.exports = function mdnsResponder(app) {
':' +
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)
})
ad.start()
ads.push(ad)
}
})

return {
stop: function() {
Expand All @@ -127,3 +130,23 @@ module.exports = function mdnsResponder(app) {
}
}
}

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) {
// tslint:disable-next-line:no-bitwise
return ~-encodeURI(s).split(/%..|./).length
}

0 comments on commit d21ad32

Please sign in to comment.