homebridge-prometheus-exporter/src/discovery/hap_node_js_client.ts

46 lines
1.5 KiB
TypeScript
Raw Normal View History

2022-11-06 13:50:39 +01:00
import type { HapDiscover } from './api'
import { HAPNodeJSClient } from 'hap-node-client'
import { Device, DeviceBoundary } from '../boundaries'
import { Array, Unknown } from 'runtypes'
const MaybeDevices = Array(Unknown)
export const discover: HapDiscover = ({ pin, refreshInterval, discoveryTimeout, requestTimeout, logger, debug }) => {
return new Promise((resolve, reject) => {
try {
const client = new HAPNodeJSClient({
debug: debug,
refresh: refreshInterval,
timeout: discoveryTimeout,
reqTimeout: requestTimeout,
pin,
})
client.on('Ready', (deviceData: unknown) => {
try {
const devices: Device[] = []
for (const device of MaybeDevices.check(deviceData)) {
try {
devices.push(DeviceBoundary.check(device))
} catch (e) {
logger.error(
'Boundary check for device data failed %o %s',
e,
JSON.stringify(device, null, 4),
)
}
}
resolve(devices)
} catch (e) {
reject(e)
}
})
} catch (e) {
reject(e)
}
})
}