diff --git a/.travis.yml b/.travis.yml index 5dd08769..99852c97 100644 --- a/.travis.yml +++ b/.travis.yml @@ -48,7 +48,7 @@ env: # Various protocol combinations - CONFIG_BOARD_VERSION=v3.4-24V CONFIG_USB_PROTOCOL=native-stream CONFIG_UART_PROTOCOL=native - - CONFIG_BOARD_VERSION=v3.4-24V CONFIG_USB_PROTOCOL=stdout CONFIG_UART_PROTOCOL=ascii + - CONFIG_BOARD_VERSION=v3.4-24V CONFIG_USB_PROTOCOL=stdout CONFIG_UART_PROTOCOL=stdout - CONFIG_BOARD_VERSION=v3.4-24V CONFIG_USB_PROTOCOL=none CONFIG_UART_PROTOCOL=none script: diff --git a/Firmware/Board/v3/Inc/usbd_cdc_if.h b/Firmware/Board/v3/Inc/usbd_cdc_if.h index c15e8b91..ed1d6705 100644 --- a/Firmware/Board/v3/Inc/usbd_cdc_if.h +++ b/Firmware/Board/v3/Inc/usbd_cdc_if.h @@ -132,7 +132,7 @@ extern USBD_CDC_ItfTypeDef USBD_Interface_fops_FS; * @{ */ -uint8_t CDC_Transmit_FS(uint8_t* Buf, uint16_t Len); +uint8_t CDC_Transmit_FS(uint8_t* Buf, uint16_t Len, uint8_t endpoint_pair); /* USER CODE BEGIN EXPORTED_FUNCTIONS */ /* USER CODE END EXPORTED_FUNCTIONS */ diff --git a/Firmware/Board/v3/Inc/usbd_conf.h b/Firmware/Board/v3/Inc/usbd_conf.h index bf276186..fe7867dd 100644 --- a/Firmware/Board/v3/Inc/usbd_conf.h +++ b/Firmware/Board/v3/Inc/usbd_conf.h @@ -89,6 +89,7 @@ * @brief Defines for configuration of the Usb device. * @{ */ +#define MS_VendorCode 'P' /*---------- -----------*/ #define USBD_MAX_NUM_INTERFACES 1 @@ -97,7 +98,7 @@ /*---------- -----------*/ #define USBD_MAX_STR_DESC_SIZ 512 /*---------- -----------*/ -#define USBD_SUPPORT_USER_STRING 0 +#define USBD_SUPPORT_USER_STRING 1 /*---------- -----------*/ #define USBD_DEBUG_LEVEL 0 /*---------- -----------*/ diff --git a/Firmware/Board/v3/Inc/usbd_desc.h b/Firmware/Board/v3/Inc/usbd_desc.h index d791d3d4..2a74de31 100644 --- a/Firmware/Board/v3/Inc/usbd_desc.h +++ b/Firmware/Board/v3/Inc/usbd_desc.h @@ -133,6 +133,8 @@ extern USBD_DescriptorsTypeDef FS_Desc; /* USER CODE BEGIN EXPORTED_FUNCTIONS */ +uint8_t * USBD_UsrStrDescriptor(struct _USBD_HandleTypeDef *pdev, uint8_t index, uint16_t *length); + /* USER CODE END EXPORTED_FUNCTIONS */ /** diff --git a/Firmware/Board/v3/Middlewares/ST/STM32_USB_Device_Library/Class/CDC/Inc/usbd_cdc.h b/Firmware/Board/v3/Middlewares/ST/STM32_USB_Device_Library/Class/CDC/Inc/usbd_cdc.h index d937b2e8..3bb73c6e 100644 --- a/Firmware/Board/v3/Middlewares/ST/STM32_USB_Device_Library/Class/CDC/Inc/usbd_cdc.h +++ b/Firmware/Board/v3/Middlewares/ST/STM32_USB_Device_Library/Class/CDC/Inc/usbd_cdc.h @@ -52,13 +52,15 @@ #define CDC_IN_EP 0x81 /* EP1 for data IN */ #define CDC_OUT_EP 0x01 /* EP1 for data OUT */ #define CDC_CMD_EP 0x82 /* EP2 for CDC commands */ +#define ODRIVE_IN_EP 0x83 /* EP3 IN: ODrive device TX endpoint */ +#define ODRIVE_OUT_EP 0x03 /* EP3 OUT: ODrive device RX endpoint */ /* CDC Endpoints parameters: you can fine tune these values depending on the needed baudrates and performance. */ -#define CDC_DATA_HS_MAX_PACKET_SIZE 512 /* Endpoint IN & OUT Packet size */ +#define CDC_DATA_HS_MAX_PACKET_SIZE 64 /* Endpoint IN & OUT Packet size */ #define CDC_DATA_FS_MAX_PACKET_SIZE 64 /* Endpoint IN & OUT Packet size */ #define CDC_CMD_PACKET_SIZE 8 /* Control Endpoint Packet size */ -#define USB_CDC_CONFIG_DESC_SIZ 67 +#define USB_CDC_CONFIG_DESC_SIZ (67 + 39) #define CDC_DATA_HS_IN_PACKET_SIZE CDC_DATA_HS_MAX_PACKET_SIZE #define CDC_DATA_HS_OUT_PACKET_SIZE CDC_DATA_HS_MAX_PACKET_SIZE @@ -103,7 +105,7 @@ typedef struct _USBD_CDC_Itf int8_t (* Init) (void); int8_t (* DeInit) (void); int8_t (* Control) (uint8_t, uint8_t * , uint16_t); - int8_t (* Receive) (uint8_t *, uint32_t *); + int8_t (* Receive) (uint8_t *, uint32_t *, uint8_t); }USBD_CDC_ItfTypeDef; @@ -156,9 +158,9 @@ uint8_t USBD_CDC_SetTxBuffer (USBD_HandleTypeDef *pdev, uint8_t USBD_CDC_SetRxBuffer (USBD_HandleTypeDef *pdev, uint8_t *pbuff); -uint8_t USBD_CDC_ReceivePacket (USBD_HandleTypeDef *pdev); +uint8_t USBD_CDC_ReceivePacket (USBD_HandleTypeDef *pdev, uint8_t endpoint_pair); -uint8_t USBD_CDC_TransmitPacket (USBD_HandleTypeDef *pdev); +uint8_t USBD_CDC_TransmitPacket (USBD_HandleTypeDef *pdev, uint8_t endpoint_pair); /** * @} */ diff --git a/Firmware/Board/v3/Middlewares/ST/STM32_USB_Device_Library/Class/CDC/Src/usbd_cdc.c b/Firmware/Board/v3/Middlewares/ST/STM32_USB_Device_Library/Class/CDC/Src/usbd_cdc.c index 24465641..2bc01513 100644 --- a/Firmware/Board/v3/Middlewares/ST/STM32_USB_Device_Library/Class/CDC/Src/usbd_cdc.c +++ b/Firmware/Board/v3/Middlewares/ST/STM32_USB_Device_Library/Class/CDC/Src/usbd_cdc.c @@ -132,6 +132,9 @@ static uint8_t *USBD_CDC_GetOtherSpeedCfgDesc (uint16_t *length); uint8_t *USBD_CDC_GetDeviceQualifierDescriptor (uint16_t *length); +static uint8_t USBD_WinUSBComm_SetupVendor(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req); +//static uint8_t * USBD_GetUsrStrDescriptor(struct _USBD_HandleTypeDef *pdev, uint8_t index, uint16_t *length); + /* USB Standard Device Descriptor */ __ALIGN_BEGIN static uint8_t USBD_CDC_DeviceQualifierDesc[USB_LEN_DEV_QUALIFIER_DESC] __ALIGN_END = { @@ -173,24 +176,37 @@ USBD_ClassTypeDef USBD_CDC = USBD_CDC_GetFSCfgDesc, USBD_CDC_GetOtherSpeedCfgDesc, USBD_CDC_GetDeviceQualifierDescriptor, + USBD_UsrStrDescriptor }; /* USB CDC device Configuration Descriptor */ -__ALIGN_BEGIN uint8_t USBD_CDC_CfgHSDesc[USB_CDC_CONFIG_DESC_SIZ] __ALIGN_END = +__ALIGN_BEGIN uint8_t USBD_CDC_CfgDesc[USB_CDC_CONFIG_DESC_SIZ] __ALIGN_END = { /*Configuration Descriptor*/ 0x09, /* bLength: Configuration Descriptor size */ USB_DESC_TYPE_CONFIGURATION, /* bDescriptorType: Configuration */ USB_CDC_CONFIG_DESC_SIZ, /* wTotalLength:no of returned bytes */ 0x00, - 0x02, /* bNumInterfaces: 2 interface */ + 0x03, /* bNumInterfaces: 3 interfaces (2 for CDC, 1 custom) */ 0x01, /* bConfigurationValue: Configuration value */ 0x00, /* iConfiguration: Index of string descriptor describing the configuration */ 0xC0, /* bmAttributes: self powered */ 0x32, /* MaxPower 0 mA */ + + /////////////////////////////////////////////////////////////////////////////// + + /* Interface Association Descriptor: CDC device (virtual com port) */ + 0x08, /* bLength: IAD size */ + 0x0B, /* bDescriptorType: Interface Association Descriptor */ + 0x00, /* bFirstInterface */ + 0x02, /* bInterfaceCount */ + 0x02, /* bFunctionClass: Communication Interface Class */ + 0x02, /* bFunctionSubClass: Abstract Control Model */ + 0x01, /* bFunctionProtocol: Common AT commands */ + 0x00, /* iFunction */ /*---------------------------------------------------------------------------*/ - + /*Interface Descriptor */ 0x09, /* bLength: Interface Descriptor size */ USB_DESC_TYPE_INTERFACE, /* bDescriptorType: Interface */ @@ -202,7 +218,7 @@ __ALIGN_BEGIN uint8_t USBD_CDC_CfgHSDesc[USB_CDC_CONFIG_DESC_SIZ] __ALIGN_END = 0x02, /* bInterfaceSubClass: Abstract Control Model */ 0x01, /* bInterfaceProtocol: Common AT commands */ 0x00, /* iInterface: */ - + /*Header Functional Descriptor*/ 0x05, /* bLength: Endpoint Descriptor size */ 0x24, /* bDescriptorType: CS_INTERFACE */ @@ -229,7 +245,7 @@ __ALIGN_BEGIN uint8_t USBD_CDC_CfgHSDesc[USB_CDC_CONFIG_DESC_SIZ] __ALIGN_END = 0x06, /* bDescriptorSubtype: Union func desc */ 0x00, /* bMasterInterface: Communication class interface */ 0x01, /* bSlaveInterface0: Data Class Interface */ - + /*Endpoint 2 Descriptor*/ 0x07, /* bLength: Endpoint Descriptor size */ USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: Endpoint */ @@ -267,196 +283,52 @@ __ALIGN_BEGIN uint8_t USBD_CDC_CfgHSDesc[USB_CDC_CONFIG_DESC_SIZ] __ALIGN_END = 0x02, /* bmAttributes: Bulk */ LOBYTE(CDC_DATA_HS_MAX_PACKET_SIZE), /* wMaxPacketSize: */ HIBYTE(CDC_DATA_HS_MAX_PACKET_SIZE), - 0x00 /* bInterval: ignore for Bulk transfer */ -} ; + 0x00, /* bInterval: ignore for Bulk transfer */ + /////////////////////////////////////////////////////////////////////////////// + + /* Interface Association Descriptor: custom device */ + 0x08, /* bLength: IAD size */ + 0x0B, /* bDescriptorType: Interface Association Descriptor */ + 0x02, /* bFirstInterface */ + 0x01, /* bInterfaceCount */ + 0x00, /* bFunctionClass: Communication Interface Class */ + 0x00, /* bFunctionSubClass: Abstract Control Model */ + 0x00, /* bFunctionProtocol: Common AT commands */ + 0x06, /* iFunction */ -/* USB CDC device Configuration Descriptor */ -__ALIGN_BEGIN uint8_t USBD_CDC_CfgFSDesc[USB_CDC_CONFIG_DESC_SIZ] __ALIGN_END = -{ - /*Configuration Descriptor*/ - 0x09, /* bLength: Configuration Descriptor size */ - USB_DESC_TYPE_CONFIGURATION, /* bDescriptorType: Configuration */ - USB_CDC_CONFIG_DESC_SIZ, /* wTotalLength:no of returned bytes */ - 0x00, - 0x02, /* bNumInterfaces: 2 interface */ - 0x01, /* bConfigurationValue: Configuration value */ - 0x00, /* iConfiguration: Index of string descriptor describing the configuration */ - 0xC0, /* bmAttributes: self powered */ - 0x32, /* MaxPower 0 mA */ - - /*---------------------------------------------------------------------------*/ - - /*Interface Descriptor */ - 0x09, /* bLength: Interface Descriptor size */ - USB_DESC_TYPE_INTERFACE, /* bDescriptorType: Interface */ - /* Interface descriptor type */ - 0x00, /* bInterfaceNumber: Number of Interface */ - 0x00, /* bAlternateSetting: Alternate setting */ - 0x01, /* bNumEndpoints: One endpoints used */ - 0x02, /* bInterfaceClass: Communication Interface Class */ - 0x02, /* bInterfaceSubClass: Abstract Control Model */ - 0x01, /* bInterfaceProtocol: Common AT commands */ - 0x00, /* iInterface: */ - - /*Header Functional Descriptor*/ - 0x05, /* bLength: Endpoint Descriptor size */ - 0x24, /* bDescriptorType: CS_INTERFACE */ - 0x00, /* bDescriptorSubtype: Header Func Desc */ - 0x10, /* bcdCDC: spec release number */ - 0x01, - - /*Call Management Functional Descriptor*/ - 0x05, /* bFunctionLength */ - 0x24, /* bDescriptorType: CS_INTERFACE */ - 0x01, /* bDescriptorSubtype: Call Management Func Desc */ - 0x00, /* bmCapabilities: D0+D1 */ - 0x01, /* bDataInterface: 1 */ - - /*ACM Functional Descriptor*/ - 0x04, /* bFunctionLength */ - 0x24, /* bDescriptorType: CS_INTERFACE */ - 0x02, /* bDescriptorSubtype: Abstract Control Management desc */ - 0x02, /* bmCapabilities */ - - /*Union Functional Descriptor*/ - 0x05, /* bFunctionLength */ - 0x24, /* bDescriptorType: CS_INTERFACE */ - 0x06, /* bDescriptorSubtype: Union func desc */ - 0x00, /* bMasterInterface: Communication class interface */ - 0x01, /* bSlaveInterface0: Data Class Interface */ - - /*Endpoint 2 Descriptor*/ - 0x07, /* bLength: Endpoint Descriptor size */ - USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: Endpoint */ - CDC_CMD_EP, /* bEndpointAddress */ - 0x03, /* bmAttributes: Interrupt */ - LOBYTE(CDC_CMD_PACKET_SIZE), /* wMaxPacketSize: */ - HIBYTE(CDC_CMD_PACKET_SIZE), - 0x10, /* bInterval: */ /*---------------------------------------------------------------------------*/ /*Data class interface descriptor*/ 0x09, /* bLength: Endpoint Descriptor size */ USB_DESC_TYPE_INTERFACE, /* bDescriptorType: */ - 0x01, /* bInterfaceNumber: Number of Interface */ + 0x02, /* bInterfaceNumber: Number of Interface */ 0x00, /* bAlternateSetting: Alternate setting */ 0x02, /* bNumEndpoints: Two endpoints used */ - 0x0A, /* bInterfaceClass: CDC */ - 0x00, /* bInterfaceSubClass: */ + 0x00, /* bInterfaceClass: vendor specific */ + 0x01, /* bInterfaceSubClass: ODrive Communication */ 0x00, /* bInterfaceProtocol: */ 0x00, /* iInterface: */ /*Endpoint OUT Descriptor*/ 0x07, /* bLength: Endpoint Descriptor size */ USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: Endpoint */ - CDC_OUT_EP, /* bEndpointAddress */ + ODRIVE_OUT_EP, /* bEndpointAddress */ 0x02, /* bmAttributes: Bulk */ - LOBYTE(CDC_DATA_FS_MAX_PACKET_SIZE), /* wMaxPacketSize: */ - HIBYTE(CDC_DATA_FS_MAX_PACKET_SIZE), + LOBYTE(CDC_DATA_HS_MAX_PACKET_SIZE), /* wMaxPacketSize: */ + HIBYTE(CDC_DATA_HS_MAX_PACKET_SIZE), 0x00, /* bInterval: ignore for Bulk transfer */ /*Endpoint IN Descriptor*/ 0x07, /* bLength: Endpoint Descriptor size */ USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: Endpoint */ - CDC_IN_EP, /* bEndpointAddress */ + ODRIVE_IN_EP, /* bEndpointAddress */ 0x02, /* bmAttributes: Bulk */ - LOBYTE(CDC_DATA_FS_MAX_PACKET_SIZE), /* wMaxPacketSize: */ - HIBYTE(CDC_DATA_FS_MAX_PACKET_SIZE), - 0x00 /* bInterval: ignore for Bulk transfer */ + LOBYTE(CDC_DATA_HS_MAX_PACKET_SIZE), /* wMaxPacketSize: */ + HIBYTE(CDC_DATA_HS_MAX_PACKET_SIZE), + 0x00, /* bInterval: ignore for Bulk transfer */ } ; -__ALIGN_BEGIN uint8_t USBD_CDC_OtherSpeedCfgDesc[USB_CDC_CONFIG_DESC_SIZ] __ALIGN_END = -{ - 0x09, /* bLength: Configuation Descriptor size */ - USB_DESC_TYPE_OTHER_SPEED_CONFIGURATION, - USB_CDC_CONFIG_DESC_SIZ, - 0x00, - 0x02, /* bNumInterfaces: 2 interfaces */ - 0x01, /* bConfigurationValue: */ - 0x04, /* iConfiguration: */ - 0xC0, /* bmAttributes: */ - 0x32, /* MaxPower 100 mA */ - - /*Interface Descriptor */ - 0x09, /* bLength: Interface Descriptor size */ - USB_DESC_TYPE_INTERFACE, /* bDescriptorType: Interface */ - /* Interface descriptor type */ - 0x00, /* bInterfaceNumber: Number of Interface */ - 0x00, /* bAlternateSetting: Alternate setting */ - 0x01, /* bNumEndpoints: One endpoints used */ - 0x02, /* bInterfaceClass: Communication Interface Class */ - 0x02, /* bInterfaceSubClass: Abstract Control Model */ - 0x01, /* bInterfaceProtocol: Common AT commands */ - 0x00, /* iInterface: */ - - /*Header Functional Descriptor*/ - 0x05, /* bLength: Endpoint Descriptor size */ - 0x24, /* bDescriptorType: CS_INTERFACE */ - 0x00, /* bDescriptorSubtype: Header Func Desc */ - 0x10, /* bcdCDC: spec release number */ - 0x01, - - /*Call Management Functional Descriptor*/ - 0x05, /* bFunctionLength */ - 0x24, /* bDescriptorType: CS_INTERFACE */ - 0x01, /* bDescriptorSubtype: Call Management Func Desc */ - 0x00, /* bmCapabilities: D0+D1 */ - 0x01, /* bDataInterface: 1 */ - - /*ACM Functional Descriptor*/ - 0x04, /* bFunctionLength */ - 0x24, /* bDescriptorType: CS_INTERFACE */ - 0x02, /* bDescriptorSubtype: Abstract Control Management desc */ - 0x02, /* bmCapabilities */ - - /*Union Functional Descriptor*/ - 0x05, /* bFunctionLength */ - 0x24, /* bDescriptorType: CS_INTERFACE */ - 0x06, /* bDescriptorSubtype: Union func desc */ - 0x00, /* bMasterInterface: Communication class interface */ - 0x01, /* bSlaveInterface0: Data Class Interface */ - - /*Endpoint 2 Descriptor*/ - 0x07, /* bLength: Endpoint Descriptor size */ - USB_DESC_TYPE_ENDPOINT , /* bDescriptorType: Endpoint */ - CDC_CMD_EP, /* bEndpointAddress */ - 0x03, /* bmAttributes: Interrupt */ - LOBYTE(CDC_CMD_PACKET_SIZE), /* wMaxPacketSize: */ - HIBYTE(CDC_CMD_PACKET_SIZE), - 0xFF, /* bInterval: */ - - /*---------------------------------------------------------------------------*/ - - /*Data class interface descriptor*/ - 0x09, /* bLength: Endpoint Descriptor size */ - USB_DESC_TYPE_INTERFACE, /* bDescriptorType: */ - 0x01, /* bInterfaceNumber: Number of Interface */ - 0x00, /* bAlternateSetting: Alternate setting */ - 0x02, /* bNumEndpoints: Two endpoints used */ - 0x0A, /* bInterfaceClass: CDC */ - 0x00, /* bInterfaceSubClass: */ - 0x00, /* bInterfaceProtocol: */ - 0x00, /* iInterface: */ - - /*Endpoint OUT Descriptor*/ - 0x07, /* bLength: Endpoint Descriptor size */ - USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: Endpoint */ - CDC_OUT_EP, /* bEndpointAddress */ - 0x02, /* bmAttributes: Bulk */ - 0x40, /* wMaxPacketSize: */ - 0x00, - 0x00, /* bInterval: ignore for Bulk transfer */ - - /*Endpoint IN Descriptor*/ - 0x07, /* bLength: Endpoint Descriptor size */ - USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: Endpoint */ - CDC_IN_EP, /* bEndpointAddress */ - 0x02, /* bmAttributes: Bulk */ - 0x40, /* wMaxPacketSize: */ - 0x00, - 0x00 /* bInterval */ -}; /** * @} @@ -508,6 +380,19 @@ static uint8_t USBD_CDC_Init (USBD_HandleTypeDef *pdev, USBD_EP_TYPE_BULK, CDC_DATA_FS_OUT_PACKET_SIZE); } + + /* Open ODrive IN endpoint */ + USBD_LL_OpenEP(pdev, + ODRIVE_IN_EP, + USBD_EP_TYPE_BULK, + pdev->dev_speed == USBD_SPEED_HIGH ? CDC_DATA_HS_IN_PACKET_SIZE : CDC_DATA_FS_IN_PACKET_SIZE); + + /* Open ODrive OUT endpoint */ + USBD_LL_OpenEP(pdev, + ODRIVE_OUT_EP, + USBD_EP_TYPE_BULK, + pdev->dev_speed == USBD_SPEED_HIGH ? CDC_DATA_HS_OUT_PACKET_SIZE : CDC_DATA_FS_OUT_PACKET_SIZE); + /* Open Command IN EP */ USBD_LL_OpenEP(pdev, CDC_CMD_EP, @@ -549,7 +434,11 @@ static uint8_t USBD_CDC_Init (USBD_HandleTypeDef *pdev, CDC_DATA_FS_OUT_PACKET_SIZE); } - + /* Prepare ODrive Out endpoint to receive next packet */ + USBD_LL_PrepareReceive(pdev, + ODRIVE_OUT_EP, + hcdc->RxBuffer, + CDC_DATA_FS_OUT_PACKET_SIZE); } return ret; } @@ -566,17 +455,25 @@ static uint8_t USBD_CDC_DeInit (USBD_HandleTypeDef *pdev, { uint8_t ret = 0; - /* Open EP IN */ + /* Close EP IN */ USBD_LL_CloseEP(pdev, CDC_IN_EP); - /* Open EP OUT */ + /* Close EP OUT */ USBD_LL_CloseEP(pdev, CDC_OUT_EP); - /* Open Command IN EP */ + /* Close Command IN EP */ USBD_LL_CloseEP(pdev, CDC_CMD_EP); + + /* Close EP IN */ + USBD_LL_CloseEP(pdev, + ODRIVE_IN_EP); + + /* Close EP OUT */ + USBD_LL_CloseEP(pdev, + ODRIVE_OUT_EP); /* DeInit physical Interface components */ @@ -648,6 +545,9 @@ static uint8_t USBD_CDC_Setup (USBD_HandleTypeDef *pdev, case USB_REQ_SET_INTERFACE : break; } + + case USB_REQ_TYPE_VENDOR: + return USBD_WinUSBComm_SetupVendor(pdev, req); default: break; @@ -697,7 +597,7 @@ static uint8_t USBD_CDC_DataOut (USBD_HandleTypeDef *pdev, uint8_t epnum) NAKed till the end of the application Xfer */ if(pdev->pClassData != NULL) { - ((USBD_CDC_ItfTypeDef *)pdev->pUserData)->Receive(hcdc->RxBuffer, &hcdc->RxLength); + ((USBD_CDC_ItfTypeDef *)pdev->pUserData)->Receive(hcdc->RxBuffer, &hcdc->RxLength, epnum); return USBD_OK; } @@ -740,8 +640,8 @@ static uint8_t USBD_CDC_EP0_RxReady (USBD_HandleTypeDef *pdev) */ static uint8_t *USBD_CDC_GetFSCfgDesc (uint16_t *length) { - *length = sizeof (USBD_CDC_CfgFSDesc); - return USBD_CDC_CfgFSDesc; + *length = sizeof (USBD_CDC_CfgDesc); + return USBD_CDC_CfgDesc; } /** @@ -753,8 +653,8 @@ static uint8_t *USBD_CDC_GetFSCfgDesc (uint16_t *length) */ static uint8_t *USBD_CDC_GetHSCfgDesc (uint16_t *length) { - *length = sizeof (USBD_CDC_CfgHSDesc); - return USBD_CDC_CfgHSDesc; + *length = sizeof (USBD_CDC_CfgDesc); + return USBD_CDC_CfgDesc; } /** @@ -766,8 +666,8 @@ static uint8_t *USBD_CDC_GetHSCfgDesc (uint16_t *length) */ static uint8_t *USBD_CDC_GetOtherSpeedCfgDesc (uint16_t *length) { - *length = sizeof (USBD_CDC_OtherSpeedCfgDesc); - return USBD_CDC_OtherSpeedCfgDesc; + *length = sizeof (USBD_CDC_CfgDesc); + return USBD_CDC_CfgDesc; } /** @@ -844,7 +744,7 @@ uint8_t USBD_CDC_SetRxBuffer (USBD_HandleTypeDef *pdev, * @param epnum: endpoint number * @retval status */ -uint8_t USBD_CDC_TransmitPacket(USBD_HandleTypeDef *pdev) +uint8_t USBD_CDC_TransmitPacket(USBD_HandleTypeDef *pdev, uint8_t endpoint_pair) { USBD_CDC_HandleTypeDef *hcdc = (USBD_CDC_HandleTypeDef*) pdev->pClassData; @@ -855,11 +755,19 @@ uint8_t USBD_CDC_TransmitPacket(USBD_HandleTypeDef *pdev) /* Tx Transfer in progress */ hcdc->TxState = 1; - /* Transmit next packet */ - USBD_LL_Transmit(pdev, - CDC_IN_EP, - hcdc->TxBuffer, - hcdc->TxLength); + //endpoint_pair = 1; + if (endpoint_pair == 1) { + /* Transmit next packet */ + USBD_LL_Transmit(pdev, + CDC_IN_EP, + hcdc->TxBuffer, + hcdc->TxLength); + } else if (endpoint_pair == 3) { + USBD_LL_Transmit(pdev, + ODRIVE_IN_EP, + hcdc->TxBuffer, + hcdc->TxLength); + } return USBD_OK; } @@ -881,29 +789,30 @@ uint8_t USBD_CDC_TransmitPacket(USBD_HandleTypeDef *pdev) * @param pdev: device instance * @retval status */ -uint8_t USBD_CDC_ReceivePacket(USBD_HandleTypeDef *pdev) +uint8_t USBD_CDC_ReceivePacket(USBD_HandleTypeDef *pdev, uint8_t endpoint_pair) { USBD_CDC_HandleTypeDef *hcdc = (USBD_CDC_HandleTypeDef*) pdev->pClassData; /* Suspend or Resume USB Out process */ if(pdev->pClassData != NULL) { - if(pdev->dev_speed == USBD_SPEED_HIGH ) + if (endpoint_pair == CDC_OUT_EP) { /* Prepare Out endpoint to receive next packet */ USBD_LL_PrepareReceive(pdev, CDC_OUT_EP, hcdc->RxBuffer, - CDC_DATA_HS_OUT_PACKET_SIZE); + pdev->dev_speed == USBD_SPEED_HIGH ? CDC_DATA_HS_OUT_PACKET_SIZE : CDC_DATA_FS_OUT_PACKET_SIZE); } - else + else if (endpoint_pair == ODRIVE_OUT_EP) { - /* Prepare Out endpoint to receive next packet */ + /* Prepare ODrive Out endpoint to receive next packet */ USBD_LL_PrepareReceive(pdev, - CDC_OUT_EP, + ODRIVE_OUT_EP, hcdc->RxBuffer, - CDC_DATA_FS_OUT_PACKET_SIZE); + pdev->dev_speed == USBD_SPEED_HIGH ? CDC_DATA_HS_OUT_PACKET_SIZE : CDC_DATA_FS_OUT_PACKET_SIZE); } + return USBD_OK; } else @@ -911,6 +820,184 @@ uint8_t USBD_CDC_ReceivePacket(USBD_HandleTypeDef *pdev) return USBD_FAIL; } } + + +/* WinUSB support ------------------------------------------------------------*/ +/* +* This section tells Windows that it should automatically load the WinUSB driver +* for the device (more specifically, interface 2 because it's a composite device). +* This allows for driverless communication with the device. +*/ + +#define NUM_INTERFACES 1 + +#if NUM_INTERFACES == 2 +#define USB_WINUSBCOMM_COMPAT_ID_OS_DESC_SIZ (16 + 24 + 24) +#else +#define USB_WINUSBCOMM_COMPAT_ID_OS_DESC_SIZ (16 + 24) +#endif + + +// This associates winusb driver with the device +__ALIGN_BEGIN uint8_t USBD_WinUSBComm_Extended_Compat_ID_OS_Desc[USB_WINUSBCOMM_COMPAT_ID_OS_DESC_SIZ] __ALIGN_END = +{ + // +-- Offset in descriptor + // | +-- Size + // v v + USB_WINUSBCOMM_COMPAT_ID_OS_DESC_SIZ, 0, 0, 0, // 0 dwLength 4 DWORD The length, in bytes, of the complete extended compat ID descriptor + 0x00, 0x01, // 4 bcdVersion 2 BCD The descriptor’s version number, in binary coded decimal (BCD) format + 0x04, 0x00, // 6 wIndex 2 WORD An index that identifies the particular OS feature descriptor + NUM_INTERFACES, // 8 bCount 1 BYTE The number of custom property sections + 0, 0, 0, 0, 0, 0, 0, // 9 RESERVED 7 BYTEs Reserved + // ===================== + // 16 + + // +-- Offset from function section start + // | +-- Size + // v v + 2, // 0 bFirstInterfaceNumber 1 BYTE The interface or function number + 0, // 1 RESERVED 1 BYTE Reserved + 0x57, 0x49, 0x4E, 0x55, 0x53, 0x42, 0x00, 0x00, // 2 compatibleID 8 BYTEs The function’s compatible ID ("WINUSB") + 0, 0, 0, 0, 0, 0, 0, 0, // 10 subCompatibleID 8 BYTEs The function’s subcompatible ID + 0, 0, 0, 0, 0, 0, // 18 RESERVED 6 BYTEs Reserved + // ================================= + // 24 +#if NUM_INTERFACES == 2 + // +-- Offset from function section start + // | +-- Size + // v v + 2, // 0 bFirstInterfaceNumber 1 BYTE The interface or function number + 0, // 1 RESERVED 1 BYTE Reserved + 0x57, 0x49, 0x4E, 0x55, 0x53, 0x42, 0x00, 0x00, // 2 compatibleID 8 BYTEs The function’s compatible ID ("WINUSB") + 0, 0, 0, 0, 0, 0, 0, 0, // 10 subCompatibleID 8 BYTEs The function’s subcompatible ID + 0, 0, 0, 0, 0, 0, // 18 RESERVED 6 BYTEs Reserved + // ================================= + // 24 +#endif +}; + + +// Properties are added to: +// HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\USB\VID_xxxx&PID_xxxx\sssssssss\Device Parameters +// Use USBDeview or similar to uninstall + +__ALIGN_BEGIN uint8_t USBD_WinUSBComm_Extended_Properties_OS_Desc[0xB6] __ALIGN_END = +{ + 0xB6, 0x00, 0x00, 0x00, // 0 dwLength 4 DWORD The length, in bytes, of the complete extended properties descriptor + 0x00, 0x01, // 4 bcdVersion 2 BCD The descriptor’s version number, in binary coded decimal (BCD) format + 0x05, 0x00, // 6 wIndex 2 WORD The index for extended properties OS descriptors + 0x02, 0x00, // 8 wCount 2 WORD The number of custom property sections that follow the header section + // ==================== + // 10 +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + 0x84, 0x00, 0x00, 0x00, // 0 dwSize 4 DWORD The size of this custom properties section + 0x01, 0x00, 0x00, 0x00, // 4 dwPropertyDataType 4 DWORD Property data format + 0x28, 0x00, // 8 wPropertyNameLength 2 DWORD Property name length + // ======================================== + // 10 + // 10 bPropertyName PNL WCHAR[] The property name + 'D',0, 'e',0, 'v',0, 'i',0, 'c',0, 'e',0, 'I',0, 'n',0, + 't',0, 'e',0, 'r',0, 'f',0, 'a',0, 'c',0, 'e',0, 'G',0, + 'U',0, 'I',0, 'D',0, 0,0, + // ======================================== + // 40 (0x28) + + 0x4E, 0x00, 0x00, 0x00, // 10 + PNL dwPropertyDataLength 4 DWORD Length of the buffer holding the property data + // ======================================== + // 4 + // 14 + PNL bPropertyData PDL Format-dependent Property data + '{',0, 'E',0, 'A',0, '0',0, 'B',0, 'D',0, '5',0, 'C',0, + '3',0, '-',0, '5',0, '0',0, 'F',0, '3',0, '-',0, '4',0, + '8',0, '8',0, '8',0, '-',0, '8',0, '4',0, 'B',0, '4',0, + '-',0, '7',0, '4',0, 'E',0, '5',0, '0',0, 'E',0, '1',0, + '6',0, '4',0, '9',0, 'D',0, 'B',0, '}',0, 0 ,0, + // ======================================== + // 78 (0x4E) +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + 0x3E, 0x00, 0x00, 0x00, // 0 dwSize 0x00000030 (62 bytes) + 0x01, 0x00, 0x00, 0x00, // 4 dwPropertyDataType 0x00000001 (Unicode string) + 0x0C, 0x00, // 8 wPropertyNameLength 0x000C (12 bytes) + // ======================================== + // 10 + 'L',0, 'a',0, 'b',0, 'e',0, 'l',0, 0,0, + // 10 bPropertyName “Label” + // ======================================== + // 12 + 0x24, 0x00, 0x00, 0x00, // 22 dwPropertyDataLength 0x00000016 (36 bytes) + // ======================================== + // 4 + 'O',0, 'D',0, 'r',0, 'i',0, 'v',0, 'e',0, 0,0 + // 26 bPropertyData “ODrive” + // ======================================== + // 14 + +}; + + + +static uint8_t USBD_WinUSBComm_GetMSExtendedCompatIDOSDescriptor (USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req) +{ + switch (req->wIndex) + { + case 0x04: + USBD_CtlSendData (pdev, USBD_WinUSBComm_Extended_Compat_ID_OS_Desc, req->wLength); + break; + default: + USBD_CtlError(pdev , req); + return USBD_FAIL; + } + return USBD_OK; +} +static uint8_t USBD_WinUSBComm_GetMSExtendedPropertiesOSDescriptor (USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req) +{ + uint8_t byInterfaceIndex = (uint8_t)req->wValue; + if ( req->wIndex != 0x05 ) + { + USBD_CtlError(pdev , req); + return USBD_FAIL; + } + switch ( byInterfaceIndex ) + { + case 0: +#if NUM_INTERFACES == 2 + case 1: +#endif + USBD_CtlSendData (pdev, USBD_WinUSBComm_Extended_Properties_OS_Desc, req->wLength); + break; + default: + USBD_CtlError(pdev , req); + return USBD_FAIL; + } + return USBD_OK; +} +static uint8_t USBD_WinUSBComm_SetupVendorDevice(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req) +{ + USBD_CtlError(pdev , req); + return USBD_FAIL; +} +static uint8_t USBD_WinUSBComm_SetupVendorInterface(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req) +{ + USBD_CtlError(pdev , req); + // TODO: check if this is important + return USBD_FAIL; +} +static uint8_t USBD_WinUSBComm_SetupVendor(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req) +{ + switch ( req->bmRequest & USB_REQ_RECIPIENT_MASK ) + { + case USB_REQ_RECIPIENT_DEVICE: + return ( MS_VendorCode == req->bRequest ) ? USBD_WinUSBComm_GetMSExtendedCompatIDOSDescriptor(pdev, req) : USBD_WinUSBComm_SetupVendorDevice(pdev, req); + case USB_REQ_RECIPIENT_INTERFACE: + return ( MS_VendorCode == req->bRequest ) ? USBD_WinUSBComm_GetMSExtendedPropertiesOSDescriptor(pdev, req) : USBD_WinUSBComm_SetupVendorInterface(pdev, req); + case USB_REQ_RECIPIENT_ENDPOINT: + // fall through + default: + break; + } + USBD_CtlError(pdev , req); + return USBD_FAIL; +} + /** * @} */ diff --git a/Firmware/Board/v3/Middlewares/ST/STM32_USB_Device_Library/Core/Inc/usbd_def.h b/Firmware/Board/v3/Middlewares/ST/STM32_USB_Device_Library/Core/Inc/usbd_def.h index 8fbe81e4..f259b51d 100644 --- a/Firmware/Board/v3/Middlewares/ST/STM32_USB_Device_Library/Core/Inc/usbd_def.h +++ b/Firmware/Board/v3/Middlewares/ST/STM32_USB_Device_Library/Core/Inc/usbd_def.h @@ -68,7 +68,9 @@ #define USBD_IDX_PRODUCT_STR 0x02 #define USBD_IDX_SERIAL_STR 0x03 #define USBD_IDX_CONFIG_STR 0x04 -#define USBD_IDX_INTERFACE_STR 0x05 +#define USBD_IDX_INTERFACE_STR 0x05 +#define USBD_IDX_ODRIVE_INTF_STR 0x06 +#define USBD_IDX_MICROSOFT_DESC_STR 0xEE #define USB_REQ_TYPE_STANDARD 0x00 #define USB_REQ_TYPE_CLASS 0x20 diff --git a/Firmware/Board/v3/Src/usbd_cdc_if.c b/Firmware/Board/v3/Src/usbd_cdc_if.c index 1a9c43c4..77e70b2c 100644 --- a/Firmware/Board/v3/Src/usbd_cdc_if.c +++ b/Firmware/Board/v3/Src/usbd_cdc_if.c @@ -151,7 +151,7 @@ extern USBD_HandleTypeDef hUsbDeviceFS; static int8_t CDC_Init_FS(void); static int8_t CDC_DeInit_FS(void); static int8_t CDC_Control_FS(uint8_t cmd, uint8_t* pbuf, uint16_t length); -static int8_t CDC_Receive_FS(uint8_t* pbuf, uint32_t *Len); +static int8_t CDC_Receive_FS(uint8_t* pbuf, uint32_t *Len, uint8_t endpoint_pair); /* USER CODE BEGIN PRIVATE_FUNCTIONS_DECLARATION */ /* USER CODE END PRIVATE_FUNCTIONS_DECLARATION */ @@ -287,10 +287,10 @@ static int8_t CDC_Control_FS(uint8_t cmd, uint8_t* pbuf, uint16_t length) * @param Len: Number of data received (in bytes) * @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL */ -static int8_t CDC_Receive_FS(uint8_t* Buf, uint32_t *Len) +static int8_t CDC_Receive_FS(uint8_t* Buf, uint32_t *Len, uint8_t endpoint_pair) { /* USER CODE BEGIN 6 */ - usb_process_packet(Buf, *Len); + usb_process_packet(Buf, *Len, endpoint_pair); return (USBD_OK); /* USER CODE END 6 */ @@ -307,7 +307,7 @@ static int8_t CDC_Receive_FS(uint8_t* Buf, uint32_t *Len) * @param Len: Number of data to be sent (in bytes) * @retval USBD_OK if all operations are OK else USBD_FAIL or USBD_BUSY */ -uint8_t CDC_Transmit_FS(uint8_t* Buf, uint16_t Len) +uint8_t CDC_Transmit_FS(uint8_t* Buf, uint16_t Len, uint8_t endpoint_pair) { uint8_t result = USBD_OK; /* USER CODE BEGIN 7 */ @@ -323,7 +323,7 @@ uint8_t CDC_Transmit_FS(uint8_t* Buf, uint16_t Len) memcpy(UserTxBufferFS, Buf, Len); // Update Len USBD_CDC_SetTxBuffer(&hUsbDeviceFS, UserTxBufferFS, Len); - result = USBD_CDC_TransmitPacket(&hUsbDeviceFS); + result = USBD_CDC_TransmitPacket(&hUsbDeviceFS, endpoint_pair); /* USER CODE END 7 */ return result; } diff --git a/Firmware/Board/v3/Src/usbd_conf.c b/Firmware/Board/v3/Src/usbd_conf.c index f3eb88a9..2d66d4a1 100644 --- a/Firmware/Board/v3/Src/usbd_conf.c +++ b/Firmware/Board/v3/Src/usbd_conf.c @@ -154,6 +154,23 @@ void HAL_PCD_MspDeInit(PCD_HandleTypeDef* pcdHandle) */ void HAL_PCD_SetupStageCallback(PCD_HandleTypeDef *hpcd) { + USBD_StatusTypeDef ret = USBD_OK; + USBD_HandleTypeDef *pdev = hpcd->pData; + USBD_SetupReqTypedef *req = &pdev->request; + USBD_ParseSetupRequest(req, (uint8_t *)hpcd->Setup); + if ( ( USB_REQ_TYPE_VENDOR == (req->bmRequest & USB_REQ_TYPE_MASK) ) && ( MS_VendorCode == req->bRequest ) ) + { + pdev->ep0_state = USBD_EP0_SETUP; + pdev->ep0_data_len = pdev->request.wLength; + + ret = pdev->pClass->Setup(pdev, req); + + if( (req->wLength == 0) && (ret == USBD_OK) ) + { + USBD_CtlSendStatus(pdev); + } + return; + } USBD_LL_SetupStage((USBD_HandleTypeDef*)hpcd->pData, (uint8_t *)hpcd->Setup); } @@ -312,7 +329,7 @@ USBD_StatusTypeDef USBD_LL_Init(USBD_HandleTypeDef *pdev) pdev->pData = &hpcd_USB_OTG_FS; hpcd_USB_OTG_FS.Instance = USB_OTG_FS; - hpcd_USB_OTG_FS.Init.dev_endpoints = 4; + hpcd_USB_OTG_FS.Init.dev_endpoints = 6; hpcd_USB_OTG_FS.Init.speed = PCD_SPEED_FULL; hpcd_USB_OTG_FS.Init.dma_enable = DISABLE; hpcd_USB_OTG_FS.Init.ep0_mps = DEP0CTL_MPS_64; @@ -329,7 +346,8 @@ USBD_StatusTypeDef USBD_LL_Init(USBD_HandleTypeDef *pdev) HAL_PCDEx_SetRxFiFo(&hpcd_USB_OTG_FS, 0x80); HAL_PCDEx_SetTxFiFo(&hpcd_USB_OTG_FS, 0, 0x40); - HAL_PCDEx_SetTxFiFo(&hpcd_USB_OTG_FS, 1, 0x80); + HAL_PCDEx_SetTxFiFo(&hpcd_USB_OTG_FS, 1, 0x40); // CDC IN endpoint + HAL_PCDEx_SetTxFiFo(&hpcd_USB_OTG_FS, 3, 0x40); // ODrive IN endpoint } return USBD_OK; } diff --git a/Firmware/Board/v3/Src/usbd_desc.c b/Firmware/Board/v3/Src/usbd_desc.c index 856d05e2..d213f64a 100644 --- a/Firmware/Board/v3/Src/usbd_desc.c +++ b/Firmware/Board/v3/Src/usbd_desc.c @@ -97,7 +97,8 @@ #define USBD_PID_FS 0x0D32 #define USBD_PRODUCT_XSTR(s) USBD_PRODUCT_STR(s) #define USBD_PRODUCT_STR(s) #s -#define USBD_PRODUCT_STRING_FS ODrive version HW_VERSION_MAJOR.HW_VERSION_MINOR +#define USBD_PRODUCT_STRING_FS ODrive HW_VERSION_MAJOR.HW_VERSION_MINOR CDC Interface +#define NATIVE_STRING ODrive HW_VERSION_MAJOR.HW_VERSION_MINOR Native Interface #define USBD_SERIALNUMBER_STRING_FS "000000000001" #define USBD_CONFIGURATION_STRING_FS "CDC Config" #define USBD_INTERFACE_STRING_FS "CDC Interface" @@ -114,6 +115,50 @@ /* USER CODE BEGIN 0 */ +// MS OS String descriptor to tell Windows that it may query for other descriptors +// It's a standard string descriptor. +// Windows will only query for OS descriptors once! +// Delete the information about already queried devices in registry by deleting: +// HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\usbflags\VVVVPPPPRRRR +__ALIGN_BEGIN uint8_t USBD_MS_OS_StringDescriptor[] __ALIGN_END = +{ + 0x12, // bLength 1 0x12 Length of the descriptor + 0x03, // bDescriptorType 1 0x03 Descriptor type + // qwSignature 14 ‘MSFT100’ Signature field + 0x4D, 0x00, // 'M' + 0x53, 0x00, // 'S' + 0x46, 0x00, // 'F' + 0x54, 0x00, // 'T' + 0x31, 0x00, // '1' + 0x30, 0x00, // '0' + 0x30, 0x00, // '0' + MS_VendorCode, // bMS_VendorCode 1 Vendor-specific Vendor code + 0x00 // bPad 1 0x00 Pad field +}; + +// redefined further down +__ALIGN_BEGIN uint8_t USBD_StrDesc[USBD_MAX_STR_DESC_SIZ] __ALIGN_END; +/** +* @brief UsrStrDescriptor +* return non standard string descriptor +* @param pdev: device instance +* @param index : descriptor index (0xEE for MS OS String Descriptor) +* @param length : pointer data length +* @retval pointer to descriptor buffer +*/ +uint8_t * USBD_UsrStrDescriptor(struct _USBD_HandleTypeDef *pdev, uint8_t index, uint16_t *length) +{ + *length = 0; + if (USBD_IDX_MICROSOFT_DESC_STR == index) { + *length = sizeof (USBD_MS_OS_StringDescriptor); + return USBD_MS_OS_StringDescriptor; + } else if (USBD_IDX_ODRIVE_INTF_STR == index) { + USBD_GetString((uint8_t *)USBD_PRODUCT_XSTR(NATIVE_STRING), USBD_StrDesc, length); + return USBD_StrDesc; + } + return NULL; +} + /* USER CODE END 0 */ /** @defgroup USBD_DESC_Private_Macros USBD_DESC_Private_Macros @@ -189,16 +234,17 @@ __ALIGN_BEGIN uint8_t USBD_FS_DeviceDesc[USB_LEN_DEV_DESC] __ALIGN_END = 0x00, /*bcdUSB */ #endif /* (USBD_LPM_ENABLED == 1) */ 0x02, - 0x02, /*bDeviceClass*/ + // Notify OS that this is a composite device + 0xEF, /*bDeviceClass*/ 0x02, /*bDeviceSubClass*/ - 0x00, /*bDeviceProtocol*/ + 0x01, /*bDeviceProtocol*/ USB_MAX_EP0_SIZE, /*bMaxPacketSize*/ LOBYTE(USBD_VID), /*idVendor*/ HIBYTE(USBD_VID), /*idVendor*/ LOBYTE(USBD_PID_FS), /*idProduct*/ HIBYTE(USBD_PID_FS), /*idProduct*/ 0x00, /*bcdDevice rel. 2.00*/ - 0x02, + 0x03, /* bNumInterfaces */ USBD_IDX_MFC_STR, /*Index of manufacturer string*/ USBD_IDX_PRODUCT_STR, /*Index of product string*/ USBD_IDX_SERIAL_STR, /*Index of serial number string*/ diff --git a/Firmware/CHANGELOG.md b/Firmware/CHANGELOG.md index 44075136..8ad796ce 100644 --- a/Firmware/CHANGELOG.md +++ b/Firmware/CHANGELOG.md @@ -11,7 +11,10 @@ Please add a note of your changes below this heading if you make a Pull Request. * System stats (e.g. stack usage) are exposed under `.system_stats` ### Changed -* The DFU script now verifies the flash after writing +* DFU script updates + * Verify the flash after writing + * Automatically download firmware from GitHub releases if no file is provided + * Retain configuration during firmware updates * Refactor python tools * The scripts `explore_odrive.py`, `liveplotter.py`, `drv_status.py` and `rate_test.py` have been merged into one single `odrivetool` script. Running this script without any arguments provides the shell that `explore_odrive.py` used to provide. * The command line options of `odrivetool` have changed compared to the original `explore_odrive.py`. See `odrivetool --help` for more details. @@ -19,11 +22,15 @@ Please add a note of your changes below this heading if you make a Pull Request. * No need to restart the `odrivetool` shell when devices get disconnected and reconnected * ODrive accesses from within python tools are now thread-safe. That means you can read from the same remote property from multiple threads concurrently. * The liveplotter (`odrivetool liveplotter`, formerly `liveplotter.py`) does no longer steal focus and closes as expected + * Add commands `odrivetool backup-config` and `odrivetool restore-config` * (experimental: start liveplotter from `odrivetool` shell by typing `start_liveplotter(lambda: odrv0.motor0.encoder.encoder_state)`) * `make write_otp` command to burn the board version onto the ODrive's one-time programmable memory. If you have an ODrive v3.4 or older, you can run this once for a better firmware update user experience in the future. Run the command without any options for more details. Once set, the board version is exposed through the `hw_version_[...]` properties. * bake Git-derived firmware version into firmware binary. The firmware version is exposed through the `fw_version_[...]` properties. * Set thread priority of USB pump thread above protocol thread * GPIO3 not sensitive to edges by default +* The device now appears as a composite device on USB. One subdevice is still a CDC device (virtual COM port), the other subdevice is a vendor specific class. This should resolve several issues that were caused by conflicting kernel drivers or OS services. +* Add WinUSB descriptors. This will tell Windows >= 8 to automatically load winusb.sys for the ODrive (only for the vendor specific subdevice). This makes it possible to use the ODrive from userspace via WinUSB with zero configuration. The Python tool currently still uses libusb so Zadig is still required. +* Add a configuration to enable the ASCII protocol on USB at runtime. This will only enable the ASCII protocol on the USB CDC subdevice, not the vendor specific subdevice so the python tools will still be able to talk to the ODrive. ### Fixed * Enums now transported with correct underlying type on native protocol diff --git a/Firmware/MotorControl/main.cpp b/Firmware/MotorControl/main.cpp index 3c2c815e..4fa3450f 100644 --- a/Firmware/MotorControl/main.cpp +++ b/Firmware/MotorControl/main.cpp @@ -34,6 +34,8 @@ void save_configuration(void) { &motor_configs, &axis_configs)) { //printf("saving configuration failed\r\n"); osDelay(5); + } else { + user_config_loaded_ = true; } } diff --git a/Firmware/MotorControl/odrive_main.h b/Firmware/MotorControl/odrive_main.h index bae964fb..af7bd3f3 100644 --- a/Firmware/MotorControl/odrive_main.h +++ b/Firmware/MotorControl/odrive_main.h @@ -57,8 +57,9 @@ extern SystemStats_t system_stats_; // @brief general user configurable board configuration struct BoardConfig_t { - bool enable_uart = false; + bool enable_uart = true; bool enable_i2c_instead_of_can = false; + bool enable_ascii_protocol_on_usb = true; float brake_resistance = 0.47f; // [ohm] float dc_bus_undervoltage_trip_level = 8.0f; //(*tree_ptr); set_application_endpoints(&endpoint_provider); - serve_on_uart(); - serve_on_usb(); + start_uart_server(); + start_usb_server(); if (board_config.enable_i2c_instead_of_can) { - serve_on_i2c(); + start_i2c_server(); } for (;;) { diff --git a/Firmware/communication/interface_i2c.cpp b/Firmware/communication/interface_i2c.cpp index 7138f662..e5060572 100644 --- a/Firmware/communication/interface_i2c.cpp +++ b/Firmware/communication/interface_i2c.cpp @@ -24,7 +24,7 @@ public: } i2c1_packet_output; BidirectionalPacketBasedChannel i2c1_channel(i2c1_packet_output); -void serve_on_i2c() { +void start_i2c_server() { // CAN H = SDA // CAN L = SCL HAL_I2C_EnableListen_IT(&hi2c1); diff --git a/Firmware/communication/interface_i2c.h b/Firmware/communication/interface_i2c.h index db866912..1bf89661 100644 --- a/Firmware/communication/interface_i2c.h +++ b/Firmware/communication/interface_i2c.h @@ -16,7 +16,7 @@ struct I2CStats_t { extern I2CStats_t i2c_stats_; -void serve_on_i2c(void); +void start_i2c_server(void); #ifdef __cplusplus } diff --git a/Firmware/communication/interface_uart.cpp b/Firmware/communication/interface_uart.cpp index 7d17e528..432159b7 100644 --- a/Firmware/communication/interface_uart.cpp +++ b/Firmware/communication/interface_uart.cpp @@ -87,7 +87,7 @@ static void uart_server_thread(void * ctx) { }; } -void serve_on_uart() { +void start_uart_server() { // DMA is set up to recieve in a circular buffer forever. // We dont use interrupts to fetch the data, instead we periodically read // data out of the circular buffer into a parse buffer, controlled by a state machine diff --git a/Firmware/communication/interface_uart.h b/Firmware/communication/interface_uart.h index 8ad71c19..a7a291f0 100644 --- a/Firmware/communication/interface_uart.h +++ b/Firmware/communication/interface_uart.h @@ -12,7 +12,7 @@ extern "C" { extern osThreadId uart_thread; -void serve_on_uart(void); +void start_uart_server(void); #ifdef __cplusplus } diff --git a/Firmware/communication/interface_usb.cpp b/Firmware/communication/interface_usb.cpp index 5687e186..c0194ec5 100644 --- a/Firmware/communication/interface_usb.cpp +++ b/Firmware/communication/interface_usb.cpp @@ -12,8 +12,12 @@ #include #include +#include +#include "ascii_protocol.h" + static uint8_t* usb_buf; static uint32_t usb_len; +static uint8_t active_endpoint_pair; // FIXME: the stdlib doesn't know about CMSIS threads, so this is just a global variable static thread_local uint32_t deadline_ms = 0; @@ -39,12 +43,12 @@ public: // transmit packet uint8_t status = CDC_Transmit_FS( const_cast(buffer) /* casting this const away is safe because... - well... it's not actually. Stupid STM. */, length); + well... it's not actually. Stupid STM. */, length, active_endpoint_pair); if (status != USBD_OK) { osSemaphoreRelease(sem_usb_tx); return -1; } - usb_stats_.tx_cnt = 0; + usb_stats_.tx_cnt++; return 0; } } usb_packet_output; @@ -90,27 +94,30 @@ static void usb_server_thread(void * ctx) { if (sem_stat == osOK) { usb_stats_.rx_cnt++; deadline_ms = timeout_to_deadline(PROTOCOL_SERVER_TIMEOUT_MS); + if (active_endpoint_pair == CDC_OUT_EP && board_config.enable_ascii_protocol_on_usb) { + ASCII_protocol_parse_stream(usb_buf, usb_len, usb_stream_output); + } else { #if defined(USB_PROTOCOL_NATIVE) - usb_channel.process_packet(usb_buf, usb_len); + usb_channel.process_packet(usb_buf, usb_len); #elif defined(USB_PROTOCOL_NATIVE_STREAM_BASED) - usb_native_stream_input.process_bytes(usb_buf, usb_len); -#elif defined(USB_PROTOCOL_ASCII) - ASCII_protocol_parse_stream(usb_buf, usb_len, usb_stream_output); + usb_native_stream_input.process_bytes(usb_buf, usb_len); #endif - USBD_CDC_ReceivePacket(&hUsbDeviceFS); // Allow next packet + } + USBD_CDC_ReceivePacket(&hUsbDeviceFS, active_endpoint_pair); // Allow next packet } } } // Called from CDC_Receive_FS callback function, this allows the communication // thread to handle the incoming data -void usb_process_packet(uint8_t *buf, uint32_t len) { +void usb_process_packet(uint8_t *buf, uint32_t len, uint8_t endpoint_pair) { usb_buf = buf; usb_len = len; + active_endpoint_pair = endpoint_pair; osSemaphoreRelease(sem_usb_rx); } -void serve_on_usb() { +void start_usb_server() { // Start USB communication thread osThreadDef(usb_server_thread_def, usb_server_thread, osPriorityNormal, 0, 512); usb_thread = osThreadCreate(osThread(usb_server_thread_def), NULL); diff --git a/Firmware/communication/interface_usb.h b/Firmware/communication/interface_usb.h index 9038d822..f8b11ee0 100644 --- a/Firmware/communication/interface_usb.h +++ b/Firmware/communication/interface_usb.h @@ -21,8 +21,8 @@ typedef struct { extern USBStats_t usb_stats_; -void usb_process_packet(uint8_t *buf, uint32_t len); -void serve_on_usb(void); +void usb_process_packet(uint8_t *buf, uint32_t len, uint8_t endpoint_pair); +void start_usb_server(void); #ifdef __cplusplus } diff --git a/tools/odrive/configuration.py b/tools/odrive/configuration.py new file mode 100644 index 00000000..8f297249 --- /dev/null +++ b/tools/odrive/configuration.py @@ -0,0 +1,82 @@ + +import json +import os +import tempfile +import odrive.remote_object +from odrive.utils import OperationAbortedException + +def get_dict(obj, is_config_object): + result = {} + for (k,v) in obj._remote_attributes.items(): + if isinstance(v, odrive.remote_object.RemoteProperty) and is_config_object: + result[k] = v.get_value() + elif isinstance(v, odrive.remote_object.RemoteObject): + sub_dict = get_dict(v, k == 'config') + if sub_dict != {}: + result[k] = sub_dict + return result + +def set_dict(obj, path, config_dict): + errors = [] + for (k,v) in config_dict.items(): + name = path + ("." if path != "" else "") + k + if not k in obj._remote_attributes: + errors.append("Could not restore {}: property not found on device".format(name)) + continue + remote_attribute = obj._remote_attributes[k] + if isinstance(remote_attribute, odrive.remote_object.RemoteObject): + errors += set_dict(remote_attribute, name, v) + else: + try: + remote_attribute.set_value(v) + except Exception as ex: + errors.append("Could not restore {}: {}".format(name, str(ex))) + return errors + +def get_temp_config_filename(device): + serial_number = odrive.utils.get_serial_number_str(device) + safe_serial_number = ''.join(filter(str.isalnum, serial_number)) + return os.path.join(tempfile.gettempdir(), 'odrive-config-{}.json'.format(safe_serial_number)) + +def backup_config(device, filename, logger): + """ + Exports the configuration of an ODrive to a JSON file. + If no file name is provided, the file is placed into a + temporary directory. + """ + + if filename is None: + filename = get_temp_config_filename(device) + + logger.info("Saving configuration to {}...".format(filename)) + + if os.path.exists(filename): + if not odrive.utils.yes_no_prompt("The file {} already exists. Do you want to override it?".format(filename), True): + raise OperationAbortedException() + + data = get_dict(device, False) + with open(filename, 'w') as file: + json.dump(data, file) + logger.info("Configuration saved.") + +def restore_config(device, filename, logger): + """ + Restores the configuration stored in a file + """ + + if filename is None: + filename = get_temp_config_filename(device) + + with open(filename) as file: + data = json.load(file) + + logger.info("Restoring configuration from {}...".format(filename)) + errors = odrive.configuration.set_dict(device, "", data) + + for error in errors: + logger.info(error) + if errors: + logger.warn("Some of the configuration could not be restored.") + + device.save_configuration() + logger.info("Configuration restored.") diff --git a/tools/odrive/dfu.py b/tools/odrive/dfu.py index 1efd4592..0f7b458d 100755 --- a/tools/odrive/dfu.py +++ b/tools/odrive/dfu.py @@ -9,11 +9,13 @@ import time import threading import platform import struct -import array -import fractions +import requests +import re +import io +import os import usb.core import odrive.discovery -from odrive.utils import Event +from odrive.utils import Event, OperationAbortedException from odrive.dfuse import * try: @@ -24,46 +26,17 @@ except: sys.exit(1) -SIZE_MULTIPLIERS = {' ': 1, 'K': 1024, 'M' : 1024*1024} -MAX_TRANSFER_SIZE = 2048 +def get_fw_version_string(fw_version): + if (fw_version[0], fw_version[1], fw_version[2]) == (0, 0, 0): + return "[unknown version]" + else: + return "v{}.{}.{}{}".format(fw_version[0], fw_version[1], fw_version[2], "-dev" if fw_version[3] else "") - -def get_device_sectors(dfudev): - """ - Returns a list of all sectors on the device. - Each sector is represented as a dictionary with the following keys: - - name: name of the associated memory region (e.g. "Internal Flash") - - alt: USB alternate setting associated with this memory region - - addr: Start address of the sector (e.g. 0x08004000 for the second flash sectors) - - baseaddr: Start address of the memory region associated with the sector - (e.g. 0x08000000 for all flash sectors) - - len: Number of bytes in the sector - """ - for name, alt in dfudev.alternates(): - # example for name: - # '@Internal Flash /0x08000000/04*016Kg,01*064Kg,07*128Kg' - label, baseaddr, layout = name.split('/') - baseaddr = int(baseaddr, 0) # convert hex to decimal - addr = baseaddr - - for sector in layout.split(','): - repeat, size = map(int, sector[:-2].split('*')) - size *= SIZE_MULTIPLIERS[sector[-2].upper()] - mode = sector[-1] - - while repeat > 0: - # TODO: verify if the section is writable - yield { - 'name': label.strip().strip('@'), - 'alt': alt, - 'baseaddr': baseaddr, - 'addr': addr, - 'len': size, - 'mode': mode - } - - addr += size - repeat -= 1 +def get_hw_version_string(hw_version): + if hw_version == (0, 0, 0): + return "[unknown version]" + else: + return "v{}.{}{}".format(hw_version[0], hw_version[1], ("-" + str(hw_version[2]) + "V") if hw_version[2] > 0 else "") def populate_sectors(sectors, hexfile): """ @@ -88,66 +61,6 @@ def populate_sectors(sectors, hexfile): # TODO: verify if the section is writable yield (sector, hexfile.tobinarray(addr, addr + size - 1)) -def set_alternate_safe(dfudev, alt): - dfudev.set_alternate(alt) - if dfudev.get_state() == DfuState.DFU_ERROR: - dfudev.clear_status() - dfudev.wait_while_state(DfuState.DFU_ERROR) - -#def clear_error(dfudev) -def set_address_safe(dfudev, addr): - dfudev.set_address(addr) - status = dfudev.wait_while_state(DfuState.DFU_DOWNLOAD_BUSY) - if status[1] != DfuState.DFU_DOWNLOAD_IDLE: - raise RuntimeError("An error occured. Device Status: %r" % status) - # take device out of DFU_DOWNLOAD_SYNC and into DFU_IDLE - dfudev.abort() - status = dfudev.wait_while_state(DfuState.DFU_DOWNLOAD_SYNC) - if status[1] != DfuState.DFU_IDLE: - raise RuntimeError("An error occured. Device Status: %r" % status) - - -def erase(dfudev, sector): - set_alternate_safe(dfudev, sector['alt']) - dfudev.erase(sector['addr']) - status = dfudev.wait_while_state(DfuState.DFU_DOWNLOAD_BUSY, timeout=sector['len']/32) - if status[1] != DfuState.DFU_DOWNLOAD_IDLE: - raise RuntimeError("An error occured. Device Status: %r" % status) - -def flash(dfudev, sector, data): - set_alternate_safe(dfudev, sector['alt']) - set_address_safe(dfudev, sector['addr']) - - transfer_size = fractions.gcd(sector['len'], MAX_TRANSFER_SIZE) - - blocks = [data[i:i + transfer_size] for i in range(0, len(data), transfer_size)] - for blocknum, block in enumerate(blocks): - #print('write to {:08X} ({} bytes)'.format( - # sector['addr'] + blocknum * TRANSFER_SIZE, len(block))) - dfudev.write(blocknum, block) - status = dfudev.wait_while_state(DfuState.DFU_DOWNLOAD_BUSY) - if status[1] != DfuState.DFU_DOWNLOAD_IDLE: - raise RuntimeError("An error occured. Device Status: %r" % status) - -def read(dfudev, sector): - """ - Reads data from the specified sector - Returns: a byte array containing the data - """ - set_alternate_safe(dfudev, sector['alt']) - set_address_safe(dfudev, sector['addr']) - - transfer_size = fractions.gcd(sector['len'], MAX_TRANSFER_SIZE) - #blocknum_offset = int((sector['addr'] - sector['baseaddr']) / transfer_size) - - - data = array.array(u'B') - for blocknum in range(int(sector['len'] / transfer_size)): - #print('read at {:08X}'.format(sector['addr'] + blocknum * TRANSFER_SIZE)) - deviceBlock = dfudev.read(blocknum, transfer_size) - data.extend(deviceBlock) - dfudev.abort() # take device into DFU_IDLE - return data def get_first_mismatch_index(array1, array2): """ @@ -161,42 +74,132 @@ def get_first_mismatch_index(array1, array2): return pos return None - -def jump_to_application(dfudev, address): - set_address_safe(dfudev, address) - #dfudev.set_address(address) - #status = dfudev.wait_while_state(DfuState.DFU_DOWNLOAD_BUSY) - #if status[1] != DfuState.DFU_DOWNLOAD_IDLE: - # raise RuntimeError("An error occured. Device Status: {}".format(status[1])) - - dfudev.leave() - status = dfudev.wait_while_state(DfuState.DFU_MANIFEST_SYNC) - if status[1] != DfuState.DFU_MANIFEST: - raise RuntimeError("An error occured. Device Status: {}".format(status[1])) - - -def dump_otp(): +def dump_otp(dfudev): """ Dumps the contents of the one-time-programmable - memory. The OTP will be used in future versions of - this script to determine the board version. + memory for debugging purposes. + The OTP is used to determine the board version. """ # 512 Byte OTP - otp_sector = [s for s in sectors if s['name'] == 'OTP Memory' and s['addr'] == 0x1fff7800][0] - data = read(dfudev, otp_sector) + otp_sector = [s for s in dfudev.sectors if s['name'] == 'OTP Memory' and s['addr'] == 0x1fff7800][0] + data = dfudev.read_sector(otp_sector) print(' '.join('{:02X}'.format(x) for x in data)) # 16 lock bytes - otp_lock_sector = [s for s in sectors if s['name'] == 'OTP Memory' and s['addr'] == 0x1fff7A00][0] - data = read(dfudev, otp_lock_sector) + otp_lock_sector = [s for s in dfudev.sectors if s['name'] == 'OTP Memory' and s['addr'] == 0x1fff7A00][0] + data = dfudev.read_sector(otp_lock_sector) print(' '.join('{:02X}'.format(x) for x in data)) +class Firmware(): + def __init__(self): + self.fw_version = (0, 0, 0, True) + self.hw_version = (0, 0, 0) + + @staticmethod + def is_newer(a, b): + a_num = (a[0], a[1], a[2]) + b_num = (b[0], b[1], b[2]) + if a_num == (0, 0, 0) or b_num == (0, 0, 0): + return False # Cannot compare unknown versions + return a_num > b_num or (a_num == b_num and not a[3] and b[3]) + + def __gt__(self, other): + """ + Compares two firmware versions. If both versions are equal, the + prerelease version is considered older than the release version. + """ + if not isinstance(other, tuple): + other = other.fw_version + return Firmware.is_newer(self.fw_version, other) + + def __lt__(self, other): + """ + Compares two firmware versions. If both versions are equal, the + prerelease version is considered older than the release version. + """ + if not isinstance(other, tuple): + other = other.fw_version + return Firmware.is_newer(other, self.fw_version) + + def is_compatible(self, hw_version): + """ + Determines if this firmware is compatible + with the specified hardware version + """ + return self.hw_version == hw_version + +class FirmwareFromGithub(Firmware): + """ + Represents a firmware asset + """ + def __init__(self, release_json, asset_json): + Firmware.__init__(self) + if release_json['draft'] or release_json['prerelease']: + release_json['tag_name'] += "*" + self.fw_version = odrive.version.version_str_to_tuple(release_json['tag_name']) + + hw_version_regex = r'.*v([0-9]+).([0-9]+)(-(?P[0-9]+)V)?.hex' + hw_version_match = re.search(hw_version_regex, asset_json['name']) + self.hw_version = (int(hw_version_match[1]), + int(hw_version_match[2]), + int(hw_version_match.groupdict().get('voltage') or 0)) + self.github_asset_id = asset_json['id'] + self.hex = None + # no technical reason to fetch this - just interesting + self.download_count = asset_json['download_count'] + + def get_as_hex(self): + """ + Returns the content of the firmware in as a binary array in Intel Hex format + """ + if self.hex is None: + print("Downloading firmware {}...".format(get_fw_version_string(self.fw_version))) + response = requests.get('https://api.github.com/repos/madcowswe/ODrive/releases/assets/' + str(self.github_asset_id), + headers={'Accept': 'application/octet-stream'}) + if response.status_code != 200: + raise Exception("failed to download firmware") + self.hex = response.content + return io.StringIO(self.hex.decode('utf-8')) + +class FirmwareFromFile(Firmware): + def __init__(self, file): + Firmware.__init__(self) + self._file = file + def get_as_hex(self): + return self._file + +def get_all_github_firmwares(): + response = requests.get('https://api.github.com/repos/madcowswe/ODrive/releases') + if response.status_code != 200: + raise Exception("could not fetch releases") + response_json = response.json() + + for release_json in response_json: + for asset_json in release_json['assets']: + try: + if asset_json['name'].lower().endswith('.hex'): + fw = FirmwareFromGithub(release_json, asset_json) + yield fw + except Exception as ex: + print(ex) + +def get_newest_firmware(hw_version): + """ + Returns the newest available firmware for the specified hardware version + """ + firmwares = get_all_github_firmwares() + firmwares = filter(lambda fw: not fw.fw_version[3], firmwares) # ignore prereleases + firmwares = filter(lambda fw: fw.hw_version == hw_version, firmwares) + firmwares = list(firmwares) + firmwares.sort() + return firmwares[-1] if len(firmwares) else None + def show_deferred_message(message, cancellation_token): """ Shows a message after 10s, unless cancellation_token gets set. """ def show_message_thread(message, cancellation_token): - for i in range(1,10): + for _ in range(1,10): if cancellation_token.is_set(): return time.sleep(1) @@ -206,104 +209,157 @@ def show_deferred_message(message, cancellation_token): t.daemon = True t.start() -def put_odrive_into_dfu_mode(my_drive, cancellation_token): +def put_into_dfu_mode(device, cancellation_token): """ Puts the specified device into DFU mode """ - if not hasattr(my_drive, "enter_dfu_mode"): + if not hasattr(device, "enter_dfu_mode"): print("The firmware on device {} does not support DFU. You need to \n" "flash the firmware once using STLink (`make flash`), after that \n" "DFU with this script should work fine." - .format(my_drive.__channel__.usb_device.serial_number)) + .format(device.__channel__.usb_device.serial_number)) return - hw_version_major = my_drive.hw_version_major if hasattr(my_drive, 'hw_version_major') else 3 - hw_version_minor = my_drive.hw_version_minor if hasattr(my_drive, 'hw_version_minor') else 4 - if hw_version_major == 3 and hw_version_minor >= 5: - print("Putting device {} into DFU mode...".format(my_drive.__channel__.usb_device.serial_number)) - try: - my_drive.enter_dfu_mode() - except odrive.protocol.ChannelBrokenException: - pass # this is expected because the device reboots - if platform.system() == "Windows": - show_deferred_message("Still waiting for the device to reappear.\n" - "Use the Zadig utility to set the driver of 'STM32 BOOTLOADER' to libusb-win32.", - cancellation_token) - else: - print("Found device {}".format(my_drive.__channel__.usb_device.serial_number)) + hw_version_major = device.hw_version_major if hasattr(device, 'hw_version_major') else 3 + hw_version_minor = device.hw_version_minor if hasattr(device, 'hw_version_minor') else 4 + if hw_version_major == 3 and hw_version_minor < 5: print(" DFU mode is not supported on board version 3.4 or earlier.") print(" This is because entering DFU mode on such a device would") print(" break the brake resistor FETs under some circumstances.") + raise Exception("not supported") + + print("Putting device {} into DFU mode...".format(device.__channel__.usb_device.serial_number)) + try: + device.enter_dfu_mode() + except odrive.protocol.ChannelBrokenException: + pass # this is expected because the device reboots + if platform.system() == "Windows": + show_deferred_message("Still waiting for the device to reappear.\n" + "Use the Zadig utility to set the driver of 'STM32 BOOTLOADER' to libusb-win32.", + cancellation_token) -def launch_dfu(args, app_shutdown_token): +def find_device_in_dfu_mode(serial_number, cancellation_token): """ - Waits for a device that matches args.path and args.serial_number - and then upgrades the device's firmware. + Polls libusb until a device in DFU mode is found """ + while not cancellation_token.is_set(): + params = {} if serial_number == None else {'serial_number': serial_number} + stm_device = usb.core.find(idVendor=0x0483, idProduct=0xdf11, **params) + if stm_device != None: + return stm_device + time.sleep(1) + return None + +def update_device(device, firmware, logger, cancellation_token): + """ + Updates the specified device with the specified firmware. + The device passed to this function can either be in + normal mode or in DFU mode. + The firmware should be an instance of Firmware or None. + If firmware is None, the newest firmware for the device is + downloaded from GitHub releases. + """ + + if isinstance(device, usb.core.Device): + serial_number = device.serial_number + dfudev = DfuDevice(device) + if (logger._verbose): + logger.debug("OTP:") + dump_otp(dfudev) + + # Read hardware version from one-time-programmable memory + otp_sector = [s for s in dfudev.sectors if s['name'] == 'OTP Memory' and s['addr'] == 0x1fff7800][0] + otp_data = dfudev.read_sector(otp_sector) + if otp_data[0] == 0: + otp_data = otp_data[16:] + if otp_data[0] == 0xfe: + hw_version = (otp_data[3], otp_data[4], otp_data[5]) + else: + hw_version = (0, 0, 0) + else: + serial_number = device.__channel__.usb_device.serial_number + dfudev = None + + # Read hardware version as reported from firmware + hw_version_major = device.hw_version_major if hasattr(device, 'hw_version_major') else 0 + hw_version_minor = device.hw_version_minor if hasattr(device, 'hw_version_minor') else 0 + hw_version_variant = device.hw_version_variant if hasattr(device, 'hw_version_variant') else 0 + hw_version = (hw_version_major, hw_version_minor, hw_version_variant) + + fw_version_major = device.fw_version_major if hasattr(device, 'fw_version_major') else 0 + fw_version_minor = device.fw_version_minor if hasattr(device, 'fw_version_minor') else 0 + fw_version_revision = device.fw_version_revision if hasattr(device, 'fw_version_revision') else 0 + fw_version_prerelease = device.fw_version_prerelease if hasattr(device, 'fw_version_prerelease') else True + fw_version = (fw_version_major, fw_version_minor, fw_version_revision, fw_version_prerelease) + + print("Found ODrive {} ({}) with firmware {}{}".format( + serial_number, + get_hw_version_string(hw_version), + get_fw_version_string(fw_version), + " in DFU mode" if dfudev is not None else "")) + + if firmware is None: + if hw_version == (0, 0, 0): + if dfudev is None: + suggestion = 'You have to manually flash an up-to-date firmware to make automatic checks work. Run `odrivetool dfu --help` for more info.' + else: + suggestion = 'Run "make write_otp" to program the board version.' + raise Exception('Cannot check online for new firmware because the board version is unknown. ' + suggestion) + print("Checking online for newest firmware...", end='') + firmware = get_newest_firmware(hw_version) + if firmware is None: + raise Exception("could not find any firmware release for this board version") + print(" found {}".format(get_fw_version_string(firmware.fw_version))) + + if firmware < fw_version: + print("Warning: you are about to flash firmware {} which is older than the firmware on the device ({}).".format( + get_fw_version_string(firmware.fw_version), + get_fw_version_string(fw_version))) + if not odrive.utils.yes_no_prompt("Do you want to flash this firmware anyway?", True): + raise OperationAbortedException() # load hex file # TODO: Either use the elf format or pack a custom format with a manifest. # This way we can for instance verify the target board version and only - # have to publish one file for every board. - hexfile = IntelHex(args.file) + # have to publish one file for every board (instead of elf AND hex files). + hexfile = IntelHex(firmware.get_as_hex()) - if (args.verbose): - print("Contiguous segments in hex file:") - for start, end in hexfile.segments(): - print(" {:08X} to {:08X}".format(start, end - 1)) + logger.debug("Contiguous segments in hex file:") + for start, end in hexfile.segments(): + logger.debug(" {:08X} to {:08X}".format(start, end - 1)) - serial_number = args.serial_number + # Back up configuration + if dfudev is None: + did_backup_config = device.user_config_loaded if hasattr(device, 'user_config_loaded') else False + if did_backup_config: + odrive.configuration.backup_config(device, None, logger) + elif not odrive.utils.yes_no_prompt("The configuration cannot be backed up because the device is already in DFU mode. The configuration may be lost after updating. Do you want to continue anyway?", True): + raise OperationAbortedException() - find_odrive_cancellation_token = Event(app_shutdown_token) + # Put the device into DFU mode if it's not already in DFU mode + if dfudev is None: + put_into_dfu_mode(device, cancellation_token) + stm_device = find_device_in_dfu_mode(serial_number, cancellation_token) + dfudev = DfuDevice(stm_device) - print("Waiting for ODrive...") - - # Scan for ODrives not in DFU mode and put them into DFU mode once they appear - # We only scan on USB because DFU is only possible over USB - odrive.discovery.find_all(args.path, serial_number, - lambda dev: put_odrive_into_dfu_mode(dev, find_odrive_cancellation_token), - find_odrive_cancellation_token, app_shutdown_token) - - # Poll libUSB until a device in DFU mode is found - while not app_shutdown_token.is_set(): - params = {} if serial_number == None else {'serial_number': serial_number} - stm_device = usb.core.find(idVendor=0x0483, idProduct=0xdf11, **params) - if stm_device != None: - break - time.sleep(1) - find_odrive_cancellation_token.set() # we don't need this thread anymore - if app_shutdown_token.is_set(): - sys.exit(1) - print("Found device {} in DFU mode".format(stm_device.serial_number)) - - dfudev = DfuDevice(stm_device) - - sectors = list(get_device_sectors(dfudev)) - - if (args.verbose): - print("Sectors on device: ") - for sector in sectors: - print(" {:08X} to {:08X} ({})".format( - sector['addr'], - sector['addr'] + sector['len'] - 1, - sector['name'])) + logger.debug("Sectors on device: ") + for sector in dfudev.sectors: + logger.debug(" {:08X} to {:08X} ({})".format( + sector['addr'], + sector['addr'] + sector['len'] - 1, + sector['name'])) # fill sectors with data - touched_sectors = list(populate_sectors(sectors, hexfile)) + touched_sectors = list(populate_sectors(dfudev.sectors, hexfile)) - if (args.verbose): - print("The following sectors will be flashed: ") - for sector,_ in touched_sectors: - print(" {:08X} to {:08X}".format(sector['addr'], sector['addr'] + sector['len'] - 1)) - - if (args.verbose): - print("OTP:") - dump_otp() + logger.debug("The following sectors will be flashed: ") + for sector,_ in touched_sectors: + logger.debug(" {:08X} to {:08X}".format(sector['addr'], sector['addr'] + sector['len'] - 1)) # Erase try: for i, (sector, data) in enumerate(touched_sectors): print("Erasing... (sector {}/{}) \r".format(i, len(touched_sectors)), end='', flush=True) - erase(dfudev, sector) + dfudev.erase_sector(sector) print('Erasing... done \r', end='', flush=True) finally: print('', flush=True) @@ -312,7 +368,7 @@ def launch_dfu(args, app_shutdown_token): try: for i, (sector, data) in enumerate(touched_sectors): print("Flashing... (sector {}/{}) \r".format(i, len(touched_sectors)), end='', flush=True) - flash(dfudev, sector, data) + dfudev.write_sector(sector, data) print('Flashing... done \r', end='', flush=True) finally: print('', flush=True) @@ -321,7 +377,7 @@ def launch_dfu(args, app_shutdown_token): try: for i, (sector, expected_data) in enumerate(touched_sectors): print("Verifying... (sector {}/{}) \r".format(i, len(touched_sectors)), end='', flush=True) - observed_data = read(dfudev, sector) + observed_data = dfudev.read_sector(sector) mismatch_pos = get_first_mismatch_index(observed_data, expected_data) if not mismatch_pos is None: mismatch_pos -= mismatch_pos % 16 @@ -341,7 +397,47 @@ def launch_dfu(args, app_shutdown_token): # So for debugging you should comment this last part out. # Jump to application - jump_to_application(dfudev, 0x08000000) + dfudev.jump_to_application(0x08000000) + + logger.info("Waiting for the device to reappear...") + device = odrive.discovery.find_any("usb", serial_number, + cancellation_token, cancellation_token, timeout=30) + + if did_backup_config: + odrive.configuration.restore_config(device, None, logger) + os.remove(odrive.configuration.get_temp_config_filename(device)) + + logger.success("Device firmware update successful.") + +def launch_dfu(args, logger, cancellation_token): + """ + Waits for a device that matches args.path and args.serial_number + and then upgrades the device's firmware. + """ + + serial_number = args.serial_number + find_odrive_cancellation_token = Event(cancellation_token) + + logger.info("Waiting for ODrive...") + + devices = [None, None] + + # Start background thread to scan for ODrives in DFU mode + def find_device_in_dfu_mode_thread(): + devices[0] = find_device_in_dfu_mode(serial_number, find_odrive_cancellation_token) + find_odrive_cancellation_token.set() + threading.Thread(target=find_device_in_dfu_mode_thread).start() + + # Scan for ODrives not in DFU mode + # We only scan on USB because DFU is only implemented over USB + devices[1] = odrive.discovery.find_any("usb", serial_number, + find_odrive_cancellation_token, cancellation_token) + find_odrive_cancellation_token.set() + + device = devices[0] or devices[1] + firmware = FirmwareFromFile(args.file) if args.file else None + + update_device(device, firmware, logger, cancellation_token) diff --git a/tools/odrive/dfuse/DfuDevice.py b/tools/odrive/dfuse/DfuDevice.py index b9ca449c..e7158d3b 100644 --- a/tools/odrive/dfuse/DfuDevice.py +++ b/tools/odrive/dfuse/DfuDevice.py @@ -1,5 +1,8 @@ import usb.util import time +import fractions +import array +from odrive.dfuse.DfuState import DfuState DFU_REQUEST_SEND = 0x21 DFU_REQUEST_RECEIVE = 0xa1 @@ -12,6 +15,9 @@ DFU_CLRSTATUS = 0x04 DFU_GETSTATE = 0x05 DFU_ABORT = 0x06 +SIZE_MULTIPLIERS = {' ': 1, 'K': 1024, 'M' : 1024*1024} +MAX_TRANSFER_SIZE = 2048 + # Order is LSB first def address_to_4bytes(a): return [ a % 256, (a >> 8)%256, (a >> 16)%256, (a >> 24)%256 ] @@ -24,6 +30,7 @@ class DfuDevice: self.intf = None #self.dev.reset() self.cfg.set() + self.sectors = list(self.get_device_sectors()) def alternates(self): return [(usb.util.get_string(self.dev, intf.iInterface), intf) for intf in self.cfg] @@ -98,3 +105,115 @@ class DfuDevice: return status + ## High level functions ## + # by ODrive Robotics + + def get_device_sectors(self): + """ + Returns a list of all sectors on the device. + Each sector is represented as a dictionary with the following keys: + - name: name of the associated memory region (e.g. "Internal Flash") + - alt: USB alternate setting associated with this memory region + - addr: Start address of the sector (e.g. 0x08004000 for the second flash sectors) + - baseaddr: Start address of the memory region associated with the sector + (e.g. 0x08000000 for all flash sectors) + - len: Number of bytes in the sector + """ + for name, alt in self.alternates(): + # example for name: + # '@Internal Flash /0x08000000/04*016Kg,01*064Kg,07*128Kg' + label, baseaddr, layout = name.split('/') + baseaddr = int(baseaddr, 0) # convert hex to decimal + addr = baseaddr + + for sector in layout.split(','): + repeat, size = map(int, sector[:-2].split('*')) + size *= SIZE_MULTIPLIERS[sector[-2].upper()] + mode = sector[-1] + + while repeat > 0: + # TODO: verify if the section is writable + yield { + 'name': label.strip().strip('@'), + 'alt': alt, + 'baseaddr': baseaddr, + 'addr': addr, + 'len': size, + 'mode': mode + } + + addr += size + repeat -= 1 + + def set_alternate_safe(self, alt): + self.set_alternate(alt) + if self.get_state() == DfuState.DFU_ERROR: + self.clear_status() + self.wait_while_state(DfuState.DFU_ERROR) + + #def clear_error(self) + def set_address_safe(self, addr): + self.set_address(addr) + status = self.wait_while_state(DfuState.DFU_DOWNLOAD_BUSY) + if status[1] != DfuState.DFU_DOWNLOAD_IDLE: + raise RuntimeError("An error occured. Device Status: %r" % status) + # take device out of DFU_DOWNLOAD_SYNC and into DFU_IDLE + self.abort() + status = self.wait_while_state(DfuState.DFU_DOWNLOAD_SYNC) + if status[1] != DfuState.DFU_IDLE: + raise RuntimeError("An error occured. Device Status: %r" % status) + + + def erase_sector(self, sector): + self.set_alternate_safe(sector['alt']) + self.erase(sector['addr']) + status = self.wait_while_state(DfuState.DFU_DOWNLOAD_BUSY, timeout=sector['len']/32) + if status[1] != DfuState.DFU_DOWNLOAD_IDLE: + raise RuntimeError("An error occured. Device Status: %r" % status) + + def write_sector(self, sector, data): + self.set_alternate_safe(sector['alt']) + self.set_address_safe(sector['addr']) + + transfer_size = fractions.gcd(sector['len'], MAX_TRANSFER_SIZE) + + blocks = [data[i:i + transfer_size] for i in range(0, len(data), transfer_size)] + for blocknum, block in enumerate(blocks): + #print('write to {:08X} ({} bytes)'.format( + # sector['addr'] + blocknum * TRANSFER_SIZE, len(block))) + self.write(blocknum, block) + status = self.wait_while_state(DfuState.DFU_DOWNLOAD_BUSY) + if status[1] != DfuState.DFU_DOWNLOAD_IDLE: + raise RuntimeError("An error occured. Device Status: %r" % status) + + def read_sector(self, sector): + """ + Reads data from the specified sector + Returns: a byte array containing the data + """ + self.set_alternate_safe(sector['alt']) + self.set_address_safe(sector['addr']) + + transfer_size = fractions.gcd(sector['len'], MAX_TRANSFER_SIZE) + #blocknum_offset = int((sector['addr'] - sector['baseaddr']) / transfer_size) + + + data = array.array(u'B') + for blocknum in range(int(sector['len'] / transfer_size)): + #print('read at {:08X}'.format(sector['addr'] + blocknum * TRANSFER_SIZE)) + deviceBlock = self.read(blocknum, transfer_size) + data.extend(deviceBlock) + self.abort() # take device into DFU_IDLE + return data + + def jump_to_application(self, address): + self.set_address_safe(address) + #self.set_address(address) + #status = self.wait_while_state(DfuState.DFU_DOWNLOAD_BUSY) + #if status[1] != DfuState.DFU_DOWNLOAD_IDLE: + # raise RuntimeError("An error occured. Device Status: {}".format(status[1])) + + self.leave() + status = self.wait_while_state(DfuState.DFU_MANIFEST_SYNC) + if status[1] != DfuState.DFU_MANIFEST: + raise RuntimeError("An error occured. Device Status: {}".format(status[1])) diff --git a/tools/odrive/discovery.py b/tools/odrive/discovery.py index 3137f0ae..d05d8f98 100644 --- a/tools/odrive/discovery.py +++ b/tools/odrive/discovery.py @@ -66,7 +66,7 @@ def find_all(path, serial_number, obj.__dict__['_json_data'] = json_data['members'] obj.__dict__['_json_crc'] = json_crc16 - device_serial_number = format(obj.serial_number, 'x').upper() if hasattr(obj, 'serial_number') else "[unknown serial number]" + device_serial_number = odrive.utils.get_serial_number_str(obj) if serial_number != None and device_serial_number != serial_number: printer("Ignoring device with serial number {}".format(device_serial_number)) return diff --git a/tools/odrive/enums.py b/tools/odrive/enums.py index 324a03a9..f5369007 100644 --- a/tools/odrive/enums.py +++ b/tools/odrive/enums.py @@ -27,7 +27,7 @@ MOTOR_TYPE_HIGH_CURRENT = 0 #MOTOR_TYPE_LOW_CURRENT = 1 MOTOR_TYPE_GIMBAL = 2 -CTRL_MODE_VOLTAGE_CONTROL = 0, -CTRL_MODE_CURRENT_CONTROL = 1, -CTRL_MODE_VELOCITY_CONTROL = 2, +CTRL_MODE_VOLTAGE_CONTROL = 0 +CTRL_MODE_CURRENT_CONTROL = 1 +CTRL_MODE_VELOCITY_CONTROL = 2 CTRL_MODE_POSITION_CONTROL = 3 diff --git a/tools/odrive/shell.py b/tools/odrive/shell.py index ef072010..7fc3e5ad 100644 --- a/tools/odrive/shell.py +++ b/tools/odrive/shell.py @@ -52,7 +52,7 @@ def did_discover_device(odrive, logger, app_shutdown_token): # Publish new ODrive to interactive console interactive_variables[interactive_name] = odrive globals()[interactive_name] = odrive # Add to globals so tab complete works - logger.info("{} to ODrive {:012X} as {}".format(verb, serial_number, interactive_name)) + logger.notify("{} to ODrive {:012X} as {}".format(verb, serial_number, interactive_name)) # Subscribe to disappearance of the device odrive.__channel__._channel_broken.subscribe(lambda: did_lose_device(interactive_name, logger, app_shutdown_token)) diff --git a/tools/odrive/usbbulk_transport.py b/tools/odrive/usbbulk_transport.py index eefc33e8..6d7b5cff 100644 --- a/tools/odrive/usbbulk_transport.py +++ b/tools/odrive/usbbulk_transport.py @@ -46,20 +46,30 @@ class USBBulkTransport(odrive.protocol.PacketSource, odrive.protocol.PacketSink) if platform.system() != 'Windows': self.dev.reset() - interface_number = 1 + #self.dev.set_configuration() # no args: set first configuration + + # Find the best interface + self.cfg = self.dev.get_active_configuration() + custom_interfaces = [i for i in self.cfg.interfaces() if i.bInterfaceClass == 0x00 and i.bInterfaceSubClass == 0x01] + cdc_interfaces = [i for i in self.cfg.interfaces() if i.bInterfaceClass == 0x0a and i.bInterfaceSubClass == 0x00] + all_compatible_interfaces = custom_interfaces + cdc_interfaces + if len(all_compatible_interfaces) == 0: + raise Exception("the device has no compatible interfaces") + self.intf = all_compatible_interfaces[0] + + # Try to detach kernel driver from interface + #interface_number = 1 try: - if self.dev.is_kernel_driver_active(interface_number): - self.dev.detach_kernel_driver(interface_number) + if self.dev.is_kernel_driver_active(self.intf.bInterfaceNumber): + self.dev.detach_kernel_driver(self.intf.bInterfaceNumber) self._printer("Detached Kernel Driver") + else: + self._printer("Kernel Driver was not attached") except NotImplementedError: pass #is_kernel_driver_active not implemented on Windows - self.dev.set_configuration() # no args: set first configuration - self.cfg = self.dev.get_active_configuration() - self.intf = self.cfg[(1,0)] # this implicitly claims the interface - # write endpoint + # find write endpoint (first OUT endpoint) self.epw = usb.util.find_descriptor(self.intf, - # match the first OUT endpoint custom_match = \ lambda e: \ usb.util.endpoint_direction(e.bEndpointAddress) == \ @@ -67,9 +77,8 @@ class USBBulkTransport(odrive.protocol.PacketSource, odrive.protocol.PacketSink) ) assert self.epw is not None self._printer("EndpointAddress for writing {}".format(self.epw.bEndpointAddress)) - # read endpoint + # find read endpoint (first IN endpoint) self.epr = usb.util.find_descriptor(self.intf, - # match the first IN endpoint custom_match = \ lambda e: \ usb.util.endpoint_direction(e.bEndpointAddress) == \ @@ -154,15 +163,18 @@ def discover_channels(path, serial_number, callback, cancellation_token, channel known_devices = [] def device_matcher(device): #print(" test {:04X}:{:04X}".format(device.idVendor, device.idProduct)) - if (device.bus, device.address) in known_devices: - return False - if bus != None and device.bus != bus: - return False - if address != None and device.address != address: - return False - if serial_number != None and device.serial_number != serial_number: - return False - if (device.idVendor, device.idProduct) not in ODRIVE_VID_PID_PAIRS: + try: + if (device.bus, device.address) in known_devices: + return False + if bus != None and device.bus != bus: + return False + if address != None and device.address != address: + return False + if serial_number != None and device.serial_number != serial_number: + return False + if (device.idVendor, device.idProduct) not in ODRIVE_VID_PID_PAIRS: + return False + except: return False return True diff --git a/tools/odrive/utils.py b/tools/odrive/utils.py index 050d4110..d73cbba2 100755 --- a/tools/odrive/utils.py +++ b/tools/odrive/utils.py @@ -25,6 +25,9 @@ data_rate = 100 plot_rate = 10 num_samples = 1000 +class OperationAbortedException(Exception): + pass + def start_liveplotter(get_var_callback): """ Starts a liveplotter. @@ -157,6 +160,11 @@ def setup_udev_rules(logger): subprocess.run(["udevadm", "trigger"], check=True) logger.info('udev rules configured successfully') +def get_serial_number_str(device): + if hasattr(device, 'serial_number'): + return format(device.serial_number, 'x').upper() + else: + return "[unknown serial number]" ## Exceptions ## @@ -357,9 +365,30 @@ class Logger(): def success(self, text): self.print_colored(self._prefix + text, Logger.COLOR_GREEN) def info(self, text): + self.print_colored(self._prefix + text, Logger.COLOR_DEFAULT) + def notify(self, text): self.print_colored(self._prefix + text, Logger.COLOR_CYAN) def warn(self, text): self.print_colored(self._prefix + text, Logger.COLOR_YELLOW) def error(self, text): # TODO: write to stderr self.print_colored(self._prefix + text, Logger.COLOR_RED) + +def yes_no_prompt(question, default=None): + if default is None: + question += " [y/n] " + elif default == True: + question += " [Y/n] " + elif default == False: + question += " [y/N] " + + while True: + print(question, end='') + + choice = input().lower() + if choice in {'yes', 'y'}: + return True + elif choice in {'no', 'n'}: + return False + elif choice == '' and default is not None: + return default diff --git a/tools/odrive/version.py b/tools/odrive/version.py index 68bad7d0..b0b43035 100644 --- a/tools/odrive/version.py +++ b/tools/odrive/version.py @@ -4,6 +4,20 @@ import subprocess import os import sys +def version_str_to_tuple(version_string): + """ + Converts a version string to a tuple of the form + (major, minor, revision, prerelease) + + Example: "fw-v0.3.6-23" => (0, 3, 6, True) + """ + regex=r'.*v([0-9a-zA-Z]+).([0-9a-zA-Z]+).([0-9a-zA-Z]+)(.*)' + return (int(re.sub(regex, r"\1", version_string)), + int(re.sub(regex, r"\2", version_string)), + int(re.sub(regex, r"\3", version_string)), + (re.sub(regex, r"\4", version_string) != "")) + + def get_version_from_git(): script_dir = os.path.dirname(os.path.realpath(__file__)) try: @@ -12,19 +26,15 @@ def get_version_from_git(): cwd=script_dir) git_tag = git_tag.decode(sys.stdout.encoding).rstrip('\n') - regex=r'.*v([0-9a-zA-Z]).([0-9a-zA-Z]).([0-9a-zA-Z])(.*)' - package_version_major = int(re.sub(regex, r"\1", git_tag)) - package_version_minor = int(re.sub(regex, r"\2", git_tag)) - package_version_revision = int(re.sub(regex, r"\3", git_tag)) - package_version_unreleased = (re.sub(regex, r"\4", git_tag) != "") + (major, minor, revision, is_prerelease) = version_str_to_tuple(git_tag) - if package_version_unreleased: - package_version_revision += 1 + if is_prerelease: + revision += 1 + return git_tag, major, minor, revision, is_prerelease except Exception as ex: print(ex) return "[unknown version]", 0, 0, 0, 1 - return git_tag, package_version_major, package_version_minor, package_version_revision, package_version_unreleased def get_version_str(git_only=False): """ diff --git a/tools/odrivetool b/tools/odrivetool index 1644acab..2e784dc7 100755 --- a/tools/odrivetool +++ b/tools/odrivetool @@ -8,7 +8,8 @@ import sys import argparse import os import odrive.discovery -from odrive.utils import Logger, Event +from odrive.utils import Logger, Event, OperationAbortedException +from odrive.configuration import * # Flush stdout by default # Source: @@ -35,8 +36,26 @@ shell_parser.add_argument("--no-ipython", action="store_true", "instead of the IPython shell, " "even if IPython is installed.") -dfu_parser = subparsers.add_parser('dfu', help="Upgrade the ODrive device firmware") -dfu_parser.add_argument('file', metavar='HEX', help='The .hex file to be flashed. Make sure your firmware board version matches the actual board version.') +dfu_parser = subparsers.add_parser('dfu', help="Upgrade the ODrive device firmware." + "If no serial number is specified, the first ODrive that is found is updated") +dfu_parser.add_argument('file', metavar='HEX', nargs='?', + help='The .hex file to be flashed. Make sure target board version ' + 'of the firmware file matches the actual board version. ' + 'You can download the latest release manually from ' + 'https://github.com/madcowswe/ODrive/releases. ' + 'If no file is provided, the script automatically downloads ' + 'the latest firmware.') + + +dfu_parser = subparsers.add_parser('backup-config', help="Saves the configuration of the ODrive to a JSON file") +dfu_parser.add_argument('file', nargs='?', + help="Path to the file where to store the data. " + "If no path is provided, the configuration is stored in {}.".format(tempfile.gettempdir())) + +dfu_parser = subparsers.add_parser('restore-config', help="Restores the configuration of the ODrive from a JSON file") +dfu_parser.add_argument('file', nargs='?', + help="Path to the file that contains the configuration data. " + "If no path is provided, the configuration is loaded from {}.".format(tempfile.gettempdir())) code_generator_parser = subparsers.add_parser('generate-code', help="Process a jinja2 template, passing the ODrive's JSON data as data input") code_generator_parser.add_argument("-t", "--template", type=argparse.FileType('r'), @@ -119,12 +138,14 @@ try: elif args.command == 'dfu': print_version() import odrive.dfu - odrive.dfu.launch_dfu(args, app_shutdown_token) + odrive.dfu.launch_dfu(args, logger, app_shutdown_token) elif args.command == 'liveplotter': from odrive.utils import start_liveplotter print("Waiting for ODrive...") - my_odrive = odrive.discovery.find_any(path=args.path, serial_number=args.serial_number) + my_odrive = odrive.discovery.find_any(path=args.path, serial_number=args.serial_number, + search_cancellation_token=app_shutdown_token, + channel_termination_token=app_shutdown_token) # If you want to plot different values, change them here. # You can plot any number of values concurrently. @@ -134,14 +155,18 @@ try: elif args.command == 'drv-status': from odrive.utils import print_drv_regs print("Waiting for ODrive...") - my_odrive = odrive.discovery.find_any(path=args.path, serial_number=args.serial_number) + my_odrive = odrive.discovery.find_any(path=args.path, serial_number=args.serial_number, + search_cancellation_token=app_shutdown_token, + channel_termination_token=app_shutdown_token) print_drv_regs("Motor 0", my_odrive.axis0.motor) print_drv_regs("Motor 1", my_odrive.axis1.motor) elif args.command == 'rate-test': from odrive.utils import rate_test print("Waiting for ODrive...") - my_odrive = odrive.discovery.find_any(path=args.path, serial_number=args.serial_number) + my_odrive = odrive.discovery.find_any(path=args.path, serial_number=args.serial_number, + search_cancellation_token=app_shutdown_token, + channel_termination_token=app_shutdown_token) rate_test(my_odrive) elif args.command == 'udev-setup': @@ -154,8 +179,26 @@ try: channel_termination_token=app_shutdown_token) generate_code(my_odrive, args.template, args.output) + elif args.command == 'backup-config': + from odrive.configuration import backup_config + print("Waiting for ODrive...") + my_odrive = odrive.discovery.find_any(path=args.path, serial_number=args.serial_number, + search_cancellation_token=app_shutdown_token, + channel_termination_token=app_shutdown_token) + backup_config(my_odrive, args.file, logger) + + elif args.command == 'restore-config': + from odrive.configuration import restore_config + print("Waiting for ODrive...") + my_odrive = odrive.discovery.find_any(path=args.path, serial_number=args.serial_number, + search_cancellation_token=app_shutdown_token, + channel_termination_token=app_shutdown_token) + restore_config(my_odrive, args.file, logger) + else: raise Exception("unknown command: " + args.command) +except OperationAbortedException: + logger.info("Operation aborted.") finally: app_shutdown_token.set() diff --git a/tools/run_tests.py b/tools/run_tests.py index 2293c573..3ba2e5ab 100755 --- a/tools/run_tests.py +++ b/tools/run_tests.py @@ -142,7 +142,7 @@ try: if isinstance(test, ODriveTest): def odrv_test_thread(odrv_name): odrv_ctx = odrives_by_name[odrv_name] - logger.info('* running {} on {}...'.format(type(test).__name__, odrv_name)) + logger.notify('* running {} on {}...'.format(type(test).__name__, odrv_name)) try: test.check_preconditions(odrv_ctx, logger.indent(' {}: '.format(odrv_name))) @@ -171,7 +171,7 @@ try: try: if not app_shutdown_token.is_set(): # Run test on this axis - logger.info('* running {} on {}...'.format(type(test).__name__, axis_name)) + logger.notify('* running {} on {}...'.format(type(test).__name__, axis_name)) try: test.check_preconditions(axis_ctx, logger.indent(' {}: '.format(axis_name))) @@ -203,7 +203,7 @@ try: try: if not app_shutdown_token.is_set(): # Run test on this axis - logger.info('* running {} on {}...'.format(type(test).__name__, coupling_name)) + logger.notify('* running {} on {}...'.format(type(test).__name__, coupling_name)) try: test.check_preconditions(coupled_axes[0], coupled_axes[1], logger.indent(' {}: '.format(coupling_name)))