Skip to content

Instantly share code, notes, and snippets.

@gustavopch
Created March 15, 2019 18:35
Show Gist options
  • Save gustavopch/d35545f4f595d7e9d75aee811013f836 to your computer and use it in GitHub Desktop.
Save gustavopch/d35545f4f595d7e9d75aee811013f836 to your computer and use it in GitHub Desktop.
import fs from 'fs'
/**
* Determines the maximum lp that will be tested.
* @example MAX = 10 // => '/dev/usb/lp9'
*/
const MAX = 10
/**
* How much to wait after each testing cycle.
*/
const WAIT = 5000
const write = (path: string, data: any) => {
return new Promise((resolve, reject) => {
fs.writeFile(path, data, err => {
if (err) {
reject(err)
} else {
resolve()
}
})
})
}
/**
* Tries to write to every /dev/usb/lp from 0 to MAX. Returns on success.
*/
export const findInterface = async (): Promise<string> => {
return new Promise(async resolve => {
while (true) {
for (let i = 0; i < MAX; i++) {
const iface = `/dev/usb/lp${i}`
try {
await write(iface, '')
// Got it!
console.log(`${iface} will be used`)
return resolve(iface)
} catch (err) {
console.log(`${iface} not available`)
}
// Wait a bit when just cycled through all interfaces
const isLast = i === MAX - 1
if (isLast) {
await new Promise(resolve => setTimeout(resolve, WAIT))
}
}
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment