// Unit discovery fed by the app shell over IPC. On Android the shell's Kotlin
// lamp finder (NsdManager, browsing _cthuloid._tcp) does the mDNS work and sends
// { t: 'unit-up', name, host, addr, port, proto }
// { t: 'unit-down', name }
// { t: 'discovery', available, reason }
// which this turns into the same events avahi produces on a desktop
// (webui/lib/discovery.js), so the rig cannot tell them apart.
import EventEmitter from 'bare-events'
export class IpcDiscovery extends EventEmitter {
constructor () {
super()
this.available = true
this.reason = ''
}
start () {}
stop () {}
// Returns true if the message was a discovery message.
handle (m) {
if (!m || typeof m !== 'object') return false
if (m.t === 'unit-up') {
const port = Number(m.port)
if (!m.name || !m.addr || !Number.isInteger(port)) return true
this.emit('up', {
name: String(m.name),
host: String(m.host || m.name + '.local'),
addr: String(m.addr),
port,
proto: Number(m.proto) || 0
})
return true
}
if (m.t === 'unit-down') {
if (m.name) this.emit('down', { name: String(m.name) })
return true
}
if (m.t === 'discovery') {
const was = this.available
this.available = !!m.available
this.reason = this.available ? '' : String(m.reason || 'lamp discovery is not running')
if (was !== this.available) this.emit(this.available ? 'available' : 'unavailable', this.reason)
return true
}
return false
}
}