From da03595c32f3822d0b8c96ab61ec7b65131196ee Mon Sep 17 00:00:00 2001 From: Zach Eveland Date: Thu, 27 Oct 2011 10:23:06 -0400 Subject: brought nuevo_diskloader changes over to diskloader Moved nuevo_diskloader files into diskloader directory. Changed back to real PID for Leonardo --- bootloaders/diskloader/src/CDC.cpp | 173 +++++++++ bootloaders/diskloader/src/DiskLoader.cpp | 333 +++++++++------- bootloaders/diskloader/src/Platform.h | 63 +++- bootloaders/diskloader/src/USBAPI.h | 83 ++++ bootloaders/diskloader/src/USBCore.cpp | 609 +++++++++++++++++++----------- bootloaders/diskloader/src/USBCore.h | 89 ++++- bootloaders/diskloader/src/USBDesc.cpp | 82 ---- bootloaders/diskloader/src/USBDesc.h | 62 +-- 8 files changed, 976 insertions(+), 518 deletions(-) create mode 100644 bootloaders/diskloader/src/CDC.cpp create mode 100644 bootloaders/diskloader/src/USBAPI.h delete mode 100644 bootloaders/diskloader/src/USBDesc.cpp (limited to 'bootloaders/diskloader/src') diff --git a/bootloaders/diskloader/src/CDC.cpp b/bootloaders/diskloader/src/CDC.cpp new file mode 100644 index 0000000..cc798b4 --- /dev/null +++ b/bootloaders/diskloader/src/CDC.cpp @@ -0,0 +1,173 @@ + + +/* Copyright (c) 2011, Peter Barrett +** +** Permission to use, copy, modify, and/or distribute this software for +** any purpose with or without fee is hereby granted, provided that the +** above copyright notice and this permission notice appear in all copies. +** +** THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL +** WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED +** WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR +** BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES +** OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +** WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +** ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS +** SOFTWARE. +*/ + +#include "Platform.h" +#include "USBAPI.h" +#include + +#if defined(USBCON) +#ifdef CDC_ENABLED + +void Reboot() +{ + USB.detach(); + cli(); + asm volatile("jmp 0x7800"); // jump to bootloader - DiskLoader takes up last 2 kB +} + +typedef struct +{ + u32 dwDTERate; + u8 bCharFormat; + u8 bParityType; + u8 bDataBits; + u8 lineState; +} LineInfo; + +static volatile LineInfo _usbLineInfo = { 57600, 0x00, 0x00, 0x00, 0x00 }; + +#define WEAK __attribute__ ((weak)) + +extern const CDCDescriptor _cdcInterface PROGMEM; +const CDCDescriptor _cdcInterface = +{ + D_IAD(0,2,CDC_COMMUNICATION_INTERFACE_CLASS,CDC_ABSTRACT_CONTROL_MODEL,1), + + // CDC communication interface + D_INTERFACE(CDC_ACM_INTERFACE,1,CDC_COMMUNICATION_INTERFACE_CLASS,CDC_ABSTRACT_CONTROL_MODEL,0), + D_CDCCS(CDC_HEADER,0x10,0x01), // Header (1.10 bcd) + D_CDCCS(CDC_CALL_MANAGEMENT,1,1), // Device handles call management (not) + D_CDCCS4(CDC_ABSTRACT_CONTROL_MANAGEMENT,6), // SET_LINE_CODING, GET_LINE_CODING, SET_CONTROL_LINE_STATE supported + D_CDCCS(CDC_UNION,CDC_ACM_INTERFACE,CDC_DATA_INTERFACE), // Communication interface is master, data interface is slave 0 + D_ENDPOINT(USB_ENDPOINT_IN (CDC_ENDPOINT_ACM),USB_ENDPOINT_TYPE_INTERRUPT,0x10,0x40), + + // CDC data interface + D_INTERFACE(CDC_DATA_INTERFACE,2,CDC_DATA_INTERFACE_CLASS,0,0), + D_ENDPOINT(USB_ENDPOINT_OUT(CDC_ENDPOINT_OUT),USB_ENDPOINT_TYPE_BULK,0x40,0), + D_ENDPOINT(USB_ENDPOINT_IN (CDC_ENDPOINT_IN ),USB_ENDPOINT_TYPE_BULK,0x40,0) +}; + +int WEAK CDC_GetInterface(u8* interfaceNum) +{ + interfaceNum[0] += 2; // uses 2 + return USB_SendControl(TRANSFER_PGM,&_cdcInterface,sizeof(_cdcInterface)); +} + +bool WEAK CDC_Setup(Setup& setup) +{ + u8 r = setup.bRequest; + u8 requestType = setup.bmRequestType; + + if (REQUEST_DEVICETOHOST_CLASS_INTERFACE == requestType) + { + if (CDC_GET_LINE_CODING == r) + { + USB_SendControl(0,(void*)&_usbLineInfo,7); + return true; + } + } + + if (REQUEST_HOSTTODEVICE_CLASS_INTERFACE == requestType) + { + if (CDC_SET_LINE_CODING == r) + { + USB_RecvControl((void*)&_usbLineInfo,7); + return true; + } + + if (CDC_SET_CONTROL_LINE_STATE == r) + { +// if (0 != _usbLineInfo.lineState && 1200 == _usbLineInfo.dwDTERate) // auto-reset is triggered when the port, already open at 1200 bps, is closed +// Reboot(); + _usbLineInfo.lineState = setup.wValueL; + return true; + } + } + return false; +} + +/* +int _serialPeek = -1; +void Serial_::begin(uint16_t baud_count) +{ +} + +void Serial_::end(void) +{ +} + +int Serial_::available(void) +{ + u8 avail = USB_Available(CDC_RX); + if (_serialPeek != -1) + avail++; + return avail; +} + +// peek is nasty +int Serial_::peek(void) +{ + if (_serialPeek == -1) + _serialPeek = read(); + return _serialPeek; +} + +int Serial_::read(void) +{ + int c; + if (_serialPeek != -1) + { + c = _serialPeek; + _serialPeek = -1; + } else { + c = USB_Recv(CDC_RX); + } + return c; +} + + + +void Serial_::flush(void) +{ + USB_Flush(CDC_TX); +} + +size_t Serial_::write(uint8_t c) +{ + + // TODO - ZE - check behavior on different OSes and test what happens if an + // open connection isn't broken cleanly (cable is yanked out, host dies + // or locks up, or host virtual serial port hangs) + if (_usbLineInfo.lineState > 0) { + int r = USB_Send(CDC_TX,&c,1); + if (r > 0) { + return r; + } else { +// setWriteError(); + return 0; + } + } +// setWriteError(); + return 0; +} + +Serial_ Serial; +*/ + +#endif +#endif /* if defined(USBCON) */ \ No newline at end of file diff --git a/bootloaders/diskloader/src/DiskLoader.cpp b/bootloaders/diskloader/src/DiskLoader.cpp index 6580618..216ddc6 100644 --- a/bootloaders/diskloader/src/DiskLoader.cpp +++ b/bootloaders/diskloader/src/DiskLoader.cpp @@ -1,65 +1,56 @@ - +/* + * DiskLoader.cpp + */ #include "Platform.h" +//#include "USBCore.h" -// This bootloader creates a composite Serial device -// -// The serial interface supports a STK500v1 protocol that is very similar to optiboot -// -// The bootloader will timeout and start the firmware after a few hundred milliseconds -// if a usb connection is not detected. -// -// The tweakier code is to keep the bootloader below 2k (no interrupt table, for example) extern "C" void entrypoint(void) __attribute__ ((naked)) __attribute__ ((section (".vectors"))); void entrypoint(void) { asm volatile ( - "eor r1, r1\n" // Zero register - "out 0x3F, r1\n" // SREG - "ldi r28, 0xFF\n" - "ldi r29, 0x0A\n" - "out 0x3E, r29\n" // SPH - "out 0x3D, r28\n" // SPL - "rjmp main" // Stack is all set up, start the main code - ::); + "eor r1, r1\n" // Zero register + "out 0x3F, r1\n" // SREG + "ldi r28, 0xFF\n" // Y-register + "ldi r29, 0x0A\n" // Y-register + "out 0x3E, r29\n" // SPH + "out 0x3D, r28\n" // SPL + "rjmp main" // Stack is all set up, start the main code + ::); } u8 _flashbuf[128]; u8 _inSync; u8 _ok; -extern volatile u8 _ejected; -extern volatile u16 _timeout; +u16 do_reset = 0; +volatile u16 _timeout; void Program(u8 ep, u16 page, u8 count) { - u8 write = page < 30*1024; // Don't write over firmware please + u8 write = page < 28*1024; // Don't write over bootloader please if (write) boot_page_erase(page); - - Recv(ep,_flashbuf,count); // Read while page is erasing - + + USB_Recv_block(ep,_flashbuf,count); // Read while page is erasing + if (!write) return; - + boot_spm_busy_wait(); // Wait until the memory is erased. - + count >>= 1; u16* p = (u16*)page; u16* b = (u16*)_flashbuf; for (u8 i = 0; i < count; i++) boot_page_fill(p++, b[i]); - + boot_page_write(page); boot_spm_busy_wait(); boot_rww_enable (); } - -int USBGetChar(); -#define getch USBGetChar - #define HW_VER 0x02 #define SW_MAJOR 0x01 #define SW_MINOR 0x10 @@ -104,136 +95,186 @@ const u8 _consts[] = 0x00, // }; +//int getch(void) +//{ +// u16 timeout; +// u8 c; +// for (timeout = 0; timeout; timeout--) +// { +// c = USB_Recv(CDC_RX); +// if (c != -1) +// return c; +// } +// return -1; +//} + + +void start_sketch() +{ + UDCON = 1; // Detatch USB + UDIEN = 0; + asm volatile ( // Reset vector to run firmware + "clr r30\n" + "clr r31\n" + "ijmp\n" + ::); +} -void USBInit(void); int main(void) __attribute__ ((naked)); - -// STK500v1 main loop, very similar to optiboot in protocol and implementation -int main() -{ +int main() +{ wdt_disable(); - TXLED0; - RXLED0; - LED0; BOARD_INIT(); - USBInit(); - + /* move interrupts to boot section: + * uses inline assembly because the procedure must be completed in four cycles. + * seems to fail if called before disabling WDT and calling BOARD_INIT() + */ + asm volatile ( + "ldi r16, 0x01\n" // (1< 2) + i = (i==0x18) ? 3 : 4; // 0x80:HW_VER,0x81:SW_MAJOR,0x82:SW_MINOR,0x18:3 or 0 + pgm = _consts + i + 3; + send = 1; + } + else if (STK_UNIVERSAL == cmd) + { + if (packet[0] == 0x30) + pgm = _consts + packet[2]; + send = 1; + } + else if (STK_READ_SIGN == cmd) + { + pgm = _consts; + send = 3; + } + else if (STK_LOAD_ADDRESS == cmd) + { + address = *((u16*)packet); // word address + address += address; + } + else if (STK_PROG_PAGE == cmd) + { + Program(CDC_RX, address, packet[1]); + } + else if (STK_READ_PAGE == cmd) + { + send = packet[1]; + pgm = (const u8*)address; + address += send; + } + + // Check sync + // if (Serial.available() > 0 && Serial.read() != ' ') + // break; + // if (USB_Available(CDC_RX) && USB_Recv(CDC_RX) != ' ') + + // u8 countdown = 10; + // while (!USB_Available(CDC_RX)) + // { + // if (countdown-- == 0) + // break; + // } + // u8 x = USB_Recv(CDC_RX); + // if (x != -1 && x != ' ') + // { + // L_LED_ON(); + // break; + // } + + // if (getch() != ' ') + // break; + + // while (!USB_Available(CDC_RX)) + // ; + // + // int x = USB_Recv(CDC_RX); + // if (x == -1) + // { + // UEINTX = 0x6B; + // break; + // } + // else if (x != ' ') + // { + //// UEINTX = 0x6B; + // break; + // } + + u16 countdown = 5000; + while (countdown-- > 10 && !USB_Available(CDC_RX)) + ; + int x = USB_Recv(CDC_RX); + if (x != -1 && x != ' ') break; + + USB_Send(CDC_TX, &_inSync, 1); + + if (send) + USB_Send(CDC_TX|TRANSFER_PGM, pgm, send); + + // Send ok + USB_Send(CDC_TX|TRANSFER_RELEASE, &_ok, 1); + + if ('Q' == cmd) + { + _delay_ms(100); + /* move interrupts to application section: + * uses inline assembly because the procedure must be completed in four cycles. + */ + asm volatile ( + "ldi r16, 0x01\n" // (1< 2) - i = (i == 0x18) ? 3 : 4; // 0x80:HW_VER,0x81:SW_MAJOR,0x82:SW_MINOR,0x18:3 or 0 - pgm = _consts + i + 3; - send = 1; - } - - else if (STK_UNIVERSAL == cmd) - { - if (packet[0] == 0x30) - pgm = _consts + packet[2]; // read signature - send = 1; - } - - // Read signature bytes - else if (STK_READ_SIGN == cmd) - { - pgm = _consts; - send = 3; - } - - else if (STK_LOAD_ADDRESS == cmd) - { - address = *((u16*)packet); // word addresses - address += address; - } - - else if (STK_PROG_PAGE == cmd) - { - Program(CDC_RX,address,packet[1]); - } - - else if (STK_READ_PAGE == cmd) - { - send = packet[1]; - pgm = (const u8*)address; - address += send; // not sure of this is required - } - - // Check sync - if (getch() != ' ') - break; - Transfer(CDC_TX,&_inSync,1); - - // Send result - if (send) - Transfer(CDC_TX|TRANSFER_PGM,pgm,send); // All from pgm memory - - // Send ok - Transfer(CDC_TX|TRANSFER_RELEASE,&_ok,1); - - if (cmd == 'Q') - break; } - _timeout = 500; // wait a moment before exiting the bootloader - may need to finish responding to 'Q' for example - _ejected = 1; } } - -// Nice breathing LED indicates we are in the firmware -u16 _pulse; -void LEDPulse() -{ - _pulse += 4; - u8 p = _pulse >> 9; - if (p > 63) - p = 127-p; - p += p; - if (((u8)_pulse) > p) - LED0; - else - LED1; -} - -void Reboot() -{ - TXLED0; // switch off the RX and TX LEDs before starting the user sketch - RXLED0; - UDCON = 1; // Detatch USB - UDIEN = 0; - asm volatile ( // Reset vector to run firmware - "clr r30\n" - "clr r31\n" - "ijmp\n" - ::); -} diff --git a/bootloaders/diskloader/src/Platform.h b/bootloaders/diskloader/src/Platform.h index 6acbf39..4b58f9f 100644 --- a/bootloaders/diskloader/src/Platform.h +++ b/bootloaders/diskloader/src/Platform.h @@ -1,3 +1,9 @@ +/* + * Platform.h + */ + +#ifndef __PLATFORM_H__ +#define __PLATFORM_H__ #include #include @@ -11,39 +17,56 @@ #include #include +#ifdef __cplusplus +extern "C"{ +#endif + typedef unsigned char u8; typedef unsigned short u16; typedef unsigned long u32; - -#define CPU_PRESCALE(n) (CLKPR = 0x80, CLKPR = (n)) -#define DISABLE_JTAG() MCUCR = (1 << JTD) | (1 << IVCE) | (0 << PUD); MCUCR = (1 << JTD) | (0 << IVSEL) | (0 << IVCE) | (0 << PUD); +#define CDC_ENABLED #define USB_PID_LEONARDO 0x0034 #define USB_PID_MICRO 0x0035 #define USB_VID 0x2341 // arduino LLC vid #define USB_PID ARDUINO_MODEL_PID // passed in by Makefile - 0x0034 for Leonardo, 0x0035 for MIcro -#define OEM_NAME 'l','e','o','n','a','r','d','o' // 8 chars -#define BOARD_INIT() DDRC |= (1<<7); DDRB |= (1<<0); DDRD |= (1<<5); CPU_PRESCALE(0); DISABLE_JTAG(); -#define LED0 PORTC &= ~(1<<7) -#define LED1 PORTC |= (1<<7) -#define TXLED0 PORTD |= (1<<5) -#define TXLED1 PORTD &= ~(1<<5) -#define RXLED0 PORTB |= (1<<0) -#define RXLED1 PORTB &= ~(1<<0) +//#include "USBDesc.h" +//#include "../../../cores/arduino/USBCore.h" -#define TRANSFER_PGM 0x80 -#define TRANSFER_RELEASE 0x40 -#define TRANSFER_ZERO 0x20 -void Transfer(u8 ep, const u8* data, int len); -void Recv(u8 ep, u8* dst, u8 len); -void Program(u8 ep, u16 page, u8 count); +#define min(a,b) ((a)<(b)?(a):(b)) -#define CDC_ENABLED +#define CPU_PRESCALE(n) (CLKPR = 0x80, CLKPR = (n)) +#define DISABLE_JTAG() MCUCR = (1 << JTD) | (1 << IVCE) | (0 << PUD); MCUCR = (1 << JTD) | (0 << IVSEL) | (0 << IVCE) | (0 << PUD) -#include "USBCore.h" -#include "USBDesc.h" +#define BOARD_INIT() DDRC |= (1<<7); DDRB |= (1<<0); DDRE |= (1<<6); CPU_PRESCALE(0); DISABLE_JTAG(); // for XXX-series boards +//#define BOARD_INIT() DDRC |= (1<<7); DDRB |= (1<<0); DDRD |= (1<<5); CPU_PRESCALE(0); DISABLE_JTAG(); // for non-XXX boards + +// for XXX-series boards +#define TX_LED_OFF() PORTE |= (1<<6) +#define TX_LED_ON() PORTE &= ~(1<<6) +#define RX_LED_OFF() PORTB |= (1<<0) +#define RX_LED_ON() PORTB &= ~(1<<0) +#define L_LED_OFF() PORTC &= ~(1<<7) +#define L_LED_ON() PORTC |= (1<<7) +#define L_LED_TOGGLE() PORTC ^= (1<<7) +// these for non-XXX boards +//#define LED0 PORTC &= ~(1<<7) +//#define LED1 PORTC |= (1<<7) +//#define TXLED0 PORTD |= (1<<5) +//#define TXLED1 PORTD &= ~(1<<5) +//#define RXLED0 PORTB |= (1<<0) +//#define RXLED1 PORTB &= ~(1<<0) + +#ifdef __cplusplus +} /* extern "C"{ */ +#endif + +#include "USBDesc.h" +#include "USBCore.h" +#include "USBAPI.h" +#endif /* __PLATFORM_H__ */ diff --git a/bootloaders/diskloader/src/USBAPI.h b/bootloaders/diskloader/src/USBAPI.h new file mode 100644 index 0000000..1724ce1 --- /dev/null +++ b/bootloaders/diskloader/src/USBAPI.h @@ -0,0 +1,83 @@ + + +#ifndef __USBAPI__ +#define __USBAPI__ + +#if defined(USBCON) + +//================================================================================ +//================================================================================ +// USB + +class USB_ +{ +public: + USB_(); + bool configured(); + + void attach(); + void detach(); // Serial port goes down too... + void poll(); +}; +extern USB_ USB; + +//================================================================================ +//================================================================================ +// Serial over CDC (Serial1 is the physical port) + +class Serial_ +{ +public: + void begin(uint16_t baud_count); + void end(void); + + virtual int available(void); + virtual int peek(void); + virtual int read(void); + virtual void flush(void); + virtual size_t write(uint8_t); +}; +extern Serial_ Serial; + +//================================================================================ +//================================================================================ +// Low level API + +typedef struct +{ + uint8_t bmRequestType; + uint8_t bRequest; + uint8_t wValueL; + uint8_t wValueH; + uint16_t wIndex; + uint16_t wLength; +} Setup; + +//================================================================================ +//================================================================================ +// CDC 'Driver' + +int CDC_GetInterface(uint8_t* interfaceNum); +int CDC_GetDescriptor(int i); +bool CDC_Setup(Setup& setup); + +//================================================================================ +//================================================================================ + +#define TRANSFER_PGM 0x80 +#define TRANSFER_RELEASE 0x40 +#define TRANSFER_ZERO 0x20 + +int USB_SendControl(uint8_t flags, const void* d, int len); +int USB_RecvControl(void* d, int len); + +uint8_t USB_Available(uint8_t ep); +int USB_Send(uint8_t ep, const void* data, int len); // blocking +int USB_Recv(uint8_t ep, void* data, int len); // non-blocking +void USB_Recv_block(u8 ep, u8* dst, int len); // blocking +int USB_Recv(uint8_t ep); // non-blocking +void USB_Flush(uint8_t ep); + +#endif + +#endif /* if defined(USBCON) */ \ No newline at end of file diff --git a/bootloaders/diskloader/src/USBCore.cpp b/bootloaders/diskloader/src/USBCore.cpp index ca74721..56944e5 100644 --- a/bootloaders/diskloader/src/USBCore.cpp +++ b/bootloaders/diskloader/src/USBCore.cpp @@ -17,9 +17,10 @@ */ #include "Platform.h" +#include "USBAPI.h" +#include "USBDesc.h" -#define CDC_TX CDC_ENDPOINT_IN -#define CDC_RX CDC_ENDPOINT_OUT +#if defined(USBCON) #define EP_TYPE_CONTROL 0x00 #define EP_TYPE_BULK_IN 0x81 @@ -31,32 +32,54 @@ /** Pulse generation counters to keep track of the number of milliseconds remaining for each pulse type */ #define TX_RX_LED_PULSE_MS 100 -u8 TxLEDPulse; /**< Milliseconds remaining for data Tx LED pulse */ -u8 RxLEDPulse; /**< Milliseconds remaining for data Rx LED pulse */ - -void Reboot(); +volatile u8 TxLEDPulse; /**< Milliseconds remaining for data Tx LED pulse */ +volatile u8 RxLEDPulse; /**< Milliseconds remaining for data Rx LED pulse */ //================================================================== //================================================================== -typedef struct -{ - u32 dwDTERate; - u8 bCharFormat; - u8 bParityType; - u8 bDataBits; - u8 lineState; -} LineInfo; +extern const u16 STRING_LANGUAGE[] PROGMEM; +extern const u16 STRING_IPRODUCT[] PROGMEM; +extern const u16 STRING_IMANUFACTURER[] PROGMEM; +extern const DeviceDescriptor USB_DeviceDescriptor PROGMEM; +extern const DeviceDescriptor USB_DeviceDescriptorA PROGMEM; + +const u16 STRING_LANGUAGE[2] = { + (3<<8) | (2+2), + 0x0409 // English +}; + +const u16 STRING_IPRODUCT[17] = { + (3<<8) | (2+2*16), +#if USB_PID == USB_PID_LEONARDO + 'A','r','d','u','i','n','o',' ','L','e','o','n','a','r','d','o' +#elif USB_PID == USB_PID_MICRO + 'A','r','d','u','i','n','o',' ','M','i','c','r','o',' ',' ',' ' +#endif +}; -static volatile LineInfo _usbLineInfo = { 57600, 0x00, 0x00, 0x00, 0x00 }; +const u16 STRING_IMANUFACTURER[12] = { + (3<<8) | (2+2*11), + 'A','r','d','u','i','n','o',' ','L','L','C' +}; + +#ifdef CDC_ENABLED +#define DEVICE_CLASS 0x02 +#else +#define DEVICE_CLASS 0x00 +#endif + +// DEVICE DESCRIPTOR +const DeviceDescriptor USB_DeviceDescriptor = + D_DEVICE(0x00,0x00,0x00,64,USB_VID,USB_PID,0x100,IMANUFACTURER,IPRODUCT,0,1); + +const DeviceDescriptor USB_DeviceDescriptorA = + D_DEVICE(DEVICE_CLASS,0x00,0x00,64,USB_VID,USB_PID,0x100,IMANUFACTURER,IPRODUCT,0,1); //================================================================== //================================================================== -// 4 bytes of RAM -volatile u8 _usbConfiguration; -volatile u8 _ejected; -volatile u16 _timeout; +volatile u8 _usbConfiguration = 0; static inline void WaitIN(void) { @@ -86,34 +109,25 @@ static inline void ClearOUT(void) UEINTX = ~(1< len) + n = len; + len -= n; + { + LockEP lock(ep); + if (ep & TRANSFER_ZERO) + { + while (n--) + Send8(0); + } + else if (ep & TRANSFER_PGM) + { + while (n--) + Send8(pgm_read_byte(data++)); + } + else + { + while (n--) + Send8(*data++); + } + if (!ReadWriteAllowed() || ((len == 0) && (ep & TRANSFER_RELEASE))) // Release full buffer + ReleaseTX(); + } } if (ep & TRANSFER_RELEASE) ReleaseTX(); + + TX_LED_ON(); + TxLEDPulse = TX_RX_LED_PULSE_MS; + return r; } extern const u8 _initEndpoints[] PROGMEM; const u8 _initEndpoints[] = { 0, - + #ifdef CDC_ENABLED EP_TYPE_INTERRUPT_IN, // CDC_ENDPOINT_ACM EP_TYPE_BULK_OUT, // CDC_ENDPOINT_OUT EP_TYPE_BULK_IN, // CDC_ENDPOINT_IN #endif - EP_TYPE_INTERRUPT_IN, // HID_ENDPOINT_INT +#ifdef HID_ENABLED + EP_TYPE_INTERRUPT_IN // HID_ENDPOINT_INT +#endif }; -static void InitEndpoints() +#define EP_SINGLE_64 0x32 // EP0 +#define EP_DOUBLE_64 0x36 // Other endpoints + +static +void InitEP(u8 index, u8 type, u8 size) +{ + UENUM = index; + UECONX = 1; + UECFG0X = type; + UECFG1X = size; +} + +static +void InitEndpoints() { for (u8 i = 1; i < sizeof(_initEndpoints); i++) { @@ -277,99 +365,123 @@ static void InitEndpoints() UERST = 0; } -typedef struct +// Handle CLASS_INTERFACE requests +static +bool ClassInterfaceRequest(Setup& setup) { - u8 bmRequestType; - u8 bRequest; - u8 wValueL; - u8 wValueH; - u16 wIndex; - u16 wLength; -} Setup; -Setup _setup; + u8 i = setup.wIndex; -//bool USBHook(Setup& setup) -bool USBHook() -{ - Setup& setup = _setup; - u8 r = setup.bRequest; +#ifdef CDC_ENABLED + if (CDC_ACM_INTERFACE == i) + return CDC_Setup(setup); +#endif - // CDC Requests - if (CDC_GET_LINE_CODING == r) - { - Send((const volatile u8*)&_usbLineInfo,7); - } + return false; +} - else if (CDC_SET_LINE_CODING == r) +int _cmark; +int _cend; +void InitControl(int end) +{ + SetEP(0); + _cmark = 0; + _cend = end; +} + +static +bool SendControl(u8 d) +{ + if (_cmark < _cend) { - WaitOUT(); - Recv((volatile u8*)&_usbLineInfo,7); - ClearOUT(); + if (!WaitForINOrOUT()) + return false; + Send8(d); + if (!((_cmark + 1) & 0x3F)) + ClearIN(); // Fifo is full, release this packet } + _cmark++; + return true; +}; - else if (CDC_SET_CONTROL_LINE_STATE == r) +// Clipped by _cmark/_cend +int USB_SendControl(u8 flags, const void* d, int len) +{ + int sent = len; + const u8* data = (const u8*)d; + bool pgm = flags & TRANSFER_PGM; + while (len--) { - _usbLineInfo.lineState = setup.wValueL; + u8 c = pgm ? pgm_read_byte(data++) : *data++; + if (!SendControl(c)) + return -1; } - - return true; + return sent; } -extern const u8 _rawHID[] PROGMEM; -#define LSB(_x) ((_x) & 0xFF) -#define MSB(_x) ((_x) >> 8) - -#define RAWHID_USAGE_PAGE 0xFFC0 -#define RAWHID_USAGE 0x0C00 -#define RAWHID_TX_SIZE 64 -#define RAWHID_RX_SIZE 64 +// Does not timeout or cross fifo boundaries +// Will only work for transfers <= 64 bytes +// TODO +int USB_RecvControl(void* d, int len) +{ + WaitOUT(); + Recv((u8*)d,len); + ClearOUT(); + return len; +} -const u8 _rawHID[] = +int SendInterfaces() { - // RAW HID - 0x06, LSB(RAWHID_USAGE_PAGE), MSB(RAWHID_USAGE_PAGE), // 30 - 0x0A, LSB(RAWHID_USAGE), MSB(RAWHID_USAGE), + int total = 0; + u8 interfaces = 0; - 0xA1, 0x01, // Collection 0x01 - 0x85, 0x03, // REPORT_ID (3) - 0x75, 0x08, // report size = 8 bits - 0x15, 0x00, // logical minimum = 0 - 0x26, 0xFF, 0x00, // logical maximum = 255 +#ifdef CDC_ENABLED + total = CDC_GetInterface(&interfaces); +#endif - 0x95, 64, // report count TX - 0x09, 0x01, // usage - 0x81, 0x02, // Input (array) + return interfaces; +} - 0x95, 64, // report count RX - 0x09, 0x02, // usage - 0x91, 0x02, // Output (array) - 0xC0 // end collection -}; +// Construct a dynamic configuration descriptor +// This really needs dynamic endpoint allocation etc +// TODO +static +bool SendConfiguration(int maxlen) +{ + // Count and measure interfaces + InitControl(0); + int interfaces = SendInterfaces(); + ConfigDescriptor config = D_CONFIG(_cmark + sizeof(ConfigDescriptor),interfaces); + + // Now send them + InitControl(maxlen); + USB_SendControl(0,&config,sizeof(ConfigDescriptor)); + SendInterfaces(); + return true; +} u8 _cdcComposite = 0; -bool SendDescriptor() +static +bool SendDescriptor(Setup& setup) { - Setup& setup = _setup; + u8 t = setup.wValueH; + if (USB_CONFIGURATION_DESCRIPTOR_TYPE == t) + return SendConfiguration(setup.wLength); + + InitControl(setup.wLength); +#ifdef HID_ENABLED + if (HID_REPORT_DESCRIPTOR_TYPE == t) + return HID_GetDescriptor(t); +#endif + u8 desc_length = 0; const u8* desc_addr = 0; - - u8 t = setup.wValueH; - if (0x22 == t) - { - desc_addr = _rawHID; - desc_length = sizeof(desc_length); - } else if (USB_DEVICE_DESCRIPTOR_TYPE == t) + if (USB_DEVICE_DESCRIPTOR_TYPE == t) { if (setup.wLength == 8) _cdcComposite = 1; desc_addr = _cdcComposite ? (const u8*)&USB_DeviceDescriptorA : (const u8*)&USB_DeviceDescriptor; } - else if (USB_CONFIGURATION_DESCRIPTOR_TYPE == t) - { - desc_addr = (const u8*)&USB_ConfigDescriptor; - desc_length = sizeof(USB_ConfigDescriptor); - } else if (USB_STRING_DESCRIPTOR_TYPE == t) { if (setup.wValueL == 0) @@ -380,81 +492,106 @@ bool SendDescriptor() desc_addr = (const u8*)&STRING_IMANUFACTURER; else return false; - } else - return false; + } + if (desc_addr == 0) + return false; if (desc_length == 0) desc_length = pgm_read_byte(desc_addr); - if ((u8)setup.wLength < desc_length) // bit of a cheat limiting to 255 bytes TODO (saved 8 bytes) - desc_length = (u8)setup.wLength; - - // Send descriptor - // EP0 is 64 bytes long - // RWAL and FIFOCON don't work on EP0 - u8 n = 0; - do - { - if (!WaitForINOrOUT()) - return false; - Send8(pgm_read_byte(&desc_addr[n++])); - u8 clr = n & 0x3F; - if (!clr) - ClearIN(); // Fifo is full, release this packet - } while (n < desc_length); + + USB_SendControl(TRANSFER_PGM,desc_addr,desc_length); return true; } -void USBSetupInterrupt() +// Endpoint 0 interrupt +ISR(USB_COM_vect) { SetEP(0); if (!ReceivedSetupInt()) return; - Setup& setup = _setup; // global saves ~30 bytes + Setup setup; Recv((u8*)&setup,8); ClearSetupInt(); - if (setup.bmRequestType & DEVICETOHOST) + u8 requestType = setup.bmRequestType; + if (requestType & REQUEST_DEVICETOHOST) WaitIN(); else ClearIN(); bool ok = true; - u8 r = setup.bRequest; - if (SET_ADDRESS == r) - { - WaitIN(); - UDADDR = setup.wValueL | (1<