// A unit seen before is dialled at its LAST IP, even before (or without)
// discovery reporting it again. On a phone `<name>.local` cannot be resolved at
// all (Android gives apps no DNS config), so falling back to it means no lamp.
import test from 'brittle'
import EventEmitter from 'bare-events'
import { Rig } from '../lib/rig.js'
import { FakeUnitV3, waitFor } from './helpers.js'
class FakeDiscovery extends EventEmitter {
constructor () { super(); this.available = true; this.reason = '' }
start () {}
stop () {}
}
class MemStore {
constructor () { this.data = {} }
load () { return this.data }
save (d) { this.data = JSON.parse(JSON.stringify(d)) }
}
test('the last discovered address is saved and dialled after a restart', async (t) => {
const fake = await new FakeUnitV3('lamp').listen()
const store = new MemStore()
const d1 = new FakeDiscovery()
const a = new Rig({ store, discovery: d1, unitOpts: { backoffStartMs: 100 } })
a.start()
d1.emit('up', { name: 'lamp', host: 'lamp.local', addr: '127.0.0.1', port: fake.port, proto: 3 })
a.updateUnit('lamp', { enabled: true })
a.flushSave()
a.stop()
t.is(store.data.units.lamp.lastAddr, '127.0.0.1', 'saved')
// Restart with a discovery that never reports the unit.
const b = new Rig({ store, discovery: new FakeDiscovery(), unitOpts: { backoffStartMs: 100 } })
b.start()
b.setConnected(true)
t.ok(await waitFor(() => b.snapshot().units[0].status === 'connected'), 'connected via the remembered IP')
b.stop()
await fake.close()
})
test('adding by IP remembers that IP', async (t) => {
const fake = await new FakeUnitV3('lamp2').listen()
const store = new MemStore()
const r = new Rig({ store, discovery: new FakeDiscovery(), unitOpts: { backoffStartMs: 100 } })
r.start()
await r.addManual('127.0.0.1', fake.port)
r.flushSave()
t.is(store.data.units.lamp2.lastAddr, '127.0.0.1')
r.stop()
await fake.close()
})