Last active
March 31, 2025 04:14
-
-
Save bekharsky/3e6fd2dd265b89817d5f08ff21f3f544 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const dgram = require('dgram'); | |
const { Buffer } = require('buffer'); | |
// const = 'ssdp:all'; | |
const SAMSUNG_TV_URN = 'urn:samsung.com:device:RemoteControlReceiver:1'; | |
const PORT = 1900; | |
const TIMEOUT = 2000; | |
function broadcastSsdp(socket, target) { | |
const query = Buffer.from( | |
'M-SEARCH * HTTP/1.1\r\n' + | |
`HOST: "239.255.255.250:${PORT}"\r\n` + | |
'MAN: "ssdp:discover"\r\n' + | |
'MX: 3\r\n' + | |
`ST: ${target}\r\n\r\n` | |
); | |
socket.send(query, 0, query.length, PORT, '239.255.255.250'); | |
} | |
function discover(urn) { | |
const socket = dgram.createSocket('udp4'); | |
const devices = []; | |
socket.on('listening', () => { | |
broadcastSsdp(socket, urn); | |
}); | |
socket.on('message', (chunk, info) => { | |
const buffer = Buffer.from(chunk); | |
const response = buffer.toString().trim().split('\r\n'); | |
response.forEach((item) => { | |
const splitter = item.indexOf(':'); | |
if (splitter > -1) { | |
const header = item.slice(0, splitter); | |
const value = item | |
.slice(splitter, item.length) | |
.replace(': ', ''); | |
if (header === 'ST' && value === urn) { | |
devices.push({ target: urn, info }); | |
} | |
} | |
}); | |
}); | |
socket.bind(PORT, '0.0.0.0'); | |
return new Promise((resolve) => { | |
setTimeout(() => { | |
socket.close(); | |
resolve(devices); | |
}, TIMEOUT); | |
}); | |
} | |
async function demo() { | |
const devices = await discover(SAMSUNG_TV_URN); | |
console.log(devices); | |
} | |
demo(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment