Python use Mac as a mouse for Android

74 Views Asked by At

Basically I'm trying to move a mouse cursor on an android with broken screen using just USB-C cable and a Mac. The goal here is to emulate a HID device without external hardware like PyBoard or ESP32

I'm using PyUSB library

import usb.core
import usb.util
import time

def find_android_device():
    # Find the USB device of the Android phone or tablet
    dev = usb.core.find(idVendor=0x18d1, idProduct=0x4ee1)
    return dev


def send_mouse_movement(dev, dx, dy):
    # Send control transfer to simulate mouse movement
    bmRequestType = usb.util.build_request_type(usb.util.CTRL_OUT, usb.util.CTRL_TYPE_CLASS, usb.util.CTRL_RECIPIENT_INTERFACE)
    dev.ctrl_transfer(bmRequestType, 0x01, 0, 0, [dx, dy, 0, 0, 0, 0, 0, 0])

def send_mouse_command(ep, x, y, button):
    # Send a simple mouse move command in a different way
    data = [button, x, y, 0, 0]
    android_device.write(ep, data)


# Example usage
android_device = find_android_device()

if android_device is not None:
    if android_device.is_kernel_driver_active(0):
        android_device.detach_kernel_driver(0)
    android_device.set_configuration()
    cfg = android_device.get_active_configuration()

    intf = cfg[(0,0)]

    ep = usb.util.find_descriptor(intf, custom_match=lambda e: usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_OUT)

    send_mouse_command(ep, 100,100,1)
    
    send_mouse_movement(android_device, 10, 5)

else:
    print("Android device not found.")

Either of the functions send_mouse_command or send_mouse_movement usually fail with timeout, and I suspect this is because of either invalid arguments, or that Mac's port has to somehow pretend to be "HID", but I can't find any good examples or documentation for neither cases.

I'm running out of ideas and documentation, so I need your help.

0

There are 0 best solutions below