Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env kscript
- //DEPS org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.0
- import java.io.File
- import java.util.concurrent.TimeUnit
- import java.io.IOException
- import kotlinx.coroutines.*
- import kotlinx.coroutines.sync.Mutex
- import kotlinx.coroutines.sync.withLock
- private var recentStart = 0L
- private val startMutex = Mutex()
- fun String.runCommand(workingDir: File = File("."), timeoutMinutes: Long = Long.MAX_VALUE * -1L): String? {
- try {
- val parts = this.split("\\s".toRegex())
- val proc = ProcessBuilder(*parts.toTypedArray())
- .directory(workingDir)
- .redirectOutput(ProcessBuilder.Redirect.PIPE)
- .redirectError(ProcessBuilder.Redirect.PIPE)
- .start()
- proc.waitFor(timeoutMinutes, TimeUnit.MINUTES)
- return proc.inputStream.bufferedReader().readText()
- } catch(e: IOException) {
- e.printStackTrace()
- return null
- }
- }
- "adb devices".runCommand()?.also { devices ->
- val deviceLines = devices.split("\n").filter { it.isNotBlank() }
- if (deviceLines.size >= 2) {
- runBlocking {
- val scrCpyJobs = (1 .. deviceLines.lastIndex).map {
- val serial = deviceLines[it].split("\t")[0]
- if (serial.isNotBlank()) restartingScrCpy(serial).also { delay(5000) }
- else null
- }.filter { it != null } as Collection<Job>
- System.out.println("waiting for exit")
- scrCpyJobs.joinAll()
- }
- }
- }
- fun CoroutineScope.restartingScrCpy(serial: String): Job =
- launch(Dispatchers.IO) { while(isActive) { scrCpy(serial) } }
- suspend fun scrCpy(serial: String): String? {
- startMutex.withLock {
- val timeDiff = System.currentTimeMillis() - recentStart
- if (timeDiff < 5000) delay(timeDiff.toLong())
- recentStart = System.currentTimeMillis()
- }
- return "scrcpy -s $serial".runCommand()
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement