import usb.core import usb.util import requests import sys # Replace with your keyboard's VID and PID (e.g., 0x046d) VENDOR_ID = 0xXXXX PRODUCT_ID = 0xYYYY URL = "http://your-api-endpoint.com" # Map HID scancodes to characters (extend this as needed) HID_MAP = { 0x04: 'a', 0x08: 'e', 0x10: 'm', 0x17: 't', 0x1e: '1', 0x1f: '2', 0x20: '3', 0x21: '4', 0x22: '5', 0x23: '6', 0x24: '7', 0x25: '8', 0x26: '9', 0x27: '0', 0x28: 'ENTER' } def main(): # Find the device dev = usb.core.find(idVendor=VENDOR_ID, idProduct=PRODUCT_ID) if dev is None: print("Device not found. Check VID/PID.") return # Detach kernel driver to stop keyboard from typing into other windows for interface in [0, 1]: # Keyboards often have 2 interfaces (Keys and Media keys) try: if dev.is_kernel_driver_active(interface): dev.detach_kernel_driver(interface) print(f"Detached kernel driver on interface {interface}") except Exception: pass # Claim the first interface (usually index 0 for standard keys) usb.util.claim_interface(dev, 0) # Identify the input endpoint endpoint = dev[0][(0,0)][0] print(f"Listening for macros... Sending to {URL}") buffer = "" last_key = 0 try: while True: try: # Read 8 bytes of raw HID data data = dev.read(endpoint.bEndpointAddress, endpoint.wMaxPacketSize, timeout=100) # Standard keyboard reports: byte 2 is the first key pressed current_key = data[2] # Only process if key changed (avoid repeats) if current_key != 0 and current_key != last_key: char = HID_MAP.get(current_key) if char == 'ENTER': print(f"Sending Macro: {buffer}") requests.post(URL, data={'message': buffer}) buffer = "" # Reset buffer elif char: buffer += char last_key = current_key except usb.core.USBError as e: if e.errno == 110: # Timeout is normal when no keys are pressed continue break except KeyboardInterrupt: print("\nExiting and releasing device...") finally: usb.util.release_interface(dev, 0) dev.attach_kernel_driver(0) if __name__ == "__main__": main()