-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnect.py
76 lines (57 loc) · 2.73 KB
/
connect.py
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
71
72
73
74
75
76
import os
import socket
from singleton import Singleton
class Connect(metaclass=Singleton):
"""CONNECT TO ANDROID!
Use this class to connect to your android.
"""
def __init__(self):
self.port = 15831
self.CMD_EXTRA_OPTS = ''
self.CMD_START_SERVICE = 'adb {extra} shell am broadcast -a CONNECT_SERVICE_START '.format(extra=self.CMD_EXTRA_OPTS)
self.CMD_STOP_SERVICE = 'adb {extra} shell am broadcast -a CONNECT_SERVICE_STOP'.format(extra=self.CMD_EXTRA_OPTS)
self.CMD_PORT_FORWARD = 'adb {extra} forward tcp:{port} tcp:{port}'.format(extra=self.CMD_EXTRA_OPTS, port=self.port)
self.CMD_LIST_DEVICES = 'adb devices'
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def updateCmd(self):
self.CMD_START_SERVICE = 'adb {extra} shell am broadcast -a CONNECT_SERVICE_START '.format(extra=self.CMD_EXTRA_OPTS)
self.CMD_STOP_SERVICE = 'adb {extra} shell am broadcast -a CONNECT_SERVICE_STOP'.format(extra=self.CMD_EXTRA_OPTS)
self.CMD_PORT_FORWARD = 'adb {extra} forward tcp:{port} tcp:{port}'.format(extra=self.CMD_EXTRA_OPTS, port=self.port)
def startConnect(self):
while os.system(self.CMD_START_SERVICE) != 0:
os.system(self.CMD_LIST_DEVICES)
print('''Use d/e/s to specify a device:
d - directs command to the only connected USB device
e - directs command to the only running emulator
s <specific device> - directs command to the device or emulator with the given
''')
opts=input("Bronzer-SpecifyDevice>> ")
self.CMD_EXTRA_OPTS = '-' + opts
self.updateCmd()
# print(self.CMD_START_SERVICE)
while os.system(self.CMD_PORT_FORWARD.format(port=self.port)) != 0:
print("Current port {} is occupied, choose another port".format())
self.port=input("Bronzer-ChoosePort>> ")
self.updateCmd()
self.socket.connect(('127.0.0.1', self.port))
def stopConnect(self):
os.system(self.CMD_STOP_SERVICE)
self.socket.close()
"""Retrive message from android
When you want to know whether android has sent something to you, use this.
Returns:
A string comes from android.
If android doesn't send anything to you, return None.
"""
def retriveMsg(self):
data = self.socket.recv(40960)
return bytes.decode(data)
"""Send command to android and retrive the response
Args:
cmd: Just a command.
Returns:
A string that android answers to the command.
"""
def sendCmd(self, cmd):
self.socket.sendall(str.encode(cmd))
return self.retriveMsg()