mcuee / libusbk

libusbk official github repo
74 stars 36 forks source link

Keep getting an error that the handle is invalid #50

Closed 0cococ closed 11 months ago

0cococ commented 11 months ago
import ctypes
from ctypes import Structure, c_uint, c_ubyte, c_void_p, POINTER

# 加载libusbK.dll
my_dll = ctypes.CDLL("libusbK.dll")

# 定义libusbK的函数原型
UsbK_Initialize = my_dll.UsbK_Initialize
UsbK_Initialize.argtypes = [c_void_p, POINTER(c_void_p)]
UsbK_Initialize.restype = ctypes.c_bool

UsbK_ControlTransfer = my_dll.UsbK_ControlTransfer
UsbK_ControlTransfer.argtypes = [c_void_p, c_void_p, POINTER(c_ubyte), c_uint, POINTER(c_uint), c_void_p]
UsbK_ControlTransfer.restype = ctypes.c_bool

LstK_Init = my_dll.LstK_Init
LstK_Init.argtypes = [POINTER(c_void_p), c_uint]
LstK_Init.restype = ctypes.c_bool

LstK_MoveNext = my_dll.LstK_MoveNext
LstK_MoveNext.argtypes = [c_void_p, POINTER(c_void_p)]
LstK_MoveNext.restype = ctypes.c_bool

LstK_Free = my_dll.LstK_Free
LstK_Free.argtypes = [c_void_p]
LstK_Free.restype = ctypes.c_bool

# 定义设备句柄类型
KUSB_HANDLE = c_void_p
KLST_HANDLE = c_void_p

# 设备列表句柄
deviceList = KLST_HANDLE()

def main():
    # 初始化设备列表句柄
    if LstK_Init(ctypes.byref(deviceList), 0):
        print("设备列表句柄创建成功!")
    else:
        print("设备列表句柄创建失败!")
        return

    # 枚举设备列表并打印设备信息
    while True:
        deviceInfo = KUSB_HANDLE()
        if not LstK_MoveNext(deviceList, ctypes.byref(deviceInfo)):
            break

        # 在这里可以根据需要获取设备信息并进行处理
        # 例如,可以使用UsbK_Initialize来创建libusbK接口句柄
        print("找到设备!设备句柄:", deviceInfo)

        # 模拟按下Home键
        class WINUSB_SETUP_PACKET(Structure):
            _fields_ = [
                ("RequestType", c_ubyte),
                ("Request", c_ubyte),
                ("Value", c_uint),
                ("Index", c_uint),
                ("Length", c_uint),
            ]

        setup_packet = WINUSB_SETUP_PACKET(0x21, 0x09, 0x0200, 0, 8)  # HID报告数据

        # 发送控制传输
        transferred = c_uint(0)
        success = UsbK_ControlTransfer(deviceInfo, ctypes.byref(setup_packet), None, 0, ctypes.byref(transferred), None)

        print("Home键模拟成功!" if success else "Home键模拟失败!")
        error_code = ctypes.windll.kernel32.GetLastError()
        print(f"设备句柄创建失败,错误代码: {error_code}")
        # 输出更多的错误信息
        buffer_size = 256
        error_message = ctypes.create_string_buffer(buffer_size)
        ctypes.windll.kernel32.FormatMessageA(0x00001000, None, error_code, 0x00000400, error_message, buffer_size,
                                              None)
        # 将错误信息转换为Unicode编码并忽略无法解码的字符
        error_message_unicode = error_message.value.decode('mbcs', 'ignore')
        print(f"错误信息: {error_message_unicode}")

    # 释放设备列表句柄
    if LstK_Free(deviceList):
        print("设备列表句柄释放成功!")
    else:
        print("设备列表句柄释放失败!")

if __name__ == "__main__":
    main()
0cococ commented 11 months ago
success = UsbK_ControlTransfer(deviceInfo, ctypes.byref(setup_packet), None, 0, ctypes.byref(transferred), None) 

has been reporting that the handle is invalid, but I created the handle and returned the creation success

mcuee commented 11 months ago

Did you use libusbK-inf-wizard (or Zadig) to install the libusbk.sys driver (or WinUSB or libusb0.sys) for your device? If not, libusbK will not work.

0cococ commented 11 months ago

My purpose is to use the usb similar to the hid protocol to control the mobile phone and click the home button. I used the ctypes library of python to call your libusbK.dll, a dynamic library. I can find the device now, but I can’t send the data and it keeps prompting that the handle is invalid. Other than that, I haven’t made any configuration. image

