Skip to content

Instantly share code, notes, and snippets.

@notthetup
Created March 12, 2020 09:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save notthetup/4361b8f030e87508d88fee1e19f137e2 to your computer and use it in GitHub Desktop.
Save notthetup/4361b8f030e87508d88fee1e19f137e2 to your computer and use it in GitHub Desktop.
Javascript to find modems.
function findModems(baseIP='192.168.0', lowIP=0, highIP=255, maxInFlight=20, timeout=4000) {
var currIP = lowIP;
var inFlight = 0;
var modems = [];
var path = '/ws/';
return new Promise( resolve => {
function tryOne(ip) {
++inFlight;
var socket = new WebSocket('ws://' + baseIP + ip + path);
var timer = setTimeout(() => {
try {
socket.close();
}catch(e){
//
}
--inFlight;
next();
}, timeout);
socket.onopen = () => {
clearTimeout(timer);
modems.push(socket.url);
--inFlight;
next();
};
socket.onerror = () => {
clearTimeout(timer);
--inFlight;
next();
};
}
function next() {
while (currIP <= highIP && inFlight < maxInFlight) tryOne(currIP++);
if (inFlight === 0) resolve(modems);
}
next();
});
}
findModems('192.168.0.', 1, 255, 20, 4000).then(modems => {
if (!modems) console.log('No modems found! :( ');
modems.forEach(m => {
console.log('Modem found at ' + m);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment