示例#1
0
def connect(deviceid):
    try:
        cnx = initmysql()
        cursor = mysqlCursor(cnx)
        query = execQuery(
            cursor,
            "SELECT port,name FROM lords.devices where id=" + str(deviceid))
        field_name = [field[0] for field in query.description]
        result_set = query.fetchone()
        if result_set != None:
            row = dict(zip(field_name, result_set))
            portNo = int(row['port'])
            emulatorname = row['name']
        else:
            portNo = 5037
        print("name ", emulatorname)
        adb = Client(host='127.0.0.1', port=portNo)
        devices = adb.devices()
        if len(devices) == 0:
            print('no device attached')
            quit()
        device = adb.device(emulatorname)
        return device
    except ():
        quit()
示例#2
0
    def tryConnect(self) -> bool:
        if self.connected and self.getDeviceSerialNo() is not None:
            return True
        self._changeConnectedState(False)
        self.checkingConnectionChange(True)

        adb = AdbClient(host="127.0.0.1", port=5037)
        devices = adb.devices()

        if len(devices) == 0:
            logger.debug(
                "No device attached. Restarting adb-server and retrying...")
            check_call(["adb", "kill-server"], stdout=DEVNULL, stderr=STDOUT)
            check_call(["adb", "start-server"], stdout=DEVNULL, stderr=STDOUT)

        else:
            self._client = adb
            try:
                self.my_device = devices[0]
                self._changeConnectedState(True)
                logger.info(f"Connected to device {self._host}:{self._port}")
            except RuntimeError:
                self._changeConnectedState(True)
                logger.info("Unable to connect to device")

        self.checkingConnectionChange(False)

        return self.connected
示例#3
0
    def start_server(self):
        """
        Start ADB server
        """
        try:
            _adb_kill_server()
            _adb_start_server()
            client = AdbClient(host=self._host, port=self._port)

            if (self._serial or "") == "":
                devices = client.devices()
                if len(devices) == 1:
                    self.device = devices[0]
                elif len(devices) > 1:
                    raise DeviceNotProvidedException()
                else:
                    raise DeviceNotFoundException()
            else:
                self.device = client.device(self._serial)

            self.state = ADBServerState.OPENED
            logger.debug("ADB server started successfully.")
        except Exception as ex:
            _adb_kill_server()
            logger.debug("ADB server has failed to start.")
            self.state = ADBServerState.CLOSED

            raise ex
示例#4
0
class adb():
    def __init__(self, path: str) -> None:
        self.path = path ##
        self.adb_exe = '{}\\platform-tools\\adb.exe'.format(self.path)
    
    def connect_to_BS(self, ip: str, port: int) -> None:
        '''
        待測試 => 重開機直接執行
        '''
        self.client = AdbClient(host="127.0.0.1", port=5037)
        try:
            self.client.remote_connect(ip, port)
        except:
            subprocess.Popen('{} start-server'.format(self.adb_exe), stdout=subprocess.PIPE).stdout.read()
        print('Connect success!')

    def list_devices(self) -> None:
        devices = self.client.devices()
        print('List of devices attached:')
        for device in devices:
            print('    {}'.format(device.serial))
    
    def tap(self, device, x: str, y: str) -> None:
        device.shell('input tap {} {}'.format(x, y))

    def get_device(self, serial: str):
        return self.client.device(serial)

    def screencap(self, device):
        image_bytes = device.screencap()
        img = cv2.imdecode(np.frombuffer(image_bytes, dtype='uint8'), cv2.IMREAD_COLOR)
        return img
示例#5
0
def check_device_exist(udid):
    client = AdbClient(host="127.0.0.1", port=5037)
    devices = client.devices()
    for device in devices:
        if device.get_serial_no() == udid:
            return udid
    return None
示例#6
0
class Adb:
    def __init__(self, host='127.0.0.1', port=5037):
        self.client = PPADBClient(host, port)

    def connect_to_device(self, host='127.0.0.1', port=5555):
        adb_path = resource_path(FilePaths.ADB_EXE_PATH.value)
        cmd = build_command(adb_path, 'connect', "{}:{}".format(host, port))
        ret = subprocess.check_output(cmd,
                                      shell=True,
                                      stderr=subprocess.PIPE,
                                      encoding="utf-8",
                                      timeout=2)
        return self.get_device(host, port)

    def get_client_devices(self):
        return self.client.devices()

    def get_device(self, host='127.0.0.1', port=5555):
        device = self.client.device('{}:{}'.format(host, port))
        try:
            if device is None:
                self.connect_to_device(host, port)
                device = self.client.device('{}:{}'.format(host, port))
        except Exception as e:
            traceback.print_exc()
            return None
        return device
示例#7
0
def connect():
    adb = Client(host="127.0.0.1", port=5037)
    devices = adb.devices()
    if len(devices) == 0:
        print("No device found!")
        quit(1)
    return devices[0]
示例#8
0
 def __init__(self):
     self.log = MyLogger('ADB', LOG_LEVEL=logging.INFO)
     client = Client(host='127.0.0.1', port=5037)
     self.log.debug(client.version())
     devices = client.devices()
     if len(devices) == 0:
         self.log.debug("no devices")
         quit()
     self.device = devices[0]
     self.log.debug(f'updating info for {self.device}')
     number = 5
     touch_id = 0
     lines = self.device.shell('getevent -p').split("\n")
     for line in lines:
         if "/dev/input" in line:
             number = line[-1]
         if "Touch" in line:
             touch_id = number
             self.touch = f"sendevent /dev/input/event{number}"
         if "max" in line and "ABS" in line and number == touch_id:
             values = line.split(', ')
             for value in values:
                 if "max" in value:
                     self.max = int(value[4:])
                     self.log.debug(f"found max: {self.max}")
示例#9
0
class SSMAndroidDevices:
    """
        AndroidDevices class
            this is collection of devices found by adb executable
    """
    def __init__(self, host: object, port: int) -> object:
        self.client = AdbClient(host, port)
        self.devices = self.client.devices()
        if self.devices.__len__() <= 0:
            logging.critical("There are no devices connected")
            self.num_of_device = 0
            exit()
        else:
            logging.info("There are " + self.devices.__len__().__str__() +
                         " devices connected")
            self.num_of_device = self.devices.__len__()
        return

    def print_devices(self):
        for device in self.devices:
            print("Serial: " + device.serial)
            # print("State: " + device.serial.get_state)
            print(device.get_serial_no())
            print(device.get_device_path())
            print(device.get_state())
            # below require package name
            # print(device.get_meminfo())
            print(device.get_top_activities())
            print(" ")
            for activity in device.get_top_activities():
                print(activity.activity)
                print(activity.package)
                print(activity.pid)
                print(" ")
        return
示例#10
0
def connect_device():
    adb = Client(host='127.0.0.1',port=5037)
    devices = adb.devices()
    if len(devices) == 0:
        print("No Devices Attached")
        quit()
    return devices[0]
def transfer_all(logger: Logger):
    music_path = Path.cwd().parents[0] / "music"
    playlists_path = Path.cwd().parents[0] / "playlists"

    # Default is "127.0.0.1" and 5037
    client = AdbClient(host="127.0.0.1", port=5037)
    if len(client.devices()) == 0:
        logger.info("No phone connected! Can't copy files.")
        return

    devices: List[Device] = client.devices()

    device = devices[0]

    transferred_count = 0

    all_music: List[Path] = []
    for dirname, dirnames, filenames in os.walk(music_path):
        for filename in filenames:
            all_music.append(Path(os.path.join(dirname, filename)))

    for file in all_music:
        file_name = file.name
        file_parent = file.parents[0].name
        if file.suffix == ".jpg":
            android_path = f"/storage/emulated/0/Music/music/{file_parent}/folder{file.suffix}"
        else:
            android_path = f"/storage/emulated/0/Music/music/{file_parent}/{file_name}"
        exists = "No such file or directory" not in device.shell(
            f"ls \"{android_path}\"")
        if not exists:
            device.push(file, android_path)
            transferred_count += 1

    all_playlists: List[Path] = []
    for dirname, dirnames, filenames in os.walk(playlists_path):
        for filename in filenames:
            all_playlists.append(Path(os.path.join(dirname, filename)))

    for file in all_playlists:
        file_name = file.name
        android_path = f"/storage/emulated/0/Music/playlists/{file_name}"

        device.push(file, android_path)
        transferred_count += 1

    logger.info(f"Copied {transferred_count} files to your Android!")
示例#12
0
async def main(argv):
    tasks = []
    config = Object()
    config.width = 1
    config.height = 1
    client = AdbClient(host="127.0.0.1", port=5037)
    devices = client.devices()
    if len(devices) == 0:
        print("no device detected!")
        exit(1)
        return
    elif len(devices) == 1:
        device = devices[0]
    else:
        # print("multiple device detected, chose one")
        index = 0
        for device in devices:
            print(f"{index}: {device.serial}")
        index = int(
            input("multiple device detected, chose one (index number): "))
        device = devices[index]
    config.device = device

    if argv[1].endswith(".yaml") or argv[1].endswith(".yml"):
        config_text = open(argv[1]).read()
        argv = argv[1:]
    else:
        config_text = open("android_clicker.yaml").read()
    config_data = yaml.safe_load(config_text)
    print(config_data)

    if "screen" in config_data:
        screen = config_data["screen"]
        screen_cap = device.screencap()
        if len(screen_cap) != 0:
            img = cv2.imdecode(np.frombuffer(screen_cap, np.uint8),
                               cv2.IMREAD_COLOR)
            sp = img.shape
            height = sp[0]
            width = sp[1]
            print(f'screen width: {width:d}, height: {height:d}')
            if "width" in screen:
                config.width = width / int(screen["width"])
            if "height" in screen:
                config.height = height / int(screen["height"])

    available_motions = argv[1:]

    if "motions" in config_data:
        motions = config_data["motions"]
        if len(available_motions) != 0:
            motions = filter(
                lambda m: "name" in m and m["name"] in available_motions,
                motions)
        for motion in motions:
            task = asyncio.create_task(loop(motion, device, config))
            tasks.append(task)
    for task in tasks:
        await task
示例#13
0
    def __init__(self):
        client = AdbClient(host="127.0.0.1", port=5037)
        devices = client.devices()
        if len(devices) == 0:
            raise Exception('There is no ADB devices')

        self.device = devices[0]
        self.app_name = 'com.firsttouchgames.smp'
示例#14
0
文件: util.py 项目: DaveBoy/kog-money
def initDevice():
    os.system('taskkill /f /im %s' % 'cmd.exe')
    os.system('taskkill /f /im %s' % 'adb.exe')

    os.system("adb kill-server")
    os.system("adb start-server")
    global client
    client = AdbClient(host="127.0.0.1", port=5037)
    global device
    device = client.devices()[0]
示例#15
0
def startInjection():
    codes = scrapeCodes()
    client = AdbClient()

    device = None
    if len(codes) > 0:
        if len(client.devices()) == 1:
            device = client.devices()[0]

    if device is not None:
        box_input_location = getLocationFromBackground(
            image_location="mobbox.png", update_background=True, device=device)
        inv_input_location = getLocationFromBackground(
            image_location="invitebox.png")

        remove_input_location = None
        codes_entered = 0
        if box_input_location is not None and inv_input_location is not None:
            for code in codes:
                print("Currently entered {} codes".format(codes_entered))
                # select the box & input text
                device.input_tap(*box_input_location)
                device.input_text(code)
                time.sleep(1)

                # select the invite location
                device.input_tap(0, 0)
                device.input_tap(*inv_input_location)
                time.sleep(1)

                # (get remove input location if not set &) remove the input.
                if remove_input_location is None:
                    remove_input_location = getLocationFromBackground(
                        "removeinput.png",
                        update_background=True,
                        device=device)

                device.input_tap(*remove_input_location)
                time.sleep(0.2)
                device.input_tap(0, 0)
                time.sleep(0.2)
                codes_entered += 1
示例#16
0
def get_device_udid(number: int):
    client = AdbClient(host="127.0.0.1", port=5037)
    devices = client.devices()
    if len(devices) > number:
        return devices[number].get_serial_no()
    else:
        new_number = number - (number // len(devices)) * len(devices)
        logger.log_warn(
            f'You choose device number {number + 1} but there are only {len(devices)} connected. '
            f'Will use device number {new_number + 1} instead',
            jump_line=True)
        return devices[new_number].get_serial_no()
示例#17
0
def init():
    os.system('adb devices -l')
    adb = Client(host='127.0.0.1', port=5037)

    devices = adb.devices()

    if len(devices) == 0:
        print('no devices found')
        quit()

    device = devices[0]
    return device
示例#18
0
def check_device():
    global current_device
    adb = Client(host='127.0.0.1', port=5037)
    devices = adb.devices()
    if len(devices) == 0:
        print('no device attached')
        print('exit')
        quit()
    else:
        current_device = devices[0]
        print(f"device found {current_device.serial} ")
        create_folder(folder)
        start()
def get_devices():
    for attempt in range(2):
        try:
            client = AdbClient(host="127.0.0.1", port=5037)
            client.version()  # a random call to check if adb server is up
        except Exception as err:
            eprint(str(err))
            eprint("⚡ Starting ADB server...")
            subprocess.run(["adb", "start-server"])

    devices = client.devices()
    if len(devices) == 0:
        eprint("⚠️  no devices connected!")
    return devices
示例#20
0
class ADBControl:
    def __init__(self, config):

        self._adb_server_host = config.get("adb_server_host", "127.0.0.1")
        self._adb_server_port = config.get("adb_server_port", 5037)
        self._adb_device_number = config.get("adb_device_number", 0)

        self._client = AdbClient(host=self._adb_server_host,
                                 port=self._adb_server_port)
        self._device = self._client.devices()[self._adb_device_number]

    def _adb_shell(self, command):

        self._device.shell(command)

    def take_photo(self):

        self._adb_shell("input keyevent KEYCODE_CAMERA")
示例#21
0
def get_device(proxy_port):
    client = AdbClient(host="localhost", port=5037)
    if client.remote_connect("backend", proxy_port):
        device = client.devices()[0]
        print("Using device : %s" % device.serial)
        waiting = True
        while waiting:
            try:
                whoami = device.shell('whoami')
                # This will always be root on an eng build
                if 'root' not in whoami:
                    print("Unlikely this will work... : %s" % whoami)
                else:
                    waiting = False
            except Exception as e:
                print("Hit exception waiting, will retry in 1 second... ", e)
                time.sleep(1)
        return device
示例#22
0
class AdbManager(Thread):
    def __init__(self):
        super().__init__()
        self.adb_client = AdbClient(host="127.0.0.1", port=5037)
        self.logcats = []
        self.start()

    def get_current_devices(self):
        devices = self.adb_client.devices()
        return devices

    def get_logcat(self, device, callback=None):
        logcat_manager = LogcatManager(device, callback)
        logcat_manager.start()

        self.logcats.append(logcat_manager)

    def stop_logcat(self, item):
        logcat_manager = self.logcats[item]
        logcat_manager.stop_logcat()

        self.logcats.remove(logcat_manager)

    def get_installed_packages(self, device):
        installed_packages = list(
            map(lambda x: x.replace("package:", ""),
                device.shell("cmd package list packages -3").split("\n")))
        return installed_packages

    def execute(self, device, command):
        device.shell("su -c '{}'".format(command), handler=self._print)

    @staticmethod
    def _print(connection):
        while True:
            data = connection.read(1024)
            if not data:
                break
            print(data.decode('utf-8'))

        connection.close()
def main():
    logging.info('before adb')

    adb = Client(host='127.0.0.1', port=5037)
    devices = adb.devices()
    logging.info('after adb')

    if len(devices) == 0:
        print('no device attached')
        quit()

    device = devices[0]

    logging.info('before adb swipe')
    device.shell('input touchscreen swipe 500 500 500 500 10')
    logging.info('after adb swipe')

    logging.info('before adb swipe2')
    device.shell('input touchscreen swipe 200 200 200 200 10')
    logging.info('after adb swipe2')

    logging.info('before touch')
示例#24
0
    def main():
        client = AdbClient()
        devices = client.devices()

        if len(devices) > 0:
            device = devices[0]

            viewer = Viewer(device)
            if not viewer.turn_on():
                error('hierarchy viewer turn on fail!')

            activities = viewer.list_activities()
            for activity in activities:
                print(activity.hashcode, activity.name)

                widget = viewer.dump_widgets(activity)
                if widget is not None:
                    # print(str(widget))
                    filepath = activity.name + '_' + widget.name
                    viewer.capture_widget(activity.hashcode, widget, filepath)
                    print('write file ', filepath)

            viewer.turn_off()
示例#25
0
####################
# IMPORTS
####################
from ppadb.client import Client
import numpy as np
import TextPositions

####################
# SETTING UP
####################
adb = Client(host='127.0.0.1', port=5037)
devices = adb.devices()
device = devices[0]

####################
# MAIN
####################
def PrintText(text,start_x,start_y,font_size=80):
    x_off = 0
    y_off = 0
    for c in range(len(text)):
        if x_off + (TextPositions.text_positions[text[c]]['Size'][0]*font_size) > 800:
            x_off = 0
            y_off += (1*font_size)
        for elm in TextPositions.text_positions[text[c]]["Vectors"]:
            for i in range(len(elm)):
                x1 = start_x + (elm[i-1][0]*font_size) + x_off
                y1 = start_y - (elm[i-1][1]*font_size) + y_off
                x2 = start_x + (elm[i  ][0]*font_size) + x_off
                y2 = start_y - (elm[i  ][1]*font_size) + y_off
                dist = numpy.linalg.norm(np.array([x1,y1]) - np.array([x2,y2]))
from ppadb.client import Client as AdbClient
import time

# Default is "127.0.0.1" and 5037
client = AdbClient(host="127.0.0.1", port=5037)
device = client.devices()[0]

# Launch whatsapp using adb
device.shell("am start -n com.whatsapp/com.whatsapp.Main")

position = 670
count = 0
for i in range(8):
    print(i + 1)
    while (position <= 2250):
        # Press new message
        device.shell("input touchscreen tap 1000 2200")

        for _ in range(i):
            # Scroll the screen by screen height amount (or a little less).
            # Scrolling i times because i number of screens have already been done.
            device.shell("input touchscreen swipe 500 2200 500 200 2000")

            # Tuning left.

        # Select chat
        device.shell(f"input touchscreen tap 500 {position}")

        # Position for next chat
        position += 170
示例#27
0
class ADBConnect(object):
    def __init__(self, args):
        self._args = args
        self._useadb = args.use_adb
        self._client = None
        if self._useadb:
            try:
                from ppadb.client import Client as AdbClient
            except ImportError:
                try:
                    from adb.client import Client as AdbClient
                except ImportError:
                    pass
            self.check_adblib = 'adb.client' in sys.modules or 'ppadb.client' in sys.modules
            if not self.check_adblib:
                logger.warning("Could not find pure-python-adb library.  If you are not using ADB you can ignore this")
                self._useadb = False
            else:
                self._client = AdbClient(
                    host=self._args.adb_server_ip, port=self._args.adb_server_port)

    def check_adb_status(self, adb):
        if not self._useadb:
            return None
        try:
            if self._client.device(adb) is not None:
                self._client.device(adb).shell('echo checkadb')
                return True
        except RuntimeError:
            logger.exception('MADmin: Exception occurred while checking adb status ({}).', adb)
        return None

    def return_adb_devices(self):
        if not self._useadb:
            return []
        try:
            return self._client.devices()
        except Exception as e:
            logger.exception('MADmin: Exception occurred while getting adb clients: {}.', e)
        return []

    def send_shell_command(self, adb, origin, command):
        origin_logger = get_origin_logger(logger, origin=origin)
        try:
            device = self._client.device(adb)
            if device is not None:
                origin_logger.info('MADmin: Using ADB shell command')
                device.shell(command)
                return True
        except Exception as e:
            origin_logger.exception('MADmin: Exception occurred while sending shell command: {}.', e)
        return False

    def make_screenshot(self, adb, origin, extenstion):
        origin_logger = get_origin_logger(logger, origin=origin)
        try:
            device = self._client.device(adb)
            if device is not None:
                origin_logger.info('MADmin: Using ADB')
                result = device.screencap()
                # TODO: adjust with devicesettings
                with open(os.path.join(self._args.temp_path, 'screenshot_%s.png' % str(origin)), "wb") as fp:
                    fp.write(result)
                if extenstion == "jpg":
                    pngtojpg(os.path.join(self._args.temp_path, 'screenshot_%s.png' % str(origin)))
                return True
        except Exception as e:
            origin_logger.exception('MADmin: Exception occurred while making screenshot: {}.', e)
        return False

    def make_screenclick(self, adb, origin, position_x, position_y):
        origin_logger = get_origin_logger(logger, origin=origin)
        try:
            device = self._client.device(adb)
            if device is not None:
                device.shell("input tap " + str(position_x) + " " + str(position_y))
                origin_logger.info('MADMin ADB Click x:{} y:{}', position_x, position_y)
                time.sleep(1)
                return True
        except Exception as e:
            origin_logger.exception('MADmin: Exception occurred while making screenclick: {}.', e)
        return False

    def make_screenswipe(self, adb, origin, position_x, position_y, swipe_x, swipe_y):
        origin_logger = get_origin_logger(logger, origin=origin)
        try:
            device = self._client.device(adb)
            if device is not None:
                device.shell("input swipe " + str(position_x) + " " +
                             str(position_y) + " " + str(swipe_x) + " " + str(swipe_y) + " 100")
                origin_logger.info('MADMin ADB Swipe x:{} y:{} xe:{} ye:{}', position_x, position_y, swipe_x, swipe_y)
                time.sleep(1)
                return True
        except Exception as e:
            origin_logger.exception('MADmin: Exception occurred while making screenswipe: {}.', e)
        return False

    def push_file(self, adb, origin, filename):
        origin_logger = get_origin_logger(logger, origin=origin)
        try:
            device = self._client.device(adb)
            if device is not None:
                device.shell("adb push  " + str(filename) + " /sdcard/Download")
                origin_logger.info('MADMin ADB Push File {}', filename)
                time.sleep(1)
                return True
        except Exception as e:
            origin_logger.exception('MADmin: Exception occurred while pushing file: {}.', e)
        return False
示例#28
0
 def testDump(self, window):
     client = AdbClient(host="127.0.0.1", port=5037)
     dev = client.devices()
     dev2 = client.device("YT910815C7")
     self.outText.delete('1.0', END)
     self.outText.insert(END, dev2.shell("echo test2"))
示例#29
0
class FireTV:
    """Represents an Amazon Fire TV device."""
    def __init__(self,
                 host,
                 port=5555,
                 adb_server_ip="127.0.0.1",
                 adb_server_port=5037):
        """Initialize FireTV object.

        :param host: Host in format <address>:port.
        :param adbkey: The path to the "adbkey" file
        :param adb_server_ip: the IP address for the ADB server
        :param adb_server_port: the port for the ADB server
        """
        self.host = host
        self.port = port
        self.adb_server_port = adb_server_port
        self.adb_server_ip = adb_server_ip

        # keep track of whether the ADB connection is intact
        self._available = False

        # use a lock to make sure that ADB commands don't overlap
        self._adb_lock = threading.Lock()

        # the attributes used for sending ADB commands; filled in in `self.connect()`
        self._adb = None  # python-adb
        self._adb_client = None  # pure-python-adb
        self._adb_device = None  # pure-python-adb && adb_shell

        # pure-python-adb
        self.adb_shell = self._adb_shell_pure_python_adb
        self.adb_streaming_shell = self._adb_streaming_shell_pure_python_adb

        # establish the ADB connection
        self.connect()

    # ======================================================================= #
    #                                                                         #
    #                               ADB methods                               #
    #                                                                         #
    # ======================================================================= #
    def _adb_shell_adb_shell(self, cmd):
        if not self.available:
            return None

        if self._adb_lock.acquire(**LOCK_KWARGS):
            try:
                return self._adb_device.shell(cmd)
            finally:
                self._adb_lock.release()

    def _adb_shell_python_adb(self, cmd):
        if not self.available:
            return None

        if self._adb_lock.acquire(**LOCK_KWARGS):
            try:
                return self._adb.Shell(cmd)
            finally:
                self._adb_lock.release()

    def _adb_shell_pure_python_adb(self, cmd):
        if not self._available:
            return None

        if self._adb_lock.acquire(**LOCK_KWARGS):
            try:
                return self._adb_device.shell(cmd)
            finally:
                self._adb_lock.release()

    def _adb_streaming_shell_adb_shell(self, cmd):
        if not self.available:
            return []

        if self._adb_lock.acquire(**LOCK_KWARGS):
            try:
                return self._adb_device.shell(cmd)
            finally:
                self._adb_lock.release()

    def _adb_streaming_shell_python_adb(self, cmd):
        if not self.available:
            return []

        if self._adb_lock.acquire(**LOCK_KWARGS):
            try:
                return self._adb.StreamingShell(cmd)
            finally:
                self._adb_lock.release()

    def _adb_streaming_shell_pure_python_adb(self, cmd):
        if not self._available:
            return None

        # this is not yet implemented
        if self._adb_lock.acquire(**LOCK_KWARGS):
            try:
                return []
            finally:
                self._adb_lock.release()

    def _dump(self, service, grep=None):
        """Perform a service dump.

        :param service: Service to dump.
        :param grep: Grep for this string.
        :returns: Dump, optionally grepped.
        """
        if grep:
            return self.adb_shell('dumpsys {0} | grep "{1}"'.format(
                service, grep))
        return self.adb_shell('dumpsys {0}'.format(service))

    def _dump_has(self, service, grep, search):
        """Check if a dump has particular content.

        :param service: Service to dump.
        :param grep: Grep for this string.
        :param search: Check for this substring.
        :returns: Found or not.
        """
        dump_grep = self._dump(service, grep=grep)

        if not dump_grep:
            return False

        return dump_grep.strip().find(search) > -1

    def _key(self, key):
        """Send a key event to device.

        :param key: Key constant.
        """
        self.adb_shell('input keyevent {0}'.format(key))

    def _keyboard(self, literal):
        """Send text to device

        :param key: text string to send.
        """
        self.adb_shell(f'input text "{literal}"')

    def _ps(self, search=''):
        """Perform a ps command with optional filtering.

        :param search: Check for this substring.
        :returns: List of matching fields
        """
        if not self.available:
            return
        result = []
        ps = self.adb_streaming_shell('ps')
        try:
            for bad_line in ps:
                # The splitting of the StreamingShell doesn't always work
                # this is to ensure that we get only one line
                for line in bad_line.splitlines():
                    if search in line:
                        result.append(line.strip().rsplit(' ', 1)[-1])
            return result
        except InvalidChecksumError as e:
            print(e)
            self.connect()
            raise IOError

    def _send_intent(self, pkg, intent, count=1):

        cmd = 'monkey -p {} -c {} {}; echo $?'.format(pkg, intent, count)
        logging.debug("Sending an intent %s to %s (count: %s)", intent, pkg,
                      count)

        # adb shell outputs in weird format, so we cut it into lines,
        # separate the retcode and return info to the user
        res = self.adb_shell(cmd)
        if res is None:
            return {}

        res = res.strip().split("\r\n")
        retcode = res[-1]
        output = "\n".join(res[:-1])

        return {"retcode": retcode, "output": output}

    def connect(self, always_log_errors=True):
        """Connect to an Amazon Fire TV device.

        Will attempt to establish ADB connection to the given host.
        Failure sets state to UNKNOWN and disables sending actions.

        :returns: True if successful, False otherwise
        """
        self._adb_lock.acquire(**LOCK_KWARGS)
        try:
            # pure-python-adb
            try:
                self._adb_client = AdbClient()
                self._adb_client.remote_connect(self.host, self.port)
                print(self._adb_client.devices())
                self._adb_device = self._adb_client.device(
                    f"{self.host}:{self.port}")
                self._available = bool(self._adb_device)
            except:
                traceback.print_exc()
                self._available = False

            finally:
                return self._available

        finally:
            self._adb_lock.release()

    # ======================================================================= #
    #                                                                         #
    #                          Home Assistant Update                          #
    #                                                                         #
    # ======================================================================= #
    def update(self, get_running_apps=True):
        """Get the state of the device, the current app, and the running apps.

        :param get_running_apps: whether or not to get the ``running_apps`` property
        :return state: the state of the device
        :return current_app: the current app
        :return running_apps: the running apps
        """
        # The `screen_on`, `awake`, `wake_lock_size`, `current_app`, and `running_apps` properties.
        screen_on, awake, wake_lock_size, _current_app, running_apps = self.get_properties(
            get_running_apps=get_running_apps, lazy=True)

        # Check if device is off.
        if not screen_on:
            state = STATE_OFF
            current_app = None
            running_apps = None

        # Check if screen saver is on.
        elif not awake:
            state = STATE_IDLE
            current_app = None
            running_apps = None

        else:
            # Get the current app.
            if isinstance(_current_app, dict) and 'package' in _current_app:
                current_app = _current_app['package']
            else:
                current_app = None

            # Get the running apps.
            if running_apps is None and current_app:
                running_apps = [current_app]

            # Get the state.
            # TODO: determine the state differently based on the `current_app`.
            if current_app in [PACKAGE_LAUNCHER, PACKAGE_SETTINGS]:
                state = STATE_STANDBY

            # Amazon Video
            elif current_app == AMAZON_VIDEO:
                if wake_lock_size == 5:
                    state = STATE_PLAYING
                else:
                    # wake_lock_size == 2
                    state = STATE_PAUSED

            # Netflix
            elif current_app == NETFLIX:
                if wake_lock_size > 3:
                    state = STATE_PLAYING
                else:
                    state = STATE_PAUSED

            # Check if `wake_lock_size` is 1 (device is playing).
            elif wake_lock_size == 1:
                state = STATE_PLAYING

            # Otherwise, device is paused.
            else:
                state = STATE_PAUSED

        return state, current_app, running_apps

    # ======================================================================= #
    #                                                                         #
    #                              App methods                                #
    #                                                                         #
    # ======================================================================= #
    def app_state(self, app):
        """Informs if application is running."""
        if not self.available or not self.screen_on:
            return STATE_OFF
        if self.current_app["package"] == app:
            return STATE_ON
        return STATE_OFF

    def launch_app(self, app):
        """Launch an app."""
        return self._send_intent(app, INTENT_LAUNCH)

    def stop_app(self, app):
        """Stop an app."""
        return self.adb_shell("am force-stop {0}".format(app))

    # ======================================================================= #
    #                                                                         #
    #                               properties                                #
    #                                                                         #
    # ======================================================================= #
    @property
    def state(self):
        """Compute and return the device state.

        :returns: Device state.
        """
        # Check if device is disconnected.
        if not self.available:
            return STATE_UNKNOWN
        # Check if device is off.
        if not self.screen_on:
            return STATE_OFF
        # Check if screen saver is on.
        if not self.awake:
            return STATE_IDLE
        # Check if the launcher is active.
        if self.launcher or self.settings:
            return STATE_STANDBY
        # Check for a wake lock (device is playing).
        if self.wake_lock:
            return STATE_PLAYING
        # Otherwise, device is paused.
        return STATE_PAUSED

    @property
    def available(self):
        """Check whether the ADB connection is intact."""

        if USE_ADB_SHELL:
            # adb_shell
            if not self._adb_device:
                return False

            return self._adb_device.available

        if not self.adb_server_ip:
            # python-adb
            return bool(self._adb)

        # pure-python-adb
        try:
            # make sure the server is available
            adb_devices = self._adb_client.devices()

            # make sure the device is available
            try:
                # case 1: the device is currently available
                if any(
                    [self.host in dev.get_serial_no() for dev in adb_devices]):
                    if not self._available:
                        self._available = True
                    return True

                # case 2: the device is not currently available
                if self._available:
                    logging.error('ADB server is not connected to the device.')
                    self._available = False
                return False

            except RuntimeError:
                if self._available:
                    logging.error(
                        'ADB device is unavailable; encountered an error when searching for device.'
                    )
                    self._available = False
                return False

        except RuntimeError:
            if self._available:
                logging.error('ADB server is unavailable.')
                self._available = False
            return False

    @property
    def running_apps(self):
        """Return a list of running user applications."""
        ps = self.adb_shell(RUNNING_APPS_CMD)
        if ps:
            return [
                line.strip().rsplit(' ', 1)[-1] for line in ps.splitlines()
                if line.strip()
            ]
        return []

    @property
    def current_app(self):
        """Return the current app."""
        current_focus = self.adb_shell(CURRENT_APP_CMD)
        if current_focus is None:
            return None

        current_focus = current_focus.replace("\r", "")
        matches = WINDOW_REGEX.search(current_focus)

        # case 1: current app was successfully found
        if matches:
            (pkg, activity) = matches.group("package", "activity")
            return {"package": pkg, "activity": activity}

        # case 2: current app could not be found
        logging.warning("Couldn't get current app, reply was %s",
                        current_focus)
        return None

    @property
    def screen_on(self):
        """Check if the screen is on."""
        return self.adb_shell(SCREEN_ON_CMD + SUCCESS1_FAILURE0) == '1'

    @property
    def awake(self):
        """Check if the device is awake (screensaver is not running)."""
        return self.adb_shell(AWAKE_CMD + SUCCESS1_FAILURE0) == '1'

    @property
    def wake_lock(self):
        """Check for wake locks (device is playing)."""
        return self.adb_shell(WAKE_LOCK_CMD + SUCCESS1_FAILURE0) == '1'

    @property
    def wake_lock_size(self):
        """Get the size of the current wake lock."""
        output = self.adb_shell(WAKE_LOCK_SIZE_CMD)
        if not output:
            return None
        return int(output.split("=")[1].strip())

    @property
    def launcher(self):
        """Check if the active application is the Amazon TV launcher."""
        return self.current_app["package"] == PACKAGE_LAUNCHER

    @property
    def settings(self):
        """Check if the active application is the Amazon menu."""
        return self.current_app["package"] == PACKAGE_SETTINGS

    def get_properties(self, get_running_apps=True, lazy=False):
        """Get the ``screen_on``, ``awake``, ``wake_lock_size``, ``current_app``, and ``running_apps`` properties."""
        if get_running_apps:
            output = self.adb_shell(SCREEN_ON_CMD +
                                    (SUCCESS1 if lazy else SUCCESS1_FAILURE0) +
                                    " && " + AWAKE_CMD +
                                    (SUCCESS1 if lazy else SUCCESS1_FAILURE0) +
                                    " && " + WAKE_LOCK_SIZE_CMD + " && " +
                                    CURRENT_APP_CMD + " && " +
                                    RUNNING_APPS_CMD)
        else:
            output = self.adb_shell(SCREEN_ON_CMD +
                                    (SUCCESS1 if lazy else SUCCESS1_FAILURE0) +
                                    " && " + AWAKE_CMD +
                                    (SUCCESS1 if lazy else SUCCESS1_FAILURE0) +
                                    " && " + WAKE_LOCK_SIZE_CMD + " && " +
                                    CURRENT_APP_CMD)

        # ADB command was unsuccessful
        if output is None:
            return None, None, None, None, None

        # `screen_on` property
        if not output:
            return False, False, -1, None, None
        screen_on = output[0] == '1'

        # `awake` property
        if len(output) < 2:
            return screen_on, False, -1, None, None
        awake = output[1] == '1'

        lines = output.strip().splitlines()

        # `wake_lock_size` property
        if len(lines[0]) < 3:
            return screen_on, awake, -1, None, None
        wake_lock_size = int(lines[0].split("=")[1].strip())

        # `current_app` property
        if len(lines) < 2:
            return screen_on, awake, wake_lock_size, None, None

        matches = WINDOW_REGEX.search(lines[1])
        if matches:
            # case 1: current app was successfully found
            (pkg, activity) = matches.group("package", "activity")
            current_app = {"package": pkg, "activity": activity}
        else:
            # case 2: current app could not be found
            current_app = None

        # `running_apps` property
        if not get_running_apps or len(lines) < 3:
            return screen_on, awake, wake_lock_size, current_app, None

        running_apps = [
            line.strip().rsplit(' ', 1)[-1] for line in lines[2:]
            if line.strip()
        ]

        return screen_on, awake, wake_lock_size, current_app, running_apps

    # ======================================================================= #
    #                                                                         #
    #                           turn on/off methods                           #
    #                                                                         #
    # ======================================================================= #
    def turn_on(self):
        """Send power action if device is off."""
        self.adb_shell(SCREEN_ON_CMD +
                       " || (input keyevent {0} && input keyevent {1})".format(
                           POWER, HOME))

    def turn_off(self):
        """Send power action if device is not off."""
        self.adb_shell(SCREEN_ON_CMD + " && input keyevent {0}".format(SLEEP))

    # ======================================================================= #
    #                                                                         #
    #                      "key" methods: basic commands                      #
    #                                                                         #
    # ======================================================================= #
    def backspace(self):
        """Send backspace action."""
        self._key(DELETE)

    def search(self):
        """Send search action."""
        self._key(SEARCH)

    def info(self):
        """Send info action."""
        self._key(INFO)

    def power(self):
        """Send power action."""
        self._key(POWER)

    def sleep(self):
        """Send sleep action."""
        self._key(SLEEP)

    def home(self):
        """Send home action."""
        self._key(HOME)

    def up(self):
        """Send up action."""
        self._key(UP)

    def down(self):
        """Send down action."""
        self._key(DOWN)

    def left(self):
        """Send left action."""
        self._key(LEFT)

    def right(self):
        """Send right action."""
        self._key(RIGHT)

    def enter(self):
        """Send enter action."""
        self._key(ENTER)

    def back(self):
        """Send back action."""
        self._key(BACK)

    def menu(self):
        """Send menu action."""
        self._key(MENU)

    def volume_up(self):
        """Send volume up action."""
        self._key(VOLUME_UP)

    def volume_down(self):
        """Send volume down action."""
        self._key(VOLUME_DOWN)

    def grave(self):
        """Send backtick action."""
        self._key(GRAVE)

    def settings(self):
        """Send settings action."""
        self._key(SETTINGS)

    def backslash(self):
        """Send backslash action."""
        self._key(BACKSLASH)

    # ======================================================================= #
    #                                                                         #
    #                      "key" methods: media commands                      #
    #                                                                         #
    # ======================================================================= #
    def media_play_pause(self):
        """Send media play/pause action."""
        self._key(PLAY_PAUSE)

    def media_play(self):
        """Send media play action."""
        self._key(PLAY)

    def media_pause(self):
        """Send media pause action."""
        self._key(PAUSE)

    def media_next(self):
        """Send media next action (results in fast-forward)."""
        self._key(NEXT)

    def media_previous(self):
        """Send media previous action (results in rewind)."""
        self._key(PREVIOUS)

    def media_fast_forward(self):
        """Send media fast forward action."""
        self._key(FAST_FORWARD)

    def media_rewind(self):
        """Send media rewind action."""
        self._key(REWIND)

    def media_skip_backwards(self):
        """Send media skip backward action."""
        self._key(SKIP_BACKWARD)

    # ======================================================================= #
    #                                                                         #
    #                       "key" methods: key commands                       #
    #                                                                         #
    # ======================================================================= #
    def keyboard(self, literal):
        """Send keyboard literal keypress."""
        self._keyboard(literal)
# Necessary libraries
from ppadb.client import Client as AdbClient
import numpy as np
import cv2
import time

#Phone connection using ADB
client = AdbClient(host='127.0.0.1', port=5037)
phones = client.devices()
phone = phones[0]

#Infinite loop to the code keep running
while (1):

    # Take the phone screenshoot
    image = phone.screencap()
    with open('screenshot.png', 'wb') as fb:
        fb.write(image)

    # Return a numpy array of size (1280,720,3) with the screenshoot info in RGB
    img = cv2.imread('screenshot.png')

    # We know that in this row you can always find the black blocks of the game
    row = 900

    # A black pixel is [0 0 0] in RGB
    # BlackPixels is a numpy array with the number of black pixels in the X axis (max of 720 pixels)
    BlackPixels = np.array([])

    # Determine how many black pixels there are
    for pix, RGB in enumerate(img[row]):