From cab1b2f6f741ea151e87f139b2115d5234228bbd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Berthoz?= Date: Sun, 4 Jan 2026 16:55:43 +0100 Subject: [PATCH] Implement Printer Device Class --- examples/device/printer_to_hid/CMakeLists.txt | 29 ++ .../device/printer_to_hid/CMakePresets.json | 6 + examples/device/printer_to_hid/Makefile | 11 + examples/device/printer_to_hid/README.md | 0 examples/device/printer_to_hid/src/main.c | 219 +++++++++++++ .../device/printer_to_hid/src/tusb_config.h | 115 +++++++ .../printer_to_hid/src/usb_descriptors.c | 247 ++++++++++++++ .../printer_to_hid/src/usb_descriptors.h | 30 ++ src/CMakeLists.txt | 1 + src/class/printer/printer.h | 277 ++++++++++++++++ src/class/printer/printer_device.c | 306 ++++++++++++++++++ src/class/printer/printer_device.h | 79 +++++ src/device/usbd.c | 13 + src/device/usbd.h | 15 + src/tinyusb.mk | 1 + src/tusb.h | 4 + src/tusb_option.h | 4 + tools/iar_template.ipcf | 5 + 18 files changed, 1362 insertions(+) create mode 100644 examples/device/printer_to_hid/CMakeLists.txt create mode 100644 examples/device/printer_to_hid/CMakePresets.json create mode 100644 examples/device/printer_to_hid/Makefile create mode 100644 examples/device/printer_to_hid/README.md create mode 100644 examples/device/printer_to_hid/src/main.c create mode 100644 examples/device/printer_to_hid/src/tusb_config.h create mode 100644 examples/device/printer_to_hid/src/usb_descriptors.c create mode 100644 examples/device/printer_to_hid/src/usb_descriptors.h create mode 100644 src/class/printer/printer.h create mode 100644 src/class/printer/printer_device.c create mode 100644 src/class/printer/printer_device.h diff --git a/examples/device/printer_to_hid/CMakeLists.txt b/examples/device/printer_to_hid/CMakeLists.txt new file mode 100644 index 000000000..f58759059 --- /dev/null +++ b/examples/device/printer_to_hid/CMakeLists.txt @@ -0,0 +1,29 @@ +cmake_minimum_required(VERSION 3.20) + +include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake) + +project(printer_to_hid C CXX ASM) + +# Checks this example is valid for the family and initializes the project +family_initialize_project(${PROJECT_NAME} ${CMAKE_CURRENT_LIST_DIR}) +# Espressif has its own cmake build system +if(FAMILY STREQUAL "espressif") + return() +endif() + +add_executable(${PROJECT_NAME}) + +# Example source +target_sources(${PROJECT_NAME} PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR}/src/main.c + ${CMAKE_CURRENT_SOURCE_DIR}/src/usb_descriptors.c + ) + +# Example include +target_include_directories(${PROJECT_NAME} PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR}/src + ) + +# Configure compilation flags and libraries for the example without RTOS. +# See the corresponding function in hw/bsp/FAMILY/family.cmake for details. +family_configure_device_example(${PROJECT_NAME} noos) diff --git a/examples/device/printer_to_hid/CMakePresets.json b/examples/device/printer_to_hid/CMakePresets.json new file mode 100644 index 000000000..5cd8971e9 --- /dev/null +++ b/examples/device/printer_to_hid/CMakePresets.json @@ -0,0 +1,6 @@ +{ + "version": 6, + "include": [ + "../../../hw/bsp/BoardPresets.json" + ] +} diff --git a/examples/device/printer_to_hid/Makefile b/examples/device/printer_to_hid/Makefile new file mode 100644 index 000000000..1a4b428dc --- /dev/null +++ b/examples/device/printer_to_hid/Makefile @@ -0,0 +1,11 @@ +include ../../../hw/bsp/family_support.mk + +INC += \ + src \ + + +# Example source +EXAMPLE_SOURCE += $(wildcard src/*.c) +SRC_C += $(addprefix $(EXAMPLE_PATH)/, $(EXAMPLE_SOURCE)) + +include ../../../hw/bsp/family_rules.mk diff --git a/examples/device/printer_to_hid/README.md b/examples/device/printer_to_hid/README.md new file mode 100644 index 000000000..e69de29bb diff --git a/examples/device/printer_to_hid/src/main.c b/examples/device/printer_to_hid/src/main.c new file mode 100644 index 000000000..f5012478c --- /dev/null +++ b/examples/device/printer_to_hid/src/main.c @@ -0,0 +1,219 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2026 Ha Thach (tinyusb.org) + * + * 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 +#include +#include + +#include "bsp/board_api.h" +#include "tusb.h" + +#include "usb_descriptors.h" + +// -------------------------------------------------------------------+ +// Variables controlled with USB endpoint callbacks +// -------------------------------------------------------------------+ + +// usb interface pointer +uint8_t printer_itf = 0; +// pendings bytes in usb endpoint buffer ; must process these bytes +uint8_t pending_bytes_on_usb_ep = 0; + + +// -------------------------------------------------------------------+ +// Variables controlled locally +// -------------------------------------------------------------------+ + +// local data buffer (copy data from usb endpoint into this buffer) ; acts as fifo +uint8_t data_buffer[16] = {0}; +// write offset for usb/printer incoming data to data_buffer +size_t data_rx_offset = 0; +// read offset for usb/hid outgoing data from data_buffer +size_t data_tx_offset = 0; +// available space in data_buffer +size_t data_available = sizeof(data_buffer); + +// next keycode to send on usb/hid +uint8_t next_keycode = 0; +// next key modifiers to send on usb/hid +uint8_t next_modifiers = 0; +// whether the next usb/hid report must be NULL to release the last keystroke +uint8_t next_keycode_is_release = false; + + +// -------------------------------------------------------------------+ +// Tasks +// -------------------------------------------------------------------+ + +// Every 10ms, we will place HID data in the usb/hid endpoint, ready to +// sent to the host when required. The tasks will read the keycode in +// next_keycode and place it in the HID report, then set next_is_null +// such that the key is released by the next report. This seem to help +// stroking the same key twice when the character is repeated in the data. +void hid_tx_task(void) { + // Poll every 10ms + const uint32_t interval_ms = 10; + static uint32_t start_ms = 0; + + if (!tud_hid_ready()) { + return; + } + + if (board_millis() - start_ms < interval_ms) { + return; // not enough time + } + start_ms += interval_ms; + + if (next_keycode_is_release || next_keycode == 0) { + tud_hid_keyboard_report(1, 0, NULL); + next_keycode_is_release = false; + return; + } + + uint8_t keycode_array[6] = {0}; + keycode_array[0] = next_keycode; + tud_hid_keyboard_report(1, next_modifiers, keycode_array); + next_keycode_is_release = true; + next_keycode = 0; +} + +// Whenever there are pendings bytes on the USB endpoint, we will pull them from the +// endpoint buffer and write then in the local data buffer. We must take care to not +// overwrite local data that is not processed yet, so we use data_buffer as a fifo. +// We do not have to take care of reading correctly from the endpoint buffer, as all +// is done well by tud_printer_n_read(). +void printer_rx_task(void) { + if (pending_bytes_on_usb_ep > 0) { + size_t len1 = data_available; + size_t len2 = 0; + if (len1 < 0) { + len1 = 0; + } + if (data_rx_offset + len1 > sizeof(data_buffer)) { + len2 = len1 - (sizeof(data_buffer) - data_rx_offset); + len1 = sizeof(data_buffer) - data_rx_offset; + } + uint32_t count = tud_printer_n_read(printer_itf, data_buffer + data_rx_offset, len1); + if (len2 > 0) { + count += tud_printer_n_read(printer_itf, data_buffer, len2); + } + + if (count > 0) { + data_available -= count; + pending_bytes_on_usb_ep -= count; + data_rx_offset = (data_rx_offset + count) % sizeof(data_buffer); + } + } +} + +// The HID keycodes are not binary mapped like UTF8 codes. If we want to send the +// data received as a usb/printer, we have to translate the binary data for the +// usb/hid interface. Note that the simple mapping below will be valid only for +// hosts expecting hid data from a QWERTY keyboard. Also note that only a-zA-Z0-9 +// characters are converted, for simplicity of the example. Other characters are +// converted to spaces. +void translation_task(void) { + if (data_tx_offset != data_rx_offset || data_available == 0) { + // If data_tx_offset and data_rx_offset have different values, then we + // can proceed: translate, prepare for TX, and advance data_tx_offset. + // + // If the buffer is full (data_available == 0), then we must also + // translate data and prepare it for TX. But the data_tx_offset and + // data_rx_offset will have the same value, since RX caught up to TX. + // Hence the OR. + + // Translate UTF8 to HID keystroke + char c = data_buffer[data_tx_offset]; + uint8_t m = 0; + if ('a' <= c && c <= 'z') { + c -= 'a'; + c += HID_KEY_A; + } else if ('A' <= c && c <= 'Z') { + c -= 'a'; + c += HID_KEY_A; + m = KEYBOARD_MODIFIER_LEFTSHIFT; + } else if ('1' <= c && c <= '9') { + c -= '1'; + c += HID_KEY_1; + } else if (c == '0') { + c = HID_KEY_0; + } else { + c = HID_KEY_SPACE; + } + + // Proceed only if there are no characters pending for TX + if (next_keycode == 0) { + // Prepare next keystroke with translated data + next_keycode = c; + next_modifiers = m; + // Increment read offset + data_tx_offset += 1; + data_tx_offset %= sizeof(data_buffer); + data_available += 1; + } + } +} + +int main(void) { + + board_init(); + tud_init(BOARD_TUD_RHPORT); // init device stack on configured roothub port + if (board_init_after_tusb) { + board_init_after_tusb(); + } + + while (1) { + tud_task(); // tinyusb device task + printer_rx_task(); // read data sent by host on our printer interface + translation_task(); // translate printer's UTF8 to HID keycodes + hid_tx_task(); // send data to host with our HID interface + } +} + + +//--------------------------------------------------------------------+ +// Printer callbacks +//--------------------------------------------------------------------+ + +// Data was received on endpoint buffer +void tud_printer_rx_cb(uint8_t itf, size_t n) { + printer_itf = itf; // get interface from which to read endpoint buffer + pending_bytes_on_usb_ep += n; // count pending bytes, counter must decrement when reading from the endpoint buffer +} + + +//--------------------------------------------------------------------+ +// HID callbacks +//--------------------------------------------------------------------+ + +uint16_t tud_hid_get_report_cb(uint8_t instance, uint8_t report_id, hid_report_type_t report_type, uint8_t *buffer, + uint16_t reqlen) { + return 0; +} + +void tud_hid_set_report_cb(uint8_t instance, uint8_t report_id, hid_report_type_t report_type, const uint8_t *buffer, + uint16_t bufsize) { + return; +} diff --git a/examples/device/printer_to_hid/src/tusb_config.h b/examples/device/printer_to_hid/src/tusb_config.h new file mode 100644 index 000000000..a8dbac89d --- /dev/null +++ b/examples/device/printer_to_hid/src/tusb_config.h @@ -0,0 +1,115 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2026 Ha Thach (tinyusb.org) + * + * 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. + * + */ + +#ifndef _TUSB_CONFIG_H_ +#define _TUSB_CONFIG_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +//--------------------------------------------------------------------+ +// Board Specific Configuration +//--------------------------------------------------------------------+ + +#define BOARD_DEVICE_RHPORT_NUM 3 + +// RHPort number used for device can be defined by board.mk, default to port 0 +#ifndef BOARD_TUD_RHPORT + #define BOARD_TUD_RHPORT 0 +#endif + +// RHPort max operational speed can defined by board.mk +#ifndef BOARD_TUD_MAX_SPEED + #define BOARD_TUD_MAX_SPEED OPT_MODE_DEFAULT_SPEED +#endif + +//-------------------------------------------------------------------- +// COMMON CONFIGURATION +//-------------------------------------------------------------------- + +// defined by compiler flags for flexibility +#ifndef CFG_TUSB_MCU + #error CFG_TUSB_MCU must be defined +#endif + +#ifndef CFG_TUSB_OS + #define CFG_TUSB_OS OPT_OS_NONE +#endif + +#ifndef CFG_TUSB_DEBUG + #define CFG_TUSB_DEBUG 0 +#endif + +// Enable Device stack +#define CFG_TUD_ENABLED 1 + +// Default is max speed that hardware controller could support with on-chip PHY +#define CFG_TUD_MAX_SPEED BOARD_TUD_MAX_SPEED + +/* USB DMA on some MCUs can only access a specific SRAM region with restriction on alignment. + * Tinyusb use follows macros to declare transferring memory so that they can be put + * into those specific section. + * e.g + * - CFG_TUSB_MEM SECTION : __attribute__ (( section(".usb_ram") )) + * - CFG_TUSB_MEM_ALIGN : __attribute__ ((aligned(4))) + */ +#ifndef CFG_TUSB_MEM_SECTION + #define CFG_TUSB_MEM_SECTION +#endif + +#ifndef CFG_TUSB_MEM_ALIGN + #define CFG_TUSB_MEM_ALIGN __attribute__((aligned(4))) +#endif + +//-------------------------------------------------------------------- +// DEVICE CONFIGURATION +//-------------------------------------------------------------------- + +#ifndef CFG_TUD_ENDPOINT0_SIZE + #define CFG_TUD_ENDPOINT0_SIZE 64 +#endif + +//------------- CLASS -------------// +#define CFG_TUD_HID 1 +#define CFG_TUD_CDC 0 +#define CFG_TUD_MSC 0 +#define CFG_TUD_MIDI 0 +#define CFG_TUD_VENDOR 0 +#define CFG_TUD_PRINTER 1 + +// HID buffer size Should be sufficient to hold ID (if any) + Data +#define CFG_TUD_HID_EP_BUFSIZE 16 + +// Printer buffer size Should be sufficient to hold data +#define CFG_TUD_PRINTER_RX_BUFSIZE 16 +#define CFG_TUD_PRINTER_TX_BUFSIZE 16 +#define CFG_TUD_PRINTER_EP_BUFSIZE 16 + +#ifdef __cplusplus +} +#endif + +#endif /* _TUSB_CONFIG_H_ */ diff --git a/examples/device/printer_to_hid/src/usb_descriptors.c b/examples/device/printer_to_hid/src/usb_descriptors.c new file mode 100644 index 000000000..161bbb7c5 --- /dev/null +++ b/examples/device/printer_to_hid/src/usb_descriptors.c @@ -0,0 +1,247 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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 "bsp/board_api.h" +#include "tusb.h" +#include "usb_descriptors.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) ? (1 << (n)) : 0) +#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 0xCafe +#define USB_BCD 0x0200 + +//--------------------------------------------------------------------+ +// Device Descriptors +//--------------------------------------------------------------------+ +static tusb_desc_device_t const desc_device = +{ + .bLength = sizeof(tusb_desc_device_t), + .bDescriptorType = TUSB_DESC_DEVICE, + .bcdUSB = USB_BCD, + .bDeviceClass = 0x00, + .bDeviceSubClass = 0x00, + .bDeviceProtocol = 0x00, + .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; +} + +//--------------------------------------------------------------------+ +// HID Report Descriptor +//--------------------------------------------------------------------+ + +uint8_t const desc_hid_report[] = +{ + TUD_HID_REPORT_DESC_KEYBOARD( HID_REPORT_ID(REPORT_ID_KEYBOARD )) +}; + +// Invoked when received GET HID REPORT DESCRIPTOR +// Application return pointer to descriptor +// Descriptor contents must exist long enough for transfer to complete +uint8_t const * tud_hid_descriptor_report_cb(uint8_t instance) +{ + (void) instance; + return desc_hid_report; +} + +//--------------------------------------------------------------------+ +// Configuration Descriptor +//--------------------------------------------------------------------+ + +enum +{ + ITF_NUM_HID, + ITF_NUM_PRINTER, + ITF_NUM_TOTAL +}; + +#define CONFIG_TOTAL_LEN (TUD_CONFIG_DESC_LEN + TUD_HID_DESC_LEN + TUD_PRINTER_DESC_LEN) + +// HID interface endpoints +#define EPADDR_HID 0x81 // Interrupt In, MSB must be 1 +// Printer interface endpoints +#define EPADDR_PRINTER_OUT 0x01 // Bulk Out, MSB must be 0 +#define EPADDR_PRINTER_IN 0x82 // Bulk In, MSB must be 1 + +uint8_t const desc_configuration[] = +{ + // Config number, interface count, string index, total length, attribute, power in mA + TUD_CONFIG_DESCRIPTOR(1, ITF_NUM_TOTAL, 0, CONFIG_TOTAL_LEN, TUSB_DESC_CONFIG_ATT_REMOTE_WAKEUP, 100), + + // HID: + // Interface number, string index, protocol, report descriptor len, EP In address, size & polling interval + TUD_HID_DESCRIPTOR(ITF_NUM_HID, 0, HID_ITF_PROTOCOL_NONE, sizeof(desc_hid_report), EPADDR_HID, CFG_TUD_HID_EP_BUFSIZE, 5), + + // Printer: + // Interface number, string index, EP Bulk Out address, EP Bulk In address, EP size + TUD_PRINTER_DESCRIPTOR(ITF_NUM_PRINTER, 0, EPADDR_PRINTER_OUT, EPADDR_PRINTER_IN, CFG_TUD_PRINTER_EP_BUFSIZE) +}; + +#if TUD_OPT_HIGH_SPEED +// Per USB specs: high speed capable device must report device_qualifier and other_speed_configuration + +// other speed configuration +static uint8_t desc_other_speed_config[CONFIG_TOTAL_LEN]; + +// device qualifier is mostly similar to device descriptor since we don't change configuration based on speed +static tusb_desc_device_qualifier_t const desc_device_qualifier = +{ + .bLength = sizeof(tusb_desc_device_qualifier_t), + .bDescriptorType = TUSB_DESC_DEVICE_QUALIFIER, + .bcdUSB = USB_BCD, + + .bDeviceClass = 0x00, + .bDeviceSubClass = 0x00, + .bDeviceProtocol = 0x00, + + .bMaxPacketSize0 = CFG_TUD_ENDPOINT0_SIZE, + .bNumConfigurations = 0x01, + .bReserved = 0x00 +}; + +// Invoked when received GET DEVICE QUALIFIER DESCRIPTOR request +// Application return pointer to descriptor, whose contents must exist long enough for transfer to complete. +// device_qualifier descriptor describes information about a high-speed capable device that would +// change if the device were operating at the other speed. If not highspeed capable stall this request. +uint8_t const* tud_descriptor_device_qualifier_cb(void) +{ + return (uint8_t const*) &desc_device_qualifier; +} + +// Invoked when received GET OTHER SEED CONFIGURATION DESCRIPTOR request +// Application return pointer to descriptor, whose contents must exist long enough for transfer to complete +// Configuration descriptor in the other speed e.g if high speed then this is for full speed and vice versa +uint8_t const* tud_descriptor_other_speed_configuration_cb(uint8_t index) +{ + (void) index; // for multiple configurations + + // other speed config is basically configuration with type = OTHER_SPEED_CONFIG + memcpy(desc_other_speed_config, desc_configuration, CONFIG_TOTAL_LEN); + desc_other_speed_config[1] = TUSB_DESC_OTHER_SPEED_CONFIG; + + // this example use the same configuration for both high and full speed mode + return desc_other_speed_config; +} + +#endif // highspeed + +// 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 + + // This example use the same configuration for both high and full speed mode + return desc_configuration; +} + +//--------------------------------------------------------------------+ +// String Descriptors +//--------------------------------------------------------------------+ + +// String Descriptor Index +enum { + STRID_LANGID = 0, + STRID_MANUFACTURER, + STRID_PRODUCT, + STRID_SERIAL, +}; + +// array of pointer to string descriptors +static char const *string_desc_arr[] = +{ + (const char[]) { 0x09, 0x04 }, // 0: is supported language is English (0x0409) + "TinyUSB", // 1: Manufacturer + "TinyUSB Device", // 2: Product + NULL, // 3: Serials will use unique ID if possible +}; + +static uint16_t _desc_str[32 + 1]; + +// 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; + size_t chr_count; + + switch ( index ) { + case STRID_LANGID: + memcpy(&_desc_str[1], string_desc_arr[0], 2); + chr_count = 1; + break; + + case STRID_SERIAL: + chr_count = board_usb_get_serial(_desc_str + 1, 32); + break; + + default: + // 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 = strlen(str); + size_t const max_count = sizeof(_desc_str) / sizeof(_desc_str[0]) - 1; // -1 for string type + if ( chr_count > max_count ) chr_count = max_count; + + // Convert ASCII string into UTF-16 + for ( size_t i = 0; i < chr_count; i++ ) { + _desc_str[1 + i] = str[i]; + } + break; + } + + // first byte is length (including header), second byte is string type + _desc_str[0] = (uint16_t) ((TUSB_DESC_STRING << 8) | (2 * chr_count + 2)); + + return _desc_str; +} diff --git a/examples/device/printer_to_hid/src/usb_descriptors.h b/examples/device/printer_to_hid/src/usb_descriptors.h new file mode 100644 index 000000000..53c4e1fbd --- /dev/null +++ b/examples/device/printer_to_hid/src/usb_descriptors.h @@ -0,0 +1,30 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + */ + +#ifndef USB_DESCRIPTORS_H_ +#define USB_DESCRIPTORS_H_ + +REPORT_ID_KEYBOARD = 1 + +#endif /* USB_DESCRIPTORS_H_ */ diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 48dc75e50..00f466007 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -19,6 +19,7 @@ function(tinyusb_sources_get OUTPUT_VAR) ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/mtp/mtp_device.c ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/net/ecm_rndis_device.c ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/net/ncm_device.c + ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/printer/printer_device.c ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/usbtmc/usbtmc_device.c ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/vendor/vendor_device.c ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/video/video_device.c diff --git a/src/class/printer/printer.h b/src/class/printer/printer.h new file mode 100644 index 000000000..4cd1d62fc --- /dev/null +++ b/src/class/printer/printer.h @@ -0,0 +1,277 @@ +#include +#include "tusb_option.h" + +#if (CFG_TUD_ENABLED && CFG_TUD_PRINTER) + + #include "device/usbd.h" + #include "device/usbd_pvt.h" + +// #include "bsp/board_api.h" + + #include "printer_device.h" + #include "printer.h" + + +//--------------------------------------------------------------------+ +// MACRO CONSTANT TYPEDEF +//--------------------------------------------------------------------+ + +typedef struct { + uint8_t itf_num; + uint8_t ep_in; + uint8_t ep_out; + /*------------- From this point, data is not cleared by bus reset -------------*/ + + // FIFO + tu_fifo_t rx_ff; + tu_fifo_t tx_ff; + + uint8_t rx_ff_buf[CFG_TUD_PRINTER_RX_BUFSIZE]; + uint8_t tx_ff_buf[CFG_TUD_PRINTER_TX_BUFSIZE]; + + OSAL_MUTEX_DEF(rx_ff_mutex); + OSAL_MUTEX_DEF(tx_ff_mutex); +} printer_interface_t; + + #define ITF_MEM_RESET_SIZE offsetof(printer_interface_t, wanted_char) + +typedef struct { + TUD_EPBUF_DEF(epout, CFG_TUD_PRINTER_EP_BUFSIZE); + TUD_EPBUF_DEF(epin, CFG_TUD_PRINTER_EP_BUFSIZE); +} printer_epbuf_t; + +static printer_interface_t _printer_itf[CFG_TUD_PRINTER]; +CFG_TUD_MEM_SECTION static printer_epbuf_t _printer_epbuf[CFG_TUD_PRINTER]; + + +//--------------------------------------------------------------------+ +// INTERNAL OBJECT & FUNCTION DECLARATION +//--------------------------------------------------------------------+ + +static tud_printer_configure_fifo_t _printer_fifo_cfg; + +static bool _prep_out_transaction(uint8_t itf) { + const uint8_t rhport = 0; + printer_interface_t *p_printer = &_printer_itf[itf]; + printer_epbuf_t *p_epbuf = &_printer_epbuf[itf]; + + // Skip if usb is not ready yet + TU_VERIFY(tud_ready() && p_printer->ep_out); + + uint16_t available = tu_fifo_remaining(&p_printer->rx_ff); + + // Prepare for incoming data but only allow what we can store in the ring buffer. + // TODO Actually we can still carry out the transfer, keeping count of received bytes + // and slowly move it to the FIFO when read(). + // This pre-check reduces endpoint claiming + TU_VERIFY(available >= CFG_TUD_PRINTER_EP_BUFSIZE); + + // claim endpoint + TU_VERIFY(usbd_edpt_claim(rhport, p_printer->ep_out)); + + // fifo can be changed before endpoint is claimed + available = tu_fifo_remaining(&p_printer->rx_ff); + + if (available >= CFG_TUD_PRINTER_EP_BUFSIZE) { + return usbd_edpt_xfer(rhport, p_printer->ep_out, p_epbuf->epout, CFG_TUD_PRINTER_EP_BUFSIZE); + } else { + // Release endpoint since we don't make any transfer + usbd_edpt_release(rhport, p_printer->ep_out); + return false; + } +} + +//--------------------------------------------------------------------+ +// APPLICATION API +//--------------------------------------------------------------------+ + +uint32_t tud_printer_n_available(uint8_t itf) { + return tu_fifo_count(&_printer_itf[itf].rx_ff); +} + +uint32_t tud_printer_n_read(uint8_t itf, void *buffer, uint32_t bufsize) { + printer_interface_t *p_printer = &_printer_itf[itf]; + uint32_t num_read = tu_fifo_read_n(&p_printer->rx_ff, buffer, (uint16_t)TU_MIN(bufsize, UINT16_MAX)); + _prep_out_transaction(itf); + return num_read; +} + +bool tud_printer_n_peek(uint8_t itf, uint8_t *chr) { + return tu_fifo_peek(&_printer_itf[itf].rx_ff, chr); +} + +void tud_printer_n_read_flush(uint8_t itf) { + printer_interface_t *p_printer = &_printer_itf[itf]; + tu_fifo_clear(&p_printer->rx_ff); + _prep_out_transaction(itf); +} + + +//--------------------------------------------------------------------+ +// USBD PRINTER DRIVER API +//--------------------------------------------------------------------+ + +void printer_init(void) { + tu_memclr(_printer_itf, sizeof(_printer_itf)); + tu_memclr(&_printer_fifo_cfg, sizeof(_printer_fifo_cfg)); + + for (uint8_t i = 0; i < CFG_TUD_PRINTER; i++) { + printer_interface_t *p_printer = &_printer_itf[i]; + + tu_fifo_config(&p_printer->rx_ff, p_printer->rx_ff_buf, TU_ARRAY_SIZE(p_printer->rx_ff_buf), 1, false); + tu_fifo_config(&p_printer->tx_ff, p_printer->tx_ff_buf, TU_ARRAY_SIZE(p_printer->tx_ff_buf), 1, true); + + #if OSAL_MUTEX_REQUIRED + osal_mutex_t mutex_rd = osal_mutex_create(&p_printer->rx_ff_mutex); + osal_mutex_t mutex_wr = osal_mutex_create(&p_printer->tx_ff_mutex); + TU_ASSERT(mutex_rd != NULL && mutex_wr != NULL, ); + + tu_fifo_config_mutex(&p_printer->rx_ff, NULL, mutex_rd); + tu_fifo_config_mutex(&p_printer->tx_ff, mutex_wr, NULL); + #endif + } +} + +bool printer_deinit(void) { + #if OSAL_MUTEX_REQUIRED + for (uint8_t i = 0; i < CFG_TUD_PRINTER; i++) { + printer_interface_t *p_printer = &_printer_itf[i]; + osal_mutex_t mutex_rd = p_printer->rx_ff.mutex_rd; + osal_mutex_t mutex_wr = p_printer->tx_ff.mutex_rd; + + if (mutex_rd) { + osal_mutex_delete(mutex_rd); + tu_fifo_config_mutex(&p_printer->rx_ff, NULL, NULL); + } + + if (mutex_wr) { + osal_mutex_delete(mutex_wr); + tu_fifo_config_mutex(&p_printer->tx_ff, NULL, NULL); + } + } + #endif + + return true; +} + +void printer_reset(uint8_t rhport) { + (void)rhport; + + for (uint8_t i = 0; i < CFG_TUD_PRINTER; i++) { + printer_interface_t *p_printer = &_printer_itf[i]; + + tu_memclr(p_printer, sizeof(p_printer)); + if (!_printer_fifo_cfg.rx_persistent) { + tu_fifo_clear(&p_printer->rx_ff); + } + if (!_printer_fifo_cfg.tx_persistent) { + tu_fifo_clear(&p_printer->tx_ff); + } + // tu_fifo_set_overwritable(&p_printer->rx_ff, true); + tu_fifo_set_overwritable(&p_printer->tx_ff, true); + } +} + +uint16_t printer_open(uint8_t rhport, const tusb_desc_interface_t *itf_desc, uint16_t max_len) { + TU_VERIFY(TUSB_CLASS_PRINTER == itf_desc->bInterfaceClass, 0); + + // Identify available interface to open + printer_interface_t *p_printer; + uint8_t printer_id; + for (printer_id = 0; printer_id < CFG_TUD_PRINTER; printer_id++) { + p_printer = &_printer_itf[printer_id]; + if (p_printer->ep_out == 0) { + break; + } + } + TU_ASSERT(printer_id < CFG_TUD_PRINTER); + + //------------- Interface -------------// + uint16_t drv_len = sizeof(tusb_desc_interface_t); + + //------------- Endpoints -------------// + TU_ASSERT(itf_desc->bNumEndpoints == 2); + drv_len += 2 * sizeof(tusb_desc_endpoint_t); + p_printer->itf_num = 2; + const uint8_t *p_desc = tu_desc_next(itf_desc); + TU_ASSERT(usbd_open_edpt_pair(rhport, p_desc, 2, TUSB_XFER_BULK, &p_printer->ep_out, &p_printer->ep_in), 0); + + _prep_out_transaction(printer_id); + + return drv_len; +} + +bool printer_control_xfer_cb(uint8_t rhport, uint8_t stage, const tusb_control_request_t *request) { + TU_VERIFY(request->bmRequestType_bit.recipient == TUSB_REQ_RCPT_INTERFACE); + + if (request->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD) { + //------------- STD Request -------------// + if (stage != CONTROL_STAGE_SETUP) { + return true; + } + } else if (request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS) { + switch (request->bRequest) { + // https://www.usb.org/sites/default/files/usbprint11a021811.pdf + case PRINTER_REQ_CONTROL_GET_DEVICE_ID: + if (stage == CONTROL_STAGE_SETUP) { + const char deviceId[] = "MANUFACTURER:ACME Manufacturing;" + "MODEL:LaserBeam 9;" + "COMMAND SET:PS;" + "COMMENT:Anything you like;" + "ACTIVE COMMAND SET:PS;"; + char buffer[256]; + strcpy(buffer + 2, deviceId); + buffer[0] = 0x00; + buffer[1] = strlen(deviceId); + return tud_control_xfer(rhport, request, buffer, strlen(deviceId) + 2); + } + break; + case PRINTER_REQ_CONTROL_GET_PORT_STATUS: + if (stage == CONTROL_STAGE_SETUP) { + static uint8_t port_status = (0 << 3) | (1 << 1) | (1 << 2); // ~Paper empty + Selected + NoError + return tud_control_xfer(rhport, request, &port_status, sizeof(port_status)); + } + break; + case PRINTER_REQ_CONTROL_SOFT_RESET: + if (stage == CONTROL_STAGE_SETUP) { + return false; // what to do ? + } + break; + default: + return false; + } + } else { + return false; + } + return true; +} + +bool printer_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) { + uint8_t itf; + printer_interface_t *p_printer; + + // Identify which interface to use + for (itf = 0; itf < CFG_TUD_PRINTER; itf++) { + p_printer = &_printer_itf[itf]; + if (ep_addr == p_printer->ep_out) { + break; + } + } + TU_ASSERT(itf < CFG_TUD_PRINTER); + printer_epbuf_t *p_epbuf = &_printer_epbuf[itf]; + + // Received new data + if (ep_addr == p_printer->ep_out) { + tu_fifo_write_n(&p_printer->rx_ff, p_epbuf->epout, (uint16_t)xferred_bytes); + // invoke receive callback (if there is still data) + if (tud_printer_rx_cb && !tu_fifo_empty(&p_printer->rx_ff)) { + tud_printer_rx_cb(itf, xferred_bytes); + } + // prepare for OUT transaction + _prep_out_transaction(itf); + } + + return true; +} + +#endif diff --git a/src/class/printer/printer_device.c b/src/class/printer/printer_device.c new file mode 100644 index 000000000..efeae100f --- /dev/null +++ b/src/class/printer/printer_device.c @@ -0,0 +1,306 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2026 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "tusb_option.h" + +#if (CFG_TUD_ENABLED && CFG_TUD_PRINTER) + + //--------------------------------------------------------------------+ + // INCLUDE + //--------------------------------------------------------------------+ + #include "device/usbd.h" + #include "device/usbd_pvt.h" + + #include "printer_device.h" + +//--------------------------------------------------------------------+ +// MACRO CONSTANT TYPEDEF +//--------------------------------------------------------------------+ + +typedef struct { + uint8_t itf_num; + uint8_t ep_out; // Bulk Out endpoint + uint8_t ep_in; // optional Bulk In endpoint + + /*------------- From this point, data is not cleared by bus reset -------------*/ + + // FIFO + tu_fifo_t rx_ff; + tu_fifo_t tx_ff; + + uint8_t rx_ff_buf[CFG_TUD_PRINTER_RX_BUFSIZE]; + uint8_t tx_ff_buf[CFG_TUD_PRINTER_TX_BUFSIZE]; + + OSAL_MUTEX_DEF(rx_ff_mutex); + OSAL_MUTEX_DEF(tx_ff_mutex); +} printer_interface_t; + +typedef struct { + TUD_EPBUF_DEF(epout, CFG_TUD_PRINTER_EP_BUFSIZE); + TUD_EPBUF_DEF(epin, CFG_TUD_PRINTER_EP_BUFSIZE); +} printer_epbuf_t; + +static printer_interface_t _printer_itf[CFG_TUD_PRINTER]; +CFG_TUD_MEM_SECTION static printer_epbuf_t _printer_epbuf[CFG_TUD_PRINTER]; + + +//--------------------------------------------------------------------+ +// INTERNAL OBJECT & FUNCTION DECLARATION +//--------------------------------------------------------------------+ + +static tud_printer_configure_fifo_t _printer_fifo_cfg; + +static bool _prep_out_transaction(uint8_t itf) { + const uint8_t rhport = 0; + printer_interface_t *p_printer = &_printer_itf[itf]; + printer_epbuf_t *p_epbuf = &_printer_epbuf[itf]; + + // Skip if usb is not ready yet + TU_VERIFY(tud_ready() && p_printer->ep_out); + + uint16_t available = tu_fifo_remaining(&p_printer->rx_ff); + + // Prepare for incoming data but only allow what we can store in the ring buffer. + // TODO Actually we can still carry out the transfer, keeping count of received bytes + // and slowly move it to the FIFO when read(). + // This pre-check reduces endpoint claiming + TU_VERIFY(available >= CFG_TUD_PRINTER_EP_BUFSIZE); + + // claim endpoint + TU_VERIFY(usbd_edpt_claim(rhport, p_printer->ep_out)); + + // fifo can be changed before endpoint is claimed + available = tu_fifo_remaining(&p_printer->rx_ff); + + if (available >= CFG_TUD_PRINTER_EP_BUFSIZE) { + return usbd_edpt_xfer(rhport, p_printer->ep_out, p_epbuf->epout, CFG_TUD_PRINTER_EP_BUFSIZE); + } else { + // Release endpoint since we don't make any transfer + usbd_edpt_release(rhport, p_printer->ep_out); + return false; + } +} + +//--------------------------------------------------------------------+ +// Weak stubs: invoked if no strong implementation is available +//--------------------------------------------------------------------+ +TU_ATTR_WEAK void tud_printer_rx_cb(uint8_t itf, size_t n) { + (void)itf; + (void)n; +} + +//--------------------------------------------------------------------+ +// APPLICATION API +//--------------------------------------------------------------------+ +uint32_t tud_printer_n_available(uint8_t itf) { + return tu_fifo_count(&_printer_itf[itf].rx_ff); +} + +uint32_t tud_printer_n_read(uint8_t itf, void *buffer, uint32_t bufsize) { + printer_interface_t *p_printer = &_printer_itf[itf]; + uint32_t num_read = tu_fifo_read_n(&p_printer->rx_ff, buffer, (uint16_t)TU_MIN(bufsize, UINT16_MAX)); + _prep_out_transaction(itf); + return num_read; +} + +bool tud_printer_n_peek(uint8_t itf, uint8_t *chr) { + return tu_fifo_peek(&_printer_itf[itf].rx_ff, chr); +} + +void tud_printer_n_read_flush(uint8_t itf) { + printer_interface_t *p_printer = &_printer_itf[itf]; + tu_fifo_clear(&p_printer->rx_ff); + _prep_out_transaction(itf); +} + + +//--------------------------------------------------------------------+ +// USBD-CLASS API +//--------------------------------------------------------------------+ +void printerd_init(void) { + tu_memclr(_printer_itf, sizeof(_printer_itf)); + tu_memclr(&_printer_fifo_cfg, sizeof(_printer_fifo_cfg)); + + for (uint8_t i = 0; i < CFG_TUD_PRINTER; i++) { + printer_interface_t *p_printer = &_printer_itf[i]; + + tu_fifo_config(&p_printer->rx_ff, p_printer->rx_ff_buf, TU_ARRAY_SIZE(p_printer->rx_ff_buf), 1, false); + tu_fifo_config(&p_printer->tx_ff, p_printer->tx_ff_buf, TU_ARRAY_SIZE(p_printer->tx_ff_buf), 1, true); + + #if OSAL_MUTEX_REQUIRED + osal_mutex_t mutex_rd = osal_mutex_create(&p_printer->rx_ff_mutex); + osal_mutex_t mutex_wr = osal_mutex_create(&p_printer->tx_ff_mutex); + TU_ASSERT(mutex_rd != NULL && mutex_wr != NULL, ); + + tu_fifo_config_mutex(&p_printer->rx_ff, NULL, mutex_rd); + tu_fifo_config_mutex(&p_printer->tx_ff, mutex_wr, NULL); + #endif + } +} + +bool printerd_deinit(void) { + #if OSAL_MUTEX_REQUIRED + for (uint8_t i = 0; i < CFG_TUD_PRINTER; i++) { + printer_interface_t *p_printer = &_printer_itf[i]; + osal_mutex_t mutex_rd = p_printer->rx_ff.mutex_rd; + osal_mutex_t mutex_wr = p_printer->tx_ff.mutex_rd; + + if (mutex_rd) { + osal_mutex_delete(mutex_rd); + tu_fifo_config_mutex(&p_printer->rx_ff, NULL, NULL); + } + + if (mutex_wr) { + osal_mutex_delete(mutex_wr); + tu_fifo_config_mutex(&p_printer->tx_ff, NULL, NULL); + } + } + #endif + + return true; +} + +void printerd_reset(uint8_t rhport) { + (void)rhport; + + for (uint8_t i = 0; i < CFG_TUD_PRINTER; i++) { + printer_interface_t *p_printer = &_printer_itf[i]; + + tu_memclr(p_printer, sizeof(p_printer)); + if (!_printer_fifo_cfg.rx_persistent) { + tu_fifo_clear(&p_printer->rx_ff); + } + if (!_printer_fifo_cfg.tx_persistent) { + tu_fifo_clear(&p_printer->tx_ff); + } + // tu_fifo_set_overwritable(&p_printer->rx_ff, true); + tu_fifo_set_overwritable(&p_printer->tx_ff, true); + } +} + +uint16_t printerd_open(uint8_t rhport, const tusb_desc_interface_t *itf_desc, uint16_t max_len) { + TU_VERIFY(TUSB_CLASS_PRINTER == itf_desc->bInterfaceClass, 0); + + // Identify available interface to open + printer_interface_t *p_printer; + uint8_t printer_id; + for (printer_id = 0; printer_id < CFG_TUD_PRINTER; printer_id++) { + p_printer = &_printer_itf[printer_id]; + if (p_printer->ep_out == 0) { + break; + } + } + TU_ASSERT(printer_id < CFG_TUD_PRINTER); + + //------------- Interface -------------// + uint16_t drv_len = sizeof(tusb_desc_interface_t); + + //------------- Endpoints -------------// + TU_ASSERT(itf_desc->bNumEndpoints == 2); + drv_len += 2 * sizeof(tusb_desc_endpoint_t); + p_printer->itf_num = 2; + const uint8_t *p_desc = tu_desc_next(itf_desc); + TU_ASSERT(usbd_open_edpt_pair(rhport, p_desc, 2, TUSB_XFER_BULK, &p_printer->ep_out, &p_printer->ep_in), 0); + + _prep_out_transaction(printer_id); + + return drv_len; +} + +bool printerd_control_xfer_cb(uint8_t rhport, uint8_t stage, const tusb_control_request_t *request) { + TU_VERIFY(request->bmRequestType_bit.recipient == TUSB_REQ_RCPT_INTERFACE); + + if (request->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD) { + //------------- STD Request -------------// + if (stage != CONTROL_STAGE_SETUP) { + return true; + } + } else if (request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS) { + switch (request->bRequest) { + // https://www.usb.org/sites/default/files/usbprint11a021811.pdf + case PRINTER_REQ_CONTROL_GET_DEVICE_ID: + if (stage == CONTROL_STAGE_SETUP) { + const char deviceId[] = "MANUFACTURER:ACME Manufacturing;" + "MODEL:LaserBeam 9;" + "COMMAND SET:PS;" + "COMMENT:Anything you like;" + "ACTIVE COMMAND SET:PS;"; + char buffer[256]; + strcpy(buffer + 2, deviceId); + buffer[0] = 0x00; + buffer[1] = strlen(deviceId); + return tud_control_xfer(rhport, request, buffer, strlen(deviceId) + 2); + } + break; + case PRINTER_REQ_CONTROL_GET_PORT_STATUS: + if (stage == CONTROL_STAGE_SETUP) { + static uint8_t port_status = (0 << 3) | (1 << 1) | (1 << 2); // ~Paper empty + Selected + NoError + return tud_control_xfer(rhport, request, &port_status, sizeof(port_status)); + } + break; + case PRINTER_REQ_CONTROL_SOFT_RESET: + if (stage == CONTROL_STAGE_SETUP) { + return false; // what to do ? + } + break; + default: + return false; + } + } else { + return false; + } + return true; +} + +bool printerd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) { + uint8_t itf; + printer_interface_t *p_printer; + + // Identify which interface to use + for (itf = 0; itf < CFG_TUD_PRINTER; itf++) { + p_printer = &_printer_itf[itf]; + if (ep_addr == p_printer->ep_out) { + break; + } + } + TU_ASSERT(itf < CFG_TUD_PRINTER); + printer_epbuf_t *p_epbuf = &_printer_epbuf[itf]; + + // Received new data + if (ep_addr == p_printer->ep_out) { + tu_fifo_write_n(&p_printer->rx_ff, p_epbuf->epout, (uint16_t)xferred_bytes); + // invoke receive callback (if there is still data) + if (tud_printer_rx_cb && !tu_fifo_empty(&p_printer->rx_ff)) { + tud_printer_rx_cb(itf, xferred_bytes); + } + // prepare for OUT transaction + _prep_out_transaction(itf); + } + + return true; +} + +#endif diff --git a/src/class/printer/printer_device.h b/src/class/printer/printer_device.h new file mode 100644 index 000000000..8c21e39ce --- /dev/null +++ b/src/class/printer/printer_device.h @@ -0,0 +1,79 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2026 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#ifndef TUSB_PRINTER_DEVICE_H_ +#define TUSB_PRINTER_DEVICE_H_ + +#include "printer.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct TU_ATTR_PACKED { + uint8_t rx_persistent : 1; // keep rx fifo on bus reset or disconnect + uint8_t tx_persistent : 1; // keep tx fifo on bus reset or disconnect +} tud_printer_configure_fifo_t; + +//--------------------------------------------------------------------+ +// Application API (Multiple Ports) i.e. CFG_TUD_PRINTER > 1 +//--------------------------------------------------------------------+ + +// Get the number of bytes available for reading +uint32_t tud_printer_n_available(uint8_t itf); + +// Read received bytes +uint32_t tud_printer_n_read(uint8_t itf, void *buffer, uint32_t bufsize); + +// Clear the received FIFO +void tud_printer_n_read_flush(uint8_t itf); + +// Get a byte from FIFO without removing it +bool tud_printer_n_peek(uint8_t itf, uint8_t *ui8); + +//--------------------------------------------------------------------+ +// Application Callback API (weak is optional) +//--------------------------------------------------------------------+ + +// Invoked when received new data +TU_ATTR_WEAK void tud_printer_rx_cb(uint8_t itf, size_t n); + +//--------------------------------------------------------------------+ +// Internal Class Driver API +//--------------------------------------------------------------------+ +void printerd_init(void); +bool printerd_deinit(void); +void printerd_reset(uint8_t rhport); +uint16_t printerd_open(uint8_t rhport, const tusb_desc_interface_t *itf_desc, uint16_t max_len); +bool printerd_control_xfer_cb(uint8_t rhport, uint8_t stage, const tusb_control_request_t *request); +bool printerd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes); + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/device/usbd.c b/src/device/usbd.c index 1e21c667a..32b3a3ee2 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -334,6 +334,19 @@ static const usbd_class_driver_t _usbd_driver[] = { .sof = NULL }, #endif + + #if CFG_TUD_PRINTER + { + .name = DRIVER_NAME("PRINTER"), + .init = printerd_init, + .deinit = printerd_deinit, + .reset = printerd_reset, + .open = printerd_open, + .control_xfer_cb = printerd_control_xfer_cb, + .xfer_cb = printerd_xfer_cb, + .sof = NULL + }, + #endif }; enum { BUILTIN_DRIVER_COUNT = TU_ARRAY_SIZE(_usbd_driver) }; diff --git a/src/device/usbd.h b/src/device/usbd.h index bd5a3c395..3b296feea 100644 --- a/src/device/usbd.h +++ b/src/device/usbd.h @@ -312,6 +312,21 @@ bool tud_vendor_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_requ 7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0 +//--------------------------------------------------------------------+ +// Printer Descriptor Templates +//--------------------------------------------------------------------+ + +#define TUD_PRINTER_DESC_LEN (9 + 7 + 7) // one interface, two endpoints + +#define TUD_PRINTER_DESCRIPTOR(_itfnum, _stridx, _epout, _epin, _epsize) \ + /* Interface */\ + 9, TUSB_DESC_INTERFACE, _itfnum, 0, 2, TUSB_CLASS_PRINTER, 1, 2, _stridx,\ + /* Endpoint Out */\ + 7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0,\ + /* Endpoint In */\ + 7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0 + + //--------------------------------------------------------------------+ // HID Descriptor Templates //--------------------------------------------------------------------+ diff --git a/src/tinyusb.mk b/src/tinyusb.mk index 8f9d52de9..e7d1c0b5b 100644 --- a/src/tinyusb.mk +++ b/src/tinyusb.mk @@ -15,6 +15,7 @@ TINYUSB_SRC_C += \ src/class/mtp/mtp_device.c \ src/class/net/ecm_rndis_device.c \ src/class/net/ncm_device.c \ + src/class/printer/printer_device.c \ src/class/usbtmc/usbtmc_device.c \ src/class/video/video_device.c \ src/class/vendor/vendor_device.c \ diff --git a/src/tusb.h b/src/tusb.h index 62b3b9783..256a239e7 100644 --- a/src/tusb.h +++ b/src/tusb.h @@ -92,6 +92,10 @@ #include "class/mtp/mtp_device.h" #endif + #if CFG_TUD_PRINTER + #include "class/printer/printer_device.h" + #endif + #if CFG_TUD_AUDIO #include "class/audio/audio_device.h" #endif diff --git a/src/tusb_option.h b/src/tusb_option.h index 64fe899db..80cbeab36 100644 --- a/src/tusb_option.h +++ b/src/tusb_option.h @@ -614,6 +614,10 @@ #define CFG_TUD_NCM 0 #endif +#ifndef CFG_TUD_PRINTER + #define CFG_TUD_PRINTER 0 +#endif + #ifndef CFG_TUD_EDPT_DEDICATED_HWFIFO #define CFG_TUD_EDPT_DEDICATED_HWFIFO 0 #endif diff --git a/tools/iar_template.ipcf b/tools/iar_template.ipcf index caddda826..035e40b94 100644 --- a/tools/iar_template.ipcf +++ b/tools/iar_template.ipcf @@ -69,6 +69,11 @@ $TUSB_DIR$/src/class/net/ncm.h $TUSB_DIR$/src/class/net/net_device.h + + $TUSB_DIR$/src/class/printer/printer_device.c + $TUSB_DIR$/src/class/printer/printer.h + $TUSB_DIR$/src/class/printer/printer_device.h + $TUSB_DIR$/src/class/usbtmc/usbtmc_device.c $TUSB_DIR$/src/class/usbtmc/usbtmc.h