Created
March 12, 2020 09:06
-
-
Save notthetup/4361b8f030e87508d88fee1e19f137e2 to your computer and use it in GitHub Desktop.
Javascript to find modems.
This file contains 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
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