-
Notifications
You must be signed in to change notification settings - Fork 149
/
Desktop.kt
67 lines (61 loc) · 2.65 KB
/
Desktop.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.kaspersky.adbserver.desktop
import com.kaspersky.adbserver.common.api.ExecutorResultStatus
import com.kaspersky.adbserver.common.log.LoggerFactory
import com.kaspersky.adbserver.common.log.logger.DesktopLogger
import java.util.regex.Pattern
internal class Desktop(
private val cmdCommandPerformer: CmdCommandPerformer,
private val presetEmulators: List<String>,
private val adbServerPort: String?,
private val logger: DesktopLogger
) {
companion object {
private const val PAUSE_MS = 500L
}
private val devices: MutableCollection<DeviceMirror> = mutableListOf()
fun startDevicesObserving() {
logger.d("start")
while (true) {
val namesOfAttachedDevicesByAdb = getAttachedDevicesByAdb()
namesOfAttachedDevicesByAdb.forEach { deviceName ->
if (devices.find { client -> client.deviceName == deviceName } == null) {
logger.i("New device has been found: $deviceName. Initialize connection to the device...")
val deviceMirror =
DeviceMirror.create(
cmdCommandPerformer,
deviceName,
adbServerPort,
LoggerFactory.getDesktopLoggerReflectingDevice(logger, deviceName)
)
deviceMirror.startConnectionToDevice()
devices += deviceMirror
}
}
devices.removeIf { client ->
if (client.deviceName !in namesOfAttachedDevicesByAdb) {
logger.i("Adb connection to ${client.deviceName} has been missed. Stop connection.")
client.stopConnectionToDevice()
return@removeIf true
} else {
return@removeIf false
}
}
Thread.sleep(PAUSE_MS)
}
}
private fun getAttachedDevicesByAdb(): List<String> {
val pattern = Pattern.compile("^([a-zA-Z0-9\\-:.]+)(\\s+)(device)")
val commandResult = cmdCommandPerformer.perform("adb devices")
if (commandResult.status != ExecutorResultStatus.SUCCESS) {
return emptyList()
}
val adbDevicesCommandResult: String = commandResult.description
return adbDevicesCommandResult.lines()
.asSequence()
.map { pattern.matcher(it) }
.filter { matcher -> matcher.find() }
.map { matcher -> matcher.group(1) }
.filter { foundEmulator -> presetEmulators.isEmpty() || presetEmulators.contains(foundEmulator) }
.toList()
}
}