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 6, 2021
1 parent 4fdd292 commit 287c2e7
Showing 1 changed file with 36 additions and 13 deletions.
49 changes: 36 additions & 13 deletions src/mdns.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
}

0 comments on commit 287c2e7

Please sign in to comment.