refactor to allow bundling

This commit is contained in:
David Ventura
2024-04-26 10:32:56 +02:00
parent 1c6312e0c9
commit 639a78419e
8 changed files with 656 additions and 188 deletions
+7 -9
View File
@@ -2,23 +2,21 @@ import EventEmitter from "node:events";
import { create_LanSearch, parse_PunchPkt } from "./impl.js";
import { createSocket, RemoteInfo } from "node:dgram";
import { Commands } from "./datatypes.js";
import { hexdump } from "./hexdump.js";
import { opt } from "./options.js";
const handleIncomingPunch = (msg: Buffer, ee: EventEmitter, rinfo: RemoteInfo, options: opt) => {
const handleIncomingPunch = (msg: Buffer, ee: EventEmitter, rinfo: RemoteInfo, debug: boolean) => {
const ab = new Uint8Array(msg).buffer;
const dv = new DataView(ab);
const cmd_id = dv.readU16();
if (cmd_id != Commands.PunchPkt) {
return;
}
if (options.debug) {
if (debug) {
console.log("Discovery got a PunchPkt");
}
ee.emit("discover", rinfo, parse_PunchPkt(dv));
};
export const discoverDevices = (options: opt): EventEmitter => {
export const discoverDevices = (debug: boolean, discovery_ip: string): EventEmitter => {
const sock = createSocket("udp4");
const SEND_PORT = 32108;
const ee = new EventEmitter();
@@ -28,18 +26,18 @@ export const discoverDevices = (options: opt): EventEmitter => {
sock.close();
});
sock.on("message", (msg, rinfo) => handleIncomingPunch(msg, ee, rinfo, options));
sock.on("message", (msg, rinfo) => handleIncomingPunch(msg, ee, rinfo, debug));
sock.on("listening", () => {
sock.setBroadcast(true);
console.log("Searching for devices..");
console.log(`Searching for devices on ${discovery_ip}`);
let buf = create_LanSearch();
setInterval(() => {
console.log(".");
sock.send(new Uint8Array(buf.buffer), SEND_PORT, options.discovery_ip);
sock.send(new Uint8Array(buf.buffer), SEND_PORT, discovery_ip);
}, 2000);
sock.send(new Uint8Array(buf.buffer), SEND_PORT, options.discovery_ip);
sock.send(new Uint8Array(buf.buffer), SEND_PORT, discovery_ip);
});
sock.bind();