hyperdeck-monitor/index.ts

108 lines
2.6 KiB
TypeScript
Raw Normal View History

2024-05-20 23:04:47 +01:00
import { Hyperdeck, Commands } from 'hyperdeck-connection';
import WebSocket from 'ws';
2024-05-20 23:04:47 +01:00
interface WrappedHyperdeck {
ip: String,
port: number,
hyperdeck: Hyperdeck
}
const hyperdecks: Map<string, WrappedHyperdeck> = new Map()
enum WebSocketMessageType {
2024-05-22 01:20:03 +01:00
AddHyperdeck = "add_hyperdeck",
RemoveHyperdeck = "remove_hyperdeck"
2024-05-20 23:04:47 +01:00
}
type WebSocketMessage = {
type: WebSocketMessageType.AddHyperdeck,
id: string,
ip: string,
port: number
2024-05-22 01:20:03 +01:00
} | {
type: WebSocketMessageType.RemoveHyperdeck,
id: string
2024-05-20 23:04:47 +01:00
}
const wss = new WebSocket.Server({ port: 7867 });
wss.on('connection', function connection(ws) {
ws.on('message', function message(data) {
2024-05-20 23:04:47 +01:00
try {
const message = JSON.parse(data.toString()) as Partial<WebSocketMessage>;
handle_message(message)
} catch (_err) {
return;
}
});
ws.send(JSON.stringify({
event: "log",
message: "Hello"
}));
});
2024-05-20 23:04:47 +01:00
function exhaustiveMatch(_never: never) {
return;
}
function handle_message(message: Partial<WebSocketMessage>) {
console.log(JSON.stringify(message));
if (message.type === undefined) return;
switch (message.type) {
case WebSocketMessageType.AddHyperdeck:
if (message.id === undefined) return;
if (message.ip === undefined) return;
if (message.port === undefined) return;
if (isNaN(message.port)) return;
if (message.port <= 0) return;
console.log("Adding hyperdeck");
const newHyperdeck = new Hyperdeck()
2024-05-22 01:20:03 +01:00
hyperdecks.set(message.id, {
ip: message.ip,
port: message.port,
hyperdeck: newHyperdeck
});
2024-05-20 23:04:47 +01:00
newHyperdeck.on('connected', (info) => {
console.log(JSON.stringify(info))
newHyperdeck.sendCommand(new Commands.TransportInfoCommand()).then((transportInfo) => {
console.log(JSON.stringify(transportInfo))
})
})
newHyperdeck.on('notify.slot', function (state) {
console.log(JSON.stringify(state)) // catch the slot state change.
})
newHyperdeck.on('notify.transport', function (state) {
console.log(JSON.stringify(state)) // catch the transport state change.
})
newHyperdeck.on('error', (err) => {
console.log('Hyperdeck error', JSON.stringify(err))
})
newHyperdeck.connect(message.ip, message.port)
2024-05-22 01:20:03 +01:00
break;
case WebSocketMessageType.RemoveHyperdeck:
if (message.id === undefined) return;
console.log("Removing hyperdeck");
let hyperdeck = hyperdecks.get(message.id)
if (hyperdeck === undefined) return;
hyperdeck.hyperdeck.disconnect()
hyperdecks.delete(message.id)
2024-05-20 23:04:47 +01:00
break;
default:
2024-05-22 01:20:03 +01:00
exhaustiveMatch(message)
2024-05-20 23:04:47 +01:00
}
}