-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathFreeDeviceFinder.js
More file actions
70 lines (59 loc) · 1.95 KB
/
FreeDeviceFinder.js
File metadata and controls
70 lines (59 loc) · 1.95 KB
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
68
69
70
/**
* @typedef {import('../../../common/drivers/android/tools/DeviceHandle')} DeviceHandle
* @typedef {import('../../../common/drivers/android/tools/EmulatorHandle')} EmulatorHandle
*/
const log = require('../../../../utils/logger').child({ cat: 'device' });
const DEVICE_LOOKUP = { event: 'DEVICE_LOOKUP' };
class FreeDeviceFinder {
/**
* @param {import('../../DeviceRegistry')} deviceRegistry
*/
constructor(deviceRegistry) {
this.deviceRegistry = deviceRegistry;
}
/**
* @param {DeviceHandle[]} candidates
* @param {string} deviceQuery
* @returns {Promise<import('../../../common/drivers/android/tools/EmulatorHandle') | null>}
*/
async findFreeDevice(candidates, deviceQuery) {
const takenDevices = this.deviceRegistry.getTakenDevicesSync();
for (const candidate of candidates) {
if (await this._isDeviceFreeAndMatching(takenDevices, candidate, deviceQuery)) {
// @ts-ignore
return candidate;
}
}
return null;
}
/**
* @private
*/
async _isDeviceFreeAndMatching(takenDevices, candidate, deviceQuery) {
const { adbName } = candidate;
const isTaken = takenDevices.includes(adbName);
if (isTaken) {
log.debug(DEVICE_LOOKUP, `Device ${adbName} is already taken, skipping...`);
return false;
}
const isOffline = candidate.status === 'offline';
if (isOffline) {
log.debug(DEVICE_LOOKUP, `Device ${adbName} is offline, skipping...`);
return false;
}
const isMatching = await this._isDeviceMatching(candidate, deviceQuery);
if (!isMatching) {
log.debug(DEVICE_LOOKUP, `Device ${adbName} does not match "${deviceQuery}"`);
return false;
}
log.debug(DEVICE_LOOKUP, `Found a matching & free device ${candidate.adbName}`);
return true;
}
/**
* @protected
*/
async _isDeviceMatching(candidate, deviceQuery) {
return RegExp(deviceQuery).test(candidate.adbName);
}
}
module.exports = FreeDeviceFinder;