Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
S2-group
GitHub Repository: S2-group/android-runner
Path: blob/master/AndroidRunner/USBHandler.py
629 views
1
import shlex
2
import subprocess
3
from .util import ConfigError
4
5
class USBHandler(object):
6
USB_COMMAND_TIMEOUT_SECONDS = 5
7
8
def __init__(self, usb_handler_config):
9
""" Inits an USBHandler instance.
10
11
Parameters
12
----------
13
usb_handler_config : dict
14
Dictionary containing the keys enable_command, disable_command
15
with the enable and disable commands as values, respectively.
16
"""
17
self._usb_enabled = True
18
19
if usb_handler_config == None:
20
self.usb_enable_command = None
21
self.usb_disable_command = None
22
self._usb_enabled = None
23
return
24
25
if usb_handler_config.get("enable_command", None) == None:
26
raise ConfigError("Please provide an enable_command for the usb_handler.")
27
28
if usb_handler_config.get("disable_command", None) == None:
29
raise ConfigError("Please provide an disable_command for the usb_handler.")
30
31
self.usb_enable_command = usb_handler_config["enable_command"]
32
self.usb_disable_command = usb_handler_config["disable_command"]
33
34
35
def enable_usb(self):
36
""" Enables the USB port(s) is non-empty usb_handler_config is given when instantiating the class.
37
38
Please note that Android Runner also calls the device.unplug() at the beginning
39
of the experiment and only calls device.plug() at the end of the experiment.
40
This only mocks the battery status (so it looks like its unplugged) but it does
41
NOT actually stop charging the device through USB.
42
Please take this into account when it seems like enabling the
43
USB port(s) does not seem to work ;).
44
45
"""
46
# Check first whether USB port(s) are "really" disabled otherwise the call in Experiment.cleanup()
47
# can result in disabled ports when using same enable and disable command.
48
if self._usb_enabled == False:
49
self._run_command(self.usb_enable_command)
50
self._usb_enabled = True
51
52
def disable_usb(self):
53
""" Disables the USB port(s) if non-empty usb_handler_config is given when instantiating the class."""
54
if self._usb_enabled == True:
55
self._run_command(self.usb_disable_command)
56
self._usb_enabled = False
57
58
def _run_command(self, command):
59
""" Runs given command
60
61
Parameters
62
----------
63
command : string
64
Command that needs to be run.
65
"""
66
if command == None:
67
return
68
69
proc = subprocess.Popen(shlex.split(command), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
70
71
try:
72
(stdout, stderr) = proc.communicate(timeout=USBHandler.USB_COMMAND_TIMEOUT_SECONDS)
73
except subprocess.TimeoutExpired:
74
raise USBHandlerException("TimeOutError while executing USB command.")
75
76
if stderr:
77
err = stderr.decode("ascii")
78
raise USBHandlerException(f"Could not execute USB command: {err}")
79
80
class USBHandlerException(Exception):
81
pass
82