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 325fe1c
Showing 1 changed file with 37 additions and 14 deletions.
51 changes: 37 additions & 14 deletions src/mdns.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,41 +89,64 @@ 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)
})
ad.start()
ads.push(ad)
}
})

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
}

0 comments on commit 325fe1c

Please sign in to comment.