Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tweak: more robust device-selection logic. Embedding idb_companion #314

Merged
merged 6 commits into from
Oct 26, 2022
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion maestro-cli/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ dependencies {

implementation project(':maestro-client')
implementation project(':maestro-orchestra')
implementation "dev.mobile:dadb:1.2.1"
implementation "dev.mobile:dadb:1.2.2"
implementation 'info.picocli:picocli:4.5.2'
implementation 'com.fasterxml.jackson.core:jackson-databind:2.13.2.1'
implementation 'com.fasterxml.jackson.module:jackson-module-kotlin:2.13.2'
Expand Down
5 changes: 4 additions & 1 deletion maestro-cli/src/main/java/maestro/cli/App.kt
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,14 @@ class App {
var platform: String? = null

@Option(names = ["--host"])
var host: String = "localhost"
var host: String? = null

@Option(names = ["--port"])
var port: Int? = null

@Option(names = ["--device", "--udid"])
var deviceId: String? = null

companion object {
init {
AnsiConsole.systemInstall()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ class PrintHierarchyCommand : Runnable {
private val parent: App? = null

override fun run() {
MaestroFactory.createMaestro(parent?.platform, parent?.host, parent?.port).use {
MaestroFactory.createMaestro(parent?.host, parent?.port, parent?.deviceId).use {
val hierarchy = jacksonObjectMapper()
.setSerializationInclusion(JsonInclude.Include.NON_NULL)
.writerWithDefaultPrettyPrinter()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ class QueryCommand : Runnable {

override fun run() {

MaestroFactory.createMaestro(parent?.platform, parent?.host, parent?.port).use { maestro ->
MaestroFactory.createMaestro(parent?.host, parent?.port, parent?.deviceId).use { maestro ->
val filters = mutableListOf<ElementFilter>()

text?.let {
Expand Down
7 changes: 6 additions & 1 deletion maestro-cli/src/main/java/maestro/cli/command/TestCommand.kt
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
package maestro.cli.command

import maestro.cli.App
import maestro.cli.CliError
import maestro.cli.runner.TestRunner
import maestro.cli.util.MaestroFactory
import picocli.CommandLine
Expand Down Expand Up @@ -55,7 +56,11 @@ class TestCommand : Callable<Int> {
)
}

val maestro = MaestroFactory.createMaestro(parent?.platform, parent?.host, parent?.port)
if (parent?.platform != null) {
throw CliError("--platform option was deprecated. You can remove it to run your test.")
}

val maestro = MaestroFactory.createMaestro(parent?.host, parent?.port, parent?.deviceId)

if (!continuous) return TestRunner.runSingle(maestro, flowFile, env)

Expand Down
15 changes: 15 additions & 0 deletions maestro-cli/src/main/java/maestro/cli/device/Device.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package maestro.cli.device

data class Device(
val id: String,
val description: String,
val platform: Platform,
val connected: Boolean,
) {

enum class Platform(val description: String) {
ANDROID("Android"),
IOS("iOS"),
}

}
164 changes: 164 additions & 0 deletions maestro-cli/src/main/java/maestro/cli/device/DeviceService.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
package maestro.cli.device

import com.github.michaelbull.result.expect
import dadb.Dadb
import io.grpc.ManagedChannelBuilder
import ios.idb.IdbIOSDevice
import maestro.MaestroTimer
import maestro.cli.CliError
import maestro.cli.device.ios.Simctl
import maestro.cli.util.EnvUtils
import java.io.File

object DeviceService {

fun startDevice(device: Device): Device {
dmitry-zaitsev marked this conversation as resolved.
Show resolved Hide resolved
when (device.platform) {
Device.Platform.IOS -> {
Simctl.launchSimulator(device.id)
Simctl.awaitLaunch(device.id)
return device
}
Device.Platform.ANDROID -> {
val androidHome = EnvUtils.androidHome()
?: throw CliError("ANDROID_HOME environment variable is not set. Unable to find 'ANDROID_HOME/tools/emulator' executable.")
dmitry-zaitsev marked this conversation as resolved.
Show resolved Hide resolved

ProcessBuilder(
File(androidHome, "tools/emulator").absolutePath,
dmitry-zaitsev marked this conversation as resolved.
Show resolved Hide resolved
"@${device.id}",
).start()

val dadb = MaestroTimer.withTimeout(30000) {
try {
Dadb.discover()
} catch (ignored: Exception) {
Thread.sleep(100)
null
}
} ?: throw CliError("Unable to start device: ${device.id}")

return device.copy(id = dadb.toString())
}
}
}

fun prepareDevice(device: Device) {
if (device.platform == Device.Platform.IOS) {
killIdbCompanion()
startIdbCompanion(device)
}
}

private fun startIdbCompanion(device: Device) {
ProcessBuilder("idb_companion", "--udid", device.id)
.redirectError(ProcessBuilder.Redirect.DISCARD)
.redirectOutput(ProcessBuilder.Redirect.DISCARD)
.start()

val iosDevice = IdbIOSDevice(
ManagedChannelBuilder.forAddress("localhost", 10882)
.usePlaintext()
.build()
)
try {
// Try to connect to the device repeatedly
MaestroTimer.withTimeout(10000) {
try {
iosDevice.deviceInfo().expect {}
} catch (ignored: Exception) {
// Ignore
null
}
} ?: error("idb_companion did not start in time")
} finally {
iosDevice.close()
}
}

private fun killIdbCompanion() {
ProcessBuilder("killall", "idb_companion")
.redirectError(ProcessBuilder.Redirect.PIPE)
.start()
.waitFor()
}

fun listConnectedDevices(): List<Device> {
return listAvailableDevices()
.filter { it.connected }
}

fun listAvailableDevices(): List<Device> {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this is used to list devices available to start, it should not include devices listed by Dadb

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tweaked it in a way that it contains a sealed class. Splitting this logic into different methods would do more harm than good, I feel

return listAndroidDevices() + listIOSDevices()
}

private fun listAndroidDevices(): List<Device> {
val connectedDevices = Dadb.list()
.map {
Device(
id = it.toString(),
description = it.toString(),
platform = Device.Platform.ANDROID,
connected = true
)
}

// Note that there is a possibility that AVD is actually already connected and is present in
// connectedDevices.
val avds = try {
ProcessBuilder("emulator", "-list-avds")
.start()
.inputStream
.bufferedReader()
.useLines { lines ->
lines
.map {
Device(
id = it,
description = it,
platform = Device.Platform.ANDROID,
connected = false
)
}
.toList()
}
} catch (ignored: Exception) {
emptyList()
}

return connectedDevices + avds
}

private fun listIOSDevices(): List<Device> {
val simctlList = try {
Simctl.list()
} catch (ignored: Exception) {
return emptyList()
}

val runtimes = simctlList
.runtimes

return runtimes
.flatMap { runtime ->
runtime.supportedDeviceTypes
.flatMap { supportedDeviceType ->
simctlList.devices
.values
.flatten()
.filter {
it.isAvailable &&
it.deviceTypeIdentifier == supportedDeviceType.identifier
}
}
.map { device ->
Device(
id = device.udid,
description = "${device.name} - ${runtime.name} - ${device.udid}",
platform = Device.Platform.IOS,
connected = device.state == "Booted"
)
}
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package maestro.cli.device

import maestro.cli.CliError

object PickDeviceInteractor {

fun pickDevice(deviceId: String? = null): Device {
if (deviceId != null) {
return DeviceService.listConnectedDevices()
.find { it.id == deviceId }
?: throw CliError("Device with id $deviceId is not connected")
}

return pickDeviceInternal()
.let { pickedDevice ->
var result = pickedDevice

if (!result.connected) {
result = DeviceService.startDevice(pickedDevice)
}

DeviceService.prepareDevice(result)

result
}
}

private fun pickDeviceInternal(): Device {
val connectedDevices = DeviceService.listConnectedDevices()

if (connectedDevices.size == 1) {
val device = connectedDevices[0]

PickDeviceView.showRunOnDevice(device)

return device
}

if (connectedDevices.isEmpty()) {
return startDevice()
}

return pickRunningDevice(connectedDevices)
}

private fun startDevice(): Device {
val availableDevices = DeviceService.listAvailableDevices()

return PickDeviceView.pickDeviceToStart(availableDevices)
}

private fun pickRunningDevice(devices: List<Device>): Device {
return PickDeviceView.pickRunningDevice(devices)
}

}

fun main() {
println(PickDeviceInteractor.pickDevice())

println("Ready")
while (!Thread.interrupted()) {
Thread.sleep(1000)
}
}
61 changes: 61 additions & 0 deletions maestro-cli/src/main/java/maestro/cli/device/PickDeviceView.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package maestro.cli.device

object PickDeviceView {

fun showRunOnDevice(device: Device) {
println("Running on ${device.description}")
}

fun pickDeviceToStart(devices: List<Device>): Device {
dmitry-zaitsev marked this conversation as resolved.
Show resolved Hide resolved
printIndexedDevices(devices)

println("No running devices detected. Choose a device to boot and run on.")
println()
println("Enter a number from the list above:")

return pickIndex(devices)
}

fun pickRunningDevice(devices: List<Device>): Device {
printIndexedDevices(devices)

println("Multiple running devices detected. Choose a device to run on.")
println()
println("Enter a number from the list above:")

return pickIndex(devices)
}

private fun <T> pickIndex(data: List<T>): T {
while (!Thread.interrupted()) {
val index = readLine()?.toIntOrNull() ?: 0

if (index < 1 || index > data.size) {
println("Invalid index")
continue
}

return data[index - 1]
}

error("Interrupted")
}

private fun printIndexedDevices(devices: List<Device>) {
val devicesByPlatform = devices.groupBy {
it.platform
}

var index = 0

devicesByPlatform.forEach { (platform, devices) ->
println(platform.description)
println()
devices.forEach { device ->
println(" [${++index}] ${device.description}")
}
println()
}
}

}
Loading