diff --git a/CMakeLists.txt b/CMakeLists.txt index 87d70f5..c5beb42 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -100,7 +100,8 @@ if(CMAKE_CROSSCOMPILING) add_link_options(-Wl,--gc-sections) # disable exceptions and related metadata - add_compile_options(-fno-exceptions -fno-unwind-tables -fno-rtti) + add_compile_options(-fno-exceptions -fno-unwind-tables) + add_compile_options($<$:-fno-rtti>) add_link_options(-Wl,--defsym,__exidx_start=0,--defsym,__exidx_end=0) else() if(CMAKE_BUILD_TYPE STREQUAL "Debug") @@ -158,7 +159,7 @@ endif() # add_link_dependency(firmware "${LINKER_SCRIPT}") -target_include_directories(firmware PRIVATE src) +target_include_directories(firmware PRIVATE src lib) target_compile_options(firmware PRIVATE -Wdouble-promotion) diff --git a/lib/AddLufa.cmake b/lib/AddLufa.cmake new file mode 100644 index 0000000..dab513b --- /dev/null +++ b/lib/AddLufa.cmake @@ -0,0 +1,19 @@ +add_library( + LUFA + Descriptors.c + lufa/LUFA/Drivers/USB/Class/Device/CDCClassDevice.c + lufa/LUFA/Drivers/USB/Core/AVR8/Device_AVR8.c + lufa/LUFA/Drivers/USB/Core/AVR8/Endpoint_AVR8.c + lufa/LUFA/Drivers/USB/Core/AVR8/EndpointStream_AVR8.c + lufa/LUFA/Drivers/USB/Core/AVR8/USBController_AVR8.c + lufa/LUFA/Drivers/USB/Core/AVR8/USBInterrupt_AVR8.c + lufa/LUFA/Drivers/USB/Core/ConfigDescriptors.c + lufa/LUFA/Drivers/USB/Core/DeviceStandardReq.c + lufa/LUFA/Drivers/USB/Core/Events.c + lufa/LUFA/Drivers/USB/Core/USBTask.c + ) + +target_include_directories(LUFA PRIVATE . lufa) +target_compile_options(LUFA PRIVATE -include lufa_config.h) + +target_compile_features(LUFA PUBLIC c_std_99) diff --git a/lib/CMakeLists.txt b/lib/CMakeLists.txt index 09159f6..17bbcac 100644 --- a/lib/CMakeLists.txt +++ b/lib/CMakeLists.txt @@ -1,3 +1,5 @@ if(NOT CMAKE_CROSSCOMPILING) add_subdirectory(Catch2) +else() + include(AddLufa.cmake) endif() diff --git a/lib/Descriptors.c b/lib/Descriptors.c new file mode 100644 index 0000000..fc87c9f --- /dev/null +++ b/lib/Descriptors.c @@ -0,0 +1,218 @@ +/* + LUFA Library + Copyright (C) Dean Camera, 2021. + + dean [at] fourwalledcubicle [dot] com + www.lufa-lib.org +*/ + +/* + Copyright 2021 Dean Camera (dean [at] fourwalledcubicle [dot] com) + + Permission to use, copy, modify, distribute, and sell this + software and its documentation for any purpose is hereby granted + without fee, provided that the above copyright notice appear in + all copies and that both that the copyright notice and this + permission notice and warranty disclaimer appear in supporting + documentation, and that the name of the author not be used in + advertising or publicity pertaining to distribution of the + software without specific, written prior permission. + + 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, 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. +*/ + +/** \file + * + * USB Device Descriptors, for library use when in USB device mode. Descriptors are special + * computer-readable structures which the host requests upon device enumeration, to determine + * the device's capabilities and functions. + */ + +#include "Descriptors.h" + +/** Device descriptor structure. This descriptor, located in FLASH memory, describes the overall + * device characteristics, including the supported USB version, control endpoint size and the + * number of device configurations. The descriptor is read out by the USB host when the enumeration + * process begins. + */ +const USB_Descriptor_Device_t PROGMEM DeviceDescriptor = { + .Header = { .Size = sizeof(USB_Descriptor_Device_t), .Type = DTYPE_Device }, + + .USBSpecification = VERSION_BCD(1, 1, 0), + .Class = CDC_CSCP_CDCClass, + .SubClass = CDC_CSCP_NoSpecificSubclass, + .Protocol = CDC_CSCP_NoSpecificProtocol, + + .Endpoint0Size = FIXED_CONTROL_ENDPOINT_SIZE, + + .VendorID = 0x2C99, + .ProductID = 0x0004, + .ReleaseNumber = VERSION_BCD(0, 0, 1), + + .ManufacturerStrIndex = STRING_ID_Manufacturer, + .ProductStrIndex = STRING_ID_Product, + .SerialNumStrIndex = USE_INTERNAL_SERIAL, + + .NumberOfConfigurations = FIXED_NUM_CONFIGURATIONS +}; + +/** Configuration descriptor structure. This descriptor, located in FLASH memory, describes the usage + * of the device in one of its supported configurations, including information about any device interfaces + * and endpoints. The descriptor is read out by the USB host during the enumeration process when selecting + * a configuration so that the host may correctly communicate with the USB device. + */ +const USB_Descriptor_Configuration_t PROGMEM ConfigurationDescriptor = { + .Config = { + .Header = { .Size = sizeof(USB_Descriptor_Configuration_Header_t), .Type = DTYPE_Configuration }, + + .TotalConfigurationSize = sizeof(USB_Descriptor_Configuration_t), + .TotalInterfaces = 2, + + .ConfigurationNumber = 1, + .ConfigurationStrIndex = NO_DESCRIPTOR, + + .ConfigAttributes = (USB_CONFIG_ATTR_RESERVED | USB_CONFIG_ATTR_SELFPOWERED), + + .MaxPowerConsumption = USB_CONFIG_POWER_MA(100) }, + + .CDC_CCI_Interface = { .Header = { .Size = sizeof(USB_Descriptor_Interface_t), .Type = DTYPE_Interface }, + + .InterfaceNumber = INTERFACE_ID_CDC_CCI, + .AlternateSetting = 0, + + .TotalEndpoints = 1, + + .Class = CDC_CSCP_CDCClass, + .SubClass = CDC_CSCP_ACMSubclass, + .Protocol = CDC_CSCP_ATCommandProtocol, + + .InterfaceStrIndex = NO_DESCRIPTOR }, + + .CDC_Functional_Header = { + .Header = { .Size = sizeof(USB_CDC_Descriptor_FunctionalHeader_t), .Type = CDC_DTYPE_CSInterface }, + .Subtype = CDC_DSUBTYPE_CSInterface_Header, + + .CDCSpecification = VERSION_BCD(1, 1, 0), + }, + + .CDC_Functional_ACM = { + .Header = { .Size = sizeof(USB_CDC_Descriptor_FunctionalACM_t), .Type = CDC_DTYPE_CSInterface }, + .Subtype = CDC_DSUBTYPE_CSInterface_ACM, + + .Capabilities = 0x06, + }, + + .CDC_Functional_Union = { + .Header = { .Size = sizeof(USB_CDC_Descriptor_FunctionalUnion_t), .Type = CDC_DTYPE_CSInterface }, + .Subtype = CDC_DSUBTYPE_CSInterface_Union, + + .MasterInterfaceNumber = INTERFACE_ID_CDC_CCI, + .SlaveInterfaceNumber = INTERFACE_ID_CDC_DCI, + }, + + .CDC_NotificationEndpoint = { .Header = { .Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint }, + + .EndpointAddress = CDC_NOTIFICATION_EPADDR, + .Attributes = (EP_TYPE_INTERRUPT | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA), + .EndpointSize = CDC_NOTIFICATION_EPSIZE, + .PollingIntervalMS = 0xFF }, + + .CDC_DCI_Interface = { .Header = { .Size = sizeof(USB_Descriptor_Interface_t), .Type = DTYPE_Interface }, + + .InterfaceNumber = INTERFACE_ID_CDC_DCI, + .AlternateSetting = 0, + + .TotalEndpoints = 2, + + .Class = CDC_CSCP_CDCDataClass, + .SubClass = CDC_CSCP_NoDataSubclass, + .Protocol = CDC_CSCP_NoDataProtocol, + + .InterfaceStrIndex = NO_DESCRIPTOR }, + + .CDC_DataOutEndpoint = { .Header = { .Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint }, + + .EndpointAddress = CDC_RX_EPADDR, + .Attributes = (EP_TYPE_BULK | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA), + .EndpointSize = CDC_TXRX_EPSIZE, + .PollingIntervalMS = 0x05 }, + + .CDC_DataInEndpoint = { .Header = { .Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint }, + + .EndpointAddress = CDC_TX_EPADDR, + .Attributes = (EP_TYPE_BULK | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA), + .EndpointSize = CDC_TXRX_EPSIZE, + .PollingIntervalMS = 0x05 } +}; + +/** Language descriptor structure. This descriptor, located in FLASH memory, is returned when the host requests + * the string descriptor with index 0 (the first index). It is actually an array of 16-bit integers, which indicate + * via the language ID table available at USB.org what languages the device supports for its string descriptors. + */ +const USB_Descriptor_String_t PROGMEM LanguageString = USB_STRING_DESCRIPTOR_ARRAY(LANGUAGE_ID_ENG); + +/** Manufacturer descriptor string. This is a Unicode string containing the manufacturer's details in human readable + * form, and is read out upon request by the host when the appropriate string ID is requested, listed in the Device + * Descriptor. + */ +const USB_Descriptor_String_t PROGMEM ManufacturerString = USB_STRING_DESCRIPTOR(L"Prusa3D"); + +/** Product descriptor string. This is a Unicode string containing the product's details in human readable form, + * and is read out upon request by the host when the appropriate string ID is requested, listed in the Device + * Descriptor. + */ +const USB_Descriptor_String_t PROGMEM ProductString = USB_STRING_DESCRIPTOR(L"Original Prusa i3 MK3 Multi Material 2.0 upgrade 🐑"); + +/** This function is called by the library when in device mode, and must be overridden (see library "USB Descriptors" + * documentation) by the application code so that the address and size of a requested descriptor can be given + * to the USB library. When the device receives a Get Descriptor request on the control endpoint, this function + * is called so that the descriptor details can be passed back and the appropriate descriptor sent back to the + * USB host. + */ +uint16_t CALLBACK_USB_GetDescriptor(const uint16_t wValue, + const uint16_t wIndex, + const void **const DescriptorAddress) { + const uint8_t DescriptorType = (wValue >> 8); + const uint8_t DescriptorNumber = (wValue & 0xFF); + + const void *Address = NULL; + uint16_t Size = NO_DESCRIPTOR; + + switch (DescriptorType) { + case DTYPE_Device: + Address = &DeviceDescriptor; + Size = sizeof(USB_Descriptor_Device_t); + break; + case DTYPE_Configuration: + Address = &ConfigurationDescriptor; + Size = sizeof(USB_Descriptor_Configuration_t); + break; + case DTYPE_String: + switch (DescriptorNumber) { + case STRING_ID_Language: + Address = &LanguageString; + Size = pgm_read_byte(&LanguageString.Header.Size); + break; + case STRING_ID_Manufacturer: + Address = &ManufacturerString; + Size = pgm_read_byte(&ManufacturerString.Header.Size); + break; + case STRING_ID_Product: + Address = &ProductString; + Size = pgm_read_byte(&ProductString.Header.Size); + break; + } + + break; + } + + *DescriptorAddress = Address; + return Size; +} diff --git a/lib/Descriptors.h b/lib/Descriptors.h new file mode 100644 index 0000000..bbf506f --- /dev/null +++ b/lib/Descriptors.h @@ -0,0 +1,107 @@ +/* + LUFA Library + Copyright (C) Dean Camera, 2021. + + dean [at] fourwalledcubicle [dot] com + www.lufa-lib.org +*/ + +/* + Copyright 2021 Dean Camera (dean [at] fourwalledcubicle [dot] com) + + Permission to use, copy, modify, distribute, and sell this + software and its documentation for any purpose is hereby granted + without fee, provided that the above copyright notice appear in + all copies and that both that the copyright notice and this + permission notice and warranty disclaimer appear in supporting + documentation, and that the name of the author not be used in + advertising or publicity pertaining to distribution of the + software without specific, written prior permission. + + 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, 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. +*/ + +/** \file + * + * Header file for Descriptors.c. + */ + +#ifndef _DESCRIPTORS_H_ +#define _DESCRIPTORS_H_ + +/* Includes: */ +#include + +#include "lufa/LUFA/Drivers/USB/USB.h" + +/* Macros: */ +/** Endpoint address of the CDC device-to-host notification IN endpoint. */ +#define CDC_NOTIFICATION_EPADDR (ENDPOINT_DIR_IN | 2) + +/** Endpoint address of the CDC device-to-host data IN endpoint. */ +#define CDC_TX_EPADDR (ENDPOINT_DIR_IN | 3) + +/** Endpoint address of the CDC host-to-device data OUT endpoint. */ +#define CDC_RX_EPADDR (ENDPOINT_DIR_OUT | 4) + +/** Size in bytes of the CDC device-to-host notification IN endpoint. */ +#define CDC_NOTIFICATION_EPSIZE 8 + +/** Size in bytes of the CDC data IN and OUT endpoints. */ +#define CDC_TXRX_EPSIZE 16 + +/* Type Defines: */ +/** Type define for the device configuration descriptor structure. This must be defined in the + * application code, as the configuration descriptor contains several sub-descriptors which + * vary between devices, and which describe the device's usage to the host. + */ +typedef struct +{ + USB_Descriptor_Configuration_Header_t Config; + + // CDC Control Interface + USB_Descriptor_Interface_t CDC_CCI_Interface; + USB_CDC_Descriptor_FunctionalHeader_t CDC_Functional_Header; + USB_CDC_Descriptor_FunctionalACM_t CDC_Functional_ACM; + USB_CDC_Descriptor_FunctionalUnion_t CDC_Functional_Union; + USB_Descriptor_Endpoint_t CDC_NotificationEndpoint; + + // CDC Data Interface + USB_Descriptor_Interface_t CDC_DCI_Interface; + USB_Descriptor_Endpoint_t CDC_DataOutEndpoint; + USB_Descriptor_Endpoint_t CDC_DataInEndpoint; +} USB_Descriptor_Configuration_t; + +/** Enum for the device interface descriptor IDs within the device. Each interface descriptor + * should have a unique ID index associated with it, which can be used to refer to the + * interface from other descriptors. + */ +enum InterfaceDescriptors_t { + INTERFACE_ID_CDC_CCI = 0, /**< CDC CCI interface descriptor ID */ + INTERFACE_ID_CDC_DCI = 1, /**< CDC DCI interface descriptor ID */ +}; + +/** Enum for the device string descriptor IDs within the device. Each string descriptor should + * have a unique ID index associated with it, which can be used to refer to the string from + * other descriptors. + */ +enum StringDescriptors_t { + STRING_ID_Language = 0, /**< Supported Languages string descriptor ID (must be zero) */ + STRING_ID_Manufacturer = 1, /**< Manufacturer string ID */ + STRING_ID_Product = 2, /**< Product string ID */ +}; + +/* Function Prototypes: */ +uint16_t CALLBACK_USB_GetDescriptor(const uint16_t wValue, + const uint16_t wIndex, + const void **const DescriptorAddress) + ATTR_WARN_UNUSED_RESULT ATTR_NON_NULL_PTR_ARG(3); + +#endif diff --git a/lib/lufa_config.h b/lib/lufa_config.h new file mode 100644 index 0000000..2ae4f65 --- /dev/null +++ b/lib/lufa_config.h @@ -0,0 +1,17 @@ +#pragma once + +#define USB_DEVICE_ONLY +#define DEVICE_STATE_AS_GPIOR 0 +// #define ORDERED_EP_CONFIG +#define FIXED_CONTROL_ENDPOINT_SIZE 8 +#define FIXED_NUM_CONFIGURATIONS 1 +#define INTERRUPT_CONTROL_ENDPOINT +#define USE_FLASH_DESCRIPTORS +#define USE_STATIC_OPTIONS (USB_DEVICE_OPT_FULLSPEED | USB_OPT_REG_ENABLED | USB_OPT_AUTO_PLL) +#define NO_INTERNAL_SERIAL +#define NO_DEVICE_SELF_POWER +#define NO_DEVICE_REMOTE_WAKEUP +// #define NO_SOF_EVENTS +#define F_USB F_CPU +#define DEVICE_VID 0x2C99 +#define DEVICE_PID 0x0004 diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 9fb39e8..e8bf73c 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1,18 +1,17 @@ -target_sources( - firmware - PRIVATE main.cpp -) +target_sources(firmware PRIVATE main.cpp) + +target_link_libraries(firmware LUFA) set_property( SOURCE src/version.c APPEND PROPERTY COMPILE_DEFINITIONS - FW_BUILD_NUMBER=${BUILD_NUMBER} - FW_VERSION_FULL=${PROJECT_VERSION_FULL} - FW_VERSION=${PROJECT_VERSION} - FW_VERSION_SUFFIX=${PROJECT_VERSION_SUFFIX} - FW_VERSION_SUFFIX_SHORT=${PROJECT_VERSION_SUFFIX_SHORT} -) + FW_BUILD_NUMBER=${BUILD_NUMBER} + FW_VERSION_FULL=${PROJECT_VERSION_FULL} + FW_VERSION=${PROJECT_VERSION} + FW_VERSION_SUFFIX=${PROJECT_VERSION_SUFFIX} + FW_VERSION_SUFFIX_SHORT=${PROJECT_VERSION_SUFFIX_SHORT} + ) add_subdirectory(hal) add_subdirectory(logic) diff --git a/src/hal/adc.h b/src/hal/adc.h index bacbbfa..5ea8040 100644 --- a/src/hal/adc.h +++ b/src/hal/adc.h @@ -12,3 +12,5 @@ uint16_t ReadADC(uint8_t channel); } // namespace adc } // namespace hal + +namespace ha = hal::adc; diff --git a/src/hal/avr/cpu.cpp b/src/hal/avr/cpu.cpp index 7bef056..db9d93f 100644 --- a/src/hal/avr/cpu.cpp +++ b/src/hal/avr/cpu.cpp @@ -2,9 +2,17 @@ #include #include "../watchdog.h" +#include "lufa_config.h" +#include "Descriptors.h" +#include "lufa/LUFA/Drivers/USB/USB.h" + +#include "../usart.h" + namespace hal { namespace cpu { +bool resetPending = false; + void Init() { } @@ -15,5 +23,14 @@ void Reset() { ; //endless loop while waiting for the watchdog to reset } +void Step() { + if (resetPending) { + hal::usart::usart1.puts("resetPending\n"); + USB_Detach(); + for (;;) + ; //endless loop while waiting for the watchdog to reset + } +} + } // namespace CPU } // namespace hal diff --git a/src/hal/circular_buffer.h b/src/hal/circular_buffer.h index 4330e15..8f99003 100644 --- a/src/hal/circular_buffer.h +++ b/src/hal/circular_buffer.h @@ -1,6 +1,6 @@ #pragma once #include -#include "../limits.h" +#include "../intlimits.h" /// A generic circular index class which can be used to build circular buffers /// Can hold up to size elements diff --git a/src/hal/cpu.h b/src/hal/cpu.h index ace6a9e..bdf0472 100644 --- a/src/hal/cpu.h +++ b/src/hal/cpu.h @@ -10,9 +10,12 @@ namespace cpu { #define F_CPU (16000000ul) #endif +extern bool resetPending; + /// CPU init routines (not really necessary for the AVR) void Init(); void Reset(); +void Step(); } // namespace cpu } // namespace hal diff --git a/src/hal/watchdog.h b/src/hal/watchdog.h index a560c14..8fe8f83 100644 --- a/src/hal/watchdog.h +++ b/src/hal/watchdog.h @@ -37,8 +37,12 @@ public: uint8_t prescalerBits = 0; uint32_t ticks = 1; switch (timeout) { + case 250: + prescalerBits = 4; + break; case 8000: prescalerBits = 9; + break; } configuration config = { prescalerBits, static_cast(ticks - 1) }; @@ -53,3 +57,5 @@ void Reset(); } // namespace watchdog } // namespace hal + +namespace hwd = hal::watchdog; diff --git a/src/limits.h b/src/intlimits.h similarity index 100% rename from src/limits.h rename to src/intlimits.h diff --git a/src/main.cpp b/src/main.cpp index a1eb58a..8d56c66 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -21,6 +21,7 @@ #include "modules/user_input.h" #include "modules/timebase.h" #include "modules/motion.h" +#include "modules/usb_cdc.h" #include "logic/command_base.h" #include "logic/cut_filament.h" @@ -32,7 +33,6 @@ #include "logic/unload_filament.h" #include "version.h" - #include "panic.h" /// Global instance of the protocol codec @@ -91,24 +91,20 @@ void TmpPlayground() { /// Called before entering the loop() function /// Green LEDs signalize the progress of initialization. If anything goes wrong we shall turn on a red LED void setup() { - using namespace hal; - - cpu::Init(); + hal::cpu::Init(); mt::timebase.Init(); - watchdog::Enable(watchdog::configuration::compute(8000)); //set 8s timeout + // watchdog init + hwd::Enable(hwd::configuration::compute(8000)); //set 8s timeout mg::globals.Init(); - // watchdog init - - shr16::shr16.Init(); + hal::shr16::shr16.Init(); ml::leds.SetMode(4, ml::green, ml::on); ml::leds.Step(); - // @@TODO if the shift register doesn't work we really can't signalize anything, only internal variables will be accessible if the UART works - + // if the shift register doesn't work we really can't signalize anything, only internal variables will be accessible if the UART works hu::USART::USART_InitTypeDef usart_conf = { .rx_pin = USART_RX, .tx_pin = USART_TX, @@ -120,7 +116,7 @@ void setup() { // @@TODO if both shift register and the UART are dead, we are sitting ducks :( - spi::SPI_InitTypeDef spi_conf = { + hal::spi::SPI_InitTypeDef spi_conf = { .miso_pin = TMC2130_SPI_MISO_PIN, .mosi_pin = TMC2130_SPI_MOSI_PIN, .sck_pin = TMC2130_SPI_SCK_PIN, @@ -129,7 +125,7 @@ void setup() { .cpha = 1, .cpol = 1, }; - spi::Init(SPI0, &spi_conf); + hal::spi::Init(SPI0, &spi_conf); ml::leds.SetMode(2, ml::green, ml::on); ml::leds.Step(); @@ -137,10 +133,14 @@ void setup() { ml::leds.SetMode(1, ml::green, ml::on); ml::leds.Step(); - adc::Init(); + ha::Init(); ml::leds.SetMode(0, ml::green, ml::on); ml::leds.Step(); + mu::cdc.Init(); + + _delay_ms(100); + /// Turn off all leds for (uint8_t i = 0; i < config::toolCount; i++) { ml::leds.SetMode(i, ml::green, ml::off); @@ -367,6 +367,8 @@ void loop() { ms::selector.Step(); mui::userInput.Step(); currentCommand->Step(); + hal::cpu::Step(); + mu::cdc.Step(); hal::watchdog::Reset(); } diff --git a/src/modules/CMakeLists.txt b/src/modules/CMakeLists.txt index 139f1e0..47ff979 100644 --- a/src/modules/CMakeLists.txt +++ b/src/modules/CMakeLists.txt @@ -11,9 +11,10 @@ target_sources( motion.cpp movable_base.cpp permanent_storage.cpp + pulse_gen.cpp selector.cpp speed_table.cpp timebase.cpp + usb_cdc.cpp user_input.cpp - pulse_gen.cpp ) diff --git a/src/modules/usb_cdc.cpp b/src/modules/usb_cdc.cpp new file mode 100644 index 0000000..913ae66 --- /dev/null +++ b/src/modules/usb_cdc.cpp @@ -0,0 +1,117 @@ +#include "usb_cdc.h" +#include "../hal/cpu.h" +#include "../hal/usart.h" +#include "../hal/watchdog.h" + +extern "C" { +#include "lufa_config.h" +#include "Descriptors.h" +#include "lufa/LUFA/Drivers/USB/USB.h" + +/** LUFA CDC Class driver interface configuration and state information. This structure is + * passed to all CDC Class driver functions, so that multiple instances of the same class + * within a device can be differentiated from one another. + */ +USB_ClassInfo_CDC_Device_t VirtualSerial_CDC_Interface = { + .Config = { + .ControlInterfaceNumber = INTERFACE_ID_CDC_CCI, + .DataINEndpoint = { + .Address = CDC_TX_EPADDR, + .Size = CDC_TXRX_EPSIZE, + .Type = EP_TYPE_BULK, + .Banks = 1, + }, + .DataOUTEndpoint = { + .Address = CDC_RX_EPADDR, + .Size = CDC_TXRX_EPSIZE, + .Type = EP_TYPE_BULK, + .Banks = 1, + }, + .NotificationEndpoint = { + .Address = CDC_NOTIFICATION_EPADDR, + .Size = CDC_NOTIFICATION_EPSIZE, + .Type = EP_TYPE_INTERRUPT, + .Banks = 1, + }, + }, +}; + +/** Event handler for the library USB Connection event. */ +void EVENT_USB_Device_Connect(void) { + hal::usart::usart1.puts("EVENT_USB_Device_Connect\n"); +} + +/** Event handler for the library USB Disconnection event. */ +void EVENT_USB_Device_Disconnect(void) { + hal::usart::usart1.puts("EVENT_USB_Device_Disconnect\n"); +} + +/** Event handler for the library USB Configuration Changed event. */ +void EVENT_USB_Device_ConfigurationChanged(void) { + bool ConfigSuccess = true; + + ConfigSuccess &= CDC_Device_ConfigureEndpoints(&VirtualSerial_CDC_Interface); + + // LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY : LEDMASK_USB_ERROR); + // char str1[] = "ready\n"; + // char str0[] = "error\n"; + // hal::usart::usart1.puts("EVENT_USB_Device_ConfigurationChanged:"); + // hal::usart::usart1.puts(ConfigSuccess ? str1 : str0); +} + +/** Event handler for the library USB Control Request reception event. */ +void EVENT_USB_Device_ControlRequest(void) { + // hal::usart::usart1.puts("EVENT_USB_Device_ControlRequest\n"); + CDC_Device_ProcessControlRequest(&VirtualSerial_CDC_Interface); +} + +/** CDC class driver callback function the processing of changes to the virtual + * control lines sent from the host.. + * + * \param[in] CDCInterfaceInfo Pointer to the CDC class interface configuration structure being referenced + */ +void EVENT_CDC_Device_ControLineStateChanged(USB_ClassInfo_CDC_Device_t *const CDCInterfaceInfo) { + // Printing to serial from here will make Windows commit suicide when opening the port + + // hal::usart::usart1.puts("EVENT_CDC_Device_ControLineStateChanged "); + // bool HostReady = (CDCInterfaceInfo->State.ControlLineStates.HostToDevice & CDC_CONTROL_LINE_OUT_DTR) != 0; + // char str[50]; + // sprintf_P(str, PSTR("DTR:%hu\n"), HostReady); + // hal::usart::usart1.puts(str); +} + +void EVENT_CDC_Device_LineEncodingChanged(USB_ClassInfo_CDC_Device_t *const CDCInterfaceInfo) { + // Printing to serial from here will make Windows commit suicide when opening the port + + // hal::usart::usart1.puts("EVENT_CDC_Device_LineEncodingChanged "); + // char str[50]; + // sprintf_P(str, PSTR("baud:%lu\n"), CDCInterfaceInfo->State.LineEncoding.BaudRateBPS); + // hal::usart::usart1.puts(str); + + if (CDCInterfaceInfo->State.LineEncoding.BaudRateBPS == 1200) { + // *(uint16_t *)0x0800U = 0x7777; //old bootloader? + *(uint16_t *)(RAMEND - 1) = 0x7777; + hal::cpu::resetPending = true; + hal::watchdog::Enable(hal::watchdog::configuration::compute(250)); + } +} +} + +namespace modules { +namespace usb { + +CDC cdc; + +void CDC::Init() { + USB_Init(); +} + +void CDC::Step() { + CDC_Device_ReceiveByte(&VirtualSerial_CDC_Interface); + CDC_Device_USBTask(&VirtualSerial_CDC_Interface); + USB_USBTask(); +} + +} // namespace usb + +} // namespace modules diff --git a/src/modules/usb_cdc.h b/src/modules/usb_cdc.h new file mode 100644 index 0000000..9ffe938 --- /dev/null +++ b/src/modules/usb_cdc.h @@ -0,0 +1,26 @@ +#pragma once +#include + +namespace modules { + +/// The usb namespace provides all necessary facilities related to the USB interface. +namespace usb { + +class CDC { +public: + constexpr inline CDC() = default; + + /// Calls USB_Init from the LUFA library + void Init(); + + /// Calls USB_USBTask from the LUFA library - basically takes care about the runtime of USB CDC operation + void Step(); +}; + +/// The one and only instance of USB CDC in the FW +extern CDC cdc; + +} // namespace usb +} // namespace modules + +namespace mu = modules::usb;