0cococ commented 11 months ago

imageDo I need any additional settings, he can find the device

0cococ commented 11 months ago

I installed libusbK-3.1.0.0-setup.exe and selected my pixel 2 device

0cococ commented 11 months ago

image image

0cococ commented 11 months ago

image

0cococ commented 11 months ago

image

0cococ commented 11 months ago
Device list handle created successfully!
Find the device! Device handle: c_void_p(2601362838080)
Home button simulation failed!
Device handle creation failed, error code: 6
Error message: The handle is invalid.

The device list handle is released successfully!

我运行我的代码他打印这些日志

0cococ commented 11 months ago
import ctypes
import time

# 加载 DLL
my_dll = ctypes.CDLL("libusbK.dll")

# 定义 LstK_Init 函数原型
LstK_Init = my_dll.LstK_Init
LstK_Init.argtypes = [ctypes.POINTER(ctypes.c_void_p), ctypes.c_ulong]
LstK_Init.restype = ctypes.c_bool

# 定义 UsbK_Init 函数原型
UsbK_Init = my_dll.UsbK_Init
UsbK_Init.argtypes = [ctypes.POINTER(ctypes.c_void_p), ctypes.c_void_p]
UsbK_Init.restype = ctypes.c_bool

# 定义 UsbK_Free 函数原型
UsbK_Free = my_dll.UsbK_Free
UsbK_Free.argtypes = [ctypes.c_void_p]
UsbK_Free.restype = ctypes.c_bool

# 定义 UsbK_ControlTransfer 函数原型
UsbK_ControlTransfer = my_dll.UsbK_ControlTransfer
UsbK_ControlTransfer.argtypes = [
    ctypes.c_void_p, ctypes.c_ubyte, ctypes.c_ubyte, ctypes.c_ushort,
    ctypes.c_ushort, ctypes.c_void_p, ctypes.c_ushort,
    ctypes.POINTER(ctypes.c_uint)
]
UsbK_ControlTransfer.restype = ctypes.c_bool

# 定义 LstK_Enumerate 函数原型
KLST_ENUM_DEVINFO_CB = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p)

# 定义 KLST_DEVINFO 结构体,注意结构体成员的类型和名称要和 DLL 中的定义一致
class KLST_DEVINFO(ctypes.Structure):
    _fields_ = [
        ("ID_VENDOR", ctypes.c_uint16),
        ("ID_PRODUCT", ctypes.c_uint16),
        # Add other members as needed based on the actual structure definition
    ]

# 枚举设备信息的回调函数
def EnumDevListCB(DeviceList, DeviceInfo):
    # 使用 ctypes.cast 将整数 DeviceInfo 转换为 KLST_DEVINFO 结构体指针
    dev_info_ptr = ctypes.cast(DeviceInfo, ctypes.POINTER(KLST_DEVINFO))
    dev_info = dev_info_ptr.contents

    # 获取设备信息的详细内容
    vendor_id = dev_info.ID_VENDOR
    product_id = dev_info.ID_PRODUCT
    # 可以根据需要打印或处理其他设备信息
    print(f"设备供应商ID: {vendor_id}, 产品ID: {product_id}")

    try:
        # 初始化 libusbK 接口句柄
        InterfaceHandle = ctypes.c_void_p()
        success = UsbK_Init(ctypes.byref(InterfaceHandle), DeviceInfo)
    except Exception as e:
        print(f"Error in UsbK_Init: {e}")
    if success:
        print("设备句柄创建成功")

        # 添加延迟,确保设备句柄已经完全初始化
        time.sleep(1)

        # 模拟按下Home键
        setup_packet = b"\x09\x02\x00\x00\x40\x00\x00\x00"  # HID报告数据

        # 发送控制传输
        transferred = ctypes.c_uint(0)
        success = UsbK_ControlTransfer(DeviceInfo, 0x21, 0x09, 0x0200, 0, setup_packet, 8, ctypes.byref(transferred))
        if success:
            print("Home键模拟成功")
        else:
            error_code = ctypes.windll.kernel32.GetLastError()
            print(f"Home键模拟失败,错误代码: {error_code}")

            # 输出更多的错误信息
            buffer_size = 256
            error_message = ctypes.create_string_buffer(buffer_size)
            ctypes.windll.kernel32.FormatMessageA(0x00001000, None, error_code, 0x00000400, error_message, buffer_size, None)
            # 将错误信息转换为Unicode编码并忽略无法解码的字符
            error_message_unicode = error_message.value.decode('mbcs', 'ignore')
            print(f"错误信息: {error_message_unicode}")

        # 释放 libusbK 接口句柄
        UsbK_Free(InterfaceHandle)
    else:

        error_code = ctypes.windll.kernel32.GetLastError()
        print(f"设备句柄创建失败,错误代码: {error_code}")
        # 输出更多的错误信息
        buffer_size = 256
        error_message = ctypes.create_string_buffer(buffer_size)
        ctypes.windll.kernel32.FormatMessageA(0x00001000, None, error_code, 0x00000400, error_message, buffer_size,
                                              None)
        # 将错误信息转换为Unicode编码并忽略无法解码的字符
        error_message_unicode = error_message.value.decode('mbcs', 'ignore')
        print(f"错误信息: {error_message_unicode}")

    return True  # 返回True表示继续枚举下一个设备信息

