From 424735d44041fc478b572f973d997829b402153d Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 18 Jun 2018 14:05:24 +0700 Subject: rename subfolder source to src --- src/class/cdc/cdc.h | 412 +++++++++++++++++++++++++++ src/class/cdc/cdc_device.c | 302 ++++++++++++++++++++ src/class/cdc/cdc_device.h | 120 ++++++++ src/class/cdc/cdc_host.c | 243 ++++++++++++++++ src/class/cdc/cdc_host.h | 163 +++++++++++ src/class/cdc/cdc_rndis.h | 313 ++++++++++++++++++++ src/class/cdc/cdc_rndis_host.c | 293 +++++++++++++++++++ src/class/cdc/cdc_rndis_host.h | 79 ++++++ src/class/custom/custom_device.c | 105 +++++++ src/class/custom/custom_device.h | 71 +++++ src/class/custom/custom_host.c | 160 +++++++++++ src/class/custom/custom_host.h | 87 ++++++ src/class/hid/hid.h | 595 +++++++++++++++++++++++++++++++++++++++ src/class/hid/hid_device.c | 322 +++++++++++++++++++++ src/class/hid/hid_device.h | 217 ++++++++++++++ src/class/hid/hid_host.c | 304 ++++++++++++++++++++ src/class/hid/hid_host.h | 231 +++++++++++++++ src/class/msc/msc.h | 376 +++++++++++++++++++++++++ src/class/msc/msc_device.c | 396 ++++++++++++++++++++++++++ src/class/msc/msc_device.h | 158 +++++++++++ src/class/msc/msc_host.c | 430 ++++++++++++++++++++++++++++ src/class/msc/msc_host.h | 219 ++++++++++++++ 22 files changed, 5596 insertions(+) create mode 100644 src/class/cdc/cdc.h create mode 100644 src/class/cdc/cdc_device.c create mode 100644 src/class/cdc/cdc_device.h create mode 100644 src/class/cdc/cdc_host.c create mode 100644 src/class/cdc/cdc_host.h create mode 100644 src/class/cdc/cdc_rndis.h create mode 100644 src/class/cdc/cdc_rndis_host.c create mode 100644 src/class/cdc/cdc_rndis_host.h create mode 100644 src/class/custom/custom_device.c create mode 100644 src/class/custom/custom_device.h create mode 100644 src/class/custom/custom_host.c create mode 100644 src/class/custom/custom_host.h create mode 100644 src/class/hid/hid.h create mode 100644 src/class/hid/hid_device.c create mode 100644 src/class/hid/hid_device.h create mode 100644 src/class/hid/hid_host.c create mode 100644 src/class/hid/hid_host.h create mode 100644 src/class/msc/msc.h create mode 100644 src/class/msc/msc_device.c create mode 100644 src/class/msc/msc_device.h create mode 100644 src/class/msc/msc_host.c create mode 100644 src/class/msc/msc_host.h (limited to 'src/class') diff --git a/src/class/cdc/cdc.h b/src/class/cdc/cdc.h new file mode 100644 index 000000000..b0c4f90d4 --- /dev/null +++ b/src/class/cdc/cdc.h @@ -0,0 +1,412 @@ +/**************************************************************************/ +/*! + @file cdc.h + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +/** \ingroup group_class + * \defgroup ClassDriver_CDC Communication Device Class (CDC) + * Currently only Abstract Control Model subclass is supported + * @{ */ + +#ifndef _TUSB_CDC_H__ +#define _TUSB_CDC_H__ + +#include "common/tusb_common.h" + +#ifdef __cplusplus + extern "C" { +#endif + +/** \defgroup ClassDriver_CDC_Common Common Definitions + * @{ */ + + +/// CDC Pipe ID, used to indicate which pipe the API is addressing to (Notification, Out, In) +typedef enum +{ + CDC_PIPE_NOTIFICATION , ///< Notification pipe + CDC_PIPE_DATA_IN , ///< Data in pipe + CDC_PIPE_DATA_OUT , ///< Data out pipe + CDC_PIPE_ERROR , ///< Invalid Pipe ID +}cdc_pipeid_t; + +//--------------------------------------------------------------------+ +// CDC COMMUNICATION INTERFACE CLASS +//--------------------------------------------------------------------+ +/// Communication Interface Subclass Codes +typedef enum +{ + CDC_COMM_SUBCLASS_DIRECT_LINE_CONTROL_MODEL = 0x01 , ///< Direct Line Control Model [USBPSTN1.2] + CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL , ///< Abstract Control Model [USBPSTN1.2] + CDC_COMM_SUBCLASS_TELEPHONE_CONTROL_MODEL , ///< Telephone Control Model [USBPSTN1.2] + CDC_COMM_SUBCLASS_MULTICHANNEL_CONTROL_MODEL , ///< Multi-Channel Control Model [USBISDN1.2] + CDC_COMM_SUBCLASS_CAPI_CONTROL_MODEL , ///< CAPI Control Model [USBISDN1.2] + CDC_COMM_SUBCLASS_ETHERNET_NETWORKING_CONTROL_MODEL , ///< Ethernet Networking Control Model [USBECM1.2] + CDC_COMM_SUBCLASS_ATM_NETWORKING_CONTROL_MODEL , ///< ATM Networking Control Model [USBATM1.2] + CDC_COMM_SUBCLASS_WIRELESS_HANDSET_CONTROL_MODEL , ///< Wireless Handset Control Model [USBWMC1.1] + CDC_COMM_SUBCLASS_DEVICE_MANAGEMENT , ///< Device Management [USBWMC1.1] + CDC_COMM_SUBCLASS_MOBILE_DIRECT_LINE_MODEL , ///< Mobile Direct Line Model [USBWMC1.1] + CDC_COMM_SUBCLASS_OBEX , ///< OBEX [USBWMC1.1] + CDC_COMM_SUBCLASS_ETHERNET_EMULATION_MODEL ///< Ethernet Emulation Model [USBEEM1.0] +} cdc_comm_sublcass_type_t; + +/// Communication Interface Protocol Codes +typedef enum +{ + CDC_COMM_PROTOCOL_ATCOMMAND = 0x01 , ///< AT Commands: V.250 etc + CDC_COMM_PROTOCOL_ATCOMMAND_PCCA_101 , ///< AT Commands defined by PCCA-101 + CDC_COMM_PROTOCOL_ATCOMMAND_PCCA_101_AND_ANNEXO , ///< AT Commands defined by PCCA-101 & Annex O + CDC_COMM_PROTOCOL_ATCOMMAND_GSM_707 , ///< AT Commands defined by GSM 07.07 + CDC_COMM_PROTOCOL_ATCOMMAND_3GPP_27007 , ///< AT Commands defined by 3GPP 27.007 + CDC_COMM_PROTOCOL_ATCOMMAND_CDMA , ///< AT Commands defined by TIA for CDMA + CDC_COMM_PROTOCOL_ETHERNET_EMULATION_MODEL ///< Ethernet Emulation Model +} cdc_comm_protocol_type_t; + +//------------- SubType Descriptor in COMM Functional Descriptor -------------// +/// Communication Interface SubType Descriptor +typedef enum +{ + CDC_FUNC_DESC_HEADER = 0x00 , ///< Header Functional Descriptor, which marks the beginning of the concatenated set of functional descriptors for the interface. + CDC_FUNC_DESC_CALL_MANAGEMENT = 0x01 , ///< Call Management Functional Descriptor. + CDC_FUNC_DESC_ABSTRACT_CONTROL_MANAGEMENT = 0x02 , ///< Abstract Control Management Functional Descriptor. + CDC_FUNC_DESC_DIRECT_LINE_MANAGEMENT = 0x03 , ///< Direct Line Management Functional Descriptor. + CDC_FUNC_DESC_TELEPHONE_RINGER = 0x04 , ///< Telephone Ringer Functional Descriptor. + CDC_FUNC_DESC_TELEPHONE_CALL_AND_LINE_STATE_REPORTING_CAPACITY = 0x05 , ///< Telephone Call and Line State Reporting Capabilities Functional Descriptor. + CDC_FUNC_DESC_UNION = 0x06 , ///< Union Functional Descriptor + CDC_FUNC_DESC_COUNTRY_SELECTION = 0x07 , ///< Country Selection Functional Descriptor + CDC_FUNC_DESC_TELEPHONE_OPERATIONAL_MODES = 0x08 , ///< Telephone Operational ModesFunctional Descriptor + CDC_FUNC_DESC_USB_TERMINAL = 0x09 , ///< USB Terminal Functional Descriptor + CDC_FUNC_DESC_NETWORK_CHANNEL_TERMINAL = 0x0A , ///< Network Channel Terminal Descriptor + CDC_FUNC_DESC_PROTOCOL_UNIT = 0x0B , ///< Protocol Unit Functional Descriptor + CDC_FUNC_DESC_EXTENSION_UNIT = 0x0C , ///< Extension Unit Functional Descriptor + CDC_FUNC_DESC_MULTICHANEL_MANAGEMENT = 0x0D , ///< Multi-Channel Management Functional Descriptor + CDC_FUNC_DESC_CAPI_CONTROL_MANAGEMENT = 0x0E , ///< CAPI Control Management Functional Descriptor + CDC_FUNC_DESC_ETHERNET_NETWORKING = 0x0F , ///< Ethernet Networking Functional Descriptor + CDC_FUNC_DESC_ATM_NETWORKING = 0x10 , ///< ATM Networking Functional Descriptor + CDC_FUNC_DESC_WIRELESS_HANDSET_CONTROL_MODEL = 0x11 , ///< Wireless Handset Control Model Functional Descriptor + CDC_FUNC_DESC_MOBILE_DIRECT_LINE_MODEL = 0x12 , ///< Mobile Direct Line Model Functional Descriptor + CDC_FUNC_DESC_MOBILE_DIRECT_LINE_MODEL_DETAIL = 0x13 , ///< MDLM Detail Functional Descriptor + CDC_FUNC_DESC_DEVICE_MANAGEMENT_MODEL = 0x14 , ///< Device Management Model Functional Descriptor + CDC_FUNC_DESC_OBEX = 0x15 , ///< OBEX Functional Descriptor + CDC_FUNC_DESC_COMMAND_SET = 0x16 , ///< Command Set Functional Descriptor + CDC_FUNC_DESC_COMMAND_SET_DETAIL = 0x17 , ///< Command Set Detail Functional Descriptor + CDC_FUNC_DESC_TELEPHONE_CONTROL_MODEL = 0x18 , ///< Telephone Control Model Functional Descriptor + CDC_FUNC_DESC_OBEX_SERVICE_IDENTIFIER = 0x19 ///< OBEX Service Identifier Functional Descriptor +}cdc_func_desc_type_t; + +//--------------------------------------------------------------------+ +// CDC DATA INTERFACE CLASS +//--------------------------------------------------------------------+ + +// SUBCLASS code of Data Interface is not used and should/must be zero +/// Data Interface Protocol Codes +typedef enum{ + CDC_DATA_PROTOCOL_ISDN_BRI = 0x30, ///< Physical interface protocol for ISDN BRI + CDC_DATA_PROTOCOL_HDLC = 0x31, ///< HDLC + CDC_DATA_PROTOCOL_TRANSPARENT = 0x32, ///< Transparent + CDC_DATA_PROTOCOL_Q921_MANAGEMENT = 0x50, ///< Management protocol for Q.921 data link protocol + CDC_DATA_PROTOCOL_Q921_DATA_LINK = 0x51, ///< Data link protocol for Q.931 + CDC_DATA_PROTOCOL_Q921_TEI_MULTIPLEXOR = 0x52, ///< TEI-multiplexor for Q.921 data link protocol + CDC_DATA_PROTOCOL_V42BIS_DATA_COMPRESSION = 0x90, ///< Data compression procedures + CDC_DATA_PROTOCOL_EURO_ISDN = 0x91, ///< Euro-ISDN protocol control + CDC_DATA_PROTOCOL_V24_RATE_ADAPTION_TO_ISDN = 0x92, ///< V.24 rate adaptation to ISDN + CDC_DATA_PROTOCOL_CAPI_COMMAND = 0x93, ///< CAPI Commands + CDC_DATA_PROTOCOL_HOST_BASED_DRIVER = 0xFD, ///< Host based driver. Note: This protocol code should only be used in messages between host and device to identify the host driver portion of a protocol stack. + CDC_DATA_PROTOCOL_IN_PROTOCOL_UNIT_FUNCTIONAL_DESCRIPTOR = 0xFE ///< The protocol(s) are described using a ProtocolUnit Functional Descriptors on Communications Class Interface +}cdc_data_protocol_type_t; + +//--------------------------------------------------------------------+ +// MANAGEMENT ELEMENT REQUEST (CONTROL ENDPOINT) +//--------------------------------------------------------------------+ +/// Communication Interface Management Element Request Codes +typedef enum +{ + CDC_REQUEST_SEND_ENCAPSULATED_COMMAND = 0x00, ///< is used to issue a command in the format of the supported control protocol of the Communications Class interface + CDC_REQUEST_GET_ENCAPSULATED_RESPONSE = 0x01, ///< is used to request a response in the format of the supported control protocol of the Communications Class interface. + + CDC_REQUEST_SET_COMM_FEATURE = 0x02, + CDC_REQUEST_GET_COMM_FEATURE = 0x03, + CDC_REQUEST_CLEAR_COMM_FEATURE = 0x04, + + CDC_REQUEST_SET_AUX_LINE_STATE = 0x10, + CDC_REQUEST_SET_HOOK_STATE = 0x11, + CDC_REQUEST_PULSE_SETUP = 0x12, + CDC_REQUEST_SEND_PULSE = 0x13, + CDC_REQUEST_SET_PULSE_TIME = 0x14, + CDC_REQUEST_RING_AUX_JACK = 0x15, + + CDC_REQUEST_SET_LINE_CODING = 0x20, + CDC_REQUEST_GET_LINE_CODING = 0x21, + CDC_REQUEST_SET_CONTROL_LINE_STATE = 0x22, + CDC_REQUEST_SEND_BREAK = 0x23, + + CDC_REQUEST_SET_RINGER_PARMS = 0x30, + CDC_REQUEST_GET_RINGER_PARMS = 0x31, + CDC_REQUEST_SET_OPERATION_PARMS = 0x32, + CDC_REQUEST_GET_OPERATION_PARMS = 0x33, + CDC_REQUEST_SET_LINE_PARMS = 0x34, + CDC_REQUEST_GET_LINE_PARMS = 0x35, + CDC_REQUEST_DIAL_DIGITS = 0x36, + CDC_REQUEST_SET_UNIT_PARAMETER = 0x37, + CDC_REQUEST_GET_UNIT_PARAMETER = 0x38, + CDC_REQUEST_CLEAR_UNIT_PARAMETER = 0x39, + CDC_REQUEST_GET_PROFILE = 0x3A, + + CDC_REQUEST_SET_ETHERNET_MULTICAST_FILTERS = 0x40, + CDC_REQUEST_SET_ETHERNET_POWER_MANAGEMENT_PATTERN_FILTER = 0x41, + CDC_REQUEST_GET_ETHERNET_POWER_MANAGEMENT_PATTERN_FILTER = 0x42, + CDC_REQUEST_SET_ETHERNET_PACKET_FILTER = 0x43, + CDC_REQUEST_GET_ETHERNET_STATISTIC = 0x44, + + CDC_REQUEST_SET_ATM_DATA_FORMAT = 0x50, + CDC_REQUEST_GET_ATM_DEVICE_STATISTICS = 0x51, + CDC_REQUEST_SET_ATM_DEFAULT_VC = 0x52, + CDC_REQUEST_GET_ATM_VC_STATISTICS = 0x53, + + CDC_REQUEST_MDLM_SEMANTIC_MODEL = 0x60, +}cdc_management_request_t; + +//--------------------------------------------------------------------+ +// MANAGEMENT ELEMENENT NOTIFICATION (NOTIFICATION ENDPOINT) +//--------------------------------------------------------------------+ +/// Communication Interface Management Element Notification Codes +typedef enum +{ + NETWORK_CONNECTION = 0x00, ///< This notification allows the device to notify the host about network connection status. + RESPONSE_AVAILABLE = 0x01, ///< This notification allows the device to notify the hostthat a response is available. This response can be retrieved with a subsequent \ref CDC_REQUEST_GET_ENCAPSULATED_RESPONSE request. + + AUX_JACK_HOOK_STATE = 0x08, + RING_DETECT = 0x09, + + SERIAL_STATE = 0x20, + + CALL_STATE_CHANGE = 0x28, + LINE_STATE_CHANGE = 0x29, + CONNECTION_SPEED_CHANGE = 0x2A, ///< This notification allows the device to inform the host-networking driver that a change in either the upstream or the downstream bit rate of the connection has occurred + MDLM_SEMANTIC_MODEL_NOTIFICATION = 0x40, +}cdc_notification_request_t; + +//--------------------------------------------------------------------+ +// FUNCTIONAL DESCRIPTOR (COMMUNICATION INTERFACE) +//--------------------------------------------------------------------+ +/// Header Functional Descriptor (Communication Interface) +typedef struct ATTR_PACKED +{ + uint8_t bLength ; ///< Size of this descriptor in bytes. + uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific + uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_ + uint16_t bcdCDC ; ///< CDC release number in Binary-Coded Decimal +}cdc_desc_func_header_t; + +/// Union Functional Descriptor (Communication Interface) +typedef struct ATTR_PACKED +{ + uint8_t bLength ; ///< Size of this descriptor in bytes. + uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific + uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_ + uint8_t bControlInterface ; ///< Interface number of Communication Interface + uint8_t bSubordinateInterface ; ///< Array of Interface number of Data Interface +}cdc_desc_func_union_t; + +#define cdc_desc_func_union_n_t(no_slave)\ + struct ATTR_PACKED { \ + uint8_t bLength ;\ + uint8_t bDescriptorType ;\ + uint8_t bDescriptorSubType ;\ + uint8_t bControlInterface ;\ + uint8_t bSubordinateInterface[no_slave] ;\ +} + +/// Country Selection Functional Descriptor (Communication Interface) +typedef struct ATTR_PACKED +{ + uint8_t bLength ; ///< Size of this descriptor in bytes. + uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific + uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_ + uint8_t iCountryCodeRelDate ; ///< Index of a string giving the release date for the implemented ISO 3166 Country Codes. + uint16_t wCountryCode[] ; ///< Country code in the format as defined in [ISO3166], release date as specified inoffset 3 for the first supported country. +}cdc_desc_func_country_selection_t; + +#define cdc_desc_func_country_selection_n_t(no_country) \ + struct ATTR_PACKED {\ + uint8_t bLength ;\ + uint8_t bDescriptorType ;\ + uint8_t bDescriptorSubType ;\ + uint8_t iCountryCodeRelDate ;\ + uint16_t wCountryCode[no_country] ;\ +} + +//--------------------------------------------------------------------+ +// PUBLIC SWITCHED TELEPHONE NETWORK (PSTN) SUBCLASS +//--------------------------------------------------------------------+ + +/// \brief Call Management Functional Descriptor +/// \details This functional descriptor describes the processing of calls for the Communications Class interface. +typedef struct ATTR_PACKED +{ + uint8_t bLength ; ///< Size of this descriptor in bytes. + uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific + uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_ + + struct { + uint8_t handle_call : 1; ///< 0 - Device sends/receives call management information only over the Communications Class interface. 1 - Device can send/receive call management information over a Data Class interface. + uint8_t send_recv_call : 1; ///< 0 - Device does not handle call management itself. 1 - Device handles call management itself. + uint8_t : 0; + } bmCapabilities; + + uint8_t bDataInterface; +}cdc_desc_func_call_management_t; + + +typedef struct ATTR_PACKED +{ + uint8_t support_comm_request : 1; ///< Device supports the request combination of Set_Comm_Feature, Clear_Comm_Feature, and Get_Comm_Feature. + uint8_t support_line_request : 1; ///< Device supports the request combination of Set_Line_Coding, Set_Control_Line_State, Get_Line_Coding, and the notification Serial_State. + uint8_t support_send_break : 1; ///< Device supports the request Send_Break + uint8_t support_notification_network_connection : 1; ///< Device supports the notification Network_Connection. + uint8_t : 0; +}cdc_acm_capability_t; + +VERIFY_STATIC(sizeof(cdc_acm_capability_t) == 1, "mostly problem with compiler"); + +/// \brief Abstract Control Management Functional Descriptor +/// \details This functional descriptor describes the commands supported by by the Communications Class interface with SubClass code of \ref CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL +typedef struct ATTR_PACKED +{ + uint8_t bLength ; ///< Size of this descriptor in bytes. + uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific + uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_ + cdc_acm_capability_t bmCapabilities ; +}cdc_desc_func_acm_t; + +/// \brief Direct Line Management Functional Descriptor +/// \details This functional descriptor describes the commands supported by the Communications Class interface with SubClass code of \ref CDC_FUNC_DESC_DIRECT_LINE_MANAGEMENT +typedef struct ATTR_PACKED +{ + uint8_t bLength ; ///< Size of this descriptor in bytes. + uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific + uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_ + struct { + uint8_t require_pulse_setup : 1; ///< Device requires extra Pulse_Setup request during pulse dialing sequence to disengage holding circuit. + uint8_t support_aux_request : 1; ///< Device supports the request combination of Set_Aux_Line_State, Ring_Aux_Jack, and notification Aux_Jack_Hook_State. + uint8_t support_pulse_request : 1; ///< Device supports the request combination of Pulse_Setup, Send_Pulse, and Set_Pulse_Time. + uint8_t : 0; + } bmCapabilities; +}cdc_desc_func_direct_line_management_t; + +/// \brief Telephone Ringer Functional Descriptor +/// \details The Telephone Ringer functional descriptor describes the ringer capabilities supported by the Communications Class interface, +/// with the SubClass code of \ref CDC_COMM_SUBCLASS_TELEPHONE_CONTROL_MODEL +typedef struct ATTR_PACKED +{ + uint8_t bLength ; ///< Size of this descriptor in bytes. + uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific + uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_ + uint8_t bRingerVolSteps ; + uint8_t bNumRingerPatterns ; +}cdc_desc_func_telephone_ringer_t; + +/// \brief Telephone Operational Modes Functional Descriptor +/// \details The Telephone Operational Modes functional descriptor describes the operational modes supported by +/// the Communications Class interface, with the SubClass code of \ref CDC_COMM_SUBCLASS_TELEPHONE_CONTROL_MODEL +typedef struct ATTR_PACKED +{ + uint8_t bLength ; ///< Size of this descriptor in bytes. + uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific + uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_ + struct { + uint8_t simple_mode : 1; + uint8_t standalone_mode : 1; + uint8_t computer_centric_mode : 1; + uint8_t : 0; + } bmCapabilities; +}cdc_desc_func_telephone_operational_modes_t; + +/// \brief Telephone Call and Line State Reporting Capabilities Descriptor +/// \details The Telephone Call and Line State Reporting Capabilities functional descriptor describes the abilities of a +/// telephone device to report optional call and line states. +typedef struct ATTR_PACKED +{ + uint8_t bLength ; ///< Size of this descriptor in bytes. + uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific + uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_ + struct { + uint32_t interrupted_dialtone : 1; ///< 0 : Reports only dialtone (does not differentiate between normal and interrupted dialtone). 1 : Reports interrupted dialtone in addition to normal dialtone + uint32_t ringback_busy_fastbusy : 1; ///< 0 : Reports only dialing state. 1 : Reports ringback, busy, and fast busy states. + uint32_t caller_id : 1; ///< 0 : Does not report caller ID. 1 : Reports caller ID information. + uint32_t incoming_distinctive : 1; ///< 0 : Reports only incoming ringing. 1 : Reports incoming distinctive ringing patterns. + uint32_t dual_tone_multi_freq : 1; ///< 0 : Cannot report dual tone multi-frequency (DTMF) digits input remotely over the telephone line. 1 : Can report DTMF digits input remotely over the telephone line. + uint32_t line_state_change : 1; ///< 0 : Does not support line state change notification. 1 : Does support line state change notification + uint32_t : 0; + } bmCapabilities; +}cdc_desc_func_telephone_call_state_reporting_capabilities_t; + +static inline uint8_t cdc_functional_desc_typeof(uint8_t const * p_desc) +{ + return p_desc[2]; +} + +//--------------------------------------------------------------------+ +// Requests +//--------------------------------------------------------------------+ +typedef struct ATTR_PACKED +{ + uint32_t bit_rate; + uint8_t stop_bits; ///< 0: 1 stop bit - 1: 1.5 stop bits - 2: 2 stop bits + uint8_t parity; ///< 0: None - 1: Odd - 2: Even - 3: Mark - 4: Space + uint8_t data_bits; ///< can be 5, 6, 7, 8 or 16 +} cdc_line_coding_t; + +VERIFY_STATIC(sizeof(cdc_line_coding_t) == 7, "size is not correct"); + +typedef struct ATTR_PACKED +{ + uint16_t dte_is_present : 1; ///< Indicates to DCE if DTE is presentor not. This signal corresponds to V.24 signal 108/2 and RS-232 signal DTR. + uint16_t half_duplex_carrier_control : 1; + uint16_t : 14; +} cdc_line_control_state_t; + +VERIFY_STATIC(sizeof(cdc_line_control_state_t) == 2, "size is not correct"); + +/** @} */ + +#ifdef __cplusplus + } +#endif + +#endif + +/** @} */ diff --git a/src/class/cdc/cdc_device.c b/src/class/cdc/cdc_device.c new file mode 100644 index 000000000..90e1924b4 --- /dev/null +++ b/src/class/cdc/cdc_device.c @@ -0,0 +1,302 @@ +/**************************************************************************/ +/*! + @file cdc_device.c + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#include "tusb_option.h" + +#if (MODE_DEVICE_SUPPORTED && CFG_TUD_CDC) + +#define _TINY_USB_SOURCE_FILE_ +//--------------------------------------------------------------------+ +// INCLUDE +//--------------------------------------------------------------------+ +#include "common/tusb_common.h" +#include "cdc_device.h" +#include "device/usbd_pvt.h" + +//--------------------------------------------------------------------+ +// MACRO CONSTANT TYPEDEF +//--------------------------------------------------------------------+ +CFG_TUSB_ATTR_USBRAM STATIC_VAR cdc_line_coding_t cdcd_line_coding[CONTROLLER_DEVICE_NUMBER]; + +typedef struct { + uint8_t itf_num; + uint8_t ep_notif; + uint8_t ep_in; + uint8_t ep_out; + + cdc_acm_capability_t acm_cap; + + // Bit 0: DTR (Data Terminal Ready), Bit 1: RTS (Request to Send) + uint8_t line_state; +}cdcd_interface_t; + +// TODO multiple rhport +CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN uint8_t _tmp_rx_buf[64]; +CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN uint8_t _tmp_tx_buf[64]; + +FIFO_DEF(_rx_ff, CFG_TUD_CDC_BUFSIZE, uint8_t, true); +FIFO_DEF(_tx_ff, CFG_TUD_CDC_BUFSIZE, uint8_t, false); + +//--------------------------------------------------------------------+ +// INTERNAL OBJECT & FUNCTION DECLARATION +//--------------------------------------------------------------------+ +STATIC_VAR cdcd_interface_t _cdcd_itf[CONTROLLER_DEVICE_NUMBER]; + +//--------------------------------------------------------------------+ +// APPLICATION API +//--------------------------------------------------------------------+ +bool tud_n_cdc_connected(uint8_t rhport) +{ + // DTR (bit 0) active isconsidered as connected + return BIT_TEST_(_cdcd_itf[rhport].line_state, 0); +} + +uint8_t tud_n_cdc_get_line_state (uint8_t rhport) +{ + return _cdcd_itf[rhport].line_state; +} + +void tud_n_cdc_get_line_coding (uint8_t rhport, cdc_line_coding_t* coding) +{ + (*coding) = cdcd_line_coding[rhport]; +} + + +//--------------------------------------------------------------------+ +// READ API +//--------------------------------------------------------------------+ +uint32_t tud_n_cdc_available(uint8_t rhport) +{ + return fifo_count(&_rx_ff); +} + +int8_t tud_n_cdc_read_char(uint8_t rhport) +{ + int8_t ch; + return fifo_read(&_rx_ff, &ch) ? ch : (-1); +} + +uint32_t tud_n_cdc_read(uint8_t rhport, void* buffer, uint32_t bufsize) +{ + return fifo_read_n(&_rx_ff, buffer, bufsize); +} + +//--------------------------------------------------------------------+ +// WRITE API +//--------------------------------------------------------------------+ + +uint32_t tud_n_cdc_write_char(uint8_t rhport, char ch) +{ + return fifo_write(&_tx_ff, &ch) ? 1 : 0; +} + +uint32_t tud_n_cdc_write(uint8_t rhport, void const* buffer, uint32_t bufsize) +{ + return fifo_write_n(&_tx_ff, buffer, bufsize); +} + +bool tud_n_cdc_flush (uint8_t rhport) +{ + uint8_t edpt = _cdcd_itf[rhport].ep_in; + VERIFY( !dcd_edpt_busy(rhport, edpt) ); // skip if previous transfer not complete + + uint16_t count = fifo_read_n(&_tx_ff, _tmp_tx_buf, sizeof(_tmp_tx_buf)); + + VERIFY( tud_n_cdc_connected(rhport) ); // fifo is empty if not connected + + if ( count ) TU_ASSERT( dcd_edpt_xfer(rhport, edpt, _tmp_tx_buf, count) ); + + return true; +} + + +//--------------------------------------------------------------------+ +// USBD Driver API +//--------------------------------------------------------------------+ +void cdcd_init(void) +{ + memclr_(_cdcd_itf, sizeof(cdcd_interface_t)*CONTROLLER_DEVICE_NUMBER); + + // default line coding is : stop bit = 1, parity = none, data bits = 8 + memclr_(cdcd_line_coding, sizeof(cdc_line_coding_t)*CONTROLLER_DEVICE_NUMBER); + for(uint8_t i=0; ibInterfaceSubClass) return TUSB_ERROR_CDC_UNSUPPORTED_SUBCLASS; + + if ( !(is_in_range(CDC_COMM_PROTOCOL_ATCOMMAND, p_interface_desc->bInterfaceProtocol, CDC_COMM_PROTOCOL_ATCOMMAND_CDMA) || + 0xff == p_interface_desc->bInterfaceProtocol) ) + { + return TUSB_ERROR_CDC_UNSUPPORTED_PROTOCOL; + } + + uint8_t const * p_desc = descriptor_next ( (uint8_t const *) p_interface_desc ); + cdcd_interface_t * p_cdc = &_cdcd_itf[rhport]; + + //------------- Communication Interface -------------// + (*p_length) = sizeof(tusb_desc_interface_t); + + // Communication Functional Descriptors + while( TUSB_DESC_CLASS_SPECIFIC == p_desc[DESCRIPTOR_OFFSET_TYPE] ) + { + if ( CDC_FUNC_DESC_ABSTRACT_CONTROL_MANAGEMENT == cdc_functional_desc_typeof(p_desc) ) + { // save ACM bmCapabilities + p_cdc->acm_cap = ((cdc_desc_func_acm_t const *) p_desc)->bmCapabilities; + } + + (*p_length) += p_desc[DESCRIPTOR_OFFSET_LENGTH]; + p_desc = descriptor_next(p_desc); + } + + if ( TUSB_DESC_ENDPOINT == p_desc[DESCRIPTOR_OFFSET_TYPE]) + { // notification endpoint if any + TU_ASSERT( dcd_edpt_open(rhport, (tusb_desc_endpoint_t const *) p_desc), TUSB_ERROR_DCD_OPEN_PIPE_FAILED); + + p_cdc->ep_notif = ((tusb_desc_endpoint_t const *) p_desc)->bEndpointAddress; + + (*p_length) += p_desc[DESCRIPTOR_OFFSET_LENGTH]; + p_desc = descriptor_next(p_desc); + } + + //------------- Data Interface (if any) -------------// + if ( (TUSB_DESC_INTERFACE == p_desc[DESCRIPTOR_OFFSET_TYPE]) && + (TUSB_CLASS_CDC_DATA == ((tusb_desc_interface_t const *) p_desc)->bInterfaceClass) ) + { + (*p_length) += p_desc[DESCRIPTOR_OFFSET_LENGTH]; + p_desc = descriptor_next(p_desc); + + // Open endpoint pair with usbd helper + tusb_desc_endpoint_t const *p_desc_ep = (tusb_desc_endpoint_t const *) p_desc; + TU_ASSERT_ERR( usbd_open_edpt_pair(rhport, p_desc_ep, TUSB_XFER_BULK, &p_cdc->ep_out, &p_cdc->ep_in) ); + + (*p_length) += 2*sizeof(tusb_desc_endpoint_t); + } + + p_cdc->itf_num = p_interface_desc->bInterfaceNumber; + + // Prepare for incoming data + TU_ASSERT( dcd_edpt_xfer(rhport, p_cdc->ep_out, _tmp_rx_buf, sizeof(_tmp_rx_buf)), TUSB_ERROR_DCD_EDPT_XFER); + + return TUSB_ERROR_NONE; +} + +void cdcd_close(uint8_t rhport) +{ + // no need to close opened pipe, dcd bus reset will put controller's endpoints to default state + memclr_(&_cdcd_itf[rhport], sizeof(cdcd_interface_t)); + + fifo_clear(&_rx_ff); + fifo_clear(&_tx_ff); +} + +tusb_error_t cdcd_control_request_st(uint8_t rhport, tusb_control_request_t const * p_request) +{ + OSAL_SUBTASK_BEGIN + + //------------- Class Specific Request -------------// + if (p_request->bmRequestType_bit.type != TUSB_REQ_TYPE_CLASS) return TUSB_ERROR_DCD_CONTROL_REQUEST_NOT_SUPPORT; + + if ( (CDC_REQUEST_GET_LINE_CODING == p_request->bRequest) || (CDC_REQUEST_SET_LINE_CODING == p_request->bRequest) ) + { + uint16_t len = min16_of(sizeof(cdc_line_coding_t), p_request->wLength); + usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, (uint8_t*) &cdcd_line_coding[rhport], len); + + // Invoke callback + if (CDC_REQUEST_SET_LINE_CODING == p_request->bRequest) + { + if ( tud_cdc_line_coding_cb ) tud_cdc_line_coding_cb(rhport, &cdcd_line_coding[rhport]); + } + } + else if (CDC_REQUEST_SET_CONTROL_LINE_STATE == p_request->bRequest ) + { + // CDC PSTN v1.2 section 6.3.12 + // Bit 0: Indicates if DTE is present or not. + // This signal corresponds to V.24 signal 108/2 and RS-232 signal DTR (Data Terminal Ready) + // Bit 1: Carrier control for half-duplex modems. + // This signal corresponds to V.24 signal 105 and RS-232 signal RTS (Request to Send) + cdcd_interface_t * p_cdc = &_cdcd_itf[rhport]; + + p_cdc->line_state = (uint8_t) p_request->wValue; + + dcd_control_status(rhport, p_request->bmRequestType_bit.direction); // ACK control request + + // Invoke callback + if ( tud_cdc_line_state_cb) tud_cdc_line_state_cb(rhport, BIT_TEST_(p_request->wValue, 0), BIT_TEST_(p_request->wValue, 1)); + } + else + { + dcd_control_stall(rhport); // stall unsupported request + } + + OSAL_SUBTASK_END +} + +tusb_error_t cdcd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, uint32_t xferred_bytes) +{ + cdcd_interface_t const * p_cdc = &_cdcd_itf[rhport]; + + if ( ep_addr == p_cdc->ep_out ) + { + fifo_write_n(&_rx_ff, _tmp_rx_buf, xferred_bytes); + + // preparing for next + TU_ASSERT( dcd_edpt_xfer(rhport, p_cdc->ep_out, _tmp_rx_buf, sizeof(_tmp_rx_buf)), TUSB_ERROR_DCD_EDPT_XFER ); + + // fire callback + if (tud_cdc_rx_cb) tud_cdc_rx_cb(rhport); + } + + return TUSB_ERROR_NONE; +} + +#if CFG_TUD_CDC_FLUSH_ON_SOF +void cdcd_sof(uint8_t rhport) +{ + tud_n_cdc_flush(rhport); +} +#endif + +#endif diff --git a/src/class/cdc/cdc_device.h b/src/class/cdc/cdc_device.h new file mode 100644 index 000000000..c1a790fc8 --- /dev/null +++ b/src/class/cdc/cdc_device.h @@ -0,0 +1,120 @@ +/**************************************************************************/ +/*! + @file cdc_device.h + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#ifndef _TUSB_CDC_DEVICE_H_ +#define _TUSB_CDC_DEVICE_H_ + +#include "common/tusb_common.h" +#include "device/usbd.h" +#include "cdc.h" + +#ifdef __cplusplus + extern "C" { +#endif + +/** \addtogroup CDC_Serial Serial + * @{ + * \defgroup CDC_Serial_Device Device + * @{ */ + +//--------------------------------------------------------------------+ +// APPLICATION API (Multiple Root Ports) +// Should be used only with MCU that support more than 1 ports +//--------------------------------------------------------------------+ +bool tud_n_cdc_connected (uint8_t rhport); +uint8_t tud_n_cdc_get_line_state (uint8_t rhport); +void tud_n_cdc_get_line_coding (uint8_t rhport, cdc_line_coding_t* coding); + +uint32_t tud_n_cdc_available (uint8_t rhport); +int8_t tud_n_cdc_read_char (uint8_t rhport); +uint32_t tud_n_cdc_read (uint8_t rhport, void* buffer, uint32_t bufsize); + +uint32_t tud_n_cdc_write_char (uint8_t rhport, char ch); +uint32_t tud_n_cdc_write (uint8_t rhport, void const* buffer, uint32_t bufsize); +bool tud_n_cdc_flush (uint8_t rhport); + +//--------------------------------------------------------------------+ +// APPLICATION API (Single Port) +// Should be used with MCU supporting only 1 USB port for code simplicity +//--------------------------------------------------------------------+ +static inline bool tud_cdc_connected (void) { return tud_n_cdc_connected(0); } +static inline uint8_t tud_cdc_get_line_state (uint8_t rhport) { return tud_n_cdc_get_line_state(0); } +static inline void tud_cdc_get_line_coding (uint8_t rhport, cdc_line_coding_t* coding) { return tud_cdc_get_line_coding(0, coding); } + +static inline uint32_t tud_cdc_available (void) { return tud_n_cdc_available(0); } +static inline int8_t tud_cdc_read_char (void) { return tud_n_cdc_read_char(0); } +static inline uint32_t tud_cdc_read (void* buffer, uint32_t bufsize) { return tud_n_cdc_read(0, buffer, bufsize); } + +static inline uint32_t tud_cdc_write_char (char ch) { return tud_n_cdc_write_char(0, ch); } +static inline uint32_t tud_cdc_write (void const* buffer, uint32_t bufsize) { return tud_n_cdc_write(0, buffer, bufsize); } +static inline bool tud_cdc_flush (void) { return tud_n_cdc_flush(0); } + +//--------------------------------------------------------------------+ +// APPLICATION CALLBACK API (WEAK is optional) +//--------------------------------------------------------------------+ +ATTR_WEAK void tud_cdc_rx_cb(uint8_t rhport); +ATTR_WEAK void tud_cdc_line_state_cb(uint8_t rhport, bool dtr, bool rts); +ATTR_WEAK void tud_cdc_line_coding_cb(uint8_t rhport, cdc_line_coding_t const* p_line_coding); + +//--------------------------------------------------------------------+ +// USBD-CLASS DRIVER API +//--------------------------------------------------------------------+ +#ifdef _TINY_USB_SOURCE_FILE_ + +void cdcd_init(void); +tusb_error_t cdcd_open(uint8_t rhport, tusb_desc_interface_t const * p_interface_desc, uint16_t *p_length); +tusb_error_t cdcd_control_request_st(uint8_t rhport, tusb_control_request_t const * p_request); +tusb_error_t cdcd_xfer_cb(uint8_t rhport, uint8_t edpt_addr, tusb_event_t event, uint32_t xferred_bytes); +void cdcd_close(uint8_t rhport); + +#if CFG_TUD_CDC_FLUSH_ON_SOF +void cdcd_sof(uint8_t rhport); +#else +#define cdcd_sof NULL +#endif + +#endif + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_CDC_DEVICE_H_ */ + +/** @} */ +/** @} */ diff --git a/src/class/cdc/cdc_host.c b/src/class/cdc/cdc_host.c new file mode 100644 index 000000000..bd5b5e32c --- /dev/null +++ b/src/class/cdc/cdc_host.c @@ -0,0 +1,243 @@ +/**************************************************************************/ +/*! + @file cdc_host.c + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#include "tusb_option.h" + +#if (MODE_HOST_SUPPORTED && CFG_TUSB_HOST_CDC) + +#define _TINY_USB_SOURCE_FILE_ + +//--------------------------------------------------------------------+ +// INCLUDE +//--------------------------------------------------------------------+ +#include "common/tusb_common.h" +#include "cdc_host.h" + +//--------------------------------------------------------------------+ +// MACRO CONSTANT TYPEDEF +//--------------------------------------------------------------------+ + +//--------------------------------------------------------------------+ +// INTERNAL OBJECT & FUNCTION DECLARATION +//--------------------------------------------------------------------+ +STATIC_VAR cdch_data_t cdch_data[CFG_TUSB_HOST_DEVICE_MAX]; // TODO to be static + +static inline cdc_pipeid_t get_app_pipeid(pipe_handle_t pipe_hdl) +{ + cdch_data_t const * p_cdc = &cdch_data[pipe_hdl.dev_addr-1]; + + return pipehandle_is_equal( pipe_hdl, p_cdc->pipe_notification ) ? CDC_PIPE_NOTIFICATION : + pipehandle_is_equal( pipe_hdl, p_cdc->pipe_in ) ? CDC_PIPE_DATA_IN : + pipehandle_is_equal( pipe_hdl, p_cdc->pipe_out ) ? CDC_PIPE_DATA_OUT : CDC_PIPE_ERROR; +} + + +static inline bool tusbh_cdc_is_mounted(uint8_t dev_addr) +{ +// FIXME cannot use mounted class flag as at the point _open_sublass is called, the flag is not set yet +#ifdef _TEST_ + return (tusbh_device_get_mounted_class_flag(dev_addr) & BIT_(TUSB_CLASS_CDC)) != 0; +#else + return pipehandle_is_valid(cdch_data[dev_addr-1].pipe_in) && + pipehandle_is_valid(cdch_data[dev_addr-1].pipe_out); +#endif +} + +bool tuh_cdc_is_busy(uint8_t dev_addr, cdc_pipeid_t pipeid) +{ + if ( !tusbh_cdc_is_mounted(dev_addr) ) return false; + + cdch_data_t const * p_cdc = &cdch_data[dev_addr-1]; + + switch (pipeid) + { + case CDC_PIPE_NOTIFICATION: + return hcd_pipe_is_busy( p_cdc->pipe_notification ); + + case CDC_PIPE_DATA_IN: + return hcd_pipe_is_busy( p_cdc->pipe_in ); + + case CDC_PIPE_DATA_OUT: + return hcd_pipe_is_busy( p_cdc->pipe_out ); + + default: + return false; + } +} + + +//--------------------------------------------------------------------+ +// APPLICATION API (parameter validation needed) +//--------------------------------------------------------------------+ +bool tuh_cdc_serial_is_mounted(uint8_t dev_addr) +{ + // TODO consider all AT Command as serial candidate + return tusbh_cdc_is_mounted(dev_addr) && + (CDC_COMM_PROTOCOL_ATCOMMAND <= cdch_data[dev_addr-1].interface_protocol) && + (cdch_data[dev_addr-1].interface_protocol <= CDC_COMM_PROTOCOL_ATCOMMAND_CDMA); +} + +tusb_error_t tuh_cdc_send(uint8_t dev_addr, void const * p_data, uint32_t length, bool is_notify) +{ + TU_ASSERT( tusbh_cdc_is_mounted(dev_addr), TUSB_ERROR_CDCH_DEVICE_NOT_MOUNTED); + TU_ASSERT( p_data != NULL && length, TUSB_ERROR_INVALID_PARA); + + pipe_handle_t pipe_out = cdch_data[dev_addr-1].pipe_out; + if ( hcd_pipe_is_busy(pipe_out) ) return TUSB_ERROR_INTERFACE_IS_BUSY; + + return hcd_pipe_xfer( pipe_out, (void *) p_data, length, is_notify); +} + +tusb_error_t tuh_cdc_receive(uint8_t dev_addr, void * p_buffer, uint32_t length, bool is_notify) +{ + TU_ASSERT( tusbh_cdc_is_mounted(dev_addr), TUSB_ERROR_CDCH_DEVICE_NOT_MOUNTED); + TU_ASSERT( p_buffer != NULL && length, TUSB_ERROR_INVALID_PARA); + + pipe_handle_t pipe_in = cdch_data[dev_addr-1].pipe_in; + if ( hcd_pipe_is_busy(pipe_in) ) return TUSB_ERROR_INTERFACE_IS_BUSY; + + return hcd_pipe_xfer( pipe_in, p_buffer, length, is_notify); +} + +//--------------------------------------------------------------------+ +// USBH-CLASS DRIVER API +//--------------------------------------------------------------------+ +void cdch_init(void) +{ + memclr_(cdch_data, sizeof(cdch_data_t)*CFG_TUSB_HOST_DEVICE_MAX); +} + +tusb_error_t cdch_open_subtask(uint8_t dev_addr, tusb_desc_interface_t const *p_interface_desc, uint16_t *p_length) +{ + OSAL_SUBTASK_BEGIN + // TODO change following assert to subtask_assert + + if ( CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL != p_interface_desc->bInterfaceSubClass) return TUSB_ERROR_CDC_UNSUPPORTED_SUBCLASS; + + if ( !(is_in_range(CDC_COMM_PROTOCOL_ATCOMMAND, p_interface_desc->bInterfaceProtocol, CDC_COMM_PROTOCOL_ATCOMMAND_CDMA) || + 0xff == p_interface_desc->bInterfaceProtocol) ) + { + return TUSB_ERROR_CDC_UNSUPPORTED_PROTOCOL; + } + + uint8_t const * p_desc; + cdch_data_t * p_cdc; + + p_desc = descriptor_next ( (uint8_t const *) p_interface_desc ); + p_cdc = &cdch_data[dev_addr-1]; // non-static variable cannot be used after OS service call + + p_cdc->interface_number = p_interface_desc->bInterfaceNumber; + p_cdc->interface_protocol = p_interface_desc->bInterfaceProtocol; // TODO 0xff is consider as rndis candidate, other is virtual Com + + //------------- Communication Interface -------------// + (*p_length) = sizeof(tusb_desc_interface_t); + + while( TUSB_DESC_CLASS_SPECIFIC == p_desc[DESCRIPTOR_OFFSET_TYPE] ) + { // Communication Functional Descriptors + if ( CDC_FUNC_DESC_ABSTRACT_CONTROL_MANAGEMENT == cdc_functional_desc_typeof(p_desc) ) + { // save ACM bmCapabilities + p_cdc->acm_capability = ((cdc_desc_func_acm_t const *) p_desc)->bmCapabilities; + } + + (*p_length) += p_desc[DESCRIPTOR_OFFSET_LENGTH]; + p_desc = descriptor_next(p_desc); + } + + if ( TUSB_DESC_ENDPOINT == p_desc[DESCRIPTOR_OFFSET_TYPE]) + { // notification endpoint if any + p_cdc->pipe_notification = hcd_pipe_open(dev_addr, (tusb_desc_endpoint_t const *) p_desc, TUSB_CLASS_CDC); + + (*p_length) += p_desc[DESCRIPTOR_OFFSET_LENGTH]; + p_desc = descriptor_next(p_desc); + + TU_ASSERT(pipehandle_is_valid(p_cdc->pipe_notification), TUSB_ERROR_HCD_OPEN_PIPE_FAILED); + } + + //------------- Data Interface (if any) -------------// + if ( (TUSB_DESC_INTERFACE == p_desc[DESCRIPTOR_OFFSET_TYPE]) && + (TUSB_CLASS_CDC_DATA == ((tusb_desc_interface_t const *) p_desc)->bInterfaceClass) ) + { + (*p_length) += p_desc[DESCRIPTOR_OFFSET_LENGTH]; + p_desc = descriptor_next(p_desc); + + // data endpoints expected to be in pairs + for(uint32_t i=0; i<2; i++) + { + tusb_desc_endpoint_t const *p_endpoint = (tusb_desc_endpoint_t const *) p_desc; + TU_ASSERT(TUSB_DESC_ENDPOINT == p_endpoint->bDescriptorType, TUSB_ERROR_USBH_DESCRIPTOR_CORRUPTED); + TU_ASSERT(TUSB_XFER_BULK == p_endpoint->bmAttributes.xfer, TUSB_ERROR_USBH_DESCRIPTOR_CORRUPTED); + + pipe_handle_t * p_pipe_hdl = ( p_endpoint->bEndpointAddress & TUSB_DIR_IN_MASK ) ? + &p_cdc->pipe_in : &p_cdc->pipe_out; + + (*p_pipe_hdl) = hcd_pipe_open(dev_addr, p_endpoint, TUSB_CLASS_CDC); + TU_ASSERT ( pipehandle_is_valid(*p_pipe_hdl), TUSB_ERROR_HCD_OPEN_PIPE_FAILED ); + + (*p_length) += p_desc[DESCRIPTOR_OFFSET_LENGTH]; + p_desc = descriptor_next( p_desc ); + } + } + + { + // FIXME mounted class flag is not set yet + tuh_cdc_mounted_cb(dev_addr); + } + + OSAL_SUBTASK_END +} + +void cdch_isr(pipe_handle_t pipe_hdl, tusb_event_t event, uint32_t xferred_bytes) +{ + tuh_cdc_xfer_isr( pipe_hdl.dev_addr, event, get_app_pipeid(pipe_hdl), xferred_bytes ); +} + +void cdch_close(uint8_t dev_addr) +{ + cdch_data_t * p_cdc = &cdch_data[dev_addr-1]; + + (void) hcd_pipe_close(p_cdc->pipe_notification); + (void) hcd_pipe_close(p_cdc->pipe_in); + (void) hcd_pipe_close(p_cdc->pipe_out); + + memclr_(p_cdc, sizeof(cdch_data_t)); + + tuh_cdc_unmounted_cb(dev_addr); + +} + +#endif diff --git a/src/class/cdc/cdc_host.h b/src/class/cdc/cdc_host.h new file mode 100644 index 000000000..77f1e5a78 --- /dev/null +++ b/src/class/cdc/cdc_host.h @@ -0,0 +1,163 @@ +/**************************************************************************/ +/*! + @file cdc_host.h + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + + +#ifndef _TUSB_CDC_HOST_H_ +#define _TUSB_CDC_HOST_H_ + +#include "common/tusb_common.h" +#include "host/usbh.h" +#include "cdc.h" + +#ifdef __cplusplus + extern "C" { +#endif + +//--------------------------------------------------------------------+ +// CDC APPLICATION PUBLIC API +//--------------------------------------------------------------------+ +/** \ingroup ClassDriver_CDC Communication Device Class (CDC) + * \addtogroup CDC_Serial Serial + * @{ + * \defgroup CDC_Serial_Host Host + * @{ */ + +/** \brief Check if device support CDC Serial interface or not + * \param[in] dev_addr device address + * \retval true if device supports + * \retval false if device does not support or is not mounted + */ +bool tuh_cdc_serial_is_mounted(uint8_t dev_addr) ATTR_PURE ATTR_WARN_UNUSED_RESULT; + +/** \brief Check if the interface is currently busy or not + * \param[in] dev_addr device address + * \param[in] pipeid value from \ref cdc_pipeid_t to indicate target pipe. + * \retval true if the interface is busy, meaning the stack is still transferring/waiting data from/to device + * \retval false if the interface is not busy, meaning the stack successfully transferred data from/to device + * \note This function is used to check if previous transfer is complete (success or error), so that the next transfer + * can be scheduled. User needs to make sure the corresponding interface is mounted + * (by \ref tuh_cdc_serial_is_mounted) before calling this function. + */ +bool tuh_cdc_is_busy(uint8_t dev_addr, cdc_pipeid_t pipeid) ATTR_PURE ATTR_WARN_UNUSED_RESULT; + +/** \brief Perform USB OUT transfer to device + * \param[in] dev_addr device address + * \param[in] p_data Buffer containing data. Must be accessible by USB controller (see \ref CFG_TUSB_ATTR_USBRAM) + * \param[in] length Number of bytes to be transferred via USB bus + * \retval TUSB_ERROR_NONE on success + * \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device + * \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request) + * \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct + * \note This function is non-blocking and returns immediately. The result of USB transfer will be reported by the + * interface's callback function. \a p_data must be declared with \ref CFG_TUSB_ATTR_USBRAM. + */ +tusb_error_t tuh_cdc_send(uint8_t dev_addr, void const * p_data, uint32_t length, bool is_notify); + +/** \brief Perform USB IN transfer to get data from device + * \param[in] dev_addr device address + * \param[in] p_buffer Buffer containing received data. Must be accessible by USB controller (see \ref CFG_TUSB_ATTR_USBRAM) + * \param[in] length Number of bytes to be transferred via USB bus + * \retval TUSB_ERROR_NONE on success + * \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device + * \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request) + * \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct + * \note This function is non-blocking and returns immediately. The result of USB transfer will be reported by the + * interface's callback function. \a p_data must be declared with \ref CFG_TUSB_ATTR_USBRAM. + */ +tusb_error_t tuh_cdc_receive(uint8_t dev_addr, void * p_buffer, uint32_t length, bool is_notify); + +//--------------------------------------------------------------------+ +// CDC APPLICATION CALLBACKS +//--------------------------------------------------------------------+ +/** \brief Callback function that will be invoked when a device with CDC Abstract Control Model interface is mounted + * \param[in] dev_addr Address of newly mounted device + * \note This callback should be used by Application to set-up interface-related data + */ +void tuh_cdc_mounted_cb(uint8_t dev_addr); + +/** \brief Callback function that will be invoked when a device with CDC Abstract Control Model interface is unmounted + * \param[in] dev_addr Address of newly unmounted device + * \note This callback should be used by Application to tear-down interface-related data + */ +void tuh_cdc_unmounted_cb(uint8_t dev_addr); + +/** \brief Callback function that is invoked when an transferring event occurred + * \param[in] dev_addr Address of device + * \param[in] event an value from \ref tusb_event_t + * \param[in] pipe_id value from \ref cdc_pipeid_t indicate the pipe + * \param[in] xferred_bytes Number of bytes transferred via USB bus + * \note event can be one of following + * - TUSB_EVENT_XFER_COMPLETE : previously scheduled transfer completes successfully. + * - TUSB_EVENT_XFER_ERROR : previously scheduled transfer encountered a transaction error. + * - TUSB_EVENT_XFER_STALLED : previously scheduled transfer is stalled by device. + * \note + */ +void tuh_cdc_xfer_isr(uint8_t dev_addr, tusb_event_t event, cdc_pipeid_t pipe_id, uint32_t xferred_bytes); + +/// @} // group CDC_Serial_Host +/// @} + +//--------------------------------------------------------------------+ +// USBH-CLASS API +//--------------------------------------------------------------------+ +#ifdef _TINY_USB_SOURCE_FILE_ + +typedef struct { + uint8_t interface_number; + uint8_t interface_protocol; + + cdc_acm_capability_t acm_capability; + + pipe_handle_t pipe_notification, pipe_out, pipe_in; + +} cdch_data_t; + +extern cdch_data_t cdch_data[CFG_TUSB_HOST_DEVICE_MAX]; // TODO consider to move to cdch internal header file + +void cdch_init(void); +tusb_error_t cdch_open_subtask(uint8_t dev_addr, tusb_desc_interface_t const *p_interface_desc, uint16_t *p_length) ATTR_WARN_UNUSED_RESULT; +void cdch_isr(pipe_handle_t pipe_hdl, tusb_event_t event, uint32_t xferred_bytes); +void cdch_close(uint8_t dev_addr); + +#endif + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_CDC_HOST_H_ */ diff --git a/src/class/cdc/cdc_rndis.h b/src/class/cdc/cdc_rndis.h new file mode 100644 index 000000000..460477eb0 --- /dev/null +++ b/src/class/cdc/cdc_rndis.h @@ -0,0 +1,313 @@ +/**************************************************************************/ +/*! + @file cdc_rndis.h + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +/** \ingroup ClassDriver_CDC Communication Device Class (CDC) + * \defgroup CDC_RNDIS Remote Network Driver Interface Specification (RNDIS) + * @{ + * \defgroup CDC_RNDIS_Common Common Definitions + * @{ */ + +#ifndef _TUSB_CDC_RNDIS_H_ +#define _TUSB_CDC_RNDIS_H_ + +#include "cdc.h" + +#ifdef __cplusplus + extern "C" { +#endif + +#ifdef __CC_ARM +#pragma diag_suppress 66 // Suppress Keil warnings #66-D: enumeration value is out of "int" range +#endif + +/// RNDIS Message Types +typedef enum +{ + RNDIS_MSG_PACKET = 0x00000001UL, ///< The host and device use this to send network data to one another. + + RNDIS_MSG_INITIALIZE = 0x00000002UL, ///< Sent by the host to initialize the device. + RNDIS_MSG_INITIALIZE_CMPLT = 0x80000002UL, ///< Device response to an initialize message. + + RNDIS_MSG_HALT = 0x00000003UL, ///< Sent by the host to halt the device. This does not have a response. It is optional for the device to send this message to the host. + + RNDIS_MSG_QUERY = 0x00000004UL, ///< Sent by the host to send a query OID. + RNDIS_MSG_QUERY_CMPLT = 0x80000004UL, ///< Device response to a query OID. + + RNDIS_MSG_SET = 0x00000005UL, ///< Sent by the host to send a set OID. + RNDIS_MSG_SET_CMPLT = 0x80000005UL, ///< Device response to a set OID. + + RNDIS_MSG_RESET = 0x00000006UL, ///< Sent by the host to perform a soft reset on the device. + RNDIS_MSG_RESET_CMPLT = 0x80000006UL, ///< Device response to reset message. + + RNDIS_MSG_INDICATE_STATUS = 0x00000007UL, ///< Sent by the device to indicate its status or an error when an unrecognized message is received. + + RNDIS_MSG_KEEP_ALIVE = 0x00000008UL, ///< During idle periods, sent every few seconds by the host to check that the device is still responsive. It is optional for the device to send this message to check if the host is active. + RNDIS_MSG_KEEP_ALIVE_CMPLT = 0x80000008UL ///< The device response to a keepalivemessage. The host can respond with this message to a keepalive message from the device when the device implements the optional KeepAliveTimer. +}rndis_msg_type_t; + +/// RNDIS Message Status Values +typedef enum +{ + RNDIS_STATUS_SUCCESS = 0x00000000UL, ///< Success + RNDIS_STATUS_FAILURE = 0xC0000001UL, ///< Unspecified error + RNDIS_STATUS_INVALID_DATA = 0xC0010015UL, ///< Invalid data error + RNDIS_STATUS_NOT_SUPPORTED = 0xC00000BBUL, ///< Unsupported request error + RNDIS_STATUS_MEDIA_CONNECT = 0x4001000BUL, ///< Device is connected to a network medium. + RNDIS_STATUS_MEDIA_DISCONNECT = 0x4001000CUL ///< Device is disconnected from the medium. +}rndis_msg_status_t; + +#ifdef __CC_ARM +#pragma diag_default 66 // return Keil 66 to normal severity +#endif + +//--------------------------------------------------------------------+ +// MESSAGE STRUCTURE +//--------------------------------------------------------------------+ + +//------------- Initialize -------------// +/// \brief Initialize Message +/// \details This message MUST be sent by the host to initialize the device. +typedef struct { + uint32_t type ; ///< Message type, must be \ref RNDIS_MSG_INITIALIZE + uint32_t length ; ///< Message length in bytes, must be 0x18 + uint32_t request_id ; ///< A 32-bit integer value, generated by the host, used to match the host's sent request to the response from the device. + uint32_t major_version ; ///< The major version of the RNDIS Protocol implemented by the host. + uint32_t minor_version ; ///< The minor version of the RNDIS Protocol implemented by the host + uint32_t max_xfer_size ; ///< The maximum size, in bytes, of any single bus data transfer that the host expects to receive from the device. +}rndis_msg_initialize_t; + +/// \brief Initialize Complete Message +/// \details This message MUST be sent by the device in response to an initialize message. +typedef struct { + uint32_t type ; ///< Message Type, must be \ref RNDIS_MSG_INITIALIZE_CMPLT + uint32_t length ; ///< Message length in bytes, must be 0x30 + uint32_t request_id ; ///< A 32-bit integer value from \a request_id field of the \ref rndis_msg_initialize_t to which this message is a response. + uint32_t status ; ///< The initialization status of the device, has value from \ref rndis_msg_status_t + uint32_t major_version ; ///< the highest-numbered RNDIS Protocol version supported by the device. + uint32_t minor_version ; ///< the highest-numbered RNDIS Protocol version supported by the device. + uint32_t device_flags ; ///< MUST be set to 0x000000010. Other values are reserved for future use. + uint32_t medium ; ///< is 0x00 for RNDIS_MEDIUM_802_3 + uint32_t max_packet_per_xfer ; ///< The maximum number of concatenated \ref RNDIS_MSG_PACKET messages that the device can handle in a single bus transfer to it. This value MUST be at least 1. + uint32_t max_xfer_size ; ///< The maximum size, in bytes, of any single bus data transfer that the device expects to receive from the host. + uint32_t packet_alignment_factor ; ///< The byte alignment the device expects for each RNDIS message that is part of a multimessage transfer to it. The value is specified as an exponent of 2; for example, the host uses 2{PacketAlignmentFactor} as the alignment value. + uint32_t reserved[2] ; +} rndis_msg_initialize_cmplt_t; + +//------------- Query -------------// +/// \brief Query Message +/// \details This message MUST be sent by the host to query an OID. +typedef struct { + uint32_t type ; ///< Message Type, must be \ref RNDIS_MSG_QUERY + uint32_t length ; ///< Message length in bytes, including the header and the \a oid_buffer + uint32_t request_id ; ///< A 32-bit integer value, generated by the host, used to match the host's sent request to the response from the device. + uint32_t oid ; ///< The integer value of the host operating system-defined identifier, for the parameter of the device being queried for. + uint32_t buffer_length ; ///< The length, in bytes, of the input data required for the OID query. This MUST be set to 0 when there is no input data associated with the OID. + uint32_t buffer_offset ; ///< The offset, in bytes, from the beginning of \a request_id field where the input data for the query is located in the message. This value MUST be set to 0 when there is no input data associated with the OID. + uint32_t reserved ; + uint8_t oid_buffer[] ; ///< Flexible array contains the input data supplied by the host, required for the OID query request processing by the device, as per the host NDIS specification. +} rndis_msg_query_t, rndis_msg_set_t; + +VERIFY_STATIC(sizeof(rndis_msg_query_t) == 28, "Make sure flexible array member does not affect layout"); + +/// \brief Query Complete Message +/// \details This message MUST be sent by the device in response to a query OID message. +typedef struct { + uint32_t type ; ///< Message Type, must be \ref RNDIS_MSG_QUERY_CMPLT + uint32_t length ; ///< Message length in bytes, including the header and the \a oid_buffer + uint32_t request_id ; ///< A 32-bit integer value from \a request_id field of the \ref rndis_msg_query_t to which this message is a response. + uint32_t status ; ///< The status of processing for the query request, has value from \ref rndis_msg_status_t. + uint32_t buffer_length ; ///< The length, in bytes, of the data in the response to the query. This MUST be set to 0 when there is no OIDInputBuffer. + uint32_t buffer_offset ; ///< The offset, in bytes, from the beginning of \a request_id field where the response data for the query is located in the message. This MUST be set to 0 when there is no \ref oid_buffer. + uint8_t oid_buffer[] ; ///< Flexible array member contains the response data to the OID query request as specified by the host. +} rndis_msg_query_cmplt_t; + +VERIFY_STATIC(sizeof(rndis_msg_query_cmplt_t) == 24, "Make sure flexible array member does not affect layout"); + +//------------- Reset -------------// +/// \brief Reset Message +/// \details This message MUST be sent by the host to perform a soft reset on the device. +typedef struct { + uint32_t type ; ///< Message Type, must be \ref RNDIS_MSG_RESET + uint32_t length ; ///< Message length in bytes, MUST be 0x06 + uint32_t reserved ; +} rndis_msg_reset_t; + +/// \brief Reset Complete Message +/// \details This message MUST be sent by the device in response to a reset message. +typedef struct { + uint32_t type ; ///< Message Type, must be \ref RNDIS_MSG_RESET_CMPLT + uint32_t length ; ///< Message length in bytes, MUST be 0x10 + uint32_t status ; ///< The status of processing for the \ref rndis_msg_reset_t, has value from \ref rndis_msg_status_t. + uint32_t addressing_reset ; ///< This field indicates whether the addressing information, which is the multicast address list or packet filter, has been lost during the reset operation. This MUST be set to 0x00000001 if the device requires that the host to resend addressing information or MUST be set to zero otherwise. +} rndis_msg_reset_cmplt_t; + +//typedef struct { +// uint32_t type; +// uint32_t length; +// uint32_t status; +// uint32_t buffer_length; +// uint32_t buffer_offset; +// uint32_t diagnostic_status; // optional +// uint32_t diagnostic_error_offset; // optional +// uint32_t status_buffer[0]; // optional +//} rndis_msg_indicate_status_t; + +/// \brief Keep Alive Message +/// \details This message MUST be sent by the host to check that device is still responsive. It is optional for the device to send this message to check if the host is active +typedef struct { + uint32_t type ; ///< Message Type + uint32_t length ; ///< Message length in bytes, MUST be 0x10 + uint32_t request_id ; +} rndis_msg_keep_alive_t, rndis_msg_halt_t; + +/// \brief Set Complete Message +/// \brief This message MUST be sent in response to a the request message +typedef struct { + uint32_t type ; ///< Message Type + uint32_t length ; ///< Message length in bytes, MUST be 0x10 + uint32_t request_id ; ///< must be the same as requesting message + uint32_t status ; ///< The status of processing for the request message request by the device to which this message is the response. +} rndis_msg_set_cmplt_t, rndis_msg_keep_alive_cmplt_t; + +/// \brief Packet Data Message +/// \brief This message MUST be used by the host and the device to send network data to one another. +typedef struct { + uint32_t type ; ///< Message Type, must be \ref RNDIS_MSG_PACKET + uint32_t length ; ///< Message length in bytes, The total length of this RNDIS message including the header, payload, and padding. + uint32_t data_offset ; ///< Specifies the offset, in bytes, from the start of this \a data_offset field of this message to the start of the data. This MUST be an integer multiple of 4. + uint32_t data_length ; ///< Specifies the number of bytes in the payload of this message. + uint32_t out_of_band_data_offet ; ///< Specifies the offset, in bytes, of the first out-of-band data record from the start of the DataOffset field in this message. MUST be an integer multiple of 4 when out-of-band data is present or set to 0 otherwise. When there are multiple out-ofband data records, each subsequent record MUST immediately follow the previous out-of-band data record. + uint32_t out_of_band_data_length ; ///< Specifies, in bytes, the total length of the out-of-band data. + uint32_t num_out_of_band_data_elements ; ///< Specifies the number of out-of-band records in this message. + uint32_t per_packet_info_offset ; ///< Specifies the offset, in bytes, of the start of per-packet-info data record from the start of the \a data_offset field in this message. MUST be an integer multiple of 4 when per-packet-info data record is present or MUST be set to 0 otherwise. When there are multiple per-packet-info data records, each subsequent record MUST immediately follow the previous record. + uint32_t per_packet_info_length ; ///< Specifies, in bytes, the total length of per-packetinformation contained in this message. + uint32_t reserved[2] ; + uint32_t payload[0] ; ///< Network data contained in this message. + + // uint8_t padding[0] + // Additional bytes of zeros added at the end of the message to comply with + // the internal and external padding requirements. Internal padding SHOULD be as per the + // specification of the out-of-band data record and per-packet-info data record. The external + //padding size SHOULD be determined based on the PacketAlignmentFactor field specification + //in REMOTE_NDIS_INITIALIZE_CMPLT message by the device, when multiple + //REMOTE_NDIS_PACKET_MSG messages are bundled together in a single bus-native message. + //In this case, all but the very last REMOTE_NDIS_PACKET_MSG MUST respect the + //PacketAlignmentFactor field. + + // rndis_msg_packet_t [0] : (optional) more packet if multiple packet per bus transaction is supported +} rndis_msg_packet_t; + + +typedef struct { + uint32_t size ; ///< Length, in bytes, of this header and appended data and padding. This value MUST be an integer multiple of 4. + uint32_t type ; ///< MUST be as per host operating system specification. + uint32_t offset ; ///< The byte offset from the beginning of this record to the beginning of data. + uint32_t data[0] ; ///< Flexible array contains data +} rndis_msg_out_of_band_data_t, rndis_msg_per_packet_info_t; + +//--------------------------------------------------------------------+ +// NDIS Object ID +//--------------------------------------------------------------------+ + +/// NDIS Object ID +typedef enum +{ + //------------- General Required OIDs -------------// + RNDIS_OID_GEN_SUPPORTED_LIST = 0x00010101, ///< List of supported OIDs + RNDIS_OID_GEN_HARDWARE_STATUS = 0x00010102, ///< Hardware status + RNDIS_OID_GEN_MEDIA_SUPPORTED = 0x00010103, ///< Media types supported (encoded) + RNDIS_OID_GEN_MEDIA_IN_USE = 0x00010104, ///< Media types in use (encoded) + RNDIS_OID_GEN_MAXIMUM_LOOKAHEAD = 0x00010105, ///< + RNDIS_OID_GEN_MAXIMUM_FRAME_SIZE = 0x00010106, ///< Maximum frame size in bytes + RNDIS_OID_GEN_LINK_SPEED = 0x00010107, ///< Link speed in units of 100 bps + RNDIS_OID_GEN_TRANSMIT_BUFFER_SPACE = 0x00010108, ///< Transmit buffer space + RNDIS_OID_GEN_RECEIVE_BUFFER_SPACE = 0x00010109, ///< Receive buffer space + RNDIS_OID_GEN_TRANSMIT_BLOCK_SIZE = 0x0001010A, ///< Minimum amount of storage, in bytes, that a single packet occupies in the transmit buffer space of the NIC + RNDIS_OID_GEN_RECEIVE_BLOCK_SIZE = 0x0001010B, ///< Amount of storage, in bytes, that a single packet occupies in the receive buffer space of the NIC + RNDIS_OID_GEN_VENDOR_ID = 0x0001010C, ///< Vendor NIC code + RNDIS_OID_GEN_VENDOR_DESCRIPTION = 0x0001010D, ///< Vendor network card description + RNDIS_OID_GEN_CURRENT_PACKET_FILTER = 0x0001010E, ///< Current packet filter (encoded) + RNDIS_OID_GEN_CURRENT_LOOKAHEAD = 0x0001010F, ///< Current lookahead size in bytes + RNDIS_OID_GEN_DRIVER_VERSION = 0x00010110, ///< NDIS version number used by the driver + RNDIS_OID_GEN_MAXIMUM_TOTAL_SIZE = 0x00010111, ///< Maximum total packet length in bytes + RNDIS_OID_GEN_PROTOCOL_OPTIONS = 0x00010112, ///< Optional protocol flags (encoded) + RNDIS_OID_GEN_MAC_OPTIONS = 0x00010113, ///< Optional NIC flags (encoded) + RNDIS_OID_GEN_MEDIA_CONNECT_STATUS = 0x00010114, ///< Whether the NIC is connected to the network + RNDIS_OID_GEN_MAXIMUM_SEND_PACKETS = 0x00010115, ///< The maximum number of send packets the driver can accept per call to its MiniportSendPacketsfunction + + //------------- General Optional OIDs -------------// + RNDIS_OID_GEN_VENDOR_DRIVER_VERSION = 0x00010116, ///< Vendor-assigned version number of the driver + RNDIS_OID_GEN_SUPPORTED_GUIDS = 0x00010117, ///< The custom GUIDs (Globally Unique Identifier) supported by the miniport driver + RNDIS_OID_GEN_NETWORK_LAYER_ADDRESSES = 0x00010118, ///< List of network-layer addresses associated with the binding between a transport and the driver + RNDIS_OID_GEN_TRANSPORT_HEADER_OFFSET = 0x00010119, ///< Size of packets' additional headers + RNDIS_OID_GEN_MEDIA_CAPABILITIES = 0x00010201, ///< + RNDIS_OID_GEN_PHYSICAL_MEDIUM = 0x00010202, ///< Physical media supported by the miniport driver (encoded) + + //------------- 802.3 Objects (Ethernet) -------------// + RNDIS_OID_802_3_PERMANENT_ADDRESS = 0x01010101, ///< Permanent station address + RNDIS_OID_802_3_CURRENT_ADDRESS = 0x01010102, ///< Current station address + RNDIS_OID_802_3_MULTICAST_LIST = 0x01010103, ///< Current multicast address list + RNDIS_OID_802_3_MAXIMUM_LIST_SIZE = 0x01010104, ///< Maximum size of multicast address list +} rndis_oid_type_t; + +/// RNDIS Packet Filter Bits \ref RNDIS_OID_GEN_CURRENT_PACKET_FILTER. +typedef enum +{ + RNDIS_PACKET_TYPE_DIRECTED = 0x00000001, ///< Directed packets. Directed packets contain a destination address equal to the station address of the NIC. + RNDIS_PACKET_TYPE_MULTICAST = 0x00000002, ///< Multicast address packets sent to addresses in the multicast address list. + RNDIS_PACKET_TYPE_ALL_MULTICAST = 0x00000004, ///< All multicast address packets, not just the ones enumerated in the multicast address list. + RNDIS_PACKET_TYPE_BROADCAST = 0x00000008, ///< Broadcast packets. + RNDIS_PACKET_TYPE_SOURCE_ROUTING = 0x00000010, ///< All source routing packets. If the protocol driver sets this bit, the NDIS library attempts to act as a source routing bridge. + RNDIS_PACKET_TYPE_PROMISCUOUS = 0x00000020, ///< Specifies all packets regardless of whether VLAN filtering is enabled or not and whether the VLAN identifier matches or not. + RNDIS_PACKET_TYPE_SMT = 0x00000040, ///< SMT packets that an FDDI NIC receives. + RNDIS_PACKET_TYPE_ALL_LOCAL = 0x00000080, ///< All packets sent by installed protocols and all packets indicated by the NIC that is identified by a given NdisBindingHandle. + RNDIS_PACKET_TYPE_GROUP = 0x00001000, ///< Packets sent to the current group address. + RNDIS_PACKET_TYPE_ALL_FUNCTIONAL = 0x00002000, ///< All functional address packets, not just the ones in the current functional address. + RNDIS_PACKET_TYPE_FUNCTIONAL = 0x00004000, ///< Functional address packets sent to addresses included in the current functional address. + RNDIS_PACKET_TYPE_MAC_FRAME = 0x00008000, ///< NIC driver frames that a Token Ring NIC receives. + RNDIS_PACKET_TYPE_NO_LOCAL = 0x00010000, +} rndis_packet_filter_type_t; + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_CDC_RNDIS_H_ */ + +/** @} */ +/** @} */ diff --git a/src/class/cdc/cdc_rndis_host.c b/src/class/cdc/cdc_rndis_host.c new file mode 100644 index 000000000..62361feb4 --- /dev/null +++ b/src/class/cdc/cdc_rndis_host.c @@ -0,0 +1,293 @@ +/**************************************************************************/ +/*! + @file cdc_rndis_host.c + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#include "tusb_option.h" + +#if (MODE_HOST_SUPPORTED && CFG_TUSB_HOST_CDC && CFG_TUSB_HOST_CDC_RNDIS) + +#define _TINY_USB_SOURCE_FILE_ + +//--------------------------------------------------------------------+ +// INCLUDE +//--------------------------------------------------------------------+ +#include "common/tusb_common.h" +#include "cdc_host.h" +#include "cdc_rndis_host.h" + +//--------------------------------------------------------------------+ +// MACRO CONSTANT TYPEDEF +//--------------------------------------------------------------------+ +#define RNDIS_MSG_PAYLOAD_MAX (1024*4) + +CFG_TUSB_ATTR_USBRAM static uint8_t msg_notification[CFG_TUSB_HOST_DEVICE_MAX][8]; +CFG_TUSB_ATTR_USBRAM ATTR_ALIGNED(4) static uint8_t msg_payload[RNDIS_MSG_PAYLOAD_MAX]; + +STATIC_VAR rndish_data_t rndish_data[CFG_TUSB_HOST_DEVICE_MAX]; + +// TODO Microsoft requires message length for any get command must be at least 4096 bytes + +//--------------------------------------------------------------------+ +// INTERNAL OBJECT & FUNCTION DECLARATION +//--------------------------------------------------------------------+ +static tusb_error_t rndis_body_subtask(void); +static tusb_error_t send_message_get_response_subtask( uint8_t dev_addr, cdch_data_t *p_cdc, + uint8_t * p_mess, uint32_t mess_length, + uint8_t *p_response ); + +//--------------------------------------------------------------------+ +// APPLICATION API +//--------------------------------------------------------------------+ +tusb_error_t tusbh_cdc_rndis_get_mac_addr(uint8_t dev_addr, uint8_t mac_address[6]) +{ + TU_ASSERT( tusbh_cdc_rndis_is_mounted(dev_addr), TUSB_ERROR_CDCH_DEVICE_NOT_MOUNTED); + VERIFY( mac_address, TUSB_ERROR_INVALID_PARA); + + memcpy(mac_address, rndish_data[dev_addr-1].mac_address, 6); + + return TUSB_ERROR_NONE; +} + +//--------------------------------------------------------------------+ +// IMPLEMENTATION +//--------------------------------------------------------------------+ + +// To enable the TASK_ASSERT style (quick return on false condition) in a real RTOS, a task must act as a wrapper +// and is used mainly to call subtasks. Within a subtask return statement can be called freely, the task with +// forever loop cannot have any return at all. +OSAL_TASK_FUNCTION(cdch_rndis_task) (void* param;) +{ + OSAL_TASK_BEGIN + rndis_body_subtask(); + OSAL_TASK_END +} + +static tusb_error_t rndis_body_subtask(void) +{ + static uint8_t relative_addr; + + OSAL_SUBTASK_BEGIN + + for (relative_addr = 0; relative_addr < CFG_TUSB_HOST_DEVICE_MAX; relative_addr++) + { + + } + + osal_task_delay(100); + + OSAL_SUBTASK_END +} + +//--------------------------------------------------------------------+ +// RNDIS-CDC Driver API +//--------------------------------------------------------------------+ +void rndish_init(void) +{ + memclr_(rndish_data, sizeof(rndish_data_t)*CFG_TUSB_HOST_DEVICE_MAX); + + //------------- Task creation -------------// + + //------------- semaphore creation for notificaiton pipe -------------// + for(uint8_t i=0; itype == RNDIS_MSG_INITIALIZE_CMPLT && p_init_cmpt->status == RNDIS_STATUS_SUCCESS && + p_init_cmpt->max_packet_per_xfer == 1 && p_init_cmpt->max_xfer_size <= RNDIS_MSG_PAYLOAD_MAX); + rndish_data[dev_addr-1].max_xfer_size = p_init_cmpt->max_xfer_size; + + //------------- Message Query 802.3 Permanent Address -------------// + memcpy(msg_payload, &msg_query_permanent_addr, sizeof(rndis_msg_query_t)); + memclr_(msg_payload + sizeof(rndis_msg_query_t), 6); // 6 bytes for MAC address + + STASK_INVOKE( + send_message_get_response_subtask( dev_addr, p_cdc, + msg_payload, sizeof(rndis_msg_query_t) + 6, + msg_payload), + error + ); + if ( TUSB_ERROR_NONE != error ) STASK_RETURN(error); + + rndis_msg_query_cmplt_t * const p_query_cmpt = (rndis_msg_query_cmplt_t *) msg_payload; + STASK_ASSERT(p_query_cmpt->type == RNDIS_MSG_QUERY_CMPLT && p_query_cmpt->status == RNDIS_STATUS_SUCCESS); + memcpy(rndish_data[dev_addr-1].mac_address, msg_payload + 8 + p_query_cmpt->buffer_offset, 6); + + //------------- Set OID_GEN_CURRENT_PACKET_FILTER to (DIRECTED | MULTICAST | BROADCAST) -------------// + memcpy(msg_payload, &msg_set_packet_filter, sizeof(rndis_msg_set_t)); + memclr_(msg_payload + sizeof(rndis_msg_set_t), 4); // 4 bytes for filter flags + ((rndis_msg_set_t*) msg_payload)->oid_buffer[0] = (RNDIS_PACKET_TYPE_DIRECTED | RNDIS_PACKET_TYPE_MULTICAST | RNDIS_PACKET_TYPE_BROADCAST); + + STASK_INVOKE( + send_message_get_response_subtask( dev_addr, p_cdc, + msg_payload, sizeof(rndis_msg_set_t) + 4, + msg_payload), + error + ); + if ( TUSB_ERROR_NONE != error ) STASK_RETURN(error); + + rndis_msg_set_cmplt_t * const p_set_cmpt = (rndis_msg_set_cmplt_t *) msg_payload; + STASK_ASSERT(p_set_cmpt->type == RNDIS_MSG_SET_CMPLT && p_set_cmpt->status == RNDIS_STATUS_SUCCESS); + + tusbh_cdc_rndis_mounted_cb(dev_addr); + + OSAL_SUBTASK_END +} + +void rndish_xfer_isr(cdch_data_t *p_cdc, pipe_handle_t pipe_hdl, tusb_event_t event, uint32_t xferred_bytes) +{ + if ( pipehandle_is_equal(pipe_hdl, p_cdc->pipe_notification) ) + { + osal_semaphore_post( rndish_data[pipe_hdl.dev_addr-1].sem_notification_hdl ); + } +} + +//--------------------------------------------------------------------+ +// INTERNAL & HELPER +//--------------------------------------------------------------------+ +static tusb_error_t send_message_get_response_subtask( uint8_t dev_addr, cdch_data_t *p_cdc, + uint8_t * p_mess, uint32_t mess_length, + uint8_t *p_response) +{ + tusb_error_t error; + + OSAL_SUBTASK_BEGIN + + //------------- Send RNDIS Control Message -------------// + STASK_INVOKE( + usbh_control_xfer_subtask( dev_addr, bm_request_type(TUSB_DIR_OUT, TUSB_REQ_TYPE_CLASS, TUSB_REQ_RCPT_INTERFACE), + CDC_REQUEST_SEND_ENCAPSULATED_COMMAND, 0, p_cdc->interface_number, + mess_length, p_mess), + error + ); + if ( TUSB_ERROR_NONE != error ) STASK_RETURN(error); + + //------------- waiting for Response Available notification -------------// + (void) hcd_pipe_xfer(p_cdc->pipe_notification, msg_notification[dev_addr-1], 8, true); + osal_semaphore_wait(rndish_data[dev_addr-1].sem_notification_hdl, OSAL_TIMEOUT_NORMAL, &error); + if ( TUSB_ERROR_NONE != error ) STASK_RETURN(error); + STASK_ASSERT(msg_notification[dev_addr-1][0] == 1); + + //------------- Get RNDIS Message Initialize Complete -------------// + STASK_INVOKE( + usbh_control_xfer_subtask( dev_addr, bm_request_type(TUSB_DIR_IN, TUSB_REQ_TYPE_CLASS, TUSB_REQ_RCPT_INTERFACE), + CDC_REQUEST_GET_ENCAPSULATED_RESPONSE, 0, p_cdc->interface_number, + RNDIS_MSG_PAYLOAD_MAX, p_response), + error + ); + if ( TUSB_ERROR_NONE != error ) STASK_RETURN(error); + + OSAL_SUBTASK_END +} + +//static tusb_error_t send_process_msg_initialize_subtask(uint8_t dev_addr, cdch_data_t *p_cdc) +//{ +// tusb_error_t error; +// +// OSAL_SUBTASK_BEGIN +// +// *((rndis_msg_initialize_t*) msg_payload) = (rndis_msg_initialize_t) +// { +// .type = RNDIS_MSG_INITIALIZE, +// .length = sizeof(rndis_msg_initialize_t), +// .request_id = 1, // TODO should use some magic number +// .major_version = 1, +// .minor_version = 0, +// .max_xfer_size = 0x4000 // TODO mimic windows +// }; +// +// +// +// OSAL_SUBTASK_END +//} +#endif diff --git a/src/class/cdc/cdc_rndis_host.h b/src/class/cdc/cdc_rndis_host.h new file mode 100644 index 000000000..c4597daa8 --- /dev/null +++ b/src/class/cdc/cdc_rndis_host.h @@ -0,0 +1,79 @@ +/**************************************************************************/ +/*! + @file cdc_rndis_host.h + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +/** \ingroup CDC_RNDIS + * \defgroup CDC_RNSID_Host Host + * @{ */ + +#ifndef _TUSB_CDC_RNDIS_HOST_H_ +#define _TUSB_CDC_RNDIS_HOST_H_ + +#include "common/tusb_common.h" +#include "host/usbh.h" +#include "cdc_rndis.h" + +#ifdef __cplusplus + extern "C" { +#endif + +//--------------------------------------------------------------------+ +// RNDIS-CDC Driver API +//--------------------------------------------------------------------+ +#ifdef _TINY_USB_SOURCE_FILE_ + +typedef struct { + OSAL_SEM_DEF(semaphore_notification); + osal_semaphore_handle_t sem_notification_hdl; // used to wait on notification pipe + uint32_t max_xfer_size; // got from device's msg initialize complete + uint8_t mac_address[6]; +}rndish_data_t; + +void rndish_init(void); +tusb_error_t rndish_open_subtask(uint8_t dev_addr, cdch_data_t *p_cdc) ATTR_WARN_UNUSED_RESULT; +void rndish_xfer_isr(cdch_data_t *p_cdc, pipe_handle_t pipe_hdl, tusb_event_t event, uint32_t xferred_bytes); +void rndish_close(uint8_t dev_addr); + +#endif + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_CDC_RNDIS_HOST_H_ */ + +/** @} */ diff --git a/src/class/custom/custom_device.c b/src/class/custom/custom_device.c new file mode 100644 index 000000000..3d0453001 --- /dev/null +++ b/src/class/custom/custom_device.c @@ -0,0 +1,105 @@ +/**************************************************************************/ +/*! + @file custom_device.c + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2018, Adafruit Industries (adafruit.com) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/**************************************************************************/ + +#include "tusb_option.h" + +#if (MODE_DEVICE_SUPPORTED && CFG_TUD_CUSTOM_CLASS) + +#define _TINY_USB_SOURCE_FILE_ + +#include "common/tusb_common.h" +#include "custom_device.h" +#include "device/usbd_pvt.h" + +/*------------------------------------------------------------------*/ +/* MACRO TYPEDEF CONSTANT ENUM + *------------------------------------------------------------------*/ + +/*------------------------------------------------------------------*/ +/* VARIABLE DECLARATION + *------------------------------------------------------------------*/ +typedef struct { + uint8_t itf_num; + + uint8_t ep_in; + uint8_t ep_out; + +} cusd_interface_t; + +static cusd_interface_t _cusd_itf; + +/*------------------------------------------------------------------*/ +/* FUNCTION DECLARATION + *------------------------------------------------------------------*/ +void cusd_init(void) +{ + varclr_(&_cusd_itf); +} + +tusb_error_t cusd_open(uint8_t rhport, tusb_desc_interface_t const * p_desc_itf, uint16_t *p_len) +{ + cusd_interface_t* p_itf = &_cusd_itf; + + // Open endpoint pair with usbd helper + tusb_desc_endpoint_t const *p_desc_ep = (tusb_desc_endpoint_t const *) descriptor_next( (uint8_t const*) p_desc_itf ); + TU_ASSERT_ERR( usbd_open_edpt_pair(rhport, p_desc_ep, TUSB_XFER_BULK, &p_itf->ep_out, &p_itf->ep_in) ); + + p_itf->itf_num = p_desc_itf->bInterfaceNumber; + + (*p_len) = sizeof(tusb_desc_interface_t) + 2*sizeof(tusb_desc_endpoint_t); + + // TODO Prepare for incoming data +// TU_ASSERT( dcd_edpt_xfer(rhport, p_itf->ep_out, (uint8_t*) &p_msc->cbw, sizeof(msc_cbw_t)), TUSB_ERROR_DCD_EDPT_XFER ); + + return TUSB_ERROR_NONE; +} + +tusb_error_t cusd_control_request_st(uint8_t rhport, tusb_control_request_t const * p_request) +{ + return TUSB_ERROR_DCD_CONTROL_REQUEST_NOT_SUPPORT; +} + +tusb_error_t cusd_xfer_cb(uint8_t rhport, uint8_t edpt_addr, tusb_event_t event, uint32_t xferred_bytes) +{ + return TUSB_ERROR_NONE; +} + +void cusd_close(uint8_t rhport) +{ + +} + +#endif diff --git a/src/class/custom/custom_device.h b/src/class/custom/custom_device.h new file mode 100644 index 000000000..08f4f7f4a --- /dev/null +++ b/src/class/custom/custom_device.h @@ -0,0 +1,71 @@ +/**************************************************************************/ +/*! + @file custom_device.h + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2018, Adafruit Industries (adafruit.com) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/**************************************************************************/ + +#ifndef _TUSB_CUSTOM_DEVICE_H_ +#define _TUSB_CUSTOM_DEVICE_H_ + +#include "common/tusb_common.h" +#include "device/usbd.h" + +//--------------------------------------------------------------------+ +// APPLICATION API (Multiple Root Ports) +// Should be used only with MCU that support more than 1 ports +//--------------------------------------------------------------------+ + +//--------------------------------------------------------------------+ +// APPLICATION API (Single Port) +// Should be used with MCU supporting only 1 USB port for code simplicity +//--------------------------------------------------------------------+ + + +//--------------------------------------------------------------------+ +// APPLICATION CALLBACK API (WEAK is optional) +//--------------------------------------------------------------------+ + +//--------------------------------------------------------------------+ +// USBD-CLASS DRIVER API +//--------------------------------------------------------------------+ +#ifdef _TINY_USB_SOURCE_FILE_ + +void cusd_init(void); +tusb_error_t cusd_open(uint8_t rhport, tusb_desc_interface_t const * p_interface_desc, uint16_t *p_length); +tusb_error_t cusd_control_request_st(uint8_t rhport, tusb_control_request_t const * p_request); +tusb_error_t cusd_xfer_cb(uint8_t rhport, uint8_t edpt_addr, tusb_event_t event, uint32_t xferred_bytes); +void cusd_close(uint8_t rhport); +#endif + + +#endif /* _TUSB_CUSTOM_DEVICE_H_ */ diff --git a/src/class/custom/custom_host.c b/src/class/custom/custom_host.c new file mode 100644 index 000000000..ad3315980 --- /dev/null +++ b/src/class/custom/custom_host.c @@ -0,0 +1,160 @@ +/**************************************************************************/ +/*! + @file custom_host.c + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#include "tusb_option.h" + +#if (MODE_HOST_SUPPORTED && CFG_TUSB_HOST_CUSTOM_CLASS) + +#define _TINY_USB_SOURCE_FILE_ + +//--------------------------------------------------------------------+ +// INCLUDE +//--------------------------------------------------------------------+ +#include "common/tusb_common.h" +#include "custom_host.h" + +//--------------------------------------------------------------------+ +// MACRO CONSTANT TYPEDEF +//--------------------------------------------------------------------+ + +//--------------------------------------------------------------------+ +// INTERNAL OBJECT & FUNCTION DECLARATION +//--------------------------------------------------------------------+ +custom_interface_info_t custom_interface[CFG_TUSB_HOST_DEVICE_MAX]; + +static tusb_error_t cush_validate_paras(uint8_t dev_addr, uint16_t vendor_id, uint16_t product_id, void * p_buffer, uint16_t length) +{ + if ( !tusbh_custom_is_mounted(dev_addr, vendor_id, product_id) ) + { + return TUSB_ERROR_DEVICE_NOT_READY; + } + + TU_ASSERT( p_buffer != NULL && length != 0, TUSB_ERROR_INVALID_PARA); + + return TUSB_ERROR_NONE; +} +//--------------------------------------------------------------------+ +// APPLICATION API (need to check parameters) +//--------------------------------------------------------------------+ +tusb_error_t tusbh_custom_read(uint8_t dev_addr, uint16_t vendor_id, uint16_t product_id, void * p_buffer, uint16_t length) +{ + TU_ASSERT_ERR( cush_validate_paras(dev_addr, vendor_id, product_id, p_buffer, length) ); + + if ( !hcd_pipe_is_idle(custom_interface[dev_addr-1].pipe_in) ) + { + return TUSB_ERROR_INTERFACE_IS_BUSY; + } + + (void) hcd_pipe_xfer( custom_interface[dev_addr-1].pipe_in, p_buffer, length, true); + + return TUSB_ERROR_NONE; +} + +tusb_error_t tusbh_custom_write(uint8_t dev_addr, uint16_t vendor_id, uint16_t product_id, void const * p_data, uint16_t length) +{ + TU_ASSERT_ERR( cush_validate_paras(dev_addr, vendor_id, product_id, p_data, length) ); + + if ( !hcd_pipe_is_idle(custom_interface[dev_addr-1].pipe_out) ) + { + return TUSB_ERROR_INTERFACE_IS_BUSY; + } + + (void) hcd_pipe_xfer( custom_interface[dev_addr-1].pipe_out, p_data, length, true); + + return TUSB_ERROR_NONE; +} + +//--------------------------------------------------------------------+ +// USBH-CLASS API +//--------------------------------------------------------------------+ +void cush_init(void) +{ + memclr_(&custom_interface, sizeof(custom_interface_info_t) * CFG_TUSB_HOST_DEVICE_MAX); +} + +tusb_error_t cush_open_subtask(uint8_t dev_addr, tusb_desc_interface_t const *p_interface_desc, uint16_t *p_length) +{ + // FIXME quick hack to test lpc1k custom class with 2 bulk endpoints + uint8_t const *p_desc = (uint8_t const *) p_interface_desc; + p_desc = descriptor_next(p_desc); + + //------------- Bulk Endpoints Descriptor -------------// + for(uint32_t i=0; i<2; i++) + { + tusb_desc_endpoint_t const *p_endpoint = (tusb_desc_endpoint_t const *) p_desc; + TU_ASSERT(TUSB_DESC_ENDPOINT == p_endpoint->bDescriptorType, TUSB_ERROR_INVALID_PARA); + + pipe_handle_t * p_pipe_hdl = ( p_endpoint->bEndpointAddress & TUSB_DIR_IN_MASK ) ? + &custom_interface[dev_addr-1].pipe_in : &custom_interface[dev_addr-1].pipe_out; + *p_pipe_hdl = hcd_pipe_open(dev_addr, p_endpoint, TUSB_CLASS_VENDOR_SPECIFIC); + TU_ASSERT ( pipehandle_is_valid(*p_pipe_hdl), TUSB_ERROR_HCD_OPEN_PIPE_FAILED ); + + p_desc = descriptor_next(p_desc); + } + + (*p_length) = sizeof(tusb_desc_interface_t) + 2*sizeof(tusb_desc_endpoint_t); + return TUSB_ERROR_NONE; +} + +void cush_isr(pipe_handle_t pipe_hdl, tusb_event_t event) +{ + +} + +void cush_close(uint8_t dev_addr) +{ + tusb_error_t err1, err2; + custom_interface_info_t * p_interface = &custom_interface[dev_addr-1]; + + // TODO re-consider to check pipe valid before calling pipe_close + if( pipehandle_is_valid( p_interface->pipe_in ) ) + { + err1 = hcd_pipe_close( p_interface->pipe_in ); + } + + if ( pipehandle_is_valid( p_interface->pipe_out ) ) + { + err2 = hcd_pipe_close( p_interface->pipe_out ); + } + + memclr_(p_interface, sizeof(custom_interface_info_t)); + + TU_ASSERT(err1 == TUSB_ERROR_NONE && err2 == TUSB_ERROR_NONE, (void) 0 ); +} + +#endif diff --git a/src/class/custom/custom_host.h b/src/class/custom/custom_host.h new file mode 100644 index 000000000..2bf3a8d3c --- /dev/null +++ b/src/class/custom/custom_host.h @@ -0,0 +1,87 @@ +/**************************************************************************/ +/*! + @file custom_host.h + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +/** \ingroup group_class + * \defgroup Group_Custom Custom Class (not supported yet) + * @{ */ + +#ifndef _TUSB_CUSTOM_HOST_H_ +#define _TUSB_CUSTOM_HOST_H_ + +#include "common/tusb_common.h" +#include "host/usbh.h" + +#ifdef __cplusplus + extern "C" { +#endif + +typedef struct { + pipe_handle_t pipe_in; + pipe_handle_t pipe_out; +}custom_interface_info_t; + +//--------------------------------------------------------------------+ +// USBH-CLASS DRIVER API +//--------------------------------------------------------------------+ +static inline bool tusbh_custom_is_mounted(uint8_t dev_addr, uint16_t vendor_id, uint16_t product_id) +{ + (void) vendor_id; // TODO check this later + (void) product_id; +// return (tusbh_device_get_mounted_class_flag(dev_addr) & BIT_(TUSB_CLASS_MAPPED_INDEX_END-1) ) != 0; + return false; +} + +tusb_error_t tusbh_custom_read(uint8_t dev_addr, uint16_t vendor_id, uint16_t product_id, void * p_buffer, uint16_t length); +tusb_error_t tusbh_custom_write(uint8_t dev_addr, uint16_t vendor_id, uint16_t product_id, void const * p_data, uint16_t length); + +#ifdef _TINY_USB_SOURCE_FILE_ + +void cush_init(void); +tusb_error_t cush_open_subtask(uint8_t dev_addr, tusb_desc_interface_t const *p_interface_desc, uint16_t *p_length) ATTR_WARN_UNUSED_RESULT; +void cush_isr(pipe_handle_t pipe_hdl, tusb_event_t event); +void cush_close(uint8_t dev_addr); + +#endif + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_CUSTOM_HOST_H_ */ + +/** @} */ diff --git a/src/class/hid/hid.h b/src/class/hid/hid.h new file mode 100644 index 000000000..d53eb979d --- /dev/null +++ b/src/class/hid/hid.h @@ -0,0 +1,595 @@ +/**************************************************************************/ +/*! + @file hid.h + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +/** \ingroup group_class + * \defgroup ClassDriver_HID Human Interface Device (HID) + * @{ */ + +#ifndef _TUSB_HID_H_ +#define _TUSB_HID_H_ + +#include "common/tusb_common.h" + +#ifdef __cplusplus + extern "C" { +#endif + +//--------------------------------------------------------------------+ +// Common Definitions +//--------------------------------------------------------------------+ +/** \defgroup ClassDriver_HID_Common Common Definitions + * @{ */ + +/// HID Subclass +typedef enum +{ + HID_SUBCLASS_NONE = 0, ///< No Subclass + HID_SUBCLASS_BOOT = 1 ///< Boot Interface Subclass +}hid_subclass_type_t; + +/// HID Protocol +typedef enum +{ + HID_PROTOCOL_NONE = 0, ///< None + HID_PROTOCOL_KEYBOARD = 1, ///< Keyboard + HID_PROTOCOL_MOUSE = 2 ///< Mouse +}hid_protocol_type_t; + +/// HID Descriptor Type +typedef enum +{ + HID_DESC_TYPE_HID = 0x21, ///< HID Descriptor + HID_DESC_TYPE_REPORT = 0x22, ///< Report Descriptor + HID_DESC_TYPE_PHYSICAL = 0x23 ///< Physical Descriptor +}hid_descriptor_type_t; + +/// HID Request Report Type +typedef enum +{ + HID_REQUEST_REPORT_INPUT = 1, ///< Input + HID_REQUEST_REPORT_OUTPUT, ///< Output + HID_REQUEST_REPORT_FEATURE ///< Feature +}hid_request_report_type_t; + +/// HID Class Specific Control Request +typedef enum +{ + HID_REQUEST_CONTROL_GET_REPORT = 0x01, ///< Get Report + HID_REQUEST_CONTROL_GET_IDLE = 0x02, ///< Get Idle + HID_REQUEST_CONTROL_GET_PROTOCOL = 0x03, ///< Get Protocol + HID_REQUEST_CONTROL_SET_REPORT = 0x09, ///< Set Report + HID_REQUEST_CONTROL_SET_IDLE = 0x0a, ///< Set Idle + HID_REQUEST_CONTROL_SET_PROTOCOL = 0x0b ///< Set Protocol +}hid_request_type_t; + +/// USB HID Descriptor +typedef struct ATTR_PACKED +{ + uint8_t bLength; /**< Numeric expression that is the total size of the HID descriptor */ + uint8_t bDescriptorType; /**< Constant name specifying type of HID descriptor. */ + + uint16_t bcdHID; /**< Numeric expression identifying the HID Class Specification release */ + uint8_t bCountryCode; /**< Numeric expression identifying country code of the localized hardware. */ + uint8_t bNumDescriptors; /**< Numeric expression specifying the number of class descriptors */ + + uint8_t bReportType; /**< Type of HID class report. */ + uint16_t wReportLength; /**< the total size of the Report descriptor. */ +} tusb_hid_descriptor_hid_t; + +/// HID Country Code +typedef enum +{ + HID_Local_NotSupported = 0 , ///< NotSupported + HID_Local_Arabic , ///< Arabic + HID_Local_Belgian , ///< Belgian + HID_Local_Canadian_Bilingual , ///< Canadian_Bilingual + HID_Local_Canadian_French , ///< Canadian_French + HID_Local_Czech_Republic , ///< Czech_Republic + HID_Local_Danish , ///< Danish + HID_Local_Finnish , ///< Finnish + HID_Local_French , ///< French + HID_Local_German , ///< German + HID_Local_Greek , ///< Greek + HID_Local_Hebrew , ///< Hebrew + HID_Local_Hungary , ///< Hungary + HID_Local_International , ///< International + HID_Local_Italian , ///< Italian + HID_Local_Japan_Katakana , ///< Japan_Katakana + HID_Local_Korean , ///< Korean + HID_Local_Latin_American , ///< Latin_American + HID_Local_Netherlands_Dutch , ///< Netherlands/Dutch + HID_Local_Norwegian , ///< Norwegian + HID_Local_Persian_Farsi , ///< Persian (Farsi) + HID_Local_Poland , ///< Poland + HID_Local_Portuguese , ///< Portuguese + HID_Local_Russia , ///< Russia + HID_Local_Slovakia , ///< Slovakia + HID_Local_Spanish , ///< Spanish + HID_Local_Swedish , ///< Swedish + HID_Local_Swiss_French , ///< Swiss/French + HID_Local_Swiss_German , ///< Swiss/German + HID_Local_Switzerland , ///< Switzerland + HID_Local_Taiwan , ///< Taiwan + HID_Local_Turkish_Q , ///< Turkish-Q + HID_Local_UK , ///< UK + HID_Local_US , ///< US + HID_Local_Yugoslavia , ///< Yugoslavia + HID_Local_Turkish_F ///< Turkish-F +} hid_country_code_t; + +/** @} */ + +//--------------------------------------------------------------------+ +// MOUSE +//--------------------------------------------------------------------+ +/** \addtogroup ClassDriver_HID_Mouse Mouse + * @{ */ + +/// Standard HID Boot Protocol Mouse Report. +typedef struct ATTR_PACKED +{ + uint8_t buttons; /**< buttons mask for currently pressed buttons in the mouse. */ + int8_t x; /**< Current delta x movement of the mouse. */ + int8_t y; /**< Current delta y movement on the mouse. */ + int8_t wheel; /**< Current delta wheel movement on the mouse. */ +} hid_mouse_report_t; + +/// Standard Mouse Buttons Bitmap +typedef enum +{ + MOUSE_BUTTON_LEFT = BIT_(0), ///< Left button + MOUSE_BUTTON_RIGHT = BIT_(1), ///< Right button + MOUSE_BUTTON_MIDDLE = BIT_(2) ///< Middle button +}hid_mouse_button_bm_t; + +/// @} + +//--------------------------------------------------------------------+ +// Keyboard +//--------------------------------------------------------------------+ +/** \addtogroup ClassDriver_HID_Keyboard Keyboard + * @{ */ + +/// Standard HID Boot Protocol Keyboard Report. +typedef struct ATTR_PACKED +{ + uint8_t modifier; /**< Keyboard modifier byte, indicating pressed modifier keys (a combination of HID_KEYBOARD_MODIFER_* masks). */ + uint8_t reserved; /**< Reserved for OEM use, always set to 0. */ + uint8_t keycode[6]; /**< Key codes of the currently pressed keys. */ +} hid_keyboard_report_t; + +/// Keyboard modifier codes bitmap +typedef enum +{ + KEYBOARD_MODIFIER_LEFTCTRL = BIT_(0), ///< Left Control + KEYBOARD_MODIFIER_LEFTSHIFT = BIT_(1), ///< Left Shift + KEYBOARD_MODIFIER_LEFTALT = BIT_(2), ///< Left Alt + KEYBOARD_MODIFIER_LEFTGUI = BIT_(3), ///< Left Window + KEYBOARD_MODIFIER_RIGHTCTRL = BIT_(4), ///< Right Control + KEYBOARD_MODIFIER_RIGHTSHIFT = BIT_(5), ///< Right Shift + KEYBOARD_MODIFIER_RIGHTALT = BIT_(6), ///< Right Alt + KEYBOARD_MODIFIER_RIGHTGUI = BIT_(7) ///< Right Window +}hid_keyboard_modifier_bm_t; + +typedef enum +{ + KEYBOARD_LED_NUMLOCK = BIT_(0), ///< Num Lock LED + KEYBOARD_LED_CAPSLOCK = BIT_(1), ///< Caps Lock LED + KEYBOARD_LED_SCROLLLOCK = BIT_(2), ///< Scroll Lock LED + KEYBOARD_LED_COMPOSE = BIT_(3), ///< Composition Mode + KEYBOARD_LED_KANA = BIT_(4) ///< Kana mode +}hid_keyboard_led_bm_t; + +/// @} + +#define HID_KEYCODE_TABLE(ENTRY) \ + ENTRY( 0x04, 'a' , 'A' )\ + ENTRY( 0x05, 'b' , 'B' )\ + ENTRY( 0x06, 'c' , 'C' )\ + ENTRY( 0x07, 'd' , 'D' )\ + ENTRY( 0x08, 'e' , 'E' )\ + ENTRY( 0x09, 'f' , 'F' )\ + ENTRY( 0x0a, 'g' , 'G' )\ + ENTRY( 0x0b, 'h' , 'H' )\ + ENTRY( 0x0c, 'i' , 'I' )\ + ENTRY( 0x0d, 'j' , 'J' )\ + ENTRY( 0x0e, 'k' , 'K' )\ + ENTRY( 0x0f, 'l' , 'L' )\ + ENTRY( 0x10, 'm' , 'M' )\ + ENTRY( 0x11, 'n' , 'N' )\ + ENTRY( 0x12, 'o' , 'O' )\ + ENTRY( 0x13, 'p' , 'P' )\ + ENTRY( 0x14, 'q' , 'Q' )\ + ENTRY( 0x15, 'r' , 'R' )\ + ENTRY( 0x16, 's' , 'S' )\ + ENTRY( 0x17, 't' , 'T' )\ + ENTRY( 0x18, 'u' , 'U' )\ + ENTRY( 0x19, 'v' , 'V' )\ + ENTRY( 0x1a, 'w' , 'W' )\ + ENTRY( 0x1b, 'x' , 'X' )\ + ENTRY( 0x1c, 'y' , 'Y' )\ + ENTRY( 0x1d, 'z' , 'Z' )\ + \ + ENTRY( 0x1e, '1' , '!' )\ + ENTRY( 0x1f, '2' , '@' )\ + ENTRY( 0x20, '3' , '#' )\ + ENTRY( 0x21, '4' , '$' )\ + ENTRY( 0x22, '5' , '%' )\ + ENTRY( 0x23, '6' , '^' )\ + ENTRY( 0x24, '7' , '&' )\ + ENTRY( 0x25, '8' , '*' )\ + ENTRY( 0x26, '9' , '(' )\ + ENTRY( 0x27, '0' , ')' )\ + \ + ENTRY( 0x28, '\r' , '\r' )\ + ENTRY( 0x29, '\x1b', '\x1b' )\ + ENTRY( 0x2a, '\b' , '\b' )\ + ENTRY( 0x2b, '\t' , '\t' )\ + ENTRY( 0x2c, ' ' , ' ' )\ + ENTRY( 0x2d, '-' , '_' )\ + ENTRY( 0x2e, '=' , '+' )\ + ENTRY( 0x2f, '[' , '{' )\ + ENTRY( 0x30, ']' , '}' )\ + ENTRY( 0x31, '\\' , '|' )\ + ENTRY( 0x32, '#' , '~' ) /* TODO non-US keyboard */ \ + ENTRY( 0x33, ';' , ':' )\ + ENTRY( 0x34, '\'' , '\"' )\ + ENTRY( 0x35, 0 , 0 )\ + ENTRY( 0x36, ',' , '<' )\ + ENTRY( 0x37, '.' , '>' )\ + ENTRY( 0x38, '/' , '?' )\ + ENTRY( 0x39, 0 , 0 ) /* TODO CapsLock, non-locking key implementation*/ \ + \ + ENTRY( 0x54, '/' , '/' )\ + ENTRY( 0x55, '*' , '*' )\ + ENTRY( 0x56, '-' , '-' )\ + ENTRY( 0x57, '+' , '+' )\ + ENTRY( 0x58, '\r' , '\r' )\ + ENTRY( 0x59, '1' , 0 ) /* numpad1 & end */ \ + ENTRY( 0x5a, '2' , 0 )\ + ENTRY( 0x5b, '3' , 0 )\ + ENTRY( 0x5c, '4' , 0 )\ + ENTRY( 0x5d, '5' , '5' )\ + ENTRY( 0x5e, '6' , 0 )\ + ENTRY( 0x5f, '7' , 0 )\ + ENTRY( 0x60, '8' , 0 )\ + ENTRY( 0x61, '9' , 0 )\ + ENTRY( 0x62, '0' , 0 )\ + ENTRY( 0x63, '0' , 0 )\ + ENTRY( 0x67, '=' , '=' )\ + + + +// TODO HID complete keycode table + +//enum +//{ +// KEYBOARD_KEYCODE_A = 0x04, +// KEYBOARD_KEYCODE_Z = 0x1d, +// +// KEYBOARD_KEYCODE_1 = 0x1e, +// KEYBOARD_KEYCODE_0 = 0x27, +// +// KEYBOARD_KEYCODE_ENTER = 0x28, +// KEYBOARD_KEYCODE_ESCAPE = 0x29, +// KEYBOARD_KEYCODE_BACKSPACE = 0x2a, +// KEYBOARD_KEYCODE_TAB = 0x2b, +// KEYBOARD_KEYCODE_SPACEBAR = 0x2c, +// +//}; + +//--------------------------------------------------------------------+ +// REPORT DESCRIPTOR +//--------------------------------------------------------------------+ +//------------- ITEM & TAG -------------// +#define HID_REPORT_DATA_0(data) +#define HID_REPORT_DATA_1(data) , data +#define HID_REPORT_DATA_2(data) , U16_TO_U8S_LE(data) +#define HID_REPORT_DATA_3(data) , U32_TO_U8S_LE(data) + +#define HID_REPORT_ITEM(data, tag, type, size) \ + (((tag) << 4) | ((type) << 2) | (size)) HID_REPORT_DATA_##size(data) + +#define RI_TYPE_MAIN 0 +#define RI_TYPE_GLOBAL 1 +#define RI_TYPE_LOCAL 2 + +//------------- MAIN ITEMS 6.2.2.4 -------------// +#define HID_INPUT(x) HID_REPORT_ITEM(x, 8, RI_TYPE_MAIN, 1) +#define HID_OUTPUT(x) HID_REPORT_ITEM(x, 9, RI_TYPE_MAIN, 1) +#define HID_COLLECTION(x) HID_REPORT_ITEM(x, 10, RI_TYPE_MAIN, 1) +#define HID_FEATURE(x) HID_REPORT_ITEM(x, 11, RI_TYPE_MAIN, 1) +#define HID_COLLECTION_END HID_REPORT_ITEM(x, 12, RI_TYPE_MAIN, 0) + +//------------- INPUT, OUTPUT, FEATURE 6.2.2.5 -------------// +#define HID_DATA (0<<0) +#define HID_CONSTANT (1<<0) + +#define HID_ARRAY (0<<1) +#define HID_VARIABLE (1<<1) + +#define HID_ABSOLUTE (0<<2) +#define HID_RELATIVE (1<<2) + +#define HID_WRAP_NO (0<<3) +#define HID_WRAP (1<<3) + +#define HID_LINEAR (0<<4) +#define HID_NONLINEAR (1<<4) + +#define HID_PREFERRED_STATE (0<<5) +#define HID_PREFERRED_NO (1<<5) + +#define HID_NO_NULL_POSITION (0<<6) +#define HID_NULL_STATE (1<<6) + +#define HID_NON_VOLATILE (0<<7) +#define HID_VOLATILE (1<<7) + +#define HID_BITFIELD (0<<8) +#define HID_BUFFERED_BYTES (1<<8) + +//------------- COLLECTION ITEM 6.2.2.6 -------------// +enum { + HID_COLLECTION_PHYSICAL = 0, + HID_COLLECTION_APPLICATION, + HID_COLLECTION_LOGICAL, + HID_COLLECTION_REPORT, + HID_COLLECTION_NAMED_ARRAY, + HID_COLLECTION_USAGE_SWITCH, + HID_COLLECTION_USAGE_MODIFIER +}; + +//------------- GLOBAL ITEMS 6.2.2.7 -------------// +#define HID_USAGE_PAGE(x) HID_REPORT_ITEM(x, 0, RI_TYPE_GLOBAL, 1) +#define HID_USAGE_PAGE_N(x, n) HID_REPORT_ITEM(x, 0, RI_TYPE_GLOBAL, n) + +#define HID_LOGICAL_MIN(x) HID_REPORT_ITEM(x, 1, RI_TYPE_GLOBAL, 1) +#define HID_LOGICAL_MIN_N(x, n) HID_REPORT_ITEM(x, 1, RI_TYPE_GLOBAL, n) + +#define HID_LOGICAL_MAX(x) HID_REPORT_ITEM(x, 2, RI_TYPE_GLOBAL, 1) +#define HID_LOGICAL_MAX_N(x, n) HID_REPORT_ITEM(x, 2, RI_TYPE_GLOBAL, n) + +#define HID_PHYSICAL_MIN(x) HID_REPORT_ITEM(x, 3, RI_TYPE_GLOBAL, 1) +#define HID_PHYSICAL_MIN_N(x, n) HID_REPORT_ITEM(x, 3, RI_TYPE_GLOBAL, n) + +#define HID_PHYSICAL_MAX(x) HID_REPORT_ITEM(x, 4, RI_TYPE_GLOBAL, 1) +#define HID_PHYSICAL_MAX_N(x, n) HID_REPORT_ITEM(x, 4, RI_TYPE_GLOBAL, n) + +#define HID_UNIT_EXPONENT(x) HID_REPORT_ITEM(x, 5, RI_TYPE_GLOBAL, 1) +#define HID_UNIT_EXPONENT_N(x, n) HID_REPORT_ITEM(x, 5, RI_TYPE_GLOBAL, n) + +#define HID_UNIT(x) HID_REPORT_ITEM(x, 6, RI_TYPE_GLOBAL, 1) +#define HID_UNIT_N(x, n) HID_REPORT_ITEM(x, 6, RI_TYPE_GLOBAL, n) + +#define HID_REPORT_SIZE(x) HID_REPORT_ITEM(x, 7, RI_TYPE_GLOBAL, 1) +#define HID_REPORT_SIZE_N(x, n) HID_REPORT_ITEM(x, 7, RI_TYPE_GLOBAL, n) + +#define HID_REPORT_ID(x) HID_REPORT_ITEM(x, 8, RI_TYPE_GLOBAL, 1) +#define HID_REPORT_ID_N(x) HID_REPORT_ITEM(x, 8, RI_TYPE_GLOBAL, n) + +#define HID_REPORT_COUNT(x) HID_REPORT_ITEM(x, 9, RI_TYPE_GLOBAL, 1) +#define HID_REPORT_COUNT_N(x, n) HID_REPORT_ITEM(x, 9, RI_TYPE_GLOBAL, n) + +#define HID_PUSH HID_REPORT_ITEM(x, 10, RI_TYPE_GLOBAL, 0) +#define HID_POP HID_REPORT_ITEM(x, 11, RI_TYPE_GLOBAL, 0) + +//------------- LOCAL ITEMS 6.2.2.8 -------------// +#define HID_USAGE(x) HID_REPORT_ITEM(x, 0, RI_TYPE_LOCAL, 1) +#define HID_USAGE_N(x, n) HID_REPORT_ITEM(x, 0, RI_TYPE_LOCAL, n) + +#define HID_USAGE_MIN(x) HID_REPORT_ITEM(x, 1, RI_TYPE_LOCAL, 1) +#define HID_USAGE_MIN_N(x, n) HID_REPORT_ITEM(x, 1, RI_TYPE_LOCAL, n) + +#define HID_USAGE_MAX(x) HID_REPORT_ITEM(x, 2, RI_TYPE_LOCAL, 1) +#define HID_USAGE_MAX_N(x, n) HID_REPORT_ITEM(x, 2, RI_TYPE_LOCAL, n) + +//--------------------------------------------------------------------+ +// Usage Table +//--------------------------------------------------------------------+ + +/// HID Usage Table - Table 1: Usage Page Summary +enum { + HID_USAGE_PAGE_DESKTOP = 0x01, + HID_USAGE_PAGE_SIMULATE = 0x02, + HID_USAGE_PAGE_VIRTUAL_REALITY = 0x03, + HID_USAGE_PAGE_SPORT = 0x04, + HID_USAGE_PAGE_GAME = 0x05, + HID_USAGE_PAGE_GENERIC_DEVICE = 0x06, + HID_USAGE_PAGE_KEYBOARD = 0x07, + HID_USAGE_PAGE_LED = 0x08, + HID_USAGE_PAGE_BUTTON = 0x09, + HID_USAGE_PAGE_ORDINAL = 0x0a, + HID_USAGE_PAGE_TELEPHONY = 0x0b, + HID_USAGE_PAGE_CONSUMER = 0x0c, + HID_USAGE_PAGE_DIGITIZER = 0x0d, + HID_USAGE_PAGE_PID = 0x0f, + HID_USAGE_PAGE_UNICODE = 0x10, + HID_USAGE_PAGE_ALPHA_DISPLAY = 0x14, + HID_USAGE_PAGE_MEDICAL = 0x40, + HID_USAGE_PAGE_MONITOR = 0x80, //0x80 - 0x83 + HID_USAGE_PAGE_POWER = 0x84, // 0x084 - 0x87 + HID_USAGE_PAGE_BARCODE_SCANNER = 0x8c, + HID_USAGE_PAGE_SCALE = 0x8d, + HID_USAGE_PAGE_MSR = 0x8e, + HID_USAGE_PAGE_CAMERA = 0x90, + HID_USAGE_PAGE_ARCADE = 0x91, + HID_USAGE_PAGE_VENDOR = 0xFFFF // 0xFF00 - 0xFFFF +}; + +/// HID Usage Table - Table 6: Generic Desktop Page +enum { + HID_USAGE_DESKTOP_POINTER = 0x01, + HID_USAGE_DESKTOP_MOUSE = 0x02, + HID_USAGE_DESKTOP_JOYSTICK = 0x04, + HID_USAGE_DESKTOP_GAMEPAD = 0x05, + HID_USAGE_DESKTOP_KEYBOARD = 0x06, + HID_USAGE_DESKTOP_KEYPAD = 0x07, + HID_USAGE_DESKTOP_MULTI_AXIS_CONTROLLER = 0x08, + HID_USAGE_DESKTOP_TABLET_PC_SYSTEM = 0x09, + HID_USAGE_DESKTOP_X = 0x30, + HID_USAGE_DESKTOP_Y = 0x31, + HID_USAGE_DESKTOP_Z = 0x32, + HID_USAGE_DESKTOP_RX = 0x33, + HID_USAGE_DESKTOP_RY = 0x34, + HID_USAGE_DESKTOP_RZ = 0x35, + HID_USAGE_DESKTOP_SLIDER = 0x36, + HID_USAGE_DESKTOP_DIAL = 0x37, + HID_USAGE_DESKTOP_WHEEL = 0x38, + HID_USAGE_DESKTOP_HAT_SWITCH = 0x39, + HID_USAGE_DESKTOP_COUNTED_BUFFER = 0x3a, + HID_USAGE_DESKTOP_BYTE_COUNT = 0x3b, + HID_USAGE_DESKTOP_MOTION_WAKEUP = 0x3c, + HID_USAGE_DESKTOP_START = 0x3d, + HID_USAGE_DESKTOP_SELECT = 0x3e, + HID_USAGE_DESKTOP_VX = 0x40, + HID_USAGE_DESKTOP_VY = 0x41, + HID_USAGE_DESKTOP_VZ = 0x42, + HID_USAGE_DESKTOP_VBRX = 0x43, + HID_USAGE_DESKTOP_VBRY = 0x44, + HID_USAGE_DESKTOP_VBRZ = 0x45, + HID_USAGE_DESKTOP_VNO = 0x46, + HID_USAGE_DESKTOP_FEATURE_NOTIFICATION = 0x47, + HID_USAGE_DESKTOP_RESOLUTION_MULTIPLIER = 0x48, + HID_USAGE_DESKTOP_SYSTEM_CONTROL = 0x80, + HID_USAGE_DESKTOP_SYSTEM_POWER_DOWN = 0x81, + HID_USAGE_DESKTOP_SYSTEM_SLEEP = 0x82, + HID_USAGE_DESKTOP_SYSTEM_WAKE_UP = 0x83, + HID_USAGE_DESKTOP_SYSTEM_CONTEXT_MENU = 0x84, + HID_USAGE_DESKTOP_SYSTEM_MAIN_MENU = 0x85, + HID_USAGE_DESKTOP_SYSTEM_APP_MENU = 0x86, + HID_USAGE_DESKTOP_SYSTEM_MENU_HELP = 0x87, + HID_USAGE_DESKTOP_SYSTEM_MENU_EXIT = 0x88, + HID_USAGE_DESKTOP_SYSTEM_MENU_SELECT = 0x89, + HID_USAGE_DESKTOP_SYSTEM_MENU_RIGHT = 0x8A, + HID_USAGE_DESKTOP_SYSTEM_MENU_LEFT = 0x8B, + HID_USAGE_DESKTOP_SYSTEM_MENU_UP = 0x8C, + HID_USAGE_DESKTOP_SYSTEM_MENU_DOWN = 0x8D, + HID_USAGE_DESKTOP_SYSTEM_COLD_RESTART = 0x8E, + HID_USAGE_DESKTOP_SYSTEM_WARM_RESTART = 0x8F, + HID_USAGE_DESKTOP_DPAD_UP = 0x90, + HID_USAGE_DESKTOP_DPAD_DOWN = 0x91, + HID_USAGE_DESKTOP_DPAD_RIGHT = 0x92, + HID_USAGE_DESKTOP_DPAD_LEFT = 0x93, + HID_USAGE_DESKTOP_SYSTEM_DOCK = 0xA0, + HID_USAGE_DESKTOP_SYSTEM_UNDOCK = 0xA1, + HID_USAGE_DESKTOP_SYSTEM_SETUP = 0xA2, + HID_USAGE_DESKTOP_SYSTEM_BREAK = 0xA3, + HID_USAGE_DESKTOP_SYSTEM_DEBUGGER_BREAK = 0xA4, + HID_USAGE_DESKTOP_APPLICATION_BREAK = 0xA5, + HID_USAGE_DESKTOP_APPLICATION_DEBUGGER_BREAK = 0xA6, + HID_USAGE_DESKTOP_SYSTEM_SPEAKER_MUTE = 0xA7, + HID_USAGE_DESKTOP_SYSTEM_HIBERNATE = 0xA8, + HID_USAGE_DESKTOP_SYSTEM_DISPLAY_INVERT = 0xB0, + HID_USAGE_DESKTOP_SYSTEM_DISPLAY_INTERNAL = 0xB1, + HID_USAGE_DESKTOP_SYSTEM_DISPLAY_EXTERNAL = 0xB2, + HID_USAGE_DESKTOP_SYSTEM_DISPLAY_BOTH = 0xB3, + HID_USAGE_DESKTOP_SYSTEM_DISPLAY_DUAL = 0xB4, + HID_USAGE_DESKTOP_SYSTEM_DISPLAY_TOGGLE_INT_EXT = 0xB5, + HID_USAGE_DESKTOP_SYSTEM_DISPLAY_SWAP_PRIMARY_SECONDARY = 0xB6, + HID_USAGE_DESKTOP_SYSTEM_DISPLAY_LCD_AUTOSCALE = 0xB7 +}; + + +/// HID Usage Table: Consumer Page (0x0C) +/// Only contains controls that supported by Windows (whole list is too long) +enum +{ + // Generic Control + HID_USAGE_CONSUMER_CONTROL = 0x0001, + + // Power Control + HID_USAGE_CONSUMER_POWER = 0x0030, + HID_USAGE_CONSUMER_RESET = 0x0031, + HID_USAGE_CONSUMER_SLEEP = 0x0032, + + // Screen Brightness + HID_USAGE_CONSUMER_BRIGHTNESS_INCREMENT = 0x006F, + HID_USAGE_CONSUMER_BRIGHTNESS_DECREMENT = 0x0070, + + // These HID usages operate only on mobile systems (battery powered) and + // require Windows 8 (build 8302 or greater). + HID_USAGE_CONSUMER_WIRELESS_RADIO_CONTROLS = 0x000C, + HID_USAGE_CONSUMER_WIRELESS_RADIO_BUTTONS = 0x00C6, + HID_USAGE_CONSUMER_WIRELESS_RADIO_LED = 0x00C7, + HID_USAGE_CONSUMER_WIRELESS_RADIO_SLIDER_SWITCH = 0x00C8, + + // Media Control + HID_USAGE_CONSUMER_PLAY_PAUSE = 0x00CD, + HID_USAGE_CONSUMER_SCAN_NEXT = 0x00B5, + HID_USAGE_CONSUMER_SCAN_PREVIOUS = 0x00B6, + HID_USAGE_CONSUMER_STOP = 0x00B7, + HID_USAGE_CONSUMER_VOLUME = 0x00E0, + HID_USAGE_CONSUMER_MUTE = 0x00E2, + HID_USAGE_CONSUMER_BASS = 0x00E3, + HID_USAGE_CONSUMER_TREBLE = 0x00E4, + HID_USAGE_CONSUMER_BASS_BOOST = 0x00E5, + HID_USAGE_CONSUMER_VOLUME_INCREMENT = 0x00E9, + HID_USAGE_CONSUMER_VOLUME_DECREMENT = 0x00EA, + HID_USAGE_CONSUMER_BASS_INCREMENT = 0x0152, + HID_USAGE_CONSUMER_BASS_DECREMENT = 0x0153, + HID_USAGE_CONSUMER_TREBLE_INCREMENT = 0x0154, + HID_USAGE_CONSUMER_TREBLE_DECREMENT = 0x0155, + + // Application Launcher + HID_USAGE_CONSUMER_AL_CONSUMER_CONTROL_CONFIGURATION = 0x0183, + HID_USAGE_CONSUMER_AL_EMAIL_READER = 0x018A, + HID_USAGE_CONSUMER_AL_CALCULATOR = 0x0192, + HID_USAGE_CONSUMER_AL_LOCAL_BROWSER = 0x0194, + + // Browser/Explorer Specific + HID_USAGE_CONSUMER_AC_SEARCH = 0x0221, + HID_USAGE_CONSUMER_AC_HOME = 0x0223, + HID_USAGE_CONSUMER_AC_BACK = 0x0224, + HID_USAGE_CONSUMER_AC_FORWARD = 0x0225, + HID_USAGE_CONSUMER_AC_STOP = 0x0226, + HID_USAGE_CONSUMER_AC_REFRESH = 0x0227, + HID_USAGE_CONSUMER_AC_BOOKMARKS = 0x022A, + + // Mouse Horizontal scroll + HID_USAGE_CONSUMER_AC_PAN = 0x0238, +}; + + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_HID_H__ */ + +/// @} diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c new file mode 100644 index 000000000..a6080e69d --- /dev/null +++ b/src/class/hid/hid_device.c @@ -0,0 +1,322 @@ +/**************************************************************************/ +/*! + @file hid_device.c + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#include "tusb_option.h" + +#if (MODE_DEVICE_SUPPORTED && DEVICE_CLASS_HID) + +#define _TINY_USB_SOURCE_FILE_ +//--------------------------------------------------------------------+ +// INCLUDE +//--------------------------------------------------------------------+ +#include "common/tusb_common.h" +#include "hid_device.h" +#include "device/usbd_pvt.h" + +//--------------------------------------------------------------------+ +// MACRO CONSTANT TYPEDEF +//--------------------------------------------------------------------+ +enum { + HIDD_NUMBER_OF_SUBCLASS = 3, + HIDD_BUFFER_SIZE = 128 +}; + +typedef struct { + uint8_t const * p_report_desc; + uint16_t report_length; + + uint8_t edpt_addr; + uint8_t interface_number; +}hidd_interface_t; + +typedef struct { + hidd_interface_t * const p_interface; + void (* const xfer_cb) (uint8_t, tusb_event_t, uint32_t); + uint16_t (* const get_report_cb) (uint8_t, hid_request_report_type_t, void**, uint16_t ); + void (* const set_report_cb) (uint8_t, hid_request_report_type_t, uint8_t[], uint16_t); +}hidd_class_driver_t; + +extern ATTR_WEAK hidd_interface_t keyboardd_data; +extern ATTR_WEAK hidd_interface_t moused_data; + +static hidd_class_driver_t const hidd_class_driver[HIDD_NUMBER_OF_SUBCLASS] = +{ +// [HID_PROTOCOL_NONE] = for HID Generic + +#if CFG_TUD_HID_KEYBOARD + [HID_PROTOCOL_KEYBOARD] = + { + .p_interface = &keyboardd_data, + .xfer_cb = tud_hid_keyboard_cb, + .get_report_cb = tud_hid_keyboard_get_report_cb, + .set_report_cb = tud_hid_keyboard_set_report_cb + }, +#endif + +#if CFG_TUD_HID_MOUSE + [HID_PROTOCOL_MOUSE] = + { + .p_interface = &moused_data, + .xfer_cb = tud_hid_mouse_cb, + .get_report_cb = tud_hid_mouse_get_report_cb, + .set_report_cb = tud_hid_mouse_set_report_cb + } +#endif +}; + +// internal buffer for transferring data +CFG_TUSB_ATTR_USBRAM STATIC_VAR uint8_t m_hid_buffer[ HIDD_BUFFER_SIZE ]; + +//--------------------------------------------------------------------+ +// KEYBOARD APPLICATION API +//--------------------------------------------------------------------+ +#if CFG_TUD_HID_KEYBOARD +STATIC_VAR hidd_interface_t keyboardd_data; + +bool tud_hid_keyboard_busy(uint8_t rhport) +{ + return dcd_edpt_busy(rhport, keyboardd_data.edpt_addr); +} + +tusb_error_t tud_hid_keyboard_send(uint8_t rhport, hid_keyboard_report_t const *p_report) +{ + VERIFY(tud_mounted(), TUSB_ERROR_USBD_DEVICE_NOT_CONFIGURED); + + hidd_interface_t * p_kbd = &keyboardd_data; // TODO &keyboardd_data[rhport]; + + TU_ASSERT( dcd_edpt_xfer(rhport, p_kbd->edpt_addr, (void*) p_report, sizeof(hid_keyboard_report_t)), TUSB_ERROR_DCD_EDPT_XFER ) ; + + return TUSB_ERROR_NONE; +} +#endif + +//--------------------------------------------------------------------+ +// MOUSE APPLICATION API +//--------------------------------------------------------------------+ +#if CFG_TUD_HID_MOUSE +STATIC_VAR hidd_interface_t moused_data; + +bool tud_hid_mouse_is_busy(uint8_t rhport) +{ + return dcd_edpt_busy(rhport, moused_data.edpt_addr); +} + +tusb_error_t tud_hid_mouse_send(uint8_t rhport, hid_mouse_report_t const *p_report) +{ + VERIFY(tud_mounted(), TUSB_ERROR_USBD_DEVICE_NOT_CONFIGURED); + + hidd_interface_t * p_mouse = &moused_data; // TODO &keyboardd_data[rhport]; + + TU_ASSERT( dcd_edpt_xfer(rhport, p_mouse->edpt_addr, (void*) p_report, sizeof(hid_mouse_report_t)), TUSB_ERROR_DCD_EDPT_XFER ) ; + + return TUSB_ERROR_NONE; +} +#endif + +//--------------------------------------------------------------------+ +// USBD-CLASS API +//--------------------------------------------------------------------+ +static void interface_clear(hidd_interface_t * p_interface) +{ + if ( p_interface != NULL ) + { + memclr_(p_interface, sizeof(hidd_interface_t)); + p_interface->interface_number = INTERFACE_INVALID_NUMBER; + } +} + +void hidd_init(void) +{ + for(uint8_t i=0; iwIndex == p_interface->interface_number) ) break; + } + + TU_ASSERT(subclass_idx < HIDD_NUMBER_OF_SUBCLASS, TUSB_ERROR_FAILED); + + hidd_class_driver_t const * const p_driver = &hidd_class_driver[subclass_idx]; + hidd_interface_t* const p_hid = p_driver->p_interface; + + OSAL_SUBTASK_BEGIN + + //------------- STD Request -------------// + if (p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD) + { + uint8_t const desc_type = u16_high_u8(p_request->wValue); + uint8_t const desc_index = u16_low_u8 (p_request->wValue); + + (void) desc_index; + + if (p_request->bRequest == TUSB_REQ_GET_DESCRIPTOR && desc_type == HID_DESC_TYPE_REPORT) + { + STASK_ASSERT ( p_hid->report_length <= HIDD_BUFFER_SIZE ); + + // copy to allow report descriptor not to be in USBRAM + memcpy(m_hid_buffer, p_hid->p_report_desc, p_hid->report_length); + + usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, m_hid_buffer, p_hid->report_length); + }else + { + dcd_control_stall(rhport); + } + } + //------------- Class Specific Request -------------// + else if (p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS) + { + if( (HID_REQUEST_CONTROL_GET_REPORT == p_request->bRequest) && (p_driver->get_report_cb != NULL) ) + { + // wValue = Report Type | Report ID + void* p_buffer = NULL; + + uint16_t actual_length = p_driver->get_report_cb(rhport, (hid_request_report_type_t) u16_high_u8(p_request->wValue), + &p_buffer, p_request->wLength); + STASK_ASSERT( p_buffer != NULL && actual_length > 0 ); + + usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, p_buffer, actual_length); + } + else if ( (HID_REQUEST_CONTROL_SET_REPORT == p_request->bRequest) && (p_driver->set_report_cb != NULL) ) + { + // return TUSB_ERROR_DCD_CONTROL_REQUEST_NOT_SUPPORT; // TODO test STALL control out endpoint (with mouse+keyboard) + // wValue = Report Type | Report ID + usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, m_hid_buffer, p_request->wLength); + + p_driver->set_report_cb(rhport, u16_high_u8(p_request->wValue), m_hid_buffer, p_request->wLength); + } + else if (HID_REQUEST_CONTROL_SET_IDLE == p_request->bRequest) + { + // uint8_t idle_rate = u16_high_u8(p_request->wValue); + dcd_control_status(rhport, p_request->bmRequestType_bit.direction); + }else + { +// HID_REQUEST_CONTROL_GET_IDLE: +// HID_REQUEST_CONTROL_GET_PROTOCOL: +// HID_REQUEST_CONTROL_SET_PROTOCOL: + dcd_control_stall(rhport); + } + }else + { + dcd_control_stall(rhport); + } + + OSAL_SUBTASK_END +} + +tusb_error_t hidd_open(uint8_t rhport, tusb_desc_interface_t const * p_interface_desc, uint16_t *p_length) +{ + uint8_t const *p_desc = (uint8_t const *) p_interface_desc; + + //------------- HID descriptor -------------// + p_desc += p_desc[DESCRIPTOR_OFFSET_LENGTH]; + tusb_hid_descriptor_hid_t const *p_desc_hid = (tusb_hid_descriptor_hid_t const *) p_desc; + TU_ASSERT(HID_DESC_TYPE_HID == p_desc_hid->bDescriptorType, TUSB_ERROR_HIDD_DESCRIPTOR_INTERFACE); + + //------------- Endpoint Descriptor -------------// + p_desc += p_desc[DESCRIPTOR_OFFSET_LENGTH]; + tusb_desc_endpoint_t const *p_desc_endpoint = (tusb_desc_endpoint_t const *) p_desc; + TU_ASSERT(TUSB_DESC_ENDPOINT == p_desc_endpoint->bDescriptorType, TUSB_ERROR_HIDD_DESCRIPTOR_INTERFACE); + + if (p_interface_desc->bInterfaceSubClass == HID_SUBCLASS_BOOT) + { + switch(p_interface_desc->bInterfaceProtocol) + { + case HID_PROTOCOL_KEYBOARD: + case HID_PROTOCOL_MOUSE: + { + hidd_class_driver_t const * const p_driver = &hidd_class_driver[p_interface_desc->bInterfaceProtocol]; + hidd_interface_t * const p_hid = p_driver->p_interface; + + VERIFY(p_hid, TUSB_ERROR_FAILED); + + VERIFY( dcd_edpt_open(rhport, p_desc_endpoint), TUSB_ERROR_DCD_FAILED ); + + p_hid->edpt_addr = p_desc_endpoint->bEndpointAddress; + + p_hid->interface_number = p_interface_desc->bInterfaceNumber; + p_hid->p_report_desc = (p_interface_desc->bInterfaceProtocol == HID_PROTOCOL_KEYBOARD) ? tusbd_descriptor_pointers.p_hid_keyboard_report : tusbd_descriptor_pointers.p_hid_mouse_report; + p_hid->report_length = p_desc_hid->wReportLength; + + VERIFY(p_hid->p_report_desc, TUSB_ERROR_DESCRIPTOR_CORRUPTED); + } + break; + + default: // TODO unknown, unsupported protocol --> skip this interface + return TUSB_ERROR_HIDD_DESCRIPTOR_INTERFACE; + } + *p_length = sizeof(tusb_desc_interface_t) + sizeof(tusb_hid_descriptor_hid_t) + sizeof(tusb_desc_endpoint_t); + }else + { + // open generic + *p_length = 0; + return TUSB_ERROR_HIDD_DESCRIPTOR_INTERFACE; + } + return TUSB_ERROR_NONE; +} + +tusb_error_t hidd_xfer_cb(uint8_t rhport, uint8_t edpt_addr, tusb_event_t event, uint32_t xferred_bytes) +{ + for(uint8_t i=0; iedpt_addr) ) + { + hidd_class_driver[i].xfer_cb(rhport, event, xferred_bytes); + } + } + + return TUSB_ERROR_NONE; +} + +#endif diff --git a/src/class/hid/hid_device.h b/src/class/hid/hid_device.h new file mode 100644 index 000000000..b211731e0 --- /dev/null +++ b/src/class/hid/hid_device.h @@ -0,0 +1,217 @@ +/**************************************************************************/ +/*! + @file hid_device.h + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#ifndef _TUSB_HID_DEVICE_H_ +#define _TUSB_HID_DEVICE_H_ + +#include "common/tusb_common.h" +#include "device/usbd.h" +#include "hid.h" + +#ifdef __cplusplus + extern "C" { +#endif + + +//--------------------------------------------------------------------+ +// KEYBOARD APPLICATION API +//--------------------------------------------------------------------+ +/** \addtogroup ClassDriver_HID_Keyboard Keyboard + * @{ */ +/** \defgroup Keyboard_Device Device + * @{ */ + +/** \brief Check if the interface is currently busy or not + * \param[in] rhport USB Controller ID + * \retval true if the interface is busy meaning the stack is still transferring/waiting data from/to host + * \retval false if the interface is not busy meaning the stack successfully transferred data from/to host + * \note This function is primarily used for polling/waiting result after \ref tusbd_hid_keyboard_send. + */ +bool tud_hid_keyboard_busy(uint8_t rhport); + +/** \brief Submit USB transfer + * \param[in] rhport USB Controller ID + * \param[in,out] p_report address that is used to store data from device. Must be accessible by usb controller (see \ref CFG_TUSB_ATTR_USBRAM) + * \returns \ref tusb_error_t type to indicate success or error condition. + * \retval TUSB_ERROR_NONE on success + * \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device + * \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request) + * \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct + * \note This function is non-blocking and returns immediately. Data will be transferred when USB Host work with this interface. + * The result of usb transfer will be reported by the interface's callback function + */ +tusb_error_t tud_hid_keyboard_send(uint8_t rhport, hid_keyboard_report_t const *p_report); + +//--------------------------------------------------------------------+ +// APPLICATION CALLBACK API +//--------------------------------------------------------------------+ + +/** \brief Callback function that is invoked when an transferring event occurred + * after invoking \ref tusbd_hid_keyboard_send + * \param[in] rhport USB Controller ID + * \param[in] event an value from \ref tusb_event_t + * \note event can be one of following + * - TUSB_EVENT_XFER_COMPLETE : previously scheduled transfer completes successfully. + * - TUSB_EVENT_XFER_ERROR : previously scheduled transfer encountered a transaction error. + * - TUSB_EVENT_XFER_STALLED : previously scheduled transfer is stalled by device. + */ +void tud_hid_keyboard_cb(uint8_t rhport, tusb_event_t event, uint32_t xferred_bytes); + +/** \brief Callback function that is invoked when USB host request \ref HID_REQUEST_CONTROL_GET_REPORT + * via control endpoint. + * \param[in] rhport USB Controller ID + * \param[in] report_type specify which report (INPUT, OUTPUT, FEATURE) that host requests + * \param[out] pp_report pointer to buffer that application need to update, value must be accessible by USB controller (see \ref CFG_TUSB_ATTR_USBRAM) + * \param[in] requested_length number of bytes that host requested + * \retval non-zero Actual number of bytes in the response's buffer. + * \retval zero indicates the current request is not supported. Tinyusb device stack will reject the request by + * sending STALL in the data phase. + * \note After this callback, the request is silently executed by the tinyusb stack, thus + * the completion of this control request will not be reported to application. + * For Keyboard, USB host often uses this to turn on/off the LED for CAPLOCKS, NUMLOCK (\ref hid_keyboard_led_bm_t) + */ +uint16_t tud_hid_keyboard_get_report_cb(uint8_t rhport, hid_request_report_type_t report_type, void** pp_report, uint16_t requested_length); + +/** \brief Callback function that is invoked when USB host request \ref HID_REQUEST_CONTROL_SET_REPORT + * via control endpoint. + * \param[in] rhport USB Controller ID + * \param[in] report_type specify which report (INPUT, OUTPUT, FEATURE) that host requests + * \param[in] p_report_data buffer containing the report's data + * \param[in] length number of bytes in the \a p_report_data + * \note By the time this callback is invoked, the USB control transfer is already completed in the hardware side. + * Application are free to handle data at its own will. + */ +void tud_hid_keyboard_set_report_cb(uint8_t rhport, hid_request_report_type_t report_type, uint8_t p_report_data[], uint16_t length); + +/** @} */ +/** @} */ + +//--------------------------------------------------------------------+ +// MOUSE APPLICATION API +//--------------------------------------------------------------------+ +/** \addtogroup ClassDriver_HID_Mouse Mouse + * @{ */ +/** \defgroup Mouse_Device Device + * @{ */ + +/** \brief Check if the interface is currently busy or not + * \param[in] rhport USB Controller ID + * \retval true if the interface is busy meaning the stack is still transferring/waiting data from/to host + * \retval false if the interface is not busy meaning the stack successfully transferred data from/to host + * \note This function is primarily used for polling/waiting result after \ref tusbd_hid_mouse_send. + */ +bool tud_hid_mouse_is_busy(uint8_t rhport); + +/** \brief Perform transfer queuing + * \param[in] rhport USB Controller ID + * \param[in,out] p_report address that is used to store data from device. Must be accessible by usb controller (see \ref CFG_TUSB_ATTR_USBRAM) + * \returns \ref tusb_error_t type to indicate success or error condition. + * \retval TUSB_ERROR_NONE on success + * \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device + * \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request) + * \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct + * \note This function is non-blocking and returns immediately. Data will be transferred when USB Host work with this interface. + * The result of usb transfer will be reported by the interface's callback function + */ +tusb_error_t tud_hid_mouse_send(uint8_t rhport, hid_mouse_report_t const *p_report); + +//--------------------------------------------------------------------+ +// APPLICATION CALLBACK API +//--------------------------------------------------------------------+ + +/** \brief Callback function that is invoked when an transferring event occurred + * after invoking \ref tusbd_hid_mouse_send + * \param[in] rhport USB Controller ID + * \param[in] event an value from \ref tusb_event_t + * \note event can be one of following + * - TUSB_EVENT_XFER_COMPLETE : previously scheduled transfer completes successfully. + * - TUSB_EVENT_XFER_ERROR : previously scheduled transfer encountered a transaction error. + * - TUSB_EVENT_XFER_STALLED : previously scheduled transfer is stalled by device. + */ +void tud_hid_mouse_cb(uint8_t rhport, tusb_event_t event, uint32_t xferred_bytes); + +/** \brief Callback function that is invoked when USB host request \ref HID_REQUEST_CONTROL_GET_REPORT + * via control endpoint. + * \param[in] rhport USB Controller ID + * \param[in] report_type specify which report (INPUT, OUTPUT, FEATURE) that host requests + * \param[out] pp_report pointer to buffer that application need to update, value must be accessible by USB controller (see \ref CFG_TUSB_ATTR_USBRAM) + * \param[in] requested_length number of bytes that host requested + * \retval non-zero Actual number of bytes in the response's buffer. + * \retval zero indicates the current request is not supported. Tinyusb device stack will reject the request by + * sending STALL in the data phase. + * \note After this callback, the request is silently executed by the tinyusb stack, thus + * the completion of this control request will not be reported to application + */ +uint16_t tud_hid_mouse_get_report_cb(uint8_t rhport, hid_request_report_type_t report_type, void** pp_report, uint16_t requested_length); + +/** \brief Callback function that is invoked when USB host request \ref HID_REQUEST_CONTROL_SET_REPORT + * via control endpoint. + * \param[in] rhport USB Controller ID + * \param[in] report_type specify which report (INPUT, OUTPUT, FEATURE) that host requests + * \param[in] p_report_data buffer containing the report's data + * \param[in] length number of bytes in the \a p_report_data + * \note By the time this callback is invoked, the USB control transfer is already completed in the hardware side. + * Application are free to handle data at its own will. + */ +void tud_hid_mouse_set_report_cb(uint8_t rhport, hid_request_report_type_t report_type, uint8_t p_report_data[], uint16_t length); + +/** @} */ +/** @} */ + + + +//--------------------------------------------------------------------+ +// USBD-CLASS DRIVER API +//--------------------------------------------------------------------+ +#ifdef _TINY_USB_SOURCE_FILE_ + +void hidd_init(void); +tusb_error_t hidd_open(uint8_t rhport, tusb_desc_interface_t const * p_interface_desc, uint16_t *p_length); +tusb_error_t hidd_control_request_st(uint8_t rhport, tusb_control_request_t const * p_request); +tusb_error_t hidd_xfer_cb(uint8_t rhport, uint8_t edpt_addr, tusb_event_t event, uint32_t xferred_bytes); +void hidd_close(uint8_t rhport); + +#endif + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_HID_DEVICE_H_ */ + + diff --git a/src/class/hid/hid_host.c b/src/class/hid/hid_host.c new file mode 100644 index 000000000..69f86ee0b --- /dev/null +++ b/src/class/hid/hid_host.c @@ -0,0 +1,304 @@ +/**************************************************************************/ +/*! + @file hid_host.c + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#include "tusb_option.h" + +#if (MODE_HOST_SUPPORTED && HOST_CLASS_HID) + +#define _TINY_USB_SOURCE_FILE_ +//--------------------------------------------------------------------+ +// INCLUDE +//--------------------------------------------------------------------+ +#include "common/tusb_common.h" +#include "hid_host.h" + +//--------------------------------------------------------------------+ +// MACRO CONSTANT TYPEDEF +//--------------------------------------------------------------------+ + +//--------------------------------------------------------------------+ +// HID Interface common functions +//--------------------------------------------------------------------+ +static inline tusb_error_t hidh_interface_open(uint8_t dev_addr, uint8_t interface_number, tusb_desc_endpoint_t const *p_endpoint_desc, hidh_interface_info_t *p_hid) +{ + p_hid->pipe_hdl = hcd_pipe_open(dev_addr, p_endpoint_desc, TUSB_CLASS_HID); + p_hid->report_size = p_endpoint_desc->wMaxPacketSize.size; // TODO get size from report descriptor + p_hid->interface_number = interface_number; + + TU_ASSERT (pipehandle_is_valid(p_hid->pipe_hdl), TUSB_ERROR_HCD_FAILED); + + return TUSB_ERROR_NONE; +} + +static inline void hidh_interface_close(hidh_interface_info_t *p_hid) +{ + (void) hcd_pipe_close(p_hid->pipe_hdl); + memclr_(p_hid, sizeof(hidh_interface_info_t)); +} + +// called from public API need to validate parameters +tusb_error_t hidh_interface_get_report(uint8_t dev_addr, void * report, hidh_interface_info_t *p_hid) +{ + //------------- parameters validation -------------// + // TODO change to use is configured function + TU_ASSERT (TUSB_DEVICE_STATE_CONFIGURED == tuh_device_get_state(dev_addr), TUSB_ERROR_DEVICE_NOT_READY); + VERIFY (report, TUSB_ERROR_INVALID_PARA); + TU_ASSSERT (!hcd_pipe_is_busy(p_hid->pipe_hdl), TUSB_ERROR_INTERFACE_IS_BUSY); + + TU_ASSERT_ERR( hcd_pipe_xfer(p_hid->pipe_hdl, report, p_hid->report_size, true) ) ; + + return TUSB_ERROR_NONE; +} + +//--------------------------------------------------------------------+ +// KEYBOARD +//--------------------------------------------------------------------+ +#if CFG_TUSB_HOST_HID_KEYBOARD + +#define EXPAND_KEYCODE_TO_ASCII(keycode, ascii, shift_modified) \ + [0][keycode] = ascii,\ + [1][keycode] = shift_modified,\ + +// TODO size of table should be a macro for application to check boundary +uint8_t const hid_keycode_to_ascii_tbl[2][128] = +{ + HID_KEYCODE_TABLE(EXPAND_KEYCODE_TO_ASCII) +}; + +STATIC_VAR hidh_interface_info_t keyboardh_data[CFG_TUSB_HOST_DEVICE_MAX]; // does not have addr0, index = dev_address-1 + +//------------- KEYBOARD PUBLIC API (parameter validation required) -------------// +bool tuh_hid_keyboard_is_mounted(uint8_t dev_addr) +{ + return tuh_device_is_configured(dev_addr) && pipehandle_is_valid(keyboardh_data[dev_addr-1].pipe_hdl); +} + +tusb_error_t tuh_hid_keyboard_get_report(uint8_t dev_addr, void* p_report) +{ + return hidh_interface_get_report(dev_addr, p_report, &keyboardh_data[dev_addr-1]); +} + +bool tuh_hid_keyboard_is_busy(uint8_t dev_addr) +{ + return tuh_hid_keyboard_is_mounted(dev_addr) && + hcd_pipe_is_busy( keyboardh_data[dev_addr-1].pipe_hdl ); +} + +#endif + +//--------------------------------------------------------------------+ +// MOUSE +//--------------------------------------------------------------------+ +#if CFG_TUSB_HOST_HID_MOUSE + +STATIC_VAR hidh_interface_info_t mouseh_data[CFG_TUSB_HOST_DEVICE_MAX]; // does not have addr0, index = dev_address-1 + +//------------- Public API -------------// +bool tuh_hid_mouse_is_mounted(uint8_t dev_addr) +{ + return tuh_device_is_configured(dev_addr) && pipehandle_is_valid(mouseh_data[dev_addr-1].pipe_hdl); +} + +bool tuh_hid_mouse_is_busy(uint8_t dev_addr) +{ + return tuh_hid_mouse_is_mounted(dev_addr) && + hcd_pipe_is_busy( mouseh_data[dev_addr-1].pipe_hdl ); +} + +tusb_error_t tuh_hid_mouse_get_report(uint8_t dev_addr, void * report) +{ + return hidh_interface_get_report(dev_addr, report, &mouseh_data[dev_addr-1]); +} + +#endif + +//--------------------------------------------------------------------+ +// GENERIC +//--------------------------------------------------------------------+ +#if CFG_TUSB_HOST_HID_GENERIC + +//STATIC_ struct { +// hidh_interface_info_t +//} generic_data[CFG_TUSB_HOST_DEVICE_MAX]; + +#endif + +//--------------------------------------------------------------------+ +// CLASS-USBH API (don't require to verify parameters) +//--------------------------------------------------------------------+ +void hidh_init(void) +{ +#if CFG_TUSB_HOST_HID_KEYBOARD + memclr_(&keyboardh_data, sizeof(hidh_interface_info_t)*CFG_TUSB_HOST_DEVICE_MAX); +#endif + +#if CFG_TUSB_HOST_HID_MOUSE + memclr_(&mouseh_data, sizeof(hidh_interface_info_t)*CFG_TUSB_HOST_DEVICE_MAX); +#endif + +#if CFG_TUSB_HOST_HID_GENERIC + hidh_generic_init(); +#endif +} + +#if 0 +CFG_TUSB_ATTR_USBRAM uint8_t report_descriptor[256]; +#endif + +tusb_error_t hidh_open_subtask(uint8_t dev_addr, tusb_desc_interface_t const *p_interface_desc, uint16_t *p_length) +{ + tusb_error_t error; + uint8_t const *p_desc = (uint8_t const *) p_interface_desc; + + //------------- HID descriptor -------------// + p_desc += p_desc[DESCRIPTOR_OFFSET_LENGTH]; + tusb_hid_descriptor_hid_t const *p_desc_hid = (tusb_hid_descriptor_hid_t const *) p_desc; + TU_ASSERT(HID_DESC_TYPE_HID == p_desc_hid->bDescriptorType, TUSB_ERROR_INVALID_PARA); + + //------------- Endpoint Descriptor -------------// + p_desc += p_desc[DESCRIPTOR_OFFSET_LENGTH]; + tusb_desc_endpoint_t const * p_endpoint_desc = (tusb_desc_endpoint_t const *) p_desc; + TU_ASSERT(TUSB_DESC_ENDPOINT == p_endpoint_desc->bDescriptorType, TUSB_ERROR_INVALID_PARA); + + OSAL_SUBTASK_BEGIN + + //------------- SET IDLE (0) request -------------// + STASK_INVOKE( + usbh_control_xfer_subtask( dev_addr, bm_request_type(TUSB_DIR_OUT, TUSB_REQ_TYPE_CLASS, TUSB_REQ_RCPT_INTERFACE), + HID_REQUEST_CONTROL_SET_IDLE, 0, p_interface_desc->bInterfaceNumber, + 0, NULL ), + error + ); + (void) error; // skip if set idle is failed + +#if 0 + //------------- Get Report Descriptor TODO HID parser -------------// + if ( p_desc_hid->bNumDescriptors ) + { + STASK_INVOKE( + usbh_control_xfer_subtask( dev_addr, bm_request_type(TUSB_DIR_IN, TUSB_REQ_TYPE_STANDARD, TUSB_REQ_RCPT_INTERFACE), + TUSB_REQ_GET_DESCRIPTOR, (p_desc_hid->bReportType << 8), 0, + p_desc_hid->wReportLength, report_descriptor ), + error + ); + (void) error; // if error in getting report descriptor --> treating like there is none + } +#endif + + if ( HID_SUBCLASS_BOOT == p_interface_desc->bInterfaceSubClass ) + { + #if CFG_TUSB_HOST_HID_KEYBOARD + if ( HID_PROTOCOL_KEYBOARD == p_interface_desc->bInterfaceProtocol) + { + STASK_ASSERT_ERR ( hidh_interface_open(dev_addr, p_interface_desc->bInterfaceNumber, p_endpoint_desc, &keyboardh_data[dev_addr-1]) ); + tuh_hid_keyboard_mounted_cb(dev_addr); + } else + #endif + + #if CFG_TUSB_HOST_HID_MOUSE + if ( HID_PROTOCOL_MOUSE == p_interface_desc->bInterfaceProtocol) + { + STASK_ASSERT_ERR ( hidh_interface_open(dev_addr, p_interface_desc->bInterfaceNumber, p_endpoint_desc, &mouseh_data[dev_addr-1]) ); + tuh_hid_mouse_mounted_cb(dev_addr); + } else + #endif + + { + STASK_RETURN(TUSB_ERROR_HIDH_NOT_SUPPORTED_PROTOCOL); // exit & restart task + } + }else + { + STASK_RETURN(TUSB_ERROR_HIDH_NOT_SUPPORTED_SUBCLASS); // exit & restart task + } + + *p_length = sizeof(tusb_desc_interface_t) + sizeof(tusb_hid_descriptor_hid_t) + sizeof(tusb_desc_endpoint_t); + + OSAL_SUBTASK_END +} + +void hidh_isr(pipe_handle_t pipe_hdl, tusb_event_t event, uint32_t xferred_bytes) +{ + (void) xferred_bytes; // TODO may need to use this para later + +#if CFG_TUSB_HOST_HID_KEYBOARD + if ( pipehandle_is_equal(pipe_hdl, keyboardh_data[pipe_hdl.dev_addr-1].pipe_hdl) ) + { + tuh_hid_keyboard_isr(pipe_hdl.dev_addr, event); + return; + } +#endif + +#if CFG_TUSB_HOST_HID_MOUSE + if ( pipehandle_is_equal(pipe_hdl, mouseh_data[pipe_hdl.dev_addr-1].pipe_hdl) ) + { + tuh_hid_mouse_isr(pipe_hdl.dev_addr, event); + return; + } +#endif + +#if CFG_TUSB_HOST_HID_GENERIC + +#endif +} + +void hidh_close(uint8_t dev_addr) +{ +#if CFG_TUSB_HOST_HID_KEYBOARD + if ( pipehandle_is_valid( keyboardh_data[dev_addr-1].pipe_hdl ) ) + { + hidh_interface_close(&keyboardh_data[dev_addr-1]); + tuh_hid_keyboard_unmounted_cb(dev_addr); + } +#endif + +#if CFG_TUSB_HOST_HID_MOUSE + if( pipehandle_is_valid( mouseh_data[dev_addr-1].pipe_hdl ) ) + { + hidh_interface_close(&mouseh_data[dev_addr-1]); + tuh_hid_mouse_unmounted_cb( dev_addr ); + } +#endif + +#if CFG_TUSB_HOST_HID_GENERIC + hidh_generic_close(dev_addr); +#endif +} + + + +#endif diff --git a/src/class/hid/hid_host.h b/src/class/hid/hid_host.h new file mode 100644 index 000000000..b93bcdccb --- /dev/null +++ b/src/class/hid/hid_host.h @@ -0,0 +1,231 @@ +/**************************************************************************/ +/*! + @file hid_host.h + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +/** \addtogroup ClassDriver_HID + * @{ */ + +#ifndef _TUSB_HID_HOST_H_ +#define _TUSB_HID_HOST_H_ + +#include "common/tusb_common.h" +#include "host/usbh.h" +#include "hid.h" + +#ifdef __cplusplus + extern "C" { +#endif + +//--------------------------------------------------------------------+ +// KEYBOARD Application API +//--------------------------------------------------------------------+ +/** \addtogroup ClassDriver_HID_Keyboard Keyboard + * @{ */ + +/** \defgroup Keyboard_Host Host + * The interface API includes status checking function, data transferring function and callback functions + * @{ */ + +extern uint8_t const hid_keycode_to_ascii_tbl[2][128]; // TODO used weak attr if build failed without KEYBOARD enabled + +/** \brief Check if device supports Keyboard interface or not + * \param[in] dev_addr device address + * \retval true if device supports Keyboard interface + * \retval false if device does not support Keyboard interface or is not mounted + */ +bool tuh_hid_keyboard_is_mounted(uint8_t dev_addr) ATTR_PURE ATTR_WARN_UNUSED_RESULT; + +/** \brief Check if the interface is currently busy or not + * \param[in] dev_addr device address + * \retval true if the interface is busy meaning the stack is still transferring/waiting data from/to device + * \retval false if the interface is not busy meaning the stack successfully transferred data from/to device + * \note This function is primarily used for polling/waiting result after \ref tuh_hid_keyboard_get_report. + * Alternatively, asynchronous event API can be used + */ +bool tuh_hid_keyboard_is_busy(uint8_t dev_addr) ATTR_PURE ATTR_WARN_UNUSED_RESULT; + +/** \brief Perform a get report from Keyboard interface + * \param[in] dev_addr device address + * \param[in,out] p_report address that is used to store data from device. Must be accessible by usb controller (see \ref CFG_TUSB_ATTR_USBRAM) + * \returns \ref tusb_error_t type to indicate success or error condition. + * \retval TUSB_ERROR_NONE on success + * \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device + * \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request) + * \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct + * \note This function is non-blocking and returns immediately. The result of usb transfer will be reported by the interface's callback function + */ +tusb_error_t tuh_hid_keyboard_get_report(uint8_t dev_addr, void * p_report) /*ATTR_WARN_UNUSED_RESULT*/; + +//------------- Application Callback -------------// +/** \brief Callback function that is invoked when an transferring event occurred + * \param[in] dev_addr Address of device + * \param[in] event an value from \ref tusb_event_t + * \note event can be one of following + * - TUSB_EVENT_XFER_COMPLETE : previously scheduled transfer completes successfully. + * - TUSB_EVENT_XFER_ERROR : previously scheduled transfer encountered a transaction error. + * - TUSB_EVENT_XFER_STALLED : previously scheduled transfer is stalled by device. + * \note Application should schedule the next report by calling \ref tuh_hid_keyboard_get_report within this callback + */ +void tuh_hid_keyboard_isr(uint8_t dev_addr, tusb_event_t event); + +/** \brief Callback function that will be invoked when a device with Keyboard interface is mounted + * \param[in] dev_addr Address of newly mounted device + * \note This callback should be used by Application to set-up interface-related data + */ +void tuh_hid_keyboard_mounted_cb(uint8_t dev_addr); + +/** \brief Callback function that will be invoked when a device with Keyboard interface is unmounted + * \param[in] dev_addr Address of newly unmounted device + * \note This callback should be used by Application to tear-down interface-related data + */ +void tuh_hid_keyboard_unmounted_cb(uint8_t dev_addr); + +/** @} */ // Keyboard_Host +/** @} */ // ClassDriver_HID_Keyboard + +//--------------------------------------------------------------------+ +// MOUSE Application API +//--------------------------------------------------------------------+ +/** \addtogroup ClassDriver_HID_Mouse Mouse + * @{ */ + +/** \defgroup Mouse_Host Host + * The interface API includes status checking function, data transferring function and callback functions + * @{ */ + +/** \brief Check if device supports Mouse interface or not + * \param[in] dev_addr device address + * \retval true if device supports Mouse interface + * \retval false if device does not support Mouse interface or is not mounted + */ +bool tuh_hid_mouse_is_mounted(uint8_t dev_addr) ATTR_PURE ATTR_WARN_UNUSED_RESULT; + +/** \brief Check if the interface is currently busy or not + * \param[in] dev_addr device address + * \retval true if the interface is busy meaning the stack is still transferring/waiting data from/to device + * \retval false if the interface is not busy meaning the stack successfully transferred data from/to device + * \note This function is primarily used for polling/waiting result after \ref tuh_hid_mouse_get_report. + * Alternatively, asynchronous event API can be used + */ +bool tuh_hid_mouse_is_busy(uint8_t dev_addr) ATTR_PURE ATTR_WARN_UNUSED_RESULT; + +/** \brief Perform a get report from Mouse interface + * \param[in] dev_addr device address + * \param[in,out] p_report address that is used to store data from device. Must be accessible by usb controller (see \ref CFG_TUSB_ATTR_USBRAM) + * \returns \ref tusb_error_t type to indicate success or error condition. + * \retval TUSB_ERROR_NONE on success + * \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device + * \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request) + * \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct + * \note This function is non-blocking and returns immediately. The result of usb transfer will be reported by the interface's callback function + */ +tusb_error_t tuh_hid_mouse_get_report(uint8_t dev_addr, void* p_report) /*ATTR_WARN_UNUSED_RESULT*/; + +//------------- Application Callback -------------// +/** \brief Callback function that is invoked when an transferring event occurred + * \param[in] dev_addr Address of device + * \param[in] event an value from \ref tusb_event_t + * \note event can be one of following + * - TUSB_EVENT_XFER_COMPLETE : previously scheduled transfer completes successfully. + * - TUSB_EVENT_XFER_ERROR : previously scheduled transfer encountered a transaction error. + * - TUSB_EVENT_XFER_STALLED : previously scheduled transfer is stalled by device. + * \note Application should schedule the next report by calling \ref tuh_hid_mouse_get_report within this callback + */ +void tuh_hid_mouse_isr(uint8_t dev_addr, tusb_event_t event); + +/** \brief Callback function that will be invoked when a device with Mouse interface is mounted + * \param[in] dev_addr Address of newly mounted device + * \note This callback should be used by Application to set-up interface-related data + */ +void tuh_hid_mouse_mounted_cb(uint8_t dev_addr); + +/** \brief Callback function that will be invoked when a device with Mouse interface is unmounted + * \param[in] dev_addr Address of newly unmounted device + * \note This callback should be used by Application to tear-down interface-related data + */ +void tuh_hid_mouse_unmounted_cb(uint8_t dev_addr); + +/** @} */ // Mouse_Host +/** @} */ // ClassDriver_HID_Mouse + +//--------------------------------------------------------------------+ +// GENERIC Application API +//--------------------------------------------------------------------+ +/** \addtogroup ClassDriver_HID_Generic Generic (not supported yet) + * @{ */ + +/** \defgroup Generic_Host Host + * The interface API includes status checking function, data transferring function and callback functions + * @{ */ + +bool tuh_hid_generic_is_mounted(uint8_t dev_addr) ATTR_PURE ATTR_WARN_UNUSED_RESULT; +tusb_error_t tuh_hid_generic_get_report(uint8_t dev_addr, void* p_report, bool int_on_complete) ATTR_WARN_UNUSED_RESULT; +tusb_error_t tuh_hid_generic_set_report(uint8_t dev_addr, void* p_report, bool int_on_complete) ATTR_WARN_UNUSED_RESULT; +tusb_interface_status_t tuh_hid_generic_get_status(uint8_t dev_addr) ATTR_WARN_UNUSED_RESULT; +tusb_interface_status_t tuh_hid_generic_set_status(uint8_t dev_addr) ATTR_WARN_UNUSED_RESULT; + +//------------- Application Callback -------------// +void tuh_hid_generic_isr(uint8_t dev_addr, tusb_event_t event); + +/** @} */ // Generic_Host +/** @} */ // ClassDriver_HID_Generic + +//--------------------------------------------------------------------+ +// USBH-CLASS DRIVER API +//--------------------------------------------------------------------+ +#ifdef _TINY_USB_SOURCE_FILE_ + +typedef struct { + pipe_handle_t pipe_hdl; + uint16_t report_size; + uint8_t interface_number; +}hidh_interface_info_t; + +void hidh_init(void); +tusb_error_t hidh_open_subtask(uint8_t dev_addr, tusb_desc_interface_t const *p_interface_desc, uint16_t *p_length) ATTR_WARN_UNUSED_RESULT; +void hidh_isr(pipe_handle_t pipe_hdl, tusb_event_t event, uint32_t xferred_bytes); +void hidh_close(uint8_t dev_addr); + +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* _TUSB_HID_HOST_H_ */ + +/** @} */ // ClassDriver_HID diff --git a/src/class/msc/msc.h b/src/class/msc/msc.h new file mode 100644 index 000000000..a8af2b886 --- /dev/null +++ b/src/class/msc/msc.h @@ -0,0 +1,376 @@ +/**************************************************************************/ +/*! + @file msc.h + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +/** \ingroup group_class + * \defgroup ClassDriver_MSC MassStorage (MSC) + * @{ */ + +/** \defgroup ClassDriver_MSC_Common Common Definitions + * @{ */ + +#ifndef _TUSB_MSC_H_ +#define _TUSB_MSC_H_ + +#include + +#ifdef __cplusplus + extern "C" { +#endif + +//--------------------------------------------------------------------+ +// Mass Storage Class Constant +//--------------------------------------------------------------------+ +/// MassStorage Subclass +typedef enum +{ + MSC_SUBCLASS_RBC = 1 , ///< Reduced Block Commands (RBC) T10 Project 1240-D + MSC_SUBCLASS_SFF_MMC , ///< SFF-8020i, MMC-2 (ATAPI). Typically used by a CD/DVD device + MSC_SUBCLASS_QIC , ///< QIC-157. Typically used by a tape device + MSC_SUBCLASS_UFI , ///< UFI. Typically used by Floppy Disk Drive (FDD) device + MSC_SUBCLASS_SFF , ///< SFF-8070i. Can be used by Floppy Disk Drive (FDD) device + MSC_SUBCLASS_SCSI ///< SCSI transparent command set +}msc_subclass_type_t; + +enum { + MSC_CBW_SIGNATURE = 0x43425355, ///< Constant value of 43425355h (little endian) + MSC_CSW_SIGNATURE = 0x53425355 ///< Constant value of 53425355h (little endian) +}; + +/// \brief MassStorage Protocol. +/// \details CBI only approved to use with full-speed floopy disk & should not used with highspeed or device other than floopy +typedef enum +{ + MSC_PROTOCOL_CBI = 0 , ///< Control/Bulk/Interrupt protocol (with command completion interrupt) + MSC_PROTOCOL_CBI_NO_INTERRUPT = 1 , ///< Control/Bulk/Interrupt protocol (without command completion interrupt) + MSC_PROTOCOL_BOT = 0x50 ///< Bulk-Only Transport +}msc_protocol_type_t; + +/// MassStorage Class-Specific Control Request +typedef enum +{ + MSC_REQUEST_GET_MAX_LUN = 254, ///< The Get Max LUN device request is used to determine the number of logical units supported by the device. Logical Unit Numbers on the device shall be numbered contiguously starting from LUN 0 to a maximum LUN of 15 + MSC_REQUEST_RESET = 255 ///< This request is used to reset the mass storage device and its associated interface. This class-specific request shall ready the device for the next CBW from the host. +}msc_request_type_t; + +/// \brief Command Block Status Values +/// \details Indicates the success or failure of the command. The device shall set this byte to zero if the command completed +/// successfully. A non-zero value shall indicate a failure during command execution according to the following +typedef enum +{ + MSC_CSW_STATUS_PASSED = 0 , ///< MSC_CSW_STATUS_PASSED + MSC_CSW_STATUS_FAILED , ///< MSC_CSW_STATUS_FAILED + MSC_CSW_STATUS_PHASE_ERROR ///< MSC_CSW_STATUS_PHASE_ERROR +}msc_csw_status_t; + +/// Command Block Wrapper +typedef struct ATTR_PACKED +{ + uint32_t signature ; ///< Signature that helps identify this data packet as a CBW. The signature field shall contain the value 43425355h (little endian), indicating a CBW. + uint32_t tag ; ///< Tag sent by the host. The device shall echo the contents of this field back to the host in the dCSWTagfield of the associated CSW. The dCSWTagpositively associates a CSW with the corresponding CBW. + uint32_t xfer_bytes ; ///< The number of bytes of data that the host expects to transfer on the Bulk-In or Bulk-Out endpoint (as indicated by the Direction bit) during the execution of this command. If this field is zero, the device and the host shall transfer no data between the CBW and the associated CSW, and the device shall ignore the value of the Direction bit in bmCBWFlags. + uint8_t dir ; ///< Bit 7 of this field define transfer direction \n - 0 : Data-Out from host to the device. \n - 1 : Data-In from the device to the host. + uint8_t lun ; ///< The device Logical Unit Number (LUN) to which the command block is being sent. For devices that support multiple LUNs, the host shall place into this field the LUN to which this command block is addressed. Otherwise, the host shall set this field to zero. + uint8_t cmd_len ; ///< The valid length of the CBWCBin bytes. This defines the valid length of the command block. The only legal values are 1 through 16 + uint8_t command[16] ; ///< The command block to be executed by the device. The device shall interpret the first cmd_len bytes in this field as a command block +}msc_cbw_t; + +VERIFY_STATIC(sizeof(msc_cbw_t) == 31, "size is not correct"); + +/// Command Status Wrapper +typedef struct ATTR_PACKED +{ + uint32_t signature ; ///< Signature that helps identify this data packet as a CSW. The signature field shall contain the value 53425355h (little endian), indicating CSW. + uint32_t tag ; ///< The device shall set this field to the value received in the dCBWTag of the associated CBW. + uint32_t data_residue ; ///< For Data-Out the device shall report in the dCSWDataResiduethe difference between the amount of data expected as stated in the dCBWDataTransferLength, and the actual amount of data processed by the device. For Data-In the device shall report in the dCSWDataResiduethe difference between the amount of data expected as stated in the dCBWDataTransferLengthand the actual amount of relevant data sent by the device + uint8_t status ; ///< indicates the success or failure of the command. Values from \ref msc_csw_status_t +}msc_csw_t; + +VERIFY_STATIC(sizeof(msc_csw_t) == 13, "size is not correct"); + +//--------------------------------------------------------------------+ +// SCSI Constant +//--------------------------------------------------------------------+ + +/// SCSI Command Operation Code +typedef enum +{ + SCSI_CMD_TEST_UNIT_READY = 0x00, ///< The SCSI Test Unit Ready command is used to determine if a device is ready to transfer data (read/write), i.e. if a disk has spun up, if a tape is loaded and ready etc. The device does not perform a self-test operation. + SCSI_CMD_INQUIRY = 0x12, ///< The SCSI Inquiry command is used to obtain basic information from a target device. + SCSI_CMD_MODE_SELECT_6 = 0x15, ///< provides a means for the application client to specify medium, logical unit, or peripheral device parameters to the device server. Device servers that implement the MODE SELECT(6) command shall also implement the MODE SENSE(6) command. Application clients should issue MODE SENSE(6) prior to each MODE SELECT(6) to determine supported mode pages, page lengths, and other parameters. + SCSI_CMD_MODE_SENSE_6 = 0x1A, ///< provides a means for a device server to report parameters to an application client. It is a complementary command to the MODE SELECT(6) command. Device servers that implement the MODE SENSE(6) command shall also implement the MODE SELECT(6) command. + SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL = 0x1E, + SCSI_CMD_READ_CAPACITY_10 = 0x25, ///< The SCSI Read Capacity command is used to obtain data capacity information from a target device. + SCSI_CMD_REQUEST_SENSE = 0x03, ///< The SCSI Request Sense command is part of the SCSI computer protocol standard. This command is used to obtain sense data -- status/error information -- from a target device. + SCSI_CMD_READ_FORMAT_CAPACITY = 0x23, ///< The command allows the Host to request a list of the possible format capacities for an installed writable media. This command also has the capability to report the writable capacity for a media when it is installed + SCSI_CMD_READ_10 = 0x28, ///< The READ (10) command requests that the device server read the specified logical block(s) and transfer them to the data-in buffer. + SCSI_CMD_WRITE_10 = 0x2A, ///< The WRITE (10) command requests thatthe device server transfer the specified logical block(s) from the data-out buffer and write them. +}scsi_cmd_type_t; + +/// SCSI Sense Key +typedef enum +{ + SCSI_SENSEKEY_NONE = 0x00, ///< no specific Sense Key. This would be the case for a successful command + SCSI_SENSEKEY_RECOVERED_ERROR = 0x01, ///< ndicates the last command completed successfully with some recovery action performed by the disc drive. + SCSI_SENSEKEY_NOT_READY = 0x02, ///< Indicates the logical unit addressed cannot be accessed. + SCSI_SENSEKEY_MEDIUM_ERROR = 0x03, ///< Indicates the command terminated with a non-recovered error condition. + SCSI_SENSEKEY_HARDWARE_ERROR = 0x04, ///< Indicates the disc drive detected a nonrecoverable hardware failure while performing the command or during a self test. + SCSI_SENSEKEY_ILLEGLA_REQUEST = 0x05, ///< Indicates an illegal parameter in the command descriptor block or in the additional parameters + SCSI_SENSEKEY_UNIT_ATTENTION = 0x06, ///< Indicates the disc drive may have been reset. + SCSI_SENSEKEY_DATA_PROTECT = 0x07, ///< Indicates that a command that reads or writes the medium was attempted on a block that is protected from this operation. The read or write operation is not performed. + SCSI_SENSEKEY_FIRMWARE_ERROR = 0x08, ///< Vendor specific sense key. + SCSI_SENSEKEY_ABORTED_COMMAND = 0x0b, ///< Indicates the disc drive aborted the command. + SCSI_SENSEKEY_EQUAL = 0x0c, ///< Indicates a SEARCH DATA command has satisfied an equal comparison. + SCSI_SENSEKEY_VOLUME_OVERFLOW = 0x0d, ///< Indicates a buffered peripheral device has reached the end of medium partition and data remains in the buffer that has not been written to the medium. + SCSI_SENSEKEY_MISCOMPARE = 0x0e ///< ndicates that the source data did not match the data read from the medium. +}scsi_sense_key_type_t; + +//--------------------------------------------------------------------+ +// SCSI Primary Command (SPC-4) +//--------------------------------------------------------------------+ + +/// SCSI Test Unit Ready Command +typedef struct ATTR_PACKED +{ + uint8_t cmd_code ; ///< SCSI OpCode for \ref SCSI_CMD_TEST_UNIT_READY + uint8_t lun ; ///< Logical Unit + uint8_t reserved[3] ; + uint8_t control ; +} scsi_test_unit_ready_t; + +VERIFY_STATIC(sizeof(scsi_test_unit_ready_t) == 6, "size is not correct"); + +/// SCSI Inquiry Command +typedef struct ATTR_PACKED +{ + uint8_t cmd_code ; ///< SCSI OpCode for \ref SCSI_CMD_INQUIRY + uint8_t reserved1 ; + uint8_t page_code ; + uint8_t reserved2 ; + uint8_t alloc_length ; ///< specifies the maximum number of bytes that USB host has allocated in the Data-In Buffer. An allocation length of zero specifies that no data shall be transferred. + uint8_t control ; +} scsi_inquiry_t, scsi_request_sense_t; + +VERIFY_STATIC(sizeof(scsi_inquiry_t) == 6, "size is not correct"); + +/// SCSI Inquiry Response Data +typedef struct ATTR_PACKED +{ + uint8_t peripheral_device_type : 5; + uint8_t peripheral_qualifier : 3; + + uint8_t : 7; + uint8_t is_removable : 1; + + uint8_t version; + + uint8_t response_data_format : 4; + uint8_t hierarchical_support : 1; + uint8_t normal_aca : 1; + uint8_t : 2; + + uint8_t additional_length; + + uint8_t protect : 1; + uint8_t : 2; + uint8_t third_party_copy : 1; + uint8_t target_port_group_support : 2; + uint8_t access_control_coordinator : 1; + uint8_t scc_support : 1; + + uint8_t addr16 : 1; + uint8_t : 3; + uint8_t multi_port : 1; + uint8_t : 1; // vendor specific + uint8_t enclosure_service : 1; + uint8_t : 1; + + uint8_t : 1; // vendor specific + uint8_t cmd_que : 1; + uint8_t : 2; + uint8_t sync : 1; + uint8_t wbus16 : 1; + uint8_t : 2; + + uint8_t vendor_id[8] ; ///< 8 bytes of ASCII data identifying the vendor of the product. The T10 vendor identification shall be one assigned by INCITS. A list of assigned T10 vendor identifications is in Annex E and on the T10 web site (http://www.t10.org). + uint8_t product_id[16] ; ///< 16 bytes of ASCII data defined by the vendor. + uint8_t product_revision[4] ; ///< 4 bytes of ASCII data defined by the vendor. +} scsi_inquiry_data_t; + +VERIFY_STATIC(sizeof(scsi_inquiry_data_t) == 36, "size is not correct"); + + +typedef struct ATTR_PACKED +{ + uint8_t response_code : 7; ///< 70h - current errors, Fixed Format 71h - deferred errors, Fixed Format + uint8_t valid : 1; + + uint8_t reserved; ///< Obsolete + + uint8_t sense_key : 4; + uint8_t : 1; + uint8_t incorrect_len_idicatior : 1; + uint8_t end_of_medium : 1; + uint8_t filemark : 1; + + uint32_t information; + uint8_t additional_sense_len; + uint32_t command_specific_info; + uint8_t additional_sense_code; + uint8_t additional_sense_qualifier; + uint8_t field_replaceable_unit_code; + + uint8_t sense_key_specific[3]; ///< sense key specific valid bit is bit 7 of key[0], aka MSB in Big Endian layout + +} scsi_sense_fixed_data_t; + +VERIFY_STATIC(sizeof(scsi_sense_fixed_data_t) == 18, "size is not correct"); + +typedef struct ATTR_PACKED +{ + uint8_t cmd_code ; ///< SCSI OpCode for \ref SCSI_CMD_MODE_SENSE_6 + + uint8_t : 3; + uint8_t disable_block_descriptor : 1; + uint8_t : 0; + + uint8_t page_code : 6; + uint8_t page_control : 2; + + uint8_t subpage_code; + uint8_t alloc_length; + uint8_t control; +} scsi_mode_sense_6_t; + +VERIFY_STATIC( sizeof(scsi_mode_sense_6_t) == 6, "size is not correct"); + +typedef struct ATTR_PACKED +{ + uint8_t mode_data_length; + uint8_t medium_type; + uint8_t device_specific_para; + uint8_t block_descriptor_length; +} scsi_mode_parameters_t; + +VERIFY_STATIC( sizeof(scsi_mode_parameters_t) == 4, "size is not correct"); + +typedef struct ATTR_PACKED +{ + uint8_t cmd_code; ///< SCSI OpCode for \ref SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL + uint8_t reserved[3]; + uint8_t prohibit_removal; + uint8_t control; +} scsi_prevent_allow_medium_removal_t; + +VERIFY_STATIC( sizeof(scsi_prevent_allow_medium_removal_t) == 6, "size is not correct"); + +//--------------------------------------------------------------------+ +// SCSI MMC +//--------------------------------------------------------------------+ +/// SCSI Read Format Capacity: Write Capacity +typedef struct ATTR_PACKED +{ + uint8_t cmd_code; + uint8_t reserved[6]; + uint16_t alloc_length; + uint8_t control; +} scsi_read_format_capacity_t; + +VERIFY_STATIC( sizeof(scsi_read_format_capacity_t) == 10, "size is not correct"); + +typedef struct ATTR_PACKED{ + uint8_t reserved[3]; + uint8_t list_length; /// must be 8*n, length in bytes of formattable capacity descriptor followed it. + + uint32_t block_num; /// Number of Logical Blocks + uint8_t descriptor_type; // 00: reserved, 01 unformatted media , 10 Formatted media, 11 No media present + + uint8_t reserved2; + uint16_t block_size_u16; + +} scsi_read_format_capacity_data_t; + +VERIFY_STATIC( sizeof(scsi_read_format_capacity_data_t) == 12, "size is not correct"); + +//--------------------------------------------------------------------+ +// SCSI Block Command (SBC-3) +// NOTE: All data in SCSI command are in Big Endian +//--------------------------------------------------------------------+ + +/// SCSI Read Capacity 10 Command: Read Capacity +typedef struct ATTR_PACKED +{ + uint8_t cmd_code ; ///< SCSI OpCode for \ref SCSI_CMD_READ_CAPACITY_10 + uint8_t reserved1 ; + uint32_t lba ; ///< The first Logical Block Address (LBA) accessed by this command + uint16_t reserved2 ; + uint8_t partial_medium_indicator ; + uint8_t control ; +} scsi_read_capacity10_t; + +VERIFY_STATIC(sizeof(scsi_read_capacity10_t) == 10, "size is not correct"); + +/// SCSI Read Capacity 10 Response Data +typedef struct { + uint32_t last_lba ; ///< The last Logical Block Address of the device + uint32_t block_size ; ///< Block size in bytes +} scsi_read_capacity10_data_t; + +VERIFY_STATIC(sizeof(scsi_read_capacity10_data_t) == 8, "size is not correct"); + +/// SCSI Read 10 Command +typedef struct ATTR_PACKED +{ + uint8_t cmd_code ; ///< SCSI OpCode + uint8_t reserved ; // has LUN according to wiki + uint32_t lba ; ///< The first Logical Block Address (LBA) accessed by this command + uint8_t reserved2 ; + uint16_t block_count ; ///< Number of Blocks used by this command + uint8_t control ; +} scsi_read10_t, scsi_write10_t; + +VERIFY_STATIC(sizeof(scsi_read10_t) == 10, "size is not correct"); +VERIFY_STATIC(sizeof(scsi_write10_t) == 10, "size is not correct"); + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_MSC_H_ */ + +/// @} +/// @} diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c new file mode 100644 index 000000000..c772e62a6 --- /dev/null +++ b/src/class/msc/msc_device.c @@ -0,0 +1,396 @@ +/**************************************************************************/ +/*! + @file msc_device.c + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#include "tusb_option.h" + +#if (MODE_DEVICE_SUPPORTED && CFG_TUD_MSC) + +#define _TINY_USB_SOURCE_FILE_ +//--------------------------------------------------------------------+ +// INCLUDE +//--------------------------------------------------------------------+ +#include "common/tusb_common.h" +#include "msc_device.h" +#include "device/usbd_pvt.h" + +//--------------------------------------------------------------------+ +// MACRO CONSTANT TYPEDEF +//--------------------------------------------------------------------+ +enum +{ + MSC_STAGE_CMD = 0, + MSC_STAGE_DATA, + MSC_STAGE_STATUS +}; + +typedef struct { + CFG_TUSB_MEM_ALIGN msc_cbw_t cbw; + +#if defined (__ICCARM__) && (CFG_TUSB_MCU == OPT_MCU_LPC11UXX || CFG_TUSB_MCU == OPT_MCU_LPC13UXX) + uint8_t padding1[64-sizeof(msc_cbw_t)]; // IAR cannot align struct's member +#endif + + CFG_TUSB_MEM_ALIGN msc_csw_t csw; + + uint8_t itf_num; + uint8_t ep_in; + uint8_t ep_out; + + uint8_t stage; + uint16_t data_len; + uint16_t xferred_len; // numbered of bytes transferred so far in the Data Stage +}mscd_interface_t; + +CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN static mscd_interface_t _mscd_itf; +CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN static uint8_t _mscd_buf[CFG_TUD_MSC_BUFSIZE]; + +//--------------------------------------------------------------------+ +// INTERNAL OBJECT & FUNCTION DECLARATION +//--------------------------------------------------------------------+ +static void proc_read10_cmd(uint8_t rhport, mscd_interface_t* p_msc); +static void proc_write10_cmd(uint8_t rhport, mscd_interface_t* p_msc); + +static inline uint32_t rdwr10_get_lba(uint8_t const command[]) +{ + // read10 & write10 has the same format + scsi_write10_t* p_rdwr10 = (scsi_write10_t*) command; + + // copy first to prevent mis-aligned access + uint32_t lba; + memcpy(&lba, &p_rdwr10->lba, 4); + + return __be2n(lba); +} + +static inline uint16_t rdwr10_get_blockcount(uint8_t const command[]) +{ + // read10 & write10 has the same format + scsi_write10_t* p_rdwr10 = (scsi_write10_t*) command; + + // copy first to prevent mis-aligned access + uint16_t block_count; + memcpy(&block_count, &p_rdwr10->block_count, 2); + + return __be2n(block_count); +} + + +//--------------------------------------------------------------------+ +// USBD-CLASS API +//--------------------------------------------------------------------+ +void mscd_init(void) +{ + memclr_(&_mscd_itf, sizeof(mscd_interface_t)); +} + +void mscd_close(uint8_t rhport) +{ + memclr_(&_mscd_itf, sizeof(mscd_interface_t)); +} + +tusb_error_t mscd_open(uint8_t rhport, tusb_desc_interface_t const * p_desc_itf, uint16_t *p_len) +{ + // only support SCSI's BOT protocol + VERIFY( ( MSC_SUBCLASS_SCSI == p_desc_itf->bInterfaceSubClass && + MSC_PROTOCOL_BOT == p_desc_itf->bInterfaceProtocol ), TUSB_ERROR_MSC_UNSUPPORTED_PROTOCOL ); + + mscd_interface_t * p_msc = &_mscd_itf; + + // Open endpoint pair with usbd helper + tusb_desc_endpoint_t const *p_desc_ep = (tusb_desc_endpoint_t const *) descriptor_next( (uint8_t const*) p_desc_itf ); + TU_ASSERT_ERR( usbd_open_edpt_pair(rhport, p_desc_ep, TUSB_XFER_BULK, &p_msc->ep_out, &p_msc->ep_in) ); + + p_msc->itf_num = p_desc_itf->bInterfaceNumber; + (*p_len) = sizeof(tusb_desc_interface_t) + 2*sizeof(tusb_desc_endpoint_t); + + //------------- Queue Endpoint OUT for Command Block Wrapper -------------// + TU_ASSERT( dcd_edpt_xfer(rhport, p_msc->ep_out, (uint8_t*) &p_msc->cbw, sizeof(msc_cbw_t)), TUSB_ERROR_DCD_EDPT_XFER ); + + return TUSB_ERROR_NONE; +} + +tusb_error_t mscd_control_request_st(uint8_t rhport, tusb_control_request_t const * p_request) +{ + OSAL_SUBTASK_BEGIN + + TU_ASSERT(p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS, TUSB_ERROR_DCD_CONTROL_REQUEST_NOT_SUPPORT); + + if(MSC_REQUEST_RESET == p_request->bRequest) + { + dcd_control_status(rhport, p_request->bmRequestType_bit.direction); + } + else if (MSC_REQUEST_GET_MAX_LUN == p_request->bRequest) + { + // returned MAX LUN is minus 1 by specs + _mscd_buf[0] = CFG_TUD_MSC_MAXLUN-1; + usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, _mscd_buf, 1); + }else + { + dcd_control_stall(rhport); // stall unsupported request + } + + OSAL_SUBTASK_END +} + +tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, uint32_t xferred_bytes) +{ + mscd_interface_t* p_msc = &_mscd_itf; + msc_cbw_t const * p_cbw = &p_msc->cbw; + msc_csw_t * p_csw = &p_msc->csw; + + VERIFY( (ep_addr == p_msc->ep_out) || (ep_addr == p_msc->ep_in), TUSB_ERROR_INVALID_PARA); + + switch (p_msc->stage) + { + case MSC_STAGE_CMD: + //------------- new CBW received -------------// + + // Complete IN while waiting for CMD is usually Status of previous SCSI op, ignore it + if(ep_addr != p_msc->ep_out) return TUSB_ERROR_NONE; + + TU_ASSERT( event == TUSB_EVENT_XFER_COMPLETE && + xferred_bytes == sizeof(msc_cbw_t) && p_cbw->signature == MSC_CBW_SIGNATURE, TUSB_ERROR_INVALID_PARA ); + + p_csw->signature = MSC_CSW_SIGNATURE; + p_csw->tag = p_cbw->tag; + p_csw->data_residue = 0; + + /*------------- Parse command and prepare DATA -------------*/ + p_msc->stage = MSC_STAGE_DATA; + p_msc->data_len = p_cbw->xfer_bytes; + p_msc->xferred_len = 0; + + if (SCSI_CMD_READ_10 == p_cbw->command[0]) + { + proc_read10_cmd(rhport, p_msc); + } + else if (SCSI_CMD_WRITE_10 == p_cbw->command[0]) + { + proc_write10_cmd(rhport, p_msc); + } + else + { + // For other SCSI commands + // 1. Zero : Invoke app callback, skip DATA and move to STATUS stage + // 2. OUT : queue transfer (invoke app callback after done) + // 3. IN : invoke app callback to get response + + if ( p_cbw->xfer_bytes == 0) + { + p_msc->data_len = tud_msc_scsi_cb(rhport, p_cbw->lun, p_cbw->command, NULL, 0); + p_csw->status = (p_msc->data_len == 0) ? MSC_CSW_STATUS_PASSED : MSC_CSW_STATUS_FAILED; + p_msc->stage = MSC_STAGE_STATUS; + + TU_ASSERT( p_msc->data_len == 0, TUSB_ERROR_INVALID_PARA); + } + else if ( !BIT_TEST_(p_cbw->dir, 7) ) + { + // OUT transfer + TU_ASSERT( dcd_edpt_xfer(rhport, p_msc->ep_out, _mscd_buf, p_msc->data_len), TUSB_ERROR_DCD_EDPT_XFER ); + } + else + { + p_msc->data_len = tud_msc_scsi_cb(rhport, p_cbw->lun, p_cbw->command, _mscd_buf, p_msc->data_len); + p_csw->status = (p_msc->data_len >= 0) ? MSC_CSW_STATUS_PASSED : MSC_CSW_STATUS_FAILED; + + TU_ASSERT( p_cbw->xfer_bytes >= p_msc->data_len, TUSB_ERROR_INVALID_PARA ); // cannot return more than host expect + + if ( p_msc->data_len ) + { + TU_ASSERT( dcd_edpt_xfer(rhport, p_msc->ep_in, _mscd_buf, p_msc->data_len), TUSB_ERROR_DCD_EDPT_XFER ); + }else + { + // application does not provide data to response --> possibly unsupported SCSI command + dcd_edpt_stall(rhport, p_msc->ep_in); + + p_csw->status = MSC_CSW_STATUS_FAILED; + p_msc->stage = MSC_STAGE_STATUS; + } + } + } + break; + + case MSC_STAGE_DATA: + // OUT transfer, invoke callback if needed + if ( !BIT_TEST_(p_cbw->dir, 7) ) + { + if ( SCSI_CMD_WRITE_10 != p_cbw->command[0] ) + { + p_csw->status = (tud_msc_scsi_cb(rhport, p_cbw->lun, p_cbw->command, _mscd_buf, p_msc->data_len) >= 0 ) ? MSC_CSW_STATUS_PASSED : MSC_CSW_STATUS_FAILED; + } + else + { + uint32_t lba = rdwr10_get_lba(p_cbw->command); + + // Application can consume smaller bytes + int32_t nbytes = tud_msc_write10_cb(rhport, p_cbw->lun, lba, p_msc->xferred_len, _mscd_buf, xferred_bytes); + + if ( nbytes < 0 ) + { + // negative means error -> skip to status phase, status in CSW set to failed + p_csw->data_residue = p_cbw->xfer_bytes - p_msc->xferred_len; + p_csw->status = MSC_CSW_STATUS_FAILED; + + p_msc->stage = MSC_STAGE_STATUS; + break; + }else + { + // Application consume less than what we got (including zero) + if ( nbytes < xferred_bytes ) + { + if ( nbytes > 0 ) + { + p_msc->xferred_len += nbytes; + memmove(_mscd_buf, _mscd_buf+nbytes, xferred_bytes-nbytes); + } + + // simulate an transfer complete with adjusted params + dcd_xfer_complete(rhport, p_msc->ep_out, xferred_bytes-nbytes, true); + + return TUSB_ERROR_NONE; // skip the rest + } + else + { + // Application consume all bytes in our buffer + // Nothing to do, process with normal flow + } + } + } + } + + // Accumulate data so far + p_msc->xferred_len += xferred_bytes; + + if ( p_msc->xferred_len >= p_msc->data_len ) + { + // Data Stage is complete + p_msc->stage = MSC_STAGE_STATUS; + } + else + { + // READ10 & WRITE10 Can be executed with large bulk of data e.g write 8K bytes (several flash write) + // We break it into multiple smaller command whose data size is up to CFG_TUD_MSC_BUFSIZE + if (SCSI_CMD_READ_10 == p_cbw->command[0]) + { + proc_read10_cmd(rhport, p_msc); + } + else if (SCSI_CMD_WRITE_10 == p_cbw->command[0]) + { + proc_write10_cmd(rhport, p_msc); + }else + { + // No other command take more than one transfer yet -> unlikely error + verify_breakpoint(); + } + } + break; + + case MSC_STAGE_STATUS: break; // processed immediately after this switch + default : break; + } + + if ( p_msc->stage == MSC_STAGE_STATUS ) + { + // Invoke Complete Callback if defined + if ( SCSI_CMD_READ_10 == p_cbw->command[0]) + { + if ( tud_msc_read10_complete_cb ) tud_msc_read10_complete_cb(rhport, p_cbw->lun); + }else if ( SCSI_CMD_WRITE_10 == p_cbw->command[0] ) + { + if ( tud_msc_write10_complete_cb ) tud_msc_write10_complete_cb(rhport, p_cbw->lun); + }else + { + if ( tud_msc_scsi_complete_cb ) tud_msc_scsi_complete_cb(rhport, p_cbw->lun, p_cbw->command); + } + + // Move to default CMD stage after sending status + p_msc->stage = MSC_STAGE_CMD; + + TU_ASSERT( dcd_edpt_xfer(rhport, p_msc->ep_in , (uint8_t*) &p_msc->csw, sizeof(msc_csw_t)) ); + + //------------- Queue the next CBW -------------// + TU_ASSERT( dcd_edpt_xfer(rhport, p_msc->ep_out, (uint8_t*) &p_msc->cbw, sizeof(msc_cbw_t)) ); + } + + return TUSB_ERROR_NONE; +} + +static void proc_read10_cmd(uint8_t rhport, mscd_interface_t* p_msc) +{ + msc_cbw_t const * p_cbw = &p_msc->cbw; + msc_csw_t * p_csw = &p_msc->csw; + + uint32_t lba = rdwr10_get_lba(p_cbw->command); + + // remaining bytes capped at class buffer + int32_t nbytes = (int32_t) min32_of(sizeof(_mscd_buf), p_cbw->xfer_bytes-p_msc->xferred_len); + + // Application can consume smaller bytes + nbytes = tud_msc_read10_cb (rhport, p_cbw->lun, lba, p_msc->xferred_len, _mscd_buf, (uint32_t) nbytes); + + if ( nbytes < 0 ) + { + // negative means error -> pipe is stalled & status in CSW set to failed + p_csw->data_residue = p_cbw->xfer_bytes - p_msc->xferred_len; + p_csw->status = MSC_CSW_STATUS_FAILED; + + dcd_edpt_stall(rhport, p_msc->ep_in); + } + else if ( nbytes == 0 ) + { + // zero means not ready -> try again later by simulate an transfer complete + dcd_xfer_complete(rhport, p_msc->ep_in, 0, true); + } + else + { + TU_ASSERT( dcd_edpt_xfer(rhport, p_msc->ep_in, _mscd_buf, nbytes), ); + } +} + +static void proc_write10_cmd(uint8_t rhport, mscd_interface_t* p_msc) +{ + msc_cbw_t const * p_cbw = &p_msc->cbw; + + // remaining bytes capped at class buffer + int32_t nbytes = (int32_t) min32_of(sizeof(_mscd_buf), p_cbw->xfer_bytes-p_msc->xferred_len); + + // Write10 callback will be called later when usb transfer complete + TU_ASSERT( dcd_edpt_xfer(rhport, p_msc->ep_out, _mscd_buf, nbytes), ); +} + +#endif diff --git a/src/class/msc/msc_device.h b/src/class/msc/msc_device.h new file mode 100644 index 000000000..104e46414 --- /dev/null +++ b/src/class/msc/msc_device.h @@ -0,0 +1,158 @@ +/**************************************************************************/ +/*! + @file msc_device.h + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#ifndef _TUSB_MSC_DEVICE_H_ +#define _TUSB_MSC_DEVICE_H_ + +#include "common/tusb_common.h" +#include "device/usbd.h" +#include "msc.h" + +#ifdef __cplusplus + extern "C" { +#endif + +/** \addtogroup ClassDriver_MSC + * @{ + * \defgroup MSC_Device Device + * @{ */ + +//--------------------------------------------------------------------+ +// APPLICATION API (Multiple Root Hub Ports) +// Should be used only with MCU that support more than 1 ports +//--------------------------------------------------------------------+ + +//--------------------------------------------------------------------+ +// APPLICATION CALLBACK API (WEAK is optional) +//--------------------------------------------------------------------+ +/** \brief Callback invoked when received \ref SCSI_CMD_READ_10 command + * \param[in] \rhport Root hub port + * \param[in] lun Targeted Logical Unit + * Must be accessible by USB controller (see \ref CFG_TUSB_ATTR_USBRAM) + * \param[in] lba Starting Logical Block Address to be read + * \param[in] offset Byte offset from LBA for reading + * \param[out] buffer Buffer which application need to update with the response data. + * \param[in] bufsize Max bytes can be copied. Application must not return more than this value. + * + * \retval positive Actual bytes returned, must not be more than \a \b bufsize. + * If value less than bufsize is returned, Tinyusb will transfer this amount and afterwards + * invoke this callback again with adjusted offset. + * + * \retval zero Indicate application is not ready yet to response e.g disk I/O is not complete. + * Tinyusb will invoke this callback with the same params again some time later. + * + * \retval negative Indicate error reading disk I/O. Tinyusb will \b STALL the corresponding + * endpoint and return failed status in command status wrapper phase. + * + * \note Host can request dozens of Kbytes in one command e.g \a \b block_count = 128, it is insufficient to require + * application to have that much of buffer. Instead, application can return the number of blocks it can processed, + * the stack after transferred that amount of data will continue to invoke this callback with adjusted \a \b lba and \a \b block_count. + * \n\n Although this callback is called by tinyusb device task (non-isr context), however as all the classes share + * the same task (to save resource), any delay in this callback will cause delay in response on other classes. + */ +int32_t tud_msc_read10_cb (uint8_t rhport, uint8_t lun, uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize); + +/** \brief Callback invoked when received \ref SCSI_CMD_WRITE_10 command + * \param[in] rhport Root hub port + * \param[in] lun Targeted Logical Unit + * Must be accessible by USB controller (see \ref CFG_TUSB_ATTR_USBRAM) + * \param[in] lba Starting Logical Block Address to be write + * \param[out] buffer Buffer which holds written data. + * \param[in] bufsize Max bytes in buffer. Application must not return more than this value. + * + * \retval positive Actual bytes written, must not be more than \a \b bufsize. + * If value less than bufsize is returned, Tinyusb will trim off this amount and + * invoke this callback again with adjusted offset some time later. + * + * \retval zero Indicate application is not ready yet e.g disk I/O is not complete. + * Tinyusb will invoke this callback with the same params again some time later. + * + * \retval negative Indicate error writing disk I/O. Tinyusb will \b STALL the corresponding + * endpoint and return failed status in command status wrapper phase. + * + * \note Host can request dozens of Kbytes in one command e.g \a \b block_count = 128, it is insufficient to require + * application to have that much of buffer. Instead, application can return the number of blocks it can processed, + * the stack after transferred that amount of data will continue to invoke this callback with adjusted \a \b lba and \a \b block_count. + * \n\n Although this callback is called by tinyusb device task (non-isr context), however as all the classes share + * the same task (to save resource), any delay in this callback will cause delay in response on other classes. + */ +int32_t tud_msc_write10_cb (uint8_t rhport, uint8_t lun, uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize); + + +/** \brief Callback invoked when received an SCSI command other than \ref SCSI_CMD_WRITE_10 and \ref SCSI_CMD_READ_10 + * \param[in] rhport Root hub port + * \param[in] lun Targeted Logical Unit + * \param[in] scsi_cmd SCSI command contents, application should examine this command block to know which command host requested + * \param[out] buffer Buffer for SCSI Data Stage. + * - For INPUT: application must fill this with response. + * - For OUTPUT it holds the Data from host + * \param[in] bufsize Buffer's length. + * + * \retval negative Indicate error e.g accessing disk I/O. Tinyusb will \b STALL the corresponding + * endpoint and return failed status in command status wrapper phase. + * \retval otherwise Actual bytes processed, must not be more than \a \b bufsize. Can be zero for no-data command. + */ +int32_t tud_msc_scsi_cb (uint8_t rhport, uint8_t lun, uint8_t const scsi_cmd[16], void* buffer, uint16_t bufsize); + +/*------------- Optional callbacks : Could be used by application to free up resources -------------*/ +ATTR_WEAK void tud_msc_read10_complete_cb(uint8_t rhport, uint8_t lun); +ATTR_WEAK void tud_msc_write10_complete_cb(uint8_t rhport, uint8_t lun); +ATTR_WEAK void tud_msc_scsi_complete_cb(uint8_t rhport, uint8_t lun, uint8_t const scsi_cmd[16]); + +/** @} */ +/** @} */ + +//--------------------------------------------------------------------+ +// USBD-CLASS DRIVER API +//--------------------------------------------------------------------+ +#ifdef _TINY_USB_SOURCE_FILE_ + +void mscd_init(void); +tusb_error_t mscd_open(uint8_t rhport, tusb_desc_interface_t const * p_interface_desc, uint16_t *p_length); +tusb_error_t mscd_control_request_st(uint8_t rhport, tusb_control_request_t const * p_request); +tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t edpt_addr, tusb_event_t event, uint32_t xferred_bytes); +void mscd_close(uint8_t rhport); + +#endif + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_MSC_DEVICE_H_ */ + diff --git a/src/class/msc/msc_host.c b/src/class/msc/msc_host.c new file mode 100644 index 000000000..afe7032a6 --- /dev/null +++ b/src/class/msc/msc_host.c @@ -0,0 +1,430 @@ +/**************************************************************************/ +/*! + @file msc_host.c + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#include "tusb_option.h" + +#if MODE_HOST_SUPPORTED & CFG_TUSB_HOST_MSC + +#define _TINY_USB_SOURCE_FILE_ + +//--------------------------------------------------------------------+ +// INCLUDE +//--------------------------------------------------------------------+ +#include "common/tusb_common.h" +#include "msc_host.h" + +//--------------------------------------------------------------------+ +// MACRO CONSTANT TYPEDEF +//--------------------------------------------------------------------+ +CFG_TUSB_ATTR_USBRAM STATIC_VAR msch_interface_t msch_data[CFG_TUSB_HOST_DEVICE_MAX]; + +//------------- Initalization Data -------------// +static osal_semaphore_t msch_sem_hdl; + +// buffer used to read scsi information when mounted, largest response data currently is inquiry +CFG_TUSB_ATTR_USBRAM ATTR_ALIGNED(4) STATIC_VAR uint8_t msch_buffer[sizeof(scsi_inquiry_data_t)]; + +//--------------------------------------------------------------------+ +// INTERNAL OBJECT & FUNCTION DECLARATION +//--------------------------------------------------------------------+ + +//--------------------------------------------------------------------+ +// PUBLIC API +//--------------------------------------------------------------------+ +bool tuh_msc_is_mounted(uint8_t dev_addr) +{ + return tuh_device_is_configured(dev_addr) && // is configured can be omitted + msch_data[dev_addr-1].is_initialized; +} + +bool tuh_msc_is_busy(uint8_t dev_addr) +{ + return msch_data[dev_addr-1].is_initialized && + hcd_pipe_is_busy(msch_data[dev_addr-1].bulk_in); +} + +uint8_t const* tuh_msc_get_vendor_name(uint8_t dev_addr) +{ + return msch_data[dev_addr-1].is_initialized ? msch_data[dev_addr-1].vendor_id : NULL; +} + +uint8_t const* tuh_msc_get_product_name(uint8_t dev_addr) +{ + return msch_data[dev_addr-1].is_initialized ? msch_data[dev_addr-1].product_id : NULL; +} + +tusb_error_t tuh_msc_get_capacity(uint8_t dev_addr, uint32_t* p_last_lba, uint32_t* p_block_size) +{ + if ( !msch_data[dev_addr-1].is_initialized ) return TUSB_ERROR_MSCH_DEVICE_NOT_MOUNTED; + TU_ASSERT(p_last_lba != NULL && p_block_size != NULL, TUSB_ERROR_INVALID_PARA); + + (*p_last_lba) = msch_data[dev_addr-1].last_lba; + (*p_block_size) = (uint32_t) msch_data[dev_addr-1].block_size; + + return TUSB_ERROR_NONE; +} + +//--------------------------------------------------------------------+ +// PUBLIC API: SCSI COMMAND +//--------------------------------------------------------------------+ +static inline void msc_cbw_add_signature(msc_cbw_t *p_cbw, uint8_t lun) +{ + p_cbw->signature = MSC_CBW_SIGNATURE; + p_cbw->tag = 0xCAFECAFE; + p_cbw->lun = lun; +} + +static tusb_error_t msch_command_xfer(msch_interface_t * p_msch, void* p_buffer) ATTR_WARN_UNUSED_RESULT; +static tusb_error_t msch_command_xfer(msch_interface_t * p_msch, void* p_buffer) +{ + if ( NULL != p_buffer) + { // there is data phase + if (p_msch->cbw.dir & TUSB_DIR_IN_MASK) + { + TU_ASSERT_ERR( hcd_pipe_xfer(p_msch->bulk_out, (uint8_t*) &p_msch->cbw, sizeof(msc_cbw_t), false) ); + TU_ASSERT_ERR( hcd_pipe_queue_xfer(p_msch->bulk_in , p_buffer, p_msch->cbw.xfer_bytes) ); + }else + { + TU_ASSERT_ERR( hcd_pipe_queue_xfer(p_msch->bulk_out, (uint8_t*) &p_msch->cbw, sizeof(msc_cbw_t)) ); + TU_ASSERT_ERR( hcd_pipe_xfer(p_msch->bulk_out , p_buffer, p_msch->cbw.xfer_bytes, false) ); + } + } + + TU_ASSERT_ERR( hcd_pipe_xfer(p_msch->bulk_in , (uint8_t*) &p_msch->csw, sizeof(msc_csw_t), true) ); + + return TUSB_ERROR_NONE; +} + +tusb_error_t tusbh_msc_inquiry(uint8_t dev_addr, uint8_t lun, uint8_t *p_data) +{ + msch_interface_t* p_msch = &msch_data[dev_addr-1]; + + //------------- Command Block Wrapper -------------// + msc_cbw_add_signature(&p_msch->cbw, lun); + p_msch->cbw.xfer_bytes = sizeof(scsi_inquiry_data_t); + p_msch->cbw.dir = TUSB_DIR_IN_MASK; + p_msch->cbw.cmd_len = sizeof(scsi_inquiry_t); + + //------------- SCSI command -------------// + scsi_inquiry_t cmd_inquiry = + { + .cmd_code = SCSI_CMD_INQUIRY, + .alloc_length = sizeof(scsi_inquiry_data_t) + }; + + memcpy(p_msch->cbw.command, &cmd_inquiry, p_msch->cbw.cmd_len); + + TU_ASSERT_ERR ( msch_command_xfer(p_msch, p_data) ); + + return TUSB_ERROR_NONE; +} + +tusb_error_t tusbh_msc_read_capacity10(uint8_t dev_addr, uint8_t lun, uint8_t *p_data) +{ + msch_interface_t* p_msch = &msch_data[dev_addr-1]; + + //------------- Command Block Wrapper -------------// + msc_cbw_add_signature(&p_msch->cbw, lun); + p_msch->cbw.xfer_bytes = sizeof(scsi_read_capacity10_data_t); + p_msch->cbw.dir = TUSB_DIR_IN_MASK; + p_msch->cbw.cmd_len = sizeof(scsi_read_capacity10_t); + + //------------- SCSI command -------------// + scsi_read_capacity10_t cmd_read_capacity10 = + { + .cmd_code = SCSI_CMD_READ_CAPACITY_10, + .lba = 0, + .partial_medium_indicator = 0 + }; + + memcpy(p_msch->cbw.command, &cmd_read_capacity10, p_msch->cbw.cmd_len); + + TU_ASSERT_ERR ( msch_command_xfer(p_msch, p_data) ); + + return TUSB_ERROR_NONE; +} + +tusb_error_t tuh_msc_request_sense(uint8_t dev_addr, uint8_t lun, uint8_t *p_data) +{ + (void) lun; // TODO [MSCH] multiple lun support + + msch_interface_t* p_msch = &msch_data[dev_addr-1]; + + //------------- Command Block Wrapper -------------// + p_msch->cbw.xfer_bytes = 18; + p_msch->cbw.dir = TUSB_DIR_IN_MASK; + p_msch->cbw.cmd_len = sizeof(scsi_request_sense_t); + + //------------- SCSI command -------------// + scsi_request_sense_t cmd_request_sense = + { + .cmd_code = SCSI_CMD_REQUEST_SENSE, + .alloc_length = 18 + }; + + memcpy(p_msch->cbw.command, &cmd_request_sense, p_msch->cbw.cmd_len); + + TU_ASSERT_ERR ( msch_command_xfer(p_msch, p_data) ); + + return TUSB_ERROR_NONE; +} + +tusb_error_t tuh_msc_test_unit_ready(uint8_t dev_addr, uint8_t lun, msc_csw_t * p_csw) +{ + msch_interface_t* p_msch = &msch_data[dev_addr-1]; + + //------------- Command Block Wrapper -------------// + msc_cbw_add_signature(&p_msch->cbw, lun); + + p_msch->cbw.xfer_bytes = 0; // Number of bytes + p_msch->cbw.dir = TUSB_DIR_OUT; + p_msch->cbw.cmd_len = sizeof(scsi_test_unit_ready_t); + + //------------- SCSI command -------------// + scsi_test_unit_ready_t cmd_test_unit_ready = + { + .cmd_code = SCSI_CMD_TEST_UNIT_READY, + .lun = lun // according to wiki + }; + + memcpy(p_msch->cbw.command, &cmd_test_unit_ready, p_msch->cbw.cmd_len); + + // TODO MSCH refractor test uinit ready + TU_ASSERT_ERR( hcd_pipe_xfer(p_msch->bulk_out, (uint8_t*) &p_msch->cbw, sizeof(msc_cbw_t), false) ); + TU_ASSERT_ERR( hcd_pipe_xfer(p_msch->bulk_in , (uint8_t*) p_csw, sizeof(msc_csw_t), true) ); + + return TUSB_ERROR_NONE; +} + +tusb_error_t tuh_msc_read10(uint8_t dev_addr, uint8_t lun, void * p_buffer, uint32_t lba, uint16_t block_count) +{ + msch_interface_t* p_msch = &msch_data[dev_addr-1]; + + //------------- Command Block Wrapper -------------// + msc_cbw_add_signature(&p_msch->cbw, lun); + + p_msch->cbw.xfer_bytes = p_msch->block_size*block_count; // Number of bytes + p_msch->cbw.dir = TUSB_DIR_IN_MASK; + p_msch->cbw.cmd_len = sizeof(scsi_read10_t); + + //------------- SCSI command -------------// + scsi_read10_t cmd_read10 = + { + .cmd_code = SCSI_CMD_READ_10, + .lba = __n2be(lba), + .block_count = u16_le2be(block_count) + }; + + memcpy(p_msch->cbw.command, &cmd_read10, p_msch->cbw.cmd_len); + + TU_ASSERT_ERR ( msch_command_xfer(p_msch, p_buffer)); + + return TUSB_ERROR_NONE; +} + +tusb_error_t tuh_msc_write10(uint8_t dev_addr, uint8_t lun, void const * p_buffer, uint32_t lba, uint16_t block_count) +{ + msch_interface_t* p_msch = &msch_data[dev_addr-1]; + + //------------- Command Block Wrapper -------------// + msc_cbw_add_signature(&p_msch->cbw, lun); + + p_msch->cbw.xfer_bytes = p_msch->block_size*block_count; // Number of bytes + p_msch->cbw.dir = TUSB_DIR_OUT; + p_msch->cbw.cmd_len = sizeof(scsi_write10_t); + + //------------- SCSI command -------------// + scsi_write10_t cmd_write10 = + { + .cmd_code = SCSI_CMD_WRITE_10, + .lba = __n2be(lba), + .block_count = u16_le2be(block_count) + }; + + memcpy(p_msch->cbw.command, &cmd_write10, p_msch->cbw.cmd_len); + + TU_ASSERT_ERR ( msch_command_xfer(p_msch, (void*) p_buffer)); + + return TUSB_ERROR_NONE; +} + +//--------------------------------------------------------------------+ +// CLASS-USBH API (don't require to verify parameters) +//--------------------------------------------------------------------+ +void msch_init(void) +{ + memclr_(msch_data, sizeof(msch_interface_t)*CFG_TUSB_HOST_DEVICE_MAX); + msch_sem_hdl = osal_semaphore_create(1, 0); +} + +tusb_error_t msch_open_subtask(uint8_t dev_addr, tusb_desc_interface_t const *p_interface_desc, uint16_t *p_length) +{ + tusb_error_t error; + + OSAL_SUBTASK_BEGIN + + if (! ( MSC_SUBCLASS_SCSI == p_interface_desc->bInterfaceSubClass && + MSC_PROTOCOL_BOT == p_interface_desc->bInterfaceProtocol ) ) + { + return TUSB_ERROR_MSC_UNSUPPORTED_PROTOCOL; + } + + //------------- Open Data Pipe -------------// + tusb_desc_endpoint_t const *p_endpoint; + p_endpoint = (tusb_desc_endpoint_t const *) descriptor_next( (uint8_t const*) p_interface_desc ); + + for(uint32_t i=0; i<2; i++) + { + STASK_ASSERT(TUSB_DESC_ENDPOINT == p_endpoint->bDescriptorType); + STASK_ASSERT(TUSB_XFER_BULK == p_endpoint->bmAttributes.xfer); + + pipe_handle_t * p_pipe_hdl = ( p_endpoint->bEndpointAddress & TUSB_DIR_IN_MASK ) ? + &msch_data[dev_addr-1].bulk_in : &msch_data[dev_addr-1].bulk_out; + + (*p_pipe_hdl) = hcd_pipe_open(dev_addr, p_endpoint, TUSB_CLASS_MSC); + STASK_ASSERT( pipehandle_is_valid(*p_pipe_hdl) ); + + p_endpoint = (tusb_desc_endpoint_t const *) descriptor_next( (uint8_t const*) p_endpoint ); + } + + msch_data[dev_addr-1].interface_number = p_interface_desc->bInterfaceNumber; + (*p_length) += sizeof(tusb_desc_interface_t) + 2*sizeof(tusb_desc_endpoint_t); + + + //------------- Get Max Lun -------------// + STASK_INVOKE( + usbh_control_xfer_subtask( dev_addr, bm_request_type(TUSB_DIR_IN, TUSB_REQ_TYPE_CLASS, TUSB_REQ_RCPT_INTERFACE), + MSC_REQUEST_GET_MAX_LUN, 0, msch_data[dev_addr-1].interface_number, + 1, msch_buffer ), + error + ); + + STASK_ASSERT( TUSB_ERROR_NONE == error /* && TODO STALL means zero */); + msch_data[dev_addr-1].max_lun = msch_buffer[0]; + +#if 0 + //------------- Reset -------------// + STASK_INVOKE( + usbh_control_xfer_subtask( dev_addr, bm_request_type(TUSB_DIR_OUT, TUSB_REQ_TYPE_CLASS, TUSB_REQ_RCPT_INTERFACE), + MSC_REQUEST_RESET, 0, msch_data[dev_addr-1].interface_number, + 0, NULL ), + error + ); +#endif + + enum { SCSI_XFER_TIMEOUT = 2000 }; + //------------- SCSI Inquiry -------------// + tusbh_msc_inquiry(dev_addr, 0, msch_buffer); + osal_semaphore_wait(msch_sem_hdl, SCSI_XFER_TIMEOUT, &error); + STASK_ASSERT_ERR(error); + + memcpy(msch_data[dev_addr-1].vendor_id , ((scsi_inquiry_data_t*) msch_buffer)->vendor_id , 8); + memcpy(msch_data[dev_addr-1].product_id, ((scsi_inquiry_data_t*) msch_buffer)->product_id, 16); + + //------------- SCSI Read Capacity 10 -------------// + tusbh_msc_read_capacity10(dev_addr, 0, msch_buffer); + osal_semaphore_wait(msch_sem_hdl, SCSI_XFER_TIMEOUT, &error); + STASK_ASSERT_ERR(error); + + // NOTE: my toshiba thumb-drive stall the first Read Capacity and require the sequence + // Read Capacity --> Stalled --> Clear Stall --> Request Sense --> Read Capacity (2) to work + if ( hcd_pipe_is_stalled(msch_data[dev_addr-1].bulk_in) ) + { // clear stall TODO abstract clear stall function + STASK_INVOKE( + usbh_control_xfer_subtask( dev_addr, bm_request_type(TUSB_DIR_OUT, TUSB_REQ_TYPE_STANDARD, TUSB_REQ_RCPT_ENDPOINT), + TUSB_REQ_CLEAR_FEATURE, 0, hcd_pipe_get_endpoint_addr(msch_data[dev_addr-1].bulk_in), + 0, NULL ), + error + ); + STASK_ASSERT_ERR(error); + + hcd_pipe_clear_stall(msch_data[dev_addr-1].bulk_in); + osal_semaphore_wait(msch_sem_hdl, SCSI_XFER_TIMEOUT, &error); // wait for SCSI status + STASK_ASSERT_ERR(error); + + //------------- SCSI Request Sense -------------// + (void) tuh_msc_request_sense(dev_addr, 0, msch_buffer); + osal_semaphore_wait(msch_sem_hdl, SCSI_XFER_TIMEOUT, &error); + STASK_ASSERT_ERR(error); + + //------------- Re-read SCSI Read Capactity -------------// + tusbh_msc_read_capacity10(dev_addr, 0, msch_buffer); + osal_semaphore_wait(msch_sem_hdl, SCSI_XFER_TIMEOUT, &error); + STASK_ASSERT_ERR(error); + } + + msch_data[dev_addr-1].last_lba = __be2n( ((scsi_read_capacity10_data_t*)msch_buffer)->last_lba ); + msch_data[dev_addr-1].block_size = (uint16_t) __be2n( ((scsi_read_capacity10_data_t*)msch_buffer)->block_size ); + + msch_data[dev_addr-1].is_initialized = true; + tuh_msc_mounted_cb(dev_addr); + + OSAL_SUBTASK_END +} + +void msch_isr(pipe_handle_t pipe_hdl, tusb_event_t event, uint32_t xferred_bytes) +{ + if ( pipehandle_is_equal(pipe_hdl, msch_data[pipe_hdl.dev_addr-1].bulk_in) ) + { + if (msch_data[pipe_hdl.dev_addr-1].is_initialized) + { + tuh_msc_isr(pipe_hdl.dev_addr, event, xferred_bytes); + }else + { // still initializing under open subtask + osal_semaphore_post(msch_sem_hdl); + } + } +} + +void msch_close(uint8_t dev_addr) +{ + (void) hcd_pipe_close(msch_data[dev_addr-1].bulk_in); + (void) hcd_pipe_close(msch_data[dev_addr-1].bulk_out); + + memclr_(&msch_data[dev_addr-1], sizeof(msch_interface_t)); + osal_semaphore_reset(msch_sem_hdl); + + tuh_msc_unmounted_cb(dev_addr); // invoke Application Callback +} + +//--------------------------------------------------------------------+ +// INTERNAL & HELPER +//--------------------------------------------------------------------+ + + +#endif diff --git a/src/class/msc/msc_host.h b/src/class/msc/msc_host.h new file mode 100644 index 000000000..dce275fc8 --- /dev/null +++ b/src/class/msc/msc_host.h @@ -0,0 +1,219 @@ +/**************************************************************************/ +/*! + @file msc_host.h + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#ifndef _TUSB_MSC_HOST_H_ +#define _TUSB_MSC_HOST_H_ + +#include "common/tusb_common.h" +#include "host/usbh.h" +#include "msc.h" + +#ifdef __cplusplus + extern "C" { +#endif + +/** \addtogroup ClassDriver_MSC + * @{ + * \defgroup MSC_Host Host + * The interface API includes status checking function, data transferring function and callback functions + * @{ */ +//--------------------------------------------------------------------+ +// MASS STORAGE Application API +//--------------------------------------------------------------------+ +/** \brief Check if device supports MassStorage interface or not + * \param[in] dev_addr device address + * \retval true if device supports + * \retval false if device does not support or is not mounted + */ +bool tuh_msc_is_mounted(uint8_t dev_addr) ATTR_PURE ATTR_WARN_UNUSED_RESULT; + +/** \brief Check if the interface is currently busy or not + * \param[in] dev_addr device address + * \retval true if the interface is busy meaning the stack is still transferring/waiting data from/to device + * \retval false if the interface is not busy meaning the stack successfully transferred data from/to device + * \note This function is used to check if previous transfer is complete (success or error), so that the next transfer + * can be scheduled. User needs to make sure the corresponding interface is mounted (by \ref tuh_msc_is_mounted) + * before calling this function + */ +bool tuh_msc_is_busy(uint8_t dev_addr) ATTR_PURE ATTR_WARN_UNUSED_RESULT; + +/** \brief Get SCSI vendor's name of MassStorage device + * \param[in] dev_addr device address + * \return pointer to vendor's name or NULL if specified device does not support MassStorage + * \note SCSI vendor's name is 8-byte length field in \ref scsi_inquiry_data_t. During enumeration, the stack has already + * retrieved (via SCSI INQUIRY) and store this information internally. There is no need for application to re-send SCSI INQUIRY + * command or allocate buffer for this. + */ +uint8_t const* tuh_msc_get_vendor_name(uint8_t dev_addr); + +/** \brief Get SCSI product's name of MassStorage device + * \param[in] dev_addr device address + * \return pointer to product's name or NULL if specified device does not support MassStorage + * \note SCSI product's name is 16-byte length field in \ref scsi_inquiry_data_t. During enumeration, the stack has already + * retrieved (via SCSI INQUIRY) and store this information internally. There is no need for application to re-send SCSI INQUIRY + * command or allocate buffer for this. + */ +uint8_t const* tuh_msc_get_product_name(uint8_t dev_addr); + +/** \brief Get SCSI Capacity of MassStorage device + * \param[in] dev_addr device address + * \param[out] p_last_lba Last Logical Block Address of device + * \param[out] p_block_size Block Size of device in bytes + * \retval pointer to product's name or NULL if specified device does not support MassStorage + * \note MassStorage's capacity can be computed by last LBA x block size (in bytes). During enumeration, the stack has already + * retrieved (via SCSI READ CAPACITY 10) and store this information internally. There is no need for application + * to re-send SCSI READ CAPACITY 10 command + */ +tusb_error_t tuh_msc_get_capacity(uint8_t dev_addr, uint32_t* p_last_lba, uint32_t* p_block_size); + +/** \brief Perform SCSI READ 10 command to read data from MassStorage device + * \param[in] dev_addr device address + * \param[in] lun Targeted Logical Unit + * \param[out] p_buffer Buffer used to store data read from device. Must be accessible by USB controller (see \ref CFG_TUSB_ATTR_USBRAM) + * \param[in] lba Starting Logical Block Address to be read + * \param[in] block_count Number of Block to be read + * \retval TUSB_ERROR_NONE on success + * \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device + * \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request) + * \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct + * \note This function is non-blocking and returns immediately. The result of USB transfer will be reported by the interface's callback function + */ +tusb_error_t tuh_msc_read10 (uint8_t dev_addr, uint8_t lun, void * p_buffer, uint32_t lba, uint16_t block_count) ATTR_WARN_UNUSED_RESULT; + +/** \brief Perform SCSI WRITE 10 command to write data to MassStorage device + * \param[in] dev_addr device address + * \param[in] lun Targeted Logical Unit + * \param[in] p_buffer Buffer containing data. Must be accessible by USB controller (see \ref CFG_TUSB_ATTR_USBRAM) + * \param[in] lba Starting Logical Block Address to be written + * \param[in] block_count Number of Block to be written + * \retval TUSB_ERROR_NONE on success + * \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device + * \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request) + * \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct + * \note This function is non-blocking and returns immediately. The result of USB transfer will be reported by the interface's callback function + */ +tusb_error_t tuh_msc_write10(uint8_t dev_addr, uint8_t lun, void const * p_buffer, uint32_t lba, uint16_t block_count) ATTR_WARN_UNUSED_RESULT; + +/** \brief Perform SCSI REQUEST SENSE command, used to retrieve sense data from MassStorage device + * \param[in] dev_addr device address + * \param[in] lun Targeted Logical Unit + * \param[in] p_data Buffer to store response's data from device. Must be accessible by USB controller (see \ref CFG_TUSB_ATTR_USBRAM) + * \retval TUSB_ERROR_NONE on success + * \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device + * \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request) + * \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct + * \note This function is non-blocking and returns immediately. The result of USB transfer will be reported by the interface's callback function + */ +tusb_error_t tuh_msc_request_sense(uint8_t dev_addr, uint8_t lun, uint8_t *p_data); + +/** \brief Perform SCSI TEST UNIT READY command to test if MassStorage device is ready + * \param[in] dev_addr device address + * \param[in] lun Targeted Logical Unit + * \retval TUSB_ERROR_NONE on success + * \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device + * \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request) + * \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct + * \note This function is non-blocking and returns immediately. The result of USB transfer will be reported by the interface's callback function + */ +tusb_error_t tuh_msc_test_unit_ready(uint8_t dev_addr, uint8_t lun, msc_csw_t * p_csw) ATTR_WARN_UNUSED_RESULT; // TODO to be refractor + +//tusb_error_t tusbh_msc_scsi_send(uint8_t dev_addr, uint8_t lun, bool is_direction_in, +// uint8_t const * p_command, uint8_t cmd_len, +// uint8_t * p_response, uint32_t resp_len) ATTR_WARN_UNUSED_RESULT; + +//------------- Application Callback -------------// +/** \brief Callback function that will be invoked when a device with MassStorage interface is mounted + * \param[in] dev_addr Address of newly mounted device + * \note This callback should be used by Application to set-up interface-related data + */ +void tuh_msc_mounted_cb(uint8_t dev_addr); + +/** \brief Callback function that will be invoked when a device with MassStorage interface is unmounted + * \param[in] dev_addr Address of newly unmounted device + * \note This callback should be used by Application to tear-down interface-related data + */ +void tuh_msc_unmounted_cb(uint8_t dev_addr); + +/** \brief Callback function that is invoked when an transferring event occurred + * \param[in] dev_addr Address of device + * \param[in] event an value from \ref tusb_event_t + * \param[in] xferred_bytes Number of bytes transferred via USB bus + * \note event can be one of following + * - TUSB_EVENT_XFER_COMPLETE : previously scheduled transfer completes successfully. + * - TUSB_EVENT_XFER_ERROR : previously scheduled transfer encountered a transaction error. + * - TUSB_EVENT_XFER_STALLED : previously scheduled transfer is stalled by device. + * \note + */ +void tuh_msc_isr(uint8_t dev_addr, tusb_event_t event, uint32_t xferred_bytes); + + +//--------------------------------------------------------------------+ +// USBH-CLASS DRIVER API +//--------------------------------------------------------------------+ +#ifdef _TINY_USB_SOURCE_FILE_ + +typedef struct { + pipe_handle_t bulk_in, bulk_out; + uint8_t interface_number; + + uint8_t max_lun; + uint16_t block_size; + uint32_t last_lba; // last logical block address + + volatile bool is_initialized; + uint8_t vendor_id[8]; + uint8_t product_id[16]; + + msc_cbw_t cbw; + msc_csw_t csw; +}msch_interface_t; + +void msch_init(void); +tusb_error_t msch_open_subtask(uint8_t dev_addr, tusb_desc_interface_t const *p_interface_desc, uint16_t *p_length) ATTR_WARN_UNUSED_RESULT; +void msch_isr(pipe_handle_t pipe_hdl, tusb_event_t event, uint32_t xferred_bytes); +void msch_close(uint8_t dev_addr); +#endif + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_MSC_HOST_H_ */ + +/// @} +/// @} -- cgit v1.3.1 From 3ace03cbc7dc98943f6b43cff3e6397302eae23a Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 19 Jun 2018 15:16:26 +0700 Subject: re-increase cdc buffer for nrf52840 due to bulk out issue --- src/class/cdc/cdc_device.c | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'src/class') diff --git a/src/class/cdc/cdc_device.c b/src/class/cdc/cdc_device.c index 90e1924b4..ccb15205b 100644 --- a/src/class/cdc/cdc_device.c +++ b/src/class/cdc/cdc_device.c @@ -66,7 +66,14 @@ typedef struct { }cdcd_interface_t; // TODO multiple rhport + +#if CFG_TUSB_MCU == OPT_MCU_NRF5X +// FIXME nrf52 OUT: Controller ACK data even we didn't prepare transfer +CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN uint8_t _tmp_rx_buf[600]; +#else CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN uint8_t _tmp_rx_buf[64]; +#endif + CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN uint8_t _tmp_tx_buf[64]; FIFO_DEF(_rx_ff, CFG_TUD_CDC_BUFSIZE, uint8_t, true); -- cgit v1.3.1 From a6a06bca69983ab74b81ae08c1aa70940c489eb8 Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 19 Jun 2018 22:59:54 +0700 Subject: update msc device adjust lba for read10, write10 callback --- src/class/msc/msc_device.c | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) (limited to 'src/class') diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index c772e62a6..1894720d6 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -255,10 +255,13 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u } else { - uint32_t lba = rdwr10_get_lba(p_cbw->command); + uint16_t const block_sz = p_cbw->xfer_bytes / rdwr10_get_blockcount(p_cbw->command); + + // Adjust lba with transferred bytes + uint32_t const lba = rdwr10_get_lba(p_cbw->command) + (p_msc->xferred_len / block_sz); // Application can consume smaller bytes - int32_t nbytes = tud_msc_write10_cb(rhport, p_cbw->lun, lba, p_msc->xferred_len, _mscd_buf, xferred_bytes); + int32_t nbytes = tud_msc_write10_cb(rhport, p_cbw->lun, lba, p_msc->xferred_len % block_sz, _mscd_buf, xferred_bytes); if ( nbytes < 0 ) { @@ -355,13 +358,16 @@ static void proc_read10_cmd(uint8_t rhport, mscd_interface_t* p_msc) msc_cbw_t const * p_cbw = &p_msc->cbw; msc_csw_t * p_csw = &p_msc->csw; - uint32_t lba = rdwr10_get_lba(p_cbw->command); + uint16_t const block_sz = p_cbw->xfer_bytes / rdwr10_get_blockcount(p_cbw->command); + + // Adjust lba with transferred bytes + uint32_t const lba = rdwr10_get_lba(p_cbw->command) + (p_msc->xferred_len / block_sz); // remaining bytes capped at class buffer int32_t nbytes = (int32_t) min32_of(sizeof(_mscd_buf), p_cbw->xfer_bytes-p_msc->xferred_len); // Application can consume smaller bytes - nbytes = tud_msc_read10_cb (rhport, p_cbw->lun, lba, p_msc->xferred_len, _mscd_buf, (uint32_t) nbytes); + nbytes = tud_msc_read10_cb (rhport, p_cbw->lun, lba, p_msc->xferred_len % block_sz, _mscd_buf, (uint32_t) nbytes); if ( nbytes < 0 ) { -- cgit v1.3.1 From 5f1bec943b2a227d6b6f2188644c7641828787e7 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 21 Jun 2018 12:20:21 +0700 Subject: fix msc block count get --- src/class/msc/msc_device.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/class') diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index 1894720d6..c10fd8a69 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -106,7 +106,7 @@ static inline uint16_t rdwr10_get_blockcount(uint8_t const command[]) uint16_t block_count; memcpy(&block_count, &p_rdwr10->block_count, 2); - return __be2n(block_count); + return __be2n_16(block_count); } -- cgit v1.3.1 From b9f8575e2d0632b2b4a2358cf181c276c49eca2f Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 23 Jun 2018 13:19:36 +0700 Subject: clean up device cdc separate cdc tx & rx bufsize --- examples/device/nrf52840/src/tusb_config.h | 4 +++- examples/obsolete/device/src/tusb_config.h | 4 +++- src/class/cdc/cdc_device.c | 11 +++-------- src/common/tusb_fifo.c | 5 ++++- src/device/usbd.c | 14 +++++++++----- 5 files changed, 22 insertions(+), 16 deletions(-) (limited to 'src/class') diff --git a/examples/device/nrf52840/src/tusb_config.h b/examples/device/nrf52840/src/tusb_config.h index 476ff4bed..aee6099b5 100644 --- a/examples/device/nrf52840/src/tusb_config.h +++ b/examples/device/nrf52840/src/tusb_config.h @@ -72,7 +72,9 @@ *------------------------------------------------------------------*/ // FIFO size of CDC TX and RX -#define CFG_TUD_CDC_BUFSIZE 64 +#define CFG_TUD_CDC_RX_BUFSIZE 64 +#define CFG_TUD_CDC_TX_BUFSIZE 64 + // TX is sent automatically every Start of Frame event. // If not enabled, application must call tud_cdc_flush() periodically diff --git a/examples/obsolete/device/src/tusb_config.h b/examples/obsolete/device/src/tusb_config.h index bdadb2110..3904facbe 100644 --- a/examples/obsolete/device/src/tusb_config.h +++ b/examples/obsolete/device/src/tusb_config.h @@ -77,7 +77,9 @@ *------------------------------------------------------------------*/ // FIFO size of CDC TX and RX -#define CFG_TUD_CDC_BUFSIZE 128 +#define CFG_TUD_CDC_RX_BUFSIZE 128 +#define CFG_TUD_CDC_TX_BUFSIZE 128 + // TX is sent automatically in Start of Frame event. // If not enabled, application must call tud_cdc_flush() periodically diff --git a/src/class/cdc/cdc_device.c b/src/class/cdc/cdc_device.c index ccb15205b..583180fcc 100644 --- a/src/class/cdc/cdc_device.c +++ b/src/class/cdc/cdc_device.c @@ -67,17 +67,12 @@ typedef struct { // TODO multiple rhport -#if CFG_TUSB_MCU == OPT_MCU_NRF5X -// FIXME nrf52 OUT: Controller ACK data even we didn't prepare transfer -CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN uint8_t _tmp_rx_buf[600]; -#else -CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN uint8_t _tmp_rx_buf[64]; -#endif +CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN uint8_t _tmp_rx_buf[64]; CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN uint8_t _tmp_tx_buf[64]; -FIFO_DEF(_rx_ff, CFG_TUD_CDC_BUFSIZE, uint8_t, true); -FIFO_DEF(_tx_ff, CFG_TUD_CDC_BUFSIZE, uint8_t, false); +FIFO_DEF(_rx_ff, CFG_TUD_CDC_RX_BUFSIZE, uint8_t, true); +FIFO_DEF(_tx_ff, CFG_TUD_CDC_TX_BUFSIZE, uint8_t, false); //--------------------------------------------------------------------+ // INTERNAL OBJECT & FUNCTION DECLARATION diff --git a/src/common/tusb_fifo.c b/src/common/tusb_fifo.c index b4bb70b87..d6f34f33f 100644 --- a/src/common/tusb_fifo.c +++ b/src/common/tusb_fifo.c @@ -37,6 +37,7 @@ /**************************************************************************/ #include "tusb_fifo.h" +#include "common/tusb_verify.h" // for ASSERT /*------------------------------------------------------------------*/ /* @@ -207,7 +208,9 @@ bool fifo_peek_at(fifo_t* f, uint16_t position, void * p_buffer) bool fifo_write(fifo_t* f, void const * p_data) { if ( !fifo_initalized(f) ) return false; - if ( fifo_full(f) && !f->overwritable ) return false; + +// if ( fifo_full(f) && !f->overwritable ) return false; + TU_ASSERT( !(fifo_full(f) && !f->overwritable) ); mutex_lock_if_needed(f); diff --git a/src/device/usbd.c b/src/device/usbd.c index 0f6cebc6c..a58196583 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -46,10 +46,12 @@ #include "usbd.h" #include "device/usbd_pvt.h" -#define USBD_TASK_QUEUE_DEPTH 16 +#ifndef CFG_TUD_TASK_QUEUE_SZ +#define CFG_TUD_TASK_QUEUE_SZ 16 +#endif -#ifndef CFG_TUD_TASK_STACKSIZE -#define CFG_TUD_TASK_STACKSIZE 150 +#ifndef CFG_TUD_TASK_STACK_SZ +#define CFG_TUD_TASK_STACK_SZ 150 #endif #ifndef CFG_TUD_TASK_PRIO @@ -190,10 +192,10 @@ typedef struct ATTR_ALIGNED(4) VERIFY_STATIC(sizeof(usbd_task_event_t) <= 12, "size is not correct"); -OSAL_TASK_DEF(_usbd_task_def, "usbd", usbd_task, CFG_TUD_TASK_PRIO, CFG_TUD_TASK_STACKSIZE); +OSAL_TASK_DEF(_usbd_task_def, "usbd", usbd_task, CFG_TUD_TASK_PRIO, CFG_TUD_TASK_STACK_SZ); /*------------- event queue -------------*/ -OSAL_QUEUE_DEF(_usbd_qdef, USBD_TASK_QUEUE_DEPTH, usbd_task_event_t); +OSAL_QUEUE_DEF(_usbd_qdef, CFG_TUD_TASK_QUEUE_SZ, usbd_task_event_t); static osal_queue_t _usbd_q; /*------------- control transfer semaphore -------------*/ @@ -547,12 +549,14 @@ void dcd_bus_event(uint8_t rhport, usbd_bus_event_type_t bus_event) case USBD_BUS_EVENT_SOF: { + #if CFG_TUD_CDC_FLUSH_ON_SOF usbd_task_event_t task_event = { .rhport = rhport, .event_id = USBD_EVT_SOF, }; osal_queue_send_isr(_usbd_q, &task_event); + #endif } break; -- cgit v1.3.1 From 6b2b6aaa3f5b63a00ac852a3a2b2cebb2bd23741 Mon Sep 17 00:00:00 2001 From: hathach Date: Sun, 24 Jun 2018 00:16:22 +0700 Subject: fix msc device with transfer len > 65k bytes --- src/class/msc/msc_device.c | 18 +++++++++++------- src/portable/nordic/nrf5x/dcd_nrf5x.c | 8 +++++--- 2 files changed, 16 insertions(+), 10 deletions(-) (limited to 'src/class') diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index c10fd8a69..ec804dcc8 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -72,8 +72,8 @@ typedef struct { uint8_t ep_out; uint8_t stage; - uint16_t data_len; - uint16_t xferred_len; // numbered of bytes transferred so far in the Data Stage + uint32_t data_len; + uint32_t xferred_len; // numbered of bytes transferred so far in the Data Stage }mscd_interface_t; CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN static mscd_interface_t _mscd_itf; @@ -225,8 +225,10 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u } else { - p_msc->data_len = tud_msc_scsi_cb(rhport, p_cbw->lun, p_cbw->command, _mscd_buf, p_msc->data_len); - p_csw->status = (p_msc->data_len >= 0) ? MSC_CSW_STATUS_PASSED : MSC_CSW_STATUS_FAILED; + int32_t const cb_result = tud_msc_scsi_cb(rhport, p_cbw->lun, p_cbw->command, _mscd_buf, p_msc->data_len); + + p_csw->status = (cb_result >= 0) ? MSC_CSW_STATUS_PASSED : MSC_CSW_STATUS_FAILED; + p_msc->data_len = (uint32_t) cb_result; TU_ASSERT( p_cbw->xfer_bytes >= p_msc->data_len, TUSB_ERROR_INVALID_PARA ); // cannot return more than host expect @@ -329,14 +331,16 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u if ( p_msc->stage == MSC_STAGE_STATUS ) { - // Invoke Complete Callback if defined + // Invoke complete callback if defined if ( SCSI_CMD_READ_10 == p_cbw->command[0]) { if ( tud_msc_read10_complete_cb ) tud_msc_read10_complete_cb(rhport, p_cbw->lun); - }else if ( SCSI_CMD_WRITE_10 == p_cbw->command[0] ) + } + else if ( SCSI_CMD_WRITE_10 == p_cbw->command[0] ) { if ( tud_msc_write10_complete_cb ) tud_msc_write10_complete_cb(rhport, p_cbw->lun); - }else + } + else { if ( tud_msc_scsi_complete_cb ) tud_msc_scsi_complete_cb(rhport, p_cbw->lun, p_cbw->command); } diff --git a/src/portable/nordic/nrf5x/dcd_nrf5x.c b/src/portable/nordic/nrf5x/dcd_nrf5x.c index 3d3fbdc80..d987cac7b 100644 --- a/src/portable/nordic/nrf5x/dcd_nrf5x.c +++ b/src/portable/nordic/nrf5x/dcd_nrf5x.c @@ -263,7 +263,7 @@ static void xact_out_dma(uint8_t epnum) /*------------- Bulk/Int IN transfer -------------*/ /** - * Prepare Bulk/Int in transaction, transfer data from Memory -> Endpoint + * Prepare Bulk/Int in transaction, use DMA to transfer data from Memory -> Endpoint * @param epnum */ static void xact_in_prepare(uint8_t epnum) @@ -415,8 +415,8 @@ void USBD_IRQHandler(void) if ( int_status & USBD_INTEN_EP0SETUP_Msk ) { uint8_t setup[8] = { - NRF_USBD->BMREQUESTTYPE, NRF_USBD->BREQUEST, NRF_USBD->WVALUEL, NRF_USBD->WVALUEH, - NRF_USBD->WINDEXL, NRF_USBD->WINDEXH, NRF_USBD->WLENGTHL, NRF_USBD->WLENGTHH + NRF_USBD->BMREQUESTTYPE , NRF_USBD->BREQUEST, NRF_USBD->WVALUEL , NRF_USBD->WVALUEH, + NRF_USBD->WINDEXL , NRF_USBD->WINDEXH , NRF_USBD->WLENGTHL, NRF_USBD->WLENGTHH }; dcd_setup_received(0, setup); @@ -486,6 +486,8 @@ void USBD_IRQHandler(void) dcd_xfer_complete(0, epnum, xfer->actual_len, true); } } + + // Ended event for Bulk/Int : nothing to do } if ( int_status & USBD_INTEN_EPDATA_Msk) -- cgit v1.3.1 From cfd5e1e6d19d94481ef84b4a16b41b2fae6c252e Mon Sep 17 00:00:00 2001 From: hathach Date: Sun, 24 Jun 2018 22:30:44 +0700 Subject: clean up --- examples/device/nrf52840/src/tusb_config.h | 2 +- examples/obsolete/device/src/tusb_config.h | 2 +- src/class/msc/msc_device.c | 6 ++++++ 3 files changed, 8 insertions(+), 2 deletions(-) (limited to 'src/class') diff --git a/examples/device/nrf52840/src/tusb_config.h b/examples/device/nrf52840/src/tusb_config.h index aee6099b5..8e031ea3b 100644 --- a/examples/device/nrf52840/src/tusb_config.h +++ b/examples/device/nrf52840/src/tusb_config.h @@ -80,7 +80,7 @@ // If not enabled, application must call tud_cdc_flush() periodically #define CFG_TUD_CDC_FLUSH_ON_SOF 1 -// Number of supported Logical Unit Number +// Number of supported Logical Unit Number (At least 1) #define CFG_TUD_MSC_MAXLUN 1 // Buffer size of Device Mass storage diff --git a/examples/obsolete/device/src/tusb_config.h b/examples/obsolete/device/src/tusb_config.h index 3904facbe..9dc9b3c2f 100644 --- a/examples/obsolete/device/src/tusb_config.h +++ b/examples/obsolete/device/src/tusb_config.h @@ -86,7 +86,7 @@ #define CFG_TUD_CDC_FLUSH_ON_SOF 1 -// Number of supported Logical Unit Number +// Number of supported Logical Unit Number (At least 1) #define CFG_TUD_MSC_MAXLUN 1 // Buffer size of Device Mass storage diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index ec804dcc8..3adcbc985 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -48,6 +48,12 @@ #include "msc_device.h" #include "device/usbd_pvt.h" +VERIFY_STATIC(CFG_TUD_MSC_BUFSIZE < UINT16_MAX, "Size is not correct"); + +#ifndef CFG_TUD_MSC_MAXLUN +#define CFG_TUD_MSC_MAXLUN 1 +#endif + //--------------------------------------------------------------------+ // MACRO CONSTANT TYPEDEF //--------------------------------------------------------------------+ -- cgit v1.3.1 From a08cb6e7274d307f704dafabbebbb7dd9ca73f30 Mon Sep 17 00:00:00 2001 From: hathach Date: Sun, 1 Jul 2018 15:54:40 +0700 Subject: clean up --- examples/device/device_virtual_com/src/main.c | 2 - .../device/device_virtual_com/src/tusb_config.h | 48 +++++- .../device_virtual_com/src/tusb_descriptors.c | 171 +-------------------- .../device_virtual_com/src/tusb_descriptors.h | 105 ------------- examples/device/nrf52840/src/tusb_config.h | 2 +- src/class/msc/msc_device.c | 4 +- src/tusb_option.h | 7 - 7 files changed, 52 insertions(+), 287 deletions(-) delete mode 100644 examples/device/device_virtual_com/src/tusb_descriptors.h (limited to 'src/class') diff --git a/examples/device/device_virtual_com/src/main.c b/examples/device/device_virtual_com/src/main.c index 8145d0183..531733cdc 100644 --- a/examples/device/device_virtual_com/src/main.c +++ b/examples/device/device_virtual_com/src/main.c @@ -45,7 +45,6 @@ #include "bsp/board.h" #include "tusb.h" -#include "tusb_descriptors.h" //--------------------------------------------------------------------+ // MACRO CONSTANT TYPEDEF @@ -65,7 +64,6 @@ int main(void) print_greeting(); tusb_init(); - tud_set_descriptors(&usb_desc_init); while (1) { diff --git a/examples/device/device_virtual_com/src/tusb_config.h b/examples/device/device_virtual_com/src/tusb_config.h index 16b932348..a69d2ecbb 100644 --- a/examples/device/device_virtual_com/src/tusb_config.h +++ b/examples/device/device_virtual_com/src/tusb_config.h @@ -51,25 +51,47 @@ #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE) //#define CFG_TUSB_RHPORT1_MODE (OPT_MODE_DEVICE) +#define CFG_TUSB_DEBUG 2 + +/*------------- RTOS -------------*/ +//#define CFG_TUSB_OS OPT_OS_NONE // be passed from IDE/command line for easy project switching +//#define CFG_TUD_TASK_PRIO 0 +//#define CFG_TUD_TASK_QUEUE_SZ 16 +//#define CFG_TUD_TASK_STACK_SZ 150 + //--------------------------------------------------------------------+ // DEVICE CONFIGURATION //--------------------------------------------------------------------+ + +/*------------- Core -------------*/ +#define CFG_TUD_DESC_AUTO 1 + +// #define CFG_TUD_DESC_VID 0xCAFE +// #define CFG_TUD_DESC_PID 0x0001 + #define CFG_TUD_ENDOINT0_SIZE 64 + //------------- CLASS -------------// +#define CFG_TUD_CDC 1 +#define CFG_TUD_MSC 0 #define CFG_TUD_HID_KEYBOARD 0 #define CFG_TUD_HID_MOUSE 0 #define CFG_TUD_HID_GENERIC 0 // not supported yet -#define CFG_TUD_MSC 0 -#define CFG_TUD_CDC 1 -//--------------------------------------------------------------------+ -// COMMON CONFIGURATION -//--------------------------------------------------------------------+ -#define CFG_TUSB_DEBUG 2 -//#define CFG_TUSB_OS OPT_OS_NONE // be passed from IDE/command line for easy project switching -//#define CFG_TUD_TASK_PRIO 0 // be passed from IDE/command line for easy project switching +/*------------------------------------------------------------------*/ +/* CLASS DRIVER + *------------------------------------------------------------------*/ + +// FIFO size of CDC TX and RX +#define CFG_TUD_CDC_RX_BUFSIZE 64 +#define CFG_TUD_CDC_TX_BUFSIZE 64 + + +// TX is sent automatically every Start of Frame event. +// If not enabled, application must call tud_cdc_flush() periodically +#define CFG_TUD_CDC_FLUSH_ON_SOF 1 //--------------------------------------------------------------------+ // USB RAM PLACEMENT @@ -115,6 +137,16 @@ #endif +// LPC11uxx and LPC13uxx requires each buffer has to be 64-byte alignment +#if CFG_TUSB_MCU == OPT_MCU_LPC11UXX || CFG_TUSB_MCU == OPT_MCU_LPC13UXX + #define CFG_TUSB_MEM_ALIGN ATTR_ALIGNED(64) +#elif CFG_TUSB_MCU == OPT_MCU_NRF5X + #define CFG_TUSB_MEM_ALIGN ATTR_ALIGNED(4) +#else + #define CFG_TUSB_MEM_ALIGN +#endif + + #ifdef __cplusplus } #endif diff --git a/examples/device/device_virtual_com/src/tusb_descriptors.c b/examples/device/device_virtual_com/src/tusb_descriptors.c index 85f8c12d8..2ba5434cc 100644 --- a/examples/device/device_virtual_com/src/tusb_descriptors.c +++ b/examples/device/device_virtual_com/src/tusb_descriptors.c @@ -36,164 +36,7 @@ */ /**************************************************************************/ -#include "tusb_descriptors.h" - -//--------------------------------------------------------------------+ -// USB DEVICE DESCRIPTOR -//--------------------------------------------------------------------+ -tusb_desc_device_t const desc_device = -{ - .bLength = sizeof(tusb_desc_device_t), - .bDescriptorType = TUSB_DESC_DEVICE, - .bcdUSB = 0x0200, - - // 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_ENDOINT0_SIZE, - - .idVendor = CFG_VENDORID, - .idProduct = CFG_PRODUCTID, - .bcdDevice = 0x0100, - - .iManufacturer = 0x01, - .iProduct = 0x02, - .iSerialNumber = 0x03, - - .bNumConfigurations = 0x01 -}; - -//--------------------------------------------------------------------+ -// USB COFNIGURATION DESCRIPTOR -//--------------------------------------------------------------------+ -app_descriptor_configuration_t const desc_configuration = -{ - .configuration = - { - .bLength = sizeof(tusb_desc_configuration_t), - .bDescriptorType = TUSB_DESC_CONFIGURATION, - - .wTotalLength = sizeof(app_descriptor_configuration_t), - .bNumInterfaces = ITF_TOTAL, - - .bConfigurationValue = 1, - .iConfiguration = 0x00, - .bmAttributes = TUSB_DESC_CONFIG_ATT_BUS_POWER, - .bMaxPower = TUSB_DESC_CONFIG_POWER_MA(500) - }, - - // IAD points to CDC Interfaces - .cdc_iad = - { - .bLength = sizeof(tusb_desc_interface_assoc_t), - .bDescriptorType = TUSB_DESC_INTERFACE_ASSOCIATION, - - .bFirstInterface = ITF_NUM_CDC, - .bInterfaceCount = 2, - - .bFunctionClass = TUSB_CLASS_CDC, - .bFunctionSubClass = CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL, - .bFunctionProtocol = CDC_COMM_PROTOCOL_ATCOMMAND, - .iFunction = 0 - }, - - //------------- CDC Communication Interface -------------// - .cdc_comm_interface = - { - .bLength = sizeof(tusb_desc_interface_t), - .bDescriptorType = TUSB_DESC_INTERFACE, - .bInterfaceNumber = ITF_NUM_CDC, - .bAlternateSetting = 0, - .bNumEndpoints = 1, - .bInterfaceClass = TUSB_CLASS_CDC, - .bInterfaceSubClass = CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL, - .bInterfaceProtocol = CDC_COMM_PROTOCOL_ATCOMMAND, - .iInterface = 0x00 - }, - - .cdc_header = - { - .bLength = sizeof(cdc_desc_func_header_t), - .bDescriptorType = TUSB_DESC_CLASS_SPECIFIC, - .bDescriptorSubType = CDC_FUNC_DESC_HEADER, - .bcdCDC = 0x0120 - }, - - .cdc_call = - { - .bLength = sizeof(cdc_desc_func_call_management_t), - .bDescriptorType = TUSB_DESC_CLASS_SPECIFIC, - .bDescriptorSubType = CDC_FUNC_DESC_CALL_MANAGEMENT, - .bmCapabilities = { 0 }, - .bDataInterface = ITF_NUM_CDC+1, - }, - - .cdc_acm = - { - .bLength = sizeof(cdc_desc_func_acm_t), - .bDescriptorType = TUSB_DESC_CLASS_SPECIFIC, - .bDescriptorSubType = CDC_FUNC_DESC_ABSTRACT_CONTROL_MANAGEMENT, - .bmCapabilities = { // 0x02 - .support_line_request = 1, - } - }, - - .cdc_union = - { - .bLength = sizeof(cdc_desc_func_union_t), // plus number of - .bDescriptorType = TUSB_DESC_CLASS_SPECIFIC, - .bDescriptorSubType = CDC_FUNC_DESC_UNION, - .bControlInterface = ITF_NUM_CDC, - .bSubordinateInterface = ITF_NUM_CDC+1, - }, - - .cdc_endpoint_notification = - { - .bLength = sizeof(tusb_desc_endpoint_t), - .bDescriptorType = TUSB_DESC_ENDPOINT, - .bEndpointAddress = CDC_EDPT_NOTIF, - .bmAttributes = { .xfer = TUSB_XFER_INTERRUPT }, - .wMaxPacketSize = { .size = 0x08 }, - .bInterval = 0x10 - }, - - //------------- CDC Data Interface -------------// - .cdc_data_interface = - { - .bLength = sizeof(tusb_desc_interface_t), - .bDescriptorType = TUSB_DESC_INTERFACE, - .bInterfaceNumber = ITF_NUM_CDC+1, - .bAlternateSetting = 0x00, - .bNumEndpoints = 2, - .bInterfaceClass = TUSB_CLASS_CDC_DATA, - .bInterfaceSubClass = 0, - .bInterfaceProtocol = 0, - .iInterface = 0x00 - }, - - .cdc_endpoint_out = - { - .bLength = sizeof(tusb_desc_endpoint_t), - .bDescriptorType = TUSB_DESC_ENDPOINT, - .bEndpointAddress = CDC_EDPT_OUT, - .bmAttributes = { .xfer = TUSB_XFER_BULK }, - .wMaxPacketSize = { .size = CDC_EDPT_SIZE }, - .bInterval = 0 - }, - - .cdc_endpoint_in = - { - .bLength = sizeof(tusb_desc_endpoint_t), - .bDescriptorType = TUSB_DESC_ENDPOINT, - .bEndpointAddress = CDC_EDPT_IN, - .bmAttributes = { .xfer = TUSB_XFER_BULK }, - .wMaxPacketSize = { .size = CDC_EDPT_SIZE }, - .bInterval = 0 - }, -}; +#include "tusb.h" //--------------------------------------------------------------------+ // STRING DESCRIPTORS @@ -246,10 +89,12 @@ uint16_t const * const string_desc_arr [] = }; -/*------------- Variable used by tud_set_descriptors -------------*/ -tud_desc_set_t usb_desc_init = +// tud_desc_set is required by tinyusb stack +// since CFG_TUD_DESC_AUTO is enabled, we only need to set string_arr +tud_desc_set_t tud_desc_set = { - .device = (uint8_t const * ) &desc_device, - .configuration = (uint8_t const * ) &desc_configuration, - .string_arr = (uint8_t const **) string_desc_arr, + .device = NULL, + .config = NULL, + .string_arr = (uint8_t const **) string_desc_arr, + .hid_report = NULL }; diff --git a/examples/device/device_virtual_com/src/tusb_descriptors.h b/examples/device/device_virtual_com/src/tusb_descriptors.h deleted file mode 100644 index 0c072fd40..000000000 --- a/examples/device/device_virtual_com/src/tusb_descriptors.h +++ /dev/null @@ -1,105 +0,0 @@ -/**************************************************************************/ -/*! - @file tusb_descriptors.h - @author hathach (tinyusb.org) - - @section LICENSE - - Software License Agreement (BSD License) - - Copyright (c) 2013, hathach (tinyusb.org) - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - 3. Neither the name of the copyright holders nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY - EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - This file is part of the tinyusb stack. -*/ -/**************************************************************************/ - -#ifndef _TUSB_DESCRIPTORS_H_ -#define _TUSB_DESCRIPTORS_H_ - -#include "tusb.h" - -//--------------------------------------------------------------------+ -// Descriptors Value (calculated by enabled Classes) -//--------------------------------------------------------------------+ -#define CFG_VENDORID 0xCAFE -//#define CFG_PRODUCTID 0x4567 // use auto product id to prevent conflict with pc's driver - -// each combination of interfaces need to have a unique productid, as windows will bind & remember device driver after the first plug. -// Auto ProductID layout's Bitmap: (MSB) MassStorage | Generic | Mouse | Key | CDC (LSB) -#ifndef CFG_PRODUCTID - #define PRODUCTID_BITMAP(interface, n) ( (CFG_TUD_##interface) << (n) ) - #define CFG_PRODUCTID (0x4000 | ( PRODUCTID_BITMAP(CDC, 0) | PRODUCTID_BITMAP(HID_KEYBOARD, 1) | \ - PRODUCTID_BITMAP(HID_MOUSE, 2) | PRODUCTID_BITMAP(HID_GENERIC, 3) | \ - PRODUCTID_BITMAP(MSC, 4) ) ) -#endif - -#define ITF_NUM_CDC 0 -#define ITF_TOTAL 2 - -//--------------------------------------------------------------------+ -// Endpoints Address & Max Packet Size -//--------------------------------------------------------------------+ -#define EDPT_IN(x) (0x80 | (x)) -#define EDPT_OUT(x) (x) - -#define CDC_EDPT_NOTIF EDPT_IN (1) -#define CDC_EDPT_NOTIFICATION_PACKETSIZE 64 - -#define CDC_EDPT_OUT EDPT_OUT(2) -#define CDC_EDPT_IN EDPT_IN (2) -#define CDC_EDPT_SIZE 64 - - -//--------------------------------------------------------------------+ -// CONFIGURATION DESCRIPTOR -//--------------------------------------------------------------------+ -typedef struct ATTR_PACKED -{ - tusb_desc_configuration_t configuration; - - //------------- CDC -------------// - tusb_desc_interface_assoc_t cdc_iad; - - //CDC Control Interface - tusb_desc_interface_t cdc_comm_interface; - cdc_desc_func_header_t cdc_header; - cdc_desc_func_call_management_t cdc_call; - cdc_desc_func_acm_t cdc_acm; - cdc_desc_func_union_t cdc_union; - tusb_desc_endpoint_t cdc_endpoint_notification; - - //CDC Data Interface - tusb_desc_interface_t cdc_data_interface; - tusb_desc_endpoint_t cdc_endpoint_out; - tusb_desc_endpoint_t cdc_endpoint_in; - -} app_descriptor_configuration_t; - - - -extern tud_desc_set_t usb_desc_init; - -#endif diff --git a/examples/device/nrf52840/src/tusb_config.h b/examples/device/nrf52840/src/tusb_config.h index 1857a8218..4e7210bcb 100644 --- a/examples/device/nrf52840/src/tusb_config.h +++ b/examples/device/nrf52840/src/tusb_config.h @@ -44,7 +44,7 @@ #endif //--------------------------------------------------------------------+ -// CONTROLLER CONFIGURATION +// COMMON CONFIGURATION //--------------------------------------------------------------------+ #define CFG_TUSB_MCU OPT_MCU_NRF5X #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index 3adcbc985..d61842c15 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -51,7 +51,9 @@ VERIFY_STATIC(CFG_TUD_MSC_BUFSIZE < UINT16_MAX, "Size is not correct"); #ifndef CFG_TUD_MSC_MAXLUN -#define CFG_TUD_MSC_MAXLUN 1 + #define CFG_TUD_MSC_MAXLUN 1 +#elif CFG_TUD_MSC_MAXLUN == 0 || CFG_TUD_MSC_MAXLUN > 16 + #error MSC Device: Incorrect setting of MAX LUN #endif //--------------------------------------------------------------------+ diff --git a/src/tusb_option.h b/src/tusb_option.h index 6cac0fe7f..4c175d5dd 100644 --- a/src/tusb_option.h +++ b/src/tusb_option.h @@ -205,13 +205,6 @@ #error Control Endpoint Max Package Size cannot larger than 64 #endif -#if CFG_TUD_MSC_MAXLUN == 0 || CFG_TUD_MSC_MAXLUN > 16 - #error MSC Device: Incorrect setting of MAX LUN -#endif - -//#if CFG_TUD_MSC_BUFSIZE - - #endif /* _TUSB_OPTION_H_ */ /** @} */ -- cgit v1.3.1 From 3e66d2d31e21d1ce91bcc4728c929b9bdf3421e8 Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 4 Jul 2018 00:22:15 +0700 Subject: rename fifo * to tu_fifo to avoid conflict with other module --- src/class/cdc/cdc_device.c | 22 +++++++-------- src/common/tusb_fifo.c | 44 ++++++++++++++--------------- src/common/tusb_fifo.h | 56 ++++++++++++++++++------------------- src/osal/osal_none.h | 12 ++++---- tests/lpc18xx_43xx/test/test_fifo.c | 20 ++++++------- 5 files changed, 77 insertions(+), 77 deletions(-) (limited to 'src/class') diff --git a/src/class/cdc/cdc_device.c b/src/class/cdc/cdc_device.c index 583180fcc..585c8c685 100644 --- a/src/class/cdc/cdc_device.c +++ b/src/class/cdc/cdc_device.c @@ -71,8 +71,8 @@ typedef struct { CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN uint8_t _tmp_rx_buf[64]; CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN uint8_t _tmp_tx_buf[64]; -FIFO_DEF(_rx_ff, CFG_TUD_CDC_RX_BUFSIZE, uint8_t, true); -FIFO_DEF(_tx_ff, CFG_TUD_CDC_TX_BUFSIZE, uint8_t, false); +TU_FIFO_DEF(_rx_ff, CFG_TUD_CDC_RX_BUFSIZE, uint8_t, true); +TU_FIFO_DEF(_tx_ff, CFG_TUD_CDC_TX_BUFSIZE, uint8_t, false); //--------------------------------------------------------------------+ // INTERNAL OBJECT & FUNCTION DECLARATION @@ -104,18 +104,18 @@ void tud_n_cdc_get_line_coding (uint8_t rhport, cdc_line_coding_t* coding) //--------------------------------------------------------------------+ uint32_t tud_n_cdc_available(uint8_t rhport) { - return fifo_count(&_rx_ff); + return tu_fifo_count(&_rx_ff); } int8_t tud_n_cdc_read_char(uint8_t rhport) { int8_t ch; - return fifo_read(&_rx_ff, &ch) ? ch : (-1); + return tu_fifo_read(&_rx_ff, &ch) ? ch : (-1); } uint32_t tud_n_cdc_read(uint8_t rhport, void* buffer, uint32_t bufsize) { - return fifo_read_n(&_rx_ff, buffer, bufsize); + return tu_fifo_read_n(&_rx_ff, buffer, bufsize); } //--------------------------------------------------------------------+ @@ -124,12 +124,12 @@ uint32_t tud_n_cdc_read(uint8_t rhport, void* buffer, uint32_t bufsize) uint32_t tud_n_cdc_write_char(uint8_t rhport, char ch) { - return fifo_write(&_tx_ff, &ch) ? 1 : 0; + return tu_fifo_write(&_tx_ff, &ch) ? 1 : 0; } uint32_t tud_n_cdc_write(uint8_t rhport, void const* buffer, uint32_t bufsize) { - return fifo_write_n(&_tx_ff, buffer, bufsize); + return tu_fifo_write_n(&_tx_ff, buffer, bufsize); } bool tud_n_cdc_flush (uint8_t rhport) @@ -137,7 +137,7 @@ bool tud_n_cdc_flush (uint8_t rhport) uint8_t edpt = _cdcd_itf[rhport].ep_in; VERIFY( !dcd_edpt_busy(rhport, edpt) ); // skip if previous transfer not complete - uint16_t count = fifo_read_n(&_tx_ff, _tmp_tx_buf, sizeof(_tmp_tx_buf)); + uint16_t count = tu_fifo_read_n(&_tx_ff, _tmp_tx_buf, sizeof(_tmp_tx_buf)); VERIFY( tud_n_cdc_connected(rhport) ); // fifo is empty if not connected @@ -230,8 +230,8 @@ void cdcd_close(uint8_t rhport) // no need to close opened pipe, dcd bus reset will put controller's endpoints to default state memclr_(&_cdcd_itf[rhport], sizeof(cdcd_interface_t)); - fifo_clear(&_rx_ff); - fifo_clear(&_tx_ff); + tu_fifo_clear(&_rx_ff); + tu_fifo_clear(&_tx_ff); } tusb_error_t cdcd_control_request_st(uint8_t rhport, tusb_control_request_t const * p_request) @@ -282,7 +282,7 @@ tusb_error_t cdcd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u if ( ep_addr == p_cdc->ep_out ) { - fifo_write_n(&_rx_ff, _tmp_rx_buf, xferred_bytes); + tu_fifo_write_n(&_rx_ff, _tmp_rx_buf, xferred_bytes); // preparing for next TU_ASSERT( dcd_edpt_xfer(rhport, p_cdc->ep_out, _tmp_rx_buf, sizeof(_tmp_rx_buf)), TUSB_ERROR_DCD_EDPT_XFER ); diff --git a/src/common/tusb_fifo.c b/src/common/tusb_fifo.c index d6f34f33f..03c0b63ab 100644 --- a/src/common/tusb_fifo.c +++ b/src/common/tusb_fifo.c @@ -1,6 +1,6 @@ /**************************************************************************/ /*! - @file fifo.c + @file tusb_fifo.c @author hathach (tinyusb.org) @section LICENSE @@ -44,8 +44,8 @@ *------------------------------------------------------------------*/ #if CFG_FIFO_MUTEX -#define mutex_lock_if_needed(_ff) if (_ff->mutex) fifo_mutex_lock(_ff->mutex) -#define mutex_unlock_if_needed(_ff) if (_ff->mutex) fifo_mutex_unlock(_ff->mutex) +#define mutex_lock_if_needed(_ff) if (_ff->mutex) tu_fifo_mutex_lock(_ff->mutex) +#define mutex_unlock_if_needed(_ff) if (_ff->mutex) tu_fifo_mutex_unlock(_ff->mutex) #else @@ -59,13 +59,13 @@ static inline uint16_t min16_of(uint16_t x, uint16_t y) return (x < y) ? x : y; } -static inline bool fifo_initalized(fifo_t* f) +static inline bool tu_fifo_initalized(tu_fifo_t* f) { return (f->buffer != NULL) && (f->depth > 0) && (f->item_size > 0); } -void fifo_config(fifo_t *f, void* buffer, uint16_t depth, uint16_t item_size, bool overwritable) +void tu_fifo_config(tu_fifo_t *f, void* buffer, uint16_t depth, uint16_t item_size, bool overwritable) { mutex_lock_if_needed(f); @@ -96,10 +96,10 @@ void fifo_config(fifo_t *f, void* buffer, uint16_t depth, uint16_t item_size, bo @returns TRUE if the queue is not empty */ /******************************************************************************/ -bool fifo_read(fifo_t* f, void * p_buffer) +bool tu_fifo_read(tu_fifo_t* f, void * p_buffer) { - if( !fifo_initalized(f) ) return false; - if( fifo_empty(f) ) return false; + if( !tu_fifo_initalized(f) ) return false; + if( tu_fifo_empty(f) ) return false; mutex_lock_if_needed(f); @@ -130,10 +130,10 @@ bool fifo_read(fifo_t* f, void * p_buffer) @returns number of items read from the FIFO */ /******************************************************************************/ -uint16_t fifo_read_n (fifo_t* f, void * p_buffer, uint16_t count) +uint16_t tu_fifo_read_n (tu_fifo_t* f, void * p_buffer, uint16_t count) { - if( !fifo_initalized(f) ) return 0; - if( fifo_empty(f) ) return 0; + if( !tu_fifo_initalized(f) ) return 0; + if( tu_fifo_empty(f) ) return 0; /* Limit up to fifo's count */ count = min16_of(count, f->count); @@ -149,7 +149,7 @@ uint16_t fifo_read_n (fifo_t* f, void * p_buffer, uint16_t count) uint8_t* p_buf = (uint8_t*) p_buffer; uint16_t len = 0; - while( (len < count) && fifo_read(f, p_buf) ) + while( (len < count) && tu_fifo_read(f, p_buf) ) { len++; p_buf += f->item_size; @@ -174,9 +174,9 @@ uint16_t fifo_read_n (fifo_t* f, void * p_buffer, uint16_t count) @returns TRUE if the queue is not empty */ /******************************************************************************/ -bool fifo_peek_at(fifo_t* f, uint16_t position, void * p_buffer) +bool tu_fifo_peek_at(tu_fifo_t* f, uint16_t position, void * p_buffer) { - if ( !fifo_initalized(f) ) return false; + if ( !tu_fifo_initalized(f) ) return false; if ( position >= f->count ) return false; // rd_idx is position=0 @@ -205,12 +205,12 @@ bool fifo_peek_at(fifo_t* f, uint16_t position, void * p_buffer) FIFO will always return TRUE) */ /******************************************************************************/ -bool fifo_write(fifo_t* f, void const * p_data) +bool tu_fifo_write(tu_fifo_t* f, void const * p_data) { - if ( !fifo_initalized(f) ) return false; + if ( !tu_fifo_initalized(f) ) return false; -// if ( fifo_full(f) && !f->overwritable ) return false; - TU_ASSERT( !(fifo_full(f) && !f->overwritable) ); +// if ( tu_fifo_full(f) && !f->overwritable ) return false; + TU_ASSERT( !(tu_fifo_full(f) && !f->overwritable) ); mutex_lock_if_needed(f); @@ -220,7 +220,7 @@ bool fifo_write(fifo_t* f, void const * p_data) f->wr_idx = (f->wr_idx + 1) % f->depth; - if (fifo_full(f)) + if (tu_fifo_full(f)) { f->rd_idx = f->wr_idx; // keep the full state (rd == wr && len = size) } @@ -249,14 +249,14 @@ bool fifo_write(fifo_t* f, void const * p_data) @return Number of written elements */ /******************************************************************************/ -uint16_t fifo_write_n(fifo_t* f, void const * p_data, uint16_t count) +uint16_t tu_fifo_write_n(tu_fifo_t* f, void const * p_data, uint16_t count) { if ( count == 0 ) return 0; uint8_t* p_buf = (uint8_t*) p_data; uint16_t len = 0; - while( (len < count) && fifo_write(f, p_buf) ) + while( (len < count) && tu_fifo_write(f, p_buf) ) { len++; p_buf += f->item_size; @@ -273,7 +273,7 @@ uint16_t fifo_write_n(fifo_t* f, void const * p_data, uint16_t count) Pointer to the FIFO buffer to manipulate */ /******************************************************************************/ -void fifo_clear(fifo_t *f) +void tu_fifo_clear(tu_fifo_t *f) { mutex_lock_if_needed(f); diff --git a/src/common/tusb_fifo.h b/src/common/tusb_fifo.h index 452b1f35f..d87b32395 100644 --- a/src/common/tusb_fifo.h +++ b/src/common/tusb_fifo.h @@ -1,6 +1,6 @@ /**************************************************************************/ /*! - @file fifo.h + @file tusb_fifo.h @author hathach (tinyusb.org) @section LICENSE @@ -65,10 +65,10 @@ #define _ff_mutex_def(mutex) #else -#define fifo_mutex_t struct os_mutex +#define tu_fifo_mutex_t struct os_mutex -#define fifo_mutex_lock(m) os_mutex_pend(m, OS_TIMEOUT_NEVER) -#define fifo_mutex_unlock(m) os_mutex_release(m) +#define tu_fifo_mutex_lock(m) os_mutex_pend(m, OS_TIMEOUT_NEVER) +#define tu_fifo_mutex_unlock(m) os_mutex_release(m) /* Internal use only */ #define _mutex_declare(m) .mutex = m @@ -82,7 +82,7 @@ #endif -/** \struct fifo_t +/** \struct tu_fifo_t * \brief Simple Circular FIFO */ typedef struct @@ -98,59 +98,59 @@ typedef struct bool overwritable ; #if CFG_FIFO_MUTEX - fifo_mutex_t * const mutex; + tu_fifo_mutex_t * const mutex; #endif -} fifo_t; +} tu_fifo_t; -#define FIFO_DEF(name, ff_depth, type, is_overwritable) /*, irq_mutex)*/ \ - uint8_t name##_buffer[ff_depth*sizeof(type)];\ - fifo_t name = {\ - .buffer = name##_buffer,\ - .depth = ff_depth,\ - .item_size = sizeof(type),\ - .overwritable = is_overwritable,\ +#define TU_FIFO_DEF(_name, _depth, _type, _overwritable) /*, irq_mutex)*/ \ + uint8_t _name##_buf[_depth*sizeof(_type)];\ + tu_fifo_t _name = {\ + .buffer = _name##_buf,\ + .depth = _depth,\ + .item_size = sizeof(_type),\ + .overwritable = _overwritable,\ /*.irq = irq_mutex*/\ _mutex_declare(_mutex)\ } -void fifo_clear(fifo_t *f); -void fifo_config(fifo_t *f, void* buffer, uint16_t depth, uint16_t item_size, bool overwritable); +void tu_fifo_clear(tu_fifo_t *f); +void tu_fifo_config(tu_fifo_t *f, void* buffer, uint16_t depth, uint16_t item_size, bool overwritable); -bool fifo_write (fifo_t* f, void const * p_data); -uint16_t fifo_write_n (fifo_t* f, void const * p_data, uint16_t count); +bool tu_fifo_write (tu_fifo_t* f, void const * p_data); +uint16_t tu_fifo_write_n (tu_fifo_t* f, void const * p_data, uint16_t count); -bool fifo_read (fifo_t* f, void * p_buffer); -uint16_t fifo_read_n (fifo_t* f, void * p_buffer, uint16_t count); +bool tu_fifo_read (tu_fifo_t* f, void * p_buffer); +uint16_t tu_fifo_read_n (tu_fifo_t* f, void * p_buffer, uint16_t count); -bool fifo_peek_at (fifo_t* f, uint16_t position, void * p_buffer); +bool tu_fifo_peek_at (tu_fifo_t* f, uint16_t position, void * p_buffer); -static inline bool fifo_peek(fifo_t* f, void * p_buffer) +static inline bool tu_fifo_peek(tu_fifo_t* f, void * p_buffer) { - return fifo_peek_at(f, 0, p_buffer); + return tu_fifo_peek_at(f, 0, p_buffer); } -static inline bool fifo_empty(fifo_t* f) +static inline bool tu_fifo_empty(tu_fifo_t* f) { return (f->count == 0); } -static inline bool fifo_full(fifo_t* f) +static inline bool tu_fifo_full(tu_fifo_t* f) { return (f->count == f->depth); } -static inline uint16_t fifo_count(fifo_t* f) +static inline uint16_t tu_fifo_count(tu_fifo_t* f) { return f->count; } -static inline uint16_t fifo_remaining(fifo_t* f) +static inline uint16_t tu_fifo_remaining(tu_fifo_t* f) { return f->depth - f->count; } -static inline uint16_t fifo_depth(fifo_t* f) +static inline uint16_t tu_fifo_depth(tu_fifo_t* f) { return f->depth; } diff --git a/src/osal/osal_none.h b/src/osal/osal_none.h index 9bdb047b4..1328d1753 100644 --- a/src/osal/osal_none.h +++ b/src/osal/osal_none.h @@ -130,20 +130,20 @@ static inline osal_task_t osal_task_create(osal_task_def_t* taskdef) //--------------------------------------------------------------------+ // QUEUE API //--------------------------------------------------------------------+ -#define OSAL_QUEUE_DEF(_name, _depth, _type) FIFO_DEF(_name, _depth, _type, false) +#define OSAL_QUEUE_DEF(_name, _depth, _type) TU_FIFO_DEF(_name, _depth, _type, false) -typedef fifo_t osal_queue_def_t; -typedef fifo_t* osal_queue_t; +typedef tu_fifo_t osal_queue_def_t; +typedef tu_fifo_t* osal_queue_t; static inline osal_queue_t osal_queue_create(osal_queue_def_t* qdef) { - fifo_clear(qdef); + tu_fifo_clear(qdef); return (osal_queue_t) qdef; } static inline bool osal_queue_send_isr(osal_queue_t const queue_hdl, void const * data) { - return fifo_write( (fifo_t*) queue_hdl, data); + return tu_fifo_write( (tu_fifo_t*) queue_hdl, data); } #define osal_queue_send osal_queue_send_isr @@ -164,7 +164,7 @@ static inline void osal_queue_flush(osal_queue_t const queue_hdl) return TUSB_ERROR_OSAL_WAITING; \ } else{ \ /*tusb_hal_int_disable_all();*/ \ - fifo_read(queue_hdl, p_data); \ + tu_fifo_read(queue_hdl, p_data); \ /*tusb_hal_int_enable_all();*/ \ *(p_error) = TUSB_ERROR_NONE; \ } \ diff --git a/tests/lpc18xx_43xx/test/test_fifo.c b/tests/lpc18xx_43xx/test/test_fifo.c index 2729644ff..0441680f7 100644 --- a/tests/lpc18xx_43xx/test/test_fifo.c +++ b/tests/lpc18xx_43xx/test/test_fifo.c @@ -40,11 +40,11 @@ #include "fifo.h" #define FIFO_SIZE 10 -FIFO_DEF(ff, FIFO_SIZE, uint8_t, false); +TU_FIFO_DEF(ff, FIFO_SIZE, uint8_t, false); void setUp(void) { - fifo_clear(&ff); + tu_fifo_clear(&ff); } void tearDown(void) @@ -57,13 +57,13 @@ void test_normal(void) for(i=0; i < FIFO_SIZE; i++) { - fifo_write(&ff, &i); + tu_fifo_write(&ff, &i); } for(i=0; i < FIFO_SIZE; i++) { uint8_t c; - fifo_read(&ff, &c); + tu_fifo_read(&ff, &c); TEST_ASSERT_EQUAL(i, c); } } @@ -71,21 +71,21 @@ void test_normal(void) void test_is_empty(void) { uint8_t temp; - TEST_ASSERT_TRUE(fifo_is_empty(&ff)); - fifo_write(&ff, &temp); - TEST_ASSERT_FALSE(fifo_is_empty(&ff)); + TEST_ASSERT_TRUE(tu_fifo_is_empty(&ff)); + tu_fifo_write(&ff, &temp); + TEST_ASSERT_FALSE(tu_fifo_is_empty(&ff)); } void test_is_full(void) { uint8_t i; - TEST_ASSERT_FALSE(fifo_is_full(&ff)); + TEST_ASSERT_FALSE(tu_fifo_is_full(&ff)); for(i=0; i < FIFO_SIZE; i++) { - fifo_write(&ff, &i); + tu_fifo_write(&ff, &i); } - TEST_ASSERT_TRUE(fifo_is_full(&ff)); + TEST_ASSERT_TRUE(tu_fifo_is_full(&ff)); } -- cgit v1.3.1 From 3eb410cf8521755874fb9900a7f711bcafdc81d5 Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 4 Jul 2018 14:39:32 +0700 Subject: add CFG_TUD_MSC_BLOCK_NUM, CFG_TUD_MSC_BLOCK_SZ msc device auto response to scsi read capa and read format cap --- src/class/msc/msc_device.c | 53 ++++++++++++++++++++++++++++++++++++++++++++-- src/tusb_option.h | 8 +++++++ 2 files changed, 59 insertions(+), 2 deletions(-) (limited to 'src/class') diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index d61842c15..f8fa33de8 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -40,14 +40,17 @@ #if (MODE_DEVICE_SUPPORTED && CFG_TUD_MSC) -#define _TINY_USB_SOURCE_FILE_ //--------------------------------------------------------------------+ // INCLUDE //--------------------------------------------------------------------+ +#define _TINY_USB_SOURCE_FILE_ #include "common/tusb_common.h" #include "msc_device.h" #include "device/usbd_pvt.h" +//--------------------------------------------------------------------+ +// Config Verification +//--------------------------------------------------------------------+ VERIFY_STATIC(CFG_TUD_MSC_BUFSIZE < UINT16_MAX, "Size is not correct"); #ifndef CFG_TUD_MSC_MAXLUN @@ -56,6 +59,18 @@ VERIFY_STATIC(CFG_TUD_MSC_BUFSIZE < UINT16_MAX, "Size is not correct"); #error MSC Device: Incorrect setting of MAX LUN #endif +#ifndef CFG_TUD_MSC_BLOCK_NUM + #error CFG_TUD_MSC_BLOCK_NUM must be defined +#endif + +#ifndef CFG_TUD_MSC_BLOCK_SZ + #error CFG_TUD_MSC_BLOCK_SZ must be defined +#endif + +#ifndef CFG_TUD_MSC_BUFSIZE + #error CFG_TUD_MSC_BUFSIZE must be defined, value of CFG_TUD_MSC_BLOCK_SZ should work well, the more the better +#endif + //--------------------------------------------------------------------+ // MACRO CONSTANT TYPEDEF //--------------------------------------------------------------------+ @@ -233,7 +248,38 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u } else { - int32_t const cb_result = tud_msc_scsi_cb(rhport, p_cbw->lun, p_cbw->command, _mscd_buf, p_msc->data_len); + // IN Transfer + + int32_t cb_result; + + if (SCSI_CMD_READ_CAPACITY_10 == p_cbw->command[0]) + { + scsi_read_capacity10_data_t read_capa10 = + { + .last_lba = ENDIAN_BE(CFG_TUD_MSC_BLOCK_NUM-1), // read capacity + .block_size = ENDIAN_BE(CFG_TUD_MSC_BLOCK_SZ) + }; + + cb_result = sizeof(read_capa10); + memcpy(_mscd_buf, &read_capa10, cb_result); + } + else if (SCSI_CMD_READ_FORMAT_CAPACITY == p_cbw->command[0]) + { + scsi_read_format_capacity_data_t read_fmt_capa = + { + .list_length = 8, + .block_num = ENDIAN_BE(CFG_TUD_MSC_BLOCK_NUM), // write capacity + .descriptor_type = 2, // formatted media + .block_size_u16 = ENDIAN_BE16(CFG_TUD_MSC_BLOCK_SZ) + }; + + cb_result = sizeof(read_fmt_capa); + memcpy(_mscd_buf, &read_fmt_capa, cb_result); + } + else + { + cb_result = tud_msc_scsi_cb(rhport, p_cbw->lun, p_cbw->command, _mscd_buf, p_msc->data_len); + } p_csw->status = (cb_result >= 0) ? MSC_CSW_STATUS_PASSED : MSC_CSW_STATUS_FAILED; p_msc->data_len = (uint32_t) cb_result; @@ -365,6 +411,9 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u return TUSB_ERROR_NONE; } +/*------------------------------------------------------------------*/ +/* SCSI Command Process + *------------------------------------------------------------------*/ static void proc_read10_cmd(uint8_t rhport, mscd_interface_t* p_msc) { msc_cbw_t const * p_cbw = &p_msc->cbw; diff --git a/src/tusb_option.h b/src/tusb_option.h index 4c175d5dd..de4720620 100644 --- a/src/tusb_option.h +++ b/src/tusb_option.h @@ -163,6 +163,14 @@ #define CFG_TUD_DESC_AUTO 0 #endif + #ifndef CFG_TUD_CDC + #define CFG_TUD_CDC 0 + #endif + + #ifndef CFG_TUD_MSC + #define CFG_TUD_MSC 0 + #endif + #endif // MODE_DEVICE_SUPPORTED //--------------------------------------------------------------------+ -- cgit v1.3.1 From fc139b009f4c49d4fdbf1b80097c94c8dabb1ee1 Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 4 Jul 2018 15:00:46 +0700 Subject: add CFG_TUD_MSC_VENDOR,CFG_TUD_MSC_PRODUCT, CFG_TUD_MSC_PRODUCT_REV for msc inquiry response --- src/class/msc/msc.h | 6 +++--- src/class/msc/msc_device.c | 34 +++++++++++++++++++++++++++++++++- 2 files changed, 36 insertions(+), 4 deletions(-) (limited to 'src/class') diff --git a/src/class/msc/msc.h b/src/class/msc/msc.h index a8af2b886..fc0b8730c 100644 --- a/src/class/msc/msc.h +++ b/src/class/msc/msc.h @@ -226,9 +226,9 @@ typedef struct ATTR_PACKED uint8_t wbus16 : 1; uint8_t : 2; - uint8_t vendor_id[8] ; ///< 8 bytes of ASCII data identifying the vendor of the product. The T10 vendor identification shall be one assigned by INCITS. A list of assigned T10 vendor identifications is in Annex E and on the T10 web site (http://www.t10.org). - uint8_t product_id[16] ; ///< 16 bytes of ASCII data defined by the vendor. - uint8_t product_revision[4] ; ///< 4 bytes of ASCII data defined by the vendor. + uint8_t vendor_id[8] ; ///< 8 bytes of ASCII data identifying the vendor of the product. + uint8_t product_id[16]; ///< 16 bytes of ASCII data defined by the vendor. + uint8_t product_rev[4]; ///< 4 bytes of ASCII data defined by the vendor. } scsi_inquiry_data_t; VERIFY_STATIC(sizeof(scsi_inquiry_data_t) == 36, "size is not correct"); diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index f8fa33de8..5a92d2470 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -71,6 +71,18 @@ VERIFY_STATIC(CFG_TUD_MSC_BUFSIZE < UINT16_MAX, "Size is not correct"); #error CFG_TUD_MSC_BUFSIZE must be defined, value of CFG_TUD_MSC_BLOCK_SZ should work well, the more the better #endif +#ifndef CFG_TUD_MSC_VENDOR + #error CFG_TUD_MSC_VENDOR 8-byte name must be defined +#endif + +#ifndef CFG_TUD_MSC_PRODUCT + #error CFG_TUD_MSC_PRODUCT 16-byte name must be defined +#endif + +#ifndef CFG_TUD_MSC_PRODUCT_REV + #error CFG_TUD_MSC_PRODUCT_REV 4-byte string must be defined +#endif + //--------------------------------------------------------------------+ // MACRO CONSTANT TYPEDEF //--------------------------------------------------------------------+ @@ -252,6 +264,7 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u int32_t cb_result; + // TODO refactor later if (SCSI_CMD_READ_CAPACITY_10 == p_cbw->command[0]) { scsi_read_capacity10_data_t read_capa10 = @@ -269,13 +282,32 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u { .list_length = 8, .block_num = ENDIAN_BE(CFG_TUD_MSC_BLOCK_NUM), // write capacity - .descriptor_type = 2, // formatted media + .descriptor_type = 2, // formatted media .block_size_u16 = ENDIAN_BE16(CFG_TUD_MSC_BLOCK_SZ) }; cb_result = sizeof(read_fmt_capa); memcpy(_mscd_buf, &read_fmt_capa, cb_result); } + else if (SCSI_CMD_INQUIRY == p_cbw->command[0]) + { + scsi_inquiry_data_t inquiry_rsp = + { + .is_removable = 1, + .version = 2, + .response_data_format = 2, + .vendor_id = "Adafruit", + .product_id = "Feather52840", + .product_rev = "1.0" + }; + + strncpy((char*) inquiry_rsp.vendor_id , CFG_TUD_MSC_VENDOR , sizeof(inquiry_rsp.vendor_id)); + strncpy((char*) inquiry_rsp.product_id , CFG_TUD_MSC_PRODUCT , sizeof(inquiry_rsp.product_id)); + strncpy((char*) inquiry_rsp.product_rev, CFG_TUD_MSC_PRODUCT_REV, sizeof(inquiry_rsp.product_rev)); + + cb_result = sizeof(inquiry_rsp); + memcpy(_mscd_buf, &inquiry_rsp, cb_result); + } else { cb_result = tud_msc_scsi_cb(rhport, p_cbw->lun, p_cbw->command, _mscd_buf, p_msc->data_len); -- cgit v1.3.1 From a4292e590668c30f78027573f59f1f4abca9dcb8 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 12 Jul 2018 23:08:54 +0700 Subject: changing cdc device to support multiple interface (not yet) --- src/class/cdc/cdc_device.c | 62 ++++++++++++++++++++++------------------------ src/class/cdc/cdc_device.h | 41 +++++++++++++++--------------- src/device/usbd.c | 3 --- 3 files changed, 50 insertions(+), 56 deletions(-) (limited to 'src/class') diff --git a/src/class/cdc/cdc_device.c b/src/class/cdc/cdc_device.c index 585c8c685..c84e67aa8 100644 --- a/src/class/cdc/cdc_device.c +++ b/src/class/cdc/cdc_device.c @@ -51,9 +51,9 @@ //--------------------------------------------------------------------+ // MACRO CONSTANT TYPEDEF //--------------------------------------------------------------------+ -CFG_TUSB_ATTR_USBRAM STATIC_VAR cdc_line_coding_t cdcd_line_coding[CONTROLLER_DEVICE_NUMBER]; - typedef struct { + CFG_TUSB_MEM_ALIGN cdc_line_coding_t line_coding; + uint8_t itf_num; uint8_t ep_notif; uint8_t ep_in; @@ -65,55 +65,53 @@ typedef struct { uint8_t line_state; }cdcd_interface_t; -// TODO multiple rhport - - -CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN uint8_t _tmp_rx_buf[64]; -CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN uint8_t _tmp_tx_buf[64]; +//--------------------------------------------------------------------+ +// INTERNAL OBJECT & FUNCTION DECLARATION +//--------------------------------------------------------------------+ +CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN static uint8_t _tmp_rx_buf[64]; +CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN static uint8_t _tmp_tx_buf[64]; TU_FIFO_DEF(_rx_ff, CFG_TUD_CDC_RX_BUFSIZE, uint8_t, true); TU_FIFO_DEF(_tx_ff, CFG_TUD_CDC_TX_BUFSIZE, uint8_t, false); -//--------------------------------------------------------------------+ -// INTERNAL OBJECT & FUNCTION DECLARATION -//--------------------------------------------------------------------+ -STATIC_VAR cdcd_interface_t _cdcd_itf[CONTROLLER_DEVICE_NUMBER]; +CFG_TUSB_ATTR_USBRAM +static cdcd_interface_t _cdcd_itf[CFG_TUD_CDC]; //--------------------------------------------------------------------+ // APPLICATION API //--------------------------------------------------------------------+ -bool tud_n_cdc_connected(uint8_t rhport) +bool tud_cdc_n_connected(uint8_t rhport) { // DTR (bit 0) active isconsidered as connected return BIT_TEST_(_cdcd_itf[rhport].line_state, 0); } -uint8_t tud_n_cdc_get_line_state (uint8_t rhport) +uint8_t tud_cdc_n_get_line_state (uint8_t rhport) { return _cdcd_itf[rhport].line_state; } -void tud_n_cdc_get_line_coding (uint8_t rhport, cdc_line_coding_t* coding) +void tud_cdc_n_get_line_coding (uint8_t rhport, cdc_line_coding_t* coding) { - (*coding) = cdcd_line_coding[rhport]; + (*coding) = _cdcd_itf[0].line_coding; } //--------------------------------------------------------------------+ // READ API //--------------------------------------------------------------------+ -uint32_t tud_n_cdc_available(uint8_t rhport) +uint32_t tud_cdc_n_available(uint8_t rhport) { return tu_fifo_count(&_rx_ff); } -int8_t tud_n_cdc_read_char(uint8_t rhport) +int8_t tud_cdc_n_read_char(uint8_t rhport) { int8_t ch; return tu_fifo_read(&_rx_ff, &ch) ? ch : (-1); } -uint32_t tud_n_cdc_read(uint8_t rhport, void* buffer, uint32_t bufsize) +uint32_t tud_cdc_n_read(uint8_t rhport, void* buffer, uint32_t bufsize) { return tu_fifo_read_n(&_rx_ff, buffer, bufsize); } @@ -122,24 +120,24 @@ uint32_t tud_n_cdc_read(uint8_t rhport, void* buffer, uint32_t bufsize) // WRITE API //--------------------------------------------------------------------+ -uint32_t tud_n_cdc_write_char(uint8_t rhport, char ch) +uint32_t tud_cdc_n_write_char(uint8_t rhport, char ch) { return tu_fifo_write(&_tx_ff, &ch) ? 1 : 0; } -uint32_t tud_n_cdc_write(uint8_t rhport, void const* buffer, uint32_t bufsize) +uint32_t tud_cdc_n_write(uint8_t rhport, void const* buffer, uint32_t bufsize) { return tu_fifo_write_n(&_tx_ff, buffer, bufsize); } -bool tud_n_cdc_flush (uint8_t rhport) +bool tud_cdc_n_flush (uint8_t rhport) { uint8_t edpt = _cdcd_itf[rhport].ep_in; VERIFY( !dcd_edpt_busy(rhport, edpt) ); // skip if previous transfer not complete uint16_t count = tu_fifo_read_n(&_tx_ff, _tmp_tx_buf, sizeof(_tmp_tx_buf)); - VERIFY( tud_n_cdc_connected(rhport) ); // fifo is empty if not connected + VERIFY( tud_cdc_n_connected(rhport) ); // fifo is empty if not connected if ( count ) TU_ASSERT( dcd_edpt_xfer(rhport, edpt, _tmp_tx_buf, count) ); @@ -152,16 +150,15 @@ bool tud_n_cdc_flush (uint8_t rhport) //--------------------------------------------------------------------+ void cdcd_init(void) { - memclr_(_cdcd_itf, sizeof(cdcd_interface_t)*CONTROLLER_DEVICE_NUMBER); + arrclr_(_cdcd_itf); // default line coding is : stop bit = 1, parity = none, data bits = 8 - memclr_(cdcd_line_coding, sizeof(cdc_line_coding_t)*CONTROLLER_DEVICE_NUMBER); - for(uint8_t i=0; ibmRequestType_bit.type != TUSB_REQ_TYPE_CLASS) return TUSB_ERROR_DCD_CONTROL_REQUEST_NOT_SUPPORT; + // TODO Support multiple interface if ( (CDC_REQUEST_GET_LINE_CODING == p_request->bRequest) || (CDC_REQUEST_SET_LINE_CODING == p_request->bRequest) ) { uint16_t len = min16_of(sizeof(cdc_line_coding_t), p_request->wLength); - usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, (uint8_t*) &cdcd_line_coding[rhport], len); + usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, (uint8_t*) &_cdcd_itf[0].line_coding, len); // Invoke callback if (CDC_REQUEST_SET_LINE_CODING == p_request->bRequest) { - if ( tud_cdc_line_coding_cb ) tud_cdc_line_coding_cb(rhport, &cdcd_line_coding[rhport]); + if ( tud_cdc_line_coding_cb ) tud_cdc_line_coding_cb(rhport, &_cdcd_itf[0].line_coding); } } else if (CDC_REQUEST_SET_CONTROL_LINE_STATE == p_request->bRequest ) @@ -297,7 +295,7 @@ tusb_error_t cdcd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u #if CFG_TUD_CDC_FLUSH_ON_SOF void cdcd_sof(uint8_t rhport) { - tud_n_cdc_flush(rhport); + tud_cdc_n_flush(rhport); } #endif diff --git a/src/class/cdc/cdc_device.h b/src/class/cdc/cdc_device.h index c1a790fc8..8b098b579 100644 --- a/src/class/cdc/cdc_device.h +++ b/src/class/cdc/cdc_device.h @@ -53,36 +53,35 @@ * @{ */ //--------------------------------------------------------------------+ -// APPLICATION API (Multiple Root Ports) -// Should be used only with MCU that support more than 1 ports +// APPLICATION API (Multiple Interfaces) +// CFG_TUD_CDC > 1 //--------------------------------------------------------------------+ -bool tud_n_cdc_connected (uint8_t rhport); -uint8_t tud_n_cdc_get_line_state (uint8_t rhport); -void tud_n_cdc_get_line_coding (uint8_t rhport, cdc_line_coding_t* coding); +bool tud_cdc_n_connected (uint8_t rhport); +uint8_t tud_cdc_n_get_line_state (uint8_t rhport); +void tud_cdc_n_get_line_coding (uint8_t rhport, cdc_line_coding_t* coding); -uint32_t tud_n_cdc_available (uint8_t rhport); -int8_t tud_n_cdc_read_char (uint8_t rhport); -uint32_t tud_n_cdc_read (uint8_t rhport, void* buffer, uint32_t bufsize); +uint32_t tud_cdc_n_available (uint8_t rhport); +int8_t tud_cdc_n_read_char (uint8_t rhport); +uint32_t tud_cdc_n_read (uint8_t rhport, void* buffer, uint32_t bufsize); -uint32_t tud_n_cdc_write_char (uint8_t rhport, char ch); -uint32_t tud_n_cdc_write (uint8_t rhport, void const* buffer, uint32_t bufsize); -bool tud_n_cdc_flush (uint8_t rhport); +uint32_t tud_cdc_n_write_char (uint8_t rhport, char ch); +uint32_t tud_cdc_n_write (uint8_t rhport, void const* buffer, uint32_t bufsize); +bool tud_cdc_n_flush (uint8_t rhport); //--------------------------------------------------------------------+ -// APPLICATION API (Single Port) -// Should be used with MCU supporting only 1 USB port for code simplicity +// APPLICATION API (Interface0) //--------------------------------------------------------------------+ -static inline bool tud_cdc_connected (void) { return tud_n_cdc_connected(0); } -static inline uint8_t tud_cdc_get_line_state (uint8_t rhport) { return tud_n_cdc_get_line_state(0); } +static inline bool tud_cdc_connected (void) { return tud_cdc_n_connected(0); } +static inline uint8_t tud_cdc_get_line_state (uint8_t rhport) { return tud_cdc_n_get_line_state(0); } static inline void tud_cdc_get_line_coding (uint8_t rhport, cdc_line_coding_t* coding) { return tud_cdc_get_line_coding(0, coding); } -static inline uint32_t tud_cdc_available (void) { return tud_n_cdc_available(0); } -static inline int8_t tud_cdc_read_char (void) { return tud_n_cdc_read_char(0); } -static inline uint32_t tud_cdc_read (void* buffer, uint32_t bufsize) { return tud_n_cdc_read(0, buffer, bufsize); } +static inline uint32_t tud_cdc_available (void) { return tud_cdc_n_available(0); } +static inline int8_t tud_cdc_read_char (void) { return tud_cdc_n_read_char(0); } +static inline uint32_t tud_cdc_read (void* buffer, uint32_t bufsize) { return tud_cdc_n_read(0, buffer, bufsize); } -static inline uint32_t tud_cdc_write_char (char ch) { return tud_n_cdc_write_char(0, ch); } -static inline uint32_t tud_cdc_write (void const* buffer, uint32_t bufsize) { return tud_n_cdc_write(0, buffer, bufsize); } -static inline bool tud_cdc_flush (void) { return tud_n_cdc_flush(0); } +static inline uint32_t tud_cdc_write_char (char ch) { return tud_cdc_n_write_char(0, ch); } +static inline uint32_t tud_cdc_write (void const* buffer, uint32_t bufsize) { return tud_cdc_n_write(0, buffer, bufsize); } +static inline bool tud_cdc_flush (void) { return tud_cdc_n_flush(0); } //--------------------------------------------------------------------+ // APPLICATION CALLBACK API (WEAK is optional) diff --git a/src/device/usbd.c b/src/device/usbd.c index 5c3e889a7..b1649ab4b 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -516,9 +516,6 @@ static uint16_t get_descriptor(uint8_t rhport, tusb_control_request_t const * co return len; } -//--------------------------------------------------------------------+ -// USBD-CLASS API -//--------------------------------------------------------------------+ //--------------------------------------------------------------------+ // USBD-DCD Callback API -- cgit v1.3.1 From a623f0c179b49f510a206666bbe2ca52144a6458 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 13 Jul 2018 00:32:02 +0700 Subject: better multiple interfaces support for cdc device --- src/class/cdc/cdc_device.c | 134 ++++++++++++++++++++++++++------------------- src/class/cdc/cdc_device.h | 42 +++++++------- src/device/usbd.c | 2 + src/device/usbd_pvt.h | 10 +++- src/tusb_option.h | 2 + 5 files changed, 112 insertions(+), 78 deletions(-) (limited to 'src/class') diff --git a/src/class/cdc/cdc_device.c b/src/class/cdc/cdc_device.c index c84e67aa8..9c991b5ab 100644 --- a/src/class/cdc/cdc_device.c +++ b/src/class/cdc/cdc_device.c @@ -51,18 +51,19 @@ //--------------------------------------------------------------------+ // MACRO CONSTANT TYPEDEF //--------------------------------------------------------------------+ -typedef struct { - CFG_TUSB_MEM_ALIGN cdc_line_coding_t line_coding; - +typedef struct +{ + /*------------- usbd_itf_t compatible -------------*/ uint8_t itf_num; + uint8_t ep_count; uint8_t ep_notif; uint8_t ep_in; uint8_t ep_out; - cdc_acm_capability_t acm_cap; - // Bit 0: DTR (Data Terminal Ready), Bit 1: RTS (Request to Send) uint8_t line_state; + + CFG_TUSB_MEM_ALIGN cdc_line_coding_t line_coding; }cdcd_interface_t; //--------------------------------------------------------------------+ @@ -71,8 +72,11 @@ typedef struct { CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN static uint8_t _tmp_rx_buf[64]; CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN static uint8_t _tmp_tx_buf[64]; -TU_FIFO_DEF(_rx_ff, CFG_TUD_CDC_RX_BUFSIZE, uint8_t, true); -TU_FIFO_DEF(_tx_ff, CFG_TUD_CDC_TX_BUFSIZE, uint8_t, false); +uint8_t _rx_ff_buf[CFG_TUD_CDC][CFG_TUD_CDC_RX_BUFSIZE]; +uint8_t _tx_ff_buf[CFG_TUD_CDC][CFG_TUD_CDC_RX_BUFSIZE]; + +tu_fifo_t _rx_ff[CFG_TUD_CDC]; +tu_fifo_t _tx_ff[CFG_TUD_CDC]; CFG_TUSB_ATTR_USBRAM static cdcd_interface_t _cdcd_itf[CFG_TUD_CDC]; @@ -80,66 +84,66 @@ static cdcd_interface_t _cdcd_itf[CFG_TUD_CDC]; //--------------------------------------------------------------------+ // APPLICATION API //--------------------------------------------------------------------+ -bool tud_cdc_n_connected(uint8_t rhport) +bool tud_cdc_n_connected(uint8_t itf) { // DTR (bit 0) active isconsidered as connected - return BIT_TEST_(_cdcd_itf[rhport].line_state, 0); + return BIT_TEST_(_cdcd_itf[itf].line_state, 0); } -uint8_t tud_cdc_n_get_line_state (uint8_t rhport) +uint8_t tud_cdc_n_get_line_state (uint8_t itf) { - return _cdcd_itf[rhport].line_state; + return _cdcd_itf[itf].line_state; } -void tud_cdc_n_get_line_coding (uint8_t rhport, cdc_line_coding_t* coding) +void tud_cdc_n_get_line_coding (uint8_t itf, cdc_line_coding_t* coding) { - (*coding) = _cdcd_itf[0].line_coding; + (*coding) = _cdcd_itf[itf].line_coding; } //--------------------------------------------------------------------+ // READ API //--------------------------------------------------------------------+ -uint32_t tud_cdc_n_available(uint8_t rhport) +uint32_t tud_cdc_n_available(uint8_t itf) { - return tu_fifo_count(&_rx_ff); + return tu_fifo_count(&_rx_ff[itf]); } -int8_t tud_cdc_n_read_char(uint8_t rhport) +int8_t tud_cdc_n_read_char(uint8_t itf) { int8_t ch; - return tu_fifo_read(&_rx_ff, &ch) ? ch : (-1); + return tu_fifo_read(&_rx_ff[itf], &ch) ? ch : (-1); } -uint32_t tud_cdc_n_read(uint8_t rhport, void* buffer, uint32_t bufsize) +uint32_t tud_cdc_n_read(uint8_t itf, void* buffer, uint32_t bufsize) { - return tu_fifo_read_n(&_rx_ff, buffer, bufsize); + return tu_fifo_read_n(&_rx_ff[itf], buffer, bufsize); } //--------------------------------------------------------------------+ // WRITE API //--------------------------------------------------------------------+ -uint32_t tud_cdc_n_write_char(uint8_t rhport, char ch) +uint32_t tud_cdc_n_write_char(uint8_t itf, char ch) { - return tu_fifo_write(&_tx_ff, &ch) ? 1 : 0; + return tu_fifo_write(&_tx_ff[itf], &ch) ? 1 : 0; } -uint32_t tud_cdc_n_write(uint8_t rhport, void const* buffer, uint32_t bufsize) +uint32_t tud_cdc_n_write(uint8_t itf, void const* buffer, uint32_t bufsize) { - return tu_fifo_write_n(&_tx_ff, buffer, bufsize); + return tu_fifo_write_n(&_tx_ff[itf], buffer, bufsize); } -bool tud_cdc_n_flush (uint8_t rhport) +bool tud_cdc_n_flush (uint8_t itf) { - uint8_t edpt = _cdcd_itf[rhport].ep_in; - VERIFY( !dcd_edpt_busy(rhport, edpt) ); // skip if previous transfer not complete + uint8_t edpt = _cdcd_itf[itf].ep_in; + VERIFY( !dcd_edpt_busy(TUD_RHPORT, edpt) ); // skip if previous transfer not complete - uint16_t count = tu_fifo_read_n(&_tx_ff, _tmp_tx_buf, sizeof(_tmp_tx_buf)); + uint16_t count = tu_fifo_read_n(&_tx_ff[itf], _tmp_tx_buf, sizeof(_tmp_tx_buf)); - VERIFY( tud_cdc_n_connected(rhport) ); // fifo is empty if not connected + VERIFY( tud_cdc_n_connected(itf) ); // fifo is empty if not connected - if ( count ) TU_ASSERT( dcd_edpt_xfer(rhport, edpt, _tmp_tx_buf, count) ); + if ( count ) TU_ASSERT( dcd_edpt_xfer(TUD_RHPORT, edpt, _tmp_tx_buf, count) ); return true; } @@ -152,13 +156,10 @@ void cdcd_init(void) { arrclr_(_cdcd_itf); - // default line coding is : stop bit = 1, parity = none, data bits = 8 for(uint8_t i=0; iitf_num = p_interface_desc->bInterfaceNumber; + p_cdc->ep_count = p_interface_desc->bNumEndpoints; - //------------- Communication Interface -------------// + uint8_t const * p_desc = descriptor_next ( (uint8_t const *) p_interface_desc ); (*p_length) = sizeof(tusb_desc_interface_t); // Communication Functional Descriptors while( TUSB_DESC_CLASS_SPECIFIC == p_desc[DESCRIPTOR_OFFSET_TYPE] ) { - if ( CDC_FUNC_DESC_ABSTRACT_CONTROL_MANAGEMENT == cdc_functional_desc_typeof(p_desc) ) - { // save ACM bmCapabilities - p_cdc->acm_cap = ((cdc_desc_func_acm_t const *) p_desc)->bmCapabilities; - } - (*p_length) += p_desc[DESCRIPTOR_OFFSET_LENGTH]; p_desc = descriptor_next(p_desc); } @@ -204,6 +212,10 @@ tusb_error_t cdcd_open(uint8_t rhport, tusb_desc_interface_t const * p_interface if ( (TUSB_DESC_INTERFACE == p_desc[DESCRIPTOR_OFFSET_TYPE]) && (TUSB_CLASS_CDC_DATA == ((tusb_desc_interface_t const *) p_desc)->bInterfaceClass) ) { + // p_cdc->itf_num = + p_cdc->ep_count += ((tusb_desc_interface_t const *) p_desc)->bNumEndpoints; + + // next to endpoint descritpor (*p_length) += p_desc[DESCRIPTOR_OFFSET_LENGTH]; p_desc = descriptor_next(p_desc); @@ -214,8 +226,6 @@ tusb_error_t cdcd_open(uint8_t rhport, tusb_desc_interface_t const * p_interface (*p_length) += 2*sizeof(tusb_desc_endpoint_t); } - p_cdc->itf_num = p_interface_desc->bInterfaceNumber; - // Prepare for incoming data TU_ASSERT( dcd_edpt_xfer(rhport, p_cdc->ep_out, _tmp_rx_buf, sizeof(_tmp_rx_buf)), TUSB_ERROR_DCD_EDPT_XFER); @@ -225,10 +235,15 @@ tusb_error_t cdcd_open(uint8_t rhport, tusb_desc_interface_t const * p_interface void cdcd_close(uint8_t rhport) { // no need to close opened pipe, dcd bus reset will put controller's endpoints to default state - memclr_(&_cdcd_itf[rhport], sizeof(cdcd_interface_t)); + (void) rhport; + + arrclr_(_cdcd_itf); - tu_fifo_clear(&_rx_ff); - tu_fifo_clear(&_tx_ff); + for(uint8_t i=0; ibmRequestType_bit.type != TUSB_REQ_TYPE_CLASS) return TUSB_ERROR_DCD_CONTROL_REQUEST_NOT_SUPPORT; - // TODO Support multiple interface + // TODO Support multiple interfaces + uint8_t const itf = 0; + cdcd_interface_t* p_cdc = &_cdcd_itf[itf]; + if ( (CDC_REQUEST_GET_LINE_CODING == p_request->bRequest) || (CDC_REQUEST_SET_LINE_CODING == p_request->bRequest) ) { uint16_t len = min16_of(sizeof(cdc_line_coding_t), p_request->wLength); - usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, (uint8_t*) &_cdcd_itf[0].line_coding, len); + usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, &p_cdc->line_coding, len); // Invoke callback if (CDC_REQUEST_SET_LINE_CODING == p_request->bRequest) { - if ( tud_cdc_line_coding_cb ) tud_cdc_line_coding_cb(rhport, &_cdcd_itf[0].line_coding); + if ( tud_cdc_line_coding_cb ) tud_cdc_line_coding_cb(itf, &p_cdc->line_coding); } } else if (CDC_REQUEST_SET_CONTROL_LINE_STATE == p_request->bRequest ) @@ -257,14 +275,13 @@ tusb_error_t cdcd_control_request_st(uint8_t rhport, tusb_control_request_t cons // This signal corresponds to V.24 signal 108/2 and RS-232 signal DTR (Data Terminal Ready) // Bit 1: Carrier control for half-duplex modems. // This signal corresponds to V.24 signal 105 and RS-232 signal RTS (Request to Send) - cdcd_interface_t * p_cdc = &_cdcd_itf[rhport]; p_cdc->line_state = (uint8_t) p_request->wValue; dcd_control_status(rhport, p_request->bmRequestType_bit.direction); // ACK control request // Invoke callback - if ( tud_cdc_line_state_cb) tud_cdc_line_state_cb(rhport, BIT_TEST_(p_request->wValue, 0), BIT_TEST_(p_request->wValue, 1)); + if ( tud_cdc_line_state_cb) tud_cdc_line_state_cb(itf, BIT_TEST_(p_request->wValue, 0), BIT_TEST_(p_request->wValue, 1)); } else { @@ -276,17 +293,19 @@ tusb_error_t cdcd_control_request_st(uint8_t rhport, tusb_control_request_t cons tusb_error_t cdcd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, uint32_t xferred_bytes) { - cdcd_interface_t const * p_cdc = &_cdcd_itf[rhport]; + // TODO Support multiple interfaces + uint8_t const itf = 0; + cdcd_interface_t const * p_cdc = &_cdcd_itf[itf]; if ( ep_addr == p_cdc->ep_out ) { - tu_fifo_write_n(&_rx_ff, _tmp_rx_buf, xferred_bytes); + tu_fifo_write_n(&_rx_ff[itf], _tmp_rx_buf, xferred_bytes); // preparing for next TU_ASSERT( dcd_edpt_xfer(rhport, p_cdc->ep_out, _tmp_rx_buf, sizeof(_tmp_rx_buf)), TUSB_ERROR_DCD_EDPT_XFER ); // fire callback - if (tud_cdc_rx_cb) tud_cdc_rx_cb(rhport); + if (tud_cdc_rx_cb) tud_cdc_rx_cb(itf); } return TUSB_ERROR_NONE; @@ -295,7 +314,10 @@ tusb_error_t cdcd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u #if CFG_TUD_CDC_FLUSH_ON_SOF void cdcd_sof(uint8_t rhport) { - tud_cdc_n_flush(rhport); + for(uint8_t i=0; i 1 //--------------------------------------------------------------------+ -bool tud_cdc_n_connected (uint8_t rhport); -uint8_t tud_cdc_n_get_line_state (uint8_t rhport); -void tud_cdc_n_get_line_coding (uint8_t rhport, cdc_line_coding_t* coding); +bool tud_cdc_n_connected (uint8_t itf); +uint8_t tud_cdc_n_get_line_state (uint8_t itf); +void tud_cdc_n_get_line_coding (uint8_t itf, cdc_line_coding_t* coding); -uint32_t tud_cdc_n_available (uint8_t rhport); -int8_t tud_cdc_n_read_char (uint8_t rhport); -uint32_t tud_cdc_n_read (uint8_t rhport, void* buffer, uint32_t bufsize); +uint32_t tud_cdc_n_available (uint8_t itf); +int8_t tud_cdc_n_read_char (uint8_t itf); +uint32_t tud_cdc_n_read (uint8_t itf, void* buffer, uint32_t bufsize); -uint32_t tud_cdc_n_write_char (uint8_t rhport, char ch); -uint32_t tud_cdc_n_write (uint8_t rhport, void const* buffer, uint32_t bufsize); -bool tud_cdc_n_flush (uint8_t rhport); +uint32_t tud_cdc_n_write_char (uint8_t itf, char ch); +uint32_t tud_cdc_n_write (uint8_t itf, void const* buffer, uint32_t bufsize); +bool tud_cdc_n_flush (uint8_t itf); //--------------------------------------------------------------------+ // APPLICATION API (Interface0) //--------------------------------------------------------------------+ -static inline bool tud_cdc_connected (void) { return tud_cdc_n_connected(0); } -static inline uint8_t tud_cdc_get_line_state (uint8_t rhport) { return tud_cdc_n_get_line_state(0); } -static inline void tud_cdc_get_line_coding (uint8_t rhport, cdc_line_coding_t* coding) { return tud_cdc_get_line_coding(0, coding); } +static inline bool tud_cdc_connected (void) { return tud_cdc_n_connected(0); } +static inline uint8_t tud_cdc_get_line_state (void) { return tud_cdc_n_get_line_state(0); } +static inline void tud_cdc_get_line_coding (cdc_line_coding_t* coding) { return tud_cdc_n_get_line_coding(0, coding);} -static inline uint32_t tud_cdc_available (void) { return tud_cdc_n_available(0); } -static inline int8_t tud_cdc_read_char (void) { return tud_cdc_n_read_char(0); } -static inline uint32_t tud_cdc_read (void* buffer, uint32_t bufsize) { return tud_cdc_n_read(0, buffer, bufsize); } +static inline uint32_t tud_cdc_available (void) { return tud_cdc_n_available(0); } +static inline int8_t tud_cdc_read_char (void) { return tud_cdc_n_read_char(0); } +static inline uint32_t tud_cdc_read (void* buffer, uint32_t bufsize) { return tud_cdc_n_read(0, buffer, bufsize); } -static inline uint32_t tud_cdc_write_char (char ch) { return tud_cdc_n_write_char(0, ch); } -static inline uint32_t tud_cdc_write (void const* buffer, uint32_t bufsize) { return tud_cdc_n_write(0, buffer, bufsize); } -static inline bool tud_cdc_flush (void) { return tud_cdc_n_flush(0); } +static inline uint32_t tud_cdc_write_char (char ch) { return tud_cdc_n_write_char(0, ch); } +static inline uint32_t tud_cdc_write (void const* buffer, uint32_t bufsize) { return tud_cdc_n_write(0, buffer, bufsize); } +static inline bool tud_cdc_flush (void) { return tud_cdc_n_flush(0); } //--------------------------------------------------------------------+ // APPLICATION CALLBACK API (WEAK is optional) //--------------------------------------------------------------------+ -ATTR_WEAK void tud_cdc_rx_cb(uint8_t rhport); -ATTR_WEAK void tud_cdc_line_state_cb(uint8_t rhport, bool dtr, bool rts); -ATTR_WEAK void tud_cdc_line_coding_cb(uint8_t rhport, cdc_line_coding_t const* p_line_coding); +ATTR_WEAK void tud_cdc_rx_cb(uint8_t itf); +ATTR_WEAK void tud_cdc_line_state_cb(uint8_t itf, bool dtr, bool rts); +ATTR_WEAK void tud_cdc_line_coding_cb(uint8_t itf, cdc_line_coding_t const* p_line_coding); //--------------------------------------------------------------------+ // USBD-CLASS DRIVER API diff --git a/src/device/usbd.c b/src/device/usbd.c index b1649ab4b..971f7dd05 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -528,6 +528,8 @@ void dcd_bus_event(uint8_t rhport, usbd_bus_event_type_t bus_event) varclr_(&_usbd_dev); osal_queue_flush(_usbd_q); osal_semaphore_reset_isr(_usbd_ctrl_sem); + + // TODO move to unplugged for (uint8_t i = 0; i < USBD_CLASS_DRIVER_COUNT; i++) { if ( usbd_class_drivers[i].close ) usbd_class_drivers[i].close( rhport ); diff --git a/src/device/usbd_pvt.h b/src/device/usbd_pvt.h index e9b8263f5..452df5934 100644 --- a/src/device/usbd_pvt.h +++ b/src/device/usbd_pvt.h @@ -45,6 +45,14 @@ // for used by usbd_control_xfer_st() only, must not be used directly extern osal_semaphore_t _usbd_ctrl_sem; + +typedef struct +{ + uint8_t itf_num; + uint8_t ep_count; + uint8_t ep_arr[1]; +}usbd_itf_t; + //--------------------------------------------------------------------+ // INTERNAL API for stack management //--------------------------------------------------------------------+ @@ -63,7 +71,7 @@ tusb_error_t usbd_open_edpt_pair(uint8_t rhport, tusb_desc_endpoint_t const* p_d do {\ if (_len) { \ tusb_error_t err;\ - dcd_control_xfer(_rhport, _dir, _buffer, _len);\ + dcd_control_xfer(_rhport, _dir, (uint8_t*) _buffer, _len);\ osal_semaphore_wait( _usbd_ctrl_sem, OSAL_TIMEOUT_CONTROL_XFER, &err );\ STASK_ASSERT_ERR( err );\ }\ diff --git a/src/tusb_option.h b/src/tusb_option.h index 6d3292171..04374bc19 100644 --- a/src/tusb_option.h +++ b/src/tusb_option.h @@ -107,6 +107,8 @@ #define MODE_HOST_SUPPORTED (CONTROLLER_HOST_NUMBER > 0) #define MODE_DEVICE_SUPPORTED (CONTROLLER_DEVICE_NUMBER > 0) +#define TUD_RHPORT ((CFG_TUSB_RHPORT0_MODE & OPT_MODE_DEVICE) ? 0 : ((CFG_TUSB_RHPORT1_MODE & OPT_MODE_DEVICE) ? 1 : -1)) + #if !MODE_HOST_SUPPORTED && !MODE_DEVICE_SUPPORTED #error please configure at least 1 CFG_TUSB_CONTROLLER_N_MODE to OPT_MODE_HOST and/or OPT_MODE_DEVICE #endif -- cgit v1.3.1 From ffdd925854c3fda233f41c929b5cf115cfdb7a62 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 13 Jul 2018 00:33:46 +0700 Subject: clean up --- examples/device/device_virtual_com/src/main.c | 2 +- examples/device/nrf52840/src/main.c | 6 +++--- examples/obsolete/device/src/cdc_device_app.c | 2 +- src/class/cdc/cdc_device.h | 10 +++++----- 4 files changed, 10 insertions(+), 10 deletions(-) (limited to 'src/class') diff --git a/examples/device/device_virtual_com/src/main.c b/examples/device/device_virtual_com/src/main.c index 531733cdc..033d313eb 100644 --- a/examples/device/device_virtual_com/src/main.c +++ b/examples/device/device_virtual_com/src/main.c @@ -103,7 +103,7 @@ void tud_umount_cb(uint8_t port) { } -void tud_cdc_rx_cb(uint8_t port) +void tud_cdc_rx_cb(uint8_t itf) { } diff --git a/examples/device/nrf52840/src/main.c b/examples/device/nrf52840/src/main.c index 2877801cf..1ac56423d 100644 --- a/examples/device/nrf52840/src/main.c +++ b/examples/device/nrf52840/src/main.c @@ -95,16 +95,16 @@ void virtual_com_task(void) //--------------------------------------------------------------------+ // tinyusb callbacks //--------------------------------------------------------------------+ -void tud_mount_cb(uint8_t port) +void tud_mount_cb(uint8_t rhport) { } -void tud_umount_cb(uint8_t port) +void tud_umount_cb(uint8_t rhport) { } -void tud_cdc_rx_cb(uint8_t port) +void tud_cdc_rx_cb(uint8_t itf) { } diff --git a/examples/obsolete/device/src/cdc_device_app.c b/examples/obsolete/device/src/cdc_device_app.c index 843ab5a7a..7989d86ab 100644 --- a/examples/obsolete/device/src/cdc_device_app.c +++ b/examples/obsolete/device/src/cdc_device_app.c @@ -67,7 +67,7 @@ void cdc_serial_app_umount(uint8_t rhport) } -void tud_cdc_rx_cb(uint8_t rhport) +void tud_cdc_rx_cb(uint8_t itf) { } diff --git a/src/class/cdc/cdc_device.h b/src/class/cdc/cdc_device.h index e3ace37bb..a754669df 100644 --- a/src/class/cdc/cdc_device.h +++ b/src/class/cdc/cdc_device.h @@ -95,11 +95,11 @@ ATTR_WEAK void tud_cdc_line_coding_cb(uint8_t itf, cdc_line_coding_t const* p_li //--------------------------------------------------------------------+ #ifdef _TINY_USB_SOURCE_FILE_ -void cdcd_init(void); -tusb_error_t cdcd_open(uint8_t rhport, tusb_desc_interface_t const * p_interface_desc, uint16_t *p_length); -tusb_error_t cdcd_control_request_st(uint8_t rhport, tusb_control_request_t const * p_request); -tusb_error_t cdcd_xfer_cb(uint8_t rhport, uint8_t edpt_addr, tusb_event_t event, uint32_t xferred_bytes); -void cdcd_close(uint8_t rhport); +void cdcd_init (void); +tusb_error_t cdcd_open (uint8_t rhport, tusb_desc_interface_t const * p_interface_desc, uint16_t *p_length); +tusb_error_t cdcd_control_request_st (uint8_t rhport, tusb_control_request_t const * p_request); +tusb_error_t cdcd_xfer_cb (uint8_t rhport, uint8_t edpt_addr, tusb_event_t event, uint32_t xferred_bytes); +void cdcd_close (uint8_t rhport); #if CFG_TUD_CDC_FLUSH_ON_SOF void cdcd_sof(uint8_t rhport); -- cgit v1.3.1 From dccb06ba7d7c1a162ea84b98b1429ff8f4b74b0e Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 13 Jul 2018 16:09:26 +0700 Subject: rename class driver close() to reset() --- src/class/cdc/cdc_device.c | 2 +- src/class/cdc/cdc_device.h | 2 +- src/class/custom/custom_device.c | 2 +- src/class/custom/custom_device.h | 2 +- src/class/hid/hid_device.c | 2 +- src/class/hid/hid_device.h | 2 +- src/class/msc/msc_device.c | 2 +- src/class/msc/msc_device.h | 2 +- src/device/usbd.c | 18 ++++++++++++------ 9 files changed, 20 insertions(+), 14 deletions(-) (limited to 'src/class') diff --git a/src/class/cdc/cdc_device.c b/src/class/cdc/cdc_device.c index 9c991b5ab..643706269 100644 --- a/src/class/cdc/cdc_device.c +++ b/src/class/cdc/cdc_device.c @@ -232,7 +232,7 @@ tusb_error_t cdcd_open(uint8_t rhport, tusb_desc_interface_t const * p_interface return TUSB_ERROR_NONE; } -void cdcd_close(uint8_t rhport) +void cdcd_reset(uint8_t rhport) { // no need to close opened pipe, dcd bus reset will put controller's endpoints to default state (void) rhport; diff --git a/src/class/cdc/cdc_device.h b/src/class/cdc/cdc_device.h index a754669df..bdce0f86e 100644 --- a/src/class/cdc/cdc_device.h +++ b/src/class/cdc/cdc_device.h @@ -99,7 +99,7 @@ void cdcd_init (void); tusb_error_t cdcd_open (uint8_t rhport, tusb_desc_interface_t const * p_interface_desc, uint16_t *p_length); tusb_error_t cdcd_control_request_st (uint8_t rhport, tusb_control_request_t const * p_request); tusb_error_t cdcd_xfer_cb (uint8_t rhport, uint8_t edpt_addr, tusb_event_t event, uint32_t xferred_bytes); -void cdcd_close (uint8_t rhport); +void cdcd_reset (uint8_t rhport); #if CFG_TUD_CDC_FLUSH_ON_SOF void cdcd_sof(uint8_t rhport); diff --git a/src/class/custom/custom_device.c b/src/class/custom/custom_device.c index 3d0453001..e4dc1a839 100644 --- a/src/class/custom/custom_device.c +++ b/src/class/custom/custom_device.c @@ -97,7 +97,7 @@ tusb_error_t cusd_xfer_cb(uint8_t rhport, uint8_t edpt_addr, tusb_event_t event, return TUSB_ERROR_NONE; } -void cusd_close(uint8_t rhport) +void cusd_reset(uint8_t rhport) { } diff --git a/src/class/custom/custom_device.h b/src/class/custom/custom_device.h index 08f4f7f4a..3e46c06a7 100644 --- a/src/class/custom/custom_device.h +++ b/src/class/custom/custom_device.h @@ -64,7 +64,7 @@ void cusd_init(void); tusb_error_t cusd_open(uint8_t rhport, tusb_desc_interface_t const * p_interface_desc, uint16_t *p_length); tusb_error_t cusd_control_request_st(uint8_t rhport, tusb_control_request_t const * p_request); tusb_error_t cusd_xfer_cb(uint8_t rhport, uint8_t edpt_addr, tusb_event_t event, uint32_t xferred_bytes); -void cusd_close(uint8_t rhport); +void cusd_reset(uint8_t rhport); #endif diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index a6080e69d..bc2ee8c64 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -168,7 +168,7 @@ void hidd_init(void) } } -void hidd_close(uint8_t rhport) +void hidd_reset(uint8_t rhport) { for(uint8_t i=0; i Date: Fri, 13 Jul 2018 17:48:26 +0700 Subject: add ep2drv, rename descriptor offset --- src/class/cdc/cdc_device.c | 12 +++---- src/class/cdc/cdc_host.c | 14 ++++---- src/class/hid/hid_device.c | 4 +-- src/class/hid/hid_host.c | 4 +-- src/common/tusb_common.h | 11 +++++-- src/common/tusb_types.h | 4 +-- src/device/usbd.c | 79 +++++++++++++++++++++++++++++++--------------- src/host/usbh.c | 8 ++--- 8 files changed, 85 insertions(+), 51 deletions(-) (limited to 'src/class') diff --git a/src/class/cdc/cdc_device.c b/src/class/cdc/cdc_device.c index 643706269..76526d40b 100644 --- a/src/class/cdc/cdc_device.c +++ b/src/class/cdc/cdc_device.c @@ -192,31 +192,31 @@ tusb_error_t cdcd_open(uint8_t rhport, tusb_desc_interface_t const * p_interface (*p_length) = sizeof(tusb_desc_interface_t); // Communication Functional Descriptors - while( TUSB_DESC_CLASS_SPECIFIC == p_desc[DESCRIPTOR_OFFSET_TYPE] ) + while( TUSB_DESC_CLASS_SPECIFIC == p_desc[DESC_OFFSET_TYPE] ) { - (*p_length) += p_desc[DESCRIPTOR_OFFSET_LENGTH]; + (*p_length) += p_desc[DESC_OFFSET_LEN]; p_desc = descriptor_next(p_desc); } - if ( TUSB_DESC_ENDPOINT == p_desc[DESCRIPTOR_OFFSET_TYPE]) + if ( TUSB_DESC_ENDPOINT == p_desc[DESC_OFFSET_TYPE]) { // notification endpoint if any TU_ASSERT( dcd_edpt_open(rhport, (tusb_desc_endpoint_t const *) p_desc), TUSB_ERROR_DCD_OPEN_PIPE_FAILED); p_cdc->ep_notif = ((tusb_desc_endpoint_t const *) p_desc)->bEndpointAddress; - (*p_length) += p_desc[DESCRIPTOR_OFFSET_LENGTH]; + (*p_length) += p_desc[DESC_OFFSET_LEN]; p_desc = descriptor_next(p_desc); } //------------- Data Interface (if any) -------------// - if ( (TUSB_DESC_INTERFACE == p_desc[DESCRIPTOR_OFFSET_TYPE]) && + if ( (TUSB_DESC_INTERFACE == p_desc[DESC_OFFSET_TYPE]) && (TUSB_CLASS_CDC_DATA == ((tusb_desc_interface_t const *) p_desc)->bInterfaceClass) ) { // p_cdc->itf_num = p_cdc->ep_count += ((tusb_desc_interface_t const *) p_desc)->bNumEndpoints; // next to endpoint descritpor - (*p_length) += p_desc[DESCRIPTOR_OFFSET_LENGTH]; + (*p_length) += p_desc[DESC_OFFSET_LEN]; p_desc = descriptor_next(p_desc); // Open endpoint pair with usbd helper diff --git a/src/class/cdc/cdc_host.c b/src/class/cdc/cdc_host.c index bd5b5e32c..6950759d1 100644 --- a/src/class/cdc/cdc_host.c +++ b/src/class/cdc/cdc_host.c @@ -167,32 +167,32 @@ tusb_error_t cdch_open_subtask(uint8_t dev_addr, tusb_desc_interface_t const *p_ //------------- Communication Interface -------------// (*p_length) = sizeof(tusb_desc_interface_t); - while( TUSB_DESC_CLASS_SPECIFIC == p_desc[DESCRIPTOR_OFFSET_TYPE] ) + while( TUSB_DESC_CLASS_SPECIFIC == p_desc[DESC_OFFSET_TYPE] ) { // Communication Functional Descriptors if ( CDC_FUNC_DESC_ABSTRACT_CONTROL_MANAGEMENT == cdc_functional_desc_typeof(p_desc) ) { // save ACM bmCapabilities p_cdc->acm_capability = ((cdc_desc_func_acm_t const *) p_desc)->bmCapabilities; } - (*p_length) += p_desc[DESCRIPTOR_OFFSET_LENGTH]; + (*p_length) += p_desc[DESC_OFFSET_LEN]; p_desc = descriptor_next(p_desc); } - if ( TUSB_DESC_ENDPOINT == p_desc[DESCRIPTOR_OFFSET_TYPE]) + if ( TUSB_DESC_ENDPOINT == p_desc[DESC_OFFSET_TYPE]) { // notification endpoint if any p_cdc->pipe_notification = hcd_pipe_open(dev_addr, (tusb_desc_endpoint_t const *) p_desc, TUSB_CLASS_CDC); - (*p_length) += p_desc[DESCRIPTOR_OFFSET_LENGTH]; + (*p_length) += p_desc[DESC_OFFSET_LEN]; p_desc = descriptor_next(p_desc); TU_ASSERT(pipehandle_is_valid(p_cdc->pipe_notification), TUSB_ERROR_HCD_OPEN_PIPE_FAILED); } //------------- Data Interface (if any) -------------// - if ( (TUSB_DESC_INTERFACE == p_desc[DESCRIPTOR_OFFSET_TYPE]) && + if ( (TUSB_DESC_INTERFACE == p_desc[DESC_OFFSET_TYPE]) && (TUSB_CLASS_CDC_DATA == ((tusb_desc_interface_t const *) p_desc)->bInterfaceClass) ) { - (*p_length) += p_desc[DESCRIPTOR_OFFSET_LENGTH]; + (*p_length) += p_desc[DESC_OFFSET_LEN]; p_desc = descriptor_next(p_desc); // data endpoints expected to be in pairs @@ -208,7 +208,7 @@ tusb_error_t cdch_open_subtask(uint8_t dev_addr, tusb_desc_interface_t const *p_ (*p_pipe_hdl) = hcd_pipe_open(dev_addr, p_endpoint, TUSB_CLASS_CDC); TU_ASSERT ( pipehandle_is_valid(*p_pipe_hdl), TUSB_ERROR_HCD_OPEN_PIPE_FAILED ); - (*p_length) += p_desc[DESCRIPTOR_OFFSET_LENGTH]; + (*p_length) += p_desc[DESC_OFFSET_LEN]; p_desc = descriptor_next( p_desc ); } } diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index bc2ee8c64..9f22697a6 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -259,12 +259,12 @@ tusb_error_t hidd_open(uint8_t rhport, tusb_desc_interface_t const * p_interface uint8_t const *p_desc = (uint8_t const *) p_interface_desc; //------------- HID descriptor -------------// - p_desc += p_desc[DESCRIPTOR_OFFSET_LENGTH]; + p_desc += p_desc[DESC_OFFSET_LEN]; tusb_hid_descriptor_hid_t const *p_desc_hid = (tusb_hid_descriptor_hid_t const *) p_desc; TU_ASSERT(HID_DESC_TYPE_HID == p_desc_hid->bDescriptorType, TUSB_ERROR_HIDD_DESCRIPTOR_INTERFACE); //------------- Endpoint Descriptor -------------// - p_desc += p_desc[DESCRIPTOR_OFFSET_LENGTH]; + p_desc += p_desc[DESC_OFFSET_LEN]; tusb_desc_endpoint_t const *p_desc_endpoint = (tusb_desc_endpoint_t const *) p_desc; TU_ASSERT(TUSB_DESC_ENDPOINT == p_desc_endpoint->bDescriptorType, TUSB_ERROR_HIDD_DESCRIPTOR_INTERFACE); diff --git a/src/class/hid/hid_host.c b/src/class/hid/hid_host.c index 69f86ee0b..fe0b7748b 100644 --- a/src/class/hid/hid_host.c +++ b/src/class/hid/hid_host.c @@ -186,12 +186,12 @@ tusb_error_t hidh_open_subtask(uint8_t dev_addr, tusb_desc_interface_t const *p_ uint8_t const *p_desc = (uint8_t const *) p_interface_desc; //------------- HID descriptor -------------// - p_desc += p_desc[DESCRIPTOR_OFFSET_LENGTH]; + p_desc += p_desc[DESC_OFFSET_LEN]; tusb_hid_descriptor_hid_t const *p_desc_hid = (tusb_hid_descriptor_hid_t const *) p_desc; TU_ASSERT(HID_DESC_TYPE_HID == p_desc_hid->bDescriptorType, TUSB_ERROR_INVALID_PARA); //------------- Endpoint Descriptor -------------// - p_desc += p_desc[DESCRIPTOR_OFFSET_LENGTH]; + p_desc += p_desc[DESC_OFFSET_LEN]; tusb_desc_endpoint_t const * p_endpoint_desc = (tusb_desc_endpoint_t const *) p_desc; TU_ASSERT(TUSB_DESC_ENDPOINT == p_endpoint_desc->bDescriptorType, TUSB_ERROR_INVALID_PARA); diff --git a/src/common/tusb_common.h b/src/common/tusb_common.h index 2b45a50c9..ddfceabdb 100644 --- a/src/common/tusb_common.h +++ b/src/common/tusb_common.h @@ -144,12 +144,17 @@ static inline uint8_t const * descriptor_next(uint8_t const p_desc[]) { - return p_desc + p_desc[DESCRIPTOR_OFFSET_LENGTH]; + return p_desc + p_desc[DESC_OFFSET_LEN]; } -static inline uint8_t descriptor_typeof(uint8_t const p_desc[]) +static inline uint8_t descriptor_type(uint8_t const p_desc[]) { - return p_desc[DESCRIPTOR_OFFSET_TYPE]; + return p_desc[DESC_OFFSET_TYPE]; +} + +static inline uint8_t descriptor_len(uint8_t const p_desc[]) +{ + return p_desc[DESC_OFFSET_LEN]; } //------------- Conversion -------------// diff --git a/src/common/tusb_types.h b/src/common/tusb_types.h index 4b8ef899c..65e7cd999 100644 --- a/src/common/tusb_types.h +++ b/src/common/tusb_types.h @@ -203,8 +203,8 @@ typedef enum }tusb_event_t; enum { - DESCRIPTOR_OFFSET_LENGTH = 0, - DESCRIPTOR_OFFSET_TYPE = 1 + DESC_OFFSET_LEN = 0, + DESC_OFFSET_TYPE = 1 }; enum { diff --git a/src/device/usbd.c b/src/device/usbd.c index 504cdf77b..d795e4f9a 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -66,7 +66,10 @@ typedef struct { uint8_t config_num; // map interface number to driver (0xff is invalid) - uint8_t itf2drv[16]; + uint8_t itf2drv[16]; + + // map endpoint to driver ( 0xff is invalid ) + uint8_t ep2drv[2][8]; }usbd_device_t; CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN uint8_t _usbd_ctrl_buf[CFG_TUD_CTRL_BUFSIZE]; @@ -100,18 +103,6 @@ static usbd_class_driver_t const usbd_class_drivers[] = }, #endif - #if DEVICE_CLASS_HID - { - .class_code = TUSB_CLASS_HID, - .init = hidd_init, - .open = hidd_open, - .control_req_st = hidd_control_request_st, - .xfer_cb = hidd_xfer_cb, - .sof = NULL, - .reset = hidd_reset - }, - #endif - #if CFG_TUD_MSC { .class_code = TUSB_CLASS_MSC, @@ -124,6 +115,19 @@ static usbd_class_driver_t const usbd_class_drivers[] = }, #endif + + #if DEVICE_CLASS_HID + { + .class_code = TUSB_CLASS_HID, + .init = hidd_init, + .open = hidd_open, + .control_req_st = hidd_control_request_st, + .xfer_cb = hidd_xfer_cb, + .sof = NULL, + .reset = hidd_reset + }, + #endif + #if CFG_TUD_CUSTOM_CLASS { .class_code = TUSB_CLASS_VENDOR_SPECIFIC, @@ -191,6 +195,7 @@ static osal_semaphore_def_t _usbd_sem_def; //--------------------------------------------------------------------+ // INTERNAL FUNCTION //--------------------------------------------------------------------+ +static void mark_interface_endpoint(uint8_t const* p_desc, uint16_t desc_len, uint8_t driver_id); static tusb_error_t proc_set_config_req(uint8_t rhport, uint8_t config_number); static uint16_t get_descriptor(uint8_t rhport, tusb_control_request_t const * const p_request, uint8_t const ** pp_buffer); @@ -300,6 +305,7 @@ static void usbd_reset(uint8_t rhport) { varclr_(&_usbd_dev); memset(_usbd_dev.itf2drv, 0xff, sizeof(_usbd_dev.itf2drv)); // invalid mapping + memset(_usbd_dev.ep2drv , 0xff, sizeof(_usbd_dev.ep2drv )); // invalid mapping for (uint8_t i = 0; i < USBD_CLASS_DRIVER_COUNT; i++) { @@ -395,6 +401,7 @@ static tusb_error_t proc_control_request_st(uint8_t rhport, tusb_control_request OSAL_SUBTASK_END } +// Process Set Configure Request // TODO Host (windows) can get HID report descriptor before set configured // may need to open interface before set configured static tusb_error_t proc_set_config_req(uint8_t rhport, uint8_t config_number) @@ -418,33 +425,35 @@ static tusb_error_t proc_set_config_req(uint8_t rhport, uint8_t config_number) while( p_desc < desc_cfg + cfg_len ) { - if ( TUSB_DESC_INTERFACE_ASSOCIATION == p_desc[DESCRIPTOR_OFFSET_TYPE]) + if ( TUSB_DESC_INTERFACE_ASSOCIATION == descriptor_type(p_desc) ) { - p_desc += p_desc[DESCRIPTOR_OFFSET_LENGTH]; // ignore Interface Association + p_desc = descriptor_next(p_desc); // ignore Interface Association }else { - TU_ASSERT( TUSB_DESC_INTERFACE == p_desc[DESCRIPTOR_OFFSET_TYPE], TUSB_ERROR_NOT_SUPPORTED_YET ); + TU_ASSERT( TUSB_DESC_INTERFACE == descriptor_type(p_desc), TUSB_ERROR_NOT_SUPPORTED_YET ); tusb_desc_interface_t* p_desc_itf = (tusb_desc_interface_t*) p_desc; uint8_t const class_code = p_desc_itf->bInterfaceClass; // Check if class is supported - uint8_t drid; - for (drid = 0; drid < USBD_CLASS_DRIVER_COUNT; drid++) + uint8_t drv_id; + for (drv_id = 0; drv_id < USBD_CLASS_DRIVER_COUNT; drv_id++) { - if ( usbd_class_drivers[drid].class_code == class_code ) break; + if ( usbd_class_drivers[drv_id].class_code == class_code ) break; } - TU_ASSERT( drid < USBD_CLASS_DRIVER_COUNT, TUSB_ERROR_NOT_SUPPORTED_YET ); + TU_ASSERT( drv_id < USBD_CLASS_DRIVER_COUNT, TUSB_ERROR_NOT_SUPPORTED_YET ); // Interface number must not be used TU_ASSERT( 0xff == _usbd_dev.itf2drv[p_desc_itf->bInterfaceNumber], TUSB_ERROR_FAILED); - _usbd_dev.itf2drv[p_desc_itf->bInterfaceNumber] = drid; + _usbd_dev.itf2drv[p_desc_itf->bInterfaceNumber] = drv_id; + + uint16_t len=0; + TU_ASSERT_ERR( usbd_class_drivers[drv_id].open( rhport, p_desc_itf, &len ) ); + TU_ASSERT( len >= sizeof(tusb_desc_interface_t), TUSB_ERROR_FAILED ); - uint16_t length=0; - TU_ASSERT_ERR( usbd_class_drivers[drid].open( rhport, p_desc_itf, &length ) ); + mark_interface_endpoint(p_desc, len, drv_id); - TU_ASSERT( length >= sizeof(tusb_desc_interface_t), TUSB_ERROR_FAILED ); - p_desc += length; + p_desc += len; // next interface } } @@ -454,6 +463,7 @@ static tusb_error_t proc_set_config_req(uint8_t rhport, uint8_t config_number) return TUSB_ERROR_NONE; } +// return len of descriptor and change pointer to descriptor's buffer static uint16_t get_descriptor(uint8_t rhport, tusb_control_request_t const * const p_request, uint8_t const ** pp_buffer) { (void) rhport; @@ -514,6 +524,25 @@ static uint16_t get_descriptor(uint8_t rhport, tusb_control_request_t const * co return len; } +// Helper marking endpoint of interface belongs to class driver +static void mark_interface_endpoint(uint8_t const* p_desc, uint16_t desc_len, uint8_t driver_id) +{ + uint16_t len = 0; + + while( len < desc_len ) + { + if ( TUSB_DESC_ENDPOINT == descriptor_type(p_desc) ) + { + uint8_t const ep_addr = ((tusb_desc_endpoint_t const*) p_desc)->bEndpointAddress; + + _usbd_dev.ep2drv[ edpt_dir(ep_addr) ][ edpt_number(ep_addr) ] = driver_id; + } + + len += descriptor_len(p_desc); + p_desc = descriptor_next(p_desc); + } +} + //--------------------------------------------------------------------+ // USBD-DCD Callback API //--------------------------------------------------------------------+ diff --git a/src/host/usbh.c b/src/host/usbh.c index a67bd8d8c..6d1cd37ad 100644 --- a/src/host/usbh.c +++ b/src/host/usbh.c @@ -572,9 +572,9 @@ tusb_error_t enumeration_body_subtask(void) while( p_desc < enum_data_buffer + ((tusb_desc_configuration_t*)enum_data_buffer)->wTotalLength ) { // skip until we see interface descriptor - if ( TUSB_DESC_INTERFACE != p_desc[DESCRIPTOR_OFFSET_TYPE] ) + if ( TUSB_DESC_INTERFACE != p_desc[DESC_OFFSET_TYPE] ) { - p_desc += p_desc[DESCRIPTOR_OFFSET_LENGTH]; // skip the descriptor, increase by the descriptor's length + p_desc += p_desc[DESC_OFFSET_LEN]; // skip the descriptor, increase by the descriptor's length }else { static uint8_t class_index; // has to be static as it is used to call class's open_subtask @@ -600,11 +600,11 @@ tusb_error_t enumeration_body_subtask(void) p_desc += length; }else // Interface open failed, for example a subclass is not supported { - p_desc += p_desc[DESCRIPTOR_OFFSET_LENGTH]; // skip this interface, the rest will be skipped by the above loop + p_desc += p_desc[DESC_OFFSET_LEN]; // skip this interface, the rest will be skipped by the above loop } } else // unsupported class (not enable or yet implemented) { - p_desc += p_desc[DESCRIPTOR_OFFSET_LENGTH]; // skip this interface, the rest will be skipped by the above loop + p_desc += p_desc[DESC_OFFSET_LEN]; // skip this interface, the rest will be skipped by the above loop } } } -- cgit v1.3.1 From 7a1f40593f984d37d602cdf6457d0f8c6f7c01d7 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 13 Jul 2018 18:01:16 +0700 Subject: only call class xfer callback associated with endpoint address --- src/class/cdc/cdc_device.c | 3 +++ src/class/msc/msc_device.c | 2 -- src/device/usbd.c | 13 ++++++------- 3 files changed, 9 insertions(+), 9 deletions(-) (limited to 'src/class') diff --git a/src/class/cdc/cdc_device.c b/src/class/cdc/cdc_device.c index 76526d40b..f8aa6824c 100644 --- a/src/class/cdc/cdc_device.c +++ b/src/class/cdc/cdc_device.c @@ -297,6 +297,7 @@ tusb_error_t cdcd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u uint8_t const itf = 0; cdcd_interface_t const * p_cdc = &_cdcd_itf[itf]; + // receive new data if ( ep_addr == p_cdc->ep_out ) { tu_fifo_write_n(&_rx_ff[itf], _tmp_rx_buf, xferred_bytes); @@ -308,6 +309,8 @@ tusb_error_t cdcd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u if (tud_cdc_rx_cb) tud_cdc_rx_cb(itf); } + // nothing to do with in and notif endpoint + return TUSB_ERROR_NONE; } diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index 71987addf..5ad8aa929 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -208,8 +208,6 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u msc_cbw_t const * p_cbw = &p_msc->cbw; msc_csw_t * p_csw = &p_msc->csw; - VERIFY( (ep_addr == p_msc->ep_out) || (ep_addr == p_msc->ep_in), TUSB_ERROR_INVALID_PARA); - switch (p_msc->stage) { case MSC_STAGE_CMD: diff --git a/src/device/usbd.c b/src/device/usbd.c index d795e4f9a..e2ef5e7bb 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -269,14 +269,13 @@ static tusb_error_t usbd_main_st(void) } else if (USBD_EVT_XFER_DONE == event.event_id) { - // TODO only call respective interface callback - // Call class handling function. Those does not own the endpoint should check and return - for (uint8_t i = 0; i < USBD_CLASS_DRIVER_COUNT; i++) + // Invoke the class callback associated with the endpoint address + uint8_t const ep_addr = event.xfer_done.ep_addr; + uint8_t const drv_id = _usbd_dev.ep2drv[ edpt_dir(ep_addr) ][ edpt_number(ep_addr) ]; + + if (drv_id < USBD_CLASS_DRIVER_COUNT) { - if ( usbd_class_drivers[i].xfer_cb ) - { - usbd_class_drivers[i].xfer_cb( event.rhport, event.xfer_done.ep_addr, (tusb_event_t) event.xfer_done.result, event.xfer_done.xferred_byte); - } + usbd_class_drivers[drv_id].xfer_cb( event.rhport, ep_addr, (tusb_event_t) event.xfer_done.result, event.xfer_done.xferred_byte); } } else if (USBD_EVT_SOF == event.event_id) -- cgit v1.3.1 From e0c4e11ea343e0189ccaa45591f42670962490fe Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 14 Jul 2018 15:12:42 +0700 Subject: use _usbd_ctrl_buf for control transferm refactor cdc device --- src/class/cdc/cdc_device.c | 90 +++++++++++++++++++++++----------------------- src/class/cdc/cdc_device.h | 6 ++-- src/class/msc/msc_device.c | 5 +-- src/device/usbd.c | 6 ++-- src/device/usbd_pvt.h | 31 +++++++--------- 5 files changed, 68 insertions(+), 70 deletions(-) (limited to 'src/class') diff --git a/src/class/cdc/cdc_device.c b/src/class/cdc/cdc_device.c index f8aa6824c..d0c76d00f 100644 --- a/src/class/cdc/cdc_device.c +++ b/src/class/cdc/cdc_device.c @@ -53,9 +53,7 @@ //--------------------------------------------------------------------+ typedef struct { - /*------------- usbd_itf_t compatible -------------*/ uint8_t itf_num; - uint8_t ep_count; uint8_t ep_notif; uint8_t ep_in; uint8_t ep_out; @@ -63,7 +61,19 @@ typedef struct // Bit 0: DTR (Data Terminal Ready), Bit 1: RTS (Request to Send) uint8_t line_state; - CFG_TUSB_MEM_ALIGN cdc_line_coding_t line_coding; + // Data that is not cleared by usb bus reset + struct { + cdc_line_coding_t line_coding; + + char wanted_char; + + uint8_t rx_ff_buf[CFG_TUD_CDC_RX_BUFSIZE]; + uint8_t tx_ff_buf[CFG_TUD_CDC_RX_BUFSIZE]; + + tu_fifo_t rx_ff; + tu_fifo_t tx_ff; + }intact; + }cdcd_interface_t; //--------------------------------------------------------------------+ @@ -72,13 +82,6 @@ typedef struct CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN static uint8_t _tmp_rx_buf[64]; CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN static uint8_t _tmp_tx_buf[64]; -uint8_t _rx_ff_buf[CFG_TUD_CDC][CFG_TUD_CDC_RX_BUFSIZE]; -uint8_t _tx_ff_buf[CFG_TUD_CDC][CFG_TUD_CDC_RX_BUFSIZE]; - -tu_fifo_t _rx_ff[CFG_TUD_CDC]; -tu_fifo_t _tx_ff[CFG_TUD_CDC]; - -CFG_TUSB_ATTR_USBRAM static cdcd_interface_t _cdcd_itf[CFG_TUD_CDC]; //--------------------------------------------------------------------+ @@ -97,7 +100,12 @@ uint8_t tud_cdc_n_get_line_state (uint8_t itf) void tud_cdc_n_get_line_coding (uint8_t itf, cdc_line_coding_t* coding) { - (*coding) = _cdcd_itf[itf].line_coding; + (*coding) = _cdcd_itf[itf].intact.line_coding; +} + +void tud_cdc_n_set_wanted_char (uint8_t itf, char wanted) +{ + } @@ -106,18 +114,18 @@ void tud_cdc_n_get_line_coding (uint8_t itf, cdc_line_coding_t* coding) //--------------------------------------------------------------------+ uint32_t tud_cdc_n_available(uint8_t itf) { - return tu_fifo_count(&_rx_ff[itf]); + return tu_fifo_count(&_cdcd_itf[itf].intact.rx_ff); } -int8_t tud_cdc_n_read_char(uint8_t itf) +char tud_cdc_n_read_char(uint8_t itf) { - int8_t ch; - return tu_fifo_read(&_rx_ff[itf], &ch) ? ch : (-1); + char ch; + return tu_fifo_read(&_cdcd_itf[itf].intact.rx_ff, &ch) ? ch : (-1); } uint32_t tud_cdc_n_read(uint8_t itf, void* buffer, uint32_t bufsize) { - return tu_fifo_read_n(&_rx_ff[itf], buffer, bufsize); + return tu_fifo_read_n(&_cdcd_itf[itf].intact.rx_ff, buffer, bufsize); } //--------------------------------------------------------------------+ @@ -126,12 +134,12 @@ uint32_t tud_cdc_n_read(uint8_t itf, void* buffer, uint32_t bufsize) uint32_t tud_cdc_n_write_char(uint8_t itf, char ch) { - return tu_fifo_write(&_tx_ff[itf], &ch) ? 1 : 0; + return tu_fifo_write(&_cdcd_itf[itf].intact.tx_ff, &ch) ? 1 : 0; } uint32_t tud_cdc_n_write(uint8_t itf, void const* buffer, uint32_t bufsize) { - return tu_fifo_write_n(&_tx_ff[itf], buffer, bufsize); + return tu_fifo_write_n(&_cdcd_itf[itf].intact.tx_ff, buffer, bufsize); } bool tud_cdc_n_flush (uint8_t itf) @@ -139,7 +147,7 @@ bool tud_cdc_n_flush (uint8_t itf) uint8_t edpt = _cdcd_itf[itf].ep_in; VERIFY( !dcd_edpt_busy(TUD_RHPORT, edpt) ); // skip if previous transfer not complete - uint16_t count = tu_fifo_read_n(&_tx_ff[itf], _tmp_tx_buf, sizeof(_tmp_tx_buf)); + uint16_t count = tu_fifo_read_n(&_cdcd_itf[itf].intact.tx_ff, _tmp_tx_buf, sizeof(_tmp_tx_buf)); VERIFY( tud_cdc_n_connected(itf) ); // fifo is empty if not connected @@ -154,12 +162,24 @@ bool tud_cdc_n_flush (uint8_t itf) //--------------------------------------------------------------------+ void cdcd_init(void) { - arrclr_(_cdcd_itf); + arrclr_( _cdcd_itf ); + + for(uint8_t i=0; iitf_num = p_interface_desc->bInterfaceNumber; - p_cdc->ep_count = p_interface_desc->bNumEndpoints; uint8_t const * p_desc = descriptor_next ( (uint8_t const *) p_interface_desc ); (*p_length) = sizeof(tusb_desc_interface_t); @@ -212,9 +231,6 @@ tusb_error_t cdcd_open(uint8_t rhport, tusb_desc_interface_t const * p_interface if ( (TUSB_DESC_INTERFACE == p_desc[DESC_OFFSET_TYPE]) && (TUSB_CLASS_CDC_DATA == ((tusb_desc_interface_t const *) p_desc)->bInterfaceClass) ) { - // p_cdc->itf_num = - p_cdc->ep_count += ((tusb_desc_interface_t const *) p_desc)->bNumEndpoints; - // next to endpoint descritpor (*p_length) += p_desc[DESC_OFFSET_LEN]; p_desc = descriptor_next(p_desc); @@ -232,20 +248,6 @@ tusb_error_t cdcd_open(uint8_t rhport, tusb_desc_interface_t const * p_interface return TUSB_ERROR_NONE; } -void cdcd_reset(uint8_t rhport) -{ - // no need to close opened pipe, dcd bus reset will put controller's endpoints to default state - (void) rhport; - - arrclr_(_cdcd_itf); - - for(uint8_t i=0; ibRequest) || (CDC_REQUEST_SET_LINE_CODING == p_request->bRequest) ) { uint16_t len = min16_of(sizeof(cdc_line_coding_t), p_request->wLength); - usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, &p_cdc->line_coding, len); + usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, &p_cdc->intact.line_coding, len); // Invoke callback if (CDC_REQUEST_SET_LINE_CODING == p_request->bRequest) { - if ( tud_cdc_line_coding_cb ) tud_cdc_line_coding_cb(itf, &p_cdc->line_coding); + if ( tud_cdc_line_coding_cb ) tud_cdc_line_coding_cb(itf, &p_cdc->intact.line_coding); } } else if (CDC_REQUEST_SET_CONTROL_LINE_STATE == p_request->bRequest ) @@ -300,7 +302,7 @@ tusb_error_t cdcd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u // receive new data if ( ep_addr == p_cdc->ep_out ) { - tu_fifo_write_n(&_rx_ff[itf], _tmp_rx_buf, xferred_bytes); + tu_fifo_write_n(&_cdcd_itf[itf].intact.rx_ff, _tmp_rx_buf, xferred_bytes); // preparing for next TU_ASSERT( dcd_edpt_xfer(rhport, p_cdc->ep_out, _tmp_rx_buf, sizeof(_tmp_rx_buf)), TUSB_ERROR_DCD_EDPT_XFER ); diff --git a/src/class/cdc/cdc_device.h b/src/class/cdc/cdc_device.h index bdce0f86e..2ff822240 100644 --- a/src/class/cdc/cdc_device.h +++ b/src/class/cdc/cdc_device.h @@ -59,9 +59,10 @@ bool tud_cdc_n_connected (uint8_t itf); uint8_t tud_cdc_n_get_line_state (uint8_t itf); void tud_cdc_n_get_line_coding (uint8_t itf, cdc_line_coding_t* coding); +void tud_cdc_n_set_wanted_char (uint8_t itf, char wanted); uint32_t tud_cdc_n_available (uint8_t itf); -int8_t tud_cdc_n_read_char (uint8_t itf); +char tud_cdc_n_read_char (uint8_t itf); uint32_t tud_cdc_n_read (uint8_t itf, void* buffer, uint32_t bufsize); uint32_t tud_cdc_n_write_char (uint8_t itf, char ch); @@ -74,9 +75,10 @@ bool tud_cdc_n_flush (uint8_t itf); static inline bool tud_cdc_connected (void) { return tud_cdc_n_connected(0); } static inline uint8_t tud_cdc_get_line_state (void) { return tud_cdc_n_get_line_state(0); } static inline void tud_cdc_get_line_coding (cdc_line_coding_t* coding) { return tud_cdc_n_get_line_coding(0, coding);} +static inline void tud_cdc_set_wanted_char (char wanted) { tud_cdc_n_set_wanted_char(0, wanted); } static inline uint32_t tud_cdc_available (void) { return tud_cdc_n_available(0); } -static inline int8_t tud_cdc_read_char (void) { return tud_cdc_n_read_char(0); } +static inline char tud_cdc_read_char (void) { return tud_cdc_n_read_char(0); } static inline uint32_t tud_cdc_read (void* buffer, uint32_t bufsize) { return tud_cdc_n_read(0, buffer, bufsize); } static inline uint32_t tud_cdc_write_char (char ch) { return tud_cdc_n_write_char(0, ch); } diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index 5ad8aa929..d82958202 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -44,6 +44,7 @@ // INCLUDE //--------------------------------------------------------------------+ #define _TINY_USB_SOURCE_FILE_ + #include "common/tusb_common.h" #include "msc_device.h" #include "device/usbd_pvt.h" @@ -192,8 +193,8 @@ tusb_error_t mscd_control_request_st(uint8_t rhport, tusb_control_request_t cons else if (MSC_REQUEST_GET_MAX_LUN == p_request->bRequest) { // returned MAX LUN is minus 1 by specs - _mscd_buf[0] = CFG_TUD_MSC_MAXLUN-1; - usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, _mscd_buf, 1); + uint8_t lun = CFG_TUD_MSC_MAXLUN-1; + usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, &lun, 1); }else { dcd_control_stall(rhport); // stall unsupported request diff --git a/src/device/usbd.c b/src/device/usbd.c index e2ef5e7bb..0eac22c15 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -334,8 +334,7 @@ static tusb_error_t proc_control_request_st(uint8_t rhport, tusb_control_request if ( len ) { STASK_ASSERT( len <= CFG_TUD_CTRL_BUFSIZE ); - memcpy(_usbd_ctrl_buf, buffer, len); - usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, _usbd_ctrl_buf, len ); + usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, buffer, len ); }else { dcd_control_stall(rhport); // stall unsupported descriptor @@ -343,8 +342,7 @@ static tusb_error_t proc_control_request_st(uint8_t rhport, tusb_control_request } else if (TUSB_REQ_GET_CONFIGURATION == p_request->bRequest ) { - memcpy(_usbd_ctrl_buf, &_usbd_dev.config_num, 1); - usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, _usbd_ctrl_buf, 1); + usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, &_usbd_dev.config_num, 1); } else if ( TUSB_REQ_SET_ADDRESS == p_request->bRequest ) { diff --git a/src/device/usbd_pvt.h b/src/device/usbd_pvt.h index 452df5934..f30cb943e 100644 --- a/src/device/usbd_pvt.h +++ b/src/device/usbd_pvt.h @@ -44,14 +44,7 @@ // for used by usbd_control_xfer_st() only, must not be used directly extern osal_semaphore_t _usbd_ctrl_sem; - - -typedef struct -{ - uint8_t itf_num; - uint8_t ep_count; - uint8_t ep_arr[1]; -}usbd_itf_t; +extern uint8_t _usbd_ctrl_buf[CFG_TUD_CTRL_BUFSIZE]; //--------------------------------------------------------------------+ // INTERNAL API for stack management @@ -67,16 +60,18 @@ tusb_error_t usbd_open_edpt_pair(uint8_t rhport, tusb_desc_endpoint_t const* p_d // Carry out Data and Status stage of control transfer // Must be call in a subtask (_st) function -#define usbd_control_xfer_st(_rhport, _dir, _buffer, _len) \ - do {\ - if (_len) { \ - tusb_error_t err;\ - dcd_control_xfer(_rhport, _dir, (uint8_t*) _buffer, _len);\ - osal_semaphore_wait( _usbd_ctrl_sem, OSAL_TIMEOUT_CONTROL_XFER, &err );\ - STASK_ASSERT_ERR( err );\ - }\ - /* No need to wait for status to complete therefore */ \ - dcd_control_status(_rhport, _dir);\ +#define usbd_control_xfer_st(_rhport, _dir, _buffer, _len) \ + do { \ + if (_len) { \ + tusb_error_t err; \ + if ( _dir ) memcpy(_usbd_ctrl_buf, _buffer, _len); \ + dcd_control_xfer(_rhport, _dir, _usbd_ctrl_buf, _len); \ + osal_semaphore_wait( _usbd_ctrl_sem, OSAL_TIMEOUT_CONTROL_XFER, &err ); \ + STASK_ASSERT_ERR( err ); \ + if (!_dir) memcpy((uint8_t*) _buffer, _usbd_ctrl_buf, _len); \ + } \ + dcd_control_status(_rhport, _dir); \ + /* No need to wait for status phase to complete */ \ }while(0) -- cgit v1.3.1 From 19b6bbfd14778c5a1fd13d2c0665dfbaa49c9425 Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 14 Jul 2018 23:28:07 +0700 Subject: add device cdc wanted char callback, cdc peek --- src/class/cdc/cdc_device.c | 53 +++++++++++++++++++++++++++++++++++----------- src/class/cdc/cdc_device.h | 3 +++ src/common/tusb_fifo.c | 10 ++++----- src/common/tusb_fifo.h | 2 +- 4 files changed, 50 insertions(+), 18 deletions(-) (limited to 'src/class') diff --git a/src/class/cdc/cdc_device.c b/src/class/cdc/cdc_device.c index d0c76d00f..04402c5bb 100644 --- a/src/class/cdc/cdc_device.c +++ b/src/class/cdc/cdc_device.c @@ -79,8 +79,10 @@ typedef struct //--------------------------------------------------------------------+ // INTERNAL OBJECT & FUNCTION DECLARATION //--------------------------------------------------------------------+ -CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN static uint8_t _tmp_rx_buf[64]; -CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN static uint8_t _tmp_tx_buf[64]; + +// TODO multiple interfaces +CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN static uint8_t _rx_buf[64]; +CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN static uint8_t _tx_buf[64]; static cdcd_interface_t _cdcd_itf[CFG_TUD_CDC]; @@ -105,7 +107,7 @@ void tud_cdc_n_get_line_coding (uint8_t itf, cdc_line_coding_t* coding) void tud_cdc_n_set_wanted_char (uint8_t itf, char wanted) { - + _cdcd_itf[itf].intact.wanted_char = wanted; } @@ -128,6 +130,12 @@ uint32_t tud_cdc_n_read(uint8_t itf, void* buffer, uint32_t bufsize) return tu_fifo_read_n(&_cdcd_itf[itf].intact.rx_ff, buffer, bufsize); } +char tud_cdc_n_peek(uint8_t itf, int pos) +{ + char ch; + return tu_fifo_peek_at(&_cdcd_itf[itf].intact.rx_ff, pos, &ch) ? ch : (-1); +} + //--------------------------------------------------------------------+ // WRITE API //--------------------------------------------------------------------+ @@ -147,11 +155,11 @@ bool tud_cdc_n_flush (uint8_t itf) uint8_t edpt = _cdcd_itf[itf].ep_in; VERIFY( !dcd_edpt_busy(TUD_RHPORT, edpt) ); // skip if previous transfer not complete - uint16_t count = tu_fifo_read_n(&_cdcd_itf[itf].intact.tx_ff, _tmp_tx_buf, sizeof(_tmp_tx_buf)); + uint16_t count = tu_fifo_read_n(&_cdcd_itf[itf].intact.tx_ff, _tx_buf, sizeof(_tx_buf)); VERIFY( tud_cdc_n_connected(itf) ); // fifo is empty if not connected - if ( count ) TU_ASSERT( dcd_edpt_xfer(TUD_RHPORT, edpt, _tmp_tx_buf, count) ); + if ( count ) TU_ASSERT( dcd_edpt_xfer(TUD_RHPORT, edpt, _tx_buf, count) ); return true; } @@ -166,6 +174,15 @@ void cdcd_init(void) for(uint8_t i=0; iep_out, _tmp_rx_buf, sizeof(_tmp_rx_buf)), TUSB_ERROR_DCD_EDPT_XFER); + TU_ASSERT( dcd_edpt_xfer(rhport, p_cdc->ep_out, _rx_buf, sizeof(_rx_buf)), TUSB_ERROR_DCD_EDPT_XFER); return TUSB_ERROR_NONE; } @@ -297,18 +314,30 @@ tusb_error_t cdcd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u { // TODO Support multiple interfaces uint8_t const itf = 0; - cdcd_interface_t const * p_cdc = &_cdcd_itf[itf]; + cdcd_interface_t* p_cdc = &_cdcd_itf[itf]; // receive new data if ( ep_addr == p_cdc->ep_out ) { - tu_fifo_write_n(&_cdcd_itf[itf].intact.rx_ff, _tmp_rx_buf, xferred_bytes); + char const wanted = p_cdc->intact.wanted_char; + + for(uint32_t i=0; iintact.rx_ff, &_rx_buf[i]); + } + } - // preparing for next - TU_ASSERT( dcd_edpt_xfer(rhport, p_cdc->ep_out, _tmp_rx_buf, sizeof(_tmp_rx_buf)), TUSB_ERROR_DCD_EDPT_XFER ); + // invoke receive callback (if there is still data) + if (tud_cdc_rx_cb && tu_fifo_count(&p_cdc->intact.rx_ff) ) tud_cdc_rx_cb(itf); - // fire callback - if (tud_cdc_rx_cb) tud_cdc_rx_cb(itf); + // prepare for next + TU_ASSERT( dcd_edpt_xfer(rhport, p_cdc->ep_out, _rx_buf, sizeof(_rx_buf)), TUSB_ERROR_DCD_EDPT_XFER ); } // nothing to do with in and notif endpoint diff --git a/src/class/cdc/cdc_device.h b/src/class/cdc/cdc_device.h index 2ff822240..c815a42b6 100644 --- a/src/class/cdc/cdc_device.h +++ b/src/class/cdc/cdc_device.h @@ -64,6 +64,7 @@ void tud_cdc_n_set_wanted_char (uint8_t itf, char wanted); uint32_t tud_cdc_n_available (uint8_t itf); char tud_cdc_n_read_char (uint8_t itf); uint32_t tud_cdc_n_read (uint8_t itf, void* buffer, uint32_t bufsize); +char tud_cdc_n_peek (uint8_t itf, int pos); uint32_t tud_cdc_n_write_char (uint8_t itf, char ch); uint32_t tud_cdc_n_write (uint8_t itf, void const* buffer, uint32_t bufsize); @@ -80,6 +81,7 @@ static inline void tud_cdc_set_wanted_char (char wanted) static inline uint32_t tud_cdc_available (void) { return tud_cdc_n_available(0); } static inline char tud_cdc_read_char (void) { return tud_cdc_n_read_char(0); } static inline uint32_t tud_cdc_read (void* buffer, uint32_t bufsize) { return tud_cdc_n_read(0, buffer, bufsize); } +static inline char tud_cdc_peek (int pos) { return tud_cdc_n_peek(0, pos); } static inline uint32_t tud_cdc_write_char (char ch) { return tud_cdc_n_write_char(0, ch); } static inline uint32_t tud_cdc_write (void const* buffer, uint32_t bufsize) { return tud_cdc_n_write(0, buffer, bufsize); } @@ -89,6 +91,7 @@ static inline bool tud_cdc_flush (void) // APPLICATION CALLBACK API (WEAK is optional) //--------------------------------------------------------------------+ ATTR_WEAK void tud_cdc_rx_cb(uint8_t itf); +ATTR_WEAK void tud_cdc_rx_wanted_cb(uint8_t itf, char wanted_char); ATTR_WEAK void tud_cdc_line_state_cb(uint8_t itf, bool dtr, bool rts); ATTR_WEAK void tud_cdc_line_coding_cb(uint8_t itf, cdc_line_coding_t const* p_line_coding); diff --git a/src/common/tusb_fifo.c b/src/common/tusb_fifo.c index 03c0b63ab..09763bee0 100644 --- a/src/common/tusb_fifo.c +++ b/src/common/tusb_fifo.c @@ -166,7 +166,7 @@ uint16_t tu_fifo_read_n (tu_fifo_t* f, void * p_buffer, uint16_t count) @param[in] f Pointer to the FIFO buffer to manipulate - @param[in] position + @param[in] pos Position to read from in the FIFO buffer @param[in] p_buffer Pointer to the place holder for data read from the buffer @@ -174,13 +174,13 @@ uint16_t tu_fifo_read_n (tu_fifo_t* f, void * p_buffer, uint16_t count) @returns TRUE if the queue is not empty */ /******************************************************************************/ -bool tu_fifo_peek_at(tu_fifo_t* f, uint16_t position, void * p_buffer) +bool tu_fifo_peek_at(tu_fifo_t* f, uint16_t pos, void * p_buffer) { if ( !tu_fifo_initalized(f) ) return false; - if ( position >= f->count ) return false; + if ( pos >= f->count ) return false; - // rd_idx is position=0 - uint16_t index = (f->rd_idx + position) % f->depth; + // rd_idx is pos=0 + uint16_t index = (f->rd_idx + pos) % f->depth; memcpy(p_buffer, f->buffer + (index * f->item_size), f->item_size); diff --git a/src/common/tusb_fifo.h b/src/common/tusb_fifo.h index d87b32395..1ddf3bd94 100644 --- a/src/common/tusb_fifo.h +++ b/src/common/tusb_fifo.h @@ -123,7 +123,7 @@ uint16_t tu_fifo_write_n (tu_fifo_t* f, void const * p_data, uint16_t count); bool tu_fifo_read (tu_fifo_t* f, void * p_buffer); uint16_t tu_fifo_read_n (tu_fifo_t* f, void * p_buffer, uint16_t count); -bool tu_fifo_peek_at (tu_fifo_t* f, uint16_t position, void * p_buffer); +bool tu_fifo_peek_at (tu_fifo_t* f, uint16_t pos, void * p_buffer); static inline bool tu_fifo_peek(tu_fifo_t* f, void * p_buffer) { -- cgit v1.3.1 From abb37e98baa16ae9f99f9d7562e4ee166e8bc4de Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 14 Jul 2018 23:43:19 +0700 Subject: rename tud_cdc_flush() to tud_cdc_write_flush(), add tud_cdc_read_flush() --- examples/device/device_virtual_com/src/tusb_config.h | 2 +- examples/device/nrf52840/src/main.c | 2 +- examples/device/nrf52840/src/tusb_config.h | 2 +- examples/obsolete/device/src/tusb_config.h | 2 +- src/class/cdc/cdc_device.c | 7 ++++++- src/class/cdc/cdc_device.h | 5 +++-- src/common/tusb_verify.h | 1 + 7 files changed, 14 insertions(+), 7 deletions(-) (limited to 'src/class') diff --git a/examples/device/device_virtual_com/src/tusb_config.h b/examples/device/device_virtual_com/src/tusb_config.h index a69d2ecbb..511b81b78 100644 --- a/examples/device/device_virtual_com/src/tusb_config.h +++ b/examples/device/device_virtual_com/src/tusb_config.h @@ -90,7 +90,7 @@ // TX is sent automatically every Start of Frame event. -// If not enabled, application must call tud_cdc_flush() periodically +// If not enabled, application must call tud_cdc_write_flush() periodically #define CFG_TUD_CDC_FLUSH_ON_SOF 1 //--------------------------------------------------------------------+ diff --git a/examples/device/nrf52840/src/main.c b/examples/device/nrf52840/src/main.c index e6a6388bf..ec574738e 100644 --- a/examples/device/nrf52840/src/main.c +++ b/examples/device/nrf52840/src/main.c @@ -87,7 +87,7 @@ void virtual_com_task(void) uint32_t count = tud_cdc_read(buf, sizeof(buf)); tud_cdc_write(buf, count); - tud_cdc_flush(); + tud_cdc_write_flush(); } } diff --git a/examples/device/nrf52840/src/tusb_config.h b/examples/device/nrf52840/src/tusb_config.h index 258a5983d..62c788413 100644 --- a/examples/device/nrf52840/src/tusb_config.h +++ b/examples/device/nrf52840/src/tusb_config.h @@ -86,7 +86,7 @@ #define CFG_TUD_CDC_TX_BUFSIZE 64 // TX is sent automatically every Start of Frame event. -// If not enabled, application must call tud_cdc_flush() periodically +// If not enabled, application must call tud_cdc_write_flush() periodically #define CFG_TUD_CDC_FLUSH_ON_SOF 0 /*------------------------------------------------------------------*/ diff --git a/examples/obsolete/device/src/tusb_config.h b/examples/obsolete/device/src/tusb_config.h index 16003dd6d..8c8d32514 100644 --- a/examples/obsolete/device/src/tusb_config.h +++ b/examples/obsolete/device/src/tusb_config.h @@ -88,7 +88,7 @@ // TX is sent automatically in Start of Frame event. -// If not enabled, application must call tud_cdc_flush() periodically +// If not enabled, application must call tud_cdc_write_flush() periodically #define CFG_TUD_CDC_FLUSH_ON_SOF 1 diff --git a/src/class/cdc/cdc_device.c b/src/class/cdc/cdc_device.c index 04402c5bb..bcef47136 100644 --- a/src/class/cdc/cdc_device.c +++ b/src/class/cdc/cdc_device.c @@ -136,6 +136,11 @@ char tud_cdc_n_peek(uint8_t itf, int pos) return tu_fifo_peek_at(&_cdcd_itf[itf].intact.rx_ff, pos, &ch) ? ch : (-1); } +void tud_cdc_n_read_flush (uint8_t itf) +{ + tu_fifo_clear(&_cdcd_itf[itf].intact.rx_ff); +} + //--------------------------------------------------------------------+ // WRITE API //--------------------------------------------------------------------+ @@ -150,7 +155,7 @@ uint32_t tud_cdc_n_write(uint8_t itf, void const* buffer, uint32_t bufsize) return tu_fifo_write_n(&_cdcd_itf[itf].intact.tx_ff, buffer, bufsize); } -bool tud_cdc_n_flush (uint8_t itf) +bool tud_cdc_n_write_flush (uint8_t itf) { uint8_t edpt = _cdcd_itf[itf].ep_in; VERIFY( !dcd_edpt_busy(TUD_RHPORT, edpt) ); // skip if previous transfer not complete diff --git a/src/class/cdc/cdc_device.h b/src/class/cdc/cdc_device.h index c815a42b6..0a1b2ca8f 100644 --- a/src/class/cdc/cdc_device.h +++ b/src/class/cdc/cdc_device.h @@ -64,11 +64,12 @@ void tud_cdc_n_set_wanted_char (uint8_t itf, char wanted); uint32_t tud_cdc_n_available (uint8_t itf); char tud_cdc_n_read_char (uint8_t itf); uint32_t tud_cdc_n_read (uint8_t itf, void* buffer, uint32_t bufsize); +void tud_cdc_n_read_flush (uint8_t itf); char tud_cdc_n_peek (uint8_t itf, int pos); uint32_t tud_cdc_n_write_char (uint8_t itf, char ch); uint32_t tud_cdc_n_write (uint8_t itf, void const* buffer, uint32_t bufsize); -bool tud_cdc_n_flush (uint8_t itf); +bool tud_cdc_n_write_flush (uint8_t itf); //--------------------------------------------------------------------+ // APPLICATION API (Interface0) @@ -85,7 +86,7 @@ static inline char tud_cdc_peek (int pos) static inline uint32_t tud_cdc_write_char (char ch) { return tud_cdc_n_write_char(0, ch); } static inline uint32_t tud_cdc_write (void const* buffer, uint32_t bufsize) { return tud_cdc_n_write(0, buffer, bufsize); } -static inline bool tud_cdc_flush (void) { return tud_cdc_n_flush(0); } +static inline bool tud_cdc_write_flush (void) { return tud_cdc_n_write_flush(0); } //--------------------------------------------------------------------+ // APPLICATION CALLBACK API (WEAK is optional) diff --git a/src/common/tusb_verify.h b/src/common/tusb_verify.h index 0e1f3b934..95816a0e7 100644 --- a/src/common/tusb_verify.h +++ b/src/common/tusb_verify.h @@ -61,6 +61,7 @@ // VERIFY Helper //--------------------------------------------------------------------+ #if CFG_TUSB_DEBUG >= 1 + #include #define _MESS_ERR(_err) printf("%s: %d: failed, error = %s\n", __func__, __LINE__, tusb_strerr[_err]) #define _MESS_FAILED() printf("%s: %d: failed\n", __func__, __LINE__) #else -- cgit v1.3.1 From 798ce59ebd46118c7d64e9cfa54319787715ef7d Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 17 Jul 2018 16:04:55 +0700 Subject: revert usbd_control_xfer_st() implementation enhance cdc with better multiple interfaces support add default ep size for cdc and msc device CFG_TUD_CDC_EPSIZE, CFG_TUD_MSC_EPSIZE --- src/class/cdc/cdc_device.c | 91 +++++++++++++++++++++++----------------------- src/class/cdc/cdc_device.h | 8 ++++ src/class/msc/msc_device.c | 39 +------------------- src/class/msc/msc_device.h | 47 +++++++++++++++++++++--- src/device/usbd.c | 6 ++- src/device/usbd_desc.c | 10 ++--- src/device/usbd_pvt.h | 2 - 7 files changed, 105 insertions(+), 98 deletions(-) (limited to 'src/class') diff --git a/src/class/cdc/cdc_device.c b/src/class/cdc/cdc_device.c index bcef47136..6d5ad4e85 100644 --- a/src/class/cdc/cdc_device.c +++ b/src/class/cdc/cdc_device.c @@ -61,30 +61,29 @@ typedef struct // Bit 0: DTR (Data Terminal Ready), Bit 1: RTS (Request to Send) uint8_t line_state; - // Data that is not cleared by usb bus reset - struct { - cdc_line_coding_t line_coding; + /*------------- From this point, data is not cleared by bus reset -------------*/ + cdc_line_coding_t line_coding; + char wanted_char; - char wanted_char; + // FIFO + tu_fifo_t rx_ff; + tu_fifo_t tx_ff; - uint8_t rx_ff_buf[CFG_TUD_CDC_RX_BUFSIZE]; - uint8_t tx_ff_buf[CFG_TUD_CDC_RX_BUFSIZE]; + uint8_t rx_ff_buf[CFG_TUD_CDC_RX_BUFSIZE]; + uint8_t tx_ff_buf[CFG_TUD_CDC_RX_BUFSIZE]; - tu_fifo_t rx_ff; - tu_fifo_t tx_ff; - }intact; + // Endpoint Transfer buffer + CFG_TUSB_MEM_ALIGN uint8_t epin_buf[CFG_TUD_CDC_EPSIZE]; + CFG_TUSB_MEM_ALIGN uint8_t epout_buf[CFG_TUD_CDC_EPSIZE]; }cdcd_interface_t; +#define ITF_BUS_RESET_SZ offsetof(cdcd_interface_t, line_coding) + //--------------------------------------------------------------------+ // INTERNAL OBJECT & FUNCTION DECLARATION //--------------------------------------------------------------------+ - -// TODO multiple interfaces -CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN static uint8_t _rx_buf[64]; -CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN static uint8_t _tx_buf[64]; - -static cdcd_interface_t _cdcd_itf[CFG_TUD_CDC]; +CFG_TUSB_ATTR_USBRAM static cdcd_interface_t _cdcd_itf[CFG_TUD_CDC]; //--------------------------------------------------------------------+ // APPLICATION API @@ -102,12 +101,12 @@ uint8_t tud_cdc_n_get_line_state (uint8_t itf) void tud_cdc_n_get_line_coding (uint8_t itf, cdc_line_coding_t* coding) { - (*coding) = _cdcd_itf[itf].intact.line_coding; + (*coding) = _cdcd_itf[itf].line_coding; } void tud_cdc_n_set_wanted_char (uint8_t itf, char wanted) { - _cdcd_itf[itf].intact.wanted_char = wanted; + _cdcd_itf[itf].wanted_char = wanted; } @@ -116,29 +115,29 @@ void tud_cdc_n_set_wanted_char (uint8_t itf, char wanted) //--------------------------------------------------------------------+ uint32_t tud_cdc_n_available(uint8_t itf) { - return tu_fifo_count(&_cdcd_itf[itf].intact.rx_ff); + return tu_fifo_count(&_cdcd_itf[itf].rx_ff); } char tud_cdc_n_read_char(uint8_t itf) { char ch; - return tu_fifo_read(&_cdcd_itf[itf].intact.rx_ff, &ch) ? ch : (-1); + return tu_fifo_read(&_cdcd_itf[itf].rx_ff, &ch) ? ch : (-1); } uint32_t tud_cdc_n_read(uint8_t itf, void* buffer, uint32_t bufsize) { - return tu_fifo_read_n(&_cdcd_itf[itf].intact.rx_ff, buffer, bufsize); + return tu_fifo_read_n(&_cdcd_itf[itf].rx_ff, buffer, bufsize); } char tud_cdc_n_peek(uint8_t itf, int pos) { char ch; - return tu_fifo_peek_at(&_cdcd_itf[itf].intact.rx_ff, pos, &ch) ? ch : (-1); + return tu_fifo_peek_at(&_cdcd_itf[itf].rx_ff, pos, &ch) ? ch : (-1); } void tud_cdc_n_read_flush (uint8_t itf) { - tu_fifo_clear(&_cdcd_itf[itf].intact.rx_ff); + tu_fifo_clear(&_cdcd_itf[itf].rx_ff); } //--------------------------------------------------------------------+ @@ -147,24 +146,24 @@ void tud_cdc_n_read_flush (uint8_t itf) uint32_t tud_cdc_n_write_char(uint8_t itf, char ch) { - return tu_fifo_write(&_cdcd_itf[itf].intact.tx_ff, &ch) ? 1 : 0; + return tu_fifo_write(&_cdcd_itf[itf].tx_ff, &ch) ? 1 : 0; } uint32_t tud_cdc_n_write(uint8_t itf, void const* buffer, uint32_t bufsize) { - return tu_fifo_write_n(&_cdcd_itf[itf].intact.tx_ff, buffer, bufsize); + return tu_fifo_write_n(&_cdcd_itf[itf].tx_ff, buffer, bufsize); } bool tud_cdc_n_write_flush (uint8_t itf) { - uint8_t edpt = _cdcd_itf[itf].ep_in; - VERIFY( !dcd_edpt_busy(TUD_RHPORT, edpt) ); // skip if previous transfer not complete + cdcd_interface_t* p_cdc = &_cdcd_itf[itf]; + VERIFY( !dcd_edpt_busy(TUD_RHPORT, p_cdc->ep_in) ); // skip if previous transfer not complete - uint16_t count = tu_fifo_read_n(&_cdcd_itf[itf].intact.tx_ff, _tx_buf, sizeof(_tx_buf)); + uint16_t count = tu_fifo_read_n(&_cdcd_itf[itf].tx_ff, p_cdc->epout_buf, CFG_TUD_CDC_EPSIZE); VERIFY( tud_cdc_n_connected(itf) ); // fifo is empty if not connected - if ( count ) TU_ASSERT( dcd_edpt_xfer(TUD_RHPORT, edpt, _tx_buf, count) ); + if ( count ) TU_ASSERT( dcd_edpt_xfer(TUD_RHPORT, p_cdc->ep_in, p_cdc->epout_buf, count) ); return true; } @@ -179,17 +178,17 @@ void cdcd_init(void) for(uint8_t i=0; iep_out, _rx_buf, sizeof(_rx_buf)), TUSB_ERROR_DCD_EDPT_XFER); + TU_ASSERT( dcd_edpt_xfer(rhport, p_cdc->ep_out, p_cdc->epin_buf, CFG_TUD_CDC_EPSIZE), TUSB_ERROR_DCD_EDPT_XFER); return TUSB_ERROR_NONE; } @@ -284,12 +283,12 @@ tusb_error_t cdcd_control_request_st(uint8_t rhport, tusb_control_request_t cons if ( (CDC_REQUEST_GET_LINE_CODING == p_request->bRequest) || (CDC_REQUEST_SET_LINE_CODING == p_request->bRequest) ) { uint16_t len = min16_of(sizeof(cdc_line_coding_t), p_request->wLength); - usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, &p_cdc->intact.line_coding, len); + usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, &p_cdc->line_coding, len); // Invoke callback if (CDC_REQUEST_SET_LINE_CODING == p_request->bRequest) { - if ( tud_cdc_line_coding_cb ) tud_cdc_line_coding_cb(itf, &p_cdc->intact.line_coding); + if ( tud_cdc_line_coding_cb ) tud_cdc_line_coding_cb(itf, &p_cdc->line_coding); } } else if (CDC_REQUEST_SET_CONTROL_LINE_STATE == p_request->bRequest ) @@ -324,25 +323,25 @@ tusb_error_t cdcd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u // receive new data if ( ep_addr == p_cdc->ep_out ) { - char const wanted = p_cdc->intact.wanted_char; + char const wanted = p_cdc->wanted_char; for(uint32_t i=0; iepin_buf[i] ) ) { tud_cdc_rx_wanted_cb(itf, wanted); }else { - tu_fifo_write(&p_cdc->intact.rx_ff, &_rx_buf[i]); + tu_fifo_write(&p_cdc->rx_ff, &p_cdc->epin_buf[i]); } } // invoke receive callback (if there is still data) - if (tud_cdc_rx_cb && tu_fifo_count(&p_cdc->intact.rx_ff) ) tud_cdc_rx_cb(itf); + if (tud_cdc_rx_cb && tu_fifo_count(&p_cdc->rx_ff) ) tud_cdc_rx_cb(itf); // prepare for next - TU_ASSERT( dcd_edpt_xfer(rhport, p_cdc->ep_out, _rx_buf, sizeof(_rx_buf)), TUSB_ERROR_DCD_EDPT_XFER ); + TU_ASSERT( dcd_edpt_xfer(rhport, p_cdc->ep_out, p_cdc->epin_buf, CFG_TUD_CDC_EPSIZE), TUSB_ERROR_DCD_EDPT_XFER ); } // nothing to do with in and notif endpoint diff --git a/src/class/cdc/cdc_device.h b/src/class/cdc/cdc_device.h index 0a1b2ca8f..046878680 100644 --- a/src/class/cdc/cdc_device.h +++ b/src/class/cdc/cdc_device.h @@ -43,6 +43,14 @@ #include "device/usbd.h" #include "cdc.h" +//--------------------------------------------------------------------+ +// Class Driver Configuration +//--------------------------------------------------------------------+ +#ifndef CFG_TUD_CDC_EPSIZE +#define CFG_TUD_CDC_EPSIZE 64 +#endif + + #ifdef __cplusplus extern "C" { #endif diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index d82958202..b0839ecb0 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -49,41 +49,6 @@ #include "msc_device.h" #include "device/usbd_pvt.h" -//--------------------------------------------------------------------+ -// Config Verification -//--------------------------------------------------------------------+ -VERIFY_STATIC(CFG_TUD_MSC_BUFSIZE < UINT16_MAX, "Size is not correct"); - -#ifndef CFG_TUD_MSC_MAXLUN - #define CFG_TUD_MSC_MAXLUN 1 -#elif CFG_TUD_MSC_MAXLUN == 0 || CFG_TUD_MSC_MAXLUN > 16 - #error MSC Device: Incorrect setting of MAX LUN -#endif - -#ifndef CFG_TUD_MSC_BLOCK_NUM - #error CFG_TUD_MSC_BLOCK_NUM must be defined -#endif - -#ifndef CFG_TUD_MSC_BLOCK_SZ - #error CFG_TUD_MSC_BLOCK_SZ must be defined -#endif - -#ifndef CFG_TUD_MSC_BUFSIZE - #error CFG_TUD_MSC_BUFSIZE must be defined, value of CFG_TUD_MSC_BLOCK_SZ should work well, the more the better -#endif - -#ifndef CFG_TUD_MSC_VENDOR - #error CFG_TUD_MSC_VENDOR 8-byte name must be defined -#endif - -#ifndef CFG_TUD_MSC_PRODUCT - #error CFG_TUD_MSC_PRODUCT 16-byte name must be defined -#endif - -#ifndef CFG_TUD_MSC_PRODUCT_REV - #error CFG_TUD_MSC_PRODUCT_REV 4-byte string must be defined -#endif - //--------------------------------------------------------------------+ // MACRO CONSTANT TYPEDEF //--------------------------------------------------------------------+ @@ -193,8 +158,8 @@ tusb_error_t mscd_control_request_st(uint8_t rhport, tusb_control_request_t cons else if (MSC_REQUEST_GET_MAX_LUN == p_request->bRequest) { // returned MAX LUN is minus 1 by specs - uint8_t lun = CFG_TUD_MSC_MAXLUN-1; - usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, &lun, 1); + _usbd_ctrl_buf[0] = CFG_TUD_MSC_MAXLUN-1; + usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, _usbd_ctrl_buf, 1); }else { dcd_control_stall(rhport); // stall unsupported request diff --git a/src/class/msc/msc_device.h b/src/class/msc/msc_device.h index 994e71c36..a32d64a93 100644 --- a/src/class/msc/msc_device.h +++ b/src/class/msc/msc_device.h @@ -43,6 +43,48 @@ #include "device/usbd.h" #include "msc.h" + +//--------------------------------------------------------------------+ +// Class Driver Configuration +//--------------------------------------------------------------------+ +VERIFY_STATIC(CFG_TUD_MSC_BUFSIZE < UINT16_MAX, "Size is not correct"); + +#ifndef CFG_TUD_MSC_MAXLUN + #define CFG_TUD_MSC_MAXLUN 1 +#elif CFG_TUD_MSC_MAXLUN == 0 || CFG_TUD_MSC_MAXLUN > 16 + #error MSC Device: Incorrect setting of MAX LUN +#endif + +#ifndef CFG_TUD_MSC_BLOCK_NUM + #error CFG_TUD_MSC_BLOCK_NUM must be defined +#endif + +#ifndef CFG_TUD_MSC_BLOCK_SZ + #error CFG_TUD_MSC_BLOCK_SZ must be defined +#endif + +#ifndef CFG_TUD_MSC_BUFSIZE + #error CFG_TUD_MSC_BUFSIZE must be defined, value of CFG_TUD_MSC_BLOCK_SZ should work well, the more the better +#endif + +#ifndef CFG_TUD_MSC_VENDOR + #error CFG_TUD_MSC_VENDOR 8-byte name must be defined +#endif + +#ifndef CFG_TUD_MSC_PRODUCT + #error CFG_TUD_MSC_PRODUCT 16-byte name must be defined +#endif + +#ifndef CFG_TUD_MSC_PRODUCT_REV + #error CFG_TUD_MSC_PRODUCT_REV 4-byte string must be defined +#endif + +// TODO highspeed device is 512 +#ifndef CFG_TUD_MSC_EPSIZE +#define CFG_TUD_MSC_EPSIZE 64 +#endif + + #ifdef __cplusplus extern "C" { #endif @@ -52,11 +94,6 @@ * \defgroup MSC_Device Device * @{ */ -//--------------------------------------------------------------------+ -// APPLICATION API (Multiple Root Hub Ports) -// Should be used only with MCU that support more than 1 ports -//--------------------------------------------------------------------+ - //--------------------------------------------------------------------+ // APPLICATION CALLBACK API (WEAK is optional) //--------------------------------------------------------------------+ diff --git a/src/device/usbd.c b/src/device/usbd.c index 0eac22c15..e8dfd83dd 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -334,7 +334,8 @@ static tusb_error_t proc_control_request_st(uint8_t rhport, tusb_control_request if ( len ) { STASK_ASSERT( len <= CFG_TUD_CTRL_BUFSIZE ); - usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, buffer, len ); + memcpy(_usbd_ctrl_buf, buffer, len); + usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, _usbd_ctrl_buf, len); }else { dcd_control_stall(rhport); // stall unsupported descriptor @@ -342,7 +343,8 @@ static tusb_error_t proc_control_request_st(uint8_t rhport, tusb_control_request } else if (TUSB_REQ_GET_CONFIGURATION == p_request->bRequest ) { - usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, &_usbd_dev.config_num, 1); + memcpy(_usbd_ctrl_buf, &_usbd_dev.config_num, 1); + usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, _usbd_ctrl_buf, 1); } else if ( TUSB_REQ_SET_ADDRESS == p_request->bRequest ) { diff --git a/src/device/usbd_desc.c b/src/device/usbd_desc.c index 99a77b22c..d672ddfaf 100644 --- a/src/device/usbd_desc.c +++ b/src/device/usbd_desc.c @@ -88,12 +88,10 @@ #define EP_CDC_OUT _EP_OUT(ITF_NUM_CDC+2) #define EP_CDC_IN _EP_IN (ITF_NUM_CDC+2) -#define EP_CDC_SIZE 64 // Mass Storage #define EP_MSC_OUT _EP_OUT(ITF_NUM_MSC+1) #define EP_MSC_IN _EP_IN (ITF_NUM_MSC+1) -#define EP_MSC_SIZE 64 // TODO usb highspeed is 512 #if 0 // HID Keyboard @@ -323,7 +321,7 @@ desc_auto_cfg_t const _desc_auto_config_struct = .bDescriptorType = TUSB_DESC_ENDPOINT, .bEndpointAddress = EP_CDC_OUT, .bmAttributes = { .xfer = TUSB_XFER_BULK }, - .wMaxPacketSize = { .size = EP_CDC_SIZE }, + .wMaxPacketSize = { .size = CFG_TUD_CDC_EPSIZE }, .bInterval = 0 }, @@ -333,7 +331,7 @@ desc_auto_cfg_t const _desc_auto_config_struct = .bDescriptorType = TUSB_DESC_ENDPOINT, .bEndpointAddress = EP_CDC_IN, .bmAttributes = { .xfer = TUSB_XFER_BULK }, - .wMaxPacketSize = { .size = EP_CDC_SIZE }, + .wMaxPacketSize = { .size = CFG_TUD_CDC_EPSIZE }, .bInterval = 0 }, }, @@ -361,7 +359,7 @@ desc_auto_cfg_t const _desc_auto_config_struct = .bDescriptorType = TUSB_DESC_ENDPOINT, .bEndpointAddress = EP_MSC_OUT, .bmAttributes = { .xfer = TUSB_XFER_BULK }, - .wMaxPacketSize = { .size = EP_MSC_SIZE}, + .wMaxPacketSize = { .size = CFG_TUD_MSC_EPSIZE}, .bInterval = 1 }, @@ -371,7 +369,7 @@ desc_auto_cfg_t const _desc_auto_config_struct = .bDescriptorType = TUSB_DESC_ENDPOINT, .bEndpointAddress = EP_MSC_IN, .bmAttributes = { .xfer = TUSB_XFER_BULK }, - .wMaxPacketSize = { .size = EP_MSC_SIZE}, + .wMaxPacketSize = { .size = CFG_TUD_MSC_EPSIZE}, .bInterval = 1 } }, diff --git a/src/device/usbd_pvt.h b/src/device/usbd_pvt.h index f30cb943e..343aade77 100644 --- a/src/device/usbd_pvt.h +++ b/src/device/usbd_pvt.h @@ -64,11 +64,9 @@ tusb_error_t usbd_open_edpt_pair(uint8_t rhport, tusb_desc_endpoint_t const* p_d do { \ if (_len) { \ tusb_error_t err; \ - if ( _dir ) memcpy(_usbd_ctrl_buf, _buffer, _len); \ dcd_control_xfer(_rhport, _dir, _usbd_ctrl_buf, _len); \ osal_semaphore_wait( _usbd_ctrl_sem, OSAL_TIMEOUT_CONTROL_XFER, &err ); \ STASK_ASSERT_ERR( err ); \ - if (!_dir) memcpy((uint8_t*) _buffer, _usbd_ctrl_buf, _len); \ } \ dcd_control_status(_rhport, _dir); \ /* No need to wait for status phase to complete */ \ -- cgit v1.3.1 From 6129670e4a23812d1926b15c191d76538f7a325a Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 17 Jul 2018 21:20:37 +0700 Subject: forgot to add tud_cdc_read_flush() --- src/class/cdc/cdc_device.h | 1 + 1 file changed, 1 insertion(+) (limited to 'src/class') diff --git a/src/class/cdc/cdc_device.h b/src/class/cdc/cdc_device.h index 046878680..4014f5fa9 100644 --- a/src/class/cdc/cdc_device.h +++ b/src/class/cdc/cdc_device.h @@ -90,6 +90,7 @@ static inline void tud_cdc_set_wanted_char (char wanted) static inline uint32_t tud_cdc_available (void) { return tud_cdc_n_available(0); } static inline char tud_cdc_read_char (void) { return tud_cdc_n_read_char(0); } static inline uint32_t tud_cdc_read (void* buffer, uint32_t bufsize) { return tud_cdc_n_read(0, buffer, bufsize); } +static inline void tud_cdc_read_flush (void) { tud_cdc_n_read_flush(0); } static inline char tud_cdc_peek (int pos) { return tud_cdc_n_peek(0, pos); } static inline uint32_t tud_cdc_write_char (char ch) { return tud_cdc_n_write_char(0, ch); } -- cgit v1.3.1 From 141ac25e3b3aaf72a50ace257d2bda41d1ebe702 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 20 Jul 2018 15:47:28 +0700 Subject: also added wanted char to fifo --- src/class/cdc/cdc_device.c | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) (limited to 'src/class') diff --git a/src/class/cdc/cdc_device.c b/src/class/cdc/cdc_device.c index 6d5ad4e85..8848ddca0 100644 --- a/src/class/cdc/cdc_device.c +++ b/src/class/cdc/cdc_device.c @@ -70,7 +70,7 @@ typedef struct tu_fifo_t tx_ff; uint8_t rx_ff_buf[CFG_TUD_CDC_RX_BUFSIZE]; - uint8_t tx_ff_buf[CFG_TUD_CDC_RX_BUFSIZE]; + uint8_t tx_ff_buf[CFG_TUD_CDC_TX_BUFSIZE]; // Endpoint Transfer buffer CFG_TUSB_MEM_ALIGN uint8_t epin_buf[CFG_TUD_CDC_EPSIZE]; @@ -327,13 +327,12 @@ tusb_error_t cdcd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u for(uint32_t i=0; irx_ff, &p_cdc->epin_buf[i]); + // Check for wanted char and invoke callback if needed if ( tud_cdc_rx_wanted_cb && ( wanted != -1 ) && ( wanted == p_cdc->epin_buf[i] ) ) { tud_cdc_rx_wanted_cb(itf, wanted); - }else - { - tu_fifo_write(&p_cdc->rx_ff, &p_cdc->epin_buf[i]); } } -- cgit v1.3.1 From 4342325ee1359d3361acca6de4f8accf013e8e39 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 23 Jul 2018 15:25:45 +0700 Subject: reworking device hid class driver --- .../device/device_virtual_com/src/tusb_config.h | 1 - examples/device/nrf52840/src/tusb_config.h | 66 +-- examples/device/nrf52840/src/tusb_descriptors.c | 12 +- examples/obsolete/device/src/keyboard_device_app.c | 14 +- examples/obsolete/device/src/mouse_device_app.c | 13 +- examples/obsolete/device/src/tusb_config.h | 5 +- hw/bsp/lpcxpresso1769/board_lpcxpresso1769.c | 2 +- src/class/cdc/cdc_device.c | 6 +- src/class/custom/custom_device.c | 2 +- src/class/hid/hid.h | 20 +- src/class/hid/hid_device.c | 328 ++++++++------- src/class/hid/hid_device.h | 61 +-- src/class/hid/hid_host.c | 2 +- src/class/msc/msc_device.c | 2 +- src/device/usbd.c | 4 +- src/device/usbd.h | 10 +- src/device/usbd_desc.c | 459 ++++++++++++--------- src/portable/nordic/nrf5x/dcd_nrf5x.c | 2 +- src/portable/nordic/nrf5x/hal_nrf5x.c | 2 +- .../nxp/lpc11xx_lpc13xx/dcd_lpc_11uxx_13uxx.c | 2 +- src/portable/nxp/lpc17xx/dcd_lpc175x_6x.c | 2 +- src/portable/nxp/lpc17xx/hal_lpc175x_6x.c | 4 +- src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c | 2 +- src/portable/nxp/lpc43xx_lpc18xx/hal_lpc43xx.c | 4 +- src/tusb.c | 4 +- src/tusb.h | 4 +- src/tusb_option.h | 30 +- tests/lpc175x_6x/test/test_usbd.c | 2 +- .../test/host/hid/test_hidh_keyboard.c | 4 +- tests/lpc18xx_43xx/test/host/hid/test_hidh_mouse.c | 2 +- tests/support/tusb_config.h | 5 +- 31 files changed, 579 insertions(+), 497 deletions(-) (limited to 'src/class') diff --git a/examples/device/device_virtual_com/src/tusb_config.h b/examples/device/device_virtual_com/src/tusb_config.h index 511b81b78..38930505b 100644 --- a/examples/device/device_virtual_com/src/tusb_config.h +++ b/examples/device/device_virtual_com/src/tusb_config.h @@ -77,7 +77,6 @@ #define CFG_TUD_MSC 0 #define CFG_TUD_HID_KEYBOARD 0 #define CFG_TUD_HID_MOUSE 0 -#define CFG_TUD_HID_GENERIC 0 // not supported yet /*------------------------------------------------------------------*/ diff --git a/examples/device/nrf52840/src/tusb_config.h b/examples/device/nrf52840/src/tusb_config.h index 62c788413..da7dc793b 100644 --- a/examples/device/nrf52840/src/tusb_config.h +++ b/examples/device/nrf52840/src/tusb_config.h @@ -43,61 +43,60 @@ extern "C" { #endif -//--------------------------------------------------------------------+ +//-------------------------------------------------------------------- // COMMON CONFIGURATION -//--------------------------------------------------------------------+ -#define CFG_TUSB_MCU OPT_MCU_NRF5X -#define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE +//-------------------------------------------------------------------- +#define CFG_TUSB_MCU OPT_MCU_NRF5X +#define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE -#define CFG_TUSB_DEBUG 2 +#define CFG_TUSB_DEBUG 2 /*------------- RTOS -------------*/ -#define CFG_TUSB_OS OPT_OS_NONE // be passed from IDE/command line for easy project switching +#define CFG_TUSB_OS OPT_OS_NONE // be passed from IDE/command line for easy project switching //#define CFG_TUD_TASK_PRIO 0 //#define CFG_TUD_TASK_QUEUE_SZ 16 //#define CFG_TUD_TASK_STACK_SZ 150 -//--------------------------------------------------------------------+ +//-------------------------------------------------------------------- // DEVICE CONFIGURATION -//--------------------------------------------------------------------+ +//-------------------------------------------------------------------- /*------------- Core -------------*/ -#define CFG_TUD_DESC_AUTO 1 +#define CFG_TUD_DESC_AUTO 1 // #define CFG_TUD_DESC_VID 0xCAFE // #define CFG_TUD_DESC_PID 0x0001 -#define CFG_TUD_ENDOINT0_SIZE 64 +#define CFG_TUD_ENDOINT0_SIZE 64 //------------- CLASS -------------// -#define CFG_TUD_CDC 1 -#define CFG_TUD_MSC 1 +#define CFG_TUD_CDC 1 +#define CFG_TUD_MSC 1 -#define CFG_TUD_HID_KEYBOARD 0 // TODO need update -#define CFG_TUD_HID_MOUSE 0 // TODO need update -#define CFG_TUD_HID_GENERIC 0 // TODO need update +#define CFG_TUD_HID_KEYBOARD 1 +#define CFG_TUD_HID_MOUSE 1 -/*------------------------------------------------------------------*/ -/* CDC DEVICE - *------------------------------------------------------------------*/ +//-------------------------------------------------------------------- +// CDC +//-------------------------------------------------------------------- // FIFO size of CDC TX and RX -#define CFG_TUD_CDC_RX_BUFSIZE 64 -#define CFG_TUD_CDC_TX_BUFSIZE 64 +#define CFG_TUD_CDC_RX_BUFSIZE 64 +#define CFG_TUD_CDC_TX_BUFSIZE 64 // TX is sent automatically every Start of Frame event. // If not enabled, application must call tud_cdc_write_flush() periodically #define CFG_TUD_CDC_FLUSH_ON_SOF 0 -/*------------------------------------------------------------------*/ -/* MSC DEVICE - *------------------------------------------------------------------*/ +//-------------------------------------------------------------------- +// MSC +//-------------------------------------------------------------------- // Number of supported Logical Unit Number (At least 1) -#define CFG_TUD_MSC_MAXLUN 1 +#define CFG_TUD_MSC_MAXLUN 1 // Buffer size of Device Mass storage -#define CFG_TUD_MSC_BUFSIZE 512 +#define CFG_TUD_MSC_BUFSIZE 512 // Number of Blocks #define CFG_TUD_MSC_BLOCK_NUM 16 @@ -114,9 +113,22 @@ // Product revision string included in Inquiry response, max 4 bytes #define CFG_TUD_MSC_PRODUCT_REV "1.0" -//--------------------------------------------------------------------+ +//-------------------------------------------------------------------- +// HID +//-------------------------------------------------------------------- + +/* Enable boot protocol will create separated HID interface for Keyboard, + * Consumer Key and Mouse --> require more In endpoints. Otherwise they + * are all packed into a single Multiple Report Interface. + * + * Note: If your device is meant to work with simple host running on + * an MCU (e.g with tinyusb host), boot protocol should be enabled. + */ +#define CFG_TUD_HID_BOOT_PROTOCOL 1 + +//-------------------------------------------------------------------- // USB RAM PLACEMENT -//--------------------------------------------------------------------+ +//-------------------------------------------------------------------- #define CFG_TUSB_ATTR_USBRAM #define CFG_TUSB_MEM_ALIGN ATTR_ALIGNED(4) diff --git a/examples/device/nrf52840/src/tusb_descriptors.c b/examples/device/nrf52840/src/tusb_descriptors.c index e5d73333d..c088fec7f 100644 --- a/examples/device/nrf52840/src/tusb_descriptors.c +++ b/examples/device/nrf52840/src/tusb_descriptors.c @@ -57,11 +57,15 @@ uint16_t const * const string_desc_arr [] = // 3: Serials TODO use chip ID TUD_DESC_STRCONV('1', '2', '3', '4', '5', '6'), +#if CFG_TUD_CDC // 4: CDC Interface TUD_DESC_STRCONV('t','u','s','b',' ','c','d','c'), +#endif +#if CFG_TUD_MSC // 5: MSC Interface TUD_DESC_STRCONV('t','u','s','b',' ','m','s','c'), +#endif }; // tud_desc_set is required by tinyusb stack @@ -71,5 +75,11 @@ tud_desc_set_t tud_desc_set = .device = NULL, .config = NULL, .string_arr = (uint8_t const **) string_desc_arr, - .hid_report = NULL + + .hid_report = + { + .composite = NULL, + .boot_keyboard = NULL, + .boot_mouse = NULL + } }; diff --git a/examples/obsolete/device/src/keyboard_device_app.c b/examples/obsolete/device/src/keyboard_device_app.c index df9172c68..4e4de8996 100644 --- a/examples/obsolete/device/src/keyboard_device_app.c +++ b/examples/obsolete/device/src/keyboard_device_app.c @@ -77,21 +77,21 @@ void tud_hid_keyboard_cb(uint8_t rhport, tusb_event_t event, uint32_t xferred_by } } -uint16_t tud_hid_keyboard_get_report_cb(uint8_t rhport, hid_request_report_type_t report_type, void** pp_report, uint16_t requested_length) +uint16_t tud_hid_keyboard_get_report_cb(hid_report_type_t report_type, uint8_t* buffer, uint16_t reqlen) { // get other than input report is not supported by this keyboard demo - if ( report_type != HID_REQUEST_REPORT_INPUT ) return 0; + if ( report_type != HID_REPORT_TYPE_INPUT ) return 0; - (*pp_report) = &keyboard_report; - return requested_length; + memcpy(buffer, &keyboard_report, reqlen); + return reqlen; } -void tud_hid_keyboard_set_report_cb(uint8_t rhport, hid_request_report_type_t report_type, uint8_t p_report_data[], uint16_t length) +void tud_hid_keyboard_set_report_cb(hid_report_type_t report_type, uint8_t* buffer, uint16_t reqlen) { // set other than output report is not supported by this keyboard demo - if ( report_type != HID_REQUEST_REPORT_OUTPUT ) return; + if ( report_type != HID_REPORT_TYPE_OUTPUT ) return; - uint8_t kbd_led = p_report_data[0]; + uint8_t kbd_led = buffer[0]; uint32_t interval_divider = 1; // each LED will reduce blinking interval by a half if (kbd_led & KEYBOARD_LED_NUMLOCK ) interval_divider *= 2; diff --git a/examples/obsolete/device/src/mouse_device_app.c b/examples/obsolete/device/src/mouse_device_app.c index 9bbb799df..d6145026a 100644 --- a/examples/obsolete/device/src/mouse_device_app.c +++ b/examples/obsolete/device/src/mouse_device_app.c @@ -77,17 +77,12 @@ void tud_hid_mouse_cb(uint8_t rhport, tusb_event_t event, uint32_t xferred_bytes } } -uint16_t tud_hid_mouse_get_report_cb(uint8_t rhport, hid_request_report_type_t report_type, void** pp_report, uint16_t requested_length) +uint16_t tud_hid_mouse_get_report_cb(hid_report_type_t report_type, uint8_t* buffer, uint16_t reqlen) { - if ( report_type != HID_REQUEST_REPORT_INPUT ) return 0; // not support other report type for this mouse demo + if ( report_type != HID_REPORT_TYPE_INPUT ) return 0; // not support other report type for this mouse demo - (*pp_report) = &mouse_report; - return requested_length; -} - -void tud_hid_mouse_set_report_cb(uint8_t rhport, hid_request_report_type_t report_type, uint8_t report_data[], uint16_t length) -{ - // mouse demo does not support set report --> do nothing + memcpy(buffer, &mouse_report, reqlen); + return reqlen; } //--------------------------------------------------------------------+ diff --git a/examples/obsolete/device/src/tusb_config.h b/examples/obsolete/device/src/tusb_config.h index 8c8d32514..fc6807aef 100644 --- a/examples/obsolete/device/src/tusb_config.h +++ b/examples/obsolete/device/src/tusb_config.h @@ -72,11 +72,10 @@ #define CFG_TUD_ENDOINT0_SIZE 64 //------------- CLASS -------------// -#define CFG_TUD_HID_KEYBOARD 0 -#define CFG_TUD_HID_MOUSE 0 -#define CFG_TUD_HID_GENERIC 0 // not supported yet #define CFG_TUD_MSC 1 #define CFG_TUD_CDC 1 +#define CFG_TUD_HID_KEYBOARD 0 +#define CFG_TUD_HID_MOUSE 0 /*------------------------------------------------------------------*/ /* CLASS DRIVER diff --git a/hw/bsp/lpcxpresso1769/board_lpcxpresso1769.c b/hw/bsp/lpcxpresso1769/board_lpcxpresso1769.c index 9fd6483a6..196199d61 100644 --- a/hw/bsp/lpcxpresso1769/board_lpcxpresso1769.c +++ b/hw/bsp/lpcxpresso1769/board_lpcxpresso1769.c @@ -77,7 +77,7 @@ void board_init(void) //------------- BUTTON -------------// for(uint8_t i=0; iep_in) ); // skip if previous transfer not complete + VERIFY( !dcd_edpt_busy(TUD_OPT_RHPORT, p_cdc->ep_in) ); // skip if previous transfer not complete uint16_t count = tu_fifo_read_n(&_cdcd_itf[itf].tx_ff, p_cdc->epout_buf, CFG_TUD_CDC_EPSIZE); VERIFY( tud_cdc_n_connected(itf) ); // fifo is empty if not connected - if ( count ) TU_ASSERT( dcd_edpt_xfer(TUD_RHPORT, p_cdc->ep_in, p_cdc->epout_buf, count) ); + if ( count ) TU_ASSERT( dcd_edpt_xfer(TUD_OPT_RHPORT, p_cdc->ep_in, p_cdc->epout_buf, count) ); return true; } diff --git a/src/class/custom/custom_device.c b/src/class/custom/custom_device.c index e4dc1a839..c895deb18 100644 --- a/src/class/custom/custom_device.c +++ b/src/class/custom/custom_device.c @@ -36,7 +36,7 @@ #include "tusb_option.h" -#if (MODE_DEVICE_SUPPORTED && CFG_TUD_CUSTOM_CLASS) +#if (TUSB_OPT_DEVICE_ENABLED && CFG_TUD_CUSTOM_CLASS) #define _TINY_USB_SOURCE_FILE_ diff --git a/src/class/hid/hid.h b/src/class/hid/hid.h index d53eb979d..a12a13800 100644 --- a/src/class/hid/hid.h +++ b/src/class/hid/hid.h @@ -81,20 +81,20 @@ typedef enum /// HID Request Report Type typedef enum { - HID_REQUEST_REPORT_INPUT = 1, ///< Input - HID_REQUEST_REPORT_OUTPUT, ///< Output - HID_REQUEST_REPORT_FEATURE ///< Feature -}hid_request_report_type_t; + HID_REPORT_TYPE_INPUT = 1, ///< Input + HID_REPORT_TYPE_OUTPUT, ///< Output + HID_REPORT_TYPE_FEATURE ///< Feature +}hid_report_type_t; /// HID Class Specific Control Request typedef enum { - HID_REQUEST_CONTROL_GET_REPORT = 0x01, ///< Get Report - HID_REQUEST_CONTROL_GET_IDLE = 0x02, ///< Get Idle - HID_REQUEST_CONTROL_GET_PROTOCOL = 0x03, ///< Get Protocol - HID_REQUEST_CONTROL_SET_REPORT = 0x09, ///< Set Report - HID_REQUEST_CONTROL_SET_IDLE = 0x0a, ///< Set Idle - HID_REQUEST_CONTROL_SET_PROTOCOL = 0x0b ///< Set Protocol + HID_REQ_CONTROL_GET_REPORT = 0x01, ///< Get Report + HID_REQ_CONTROL_GET_IDLE = 0x02, ///< Get Idle + HID_REQ_CONTROL_GET_PROTOCOL = 0x03, ///< Get Protocol + HID_REQ_CONTROL_SET_REPORT = 0x09, ///< Set Report + HID_REQ_CONTROL_SET_IDLE = 0x0a, ///< Set Idle + HID_REQ_CONTROL_SET_PROTOCOL = 0x0b ///< Set Protocol }hid_request_type_t; /// USB HID Descriptor diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index 9f22697a6..7b2c1da2d 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -38,7 +38,7 @@ #include "tusb_option.h" -#if (MODE_DEVICE_SUPPORTED && DEVICE_CLASS_HID) +#if (TUSB_OPT_DEVICE_ENABLED && TUD_OPT_HID_ENABLED) #define _TINY_USB_SOURCE_FILE_ //--------------------------------------------------------------------+ @@ -51,75 +51,53 @@ //--------------------------------------------------------------------+ // MACRO CONSTANT TYPEDEF //--------------------------------------------------------------------+ -enum { - HIDD_NUMBER_OF_SUBCLASS = 3, - HIDD_BUFFER_SIZE = 128 -}; + +// Max report len is keyboard's one with 8 byte + 1 byte report id +#define REPORT_BUFSIZE 9 typedef struct { - uint8_t const * p_report_desc; - uint16_t report_length; + uint8_t itf_num; + uint8_t ep_in; + uint8_t idle_rate; + + uint8_t report_id; + uint16_t report_len; + uint8_t const * report_desc; - uint8_t edpt_addr; - uint8_t interface_number; + // class specific control request + uint16_t (*get_report_cb) (hid_report_type_t type, uint8_t* buffer, uint16_t reqlen); + void (*set_report_cb) (hid_report_type_t type, uint8_t const* buffer, uint16_t bufsize); + + CFG_TUSB_MEM_ALIGN uint8_t report_buf[REPORT_BUFSIZE]; }hidd_interface_t; -typedef struct { - hidd_interface_t * const p_interface; - void (* const xfer_cb) (uint8_t, tusb_event_t, uint32_t); - uint16_t (* const get_report_cb) (uint8_t, hid_request_report_type_t, void**, uint16_t ); - void (* const set_report_cb) (uint8_t, hid_request_report_type_t, uint8_t[], uint16_t); -}hidd_class_driver_t; +#if CFG_TUD_HID_BOOT_PROTOCOL -extern ATTR_WEAK hidd_interface_t keyboardd_data; -extern ATTR_WEAK hidd_interface_t moused_data; +CFG_TUSB_ATTR_USBRAM static hidd_interface_t _kbd_itf; +CFG_TUSB_ATTR_USBRAM static hidd_interface_t _mse_itf; -static hidd_class_driver_t const hidd_class_driver[HIDD_NUMBER_OF_SUBCLASS] = -{ -// [HID_PROTOCOL_NONE] = for HID Generic +#else -#if CFG_TUD_HID_KEYBOARD - [HID_PROTOCOL_KEYBOARD] = - { - .p_interface = &keyboardd_data, - .xfer_cb = tud_hid_keyboard_cb, - .get_report_cb = tud_hid_keyboard_get_report_cb, - .set_report_cb = tud_hid_keyboard_set_report_cb - }, -#endif +CFG_TUSB_ATTR_USBRAM static hidd_interface_t _composite_itf; -#if CFG_TUD_HID_MOUSE - [HID_PROTOCOL_MOUSE] = - { - .p_interface = &moused_data, - .xfer_cb = tud_hid_mouse_cb, - .get_report_cb = tud_hid_mouse_get_report_cb, - .set_report_cb = tud_hid_mouse_set_report_cb - } #endif -}; - -// internal buffer for transferring data -CFG_TUSB_ATTR_USBRAM STATIC_VAR uint8_t m_hid_buffer[ HIDD_BUFFER_SIZE ]; //--------------------------------------------------------------------+ // KEYBOARD APPLICATION API //--------------------------------------------------------------------+ #if CFG_TUD_HID_KEYBOARD -STATIC_VAR hidd_interface_t keyboardd_data; - -bool tud_hid_keyboard_busy(uint8_t rhport) +bool tud_hid_keyboard_busy(void) { - return dcd_edpt_busy(rhport, keyboardd_data.edpt_addr); + return dcd_edpt_busy(TUD_OPT_RHPORT, _kbd_itf.ep_in); } -tusb_error_t tud_hid_keyboard_send(uint8_t rhport, hid_keyboard_report_t const *p_report) +tusb_error_t tud_hid_keyboard_send(hid_keyboard_report_t const *p_report) { VERIFY(tud_mounted(), TUSB_ERROR_USBD_DEVICE_NOT_CONFIGURED); - hidd_interface_t * p_kbd = &keyboardd_data; // TODO &keyboardd_data[rhport]; + hidd_interface_t * p_kbd = &_kbd_itf; - TU_ASSERT( dcd_edpt_xfer(rhport, p_kbd->edpt_addr, (void*) p_report, sizeof(hid_keyboard_report_t)), TUSB_ERROR_DCD_EDPT_XFER ) ; + TU_ASSERT( dcd_edpt_xfer(TUD_OPT_RHPORT, p_kbd->ep_in, (void*) p_report, sizeof(hid_keyboard_report_t)), TUSB_ERROR_DCD_EDPT_XFER ) ; return TUSB_ERROR_NONE; } @@ -129,66 +107,130 @@ tusb_error_t tud_hid_keyboard_send(uint8_t rhport, hid_keyboard_report_t const * // MOUSE APPLICATION API //--------------------------------------------------------------------+ #if CFG_TUD_HID_MOUSE -STATIC_VAR hidd_interface_t moused_data; - -bool tud_hid_mouse_is_busy(uint8_t rhport) +bool tud_hid_mouse_is_busy(void) { - return dcd_edpt_busy(rhport, moused_data.edpt_addr); + return dcd_edpt_busy(TUD_OPT_RHPORT, _mse_itf.ep_in); } -tusb_error_t tud_hid_mouse_send(uint8_t rhport, hid_mouse_report_t const *p_report) +tusb_error_t tud_hid_mouse_send(hid_mouse_report_t const *p_report) { VERIFY(tud_mounted(), TUSB_ERROR_USBD_DEVICE_NOT_CONFIGURED); - hidd_interface_t * p_mouse = &moused_data; // TODO &keyboardd_data[rhport]; + hidd_interface_t * p_mouse = &_mse_itf; - TU_ASSERT( dcd_edpt_xfer(rhport, p_mouse->edpt_addr, (void*) p_report, sizeof(hid_mouse_report_t)), TUSB_ERROR_DCD_EDPT_XFER ) ; + TU_ASSERT( dcd_edpt_xfer(TUD_OPT_RHPORT, p_mouse->ep_in, (void*) p_report, sizeof(hid_mouse_report_t)), TUSB_ERROR_DCD_EDPT_XFER ) ; return TUSB_ERROR_NONE; } #endif -//--------------------------------------------------------------------+ -// USBD-CLASS API -//--------------------------------------------------------------------+ -static void interface_clear(hidd_interface_t * p_interface) +static inline hidd_interface_t* get_interface_by_edpt(uint8_t ep_addr) { - if ( p_interface != NULL ) - { - memclr_(p_interface, sizeof(hidd_interface_t)); - p_interface->interface_number = INTERFACE_INVALID_NUMBER; - } + return ( ep_addr == _kbd_itf.ep_in ) ? &_kbd_itf : + ( ep_addr == _mse_itf.ep_in ) ? &_mse_itf : NULL; +} + +static inline hidd_interface_t* get_interface_by_number(uint8_t itf_num) +{ + return ( itf_num == _kbd_itf.itf_num ) ? &_kbd_itf : + ( itf_num == _mse_itf.itf_num ) ? &_mse_itf : NULL; } +//--------------------------------------------------------------------+ +// USBD-CLASS API +//--------------------------------------------------------------------+ void hidd_init(void) { - for(uint8_t i=0; ibDescriptorType, TUSB_ERROR_HIDD_DESCRIPTOR_INTERFACE); + + //------------- Endpoint Descriptor -------------// + p_desc += p_desc[DESC_OFFSET_LEN]; + tusb_desc_endpoint_t const *desc_edpt = (tusb_desc_endpoint_t const *) p_desc; + TU_ASSERT(TUSB_DESC_ENDPOINT == desc_edpt->bDescriptorType, TUSB_ERROR_HIDD_DESCRIPTOR_INTERFACE); + + if (desc_itf->bInterfaceSubClass == HID_SUBCLASS_BOOT) { - hidd_interface_t * const p_interface = hidd_class_driver[subclass_idx].p_interface; - if ( (p_interface != NULL) && (p_request->wIndex == p_interface->interface_number) ) break; +#if CFG_TUD_HID_BOOT_PROTOCOL + if ( (desc_itf->bInterfaceProtocol != HID_PROTOCOL_KEYBOARD) && (desc_itf->bInterfaceProtocol != HID_PROTOCOL_MOUSE) ) + { + // unknown, unsupported protocol + return TUSB_ERROR_HIDD_DESCRIPTOR_INTERFACE; + }else + { + hidd_interface_t * p_hid = NULL; + + #if CFG_TUD_HID_KEYBOARD + if (desc_itf->bInterfaceProtocol == HID_PROTOCOL_KEYBOARD) + { + p_hid = &_kbd_itf; + p_hid->report_desc = tud_desc_set.hid_report.boot_keyboard; + p_hid->get_report_cb = tud_hid_keyboard_get_report_cb; + p_hid->set_report_cb = tud_hid_keyboard_set_report_cb; + } + #endif + + #if CFG_TUD_HID_MOUSE + if (desc_itf->bInterfaceProtocol == HID_PROTOCOL_MOUSE) + { + p_hid = &_mse_itf; + p_hid->report_desc = tud_desc_set.hid_report.boot_mouse; + p_hid->get_report_cb = tud_hid_mouse_get_report_cb; + p_hid->set_report_cb = tud_hid_mouse_set_report_cb; + } + #endif + + TU_ASSERT(p_hid, TUSB_ERROR_HIDD_DESCRIPTOR_INTERFACE); + VERIFY(p_hid->report_desc, TUSB_ERROR_DESCRIPTOR_CORRUPTED); + + TU_ASSERT( dcd_edpt_open(rhport, desc_edpt), TUSB_ERROR_DCD_FAILED ); + + p_hid->report_len = desc_hid->wReportLength; + p_hid->itf_num = desc_itf->bInterfaceNumber; + p_hid->ep_in = desc_edpt->bEndpointAddress; + p_hid->report_id = 0; + + *p_length = sizeof(tusb_desc_interface_t) + sizeof(tusb_hid_descriptor_hid_t) + sizeof(tusb_desc_endpoint_t); + } +#else + return TUSB_ERROR_HIDD_DESCRIPTOR_INTERFACE; +#endif + } + else + { + // TODO HID generic + // TODO parse report ID for keyboard, mouse + *p_length = 0; + return TUSB_ERROR_HIDD_DESCRIPTOR_INTERFACE; } - TU_ASSERT(subclass_idx < HIDD_NUMBER_OF_SUBCLASS, TUSB_ERROR_FAILED); + return TUSB_ERROR_NONE; +} - hidd_class_driver_t const * const p_driver = &hidd_class_driver[subclass_idx]; - hidd_interface_t* const p_hid = p_driver->p_interface; +tusb_error_t hidd_control_request_st(uint8_t rhport, tusb_control_request_t const * p_request) +{ + hidd_interface_t* p_hid = get_interface_by_number( (uint8_t) p_request->wIndex ); + TU_ASSERT(p_hid, TUSB_ERROR_FAILED); OSAL_SUBTASK_BEGIN @@ -202,12 +244,12 @@ tusb_error_t hidd_control_request_st(uint8_t rhport, tusb_control_request_t cons if (p_request->bRequest == TUSB_REQ_GET_DESCRIPTOR && desc_type == HID_DESC_TYPE_REPORT) { - STASK_ASSERT ( p_hid->report_length <= HIDD_BUFFER_SIZE ); + STASK_ASSERT ( p_hid->report_len <= CFG_TUD_CTRL_BUFSIZE ); - // copy to allow report descriptor not to be in USBRAM - memcpy(m_hid_buffer, p_hid->p_report_desc, p_hid->report_length); + // use device control buffer (in USB SRAM) + memcpy(_usbd_ctrl_buf, p_hid->report_desc, p_hid->report_len); - usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, m_hid_buffer, p_hid->report_length); + usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, _usbd_ctrl_buf, p_hid->report_len); }else { dcd_control_stall(rhport); @@ -216,34 +258,59 @@ tusb_error_t hidd_control_request_st(uint8_t rhport, tusb_control_request_t cons //------------- Class Specific Request -------------// else if (p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS) { - if( (HID_REQUEST_CONTROL_GET_REPORT == p_request->bRequest) && (p_driver->get_report_cb != NULL) ) + if( HID_REQ_CONTROL_GET_REPORT == p_request->bRequest ) { // wValue = Report Type | Report ID - void* p_buffer = NULL; + uint8_t const report_type = u16_high_u8(p_request->wValue); + uint8_t const report_id = u16_low_u8(p_request->wValue); - uint16_t actual_length = p_driver->get_report_cb(rhport, (hid_request_report_type_t) u16_high_u8(p_request->wValue), - &p_buffer, p_request->wLength); - STASK_ASSERT( p_buffer != NULL && actual_length > 0 ); + // Composite interface need to determine it is Keyboard, Mouse or Gamepad + if ( report_id > 0 ) + { + + } + + uint16_t xferlen; + if ( p_hid->get_report_cb ) + { + xferlen = p_hid->get_report_cb((hid_report_type_t) report_type, p_hid->report_buf, p_request->wLength); + }else + { + xferlen = p_request->wLength; + // re-use report_buf -> report has no change + } - usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, p_buffer, actual_length); + STASK_ASSERT( xferlen > 0 ); + usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, p_hid->report_buf, xferlen); } - else if ( (HID_REQUEST_CONTROL_SET_REPORT == p_request->bRequest) && (p_driver->set_report_cb != NULL) ) + else if ( HID_REQ_CONTROL_SET_REPORT == p_request->bRequest ) { - // return TUSB_ERROR_DCD_CONTROL_REQUEST_NOT_SUPPORT; // TODO test STALL control out endpoint (with mouse+keyboard) // wValue = Report Type | Report ID - usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, m_hid_buffer, p_request->wLength); + usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, _usbd_ctrl_buf, p_request->wLength); - p_driver->set_report_cb(rhport, u16_high_u8(p_request->wValue), m_hid_buffer, p_request->wLength); + if ( p_hid->set_report_cb ) + { + p_hid->set_report_cb(u16_high_u8(p_request->wValue), _usbd_ctrl_buf, p_request->wLength); + } } - else if (HID_REQUEST_CONTROL_SET_IDLE == p_request->bRequest) + else if (HID_REQ_CONTROL_SET_IDLE == p_request->bRequest) { - // uint8_t idle_rate = u16_high_u8(p_request->wValue); + p_hid->idle_rate = u16_high_u8(p_request->wValue); dcd_control_status(rhport, p_request->bmRequestType_bit.direction); - }else + } + else if (HID_REQ_CONTROL_GET_IDLE == p_request->bRequest) { -// HID_REQUEST_CONTROL_GET_IDLE: -// HID_REQUEST_CONTROL_GET_PROTOCOL: -// HID_REQUEST_CONTROL_SET_PROTOCOL: + _usbd_ctrl_buf[0] = p_hid->idle_rate; + usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, _usbd_ctrl_buf, 1); + } + else if (HID_REQ_CONTROL_GET_PROTOCOL == p_request->bRequest ) + { + _usbd_ctrl_buf[0] = 1 - CFG_TUD_HID_BOOT_PROTOCOL; // 0 is Boot, 1 is Report protocol + usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, _usbd_ctrl_buf, 1); + } + else + { +// HID_REQ_CONTROL_SET_PROTOCOL: dcd_control_stall(rhport); } }else @@ -254,68 +321,9 @@ tusb_error_t hidd_control_request_st(uint8_t rhport, tusb_control_request_t cons OSAL_SUBTASK_END } -tusb_error_t hidd_open(uint8_t rhport, tusb_desc_interface_t const * p_interface_desc, uint16_t *p_length) -{ - uint8_t const *p_desc = (uint8_t const *) p_interface_desc; - - //------------- HID descriptor -------------// - p_desc += p_desc[DESC_OFFSET_LEN]; - tusb_hid_descriptor_hid_t const *p_desc_hid = (tusb_hid_descriptor_hid_t const *) p_desc; - TU_ASSERT(HID_DESC_TYPE_HID == p_desc_hid->bDescriptorType, TUSB_ERROR_HIDD_DESCRIPTOR_INTERFACE); - - //------------- Endpoint Descriptor -------------// - p_desc += p_desc[DESC_OFFSET_LEN]; - tusb_desc_endpoint_t const *p_desc_endpoint = (tusb_desc_endpoint_t const *) p_desc; - TU_ASSERT(TUSB_DESC_ENDPOINT == p_desc_endpoint->bDescriptorType, TUSB_ERROR_HIDD_DESCRIPTOR_INTERFACE); - - if (p_interface_desc->bInterfaceSubClass == HID_SUBCLASS_BOOT) - { - switch(p_interface_desc->bInterfaceProtocol) - { - case HID_PROTOCOL_KEYBOARD: - case HID_PROTOCOL_MOUSE: - { - hidd_class_driver_t const * const p_driver = &hidd_class_driver[p_interface_desc->bInterfaceProtocol]; - hidd_interface_t * const p_hid = p_driver->p_interface; - - VERIFY(p_hid, TUSB_ERROR_FAILED); - - VERIFY( dcd_edpt_open(rhport, p_desc_endpoint), TUSB_ERROR_DCD_FAILED ); - - p_hid->edpt_addr = p_desc_endpoint->bEndpointAddress; - - p_hid->interface_number = p_interface_desc->bInterfaceNumber; - p_hid->p_report_desc = (p_interface_desc->bInterfaceProtocol == HID_PROTOCOL_KEYBOARD) ? tusbd_descriptor_pointers.p_hid_keyboard_report : tusbd_descriptor_pointers.p_hid_mouse_report; - p_hid->report_length = p_desc_hid->wReportLength; - - VERIFY(p_hid->p_report_desc, TUSB_ERROR_DESCRIPTOR_CORRUPTED); - } - break; - - default: // TODO unknown, unsupported protocol --> skip this interface - return TUSB_ERROR_HIDD_DESCRIPTOR_INTERFACE; - } - *p_length = sizeof(tusb_desc_interface_t) + sizeof(tusb_hid_descriptor_hid_t) + sizeof(tusb_desc_endpoint_t); - }else - { - // open generic - *p_length = 0; - return TUSB_ERROR_HIDD_DESCRIPTOR_INTERFACE; - } - return TUSB_ERROR_NONE; -} - tusb_error_t hidd_xfer_cb(uint8_t rhport, uint8_t edpt_addr, tusb_event_t event, uint32_t xferred_bytes) { - for(uint8_t i=0; iedpt_addr) ) - { - hidd_class_driver[i].xfer_cb(rhport, event, xferred_bytes); - } - } - + // nothing to do return TUSB_ERROR_NONE; } diff --git a/src/class/hid/hid_device.h b/src/class/hid/hid_device.h index 855421eca..a2238473d 100644 --- a/src/class/hid/hid_device.h +++ b/src/class/hid/hid_device.h @@ -57,12 +57,11 @@ * @{ */ /** \brief Check if the interface is currently busy or not - * \param[in] rhport USB Controller ID * \retval true if the interface is busy meaning the stack is still transferring/waiting data from/to host * \retval false if the interface is not busy meaning the stack successfully transferred data from/to host * \note This function is primarily used for polling/waiting result after \ref tusbd_hid_keyboard_send. */ -bool tud_hid_keyboard_busy(uint8_t rhport); +bool tud_hid_keyboard_busy(void); /** \brief Submit USB transfer * \param[in] rhport USB Controller ID @@ -75,29 +74,17 @@ bool tud_hid_keyboard_busy(uint8_t rhport); * \note This function is non-blocking and returns immediately. Data will be transferred when USB Host work with this interface. * The result of usb transfer will be reported by the interface's callback function */ -tusb_error_t tud_hid_keyboard_send(uint8_t rhport, hid_keyboard_report_t const *p_report); +tusb_error_t tud_hid_keyboard_send(hid_keyboard_report_t const *p_report); //--------------------------------------------------------------------+ // APPLICATION CALLBACK API //--------------------------------------------------------------------+ -/** \brief Callback function that is invoked when an transferring event occurred - * after invoking \ref tusbd_hid_keyboard_send - * \param[in] rhport USB Controller ID - * \param[in] event an value from \ref tusb_event_t - * \note event can be one of following - * - TUSB_EVENT_XFER_COMPLETE : previously scheduled transfer completes successfully. - * - TUSB_EVENT_XFER_ERROR : previously scheduled transfer encountered a transaction error. - * - TUSB_EVENT_XFER_STALLED : previously scheduled transfer is stalled by device. - */ -void tud_hid_keyboard_cb(uint8_t rhport, tusb_event_t event, uint32_t xferred_bytes); - /** \brief Callback function that is invoked when USB host request \ref HID_REQUEST_CONTROL_GET_REPORT * via control endpoint. - * \param[in] rhport USB Controller ID * \param[in] report_type specify which report (INPUT, OUTPUT, FEATURE) that host requests - * \param[out] pp_report pointer to buffer that application need to update, value must be accessible by USB controller (see \ref CFG_TUSB_ATTR_USBRAM) - * \param[in] requested_length number of bytes that host requested + * \param[out] buffer data that application need to update, value must be accessible by USB controller (see \ref CFG_TUSB_ATTR_USBRAM) + * \param[in] reqlen number of bytes that host requested * \retval non-zero Actual number of bytes in the response's buffer. * \retval zero indicates the current request is not supported. Tinyusb device stack will reject the request by * sending STALL in the data phase. @@ -105,18 +92,17 @@ void tud_hid_keyboard_cb(uint8_t rhport, tusb_event_t event, uint32_t xferred_by * the completion of this control request will not be reported to application. * For Keyboard, USB host often uses this to turn on/off the LED for CAPLOCKS, NUMLOCK (\ref hid_keyboard_led_bm_t) */ -uint16_t tud_hid_keyboard_get_report_cb(uint8_t rhport, hid_request_report_type_t report_type, void** pp_report, uint16_t requested_length); +ATTR_WEAK uint16_t tud_hid_keyboard_get_report_cb(hid_report_type_t report_type, uint8_t* buffer, uint16_t reqlen); /** \brief Callback function that is invoked when USB host request \ref HID_REQUEST_CONTROL_SET_REPORT * via control endpoint. - * \param[in] rhport USB Controller ID * \param[in] report_type specify which report (INPUT, OUTPUT, FEATURE) that host requests - * \param[in] p_report_data buffer containing the report's data - * \param[in] length number of bytes in the \a p_report_data + * \param[in] buffer containing the report's data + * \param[in] bufsize number of bytes in the \a buffer * \note By the time this callback is invoked, the USB control transfer is already completed in the hardware side. * Application are free to handle data at its own will. */ -void tud_hid_keyboard_set_report_cb(uint8_t rhport, hid_request_report_type_t report_type, uint8_t p_report_data[], uint16_t length); +ATTR_WEAK void tud_hid_keyboard_set_report_cb(hid_report_type_t report_type, uint8_t const* buffer, uint16_t bufsize); /** @} */ /** @} */ @@ -130,15 +116,13 @@ void tud_hid_keyboard_set_report_cb(uint8_t rhport, hid_request_report_type_t re * @{ */ /** \brief Check if the interface is currently busy or not - * \param[in] rhport USB Controller ID * \retval true if the interface is busy meaning the stack is still transferring/waiting data from/to host * \retval false if the interface is not busy meaning the stack successfully transferred data from/to host * \note This function is primarily used for polling/waiting result after \ref tusbd_hid_mouse_send. */ -bool tud_hid_mouse_is_busy(uint8_t rhport); +bool tud_hid_mouse_is_busy(void); /** \brief Perform transfer queuing - * \param[in] rhport USB Controller ID * \param[in,out] p_report address that is used to store data from device. Must be accessible by usb controller (see \ref CFG_TUSB_ATTR_USBRAM) * \returns \ref tusb_error_t type to indicate success or error condition. * \retval TUSB_ERROR_NONE on success @@ -148,47 +132,34 @@ bool tud_hid_mouse_is_busy(uint8_t rhport); * \note This function is non-blocking and returns immediately. Data will be transferred when USB Host work with this interface. * The result of usb transfer will be reported by the interface's callback function */ -tusb_error_t tud_hid_mouse_send(uint8_t rhport, hid_mouse_report_t const *p_report); +tusb_error_t tud_hid_mouse_send(hid_mouse_report_t const *p_report); //--------------------------------------------------------------------+ // APPLICATION CALLBACK API //--------------------------------------------------------------------+ -/** \brief Callback function that is invoked when an transferring event occurred - * after invoking \ref tusbd_hid_mouse_send - * \param[in] rhport USB Controller ID - * \param[in] event an value from \ref tusb_event_t - * \note event can be one of following - * - TUSB_EVENT_XFER_COMPLETE : previously scheduled transfer completes successfully. - * - TUSB_EVENT_XFER_ERROR : previously scheduled transfer encountered a transaction error. - * - TUSB_EVENT_XFER_STALLED : previously scheduled transfer is stalled by device. - */ -void tud_hid_mouse_cb(uint8_t rhport, tusb_event_t event, uint32_t xferred_bytes); - /** \brief Callback function that is invoked when USB host request \ref HID_REQUEST_CONTROL_GET_REPORT * via control endpoint. - * \param[in] rhport USB Controller ID * \param[in] report_type specify which report (INPUT, OUTPUT, FEATURE) that host requests - * \param[out] pp_report pointer to buffer that application need to update, value must be accessible by USB controller (see \ref CFG_TUSB_ATTR_USBRAM) - * \param[in] requested_length number of bytes that host requested + * \param[out] buffer buffer that application need to update, value must be accessible by USB controller (see \ref CFG_TUSB_ATTR_USBRAM) + * \param[in] reqlen number of bytes that host requested * \retval non-zero Actual number of bytes in the response's buffer. * \retval zero indicates the current request is not supported. Tinyusb device stack will reject the request by * sending STALL in the data phase. * \note After this callback, the request is silently executed by the tinyusb stack, thus * the completion of this control request will not be reported to application */ -uint16_t tud_hid_mouse_get_report_cb(uint8_t rhport, hid_request_report_type_t report_type, void** pp_report, uint16_t requested_length); +ATTR_WEAK uint16_t tud_hid_mouse_get_report_cb(hid_report_type_t report_type, uint8_t* buffer, uint16_t reqlen); /** \brief Callback function that is invoked when USB host request \ref HID_REQUEST_CONTROL_SET_REPORT * via control endpoint. - * \param[in] rhport USB Controller ID * \param[in] report_type specify which report (INPUT, OUTPUT, FEATURE) that host requests - * \param[in] p_report_data buffer containing the report's data - * \param[in] length number of bytes in the \a p_report_data + * \param[in] buffer buffer containing the report's data + * \param[in] bufsize number of bytes in the \a p_report_data * \note By the time this callback is invoked, the USB control transfer is already completed in the hardware side. * Application are free to handle data at its own will. */ -void tud_hid_mouse_set_report_cb(uint8_t rhport, hid_request_report_type_t report_type, uint8_t p_report_data[], uint16_t length); +ATTR_WEAK void tud_hid_mouse_set_report_cb(hid_report_type_t report_type, uint8_t const* buffer, uint16_t bufsize); /** @} */ /** @} */ diff --git a/src/class/hid/hid_host.c b/src/class/hid/hid_host.c index fe0b7748b..fa617c5b0 100644 --- a/src/class/hid/hid_host.c +++ b/src/class/hid/hid_host.c @@ -200,7 +200,7 @@ tusb_error_t hidh_open_subtask(uint8_t dev_addr, tusb_desc_interface_t const *p_ //------------- SET IDLE (0) request -------------// STASK_INVOKE( usbh_control_xfer_subtask( dev_addr, bm_request_type(TUSB_DIR_OUT, TUSB_REQ_TYPE_CLASS, TUSB_REQ_RCPT_INTERFACE), - HID_REQUEST_CONTROL_SET_IDLE, 0, p_interface_desc->bInterfaceNumber, + HID_REQ_CONTROL_SET_IDLE, 0, p_interface_desc->bInterfaceNumber, 0, NULL ), error ); diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index b0839ecb0..f32a1f833 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -38,7 +38,7 @@ #include "tusb_option.h" -#if (MODE_DEVICE_SUPPORTED && CFG_TUD_MSC) +#if (TUSB_OPT_DEVICE_ENABLED && CFG_TUD_MSC) //--------------------------------------------------------------------+ // INCLUDE diff --git a/src/device/usbd.c b/src/device/usbd.c index e8dfd83dd..2aabd1892 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -38,7 +38,7 @@ #include "tusb_option.h" -#if MODE_DEVICE_SUPPORTED +#if TUSB_OPT_DEVICE_ENABLED #define _TINY_USB_SOURCE_FILE_ @@ -116,7 +116,7 @@ static usbd_class_driver_t const usbd_class_drivers[] = #endif - #if DEVICE_CLASS_HID + #if TUD_OPT_HID_ENABLED { .class_code = TUSB_CLASS_HID, .init = hidd_init, diff --git a/src/device/usbd.h b/src/device/usbd.h index 7fc440637..c2b05f8ff 100644 --- a/src/device/usbd.h +++ b/src/device/usbd.h @@ -59,10 +59,16 @@ /// \brief Descriptor pointer collector to all the needed. typedef struct { - uint8_t const * device; ///< pointer to device descriptor \ref tusb_desc_device_t + void const * device; ///< pointer to device descriptor \ref tusb_desc_device_t uint8_t const * config; ///< pointer to the whole configuration descriptor, starting by \ref tusb_desc_configuration_t uint8_t const** string_arr; ///< a array of pointers to string descriptors - uint8_t const * hid_report; ///< pointer to HID report descriptor only needed if CFG_TUD_HID_* is enabled + + struct { + uint8_t const* composite; + uint8_t const* boot_keyboard; + uint8_t const* boot_mouse; + } hid_report; + }tud_desc_set_t; diff --git a/src/device/usbd_desc.c b/src/device/usbd_desc.c index d672ddfaf..c2674d11a 100644 --- a/src/device/usbd_desc.c +++ b/src/device/usbd_desc.c @@ -36,7 +36,7 @@ #include "tusb_option.h" -#if MODE_DEVICE_SUPPORTED +#if TUSB_OPT_DEVICE_ENABLED #define _TINY_USB_SOURCE_FILE_ @@ -60,7 +60,7 @@ */ #define _PID_MAP(itf, n) ( (CFG_TUD_##itf) << (n) ) #define CFG_TUD_DESC_PID (0x8000 | _PID_MAP(CDC, 0) | _PID_MAP(MSC, 1) | \ - _PID_MAP(HID_KEYBOARD, 2) | _PID_MAP(HID_MOUSE, 3) | _PID_MAP(HID_GENERIC, 4) ) + _PID_MAP(HID_KEYBOARD, 2) | _PID_MAP(HID_MOUSE, 3) ) #endif /*------------- Interface Numbering -------------*/ @@ -69,43 +69,145 @@ */ #define ITF_NUM_CDC 0 -#define ITF_NUM_MSC (ITF_NUM_CDC + 2*CFG_TUD_CDC) +#define ITF_NUM_MSC (ITF_NUM_CDC + 2*CFG_TUD_CDC) -#define ITF_NUM_HID_KEYBOARD (ITF_NUM_MSC + CFG_TUD_MSC ) -#define ITF_NUM_HID_MOUSE (ITF_NUM_HID_KEYBOARD + CFG_TUD_HID_KEYBOARD ) -#define ITF_NUM_HID_GENERIC (ITF_NUM_HID_MOUSE + CFG_TUD_HID_MOUSE ) +#define ITF_NUM_HID_KBD (ITF_NUM_MSC + CFG_TUD_MSC) +#define ITF_NUM_HID_MSE (ITF_NUM_HID_KBD + CFG_TUD_HID_KEYBOARD) -#define ITF_TOTAL (ITF_NUM_HID_GENERIC + CFG_TUD_HID_GENERIC) +#define ITF_TOTAL (ITF_NUM_HID_MSE + CFG_TUD_HID_MOUSE) /*------------- Endpoint Numbering & Size -------------*/ -#define _EP_IN(x) (0x80 | (x)) -#define _EP_OUT(x) (x) +#define _EP_IN(x) (0x80 | (x)) +#define _EP_OUT(x) (x) // CDC -#define EP_CDC_NOTIF _EP_IN (ITF_NUM_CDC+1) -#define EP_CDC_NOTIF_SIZE 8 +#define EP_CDC_NOTIF _EP_IN (ITF_NUM_CDC+1) +#define EP_CDC_NOTIF_SIZE 8 -#define EP_CDC_OUT _EP_OUT(ITF_NUM_CDC+2) -#define EP_CDC_IN _EP_IN (ITF_NUM_CDC+2) +#define EP_CDC_OUT _EP_OUT(ITF_NUM_CDC+2) +#define EP_CDC_IN _EP_IN (ITF_NUM_CDC+2) // Mass Storage -#define EP_MSC_OUT _EP_OUT(ITF_NUM_MSC+1) -#define EP_MSC_IN _EP_IN (ITF_NUM_MSC+1) +#define EP_MSC_OUT _EP_OUT(ITF_NUM_MSC+1) +#define EP_MSC_IN _EP_IN (ITF_NUM_MSC+1) -#if 0 +// Boot protocol each report has its own interface +#if CFG_TUD_HID_BOOT_PROTOCOL // HID Keyboard -#define EP_HID_KBD _EP_IN (INTERFACE_NO_HID_KEYBOARD+1) -#define EP_HID_KBD_SZIE 8 +#define EP_HID_KBD _EP_IN (ITF_NUM_HID_KBD+1) +#define EP_HID_KBD_SIZE 8 // HID Mouse -#define EP_HID_MSE _EP_IN (INTERFACE_NO_HID_MOUSE+1) -#define EP_HID_MSE_SIZE 8 +#define EP_HID_MSE _EP_IN (ITF_NUM_HID_MSE+1) +#define EP_HID_MSE_SIZE 8 + +#else + +// HID composite = keyboard + mouse +#define EP_HID_COMP _EP_IN (ITF_NUM_HID_KBD+1) +#define EP_HID_COMP_SIZE 16 -// HID Generic #endif +// TODO HID Generic + + +//--------------------------------------------------------------------+ +// Keyboard Report Descriptor +//--------------------------------------------------------------------+ +#if CFG_TUD_HID_KEYBOARD +uint8_t const _desc_auto_hid_kbd_report[] = { + HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ), + HID_USAGE ( HID_USAGE_DESKTOP_KEYBOARD ), + HID_COLLECTION ( HID_COLLECTION_APPLICATION ), + HID_USAGE_PAGE ( HID_USAGE_PAGE_KEYBOARD ), + HID_USAGE_MIN ( 224 ), + HID_USAGE_MAX ( 231 ), + HID_LOGICAL_MIN ( 0 ), + HID_LOGICAL_MAX ( 1 ), + + HID_REPORT_SIZE ( 1 ), + HID_REPORT_COUNT ( 8 ), /* 8 bits */ + HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ), /* maskable modifier key */ + + HID_REPORT_SIZE ( 8 ), + HID_REPORT_COUNT ( 1 ), + HID_INPUT ( HID_CONSTANT ), /* reserved */ + + HID_USAGE_PAGE ( HID_USAGE_PAGE_LED ), + HID_USAGE_MIN ( 1 ), + HID_USAGE_MAX ( 5 ), + HID_REPORT_COUNT ( 5 ), + HID_REPORT_SIZE ( 1 ), + HID_OUTPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ), /* 5-bit Led report */ + + HID_REPORT_SIZE ( 3 ), /* led padding */ + HID_REPORT_COUNT ( 1 ), + HID_OUTPUT ( HID_CONSTANT ), + + HID_USAGE_PAGE (HID_USAGE_PAGE_KEYBOARD), + HID_USAGE_MIN ( 0 ), + HID_USAGE_MAX ( 101 ), + HID_LOGICAL_MIN ( 0 ), + HID_LOGICAL_MAX ( 101 ), + + HID_REPORT_SIZE ( 8 ), + HID_REPORT_COUNT ( 6 ), + HID_INPUT ( HID_DATA | HID_ARRAY | HID_ABSOLUTE ), /* keycodes array 6 items */ + HID_COLLECTION_END +}; +#endif + +//--------------------------------------------------------------------+ +// Mouse Report Descriptor +//--------------------------------------------------------------------+ +#if CFG_TUD_HID_MOUSE +uint8_t const _desc_auto_hid_mse_report[] = { + HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ), + HID_USAGE ( HID_USAGE_DESKTOP_MOUSE ), + HID_COLLECTION ( HID_COLLECTION_APPLICATION ), + HID_USAGE (HID_USAGE_DESKTOP_POINTER), + + HID_COLLECTION ( HID_COLLECTION_PHYSICAL ), + HID_USAGE_PAGE ( HID_USAGE_PAGE_BUTTON ), + HID_USAGE_MIN ( 1 ), + HID_USAGE_MAX ( 3 ), + HID_LOGICAL_MIN ( 0 ), + HID_LOGICAL_MAX ( 1 ), + + HID_REPORT_SIZE ( 1 ), + HID_REPORT_COUNT ( 3 ), /* Left, Right and Middle mouse*/ + HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ), + + HID_REPORT_SIZE ( 5 ), + HID_REPORT_COUNT ( 1 ), + HID_INPUT ( HID_CONSTANT ), /* 5 bit padding followed 3 bit buttons */ + + HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ), + HID_USAGE ( HID_USAGE_DESKTOP_X ), + HID_USAGE ( HID_USAGE_DESKTOP_Y ), + HID_LOGICAL_MIN ( 0x81 ), /* -127 */ + HID_LOGICAL_MAX ( 0x7f ), /* 127 */ + + HID_REPORT_SIZE ( 8 ), + HID_REPORT_COUNT ( 2 ), /* X, Y position */ + HID_INPUT ( HID_DATA | HID_VARIABLE | HID_RELATIVE ), /* relative values */ + + HID_USAGE ( HID_USAGE_DESKTOP_WHEEL ), /* mouse scroll */ + HID_LOGICAL_MIN ( 0x81 ), /* -127 */ + HID_LOGICAL_MAX ( 0x7f ), /* 127 */ + HID_REPORT_COUNT( 1 ), + HID_REPORT_SIZE ( 8 ), /* 8-bit value */ + HID_INPUT ( HID_DATA | HID_VARIABLE | HID_RELATIVE ), /* relative values */ + + HID_COLLECTION_END, + + HID_COLLECTION_END +}; +#endif + /*------------------------------------------------------------------*/ /* Auto generate descriptor @@ -179,30 +281,52 @@ typedef struct ATTR_PACKED }cdc; #endif -//------------- Mass Storage -------------// + //------------- Mass Storage -------------// #if CFG_TUD_MSC struct ATTR_PACKED { tusb_desc_interface_t itf; tusb_desc_endpoint_t ep_out; tusb_desc_endpoint_t ep_in; - }msc; + } msc; #endif -#if 0 - //------------- HID Keyboard -------------// + //------------- HID -------------// +#if CFG_TUD_HID_BOOT_PROTOCOL + #if CFG_TUD_HID_KEYBOARD - tusb_desc_interface_t keyboard_interface; - tusb_hid_descriptor_hid_t keyboard_hid; - tusb_desc_endpoint_t keyboard_endpoint; + struct ATTR_PACKED + { + tusb_desc_interface_t itf; + tusb_hid_descriptor_hid_t hid_desc; + tusb_desc_endpoint_t ep_in; + } hid_kbd; #endif -//------------- HID Mouse -------------// #if CFG_TUD_HID_MOUSE - tusb_desc_interface_t mouse_interface; - tusb_hid_descriptor_hid_t mouse_hid; - tusb_desc_endpoint_t mouse_endpoint; + struct ATTR_PACKED + { + tusb_desc_interface_t itf; + tusb_hid_descriptor_hid_t hid_desc; + tusb_desc_endpoint_t ep_in; + } hid_mse; +#endif + +#else + +#if CFG_TUD_HID_KEYBOARD || CFG_TUD_HID_MOUSE + struct ATTR_PACKED + { + tusb_desc_interface_t itf; + tusb_hid_descriptor_hid_t hid_desc; + tusb_desc_endpoint_t ep_in; + + #if CFG_TUD_HID_KEYBOARD + tusb_desc_endpoint_t ep_out; + #endif + } hid_composite; #endif + #endif } desc_auto_cfg_t; @@ -338,6 +462,7 @@ desc_auto_cfg_t const _desc_auto_config_struct = #endif #if CFG_TUD_MSC + //------------- Mass Storage-------------// .msc = { .itf = @@ -375,179 +500,137 @@ desc_auto_cfg_t const _desc_auto_config_struct = }, #endif -#if 0 - //------------- HID Keyboard -------------// - #if CFG_TUD_HID_KEYBOARD - .keyboard_interface = - { - .bLength = sizeof(tusb_desc_interface_t), - .bDescriptorType = TUSB_DESC_INTERFACE, - .bInterfaceNumber = ITF_NUM_HID_KEYBOARD, - .bAlternateSetting = 0x00, - .bNumEndpoints = 1, - .bInterfaceClass = TUSB_CLASS_HID, - .bInterfaceSubClass = HID_SUBCLASS_BOOT, - .bInterfaceProtocol = HID_PROTOCOL_KEYBOARD, - .iInterface = ITF_NUM_HID_KEYBOARD + 3, - }, +#if CFG_TUD_HID_BOOT_PROTOCOL - .keyboard_hid = +#if CFG_TUD_HID_KEYBOARD + .hid_kbd = { - .bLength = sizeof(tusb_hid_descriptor_hid_t), - .bDescriptorType = HID_DESC_TYPE_HID, - .bcdHID = 0x0111, - .bCountryCode = HID_Local_NotSupported, - .bNumDescriptors = 1, - .bReportType = HID_DESC_TYPE_REPORT, - .wReportLength = sizeof(desc_keyboard_report) + .itf = + { + .bLength = sizeof(tusb_desc_interface_t), + .bDescriptorType = TUSB_DESC_INTERFACE, + .bInterfaceNumber = ITF_NUM_HID_KBD, + .bAlternateSetting = 0x00, + .bNumEndpoints = 2, + .bInterfaceClass = TUSB_CLASS_HID, + .bInterfaceSubClass = HID_SUBCLASS_BOOT, + .bInterfaceProtocol = HID_PROTOCOL_KEYBOARD, + .iInterface = 4 + CFG_TUD_CDC + CFG_TUD_MSC + }, + + .hid_desc = + { + .bLength = sizeof(tusb_hid_descriptor_hid_t), + .bDescriptorType = HID_DESC_TYPE_HID, + .bcdHID = 0x0111, + .bCountryCode = HID_Local_NotSupported, + .bNumDescriptors = 1, + .bReportType = HID_DESC_TYPE_REPORT, + .wReportLength = sizeof(_desc_auto_hid_kbd_report) + }, + + .ep_in = + { + .bLength = sizeof(tusb_desc_endpoint_t), + .bDescriptorType = TUSB_DESC_ENDPOINT, + .bEndpointAddress = EP_HID_KBD, + .bmAttributes = { .xfer = TUSB_XFER_INTERRUPT }, + .wMaxPacketSize = { .size = EP_HID_KBD_SIZE }, + .bInterval = 0x0A + } }, +#endif // keyboard - .keyboard_endpoint = + //------------- HID Mouse -------------// +#if CFG_TUD_HID_MOUSE + .hid_mse = { - .bLength = sizeof(tusb_desc_endpoint_t), - .bDescriptorType = TUSB_DESC_ENDPOINT, - .bEndpointAddress = EP_HID_KBD, - .bmAttributes = { .xfer = TUSB_XFER_INTERRUPT }, - .wMaxPacketSize = { .size = EP_HID_KBD_SZIE }, - .bInterval = 0x0A + .itf = + { + .bLength = sizeof(tusb_desc_interface_t), + .bDescriptorType = TUSB_DESC_INTERFACE, + .bInterfaceNumber = ITF_NUM_HID_MSE, + .bAlternateSetting = 0x00, + .bNumEndpoints = 1, + .bInterfaceClass = TUSB_CLASS_HID, + .bInterfaceSubClass = HID_SUBCLASS_BOOT, + .bInterfaceProtocol = HID_PROTOCOL_MOUSE, + .iInterface = 4 + CFG_TUD_CDC + CFG_TUD_MSC + CFG_TUD_HID_KEYBOARD + }, + + .hid_desc = + { + .bLength = sizeof(tusb_hid_descriptor_hid_t), + .bDescriptorType = HID_DESC_TYPE_HID, + .bcdHID = 0x0111, + .bCountryCode = HID_Local_NotSupported, + .bNumDescriptors = 1, + .bReportType = HID_DESC_TYPE_REPORT, + .wReportLength = sizeof(_desc_auto_hid_mse_report) + }, + + .ep_in = + { + .bLength = sizeof(tusb_desc_endpoint_t), + .bDescriptorType = TUSB_DESC_ENDPOINT, + .bEndpointAddress = EP_HID_MSE, + .bmAttributes = { .xfer = TUSB_XFER_INTERRUPT }, + .wMaxPacketSize = { .size = EP_HID_MSE_SIZE }, + .bInterval = 0x0A + }, }, - #endif - //------------- HID Mouse -------------// - #if CFG_TUD_HID_MOUSE - .mouse_interface = - { - .bLength = sizeof(tusb_desc_interface_t), - .bDescriptorType = TUSB_DESC_INTERFACE, - .bInterfaceNumber = ITF_NUM_HID_MOUSE, - .bAlternateSetting = 0x00, - .bNumEndpoints = 1, - .bInterfaceClass = TUSB_CLASS_HID, - .bInterfaceSubClass = HID_SUBCLASS_BOOT, - .bInterfaceProtocol = HID_PROTOCOL_MOUSE, - .iInterface = ITF_NUM_HID_MOUSE+3 - }, +#endif // mouse - .mouse_hid = - { - .bLength = sizeof(tusb_hid_descriptor_hid_t), - .bDescriptorType = HID_DESC_TYPE_HID, - .bcdHID = 0x0111, - .bCountryCode = HID_Local_NotSupported, - .bNumDescriptors = 1, - .bReportType = HID_DESC_TYPE_REPORT, - .wReportLength = sizeof(desc_mouse_report) - }, +#else - .mouse_endpoint = +#if CFG_TUD_HID_KEYBOARD || CFG_TUD_HID_MOUSE + //------------- HID Keyboard + Mouse 9multiple reports) -------------// + .hid_composite = { - .bLength = sizeof(tusb_desc_endpoint_t), - .bDescriptorType = TUSB_DESC_ENDPOINT, - .bEndpointAddress = EP_HID_MSE, // TODO - .bmAttributes = { .xfer = TUSB_XFER_INTERRUPT }, - .wMaxPacketSize = { .size = EP_HID_MSE_SIZE }, - .bInterval = 0x0A - }, - #endif + .itf = + { + .bLength = sizeof(tusb_desc_interface_t), + .bDescriptorType = TUSB_DESC_INTERFACE, + .bInterfaceNumber = ITF_NUM_HID_KBD, + .bAlternateSetting = 0x00, + .bNumEndpoints = 2, + .bInterfaceClass = TUSB_CLASS_HID, + .bInterfaceSubClass = 0, + .bInterfaceProtocol = 0, + .iInterface = 4 + CFG_TUD_CDC + CFG_TUD_MSC, + }, + + .hid_desc = + { + .bLength = sizeof(tusb_hid_descriptor_hid_t), + .bDescriptorType = HID_DESC_TYPE_HID, + .bcdHID = 0x0111, + .bCountryCode = HID_Local_NotSupported, + .bNumDescriptors = 1, + .bReportType = HID_DESC_TYPE_REPORT, + .wReportLength = sizeof(_desc_auto_hid_composite_report) + }, + + .ep_in = + { + .bLength = sizeof(tusb_desc_endpoint_t), + .bDescriptorType = TUSB_DESC_ENDPOINT, + .bEndpointAddress = EP_HID_COMP, + .bmAttributes = { .xfer = TUSB_XFER_INTERRUPT }, + .wMaxPacketSize = { .size = EP_HID_COMP_SIZE }, + .bInterval = 0x0A + } + } #endif -}; - -uint8_t const * const _desc_auto_config = (uint8_t const*) &_desc_auto_config_struct; - -//--------------------------------------------------------------------+ -// Keyboard Report Descriptor -//--------------------------------------------------------------------+ -#if CFG_TUD_HID_KEYBOARD -uint8_t const desc_keyboard_report[] = { - HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ), - HID_USAGE ( HID_USAGE_DESKTOP_KEYBOARD ), - HID_COLLECTION ( HID_COLLECTION_APPLICATION ), - HID_USAGE_PAGE ( HID_USAGE_PAGE_KEYBOARD ), - HID_USAGE_MIN ( 224 ), - HID_USAGE_MAX ( 231 ), - HID_LOGICAL_MIN ( 0 ), - HID_LOGICAL_MAX ( 1 ), - - HID_REPORT_SIZE ( 1 ), - HID_REPORT_COUNT ( 8 ), /* 8 bits */ - HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ), /* maskable modifier key */ - - HID_REPORT_SIZE ( 8 ), - HID_REPORT_COUNT ( 1 ), - HID_INPUT ( HID_CONSTANT ), /* reserved */ - - HID_USAGE_PAGE ( HID_USAGE_PAGE_LED ), - HID_USAGE_MIN ( 1 ), - HID_USAGE_MAX ( 5 ), - HID_REPORT_COUNT ( 5 ), - HID_REPORT_SIZE ( 1 ), - HID_OUTPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ), /* 5-bit Led report */ - - HID_REPORT_SIZE ( 3 ), /* led padding */ - HID_REPORT_COUNT ( 1 ), - HID_OUTPUT ( HID_CONSTANT ), - - HID_USAGE_PAGE (HID_USAGE_PAGE_KEYBOARD), - HID_USAGE_MIN ( 0 ), - HID_USAGE_MAX ( 101 ), - HID_LOGICAL_MIN ( 0 ), - HID_LOGICAL_MAX ( 101 ), - - HID_REPORT_SIZE ( 8 ), - HID_REPORT_COUNT ( 6 ), - HID_INPUT ( HID_DATA | HID_ARRAY | HID_ABSOLUTE ), /* keycodes array 6 items */ - HID_COLLECTION_END +#endif // boot protocol }; -#endif - -//--------------------------------------------------------------------+ -// Mouse Report Descriptor -//--------------------------------------------------------------------+ -#if CFG_TUD_HID_MOUSE -uint8_t const desc_mouse_report[] = { - HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ), - HID_USAGE ( HID_USAGE_DESKTOP_MOUSE ), - HID_COLLECTION ( HID_COLLECTION_APPLICATION ), - HID_USAGE (HID_USAGE_DESKTOP_POINTER), - - HID_COLLECTION ( HID_COLLECTION_PHYSICAL ), - HID_USAGE_PAGE ( HID_USAGE_PAGE_BUTTON ), - HID_USAGE_MIN ( 1 ), - HID_USAGE_MAX ( 3 ), - HID_LOGICAL_MIN ( 0 ), - HID_LOGICAL_MAX ( 1 ), - - HID_REPORT_SIZE ( 1 ), - HID_REPORT_COUNT ( 3 ), /* Left, Right and Middle mouse*/ - HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ), - - HID_REPORT_SIZE ( 5 ), - HID_REPORT_COUNT ( 1 ), - HID_INPUT ( HID_CONSTANT ), /* 5 bit padding followed 3 bit buttons */ - - HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ), - HID_USAGE ( HID_USAGE_DESKTOP_X ), - HID_USAGE ( HID_USAGE_DESKTOP_Y ), - HID_LOGICAL_MIN ( 0x81 ), /* -127 */ - HID_LOGICAL_MAX ( 0x7f ), /* 127 */ - HID_REPORT_SIZE ( 8 ), - HID_REPORT_COUNT ( 2 ), /* X, Y position */ - HID_INPUT ( HID_DATA | HID_VARIABLE | HID_RELATIVE ), /* relative values */ +uint8_t const * const _desc_auto_config = (uint8_t const*) &_desc_auto_config_struct; - HID_USAGE ( HID_USAGE_DESKTOP_WHEEL ), /* mouse scroll */ - HID_LOGICAL_MIN ( 0x81 ), /* -127 */ - HID_LOGICAL_MAX ( 0x7f ), /* 127 */ - HID_REPORT_COUNT( 1 ), - HID_REPORT_SIZE ( 8 ), /* 8-bit value */ - HID_INPUT ( HID_DATA | HID_VARIABLE | HID_RELATIVE ), /* relative values */ - HID_COLLECTION_END, - HID_COLLECTION_END -}; -#endif #endif diff --git a/src/portable/nordic/nrf5x/dcd_nrf5x.c b/src/portable/nordic/nrf5x/dcd_nrf5x.c index db424f650..5444a0e97 100644 --- a/src/portable/nordic/nrf5x/dcd_nrf5x.c +++ b/src/portable/nordic/nrf5x/dcd_nrf5x.c @@ -36,7 +36,7 @@ #include "tusb_option.h" -#if MODE_DEVICE_SUPPORTED && CFG_TUSB_MCU == OPT_MCU_NRF5X +#if TUSB_OPT_DEVICE_ENABLED && CFG_TUSB_MCU == OPT_MCU_NRF5X #include "nrf.h" #include "nrf_power.h" diff --git a/src/portable/nordic/nrf5x/hal_nrf5x.c b/src/portable/nordic/nrf5x/hal_nrf5x.c index 806d8f098..f04867676 100644 --- a/src/portable/nordic/nrf5x/hal_nrf5x.c +++ b/src/portable/nordic/nrf5x/hal_nrf5x.c @@ -36,7 +36,7 @@ #include "tusb_option.h" -#if MODE_DEVICE_SUPPORTED && CFG_TUSB_MCU == OPT_MCU_NRF5X +#if TUSB_OPT_DEVICE_ENABLED && CFG_TUSB_MCU == OPT_MCU_NRF5X #include "nrf.h" #include "nrf_gpio.h" diff --git a/src/portable/nxp/lpc11xx_lpc13xx/dcd_lpc_11uxx_13uxx.c b/src/portable/nxp/lpc11xx_lpc13xx/dcd_lpc_11uxx_13uxx.c index a9f05f573..f0472f41d 100644 --- a/src/portable/nxp/lpc11xx_lpc13xx/dcd_lpc_11uxx_13uxx.c +++ b/src/portable/nxp/lpc11xx_lpc13xx/dcd_lpc_11uxx_13uxx.c @@ -38,7 +38,7 @@ #include "tusb_option.h" -#if MODE_DEVICE_SUPPORTED && (CFG_TUSB_MCU == OPT_MCU_LPC11UXX || CFG_TUSB_MCU == OPT_MCU_LPC13UXX) +#if TUSB_OPT_DEVICE_ENABLED && (CFG_TUSB_MCU == OPT_MCU_LPC11UXX || CFG_TUSB_MCU == OPT_MCU_LPC13UXX) #define _TINY_USB_SOURCE_FILE_ diff --git a/src/portable/nxp/lpc17xx/dcd_lpc175x_6x.c b/src/portable/nxp/lpc17xx/dcd_lpc175x_6x.c index 18947997f..948572129 100644 --- a/src/portable/nxp/lpc17xx/dcd_lpc175x_6x.c +++ b/src/portable/nxp/lpc17xx/dcd_lpc175x_6x.c @@ -38,7 +38,7 @@ #include "tusb_option.h" -#if MODE_DEVICE_SUPPORTED && (CFG_TUSB_MCU == OPT_MCU_LPC175X_6X) +#if TUSB_OPT_DEVICE_ENABLED && (CFG_TUSB_MCU == OPT_MCU_LPC175X_6X) #define _TINY_USB_SOURCE_FILE_ //--------------------------------------------------------------------+ diff --git a/src/portable/nxp/lpc17xx/hal_lpc175x_6x.c b/src/portable/nxp/lpc17xx/hal_lpc175x_6x.c index 5fa5ecfa0..de9d9a86e 100644 --- a/src/portable/nxp/lpc17xx/hal_lpc175x_6x.c +++ b/src/portable/nxp/lpc17xx/hal_lpc175x_6x.c @@ -80,7 +80,7 @@ bool tusb_hal_init(void) LPC_USB->OTGStCtrl = 0x3; #endif -#if MODE_DEVICE_SUPPORTED +#if TUSB_OPT_DEVICE_ENABLED LPC_PINCON->PINSEL4 = bit_set_range(LPC_PINCON->PINSEL4, 18, 19, BIN8(01)); // P2_9 as USB Connect // P1_30 as VBUS, ignore if it is already in VBUS mode @@ -106,7 +106,7 @@ void USB_IRQHandler(void) hal_hcd_isr(0); #endif - #if MODE_DEVICE_SUPPORTED + #if TUSB_OPT_DEVICE_ENABLED hal_dcd_isr(0); #endif } diff --git a/src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c b/src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c index ef586c9e3..a08e20a3f 100644 --- a/src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c +++ b/src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c @@ -38,7 +38,7 @@ #include "tusb_option.h" -#if MODE_DEVICE_SUPPORTED && CFG_TUSB_MCU == OPT_MCU_LPC43XX +#if TUSB_OPT_DEVICE_ENABLED && CFG_TUSB_MCU == OPT_MCU_LPC43XX //--------------------------------------------------------------------+ // INCLUDE diff --git a/src/portable/nxp/lpc43xx_lpc18xx/hal_lpc43xx.c b/src/portable/nxp/lpc43xx_lpc18xx/hal_lpc43xx.c index a25710d3f..92f9f1cf0 100644 --- a/src/portable/nxp/lpc43xx_lpc18xx/hal_lpc43xx.c +++ b/src/portable/nxp/lpc43xx_lpc18xx/hal_lpc43xx.c @@ -136,7 +136,7 @@ void USB0_IRQHandler(void) hal_hcd_isr(0); #endif - #if MODE_DEVICE_SUPPORTED + #if TUSB_OPT_DEVICE_ENABLED hal_dcd_isr(0); #endif } @@ -149,7 +149,7 @@ void USB1_IRQHandler(void) hal_hcd_isr(1); #endif - #if MODE_DEVICE_SUPPORTED + #if TUSB_OPT_DEVICE_ENABLED hal_dcd_isr(1); #endif } diff --git a/src/tusb.c b/src/tusb.c index fde29c24f..0ef1301a4 100644 --- a/src/tusb.c +++ b/src/tusb.c @@ -55,7 +55,7 @@ tusb_error_t tusb_init(void) TU_ASSERT_ERR( usbh_init() ); // host stack init #endif -#if MODE_DEVICE_SUPPORTED +#if TUSB_OPT_DEVICE_ENABLED TU_ASSERT_ERR ( usbd_init() ); // device stack init #endif @@ -71,7 +71,7 @@ void tusb_task(void) usbh_enumeration_task(NULL); #endif - #if MODE_DEVICE_SUPPORTED + #if TUSB_OPT_DEVICE_ENABLED usbd_task(NULL); #endif } diff --git a/src/tusb.h b/src/tusb.h index 3f70546c8..8f25e2867 100644 --- a/src/tusb.h +++ b/src/tusb.h @@ -73,10 +73,10 @@ #endif //------------- DEVICE -------------// -#if MODE_DEVICE_SUPPORTED +#if TUSB_OPT_DEVICE_ENABLED #include "device/usbd.h" - #if DEVICE_CLASS_HID + #if TUD_OPT_HID_ENABLED #include "class/hid/hid_device.h" #endif diff --git a/src/tusb_option.h b/src/tusb_option.h index 04374bc19..a7b18d504 100644 --- a/src/tusb_option.h +++ b/src/tusb_option.h @@ -77,9 +77,9 @@ /** \addtogroup group_configuration * @{ */ -//--------------------------------------------------------------------+ +//-------------------------------------------------------------------- // CONTROLLER -//--------------------------------------------------------------------+ +//-------------------------------------------------------------------- /** \defgroup group_mode Controller Mode Selection * \brief CFG_TUSB_CONTROLLER_N_MODE must be defined with these * @{ */ @@ -105,11 +105,11 @@ ((CFG_TUSB_RHPORT1_MODE & OPT_MODE_DEVICE) ? 1 : 0)) #define MODE_HOST_SUPPORTED (CONTROLLER_HOST_NUMBER > 0) -#define MODE_DEVICE_SUPPORTED (CONTROLLER_DEVICE_NUMBER > 0) +#define TUSB_OPT_DEVICE_ENABLED (CONTROLLER_DEVICE_NUMBER > 0) -#define TUD_RHPORT ((CFG_TUSB_RHPORT0_MODE & OPT_MODE_DEVICE) ? 0 : ((CFG_TUSB_RHPORT1_MODE & OPT_MODE_DEVICE) ? 1 : -1)) +#define TUD_OPT_RHPORT ((CFG_TUSB_RHPORT0_MODE & OPT_MODE_DEVICE) ? 0 : ((CFG_TUSB_RHPORT1_MODE & OPT_MODE_DEVICE) ? 1 : -1)) -#if !MODE_HOST_SUPPORTED && !MODE_DEVICE_SUPPORTED +#if !MODE_HOST_SUPPORTED && !TUSB_OPT_DEVICE_ENABLED #error please configure at least 1 CFG_TUSB_CONTROLLER_N_MODE to OPT_MODE_HOST and/or OPT_MODE_DEVICE #endif @@ -146,12 +146,12 @@ #define tu_free free #endif -//--------------------------------------------------------------------+ +//-------------------------------------------------------------------- // DEVICE OPTIONS -//--------------------------------------------------------------------+ -#if MODE_DEVICE_SUPPORTED +//-------------------------------------------------------------------- +#if TUSB_OPT_DEVICE_ENABLED - #define DEVICE_CLASS_HID ( CFG_TUD_HID_KEYBOARD + CFG_TUD_HID_MOUSE + CFG_TUD_HID_GENERIC ) + #define TUD_OPT_HID_ENABLED ( CFG_TUD_HID_KEYBOARD + CFG_TUD_HID_MOUSE ) #ifndef CFG_TUD_ENDOINT0_SIZE #define CFG_TUD_ENDOINT0_SIZE 64 @@ -173,11 +173,11 @@ #define CFG_TUD_MSC 0 #endif -#endif // MODE_DEVICE_SUPPORTED +#endif // TUSB_OPT_DEVICE_ENABLED -//--------------------------------------------------------------------+ +//-------------------------------------------------------------------- // HOST OPTIONS -//--------------------------------------------------------------------+ +//-------------------------------------------------------------------- #if MODE_HOST_SUPPORTED #ifndef CFG_TUSB_HOST_DEVICE_MAX #define CFG_TUSB_HOST_DEVICE_MAX 1 @@ -203,9 +203,9 @@ #endif // MODE_HOST_SUPPORTED -/*------------------------------------------------------------------*/ -/* Config Verification - *------------------------------------------------------------------*/ +//------------------------------------------------------------------ +// Config Verification +//------------------------------------------------------------------ #if (CFG_TUSB_OS != OPT_OS_NONE) && !defined (CFG_TUD_TASK_PRIO) #error CFG_TUD_TASK_PRIO need to be defined (hint: use the highest if possible) diff --git a/tests/lpc175x_6x/test/test_usbd.c b/tests/lpc175x_6x/test/test_usbd.c index 5cb7c232d..b70f4592c 100644 --- a/tests/lpc175x_6x/test/test_usbd.c +++ b/tests/lpc175x_6x/test/test_usbd.c @@ -87,7 +87,7 @@ tusb_error_t stub_hidd_init(uint8_t coreid, tusb_desc_interface_t const* p_inter void class_init_epxect(void) { -#if DEVICE_CLASS_HID +#if TUD_OPT_HID_ENABLED hidd_init_StubWithCallback(stub_hidd_init); #endif } diff --git a/tests/lpc18xx_43xx/test/host/hid/test_hidh_keyboard.c b/tests/lpc18xx_43xx/test/host/hid/test_hidh_keyboard.c index 2b109729d..75c8f8a90 100644 --- a/tests/lpc18xx_43xx/test/host/hid/test_hidh_keyboard.c +++ b/tests/lpc18xx_43xx/test/host/hid/test_hidh_keyboard.c @@ -127,7 +127,7 @@ tusb_error_t stub_set_idle_request(uint8_t address, tusb_control_request_t const TEST_ASSERT_EQUAL(TUSB_DIR_HOST_TO_DEV , p_request->bmRequestType_bit.direction); TEST_ASSERT_EQUAL(TUSB_REQ_TYPE_CLASS , p_request->bmRequestType_bit.type); TEST_ASSERT_EQUAL(TUSB_REQ_RECIPIENT_INTERFACE , p_request->bmRequestType_bit.recipient); - TEST_ASSERT_EQUAL(HID_REQUEST_CONTROL_SET_IDLE , p_request->bRequest); + TEST_ASSERT_EQUAL(HID_REQ_CONTROL_SET_IDLE , p_request->bRequest); TEST_ASSERT_EQUAL(0 , p_request->wValue); TEST_ASSERT_EQUAL(p_kbd_interface_desc->bInterfaceNumber , p_request->wIndex); @@ -144,7 +144,7 @@ void test_keyboard_open_ok(void) hidh_init(); usbh_control_xfer_subtask_ExpectAndReturn(dev_addr, bm_request_type(TUSB_DIR_HOST_TO_DEV, TUSB_REQ_TYPE_CLASS, TUSB_REQ_RECIPIENT_INTERFACE), - HID_REQUEST_CONTROL_SET_IDLE, 0, p_kbd_interface_desc->bInterfaceNumber, 0, NULL, + HID_REQ_CONTROL_SET_IDLE, 0, p_kbd_interface_desc->bInterfaceNumber, 0, NULL, TUSB_ERROR_NONE); hcd_pipe_open_ExpectAndReturn(dev_addr, p_kdb_endpoint_desc, TUSB_CLASS_HID, pipe_hdl); tusbh_hid_keyboard_mounted_cb_Expect(dev_addr); diff --git a/tests/lpc18xx_43xx/test/host/hid/test_hidh_mouse.c b/tests/lpc18xx_43xx/test/host/hid/test_hidh_mouse.c index 31349798d..741f54428 100644 --- a/tests/lpc18xx_43xx/test/host/hid/test_hidh_mouse.c +++ b/tests/lpc18xx_43xx/test/host/hid/test_hidh_mouse.c @@ -115,7 +115,7 @@ void test_mouse_open_ok(void) hidh_init(); usbh_control_xfer_subtask_ExpectAndReturn(dev_addr, bm_request_type(TUSB_DIR_HOST_TO_DEV, TUSB_REQ_TYPE_CLASS, TUSB_REQ_RECIPIENT_INTERFACE), - HID_REQUEST_CONTROL_SET_IDLE, 0, p_mouse_interface_desc->bInterfaceNumber, 0, NULL, + HID_REQ_CONTROL_SET_IDLE, 0, p_mouse_interface_desc->bInterfaceNumber, 0, NULL, TUSB_ERROR_NONE); hcd_pipe_open_ExpectAndReturn(dev_addr, p_mouse_endpoint_desc, TUSB_CLASS_HID, pipe_hdl); tusbh_hid_mouse_mounted_cb_Expect(dev_addr); diff --git a/tests/support/tusb_config.h b/tests/support/tusb_config.h index 757ac7bac..e46d6f04d 100644 --- a/tests/support/tusb_config.h +++ b/tests/support/tusb_config.h @@ -73,11 +73,10 @@ #define CFG_TUD_ENDOINT0_SIZE 64 //------------- CLASS -------------// +#define CFG_TUD_CDC 1 +#define CFG_TUD_MSC 1 #define CFG_TUD_HID_KEYBOARD 1 #define CFG_TUD_HID_MOUSE 1 -#define CFG_TUD_HID_GENERIC 0 -#define CFG_TUD_MSC 1 -#define CFG_TUD_CDC 1 //--------------------------------------------------------------------+ -- cgit v1.3.1 From 3e209f9c20c9251e01af35da4d9e454fcc2f61dd Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 23 Jul 2018 17:46:07 +0700 Subject: enhance device hid - add CFG_TUD_HID_ASCII_TO_KEYCODE_LOOKUP - add tud_hid_keyboard_send_keycode(), tud_hid_keyboard_send_char(), tud_hid_keyboard_send_string() - add timeout_blocking_wait() --- examples/device/nrf52840/src/main.c | 27 ++++ examples/device/nrf52840/src/tusb_config.h | 7 + src/class/hid/hid.h | 211 +++++++++++++++------------- src/class/hid/hid_device.c | 216 +++++++++++++++++++++++++++-- src/class/hid/hid_device.h | 48 +++---- src/common/timeout_timer.h | 9 ++ 6 files changed, 386 insertions(+), 132 deletions(-) (limited to 'src/class') diff --git a/examples/device/nrf52840/src/main.c b/examples/device/nrf52840/src/main.c index 00937d7d2..1993109b4 100644 --- a/examples/device/nrf52840/src/main.c +++ b/examples/device/nrf52840/src/main.c @@ -76,6 +76,9 @@ int main(void) return 0; } +//--------------------------------------------------------------------+ +// USB CDC +//--------------------------------------------------------------------+ void virtual_com_task(void) { // connected and there are data available @@ -91,6 +94,30 @@ void virtual_com_task(void) } } +//--------------------------------------------------------------------+ +// USB CDC +//--------------------------------------------------------------------+ +void usb_hid_task(void) +{ + if ( tud_mounted() ) + { + if ( !tud_hid_keyboard_busy() ) + { + static bool toggle = false; // send either A or B + + tud_hid_keyboard_send_char( toggle ? 'A' : 'B' ); + toggle = !toggle; + } + + if ( !tud_hid_mouse_busy() ) + { + + } + + } +} + + //--------------------------------------------------------------------+ // tinyusb callbacks diff --git a/examples/device/nrf52840/src/tusb_config.h b/examples/device/nrf52840/src/tusb_config.h index da7dc793b..457dceea7 100644 --- a/examples/device/nrf52840/src/tusb_config.h +++ b/examples/device/nrf52840/src/tusb_config.h @@ -126,6 +126,13 @@ */ #define CFG_TUD_HID_BOOT_PROTOCOL 1 +/* Use the HID_ASCII_TO_KEYCODE lookup if CFG_TUD_HID_KEYBOARD is enabled. + * This will occupies 256 bytes of ROM. It will also enable the use of 2 extra APIs + * - tud_hid_keyboard_send_char() + * - tud_hid_keyboard_send_string() + */ +#define CFG_TUD_HID_ASCII_TO_KEYCODE_LOOKUP 1 + //-------------------------------------------------------------------- // USB RAM PLACEMENT //-------------------------------------------------------------------- diff --git a/src/class/hid/hid.h b/src/class/hid/hid.h index a12a13800..c898b09d4 100644 --- a/src/class/hid/hid.h +++ b/src/class/hid/hid.h @@ -217,101 +217,122 @@ typedef enum /// @} -#define HID_KEYCODE_TABLE(ENTRY) \ - ENTRY( 0x04, 'a' , 'A' )\ - ENTRY( 0x05, 'b' , 'B' )\ - ENTRY( 0x06, 'c' , 'C' )\ - ENTRY( 0x07, 'd' , 'D' )\ - ENTRY( 0x08, 'e' , 'E' )\ - ENTRY( 0x09, 'f' , 'F' )\ - ENTRY( 0x0a, 'g' , 'G' )\ - ENTRY( 0x0b, 'h' , 'H' )\ - ENTRY( 0x0c, 'i' , 'I' )\ - ENTRY( 0x0d, 'j' , 'J' )\ - ENTRY( 0x0e, 'k' , 'K' )\ - ENTRY( 0x0f, 'l' , 'L' )\ - ENTRY( 0x10, 'm' , 'M' )\ - ENTRY( 0x11, 'n' , 'N' )\ - ENTRY( 0x12, 'o' , 'O' )\ - ENTRY( 0x13, 'p' , 'P' )\ - ENTRY( 0x14, 'q' , 'Q' )\ - ENTRY( 0x15, 'r' , 'R' )\ - ENTRY( 0x16, 's' , 'S' )\ - ENTRY( 0x17, 't' , 'T' )\ - ENTRY( 0x18, 'u' , 'U' )\ - ENTRY( 0x19, 'v' , 'V' )\ - ENTRY( 0x1a, 'w' , 'W' )\ - ENTRY( 0x1b, 'x' , 'X' )\ - ENTRY( 0x1c, 'y' , 'Y' )\ - ENTRY( 0x1d, 'z' , 'Z' )\ - \ - ENTRY( 0x1e, '1' , '!' )\ - ENTRY( 0x1f, '2' , '@' )\ - ENTRY( 0x20, '3' , '#' )\ - ENTRY( 0x21, '4' , '$' )\ - ENTRY( 0x22, '5' , '%' )\ - ENTRY( 0x23, '6' , '^' )\ - ENTRY( 0x24, '7' , '&' )\ - ENTRY( 0x25, '8' , '*' )\ - ENTRY( 0x26, '9' , '(' )\ - ENTRY( 0x27, '0' , ')' )\ - \ - ENTRY( 0x28, '\r' , '\r' )\ - ENTRY( 0x29, '\x1b', '\x1b' )\ - ENTRY( 0x2a, '\b' , '\b' )\ - ENTRY( 0x2b, '\t' , '\t' )\ - ENTRY( 0x2c, ' ' , ' ' )\ - ENTRY( 0x2d, '-' , '_' )\ - ENTRY( 0x2e, '=' , '+' )\ - ENTRY( 0x2f, '[' , '{' )\ - ENTRY( 0x30, ']' , '}' )\ - ENTRY( 0x31, '\\' , '|' )\ - ENTRY( 0x32, '#' , '~' ) /* TODO non-US keyboard */ \ - ENTRY( 0x33, ';' , ':' )\ - ENTRY( 0x34, '\'' , '\"' )\ - ENTRY( 0x35, 0 , 0 )\ - ENTRY( 0x36, ',' , '<' )\ - ENTRY( 0x37, '.' , '>' )\ - ENTRY( 0x38, '/' , '?' )\ - ENTRY( 0x39, 0 , 0 ) /* TODO CapsLock, non-locking key implementation*/ \ - \ - ENTRY( 0x54, '/' , '/' )\ - ENTRY( 0x55, '*' , '*' )\ - ENTRY( 0x56, '-' , '-' )\ - ENTRY( 0x57, '+' , '+' )\ - ENTRY( 0x58, '\r' , '\r' )\ - ENTRY( 0x59, '1' , 0 ) /* numpad1 & end */ \ - ENTRY( 0x5a, '2' , 0 )\ - ENTRY( 0x5b, '3' , 0 )\ - ENTRY( 0x5c, '4' , 0 )\ - ENTRY( 0x5d, '5' , '5' )\ - ENTRY( 0x5e, '6' , 0 )\ - ENTRY( 0x5f, '7' , 0 )\ - ENTRY( 0x60, '8' , 0 )\ - ENTRY( 0x61, '9' , 0 )\ - ENTRY( 0x62, '0' , 0 )\ - ENTRY( 0x63, '0' , 0 )\ - ENTRY( 0x67, '=' , '=' )\ - - - -// TODO HID complete keycode table - -//enum -//{ -// KEYBOARD_KEYCODE_A = 0x04, -// KEYBOARD_KEYCODE_Z = 0x1d, -// -// KEYBOARD_KEYCODE_1 = 0x1e, -// KEYBOARD_KEYCODE_0 = 0x27, -// -// KEYBOARD_KEYCODE_ENTER = 0x28, -// KEYBOARD_KEYCODE_ESCAPE = 0x29, -// KEYBOARD_KEYCODE_BACKSPACE = 0x2a, -// KEYBOARD_KEYCODE_TAB = 0x2b, -// KEYBOARD_KEYCODE_SPACEBAR = 0x2c, -// -//}; +//--------------------------------------------------------------------+ +// HID KEYCODE +//--------------------------------------------------------------------+ +#define HID_KEY_NONE 0x00 +#define HID_KEY_A 0x04 +#define HID_KEY_B 0x05 +#define HID_KEY_C 0x06 +#define HID_KEY_D 0x07 +#define HID_KEY_E 0x08 +#define HID_KEY_F 0x09 +#define HID_KEY_G 0x0A +#define HID_KEY_H 0x0B +#define HID_KEY_I 0x0C +#define HID_KEY_J 0x0D +#define HID_KEY_K 0x0E +#define HID_KEY_L 0x0F +#define HID_KEY_M 0x10 +#define HID_KEY_N 0x11 +#define HID_KEY_O 0x12 +#define HID_KEY_P 0x13 +#define HID_KEY_Q 0x14 +#define HID_KEY_R 0x15 +#define HID_KEY_S 0x16 +#define HID_KEY_T 0x17 +#define HID_KEY_U 0x18 +#define HID_KEY_V 0x19 +#define HID_KEY_W 0x1A +#define HID_KEY_X 0x1B +#define HID_KEY_Y 0x1C +#define HID_KEY_Z 0x1D +#define HID_KEY_1 0x1E +#define HID_KEY_2 0x1F +#define HID_KEY_3 0x20 +#define HID_KEY_4 0x21 +#define HID_KEY_5 0x22 +#define HID_KEY_6 0x23 +#define HID_KEY_7 0x24 +#define HID_KEY_8 0x25 +#define HID_KEY_9 0x26 +#define HID_KEY_0 0x27 +#define HID_KEY_RETURN 0x28 +#define HID_KEY_ESCAPE 0x29 +#define HID_KEY_BACKSPACE 0x2A +#define HID_KEY_TAB 0x2B +#define HID_KEY_SPACE 0x2C +#define HID_KEY_MINUS 0x2D +#define HID_KEY_EQUAL 0x2E +#define HID_KEY_BRACKET_LEFT 0x2F +#define HID_KEY_BRACKET_RIGHT 0x30 +#define HID_KEY_BACKSLASH 0x31 +#define HID_KEY_EUROPE_1 0x32 +#define HID_KEY_SEMICOLON 0x33 +#define HID_KEY_APOSTROPHE 0x34 +#define HID_KEY_GRAVE 0x35 +#define HID_KEY_COMMA 0x36 +#define HID_KEY_PERIOD 0x37 +#define HID_KEY_SLASH 0x38 +#define HID_KEY_CAPS_LOCK 0x39 +#define HID_KEY_F1 0x3A +#define HID_KEY_F2 0x3B +#define HID_KEY_F3 0x3C +#define HID_KEY_F4 0x3D +#define HID_KEY_F5 0x3E +#define HID_KEY_F6 0x3F +#define HID_KEY_F7 0x40 +#define HID_KEY_F8 0x41 +#define HID_KEY_F9 0x42 +#define HID_KEY_F10 0x43 +#define HID_KEY_F11 0x44 +#define HID_KEY_F12 0x45 +#define HID_KEY_PRINT_SCREEN 0x46 +#define HID_KEY_SCROLL_LOCK 0x47 +#define HID_KEY_PAUSE 0x48 +#define HID_KEY_INSERT 0x49 +#define HID_KEY_HOME 0x4A +#define HID_KEY_PAGE_UP 0x4B +#define HID_KEY_DELETE 0x4C +#define HID_KEY_END 0x4D +#define HID_KEY_PAGE_DOWN 0x4E +#define HID_KEY_ARROW_RIGHT 0x4F +#define HID_KEY_ARROW_LEFT 0x50 +#define HID_KEY_ARROW_DOWN 0x51 +#define HID_KEY_ARROW_UP 0x52 +#define HID_KEY_NUM_LOCK 0x53 +#define HID_KEY_KEYPAD_DIVIDE 0x54 +#define HID_KEY_KEYPAD_MULTIPLY 0x55 +#define HID_KEY_KEYPAD_SUBTRACT 0x56 +#define HID_KEY_KEYPAD_ADD 0x57 +#define HID_KEY_KEYPAD_ENTER 0x58 +#define HID_KEY_KEYPAD_1 0x59 +#define HID_KEY_KEYPAD_2 0x5A +#define HID_KEY_KEYPAD_3 0x5B +#define HID_KEY_KEYPAD_4 0x5C +#define HID_KEY_KEYPAD_5 0x5D +#define HID_KEY_KEYPAD_6 0x5E +#define HID_KEY_KEYPAD_7 0x5F +#define HID_KEY_KEYPAD_8 0x60 +#define HID_KEY_KEYPAD_9 0x61 +#define HID_KEY_KEYPAD_0 0x62 +#define HID_KEY_KEYPAD_DECIMAL 0x63 +#define HID_KEY_EUROPE_2 0x64 +#define HID_KEY_APPLICATION 0x65 +#define HID_KEY_POWER 0x66 +#define HID_KEY_KEYPAD_EQUAL 0x67 +#define HID_KEY_F13 0x68 +#define HID_KEY_F14 0x69 +#define HID_KEY_F15 0x6A +#define HID_KEY_CONTROL_LEFT 0xE0 +#define HID_KEY_SHIFT_LEFT 0xE1 +#define HID_KEY_ALT_LEFT 0xE2 +#define HID_KEY_GUI_LEFT 0xE3 +#define HID_KEY_CONTROL_RIGHT 0xE4 +#define HID_KEY_SHIFT_RIGHT 0xE5 +#define HID_KEY_ALT_RIGHT 0xE6 +#define HID_KEY_GUI_RIGHT 0xE7 + //--------------------------------------------------------------------+ // REPORT DESCRIPTOR diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index 7b2c1da2d..f2d89250c 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -45,6 +45,7 @@ // INCLUDE //--------------------------------------------------------------------+ #include "common/tusb_common.h" +#include "common/timeout_timer.h" #include "hid_device.h" #include "device/usbd_pvt.h" @@ -91,16 +92,71 @@ bool tud_hid_keyboard_busy(void) return dcd_edpt_busy(TUD_OPT_RHPORT, _kbd_itf.ep_in); } -tusb_error_t tud_hid_keyboard_send(hid_keyboard_report_t const *p_report) +bool tud_hid_keyboard_send_report(hid_keyboard_report_t const *p_report) { - VERIFY(tud_mounted(), TUSB_ERROR_USBD_DEVICE_NOT_CONFIGURED); + VERIFY( tud_mounted() && !tud_hid_keyboard_busy() ); - hidd_interface_t * p_kbd = &_kbd_itf; + hidd_interface_t * p_hid = &_kbd_itf; - TU_ASSERT( dcd_edpt_xfer(TUD_OPT_RHPORT, p_kbd->ep_in, (void*) p_report, sizeof(hid_keyboard_report_t)), TUSB_ERROR_DCD_EDPT_XFER ) ; + if ( p_report ) + { + memcpy(p_hid->report_buf, p_report, sizeof(hid_keyboard_report_t)); + }else + { + // empty report + arrclr_(p_hid->report_buf); + } - return TUSB_ERROR_NONE; + return dcd_edpt_xfer(TUD_OPT_RHPORT, p_hid->ep_in, p_hid->report_buf, sizeof(hid_keyboard_report_t)); +} + +bool tud_hid_keyboard_send_keycode(uint8_t modifier, uint8_t keycode[6]) +{ + hid_keyboard_report_t report = { .modifier = modifier }; + memcpy(report.keycode, keycode, 6); + + return tud_hid_keyboard_send_report(&report); } + +#if CFG_TUD_HID_ASCII_TO_KEYCODE_LOOKUP + +bool tud_hid_keyboard_send_char(char ch) +{ + hid_keyboard_report_t report; + varclr_(&report); + + report.modifier = ( HID_ASCII_TO_KEYCODE[(uint8_t)ch].shift ) ? KEYBOARD_MODIFIER_LEFTSHIFT : 0; + report.keycode[0] = HID_ASCII_TO_KEYCODE[(uint8_t)ch].keycode; + + return tud_hid_keyboard_send_report(&report); +} + +bool tud_hid_keyboard_send_string(const char* str, uint32_t interval_ms) +{ + // Send each key in string + char ch; + while( (ch = *str++) != 0 ) + { + char lookahead = *str; + + tud_hid_keyboard_send_char(ch); + + // Blocking delay + timeout_blocking_wait(interval_ms); + + /* Only need to empty report if the next character is NULL or the same with + * the current one, else no need to send */ + if ( lookahead == ch || lookahead == 0 ) + { + tud_hid_keyboard_send_report(NULL); + timeout_blocking_wait(interval_ms); + } + } + +} + +#endif // CFG_TUD_HID_ASCII_TO_KEYCODE_LOOKUP + #endif //--------------------------------------------------------------------+ @@ -112,15 +168,14 @@ bool tud_hid_mouse_is_busy(void) return dcd_edpt_busy(TUD_OPT_RHPORT, _mse_itf.ep_in); } -tusb_error_t tud_hid_mouse_send(hid_mouse_report_t const *p_report) +bool tud_hid_mouse_send(hid_mouse_report_t const *p_report) { - VERIFY(tud_mounted(), TUSB_ERROR_USBD_DEVICE_NOT_CONFIGURED); - - hidd_interface_t * p_mouse = &_mse_itf; + VERIFY( tud_mounted() && !tud_hid_mouse_is_busy() ); - TU_ASSERT( dcd_edpt_xfer(TUD_OPT_RHPORT, p_mouse->ep_in, (void*) p_report, sizeof(hid_mouse_report_t)), TUSB_ERROR_DCD_EDPT_XFER ) ; + hidd_interface_t * p_hid = &_mse_itf; + memcpy(p_hid->report_buf, p_report, sizeof(hid_mouse_report_t)); - return TUSB_ERROR_NONE; + return dcd_edpt_xfer(TUD_OPT_RHPORT, p_hid->ep_in, p_hid->report_buf, sizeof(hid_mouse_report_t)); } #endif @@ -327,4 +382,143 @@ tusb_error_t hidd_xfer_cb(uint8_t rhport, uint8_t edpt_addr, tusb_event_t event, return TUSB_ERROR_NONE; } + +/*------------------------------------------------------------------*/ +/* Ascii to Keycode + *------------------------------------------------------------------*/ +const hid_ascii_to_keycode_entry_t HID_ASCII_TO_KEYCODE[128] = +{ + {0, 0 }, // 0x00 Null + {0, 0 }, // 0x01 + {0, 0 }, // 0x02 + {0, 0 }, // 0x03 + {0, 0 }, // 0x04 + {0, 0 }, // 0x05 + {0, 0 }, // 0x06 + {0, 0 }, // 0x07 + {0, HID_KEY_BACKSPACE }, // 0x08 Backspace + {0, HID_KEY_TAB }, // 0x09 Horizontal Tab + {0, HID_KEY_RETURN }, // 0x0A Line Feed + {0, 0 }, // 0x0B + {0, 0 }, // 0x0C + {0, HID_KEY_RETURN }, // 0x0D Carriage return + {0, 0 }, // 0x0E + {0, 0 }, // 0x0F + {0, 0 }, // 0x10 + {0, 0 }, // 0x11 + {0, 0 }, // 0x12 + {0, 0 }, // 0x13 + {0, 0 }, // 0x14 + {0, 0 }, // 0x15 + {0, 0 }, // 0x16 + {0, 0 }, // 0x17 + {0, 0 }, // 0x18 + {0, 0 }, // 0x19 + {0, 0 }, // 0x1A + {0, HID_KEY_ESCAPE }, // 0x1B Escape + {0, 0 }, // 0x1C + {0, 0 }, // 0x1D + {0, 0 }, // 0x1E + {0, 0 }, // 0x1F + + {0, HID_KEY_SPACE }, // 0x20 + {1, HID_KEY_1 }, // 0x21 ! + {1, HID_KEY_APOSTROPHE }, // 0x22 " + {1, HID_KEY_3 }, // 0x23 # + {1, HID_KEY_4 }, // 0x24 $ + {1, HID_KEY_5 }, // 0x25 % + {1, HID_KEY_7 }, // 0x26 & + {0, HID_KEY_APOSTROPHE }, // 0x27 ' + {1, HID_KEY_9 }, // 0x28 ( + {1, HID_KEY_0 }, // 0x29 ) + {1, HID_KEY_8 }, // 0x2A * + {1, HID_KEY_EQUAL }, // 0x2B + + {0, HID_KEY_COMMA }, // 0x2C , + {0, HID_KEY_MINUS }, // 0x2D - + {0, HID_KEY_PERIOD }, // 0x2E . + {0, HID_KEY_SLASH }, // 0x2F / + {0, HID_KEY_0 }, // 0x30 0 + {0, HID_KEY_1 }, // 0x31 1 + {0, HID_KEY_2 }, // 0x32 2 + {0, HID_KEY_3 }, // 0x33 3 + {0, HID_KEY_4 }, // 0x34 4 + {0, HID_KEY_5 }, // 0x35 5 + {0, HID_KEY_6 }, // 0x36 6 + {0, HID_KEY_7 }, // 0x37 7 + {0, HID_KEY_8 }, // 0x38 8 + {0, HID_KEY_9 }, // 0x39 9 + {1, HID_KEY_SEMICOLON }, // 0x3A : + {0, HID_KEY_SEMICOLON }, // 0x3B ; + {1, HID_KEY_COMMA }, // 0x3C < + {0, HID_KEY_EQUAL }, // 0x3D = + {1, HID_KEY_PERIOD }, // 0x3E > + {1, HID_KEY_SLASH }, // 0x3F ? + + {1, HID_KEY_2 }, // 0x40 @ + {1, HID_KEY_A }, // 0x41 A + {1, HID_KEY_B }, // 0x42 B + {1, HID_KEY_C }, // 0x43 C + {1, HID_KEY_D }, // 0x44 D + {1, HID_KEY_E }, // 0x45 E + {1, HID_KEY_F }, // 0x46 F + {1, HID_KEY_G }, // 0x47 G + {1, HID_KEY_H }, // 0x48 H + {1, HID_KEY_I }, // 0x49 I + {1, HID_KEY_J }, // 0x4A J + {1, HID_KEY_K }, // 0x4B K + {1, HID_KEY_L }, // 0x4C L + {1, HID_KEY_M }, // 0x4D M + {1, HID_KEY_N }, // 0x4E N + {1, HID_KEY_O }, // 0x4F O + {1, HID_KEY_P }, // 0x50 P + {1, HID_KEY_Q }, // 0x51 Q + {1, HID_KEY_R }, // 0x52 R + {1, HID_KEY_S }, // 0x53 S + {1, HID_KEY_T }, // 0x55 T + {1, HID_KEY_U }, // 0x55 U + {1, HID_KEY_V }, // 0x56 V + {1, HID_KEY_W }, // 0x57 W + {1, HID_KEY_X }, // 0x58 X + {1, HID_KEY_Y }, // 0x59 Y + {1, HID_KEY_Z }, // 0x5A Z + {0, HID_KEY_BRACKET_LEFT }, // 0x5B [ + {0, HID_KEY_BACKSLASH }, // 0x5C '\' + {0, HID_KEY_BRACKET_RIGHT }, // 0x5D ] + {1, HID_KEY_6 }, // 0x5E ^ + {1, HID_KEY_MINUS }, // 0x5F _ + + {0, HID_KEY_GRAVE }, // 0x60 ` + {0, HID_KEY_A }, // 0x61 a + {0, HID_KEY_B }, // 0x62 b + {0, HID_KEY_C }, // 0x63 c + {0, HID_KEY_D }, // 0x66 d + {0, HID_KEY_E }, // 0x65 e + {0, HID_KEY_F }, // 0x66 f + {0, HID_KEY_G }, // 0x67 g + {0, HID_KEY_H }, // 0x68 h + {0, HID_KEY_I }, // 0x69 i + {0, HID_KEY_J }, // 0x6A j + {0, HID_KEY_K }, // 0x6B k + {0, HID_KEY_L }, // 0x6C l + {0, HID_KEY_M }, // 0x6D m + {0, HID_KEY_N }, // 0x6E n + {0, HID_KEY_O }, // 0x6F o + {0, HID_KEY_P }, // 0x70 p + {0, HID_KEY_Q }, // 0x71 q + {0, HID_KEY_R }, // 0x72 r + {0, HID_KEY_S }, // 0x73 s + {0, HID_KEY_T }, // 0x75 t + {0, HID_KEY_U }, // 0x75 u + {0, HID_KEY_V }, // 0x76 v + {0, HID_KEY_W }, // 0x77 w + {0, HID_KEY_X }, // 0x78 x + {0, HID_KEY_Y }, // 0x79 y + {0, HID_KEY_Z }, // 0x7A z + {1, HID_KEY_BRACKET_LEFT }, // 0x7B { + {1, HID_KEY_BACKSLASH }, // 0x7C | + {1, HID_KEY_BRACKET_RIGHT }, // 0x7D } + {1, HID_KEY_GRAVE }, // 0x7E ~ + {0, HID_KEY_DELETE } // 0x7F Delete +}; + #endif diff --git a/src/class/hid/hid_device.h b/src/class/hid/hid_device.h index a2238473d..21561041a 100644 --- a/src/class/hid/hid_device.h +++ b/src/class/hid/hid_device.h @@ -63,22 +63,26 @@ */ bool tud_hid_keyboard_busy(void); -/** \brief Submit USB transfer - * \param[in] rhport USB Controller ID - * \param[in,out] p_report address that is used to store data from device. Must be accessible by usb controller (see \ref CFG_TUSB_ATTR_USBRAM) - * \returns \ref tusb_error_t type to indicate success or error condition. - * \retval TUSB_ERROR_NONE on success - * \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device - * \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request) - * \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct - * \note This function is non-blocking and returns immediately. Data will be transferred when USB Host work with this interface. - * The result of usb transfer will be reported by the interface's callback function +/** \brief Send a keyboard report + * \param[in,out] p_report Report data, if NULL, an empty report (all zeroes) is used + * \returns true on success, false otherwise (not mounted or busy) */ -tusb_error_t tud_hid_keyboard_send(hid_keyboard_report_t const *p_report); +bool tud_hid_keyboard_send_report(hid_keyboard_report_t const *p_report); -//--------------------------------------------------------------------+ -// APPLICATION CALLBACK API -//--------------------------------------------------------------------+ +bool tud_hid_keyboard_send_keycode(uint8_t modifier, uint8_t keycode[6]); + +#if CFG_TUD_HID_ASCII_TO_KEYCODE_LOOKUP +bool tud_hid_keyboard_send_char(char ch); +bool tud_hid_keyboard_send_string(const char* str, uint32_t interval_ms); + +typedef struct{ + uint8_t shift; + uint8_t keycode; +}hid_ascii_to_keycode_entry_t; +extern const hid_ascii_to_keycode_entry_t HID_ASCII_TO_KEYCODE[128]; +#endif + +/*------------- Callbacks -------------*/ /** \brief Callback function that is invoked when USB host request \ref HID_REQUEST_CONTROL_GET_REPORT * via control endpoint. @@ -120,23 +124,15 @@ ATTR_WEAK void tud_hid_keyboard_set_report_cb(hid_report_type_t report_type, uin * \retval false if the interface is not busy meaning the stack successfully transferred data from/to host * \note This function is primarily used for polling/waiting result after \ref tusbd_hid_mouse_send. */ -bool tud_hid_mouse_is_busy(void); +bool tud_hid_mouse_busy(void); /** \brief Perform transfer queuing * \param[in,out] p_report address that is used to store data from device. Must be accessible by usb controller (see \ref CFG_TUSB_ATTR_USBRAM) - * \returns \ref tusb_error_t type to indicate success or error condition. - * \retval TUSB_ERROR_NONE on success - * \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device - * \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request) - * \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct - * \note This function is non-blocking and returns immediately. Data will be transferred when USB Host work with this interface. - * The result of usb transfer will be reported by the interface's callback function + * \returns true on success, false otherwise (not mounted or busy) */ -tusb_error_t tud_hid_mouse_send(hid_mouse_report_t const *p_report); +bool tud_hid_mouse_send(hid_mouse_report_t const *p_report); -//--------------------------------------------------------------------+ -// APPLICATION CALLBACK API -//--------------------------------------------------------------------+ +/*------------- Callbacks -------------*/ /** \brief Callback function that is invoked when USB host request \ref HID_REQUEST_CONTROL_GET_REPORT * via control endpoint. diff --git a/src/common/timeout_timer.h b/src/common/timeout_timer.h index aafc8cce2..5c62c6904 100644 --- a/src/common/timeout_timer.h +++ b/src/common/timeout_timer.h @@ -67,6 +67,15 @@ static inline bool timeout_expired(timeout_timer_t* tt) return ( tusb_hal_millis() - tt->start ) >= tt->interval; } +static inline void timeout_blocking_wait(uint32_t msec) +{ + timeout_timer_t tt; + timeout_set(&tt, msec); + + // blocking delay + while ( !timeout_expired(&tt) ) { } +} + #ifdef __cplusplus } #endif -- cgit v1.3.1 From 176607dbe16207a3d2d46e9674ae15a995406478 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 23 Jul 2018 22:30:24 +0700 Subject: rename tud_hid_mouse_is_busy to tud_hid_mouse_busy --- examples/device/nrf52840/src/main.c | 3 +++ src/class/hid/hid_device.c | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) (limited to 'src/class') diff --git a/examples/device/nrf52840/src/main.c b/examples/device/nrf52840/src/main.c index 1993109b4..04d07f0a6 100644 --- a/examples/device/nrf52840/src/main.c +++ b/examples/device/nrf52840/src/main.c @@ -56,6 +56,7 @@ void print_greeting(void); void led_blinking_task(void); void virtual_com_task(void); +void usb_hid_task(void); /*------------- MAIN -------------*/ int main(void) @@ -71,6 +72,8 @@ int main(void) led_blinking_task(); virtual_com_task(); + + usb_hid_task(); } return 0; diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index f2d89250c..325485425 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -163,7 +163,7 @@ bool tud_hid_keyboard_send_string(const char* str, uint32_t interval_ms) // MOUSE APPLICATION API //--------------------------------------------------------------------+ #if CFG_TUD_HID_MOUSE -bool tud_hid_mouse_is_busy(void) +bool tud_hid_mouse_busy(void) { return dcd_edpt_busy(TUD_OPT_RHPORT, _mse_itf.ep_in); } -- cgit v1.3.1 From 361928f42983bed4d10443668d8eb3db69ade80f Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 23 Jul 2018 22:32:21 +0700 Subject: rename timeout_timer.h to tusb_timeout.h --- src/class/hid/hid_device.c | 2 +- src/common/timeout_timer.h | 85 ---------------------- src/common/tusb_timeout.h | 85 ++++++++++++++++++++++ src/host/ehci/ehci.c | 2 +- src/host/ohci/ohci.c | 2 +- .../nxp/lpc11xx_lpc13xx/dcd_lpc_11uxx_13uxx.c | 2 +- src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c | 2 +- 7 files changed, 90 insertions(+), 90 deletions(-) delete mode 100644 src/common/timeout_timer.h create mode 100644 src/common/tusb_timeout.h (limited to 'src/class') diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index 325485425..4ce927725 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -45,7 +45,7 @@ // INCLUDE //--------------------------------------------------------------------+ #include "common/tusb_common.h" -#include "common/timeout_timer.h" +#include "common/tusb_timeout.h" #include "hid_device.h" #include "device/usbd_pvt.h" diff --git a/src/common/timeout_timer.h b/src/common/timeout_timer.h deleted file mode 100644 index 5c62c6904..000000000 --- a/src/common/timeout_timer.h +++ /dev/null @@ -1,85 +0,0 @@ -/**************************************************************************/ -/*! - @file timeout_timer.h - @author hathach (tinyusb.org) - - @section LICENSE - - Software License Agreement (BSD License) - - Copyright (c) 2013, hathach (tinyusb.org) - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - 3. Neither the name of the copyright holders nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY - EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - This file is part of the tinyusb stack. -*/ -/**************************************************************************/ - -/** \ingroup Group_Common Common Files - * \defgroup Group_TimeoutTimer timeout timer - * @{ */ - - -#ifndef _TUSB_TIMEOUT_TTIMER_H_ -#define _TUSB_TIMEOUT_TTIMER_H_ - -#include "tusb_compiler.h" -#include "tusb_hal.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct { - uint32_t start; - uint32_t interval; -}timeout_timer_t; - -static inline void timeout_set(timeout_timer_t* tt, uint32_t msec) -{ - tt->interval = msec; - tt->start = tusb_hal_millis(); -} - -static inline bool timeout_expired(timeout_timer_t* tt) -{ - return ( tusb_hal_millis() - tt->start ) >= tt->interval; -} - -static inline void timeout_blocking_wait(uint32_t msec) -{ - timeout_timer_t tt; - timeout_set(&tt, msec); - - // blocking delay - while ( !timeout_expired(&tt) ) { } -} - -#ifdef __cplusplus - } -#endif - -#endif /* _TUSB_TIMEOUT_TTIMER_H_ */ - -/** @} */ diff --git a/src/common/tusb_timeout.h b/src/common/tusb_timeout.h new file mode 100644 index 000000000..400434708 --- /dev/null +++ b/src/common/tusb_timeout.h @@ -0,0 +1,85 @@ +/**************************************************************************/ +/*! + @file tusb_timeout.h + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +/** \ingroup Group_Common Common Files + * \defgroup Group_TimeoutTimer timeout timer + * @{ */ + + +#ifndef _TUSB_TIMEOUT_H_ +#define _TUSB_TIMEOUT_H_ + +#include "tusb_compiler.h" +#include "tusb_hal.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct { + uint32_t start; + uint32_t interval; +}timeout_timer_t; + +static inline void timeout_set(timeout_timer_t* tt, uint32_t msec) +{ + tt->interval = msec; + tt->start = tusb_hal_millis(); +} + +static inline bool timeout_expired(timeout_timer_t* tt) +{ + return ( tusb_hal_millis() - tt->start ) >= tt->interval; +} + +static inline void timeout_blocking_wait(uint32_t msec) +{ + timeout_timer_t tt; + timeout_set(&tt, msec); + + // blocking delay + while ( !timeout_expired(&tt) ) { } +} + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_TIMEOUT_H_ */ + +/** @} */ diff --git a/src/host/ehci/ehci.c b/src/host/ehci/ehci.c index c9cd39378..9e326ec53 100644 --- a/src/host/ehci/ehci.c +++ b/src/host/ehci/ehci.c @@ -44,7 +44,7 @@ //--------------------------------------------------------------------+ #include "hal/hal.h" #include "osal/osal.h" -#include "common/timeout_timer.h" +#include "common/tusb_timeout.h" #include "../hcd.h" #include "../usbh_hcd.h" diff --git a/src/host/ohci/ohci.c b/src/host/ohci/ohci.c index 5788aac94..73e9d887e 100644 --- a/src/host/ohci/ohci.c +++ b/src/host/ohci/ohci.c @@ -44,7 +44,7 @@ //--------------------------------------------------------------------+ #include "hal/hal.h" #include "osal/osal.h" -#include "common/timeout_timer.h" +#include "common/tusb_timeout.h" #include "../hcd.h" #include "../usbh_hcd.h" diff --git a/src/portable/nxp/lpc11xx_lpc13xx/dcd_lpc_11uxx_13uxx.c b/src/portable/nxp/lpc11xx_lpc13xx/dcd_lpc_11uxx_13uxx.c index f0472f41d..0bb79090e 100644 --- a/src/portable/nxp/lpc11xx_lpc13xx/dcd_lpc_11uxx_13uxx.c +++ b/src/portable/nxp/lpc11xx_lpc13xx/dcd_lpc_11uxx_13uxx.c @@ -51,7 +51,7 @@ #include "common/tusb_common.h" #include "hal/hal.h" #include "osal/osal.h" -#include "common/timeout_timer.h" +#include "common/tusb_timeout.h" #include "device/dcd.h" #include "usbd_dcd.h" diff --git a/src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c b/src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c index a08e20a3f..6c076baa8 100644 --- a/src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c +++ b/src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c @@ -46,7 +46,7 @@ #include "common/tusb_common.h" #include "tusb_hal.h" #include "osal/osal.h" -#include "common/timeout_timer.h" +#include "common/tusb_timeout.h" #include "device/dcd.h" #include "dcd_lpc43xx.h" -- cgit v1.3.1 From 51903a60c51bd1006bec9266dbe1bfb35e282675 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 23 Jul 2018 22:36:29 +0700 Subject: rename timeout_ API to tu_timeout API --- src/class/hid/hid_device.c | 6 +++--- src/common/tusb_timeout.h | 14 +++++++------- src/host/ehci/ehci.c | 8 ++++---- src/portable/nxp/lpc43xx_lpc18xx/hal_lpc43xx.c | 8 ++++---- 4 files changed, 18 insertions(+), 18 deletions(-) (limited to 'src/class') diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index 4ce927725..82c7e3d3f 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -142,14 +142,14 @@ bool tud_hid_keyboard_send_string(const char* str, uint32_t interval_ms) tud_hid_keyboard_send_char(ch); // Blocking delay - timeout_blocking_wait(interval_ms); + tu_timeout_wait(interval_ms); /* Only need to empty report if the next character is NULL or the same with * the current one, else no need to send */ if ( lookahead == ch || lookahead == 0 ) { tud_hid_keyboard_send_report(NULL); - timeout_blocking_wait(interval_ms); + tu_timeout_wait(interval_ms); } } @@ -170,7 +170,7 @@ bool tud_hid_mouse_busy(void) bool tud_hid_mouse_send(hid_mouse_report_t const *p_report) { - VERIFY( tud_mounted() && !tud_hid_mouse_is_busy() ); + VERIFY( tud_mounted() && !tud_hid_mouse_busy() ); hidd_interface_t * p_hid = &_mse_itf; memcpy(p_hid->report_buf, p_report, sizeof(hid_mouse_report_t)); diff --git a/src/common/tusb_timeout.h b/src/common/tusb_timeout.h index 400434708..7c51ff36f 100644 --- a/src/common/tusb_timeout.h +++ b/src/common/tusb_timeout.h @@ -54,26 +54,26 @@ extern "C" { typedef struct { uint32_t start; uint32_t interval; -}timeout_timer_t; +}tu_timeout_t; -static inline void timeout_set(timeout_timer_t* tt, uint32_t msec) +static inline void tu_timeout_set(tu_timeout_t* tt, uint32_t msec) { tt->interval = msec; tt->start = tusb_hal_millis(); } -static inline bool timeout_expired(timeout_timer_t* tt) +static inline bool tu_timeout_expired(tu_timeout_t* tt) { return ( tusb_hal_millis() - tt->start ) >= tt->interval; } -static inline void timeout_blocking_wait(uint32_t msec) +static inline void tu_timeout_wait(uint32_t msec) { - timeout_timer_t tt; - timeout_set(&tt, msec); + tu_timeout_t tt; + tu_timeout_set(&tt, msec); // blocking delay - while ( !timeout_expired(&tt) ) { } + while ( !tu_timeout_expired(&tt) ) { } } #ifdef __cplusplus diff --git a/src/host/ehci/ehci.c b/src/host/ehci/ehci.c index 9e326ec53..ba23319ca 100644 --- a/src/host/ehci/ehci.c +++ b/src/host/ehci/ehci.c @@ -268,14 +268,14 @@ static tusb_error_t hcd_controller_init(uint8_t hostid) static tusb_error_t hcd_controller_stop(uint8_t hostid) { ehci_registers_t* const regs = get_operational_register(hostid); - timeout_timer_t timeout; + tu_timeout_t timeout; regs->usb_cmd_bit.run_stop = 0; - timeout_set(&timeout, 2); // USB Spec: controller has to stop within 16 uframe = 2 frames - while( regs->usb_sts_bit.hc_halted == 0 && !timeout_expired(&timeout)) {} + tu_timeout_set(&timeout, 2); // USB Spec: controller has to stop within 16 uframe = 2 frames + while( regs->usb_sts_bit.hc_halted == 0 && !tu_timeout_expired(&timeout)) {} - return timeout_expired(&timeout) ? TUSB_ERROR_OSAL_TIMEOUT : TUSB_ERROR_NONE; + return tu_timeout_expired(&timeout) ? TUSB_ERROR_OSAL_TIMEOUT : TUSB_ERROR_NONE; } //--------------------------------------------------------------------+ diff --git a/src/portable/nxp/lpc43xx_lpc18xx/hal_lpc43xx.c b/src/portable/nxp/lpc43xx_lpc18xx/hal_lpc43xx.c index 92f9f1cf0..18745d03e 100644 --- a/src/portable/nxp/lpc43xx_lpc18xx/hal_lpc43xx.c +++ b/src/portable/nxp/lpc43xx_lpc18xx/hal_lpc43xx.c @@ -72,11 +72,11 @@ static void hal_controller_reset(uint8_t rhport) // NXP chip powered with non-host mode --> sts bit is not correctly reflected (*p_reg_usbcmd) |= BIT_(1); -// timeout_timer_t timeout; -// timeout_set(&timeout, 2); // should not take longer the time to stop controller - while( ((*p_reg_usbcmd) & BIT_(1)) /*&& !timeout_expired(&timeout)*/) {} +// tu_timeout_t timeout; +// tu_timeout_set(&timeout, 2); // should not take longer the time to stop controller + while( ((*p_reg_usbcmd) & BIT_(1)) /*&& !tu_timeout_expired(&timeout)*/) {} // -// return timeout_expired(&timeout) ? TUSB_ERROR_OSAL_TIMEOUT : TUSB_ERROR_NONE; +// return tu_timeout_expired(&timeout) ? TUSB_ERROR_OSAL_TIMEOUT : TUSB_ERROR_NONE; } bool tusb_hal_init(void) -- cgit v1.3.1 From 5f6cd4903101b0486771efdb2bb435ddf6cf8e7a Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 23 Jul 2018 23:41:14 +0700 Subject: clean up include --- src/class/hid/hid_device.c | 1 - src/common/tusb_common.h | 6 ++---- src/common/tusb_timeout.h | 15 ++++++++++++++- src/host/ehci/ehci.c | 1 - src/host/ohci/ohci.c | 1 - src/portable/nxp/lpc11xx_lpc13xx/dcd_lpc_11uxx_13uxx.c | 1 - src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c | 1 - 7 files changed, 16 insertions(+), 10 deletions(-) (limited to 'src/class') diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index 82c7e3d3f..7aca8ef8e 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -45,7 +45,6 @@ // INCLUDE //--------------------------------------------------------------------+ #include "common/tusb_common.h" -#include "common/tusb_timeout.h" #include "hid_device.h" #include "device/usbd_pvt.h" diff --git a/src/common/tusb_common.h b/src/common/tusb_common.h index ddfceabdb..44f31ffe0 100644 --- a/src/common/tusb_common.h +++ b/src/common/tusb_common.h @@ -61,15 +61,13 @@ //------------- TUSB Option Header -------------// #include "tusb_option.h" -//------------- General Header -------------// +//------------- Common Header -------------// #include "tusb_compiler.h" #include "tusb_verify.h" #include "binary.h" #include "tusb_error.h" -#include "tusb_hal.h" #include "tusb_fifo.h" - -//------------- TUSB Header -------------// +#include "tusb_timeout.h" #include "tusb_types.h" //--------------------------------------------------------------------+ diff --git a/src/common/tusb_timeout.h b/src/common/tusb_timeout.h index 7c51ff36f..9d80f5fe7 100644 --- a/src/common/tusb_timeout.h +++ b/src/common/tusb_timeout.h @@ -45,7 +45,6 @@ #define _TUSB_TIMEOUT_H_ #include "tusb_compiler.h" -#include "tusb_hal.h" #ifdef __cplusplus extern "C" { @@ -56,6 +55,8 @@ typedef struct { uint32_t interval; }tu_timeout_t; +extern uint32_t tusb_hal_millis(void); + static inline void tu_timeout_set(tu_timeout_t* tt, uint32_t msec) { tt->interval = msec; @@ -67,6 +68,18 @@ static inline bool tu_timeout_expired(tu_timeout_t* tt) return ( tusb_hal_millis() - tt->start ) >= tt->interval; } +// For used with periodic event to prevent drift +static inline void tu_timeout_reset(tu_timeout_t* tt) +{ + tt->start += tt->interval; +} + +static inline void tu_timeout_restart(tu_timeout_t* tt) +{ + tt->start = tusb_hal_millis(); +} + + static inline void tu_timeout_wait(uint32_t msec) { tu_timeout_t tt; diff --git a/src/host/ehci/ehci.c b/src/host/ehci/ehci.c index ba23319ca..09f2f573a 100644 --- a/src/host/ehci/ehci.c +++ b/src/host/ehci/ehci.c @@ -44,7 +44,6 @@ //--------------------------------------------------------------------+ #include "hal/hal.h" #include "osal/osal.h" -#include "common/tusb_timeout.h" #include "../hcd.h" #include "../usbh_hcd.h" diff --git a/src/host/ohci/ohci.c b/src/host/ohci/ohci.c index 73e9d887e..644dbfa0f 100644 --- a/src/host/ohci/ohci.c +++ b/src/host/ohci/ohci.c @@ -44,7 +44,6 @@ //--------------------------------------------------------------------+ #include "hal/hal.h" #include "osal/osal.h" -#include "common/tusb_timeout.h" #include "../hcd.h" #include "../usbh_hcd.h" diff --git a/src/portable/nxp/lpc11xx_lpc13xx/dcd_lpc_11uxx_13uxx.c b/src/portable/nxp/lpc11xx_lpc13xx/dcd_lpc_11uxx_13uxx.c index 0bb79090e..68eef47e1 100644 --- a/src/portable/nxp/lpc11xx_lpc13xx/dcd_lpc_11uxx_13uxx.c +++ b/src/portable/nxp/lpc11xx_lpc13xx/dcd_lpc_11uxx_13uxx.c @@ -51,7 +51,6 @@ #include "common/tusb_common.h" #include "hal/hal.h" #include "osal/osal.h" -#include "common/tusb_timeout.h" #include "device/dcd.h" #include "usbd_dcd.h" diff --git a/src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c b/src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c index 6c076baa8..0b48ad1e6 100644 --- a/src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c +++ b/src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c @@ -46,7 +46,6 @@ #include "common/tusb_common.h" #include "tusb_hal.h" #include "osal/osal.h" -#include "common/tusb_timeout.h" #include "device/dcd.h" #include "dcd_lpc43xx.h" -- cgit v1.3.1 From 3400dfdf4ea478894b2a96ac0bd27868c052fbeb Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 24 Jul 2018 00:45:07 +0700 Subject: nrf52840 boot mouse does not work, need more work --- examples/device/nrf52840/src/main.c | 32 ++++++++++++++-------- src/class/hid/hid.h | 9 ++++--- src/class/hid/hid_device.c | 2 +- src/class/hid/hid_device.h | 8 +++--- src/device/usbd_desc.c | 54 ++++++++++++++++++++++--------------- 5 files changed, 64 insertions(+), 41 deletions(-) (limited to 'src/class') diff --git a/examples/device/nrf52840/src/main.c b/examples/device/nrf52840/src/main.c index cc18cce24..1f7f5b22e 100644 --- a/examples/device/nrf52840/src/main.c +++ b/examples/device/nrf52840/src/main.c @@ -98,29 +98,25 @@ void virtual_com_task(void) } //--------------------------------------------------------------------+ -// USB CDC +// USB HID //--------------------------------------------------------------------+ void usb_hid_task(void) { if ( tud_mounted() ) { - if ( !tud_hid_keyboard_busy() ) - { - // Poll every 10ms - static tu_timeout_t tm = { .start = 0, .interval = 10 }; - if ( !tu_timeout_expired(&tm) ) return; // not enough time - tu_timeout_reset(&tm); - - uint32_t bt = board_buttons(); - if ( bt ) + /*------------- Keyboard -------------*/ +/* + if ( !tud_hid_keyboard_busy() ) + { + if ( btn ) { uint8_t keycode[6] = { 0 }; for(uint8_t i=0; i < 6; i++) { - if ( bt & (1 << i) ) keycode[i] = HID_KEY_A + i; + if ( btn & (1 << i) ) keycode[i] = HID_KEY_A + i; } tud_hid_keyboard_send_keycode(0, keycode); @@ -130,10 +126,24 @@ void usb_hid_task(void) tud_hid_keyboard_send_report(NULL); } } +*/ + /*------------- Mouse -------------*/ if ( !tud_hid_mouse_busy() ) { + // Poll every 10ms + static tu_timeout_t tm = { .start = 0, .interval = 10 }; + if ( !tu_timeout_expired(&tm) ) return; // not enough time + tu_timeout_reset(&tm); + + uint32_t const btn = board_buttons(); + + if ( btn ) + { + hid_mouse_report_t report = { .buttons = 0, .x = 10, .y = 0, .wheel = 0 }; + tud_hid_mouse_send_report(&report); + } } } diff --git a/src/class/hid/hid.h b/src/class/hid/hid.h index c898b09d4..9872172a9 100644 --- a/src/class/hid/hid.h +++ b/src/class/hid/hid.h @@ -167,14 +167,17 @@ typedef struct ATTR_PACKED int8_t x; /**< Current delta x movement of the mouse. */ int8_t y; /**< Current delta y movement on the mouse. */ int8_t wheel; /**< Current delta wheel movement on the mouse. */ +// int8_t pan; } hid_mouse_report_t; /// Standard Mouse Buttons Bitmap typedef enum { - MOUSE_BUTTON_LEFT = BIT_(0), ///< Left button - MOUSE_BUTTON_RIGHT = BIT_(1), ///< Right button - MOUSE_BUTTON_MIDDLE = BIT_(2) ///< Middle button + MOUSE_BUTTON_LEFT = BIT_(0), ///< Left button + MOUSE_BUTTON_RIGHT = BIT_(1), ///< Right button + MOUSE_BUTTON_MIDDLE = BIT_(2), ///< Middle button + MOUSE_BUTTON_BACKWARD = BIT_(3), ///< Backward button, + MOUSE_BUTTON_FORWARD = BIT_(4), ///< Forward button, }hid_mouse_button_bm_t; /// @} diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index 7aca8ef8e..1efceafd0 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -167,7 +167,7 @@ bool tud_hid_mouse_busy(void) return dcd_edpt_busy(TUD_OPT_RHPORT, _mse_itf.ep_in); } -bool tud_hid_mouse_send(hid_mouse_report_t const *p_report) +bool tud_hid_mouse_send_report(hid_mouse_report_t const *p_report) { VERIFY( tud_mounted() && !tud_hid_mouse_busy() ); diff --git a/src/class/hid/hid_device.h b/src/class/hid/hid_device.h index 21561041a..1293d212d 100644 --- a/src/class/hid/hid_device.h +++ b/src/class/hid/hid_device.h @@ -65,7 +65,7 @@ bool tud_hid_keyboard_busy(void); /** \brief Send a keyboard report * \param[in,out] p_report Report data, if NULL, an empty report (all zeroes) is used - * \returns true on success, false otherwise (not mounted or busy) + * \returns true on success, false otherwise (not mounted or busy) */ bool tud_hid_keyboard_send_report(hid_keyboard_report_t const *p_report); @@ -127,10 +127,10 @@ ATTR_WEAK void tud_hid_keyboard_set_report_cb(hid_report_type_t report_type, uin bool tud_hid_mouse_busy(void); /** \brief Perform transfer queuing - * \param[in,out] p_report address that is used to store data from device. Must be accessible by usb controller (see \ref CFG_TUSB_ATTR_USBRAM) - * \returns true on success, false otherwise (not mounted or busy) + * \param[in,out] p_report Report data, if NULL, an empty report (all zeroes) is used + * \returns true on success, false otherwise (not mounted or busy) */ -bool tud_hid_mouse_send(hid_mouse_report_t const *p_report); +bool tud_hid_mouse_send_report(hid_mouse_report_t const *p_report); /*------------- Callbacks -------------*/ diff --git a/src/device/usbd_desc.c b/src/device/usbd_desc.c index 452a6674e..27bf272b2 100644 --- a/src/device/usbd_desc.c +++ b/src/device/usbd_desc.c @@ -123,39 +123,45 @@ uint8_t const _desc_auto_hid_kbd_report[] = { HID_USAGE ( HID_USAGE_DESKTOP_KEYBOARD ), HID_COLLECTION ( HID_COLLECTION_APPLICATION ), HID_USAGE_PAGE ( HID_USAGE_PAGE_KEYBOARD ), + // 8 bits Modifier Keys (Shfit, Control, Alt) HID_USAGE_MIN ( 224 ), HID_USAGE_MAX ( 231 ), HID_LOGICAL_MIN ( 0 ), HID_LOGICAL_MAX ( 1 ), + HID_REPORT_COUNT ( 8 ), HID_REPORT_SIZE ( 1 ), - HID_REPORT_COUNT ( 8 ), /* 8 bits */ - HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ), /* maskable modifier key */ + HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ), - HID_REPORT_SIZE ( 8 ), + // 8 bit reserved HID_REPORT_COUNT ( 1 ), - HID_INPUT ( HID_CONSTANT ), /* reserved */ + HID_REPORT_SIZE ( 8 ), + HID_INPUT ( HID_CONSTANT ), + + // 6-byte Keycodes + HID_USAGE_PAGE (HID_USAGE_PAGE_KEYBOARD), + HID_USAGE_MIN ( 0 ), + HID_USAGE_MAX ( 255 ), + HID_LOGICAL_MIN ( 0 ), + HID_LOGICAL_MAX ( 255 ), + + HID_REPORT_COUNT ( 6 ), + HID_REPORT_SIZE ( 8 ), + HID_INPUT ( HID_DATA | HID_ARRAY | HID_ABSOLUTE ), + // LED Indicator Kana | Compose | Scroll Lock | CapsLock | NumLock HID_USAGE_PAGE ( HID_USAGE_PAGE_LED ), + /* 5-bit Led report */ HID_USAGE_MIN ( 1 ), HID_USAGE_MAX ( 5 ), HID_REPORT_COUNT ( 5 ), HID_REPORT_SIZE ( 1 ), - HID_OUTPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ), /* 5-bit Led report */ + HID_OUTPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ), - HID_REPORT_SIZE ( 3 ), /* led padding */ + /* led padding */ HID_REPORT_COUNT ( 1 ), + HID_REPORT_SIZE ( 3 ), HID_OUTPUT ( HID_CONSTANT ), - - HID_USAGE_PAGE (HID_USAGE_PAGE_KEYBOARD), - HID_USAGE_MIN ( 0 ), - HID_USAGE_MAX ( 101 ), - HID_LOGICAL_MIN ( 0 ), - HID_LOGICAL_MAX ( 101 ), - - HID_REPORT_SIZE ( 8 ), - HID_REPORT_COUNT ( 6 ), - HID_INPUT ( HID_DATA | HID_ARRAY | HID_ABSOLUTE ), /* keycodes array 6 items */ HID_COLLECTION_END }; #endif @@ -173,29 +179,33 @@ uint8_t const _desc_auto_hid_mse_report[] = { HID_COLLECTION ( HID_COLLECTION_PHYSICAL ), HID_USAGE_PAGE ( HID_USAGE_PAGE_BUTTON ), HID_USAGE_MIN ( 1 ), - HID_USAGE_MAX ( 3 ), + HID_USAGE_MAX ( 5 ), HID_LOGICAL_MIN ( 0 ), HID_LOGICAL_MAX ( 1 ), + // Left, Right, Middle, Backward, Forward mouse buttons + HID_REPORT_COUNT ( 5 ), HID_REPORT_SIZE ( 1 ), - HID_REPORT_COUNT ( 3 ), /* Left, Right and Middle mouse*/ HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ), - HID_REPORT_SIZE ( 5 ), + // 3 bit padding + HID_REPORT_SIZE ( 3 ), HID_REPORT_COUNT ( 1 ), - HID_INPUT ( HID_CONSTANT ), /* 5 bit padding followed 3 bit buttons */ + HID_INPUT ( HID_CONSTANT ), HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ), + /* X, Y position */ HID_USAGE ( HID_USAGE_DESKTOP_X ), HID_USAGE ( HID_USAGE_DESKTOP_Y ), HID_LOGICAL_MIN ( 0x81 ), /* -127 */ HID_LOGICAL_MAX ( 0x7f ), /* 127 */ + HID_REPORT_COUNT ( 2 ), HID_REPORT_SIZE ( 8 ), - HID_REPORT_COUNT ( 2 ), /* X, Y position */ HID_INPUT ( HID_DATA | HID_VARIABLE | HID_RELATIVE ), /* relative values */ - HID_USAGE ( HID_USAGE_DESKTOP_WHEEL ), /* mouse scroll */ + /* mouse scroll */ + HID_USAGE ( HID_USAGE_DESKTOP_WHEEL ), HID_LOGICAL_MIN ( 0x81 ), /* -127 */ HID_LOGICAL_MAX ( 0x7f ), /* 127 */ HID_REPORT_COUNT( 1 ), -- cgit v1.3.1 From 3dc1d847b8847ba82561df9c7b4cb62fca7938cf Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 24 Jul 2018 16:52:24 +0700 Subject: rename device keyboard api --- src/class/hid/hid_device.c | 21 +++++++++++++-------- src/class/hid/hid_device.h | 10 +++++----- 2 files changed, 18 insertions(+), 13 deletions(-) (limited to 'src/class') diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index 1efceafd0..4ea584429 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -91,7 +91,7 @@ bool tud_hid_keyboard_busy(void) return dcd_edpt_busy(TUD_OPT_RHPORT, _kbd_itf.ep_in); } -bool tud_hid_keyboard_send_report(hid_keyboard_report_t const *p_report) +bool tud_hid_keyboard_report(hid_keyboard_report_t const *p_report) { VERIFY( tud_mounted() && !tud_hid_keyboard_busy() ); @@ -109,17 +109,17 @@ bool tud_hid_keyboard_send_report(hid_keyboard_report_t const *p_report) return dcd_edpt_xfer(TUD_OPT_RHPORT, p_hid->ep_in, p_hid->report_buf, sizeof(hid_keyboard_report_t)); } -bool tud_hid_keyboard_send_keycode(uint8_t modifier, uint8_t keycode[6]) +bool tud_hid_keyboard_keycode(uint8_t modifier, uint8_t keycode[6]) { hid_keyboard_report_t report = { .modifier = modifier }; memcpy(report.keycode, keycode, 6); - return tud_hid_keyboard_send_report(&report); + return tud_hid_keyboard_report(&report); } #if CFG_TUD_HID_ASCII_TO_KEYCODE_LOOKUP -bool tud_hid_keyboard_send_char(char ch) +bool tud_hid_keyboard_key_press(char ch) { hid_keyboard_report_t report; varclr_(&report); @@ -127,10 +127,15 @@ bool tud_hid_keyboard_send_char(char ch) report.modifier = ( HID_ASCII_TO_KEYCODE[(uint8_t)ch].shift ) ? KEYBOARD_MODIFIER_LEFTSHIFT : 0; report.keycode[0] = HID_ASCII_TO_KEYCODE[(uint8_t)ch].keycode; - return tud_hid_keyboard_send_report(&report); + return tud_hid_keyboard_report(&report); } -bool tud_hid_keyboard_send_string(const char* str, uint32_t interval_ms) +bool tud_hid_keyboard_key_release(void) +{ + return tud_hid_keyboard_report(NULL); +} + +bool tud_hid_keyboard_key_sequence(const char* str, uint32_t interval_ms) { // Send each key in string char ch; @@ -138,7 +143,7 @@ bool tud_hid_keyboard_send_string(const char* str, uint32_t interval_ms) { char lookahead = *str; - tud_hid_keyboard_send_char(ch); + tud_hid_keyboard_key_press(ch); // Blocking delay tu_timeout_wait(interval_ms); @@ -147,7 +152,7 @@ bool tud_hid_keyboard_send_string(const char* str, uint32_t interval_ms) * the current one, else no need to send */ if ( lookahead == ch || lookahead == 0 ) { - tud_hid_keyboard_send_report(NULL); + tud_hid_keyboard_report(NULL); tu_timeout_wait(interval_ms); } } diff --git a/src/class/hid/hid_device.h b/src/class/hid/hid_device.h index 1293d212d..e0309fe4f 100644 --- a/src/class/hid/hid_device.h +++ b/src/class/hid/hid_device.h @@ -67,13 +67,13 @@ bool tud_hid_keyboard_busy(void); * \param[in,out] p_report Report data, if NULL, an empty report (all zeroes) is used * \returns true on success, false otherwise (not mounted or busy) */ -bool tud_hid_keyboard_send_report(hid_keyboard_report_t const *p_report); - -bool tud_hid_keyboard_send_keycode(uint8_t modifier, uint8_t keycode[6]); +bool tud_hid_keyboard_report(hid_keyboard_report_t const *p_report); +bool tud_hid_keyboard_keycode(uint8_t modifier, uint8_t keycode[6]); #if CFG_TUD_HID_ASCII_TO_KEYCODE_LOOKUP -bool tud_hid_keyboard_send_char(char ch); -bool tud_hid_keyboard_send_string(const char* str, uint32_t interval_ms); +bool tud_hid_keyboard_key_press(char ch); +bool tud_hid_keyboard_key_release(void); +bool tud_hid_keyboard_key_sequence(const char* str, uint32_t interval_ms); typedef struct{ uint8_t shift; -- cgit v1.3.1 From 255f8329049b41926989398ac58455e39fe93a25 Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 24 Jul 2018 16:55:30 +0700 Subject: rename device mouse API --- examples/device/nrf52840/src/main.c | 2 +- src/class/hid/hid_device.c | 2 +- src/class/hid/hid_device.h | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) (limited to 'src/class') diff --git a/examples/device/nrf52840/src/main.c b/examples/device/nrf52840/src/main.c index 1f7f5b22e..286db9e39 100644 --- a/examples/device/nrf52840/src/main.c +++ b/examples/device/nrf52840/src/main.c @@ -142,7 +142,7 @@ void usb_hid_task(void) if ( btn ) { hid_mouse_report_t report = { .buttons = 0, .x = 10, .y = 0, .wheel = 0 }; - tud_hid_mouse_send_report(&report); + tud_hid_mouse_report(&report); } } diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index 4ea584429..a49479000 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -172,7 +172,7 @@ bool tud_hid_mouse_busy(void) return dcd_edpt_busy(TUD_OPT_RHPORT, _mse_itf.ep_in); } -bool tud_hid_mouse_send_report(hid_mouse_report_t const *p_report) +bool tud_hid_mouse_report(hid_mouse_report_t const *p_report) { VERIFY( tud_mounted() && !tud_hid_mouse_busy() ); diff --git a/src/class/hid/hid_device.h b/src/class/hid/hid_device.h index e0309fe4f..842eb8fa7 100644 --- a/src/class/hid/hid_device.h +++ b/src/class/hid/hid_device.h @@ -130,7 +130,7 @@ bool tud_hid_mouse_busy(void); * \param[in,out] p_report Report data, if NULL, an empty report (all zeroes) is used * \returns true on success, false otherwise (not mounted or busy) */ -bool tud_hid_mouse_send_report(hid_mouse_report_t const *p_report); +bool tud_hid_mouse_report(hid_mouse_report_t const *p_report); /*------------- Callbacks -------------*/ -- cgit v1.3.1 From 17369cfda0f077c29eea1f7ab486d60167511f36 Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 24 Jul 2018 18:18:02 +0700 Subject: change tud_hid_keyboard_busy() to tud_hid_keyboard_ready() for positive meaning --- examples/device/nrf52840/src/main.c | 68 +++++++++++----------- examples/obsolete/device/src/keyboard_device_app.c | 2 +- src/class/hid/hid_device.c | 42 +++++++------ src/class/hid/hid_device.h | 23 ++++---- 4 files changed, 72 insertions(+), 63 deletions(-) (limited to 'src/class') diff --git a/examples/device/nrf52840/src/main.c b/examples/device/nrf52840/src/main.c index 286db9e39..b8f1674a7 100644 --- a/examples/device/nrf52840/src/main.c +++ b/examples/device/nrf52840/src/main.c @@ -102,51 +102,53 @@ void virtual_com_task(void) //--------------------------------------------------------------------+ void usb_hid_task(void) { - if ( tud_mounted() ) + /*------------- Keyboard -------------*/ + if ( tud_hid_keyboard_ready() ) { + // Poll every 10ms + static tu_timeout_t tm = { .start = 0, .interval = 10 }; + if ( !tu_timeout_expired(&tm) ) return; // not enough time + tu_timeout_reset(&tm); - /*------------- Keyboard -------------*/ -/* - if ( !tud_hid_keyboard_busy() ) - { - if ( btn ) - { - uint8_t keycode[6] = { 0 }; + uint32_t const btn = board_buttons(); - for(uint8_t i=0; i < 6; i++) - { - if ( btn & (1 << i) ) keycode[i] = HID_KEY_A + i; - } + if ( btn ) + { + uint8_t keycode[6] = { 0 }; - tud_hid_keyboard_send_keycode(0, keycode); - }else + for(uint8_t i=0; i < 6; i++) { - // Null means empty (all zeroes) report - tud_hid_keyboard_send_report(NULL); + if ( btn & (1 << i) ) keycode[i] = HID_KEY_A + i; } - } -*/ - /*------------- Mouse -------------*/ - if ( !tud_hid_mouse_busy() ) + tud_hid_keyboard_keycode(0, keycode); + }else { - // Poll every 10ms - static tu_timeout_t tm = { .start = 0, .interval = 10 }; - - if ( !tu_timeout_expired(&tm) ) return; // not enough time - tu_timeout_reset(&tm); + // Null means all zeroes keycodes + tud_hid_keyboard_keycode(0, NULL); + } + } - uint32_t const btn = board_buttons(); - if ( btn ) - { - hid_mouse_report_t report = { .buttons = 0, .x = 10, .y = 0, .wheel = 0 }; - tud_hid_mouse_report(&report); - } - } + /*------------- Mouse -------------*/ + // if ( !tud_hid_mouse_busy() ) + // { + // // Poll every 10ms + // static tu_timeout_t tm = { .start = 0, .interval = 10 }; + // + // if ( !tu_timeout_expired(&tm) ) return; // not enough time + // tu_timeout_reset(&tm); + // + // uint32_t const btn = board_buttons(); + // + // if ( btn ) + // { + // hid_mouse_report_t report = { .buttons = 0, .x = 10, .y = 0, .wheel = 0 }; + // tud_hid_mouse_report(&report); + // } + // } - } } diff --git a/examples/obsolete/device/src/keyboard_device_app.c b/examples/obsolete/device/src/keyboard_device_app.c index 4e4de8996..4bb25b9c0 100644 --- a/examples/obsolete/device/src/keyboard_device_app.c +++ b/examples/obsolete/device/src/keyboard_device_app.c @@ -128,7 +128,7 @@ tusb_error_t keyboard_device_subtask(void) osal_task_delay(50); - if ( tud_mounted() && !tud_hid_keyboard_busy(0) ) + if ( tud_mounted() && tud_hid_keyboard_ready(0) ) { static uint32_t button_mask = 0; uint32_t new_button_mask = board_buttons(); diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index a49479000..9f54da34f 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -86,14 +86,15 @@ CFG_TUSB_ATTR_USBRAM static hidd_interface_t _composite_itf; // KEYBOARD APPLICATION API //--------------------------------------------------------------------+ #if CFG_TUD_HID_KEYBOARD -bool tud_hid_keyboard_busy(void) +bool tud_hid_keyboard_ready(void) { - return dcd_edpt_busy(TUD_OPT_RHPORT, _kbd_itf.ep_in); + VERIFY( _kbd_itf.ep_in != 0 ); + return !dcd_edpt_busy(TUD_OPT_RHPORT, _kbd_itf.ep_in); } -bool tud_hid_keyboard_report(hid_keyboard_report_t const *p_report) +static bool hidd_kbd_report(hid_keyboard_report_t const *p_report) { - VERIFY( tud_mounted() && !tud_hid_keyboard_busy() ); + VERIFY( tud_hid_keyboard_ready() ); hidd_interface_t * p_hid = &_kbd_itf; @@ -102,7 +103,10 @@ bool tud_hid_keyboard_report(hid_keyboard_report_t const *p_report) memcpy(p_hid->report_buf, p_report, sizeof(hid_keyboard_report_t)); }else { - // empty report + // only send empty report if previous report is not empty + // TODO idle rate + if ( mem_all_zero(p_hid->report_buf, sizeof(hid_keyboard_report_t)) ) return true; + arrclr_(p_hid->report_buf); } @@ -112,27 +116,29 @@ bool tud_hid_keyboard_report(hid_keyboard_report_t const *p_report) bool tud_hid_keyboard_keycode(uint8_t modifier, uint8_t keycode[6]) { hid_keyboard_report_t report = { .modifier = modifier }; - memcpy(report.keycode, keycode, 6); - return tud_hid_keyboard_report(&report); + if ( keycode ) + { + memcpy(report.keycode, keycode, 6); + }else + { + memclr_(report.keycode, 6); + } + + return hidd_kbd_report(&report); } #if CFG_TUD_HID_ASCII_TO_KEYCODE_LOOKUP bool tud_hid_keyboard_key_press(char ch) { - hid_keyboard_report_t report; - varclr_(&report); - - report.modifier = ( HID_ASCII_TO_KEYCODE[(uint8_t)ch].shift ) ? KEYBOARD_MODIFIER_LEFTSHIFT : 0; - report.keycode[0] = HID_ASCII_TO_KEYCODE[(uint8_t)ch].keycode; + uint8_t keycode[6] = { 0 }; + uint8_t modifier = 0; - return tud_hid_keyboard_report(&report); -} + if ( HID_ASCII_TO_KEYCODE[(uint8_t)ch].shift ) modifier = KEYBOARD_MODIFIER_LEFTSHIFT; + keycode[0] = HID_ASCII_TO_KEYCODE[(uint8_t)ch].keycode; -bool tud_hid_keyboard_key_release(void) -{ - return tud_hid_keyboard_report(NULL); + return tud_hid_keyboard_keycode(modifier, keycode); } bool tud_hid_keyboard_key_sequence(const char* str, uint32_t interval_ms) @@ -152,7 +158,7 @@ bool tud_hid_keyboard_key_sequence(const char* str, uint32_t interval_ms) * the current one, else no need to send */ if ( lookahead == ch || lookahead == 0 ) { - tud_hid_keyboard_report(NULL); + tud_hid_keyboard_key_release(); tu_timeout_wait(interval_ms); } } diff --git a/src/class/hid/hid_device.h b/src/class/hid/hid_device.h index 842eb8fa7..76a59e13a 100644 --- a/src/class/hid/hid_device.h +++ b/src/class/hid/hid_device.h @@ -56,23 +56,18 @@ /** \defgroup Keyboard_Device Device * @{ */ -/** \brief Check if the interface is currently busy or not - * \retval true if the interface is busy meaning the stack is still transferring/waiting data from/to host - * \retval false if the interface is not busy meaning the stack successfully transferred data from/to host - * \note This function is primarily used for polling/waiting result after \ref tusbd_hid_keyboard_send. +/** Check if the interface is ready to use + * \returns true if ready, otherwise interface may not be mounted or still busy transferring data + * \note Application must not perform any action if the interface is not ready */ -bool tud_hid_keyboard_busy(void); +bool tud_hid_keyboard_ready(void); -/** \brief Send a keyboard report - * \param[in,out] p_report Report data, if NULL, an empty report (all zeroes) is used - * \returns true on success, false otherwise (not mounted or busy) - */ -bool tud_hid_keyboard_report(hid_keyboard_report_t const *p_report); bool tud_hid_keyboard_keycode(uint8_t modifier, uint8_t keycode[6]); +static inline bool tud_hid_keyboard_key_release(void) { return tud_hid_keyboard_keycode(0, NULL); } + #if CFG_TUD_HID_ASCII_TO_KEYCODE_LOOKUP bool tud_hid_keyboard_key_press(char ch); -bool tud_hid_keyboard_key_release(void); bool tud_hid_keyboard_key_sequence(const char* str, uint32_t interval_ms); typedef struct{ @@ -131,6 +126,12 @@ bool tud_hid_mouse_busy(void); * \returns true on success, false otherwise (not mounted or busy) */ bool tud_hid_mouse_report(hid_mouse_report_t const *p_report); +bool tud_hid_mouse_data(uint8_t buttons, int8_t x, int8_t y, int8_t scroll, int8_t pan); + +bool tud_hid_mouse_move(int8_t x, int8_t y, int8_t scroll, int8_t pan); + +bool tud_hid_mouse_button_press(uint8_t buttons); +bool tud_hid_mouse_button_release(uint8_t buttons); /*------------- Callbacks -------------*/ -- cgit v1.3.1 From b370283174fbdb066bc662f8885956dbf947559b Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 24 Jul 2018 20:41:06 +0700 Subject: rename tud_hid_mouse_busy to tud_hid_mouse_ready --- examples/device/nrf52840/src/main.c | 2 +- src/class/hid/hid_device.c | 9 +++++---- src/class/hid/hid_device.h | 8 +------- 3 files changed, 7 insertions(+), 12 deletions(-) (limited to 'src/class') diff --git a/examples/device/nrf52840/src/main.c b/examples/device/nrf52840/src/main.c index b8f1674a7..000adb9dc 100644 --- a/examples/device/nrf52840/src/main.c +++ b/examples/device/nrf52840/src/main.c @@ -132,7 +132,7 @@ void usb_hid_task(void) /*------------- Mouse -------------*/ - // if ( !tud_hid_mouse_busy() ) + // if ( tud_hid_mouse_ready() ) // { // // Poll every 10ms // static tu_timeout_t tm = { .start = 0, .interval = 10 }; diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index 9f54da34f..292024a61 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -173,14 +173,15 @@ bool tud_hid_keyboard_key_sequence(const char* str, uint32_t interval_ms) // MOUSE APPLICATION API //--------------------------------------------------------------------+ #if CFG_TUD_HID_MOUSE -bool tud_hid_mouse_busy(void) +bool tud_hid_mouse_ready(void) { - return dcd_edpt_busy(TUD_OPT_RHPORT, _mse_itf.ep_in); + VERIFY( _mse_itf.ep_in != 0 ); + return !dcd_edpt_busy(TUD_OPT_RHPORT, _mse_itf.ep_in); } -bool tud_hid_mouse_report(hid_mouse_report_t const *p_report) +static bool hidd_mouse_report(hid_mouse_report_t const *p_report) { - VERIFY( tud_mounted() && !tud_hid_mouse_busy() ); + VERIFY( tud_hid_mouse_ready() ); hidd_interface_t * p_hid = &_mse_itf; memcpy(p_hid->report_buf, p_report, sizeof(hid_mouse_report_t)); diff --git a/src/class/hid/hid_device.h b/src/class/hid/hid_device.h index 76a59e13a..ba8a5a4a1 100644 --- a/src/class/hid/hid_device.h +++ b/src/class/hid/hid_device.h @@ -119,15 +119,9 @@ ATTR_WEAK void tud_hid_keyboard_set_report_cb(hid_report_type_t report_type, uin * \retval false if the interface is not busy meaning the stack successfully transferred data from/to host * \note This function is primarily used for polling/waiting result after \ref tusbd_hid_mouse_send. */ -bool tud_hid_mouse_busy(void); +bool tud_hid_mouse_ready(void); -/** \brief Perform transfer queuing - * \param[in,out] p_report Report data, if NULL, an empty report (all zeroes) is used - * \returns true on success, false otherwise (not mounted or busy) - */ -bool tud_hid_mouse_report(hid_mouse_report_t const *p_report); bool tud_hid_mouse_data(uint8_t buttons, int8_t x, int8_t y, int8_t scroll, int8_t pan); - bool tud_hid_mouse_move(int8_t x, int8_t y, int8_t scroll, int8_t pan); bool tud_hid_mouse_button_press(uint8_t buttons); -- cgit v1.3.1 From a6fede4962fb65bfb353c3a4a4f927c3fc501eb2 Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 24 Jul 2018 20:51:50 +0700 Subject: improve tud_hid_mouse API() --- src/class/hid/hid_device.c | 31 +++++++++++++++++++++++++++++++ src/class/hid/hid_device.h | 15 ++++++++++++--- 2 files changed, 43 insertions(+), 3 deletions(-) (limited to 'src/class') diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index 292024a61..59bf24256 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -188,6 +188,37 @@ static bool hidd_mouse_report(hid_mouse_report_t const *p_report) return dcd_edpt_xfer(TUD_OPT_RHPORT, p_hid->ep_in, p_hid->report_buf, sizeof(hid_mouse_report_t)); } + +bool tud_hid_mouse_data(uint8_t buttons, int8_t x, int8_t y, int8_t scroll, int8_t pan) +{ + hid_mouse_report_t report = + { + .buttons = buttons, + .x = x, + .y = y, + .wheel = scroll, +// .pan = pan + }; + + return hidd_mouse_report( &report ); +} + +bool tud_hid_mouse_move(int8_t x, int8_t y) +{ + hidd_interface_t * p_hid = &_mse_itf; + uint8_t prev_buttons = p_hid->report_buf[0]; + + return tud_hid_mouse_data(prev_buttons, x, y, 0, 0); +} + +bool tud_hid_mouse_scroll(int8_t vertical, int8_t horizontal) +{ + hidd_interface_t * p_hid = &_mse_itf; + uint8_t prev_buttons = p_hid->report_buf[0]; + + return tud_hid_mouse_data(prev_buttons, 0, 0, vertical, horizontal); +} + #endif static inline hidd_interface_t* get_interface_by_edpt(uint8_t ep_addr) diff --git a/src/class/hid/hid_device.h b/src/class/hid/hid_device.h index ba8a5a4a1..659981a48 100644 --- a/src/class/hid/hid_device.h +++ b/src/class/hid/hid_device.h @@ -122,10 +122,19 @@ ATTR_WEAK void tud_hid_keyboard_set_report_cb(hid_report_type_t report_type, uin bool tud_hid_mouse_ready(void); bool tud_hid_mouse_data(uint8_t buttons, int8_t x, int8_t y, int8_t scroll, int8_t pan); -bool tud_hid_mouse_move(int8_t x, int8_t y, int8_t scroll, int8_t pan); -bool tud_hid_mouse_button_press(uint8_t buttons); -bool tud_hid_mouse_button_release(uint8_t buttons); +bool tud_hid_mouse_move(int8_t x, int8_t y); +bool tud_hid_mouse_scroll(int8_t vertical, int8_t horizontal); + +static inline bool tud_hid_mouse_button_press(uint8_t buttons) +{ + return tud_hid_mouse_data(buttons, 0, 0, 0, 0); +} + +static inline bool tud_hid_mouse_button_release(void) +{ + return tud_hid_mouse_data(0, 0, 0, 0, 0); +} /*------------- Callbacks -------------*/ -- cgit v1.3.1 From 2729937e87feef3baa45113e220feddd82fde722 Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 25 Jul 2018 12:24:16 +0700 Subject: add tud_msc_ready() --- src/class/msc/msc_device.c | 5 +++++ src/class/msc/msc_device.h | 4 ++++ 2 files changed, 9 insertions(+) (limited to 'src/class') diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index f32a1f833..dc3d47dfd 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -110,6 +110,11 @@ static inline uint16_t rdwr10_get_blockcount(uint8_t const command[]) return __be2n_16(block_count); } +bool tud_msc_ready(void) +{ + return ( _mscd_itf.ep_in != 0 ) && ( _mscd_itf.ep_out != 0 ) ; +} + //--------------------------------------------------------------------+ // USBD-CLASS API diff --git a/src/class/msc/msc_device.h b/src/class/msc/msc_device.h index a32d64a93..fbfe7ef14 100644 --- a/src/class/msc/msc_device.h +++ b/src/class/msc/msc_device.h @@ -94,6 +94,10 @@ VERIFY_STATIC(CFG_TUD_MSC_BUFSIZE < UINT16_MAX, "Size is not correct"); * \defgroup MSC_Device Device * @{ */ + +// Check if MSC interface is ready to use +bool tud_msc_ready(void); + //--------------------------------------------------------------------+ // APPLICATION CALLBACK API (WEAK is optional) //--------------------------------------------------------------------+ -- cgit v1.3.1 From 1982886f87f87785fbc8b12dbc77393b0371bec2 Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 25 Jul 2018 15:58:52 +0700 Subject: add control set boot protocol support and keyboard idle rate - tud_hid_keyboard_is_boot_protocol() - tud_hid_mouse_is_boot_protocol() --- examples/device/nrf52840/src/main.c | 10 ++++--- src/class/hid/hid_device.c | 52 +++++++++++++++++++++++++------------ src/class/hid/hid_device.h | 15 +++++++---- 3 files changed, 51 insertions(+), 26 deletions(-) (limited to 'src/class') diff --git a/examples/device/nrf52840/src/main.c b/examples/device/nrf52840/src/main.c index 5ece8bf96..0008bb69c 100644 --- a/examples/device/nrf52840/src/main.c +++ b/examples/device/nrf52840/src/main.c @@ -134,10 +134,12 @@ void usb_hid_task(void) /*------------- Mouse -------------*/ if ( tud_hid_mouse_ready() ) { - if ( btn & 0x01 ) tud_hid_mouse_move(-10, 0 ); // left - else if( btn & 0x02 ) tud_hid_mouse_move( 10, 0 ); // right - else if( btn & 0x04 ) tud_hid_mouse_move( 0, -10); // up - else if( btn & 0x08 ) tud_hid_mouse_move( 0, 10); // down + enum { DELTA = 5 }; + + if ( btn & 0x01 ) tud_hid_mouse_move(-DELTA, 0); // left + if ( btn & 0x02 ) tud_hid_mouse_move( DELTA, 0); // right + if ( btn & 0x04 ) tud_hid_mouse_move( 0 , -DELTA); // up + if ( btn & 0x08 ) tud_hid_mouse_move( 0 , DELTA); // down } } diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index 59bf24256..81805665e 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -58,7 +58,9 @@ typedef struct { uint8_t itf_num; uint8_t ep_in; - uint8_t idle_rate; + + uint8_t idle_rate; // in unit of 4 ms + bool boot_protocol; uint8_t report_id; uint16_t report_len; @@ -92,24 +94,30 @@ bool tud_hid_keyboard_ready(void) return !dcd_edpt_busy(TUD_OPT_RHPORT, _kbd_itf.ep_in); } +bool tud_hid_keyboard_is_boot_protocol(void) +{ + return _kbd_itf.boot_protocol; +} + static bool hidd_kbd_report(hid_keyboard_report_t const *p_report) { VERIFY( tud_hid_keyboard_ready() ); hidd_interface_t * p_hid = &_kbd_itf; - if ( p_report ) - { - memcpy(p_hid->report_buf, p_report, sizeof(hid_keyboard_report_t)); - }else - { - // only send empty report if previous report is not empty - // TODO idle rate - if ( mem_all_zero(p_hid->report_buf, sizeof(hid_keyboard_report_t)) ) return true; + // Idle Rate = 0 : only send report if there is changes, i.e skip duplication + // Idle Rate > 0 : skip duplication, but send at least 1 report every idle rate (in unit of 4 ms). + // If idle time is less than interrupt polling then use the polling. + static tu_timeout_t idle_tm = { 0, 0 }; - arrclr_(p_hid->report_buf); + if ( (p_hid->idle_rate == 0) || !tu_timeout_expired(&idle_tm) ) + { + if ( 0 == memcmp(p_hid->report_buf, p_report, sizeof(hid_keyboard_report_t)) ) return true; } + tu_timeout_restart(&idle_tm); + + memcpy(p_hid->report_buf, p_report, sizeof(hid_keyboard_report_t)); return dcd_edpt_xfer(TUD_OPT_RHPORT, p_hid->ep_in, p_hid->report_buf, sizeof(hid_keyboard_report_t)); } @@ -173,12 +181,18 @@ bool tud_hid_keyboard_key_sequence(const char* str, uint32_t interval_ms) // MOUSE APPLICATION API //--------------------------------------------------------------------+ #if CFG_TUD_HID_MOUSE + bool tud_hid_mouse_ready(void) { VERIFY( _mse_itf.ep_in != 0 ); return !dcd_edpt_busy(TUD_OPT_RHPORT, _mse_itf.ep_in); } +bool tud_hid_mouse_is_boot_protocol(void) +{ + return _mse_itf.boot_protocol; +} + static bool hidd_mouse_report(hid_mouse_report_t const *p_report) { VERIFY( tud_hid_mouse_ready() ); @@ -302,10 +316,11 @@ tusb_error_t hidd_open(uint8_t rhport, tusb_desc_interface_t const * desc_itf, u TU_ASSERT( dcd_edpt_open(rhport, desc_edpt), TUSB_ERROR_DCD_FAILED ); - p_hid->report_len = desc_hid->wReportLength; - p_hid->itf_num = desc_itf->bInterfaceNumber; - p_hid->ep_in = desc_edpt->bEndpointAddress; - p_hid->report_id = 0; + p_hid->boot_protocol = true; // default to boot mode when mounted + p_hid->report_len = desc_hid->wReportLength; + p_hid->itf_num = desc_itf->bInterfaceNumber; + p_hid->ep_in = desc_edpt->bEndpointAddress; + p_hid->report_id = 0; *p_length = sizeof(tusb_desc_interface_t) + sizeof(tusb_hid_descriptor_hid_t) + sizeof(tusb_desc_endpoint_t); } @@ -402,12 +417,15 @@ tusb_error_t hidd_control_request_st(uint8_t rhport, tusb_control_request_t cons } else if (HID_REQ_CONTROL_GET_PROTOCOL == p_request->bRequest ) { - _usbd_ctrl_buf[0] = 1 - CFG_TUD_HID_BOOT_PROTOCOL; // 0 is Boot, 1 is Report protocol + _usbd_ctrl_buf[0] = 1-p_hid->boot_protocol; // 0 is Boot, 1 is Report protocol usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, _usbd_ctrl_buf, 1); } - else + else if (HID_REQ_CONTROL_SET_PROTOCOL == p_request->bRequest ) + { + p_hid->boot_protocol = 1 - p_request->wValue; // 0 is Boot, 1 is Report protocol + dcd_control_status(rhport, p_request->bmRequestType_bit.direction); + }else { -// HID_REQ_CONTROL_SET_PROTOCOL: dcd_control_stall(rhport); } }else diff --git a/src/class/hid/hid_device.h b/src/class/hid/hid_device.h index 659981a48..e8f5b40f4 100644 --- a/src/class/hid/hid_device.h +++ b/src/class/hid/hid_device.h @@ -61,6 +61,7 @@ * \note Application must not perform any action if the interface is not ready */ bool tud_hid_keyboard_ready(void); +bool tud_hid_keyboard_is_boot_protocol(void); bool tud_hid_keyboard_keycode(uint8_t modifier, uint8_t keycode[6]); @@ -77,10 +78,9 @@ typedef struct{ extern const hid_ascii_to_keycode_entry_t HID_ASCII_TO_KEYCODE[128]; #endif -/*------------- Callbacks -------------*/ +/*------------- Callbacks, ATTR_WEAK means optional -------------*/ -/** \brief Callback function that is invoked when USB host request \ref HID_REQUEST_CONTROL_GET_REPORT - * via control endpoint. +/** Callback invoked when USB host request \ref HID_REQ_CONTROL_GET_REPORT. * \param[in] report_type specify which report (INPUT, OUTPUT, FEATURE) that host requests * \param[out] buffer data that application need to update, value must be accessible by USB controller (see \ref CFG_TUSB_ATTR_USBRAM) * \param[in] reqlen number of bytes that host requested @@ -93,8 +93,7 @@ extern const hid_ascii_to_keycode_entry_t HID_ASCII_TO_KEYCODE[128]; */ ATTR_WEAK uint16_t tud_hid_keyboard_get_report_cb(hid_report_type_t report_type, uint8_t* buffer, uint16_t reqlen); -/** \brief Callback function that is invoked when USB host request \ref HID_REQUEST_CONTROL_SET_REPORT - * via control endpoint. +/** Callback invoked when USB host request \ref HID_REQ_CONTROL_SET_REPORT. * \param[in] report_type specify which report (INPUT, OUTPUT, FEATURE) that host requests * \param[in] buffer containing the report's data * \param[in] bufsize number of bytes in the \a buffer @@ -103,6 +102,9 @@ ATTR_WEAK uint16_t tud_hid_keyboard_get_report_cb(hid_report_type_t report_type, */ ATTR_WEAK void tud_hid_keyboard_set_report_cb(hid_report_type_t report_type, uint8_t const* buffer, uint16_t bufsize); + +//ATTR_WEAK void tud_hid_keyboard_set_protocol_cb(bool boot_protocol); + /** @} */ /** @} */ @@ -120,6 +122,7 @@ ATTR_WEAK void tud_hid_keyboard_set_report_cb(hid_report_type_t report_type, uin * \note This function is primarily used for polling/waiting result after \ref tusbd_hid_mouse_send. */ bool tud_hid_mouse_ready(void); +bool tud_hid_mouse_is_boot_protocol(void); bool tud_hid_mouse_data(uint8_t buttons, int8_t x, int8_t y, int8_t scroll, int8_t pan); @@ -161,6 +164,8 @@ ATTR_WEAK uint16_t tud_hid_mouse_get_report_cb(hid_report_type_t report_type, ui */ ATTR_WEAK void tud_hid_mouse_set_report_cb(hid_report_type_t report_type, uint8_t const* buffer, uint16_t bufsize); +//ATTR_WEAK void tud_hid_mouse_set_protocol_cb(bool boot_protocol); + /** @} */ /** @} */ -- cgit v1.3.1 From d2ab4db25ee95058131d3b6139f9bb89d16f9cd7 Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 25 Jul 2018 16:56:57 +0700 Subject: add scsi start stop unit struct, improve device msc, correctly stall unsupported scsi command --- examples/device/nrf52840/src/msc_device_app.c | 2 +- src/class/msc/msc.h | 23 +++++++++++++++++++++++ src/class/msc/msc_device.c | 27 ++++++++++++++++++--------- src/common/tusb_common.h | 3 +++ src/common/tusb_compiler.h | 14 +++++++------- 5 files changed, 52 insertions(+), 17 deletions(-) (limited to 'src/class') diff --git a/examples/device/nrf52840/src/msc_device_app.c b/examples/device/nrf52840/src/msc_device_app.c index 3f97863e4..d43767119 100644 --- a/examples/device/nrf52840/src/msc_device_app.c +++ b/examples/device/nrf52840/src/msc_device_app.c @@ -112,7 +112,7 @@ int32_t tud_msc_scsi_cb (uint8_t rhport, uint8_t lun, uint8_t const scsi_cmd[16] } // return len must not larger than bufsize - TU_ASSERT( bufsize >= len ); + if ( len > bufsize ) len = bufsize; if ( ptr && len ) { diff --git a/src/class/msc/msc.h b/src/class/msc/msc.h index fc0b8730c..ed9fbfce5 100644 --- a/src/class/msc/msc.h +++ b/src/class/msc/msc.h @@ -298,6 +298,29 @@ typedef struct ATTR_PACKED VERIFY_STATIC( sizeof(scsi_prevent_allow_medium_removal_t) == 6, "size is not correct"); +typedef struct ATTR_PACKED +{ + uint8_t cmd_code; + + uint8_t immded : 1; + uint8_t : 7; + + uint8_t TU_RESERVED; + + uint8_t power_condition_mod : 4; + uint8_t : 4; + + uint8_t start : 1; + uint8_t load_eject : 1; + uint8_t no_flush : 1; + uint8_t : 1; + uint8_t power_condition : 4; + + uint8_t control; +} scsi_start_stop_unit_t; + +VERIFY_STATIC( sizeof(scsi_start_stop_unit_t) == 6, "size is not correct"); + //--------------------------------------------------------------------+ // SCSI MMC //--------------------------------------------------------------------+ diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index dc3d47dfd..d9b4c76a8 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -216,11 +216,14 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u if ( p_cbw->xfer_bytes == 0) { - p_msc->data_len = tud_msc_scsi_cb(rhport, p_cbw->lun, p_cbw->command, NULL, 0); - p_csw->status = (p_msc->data_len == 0) ? MSC_CSW_STATUS_PASSED : MSC_CSW_STATUS_FAILED; + int32_t const cb_result = tud_msc_scsi_cb(rhport, p_cbw->lun, p_cbw->command, NULL, 0); + + p_csw->status = (cb_result == 0) ? MSC_CSW_STATUS_PASSED : MSC_CSW_STATUS_FAILED; + p_msc->data_len = 0; p_msc->stage = MSC_STAGE_STATUS; - TU_ASSERT( p_msc->data_len == 0, TUSB_ERROR_INVALID_PARA); + // stall request since callback return negative + if ( cb_result < 0 ) dcd_edpt_stall(rhport, p_msc->ep_in); } else if ( !BIT_TEST_(p_cbw->dir, 7) ) { @@ -230,7 +233,6 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u else { // IN Transfer - int32_t cb_result; // TODO refactor later @@ -282,8 +284,15 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u cb_result = tud_msc_scsi_cb(rhport, p_cbw->lun, p_cbw->command, _mscd_buf, p_msc->data_len); } - p_csw->status = (cb_result >= 0) ? MSC_CSW_STATUS_PASSED : MSC_CSW_STATUS_FAILED; - p_msc->data_len = (uint32_t) cb_result; + if ( cb_result > 0 ) + { + p_csw->status = MSC_CSW_STATUS_PASSED; + p_msc->data_len = (uint32_t) cb_result; + }else + { + p_csw->status = MSC_CSW_STATUS_FAILED; + p_msc->data_len = 0; + } TU_ASSERT( p_cbw->xfer_bytes >= p_msc->data_len, TUSB_ERROR_INVALID_PARA ); // cannot return more than host expect @@ -292,11 +301,11 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u TU_ASSERT( dcd_edpt_xfer(rhport, p_msc->ep_in, _mscd_buf, p_msc->data_len), TUSB_ERROR_DCD_EDPT_XFER ); }else { - // application does not provide data to response --> possibly unsupported SCSI command - dcd_edpt_stall(rhport, p_msc->ep_in); - + // callback does not provide response's data --> possibly unsupported SCSI command p_csw->status = MSC_CSW_STATUS_FAILED; p_msc->stage = MSC_STAGE_STATUS; + + dcd_edpt_stall(rhport, p_msc->ep_in); } } } diff --git a/src/common/tusb_common.h b/src/common/tusb_common.h index 58a18f25c..e8baa9de4 100644 --- a/src/common/tusb_common.h +++ b/src/common/tusb_common.h @@ -101,6 +101,9 @@ #endif +// for declaration of reserved field, make use of _TU_COUNTER_ +#define TU_RESERVED XSTRING_CONCAT_(reserved, _TU_COUNTER_) + /*------------------------------------------------------------------*/ /* Count number of arguments of __VA_ARGS__ * - reference https://groups.google.com/forum/#!topic/comp.std.c/d-6Mj5Lko_s diff --git a/src/common/tusb_compiler.h b/src/common/tusb_compiler.h index 369c3121a..35a4cc928 100644 --- a/src/common/tusb_compiler.h +++ b/src/common/tusb_compiler.h @@ -49,19 +49,19 @@ #define STRING_CONCAT_(a, b) a##b ///< concat without expand #define XSTRING_CONCAT_(a, b) STRING_CONCAT_(a, b) ///< expand then concat +#if defined __COUNTER__ && __COUNTER__ != __COUNTER__ + #define _TU_COUNTER_ __COUNTER__ +#else + #define _TU_COUNTER_ __LINE__ +#endif + //--------------------------------------------------------------------+ // Compile-time Assert (use VERIFY_STATIC to avoid name conflict) //--------------------------------------------------------------------+ #if defined(__ICCARM__) || (__STDC_VERSION__ >= 201112L ) #define VERIFY_STATIC static_assert #else - #if defined __COUNTER__ && __COUNTER__ != __COUNTER__ - #define _VERIFY_COUNTER __COUNTER__ - #else - #define _VERIFY_COUNTER __LINE__ - #endif - - #define VERIFY_STATIC(const_expr, _mess) enum { XSTRING_CONCAT_(_verify_static_, _VERIFY_COUNTER) = 1/(!!(const_expr)) } + #define VERIFY_STATIC(const_expr, _mess) enum { XSTRING_CONCAT_(_verify_static_, _TU_COUNTER_) = 1/(!!(const_expr)) } #endif // allow debugger to watch any module-wide variables anywhere -- cgit v1.3.1 From 936579462384a977ff637c111fce78535149df2d Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 25 Jul 2018 20:34:56 +0700 Subject: clean up device msc API --- examples/device/nrf52840/src/msc_device_app.c | 2 +- examples/device/nrf52840/src/msc_device_ramdisk.c | 4 ++-- examples/obsolete/device/src/msc_device_app.c | 2 +- examples/obsolete/device/src/msc_device_ramdisk.c | 4 ++-- examples/obsolete/device/src/msc_device_romdisk.c | 4 ++-- src/class/msc/msc_device.c | 16 ++++++++-------- src/class/msc/msc_device.h | 15 ++++++--------- 7 files changed, 22 insertions(+), 25 deletions(-) (limited to 'src/class') diff --git a/examples/device/nrf52840/src/msc_device_app.c b/examples/device/nrf52840/src/msc_device_app.c index d43767119..836dd2d48 100644 --- a/examples/device/nrf52840/src/msc_device_app.c +++ b/examples/device/nrf52840/src/msc_device_app.c @@ -74,7 +74,7 @@ void msc_app_umount(uint8_t rhport) } -int32_t tud_msc_scsi_cb (uint8_t rhport, uint8_t lun, uint8_t const scsi_cmd[16], void* buffer, uint16_t bufsize) +int32_t tud_msc_scsi_cb (uint8_t lun, uint8_t const scsi_cmd[16], void* buffer, uint16_t bufsize) { // read10 & write10 has their own callback and MUST not be handled here diff --git a/examples/device/nrf52840/src/msc_device_ramdisk.c b/examples/device/nrf52840/src/msc_device_ramdisk.c index f50b03f1e..3d2fca1d6 100644 --- a/examples/device/nrf52840/src/msc_device_ramdisk.c +++ b/examples/device/nrf52840/src/msc_device_ramdisk.c @@ -91,7 +91,7 @@ uint8_t msc_device_ramdisk[DISK_BLOCK_NUM][DISK_BLOCK_SIZE] = //--------------------------------------------------------------------+ // IMPLEMENTATION //--------------------------------------------------------------------+ -int32_t tud_msc_read10_cb (uint8_t rhport, uint8_t lun, uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize) +int32_t tud_msc_read10_cb(uint8_t lun, uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize) { uint8_t* addr = msc_device_ramdisk[lba] + offset; memcpy(buffer, addr, bufsize); @@ -99,7 +99,7 @@ int32_t tud_msc_read10_cb (uint8_t rhport, uint8_t lun, uint32_t lba, uint32_t o return bufsize; } -int32_t tud_msc_write10_cb (uint8_t rhport, uint8_t lun, uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize) +int32_t tud_msc_write10_cb(uint8_t lun, uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize) { uint8_t* addr = msc_device_ramdisk[lba] + offset; memcpy(addr, buffer, bufsize); diff --git a/examples/obsolete/device/src/msc_device_app.c b/examples/obsolete/device/src/msc_device_app.c index 7b1fb9411..572c90efd 100644 --- a/examples/obsolete/device/src/msc_device_app.c +++ b/examples/obsolete/device/src/msc_device_app.c @@ -99,7 +99,7 @@ void msc_app_umount(uint8_t rhport) } -int32_t tud_msc_scsi_cb (uint8_t rhport, uint8_t lun, uint8_t const scsi_cmd[16], void* buffer, uint16_t bufsize) +int32_t tud_msc_scsi_cb (uint8_t lun, uint8_t const scsi_cmd[16], void* buffer, uint16_t bufsize) { // read10 & write10 has their own callback and MUST not be handled here diff --git a/examples/obsolete/device/src/msc_device_ramdisk.c b/examples/obsolete/device/src/msc_device_ramdisk.c index 7133e745d..6dc48e290 100644 --- a/examples/obsolete/device/src/msc_device_ramdisk.c +++ b/examples/obsolete/device/src/msc_device_ramdisk.c @@ -91,7 +91,7 @@ uint8_t msc_device_ramdisk[DISK_BLOCK_NUM][DISK_BLOCK_SIZE] = //--------------------------------------------------------------------+ // IMPLEMENTATION //--------------------------------------------------------------------+ -int32_t tud_msc_read10_cb (uint8_t rhport, uint8_t lun, uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize) +int32_t tud_msc_read10_cb (uint8_t lun, uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize) { (void) rhport; (void) lun; @@ -101,7 +101,7 @@ int32_t tud_msc_read10_cb (uint8_t rhport, uint8_t lun, uint32_t lba, uint32_t o return bufsize; } -int32_t tud_msc_write10_cb (uint8_t rhport, uint8_t lun, uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize) +int32_t tud_msc_write10_cb (uint8_t lun, uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize) { (void) rhport; (void) lun; diff --git a/examples/obsolete/device/src/msc_device_romdisk.c b/examples/obsolete/device/src/msc_device_romdisk.c index 0dd84bdf4..1e6ca1bc3 100644 --- a/examples/obsolete/device/src/msc_device_romdisk.c +++ b/examples/obsolete/device/src/msc_device_romdisk.c @@ -94,7 +94,7 @@ const uint8_t msc_device_app_rommdisk[DISK_BLOCK_NUM][DISK_BLOCK_SIZE] = //--------------------------------------------------------------------+ // IMPLEMENTATION //--------------------------------------------------------------------+ -int32_t tud_msc_read10_cb (uint8_t rhport, uint8_t lun, uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize) +int32_t tud_msc_read10_cb (uint8_t lun, uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize) { (void) rhport; (void) lun; @@ -106,7 +106,7 @@ int32_t tud_msc_read10_cb (uint8_t rhport, uint8_t lun, uint32_t lba, uint32_t o // Stall write10 by return 0, as this is readonly disk -int32_t tud_msc_write10_cb (uint8_t rhport, uint8_t lun, uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize) +int32_t tud_msc_write10_cb (uint8_t lun, uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize) { (void) rhport; (void) lun; diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index d9b4c76a8..e92021176 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -216,7 +216,7 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u if ( p_cbw->xfer_bytes == 0) { - int32_t const cb_result = tud_msc_scsi_cb(rhport, p_cbw->lun, p_cbw->command, NULL, 0); + int32_t const cb_result = tud_msc_scsi_cb(p_cbw->lun, p_cbw->command, NULL, 0); p_csw->status = (cb_result == 0) ? MSC_CSW_STATUS_PASSED : MSC_CSW_STATUS_FAILED; p_msc->data_len = 0; @@ -281,7 +281,7 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u } else { - cb_result = tud_msc_scsi_cb(rhport, p_cbw->lun, p_cbw->command, _mscd_buf, p_msc->data_len); + cb_result = tud_msc_scsi_cb(p_cbw->lun, p_cbw->command, _mscd_buf, p_msc->data_len); } if ( cb_result > 0 ) @@ -317,7 +317,7 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u { if ( SCSI_CMD_WRITE_10 != p_cbw->command[0] ) { - p_csw->status = (tud_msc_scsi_cb(rhport, p_cbw->lun, p_cbw->command, _mscd_buf, p_msc->data_len) >= 0 ) ? MSC_CSW_STATUS_PASSED : MSC_CSW_STATUS_FAILED; + p_csw->status = (tud_msc_scsi_cb(p_cbw->lun, p_cbw->command, _mscd_buf, p_msc->data_len) >= 0 ) ? MSC_CSW_STATUS_PASSED : MSC_CSW_STATUS_FAILED; } else { @@ -327,7 +327,7 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u uint32_t const lba = rdwr10_get_lba(p_cbw->command) + (p_msc->xferred_len / block_sz); // Application can consume smaller bytes - int32_t nbytes = tud_msc_write10_cb(rhport, p_cbw->lun, lba, p_msc->xferred_len % block_sz, _mscd_buf, xferred_bytes); + int32_t nbytes = tud_msc_write10_cb(p_cbw->lun, lba, p_msc->xferred_len % block_sz, _mscd_buf, xferred_bytes); if ( nbytes < 0 ) { @@ -398,15 +398,15 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u // Invoke complete callback if defined if ( SCSI_CMD_READ_10 == p_cbw->command[0]) { - if ( tud_msc_read10_complete_cb ) tud_msc_read10_complete_cb(rhport, p_cbw->lun); + if ( tud_msc_read10_complete_cb ) tud_msc_read10_complete_cb(p_cbw->lun); } else if ( SCSI_CMD_WRITE_10 == p_cbw->command[0] ) { - if ( tud_msc_write10_complete_cb ) tud_msc_write10_complete_cb(rhport, p_cbw->lun); + if ( tud_msc_write10_complete_cb ) tud_msc_write10_complete_cb(p_cbw->lun); } else { - if ( tud_msc_scsi_complete_cb ) tud_msc_scsi_complete_cb(rhport, p_cbw->lun, p_cbw->command); + if ( tud_msc_scsi_complete_cb ) tud_msc_scsi_complete_cb(p_cbw->lun, p_cbw->command); } // Move to default CMD stage after sending status @@ -438,7 +438,7 @@ static void proc_read10_cmd(uint8_t rhport, mscd_interface_t* p_msc) int32_t nbytes = (int32_t) min32_of(sizeof(_mscd_buf), p_cbw->xfer_bytes-p_msc->xferred_len); // Application can consume smaller bytes - nbytes = tud_msc_read10_cb (rhport, p_cbw->lun, lba, p_msc->xferred_len % block_sz, _mscd_buf, (uint32_t) nbytes); + nbytes = tud_msc_read10_cb(p_cbw->lun, lba, p_msc->xferred_len % block_sz, _mscd_buf, (uint32_t) nbytes); if ( nbytes < 0 ) { diff --git a/src/class/msc/msc_device.h b/src/class/msc/msc_device.h index fbfe7ef14..60144cc55 100644 --- a/src/class/msc/msc_device.h +++ b/src/class/msc/msc_device.h @@ -102,7 +102,6 @@ bool tud_msc_ready(void); // APPLICATION CALLBACK API (WEAK is optional) //--------------------------------------------------------------------+ /** \brief Callback invoked when received \ref SCSI_CMD_READ_10 command - * \param[in] \rhport Root hub port * \param[in] lun Targeted Logical Unit * Must be accessible by USB controller (see \ref CFG_TUSB_ATTR_USBRAM) * \param[in] lba Starting Logical Block Address to be read @@ -126,10 +125,9 @@ bool tud_msc_ready(void); * \n\n Although this callback is called by tinyusb device task (non-isr context), however as all the classes share * the same task (to save resource), any delay in this callback will cause delay in response on other classes. */ -int32_t tud_msc_read10_cb (uint8_t rhport, uint8_t lun, uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize); +int32_t tud_msc_read10_cb (uint8_t lun, uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize); /** \brief Callback invoked when received \ref SCSI_CMD_WRITE_10 command - * \param[in] rhport Root hub port * \param[in] lun Targeted Logical Unit * Must be accessible by USB controller (see \ref CFG_TUSB_ATTR_USBRAM) * \param[in] lba Starting Logical Block Address to be write @@ -152,11 +150,10 @@ int32_t tud_msc_read10_cb (uint8_t rhport, uint8_t lun, uint32_t lba, uint32_t o * \n\n Although this callback is called by tinyusb device task (non-isr context), however as all the classes share * the same task (to save resource), any delay in this callback will cause delay in response on other classes. */ -int32_t tud_msc_write10_cb (uint8_t rhport, uint8_t lun, uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize); +int32_t tud_msc_write10_cb (uint8_t lun, uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize); /** \brief Callback invoked when received an SCSI command other than \ref SCSI_CMD_WRITE_10 and \ref SCSI_CMD_READ_10 - * \param[in] rhport Root hub port * \param[in] lun Targeted Logical Unit * \param[in] scsi_cmd SCSI command contents, application should examine this command block to know which command host requested * \param[out] buffer Buffer for SCSI Data Stage. @@ -168,12 +165,12 @@ int32_t tud_msc_write10_cb (uint8_t rhport, uint8_t lun, uint32_t lba, uint32_t * endpoint and return failed status in command status wrapper phase. * \retval otherwise Actual bytes processed, must not be more than \a \b bufsize. Can be zero for no-data command. */ -int32_t tud_msc_scsi_cb (uint8_t rhport, uint8_t lun, uint8_t const scsi_cmd[16], void* buffer, uint16_t bufsize); +int32_t tud_msc_scsi_cb (uint8_t lun, uint8_t const scsi_cmd[16], void* buffer, uint16_t bufsize); /*------------- Optional callbacks : Could be used by application to free up resources -------------*/ -ATTR_WEAK void tud_msc_read10_complete_cb(uint8_t rhport, uint8_t lun); -ATTR_WEAK void tud_msc_write10_complete_cb(uint8_t rhport, uint8_t lun); -ATTR_WEAK void tud_msc_scsi_complete_cb(uint8_t rhport, uint8_t lun, uint8_t const scsi_cmd[16]); +ATTR_WEAK void tud_msc_read10_complete_cb(uint8_t lun); +ATTR_WEAK void tud_msc_write10_complete_cb(uint8_t lun); +ATTR_WEAK void tud_msc_scsi_complete_cb(uint8_t lun, uint8_t const scsi_cmd[16]); /** @} */ /** @} */ -- cgit v1.3.1 From be7b0caf2d5d3219b2cbef535b6817fb39625ffb Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 25 Jul 2018 22:21:14 +0700 Subject: enhance device msc response in case of STALL response --- src/class/msc/msc_device.c | 41 +++++++++++++++++++++++++---------------- 1 file changed, 25 insertions(+), 16 deletions(-) (limited to 'src/class') diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index e92021176..e2b35163d 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -348,7 +348,7 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u memmove(_mscd_buf, _mscd_buf+nbytes, xferred_bytes-nbytes); } - // simulate an transfer complete with adjusted params + // simulate an transfer complete with adjusted parameters --> this driver callback will fired again dcd_xfer_complete(rhport, p_msc->ep_out, xferred_bytes-nbytes, true); return TUSB_ERROR_NONE; // skip the rest @@ -395,27 +395,36 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u if ( p_msc->stage == MSC_STAGE_STATUS ) { - // Invoke complete callback if defined - if ( SCSI_CMD_READ_10 == p_cbw->command[0]) + // Either endpoints is stalled, need to wait until it is cleared by host + if ( dcd_edpt_stalled(rhport, p_msc->ep_in) || dcd_edpt_stalled(rhport, p_msc->ep_out) ) { - if ( tud_msc_read10_complete_cb ) tud_msc_read10_complete_cb(p_cbw->lun); - } - else if ( SCSI_CMD_WRITE_10 == p_cbw->command[0] ) - { - if ( tud_msc_write10_complete_cb ) tud_msc_write10_complete_cb(p_cbw->lun); + // simulate an transfer complete with adjusted parameters --> this driver callback will fired again + dcd_xfer_complete(rhport, p_msc->ep_out, 0, true); } else { - if ( tud_msc_scsi_complete_cb ) tud_msc_scsi_complete_cb(p_cbw->lun, p_cbw->command); - } + // Invoke complete callback if defined + if ( SCSI_CMD_READ_10 == p_cbw->command[0]) + { + if ( tud_msc_read10_complete_cb ) tud_msc_read10_complete_cb(p_cbw->lun); + } + else if ( SCSI_CMD_WRITE_10 == p_cbw->command[0] ) + { + if ( tud_msc_write10_complete_cb ) tud_msc_write10_complete_cb(p_cbw->lun); + } + else + { + if ( tud_msc_scsi_complete_cb ) tud_msc_scsi_complete_cb(p_cbw->lun, p_cbw->command); + } - // Move to default CMD stage after sending status - p_msc->stage = MSC_STAGE_CMD; + // Move to default CMD stage after sending status + p_msc->stage = MSC_STAGE_CMD; - TU_ASSERT( dcd_edpt_xfer(rhport, p_msc->ep_in , (uint8_t*) &p_msc->csw, sizeof(msc_csw_t)) ); + TU_ASSERT( dcd_edpt_xfer(rhport, p_msc->ep_in , (uint8_t*) &p_msc->csw, sizeof(msc_csw_t)) ); - //------------- Queue the next CBW -------------// - TU_ASSERT( dcd_edpt_xfer(rhport, p_msc->ep_out, (uint8_t*) &p_msc->cbw, sizeof(msc_cbw_t)) ); + //------------- Queue the next CBW -------------// + TU_ASSERT( dcd_edpt_xfer(rhport, p_msc->ep_out, (uint8_t*) &p_msc->cbw, sizeof(msc_cbw_t)) ); + } } return TUSB_ERROR_NONE; @@ -450,7 +459,7 @@ static void proc_read10_cmd(uint8_t rhport, mscd_interface_t* p_msc) } else if ( nbytes == 0 ) { - // zero means not ready -> try again later by simulate an transfer complete + // zero means not ready -> simulate an transfer complete so that this driver callback will fired again dcd_xfer_complete(rhport, p_msc->ep_in, 0, true); } else -- cgit v1.3.1 From 8fc1d151fc4b47e3d91b683caedf220adee8a630 Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 25 Jul 2018 22:24:58 +0700 Subject: correct msc stall behavior --- src/class/msc/msc_device.c | 3 --- 1 file changed, 3 deletions(-) (limited to 'src/class') diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index e2b35163d..488c9d41e 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -221,9 +221,6 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u p_csw->status = (cb_result == 0) ? MSC_CSW_STATUS_PASSED : MSC_CSW_STATUS_FAILED; p_msc->data_len = 0; p_msc->stage = MSC_STAGE_STATUS; - - // stall request since callback return negative - if ( cb_result < 0 ) dcd_edpt_stall(rhport, p_msc->ep_in); } else if ( !BIT_TEST_(p_cbw->dir, 7) ) { -- cgit v1.3.1 From 93db46292a2e9446c8d5be53279dcc6c91613755 Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 25 Jul 2018 22:35:02 +0700 Subject: update msc example --- examples/device/nrf52840/src/msc_device_app.c | 10 ++++++++-- src/class/msc/msc.h | 1 + 2 files changed, 9 insertions(+), 2 deletions(-) (limited to 'src/class') diff --git a/examples/device/nrf52840/src/msc_device_app.c b/examples/device/nrf52840/src/msc_device_app.c index 836dd2d48..1dfce5e16 100644 --- a/examples/device/nrf52840/src/msc_device_app.c +++ b/examples/device/nrf52840/src/msc_device_app.c @@ -97,12 +97,18 @@ int32_t tud_msc_scsi_cb (uint8_t lun, uint8_t const scsi_cmd[16], void* buffer, break; case SCSI_CMD_TEST_UNIT_READY: - ptr = NULL; + // Command that host uses to check our readiness before sending other commands len = 0; break; case SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL: - ptr = NULL; + // Host is about to read/write etc ... better not to disconnect disk + len = 0; + break; + + case SCSI_CMD_START_STOP_UNIT: + // Host try to eject/safe remove/powerof us. We could safely disconnect with disk storage, or go into lower power + // scsi_start_stop_unit_t const * cmd_start_stop = (scsi_start_stop_unit_t const *) scsi_cmd len = 0; break; diff --git a/src/class/msc/msc.h b/src/class/msc/msc.h index ed9fbfce5..333bb4d29 100644 --- a/src/class/msc/msc.h +++ b/src/class/msc/msc.h @@ -133,6 +133,7 @@ typedef enum SCSI_CMD_INQUIRY = 0x12, ///< The SCSI Inquiry command is used to obtain basic information from a target device. SCSI_CMD_MODE_SELECT_6 = 0x15, ///< provides a means for the application client to specify medium, logical unit, or peripheral device parameters to the device server. Device servers that implement the MODE SELECT(6) command shall also implement the MODE SENSE(6) command. Application clients should issue MODE SENSE(6) prior to each MODE SELECT(6) to determine supported mode pages, page lengths, and other parameters. SCSI_CMD_MODE_SENSE_6 = 0x1A, ///< provides a means for a device server to report parameters to an application client. It is a complementary command to the MODE SELECT(6) command. Device servers that implement the MODE SENSE(6) command shall also implement the MODE SELECT(6) command. + SCSI_CMD_START_STOP_UNIT = 0x1B, SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL = 0x1E, SCSI_CMD_READ_CAPACITY_10 = 0x25, ///< The SCSI Read Capacity command is used to obtain data capacity information from a target device. SCSI_CMD_REQUEST_SENSE = 0x03, ///< The SCSI Request Sense command is part of the SCSI computer protocol standard. This command is used to obtain sense data -- status/error information -- from a target device. -- cgit v1.3.1 From 226a4f8816ce265e4d90d9586699d70879fd3517 Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 25 Jul 2018 22:51:43 +0700 Subject: clean up device msc --- examples/device/nrf52840/src/msc_device_app.c | 18 ++++++++++-------- examples/obsolete/device/src/msc_device_app.c | 6 +++--- src/class/msc/msc.h | 26 +++++++++++++------------- 3 files changed, 26 insertions(+), 24 deletions(-) (limited to 'src/class') diff --git a/examples/device/nrf52840/src/msc_device_app.c b/examples/device/nrf52840/src/msc_device_app.c index 1dfce5e16..75d33d722 100644 --- a/examples/device/nrf52840/src/msc_device_app.c +++ b/examples/device/nrf52840/src/msc_device_app.c @@ -49,8 +49,10 @@ scsi_sense_fixed_data_t mscd_sense_data = { .response_code = 0x70, + .valid = 1, + .sense_key = 0, // no errors - .additional_sense_len = sizeof(scsi_sense_fixed_data_t) - 8 + .add_sense_len = sizeof(scsi_sense_fixed_data_t) - 8 }; static scsi_mode_parameters_t const msc_dev_mode_para = @@ -106,11 +108,11 @@ int32_t tud_msc_scsi_cb (uint8_t lun, uint8_t const scsi_cmd[16], void* buffer, len = 0; break; - case SCSI_CMD_START_STOP_UNIT: - // Host try to eject/safe remove/powerof us. We could safely disconnect with disk storage, or go into lower power - // scsi_start_stop_unit_t const * cmd_start_stop = (scsi_start_stop_unit_t const *) scsi_cmd - len = 0; - break; +// case SCSI_CMD_START_STOP_UNIT: +// // Host try to eject/safe remove/powerof us. We could safely disconnect with disk storage, or go into lower power +// // scsi_start_stop_unit_t const * cmd_start_stop = (scsi_start_stop_unit_t const *) scsi_cmd +// len = 0; +// break; default: // negative is error -> Data stage is STALL, status = failed @@ -135,8 +137,8 @@ int32_t tud_msc_scsi_cb (uint8_t lun, uint8_t const scsi_cmd[16], void* buffer, if ( SCSI_CMD_REQUEST_SENSE != scsi_cmd[0] ) { mscd_sense_data.sense_key = SCSI_SENSEKEY_NONE; - mscd_sense_data.additional_sense_code = 0; - mscd_sense_data.additional_sense_qualifier = 0; + mscd_sense_data.add_sense_code = 0; + mscd_sense_data.add_sense_qualifier = 0; } return len; diff --git a/examples/obsolete/device/src/msc_device_app.c b/examples/obsolete/device/src/msc_device_app.c index 572c90efd..0831d4444 100644 --- a/examples/obsolete/device/src/msc_device_app.c +++ b/examples/obsolete/device/src/msc_device_app.c @@ -67,7 +67,7 @@ static scsi_sense_fixed_data_t mscd_sense_data = { .response_code = 0x70, .sense_key = 0, // no errors - .additional_sense_len = sizeof(scsi_sense_fixed_data_t) - 8 + .add_sense_len = sizeof(scsi_sense_fixed_data_t) - 8 }; static scsi_read_format_capacity_data_t const mscd_format_capacity_data = @@ -169,8 +169,8 @@ int32_t tud_msc_scsi_cb (uint8_t lun, uint8_t const scsi_cmd[16], void* buffer, if ( SCSI_CMD_REQUEST_SENSE != scsi_cmd[0] ) { mscd_sense_data.sense_key = SCSI_SENSEKEY_NONE; - mscd_sense_data.additional_sense_code = 0; - mscd_sense_data.additional_sense_qualifier = 0; + mscd_sense_data.add_sense_code = 0; + mscd_sense_data.add_sense_qualifier = 0; } return len; diff --git a/src/class/msc/msc.h b/src/class/msc/msc.h index 333bb4d29..290ee2550 100644 --- a/src/class/msc/msc.h +++ b/src/class/msc/msc.h @@ -237,25 +237,25 @@ VERIFY_STATIC(sizeof(scsi_inquiry_data_t) == 36, "size is not correct"); typedef struct ATTR_PACKED { - uint8_t response_code : 7; ///< 70h - current errors, Fixed Format 71h - deferred errors, Fixed Format - uint8_t valid : 1; + uint8_t response_code : 7; ///< 70h - current errors, Fixed Format 71h - deferred errors, Fixed Format + uint8_t valid : 1; - uint8_t reserved; ///< Obsolete + uint8_t TU_RESERVED; - uint8_t sense_key : 4; - uint8_t : 1; - uint8_t incorrect_len_idicatior : 1; - uint8_t end_of_medium : 1; - uint8_t filemark : 1; + uint8_t sense_key : 4; + uint8_t : 1; + uint8_t ili : 1; ///< Incorrect length indicator + uint8_t end_of_medium : 1; + uint8_t filemark : 1; uint32_t information; - uint8_t additional_sense_len; + uint8_t add_sense_len; uint32_t command_specific_info; - uint8_t additional_sense_code; - uint8_t additional_sense_qualifier; - uint8_t field_replaceable_unit_code; + uint8_t add_sense_code; + uint8_t add_sense_qualifier; + uint8_t field_replaceable_unit_code; - uint8_t sense_key_specific[3]; ///< sense key specific valid bit is bit 7 of key[0], aka MSB in Big Endian layout + uint8_t sense_key_specific[3]; ///< sense key specific valid bit is bit 7 of key[0], aka MSB in Big Endian layout } scsi_sense_fixed_data_t; -- cgit v1.3.1 From 8694285ad2fc7bd5caf8c35691056252ef534c7b Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 25 Jul 2018 23:56:06 +0700 Subject: add SCSI_CMD_REQUEST_SENSE into device msc built-in command --- examples/device/nrf52840/src/msc_device_app.c | 22 ---- examples/device/nrf52840/src/msc_device_app.h | 2 - src/class/msc/msc.h | 2 +- src/class/msc/msc_device.c | 139 ++++++++++++++++++-------- 4 files changed, 96 insertions(+), 69 deletions(-) (limited to 'src/class') diff --git a/examples/device/nrf52840/src/msc_device_app.c b/examples/device/nrf52840/src/msc_device_app.c index 75d33d722..e20ad45f8 100644 --- a/examples/device/nrf52840/src/msc_device_app.c +++ b/examples/device/nrf52840/src/msc_device_app.c @@ -46,15 +46,6 @@ //--------------------------------------------------------------------+ // MACRO CONSTANT TYPEDEF //--------------------------------------------------------------------+ -scsi_sense_fixed_data_t mscd_sense_data = -{ - .response_code = 0x70, - .valid = 1, - - .sense_key = 0, // no errors - .add_sense_len = sizeof(scsi_sense_fixed_data_t) - 8 -}; - static scsi_mode_parameters_t const msc_dev_mode_para = { .mode_data_length = 3, @@ -88,11 +79,6 @@ int32_t tud_msc_scsi_cb (uint8_t lun, uint8_t const scsi_cmd[16], void* buffer, switch (scsi_cmd[0]) { - case SCSI_CMD_REQUEST_SENSE: - ptr = &mscd_sense_data; - len = sizeof(scsi_sense_fixed_data_t); - break; - case SCSI_CMD_MODE_SENSE_6: ptr = &msc_dev_mode_para; len = sizeof(msc_dev_mode_para); @@ -133,14 +119,6 @@ int32_t tud_msc_scsi_cb (uint8_t lun, uint8_t const scsi_cmd[16], void* buffer, } } - //------------- clear sense data if it is not request sense command -------------// - if ( SCSI_CMD_REQUEST_SENSE != scsi_cmd[0] ) - { - mscd_sense_data.sense_key = SCSI_SENSEKEY_NONE; - mscd_sense_data.add_sense_code = 0; - mscd_sense_data.add_sense_qualifier = 0; - } - return len; } diff --git a/examples/device/nrf52840/src/msc_device_app.h b/examples/device/nrf52840/src/msc_device_app.h index 0ed04d285..cc3caa102 100644 --- a/examples/device/nrf52840/src/msc_device_app.h +++ b/examples/device/nrf52840/src/msc_device_app.h @@ -75,8 +75,6 @@ void msc_app_task(void* param); void msc_app_mount(uint8_t rhport); void msc_app_umount(uint8_t rhport); -extern scsi_sense_fixed_data_t mscd_sense_data; - #else #define msc_app_init() diff --git a/src/class/msc/msc.h b/src/class/msc/msc.h index 290ee2550..630f4e7ba 100644 --- a/src/class/msc/msc.h +++ b/src/class/msc/msc.h @@ -240,7 +240,7 @@ typedef struct ATTR_PACKED uint8_t response_code : 7; ///< 70h - current errors, Fixed Format 71h - deferred errors, Fixed Format uint8_t valid : 1; - uint8_t TU_RESERVED; + uint8_t reserved; uint8_t sense_key : 4; uint8_t : 1; diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index 488c9d41e..ef8a45bc9 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -72,9 +72,15 @@ typedef struct { uint8_t ep_in; uint8_t ep_out; + // Bulk Only Transfer (BOT) Protocol uint8_t stage; uint32_t data_len; uint32_t xferred_len; // numbered of bytes transferred so far in the Data Stage + + // Sense Response Data + uint8_t sense_key; + uint8_t add_sense_code; + uint8_t add_sense_qualifier; }mscd_interface_t; CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN static mscd_interface_t _mscd_itf; @@ -173,6 +179,91 @@ tusb_error_t mscd_control_request_st(uint8_t rhport, tusb_control_request_t cons OSAL_SUBTASK_END } +// return length of response (copied to buffer), -1 if it is not an built-in commands +int32_t proc_builtin_scsi(msc_cbw_t const * p_cbw, uint8_t* buffer, uint32_t bufsize) +{ + int32_t ret; + + switch ( p_cbw->command[0] ) + { + case SCSI_CMD_READ_CAPACITY_10: + { + scsi_read_capacity10_data_t read_capa10 = + { + .last_lba = ENDIAN_BE(CFG_TUD_MSC_BLOCK_NUM-1), // read capacity + .block_size = ENDIAN_BE(CFG_TUD_MSC_BLOCK_SZ) + }; + + ret = sizeof(read_capa10); + memcpy(buffer, &read_capa10, ret); + } + break; + + case SCSI_CMD_READ_FORMAT_CAPACITY: + { + scsi_read_format_capacity_data_t read_fmt_capa = + { + .list_length = 8, + .block_num = ENDIAN_BE(CFG_TUD_MSC_BLOCK_NUM), // write capacity + .descriptor_type = 2, // formatted media + .block_size_u16 = ENDIAN_BE16(CFG_TUD_MSC_BLOCK_SZ) + }; + + ret = sizeof(read_fmt_capa); + memcpy(buffer, &read_fmt_capa, ret); + } + break; + + case SCSI_CMD_INQUIRY: + { + scsi_inquiry_data_t inquiry_rsp = + { + .is_removable = 1, + .version = 2, + .response_data_format = 2, + .vendor_id = "Adafruit", + .product_id = "Feather52840", + .product_rev = "1.0" + }; + + strncpy((char*) inquiry_rsp.vendor_id , CFG_TUD_MSC_VENDOR , sizeof(inquiry_rsp.vendor_id)); + strncpy((char*) inquiry_rsp.product_id , CFG_TUD_MSC_PRODUCT , sizeof(inquiry_rsp.product_id)); + strncpy((char*) inquiry_rsp.product_rev, CFG_TUD_MSC_PRODUCT_REV, sizeof(inquiry_rsp.product_rev)); + + ret = sizeof(inquiry_rsp); + memcpy(buffer, &inquiry_rsp, ret); + } + break; + + case SCSI_CMD_REQUEST_SENSE: + { + scsi_sense_fixed_data_t sense_rsp = + { + .response_code = 0x70, + .valid = 1 + }; + + sense_rsp.add_sense_len = sizeof(scsi_sense_fixed_data_t) - 8; + + ret = sizeof(sense_rsp); + memcpy(buffer, &sense_rsp, ret); + } + break; + + default: ret = -1; break; + } + + //------------- clear sense data if it is not request sense command -------------// +// if ( SCSI_CMD_REQUEST_SENSE != p_cbw->command[0]) +// { +// sense_rsp.sense_key = SCSI_SENSEKEY_NONE; +// sense_rsp.add_sense_code = 0; +// sense_rsp.add_sense_qualifier = 0; +// } + + return ret; +} + tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, uint32_t xferred_bytes) { mscd_interface_t* p_msc = &_mscd_itf; @@ -232,51 +323,11 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u // IN Transfer int32_t cb_result; - // TODO refactor later - if (SCSI_CMD_READ_CAPACITY_10 == p_cbw->command[0]) - { - scsi_read_capacity10_data_t read_capa10 = - { - .last_lba = ENDIAN_BE(CFG_TUD_MSC_BLOCK_NUM-1), // read capacity - .block_size = ENDIAN_BE(CFG_TUD_MSC_BLOCK_SZ) - }; + // first process if it is a built-in commands + cb_result = proc_builtin_scsi(p_cbw, _mscd_buf, sizeof(_mscd_buf)); - cb_result = sizeof(read_capa10); - memcpy(_mscd_buf, &read_capa10, cb_result); - } - else if (SCSI_CMD_READ_FORMAT_CAPACITY == p_cbw->command[0]) - { - scsi_read_format_capacity_data_t read_fmt_capa = - { - .list_length = 8, - .block_num = ENDIAN_BE(CFG_TUD_MSC_BLOCK_NUM), // write capacity - .descriptor_type = 2, // formatted media - .block_size_u16 = ENDIAN_BE16(CFG_TUD_MSC_BLOCK_SZ) - }; - - cb_result = sizeof(read_fmt_capa); - memcpy(_mscd_buf, &read_fmt_capa, cb_result); - } - else if (SCSI_CMD_INQUIRY == p_cbw->command[0]) - { - scsi_inquiry_data_t inquiry_rsp = - { - .is_removable = 1, - .version = 2, - .response_data_format = 2, - .vendor_id = "Adafruit", - .product_id = "Feather52840", - .product_rev = "1.0" - }; - - strncpy((char*) inquiry_rsp.vendor_id , CFG_TUD_MSC_VENDOR , sizeof(inquiry_rsp.vendor_id)); - strncpy((char*) inquiry_rsp.product_id , CFG_TUD_MSC_PRODUCT , sizeof(inquiry_rsp.product_id)); - strncpy((char*) inquiry_rsp.product_rev, CFG_TUD_MSC_PRODUCT_REV, sizeof(inquiry_rsp.product_rev)); - - cb_result = sizeof(inquiry_rsp); - memcpy(_mscd_buf, &inquiry_rsp, cb_result); - } - else + // Not an built-in command, invoke user callback + if ( cb_result < 0 ) { cb_result = tud_msc_scsi_cb(p_cbw->lun, p_cbw->command, _mscd_buf, p_msc->data_len); } -- cgit v1.3.1 From 602315cd57535598c88034727116532689ed6b65 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 26 Jul 2018 11:27:34 +0700 Subject: fix hid keyboard idle rate --- src/class/hid/hid_device.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/class') diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index 81805665e..7aeb39957 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -115,7 +115,7 @@ static bool hidd_kbd_report(hid_keyboard_report_t const *p_report) if ( 0 == memcmp(p_hid->report_buf, p_report, sizeof(hid_keyboard_report_t)) ) return true; } - tu_timeout_restart(&idle_tm); + tu_timeout_set(&idle_tm, p_hid->idle_rate *4); memcpy(p_hid->report_buf, p_report, sizeof(hid_keyboard_report_t)); return dcd_edpt_xfer(TUD_OPT_RHPORT, p_hid->ep_in, p_hid->report_buf, sizeof(hid_keyboard_report_t)); -- cgit v1.3.1 From f5b2912372b6fbd69a18774f46155ae6723cb4e3 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 26 Jul 2018 15:59:13 +0700 Subject: add tud_msc_set_sense(), update msc device to reponse with default sense (illegal request) when there is issue with scsi command --- src/class/msc/msc.h | 30 ++++----- src/class/msc/msc_device.c | 81 ++++++++++++++++-------- src/class/msc/msc_device.h | 1 + src/class/msc/msc_host.c | 4 +- tests/lpc18xx_43xx/test/host/msc/test_msc_host.c | 2 +- 5 files changed, 72 insertions(+), 46 deletions(-) (limited to 'src/class') diff --git a/src/class/msc/msc.h b/src/class/msc/msc.h index 630f4e7ba..fe90e6684 100644 --- a/src/class/msc/msc.h +++ b/src/class/msc/msc.h @@ -83,8 +83,8 @@ typedef enum /// MassStorage Class-Specific Control Request typedef enum { - MSC_REQUEST_GET_MAX_LUN = 254, ///< The Get Max LUN device request is used to determine the number of logical units supported by the device. Logical Unit Numbers on the device shall be numbered contiguously starting from LUN 0 to a maximum LUN of 15 - MSC_REQUEST_RESET = 255 ///< This request is used to reset the mass storage device and its associated interface. This class-specific request shall ready the device for the next CBW from the host. + MSC_REQ_GET_MAX_LUN = 254, ///< The Get Max LUN device request is used to determine the number of logical units supported by the device. Logical Unit Numbers on the device shall be numbered contiguously starting from LUN 0 to a maximum LUN of 15 + MSC_REQ_RESET = 255 ///< This request is used to reset the mass storage device and its associated interface. This class-specific request shall ready the device for the next CBW from the host. }msc_request_type_t; /// \brief Command Block Status Values @@ -145,19 +145,19 @@ typedef enum /// SCSI Sense Key typedef enum { - SCSI_SENSEKEY_NONE = 0x00, ///< no specific Sense Key. This would be the case for a successful command - SCSI_SENSEKEY_RECOVERED_ERROR = 0x01, ///< ndicates the last command completed successfully with some recovery action performed by the disc drive. - SCSI_SENSEKEY_NOT_READY = 0x02, ///< Indicates the logical unit addressed cannot be accessed. - SCSI_SENSEKEY_MEDIUM_ERROR = 0x03, ///< Indicates the command terminated with a non-recovered error condition. - SCSI_SENSEKEY_HARDWARE_ERROR = 0x04, ///< Indicates the disc drive detected a nonrecoverable hardware failure while performing the command or during a self test. - SCSI_SENSEKEY_ILLEGLA_REQUEST = 0x05, ///< Indicates an illegal parameter in the command descriptor block or in the additional parameters - SCSI_SENSEKEY_UNIT_ATTENTION = 0x06, ///< Indicates the disc drive may have been reset. - SCSI_SENSEKEY_DATA_PROTECT = 0x07, ///< Indicates that a command that reads or writes the medium was attempted on a block that is protected from this operation. The read or write operation is not performed. - SCSI_SENSEKEY_FIRMWARE_ERROR = 0x08, ///< Vendor specific sense key. - SCSI_SENSEKEY_ABORTED_COMMAND = 0x0b, ///< Indicates the disc drive aborted the command. - SCSI_SENSEKEY_EQUAL = 0x0c, ///< Indicates a SEARCH DATA command has satisfied an equal comparison. - SCSI_SENSEKEY_VOLUME_OVERFLOW = 0x0d, ///< Indicates a buffered peripheral device has reached the end of medium partition and data remains in the buffer that has not been written to the medium. - SCSI_SENSEKEY_MISCOMPARE = 0x0e ///< ndicates that the source data did not match the data read from the medium. + SCSI_SENSE_NONE = 0x00, ///< no specific Sense Key. This would be the case for a successful command + SCSI_SENSE_RECOVERED_ERROR = 0x01, ///< ndicates the last command completed successfully with some recovery action performed by the disc drive. + SCSI_SENSE_NOT_READY = 0x02, ///< Indicates the logical unit addressed cannot be accessed. + SCSI_SENSE_MEDIUM_ERROR = 0x03, ///< Indicates the command terminated with a non-recovered error condition. + SCSI_SENSE_HARDWARE_ERROR = 0x04, ///< Indicates the disc drive detected a nonrecoverable hardware failure while performing the command or during a self test. + SCSI_SENSE_ILLEGAL_REQUEST = 0x05, ///< Indicates an illegal parameter in the command descriptor block or in the additional parameters + SCSI_SENSE_UNIT_ATTENTION = 0x06, ///< Indicates the disc drive may have been reset. + SCSI_SENSE_DATA_PROTECT = 0x07, ///< Indicates that a command that reads or writes the medium was attempted on a block that is protected from this operation. The read or write operation is not performed. + SCSI_SENSE_FIRMWARE_ERROR = 0x08, ///< Vendor specific sense key. + SCSI_SENSE_ABORTED_COMMAND = 0x0b, ///< Indicates the disc drive aborted the command. + SCSI_SENSE_EQUAL = 0x0c, ///< Indicates a SEARCH DATA command has satisfied an equal comparison. + SCSI_SENSE_VOLUME_OVERFLOW = 0x0d, ///< Indicates a buffered peripheral device has reached the end of medium partition and data remains in the buffer that has not been written to the medium. + SCSI_SENSE_MISCOMPARE = 0x0e ///< ndicates that the source data did not match the data read from the medium. }scsi_sense_key_type_t; //--------------------------------------------------------------------+ diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index ef8a45bc9..9f037a73c 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -116,11 +116,25 @@ static inline uint16_t rdwr10_get_blockcount(uint8_t const command[]) return __be2n_16(block_count); } +//--------------------------------------------------------------------+ +// APPLICATION API +//--------------------------------------------------------------------+ bool tud_msc_ready(void) { return ( _mscd_itf.ep_in != 0 ) && ( _mscd_itf.ep_out != 0 ) ; } +bool tud_msc_set_sense(uint8_t lun, uint8_t sense_key, uint8_t add_sense_code, uint8_t add_sense_qualifier) +{ + (void) lun; + + _mscd_itf.sense_key = sense_key; + _mscd_itf.add_sense_code = add_sense_code; + _mscd_itf.add_sense_qualifier = add_sense_qualifier; + + return true; +} + //--------------------------------------------------------------------+ // USBD-CLASS API @@ -162,11 +176,11 @@ tusb_error_t mscd_control_request_st(uint8_t rhport, tusb_control_request_t cons TU_ASSERT(p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS, TUSB_ERROR_DCD_CONTROL_REQUEST_NOT_SUPPORT); - if(MSC_REQUEST_RESET == p_request->bRequest) + if(MSC_REQ_RESET == p_request->bRequest) { dcd_control_status(rhport, p_request->bmRequestType_bit.direction); } - else if (MSC_REQUEST_GET_MAX_LUN == p_request->bRequest) + else if (MSC_REQ_GET_MAX_LUN == p_request->bRequest) { // returned MAX LUN is minus 1 by specs _usbd_ctrl_buf[0] = CFG_TUD_MSC_MAXLUN-1; @@ -245,22 +259,21 @@ int32_t proc_builtin_scsi(msc_cbw_t const * p_cbw, uint8_t* buffer, uint32_t buf sense_rsp.add_sense_len = sizeof(scsi_sense_fixed_data_t) - 8; + sense_rsp.sense_key = _mscd_itf.sense_key; + sense_rsp.add_sense_code = _mscd_itf.add_sense_code; + sense_rsp.add_sense_qualifier = _mscd_itf.add_sense_qualifier; + ret = sizeof(sense_rsp); memcpy(buffer, &sense_rsp, ret); + + // Clear sense data after copy + tud_msc_set_sense(p_cbw->lun, 0, 0, 0); } break; default: ret = -1; break; } - //------------- clear sense data if it is not request sense command -------------// -// if ( SCSI_CMD_REQUEST_SENSE != p_cbw->command[0]) -// { -// sense_rsp.sense_key = SCSI_SENSEKEY_NONE; -// sense_rsp.add_sense_code = 0; -// sense_rsp.add_sense_qualifier = 0; -// } - return ret; } @@ -309,9 +322,18 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u { int32_t const cb_result = tud_msc_scsi_cb(p_cbw->lun, p_cbw->command, NULL, 0); - p_csw->status = (cb_result == 0) ? MSC_CSW_STATUS_PASSED : MSC_CSW_STATUS_FAILED; p_msc->data_len = 0; p_msc->stage = MSC_STAGE_STATUS; + + if ( cb_result < 0 ) + { + p_csw->status = MSC_CSW_STATUS_FAILED; + tud_msc_set_sense(p_cbw->lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00); // Sense = Invalid Command Operation + } + else + { + p_csw->status = MSC_CSW_STATUS_PASSED; + } } else if ( !BIT_TEST_(p_cbw->dir, 7) ) { @@ -334,25 +356,18 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u if ( cb_result > 0 ) { - p_csw->status = MSC_CSW_STATUS_PASSED; p_msc->data_len = (uint32_t) cb_result; - }else - { - p_csw->status = MSC_CSW_STATUS_FAILED; - p_msc->data_len = 0; - } - - TU_ASSERT( p_cbw->xfer_bytes >= p_msc->data_len, TUSB_ERROR_INVALID_PARA ); // cannot return more than host expect + p_csw->status = MSC_CSW_STATUS_PASSED; - if ( p_msc->data_len ) - { + TU_ASSERT( p_cbw->xfer_bytes >= p_msc->data_len, TUSB_ERROR_INVALID_PARA ); // cannot return more than host expect TU_ASSERT( dcd_edpt_xfer(rhport, p_msc->ep_in, _mscd_buf, p_msc->data_len), TUSB_ERROR_DCD_EDPT_XFER ); }else { - // callback does not provide response's data --> possibly unsupported SCSI command - p_csw->status = MSC_CSW_STATUS_FAILED; - p_msc->stage = MSC_STAGE_STATUS; + p_msc->data_len = 0; + p_csw->status = MSC_CSW_STATUS_FAILED; + p_msc->stage = MSC_STAGE_STATUS; + tud_msc_set_sense(p_cbw->lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00); // Sense = Invalid Command Operation dcd_edpt_stall(rhport, p_msc->ep_in); } } @@ -365,7 +380,16 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u { if ( SCSI_CMD_WRITE_10 != p_cbw->command[0] ) { - p_csw->status = (tud_msc_scsi_cb(p_cbw->lun, p_cbw->command, _mscd_buf, p_msc->data_len) >= 0 ) ? MSC_CSW_STATUS_PASSED : MSC_CSW_STATUS_FAILED; + int32_t cb_result = tud_msc_scsi_cb(p_cbw->lun, p_cbw->command, _mscd_buf, p_msc->data_len); + + if ( cb_result < 0 ) + { + p_csw->status = MSC_CSW_STATUS_FAILED; + tud_msc_set_sense(p_cbw->lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00); // Sense = Invalid Command Operation + }else + { + p_csw->status = MSC_CSW_STATUS_PASSED; + } } else { @@ -382,8 +406,9 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u // negative means error -> skip to status phase, status in CSW set to failed p_csw->data_residue = p_cbw->xfer_bytes - p_msc->xferred_len; p_csw->status = MSC_CSW_STATUS_FAILED; + p_msc->stage = MSC_STAGE_STATUS; - p_msc->stage = MSC_STAGE_STATUS; + tud_msc_set_sense(p_cbw->lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00); // Sense = Invalid Command Operation break; }else { @@ -403,8 +428,7 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u } else { - // Application consume all bytes in our buffer - // Nothing to do, process with normal flow + // Application consume all bytes in our buffer. Nothing to do, process with normal flow } } } @@ -503,6 +527,7 @@ static void proc_read10_cmd(uint8_t rhport, mscd_interface_t* p_msc) p_csw->data_residue = p_cbw->xfer_bytes - p_msc->xferred_len; p_csw->status = MSC_CSW_STATUS_FAILED; + tud_msc_set_sense(p_cbw->lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00); // Sense = Invalid Command Operation dcd_edpt_stall(rhport, p_msc->ep_in); } else if ( nbytes == 0 ) diff --git a/src/class/msc/msc_device.h b/src/class/msc/msc_device.h index 60144cc55..236968f49 100644 --- a/src/class/msc/msc_device.h +++ b/src/class/msc/msc_device.h @@ -97,6 +97,7 @@ VERIFY_STATIC(CFG_TUD_MSC_BUFSIZE < UINT16_MAX, "Size is not correct"); // Check if MSC interface is ready to use bool tud_msc_ready(void); +bool tud_msc_set_sense(uint8_t lun, uint8_t sense_key, uint8_t add_sense_code, uint8_t add_sense_qualifier); //--------------------------------------------------------------------+ // APPLICATION CALLBACK API (WEAK is optional) diff --git a/src/class/msc/msc_host.c b/src/class/msc/msc_host.c index afe7032a6..7e6396389 100644 --- a/src/class/msc/msc_host.c +++ b/src/class/msc/msc_host.c @@ -329,7 +329,7 @@ tusb_error_t msch_open_subtask(uint8_t dev_addr, tusb_desc_interface_t const *p_ //------------- Get Max Lun -------------// STASK_INVOKE( usbh_control_xfer_subtask( dev_addr, bm_request_type(TUSB_DIR_IN, TUSB_REQ_TYPE_CLASS, TUSB_REQ_RCPT_INTERFACE), - MSC_REQUEST_GET_MAX_LUN, 0, msch_data[dev_addr-1].interface_number, + MSC_REQ_GET_MAX_LUN, 0, msch_data[dev_addr-1].interface_number, 1, msch_buffer ), error ); @@ -341,7 +341,7 @@ tusb_error_t msch_open_subtask(uint8_t dev_addr, tusb_desc_interface_t const *p_ //------------- Reset -------------// STASK_INVOKE( usbh_control_xfer_subtask( dev_addr, bm_request_type(TUSB_DIR_OUT, TUSB_REQ_TYPE_CLASS, TUSB_REQ_RCPT_INTERFACE), - MSC_REQUEST_RESET, 0, msch_data[dev_addr-1].interface_number, + MSC_REQ_RESET, 0, msch_data[dev_addr-1].interface_number, 0, NULL ), error ); diff --git a/tests/lpc18xx_43xx/test/host/msc/test_msc_host.c b/tests/lpc18xx_43xx/test/host/msc/test_msc_host.c index 2a752f971..3f4f9102b 100644 --- a/tests/lpc18xx_43xx/test/host/msc/test_msc_host.c +++ b/tests/lpc18xx_43xx/test/host/msc/test_msc_host.c @@ -105,7 +105,7 @@ tusb_error_t stub_control_xfer(uint8_t dev_addr, uint8_t bmRequestType, uint8_t case 0: // get max lun TEST_ASSERT_EQUAL(bm_request_type(TUSB_DIR_DEV_TO_HOST, TUSB_REQ_TYPE_CLASS, TUSB_REQ_RECIPIENT_INTERFACE), bmRequestType); - TEST_ASSERT_EQUAL(MSC_REQUEST_GET_MAX_LUN, bRequest); + TEST_ASSERT_EQUAL(MSC_REQ_GET_MAX_LUN, bRequest); TEST_ASSERT_EQUAL(p_msc_interface_desc->bInterfaceNumber, wIndex); TEST_ASSERT_EQUAL(1, wLength); *data = 1; // TODO multiple LUN support -- cgit v1.3.1 From faf88d00c2a03a38465932b1e8215656ba56316a Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 26 Jul 2018 16:01:14 +0700 Subject: clean up --- src/class/hid/hid_device.c | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src/class') diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index 7aeb39957..316067e61 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -446,6 +446,8 @@ tusb_error_t hidd_xfer_cb(uint8_t rhport, uint8_t edpt_addr, tusb_event_t event, /*------------------------------------------------------------------*/ /* Ascii to Keycode *------------------------------------------------------------------*/ +#if CFG_TUD_HID_ASCII_TO_KEYCODE_LOOKUP + const hid_ascii_to_keycode_entry_t HID_ASCII_TO_KEYCODE[128] = { {0, 0 }, // 0x00 Null @@ -582,3 +584,5 @@ const hid_ascii_to_keycode_entry_t HID_ASCII_TO_KEYCODE[128] = }; #endif + +#endif -- cgit v1.3.1 From e362f5fd64d257e3ad70962be59fc8593a0f5d95 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 26 Jul 2018 16:57:30 +0700 Subject: rename some scsi command struct, add SCSI_CMD_MODE_SENSE_6 to built-in support command --- examples/device/nrf52840/src/msc_device_app.c | 20 +------ examples/obsolete/device/src/msc_device_app.c | 84 +++------------------------ src/class/msc/msc.h | 24 ++++---- src/class/msc/msc_device.c | 23 ++++++-- 4 files changed, 41 insertions(+), 110 deletions(-) (limited to 'src/class') diff --git a/examples/device/nrf52840/src/msc_device_app.c b/examples/device/nrf52840/src/msc_device_app.c index 5edd4e0f5..aa6b2fb43 100644 --- a/examples/device/nrf52840/src/msc_device_app.c +++ b/examples/device/nrf52840/src/msc_device_app.c @@ -39,20 +39,10 @@ #include "msc_device_app.h" #if CFG_TUD_MSC -//--------------------------------------------------------------------+ -// INCLUDE -//--------------------------------------------------------------------+ //--------------------------------------------------------------------+ // MACRO CONSTANT TYPEDEF //--------------------------------------------------------------------+ -static scsi_mode_parameters_t const msc_dev_mode_para = -{ - .mode_data_length = 3, - .medium_type = 0, - .device_specific_para = 0, - .block_descriptor_length = 0 -}; //--------------------------------------------------------------------+ // tinyusb callbacks @@ -79,11 +69,6 @@ int32_t tud_msc_scsi_cb (uint8_t lun, uint8_t const scsi_cmd[16], void* buffer, switch (scsi_cmd[0]) { - case SCSI_CMD_MODE_SENSE_6: - ptr = &msc_dev_mode_para; - len = sizeof(msc_dev_mode_para); - break; - case SCSI_CMD_TEST_UNIT_READY: // Command that host uses to check our readiness before sending other commands len = 0; @@ -100,9 +85,8 @@ int32_t tud_msc_scsi_cb (uint8_t lun, uint8_t const scsi_cmd[16], void* buffer, len = 0; break; - default: - // negative is error -> Data stage is STALL, status = failed - return -1; + // negative is error -> Data stage is STALL, status = failed + default: return -1; } // return len must not larger than bufsize diff --git a/examples/obsolete/device/src/msc_device_app.c b/examples/obsolete/device/src/msc_device_app.c index 0831d4444..5190e6265 100644 --- a/examples/obsolete/device/src/msc_device_app.c +++ b/examples/obsolete/device/src/msc_device_app.c @@ -39,52 +39,11 @@ #include "msc_device_app.h" #if CFG_TUD_MSC -//--------------------------------------------------------------------+ -// INCLUDE -//--------------------------------------------------------------------+ #include "app_os_prio.h" //--------------------------------------------------------------------+ // MACRO CONSTANT TYPEDEF //--------------------------------------------------------------------+ -static scsi_inquiry_data_t const mscd_inquiry_data = -{ - .is_removable = 1, - .version = 2, - .response_data_format = 2, - .vendor_id = "tinyusb", - .product_id = "MSC Example", - .product_revision = "0.01" -}; - -static scsi_read_capacity10_data_t const mscd_read_capacity10_data = -{ - .last_lba = ENDIAN_BE(DISK_BLOCK_NUM-1), // Big Endian - .block_size = ENDIAN_BE(DISK_BLOCK_SIZE) // Big Endian -}; - -static scsi_sense_fixed_data_t mscd_sense_data = -{ - .response_code = 0x70, - .sense_key = 0, // no errors - .add_sense_len = sizeof(scsi_sense_fixed_data_t) - 8 -}; - -static scsi_read_format_capacity_data_t const mscd_format_capacity_data = -{ - .list_length = 8, - .block_num = ENDIAN_BE(DISK_BLOCK_NUM), // write capacity - .descriptor_type = 2, // TODO formatted media, refractor to const - .block_size_u16 = ENDIAN_BE16(DISK_BLOCK_SIZE) -}; - -static scsi_mode_parameters_t const msc_dev_mode_para = -{ - .mode_data_length = 3, - .medium_type = 0, - .device_specific_para = 0, - .block_descriptor_length = 0 -}; //--------------------------------------------------------------------+ // tinyusb callbacks @@ -111,38 +70,19 @@ int32_t tud_msc_scsi_cb (uint8_t lun, uint8_t const scsi_cmd[16], void* buffer, switch (scsi_cmd[0]) { - case SCSI_CMD_INQUIRY: - ptr = &mscd_inquiry_data; - len = sizeof(scsi_inquiry_data_t); - break; - - case SCSI_CMD_READ_CAPACITY_10: - ptr = &mscd_read_capacity10_data; - len = sizeof(scsi_read_capacity10_data_t); - break; - - case SCSI_CMD_REQUEST_SENSE: - ptr = &mscd_sense_data; - len = sizeof(scsi_sense_fixed_data_t); - break; - - case SCSI_CMD_READ_FORMAT_CAPACITY: - ptr = &mscd_format_capacity_data; - len = sizeof(scsi_read_format_capacity_data_t); - break; - - case SCSI_CMD_MODE_SENSE_6: - ptr = &msc_dev_mode_para; - len = sizeof(msc_dev_mode_para); - break; - case SCSI_CMD_TEST_UNIT_READY: - ptr = NULL; + // Command that host uses to check our readiness before sending other commands len = 0; break; case SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL: - ptr = NULL; + // Host is about to read/write etc ... better not to disconnect disk + len = 0; + break; + + case SCSI_CMD_START_STOP_UNIT: + // Host try to eject/safe remove/powerof us. We could safely disconnect with disk storage, or go into lower power + // scsi_start_stop_unit_t const * cmd_start_stop = (scsi_start_stop_unit_t const *) scsi_cmd len = 0; break; @@ -165,14 +105,6 @@ int32_t tud_msc_scsi_cb (uint8_t lun, uint8_t const scsi_cmd[16], void* buffer, } } - //------------- clear sense data if it is not request sense command -------------// - if ( SCSI_CMD_REQUEST_SENSE != scsi_cmd[0] ) - { - mscd_sense_data.sense_key = SCSI_SENSEKEY_NONE; - mscd_sense_data.add_sense_code = 0; - mscd_sense_data.add_sense_qualifier = 0; - } - return len; } diff --git a/src/class/msc/msc.h b/src/class/msc/msc.h index fe90e6684..ab8f066b3 100644 --- a/src/class/msc/msc.h +++ b/src/class/msc/msc.h @@ -230,9 +230,9 @@ typedef struct ATTR_PACKED uint8_t vendor_id[8] ; ///< 8 bytes of ASCII data identifying the vendor of the product. uint8_t product_id[16]; ///< 16 bytes of ASCII data defined by the vendor. uint8_t product_rev[4]; ///< 4 bytes of ASCII data defined by the vendor. -} scsi_inquiry_data_t; +} scsi_inquiry_resp_t; -VERIFY_STATIC(sizeof(scsi_inquiry_data_t) == 36, "size is not correct"); +VERIFY_STATIC(sizeof(scsi_inquiry_resp_t) == 36, "size is not correct"); typedef struct ATTR_PACKED @@ -257,9 +257,9 @@ typedef struct ATTR_PACKED uint8_t sense_key_specific[3]; ///< sense key specific valid bit is bit 7 of key[0], aka MSB in Big Endian layout -} scsi_sense_fixed_data_t; +} scsi_sense_fixed_resp_t; -VERIFY_STATIC(sizeof(scsi_sense_fixed_data_t) == 18, "size is not correct"); +VERIFY_STATIC(sizeof(scsi_sense_fixed_resp_t) == 18, "size is not correct"); typedef struct ATTR_PACKED { @@ -275,19 +275,19 @@ typedef struct ATTR_PACKED uint8_t subpage_code; uint8_t alloc_length; uint8_t control; -} scsi_mode_sense_6_t; +} scsi_mode_sense6_t; -VERIFY_STATIC( sizeof(scsi_mode_sense_6_t) == 6, "size is not correct"); +VERIFY_STATIC( sizeof(scsi_mode_sense6_t) == 6, "size is not correct"); typedef struct ATTR_PACKED { - uint8_t mode_data_length; + uint8_t data_len; uint8_t medium_type; uint8_t device_specific_para; - uint8_t block_descriptor_length; -} scsi_mode_parameters_t; + uint8_t block_descriptor_len; +} scsi_mode_sense6_resp_t; -VERIFY_STATIC( sizeof(scsi_mode_parameters_t) == 4, "size is not correct"); +VERIFY_STATIC( sizeof(scsi_mode_sense6_resp_t) == 4, "size is not correct"); typedef struct ATTR_PACKED { @@ -372,9 +372,9 @@ VERIFY_STATIC(sizeof(scsi_read_capacity10_t) == 10, "size is not correct"); typedef struct { uint32_t last_lba ; ///< The last Logical Block Address of the device uint32_t block_size ; ///< Block size in bytes -} scsi_read_capacity10_data_t; +} scsi_read_capacity10_resp_t; -VERIFY_STATIC(sizeof(scsi_read_capacity10_data_t) == 8, "size is not correct"); +VERIFY_STATIC(sizeof(scsi_read_capacity10_resp_t) == 8, "size is not correct"); /// SCSI Read 10 Command typedef struct ATTR_PACKED diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index 9f037a73c..27762805c 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -202,7 +202,7 @@ int32_t proc_builtin_scsi(msc_cbw_t const * p_cbw, uint8_t* buffer, uint32_t buf { case SCSI_CMD_READ_CAPACITY_10: { - scsi_read_capacity10_data_t read_capa10 = + scsi_read_capacity10_resp_t read_capa10 = { .last_lba = ENDIAN_BE(CFG_TUD_MSC_BLOCK_NUM-1), // read capacity .block_size = ENDIAN_BE(CFG_TUD_MSC_BLOCK_SZ) @@ -230,7 +230,7 @@ int32_t proc_builtin_scsi(msc_cbw_t const * p_cbw, uint8_t* buffer, uint32_t buf case SCSI_CMD_INQUIRY: { - scsi_inquiry_data_t inquiry_rsp = + scsi_inquiry_resp_t inquiry_rsp = { .is_removable = 1, .version = 2, @@ -249,15 +249,30 @@ int32_t proc_builtin_scsi(msc_cbw_t const * p_cbw, uint8_t* buffer, uint32_t buf } break; + case SCSI_CMD_MODE_SENSE_6: + { + scsi_mode_sense6_resp_t const mode_resp = + { + .data_len = 3, + .medium_type = 0, + .device_specific_para = 0, + .block_descriptor_len = 0 // no block descriptor are included + }; + + ret = sizeof(mode_resp); + memcpy(buffer, &mode_resp, ret); + } + break; + case SCSI_CMD_REQUEST_SENSE: { - scsi_sense_fixed_data_t sense_rsp = + scsi_sense_fixed_resp_t sense_rsp = { .response_code = 0x70, .valid = 1 }; - sense_rsp.add_sense_len = sizeof(scsi_sense_fixed_data_t) - 8; + sense_rsp.add_sense_len = sizeof(scsi_sense_fixed_resp_t) - 8; sense_rsp.sense_key = _mscd_itf.sense_key; sense_rsp.add_sense_code = _mscd_itf.add_sense_code; -- cgit v1.3.1 From 72b600c393e543361b073abee3da823d41383660 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 26 Jul 2018 22:41:46 +0700 Subject: update device msc callback --- src/class/msc/msc_device.h | 69 ++++++++++++++++++++-------------------------- 1 file changed, 30 insertions(+), 39 deletions(-) (limited to 'src/class') diff --git a/src/class/msc/msc_device.h b/src/class/msc/msc_device.h index 236968f49..10d602ecf 100644 --- a/src/class/msc/msc_device.h +++ b/src/class/msc/msc_device.h @@ -100,71 +100,62 @@ bool tud_msc_ready(void); bool tud_msc_set_sense(uint8_t lun, uint8_t sense_key, uint8_t add_sense_code, uint8_t add_sense_qualifier); //--------------------------------------------------------------------+ -// APPLICATION CALLBACK API (WEAK is optional) +// APPLICATION CALLBACK (WEAK is optional) //--------------------------------------------------------------------+ -/** \brief Callback invoked when received \ref SCSI_CMD_READ_10 command - * \param[in] lun Targeted Logical Unit - * Must be accessible by USB controller (see \ref CFG_TUSB_ATTR_USBRAM) - * \param[in] lba Starting Logical Block Address to be read - * \param[in] offset Byte offset from LBA for reading +/** + * Callback invoked when received \ref SCSI_CMD_READ_10 command + * \param[in] lun Logical unit number + * \param[in] lba Logical Block Address to be read + * \param[in] offset Byte offset from LBA * \param[out] buffer Buffer which application need to update with the response data. - * \param[in] bufsize Max bytes can be copied. Application must not return more than this value. + * \param[in] bufsize Requested bytes * - * \retval positive Actual bytes returned, must not be more than \a \b bufsize. - * If value less than bufsize is returned, Tinyusb will transfer this amount and afterwards - * invoke this callback again with adjusted offset. + * \return Number of byte read, if it is less than requested bytes by \a \b bufsize. Tinyusb will transfer + * this amount first and invoked this again for remaining data. * * \retval zero Indicate application is not ready yet to response e.g disk I/O is not complete. - * Tinyusb will invoke this callback with the same params again some time later. + * tinyusb will invoke this callback with the same parameters again some time later. * - * \retval negative Indicate error reading disk I/O. Tinyusb will \b STALL the corresponding + * \retval negative Indicate error e.g reading disk I/O. tinyusb will \b STALL the corresponding * endpoint and return failed status in command status wrapper phase. - * - * \note Host can request dozens of Kbytes in one command e.g \a \b block_count = 128, it is insufficient to require - * application to have that much of buffer. Instead, application can return the number of blocks it can processed, - * the stack after transferred that amount of data will continue to invoke this callback with adjusted \a \b lba and \a \b block_count. - * \n\n Although this callback is called by tinyusb device task (non-isr context), however as all the classes share - * the same task (to save resource), any delay in this callback will cause delay in response on other classes. */ int32_t tud_msc_read10_cb (uint8_t lun, uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize); -/** \brief Callback invoked when received \ref SCSI_CMD_WRITE_10 command - * \param[in] lun Targeted Logical Unit - * Must be accessible by USB controller (see \ref CFG_TUSB_ATTR_USBRAM) - * \param[in] lba Starting Logical Block Address to be write +/** + * Callback invoked when received \ref SCSI_CMD_WRITE_10 command + * \param[in] lun Logical unit number + * \param[in] lba Logical Block Address to be write + * \param[in] offset Byte offset from LBA * \param[out] buffer Buffer which holds written data. - * \param[in] bufsize Max bytes in buffer. Application must not return more than this value. + * \param[in] bufsize Requested bytes * - * \retval positive Actual bytes written, must not be more than \a \b bufsize. - * If value less than bufsize is returned, Tinyusb will trim off this amount and - * invoke this callback again with adjusted offset some time later. + * \return Number of byte written, if it is less than requested bytes by \a \b bufsize. Tinyusb will proceed with + * other work and invoked this again with adjusted parameters. * * \retval zero Indicate application is not ready yet e.g disk I/O is not complete. - * Tinyusb will invoke this callback with the same params again some time later. + * Tinyusb will invoke this callback with the same parameters again some time later. * * \retval negative Indicate error writing disk I/O. Tinyusb will \b STALL the corresponding * endpoint and return failed status in command status wrapper phase. - * - * \note Host can request dozens of Kbytes in one command e.g \a \b block_count = 128, it is insufficient to require - * application to have that much of buffer. Instead, application can return the number of blocks it can processed, - * the stack after transferred that amount of data will continue to invoke this callback with adjusted \a \b lba and \a \b block_count. - * \n\n Although this callback is called by tinyusb device task (non-isr context), however as all the classes share - * the same task (to save resource), any delay in this callback will cause delay in response on other classes. */ int32_t tud_msc_write10_cb (uint8_t lun, uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize); - -/** \brief Callback invoked when received an SCSI command other than \ref SCSI_CMD_WRITE_10 and \ref SCSI_CMD_READ_10 - * \param[in] lun Targeted Logical Unit - * \param[in] scsi_cmd SCSI command contents, application should examine this command block to know which command host requested +/** + * Callback invoked when received an SCSI command not in built-in list below. + * \param[in] lun Logical unit number + * \param[in] scsi_cmd SCSI command contents which application must examine to response accordingly * \param[out] buffer Buffer for SCSI Data Stage. * - For INPUT: application must fill this with response. * - For OUTPUT it holds the Data from host * \param[in] bufsize Buffer's length. * - * \retval negative Indicate error e.g accessing disk I/O. Tinyusb will \b STALL the corresponding + * \return Actual bytes processed, can be zero for no-data command. + * \retval negative Indicate error e.g unsupported command, tinyusb will \b STALL the corresponding * endpoint and return failed status in command status wrapper phase. - * \retval otherwise Actual bytes processed, must not be more than \a \b bufsize. Can be zero for no-data command. + * + * \note Following command is automatically handled by tinyusb stack, callback should not be worried: + * - READ_CAPACITY10, READ_FORMAT_CAPACITY, INQUIRY, MODE_SENSE6, REQUEST_SENSE + * - READ10 and WRITE10 has their own callbacks */ int32_t tud_msc_scsi_cb (uint8_t lun, uint8_t const scsi_cmd[16], void* buffer, uint16_t bufsize); -- cgit v1.3.1 From 5dd02cbdd37e09de4265105cc9dbb7df00a5f3f7 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 27 Jul 2018 16:59:57 +0700 Subject: house keeping --- examples/obsolete/host/src/msc_cli.c | 2 ++ examples/obsolete/host/src/msc_cli.h | 2 ++ hw/bsp/pca10056/board_pca10056.c | 2 ++ hw/bsp/pca10056/board_pca10056.h | 2 ++ src/class/custom/custom_device.c | 4 +++- src/class/custom/custom_device.h | 4 +++- src/common/tusb_verify.h | 2 ++ src/device/usbd_desc.c | 4 +++- src/device/usbd_pvt.h | 2 ++ src/portable/nordic/nrf5x/dcd_nrf5x.c | 2 ++ src/portable/nordic/nrf5x/hal_nrf5x.c | 2 ++ 11 files changed, 25 insertions(+), 3 deletions(-) (limited to 'src/class') diff --git a/examples/obsolete/host/src/msc_cli.c b/examples/obsolete/host/src/msc_cli.c index aeadb4933..0182a6df9 100644 --- a/examples/obsolete/host/src/msc_cli.c +++ b/examples/obsolete/host/src/msc_cli.c @@ -31,6 +31,8 @@ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. */ /**************************************************************************/ diff --git a/examples/obsolete/host/src/msc_cli.h b/examples/obsolete/host/src/msc_cli.h index 052ad05ee..9e41bfd06 100644 --- a/examples/obsolete/host/src/msc_cli.h +++ b/examples/obsolete/host/src/msc_cli.h @@ -31,6 +31,8 @@ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. */ /**************************************************************************/ #ifndef _TUSB_MSC_CLI_H_ diff --git a/hw/bsp/pca10056/board_pca10056.c b/hw/bsp/pca10056/board_pca10056.c index 85e32cf2d..c6815917e 100644 --- a/hw/bsp/pca10056/board_pca10056.c +++ b/hw/bsp/pca10056/board_pca10056.c @@ -31,6 +31,8 @@ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. */ /**************************************************************************/ diff --git a/hw/bsp/pca10056/board_pca10056.h b/hw/bsp/pca10056/board_pca10056.h index cb477aab8..86544fcc1 100644 --- a/hw/bsp/pca10056/board_pca10056.h +++ b/hw/bsp/pca10056/board_pca10056.h @@ -31,6 +31,8 @@ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. */ /**************************************************************************/ #ifndef BOARD_PCA10056_H_ diff --git a/src/class/custom/custom_device.c b/src/class/custom/custom_device.c index c895deb18..2c3783e35 100644 --- a/src/class/custom/custom_device.c +++ b/src/class/custom/custom_device.c @@ -7,7 +7,7 @@ Software License Agreement (BSD License) - Copyright (c) 2018, Adafruit Industries (adafruit.com) + Copyright (c) 2018, hathach (tinyusb.org) All rights reserved. Redistribution and use in source and binary forms, with or without @@ -31,6 +31,8 @@ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. */ /**************************************************************************/ diff --git a/src/class/custom/custom_device.h b/src/class/custom/custom_device.h index 3e46c06a7..81a074ce3 100644 --- a/src/class/custom/custom_device.h +++ b/src/class/custom/custom_device.h @@ -7,7 +7,7 @@ Software License Agreement (BSD License) - Copyright (c) 2018, Adafruit Industries (adafruit.com) + Copyright (c) 2018, hathach (tinyusb.org) All rights reserved. Redistribution and use in source and binary forms, with or without @@ -31,6 +31,8 @@ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. */ /**************************************************************************/ diff --git a/src/common/tusb_verify.h b/src/common/tusb_verify.h index 95816a0e7..adcdfc97f 100644 --- a/src/common/tusb_verify.h +++ b/src/common/tusb_verify.h @@ -31,6 +31,8 @@ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. */ /**************************************************************************/ #ifndef TUSB_VERIFY_H_ diff --git a/src/device/usbd_desc.c b/src/device/usbd_desc.c index 7e9feae90..095464051 100644 --- a/src/device/usbd_desc.c +++ b/src/device/usbd_desc.c @@ -7,7 +7,7 @@ Software License Agreement (BSD License) - Copyright (c) 2018, Adafruit Industries (adafruit.com) + Copyright (c) 2018, hathach (tinyusb.org) All rights reserved. Redistribution and use in source and binary forms, with or without @@ -31,6 +31,8 @@ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. */ /**************************************************************************/ diff --git a/src/device/usbd_pvt.h b/src/device/usbd_pvt.h index 343aade77..205057db6 100644 --- a/src/device/usbd_pvt.h +++ b/src/device/usbd_pvt.h @@ -31,6 +31,8 @@ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. */ /**************************************************************************/ #ifndef USBD_PVT_H_ diff --git a/src/portable/nordic/nrf5x/dcd_nrf5x.c b/src/portable/nordic/nrf5x/dcd_nrf5x.c index 44d1b93e2..339b8df1f 100644 --- a/src/portable/nordic/nrf5x/dcd_nrf5x.c +++ b/src/portable/nordic/nrf5x/dcd_nrf5x.c @@ -31,6 +31,8 @@ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. */ /**************************************************************************/ diff --git a/src/portable/nordic/nrf5x/hal_nrf5x.c b/src/portable/nordic/nrf5x/hal_nrf5x.c index 870f8899a..7ace69ef6 100644 --- a/src/portable/nordic/nrf5x/hal_nrf5x.c +++ b/src/portable/nordic/nrf5x/hal_nrf5x.c @@ -31,6 +31,8 @@ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. */ /**************************************************************************/ -- cgit v1.3.1 From cf6c534c1974f4efeb5c136697d1f1028e6aa34a Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 27 Jul 2018 17:14:49 +0700 Subject: add usb msc callback description --- examples/device/nrf52840/src/msc_device_app.c | 27 ++++++++++++++++----------- src/class/msc/msc_device.h | 20 ++++++++++---------- 2 files changed, 26 insertions(+), 21 deletions(-) (limited to 'src/class') diff --git a/examples/device/nrf52840/src/msc_device_app.c b/examples/device/nrf52840/src/msc_device_app.c index 96dea077e..916e4331c 100644 --- a/examples/device/nrf52840/src/msc_device_app.c +++ b/examples/device/nrf52840/src/msc_device_app.c @@ -64,8 +64,8 @@ int32_t tud_msc_scsi_cb (uint8_t lun, uint8_t const scsi_cmd[16], void* buffer, { // read10 & write10 has their own callback and MUST not be handled here - void const* ptr = NULL; - uint16_t len = 0; + void const* response = NULL; + uint16_t resplen = 0; // most scsi handled is input bool in_xfer = true; @@ -74,39 +74,44 @@ int32_t tud_msc_scsi_cb (uint8_t lun, uint8_t const scsi_cmd[16], void* buffer, { case SCSI_CMD_TEST_UNIT_READY: // Command that host uses to check our readiness before sending other commands - len = 0; + resplen = 0; break; case SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL: // Host is about to read/write etc ... better not to disconnect disk - len = 0; + resplen = 0; break; case SCSI_CMD_START_STOP_UNIT: // Host try to eject/safe remove/poweroff us. We could safely disconnect with disk storage, or go into lower power - // scsi_start_stop_unit_t const * cmd_start_stop = (scsi_start_stop_unit_t const *) scsi_cmd - len = 0; + /* scsi_start_stop_unit_t const * start_stop = (scsi_start_stop_unit_t const *) scsi_cmd; + // Start bit = 0 : low power mode, if load_eject = 1 : unmount disk storage as well + // Start bit = 1 : Ready mode, if load_eject = 1 : mount disk storage + start_stop->start; + start_stop->load_eject; + */ + resplen = 0; break; // negative means error -> tusb could stall and/or response with failed status default: return -1; } - // return len must not larger than bufsize - if ( len > bufsize ) len = bufsize; + // return resplen must not larger than bufsize + if ( resplen > bufsize ) resplen = bufsize; - if ( ptr && len ) + if ( response && resplen ) { if(in_xfer) { - memcpy(buffer, ptr, len); + memcpy(buffer, response, resplen); }else { // SCSI output } } - return len; + return resplen; } diff --git a/src/class/msc/msc_device.h b/src/class/msc/msc_device.h index 10d602ecf..6080b10df 100644 --- a/src/class/msc/msc_device.h +++ b/src/class/msc/msc_device.h @@ -104,10 +104,10 @@ bool tud_msc_set_sense(uint8_t lun, uint8_t sense_key, uint8_t add_sense_code, u //--------------------------------------------------------------------+ /** * Callback invoked when received \ref SCSI_CMD_READ_10 command - * \param[in] lun Logical unit number - * \param[in] lba Logical Block Address to be read - * \param[in] offset Byte offset from LBA - * \param[out] buffer Buffer which application need to update with the response data. + * \param[in] lun Logical unit number + * \param[in] lba Logical Block Address to be read + * \param[in] offset Byte offset from LBA + * \param[out] buffer Buffer which application need to update with the response data. * \param[in] bufsize Requested bytes * * \return Number of byte read, if it is less than requested bytes by \a \b bufsize. Tinyusb will transfer @@ -123,10 +123,10 @@ int32_t tud_msc_read10_cb (uint8_t lun, uint32_t lba, uint32_t offset, void* buf /** * Callback invoked when received \ref SCSI_CMD_WRITE_10 command - * \param[in] lun Logical unit number - * \param[in] lba Logical Block Address to be write - * \param[in] offset Byte offset from LBA - * \param[out] buffer Buffer which holds written data. + * \param[in] lun Logical unit number + * \param[in] lba Logical Block Address to be write + * \param[in] offset Byte offset from LBA + * \param[out] buffer Buffer which holds written data. * \param[in] bufsize Requested bytes * * \return Number of byte written, if it is less than requested bytes by \a \b bufsize. Tinyusb will proceed with @@ -142,8 +142,8 @@ int32_t tud_msc_write10_cb (uint8_t lun, uint32_t lba, uint32_t offset, void* bu /** * Callback invoked when received an SCSI command not in built-in list below. - * \param[in] lun Logical unit number - * \param[in] scsi_cmd SCSI command contents which application must examine to response accordingly + * \param[in] lun Logical unit number + * \param[in] scsi_cmd SCSI command contents which application must examine to response accordingly * \param[out] buffer Buffer for SCSI Data Stage. * - For INPUT: application must fill this with response. * - For OUTPUT it holds the Data from host -- cgit v1.3.1 From 456506045f0cb4234b6fef9fddf621a53cd862ac Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 27 Jul 2018 21:48:15 +0700 Subject: seperate CFG_TUD_HID_BOOT_PROTOCOL to CFG_TUD_HID_KEYBOARD_BOOT & CFG_TUD_HID_MOUSE_BOOT --- examples/device/nrf52840/src/tusb_config.h | 22 ++++---- src/class/hid/hid_device.c | 80 ++++++++++++++---------------- src/device/usbd.c | 8 ++- src/device/usbd_desc.c | 68 ++++++++++++------------- 4 files changed, 87 insertions(+), 91 deletions(-) (limited to 'src/class') diff --git a/examples/device/nrf52840/src/tusb_config.h b/examples/device/nrf52840/src/tusb_config.h index 457dceea7..aad189429 100644 --- a/examples/device/nrf52840/src/tusb_config.h +++ b/examples/device/nrf52840/src/tusb_config.h @@ -75,6 +75,19 @@ #define CFG_TUD_HID_KEYBOARD 1 #define CFG_TUD_HID_MOUSE 1 +//#define CFG_TUD_HID_GENERIC 0 + +/* Enable boot protocol will create separated HID interface for Keyboard, + * Consumer Key and Mouse --> require more In endpoints. Otherwise they + * are all packed into a single Multiple Report Interface. + * + * Note: If your device is meant to work with simple host running on + * an MCU (e.g with tinyusb host), boot protocol should be enabled. + */ +//#define CFG_TUD_HID_BOOT_PROTOCOL 1 + +#define CFG_TUD_HID_KEYBOARD_BOOT 1 +#define CFG_TUD_HID_MOUSE_BOOT 1 //-------------------------------------------------------------------- // CDC @@ -117,15 +130,6 @@ // HID //-------------------------------------------------------------------- -/* Enable boot protocol will create separated HID interface for Keyboard, - * Consumer Key and Mouse --> require more In endpoints. Otherwise they - * are all packed into a single Multiple Report Interface. - * - * Note: If your device is meant to work with simple host running on - * an MCU (e.g with tinyusb host), boot protocol should be enabled. - */ -#define CFG_TUD_HID_BOOT_PROTOCOL 1 - /* Use the HID_ASCII_TO_KEYCODE lookup if CFG_TUD_HID_KEYBOARD is enabled. * This will occupies 256 bytes of ROM. It will also enable the use of 2 extra APIs * - tud_hid_keyboard_send_char() diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index 316067e61..e58b7dc5c 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -73,15 +73,17 @@ typedef struct { CFG_TUSB_MEM_ALIGN uint8_t report_buf[REPORT_BUFSIZE]; }hidd_interface_t; -#if CFG_TUD_HID_BOOT_PROTOCOL +#if CFG_TUD_HID_KEYBOARD CFG_TUSB_ATTR_USBRAM static hidd_interface_t _kbd_itf; -CFG_TUSB_ATTR_USBRAM static hidd_interface_t _mse_itf; +#endif -#else +#if CFG_TUD_HID_MOUSE +CFG_TUSB_ATTR_USBRAM static hidd_interface_t _mse_itf; +#endif +#if 0 // CFG_TUD_HID_BOOT_PROTOCOL CFG_TUSB_ATTR_USBRAM static hidd_interface_t _composite_itf; - #endif //--------------------------------------------------------------------+ @@ -282,51 +284,43 @@ tusb_error_t hidd_open(uint8_t rhport, tusb_desc_interface_t const * desc_itf, u if (desc_itf->bInterfaceSubClass == HID_SUBCLASS_BOOT) { -#if CFG_TUD_HID_BOOT_PROTOCOL - if ( (desc_itf->bInterfaceProtocol != HID_PROTOCOL_KEYBOARD) && (desc_itf->bInterfaceProtocol != HID_PROTOCOL_MOUSE) ) - { - // unknown, unsupported protocol - return TUSB_ERROR_HIDD_DESCRIPTOR_INTERFACE; - }else - { - hidd_interface_t * p_hid = NULL; + TU_ASSERT(desc_itf->bInterfaceProtocol == HID_PROTOCOL_KEYBOARD || desc_itf->bInterfaceProtocol == HID_PROTOCOL_MOUSE, TUSB_ERROR_HIDD_DESCRIPTOR_INTERFACE); - #if CFG_TUD_HID_KEYBOARD - if (desc_itf->bInterfaceProtocol == HID_PROTOCOL_KEYBOARD) - { - p_hid = &_kbd_itf; - p_hid->report_desc = tud_desc_set.hid_report.boot_keyboard; - p_hid->get_report_cb = tud_hid_keyboard_get_report_cb; - p_hid->set_report_cb = tud_hid_keyboard_set_report_cb; - } - #endif + hidd_interface_t * p_hid = NULL; - #if CFG_TUD_HID_MOUSE - if (desc_itf->bInterfaceProtocol == HID_PROTOCOL_MOUSE) - { - p_hid = &_mse_itf; - p_hid->report_desc = tud_desc_set.hid_report.boot_mouse; - p_hid->get_report_cb = tud_hid_mouse_get_report_cb; - p_hid->set_report_cb = tud_hid_mouse_set_report_cb; - } - #endif + #if CFG_TUD_HID_KEYBOARD + if (desc_itf->bInterfaceProtocol == HID_PROTOCOL_KEYBOARD) + { + p_hid = &_kbd_itf; + p_hid->report_desc = tud_desc_set.hid_report.boot_keyboard; + p_hid->boot_protocol = CFG_TUD_HID_KEYBOARD_BOOT; // default mode is BOOT if enabled + p_hid->get_report_cb = tud_hid_keyboard_get_report_cb; + p_hid->set_report_cb = tud_hid_keyboard_set_report_cb; + } + #endif - TU_ASSERT(p_hid, TUSB_ERROR_HIDD_DESCRIPTOR_INTERFACE); - VERIFY(p_hid->report_desc, TUSB_ERROR_DESCRIPTOR_CORRUPTED); + #if CFG_TUD_HID_MOUSE + if (desc_itf->bInterfaceProtocol == HID_PROTOCOL_MOUSE) + { + p_hid = &_mse_itf; + p_hid->report_desc = tud_desc_set.hid_report.boot_mouse; + p_hid->boot_protocol = CFG_TUD_HID_MOUSE_BOOT; // default mode is BOOT if enabled + p_hid->get_report_cb = tud_hid_mouse_get_report_cb; + p_hid->set_report_cb = tud_hid_mouse_set_report_cb; + } + #endif - TU_ASSERT( dcd_edpt_open(rhport, desc_edpt), TUSB_ERROR_DCD_FAILED ); + TU_ASSERT(p_hid, TUSB_ERROR_HIDD_DESCRIPTOR_INTERFACE); + VERIFY(p_hid->report_desc, TUSB_ERROR_DESCRIPTOR_CORRUPTED); - p_hid->boot_protocol = true; // default to boot mode when mounted - p_hid->report_len = desc_hid->wReportLength; - p_hid->itf_num = desc_itf->bInterfaceNumber; - p_hid->ep_in = desc_edpt->bEndpointAddress; - p_hid->report_id = 0; + TU_ASSERT( dcd_edpt_open(rhport, desc_edpt), TUSB_ERROR_DCD_FAILED ); - *p_length = sizeof(tusb_desc_interface_t) + sizeof(tusb_hid_descriptor_hid_t) + sizeof(tusb_desc_endpoint_t); - } -#else - return TUSB_ERROR_HIDD_DESCRIPTOR_INTERFACE; -#endif + p_hid->report_len = desc_hid->wReportLength; + p_hid->itf_num = desc_itf->bInterfaceNumber; + p_hid->ep_in = desc_edpt->bEndpointAddress; + p_hid->report_id = 0; + + *p_length = sizeof(tusb_desc_interface_t) + sizeof(tusb_hid_descriptor_hid_t) + sizeof(tusb_desc_endpoint_t); } else { diff --git a/src/device/usbd.c b/src/device/usbd.c index 443ca8056..8f406d0bd 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -318,19 +318,17 @@ static void usbd_reset(uint8_t rhport) tud_desc_set.device = (uint8_t const*) &_desc_auto_device; tud_desc_set.config = _desc_auto_config; -#if CFG_TUD_HID_BOOT_PROTOCOL - - #if CFG_TUD_HID_KEYBOARD + #if CFG_TUD_HID_KEYBOARD && CFG_TUD_HID_KEYBOARD_BOOT extern uint8_t const _desc_auto_hid_kbd_report[]; tud_desc_set.hid_report.boot_keyboard = _desc_auto_hid_kbd_report; #endif - #if CFG_TUD_HID_MOUSE + #if CFG_TUD_HID_MOUSE && CFG_TUD_HID_MOUSE_BOOT extern uint8_t const _desc_auto_hid_mse_report[]; tud_desc_set.hid_report.boot_mouse = _desc_auto_hid_mse_report; #endif -#else +#if 0 // CFG_TUD_HID_BOOT_PROTOCOL #if CFG_TUD_HID_KEYBOARD + CFG_TUD_HID_MOUSE tud_desc_set.hid_report.composite = ; diff --git a/src/device/usbd_desc.c b/src/device/usbd_desc.c index 095464051..b1bb07809 100644 --- a/src/device/usbd_desc.c +++ b/src/device/usbd_desc.c @@ -62,7 +62,7 @@ */ #define _PID_MAP(itf, n) ( (CFG_TUD_##itf) << (n) ) #define CFG_TUD_DESC_PID (0x4000 | _PID_MAP(CDC, 0) | _PID_MAP(MSC, 1) | \ - _PID_MAP(HID_KEYBOARD, 2) | _PID_MAP(HID_MOUSE, 3) ) + _PID_MAP(HID_KEYBOARD, 2) | _PID_MAP(HID_MOUSE, 3) /*| _PID_MAP(HID_GENERIC, 5)*/ ) #endif /*------------- Interface Numbering -------------*/ @@ -94,17 +94,21 @@ #define EP_MSC_OUT _EP_OUT(ITF_NUM_MSC+1) #define EP_MSC_IN _EP_IN (ITF_NUM_MSC+1) -// Boot protocol each report has its own interface -#if CFG_TUD_HID_BOOT_PROTOCOL -// HID Keyboard -#define EP_HID_KBD _EP_IN (ITF_NUM_HID_KBD+1) -#define EP_HID_KBD_SIZE 8 -// HID Mouse -#define EP_HID_MSE _EP_IN (ITF_NUM_HID_MSE+1) -#define EP_HID_MSE_SIZE 8 +// HID Keyboard with boot protocol +#if CFG_TUD_HID_KEYBOARD && CFG_TUD_HID_KEYBOARD_BOOT +#define EP_HID_KBD_BOOT _EP_IN (ITF_NUM_HID_KBD+1) +#define EP_HID_KBD_BOOT_SZ 8 -#else +#endif + +// HID Mouse with boot protocol +#if CFG_TUD_HID_MOUSE && CFG_TUD_HID_MOUSE_BOOT +#define EP_HID_MSE_BOOT _EP_IN (ITF_NUM_HID_MSE+1) +#define EP_HID_MSE_BOOT_SZ 8 +#endif + +#if 0 // CFG_TUD_HID_BOOT_PROTOCOL // HID composite = keyboard + mouse #define EP_HID_COMP _EP_IN (ITF_NUM_HID_KBD+1) @@ -303,27 +307,25 @@ typedef struct ATTR_PACKED #endif //------------- HID -------------// -#if CFG_TUD_HID_BOOT_PROTOCOL - -#if CFG_TUD_HID_KEYBOARD +#if CFG_TUD_HID_KEYBOARD && CFG_TUD_HID_KEYBOARD_BOOT struct ATTR_PACKED { tusb_desc_interface_t itf; tusb_hid_descriptor_hid_t hid_desc; tusb_desc_endpoint_t ep_in; - } hid_kbd; + } hid_kbd_boot; #endif -#if CFG_TUD_HID_MOUSE +#if CFG_TUD_HID_MOUSE && CFG_TUD_HID_MOUSE_BOOT struct ATTR_PACKED { tusb_desc_interface_t itf; tusb_hid_descriptor_hid_t hid_desc; tusb_desc_endpoint_t ep_in; - } hid_mse; + } hid_mse_boot; #endif -#else +#if 0 // CFG_TUD_HID_BOOT_PROTOCOL #if CFG_TUD_HID_KEYBOARD || CFG_TUD_HID_MOUSE struct ATTR_PACKED @@ -470,7 +472,7 @@ desc_auto_cfg_t const _desc_auto_config_struct = .bInterval = 0 }, }, -#endif +#endif // cdc #if CFG_TUD_MSC //------------- Mass Storage-------------// @@ -509,12 +511,10 @@ desc_auto_cfg_t const _desc_auto_config_struct = .bInterval = 1 } }, -#endif +#endif // msc -#if CFG_TUD_HID_BOOT_PROTOCOL - -#if CFG_TUD_HID_KEYBOARD - .hid_kbd = +#if CFG_TUD_HID_KEYBOARD && CFG_TUD_HID_KEYBOARD_BOOT + .hid_kbd_boot = { .itf = { @@ -526,7 +526,7 @@ desc_auto_cfg_t const _desc_auto_config_struct = .bInterfaceClass = TUSB_CLASS_HID, .bInterfaceSubClass = HID_SUBCLASS_BOOT, .bInterfaceProtocol = HID_PROTOCOL_KEYBOARD, - .iInterface = 4 + CFG_TUD_CDC + CFG_TUD_MSC + .iInterface = 0 //4 + CFG_TUD_CDC + CFG_TUD_MSC }, .hid_desc = @@ -544,17 +544,17 @@ desc_auto_cfg_t const _desc_auto_config_struct = { .bLength = sizeof(tusb_desc_endpoint_t), .bDescriptorType = TUSB_DESC_ENDPOINT, - .bEndpointAddress = EP_HID_KBD, + .bEndpointAddress = EP_HID_KBD_BOOT, .bmAttributes = { .xfer = TUSB_XFER_INTERRUPT }, - .wMaxPacketSize = { .size = EP_HID_KBD_SIZE }, + .wMaxPacketSize = { .size = EP_HID_KBD_BOOT_SZ }, .bInterval = 0x0A } }, -#endif // keyboard +#endif // boot keyboard //------------- HID Mouse -------------// -#if CFG_TUD_HID_MOUSE - .hid_mse = +#if CFG_TUD_HID_MOUSE && CFG_TUD_HID_MOUSE_BOOT + .hid_mse_boot = { .itf = { @@ -566,7 +566,7 @@ desc_auto_cfg_t const _desc_auto_config_struct = .bInterfaceClass = TUSB_CLASS_HID, .bInterfaceSubClass = HID_SUBCLASS_BOOT, .bInterfaceProtocol = HID_PROTOCOL_MOUSE, - .iInterface = 4 + CFG_TUD_CDC + CFG_TUD_MSC + CFG_TUD_HID_KEYBOARD + .iInterface = 0 // 4 + CFG_TUD_CDC + CFG_TUD_MSC + CFG_TUD_HID_KEYBOARD }, .hid_desc = @@ -584,16 +584,16 @@ desc_auto_cfg_t const _desc_auto_config_struct = { .bLength = sizeof(tusb_desc_endpoint_t), .bDescriptorType = TUSB_DESC_ENDPOINT, - .bEndpointAddress = EP_HID_MSE, + .bEndpointAddress = EP_HID_MSE_BOOT, .bmAttributes = { .xfer = TUSB_XFER_INTERRUPT }, - .wMaxPacketSize = { .size = EP_HID_MSE_SIZE }, + .wMaxPacketSize = { .size = EP_HID_MSE_BOOT_SZ }, .bInterval = 0x0A }, }, -#endif // mouse +#endif // boot mouse -#else +#if 0 #if CFG_TUD_HID_KEYBOARD || CFG_TUD_HID_MOUSE //------------- HID Keyboard + Mouse (multiple reports) -------------// -- cgit v1.3.1 From 9f61493020821ba7e3226e67b56a062501feb429 Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 28 Jul 2018 12:38:45 +0700 Subject: change HID config, move HID boot config to part of auto descriptor only --- examples/device/nrf52840/src/tusb_config.h | 33 ++++++----- examples/device/nrf52840/src/tusb_descriptors.c | 2 +- src/class/hid/hid_device.c | 49 ++++++++++----- src/class/hid/hid_device.h | 34 ++++++++--- src/common/tusb_error.h | 2 + src/device/usbd.c | 6 +- src/device/usbd.h | 2 +- src/device/usbd_desc.c | 79 +++++++++++-------------- src/tusb.h | 2 +- src/tusb_option.h | 2 - tests/lpc175x_6x/test/test_usbd.c | 2 +- 11 files changed, 120 insertions(+), 93 deletions(-) (limited to 'src/class') diff --git a/examples/device/nrf52840/src/tusb_config.h b/examples/device/nrf52840/src/tusb_config.h index aad189429..9ef739bcd 100644 --- a/examples/device/nrf52840/src/tusb_config.h +++ b/examples/device/nrf52840/src/tusb_config.h @@ -61,33 +61,38 @@ // DEVICE CONFIGURATION //-------------------------------------------------------------------- -/*------------- Core -------------*/ +#define CFG_TUD_ENDOINT0_SIZE 64 + +/*------------- Descriptors -------------*/ + +/* Enable auto generated descriptor, tinyusb will try its best to create + * descriptor ( device, configuration, hid ) that matches enabled CFG_* in this file + * + * Note: All CFG_TUD_DESC_* are relevant only if CFG_TUD_DESC_AUTO is enabled + */ #define CFG_TUD_DESC_AUTO 1 +/* USB VID/PID if not defined, tinyusb to use default value + * Note: different class combination e.g CDC and (CDC + MSC) should have different + * PID since Host OS will "remembered" device driver after the first plug */ // #define CFG_TUD_DESC_VID 0xCAFE // #define CFG_TUD_DESC_PID 0x0001 -#define CFG_TUD_ENDOINT0_SIZE 64 +/* Use Boot Protocol for Keyboard, Mouse. Enable this will create separated HID interface + * require more IN endpoints. If disabled, they they are all packed into a single + * multiple report interface called "Generic". + */ +#define CFG_TUD_DESC_BOOT_KEYBOARD 1 +#define CFG_TUD_DESC_BOOT_MOUSE 1 //------------- CLASS -------------// #define CFG_TUD_CDC 1 #define CFG_TUD_MSC 1 +#define CFG_TUD_HID 1 #define CFG_TUD_HID_KEYBOARD 1 #define CFG_TUD_HID_MOUSE 1 -//#define CFG_TUD_HID_GENERIC 0 - -/* Enable boot protocol will create separated HID interface for Keyboard, - * Consumer Key and Mouse --> require more In endpoints. Otherwise they - * are all packed into a single Multiple Report Interface. - * - * Note: If your device is meant to work with simple host running on - * an MCU (e.g with tinyusb host), boot protocol should be enabled. - */ -//#define CFG_TUD_HID_BOOT_PROTOCOL 1 -#define CFG_TUD_HID_KEYBOARD_BOOT 1 -#define CFG_TUD_HID_MOUSE_BOOT 1 //-------------------------------------------------------------------- // CDC diff --git a/examples/device/nrf52840/src/tusb_descriptors.c b/examples/device/nrf52840/src/tusb_descriptors.c index 7dc3642aa..2b219c87a 100644 --- a/examples/device/nrf52840/src/tusb_descriptors.c +++ b/examples/device/nrf52840/src/tusb_descriptors.c @@ -91,7 +91,7 @@ tud_desc_set_t tud_desc_set = .hid_report = { - .composite = NULL, + .generic = NULL, .boot_keyboard = NULL, .boot_mouse = NULL } diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index e58b7dc5c..bd9d800d1 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -38,7 +38,7 @@ #include "tusb_option.h" -#if (TUSB_OPT_DEVICE_ENABLED && TUD_OPT_HID_ENABLED) +#if (TUSB_OPT_DEVICE_ENABLED && CFG_TUD_HID) #define _TINY_USB_SOURCE_FILE_ //--------------------------------------------------------------------+ @@ -82,9 +82,16 @@ CFG_TUSB_ATTR_USBRAM static hidd_interface_t _kbd_itf; CFG_TUSB_ATTR_USBRAM static hidd_interface_t _mse_itf; #endif -#if 0 // CFG_TUD_HID_BOOT_PROTOCOL -CFG_TUSB_ATTR_USBRAM static hidd_interface_t _composite_itf; -#endif +CFG_TUSB_ATTR_USBRAM static hidd_interface_t _hidd_itf; + + +//--------------------------------------------------------------------+ +// HID GENERIC API +//--------------------------------------------------------------------+ +bool tud_hid_generic_ready(void) +{ + +} //--------------------------------------------------------------------+ // KEYBOARD APPLICATION API @@ -173,6 +180,7 @@ bool tud_hid_keyboard_key_sequence(const char* str, uint32_t interval_ms) } } + return true; } #endif // CFG_TUD_HID_ASCII_TO_KEYCODE_LOOKUP @@ -268,23 +276,25 @@ void hidd_reset(uint8_t rhport) #endif } -tusb_error_t hidd_open(uint8_t rhport, tusb_desc_interface_t const * desc_itf, uint16_t *p_length) +tusb_error_t hidd_open(uint8_t rhport, tusb_desc_interface_t const * desc_itf, uint16_t *p_len) { uint8_t const *p_desc = (uint8_t const *) desc_itf; //------------- HID descriptor -------------// p_desc += p_desc[DESC_OFFSET_LEN]; tusb_hid_descriptor_hid_t const *desc_hid = (tusb_hid_descriptor_hid_t const *) p_desc; - TU_ASSERT(HID_DESC_TYPE_HID == desc_hid->bDescriptorType, TUSB_ERROR_HIDD_DESCRIPTOR_INTERFACE); + TU_ASSERT(HID_DESC_TYPE_HID == desc_hid->bDescriptorType, ERR_TUD_INVALID_DESCRIPTOR); //------------- Endpoint Descriptor -------------// p_desc += p_desc[DESC_OFFSET_LEN]; tusb_desc_endpoint_t const *desc_edpt = (tusb_desc_endpoint_t const *) p_desc; - TU_ASSERT(TUSB_DESC_ENDPOINT == desc_edpt->bDescriptorType, TUSB_ERROR_HIDD_DESCRIPTOR_INTERFACE); + TU_ASSERT(TUSB_DESC_ENDPOINT == desc_edpt->bDescriptorType, ERR_TUD_INVALID_DESCRIPTOR); + + *p_len = 0; if (desc_itf->bInterfaceSubClass == HID_SUBCLASS_BOOT) { - TU_ASSERT(desc_itf->bInterfaceProtocol == HID_PROTOCOL_KEYBOARD || desc_itf->bInterfaceProtocol == HID_PROTOCOL_MOUSE, TUSB_ERROR_HIDD_DESCRIPTOR_INTERFACE); + TU_ASSERT(desc_itf->bInterfaceProtocol == HID_PROTOCOL_KEYBOARD || desc_itf->bInterfaceProtocol == HID_PROTOCOL_MOUSE, ERR_TUD_INVALID_DESCRIPTOR); hidd_interface_t * p_hid = NULL; @@ -293,7 +303,6 @@ tusb_error_t hidd_open(uint8_t rhport, tusb_desc_interface_t const * desc_itf, u { p_hid = &_kbd_itf; p_hid->report_desc = tud_desc_set.hid_report.boot_keyboard; - p_hid->boot_protocol = CFG_TUD_HID_KEYBOARD_BOOT; // default mode is BOOT if enabled p_hid->get_report_cb = tud_hid_keyboard_get_report_cb; p_hid->set_report_cb = tud_hid_keyboard_set_report_cb; } @@ -304,13 +313,12 @@ tusb_error_t hidd_open(uint8_t rhport, tusb_desc_interface_t const * desc_itf, u { p_hid = &_mse_itf; p_hid->report_desc = tud_desc_set.hid_report.boot_mouse; - p_hid->boot_protocol = CFG_TUD_HID_MOUSE_BOOT; // default mode is BOOT if enabled p_hid->get_report_cb = tud_hid_mouse_get_report_cb; p_hid->set_report_cb = tud_hid_mouse_set_report_cb; } #endif - TU_ASSERT(p_hid, TUSB_ERROR_HIDD_DESCRIPTOR_INTERFACE); + TU_ASSERT(p_hid, ERR_TUD_INVALID_DESCRIPTOR); VERIFY(p_hid->report_desc, TUSB_ERROR_DESCRIPTOR_CORRUPTED); TU_ASSERT( dcd_edpt_open(rhport, desc_edpt), TUSB_ERROR_DCD_FAILED ); @@ -319,15 +327,26 @@ tusb_error_t hidd_open(uint8_t rhport, tusb_desc_interface_t const * desc_itf, u p_hid->itf_num = desc_itf->bInterfaceNumber; p_hid->ep_in = desc_edpt->bEndpointAddress; p_hid->report_id = 0; + p_hid->boot_protocol = true; // default mode is BOOT - *p_length = sizeof(tusb_desc_interface_t) + sizeof(tusb_hid_descriptor_hid_t) + sizeof(tusb_desc_endpoint_t); + *p_len = sizeof(tusb_desc_interface_t) + sizeof(tusb_hid_descriptor_hid_t) + sizeof(tusb_desc_endpoint_t); } else { // TODO HID generic + hidd_interface_t * p_hid = &_hidd_itf; + + p_hid->itf_num = desc_itf->bInterfaceNumber; + p_hid->ep_in = desc_edpt->bEndpointAddress; + // TODO parse report ID for keyboard, mouse - *p_length = 0; - return TUSB_ERROR_HIDD_DESCRIPTOR_INTERFACE; + p_hid->report_id = 0; + p_hid->report_len = 0; + p_hid->report_desc = NULL; + //p_hid->get_report_cb = tud_hid_get_report_cb; + //p_hid->set_report_cb = tud_hid_set_report_cb; + + return ERR_TUD_INVALID_DESCRIPTOR; } return TUSB_ERROR_NONE; @@ -352,7 +371,7 @@ tusb_error_t hidd_control_request_st(uint8_t rhport, tusb_control_request_t cons { STASK_ASSERT ( p_hid->report_len <= CFG_TUD_CTRL_BUFSIZE ); - // use device control buffer (in USB SRAM) + // use device control buffer memcpy(_usbd_ctrl_buf, p_hid->report_desc, p_hid->report_len); usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, _usbd_ctrl_buf, p_hid->report_len); diff --git a/src/class/hid/hid_device.h b/src/class/hid/hid_device.h index e8f5b40f4..06c07d446 100644 --- a/src/class/hid/hid_device.h +++ b/src/class/hid/hid_device.h @@ -49,8 +49,19 @@ //--------------------------------------------------------------------+ -// KEYBOARD APPLICATION API +// HID GENERIC API //--------------------------------------------------------------------+ +bool tud_hid_generic_ready(void); +bool tud_hid_generic_report(void); + +/*------------- Callbacks -------------*/ +ATTR_WEAK uint16_t tud_hid_get_report_cb(uint8_t report_id, hid_report_type_t report_type, uint8_t* buffer, uint16_t reqlen); +ATTR_WEAK void tud_hid_set_report_cb(uint8_t report_id, hid_report_type_t report_type, uint8_t const* buffer, uint16_t bufsize); + +//--------------------------------------------------------------------+ +// KEYBOARD API +//--------------------------------------------------------------------+ +#if CFG_TUD_HID_KEYBOARD /** \addtogroup ClassDriver_HID_Keyboard Keyboard * @{ */ /** \defgroup Keyboard_Device Device @@ -78,7 +89,9 @@ typedef struct{ extern const hid_ascii_to_keycode_entry_t HID_ASCII_TO_KEYCODE[128]; #endif -/*------------- Callbacks, ATTR_WEAK means optional -------------*/ +#endif + +/*------------- Callbacks -------------*/ /** Callback invoked when USB host request \ref HID_REQ_CONTROL_GET_REPORT. * \param[in] report_type specify which report (INPUT, OUTPUT, FEATURE) that host requests @@ -109,8 +122,9 @@ ATTR_WEAK void tud_hid_keyboard_set_report_cb(hid_report_type_t report_type, uin /** @} */ //--------------------------------------------------------------------+ -// MOUSE APPLICATION API +// MOUSE API //--------------------------------------------------------------------+ +#if CFG_TUD_HID_MOUSE /** \addtogroup ClassDriver_HID_Mouse Mouse * @{ */ /** \defgroup Mouse_Device Device @@ -141,10 +155,10 @@ static inline bool tud_hid_mouse_button_release(void) /*------------- Callbacks -------------*/ -/** \brief Callback function that is invoked when USB host request \ref HID_REQUEST_CONTROL_GET_REPORT - * via control endpoint. +/** + * Callback function that is invoked when USB host request \ref HID_REQ_CONTROL_GET_REPORT. * \param[in] report_type specify which report (INPUT, OUTPUT, FEATURE) that host requests - * \param[out] buffer buffer that application need to update, value must be accessible by USB controller (see \ref CFG_TUSB_ATTR_USBRAM) + * \param[out] buffer buffer that application need to update, value must be accessible by USB controller (see \ref CFG_TUSB_ATTR_USBRAM) * \param[in] reqlen number of bytes that host requested * \retval non-zero Actual number of bytes in the response's buffer. * \retval zero indicates the current request is not supported. Tinyusb device stack will reject the request by @@ -154,8 +168,8 @@ static inline bool tud_hid_mouse_button_release(void) */ ATTR_WEAK uint16_t tud_hid_mouse_get_report_cb(hid_report_type_t report_type, uint8_t* buffer, uint16_t reqlen); -/** \brief Callback function that is invoked when USB host request \ref HID_REQUEST_CONTROL_SET_REPORT - * via control endpoint. +/** + * Callback function that is invoked when USB host request \ref HID_REQ_CONTROL_SET_REPORT. * \param[in] report_type specify which report (INPUT, OUTPUT, FEATURE) that host requests * \param[in] buffer buffer containing the report's data * \param[in] bufsize number of bytes in the \a p_report_data @@ -166,13 +180,15 @@ ATTR_WEAK void tud_hid_mouse_set_report_cb(hid_report_type_t report_type, uint8_ //ATTR_WEAK void tud_hid_mouse_set_protocol_cb(bool boot_protocol); +#endif + /** @} */ /** @} */ //--------------------------------------------------------------------+ -// USBD-CLASS DRIVER API +// INTERNAL API //--------------------------------------------------------------------+ #ifdef _TINY_USB_SOURCE_FILE_ diff --git a/src/common/tusb_error.h b/src/common/tusb_error.h index 339f6ced1..e7c7f69f9 100644 --- a/src/common/tusb_error.h +++ b/src/common/tusb_error.h @@ -91,6 +91,8 @@ ENTRY(TUSB_ERROR_USBD_DEVICE_NOT_CONFIGURED )\ ENTRY(TUSB_ERROR_NOT_ENOUGH_MEMORY )\ ENTRY(TUSB_ERROR_FAILED )\ + \ + ENTRY(ERR_TUD_INVALID_DESCRIPTOR) /// \brief Error Code returned diff --git a/src/device/usbd.c b/src/device/usbd.c index 8f406d0bd..f6b55a81d 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -116,7 +116,7 @@ static usbd_class_driver_t const usbd_class_drivers[] = #endif - #if TUD_OPT_HID_ENABLED + #if CFG_TUD_HID { .class_code = TUSB_CLASS_HID, .init = hidd_init, @@ -318,12 +318,12 @@ static void usbd_reset(uint8_t rhport) tud_desc_set.device = (uint8_t const*) &_desc_auto_device; tud_desc_set.config = _desc_auto_config; - #if CFG_TUD_HID_KEYBOARD && CFG_TUD_HID_KEYBOARD_BOOT + #if CFG_TUD_HID_KEYBOARD && CFG_TUD_DESC_BOOT_KEYBOARD extern uint8_t const _desc_auto_hid_kbd_report[]; tud_desc_set.hid_report.boot_keyboard = _desc_auto_hid_kbd_report; #endif - #if CFG_TUD_HID_MOUSE && CFG_TUD_HID_MOUSE_BOOT + #if CFG_TUD_HID_MOUSE && CFG_TUD_DESC_BOOT_MOUSE extern uint8_t const _desc_auto_hid_mse_report[]; tud_desc_set.hid_report.boot_mouse = _desc_auto_hid_mse_report; #endif diff --git a/src/device/usbd.h b/src/device/usbd.h index 8413aa15e..8ef1209e1 100644 --- a/src/device/usbd.h +++ b/src/device/usbd.h @@ -66,7 +66,7 @@ typedef struct { uint16_t string_count; struct { - uint8_t const* composite; + uint8_t const* generic; uint8_t const* boot_keyboard; uint8_t const* boot_mouse; } hid_report; diff --git a/src/device/usbd_desc.c b/src/device/usbd_desc.c index b1bb07809..1a37c6f58 100644 --- a/src/device/usbd_desc.c +++ b/src/device/usbd_desc.c @@ -47,9 +47,13 @@ #if CFG_TUD_DESC_AUTO +// Generic (multiple) Report : Keyboard + Mouse + Gamepad + Joystick +#define HID_GENERIC (CFG_TUD_HID && ( (CFG_TUD_HID_KEYBOARD && !CFG_TUD_DESC_BOOT_KEYBOARD) || \ + (CFG_TUD_HID_MOUSE && !CFG_TUD_DESC_BOOT_MOUSE) )) + /*------------- VID/PID -------------*/ #ifndef CFG_TUD_DESC_VID -#define CFG_TUD_DESC_VID 0xCAFE +#define CFG_TUD_DESC_VID 0xCAFE #endif #ifndef CFG_TUD_DESC_PID @@ -58,11 +62,11 @@ * 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 Generic | HID Composite | HID Mouse | HID Keyboard | MSC | CDC [LSB] + * [MSB] HID Generic | Boot Mouse | Boot Keyboard | MSC | CDC [LSB] */ -#define _PID_MAP(itf, n) ( (CFG_TUD_##itf) << (n) ) -#define CFG_TUD_DESC_PID (0x4000 | _PID_MAP(CDC, 0) | _PID_MAP(MSC, 1) | \ - _PID_MAP(HID_KEYBOARD, 2) | _PID_MAP(HID_MOUSE, 3) /*| _PID_MAP(HID_GENERIC, 5)*/ ) +#define _PID_MAP(itf, n) ( (CFG_TUD_##itf) << (n) ) +#define CFG_TUD_DESC_PID (0x4000 | _PID_MAP(CDC, 0) | _PID_MAP(MSC, 1) | _PID_MAP(HID, 2) | \ + _PID_MAP(HID_KEYBOARD, 2) | _PID_MAP(HID_MOUSE, 3) | (HID_GENERIC << 4) ) #endif /*------------- Interface Numbering -------------*/ @@ -76,8 +80,8 @@ #define ITF_NUM_HID_KBD (ITF_NUM_MSC + CFG_TUD_MSC) #define ITF_NUM_HID_MSE (ITF_NUM_HID_KBD + CFG_TUD_HID_KEYBOARD) -#define ITF_TOTAL (ITF_NUM_HID_MSE + CFG_TUD_HID_MOUSE) - +#define ITF_NUM_HID_GEN (ITF_NUM_HID_MSE + CFG_TUD_HID_MOUSE) +#define ITF_TOTAL (ITF_NUM_HID_GEN + HID_GENERIC) /*------------- Endpoint Numbering & Size -------------*/ #define _EP_IN(x) (0x80 | (x)) @@ -96,23 +100,24 @@ // HID Keyboard with boot protocol -#if CFG_TUD_HID_KEYBOARD && CFG_TUD_HID_KEYBOARD_BOOT +#if CFG_TUD_HID_KEYBOARD && CFG_TUD_DESC_BOOT_KEYBOARD #define EP_HID_KBD_BOOT _EP_IN (ITF_NUM_HID_KBD+1) #define EP_HID_KBD_BOOT_SZ 8 - #endif // HID Mouse with boot protocol -#if CFG_TUD_HID_MOUSE && CFG_TUD_HID_MOUSE_BOOT +#if CFG_TUD_HID_MOUSE && CFG_TUD_DESC_BOOT_MOUSE #define EP_HID_MSE_BOOT _EP_IN (ITF_NUM_HID_MSE+1) #define EP_HID_MSE_BOOT_SZ 8 #endif -#if 0 // CFG_TUD_HID_BOOT_PROTOCOL + + +#if HID_GENERIC // HID composite = keyboard + mouse -#define EP_HID_COMP _EP_IN (ITF_NUM_HID_KBD+1) -#define EP_HID_COMP_SIZE 16 +#define EP_HID_GEN _EP_IN (EP_HID_MSE_BOOT+1) +#define EP_HID_GEN_SIZE 16 #endif @@ -307,7 +312,7 @@ typedef struct ATTR_PACKED #endif //------------- HID -------------// -#if CFG_TUD_HID_KEYBOARD && CFG_TUD_HID_KEYBOARD_BOOT +#if CFG_TUD_HID_KEYBOARD && CFG_TUD_DESC_BOOT_KEYBOARD struct ATTR_PACKED { tusb_desc_interface_t itf; @@ -316,7 +321,7 @@ typedef struct ATTR_PACKED } hid_kbd_boot; #endif -#if CFG_TUD_HID_MOUSE && CFG_TUD_HID_MOUSE_BOOT +#if CFG_TUD_HID_MOUSE && CFG_TUD_DESC_BOOT_MOUSE struct ATTR_PACKED { tusb_desc_interface_t itf; @@ -325,20 +330,18 @@ typedef struct ATTR_PACKED } hid_mse_boot; #endif -#if 0 // CFG_TUD_HID_BOOT_PROTOCOL +#if HID_GENERIC -#if CFG_TUD_HID_KEYBOARD || CFG_TUD_HID_MOUSE struct ATTR_PACKED { tusb_desc_interface_t itf; tusb_hid_descriptor_hid_t hid_desc; tusb_desc_endpoint_t ep_in; - #if CFG_TUD_HID_KEYBOARD + #if 0 // CFG_TUD_HID_KEYBOARD tusb_desc_endpoint_t ep_out; #endif - } hid_composite; -#endif + } hid_generic; #endif @@ -513,7 +516,7 @@ desc_auto_cfg_t const _desc_auto_config_struct = }, #endif // msc -#if CFG_TUD_HID_KEYBOARD && CFG_TUD_HID_KEYBOARD_BOOT +#if CFG_TUD_HID_KEYBOARD && CFG_TUD_DESC_BOOT_KEYBOARD .hid_kbd_boot = { .itf = @@ -553,7 +556,7 @@ desc_auto_cfg_t const _desc_auto_config_struct = #endif // boot keyboard //------------- HID Mouse -------------// -#if CFG_TUD_HID_MOUSE && CFG_TUD_HID_MOUSE_BOOT +#if CFG_TUD_HID_MOUSE && CFG_TUD_DESC_BOOT_MOUSE .hid_mse_boot = { .itf = @@ -593,23 +596,22 @@ desc_auto_cfg_t const _desc_auto_config_struct = #endif // boot mouse -#if 0 +#if HID_GENERIC -#if CFG_TUD_HID_KEYBOARD || CFG_TUD_HID_MOUSE - //------------- HID Keyboard + Mouse (multiple reports) -------------// + //------------- HID Generic Multiple report -------------// .hid_composite = { .itf = { .bLength = sizeof(tusb_desc_interface_t), .bDescriptorType = TUSB_DESC_INTERFACE, - .bInterfaceNumber = ITF_NUM_HID_KBD, + .bInterfaceNumber = ITF_NUM_HID_GEN, .bAlternateSetting = 0x00, .bNumEndpoints = 2, .bInterfaceClass = TUSB_CLASS_HID, .bInterfaceSubClass = 0, .bInterfaceProtocol = 0, - .iInterface = 4 + CFG_TUD_CDC + CFG_TUD_MSC, + .iInterface = 0, // 4 + CFG_TUD_CDC + CFG_TUD_MSC, }, .hid_desc = @@ -620,41 +622,26 @@ desc_auto_cfg_t const _desc_auto_config_struct = .bCountryCode = HID_Local_NotSupported, .bNumDescriptors = 1, .bReportType = HID_DESC_TYPE_REPORT, - .wReportLength = sizeof(_desc_auto_hid_composite_report) + .wReportLength = sizeof(_desc_auto_hid_generic_report) }, .ep_in = { .bLength = sizeof(tusb_desc_endpoint_t), .bDescriptorType = TUSB_DESC_ENDPOINT, - .bEndpointAddress = EP_HID_COMP, + .bEndpointAddress = EP_HID_GEN, .bmAttributes = { .xfer = TUSB_XFER_INTERRUPT }, - .wMaxPacketSize = { .size = EP_HID_COMP_SIZE }, + .wMaxPacketSize = { .size = EP_HID_GEN_SIZE }, .bInterval = 0x0A } } -#endif -#endif // boot protocol +#endif // hid generic }; uint8_t const * const _desc_auto_config = (uint8_t const*) &_desc_auto_config_struct; #endif -/*------------------------------------------------------------------*/ -/* MACRO TYPEDEF CONSTANT ENUM - *------------------------------------------------------------------*/ - -/*------------------------------------------------------------------*/ -/* VARIABLE DECLARATION - *------------------------------------------------------------------*/ - -/*------------------------------------------------------------------*/ -/* FUNCTION DECLARATION - *------------------------------------------------------------------*/ - - - #endif diff --git a/src/tusb.h b/src/tusb.h index 8f25e2867..01fdf5ed3 100644 --- a/src/tusb.h +++ b/src/tusb.h @@ -76,7 +76,7 @@ #if TUSB_OPT_DEVICE_ENABLED #include "device/usbd.h" - #if TUD_OPT_HID_ENABLED + #if CFG_TUD_HID #include "class/hid/hid_device.h" #endif diff --git a/src/tusb_option.h b/src/tusb_option.h index a7b18d504..251fb2470 100644 --- a/src/tusb_option.h +++ b/src/tusb_option.h @@ -151,8 +151,6 @@ //-------------------------------------------------------------------- #if TUSB_OPT_DEVICE_ENABLED - #define TUD_OPT_HID_ENABLED ( CFG_TUD_HID_KEYBOARD + CFG_TUD_HID_MOUSE ) - #ifndef CFG_TUD_ENDOINT0_SIZE #define CFG_TUD_ENDOINT0_SIZE 64 #endif diff --git a/tests/lpc175x_6x/test/test_usbd.c b/tests/lpc175x_6x/test/test_usbd.c index b70f4592c..1dd041a41 100644 --- a/tests/lpc175x_6x/test/test_usbd.c +++ b/tests/lpc175x_6x/test/test_usbd.c @@ -87,7 +87,7 @@ tusb_error_t stub_hidd_init(uint8_t coreid, tusb_desc_interface_t const* p_inter void class_init_epxect(void) { -#if TUD_OPT_HID_ENABLED +#if CFG_TUD_HID hidd_init_StubWithCallback(stub_hidd_init); #endif } -- cgit v1.3.1 From 6034553be7fed82e56da572fad798220117e8f1f Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 28 Jul 2018 13:50:46 +0700 Subject: adding hid_generic support --- src/class/hid/hid_device.c | 48 ++++++++++++++++++---------------------------- src/class/hid/hid_device.h | 12 ++++++------ 2 files changed, 25 insertions(+), 35 deletions(-) (limited to 'src/class') diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index bd9d800d1..0b4116009 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -59,7 +59,8 @@ typedef struct { uint8_t itf_num; uint8_t ep_in; - uint8_t idle_rate; // in unit of 4 ms + uint8_t idle_rate; // in unit of 4 ms + uint8_t usage; // HID_USAGE_* bool boot_protocol; uint8_t report_id; @@ -67,8 +68,8 @@ typedef struct { uint8_t const * report_desc; // class specific control request - uint16_t (*get_report_cb) (hid_report_type_t type, uint8_t* buffer, uint16_t reqlen); - void (*set_report_cb) (hid_report_type_t type, uint8_t const* buffer, uint16_t bufsize); + uint16_t (*get_report_cb) (uint8_t report_id, hid_report_type_t type, uint8_t* buffer, uint16_t reqlen); + void (*set_report_cb) (uint8_t report_id, hid_report_type_t type, uint8_t const* buffer, uint16_t bufsize); CFG_TUSB_MEM_ALIGN uint8_t report_buf[REPORT_BUFSIZE]; }hidd_interface_t; @@ -84,6 +85,12 @@ CFG_TUSB_ATTR_USBRAM static hidd_interface_t _mse_itf; CFG_TUSB_ATTR_USBRAM static hidd_interface_t _hidd_itf; +static inline hidd_interface_t* get_interface_by_itfnum(uint8_t itf_num) +{ + return ( itf_num == _kbd_itf.itf_num ) ? &_kbd_itf : + ( itf_num == _mse_itf.itf_num ) ? &_mse_itf : NULL; +} + //--------------------------------------------------------------------+ // HID GENERIC API @@ -245,18 +252,6 @@ bool tud_hid_mouse_scroll(int8_t vertical, int8_t horizontal) #endif -static inline hidd_interface_t* get_interface_by_edpt(uint8_t ep_addr) -{ - return ( ep_addr == _kbd_itf.ep_in ) ? &_kbd_itf : - ( ep_addr == _mse_itf.ep_in ) ? &_mse_itf : NULL; -} - -static inline hidd_interface_t* get_interface_by_number(uint8_t itf_num) -{ - return ( itf_num == _kbd_itf.itf_num ) ? &_kbd_itf : - ( itf_num == _mse_itf.itf_num ) ? &_mse_itf : NULL; -} - //--------------------------------------------------------------------+ // USBD-CLASS API //--------------------------------------------------------------------+ @@ -343,8 +338,8 @@ tusb_error_t hidd_open(uint8_t rhport, tusb_desc_interface_t const * desc_itf, u p_hid->report_id = 0; p_hid->report_len = 0; p_hid->report_desc = NULL; - //p_hid->get_report_cb = tud_hid_get_report_cb; - //p_hid->set_report_cb = tud_hid_set_report_cb; + p_hid->get_report_cb = tud_hid_generic_get_report_cb; + p_hid->set_report_cb = tud_hid_generic_set_report_cb; return ERR_TUD_INVALID_DESCRIPTOR; } @@ -354,7 +349,7 @@ tusb_error_t hidd_open(uint8_t rhport, tusb_desc_interface_t const * desc_itf, u tusb_error_t hidd_control_request_st(uint8_t rhport, tusb_control_request_t const * p_request) { - hidd_interface_t* p_hid = get_interface_by_number( (uint8_t) p_request->wIndex ); + hidd_interface_t* p_hid = get_interface_by_itfnum( (uint8_t) p_request->wIndex ); TU_ASSERT(p_hid, TUSB_ERROR_FAILED); OSAL_SUBTASK_BEGIN @@ -364,14 +359,12 @@ tusb_error_t hidd_control_request_st(uint8_t rhport, tusb_control_request_t cons { uint8_t const desc_type = u16_high_u8(p_request->wValue); uint8_t const desc_index = u16_low_u8 (p_request->wValue); - (void) desc_index; if (p_request->bRequest == TUSB_REQ_GET_DESCRIPTOR && desc_type == HID_DESC_TYPE_REPORT) { - STASK_ASSERT ( p_hid->report_len <= CFG_TUD_CTRL_BUFSIZE ); - // use device control buffer + STASK_ASSERT ( p_hid->report_len <= CFG_TUD_CTRL_BUFSIZE ); memcpy(_usbd_ctrl_buf, p_hid->report_desc, p_hid->report_len); usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, _usbd_ctrl_buf, p_hid->report_len); @@ -389,16 +382,10 @@ tusb_error_t hidd_control_request_st(uint8_t rhport, tusb_control_request_t cons uint8_t const report_type = u16_high_u8(p_request->wValue); uint8_t const report_id = u16_low_u8(p_request->wValue); - // Composite interface need to determine it is Keyboard, Mouse or Gamepad - if ( report_id > 0 ) - { - - } - uint16_t xferlen; if ( p_hid->get_report_cb ) { - xferlen = p_hid->get_report_cb((hid_report_type_t) report_type, p_hid->report_buf, p_request->wLength); + xferlen = p_hid->get_report_cb(p_hid->report_id, (hid_report_type_t) report_type, p_hid->report_buf, p_request->wLength); }else { xferlen = p_request->wLength; @@ -411,11 +398,14 @@ tusb_error_t hidd_control_request_st(uint8_t rhport, tusb_control_request_t cons else if ( HID_REQ_CONTROL_SET_REPORT == p_request->bRequest ) { // wValue = Report Type | Report ID + uint8_t const report_type = u16_high_u8(p_request->wValue); + uint8_t const report_id = u16_low_u8(p_request->wValue); + usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, _usbd_ctrl_buf, p_request->wLength); if ( p_hid->set_report_cb ) { - p_hid->set_report_cb(u16_high_u8(p_request->wValue), _usbd_ctrl_buf, p_request->wLength); + p_hid->set_report_cb(report_id, (hid_report_type_t) report_type, _usbd_ctrl_buf, p_request->wLength); } } else if (HID_REQ_CONTROL_SET_IDLE == p_request->bRequest) diff --git a/src/class/hid/hid_device.h b/src/class/hid/hid_device.h index 06c07d446..c78f56bb1 100644 --- a/src/class/hid/hid_device.h +++ b/src/class/hid/hid_device.h @@ -55,8 +55,8 @@ bool tud_hid_generic_ready(void); bool tud_hid_generic_report(void); /*------------- Callbacks -------------*/ -ATTR_WEAK uint16_t tud_hid_get_report_cb(uint8_t report_id, hid_report_type_t report_type, uint8_t* buffer, uint16_t reqlen); -ATTR_WEAK void tud_hid_set_report_cb(uint8_t report_id, hid_report_type_t report_type, uint8_t const* buffer, uint16_t bufsize); +ATTR_WEAK uint16_t tud_hid_generic_get_report_cb(uint8_t report_id, hid_report_type_t report_type, uint8_t* buffer, uint16_t reqlen); +ATTR_WEAK void tud_hid_generic_set_report_cb(uint8_t report_id, hid_report_type_t report_type, uint8_t const* buffer, uint16_t bufsize); //--------------------------------------------------------------------+ // KEYBOARD API @@ -104,7 +104,7 @@ extern const hid_ascii_to_keycode_entry_t HID_ASCII_TO_KEYCODE[128]; * the completion of this control request will not be reported to application. * For Keyboard, USB host often uses this to turn on/off the LED for CAPLOCKS, NUMLOCK (\ref hid_keyboard_led_bm_t) */ -ATTR_WEAK uint16_t tud_hid_keyboard_get_report_cb(hid_report_type_t report_type, uint8_t* buffer, uint16_t reqlen); +ATTR_WEAK uint16_t tud_hid_keyboard_get_report_cb(uint8_t report_id, hid_report_type_t report_type, uint8_t* buffer, uint16_t reqlen); /** Callback invoked when USB host request \ref HID_REQ_CONTROL_SET_REPORT. * \param[in] report_type specify which report (INPUT, OUTPUT, FEATURE) that host requests @@ -113,7 +113,7 @@ ATTR_WEAK uint16_t tud_hid_keyboard_get_report_cb(hid_report_type_t report_type, * \note By the time this callback is invoked, the USB control transfer is already completed in the hardware side. * Application are free to handle data at its own will. */ -ATTR_WEAK void tud_hid_keyboard_set_report_cb(hid_report_type_t report_type, uint8_t const* buffer, uint16_t bufsize); +ATTR_WEAK void tud_hid_keyboard_set_report_cb(uint8_t report_id, hid_report_type_t report_type, uint8_t const* buffer, uint16_t bufsize); //ATTR_WEAK void tud_hid_keyboard_set_protocol_cb(bool boot_protocol); @@ -166,7 +166,7 @@ static inline bool tud_hid_mouse_button_release(void) * \note After this callback, the request is silently executed by the tinyusb stack, thus * the completion of this control request will not be reported to application */ -ATTR_WEAK uint16_t tud_hid_mouse_get_report_cb(hid_report_type_t report_type, uint8_t* buffer, uint16_t reqlen); +ATTR_WEAK uint16_t tud_hid_mouse_get_report_cb(uint8_t report_id, hid_report_type_t report_type, uint8_t* buffer, uint16_t reqlen); /** * Callback function that is invoked when USB host request \ref HID_REQ_CONTROL_SET_REPORT. @@ -176,7 +176,7 @@ ATTR_WEAK uint16_t tud_hid_mouse_get_report_cb(hid_report_type_t report_type, ui * \note By the time this callback is invoked, the USB control transfer is already completed in the hardware side. * Application are free to handle data at its own will. */ -ATTR_WEAK void tud_hid_mouse_set_report_cb(hid_report_type_t report_type, uint8_t const* buffer, uint16_t bufsize); +ATTR_WEAK void tud_hid_mouse_set_report_cb(uint8_t report_id, hid_report_type_t report_type, uint8_t const* buffer, uint16_t bufsize); //ATTR_WEAK void tud_hid_mouse_set_protocol_cb(bool boot_protocol); -- cgit v1.3.1 From c729db229422a2771be394ea4ac8de65eac619e4 Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 28 Jul 2018 18:14:30 +0700 Subject: beter hid report --- src/class/hid/hid_device.c | 2 + src/device/usbd.c | 8 +- src/device/usbd_desc.c | 193 ++++++++++++++++++++++----------------------- 3 files changed, 99 insertions(+), 104 deletions(-) (limited to 'src/class') diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index 0b4116009..e0ed2e719 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -287,6 +287,7 @@ tusb_error_t hidd_open(uint8_t rhport, tusb_desc_interface_t const * desc_itf, u *p_len = 0; + /*------------- Boot protocol only keyboard & mouse -------------*/ if (desc_itf->bInterfaceSubClass == HID_SUBCLASS_BOOT) { TU_ASSERT(desc_itf->bInterfaceProtocol == HID_PROTOCOL_KEYBOARD || desc_itf->bInterfaceProtocol == HID_PROTOCOL_MOUSE, ERR_TUD_INVALID_DESCRIPTOR); @@ -326,6 +327,7 @@ tusb_error_t hidd_open(uint8_t rhport, tusb_desc_interface_t const * desc_itf, u *p_len = sizeof(tusb_desc_interface_t) + sizeof(tusb_hid_descriptor_hid_t) + sizeof(tusb_desc_endpoint_t); } + /*------------- Generic (multiple report) -------------*/ else { // TODO HID generic diff --git a/src/device/usbd.c b/src/device/usbd.c index f6b55a81d..49fee44c2 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -319,13 +319,13 @@ static void usbd_reset(uint8_t rhport) tud_desc_set.config = _desc_auto_config; #if CFG_TUD_HID_KEYBOARD && CFG_TUD_DESC_BOOT_KEYBOARD - extern uint8_t const _desc_auto_hid_kbd_report[]; - tud_desc_set.hid_report.boot_keyboard = _desc_auto_hid_kbd_report; + extern uint8_t const _desc_auto_hid_boot_kbd_report[]; + tud_desc_set.hid_report.boot_keyboard = _desc_auto_hid_boot_kbd_report; #endif #if CFG_TUD_HID_MOUSE && CFG_TUD_DESC_BOOT_MOUSE - extern uint8_t const _desc_auto_hid_mse_report[]; - tud_desc_set.hid_report.boot_mouse = _desc_auto_hid_mse_report; + extern uint8_t const _desc_auto_hid_boot_mse_report[]; + tud_desc_set.hid_report.boot_mouse = _desc_auto_hid_boot_mse_report; #endif #if 0 // CFG_TUD_HID_BOOT_PROTOCOL diff --git a/src/device/usbd_desc.c b/src/device/usbd_desc.c index 1a37c6f58..5ef205071 100644 --- a/src/device/usbd_desc.c +++ b/src/device/usbd_desc.c @@ -122,110 +122,103 @@ #endif -// TODO HID Generic - - //--------------------------------------------------------------------+ -// Keyboard Report Descriptor +// HID Report Descriptors //--------------------------------------------------------------------+ + + +/*------------- Keyboard Descriptor -------------*/ #if CFG_TUD_HID_KEYBOARD -uint8_t const _desc_auto_hid_kbd_report[] = { - HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ), - HID_USAGE ( HID_USAGE_DESKTOP_KEYBOARD ), - HID_COLLECTION ( HID_COLLECTION_APPLICATION ), - HID_USAGE_PAGE ( HID_USAGE_PAGE_KEYBOARD ), - // 8 bits Modifier Keys (Shfit, Control, Alt) - HID_USAGE_MIN ( 224 ), - HID_USAGE_MAX ( 231 ), - HID_LOGICAL_MIN ( 0 ), - HID_LOGICAL_MAX ( 1 ), - - HID_REPORT_COUNT ( 8 ), - HID_REPORT_SIZE ( 1 ), - HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ), - - // 8 bit reserved - HID_REPORT_COUNT ( 1 ), - HID_REPORT_SIZE ( 8 ), - HID_INPUT ( HID_CONSTANT ), - - // 6-byte Keycodes - HID_USAGE_PAGE (HID_USAGE_PAGE_KEYBOARD), - HID_USAGE_MIN ( 0 ), - HID_USAGE_MAX ( 255 ), - HID_LOGICAL_MIN ( 0 ), - HID_LOGICAL_MAX ( 255 ), - - HID_REPORT_COUNT ( 6 ), - HID_REPORT_SIZE ( 8 ), - HID_INPUT ( HID_DATA | HID_ARRAY | HID_ABSOLUTE ), - - // LED Indicator Kana | Compose | Scroll Lock | CapsLock | NumLock - HID_USAGE_PAGE ( HID_USAGE_PAGE_LED ), - /* 5-bit Led report */ - HID_USAGE_MIN ( 1 ), - HID_USAGE_MAX ( 5 ), - HID_REPORT_COUNT ( 5 ), - HID_REPORT_SIZE ( 1 ), - HID_OUTPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ), - - /* led padding */ - HID_REPORT_COUNT ( 1 ), - HID_REPORT_SIZE ( 3 ), - HID_OUTPUT ( HID_CONSTANT ), - HID_COLLECTION_END -}; + +#define HID_REPORT_KEYBOARD(...) \ + HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_KEYBOARD ) ,\ + HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\ + /* 8 bits Modifier Keys (Shfit, Control, Alt) */ \ + HID_USAGE_PAGE ( HID_USAGE_PAGE_KEYBOARD ) ,\ + HID_USAGE_MIN ( 224 ) ,\ + HID_USAGE_MAX ( 231 ) ,\ + HID_LOGICAL_MIN ( 0 ) ,\ + HID_LOGICAL_MAX ( 1 ) ,\ + HID_REPORT_COUNT ( 8 ) ,\ + HID_REPORT_SIZE ( 1 ) ,\ + HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\ + /* 8 bit reserved */ \ + HID_REPORT_COUNT ( 1 ) ,\ + HID_REPORT_SIZE ( 8 ) ,\ + HID_INPUT ( HID_CONSTANT ) ,\ + /* 6-byte Keycodes */ \ + HID_USAGE_PAGE ( HID_USAGE_PAGE_KEYBOARD ) ,\ + HID_USAGE_MIN ( 0 ) ,\ + HID_USAGE_MAX ( 255 ) ,\ + HID_LOGICAL_MIN ( 0 ) ,\ + HID_LOGICAL_MAX ( 255 ) ,\ + HID_REPORT_COUNT ( 6 ) ,\ + HID_REPORT_SIZE ( 8 ) ,\ + HID_INPUT ( HID_DATA | HID_ARRAY | HID_ABSOLUTE ) ,\ + /* 5-bit LED Indicator Kana | Compose | ScrollLock | CapsLock | NumLock */ \ + HID_USAGE_PAGE ( HID_USAGE_PAGE_LED ) ,\ + HID_USAGE_MIN ( 1 ) ,\ + HID_USAGE_MAX ( 5 ) ,\ + HID_REPORT_COUNT ( 5 ) ,\ + HID_REPORT_SIZE ( 1 ) ,\ + HID_OUTPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\ + /* led padding */ \ + HID_REPORT_COUNT ( 1 ) ,\ + HID_REPORT_SIZE ( 3 ) ,\ + HID_OUTPUT ( HID_CONSTANT ) ,\ + HID_COLLECTION_END \ + +#if CFG_TUD_DESC_BOOT_KEYBOARD +uint8_t const _desc_auto_hid_boot_kbd_report[] = { HID_REPORT_KEYBOARD() }; #endif -//--------------------------------------------------------------------+ -// Mouse Report Descriptor -//--------------------------------------------------------------------+ +#endif + +/*------------- Mouse Descriptor -------------*/ #if CFG_TUD_HID_MOUSE -uint8_t const _desc_auto_hid_mse_report[] = { - HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ), - HID_USAGE ( HID_USAGE_DESKTOP_MOUSE ), - HID_COLLECTION ( HID_COLLECTION_APPLICATION ), - HID_USAGE (HID_USAGE_DESKTOP_POINTER), - - HID_COLLECTION ( HID_COLLECTION_PHYSICAL ), - HID_USAGE_PAGE ( HID_USAGE_PAGE_BUTTON ), - HID_USAGE_MIN ( 1 ), - HID_USAGE_MAX ( 3 ), - HID_LOGICAL_MIN ( 0 ), - HID_LOGICAL_MAX ( 1 ), - - // Left, Right, Middle, Backward, Forward mouse buttons - HID_REPORT_COUNT ( 3 ), - HID_REPORT_SIZE ( 1 ), - HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ), - - // 3 bit padding - HID_REPORT_COUNT ( 1 ), - HID_REPORT_SIZE ( 5 ), - HID_INPUT ( HID_CONSTANT ), - - HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ), - /* X, Y position */ - HID_USAGE ( HID_USAGE_DESKTOP_X ), - HID_USAGE ( HID_USAGE_DESKTOP_Y ), - HID_LOGICAL_MIN ( 0x81 ), /* -127 */ - HID_LOGICAL_MAX ( 0x7f ), /* 127 */ - - HID_REPORT_COUNT ( 2 ), - HID_REPORT_SIZE ( 8 ), - HID_INPUT ( HID_DATA | HID_VARIABLE | HID_RELATIVE ), - - /* mouse scroll */ - HID_USAGE ( HID_USAGE_DESKTOP_WHEEL ), - HID_LOGICAL_MIN ( 0x81 ), /* -127 */ - HID_LOGICAL_MAX ( 0x7f ), /* 127 */ - HID_REPORT_COUNT( 1 ), - HID_REPORT_SIZE ( 8 ), - HID_INPUT ( HID_DATA | HID_VARIABLE | HID_RELATIVE ), - - HID_COLLECTION_END, - HID_COLLECTION_END -}; +#define HID_REPORT_MOUSE(...) \ + HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_MOUSE ) ,\ + HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_POINTER ) ,\ + HID_COLLECTION ( HID_COLLECTION_PHYSICAL ) ,\ + HID_USAGE_PAGE ( HID_USAGE_PAGE_BUTTON ) ,\ + HID_USAGE_MIN ( 1 ) ,\ + HID_USAGE_MAX ( 3 ) ,\ + HID_LOGICAL_MIN ( 0 ) ,\ + HID_LOGICAL_MAX ( 1 ) ,\ + /* Left, Right, Middle, Backward, Forward mouse buttons */ \ + HID_REPORT_COUNT ( 3 ) ,\ + HID_REPORT_SIZE ( 1 ) ,\ + HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\ + /* 3 bit padding */ \ + HID_REPORT_COUNT ( 1 ) ,\ + HID_REPORT_SIZE ( 5 ) ,\ + HID_INPUT ( HID_CONSTANT ) ,\ + HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ + /* X, Y position [-127, 127] */ \ + HID_USAGE ( HID_USAGE_DESKTOP_X ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_Y ) ,\ + HID_LOGICAL_MIN ( 0x81 ) ,\ + HID_LOGICAL_MAX ( 0x7f ) ,\ + HID_REPORT_COUNT ( 2 ) ,\ + HID_REPORT_SIZE ( 8 ) ,\ + HID_INPUT ( HID_DATA | HID_VARIABLE | HID_RELATIVE ) ,\ + /* Mouse scroll [-127, 127] */ \ + HID_USAGE ( HID_USAGE_DESKTOP_WHEEL ) ,\ + HID_LOGICAL_MIN ( 0x81 ) ,\ + HID_LOGICAL_MAX ( 0x7f ) ,\ + HID_REPORT_COUNT( 1 ) ,\ + HID_REPORT_SIZE ( 8 ) ,\ + HID_INPUT ( HID_DATA | HID_VARIABLE | HID_RELATIVE ) ,\ + HID_COLLECTION_END ,\ + HID_COLLECTION_END \ + +#if CFG_TUD_DESC_BOOT_MOUSE +uint8_t const _desc_auto_hid_boot_mse_report[] = { HID_REPORT_MOUSE() }; +#endif + #endif @@ -540,7 +533,7 @@ desc_auto_cfg_t const _desc_auto_config_struct = .bCountryCode = HID_Local_NotSupported, .bNumDescriptors = 1, .bReportType = HID_DESC_TYPE_REPORT, - .wReportLength = sizeof(_desc_auto_hid_kbd_report) + .wReportLength = sizeof(_desc_auto_hid_boot_kbd_report) }, .ep_in = @@ -580,7 +573,7 @@ desc_auto_cfg_t const _desc_auto_config_struct = .bCountryCode = HID_Local_NotSupported, .bNumDescriptors = 1, .bReportType = HID_DESC_TYPE_REPORT, - .wReportLength = sizeof(_desc_auto_hid_mse_report) + .wReportLength = sizeof(_desc_auto_hid_boot_mse_report) }, .ep_in = -- cgit v1.3.1 From 8b17c5460950c425e17a055940e3a02cf6b29962 Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 28 Jul 2018 20:15:20 +0700 Subject: fix hid generic various error --- examples/device/nrf52840/src/tusb_config.h | 4 +- src/class/hid/hid.h | 4 +- src/class/hid/hid_device.c | 13 ++-- src/class/hid/hid_device.h | 11 ++++ src/device/usbd.c | 9 +-- src/device/usbd_desc.c | 98 ++++++++++++++++-------------- src/tusb_option.h | 4 ++ 7 files changed, 81 insertions(+), 62 deletions(-) (limited to 'src/class') diff --git a/examples/device/nrf52840/src/tusb_config.h b/examples/device/nrf52840/src/tusb_config.h index 9ef739bcd..3b5ec360d 100644 --- a/examples/device/nrf52840/src/tusb_config.h +++ b/examples/device/nrf52840/src/tusb_config.h @@ -82,8 +82,8 @@ * require more IN endpoints. If disabled, they they are all packed into a single * multiple report interface called "Generic". */ -#define CFG_TUD_DESC_BOOT_KEYBOARD 1 -#define CFG_TUD_DESC_BOOT_MOUSE 1 +#define CFG_TUD_DESC_BOOT_KEYBOARD 0 +#define CFG_TUD_DESC_BOOT_MOUSE 0 //------------- CLASS -------------// #define CFG_TUD_CDC 1 diff --git a/src/class/hid/hid.h b/src/class/hid/hid.h index 9872172a9..d2803177b 100644 --- a/src/class/hid/hid.h +++ b/src/class/hid/hid.h @@ -354,8 +354,8 @@ typedef enum #define RI_TYPE_LOCAL 2 //------------- MAIN ITEMS 6.2.2.4 -------------// -#define HID_INPUT(x) HID_REPORT_ITEM(x, 8, RI_TYPE_MAIN, 1) -#define HID_OUTPUT(x) HID_REPORT_ITEM(x, 9, RI_TYPE_MAIN, 1) +#define HID_INPUT(x) HID_REPORT_ITEM(x, 8, RI_TYPE_MAIN, 1) +#define HID_OUTPUT(x) HID_REPORT_ITEM(x, 9, RI_TYPE_MAIN, 1) #define HID_COLLECTION(x) HID_REPORT_ITEM(x, 10, RI_TYPE_MAIN, 1) #define HID_FEATURE(x) HID_REPORT_ITEM(x, 11, RI_TYPE_MAIN, 1) #define HID_COLLECTION_END HID_REPORT_ITEM(x, 12, RI_TYPE_MAIN, 0) diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index e0ed2e719..bf2cc75af 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -87,8 +87,9 @@ CFG_TUSB_ATTR_USBRAM static hidd_interface_t _hidd_itf; static inline hidd_interface_t* get_interface_by_itfnum(uint8_t itf_num) { - return ( itf_num == _kbd_itf.itf_num ) ? &_kbd_itf : - ( itf_num == _mse_itf.itf_num ) ? &_mse_itf : NULL; + return ( itf_num == _kbd_itf.itf_num ) ? &_kbd_itf : + ( itf_num == _mse_itf.itf_num ) ? &_mse_itf : + ( itf_num == _hidd_itf.itf_num ) ? &_hidd_itf : NULL; } @@ -333,17 +334,19 @@ tusb_error_t hidd_open(uint8_t rhport, tusb_desc_interface_t const * desc_itf, u // TODO HID generic hidd_interface_t * p_hid = &_hidd_itf; + TU_ASSERT( dcd_edpt_open(rhport, desc_edpt), TUSB_ERROR_DCD_FAILED ); + p_hid->itf_num = desc_itf->bInterfaceNumber; p_hid->ep_in = desc_edpt->bEndpointAddress; // TODO parse report ID for keyboard, mouse p_hid->report_id = 0; - p_hid->report_len = 0; - p_hid->report_desc = NULL; + p_hid->report_len = desc_hid->wReportLength; + p_hid->report_desc = tud_desc_set.hid_report.generic; p_hid->get_report_cb = tud_hid_generic_get_report_cb; p_hid->set_report_cb = tud_hid_generic_set_report_cb; - return ERR_TUD_INVALID_DESCRIPTOR; + *p_len = sizeof(tusb_desc_interface_t) + sizeof(tusb_hid_descriptor_hid_t) + sizeof(tusb_desc_endpoint_t); } return TUSB_ERROR_NONE; diff --git a/src/class/hid/hid_device.h b/src/class/hid/hid_device.h index c78f56bb1..31d4a0c2f 100644 --- a/src/class/hid/hid_device.h +++ b/src/class/hid/hid_device.h @@ -47,6 +47,17 @@ extern "C" { #endif +//--------------------------------------------------------------------+ +// Class Driver Configuration +//--------------------------------------------------------------------+ +#if !CFG_TUD_HID_KEYBOARD && CFG_TUD_DESC_BOOT_KEYBOARD +#error CFG_TUD_HID_KEYBOARD must be enabled +#endif + +#if !CFG_TUD_HID_MOUSE && CFG_TUD_DESC_BOOT_MOUSE +#error CFG_TUD_HID_MOUSE must be enabled +#endif + //--------------------------------------------------------------------+ // HID GENERIC API diff --git a/src/device/usbd.c b/src/device/usbd.c index 49fee44c2..7c302cc77 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -328,14 +328,11 @@ static void usbd_reset(uint8_t rhport) tud_desc_set.hid_report.boot_mouse = _desc_auto_hid_boot_mse_report; #endif -#if 0 // CFG_TUD_HID_BOOT_PROTOCOL - - #if CFG_TUD_HID_KEYBOARD + CFG_TUD_HID_MOUSE - tud_desc_set.hid_report.composite = ; + #if TUD_OPT_HID_GENERIC + extern uint8_t const _desc_auto_hid_generic_report[]; + tud_desc_set.hid_report.generic = _desc_auto_hid_generic_report; #endif -#endif - #endif // CFG_TUD_DESC_AUTO } diff --git a/src/device/usbd_desc.c b/src/device/usbd_desc.c index 5ef205071..8d3095503 100644 --- a/src/device/usbd_desc.c +++ b/src/device/usbd_desc.c @@ -40,17 +40,11 @@ #if TUSB_OPT_DEVICE_ENABLED -#define _TINY_USB_SOURCE_FILE_ #include "tusb.h" - #if CFG_TUD_DESC_AUTO -// Generic (multiple) Report : Keyboard + Mouse + Gamepad + Joystick -#define HID_GENERIC (CFG_TUD_HID && ( (CFG_TUD_HID_KEYBOARD && !CFG_TUD_DESC_BOOT_KEYBOARD) || \ - (CFG_TUD_HID_MOUSE && !CFG_TUD_DESC_BOOT_MOUSE) )) - /*------------- VID/PID -------------*/ #ifndef CFG_TUD_DESC_VID #define CFG_TUD_DESC_VID 0xCAFE @@ -66,7 +60,7 @@ */ #define _PID_MAP(itf, n) ( (CFG_TUD_##itf) << (n) ) #define CFG_TUD_DESC_PID (0x4000 | _PID_MAP(CDC, 0) | _PID_MAP(MSC, 1) | _PID_MAP(HID, 2) | \ - _PID_MAP(HID_KEYBOARD, 2) | _PID_MAP(HID_MOUSE, 3) | (HID_GENERIC << 4) ) + _PID_MAP(HID_KEYBOARD, 2) | _PID_MAP(HID_MOUSE, 3) | (TUD_OPT_HID_GENERIC << 4) ) #endif /*------------- Interface Numbering -------------*/ @@ -74,56 +68,46 @@ * If a interface is not enabled, the later will take its place */ -#define ITF_NUM_CDC 0 -#define ITF_NUM_MSC (ITF_NUM_CDC + 2*CFG_TUD_CDC) +#define ITF_NUM_CDC 0 +#define ITF_NUM_MSC (ITF_NUM_CDC + 2*CFG_TUD_CDC) -#define ITF_NUM_HID_KBD (ITF_NUM_MSC + CFG_TUD_MSC) -#define ITF_NUM_HID_MSE (ITF_NUM_HID_KBD + CFG_TUD_HID_KEYBOARD) +#define ITF_NUM_HID_BOOT_KBD (ITF_NUM_MSC + CFG_TUD_MSC) +#define ITF_NUM_HID_BOOT_MSE (ITF_NUM_HID_BOOT_KBD + CFG_TUD_DESC_BOOT_KEYBOARD) +#define ITF_NUM_HID_GEN (ITF_NUM_HID_BOOT_MSE + CFG_TUD_DESC_BOOT_MOUSE) -#define ITF_NUM_HID_GEN (ITF_NUM_HID_MSE + CFG_TUD_HID_MOUSE) -#define ITF_TOTAL (ITF_NUM_HID_GEN + HID_GENERIC) +#define ITF_TOTAL (ITF_NUM_HID_GEN + TUD_OPT_HID_GENERIC) /*------------- Endpoint Numbering & Size -------------*/ -#define _EP_IN(x) (0x80 | (x)) -#define _EP_OUT(x) (x) +#define _EP_IN(x) (0x80 | (x)) +#define _EP_OUT(x) (x) // CDC -#define EP_CDC_NOTIF _EP_IN (ITF_NUM_CDC+1) -#define EP_CDC_NOTIF_SIZE 8 +#define EP_CDC_NOTIF _EP_IN ( ITF_NUM_CDC+1 ) +#define EP_CDC_NOTIF_SIZE 8 -#define EP_CDC_OUT _EP_OUT(ITF_NUM_CDC+2) -#define EP_CDC_IN _EP_IN (ITF_NUM_CDC+2) +#define EP_CDC_OUT _EP_OUT( ITF_NUM_CDC+2 ) +#define EP_CDC_IN _EP_IN ( ITF_NUM_CDC+2 ) // Mass Storage -#define EP_MSC_OUT _EP_OUT(ITF_NUM_MSC+1) -#define EP_MSC_IN _EP_IN (ITF_NUM_MSC+1) +#define EP_MSC_OUT _EP_OUT( ITF_NUM_MSC+1 ) +#define EP_MSC_IN _EP_IN ( ITF_NUM_MSC+1 ) // HID Keyboard with boot protocol -#if CFG_TUD_HID_KEYBOARD && CFG_TUD_DESC_BOOT_KEYBOARD -#define EP_HID_KBD_BOOT _EP_IN (ITF_NUM_HID_KBD+1) -#define EP_HID_KBD_BOOT_SZ 8 -#endif +#define EP_HID_KBD_BOOT _EP_IN ( ITF_NUM_HID_BOOT_KBD+1 ) +#define EP_HID_KBD_BOOT_SZ 8 // HID Mouse with boot protocol -#if CFG_TUD_HID_MOUSE && CFG_TUD_DESC_BOOT_MOUSE -#define EP_HID_MSE_BOOT _EP_IN (ITF_NUM_HID_MSE+1) -#define EP_HID_MSE_BOOT_SZ 8 -#endif +#define EP_HID_MSE_BOOT _EP_IN ( ITF_NUM_HID_BOOT_MSE+1 ) +#define EP_HID_MSE_BOOT_SZ 8 - - -#if HID_GENERIC - -// HID composite = keyboard + mouse -#define EP_HID_GEN _EP_IN (EP_HID_MSE_BOOT+1) -#define EP_HID_GEN_SIZE 16 - -#endif +// HID composite = keyboard + mouse + gamepad + etc ... +#define EP_HID_GEN _EP_IN ( ITF_NUM_HID_GEN+1 ) +#define EP_HID_GEN_SIZE 16 //--------------------------------------------------------------------+ -// HID Report Descriptors +// Auto generated HID Report Descriptors //--------------------------------------------------------------------+ @@ -135,6 +119,7 @@ HID_USAGE ( HID_USAGE_DESKTOP_KEYBOARD ) ,\ HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\ /* 8 bits Modifier Keys (Shfit, Control, Alt) */ \ + __VA_ARGS__ \ HID_USAGE_PAGE ( HID_USAGE_PAGE_KEYBOARD ) ,\ HID_USAGE_MIN ( 224 ) ,\ HID_USAGE_MAX ( 231 ) ,\ @@ -173,7 +158,7 @@ uint8_t const _desc_auto_hid_boot_kbd_report[] = { HID_REPORT_KEYBOARD() }; #endif -#endif +#endif // hid keyboard /*------------- Mouse Descriptor -------------*/ #if CFG_TUD_HID_MOUSE @@ -181,6 +166,7 @@ uint8_t const _desc_auto_hid_boot_kbd_report[] = { HID_REPORT_KEYBOARD() }; HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ HID_USAGE ( HID_USAGE_DESKTOP_MOUSE ) ,\ HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\ + __VA_ARGS__ \ HID_USAGE ( HID_USAGE_DESKTOP_POINTER ) ,\ HID_COLLECTION ( HID_COLLECTION_PHYSICAL ) ,\ HID_USAGE_PAGE ( HID_USAGE_PAGE_BUTTON ) ,\ @@ -219,11 +205,29 @@ uint8_t const _desc_auto_hid_boot_kbd_report[] = { HID_REPORT_KEYBOARD() }; uint8_t const _desc_auto_hid_boot_mse_report[] = { HID_REPORT_MOUSE() }; #endif +#endif // hid mouse + +/*------------- Generic (composite) Descriptor -------------*/ + +#if TUD_OPT_HID_GENERIC + +uint8_t const _desc_auto_hid_generic_report[] = +{ +#if !CFG_TUD_DESC_BOOT_KEYBOARD + HID_REPORT_KEYBOARD( HID_REPORT_ID(1), ), #endif +#if !CFG_TUD_DESC_BOOT_MOUSE + HID_REPORT_MOUSE( HID_REPORT_ID(2), ) +#endif + +}; + +#endif // hid generic + /*------------------------------------------------------------------*/ -/* Auto generate descriptor +/* Auto generated Device & Configuration descriptor *------------------------------------------------------------------*/ // For highspeed device but currently in full speed mode @@ -323,7 +327,7 @@ typedef struct ATTR_PACKED } hid_mse_boot; #endif -#if HID_GENERIC +#if TUD_OPT_HID_GENERIC struct ATTR_PACKED { @@ -516,7 +520,7 @@ desc_auto_cfg_t const _desc_auto_config_struct = { .bLength = sizeof(tusb_desc_interface_t), .bDescriptorType = TUSB_DESC_INTERFACE, - .bInterfaceNumber = ITF_NUM_HID_KBD, + .bInterfaceNumber = ITF_NUM_HID_BOOT_KBD, .bAlternateSetting = 0x00, .bNumEndpoints = 1, .bInterfaceClass = TUSB_CLASS_HID, @@ -556,7 +560,7 @@ desc_auto_cfg_t const _desc_auto_config_struct = { .bLength = sizeof(tusb_desc_interface_t), .bDescriptorType = TUSB_DESC_INTERFACE, - .bInterfaceNumber = ITF_NUM_HID_MSE, + .bInterfaceNumber = ITF_NUM_HID_BOOT_MSE, .bAlternateSetting = 0x00, .bNumEndpoints = 1, .bInterfaceClass = TUSB_CLASS_HID, @@ -589,10 +593,10 @@ desc_auto_cfg_t const _desc_auto_config_struct = #endif // boot mouse -#if HID_GENERIC +#if TUD_OPT_HID_GENERIC //------------- HID Generic Multiple report -------------// - .hid_composite = + .hid_generic = { .itf = { @@ -600,7 +604,7 @@ desc_auto_cfg_t const _desc_auto_config_struct = .bDescriptorType = TUSB_DESC_INTERFACE, .bInterfaceNumber = ITF_NUM_HID_GEN, .bAlternateSetting = 0x00, - .bNumEndpoints = 2, + .bNumEndpoints = 1, .bInterfaceClass = TUSB_CLASS_HID, .bInterfaceSubClass = 0, .bInterfaceProtocol = 0, diff --git a/src/tusb_option.h b/src/tusb_option.h index 251fb2470..4af327a5d 100644 --- a/src/tusb_option.h +++ b/src/tusb_option.h @@ -171,6 +171,10 @@ #define CFG_TUD_MSC 0 #endif + // Generic (multiple) Report : Keyboard + Mouse + Gamepad + Joystick + #define TUD_OPT_HID_GENERIC (CFG_TUD_HID && ( (CFG_TUD_HID_KEYBOARD && !CFG_TUD_DESC_BOOT_KEYBOARD) || \ + (CFG_TUD_HID_MOUSE && !CFG_TUD_DESC_BOOT_MOUSE) )) + #endif // TUSB_OPT_DEVICE_ENABLED //-------------------------------------------------------------------- -- cgit v1.3.1 From 683bb574e723685f38082f2461f2fa8eb9900c90 Mon Sep 17 00:00:00 2001 From: hathach Date: Sun, 29 Jul 2018 14:03:48 +0700 Subject: hid device enhance --- examples/device/nrf52840/src/tusb_config.h | 13 ++++---- src/class/hid/hid_device.h | 16 +++++++--- src/common/tusb_error.h | 3 +- src/device/usbd.c | 6 ++-- src/device/usbd_desc.c | 51 +++++++++++++++--------------- src/tusb_option.h | 8 ++--- 6 files changed, 54 insertions(+), 43 deletions(-) (limited to 'src/class') diff --git a/examples/device/nrf52840/src/tusb_config.h b/examples/device/nrf52840/src/tusb_config.h index 3b5ec360d..9e6b01616 100644 --- a/examples/device/nrf52840/src/tusb_config.h +++ b/examples/device/nrf52840/src/tusb_config.h @@ -78,13 +78,6 @@ // #define CFG_TUD_DESC_VID 0xCAFE // #define CFG_TUD_DESC_PID 0x0001 -/* Use Boot Protocol for Keyboard, Mouse. Enable this will create separated HID interface - * require more IN endpoints. If disabled, they they are all packed into a single - * multiple report interface called "Generic". - */ -#define CFG_TUD_DESC_BOOT_KEYBOARD 0 -#define CFG_TUD_DESC_BOOT_MOUSE 0 - //------------- CLASS -------------// #define CFG_TUD_CDC 1 #define CFG_TUD_MSC 1 @@ -93,6 +86,12 @@ #define CFG_TUD_HID_KEYBOARD 1 #define CFG_TUD_HID_MOUSE 1 +/* Use Boot Protocol for Keyboard, Mouse. Enable this will create separated HID interface + * require more IN endpoints. If disabled, they they are all packed into a single + * multiple report interface called "Generic". */ +#define CFG_TUD_HID_KEYBOARD_BOOT 1 +#define CFG_TUD_HID_MOUSE_BOOT 1 + //-------------------------------------------------------------------- // CDC diff --git a/src/class/hid/hid_device.h b/src/class/hid/hid_device.h index 31d4a0c2f..5f21878e0 100644 --- a/src/class/hid/hid_device.h +++ b/src/class/hid/hid_device.h @@ -48,14 +48,22 @@ #endif //--------------------------------------------------------------------+ -// Class Driver Configuration +// Class Driver Default Configure & Validation //--------------------------------------------------------------------+ -#if !CFG_TUD_HID_KEYBOARD && CFG_TUD_DESC_BOOT_KEYBOARD +#ifndef CFG_TUD_HID_KEYBOARD_BOOT +#define CFG_TUD_HID_KEYBOARD_BOOT 0 +#endif + +#ifndef CFG_TUD_HID_MOUSE_BOOT +#define CFG_TUD_HID_MOUSE_BOOT 0 +#endif + +#if !CFG_TUD_HID_KEYBOARD && CFG_TUD_HID_KEYBOARD_BOOT #error CFG_TUD_HID_KEYBOARD must be enabled #endif -#if !CFG_TUD_HID_MOUSE && CFG_TUD_DESC_BOOT_MOUSE -#error CFG_TUD_HID_MOUSE must be enabled +#if !CFG_TUD_HID_MOUSE && CFG_TUD_HID_MOUSE_BOOT +#error CFG_TUD_HID_MOUSE must be enabled #endif diff --git a/src/common/tusb_error.h b/src/common/tusb_error.h index e7c7f69f9..677fc44e4 100644 --- a/src/common/tusb_error.h +++ b/src/common/tusb_error.h @@ -92,7 +92,8 @@ ENTRY(TUSB_ERROR_NOT_ENOUGH_MEMORY )\ ENTRY(TUSB_ERROR_FAILED )\ \ - ENTRY(ERR_TUD_INVALID_DESCRIPTOR) + ENTRY(ERR_TUD_INVALID_DESCRIPTOR) \ + ENTRY(ERR_TUD_EDPT_OPEN_FAILED) \ /// \brief Error Code returned diff --git a/src/device/usbd.c b/src/device/usbd.c index 7c302cc77..5f83728ef 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -318,12 +318,13 @@ static void usbd_reset(uint8_t rhport) tud_desc_set.device = (uint8_t const*) &_desc_auto_device; tud_desc_set.config = _desc_auto_config; - #if CFG_TUD_HID_KEYBOARD && CFG_TUD_DESC_BOOT_KEYBOARD +#if CFG_TUD_HID + #if CFG_TUD_HID_KEYBOARD && CFG_TUD_HID_KEYBOARD_BOOT extern uint8_t const _desc_auto_hid_boot_kbd_report[]; tud_desc_set.hid_report.boot_keyboard = _desc_auto_hid_boot_kbd_report; #endif - #if CFG_TUD_HID_MOUSE && CFG_TUD_DESC_BOOT_MOUSE + #if CFG_TUD_HID_MOUSE && CFG_TUD_HID_MOUSE_BOOT extern uint8_t const _desc_auto_hid_boot_mse_report[]; tud_desc_set.hid_report.boot_mouse = _desc_auto_hid_boot_mse_report; #endif @@ -332,6 +333,7 @@ static void usbd_reset(uint8_t rhport) extern uint8_t const _desc_auto_hid_generic_report[]; tud_desc_set.hid_report.generic = _desc_auto_hid_generic_report; #endif +#endif // CFG_TUD_HID #endif // CFG_TUD_DESC_AUTO diff --git a/src/device/usbd_desc.c b/src/device/usbd_desc.c index 8d3095503..8f147aa67 100644 --- a/src/device/usbd_desc.c +++ b/src/device/usbd_desc.c @@ -45,6 +45,10 @@ #if CFG_TUD_DESC_AUTO +//--------------------------------------------------------------------+ +// Auto Description Default Configure & Validation +//--------------------------------------------------------------------+ + /*------------- VID/PID -------------*/ #ifndef CFG_TUD_DESC_VID #define CFG_TUD_DESC_VID 0xCAFE @@ -63,17 +67,20 @@ _PID_MAP(HID_KEYBOARD, 2) | _PID_MAP(HID_MOUSE, 3) | (TUD_OPT_HID_GENERIC << 4) ) #endif +//--------------------------------------------------------------------+ +// Interface & Endpoint mapping +//--------------------------------------------------------------------+ + /*------------- Interface Numbering -------------*/ -/* The order as follows: CDC, MSC, HID - * If a interface is not enabled, the later will take its place - */ +/* The order as follows: CDC, MSC, Boot Keyboard, Boot Mouse, HID Generic + * If an interface is not enabled, the later will take its place */ #define ITF_NUM_CDC 0 #define ITF_NUM_MSC (ITF_NUM_CDC + 2*CFG_TUD_CDC) #define ITF_NUM_HID_BOOT_KBD (ITF_NUM_MSC + CFG_TUD_MSC) -#define ITF_NUM_HID_BOOT_MSE (ITF_NUM_HID_BOOT_KBD + CFG_TUD_DESC_BOOT_KEYBOARD) -#define ITF_NUM_HID_GEN (ITF_NUM_HID_BOOT_MSE + CFG_TUD_DESC_BOOT_MOUSE) +#define ITF_NUM_HID_BOOT_MSE (ITF_NUM_HID_BOOT_KBD + CFG_TUD_HID_KEYBOARD_BOOT) +#define ITF_NUM_HID_GEN (ITF_NUM_HID_BOOT_MSE + CFG_TUD_HID_MOUSE_BOOT) #define ITF_TOTAL (ITF_NUM_HID_GEN + TUD_OPT_HID_GENERIC) @@ -112,8 +119,6 @@ /*------------- Keyboard Descriptor -------------*/ -#if CFG_TUD_HID_KEYBOARD - #define HID_REPORT_KEYBOARD(...) \ HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ HID_USAGE ( HID_USAGE_DESKTOP_KEYBOARD ) ,\ @@ -154,14 +159,7 @@ HID_OUTPUT ( HID_CONSTANT ) ,\ HID_COLLECTION_END \ -#if CFG_TUD_DESC_BOOT_KEYBOARD -uint8_t const _desc_auto_hid_boot_kbd_report[] = { HID_REPORT_KEYBOARD() }; -#endif - -#endif // hid keyboard - /*------------- Mouse Descriptor -------------*/ -#if CFG_TUD_HID_MOUSE #define HID_REPORT_MOUSE(...) \ HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ HID_USAGE ( HID_USAGE_DESKTOP_MOUSE ) ,\ @@ -201,23 +199,26 @@ uint8_t const _desc_auto_hid_boot_kbd_report[] = { HID_REPORT_KEYBOARD() }; HID_COLLECTION_END ,\ HID_COLLECTION_END \ -#if CFG_TUD_DESC_BOOT_MOUSE -uint8_t const _desc_auto_hid_boot_mse_report[] = { HID_REPORT_MOUSE() }; -#endif - -#endif // hid mouse /*------------- Generic (composite) Descriptor -------------*/ +#if CFG_TUD_HID_KEYBOARD && CFG_TUD_HID_KEYBOARD_BOOT +uint8_t const _desc_auto_hid_boot_kbd_report[] = { HID_REPORT_KEYBOARD() }; +#endif + +#if CFG_TUD_HID_MOUSE && CFG_TUD_HID_MOUSE_BOOT +uint8_t const _desc_auto_hid_boot_mse_report[] = { HID_REPORT_MOUSE() }; +#endif #if TUD_OPT_HID_GENERIC +// TODO report ID uint8_t const _desc_auto_hid_generic_report[] = { -#if !CFG_TUD_DESC_BOOT_KEYBOARD +#if CFG_TUD_HID_KEYBOARD && !CFG_TUD_HID_KEYBOARD_BOOT HID_REPORT_KEYBOARD( HID_REPORT_ID(1), ), #endif -#if !CFG_TUD_DESC_BOOT_MOUSE +#if CFG_TUD_HID_MOUSE && !CFG_TUD_HID_MOUSE_BOOT HID_REPORT_MOUSE( HID_REPORT_ID(2), ) #endif @@ -309,7 +310,7 @@ typedef struct ATTR_PACKED #endif //------------- HID -------------// -#if CFG_TUD_HID_KEYBOARD && CFG_TUD_DESC_BOOT_KEYBOARD +#if CFG_TUD_HID_KEYBOARD && CFG_TUD_HID_KEYBOARD_BOOT struct ATTR_PACKED { tusb_desc_interface_t itf; @@ -318,7 +319,7 @@ typedef struct ATTR_PACKED } hid_kbd_boot; #endif -#if CFG_TUD_HID_MOUSE && CFG_TUD_DESC_BOOT_MOUSE +#if CFG_TUD_HID_MOUSE && CFG_TUD_HID_MOUSE_BOOT struct ATTR_PACKED { tusb_desc_interface_t itf; @@ -513,7 +514,7 @@ desc_auto_cfg_t const _desc_auto_config_struct = }, #endif // msc -#if CFG_TUD_HID_KEYBOARD && CFG_TUD_DESC_BOOT_KEYBOARD +#if CFG_TUD_HID_KEYBOARD && CFG_TUD_HID_KEYBOARD_BOOT .hid_kbd_boot = { .itf = @@ -553,7 +554,7 @@ desc_auto_cfg_t const _desc_auto_config_struct = #endif // boot keyboard //------------- HID Mouse -------------// -#if CFG_TUD_HID_MOUSE && CFG_TUD_DESC_BOOT_MOUSE +#if CFG_TUD_HID_MOUSE && CFG_TUD_HID_MOUSE_BOOT .hid_mse_boot = { .itf = diff --git a/src/tusb_option.h b/src/tusb_option.h index 4af327a5d..f4f1389da 100644 --- a/src/tusb_option.h +++ b/src/tusb_option.h @@ -171,9 +171,9 @@ #define CFG_TUD_MSC 0 #endif - // Generic (multiple) Report : Keyboard + Mouse + Gamepad + Joystick - #define TUD_OPT_HID_GENERIC (CFG_TUD_HID && ( (CFG_TUD_HID_KEYBOARD && !CFG_TUD_DESC_BOOT_KEYBOARD) || \ - (CFG_TUD_HID_MOUSE && !CFG_TUD_DESC_BOOT_MOUSE) )) + // IF HID Generic is required, it is multiple Report : Keyboard + Mouse + Gamepad + Joystick + #define TUD_OPT_HID_GENERIC ( (CFG_TUD_HID_KEYBOARD && !CFG_TUD_HID_KEYBOARD_BOOT) || \ + (CFG_TUD_HID_MOUSE && !CFG_TUD_HID_MOUSE_BOOT) ) #endif // TUSB_OPT_DEVICE_ENABLED @@ -206,7 +206,7 @@ //------------------------------------------------------------------ -// Config Verification +// Configuration Validation //------------------------------------------------------------------ #if (CFG_TUSB_OS != OPT_OS_NONE) && !defined (CFG_TUD_TASK_PRIO) -- cgit v1.3.1 From 8eeee22ffc82bd63adc85a36bd6194d0fd879c11 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 30 Jul 2018 17:01:20 +0700 Subject: enhance device hid driver seperate inteface and report --- src/class/hid/hid_device.c | 174 +++++++++++++++++++++++++++------------------ 1 file changed, 106 insertions(+), 68 deletions(-) (limited to 'src/class') diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index bf2cc75af..d6671e4f3 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -55,41 +55,63 @@ // Max report len is keyboard's one with 8 byte + 1 byte report id #define REPORT_BUFSIZE 9 -typedef struct { +typedef struct +{ uint8_t itf_num; uint8_t ep_in; - uint8_t idle_rate; // in unit of 4 ms - uint8_t usage; // HID_USAGE_* + uint8_t idle_rate; // in unit of 4 ms TODO removed bool boot_protocol; - uint8_t report_id; - uint16_t report_len; - uint8_t const * report_desc; + uint16_t desc_len; + uint8_t const * desc_report; + + CFG_TUSB_MEM_ALIGN uint8_t report_buf[REPORT_BUFSIZE]; - // class specific control request + // callbacks uint16_t (*get_report_cb) (uint8_t report_id, hid_report_type_t type, uint8_t* buffer, uint16_t reqlen); void (*set_report_cb) (uint8_t report_id, hid_report_type_t type, uint8_t const* buffer, uint16_t bufsize); - CFG_TUSB_MEM_ALIGN uint8_t report_buf[REPORT_BUFSIZE]; }hidd_interface_t; +typedef struct +{ + uint8_t usage; // HID_USAGE_* + uint8_t idle_rate; // in unit of 4 ms + + uint8_t report_id; + uint8_t report_len; + + hidd_interface_t* itf; +} hidd_report_t ; + + +#define ITF_IDX_BOOT_KBD 0 +#define ITF_IDX_BOOT_MSE ( ITF_IDX_BOOT_KBD + (CFG_TUD_HID_KEYBOARD && CFG_TUD_HID_KEYBOARD_BOOT) ) +#define ITF_IDX_GENERIC ( ITF_IDX_BOOT_MSE + (CFG_TUD_HID_MOUSE && CFG_TUD_HID_MOUSE_BOOT) ) +#define ITF_COUNT ( ITF_IDX_GENERIC + TUD_OPT_HID_GENERIC ) + +CFG_TUSB_ATTR_USBRAM static hidd_interface_t _hidd_itf[ITF_COUNT]; + #if CFG_TUD_HID_KEYBOARD -CFG_TUSB_ATTR_USBRAM static hidd_interface_t _kbd_itf; +static hidd_report_t _kbd_rpt; #endif #if CFG_TUD_HID_MOUSE -CFG_TUSB_ATTR_USBRAM static hidd_interface_t _mse_itf; +static hidd_report_t _mse_rpt; #endif -CFG_TUSB_ATTR_USBRAM static hidd_interface_t _hidd_itf; +/*------------- -------------*/ static inline hidd_interface_t* get_interface_by_itfnum(uint8_t itf_num) { - return ( itf_num == _kbd_itf.itf_num ) ? &_kbd_itf : - ( itf_num == _mse_itf.itf_num ) ? &_mse_itf : - ( itf_num == _hidd_itf.itf_num ) ? &_hidd_itf : NULL; + for (uint8_t i=0; i < ITF_COUNT; i++ ) + { + if ( itf_num == _hidd_itf[i].itf_num ) return &_hidd_itf[i]; + } + + return NULL; } @@ -98,7 +120,11 @@ static inline hidd_interface_t* get_interface_by_itfnum(uint8_t itf_num) //--------------------------------------------------------------------+ bool tud_hid_generic_ready(void) { - +#if TUD_OPT_HID_GENERIC + return (_hidd_itf[ITF_IDX_GENERIC].ep_in != 0) && !dcd_edpt_busy(TUD_OPT_RHPORT, _hidd_itf[ITF_IDX_GENERIC].ep_in); +#else + return false; +#endif } //--------------------------------------------------------------------+ @@ -107,32 +133,31 @@ bool tud_hid_generic_ready(void) #if CFG_TUD_HID_KEYBOARD bool tud_hid_keyboard_ready(void) { - VERIFY( _kbd_itf.ep_in != 0 ); - return !dcd_edpt_busy(TUD_OPT_RHPORT, _kbd_itf.ep_in); + return (_kbd_rpt.itf != NULL) && !dcd_edpt_busy(TUD_OPT_RHPORT, _kbd_rpt.itf->ep_in); } bool tud_hid_keyboard_is_boot_protocol(void) { - return _kbd_itf.boot_protocol; + return (_kbd_rpt.itf != NULL) && _kbd_rpt.itf->boot_protocol; } static bool hidd_kbd_report(hid_keyboard_report_t const *p_report) { VERIFY( tud_hid_keyboard_ready() ); - hidd_interface_t * p_hid = &_kbd_itf; + hidd_interface_t * p_hid = _kbd_rpt.itf; // Idle Rate = 0 : only send report if there is changes, i.e skip duplication // Idle Rate > 0 : skip duplication, but send at least 1 report every idle rate (in unit of 4 ms). // If idle time is less than interrupt polling then use the polling. static tu_timeout_t idle_tm = { 0, 0 }; - if ( (p_hid->idle_rate == 0) || !tu_timeout_expired(&idle_tm) ) + if ( (_kbd_rpt.idle_rate == 0) || !tu_timeout_expired(&idle_tm) ) { if ( 0 == memcmp(p_hid->report_buf, p_report, sizeof(hid_keyboard_report_t)) ) return true; } - tu_timeout_set(&idle_tm, p_hid->idle_rate *4); + tu_timeout_set(&idle_tm, _kbd_rpt.idle_rate * 4); memcpy(p_hid->report_buf, p_report, sizeof(hid_keyboard_report_t)); return dcd_edpt_xfer(TUD_OPT_RHPORT, p_hid->ep_in, p_hid->report_buf, sizeof(hid_keyboard_report_t)); @@ -193,7 +218,7 @@ bool tud_hid_keyboard_key_sequence(const char* str, uint32_t interval_ms) #endif // CFG_TUD_HID_ASCII_TO_KEYCODE_LOOKUP -#endif +#endif // CFG_TUD_HID_KEYBOARD //--------------------------------------------------------------------+ // MOUSE APPLICATION API @@ -202,20 +227,19 @@ bool tud_hid_keyboard_key_sequence(const char* str, uint32_t interval_ms) bool tud_hid_mouse_ready(void) { - VERIFY( _mse_itf.ep_in != 0 ); - return !dcd_edpt_busy(TUD_OPT_RHPORT, _mse_itf.ep_in); + return (_mse_rpt.itf != NULL) && !dcd_edpt_busy(TUD_OPT_RHPORT, _mse_rpt.itf->ep_in); } bool tud_hid_mouse_is_boot_protocol(void) { - return _mse_itf.boot_protocol; + return (_mse_rpt.itf != NULL) && _mse_rpt.itf->boot_protocol; } static bool hidd_mouse_report(hid_mouse_report_t const *p_report) { VERIFY( tud_hid_mouse_ready() ); - hidd_interface_t * p_hid = &_mse_itf; + hidd_interface_t * p_hid = _mse_rpt.itf; memcpy(p_hid->report_buf, p_report, sizeof(hid_mouse_report_t)); return dcd_edpt_xfer(TUD_OPT_RHPORT, p_hid->ep_in, p_hid->report_buf, sizeof(hid_mouse_report_t)); @@ -237,7 +261,9 @@ bool tud_hid_mouse_data(uint8_t buttons, int8_t x, int8_t y, int8_t scroll, int8 bool tud_hid_mouse_move(int8_t x, int8_t y) { - hidd_interface_t * p_hid = &_mse_itf; + VERIFY( tud_hid_mouse_ready() ); + + hidd_interface_t * p_hid = _mse_rpt.itf; uint8_t prev_buttons = p_hid->report_buf[0]; return tud_hid_mouse_data(prev_buttons, x, y, 0, 0); @@ -245,13 +271,15 @@ bool tud_hid_mouse_move(int8_t x, int8_t y) bool tud_hid_mouse_scroll(int8_t vertical, int8_t horizontal) { - hidd_interface_t * p_hid = &_mse_itf; + VERIFY( tud_hid_mouse_ready() ); + + hidd_interface_t * p_hid = _mse_rpt.itf; uint8_t prev_buttons = p_hid->report_buf[0]; return tud_hid_mouse_data(prev_buttons, 0, 0, vertical, horizontal); } -#endif +#endif // CFG_TUD_HID_MOUSE //--------------------------------------------------------------------+ // USBD-CLASS API @@ -263,12 +291,14 @@ void hidd_init(void) void hidd_reset(uint8_t rhport) { - #if CFG_TUD_HID_MOUSE - varclr_(&_mse_itf); - #endif + arrclr_(_hidd_itf); #if CFG_TUD_HID_KEYBOARD - varclr_(&_kbd_itf); + varclr_(&_kbd_rpt); + #endif + + #if CFG_TUD_HID_MOUSE + varclr_(&_mse_rpt); #endif } @@ -276,6 +306,9 @@ tusb_error_t hidd_open(uint8_t rhport, tusb_desc_interface_t const * desc_itf, u { uint8_t const *p_desc = (uint8_t const *) desc_itf; + // TODO not support HID OUT Endpoint + TU_ASSERT(desc_itf->bNumEndpoints == 1, ERR_TUD_INVALID_DESCRIPTOR); + //------------- HID descriptor -------------// p_desc += p_desc[DESC_OFFSET_LEN]; tusb_hid_descriptor_hid_t const *desc_hid = (tusb_hid_descriptor_hid_t const *) p_desc; @@ -286,69 +319,72 @@ tusb_error_t hidd_open(uint8_t rhport, tusb_desc_interface_t const * desc_itf, u tusb_desc_endpoint_t const *desc_edpt = (tusb_desc_endpoint_t const *) p_desc; TU_ASSERT(TUSB_DESC_ENDPOINT == desc_edpt->bDescriptorType, ERR_TUD_INVALID_DESCRIPTOR); - *p_len = 0; + hidd_interface_t * p_hid = NULL; /*------------- Boot protocol only keyboard & mouse -------------*/ if (desc_itf->bInterfaceSubClass == HID_SUBCLASS_BOOT) { TU_ASSERT(desc_itf->bInterfaceProtocol == HID_PROTOCOL_KEYBOARD || desc_itf->bInterfaceProtocol == HID_PROTOCOL_MOUSE, ERR_TUD_INVALID_DESCRIPTOR); - hidd_interface_t * p_hid = NULL; - - #if CFG_TUD_HID_KEYBOARD + #if CFG_TUD_HID_KEYBOARD && CFG_TUD_HID_KEYBOARD_BOOT if (desc_itf->bInterfaceProtocol == HID_PROTOCOL_KEYBOARD) { - p_hid = &_kbd_itf; - p_hid->report_desc = tud_desc_set.hid_report.boot_keyboard; + p_hid = &_hidd_itf[ITF_IDX_BOOT_KBD]; + p_hid->desc_report = tud_desc_set.hid_report.boot_keyboard; p_hid->get_report_cb = tud_hid_keyboard_get_report_cb; p_hid->set_report_cb = tud_hid_keyboard_set_report_cb; + + hidd_report_t* report = &_kbd_rpt; + report->usage = HID_USAGE_DESKTOP_KEYBOARD; + report->report_id = 0; + report->report_len = 8; + report->itf = p_hid; } #endif - #if CFG_TUD_HID_MOUSE + #if CFG_TUD_HID_MOUSE && CFG_TUD_HID_MOUSE_BOOT if (desc_itf->bInterfaceProtocol == HID_PROTOCOL_MOUSE) { - p_hid = &_mse_itf; - p_hid->report_desc = tud_desc_set.hid_report.boot_mouse; + p_hid = &_hidd_itf[ITF_IDX_BOOT_MSE]; + p_hid->desc_report = tud_desc_set.hid_report.boot_mouse; p_hid->get_report_cb = tud_hid_mouse_get_report_cb; p_hid->set_report_cb = tud_hid_mouse_set_report_cb; + + hidd_report_t* report = &_mse_rpt; + report->usage = HID_USAGE_DESKTOP_MOUSE; + report->report_id = 0; + report->report_len = 4; + report->itf = p_hid; } #endif TU_ASSERT(p_hid, ERR_TUD_INVALID_DESCRIPTOR); - VERIFY(p_hid->report_desc, TUSB_ERROR_DESCRIPTOR_CORRUPTED); - - TU_ASSERT( dcd_edpt_open(rhport, desc_edpt), TUSB_ERROR_DCD_FAILED ); - - p_hid->report_len = desc_hid->wReportLength; - p_hid->itf_num = desc_itf->bInterfaceNumber; - p_hid->ep_in = desc_edpt->bEndpointAddress; - p_hid->report_id = 0; p_hid->boot_protocol = true; // default mode is BOOT - - *p_len = sizeof(tusb_desc_interface_t) + sizeof(tusb_hid_descriptor_hid_t) + sizeof(tusb_desc_endpoint_t); } /*------------- Generic (multiple report) -------------*/ else { - // TODO HID generic - hidd_interface_t * p_hid = &_hidd_itf; - - TU_ASSERT( dcd_edpt_open(rhport, desc_edpt), TUSB_ERROR_DCD_FAILED ); - - p_hid->itf_num = desc_itf->bInterfaceNumber; - p_hid->ep_in = desc_edpt->bEndpointAddress; - + #if TUD_OPT_HID_GENERIC // TODO parse report ID for keyboard, mouse - p_hid->report_id = 0; - p_hid->report_len = desc_hid->wReportLength; - p_hid->report_desc = tud_desc_set.hid_report.generic; + p_hid = &_hidd_itf[ITF_IDX_GENERIC]; + + p_hid->desc_report = tud_desc_set.hid_report.generic; p_hid->get_report_cb = tud_hid_generic_get_report_cb; p_hid->set_report_cb = tud_hid_generic_set_report_cb; + #endif - *p_len = sizeof(tusb_desc_interface_t) + sizeof(tusb_hid_descriptor_hid_t) + sizeof(tusb_desc_endpoint_t); + TU_ASSERT(p_hid, ERR_TUD_INVALID_DESCRIPTOR); } + VERIFY(p_hid->desc_report, ERR_TUD_INVALID_DESCRIPTOR); + TU_ASSERT( dcd_edpt_open(rhport, desc_edpt), ERR_TUD_EDPT_OPEN_FAILED ); + + p_hid->itf_num = desc_itf->bInterfaceNumber; + p_hid->ep_in = desc_edpt->bEndpointAddress; + p_hid->desc_len = desc_hid->wReportLength; + + *p_len = sizeof(tusb_desc_interface_t) + sizeof(tusb_hid_descriptor_hid_t) + desc_itf->bNumEndpoints*sizeof(tusb_desc_endpoint_t); + return TUSB_ERROR_NONE; } @@ -369,10 +405,10 @@ tusb_error_t hidd_control_request_st(uint8_t rhport, tusb_control_request_t cons if (p_request->bRequest == TUSB_REQ_GET_DESCRIPTOR && desc_type == HID_DESC_TYPE_REPORT) { // use device control buffer - STASK_ASSERT ( p_hid->report_len <= CFG_TUD_CTRL_BUFSIZE ); - memcpy(_usbd_ctrl_buf, p_hid->report_desc, p_hid->report_len); + STASK_ASSERT ( p_hid->desc_len <= CFG_TUD_CTRL_BUFSIZE ); + memcpy(_usbd_ctrl_buf, p_hid->desc_report, p_hid->desc_len); - usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, _usbd_ctrl_buf, p_hid->report_len); + usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, _usbd_ctrl_buf, p_hid->desc_len); }else { dcd_control_stall(rhport); @@ -390,7 +426,7 @@ tusb_error_t hidd_control_request_st(uint8_t rhport, tusb_control_request_t cons uint16_t xferlen; if ( p_hid->get_report_cb ) { - xferlen = p_hid->get_report_cb(p_hid->report_id, (hid_report_type_t) report_type, p_hid->report_buf, p_request->wLength); + xferlen = p_hid->get_report_cb(report_id, (hid_report_type_t) report_type, p_hid->report_buf, p_request->wLength); }else { xferlen = p_request->wLength; @@ -415,11 +451,13 @@ tusb_error_t hidd_control_request_st(uint8_t rhport, tusb_control_request_t cons } else if (HID_REQ_CONTROL_SET_IDLE == p_request->bRequest) { + // TODO idle rate of report p_hid->idle_rate = u16_high_u8(p_request->wValue); dcd_control_status(rhport, p_request->bmRequestType_bit.direction); } else if (HID_REQ_CONTROL_GET_IDLE == p_request->bRequest) { + // TODO idle rate of report _usbd_ctrl_buf[0] = p_hid->idle_rate; usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, _usbd_ctrl_buf, 1); } -- cgit v1.3.1 From 1a0ffcee25566c03cc267c96cceb7a0189d2b026 Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 31 Jul 2018 13:31:03 +0700 Subject: add tud_hid_generic_report() --- src/class/hid/hid_device.c | 44 ++++++++++++++++++++++++++++++++------------ src/class/hid/hid_device.h | 2 +- 2 files changed, 33 insertions(+), 13 deletions(-) (limited to 'src/class') diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index d6671e4f3..e52952e08 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -53,7 +53,13 @@ //--------------------------------------------------------------------+ // Max report len is keyboard's one with 8 byte + 1 byte report id -#define REPORT_BUFSIZE 9 +#define REPORT_BUFSIZE 12 + + +#define ITF_IDX_BOOT_KBD 0 +#define ITF_IDX_BOOT_MSE ( ITF_IDX_BOOT_KBD + (CFG_TUD_HID_KEYBOARD && CFG_TUD_HID_KEYBOARD_BOOT) ) +#define ITF_IDX_GENERIC ( ITF_IDX_BOOT_MSE + (CFG_TUD_HID_MOUSE && CFG_TUD_HID_MOUSE_BOOT) ) +#define ITF_COUNT ( ITF_IDX_GENERIC + TUD_OPT_HID_GENERIC ) typedef struct { @@ -85,12 +91,6 @@ typedef struct hidd_interface_t* itf; } hidd_report_t ; - -#define ITF_IDX_BOOT_KBD 0 -#define ITF_IDX_BOOT_MSE ( ITF_IDX_BOOT_KBD + (CFG_TUD_HID_KEYBOARD && CFG_TUD_HID_KEYBOARD_BOOT) ) -#define ITF_IDX_GENERIC ( ITF_IDX_BOOT_MSE + (CFG_TUD_HID_MOUSE && CFG_TUD_HID_MOUSE_BOOT) ) -#define ITF_COUNT ( ITF_IDX_GENERIC + TUD_OPT_HID_GENERIC ) - CFG_TUSB_ATTR_USBRAM static hidd_interface_t _hidd_itf[ITF_COUNT]; @@ -102,7 +102,7 @@ static hidd_report_t _kbd_rpt; static hidd_report_t _mse_rpt; #endif -/*------------- -------------*/ +/*------------- Helpers -------------*/ static inline hidd_interface_t* get_interface_by_itfnum(uint8_t itf_num) { @@ -118,15 +118,35 @@ static inline hidd_interface_t* get_interface_by_itfnum(uint8_t itf_num) //--------------------------------------------------------------------+ // HID GENERIC API //--------------------------------------------------------------------+ +#if TUD_OPT_HID_GENERIC + bool tud_hid_generic_ready(void) { -#if TUD_OPT_HID_GENERIC return (_hidd_itf[ITF_IDX_GENERIC].ep_in != 0) && !dcd_edpt_busy(TUD_OPT_RHPORT, _hidd_itf[ITF_IDX_GENERIC].ep_in); -#else - return false; -#endif } +bool tud_hid_generic_report(uint8_t report_id, void const* report, uint8_t len) +{ + VERIFY( tud_hid_generic_ready() && (len < REPORT_BUFSIZE) ); + + hidd_interface_t * p_hid = &_hidd_itf[ITF_IDX_GENERIC]; + + // If report id = 0, skip ID field + if (report_id) + { + p_hid->report_buf[0] = report_id; + memcpy(p_hid->report_buf+1, report, len); + }else + { + memcpy(p_hid->report_buf, report, len); + } + + // TODO idle rate + return dcd_edpt_xfer(TUD_OPT_RHPORT, p_hid->ep_in, p_hid->report_buf, len + ( report_id ? 1 : 0) ); +} + +#endif // TUD_OPT_HID_GENERIC + //--------------------------------------------------------------------+ // KEYBOARD APPLICATION API //--------------------------------------------------------------------+ diff --git a/src/class/hid/hid_device.h b/src/class/hid/hid_device.h index 5f21878e0..43181b1a9 100644 --- a/src/class/hid/hid_device.h +++ b/src/class/hid/hid_device.h @@ -71,7 +71,7 @@ // HID GENERIC API //--------------------------------------------------------------------+ bool tud_hid_generic_ready(void); -bool tud_hid_generic_report(void); +bool tud_hid_generic_report(uint8_t report_id, void const* report, uint8_t len); /*------------- Callbacks -------------*/ ATTR_WEAK uint16_t tud_hid_generic_get_report_cb(uint8_t report_id, hid_report_type_t report_type, uint8_t* buffer, uint16_t reqlen); -- cgit v1.3.1 From 191b73b58c5ad6a098c652f31459ef39078a484b Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 31 Jul 2018 13:45:31 +0700 Subject: tud_hid_generic_get_report_cb and tud_hid_generic_set_report_cb are mandantory --- examples/device/nrf52840/src/main.c | 9 +++++++++ examples/device/nrf52840/src/msc_device_app.c | 14 ++++++++++---- src/class/hid/hid_device.c | 2 +- src/class/hid/hid_device.h | 10 +++++----- 4 files changed, 25 insertions(+), 10 deletions(-) (limited to 'src/class') diff --git a/examples/device/nrf52840/src/main.c b/examples/device/nrf52840/src/main.c index 0008bb69c..9a80accc9 100644 --- a/examples/device/nrf52840/src/main.c +++ b/examples/device/nrf52840/src/main.c @@ -143,7 +143,16 @@ void usb_hid_task(void) } } +uint16_t tud_hid_generic_get_report_cb(uint8_t report_id, hid_report_type_t report_type, uint8_t* buffer, uint16_t reqlen) +{ + // TODO not Implemented + return 0; +} +void tud_hid_generic_set_report_cb(uint8_t report_id, hid_report_type_t report_type, uint8_t const* buffer, uint16_t bufsize) +{ + // TODO not Implemented +} //--------------------------------------------------------------------+ // tinyusb callbacks diff --git a/examples/device/nrf52840/src/msc_device_app.c b/examples/device/nrf52840/src/msc_device_app.c index 916e4331c..9f5015042 100644 --- a/examples/device/nrf52840/src/msc_device_app.c +++ b/examples/device/nrf52840/src/msc_device_app.c @@ -90,17 +90,23 @@ int32_t tud_msc_scsi_cb (uint8_t lun, uint8_t const scsi_cmd[16], void* buffer, start_stop->start; start_stop->load_eject; */ - resplen = 0; + resplen = 0; break; - // negative means error -> tusb could stall and/or response with failed status - default: return -1; + + default: + // Set Sense = Invalid Command Operation + tud_msc_set_sense(lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00); + + // negative means error -> tinyusb could stall and/or response with failed status + resplen = -1; + break; } // return resplen must not larger than bufsize if ( resplen > bufsize ) resplen = bufsize; - if ( response && resplen ) + if ( response && (resplen > 0) ) { if(in_xfer) { diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index e52952e08..4df370cfe 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -449,8 +449,8 @@ tusb_error_t hidd_control_request_st(uint8_t rhport, tusb_control_request_t cons xferlen = p_hid->get_report_cb(report_id, (hid_report_type_t) report_type, p_hid->report_buf, p_request->wLength); }else { + // For boot Interface only: re-use report_buf -> report has no change xferlen = p_request->wLength; - // re-use report_buf -> report has no change } STASK_ASSERT( xferlen > 0 ); diff --git a/src/class/hid/hid_device.h b/src/class/hid/hid_device.h index 43181b1a9..6edd9f934 100644 --- a/src/class/hid/hid_device.h +++ b/src/class/hid/hid_device.h @@ -73,9 +73,9 @@ bool tud_hid_generic_ready(void); bool tud_hid_generic_report(uint8_t report_id, void const* report, uint8_t len); -/*------------- Callbacks -------------*/ -ATTR_WEAK uint16_t tud_hid_generic_get_report_cb(uint8_t report_id, hid_report_type_t report_type, uint8_t* buffer, uint16_t reqlen); -ATTR_WEAK void tud_hid_generic_set_report_cb(uint8_t report_id, hid_report_type_t report_type, uint8_t const* buffer, uint16_t bufsize); +/*------------- Callbacks (Weak is optional) -------------*/ +uint16_t tud_hid_generic_get_report_cb(uint8_t report_id, hid_report_type_t report_type, uint8_t* buffer, uint16_t reqlen); +void tud_hid_generic_set_report_cb(uint8_t report_id, hid_report_type_t report_type, uint8_t const* buffer, uint16_t bufsize); //--------------------------------------------------------------------+ // KEYBOARD API @@ -110,7 +110,7 @@ extern const hid_ascii_to_keycode_entry_t HID_ASCII_TO_KEYCODE[128]; #endif -/*------------- Callbacks -------------*/ +/*------------- Callbacks (Weak is optional) -------------*/ /** Callback invoked when USB host request \ref HID_REQ_CONTROL_GET_REPORT. * \param[in] report_type specify which report (INPUT, OUTPUT, FEATURE) that host requests @@ -172,7 +172,7 @@ static inline bool tud_hid_mouse_button_release(void) return tud_hid_mouse_data(0, 0, 0, 0, 0); } -/*------------- Callbacks -------------*/ +/*------------- Callbacks (Weak is optional) -------------*/ /** * Callback function that is invoked when USB host request \ref HID_REQ_CONTROL_GET_REPORT. -- cgit v1.3.1 From cc143cccf414f67bf2fc04751b12ee18c447997b Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 31 Jul 2018 14:27:48 +0700 Subject: move default option --- src/class/hid/hid_device.h | 8 -------- src/tusb_option.h | 8 ++++++++ 2 files changed, 8 insertions(+), 8 deletions(-) (limited to 'src/class') diff --git a/src/class/hid/hid_device.h b/src/class/hid/hid_device.h index 6edd9f934..5163a8ca8 100644 --- a/src/class/hid/hid_device.h +++ b/src/class/hid/hid_device.h @@ -50,14 +50,6 @@ //--------------------------------------------------------------------+ // Class Driver Default Configure & Validation //--------------------------------------------------------------------+ -#ifndef CFG_TUD_HID_KEYBOARD_BOOT -#define CFG_TUD_HID_KEYBOARD_BOOT 0 -#endif - -#ifndef CFG_TUD_HID_MOUSE_BOOT -#define CFG_TUD_HID_MOUSE_BOOT 0 -#endif - #if !CFG_TUD_HID_KEYBOARD && CFG_TUD_HID_KEYBOARD_BOOT #error CFG_TUD_HID_KEYBOARD must be enabled #endif diff --git a/src/tusb_option.h b/src/tusb_option.h index f4f1389da..291800c56 100644 --- a/src/tusb_option.h +++ b/src/tusb_option.h @@ -171,6 +171,14 @@ #define CFG_TUD_MSC 0 #endif + #ifndef CFG_TUD_HID_KEYBOARD_BOOT + #define CFG_TUD_HID_KEYBOARD_BOOT 0 + #endif + + #ifndef CFG_TUD_HID_MOUSE_BOOT + #define CFG_TUD_HID_MOUSE_BOOT 0 + #endif + // IF HID Generic is required, it is multiple Report : Keyboard + Mouse + Gamepad + Joystick #define TUD_OPT_HID_GENERIC ( (CFG_TUD_HID_KEYBOARD && !CFG_TUD_HID_KEYBOARD_BOOT) || \ (CFG_TUD_HID_MOUSE && !CFG_TUD_HID_MOUSE_BOOT) ) -- cgit v1.3.1 From a2b7b9ddb9f3c01bd0572eba73c33548ee2ce1df Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 31 Jul 2018 14:59:39 +0700 Subject: fix hid warning, move report descriptor template to hid.h --- src/class/hid/hid.h | 100 ++++++++++++++++++++++++++++++++++++++++++ src/class/hid/hid_device.c | 4 +- src/class/hid/hid_device.h | 4 ++ src/device/usbd_auto_desc.c | 104 ++------------------------------------------ 4 files changed, 110 insertions(+), 102 deletions(-) (limited to 'src/class') diff --git a/src/class/hid/hid.h b/src/class/hid/hid.h index d2803177b..3b66ce4f2 100644 --- a/src/class/hid/hid.h +++ b/src/class/hid/hid.h @@ -609,6 +609,106 @@ enum HID_USAGE_CONSUMER_AC_PAN = 0x0238, }; +//--------------------------------------------------------------------+ +// HID Report Descriptor Template +//--------------------------------------------------------------------+ + +/*------------- Keyboard Descriptor Template -------------*/ +#define HID_REPORT_DESC_KEYBOARD(...) \ + HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_KEYBOARD ) ,\ + HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\ + /* 8 bits Modifier Keys (Shfit, Control, Alt) */ \ + __VA_ARGS__ \ + HID_USAGE_PAGE ( HID_USAGE_PAGE_KEYBOARD ) ,\ + HID_USAGE_MIN ( 224 ) ,\ + HID_USAGE_MAX ( 231 ) ,\ + HID_LOGICAL_MIN ( 0 ) ,\ + HID_LOGICAL_MAX ( 1 ) ,\ + HID_REPORT_COUNT ( 8 ) ,\ + HID_REPORT_SIZE ( 1 ) ,\ + HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\ + /* 8 bit reserved */ \ + HID_REPORT_COUNT ( 1 ) ,\ + HID_REPORT_SIZE ( 8 ) ,\ + HID_INPUT ( HID_CONSTANT ) ,\ + /* 6-byte Keycodes */ \ + HID_USAGE_PAGE ( HID_USAGE_PAGE_KEYBOARD ) ,\ + HID_USAGE_MIN ( 0 ) ,\ + HID_USAGE_MAX ( 255 ) ,\ + HID_LOGICAL_MIN ( 0 ) ,\ + HID_LOGICAL_MAX ( 255 ) ,\ + HID_REPORT_COUNT ( 6 ) ,\ + HID_REPORT_SIZE ( 8 ) ,\ + HID_INPUT ( HID_DATA | HID_ARRAY | HID_ABSOLUTE ) ,\ + /* 5-bit LED Indicator Kana | Compose | ScrollLock | CapsLock | NumLock */ \ + HID_USAGE_PAGE ( HID_USAGE_PAGE_LED ) ,\ + HID_USAGE_MIN ( 1 ) ,\ + HID_USAGE_MAX ( 5 ) ,\ + HID_REPORT_COUNT ( 5 ) ,\ + HID_REPORT_SIZE ( 1 ) ,\ + HID_OUTPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\ + /* led padding */ \ + HID_REPORT_COUNT ( 1 ) ,\ + HID_REPORT_SIZE ( 3 ) ,\ + HID_OUTPUT ( HID_CONSTANT ) ,\ + HID_COLLECTION_END \ + +/*------------- Mouse Descriptor Template -------------*/ +#define HID_REPORT_DESC_MOUSE(...) \ + HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_MOUSE ) ,\ + HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\ + __VA_ARGS__ \ + HID_USAGE ( HID_USAGE_DESKTOP_POINTER ) ,\ + HID_COLLECTION ( HID_COLLECTION_PHYSICAL ) ,\ + HID_USAGE_PAGE ( HID_USAGE_PAGE_BUTTON ) ,\ + HID_USAGE_MIN ( 1 ) ,\ + HID_USAGE_MAX ( 3 ) ,\ + HID_LOGICAL_MIN ( 0 ) ,\ + HID_LOGICAL_MAX ( 1 ) ,\ + /* Left, Right, Middle, Backward, Forward mouse buttons */ \ + HID_REPORT_COUNT ( 3 ) ,\ + HID_REPORT_SIZE ( 1 ) ,\ + HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\ + /* 3 bit padding */ \ + HID_REPORT_COUNT ( 1 ) ,\ + HID_REPORT_SIZE ( 5 ) ,\ + HID_INPUT ( HID_CONSTANT ) ,\ + HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ + /* X, Y position [-127, 127] */ \ + HID_USAGE ( HID_USAGE_DESKTOP_X ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_Y ) ,\ + HID_LOGICAL_MIN ( 0x81 ) ,\ + HID_LOGICAL_MAX ( 0x7f ) ,\ + HID_REPORT_COUNT ( 2 ) ,\ + HID_REPORT_SIZE ( 8 ) ,\ + HID_INPUT ( HID_DATA | HID_VARIABLE | HID_RELATIVE ) ,\ + /* Mouse scroll [-127, 127] */ \ + HID_USAGE ( HID_USAGE_DESKTOP_WHEEL ) ,\ + HID_LOGICAL_MIN ( 0x81 ) ,\ + HID_LOGICAL_MAX ( 0x7f ) ,\ + HID_REPORT_COUNT( 1 ) ,\ + HID_REPORT_SIZE ( 8 ) ,\ + HID_INPUT ( HID_DATA | HID_VARIABLE | HID_RELATIVE ) ,\ + HID_COLLECTION_END ,\ + HID_COLLECTION_END \ + +//------------- Consumer Control Report Template -------------// +#define HID_REPORT_DESC_CONSUMER(...) \ + HID_USAGE_PAGE ( HID_USAGE_PAGE_CONSUMER ) ,\ + HID_USAGE ( HID_USAGE_CONSUMER_CONTROL ) ,\ + HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\ + __VA_ARGS__ \ + HID_LOGICAL_MIN ( 0x00 ) ,\ + HID_LOGICAL_MAX_N( 0x03FF, 2 ) ,\ + HID_USAGE_MIN ( 0x00 ) ,\ + HID_USAGE_MAX_N ( 0x03FF, 2 ) ,\ + HID_REPORT_COUNT ( 1 ) ,\ + HID_REPORT_SIZE ( 16 ) ,\ + HID_INPUT ( HID_DATA | HID_ARRAY | HID_ABSOLUTE ) ,\ + HID_COLLECTION_END \ + #ifdef __cplusplus } diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index 4df370cfe..d0ecad2d9 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -458,12 +458,12 @@ tusb_error_t hidd_control_request_st(uint8_t rhport, tusb_control_request_t cons } else if ( HID_REQ_CONTROL_SET_REPORT == p_request->bRequest ) { + usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, _usbd_ctrl_buf, p_request->wLength); + // wValue = Report Type | Report ID uint8_t const report_type = u16_high_u8(p_request->wValue); uint8_t const report_id = u16_low_u8(p_request->wValue); - usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, _usbd_ctrl_buf, p_request->wLength); - if ( p_hid->set_report_cb ) { p_hid->set_report_cb(report_id, (hid_report_type_t) report_type, _usbd_ctrl_buf, p_request->wLength); diff --git a/src/class/hid/hid_device.h b/src/class/hid/hid_device.h index 5163a8ca8..041770c02 100644 --- a/src/class/hid/hid_device.h +++ b/src/class/hid/hid_device.h @@ -50,6 +50,10 @@ //--------------------------------------------------------------------+ // Class Driver Default Configure & Validation //--------------------------------------------------------------------+ +#ifndef CFG_TUD_HID_ASCII_TO_KEYCODE_LOOKUP +#define CFG_TUD_HID_ASCII_TO_KEYCODE_LOOKUP 0 +#endif + #if !CFG_TUD_HID_KEYBOARD && CFG_TUD_HID_KEYBOARD_BOOT #error CFG_TUD_HID_KEYBOARD must be enabled #endif diff --git a/src/device/usbd_auto_desc.c b/src/device/usbd_auto_desc.c index d09ea3834..cb4ec6a77 100644 --- a/src/device/usbd_auto_desc.c +++ b/src/device/usbd_auto_desc.c @@ -118,109 +118,13 @@ //--------------------------------------------------------------------+ -/*------------- Keyboard Descriptor Template -------------*/ -#define HID_REPORT_KEYBOARD(...) \ - HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ - HID_USAGE ( HID_USAGE_DESKTOP_KEYBOARD ) ,\ - HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\ - /* 8 bits Modifier Keys (Shfit, Control, Alt) */ \ - __VA_ARGS__ \ - HID_USAGE_PAGE ( HID_USAGE_PAGE_KEYBOARD ) ,\ - HID_USAGE_MIN ( 224 ) ,\ - HID_USAGE_MAX ( 231 ) ,\ - HID_LOGICAL_MIN ( 0 ) ,\ - HID_LOGICAL_MAX ( 1 ) ,\ - HID_REPORT_COUNT ( 8 ) ,\ - HID_REPORT_SIZE ( 1 ) ,\ - HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\ - /* 8 bit reserved */ \ - HID_REPORT_COUNT ( 1 ) ,\ - HID_REPORT_SIZE ( 8 ) ,\ - HID_INPUT ( HID_CONSTANT ) ,\ - /* 6-byte Keycodes */ \ - HID_USAGE_PAGE ( HID_USAGE_PAGE_KEYBOARD ) ,\ - HID_USAGE_MIN ( 0 ) ,\ - HID_USAGE_MAX ( 255 ) ,\ - HID_LOGICAL_MIN ( 0 ) ,\ - HID_LOGICAL_MAX ( 255 ) ,\ - HID_REPORT_COUNT ( 6 ) ,\ - HID_REPORT_SIZE ( 8 ) ,\ - HID_INPUT ( HID_DATA | HID_ARRAY | HID_ABSOLUTE ) ,\ - /* 5-bit LED Indicator Kana | Compose | ScrollLock | CapsLock | NumLock */ \ - HID_USAGE_PAGE ( HID_USAGE_PAGE_LED ) ,\ - HID_USAGE_MIN ( 1 ) ,\ - HID_USAGE_MAX ( 5 ) ,\ - HID_REPORT_COUNT ( 5 ) ,\ - HID_REPORT_SIZE ( 1 ) ,\ - HID_OUTPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\ - /* led padding */ \ - HID_REPORT_COUNT ( 1 ) ,\ - HID_REPORT_SIZE ( 3 ) ,\ - HID_OUTPUT ( HID_CONSTANT ) ,\ - HID_COLLECTION_END \ - -/*------------- Mouse Descriptor Template -------------*/ -#define HID_REPORT_MOUSE(...) \ - HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ - HID_USAGE ( HID_USAGE_DESKTOP_MOUSE ) ,\ - HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\ - __VA_ARGS__ \ - HID_USAGE ( HID_USAGE_DESKTOP_POINTER ) ,\ - HID_COLLECTION ( HID_COLLECTION_PHYSICAL ) ,\ - HID_USAGE_PAGE ( HID_USAGE_PAGE_BUTTON ) ,\ - HID_USAGE_MIN ( 1 ) ,\ - HID_USAGE_MAX ( 3 ) ,\ - HID_LOGICAL_MIN ( 0 ) ,\ - HID_LOGICAL_MAX ( 1 ) ,\ - /* Left, Right, Middle, Backward, Forward mouse buttons */ \ - HID_REPORT_COUNT ( 3 ) ,\ - HID_REPORT_SIZE ( 1 ) ,\ - HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\ - /* 3 bit padding */ \ - HID_REPORT_COUNT ( 1 ) ,\ - HID_REPORT_SIZE ( 5 ) ,\ - HID_INPUT ( HID_CONSTANT ) ,\ - HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ - /* X, Y position [-127, 127] */ \ - HID_USAGE ( HID_USAGE_DESKTOP_X ) ,\ - HID_USAGE ( HID_USAGE_DESKTOP_Y ) ,\ - HID_LOGICAL_MIN ( 0x81 ) ,\ - HID_LOGICAL_MAX ( 0x7f ) ,\ - HID_REPORT_COUNT ( 2 ) ,\ - HID_REPORT_SIZE ( 8 ) ,\ - HID_INPUT ( HID_DATA | HID_VARIABLE | HID_RELATIVE ) ,\ - /* Mouse scroll [-127, 127] */ \ - HID_USAGE ( HID_USAGE_DESKTOP_WHEEL ) ,\ - HID_LOGICAL_MIN ( 0x81 ) ,\ - HID_LOGICAL_MAX ( 0x7f ) ,\ - HID_REPORT_COUNT( 1 ) ,\ - HID_REPORT_SIZE ( 8 ) ,\ - HID_INPUT ( HID_DATA | HID_VARIABLE | HID_RELATIVE ) ,\ - HID_COLLECTION_END ,\ - HID_COLLECTION_END \ - -//------------- Consumer Control Report Template -------------// -// HID_USAGE_PAGE ( HID_USAGE_PAGE_CONSUMER ), -// HID_USAGE ( HID_USAGE_CONSUMER_CONTROL ), -// HID_COLLECTION ( HID_COLLECTION_APPLICATION ), -// HID_REPORT_ID( REPORT_ID_CONSUMER_CONTROL ), -// HID_LOGICAL_MIN ( 0x00 ), -// HID_LOGICAL_MAX_N( 0x03FF, 2 ), -// HID_USAGE_MIN ( 0x00 ), -// HID_USAGE_MAX_N ( 0x03FF, 2 ), -// HID_REPORT_COUNT ( 1 ), -// HID_REPORT_SIZE ( 16 ), -// HID_INPUT ( HID_DATA | HID_ARRAY | HID_ABSOLUTE ), -// HID_COLLECTION_END, - - /*------------- Boot Protocol Report Descriptor -------------*/ #if CFG_TUD_HID_KEYBOARD && CFG_TUD_HID_KEYBOARD_BOOT -uint8_t const _desc_auto_hid_boot_kbd_report[] = { HID_REPORT_KEYBOARD() }; +uint8_t const _desc_auto_hid_boot_kbd_report[] = { HID_REPORT_DESC_KEYBOARD() }; #endif #if CFG_TUD_HID_MOUSE && CFG_TUD_HID_MOUSE_BOOT -uint8_t const _desc_auto_hid_boot_mse_report[] = { HID_REPORT_MOUSE() }; +uint8_t const _desc_auto_hid_boot_mse_report[] = { HID_REPORT_DESC_MOUSE() }; #endif @@ -235,11 +139,11 @@ uint8_t const _desc_auto_hid_boot_mse_report[] = { HID_REPORT_MOUSE() }; uint8_t const _desc_auto_hid_generic_report[] = { #if CFG_TUD_HID_KEYBOARD && !CFG_TUD_HID_KEYBOARD_BOOT - HID_REPORT_KEYBOARD( HID_REPORT_ID(1), ), + HID_REPORT_DESC_KEYBOARD( HID_REPORT_ID(1), ), #endif #if CFG_TUD_HID_MOUSE && !CFG_TUD_HID_MOUSE_BOOT - HID_REPORT_MOUSE( HID_REPORT_ID(2), ) + HID_REPORT_DESC_MOUSE( HID_REPORT_ID(2), ) #endif }; -- cgit v1.3.1 From 9444d45af6dfff6a34ac290cf5a221abd0c2529b Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 31 Jul 2018 23:10:50 +0700 Subject: dev hid enhancement, add report descriptor templates for keyboard, mouse, consumer, syscontrol, gamepad --- src/class/hid/hid.h | 100 -------------------------- src/class/hid/hid_device.c | 8 +-- src/class/hid/hid_device.h | 169 ++++++++++++++++++++++++++++++++++++++++++++ src/device/usbd_auto_desc.c | 3 + src/tusb_option.h | 12 ++-- 5 files changed, 181 insertions(+), 111 deletions(-) (limited to 'src/class') diff --git a/src/class/hid/hid.h b/src/class/hid/hid.h index 3b66ce4f2..d2803177b 100644 --- a/src/class/hid/hid.h +++ b/src/class/hid/hid.h @@ -609,106 +609,6 @@ enum HID_USAGE_CONSUMER_AC_PAN = 0x0238, }; -//--------------------------------------------------------------------+ -// HID Report Descriptor Template -//--------------------------------------------------------------------+ - -/*------------- Keyboard Descriptor Template -------------*/ -#define HID_REPORT_DESC_KEYBOARD(...) \ - HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ - HID_USAGE ( HID_USAGE_DESKTOP_KEYBOARD ) ,\ - HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\ - /* 8 bits Modifier Keys (Shfit, Control, Alt) */ \ - __VA_ARGS__ \ - HID_USAGE_PAGE ( HID_USAGE_PAGE_KEYBOARD ) ,\ - HID_USAGE_MIN ( 224 ) ,\ - HID_USAGE_MAX ( 231 ) ,\ - HID_LOGICAL_MIN ( 0 ) ,\ - HID_LOGICAL_MAX ( 1 ) ,\ - HID_REPORT_COUNT ( 8 ) ,\ - HID_REPORT_SIZE ( 1 ) ,\ - HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\ - /* 8 bit reserved */ \ - HID_REPORT_COUNT ( 1 ) ,\ - HID_REPORT_SIZE ( 8 ) ,\ - HID_INPUT ( HID_CONSTANT ) ,\ - /* 6-byte Keycodes */ \ - HID_USAGE_PAGE ( HID_USAGE_PAGE_KEYBOARD ) ,\ - HID_USAGE_MIN ( 0 ) ,\ - HID_USAGE_MAX ( 255 ) ,\ - HID_LOGICAL_MIN ( 0 ) ,\ - HID_LOGICAL_MAX ( 255 ) ,\ - HID_REPORT_COUNT ( 6 ) ,\ - HID_REPORT_SIZE ( 8 ) ,\ - HID_INPUT ( HID_DATA | HID_ARRAY | HID_ABSOLUTE ) ,\ - /* 5-bit LED Indicator Kana | Compose | ScrollLock | CapsLock | NumLock */ \ - HID_USAGE_PAGE ( HID_USAGE_PAGE_LED ) ,\ - HID_USAGE_MIN ( 1 ) ,\ - HID_USAGE_MAX ( 5 ) ,\ - HID_REPORT_COUNT ( 5 ) ,\ - HID_REPORT_SIZE ( 1 ) ,\ - HID_OUTPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\ - /* led padding */ \ - HID_REPORT_COUNT ( 1 ) ,\ - HID_REPORT_SIZE ( 3 ) ,\ - HID_OUTPUT ( HID_CONSTANT ) ,\ - HID_COLLECTION_END \ - -/*------------- Mouse Descriptor Template -------------*/ -#define HID_REPORT_DESC_MOUSE(...) \ - HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ - HID_USAGE ( HID_USAGE_DESKTOP_MOUSE ) ,\ - HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\ - __VA_ARGS__ \ - HID_USAGE ( HID_USAGE_DESKTOP_POINTER ) ,\ - HID_COLLECTION ( HID_COLLECTION_PHYSICAL ) ,\ - HID_USAGE_PAGE ( HID_USAGE_PAGE_BUTTON ) ,\ - HID_USAGE_MIN ( 1 ) ,\ - HID_USAGE_MAX ( 3 ) ,\ - HID_LOGICAL_MIN ( 0 ) ,\ - HID_LOGICAL_MAX ( 1 ) ,\ - /* Left, Right, Middle, Backward, Forward mouse buttons */ \ - HID_REPORT_COUNT ( 3 ) ,\ - HID_REPORT_SIZE ( 1 ) ,\ - HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\ - /* 3 bit padding */ \ - HID_REPORT_COUNT ( 1 ) ,\ - HID_REPORT_SIZE ( 5 ) ,\ - HID_INPUT ( HID_CONSTANT ) ,\ - HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ - /* X, Y position [-127, 127] */ \ - HID_USAGE ( HID_USAGE_DESKTOP_X ) ,\ - HID_USAGE ( HID_USAGE_DESKTOP_Y ) ,\ - HID_LOGICAL_MIN ( 0x81 ) ,\ - HID_LOGICAL_MAX ( 0x7f ) ,\ - HID_REPORT_COUNT ( 2 ) ,\ - HID_REPORT_SIZE ( 8 ) ,\ - HID_INPUT ( HID_DATA | HID_VARIABLE | HID_RELATIVE ) ,\ - /* Mouse scroll [-127, 127] */ \ - HID_USAGE ( HID_USAGE_DESKTOP_WHEEL ) ,\ - HID_LOGICAL_MIN ( 0x81 ) ,\ - HID_LOGICAL_MAX ( 0x7f ) ,\ - HID_REPORT_COUNT( 1 ) ,\ - HID_REPORT_SIZE ( 8 ) ,\ - HID_INPUT ( HID_DATA | HID_VARIABLE | HID_RELATIVE ) ,\ - HID_COLLECTION_END ,\ - HID_COLLECTION_END \ - -//------------- Consumer Control Report Template -------------// -#define HID_REPORT_DESC_CONSUMER(...) \ - HID_USAGE_PAGE ( HID_USAGE_PAGE_CONSUMER ) ,\ - HID_USAGE ( HID_USAGE_CONSUMER_CONTROL ) ,\ - HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\ - __VA_ARGS__ \ - HID_LOGICAL_MIN ( 0x00 ) ,\ - HID_LOGICAL_MAX_N( 0x03FF, 2 ) ,\ - HID_USAGE_MIN ( 0x00 ) ,\ - HID_USAGE_MAX_N ( 0x03FF, 2 ) ,\ - HID_REPORT_COUNT ( 1 ) ,\ - HID_REPORT_SIZE ( 16 ) ,\ - HID_INPUT ( HID_DATA | HID_ARRAY | HID_ABSOLUTE ) ,\ - HID_COLLECTION_END \ - #ifdef __cplusplus } diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index d0ecad2d9..2616155b8 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -59,7 +59,7 @@ #define ITF_IDX_BOOT_KBD 0 #define ITF_IDX_BOOT_MSE ( ITF_IDX_BOOT_KBD + (CFG_TUD_HID_KEYBOARD && CFG_TUD_HID_KEYBOARD_BOOT) ) #define ITF_IDX_GENERIC ( ITF_IDX_BOOT_MSE + (CFG_TUD_HID_MOUSE && CFG_TUD_HID_MOUSE_BOOT) ) -#define ITF_COUNT ( ITF_IDX_GENERIC + TUD_OPT_HID_GENERIC ) +#define ITF_COUNT ( ITF_IDX_GENERIC + 1 ) typedef struct { @@ -118,8 +118,6 @@ static inline hidd_interface_t* get_interface_by_itfnum(uint8_t itf_num) //--------------------------------------------------------------------+ // HID GENERIC API //--------------------------------------------------------------------+ -#if TUD_OPT_HID_GENERIC - bool tud_hid_generic_ready(void) { return (_hidd_itf[ITF_IDX_GENERIC].ep_in != 0) && !dcd_edpt_busy(TUD_OPT_RHPORT, _hidd_itf[ITF_IDX_GENERIC].ep_in); @@ -145,8 +143,6 @@ bool tud_hid_generic_report(uint8_t report_id, void const* report, uint8_t len) return dcd_edpt_xfer(TUD_OPT_RHPORT, p_hid->ep_in, p_hid->report_buf, len + ( report_id ? 1 : 0) ); } -#endif // TUD_OPT_HID_GENERIC - //--------------------------------------------------------------------+ // KEYBOARD APPLICATION API //--------------------------------------------------------------------+ @@ -384,14 +380,12 @@ tusb_error_t hidd_open(uint8_t rhport, tusb_desc_interface_t const * desc_itf, u /*------------- Generic (multiple report) -------------*/ else { - #if TUD_OPT_HID_GENERIC // TODO parse report ID for keyboard, mouse p_hid = &_hidd_itf[ITF_IDX_GENERIC]; p_hid->desc_report = tud_desc_set.hid_report.generic; p_hid->get_report_cb = tud_hid_generic_get_report_cb; p_hid->set_report_cb = tud_hid_generic_set_report_cb; - #endif TU_ASSERT(p_hid, ERR_TUD_INVALID_DESCRIPTOR); } diff --git a/src/class/hid/hid_device.h b/src/class/hid/hid_device.h index 041770c02..d5b9f3831 100644 --- a/src/class/hid/hid_device.h +++ b/src/class/hid/hid_device.h @@ -197,6 +197,175 @@ ATTR_WEAK void tud_hid_mouse_set_report_cb(uint8_t report_id, hid_report_type_t #endif + +//--------------------------------------------------------------------+ +// HID Report Descriptor Template +//--------------------------------------------------------------------+ +/* These template should be used as follow + * - Only 1 report : no parameter + * uint8_t report_desc[] = { ID_REPORT_DESC_KEYBOARD() }; + * + * - Multiple Reports: "HID_REPORT_ID(ID)," must be passed to template + * uint8_t report_desc[] = { + * ID_REPORT_DESC_KEYBOARD( HID_REPORT_ID(1) ,) , + * HID_REPORT_DESC_MOUSE ( HID_REPORT_ID(2) ,) + * }; + */ + +/*------------- Keyboard Descriptor Template -------------*/ +#define HID_REPORT_DESC_KEYBOARD(...) \ + HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_KEYBOARD ) ,\ + HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\ + /* 8 bits Modifier Keys (Shfit, Control, Alt) */ \ + __VA_ARGS__ \ + HID_USAGE_PAGE ( HID_USAGE_PAGE_KEYBOARD ) ,\ + HID_USAGE_MIN ( 224 ) ,\ + HID_USAGE_MAX ( 231 ) ,\ + HID_LOGICAL_MIN ( 0 ) ,\ + HID_LOGICAL_MAX ( 1 ) ,\ + HID_REPORT_COUNT ( 8 ) ,\ + HID_REPORT_SIZE ( 1 ) ,\ + HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\ + /* 8 bit reserved */ \ + HID_REPORT_COUNT ( 1 ) ,\ + HID_REPORT_SIZE ( 8 ) ,\ + HID_INPUT ( HID_CONSTANT ) ,\ + /* 6-byte Keycodes */ \ + HID_USAGE_PAGE ( HID_USAGE_PAGE_KEYBOARD ) ,\ + HID_USAGE_MIN ( 0 ) ,\ + HID_USAGE_MAX ( 255 ) ,\ + HID_LOGICAL_MIN ( 0 ) ,\ + HID_LOGICAL_MAX ( 255 ) ,\ + HID_REPORT_COUNT ( 6 ) ,\ + HID_REPORT_SIZE ( 8 ) ,\ + HID_INPUT ( HID_DATA | HID_ARRAY | HID_ABSOLUTE ) ,\ + /* 5-bit LED Indicator Kana | Compose | ScrollLock | CapsLock | NumLock */ \ + HID_USAGE_PAGE ( HID_USAGE_PAGE_LED ) ,\ + HID_USAGE_MIN ( 1 ) ,\ + HID_USAGE_MAX ( 5 ) ,\ + HID_REPORT_COUNT ( 5 ) ,\ + HID_REPORT_SIZE ( 1 ) ,\ + HID_OUTPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\ + /* led padding */ \ + HID_REPORT_COUNT ( 1 ) ,\ + HID_REPORT_SIZE ( 3 ) ,\ + HID_OUTPUT ( HID_CONSTANT ) ,\ + HID_COLLECTION_END \ + +/*------------- Mouse Descriptor Template -------------*/ +#define HID_REPORT_DESC_MOUSE(...) \ + HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_MOUSE ) ,\ + HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\ + __VA_ARGS__ \ + HID_USAGE ( HID_USAGE_DESKTOP_POINTER ) ,\ + HID_COLLECTION ( HID_COLLECTION_PHYSICAL ) ,\ + HID_USAGE_PAGE ( HID_USAGE_PAGE_BUTTON ) ,\ + HID_USAGE_MIN ( 1 ) ,\ + HID_USAGE_MAX ( 3 ) ,\ + HID_LOGICAL_MIN ( 0 ) ,\ + HID_LOGICAL_MAX ( 1 ) ,\ + /* Left, Right, Middle, Backward, Forward mouse buttons */ \ + HID_REPORT_COUNT ( 3 ) ,\ + HID_REPORT_SIZE ( 1 ) ,\ + HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\ + /* 3 bit padding */ \ + HID_REPORT_COUNT ( 1 ) ,\ + HID_REPORT_SIZE ( 5 ) ,\ + HID_INPUT ( HID_CONSTANT ) ,\ + HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ + /* X, Y position [-127, 127] */ \ + HID_USAGE ( HID_USAGE_DESKTOP_X ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_Y ) ,\ + HID_LOGICAL_MIN ( 0x81 ) ,\ + HID_LOGICAL_MAX ( 0x7f ) ,\ + HID_REPORT_COUNT ( 2 ) ,\ + HID_REPORT_SIZE ( 8 ) ,\ + HID_INPUT ( HID_DATA | HID_VARIABLE | HID_RELATIVE ) ,\ + /* Mouse scroll [-127, 127] */ \ + HID_USAGE ( HID_USAGE_DESKTOP_WHEEL ) ,\ + HID_LOGICAL_MIN ( 0x81 ) ,\ + HID_LOGICAL_MAX ( 0x7f ) ,\ + HID_REPORT_COUNT( 1 ) ,\ + HID_REPORT_SIZE ( 8 ) ,\ + HID_INPUT ( HID_DATA | HID_VARIABLE | HID_RELATIVE ) ,\ + HID_COLLECTION_END ,\ + HID_COLLECTION_END \ + +//------------- Consumer Control Report Template -------------// +#define HID_REPORT_DESC_CONSUMER(...) \ + HID_USAGE_PAGE ( HID_USAGE_PAGE_CONSUMER ) ,\ + HID_USAGE ( HID_USAGE_CONSUMER_CONTROL ) ,\ + HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\ + __VA_ARGS__ \ + HID_LOGICAL_MIN ( 0x00 ) ,\ + HID_LOGICAL_MAX_N( 0x03FF, 2 ) ,\ + HID_USAGE_MIN ( 0x00 ) ,\ + HID_USAGE_MAX_N ( 0x03FF, 2 ) ,\ + HID_REPORT_COUNT ( 1 ) ,\ + HID_REPORT_SIZE ( 16 ) ,\ + HID_INPUT ( HID_DATA | HID_ARRAY | HID_ABSOLUTE ) ,\ + HID_COLLECTION_END \ + +//------------- System Control Report Template -------------// +/* 0x00 - do nothing + * 0x01 - Power Off + * 0x02 - Standby + * 0x04 - Wake Host + */ +#define HID_REPORT_DESC_SYSTEM_CONTROL(...) \ + HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_SYSTEM_CONTROL ) ,\ + HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\ + __VA_ARGS__ \ + /* 2 bit system power control */ \ + HID_LOGICAL_MIN ( 1 ) ,\ + HID_LOGICAL_MAX ( 3 ) ,\ + HID_REPORT_COUNT ( 1 ) ,\ + HID_REPORT_SIZE ( 2 ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_SYSTEM_SLEEP ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_SYSTEM_POWER_DOWN ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_SYSTEM_WAKE_UP ) ,\ + HID_INPUT ( HID_DATA | HID_ARRAY | HID_ABSOLUTE ) ,\ + /* 6 bit padding */ \ + HID_REPORT_COUNT ( 1 ) ,\ + HID_REPORT_SIZE ( 6 ) ,\ + HID_INPUT ( HID_CONSTANT ) ,\ + HID_COLLECTION_END \ + +//------------- Gamepad Report Template -------------// +// Gamepad with 16 buttons and 2 joysticks +// | Button Map (2 bytes) | X | Y | Z | Rz +#define HID_REPORT_DESC_GAMEPAD(...) \ + HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_GAMEPAD ) ,\ + HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\ + __VA_ARGS__ \ + /* 16 bit Button Map */ \ + HID_USAGE_PAGE ( HID_USAGE_PAGE_BUTTON ) ,\ + HID_USAGE_MIN ( 1 ) ,\ + HID_USAGE_MAX ( 16 ) ,\ + HID_LOGICAL_MIN ( 0 ) ,\ + HID_LOGICAL_MAX ( 1 ) ,\ + HID_REPORT_COUNT ( 16 ) ,\ + HID_REPORT_SIZE ( 1 ) ,\ + HID_INPUT ( HID_DATA | HID_ARRAY | HID_ABSOLUTE ) ,\ + /* X, Y, Z, Rz (min -127, max 127 ) */ \ + HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ + HID_LOGICAL_MIN ( 0x81 ) ,\ + HID_LOGICAL_MAX ( 0x7f ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_X ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_Y ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_Z ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_RZ ) ,\ + HID_REPORT_COUNT ( 4 ) ,\ + HID_REPORT_SIZE ( 8 ) ,\ + HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\ + HID_COLLECTION_END \ + + + /** @} */ /** @} */ diff --git a/src/device/usbd_auto_desc.c b/src/device/usbd_auto_desc.c index cb4ec6a77..eaa866af0 100644 --- a/src/device/usbd_auto_desc.c +++ b/src/device/usbd_auto_desc.c @@ -49,6 +49,9 @@ // Auto Description Default Configure & Validation //--------------------------------------------------------------------+ +// IF HID Generic is required, it is multiple Report : Keyboard + Mouse + Gamepad + Joystick +#define TUD_OPT_HID_GENERIC (CFG_TUD_HID && ((CFG_TUD_HID_KEYBOARD && !CFG_TUD_HID_KEYBOARD_BOOT) || \ + (CFG_TUD_HID_MOUSE && !CFG_TUD_HID_MOUSE_BOOT)) ) /*------------- VID/PID -------------*/ #ifndef CFG_TUD_DESC_VID #define CFG_TUD_DESC_VID 0xCAFE diff --git a/src/tusb_option.h b/src/tusb_option.h index 291800c56..efb180c3a 100644 --- a/src/tusb_option.h +++ b/src/tusb_option.h @@ -171,6 +171,14 @@ #define CFG_TUD_MSC 0 #endif + #ifndef CFG_TUD_HID_KEYBOARD + #define CFG_TUD_HID_KEYBOARD 0 + #endif + + #ifndef CFG_TUD_HID_MOUSE + #define CFG_TUD_HID_MOUSE 0 + #endif + #ifndef CFG_TUD_HID_KEYBOARD_BOOT #define CFG_TUD_HID_KEYBOARD_BOOT 0 #endif @@ -179,10 +187,6 @@ #define CFG_TUD_HID_MOUSE_BOOT 0 #endif - // IF HID Generic is required, it is multiple Report : Keyboard + Mouse + Gamepad + Joystick - #define TUD_OPT_HID_GENERIC ( (CFG_TUD_HID_KEYBOARD && !CFG_TUD_HID_KEYBOARD_BOOT) || \ - (CFG_TUD_HID_MOUSE && !CFG_TUD_HID_MOUSE_BOOT) ) - #endif // TUSB_OPT_DEVICE_ENABLED //-------------------------------------------------------------------- -- cgit v1.3.1 From 6d96b12e27ae60ca500365ee2137105145ada9dd Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 1 Aug 2018 00:50:04 +0700 Subject: improve auto descriptor --- src/class/hid/hid_device.c | 6 ++--- src/device/usbd.c | 43 +++++++++++------------------------ src/device/usbd.h | 4 ++-- src/device/usbd_auto_desc.c | 37 ++++++++++++++++++++++++------ src/device/usbd_pvt.h | 3 +++ src/portable/nordic/nrf5x/dcd_nrf5x.c | 3 +++ 6 files changed, 54 insertions(+), 42 deletions(-) (limited to 'src/class') diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index 2616155b8..0527c14bf 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -346,7 +346,7 @@ tusb_error_t hidd_open(uint8_t rhport, tusb_desc_interface_t const * desc_itf, u if (desc_itf->bInterfaceProtocol == HID_PROTOCOL_KEYBOARD) { p_hid = &_hidd_itf[ITF_IDX_BOOT_KBD]; - p_hid->desc_report = tud_desc_set.hid_report.boot_keyboard; + p_hid->desc_report = usbd_desc_set->hid_report.boot_keyboard; p_hid->get_report_cb = tud_hid_keyboard_get_report_cb; p_hid->set_report_cb = tud_hid_keyboard_set_report_cb; @@ -362,7 +362,7 @@ tusb_error_t hidd_open(uint8_t rhport, tusb_desc_interface_t const * desc_itf, u if (desc_itf->bInterfaceProtocol == HID_PROTOCOL_MOUSE) { p_hid = &_hidd_itf[ITF_IDX_BOOT_MSE]; - p_hid->desc_report = tud_desc_set.hid_report.boot_mouse; + p_hid->desc_report = usbd_desc_set->hid_report.boot_mouse; p_hid->get_report_cb = tud_hid_mouse_get_report_cb; p_hid->set_report_cb = tud_hid_mouse_set_report_cb; @@ -383,7 +383,7 @@ tusb_error_t hidd_open(uint8_t rhport, tusb_desc_interface_t const * desc_itf, u // TODO parse report ID for keyboard, mouse p_hid = &_hidd_itf[ITF_IDX_GENERIC]; - p_hid->desc_report = tud_desc_set.hid_report.generic; + p_hid->desc_report = usbd_desc_set->hid_report.generic; p_hid->get_report_cb = tud_hid_generic_get_report_cb; p_hid->set_report_cb = tud_hid_generic_set_report_cb; diff --git a/src/device/usbd.c b/src/device/usbd.c index 5f83728ef..219562fa6 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -75,6 +75,15 @@ typedef struct { CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN uint8_t _usbd_ctrl_buf[CFG_TUD_CTRL_BUFSIZE]; static usbd_device_t _usbd_dev; + +// Auto descriptor is enabled, descriptor set point to auto generated one +#if CFG_TUD_DESC_AUTO +extern tud_desc_set_t const _usbd_auto_desc_set; +tud_desc_set_t const* usbd_desc_set = &_usbd_auto_desc_set; +#else +tud_desc_set_t const* usbd_desc_set = &tud_desc_set; +#endif + //--------------------------------------------------------------------+ // Class Driver //--------------------------------------------------------------------+ @@ -310,33 +319,6 @@ static void usbd_reset(uint8_t rhport) { if ( usbd_class_drivers[i].reset ) usbd_class_drivers[i].reset( rhport ); } - -#if CFG_TUD_DESC_AUTO - extern tusb_desc_device_t const _desc_auto_device; - extern uint8_t const * const _desc_auto_config; - - tud_desc_set.device = (uint8_t const*) &_desc_auto_device; - tud_desc_set.config = _desc_auto_config; - -#if CFG_TUD_HID - #if CFG_TUD_HID_KEYBOARD && CFG_TUD_HID_KEYBOARD_BOOT - extern uint8_t const _desc_auto_hid_boot_kbd_report[]; - tud_desc_set.hid_report.boot_keyboard = _desc_auto_hid_boot_kbd_report; - #endif - - #if CFG_TUD_HID_MOUSE && CFG_TUD_HID_MOUSE_BOOT - extern uint8_t const _desc_auto_hid_boot_mse_report[]; - tud_desc_set.hid_report.boot_mouse = _desc_auto_hid_boot_mse_report; - #endif - - #if TUD_OPT_HID_GENERIC - extern uint8_t const _desc_auto_hid_generic_report[]; - tud_desc_set.hid_report.generic = _desc_auto_hid_generic_report; - #endif -#endif // CFG_TUD_HID - -#endif // CFG_TUD_DESC_AUTO - } //--------------------------------------------------------------------+ @@ -452,7 +434,7 @@ static tusb_error_t proc_set_config_req(uint8_t rhport, uint8_t config_number) _usbd_dev.config_num = config_number; //------------- parse configuration & open drivers -------------// - uint8_t const * desc_cfg = tud_desc_set.config; + uint8_t const * desc_cfg = (uint8_t const *) usbd_desc_set->config; TU_ASSERT(desc_cfg != NULL, TUSB_ERROR_DESCRIPTOR_CORRUPTED); uint8_t const * p_desc = desc_cfg + sizeof(tusb_desc_configuration_t); uint16_t const cfg_len = ((tusb_desc_configuration_t*)desc_cfg)->wTotalLength; @@ -511,16 +493,17 @@ static uint16_t get_descriptor(uint8_t rhport, tusb_control_request_t const * co switch(desc_type) { case TUSB_DESC_DEVICE: - desc_data = tud_desc_set.device; + desc_data = (uint8_t const *) usbd_desc_set->device; len = sizeof(tusb_desc_device_t); break; case TUSB_DESC_CONFIGURATION: - desc_data = tud_desc_set.config; + desc_data = (uint8_t const *) usbd_desc_set->config; len = ((tusb_desc_configuration_t const*) desc_data)->wTotalLength; break; case TUSB_DESC_STRING: + // String Descriptor always uses the desc set from user if ( desc_index < tud_desc_set.string_count ) { desc_data = tud_desc_set.string_arr[desc_index]; diff --git a/src/device/usbd.h b/src/device/usbd.h index 8ef1209e1..1e59c0a7e 100644 --- a/src/device/usbd.h +++ b/src/device/usbd.h @@ -59,8 +59,8 @@ /// \brief Descriptor pointer collector to all the needed. typedef struct { - uint8_t const * device; ///< pointer to device descriptor \ref tusb_desc_device_t - uint8_t const * config; ///< pointer to the whole configuration descriptor, starting by \ref tusb_desc_configuration_t + void const * device; ///< pointer to device descriptor \ref tusb_desc_device_t + void const * config; ///< pointer to the whole configuration descriptor, starting by \ref tusb_desc_configuration_t uint8_t const** string_arr; ///< a array of pointers to string descriptors uint16_t string_count; diff --git a/src/device/usbd_auto_desc.c b/src/device/usbd_auto_desc.c index eaa866af0..a42af1ef5 100644 --- a/src/device/usbd_auto_desc.c +++ b/src/device/usbd_auto_desc.c @@ -49,8 +49,8 @@ // Auto Description Default Configure & Validation //--------------------------------------------------------------------+ -// IF HID Generic is required, it is multiple Report : Keyboard + Mouse + Gamepad + Joystick -#define TUD_OPT_HID_GENERIC (CFG_TUD_HID && ((CFG_TUD_HID_KEYBOARD && !CFG_TUD_HID_KEYBOARD_BOOT) || \ +// If HID Generic interface is generated +#define AUTO_DESC_HID_GENERIC (CFG_TUD_HID && ((CFG_TUD_HID_KEYBOARD && !CFG_TUD_HID_KEYBOARD_BOOT) || \ (CFG_TUD_HID_MOUSE && !CFG_TUD_HID_MOUSE_BOOT)) ) /*------------- VID/PID -------------*/ #ifndef CFG_TUD_DESC_VID @@ -67,7 +67,7 @@ */ #define _PID_MAP(itf, n) ( (CFG_TUD_##itf) << (n) ) #define CFG_TUD_DESC_PID (0x4000 | _PID_MAP(CDC, 0) | _PID_MAP(MSC, 1) | _PID_MAP(HID, 2) | \ - _PID_MAP(HID_KEYBOARD, 2) | _PID_MAP(HID_MOUSE, 3) | (TUD_OPT_HID_GENERIC << 4) ) + _PID_MAP(HID_KEYBOARD, 2) | _PID_MAP(HID_MOUSE, 3) | (AUTO_DESC_HID_GENERIC << 4) ) #endif //--------------------------------------------------------------------+ @@ -85,7 +85,7 @@ #define ITF_NUM_HID_BOOT_MSE (ITF_NUM_HID_BOOT_KBD + CFG_TUD_HID_KEYBOARD_BOOT) #define ITF_NUM_HID_GEN (ITF_NUM_HID_BOOT_MSE + CFG_TUD_HID_MOUSE_BOOT) -#define ITF_TOTAL (ITF_NUM_HID_GEN + TUD_OPT_HID_GENERIC) +#define ITF_TOTAL (ITF_NUM_HID_GEN + AUTO_DESC_HID_GENERIC) /*------------- Endpoint Numbering & Size -------------*/ #define _EP_IN(x) (0x80 | (x)) @@ -132,7 +132,7 @@ uint8_t const _desc_auto_hid_boot_mse_report[] = { HID_REPORT_DESC_MOUSE() }; /*------------- Generic (composite) Descriptor -------------*/ -#if TUD_OPT_HID_GENERIC +#if AUTO_DESC_HID_GENERIC // Report ID: 0 if there is only 1 report // starting from 1 if there is multiple reports @@ -255,7 +255,7 @@ typedef struct ATTR_PACKED } hid_mse_boot; #endif -#if TUD_OPT_HID_GENERIC +#if AUTO_DESC_HID_GENERIC struct ATTR_PACKED { @@ -521,7 +521,7 @@ desc_auto_cfg_t const _desc_auto_config_struct = #endif // boot mouse -#if TUD_OPT_HID_GENERIC +#if AUTO_DESC_HID_GENERIC //------------- HID Generic Multiple report -------------// .hid_generic = @@ -566,6 +566,29 @@ desc_auto_cfg_t const _desc_auto_config_struct = uint8_t const * const _desc_auto_config = (uint8_t const*) &_desc_auto_config_struct; +tud_desc_set_t const _usbd_auto_desc_set = +{ + .device = &_desc_auto_device, + .config = &_desc_auto_config_struct, + + .hid_report = + { +#if AUTO_DESC_HID_GENERIC + .generic = _desc_auto_hid_generic_report, +#else + .generic = NULL, +#endif + +#if CFG_TUD_HID_KEYBOARD && CFG_TUD_HID_KEYBOARD_BOOT + .boot_keyboard = _desc_auto_hid_boot_kbd_report, +#endif + +#if CFG_TUD_HID_MOUSE && CFG_TUD_HID_MOUSE_BOOT + .boot_mouse = _desc_auto_hid_boot_mse_report +#endif + } +}; + #endif diff --git a/src/device/usbd_pvt.h b/src/device/usbd_pvt.h index 205057db6..707e8036f 100644 --- a/src/device/usbd_pvt.h +++ b/src/device/usbd_pvt.h @@ -48,6 +48,9 @@ extern osal_semaphore_t _usbd_ctrl_sem; extern uint8_t _usbd_ctrl_buf[CFG_TUD_CTRL_BUFSIZE]; +// Either point to tud_desc_set or usbd_auto_desc_set depending on CFG_TUD_DESC_AUTO +extern tud_desc_set_t const* usbd_desc_set; + //--------------------------------------------------------------------+ // INTERNAL API for stack management //--------------------------------------------------------------------+ diff --git a/src/portable/nordic/nrf5x/dcd_nrf5x.c b/src/portable/nordic/nrf5x/dcd_nrf5x.c index 339b8df1f..b9bd6ef1a 100644 --- a/src/portable/nordic/nrf5x/dcd_nrf5x.c +++ b/src/portable/nordic/nrf5x/dcd_nrf5x.c @@ -46,6 +46,9 @@ #include "nrf_clock.h" #include "device/dcd.h" + +// TODO remove later +#include "device/usbd.h" #include "device/usbd_pvt.h" // to use defer function helper /*------------------------------------------------------------------*/ -- cgit v1.3.1 From e07b1acbed02fff395c91b421b7fdf6c7cda61a4 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 13 Aug 2018 18:10:23 +0700 Subject: rename VERIFY to TU_VERIFY to avoid conflict with application --- examples/obsolete/host/src/cdc_serial_host_app.c | 2 +- examples/obsolete/host/src/keyboard_host_app.c | 2 +- examples/obsolete/host/src/mouse_host_app.c | 2 +- src/class/cdc/cdc.h | 6 +- src/class/cdc/cdc_device.c | 4 +- src/class/cdc/cdc_rndis.h | 4 +- src/class/cdc/cdc_rndis_host.c | 2 +- src/class/hid/hid_device.c | 12 ++-- src/class/hid/hid_host.c | 2 +- src/class/msc/msc.h | 32 ++++----- src/class/msc/msc_device.c | 2 +- src/class/msc/msc_device.h | 2 +- src/common/tusb_compiler.h | 6 +- src/common/tusb_types.h | 2 +- src/common/tusb_verify.h | 78 +++++++++++----------- src/device/usbd.c | 8 +-- src/host/ehci/ehci.c | 4 +- src/host/ehci/ehci.h | 10 +-- src/host/hub.h | 6 +- src/host/ohci/ohci.h | 10 +-- src/osal/osal.h | 8 +-- src/osal/osal_none.h | 8 +-- .../nxp/lpc11xx_lpc13xx/dcd_lpc_11uxx_13uxx.c | 2 +- src/portable/nxp/lpc17xx/dcd_lpc175x_6x.c | 6 +- src/portable/nxp/lpc17xx/dcd_lpc175x_6x.h | 2 +- src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c | 8 +-- src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.h | 4 +- src/portable/nxp/lpc43xx_lpc18xx/hal_lpc43xx.c | 2 +- src/tusb.c | 2 +- 29 files changed, 119 insertions(+), 119 deletions(-) (limited to 'src/class') diff --git a/examples/obsolete/host/src/cdc_serial_host_app.c b/examples/obsolete/host/src/cdc_serial_host_app.c index 0782d0518..e21a3a67d 100644 --- a/examples/obsolete/host/src/cdc_serial_host_app.c +++ b/examples/obsolete/host/src/cdc_serial_host_app.c @@ -115,7 +115,7 @@ void cdc_serial_host_app_init(void) sem_hdl = osal_semaphore_create(1, 0); TU_ASSERT( sem_hdl, VOID_RETURN); - VERIFY( osal_task_create(cdc_serial_host_app_task, "cdc", 128, NULL, CDC_SERIAL_APP_TASK_PRIO), ); + TU_VERIFY( osal_task_create(cdc_serial_host_app_task, "cdc", 128, NULL, CDC_SERIAL_APP_TASK_PRIO), ); } //------------- main task -------------// diff --git a/examples/obsolete/host/src/keyboard_host_app.c b/examples/obsolete/host/src/keyboard_host_app.c index 130df0feb..26b1a0800 100644 --- a/examples/obsolete/host/src/keyboard_host_app.c +++ b/examples/obsolete/host/src/keyboard_host_app.c @@ -105,7 +105,7 @@ void keyboard_host_app_init(void) queue_kbd_hdl = osal_queue_create( QUEUE_KEYBOARD_REPORT_DEPTH, sizeof(hid_keyboard_report_t) ); TU_ASSERT( queue_kbd_hdl, VOID_RETURN ); - VERIFY( osal_task_create(keyboard_host_app_task, "kbd", 128, NULL, KEYBOARD_APP_TASK_PRIO), ); + TU_VERIFY( osal_task_create(keyboard_host_app_task, "kbd", 128, NULL, KEYBOARD_APP_TASK_PRIO), ); } //------------- main task -------------// diff --git a/examples/obsolete/host/src/mouse_host_app.c b/examples/obsolete/host/src/mouse_host_app.c index e9ee482d8..c326becb8 100644 --- a/examples/obsolete/host/src/mouse_host_app.c +++ b/examples/obsolete/host/src/mouse_host_app.c @@ -106,7 +106,7 @@ void mouse_host_app_init(void) queue_mouse_hdl = osal_queue_create( QUEUE_MOUSE_REPORT_DEPTH, sizeof(hid_mouse_report_t) ); TU_ASSERT( queue_mouse_hdl, VOID_RETURN); - VERIFY( osal_task_create(mouse_host_app_task, "mouse", 128, NULL, MOUSE_APP_TASK_PRIO), ); + TU_VERIFY( osal_task_create(mouse_host_app_task, "mouse", 128, NULL, MOUSE_APP_TASK_PRIO), ); } //------------- main task -------------// diff --git a/src/class/cdc/cdc.h b/src/class/cdc/cdc.h index b0c4f90d4..1b127ad28 100644 --- a/src/class/cdc/cdc.h +++ b/src/class/cdc/cdc.h @@ -300,7 +300,7 @@ typedef struct ATTR_PACKED uint8_t : 0; }cdc_acm_capability_t; -VERIFY_STATIC(sizeof(cdc_acm_capability_t) == 1, "mostly problem with compiler"); +TU_VERIFY_STATIC(sizeof(cdc_acm_capability_t) == 1, "mostly problem with compiler"); /// \brief Abstract Control Management Functional Descriptor /// \details This functional descriptor describes the commands supported by by the Communications Class interface with SubClass code of \ref CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL @@ -390,7 +390,7 @@ typedef struct ATTR_PACKED uint8_t data_bits; ///< can be 5, 6, 7, 8 or 16 } cdc_line_coding_t; -VERIFY_STATIC(sizeof(cdc_line_coding_t) == 7, "size is not correct"); +TU_VERIFY_STATIC(sizeof(cdc_line_coding_t) == 7, "size is not correct"); typedef struct ATTR_PACKED { @@ -399,7 +399,7 @@ typedef struct ATTR_PACKED uint16_t : 14; } cdc_line_control_state_t; -VERIFY_STATIC(sizeof(cdc_line_control_state_t) == 2, "size is not correct"); +TU_VERIFY_STATIC(sizeof(cdc_line_control_state_t) == 2, "size is not correct"); /** @} */ diff --git a/src/class/cdc/cdc_device.c b/src/class/cdc/cdc_device.c index bbf1c8ceb..175e78d2f 100644 --- a/src/class/cdc/cdc_device.c +++ b/src/class/cdc/cdc_device.c @@ -157,11 +157,11 @@ uint32_t tud_cdc_n_write(uint8_t itf, void const* buffer, uint32_t bufsize) bool tud_cdc_n_write_flush (uint8_t itf) { cdcd_interface_t* p_cdc = &_cdcd_itf[itf]; - VERIFY( !dcd_edpt_busy(TUD_OPT_RHPORT, p_cdc->ep_in) ); // skip if previous transfer not complete + TU_VERIFY( !dcd_edpt_busy(TUD_OPT_RHPORT, p_cdc->ep_in) ); // skip if previous transfer not complete uint16_t count = tu_fifo_read_n(&_cdcd_itf[itf].tx_ff, p_cdc->epout_buf, CFG_TUD_CDC_EPSIZE); - VERIFY( tud_cdc_n_connected(itf) ); // fifo is empty if not connected + TU_VERIFY( tud_cdc_n_connected(itf) ); // fifo is empty if not connected if ( count ) TU_ASSERT( dcd_edpt_xfer(TUD_OPT_RHPORT, p_cdc->ep_in, p_cdc->epout_buf, count) ); diff --git a/src/class/cdc/cdc_rndis.h b/src/class/cdc/cdc_rndis.h index 460477eb0..20da5660b 100644 --- a/src/class/cdc/cdc_rndis.h +++ b/src/class/cdc/cdc_rndis.h @@ -142,7 +142,7 @@ typedef struct { uint8_t oid_buffer[] ; ///< Flexible array contains the input data supplied by the host, required for the OID query request processing by the device, as per the host NDIS specification. } rndis_msg_query_t, rndis_msg_set_t; -VERIFY_STATIC(sizeof(rndis_msg_query_t) == 28, "Make sure flexible array member does not affect layout"); +TU_VERIFY_STATIC(sizeof(rndis_msg_query_t) == 28, "Make sure flexible array member does not affect layout"); /// \brief Query Complete Message /// \details This message MUST be sent by the device in response to a query OID message. @@ -156,7 +156,7 @@ typedef struct { uint8_t oid_buffer[] ; ///< Flexible array member contains the response data to the OID query request as specified by the host. } rndis_msg_query_cmplt_t; -VERIFY_STATIC(sizeof(rndis_msg_query_cmplt_t) == 24, "Make sure flexible array member does not affect layout"); +TU_VERIFY_STATIC(sizeof(rndis_msg_query_cmplt_t) == 24, "Make sure flexible array member does not affect layout"); //------------- Reset -------------// /// \brief Reset Message diff --git a/src/class/cdc/cdc_rndis_host.c b/src/class/cdc/cdc_rndis_host.c index 62361feb4..4d28b0e0c 100644 --- a/src/class/cdc/cdc_rndis_host.c +++ b/src/class/cdc/cdc_rndis_host.c @@ -75,7 +75,7 @@ static tusb_error_t send_message_get_response_subtask( uint8_t dev_addr, cdch_da tusb_error_t tusbh_cdc_rndis_get_mac_addr(uint8_t dev_addr, uint8_t mac_address[6]) { TU_ASSERT( tusbh_cdc_rndis_is_mounted(dev_addr), TUSB_ERROR_CDCH_DEVICE_NOT_MOUNTED); - VERIFY( mac_address, TUSB_ERROR_INVALID_PARA); + TU_VERIFY( mac_address, TUSB_ERROR_INVALID_PARA); memcpy(mac_address, rndish_data[dev_addr-1].mac_address, 6); diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index 0527c14bf..410359e6d 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -125,7 +125,7 @@ bool tud_hid_generic_ready(void) bool tud_hid_generic_report(uint8_t report_id, void const* report, uint8_t len) { - VERIFY( tud_hid_generic_ready() && (len < REPORT_BUFSIZE) ); + TU_VERIFY( tud_hid_generic_ready() && (len < REPORT_BUFSIZE) ); hidd_interface_t * p_hid = &_hidd_itf[ITF_IDX_GENERIC]; @@ -159,7 +159,7 @@ bool tud_hid_keyboard_is_boot_protocol(void) static bool hidd_kbd_report(hid_keyboard_report_t const *p_report) { - VERIFY( tud_hid_keyboard_ready() ); + TU_VERIFY( tud_hid_keyboard_ready() ); hidd_interface_t * p_hid = _kbd_rpt.itf; @@ -253,7 +253,7 @@ bool tud_hid_mouse_is_boot_protocol(void) static bool hidd_mouse_report(hid_mouse_report_t const *p_report) { - VERIFY( tud_hid_mouse_ready() ); + TU_VERIFY( tud_hid_mouse_ready() ); hidd_interface_t * p_hid = _mse_rpt.itf; memcpy(p_hid->report_buf, p_report, sizeof(hid_mouse_report_t)); @@ -277,7 +277,7 @@ bool tud_hid_mouse_data(uint8_t buttons, int8_t x, int8_t y, int8_t scroll, int8 bool tud_hid_mouse_move(int8_t x, int8_t y) { - VERIFY( tud_hid_mouse_ready() ); + TU_VERIFY( tud_hid_mouse_ready() ); hidd_interface_t * p_hid = _mse_rpt.itf; uint8_t prev_buttons = p_hid->report_buf[0]; @@ -287,7 +287,7 @@ bool tud_hid_mouse_move(int8_t x, int8_t y) bool tud_hid_mouse_scroll(int8_t vertical, int8_t horizontal) { - VERIFY( tud_hid_mouse_ready() ); + TU_VERIFY( tud_hid_mouse_ready() ); hidd_interface_t * p_hid = _mse_rpt.itf; uint8_t prev_buttons = p_hid->report_buf[0]; @@ -390,7 +390,7 @@ tusb_error_t hidd_open(uint8_t rhport, tusb_desc_interface_t const * desc_itf, u TU_ASSERT(p_hid, ERR_TUD_INVALID_DESCRIPTOR); } - VERIFY(p_hid->desc_report, ERR_TUD_INVALID_DESCRIPTOR); + TU_VERIFY(p_hid->desc_report, ERR_TUD_INVALID_DESCRIPTOR); TU_ASSERT( dcd_edpt_open(rhport, desc_edpt), ERR_TUD_EDPT_OPEN_FAILED ); p_hid->itf_num = desc_itf->bInterfaceNumber; diff --git a/src/class/hid/hid_host.c b/src/class/hid/hid_host.c index fa617c5b0..369dad638 100644 --- a/src/class/hid/hid_host.c +++ b/src/class/hid/hid_host.c @@ -77,7 +77,7 @@ tusb_error_t hidh_interface_get_report(uint8_t dev_addr, void * report, hidh_int //------------- parameters validation -------------// // TODO change to use is configured function TU_ASSERT (TUSB_DEVICE_STATE_CONFIGURED == tuh_device_get_state(dev_addr), TUSB_ERROR_DEVICE_NOT_READY); - VERIFY (report, TUSB_ERROR_INVALID_PARA); + TU_VERIFY (report, TUSB_ERROR_INVALID_PARA); TU_ASSSERT (!hcd_pipe_is_busy(p_hid->pipe_hdl), TUSB_ERROR_INTERFACE_IS_BUSY); TU_ASSERT_ERR( hcd_pipe_xfer(p_hid->pipe_hdl, report, p_hid->report_size, true) ) ; diff --git a/src/class/msc/msc.h b/src/class/msc/msc.h index ab8f066b3..ca5615055 100644 --- a/src/class/msc/msc.h +++ b/src/class/msc/msc.h @@ -109,7 +109,7 @@ typedef struct ATTR_PACKED uint8_t command[16] ; ///< The command block to be executed by the device. The device shall interpret the first cmd_len bytes in this field as a command block }msc_cbw_t; -VERIFY_STATIC(sizeof(msc_cbw_t) == 31, "size is not correct"); +TU_VERIFY_STATIC(sizeof(msc_cbw_t) == 31, "size is not correct"); /// Command Status Wrapper typedef struct ATTR_PACKED @@ -120,7 +120,7 @@ typedef struct ATTR_PACKED uint8_t status ; ///< indicates the success or failure of the command. Values from \ref msc_csw_status_t }msc_csw_t; -VERIFY_STATIC(sizeof(msc_csw_t) == 13, "size is not correct"); +TU_VERIFY_STATIC(sizeof(msc_csw_t) == 13, "size is not correct"); //--------------------------------------------------------------------+ // SCSI Constant @@ -173,7 +173,7 @@ typedef struct ATTR_PACKED uint8_t control ; } scsi_test_unit_ready_t; -VERIFY_STATIC(sizeof(scsi_test_unit_ready_t) == 6, "size is not correct"); +TU_VERIFY_STATIC(sizeof(scsi_test_unit_ready_t) == 6, "size is not correct"); /// SCSI Inquiry Command typedef struct ATTR_PACKED @@ -186,7 +186,7 @@ typedef struct ATTR_PACKED uint8_t control ; } scsi_inquiry_t, scsi_request_sense_t; -VERIFY_STATIC(sizeof(scsi_inquiry_t) == 6, "size is not correct"); +TU_VERIFY_STATIC(sizeof(scsi_inquiry_t) == 6, "size is not correct"); /// SCSI Inquiry Response Data typedef struct ATTR_PACKED @@ -232,7 +232,7 @@ typedef struct ATTR_PACKED uint8_t product_rev[4]; ///< 4 bytes of ASCII data defined by the vendor. } scsi_inquiry_resp_t; -VERIFY_STATIC(sizeof(scsi_inquiry_resp_t) == 36, "size is not correct"); +TU_VERIFY_STATIC(sizeof(scsi_inquiry_resp_t) == 36, "size is not correct"); typedef struct ATTR_PACKED @@ -259,7 +259,7 @@ typedef struct ATTR_PACKED } scsi_sense_fixed_resp_t; -VERIFY_STATIC(sizeof(scsi_sense_fixed_resp_t) == 18, "size is not correct"); +TU_VERIFY_STATIC(sizeof(scsi_sense_fixed_resp_t) == 18, "size is not correct"); typedef struct ATTR_PACKED { @@ -277,7 +277,7 @@ typedef struct ATTR_PACKED uint8_t control; } scsi_mode_sense6_t; -VERIFY_STATIC( sizeof(scsi_mode_sense6_t) == 6, "size is not correct"); +TU_VERIFY_STATIC( sizeof(scsi_mode_sense6_t) == 6, "size is not correct"); typedef struct ATTR_PACKED { @@ -287,7 +287,7 @@ typedef struct ATTR_PACKED uint8_t block_descriptor_len; } scsi_mode_sense6_resp_t; -VERIFY_STATIC( sizeof(scsi_mode_sense6_resp_t) == 4, "size is not correct"); +TU_VERIFY_STATIC( sizeof(scsi_mode_sense6_resp_t) == 4, "size is not correct"); typedef struct ATTR_PACKED { @@ -297,7 +297,7 @@ typedef struct ATTR_PACKED uint8_t control; } scsi_prevent_allow_medium_removal_t; -VERIFY_STATIC( sizeof(scsi_prevent_allow_medium_removal_t) == 6, "size is not correct"); +TU_VERIFY_STATIC( sizeof(scsi_prevent_allow_medium_removal_t) == 6, "size is not correct"); typedef struct ATTR_PACKED { @@ -320,7 +320,7 @@ typedef struct ATTR_PACKED uint8_t control; } scsi_start_stop_unit_t; -VERIFY_STATIC( sizeof(scsi_start_stop_unit_t) == 6, "size is not correct"); +TU_VERIFY_STATIC( sizeof(scsi_start_stop_unit_t) == 6, "size is not correct"); //--------------------------------------------------------------------+ // SCSI MMC @@ -334,7 +334,7 @@ typedef struct ATTR_PACKED uint8_t control; } scsi_read_format_capacity_t; -VERIFY_STATIC( sizeof(scsi_read_format_capacity_t) == 10, "size is not correct"); +TU_VERIFY_STATIC( sizeof(scsi_read_format_capacity_t) == 10, "size is not correct"); typedef struct ATTR_PACKED{ uint8_t reserved[3]; @@ -348,7 +348,7 @@ typedef struct ATTR_PACKED{ } scsi_read_format_capacity_data_t; -VERIFY_STATIC( sizeof(scsi_read_format_capacity_data_t) == 12, "size is not correct"); +TU_VERIFY_STATIC( sizeof(scsi_read_format_capacity_data_t) == 12, "size is not correct"); //--------------------------------------------------------------------+ // SCSI Block Command (SBC-3) @@ -366,7 +366,7 @@ typedef struct ATTR_PACKED uint8_t control ; } scsi_read_capacity10_t; -VERIFY_STATIC(sizeof(scsi_read_capacity10_t) == 10, "size is not correct"); +TU_VERIFY_STATIC(sizeof(scsi_read_capacity10_t) == 10, "size is not correct"); /// SCSI Read Capacity 10 Response Data typedef struct { @@ -374,7 +374,7 @@ typedef struct { uint32_t block_size ; ///< Block size in bytes } scsi_read_capacity10_resp_t; -VERIFY_STATIC(sizeof(scsi_read_capacity10_resp_t) == 8, "size is not correct"); +TU_VERIFY_STATIC(sizeof(scsi_read_capacity10_resp_t) == 8, "size is not correct"); /// SCSI Read 10 Command typedef struct ATTR_PACKED @@ -387,8 +387,8 @@ typedef struct ATTR_PACKED uint8_t control ; } scsi_read10_t, scsi_write10_t; -VERIFY_STATIC(sizeof(scsi_read10_t) == 10, "size is not correct"); -VERIFY_STATIC(sizeof(scsi_write10_t) == 10, "size is not correct"); +TU_VERIFY_STATIC(sizeof(scsi_read10_t) == 10, "size is not correct"); +TU_VERIFY_STATIC(sizeof(scsi_write10_t) == 10, "size is not correct"); #ifdef __cplusplus } diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index 27762805c..a11212c4b 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -152,7 +152,7 @@ void mscd_reset(uint8_t rhport) tusb_error_t mscd_open(uint8_t rhport, tusb_desc_interface_t const * p_desc_itf, uint16_t *p_len) { // only support SCSI's BOT protocol - VERIFY( ( MSC_SUBCLASS_SCSI == p_desc_itf->bInterfaceSubClass && + TU_VERIFY( ( MSC_SUBCLASS_SCSI == p_desc_itf->bInterfaceSubClass && MSC_PROTOCOL_BOT == p_desc_itf->bInterfaceProtocol ), TUSB_ERROR_MSC_UNSUPPORTED_PROTOCOL ); mscd_interface_t * p_msc = &_mscd_itf; diff --git a/src/class/msc/msc_device.h b/src/class/msc/msc_device.h index 6080b10df..8403dfed9 100644 --- a/src/class/msc/msc_device.h +++ b/src/class/msc/msc_device.h @@ -47,7 +47,7 @@ //--------------------------------------------------------------------+ // Class Driver Configuration //--------------------------------------------------------------------+ -VERIFY_STATIC(CFG_TUD_MSC_BUFSIZE < UINT16_MAX, "Size is not correct"); +TU_VERIFY_STATIC(CFG_TUD_MSC_BUFSIZE < UINT16_MAX, "Size is not correct"); #ifndef CFG_TUD_MSC_MAXLUN #define CFG_TUD_MSC_MAXLUN 1 diff --git a/src/common/tusb_compiler.h b/src/common/tusb_compiler.h index 35a4cc928..09cc59633 100644 --- a/src/common/tusb_compiler.h +++ b/src/common/tusb_compiler.h @@ -56,12 +56,12 @@ #endif //--------------------------------------------------------------------+ -// Compile-time Assert (use VERIFY_STATIC to avoid name conflict) +// Compile-time Assert (use TU_VERIFY_STATIC to avoid name conflict) //--------------------------------------------------------------------+ #if defined(__ICCARM__) || (__STDC_VERSION__ >= 201112L ) - #define VERIFY_STATIC static_assert + #define TU_VERIFY_STATIC static_assert #else - #define VERIFY_STATIC(const_expr, _mess) enum { XSTRING_CONCAT_(_verify_static_, _TU_COUNTER_) = 1/(!!(const_expr)) } + #define TU_VERIFY_STATIC(const_expr, _mess) enum { XSTRING_CONCAT_(_verify_static_, _TU_COUNTER_) = 1/(!!(const_expr)) } #endif // allow debugger to watch any module-wide variables anywhere diff --git a/src/common/tusb_types.h b/src/common/tusb_types.h index 1e8a5ef27..c3ed4f2bd 100644 --- a/src/common/tusb_types.h +++ b/src/common/tusb_types.h @@ -369,7 +369,7 @@ typedef struct ATTR_PACKED{ uint16_t wLength; } tusb_control_request_t; -VERIFY_STATIC( sizeof(tusb_control_request_t) == 8, "mostly compiler option issue"); +TU_VERIFY_STATIC( sizeof(tusb_control_request_t) == 8, "mostly compiler option issue"); // TODO move to somewhere suitable static inline uint8_t bm_request_type(uint8_t direction, uint8_t type, uint8_t recipient) diff --git a/src/common/tusb_verify.h b/src/common/tusb_verify.h index adcdfc97f..41c2b5be1 100644 --- a/src/common/tusb_verify.h +++ b/src/common/tusb_verify.h @@ -50,8 +50,8 @@ * * e.g * - * - VERIFY( cond ) will return false if cond is false - * - VERIFY( cond, err) will return err instead if cond is false + * - TU_VERIFY( cond ) will return false if cond is false + * - TU_VERIFY( cond, err) will return err instead if cond is false *------------------------------------------------------------------*/ #ifdef __cplusplus @@ -60,7 +60,7 @@ //--------------------------------------------------------------------+ -// VERIFY Helper +// TU_VERIFY Helper //--------------------------------------------------------------------+ #if CFG_TUSB_DEBUG >= 1 #include @@ -88,21 +88,21 @@ /* Macro Generator *------------------------------------------------------------------*/ -// Helper to implement optional parameter for VERIFY Macro family +// Helper to implement optional parameter for TU_VERIFY Macro family #define GET_3RD_ARG(arg1, arg2, arg3, ...) arg3 #define GET_4TH_ARG(arg1, arg2, arg3, arg4, ...) arg4 -/*------------- Generator for VERIFY and VERIFY_HDLR -------------*/ -#define VERIFY_DEFINE(_cond, _handler, _ret) do { if ( !(_cond) ) { _handler; return _ret; } } while(0) +/*------------- Generator for TU_VERIFY and TU_VERIFY_HDLR -------------*/ +#define TU_VERIFY_DEFINE(_cond, _handler, _ret) do { if ( !(_cond) ) { _handler; return _ret; } } while(0) -/*------------- Generator for VERIFY_ERR and VERIFY_ERR_HDLR -------------*/ -#define VERIFY_ERR_DEF2(_error, _handler) \ +/*------------- Generator for TU_VERIFY_ERR and TU_VERIFY_ERR_HDLR -------------*/ +#define TU_VERIFY_ERR_DEF2(_error, _handler) \ do { \ uint32_t _err = (uint32_t)(_error); \ if ( 0 != _err ) { _MESS_ERR(_err); _handler; return _err; }\ } while(0) -#define VERIFY_ERR_DEF3(_error, _handler, _ret) \ +#define TU_VERIFY_ERR_DEF3(_error, _handler, _ret) \ do { \ uint32_t _err = (uint32_t)(_error); \ if ( 0 != _err ) { _MESS_ERR(_err); _handler; return _ret; }\ @@ -112,66 +112,66 @@ /*------------------------------------------------------------------*/ -/* VERIFY - * - VERIFY_1ARGS : return false if failed - * - VERIFY_2ARGS : return provided value if failed +/* TU_VERIFY + * - TU_VERIFY_1ARGS : return false if failed + * - TU_VERIFY_2ARGS : return provided value if failed *------------------------------------------------------------------*/ -#define VERIFY_1ARGS(_cond) VERIFY_DEFINE(_cond, , false) -#define VERIFY_2ARGS(_cond, _ret) VERIFY_DEFINE(_cond, , _ret) +#define TU_VERIFY_1ARGS(_cond) TU_VERIFY_DEFINE(_cond, , false) +#define TU_VERIFY_2ARGS(_cond, _ret) TU_VERIFY_DEFINE(_cond, , _ret) -#define VERIFY(...) GET_3RD_ARG(__VA_ARGS__, VERIFY_2ARGS, VERIFY_1ARGS)(__VA_ARGS__) +#define TU_VERIFY(...) GET_3RD_ARG(__VA_ARGS__, TU_VERIFY_2ARGS, TU_VERIFY_1ARGS)(__VA_ARGS__) /*------------------------------------------------------------------*/ -/* VERIFY WITH HANDLER - * - VERIFY_HDLR_2ARGS : execute handler, return false if failed - * - VERIFY_HDLR_3ARGS : execute handler, return provided error if failed +/* TU_VERIFY WITH HANDLER + * - TU_VERIFY_HDLR_2ARGS : execute handler, return false if failed + * - TU_VERIFY_HDLR_3ARGS : execute handler, return provided error if failed *------------------------------------------------------------------*/ -#define VERIFY_HDLR_2ARGS(_cond, _handler) VERIFY_DEFINE(_cond, _handler, false) -#define VERIFY_HDLR_3ARGS(_cond, _handler, _ret) VERIFY_DEFINE(_cond, _handler, _ret) +#define TU_VERIFY_HDLR_2ARGS(_cond, _handler) TU_VERIFY_DEFINE(_cond, _handler, false) +#define TU_VERIFY_HDLR_3ARGS(_cond, _handler, _ret) TU_VERIFY_DEFINE(_cond, _handler, _ret) -#define VERIFY_HDLR(...) GET_4TH_ARG(__VA_ARGS__, VERIFY_HDLR_3ARGS, VERIFY_HDLR_2ARGS)(__VA_ARGS__) +#define TU_VERIFY_HDLR(...) GET_4TH_ARG(__VA_ARGS__, TU_VERIFY_HDLR_3ARGS, TU_VERIFY_HDLR_2ARGS)(__VA_ARGS__) /*------------------------------------------------------------------*/ -/* VERIFY STATUS - * - VERIFY_ERR_1ARGS : return status of condition if failed - * - VERIFY_ERR_2ARGS : return provided status code if failed +/* TU_VERIFY STATUS + * - TU_VERIFY_ERR_1ARGS : return status of condition if failed + * - TU_VERIFY_ERR_2ARGS : return provided status code if failed *------------------------------------------------------------------*/ -#define VERIFY_ERR_1ARGS(_error) VERIFY_ERR_DEF2(_error, ) -#define VERIFY_ERR_2ARGS(_error, _ret) VERIFY_ERR_DEF3(_error, ,_ret) +#define TU_VERIFY_ERR_1ARGS(_error) TU_VERIFY_ERR_DEF2(_error, ) +#define TU_VERIFY_ERR_2ARGS(_error, _ret) TU_VERIFY_ERR_DEF3(_error, ,_ret) -#define VERIFY_ERR(...) GET_3RD_ARG(__VA_ARGS__, VERIFY_ERR_2ARGS, VERIFY_ERR_1ARGS)(__VA_ARGS__) +#define TU_VERIFY_ERR(...) GET_3RD_ARG(__VA_ARGS__, TU_VERIFY_ERR_2ARGS, TU_VERIFY_ERR_1ARGS)(__VA_ARGS__) /*------------------------------------------------------------------*/ -/* VERIFY STATUS WITH HANDLER - * - VERIFY_ERR_HDLR_2ARGS : execute handler, return status if failed - * - VERIFY_ERR_HDLR_3ARGS : execute handler, return provided error if failed +/* TU_VERIFY STATUS WITH HANDLER + * - TU_VERIFY_ERR_HDLR_2ARGS : execute handler, return status if failed + * - TU_VERIFY_ERR_HDLR_3ARGS : execute handler, return provided error if failed *------------------------------------------------------------------*/ -#define VERIFY_ERR_HDLR_2ARGS(_error, _handler) VERIFY_ERR_DEF2(_error, _handler) -#define VERIFY_ERR_HDLR_3ARGS(_error, _handler, _ret) VERIFY_ERR_DEF3(_error, _handler, _ret) +#define TU_VERIFY_ERR_HDLR_2ARGS(_error, _handler) TU_VERIFY_ERR_DEF2(_error, _handler) +#define TU_VERIFY_ERR_HDLR_3ARGS(_error, _handler, _ret) TU_VERIFY_ERR_DEF3(_error, _handler, _ret) -#define VERIFY_ERR_HDLR(...) GET_4TH_ARG(__VA_ARGS__, VERIFY_ERR_HDLR_3ARGS, VERIFY_ERR_HDLR_2ARGS)(__VA_ARGS__) +#define TU_VERIFY_ERR_HDLR(...) GET_4TH_ARG(__VA_ARGS__, TU_VERIFY_ERR_HDLR_3ARGS, TU_VERIFY_ERR_HDLR_2ARGS)(__VA_ARGS__) /*------------------------------------------------------------------*/ /* ASSERT - * basically VERIFY with verify_breakpoint() as handler + * basically TU_VERIFY with verify_breakpoint() as handler * - 1 arg : return false if failed * - 2 arg : return error if failed *------------------------------------------------------------------*/ -#define ASSERT_1ARGS(_cond) VERIFY_DEFINE(_cond, _MESS_FAILED(); verify_breakpoint(), false) -#define ASSERT_2ARGS(_cond, _ret) VERIFY_DEFINE(_cond, _MESS_FAILED(); verify_breakpoint(), _ret) +#define ASSERT_1ARGS(_cond) TU_VERIFY_DEFINE(_cond, _MESS_FAILED(); verify_breakpoint(), false) +#define ASSERT_2ARGS(_cond, _ret) TU_VERIFY_DEFINE(_cond, _MESS_FAILED(); verify_breakpoint(), _ret) #define TU_ASSERT(...) GET_3RD_ARG(__VA_ARGS__, ASSERT_2ARGS, ASSERT_1ARGS)(__VA_ARGS__) /*------------------------------------------------------------------*/ /* ASSERT Error - * basically VERIFY Error with verify_breakpoint() as handler + * basically TU_VERIFY Error with verify_breakpoint() as handler *------------------------------------------------------------------*/ -#define ASERT_ERR_1ARGS(_error) VERIFY_ERR_DEF2(_error, verify_breakpoint()) -#define ASERT_ERR_2ARGS(_error, _ret) VERIFY_ERR_DEF3(_error, verify_breakpoint(), _ret) +#define ASERT_ERR_1ARGS(_error) TU_VERIFY_ERR_DEF2(_error, verify_breakpoint()) +#define ASERT_ERR_2ARGS(_error, _ret) TU_VERIFY_ERR_DEF3(_error, verify_breakpoint(), _ret) #define TU_ASSERT_ERR(...) GET_3RD_ARG(__VA_ARGS__, ASERT_ERR_2ARGS, ASERT_ERR_1ARGS)(__VA_ARGS__) diff --git a/src/device/usbd.c b/src/device/usbd.c index 219562fa6..79ad8ffa2 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -189,7 +189,7 @@ typedef struct ATTR_ALIGNED(4) }; } usbd_task_event_t; -VERIFY_STATIC(sizeof(usbd_task_event_t) <= 12, "size is not correct"); +TU_VERIFY_STATIC(sizeof(usbd_task_event_t) <= 12, "size is not correct"); OSAL_TASK_DEF(_usbd_task_def, "usbd", usbd_task, CFG_TUD_TASK_PRIO, CFG_TUD_TASK_STACK_SZ); @@ -234,10 +234,10 @@ tusb_error_t usbd_init (void) //------------- Task init -------------// _usbd_q = osal_queue_create(&_usbd_qdef); - VERIFY(_usbd_q, TUSB_ERROR_OSAL_QUEUE_FAILED); + TU_VERIFY(_usbd_q, TUSB_ERROR_OSAL_QUEUE_FAILED); _usbd_ctrl_sem = osal_semaphore_create(&_usbd_sem_def); - VERIFY(_usbd_q, TUSB_ERROR_OSAL_SEMAPHORE_FAILED); + TU_VERIFY(_usbd_q, TUSB_ERROR_OSAL_SEMAPHORE_FAILED); osal_task_create(&_usbd_task_def); @@ -507,7 +507,7 @@ static uint16_t get_descriptor(uint8_t rhport, tusb_control_request_t const * co if ( desc_index < tud_desc_set.string_count ) { desc_data = tud_desc_set.string_arr[desc_index]; - VERIFY( desc_data != NULL, 0 ); + TU_VERIFY( desc_data != NULL, 0 ); len = desc_data[0]; // first byte of descriptor is its size }else diff --git a/src/host/ehci/ehci.c b/src/host/ehci/ehci.c index 09f2f573a..32fcc8140 100644 --- a/src/host/ehci/ehci.c +++ b/src/host/ehci/ehci.c @@ -64,7 +64,7 @@ CFG_TUSB_ATTR_USBRAM STATIC_VAR ehci_data_t ehci_data; CFG_TUSB_ATTR_USBRAM ATTR_ALIGNED(4096) STATIC_VAR ehci_link_t period_frame_list0[EHCI_FRAMELIST_SIZE]; #ifndef __ICCARM__ // IAR cannot able to determine the alignment with datalignment pragma - VERIFY_STATIC( ALIGN_OF(period_frame_list0) == 4096, "Period Framelist must be 4k alginment"); // validation + TU_VERIFY_STATIC( ALIGN_OF(period_frame_list0) == 4096, "Period Framelist must be 4k alginment"); // validation #endif #endif @@ -72,7 +72,7 @@ CFG_TUSB_ATTR_USBRAM STATIC_VAR ehci_data_t ehci_data; CFG_TUSB_ATTR_USBRAM ATTR_ALIGNED(4096) STATIC_VAR ehci_link_t period_frame_list1[EHCI_FRAMELIST_SIZE]; #ifndef __ICCARM__ // IAR cannot able to determine the alignment with datalignment pragma - VERIFY_STATIC( ALIGN_OF(period_frame_list1) == 4096, "Period Framelist must be 4k alginment"); // validation + TU_VERIFY_STATIC( ALIGN_OF(period_frame_list1) == 4096, "Period Framelist must be 4k alginment"); // validation #endif #endif #endif diff --git a/src/host/ehci/ehci.h b/src/host/ehci/ehci.h index 250023ee5..f5180402b 100644 --- a/src/host/ehci/ehci.h +++ b/src/host/ehci/ehci.h @@ -81,7 +81,7 @@ enum { }; //------------- Validation -------------// -VERIFY_STATIC(EHCI_CFG_FRAMELIST_SIZE_BITS <= 7, "incorrect value"); +TU_VERIFY_STATIC(EHCI_CFG_FRAMELIST_SIZE_BITS <= 7, "incorrect value"); //--------------------------------------------------------------------+ // EHCI Data Structure @@ -150,7 +150,7 @@ typedef struct { uint32_t buffer[5]; } ehci_qtd_t; // XXX qtd is used to declare overlay in ehci_qhd_t -> cannot be declared with ATTR_ALIGNED(32) -VERIFY_STATIC( sizeof(ehci_qtd_t) == 32, "size is not correct" ); +TU_VERIFY_STATIC( sizeof(ehci_qtd_t) == 32, "size is not correct" ); /// Queue Head (section 3.6) typedef struct ATTR_ALIGNED(32) { @@ -202,7 +202,7 @@ typedef struct ATTR_ALIGNED(32) { ehci_qtd_t * volatile p_qtd_list_tail; // tail of the scheduled TD list } ehci_qhd_t; -VERIFY_STATIC( sizeof(ehci_qhd_t) == 64, "size is not correct" ); +TU_VERIFY_STATIC( sizeof(ehci_qhd_t) == 64, "size is not correct" ); /// Highspeed Isochronous Transfer Descriptor (section 3.3) typedef struct ATTR_ALIGNED(32) { @@ -234,7 +234,7 @@ typedef struct ATTR_ALIGNED(32) { // uint32_t reserved[6]; } ehci_itd_t; -VERIFY_STATIC( sizeof(ehci_itd_t) == 64, "size is not correct" ); +TU_VERIFY_STATIC( sizeof(ehci_itd_t) == 64, "size is not correct" ); /// Split (Full-Speed) Isochronous Transfer Descriptor typedef struct ATTR_ALIGNED(32) { @@ -298,7 +298,7 @@ typedef struct ATTR_ALIGNED(32) { uint8_t reserved2[2]; } ehci_sitd_t; -VERIFY_STATIC( sizeof(ehci_sitd_t) == 32, "size is not correct" ); +TU_VERIFY_STATIC( sizeof(ehci_sitd_t) == 32, "size is not correct" ); //--------------------------------------------------------------------+ // EHCI Operational Register diff --git a/src/host/hub.h b/src/host/hub.h index b8499275c..67c02f2e3 100644 --- a/src/host/hub.h +++ b/src/host/hub.h @@ -104,7 +104,7 @@ typedef struct ATTR_PACKED{ uint8_t PortPwrCtrlMask; // just for compatibility, should be 0xff } descriptor_hub_desc_t; -VERIFY_STATIC( sizeof(descriptor_hub_desc_t) == 9, "size is not correct"); +TU_VERIFY_STATIC( sizeof(descriptor_hub_desc_t) == 9, "size is not correct"); enum { HUB_REQUEST_GET_STATUS = 0 , @@ -157,7 +157,7 @@ typedef struct { } status, status_change; } hub_status_response_t; -VERIFY_STATIC( sizeof(hub_status_response_t) == 4, "size is not correct"); +TU_VERIFY_STATIC( sizeof(hub_status_response_t) == 4, "size is not correct"); // data in response of HUB_REQUEST_GET_STATUS, wIndex = Port num typedef struct { @@ -182,7 +182,7 @@ typedef struct { } status_current, status_change; } hub_port_status_response_t; -VERIFY_STATIC( sizeof(hub_port_status_response_t) == 4, "size is not correct"); +TU_VERIFY_STATIC( sizeof(hub_port_status_response_t) == 4, "size is not correct"); tusb_error_t hub_port_reset_subtask(uint8_t hub_addr, uint8_t hub_port); tusb_error_t hub_port_clear_feature_subtask(uint8_t hub_addr, uint8_t hub_port, uint8_t feature); diff --git a/src/host/ohci/ohci.h b/src/host/ohci/ohci.h index f49d85261..c407b8ac1 100644 --- a/src/host/ohci/ohci.h +++ b/src/host/ohci/ohci.h @@ -79,7 +79,7 @@ typedef struct { uint8_t reserved[116+4]; // TODO try to make use of this area if possible, extra 4 byte to make the whole struct size = 256 }ohci_hcca_t; // ATTR_ALIGNED(256) -VERIFY_STATIC( sizeof(ohci_hcca_t) == 256, "size is not correct" ); +TU_VERIFY_STATIC( sizeof(ohci_hcca_t) == 256, "size is not correct" ); typedef struct { uint32_t reserved[2]; @@ -112,7 +112,7 @@ typedef struct ATTR_ALIGNED(16) { uint8_t* buffer_end; } ohci_gtd_t; -VERIFY_STATIC( sizeof(ohci_gtd_t) == 16, "size is not correct" ); +TU_VERIFY_STATIC( sizeof(ohci_gtd_t) == 16, "size is not correct" ); typedef struct ATTR_ALIGNED(16) { //------------- Word 0 -------------// @@ -153,7 +153,7 @@ typedef struct ATTR_ALIGNED(16) { uint32_t next_ed; // 4 lsb bits are free to use } ohci_ed_t; -VERIFY_STATIC( sizeof(ohci_ed_t) == 16, "size is not correct" ); +TU_VERIFY_STATIC( sizeof(ohci_ed_t) == 16, "size is not correct" ); typedef struct ATTR_ALIGNED(32) { /*---------- Word 1 ----------*/ @@ -178,7 +178,7 @@ typedef struct ATTR_ALIGNED(32) { volatile uint16_t offset_packetstatus[8]; } ochi_itd_t; -VERIFY_STATIC( sizeof(ochi_itd_t) == 32, "size is not correct" ); +TU_VERIFY_STATIC( sizeof(ochi_itd_t) == 32, "size is not correct" ); // structure with member alignment required from large to small typedef struct ATTR_ALIGNED(256) { @@ -298,7 +298,7 @@ typedef volatile struct }; }ohci_registers_t; -VERIFY_STATIC( sizeof(ohci_registers_t) == 0x5c, "size is not correct"); +TU_VERIFY_STATIC( sizeof(ohci_registers_t) == 0x5c, "size is not correct"); #ifdef __cplusplus } diff --git a/src/osal/osal.h b/src/osal/osal.h index 7a8e6ecbf..3e0d9d5f1 100644 --- a/src/osal/osal.h +++ b/src/osal/osal.h @@ -81,11 +81,11 @@ typedef void (*osal_task_func_t)( void * ); #define STASK_INVOKE(_subtask, _status) (_status) = _subtask //------------- Sub Task Assert -------------// - #define STASK_ASSERT_ERR(_err) VERIFY_ERR(_err) - #define STASK_ASSERT_ERR_HDLR(_err, _func) VERIFY_ERR_HDLR(_err, _func) + #define STASK_ASSERT_ERR(_err) TU_VERIFY_ERR(_err) + #define STASK_ASSERT_ERR_HDLR(_err, _func) TU_VERIFY_ERR_HDLR(_err, _func) - #define STASK_ASSERT(_cond) VERIFY(_cond, TUSB_ERROR_OSAL_TASK_FAILED) - #define STASK_ASSERT_HDLR(_cond, _func) VERIFY_HDLR(_cond, _func) + #define STASK_ASSERT(_cond) TU_VERIFY(_cond, TUSB_ERROR_OSAL_TASK_FAILED) + #define STASK_ASSERT_HDLR(_cond, _func) TU_VERIFY_HDLR(_cond, _func) #endif #ifdef __cplusplus diff --git a/src/osal/osal_none.h b/src/osal/osal_none.h index b8cd2893c..3531686b4 100644 --- a/src/osal/osal_none.h +++ b/src/osal/osal_none.h @@ -121,11 +121,11 @@ static inline osal_task_t osal_task_create(osal_task_def_t* taskdef) //------------- Sub Task Assert -------------// #define STASK_RETURN(error) do { TASK_RESTART; return error; } while(0) -#define STASK_ASSERT_ERR(_err) VERIFY_ERR_HDLR(_err, verify_breakpoint(); TASK_RESTART, TUSB_ERROR_FAILED) -#define STASK_ASSERT_ERR_HDLR(_err, _func) VERIFY_ERR_HDLR(_err, verify_breakpoint(); _func; TASK_RESTART, TUSB_ERROR_FAILED ) +#define STASK_ASSERT_ERR(_err) TU_VERIFY_ERR_HDLR(_err, verify_breakpoint(); TASK_RESTART, TUSB_ERROR_FAILED) +#define STASK_ASSERT_ERR_HDLR(_err, _func) TU_VERIFY_ERR_HDLR(_err, verify_breakpoint(); _func; TASK_RESTART, TUSB_ERROR_FAILED ) -#define STASK_ASSERT(_cond) VERIFY_HDLR(_cond, verify_breakpoint(); TASK_RESTART, TUSB_ERROR_FAILED) -#define STASK_ASSERT_HDLR(_cond, _func) VERIFY_HDLR(_cond, verify_breakpoint(); _func; TASK_RESTART, TUSB_ERROR_FAILED) +#define STASK_ASSERT(_cond) TU_VERIFY_HDLR(_cond, verify_breakpoint(); TASK_RESTART, TUSB_ERROR_FAILED) +#define STASK_ASSERT_HDLR(_cond, _func) TU_VERIFY_HDLR(_cond, verify_breakpoint(); _func; TASK_RESTART, TUSB_ERROR_FAILED) //--------------------------------------------------------------------+ // QUEUE API diff --git a/src/portable/nxp/lpc11xx_lpc13xx/dcd_lpc_11uxx_13uxx.c b/src/portable/nxp/lpc11xx_lpc13xx/dcd_lpc_11uxx_13uxx.c index 68eef47e1..0eaecf1b8 100644 --- a/src/portable/nxp/lpc11xx_lpc13xx/dcd_lpc_11uxx_13uxx.c +++ b/src/portable/nxp/lpc11xx_lpc13xx/dcd_lpc_11uxx_13uxx.c @@ -104,7 +104,7 @@ typedef struct ATTR_PACKED volatile uint16_t active : 1 ; ///< The buffer is enabled. HW can use the buffer to store received OUT data or to transmit data on the IN endpoint. Software can only set this bit to ‘1’. As long as this bit is set to one, software is not allowed to update any of the values in this 32-bit word. In case software wants to deactivate the buffer, it must write a one to the corresponding “skip” bit in the USB Endpoint skip register. Hardware can only write this bit to zero. It will do this when it receives a short packet or when the NBytes field transitions to zero or when software has written a one to the “skip” bit. }dcd_11u_13u_qhd_t; -VERIFY_STATIC( sizeof(dcd_11u_13u_qhd_t) == 4, "size is not correct" ); +TU_VERIFY_STATIC( sizeof(dcd_11u_13u_qhd_t) == 4, "size is not correct" ); // NOTE data will be transferred as soon as dcd get request by dcd_pipe(_queue)_xfer using double buffering. // If there is another dcd_edpt_xfer request, the new request will be saved and executed when the first is done. diff --git a/src/portable/nxp/lpc17xx/dcd_lpc175x_6x.c b/src/portable/nxp/lpc17xx/dcd_lpc175x_6x.c index 948572129..a87e7d899 100644 --- a/src/portable/nxp/lpc17xx/dcd_lpc175x_6x.c +++ b/src/portable/nxp/lpc17xx/dcd_lpc175x_6x.c @@ -384,7 +384,7 @@ bool dcd_control_xfer(uint8_t rhport, tusb_dir_t dir, uint8_t * p_buffer, uint16 { (void) rhport; - VERIFY( !(length != 0 && p_buffer == NULL) ); + TU_VERIFY( !(length != 0 && p_buffer == NULL) ); // determine Endpoint where Data & Status phase occurred (IN or OUT) uint8_t const ep_data = (dir == TUSB_DIR_IN) ? 1 : 0; @@ -399,13 +399,13 @@ bool dcd_control_xfer(uint8_t rhport, tusb_dir_t dir, uint8_t * p_buffer, uint16 dcd_data.control_dma.remaining_bytes = length; // lpc17xx already received the first DATA OUT packet by now - VERIFY_ERR ( pipe_control_xfer(ep_data, p_buffer, length), false ); + TU_VERIFY_ERR ( pipe_control_xfer(ep_data, p_buffer, length), false ); } //------------- Status Phase (opposite direct to Data) -------------// if (dir == TUSB_DIR_OUT) { // only write for CONTROL OUT, CONTROL IN data will be retrieved in hal_dcd_isr // TODO ???? - VERIFY_ERR ( pipe_control_write(NULL, 0), false ); + TU_VERIFY_ERR ( pipe_control_write(NULL, 0), false ); } return true; diff --git a/src/portable/nxp/lpc17xx/dcd_lpc175x_6x.h b/src/portable/nxp/lpc17xx/dcd_lpc175x_6x.h index 1df1fcd30..4746b4acf 100644 --- a/src/portable/nxp/lpc17xx/dcd_lpc175x_6x.h +++ b/src/portable/nxp/lpc17xx/dcd_lpc175x_6x.h @@ -80,7 +80,7 @@ typedef struct ATTR_ALIGNED(4) // uint32_t iso_packet_size_addr; // iso only, can be omitted for non-iso }dcd_dma_descriptor_t; -VERIFY_STATIC( sizeof(dcd_dma_descriptor_t) == 16, "size is not correct"); // TODO not support ISO for now +TU_VERIFY_STATIC( sizeof(dcd_dma_descriptor_t) == 16, "size is not correct"); // TODO not support ISO for now //--------------------------------------------------------------------+ diff --git a/src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c b/src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c index 0b48ad1e6..61f829713 100644 --- a/src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c +++ b/src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c @@ -244,7 +244,7 @@ bool dcd_control_xfer(uint8_t rhport, tusb_dir_t dir, uint8_t * p_buffer, uint16 // wait until ENDPTSETUPSTAT before priming data/status in response TODO add time out while(lpc_usb->ENDPTSETUPSTAT & BIT_(0)) {} - VERIFY( !qhd->qtd_overlay.active ); + TU_VERIFY( !qhd->qtd_overlay.active ); dcd_qtd_t* qtd = &p_dcd->qtd[0]; qtd_init(qtd, p_buffer, length); @@ -295,7 +295,7 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc) { // TODO USB1 only has 4 non-control enpoint (USB0 has 5) // TODO not support ISO yet - VERIFY ( p_endpoint_desc->bmAttributes.xfer != TUSB_XFER_ISOCHRONOUS); + TU_VERIFY ( p_endpoint_desc->bmAttributes.xfer != TUSB_XFER_ISOCHRONOUS); tusb_dir_t dir = (p_endpoint_desc->bEndpointAddress & TUSB_DIR_IN_MASK) ? TUSB_DIR_IN : TUSB_DIR_OUT; @@ -313,7 +313,7 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc) volatile uint32_t * reg_control = get_reg_control_addr(rhport, ep_idx); // endpoint must not be already enabled - VERIFY( !( (*reg_control) & (ENDPTCTRL_MASK_ENABLE << (dir ? 16 : 0)) ) ); + TU_VERIFY( !( (*reg_control) & (ENDPTCTRL_MASK_ENABLE << (dir ? 16 : 0)) ) ); (*reg_control) |= ((p_endpoint_desc->bmAttributes.xfer << 2) | ENDPTCTRL_MASK_ENABLE | ENDPTCTRL_MASK_TOGGLE_RESET) << (dir ? 16 : 0); @@ -363,7 +363,7 @@ bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t { uint8_t ep_idx = edpt_addr2phy(ep_addr); - VERIFY ( pipe_add_xfer(rhport, ep_idx, buffer, total_bytes, true) ); + TU_VERIFY ( pipe_add_xfer(rhport, ep_idx, buffer, total_bytes, true) ); dcd_qhd_t* p_qhd = &dcd_data_ptr[rhport]->qhd[ ep_idx ]; dcd_qtd_t* p_qtd = &dcd_data_ptr[rhport]->qtd[ p_qhd->list_qtd_idx[0] ]; diff --git a/src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.h b/src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.h index 92e24c1fb..1476c0d30 100644 --- a/src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.h +++ b/src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.h @@ -122,7 +122,7 @@ typedef struct uint8_t reserved; } dcd_qtd_t; -VERIFY_STATIC( sizeof(dcd_qtd_t) == 32, "size is not correct"); +TU_VERIFY_STATIC( sizeof(dcd_qtd_t) == 32, "size is not correct"); typedef struct { @@ -153,7 +153,7 @@ typedef struct uint8_t reserved[16-DCD_QTD_PER_QHD_MAX]; } dcd_qhd_t; -VERIFY_STATIC( sizeof(dcd_qhd_t) == 64, "size is not correct"); +TU_VERIFY_STATIC( sizeof(dcd_qhd_t) == 64, "size is not correct"); #ifdef __cplusplus diff --git a/src/portable/nxp/lpc43xx_lpc18xx/hal_lpc43xx.c b/src/portable/nxp/lpc43xx_lpc18xx/hal_lpc43xx.c index 18745d03e..213b8dd99 100644 --- a/src/portable/nxp/lpc43xx_lpc18xx/hal_lpc43xx.c +++ b/src/portable/nxp/lpc43xx_lpc18xx/hal_lpc43xx.c @@ -86,7 +86,7 @@ bool tusb_hal_init(void) //------------- USB0 -------------// #if CFG_TUSB_RHPORT0_MODE CGU_EnableEntity(CGU_CLKSRC_PLL0, DISABLE); /* Disable PLL first */ - VERIFY( CGU_ERROR_SUCCESS == CGU_SetPLL0()); /* the usb core require output clock = 480MHz */ + TU_VERIFY( CGU_ERROR_SUCCESS == CGU_SetPLL0()); /* the usb core require output clock = 480MHz */ CGU_EntityConnect(CGU_CLKSRC_XTAL_OSC, CGU_CLKSRC_PLL0); CGU_EnableEntity(CGU_CLKSRC_PLL0, ENABLE); /* Enable PLL after all setting is done */ diff --git a/src/tusb.c b/src/tusb.c index 0ef1301a4..b064d03f9 100644 --- a/src/tusb.c +++ b/src/tusb.c @@ -49,7 +49,7 @@ tusb_error_t tusb_init(void) // skip if already initialized if (_initialized) return TUSB_ERROR_NONE; - VERIFY( tusb_hal_init(), TUSB_ERROR_FAILED ) ; // hardware init + TU_VERIFY( tusb_hal_init(), TUSB_ERROR_FAILED ) ; // hardware init #if MODE_HOST_SUPPORTED TU_ASSERT_ERR( usbh_init() ); // host stack init -- cgit v1.3.1 From d996bd529591c98f366ddedbde63ac21755996e2 Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 15 Aug 2018 17:57:33 +0700 Subject: correct cdc line coding memory align --- src/class/cdc/cdc_device.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src/class') diff --git a/src/class/cdc/cdc_device.c b/src/class/cdc/cdc_device.c index 175e78d2f..075a7f8db 100644 --- a/src/class/cdc/cdc_device.c +++ b/src/class/cdc/cdc_device.c @@ -62,8 +62,8 @@ typedef struct uint8_t line_state; /*------------- From this point, data is not cleared by bus reset -------------*/ - cdc_line_coding_t line_coding; char wanted_char; + CFG_TUSB_MEM_ALIGN cdc_line_coding_t line_coding; // FIFO tu_fifo_t rx_ff; @@ -78,7 +78,7 @@ typedef struct }cdcd_interface_t; -#define ITF_BUS_RESET_SZ offsetof(cdcd_interface_t, line_coding) +#define ITF_BUS_RESET_SZ offsetof(cdcd_interface_t, wanted_char) //--------------------------------------------------------------------+ // INTERNAL OBJECT & FUNCTION DECLARATION -- cgit v1.3.1 From c5d2f661e76adbe2f047c2f3a405ed60262ecb9b Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 23 Aug 2018 20:09:28 +0700 Subject: rename common func to avoid conflict --- src/class/cdc/cdc_device.c | 4 +- src/class/cdc/cdc_host.c | 2 +- src/class/hid/hid_device.c | 14 ++--- src/class/msc/msc_device.c | 4 +- src/common/tusb_common.h | 64 +++++++--------------- src/common/tusb_fifo.c | 6 +- src/device/usbd.c | 16 +++--- src/host/ehci/ehci.c | 28 +++++----- src/host/ohci/ohci.c | 24 ++++---- src/host/usbh.c | 2 +- src/portable/nordic/nrf5x/dcd_nrf5x.c | 4 +- .../nxp/lpc11xx_lpc13xx/dcd_lpc_11uxx_13uxx.c | 2 +- src/portable/nxp/lpc17xx/dcd_lpc175x_6x.c | 4 +- src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c | 2 +- tests/lpc18xx_43xx/test/host/ehci/test_ehci_init.c | 4 +- .../test/host/ehci/test_pipe_bulk_open.c | 8 +-- .../test/host/ehci/test_pipe_bulk_xfer.c | 4 +- .../test/host/ehci/test_pipe_control_open.c | 6 +- .../test/host/ehci/test_pipe_interrupt_open.c | 24 ++++---- .../test/host/ehci/test_pipe_interrupt_xfer.c | 4 +- tests/support/ehci_controller_fake.c | 12 ++-- tests/support/type_helper.h | 6 +- 22 files changed, 109 insertions(+), 135 deletions(-) (limited to 'src/class') diff --git a/src/class/cdc/cdc_device.c b/src/class/cdc/cdc_device.c index 075a7f8db..2a598f051 100644 --- a/src/class/cdc/cdc_device.c +++ b/src/class/cdc/cdc_device.c @@ -208,7 +208,7 @@ tusb_error_t cdcd_open(uint8_t rhport, tusb_desc_interface_t const * p_interface { if ( CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL != p_interface_desc->bInterfaceSubClass) return TUSB_ERROR_CDC_UNSUPPORTED_SUBCLASS; - if ( !(is_in_range(CDC_COMM_PROTOCOL_ATCOMMAND, p_interface_desc->bInterfaceProtocol, CDC_COMM_PROTOCOL_ATCOMMAND_CDMA) || + if ( !(tu_within(CDC_COMM_PROTOCOL_ATCOMMAND, p_interface_desc->bInterfaceProtocol, CDC_COMM_PROTOCOL_ATCOMMAND_CDMA) || 0xff == p_interface_desc->bInterfaceProtocol) ) { return TUSB_ERROR_CDC_UNSUPPORTED_PROTOCOL; @@ -282,7 +282,7 @@ tusb_error_t cdcd_control_request_st(uint8_t rhport, tusb_control_request_t cons if ( (CDC_REQUEST_GET_LINE_CODING == p_request->bRequest) || (CDC_REQUEST_SET_LINE_CODING == p_request->bRequest) ) { - uint16_t len = min16_of(sizeof(cdc_line_coding_t), p_request->wLength); + uint16_t len = tu_min16(sizeof(cdc_line_coding_t), p_request->wLength); usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, &p_cdc->line_coding, len); // Invoke callback diff --git a/src/class/cdc/cdc_host.c b/src/class/cdc/cdc_host.c index 6950759d1..ca448ba5e 100644 --- a/src/class/cdc/cdc_host.c +++ b/src/class/cdc/cdc_host.c @@ -149,7 +149,7 @@ tusb_error_t cdch_open_subtask(uint8_t dev_addr, tusb_desc_interface_t const *p_ if ( CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL != p_interface_desc->bInterfaceSubClass) return TUSB_ERROR_CDC_UNSUPPORTED_SUBCLASS; - if ( !(is_in_range(CDC_COMM_PROTOCOL_ATCOMMAND, p_interface_desc->bInterfaceProtocol, CDC_COMM_PROTOCOL_ATCOMMAND_CDMA) || + if ( !(tu_within(CDC_COMM_PROTOCOL_ATCOMMAND, p_interface_desc->bInterfaceProtocol, CDC_COMM_PROTOCOL_ATCOMMAND_CDMA) || 0xff == p_interface_desc->bInterfaceProtocol) ) { return TUSB_ERROR_CDC_UNSUPPORTED_PROTOCOL; diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index 410359e6d..b1cd1d1bd 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -412,8 +412,8 @@ tusb_error_t hidd_control_request_st(uint8_t rhport, tusb_control_request_t cons //------------- STD Request -------------// if (p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD) { - uint8_t const desc_type = u16_high_u8(p_request->wValue); - uint8_t const desc_index = u16_low_u8 (p_request->wValue); + uint8_t const desc_type = tu_u16_high(p_request->wValue); + uint8_t const desc_index = tu_u16_low (p_request->wValue); (void) desc_index; if (p_request->bRequest == TUSB_REQ_GET_DESCRIPTOR && desc_type == HID_DESC_TYPE_REPORT) @@ -434,8 +434,8 @@ tusb_error_t hidd_control_request_st(uint8_t rhport, tusb_control_request_t cons if( HID_REQ_CONTROL_GET_REPORT == p_request->bRequest ) { // wValue = Report Type | Report ID - uint8_t const report_type = u16_high_u8(p_request->wValue); - uint8_t const report_id = u16_low_u8(p_request->wValue); + uint8_t const report_type = tu_u16_high(p_request->wValue); + uint8_t const report_id = tu_u16_low(p_request->wValue); uint16_t xferlen; if ( p_hid->get_report_cb ) @@ -455,8 +455,8 @@ tusb_error_t hidd_control_request_st(uint8_t rhport, tusb_control_request_t cons usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, _usbd_ctrl_buf, p_request->wLength); // wValue = Report Type | Report ID - uint8_t const report_type = u16_high_u8(p_request->wValue); - uint8_t const report_id = u16_low_u8(p_request->wValue); + uint8_t const report_type = tu_u16_high(p_request->wValue); + uint8_t const report_id = tu_u16_low(p_request->wValue); if ( p_hid->set_report_cb ) { @@ -466,7 +466,7 @@ tusb_error_t hidd_control_request_st(uint8_t rhport, tusb_control_request_t cons else if (HID_REQ_CONTROL_SET_IDLE == p_request->bRequest) { // TODO idle rate of report - p_hid->idle_rate = u16_high_u8(p_request->wValue); + p_hid->idle_rate = tu_u16_high(p_request->wValue); dcd_control_status(rhport, p_request->bmRequestType_bit.direction); } else if (HID_REQ_CONTROL_GET_IDLE == p_request->bRequest) diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index a11212c4b..3335ad9b3 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -531,7 +531,7 @@ static void proc_read10_cmd(uint8_t rhport, mscd_interface_t* p_msc) uint32_t const lba = rdwr10_get_lba(p_cbw->command) + (p_msc->xferred_len / block_sz); // remaining bytes capped at class buffer - int32_t nbytes = (int32_t) min32_of(sizeof(_mscd_buf), p_cbw->xfer_bytes-p_msc->xferred_len); + int32_t nbytes = (int32_t) tu_min32(sizeof(_mscd_buf), p_cbw->xfer_bytes-p_msc->xferred_len); // Application can consume smaller bytes nbytes = tud_msc_read10_cb(p_cbw->lun, lba, p_msc->xferred_len % block_sz, _mscd_buf, (uint32_t) nbytes); @@ -561,7 +561,7 @@ static void proc_write10_cmd(uint8_t rhport, mscd_interface_t* p_msc) msc_cbw_t const * p_cbw = &p_msc->cbw; // remaining bytes capped at class buffer - int32_t nbytes = (int32_t) min32_of(sizeof(_mscd_buf), p_cbw->xfer_bytes-p_msc->xferred_len); + int32_t nbytes = (int32_t) tu_min32(sizeof(_mscd_buf), p_cbw->xfer_bytes-p_msc->xferred_len); // Write10 callback will be called later when usb transfer complete TU_ASSERT( dcd_edpt_xfer(rhport, p_msc->ep_out, _mscd_buf, nbytes), ); diff --git a/src/common/tusb_common.h b/src/common/tusb_common.h index e8baa9de4..778e70676 100644 --- a/src/common/tusb_common.h +++ b/src/common/tusb_common.h @@ -151,119 +151,94 @@ static inline bool mem_all_zero(void const* buffer, uint32_t size) //------------- Conversion -------------// -/// form an uint32_t from 4 x uint8_t -static inline uint32_t u32_from_u8(uint8_t b1, uint8_t b2, uint8_t b3, uint8_t b4) ATTR_ALWAYS_INLINE ATTR_CONST; -static inline uint32_t u32_from_u8(uint8_t b1, uint8_t b2, uint8_t b3, uint8_t b4) +static inline uint32_t tu_u32_from_u8(uint8_t b1, uint8_t b2, uint8_t b3, uint8_t b4) { return ( ((uint32_t) b1) << 24) + ( ((uint32_t) b2) << 16) + ( ((uint32_t) b3) << 8) + b4; } -static inline uint8_t u16_high_u8(uint16_t u16) ATTR_CONST ATTR_ALWAYS_INLINE; -static inline uint8_t u16_high_u8(uint16_t u16) +static inline uint8_t tu_u16_high(uint16_t u16) { return (uint8_t) ( ((uint16_t) (u16 >> 8)) & 0x00ff); } -static inline uint8_t u16_low_u8(uint16_t u16) ATTR_CONST ATTR_ALWAYS_INLINE; -static inline uint8_t u16_low_u8(uint16_t u16) +static inline uint8_t tu_u16_low(uint16_t u16) { return (uint8_t) (u16 & 0x00ff); } -static inline uint16_t u16_le2be(uint16_t u16) ATTR_CONST ATTR_ALWAYS_INLINE; -static inline uint16_t u16_le2be(uint16_t u16) +static inline uint16_t tu_u16_le2be(uint16_t u16) { - return ((uint16_t)(u16_low_u8(u16) << 8)) | u16_high_u8(u16); + return ((uint16_t)(tu_u16_low(u16) << 8)) | tu_u16_high(u16); } //------------- Min -------------// -static inline uint8_t min8_of(uint8_t x, uint8_t y) ATTR_ALWAYS_INLINE ATTR_CONST; -static inline uint8_t min8_of(uint8_t x, uint8_t y) +static inline uint8_t tu_min8(uint8_t x, uint8_t y) { return (x < y) ? x : y; } -static inline uint16_t min16_of(uint16_t x, uint16_t y) ATTR_ALWAYS_INLINE ATTR_CONST; -static inline uint16_t min16_of(uint16_t x, uint16_t y) +static inline uint16_t tu_min16(uint16_t x, uint16_t y) { return (x < y) ? x : y; } -static inline uint32_t min32_of(uint32_t x, uint32_t y) ATTR_ALWAYS_INLINE ATTR_CONST; -static inline uint32_t min32_of(uint32_t x, uint32_t y) +static inline uint32_t tu_min32(uint32_t x, uint32_t y) { return (x < y) ? x : y; } //------------- Max -------------// -static inline uint32_t max32_of(uint32_t x, uint32_t y) ATTR_ALWAYS_INLINE ATTR_CONST; -static inline uint32_t max32_of(uint32_t x, uint32_t y) +static inline uint32_t tu_max32(uint32_t x, uint32_t y) { return (x > y) ? x : y; } -static inline uint16_t max16_of(uint16_t x, uint16_t y) ATTR_ALWAYS_INLINE ATTR_CONST; -static inline uint16_t max16_of(uint16_t x, uint16_t y) +static inline uint16_t tu_max16(uint16_t x, uint16_t y) { return (x > y) ? x : y; } //------------- Align -------------// -static inline uint32_t align32 (uint32_t value) ATTR_ALWAYS_INLINE ATTR_CONST; -static inline uint32_t align32 (uint32_t value) +static inline uint32_t tu_align32 (uint32_t value) { return (value & 0xFFFFFFE0UL); } -static inline uint32_t align16 (uint32_t value) ATTR_ALWAYS_INLINE ATTR_CONST; -static inline uint32_t align16 (uint32_t value) +static inline uint32_t tu_align16 (uint32_t value) { return (value & 0xFFFFFFF0UL); } -static inline uint32_t align_n (uint32_t alignment, uint32_t value) ATTR_ALWAYS_INLINE ATTR_CONST; -static inline uint32_t align_n (uint32_t alignment, uint32_t value) +static inline uint32_t tu_align_n (uint32_t alignment, uint32_t value) { return value & ((uint32_t) ~(alignment-1)); } -static inline uint32_t align4k (uint32_t value) ATTR_ALWAYS_INLINE ATTR_CONST; -static inline uint32_t align4k (uint32_t value) +static inline uint32_t tu_align4k (uint32_t value) { return (value & 0xFFFFF000UL); } -static inline uint32_t offset4k(uint32_t value) ATTR_ALWAYS_INLINE ATTR_CONST; -static inline uint32_t offset4k(uint32_t value) +static inline uint32_t tu_offset4k(uint32_t value) { return (value & 0xFFFUL); } //------------- Mathematics -------------// -static inline uint32_t abs_of(int32_t value) ATTR_ALWAYS_INLINE ATTR_CONST; -static inline uint32_t abs_of(int32_t value) +static inline uint32_t tu_abs(int32_t value) { return (value < 0) ? (-value) : value; } /// inclusive range checking -static inline bool is_in_range(uint32_t lower, uint32_t value, uint32_t upper) ATTR_ALWAYS_INLINE ATTR_CONST; -static inline bool is_in_range(uint32_t lower, uint32_t value, uint32_t upper) +static inline bool tu_within(uint32_t lower, uint32_t value, uint32_t upper) { return (lower <= value) && (value <= upper); } -/// exclusive range checking -static inline bool is_in_range_exclusive(uint32_t lower, uint32_t value, uint32_t upper) ATTR_ALWAYS_INLINE ATTR_CONST; -static inline bool is_in_range_exclusive(uint32_t lower, uint32_t value, uint32_t upper) -{ - return (lower < value) && (value < upper); -} - // TODO use clz -static inline uint8_t log2_of(uint32_t value) ATTR_ALWAYS_INLINE ATTR_CONST; -static inline uint8_t log2_of(uint32_t value) +static inline uint8_t tu_log2(uint32_t value) { uint8_t result = 0; // log2 of a value is its MSB's position @@ -275,8 +250,7 @@ static inline uint8_t log2_of(uint32_t value) } // return the number of set bits in value -static inline uint8_t cardinality_of(uint32_t value) ATTR_ALWAYS_INLINE ATTR_CONST; -static inline uint8_t cardinality_of(uint32_t value) +static inline uint8_t tu_cardof(uint32_t value) { // Brian Kernighan's method goes through as many iterations as there are set bits. So if we have a 32-bit word with only // the high bit set, then it will only go once through the loop diff --git a/src/common/tusb_fifo.c b/src/common/tusb_fifo.c index 09763bee0..e90264f8b 100644 --- a/src/common/tusb_fifo.c +++ b/src/common/tusb_fifo.c @@ -54,7 +54,7 @@ #endif -static inline uint16_t min16_of(uint16_t x, uint16_t y) +static inline uint16_t tu_min16(uint16_t x, uint16_t y) { return (x < y) ? x : y; } @@ -136,7 +136,7 @@ uint16_t tu_fifo_read_n (tu_fifo_t* f, void * p_buffer, uint16_t count) if( tu_fifo_empty(f) ) return 0; /* Limit up to fifo's count */ - count = min16_of(count, f->count); + count = tu_min16(count, f->count); if( count == 0 ) return 0; mutex_lock_if_needed(f); @@ -145,7 +145,7 @@ uint16_t tu_fifo_read_n (tu_fifo_t* f, void * p_buffer, uint16_t count) * case 1: ....RxxxxW....... * case 2: xxxxxW....Rxxxxxx */ -// uint16_t index2upper = min16_of(count, f->count-f->rd_idx); +// uint16_t index2upper = tu_min16(count, f->count-f->rd_idx); uint8_t* p_buf = (uint8_t*) p_buffer; uint16_t len = 0; diff --git a/src/device/usbd.c b/src/device/usbd.c index 79ad8ffa2..ea5e24884 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -377,9 +377,9 @@ static tusb_error_t proc_control_request_st(uint8_t rhport, tusb_control_request //------------- Class/Interface Specific Request -------------// else if ( TUSB_REQ_RCPT_INTERFACE == p_request->bmRequestType_bit.recipient ) { - if (_usbd_dev.itf2drv[ u16_low_u8(p_request->wIndex) ] < USBD_CLASS_DRIVER_COUNT) + if (_usbd_dev.itf2drv[ tu_u16_low(p_request->wIndex) ] < USBD_CLASS_DRIVER_COUNT) { - STASK_INVOKE( usbd_class_drivers[ _usbd_dev.itf2drv[ u16_low_u8(p_request->wIndex) ] ].control_req_st(rhport, p_request), error ); + STASK_INVOKE( usbd_class_drivers[ _usbd_dev.itf2drv[ tu_u16_low(p_request->wIndex) ] ].control_req_st(rhport, p_request), error ); }else { dcd_control_stall(rhport); // Stall unsupported request @@ -392,7 +392,7 @@ static tusb_error_t proc_control_request_st(uint8_t rhport, tusb_control_request { if (TUSB_REQ_GET_STATUS == p_request->bRequest ) { - uint16_t status = dcd_edpt_stalled(rhport, u16_low_u8(p_request->wIndex)) ? 0x0001 : 0x0000; + uint16_t status = dcd_edpt_stalled(rhport, tu_u16_low(p_request->wIndex)) ? 0x0001 : 0x0000; memcpy(_usbd_ctrl_buf, &status, 2); usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, _usbd_ctrl_buf, 2); @@ -400,13 +400,13 @@ static tusb_error_t proc_control_request_st(uint8_t rhport, tusb_control_request else if (TUSB_REQ_CLEAR_FEATURE == p_request->bRequest ) { // only endpoint feature is halted/stalled - dcd_edpt_clear_stall(rhport, u16_low_u8(p_request->wIndex)); + dcd_edpt_clear_stall(rhport, tu_u16_low(p_request->wIndex)); dcd_control_status(rhport, p_request->bmRequestType_bit.direction); } else if (TUSB_REQ_SET_FEATURE == p_request->bRequest ) { // only endpoint feature is halted/stalled - dcd_edpt_stall(rhport, u16_low_u8(p_request->wIndex)); + dcd_edpt_stall(rhport, tu_u16_low(p_request->wIndex)); dcd_control_status(rhport, p_request->bmRequestType_bit.direction); } else @@ -484,8 +484,8 @@ static uint16_t get_descriptor(uint8_t rhport, tusb_control_request_t const * co { (void) rhport; - tusb_desc_type_t const desc_type = (tusb_desc_type_t) u16_high_u8(p_request->wValue); - uint8_t const desc_index = u16_low_u8( p_request->wValue ); + tusb_desc_type_t const desc_type = (tusb_desc_type_t) tu_u16_high(p_request->wValue); + uint8_t const desc_index = tu_u16_low( p_request->wValue ); uint8_t const * desc_data = NULL ; uint16_t len = 0; @@ -532,7 +532,7 @@ static uint16_t get_descriptor(uint8_t rhport, tusb_control_request_t const * co TU_ASSERT( desc_data != NULL, 0); // up to Host's length - len = min16_of(p_request->wLength, len ); + len = tu_min16(p_request->wLength, len ); (*pp_buffer) = desc_data; return len; diff --git a/src/host/ehci/ehci.c b/src/host/ehci/ehci.c index 32fcc8140..84821e3f5 100644 --- a/src/host/ehci/ehci.c +++ b/src/host/ehci/ehci.c @@ -604,14 +604,14 @@ static void period_list_xfer_complete_isr(uint8_t hostid, uint8_t interval_ms) // TODO abstract max loop guard for period while( !next_item.terminate && - !(interval_ms > 1 && period_1ms_addr == align32(next_item.address)) && + !(interval_ms > 1 && period_1ms_addr == tu_align32(next_item.address)) && max_loop < (HCD_MAX_ENDPOINT + EHCI_MAX_ITD + EHCI_MAX_SITD)*CFG_TUSB_HOST_DEVICE_MAX) { switch ( next_item.type ) { case EHCI_QUEUE_ELEMENT_QHD: { - ehci_qhd_t *p_qhd_int = (ehci_qhd_t *) align32(next_item.address); + ehci_qhd_t *p_qhd_int = (ehci_qhd_t *) tu_align32(next_item.address); if ( !p_qhd_int->qtd_overlay.halted ) { qhd_xfer_complete_isr(p_qhd_int); @@ -653,7 +653,7 @@ static void qhd_xfer_error_isr(ehci_qhd_t * p_qhd) if ( TUSB_XFER_CONTROL == xfer_type ) { - p_qhd->total_xferred_bytes -= min8_of(8, p_qhd->total_xferred_bytes); // subtract setup size + p_qhd->total_xferred_bytes -= tu_min8(8, p_qhd->total_xferred_bytes); // subtract setup size // control cannot be halted --> clear all qtd list p_qhd->p_qtd_list_head = NULL; @@ -702,14 +702,14 @@ static void xfer_error_isr(uint8_t hostid) // TODO abstract max loop guard for period while( !next_item.terminate && - !(interval_ms > 1 && period_1ms_addr == align32(next_item.address)) && + !(interval_ms > 1 && period_1ms_addr == tu_align32(next_item.address)) && period_max_loop < (HCD_MAX_ENDPOINT + EHCI_MAX_ITD + EHCI_MAX_SITD)*CFG_TUSB_HOST_DEVICE_MAX) { switch ( next_item.type ) { case EHCI_QUEUE_ELEMENT_QHD: { - ehci_qhd_t *p_qhd_int = (ehci_qhd_t *) align32(next_item.address); + ehci_qhd_t *p_qhd_int = (ehci_qhd_t *) tu_align32(next_item.address); qhd_xfer_error_isr(p_qhd_int); } break; @@ -828,7 +828,7 @@ static inline ehci_qhd_t* get_async_head(uint8_t hostid) static inline ehci_link_t* get_period_head(uint8_t hostid, uint8_t interval_ms) { return (ehci_link_t*) (&ehci_data.period_head_arr[ hostid_to_data_idx(hostid) ] - [ log2_of( min8_of(EHCI_FRAMELIST_SIZE, interval_ms) ) ] ); + [ tu_log2( tu_min8(EHCI_FRAMELIST_SIZE, interval_ms) ) ] ); } #endif @@ -869,7 +869,7 @@ static inline tusb_xfer_type_t qhd_get_xfer_type(ehci_qhd_t const * p_qhd) static inline ehci_qhd_t* qhd_next(ehci_qhd_t const * p_qhd) { - return (ehci_qhd_t*) align32(p_qhd->next.address); + return (ehci_qhd_t*) tu_align32(p_qhd->next.address); } static inline ehci_qhd_t* qhd_get_from_pipe_handle(pipe_handle_t pipe_hdl) @@ -907,7 +907,7 @@ static inline ehci_qtd_t* qtd_find_free(uint8_t dev_addr) static inline ehci_qtd_t* qtd_next(ehci_qtd_t const * p_qtd ) { - return (ehci_qtd_t*) align32(p_qtd->next.address); + return (ehci_qtd_t*) tu_align32(p_qtd->next.address); } static inline void qtd_remove_1st_from_qhd(ehci_qhd_t *p_qhd) @@ -965,7 +965,7 @@ static void qhd_init(ehci_qhd_t *p_qhd, uint8_t dev_addr, uint16_t max_packet_si (interval == 2) ? BIN8(10101010) : BIN8(01000100); }else { - p_qhd->interval_ms = (uint8_t) min16_of( 1 << (interval-4), 255 ); + p_qhd->interval_ms = (uint8_t) tu_min16( 1 << (interval-4), 255 ); p_qhd->interrupt_smask = BIT_(interval % 8); } }else @@ -1019,7 +1019,7 @@ static void qtd_init(ehci_qtd_t* p_qtd, uint32_t data_ptr, uint16_t total_bytes) p_qtd->buffer[0] = data_ptr; for(uint8_t i=1; i<5; i++) { - p_qtd->buffer[i] |= align4k( p_qtd->buffer[i-1] ) + 4096; + p_qtd->buffer[i] |= tu_align4k( p_qtd->buffer[i-1] ) + 4096; } } @@ -1032,15 +1032,15 @@ static inline void list_insert(ehci_link_t *current, ehci_link_t *new, uint8_t n static inline ehci_link_t* list_next(ehci_link_t *p_link_pointer) { - return (ehci_link_t*) align32(p_link_pointer->address); + return (ehci_link_t*) tu_align32(p_link_pointer->address); } static ehci_link_t* list_find_previous_item(ehci_link_t* p_head, ehci_link_t* p_current) { ehci_link_t *p_prev = p_head; uint32_t max_loop = 0; - while( (align32(p_prev->address) != (uint32_t) p_head) && // not loop around - (align32(p_prev->address) != (uint32_t) p_current) && // not found yet + while( (tu_align32(p_prev->address) != (uint32_t) p_head) && // not loop around + (tu_align32(p_prev->address) != (uint32_t) p_current) && // not found yet !p_prev->terminate && // not advanceable max_loop < HCD_MAX_ENDPOINT) { @@ -1048,7 +1048,7 @@ static ehci_link_t* list_find_previous_item(ehci_link_t* p_head, ehci_link_t* p_ max_loop++; } - return (align32(p_prev->address) != (uint32_t) p_head) ? p_prev : NULL; + return (tu_align32(p_prev->address) != (uint32_t) p_head) ? p_prev : NULL; } static tusb_error_t list_remove_qhd(ehci_link_t* p_head, ehci_link_t* p_remove) diff --git a/src/host/ohci/ohci.c b/src/host/ohci/ohci.c index 644dbfa0f..1c9f3f293 100644 --- a/src/host/ohci/ohci.c +++ b/src/host/ohci/ohci.c @@ -389,15 +389,15 @@ static ohci_ed_t * ed_list_find_previous(ohci_ed_t const * p_head, ohci_ed_t con TU_ASSERT(p_prev, NULL); - while ( align16(p_prev->next_ed) != 0 && /* not reach null */ - align16(p_prev->next_ed) != (uint32_t) p_ed && /* not found yet */ + while ( tu_align16(p_prev->next_ed) != 0 && /* not reach null */ + tu_align16(p_prev->next_ed) != (uint32_t) p_ed && /* not found yet */ max_loop > 0) { - p_prev = (ohci_ed_t const *) align16(p_prev->next_ed); + p_prev = (ohci_ed_t const *) tu_align16(p_prev->next_ed); max_loop--; } - return ( align16(p_prev->next_ed) == (uint32_t) p_ed ) ? (ohci_ed_t*) p_prev : NULL; + return ( tu_align16(p_prev->next_ed) == (uint32_t) p_ed ) ? (ohci_ed_t*) p_prev : NULL; } static void ed_list_insert(ohci_ed_t * p_pre, ohci_ed_t * p_ed) @@ -410,7 +410,7 @@ static void ed_list_remove(ohci_ed_t * p_head, ohci_ed_t * p_ed) { ohci_ed_t * const p_prev = ed_list_find_previous(p_head, p_ed); - p_prev->next_ed = (p_prev->next_ed & 0x0fUL) | align16(p_ed->next_ed); + p_prev->next_ed = (p_prev->next_ed & 0x0fUL) | tu_align16(p_ed->next_ed); // point the removed ED's next pointer to list head to make sure HC can always safely move away from this ED p_ed->next_ed = (uint32_t) p_head; p_ed->used = 0; // free ED @@ -457,13 +457,13 @@ static ohci_gtd_t * gtd_find_free(uint8_t dev_addr) static void td_insert_to_ed(ohci_ed_t* p_ed, ohci_gtd_t * p_gtd) { // tail is always NULL - if ( align16(p_ed->td_head.address) == 0 ) + if ( tu_align16(p_ed->td_head.address) == 0 ) { // TD queue is empty --> head = TD p_ed->td_head.address |= (uint32_t) p_gtd; } else { // TODO currently only support queue up to 2 TD each endpoint at a time - ((ohci_gtd_t*) align16(p_ed->td_head.address))->next_td = (uint32_t) p_gtd; + ((ohci_gtd_t*) tu_align16(p_ed->td_head.address))->next_td = (uint32_t) p_gtd; } } @@ -520,7 +520,7 @@ tusb_error_t hcd_pipe_close(pipe_handle_t pipe_hdl) bool hcd_pipe_is_busy(pipe_handle_t pipe_hdl) { ohci_ed_t const * const p_ed = ed_from_pipe_handle(pipe_hdl); - return align16(p_ed->td_head.address) != align16(p_ed->td_tail.address); + return tu_align16(p_ed->td_head.address) != tu_align16(p_ed->td_tail.address); } bool hcd_pipe_is_error(pipe_handle_t pipe_hdl) @@ -601,8 +601,8 @@ static inline ohci_ed_t* gtd_get_ed(ohci_gtd_t const * const p_qtd) static inline uint32_t gtd_xfer_byte_left(uint32_t buffer_end, uint32_t current_buffer) ATTR_CONST ATTR_ALWAYS_INLINE; static inline uint32_t gtd_xfer_byte_left(uint32_t buffer_end, uint32_t current_buffer) { // 5.2.9 OHCI sample code - return (align4k(buffer_end ^ current_buffer) ? 0x1000 : 0) + - offset4k(buffer_end) - offset4k(current_buffer) + 1; + return (tu_align4k(buffer_end ^ current_buffer) ? 0x1000 : 0) + + tu_offset4k(buffer_end) - tu_offset4k(current_buffer) + 1; } static void done_queue_isr(uint8_t hostid) @@ -610,7 +610,7 @@ static void done_queue_isr(uint8_t hostid) uint8_t max_loop = (CFG_TUSB_HOST_DEVICE_MAX+1)*(HCD_MAX_XFER+OHCI_MAX_ITD); // done head is written in reversed order of completion --> need to reverse the done queue first - ohci_td_item_t* td_head = list_reverse ( (ohci_td_item_t*) align16(ohci_data.hcca.done_head) ); + ohci_td_item_t* td_head = list_reverse ( (ohci_td_item_t*) tu_align16(ohci_data.hcca.done_head) ); while( td_head != NULL && max_loop > 0) { @@ -637,7 +637,7 @@ static void done_queue_isr(uint8_t hostid) if ((event != TUSB_EVENT_XFER_COMPLETE)) { p_ed->td_tail.address &= 0x0Ful; - p_ed->td_tail.address |= align16(p_ed->td_head.address); // mark halted EP as empty queue + p_ed->td_tail.address |= tu_align16(p_ed->td_head.address); // mark halted EP as empty queue if ( event == TUSB_EVENT_XFER_STALLED ) p_ed->is_stalled = 1; } diff --git a/src/host/usbh.c b/src/host/usbh.c index 6d1cd37ad..8b858b2de 100644 --- a/src/host/usbh.c +++ b/src/host/usbh.c @@ -643,7 +643,7 @@ static inline uint8_t get_configure_number_for_device(tusb_desc_device_t* dev_de // invoke callback to ask user which configuration to select if (tuh_device_attached_cb) { - config_num = min8_of(1, tuh_device_attached_cb(dev_desc) ); + config_num = tu_min8(1, tuh_device_attached_cb(dev_desc) ); } return config_num; diff --git a/src/portable/nordic/nrf5x/dcd_nrf5x.c b/src/portable/nordic/nrf5x/dcd_nrf5x.c index 72cd8d0b1..1c91779a7 100644 --- a/src/portable/nordic/nrf5x/dcd_nrf5x.c +++ b/src/portable/nordic/nrf5x/dcd_nrf5x.c @@ -178,7 +178,7 @@ static void edpt_dma_end(void) static void xact_control_start(void) { // Each transaction is up to 64 bytes - uint8_t const xact_len = min16_of(_dcd.control.total_len-_dcd.control.actual_len, MAX_PACKET_SIZE); + uint8_t const xact_len = tu_min16(_dcd.control.total_len-_dcd.control.actual_len, MAX_PACKET_SIZE); if ( _dcd.control.dir == TUSB_DIR_OUT ) { @@ -274,7 +274,7 @@ static void xact_in_prepare(uint8_t epnum) nom_xfer_t* xfer = get_td(epnum, TUSB_DIR_IN); // Each transaction is up to Max Packet Size - uint8_t const xact_len = min16_of(xfer->total_len - xfer->actual_len, xfer->mps); + uint8_t const xact_len = tu_min16(xfer->total_len - xfer->actual_len, xfer->mps); NRF_USBD->EPIN[epnum].PTR = (uint32_t) xfer->buffer; NRF_USBD->EPIN[epnum].MAXCNT = xact_len; diff --git a/src/portable/nxp/lpc11xx_lpc13xx/dcd_lpc_11uxx_13uxx.c b/src/portable/nxp/lpc11xx_lpc13xx/dcd_lpc_11uxx_13uxx.c index 0eaecf1b8..3e536312a 100644 --- a/src/portable/nxp/lpc11xx_lpc13xx/dcd_lpc_11uxx_13uxx.c +++ b/src/portable/nxp/lpc11xx_lpc13xx/dcd_lpc_11uxx_13uxx.c @@ -497,7 +497,7 @@ bool dcd_edpt_busy(edpt_hdl_t edpt_hdl) static void queue_xfer_to_buffer(uint8_t ep_id, uint8_t buff_idx, uint16_t buff_addr_offset, uint16_t total_bytes) { - uint16_t const queued_bytes = min16_of(total_bytes, DCD_11U_13U_MAX_BYTE_PER_TD); + uint16_t const queued_bytes = tu_min16(total_bytes, DCD_11U_13U_MAX_BYTE_PER_TD); dcd_data.current_td[ep_id].queued_bytes_in_buff[buff_idx] = queued_bytes; dcd_data.current_td[ep_id].remaining_bytes -= queued_bytes; diff --git a/src/portable/nxp/lpc17xx/dcd_lpc175x_6x.c b/src/portable/nxp/lpc17xx/dcd_lpc175x_6x.c index a87e7d899..8c87984e8 100644 --- a/src/portable/nxp/lpc17xx/dcd_lpc175x_6x.c +++ b/src/portable/nxp/lpc17xx/dcd_lpc175x_6x.c @@ -312,7 +312,7 @@ static inline uint16_t length_byte2dword(uint16_t length_in_bytes) static tusb_error_t pipe_control_xfer(uint8_t ep_id, uint8_t* p_buffer, uint16_t length) { - uint16_t const packet_len = min16_of(length, CFG_TUD_ENDOINT0_SIZE); + uint16_t const packet_len = tu_min16(length, CFG_TUD_ENDOINT0_SIZE); if (ep_id) { @@ -355,7 +355,7 @@ static tusb_error_t pipe_control_read(void * buffer, uint16_t length) LPC_USB->USBCtrl = USBCTRL_READ_ENABLE_MASK; // logical endpoint = 0 while ((LPC_USB->USBRxPLen & USBRXPLEN_PACKET_READY_MASK) == 0) {} // TODO blocking, should have timeout - uint16_t actual_length = min16_of(length, (uint16_t) (LPC_USB->USBRxPLen & USBRXPLEN_PACKET_LENGTH_MASK) ); + uint16_t actual_length = tu_min16(length, (uint16_t) (LPC_USB->USBRxPLen & USBRXPLEN_PACKET_LENGTH_MASK) ); uint32_t *p_read_data = (uint32_t*) buffer; for( uint16_t count=0; count < length_byte2dword(actual_length); count++) { diff --git a/src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c b/src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c index 61f829713..792a009f2 100644 --- a/src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c +++ b/src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c @@ -209,7 +209,7 @@ static void qtd_init(dcd_qtd_t* p_qtd, void * data_ptr, uint16_t total_bytes) p_qtd->buffer[0] = (uint32_t) data_ptr; for(uint8_t i=1; i<5; i++) { - p_qtd->buffer[i] |= align4k( p_qtd->buffer[i-1] ) + 4096; + p_qtd->buffer[i] |= tu_align4k( p_qtd->buffer[i-1] ) + 4096; } } } diff --git a/tests/lpc18xx_43xx/test/host/ehci/test_ehci_init.c b/tests/lpc18xx_43xx/test/host/ehci/test_ehci_init.c index f31944338..69b7c1dd9 100644 --- a/tests/lpc18xx_43xx/test/host/ehci/test_ehci_init.c +++ b/tests/lpc18xx_43xx/test/host/ehci/test_ehci_init.c @@ -107,7 +107,7 @@ void test_hcd_init_async_list(void) TEST_ASSERT_EQUAL_HEX(async_head, regs->async_list_base); - TEST_ASSERT_EQUAL_HEX(async_head, align32( (uint32_t) async_head) ); + TEST_ASSERT_EQUAL_HEX(async_head, tu_align32( (uint32_t) async_head) ); TEST_ASSERT_EQUAL(EHCI_QUEUE_ELEMENT_QHD, async_head->next.type); TEST_ASSERT_FALSE(async_head->next.terminate); @@ -118,7 +118,7 @@ void test_hcd_init_async_list(void) void check_qhd_endpoint_link(ehci_link_t *p_prev, ehci_qhd_t *p_qhd) { //------------- period list check -------------// - TEST_ASSERT_EQUAL_HEX((uint32_t) p_qhd, align32(p_prev->address)); + TEST_ASSERT_EQUAL_HEX((uint32_t) p_qhd, tu_align32(p_prev->address)); TEST_ASSERT_FALSE(p_prev->terminate); TEST_ASSERT_EQUAL(EHCI_QUEUE_ELEMENT_QHD, p_prev->type); } diff --git a/tests/lpc18xx_43xx/test/host/ehci/test_pipe_bulk_open.c b/tests/lpc18xx_43xx/test/host/ehci/test_pipe_bulk_open.c index c2d52ce4c..a26b990d3 100644 --- a/tests/lpc18xx_43xx/test/host/ehci/test_pipe_bulk_open.c +++ b/tests/lpc18xx_43xx/test/host/ehci/test_pipe_bulk_open.c @@ -143,7 +143,7 @@ void verify_bulk_open_qhd(ehci_qhd_t *p_qhd, tusb_desc_endpoint_t const * desc_e TEST_ASSERT_EQUAL(class_code, p_qhd->class_code); //------------- async list check -------------// - TEST_ASSERT_EQUAL_HEX((uint32_t) p_qhd, align32(async_head->next.address)); + TEST_ASSERT_EQUAL_HEX((uint32_t) p_qhd, tu_align32(async_head->next.address)); TEST_ASSERT_FALSE(async_head->next.terminate); TEST_ASSERT_EQUAL(EHCI_QUEUE_ELEMENT_QHD, async_head->next.type); } @@ -164,7 +164,7 @@ void test_open_bulk_qhd_data(void) verify_bulk_open_qhd(p_qhd, desc_endpoint, TUSB_CLASS_MSC); //------------- async list check -------------// - TEST_ASSERT_EQUAL_HEX((uint32_t) p_qhd, align32(async_head->next.address)); + TEST_ASSERT_EQUAL_HEX((uint32_t) p_qhd, tu_align32(async_head->next.address)); TEST_ASSERT_FALSE(async_head->next.terminate); TEST_ASSERT_EQUAL(EHCI_QUEUE_ELEMENT_QHD, async_head->next.type); } @@ -194,7 +194,7 @@ void test_bulk_close(void) hcd_pipe_close(pipe_hdl); TEST_ASSERT(p_qhd->is_removing); - TEST_ASSERT( align32(async_head->next.address) != (uint32_t) p_qhd ); - TEST_ASSERT_EQUAL_HEX( (uint32_t) async_head, align32(p_qhd->next.address) ); + TEST_ASSERT( tu_align32(async_head->next.address) != (uint32_t) p_qhd ); + TEST_ASSERT_EQUAL_HEX( (uint32_t) async_head, tu_align32(p_qhd->next.address) ); TEST_ASSERT_EQUAL(EHCI_QUEUE_ELEMENT_QHD, p_qhd->next.type); } diff --git a/tests/lpc18xx_43xx/test/host/ehci/test_pipe_bulk_xfer.c b/tests/lpc18xx_43xx/test/host/ehci/test_pipe_bulk_xfer.c index e3d78f668..a52c721fe 100644 --- a/tests/lpc18xx_43xx/test/host/ehci/test_pipe_bulk_xfer.c +++ b/tests/lpc18xx_43xx/test/host/ehci/test_pipe_bulk_xfer.c @@ -140,7 +140,7 @@ void verify_qtd(ehci_qtd_t *p_qtd, uint8_t p_data[], uint16_t length) TEST_ASSERT_EQUAL_HEX( p_data, p_qtd->buffer[0] ); for(uint8_t i=1; i<5; i++) { - TEST_ASSERT_EQUAL_HEX( align4k((uint32_t) (p_data+4096*i)), align4k(p_qtd->buffer[i]) ); + TEST_ASSERT_EQUAL_HEX( tu_align4k((uint32_t) (p_data+4096*i)), tu_align4k(p_qtd->buffer[i]) ); } } @@ -193,7 +193,7 @@ void test_bulk_xfer_double(void) //------------- list tail -------------// TEST_ASSERT_NOT_NULL(p_tail); verify_qtd(p_tail, data2, sizeof(data2)); - TEST_ASSERT_EQUAL_HEX( align32(p_head->next.address), p_tail); + TEST_ASSERT_EQUAL_HEX( tu_align32(p_head->next.address), p_tail); TEST_ASSERT_EQUAL(EHCI_PID_IN, p_tail->pid); TEST_ASSERT_TRUE(p_tail->next.terminate); TEST_ASSERT_TRUE(p_tail->int_on_complete); diff --git a/tests/lpc18xx_43xx/test/host/ehci/test_pipe_control_open.c b/tests/lpc18xx_43xx/test/host/ehci/test_pipe_control_open.c index 1143b9faa..22cbf7569 100644 --- a/tests/lpc18xx_43xx/test/host/ehci/test_pipe_control_open.c +++ b/tests/lpc18xx_43xx/test/host/ehci/test_pipe_control_open.c @@ -142,7 +142,7 @@ void test_control_open_qhd_data(void) TEST_ASSERT_FALSE(p_control_qhd->head_list_flag); //------------- async list check -------------// - TEST_ASSERT_EQUAL_HEX((uint32_t) p_control_qhd, align32(async_head->next.address)); + TEST_ASSERT_EQUAL_HEX((uint32_t) p_control_qhd, tu_align32(async_head->next.address)); TEST_ASSERT_FALSE(async_head->next.terminate); TEST_ASSERT_EQUAL(EHCI_QUEUE_ELEMENT_QHD, async_head->next.type); } @@ -191,6 +191,6 @@ void test_control_close(void) TEST_ASSERT(p_control_qhd->is_removing); TEST_ASSERT(p_control_qhd->used); - TEST_ASSERT( align32(get_async_head(hostid)->next.address) != (uint32_t) p_control_qhd ); - TEST_ASSERT_EQUAL( get_async_head(hostid), align32(p_control_qhd->next.address)); + TEST_ASSERT( tu_align32(get_async_head(hostid)->next.address) != (uint32_t) p_control_qhd ); + TEST_ASSERT_EQUAL( get_async_head(hostid), tu_align32(p_control_qhd->next.address)); } diff --git a/tests/lpc18xx_43xx/test/host/ehci/test_pipe_interrupt_open.c b/tests/lpc18xx_43xx/test/host/ehci/test_pipe_interrupt_open.c index 1f8fc9a12..f39021ef2 100644 --- a/tests/lpc18xx_43xx/test/host/ehci/test_pipe_interrupt_open.c +++ b/tests/lpc18xx_43xx/test/host/ehci/test_pipe_interrupt_open.c @@ -136,7 +136,7 @@ void verify_int_qhd(ehci_qhd_t *p_qhd, tusb_desc_endpoint_t const * desc_endpoin void check_int_endpoint_link(ehci_qhd_t *p_prev, ehci_qhd_t *p_qhd) { //------------- period list check -------------// - TEST_ASSERT_EQUAL_HEX((uint32_t) p_qhd, align32(p_prev->next.address)); + TEST_ASSERT_EQUAL_HEX((uint32_t) p_qhd, tu_align32(p_prev->next.address)); TEST_ASSERT_FALSE(p_prev->next.terminate); TEST_ASSERT_EQUAL(EHCI_QUEUE_ELEMENT_QHD, p_prev->next.type); } @@ -181,7 +181,7 @@ void test_open_interrupt_hs_interval_2(void) p_int_qhd = &ehci_data.device[ pipe_hdl.dev_addr-1].qhd[ pipe_hdl.index ]; TEST_ASSERT_EQUAL(0 , p_int_qhd->interval_ms); - TEST_ASSERT_EQUAL(4 , cardinality_of(p_int_qhd->interrupt_smask)); // either 10101010 or 01010101 + TEST_ASSERT_EQUAL(4 , tu_cardof(p_int_qhd->interrupt_smask)); // either 10101010 or 01010101 check_int_endpoint_link(period_head_arr, p_int_qhd); } @@ -195,7 +195,7 @@ void test_open_interrupt_hs_interval_3(void) p_int_qhd = &ehci_data.device[ pipe_hdl.dev_addr-1].qhd[ pipe_hdl.index ]; TEST_ASSERT_EQUAL(0, p_int_qhd->interval_ms); - TEST_ASSERT_EQUAL(2, cardinality_of(p_int_qhd->interrupt_smask) ); + TEST_ASSERT_EQUAL(2, tu_cardof(p_int_qhd->interrupt_smask) ); check_int_endpoint_link(period_head_arr, p_int_qhd); } @@ -209,7 +209,7 @@ void test_open_interrupt_hs_interval_4(void) p_int_qhd = &ehci_data.device[ pipe_hdl.dev_addr-1].qhd[ pipe_hdl.index ]; TEST_ASSERT_EQUAL(1, p_int_qhd->interval_ms); - TEST_ASSERT_EQUAL(1, cardinality_of(p_int_qhd->interrupt_smask) ); + TEST_ASSERT_EQUAL(1, tu_cardof(p_int_qhd->interrupt_smask) ); check_int_endpoint_link(period_head_arr, p_int_qhd); } @@ -223,7 +223,7 @@ void test_open_interrupt_hs_interval_5(void) p_int_qhd = &ehci_data.device[ pipe_hdl.dev_addr-1].qhd[ pipe_hdl.index ]; TEST_ASSERT_EQUAL(2, p_int_qhd->interval_ms); - TEST_ASSERT_EQUAL(1, cardinality_of(p_int_qhd->interrupt_smask) ); + TEST_ASSERT_EQUAL(1, tu_cardof(p_int_qhd->interrupt_smask) ); check_int_endpoint_link( get_period_head(hostid, 2), p_int_qhd ); } @@ -237,7 +237,7 @@ void test_open_interrupt_hs_interval_6(void) p_int_qhd = &ehci_data.device[ pipe_hdl.dev_addr-1].qhd[ pipe_hdl.index ]; TEST_ASSERT_EQUAL(4, p_int_qhd->interval_ms); - TEST_ASSERT_EQUAL(1, cardinality_of(p_int_qhd->interrupt_smask) ); + TEST_ASSERT_EQUAL(1, tu_cardof(p_int_qhd->interrupt_smask) ); check_int_endpoint_link( get_period_head(hostid, 4), p_int_qhd); } @@ -251,7 +251,7 @@ void test_open_interrupt_hs_interval_7(void) p_int_qhd = &ehci_data.device[ pipe_hdl.dev_addr-1].qhd[ pipe_hdl.index ]; TEST_ASSERT_EQUAL(8, p_int_qhd->interval_ms); - TEST_ASSERT_EQUAL(1, cardinality_of(p_int_qhd->interrupt_smask) ); + TEST_ASSERT_EQUAL(1, tu_cardof(p_int_qhd->interrupt_smask) ); check_int_endpoint_link( get_period_head(hostid, 8), p_int_qhd); } @@ -265,7 +265,7 @@ void test_open_interrupt_hs_interval_8(void) p_int_qhd = &ehci_data.device[ pipe_hdl.dev_addr-1].qhd[ pipe_hdl.index ]; TEST_ASSERT_EQUAL(255, p_int_qhd->interval_ms); - TEST_ASSERT_EQUAL(1, cardinality_of(p_int_qhd->interrupt_smask) ); + TEST_ASSERT_EQUAL(1, tu_cardof(p_int_qhd->interrupt_smask) ); check_int_endpoint_link( get_period_head(hostid, 255), p_int_qhd); check_int_endpoint_link( get_period_head(hostid, 8) , p_int_qhd); } @@ -318,8 +318,8 @@ void test_interrupt_close(void) hcd_pipe_close(pipe_hdl) ); TEST_ASSERT(p_int_qhd->is_removing); - TEST_ASSERT( align32(period_head_arr->next.address) != (uint32_t) p_int_qhd ); - TEST_ASSERT_EQUAL_HEX( (uint32_t) period_head_arr, align32(p_int_qhd->next.address ) ); + TEST_ASSERT( tu_align32(period_head_arr->next.address) != (uint32_t) p_int_qhd ); + TEST_ASSERT_EQUAL_HEX( (uint32_t) period_head_arr, tu_align32(p_int_qhd->next.address ) ); TEST_ASSERT_EQUAL(EHCI_QUEUE_ELEMENT_QHD, p_int_qhd->next.type); } @@ -336,7 +336,7 @@ void test_interrupt_256ms_close(void) hcd_pipe_close(pipe_hdl) ); TEST_ASSERT(p_int_qhd->is_removing); - TEST_ASSERT( align32(get_period_head(hostid, 8)->address) != (uint32_t) p_int_qhd ); - TEST_ASSERT_EQUAL_HEX( (uint32_t) get_period_head(hostid, 8), align32(p_int_qhd->next.address ) ); + TEST_ASSERT( tu_align32(get_period_head(hostid, 8)->address) != (uint32_t) p_int_qhd ); + TEST_ASSERT_EQUAL_HEX( (uint32_t) get_period_head(hostid, 8), tu_align32(p_int_qhd->next.address ) ); TEST_ASSERT_EQUAL(EHCI_QUEUE_ELEMENT_QHD, p_int_qhd->next.type); } diff --git a/tests/lpc18xx_43xx/test/host/ehci/test_pipe_interrupt_xfer.c b/tests/lpc18xx_43xx/test/host/ehci/test_pipe_interrupt_xfer.c index cacc1e98c..aeb094932 100644 --- a/tests/lpc18xx_43xx/test/host/ehci/test_pipe_interrupt_xfer.c +++ b/tests/lpc18xx_43xx/test/host/ehci/test_pipe_interrupt_xfer.c @@ -142,7 +142,7 @@ void verify_qtd(ehci_qtd_t *p_qtd, uint8_t p_data[], uint16_t length) TEST_ASSERT_EQUAL_HEX( p_data, p_qtd->buffer[0] ); for(uint8_t i=1; i<5; i++) { - TEST_ASSERT_EQUAL_HEX( align4k((uint32_t) (p_data+4096*i)), align4k(p_qtd->buffer[i]) ); + TEST_ASSERT_EQUAL_HEX( tu_align4k((uint32_t) (p_data+4096*i)), tu_align4k(p_qtd->buffer[i]) ); } } @@ -182,7 +182,7 @@ void test_interrupt_xfer_double(void) //------------- list tail -------------// TEST_ASSERT_NOT_NULL(p_tail); verify_qtd(p_tail, data2, sizeof(data2)); - TEST_ASSERT_EQUAL_HEX( align32(p_head->next.address), p_tail); + TEST_ASSERT_EQUAL_HEX( tu_align32(p_head->next.address), p_tail); TEST_ASSERT_EQUAL(EHCI_PID_IN, p_tail->pid); TEST_ASSERT_TRUE(p_tail->next.terminate); TEST_ASSERT_TRUE(p_tail->int_on_complete); diff --git a/tests/support/ehci_controller_fake.c b/tests/support/ehci_controller_fake.c index 04d55172c..041e1dbb5 100644 --- a/tests/support/ehci_controller_fake.c +++ b/tests/support/ehci_controller_fake.c @@ -95,7 +95,7 @@ void complete_qtd_in_qhd(ehci_qhd_t *p_qhd) { while(!p_qhd->qtd_overlay.next.terminate) { - ehci_qtd_t* p_qtd = (ehci_qtd_t*) align32(p_qhd->qtd_overlay.next.address); + ehci_qtd_t* p_qtd = (ehci_qtd_t*) tu_align32(p_qhd->qtd_overlay.next.address); p_qtd->active = 0; p_qtd->total_bytes = 0; p_qhd->qtd_overlay = *p_qtd; @@ -110,7 +110,7 @@ bool complete_all_qtd_in_async(ehci_qhd_t *head) do { complete_qtd_in_qhd(p_qhd); - p_qhd = (ehci_qhd_t*) align32(p_qhd->next.address); + p_qhd = (ehci_qhd_t*) tu_align32(p_qhd->next.address); }while(p_qhd != head); // stop if loop around return true; @@ -121,7 +121,7 @@ bool complete_all_qtd_in_period(ehci_link_t *head) while(!head->terminate) { uint32_t queue_type = head->type; - head = (ehci_link_t*) align32(head->address); + head = (ehci_link_t*) tu_align32(head->address); if ( queue_type == EHCI_QUEUE_ELEMENT_QHD) { @@ -153,7 +153,7 @@ void complete_1st_qtd_with_error(ehci_qhd_t* p_qhd, bool halted, bool xact_err) { if(!p_qhd->qtd_overlay.next.terminate) // TODO add active check { - ehci_qtd_t* p_qtd = (ehci_qtd_t*) align32(p_qhd->qtd_overlay.next.address); + ehci_qtd_t* p_qtd = (ehci_qtd_t*) tu_align32(p_qhd->qtd_overlay.next.address); p_qtd->active = 0; p_qtd->halted = halted ? 1 : 0; p_qtd->xact_err = xact_err ? 1 : 0; @@ -172,7 +172,7 @@ void complete_list_with_error(uint8_t hostid, bool halted, bool xact_err) do { complete_1st_qtd_with_error(p_qhd, halted, xact_err); - p_qhd = (ehci_qhd_t*) align32(p_qhd->next.address); + p_qhd = (ehci_qhd_t*) tu_align32(p_qhd->next.address); }while(p_qhd != get_async_head(hostid)); // stop if loop around //------------- Period List -------------// @@ -183,7 +183,7 @@ void complete_list_with_error(uint8_t hostid, bool halted, bool xact_err) while(!head->terminate) { uint32_t queue_type = head->type; - head = (ehci_link_t*) align32(head->address); + head = (ehci_link_t*) tu_align32(head->address); if ( queue_type == EHCI_QUEUE_ELEMENT_QHD) { diff --git a/tests/support/type_helper.h b/tests/support/type_helper.h index d0712e4f0..3e27cef2e 100644 --- a/tests/support/type_helper.h +++ b/tests/support/type_helper.h @@ -70,7 +70,7 @@ #define TEST_ASSERT_STATUS( actual )\ TEST_ASSERT_EQUAL( TUSB_ERROR_NONE, (actual) ) -// log2_of a value is equivalent to its highest set bit's position +// tu_log2 a value is equivalent to its highest set bit's position #define BITFIELD_OFFSET_OF_MEMBER(struct_type, member, bitfield_member) \ ({\ uint32_t value=0;\ @@ -78,7 +78,7 @@ memclr_((void*)&str, sizeof(struct_type));\ str.member.bitfield_member = 1;\ memcpy(&value, (void*)&str.member, sizeof(str.member));\ - log2_of( value );\ + tu_log2( value );\ }) #define BITFIELD_OFFSET_OF_UINT32(struct_type, offset, bitfield_member) \ @@ -86,7 +86,7 @@ struct_type str;\ memclr_(&str, sizeof(struct_type));\ str.bitfield_member = 1;\ - log2_of( ((uint32_t*) &str)[offset] );\ + tu_log2( ((uint32_t*) &str)[offset] );\ }) #ifdef __cplusplus -- cgit v1.3.1 From b0d14e2e412dded8c13f1a7e8af9e2703d746752 Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 28 Aug 2018 12:18:10 +0700 Subject: minor nrf52 driver correct --- src/class/cdc/cdc_device.c | 5 ++--- src/portable/nordic/nrf5x/dcd_nrf5x.c | 5 +++-- 2 files changed, 5 insertions(+), 5 deletions(-) (limited to 'src/class') diff --git a/src/class/cdc/cdc_device.c b/src/class/cdc/cdc_device.c index 2a598f051..b378689e1 100644 --- a/src/class/cdc/cdc_device.c +++ b/src/class/cdc/cdc_device.c @@ -293,16 +293,15 @@ tusb_error_t cdcd_control_request_st(uint8_t rhport, tusb_control_request_t cons } else if (CDC_REQUEST_SET_CONTROL_LINE_STATE == p_request->bRequest ) { + dcd_control_status(rhport, p_request->bmRequestType_bit.direction); // ACK control request + // CDC PSTN v1.2 section 6.3.12 // Bit 0: Indicates if DTE is present or not. // This signal corresponds to V.24 signal 108/2 and RS-232 signal DTR (Data Terminal Ready) // Bit 1: Carrier control for half-duplex modems. // This signal corresponds to V.24 signal 105 and RS-232 signal RTS (Request to Send) - p_cdc->line_state = (uint8_t) p_request->wValue; - dcd_control_status(rhport, p_request->bmRequestType_bit.direction); // ACK control request - // Invoke callback if ( tud_cdc_line_state_cb) tud_cdc_line_state_cb(itf, BIT_TEST_(p_request->wValue, 0), BIT_TEST_(p_request->wValue, 1)); } diff --git a/src/portable/nordic/nrf5x/dcd_nrf5x.c b/src/portable/nordic/nrf5x/dcd_nrf5x.c index b27d6c0ae..f9a278a49 100644 --- a/src/portable/nordic/nrf5x/dcd_nrf5x.c +++ b/src/portable/nordic/nrf5x/dcd_nrf5x.c @@ -60,7 +60,8 @@ enum MAX_PACKET_SIZE = 64, // Mask of all END event (IN & OUT) for all endpoints. ENDEPIN0-7, ENDEPOUT0-7, ENDISOIN, ENDISOOUT - EDPT_END_ALL_MASK = 0x1FFBFCUL + EDPT_END_ALL_MASK = (0xff << USBD_INTEN_ENDEPIN0_Pos) | (0xff << USBD_INTEN_ENDEPOUT0_Pos) | + USBD_INTENCLR_ENDISOIN_Msk | USBD_INTEN_ENDISOOUT_Msk }; /*------------------------------------------------------------------*/ @@ -401,7 +402,7 @@ void USBD_IRQHandler(void) volatile uint32_t* regevt = &NRF_USBD->EVENTS_USBRESET; - for(int i=0; i<32; i++) + for(int i=0; i Date: Tue, 28 Aug 2018 14:18:39 +0700 Subject: cdc device : rename epin_buf, epout_buf --- src/class/cdc/cdc_device.c | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) (limited to 'src/class') diff --git a/src/class/cdc/cdc_device.c b/src/class/cdc/cdc_device.c index b378689e1..5dd7da122 100644 --- a/src/class/cdc/cdc_device.c +++ b/src/class/cdc/cdc_device.c @@ -73,8 +73,8 @@ typedef struct uint8_t tx_ff_buf[CFG_TUD_CDC_TX_BUFSIZE]; // Endpoint Transfer buffer - CFG_TUSB_MEM_ALIGN uint8_t epin_buf[CFG_TUD_CDC_EPSIZE]; CFG_TUSB_MEM_ALIGN uint8_t epout_buf[CFG_TUD_CDC_EPSIZE]; + CFG_TUSB_MEM_ALIGN uint8_t epin_buf[CFG_TUD_CDC_EPSIZE]; }cdcd_interface_t; @@ -159,11 +159,12 @@ bool tud_cdc_n_write_flush (uint8_t itf) cdcd_interface_t* p_cdc = &_cdcd_itf[itf]; TU_VERIFY( !dcd_edpt_busy(TUD_OPT_RHPORT, p_cdc->ep_in) ); // skip if previous transfer not complete - uint16_t count = tu_fifo_read_n(&_cdcd_itf[itf].tx_ff, p_cdc->epout_buf, CFG_TUD_CDC_EPSIZE); - - TU_VERIFY( tud_cdc_n_connected(itf) ); // fifo is empty if not connected - - if ( count ) TU_ASSERT( dcd_edpt_xfer(TUD_OPT_RHPORT, p_cdc->ep_in, p_cdc->epout_buf, count) ); + uint16_t count = tu_fifo_read_n(&_cdcd_itf[itf].tx_ff, p_cdc->epin_buf, CFG_TUD_CDC_EPSIZE); + if ( count ) + { + TU_VERIFY( tud_cdc_n_connected(itf) ); // fifo is empty if not connected + TU_ASSERT( dcd_edpt_xfer(TUD_OPT_RHPORT, p_cdc->ep_in, p_cdc->epin_buf, count) ); + } return true; } @@ -264,7 +265,7 @@ tusb_error_t cdcd_open(uint8_t rhport, tusb_desc_interface_t const * p_interface } // Prepare for incoming data - TU_ASSERT( dcd_edpt_xfer(rhport, p_cdc->ep_out, p_cdc->epin_buf, CFG_TUD_CDC_EPSIZE), TUSB_ERROR_DCD_EDPT_XFER); + TU_ASSERT( dcd_edpt_xfer(rhport, p_cdc->ep_out, p_cdc->epout_buf, CFG_TUD_CDC_EPSIZE), TUSB_ERROR_DCD_EDPT_XFER); return TUSB_ERROR_NONE; } @@ -326,10 +327,10 @@ tusb_error_t cdcd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u for(uint32_t i=0; irx_ff, &p_cdc->epin_buf[i]); + tu_fifo_write(&p_cdc->rx_ff, &p_cdc->epout_buf[i]); // Check for wanted char and invoke callback if needed - if ( tud_cdc_rx_wanted_cb && ( wanted != -1 ) && ( wanted == p_cdc->epin_buf[i] ) ) + if ( tud_cdc_rx_wanted_cb && ( wanted != -1 ) && ( wanted == p_cdc->epout_buf[i] ) ) { tud_cdc_rx_wanted_cb(itf, wanted); } @@ -339,7 +340,7 @@ tusb_error_t cdcd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u if (tud_cdc_rx_cb && tu_fifo_count(&p_cdc->rx_ff) ) tud_cdc_rx_cb(itf); // prepare for next - TU_ASSERT( dcd_edpt_xfer(rhport, p_cdc->ep_out, p_cdc->epin_buf, CFG_TUD_CDC_EPSIZE), TUSB_ERROR_DCD_EDPT_XFER ); + TU_ASSERT( dcd_edpt_xfer(rhport, p_cdc->ep_out, p_cdc->epout_buf, CFG_TUD_CDC_EPSIZE), TUSB_ERROR_DCD_EDPT_XFER ); } // nothing to do with in and notif endpoint -- cgit v1.3.1 From 61e4a8c3d34994f47ae7380217af4dbefef4aab9 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 30 Aug 2018 15:20:15 +0700 Subject: remove CFG_TUD_CDC_FLUSH_ON_SOF option --- examples/device/device_virtual_com/src/tusb_config.h | 5 ----- examples/device/nrf52840/src/tusb_config.h | 4 ---- examples/device/nrf52840_freertos/src/tusb_config.h | 4 ---- examples/obsolete/device/src/tusb_config.h | 6 ------ src/class/cdc/cdc_device.c | 12 +----------- src/class/cdc/cdc_device.h | 6 ------ src/portable/nordic/nrf5x/hal_nrf5x.c | 4 ---- 7 files changed, 1 insertion(+), 40 deletions(-) (limited to 'src/class') diff --git a/examples/device/device_virtual_com/src/tusb_config.h b/examples/device/device_virtual_com/src/tusb_config.h index 38930505b..f7cde7848 100644 --- a/examples/device/device_virtual_com/src/tusb_config.h +++ b/examples/device/device_virtual_com/src/tusb_config.h @@ -87,11 +87,6 @@ #define CFG_TUD_CDC_RX_BUFSIZE 64 #define CFG_TUD_CDC_TX_BUFSIZE 64 - -// TX is sent automatically every Start of Frame event. -// If not enabled, application must call tud_cdc_write_flush() periodically -#define CFG_TUD_CDC_FLUSH_ON_SOF 1 - //--------------------------------------------------------------------+ // USB RAM PLACEMENT //--------------------------------------------------------------------+ diff --git a/examples/device/nrf52840/src/tusb_config.h b/examples/device/nrf52840/src/tusb_config.h index 9e6b01616..86bd9e9a0 100644 --- a/examples/device/nrf52840/src/tusb_config.h +++ b/examples/device/nrf52840/src/tusb_config.h @@ -101,10 +101,6 @@ #define CFG_TUD_CDC_RX_BUFSIZE 64 #define CFG_TUD_CDC_TX_BUFSIZE 64 -// TX is sent automatically every Start of Frame event. -// If not enabled, application must call tud_cdc_write_flush() periodically -#define CFG_TUD_CDC_FLUSH_ON_SOF 0 - //-------------------------------------------------------------------- // MSC //-------------------------------------------------------------------- diff --git a/examples/device/nrf52840_freertos/src/tusb_config.h b/examples/device/nrf52840_freertos/src/tusb_config.h index bd27f58b5..cadff0403 100644 --- a/examples/device/nrf52840_freertos/src/tusb_config.h +++ b/examples/device/nrf52840_freertos/src/tusb_config.h @@ -101,10 +101,6 @@ #define CFG_TUD_CDC_RX_BUFSIZE 64 #define CFG_TUD_CDC_TX_BUFSIZE 64 -// TX is sent automatically every Start of Frame event. -// If not enabled, application must call tud_cdc_write_flush() periodically -#define CFG_TUD_CDC_FLUSH_ON_SOF 0 - //-------------------------------------------------------------------- // MSC //-------------------------------------------------------------------- diff --git a/examples/obsolete/device/src/tusb_config.h b/examples/obsolete/device/src/tusb_config.h index fc6807aef..7b7c82299 100644 --- a/examples/obsolete/device/src/tusb_config.h +++ b/examples/obsolete/device/src/tusb_config.h @@ -85,12 +85,6 @@ #define CFG_TUD_CDC_RX_BUFSIZE 128 #define CFG_TUD_CDC_TX_BUFSIZE 128 - -// TX is sent automatically in Start of Frame event. -// If not enabled, application must call tud_cdc_write_flush() periodically -#define CFG_TUD_CDC_FLUSH_ON_SOF 1 - - // Number of supported Logical Unit Number (At least 1) #define CFG_TUD_MSC_MAXLUN 1 diff --git a/src/class/cdc/cdc_device.c b/src/class/cdc/cdc_device.c index 5dd7da122..6858b6ad0 100644 --- a/src/class/cdc/cdc_device.c +++ b/src/class/cdc/cdc_device.c @@ -90,7 +90,7 @@ CFG_TUSB_ATTR_USBRAM static cdcd_interface_t _cdcd_itf[CFG_TUD_CDC]; //--------------------------------------------------------------------+ bool tud_cdc_n_connected(uint8_t itf) { - // DTR (bit 0) active isconsidered as connected + // DTR (bit 0) active is considered as connected return BIT_TEST_(_cdcd_itf[itf].line_state, 0); } @@ -348,14 +348,4 @@ tusb_error_t cdcd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u return TUSB_ERROR_NONE; } -#if CFG_TUD_CDC_FLUSH_ON_SOF -void cdcd_sof(uint8_t rhport) -{ - for(uint8_t i=0; iINTENSET = USBD_INTEN_USBRESET_Msk | USBD_INTEN_USBEVENT_Msk | USBD_INTEN_EPDATA_Msk | USBD_INTEN_EP0SETUP_Msk | USBD_INTEN_EP0DATADONE_Msk | USBD_INTEN_ENDEPIN0_Msk | USBD_INTEN_ENDEPOUT0_Msk; -#if CFG_TUD_CDC && CFG_TUD_CDC_FLUSH_ON_SOF - NRF_USBD->INTENSET |= USBD_INTEN_SOF_Msk; -#endif - // Enable interrupt, Priorities 0,1,4,5 (nRF52) are reserved for SoftDevice NVIC_SetPriority(USBD_IRQn, USB_NVIC_PRIO); NVIC_ClearPendingIRQ(USBD_IRQn); -- cgit v1.3.1 From e623fc656d4973ca32b8c9547409e65e12ad9b4c Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 30 Aug 2018 15:26:53 +0700 Subject: cdc flush on write() if queue more than epsize --- src/class/cdc/cdc_device.c | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) (limited to 'src/class') diff --git a/src/class/cdc/cdc_device.c b/src/class/cdc/cdc_device.c index 6858b6ad0..2215e00ea 100644 --- a/src/class/cdc/cdc_device.c +++ b/src/class/cdc/cdc_device.c @@ -146,12 +146,20 @@ void tud_cdc_n_read_flush (uint8_t itf) uint32_t tud_cdc_n_write_char(uint8_t itf, char ch) { - return tu_fifo_write(&_cdcd_itf[itf].tx_ff, &ch) ? 1 : 0; + return tud_cdc_n_write(itf, &ch, 1); } uint32_t tud_cdc_n_write(uint8_t itf, void const* buffer, uint32_t bufsize) { - return tu_fifo_write_n(&_cdcd_itf[itf].tx_ff, buffer, bufsize); + uint16_t ret = tu_fifo_write_n(&_cdcd_itf[itf].tx_ff, buffer, bufsize); + + // flush if queue more than endpoint size + if ( tu_fifo_count(&_cdcd_itf[itf].tx_ff) >= CFG_TUD_CDC_EPSIZE ) + { + tud_cdc_n_write_flush(itf); + } + + return ret; } bool tud_cdc_n_write_flush (uint8_t itf) -- cgit v1.3.1 From 33c61bfda2c3aada3cb06d36e12d7cf57da02037 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 5 Oct 2018 21:35:40 +0700 Subject: comment out cdc flush on write (for now). Since it has issue with circuitpython --- src/class/cdc/cdc_device.c | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src/class') diff --git a/src/class/cdc/cdc_device.c b/src/class/cdc/cdc_device.c index 2215e00ea..70d51c258 100644 --- a/src/class/cdc/cdc_device.c +++ b/src/class/cdc/cdc_device.c @@ -153,11 +153,13 @@ uint32_t tud_cdc_n_write(uint8_t itf, void const* buffer, uint32_t bufsize) { uint16_t ret = tu_fifo_write_n(&_cdcd_itf[itf].tx_ff, buffer, bufsize); +#if 0 // TODO issue with circuitpython's REPL // flush if queue more than endpoint size if ( tu_fifo_count(&_cdcd_itf[itf].tx_ff) >= CFG_TUD_CDC_EPSIZE ) { tud_cdc_n_write_flush(itf); } +#endif return ret; } -- cgit v1.3.1 From c7340f4b0eb8dcf15fa93f6bf6589a94fb59dc95 Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 23 Oct 2018 12:19:32 +0700 Subject: clean up helper func --- examples/obsolete/device/src/mouse_device_app.c | 2 +- examples/obsolete/host/src/cdc_serial_host_app.c | 4 +-- examples/obsolete/host/src/keyboard_host_app.c | 2 +- examples/obsolete/host/src/mouse_host_app.c | 2 +- examples/obsolete/host/src/msc_cli.c | 6 ++-- src/class/cdc/cdc_device.c | 4 +-- src/class/cdc/cdc_host.c | 4 +-- src/class/cdc/cdc_rndis_host.c | 8 ++--- src/class/custom/custom_device.c | 2 +- src/class/custom/custom_host.c | 4 +-- src/class/hid/hid_device.c | 8 ++--- src/class/hid/hid_host.c | 6 ++-- src/class/msc/msc_device.c | 12 ++++---- src/class/msc/msc_host.c | 4 +-- src/common/tusb_common.h | 34 +++------------------- src/device/usbd.c | 4 +-- src/host/ehci/ehci.c | 8 ++--- src/host/hub.c | 4 +-- src/host/ohci/ohci.c | 6 ++-- src/host/usbh.c | 2 +- src/osal/osal_mynewt.h | 2 +- src/portable/nordic/nrf5x/dcd_nrf5x.c | 2 +- .../nxp/lpc11xx_lpc13xx/dcd_lpc_11uxx_13uxx.c | 4 +-- src/portable/nxp/lpc17xx/dcd_lpc175x_6x.c | 6 ++-- src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c | 8 ++--- tests/lpc175x_6x/test/test_dcd_lpc175x_6x.c | 8 ++--- tests/lpc18xx_43xx/test/host/cdc/test_cdc_host.c | 2 +- .../test/host/ehci/test_pipe_bulk_open.c | 2 +- .../test/host/ehci/test_pipe_bulk_xfer.c | 4 +-- .../test/host/ehci/test_pipe_control_open.c | 2 +- .../test/host/ehci/test_pipe_control_xfer.c | 4 +-- .../test/host/ehci/test_pipe_interrupt_open.c | 4 +-- .../test/host/ehci/test_pipe_interrupt_xfer.c | 4 +-- .../test/host/ehci/test_pipe_isochronous_open.c | 2 +- .../test/host/hid/test_hidh_keyboard.c | 2 +- tests/lpc18xx_43xx/test/host/hid/test_hidh_mouse.c | 2 +- tests/lpc18xx_43xx/test/host/usbh/test_enum_task.c | 2 +- tests/support/ehci_controller_fake.c | 4 +-- tests/support/type_helper.h | 4 +-- 39 files changed, 83 insertions(+), 111 deletions(-) (limited to 'src/class') diff --git a/examples/obsolete/device/src/mouse_device_app.c b/examples/obsolete/device/src/mouse_device_app.c index d6145026a..077cecc7c 100644 --- a/examples/obsolete/device/src/mouse_device_app.c +++ b/examples/obsolete/device/src/mouse_device_app.c @@ -126,7 +126,7 @@ void mouse_app_subtask(void) enum { MOUSE_RESOLUTION = 5 }; uint32_t button_mask = board_buttons(); - memclr_(&mouse_report, sizeof(hid_mouse_report_t)); + tu_memclr(&mouse_report, sizeof(hid_mouse_report_t)); if ( BIT_TEST_(button_mask, BUTTON_UP ) ) mouse_report.y = -MOUSE_RESOLUTION; if ( BIT_TEST_(button_mask, BUTTON_DOWN ) ) mouse_report.y = MOUSE_RESOLUTION; diff --git a/examples/obsolete/host/src/cdc_serial_host_app.c b/examples/obsolete/host/src/cdc_serial_host_app.c index e21a3a67d..30ed6698e 100644 --- a/examples/obsolete/host/src/cdc_serial_host_app.c +++ b/examples/obsolete/host/src/cdc_serial_host_app.c @@ -61,8 +61,8 @@ void tuh_cdc_mounted_cb(uint8_t dev_addr) { // application set-up printf("\na CDC device (address %d) is mounted\n", dev_addr); - memclr_(serial_in_buffer, sizeof(serial_in_buffer)); - memclr_(serial_out_buffer, sizeof(serial_out_buffer)); + tu_memclr(serial_in_buffer, sizeof(serial_in_buffer)); + tu_memclr(serial_out_buffer, sizeof(serial_out_buffer)); received_bytes = 0; osal_semaphore_reset(sem_hdl); diff --git a/examples/obsolete/host/src/keyboard_host_app.c b/examples/obsolete/host/src/keyboard_host_app.c index 26b1a0800..21ace3bbf 100644 --- a/examples/obsolete/host/src/keyboard_host_app.c +++ b/examples/obsolete/host/src/keyboard_host_app.c @@ -100,7 +100,7 @@ void tuh_hid_keyboard_isr(uint8_t dev_addr, tusb_event_t event) //--------------------------------------------------------------------+ void keyboard_host_app_init(void) { - memclr_(&usb_keyboard_report, sizeof(hid_keyboard_report_t)); + tu_memclr(&usb_keyboard_report, sizeof(hid_keyboard_report_t)); queue_kbd_hdl = osal_queue_create( QUEUE_KEYBOARD_REPORT_DEPTH, sizeof(hid_keyboard_report_t) ); TU_ASSERT( queue_kbd_hdl, VOID_RETURN ); diff --git a/examples/obsolete/host/src/mouse_host_app.c b/examples/obsolete/host/src/mouse_host_app.c index c326becb8..e242c7caa 100644 --- a/examples/obsolete/host/src/mouse_host_app.c +++ b/examples/obsolete/host/src/mouse_host_app.c @@ -101,7 +101,7 @@ void tuh_hid_mouse_isr(uint8_t dev_addr, tusb_event_t event) //--------------------------------------------------------------------+ void mouse_host_app_init(void) { - memclr_(&usb_mouse_report, sizeof(hid_mouse_report_t)); + tu_memclr(&usb_mouse_report, sizeof(hid_mouse_report_t)); queue_mouse_hdl = osal_queue_create( QUEUE_MOUSE_REPORT_DEPTH, sizeof(hid_mouse_report_t) ); TU_ASSERT( queue_mouse_hdl, VOID_RETURN); diff --git a/examples/obsolete/host/src/msc_cli.c b/examples/obsolete/host/src/msc_cli.c index 0182a6df9..1f7b1f5ec 100644 --- a/examples/obsolete/host/src/msc_cli.c +++ b/examples/obsolete/host/src/msc_cli.c @@ -176,12 +176,12 @@ void cli_command_prompt(void) (volume_label[0] !=0) ? volume_label : "No Label", cli_buffer); - memclr_(cli_buffer, CLI_MAX_BUFFER); + tu_memclr(cli_buffer, CLI_MAX_BUFFER); } void cli_init(void) { - memclr_(cli_buffer, CLI_MAX_BUFFER); + tu_memclr(cli_buffer, CLI_MAX_BUFFER); f_getlabel(NULL, volume_label, NULL); cli_command_prompt(); } @@ -197,7 +197,7 @@ void cli_poll(char ch) }else { puts("cli buffer overflows"); - memclr_(cli_buffer, CLI_MAX_BUFFER); + tu_memclr(cli_buffer, CLI_MAX_BUFFER); } } else if ( ch == ASCII_BACKSPACE && strlen(cli_buffer)) diff --git a/src/class/cdc/cdc_device.c b/src/class/cdc/cdc_device.c index 70d51c258..06530bc7a 100644 --- a/src/class/cdc/cdc_device.c +++ b/src/class/cdc/cdc_device.c @@ -185,7 +185,7 @@ bool tud_cdc_n_write_flush (uint8_t itf) //--------------------------------------------------------------------+ void cdcd_init(void) { - arrclr_( _cdcd_itf ); + tu_memclr(_cdcd_itf, sizeof(_cdcd_itf)); for(uint8_t i=0; ipipe_in); (void) hcd_pipe_close(p_cdc->pipe_out); - memclr_(p_cdc, sizeof(cdch_data_t)); + tu_memclr(p_cdc, sizeof(cdch_data_t)); tuh_cdc_unmounted_cb(dev_addr); diff --git a/src/class/cdc/cdc_rndis_host.c b/src/class/cdc/cdc_rndis_host.c index 4d28b0e0c..9b7684f77 100644 --- a/src/class/cdc/cdc_rndis_host.c +++ b/src/class/cdc/cdc_rndis_host.c @@ -117,7 +117,7 @@ static tusb_error_t rndis_body_subtask(void) //--------------------------------------------------------------------+ void rndish_init(void) { - memclr_(rndish_data, sizeof(rndish_data_t)*CFG_TUSB_HOST_DEVICE_MAX); + tu_memclr(rndish_data, sizeof(rndish_data_t)*CFG_TUSB_HOST_DEVICE_MAX); //------------- Task creation -------------// @@ -131,7 +131,7 @@ void rndish_init(void) void rndish_close(uint8_t dev_addr) { osal_semaphore_reset( rndish_data[dev_addr-1].sem_notification_hdl ); -// memclr_(&rndish_data[dev_addr-1], sizeof(rndish_data_t)); TODO need to move semaphore & its handle out before memclr +// tu_memclr(&rndish_data[dev_addr-1], sizeof(rndish_data_t)); TODO need to move semaphore & its handle out before memclr } @@ -189,7 +189,7 @@ tusb_error_t rndish_open_subtask(uint8_t dev_addr, cdch_data_t *p_cdc) //------------- Message Query 802.3 Permanent Address -------------// memcpy(msg_payload, &msg_query_permanent_addr, sizeof(rndis_msg_query_t)); - memclr_(msg_payload + sizeof(rndis_msg_query_t), 6); // 6 bytes for MAC address + tu_memclr(msg_payload + sizeof(rndis_msg_query_t), 6); // 6 bytes for MAC address STASK_INVOKE( send_message_get_response_subtask( dev_addr, p_cdc, @@ -205,7 +205,7 @@ tusb_error_t rndish_open_subtask(uint8_t dev_addr, cdch_data_t *p_cdc) //------------- Set OID_GEN_CURRENT_PACKET_FILTER to (DIRECTED | MULTICAST | BROADCAST) -------------// memcpy(msg_payload, &msg_set_packet_filter, sizeof(rndis_msg_set_t)); - memclr_(msg_payload + sizeof(rndis_msg_set_t), 4); // 4 bytes for filter flags + tu_memclr(msg_payload + sizeof(rndis_msg_set_t), 4); // 4 bytes for filter flags ((rndis_msg_set_t*) msg_payload)->oid_buffer[0] = (RNDIS_PACKET_TYPE_DIRECTED | RNDIS_PACKET_TYPE_MULTICAST | RNDIS_PACKET_TYPE_BROADCAST); STASK_INVOKE( diff --git a/src/class/custom/custom_device.c b/src/class/custom/custom_device.c index 2c3783e35..d43a86b14 100644 --- a/src/class/custom/custom_device.c +++ b/src/class/custom/custom_device.c @@ -68,7 +68,7 @@ static cusd_interface_t _cusd_itf; *------------------------------------------------------------------*/ void cusd_init(void) { - varclr_(&_cusd_itf); + tu_varclr(&_cusd_itf); } tusb_error_t cusd_open(uint8_t rhport, tusb_desc_interface_t const * p_desc_itf, uint16_t *p_len) diff --git a/src/class/custom/custom_host.c b/src/class/custom/custom_host.c index ad3315980..329012fda 100644 --- a/src/class/custom/custom_host.c +++ b/src/class/custom/custom_host.c @@ -104,7 +104,7 @@ tusb_error_t tusbh_custom_write(uint8_t dev_addr, uint16_t vendor_id, uint16_t p //--------------------------------------------------------------------+ void cush_init(void) { - memclr_(&custom_interface, sizeof(custom_interface_info_t) * CFG_TUSB_HOST_DEVICE_MAX); + tu_memclr(&custom_interface, sizeof(custom_interface_info_t) * CFG_TUSB_HOST_DEVICE_MAX); } tusb_error_t cush_open_subtask(uint8_t dev_addr, tusb_desc_interface_t const *p_interface_desc, uint16_t *p_length) @@ -152,7 +152,7 @@ void cush_close(uint8_t dev_addr) err2 = hcd_pipe_close( p_interface->pipe_out ); } - memclr_(p_interface, sizeof(custom_interface_info_t)); + tu_memclr(p_interface, sizeof(custom_interface_info_t)); TU_ASSERT(err1 == TUSB_ERROR_NONE && err2 == TUSB_ERROR_NONE, (void) 0 ); } diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index b1cd1d1bd..d8696f137 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -188,7 +188,7 @@ bool tud_hid_keyboard_keycode(uint8_t modifier, uint8_t keycode[6]) memcpy(report.keycode, keycode, 6); }else { - memclr_(report.keycode, 6); + tu_memclr(report.keycode, 6); } return hidd_kbd_report(&report); @@ -307,14 +307,14 @@ void hidd_init(void) void hidd_reset(uint8_t rhport) { - arrclr_(_hidd_itf); + tu_memclr(_hidd_itf, sizeof(_hidd_itf)); #if CFG_TUD_HID_KEYBOARD - varclr_(&_kbd_rpt); + tu_varclr(&_kbd_rpt); #endif #if CFG_TUD_HID_MOUSE - varclr_(&_mse_rpt); + tu_varclr(&_mse_rpt); #endif } diff --git a/src/class/hid/hid_host.c b/src/class/hid/hid_host.c index 369dad638..518297eec 100644 --- a/src/class/hid/hid_host.c +++ b/src/class/hid/hid_host.c @@ -68,7 +68,7 @@ static inline tusb_error_t hidh_interface_open(uint8_t dev_addr, uint8_t interfa static inline void hidh_interface_close(hidh_interface_info_t *p_hid) { (void) hcd_pipe_close(p_hid->pipe_hdl); - memclr_(p_hid, sizeof(hidh_interface_info_t)); + tu_memclr(p_hid, sizeof(hidh_interface_info_t)); } // called from public API need to validate parameters @@ -164,11 +164,11 @@ tusb_error_t tuh_hid_mouse_get_report(uint8_t dev_addr, void * report) void hidh_init(void) { #if CFG_TUSB_HOST_HID_KEYBOARD - memclr_(&keyboardh_data, sizeof(hidh_interface_info_t)*CFG_TUSB_HOST_DEVICE_MAX); + tu_memclr(&keyboardh_data, sizeof(hidh_interface_info_t)*CFG_TUSB_HOST_DEVICE_MAX); #endif #if CFG_TUSB_HOST_HID_MOUSE - memclr_(&mouseh_data, sizeof(hidh_interface_info_t)*CFG_TUSB_HOST_DEVICE_MAX); + tu_memclr(&mouseh_data, sizeof(hidh_interface_info_t)*CFG_TUSB_HOST_DEVICE_MAX); #endif #if CFG_TUSB_HOST_HID_GENERIC diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index 3335ad9b3..830ce85b7 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -62,9 +62,9 @@ enum typedef struct { CFG_TUSB_MEM_ALIGN msc_cbw_t cbw; -#if defined (__ICCARM__) && (CFG_TUSB_MCU == OPT_MCU_LPC11UXX || CFG_TUSB_MCU == OPT_MCU_LPC13UXX) - uint8_t padding1[64-sizeof(msc_cbw_t)]; // IAR cannot align struct's member -#endif +//#if defined (__ICCARM__) && (CFG_TUSB_MCU == OPT_MCU_LPC11UXX || CFG_TUSB_MCU == OPT_MCU_LPC13UXX) +// uint8_t padding1[64-sizeof(msc_cbw_t)]; // IAR cannot align struct's member +//#endif CFG_TUSB_MEM_ALIGN msc_csw_t csw; @@ -141,12 +141,12 @@ bool tud_msc_set_sense(uint8_t lun, uint8_t sense_key, uint8_t add_sense_code, u //--------------------------------------------------------------------+ void mscd_init(void) { - memclr_(&_mscd_itf, sizeof(mscd_interface_t)); + tu_memclr(&_mscd_itf, sizeof(mscd_interface_t)); } void mscd_reset(uint8_t rhport) { - memclr_(&_mscd_itf, sizeof(mscd_interface_t)); + tu_memclr(&_mscd_itf, sizeof(mscd_interface_t)); } tusb_error_t mscd_open(uint8_t rhport, tusb_desc_interface_t const * p_desc_itf, uint16_t *p_len) @@ -302,7 +302,6 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u { case MSC_STAGE_CMD: //------------- new CBW received -------------// - // Complete IN while waiting for CMD is usually Status of previous SCSI op, ignore it if(ep_addr != p_msc->ep_out) return TUSB_ERROR_NONE; @@ -332,7 +331,6 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u // 1. Zero : Invoke app callback, skip DATA and move to STATUS stage // 2. OUT : queue transfer (invoke app callback after done) // 3. IN : invoke app callback to get response - if ( p_cbw->xfer_bytes == 0) { int32_t const cb_result = tud_msc_scsi_cb(p_cbw->lun, p_cbw->command, NULL, 0); diff --git a/src/class/msc/msc_host.c b/src/class/msc/msc_host.c index 7e6396389..9250b8df7 100644 --- a/src/class/msc/msc_host.c +++ b/src/class/msc/msc_host.c @@ -288,7 +288,7 @@ tusb_error_t tuh_msc_write10(uint8_t dev_addr, uint8_t lun, void const * p_buffe //--------------------------------------------------------------------+ void msch_init(void) { - memclr_(msch_data, sizeof(msch_interface_t)*CFG_TUSB_HOST_DEVICE_MAX); + tu_memclr(msch_data, sizeof(msch_interface_t)*CFG_TUSB_HOST_DEVICE_MAX); msch_sem_hdl = osal_semaphore_create(1, 0); } @@ -416,7 +416,7 @@ void msch_close(uint8_t dev_addr) (void) hcd_pipe_close(msch_data[dev_addr-1].bulk_in); (void) hcd_pipe_close(msch_data[dev_addr-1].bulk_out); - memclr_(&msch_data[dev_addr-1], sizeof(msch_interface_t)); + tu_memclr(&msch_data[dev_addr-1], sizeof(msch_interface_t)); osal_semaphore_reset(msch_sem_hdl); tuh_msc_unmounted_cb(dev_addr); // invoke Application Callback diff --git a/src/common/tusb_common.h b/src/common/tusb_common.h index 778e70676..85bd15d43 100644 --- a/src/common/tusb_common.h +++ b/src/common/tusb_common.h @@ -73,8 +73,7 @@ //--------------------------------------------------------------------+ // MACROS //--------------------------------------------------------------------+ -#define MAX_OF(a, b) ( (a) > (b) ? (a) : (b) ) -#define MIN_OF(a, b) ( (a) < (b) ? (a) : (b) ) +#define TU_ARRAY_SZIE(_arr) ( sizeof(_arr) / sizeof(_arr[0]) ) #define U16_HIGH_U8(u16) ((uint8_t) (((u16) >> 8) & 0x00ff)) #define U16_LOW_U8(u16) ((uint8_t) ((u16) & 0x00ff)) @@ -137,12 +136,10 @@ //--------------------------------------------------------------------+ // INLINE FUNCTION //--------------------------------------------------------------------+ -#define memclr_(buffer, size) memset((buffer), 0, (size)) -#define varclr_(_var) memclr_(_var, sizeof(*(_var))) -#define arrclr_(_arr) memclr_(_arr, sizeof(_arr)) -#define arrcount_(_arr) ( sizeof(_arr) / sizeof(_arr[0]) ) +#define tu_memclr(buffer, size) memset((buffer), 0, (size)) +#define tu_varclr(_var) tu_memclr(_var, sizeof(*(_var))) -static inline bool mem_all_zero(void const* buffer, uint32_t size) +static inline bool tu_mem_test_zero (void const* buffer, uint32_t size) { uint8_t const* p_mem = (uint8_t const*) buffer; for(uint32_t i=0; i y) ? x : y; } -static inline uint16_t tu_max16(uint16_t x, uint16_t y) -{ - return (x > y) ? x : y; -} - //------------- Align -------------// static inline uint32_t tu_align32 (uint32_t value) { @@ -249,24 +241,6 @@ static inline uint8_t tu_log2(uint32_t value) return result; } -// return the number of set bits in value -static inline uint8_t tu_cardof(uint32_t value) -{ - // Brian Kernighan's method goes through as many iterations as there are set bits. So if we have a 32-bit word with only - // the high bit set, then it will only go once through the loop - // Published in 1988, the C Programming Language 2nd Ed. (by Brian W. Kernighan and Dennis M. Ritchie) - // mentions this in exercise 2-9. On April 19, 2006 Don Knuth pointed out to me that this method - // "was first published by Peter Wegner in CACM 3 (1960), 322. (Also discovered independently by Derrick Lehmer and - // published in 1964 in a book edited by Beckenbach.)" - uint8_t count; - for (count = 0; value; count++) - { - value &= value - 1; // clear the least significant bit set - } - - return count; -} - #ifdef __cplusplus } #endif diff --git a/src/device/usbd.c b/src/device/usbd.c index 89dd4b722..146f8ec89 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -274,7 +274,7 @@ static tusb_error_t usbd_main_st(void) tusb_error_t err; err = TUSB_ERROR_NONE; - memclr_(&event, sizeof(usbd_task_event_t)); + tu_memclr(&event, sizeof(usbd_task_event_t)); osal_queue_receive(_usbd_q, &event, OSAL_TIMEOUT_WAIT_FOREVER, &err); @@ -318,7 +318,7 @@ static tusb_error_t usbd_main_st(void) static void usbd_reset(uint8_t rhport) { - varclr_(&_usbd_dev); + tu_varclr(&_usbd_dev); memset(_usbd_dev.itf2drv, 0xff, sizeof(_usbd_dev.itf2drv)); // invalid mapping memset(_usbd_dev.ep2drv , 0xff, sizeof(_usbd_dev.ep2drv )); // invalid mapping diff --git a/src/host/ehci/ehci.c b/src/host/ehci/ehci.c index 84821e3f5..99e7fdb65 100644 --- a/src/host/ehci/ehci.c +++ b/src/host/ehci/ehci.c @@ -130,7 +130,7 @@ static tusb_error_t hcd_controller_stop(uint8_t hostid) ATTR_WARN_UNUSED_RESULT tusb_error_t hcd_init(void) { //------------- Data Structure init -------------// - memclr_(&ehci_data, sizeof(ehci_data_t)); + tu_memclr(&ehci_data, sizeof(ehci_data_t)); #if (CFG_TUSB_RHPORT0_MODE & OPT_MODE_HOST) TU_ASSERT_ERR (hcd_controller_init(0)); @@ -192,7 +192,7 @@ static tusb_error_t hcd_controller_init(uint8_t hostid) //------------- Asynchronous List -------------// ehci_qhd_t * const async_head = get_async_head(hostid); - memclr_(async_head, sizeof(ehci_qhd_t)); + tu_memclr(async_head, sizeof(ehci_qhd_t)); async_head->next.address = (uint32_t) async_head; // circular list, next is itself async_head->next.type = EHCI_QUEUE_ELEMENT_QHD; @@ -938,7 +938,7 @@ static void qhd_init(ehci_qhd_t *p_qhd, uint8_t dev_addr, uint16_t max_packet_si // address 0 is used as async head, which always on the list --> cannot be cleared (ehci halted otherwise) if (dev_addr != 0) { - memclr_(p_qhd, sizeof(ehci_qhd_t)); + tu_memclr(p_qhd, sizeof(ehci_qhd_t)); } p_qhd->device_address = dev_addr; @@ -1004,7 +1004,7 @@ static void qhd_init(ehci_qhd_t *p_qhd, uint8_t dev_addr, uint16_t max_packet_si static void qtd_init(ehci_qtd_t* p_qtd, uint32_t data_ptr, uint16_t total_bytes) { - memclr_(p_qtd, sizeof(ehci_qtd_t)); + tu_memclr(p_qtd, sizeof(ehci_qtd_t)); p_qtd->used = 1; diff --git a/src/host/hub.c b/src/host/hub.c index 063cef61a..624e43563 100644 --- a/src/host/hub.c +++ b/src/host/hub.c @@ -152,7 +152,7 @@ tusb_speed_t hub_port_get_speed(void) //--------------------------------------------------------------------+ void hub_init(void) { - memclr_(hub_data, CFG_TUSB_HOST_DEVICE_MAX*sizeof(usbh_hub_t)); + tu_memclr(hub_data, CFG_TUSB_HOST_DEVICE_MAX*sizeof(usbh_hub_t)); // hub_enum_sem_hdl = osal_semaphore_create( OSAL_SEM_REF(hub_enum_semaphore) ); } @@ -237,7 +237,7 @@ void hub_isr(pipe_handle_t pipe_hdl, tusb_event_t event, uint32_t xferred_bytes) void hub_close(uint8_t dev_addr) { (void) hcd_pipe_close(hub_data[dev_addr-1].pipe_status); - memclr_(&hub_data[dev_addr-1], sizeof(usbh_hub_t)); + tu_memclr(&hub_data[dev_addr-1], sizeof(usbh_hub_t)); // osal_semaphore_reset(hub_enum_sem_hdl); } diff --git a/src/host/ohci/ohci.c b/src/host/ohci/ohci.c index 1c9f3f293..b9183a025 100644 --- a/src/host/ohci/ohci.c +++ b/src/host/ohci/ohci.c @@ -164,7 +164,7 @@ static ohci_ed_t * ed_list_find_previous(ohci_ed_t const * p_head, ohci_ed_t con tusb_error_t hcd_init(void) { //------------- Data Structure init -------------// - memclr_(&ohci_data, sizeof(ohci_data_t)); + tu_memclr(&ohci_data, sizeof(ohci_data_t)); for(uint8_t i=0; i<32; i++) { // assign all interrupt pointes to period head ed ohci_data.hcca.interrupt_table[i] = (uint32_t) &ohci_data.period_head_ed; @@ -245,7 +245,7 @@ static void ed_init(ohci_ed_t *p_ed, uint8_t dev_addr, uint16_t max_packet_size, // address 0 is used as async head, which always on the list --> cannot be cleared if (dev_addr != 0) { - memclr_(p_ed, sizeof(ohci_ed_t)); + tu_memclr(p_ed, sizeof(ohci_ed_t)); } p_ed->device_address = dev_addr; @@ -261,7 +261,7 @@ static void ed_init(ohci_ed_t *p_ed, uint8_t dev_addr, uint16_t max_packet_size, static void gtd_init(ohci_gtd_t* p_td, void* data_ptr, uint16_t total_bytes) { - memclr_(p_td, sizeof(ohci_gtd_t)); + tu_memclr(p_td, sizeof(ohci_gtd_t)); p_td->used = 1; p_td->expected_bytes = total_bytes; diff --git a/src/host/usbh.c b/src/host/usbh.c index 8b858b2de..b849de9b9 100644 --- a/src/host/usbh.c +++ b/src/host/usbh.c @@ -142,7 +142,7 @@ uint32_t tuh_device_get_mounted_class_flag(uint8_t dev_addr) //--------------------------------------------------------------------+ tusb_error_t usbh_init(void) { - memclr_(usbh_devices, sizeof(usbh_device_info_t)*(CFG_TUSB_HOST_DEVICE_MAX+1)); + tu_memclr(usbh_devices, sizeof(usbh_device_info_t)*(CFG_TUSB_HOST_DEVICE_MAX+1)); TU_ASSERT_ERR( hcd_init() ); diff --git a/src/osal/osal_mynewt.h b/src/osal/osal_mynewt.h index db65ac553..59cd1b821 100644 --- a/src/osal/osal_mynewt.h +++ b/src/osal/osal_mynewt.h @@ -145,7 +145,7 @@ static inline bool osal_queue_send(osal_queue_t const queue_hdl, void const * da os_memblock_put(&queue_hdl->mpool, ptr); return false; } - memclr_(ev, sizeof(struct os_event)); + tu_memclr(ev, sizeof(struct os_event)); ev->ev_arg = ptr; os_eventq_put(&queue_hdl->evq, ev); diff --git a/src/portable/nordic/nrf5x/dcd_nrf5x.c b/src/portable/nordic/nrf5x/dcd_nrf5x.c index 01926c76e..371c291a3 100644 --- a/src/portable/nordic/nrf5x/dcd_nrf5x.c +++ b/src/portable/nordic/nrf5x/dcd_nrf5x.c @@ -108,7 +108,7 @@ void bus_reset(void) NRF_USBD->TASKS_STARTISOIN = 0; NRF_USBD->TASKS_STARTISOOUT = 0; - varclr_(&_dcd); + tu_varclr(&_dcd); } /*------------------------------------------------------------------*/ diff --git a/src/portable/nxp/lpc11xx_lpc13xx/dcd_lpc_11uxx_13uxx.c b/src/portable/nxp/lpc11xx_lpc13xx/dcd_lpc_11uxx_13uxx.c index 292d1fa6d..8e5a4d1aa 100644 --- a/src/portable/nxp/lpc11xx_lpc13xx/dcd_lpc_11uxx_13uxx.c +++ b/src/portable/nxp/lpc11xx_lpc13xx/dcd_lpc_11uxx_13uxx.c @@ -201,7 +201,7 @@ bool dcd_init(uint8_t rhport) static void bus_reset(void) { - memclr_(&dcd_data, sizeof(dcd_11u_13u_data_t)); + tu_memclr(&dcd_data, sizeof(dcd_11u_13u_data_t)); for(uint8_t ep_id = 2; ep_id < DCD_11U_13U_QHD_COUNT; ep_id++) { // disable all non-control endpoints on bus reset dcd_data.qhd[ep_id][0].disable = dcd_data.qhd[ep_id][1].disable = 1; @@ -473,7 +473,7 @@ edpt_hdl_t dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint TU_ASSERT( dcd_data.qhd[ep_id][0].disable && dcd_data.qhd[ep_id][1].disable, null_handle ); // endpoint must not previously opened, normally this means running out of endpoints - memclr_(dcd_data.qhd[ep_id], 2*sizeof(dcd_11u_13u_qhd_t)); + tu_memclr(dcd_data.qhd[ep_id], 2*sizeof(dcd_11u_13u_qhd_t)); dcd_data.qhd[ep_id][0].is_isochronous = dcd_data.qhd[ep_id][1].is_isochronous = (p_endpoint_desc->bmAttributes.xfer == TUSB_XFER_ISOCHRONOUS); dcd_data.class_code[ep_id] = class_code; diff --git a/src/portable/nxp/lpc17xx/dcd_lpc175x_6x.c b/src/portable/nxp/lpc17xx/dcd_lpc175x_6x.c index 4d3687830..189521d25 100644 --- a/src/portable/nxp/lpc17xx/dcd_lpc175x_6x.c +++ b/src/portable/nxp/lpc17xx/dcd_lpc175x_6x.c @@ -119,7 +119,7 @@ static void bus_reset(void) LPC_USB->USBNDDRIntClr = 0xFFFFFFFF; LPC_USB->USBSysErrIntClr = 0xFFFFFFFF; - memclr_(&dcd_data, sizeof(dcd_data_t)); + tu_memclr(&dcd_data, sizeof(dcd_data_t)); } bool dcd_init(uint8_t rhport) @@ -432,7 +432,7 @@ edpt_hdl_t dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint //------------- first DD prepare -------------// dcd_dma_descriptor_t* const p_dd = &dcd_data.dd[ep_id][0]; - memclr_(p_dd, sizeof(dcd_dma_descriptor_t)); + tu_memclr(p_dd, sizeof(dcd_dma_descriptor_t)); p_dd->is_isochronous = (p_endpoint_desc->bmAttributes.xfer == TUSB_XFER_ISOCHRONOUS) ? 1 : 0; p_dd->max_packet_size = p_endpoint_desc->wMaxPacketSize.size; @@ -498,7 +498,7 @@ tusb_error_t dcd_edpt_xfer(edpt_hdl_t edpt_hdl, uint8_t* buffer, uint16_t total_ { // setup new dd dcd_dma_descriptor_t* const p_dd = &dcd_data.dd[ edpt_hdl.index ][1]; - memclr_(p_dd, sizeof(dcd_dma_descriptor_t)); + tu_memclr(p_dd, sizeof(dcd_dma_descriptor_t)); dd_xfer_init(p_dd, buffer, total_bytes); diff --git a/src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c b/src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c index 7368542b8..5a7d61004 100644 --- a/src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c +++ b/src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c @@ -133,7 +133,7 @@ static void bus_reset(uint8_t rhport) //------------- Queue Head & Queue TD -------------// dcd_data_t* p_dcd = dcd_data_ptr[rhport]; - memclr_(p_dcd, sizeof(dcd_data_t)); + tu_memclr(p_dcd, sizeof(dcd_data_t)); //------------- Set up Control Endpoints (0 OUT, 1 IN) -------------// p_dcd->qhd[0].zero_length_termination = p_dcd->qhd[1].zero_length_termination = 1; @@ -149,7 +149,7 @@ bool dcd_init(uint8_t rhport) LPC_USB0_Type* const lpc_usb = LPC_USB[rhport]; dcd_data_t* p_dcd = dcd_data_ptr[rhport]; - memclr_(p_dcd, sizeof(dcd_data_t)); + tu_memclr(p_dcd, sizeof(dcd_data_t)); lpc_usb->ENDPOINTLISTADDR = (uint32_t) p_dcd->qhd; // Endpoint List Address has to be 2K alignment lpc_usb->USBSTS_D = lpc_usb->USBSTS_D; @@ -196,7 +196,7 @@ static inline uint8_t edpt_phy2log(uint8_t physical_endpoint) static void qtd_init(dcd_qtd_t* p_qtd, void * data_ptr, uint16_t total_bytes) { - memclr_(p_qtd, sizeof(dcd_qtd_t)); + tu_memclr(p_qtd, sizeof(dcd_qtd_t)); p_qtd->used = 1; @@ -303,7 +303,7 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc) uint8_t ep_idx = edpt_addr2phy(p_endpoint_desc->bEndpointAddress); dcd_qhd_t * p_qhd = &dcd_data_ptr[rhport]->qhd[ep_idx]; - memclr_(p_qhd, sizeof(dcd_qhd_t)); + tu_memclr(p_qhd, sizeof(dcd_qhd_t)); p_qhd->zero_length_termination = 1; p_qhd->max_package_size = p_endpoint_desc->wMaxPacketSize.size; diff --git a/tests/lpc175x_6x/test/test_dcd_lpc175x_6x.c b/tests/lpc175x_6x/test/test_dcd_lpc175x_6x.c index ef084fc77..31baa5f5c 100644 --- a/tests/lpc175x_6x/test/test_dcd_lpc175x_6x.c +++ b/tests/lpc175x_6x/test/test_dcd_lpc175x_6x.c @@ -51,9 +51,9 @@ extern dcd_dma_descriptor_t dcd_dd[DCD_MAX_DD]; void setUp(void) { - memclr_(dcd_udca, 32*4); - memclr_(dcd_dd, sizeof(dcd_dma_descriptor_t)*DCD_MAX_DD); - memclr_(&lpc_usb, sizeof(LPC_USB_TypeDef)); + tu_memclr(dcd_udca, 32*4); + tu_memclr(dcd_dd, sizeof(dcd_dma_descriptor_t)*DCD_MAX_DD); + tu_memclr(&lpc_usb, sizeof(LPC_USB_TypeDef)); } void tearDown(void) @@ -129,7 +129,7 @@ void test_dcd_configure_endpoint_in(void) }; dcd_init(); - memclr_(&lpc_usb, sizeof(LPC_USB_TypeDef)); // clear to examine register after CUT + tu_memclr(&lpc_usb, sizeof(LPC_USB_TypeDef)); // clear to examine register after CUT //------------- Code Under Test -------------// dcd_pipe_open(0, &desc_endpoint); diff --git a/tests/lpc18xx_43xx/test/host/cdc/test_cdc_host.c b/tests/lpc18xx_43xx/test/host/cdc/test_cdc_host.c index a74270e8b..5077eea93 100644 --- a/tests/lpc18xx_43xx/test/host/cdc/test_cdc_host.c +++ b/tests/lpc18xx_43xx/test/host/cdc/test_cdc_host.c @@ -71,7 +71,7 @@ void setUp(void) length = 0; dev_addr = 1; - memclr_(cdch_data, sizeof(cdch_data_t)*CFG_TUSB_HOST_DEVICE_MAX); + tu_memclr(cdch_data, sizeof(cdch_data_t)*CFG_TUSB_HOST_DEVICE_MAX); } void tearDown(void) diff --git a/tests/lpc18xx_43xx/test/host/ehci/test_pipe_bulk_open.c b/tests/lpc18xx_43xx/test/host/ehci/test_pipe_bulk_open.c index a26b990d3..581488d7d 100644 --- a/tests/lpc18xx_43xx/test/host/ehci/test_pipe_bulk_open.c +++ b/tests/lpc18xx_43xx/test/host/ehci/test_pipe_bulk_open.c @@ -70,7 +70,7 @@ void setUp(void) dev_addr = 1; hostid = RANDOM(CONTROLLER_HOST_NUMBER) + TEST_CONTROLLER_HOST_START_INDEX; - memclr_(usbh_devices, sizeof(usbh_device_info_t)*(CFG_TUSB_HOST_DEVICE_MAX+1)); + tu_memclr(usbh_devices, sizeof(usbh_device_info_t)*(CFG_TUSB_HOST_DEVICE_MAX+1)); helper_usbh_device_emulate(dev_addr, hub_addr, hub_port, hostid, TUSB_SPEED_HIGH); async_head = get_async_head( hostid ); diff --git a/tests/lpc18xx_43xx/test/host/ehci/test_pipe_bulk_xfer.c b/tests/lpc18xx_43xx/test/host/ehci/test_pipe_bulk_xfer.c index a52c721fe..2e9e29fdc 100644 --- a/tests/lpc18xx_43xx/test/host/ehci/test_pipe_bulk_xfer.c +++ b/tests/lpc18xx_43xx/test/host/ehci/test_pipe_bulk_xfer.c @@ -90,8 +90,8 @@ tusb_desc_endpoint_t const desc_ept_bulk_out = void setUp(void) { ehci_controller_init(); - memclr_(xfer_data, sizeof(xfer_data)); - memclr_(usbh_devices, sizeof(usbh_device_info_t)*(CFG_TUSB_HOST_DEVICE_MAX+1)); + tu_memclr(xfer_data, sizeof(xfer_data)); + tu_memclr(usbh_devices, sizeof(usbh_device_info_t)*(CFG_TUSB_HOST_DEVICE_MAX+1)); TEST_ASSERT_STATUS( hcd_init() ); diff --git a/tests/lpc18xx_43xx/test/host/ehci/test_pipe_control_open.c b/tests/lpc18xx_43xx/test/host/ehci/test_pipe_control_open.c index 22cbf7569..426fed9f2 100644 --- a/tests/lpc18xx_43xx/test/host/ehci/test_pipe_control_open.c +++ b/tests/lpc18xx_43xx/test/host/ehci/test_pipe_control_open.c @@ -67,7 +67,7 @@ static ehci_qhd_t *p_control_qhd; //--------------------------------------------------------------------+ void setUp(void) { - memclr_(usbh_devices, sizeof(usbh_device_info_t)*(CFG_TUSB_HOST_DEVICE_MAX+1)); + tu_memclr(usbh_devices, sizeof(usbh_device_info_t)*(CFG_TUSB_HOST_DEVICE_MAX+1)); TEST_ASSERT_STATUS( hcd_init() ); diff --git a/tests/lpc18xx_43xx/test/host/ehci/test_pipe_control_xfer.c b/tests/lpc18xx_43xx/test/host/ehci/test_pipe_control_xfer.c index 286aae113..ffd7ffb67 100644 --- a/tests/lpc18xx_43xx/test/host/ehci/test_pipe_control_xfer.c +++ b/tests/lpc18xx_43xx/test/host/ehci/test_pipe_control_xfer.c @@ -74,8 +74,8 @@ void setUp(void) { ehci_controller_init(); - memclr_(usbh_devices, sizeof(usbh_device_info_t)*(CFG_TUSB_HOST_DEVICE_MAX+1)); - memclr_(xfer_data, sizeof(xfer_data)); + tu_memclr(usbh_devices, sizeof(usbh_device_info_t)*(CFG_TUSB_HOST_DEVICE_MAX+1)); + tu_memclr(xfer_data, sizeof(xfer_data)); TEST_ASSERT_STATUS( hcd_init() ); diff --git a/tests/lpc18xx_43xx/test/host/ehci/test_pipe_interrupt_open.c b/tests/lpc18xx_43xx/test/host/ehci/test_pipe_interrupt_open.c index f39021ef2..b243a468e 100644 --- a/tests/lpc18xx_43xx/test/host/ehci/test_pipe_interrupt_open.c +++ b/tests/lpc18xx_43xx/test/host/ehci/test_pipe_interrupt_open.c @@ -67,7 +67,7 @@ static pipe_handle_t pipe_hdl; //--------------------------------------------------------------------+ void setUp(void) { - memclr_(usbh_devices, sizeof(usbh_device_info_t)*(CFG_TUSB_HOST_DEVICE_MAX+1)); + tu_memclr(usbh_devices, sizeof(usbh_device_info_t)*(CFG_TUSB_HOST_DEVICE_MAX+1)); hcd_init(); @@ -78,7 +78,7 @@ void setUp(void) period_head_arr = get_period_head( hostid, 1 ); p_int_qhd = NULL; - memclr_(&pipe_hdl, sizeof(pipe_handle_t)); + tu_memclr(&pipe_hdl, sizeof(pipe_handle_t)); } void tearDown(void) diff --git a/tests/lpc18xx_43xx/test/host/ehci/test_pipe_interrupt_xfer.c b/tests/lpc18xx_43xx/test/host/ehci/test_pipe_interrupt_xfer.c index aeb094932..827db2897 100644 --- a/tests/lpc18xx_43xx/test/host/ehci/test_pipe_interrupt_xfer.c +++ b/tests/lpc18xx_43xx/test/host/ehci/test_pipe_interrupt_xfer.c @@ -91,8 +91,8 @@ void setUp(void) { ehci_controller_init(); - memclr_(usbh_devices, sizeof(usbh_device_info_t)*(CFG_TUSB_HOST_DEVICE_MAX+1)); - memclr_(xfer_data, sizeof(xfer_data)); + tu_memclr(usbh_devices, sizeof(usbh_device_info_t)*(CFG_TUSB_HOST_DEVICE_MAX+1)); + tu_memclr(xfer_data, sizeof(xfer_data)); TEST_ASSERT_STATUS( hcd_init() ); diff --git a/tests/lpc18xx_43xx/test/host/ehci/test_pipe_isochronous_open.c b/tests/lpc18xx_43xx/test/host/ehci/test_pipe_isochronous_open.c index 584c44471..1feff94e5 100644 --- a/tests/lpc18xx_43xx/test/host/ehci/test_pipe_isochronous_open.c +++ b/tests/lpc18xx_43xx/test/host/ehci/test_pipe_isochronous_open.c @@ -63,7 +63,7 @@ static ehci_qhd_t *period_head_arr; //--------------------------------------------------------------------+ void setUp(void) { - memclr_(usbh_devices, sizeof(usbh_device_info_t)*(CFG_TUSB_HOST_DEVICE_MAX+1)); + tu_memclr(usbh_devices, sizeof(usbh_device_info_t)*(CFG_TUSB_HOST_DEVICE_MAX+1)); hcd_init(); diff --git a/tests/lpc18xx_43xx/test/host/hid/test_hidh_keyboard.c b/tests/lpc18xx_43xx/test/host/hid/test_hidh_keyboard.c index 75c8f8a90..b3b49c172 100644 --- a/tests/lpc18xx_43xx/test/host/hid/test_hidh_keyboard.c +++ b/tests/lpc18xx_43xx/test/host/hid/test_hidh_keyboard.c @@ -73,7 +73,7 @@ tusb_desc_endpoint_t const *p_kdb_endpoint_desc = &desc_configuration.keyboard void setUp(void) { hidh_init(); - memclr_(&report, sizeof(hid_keyboard_report_t)); + tu_memclr(&report, sizeof(hid_keyboard_report_t)); dev_addr = RANDOM(CFG_TUSB_HOST_DEVICE_MAX)+1; p_hidh_kbd = &keyboardh_data[dev_addr-1]; diff --git a/tests/lpc18xx_43xx/test/host/hid/test_hidh_mouse.c b/tests/lpc18xx_43xx/test/host/hid/test_hidh_mouse.c index 741f54428..b1a3558e6 100644 --- a/tests/lpc18xx_43xx/test/host/hid/test_hidh_mouse.c +++ b/tests/lpc18xx_43xx/test/host/hid/test_hidh_mouse.c @@ -62,7 +62,7 @@ void setUp(void) { hidh_init(); - memclr_(&report, sizeof(hid_mouse_report_t)); + tu_memclr(&report, sizeof(hid_mouse_report_t)); dev_addr = RANDOM(CFG_TUSB_HOST_DEVICE_MAX)+1; p_hidh_mouse = &mouseh_data[dev_addr-1]; diff --git a/tests/lpc18xx_43xx/test/host/usbh/test_enum_task.c b/tests/lpc18xx_43xx/test/host/usbh/test_enum_task.c index 7aeba21a0..a85c3c48a 100644 --- a/tests/lpc18xx_43xx/test/host/usbh/test_enum_task.c +++ b/tests/lpc18xx_43xx/test/host/usbh/test_enum_task.c @@ -73,7 +73,7 @@ enum { void setUp(void) { - memclr_(usbh_devices, sizeof(usbh_device_info_t)*(CFG_TUSB_HOST_DEVICE_MAX+1)); + tu_memclr(usbh_devices, sizeof(usbh_device_info_t)*(CFG_TUSB_HOST_DEVICE_MAX+1)); osal_queue_receive_StubWithCallback(queue_recv_stub); osal_semaphore_wait_StubWithCallback(semaphore_wait_success_stub); diff --git a/tests/support/ehci_controller_fake.c b/tests/support/ehci_controller_fake.c index 041e1dbb5..acd40cc0b 100644 --- a/tests/support/ehci_controller_fake.c +++ b/tests/support/ehci_controller_fake.c @@ -61,8 +61,8 @@ extern usbh_device_info_t usbh_devices[CFG_TUSB_HOST_DEVICE_MAX+1]; //--------------------------------------------------------------------+ void ehci_controller_init(void) { - memclr_(&lpc_usb0, sizeof(LPC_USB0_Type)); - memclr_(&lpc_usb1, sizeof(LPC_USB1_Type)); + tu_memclr(&lpc_usb0, sizeof(LPC_USB0_Type)); + tu_memclr(&lpc_usb1, sizeof(LPC_USB1_Type)); } void ehci_controller_control_xfer_proceed(uint8_t dev_addr, uint8_t p_data[]) diff --git a/tests/support/type_helper.h b/tests/support/type_helper.h index 3e27cef2e..36502ba35 100644 --- a/tests/support/type_helper.h +++ b/tests/support/type_helper.h @@ -75,7 +75,7 @@ ({\ uint32_t value=0;\ struct_type str;\ - memclr_((void*)&str, sizeof(struct_type));\ + tu_memclr((void*)&str, sizeof(struct_type));\ str.member.bitfield_member = 1;\ memcpy(&value, (void*)&str.member, sizeof(str.member));\ tu_log2( value );\ @@ -84,7 +84,7 @@ #define BITFIELD_OFFSET_OF_UINT32(struct_type, offset, bitfield_member) \ ({\ struct_type str;\ - memclr_(&str, sizeof(struct_type));\ + tu_memclr(&str, sizeof(struct_type));\ str.bitfield_member = 1;\ tu_log2( ((uint32_t*) &str)[offset] );\ }) -- cgit v1.3.1 From f339ac7a6afcf7aecc8720d5590aae39bd3ae929 Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 23 Oct 2018 12:33:21 +0700 Subject: clean up msc device --- src/class/msc/msc.h | 14 ++++++------ src/class/msc/msc_device.c | 57 +++++++++++++++++++++++----------------------- 2 files changed, 35 insertions(+), 36 deletions(-) (limited to 'src/class') diff --git a/src/class/msc/msc.h b/src/class/msc/msc.h index ca5615055..59df6bed6 100644 --- a/src/class/msc/msc.h +++ b/src/class/msc/msc.h @@ -100,13 +100,13 @@ typedef enum /// Command Block Wrapper typedef struct ATTR_PACKED { - uint32_t signature ; ///< Signature that helps identify this data packet as a CBW. The signature field shall contain the value 43425355h (little endian), indicating a CBW. - uint32_t tag ; ///< Tag sent by the host. The device shall echo the contents of this field back to the host in the dCSWTagfield of the associated CSW. The dCSWTagpositively associates a CSW with the corresponding CBW. - uint32_t xfer_bytes ; ///< The number of bytes of data that the host expects to transfer on the Bulk-In or Bulk-Out endpoint (as indicated by the Direction bit) during the execution of this command. If this field is zero, the device and the host shall transfer no data between the CBW and the associated CSW, and the device shall ignore the value of the Direction bit in bmCBWFlags. - uint8_t dir ; ///< Bit 7 of this field define transfer direction \n - 0 : Data-Out from host to the device. \n - 1 : Data-In from the device to the host. - uint8_t lun ; ///< The device Logical Unit Number (LUN) to which the command block is being sent. For devices that support multiple LUNs, the host shall place into this field the LUN to which this command block is addressed. Otherwise, the host shall set this field to zero. - uint8_t cmd_len ; ///< The valid length of the CBWCBin bytes. This defines the valid length of the command block. The only legal values are 1 through 16 - uint8_t command[16] ; ///< The command block to be executed by the device. The device shall interpret the first cmd_len bytes in this field as a command block + uint32_t signature; ///< Signature that helps identify this data packet as a CBW. The signature field shall contain the value 43425355h (little endian), indicating a CBW. + uint32_t tag; ///< Tag sent by the host. The device shall echo the contents of this field back to the host in the dCSWTagfield of the associated CSW. The dCSWTagpositively associates a CSW with the corresponding CBW. + uint32_t total_bytes; ///< The number of bytes of data that the host expects to transfer on the Bulk-In or Bulk-Out endpoint (as indicated by the Direction bit) during the execution of this command. If this field is zero, the device and the host shall transfer no data between the CBW and the associated CSW, and the device shall ignore the value of the Direction bit in bmCBWFlags. + uint8_t dir; ///< Bit 7 of this field define transfer direction \n - 0 : Data-Out from host to the device. \n - 1 : Data-In from the device to the host. + uint8_t lun; ///< The device Logical Unit Number (LUN) to which the command block is being sent. For devices that support multiple LUNs, the host shall place into this field the LUN to which this command block is addressed. Otherwise, the host shall set this field to zero. + uint8_t cmd_len; ///< The valid length of the CBWCBin bytes. This defines the valid length of the command block. The only legal values are 1 through 16 + uint8_t command[16]; ///< The command block to be executed by the device. The device shall interpret the first cmd_len bytes in this field as a command block }msc_cbw_t; TU_VERIFY_STATIC(sizeof(msc_cbw_t) == 31, "size is not correct"); diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index 830ce85b7..4d2f9249c 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -74,7 +74,7 @@ typedef struct { // Bulk Only Transfer (BOT) Protocol uint8_t stage; - uint32_t data_len; + uint32_t total_len; uint32_t xferred_len; // numbered of bytes transferred so far in the Data Stage // Sense Response Data @@ -251,12 +251,11 @@ int32_t proc_builtin_scsi(msc_cbw_t const * p_cbw, uint8_t* buffer, uint32_t buf case SCSI_CMD_MODE_SENSE_6: { - scsi_mode_sense6_resp_t const mode_resp = - { - .data_len = 3, - .medium_type = 0, - .device_specific_para = 0, - .block_descriptor_len = 0 // no block descriptor are included + scsi_mode_sense6_resp_t const mode_resp = { + .data_len = 3, + .medium_type = 0, + .device_specific_para = 0, + .block_descriptor_len = 0 // no block descriptor are included }; ret = sizeof(mode_resp); @@ -313,8 +312,8 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u p_csw->data_residue = 0; /*------------- Parse command and prepare DATA -------------*/ - p_msc->stage = MSC_STAGE_DATA; - p_msc->data_len = p_cbw->xfer_bytes; + p_msc->stage = MSC_STAGE_DATA; + p_msc->total_len = p_cbw->total_bytes; p_msc->xferred_len = 0; if (SCSI_CMD_READ_10 == p_cbw->command[0]) @@ -331,12 +330,12 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u // 1. Zero : Invoke app callback, skip DATA and move to STATUS stage // 2. OUT : queue transfer (invoke app callback after done) // 3. IN : invoke app callback to get response - if ( p_cbw->xfer_bytes == 0) + if ( p_cbw->total_bytes == 0) { int32_t const cb_result = tud_msc_scsi_cb(p_cbw->lun, p_cbw->command, NULL, 0); - p_msc->data_len = 0; - p_msc->stage = MSC_STAGE_STATUS; + p_msc->total_len = 0; + p_msc->stage = MSC_STAGE_STATUS; if ( cb_result < 0 ) { @@ -351,7 +350,7 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u else if ( !BIT_TEST_(p_cbw->dir, 7) ) { // OUT transfer - TU_ASSERT( dcd_edpt_xfer(rhport, p_msc->ep_out, _mscd_buf, p_msc->data_len), TUSB_ERROR_DCD_EDPT_XFER ); + TU_ASSERT( dcd_edpt_xfer(rhport, p_msc->ep_out, _mscd_buf, p_msc->total_len), TUSB_ERROR_DCD_EDPT_XFER ); } else { @@ -364,21 +363,21 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u // Not an built-in command, invoke user callback if ( cb_result < 0 ) { - cb_result = tud_msc_scsi_cb(p_cbw->lun, p_cbw->command, _mscd_buf, p_msc->data_len); + cb_result = tud_msc_scsi_cb(p_cbw->lun, p_cbw->command, _mscd_buf, p_msc->total_len); } if ( cb_result > 0 ) { - p_msc->data_len = (uint32_t) cb_result; - p_csw->status = MSC_CSW_STATUS_PASSED; + p_msc->total_len = (uint32_t) cb_result; + p_csw->status = MSC_CSW_STATUS_PASSED; - TU_ASSERT( p_cbw->xfer_bytes >= p_msc->data_len, TUSB_ERROR_INVALID_PARA ); // cannot return more than host expect - TU_ASSERT( dcd_edpt_xfer(rhport, p_msc->ep_in, _mscd_buf, p_msc->data_len), TUSB_ERROR_DCD_EDPT_XFER ); + TU_ASSERT( p_cbw->total_bytes >= p_msc->total_len, TUSB_ERROR_INVALID_PARA ); // cannot return more than host expect + TU_ASSERT( dcd_edpt_xfer(rhport, p_msc->ep_in, _mscd_buf, p_msc->total_len), TUSB_ERROR_DCD_EDPT_XFER ); }else { - p_msc->data_len = 0; - p_csw->status = MSC_CSW_STATUS_FAILED; - p_msc->stage = MSC_STAGE_STATUS; + p_msc->total_len = 0; + p_csw->status = MSC_CSW_STATUS_FAILED; + p_msc->stage = MSC_STAGE_STATUS; tud_msc_set_sense(p_cbw->lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00); // Sense = Invalid Command Operation dcd_edpt_stall(rhport, p_msc->ep_in); @@ -393,7 +392,7 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u { if ( SCSI_CMD_WRITE_10 != p_cbw->command[0] ) { - int32_t cb_result = tud_msc_scsi_cb(p_cbw->lun, p_cbw->command, _mscd_buf, p_msc->data_len); + int32_t cb_result = tud_msc_scsi_cb(p_cbw->lun, p_cbw->command, _mscd_buf, p_msc->total_len); if ( cb_result < 0 ) { @@ -406,7 +405,7 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u } else { - uint16_t const block_sz = p_cbw->xfer_bytes / rdwr10_get_blockcount(p_cbw->command); + uint16_t const block_sz = p_cbw->total_bytes / rdwr10_get_blockcount(p_cbw->command); // Adjust lba with transferred bytes uint32_t const lba = rdwr10_get_lba(p_cbw->command) + (p_msc->xferred_len / block_sz); @@ -417,7 +416,7 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u if ( nbytes < 0 ) { // negative means error -> skip to status phase, status in CSW set to failed - p_csw->data_residue = p_cbw->xfer_bytes - p_msc->xferred_len; + p_csw->data_residue = p_cbw->total_bytes - p_msc->xferred_len; p_csw->status = MSC_CSW_STATUS_FAILED; p_msc->stage = MSC_STAGE_STATUS; @@ -450,7 +449,7 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u // Accumulate data so far p_msc->xferred_len += xferred_bytes; - if ( p_msc->xferred_len >= p_msc->data_len ) + if ( p_msc->xferred_len >= p_msc->total_len ) { // Data Stage is complete p_msc->stage = MSC_STAGE_STATUS; @@ -523,13 +522,13 @@ static void proc_read10_cmd(uint8_t rhport, mscd_interface_t* p_msc) msc_cbw_t const * p_cbw = &p_msc->cbw; msc_csw_t * p_csw = &p_msc->csw; - uint16_t const block_sz = p_cbw->xfer_bytes / rdwr10_get_blockcount(p_cbw->command); + uint16_t const block_sz = p_cbw->total_bytes / rdwr10_get_blockcount(p_cbw->command); // Adjust lba with transferred bytes uint32_t const lba = rdwr10_get_lba(p_cbw->command) + (p_msc->xferred_len / block_sz); // remaining bytes capped at class buffer - int32_t nbytes = (int32_t) tu_min32(sizeof(_mscd_buf), p_cbw->xfer_bytes-p_msc->xferred_len); + int32_t nbytes = (int32_t) tu_min32(sizeof(_mscd_buf), p_cbw->total_bytes-p_msc->xferred_len); // Application can consume smaller bytes nbytes = tud_msc_read10_cb(p_cbw->lun, lba, p_msc->xferred_len % block_sz, _mscd_buf, (uint32_t) nbytes); @@ -537,7 +536,7 @@ static void proc_read10_cmd(uint8_t rhport, mscd_interface_t* p_msc) if ( nbytes < 0 ) { // negative means error -> pipe is stalled & status in CSW set to failed - p_csw->data_residue = p_cbw->xfer_bytes - p_msc->xferred_len; + p_csw->data_residue = p_cbw->total_bytes - p_msc->xferred_len; p_csw->status = MSC_CSW_STATUS_FAILED; tud_msc_set_sense(p_cbw->lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00); // Sense = Invalid Command Operation @@ -559,7 +558,7 @@ static void proc_write10_cmd(uint8_t rhport, mscd_interface_t* p_msc) msc_cbw_t const * p_cbw = &p_msc->cbw; // remaining bytes capped at class buffer - int32_t nbytes = (int32_t) tu_min32(sizeof(_mscd_buf), p_cbw->xfer_bytes-p_msc->xferred_len); + int32_t nbytes = (int32_t) tu_min32(sizeof(_mscd_buf), p_cbw->total_bytes-p_msc->xferred_len); // Write10 callback will be called later when usb transfer complete TU_ASSERT( dcd_edpt_xfer(rhport, p_msc->ep_out, _mscd_buf, nbytes), ); -- cgit v1.3.1 From 55427606ef7fbdafa5a9da6b8a0f798dcb619817 Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 24 Oct 2018 00:44:26 +0700 Subject: replace dcd_xfer_complete by dcd_xfer_complete() --- src/class/msc/msc_device.c | 8 ++--- src/common/tusb_types.h | 3 -- src/device/dcd.h | 26 +++++++++++---- src/device/usbd.c | 46 ++++++++++---------------- src/portable/nordic/nrf5x/dcd_nrf5x.c | 16 ++++----- src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c | 22 ++++++------ 6 files changed, 59 insertions(+), 62 deletions(-) (limited to 'src/class') diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index 4d2f9249c..b050ea705 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -304,7 +304,7 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u // Complete IN while waiting for CMD is usually Status of previous SCSI op, ignore it if(ep_addr != p_msc->ep_out) return TUSB_ERROR_NONE; - TU_ASSERT( event == TUSB_EVENT_XFER_COMPLETE && + TU_ASSERT( event == DCD_XFER_SUCCESS && xferred_bytes == sizeof(msc_cbw_t) && p_cbw->signature == MSC_CBW_SIGNATURE, TUSB_ERROR_INVALID_PARA ); p_csw->signature = MSC_CSW_SIGNATURE; @@ -434,7 +434,7 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u } // simulate an transfer complete with adjusted parameters --> this driver callback will fired again - dcd_xfer_complete(rhport, p_msc->ep_out, xferred_bytes-nbytes, true); + dcd_event_xfer_complete(rhport, p_msc->ep_out, xferred_bytes-nbytes, DCD_XFER_SUCCESS, false); return TUSB_ERROR_NONE; // skip the rest } @@ -483,7 +483,7 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u if ( dcd_edpt_stalled(rhport, p_msc->ep_in) || dcd_edpt_stalled(rhport, p_msc->ep_out) ) { // simulate an transfer complete with adjusted parameters --> this driver callback will fired again - dcd_xfer_complete(rhport, p_msc->ep_out, 0, true); + dcd_event_xfer_complete(rhport, p_msc->ep_out, 0, DCD_XFER_SUCCESS, false); } else { @@ -545,7 +545,7 @@ static void proc_read10_cmd(uint8_t rhport, mscd_interface_t* p_msc) else if ( nbytes == 0 ) { // zero means not ready -> simulate an transfer complete so that this driver callback will fired again - dcd_xfer_complete(rhport, p_msc->ep_in, 0, true); + dcd_event_xfer_complete(rhport, p_msc->ep_in, 0, DCD_XFER_SUCCESS, false); } else { diff --git a/src/common/tusb_types.h b/src/common/tusb_types.h index ee9e849bf..8ce334e55 100644 --- a/src/common/tusb_types.h +++ b/src/common/tusb_types.h @@ -197,9 +197,6 @@ typedef enum TUSB_EVENT_XFER_COMPLETE, TUSB_EVENT_XFER_ERROR, TUSB_EVENT_XFER_STALLED, - - TUSB_EVENT_BUS_RESET, // TODO refractor - TUSB_EVENT_SETUP_RECEIVED, }tusb_event_t; enum { diff --git a/src/device/dcd.h b/src/device/dcd.h index 5a28296cd..662496701 100644 --- a/src/device/dcd.h +++ b/src/device/dcd.h @@ -49,6 +49,13 @@ extern "C" { #endif +enum +{ + DCD_XFER_SUCCESS = 0, + DCD_XFER_FAILED, + DCD_XFER_STALLED +}; + typedef enum { DCD_EVENT_BUS_RESET = 1, @@ -103,15 +110,22 @@ void dcd_disconnect (uint8_t rhport) ATTR_WEAK; /* Event Function * Called by DCD to notify USBD *------------------------------------------------------------------*/ -void dcd_xfer_complete (uint8_t rhport, uint8_t ep_addr, uint32_t xferred_bytes, bool succeeded); +void dcd_event_handler(dcd_event_t const * event, bool in_isr); -static inline void dcd_control_complete(uint8_t rhport, uint32_t xferred_bytes) +static inline void dcd_event_xfer_complete(uint8_t rhport, uint8_t ep_addr, uint32_t xferred_bytes, uint8_t result, bool in_isr) { - // all control complete is successful !! - dcd_xfer_complete(rhport, 0, xferred_bytes, true); -} + dcd_event_t event = + { + .rhport = 0, + .event_id = DCD_EVENT_XFER_COMPLETE, + }; -void dcd_event_handler(dcd_event_t const * event, bool in_isr); + event.xfer_complete.ep_addr = ep_addr; + event.xfer_complete.len = xferred_bytes; + event.xfer_complete.result = result; + + dcd_event_handler(&event, true); +} /*------------------------------------------------------------------*/ /* Endpoint API diff --git a/src/device/usbd.c b/src/device/usbd.c index 58581d609..f35671f17 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -164,7 +164,7 @@ static osal_queue_t _usbd_q; /*------------- control transfer semaphore -------------*/ static osal_semaphore_def_t _usbd_sem_def; -/*static*/ osal_semaphore_t _usbd_ctrl_sem; +osal_semaphore_t _usbd_ctrl_sem; //--------------------------------------------------------------------+ // INTERNAL FUNCTION @@ -532,34 +532,6 @@ static void mark_interface_endpoint(uint8_t const* p_desc, uint16_t desc_len, ui //--------------------------------------------------------------------+ // USBD-DCD Callback API //--------------------------------------------------------------------+ -void dcd_xfer_complete(uint8_t rhport, uint8_t ep_addr, uint32_t xferred_bytes, bool succeeded) -{ - if (ep_addr == 0 ) - { - // Control Transfer - (void) rhport; - (void) succeeded; - - // only signal data stage, skip status (zero byte) - if (xferred_bytes) osal_semaphore_post( _usbd_ctrl_sem, true); - }else - { - dcd_event_t event = - { - .rhport = rhport, - .event_id = DCD_EVENT_XFER_COMPLETE, - }; - - event.xfer_complete.ep_addr = ep_addr; - event.xfer_complete.len = xferred_bytes; - event.xfer_complete.result = succeeded ? TUSB_EVENT_XFER_COMPLETE : TUSB_EVENT_XFER_ERROR; - - osal_queue_send(_usbd_q, &event, true); - } - - TU_ASSERT(succeeded, ); -} - void dcd_event_handler(dcd_event_t const * event, bool in_isr) { uint8_t const rhport = event->rhport; @@ -603,6 +575,22 @@ void dcd_event_handler(dcd_event_t const * event, bool in_isr) osal_queue_send(_usbd_q, event, in_isr); break; + case DCD_EVENT_XFER_COMPLETE: + if (event->xfer_complete.ep_addr == 0) + { + // only signal data stage, skip status (zero byte) + if (event->xfer_complete.len) + { + (void) event->xfer_complete.result; // TODO handle control error/stalled + osal_semaphore_post( _usbd_ctrl_sem, true); + } + }else + { + osal_queue_send(_usbd_q, event, true); + } + TU_ASSERT(event->xfer_complete.result == DCD_XFER_SUCCESS,); + break; + default: break; } } diff --git a/src/portable/nordic/nrf5x/dcd_nrf5x.c b/src/portable/nordic/nrf5x/dcd_nrf5x.c index f04acb6e3..d1ca91173 100644 --- a/src/portable/nordic/nrf5x/dcd_nrf5x.c +++ b/src/portable/nordic/nrf5x/dcd_nrf5x.c @@ -414,14 +414,12 @@ void USBD_IRQHandler(void) } } - dcd_event_t event = { .rhport = 0 }; - /*------------- Interrupt Processing -------------*/ if ( int_status & USBD_INTEN_USBRESET_Msk ) { bus_reset(); - event.event_id = DCD_EVENT_BUS_RESET; + dcd_event_t event = { .rhport = 0, .event_id = DCD_EVENT_BUS_RESET }; dcd_event_handler(&event, true); } @@ -439,7 +437,7 @@ void USBD_IRQHandler(void) NRF_USBD->WINDEXL , NRF_USBD->WINDEXH , NRF_USBD->WLENGTHL, NRF_USBD->WLENGTHH }; - event.event_id = DCD_EVENT_SETUP_RECEIVED; + dcd_event_t event = { .rhport = 0, .event_id = DCD_EVENT_SETUP_RECEIVED }; memcpy(&event.setup_received, setup, 8); dcd_event_handler(&event, true); @@ -461,7 +459,7 @@ void USBD_IRQHandler(void) }else { // Control IN complete - dcd_control_complete(0, _dcd.control.actual_len); + dcd_event_xfer_complete(0, 0, _dcd.control.actual_len, DCD_XFER_SUCCESS, true); } } } @@ -475,7 +473,7 @@ void USBD_IRQHandler(void) }else { // Control OUT complete - dcd_control_complete(0, _dcd.control.actual_len); + dcd_event_xfer_complete(0, 0, _dcd.control.actual_len, DCD_XFER_SUCCESS, true); } } @@ -506,7 +504,7 @@ void USBD_IRQHandler(void) xfer->total_len = xfer->actual_len; // BULK/INT OUT complete - dcd_xfer_complete(0, epnum, xfer->actual_len, true); + dcd_event_xfer_complete(0, epnum, xfer->actual_len, DCD_XFER_SUCCESS, true); } } @@ -535,7 +533,7 @@ void USBD_IRQHandler(void) } else { // Bulk/Int IN complete - dcd_xfer_complete(0, epnum | TUSB_DIR_IN_MASK, xfer->actual_len, true); + dcd_event_xfer_complete(0, epnum | TUSB_DIR_IN_MASK, xfer->actual_len, DCD_XFER_SUCCESS, true); } } } @@ -563,7 +561,7 @@ void USBD_IRQHandler(void) // SOF interrupt if ( int_status & USBD_INTEN_SOF_Msk ) { - event.event_id = DCD_EVENT_SOF; + dcd_event_t event = { .rhport = 0, .event_id = DCD_EVENT_SOF }; dcd_event_handler(&event, true); } } diff --git a/src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c b/src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c index 6e1d96168..8d53759e6 100644 --- a/src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c +++ b/src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c @@ -398,10 +398,11 @@ void xfer_complete_isr(uint8_t rhport, uint32_t reg_complete) if (p_qtd->int_on_complete) { - bool succeeded = ( p_qtd->xact_err || p_qtd->halted || p_qtd->buffer_err ) ? false : true; + uint8_t result = p_qtd->halted ? DCD_XFER_STALLED : + ( p_qtd->xact_err ||p_qtd->buffer_err ) ? DCD_XFER_FAILED : DCD_XFER_SUCCESS; uint8_t ep_addr = edpt_phy2addr(ep_idx); - dcd_xfer_complete(rhport, ep_addr, p_qtd->expected_bytes - p_qtd->total_bytes, succeeded); // only number of bytes in the IOC qtd + dcd_event_xfer_complete(rhport, ep_addr, p_qtd->expected_bytes - p_qtd->total_bytes, result, true); // only number of bytes in the IOC qtd } } } @@ -418,13 +419,12 @@ void hal_dcd_isr(uint8_t rhport) if (int_status == 0) return;// disabled interrupt sources - dcd_event_t event = { .rhport = rhport }; if (int_status & INT_MASK_RESET) { bus_reset(rhport); - event.event_id = DCD_EVENT_BUS_RESET; + dcd_event_t event = { .rhport = rhport, .event_id = DCD_EVENT_BUS_RESET }; dcd_event_handler(&event, true); } @@ -434,7 +434,7 @@ void hal_dcd_isr(uint8_t rhport) { // Note: Host may delay more than 3 ms before and/or after bus reset before doing enumeration. if ((lpc_usb->DEVICEADDR >> 25) & 0x0f) { - event.event_id = DCD_EVENT_SUSPENDED; + dcd_event_t event = { .rhport = rhport, .event_id = DCD_EVENT_SUSPENDED }; dcd_event_handler(&event, true); } } @@ -445,7 +445,7 @@ void hal_dcd_isr(uint8_t rhport) // { // if ( !(lpc_usb->PORTSC1_D & PORTSC_CURRENT_CONNECT_STATUS_MASK) ) // { -// event.event_id = DCD_EVENT_UNPLUGGED; +// dcd_event_t event = { .rhport = rhport, .event_id = DCD_EVENT_UNPLUGGED }; // dcd_event_handler(&event, true); // } // } @@ -463,7 +463,7 @@ void hal_dcd_isr(uint8_t rhport) // 23.10.10.2 Operational model for setup transfers lpc_usb->ENDPTSETUPSTAT = lpc_usb->ENDPTSETUPSTAT;// acknowledge - event.event_id = DCD_EVENT_SETUP_RECEIVED; + dcd_event_t event = { .rhport = rhport, .event_id = DCD_EVENT_SETUP_RECEIVED }; event.setup_received = p_dcd->qhd[0].setup_request; dcd_event_handler(&event, true); @@ -480,10 +480,10 @@ void hal_dcd_isr(uint8_t rhport) if ( p_qtd->int_on_complete ) { - bool succeeded = ( p_qtd->xact_err || p_qtd->halted || p_qtd->buffer_err ) ? false : true; - (void) succeeded; + uint8_t result = p_qtd->halted ? DCD_XFER_STALLED : + ( p_qtd->xact_err ||p_qtd->buffer_err ) ? DCD_XFER_FAILED : DCD_XFER_SUCCESS; - dcd_control_complete(rhport, p_qtd->expected_bytes - p_qtd->total_bytes); + dcd_event_xfer_complete(rhport, 0, p_qtd->expected_bytes - p_qtd->total_bytes, result, true); } } @@ -496,7 +496,7 @@ void hal_dcd_isr(uint8_t rhport) if (int_status & INT_MASK_SOF) { - event.event_id = DCD_EVENT_SOF; + dcd_event_t event = { .rhport = rhport, .event_id = DCD_EVENT_SOF }; dcd_event_handler(&event, true); } -- cgit v1.3.1 From bfa10016ae353779f7b94da31156ac997062322a Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 24 Oct 2018 12:37:43 +0700 Subject: rename verify_breakpoint to TU_BREAKPOINT --- src/class/msc/msc_device.c | 2 +- src/common/tusb_verify.h | 16 ++++++++-------- src/device/usbd.c | 2 +- src/host/ehci/ehci.c | 2 +- src/osal/osal_none.h | 8 ++++---- 5 files changed, 15 insertions(+), 15 deletions(-) (limited to 'src/class') diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index b050ea705..5a047b016 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -468,7 +468,7 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u }else { // No other command take more than one transfer yet -> unlikely error - verify_breakpoint(); + TU_BREAKPOINT(); } } break; diff --git a/src/common/tusb_verify.h b/src/common/tusb_verify.h index 41c2b5be1..1cb8443bc 100644 --- a/src/common/tusb_verify.h +++ b/src/common/tusb_verify.h @@ -74,14 +74,14 @@ // Halt CPU (breakpoint) when hitting error, only apply for Cortex M3, M4, M7 #if defined(__ARM_ARCH_7M__) || defined (__ARM_ARCH_7EM__) -#define verify_breakpoint() \ +#define TU_BREAKPOINT() \ do {\ volatile uint32_t* ARM_CM_DHCSR = ((volatile uint32_t*) 0xE000EDF0UL); /* Cortex M CoreDebug->DHCSR */ \ if ( (*ARM_CM_DHCSR) & 1UL ) __asm("BKPT #0\n"); /* Only halt mcu if debugger is attached */\ } while(0) #else -#define verify_breakpoint() +#define TU_BREAKPOINT() #endif /*------------------------------------------------------------------*/ @@ -157,21 +157,21 @@ /*------------------------------------------------------------------*/ /* ASSERT - * basically TU_VERIFY with verify_breakpoint() as handler + * basically TU_VERIFY with TU_BREAKPOINT() as handler * - 1 arg : return false if failed * - 2 arg : return error if failed *------------------------------------------------------------------*/ -#define ASSERT_1ARGS(_cond) TU_VERIFY_DEFINE(_cond, _MESS_FAILED(); verify_breakpoint(), false) -#define ASSERT_2ARGS(_cond, _ret) TU_VERIFY_DEFINE(_cond, _MESS_FAILED(); verify_breakpoint(), _ret) +#define ASSERT_1ARGS(_cond) TU_VERIFY_DEFINE(_cond, _MESS_FAILED(); TU_BREAKPOINT(), false) +#define ASSERT_2ARGS(_cond, _ret) TU_VERIFY_DEFINE(_cond, _MESS_FAILED(); TU_BREAKPOINT(), _ret) #define TU_ASSERT(...) GET_3RD_ARG(__VA_ARGS__, ASSERT_2ARGS, ASSERT_1ARGS)(__VA_ARGS__) /*------------------------------------------------------------------*/ /* ASSERT Error - * basically TU_VERIFY Error with verify_breakpoint() as handler + * basically TU_VERIFY Error with TU_BREAKPOINT() as handler *------------------------------------------------------------------*/ -#define ASERT_ERR_1ARGS(_error) TU_VERIFY_ERR_DEF2(_error, verify_breakpoint()) -#define ASERT_ERR_2ARGS(_error, _ret) TU_VERIFY_ERR_DEF3(_error, verify_breakpoint(), _ret) +#define ASERT_ERR_1ARGS(_error) TU_VERIFY_ERR_DEF2(_error, TU_BREAKPOINT()) +#define ASERT_ERR_2ARGS(_error, _ret) TU_VERIFY_ERR_DEF3(_error, TU_BREAKPOINT(), _ret) #define TU_ASSERT_ERR(...) GET_3RD_ARG(__VA_ARGS__, ASERT_ERR_2ARGS, ASERT_ERR_1ARGS)(__VA_ARGS__) diff --git a/src/device/usbd.c b/src/device/usbd.c index f35671f17..1e96983b1 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -274,7 +274,7 @@ static tusb_error_t usbd_main_st(void) } else { - verify_breakpoint(); + TU_BREAKPOINT(); } } diff --git a/src/host/ehci/ehci.c b/src/host/ehci/ehci.c index 99e7fdb65..c7ff70d70 100644 --- a/src/host/ehci/ehci.c +++ b/src/host/ehci/ehci.c @@ -646,7 +646,7 @@ static void qhd_xfer_error_isr(ehci_qhd_t * p_qhd) p_qhd->total_xferred_bytes += p_qhd->p_qtd_list_head->expected_bytes - p_qhd->p_qtd_list_head->total_bytes; -// if ( TUSB_EVENT_XFER_ERROR == error_event ) verify_breakpoint(); // TODO skip unplugged device +// if ( TUSB_EVENT_XFER_ERROR == error_event ) TU_BREAKPOINT(); // TODO skip unplugged device p_qhd->p_qtd_list_head->used = 0; // free QTD qtd_remove_1st_from_qhd(p_qhd); diff --git a/src/osal/osal_none.h b/src/osal/osal_none.h index 91848f221..783e4fd2e 100644 --- a/src/osal/osal_none.h +++ b/src/osal/osal_none.h @@ -113,11 +113,11 @@ static inline bool osal_task_create(osal_task_def_t* taskdef) //------------- Sub Task Assert -------------// #define STASK_RETURN(error) do { TASK_RESTART; return error; } while(0) -#define STASK_ASSERT_ERR(_err) TU_VERIFY_ERR_HDLR(_err, verify_breakpoint(); TASK_RESTART, TUSB_ERROR_FAILED) -#define STASK_ASSERT_ERR_HDLR(_err, _func) TU_VERIFY_ERR_HDLR(_err, verify_breakpoint(); _func; TASK_RESTART, TUSB_ERROR_FAILED ) +#define STASK_ASSERT_ERR(_err) TU_VERIFY_ERR_HDLR(_err, TU_BREAKPOINT(); TASK_RESTART, TUSB_ERROR_FAILED) +#define STASK_ASSERT_ERR_HDLR(_err, _func) TU_VERIFY_ERR_HDLR(_err, TU_BREAKPOINT(); _func; TASK_RESTART, TUSB_ERROR_FAILED ) -#define STASK_ASSERT(_cond) TU_VERIFY_HDLR(_cond, verify_breakpoint(); TASK_RESTART, TUSB_ERROR_FAILED) -#define STASK_ASSERT_HDLR(_cond, _func) TU_VERIFY_HDLR(_cond, verify_breakpoint(); _func; TASK_RESTART, TUSB_ERROR_FAILED) +#define STASK_ASSERT(_cond) TU_VERIFY_HDLR(_cond, TU_BREAKPOINT(); TASK_RESTART, TUSB_ERROR_FAILED) +#define STASK_ASSERT_HDLR(_cond, _func) TU_VERIFY_HDLR(_cond, TU_BREAKPOINT(); _func; TASK_RESTART, TUSB_ERROR_FAILED) //--------------------------------------------------------------------+ // QUEUE API -- cgit v1.3.1 From cb9bcce6a21c28e8bf0fa4259ebbb55614f05aca Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 2 Nov 2018 18:40:47 +0700 Subject: use mutex for cdc device fifo --- src/class/cdc/cdc_device.c | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) (limited to 'src/class') diff --git a/src/class/cdc/cdc_device.c b/src/class/cdc/cdc_device.c index 06530bc7a..a6f1f1fbb 100644 --- a/src/class/cdc/cdc_device.c +++ b/src/class/cdc/cdc_device.c @@ -44,7 +44,6 @@ //--------------------------------------------------------------------+ // INCLUDE //--------------------------------------------------------------------+ -#include "common/tusb_common.h" #include "cdc_device.h" #include "device/usbd_pvt.h" @@ -72,13 +71,16 @@ typedef struct uint8_t rx_ff_buf[CFG_TUD_CDC_RX_BUFSIZE]; uint8_t tx_ff_buf[CFG_TUD_CDC_TX_BUFSIZE]; + osal_mutex_def_t rx_ff_mutex; + osal_mutex_def_t tx_ff_mutex; + // Endpoint Transfer buffer CFG_TUSB_MEM_ALIGN uint8_t epout_buf[CFG_TUD_CDC_EPSIZE]; CFG_TUSB_MEM_ALIGN uint8_t epin_buf[CFG_TUD_CDC_EPSIZE]; }cdcd_interface_t; -#define ITF_BUS_RESET_SZ offsetof(cdcd_interface_t, wanted_char) +#define ITF_MEM_RESET_SIZE offsetof(cdcd_interface_t, wanted_char) //--------------------------------------------------------------------+ // INTERNAL OBJECT & FUNCTION DECLARATION @@ -189,17 +191,22 @@ void cdcd_init(void) for(uint8_t i=0; iwanted_char = -1; // default line coding is : stop bit = 1, parity = none, data bits = 8 - _cdcd_itf[i].line_coding.bit_rate = 115200; - _cdcd_itf[i].line_coding.stop_bits = 0; - _cdcd_itf[i].line_coding.parity = 0; - _cdcd_itf[i].line_coding.data_bits = 8; + ser->line_coding.bit_rate = 115200; + ser->line_coding.stop_bits = 0; + ser->line_coding.parity = 0; + ser->line_coding.data_bits = 8; // config fifo - tu_fifo_config(&_cdcd_itf[i].rx_ff, _cdcd_itf[i].rx_ff_buf, CFG_TUD_CDC_RX_BUFSIZE, 1, true); - tu_fifo_config(&_cdcd_itf[i].tx_ff, _cdcd_itf[i].tx_ff_buf, CFG_TUD_CDC_TX_BUFSIZE, 1, false); + tu_fifo_config(&ser->rx_ff, ser->rx_ff_buf, CFG_TUD_CDC_RX_BUFSIZE, 1, true); + tu_fifo_config_mutex(&ser->rx_ff, osal_mutex_create(&ser->rx_ff_mutex)); + + tu_fifo_config(&ser->tx_ff, ser->tx_ff_buf, CFG_TUD_CDC_TX_BUFSIZE, 1, false); + tu_fifo_config_mutex(&ser->tx_ff, osal_mutex_create(&ser->tx_ff_mutex)); } } @@ -209,7 +216,7 @@ void cdcd_reset(uint8_t rhport) for(uint8_t i=0; i Date: Wed, 24 Oct 2018 23:55:10 -0700 Subject: Add SAMD21 and SAMD51 support for CircuitPython. The ProtoThreads style subtasks were removed because it led to extremely unclear control flow. RTOSes can be used if threading is needed. Also added some additional functionality to MSC to support dynamic LUNs and read-only LUNs. --- src/class/cdc/cdc_device.c | 7 +- src/class/hid/hid_device.c | 9 +- src/class/msc/msc.h | 4 +- src/class/msc/msc_device.c | 83 ++++---- src/class/msc/msc_device.h | 43 +++- src/device/dcd.h | 27 +-- src/device/usbd.c | 82 +++++--- src/device/usbd_pvt.h | 15 +- src/osal/osal_freertos.h | 1 - src/osal/osal_none.h | 103 +++------- src/portable/microchip/samd21/dcd.c | 341 ++++++++++++++++++++++++++++++++ src/portable/microchip/samd21/hal.c | 82 ++++++++ src/portable/microchip/samd51/dcd.c | 360 ++++++++++++++++++++++++++++++++++ src/portable/microchip/samd51/hal.c | 88 +++++++++ src/portable/nordic/nrf5x/dcd_nrf5x.c | 10 +- src/tusb_option.h | 2 + 16 files changed, 1050 insertions(+), 207 deletions(-) create mode 100644 src/portable/microchip/samd21/dcd.c create mode 100644 src/portable/microchip/samd21/hal.c create mode 100644 src/portable/microchip/samd51/dcd.c create mode 100644 src/portable/microchip/samd51/hal.c (limited to 'src/class') diff --git a/src/class/cdc/cdc_device.c b/src/class/cdc/cdc_device.c index a6f1f1fbb..f3d4622f8 100644 --- a/src/class/cdc/cdc_device.c +++ b/src/class/cdc/cdc_device.c @@ -289,8 +289,6 @@ tusb_error_t cdcd_open(uint8_t rhport, tusb_desc_interface_t const * p_interface tusb_error_t cdcd_control_request_st(uint8_t rhport, tusb_control_request_t const * p_request) { - OSAL_SUBTASK_BEGIN - //------------- Class Specific Request -------------// if (p_request->bmRequestType_bit.type != TUSB_REQ_TYPE_CLASS) return TUSB_ERROR_DCD_CONTROL_REQUEST_NOT_SUPPORT; @@ -301,7 +299,7 @@ tusb_error_t cdcd_control_request_st(uint8_t rhport, tusb_control_request_t cons if ( (CDC_REQUEST_GET_LINE_CODING == p_request->bRequest) || (CDC_REQUEST_SET_LINE_CODING == p_request->bRequest) ) { uint16_t len = tu_min16(sizeof(cdc_line_coding_t), p_request->wLength); - usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, &p_cdc->line_coding, len); + usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, (uint8_t*) &p_cdc->line_coding, len); // Invoke callback if (CDC_REQUEST_SET_LINE_CODING == p_request->bRequest) @@ -327,8 +325,7 @@ tusb_error_t cdcd_control_request_st(uint8_t rhport, tusb_control_request_t cons { dcd_control_stall(rhport); // stall unsupported request } - - OSAL_SUBTASK_END + return TUSB_ERROR_NONE; } tusb_error_t cdcd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, uint32_t xferred_bytes) diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index d8696f137..3e74950e6 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -407,8 +407,6 @@ tusb_error_t hidd_control_request_st(uint8_t rhport, tusb_control_request_t cons hidd_interface_t* p_hid = get_interface_by_itfnum( (uint8_t) p_request->wIndex ); TU_ASSERT(p_hid, TUSB_ERROR_FAILED); - OSAL_SUBTASK_BEGIN - //------------- STD Request -------------// if (p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD) { @@ -419,7 +417,7 @@ tusb_error_t hidd_control_request_st(uint8_t rhport, tusb_control_request_t cons if (p_request->bRequest == TUSB_REQ_GET_DESCRIPTOR && desc_type == HID_DESC_TYPE_REPORT) { // use device control buffer - STASK_ASSERT ( p_hid->desc_len <= CFG_TUD_CTRL_BUFSIZE ); + TU_ASSERT ( p_hid->desc_len <= CFG_TUD_CTRL_BUFSIZE ); memcpy(_usbd_ctrl_buf, p_hid->desc_report, p_hid->desc_len); usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, _usbd_ctrl_buf, p_hid->desc_len); @@ -447,7 +445,7 @@ tusb_error_t hidd_control_request_st(uint8_t rhport, tusb_control_request_t cons xferlen = p_request->wLength; } - STASK_ASSERT( xferlen > 0 ); + TU_ASSERT( xferlen > 0 ); usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, p_hid->report_buf, xferlen); } else if ( HID_REQ_CONTROL_SET_REPORT == p_request->bRequest ) @@ -492,8 +490,7 @@ tusb_error_t hidd_control_request_st(uint8_t rhport, tusb_control_request_t cons { dcd_control_stall(rhport); } - - OSAL_SUBTASK_END + return TUSB_ERROR_NONE; } tusb_error_t hidd_xfer_cb(uint8_t rhport, uint8_t edpt_addr, tusb_event_t event, uint32_t xferred_bytes) diff --git a/src/class/msc/msc.h b/src/class/msc/msc.h index 59df6bed6..a0abc2501 100644 --- a/src/class/msc/msc.h +++ b/src/class/msc/msc.h @@ -279,11 +279,13 @@ typedef struct ATTR_PACKED TU_VERIFY_STATIC( sizeof(scsi_mode_sense6_t) == 6, "size is not correct"); +// This is only a Mode parameter header(6). typedef struct ATTR_PACKED { uint8_t data_len; uint8_t medium_type; - uint8_t device_specific_para; + bool write_protected : 1; + uint8_t reserved : 7; uint8_t block_descriptor_len; } scsi_mode_sense6_resp_t; diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index 5a047b016..aa9ebbbc9 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -59,31 +59,7 @@ enum MSC_STAGE_STATUS }; -typedef struct { - CFG_TUSB_MEM_ALIGN msc_cbw_t cbw; - -//#if defined (__ICCARM__) && (CFG_TUSB_MCU == OPT_MCU_LPC11UXX || CFG_TUSB_MCU == OPT_MCU_LPC13UXX) -// uint8_t padding1[64-sizeof(msc_cbw_t)]; // IAR cannot align struct's member -//#endif - - CFG_TUSB_MEM_ALIGN msc_csw_t csw; - - uint8_t itf_num; - uint8_t ep_in; - uint8_t ep_out; - - // Bulk Only Transfer (BOT) Protocol - uint8_t stage; - uint32_t total_len; - uint32_t xferred_len; // numbered of bytes transferred so far in the Data Stage - - // Sense Response Data - uint8_t sense_key; - uint8_t add_sense_code; - uint8_t add_sense_qualifier; -}mscd_interface_t; - -CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN static mscd_interface_t _mscd_itf; +CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN mscd_interface_t _mscd_itf; CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN static uint8_t _mscd_buf[CFG_TUD_MSC_BUFSIZE]; //--------------------------------------------------------------------+ @@ -172,8 +148,6 @@ tusb_error_t mscd_open(uint8_t rhport, tusb_desc_interface_t const * p_desc_itf, tusb_error_t mscd_control_request_st(uint8_t rhport, tusb_control_request_t const * p_request) { - OSAL_SUBTASK_BEGIN - TU_ASSERT(p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS, TUSB_ERROR_DCD_CONTROL_REQUEST_NOT_SUPPORT); if(MSC_REQ_RESET == p_request->bRequest) @@ -189,9 +163,18 @@ tusb_error_t mscd_control_request_st(uint8_t rhport, tusb_control_request_t cons { dcd_control_stall(rhport); // stall unsupported request } + return TUSB_ERROR_NONE; +} - OSAL_SUBTASK_END +// For backwards compatibility we support static block counts. +#if defined(CFG_TUD_MSC_BLOCK_NUM) && defined(CFG_TUD_MSC_BLOCK_SZ) +ATTR_WEAK bool tud_lun_capacity_cb(uint8_t lun, uint32_t* last_valid_sector, uint16_t* block_size) { + (void) lun; + *last_valid_sector = CFG_TUD_MSC_BLOCK_NUM-1; + *block_size = CFG_TUD_MSC_BLOCK_SZ; + return true; } +#endif // return length of response (copied to buffer), -1 if it is not an built-in commands int32_t proc_builtin_scsi(msc_cbw_t const * p_cbw, uint8_t* buffer, uint32_t bufsize) @@ -202,11 +185,13 @@ int32_t proc_builtin_scsi(msc_cbw_t const * p_cbw, uint8_t* buffer, uint32_t buf { case SCSI_CMD_READ_CAPACITY_10: { - scsi_read_capacity10_resp_t read_capa10 = - { - .last_lba = ENDIAN_BE(CFG_TUD_MSC_BLOCK_NUM-1), // read capacity - .block_size = ENDIAN_BE(CFG_TUD_MSC_BLOCK_SZ) - }; + scsi_read_capacity10_resp_t read_capa10; + + uint32_t last_valid_sector; + uint16_t block_size; + tud_lun_capacity_cb(p_cbw->lun, &last_valid_sector, &block_size); + read_capa10.last_lba = ENDIAN_BE(last_valid_sector); // read capacity + read_capa10.block_size = ENDIAN_BE(block_size); ret = sizeof(read_capa10); memcpy(buffer, &read_capa10, ret); @@ -218,11 +203,17 @@ int32_t proc_builtin_scsi(msc_cbw_t const * p_cbw, uint8_t* buffer, uint32_t buf scsi_read_format_capacity_data_t read_fmt_capa = { .list_length = 8, - .block_num = ENDIAN_BE(CFG_TUD_MSC_BLOCK_NUM), // write capacity + .block_num = 0, .descriptor_type = 2, // formatted media - .block_size_u16 = ENDIAN_BE16(CFG_TUD_MSC_BLOCK_SZ) + .block_size_u16 = 0 }; + uint32_t last_valid_sector; + uint16_t block_size; + tud_lun_capacity_cb(p_cbw->lun, &last_valid_sector, &block_size); + read_fmt_capa.block_num = ENDIAN_BE(last_valid_sector+1); + read_fmt_capa.block_size_u16 = ENDIAN_BE16(block_size); + ret = sizeof(read_fmt_capa); memcpy(buffer, &read_fmt_capa, ret); } @@ -251,13 +242,21 @@ int32_t proc_builtin_scsi(msc_cbw_t const * p_cbw, uint8_t* buffer, uint32_t buf case SCSI_CMD_MODE_SENSE_6: { - scsi_mode_sense6_resp_t const mode_resp = { - .data_len = 3, - .medium_type = 0, - .device_specific_para = 0, - .block_descriptor_len = 0 // no block descriptor are included + scsi_mode_sense6_resp_t mode_resp = + { + .data_len = 3, + .medium_type = 0, + .write_protected = false, + .reserved = 0, + .block_descriptor_len = 0 // no block descriptor are included }; + bool writable = true; + if (tud_msc_is_writable_cb) { + writable = tud_msc_is_writable_cb(p_cbw->lun); + } + mode_resp.write_protected = !writable; + ret = sizeof(mode_resp); memcpy(buffer, &mode_resp, ret); } @@ -291,7 +290,7 @@ int32_t proc_builtin_scsi(msc_cbw_t const * p_cbw, uint8_t* buffer, uint32_t buf return ret; } -tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, uint32_t xferred_bytes) +tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, uint8_t event, uint32_t xferred_bytes) { mscd_interface_t* p_msc = &_mscd_itf; msc_cbw_t const * p_cbw = &p_msc->cbw; @@ -425,7 +424,7 @@ tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, u }else { // Application consume less than what we got (including zero) - if ( nbytes < xferred_bytes ) + if ( nbytes < (int32_t) xferred_bytes ) { if ( nbytes > 0 ) { diff --git a/src/class/msc/msc_device.h b/src/class/msc/msc_device.h index 8403dfed9..92ab4dde0 100644 --- a/src/class/msc/msc_device.h +++ b/src/class/msc/msc_device.h @@ -55,14 +55,6 @@ TU_VERIFY_STATIC(CFG_TUD_MSC_BUFSIZE < UINT16_MAX, "Size is not correct"); #error MSC Device: Incorrect setting of MAX LUN #endif -#ifndef CFG_TUD_MSC_BLOCK_NUM - #error CFG_TUD_MSC_BLOCK_NUM must be defined -#endif - -#ifndef CFG_TUD_MSC_BLOCK_SZ - #error CFG_TUD_MSC_BLOCK_SZ must be defined -#endif - #ifndef CFG_TUD_MSC_BUFSIZE #error CFG_TUD_MSC_BUFSIZE must be defined, value of CFG_TUD_MSC_BLOCK_SZ should work well, the more the better #endif @@ -89,6 +81,32 @@ TU_VERIFY_STATIC(CFG_TUD_MSC_BUFSIZE < UINT16_MAX, "Size is not correct"); extern "C" { #endif +typedef struct { + CFG_TUSB_MEM_ALIGN msc_cbw_t cbw; + +//#if defined (__ICCARM__) && (CFG_TUSB_MCU == OPT_MCU_LPC11UXX || CFG_TUSB_MCU == OPT_MCU_LPC13UXX) +// uint8_t padding1[64-sizeof(msc_cbw_t)]; // IAR cannot align struct's member +//#endif + + CFG_TUSB_MEM_ALIGN msc_csw_t csw; + + uint8_t itf_num; + uint8_t ep_in; + uint8_t ep_out; + + // Bulk Only Transfer (BOT) Protocol + uint8_t stage; + uint32_t total_len; + uint32_t xferred_len; // numbered of bytes transferred so far in the Data Stage + + // Sense Response Data + uint8_t sense_key; + uint8_t add_sense_code; + uint8_t add_sense_qualifier; +}mscd_interface_t; + +extern mscd_interface_t _mscd_itf; + /** \addtogroup ClassDriver_MSC * @{ * \defgroup MSC_Device Device @@ -138,7 +156,7 @@ int32_t tud_msc_read10_cb (uint8_t lun, uint32_t lba, uint32_t offset, void* buf * \retval negative Indicate error writing disk I/O. Tinyusb will \b STALL the corresponding * endpoint and return failed status in command status wrapper phase. */ -int32_t tud_msc_write10_cb (uint8_t lun, uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize); +int32_t tud_msc_write10_cb (uint8_t lun, uint32_t lba, uint32_t offset, uint8_t* buffer, uint32_t bufsize); /** * Callback invoked when received an SCSI command not in built-in list below. @@ -164,6 +182,12 @@ ATTR_WEAK void tud_msc_read10_complete_cb(uint8_t lun); ATTR_WEAK void tud_msc_write10_complete_cb(uint8_t lun); ATTR_WEAK void tud_msc_scsi_complete_cb(uint8_t lun, uint8_t const scsi_cmd[16]); +// Hook to make a mass storage device read-only. +ATTR_WEAK bool tud_msc_is_writable_cb(uint8_t lun); + +// Override for dynamic LUN sizes. +ATTR_WEAK bool tud_lun_capacity_cb(uint8_t lun, uint32_t* last_valid_sector, uint16_t* block_size); + /** @} */ /** @} */ @@ -185,4 +209,3 @@ void mscd_reset(uint8_t rhport); #endif #endif /* _TUSB_MSC_DEVICE_H_ */ - diff --git a/src/device/dcd.h b/src/device/dcd.h index 87837df20..c1715a5b7 100644 --- a/src/device/dcd.h +++ b/src/device/dcd.h @@ -113,32 +113,13 @@ void dcd_disconnect (uint8_t rhport) ATTR_WEAK; void dcd_event_handler(dcd_event_t const * event, bool in_isr); // helper to send bus signal event -static inline void dcd_event_bus_signal (uint8_t rhport, dcd_eventid_t eid, bool in_isr) -{ - dcd_event_t event = { .rhport = 0, .event_id = eid, }; - dcd_event_handler(&event, in_isr); -} +void dcd_event_bus_signal (uint8_t rhport, dcd_eventid_t eid, bool in_isr); // helper to send setup received -static inline void dcd_event_setup_recieved(uint8_t rhport, uint8_t const * setup, bool in_isr) -{ - dcd_event_t event = { .rhport = 0, .event_id = DCD_EVENT_SETUP_RECEIVED }; - memcpy(&event.setup_received, setup, 8); - - dcd_event_handler(&event, true); -} +void dcd_event_setup_received(uint8_t rhport, uint8_t const * setup, bool in_isr); // helper to send transfer complete event -static inline void dcd_event_xfer_complete (uint8_t rhport, uint8_t ep_addr, uint32_t xferred_bytes, uint8_t result, bool in_isr) -{ - dcd_event_t event = { .rhport = 0, .event_id = DCD_EVENT_XFER_COMPLETE }; - - event.xfer_complete.ep_addr = ep_addr; - event.xfer_complete.len = xferred_bytes; - event.xfer_complete.result = result; - - dcd_event_handler(&event, in_isr); -} +void dcd_event_xfer_complete (uint8_t rhport, uint8_t ep_addr, uint32_t xferred_bytes, uint8_t result, bool in_isr); /*------------------------------------------------------------------*/ @@ -167,7 +148,7 @@ static inline bool dcd_control_status(uint8_t rhport, uint8_t dir) static inline void dcd_control_stall(uint8_t rhport) { - dcd_edpt_stall(rhport, 0); + dcd_edpt_stall(rhport, 0 | TUSB_DIR_IN_MASK); } #ifdef __cplusplus diff --git a/src/device/usbd.c b/src/device/usbd.c index 1c2fa5d5d..8155b585f 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -239,25 +239,25 @@ void usbd_task( void* param) OSAL_TASK_END } +extern uint32_t setup_count; + static tusb_error_t usbd_main_st(void) { - static dcd_event_t event; - - OSAL_SUBTASK_BEGIN - + dcd_event_t event; + tusb_error_t err = TUSB_ERROR_NONE; // Loop until there is no more events in the queue - while (1) + while (_usbd_q->count > 0) { - uint32_t err; - - err = TUSB_ERROR_NONE; tu_memclr(&event, sizeof(dcd_event_t)); - osal_queue_receive(_usbd_q, &event, OSAL_TIMEOUT_WAIT_FOREVER, &err); + err = osal_queue_receive(_usbd_q, &event); + if (err != TUSB_ERROR_NONE) { + break; + } if ( DCD_EVENT_SETUP_RECEIVED == event.event_id ) { - STASK_INVOKE( proc_control_request_st(event.rhport, &event.setup_received), err ); + proc_control_request_st(event.rhport, &event.setup_received); } else if (DCD_EVENT_XFER_COMPLETE == event.event_id) { @@ -267,7 +267,7 @@ static tusb_error_t usbd_main_st(void) if (drv_id < USBD_CLASS_DRIVER_COUNT) { - usbd_class_drivers[drv_id].xfer_cb( event.rhport, ep_addr, (tusb_event_t) event.xfer_complete.result, event.xfer_complete.len); + usbd_class_drivers[drv_id].xfer_cb( event.rhport, ep_addr, event.xfer_complete.result, event.xfer_complete.len); } } else if (DCD_EVENT_BUS_RESET == event.event_id) @@ -304,7 +304,7 @@ static tusb_error_t usbd_main_st(void) } } - OSAL_SUBTASK_END + return err; } //--------------------------------------------------------------------+ @@ -312,10 +312,7 @@ static tusb_error_t usbd_main_st(void) //--------------------------------------------------------------------+ static tusb_error_t proc_control_request_st(uint8_t rhport, tusb_control_request_t const * const p_request) { - OSAL_SUBTASK_BEGIN - - ATTR_UNUSED tusb_error_t error; - error = TUSB_ERROR_NONE; + tusb_error_t error = TUSB_ERROR_NONE; //------------- Standard Request e.g in enumeration -------------// if( TUSB_REQ_RCPT_DEVICE == p_request->bmRequestType_bit.recipient && @@ -326,9 +323,10 @@ static tusb_error_t proc_control_request_st(uint8_t rhport, tusb_control_request uint8_t const * buffer = NULL; uint16_t const len = get_descriptor(rhport, p_request, &buffer); + if ( len ) { - STASK_ASSERT( len <= CFG_TUD_CTRL_BUFSIZE ); + TU_ASSERT( len <= CFG_TUD_CTRL_BUFSIZE ); memcpy(_usbd_ctrl_buf, buffer, len); usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, _usbd_ctrl_buf, len); }else @@ -365,7 +363,7 @@ static tusb_error_t proc_control_request_st(uint8_t rhport, tusb_control_request { if (_usbd_dev.itf2drv[ tu_u16_low(p_request->wIndex) ] < USBD_CLASS_DRIVER_COUNT) { - STASK_INVOKE( usbd_class_drivers[ _usbd_dev.itf2drv[ tu_u16_low(p_request->wIndex) ] ].control_req_st(rhport, p_request), error ); + error = usbd_class_drivers[ _usbd_dev.itf2drv[ tu_u16_low(p_request->wIndex) ] ].control_req_st(rhport, p_request); }else { dcd_control_stall(rhport); // Stall unsupported request @@ -406,8 +404,10 @@ static tusb_error_t proc_control_request_st(uint8_t rhport, tusb_control_request { dcd_control_stall(rhport); // Stall unsupported request } - - OSAL_SUBTASK_END + if (error != TUSB_ERROR_NONE) { + dcd_control_stall(rhport); // Stall errored requests + } + return error; } // Process Set Configure Request @@ -548,8 +548,6 @@ static void mark_interface_endpoint(uint8_t const* p_desc, uint16_t desc_len, ui //--------------------------------------------------------------------+ void dcd_event_handler(dcd_event_t const * event, bool in_isr) { - uint8_t const rhport = event->rhport; - switch (event->event_id) { case DCD_EVENT_BUS_RESET: @@ -590,9 +588,49 @@ void dcd_event_handler(dcd_event_t const * event, bool in_isr) } } +void dcd_event_handler(dcd_event_t const * event, bool in_isr); + +// helper to send bus signal event +void dcd_event_bus_signal (uint8_t rhport, dcd_eventid_t eid, bool in_isr) +{ + dcd_event_t event = { .rhport = 0, .event_id = eid, }; + dcd_event_handler(&event, in_isr); +} + +// helper to send setup received +void dcd_event_setup_received(uint8_t rhport, uint8_t const * setup, bool in_isr) +{ + dcd_event_t event = { .rhport = 0, .event_id = DCD_EVENT_SETUP_RECEIVED }; + memcpy(&event.setup_received, setup, 8); + + dcd_event_handler(&event, true); +} + +// helper to send transfer complete event +void dcd_event_xfer_complete (uint8_t rhport, uint8_t ep_addr, uint32_t xferred_bytes, uint8_t result, bool in_isr) +{ + dcd_event_t event = { .rhport = 0, .event_id = DCD_EVENT_XFER_COMPLETE }; + + event.xfer_complete.ep_addr = ep_addr; + event.xfer_complete.len = xferred_bytes; + event.xfer_complete.result = result; + + dcd_event_handler(&event, in_isr); +} + //--------------------------------------------------------------------+ // Helper //--------------------------------------------------------------------+ +uint32_t usbd_control_xfer_st(uint8_t _rhport, uint8_t _dir, uint8_t* _buffer, uint16_t _len) { + uint32_t err = TUSB_ERROR_NONE; + if (_len) { + dcd_control_xfer(_rhport, _dir, (uint8_t*) _buffer, _len); + } + + dcd_control_status(_rhport, _dir); + return err; +} + tusb_error_t usbd_open_edpt_pair(uint8_t rhport, tusb_desc_endpoint_t const* p_desc_ep, uint8_t xfer_type, uint8_t* ep_out, uint8_t* ep_in) { for(int i=0; i<2; i++) diff --git a/src/device/usbd_pvt.h b/src/device/usbd_pvt.h index 0b6b56d7d..ecb71f771 100644 --- a/src/device/usbd_pvt.h +++ b/src/device/usbd_pvt.h @@ -64,20 +64,7 @@ void usbd_task (void* param); // helper to parse an pair of In and Out endpoint descriptors. They must be consecutive tusb_error_t usbd_open_edpt_pair(uint8_t rhport, tusb_desc_endpoint_t const* p_desc_ep, uint8_t xfer_type, uint8_t* ep_out, uint8_t* ep_in); -// Carry out Data and Status stage of control transfer -// Must be call in a subtask (_st) function -#define usbd_control_xfer_st(_rhport, _dir, _buffer, _len) \ - do { \ - if (_len) { \ - uint32_t err; \ - dcd_control_xfer(_rhport, _dir, (uint8_t*) _buffer, _len); \ - osal_semaphore_wait( _usbd_ctrl_sem, OSAL_TIMEOUT_CONTROL_XFER, &err ); \ - STASK_ASSERT_ERR( err ); \ - } \ - dcd_control_status(_rhport, _dir); \ - /* No need to wait for status phase to complete */ \ - }while(0) - +uint32_t usbd_control_xfer_st(uint8_t _rhport, uint8_t _dir, uint8_t* _buffer, uint16_t _len); /*------------------------------------------------------------------*/ /* Other Helpers diff --git a/src/osal/osal_freertos.h b/src/osal/osal_freertos.h index ae988ec1f..f29759225 100644 --- a/src/osal/osal_freertos.h +++ b/src/osal/osal_freertos.h @@ -183,4 +183,3 @@ static inline void osal_queue_reset(osal_queue_t const queue_hdl) /** @} */ /** @} */ - diff --git a/src/osal/osal_none.h b/src/osal/osal_none.h index 796ddc15f..6e67c8ea6 100644 --- a/src/osal/osal_none.h +++ b/src/osal/osal_none.h @@ -60,8 +60,6 @@ // // OSAL_TASK_LOOP_ENG // } -// -// NOTE: no switch statement is allowed in Task and subtask //--------------------------------------------------------------------+ #define OSAL_TASK_DEF(_name, _str, _func, _prio, _stack_sz) osal_task_def_t _name; @@ -73,52 +71,8 @@ static inline bool osal_task_create(osal_task_def_t* taskdef) return true; } -#define TASK_RESTART \ - _state = 0 - -#define osal_task_delay(_msec) \ - do { \ - _timeout = tusb_hal_millis(); \ - _state = __LINE__; case __LINE__: \ - if ( _timeout + (_msec) > tusb_hal_millis() ) \ - return TUSB_ERROR_OSAL_WAITING; \ - }while(0) - //--------------------------------------------------------------------+ -// SUBTASK (a sub function that uses OS blocking services & called by a task -//--------------------------------------------------------------------+ -#define OSAL_SUBTASK_BEGIN \ - static uint16_t _state = 0; \ - ATTR_UNUSED static uint32_t _timeout = 0; \ - (void) _timeout; \ - switch(_state) { \ - case 0: { - -#define OSAL_SUBTASK_END \ - default: TASK_RESTART; break; \ - }} \ - return TUSB_ERROR_NONE; - -#define STASK_INVOKE(_subtask, _status) \ - do { \ - _state = __LINE__; case __LINE__: \ - { \ - (_status) = _subtask; /* invoke sub task */ \ - if (TUSB_ERROR_OSAL_WAITING == (_status)) return TUSB_ERROR_OSAL_WAITING; \ - } \ - }while(0) - -//------------- Sub Task Assert -------------// -#define STASK_RETURN(error) do { TASK_RESTART; return error; } while(0) - -#define STASK_ASSERT_ERR(_err) TU_VERIFY_ERR_HDLR(_err, TU_BREAKPOINT(); TASK_RESTART, TUSB_ERROR_FAILED) -#define STASK_ASSERT_ERR_HDLR(_err, _func) TU_VERIFY_ERR_HDLR(_err, TU_BREAKPOINT(); _func; TASK_RESTART, TUSB_ERROR_FAILED ) - -#define STASK_ASSERT(_cond) TU_VERIFY_HDLR(_cond, TU_BREAKPOINT(); TASK_RESTART, TUSB_ERROR_FAILED) -#define STASK_ASSERT_HDLR(_cond, _func) TU_VERIFY_HDLR(_cond, TU_BREAKPOINT(); _func; TASK_RESTART, TUSB_ERROR_FAILED) - -//--------------------------------------------------------------------+ -// Semaphore API +// Binary Semaphore API //--------------------------------------------------------------------+ typedef struct { @@ -135,7 +89,6 @@ static inline osal_semaphore_t osal_semaphore_create(osal_semaphore_def_t* semde static inline bool osal_semaphore_post(osal_semaphore_t sem_hdl, bool in_isr) { - (void) in_isr; sem_hdl->count++; return true; } @@ -145,22 +98,21 @@ static inline void osal_semaphore_reset(osal_semaphore_t sem_hdl) sem_hdl->count = 0; } -#define osal_semaphore_wait(_sem_hdl, _msec, _err) \ - do { \ - _timeout = tusb_hal_millis(); \ - _state = __LINE__; case __LINE__: \ - if( (_sem_hdl)->count == 0 ) { \ - if ( ((_msec) != OSAL_TIMEOUT_WAIT_FOREVER) && (_timeout + (_msec) <= tusb_hal_millis()) ) \ - *(_err) = TUSB_ERROR_OSAL_TIMEOUT; \ - else \ - return TUSB_ERROR_OSAL_WAITING; \ - } else{ \ - /* Enter critical ? */ \ - (_sem_hdl)->count--; \ - /* Exit critical ? */ \ - *(_err) = TUSB_ERROR_NONE; \ - } \ - }while(0) +static inline tusb_error_t osal_semaphore_wait(osal_semaphore_t sem_hdl, uint32_t msec) { + (void) msec; + while (true) { + while (sem_hdl->count == 0) { + } + // tusb_hal_int_disable_all(); + if (sem_hdl->count == 0) { + sem_hdl->count--; + // tusb_hal_int_enable_all(); + break; + } + // tusb_hal_int_enable_all(); + } + return TUSB_ERROR_NONE; +} //--------------------------------------------------------------------+ // MUTEX API @@ -218,22 +170,13 @@ static inline void osal_queue_reset(osal_queue_t const queue_hdl) queue_hdl->count = queue_hdl->rd_idx = queue_hdl->wr_idx = 0; } -#define osal_queue_receive(_q_hdl, p_data, _msec, _err) \ - do { \ - _timeout = tusb_hal_millis(); \ - _state = __LINE__; case __LINE__: \ - if( (_q_hdl)->count == 0 ) { \ - if ( ((_msec) != OSAL_TIMEOUT_WAIT_FOREVER) && ( _timeout + (_msec) <= tusb_hal_millis()) ) \ - *(_err) = TUSB_ERROR_OSAL_TIMEOUT; \ - else \ - return TUSB_ERROR_OSAL_WAITING; \ - } else{ \ - /* Enter critical ? */ \ - tu_fifo_read(_q_hdl, p_data); \ - /* Exit critical ? */ \ - *(_err) = TUSB_ERROR_NONE; \ - } \ - }while(0) +static inline tusb_error_t osal_queue_receive(osal_queue_t const queue_hdl, void* data) { + if (!tu_fifo_read(queue_hdl, data)) { + return TUSB_ERROR_OSAL_WAITING; + } + return TUSB_ERROR_NONE; +} + #ifdef __cplusplus } diff --git a/src/portable/microchip/samd21/dcd.c b/src/portable/microchip/samd21/dcd.c new file mode 100644 index 000000000..c9e88ad17 --- /dev/null +++ b/src/portable/microchip/samd21/dcd.c @@ -0,0 +1,341 @@ +/**************************************************************************/ +/*! + @file dcd_nrf5x.c + @author hathach + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2018, Scott Shawcroft for Adafruit Industries + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#include "tusb_option.h" + +#if TUSB_OPT_DEVICE_ENABLED && CFG_TUSB_MCU == OPT_MCU_SAMD51 + +#include "device/dcd.h" + +#include "device/usbd.h" +#include "device/usbd_pvt.h" // to use defer function helper + +#include "class/msc/msc_device.h" + +#include "sam.h" + +/*------------------------------------------------------------------*/ +/* MACRO TYPEDEF CONSTANT ENUM + *------------------------------------------------------------------*/ +enum +{ + // Max allowed by USB specs + MAX_PACKET_SIZE = 64, +}; + +UsbDeviceDescBank sram_registers[8][2]; +ATTR_ALIGNED(4) uint8_t control_out_buffer[64]; +ATTR_ALIGNED(4) uint8_t control_in_buffer[64]; + +volatile uint32_t setup_count = 0; + +// Setup the control endpoint 0. +static void bus_reset(void) { + // Max size of packets is 64 bytes. + UsbDeviceDescBank* bank_out = &sram_registers[0][TUSB_DIR_OUT]; + bank_out->PCKSIZE.bit.SIZE = 0x3; + UsbDeviceDescBank* bank_in = &sram_registers[0][TUSB_DIR_IN]; + bank_in->PCKSIZE.bit.SIZE = 0x3; + + UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[0]; + ep->EPCFG.reg = USB_DEVICE_EPCFG_EPTYPE0(0x1) | USB_DEVICE_EPCFG_EPTYPE1(0x1); + ep->EPINTENSET.reg = USB_DEVICE_EPINTENSET_TRCPT0 | USB_DEVICE_EPINTENSET_TRCPT1 | USB_DEVICE_EPINTENSET_RXSTP; + + dcd_edpt_xfer(0, 0, control_out_buffer, 64); + setup_count = 0; +} + + +/*------------------------------------------------------------------*/ +/* Controller API + *------------------------------------------------------------------*/ +bool dcd_init (uint8_t rhport) +{ + (void) rhport; + USB->DEVICE.DESCADD.reg = (uint32_t) &sram_registers; + USB->DEVICE.CTRLB.reg = USB_DEVICE_CTRLB_SPDCONF_FS; + USB->DEVICE.CTRLA.reg = USB_CTRLA_MODE_DEVICE | USB_CTRLA_ENABLE; + USB->DEVICE.INTENSET.reg = USB_DEVICE_INTENSET_SOF | USB_DEVICE_INTENSET_EORST; + + return true; +} + +void dcd_connect (uint8_t rhport) +{ + +} +void dcd_disconnect (uint8_t rhport) +{ + +} + +void dcd_set_address (uint8_t rhport, uint8_t dev_addr) +{ + (void) rhport; + dcd_edpt_xfer (0, TUSB_DIR_IN_MASK, NULL, 0); + // Wait for EP0 to finish before switching the address. + while (USB->DEVICE.DeviceEndpoint[0].EPSTATUS.bit.BK1RDY == 1) {} + USB->DEVICE.DADD.reg = USB_DEVICE_DADD_DADD(dev_addr) | USB_DEVICE_DADD_ADDEN; +} + +void dcd_set_config (uint8_t rhport, uint8_t config_num) +{ + (void) rhport; + (void) config_num; + // Nothing to do +} + +/*------------------------------------------------------------------*/ +/* Control + *------------------------------------------------------------------*/ + +bool dcd_control_xfer (uint8_t rhport, uint8_t dir, uint8_t * buffer, uint16_t length) +{ + (void) rhport; + uint8_t ep_addr = 0; + if (dir == TUSB_DIR_IN) { + ep_addr |= TUSB_DIR_IN_MASK; + } + + return dcd_edpt_xfer (rhport, ep_addr, buffer, length); +} + +bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * desc_edpt) +{ + (void) rhport; + + uint8_t const epnum = edpt_number(desc_edpt->bEndpointAddress); + uint8_t const dir = edpt_dir(desc_edpt->bEndpointAddress); + + UsbDeviceDescBank* bank = &sram_registers[epnum][dir]; + uint32_t size_value = 0; + while (size_value < 7) { + if (1 << (size_value + 3) == desc_edpt->wMaxPacketSize.size) { + break; + } + size_value++; + } + bank->PCKSIZE.bit.SIZE = size_value; + + UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; + + if ( dir == TUSB_DIR_OUT ) + { + ep->EPCFG.bit.EPTYPE0 = desc_edpt->bmAttributes.xfer + 1; + ep->EPINTENSET.bit.TRCPT0 = true; + }else + { + ep->EPCFG.bit.EPTYPE1 = desc_edpt->bmAttributes.xfer + 1; + ep->EPINTENSET.bit.TRCPT1 = true; + } + __ISB(); __DSB(); + + return true; +} + +bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes) +{ + (void) rhport; + + uint8_t const epnum = edpt_number(ep_addr); + uint8_t const dir = edpt_dir(ep_addr); + + UsbDeviceDescBank* bank = &sram_registers[epnum][dir]; + UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; + + bank->ADDR.reg = (uint32_t) buffer; + if ( dir == TUSB_DIR_OUT ) + { + bank->PCKSIZE.bit.MULTI_PACKET_SIZE = total_bytes; + bank->PCKSIZE.bit.BYTE_COUNT = 0; + ep->EPSTATUSCLR.reg |= USB_DEVICE_EPSTATUSCLR_BK0RDY; + ep->EPINTFLAG.reg |= USB_DEVICE_EPINTFLAG_TRFAIL0; + } else + { + bank->PCKSIZE.bit.MULTI_PACKET_SIZE = 0; + bank->PCKSIZE.bit.BYTE_COUNT = total_bytes; + // bank->PCKSIZE.bit.AUTO_ZLP = 1; + ep->EPSTATUSSET.reg |= USB_DEVICE_EPSTATUSSET_BK1RDY; + ep->EPINTFLAG.reg |= USB_DEVICE_EPINTFLAG_TRFAIL1; + } + + return true; +} + +bool dcd_edpt_stalled (uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + + // control is never got halted + if ( ep_addr == 0 ) { + return false; + } + + uint8_t const epnum = edpt_number(ep_addr); + UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; + return (edpt_dir(ep_addr) == TUSB_DIR_IN ) ? ep->EPINTFLAG.bit.STALL1 : ep->EPINTFLAG.bit.STALL0; +} + +void dcd_edpt_stall (uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + + uint8_t const epnum = edpt_number(ep_addr); + UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; + + if (edpt_dir(ep_addr) == TUSB_DIR_IN) { + ep->EPSTATUSSET.reg = USB_DEVICE_EPSTATUSSET_STALLRQ1; + } else { + ep->EPSTATUSSET.reg = USB_DEVICE_EPSTATUSSET_STALLRQ0; + } + + __ISB(); __DSB(); +} + +void dcd_edpt_clear_stall (uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + + uint8_t const epnum = edpt_number(ep_addr); + UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; + + if (edpt_dir(ep_addr) == TUSB_DIR_IN) { + ep->EPSTATUSCLR.reg = USB_DEVICE_EPSTATUSCLR_STALLRQ1; + } else { + ep->EPSTATUSCLR.reg = USB_DEVICE_EPSTATUSCLR_STALLRQ0; + } +} + +bool dcd_edpt_busy (uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + + // USBD shouldn't check control endpoint state + if ( 0 == ep_addr ) return false; + + uint8_t const epnum = edpt_number(ep_addr); + UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; + + if (edpt_dir(ep_addr) == TUSB_DIR_IN) { + return ep->EPINTFLAG.bit.TRCPT1 == 0 && ep->EPSTATUS.bit.BK1RDY == 1; + } + return ep->EPINTFLAG.bit.TRCPT0 == 0 && ep->EPSTATUS.bit.BK0RDY == 1; +} + +/*------------------------------------------------------------------*/ + +static bool maybe_handle_setup_packet(void) { + if (USB->DEVICE.DeviceEndpoint[0].EPINTFLAG.bit.RXSTP) + { + USB->DEVICE.DeviceEndpoint[0].EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_RXSTP; + + // This copies the data elsewhere so we can reuse the buffer. + dcd_event_setup_received(0, (uint8_t*) sram_registers[0][0].ADDR.reg, true); + dcd_edpt_xfer(0, 0, control_out_buffer, 64); + setup_count += 1; + return true; + } + return false; +} + +void maybe_transfer_complete(void) { + uint32_t epints = USB->DEVICE.EPINTSMRY.reg; + for (uint8_t epnum = 0; epnum < USB_EPT_NUM; epnum++) { + if ((epints & (1 << epnum)) == 0) { + continue; + } + + if (maybe_handle_setup_packet()) { + continue; + } + UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; + + uint32_t epintflag = ep->EPINTFLAG.reg; + + // Handle IN completions + if ((epintflag & USB_DEVICE_EPINTFLAG_TRCPT1) != 0) { + ep->EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_TRCPT1; + + UsbDeviceDescBank* bank = &sram_registers[epnum][TUSB_DIR_IN]; + uint16_t total_transfer_size = bank->PCKSIZE.bit.BYTE_COUNT; + + uint8_t ep_addr = epnum | TUSB_DIR_IN_MASK; + dcd_event_xfer_complete(0, ep_addr, total_transfer_size, DCD_XFER_SUCCESS, true); + } + + // Handle OUT completions + if ((epintflag & USB_DEVICE_EPINTFLAG_TRCPT0) != 0) { + ep->EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_TRCPT0; + + UsbDeviceDescBank* bank = &sram_registers[epnum][TUSB_DIR_OUT]; + uint16_t total_transfer_size = bank->PCKSIZE.bit.BYTE_COUNT; + + uint8_t ep_addr = epnum; + dcd_event_xfer_complete(0, ep_addr, total_transfer_size, DCD_XFER_SUCCESS, true); + if (epnum == 0) { + dcd_edpt_xfer(0, 0, control_out_buffer, 64); + } + } + } +} + +void USB_Handler(void) { + uint32_t int_status = USB->DEVICE.INTFLAG.reg; + + /*------------- Interrupt Processing -------------*/ + if ( int_status & USB_DEVICE_INTFLAG_EORST ) + { + USB->DEVICE.INTFLAG.reg = USB_DEVICE_INTENCLR_EORST; + bus_reset(); + dcd_event_bus_signal(0, DCD_EVENT_BUS_RESET, true); + } + + if ( int_status & USB_DEVICE_INTFLAG_SOF ) + { + USB->DEVICE.INTFLAG.reg = USB_DEVICE_INTFLAG_SOF; + dcd_event_bus_signal(0, DCD_EVENT_SOF, true); + } + + // Setup packet received. + maybe_handle_setup_packet(); + + // Handle complete transfer + maybe_transfer_complete(); +} + +#endif diff --git a/src/portable/microchip/samd21/hal.c b/src/portable/microchip/samd21/hal.c new file mode 100644 index 000000000..524840be2 --- /dev/null +++ b/src/portable/microchip/samd21/hal.c @@ -0,0 +1,82 @@ +/**************************************************************************/ +/*! + @file hal_nrf5x.c + @author hathach + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2018, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#include "tusb_option.h" + +#if TUSB_OPT_DEVICE_ENABLED && CFG_TUSB_MCU == OPT_MCU_SAMD21 + +#include "sam.h" + +#include "tusb_hal.h" + +/*------------------------------------------------------------------*/ +/* MACRO TYPEDEF CONSTANT ENUM + *------------------------------------------------------------------*/ +#define USB_NVIC_PRIO 7 + +void tusb_hal_nrf_power_event(uint32_t event); + +/*------------------------------------------------------------------*/ +/* TUSB HAL + *------------------------------------------------------------------*/ +bool tusb_hal_init(void) +{ + USB->DEVICE.PADCAL.bit.TRANSP = (*((uint32_t*) USB_FUSES_TRANSP_ADDR) & USB_FUSES_TRANSP_Msk) >> USB_FUSES_TRANSP_Pos; + USB->DEVICE.PADCAL.bit.TRANSN = (*((uint32_t*) USB_FUSES_TRANSN_ADDR) & USB_FUSES_TRANSN_Msk) >> USB_FUSES_TRANSN_Pos; + USB->DEVICE.PADCAL.bit.TRIM = (*((uint32_t*) USB_FUSES_TRIM_ADDR) & USB_FUSES_TRIM_Msk) >> USB_FUSES_TRIM_Pos; + + USB->DEVICE.QOSCTRL.bit.CQOS = USB_QOSCTRL_CQOS_HIGH_Val; + USB->DEVICE.QOSCTRL.bit.DQOS = USB_QOSCTRL_DQOS_HIGH_Val; + + tusb_hal_int_enable(0); + return true; +} + +void tusb_hal_int_enable(uint8_t rhport) +{ + (void) rhport; + NVIC_EnableIRQ(USB_IRQn); +} + +void tusb_hal_int_disable(uint8_t rhport) +{ + (void) rhport; + NVIC_DisableIRQ(USB_IRQn); +} + +#endif diff --git a/src/portable/microchip/samd51/dcd.c b/src/portable/microchip/samd51/dcd.c new file mode 100644 index 000000000..e67fbd295 --- /dev/null +++ b/src/portable/microchip/samd51/dcd.c @@ -0,0 +1,360 @@ +/**************************************************************************/ +/*! + @file dcd_nrf5x.c + @author hathach + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2018, Scott Shawcroft for Adafruit Industries + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#include "tusb_option.h" + +#if TUSB_OPT_DEVICE_ENABLED && CFG_TUSB_MCU == OPT_MCU_SAMD51 + +#include "device/dcd.h" + +#include "device/usbd.h" +#include "device/usbd_pvt.h" // to use defer function helper + +#include "sam.h" + +/*------------------------------------------------------------------*/ +/* MACRO TYPEDEF CONSTANT ENUM + *------------------------------------------------------------------*/ +enum +{ + // Max allowed by USB specs + MAX_PACKET_SIZE = 64, +}; + +UsbDeviceDescBank sram_registers[8][2]; +ATTR_ALIGNED(4) uint8_t control_out_buffer[64]; +ATTR_ALIGNED(4) uint8_t control_in_buffer[64]; + +volatile uint32_t setup_count = 0; + +// Setup the control endpoint 0. +static void bus_reset(void) { + // Max size of packets is 64 bytes. + UsbDeviceDescBank* bank_out = &sram_registers[0][TUSB_DIR_OUT]; + bank_out->PCKSIZE.bit.SIZE = 0x3; + UsbDeviceDescBank* bank_in = &sram_registers[0][TUSB_DIR_IN]; + bank_in->PCKSIZE.bit.SIZE = 0x3; + + UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[0]; + ep->EPCFG.reg = USB_DEVICE_EPCFG_EPTYPE0(0x1) | USB_DEVICE_EPCFG_EPTYPE1(0x1); + ep->EPINTENSET.reg = USB_DEVICE_EPINTENSET_TRCPT0 | USB_DEVICE_EPINTENSET_TRCPT1 | USB_DEVICE_EPINTENSET_RXSTP; + + dcd_edpt_xfer(0, 0, control_out_buffer, 64); + setup_count = 0; +} + + +/*------------------------------------------------------------------*/ +/* Controller API + *------------------------------------------------------------------*/ +bool dcd_init (uint8_t rhport) +{ + (void) rhport; + USB->DEVICE.DESCADD.reg = (uint32_t) &sram_registers; + USB->DEVICE.CTRLB.reg = USB_DEVICE_CTRLB_SPDCONF_FS; + USB->DEVICE.CTRLA.reg = USB_CTRLA_MODE_DEVICE | USB_CTRLA_ENABLE; + USB->DEVICE.INTENSET.reg = USB_DEVICE_INTENSET_SOF | USB_DEVICE_INTENSET_EORST; + + return true; +} + +void dcd_connect (uint8_t rhport) +{ + +} +void dcd_disconnect (uint8_t rhport) +{ + +} + +void dcd_set_address (uint8_t rhport, uint8_t dev_addr) +{ + (void) rhport; + dcd_edpt_xfer (0, TUSB_DIR_IN_MASK, NULL, 0); + // Wait for EP0 to finish before switching the address. + while (USB->DEVICE.DeviceEndpoint[0].EPSTATUS.bit.BK1RDY == 1) {} + USB->DEVICE.DADD.reg = USB_DEVICE_DADD_DADD(dev_addr) | USB_DEVICE_DADD_ADDEN; +} + +void dcd_set_config (uint8_t rhport, uint8_t config_num) +{ + (void) rhport; + (void) config_num; + // Nothing to do +} + +/*------------------------------------------------------------------*/ +/* Control + *------------------------------------------------------------------*/ + +bool dcd_control_xfer (uint8_t rhport, uint8_t dir, uint8_t * buffer, uint16_t length) +{ + (void) rhport; + uint8_t ep_addr = 0; + if (dir == TUSB_DIR_IN) { + ep_addr |= TUSB_DIR_IN_MASK; + } + + return dcd_edpt_xfer (rhport, ep_addr, buffer, length); +} + +bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * desc_edpt) +{ + (void) rhport; + + uint8_t const epnum = edpt_number(desc_edpt->bEndpointAddress); + uint8_t const dir = edpt_dir(desc_edpt->bEndpointAddress); + + UsbDeviceDescBank* bank = &sram_registers[epnum][dir]; + uint32_t size_value = 0; + while (size_value < 7) { + if (1 << (size_value + 3) == desc_edpt->wMaxPacketSize.size) { + break; + } + size_value++; + } + bank->PCKSIZE.bit.SIZE = size_value; + + UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; + + if ( dir == TUSB_DIR_OUT ) + { + ep->EPCFG.bit.EPTYPE0 = desc_edpt->bmAttributes.xfer + 1; + ep->EPINTENSET.bit.TRCPT0 = true; + }else + { + ep->EPCFG.bit.EPTYPE1 = desc_edpt->bmAttributes.xfer + 1; + ep->EPINTENSET.bit.TRCPT1 = true; + } + __ISB(); __DSB(); + + return true; +} + +bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes) +{ + (void) rhport; + + uint8_t const epnum = edpt_number(ep_addr); + uint8_t const dir = edpt_dir(ep_addr); + + UsbDeviceDescBank* bank = &sram_registers[epnum][dir]; + UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; + + bank->ADDR.reg = (uint32_t) buffer; + if ( dir == TUSB_DIR_OUT ) + { + bank->PCKSIZE.bit.MULTI_PACKET_SIZE = total_bytes; + bank->PCKSIZE.bit.BYTE_COUNT = 0; + ep->EPSTATUSCLR.reg |= USB_DEVICE_EPSTATUSCLR_BK0RDY; + ep->EPINTFLAG.reg |= USB_DEVICE_EPINTFLAG_TRFAIL0; + } else + { + bank->PCKSIZE.bit.MULTI_PACKET_SIZE = 0; + bank->PCKSIZE.bit.BYTE_COUNT = total_bytes; + ep->EPSTATUSSET.reg |= USB_DEVICE_EPSTATUSSET_BK1RDY; + ep->EPINTFLAG.reg |= USB_DEVICE_EPINTFLAG_TRFAIL1; + } + + return true; +} + +bool dcd_edpt_stalled (uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + + // control is never got halted + if ( ep_addr == 0 ) { + return false; + } + + uint8_t const epnum = edpt_number(ep_addr); + UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; + return (edpt_dir(ep_addr) == TUSB_DIR_IN ) ? ep->EPINTFLAG.bit.STALL1 : ep->EPINTFLAG.bit.STALL0; +} + +void dcd_edpt_stall (uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + + uint8_t const epnum = edpt_number(ep_addr); + UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; + + if (edpt_dir(ep_addr) == TUSB_DIR_IN) { + ep->EPSTATUSSET.reg = USB_DEVICE_EPSTATUSSET_STALLRQ1; + } else { + ep->EPSTATUSSET.reg = USB_DEVICE_EPSTATUSSET_STALLRQ0; + } + + __ISB(); __DSB(); +} + +void dcd_edpt_clear_stall (uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + + uint8_t const epnum = edpt_number(ep_addr); + UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; + + if (edpt_dir(ep_addr) == TUSB_DIR_IN) { + ep->EPSTATUSCLR.reg = USB_DEVICE_EPSTATUSCLR_STALLRQ1; + } else { + ep->EPSTATUSCLR.reg = USB_DEVICE_EPSTATUSCLR_STALLRQ0; + } +} + +bool dcd_edpt_busy (uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + + // USBD shouldn't check control endpoint state + if ( 0 == ep_addr ) return false; + + uint8_t const epnum = edpt_number(ep_addr); + UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; + + if (edpt_dir(ep_addr) == TUSB_DIR_IN) { + return ep->EPINTFLAG.bit.TRCPT1 == 0 && ep->EPSTATUS.bit.BK1RDY == 1; + } + return ep->EPINTFLAG.bit.TRCPT0 == 0 && ep->EPSTATUS.bit.BK0RDY == 1; +} + +/*------------------------------------------------------------------*/ + +static bool maybe_handle_setup_packet(void) { + if (USB->DEVICE.DeviceEndpoint[0].EPINTFLAG.bit.RXSTP) + { + USB->DEVICE.DeviceEndpoint[0].EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_RXSTP; + // uint8_t* buf = (uint8_t*) sram_registers[0][0].ADDR.reg; + // + // if (buf[6] == 0x12) asm("bkpt"); + // This copies the data elsewhere so we can reuse the buffer. + dcd_event_setup_received(0, (uint8_t*) sram_registers[0][0].ADDR.reg, true); + dcd_edpt_xfer(0, 0, control_out_buffer, 64); + setup_count += 1; + return true; + } + return false; +} +/* + *------------------------------------------------------------------*/ +/* USB_EORSM_DNRSM, USB_EORST_RST, USB_LPMSUSP_DDISC, USB_LPM_DCONN, +USB_MSOF, USB_RAMACER, USB_RXSTP_TXSTP_0, USB_RXSTP_TXSTP_1, +USB_RXSTP_TXSTP_2, USB_RXSTP_TXSTP_3, USB_RXSTP_TXSTP_4, +USB_RXSTP_TXSTP_5, USB_RXSTP_TXSTP_6, USB_RXSTP_TXSTP_7, +USB_STALL0_STALL_0, USB_STALL0_STALL_1, USB_STALL0_STALL_2, +USB_STALL0_STALL_3, USB_STALL0_STALL_4, USB_STALL0_STALL_5, +USB_STALL0_STALL_6, USB_STALL0_STALL_7, USB_STALL1_0, USB_STALL1_1, +USB_STALL1_2, USB_STALL1_3, USB_STALL1_4, USB_STALL1_5, USB_STALL1_6, +USB_STALL1_7, USB_SUSPEND, USB_TRFAIL0_TRFAIL_0, USB_TRFAIL0_TRFAIL_1, +USB_TRFAIL0_TRFAIL_2, USB_TRFAIL0_TRFAIL_3, USB_TRFAIL0_TRFAIL_4, +USB_TRFAIL0_TRFAIL_5, USB_TRFAIL0_TRFAIL_6, USB_TRFAIL0_TRFAIL_7, +USB_TRFAIL1_PERR_0, USB_TRFAIL1_PERR_1, USB_TRFAIL1_PERR_2, +USB_TRFAIL1_PERR_3, USB_TRFAIL1_PERR_4, USB_TRFAIL1_PERR_5, +USB_TRFAIL1_PERR_6, USB_TRFAIL1_PERR_7, USB_UPRSM, USB_WAKEUP */ +void USB_0_Handler(void) { + uint32_t int_status = USB->DEVICE.INTFLAG.reg; + + /*------------- Interrupt Processing -------------*/ + if ( int_status & USB_DEVICE_INTFLAG_EORST ) + { + USB->DEVICE.INTFLAG.reg = USB_DEVICE_INTENCLR_EORST; + bus_reset(); + dcd_event_bus_signal(0, DCD_EVENT_BUS_RESET, true); + } + + // Setup packet received. + maybe_handle_setup_packet(); +} +/* USB_SOF_HSOF */ +void USB_1_Handler(void) { + USB->DEVICE.INTFLAG.reg = USB_DEVICE_INTFLAG_SOF; + dcd_event_bus_signal(0, DCD_EVENT_SOF, true); +} + +void transfer_complete(uint8_t direction) { + // uint8_t* buf = (uint8_t*) sram_registers[0][0].ADDR.reg; + // + // if (buf[6] == 0x12 || setup_count == 2) asm("bkpt"); + uint32_t epints = USB->DEVICE.EPINTSMRY.reg; + for (uint8_t epnum = 0; epnum < USB_EPT_NUM; epnum++) { + if ((epints & (1 << epnum)) == 0) { + continue; + } + + if (direction == TUSB_DIR_OUT && maybe_handle_setup_packet()) { + continue; + } + UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; + + UsbDeviceDescBank* bank = &sram_registers[epnum][direction]; + uint16_t total_transfer_size = bank->PCKSIZE.bit.BYTE_COUNT; + + uint8_t ep_addr = epnum; + if (direction == TUSB_DIR_IN) { + ep_addr |= TUSB_DIR_IN_MASK; + } + dcd_event_xfer_complete(0, ep_addr, total_transfer_size, DCD_XFER_SUCCESS, true); + if (epnum == 0 && direction == TUSB_DIR_OUT) { + dcd_edpt_xfer(0, 0, control_out_buffer, 64); + } + if (direction == TUSB_DIR_IN) { + ep->EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_TRCPT1; + } else { + ep->EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_TRCPT0; + } + } +} + +// Bank zero is for OUT and SETUP transactions. +/* USB_TRCPT0_0, USB_TRCPT0_1, USB_TRCPT0_2, +USB_TRCPT0_3, USB_TRCPT0_4, USB_TRCPT0_5, +USB_TRCPT0_6, USB_TRCPT0_7 */ +void USB_2_Handler(void) { + transfer_complete(TUSB_DIR_OUT); +} + +// Bank one is used for IN transactions. +/* USB_TRCPT1_0, USB_TRCPT1_1, USB_TRCPT1_2, +USB_TRCPT1_3, USB_TRCPT1_4, USB_TRCPT1_5, +USB_TRCPT1_6, USB_TRCPT1_7 */ +void USB_3_Handler(void) { + transfer_complete(TUSB_DIR_IN); +} + +#endif diff --git a/src/portable/microchip/samd51/hal.c b/src/portable/microchip/samd51/hal.c new file mode 100644 index 000000000..d8c71a7fe --- /dev/null +++ b/src/portable/microchip/samd51/hal.c @@ -0,0 +1,88 @@ +/**************************************************************************/ +/*! + @file hal_nrf5x.c + @author hathach + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2018, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#include "tusb_option.h" + +#if TUSB_OPT_DEVICE_ENABLED && CFG_TUSB_MCU == OPT_MCU_SAMD51 + +#include "sam.h" + +#include "tusb_hal.h" + +/*------------------------------------------------------------------*/ +/* MACRO TYPEDEF CONSTANT ENUM + *------------------------------------------------------------------*/ +#define USB_NVIC_PRIO 7 + +void tusb_hal_nrf_power_event(uint32_t event); + +/*------------------------------------------------------------------*/ +/* TUSB HAL + *------------------------------------------------------------------*/ +bool tusb_hal_init(void) +{ + USB->DEVICE.PADCAL.bit.TRANSP = (*((uint32_t*) USB_FUSES_TRANSP_ADDR) & USB_FUSES_TRANSP_Msk) >> USB_FUSES_TRANSP_Pos; + USB->DEVICE.PADCAL.bit.TRANSN = (*((uint32_t*) USB_FUSES_TRANSN_ADDR) & USB_FUSES_TRANSN_Msk) >> USB_FUSES_TRANSN_Pos; + USB->DEVICE.PADCAL.bit.TRIM = (*((uint32_t*) USB_FUSES_TRIM_ADDR) & USB_FUSES_TRIM_Msk) >> USB_FUSES_TRIM_Pos; + + USB->DEVICE.QOSCTRL.bit.CQOS = 3; + USB->DEVICE.QOSCTRL.bit.DQOS = 3; + + tusb_hal_int_enable(0); + return true; +} + +void tusb_hal_int_enable(uint8_t rhport) +{ + (void) rhport; + NVIC_EnableIRQ(USB_0_IRQn); + NVIC_EnableIRQ(USB_1_IRQn); + NVIC_EnableIRQ(USB_2_IRQn); + NVIC_EnableIRQ(USB_3_IRQn); +} + +void tusb_hal_int_disable(uint8_t rhport) +{ + (void) rhport; + NVIC_DisableIRQ(USB_3_IRQn); + NVIC_DisableIRQ(USB_2_IRQn); + NVIC_DisableIRQ(USB_1_IRQn); + NVIC_DisableIRQ(USB_0_IRQn); +} + +#endif diff --git a/src/portable/nordic/nrf5x/dcd_nrf5x.c b/src/portable/nordic/nrf5x/dcd_nrf5x.c index 69e001240..7eeab1306 100644 --- a/src/portable/nordic/nrf5x/dcd_nrf5x.c +++ b/src/portable/nordic/nrf5x/dcd_nrf5x.c @@ -203,7 +203,9 @@ static void xact_control_start(void) bool dcd_control_xfer (uint8_t rhport, uint8_t dir, uint8_t * buffer, uint16_t length) { + (void) rhport; + osal_semaphore_wait( _usbd_ctrl_sem, OSAL_TIMEOUT_CONTROL_XFER); if ( length ) { @@ -216,9 +218,11 @@ bool dcd_control_xfer (uint8_t rhport, uint8_t dir, uint8_t * buffer, uint16_t l xact_control_start(); }else { + NRF_USBD->EPIN[0].PTR = 0; + NRF_USBD->EPIN[0].MAXCNT = 0; // Status Phase also require Easy DMA has to be free as well !!!! - edpt_dma_start(&NRF_USBD->TASKS_EP0STATUS); - edpt_dma_end(); + NRF_USBD->TASKS_EP0STATUS = 1; + osal_semaphore_post(_usbd_ctrl_sem, false); } return true; @@ -434,7 +438,7 @@ void USBD_IRQHandler(void) NRF_USBD->BMREQUESTTYPE , NRF_USBD->BREQUEST, NRF_USBD->WVALUEL , NRF_USBD->WVALUEH, NRF_USBD->WINDEXL , NRF_USBD->WINDEXH , NRF_USBD->WLENGTHL, NRF_USBD->WLENGTHH }; - dcd_event_setup_recieved(0, setup, true); + dcd_event_setup_received(0, setup, true); } if ( int_status & USBD_INTEN_EP0DATADONE_Msk ) diff --git a/src/tusb_option.h b/src/tusb_option.h index 846367129..d7a6c6fe0 100644 --- a/src/tusb_option.h +++ b/src/tusb_option.h @@ -147,6 +147,8 @@ #ifndef CFG_TUD_ENUM_BUFFER_SIZE #define CFG_TUD_CTRL_BUFSIZE 256 + #else + #define CFG_TUD_CTRL_BUFSIZE CFG_TUD_ENUM_BUFFER_SIZE #endif #ifndef CFG_TUD_DESC_AUTO -- cgit v1.3.1 From 7a40ec2647f06c37c6b8f0b8af2c17ba747f0aeb Mon Sep 17 00:00:00 2001 From: Scott Shawcroft Date: Wed, 7 Nov 2018 23:04:34 -0800 Subject: Split out the control endpoint logic --- src/class/cdc/cdc_device.c | 9 +- src/class/cdc/cdc_device.h | 2 +- src/class/hid/hid_device.c | 36 ++--- src/class/hid/hid_device.h | 4 +- src/class/msc/msc_device.c | 11 +- src/class/msc/msc_device.h | 2 +- src/device/control.c | 252 ++++++++++++++++++++++++++++++ src/device/control.h | 95 ++++++++++++ src/device/dcd.h | 16 -- src/device/usbd.c | 278 +++++++--------------------------- src/device/usbd_pvt.h | 6 - src/portable/nordic/nrf5x/dcd_nrf5x.c | 6 +- 12 files changed, 435 insertions(+), 282 deletions(-) create mode 100644 src/device/control.c create mode 100644 src/device/control.h (limited to 'src/class') diff --git a/src/class/cdc/cdc_device.c b/src/class/cdc/cdc_device.c index f3d4622f8..81d7fa526 100644 --- a/src/class/cdc/cdc_device.c +++ b/src/class/cdc/cdc_device.c @@ -45,6 +45,7 @@ // INCLUDE //--------------------------------------------------------------------+ #include "cdc_device.h" +#include "device/control.h" #include "device/usbd_pvt.h" //--------------------------------------------------------------------+ @@ -287,7 +288,7 @@ tusb_error_t cdcd_open(uint8_t rhport, tusb_desc_interface_t const * p_interface return TUSB_ERROR_NONE; } -tusb_error_t cdcd_control_request_st(uint8_t rhport, tusb_control_request_t const * p_request) +tusb_error_t cdcd_control_request(uint8_t rhport, tusb_control_request_t const * p_request, uint16_t bytes_already_sent) { //------------- Class Specific Request -------------// if (p_request->bmRequestType_bit.type != TUSB_REQ_TYPE_CLASS) return TUSB_ERROR_DCD_CONTROL_REQUEST_NOT_SUPPORT; @@ -299,7 +300,7 @@ tusb_error_t cdcd_control_request_st(uint8_t rhport, tusb_control_request_t cons if ( (CDC_REQUEST_GET_LINE_CODING == p_request->bRequest) || (CDC_REQUEST_SET_LINE_CODING == p_request->bRequest) ) { uint16_t len = tu_min16(sizeof(cdc_line_coding_t), p_request->wLength); - usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, (uint8_t*) &p_cdc->line_coding, len); + dcd_edpt_xfer(rhport, TUSB_DIR_IN_MASK, (uint8_t*) &p_cdc->line_coding, len); // Invoke callback if (CDC_REQUEST_SET_LINE_CODING == p_request->bRequest) @@ -309,8 +310,6 @@ tusb_error_t cdcd_control_request_st(uint8_t rhport, tusb_control_request_t cons } else if (CDC_REQUEST_SET_CONTROL_LINE_STATE == p_request->bRequest ) { - dcd_control_status(rhport, p_request->bmRequestType_bit.direction); // ACK control request - // CDC PSTN v1.2 section 6.3.12 // Bit 0: Indicates if DTE is present or not. // This signal corresponds to V.24 signal 108/2 and RS-232 signal DTR (Data Terminal Ready) @@ -323,7 +322,7 @@ tusb_error_t cdcd_control_request_st(uint8_t rhport, tusb_control_request_t cons } else { - dcd_control_stall(rhport); // stall unsupported request + return TUSB_ERROR_FAILED; // stall unsupported request } return TUSB_ERROR_NONE; } diff --git a/src/class/cdc/cdc_device.h b/src/class/cdc/cdc_device.h index 2e03793a9..88d37a83c 100644 --- a/src/class/cdc/cdc_device.h +++ b/src/class/cdc/cdc_device.h @@ -112,7 +112,7 @@ ATTR_WEAK void tud_cdc_line_coding_cb(uint8_t itf, cdc_line_coding_t const* p_li void cdcd_init (void); tusb_error_t cdcd_open (uint8_t rhport, tusb_desc_interface_t const * p_interface_desc, uint16_t *p_length); -tusb_error_t cdcd_control_request_st (uint8_t rhport, tusb_control_request_t const * p_request); +tusb_error_t cdcd_control_request (uint8_t rhport, tusb_control_request_t const * p_request, uint16_t bytes_already_sent); tusb_error_t cdcd_xfer_cb (uint8_t rhport, uint8_t edpt_addr, tusb_event_t event, uint32_t xferred_bytes); void cdcd_reset (uint8_t rhport); diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index 3e74950e6..aa7a8008e 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -46,6 +46,7 @@ //--------------------------------------------------------------------+ #include "common/tusb_common.h" #include "hid_device.h" +#include "device/control.h" #include "device/usbd_pvt.h" //--------------------------------------------------------------------+ @@ -402,7 +403,7 @@ tusb_error_t hidd_open(uint8_t rhport, tusb_desc_interface_t const * desc_itf, u return TUSB_ERROR_NONE; } -tusb_error_t hidd_control_request_st(uint8_t rhport, tusb_control_request_t const * p_request) +tusb_error_t hidd_control_request(uint8_t rhport, tusb_control_request_t const * p_request, uint16_t bytes_already_sent) { hidd_interface_t* p_hid = get_interface_by_itfnum( (uint8_t) p_request->wIndex ); TU_ASSERT(p_hid, TUSB_ERROR_FAILED); @@ -416,14 +417,17 @@ tusb_error_t hidd_control_request_st(uint8_t rhport, tusb_control_request_t cons if (p_request->bRequest == TUSB_REQ_GET_DESCRIPTOR && desc_type == HID_DESC_TYPE_REPORT) { - // use device control buffer - TU_ASSERT ( p_hid->desc_len <= CFG_TUD_CTRL_BUFSIZE ); - memcpy(_usbd_ctrl_buf, p_hid->desc_report, p_hid->desc_len); + // TODO: Handle zero length packet. + uint16_t remaining_bytes = p_hid->desc_len - bytes_already_sent; + if (remaining_bytes > 64) { + remaining_bytes = 64; + } + memcpy(_shared_control_buffer, p_hid->desc_report + bytes_already_sent, remaining_bytes); - usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, _usbd_ctrl_buf, p_hid->desc_len); + dcd_edpt_xfer(rhport, TUSB_DIR_IN_MASK, _shared_control_buffer, remaining_bytes); }else { - dcd_control_stall(rhport); + return TUSB_ERROR_FAILED; } } //------------- Class Specific Request -------------// @@ -446,11 +450,11 @@ tusb_error_t hidd_control_request_st(uint8_t rhport, tusb_control_request_t cons } TU_ASSERT( xferlen > 0 ); - usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, p_hid->report_buf, xferlen); + dcd_edpt_xfer(rhport, TUSB_DIR_IN_MASK, _shared_control_buffer, xferlen); } else if ( HID_REQ_CONTROL_SET_REPORT == p_request->bRequest ) { - usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, _usbd_ctrl_buf, p_request->wLength); + dcd_edpt_xfer(rhport, 0, _shared_control_buffer, p_request->wLength); // wValue = Report Type | Report ID uint8_t const report_type = tu_u16_high(p_request->wValue); @@ -458,37 +462,35 @@ tusb_error_t hidd_control_request_st(uint8_t rhport, tusb_control_request_t cons if ( p_hid->set_report_cb ) { - p_hid->set_report_cb(report_id, (hid_report_type_t) report_type, _usbd_ctrl_buf, p_request->wLength); + p_hid->set_report_cb(report_id, (hid_report_type_t) report_type, _shared_control_buffer, p_request->wLength); } } else if (HID_REQ_CONTROL_SET_IDLE == p_request->bRequest) { // TODO idle rate of report p_hid->idle_rate = tu_u16_high(p_request->wValue); - dcd_control_status(rhport, p_request->bmRequestType_bit.direction); } else if (HID_REQ_CONTROL_GET_IDLE == p_request->bRequest) { // TODO idle rate of report - _usbd_ctrl_buf[0] = p_hid->idle_rate; - usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, _usbd_ctrl_buf, 1); + _shared_control_buffer[0] = p_hid->idle_rate; + dcd_edpt_xfer(rhport, TUSB_DIR_IN_MASK, _shared_control_buffer, 1); } else if (HID_REQ_CONTROL_GET_PROTOCOL == p_request->bRequest ) { - _usbd_ctrl_buf[0] = 1-p_hid->boot_protocol; // 0 is Boot, 1 is Report protocol - usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, _usbd_ctrl_buf, 1); + _shared_control_buffer[0] = 1-p_hid->boot_protocol; // 0 is Boot, 1 is Report protocol + dcd_edpt_xfer(rhport, TUSB_DIR_IN_MASK, _shared_control_buffer, 1); } else if (HID_REQ_CONTROL_SET_PROTOCOL == p_request->bRequest ) { p_hid->boot_protocol = 1 - p_request->wValue; // 0 is Boot, 1 is Report protocol - dcd_control_status(rhport, p_request->bmRequestType_bit.direction); }else { - dcd_control_stall(rhport); + return TUSB_ERROR_FAILED; } }else { - dcd_control_stall(rhport); + return TUSB_ERROR_FAILED; } return TUSB_ERROR_NONE; } diff --git a/src/class/hid/hid_device.h b/src/class/hid/hid_device.h index d5b9f3831..10aea10ac 100644 --- a/src/class/hid/hid_device.h +++ b/src/class/hid/hid_device.h @@ -378,7 +378,7 @@ ATTR_WEAK void tud_hid_mouse_set_report_cb(uint8_t report_id, hid_report_type_t void hidd_init(void); tusb_error_t hidd_open(uint8_t rhport, tusb_desc_interface_t const * p_interface_desc, uint16_t *p_length); -tusb_error_t hidd_control_request_st(uint8_t rhport, tusb_control_request_t const * p_request); +tusb_error_t hidd_control_request(uint8_t rhport, tusb_control_request_t const * p_request, uint16_t bytes_already_sent); tusb_error_t hidd_xfer_cb(uint8_t rhport, uint8_t edpt_addr, tusb_event_t event, uint32_t xferred_bytes); void hidd_reset(uint8_t rhport); @@ -389,5 +389,3 @@ void hidd_reset(uint8_t rhport); #endif #endif /* _TUSB_HID_DEVICE_H_ */ - - diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index aa9ebbbc9..3c9997b95 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -47,6 +47,7 @@ #include "common/tusb_common.h" #include "msc_device.h" +#include "device/control.h" #include "device/usbd_pvt.h" //--------------------------------------------------------------------+ @@ -146,22 +147,22 @@ tusb_error_t mscd_open(uint8_t rhport, tusb_desc_interface_t const * p_desc_itf, return TUSB_ERROR_NONE; } -tusb_error_t mscd_control_request_st(uint8_t rhport, tusb_control_request_t const * p_request) +tusb_error_t mscd_control_request(uint8_t rhport, tusb_control_request_t const * p_request, uint16_t bytes_already_sent) { TU_ASSERT(p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS, TUSB_ERROR_DCD_CONTROL_REQUEST_NOT_SUPPORT); if(MSC_REQ_RESET == p_request->bRequest) { - dcd_control_status(rhport, p_request->bmRequestType_bit.direction); + // TODO: Actually reset. } else if (MSC_REQ_GET_MAX_LUN == p_request->bRequest) { // returned MAX LUN is minus 1 by specs - _usbd_ctrl_buf[0] = CFG_TUD_MSC_MAXLUN-1; - usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, _usbd_ctrl_buf, 1); + _shared_control_buffer[0] = CFG_TUD_MSC_MAXLUN-1; + dcd_edpt_xfer(rhport, TUSB_DIR_IN_MASK, _shared_control_buffer, 1); }else { - dcd_control_stall(rhport); // stall unsupported request + return TUSB_ERROR_FAILED; // stall unsupported request } return TUSB_ERROR_NONE; } diff --git a/src/class/msc/msc_device.h b/src/class/msc/msc_device.h index 92ab4dde0..a5bc54ff9 100644 --- a/src/class/msc/msc_device.h +++ b/src/class/msc/msc_device.h @@ -198,7 +198,7 @@ ATTR_WEAK bool tud_lun_capacity_cb(uint8_t lun, uint32_t* last_valid_sector, uin void mscd_init(void); tusb_error_t mscd_open(uint8_t rhport, tusb_desc_interface_t const * p_interface_desc, uint16_t *p_length); -tusb_error_t mscd_control_request_st(uint8_t rhport, tusb_control_request_t const * p_request); +tusb_error_t mscd_control_request(uint8_t rhport, tusb_control_request_t const * p_request, uint16_t bytes_already_sent); tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t edpt_addr, tusb_event_t event, uint32_t xferred_bytes); void mscd_reset(uint8_t rhport); diff --git a/src/device/control.c b/src/device/control.c new file mode 100644 index 000000000..4944a999e --- /dev/null +++ b/src/device/control.c @@ -0,0 +1,252 @@ +/**************************************************************************/ +/*! + @file usbd.c + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#include "tusb_option.h" + +#if TUSB_OPT_DEVICE_ENABLED + +#define _TINY_USB_SOURCE_FILE_ + +#include "tusb.h" +#include "control.h" +#include "device/usbd_pvt.h" + +control_t control_state; + +void controld_reset(uint8_t rhport) { + control_state.current_stage = CONTROL_STAGE_SETUP; +} + +void controld_init(void) { +} + +// Helper to send STATUS (zero length) packet +// Note dir is value of direction bit in setup packet (i.e DATA stage direction) +static inline bool dcd_control_status(uint8_t rhport, uint8_t dir) +{ + // status direction is reversed to one in the setup packet + return dcd_edpt_xfer(rhport, 1-dir, NULL, 0); +} + +static inline void dcd_control_stall(uint8_t rhport) +{ + dcd_edpt_stall(rhport, 0 | TUSB_DIR_IN_MASK); +} + + +// return len of descriptor and change pointer to descriptor's buffer +static uint16_t get_descriptor(uint8_t rhport, tusb_control_request_t const * const p_request, uint8_t const ** pp_buffer) +{ + (void) rhport; + + tusb_desc_type_t const desc_type = (tusb_desc_type_t) tu_u16_high(p_request->wValue); + uint8_t const desc_index = tu_u16_low( p_request->wValue ); + + uint8_t const * desc_data = NULL ; + uint16_t len = 0; + + switch(desc_type) + { + case TUSB_DESC_DEVICE: + desc_data = (uint8_t const *) usbd_desc_set->device; + len = sizeof(tusb_desc_device_t); + break; + + case TUSB_DESC_CONFIGURATION: + desc_data = (uint8_t const *) usbd_desc_set->config; + len = ((tusb_desc_configuration_t const*) desc_data)->wTotalLength; + break; + + case TUSB_DESC_STRING: + // String Descriptor always uses the desc set from user + if ( desc_index < tud_desc_set.string_count ) + { + desc_data = tud_desc_set.string_arr[desc_index]; + TU_VERIFY( desc_data != NULL, 0 ); + + len = desc_data[0]; // first byte of descriptor is its size + }else + { + // out of range + /* The 0xee string is indeed a Microsoft USB extension. + * It can be used to tell Windows what driver it should use for the device !!! + */ + return 0; + } + break; + + case TUSB_DESC_DEVICE_QUALIFIER: + // TODO If not highspeed capable stall this request otherwise + // return the descriptor that could work in highspeed + return 0; + break; + + default: return 0; + } + + TU_ASSERT( desc_data != NULL, 0); + + // up to Host's length + len = tu_min16(p_request->wLength, len ); + (*pp_buffer) = desc_data; + + return len; +} + +tusb_error_t controld_xfer_cb(uint8_t rhport, uint8_t edpt_addr, tusb_event_t event, uint32_t xferred_bytes) { + if (control_state.current_stage == CONTROL_STAGE_STATUS && xferred_bytes == 0) { + control_state.current_stage = CONTROL_STAGE_SETUP; + return TUSB_ERROR_NONE; + } + tusb_error_t error = TUSB_ERROR_NONE; + control_state.total_transferred += xferred_bytes; + tusb_control_request_t const *p_request = &control_state.current_request; + + if (p_request->wLength == control_state.total_transferred || xferred_bytes < 64) { + control_state.current_stage = CONTROL_STAGE_STATUS; + dcd_control_status(rhport, p_request->bmRequestType_bit.direction); + } else { + if (TUSB_REQ_RCPT_INTERFACE == p_request->bmRequestType_bit.recipient) { + error = tud_control_interface_control_cb(rhport, tu_u16_low(p_request->wIndex), p_request, control_state.total_transferred); + } else { + error = controld_process_control_request(rhport, p_request, control_state.total_transferred); + } + } + return error; +} + +// This tracks the state of a control request. +tusb_error_t controld_process_setup_request(uint8_t rhport, tusb_control_request_t const * p_request) { + tusb_error_t error = TUSB_ERROR_NONE; + memcpy(&control_state.current_request, p_request, sizeof(tusb_control_request_t)); + if (p_request->wLength == 0) { + control_state.current_stage = CONTROL_STAGE_STATUS; + } else { + control_state.current_stage = CONTROL_STAGE_DATA; + control_state.total_transferred = 0; + } + + + if ( TUSB_REQ_RCPT_INTERFACE == p_request->bmRequestType_bit.recipient ) + { + error = tud_control_interface_control_cb(rhport, tu_u16_low(p_request->wIndex), p_request, 0); + } else { + error = controld_process_control_request(rhport, p_request, 0); + } + + if (error != TUSB_ERROR_NONE) { + dcd_control_stall(rhport); // Stall errored requests + } else if (control_state.current_stage == CONTROL_STAGE_STATUS) { + dcd_control_status(rhport, p_request->bmRequestType_bit.direction); + } + return error; +} + +// This handles the actual request and its response. +tusb_error_t controld_process_control_request(uint8_t rhport, tusb_control_request_t const * p_request, uint16_t bytes_already_sent) +{ + tusb_error_t error = TUSB_ERROR_NONE; + uint8_t ep_addr = 0; + if (p_request->bmRequestType_bit.direction == TUSB_DIR_IN) { + ep_addr |= TUSB_DIR_IN_MASK; + } + + //------------- Standard Request e.g in enumeration -------------// + if( TUSB_REQ_RCPT_DEVICE == p_request->bmRequestType_bit.recipient && + TUSB_REQ_TYPE_STANDARD == p_request->bmRequestType_bit.type ) { + switch (p_request->bRequest) { + case TUSB_REQ_GET_DESCRIPTOR: { + uint8_t const * buffer = NULL; + uint16_t const len = get_descriptor(rhport, p_request, &buffer); + + if (len) { + uint16_t remaining_bytes = len - bytes_already_sent; + if (remaining_bytes > 64) { + remaining_bytes = 64; + } + memcpy(_shared_control_buffer, buffer + bytes_already_sent, remaining_bytes); + dcd_edpt_xfer(rhport, ep_addr, _shared_control_buffer, remaining_bytes); + } else { + return TUSB_ERROR_FAILED; + } + break; + } + case TUSB_REQ_GET_CONFIGURATION: + memcpy(_shared_control_buffer, &control_state.config, 1); + dcd_edpt_xfer(rhport, ep_addr, _shared_control_buffer, 1); + break; + case TUSB_REQ_SET_ADDRESS: + dcd_set_address(rhport, (uint8_t) p_request->wValue); + break; + case TUSB_REQ_SET_CONFIGURATION: + control_state.config = p_request->wValue; + tud_control_set_config_cb (rhport, control_state.config); + break; + default: + return TUSB_ERROR_FAILED; + } + } else if (p_request->bmRequestType_bit.recipient == TUSB_REQ_RCPT_ENDPOINT && + p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD) { + //------------- Endpoint Request -------------// + switch (p_request->bRequest) { + case TUSB_REQ_GET_STATUS: { + uint16_t status = dcd_edpt_stalled(rhport, tu_u16_low(p_request->wIndex)) ? 0x0001 : 0x0000; + memcpy(_shared_control_buffer, &status, 2); + + dcd_edpt_xfer(rhport, ep_addr, _shared_control_buffer, 2); + break; + } + case TUSB_REQ_CLEAR_FEATURE: + // only endpoint feature is halted/stalled + dcd_edpt_clear_stall(rhport, tu_u16_low(p_request->wIndex)); + break; + case TUSB_REQ_SET_FEATURE: + // only endpoint feature is halted/stalled + dcd_edpt_stall(rhport, tu_u16_low(p_request->wIndex)); + break; + default: + return TUSB_ERROR_FAILED; + } + } else { + //------------- Unsupported Request -------------// + return TUSB_ERROR_FAILED; + } + return error; +} + +#endif diff --git a/src/device/control.h b/src/device/control.h new file mode 100644 index 000000000..24f0d0a14 --- /dev/null +++ b/src/device/control.h @@ -0,0 +1,95 @@ +/**************************************************************************/ +/*! + @file usbd.h + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +/** \ingroup group_usbd + * @{ */ + +#ifndef _TUSB_CONTROL_H_ +#define _TUSB_CONTROL_H_ + +#ifdef __cplusplus + extern "C" { +#endif + +#include "tusb.h" + +typedef enum { + CONTROL_STAGE_SETUP, // Waiting for a setup token. + CONTROL_STAGE_DATA, // In the process of sending or receiving data. + CONTROL_STAGE_STATUS // In the process of transmitting the STATUS ZLP. +} control_stage_t; + +typedef struct { + control_stage_t current_stage; + tusb_control_request_t current_request; + uint16_t total_transferred; + uint8_t config; +} control_t; + +CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN uint8_t _shared_control_buffer[64]; + +tusb_error_t controld_process_setup_request(uint8_t rhport, tusb_control_request_t const * const p_request); + +// Callback when the configuration of the device is changed. +tusb_error_t tud_control_set_config_cb(uint8_t rhport, uint8_t config_number); + +tusb_error_t tud_control_interface_control_cb(uint8_t rhport, uint8_t interface, tusb_control_request_t const * const p_request, uint16_t bytes_already_sent); + +//--------------------------------------------------------------------+ +// INTERNAL API +//--------------------------------------------------------------------+ + +void controld_init(void); +tusb_error_t controld_open(uint8_t rhport, tusb_desc_interface_t const * p_interface_desc, uint16_t *p_length); + +// This tracks the state of a control request. +tusb_error_t controld_process_setup_request(uint8_t rhport, tusb_control_request_t const * p_request); + +// This handles the actual request and its response. +tusb_error_t controld_process_control_request(uint8_t rhport, tusb_control_request_t const * p_request, uint16_t bytes_already_sent); + +tusb_error_t controld_xfer_cb(uint8_t rhport, uint8_t edpt_addr, tusb_event_t event, uint32_t xferred_bytes); +void controld_reset(uint8_t rhport); + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_CONTROL_H_ */ + +/** @} */ diff --git a/src/device/dcd.h b/src/device/dcd.h index c1715a5b7..0c976edec 100644 --- a/src/device/dcd.h +++ b/src/device/dcd.h @@ -135,22 +135,6 @@ void dcd_edpt_stall (uint8_t rhport, uint8_t ep_addr); void dcd_edpt_clear_stall (uint8_t rhport, uint8_t ep_addr); bool dcd_edpt_stalled (uint8_t rhport, uint8_t ep_addr); -//------------- Control Endpoint -------------// -bool dcd_control_xfer (uint8_t rhport, uint8_t dir, uint8_t * buffer, uint16_t length); - -// Helper to send STATUS (zero length) packet -// Note dir is value of direction bit in setup packet (i.e DATA stage direction) -static inline bool dcd_control_status(uint8_t rhport, uint8_t dir) -{ - // status direction is reversed to one in the setup packet - return dcd_control_xfer(rhport, 1-dir, NULL, 0); -} - -static inline void dcd_control_stall(uint8_t rhport) -{ - dcd_edpt_stall(rhport, 0 | TUSB_DIR_IN_MASK); -} - #ifdef __cplusplus } #endif diff --git a/src/device/usbd.c b/src/device/usbd.c index 8155b585f..3c77fefba 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -36,12 +36,15 @@ */ /**************************************************************************/ +// This top level class manages the bus state and delegates events to class-specific drivers. + #include "tusb_option.h" #if TUSB_OPT_DEVICE_ENABLED #define _TINY_USB_SOURCE_FILE_ +#include "control.h" #include "tusb.h" #include "usbd.h" #include "device/usbd_pvt.h" @@ -72,7 +75,6 @@ typedef struct { uint8_t ep2drv[2][8]; }usbd_device_t; -CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN uint8_t _usbd_ctrl_buf[CFG_TUD_CTRL_BUFSIZE]; static usbd_device_t _usbd_dev; @@ -92,7 +94,8 @@ typedef struct { void (* init ) (void); tusb_error_t (* open ) (uint8_t rhport, tusb_desc_interface_t const * desc_intf, uint16_t* p_length); - tusb_error_t (* control_req_st ) (uint8_t rhport, tusb_control_request_t const *); + // Control request is called one or more times for a request and can queue multiple data packets. + tusb_error_t (* control_request ) (uint8_t rhport, tusb_control_request_t const *, uint16_t bytes_already_sent); tusb_error_t (* xfer_cb ) (uint8_t rhport, uint8_t ep_addr, tusb_event_t, uint32_t); void (* sof ) (uint8_t rhport); void (* reset ) (uint8_t); @@ -100,52 +103,61 @@ typedef struct { static usbd_class_driver_t const usbd_class_drivers[] = { + { + .class_code = TUSB_CLASS_UNSPECIFIED, + .init = controld_init, + .open = NULL, + .control_request = NULL, + .xfer_cb = controld_xfer_cb, + .sof = NULL, + .reset = controld_reset + }, #if CFG_TUD_CDC { - .class_code = TUSB_CLASS_CDC, - .init = cdcd_init, - .open = cdcd_open, - .control_req_st = cdcd_control_request_st, - .xfer_cb = cdcd_xfer_cb, - .sof = NULL, - .reset = cdcd_reset + .class_code = TUSB_CLASS_CDC, + .init = cdcd_init, + .open = cdcd_open, + .control_request = cdcd_control_request, + .xfer_cb = cdcd_xfer_cb, + .sof = NULL, + .reset = cdcd_reset }, #endif #if CFG_TUD_MSC { - .class_code = TUSB_CLASS_MSC, - .init = mscd_init, - .open = mscd_open, - .control_req_st = mscd_control_request_st, - .xfer_cb = mscd_xfer_cb, - .sof = NULL, - .reset = mscd_reset + .class_code = TUSB_CLASS_MSC, + .init = mscd_init, + .open = mscd_open, + .control_request = mscd_control_request, + .xfer_cb = mscd_xfer_cb, + .sof = NULL, + .reset = mscd_reset }, #endif #if CFG_TUD_HID { - .class_code = TUSB_CLASS_HID, - .init = hidd_init, - .open = hidd_open, - .control_req_st = hidd_control_request_st, - .xfer_cb = hidd_xfer_cb, - .sof = NULL, - .reset = hidd_reset + .class_code = TUSB_CLASS_HID, + .init = hidd_init, + .open = hidd_open, + .control_request = hidd_control_request, + .xfer_cb = hidd_xfer_cb, + .sof = NULL, + .reset = hidd_reset }, #endif #if CFG_TUD_CUSTOM_CLASS { - .class_code = TUSB_CLASS_VENDOR_SPECIFIC, - .init = cusd_init, - .open = cusd_open, - .control_req_st = cusd_control_request_st, - .xfer_cb = cusd_xfer_cb, - .sof = NULL, - .reset = cusd_reset + .class_code = TUSB_CLASS_VENDOR_SPECIFIC, + .init = cusd_init, + .open = cusd_open, + .control_request = cusd_control_request, + .xfer_cb = cusd_xfer_cb, + .sof = NULL, + .reset = cusd_reset }, #endif }; @@ -162,16 +174,10 @@ OSAL_TASK_DEF(_usbd_task_def, "usbd", usbd_task, CFG_TUD_TASK_PRIO, CFG_TUD_TASK OSAL_QUEUE_DEF(_usbd_qdef, CFG_TUD_TASK_QUEUE_SZ, dcd_event_t); static osal_queue_t _usbd_q; -/*------------- control transfer semaphore -------------*/ -static osal_semaphore_def_t _usbd_sem_def; -osal_semaphore_t _usbd_ctrl_sem; - //--------------------------------------------------------------------+ // INTERNAL FUNCTION //--------------------------------------------------------------------+ static void mark_interface_endpoint(uint8_t const* p_desc, uint16_t desc_len, uint8_t driver_id); -static tusb_error_t proc_set_config_req(uint8_t rhport, uint8_t config_number); -static uint16_t get_descriptor(uint8_t rhport, tusb_control_request_t const * const p_request, uint8_t const ** pp_buffer); //--------------------------------------------------------------------+ // APPLICATION API @@ -184,7 +190,6 @@ bool tud_mounted(void) //--------------------------------------------------------------------+ // IMPLEMENTATION //--------------------------------------------------------------------+ -static tusb_error_t proc_control_request_st(uint8_t rhport, tusb_control_request_t const * const p_request); static tusb_error_t usbd_main_st(void); tusb_error_t usbd_init (void) @@ -201,9 +206,6 @@ tusb_error_t usbd_init (void) _usbd_q = osal_queue_create(&_usbd_qdef); TU_VERIFY(_usbd_q, TUSB_ERROR_OSAL_QUEUE_FAILED); - _usbd_ctrl_sem = osal_semaphore_create(&_usbd_sem_def); - TU_VERIFY(_usbd_q, TUSB_ERROR_OSAL_SEMAPHORE_FAILED); - osal_task_create(&_usbd_task_def); //------------- class init -------------// @@ -217,6 +219,9 @@ static void usbd_reset(uint8_t rhport) tu_varclr(&_usbd_dev); memset(_usbd_dev.itf2drv, 0xff, sizeof(_usbd_dev.itf2drv)); // invalid mapping memset(_usbd_dev.ep2drv , 0xff, sizeof(_usbd_dev.ep2drv )); // invalid mapping + // Always map the 0th endpoint to the control driver. + _usbd_dev.ep2drv[TUSB_DIR_IN][0] = 0; + _usbd_dev.ep2drv[TUSB_DIR_OUT][0] = 0; for (uint8_t i = 0; i < USBD_CLASS_DRIVER_COUNT; i++) { @@ -239,8 +244,6 @@ void usbd_task( void* param) OSAL_TASK_END } -extern uint32_t setup_count; - static tusb_error_t usbd_main_st(void) { dcd_event_t event; @@ -257,7 +260,8 @@ static tusb_error_t usbd_main_st(void) if ( DCD_EVENT_SETUP_RECEIVED == event.event_id ) { - proc_control_request_st(event.rhport, &event.setup_received); + // Setup tokens are unique to the Control endpointso we delegate to it directly. + controld_process_setup_request(event.rhport, &event.setup_received); } else if (DCD_EVENT_XFER_COMPLETE == event.event_id) { @@ -274,13 +278,11 @@ static tusb_error_t usbd_main_st(void) { usbd_reset(event.rhport); osal_queue_reset(_usbd_q); - osal_semaphore_reset(_usbd_ctrl_sem); } else if (DCD_EVENT_UNPLUGGED == event.event_id) { usbd_reset(event.rhport); osal_queue_reset(_usbd_q); - osal_semaphore_reset(_usbd_ctrl_sem); tud_umount_cb(); // invoke callback } @@ -307,113 +309,18 @@ static tusb_error_t usbd_main_st(void) return err; } -//--------------------------------------------------------------------+ -// CONTROL REQUEST -//--------------------------------------------------------------------+ -static tusb_error_t proc_control_request_st(uint8_t rhport, tusb_control_request_t const * const p_request) -{ - tusb_error_t error = TUSB_ERROR_NONE; - - //------------- Standard Request e.g in enumeration -------------// - if( TUSB_REQ_RCPT_DEVICE == p_request->bmRequestType_bit.recipient && - TUSB_REQ_TYPE_STANDARD == p_request->bmRequestType_bit.type ) - { - if ( TUSB_REQ_GET_DESCRIPTOR == p_request->bRequest ) - { - uint8_t const * buffer = NULL; - uint16_t const len = get_descriptor(rhport, p_request, &buffer); - - - if ( len ) - { - TU_ASSERT( len <= CFG_TUD_CTRL_BUFSIZE ); - memcpy(_usbd_ctrl_buf, buffer, len); - usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, _usbd_ctrl_buf, len); - }else - { - dcd_control_stall(rhport); // stall unsupported descriptor - } - } - else if (TUSB_REQ_GET_CONFIGURATION == p_request->bRequest ) - { - memcpy(_usbd_ctrl_buf, &_usbd_dev.config_num, 1); - usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, _usbd_ctrl_buf, 1); - } - else if ( TUSB_REQ_SET_ADDRESS == p_request->bRequest ) - { - dcd_set_address(rhport, (uint8_t) p_request->wValue); - - #if CFG_TUSB_MCU != OPT_MCU_NRF5X // nrf5x auto handle set address, we must not return status - dcd_control_status(rhport, p_request->bmRequestType_bit.direction); - #endif - } - else if ( TUSB_REQ_SET_CONFIGURATION == p_request->bRequest ) - { - proc_set_config_req(rhport, (uint8_t) p_request->wValue); - dcd_control_status(rhport, p_request->bmRequestType_bit.direction); - } - else - { - dcd_control_stall(rhport); // Stall unsupported request - } - } - - //------------- Class/Interface Specific Request -------------// - else if ( TUSB_REQ_RCPT_INTERFACE == p_request->bmRequestType_bit.recipient ) - { - if (_usbd_dev.itf2drv[ tu_u16_low(p_request->wIndex) ] < USBD_CLASS_DRIVER_COUNT) - { - error = usbd_class_drivers[ _usbd_dev.itf2drv[ tu_u16_low(p_request->wIndex) ] ].control_req_st(rhport, p_request); - }else - { - dcd_control_stall(rhport); // Stall unsupported request - } - } - - //------------- Endpoint Request -------------// - else if ( TUSB_REQ_RCPT_ENDPOINT == p_request->bmRequestType_bit.recipient && - TUSB_REQ_TYPE_STANDARD == p_request->bmRequestType_bit.type) - { - if (TUSB_REQ_GET_STATUS == p_request->bRequest ) - { - uint16_t status = dcd_edpt_stalled(rhport, tu_u16_low(p_request->wIndex)) ? 0x0001 : 0x0000; - memcpy(_usbd_ctrl_buf, &status, 2); - - usbd_control_xfer_st(rhport, p_request->bmRequestType_bit.direction, _usbd_ctrl_buf, 2); - } - else if (TUSB_REQ_CLEAR_FEATURE == p_request->bRequest ) - { - // only endpoint feature is halted/stalled - dcd_edpt_clear_stall(rhport, tu_u16_low(p_request->wIndex)); - dcd_control_status(rhport, p_request->bmRequestType_bit.direction); - } - else if (TUSB_REQ_SET_FEATURE == p_request->bRequest ) +tusb_error_t tud_control_interface_control_cb(uint8_t rhport, uint8_t interface, tusb_control_request_t const * const p_request, uint16_t bytes_already_sent) { + if (_usbd_dev.itf2drv[ interface ] < USBD_CLASS_DRIVER_COUNT) { - // only endpoint feature is halted/stalled - dcd_edpt_stall(rhport, tu_u16_low(p_request->wIndex)); - dcd_control_status(rhport, p_request->bmRequestType_bit.direction); + return usbd_class_drivers[_usbd_dev.itf2drv[interface]].control_request(rhport, p_request, bytes_already_sent); } - else - { - dcd_control_stall(rhport); // Stall unsupported request - } - } - - //------------- Unsupported Request -------------// - else - { - dcd_control_stall(rhport); // Stall unsupported request - } - if (error != TUSB_ERROR_NONE) { - dcd_control_stall(rhport); // Stall errored requests - } - return error; + return TUSB_ERROR_FAILED; } // Process Set Configure Request // TODO Host (windows) can get HID report descriptor before set configured // may need to open interface before set configured -static tusb_error_t proc_set_config_req(uint8_t rhport, uint8_t config_number) +tusb_error_t tud_control_set_config_cb(uint8_t rhport, uint8_t config_number) { dcd_set_config(rhport, config_number); @@ -465,65 +372,6 @@ static tusb_error_t proc_set_config_req(uint8_t rhport, uint8_t config_number) return TUSB_ERROR_NONE; } -// return len of descriptor and change pointer to descriptor's buffer -static uint16_t get_descriptor(uint8_t rhport, tusb_control_request_t const * const p_request, uint8_t const ** pp_buffer) -{ - (void) rhport; - - tusb_desc_type_t const desc_type = (tusb_desc_type_t) tu_u16_high(p_request->wValue); - uint8_t const desc_index = tu_u16_low( p_request->wValue ); - - uint8_t const * desc_data = NULL ; - uint16_t len = 0; - - switch(desc_type) - { - case TUSB_DESC_DEVICE: - desc_data = (uint8_t const *) usbd_desc_set->device; - len = sizeof(tusb_desc_device_t); - break; - - case TUSB_DESC_CONFIGURATION: - desc_data = (uint8_t const *) usbd_desc_set->config; - len = ((tusb_desc_configuration_t const*) desc_data)->wTotalLength; - break; - - case TUSB_DESC_STRING: - // String Descriptor always uses the desc set from user - if ( desc_index < tud_desc_set.string_count ) - { - desc_data = tud_desc_set.string_arr[desc_index]; - TU_VERIFY( desc_data != NULL, 0 ); - - len = desc_data[0]; // first byte of descriptor is its size - }else - { - // out of range - /* The 0xee string is indeed a Microsoft USB extension. - * It can be used to tell Windows what driver it should use for the device !!! - */ - return 0; - } - break; - - case TUSB_DESC_DEVICE_QUALIFIER: - // TODO If not highspeed capable stall this request otherwise - // return the descriptor that could work in highspeed - return 0; - break; - - default: return 0; - } - - TU_ASSERT( desc_data != NULL, 0); - - // up to Host's length - len = tu_min16(p_request->wLength, len ); - (*pp_buffer) = desc_data; - - return len; -} - // Helper marking endpoint of interface belongs to class driver static void mark_interface_endpoint(uint8_t const* p_desc, uint16_t desc_len, uint8_t driver_id) { @@ -569,18 +417,7 @@ void dcd_event_handler(dcd_event_t const * event, bool in_isr) break; case DCD_EVENT_XFER_COMPLETE: - if (event->xfer_complete.ep_addr == 0) - { - // only signal data stage, skip status (zero byte) - if (event->xfer_complete.len) - { - (void) event->xfer_complete.result; // TODO handle control error/stalled - osal_semaphore_post( _usbd_ctrl_sem, in_isr); - } - }else - { - osal_queue_send(_usbd_q, event, in_isr); - } + osal_queue_send(_usbd_q, event, in_isr); TU_ASSERT(event->xfer_complete.result == DCD_XFER_SUCCESS,); break; @@ -621,15 +458,6 @@ void dcd_event_xfer_complete (uint8_t rhport, uint8_t ep_addr, uint32_t xferred_ //--------------------------------------------------------------------+ // Helper //--------------------------------------------------------------------+ -uint32_t usbd_control_xfer_st(uint8_t _rhport, uint8_t _dir, uint8_t* _buffer, uint16_t _len) { - uint32_t err = TUSB_ERROR_NONE; - if (_len) { - dcd_control_xfer(_rhport, _dir, (uint8_t*) _buffer, _len); - } - - dcd_control_status(_rhport, _dir); - return err; -} tusb_error_t usbd_open_edpt_pair(uint8_t rhport, tusb_desc_endpoint_t const* p_desc_ep, uint8_t xfer_type, uint8_t* ep_out, uint8_t* ep_in) { diff --git a/src/device/usbd_pvt.h b/src/device/usbd_pvt.h index ecb71f771..bbbe0a604 100644 --- a/src/device/usbd_pvt.h +++ b/src/device/usbd_pvt.h @@ -45,10 +45,6 @@ extern "C" { #endif -// for used by usbd_control_xfer_st() only, must not be used directly -extern osal_semaphore_t _usbd_ctrl_sem; -extern uint8_t _usbd_ctrl_buf[CFG_TUD_CTRL_BUFSIZE]; - // Either point to tud_desc_set or usbd_auto_desc_set depending on CFG_TUD_DESC_AUTO extern tud_desc_set_t const* usbd_desc_set; @@ -64,8 +60,6 @@ void usbd_task (void* param); // helper to parse an pair of In and Out endpoint descriptors. They must be consecutive tusb_error_t usbd_open_edpt_pair(uint8_t rhport, tusb_desc_endpoint_t const* p_desc_ep, uint8_t xfer_type, uint8_t* ep_out, uint8_t* ep_in); -uint32_t usbd_control_xfer_st(uint8_t _rhport, uint8_t _dir, uint8_t* _buffer, uint16_t _len); - /*------------------------------------------------------------------*/ /* Other Helpers *------------------------------------------------------------------*/ diff --git a/src/portable/nordic/nrf5x/dcd_nrf5x.c b/src/portable/nordic/nrf5x/dcd_nrf5x.c index 7eeab1306..1e3dc4cba 100644 --- a/src/portable/nordic/nrf5x/dcd_nrf5x.c +++ b/src/portable/nordic/nrf5x/dcd_nrf5x.c @@ -203,9 +203,7 @@ static void xact_control_start(void) bool dcd_control_xfer (uint8_t rhport, uint8_t dir, uint8_t * buffer, uint16_t length) { - (void) rhport; - osal_semaphore_wait( _usbd_ctrl_sem, OSAL_TIMEOUT_CONTROL_XFER); if ( length ) { @@ -222,7 +220,9 @@ bool dcd_control_xfer (uint8_t rhport, uint8_t dir, uint8_t * buffer, uint16_t l NRF_USBD->EPIN[0].MAXCNT = 0; // Status Phase also require Easy DMA has to be free as well !!!! NRF_USBD->TASKS_EP0STATUS = 1; - osal_semaphore_post(_usbd_ctrl_sem, false); + + // The nRF doesn't interrupt on status transmit so we queue up a success response. + dcd_event_xfer_complete(0, 0, 0, DCD_XFER_SUCCESS, false); } return true; -- cgit v1.3.1 From 30e3c64134789416e10ed867fa12c210b808e98f Mon Sep 17 00:00:00 2001 From: Scott Shawcroft Date: Thu, 8 Nov 2018 13:45:30 -0800 Subject: Polish up control split and treat it more like a normal endpoint. --- src/class/cdc/cdc_device.c | 28 +++++-- src/class/cdc/cdc_device.h | 1 + src/class/custom/custom_device.c | 2 +- src/class/custom/custom_device.h | 1 + src/class/hid/hid_device.c | 32 +++++--- src/class/hid/hid_device.h | 1 + src/class/msc/msc_device.c | 5 ++ src/class/msc/msc_device.h | 1 + src/device/control.c | 14 +++- src/device/control.h | 3 + src/device/usbd.c | 16 ++++ src/portable/nordic/nrf5x/dcd_nrf5x.c | 136 ++++++++-------------------------- 12 files changed, 114 insertions(+), 126 deletions(-) (limited to 'src/class') diff --git a/src/class/cdc/cdc_device.c b/src/class/cdc/cdc_device.c index 81d7fa526..ab9addc93 100644 --- a/src/class/cdc/cdc_device.c +++ b/src/class/cdc/cdc_device.c @@ -288,6 +288,21 @@ tusb_error_t cdcd_open(uint8_t rhport, tusb_desc_interface_t const * p_interface return TUSB_ERROR_NONE; } +void cdcd_control_request_complete(uint8_t rhport, tusb_control_request_t const * p_request) +{ + //------------- Class Specific Request -------------// + if (p_request->bmRequestType_bit.type != TUSB_REQ_TYPE_CLASS) return; + + // TODO Support multiple interfaces + uint8_t const itf = 0; + cdcd_interface_t* p_cdc = &_cdcd_itf[itf]; + + // Invoke callback + if (CDC_REQUEST_SET_LINE_CODING == p_request->bRequest) { + if ( tud_cdc_line_coding_cb ) tud_cdc_line_coding_cb(itf, &p_cdc->line_coding); + } +} + tusb_error_t cdcd_control_request(uint8_t rhport, tusb_control_request_t const * p_request, uint16_t bytes_already_sent) { //------------- Class Specific Request -------------// @@ -297,16 +312,15 @@ tusb_error_t cdcd_control_request(uint8_t rhport, tusb_control_request_t const * uint8_t const itf = 0; cdcd_interface_t* p_cdc = &_cdcd_itf[itf]; - if ( (CDC_REQUEST_GET_LINE_CODING == p_request->bRequest) || (CDC_REQUEST_SET_LINE_CODING == p_request->bRequest) ) + if ((CDC_REQUEST_SET_LINE_CODING == p_request->bRequest) ) + { + uint16_t len = tu_min16(sizeof(cdc_line_coding_t), p_request->wLength); + dcd_edpt_xfer(rhport, 0, (uint8_t*) &p_cdc->line_coding, len); + } + else if ( (CDC_REQUEST_GET_LINE_CODING == p_request->bRequest)) { uint16_t len = tu_min16(sizeof(cdc_line_coding_t), p_request->wLength); dcd_edpt_xfer(rhport, TUSB_DIR_IN_MASK, (uint8_t*) &p_cdc->line_coding, len); - - // Invoke callback - if (CDC_REQUEST_SET_LINE_CODING == p_request->bRequest) - { - if ( tud_cdc_line_coding_cb ) tud_cdc_line_coding_cb(itf, &p_cdc->line_coding); - } } else if (CDC_REQUEST_SET_CONTROL_LINE_STATE == p_request->bRequest ) { diff --git a/src/class/cdc/cdc_device.h b/src/class/cdc/cdc_device.h index 88d37a83c..2f902ae04 100644 --- a/src/class/cdc/cdc_device.h +++ b/src/class/cdc/cdc_device.h @@ -113,6 +113,7 @@ ATTR_WEAK void tud_cdc_line_coding_cb(uint8_t itf, cdc_line_coding_t const* p_li void cdcd_init (void); tusb_error_t cdcd_open (uint8_t rhport, tusb_desc_interface_t const * p_interface_desc, uint16_t *p_length); tusb_error_t cdcd_control_request (uint8_t rhport, tusb_control_request_t const * p_request, uint16_t bytes_already_sent); +void cdcd_control_request_complete (uint8_t rhport, tusb_control_request_t const * p_request); tusb_error_t cdcd_xfer_cb (uint8_t rhport, uint8_t edpt_addr, tusb_event_t event, uint32_t xferred_bytes); void cdcd_reset (uint8_t rhport); diff --git a/src/class/custom/custom_device.c b/src/class/custom/custom_device.c index d43a86b14..1b36f1331 100644 --- a/src/class/custom/custom_device.c +++ b/src/class/custom/custom_device.c @@ -89,7 +89,7 @@ tusb_error_t cusd_open(uint8_t rhport, tusb_desc_interface_t const * p_desc_itf, return TUSB_ERROR_NONE; } -tusb_error_t cusd_control_request_st(uint8_t rhport, tusb_control_request_t const * p_request) +tusb_error_t cusd_control_request(uint8_t rhport, tusb_control_request_t const * p_request) { return TUSB_ERROR_DCD_CONTROL_REQUEST_NOT_SUPPORT; } diff --git a/src/class/custom/custom_device.h b/src/class/custom/custom_device.h index 81a074ce3..116c6897d 100644 --- a/src/class/custom/custom_device.h +++ b/src/class/custom/custom_device.h @@ -65,6 +65,7 @@ void cusd_init(void); tusb_error_t cusd_open(uint8_t rhport, tusb_desc_interface_t const * p_interface_desc, uint16_t *p_length); tusb_error_t cusd_control_request_st(uint8_t rhport, tusb_control_request_t const * p_request); +void cusd_control_request_complete (uint8_t rhport, tusb_control_request_t const * p_request); tusb_error_t cusd_xfer_cb(uint8_t rhport, uint8_t edpt_addr, tusb_event_t event, uint32_t xferred_bytes); void cusd_reset(uint8_t rhport); #endif diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index aa7a8008e..efa602ad6 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -455,15 +455,6 @@ tusb_error_t hidd_control_request(uint8_t rhport, tusb_control_request_t const * else if ( HID_REQ_CONTROL_SET_REPORT == p_request->bRequest ) { dcd_edpt_xfer(rhport, 0, _shared_control_buffer, p_request->wLength); - - // wValue = Report Type | Report ID - uint8_t const report_type = tu_u16_high(p_request->wValue); - uint8_t const report_id = tu_u16_low(p_request->wValue); - - if ( p_hid->set_report_cb ) - { - p_hid->set_report_cb(report_id, (hid_report_type_t) report_type, _shared_control_buffer, p_request->wLength); - } } else if (HID_REQ_CONTROL_SET_IDLE == p_request->bRequest) { @@ -495,6 +486,29 @@ tusb_error_t hidd_control_request(uint8_t rhport, tusb_control_request_t const * return TUSB_ERROR_NONE; } +void hidd_control_request_complete(uint8_t rhport, tusb_control_request_t const * p_request) +{ + hidd_interface_t* p_hid = get_interface_by_itfnum( (uint8_t) p_request->wIndex ); + if (p_hid == NULL) { + return; + } + + if (p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS) + { + if ( HID_REQ_CONTROL_SET_REPORT == p_request->bRequest ) + { + // wValue = Report Type | Report ID + uint8_t const report_type = tu_u16_high(p_request->wValue); + uint8_t const report_id = tu_u16_low(p_request->wValue); + + if ( p_hid->set_report_cb ) + { + p_hid->set_report_cb(report_id, (hid_report_type_t) report_type, _shared_control_buffer, p_request->wLength); + } + } + } +} + tusb_error_t hidd_xfer_cb(uint8_t rhport, uint8_t edpt_addr, tusb_event_t event, uint32_t xferred_bytes) { // nothing to do diff --git a/src/class/hid/hid_device.h b/src/class/hid/hid_device.h index 10aea10ac..1dc40af57 100644 --- a/src/class/hid/hid_device.h +++ b/src/class/hid/hid_device.h @@ -379,6 +379,7 @@ ATTR_WEAK void tud_hid_mouse_set_report_cb(uint8_t report_id, hid_report_type_t void hidd_init(void); tusb_error_t hidd_open(uint8_t rhport, tusb_desc_interface_t const * p_interface_desc, uint16_t *p_length); tusb_error_t hidd_control_request(uint8_t rhport, tusb_control_request_t const * p_request, uint16_t bytes_already_sent); +void hidd_control_request_complete (uint8_t rhport, tusb_control_request_t const * p_request); tusb_error_t hidd_xfer_cb(uint8_t rhport, uint8_t edpt_addr, tusb_event_t event, uint32_t xferred_bytes); void hidd_reset(uint8_t rhport); diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index 3c9997b95..32ad90102 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -167,6 +167,11 @@ tusb_error_t mscd_control_request(uint8_t rhport, tusb_control_request_t const * return TUSB_ERROR_NONE; } +void mscd_control_request_complete(uint8_t rhport, tusb_control_request_t const * p_request) +{ + return; +} + // For backwards compatibility we support static block counts. #if defined(CFG_TUD_MSC_BLOCK_NUM) && defined(CFG_TUD_MSC_BLOCK_SZ) ATTR_WEAK bool tud_lun_capacity_cb(uint8_t lun, uint32_t* last_valid_sector, uint16_t* block_size) { diff --git a/src/class/msc/msc_device.h b/src/class/msc/msc_device.h index a5bc54ff9..ac3eade22 100644 --- a/src/class/msc/msc_device.h +++ b/src/class/msc/msc_device.h @@ -199,6 +199,7 @@ ATTR_WEAK bool tud_lun_capacity_cb(uint8_t lun, uint32_t* last_valid_sector, uin void mscd_init(void); tusb_error_t mscd_open(uint8_t rhport, tusb_desc_interface_t const * p_interface_desc, uint16_t *p_length); tusb_error_t mscd_control_request(uint8_t rhport, tusb_control_request_t const * p_request, uint16_t bytes_already_sent); +void mscd_control_request_complete (uint8_t rhport, tusb_control_request_t const * p_request); tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t edpt_addr, tusb_event_t event, uint32_t xferred_bytes); void mscd_reset(uint8_t rhport); diff --git a/src/device/control.c b/src/device/control.c index 4944a999e..5856f0628 100644 --- a/src/device/control.c +++ b/src/device/control.c @@ -59,8 +59,13 @@ void controld_init(void) { // Note dir is value of direction bit in setup packet (i.e DATA stage direction) static inline bool dcd_control_status(uint8_t rhport, uint8_t dir) { + uint8_t ep_addr = 0; + // Invert the direction. + if (dir == TUSB_DIR_OUT) { + ep_addr |= TUSB_DIR_IN_MASK; + } // status direction is reversed to one in the setup packet - return dcd_edpt_xfer(rhport, 1-dir, NULL, 0); + return dcd_edpt_xfer(rhport, ep_addr, NULL, 0); } static inline void dcd_control_stall(uint8_t rhport) @@ -140,6 +145,12 @@ tusb_error_t controld_xfer_cb(uint8_t rhport, uint8_t edpt_addr, tusb_event_t ev if (p_request->wLength == control_state.total_transferred || xferred_bytes < 64) { control_state.current_stage = CONTROL_STAGE_STATUS; dcd_control_status(rhport, p_request->bmRequestType_bit.direction); + + // Do the user callback after queueing the STATUS packet because the callback could be slow. + if ( TUSB_REQ_RCPT_INTERFACE == p_request->bmRequestType_bit.recipient ) + { + tud_control_interface_control_complete_cb(rhport, tu_u16_low(p_request->wIndex), p_request); + } } else { if (TUSB_REQ_RCPT_INTERFACE == p_request->bmRequestType_bit.recipient) { error = tud_control_interface_control_cb(rhport, tu_u16_low(p_request->wIndex), p_request, control_state.total_transferred); @@ -161,7 +172,6 @@ tusb_error_t controld_process_setup_request(uint8_t rhport, tusb_control_request control_state.total_transferred = 0; } - if ( TUSB_REQ_RCPT_INTERFACE == p_request->bmRequestType_bit.recipient ) { error = tud_control_interface_control_cb(rhport, tu_u16_low(p_request->wIndex), p_request, 0); diff --git a/src/device/control.h b/src/device/control.h index 24f0d0a14..881c99ead 100644 --- a/src/device/control.h +++ b/src/device/control.h @@ -68,6 +68,9 @@ tusb_error_t controld_process_setup_request(uint8_t rhport, tusb_control_request // Callback when the configuration of the device is changed. tusb_error_t tud_control_set_config_cb(uint8_t rhport, uint8_t config_number); +// Called when the DATA stage of a control transaction is complete. +void tud_control_interface_control_complete_cb(uint8_t rhport, uint8_t interface, tusb_control_request_t const * const p_request); + tusb_error_t tud_control_interface_control_cb(uint8_t rhport, uint8_t interface, tusb_control_request_t const * const p_request, uint16_t bytes_already_sent); //--------------------------------------------------------------------+ diff --git a/src/device/usbd.c b/src/device/usbd.c index 3c77fefba..c9d5e5642 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -96,6 +96,7 @@ typedef struct { tusb_error_t (* open ) (uint8_t rhport, tusb_desc_interface_t const * desc_intf, uint16_t* p_length); // Control request is called one or more times for a request and can queue multiple data packets. tusb_error_t (* control_request ) (uint8_t rhport, tusb_control_request_t const *, uint16_t bytes_already_sent); + void (* control_request_complete ) (uint8_t rhport, tusb_control_request_t const *); tusb_error_t (* xfer_cb ) (uint8_t rhport, uint8_t ep_addr, tusb_event_t, uint32_t); void (* sof ) (uint8_t rhport); void (* reset ) (uint8_t); @@ -108,6 +109,7 @@ static usbd_class_driver_t const usbd_class_drivers[] = .init = controld_init, .open = NULL, .control_request = NULL, + .control_request_complete = NULL, .xfer_cb = controld_xfer_cb, .sof = NULL, .reset = controld_reset @@ -118,6 +120,7 @@ static usbd_class_driver_t const usbd_class_drivers[] = .init = cdcd_init, .open = cdcd_open, .control_request = cdcd_control_request, + .control_request_complete = cdcd_control_request_complete, .xfer_cb = cdcd_xfer_cb, .sof = NULL, .reset = cdcd_reset @@ -130,6 +133,7 @@ static usbd_class_driver_t const usbd_class_drivers[] = .init = mscd_init, .open = mscd_open, .control_request = mscd_control_request, + .control_request_complete = mscd_control_request_complete, .xfer_cb = mscd_xfer_cb, .sof = NULL, .reset = mscd_reset @@ -143,6 +147,7 @@ static usbd_class_driver_t const usbd_class_drivers[] = .init = hidd_init, .open = hidd_open, .control_request = hidd_control_request, + .control_request_complete = hidd_control_request_complete, .xfer_cb = hidd_xfer_cb, .sof = NULL, .reset = hidd_reset @@ -155,6 +160,7 @@ static usbd_class_driver_t const usbd_class_drivers[] = .init = cusd_init, .open = cusd_open, .control_request = cusd_control_request, + .control_request_complete = cusd_control_request_complete, .xfer_cb = cusd_xfer_cb, .sof = NULL, .reset = cusd_reset @@ -309,6 +315,16 @@ static tusb_error_t usbd_main_st(void) return err; } +void tud_control_interface_control_complete_cb(uint8_t rhport, uint8_t interface, tusb_control_request_t const * const p_request) { + if (_usbd_dev.itf2drv[ interface ] < USBD_CLASS_DRIVER_COUNT) + { + const usbd_class_driver_t *driver = &usbd_class_drivers[_usbd_dev.itf2drv[interface]]; + if (driver->control_request_complete != NULL) { + driver->control_request_complete(rhport, p_request); + } + } +} + tusb_error_t tud_control_interface_control_cb(uint8_t rhport, uint8_t interface, tusb_control_request_t const * const p_request, uint16_t bytes_already_sent) { if (_usbd_dev.itf2drv[ interface ] < USBD_CLASS_DRIVER_COUNT) { diff --git a/src/portable/nordic/nrf5x/dcd_nrf5x.c b/src/portable/nordic/nrf5x/dcd_nrf5x.c index 1e3dc4cba..74b7bb7b8 100644 --- a/src/portable/nordic/nrf5x/dcd_nrf5x.c +++ b/src/portable/nordic/nrf5x/dcd_nrf5x.c @@ -82,17 +82,8 @@ typedef struct /*static*/ struct { - struct - { - uint8_t* buffer; - uint16_t total_len; - volatile uint16_t actual_len; - - uint8_t dir; - }control; - - // Non control: 7 endpoints IN & OUT (offset 1) - nom_xfer_t xfer[7][2]; + // All 8 endpoints including control IN & OUT (offset 1) + nom_xfer_t xfer[8][2]; volatile bool dma_running; }_dcd; @@ -109,6 +100,8 @@ void bus_reset(void) NRF_USBD->TASKS_STARTISOOUT = 0; tu_varclr(&_dcd); + _dcd.xfer[0][TUSB_DIR_IN].mps = MAX_PACKET_SIZE; + _dcd.xfer[0][TUSB_DIR_OUT].mps = MAX_PACKET_SIZE; } /*------------------------------------------------------------------*/ @@ -176,65 +169,13 @@ static void edpt_dma_end(void) _dcd.dma_running = false; } -static void xact_control_start(void) -{ - // Each transaction is up to 64 bytes - uint8_t const xact_len = tu_min16(_dcd.control.total_len-_dcd.control.actual_len, MAX_PACKET_SIZE); - - if ( _dcd.control.dir == TUSB_DIR_OUT ) - { - // TODO control out - NRF_USBD->EPOUT[0].PTR = (uint32_t) _dcd.control.buffer; - NRF_USBD->EPOUT[0].MAXCNT = xact_len; - - NRF_USBD->TASKS_EP0RCVOUT = 1; - __ISB(); __DSB(); - }else - { - NRF_USBD->EPIN[0].PTR = (uint32_t) _dcd.control.buffer; - NRF_USBD->EPIN[0].MAXCNT = xact_len; - - edpt_dma_start(&NRF_USBD->TASKS_STARTEPIN[0]); - } - - _dcd.control.buffer += xact_len; - _dcd.control.actual_len += xact_len; -} - -bool dcd_control_xfer (uint8_t rhport, uint8_t dir, uint8_t * buffer, uint16_t length) -{ - (void) rhport; - - if ( length ) - { - // Data Phase - _dcd.control.total_len = length; - _dcd.control.actual_len = 0; - _dcd.control.buffer = buffer; - _dcd.control.dir = dir; - - xact_control_start(); - }else - { - NRF_USBD->EPIN[0].PTR = 0; - NRF_USBD->EPIN[0].MAXCNT = 0; - // Status Phase also require Easy DMA has to be free as well !!!! - NRF_USBD->TASKS_EP0STATUS = 1; - - // The nRF doesn't interrupt on status transmit so we queue up a success response. - dcd_event_xfer_complete(0, 0, 0, DCD_XFER_SUCCESS, false); - } - - return true; -} - /*------------------------------------------------------------------*/ /* *------------------------------------------------------------------*/ static inline nom_xfer_t* get_td(uint8_t epnum, uint8_t dir) { - return &_dcd.xfer[epnum-1][dir]; + return &_dcd.xfer[epnum][dir]; } /*------------- Bulk/Int OUT transfer -------------*/ @@ -296,7 +237,7 @@ bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * desc_edpt) uint8_t const epnum = edpt_number(desc_edpt->bEndpointAddress); uint8_t const dir = edpt_dir(desc_edpt->bEndpointAddress); - _dcd.xfer[epnum-1][dir].mps = desc_edpt->wMaxPacketSize.size; + _dcd.xfer[epnum][dir].mps = desc_edpt->wMaxPacketSize.size; if ( dir == TUSB_DIR_OUT ) { @@ -312,6 +253,16 @@ bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * desc_edpt) return true; } +void control_status_token(uint8_t addr) { + NRF_USBD->EPIN[0].PTR = 0; + NRF_USBD->EPIN[0].MAXCNT = 0; + // Status Phase also require Easy DMA has to be free as well !!!! + NRF_USBD->TASKS_EP0STATUS = 1; + + // The nRF doesn't interrupt on status transmit so we queue up a success response. + dcd_event_xfer_complete(0, addr, 0, DCD_XFER_SUCCESS, false); +} + bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes) { (void) rhport; @@ -325,7 +276,10 @@ bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t xfer->total_len = total_bytes; xfer->actual_len = 0; - if ( dir == TUSB_DIR_OUT ) + // How does the control endpoint handle a ZLP in the data phase? + if (epnum == 0 && total_bytes == 0) { + control_status_token(ep_addr); + } else if ( dir == TUSB_DIR_OUT ) { if ( xfer->data_received ) { @@ -431,47 +385,15 @@ void USBD_IRQHandler(void) edpt_dma_end(); } - /*------------- Control Transfer -------------*/ + // Setup tokens are specific to the Control endpoint. if ( int_status & USBD_INTEN_EP0SETUP_Msk ) { uint8_t setup[8] = { NRF_USBD->BMREQUESTTYPE , NRF_USBD->BREQUEST, NRF_USBD->WVALUEL , NRF_USBD->WVALUEH, NRF_USBD->WINDEXL , NRF_USBD->WINDEXH , NRF_USBD->WLENGTHL, NRF_USBD->WLENGTHH }; - dcd_event_setup_received(0, setup, true); - } - - if ( int_status & USBD_INTEN_EP0DATADONE_Msk ) - { - if ( _dcd.control.dir == TUSB_DIR_OUT ) - { - // Control OUT: data from Host -> Endpoint - // Trigger DMA to move Endpoint -> SRAM - edpt_dma_start(&NRF_USBD->TASKS_STARTEPOUT[0]); - }else - { - // Control IN: data transferred from Endpoint -> Host - if ( _dcd.control.actual_len < _dcd.control.total_len ) - { - xact_control_start(); - }else - { - // Control IN complete - dcd_event_xfer_complete(0, 0, _dcd.control.actual_len, DCD_XFER_SUCCESS, true); - } - } - } - - // Control OUT: data from Endpoint -> SRAM - if ( int_status & USBD_INTEN_ENDEPOUT0_Msk) - { - if ( _dcd.control.actual_len < _dcd.control.total_len ) - { - xact_control_start(); - }else - { - // Control OUT complete - dcd_event_xfer_complete(0, 0, _dcd.control.actual_len, DCD_XFER_SUCCESS, true); + if (setup[1] != TUSB_REQ_SET_ADDRESS) { + dcd_event_setup_received(0, setup, true); } } @@ -482,9 +404,9 @@ void USBD_IRQHandler(void) * We must handle this stage before Host -> Endpoint just in case * 2 event happens at once */ - for(uint8_t epnum=1; epnum<8; epnum++) + for(uint8_t epnum=0; epnum<8; epnum++) { - if ( BIT_TEST_(int_status, USBD_INTEN_ENDEPOUT0_Pos+epnum) ) + if ( BIT_TEST_(int_status, USBD_INTEN_ENDEPOUT0_Pos+epnum)) { nom_xfer_t* xfer = get_td(epnum, TUSB_DIR_OUT); @@ -509,16 +431,16 @@ void USBD_IRQHandler(void) // Ended event for Bulk/Int : nothing to do } - if ( int_status & USBD_INTEN_EPDATA_Msk) + if ( int_status & USBD_INTEN_EPDATA_Msk || int_status & USBD_INTEN_EP0DATADONE_Msk) { uint32_t data_status = NRF_USBD->EPDATASTATUS; nrf_usbd_epdatastatus_clear(data_status); // Bulk/Int In: data from Endpoint -> Host - for(uint8_t epnum=1; epnum<8; epnum++) + for(uint8_t epnum=0; epnum<8; epnum++) { - if ( BIT_TEST_(data_status, epnum ) ) + if ( BIT_TEST_(data_status, epnum ) || (epnum == 0 && BIT_TEST_(int_status, USBD_INTEN_EP0DATADONE_Pos))) { nom_xfer_t* xfer = get_td(epnum, TUSB_DIR_IN); @@ -537,7 +459,7 @@ void USBD_IRQHandler(void) } // Bulk/Int OUT: data from Host -> Endpoint - for(uint8_t epnum=1; epnum<8; epnum++) + for(uint8_t epnum=0; epnum<8; epnum++) { if ( BIT_TEST_(data_status, 16+epnum ) ) { -- cgit v1.3.1 From 537a29273c08b1e047004e1bd71c37af82937dd4 Mon Sep 17 00:00:00 2001 From: Scott Shawcroft Date: Fri, 9 Nov 2018 00:10:44 -0800 Subject: Exempt from strict warnings for struct packing and add MCU options --- src/class/cdc/cdc.h | 6 ++++++ src/class/hid/hid.h | 5 +++++ src/class/msc/msc.h | 6 ++++++ src/common/tusb_types.h | 6 ++++++ src/portable/microchip/samd21/dcd.c | 2 +- src/tusb_option.h | 3 +++ 6 files changed, 27 insertions(+), 1 deletion(-) (limited to 'src/class') diff --git a/src/class/cdc/cdc.h b/src/class/cdc/cdc.h index 1b127ad28..0b6e57735 100644 --- a/src/class/cdc/cdc.h +++ b/src/class/cdc/cdc.h @@ -50,6 +50,10 @@ extern "C" { #endif +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wpacked" +#pragma GCC diagnostic ignored "-Wattributes" + /** \defgroup ClassDriver_CDC_Common Common Definitions * @{ */ @@ -401,6 +405,8 @@ typedef struct ATTR_PACKED TU_VERIFY_STATIC(sizeof(cdc_line_control_state_t) == 2, "size is not correct"); +#pragma GCC diagnostic pop + /** @} */ #ifdef __cplusplus diff --git a/src/class/hid/hid.h b/src/class/hid/hid.h index d2803177b..0008e47fb 100644 --- a/src/class/hid/hid.h +++ b/src/class/hid/hid.h @@ -49,6 +49,10 @@ extern "C" { #endif +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wpacked" +#pragma GCC diagnostic ignored "-Wattributes" + //--------------------------------------------------------------------+ // Common Definitions //--------------------------------------------------------------------+ @@ -609,6 +613,7 @@ enum HID_USAGE_CONSUMER_AC_PAN = 0x0238, }; +#pragma GCC diagnostic pop #ifdef __cplusplus } diff --git a/src/class/msc/msc.h b/src/class/msc/msc.h index a0abc2501..e7c32b303 100644 --- a/src/class/msc/msc.h +++ b/src/class/msc/msc.h @@ -52,6 +52,10 @@ extern "C" { #endif +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wpacked" +#pragma GCC diagnostic ignored "-Wattributes" + //--------------------------------------------------------------------+ // Mass Storage Class Constant //--------------------------------------------------------------------+ @@ -392,6 +396,8 @@ typedef struct ATTR_PACKED TU_VERIFY_STATIC(sizeof(scsi_read10_t) == 10, "size is not correct"); TU_VERIFY_STATIC(sizeof(scsi_write10_t) == 10, "size is not correct"); +#pragma GCC diagnostic pop + #ifdef __cplusplus } #endif diff --git a/src/common/tusb_types.h b/src/common/tusb_types.h index 8ce334e55..5c226f556 100644 --- a/src/common/tusb_types.h +++ b/src/common/tusb_types.h @@ -51,6 +51,10 @@ extern "C" { #endif +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wpacked" +#pragma GCC diagnostic ignored "-Wattributes" + /*------------------------------------------------------------------*/ /* CONSTANTS *------------------------------------------------------------------*/ @@ -422,6 +426,8 @@ static inline uint8_t descriptor_len(uint8_t const p_desc[]) // Convert comma-separated string to descriptor unicode format #define TUD_DESC_STRCONV( ... ) (const uint16_t[]) { TUD_DESC_STR_HEADER(VA_ARGS_NUM_(__VA_ARGS__)), __VA_ARGS__ } +#pragma GCC diagnostic pop + #ifdef __cplusplus } #endif diff --git a/src/portable/microchip/samd21/dcd.c b/src/portable/microchip/samd21/dcd.c index c9e88ad17..33cbc8d92 100644 --- a/src/portable/microchip/samd21/dcd.c +++ b/src/portable/microchip/samd21/dcd.c @@ -38,7 +38,7 @@ #include "tusb_option.h" -#if TUSB_OPT_DEVICE_ENABLED && CFG_TUSB_MCU == OPT_MCU_SAMD51 +#if TUSB_OPT_DEVICE_ENABLED && CFG_TUSB_MCU == OPT_MCU_SAMD21 #include "device/dcd.h" diff --git a/src/tusb_option.h b/src/tusb_option.h index d7a6c6fe0..d027ea0e6 100644 --- a/src/tusb_option.h +++ b/src/tusb_option.h @@ -57,6 +57,9 @@ #define OPT_MCU_LPC43XX 7 ///< NXP LPC43xx series #define OPT_MCU_NRF5X 100 ///< Nordic nRF5x series + +#define OPT_MCU_SAMD21 200 ///< MicroChip SAMD21 +#define OPT_MCU_SAMD51 201 ///< MicroChip SAMD51 /** @} */ /** \defgroup group_supported_os Supported RTOS -- cgit v1.3.1 From 299a2f12de2ddb76b9a488b23e7e562058faee90 Mon Sep 17 00:00:00 2001 From: Scott Shawcroft Date: Fri, 9 Nov 2018 11:30:51 -0800 Subject: Support the no CDC protocol as well. --- src/class/cdc/cdc.h | 3 ++- src/class/cdc/cdc_device.c | 4 +++- 2 files changed, 5 insertions(+), 2 deletions(-) (limited to 'src/class') diff --git a/src/class/cdc/cdc.h b/src/class/cdc/cdc.h index 0b6e57735..afac8379d 100644 --- a/src/class/cdc/cdc.h +++ b/src/class/cdc/cdc.h @@ -90,7 +90,8 @@ typedef enum /// Communication Interface Protocol Codes typedef enum { - CDC_COMM_PROTOCOL_ATCOMMAND = 0x01 , ///< AT Commands: V.250 etc + CDC_COMM_PROTOCOL_NONE = 0x00 , ///< No specific protocol + CDC_COMM_PROTOCOL_ATCOMMAND , ///< AT Commands: V.250 etc CDC_COMM_PROTOCOL_ATCOMMAND_PCCA_101 , ///< AT Commands defined by PCCA-101 CDC_COMM_PROTOCOL_ATCOMMAND_PCCA_101_AND_ANNEXO , ///< AT Commands defined by PCCA-101 & Annex O CDC_COMM_PROTOCOL_ATCOMMAND_GSM_707 , ///< AT Commands defined by GSM 07.07 diff --git a/src/class/cdc/cdc_device.c b/src/class/cdc/cdc_device.c index ab9addc93..49e13c4b7 100644 --- a/src/class/cdc/cdc_device.c +++ b/src/class/cdc/cdc_device.c @@ -227,8 +227,10 @@ tusb_error_t cdcd_open(uint8_t rhport, tusb_desc_interface_t const * p_interface { if ( CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL != p_interface_desc->bInterfaceSubClass) return TUSB_ERROR_CDC_UNSUPPORTED_SUBCLASS; + // Only support AT commands, no protocol and vendor specific commands. if ( !(tu_within(CDC_COMM_PROTOCOL_ATCOMMAND, p_interface_desc->bInterfaceProtocol, CDC_COMM_PROTOCOL_ATCOMMAND_CDMA) || - 0xff == p_interface_desc->bInterfaceProtocol) ) + p_interface_desc->bInterfaceProtocol == CDC_COMM_PROTOCOL_NONE || + p_interface_desc->bInterfaceProtocol == 0xff ) ) { return TUSB_ERROR_CDC_UNSUPPORTED_PROTOCOL; } -- cgit v1.3.1 From 3fe7cd165902948240ecc40468b3610686f579c3 Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 13 Nov 2018 15:34:50 +0700 Subject: added tud_cdc_write_str, tu_fifo only use mutex for RTOS config --- examples/device/nrf52840/segger/SEGGER_RTT.c | 1329 -------------------- examples/device/nrf52840/segger/SEGGER_RTT.h | 234 ---- examples/device/nrf52840/segger/SEGGER_RTT_Conf.h | 242 ---- examples/device/nrf52840/segger/SEGGER_RTT_SES.c | 76 -- examples/device/nrf52840/segger/nrf52840.emProject | 12 +- examples/device/nrf52840/src/main.c | 83 +- .../device/nrf52840/src/segger_rtt/SEGGER_RTT.c | 1329 ++++++++++++++++++++ .../device/nrf52840/src/segger_rtt/SEGGER_RTT.h | 234 ++++ .../nrf52840/src/segger_rtt/SEGGER_RTT_Conf.h | 242 ++++ .../nrf52840/src/segger_rtt/SEGGER_RTT_SES.c | 76 ++ .../device/nrf52840_freertos/segger/SEGGER_RTT.c | 1329 -------------------- .../device/nrf52840_freertos/segger/SEGGER_RTT.h | 234 ---- .../nrf52840_freertos/segger/SEGGER_RTT_Conf.h | 242 ---- .../nrf52840_freertos/segger/SEGGER_RTT_SES.c | 76 -- .../segger/nrf5x_freertos.emProject | 12 +- examples/device/nrf52840_freertos/src/main.c | 26 +- .../nrf52840_freertos/src/segger_rtt/SEGGER_RTT.c | 1329 ++++++++++++++++++++ .../nrf52840_freertos/src/segger_rtt/SEGGER_RTT.h | 234 ++++ .../src/segger_rtt/SEGGER_RTT_Conf.h | 242 ++++ .../src/segger_rtt/SEGGER_RTT_SES.c | 76 ++ .../device/nrf52840_freertos/src/tusb_config.h | 2 +- hw/bsp/pca10056/board_pca10056.c | 5 + src/class/cdc/cdc_device.c | 13 +- src/class/cdc/cdc_device.h | 2 + src/common/tusb_fifo.c | 21 +- src/common/tusb_fifo.h | 4 +- src/osal/osal_none.h | 13 - 27 files changed, 3872 insertions(+), 3845 deletions(-) delete mode 100644 examples/device/nrf52840/segger/SEGGER_RTT.c delete mode 100644 examples/device/nrf52840/segger/SEGGER_RTT.h delete mode 100644 examples/device/nrf52840/segger/SEGGER_RTT_Conf.h delete mode 100644 examples/device/nrf52840/segger/SEGGER_RTT_SES.c create mode 100644 examples/device/nrf52840/src/segger_rtt/SEGGER_RTT.c create mode 100644 examples/device/nrf52840/src/segger_rtt/SEGGER_RTT.h create mode 100644 examples/device/nrf52840/src/segger_rtt/SEGGER_RTT_Conf.h create mode 100644 examples/device/nrf52840/src/segger_rtt/SEGGER_RTT_SES.c delete mode 100644 examples/device/nrf52840_freertos/segger/SEGGER_RTT.c delete mode 100644 examples/device/nrf52840_freertos/segger/SEGGER_RTT.h delete mode 100644 examples/device/nrf52840_freertos/segger/SEGGER_RTT_Conf.h delete mode 100644 examples/device/nrf52840_freertos/segger/SEGGER_RTT_SES.c create mode 100644 examples/device/nrf52840_freertos/src/segger_rtt/SEGGER_RTT.c create mode 100644 examples/device/nrf52840_freertos/src/segger_rtt/SEGGER_RTT.h create mode 100644 examples/device/nrf52840_freertos/src/segger_rtt/SEGGER_RTT_Conf.h create mode 100644 examples/device/nrf52840_freertos/src/segger_rtt/SEGGER_RTT_SES.c (limited to 'src/class') diff --git a/examples/device/nrf52840/segger/SEGGER_RTT.c b/examples/device/nrf52840/segger/SEGGER_RTT.c deleted file mode 100644 index aee5bd21e..000000000 --- a/examples/device/nrf52840/segger/SEGGER_RTT.c +++ /dev/null @@ -1,1329 +0,0 @@ -/********************************************************************* -* SEGGER MICROCONTROLLER GmbH & Co. KG * -* Solutions for real time microcontroller applications * -********************************************************************** -* * -* (c) 2014 - 2016 SEGGER Microcontroller GmbH & Co. KG * -* * -* www.segger.com Support: support@segger.com * -* * -********************************************************************** -* * -* SEGGER RTT * Real Time Transfer for embedded targets * -* * -********************************************************************** -* * -* All rights reserved. * -* * -* * This software may in its unmodified form be freely redistributed * -* in source form. * -* * The source code may be modified, provided the source code * -* retains the above copyright notice, this list of conditions and * -* the following disclaimer. * -* * Modified versions of this software in source or linkable form * -* may not be distributed without prior consent of SEGGER. * -* * This software may only be used for communication with SEGGER * -* J-Link debug probes. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * -* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * -* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * -* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * -* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * -* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * -* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * -* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * -* DAMAGE. * -* * -********************************************************************** -* * -* RTT version: 5.12e * -* * -********************************************************************** ----------------------------END-OF-HEADER------------------------------ -File : SEGGER_RTT.c -Purpose : Implementation of SEGGER real-time transfer (RTT) which - allows real-time communication on targets which support - debugger memory accesses while the CPU is running. - -Additional information: - Type "int" is assumed to be 32-bits in size - H->T Host to target communication - T->H Target to host communication - - RTT channel 0 is always present and reserved for Terminal usage. - Name is fixed to "Terminal" - - Effective buffer size: SizeOfBuffer - 1 - - WrOff == RdOff: Buffer is empty - WrOff == (RdOff - 1): Buffer is full - WrOff > RdOff: Free space includes wrap-around - WrOff < RdOff: Used space includes wrap-around - (WrOff == (SizeOfBuffer - 1)) && (RdOff == 0): - Buffer full and wrap-around after next byte - - ----------------------------------------------------------------------- -*/ - -#include "SEGGER_RTT.h" - -#include // for memcpy - -/********************************************************************* -* -* Configuration, default values -* -********************************************************************** -*/ - -#ifndef BUFFER_SIZE_UP - #define BUFFER_SIZE_UP 1024 // Size of the buffer for terminal output of target, up to host -#endif - -#ifndef BUFFER_SIZE_DOWN - #define BUFFER_SIZE_DOWN 16 // Size of the buffer for terminal input to target from host (Usually keyboard input) -#endif - -#ifndef SEGGER_RTT_MAX_NUM_UP_BUFFERS - #define SEGGER_RTT_MAX_NUM_UP_BUFFERS 2 // Number of up-buffers (T->H) available on this target -#endif - -#ifndef SEGGER_RTT_MAX_NUM_DOWN_BUFFERS - #define SEGGER_RTT_MAX_NUM_DOWN_BUFFERS 2 // Number of down-buffers (H->T) available on this target -#endif - -#ifndef SEGGER_RTT_BUFFER_SECTION - #if defined SEGGER_RTT_SECTION - #define SEGGER_RTT_BUFFER_SECTION SEGGER_RTT_SECTION - #endif -#endif - -#ifndef SEGGER_RTT_MODE_DEFAULT - #define SEGGER_RTT_MODE_DEFAULT SEGGER_RTT_MODE_NO_BLOCK_SKIP -#endif - -#ifndef SEGGER_RTT_LOCK - #define SEGGER_RTT_LOCK() -#endif - -#ifndef SEGGER_RTT_UNLOCK - #define SEGGER_RTT_UNLOCK() -#endif - -#ifndef STRLEN - #define STRLEN(a) strlen((a)) -#endif - -#ifndef MEMCPY - #define MEMCPY(pDest, pSrc, NumBytes) memcpy((pDest), (pSrc), (NumBytes)) -#endif - -#ifndef MIN - #define MIN(a, b) (((a) < (b)) ? (a) : (b)) -#endif - -#ifndef MAX - #define MAX(a, b) (((a) > (b)) ? (a) : (b)) -#endif -// -// For some environments, NULL may not be defined until certain headers are included -// -#ifndef NULL - #define NULL 0 -#endif - -/********************************************************************* -* -* Static const data -* -********************************************************************** -*/ - -static unsigned char _aTerminalId[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; - -/********************************************************************* -* -* Static data -* -********************************************************************** -*/ -// -// RTT Control Block and allocate buffers for channel 0 -// -#ifdef SEGGER_RTT_SECTION - #if (defined __GNUC__) - __attribute__ ((section (SEGGER_RTT_SECTION))) SEGGER_RTT_CB _SEGGER_RTT; - #elif (defined __ICCARM__) || (defined __ICCRX__) - #pragma location=SEGGER_RTT_SECTION - SEGGER_RTT_CB _SEGGER_RTT; - #elif (defined __CC_ARM__) - __attribute__ ((section (SEGGER_RTT_SECTION), zero_init)) SEGGER_RTT_CB _SEGGER_RTT; - #else - SEGGER_RTT_CB _SEGGER_RTT; - #endif -#else - SEGGER_RTT_CB _SEGGER_RTT; -#endif - -#ifdef SEGGER_RTT_BUFFER_SECTION - #if (defined __GNUC__) - __attribute__ ((section (SEGGER_RTT_BUFFER_SECTION))) static char _acUpBuffer [BUFFER_SIZE_UP]; - __attribute__ ((section (SEGGER_RTT_BUFFER_SECTION))) static char _acDownBuffer[BUFFER_SIZE_DOWN]; - #elif (defined __ICCARM__) || (defined __ICCRX__) - #pragma location=SEGGER_RTT_BUFFER_SECTION - static char _acUpBuffer [BUFFER_SIZE_UP]; - #pragma location=SEGGER_RTT_BUFFER_SECTION - static char _acDownBuffer[BUFFER_SIZE_DOWN]; - #elif (defined __CC_ARM__) - __attribute__ ((section (SEGGER_RTT_BUFFER_SECTION), zero_init)) static char _acUpBuffer [BUFFER_SIZE_UP]; - __attribute__ ((section (SEGGER_RTT_BUFFER_SECTION), zero_init)) static char _acDownBuffer[BUFFER_SIZE_DOWN]; - #else - static char _acUpBuffer [BUFFER_SIZE_UP]; - static char _acDownBuffer[BUFFER_SIZE_DOWN]; - #endif -#else - static char _acUpBuffer [BUFFER_SIZE_UP]; - static char _acDownBuffer[BUFFER_SIZE_DOWN]; -#endif - -static char _ActiveTerminal; - -/********************************************************************* -* -* Static functions -* -********************************************************************** -*/ - -/********************************************************************* -* -* _DoInit() -* -* Function description -* Initializes the control block an buffers. -* May only be called via INIT() to avoid overriding settings. -* -*/ -#define INIT() do { \ - if (_SEGGER_RTT.acID[0] == '\0') { _DoInit(); } \ - } while (0) -static void _DoInit(void) { - SEGGER_RTT_CB* p; - // - // Initialize control block - // - p = &_SEGGER_RTT; - p->MaxNumUpBuffers = SEGGER_RTT_MAX_NUM_UP_BUFFERS; - p->MaxNumDownBuffers = SEGGER_RTT_MAX_NUM_DOWN_BUFFERS; - // - // Initialize up buffer 0 - // - p->aUp[0].sName = "Terminal"; - p->aUp[0].pBuffer = _acUpBuffer; - p->aUp[0].SizeOfBuffer = sizeof(_acUpBuffer); - p->aUp[0].RdOff = 0u; - p->aUp[0].WrOff = 0u; - p->aUp[0].Flags = SEGGER_RTT_MODE_DEFAULT; - // - // Initialize down buffer 0 - // - p->aDown[0].sName = "Terminal"; - p->aDown[0].pBuffer = _acDownBuffer; - p->aDown[0].SizeOfBuffer = sizeof(_acDownBuffer); - p->aDown[0].RdOff = 0u; - p->aDown[0].WrOff = 0u; - p->aDown[0].Flags = SEGGER_RTT_MODE_DEFAULT; - // - // Finish initialization of the control block. - // Copy Id string in three steps to make sure "SEGGER RTT" is not found - // in initializer memory (usually flash) by J-Link - // - strcpy(&p->acID[7], "RTT"); - strcpy(&p->acID[0], "SEGGER"); - p->acID[6] = ' '; -} - -/********************************************************************* -* -* _WriteBlocking() -* -* Function description -* Stores a specified number of characters in SEGGER RTT ring buffer -* and updates the associated write pointer which is periodically -* read by the host. -* The caller is responsible for managing the write chunk sizes as -* _WriteBlocking() will block until all data has been posted successfully. -* -* Parameters -* pRing Ring buffer to post to. -* pBuffer Pointer to character array. Does not need to point to a \0 terminated string. -* NumBytes Number of bytes to be stored in the SEGGER RTT control block. -* -* Return value -* >= 0 - Number of bytes written into buffer. -*/ -static unsigned _WriteBlocking(SEGGER_RTT_BUFFER_UP* pRing, const char* pBuffer, unsigned NumBytes) { - unsigned NumBytesToWrite; - unsigned NumBytesWritten; - unsigned RdOff; - unsigned WrOff; - // - // Write data to buffer and handle wrap-around if necessary - // - NumBytesWritten = 0u; - WrOff = pRing->WrOff; - do { - RdOff = pRing->RdOff; // May be changed by host (debug probe) in the meantime - if (RdOff > WrOff) { - NumBytesToWrite = RdOff - WrOff - 1u; - } else { - NumBytesToWrite = pRing->SizeOfBuffer - (WrOff - RdOff + 1u); - } - NumBytesToWrite = MIN(NumBytesToWrite, (pRing->SizeOfBuffer - WrOff)); // Number of bytes that can be written until buffer wrap-around - NumBytesToWrite = MIN(NumBytesToWrite, NumBytes); - memcpy(pRing->pBuffer + WrOff, pBuffer, NumBytesToWrite); - NumBytesWritten += NumBytesToWrite; - pBuffer += NumBytesToWrite; - NumBytes -= NumBytesToWrite; - WrOff += NumBytesToWrite; - if (WrOff == pRing->SizeOfBuffer) { - WrOff = 0u; - } - pRing->WrOff = WrOff; - } while (NumBytes); - // - return NumBytesWritten; -} - -/********************************************************************* -* -* _WriteNoCheck() -* -* Function description -* Stores a specified number of characters in SEGGER RTT ring buffer -* and updates the associated write pointer which is periodically -* read by the host. -* It is callers responsibility to make sure data actually fits in buffer. -* -* Parameters -* pRing Ring buffer to post to. -* pBuffer Pointer to character array. Does not need to point to a \0 terminated string. -* NumBytes Number of bytes to be stored in the SEGGER RTT control block. -* -* Notes -* (1) If there might not be enough space in the "Up"-buffer, call _WriteBlocking -*/ -static void _WriteNoCheck(SEGGER_RTT_BUFFER_UP* pRing, const char* pData, unsigned NumBytes) { - unsigned NumBytesAtOnce; - unsigned WrOff; - unsigned Rem; - - WrOff = pRing->WrOff; - Rem = pRing->SizeOfBuffer - WrOff; - if (Rem > NumBytes) { - // - // All data fits before wrap around - // - memcpy(pRing->pBuffer + WrOff, pData, NumBytes); - pRing->WrOff = WrOff + NumBytes; - } else { - // - // We reach the end of the buffer, so need to wrap around - // - NumBytesAtOnce = Rem; - memcpy(pRing->pBuffer + WrOff, pData, NumBytesAtOnce); - NumBytesAtOnce = NumBytes - Rem; - memcpy(pRing->pBuffer, pData + Rem, NumBytesAtOnce); - pRing->WrOff = NumBytesAtOnce; - } -} - -/********************************************************************* -* -* _PostTerminalSwitch() -* -* Function description -* Switch terminal to the given terminal ID. It is the caller's -* responsibility to ensure the terminal ID is correct and there is -* enough space in the buffer for this to complete successfully. -* -* Parameters -* pRing Ring buffer to post to. -* TerminalId Terminal ID to switch to. -*/ -static void _PostTerminalSwitch(SEGGER_RTT_BUFFER_UP* pRing, unsigned char TerminalId) { - char ac[2]; - - ac[0] = 0xFFu; - ac[1] = _aTerminalId[TerminalId]; // Caller made already sure that TerminalId does not exceed our terminal limit - _WriteBlocking(pRing, ac, 2u); -} - -/********************************************************************* -* -* _GetAvailWriteSpace() -* -* Function description -* Returns the number of bytes that can be written to the ring -* buffer without blocking. -* -* Parameters -* pRing Ring buffer to check. -* -* Return value -* Number of bytes that are free in the buffer. -*/ -static unsigned _GetAvailWriteSpace(SEGGER_RTT_BUFFER_UP* pRing) { - unsigned RdOff; - unsigned WrOff; - unsigned r; - // - // Avoid warnings regarding volatile access order. It's not a problem - // in this case, but dampen compiler enthusiasm. - // - RdOff = pRing->RdOff; - WrOff = pRing->WrOff; - if (RdOff <= WrOff) { - r = pRing->SizeOfBuffer - 1u - WrOff + RdOff; - } else { - r = RdOff - WrOff - 1u; - } - return r; -} - -/********************************************************************* -* -* Public code -* -********************************************************************** -*/ -/********************************************************************* -* -* SEGGER_RTT_ReadNoLock() -* -* Function description -* Reads characters from SEGGER real-time-terminal control block -* which have been previously stored by the host. -* Do not lock against interrupts and multiple access. -* -* Parameters -* BufferIndex Index of Down-buffer to be used (e.g. 0 for "Terminal"). -* pBuffer Pointer to buffer provided by target application, to copy characters from RTT-down-buffer to. -* BufferSize Size of the target application buffer. -* -* Return value -* Number of bytes that have been read. -*/ -unsigned SEGGER_RTT_ReadNoLock(unsigned BufferIndex, void* pData, unsigned BufferSize) { - unsigned NumBytesRem; - unsigned NumBytesRead; - unsigned RdOff; - unsigned WrOff; - unsigned char* pBuffer; - SEGGER_RTT_BUFFER_DOWN* pRing; - // - INIT(); - pRing = &_SEGGER_RTT.aDown[BufferIndex]; - pBuffer = (unsigned char*)pData; - RdOff = pRing->RdOff; - WrOff = pRing->WrOff; - NumBytesRead = 0u; - // - // Read from current read position to wrap-around of buffer, first - // - if (RdOff > WrOff) { - NumBytesRem = pRing->SizeOfBuffer - RdOff; - NumBytesRem = MIN(NumBytesRem, BufferSize); - memcpy(pBuffer, pRing->pBuffer + RdOff, NumBytesRem); - NumBytesRead += NumBytesRem; - pBuffer += NumBytesRem; - BufferSize -= NumBytesRem; - RdOff += NumBytesRem; - // - // Handle wrap-around of buffer - // - if (RdOff == pRing->SizeOfBuffer) { - RdOff = 0u; - } - } - // - // Read remaining items of buffer - // - NumBytesRem = WrOff - RdOff; - NumBytesRem = MIN(NumBytesRem, BufferSize); - if (NumBytesRem > 0u) { - memcpy(pBuffer, pRing->pBuffer + RdOff, NumBytesRem); - NumBytesRead += NumBytesRem; - pBuffer += NumBytesRem; - BufferSize -= NumBytesRem; - RdOff += NumBytesRem; - } - if (NumBytesRead) { - pRing->RdOff = RdOff; - } - // - return NumBytesRead; -} - -/********************************************************************* -* -* SEGGER_RTT_Read -* -* Function description -* Reads characters from SEGGER real-time-terminal control block -* which have been previously stored by the host. -* -* Parameters -* BufferIndex Index of Down-buffer to be used (e.g. 0 for "Terminal"). -* pBuffer Pointer to buffer provided by target application, to copy characters from RTT-down-buffer to. -* BufferSize Size of the target application buffer. -* -* Return value -* Number of bytes that have been read. -*/ -unsigned SEGGER_RTT_Read(unsigned BufferIndex, void* pBuffer, unsigned BufferSize) { - unsigned NumBytesRead; - // - SEGGER_RTT_LOCK(); - // - // Call the non-locking read function - // - NumBytesRead = SEGGER_RTT_ReadNoLock(BufferIndex, pBuffer, BufferSize); - // - // Finish up. - // - SEGGER_RTT_UNLOCK(); - // - return NumBytesRead; -} - -/********************************************************************* -* -* SEGGER_RTT_WriteWithOverwriteNoLock -* -* Function description -* Stores a specified number of characters in SEGGER RTT -* control block. -* SEGGER_RTT_WriteWithOverwriteNoLock does not lock the application -* and overwrites data if the data does not fit into the buffer. -* -* Parameters -* BufferIndex Index of "Up"-buffer to be used (e.g. 0 for "Terminal"). -* pBuffer Pointer to character array. Does not need to point to a \0 terminated string. -* NumBytes Number of bytes to be stored in the SEGGER RTT control block. -* -* Notes -* (1) If there is not enough space in the "Up"-buffer, data is overwritten. -* (2) For performance reasons this function does not call Init() -* and may only be called after RTT has been initialized. -* Either by calling SEGGER_RTT_Init() or calling another RTT API function first. -* (3) Do not use SEGGER_RTT_WriteWithOverwriteNoLock if a J-Link -* connection reads RTT data. -*/ -void SEGGER_RTT_WriteWithOverwriteNoLock(unsigned BufferIndex, const void* pBuffer, unsigned NumBytes) { - const char* pData; - SEGGER_RTT_BUFFER_UP* pRing; - unsigned Avail; - - pData = (const char *)pBuffer; - // - // Get "to-host" ring buffer and copy some elements into local variables. - // - pRing = &_SEGGER_RTT.aUp[BufferIndex]; - // - // Check if we will overwrite data and need to adjust the RdOff. - // - if (pRing->WrOff == pRing->RdOff) { - Avail = pRing->SizeOfBuffer - 1u; - } else if ( pRing->WrOff < pRing->RdOff) { - Avail = pRing->RdOff - pRing->WrOff - 1u; - } else { - Avail = pRing->RdOff - pRing->WrOff - 1u + pRing->SizeOfBuffer; - } - if (NumBytes > Avail) { - pRing->RdOff += (NumBytes - Avail); - while (pRing->RdOff >= pRing->SizeOfBuffer) { - pRing->RdOff -= pRing->SizeOfBuffer; - } - } - // - // Write all data, no need to check the RdOff, but possibly handle multiple wrap-arounds - // - Avail = pRing->SizeOfBuffer - pRing->WrOff; - do { - if (Avail > NumBytes) { - // - // Last round - // -#if 1 // memcpy() is good for large amounts of data, but the overhead is too big for small amounts. Use a simple byte loop instead. - char* pDst; - pDst = pRing->pBuffer + pRing->WrOff; - pRing->WrOff += NumBytes; - do { - *pDst++ = *pData++; - } while (--NumBytes); -#else - memcpy(pRing->pBuffer + WrOff, pData, NumBytes); - pRing->WrOff += NumBytes; -#endif - break; //Alternatively: NumBytes = 0; - } else { - // - // Wrap-around necessary, write until wrap-around and reset WrOff - // - memcpy(pRing->pBuffer + pRing->WrOff, pData, Avail); - pData += Avail; - pRing->WrOff = 0; - NumBytes -= Avail; - Avail = (pRing->SizeOfBuffer - 1); - } - } while (NumBytes); -} - -/********************************************************************* -* -* SEGGER_RTT_WriteSkipNoLock -* -* Function description -* Stores a specified number of characters in SEGGER RTT -* control block which is then read by the host. -* SEGGER_RTT_WriteSkipNoLock does not lock the application and -* skips all data, if the data does not fit into the buffer. -* -* Parameters -* BufferIndex Index of "Up"-buffer to be used (e.g. 0 for "Terminal"). -* pBuffer Pointer to character array. Does not need to point to a \0 terminated string. -* NumBytes Number of bytes to be stored in the SEGGER RTT control block. -* -* Return value -* Number of bytes which have been stored in the "Up"-buffer. -* -* Notes -* (1) If there is not enough space in the "Up"-buffer, all data is dropped. -* (2) For performance reasons this function does not call Init() -* and may only be called after RTT has been initialized. -* Either by calling SEGGER_RTT_Init() or calling another RTT API function first. -*/ -unsigned SEGGER_RTT_WriteSkipNoLock(unsigned BufferIndex, const void* pBuffer, unsigned NumBytes) { - const char* pData; - SEGGER_RTT_BUFFER_UP* pRing; - unsigned Avail; - unsigned RdOff; - unsigned WrOff; - unsigned Rem; - - pData = (const char *)pBuffer; - // - // Get "to-host" ring buffer and copy some elements into local variables. - // - pRing = &_SEGGER_RTT.aUp[BufferIndex]; - RdOff = pRing->RdOff; - WrOff = pRing->WrOff; - // - // Handle the most common cases fastest. - // Which is: - // RdOff <= WrOff -> Space until wrap around is free. - // AND - // WrOff + NumBytes < SizeOfBuffer -> No Wrap around necessary. - // - // OR - // - // RdOff > WrOff -> Space until RdOff - 1 is free. - // AND - // WrOff + NumBytes < RdOff -> Data fits into buffer - // - if (RdOff <= WrOff) { - // - // Get space until WrOff will be at wrap around. - // - Avail = pRing->SizeOfBuffer - 1u - WrOff ; - if (Avail >= NumBytes) { -#if 1 // memcpy() is good for large amounts of data, but the overhead is too big for small amounts. Use a simple byte loop instead. - char* pDst; - pDst = pRing->pBuffer + WrOff; - WrOff += NumBytes; - do { - *pDst++ = *pData++; - } while (--NumBytes); - pRing->WrOff = WrOff + NumBytes; -#else - memcpy(pRing->pBuffer + WrOff, pData, NumBytes); - pRing->WrOff = WrOff + NumBytes; -#endif - return 1; - } - // - // If data did not fit into space until wrap around calculate complete space in buffer. - // - Avail += RdOff; - // - // If there is still no space for the whole of this output, don't bother. - // - if (Avail >= NumBytes) { - // - // OK, we have enough space in buffer. Copy in one or 2 chunks - // - Rem = pRing->SizeOfBuffer - WrOff; // Space until end of buffer - if (Rem > NumBytes) { - memcpy(pRing->pBuffer + WrOff, pData, NumBytes); - pRing->WrOff = WrOff + NumBytes; - } else { - // - // We reach the end of the buffer, so need to wrap around - // - memcpy(pRing->pBuffer + WrOff, pData, Rem); - memcpy(pRing->pBuffer, pData + Rem, NumBytes - Rem); - pRing->WrOff = NumBytes - Rem; - } - return 1; - } - } else { - Avail = RdOff - WrOff - 1u; - if (Avail >= NumBytes) { - memcpy(pRing->pBuffer + WrOff, pData, NumBytes); - pRing->WrOff = WrOff + NumBytes; - return 1; - } - } - // - // If we reach this point no data has been written - // - return 0; -} - -/********************************************************************* -* -* SEGGER_RTT_WriteNoLock -* -* Function description -* Stores a specified number of characters in SEGGER RTT -* control block which is then read by the host. -* SEGGER_RTT_WriteNoLock does not lock the application. -* -* Parameters -* BufferIndex Index of "Up"-buffer to be used (e.g. 0 for "Terminal"). -* pBuffer Pointer to character array. Does not need to point to a \0 terminated string. -* NumBytes Number of bytes to be stored in the SEGGER RTT control block. -* -* Return value -* Number of bytes which have been stored in the "Up"-buffer. -* -* Notes -* (1) If there is not enough space in the "Up"-buffer, remaining characters of pBuffer are dropped. -* (2) For performance reasons this function does not call Init() -* and may only be called after RTT has been initialized. -* Either by calling SEGGER_RTT_Init() or calling another RTT API function first. -*/ -unsigned SEGGER_RTT_WriteNoLock(unsigned BufferIndex, const void* pBuffer, unsigned NumBytes) { - unsigned Status; - unsigned Avail; - const char* pData; - SEGGER_RTT_BUFFER_UP* pRing; - - pData = (const char *)pBuffer; - // - // Get "to-host" ring buffer. - // - pRing = &_SEGGER_RTT.aUp[BufferIndex]; - // - // How we output depends upon the mode... - // - switch (pRing->Flags) { - case SEGGER_RTT_MODE_NO_BLOCK_SKIP: - // - // If we are in skip mode and there is no space for the whole - // of this output, don't bother. - // - Avail = _GetAvailWriteSpace(pRing); - if (Avail < NumBytes) { - Status = 0u; - } else { - Status = NumBytes; - _WriteNoCheck(pRing, pData, NumBytes); - } - break; - case SEGGER_RTT_MODE_NO_BLOCK_TRIM: - // - // If we are in trim mode, trim to what we can output without blocking. - // - Avail = _GetAvailWriteSpace(pRing); - Status = Avail < NumBytes ? Avail : NumBytes; - _WriteNoCheck(pRing, pData, Status); - break; - case SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL: - // - // If we are in blocking mode, output everything. - // - Status = _WriteBlocking(pRing, pData, NumBytes); - break; - default: - Status = 0u; - break; - } - // - // Finish up. - // - return Status; -} - -/********************************************************************* -* -* SEGGER_RTT_Write -* -* Function description -* Stores a specified number of characters in SEGGER RTT -* control block which is then read by the host. -* -* Parameters -* BufferIndex Index of "Up"-buffer to be used (e.g. 0 for "Terminal"). -* pBuffer Pointer to character array. Does not need to point to a \0 terminated string. -* NumBytes Number of bytes to be stored in the SEGGER RTT control block. -* -* Return value -* Number of bytes which have been stored in the "Up"-buffer. -* -* Notes -* (1) If there is not enough space in the "Up"-buffer, remaining characters of pBuffer are dropped. -*/ -unsigned SEGGER_RTT_Write(unsigned BufferIndex, const void* pBuffer, unsigned NumBytes) { - unsigned Status; - // - INIT(); - SEGGER_RTT_LOCK(); - // - // Call the non-locking write function - // - Status = SEGGER_RTT_WriteNoLock(BufferIndex, pBuffer, NumBytes); - // - // Finish up. - // - SEGGER_RTT_UNLOCK(); - // - return Status; -} - -/********************************************************************* -* -* SEGGER_RTT_WriteString -* -* Function description -* Stores string in SEGGER RTT control block. -* This data is read by the host. -* -* Parameters -* BufferIndex Index of "Up"-buffer to be used (e.g. 0 for "Terminal"). -* s Pointer to string. -* -* Return value -* Number of bytes which have been stored in the "Up"-buffer. -* -* Notes -* (1) If there is not enough space in the "Up"-buffer, depending on configuration, -* remaining characters may be dropped or RTT module waits until there is more space in the buffer. -* (2) String passed to this function has to be \0 terminated -* (3) \0 termination character is *not* stored in RTT buffer -*/ -unsigned SEGGER_RTT_WriteString(unsigned BufferIndex, const char* s) { - unsigned Len; - - Len = STRLEN(s); - return SEGGER_RTT_Write(BufferIndex, s, Len); -} - -/********************************************************************* -* -* SEGGER_RTT_GetKey -* -* Function description -* Reads one character from the SEGGER RTT buffer. -* Host has previously stored data there. -* -* Return value -* < 0 - No character available (buffer empty). -* >= 0 - Character which has been read. (Possible values: 0 - 255) -* -* Notes -* (1) This function is only specified for accesses to RTT buffer 0. -*/ -int SEGGER_RTT_GetKey(void) { - char c; - int r; - - r = (int)SEGGER_RTT_Read(0u, &c, 1u); - if (r == 1) { - r = (int)(unsigned char)c; - } else { - r = -1; - } - return r; -} - -/********************************************************************* -* -* SEGGER_RTT_WaitKey -* -* Function description -* Waits until at least one character is avaible in the SEGGER RTT buffer. -* Once a character is available, it is read and this function returns. -* -* Return value -* >=0 - Character which has been read. -* -* Notes -* (1) This function is only specified for accesses to RTT buffer 0 -* (2) This function is blocking if no character is present in RTT buffer -*/ -int SEGGER_RTT_WaitKey(void) { - int r; - - do { - r = SEGGER_RTT_GetKey(); - } while (r < 0); - return r; -} - -/********************************************************************* -* -* SEGGER_RTT_HasKey -* -* Function description -* Checks if at least one character for reading is available in the SEGGER RTT buffer. -* -* Return value -* == 0 - No characters are available to read. -* == 1 - At least one character is available. -* -* Notes -* (1) This function is only specified for accesses to RTT buffer 0 -*/ -int SEGGER_RTT_HasKey(void) { - unsigned RdOff; - int r; - - INIT(); - RdOff = _SEGGER_RTT.aDown[0].RdOff; - if (RdOff != _SEGGER_RTT.aDown[0].WrOff) { - r = 1; - } else { - r = 0; - } - return r; -} - -/********************************************************************* -* -* SEGGER_RTT_HasData -* -* Function description -* Check if there is data from the host in the given buffer. -* -* Return value: -* ==0: No data -* !=0: Data in buffer -* -*/ -unsigned SEGGER_RTT_HasData(unsigned BufferIndex) { - SEGGER_RTT_BUFFER_DOWN* pRing; - unsigned v; - - pRing = &_SEGGER_RTT.aDown[BufferIndex]; - v = pRing->WrOff; - return v - pRing->RdOff; -} - -/********************************************************************* -* -* SEGGER_RTT_AllocDownBuffer -* -* Function description -* Run-time configuration of the next down-buffer (H->T). -* The next buffer, which is not used yet is configured. -* This includes: Buffer address, size, name, flags, ... -* -* Parameters -* sName Pointer to a constant name string. -* pBuffer Pointer to a buffer to be used. -* BufferSize Size of the buffer. -* Flags Operating modes. Define behavior if buffer is full (not enough space for entire message). -* -* Return value -* >= 0 - O.K. Buffer Index -* < 0 - Error -*/ -int SEGGER_RTT_AllocDownBuffer(const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags) { - int BufferIndex; - - INIT(); - SEGGER_RTT_LOCK(); - BufferIndex = 0; - do { - if (_SEGGER_RTT.aDown[BufferIndex].pBuffer == NULL) { - break; - } - BufferIndex++; - } while (BufferIndex < _SEGGER_RTT.MaxNumDownBuffers); - if (BufferIndex < _SEGGER_RTT.MaxNumDownBuffers) { - _SEGGER_RTT.aDown[BufferIndex].sName = sName; - _SEGGER_RTT.aDown[BufferIndex].pBuffer = pBuffer; - _SEGGER_RTT.aDown[BufferIndex].SizeOfBuffer = BufferSize; - _SEGGER_RTT.aDown[BufferIndex].RdOff = 0u; - _SEGGER_RTT.aDown[BufferIndex].WrOff = 0u; - _SEGGER_RTT.aDown[BufferIndex].Flags = Flags; - } else { - BufferIndex = -1; - } - SEGGER_RTT_UNLOCK(); - return BufferIndex; -} - -/********************************************************************* -* -* SEGGER_RTT_AllocUpBuffer -* -* Function description -* Run-time configuration of the next up-buffer (T->H). -* The next buffer, which is not used yet is configured. -* This includes: Buffer address, size, name, flags, ... -* -* Parameters -* sName Pointer to a constant name string. -* pBuffer Pointer to a buffer to be used. -* BufferSize Size of the buffer. -* Flags Operating modes. Define behavior if buffer is full (not enough space for entire message). -* -* Return value -* >= 0 - O.K. Buffer Index -* < 0 - Error -*/ -int SEGGER_RTT_AllocUpBuffer(const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags) { - int BufferIndex; - - INIT(); - SEGGER_RTT_LOCK(); - BufferIndex = 0; - do { - if (_SEGGER_RTT.aUp[BufferIndex].pBuffer == NULL) { - break; - } - BufferIndex++; - } while (BufferIndex < _SEGGER_RTT.MaxNumUpBuffers); - if (BufferIndex < _SEGGER_RTT.MaxNumUpBuffers) { - _SEGGER_RTT.aUp[BufferIndex].sName = sName; - _SEGGER_RTT.aUp[BufferIndex].pBuffer = pBuffer; - _SEGGER_RTT.aUp[BufferIndex].SizeOfBuffer = BufferSize; - _SEGGER_RTT.aUp[BufferIndex].RdOff = 0u; - _SEGGER_RTT.aUp[BufferIndex].WrOff = 0u; - _SEGGER_RTT.aUp[BufferIndex].Flags = Flags; - } else { - BufferIndex = -1; - } - SEGGER_RTT_UNLOCK(); - return BufferIndex; -} - -/********************************************************************* -* -* SEGGER_RTT_ConfigUpBuffer -* -* Function description -* Run-time configuration of a specific up-buffer (T->H). -* Buffer to be configured is specified by index. -* This includes: Buffer address, size, name, flags, ... -* -* Parameters -* BufferIndex Index of the buffer to configure. -* sName Pointer to a constant name string. -* pBuffer Pointer to a buffer to be used. -* BufferSize Size of the buffer. -* Flags Operating modes. Define behavior if buffer is full (not enough space for entire message). -* -* Return value -* >= 0 - O.K. -* < 0 - Error -*/ -int SEGGER_RTT_ConfigUpBuffer(unsigned BufferIndex, const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags) { - int r; - - INIT(); - if (BufferIndex < (unsigned)_SEGGER_RTT.MaxNumUpBuffers) { - SEGGER_RTT_LOCK(); - if (BufferIndex > 0u) { - _SEGGER_RTT.aUp[BufferIndex].sName = sName; - _SEGGER_RTT.aUp[BufferIndex].pBuffer = pBuffer; - _SEGGER_RTT.aUp[BufferIndex].SizeOfBuffer = BufferSize; - _SEGGER_RTT.aUp[BufferIndex].RdOff = 0u; - _SEGGER_RTT.aUp[BufferIndex].WrOff = 0u; - } - _SEGGER_RTT.aUp[BufferIndex].Flags = Flags; - SEGGER_RTT_UNLOCK(); - r = 0; - } else { - r = -1; - } - return r; -} - -/********************************************************************* -* -* SEGGER_RTT_ConfigDownBuffer -* -* Function description -* Run-time configuration of a specific down-buffer (H->T). -* Buffer to be configured is specified by index. -* This includes: Buffer address, size, name, flags, ... -* -* Parameters -* BufferIndex Index of the buffer to configure. -* sName Pointer to a constant name string. -* pBuffer Pointer to a buffer to be used. -* BufferSize Size of the buffer. -* Flags Operating modes. Define behavior if buffer is full (not enough space for entire message). -* -* Return value -* >= 0 O.K. -* < 0 Error -*/ -int SEGGER_RTT_ConfigDownBuffer(unsigned BufferIndex, const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags) { - int r; - - INIT(); - if (BufferIndex < (unsigned)_SEGGER_RTT.MaxNumDownBuffers) { - SEGGER_RTT_LOCK(); - if (BufferIndex > 0u) { - _SEGGER_RTT.aDown[BufferIndex].sName = sName; - _SEGGER_RTT.aDown[BufferIndex].pBuffer = pBuffer; - _SEGGER_RTT.aDown[BufferIndex].SizeOfBuffer = BufferSize; - _SEGGER_RTT.aDown[BufferIndex].RdOff = 0u; - _SEGGER_RTT.aDown[BufferIndex].WrOff = 0u; - } - _SEGGER_RTT.aDown[BufferIndex].Flags = Flags; - SEGGER_RTT_UNLOCK(); - r = 0; - } else { - r = -1; - } - return r; -} - -/********************************************************************* -* -* SEGGER_RTT_SetNameUpBuffer -* -* Function description -* Run-time configuration of a specific up-buffer name (T->H). -* Buffer to be configured is specified by index. -* -* Parameters -* BufferIndex Index of the buffer to renamed. -* sName Pointer to a constant name string. -* -* Return value -* >= 0 O.K. -* < 0 Error -*/ -int SEGGER_RTT_SetNameUpBuffer(unsigned BufferIndex, const char* sName) { - int r; - - INIT(); - if (BufferIndex < (unsigned)_SEGGER_RTT.MaxNumUpBuffers) { - SEGGER_RTT_LOCK(); - _SEGGER_RTT.aUp[BufferIndex].sName = sName; - SEGGER_RTT_UNLOCK(); - r = 0; - } else { - r = -1; - } - return r; -} - -/********************************************************************* -* -* SEGGER_RTT_SetNameDownBuffer -* -* Function description -* Run-time configuration of a specific Down-buffer name (T->H). -* Buffer to be configured is specified by index. -* -* Parameters -* BufferIndex Index of the buffer to renamed. -* sName Pointer to a constant name string. -* -* Return value -* >= 0 O.K. -* < 0 Error -*/ -int SEGGER_RTT_SetNameDownBuffer(unsigned BufferIndex, const char* sName) { - int r; - - INIT(); - if (BufferIndex < (unsigned)_SEGGER_RTT.MaxNumDownBuffers) { - SEGGER_RTT_LOCK(); - _SEGGER_RTT.aDown[BufferIndex].sName = sName; - SEGGER_RTT_UNLOCK(); - r = 0; - } else { - r = -1; - } - return r; -} - -/********************************************************************* -* -* SEGGER_RTT_Init -* -* Function description -* Initializes the RTT Control Block. -* Should be used in RAM targets, at start of the application. -* -*/ -void SEGGER_RTT_Init (void) { - _DoInit(); -} - -/********************************************************************* -* -* SEGGER_RTT_SetTerminal -* -* Function description -* Sets the terminal to be used for output on channel 0. -* -* Parameters -* TerminalId Index of the terminal. -* -* Return value -* >= 0 O.K. -* < 0 Error (e.g. if RTT is configured for non-blocking mode and there was no space in the buffer to set the new terminal Id) -*/ -int SEGGER_RTT_SetTerminal (char TerminalId) { - char ac[2]; - SEGGER_RTT_BUFFER_UP* pRing; - unsigned Avail; - int r; - // - INIT(); - // - r = 0; - ac[0] = 0xFFU; - if ((unsigned char)TerminalId < (unsigned char)sizeof(_aTerminalId)) { // We only support a certain number of channels - ac[1] = _aTerminalId[(unsigned char)TerminalId]; - pRing = &_SEGGER_RTT.aUp[0]; // Buffer 0 is always reserved for terminal I/O, so we can use index 0 here, fixed - SEGGER_RTT_LOCK(); // Lock to make sure that no other task is writing into buffer, while we are and number of free bytes in buffer does not change downwards after checking and before writing - if ((pRing->Flags & SEGGER_RTT_MODE_MASK) == SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL) { - _ActiveTerminal = TerminalId; - _WriteBlocking(pRing, ac, 2u); - } else { // Skipping mode or trim mode? => We cannot trim this command so handling is the same for both modes - Avail = _GetAvailWriteSpace(pRing); - if (Avail >= 2) { - _ActiveTerminal = TerminalId; // Only change active terminal in case of success - _WriteNoCheck(pRing, ac, 2u); - } else { - r = -1; - } - } - SEGGER_RTT_UNLOCK(); - } else { - r = -1; - } - return r; -} - -/********************************************************************* -* -* SEGGER_RTT_TerminalOut -* -* Function description -* Writes a string to the given terminal -* without changing the terminal for channel 0. -* -* Parameters -* TerminalId Index of the terminal. -* s String to be printed on the terminal. -* -* Return value -* >= 0 - Number of bytes written. -* < 0 - Error. -* -*/ -int SEGGER_RTT_TerminalOut (char TerminalId, const char* s) { - int Status; - unsigned FragLen; - unsigned Avail; - SEGGER_RTT_BUFFER_UP* pRing; - // - INIT(); - // - // Validate terminal ID. - // - if (TerminalId < (char)sizeof(_aTerminalId)) { // We only support a certain number of channels - // - // Get "to-host" ring buffer. - // - pRing = &_SEGGER_RTT.aUp[0]; - // - // Need to be able to change terminal, write data, change back. - // Compute the fixed and variable sizes. - // - FragLen = strlen(s); - // - // How we output depends upon the mode... - // - SEGGER_RTT_LOCK(); - Avail = _GetAvailWriteSpace(pRing); - switch (pRing->Flags & SEGGER_RTT_MODE_MASK) { - case SEGGER_RTT_MODE_NO_BLOCK_SKIP: - // - // If we are in skip mode and there is no space for the whole - // of this output, don't bother switching terminals at all. - // - if (Avail < (FragLen + 4u)) { - Status = 0; - } else { - _PostTerminalSwitch(pRing, TerminalId); - Status = (int)_WriteBlocking(pRing, s, FragLen); - _PostTerminalSwitch(pRing, _ActiveTerminal); - } - break; - case SEGGER_RTT_MODE_NO_BLOCK_TRIM: - // - // If we are in trim mode and there is not enough space for everything, - // trim the output but always include the terminal switch. If no room - // for terminal switch, skip that totally. - // - if (Avail < 4u) { - Status = -1; - } else { - _PostTerminalSwitch(pRing, TerminalId); - Status = (int)_WriteBlocking(pRing, s, (FragLen < (Avail - 4u)) ? FragLen : (Avail - 4u)); - _PostTerminalSwitch(pRing, _ActiveTerminal); - } - break; - case SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL: - // - // If we are in blocking mode, output everything. - // - _PostTerminalSwitch(pRing, TerminalId); - Status = (int)_WriteBlocking(pRing, s, FragLen); - _PostTerminalSwitch(pRing, _ActiveTerminal); - break; - default: - Status = -1; - break; - } - // - // Finish up. - // - SEGGER_RTT_UNLOCK(); - } else { - Status = -1; - } - return Status; -} - - -/*************************** End of file ****************************/ diff --git a/examples/device/nrf52840/segger/SEGGER_RTT.h b/examples/device/nrf52840/segger/SEGGER_RTT.h deleted file mode 100644 index d3cac44dd..000000000 --- a/examples/device/nrf52840/segger/SEGGER_RTT.h +++ /dev/null @@ -1,234 +0,0 @@ -/********************************************************************* -* SEGGER MICROCONTROLLER GmbH & Co. KG * -* Solutions for real time microcontroller applications * -********************************************************************** -* * -* (c) 2014 - 2016 SEGGER Microcontroller GmbH & Co. KG * -* * -* www.segger.com Support: support@segger.com * -* * -********************************************************************** -* * -* SEGGER RTT * Real Time Transfer for embedded targets * -* * -********************************************************************** -* * -* All rights reserved. * -* * -* * This software may in its unmodified form be freely redistributed * -* in source form. * -* * The source code may be modified, provided the source code * -* retains the above copyright notice, this list of conditions and * -* the following disclaimer. * -* * Modified versions of this software in source or linkable form * -* may not be distributed without prior consent of SEGGER. * -* * This software may only be used for communication with SEGGER * -* J-Link debug probes. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * -* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * -* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * -* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * -* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * -* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * -* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * -* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * -* DAMAGE. * -* * -********************************************************************** -* * -* RTT version: 5.12e * -* * -********************************************************************** ----------------------------END-OF-HEADER------------------------------ -File : SEGGER_RTT.h -Purpose : Implementation of SEGGER real-time transfer which allows - real-time communication on targets which support debugger - memory accesses while the CPU is running. ----------------------------------------------------------------------- -*/ - -#ifndef SEGGER_RTT_H -#define SEGGER_RTT_H - -#include "SEGGER_RTT_Conf.h" - -/********************************************************************* -* -* Defines, fixed -* -********************************************************************** -*/ - -/********************************************************************* -* -* Types -* -********************************************************************** -*/ - -// -// Description for a circular buffer (also called "ring buffer") -// which is used as up-buffer (T->H) -// -typedef struct { - const char* sName; // Optional name. Standard names so far are: "Terminal", "SysView", "J-Scope_t4i4" - char* pBuffer; // Pointer to start of buffer - unsigned SizeOfBuffer; // Buffer size in bytes. Note that one byte is lost, as this implementation does not fill up the buffer in order to avoid the problem of being unable to distinguish between full and empty. - unsigned WrOff; // Position of next item to be written by either target. - volatile unsigned RdOff; // Position of next item to be read by host. Must be volatile since it may be modified by host. - unsigned Flags; // Contains configuration flags -} SEGGER_RTT_BUFFER_UP; - -// -// Description for a circular buffer (also called "ring buffer") -// which is used as down-buffer (H->T) -// -typedef struct { - const char* sName; // Optional name. Standard names so far are: "Terminal", "SysView", "J-Scope_t4i4" - char* pBuffer; // Pointer to start of buffer - unsigned SizeOfBuffer; // Buffer size in bytes. Note that one byte is lost, as this implementation does not fill up the buffer in order to avoid the problem of being unable to distinguish between full and empty. - volatile unsigned WrOff; // Position of next item to be written by host. Must be volatile since it may be modified by host. - unsigned RdOff; // Position of next item to be read by target (down-buffer). - unsigned Flags; // Contains configuration flags -} SEGGER_RTT_BUFFER_DOWN; - -// -// RTT control block which describes the number of buffers available -// as well as the configuration for each buffer -// -// -typedef struct { - char acID[16]; // Initialized to "SEGGER RTT" - int MaxNumUpBuffers; // Initialized to SEGGER_RTT_MAX_NUM_UP_BUFFERS (type. 2) - int MaxNumDownBuffers; // Initialized to SEGGER_RTT_MAX_NUM_DOWN_BUFFERS (type. 2) - SEGGER_RTT_BUFFER_UP aUp[SEGGER_RTT_MAX_NUM_UP_BUFFERS]; // Up buffers, transferring information up from target via debug probe to host - SEGGER_RTT_BUFFER_DOWN aDown[SEGGER_RTT_MAX_NUM_DOWN_BUFFERS]; // Down buffers, transferring information down from host via debug probe to target -} SEGGER_RTT_CB; - -/********************************************************************* -* -* Global data -* -********************************************************************** -*/ -extern SEGGER_RTT_CB _SEGGER_RTT; - -/********************************************************************* -* -* RTT API functions -* -********************************************************************** -*/ -#ifdef __cplusplus - extern "C" { -#endif -int SEGGER_RTT_AllocDownBuffer (const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags); -int SEGGER_RTT_AllocUpBuffer (const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags); -int SEGGER_RTT_ConfigUpBuffer (unsigned BufferIndex, const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags); -int SEGGER_RTT_ConfigDownBuffer (unsigned BufferIndex, const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags); -int SEGGER_RTT_GetKey (void); -unsigned SEGGER_RTT_HasData (unsigned BufferIndex); -int SEGGER_RTT_HasKey (void); -void SEGGER_RTT_Init (void); -unsigned SEGGER_RTT_Read (unsigned BufferIndex, void* pBuffer, unsigned BufferSize); -unsigned SEGGER_RTT_ReadNoLock (unsigned BufferIndex, void* pData, unsigned BufferSize); -int SEGGER_RTT_SetNameDownBuffer(unsigned BufferIndex, const char* sName); -int SEGGER_RTT_SetNameUpBuffer (unsigned BufferIndex, const char* sName); -int SEGGER_RTT_WaitKey (void); -unsigned SEGGER_RTT_Write (unsigned BufferIndex, const void* pBuffer, unsigned NumBytes); -unsigned SEGGER_RTT_WriteNoLock (unsigned BufferIndex, const void* pBuffer, unsigned NumBytes); -unsigned SEGGER_RTT_WriteSkipNoLock (unsigned BufferIndex, const void* pBuffer, unsigned NumBytes); -unsigned SEGGER_RTT_WriteString (unsigned BufferIndex, const char* s); -void SEGGER_RTT_WriteWithOverwriteNoLock(unsigned BufferIndex, const void* pBuffer, unsigned NumBytes); -// -// Function macro for performance optimization -// -#define SEGGER_RTT_HASDATA(n) (_SEGGER_RTT.aDown[n].WrOff - _SEGGER_RTT.aDown[n].RdOff) - -/********************************************************************* -* -* RTT "Terminal" API functions -* -********************************************************************** -*/ -int SEGGER_RTT_SetTerminal (char TerminalId); -int SEGGER_RTT_TerminalOut (char TerminalId, const char* s); - -/********************************************************************* -* -* RTT printf functions (require SEGGER_RTT_printf.c) -* -********************************************************************** -*/ -int SEGGER_RTT_printf(unsigned BufferIndex, const char * sFormat, ...); -#ifdef __cplusplus - } -#endif - -/********************************************************************* -* -* Defines -* -********************************************************************** -*/ - -// -// Operating modes. Define behavior if buffer is full (not enough space for entire message) -// -#define SEGGER_RTT_MODE_NO_BLOCK_SKIP (0U) // Skip. Do not block, output nothing. (Default) -#define SEGGER_RTT_MODE_NO_BLOCK_TRIM (1U) // Trim: Do not block, output as much as fits. -#define SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL (2U) // Block: Wait until there is space in the buffer. -#define SEGGER_RTT_MODE_MASK (3U) - -// -// Control sequences, based on ANSI. -// Can be used to control color, and clear the screen -// -#define RTT_CTRL_RESET "" // Reset to default colors -#define RTT_CTRL_CLEAR "" // Clear screen, reposition cursor to top left - -#define RTT_CTRL_TEXT_BLACK "" -#define RTT_CTRL_TEXT_RED "" -#define RTT_CTRL_TEXT_GREEN "" -#define RTT_CTRL_TEXT_YELLOW "" -#define RTT_CTRL_TEXT_BLUE "" -#define RTT_CTRL_TEXT_MAGENTA "" -#define RTT_CTRL_TEXT_CYAN "" -#define RTT_CTRL_TEXT_WHITE "" - -#define RTT_CTRL_TEXT_BRIGHT_BLACK "" -#define RTT_CTRL_TEXT_BRIGHT_RED "" -#define RTT_CTRL_TEXT_BRIGHT_GREEN "" -#define RTT_CTRL_TEXT_BRIGHT_YELLOW "" -#define RTT_CTRL_TEXT_BRIGHT_BLUE "" -#define RTT_CTRL_TEXT_BRIGHT_MAGENTA "" -#define RTT_CTRL_TEXT_BRIGHT_CYAN "" -#define RTT_CTRL_TEXT_BRIGHT_WHITE "" - -#define RTT_CTRL_BG_BLACK "" -#define RTT_CTRL_BG_RED "" -#define RTT_CTRL_BG_GREEN "" -#define RTT_CTRL_BG_YELLOW "" -#define RTT_CTRL_BG_BLUE "" -#define RTT_CTRL_BG_MAGENTA "" -#define RTT_CTRL_BG_CYAN "" -#define RTT_CTRL_BG_WHITE "" - -#define RTT_CTRL_BG_BRIGHT_BLACK "" -#define RTT_CTRL_BG_BRIGHT_RED "" -#define RTT_CTRL_BG_BRIGHT_GREEN "" -#define RTT_CTRL_BG_BRIGHT_YELLOW "" -#define RTT_CTRL_BG_BRIGHT_BLUE "" -#define RTT_CTRL_BG_BRIGHT_MAGENTA "" -#define RTT_CTRL_BG_BRIGHT_CYAN "" -#define RTT_CTRL_BG_BRIGHT_WHITE "" - - -#endif - -/*************************** End of file ****************************/ diff --git a/examples/device/nrf52840/segger/SEGGER_RTT_Conf.h b/examples/device/nrf52840/segger/SEGGER_RTT_Conf.h deleted file mode 100644 index aef3b4053..000000000 --- a/examples/device/nrf52840/segger/SEGGER_RTT_Conf.h +++ /dev/null @@ -1,242 +0,0 @@ -/********************************************************************* -* SEGGER MICROCONTROLLER GmbH & Co. KG * -* Solutions for real time microcontroller applications * -********************************************************************** -* * -* (c) 2014 - 2016 SEGGER Microcontroller GmbH & Co. KG * -* * -* www.segger.com Support: support@segger.com * -* * -********************************************************************** -* * -* SEGGER RTT * Real Time Transfer for embedded targets * -* * -********************************************************************** -* * -* All rights reserved. * -* * -* * This software may in its unmodified form be freely redistributed * -* in source form. * -* * The source code may be modified, provided the source code * -* retains the above copyright notice, this list of conditions and * -* the following disclaimer. * -* * Modified versions of this software in source or linkable form * -* may not be distributed without prior consent of SEGGER. * -* * This software may only be used for communication with SEGGER * -* J-Link debug probes. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * -* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * -* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * -* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * -* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * -* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * -* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * -* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * -* DAMAGE. * -* * -********************************************************************** -* * -* RTT version: 5.12e * -* * -********************************************************************** ----------------------------------------------------------------------- -File : SEGGER_RTT_Conf.h -Purpose : Implementation of SEGGER real-time transfer (RTT) which - allows real-time communication on targets which support - debugger memory accesses while the CPU is running. ----------------------------END-OF-HEADER------------------------------ -*/ - -#ifndef SEGGER_RTT_CONF_H -#define SEGGER_RTT_CONF_H - -#ifdef __ICCARM__ - #include -#endif - -/********************************************************************* -* -* Defines, configurable -* -********************************************************************** -*/ - -#define SEGGER_RTT_MAX_NUM_UP_BUFFERS (2) // Max. number of up-buffers (T->H) available on this target (Default: 2) -#define SEGGER_RTT_MAX_NUM_DOWN_BUFFERS (2) // Max. number of down-buffers (H->T) available on this target (Default: 2) - -#define BUFFER_SIZE_UP (1024) // Size of the buffer for terminal output of target, up to host (Default: 1k) -#define BUFFER_SIZE_DOWN (16) // Size of the buffer for terminal input to target from host (Usually keyboard input) (Default: 16) - -#define SEGGER_RTT_PRINTF_BUFFER_SIZE (64u) // Size of buffer for RTT printf to bulk-send chars via RTT (Default: 64) - -#define SEGGER_RTT_MODE_DEFAULT SEGGER_RTT_MODE_NO_BLOCK_SKIP // Mode for pre-initialized terminal channel (buffer 0) - -// -// Target is not allowed to perform other RTT operations while string still has not been stored completely. -// Otherwise we would probably end up with a mixed string in the buffer. -// If using RTT from within interrupts, multiple tasks or multi processors, define the SEGGER_RTT_LOCK() and SEGGER_RTT_UNLOCK() function here. -// -// SEGGER_RTT_MAX_INTERRUPT_PRIORITY can be used in the sample lock routines on Cortex-M3/4. -// Make sure to mask all interrupts which can send RTT data, i.e. generate SystemView events, or cause task switches. -// When high-priority interrupts must not be masked while sending RTT data, SEGGER_RTT_MAX_INTERRUPT_PRIORITY needs to be adjusted accordingly. -// (Higher priority = lower priority number) -// Default value for embOS: 128u -// Default configuration in FreeRTOS: configMAX_SYSCALL_INTERRUPT_PRIORITY: ( configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY << (8 - configPRIO_BITS) ) -// In case of doubt mask all interrupts: 0u -// - -#define SEGGER_RTT_MAX_INTERRUPT_PRIORITY (0x20) // Interrupt priority to lock on SEGGER_RTT_LOCK on Cortex-M3/4 (Default: 0x20) - -/********************************************************************* -* -* RTT lock configuration for SEGGER Embedded Studio, -* Rowley CrossStudio and GCC -*/ -#if (defined __SES_ARM) || (defined __CROSSWORKS_ARM) || (defined __GNUC__) - #ifdef __ARM_ARCH_6M__ - #define SEGGER_RTT_LOCK() { \ - unsigned int LockState; \ - __asm volatile ("mrs %0, primask \n\t" \ - "mov r1, $1 \n\t" \ - "msr primask, r1 \n\t" \ - : "=r" (LockState) \ - : \ - : "r1" \ - ); - - #define SEGGER_RTT_UNLOCK() __asm volatile ("msr primask, %0 \n\t" \ - : \ - : "r" (LockState) \ - : \ - ); \ - } - - #elif (defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7EM__)) - #ifndef SEGGER_RTT_MAX_INTERRUPT_PRIORITY - #define SEGGER_RTT_MAX_INTERRUPT_PRIORITY (0x20) - #endif - #define SEGGER_RTT_LOCK() { \ - unsigned int LockState; \ - __asm volatile ("mrs %0, basepri \n\t" \ - "mov r1, %1 \n\t" \ - "msr basepri, r1 \n\t" \ - : "=r" (LockState) \ - : "i"(SEGGER_RTT_MAX_INTERRUPT_PRIORITY) \ - : "r1" \ - ); - - #define SEGGER_RTT_UNLOCK() __asm volatile ("msr basepri, %0 \n\t" \ - : \ - : "r" (LockState) \ - : \ - ); \ - } - - #elif defined(__ARM_ARCH_7A__) - #define SEGGER_RTT_LOCK() { \ - unsigned int LockState; \ - __asm volatile ("mrs r1, CPSR \n\t" \ - "mov %0, r1 \n\t" \ - "orr r1, r1, #0xC0 \n\t" \ - "msr CPSR_c, r1 \n\t" \ - : "=r" (LockState) \ - : \ - : "r1" \ - ); - - #define SEGGER_RTT_UNLOCK() __asm volatile ("mov r0, %0 \n\t" \ - "mrs r1, CPSR \n\t" \ - "bic r1, r1, #0xC0 \n\t" \ - "and r0, r0, #0xC0 \n\t" \ - "orr r1, r1, r0 \n\t" \ - "msr CPSR_c, r1 \n\t" \ - : \ - : "r" (LockState) \ - : "r0", "r1" \ - ); \ - } -#else - #define SEGGER_RTT_LOCK() - #define SEGGER_RTT_UNLOCK() - #endif -#endif - -/********************************************************************* -* -* RTT lock configuration for IAR EWARM -*/ -#ifdef __ICCARM__ - #if (defined (__ARM6M__) && (__CORE__ == __ARM6M__)) - #define SEGGER_RTT_LOCK() { \ - unsigned int LockState; \ - LockState = __get_PRIMASK(); \ - __set_PRIMASK(1); - - #define SEGGER_RTT_UNLOCK() __set_PRIMASK(LockState); \ - } - #elif ((defined (__ARM7EM__) && (__CORE__ == __ARM7EM__)) || (defined (__ARM7M__) && (__CORE__ == __ARM7M__))) - #ifndef SEGGER_RTT_MAX_INTERRUPT_PRIORITY - #define SEGGER_RTT_MAX_INTERRUPT_PRIORITY (0x20) - #endif - #define SEGGER_RTT_LOCK() { \ - unsigned int LockState; \ - LockState = __get_BASEPRI(); \ - __set_BASEPRI(SEGGER_RTT_MAX_INTERRUPT_PRIORITY); - - #define SEGGER_RTT_UNLOCK() __set_BASEPRI(LockState); \ - } - #endif -#endif - -/********************************************************************* -* -* RTT lock configuration for KEIL ARM -*/ -#ifdef __CC_ARM - #if (defined __TARGET_ARCH_6S_M) - #define SEGGER_RTT_LOCK() { \ - unsigned int LockState; \ - register unsigned char PRIMASK __asm( "primask"); \ - LockState = PRIMASK; \ - PRIMASK = 1u; \ - __schedule_barrier(); - - #define SEGGER_RTT_UNLOCK() PRIMASK = LockState; \ - __schedule_barrier(); \ - } - #elif (defined(__TARGET_ARCH_7_M) || defined(__TARGET_ARCH_7E_M)) - #ifndef SEGGER_RTT_MAX_INTERRUPT_PRIORITY - #define SEGGER_RTT_MAX_INTERRUPT_PRIORITY (0x20) - #endif - #define SEGGER_RTT_LOCK() { \ - unsigned int LockState; \ - register unsigned char BASEPRI __asm( "basepri"); \ - LockState = BASEPRI; \ - BASEPRI = SEGGER_RTT_MAX_INTERRUPT_PRIORITY; \ - __schedule_barrier(); - - #define SEGGER_RTT_UNLOCK() BASEPRI = LockState; \ - __schedule_barrier(); \ - } - #endif -#endif - -/********************************************************************* -* -* RTT lock configuration fallback -*/ -#ifndef SEGGER_RTT_LOCK - #define SEGGER_RTT_LOCK() // Lock RTT (nestable) (i.e. disable interrupts) -#endif - -#ifndef SEGGER_RTT_UNLOCK - #define SEGGER_RTT_UNLOCK() // Unlock RTT (nestable) (i.e. enable previous interrupt lock state) -#endif - -#endif -/*************************** End of file ****************************/ diff --git a/examples/device/nrf52840/segger/SEGGER_RTT_SES.c b/examples/device/nrf52840/segger/SEGGER_RTT_SES.c deleted file mode 100644 index e6634147c..000000000 --- a/examples/device/nrf52840/segger/SEGGER_RTT_SES.c +++ /dev/null @@ -1,76 +0,0 @@ -/********************************************************************* -* SEGGER MICROCONTROLLER GmbH & Co. KG * -* Solutions for real time microcontroller applications * -********************************************************************** -* * -* (c) 2014 - 2015 SEGGER Microcontroller GmbH & Co. KG * -* * -* www.segger.com Support: support@segger.com * -* * -********************************************************************** -* * -* All rights reserved. * -* * -* * This software may in its unmodified form be freely redistributed * -* in source form. * -* * The source code may be modified, provided the source code * -* retains the above copyright notice, this list of conditions and * -* the following disclaimer. * -* * Modified versions of this software in source or linkable form * -* may not be distributed without prior consent of SEGGER. * -* * This software may only be used for communication with SEGGER * -* J-Link debug probes. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * -* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * -* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * -* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * -* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * -* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * -* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * -* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * -* DAMAGE. * -* * -********************************************************************** --------- END-OF-HEADER --------------------------------------------- -File : SEGGER_RTT_Syscalls_SES.c -Purpose : Reimplementation of printf, puts and - implementation of __putchar and __getchar using RTT in SES. - To use RTT for printf output, include this file in your - application. ----------------------------------------------------------------------- -*/ -#include "SEGGER_RTT.h" -#include "__libc.h" -#include -#include - -int printf(const char *fmt,...) { - char buffer[128]; - va_list args; - va_start (args, fmt); - int n = vsnprintf(buffer, sizeof(buffer), fmt, args); - SEGGER_RTT_Write(0, buffer, n); - va_end(args); - return n; -} - -int puts(const char *s) { - return SEGGER_RTT_WriteString(0, s); -} - -int __putchar(int x, __printf_tag_ptr ctx) { - (void)ctx; - SEGGER_RTT_Write(0, (char *)&x, 1); - return x; -} - -int __getchar() { - return SEGGER_RTT_WaitKey(); -} - -/****** End Of File *************************************************/ diff --git a/examples/device/nrf52840/segger/nrf52840.emProject b/examples/device/nrf52840/segger/nrf52840.emProject index 8775d1bca..5851c33d6 100644 --- a/examples/device/nrf52840/segger/nrf52840.emProject +++ b/examples/device/nrf52840/segger/nrf52840.emProject @@ -32,12 +32,6 @@ target_reset_script="Reset();" target_script_file="$(ProjectDir)/nRF_Target.js" target_trace_initialize_script="EnableTrace("$(TraceInterfaceType)")" /> - - - - - - @@ -61,6 +55,12 @@ + + + + + + diff --git a/examples/device/nrf52840/src/main.c b/examples/device/nrf52840/src/main.c index 58ac1ad21..11b73ebf9 100644 --- a/examples/device/nrf52840/src/main.c +++ b/examples/device/nrf52840/src/main.c @@ -55,56 +55,51 @@ //--------------------------------------------------------------------+ void print_greeting(void); void led_blinking_task(void); -void virtual_com_task(void); -void usb_hid_task(void); - -/*------------- MAIN -------------*/ -int main(void) -{ - board_init(); - print_greeting(); - - tusb_init(); - - while (1) - { - tusb_task(); - - led_blinking_task(); - virtual_com_task(); - - usb_hid_task(); - } - - return 0; -} //--------------------------------------------------------------------+ // USB CDC //--------------------------------------------------------------------+ +#if CFG_TUD_CDC void virtual_com_task(void) { -#if CFG_TUD_CDC // connected and there are data available - if ( tud_mounted() && tud_cdc_available() ) + if ( tud_cdc_connected() ) { - uint8_t buf[64]; + if ( tud_cdc_available() ) + { + uint8_t buf[64]; + + // read and echo back + uint32_t count = tud_cdc_read(buf, sizeof(buf)); - // read and echo back - uint32_t count = tud_cdc_read(buf, sizeof(buf)); + tud_cdc_write(buf, count); + } - tud_cdc_write(buf, count); tud_cdc_write_flush(); } -#endif } +void tud_cdc_line_state_cb(uint8_t itf, bool dtr, bool rts) +{ + (void) itf; + + // connected + if ( dtr && rts ) + { + // print greeting + tud_cdc_write_str("tinyusb usb cdc\n"); + } +} +#else +#define virtual_com_task() +#endif + //--------------------------------------------------------------------+ // USB HID //--------------------------------------------------------------------+ +#if CFG_TUD_HID void usb_hid_task(void) { -#if CFG_TUD_HID // Poll every 10ms static tu_timeout_t tm = { .start = 0, .interval = 10 }; @@ -144,10 +139,8 @@ void usb_hid_task(void) if ( btn & 0x04 ) tud_hid_mouse_move( 0 , -DELTA); // up if ( btn & 0x08 ) tud_hid_mouse_move( 0 , DELTA); // down } -#endif } -#if CFG_TUD_HID uint16_t tud_hid_generic_get_report_cb(uint8_t report_id, hid_report_type_t report_type, uint8_t* buffer, uint16_t reqlen) { // TODO not Implemented @@ -158,8 +151,32 @@ void tud_hid_generic_set_report_cb(uint8_t report_id, hid_report_type_t report_t { // TODO not Implemented } + +#else +#define usb_hid_task() #endif + +/*------------- MAIN -------------*/ +int main(void) +{ + board_init(); + print_greeting(); + + tusb_init(); + + while (1) + { + tusb_task(); + + led_blinking_task(); + virtual_com_task(); + usb_hid_task(); + } + + return 0; +} + //--------------------------------------------------------------------+ // tinyusb callbacks //--------------------------------------------------------------------+ diff --git a/examples/device/nrf52840/src/segger_rtt/SEGGER_RTT.c b/examples/device/nrf52840/src/segger_rtt/SEGGER_RTT.c new file mode 100644 index 000000000..aee5bd21e --- /dev/null +++ b/examples/device/nrf52840/src/segger_rtt/SEGGER_RTT.c @@ -0,0 +1,1329 @@ +/********************************************************************* +* SEGGER MICROCONTROLLER GmbH & Co. KG * +* Solutions for real time microcontroller applications * +********************************************************************** +* * +* (c) 2014 - 2016 SEGGER Microcontroller GmbH & Co. KG * +* * +* www.segger.com Support: support@segger.com * +* * +********************************************************************** +* * +* SEGGER RTT * Real Time Transfer for embedded targets * +* * +********************************************************************** +* * +* All rights reserved. * +* * +* * This software may in its unmodified form be freely redistributed * +* in source form. * +* * The source code may be modified, provided the source code * +* retains the above copyright notice, this list of conditions and * +* the following disclaimer. * +* * Modified versions of this software in source or linkable form * +* may not be distributed without prior consent of SEGGER. * +* * This software may only be used for communication with SEGGER * +* J-Link debug probes. * +* * +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * +* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * +* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * +* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * +* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR * +* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * +* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * +* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * +* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * +* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * +* DAMAGE. * +* * +********************************************************************** +* * +* RTT version: 5.12e * +* * +********************************************************************** +---------------------------END-OF-HEADER------------------------------ +File : SEGGER_RTT.c +Purpose : Implementation of SEGGER real-time transfer (RTT) which + allows real-time communication on targets which support + debugger memory accesses while the CPU is running. + +Additional information: + Type "int" is assumed to be 32-bits in size + H->T Host to target communication + T->H Target to host communication + + RTT channel 0 is always present and reserved for Terminal usage. + Name is fixed to "Terminal" + + Effective buffer size: SizeOfBuffer - 1 + + WrOff == RdOff: Buffer is empty + WrOff == (RdOff - 1): Buffer is full + WrOff > RdOff: Free space includes wrap-around + WrOff < RdOff: Used space includes wrap-around + (WrOff == (SizeOfBuffer - 1)) && (RdOff == 0): + Buffer full and wrap-around after next byte + + +---------------------------------------------------------------------- +*/ + +#include "SEGGER_RTT.h" + +#include // for memcpy + +/********************************************************************* +* +* Configuration, default values +* +********************************************************************** +*/ + +#ifndef BUFFER_SIZE_UP + #define BUFFER_SIZE_UP 1024 // Size of the buffer for terminal output of target, up to host +#endif + +#ifndef BUFFER_SIZE_DOWN + #define BUFFER_SIZE_DOWN 16 // Size of the buffer for terminal input to target from host (Usually keyboard input) +#endif + +#ifndef SEGGER_RTT_MAX_NUM_UP_BUFFERS + #define SEGGER_RTT_MAX_NUM_UP_BUFFERS 2 // Number of up-buffers (T->H) available on this target +#endif + +#ifndef SEGGER_RTT_MAX_NUM_DOWN_BUFFERS + #define SEGGER_RTT_MAX_NUM_DOWN_BUFFERS 2 // Number of down-buffers (H->T) available on this target +#endif + +#ifndef SEGGER_RTT_BUFFER_SECTION + #if defined SEGGER_RTT_SECTION + #define SEGGER_RTT_BUFFER_SECTION SEGGER_RTT_SECTION + #endif +#endif + +#ifndef SEGGER_RTT_MODE_DEFAULT + #define SEGGER_RTT_MODE_DEFAULT SEGGER_RTT_MODE_NO_BLOCK_SKIP +#endif + +#ifndef SEGGER_RTT_LOCK + #define SEGGER_RTT_LOCK() +#endif + +#ifndef SEGGER_RTT_UNLOCK + #define SEGGER_RTT_UNLOCK() +#endif + +#ifndef STRLEN + #define STRLEN(a) strlen((a)) +#endif + +#ifndef MEMCPY + #define MEMCPY(pDest, pSrc, NumBytes) memcpy((pDest), (pSrc), (NumBytes)) +#endif + +#ifndef MIN + #define MIN(a, b) (((a) < (b)) ? (a) : (b)) +#endif + +#ifndef MAX + #define MAX(a, b) (((a) > (b)) ? (a) : (b)) +#endif +// +// For some environments, NULL may not be defined until certain headers are included +// +#ifndef NULL + #define NULL 0 +#endif + +/********************************************************************* +* +* Static const data +* +********************************************************************** +*/ + +static unsigned char _aTerminalId[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; + +/********************************************************************* +* +* Static data +* +********************************************************************** +*/ +// +// RTT Control Block and allocate buffers for channel 0 +// +#ifdef SEGGER_RTT_SECTION + #if (defined __GNUC__) + __attribute__ ((section (SEGGER_RTT_SECTION))) SEGGER_RTT_CB _SEGGER_RTT; + #elif (defined __ICCARM__) || (defined __ICCRX__) + #pragma location=SEGGER_RTT_SECTION + SEGGER_RTT_CB _SEGGER_RTT; + #elif (defined __CC_ARM__) + __attribute__ ((section (SEGGER_RTT_SECTION), zero_init)) SEGGER_RTT_CB _SEGGER_RTT; + #else + SEGGER_RTT_CB _SEGGER_RTT; + #endif +#else + SEGGER_RTT_CB _SEGGER_RTT; +#endif + +#ifdef SEGGER_RTT_BUFFER_SECTION + #if (defined __GNUC__) + __attribute__ ((section (SEGGER_RTT_BUFFER_SECTION))) static char _acUpBuffer [BUFFER_SIZE_UP]; + __attribute__ ((section (SEGGER_RTT_BUFFER_SECTION))) static char _acDownBuffer[BUFFER_SIZE_DOWN]; + #elif (defined __ICCARM__) || (defined __ICCRX__) + #pragma location=SEGGER_RTT_BUFFER_SECTION + static char _acUpBuffer [BUFFER_SIZE_UP]; + #pragma location=SEGGER_RTT_BUFFER_SECTION + static char _acDownBuffer[BUFFER_SIZE_DOWN]; + #elif (defined __CC_ARM__) + __attribute__ ((section (SEGGER_RTT_BUFFER_SECTION), zero_init)) static char _acUpBuffer [BUFFER_SIZE_UP]; + __attribute__ ((section (SEGGER_RTT_BUFFER_SECTION), zero_init)) static char _acDownBuffer[BUFFER_SIZE_DOWN]; + #else + static char _acUpBuffer [BUFFER_SIZE_UP]; + static char _acDownBuffer[BUFFER_SIZE_DOWN]; + #endif +#else + static char _acUpBuffer [BUFFER_SIZE_UP]; + static char _acDownBuffer[BUFFER_SIZE_DOWN]; +#endif + +static char _ActiveTerminal; + +/********************************************************************* +* +* Static functions +* +********************************************************************** +*/ + +/********************************************************************* +* +* _DoInit() +* +* Function description +* Initializes the control block an buffers. +* May only be called via INIT() to avoid overriding settings. +* +*/ +#define INIT() do { \ + if (_SEGGER_RTT.acID[0] == '\0') { _DoInit(); } \ + } while (0) +static void _DoInit(void) { + SEGGER_RTT_CB* p; + // + // Initialize control block + // + p = &_SEGGER_RTT; + p->MaxNumUpBuffers = SEGGER_RTT_MAX_NUM_UP_BUFFERS; + p->MaxNumDownBuffers = SEGGER_RTT_MAX_NUM_DOWN_BUFFERS; + // + // Initialize up buffer 0 + // + p->aUp[0].sName = "Terminal"; + p->aUp[0].pBuffer = _acUpBuffer; + p->aUp[0].SizeOfBuffer = sizeof(_acUpBuffer); + p->aUp[0].RdOff = 0u; + p->aUp[0].WrOff = 0u; + p->aUp[0].Flags = SEGGER_RTT_MODE_DEFAULT; + // + // Initialize down buffer 0 + // + p->aDown[0].sName = "Terminal"; + p->aDown[0].pBuffer = _acDownBuffer; + p->aDown[0].SizeOfBuffer = sizeof(_acDownBuffer); + p->aDown[0].RdOff = 0u; + p->aDown[0].WrOff = 0u; + p->aDown[0].Flags = SEGGER_RTT_MODE_DEFAULT; + // + // Finish initialization of the control block. + // Copy Id string in three steps to make sure "SEGGER RTT" is not found + // in initializer memory (usually flash) by J-Link + // + strcpy(&p->acID[7], "RTT"); + strcpy(&p->acID[0], "SEGGER"); + p->acID[6] = ' '; +} + +/********************************************************************* +* +* _WriteBlocking() +* +* Function description +* Stores a specified number of characters in SEGGER RTT ring buffer +* and updates the associated write pointer which is periodically +* read by the host. +* The caller is responsible for managing the write chunk sizes as +* _WriteBlocking() will block until all data has been posted successfully. +* +* Parameters +* pRing Ring buffer to post to. +* pBuffer Pointer to character array. Does not need to point to a \0 terminated string. +* NumBytes Number of bytes to be stored in the SEGGER RTT control block. +* +* Return value +* >= 0 - Number of bytes written into buffer. +*/ +static unsigned _WriteBlocking(SEGGER_RTT_BUFFER_UP* pRing, const char* pBuffer, unsigned NumBytes) { + unsigned NumBytesToWrite; + unsigned NumBytesWritten; + unsigned RdOff; + unsigned WrOff; + // + // Write data to buffer and handle wrap-around if necessary + // + NumBytesWritten = 0u; + WrOff = pRing->WrOff; + do { + RdOff = pRing->RdOff; // May be changed by host (debug probe) in the meantime + if (RdOff > WrOff) { + NumBytesToWrite = RdOff - WrOff - 1u; + } else { + NumBytesToWrite = pRing->SizeOfBuffer - (WrOff - RdOff + 1u); + } + NumBytesToWrite = MIN(NumBytesToWrite, (pRing->SizeOfBuffer - WrOff)); // Number of bytes that can be written until buffer wrap-around + NumBytesToWrite = MIN(NumBytesToWrite, NumBytes); + memcpy(pRing->pBuffer + WrOff, pBuffer, NumBytesToWrite); + NumBytesWritten += NumBytesToWrite; + pBuffer += NumBytesToWrite; + NumBytes -= NumBytesToWrite; + WrOff += NumBytesToWrite; + if (WrOff == pRing->SizeOfBuffer) { + WrOff = 0u; + } + pRing->WrOff = WrOff; + } while (NumBytes); + // + return NumBytesWritten; +} + +/********************************************************************* +* +* _WriteNoCheck() +* +* Function description +* Stores a specified number of characters in SEGGER RTT ring buffer +* and updates the associated write pointer which is periodically +* read by the host. +* It is callers responsibility to make sure data actually fits in buffer. +* +* Parameters +* pRing Ring buffer to post to. +* pBuffer Pointer to character array. Does not need to point to a \0 terminated string. +* NumBytes Number of bytes to be stored in the SEGGER RTT control block. +* +* Notes +* (1) If there might not be enough space in the "Up"-buffer, call _WriteBlocking +*/ +static void _WriteNoCheck(SEGGER_RTT_BUFFER_UP* pRing, const char* pData, unsigned NumBytes) { + unsigned NumBytesAtOnce; + unsigned WrOff; + unsigned Rem; + + WrOff = pRing->WrOff; + Rem = pRing->SizeOfBuffer - WrOff; + if (Rem > NumBytes) { + // + // All data fits before wrap around + // + memcpy(pRing->pBuffer + WrOff, pData, NumBytes); + pRing->WrOff = WrOff + NumBytes; + } else { + // + // We reach the end of the buffer, so need to wrap around + // + NumBytesAtOnce = Rem; + memcpy(pRing->pBuffer + WrOff, pData, NumBytesAtOnce); + NumBytesAtOnce = NumBytes - Rem; + memcpy(pRing->pBuffer, pData + Rem, NumBytesAtOnce); + pRing->WrOff = NumBytesAtOnce; + } +} + +/********************************************************************* +* +* _PostTerminalSwitch() +* +* Function description +* Switch terminal to the given terminal ID. It is the caller's +* responsibility to ensure the terminal ID is correct and there is +* enough space in the buffer for this to complete successfully. +* +* Parameters +* pRing Ring buffer to post to. +* TerminalId Terminal ID to switch to. +*/ +static void _PostTerminalSwitch(SEGGER_RTT_BUFFER_UP* pRing, unsigned char TerminalId) { + char ac[2]; + + ac[0] = 0xFFu; + ac[1] = _aTerminalId[TerminalId]; // Caller made already sure that TerminalId does not exceed our terminal limit + _WriteBlocking(pRing, ac, 2u); +} + +/********************************************************************* +* +* _GetAvailWriteSpace() +* +* Function description +* Returns the number of bytes that can be written to the ring +* buffer without blocking. +* +* Parameters +* pRing Ring buffer to check. +* +* Return value +* Number of bytes that are free in the buffer. +*/ +static unsigned _GetAvailWriteSpace(SEGGER_RTT_BUFFER_UP* pRing) { + unsigned RdOff; + unsigned WrOff; + unsigned r; + // + // Avoid warnings regarding volatile access order. It's not a problem + // in this case, but dampen compiler enthusiasm. + // + RdOff = pRing->RdOff; + WrOff = pRing->WrOff; + if (RdOff <= WrOff) { + r = pRing->SizeOfBuffer - 1u - WrOff + RdOff; + } else { + r = RdOff - WrOff - 1u; + } + return r; +} + +/********************************************************************* +* +* Public code +* +********************************************************************** +*/ +/********************************************************************* +* +* SEGGER_RTT_ReadNoLock() +* +* Function description +* Reads characters from SEGGER real-time-terminal control block +* which have been previously stored by the host. +* Do not lock against interrupts and multiple access. +* +* Parameters +* BufferIndex Index of Down-buffer to be used (e.g. 0 for "Terminal"). +* pBuffer Pointer to buffer provided by target application, to copy characters from RTT-down-buffer to. +* BufferSize Size of the target application buffer. +* +* Return value +* Number of bytes that have been read. +*/ +unsigned SEGGER_RTT_ReadNoLock(unsigned BufferIndex, void* pData, unsigned BufferSize) { + unsigned NumBytesRem; + unsigned NumBytesRead; + unsigned RdOff; + unsigned WrOff; + unsigned char* pBuffer; + SEGGER_RTT_BUFFER_DOWN* pRing; + // + INIT(); + pRing = &_SEGGER_RTT.aDown[BufferIndex]; + pBuffer = (unsigned char*)pData; + RdOff = pRing->RdOff; + WrOff = pRing->WrOff; + NumBytesRead = 0u; + // + // Read from current read position to wrap-around of buffer, first + // + if (RdOff > WrOff) { + NumBytesRem = pRing->SizeOfBuffer - RdOff; + NumBytesRem = MIN(NumBytesRem, BufferSize); + memcpy(pBuffer, pRing->pBuffer + RdOff, NumBytesRem); + NumBytesRead += NumBytesRem; + pBuffer += NumBytesRem; + BufferSize -= NumBytesRem; + RdOff += NumBytesRem; + // + // Handle wrap-around of buffer + // + if (RdOff == pRing->SizeOfBuffer) { + RdOff = 0u; + } + } + // + // Read remaining items of buffer + // + NumBytesRem = WrOff - RdOff; + NumBytesRem = MIN(NumBytesRem, BufferSize); + if (NumBytesRem > 0u) { + memcpy(pBuffer, pRing->pBuffer + RdOff, NumBytesRem); + NumBytesRead += NumBytesRem; + pBuffer += NumBytesRem; + BufferSize -= NumBytesRem; + RdOff += NumBytesRem; + } + if (NumBytesRead) { + pRing->RdOff = RdOff; + } + // + return NumBytesRead; +} + +/********************************************************************* +* +* SEGGER_RTT_Read +* +* Function description +* Reads characters from SEGGER real-time-terminal control block +* which have been previously stored by the host. +* +* Parameters +* BufferIndex Index of Down-buffer to be used (e.g. 0 for "Terminal"). +* pBuffer Pointer to buffer provided by target application, to copy characters from RTT-down-buffer to. +* BufferSize Size of the target application buffer. +* +* Return value +* Number of bytes that have been read. +*/ +unsigned SEGGER_RTT_Read(unsigned BufferIndex, void* pBuffer, unsigned BufferSize) { + unsigned NumBytesRead; + // + SEGGER_RTT_LOCK(); + // + // Call the non-locking read function + // + NumBytesRead = SEGGER_RTT_ReadNoLock(BufferIndex, pBuffer, BufferSize); + // + // Finish up. + // + SEGGER_RTT_UNLOCK(); + // + return NumBytesRead; +} + +/********************************************************************* +* +* SEGGER_RTT_WriteWithOverwriteNoLock +* +* Function description +* Stores a specified number of characters in SEGGER RTT +* control block. +* SEGGER_RTT_WriteWithOverwriteNoLock does not lock the application +* and overwrites data if the data does not fit into the buffer. +* +* Parameters +* BufferIndex Index of "Up"-buffer to be used (e.g. 0 for "Terminal"). +* pBuffer Pointer to character array. Does not need to point to a \0 terminated string. +* NumBytes Number of bytes to be stored in the SEGGER RTT control block. +* +* Notes +* (1) If there is not enough space in the "Up"-buffer, data is overwritten. +* (2) For performance reasons this function does not call Init() +* and may only be called after RTT has been initialized. +* Either by calling SEGGER_RTT_Init() or calling another RTT API function first. +* (3) Do not use SEGGER_RTT_WriteWithOverwriteNoLock if a J-Link +* connection reads RTT data. +*/ +void SEGGER_RTT_WriteWithOverwriteNoLock(unsigned BufferIndex, const void* pBuffer, unsigned NumBytes) { + const char* pData; + SEGGER_RTT_BUFFER_UP* pRing; + unsigned Avail; + + pData = (const char *)pBuffer; + // + // Get "to-host" ring buffer and copy some elements into local variables. + // + pRing = &_SEGGER_RTT.aUp[BufferIndex]; + // + // Check if we will overwrite data and need to adjust the RdOff. + // + if (pRing->WrOff == pRing->RdOff) { + Avail = pRing->SizeOfBuffer - 1u; + } else if ( pRing->WrOff < pRing->RdOff) { + Avail = pRing->RdOff - pRing->WrOff - 1u; + } else { + Avail = pRing->RdOff - pRing->WrOff - 1u + pRing->SizeOfBuffer; + } + if (NumBytes > Avail) { + pRing->RdOff += (NumBytes - Avail); + while (pRing->RdOff >= pRing->SizeOfBuffer) { + pRing->RdOff -= pRing->SizeOfBuffer; + } + } + // + // Write all data, no need to check the RdOff, but possibly handle multiple wrap-arounds + // + Avail = pRing->SizeOfBuffer - pRing->WrOff; + do { + if (Avail > NumBytes) { + // + // Last round + // +#if 1 // memcpy() is good for large amounts of data, but the overhead is too big for small amounts. Use a simple byte loop instead. + char* pDst; + pDst = pRing->pBuffer + pRing->WrOff; + pRing->WrOff += NumBytes; + do { + *pDst++ = *pData++; + } while (--NumBytes); +#else + memcpy(pRing->pBuffer + WrOff, pData, NumBytes); + pRing->WrOff += NumBytes; +#endif + break; //Alternatively: NumBytes = 0; + } else { + // + // Wrap-around necessary, write until wrap-around and reset WrOff + // + memcpy(pRing->pBuffer + pRing->WrOff, pData, Avail); + pData += Avail; + pRing->WrOff = 0; + NumBytes -= Avail; + Avail = (pRing->SizeOfBuffer - 1); + } + } while (NumBytes); +} + +/********************************************************************* +* +* SEGGER_RTT_WriteSkipNoLock +* +* Function description +* Stores a specified number of characters in SEGGER RTT +* control block which is then read by the host. +* SEGGER_RTT_WriteSkipNoLock does not lock the application and +* skips all data, if the data does not fit into the buffer. +* +* Parameters +* BufferIndex Index of "Up"-buffer to be used (e.g. 0 for "Terminal"). +* pBuffer Pointer to character array. Does not need to point to a \0 terminated string. +* NumBytes Number of bytes to be stored in the SEGGER RTT control block. +* +* Return value +* Number of bytes which have been stored in the "Up"-buffer. +* +* Notes +* (1) If there is not enough space in the "Up"-buffer, all data is dropped. +* (2) For performance reasons this function does not call Init() +* and may only be called after RTT has been initialized. +* Either by calling SEGGER_RTT_Init() or calling another RTT API function first. +*/ +unsigned SEGGER_RTT_WriteSkipNoLock(unsigned BufferIndex, const void* pBuffer, unsigned NumBytes) { + const char* pData; + SEGGER_RTT_BUFFER_UP* pRing; + unsigned Avail; + unsigned RdOff; + unsigned WrOff; + unsigned Rem; + + pData = (const char *)pBuffer; + // + // Get "to-host" ring buffer and copy some elements into local variables. + // + pRing = &_SEGGER_RTT.aUp[BufferIndex]; + RdOff = pRing->RdOff; + WrOff = pRing->WrOff; + // + // Handle the most common cases fastest. + // Which is: + // RdOff <= WrOff -> Space until wrap around is free. + // AND + // WrOff + NumBytes < SizeOfBuffer -> No Wrap around necessary. + // + // OR + // + // RdOff > WrOff -> Space until RdOff - 1 is free. + // AND + // WrOff + NumBytes < RdOff -> Data fits into buffer + // + if (RdOff <= WrOff) { + // + // Get space until WrOff will be at wrap around. + // + Avail = pRing->SizeOfBuffer - 1u - WrOff ; + if (Avail >= NumBytes) { +#if 1 // memcpy() is good for large amounts of data, but the overhead is too big for small amounts. Use a simple byte loop instead. + char* pDst; + pDst = pRing->pBuffer + WrOff; + WrOff += NumBytes; + do { + *pDst++ = *pData++; + } while (--NumBytes); + pRing->WrOff = WrOff + NumBytes; +#else + memcpy(pRing->pBuffer + WrOff, pData, NumBytes); + pRing->WrOff = WrOff + NumBytes; +#endif + return 1; + } + // + // If data did not fit into space until wrap around calculate complete space in buffer. + // + Avail += RdOff; + // + // If there is still no space for the whole of this output, don't bother. + // + if (Avail >= NumBytes) { + // + // OK, we have enough space in buffer. Copy in one or 2 chunks + // + Rem = pRing->SizeOfBuffer - WrOff; // Space until end of buffer + if (Rem > NumBytes) { + memcpy(pRing->pBuffer + WrOff, pData, NumBytes); + pRing->WrOff = WrOff + NumBytes; + } else { + // + // We reach the end of the buffer, so need to wrap around + // + memcpy(pRing->pBuffer + WrOff, pData, Rem); + memcpy(pRing->pBuffer, pData + Rem, NumBytes - Rem); + pRing->WrOff = NumBytes - Rem; + } + return 1; + } + } else { + Avail = RdOff - WrOff - 1u; + if (Avail >= NumBytes) { + memcpy(pRing->pBuffer + WrOff, pData, NumBytes); + pRing->WrOff = WrOff + NumBytes; + return 1; + } + } + // + // If we reach this point no data has been written + // + return 0; +} + +/********************************************************************* +* +* SEGGER_RTT_WriteNoLock +* +* Function description +* Stores a specified number of characters in SEGGER RTT +* control block which is then read by the host. +* SEGGER_RTT_WriteNoLock does not lock the application. +* +* Parameters +* BufferIndex Index of "Up"-buffer to be used (e.g. 0 for "Terminal"). +* pBuffer Pointer to character array. Does not need to point to a \0 terminated string. +* NumBytes Number of bytes to be stored in the SEGGER RTT control block. +* +* Return value +* Number of bytes which have been stored in the "Up"-buffer. +* +* Notes +* (1) If there is not enough space in the "Up"-buffer, remaining characters of pBuffer are dropped. +* (2) For performance reasons this function does not call Init() +* and may only be called after RTT has been initialized. +* Either by calling SEGGER_RTT_Init() or calling another RTT API function first. +*/ +unsigned SEGGER_RTT_WriteNoLock(unsigned BufferIndex, const void* pBuffer, unsigned NumBytes) { + unsigned Status; + unsigned Avail; + const char* pData; + SEGGER_RTT_BUFFER_UP* pRing; + + pData = (const char *)pBuffer; + // + // Get "to-host" ring buffer. + // + pRing = &_SEGGER_RTT.aUp[BufferIndex]; + // + // How we output depends upon the mode... + // + switch (pRing->Flags) { + case SEGGER_RTT_MODE_NO_BLOCK_SKIP: + // + // If we are in skip mode and there is no space for the whole + // of this output, don't bother. + // + Avail = _GetAvailWriteSpace(pRing); + if (Avail < NumBytes) { + Status = 0u; + } else { + Status = NumBytes; + _WriteNoCheck(pRing, pData, NumBytes); + } + break; + case SEGGER_RTT_MODE_NO_BLOCK_TRIM: + // + // If we are in trim mode, trim to what we can output without blocking. + // + Avail = _GetAvailWriteSpace(pRing); + Status = Avail < NumBytes ? Avail : NumBytes; + _WriteNoCheck(pRing, pData, Status); + break; + case SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL: + // + // If we are in blocking mode, output everything. + // + Status = _WriteBlocking(pRing, pData, NumBytes); + break; + default: + Status = 0u; + break; + } + // + // Finish up. + // + return Status; +} + +/********************************************************************* +* +* SEGGER_RTT_Write +* +* Function description +* Stores a specified number of characters in SEGGER RTT +* control block which is then read by the host. +* +* Parameters +* BufferIndex Index of "Up"-buffer to be used (e.g. 0 for "Terminal"). +* pBuffer Pointer to character array. Does not need to point to a \0 terminated string. +* NumBytes Number of bytes to be stored in the SEGGER RTT control block. +* +* Return value +* Number of bytes which have been stored in the "Up"-buffer. +* +* Notes +* (1) If there is not enough space in the "Up"-buffer, remaining characters of pBuffer are dropped. +*/ +unsigned SEGGER_RTT_Write(unsigned BufferIndex, const void* pBuffer, unsigned NumBytes) { + unsigned Status; + // + INIT(); + SEGGER_RTT_LOCK(); + // + // Call the non-locking write function + // + Status = SEGGER_RTT_WriteNoLock(BufferIndex, pBuffer, NumBytes); + // + // Finish up. + // + SEGGER_RTT_UNLOCK(); + // + return Status; +} + +/********************************************************************* +* +* SEGGER_RTT_WriteString +* +* Function description +* Stores string in SEGGER RTT control block. +* This data is read by the host. +* +* Parameters +* BufferIndex Index of "Up"-buffer to be used (e.g. 0 for "Terminal"). +* s Pointer to string. +* +* Return value +* Number of bytes which have been stored in the "Up"-buffer. +* +* Notes +* (1) If there is not enough space in the "Up"-buffer, depending on configuration, +* remaining characters may be dropped or RTT module waits until there is more space in the buffer. +* (2) String passed to this function has to be \0 terminated +* (3) \0 termination character is *not* stored in RTT buffer +*/ +unsigned SEGGER_RTT_WriteString(unsigned BufferIndex, const char* s) { + unsigned Len; + + Len = STRLEN(s); + return SEGGER_RTT_Write(BufferIndex, s, Len); +} + +/********************************************************************* +* +* SEGGER_RTT_GetKey +* +* Function description +* Reads one character from the SEGGER RTT buffer. +* Host has previously stored data there. +* +* Return value +* < 0 - No character available (buffer empty). +* >= 0 - Character which has been read. (Possible values: 0 - 255) +* +* Notes +* (1) This function is only specified for accesses to RTT buffer 0. +*/ +int SEGGER_RTT_GetKey(void) { + char c; + int r; + + r = (int)SEGGER_RTT_Read(0u, &c, 1u); + if (r == 1) { + r = (int)(unsigned char)c; + } else { + r = -1; + } + return r; +} + +/********************************************************************* +* +* SEGGER_RTT_WaitKey +* +* Function description +* Waits until at least one character is avaible in the SEGGER RTT buffer. +* Once a character is available, it is read and this function returns. +* +* Return value +* >=0 - Character which has been read. +* +* Notes +* (1) This function is only specified for accesses to RTT buffer 0 +* (2) This function is blocking if no character is present in RTT buffer +*/ +int SEGGER_RTT_WaitKey(void) { + int r; + + do { + r = SEGGER_RTT_GetKey(); + } while (r < 0); + return r; +} + +/********************************************************************* +* +* SEGGER_RTT_HasKey +* +* Function description +* Checks if at least one character for reading is available in the SEGGER RTT buffer. +* +* Return value +* == 0 - No characters are available to read. +* == 1 - At least one character is available. +* +* Notes +* (1) This function is only specified for accesses to RTT buffer 0 +*/ +int SEGGER_RTT_HasKey(void) { + unsigned RdOff; + int r; + + INIT(); + RdOff = _SEGGER_RTT.aDown[0].RdOff; + if (RdOff != _SEGGER_RTT.aDown[0].WrOff) { + r = 1; + } else { + r = 0; + } + return r; +} + +/********************************************************************* +* +* SEGGER_RTT_HasData +* +* Function description +* Check if there is data from the host in the given buffer. +* +* Return value: +* ==0: No data +* !=0: Data in buffer +* +*/ +unsigned SEGGER_RTT_HasData(unsigned BufferIndex) { + SEGGER_RTT_BUFFER_DOWN* pRing; + unsigned v; + + pRing = &_SEGGER_RTT.aDown[BufferIndex]; + v = pRing->WrOff; + return v - pRing->RdOff; +} + +/********************************************************************* +* +* SEGGER_RTT_AllocDownBuffer +* +* Function description +* Run-time configuration of the next down-buffer (H->T). +* The next buffer, which is not used yet is configured. +* This includes: Buffer address, size, name, flags, ... +* +* Parameters +* sName Pointer to a constant name string. +* pBuffer Pointer to a buffer to be used. +* BufferSize Size of the buffer. +* Flags Operating modes. Define behavior if buffer is full (not enough space for entire message). +* +* Return value +* >= 0 - O.K. Buffer Index +* < 0 - Error +*/ +int SEGGER_RTT_AllocDownBuffer(const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags) { + int BufferIndex; + + INIT(); + SEGGER_RTT_LOCK(); + BufferIndex = 0; + do { + if (_SEGGER_RTT.aDown[BufferIndex].pBuffer == NULL) { + break; + } + BufferIndex++; + } while (BufferIndex < _SEGGER_RTT.MaxNumDownBuffers); + if (BufferIndex < _SEGGER_RTT.MaxNumDownBuffers) { + _SEGGER_RTT.aDown[BufferIndex].sName = sName; + _SEGGER_RTT.aDown[BufferIndex].pBuffer = pBuffer; + _SEGGER_RTT.aDown[BufferIndex].SizeOfBuffer = BufferSize; + _SEGGER_RTT.aDown[BufferIndex].RdOff = 0u; + _SEGGER_RTT.aDown[BufferIndex].WrOff = 0u; + _SEGGER_RTT.aDown[BufferIndex].Flags = Flags; + } else { + BufferIndex = -1; + } + SEGGER_RTT_UNLOCK(); + return BufferIndex; +} + +/********************************************************************* +* +* SEGGER_RTT_AllocUpBuffer +* +* Function description +* Run-time configuration of the next up-buffer (T->H). +* The next buffer, which is not used yet is configured. +* This includes: Buffer address, size, name, flags, ... +* +* Parameters +* sName Pointer to a constant name string. +* pBuffer Pointer to a buffer to be used. +* BufferSize Size of the buffer. +* Flags Operating modes. Define behavior if buffer is full (not enough space for entire message). +* +* Return value +* >= 0 - O.K. Buffer Index +* < 0 - Error +*/ +int SEGGER_RTT_AllocUpBuffer(const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags) { + int BufferIndex; + + INIT(); + SEGGER_RTT_LOCK(); + BufferIndex = 0; + do { + if (_SEGGER_RTT.aUp[BufferIndex].pBuffer == NULL) { + break; + } + BufferIndex++; + } while (BufferIndex < _SEGGER_RTT.MaxNumUpBuffers); + if (BufferIndex < _SEGGER_RTT.MaxNumUpBuffers) { + _SEGGER_RTT.aUp[BufferIndex].sName = sName; + _SEGGER_RTT.aUp[BufferIndex].pBuffer = pBuffer; + _SEGGER_RTT.aUp[BufferIndex].SizeOfBuffer = BufferSize; + _SEGGER_RTT.aUp[BufferIndex].RdOff = 0u; + _SEGGER_RTT.aUp[BufferIndex].WrOff = 0u; + _SEGGER_RTT.aUp[BufferIndex].Flags = Flags; + } else { + BufferIndex = -1; + } + SEGGER_RTT_UNLOCK(); + return BufferIndex; +} + +/********************************************************************* +* +* SEGGER_RTT_ConfigUpBuffer +* +* Function description +* Run-time configuration of a specific up-buffer (T->H). +* Buffer to be configured is specified by index. +* This includes: Buffer address, size, name, flags, ... +* +* Parameters +* BufferIndex Index of the buffer to configure. +* sName Pointer to a constant name string. +* pBuffer Pointer to a buffer to be used. +* BufferSize Size of the buffer. +* Flags Operating modes. Define behavior if buffer is full (not enough space for entire message). +* +* Return value +* >= 0 - O.K. +* < 0 - Error +*/ +int SEGGER_RTT_ConfigUpBuffer(unsigned BufferIndex, const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags) { + int r; + + INIT(); + if (BufferIndex < (unsigned)_SEGGER_RTT.MaxNumUpBuffers) { + SEGGER_RTT_LOCK(); + if (BufferIndex > 0u) { + _SEGGER_RTT.aUp[BufferIndex].sName = sName; + _SEGGER_RTT.aUp[BufferIndex].pBuffer = pBuffer; + _SEGGER_RTT.aUp[BufferIndex].SizeOfBuffer = BufferSize; + _SEGGER_RTT.aUp[BufferIndex].RdOff = 0u; + _SEGGER_RTT.aUp[BufferIndex].WrOff = 0u; + } + _SEGGER_RTT.aUp[BufferIndex].Flags = Flags; + SEGGER_RTT_UNLOCK(); + r = 0; + } else { + r = -1; + } + return r; +} + +/********************************************************************* +* +* SEGGER_RTT_ConfigDownBuffer +* +* Function description +* Run-time configuration of a specific down-buffer (H->T). +* Buffer to be configured is specified by index. +* This includes: Buffer address, size, name, flags, ... +* +* Parameters +* BufferIndex Index of the buffer to configure. +* sName Pointer to a constant name string. +* pBuffer Pointer to a buffer to be used. +* BufferSize Size of the buffer. +* Flags Operating modes. Define behavior if buffer is full (not enough space for entire message). +* +* Return value +* >= 0 O.K. +* < 0 Error +*/ +int SEGGER_RTT_ConfigDownBuffer(unsigned BufferIndex, const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags) { + int r; + + INIT(); + if (BufferIndex < (unsigned)_SEGGER_RTT.MaxNumDownBuffers) { + SEGGER_RTT_LOCK(); + if (BufferIndex > 0u) { + _SEGGER_RTT.aDown[BufferIndex].sName = sName; + _SEGGER_RTT.aDown[BufferIndex].pBuffer = pBuffer; + _SEGGER_RTT.aDown[BufferIndex].SizeOfBuffer = BufferSize; + _SEGGER_RTT.aDown[BufferIndex].RdOff = 0u; + _SEGGER_RTT.aDown[BufferIndex].WrOff = 0u; + } + _SEGGER_RTT.aDown[BufferIndex].Flags = Flags; + SEGGER_RTT_UNLOCK(); + r = 0; + } else { + r = -1; + } + return r; +} + +/********************************************************************* +* +* SEGGER_RTT_SetNameUpBuffer +* +* Function description +* Run-time configuration of a specific up-buffer name (T->H). +* Buffer to be configured is specified by index. +* +* Parameters +* BufferIndex Index of the buffer to renamed. +* sName Pointer to a constant name string. +* +* Return value +* >= 0 O.K. +* < 0 Error +*/ +int SEGGER_RTT_SetNameUpBuffer(unsigned BufferIndex, const char* sName) { + int r; + + INIT(); + if (BufferIndex < (unsigned)_SEGGER_RTT.MaxNumUpBuffers) { + SEGGER_RTT_LOCK(); + _SEGGER_RTT.aUp[BufferIndex].sName = sName; + SEGGER_RTT_UNLOCK(); + r = 0; + } else { + r = -1; + } + return r; +} + +/********************************************************************* +* +* SEGGER_RTT_SetNameDownBuffer +* +* Function description +* Run-time configuration of a specific Down-buffer name (T->H). +* Buffer to be configured is specified by index. +* +* Parameters +* BufferIndex Index of the buffer to renamed. +* sName Pointer to a constant name string. +* +* Return value +* >= 0 O.K. +* < 0 Error +*/ +int SEGGER_RTT_SetNameDownBuffer(unsigned BufferIndex, const char* sName) { + int r; + + INIT(); + if (BufferIndex < (unsigned)_SEGGER_RTT.MaxNumDownBuffers) { + SEGGER_RTT_LOCK(); + _SEGGER_RTT.aDown[BufferIndex].sName = sName; + SEGGER_RTT_UNLOCK(); + r = 0; + } else { + r = -1; + } + return r; +} + +/********************************************************************* +* +* SEGGER_RTT_Init +* +* Function description +* Initializes the RTT Control Block. +* Should be used in RAM targets, at start of the application. +* +*/ +void SEGGER_RTT_Init (void) { + _DoInit(); +} + +/********************************************************************* +* +* SEGGER_RTT_SetTerminal +* +* Function description +* Sets the terminal to be used for output on channel 0. +* +* Parameters +* TerminalId Index of the terminal. +* +* Return value +* >= 0 O.K. +* < 0 Error (e.g. if RTT is configured for non-blocking mode and there was no space in the buffer to set the new terminal Id) +*/ +int SEGGER_RTT_SetTerminal (char TerminalId) { + char ac[2]; + SEGGER_RTT_BUFFER_UP* pRing; + unsigned Avail; + int r; + // + INIT(); + // + r = 0; + ac[0] = 0xFFU; + if ((unsigned char)TerminalId < (unsigned char)sizeof(_aTerminalId)) { // We only support a certain number of channels + ac[1] = _aTerminalId[(unsigned char)TerminalId]; + pRing = &_SEGGER_RTT.aUp[0]; // Buffer 0 is always reserved for terminal I/O, so we can use index 0 here, fixed + SEGGER_RTT_LOCK(); // Lock to make sure that no other task is writing into buffer, while we are and number of free bytes in buffer does not change downwards after checking and before writing + if ((pRing->Flags & SEGGER_RTT_MODE_MASK) == SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL) { + _ActiveTerminal = TerminalId; + _WriteBlocking(pRing, ac, 2u); + } else { // Skipping mode or trim mode? => We cannot trim this command so handling is the same for both modes + Avail = _GetAvailWriteSpace(pRing); + if (Avail >= 2) { + _ActiveTerminal = TerminalId; // Only change active terminal in case of success + _WriteNoCheck(pRing, ac, 2u); + } else { + r = -1; + } + } + SEGGER_RTT_UNLOCK(); + } else { + r = -1; + } + return r; +} + +/********************************************************************* +* +* SEGGER_RTT_TerminalOut +* +* Function description +* Writes a string to the given terminal +* without changing the terminal for channel 0. +* +* Parameters +* TerminalId Index of the terminal. +* s String to be printed on the terminal. +* +* Return value +* >= 0 - Number of bytes written. +* < 0 - Error. +* +*/ +int SEGGER_RTT_TerminalOut (char TerminalId, const char* s) { + int Status; + unsigned FragLen; + unsigned Avail; + SEGGER_RTT_BUFFER_UP* pRing; + // + INIT(); + // + // Validate terminal ID. + // + if (TerminalId < (char)sizeof(_aTerminalId)) { // We only support a certain number of channels + // + // Get "to-host" ring buffer. + // + pRing = &_SEGGER_RTT.aUp[0]; + // + // Need to be able to change terminal, write data, change back. + // Compute the fixed and variable sizes. + // + FragLen = strlen(s); + // + // How we output depends upon the mode... + // + SEGGER_RTT_LOCK(); + Avail = _GetAvailWriteSpace(pRing); + switch (pRing->Flags & SEGGER_RTT_MODE_MASK) { + case SEGGER_RTT_MODE_NO_BLOCK_SKIP: + // + // If we are in skip mode and there is no space for the whole + // of this output, don't bother switching terminals at all. + // + if (Avail < (FragLen + 4u)) { + Status = 0; + } else { + _PostTerminalSwitch(pRing, TerminalId); + Status = (int)_WriteBlocking(pRing, s, FragLen); + _PostTerminalSwitch(pRing, _ActiveTerminal); + } + break; + case SEGGER_RTT_MODE_NO_BLOCK_TRIM: + // + // If we are in trim mode and there is not enough space for everything, + // trim the output but always include the terminal switch. If no room + // for terminal switch, skip that totally. + // + if (Avail < 4u) { + Status = -1; + } else { + _PostTerminalSwitch(pRing, TerminalId); + Status = (int)_WriteBlocking(pRing, s, (FragLen < (Avail - 4u)) ? FragLen : (Avail - 4u)); + _PostTerminalSwitch(pRing, _ActiveTerminal); + } + break; + case SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL: + // + // If we are in blocking mode, output everything. + // + _PostTerminalSwitch(pRing, TerminalId); + Status = (int)_WriteBlocking(pRing, s, FragLen); + _PostTerminalSwitch(pRing, _ActiveTerminal); + break; + default: + Status = -1; + break; + } + // + // Finish up. + // + SEGGER_RTT_UNLOCK(); + } else { + Status = -1; + } + return Status; +} + + +/*************************** End of file ****************************/ diff --git a/examples/device/nrf52840/src/segger_rtt/SEGGER_RTT.h b/examples/device/nrf52840/src/segger_rtt/SEGGER_RTT.h new file mode 100644 index 000000000..d3cac44dd --- /dev/null +++ b/examples/device/nrf52840/src/segger_rtt/SEGGER_RTT.h @@ -0,0 +1,234 @@ +/********************************************************************* +* SEGGER MICROCONTROLLER GmbH & Co. KG * +* Solutions for real time microcontroller applications * +********************************************************************** +* * +* (c) 2014 - 2016 SEGGER Microcontroller GmbH & Co. KG * +* * +* www.segger.com Support: support@segger.com * +* * +********************************************************************** +* * +* SEGGER RTT * Real Time Transfer for embedded targets * +* * +********************************************************************** +* * +* All rights reserved. * +* * +* * This software may in its unmodified form be freely redistributed * +* in source form. * +* * The source code may be modified, provided the source code * +* retains the above copyright notice, this list of conditions and * +* the following disclaimer. * +* * Modified versions of this software in source or linkable form * +* may not be distributed without prior consent of SEGGER. * +* * This software may only be used for communication with SEGGER * +* J-Link debug probes. * +* * +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * +* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * +* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * +* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * +* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR * +* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * +* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * +* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * +* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * +* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * +* DAMAGE. * +* * +********************************************************************** +* * +* RTT version: 5.12e * +* * +********************************************************************** +---------------------------END-OF-HEADER------------------------------ +File : SEGGER_RTT.h +Purpose : Implementation of SEGGER real-time transfer which allows + real-time communication on targets which support debugger + memory accesses while the CPU is running. +---------------------------------------------------------------------- +*/ + +#ifndef SEGGER_RTT_H +#define SEGGER_RTT_H + +#include "SEGGER_RTT_Conf.h" + +/********************************************************************* +* +* Defines, fixed +* +********************************************************************** +*/ + +/********************************************************************* +* +* Types +* +********************************************************************** +*/ + +// +// Description for a circular buffer (also called "ring buffer") +// which is used as up-buffer (T->H) +// +typedef struct { + const char* sName; // Optional name. Standard names so far are: "Terminal", "SysView", "J-Scope_t4i4" + char* pBuffer; // Pointer to start of buffer + unsigned SizeOfBuffer; // Buffer size in bytes. Note that one byte is lost, as this implementation does not fill up the buffer in order to avoid the problem of being unable to distinguish between full and empty. + unsigned WrOff; // Position of next item to be written by either target. + volatile unsigned RdOff; // Position of next item to be read by host. Must be volatile since it may be modified by host. + unsigned Flags; // Contains configuration flags +} SEGGER_RTT_BUFFER_UP; + +// +// Description for a circular buffer (also called "ring buffer") +// which is used as down-buffer (H->T) +// +typedef struct { + const char* sName; // Optional name. Standard names so far are: "Terminal", "SysView", "J-Scope_t4i4" + char* pBuffer; // Pointer to start of buffer + unsigned SizeOfBuffer; // Buffer size in bytes. Note that one byte is lost, as this implementation does not fill up the buffer in order to avoid the problem of being unable to distinguish between full and empty. + volatile unsigned WrOff; // Position of next item to be written by host. Must be volatile since it may be modified by host. + unsigned RdOff; // Position of next item to be read by target (down-buffer). + unsigned Flags; // Contains configuration flags +} SEGGER_RTT_BUFFER_DOWN; + +// +// RTT control block which describes the number of buffers available +// as well as the configuration for each buffer +// +// +typedef struct { + char acID[16]; // Initialized to "SEGGER RTT" + int MaxNumUpBuffers; // Initialized to SEGGER_RTT_MAX_NUM_UP_BUFFERS (type. 2) + int MaxNumDownBuffers; // Initialized to SEGGER_RTT_MAX_NUM_DOWN_BUFFERS (type. 2) + SEGGER_RTT_BUFFER_UP aUp[SEGGER_RTT_MAX_NUM_UP_BUFFERS]; // Up buffers, transferring information up from target via debug probe to host + SEGGER_RTT_BUFFER_DOWN aDown[SEGGER_RTT_MAX_NUM_DOWN_BUFFERS]; // Down buffers, transferring information down from host via debug probe to target +} SEGGER_RTT_CB; + +/********************************************************************* +* +* Global data +* +********************************************************************** +*/ +extern SEGGER_RTT_CB _SEGGER_RTT; + +/********************************************************************* +* +* RTT API functions +* +********************************************************************** +*/ +#ifdef __cplusplus + extern "C" { +#endif +int SEGGER_RTT_AllocDownBuffer (const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags); +int SEGGER_RTT_AllocUpBuffer (const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags); +int SEGGER_RTT_ConfigUpBuffer (unsigned BufferIndex, const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags); +int SEGGER_RTT_ConfigDownBuffer (unsigned BufferIndex, const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags); +int SEGGER_RTT_GetKey (void); +unsigned SEGGER_RTT_HasData (unsigned BufferIndex); +int SEGGER_RTT_HasKey (void); +void SEGGER_RTT_Init (void); +unsigned SEGGER_RTT_Read (unsigned BufferIndex, void* pBuffer, unsigned BufferSize); +unsigned SEGGER_RTT_ReadNoLock (unsigned BufferIndex, void* pData, unsigned BufferSize); +int SEGGER_RTT_SetNameDownBuffer(unsigned BufferIndex, const char* sName); +int SEGGER_RTT_SetNameUpBuffer (unsigned BufferIndex, const char* sName); +int SEGGER_RTT_WaitKey (void); +unsigned SEGGER_RTT_Write (unsigned BufferIndex, const void* pBuffer, unsigned NumBytes); +unsigned SEGGER_RTT_WriteNoLock (unsigned BufferIndex, const void* pBuffer, unsigned NumBytes); +unsigned SEGGER_RTT_WriteSkipNoLock (unsigned BufferIndex, const void* pBuffer, unsigned NumBytes); +unsigned SEGGER_RTT_WriteString (unsigned BufferIndex, const char* s); +void SEGGER_RTT_WriteWithOverwriteNoLock(unsigned BufferIndex, const void* pBuffer, unsigned NumBytes); +// +// Function macro for performance optimization +// +#define SEGGER_RTT_HASDATA(n) (_SEGGER_RTT.aDown[n].WrOff - _SEGGER_RTT.aDown[n].RdOff) + +/********************************************************************* +* +* RTT "Terminal" API functions +* +********************************************************************** +*/ +int SEGGER_RTT_SetTerminal (char TerminalId); +int SEGGER_RTT_TerminalOut (char TerminalId, const char* s); + +/********************************************************************* +* +* RTT printf functions (require SEGGER_RTT_printf.c) +* +********************************************************************** +*/ +int SEGGER_RTT_printf(unsigned BufferIndex, const char * sFormat, ...); +#ifdef __cplusplus + } +#endif + +/********************************************************************* +* +* Defines +* +********************************************************************** +*/ + +// +// Operating modes. Define behavior if buffer is full (not enough space for entire message) +// +#define SEGGER_RTT_MODE_NO_BLOCK_SKIP (0U) // Skip. Do not block, output nothing. (Default) +#define SEGGER_RTT_MODE_NO_BLOCK_TRIM (1U) // Trim: Do not block, output as much as fits. +#define SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL (2U) // Block: Wait until there is space in the buffer. +#define SEGGER_RTT_MODE_MASK (3U) + +// +// Control sequences, based on ANSI. +// Can be used to control color, and clear the screen +// +#define RTT_CTRL_RESET "" // Reset to default colors +#define RTT_CTRL_CLEAR "" // Clear screen, reposition cursor to top left + +#define RTT_CTRL_TEXT_BLACK "" +#define RTT_CTRL_TEXT_RED "" +#define RTT_CTRL_TEXT_GREEN "" +#define RTT_CTRL_TEXT_YELLOW "" +#define RTT_CTRL_TEXT_BLUE "" +#define RTT_CTRL_TEXT_MAGENTA "" +#define RTT_CTRL_TEXT_CYAN "" +#define RTT_CTRL_TEXT_WHITE "" + +#define RTT_CTRL_TEXT_BRIGHT_BLACK "" +#define RTT_CTRL_TEXT_BRIGHT_RED "" +#define RTT_CTRL_TEXT_BRIGHT_GREEN "" +#define RTT_CTRL_TEXT_BRIGHT_YELLOW "" +#define RTT_CTRL_TEXT_BRIGHT_BLUE "" +#define RTT_CTRL_TEXT_BRIGHT_MAGENTA "" +#define RTT_CTRL_TEXT_BRIGHT_CYAN "" +#define RTT_CTRL_TEXT_BRIGHT_WHITE "" + +#define RTT_CTRL_BG_BLACK "" +#define RTT_CTRL_BG_RED "" +#define RTT_CTRL_BG_GREEN "" +#define RTT_CTRL_BG_YELLOW "" +#define RTT_CTRL_BG_BLUE "" +#define RTT_CTRL_BG_MAGENTA "" +#define RTT_CTRL_BG_CYAN "" +#define RTT_CTRL_BG_WHITE "" + +#define RTT_CTRL_BG_BRIGHT_BLACK "" +#define RTT_CTRL_BG_BRIGHT_RED "" +#define RTT_CTRL_BG_BRIGHT_GREEN "" +#define RTT_CTRL_BG_BRIGHT_YELLOW "" +#define RTT_CTRL_BG_BRIGHT_BLUE "" +#define RTT_CTRL_BG_BRIGHT_MAGENTA "" +#define RTT_CTRL_BG_BRIGHT_CYAN "" +#define RTT_CTRL_BG_BRIGHT_WHITE "" + + +#endif + +/*************************** End of file ****************************/ diff --git a/examples/device/nrf52840/src/segger_rtt/SEGGER_RTT_Conf.h b/examples/device/nrf52840/src/segger_rtt/SEGGER_RTT_Conf.h new file mode 100644 index 000000000..aef3b4053 --- /dev/null +++ b/examples/device/nrf52840/src/segger_rtt/SEGGER_RTT_Conf.h @@ -0,0 +1,242 @@ +/********************************************************************* +* SEGGER MICROCONTROLLER GmbH & Co. KG * +* Solutions for real time microcontroller applications * +********************************************************************** +* * +* (c) 2014 - 2016 SEGGER Microcontroller GmbH & Co. KG * +* * +* www.segger.com Support: support@segger.com * +* * +********************************************************************** +* * +* SEGGER RTT * Real Time Transfer for embedded targets * +* * +********************************************************************** +* * +* All rights reserved. * +* * +* * This software may in its unmodified form be freely redistributed * +* in source form. * +* * The source code may be modified, provided the source code * +* retains the above copyright notice, this list of conditions and * +* the following disclaimer. * +* * Modified versions of this software in source or linkable form * +* may not be distributed without prior consent of SEGGER. * +* * This software may only be used for communication with SEGGER * +* J-Link debug probes. * +* * +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * +* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * +* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * +* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * +* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR * +* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * +* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * +* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * +* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * +* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * +* DAMAGE. * +* * +********************************************************************** +* * +* RTT version: 5.12e * +* * +********************************************************************** +---------------------------------------------------------------------- +File : SEGGER_RTT_Conf.h +Purpose : Implementation of SEGGER real-time transfer (RTT) which + allows real-time communication on targets which support + debugger memory accesses while the CPU is running. +---------------------------END-OF-HEADER------------------------------ +*/ + +#ifndef SEGGER_RTT_CONF_H +#define SEGGER_RTT_CONF_H + +#ifdef __ICCARM__ + #include +#endif + +/********************************************************************* +* +* Defines, configurable +* +********************************************************************** +*/ + +#define SEGGER_RTT_MAX_NUM_UP_BUFFERS (2) // Max. number of up-buffers (T->H) available on this target (Default: 2) +#define SEGGER_RTT_MAX_NUM_DOWN_BUFFERS (2) // Max. number of down-buffers (H->T) available on this target (Default: 2) + +#define BUFFER_SIZE_UP (1024) // Size of the buffer for terminal output of target, up to host (Default: 1k) +#define BUFFER_SIZE_DOWN (16) // Size of the buffer for terminal input to target from host (Usually keyboard input) (Default: 16) + +#define SEGGER_RTT_PRINTF_BUFFER_SIZE (64u) // Size of buffer for RTT printf to bulk-send chars via RTT (Default: 64) + +#define SEGGER_RTT_MODE_DEFAULT SEGGER_RTT_MODE_NO_BLOCK_SKIP // Mode for pre-initialized terminal channel (buffer 0) + +// +// Target is not allowed to perform other RTT operations while string still has not been stored completely. +// Otherwise we would probably end up with a mixed string in the buffer. +// If using RTT from within interrupts, multiple tasks or multi processors, define the SEGGER_RTT_LOCK() and SEGGER_RTT_UNLOCK() function here. +// +// SEGGER_RTT_MAX_INTERRUPT_PRIORITY can be used in the sample lock routines on Cortex-M3/4. +// Make sure to mask all interrupts which can send RTT data, i.e. generate SystemView events, or cause task switches. +// When high-priority interrupts must not be masked while sending RTT data, SEGGER_RTT_MAX_INTERRUPT_PRIORITY needs to be adjusted accordingly. +// (Higher priority = lower priority number) +// Default value for embOS: 128u +// Default configuration in FreeRTOS: configMAX_SYSCALL_INTERRUPT_PRIORITY: ( configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY << (8 - configPRIO_BITS) ) +// In case of doubt mask all interrupts: 0u +// + +#define SEGGER_RTT_MAX_INTERRUPT_PRIORITY (0x20) // Interrupt priority to lock on SEGGER_RTT_LOCK on Cortex-M3/4 (Default: 0x20) + +/********************************************************************* +* +* RTT lock configuration for SEGGER Embedded Studio, +* Rowley CrossStudio and GCC +*/ +#if (defined __SES_ARM) || (defined __CROSSWORKS_ARM) || (defined __GNUC__) + #ifdef __ARM_ARCH_6M__ + #define SEGGER_RTT_LOCK() { \ + unsigned int LockState; \ + __asm volatile ("mrs %0, primask \n\t" \ + "mov r1, $1 \n\t" \ + "msr primask, r1 \n\t" \ + : "=r" (LockState) \ + : \ + : "r1" \ + ); + + #define SEGGER_RTT_UNLOCK() __asm volatile ("msr primask, %0 \n\t" \ + : \ + : "r" (LockState) \ + : \ + ); \ + } + + #elif (defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7EM__)) + #ifndef SEGGER_RTT_MAX_INTERRUPT_PRIORITY + #define SEGGER_RTT_MAX_INTERRUPT_PRIORITY (0x20) + #endif + #define SEGGER_RTT_LOCK() { \ + unsigned int LockState; \ + __asm volatile ("mrs %0, basepri \n\t" \ + "mov r1, %1 \n\t" \ + "msr basepri, r1 \n\t" \ + : "=r" (LockState) \ + : "i"(SEGGER_RTT_MAX_INTERRUPT_PRIORITY) \ + : "r1" \ + ); + + #define SEGGER_RTT_UNLOCK() __asm volatile ("msr basepri, %0 \n\t" \ + : \ + : "r" (LockState) \ + : \ + ); \ + } + + #elif defined(__ARM_ARCH_7A__) + #define SEGGER_RTT_LOCK() { \ + unsigned int LockState; \ + __asm volatile ("mrs r1, CPSR \n\t" \ + "mov %0, r1 \n\t" \ + "orr r1, r1, #0xC0 \n\t" \ + "msr CPSR_c, r1 \n\t" \ + : "=r" (LockState) \ + : \ + : "r1" \ + ); + + #define SEGGER_RTT_UNLOCK() __asm volatile ("mov r0, %0 \n\t" \ + "mrs r1, CPSR \n\t" \ + "bic r1, r1, #0xC0 \n\t" \ + "and r0, r0, #0xC0 \n\t" \ + "orr r1, r1, r0 \n\t" \ + "msr CPSR_c, r1 \n\t" \ + : \ + : "r" (LockState) \ + : "r0", "r1" \ + ); \ + } +#else + #define SEGGER_RTT_LOCK() + #define SEGGER_RTT_UNLOCK() + #endif +#endif + +/********************************************************************* +* +* RTT lock configuration for IAR EWARM +*/ +#ifdef __ICCARM__ + #if (defined (__ARM6M__) && (__CORE__ == __ARM6M__)) + #define SEGGER_RTT_LOCK() { \ + unsigned int LockState; \ + LockState = __get_PRIMASK(); \ + __set_PRIMASK(1); + + #define SEGGER_RTT_UNLOCK() __set_PRIMASK(LockState); \ + } + #elif ((defined (__ARM7EM__) && (__CORE__ == __ARM7EM__)) || (defined (__ARM7M__) && (__CORE__ == __ARM7M__))) + #ifndef SEGGER_RTT_MAX_INTERRUPT_PRIORITY + #define SEGGER_RTT_MAX_INTERRUPT_PRIORITY (0x20) + #endif + #define SEGGER_RTT_LOCK() { \ + unsigned int LockState; \ + LockState = __get_BASEPRI(); \ + __set_BASEPRI(SEGGER_RTT_MAX_INTERRUPT_PRIORITY); + + #define SEGGER_RTT_UNLOCK() __set_BASEPRI(LockState); \ + } + #endif +#endif + +/********************************************************************* +* +* RTT lock configuration for KEIL ARM +*/ +#ifdef __CC_ARM + #if (defined __TARGET_ARCH_6S_M) + #define SEGGER_RTT_LOCK() { \ + unsigned int LockState; \ + register unsigned char PRIMASK __asm( "primask"); \ + LockState = PRIMASK; \ + PRIMASK = 1u; \ + __schedule_barrier(); + + #define SEGGER_RTT_UNLOCK() PRIMASK = LockState; \ + __schedule_barrier(); \ + } + #elif (defined(__TARGET_ARCH_7_M) || defined(__TARGET_ARCH_7E_M)) + #ifndef SEGGER_RTT_MAX_INTERRUPT_PRIORITY + #define SEGGER_RTT_MAX_INTERRUPT_PRIORITY (0x20) + #endif + #define SEGGER_RTT_LOCK() { \ + unsigned int LockState; \ + register unsigned char BASEPRI __asm( "basepri"); \ + LockState = BASEPRI; \ + BASEPRI = SEGGER_RTT_MAX_INTERRUPT_PRIORITY; \ + __schedule_barrier(); + + #define SEGGER_RTT_UNLOCK() BASEPRI = LockState; \ + __schedule_barrier(); \ + } + #endif +#endif + +/********************************************************************* +* +* RTT lock configuration fallback +*/ +#ifndef SEGGER_RTT_LOCK + #define SEGGER_RTT_LOCK() // Lock RTT (nestable) (i.e. disable interrupts) +#endif + +#ifndef SEGGER_RTT_UNLOCK + #define SEGGER_RTT_UNLOCK() // Unlock RTT (nestable) (i.e. enable previous interrupt lock state) +#endif + +#endif +/*************************** End of file ****************************/ diff --git a/examples/device/nrf52840/src/segger_rtt/SEGGER_RTT_SES.c b/examples/device/nrf52840/src/segger_rtt/SEGGER_RTT_SES.c new file mode 100644 index 000000000..e6634147c --- /dev/null +++ b/examples/device/nrf52840/src/segger_rtt/SEGGER_RTT_SES.c @@ -0,0 +1,76 @@ +/********************************************************************* +* SEGGER MICROCONTROLLER GmbH & Co. KG * +* Solutions for real time microcontroller applications * +********************************************************************** +* * +* (c) 2014 - 2015 SEGGER Microcontroller GmbH & Co. KG * +* * +* www.segger.com Support: support@segger.com * +* * +********************************************************************** +* * +* All rights reserved. * +* * +* * This software may in its unmodified form be freely redistributed * +* in source form. * +* * The source code may be modified, provided the source code * +* retains the above copyright notice, this list of conditions and * +* the following disclaimer. * +* * Modified versions of this software in source or linkable form * +* may not be distributed without prior consent of SEGGER. * +* * This software may only be used for communication with SEGGER * +* J-Link debug probes. * +* * +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * +* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * +* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * +* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * +* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR * +* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * +* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * +* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * +* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * +* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * +* DAMAGE. * +* * +********************************************************************** +-------- END-OF-HEADER --------------------------------------------- +File : SEGGER_RTT_Syscalls_SES.c +Purpose : Reimplementation of printf, puts and + implementation of __putchar and __getchar using RTT in SES. + To use RTT for printf output, include this file in your + application. +---------------------------------------------------------------------- +*/ +#include "SEGGER_RTT.h" +#include "__libc.h" +#include +#include + +int printf(const char *fmt,...) { + char buffer[128]; + va_list args; + va_start (args, fmt); + int n = vsnprintf(buffer, sizeof(buffer), fmt, args); + SEGGER_RTT_Write(0, buffer, n); + va_end(args); + return n; +} + +int puts(const char *s) { + return SEGGER_RTT_WriteString(0, s); +} + +int __putchar(int x, __printf_tag_ptr ctx) { + (void)ctx; + SEGGER_RTT_Write(0, (char *)&x, 1); + return x; +} + +int __getchar() { + return SEGGER_RTT_WaitKey(); +} + +/****** End Of File *************************************************/ diff --git a/examples/device/nrf52840_freertos/segger/SEGGER_RTT.c b/examples/device/nrf52840_freertos/segger/SEGGER_RTT.c deleted file mode 100644 index aee5bd21e..000000000 --- a/examples/device/nrf52840_freertos/segger/SEGGER_RTT.c +++ /dev/null @@ -1,1329 +0,0 @@ -/********************************************************************* -* SEGGER MICROCONTROLLER GmbH & Co. KG * -* Solutions for real time microcontroller applications * -********************************************************************** -* * -* (c) 2014 - 2016 SEGGER Microcontroller GmbH & Co. KG * -* * -* www.segger.com Support: support@segger.com * -* * -********************************************************************** -* * -* SEGGER RTT * Real Time Transfer for embedded targets * -* * -********************************************************************** -* * -* All rights reserved. * -* * -* * This software may in its unmodified form be freely redistributed * -* in source form. * -* * The source code may be modified, provided the source code * -* retains the above copyright notice, this list of conditions and * -* the following disclaimer. * -* * Modified versions of this software in source or linkable form * -* may not be distributed without prior consent of SEGGER. * -* * This software may only be used for communication with SEGGER * -* J-Link debug probes. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * -* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * -* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * -* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * -* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * -* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * -* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * -* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * -* DAMAGE. * -* * -********************************************************************** -* * -* RTT version: 5.12e * -* * -********************************************************************** ----------------------------END-OF-HEADER------------------------------ -File : SEGGER_RTT.c -Purpose : Implementation of SEGGER real-time transfer (RTT) which - allows real-time communication on targets which support - debugger memory accesses while the CPU is running. - -Additional information: - Type "int" is assumed to be 32-bits in size - H->T Host to target communication - T->H Target to host communication - - RTT channel 0 is always present and reserved for Terminal usage. - Name is fixed to "Terminal" - - Effective buffer size: SizeOfBuffer - 1 - - WrOff == RdOff: Buffer is empty - WrOff == (RdOff - 1): Buffer is full - WrOff > RdOff: Free space includes wrap-around - WrOff < RdOff: Used space includes wrap-around - (WrOff == (SizeOfBuffer - 1)) && (RdOff == 0): - Buffer full and wrap-around after next byte - - ----------------------------------------------------------------------- -*/ - -#include "SEGGER_RTT.h" - -#include // for memcpy - -/********************************************************************* -* -* Configuration, default values -* -********************************************************************** -*/ - -#ifndef BUFFER_SIZE_UP - #define BUFFER_SIZE_UP 1024 // Size of the buffer for terminal output of target, up to host -#endif - -#ifndef BUFFER_SIZE_DOWN - #define BUFFER_SIZE_DOWN 16 // Size of the buffer for terminal input to target from host (Usually keyboard input) -#endif - -#ifndef SEGGER_RTT_MAX_NUM_UP_BUFFERS - #define SEGGER_RTT_MAX_NUM_UP_BUFFERS 2 // Number of up-buffers (T->H) available on this target -#endif - -#ifndef SEGGER_RTT_MAX_NUM_DOWN_BUFFERS - #define SEGGER_RTT_MAX_NUM_DOWN_BUFFERS 2 // Number of down-buffers (H->T) available on this target -#endif - -#ifndef SEGGER_RTT_BUFFER_SECTION - #if defined SEGGER_RTT_SECTION - #define SEGGER_RTT_BUFFER_SECTION SEGGER_RTT_SECTION - #endif -#endif - -#ifndef SEGGER_RTT_MODE_DEFAULT - #define SEGGER_RTT_MODE_DEFAULT SEGGER_RTT_MODE_NO_BLOCK_SKIP -#endif - -#ifndef SEGGER_RTT_LOCK - #define SEGGER_RTT_LOCK() -#endif - -#ifndef SEGGER_RTT_UNLOCK - #define SEGGER_RTT_UNLOCK() -#endif - -#ifndef STRLEN - #define STRLEN(a) strlen((a)) -#endif - -#ifndef MEMCPY - #define MEMCPY(pDest, pSrc, NumBytes) memcpy((pDest), (pSrc), (NumBytes)) -#endif - -#ifndef MIN - #define MIN(a, b) (((a) < (b)) ? (a) : (b)) -#endif - -#ifndef MAX - #define MAX(a, b) (((a) > (b)) ? (a) : (b)) -#endif -// -// For some environments, NULL may not be defined until certain headers are included -// -#ifndef NULL - #define NULL 0 -#endif - -/********************************************************************* -* -* Static const data -* -********************************************************************** -*/ - -static unsigned char _aTerminalId[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; - -/********************************************************************* -* -* Static data -* -********************************************************************** -*/ -// -// RTT Control Block and allocate buffers for channel 0 -// -#ifdef SEGGER_RTT_SECTION - #if (defined __GNUC__) - __attribute__ ((section (SEGGER_RTT_SECTION))) SEGGER_RTT_CB _SEGGER_RTT; - #elif (defined __ICCARM__) || (defined __ICCRX__) - #pragma location=SEGGER_RTT_SECTION - SEGGER_RTT_CB _SEGGER_RTT; - #elif (defined __CC_ARM__) - __attribute__ ((section (SEGGER_RTT_SECTION), zero_init)) SEGGER_RTT_CB _SEGGER_RTT; - #else - SEGGER_RTT_CB _SEGGER_RTT; - #endif -#else - SEGGER_RTT_CB _SEGGER_RTT; -#endif - -#ifdef SEGGER_RTT_BUFFER_SECTION - #if (defined __GNUC__) - __attribute__ ((section (SEGGER_RTT_BUFFER_SECTION))) static char _acUpBuffer [BUFFER_SIZE_UP]; - __attribute__ ((section (SEGGER_RTT_BUFFER_SECTION))) static char _acDownBuffer[BUFFER_SIZE_DOWN]; - #elif (defined __ICCARM__) || (defined __ICCRX__) - #pragma location=SEGGER_RTT_BUFFER_SECTION - static char _acUpBuffer [BUFFER_SIZE_UP]; - #pragma location=SEGGER_RTT_BUFFER_SECTION - static char _acDownBuffer[BUFFER_SIZE_DOWN]; - #elif (defined __CC_ARM__) - __attribute__ ((section (SEGGER_RTT_BUFFER_SECTION), zero_init)) static char _acUpBuffer [BUFFER_SIZE_UP]; - __attribute__ ((section (SEGGER_RTT_BUFFER_SECTION), zero_init)) static char _acDownBuffer[BUFFER_SIZE_DOWN]; - #else - static char _acUpBuffer [BUFFER_SIZE_UP]; - static char _acDownBuffer[BUFFER_SIZE_DOWN]; - #endif -#else - static char _acUpBuffer [BUFFER_SIZE_UP]; - static char _acDownBuffer[BUFFER_SIZE_DOWN]; -#endif - -static char _ActiveTerminal; - -/********************************************************************* -* -* Static functions -* -********************************************************************** -*/ - -/********************************************************************* -* -* _DoInit() -* -* Function description -* Initializes the control block an buffers. -* May only be called via INIT() to avoid overriding settings. -* -*/ -#define INIT() do { \ - if (_SEGGER_RTT.acID[0] == '\0') { _DoInit(); } \ - } while (0) -static void _DoInit(void) { - SEGGER_RTT_CB* p; - // - // Initialize control block - // - p = &_SEGGER_RTT; - p->MaxNumUpBuffers = SEGGER_RTT_MAX_NUM_UP_BUFFERS; - p->MaxNumDownBuffers = SEGGER_RTT_MAX_NUM_DOWN_BUFFERS; - // - // Initialize up buffer 0 - // - p->aUp[0].sName = "Terminal"; - p->aUp[0].pBuffer = _acUpBuffer; - p->aUp[0].SizeOfBuffer = sizeof(_acUpBuffer); - p->aUp[0].RdOff = 0u; - p->aUp[0].WrOff = 0u; - p->aUp[0].Flags = SEGGER_RTT_MODE_DEFAULT; - // - // Initialize down buffer 0 - // - p->aDown[0].sName = "Terminal"; - p->aDown[0].pBuffer = _acDownBuffer; - p->aDown[0].SizeOfBuffer = sizeof(_acDownBuffer); - p->aDown[0].RdOff = 0u; - p->aDown[0].WrOff = 0u; - p->aDown[0].Flags = SEGGER_RTT_MODE_DEFAULT; - // - // Finish initialization of the control block. - // Copy Id string in three steps to make sure "SEGGER RTT" is not found - // in initializer memory (usually flash) by J-Link - // - strcpy(&p->acID[7], "RTT"); - strcpy(&p->acID[0], "SEGGER"); - p->acID[6] = ' '; -} - -/********************************************************************* -* -* _WriteBlocking() -* -* Function description -* Stores a specified number of characters in SEGGER RTT ring buffer -* and updates the associated write pointer which is periodically -* read by the host. -* The caller is responsible for managing the write chunk sizes as -* _WriteBlocking() will block until all data has been posted successfully. -* -* Parameters -* pRing Ring buffer to post to. -* pBuffer Pointer to character array. Does not need to point to a \0 terminated string. -* NumBytes Number of bytes to be stored in the SEGGER RTT control block. -* -* Return value -* >= 0 - Number of bytes written into buffer. -*/ -static unsigned _WriteBlocking(SEGGER_RTT_BUFFER_UP* pRing, const char* pBuffer, unsigned NumBytes) { - unsigned NumBytesToWrite; - unsigned NumBytesWritten; - unsigned RdOff; - unsigned WrOff; - // - // Write data to buffer and handle wrap-around if necessary - // - NumBytesWritten = 0u; - WrOff = pRing->WrOff; - do { - RdOff = pRing->RdOff; // May be changed by host (debug probe) in the meantime - if (RdOff > WrOff) { - NumBytesToWrite = RdOff - WrOff - 1u; - } else { - NumBytesToWrite = pRing->SizeOfBuffer - (WrOff - RdOff + 1u); - } - NumBytesToWrite = MIN(NumBytesToWrite, (pRing->SizeOfBuffer - WrOff)); // Number of bytes that can be written until buffer wrap-around - NumBytesToWrite = MIN(NumBytesToWrite, NumBytes); - memcpy(pRing->pBuffer + WrOff, pBuffer, NumBytesToWrite); - NumBytesWritten += NumBytesToWrite; - pBuffer += NumBytesToWrite; - NumBytes -= NumBytesToWrite; - WrOff += NumBytesToWrite; - if (WrOff == pRing->SizeOfBuffer) { - WrOff = 0u; - } - pRing->WrOff = WrOff; - } while (NumBytes); - // - return NumBytesWritten; -} - -/********************************************************************* -* -* _WriteNoCheck() -* -* Function description -* Stores a specified number of characters in SEGGER RTT ring buffer -* and updates the associated write pointer which is periodically -* read by the host. -* It is callers responsibility to make sure data actually fits in buffer. -* -* Parameters -* pRing Ring buffer to post to. -* pBuffer Pointer to character array. Does not need to point to a \0 terminated string. -* NumBytes Number of bytes to be stored in the SEGGER RTT control block. -* -* Notes -* (1) If there might not be enough space in the "Up"-buffer, call _WriteBlocking -*/ -static void _WriteNoCheck(SEGGER_RTT_BUFFER_UP* pRing, const char* pData, unsigned NumBytes) { - unsigned NumBytesAtOnce; - unsigned WrOff; - unsigned Rem; - - WrOff = pRing->WrOff; - Rem = pRing->SizeOfBuffer - WrOff; - if (Rem > NumBytes) { - // - // All data fits before wrap around - // - memcpy(pRing->pBuffer + WrOff, pData, NumBytes); - pRing->WrOff = WrOff + NumBytes; - } else { - // - // We reach the end of the buffer, so need to wrap around - // - NumBytesAtOnce = Rem; - memcpy(pRing->pBuffer + WrOff, pData, NumBytesAtOnce); - NumBytesAtOnce = NumBytes - Rem; - memcpy(pRing->pBuffer, pData + Rem, NumBytesAtOnce); - pRing->WrOff = NumBytesAtOnce; - } -} - -/********************************************************************* -* -* _PostTerminalSwitch() -* -* Function description -* Switch terminal to the given terminal ID. It is the caller's -* responsibility to ensure the terminal ID is correct and there is -* enough space in the buffer for this to complete successfully. -* -* Parameters -* pRing Ring buffer to post to. -* TerminalId Terminal ID to switch to. -*/ -static void _PostTerminalSwitch(SEGGER_RTT_BUFFER_UP* pRing, unsigned char TerminalId) { - char ac[2]; - - ac[0] = 0xFFu; - ac[1] = _aTerminalId[TerminalId]; // Caller made already sure that TerminalId does not exceed our terminal limit - _WriteBlocking(pRing, ac, 2u); -} - -/********************************************************************* -* -* _GetAvailWriteSpace() -* -* Function description -* Returns the number of bytes that can be written to the ring -* buffer without blocking. -* -* Parameters -* pRing Ring buffer to check. -* -* Return value -* Number of bytes that are free in the buffer. -*/ -static unsigned _GetAvailWriteSpace(SEGGER_RTT_BUFFER_UP* pRing) { - unsigned RdOff; - unsigned WrOff; - unsigned r; - // - // Avoid warnings regarding volatile access order. It's not a problem - // in this case, but dampen compiler enthusiasm. - // - RdOff = pRing->RdOff; - WrOff = pRing->WrOff; - if (RdOff <= WrOff) { - r = pRing->SizeOfBuffer - 1u - WrOff + RdOff; - } else { - r = RdOff - WrOff - 1u; - } - return r; -} - -/********************************************************************* -* -* Public code -* -********************************************************************** -*/ -/********************************************************************* -* -* SEGGER_RTT_ReadNoLock() -* -* Function description -* Reads characters from SEGGER real-time-terminal control block -* which have been previously stored by the host. -* Do not lock against interrupts and multiple access. -* -* Parameters -* BufferIndex Index of Down-buffer to be used (e.g. 0 for "Terminal"). -* pBuffer Pointer to buffer provided by target application, to copy characters from RTT-down-buffer to. -* BufferSize Size of the target application buffer. -* -* Return value -* Number of bytes that have been read. -*/ -unsigned SEGGER_RTT_ReadNoLock(unsigned BufferIndex, void* pData, unsigned BufferSize) { - unsigned NumBytesRem; - unsigned NumBytesRead; - unsigned RdOff; - unsigned WrOff; - unsigned char* pBuffer; - SEGGER_RTT_BUFFER_DOWN* pRing; - // - INIT(); - pRing = &_SEGGER_RTT.aDown[BufferIndex]; - pBuffer = (unsigned char*)pData; - RdOff = pRing->RdOff; - WrOff = pRing->WrOff; - NumBytesRead = 0u; - // - // Read from current read position to wrap-around of buffer, first - // - if (RdOff > WrOff) { - NumBytesRem = pRing->SizeOfBuffer - RdOff; - NumBytesRem = MIN(NumBytesRem, BufferSize); - memcpy(pBuffer, pRing->pBuffer + RdOff, NumBytesRem); - NumBytesRead += NumBytesRem; - pBuffer += NumBytesRem; - BufferSize -= NumBytesRem; - RdOff += NumBytesRem; - // - // Handle wrap-around of buffer - // - if (RdOff == pRing->SizeOfBuffer) { - RdOff = 0u; - } - } - // - // Read remaining items of buffer - // - NumBytesRem = WrOff - RdOff; - NumBytesRem = MIN(NumBytesRem, BufferSize); - if (NumBytesRem > 0u) { - memcpy(pBuffer, pRing->pBuffer + RdOff, NumBytesRem); - NumBytesRead += NumBytesRem; - pBuffer += NumBytesRem; - BufferSize -= NumBytesRem; - RdOff += NumBytesRem; - } - if (NumBytesRead) { - pRing->RdOff = RdOff; - } - // - return NumBytesRead; -} - -/********************************************************************* -* -* SEGGER_RTT_Read -* -* Function description -* Reads characters from SEGGER real-time-terminal control block -* which have been previously stored by the host. -* -* Parameters -* BufferIndex Index of Down-buffer to be used (e.g. 0 for "Terminal"). -* pBuffer Pointer to buffer provided by target application, to copy characters from RTT-down-buffer to. -* BufferSize Size of the target application buffer. -* -* Return value -* Number of bytes that have been read. -*/ -unsigned SEGGER_RTT_Read(unsigned BufferIndex, void* pBuffer, unsigned BufferSize) { - unsigned NumBytesRead; - // - SEGGER_RTT_LOCK(); - // - // Call the non-locking read function - // - NumBytesRead = SEGGER_RTT_ReadNoLock(BufferIndex, pBuffer, BufferSize); - // - // Finish up. - // - SEGGER_RTT_UNLOCK(); - // - return NumBytesRead; -} - -/********************************************************************* -* -* SEGGER_RTT_WriteWithOverwriteNoLock -* -* Function description -* Stores a specified number of characters in SEGGER RTT -* control block. -* SEGGER_RTT_WriteWithOverwriteNoLock does not lock the application -* and overwrites data if the data does not fit into the buffer. -* -* Parameters -* BufferIndex Index of "Up"-buffer to be used (e.g. 0 for "Terminal"). -* pBuffer Pointer to character array. Does not need to point to a \0 terminated string. -* NumBytes Number of bytes to be stored in the SEGGER RTT control block. -* -* Notes -* (1) If there is not enough space in the "Up"-buffer, data is overwritten. -* (2) For performance reasons this function does not call Init() -* and may only be called after RTT has been initialized. -* Either by calling SEGGER_RTT_Init() or calling another RTT API function first. -* (3) Do not use SEGGER_RTT_WriteWithOverwriteNoLock if a J-Link -* connection reads RTT data. -*/ -void SEGGER_RTT_WriteWithOverwriteNoLock(unsigned BufferIndex, const void* pBuffer, unsigned NumBytes) { - const char* pData; - SEGGER_RTT_BUFFER_UP* pRing; - unsigned Avail; - - pData = (const char *)pBuffer; - // - // Get "to-host" ring buffer and copy some elements into local variables. - // - pRing = &_SEGGER_RTT.aUp[BufferIndex]; - // - // Check if we will overwrite data and need to adjust the RdOff. - // - if (pRing->WrOff == pRing->RdOff) { - Avail = pRing->SizeOfBuffer - 1u; - } else if ( pRing->WrOff < pRing->RdOff) { - Avail = pRing->RdOff - pRing->WrOff - 1u; - } else { - Avail = pRing->RdOff - pRing->WrOff - 1u + pRing->SizeOfBuffer; - } - if (NumBytes > Avail) { - pRing->RdOff += (NumBytes - Avail); - while (pRing->RdOff >= pRing->SizeOfBuffer) { - pRing->RdOff -= pRing->SizeOfBuffer; - } - } - // - // Write all data, no need to check the RdOff, but possibly handle multiple wrap-arounds - // - Avail = pRing->SizeOfBuffer - pRing->WrOff; - do { - if (Avail > NumBytes) { - // - // Last round - // -#if 1 // memcpy() is good for large amounts of data, but the overhead is too big for small amounts. Use a simple byte loop instead. - char* pDst; - pDst = pRing->pBuffer + pRing->WrOff; - pRing->WrOff += NumBytes; - do { - *pDst++ = *pData++; - } while (--NumBytes); -#else - memcpy(pRing->pBuffer + WrOff, pData, NumBytes); - pRing->WrOff += NumBytes; -#endif - break; //Alternatively: NumBytes = 0; - } else { - // - // Wrap-around necessary, write until wrap-around and reset WrOff - // - memcpy(pRing->pBuffer + pRing->WrOff, pData, Avail); - pData += Avail; - pRing->WrOff = 0; - NumBytes -= Avail; - Avail = (pRing->SizeOfBuffer - 1); - } - } while (NumBytes); -} - -/********************************************************************* -* -* SEGGER_RTT_WriteSkipNoLock -* -* Function description -* Stores a specified number of characters in SEGGER RTT -* control block which is then read by the host. -* SEGGER_RTT_WriteSkipNoLock does not lock the application and -* skips all data, if the data does not fit into the buffer. -* -* Parameters -* BufferIndex Index of "Up"-buffer to be used (e.g. 0 for "Terminal"). -* pBuffer Pointer to character array. Does not need to point to a \0 terminated string. -* NumBytes Number of bytes to be stored in the SEGGER RTT control block. -* -* Return value -* Number of bytes which have been stored in the "Up"-buffer. -* -* Notes -* (1) If there is not enough space in the "Up"-buffer, all data is dropped. -* (2) For performance reasons this function does not call Init() -* and may only be called after RTT has been initialized. -* Either by calling SEGGER_RTT_Init() or calling another RTT API function first. -*/ -unsigned SEGGER_RTT_WriteSkipNoLock(unsigned BufferIndex, const void* pBuffer, unsigned NumBytes) { - const char* pData; - SEGGER_RTT_BUFFER_UP* pRing; - unsigned Avail; - unsigned RdOff; - unsigned WrOff; - unsigned Rem; - - pData = (const char *)pBuffer; - // - // Get "to-host" ring buffer and copy some elements into local variables. - // - pRing = &_SEGGER_RTT.aUp[BufferIndex]; - RdOff = pRing->RdOff; - WrOff = pRing->WrOff; - // - // Handle the most common cases fastest. - // Which is: - // RdOff <= WrOff -> Space until wrap around is free. - // AND - // WrOff + NumBytes < SizeOfBuffer -> No Wrap around necessary. - // - // OR - // - // RdOff > WrOff -> Space until RdOff - 1 is free. - // AND - // WrOff + NumBytes < RdOff -> Data fits into buffer - // - if (RdOff <= WrOff) { - // - // Get space until WrOff will be at wrap around. - // - Avail = pRing->SizeOfBuffer - 1u - WrOff ; - if (Avail >= NumBytes) { -#if 1 // memcpy() is good for large amounts of data, but the overhead is too big for small amounts. Use a simple byte loop instead. - char* pDst; - pDst = pRing->pBuffer + WrOff; - WrOff += NumBytes; - do { - *pDst++ = *pData++; - } while (--NumBytes); - pRing->WrOff = WrOff + NumBytes; -#else - memcpy(pRing->pBuffer + WrOff, pData, NumBytes); - pRing->WrOff = WrOff + NumBytes; -#endif - return 1; - } - // - // If data did not fit into space until wrap around calculate complete space in buffer. - // - Avail += RdOff; - // - // If there is still no space for the whole of this output, don't bother. - // - if (Avail >= NumBytes) { - // - // OK, we have enough space in buffer. Copy in one or 2 chunks - // - Rem = pRing->SizeOfBuffer - WrOff; // Space until end of buffer - if (Rem > NumBytes) { - memcpy(pRing->pBuffer + WrOff, pData, NumBytes); - pRing->WrOff = WrOff + NumBytes; - } else { - // - // We reach the end of the buffer, so need to wrap around - // - memcpy(pRing->pBuffer + WrOff, pData, Rem); - memcpy(pRing->pBuffer, pData + Rem, NumBytes - Rem); - pRing->WrOff = NumBytes - Rem; - } - return 1; - } - } else { - Avail = RdOff - WrOff - 1u; - if (Avail >= NumBytes) { - memcpy(pRing->pBuffer + WrOff, pData, NumBytes); - pRing->WrOff = WrOff + NumBytes; - return 1; - } - } - // - // If we reach this point no data has been written - // - return 0; -} - -/********************************************************************* -* -* SEGGER_RTT_WriteNoLock -* -* Function description -* Stores a specified number of characters in SEGGER RTT -* control block which is then read by the host. -* SEGGER_RTT_WriteNoLock does not lock the application. -* -* Parameters -* BufferIndex Index of "Up"-buffer to be used (e.g. 0 for "Terminal"). -* pBuffer Pointer to character array. Does not need to point to a \0 terminated string. -* NumBytes Number of bytes to be stored in the SEGGER RTT control block. -* -* Return value -* Number of bytes which have been stored in the "Up"-buffer. -* -* Notes -* (1) If there is not enough space in the "Up"-buffer, remaining characters of pBuffer are dropped. -* (2) For performance reasons this function does not call Init() -* and may only be called after RTT has been initialized. -* Either by calling SEGGER_RTT_Init() or calling another RTT API function first. -*/ -unsigned SEGGER_RTT_WriteNoLock(unsigned BufferIndex, const void* pBuffer, unsigned NumBytes) { - unsigned Status; - unsigned Avail; - const char* pData; - SEGGER_RTT_BUFFER_UP* pRing; - - pData = (const char *)pBuffer; - // - // Get "to-host" ring buffer. - // - pRing = &_SEGGER_RTT.aUp[BufferIndex]; - // - // How we output depends upon the mode... - // - switch (pRing->Flags) { - case SEGGER_RTT_MODE_NO_BLOCK_SKIP: - // - // If we are in skip mode and there is no space for the whole - // of this output, don't bother. - // - Avail = _GetAvailWriteSpace(pRing); - if (Avail < NumBytes) { - Status = 0u; - } else { - Status = NumBytes; - _WriteNoCheck(pRing, pData, NumBytes); - } - break; - case SEGGER_RTT_MODE_NO_BLOCK_TRIM: - // - // If we are in trim mode, trim to what we can output without blocking. - // - Avail = _GetAvailWriteSpace(pRing); - Status = Avail < NumBytes ? Avail : NumBytes; - _WriteNoCheck(pRing, pData, Status); - break; - case SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL: - // - // If we are in blocking mode, output everything. - // - Status = _WriteBlocking(pRing, pData, NumBytes); - break; - default: - Status = 0u; - break; - } - // - // Finish up. - // - return Status; -} - -/********************************************************************* -* -* SEGGER_RTT_Write -* -* Function description -* Stores a specified number of characters in SEGGER RTT -* control block which is then read by the host. -* -* Parameters -* BufferIndex Index of "Up"-buffer to be used (e.g. 0 for "Terminal"). -* pBuffer Pointer to character array. Does not need to point to a \0 terminated string. -* NumBytes Number of bytes to be stored in the SEGGER RTT control block. -* -* Return value -* Number of bytes which have been stored in the "Up"-buffer. -* -* Notes -* (1) If there is not enough space in the "Up"-buffer, remaining characters of pBuffer are dropped. -*/ -unsigned SEGGER_RTT_Write(unsigned BufferIndex, const void* pBuffer, unsigned NumBytes) { - unsigned Status; - // - INIT(); - SEGGER_RTT_LOCK(); - // - // Call the non-locking write function - // - Status = SEGGER_RTT_WriteNoLock(BufferIndex, pBuffer, NumBytes); - // - // Finish up. - // - SEGGER_RTT_UNLOCK(); - // - return Status; -} - -/********************************************************************* -* -* SEGGER_RTT_WriteString -* -* Function description -* Stores string in SEGGER RTT control block. -* This data is read by the host. -* -* Parameters -* BufferIndex Index of "Up"-buffer to be used (e.g. 0 for "Terminal"). -* s Pointer to string. -* -* Return value -* Number of bytes which have been stored in the "Up"-buffer. -* -* Notes -* (1) If there is not enough space in the "Up"-buffer, depending on configuration, -* remaining characters may be dropped or RTT module waits until there is more space in the buffer. -* (2) String passed to this function has to be \0 terminated -* (3) \0 termination character is *not* stored in RTT buffer -*/ -unsigned SEGGER_RTT_WriteString(unsigned BufferIndex, const char* s) { - unsigned Len; - - Len = STRLEN(s); - return SEGGER_RTT_Write(BufferIndex, s, Len); -} - -/********************************************************************* -* -* SEGGER_RTT_GetKey -* -* Function description -* Reads one character from the SEGGER RTT buffer. -* Host has previously stored data there. -* -* Return value -* < 0 - No character available (buffer empty). -* >= 0 - Character which has been read. (Possible values: 0 - 255) -* -* Notes -* (1) This function is only specified for accesses to RTT buffer 0. -*/ -int SEGGER_RTT_GetKey(void) { - char c; - int r; - - r = (int)SEGGER_RTT_Read(0u, &c, 1u); - if (r == 1) { - r = (int)(unsigned char)c; - } else { - r = -1; - } - return r; -} - -/********************************************************************* -* -* SEGGER_RTT_WaitKey -* -* Function description -* Waits until at least one character is avaible in the SEGGER RTT buffer. -* Once a character is available, it is read and this function returns. -* -* Return value -* >=0 - Character which has been read. -* -* Notes -* (1) This function is only specified for accesses to RTT buffer 0 -* (2) This function is blocking if no character is present in RTT buffer -*/ -int SEGGER_RTT_WaitKey(void) { - int r; - - do { - r = SEGGER_RTT_GetKey(); - } while (r < 0); - return r; -} - -/********************************************************************* -* -* SEGGER_RTT_HasKey -* -* Function description -* Checks if at least one character for reading is available in the SEGGER RTT buffer. -* -* Return value -* == 0 - No characters are available to read. -* == 1 - At least one character is available. -* -* Notes -* (1) This function is only specified for accesses to RTT buffer 0 -*/ -int SEGGER_RTT_HasKey(void) { - unsigned RdOff; - int r; - - INIT(); - RdOff = _SEGGER_RTT.aDown[0].RdOff; - if (RdOff != _SEGGER_RTT.aDown[0].WrOff) { - r = 1; - } else { - r = 0; - } - return r; -} - -/********************************************************************* -* -* SEGGER_RTT_HasData -* -* Function description -* Check if there is data from the host in the given buffer. -* -* Return value: -* ==0: No data -* !=0: Data in buffer -* -*/ -unsigned SEGGER_RTT_HasData(unsigned BufferIndex) { - SEGGER_RTT_BUFFER_DOWN* pRing; - unsigned v; - - pRing = &_SEGGER_RTT.aDown[BufferIndex]; - v = pRing->WrOff; - return v - pRing->RdOff; -} - -/********************************************************************* -* -* SEGGER_RTT_AllocDownBuffer -* -* Function description -* Run-time configuration of the next down-buffer (H->T). -* The next buffer, which is not used yet is configured. -* This includes: Buffer address, size, name, flags, ... -* -* Parameters -* sName Pointer to a constant name string. -* pBuffer Pointer to a buffer to be used. -* BufferSize Size of the buffer. -* Flags Operating modes. Define behavior if buffer is full (not enough space for entire message). -* -* Return value -* >= 0 - O.K. Buffer Index -* < 0 - Error -*/ -int SEGGER_RTT_AllocDownBuffer(const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags) { - int BufferIndex; - - INIT(); - SEGGER_RTT_LOCK(); - BufferIndex = 0; - do { - if (_SEGGER_RTT.aDown[BufferIndex].pBuffer == NULL) { - break; - } - BufferIndex++; - } while (BufferIndex < _SEGGER_RTT.MaxNumDownBuffers); - if (BufferIndex < _SEGGER_RTT.MaxNumDownBuffers) { - _SEGGER_RTT.aDown[BufferIndex].sName = sName; - _SEGGER_RTT.aDown[BufferIndex].pBuffer = pBuffer; - _SEGGER_RTT.aDown[BufferIndex].SizeOfBuffer = BufferSize; - _SEGGER_RTT.aDown[BufferIndex].RdOff = 0u; - _SEGGER_RTT.aDown[BufferIndex].WrOff = 0u; - _SEGGER_RTT.aDown[BufferIndex].Flags = Flags; - } else { - BufferIndex = -1; - } - SEGGER_RTT_UNLOCK(); - return BufferIndex; -} - -/********************************************************************* -* -* SEGGER_RTT_AllocUpBuffer -* -* Function description -* Run-time configuration of the next up-buffer (T->H). -* The next buffer, which is not used yet is configured. -* This includes: Buffer address, size, name, flags, ... -* -* Parameters -* sName Pointer to a constant name string. -* pBuffer Pointer to a buffer to be used. -* BufferSize Size of the buffer. -* Flags Operating modes. Define behavior if buffer is full (not enough space for entire message). -* -* Return value -* >= 0 - O.K. Buffer Index -* < 0 - Error -*/ -int SEGGER_RTT_AllocUpBuffer(const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags) { - int BufferIndex; - - INIT(); - SEGGER_RTT_LOCK(); - BufferIndex = 0; - do { - if (_SEGGER_RTT.aUp[BufferIndex].pBuffer == NULL) { - break; - } - BufferIndex++; - } while (BufferIndex < _SEGGER_RTT.MaxNumUpBuffers); - if (BufferIndex < _SEGGER_RTT.MaxNumUpBuffers) { - _SEGGER_RTT.aUp[BufferIndex].sName = sName; - _SEGGER_RTT.aUp[BufferIndex].pBuffer = pBuffer; - _SEGGER_RTT.aUp[BufferIndex].SizeOfBuffer = BufferSize; - _SEGGER_RTT.aUp[BufferIndex].RdOff = 0u; - _SEGGER_RTT.aUp[BufferIndex].WrOff = 0u; - _SEGGER_RTT.aUp[BufferIndex].Flags = Flags; - } else { - BufferIndex = -1; - } - SEGGER_RTT_UNLOCK(); - return BufferIndex; -} - -/********************************************************************* -* -* SEGGER_RTT_ConfigUpBuffer -* -* Function description -* Run-time configuration of a specific up-buffer (T->H). -* Buffer to be configured is specified by index. -* This includes: Buffer address, size, name, flags, ... -* -* Parameters -* BufferIndex Index of the buffer to configure. -* sName Pointer to a constant name string. -* pBuffer Pointer to a buffer to be used. -* BufferSize Size of the buffer. -* Flags Operating modes. Define behavior if buffer is full (not enough space for entire message). -* -* Return value -* >= 0 - O.K. -* < 0 - Error -*/ -int SEGGER_RTT_ConfigUpBuffer(unsigned BufferIndex, const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags) { - int r; - - INIT(); - if (BufferIndex < (unsigned)_SEGGER_RTT.MaxNumUpBuffers) { - SEGGER_RTT_LOCK(); - if (BufferIndex > 0u) { - _SEGGER_RTT.aUp[BufferIndex].sName = sName; - _SEGGER_RTT.aUp[BufferIndex].pBuffer = pBuffer; - _SEGGER_RTT.aUp[BufferIndex].SizeOfBuffer = BufferSize; - _SEGGER_RTT.aUp[BufferIndex].RdOff = 0u; - _SEGGER_RTT.aUp[BufferIndex].WrOff = 0u; - } - _SEGGER_RTT.aUp[BufferIndex].Flags = Flags; - SEGGER_RTT_UNLOCK(); - r = 0; - } else { - r = -1; - } - return r; -} - -/********************************************************************* -* -* SEGGER_RTT_ConfigDownBuffer -* -* Function description -* Run-time configuration of a specific down-buffer (H->T). -* Buffer to be configured is specified by index. -* This includes: Buffer address, size, name, flags, ... -* -* Parameters -* BufferIndex Index of the buffer to configure. -* sName Pointer to a constant name string. -* pBuffer Pointer to a buffer to be used. -* BufferSize Size of the buffer. -* Flags Operating modes. Define behavior if buffer is full (not enough space for entire message). -* -* Return value -* >= 0 O.K. -* < 0 Error -*/ -int SEGGER_RTT_ConfigDownBuffer(unsigned BufferIndex, const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags) { - int r; - - INIT(); - if (BufferIndex < (unsigned)_SEGGER_RTT.MaxNumDownBuffers) { - SEGGER_RTT_LOCK(); - if (BufferIndex > 0u) { - _SEGGER_RTT.aDown[BufferIndex].sName = sName; - _SEGGER_RTT.aDown[BufferIndex].pBuffer = pBuffer; - _SEGGER_RTT.aDown[BufferIndex].SizeOfBuffer = BufferSize; - _SEGGER_RTT.aDown[BufferIndex].RdOff = 0u; - _SEGGER_RTT.aDown[BufferIndex].WrOff = 0u; - } - _SEGGER_RTT.aDown[BufferIndex].Flags = Flags; - SEGGER_RTT_UNLOCK(); - r = 0; - } else { - r = -1; - } - return r; -} - -/********************************************************************* -* -* SEGGER_RTT_SetNameUpBuffer -* -* Function description -* Run-time configuration of a specific up-buffer name (T->H). -* Buffer to be configured is specified by index. -* -* Parameters -* BufferIndex Index of the buffer to renamed. -* sName Pointer to a constant name string. -* -* Return value -* >= 0 O.K. -* < 0 Error -*/ -int SEGGER_RTT_SetNameUpBuffer(unsigned BufferIndex, const char* sName) { - int r; - - INIT(); - if (BufferIndex < (unsigned)_SEGGER_RTT.MaxNumUpBuffers) { - SEGGER_RTT_LOCK(); - _SEGGER_RTT.aUp[BufferIndex].sName = sName; - SEGGER_RTT_UNLOCK(); - r = 0; - } else { - r = -1; - } - return r; -} - -/********************************************************************* -* -* SEGGER_RTT_SetNameDownBuffer -* -* Function description -* Run-time configuration of a specific Down-buffer name (T->H). -* Buffer to be configured is specified by index. -* -* Parameters -* BufferIndex Index of the buffer to renamed. -* sName Pointer to a constant name string. -* -* Return value -* >= 0 O.K. -* < 0 Error -*/ -int SEGGER_RTT_SetNameDownBuffer(unsigned BufferIndex, const char* sName) { - int r; - - INIT(); - if (BufferIndex < (unsigned)_SEGGER_RTT.MaxNumDownBuffers) { - SEGGER_RTT_LOCK(); - _SEGGER_RTT.aDown[BufferIndex].sName = sName; - SEGGER_RTT_UNLOCK(); - r = 0; - } else { - r = -1; - } - return r; -} - -/********************************************************************* -* -* SEGGER_RTT_Init -* -* Function description -* Initializes the RTT Control Block. -* Should be used in RAM targets, at start of the application. -* -*/ -void SEGGER_RTT_Init (void) { - _DoInit(); -} - -/********************************************************************* -* -* SEGGER_RTT_SetTerminal -* -* Function description -* Sets the terminal to be used for output on channel 0. -* -* Parameters -* TerminalId Index of the terminal. -* -* Return value -* >= 0 O.K. -* < 0 Error (e.g. if RTT is configured for non-blocking mode and there was no space in the buffer to set the new terminal Id) -*/ -int SEGGER_RTT_SetTerminal (char TerminalId) { - char ac[2]; - SEGGER_RTT_BUFFER_UP* pRing; - unsigned Avail; - int r; - // - INIT(); - // - r = 0; - ac[0] = 0xFFU; - if ((unsigned char)TerminalId < (unsigned char)sizeof(_aTerminalId)) { // We only support a certain number of channels - ac[1] = _aTerminalId[(unsigned char)TerminalId]; - pRing = &_SEGGER_RTT.aUp[0]; // Buffer 0 is always reserved for terminal I/O, so we can use index 0 here, fixed - SEGGER_RTT_LOCK(); // Lock to make sure that no other task is writing into buffer, while we are and number of free bytes in buffer does not change downwards after checking and before writing - if ((pRing->Flags & SEGGER_RTT_MODE_MASK) == SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL) { - _ActiveTerminal = TerminalId; - _WriteBlocking(pRing, ac, 2u); - } else { // Skipping mode or trim mode? => We cannot trim this command so handling is the same for both modes - Avail = _GetAvailWriteSpace(pRing); - if (Avail >= 2) { - _ActiveTerminal = TerminalId; // Only change active terminal in case of success - _WriteNoCheck(pRing, ac, 2u); - } else { - r = -1; - } - } - SEGGER_RTT_UNLOCK(); - } else { - r = -1; - } - return r; -} - -/********************************************************************* -* -* SEGGER_RTT_TerminalOut -* -* Function description -* Writes a string to the given terminal -* without changing the terminal for channel 0. -* -* Parameters -* TerminalId Index of the terminal. -* s String to be printed on the terminal. -* -* Return value -* >= 0 - Number of bytes written. -* < 0 - Error. -* -*/ -int SEGGER_RTT_TerminalOut (char TerminalId, const char* s) { - int Status; - unsigned FragLen; - unsigned Avail; - SEGGER_RTT_BUFFER_UP* pRing; - // - INIT(); - // - // Validate terminal ID. - // - if (TerminalId < (char)sizeof(_aTerminalId)) { // We only support a certain number of channels - // - // Get "to-host" ring buffer. - // - pRing = &_SEGGER_RTT.aUp[0]; - // - // Need to be able to change terminal, write data, change back. - // Compute the fixed and variable sizes. - // - FragLen = strlen(s); - // - // How we output depends upon the mode... - // - SEGGER_RTT_LOCK(); - Avail = _GetAvailWriteSpace(pRing); - switch (pRing->Flags & SEGGER_RTT_MODE_MASK) { - case SEGGER_RTT_MODE_NO_BLOCK_SKIP: - // - // If we are in skip mode and there is no space for the whole - // of this output, don't bother switching terminals at all. - // - if (Avail < (FragLen + 4u)) { - Status = 0; - } else { - _PostTerminalSwitch(pRing, TerminalId); - Status = (int)_WriteBlocking(pRing, s, FragLen); - _PostTerminalSwitch(pRing, _ActiveTerminal); - } - break; - case SEGGER_RTT_MODE_NO_BLOCK_TRIM: - // - // If we are in trim mode and there is not enough space for everything, - // trim the output but always include the terminal switch. If no room - // for terminal switch, skip that totally. - // - if (Avail < 4u) { - Status = -1; - } else { - _PostTerminalSwitch(pRing, TerminalId); - Status = (int)_WriteBlocking(pRing, s, (FragLen < (Avail - 4u)) ? FragLen : (Avail - 4u)); - _PostTerminalSwitch(pRing, _ActiveTerminal); - } - break; - case SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL: - // - // If we are in blocking mode, output everything. - // - _PostTerminalSwitch(pRing, TerminalId); - Status = (int)_WriteBlocking(pRing, s, FragLen); - _PostTerminalSwitch(pRing, _ActiveTerminal); - break; - default: - Status = -1; - break; - } - // - // Finish up. - // - SEGGER_RTT_UNLOCK(); - } else { - Status = -1; - } - return Status; -} - - -/*************************** End of file ****************************/ diff --git a/examples/device/nrf52840_freertos/segger/SEGGER_RTT.h b/examples/device/nrf52840_freertos/segger/SEGGER_RTT.h deleted file mode 100644 index d3cac44dd..000000000 --- a/examples/device/nrf52840_freertos/segger/SEGGER_RTT.h +++ /dev/null @@ -1,234 +0,0 @@ -/********************************************************************* -* SEGGER MICROCONTROLLER GmbH & Co. KG * -* Solutions for real time microcontroller applications * -********************************************************************** -* * -* (c) 2014 - 2016 SEGGER Microcontroller GmbH & Co. KG * -* * -* www.segger.com Support: support@segger.com * -* * -********************************************************************** -* * -* SEGGER RTT * Real Time Transfer for embedded targets * -* * -********************************************************************** -* * -* All rights reserved. * -* * -* * This software may in its unmodified form be freely redistributed * -* in source form. * -* * The source code may be modified, provided the source code * -* retains the above copyright notice, this list of conditions and * -* the following disclaimer. * -* * Modified versions of this software in source or linkable form * -* may not be distributed without prior consent of SEGGER. * -* * This software may only be used for communication with SEGGER * -* J-Link debug probes. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * -* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * -* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * -* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * -* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * -* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * -* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * -* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * -* DAMAGE. * -* * -********************************************************************** -* * -* RTT version: 5.12e * -* * -********************************************************************** ----------------------------END-OF-HEADER------------------------------ -File : SEGGER_RTT.h -Purpose : Implementation of SEGGER real-time transfer which allows - real-time communication on targets which support debugger - memory accesses while the CPU is running. ----------------------------------------------------------------------- -*/ - -#ifndef SEGGER_RTT_H -#define SEGGER_RTT_H - -#include "SEGGER_RTT_Conf.h" - -/********************************************************************* -* -* Defines, fixed -* -********************************************************************** -*/ - -/********************************************************************* -* -* Types -* -********************************************************************** -*/ - -// -// Description for a circular buffer (also called "ring buffer") -// which is used as up-buffer (T->H) -// -typedef struct { - const char* sName; // Optional name. Standard names so far are: "Terminal", "SysView", "J-Scope_t4i4" - char* pBuffer; // Pointer to start of buffer - unsigned SizeOfBuffer; // Buffer size in bytes. Note that one byte is lost, as this implementation does not fill up the buffer in order to avoid the problem of being unable to distinguish between full and empty. - unsigned WrOff; // Position of next item to be written by either target. - volatile unsigned RdOff; // Position of next item to be read by host. Must be volatile since it may be modified by host. - unsigned Flags; // Contains configuration flags -} SEGGER_RTT_BUFFER_UP; - -// -// Description for a circular buffer (also called "ring buffer") -// which is used as down-buffer (H->T) -// -typedef struct { - const char* sName; // Optional name. Standard names so far are: "Terminal", "SysView", "J-Scope_t4i4" - char* pBuffer; // Pointer to start of buffer - unsigned SizeOfBuffer; // Buffer size in bytes. Note that one byte is lost, as this implementation does not fill up the buffer in order to avoid the problem of being unable to distinguish between full and empty. - volatile unsigned WrOff; // Position of next item to be written by host. Must be volatile since it may be modified by host. - unsigned RdOff; // Position of next item to be read by target (down-buffer). - unsigned Flags; // Contains configuration flags -} SEGGER_RTT_BUFFER_DOWN; - -// -// RTT control block which describes the number of buffers available -// as well as the configuration for each buffer -// -// -typedef struct { - char acID[16]; // Initialized to "SEGGER RTT" - int MaxNumUpBuffers; // Initialized to SEGGER_RTT_MAX_NUM_UP_BUFFERS (type. 2) - int MaxNumDownBuffers; // Initialized to SEGGER_RTT_MAX_NUM_DOWN_BUFFERS (type. 2) - SEGGER_RTT_BUFFER_UP aUp[SEGGER_RTT_MAX_NUM_UP_BUFFERS]; // Up buffers, transferring information up from target via debug probe to host - SEGGER_RTT_BUFFER_DOWN aDown[SEGGER_RTT_MAX_NUM_DOWN_BUFFERS]; // Down buffers, transferring information down from host via debug probe to target -} SEGGER_RTT_CB; - -/********************************************************************* -* -* Global data -* -********************************************************************** -*/ -extern SEGGER_RTT_CB _SEGGER_RTT; - -/********************************************************************* -* -* RTT API functions -* -********************************************************************** -*/ -#ifdef __cplusplus - extern "C" { -#endif -int SEGGER_RTT_AllocDownBuffer (const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags); -int SEGGER_RTT_AllocUpBuffer (const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags); -int SEGGER_RTT_ConfigUpBuffer (unsigned BufferIndex, const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags); -int SEGGER_RTT_ConfigDownBuffer (unsigned BufferIndex, const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags); -int SEGGER_RTT_GetKey (void); -unsigned SEGGER_RTT_HasData (unsigned BufferIndex); -int SEGGER_RTT_HasKey (void); -void SEGGER_RTT_Init (void); -unsigned SEGGER_RTT_Read (unsigned BufferIndex, void* pBuffer, unsigned BufferSize); -unsigned SEGGER_RTT_ReadNoLock (unsigned BufferIndex, void* pData, unsigned BufferSize); -int SEGGER_RTT_SetNameDownBuffer(unsigned BufferIndex, const char* sName); -int SEGGER_RTT_SetNameUpBuffer (unsigned BufferIndex, const char* sName); -int SEGGER_RTT_WaitKey (void); -unsigned SEGGER_RTT_Write (unsigned BufferIndex, const void* pBuffer, unsigned NumBytes); -unsigned SEGGER_RTT_WriteNoLock (unsigned BufferIndex, const void* pBuffer, unsigned NumBytes); -unsigned SEGGER_RTT_WriteSkipNoLock (unsigned BufferIndex, const void* pBuffer, unsigned NumBytes); -unsigned SEGGER_RTT_WriteString (unsigned BufferIndex, const char* s); -void SEGGER_RTT_WriteWithOverwriteNoLock(unsigned BufferIndex, const void* pBuffer, unsigned NumBytes); -// -// Function macro for performance optimization -// -#define SEGGER_RTT_HASDATA(n) (_SEGGER_RTT.aDown[n].WrOff - _SEGGER_RTT.aDown[n].RdOff) - -/********************************************************************* -* -* RTT "Terminal" API functions -* -********************************************************************** -*/ -int SEGGER_RTT_SetTerminal (char TerminalId); -int SEGGER_RTT_TerminalOut (char TerminalId, const char* s); - -/********************************************************************* -* -* RTT printf functions (require SEGGER_RTT_printf.c) -* -********************************************************************** -*/ -int SEGGER_RTT_printf(unsigned BufferIndex, const char * sFormat, ...); -#ifdef __cplusplus - } -#endif - -/********************************************************************* -* -* Defines -* -********************************************************************** -*/ - -// -// Operating modes. Define behavior if buffer is full (not enough space for entire message) -// -#define SEGGER_RTT_MODE_NO_BLOCK_SKIP (0U) // Skip. Do not block, output nothing. (Default) -#define SEGGER_RTT_MODE_NO_BLOCK_TRIM (1U) // Trim: Do not block, output as much as fits. -#define SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL (2U) // Block: Wait until there is space in the buffer. -#define SEGGER_RTT_MODE_MASK (3U) - -// -// Control sequences, based on ANSI. -// Can be used to control color, and clear the screen -// -#define RTT_CTRL_RESET "" // Reset to default colors -#define RTT_CTRL_CLEAR "" // Clear screen, reposition cursor to top left - -#define RTT_CTRL_TEXT_BLACK "" -#define RTT_CTRL_TEXT_RED "" -#define RTT_CTRL_TEXT_GREEN "" -#define RTT_CTRL_TEXT_YELLOW "" -#define RTT_CTRL_TEXT_BLUE "" -#define RTT_CTRL_TEXT_MAGENTA "" -#define RTT_CTRL_TEXT_CYAN "" -#define RTT_CTRL_TEXT_WHITE "" - -#define RTT_CTRL_TEXT_BRIGHT_BLACK "" -#define RTT_CTRL_TEXT_BRIGHT_RED "" -#define RTT_CTRL_TEXT_BRIGHT_GREEN "" -#define RTT_CTRL_TEXT_BRIGHT_YELLOW "" -#define RTT_CTRL_TEXT_BRIGHT_BLUE "" -#define RTT_CTRL_TEXT_BRIGHT_MAGENTA "" -#define RTT_CTRL_TEXT_BRIGHT_CYAN "" -#define RTT_CTRL_TEXT_BRIGHT_WHITE "" - -#define RTT_CTRL_BG_BLACK "" -#define RTT_CTRL_BG_RED "" -#define RTT_CTRL_BG_GREEN "" -#define RTT_CTRL_BG_YELLOW "" -#define RTT_CTRL_BG_BLUE "" -#define RTT_CTRL_BG_MAGENTA "" -#define RTT_CTRL_BG_CYAN "" -#define RTT_CTRL_BG_WHITE "" - -#define RTT_CTRL_BG_BRIGHT_BLACK "" -#define RTT_CTRL_BG_BRIGHT_RED "" -#define RTT_CTRL_BG_BRIGHT_GREEN "" -#define RTT_CTRL_BG_BRIGHT_YELLOW "" -#define RTT_CTRL_BG_BRIGHT_BLUE "" -#define RTT_CTRL_BG_BRIGHT_MAGENTA "" -#define RTT_CTRL_BG_BRIGHT_CYAN "" -#define RTT_CTRL_BG_BRIGHT_WHITE "" - - -#endif - -/*************************** End of file ****************************/ diff --git a/examples/device/nrf52840_freertos/segger/SEGGER_RTT_Conf.h b/examples/device/nrf52840_freertos/segger/SEGGER_RTT_Conf.h deleted file mode 100644 index aef3b4053..000000000 --- a/examples/device/nrf52840_freertos/segger/SEGGER_RTT_Conf.h +++ /dev/null @@ -1,242 +0,0 @@ -/********************************************************************* -* SEGGER MICROCONTROLLER GmbH & Co. KG * -* Solutions for real time microcontroller applications * -********************************************************************** -* * -* (c) 2014 - 2016 SEGGER Microcontroller GmbH & Co. KG * -* * -* www.segger.com Support: support@segger.com * -* * -********************************************************************** -* * -* SEGGER RTT * Real Time Transfer for embedded targets * -* * -********************************************************************** -* * -* All rights reserved. * -* * -* * This software may in its unmodified form be freely redistributed * -* in source form. * -* * The source code may be modified, provided the source code * -* retains the above copyright notice, this list of conditions and * -* the following disclaimer. * -* * Modified versions of this software in source or linkable form * -* may not be distributed without prior consent of SEGGER. * -* * This software may only be used for communication with SEGGER * -* J-Link debug probes. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * -* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * -* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * -* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * -* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * -* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * -* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * -* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * -* DAMAGE. * -* * -********************************************************************** -* * -* RTT version: 5.12e * -* * -********************************************************************** ----------------------------------------------------------------------- -File : SEGGER_RTT_Conf.h -Purpose : Implementation of SEGGER real-time transfer (RTT) which - allows real-time communication on targets which support - debugger memory accesses while the CPU is running. ----------------------------END-OF-HEADER------------------------------ -*/ - -#ifndef SEGGER_RTT_CONF_H -#define SEGGER_RTT_CONF_H - -#ifdef __ICCARM__ - #include -#endif - -/********************************************************************* -* -* Defines, configurable -* -********************************************************************** -*/ - -#define SEGGER_RTT_MAX_NUM_UP_BUFFERS (2) // Max. number of up-buffers (T->H) available on this target (Default: 2) -#define SEGGER_RTT_MAX_NUM_DOWN_BUFFERS (2) // Max. number of down-buffers (H->T) available on this target (Default: 2) - -#define BUFFER_SIZE_UP (1024) // Size of the buffer for terminal output of target, up to host (Default: 1k) -#define BUFFER_SIZE_DOWN (16) // Size of the buffer for terminal input to target from host (Usually keyboard input) (Default: 16) - -#define SEGGER_RTT_PRINTF_BUFFER_SIZE (64u) // Size of buffer for RTT printf to bulk-send chars via RTT (Default: 64) - -#define SEGGER_RTT_MODE_DEFAULT SEGGER_RTT_MODE_NO_BLOCK_SKIP // Mode for pre-initialized terminal channel (buffer 0) - -// -// Target is not allowed to perform other RTT operations while string still has not been stored completely. -// Otherwise we would probably end up with a mixed string in the buffer. -// If using RTT from within interrupts, multiple tasks or multi processors, define the SEGGER_RTT_LOCK() and SEGGER_RTT_UNLOCK() function here. -// -// SEGGER_RTT_MAX_INTERRUPT_PRIORITY can be used in the sample lock routines on Cortex-M3/4. -// Make sure to mask all interrupts which can send RTT data, i.e. generate SystemView events, or cause task switches. -// When high-priority interrupts must not be masked while sending RTT data, SEGGER_RTT_MAX_INTERRUPT_PRIORITY needs to be adjusted accordingly. -// (Higher priority = lower priority number) -// Default value for embOS: 128u -// Default configuration in FreeRTOS: configMAX_SYSCALL_INTERRUPT_PRIORITY: ( configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY << (8 - configPRIO_BITS) ) -// In case of doubt mask all interrupts: 0u -// - -#define SEGGER_RTT_MAX_INTERRUPT_PRIORITY (0x20) // Interrupt priority to lock on SEGGER_RTT_LOCK on Cortex-M3/4 (Default: 0x20) - -/********************************************************************* -* -* RTT lock configuration for SEGGER Embedded Studio, -* Rowley CrossStudio and GCC -*/ -#if (defined __SES_ARM) || (defined __CROSSWORKS_ARM) || (defined __GNUC__) - #ifdef __ARM_ARCH_6M__ - #define SEGGER_RTT_LOCK() { \ - unsigned int LockState; \ - __asm volatile ("mrs %0, primask \n\t" \ - "mov r1, $1 \n\t" \ - "msr primask, r1 \n\t" \ - : "=r" (LockState) \ - : \ - : "r1" \ - ); - - #define SEGGER_RTT_UNLOCK() __asm volatile ("msr primask, %0 \n\t" \ - : \ - : "r" (LockState) \ - : \ - ); \ - } - - #elif (defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7EM__)) - #ifndef SEGGER_RTT_MAX_INTERRUPT_PRIORITY - #define SEGGER_RTT_MAX_INTERRUPT_PRIORITY (0x20) - #endif - #define SEGGER_RTT_LOCK() { \ - unsigned int LockState; \ - __asm volatile ("mrs %0, basepri \n\t" \ - "mov r1, %1 \n\t" \ - "msr basepri, r1 \n\t" \ - : "=r" (LockState) \ - : "i"(SEGGER_RTT_MAX_INTERRUPT_PRIORITY) \ - : "r1" \ - ); - - #define SEGGER_RTT_UNLOCK() __asm volatile ("msr basepri, %0 \n\t" \ - : \ - : "r" (LockState) \ - : \ - ); \ - } - - #elif defined(__ARM_ARCH_7A__) - #define SEGGER_RTT_LOCK() { \ - unsigned int LockState; \ - __asm volatile ("mrs r1, CPSR \n\t" \ - "mov %0, r1 \n\t" \ - "orr r1, r1, #0xC0 \n\t" \ - "msr CPSR_c, r1 \n\t" \ - : "=r" (LockState) \ - : \ - : "r1" \ - ); - - #define SEGGER_RTT_UNLOCK() __asm volatile ("mov r0, %0 \n\t" \ - "mrs r1, CPSR \n\t" \ - "bic r1, r1, #0xC0 \n\t" \ - "and r0, r0, #0xC0 \n\t" \ - "orr r1, r1, r0 \n\t" \ - "msr CPSR_c, r1 \n\t" \ - : \ - : "r" (LockState) \ - : "r0", "r1" \ - ); \ - } -#else - #define SEGGER_RTT_LOCK() - #define SEGGER_RTT_UNLOCK() - #endif -#endif - -/********************************************************************* -* -* RTT lock configuration for IAR EWARM -*/ -#ifdef __ICCARM__ - #if (defined (__ARM6M__) && (__CORE__ == __ARM6M__)) - #define SEGGER_RTT_LOCK() { \ - unsigned int LockState; \ - LockState = __get_PRIMASK(); \ - __set_PRIMASK(1); - - #define SEGGER_RTT_UNLOCK() __set_PRIMASK(LockState); \ - } - #elif ((defined (__ARM7EM__) && (__CORE__ == __ARM7EM__)) || (defined (__ARM7M__) && (__CORE__ == __ARM7M__))) - #ifndef SEGGER_RTT_MAX_INTERRUPT_PRIORITY - #define SEGGER_RTT_MAX_INTERRUPT_PRIORITY (0x20) - #endif - #define SEGGER_RTT_LOCK() { \ - unsigned int LockState; \ - LockState = __get_BASEPRI(); \ - __set_BASEPRI(SEGGER_RTT_MAX_INTERRUPT_PRIORITY); - - #define SEGGER_RTT_UNLOCK() __set_BASEPRI(LockState); \ - } - #endif -#endif - -/********************************************************************* -* -* RTT lock configuration for KEIL ARM -*/ -#ifdef __CC_ARM - #if (defined __TARGET_ARCH_6S_M) - #define SEGGER_RTT_LOCK() { \ - unsigned int LockState; \ - register unsigned char PRIMASK __asm( "primask"); \ - LockState = PRIMASK; \ - PRIMASK = 1u; \ - __schedule_barrier(); - - #define SEGGER_RTT_UNLOCK() PRIMASK = LockState; \ - __schedule_barrier(); \ - } - #elif (defined(__TARGET_ARCH_7_M) || defined(__TARGET_ARCH_7E_M)) - #ifndef SEGGER_RTT_MAX_INTERRUPT_PRIORITY - #define SEGGER_RTT_MAX_INTERRUPT_PRIORITY (0x20) - #endif - #define SEGGER_RTT_LOCK() { \ - unsigned int LockState; \ - register unsigned char BASEPRI __asm( "basepri"); \ - LockState = BASEPRI; \ - BASEPRI = SEGGER_RTT_MAX_INTERRUPT_PRIORITY; \ - __schedule_barrier(); - - #define SEGGER_RTT_UNLOCK() BASEPRI = LockState; \ - __schedule_barrier(); \ - } - #endif -#endif - -/********************************************************************* -* -* RTT lock configuration fallback -*/ -#ifndef SEGGER_RTT_LOCK - #define SEGGER_RTT_LOCK() // Lock RTT (nestable) (i.e. disable interrupts) -#endif - -#ifndef SEGGER_RTT_UNLOCK - #define SEGGER_RTT_UNLOCK() // Unlock RTT (nestable) (i.e. enable previous interrupt lock state) -#endif - -#endif -/*************************** End of file ****************************/ diff --git a/examples/device/nrf52840_freertos/segger/SEGGER_RTT_SES.c b/examples/device/nrf52840_freertos/segger/SEGGER_RTT_SES.c deleted file mode 100644 index e6634147c..000000000 --- a/examples/device/nrf52840_freertos/segger/SEGGER_RTT_SES.c +++ /dev/null @@ -1,76 +0,0 @@ -/********************************************************************* -* SEGGER MICROCONTROLLER GmbH & Co. KG * -* Solutions for real time microcontroller applications * -********************************************************************** -* * -* (c) 2014 - 2015 SEGGER Microcontroller GmbH & Co. KG * -* * -* www.segger.com Support: support@segger.com * -* * -********************************************************************** -* * -* All rights reserved. * -* * -* * This software may in its unmodified form be freely redistributed * -* in source form. * -* * The source code may be modified, provided the source code * -* retains the above copyright notice, this list of conditions and * -* the following disclaimer. * -* * Modified versions of this software in source or linkable form * -* may not be distributed without prior consent of SEGGER. * -* * This software may only be used for communication with SEGGER * -* J-Link debug probes. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * -* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * -* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * -* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * -* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * -* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * -* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * -* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * -* DAMAGE. * -* * -********************************************************************** --------- END-OF-HEADER --------------------------------------------- -File : SEGGER_RTT_Syscalls_SES.c -Purpose : Reimplementation of printf, puts and - implementation of __putchar and __getchar using RTT in SES. - To use RTT for printf output, include this file in your - application. ----------------------------------------------------------------------- -*/ -#include "SEGGER_RTT.h" -#include "__libc.h" -#include -#include - -int printf(const char *fmt,...) { - char buffer[128]; - va_list args; - va_start (args, fmt); - int n = vsnprintf(buffer, sizeof(buffer), fmt, args); - SEGGER_RTT_Write(0, buffer, n); - va_end(args); - return n; -} - -int puts(const char *s) { - return SEGGER_RTT_WriteString(0, s); -} - -int __putchar(int x, __printf_tag_ptr ctx) { - (void)ctx; - SEGGER_RTT_Write(0, (char *)&x, 1); - return x; -} - -int __getchar() { - return SEGGER_RTT_WaitKey(); -} - -/****** End Of File *************************************************/ diff --git a/examples/device/nrf52840_freertos/segger/nrf5x_freertos.emProject b/examples/device/nrf52840_freertos/segger/nrf5x_freertos.emProject index f01207bab..661dc12a6 100644 --- a/examples/device/nrf52840_freertos/segger/nrf5x_freertos.emProject +++ b/examples/device/nrf52840_freertos/segger/nrf5x_freertos.emProject @@ -32,12 +32,6 @@ target_reset_script="Reset();" target_script_file="$(ProjectDir)/nRF_Target.js" target_trace_initialize_script="EnableTrace("$(TraceInterfaceType)")" /> - - - - - - @@ -60,6 +54,12 @@ + + + + + + diff --git a/examples/device/nrf52840_freertos/src/main.c b/examples/device/nrf52840_freertos/src/main.c index 6fb76a84d..d5a5d0c2c 100644 --- a/examples/device/nrf52840_freertos/src/main.c +++ b/examples/device/nrf52840_freertos/src/main.c @@ -101,18 +101,32 @@ void cdc_task(void* params) while ( 1 ) { // connected and there are data available - if ( tud_mounted() && tud_cdc_available() ) + if ( tud_cdc_connected() ) { - uint8_t buf[64]; + if ( tud_cdc_available() ) + { + uint8_t buf[64]; + + // read and echo back + uint32_t count = tud_cdc_read(buf, sizeof(buf)); - // read and echo back - uint32_t count = tud_cdc_read(buf, sizeof(buf)); + tud_cdc_write(buf, count); + } - tud_cdc_write(buf, count); tud_cdc_write_flush(); } + } +} + +void tud_cdc_line_state_cb(uint8_t itf, bool dtr, bool rts) +{ + (void) itf; - taskYIELD(); + // connected + if ( dtr && rts ) + { + // print greeting + tud_cdc_write_str("tinyusb usb cdc\n"); } } #endif diff --git a/examples/device/nrf52840_freertos/src/segger_rtt/SEGGER_RTT.c b/examples/device/nrf52840_freertos/src/segger_rtt/SEGGER_RTT.c new file mode 100644 index 000000000..aee5bd21e --- /dev/null +++ b/examples/device/nrf52840_freertos/src/segger_rtt/SEGGER_RTT.c @@ -0,0 +1,1329 @@ +/********************************************************************* +* SEGGER MICROCONTROLLER GmbH & Co. KG * +* Solutions for real time microcontroller applications * +********************************************************************** +* * +* (c) 2014 - 2016 SEGGER Microcontroller GmbH & Co. KG * +* * +* www.segger.com Support: support@segger.com * +* * +********************************************************************** +* * +* SEGGER RTT * Real Time Transfer for embedded targets * +* * +********************************************************************** +* * +* All rights reserved. * +* * +* * This software may in its unmodified form be freely redistributed * +* in source form. * +* * The source code may be modified, provided the source code * +* retains the above copyright notice, this list of conditions and * +* the following disclaimer. * +* * Modified versions of this software in source or linkable form * +* may not be distributed without prior consent of SEGGER. * +* * This software may only be used for communication with SEGGER * +* J-Link debug probes. * +* * +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * +* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * +* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * +* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * +* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR * +* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * +* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * +* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * +* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * +* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * +* DAMAGE. * +* * +********************************************************************** +* * +* RTT version: 5.12e * +* * +********************************************************************** +---------------------------END-OF-HEADER------------------------------ +File : SEGGER_RTT.c +Purpose : Implementation of SEGGER real-time transfer (RTT) which + allows real-time communication on targets which support + debugger memory accesses while the CPU is running. + +Additional information: + Type "int" is assumed to be 32-bits in size + H->T Host to target communication + T->H Target to host communication + + RTT channel 0 is always present and reserved for Terminal usage. + Name is fixed to "Terminal" + + Effective buffer size: SizeOfBuffer - 1 + + WrOff == RdOff: Buffer is empty + WrOff == (RdOff - 1): Buffer is full + WrOff > RdOff: Free space includes wrap-around + WrOff < RdOff: Used space includes wrap-around + (WrOff == (SizeOfBuffer - 1)) && (RdOff == 0): + Buffer full and wrap-around after next byte + + +---------------------------------------------------------------------- +*/ + +#include "SEGGER_RTT.h" + +#include // for memcpy + +/********************************************************************* +* +* Configuration, default values +* +********************************************************************** +*/ + +#ifndef BUFFER_SIZE_UP + #define BUFFER_SIZE_UP 1024 // Size of the buffer for terminal output of target, up to host +#endif + +#ifndef BUFFER_SIZE_DOWN + #define BUFFER_SIZE_DOWN 16 // Size of the buffer for terminal input to target from host (Usually keyboard input) +#endif + +#ifndef SEGGER_RTT_MAX_NUM_UP_BUFFERS + #define SEGGER_RTT_MAX_NUM_UP_BUFFERS 2 // Number of up-buffers (T->H) available on this target +#endif + +#ifndef SEGGER_RTT_MAX_NUM_DOWN_BUFFERS + #define SEGGER_RTT_MAX_NUM_DOWN_BUFFERS 2 // Number of down-buffers (H->T) available on this target +#endif + +#ifndef SEGGER_RTT_BUFFER_SECTION + #if defined SEGGER_RTT_SECTION + #define SEGGER_RTT_BUFFER_SECTION SEGGER_RTT_SECTION + #endif +#endif + +#ifndef SEGGER_RTT_MODE_DEFAULT + #define SEGGER_RTT_MODE_DEFAULT SEGGER_RTT_MODE_NO_BLOCK_SKIP +#endif + +#ifndef SEGGER_RTT_LOCK + #define SEGGER_RTT_LOCK() +#endif + +#ifndef SEGGER_RTT_UNLOCK + #define SEGGER_RTT_UNLOCK() +#endif + +#ifndef STRLEN + #define STRLEN(a) strlen((a)) +#endif + +#ifndef MEMCPY + #define MEMCPY(pDest, pSrc, NumBytes) memcpy((pDest), (pSrc), (NumBytes)) +#endif + +#ifndef MIN + #define MIN(a, b) (((a) < (b)) ? (a) : (b)) +#endif + +#ifndef MAX + #define MAX(a, b) (((a) > (b)) ? (a) : (b)) +#endif +// +// For some environments, NULL may not be defined until certain headers are included +// +#ifndef NULL + #define NULL 0 +#endif + +/********************************************************************* +* +* Static const data +* +********************************************************************** +*/ + +static unsigned char _aTerminalId[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; + +/********************************************************************* +* +* Static data +* +********************************************************************** +*/ +// +// RTT Control Block and allocate buffers for channel 0 +// +#ifdef SEGGER_RTT_SECTION + #if (defined __GNUC__) + __attribute__ ((section (SEGGER_RTT_SECTION))) SEGGER_RTT_CB _SEGGER_RTT; + #elif (defined __ICCARM__) || (defined __ICCRX__) + #pragma location=SEGGER_RTT_SECTION + SEGGER_RTT_CB _SEGGER_RTT; + #elif (defined __CC_ARM__) + __attribute__ ((section (SEGGER_RTT_SECTION), zero_init)) SEGGER_RTT_CB _SEGGER_RTT; + #else + SEGGER_RTT_CB _SEGGER_RTT; + #endif +#else + SEGGER_RTT_CB _SEGGER_RTT; +#endif + +#ifdef SEGGER_RTT_BUFFER_SECTION + #if (defined __GNUC__) + __attribute__ ((section (SEGGER_RTT_BUFFER_SECTION))) static char _acUpBuffer [BUFFER_SIZE_UP]; + __attribute__ ((section (SEGGER_RTT_BUFFER_SECTION))) static char _acDownBuffer[BUFFER_SIZE_DOWN]; + #elif (defined __ICCARM__) || (defined __ICCRX__) + #pragma location=SEGGER_RTT_BUFFER_SECTION + static char _acUpBuffer [BUFFER_SIZE_UP]; + #pragma location=SEGGER_RTT_BUFFER_SECTION + static char _acDownBuffer[BUFFER_SIZE_DOWN]; + #elif (defined __CC_ARM__) + __attribute__ ((section (SEGGER_RTT_BUFFER_SECTION), zero_init)) static char _acUpBuffer [BUFFER_SIZE_UP]; + __attribute__ ((section (SEGGER_RTT_BUFFER_SECTION), zero_init)) static char _acDownBuffer[BUFFER_SIZE_DOWN]; + #else + static char _acUpBuffer [BUFFER_SIZE_UP]; + static char _acDownBuffer[BUFFER_SIZE_DOWN]; + #endif +#else + static char _acUpBuffer [BUFFER_SIZE_UP]; + static char _acDownBuffer[BUFFER_SIZE_DOWN]; +#endif + +static char _ActiveTerminal; + +/********************************************************************* +* +* Static functions +* +********************************************************************** +*/ + +/********************************************************************* +* +* _DoInit() +* +* Function description +* Initializes the control block an buffers. +* May only be called via INIT() to avoid overriding settings. +* +*/ +#define INIT() do { \ + if (_SEGGER_RTT.acID[0] == '\0') { _DoInit(); } \ + } while (0) +static void _DoInit(void) { + SEGGER_RTT_CB* p; + // + // Initialize control block + // + p = &_SEGGER_RTT; + p->MaxNumUpBuffers = SEGGER_RTT_MAX_NUM_UP_BUFFERS; + p->MaxNumDownBuffers = SEGGER_RTT_MAX_NUM_DOWN_BUFFERS; + // + // Initialize up buffer 0 + // + p->aUp[0].sName = "Terminal"; + p->aUp[0].pBuffer = _acUpBuffer; + p->aUp[0].SizeOfBuffer = sizeof(_acUpBuffer); + p->aUp[0].RdOff = 0u; + p->aUp[0].WrOff = 0u; + p->aUp[0].Flags = SEGGER_RTT_MODE_DEFAULT; + // + // Initialize down buffer 0 + // + p->aDown[0].sName = "Terminal"; + p->aDown[0].pBuffer = _acDownBuffer; + p->aDown[0].SizeOfBuffer = sizeof(_acDownBuffer); + p->aDown[0].RdOff = 0u; + p->aDown[0].WrOff = 0u; + p->aDown[0].Flags = SEGGER_RTT_MODE_DEFAULT; + // + // Finish initialization of the control block. + // Copy Id string in three steps to make sure "SEGGER RTT" is not found + // in initializer memory (usually flash) by J-Link + // + strcpy(&p->acID[7], "RTT"); + strcpy(&p->acID[0], "SEGGER"); + p->acID[6] = ' '; +} + +/********************************************************************* +* +* _WriteBlocking() +* +* Function description +* Stores a specified number of characters in SEGGER RTT ring buffer +* and updates the associated write pointer which is periodically +* read by the host. +* The caller is responsible for managing the write chunk sizes as +* _WriteBlocking() will block until all data has been posted successfully. +* +* Parameters +* pRing Ring buffer to post to. +* pBuffer Pointer to character array. Does not need to point to a \0 terminated string. +* NumBytes Number of bytes to be stored in the SEGGER RTT control block. +* +* Return value +* >= 0 - Number of bytes written into buffer. +*/ +static unsigned _WriteBlocking(SEGGER_RTT_BUFFER_UP* pRing, const char* pBuffer, unsigned NumBytes) { + unsigned NumBytesToWrite; + unsigned NumBytesWritten; + unsigned RdOff; + unsigned WrOff; + // + // Write data to buffer and handle wrap-around if necessary + // + NumBytesWritten = 0u; + WrOff = pRing->WrOff; + do { + RdOff = pRing->RdOff; // May be changed by host (debug probe) in the meantime + if (RdOff > WrOff) { + NumBytesToWrite = RdOff - WrOff - 1u; + } else { + NumBytesToWrite = pRing->SizeOfBuffer - (WrOff - RdOff + 1u); + } + NumBytesToWrite = MIN(NumBytesToWrite, (pRing->SizeOfBuffer - WrOff)); // Number of bytes that can be written until buffer wrap-around + NumBytesToWrite = MIN(NumBytesToWrite, NumBytes); + memcpy(pRing->pBuffer + WrOff, pBuffer, NumBytesToWrite); + NumBytesWritten += NumBytesToWrite; + pBuffer += NumBytesToWrite; + NumBytes -= NumBytesToWrite; + WrOff += NumBytesToWrite; + if (WrOff == pRing->SizeOfBuffer) { + WrOff = 0u; + } + pRing->WrOff = WrOff; + } while (NumBytes); + // + return NumBytesWritten; +} + +/********************************************************************* +* +* _WriteNoCheck() +* +* Function description +* Stores a specified number of characters in SEGGER RTT ring buffer +* and updates the associated write pointer which is periodically +* read by the host. +* It is callers responsibility to make sure data actually fits in buffer. +* +* Parameters +* pRing Ring buffer to post to. +* pBuffer Pointer to character array. Does not need to point to a \0 terminated string. +* NumBytes Number of bytes to be stored in the SEGGER RTT control block. +* +* Notes +* (1) If there might not be enough space in the "Up"-buffer, call _WriteBlocking +*/ +static void _WriteNoCheck(SEGGER_RTT_BUFFER_UP* pRing, const char* pData, unsigned NumBytes) { + unsigned NumBytesAtOnce; + unsigned WrOff; + unsigned Rem; + + WrOff = pRing->WrOff; + Rem = pRing->SizeOfBuffer - WrOff; + if (Rem > NumBytes) { + // + // All data fits before wrap around + // + memcpy(pRing->pBuffer + WrOff, pData, NumBytes); + pRing->WrOff = WrOff + NumBytes; + } else { + // + // We reach the end of the buffer, so need to wrap around + // + NumBytesAtOnce = Rem; + memcpy(pRing->pBuffer + WrOff, pData, NumBytesAtOnce); + NumBytesAtOnce = NumBytes - Rem; + memcpy(pRing->pBuffer, pData + Rem, NumBytesAtOnce); + pRing->WrOff = NumBytesAtOnce; + } +} + +/********************************************************************* +* +* _PostTerminalSwitch() +* +* Function description +* Switch terminal to the given terminal ID. It is the caller's +* responsibility to ensure the terminal ID is correct and there is +* enough space in the buffer for this to complete successfully. +* +* Parameters +* pRing Ring buffer to post to. +* TerminalId Terminal ID to switch to. +*/ +static void _PostTerminalSwitch(SEGGER_RTT_BUFFER_UP* pRing, unsigned char TerminalId) { + char ac[2]; + + ac[0] = 0xFFu; + ac[1] = _aTerminalId[TerminalId]; // Caller made already sure that TerminalId does not exceed our terminal limit + _WriteBlocking(pRing, ac, 2u); +} + +/********************************************************************* +* +* _GetAvailWriteSpace() +* +* Function description +* Returns the number of bytes that can be written to the ring +* buffer without blocking. +* +* Parameters +* pRing Ring buffer to check. +* +* Return value +* Number of bytes that are free in the buffer. +*/ +static unsigned _GetAvailWriteSpace(SEGGER_RTT_BUFFER_UP* pRing) { + unsigned RdOff; + unsigned WrOff; + unsigned r; + // + // Avoid warnings regarding volatile access order. It's not a problem + // in this case, but dampen compiler enthusiasm. + // + RdOff = pRing->RdOff; + WrOff = pRing->WrOff; + if (RdOff <= WrOff) { + r = pRing->SizeOfBuffer - 1u - WrOff + RdOff; + } else { + r = RdOff - WrOff - 1u; + } + return r; +} + +/********************************************************************* +* +* Public code +* +********************************************************************** +*/ +/********************************************************************* +* +* SEGGER_RTT_ReadNoLock() +* +* Function description +* Reads characters from SEGGER real-time-terminal control block +* which have been previously stored by the host. +* Do not lock against interrupts and multiple access. +* +* Parameters +* BufferIndex Index of Down-buffer to be used (e.g. 0 for "Terminal"). +* pBuffer Pointer to buffer provided by target application, to copy characters from RTT-down-buffer to. +* BufferSize Size of the target application buffer. +* +* Return value +* Number of bytes that have been read. +*/ +unsigned SEGGER_RTT_ReadNoLock(unsigned BufferIndex, void* pData, unsigned BufferSize) { + unsigned NumBytesRem; + unsigned NumBytesRead; + unsigned RdOff; + unsigned WrOff; + unsigned char* pBuffer; + SEGGER_RTT_BUFFER_DOWN* pRing; + // + INIT(); + pRing = &_SEGGER_RTT.aDown[BufferIndex]; + pBuffer = (unsigned char*)pData; + RdOff = pRing->RdOff; + WrOff = pRing->WrOff; + NumBytesRead = 0u; + // + // Read from current read position to wrap-around of buffer, first + // + if (RdOff > WrOff) { + NumBytesRem = pRing->SizeOfBuffer - RdOff; + NumBytesRem = MIN(NumBytesRem, BufferSize); + memcpy(pBuffer, pRing->pBuffer + RdOff, NumBytesRem); + NumBytesRead += NumBytesRem; + pBuffer += NumBytesRem; + BufferSize -= NumBytesRem; + RdOff += NumBytesRem; + // + // Handle wrap-around of buffer + // + if (RdOff == pRing->SizeOfBuffer) { + RdOff = 0u; + } + } + // + // Read remaining items of buffer + // + NumBytesRem = WrOff - RdOff; + NumBytesRem = MIN(NumBytesRem, BufferSize); + if (NumBytesRem > 0u) { + memcpy(pBuffer, pRing->pBuffer + RdOff, NumBytesRem); + NumBytesRead += NumBytesRem; + pBuffer += NumBytesRem; + BufferSize -= NumBytesRem; + RdOff += NumBytesRem; + } + if (NumBytesRead) { + pRing->RdOff = RdOff; + } + // + return NumBytesRead; +} + +/********************************************************************* +* +* SEGGER_RTT_Read +* +* Function description +* Reads characters from SEGGER real-time-terminal control block +* which have been previously stored by the host. +* +* Parameters +* BufferIndex Index of Down-buffer to be used (e.g. 0 for "Terminal"). +* pBuffer Pointer to buffer provided by target application, to copy characters from RTT-down-buffer to. +* BufferSize Size of the target application buffer. +* +* Return value +* Number of bytes that have been read. +*/ +unsigned SEGGER_RTT_Read(unsigned BufferIndex, void* pBuffer, unsigned BufferSize) { + unsigned NumBytesRead; + // + SEGGER_RTT_LOCK(); + // + // Call the non-locking read function + // + NumBytesRead = SEGGER_RTT_ReadNoLock(BufferIndex, pBuffer, BufferSize); + // + // Finish up. + // + SEGGER_RTT_UNLOCK(); + // + return NumBytesRead; +} + +/********************************************************************* +* +* SEGGER_RTT_WriteWithOverwriteNoLock +* +* Function description +* Stores a specified number of characters in SEGGER RTT +* control block. +* SEGGER_RTT_WriteWithOverwriteNoLock does not lock the application +* and overwrites data if the data does not fit into the buffer. +* +* Parameters +* BufferIndex Index of "Up"-buffer to be used (e.g. 0 for "Terminal"). +* pBuffer Pointer to character array. Does not need to point to a \0 terminated string. +* NumBytes Number of bytes to be stored in the SEGGER RTT control block. +* +* Notes +* (1) If there is not enough space in the "Up"-buffer, data is overwritten. +* (2) For performance reasons this function does not call Init() +* and may only be called after RTT has been initialized. +* Either by calling SEGGER_RTT_Init() or calling another RTT API function first. +* (3) Do not use SEGGER_RTT_WriteWithOverwriteNoLock if a J-Link +* connection reads RTT data. +*/ +void SEGGER_RTT_WriteWithOverwriteNoLock(unsigned BufferIndex, const void* pBuffer, unsigned NumBytes) { + const char* pData; + SEGGER_RTT_BUFFER_UP* pRing; + unsigned Avail; + + pData = (const char *)pBuffer; + // + // Get "to-host" ring buffer and copy some elements into local variables. + // + pRing = &_SEGGER_RTT.aUp[BufferIndex]; + // + // Check if we will overwrite data and need to adjust the RdOff. + // + if (pRing->WrOff == pRing->RdOff) { + Avail = pRing->SizeOfBuffer - 1u; + } else if ( pRing->WrOff < pRing->RdOff) { + Avail = pRing->RdOff - pRing->WrOff - 1u; + } else { + Avail = pRing->RdOff - pRing->WrOff - 1u + pRing->SizeOfBuffer; + } + if (NumBytes > Avail) { + pRing->RdOff += (NumBytes - Avail); + while (pRing->RdOff >= pRing->SizeOfBuffer) { + pRing->RdOff -= pRing->SizeOfBuffer; + } + } + // + // Write all data, no need to check the RdOff, but possibly handle multiple wrap-arounds + // + Avail = pRing->SizeOfBuffer - pRing->WrOff; + do { + if (Avail > NumBytes) { + // + // Last round + // +#if 1 // memcpy() is good for large amounts of data, but the overhead is too big for small amounts. Use a simple byte loop instead. + char* pDst; + pDst = pRing->pBuffer + pRing->WrOff; + pRing->WrOff += NumBytes; + do { + *pDst++ = *pData++; + } while (--NumBytes); +#else + memcpy(pRing->pBuffer + WrOff, pData, NumBytes); + pRing->WrOff += NumBytes; +#endif + break; //Alternatively: NumBytes = 0; + } else { + // + // Wrap-around necessary, write until wrap-around and reset WrOff + // + memcpy(pRing->pBuffer + pRing->WrOff, pData, Avail); + pData += Avail; + pRing->WrOff = 0; + NumBytes -= Avail; + Avail = (pRing->SizeOfBuffer - 1); + } + } while (NumBytes); +} + +/********************************************************************* +* +* SEGGER_RTT_WriteSkipNoLock +* +* Function description +* Stores a specified number of characters in SEGGER RTT +* control block which is then read by the host. +* SEGGER_RTT_WriteSkipNoLock does not lock the application and +* skips all data, if the data does not fit into the buffer. +* +* Parameters +* BufferIndex Index of "Up"-buffer to be used (e.g. 0 for "Terminal"). +* pBuffer Pointer to character array. Does not need to point to a \0 terminated string. +* NumBytes Number of bytes to be stored in the SEGGER RTT control block. +* +* Return value +* Number of bytes which have been stored in the "Up"-buffer. +* +* Notes +* (1) If there is not enough space in the "Up"-buffer, all data is dropped. +* (2) For performance reasons this function does not call Init() +* and may only be called after RTT has been initialized. +* Either by calling SEGGER_RTT_Init() or calling another RTT API function first. +*/ +unsigned SEGGER_RTT_WriteSkipNoLock(unsigned BufferIndex, const void* pBuffer, unsigned NumBytes) { + const char* pData; + SEGGER_RTT_BUFFER_UP* pRing; + unsigned Avail; + unsigned RdOff; + unsigned WrOff; + unsigned Rem; + + pData = (const char *)pBuffer; + // + // Get "to-host" ring buffer and copy some elements into local variables. + // + pRing = &_SEGGER_RTT.aUp[BufferIndex]; + RdOff = pRing->RdOff; + WrOff = pRing->WrOff; + // + // Handle the most common cases fastest. + // Which is: + // RdOff <= WrOff -> Space until wrap around is free. + // AND + // WrOff + NumBytes < SizeOfBuffer -> No Wrap around necessary. + // + // OR + // + // RdOff > WrOff -> Space until RdOff - 1 is free. + // AND + // WrOff + NumBytes < RdOff -> Data fits into buffer + // + if (RdOff <= WrOff) { + // + // Get space until WrOff will be at wrap around. + // + Avail = pRing->SizeOfBuffer - 1u - WrOff ; + if (Avail >= NumBytes) { +#if 1 // memcpy() is good for large amounts of data, but the overhead is too big for small amounts. Use a simple byte loop instead. + char* pDst; + pDst = pRing->pBuffer + WrOff; + WrOff += NumBytes; + do { + *pDst++ = *pData++; + } while (--NumBytes); + pRing->WrOff = WrOff + NumBytes; +#else + memcpy(pRing->pBuffer + WrOff, pData, NumBytes); + pRing->WrOff = WrOff + NumBytes; +#endif + return 1; + } + // + // If data did not fit into space until wrap around calculate complete space in buffer. + // + Avail += RdOff; + // + // If there is still no space for the whole of this output, don't bother. + // + if (Avail >= NumBytes) { + // + // OK, we have enough space in buffer. Copy in one or 2 chunks + // + Rem = pRing->SizeOfBuffer - WrOff; // Space until end of buffer + if (Rem > NumBytes) { + memcpy(pRing->pBuffer + WrOff, pData, NumBytes); + pRing->WrOff = WrOff + NumBytes; + } else { + // + // We reach the end of the buffer, so need to wrap around + // + memcpy(pRing->pBuffer + WrOff, pData, Rem); + memcpy(pRing->pBuffer, pData + Rem, NumBytes - Rem); + pRing->WrOff = NumBytes - Rem; + } + return 1; + } + } else { + Avail = RdOff - WrOff - 1u; + if (Avail >= NumBytes) { + memcpy(pRing->pBuffer + WrOff, pData, NumBytes); + pRing->WrOff = WrOff + NumBytes; + return 1; + } + } + // + // If we reach this point no data has been written + // + return 0; +} + +/********************************************************************* +* +* SEGGER_RTT_WriteNoLock +* +* Function description +* Stores a specified number of characters in SEGGER RTT +* control block which is then read by the host. +* SEGGER_RTT_WriteNoLock does not lock the application. +* +* Parameters +* BufferIndex Index of "Up"-buffer to be used (e.g. 0 for "Terminal"). +* pBuffer Pointer to character array. Does not need to point to a \0 terminated string. +* NumBytes Number of bytes to be stored in the SEGGER RTT control block. +* +* Return value +* Number of bytes which have been stored in the "Up"-buffer. +* +* Notes +* (1) If there is not enough space in the "Up"-buffer, remaining characters of pBuffer are dropped. +* (2) For performance reasons this function does not call Init() +* and may only be called after RTT has been initialized. +* Either by calling SEGGER_RTT_Init() or calling another RTT API function first. +*/ +unsigned SEGGER_RTT_WriteNoLock(unsigned BufferIndex, const void* pBuffer, unsigned NumBytes) { + unsigned Status; + unsigned Avail; + const char* pData; + SEGGER_RTT_BUFFER_UP* pRing; + + pData = (const char *)pBuffer; + // + // Get "to-host" ring buffer. + // + pRing = &_SEGGER_RTT.aUp[BufferIndex]; + // + // How we output depends upon the mode... + // + switch (pRing->Flags) { + case SEGGER_RTT_MODE_NO_BLOCK_SKIP: + // + // If we are in skip mode and there is no space for the whole + // of this output, don't bother. + // + Avail = _GetAvailWriteSpace(pRing); + if (Avail < NumBytes) { + Status = 0u; + } else { + Status = NumBytes; + _WriteNoCheck(pRing, pData, NumBytes); + } + break; + case SEGGER_RTT_MODE_NO_BLOCK_TRIM: + // + // If we are in trim mode, trim to what we can output without blocking. + // + Avail = _GetAvailWriteSpace(pRing); + Status = Avail < NumBytes ? Avail : NumBytes; + _WriteNoCheck(pRing, pData, Status); + break; + case SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL: + // + // If we are in blocking mode, output everything. + // + Status = _WriteBlocking(pRing, pData, NumBytes); + break; + default: + Status = 0u; + break; + } + // + // Finish up. + // + return Status; +} + +/********************************************************************* +* +* SEGGER_RTT_Write +* +* Function description +* Stores a specified number of characters in SEGGER RTT +* control block which is then read by the host. +* +* Parameters +* BufferIndex Index of "Up"-buffer to be used (e.g. 0 for "Terminal"). +* pBuffer Pointer to character array. Does not need to point to a \0 terminated string. +* NumBytes Number of bytes to be stored in the SEGGER RTT control block. +* +* Return value +* Number of bytes which have been stored in the "Up"-buffer. +* +* Notes +* (1) If there is not enough space in the "Up"-buffer, remaining characters of pBuffer are dropped. +*/ +unsigned SEGGER_RTT_Write(unsigned BufferIndex, const void* pBuffer, unsigned NumBytes) { + unsigned Status; + // + INIT(); + SEGGER_RTT_LOCK(); + // + // Call the non-locking write function + // + Status = SEGGER_RTT_WriteNoLock(BufferIndex, pBuffer, NumBytes); + // + // Finish up. + // + SEGGER_RTT_UNLOCK(); + // + return Status; +} + +/********************************************************************* +* +* SEGGER_RTT_WriteString +* +* Function description +* Stores string in SEGGER RTT control block. +* This data is read by the host. +* +* Parameters +* BufferIndex Index of "Up"-buffer to be used (e.g. 0 for "Terminal"). +* s Pointer to string. +* +* Return value +* Number of bytes which have been stored in the "Up"-buffer. +* +* Notes +* (1) If there is not enough space in the "Up"-buffer, depending on configuration, +* remaining characters may be dropped or RTT module waits until there is more space in the buffer. +* (2) String passed to this function has to be \0 terminated +* (3) \0 termination character is *not* stored in RTT buffer +*/ +unsigned SEGGER_RTT_WriteString(unsigned BufferIndex, const char* s) { + unsigned Len; + + Len = STRLEN(s); + return SEGGER_RTT_Write(BufferIndex, s, Len); +} + +/********************************************************************* +* +* SEGGER_RTT_GetKey +* +* Function description +* Reads one character from the SEGGER RTT buffer. +* Host has previously stored data there. +* +* Return value +* < 0 - No character available (buffer empty). +* >= 0 - Character which has been read. (Possible values: 0 - 255) +* +* Notes +* (1) This function is only specified for accesses to RTT buffer 0. +*/ +int SEGGER_RTT_GetKey(void) { + char c; + int r; + + r = (int)SEGGER_RTT_Read(0u, &c, 1u); + if (r == 1) { + r = (int)(unsigned char)c; + } else { + r = -1; + } + return r; +} + +/********************************************************************* +* +* SEGGER_RTT_WaitKey +* +* Function description +* Waits until at least one character is avaible in the SEGGER RTT buffer. +* Once a character is available, it is read and this function returns. +* +* Return value +* >=0 - Character which has been read. +* +* Notes +* (1) This function is only specified for accesses to RTT buffer 0 +* (2) This function is blocking if no character is present in RTT buffer +*/ +int SEGGER_RTT_WaitKey(void) { + int r; + + do { + r = SEGGER_RTT_GetKey(); + } while (r < 0); + return r; +} + +/********************************************************************* +* +* SEGGER_RTT_HasKey +* +* Function description +* Checks if at least one character for reading is available in the SEGGER RTT buffer. +* +* Return value +* == 0 - No characters are available to read. +* == 1 - At least one character is available. +* +* Notes +* (1) This function is only specified for accesses to RTT buffer 0 +*/ +int SEGGER_RTT_HasKey(void) { + unsigned RdOff; + int r; + + INIT(); + RdOff = _SEGGER_RTT.aDown[0].RdOff; + if (RdOff != _SEGGER_RTT.aDown[0].WrOff) { + r = 1; + } else { + r = 0; + } + return r; +} + +/********************************************************************* +* +* SEGGER_RTT_HasData +* +* Function description +* Check if there is data from the host in the given buffer. +* +* Return value: +* ==0: No data +* !=0: Data in buffer +* +*/ +unsigned SEGGER_RTT_HasData(unsigned BufferIndex) { + SEGGER_RTT_BUFFER_DOWN* pRing; + unsigned v; + + pRing = &_SEGGER_RTT.aDown[BufferIndex]; + v = pRing->WrOff; + return v - pRing->RdOff; +} + +/********************************************************************* +* +* SEGGER_RTT_AllocDownBuffer +* +* Function description +* Run-time configuration of the next down-buffer (H->T). +* The next buffer, which is not used yet is configured. +* This includes: Buffer address, size, name, flags, ... +* +* Parameters +* sName Pointer to a constant name string. +* pBuffer Pointer to a buffer to be used. +* BufferSize Size of the buffer. +* Flags Operating modes. Define behavior if buffer is full (not enough space for entire message). +* +* Return value +* >= 0 - O.K. Buffer Index +* < 0 - Error +*/ +int SEGGER_RTT_AllocDownBuffer(const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags) { + int BufferIndex; + + INIT(); + SEGGER_RTT_LOCK(); + BufferIndex = 0; + do { + if (_SEGGER_RTT.aDown[BufferIndex].pBuffer == NULL) { + break; + } + BufferIndex++; + } while (BufferIndex < _SEGGER_RTT.MaxNumDownBuffers); + if (BufferIndex < _SEGGER_RTT.MaxNumDownBuffers) { + _SEGGER_RTT.aDown[BufferIndex].sName = sName; + _SEGGER_RTT.aDown[BufferIndex].pBuffer = pBuffer; + _SEGGER_RTT.aDown[BufferIndex].SizeOfBuffer = BufferSize; + _SEGGER_RTT.aDown[BufferIndex].RdOff = 0u; + _SEGGER_RTT.aDown[BufferIndex].WrOff = 0u; + _SEGGER_RTT.aDown[BufferIndex].Flags = Flags; + } else { + BufferIndex = -1; + } + SEGGER_RTT_UNLOCK(); + return BufferIndex; +} + +/********************************************************************* +* +* SEGGER_RTT_AllocUpBuffer +* +* Function description +* Run-time configuration of the next up-buffer (T->H). +* The next buffer, which is not used yet is configured. +* This includes: Buffer address, size, name, flags, ... +* +* Parameters +* sName Pointer to a constant name string. +* pBuffer Pointer to a buffer to be used. +* BufferSize Size of the buffer. +* Flags Operating modes. Define behavior if buffer is full (not enough space for entire message). +* +* Return value +* >= 0 - O.K. Buffer Index +* < 0 - Error +*/ +int SEGGER_RTT_AllocUpBuffer(const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags) { + int BufferIndex; + + INIT(); + SEGGER_RTT_LOCK(); + BufferIndex = 0; + do { + if (_SEGGER_RTT.aUp[BufferIndex].pBuffer == NULL) { + break; + } + BufferIndex++; + } while (BufferIndex < _SEGGER_RTT.MaxNumUpBuffers); + if (BufferIndex < _SEGGER_RTT.MaxNumUpBuffers) { + _SEGGER_RTT.aUp[BufferIndex].sName = sName; + _SEGGER_RTT.aUp[BufferIndex].pBuffer = pBuffer; + _SEGGER_RTT.aUp[BufferIndex].SizeOfBuffer = BufferSize; + _SEGGER_RTT.aUp[BufferIndex].RdOff = 0u; + _SEGGER_RTT.aUp[BufferIndex].WrOff = 0u; + _SEGGER_RTT.aUp[BufferIndex].Flags = Flags; + } else { + BufferIndex = -1; + } + SEGGER_RTT_UNLOCK(); + return BufferIndex; +} + +/********************************************************************* +* +* SEGGER_RTT_ConfigUpBuffer +* +* Function description +* Run-time configuration of a specific up-buffer (T->H). +* Buffer to be configured is specified by index. +* This includes: Buffer address, size, name, flags, ... +* +* Parameters +* BufferIndex Index of the buffer to configure. +* sName Pointer to a constant name string. +* pBuffer Pointer to a buffer to be used. +* BufferSize Size of the buffer. +* Flags Operating modes. Define behavior if buffer is full (not enough space for entire message). +* +* Return value +* >= 0 - O.K. +* < 0 - Error +*/ +int SEGGER_RTT_ConfigUpBuffer(unsigned BufferIndex, const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags) { + int r; + + INIT(); + if (BufferIndex < (unsigned)_SEGGER_RTT.MaxNumUpBuffers) { + SEGGER_RTT_LOCK(); + if (BufferIndex > 0u) { + _SEGGER_RTT.aUp[BufferIndex].sName = sName; + _SEGGER_RTT.aUp[BufferIndex].pBuffer = pBuffer; + _SEGGER_RTT.aUp[BufferIndex].SizeOfBuffer = BufferSize; + _SEGGER_RTT.aUp[BufferIndex].RdOff = 0u; + _SEGGER_RTT.aUp[BufferIndex].WrOff = 0u; + } + _SEGGER_RTT.aUp[BufferIndex].Flags = Flags; + SEGGER_RTT_UNLOCK(); + r = 0; + } else { + r = -1; + } + return r; +} + +/********************************************************************* +* +* SEGGER_RTT_ConfigDownBuffer +* +* Function description +* Run-time configuration of a specific down-buffer (H->T). +* Buffer to be configured is specified by index. +* This includes: Buffer address, size, name, flags, ... +* +* Parameters +* BufferIndex Index of the buffer to configure. +* sName Pointer to a constant name string. +* pBuffer Pointer to a buffer to be used. +* BufferSize Size of the buffer. +* Flags Operating modes. Define behavior if buffer is full (not enough space for entire message). +* +* Return value +* >= 0 O.K. +* < 0 Error +*/ +int SEGGER_RTT_ConfigDownBuffer(unsigned BufferIndex, const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags) { + int r; + + INIT(); + if (BufferIndex < (unsigned)_SEGGER_RTT.MaxNumDownBuffers) { + SEGGER_RTT_LOCK(); + if (BufferIndex > 0u) { + _SEGGER_RTT.aDown[BufferIndex].sName = sName; + _SEGGER_RTT.aDown[BufferIndex].pBuffer = pBuffer; + _SEGGER_RTT.aDown[BufferIndex].SizeOfBuffer = BufferSize; + _SEGGER_RTT.aDown[BufferIndex].RdOff = 0u; + _SEGGER_RTT.aDown[BufferIndex].WrOff = 0u; + } + _SEGGER_RTT.aDown[BufferIndex].Flags = Flags; + SEGGER_RTT_UNLOCK(); + r = 0; + } else { + r = -1; + } + return r; +} + +/********************************************************************* +* +* SEGGER_RTT_SetNameUpBuffer +* +* Function description +* Run-time configuration of a specific up-buffer name (T->H). +* Buffer to be configured is specified by index. +* +* Parameters +* BufferIndex Index of the buffer to renamed. +* sName Pointer to a constant name string. +* +* Return value +* >= 0 O.K. +* < 0 Error +*/ +int SEGGER_RTT_SetNameUpBuffer(unsigned BufferIndex, const char* sName) { + int r; + + INIT(); + if (BufferIndex < (unsigned)_SEGGER_RTT.MaxNumUpBuffers) { + SEGGER_RTT_LOCK(); + _SEGGER_RTT.aUp[BufferIndex].sName = sName; + SEGGER_RTT_UNLOCK(); + r = 0; + } else { + r = -1; + } + return r; +} + +/********************************************************************* +* +* SEGGER_RTT_SetNameDownBuffer +* +* Function description +* Run-time configuration of a specific Down-buffer name (T->H). +* Buffer to be configured is specified by index. +* +* Parameters +* BufferIndex Index of the buffer to renamed. +* sName Pointer to a constant name string. +* +* Return value +* >= 0 O.K. +* < 0 Error +*/ +int SEGGER_RTT_SetNameDownBuffer(unsigned BufferIndex, const char* sName) { + int r; + + INIT(); + if (BufferIndex < (unsigned)_SEGGER_RTT.MaxNumDownBuffers) { + SEGGER_RTT_LOCK(); + _SEGGER_RTT.aDown[BufferIndex].sName = sName; + SEGGER_RTT_UNLOCK(); + r = 0; + } else { + r = -1; + } + return r; +} + +/********************************************************************* +* +* SEGGER_RTT_Init +* +* Function description +* Initializes the RTT Control Block. +* Should be used in RAM targets, at start of the application. +* +*/ +void SEGGER_RTT_Init (void) { + _DoInit(); +} + +/********************************************************************* +* +* SEGGER_RTT_SetTerminal +* +* Function description +* Sets the terminal to be used for output on channel 0. +* +* Parameters +* TerminalId Index of the terminal. +* +* Return value +* >= 0 O.K. +* < 0 Error (e.g. if RTT is configured for non-blocking mode and there was no space in the buffer to set the new terminal Id) +*/ +int SEGGER_RTT_SetTerminal (char TerminalId) { + char ac[2]; + SEGGER_RTT_BUFFER_UP* pRing; + unsigned Avail; + int r; + // + INIT(); + // + r = 0; + ac[0] = 0xFFU; + if ((unsigned char)TerminalId < (unsigned char)sizeof(_aTerminalId)) { // We only support a certain number of channels + ac[1] = _aTerminalId[(unsigned char)TerminalId]; + pRing = &_SEGGER_RTT.aUp[0]; // Buffer 0 is always reserved for terminal I/O, so we can use index 0 here, fixed + SEGGER_RTT_LOCK(); // Lock to make sure that no other task is writing into buffer, while we are and number of free bytes in buffer does not change downwards after checking and before writing + if ((pRing->Flags & SEGGER_RTT_MODE_MASK) == SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL) { + _ActiveTerminal = TerminalId; + _WriteBlocking(pRing, ac, 2u); + } else { // Skipping mode or trim mode? => We cannot trim this command so handling is the same for both modes + Avail = _GetAvailWriteSpace(pRing); + if (Avail >= 2) { + _ActiveTerminal = TerminalId; // Only change active terminal in case of success + _WriteNoCheck(pRing, ac, 2u); + } else { + r = -1; + } + } + SEGGER_RTT_UNLOCK(); + } else { + r = -1; + } + return r; +} + +/********************************************************************* +* +* SEGGER_RTT_TerminalOut +* +* Function description +* Writes a string to the given terminal +* without changing the terminal for channel 0. +* +* Parameters +* TerminalId Index of the terminal. +* s String to be printed on the terminal. +* +* Return value +* >= 0 - Number of bytes written. +* < 0 - Error. +* +*/ +int SEGGER_RTT_TerminalOut (char TerminalId, const char* s) { + int Status; + unsigned FragLen; + unsigned Avail; + SEGGER_RTT_BUFFER_UP* pRing; + // + INIT(); + // + // Validate terminal ID. + // + if (TerminalId < (char)sizeof(_aTerminalId)) { // We only support a certain number of channels + // + // Get "to-host" ring buffer. + // + pRing = &_SEGGER_RTT.aUp[0]; + // + // Need to be able to change terminal, write data, change back. + // Compute the fixed and variable sizes. + // + FragLen = strlen(s); + // + // How we output depends upon the mode... + // + SEGGER_RTT_LOCK(); + Avail = _GetAvailWriteSpace(pRing); + switch (pRing->Flags & SEGGER_RTT_MODE_MASK) { + case SEGGER_RTT_MODE_NO_BLOCK_SKIP: + // + // If we are in skip mode and there is no space for the whole + // of this output, don't bother switching terminals at all. + // + if (Avail < (FragLen + 4u)) { + Status = 0; + } else { + _PostTerminalSwitch(pRing, TerminalId); + Status = (int)_WriteBlocking(pRing, s, FragLen); + _PostTerminalSwitch(pRing, _ActiveTerminal); + } + break; + case SEGGER_RTT_MODE_NO_BLOCK_TRIM: + // + // If we are in trim mode and there is not enough space for everything, + // trim the output but always include the terminal switch. If no room + // for terminal switch, skip that totally. + // + if (Avail < 4u) { + Status = -1; + } else { + _PostTerminalSwitch(pRing, TerminalId); + Status = (int)_WriteBlocking(pRing, s, (FragLen < (Avail - 4u)) ? FragLen : (Avail - 4u)); + _PostTerminalSwitch(pRing, _ActiveTerminal); + } + break; + case SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL: + // + // If we are in blocking mode, output everything. + // + _PostTerminalSwitch(pRing, TerminalId); + Status = (int)_WriteBlocking(pRing, s, FragLen); + _PostTerminalSwitch(pRing, _ActiveTerminal); + break; + default: + Status = -1; + break; + } + // + // Finish up. + // + SEGGER_RTT_UNLOCK(); + } else { + Status = -1; + } + return Status; +} + + +/*************************** End of file ****************************/ diff --git a/examples/device/nrf52840_freertos/src/segger_rtt/SEGGER_RTT.h b/examples/device/nrf52840_freertos/src/segger_rtt/SEGGER_RTT.h new file mode 100644 index 000000000..d3cac44dd --- /dev/null +++ b/examples/device/nrf52840_freertos/src/segger_rtt/SEGGER_RTT.h @@ -0,0 +1,234 @@ +/********************************************************************* +* SEGGER MICROCONTROLLER GmbH & Co. KG * +* Solutions for real time microcontroller applications * +********************************************************************** +* * +* (c) 2014 - 2016 SEGGER Microcontroller GmbH & Co. KG * +* * +* www.segger.com Support: support@segger.com * +* * +********************************************************************** +* * +* SEGGER RTT * Real Time Transfer for embedded targets * +* * +********************************************************************** +* * +* All rights reserved. * +* * +* * This software may in its unmodified form be freely redistributed * +* in source form. * +* * The source code may be modified, provided the source code * +* retains the above copyright notice, this list of conditions and * +* the following disclaimer. * +* * Modified versions of this software in source or linkable form * +* may not be distributed without prior consent of SEGGER. * +* * This software may only be used for communication with SEGGER * +* J-Link debug probes. * +* * +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * +* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * +* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * +* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * +* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR * +* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * +* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * +* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * +* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * +* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * +* DAMAGE. * +* * +********************************************************************** +* * +* RTT version: 5.12e * +* * +********************************************************************** +---------------------------END-OF-HEADER------------------------------ +File : SEGGER_RTT.h +Purpose : Implementation of SEGGER real-time transfer which allows + real-time communication on targets which support debugger + memory accesses while the CPU is running. +---------------------------------------------------------------------- +*/ + +#ifndef SEGGER_RTT_H +#define SEGGER_RTT_H + +#include "SEGGER_RTT_Conf.h" + +/********************************************************************* +* +* Defines, fixed +* +********************************************************************** +*/ + +/********************************************************************* +* +* Types +* +********************************************************************** +*/ + +// +// Description for a circular buffer (also called "ring buffer") +// which is used as up-buffer (T->H) +// +typedef struct { + const char* sName; // Optional name. Standard names so far are: "Terminal", "SysView", "J-Scope_t4i4" + char* pBuffer; // Pointer to start of buffer + unsigned SizeOfBuffer; // Buffer size in bytes. Note that one byte is lost, as this implementation does not fill up the buffer in order to avoid the problem of being unable to distinguish between full and empty. + unsigned WrOff; // Position of next item to be written by either target. + volatile unsigned RdOff; // Position of next item to be read by host. Must be volatile since it may be modified by host. + unsigned Flags; // Contains configuration flags +} SEGGER_RTT_BUFFER_UP; + +// +// Description for a circular buffer (also called "ring buffer") +// which is used as down-buffer (H->T) +// +typedef struct { + const char* sName; // Optional name. Standard names so far are: "Terminal", "SysView", "J-Scope_t4i4" + char* pBuffer; // Pointer to start of buffer + unsigned SizeOfBuffer; // Buffer size in bytes. Note that one byte is lost, as this implementation does not fill up the buffer in order to avoid the problem of being unable to distinguish between full and empty. + volatile unsigned WrOff; // Position of next item to be written by host. Must be volatile since it may be modified by host. + unsigned RdOff; // Position of next item to be read by target (down-buffer). + unsigned Flags; // Contains configuration flags +} SEGGER_RTT_BUFFER_DOWN; + +// +// RTT control block which describes the number of buffers available +// as well as the configuration for each buffer +// +// +typedef struct { + char acID[16]; // Initialized to "SEGGER RTT" + int MaxNumUpBuffers; // Initialized to SEGGER_RTT_MAX_NUM_UP_BUFFERS (type. 2) + int MaxNumDownBuffers; // Initialized to SEGGER_RTT_MAX_NUM_DOWN_BUFFERS (type. 2) + SEGGER_RTT_BUFFER_UP aUp[SEGGER_RTT_MAX_NUM_UP_BUFFERS]; // Up buffers, transferring information up from target via debug probe to host + SEGGER_RTT_BUFFER_DOWN aDown[SEGGER_RTT_MAX_NUM_DOWN_BUFFERS]; // Down buffers, transferring information down from host via debug probe to target +} SEGGER_RTT_CB; + +/********************************************************************* +* +* Global data +* +********************************************************************** +*/ +extern SEGGER_RTT_CB _SEGGER_RTT; + +/********************************************************************* +* +* RTT API functions +* +********************************************************************** +*/ +#ifdef __cplusplus + extern "C" { +#endif +int SEGGER_RTT_AllocDownBuffer (const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags); +int SEGGER_RTT_AllocUpBuffer (const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags); +int SEGGER_RTT_ConfigUpBuffer (unsigned BufferIndex, const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags); +int SEGGER_RTT_ConfigDownBuffer (unsigned BufferIndex, const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags); +int SEGGER_RTT_GetKey (void); +unsigned SEGGER_RTT_HasData (unsigned BufferIndex); +int SEGGER_RTT_HasKey (void); +void SEGGER_RTT_Init (void); +unsigned SEGGER_RTT_Read (unsigned BufferIndex, void* pBuffer, unsigned BufferSize); +unsigned SEGGER_RTT_ReadNoLock (unsigned BufferIndex, void* pData, unsigned BufferSize); +int SEGGER_RTT_SetNameDownBuffer(unsigned BufferIndex, const char* sName); +int SEGGER_RTT_SetNameUpBuffer (unsigned BufferIndex, const char* sName); +int SEGGER_RTT_WaitKey (void); +unsigned SEGGER_RTT_Write (unsigned BufferIndex, const void* pBuffer, unsigned NumBytes); +unsigned SEGGER_RTT_WriteNoLock (unsigned BufferIndex, const void* pBuffer, unsigned NumBytes); +unsigned SEGGER_RTT_WriteSkipNoLock (unsigned BufferIndex, const void* pBuffer, unsigned NumBytes); +unsigned SEGGER_RTT_WriteString (unsigned BufferIndex, const char* s); +void SEGGER_RTT_WriteWithOverwriteNoLock(unsigned BufferIndex, const void* pBuffer, unsigned NumBytes); +// +// Function macro for performance optimization +// +#define SEGGER_RTT_HASDATA(n) (_SEGGER_RTT.aDown[n].WrOff - _SEGGER_RTT.aDown[n].RdOff) + +/********************************************************************* +* +* RTT "Terminal" API functions +* +********************************************************************** +*/ +int SEGGER_RTT_SetTerminal (char TerminalId); +int SEGGER_RTT_TerminalOut (char TerminalId, const char* s); + +/********************************************************************* +* +* RTT printf functions (require SEGGER_RTT_printf.c) +* +********************************************************************** +*/ +int SEGGER_RTT_printf(unsigned BufferIndex, const char * sFormat, ...); +#ifdef __cplusplus + } +#endif + +/********************************************************************* +* +* Defines +* +********************************************************************** +*/ + +// +// Operating modes. Define behavior if buffer is full (not enough space for entire message) +// +#define SEGGER_RTT_MODE_NO_BLOCK_SKIP (0U) // Skip. Do not block, output nothing. (Default) +#define SEGGER_RTT_MODE_NO_BLOCK_TRIM (1U) // Trim: Do not block, output as much as fits. +#define SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL (2U) // Block: Wait until there is space in the buffer. +#define SEGGER_RTT_MODE_MASK (3U) + +// +// Control sequences, based on ANSI. +// Can be used to control color, and clear the screen +// +#define RTT_CTRL_RESET "" // Reset to default colors +#define RTT_CTRL_CLEAR "" // Clear screen, reposition cursor to top left + +#define RTT_CTRL_TEXT_BLACK "" +#define RTT_CTRL_TEXT_RED "" +#define RTT_CTRL_TEXT_GREEN "" +#define RTT_CTRL_TEXT_YELLOW "" +#define RTT_CTRL_TEXT_BLUE "" +#define RTT_CTRL_TEXT_MAGENTA "" +#define RTT_CTRL_TEXT_CYAN "" +#define RTT_CTRL_TEXT_WHITE "" + +#define RTT_CTRL_TEXT_BRIGHT_BLACK "" +#define RTT_CTRL_TEXT_BRIGHT_RED "" +#define RTT_CTRL_TEXT_BRIGHT_GREEN "" +#define RTT_CTRL_TEXT_BRIGHT_YELLOW "" +#define RTT_CTRL_TEXT_BRIGHT_BLUE "" +#define RTT_CTRL_TEXT_BRIGHT_MAGENTA "" +#define RTT_CTRL_TEXT_BRIGHT_CYAN "" +#define RTT_CTRL_TEXT_BRIGHT_WHITE "" + +#define RTT_CTRL_BG_BLACK "" +#define RTT_CTRL_BG_RED "" +#define RTT_CTRL_BG_GREEN "" +#define RTT_CTRL_BG_YELLOW "" +#define RTT_CTRL_BG_BLUE "" +#define RTT_CTRL_BG_MAGENTA "" +#define RTT_CTRL_BG_CYAN "" +#define RTT_CTRL_BG_WHITE "" + +#define RTT_CTRL_BG_BRIGHT_BLACK "" +#define RTT_CTRL_BG_BRIGHT_RED "" +#define RTT_CTRL_BG_BRIGHT_GREEN "" +#define RTT_CTRL_BG_BRIGHT_YELLOW "" +#define RTT_CTRL_BG_BRIGHT_BLUE "" +#define RTT_CTRL_BG_BRIGHT_MAGENTA "" +#define RTT_CTRL_BG_BRIGHT_CYAN "" +#define RTT_CTRL_BG_BRIGHT_WHITE "" + + +#endif + +/*************************** End of file ****************************/ diff --git a/examples/device/nrf52840_freertos/src/segger_rtt/SEGGER_RTT_Conf.h b/examples/device/nrf52840_freertos/src/segger_rtt/SEGGER_RTT_Conf.h new file mode 100644 index 000000000..aef3b4053 --- /dev/null +++ b/examples/device/nrf52840_freertos/src/segger_rtt/SEGGER_RTT_Conf.h @@ -0,0 +1,242 @@ +/********************************************************************* +* SEGGER MICROCONTROLLER GmbH & Co. KG * +* Solutions for real time microcontroller applications * +********************************************************************** +* * +* (c) 2014 - 2016 SEGGER Microcontroller GmbH & Co. KG * +* * +* www.segger.com Support: support@segger.com * +* * +********************************************************************** +* * +* SEGGER RTT * Real Time Transfer for embedded targets * +* * +********************************************************************** +* * +* All rights reserved. * +* * +* * This software may in its unmodified form be freely redistributed * +* in source form. * +* * The source code may be modified, provided the source code * +* retains the above copyright notice, this list of conditions and * +* the following disclaimer. * +* * Modified versions of this software in source or linkable form * +* may not be distributed without prior consent of SEGGER. * +* * This software may only be used for communication with SEGGER * +* J-Link debug probes. * +* * +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * +* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * +* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * +* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * +* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR * +* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * +* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * +* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * +* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * +* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * +* DAMAGE. * +* * +********************************************************************** +* * +* RTT version: 5.12e * +* * +********************************************************************** +---------------------------------------------------------------------- +File : SEGGER_RTT_Conf.h +Purpose : Implementation of SEGGER real-time transfer (RTT) which + allows real-time communication on targets which support + debugger memory accesses while the CPU is running. +---------------------------END-OF-HEADER------------------------------ +*/ + +#ifndef SEGGER_RTT_CONF_H +#define SEGGER_RTT_CONF_H + +#ifdef __ICCARM__ + #include +#endif + +/********************************************************************* +* +* Defines, configurable +* +********************************************************************** +*/ + +#define SEGGER_RTT_MAX_NUM_UP_BUFFERS (2) // Max. number of up-buffers (T->H) available on this target (Default: 2) +#define SEGGER_RTT_MAX_NUM_DOWN_BUFFERS (2) // Max. number of down-buffers (H->T) available on this target (Default: 2) + +#define BUFFER_SIZE_UP (1024) // Size of the buffer for terminal output of target, up to host (Default: 1k) +#define BUFFER_SIZE_DOWN (16) // Size of the buffer for terminal input to target from host (Usually keyboard input) (Default: 16) + +#define SEGGER_RTT_PRINTF_BUFFER_SIZE (64u) // Size of buffer for RTT printf to bulk-send chars via RTT (Default: 64) + +#define SEGGER_RTT_MODE_DEFAULT SEGGER_RTT_MODE_NO_BLOCK_SKIP // Mode for pre-initialized terminal channel (buffer 0) + +// +// Target is not allowed to perform other RTT operations while string still has not been stored completely. +// Otherwise we would probably end up with a mixed string in the buffer. +// If using RTT from within interrupts, multiple tasks or multi processors, define the SEGGER_RTT_LOCK() and SEGGER_RTT_UNLOCK() function here. +// +// SEGGER_RTT_MAX_INTERRUPT_PRIORITY can be used in the sample lock routines on Cortex-M3/4. +// Make sure to mask all interrupts which can send RTT data, i.e. generate SystemView events, or cause task switches. +// When high-priority interrupts must not be masked while sending RTT data, SEGGER_RTT_MAX_INTERRUPT_PRIORITY needs to be adjusted accordingly. +// (Higher priority = lower priority number) +// Default value for embOS: 128u +// Default configuration in FreeRTOS: configMAX_SYSCALL_INTERRUPT_PRIORITY: ( configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY << (8 - configPRIO_BITS) ) +// In case of doubt mask all interrupts: 0u +// + +#define SEGGER_RTT_MAX_INTERRUPT_PRIORITY (0x20) // Interrupt priority to lock on SEGGER_RTT_LOCK on Cortex-M3/4 (Default: 0x20) + +/********************************************************************* +* +* RTT lock configuration for SEGGER Embedded Studio, +* Rowley CrossStudio and GCC +*/ +#if (defined __SES_ARM) || (defined __CROSSWORKS_ARM) || (defined __GNUC__) + #ifdef __ARM_ARCH_6M__ + #define SEGGER_RTT_LOCK() { \ + unsigned int LockState; \ + __asm volatile ("mrs %0, primask \n\t" \ + "mov r1, $1 \n\t" \ + "msr primask, r1 \n\t" \ + : "=r" (LockState) \ + : \ + : "r1" \ + ); + + #define SEGGER_RTT_UNLOCK() __asm volatile ("msr primask, %0 \n\t" \ + : \ + : "r" (LockState) \ + : \ + ); \ + } + + #elif (defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7EM__)) + #ifndef SEGGER_RTT_MAX_INTERRUPT_PRIORITY + #define SEGGER_RTT_MAX_INTERRUPT_PRIORITY (0x20) + #endif + #define SEGGER_RTT_LOCK() { \ + unsigned int LockState; \ + __asm volatile ("mrs %0, basepri \n\t" \ + "mov r1, %1 \n\t" \ + "msr basepri, r1 \n\t" \ + : "=r" (LockState) \ + : "i"(SEGGER_RTT_MAX_INTERRUPT_PRIORITY) \ + : "r1" \ + ); + + #define SEGGER_RTT_UNLOCK() __asm volatile ("msr basepri, %0 \n\t" \ + : \ + : "r" (LockState) \ + : \ + ); \ + } + + #elif defined(__ARM_ARCH_7A__) + #define SEGGER_RTT_LOCK() { \ + unsigned int LockState; \ + __asm volatile ("mrs r1, CPSR \n\t" \ + "mov %0, r1 \n\t" \ + "orr r1, r1, #0xC0 \n\t" \ + "msr CPSR_c, r1 \n\t" \ + : "=r" (LockState) \ + : \ + : "r1" \ + ); + + #define SEGGER_RTT_UNLOCK() __asm volatile ("mov r0, %0 \n\t" \ + "mrs r1, CPSR \n\t" \ + "bic r1, r1, #0xC0 \n\t" \ + "and r0, r0, #0xC0 \n\t" \ + "orr r1, r1, r0 \n\t" \ + "msr CPSR_c, r1 \n\t" \ + : \ + : "r" (LockState) \ + : "r0", "r1" \ + ); \ + } +#else + #define SEGGER_RTT_LOCK() + #define SEGGER_RTT_UNLOCK() + #endif +#endif + +/********************************************************************* +* +* RTT lock configuration for IAR EWARM +*/ +#ifdef __ICCARM__ + #if (defined (__ARM6M__) && (__CORE__ == __ARM6M__)) + #define SEGGER_RTT_LOCK() { \ + unsigned int LockState; \ + LockState = __get_PRIMASK(); \ + __set_PRIMASK(1); + + #define SEGGER_RTT_UNLOCK() __set_PRIMASK(LockState); \ + } + #elif ((defined (__ARM7EM__) && (__CORE__ == __ARM7EM__)) || (defined (__ARM7M__) && (__CORE__ == __ARM7M__))) + #ifndef SEGGER_RTT_MAX_INTERRUPT_PRIORITY + #define SEGGER_RTT_MAX_INTERRUPT_PRIORITY (0x20) + #endif + #define SEGGER_RTT_LOCK() { \ + unsigned int LockState; \ + LockState = __get_BASEPRI(); \ + __set_BASEPRI(SEGGER_RTT_MAX_INTERRUPT_PRIORITY); + + #define SEGGER_RTT_UNLOCK() __set_BASEPRI(LockState); \ + } + #endif +#endif + +/********************************************************************* +* +* RTT lock configuration for KEIL ARM +*/ +#ifdef __CC_ARM + #if (defined __TARGET_ARCH_6S_M) + #define SEGGER_RTT_LOCK() { \ + unsigned int LockState; \ + register unsigned char PRIMASK __asm( "primask"); \ + LockState = PRIMASK; \ + PRIMASK = 1u; \ + __schedule_barrier(); + + #define SEGGER_RTT_UNLOCK() PRIMASK = LockState; \ + __schedule_barrier(); \ + } + #elif (defined(__TARGET_ARCH_7_M) || defined(__TARGET_ARCH_7E_M)) + #ifndef SEGGER_RTT_MAX_INTERRUPT_PRIORITY + #define SEGGER_RTT_MAX_INTERRUPT_PRIORITY (0x20) + #endif + #define SEGGER_RTT_LOCK() { \ + unsigned int LockState; \ + register unsigned char BASEPRI __asm( "basepri"); \ + LockState = BASEPRI; \ + BASEPRI = SEGGER_RTT_MAX_INTERRUPT_PRIORITY; \ + __schedule_barrier(); + + #define SEGGER_RTT_UNLOCK() BASEPRI = LockState; \ + __schedule_barrier(); \ + } + #endif +#endif + +/********************************************************************* +* +* RTT lock configuration fallback +*/ +#ifndef SEGGER_RTT_LOCK + #define SEGGER_RTT_LOCK() // Lock RTT (nestable) (i.e. disable interrupts) +#endif + +#ifndef SEGGER_RTT_UNLOCK + #define SEGGER_RTT_UNLOCK() // Unlock RTT (nestable) (i.e. enable previous interrupt lock state) +#endif + +#endif +/*************************** End of file ****************************/ diff --git a/examples/device/nrf52840_freertos/src/segger_rtt/SEGGER_RTT_SES.c b/examples/device/nrf52840_freertos/src/segger_rtt/SEGGER_RTT_SES.c new file mode 100644 index 000000000..e6634147c --- /dev/null +++ b/examples/device/nrf52840_freertos/src/segger_rtt/SEGGER_RTT_SES.c @@ -0,0 +1,76 @@ +/********************************************************************* +* SEGGER MICROCONTROLLER GmbH & Co. KG * +* Solutions for real time microcontroller applications * +********************************************************************** +* * +* (c) 2014 - 2015 SEGGER Microcontroller GmbH & Co. KG * +* * +* www.segger.com Support: support@segger.com * +* * +********************************************************************** +* * +* All rights reserved. * +* * +* * This software may in its unmodified form be freely redistributed * +* in source form. * +* * The source code may be modified, provided the source code * +* retains the above copyright notice, this list of conditions and * +* the following disclaimer. * +* * Modified versions of this software in source or linkable form * +* may not be distributed without prior consent of SEGGER. * +* * This software may only be used for communication with SEGGER * +* J-Link debug probes. * +* * +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * +* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * +* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * +* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * +* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR * +* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * +* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * +* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * +* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * +* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * +* DAMAGE. * +* * +********************************************************************** +-------- END-OF-HEADER --------------------------------------------- +File : SEGGER_RTT_Syscalls_SES.c +Purpose : Reimplementation of printf, puts and + implementation of __putchar and __getchar using RTT in SES. + To use RTT for printf output, include this file in your + application. +---------------------------------------------------------------------- +*/ +#include "SEGGER_RTT.h" +#include "__libc.h" +#include +#include + +int printf(const char *fmt,...) { + char buffer[128]; + va_list args; + va_start (args, fmt); + int n = vsnprintf(buffer, sizeof(buffer), fmt, args); + SEGGER_RTT_Write(0, buffer, n); + va_end(args); + return n; +} + +int puts(const char *s) { + return SEGGER_RTT_WriteString(0, s); +} + +int __putchar(int x, __printf_tag_ptr ctx) { + (void)ctx; + SEGGER_RTT_Write(0, (char *)&x, 1); + return x; +} + +int __getchar() { + return SEGGER_RTT_WaitKey(); +} + +/****** End Of File *************************************************/ diff --git a/examples/device/nrf52840_freertos/src/tusb_config.h b/examples/device/nrf52840_freertos/src/tusb_config.h index 96d851f90..9641f7bde 100644 --- a/examples/device/nrf52840_freertos/src/tusb_config.h +++ b/examples/device/nrf52840_freertos/src/tusb_config.h @@ -55,7 +55,7 @@ /*------------- RTOS -------------*/ #define CFG_TUSB_OS OPT_OS_FREERTOS -#define CFG_TUD_TASK_PRIO (configMAX_PRIORITIES-3) +#define CFG_TUD_TASK_PRIO (configMAX_PRIORITIES-1) //#define CFG_TUD_TASK_QUEUE_SZ 16 //#define CFG_TUD_TASK_STACK_SZ 150 diff --git a/hw/bsp/pca10056/board_pca10056.c b/hw/bsp/pca10056/board_pca10056.c index 928c39acf..54b1488a8 100644 --- a/hw/bsp/pca10056/board_pca10056.c +++ b/hw/bsp/pca10056/board_pca10056.c @@ -98,6 +98,11 @@ void board_init(void) nrf_gpio_cfg_output(BOARD_LED2); nrf_gpio_cfg_output(BOARD_LED3); + board_led_control(BOARD_LED0, false); + board_led_control(BOARD_LED1, false); + board_led_control(BOARD_LED2, false); + board_led_control(BOARD_LED3, false); + // Button for(uint8_t i=0; irx_ff, ser->rx_ff_buf, CFG_TUD_CDC_RX_BUFSIZE, 1, true); - tu_fifo_config_mutex(&ser->rx_ff, osal_mutex_create(&ser->rx_ff_mutex)); - tu_fifo_config(&ser->tx_ff, ser->tx_ff_buf, CFG_TUD_CDC_TX_BUFSIZE, 1, false); + +#if CFG_FIFO_MUTEX + tu_fifo_config_mutex(&ser->rx_ff, osal_mutex_create(&ser->rx_ff_mutex)); tu_fifo_config_mutex(&ser->tx_ff, osal_mutex_create(&ser->tx_ff_mutex)); +#endif } } diff --git a/src/class/cdc/cdc_device.h b/src/class/cdc/cdc_device.h index 2e03793a9..f1bd33953 100644 --- a/src/class/cdc/cdc_device.h +++ b/src/class/cdc/cdc_device.h @@ -77,6 +77,7 @@ char tud_cdc_n_peek (uint8_t itf, int pos); uint32_t tud_cdc_n_write_char (uint8_t itf, char ch); uint32_t tud_cdc_n_write (uint8_t itf, void const* buffer, uint32_t bufsize); +uint32_t tud_cdc_n_write_str (uint8_t itf, char const* str); bool tud_cdc_n_write_flush (uint8_t itf); //--------------------------------------------------------------------+ @@ -95,6 +96,7 @@ static inline char tud_cdc_peek (int pos) static inline uint32_t tud_cdc_write_char (char ch) { return tud_cdc_n_write_char(0, ch); } static inline uint32_t tud_cdc_write (void const* buffer, uint32_t bufsize) { return tud_cdc_n_write(0, buffer, bufsize); } +static inline uint32_t tud_cdc_write_str (char const* str) { return tud_cdc_n_write_str(0, str); } static inline bool tud_cdc_write_flush (void) { return tud_cdc_n_write_flush(0); } //--------------------------------------------------------------------+ diff --git a/src/common/tusb_fifo.c b/src/common/tusb_fifo.c index e0b3d0aa0..2acd4b696 100644 --- a/src/common/tusb_fifo.c +++ b/src/common/tusb_fifo.c @@ -42,25 +42,16 @@ #include "tusb_fifo.h" // implement mutex lock and unlock -// For OSAL_NONE: if mutex is locked by other, function return immediately (since there is no task context) -// For Real RTOS: fifo lock is a blocking API #if CFG_FIFO_MUTEX -static bool tu_fifo_lock(tu_fifo_t *f) +static void tu_fifo_lock(tu_fifo_t *f) { if (f->mutex) { -#if CFG_TUSB_OS == OPT_OS_NONE - // There is no subtask context for blocking mutex, we will check and return if cannot lock the mutex - if ( !osal_mutex_lock_notask(f->mutex) ) return false; -#else uint32_t err; (void) err; osal_mutex_lock(f->mutex, OSAL_TIMEOUT_WAIT_FOREVER, &err); -#endif } - - return true; } static void tu_fifo_unlock(tu_fifo_t *f) @@ -73,14 +64,14 @@ static void tu_fifo_unlock(tu_fifo_t *f) #else -#define tu_fifo_lock(_ff) true +#define tu_fifo_lock(_ff) #define tu_fifo_unlock(_ff) #endif bool tu_fifo_config(tu_fifo_t *f, void* buffer, uint16_t depth, uint16_t item_size, bool overwritable) { - if ( !tu_fifo_lock(f) ) return false; + tu_fifo_lock(f); f->buffer = (uint8_t*) buffer; f->depth = depth; @@ -115,7 +106,7 @@ bool tu_fifo_read(tu_fifo_t* f, void * p_buffer) { if( tu_fifo_empty(f) ) return false; - if ( !tu_fifo_lock(f) ) return false; + tu_fifo_lock(f); memcpy(p_buffer, f->buffer + (f->rd_idx * f->item_size), @@ -216,7 +207,7 @@ bool tu_fifo_write (tu_fifo_t* f, const void * p_data) { if ( tu_fifo_full(f) && !f->overwritable ) return false; - if ( !tu_fifo_lock(f) ) return false; + tu_fifo_lock(f); memcpy( f->buffer + (f->wr_idx * f->item_size), p_data, @@ -279,7 +270,7 @@ uint16_t tu_fifo_write_n (tu_fifo_t* f, const void * p_data, uint16_t count) /******************************************************************************/ bool tu_fifo_clear(tu_fifo_t *f) { - if ( !tu_fifo_lock(f) ) return false; + tu_fifo_lock(f); f->rd_idx = f->wr_idx = f->count = 0; diff --git a/src/common/tusb_fifo.h b/src/common/tusb_fifo.h index 70dc087c2..61d92b602 100644 --- a/src/common/tusb_fifo.h +++ b/src/common/tusb_fifo.h @@ -43,7 +43,9 @@ #ifndef _TUSB_FIFO_H_ #define _TUSB_FIFO_H_ -#define CFG_FIFO_MUTEX 1 +// mutex is only needed for RTOS +// for OS None, we don't get preempted +#define CFG_FIFO_MUTEX (CFG_TUSB_OS != OPT_OS_NONE) #include #include diff --git a/src/osal/osal_none.h b/src/osal/osal_none.h index 796ddc15f..f70c99c7f 100644 --- a/src/osal/osal_none.h +++ b/src/osal/osal_none.h @@ -178,19 +178,6 @@ static inline osal_mutex_t osal_mutex_create(osal_mutex_def_t* mdef) #define osal_mutex_unlock(_mutex_hdl) osal_semaphore_post(_mutex_hdl, false) #define osal_mutex_lock osal_semaphore_wait -// check if mutex is available for non-thread/substask usage in some cases -static inline bool osal_mutex_lock_notask(osal_mutex_t mutex_hdl) -{ - if (mutex_hdl->count) - { - mutex_hdl->count--; - return true; - }else - { - return false; - } -} - //--------------------------------------------------------------------+ // QUEUE API //--------------------------------------------------------------------+ -- cgit v1.3.1 From 215f8603b14cc29e08d8a25e08f8eca44ed90826 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 16 Nov 2018 21:56:39 +0700 Subject: nrf5x: refactor device control transfer. - make control transfer as part of usbd. Class driver must use usbd_control_ API() instead of dcd_ api. - change the signature of class driver's control_request - allow control request complete to stall in staus stage - move control request parser & handling to usbd. --- src/class/cdc/cdc_device.c | 90 +++++++------- src/class/cdc/cdc_device.h | 4 +- src/class/custom/custom_device.c | 4 +- src/class/custom/custom_device.h | 4 +- src/class/hid/hid_device.c | 141 ++++++++++----------- src/class/hid/hid_device.h | 5 +- src/class/msc/msc_device.c | 71 ++++++++--- src/class/msc/msc_device.h | 30 +---- src/common/tusb_types.h | 6 +- src/device/control.c | 261 +++++++++++++-------------------------- src/device/control.h | 38 ------ src/device/dcd.h | 4 + src/device/usbd.c | 236 ++++++++++++++++++++++++++++------- src/device/usbd_pvt.h | 17 ++- src/tusb_option.h | 4 +- 15 files changed, 477 insertions(+), 438 deletions(-) (limited to 'src/class') diff --git a/src/class/cdc/cdc_device.c b/src/class/cdc/cdc_device.c index bc16699f1..d8ade9c7f 100644 --- a/src/class/cdc/cdc_device.c +++ b/src/class/cdc/cdc_device.c @@ -45,7 +45,6 @@ // INCLUDE //--------------------------------------------------------------------+ #include "cdc_device.h" -#include "device/control.h" #include "device/usbd_pvt.h" //--------------------------------------------------------------------+ @@ -63,7 +62,7 @@ typedef struct /*------------- From this point, data is not cleared by bus reset -------------*/ char wanted_char; - CFG_TUSB_MEM_ALIGN cdc_line_coding_t line_coding; + cdc_line_coding_t line_coding; // FIFO tu_fifo_t rx_ff; @@ -199,23 +198,23 @@ void cdcd_init(void) for(uint8_t i=0; iwanted_char = -1; + p_cdc->wanted_char = -1; // default line coding is : stop bit = 1, parity = none, data bits = 8 - ser->line_coding.bit_rate = 115200; - ser->line_coding.stop_bits = 0; - ser->line_coding.parity = 0; - ser->line_coding.data_bits = 8; + p_cdc->line_coding.bit_rate = 115200; + p_cdc->line_coding.stop_bits = 0; + p_cdc->line_coding.parity = 0; + p_cdc->line_coding.data_bits = 8; // config fifo - tu_fifo_config(&ser->rx_ff, ser->rx_ff_buf, CFG_TUD_CDC_RX_BUFSIZE, 1, true); - tu_fifo_config(&ser->tx_ff, ser->tx_ff_buf, CFG_TUD_CDC_TX_BUFSIZE, 1, false); + tu_fifo_config(&p_cdc->rx_ff, p_cdc->rx_ff_buf, CFG_TUD_CDC_RX_BUFSIZE, 1, true); + tu_fifo_config(&p_cdc->tx_ff, p_cdc->tx_ff_buf, CFG_TUD_CDC_TX_BUFSIZE, 1, false); #if CFG_FIFO_MUTEX - tu_fifo_config_mutex(&ser->rx_ff, osal_mutex_create(&ser->rx_ff_mutex)); - tu_fifo_config_mutex(&ser->tx_ff, osal_mutex_create(&ser->tx_ff_mutex)); + tu_fifo_config_mutex(&p_cdc->rx_ff, osal_mutex_create(&p_cdc->rx_ff_mutex)); + tu_fifo_config_mutex(&p_cdc->tx_ff, osal_mutex_create(&p_cdc->tx_ff_mutex)); #endif } } @@ -299,57 +298,64 @@ tusb_error_t cdcd_open(uint8_t rhport, tusb_desc_interface_t const * p_interface return TUSB_ERROR_NONE; } -void cdcd_control_request_complete(uint8_t rhport, tusb_control_request_t const * p_request) +// Invoked when class request DATA stage is finished. +// return false to stall control endpoint (e.g Host send non-sense DATA) +bool cdcd_control_request_complete(uint8_t rhport, tusb_control_request_t const * request) { //------------- Class Specific Request -------------// - if (p_request->bmRequestType_bit.type != TUSB_REQ_TYPE_CLASS) return; + TU_VERIFY (request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS); // TODO Support multiple interfaces uint8_t const itf = 0; cdcd_interface_t* p_cdc = &_cdcd_itf[itf]; // Invoke callback - if (CDC_REQUEST_SET_LINE_CODING == p_request->bRequest) { + if ( CDC_REQUEST_SET_LINE_CODING == request->bRequest ) + { if ( tud_cdc_line_coding_cb ) tud_cdc_line_coding_cb(itf, &p_cdc->line_coding); } + + return true; } -tusb_error_t cdcd_control_request(uint8_t rhport, tusb_control_request_t const * p_request, uint16_t bytes_already_sent) +// Handle class control request +// return false to stall control endpoint (e.g unsupported request) +bool cdcd_control_request(uint8_t rhport, tusb_control_request_t const * request) { //------------- Class Specific Request -------------// - if (p_request->bmRequestType_bit.type != TUSB_REQ_TYPE_CLASS) return TUSB_ERROR_DCD_CONTROL_REQUEST_NOT_SUPPORT; + TU_ASSERT(request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS); // TODO Support multiple interfaces uint8_t const itf = 0; cdcd_interface_t* p_cdc = &_cdcd_itf[itf]; - if ((CDC_REQUEST_SET_LINE_CODING == p_request->bRequest) ) - { - uint16_t len = tu_min16(sizeof(cdc_line_coding_t), p_request->wLength); - dcd_edpt_xfer(rhport, 0, (uint8_t*) &p_cdc->line_coding, len); - } - else if ( (CDC_REQUEST_GET_LINE_CODING == p_request->bRequest)) - { - uint16_t len = tu_min16(sizeof(cdc_line_coding_t), p_request->wLength); - dcd_edpt_xfer(rhport, TUSB_DIR_IN_MASK, (uint8_t*) &p_cdc->line_coding, len); - } - else if (CDC_REQUEST_SET_CONTROL_LINE_STATE == p_request->bRequest ) - { - // CDC PSTN v1.2 section 6.3.12 - // Bit 0: Indicates if DTE is present or not. - // This signal corresponds to V.24 signal 108/2 and RS-232 signal DTR (Data Terminal Ready) - // Bit 1: Carrier control for half-duplex modems. - // This signal corresponds to V.24 signal 105 and RS-232 signal RTS (Request to Send) - p_cdc->line_state = (uint8_t) p_request->wValue; - - // Invoke callback - if ( tud_cdc_line_state_cb) tud_cdc_line_state_cb(itf, BIT_TEST_(p_request->wValue, 0), BIT_TEST_(p_request->wValue, 1)); - } - else + switch ( request->bRequest ) { - return TUSB_ERROR_FAILED; // stall unsupported request + case CDC_REQUEST_SET_LINE_CODING: + usbd_control_xfer(rhport, request, &p_cdc->line_coding, sizeof(cdc_line_coding_t)); + break; + + case CDC_REQUEST_GET_LINE_CODING: + usbd_control_xfer(rhport, request, &p_cdc->line_coding, sizeof(cdc_line_coding_t)); + break; + + case CDC_REQUEST_SET_CONTROL_LINE_STATE: + // CDC PSTN v1.2 section 6.3.12 + // Bit 0: Indicates if DTE is present or not. + // This signal corresponds to V.24 signal 108/2 and RS-232 signal DTR (Data Terminal Ready) + // Bit 1: Carrier control for half-duplex modems. + // This signal corresponds to V.24 signal 105 and RS-232 signal RTS (Request to Send) + p_cdc->line_state = (uint8_t) request->wValue; + + // Invoke callback + if ( tud_cdc_line_state_cb) tud_cdc_line_state_cb(itf, BIT_TEST_(request->wValue, 0), BIT_TEST_(request->wValue, 1)); + usbd_control_status(rhport, request); + break; + + default: return false; // stall unsupported request } - return TUSB_ERROR_NONE; + + return true; } tusb_error_t cdcd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, uint32_t xferred_bytes) diff --git a/src/class/cdc/cdc_device.h b/src/class/cdc/cdc_device.h index 9d0b93c6d..749351a54 100644 --- a/src/class/cdc/cdc_device.h +++ b/src/class/cdc/cdc_device.h @@ -114,8 +114,8 @@ ATTR_WEAK void tud_cdc_line_coding_cb(uint8_t itf, cdc_line_coding_t const* p_li void cdcd_init (void); tusb_error_t cdcd_open (uint8_t rhport, tusb_desc_interface_t const * p_interface_desc, uint16_t *p_length); -tusb_error_t cdcd_control_request (uint8_t rhport, tusb_control_request_t const * p_request, uint16_t bytes_already_sent); -void cdcd_control_request_complete (uint8_t rhport, tusb_control_request_t const * p_request); +bool cdcd_control_request (uint8_t rhport, tusb_control_request_t const * p_request); +bool cdcd_control_request_complete (uint8_t rhport, tusb_control_request_t const * p_request); tusb_error_t cdcd_xfer_cb (uint8_t rhport, uint8_t edpt_addr, tusb_event_t event, uint32_t xferred_bytes); void cdcd_reset (uint8_t rhport); diff --git a/src/class/custom/custom_device.c b/src/class/custom/custom_device.c index 1b36f1331..cc440fc7e 100644 --- a/src/class/custom/custom_device.c +++ b/src/class/custom/custom_device.c @@ -89,9 +89,9 @@ tusb_error_t cusd_open(uint8_t rhport, tusb_desc_interface_t const * p_desc_itf, return TUSB_ERROR_NONE; } -tusb_error_t cusd_control_request(uint8_t rhport, tusb_control_request_t const * p_request) +bool cusd_control_request(uint8_t rhport, tusb_control_request_t const * p_request) { - return TUSB_ERROR_DCD_CONTROL_REQUEST_NOT_SUPPORT; + return false; } tusb_error_t cusd_xfer_cb(uint8_t rhport, uint8_t edpt_addr, tusb_event_t event, uint32_t xferred_bytes) diff --git a/src/class/custom/custom_device.h b/src/class/custom/custom_device.h index 116c6897d..704c4127b 100644 --- a/src/class/custom/custom_device.h +++ b/src/class/custom/custom_device.h @@ -64,8 +64,8 @@ void cusd_init(void); tusb_error_t cusd_open(uint8_t rhport, tusb_desc_interface_t const * p_interface_desc, uint16_t *p_length); -tusb_error_t cusd_control_request_st(uint8_t rhport, tusb_control_request_t const * p_request); -void cusd_control_request_complete (uint8_t rhport, tusb_control_request_t const * p_request); +bool cusd_control_request_st(uint8_t rhport, tusb_control_request_t const * p_request); +bool cusd_control_request_complete (uint8_t rhport, tusb_control_request_t const * p_request); tusb_error_t cusd_xfer_cb(uint8_t rhport, uint8_t edpt_addr, tusb_event_t event, uint32_t xferred_bytes); void cusd_reset(uint8_t rhport); #endif diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index efa602ad6..b5586a488 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -46,7 +46,6 @@ //--------------------------------------------------------------------+ #include "common/tusb_common.h" #include "hid_device.h" -#include "device/control.h" #include "device/usbd_pvt.h" //--------------------------------------------------------------------+ @@ -403,110 +402,112 @@ tusb_error_t hidd_open(uint8_t rhport, tusb_desc_interface_t const * desc_itf, u return TUSB_ERROR_NONE; } -tusb_error_t hidd_control_request(uint8_t rhport, tusb_control_request_t const * p_request, uint16_t bytes_already_sent) +// Handle class control request +// return false to stall control endpoint (e.g unsupported request) +bool hidd_control_request(uint8_t rhport, tusb_control_request_t const * p_request) { hidd_interface_t* p_hid = get_interface_by_itfnum( (uint8_t) p_request->wIndex ); - TU_ASSERT(p_hid, TUSB_ERROR_FAILED); + TU_ASSERT(p_hid); - //------------- STD Request -------------// if (p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD) { + //------------- STD Request -------------// uint8_t const desc_type = tu_u16_high(p_request->wValue); uint8_t const desc_index = tu_u16_low (p_request->wValue); (void) desc_index; if (p_request->bRequest == TUSB_REQ_GET_DESCRIPTOR && desc_type == HID_DESC_TYPE_REPORT) { - // TODO: Handle zero length packet. - uint16_t remaining_bytes = p_hid->desc_len - bytes_already_sent; - if (remaining_bytes > 64) { - remaining_bytes = 64; - } - memcpy(_shared_control_buffer, p_hid->desc_report + bytes_already_sent, remaining_bytes); - - dcd_edpt_xfer(rhport, TUSB_DIR_IN_MASK, _shared_control_buffer, remaining_bytes); + usbd_control_xfer(rhport, p_request, p_hid->desc_report, p_hid->desc_len); }else { - return TUSB_ERROR_FAILED; + return false; // stall unsupported request } } - //------------- Class Specific Request -------------// else if (p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS) { - if( HID_REQ_CONTROL_GET_REPORT == p_request->bRequest ) + //------------- Class Specific Request -------------// + switch( p_request->bRequest ) { - // wValue = Report Type | Report ID - uint8_t const report_type = tu_u16_high(p_request->wValue); - uint8_t const report_id = tu_u16_low(p_request->wValue); - - uint16_t xferlen; - if ( p_hid->get_report_cb ) + case HID_REQ_CONTROL_GET_REPORT: { - xferlen = p_hid->get_report_cb(report_id, (hid_report_type_t) report_type, p_hid->report_buf, p_request->wLength); - }else + // wValue = Report Type | Report ID + uint8_t const report_type = tu_u16_high(p_request->wValue); + uint8_t const report_id = tu_u16_low(p_request->wValue); + + uint16_t xferlen; + if ( p_hid->get_report_cb ) + { + xferlen = p_hid->get_report_cb(report_id, (hid_report_type_t) report_type, p_hid->report_buf, p_request->wLength); + }else + { + // For boot Interface only: re-use report_buf -> report has no change + xferlen = p_request->wLength; + } + + TU_ASSERT( xferlen > 0 ); + usbd_control_xfer(rhport, p_request, p_hid->report_buf, xferlen); + } + break; + + case HID_REQ_CONTROL_SET_REPORT: + usbd_control_xfer(rhport, p_request, p_hid->report_buf, p_request->wLength); + break; + + case HID_REQ_CONTROL_SET_IDLE: + // TODO idle rate of report + p_hid->idle_rate = tu_u16_high(p_request->wValue); + usbd_control_status(rhport, p_request); + break; + + case HID_REQ_CONTROL_GET_IDLE: + // TODO idle rate of report + usbd_control_xfer(rhport, p_request, &p_hid->idle_rate, 1); + break; + + case HID_REQ_CONTROL_GET_PROTOCOL: { - // For boot Interface only: re-use report_buf -> report has no change - xferlen = p_request->wLength; + uint8_t protocol = 1-p_hid->boot_protocol; // 0 is Boot, 1 is Report protocol + usbd_control_xfer(rhport, p_request, &protocol, 1); } + break; - TU_ASSERT( xferlen > 0 ); - dcd_edpt_xfer(rhport, TUSB_DIR_IN_MASK, _shared_control_buffer, xferlen); - } - else if ( HID_REQ_CONTROL_SET_REPORT == p_request->bRequest ) - { - dcd_edpt_xfer(rhport, 0, _shared_control_buffer, p_request->wLength); - } - else if (HID_REQ_CONTROL_SET_IDLE == p_request->bRequest) - { - // TODO idle rate of report - p_hid->idle_rate = tu_u16_high(p_request->wValue); - } - else if (HID_REQ_CONTROL_GET_IDLE == p_request->bRequest) - { - // TODO idle rate of report - _shared_control_buffer[0] = p_hid->idle_rate; - dcd_edpt_xfer(rhport, TUSB_DIR_IN_MASK, _shared_control_buffer, 1); - } - else if (HID_REQ_CONTROL_GET_PROTOCOL == p_request->bRequest ) - { - _shared_control_buffer[0] = 1-p_hid->boot_protocol; // 0 is Boot, 1 is Report protocol - dcd_edpt_xfer(rhport, TUSB_DIR_IN_MASK, _shared_control_buffer, 1); - } - else if (HID_REQ_CONTROL_SET_PROTOCOL == p_request->bRequest ) - { - p_hid->boot_protocol = 1 - p_request->wValue; // 0 is Boot, 1 is Report protocol - }else - { - return TUSB_ERROR_FAILED; + case HID_REQ_CONTROL_SET_PROTOCOL: + p_hid->boot_protocol = 1 - p_request->wValue; // 0 is Boot, 1 is Report protocol + usbd_control_status(rhport, p_request); + break; + + default: return false; // stall unsupported request } }else { - return TUSB_ERROR_FAILED; + return false; // stall unsupported request } - return TUSB_ERROR_NONE; + + return true; } -void hidd_control_request_complete(uint8_t rhport, tusb_control_request_t const * p_request) +// Invoked when class request DATA stage is finished. +// return false to stall control endpoint (e.g Host send non-sense DATA) +bool hidd_control_request_complete(uint8_t rhport, tusb_control_request_t const * p_request) { hidd_interface_t* p_hid = get_interface_by_itfnum( (uint8_t) p_request->wIndex ); - if (p_hid == NULL) { - return; - } + TU_ASSERT(p_hid); - if (p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS) + if (p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS && + p_request->bRequest == HID_REQ_CONTROL_SET_REPORT) { - if ( HID_REQ_CONTROL_SET_REPORT == p_request->bRequest ) - { - // wValue = Report Type | Report ID - uint8_t const report_type = tu_u16_high(p_request->wValue); - uint8_t const report_id = tu_u16_low(p_request->wValue); + // wValue = Report Type | Report ID + uint8_t const report_type = tu_u16_high(p_request->wValue); + uint8_t const report_id = tu_u16_low(p_request->wValue); - if ( p_hid->set_report_cb ) - { - p_hid->set_report_cb(report_id, (hid_report_type_t) report_type, _shared_control_buffer, p_request->wLength); - } + if ( p_hid->set_report_cb ) + { + p_hid->set_report_cb(report_id, (hid_report_type_t) report_type, p_hid->report_buf, p_request->wLength); } } + + return true; } tusb_error_t hidd_xfer_cb(uint8_t rhport, uint8_t edpt_addr, tusb_event_t event, uint32_t xferred_bytes) diff --git a/src/class/hid/hid_device.h b/src/class/hid/hid_device.h index 1dc40af57..7f8cd0fa7 100644 --- a/src/class/hid/hid_device.h +++ b/src/class/hid/hid_device.h @@ -378,8 +378,8 @@ ATTR_WEAK void tud_hid_mouse_set_report_cb(uint8_t report_id, hid_report_type_t void hidd_init(void); tusb_error_t hidd_open(uint8_t rhport, tusb_desc_interface_t const * p_interface_desc, uint16_t *p_length); -tusb_error_t hidd_control_request(uint8_t rhport, tusb_control_request_t const * p_request, uint16_t bytes_already_sent); -void hidd_control_request_complete (uint8_t rhport, tusb_control_request_t const * p_request); +bool hidd_control_request(uint8_t rhport, tusb_control_request_t const * p_request); +bool hidd_control_request_complete (uint8_t rhport, tusb_control_request_t const * p_request); tusb_error_t hidd_xfer_cb(uint8_t rhport, uint8_t edpt_addr, tusb_event_t event, uint32_t xferred_bytes); void hidd_reset(uint8_t rhport); @@ -390,3 +390,4 @@ void hidd_reset(uint8_t rhport); #endif #endif /* _TUSB_HID_DEVICE_H_ */ + diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index 32ad90102..92bc4c6c8 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -47,7 +47,6 @@ #include "common/tusb_common.h" #include "msc_device.h" -#include "device/control.h" #include "device/usbd_pvt.h" //--------------------------------------------------------------------+ @@ -60,7 +59,31 @@ enum MSC_STAGE_STATUS }; -CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN mscd_interface_t _mscd_itf; +typedef struct { + CFG_TUSB_MEM_ALIGN msc_cbw_t cbw; + +//#if defined (__ICCARM__) && (CFG_TUSB_MCU == OPT_MCU_LPC11UXX || CFG_TUSB_MCU == OPT_MCU_LPC13UXX) +// uint8_t padding1[64-sizeof(msc_cbw_t)]; // IAR cannot align struct's member +//#endif + + CFG_TUSB_MEM_ALIGN msc_csw_t csw; + + uint8_t itf_num; + uint8_t ep_in; + uint8_t ep_out; + + // Bulk Only Transfer (BOT) Protocol + uint8_t stage; + uint32_t total_len; + uint32_t xferred_len; // numbered of bytes transferred so far in the Data Stage + + // Sense Response Data + uint8_t sense_key; + uint8_t add_sense_code; + uint8_t add_sense_qualifier; +}mscd_interface_t; + +CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN static mscd_interface_t _mscd_itf; CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN static uint8_t _mscd_buf[CFG_TUD_MSC_BUFSIZE]; //--------------------------------------------------------------------+ @@ -147,29 +170,39 @@ tusb_error_t mscd_open(uint8_t rhport, tusb_desc_interface_t const * p_desc_itf, return TUSB_ERROR_NONE; } -tusb_error_t mscd_control_request(uint8_t rhport, tusb_control_request_t const * p_request, uint16_t bytes_already_sent) +// Handle class control request +// return false to stall control endpoint (e.g unsupported request) +bool mscd_control_request(uint8_t rhport, tusb_control_request_t const * p_request) { - TU_ASSERT(p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS, TUSB_ERROR_DCD_CONTROL_REQUEST_NOT_SUPPORT); + TU_ASSERT(p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS); - if(MSC_REQ_RESET == p_request->bRequest) - { - // TODO: Actually reset. - } - else if (MSC_REQ_GET_MAX_LUN == p_request->bRequest) + switch ( p_request->bRequest ) { - // returned MAX LUN is minus 1 by specs - _shared_control_buffer[0] = CFG_TUD_MSC_MAXLUN-1; - dcd_edpt_xfer(rhport, TUSB_DIR_IN_MASK, _shared_control_buffer, 1); - }else - { - return TUSB_ERROR_FAILED; // stall unsupported request + case MSC_REQ_RESET: + // TODO: Actually reset interface. + usbd_control_status(rhport, p_request); + break; + + case MSC_REQ_GET_MAX_LUN: + { + // returned MAX LUN is minus 1 by specs + uint8_t maxlun = CFG_TUD_MSC_MAXLUN-1; + usbd_control_xfer(rhport, p_request, &maxlun, 1); + } + break; + + default: return false; // stall unsupported request } - return TUSB_ERROR_NONE; + + return true; } -void mscd_control_request_complete(uint8_t rhport, tusb_control_request_t const * p_request) +// Invoked when class request DATA stage is finished. +// return false to stall control endpoint (e.g Host send non-sense DATA) +bool mscd_control_request_complete(uint8_t rhport, tusb_control_request_t const * p_request) { - return; + // nothing to do + return true; } // For backwards compatibility we support static block counts. @@ -296,7 +329,7 @@ int32_t proc_builtin_scsi(msc_cbw_t const * p_cbw, uint8_t* buffer, uint32_t buf return ret; } -tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, uint8_t event, uint32_t xferred_bytes) +tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, tusb_event_t event, uint32_t xferred_bytes) { mscd_interface_t* p_msc = &_mscd_itf; msc_cbw_t const * p_cbw = &p_msc->cbw; diff --git a/src/class/msc/msc_device.h b/src/class/msc/msc_device.h index ac3eade22..d08d9f9cb 100644 --- a/src/class/msc/msc_device.h +++ b/src/class/msc/msc_device.h @@ -81,32 +81,6 @@ TU_VERIFY_STATIC(CFG_TUD_MSC_BUFSIZE < UINT16_MAX, "Size is not correct"); extern "C" { #endif -typedef struct { - CFG_TUSB_MEM_ALIGN msc_cbw_t cbw; - -//#if defined (__ICCARM__) && (CFG_TUSB_MCU == OPT_MCU_LPC11UXX || CFG_TUSB_MCU == OPT_MCU_LPC13UXX) -// uint8_t padding1[64-sizeof(msc_cbw_t)]; // IAR cannot align struct's member -//#endif - - CFG_TUSB_MEM_ALIGN msc_csw_t csw; - - uint8_t itf_num; - uint8_t ep_in; - uint8_t ep_out; - - // Bulk Only Transfer (BOT) Protocol - uint8_t stage; - uint32_t total_len; - uint32_t xferred_len; // numbered of bytes transferred so far in the Data Stage - - // Sense Response Data - uint8_t sense_key; - uint8_t add_sense_code; - uint8_t add_sense_qualifier; -}mscd_interface_t; - -extern mscd_interface_t _mscd_itf; - /** \addtogroup ClassDriver_MSC * @{ * \defgroup MSC_Device Device @@ -198,8 +172,8 @@ ATTR_WEAK bool tud_lun_capacity_cb(uint8_t lun, uint32_t* last_valid_sector, uin void mscd_init(void); tusb_error_t mscd_open(uint8_t rhport, tusb_desc_interface_t const * p_interface_desc, uint16_t *p_length); -tusb_error_t mscd_control_request(uint8_t rhport, tusb_control_request_t const * p_request, uint16_t bytes_already_sent); -void mscd_control_request_complete (uint8_t rhport, tusb_control_request_t const * p_request); +bool mscd_control_request(uint8_t rhport, tusb_control_request_t const * p_request); +bool mscd_control_request_complete (uint8_t rhport, tusb_control_request_t const * p_request); tusb_error_t mscd_xfer_cb(uint8_t rhport, uint8_t edpt_addr, tusb_event_t event, uint32_t xferred_bytes); void mscd_reset(uint8_t rhport); diff --git a/src/common/tusb_types.h b/src/common/tusb_types.h index 5c226f556..32632cd90 100644 --- a/src/common/tusb_types.h +++ b/src/common/tusb_types.h @@ -203,12 +203,14 @@ typedef enum TUSB_EVENT_XFER_STALLED, }tusb_event_t; -enum { +enum +{ DESC_OFFSET_LEN = 0, DESC_OFFSET_TYPE = 1 }; -enum { +enum +{ INTERFACE_INVALID_NUMBER = 0xff }; diff --git a/src/device/control.c b/src/device/control.c index 35ae536e1..7ab1e16ab 100644 --- a/src/device/control.c +++ b/src/device/control.c @@ -46,216 +46,125 @@ #include "control.h" #include "device/usbd_pvt.h" +enum +{ + EDPT_CTRL_OUT = 0x00, + EDPT_CTRL_IN = 0x80 +}; + +typedef struct { + tusb_control_request_t request; + + void* buffer; + uint16_t total_len; + uint16_t total_transferred; + + bool (*complete_cb) (uint8_t, tusb_control_request_t const * ); +} control_t; + control_t control_state; -CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN uint8_t _shared_control_buffer[64]; +CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN uint8_t _usbd_ctrl_buf[CFG_TUD_ENDOINT0_SIZE]; -void controld_reset(uint8_t rhport) { - control_state.current_stage = CONTROL_STAGE_SETUP; +void usbd_control_reset (uint8_t rhport) +{ + tu_varclr(&control_state); } -// Helper to send STATUS (zero length) packet -// Note dir is value of direction bit in setup packet (i.e DATA stage direction) -static inline bool dcd_control_status(uint8_t rhport, uint8_t dir) +void usbd_control_stall(uint8_t rhport) { - uint8_t ep_addr = 0; - // Invert the direction. - if (dir == TUSB_DIR_OUT) { - ep_addr |= TUSB_DIR_IN_MASK; - } - // status direction is reversed to one in the setup packet - return dcd_edpt_xfer(rhport, ep_addr, NULL, 0); + dcd_edpt_stall(rhport, 0); } -static inline void dcd_control_stall(uint8_t rhport) +bool usbd_control_status(uint8_t rhport, tusb_control_request_t const * request) { - dcd_edpt_stall(rhport, 0 | TUSB_DIR_IN_MASK); + // status direction is reversed to one in the setup packet + return dcd_edpt_xfer(rhport, request->bmRequestType_bit.direction ? EDPT_CTRL_OUT : EDPT_CTRL_IN, NULL, 0); } -// return len of descriptor and change pointer to descriptor's buffer -static uint16_t get_descriptor(uint8_t rhport, tusb_control_request_t const * const p_request, uint8_t const ** pp_buffer) +// Each transaction is up to endpoint0's max packet size +static bool start_control_data_xact(uint8_t rhport) { - (void) rhport; - - tusb_desc_type_t const desc_type = (tusb_desc_type_t) tu_u16_high(p_request->wValue); - uint8_t const desc_index = tu_u16_low( p_request->wValue ); + uint16_t const xact_len = tu_min16(control_state.total_len - control_state.total_transferred, CFG_TUD_ENDOINT0_SIZE); - uint8_t const * desc_data = NULL ; - uint16_t len = 0; + uint8_t ep_addr = EDPT_CTRL_OUT; - switch(desc_type) + if ( control_state.request.bmRequestType_bit.direction == TUSB_DIR_IN ) { - case TUSB_DESC_DEVICE: - desc_data = (uint8_t const *) usbd_desc_set->device; - len = sizeof(tusb_desc_device_t); - break; - - case TUSB_DESC_CONFIGURATION: - desc_data = (uint8_t const *) usbd_desc_set->config; - len = ((tusb_desc_configuration_t const*) desc_data)->wTotalLength; - break; - - case TUSB_DESC_STRING: - // String Descriptor always uses the desc set from user - if ( desc_index < tud_desc_set.string_count ) - { - desc_data = tud_desc_set.string_arr[desc_index]; - TU_VERIFY( desc_data != NULL, 0 ); - - len = desc_data[0]; // first byte of descriptor is its size - }else - { - // out of range - /* The 0xee string is indeed a Microsoft USB extension. - * It can be used to tell Windows what driver it should use for the device !!! - */ - return 0; - } - break; - - case TUSB_DESC_DEVICE_QUALIFIER: - // TODO If not highspeed capable stall this request otherwise - // return the descriptor that could work in highspeed - return 0; - break; - - default: return 0; + ep_addr = EDPT_CTRL_IN; + memcpy(_usbd_ctrl_buf, control_state.buffer, xact_len); } - TU_ASSERT( desc_data != NULL, 0); - - // up to Host's length - len = tu_min16(p_request->wLength, len ); - (*pp_buffer) = desc_data; - - return len; + return dcd_edpt_xfer(rhport, ep_addr, _usbd_ctrl_buf, xact_len); } -tusb_error_t controld_xfer_cb(uint8_t rhport, uint8_t edpt_addr, tusb_event_t event, uint32_t xferred_bytes) { - if (control_state.current_stage == CONTROL_STAGE_STATUS && xferred_bytes == 0) { - control_state.current_stage = CONTROL_STAGE_SETUP; - return TUSB_ERROR_NONE; - } - tusb_error_t error = TUSB_ERROR_NONE; - control_state.total_transferred += xferred_bytes; - tusb_control_request_t const *p_request = &control_state.current_request; - - if (p_request->wLength == control_state.total_transferred || xferred_bytes < 64) { - control_state.current_stage = CONTROL_STAGE_STATUS; - dcd_control_status(rhport, p_request->bmRequestType_bit.direction); - - // Do the user callback after queueing the STATUS packet because the callback could be slow. - if ( TUSB_REQ_RCPT_INTERFACE == p_request->bmRequestType_bit.recipient ) - { - tud_control_interface_control_complete_cb(rhport, tu_u16_low(p_request->wIndex), p_request); - } - } else { - if (TUSB_REQ_RCPT_INTERFACE == p_request->bmRequestType_bit.recipient) { - error = tud_control_interface_control_cb(rhport, tu_u16_low(p_request->wIndex), p_request, control_state.total_transferred); - } else { - error = controld_process_control_request(rhport, p_request, control_state.total_transferred); - } - } - return error; +// TODO may find a better way +void usbd_control_set_complete_callback( bool (*fp) (uint8_t, tusb_control_request_t const * ) ) +{ + control_state.complete_cb = fp; } -// This tracks the state of a control request. -tusb_error_t controld_process_setup_request(uint8_t rhport, tusb_control_request_t const * p_request) { - tusb_error_t error = TUSB_ERROR_NONE; - memcpy(&control_state.current_request, p_request, sizeof(tusb_control_request_t)); - if (p_request->wLength == 0) { - control_state.current_stage = CONTROL_STAGE_STATUS; - } else { - control_state.current_stage = CONTROL_STAGE_DATA; - control_state.total_transferred = 0; - } +bool usbd_control_xfer(uint8_t rhport, tusb_control_request_t const * request, void* buffer, uint16_t len) +{ + control_state.request = (*request); + control_state.buffer = buffer; + control_state.total_len = tu_min16(len, request->wLength); + control_state.total_transferred = 0; - if ( TUSB_REQ_RCPT_INTERFACE == p_request->bmRequestType_bit.recipient ) + if ( buffer != NULL && len ) { - error = tud_control_interface_control_cb(rhport, tu_u16_low(p_request->wIndex), p_request, 0); - } else { - error = controld_process_control_request(rhport, p_request, 0); + // Data stage + TU_ASSERT( start_control_data_xact(rhport) ); + }else + { + // Status stage + TU_ASSERT( usbd_control_status(rhport, request) ); } - if (error != TUSB_ERROR_NONE) { - dcd_control_stall(rhport); // Stall errored requests - } else if (control_state.current_stage == CONTROL_STAGE_STATUS) { - dcd_control_status(rhport, p_request->bmRequestType_bit.direction); - } - return error; + return true; } -// This handles the actual request and its response. -tusb_error_t controld_process_control_request(uint8_t rhport, tusb_control_request_t const * p_request, uint16_t bytes_already_sent) +// callback when a transaction complete on DATA stage of control endpoint +tusb_error_t usbd_control_xfer_cb (uint8_t rhport, uint8_t ep_addr, tusb_event_t event, uint32_t xferred_bytes) { - tusb_error_t error = TUSB_ERROR_NONE; - uint8_t ep_addr = 0; - if (p_request->bmRequestType_bit.direction == TUSB_DIR_IN) { - ep_addr |= TUSB_DIR_IN_MASK; + if ( control_state.request.bmRequestType_bit.direction == TUSB_DIR_OUT ) + { + memcpy(control_state.buffer, _usbd_ctrl_buf, xferred_bytes); } - //------------- Standard Request e.g in enumeration -------------// - if( TUSB_REQ_RCPT_DEVICE == p_request->bmRequestType_bit.recipient && - TUSB_REQ_TYPE_STANDARD == p_request->bmRequestType_bit.type ) { - switch (p_request->bRequest) { - case TUSB_REQ_GET_DESCRIPTOR: { - uint8_t const * buffer = NULL; - uint16_t const len = get_descriptor(rhport, p_request, &buffer); - - if (len) { - uint16_t remaining_bytes = len - bytes_already_sent; - if (remaining_bytes > 64) { - remaining_bytes = 64; - } - memcpy(_shared_control_buffer, buffer + bytes_already_sent, remaining_bytes); - dcd_edpt_xfer(rhport, ep_addr, _shared_control_buffer, remaining_bytes); - } else { - return TUSB_ERROR_FAILED; - } - break; - } - case TUSB_REQ_GET_CONFIGURATION: - memcpy(_shared_control_buffer, &control_state.config, 1); - dcd_edpt_xfer(rhport, ep_addr, _shared_control_buffer, 1); - break; - case TUSB_REQ_SET_ADDRESS: - dcd_set_address(rhport, (uint8_t) p_request->wValue); - break; - case TUSB_REQ_SET_CONFIGURATION: - control_state.config = p_request->wValue; - tud_control_set_config_cb (rhport, control_state.config); - break; - default: - return TUSB_ERROR_FAILED; + control_state.total_transferred += xferred_bytes; + control_state.buffer += xferred_bytes; + + if ( control_state.total_len == control_state.total_transferred || xferred_bytes < CFG_TUD_ENDOINT0_SIZE ) + { + // DATA stage is complete + bool is_ok = true; + + // invoke complete callback if set + // callback can still stall control in status phase e.g out data does not make sense + if ( control_state.complete_cb ) + { + is_ok = control_state.complete_cb(rhport, &control_state.request); } - } else if (p_request->bmRequestType_bit.recipient == TUSB_REQ_RCPT_ENDPOINT && - p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD) { - //------------- Endpoint Request -------------// - switch (p_request->bRequest) { - case TUSB_REQ_GET_STATUS: { - uint16_t status = dcd_edpt_stalled(rhport, tu_u16_low(p_request->wIndex)) ? 0x0001 : 0x0000; - memcpy(_shared_control_buffer, &status, 2); - - dcd_edpt_xfer(rhport, ep_addr, _shared_control_buffer, 2); - break; - } - case TUSB_REQ_CLEAR_FEATURE: - // only endpoint feature is halted/stalled - dcd_edpt_clear_stall(rhport, tu_u16_low(p_request->wIndex)); - break; - case TUSB_REQ_SET_FEATURE: - // only endpoint feature is halted/stalled - dcd_edpt_stall(rhport, tu_u16_low(p_request->wIndex)); - break; - default: - return TUSB_ERROR_FAILED; + + if ( is_ok ) + { + // Send status + TU_ASSERT( usbd_control_status(rhport, &control_state.request), TUSB_ERROR_FAILED ); + }else + { + // stall due to callback + usbd_control_stall(rhport); } - } else { - //------------- Unsupported Request -------------// - return TUSB_ERROR_FAILED; } - return error; + else + { + // More data to transfer + TU_ASSERT(start_control_data_xact(rhport), TUSB_ERROR_FAILED); + } + + return TUSB_ERROR_NONE; } #endif diff --git a/src/device/control.h b/src/device/control.h index e8dcf76f9..e1709bcee 100644 --- a/src/device/control.h +++ b/src/device/control.h @@ -48,44 +48,6 @@ #include "tusb.h" -typedef enum { - CONTROL_STAGE_SETUP, // Waiting for a setup token. - CONTROL_STAGE_DATA, // In the process of sending or receiving data. - CONTROL_STAGE_STATUS // In the process of transmitting the STATUS ZLP. -} control_stage_t; - -typedef struct { - control_stage_t current_stage; - tusb_control_request_t current_request; - uint16_t total_transferred; - uint8_t config; -} control_t; - -extern uint8_t _shared_control_buffer[64]; - -tusb_error_t controld_process_setup_request(uint8_t rhport, tusb_control_request_t const * const p_request); - -// Callback when the configuration of the device is changed. -tusb_error_t tud_control_set_config_cb(uint8_t rhport, uint8_t config_number); - -// Called when the DATA stage of a control transaction is complete. -void tud_control_interface_control_complete_cb(uint8_t rhport, uint8_t interface, tusb_control_request_t const * const p_request); - -tusb_error_t tud_control_interface_control_cb(uint8_t rhport, uint8_t interface, tusb_control_request_t const * const p_request, uint16_t bytes_already_sent); - -//--------------------------------------------------------------------+ -// INTERNAL API -//--------------------------------------------------------------------+ -tusb_error_t controld_open(uint8_t rhport, tusb_desc_interface_t const * p_interface_desc, uint16_t *p_length); - -// This tracks the state of a control request. -tusb_error_t controld_process_setup_request(uint8_t rhport, tusb_control_request_t const * p_request); - -// This handles the actual request and its response. -tusb_error_t controld_process_control_request(uint8_t rhport, tusb_control_request_t const * p_request, uint16_t bytes_already_sent); - -tusb_error_t controld_xfer_cb(uint8_t rhport, uint8_t edpt_addr, tusb_event_t event, uint32_t xferred_bytes); -void controld_reset(uint8_t rhport); #ifdef __cplusplus } diff --git a/src/device/dcd.h b/src/device/dcd.h index ff836f405..bd0ea852e 100644 --- a/src/device/dcd.h +++ b/src/device/dcd.h @@ -124,6 +124,10 @@ void dcd_event_xfer_complete (uint8_t rhport, uint8_t ep_addr, uint32_t xferred_ /*------------------------------------------------------------------*/ /* Endpoint API + * Note: + * - Address of control endpoint OUT is 0x00, In is 0x80 + * - When stalling control endpoint both control OUT and IN must be stalled + * (according to USB spec, stalled control is only recovered with setup token) *------------------------------------------------------------------*/ bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc); bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes); diff --git a/src/device/usbd.c b/src/device/usbd.c index 13cc7f332..e9ac24c4b 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -68,11 +68,10 @@ typedef struct { uint8_t config_num; - // map interface number to driver (0xff is invalid) - uint8_t itf2drv[16]; + uint8_t itf2drv[16]; // map interface number to driver (0xff is invalid) + uint8_t ep2drv[2][8]; // map endpoint to driver ( 0xff is invalid ) + - // map endpoint to driver ( 0xff is invalid ) - uint8_t ep2drv[2][8]; }usbd_device_t; static usbd_device_t _usbd_dev; @@ -94,9 +93,8 @@ typedef struct { void (* init ) (void); tusb_error_t (* open ) (uint8_t rhport, tusb_desc_interface_t const * desc_intf, uint16_t* p_length); - // Control request is called one or more times for a request and can queue multiple data packets. - tusb_error_t (* control_request ) (uint8_t rhport, tusb_control_request_t const *, uint16_t bytes_already_sent); - void (* control_request_complete ) (uint8_t rhport, tusb_control_request_t const *); + bool (* control_request ) (uint8_t rhport, tusb_control_request_t const * request); + bool (* control_request_complete ) (uint8_t rhport, tusb_control_request_t const * request); tusb_error_t (* xfer_cb ) (uint8_t rhport, uint8_t ep_addr, tusb_event_t, uint32_t); void (* sof ) (uint8_t rhport); void (* reset ) (uint8_t); @@ -171,9 +169,16 @@ OSAL_QUEUE_DEF(_usbd_qdef, CFG_TUD_TASK_QUEUE_SZ, dcd_event_t); static osal_queue_t _usbd_q; //--------------------------------------------------------------------+ -// INTERNAL FUNCTION +// Prototypes //--------------------------------------------------------------------+ static void mark_interface_endpoint(uint8_t const* p_desc, uint16_t desc_len, uint8_t driver_id); +static bool process_control_request(uint8_t rhport, tusb_control_request_t const * p_request); +static bool process_set_config(uint8_t rhport, uint8_t config_number); +static void const* get_descriptor(tusb_control_request_t const * p_request, uint16_t* desc_len); + +void usbd_control_reset (uint8_t rhport); +tusb_error_t usbd_control_xfer_cb (uint8_t rhport, uint8_t ep_addr, tusb_event_t event, uint32_t xferred_bytes); +void usbd_control_set_complete_callback( bool (*fp) (uint8_t, tusb_control_request_t const * ) ); //--------------------------------------------------------------------+ // APPLICATION API @@ -184,7 +189,7 @@ bool tud_mounted(void) } //--------------------------------------------------------------------+ -// IMPLEMENTATION +// USBD Task //--------------------------------------------------------------------+ tusb_error_t usbd_init (void) { @@ -214,7 +219,7 @@ static void usbd_reset(uint8_t rhport) memset(_usbd_dev.itf2drv, 0xff, sizeof(_usbd_dev.itf2drv)); // invalid mapping memset(_usbd_dev.ep2drv , 0xff, sizeof(_usbd_dev.ep2drv )); // invalid mapping - controld_reset(rhport); + usbd_control_reset(rhport); for (uint8_t i = 0; i < USBD_CLASS_DRIVER_COUNT; i++) { @@ -222,20 +227,24 @@ static void usbd_reset(uint8_t rhport) } } +// Main device task implementation static void usbd_task_body(void) { - dcd_event_t event; - // Loop until there is no more events in the queue while (1) { + dcd_event_t event; + if ( !osal_queue_receive(_usbd_q, &event) ) return; switch ( event.event_id ) { case DCD_EVENT_SETUP_RECEIVED: - // Setup tokens are unique to the Control endpoint so we delegate to it directly. - controld_process_setup_request(event.rhport, &event.setup_received); + // Process control request, if failed control endpoint is stalled + if ( !process_control_request(event.rhport, &event.setup_received) ) + { + usbd_control_stall(event.rhport); + } break; case DCD_EVENT_XFER_COMPLETE: @@ -245,8 +254,8 @@ static void usbd_task_body(void) if ( 0 == edpt_number(ep_addr) ) { - // control transfer - controld_xfer_cb(event.rhport, ep_addr, event.xfer_complete.result, event.xfer_complete.len); + // control transfer DATA stage callback + usbd_control_xfer_cb(event.rhport, ep_addr, event.xfer_complete.result, event.xfer_complete.len); } else { @@ -312,66 +321,142 @@ void usbd_task( void* param) #endif } -void tud_control_interface_control_complete_cb(uint8_t rhport, uint8_t interface, tusb_control_request_t const * const p_request) { - if (_usbd_dev.itf2drv[ interface ] < USBD_CLASS_DRIVER_COUNT) +//--------------------------------------------------------------------+ +// Control Request Parser & Handling +//--------------------------------------------------------------------+ + +// This handles the actual request and its response. +// return false will cause its caller to stall control endpoint +static bool process_control_request(uint8_t rhport, tusb_control_request_t const * p_request) +{ + usbd_control_set_complete_callback(NULL); + + if ( TUSB_REQ_RCPT_DEVICE == p_request->bmRequestType_bit.recipient && + TUSB_REQ_TYPE_STANDARD == p_request->bmRequestType_bit.type ) + { + //------------- Standard Device Requests e.g in enumeration -------------// + void* data_buf = NULL; + uint16_t data_len = 0; + + switch ( p_request->bRequest ) { - const usbd_class_driver_t *driver = &usbd_class_drivers[_usbd_dev.itf2drv[interface]]; - if (driver->control_request_complete != NULL) { - driver->control_request_complete(rhport, p_request); + case TUSB_REQ_SET_ADDRESS: + dcd_set_address(rhport, (uint8_t) p_request->wValue); + break; + + case TUSB_REQ_GET_CONFIGURATION: + data_buf = &_usbd_dev.config_num; + data_len = 1; + break; + + case TUSB_REQ_SET_CONFIGURATION: + { + uint8_t const config = (uint8_t) p_request->wValue; + + dcd_set_config(rhport, config); + _usbd_dev.config_num = config; + + TU_ASSERT( TUSB_ERROR_NONE == process_set_config(rhport, config) ); } + break; + + case TUSB_REQ_GET_DESCRIPTOR: + data_buf = (void*) get_descriptor(p_request, &data_len); + if ( data_buf == NULL || data_len == 0 ) return false; + break; + + default: return false; } -} -tusb_error_t tud_control_interface_control_cb(uint8_t rhport, uint8_t interface, tusb_control_request_t const * const p_request, uint16_t bytes_already_sent) { - if (_usbd_dev.itf2drv[ interface ] < USBD_CLASS_DRIVER_COUNT) + usbd_control_xfer(rhport, p_request, data_buf, data_len); + } + else if ( TUSB_REQ_RCPT_INTERFACE == p_request->bmRequestType_bit.recipient ) + { + //------------- Class/Interface Specific Request -------------// + uint8_t const itf = tu_u16_low(p_request->wIndex); + uint8_t const drvid = _usbd_dev.itf2drv[ itf ]; + + TU_VERIFY (drvid < USBD_CLASS_DRIVER_COUNT ); + + usbd_control_set_complete_callback(usbd_class_drivers[drvid].control_request_complete ); + + // control endpoint will be stalled if driver return false + return usbd_class_drivers[drvid].control_request(rhport, p_request); + } + else if ( p_request->bmRequestType_bit.recipient == TUSB_REQ_RCPT_ENDPOINT && + p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD ) + { + //------------- Endpoint Request -------------// + switch ( p_request->bRequest ) { - return usbd_class_drivers[_usbd_dev.itf2drv[interface]].control_request(rhport, p_request, bytes_already_sent); + case TUSB_REQ_GET_STATUS: + { + uint16_t status = dcd_edpt_stalled(rhport, tu_u16_low(p_request->wIndex)) ? 0x0001 : 0x0000; + usbd_control_xfer(rhport, p_request, &status, 2); + } + break; + + case TUSB_REQ_CLEAR_FEATURE: + // only endpoint feature is halted/stalled + dcd_edpt_clear_stall(rhport, tu_u16_low(p_request->wIndex)); + usbd_control_status(rhport, p_request); + break; + + case TUSB_REQ_SET_FEATURE: + // only endpoint feature is halted/stalled + dcd_edpt_stall(rhport, tu_u16_low(p_request->wIndex)); + usbd_control_status(rhport, p_request); + break; + + default: return false; } - return TUSB_ERROR_FAILED; + } + else + { + //------------- Unsupported Request -------------// + return false; + } + + return true; } // Process Set Configure Request -// TODO Host (windows) can get HID report descriptor before set configured -// may need to open interface before set configured -tusb_error_t tud_control_set_config_cb(uint8_t rhport, uint8_t config_number) +// This function parse configuration descriptor & open drivers accordingly +static bool process_set_config(uint8_t rhport, uint8_t config_number) { - dcd_set_config(rhport, config_number); - - _usbd_dev.config_num = config_number; - - //------------- parse configuration & open drivers -------------// uint8_t const * desc_cfg = (uint8_t const *) usbd_desc_set->config; - TU_ASSERT(desc_cfg != NULL, TUSB_ERROR_DESCRIPTOR_CORRUPTED); + TU_ASSERT(desc_cfg != NULL); + uint8_t const * p_desc = desc_cfg + sizeof(tusb_desc_configuration_t); uint16_t const cfg_len = ((tusb_desc_configuration_t*)desc_cfg)->wTotalLength; while( p_desc < desc_cfg + cfg_len ) { + // Each interface always starts with Interface or Association descriptor if ( TUSB_DESC_INTERFACE_ASSOCIATION == descriptor_type(p_desc) ) { p_desc = descriptor_next(p_desc); // ignore Interface Association }else { - TU_ASSERT( TUSB_DESC_INTERFACE == descriptor_type(p_desc), TUSB_ERROR_NOT_SUPPORTED_YET ); + TU_ASSERT( TUSB_DESC_INTERFACE == descriptor_type(p_desc) ); - tusb_desc_interface_t* p_desc_itf = (tusb_desc_interface_t*) p_desc; - uint8_t const class_code = p_desc_itf->bInterfaceClass; + tusb_desc_interface_t* desc_itf = (tusb_desc_interface_t*) p_desc; // Check if class is supported uint8_t drv_id; for (drv_id = 0; drv_id < USBD_CLASS_DRIVER_COUNT; drv_id++) { - if ( usbd_class_drivers[drv_id].class_code == class_code ) break; + if ( usbd_class_drivers[drv_id].class_code == desc_itf->bInterfaceClass ) break; } - TU_ASSERT( drv_id < USBD_CLASS_DRIVER_COUNT, TUSB_ERROR_NOT_SUPPORTED_YET ); + TU_ASSERT( drv_id < USBD_CLASS_DRIVER_COUNT ); // unsupported class - // Interface number must not be used - TU_ASSERT( 0xff == _usbd_dev.itf2drv[p_desc_itf->bInterfaceNumber], TUSB_ERROR_FAILED); - _usbd_dev.itf2drv[p_desc_itf->bInterfaceNumber] = drv_id; + // Interface number must not be used already TODO alternate interface + TU_ASSERT( 0xff == _usbd_dev.itf2drv[desc_itf->bInterfaceNumber] ); + _usbd_dev.itf2drv[desc_itf->bInterfaceNumber] = drv_id; uint16_t len=0; - TU_ASSERT_ERR( usbd_class_drivers[drv_id].open( rhport, p_desc_itf, &len ) ); - TU_ASSERT( len >= sizeof(tusb_desc_interface_t), TUSB_ERROR_FAILED ); + TU_ASSERT_ERR( usbd_class_drivers[drv_id].open( rhport, desc_itf, &len ), false ); + TU_ASSERT( len >= sizeof(tusb_desc_interface_t) ); mark_interface_endpoint(p_desc, len, drv_id); @@ -404,8 +489,62 @@ static void mark_interface_endpoint(uint8_t const* p_desc, uint16_t desc_len, ui } } +// return descriptor's buffer and update desc_len +static void const* get_descriptor(tusb_control_request_t const * p_request, uint16_t* desc_len) +{ + tusb_desc_type_t const desc_type = (tusb_desc_type_t) tu_u16_high(p_request->wValue); + uint8_t const desc_index = tu_u16_low( p_request->wValue ); + + uint8_t const * desc_data = NULL; + uint16_t len = 0; + + *desc_len = 0; + + switch(desc_type) + { + case TUSB_DESC_DEVICE: + desc_data = (uint8_t const *) usbd_desc_set->device; + len = sizeof(tusb_desc_device_t); + break; + + case TUSB_DESC_CONFIGURATION: + desc_data = (uint8_t const *) usbd_desc_set->config; + len = ((tusb_desc_configuration_t const*) desc_data)->wTotalLength; + break; + + case TUSB_DESC_STRING: + // String Descriptor always uses the desc set from user + if ( desc_index < tud_desc_set.string_count ) + { + desc_data = tud_desc_set.string_arr[desc_index]; + TU_VERIFY( desc_data != NULL, NULL ); + + len = desc_data[0]; // first byte of descriptor is its size + }else + { + // out of range + /* The 0xEE index string is a Microsoft USB extension. + * It can be used to tell Windows what driver it should use for the device !!! + */ + return NULL; + } + break; + + case TUSB_DESC_DEVICE_QUALIFIER: + // TODO If not highspeed capable stall this request otherwise + // return the descriptor that could work in highspeed + return NULL; + break; + + default: return NULL; + } + + *desc_len = len; + return desc_data; +} + //--------------------------------------------------------------------+ -// USBD-DCD Callback API +// DCD Event Handler //--------------------------------------------------------------------+ void dcd_event_handler(dcd_event_t const * event, bool in_isr) { @@ -430,6 +569,9 @@ void dcd_event_handler(dcd_event_t const * event, bool in_isr) break; case DCD_EVENT_XFER_COMPLETE: + // skip zero-length control status complete event, should dcd notifies us. + if ( 0 == edpt_number(event->xfer_complete.ep_addr) && event->xfer_complete.len == 0) break; + osal_queue_send(_usbd_q, event, in_isr); TU_ASSERT(event->xfer_complete.result == DCD_XFER_SUCCESS,); break; @@ -438,8 +580,6 @@ void dcd_event_handler(dcd_event_t const * event, bool in_isr) } } -void dcd_event_handler(dcd_event_t const * event, bool in_isr); - // helper to send bus signal event void dcd_event_bus_signal (uint8_t rhport, dcd_eventid_t eid, bool in_isr) { diff --git a/src/device/usbd_pvt.h b/src/device/usbd_pvt.h index bbbe0a604..30f010887 100644 --- a/src/device/usbd_pvt.h +++ b/src/device/usbd_pvt.h @@ -54,15 +54,24 @@ extern tud_desc_set_t const* usbd_desc_set; tusb_error_t usbd_init (void); void usbd_task (void* param); + +// Carry out Data and Status stage of control transfer +// - If len = 0, it is equivalent to sending status only +// - If len > wLength : it will be truncated +bool usbd_control_xfer(uint8_t rhport, tusb_control_request_t const * request, void* buffer, uint16_t len); + +// Send STATUS (zero length) packet +bool usbd_control_status(uint8_t rhport, tusb_control_request_t const * request); + +// Stall control endpoint until new setup packet arrived +void usbd_control_stall(uint8_t rhport); + /*------------------------------------------------------------------*/ -/* Endpoint helper +/* Helper *------------------------------------------------------------------*/ // helper to parse an pair of In and Out endpoint descriptors. They must be consecutive tusb_error_t usbd_open_edpt_pair(uint8_t rhport, tusb_desc_endpoint_t const* p_desc_ep, uint8_t xfer_type, uint8_t* ep_out, uint8_t* ep_in); -/*------------------------------------------------------------------*/ -/* Other Helpers - *------------------------------------------------------------------*/ void usbd_defer_func( osal_task_func_t func, void* param, bool in_isr ); diff --git a/src/tusb_option.h b/src/tusb_option.h index d027ea0e6..f19ff4076 100644 --- a/src/tusb_option.h +++ b/src/tusb_option.h @@ -148,10 +148,8 @@ #define CFG_TUD_ENDOINT0_SIZE 64 #endif - #ifndef CFG_TUD_ENUM_BUFFER_SIZE + #ifndef CFG_TUD_CTRL_BUFSIZE #define CFG_TUD_CTRL_BUFSIZE 256 - #else - #define CFG_TUD_CTRL_BUFSIZE CFG_TUD_ENUM_BUFFER_SIZE #endif #ifndef CFG_TUD_DESC_AUTO -- cgit v1.3.1 From 4314be9aebff009f5dd626d59142459edea5c8a2 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 22 Nov 2018 12:11:06 +0700 Subject: msc device block count and block num - replace CFG_TUD_MSC_BLOCK_NUM & CFG_TUD_MSC_BLOCK_SZ by tud_msc_capacity_cb() (mandatory callback) --- examples/device/cdc_msc_hid/src/msc_disk_ram.c | 14 ++- examples/device/cdc_msc_hid/src/tusb_config.h | 14 +-- examples/device/cdc_msc_hid_freertos/src/msc_app.c | 3 +- examples/device/cdc_msc_hid_freertos/src/msc_app.h | 64 ----------- .../cdc_msc_hid_freertos/src/msc_device_ramdisk.c | 116 -------------------- .../device/cdc_msc_hid_freertos/src/msc_disk_ram.c | 122 +++++++++++++++++++++ .../device/cdc_msc_hid_freertos/src/tusb_config.h | 6 - src/class/msc/msc_device.c | 31 +++--- src/class/msc/msc_device.h | 14 ++- 9 files changed, 159 insertions(+), 225 deletions(-) delete mode 100644 examples/device/cdc_msc_hid_freertos/src/msc_app.h delete mode 100644 examples/device/cdc_msc_hid_freertos/src/msc_device_ramdisk.c create mode 100644 examples/device/cdc_msc_hid_freertos/src/msc_disk_ram.c (limited to 'src/class') diff --git a/examples/device/cdc_msc_hid/src/msc_disk_ram.c b/examples/device/cdc_msc_hid/src/msc_disk_ram.c index 89711ad32..08cef5f25 100644 --- a/examples/device/cdc_msc_hid/src/msc_disk_ram.c +++ b/examples/device/cdc_msc_hid/src/msc_disk_ram.c @@ -97,6 +97,8 @@ uint8_t msc_device_ramdisk[DISK_BLOCK_NUM][DISK_BLOCK_SIZE] = // Copy disk's data to buffer (up to bufsize) and return number of copied bytes. int32_t tud_msc_read10_cb(uint8_t lun, uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize) { + (void) lun; + uint8_t* addr = msc_device_ramdisk[lba] + offset; memcpy(buffer, addr, bufsize); @@ -107,14 +109,20 @@ int32_t tud_msc_read10_cb(uint8_t lun, uint32_t lba, uint32_t offset, void* buff // Process data in buffer to disk's storage and return number of written bytes int32_t tud_msc_write10_cb(uint8_t lun, uint32_t lba, uint32_t offset, uint8_t* buffer, uint32_t bufsize) { + (void) lun; + uint8_t* addr = msc_device_ramdisk[lba] + offset; memcpy(addr, buffer, bufsize); return bufsize; } -//--------------------------------------------------------------------+ -// HELPER -//--------------------------------------------------------------------+ +void tud_msc_capacity_cb(uint8_t lun, uint32_t* block_count, uint16_t* block_size) +{ + (void) lun; + + *block_count = DISK_BLOCK_NUM; + *block_size = DISK_BLOCK_SIZE; +} #endif diff --git a/examples/device/cdc_msc_hid/src/tusb_config.h b/examples/device/cdc_msc_hid/src/tusb_config.h index f54f9d58d..29ed8a8e0 100644 --- a/examples/device/cdc_msc_hid/src/tusb_config.h +++ b/examples/device/cdc_msc_hid/src/tusb_config.h @@ -55,14 +55,8 @@ #endif #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE - #define CFG_TUSB_DEBUG 2 - -/*------------- RTOS -------------*/ -#define CFG_TUSB_OS OPT_OS_NONE // be passed from IDE/command line for easy project switching -//#define CFG_TUD_TASK_PRIO 0 -//#define CFG_TUD_TASK_QUEUE_SZ 16 -//#define CFG_TUD_TASK_STACK_SZ 150 +#define CFG_TUSB_OS OPT_OS_NONE //-------------------------------------------------------------------- // DEVICE CONFIGURATION @@ -118,12 +112,6 @@ // Buffer size of Device Mass storage #define CFG_TUD_MSC_BUFSIZE 512 -// Number of Blocks -#define CFG_TUD_MSC_BLOCK_NUM 16 - -// Block size -#define CFG_TUD_MSC_BLOCK_SZ 512 - // Vendor name included in Inquiry response, max 8 bytes #define CFG_TUD_MSC_VENDOR "tinyusb" diff --git a/examples/device/cdc_msc_hid_freertos/src/msc_app.c b/examples/device/cdc_msc_hid_freertos/src/msc_app.c index 52cf58f78..5d46b1cfa 100644 --- a/examples/device/cdc_msc_hid_freertos/src/msc_app.c +++ b/examples/device/cdc_msc_hid_freertos/src/msc_app.c @@ -36,7 +36,8 @@ */ /**************************************************************************/ -#include "msc_app.h" +#include "bsp/board.h" +#include "tusb.h" #if CFG_TUD_MSC diff --git a/examples/device/cdc_msc_hid_freertos/src/msc_app.h b/examples/device/cdc_msc_hid_freertos/src/msc_app.h deleted file mode 100644 index 38d0f4c99..000000000 --- a/examples/device/cdc_msc_hid_freertos/src/msc_app.h +++ /dev/null @@ -1,64 +0,0 @@ -/**************************************************************************/ -/*! - @file msc_app.h - @author hathach (tinyusb.org) - - @section LICENSE - - Software License Agreement (BSD License) - - Copyright (c) 2013, hathach (tinyusb.org) - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - 3. Neither the name of the copyright holders nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY - EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - This file is part of the tinyusb stack. - */ -/**************************************************************************/ - -/** \ingroup group_demo - * \defgroup Mass Storage Device App - * @{ */ - -#ifndef _TUSB_MSCD_DEVICE_APP_H_ -#define _TUSB_MSCD_DEVICE_APP_H_ - -#include "bsp/board.h" -#include "tusb.h" - -#ifdef __cplusplus - extern "C" { -#endif - -#define README_CONTENTS \ -"This is tinyusb's MassStorage Class demo.\r\n\r\n\ -If you find any bugs or get any questions, feel free to file an\r\n\ -issue at github.com/hathach/tinyusb" - -#ifdef __cplusplus - } -#endif - -#endif /* _TUSB_MSCD_DEVICE_APP_H_ */ - -/** @} */ diff --git a/examples/device/cdc_msc_hid_freertos/src/msc_device_ramdisk.c b/examples/device/cdc_msc_hid_freertos/src/msc_device_ramdisk.c deleted file mode 100644 index e7c432866..000000000 --- a/examples/device/cdc_msc_hid_freertos/src/msc_device_ramdisk.c +++ /dev/null @@ -1,116 +0,0 @@ -/**************************************************************************/ -/*! - @file msc_device_ramdisk.c - @author hathach (tinyusb.org) - - @section LICENSE - - Software License Agreement (BSD License) - - Copyright (c) 2013, hathach (tinyusb.org) - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - 3. Neither the name of the copyright holders nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY - EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - This file is part of the tinyusb stack. -*/ -/**************************************************************************/ - -#include "msc_app.h" - -#if CFG_TUD_MSC && defined (MSCD_APP_RAMDISK) - -//--------------------------------------------------------------------+ -// MACRO CONSTANT TYPEDEF -//--------------------------------------------------------------------+ - -//--------------------------------------------------------------------+ -// INTERNAL OBJECT & FUNCTION DECLARATION -//--------------------------------------------------------------------+ -CFG_TUSB_ATTR_USBRAM CFG_TUSB_MEM_ALIGN -uint8_t msc_device_ramdisk[DISK_BLOCK_NUM][DISK_BLOCK_SIZE] = -{ - //------------- Boot Sector -------------// - // byte_per_sector = DISK_BLOCK_SIZE; fat12_sector_num_16 = DISK_BLOCK_NUM; - // sector_per_cluster = 1; reserved_sectors = 1; - // fat_num = 1; fat12_root_entry_num = 16; - // sector_per_fat = 1; sector_per_track = 1; head_num = 1; hidden_sectors = 0; - // drive_number = 0x80; media_type = 0xf8; extended_boot_signature = 0x29; - // filesystem_type = "FAT12 "; volume_serial_number = 0x1234; volume_label = "tinyusb msc"; - [0] = - { - 0xEB, 0x3C, 0x90, 0x4D, 0x53, 0x44, 0x4F, 0x53, 0x35, 0x2E, 0x30, 0x00, 0x02, 0x01, 0x01, 0x00, - 0x01, 0x10, 0x00, 0x10, 0x00, 0xF8, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x29, 0x34, 0x12, 0x00, 0x00, 0x74, 0x69, 0x6E, 0x79, 0x75, - 0x73, 0x62, 0x20, 0x6D, 0x73, 0x63, 0x46, 0x41, 0x54, 0x31, 0x32, 0x20, 0x20, 0x20, 0x00, 0x00, - [510] = 0x55, [511] = 0xAA // FAT magic code - }, - - //------------- FAT12 Table -------------// - [1] = - { - 0xF8, 0xFF, 0xFF, 0xFF, 0x0F // // first 2 entries must be F8FF, third entry is cluster end of readme file - }, - - //------------- Root Directory -------------// - [2] = - { - // first entry is volume label - 0x54, 0x49, 0x4E, 0x59, 0x55, 0x53, 0x42, 0x20, 0x4D, 0x53, 0x43, 0x08, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4F, 0x6D, 0x65, 0x43, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - // second entry is readme file - 'R' , 'E' , 'A' , 'D' , 'M' , 'E' , ' ' , ' ' , 'T' , 'X' , 'T' , 0x20, 0x00, 0xC6, 0x52, 0x6D, - 0x65, 0x43, 0x65, 0x43, 0x00, 0x00, 0x88, 0x6D, 0x65, 0x43, 0x02, 0x00, - sizeof(README_CONTENTS)-1, 0x00, 0x00, 0x00 // readme's filesize (4 Bytes) - }, - - //------------- Readme Content -------------// - [3] = README_CONTENTS -}; - - -// Callback invoked when received READ10 command. -// Copy disk's data to buffer (up to bufsize) and return number of copied bytes. -int32_t tud_msc_read10_cb(uint8_t lun, uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize) -{ - uint8_t* addr = msc_device_ramdisk[lba] + offset; - memcpy(buffer, addr, bufsize); - - return bufsize; -} - -// Callback invoked when received WRITE10 command. -// Process data in buffer to disk's storage and return number of written bytes -int32_t tud_msc_write10_cb(uint8_t lun, uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize) -{ - uint8_t* addr = msc_device_ramdisk[lba] + offset; - memcpy(addr, buffer, bufsize); - - return bufsize; -} - -//--------------------------------------------------------------------+ -// HELPER -//--------------------------------------------------------------------+ - -#endif diff --git a/examples/device/cdc_msc_hid_freertos/src/msc_disk_ram.c b/examples/device/cdc_msc_hid_freertos/src/msc_disk_ram.c new file mode 100644 index 000000000..5e2f5e6be --- /dev/null +++ b/examples/device/cdc_msc_hid_freertos/src/msc_disk_ram.c @@ -0,0 +1,122 @@ +/**************************************************************************/ +/*! + @file msc_device_ramdisk.c + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#include "bsp/board.h" +#include "tusb.h" + +#if CFG_TUD_MSC + +#define README_CONTENTS \ +"This is tinyusb's MassStorage Class demo.\r\n\r\n\ +If you find any bugs or get any questions, feel free to file an\r\n\ +issue at github.com/hathach/tinyusb" + +enum +{ + DISK_BLOCK_NUM = 16, // 8KB is the smallest size that windows allow to mount + DISK_BLOCK_SIZE = 512 +}; + +uint8_t msc_device_ramdisk[DISK_BLOCK_NUM][DISK_BLOCK_SIZE] = +{ + //------------- Boot Sector -------------// + // byte_per_sector = DISK_BLOCK_SIZE; fat12_sector_num_16 = DISK_BLOCK_NUM; + // sector_per_cluster = 1; reserved_sectors = 1; + // fat_num = 1; fat12_root_entry_num = 16; + // sector_per_fat = 1; sector_per_track = 1; head_num = 1; hidden_sectors = 0; + // drive_number = 0x80; media_type = 0xf8; extended_boot_signature = 0x29; + // filesystem_type = "FAT12 "; volume_serial_number = 0x1234; volume_label = "tinyusb msc"; + [0] = + { + 0xEB, 0x3C, 0x90, 0x4D, 0x53, 0x44, 0x4F, 0x53, 0x35, 0x2E, 0x30, 0x00, 0x02, 0x01, 0x01, 0x00, + 0x01, 0x10, 0x00, 0x10, 0x00, 0xF8, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x29, 0x34, 0x12, 0x00, 0x00, 0x74, 0x69, 0x6E, 0x79, 0x75, + 0x73, 0x62, 0x20, 0x6D, 0x73, 0x63, 0x46, 0x41, 0x54, 0x31, 0x32, 0x20, 0x20, 0x20, 0x00, 0x00, + [510] = 0x55, [511] = 0xAA // FAT magic code + }, + + //------------- FAT12 Table -------------// + [1] = + { + 0xF8, 0xFF, 0xFF, 0xFF, 0x0F // // first 2 entries must be F8FF, third entry is cluster end of readme file + }, + + //------------- Root Directory -------------// + [2] = + { + // first entry is volume label + 0x54, 0x49, 0x4E, 0x59, 0x55, 0x53, 0x42, 0x20, 0x4D, 0x53, 0x43, 0x08, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4F, 0x6D, 0x65, 0x43, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // second entry is readme file + 'R' , 'E' , 'A' , 'D' , 'M' , 'E' , ' ' , ' ' , 'T' , 'X' , 'T' , 0x20, 0x00, 0xC6, 0x52, 0x6D, + 0x65, 0x43, 0x65, 0x43, 0x00, 0x00, 0x88, 0x6D, 0x65, 0x43, 0x02, 0x00, + sizeof(README_CONTENTS)-1, 0x00, 0x00, 0x00 // readme's filesize (4 Bytes) + }, + + //------------- Readme Content -------------// + [3] = README_CONTENTS +}; + + +// Callback invoked when received READ10 command. +// Copy disk's data to buffer (up to bufsize) and return number of copied bytes. +int32_t tud_msc_read10_cb(uint8_t lun, uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize) +{ + uint8_t* addr = msc_device_ramdisk[lba] + offset; + memcpy(buffer, addr, bufsize); + + return bufsize; +} + +// Callback invoked when received WRITE10 command. +// Process data in buffer to disk's storage and return number of written bytes +int32_t tud_msc_write10_cb(uint8_t lun, uint32_t lba, uint32_t offset, uint8_t* buffer, uint32_t bufsize) +{ + uint8_t* addr = msc_device_ramdisk[lba] + offset; + memcpy(addr, buffer, bufsize); + + return bufsize; +} + +void tud_msc_capacity_cb(uint8_t lun, uint32_t* block_count, uint16_t* block_size) +{ + *block_count = DISK_BLOCK_NUM; + *block_size = DISK_BLOCK_SIZE; +} + +#endif diff --git a/examples/device/cdc_msc_hid_freertos/src/tusb_config.h b/examples/device/cdc_msc_hid_freertos/src/tusb_config.h index 4c8635fc0..a80680338 100644 --- a/examples/device/cdc_msc_hid_freertos/src/tusb_config.h +++ b/examples/device/cdc_msc_hid_freertos/src/tusb_config.h @@ -117,12 +117,6 @@ // Buffer size of Device Mass storage #define CFG_TUD_MSC_BUFSIZE 512 -// Number of Blocks -#define CFG_TUD_MSC_BLOCK_NUM BOARD_MSC_FLASH_SIZE/CFG_TUD_MSC_BLOCK_SZ - -// Block size -#define CFG_TUD_MSC_BLOCK_SZ 512 - // Vendor name included in Inquiry response, max 8 bytes #define CFG_TUD_MSC_VENDOR "tinyusb" diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index 92bc4c6c8..bfe708f42 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -205,16 +205,6 @@ bool mscd_control_request_complete(uint8_t rhport, tusb_control_request_t const return true; } -// For backwards compatibility we support static block counts. -#if defined(CFG_TUD_MSC_BLOCK_NUM) && defined(CFG_TUD_MSC_BLOCK_SZ) -ATTR_WEAK bool tud_lun_capacity_cb(uint8_t lun, uint32_t* last_valid_sector, uint16_t* block_size) { - (void) lun; - *last_valid_sector = CFG_TUD_MSC_BLOCK_NUM-1; - *block_size = CFG_TUD_MSC_BLOCK_SZ; - return true; -} -#endif - // return length of response (copied to buffer), -1 if it is not an built-in commands int32_t proc_builtin_scsi(msc_cbw_t const * p_cbw, uint8_t* buffer, uint32_t bufsize) { @@ -226,10 +216,14 @@ int32_t proc_builtin_scsi(msc_cbw_t const * p_cbw, uint8_t* buffer, uint32_t buf { scsi_read_capacity10_resp_t read_capa10; - uint32_t last_valid_sector; - uint16_t block_size; - tud_lun_capacity_cb(p_cbw->lun, &last_valid_sector, &block_size); - read_capa10.last_lba = ENDIAN_BE(last_valid_sector); // read capacity + uint32_t block_count; + uint32_t block_size; + uint16_t block_size_u16; + + tud_msc_capacity_cb(p_cbw->lun, &block_count, &block_size_u16); + block_size = (uint32_t) block_size_u16; + + read_capa10.last_lba = ENDIAN_BE(block_count-1); read_capa10.block_size = ENDIAN_BE(block_size); ret = sizeof(read_capa10); @@ -243,14 +237,15 @@ int32_t proc_builtin_scsi(msc_cbw_t const * p_cbw, uint8_t* buffer, uint32_t buf { .list_length = 8, .block_num = 0, - .descriptor_type = 2, // formatted media + .descriptor_type = 2, // formatted media .block_size_u16 = 0 }; - uint32_t last_valid_sector; + uint32_t block_count; uint16_t block_size; - tud_lun_capacity_cb(p_cbw->lun, &last_valid_sector, &block_size); - read_fmt_capa.block_num = ENDIAN_BE(last_valid_sector+1); + + tud_msc_capacity_cb(p_cbw->lun, &block_count, &block_size); + read_fmt_capa.block_num = ENDIAN_BE(block_count); read_fmt_capa.block_size_u16 = ENDIAN_BE16(block_size); ret = sizeof(read_fmt_capa); diff --git a/src/class/msc/msc_device.h b/src/class/msc/msc_device.h index d08d9f9cb..c1c51255a 100644 --- a/src/class/msc/msc_device.h +++ b/src/class/msc/msc_device.h @@ -132,6 +132,9 @@ int32_t tud_msc_read10_cb (uint8_t lun, uint32_t lba, uint32_t offset, void* buf */ int32_t tud_msc_write10_cb (uint8_t lun, uint32_t lba, uint32_t offset, uint8_t* buffer, uint32_t bufsize); +// Invoked to determine the disk size +void tud_msc_capacity_cb(uint8_t lun, uint32_t* block_count, uint16_t* block_size); + /** * Callback invoked when received an SCSI command not in built-in list below. * \param[in] lun Logical unit number @@ -152,16 +155,19 @@ int32_t tud_msc_write10_cb (uint8_t lun, uint32_t lba, uint32_t offset, uint8_t* int32_t tud_msc_scsi_cb (uint8_t lun, uint8_t const scsi_cmd[16], void* buffer, uint16_t bufsize); /*------------- Optional callbacks : Could be used by application to free up resources -------------*/ + +// Invoked when Read10 command is complete ATTR_WEAK void tud_msc_read10_complete_cb(uint8_t lun); + +// Invoke when Write10 command is complete ATTR_WEAK void tud_msc_write10_complete_cb(uint8_t lun); + +// Invoked when command in tud_msc_scsi_cb is complete ATTR_WEAK void tud_msc_scsi_complete_cb(uint8_t lun, uint8_t const scsi_cmd[16]); -// Hook to make a mass storage device read-only. +// Hook to make a mass storage device read-only. TODO remove ATTR_WEAK bool tud_msc_is_writable_cb(uint8_t lun); -// Override for dynamic LUN sizes. -ATTR_WEAK bool tud_lun_capacity_cb(uint8_t lun, uint32_t* last_valid_sector, uint16_t* block_size); - /** @} */ /** @} */ -- cgit v1.3.1 From 60d8cde6951fa9fe9c43064ee701598e9da566f7 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 22 Nov 2018 17:21:07 +0700 Subject: rename CFG_TUSB_MEM_SECTION to CFG_TUSB_MEM_SECTION --- doxygen/configuration.txt | 6 +-- examples/device/cdc_msc_hid/src/tusb_config.h | 12 +++--- .../device/cdc_msc_hid_freertos/src/tusb_config.h | 2 +- .../device/device_virtual_com/src/tusb_config.h | 20 ++++----- .../device/device_virtual_com/xpresso/.cproject | 14 ++----- examples/obsolete/device/src/keyboard_device_app.c | 2 +- examples/obsolete/device/src/mouse_device_app.c | 2 +- examples/obsolete/device/src/msc_device_ramdisk.c | 2 +- examples/obsolete/device/src/tusb_config.h | 18 ++++----- examples/obsolete/host/src/cdc_serial_host_app.c | 4 +- examples/obsolete/host/src/keyboard_host_app.c | 2 +- examples/obsolete/host/src/mouse_host_app.c | 2 +- examples/obsolete/host/src/msc_cli.c | 2 +- examples/obsolete/host/src/msc_host_app.c | 2 +- examples/obsolete/host/src/tusb_config.h | 12 +++--- hw/bsp/ea4357/board_ea4357.c | 6 ++- src/class/cdc/cdc_device.c | 2 +- src/class/cdc/cdc_host.h | 8 ++-- src/class/cdc/cdc_rndis_host.c | 4 +- src/class/hid/hid_device.c | 2 +- src/class/hid/hid_device.h | 4 +- src/class/hid/hid_host.c | 2 +- src/class/hid/hid_host.h | 4 +- src/class/msc/msc_device.c | 4 +- src/class/msc/msc_host.c | 4 +- src/class/msc/msc_host.h | 6 +-- src/device/usbd_control.c | 2 +- src/host/ehci/ehci.c | 6 +-- src/host/hub.c | 4 +- src/host/ohci/ohci.c | 2 +- src/host/usbh.c | 4 +- .../nxp/lpc11xx_lpc13xx/dcd_lpc_11uxx_13uxx.c | 6 +-- src/portable/nxp/lpc17xx/dcd_lpc175x_6x.c | 2 +- src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c | 47 ++++++++++++++-------- src/tusb_option.h | 5 ++- tests/lpc18xx_43xx/test/host/cdc/descriptor_cdc.c | 4 +- tests/support/descriptor_test.c | 8 ++-- tests/support/tusb_config.h | 2 +- 38 files changed, 126 insertions(+), 114 deletions(-) (limited to 'src/class') diff --git a/doxygen/configuration.txt b/doxygen/configuration.txt index 5816826d7..da30786ed 100644 --- a/doxygen/configuration.txt +++ b/doxygen/configuration.txt @@ -10,13 +10,13 @@ #define CFG_TUSB_RHPORT0_MODE /** USB controller in MCU often has limited access to specific RAM section. The Stack will use this macro to place internal variables - into the USB RAM section as follows. if your mcu's usb controller has no such limit, define CFG_TUSB_ATTR_USBRAM as empty macro. + into the USB RAM section as follows. if your mcu's usb controller has no such limit, define CFG_TUSB_MEM_SECTION as empty macro. @code - CFG_TUSB_ATTR_USBRAM uint8_t usb_xfer_buffer[10]; + CFG_TUSB_MEM_SECTION uint8_t usb_xfer_buffer[10]; @endcode */ -#define CFG_TUSB_ATTR_USBRAM +#define CFG_TUSB_MEM_SECTION #define CFG_TUSB_MCU ///< Select one of the supported MCU, the value must be from \ref group_mcu #define CFG_TUSB_OS ///< Select one of the supported RTOS, the value must be from \ref group_supported_os. diff --git a/examples/device/cdc_msc_hid/src/tusb_config.h b/examples/device/cdc_msc_hid/src/tusb_config.h index 29ed8a8e0..3af109188 100644 --- a/examples/device/cdc_msc_hid/src/tusb_config.h +++ b/examples/device/cdc_msc_hid/src/tusb_config.h @@ -58,6 +58,12 @@ #define CFG_TUSB_DEBUG 2 #define CFG_TUSB_OS OPT_OS_NONE +//-------------------------------------------------------------------- +// USB RAM PLACEMENT +//-------------------------------------------------------------------- +#define CFG_TUSB_ATTR_USBRAM +#define CFG_TUSB_MEM_ALIGN ATTR_ALIGNED(4) + //-------------------------------------------------------------------- // DEVICE CONFIGURATION //-------------------------------------------------------------------- @@ -132,12 +138,6 @@ */ #define CFG_TUD_HID_ASCII_TO_KEYCODE_LOOKUP 1 -//-------------------------------------------------------------------- -// USB RAM PLACEMENT -//-------------------------------------------------------------------- -#define CFG_TUSB_ATTR_USBRAM -#define CFG_TUSB_MEM_ALIGN ATTR_ALIGNED(4) - #ifdef __cplusplus } diff --git a/examples/device/cdc_msc_hid_freertos/src/tusb_config.h b/examples/device/cdc_msc_hid_freertos/src/tusb_config.h index a80680338..777930ba3 100644 --- a/examples/device/cdc_msc_hid_freertos/src/tusb_config.h +++ b/examples/device/cdc_msc_hid_freertos/src/tusb_config.h @@ -140,7 +140,7 @@ //-------------------------------------------------------------------- // USB RAM PLACEMENT //-------------------------------------------------------------------- -#define CFG_TUSB_ATTR_USBRAM +#define CFG_TUSB_MEM_SECTION #define CFG_TUSB_MEM_ALIGN ATTR_ALIGNED(4) diff --git a/examples/device/device_virtual_com/src/tusb_config.h b/examples/device/device_virtual_com/src/tusb_config.h index f7cde7848..fd3f41b01 100644 --- a/examples/device/device_virtual_com/src/tusb_config.h +++ b/examples/device/device_virtual_com/src/tusb_config.h @@ -93,36 +93,36 @@ #ifdef __CODE_RED // compiled with lpcxpresso #if (CFG_TUSB_MCU == OPT_MCU_LPC11UXX) || (CFG_TUSB_MCU == OPT_MCU_LPC13UXX) - #define CFG_TUSB_ATTR_USBRAM ATTR_SECTION(.data.$RAM2) ATTR_ALIGNED(64) // lp11u & lp13u requires data to be 64 byte aligned + #define CFG_TUSB_MEM_SECTION ATTR_SECTION(.data.$RAM2) ATTR_ALIGNED(64) // lp11u & lp13u requires data to be 64 byte aligned #elif CFG_TUSB_MCU == OPT_MCU_LPC175X_6X - #define CFG_TUSB_ATTR_USBRAM // LPC17xx USB DMA can access all + #define CFG_TUSB_MEM_SECTION // LPC17xx USB DMA can access all #elif (CFG_TUSB_MCU == OPT_MCU_LPC43XX) - #define CFG_TUSB_ATTR_USBRAM ATTR_SECTION(.data.$RAM3) + #define CFG_TUSB_MEM_SECTION ATTR_SECTION(.data.$RAM3) #endif #elif defined __CC_ARM // Compiled with Keil armcc, USBRAM_SECTION is defined in scatter files #if (CFG_TUSB_MCU == OPT_MCU_LPC11UXX) || (CFG_TUSB_MCU == OPT_MCU_LPC13UXX) - #define CFG_TUSB_ATTR_USBRAM ATTR_SECTION(USBRAM_SECTION) ATTR_ALIGNED(64) // lp11u & lp13u requires data to be 64 byte aligned + #define CFG_TUSB_MEM_SECTION ATTR_SECTION(USBRAM_SECTION) ATTR_ALIGNED(64) // lp11u & lp13u requires data to be 64 byte aligned #elif (CFG_TUSB_MCU == OPT_MCU_LPC175X_6X) - #define CFG_TUSB_ATTR_USBRAM // LPC17xx USB DMA can access all address + #define CFG_TUSB_MEM_SECTION // LPC17xx USB DMA can access all address #elif (CFG_TUSB_MCU == OPT_MCU_LPC43XX) - #define CFG_TUSB_ATTR_USBRAM // Use keil tool configure to have AHB SRAM as default memory + #define CFG_TUSB_MEM_SECTION // Use keil tool configure to have AHB SRAM as default memory #endif #elif defined __ICCARM__ // compiled with IAR #if (CFG_TUSB_MCU == OPT_MCU_LPC11UXX) || (CFG_TUSB_MCU == OPT_MCU_LPC13UXX) - #define CFG_TUSB_ATTR_USBRAM _Pragma("location=\"USB_PACKET_MEMORY\"") ATTR_ALIGNED(64) + #define CFG_TUSB_MEM_SECTION _Pragma("location=\"USB_PACKET_MEMORY\"") ATTR_ALIGNED(64) #elif (CFG_TUSB_MCU == OPT_MCU_LPC175X_6X) - #define CFG_TUSB_ATTR_USBRAM + #define CFG_TUSB_MEM_SECTION #elif (CFG_TUSB_MCU == OPT_MCU_LPC43XX) - #define CFG_TUSB_ATTR_USBRAM _Pragma("location=\".ahb_sram1\"") + #define CFG_TUSB_MEM_SECTION _Pragma("location=\".ahb_sram1\"") #endif #elif defined __SES_ARM -#define CFG_TUSB_ATTR_USBRAM ATTR_SECTION(.bss2) +#define CFG_TUSB_MEM_SECTION ATTR_SECTION(.bss2) #else diff --git a/examples/device/device_virtual_com/xpresso/.cproject b/examples/device/device_virtual_com/xpresso/.cproject index a9c1f03f7..1e76a688c 100644 --- a/examples/device/device_virtual_com/xpresso/.cproject +++ b/examples/device/device_virtual_com/xpresso/.cproject @@ -80,6 +80,9 @@ - - - + diff --git a/examples/device/cdc_msc_hid/ses/samd51/samd51.emProject b/examples/device/cdc_msc_hid/ses/samd51/samd51.emProject index 260d452f7..51b21feb6 100644 --- a/examples/device/cdc_msc_hid/ses/samd51/samd51.emProject +++ b/examples/device/cdc_msc_hid/ses/samd51/samd51.emProject @@ -23,6 +23,7 @@ c_user_include_directories="../../src;$(rootDir)/hw/cmsis/Include;$(rootDir)/hw;$(rootDir)/src;$(asf4Dir);$(asf4Dir)/include;$(asf4Dir)/config;$(asf4Dir)/hri;$(asf4Dir)/hal/include;$(asf4Dir)/hal/utils/include;$(asf4Dir)/hpl/port;$(asf4Dir)/hpl/gclk" debug_register_definition_file="ATSAMD51J19A_Registers.xml" debug_target_connection="J-Link" + gcc_enable_all_warnings="Yes" gcc_entry_point="Reset_Handler" link_use_linker_script_file="No" linker_memory_map_file="ATSAMD51J19A_MemoryMap.xml" @@ -58,9 +59,6 @@ - - - diff --git a/examples/device/cdc_msc_hid/src/main.c b/examples/device/cdc_msc_hid/src/main.c index 9d3e088cf..03bc8a879 100644 --- a/examples/device/cdc_msc_hid/src/main.c +++ b/examples/device/cdc_msc_hid/src/main.c @@ -187,6 +187,7 @@ void tud_umount_cb(void) void tud_cdc_rx_cb(uint8_t itf) { + (void) itf; } //--------------------------------------------------------------------+ diff --git a/hw/bsp/pca10056/board_pca10056.c b/hw/bsp/pca10056/board_pca10056.c index e34ed27fa..fc88a6b28 100644 --- a/hw/bsp/pca10056/board_pca10056.c +++ b/hw/bsp/pca10056/board_pca10056.c @@ -248,7 +248,6 @@ uint8_t board_uart_getchar(void) void board_uart_putchar(uint8_t c) { - } #endif diff --git a/src/class/cdc/cdc_device.c b/src/class/cdc/cdc_device.c index b68a6a7ff..040c8d4f4 100644 --- a/src/class/cdc/cdc_device.c +++ b/src/class/cdc/cdc_device.c @@ -302,6 +302,8 @@ tusb_error_t cdcd_open(uint8_t rhport, tusb_desc_interface_t const * p_interface // return false to stall control endpoint (e.g Host send non-sense DATA) bool cdcd_control_request_complete(uint8_t rhport, tusb_control_request_t const * request) { + (void) rhport; + //------------- Class Specific Request -------------// TU_VERIFY (request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS); @@ -358,8 +360,10 @@ bool cdcd_control_request(uint8_t rhport, tusb_control_request_t const * request return true; } -tusb_error_t cdcd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes) +tusb_error_t cdcd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) { + (void) result; + // TODO Support multiple interfaces uint8_t const itf = 0; cdcd_interface_t* p_cdc = &_cdcd_itf[itf]; @@ -367,16 +371,14 @@ tusb_error_t cdcd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, // receive new data if ( ep_addr == p_cdc->ep_out ) { - char const wanted = p_cdc->wanted_char; - for(uint32_t i=0; irx_ff, &p_cdc->epout_buf[i]); // Check for wanted char and invoke callback if needed - if ( tud_cdc_rx_wanted_cb && ( wanted != -1 ) && ( wanted == p_cdc->epout_buf[i] ) ) + if ( tud_cdc_rx_wanted_cb && ( ((signed char) p_cdc->wanted_char) != -1 ) && ( p_cdc->wanted_char == p_cdc->epout_buf[i] ) ) { - tud_cdc_rx_wanted_cb(itf, wanted); + tud_cdc_rx_wanted_cb(itf, p_cdc->wanted_char); } } diff --git a/src/class/cdc/cdc_device.h b/src/class/cdc/cdc_device.h index ad1100e9c..0a17aa916 100644 --- a/src/class/cdc/cdc_device.h +++ b/src/class/cdc/cdc_device.h @@ -116,7 +116,7 @@ void cdcd_init (void); tusb_error_t cdcd_open (uint8_t rhport, tusb_desc_interface_t const * p_interface_desc, uint16_t *p_length); bool cdcd_control_request (uint8_t rhport, tusb_control_request_t const * p_request); bool cdcd_control_request_complete (uint8_t rhport, tusb_control_request_t const * p_request); -tusb_error_t cdcd_xfer_cb (uint8_t rhport, uint8_t edpt_addr, xfer_result_t event, uint32_t xferred_bytes); +tusb_error_t cdcd_xfer_cb (uint8_t rhport, uint8_t edpt_addr, xfer_result_t result, uint32_t xferred_bytes); void cdcd_reset (uint8_t rhport); #endif diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index c89c15acc..6e2ea27db 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -418,7 +418,6 @@ bool hidd_control_request(uint8_t rhport, tusb_control_request_t const * p_reque if (p_request->bRequest == TUSB_REQ_GET_DESCRIPTOR && desc_type == HID_DESC_TYPE_REPORT) { - // Cast away the const on p_hid->desc_report because we know it won't be modified. usbd_control_xfer(rhport, p_request, (void *)p_hid->desc_report, p_hid->desc_len); }else { diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index 88f8da6db..4fc3dd1b5 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -146,6 +146,7 @@ void mscd_init(void) void mscd_reset(uint8_t rhport) { + (void) rhport; tu_memclr(&_mscd_itf, sizeof(mscd_interface_t)); } @@ -201,6 +202,9 @@ bool mscd_control_request(uint8_t rhport, tusb_control_request_t const * p_reque // return false to stall control endpoint (e.g Host send non-sense DATA) bool mscd_control_request_complete(uint8_t rhport, tusb_control_request_t const * p_request) { + (void) rhport; + (void) p_request; + // nothing to do return true; } @@ -208,6 +212,7 @@ bool mscd_control_request_complete(uint8_t rhport, tusb_control_request_t const // return length of response (copied to buffer), -1 if it is not an built-in commands int32_t proc_builtin_scsi(msc_cbw_t const * p_cbw, uint8_t* buffer, uint32_t bufsize) { + (void) bufsize; // TODO refractor later int32_t ret; switch ( p_cbw->command[0] ) diff --git a/src/device/usbd.c b/src/device/usbd.c index 8c7e588e0..81fcfe959 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -170,7 +170,7 @@ static osal_queue_t _usbd_q; //--------------------------------------------------------------------+ static void mark_interface_endpoint(uint8_t const* p_desc, uint16_t desc_len, uint8_t driver_id); static bool process_control_request(uint8_t rhport, tusb_control_request_t const * p_request); -static bool process_set_config(uint8_t rhport, uint8_t config_number); +static bool process_set_config(uint8_t rhport); static void const* get_descriptor(tusb_control_request_t const * p_request, uint16_t* desc_len); void usbd_control_reset (uint8_t rhport); @@ -356,7 +356,7 @@ static bool process_control_request(uint8_t rhport, tusb_control_request_t const dcd_set_config(rhport, config); _usbd_dev.config_num = config; - TU_ASSERT( TUSB_ERROR_NONE == process_set_config(rhport, config) ); + TU_ASSERT( TUSB_ERROR_NONE == process_set_config(rhport) ); } break; @@ -427,7 +427,7 @@ static bool process_control_request(uint8_t rhport, tusb_control_request_t const // Process Set Configure Request // This function parse configuration descriptor & open drivers accordingly -static bool process_set_config(uint8_t rhport, uint8_t config_number) +static bool process_set_config(uint8_t rhport) { uint8_t const * desc_cfg = (uint8_t const *) usbd_desc_set->config; TU_ASSERT(desc_cfg != NULL); @@ -591,23 +591,23 @@ void dcd_event_handler(dcd_event_t const * event, bool in_isr) // helper to send bus signal event void dcd_event_bus_signal (uint8_t rhport, dcd_eventid_t eid, bool in_isr) { - dcd_event_t event = { .rhport = 0, .event_id = eid, }; + dcd_event_t event = { .rhport = rhport, .event_id = eid, }; dcd_event_handler(&event, in_isr); } // helper to send setup received void dcd_event_setup_received(uint8_t rhport, uint8_t const * setup, bool in_isr) { - dcd_event_t event = { .rhport = 0, .event_id = DCD_EVENT_SETUP_RECEIVED }; + dcd_event_t event = { .rhport = rhport, .event_id = DCD_EVENT_SETUP_RECEIVED }; memcpy(&event.setup_received, setup, 8); - dcd_event_handler(&event, true); + dcd_event_handler(&event, in_isr); } // helper to send transfer complete event void dcd_event_xfer_complete (uint8_t rhport, uint8_t ep_addr, uint32_t xferred_bytes, uint8_t result, bool in_isr) { - dcd_event_t event = { .rhport = 0, .event_id = DCD_EVENT_XFER_COMPLETE }; + dcd_event_t event = { .rhport = rhport, .event_id = DCD_EVENT_XFER_COMPLETE }; event.xfer_complete.ep_addr = ep_addr; event.xfer_complete.len = xferred_bytes; diff --git a/src/device/usbd_control.c b/src/device/usbd_control.c index 31d74edf0..ebeaaaa4d 100644 --- a/src/device/usbd_control.c +++ b/src/device/usbd_control.c @@ -68,6 +68,7 @@ CFG_TUSB_MEM_SECTION CFG_TUSB_MEM_ALIGN uint8_t _usbd_ctrl_buf[CFG_TUD_ENDOINT0_ void usbd_control_reset (uint8_t rhport) { + (void) rhport; tu_varclr(&_control_state); } @@ -126,8 +127,11 @@ bool usbd_control_xfer(uint8_t rhport, tusb_control_request_t const * request, v } // callback when a transaction complete on DATA stage of control endpoint -bool usbd_control_xfer_cb (uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes) +bool usbd_control_xfer_cb (uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) { + (void) result; + (void) ep_addr; + if ( _control_state.request.bmRequestType_bit.direction == TUSB_DIR_OUT ) { memcpy(_control_state.buffer, _usbd_ctrl_buf, xferred_bytes); diff --git a/src/portable/microchip/samd51/dcd_samd51.c b/src/portable/microchip/samd51/dcd_samd51.c index e76b5a1fa..d0ad17f92 100644 --- a/src/portable/microchip/samd51/dcd_samd51.c +++ b/src/portable/microchip/samd51/dcd_samd51.c @@ -84,11 +84,11 @@ bool dcd_init (uint8_t rhport) void dcd_connect (uint8_t rhport) { - + (void) rhport; } void dcd_disconnect (uint8_t rhport) { - + (void) rhport; } void dcd_set_address (uint8_t rhport, uint8_t dev_addr) diff --git a/src/portable/nordic/nrf5x/dcd_nrf5x.c b/src/portable/nordic/nrf5x/dcd_nrf5x.c index 4fb88689c..e1e53a83e 100644 --- a/src/portable/nordic/nrf5x/dcd_nrf5x.c +++ b/src/portable/nordic/nrf5x/dcd_nrf5x.c @@ -197,16 +197,17 @@ bool dcd_init (uint8_t rhport) void dcd_connect (uint8_t rhport) { - + (void) rhport; } void dcd_disconnect (uint8_t rhport) { - + (void) rhport; } void dcd_set_address (uint8_t rhport, uint8_t dev_addr) { (void) rhport; + (void) dev_addr; // Set Address is automatically update by hw controller } @@ -362,7 +363,7 @@ void USBD_IRQHandler(void) volatile uint32_t* regevt = &NRF_USBD->EVENTS_USBRESET; - for(int i=0; i Date: Mon, 26 Nov 2018 14:56:07 +0700 Subject: add OPT_MODE_HIGH_SPEED --- examples/device/cdc_msc_hid/src/tusb_config.h | 6 +++++- src/class/msc/msc_device.h | 4 ++++ src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c | 7 +++---- src/tusb_option.h | 22 ++++++++++++++++------ 4 files changed, 28 insertions(+), 11 deletions(-) (limited to 'src/class') diff --git a/examples/device/cdc_msc_hid/src/tusb_config.h b/examples/device/cdc_msc_hid/src/tusb_config.h index 0aa023352..0634c9576 100644 --- a/examples/device/cdc_msc_hid/src/tusb_config.h +++ b/examples/device/cdc_msc_hid/src/tusb_config.h @@ -55,7 +55,12 @@ #error CFG_TUSB_MCU should be defined using compiler flags #endif +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX +#define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) +#else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE +#endif + #define CFG_TUSB_DEBUG 2 #define CFG_TUSB_OS OPT_OS_NONE @@ -121,7 +126,6 @@ //-------------------------------------------------------------------- // MSC //-------------------------------------------------------------------- - // Number of supported Logical Unit Number (At least 1) #define CFG_TUD_MSC_MAXLUN 1 diff --git a/src/class/msc/msc_device.h b/src/class/msc/msc_device.h index c4476f56f..b268830ca 100644 --- a/src/class/msc/msc_device.h +++ b/src/class/msc/msc_device.h @@ -73,8 +73,12 @@ TU_VERIFY_STATIC(CFG_TUD_MSC_BUFSIZE < UINT16_MAX, "Size is not correct"); // TODO highspeed device is 512 #ifndef CFG_TUD_MSC_EPSIZE +#if TUD_OPT_HIGH_SPEED +#define CFG_TUD_MSC_EPSIZE 512 +#else #define CFG_TUD_MSC_EPSIZE 64 #endif +#endif #ifdef __cplusplus diff --git a/src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c b/src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c index 2f83f4203..260cc3a45 100644 --- a/src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c +++ b/src/portable/nxp/lpc43xx_lpc18xx/dcd_lpc43xx.c @@ -288,7 +288,7 @@ bool dcd_edpt_busy(uint8_t rhport, uint8_t ep_addr) // return !p_qhd->qtd_overlay.halted && p_qhd->qtd_overlay.active; } -bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes) +bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes) { uint8_t const epnum = edpt_number(ep_addr); uint8_t const dir = edpt_dir(ep_addr); @@ -301,9 +301,8 @@ bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t while(LPC_USB[rhport]->ENDPTSETUPSTAT & BIT_(0)) {} } - dcd_data_t* p_dcd = dcd_data_ptr[rhport]; - dcd_qhd_t * p_qhd = &p_dcd->qhd[ep_idx]; - dcd_qtd_t * p_qtd = &p_dcd->qtd[ep_idx]; + dcd_qhd_t * p_qhd = &dcd_data_ptr[rhport]->qhd[ep_idx]; + dcd_qtd_t * p_qtd = &dcd_data_ptr[rhport]->qtd[ep_idx]; //------------- Prepare qtd -------------// qtd_init(p_qtd, buffer, total_bytes); diff --git a/src/tusb_option.h b/src/tusb_option.h index 18e1e245e..b64a61e42 100644 --- a/src/tusb_option.h +++ b/src/tusb_option.h @@ -83,13 +83,16 @@ //-------------------------------------------------------------------- // CONTROLLER +// Only 1 roothub port can be configured to be device and/or host. +// tinyusb does not support dual devices or dual host configuration //-------------------------------------------------------------------- /** \defgroup group_mode Controller Mode Selection * \brief CFG_TUSB_CONTROLLER_N_MODE must be defined with these * @{ */ -#define OPT_MODE_HOST 0x02 ///< Host Mode -#define OPT_MODE_DEVICE 0x01 ///< Device Mode -#define OPT_MODE_NONE 0x00 ///< Disabled +#define OPT_MODE_NONE 0x00 ///< Disabled +#define OPT_MODE_DEVICE 0x01 ///< Device Mode +#define OPT_MODE_HOST 0x02 ///< Host Mode +#define OPT_MODE_HIGH_SPEED 0x10 ///< Highspeed /** @} */ #ifndef CFG_TUSB_RHPORT0_MODE @@ -100,21 +103,28 @@ #define CFG_TUSB_RHPORT1_MODE OPT_MODE_NONE #endif +#if ((CFG_TUSB_RHPORT0_MODE & OPT_MODE_HOST) && (CFG_TUSB_RHPORT1_MODE & OPT_MODE_HOST)) || \ + ((CFG_TUSB_RHPORT0_MODE & OPT_MODE_DEVICE) && (CFG_TUSB_RHPORT1_MODE & OPT_MODE_DEVICE)) + #error "tinyusb does not support same modes on more than 1 roothub port" +#endif + +// TODO remove #define CONTROLLER_HOST_NUMBER (\ ((CFG_TUSB_RHPORT0_MODE & OPT_MODE_HOST) ? 1 : 0) + \ ((CFG_TUSB_RHPORT1_MODE & OPT_MODE_HOST) ? 1 : 0)) #define MODE_HOST_SUPPORTED (CONTROLLER_HOST_NUMBER > 0) +// Which roothub port is configured as host #define TUH_OPT_RHPORT ( (CFG_TUSB_RHPORT0_MODE & OPT_MODE_HOST) ? 0 : ((CFG_TUSB_RHPORT1_MODE & OPT_MODE_HOST) ? 1 : -1) ) #define TUSB_OPT_HOST_ENABLED ( TUH_OPT_RHPORT >= 0 ) +// Which roothub port is configured as device #define TUD_OPT_RHPORT ( (CFG_TUSB_RHPORT0_MODE & OPT_MODE_DEVICE) ? 0 : ((CFG_TUSB_RHPORT1_MODE & OPT_MODE_DEVICE) ? 1 : -1) ) +#define TUD_OPT_HIGH_SPEED ( (CFG_TUSB_RHPORT0_MODE & (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED)) || (CFG_TUSB_RHPORT1_MODE & (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED)) ) + #define TUSB_OPT_DEVICE_ENABLED ( TUD_OPT_RHPORT >= 0 ) -#if ((CFG_TUSB_RHPORT0_MODE & OPT_MODE_HOST) && (CFG_TUSB_RHPORT1_MODE & OPT_MODE_HOST)) || ((CFG_TUSB_RHPORT0_MODE & OPT_MODE_DEVICE) && (CFG_TUSB_RHPORT1_MODE & OPT_MODE_DEVICE)) - #error "tinyusb does not support same modes on more than 1 roothub port" -#endif //--------------------------------------------------------------------+ // COMMON OPTIONS -- cgit v1.3.1 From 8b03b6d3b45167b8db805ca95aafce92a1a2e4b0 Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 28 Nov 2018 16:10:31 +0700 Subject: add Auto descriptor endpoint num config to support lpc17xx CFG_TUD_DESC_*_EPNUM --- examples/device/cdc_msc_hid/src/tusb_config.h | 15 +++++-- src/class/msc/msc_device.h | 10 ----- src/device/usbd_auto_desc.c | 63 +++++++++++++++++++-------- 3 files changed, 57 insertions(+), 31 deletions(-) (limited to 'src/class') diff --git a/examples/device/cdc_msc_hid/src/tusb_config.h b/examples/device/cdc_msc_hid/src/tusb_config.h index 0634c9576..a9a356f20 100644 --- a/examples/device/cdc_msc_hid/src/tusb_config.h +++ b/examples/device/cdc_msc_hid/src/tusb_config.h @@ -52,7 +52,7 @@ // defined by compiler flags for flexibility #ifndef CFG_TUSB_MCU - #error CFG_TUSB_MCU should be defined using compiler flags + #error CFG_TUSB_MCU must be defined #endif #if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX @@ -93,12 +93,22 @@ */ #define CFG_TUD_DESC_AUTO 1 -/* USB VID/PID if not defined, tinyusb to use default value +/* If USB VID/PID is not defined, tinyusb will use default value * Note: different class combination e.g CDC and (CDC + MSC) should have different * PID since Host OS will "remembered" device driver after the first plug */ // #define CFG_TUD_DESC_VID 0xCAFE // #define CFG_TUD_DESC_PID 0x0001 +// LPC175x_6x's endpoint type (bulk/interrupt/iso) are fixed by its number +// Therefor we need to force endpoint number to correct type on lpc17xx +#if CFG_TUSB_MCU == OPT_MCU_LPC175X_6X +#define CFG_TUD_DESC_CDC_EPNUM_NOTIF 1 +#define CFG_TUD_DESC_CDC_EPNUM 2 +#define CFG_TUD_DESC_MSC_EPNUM 5 +#define CFG_TUD_DESC_HID_KEYBOARD_EPNUM 4 +#define CFG_TUD_DESC_HID_MOUSE_EPNUM 7 +#endif + //------------- CLASS -------------// #define CFG_TUD_CDC 1 #define CFG_TUD_MSC 1 @@ -114,7 +124,6 @@ #define CFG_TUD_HID_KEYBOARD_BOOT 1 #define CFG_TUD_HID_MOUSE_BOOT 1 - //-------------------------------------------------------------------- // CDC //-------------------------------------------------------------------- diff --git a/src/class/msc/msc_device.h b/src/class/msc/msc_device.h index b268830ca..4053679b8 100644 --- a/src/class/msc/msc_device.h +++ b/src/class/msc/msc_device.h @@ -71,16 +71,6 @@ TU_VERIFY_STATIC(CFG_TUD_MSC_BUFSIZE < UINT16_MAX, "Size is not correct"); #error CFG_TUD_MSC_PRODUCT_REV 4-byte string must be defined #endif -// TODO highspeed device is 512 -#ifndef CFG_TUD_MSC_EPSIZE -#if TUD_OPT_HIGH_SPEED -#define CFG_TUD_MSC_EPSIZE 512 -#else -#define CFG_TUD_MSC_EPSIZE 64 -#endif -#endif - - #ifdef __cplusplus extern "C" { #endif diff --git a/src/device/usbd_auto_desc.c b/src/device/usbd_auto_desc.c index 2d54a934d..028d1b433 100644 --- a/src/device/usbd_auto_desc.c +++ b/src/device/usbd_auto_desc.c @@ -101,18 +101,19 @@ enum ITF_NUM_TOTAL }; -enum { - ITF_STR_LANGUAGE = 0 , - ITF_STR_MANUFACTURER , - ITF_STR_PRODUCT , - ITF_STR_SERIAL , +enum +{ + ITF_STR_LANGUAGE = 0 , + ITF_STR_MANUFACTURER , + ITF_STR_PRODUCT , + ITF_STR_SERIAL , #if CFG_TUD_CDC - ITF_STR_CDC , + ITF_STR_CDC , #endif #if CFG_TUD_MSC - ITF_STR_MSC , + ITF_STR_MSC , #endif #if CFG_TUD_HID_KEYBOARD && CFG_TUD_HID_KEYBOARD_BOOT @@ -133,23 +134,51 @@ enum { #define _EP_OUT(x) (x) // CDC -#define EP_CDC_NOTIF _EP_IN ( ITF_NUM_CDC+1 ) +#ifdef CFG_TUD_DESC_CDC_EPNUM_NOTIF + #define EP_CDC_NOTIF _EP_IN (CFG_TUD_DESC_CDC_EPNUM_NOTIF) +#else + #define EP_CDC_NOTIF _EP_IN ( ITF_NUM_CDC+1 ) +#endif #define EP_CDC_NOTIF_SIZE 8 -#define EP_CDC_OUT _EP_OUT( ITF_NUM_CDC+2 ) -#define EP_CDC_IN _EP_IN ( ITF_NUM_CDC+2 ) +#ifdef CFG_TUD_DESC_CDC_EPNUM + #define EP_CDC_OUT _EP_OUT( CFG_TUD_DESC_CDC_EPNUM ) + #define EP_CDC_IN _EP_IN ( CFG_TUD_DESC_CDC_EPNUM ) +#else + #define EP_CDC_OUT _EP_OUT( ITF_NUM_CDC+2 ) + #define EP_CDC_IN _EP_IN ( ITF_NUM_CDC+2 ) +#endif // Mass Storage -#define EP_MSC_OUT _EP_OUT( ITF_NUM_MSC+1 ) -#define EP_MSC_IN _EP_IN ( ITF_NUM_MSC+1 ) +#ifdef CFG_TUD_DESC_MSC_EPNUM + #define EP_MSC_OUT _EP_OUT( CFG_TUD_DESC_MSC_EPNUM ) + #define EP_MSC_IN _EP_IN ( CFG_TUD_DESC_MSC_EPNUM ) +#else + #define EP_MSC_OUT _EP_OUT( ITF_NUM_MSC+1 ) + #define EP_MSC_IN _EP_IN ( ITF_NUM_MSC+1 ) +#endif + +#if TUD_OPT_HIGH_SPEED +#define EP_MSC_SIZE 512 +#else +#define EP_MSC_SIZE 64 +#endif // HID Keyboard with boot protocol -#define EP_HID_KBD_BOOT _EP_IN ( ITF_NUM_HID_BOOT_KBD+1 ) +#ifdef CFG_TUD_DESC_HID_KEYBOARD_EPNUM + #define EP_HID_KBD_BOOT _EP_IN ( CFG_TUD_DESC_HID_KEYBOARD_EPNUM ) +#else + #define EP_HID_KBD_BOOT _EP_IN ( ITF_NUM_HID_BOOT_KBD+1 ) +#endif #define EP_HID_KBD_BOOT_SZ 8 // HID Mouse with boot protocol -#define EP_HID_MSE_BOOT _EP_IN ( ITF_NUM_HID_BOOT_MSE+1 ) +#ifdef CFG_TUD_DESC_HID_MOUSE_EPNUM + #define EP_HID_MSE_BOOT _EP_IN ( CFG_TUD_DESC_HID_MOUSE_EPNUM ) +#else + #define EP_HID_MSE_BOOT _EP_IN ( ITF_NUM_HID_BOOT_MSE+1 ) +#endif #define EP_HID_MSE_BOOT_SZ 8 // HID composite = keyboard + mouse + gamepad + etc ... @@ -466,7 +495,7 @@ desc_auto_cfg_t const _desc_auto_config_struct = .bDescriptorType = TUSB_DESC_ENDPOINT, .bEndpointAddress = EP_MSC_OUT, .bmAttributes = { .xfer = TUSB_XFER_BULK }, - .wMaxPacketSize = { .size = CFG_TUD_MSC_EPSIZE}, + .wMaxPacketSize = { .size = EP_MSC_SIZE}, .bInterval = 1 }, @@ -476,7 +505,7 @@ desc_auto_cfg_t const _desc_auto_config_struct = .bDescriptorType = TUSB_DESC_ENDPOINT, .bEndpointAddress = EP_MSC_IN, .bmAttributes = { .xfer = TUSB_XFER_BULK }, - .wMaxPacketSize = { .size = CFG_TUD_MSC_EPSIZE}, + .wMaxPacketSize = { .size = EP_MSC_SIZE}, .bInterval = 1 } }, @@ -563,7 +592,6 @@ desc_auto_cfg_t const _desc_auto_config_struct = #endif // boot mouse #if AUTO_DESC_HID_GENERIC - //------------- HID Generic Multiple report -------------// .hid_generic = { @@ -601,7 +629,6 @@ desc_auto_cfg_t const _desc_auto_config_struct = .bInterval = 0x0A } } - #endif // hid generic }; -- cgit v1.3.1 From d96347a0f5ec9272088b11425e1a8a3fb4115e8a Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 30 Nov 2018 12:48:06 +0700 Subject: rename OPT_MCU_LPC13UXX to OPT_MCU_LPC13XX --- examples/device/device_virtual_com/src/tusb_config.h | 8 ++++---- examples/obsolete/device/device_freertos/.cproject | 2 +- examples/obsolete/device/device_os_none/.cproject | 2 +- examples/obsolete/device/src/msc_device_app.h | 2 +- examples/obsolete/device/src/tusb_config.h | 8 ++++---- hw/mcu/nxp/lpc13uxx/hal_mcu/hal_lpc13uxx.c | 2 +- src/class/msc/msc_device.c | 2 +- src/portable/nxp/lpc11xx_lpc13xx/dcd_lpc_11uxx_13uxx.c | 2 +- src/tusb_option.h | 4 ++-- 9 files changed, 16 insertions(+), 16 deletions(-) (limited to 'src/class') diff --git a/examples/device/device_virtual_com/src/tusb_config.h b/examples/device/device_virtual_com/src/tusb_config.h index fd3f41b01..77be85df3 100644 --- a/examples/device/device_virtual_com/src/tusb_config.h +++ b/examples/device/device_virtual_com/src/tusb_config.h @@ -92,7 +92,7 @@ //--------------------------------------------------------------------+ #ifdef __CODE_RED // compiled with lpcxpresso - #if (CFG_TUSB_MCU == OPT_MCU_LPC11UXX) || (CFG_TUSB_MCU == OPT_MCU_LPC13UXX) + #if (CFG_TUSB_MCU == OPT_MCU_LPC11UXX) || (CFG_TUSB_MCU == OPT_MCU_LPC13XX) #define CFG_TUSB_MEM_SECTION ATTR_SECTION(.data.$RAM2) ATTR_ALIGNED(64) // lp11u & lp13u requires data to be 64 byte aligned #elif CFG_TUSB_MCU == OPT_MCU_LPC175X_6X #define CFG_TUSB_MEM_SECTION // LPC17xx USB DMA can access all @@ -102,7 +102,7 @@ #elif defined __CC_ARM // Compiled with Keil armcc, USBRAM_SECTION is defined in scatter files - #if (CFG_TUSB_MCU == OPT_MCU_LPC11UXX) || (CFG_TUSB_MCU == OPT_MCU_LPC13UXX) + #if (CFG_TUSB_MCU == OPT_MCU_LPC11UXX) || (CFG_TUSB_MCU == OPT_MCU_LPC13XX) #define CFG_TUSB_MEM_SECTION ATTR_SECTION(USBRAM_SECTION) ATTR_ALIGNED(64) // lp11u & lp13u requires data to be 64 byte aligned #elif (CFG_TUSB_MCU == OPT_MCU_LPC175X_6X) #define CFG_TUSB_MEM_SECTION // LPC17xx USB DMA can access all address @@ -112,7 +112,7 @@ #elif defined __ICCARM__ // compiled with IAR - #if (CFG_TUSB_MCU == OPT_MCU_LPC11UXX) || (CFG_TUSB_MCU == OPT_MCU_LPC13UXX) + #if (CFG_TUSB_MCU == OPT_MCU_LPC11UXX) || (CFG_TUSB_MCU == OPT_MCU_LPC13XX) #define CFG_TUSB_MEM_SECTION _Pragma("location=\"USB_PACKET_MEMORY\"") ATTR_ALIGNED(64) #elif (CFG_TUSB_MCU == OPT_MCU_LPC175X_6X) #define CFG_TUSB_MEM_SECTION @@ -132,7 +132,7 @@ // LPC11uxx and LPC13uxx requires each buffer has to be 64-byte alignment -#if CFG_TUSB_MCU == OPT_MCU_LPC11UXX || CFG_TUSB_MCU == OPT_MCU_LPC13UXX +#if CFG_TUSB_MCU == OPT_MCU_LPC11UXX || CFG_TUSB_MCU == OPT_MCU_LPC13XX #define CFG_TUSB_MEM_ALIGN ATTR_ALIGNED(64) #elif CFG_TUSB_MCU == OPT_MCU_NRF5X #define CFG_TUSB_MEM_ALIGN ATTR_ALIGNED(4) diff --git a/examples/obsolete/device/device_freertos/.cproject b/examples/obsolete/device/device_freertos/.cproject index eb09f25e7..53b3552b1 100644 --- a/examples/obsolete/device/device_freertos/.cproject +++ b/examples/obsolete/device/device_freertos/.cproject @@ -34,7 +34,7 @@ - + diff --git a/examples/obsolete/device/device_os_none/.cproject b/examples/obsolete/device/device_os_none/.cproject index fabc46d88..355f8ba96 100644 --- a/examples/obsolete/device/device_os_none/.cproject +++ b/examples/obsolete/device/device_os_none/.cproject @@ -33,7 +33,7 @@