Advertisement
Guest User

Untitled

a guest
Oct 15th, 2019
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.90 KB | None | 0 0
  1. #!/usr/bin/env kscript
  2. //DEPS org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.0
  3.  
  4. import java.io.File
  5. import java.util.concurrent.TimeUnit
  6. import java.io.IOException
  7. import kotlinx.coroutines.*
  8. import kotlinx.coroutines.sync.Mutex
  9. import kotlinx.coroutines.sync.withLock
  10.  
  11.  
  12.  
  13. private var recentStart = 0L
  14. private val startMutex = Mutex()
  15.  
  16. fun String.runCommand(workingDir: File = File("."), timeoutMinutes: Long = Long.MAX_VALUE * -1L): String? {
  17. try {
  18. val parts = this.split("\\s".toRegex())
  19. val proc = ProcessBuilder(*parts.toTypedArray())
  20. .directory(workingDir)
  21. .redirectOutput(ProcessBuilder.Redirect.PIPE)
  22. .redirectError(ProcessBuilder.Redirect.PIPE)
  23. .start()
  24.  
  25. proc.waitFor(timeoutMinutes, TimeUnit.MINUTES)
  26. return proc.inputStream.bufferedReader().readText()
  27. } catch(e: IOException) {
  28. e.printStackTrace()
  29. return null
  30. }
  31. }
  32.  
  33.  
  34. "adb devices".runCommand()?.also { devices ->
  35. val deviceLines = devices.split("\n").filter { it.isNotBlank() }
  36. if (deviceLines.size >= 2) {
  37. runBlocking {
  38. val scrCpyJobs = (1 .. deviceLines.lastIndex).map {
  39. val serial = deviceLines[it].split("\t")[0]
  40. if (serial.isNotBlank()) restartingScrCpy(serial).also { delay(5000) }
  41. else null
  42. }.filter { it != null } as Collection<Job>
  43.  
  44. System.out.println("waiting for exit")
  45. scrCpyJobs.joinAll()
  46. }
  47. }
  48. }
  49.  
  50. fun CoroutineScope.restartingScrCpy(serial: String): Job =
  51. launch(Dispatchers.IO) { while(isActive) { scrCpy(serial) } }
  52.  
  53. suspend fun scrCpy(serial: String): String? {
  54. startMutex.withLock {
  55. val timeDiff = System.currentTimeMillis() - recentStart
  56. if (timeDiff < 5000) delay(timeDiff.toLong())
  57. recentStart = System.currentTimeMillis()
  58. }
  59. return "scrcpy -s $serial".runCommand()
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement