From f5b4382efe2cec6cf34815d3d6f594d5cf4a4708 Mon Sep 17 00:00:00 2001 From: Elizabeth Cray Date: Sun, 27 Jul 2025 20:32:01 -0400 Subject: [PATCH] Enable building with USB Host/Device Stacks --- src/CMakeLists.txt | 22 +++--- src/config.h | 2 - src/hirsute.c | 109 +++++++++++++++++++++++----- src/tusb_config.h | 26 ++++--- src/usb_descriptors.c | 165 ++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 281 insertions(+), 43 deletions(-) create mode 100644 src/usb_descriptors.c diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index f745376..0fc76df 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -6,8 +6,8 @@ set(CMAKE_CXX_STANDARD 17) set(PICO_SDK_PATH "${CMAKE_CURRENT_LIST_DIR}/../libs/pico-sdk") include("${PICO_SDK_PATH}/external/pico_sdk_import.cmake") -# set(PICO_PIO_USB_DIR "${CMAKE_CURRENT_LIST_DIR}/../libs/pico-pio-hirsute") -# add_subdirectory(${PICO_PIO_USB_DIR} pico_pio_usb) +set(PICO_PIO_USB_DIR "${CMAKE_CURRENT_LIST_DIR}/../libs/pico-pio-hirsute") +add_subdirectory(${PICO_PIO_USB_DIR} pico_pio_usb) set(target_name hirsute) @@ -15,27 +15,23 @@ project(${target_name} C CXX ASM) add_executable(${target_name} hirsute.c - ) +) target_sources(${target_name} PRIVATE hirsute.c - # ${PICO_SDK_PATH}/lib/tinyusb/src/portable/raspberrypi/pio_usb/dcd_pio_usb.c - # ${PICO_SDK_PATH}/lib/tinyusb/src/portable/raspberrypi/pio_usb/hcd_pio_usb.c + usb_descriptors.c + ${PICO_SDK_PATH}/lib/tinyusb/src/portable/raspberrypi/pio_usb/dcd_pio_usb.c + ${PICO_SDK_PATH}/lib/tinyusb/src/portable/raspberrypi/pio_usb/hcd_pio_usb.c ) pico_sdk_init() -pico_enable_stdio_usb(${target_name} 1) -pico_enable_stdio_uart(${target_name} 0) - target_link_options(${target_name} PRIVATE -Xlinker --print-memory-usage) target_compile_options(${target_name} PRIVATE -Wall -Wextra) -# target_compile_definitions(${target_name} PRIVATE PIO_USB_USE_TINYUSB) -# target_include_directories(${target_name} PRIVATE ${CMAKE_CURRENT_LIST_DIR}) +target_compile_definitions(${target_name} PRIVATE PIO_USB_USE_TINYUSB) +target_include_directories(${target_name} PRIVATE ${CMAKE_CURRENT_LIST_DIR}) -# target_link_libraries(${target_name} PRIVATE pico_stdlib pico_multicore pico_pio_usb tinyusb_host tinyusb_board) -target_link_libraries(${target_name} PRIVATE pico_stdlib pico_multicore) +target_link_libraries(${target_name} PRIVATE pico_stdlib pico_multicore pico_pio_usb tinyusb_device tinyusb_host tinyusb_board) -# Generate hex file pico_add_extra_outputs(${target_name}) diff --git a/src/config.h b/src/config.h index f15fdb6..4e92982 100644 --- a/src/config.h +++ b/src/config.h @@ -1,8 +1,6 @@ #ifndef CONFIG_H #define CONFIG_H -#define EN_USB 0 // Enable USB Host - #define USB_DP 16 // USB D+ pin on GP16 #define MAC_MOUSE_X2 diff --git a/src/hirsute.c b/src/hirsute.c index 42ac5f7..fbc8d9d 100644 --- a/src/hirsute.c +++ b/src/hirsute.c @@ -22,13 +22,10 @@ #include "pico/util/queue.h" #include "pico/multicore.h" #include "pico/bootrom.h" -#if EN_USB +#include "bsp/board.h" +#include "hardware/clocks.h" #include "pio_usb.h" #include "tusb.h" -#include "bsp/board.h" -#endif -#include "hardware/uart.h" -#include "hardware/clocks.h" void setPullup(uint PIN); void holdForEnable(); @@ -40,7 +37,6 @@ void sendKey(uint8_t key); queue_t key_queue; -#if EN_USB void core_one() { sleep_ms(10); pio_usb_configuration_t pio_config = PIO_USB_DEFAULT_CONFIG; @@ -51,26 +47,32 @@ void core_one() { tuh_task(); } } -#endif int main() { - #if EN_USB - board_init(); - #endif - stdio_init_all(); + board_init(); + set_sys_clock_khz(120000, true); sleep_ms(10); + queue_init(&key_queue, sizeof(uint8_t), 1024); + + // Initialize USB Host Core multicore_reset_core1(); - #if EN_USB - multicore_launch_core1(core_one); - #endif + multicore_launch_core1(core_one); + + // Initialize USB Device Core for debugging + tud_init(0); + // Init Pins for Keyboard gpio_init(MAC_KB_CLOCK); gpio_set_dir(MAC_KB_CLOCK, GPIO_OUT); gpio_init(MAC_KB_DATA); setPullup(MAC_KB_DATA); + + // Handle Mac Keyboard Interface + Debug Tasks while (true){ + tud_task(); + tud_cdc_write_flush(); switch(readCommand()) { case 0x10: // Key Requested @@ -93,18 +95,20 @@ int main() { return 0; } +/* -------------------------------------------------- + * Macintosh Keyboard Commands + * -------------------------------------------------- + */ + void setPullup(uint PIN){ gpio_set_dir(PIN, GPIO_IN); gpio_pull_up(PIN); } void holdForEnable() { - printf("Waiting for keyboard enable...\n"); while (gpio_get(MAC_KB_DATA)) { - printf("."); sleep_ms(10); } - printf("\nKeyboard enabled.\n"); sleep_us(180); } @@ -174,3 +178,74 @@ void sendKey(uint8_t key) { sendByte(key); } } + +/* --------------------------------------------------- + * TinyUSB Device Callbacks + * --------------------------------------------------- + */ + +void tud_cdc_rx_cb(uint8_t itf) { + (void) itf; + char buf[64]; + uint32_t count = tud_cdc_read(buf, sizeof(buf)); + // TODO control LED on keyboard of host stack + (void) count; +} + +/* --------------------------------------------------- + * TinyUSB Host Callbacks + * --------------------------------------------------- + * Pulled from Pico PIO USB examples + */ + +void tuh_hid_mount_cb(uint8_t dev_addr, uint8_t instance, uint8_t const* desc_report, uint16_t desc_len) { + (void)desc_report; + (void)desc_len; + + // Interface protocol (hid_interface_protocol_enum_t) + const char* protocol_str[] = { "None", "Keyboard", "Mouse" }; + uint8_t const itf_protocol = tuh_hid_interface_protocol(dev_addr, instance); + + uint16_t vid, pid; + tuh_vid_pid_get(dev_addr, &vid, &pid); + + char tempbuf[256]; + int count = sprintf(tempbuf, "[%04x:%04x][%u] HID Interface%u, Protocol = %s\r\n", vid, pid, dev_addr, instance, protocol_str[itf_protocol]); + + tud_cdc_write(tempbuf, count); + tud_cdc_write_flush(); + + // Receive report from boot keyboard & mouse only + // tuh_hid_report_received_cb() will be invoked when report is available + if (itf_protocol == HID_ITF_PROTOCOL_KEYBOARD || itf_protocol == HID_ITF_PROTOCOL_MOUSE) + { + if ( !tuh_hid_receive_report(dev_addr, instance) ) + { + tud_cdc_write_str("Error: cannot request report\r\n"); + } + } +} + +void tuh_hid_report_received_cb(uint8_t dev_addr, uint8_t instance, uint8_t const* report, uint16_t len){ + (void) len; + uint8_t const itf_protocol = tuh_hid_interface_protocol(dev_addr, instance); + + switch(itf_protocol) + { + case HID_ITF_PROTOCOL_KEYBOARD: + // process_kbd_report(dev_addr, (hid_keyboard_report_t const*) report ); + break; + + case HID_ITF_PROTOCOL_MOUSE: + // process_mouse_report(dev_addr, (hid_mouse_report_t const*) report ); + break; + + default: break; + } + + // continue to request to receive report + if ( !tuh_hid_receive_report(dev_addr, instance) ) + { + tud_cdc_write_str("Error: cannot request report\r\n"); + } +} diff --git a/src/tusb_config.h b/src/tusb_config.h index 716b9be..46fc991 100644 --- a/src/tusb_config.h +++ b/src/tusb_config.h @@ -61,6 +61,10 @@ // Enable device stack // #define CFG_TUD_ENABLED 1 +// Enable device stack +#define CFG_TUD_ENABLED 1 + + // Enable host stack with pio-usb if Pico-PIO-USB library is available #define CFG_TUH_ENABLED 1 #define CFG_TUH_RPI_PIO_USB 1 @@ -87,19 +91,19 @@ // DEVICE CONFIGURATION //-------------------------------------------------------------------- -// #ifndef CFG_TUD_ENDPOINT0_SIZE -// #define CFG_TUD_ENDPOINT0_SIZE 64 -// #endif +#ifndef CFG_TUD_ENDPOINT0_SIZE +#define CFG_TUD_ENDPOINT0_SIZE 64 +#endif -// //------------- CLASS -------------// -// #define CFG_TUD_CDC 1 +//------------- CLASS -------------// +#define CFG_TUD_CDC 1 -// // CDC FIFO size of TX and RX -// #define CFG_TUD_CDC_RX_BUFSIZE 256 -// #define CFG_TUD_CDC_TX_BUFSIZE 256 +// CDC FIFO size of TX and RX +#define CFG_TUD_CDC_RX_BUFSIZE 256 +#define CFG_TUD_CDC_TX_BUFSIZE 256 -// // CDC Endpoint transfer buffer size, more is faster -// #define CFG_TUD_CDC_EP_BUFSIZE 64 +// CDC Endpoint transfer buffer size, more is faster +#define CFG_TUD_CDC_EP_BUFSIZE 64 //-------------------------------------------------------------------- // HOST CONFIGURATION @@ -120,4 +124,4 @@ } #endif -#endif /* _TUSB_CONFIG_H_ */ \ No newline at end of file +#endif /* _TUSB_CONFIG_H_ */ diff --git a/src/usb_descriptors.c b/src/usb_descriptors.c new file mode 100644 index 0000000..14f06bc --- /dev/null +++ b/src/usb_descriptors.c @@ -0,0 +1,165 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * sekigon-gonnoc + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +#include "tusb.h" + +/* A combination of interfaces must have a unique product id, since PC will save device driver after the first plug. + * Same VID/PID with different interface e.g MSC (first), then CDC (later) will possibly cause system error on PC. + * + * Auto ProductID layout's Bitmap: + * [MSB] HID | MSC | CDC [LSB] + */ +#define _PID_MAP(itf, n) ( (CFG_TUD_##itf) << (n) ) +#define USB_PID (0x4000 | _PID_MAP(CDC, 0) | _PID_MAP(MSC, 1) | _PID_MAP(HID, 2) | \ + _PID_MAP(MIDI, 3) | _PID_MAP(VENDOR, 4) ) + +#define USB_VID 0x2E8A // Raspberry Pi Vendor ID +#define USB_BCD 0x05AC + +//--------------------------------------------------------------------+ +// Device Descriptors +//--------------------------------------------------------------------+ +tusb_desc_device_t const desc_device = +{ + .bLength = sizeof(tusb_desc_device_t), + .bDescriptorType = TUSB_DESC_DEVICE, + .bcdUSB = USB_BCD, + + // Use Interface Association Descriptor (IAD) for CDC + // As required by USB Specs IAD's subclass must be common class (2) and protocol must be IAD (1) + .bDeviceClass = TUSB_CLASS_MISC, + .bDeviceSubClass = MISC_SUBCLASS_COMMON, + .bDeviceProtocol = MISC_PROTOCOL_IAD, + + .bMaxPacketSize0 = CFG_TUD_ENDPOINT0_SIZE, + + .idVendor = USB_VID, + .idProduct = USB_PID, + .bcdDevice = 0x0100, + + .iManufacturer = 0x01, + .iProduct = 0x02, + .iSerialNumber = 0x03, + + .bNumConfigurations = 0x01 +}; + +// Invoked when received GET DEVICE DESCRIPTOR +// Application return pointer to descriptor +uint8_t const * tud_descriptor_device_cb(void) +{ + return (uint8_t const *) &desc_device; +} + +//--------------------------------------------------------------------+ +// Configuration Descriptor +//--------------------------------------------------------------------+ + +enum +{ + ITF_NUM_CDC = 0, + ITF_NUM_CDC_DATA, + ITF_NUM_TOTAL +}; + +#define EPNUM_CDC_NOTIF 0x81 +#define EPNUM_CDC_OUT 0x02 +#define EPNUM_CDC_IN 0x82 + +#define CONFIG_TOTAL_LEN (TUD_CONFIG_DESC_LEN + TUD_CDC_DESC_LEN) + +// full speed configuration +uint8_t const desc_fs_configuration[] = +{ + // Config number, interface count, string index, total length, attribute, power in mA + TUD_CONFIG_DESCRIPTOR(1, ITF_NUM_TOTAL, 0, CONFIG_TOTAL_LEN, 0x00, 100), + + // Interface number, string index, EP notification address and size, EP data address (out, in) and size. + TUD_CDC_DESCRIPTOR(ITF_NUM_CDC, 4, EPNUM_CDC_NOTIF, 8, EPNUM_CDC_OUT, EPNUM_CDC_IN, 64), +}; + +// Invoked when received GET CONFIGURATION DESCRIPTOR +// Application return pointer to descriptor +// Descriptor contents must exist long enough for transfer to complete +uint8_t const * tud_descriptor_configuration_cb(uint8_t index) +{ + (void) index; // for multiple configurations + return desc_fs_configuration; +} + +//--------------------------------------------------------------------+ +// String Descriptors +//--------------------------------------------------------------------+ + +// array of pointer to string descriptors +char const* string_desc_arr [] = +{ + (const char[]) { 0x09, 0x04 }, // 0: is supported language is English (0x0409) + "TinyUSB", // 1: Manufacturer + "TinyUSB Device", // 2: Product + "123456789012", // 3: Serials, should use chip ID + "TinyUSB CDC", // 4: CDC Interface +}; + +static uint16_t _desc_str[32]; + +// Invoked when received GET STRING DESCRIPTOR request +// Application return pointer to descriptor, whose contents must exist long enough for transfer to complete +uint16_t const* tud_descriptor_string_cb(uint8_t index, uint16_t langid) +{ + (void) langid; + + uint8_t chr_count; + + if ( index == 0) + { + memcpy(&_desc_str[1], string_desc_arr[0], 2); + chr_count = 1; + }else + { + // Note: the 0xEE index string is a Microsoft OS 1.0 Descriptors. + // https://docs.microsoft.com/en-us/windows-hardware/drivers/usbcon/microsoft-defined-usb-descriptors + + if ( !(index < sizeof(string_desc_arr)/sizeof(string_desc_arr[0])) ) return NULL; + + const char* str = string_desc_arr[index]; + + // Cap at max char + chr_count = (uint8_t) strlen(str); + if ( chr_count > 31 ) chr_count = 31; + + // Convert ASCII string into UTF-16 + for(uint8_t i=0; i