if __name__ == "__main__":
    DeviceList = ctypes.c_void_p()
    Flags = 1

    success = LstK_Init(ctypes.byref(DeviceList), Flags)
    print("LstK_Init 返回值:", success)

    if success:
        print("初始化成功,打印设备列表:")

        # 枚举设备信息并打印
        EnumDevListCB_func = KLST_ENUM_DEVINFO_CB(EnumDevListCB)
        my_dll.LstK_Enumerate(DeviceList, EnumDevListCB_func, None)

        # 在不再需要 DeviceList 时,需要调用 LstK_Free 释放资源
        my_dll.LstK_Free(DeviceList)
    else:
        print("初始化设备列表失败")
mcuee commented 11 months ago

For HID device, please use HIDAPI library and they have proper Python bindings. https://github.com/libusb/hidapi https://github.com/trezor/cython-hidapi

Please do not use ths library for HID devices.

0cococ commented 11 months ago

For HID device, please use HIDAPI library and they have proper Python bindings.

https://github.com/libusb/hidapi

https://github.com/trezor/cython-hidapi

Please do not use ths library for HID devices.

I want to use this library to drink my phone for data interaction and not just for controlling the phone because I think it's a perfect library can you tell me why I keep displaying invalid handles

mcuee commented 11 months ago

You need to check your control transfer is valid or not. Basically you need to understand the device protocol in order to use libusbK (or libusb-win32 or libusb). The above error is not saying the device handle is not correct, but rather your device does not understand the command. Your control transfer is not correct.

USB HID Specification is a good read. https://www.usb.org/sites/default/files/hid1_11.pdf

HIDAPI will help you as it is more suitable for HID device.

mcuee commented 11 months ago

This git repo is not for technical support, but rather reporting libusbK issues. Please use HIDAPI and if you encounter issues, you can ask in libusb-devel mailing list.

You need to subscribe to the mailing list in order to post questions. https://sourceforge.net/projects/libusb/lists/libusb-devel

If you really want to use libusbK, then you may want to ask in libusb-win32 mailing list. Unlikely you will get a good answer though as you really should use HIDAPI. You need to subscribe to the mailing list in order to post. https://sourceforge.net/projects/libusb-win32/lists/libusb-win32-devel

0cococ commented 11 months ago

您需要检查您的控制权转移是否有效。基本上,您需要了解设备协议才能使用libusbK(或libusb-win32或libusb)。上述错误并不是说设备句柄不正确,而是您的设备无法理解该命令。您的控制权转移不正确。

USB HID 规范是一个很好的阅读。 https://www.usb.org/sites/default/files/hid1_11.pdf

HIDAPI将为您提供帮助,因为它更适合HID设备。

Can this library interact with android, or what should I do if I can? I need this library to interact with android, and the data does not necessarily have to be hid

mcuee commented 11 months ago

Can this library interact with android, or what should I do if I can? I need this library to interact with android, and the data does not necessarily have to be hid

Sorry but I do not know anything about Android so I can not help you much.

libusb is probably a better library as it suports Windows, macOS and Linux, as well as other operating systems. libusbK only supports Windows.

You can state your goal and ask in libusb-devel mailing list to see which library to use. The mailing list allows questions on libusb, HIDAPI and general USB questions. https://sourceforge.net/projects/libusb/lists/libusb-devel

BTW, your English is okay, and you need to post in English if you want to ask questions in libusb-devel mailing list.