Last active
May 30, 2023 13:25
-
-
Save qgustavor/64141a41907db78401a41b4c494f91b7 to your computer and use it in GitHub Desktop.
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
// Download Deno here: https://deno.land/#installation | |
// Download this file | |
// Run it using: deno run -A adb-auto-connect.ts [ip address] | |
import PQueue from 'https://deno.land/x/p_queue@1.0.1/mod.ts' | |
import ProgressBar from 'https://deno.land/x/progress@v1.2.7/mod.ts' | |
const hostname = Deno.args[0] ?? '' // <-- set default ip address here to make the argument optional | |
// Check if it's needed and prompt | |
const connectedDevices = new TextDecoder().decode(await Deno.run({ | |
cmd: ['adb', 'devices'], | |
stdout: 'piped' | |
}).output()).split(/\r?\n/g).filter(e => e).slice(1).map(e => e.split('\t')[0]) | |
if (connectedDevices.length > 0) { | |
console.log('Already connected to ' + connectedDevices.join(' ')) | |
console.log('Press y to disconnect and start scanning') | |
if (!confirm()) Deno.exit() | |
await Deno.run({ | |
cmd: ['adb', 'disconnect'] | |
}).status() | |
} | |
let foundPort: number | null = null | |
const queue = new PQueue({ concurrency: 2048 }) | |
const title = 'Scanning:' | |
const minPort = 37000 | |
const maxPort = 44000 | |
const total = maxPort - minPort | |
let completed = 0 | |
const progress = new ProgressBar({ | |
display: ':bar :percent eta :eta', | |
title, | |
total | |
}) | |
for (let port = minPort; port < maxPort; port++) { | |
queue.add(async () => { | |
if (foundPort) return | |
try { | |
const conn = await Deno.connect({ | |
hostname, | |
port | |
}) | |
conn.closeWrite() | |
foundPort = port | |
} catch (e) {} | |
progress.render(completed++) | |
}) | |
} | |
if (foundPort === null) { | |
await new Promise(resolve => queue.addEventListener('idle', resolve)) | |
} | |
if (foundPort) { | |
const ipPortPair = hostname + ':' + foundPort | |
console.log('\n\nConnecting to', ipPortPair) | |
await Deno.run({ | |
cmd: ['adb', 'connect', ipPortPair] | |
}).status() | |
} else { | |
console.error('Not found!') | |
} | |
// By the way, "-A" means "allow all permissions" but if you want to be | |
// extra safe replace it with --allow-net=[ip address] --allow-run=adb | |
// More info here: https://deno.land/manual@v1.24.3/getting_started/permissions |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Check multicast DNS version here: https://gist.github.com/qgustavor/3a7798606fb8109c22609780115b71ac