From c076a9f2f679ee796ce5524526001782c7a550c3 Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Fri, 16 Feb 2024 22:58:01 -0800 Subject: [PATCH 01/15] remove pedal fw (#1872) * remove pedal fw * little more * one more * and tests * rest of it * little more * fix linter * more fix --- .github/workflows/test.yaml | 2 +- Jenkinsfile | 7 - README.md | 2 +- SConscript | 3 - board/SConscript | 2 +- board/boards/pedal.h | 93 --------- board/can_definitions.h | 4 +- board/config.h | 2 +- board/drivers/usb.h | 5 - board/drivers/watchdog.h | 6 - board/flasher.h | 160 +-------------- board/pedal/.gitignore | 1 - board/pedal/README.md | 28 --- board/pedal/SConscript | 28 --- board/pedal/flash_can.sh | 8 - board/pedal/main.c | 319 ----------------------------- board/pedal/main_declarations.h | 11 - board/pedal/recover.sh | 11 - board/stm32fx/board.h | 72 +++---- board/stm32fx/interrupt_handlers.h | 50 +++-- board/stm32fx/llbxcan.h | 20 +- board/stm32fx/lldac.h | 16 -- board/stm32fx/llusb.h | 4 - board/stm32fx/peripherals.h | 19 +- board/stm32fx/stm32fx_config.h | 35 +--- python/__init__.py | 7 +- python/constants.py | 9 +- python/spi.py | 17 +- python/utils.py | 12 -- tests/misra/test_misra.sh | 7 +- tests/pedal/enter_canloader.py | 32 --- tests/pedal/test_pedal.py | 58 ------ 32 files changed, 114 insertions(+), 936 deletions(-) delete mode 100644 board/boards/pedal.h delete mode 100644 board/pedal/.gitignore delete mode 100644 board/pedal/README.md delete mode 100644 board/pedal/SConscript delete mode 100755 board/pedal/flash_can.sh delete mode 100644 board/pedal/main.c delete mode 100644 board/pedal/main_declarations.h delete mode 100755 board/pedal/recover.sh delete mode 100644 board/stm32fx/lldac.h delete mode 100644 python/utils.py delete mode 100755 tests/pedal/enter_canloader.py delete mode 100755 tests/pedal/test_pedal.py diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index 8f1c5f0197..968ee3ecf8 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -46,7 +46,7 @@ jobs: run: eval "$BUILD" - name: Test python package installer run: ${{ env.RUN }} "python setup.py install" - - name: Build panda + pedal images and bootstub + - name: Build panda images and bootstub run: ${{ env.RUN }} "scons -j4" - name: Build panda with SPI support run: ${{ env.RUN }} "ENABLE_SPI=1 scons -j4" diff --git a/Jenkinsfile b/Jenkinsfile index bf680d33a3..cbb20d192f 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -132,13 +132,6 @@ pipeline { } /* - stage('pedal tests') { - steps { - script { - docker_run("test pedal", 1, "PEDAL_JUNGLE=058010800f51363038363036 python ./tests/pedal/test_pedal.py") - } - } - } stage('HITL tests') { steps { script { diff --git a/README.md b/README.md index 330a94741f..10e66cf402 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ ![panda tests](https://github.com/commaai/panda/workflows/tests/badge.svg) ![panda drivers](https://github.com/commaai/panda/workflows/drivers/badge.svg) -panda speaks CAN and CAN FD, and it runs on [STM32F205](https://www.st.com/resource/en/reference_manual/rm0033-stm32f205xx-stm32f207xx-stm32f215xx-and-stm32f217xx-advanced-armbased-32bit-mcus-stmicroelectronics.pdf), [STM32F413](https://www.st.com/resource/en/reference_manual/rm0430-stm32f413423-advanced-armbased-32bit-mcus-stmicroelectronics.pdf), and [STM32H725](https://www.st.com/resource/en/reference_manual/rm0468-stm32h723733-stm32h725735-and-stm32h730-value-line-advanced-armbased-32bit-mcus-stmicroelectronics.pdf). +panda speaks CAN and CAN FD, and it runs on [STM32F413](https://www.st.com/resource/en/reference_manual/rm0430-stm32f413423-advanced-armbased-32bit-mcus-stmicroelectronics.pdf) and [STM32H725](https://www.st.com/resource/en/reference_manual/rm0468-stm32h723733-stm32h725735-and-stm32h730-value-line-advanced-armbased-32bit-mcus-stmicroelectronics.pdf). ## Directory structure diff --git a/SConscript b/SConscript index 1a79e3880d..357daba954 100644 --- a/SConscript +++ b/SConscript @@ -180,9 +180,6 @@ with open("board/obj/cert.h", "w") as f: # panda fw SConscript('board/SConscript') -# pedal fw -SConscript('board/pedal/SConscript') - # panda jungle fw SConscript('board/jungle/SConscript') diff --git a/board/SConscript b/board/SConscript index 81f1ef84ae..93fd47b07e 100644 --- a/board/SConscript +++ b/board/SConscript @@ -12,7 +12,7 @@ for project_name, project in build_projects.items(): flags = [ "-DPANDA", ] - if ("ENABLE_SPI" in os.environ or "h7" in project_name) and not project_name.startswith('pedal'): + if ("ENABLE_SPI" in os.environ or "h7" in project_name): flags.append('-DENABLE_SPI') if "H723" in os.environ: diff --git a/board/boards/pedal.h b/board/boards/pedal.h deleted file mode 100644 index c4adaf8664..0000000000 --- a/board/boards/pedal.h +++ /dev/null @@ -1,93 +0,0 @@ -// ///////////// // -// Pedal STM32F2 // -// ///////////// // - -void pedal_enable_can_transceiver(uint8_t transceiver, bool enabled) { - switch (transceiver){ - case 1: - set_gpio_output(GPIOB, 3, !enabled); - break; - default: - print("Invalid CAN transceiver ("); puth(transceiver); print("): enabling failed\n"); - break; - } -} - -void pedal_enable_can_transceivers(bool enabled) { - pedal_enable_can_transceiver(1U, enabled); -} - -void pedal_set_led(uint8_t color, bool enabled) { - switch (color){ - case LED_RED: - set_gpio_output(GPIOB, 10, !enabled); - break; - case LED_GREEN: - set_gpio_output(GPIOB, 11, !enabled); - break; - default: - break; - } -} - -void pedal_set_can_mode(uint8_t mode){ - switch (mode) { - case CAN_MODE_NORMAL: - break; - default: - print("Tried to set unsupported CAN mode: "); puth(mode); print("\n"); - break; - } -} - -bool pedal_check_ignition(void){ - // not supported on pedal - return false; -} - -void pedal_init(void) { - common_init_gpio(); - - // C0, C1: Throttle inputs - set_gpio_mode(GPIOC, 0, MODE_ANALOG); - set_gpio_mode(GPIOC, 1, MODE_ANALOG); - // DAC outputs on A4 and A5 - // apparently they don't need GPIO setup - - // Enable transceiver - pedal_enable_can_transceivers(true); - - // Disable LEDs - pedal_set_led(LED_RED, false); - pedal_set_led(LED_GREEN, false); -} - -const harness_configuration pedal_harness_config = { - .has_harness = false -}; - -const board board_pedal = { - .set_bootkick = unused_set_bootkick, - .harness_config = &pedal_harness_config, - .has_obd = false, - .has_spi = false, - .has_canfd = false, - .has_rtc_battery = false, - .fan_max_rpm = 0U, - .avdd_mV = 3300U, - .fan_stall_recovery = false, - .fan_enable_cooldown_time = 0U, - .init = pedal_init, - .init_bootloader = unused_init_bootloader, - .enable_can_transceiver = pedal_enable_can_transceiver, - .enable_can_transceivers = pedal_enable_can_transceivers, - .set_led = pedal_set_led, - .set_can_mode = pedal_set_can_mode, - .check_ignition = pedal_check_ignition, - .read_voltage_mV = unused_read_voltage, - .read_current_mA = unused_read_current, - .set_fan_enabled = unused_set_fan_enabled, - .set_ir_power = unused_set_ir_power, - .set_siren = unused_set_siren, - .read_som_gpio = unused_read_som_gpio -}; diff --git a/board/can_definitions.h b/board/can_definitions.h index db3d621706..b3631d8071 100644 --- a/board/can_definitions.h +++ b/board/can_definitions.h @@ -8,14 +8,13 @@ const uint8_t PANDA_BUS_CNT = 4U; #define CANPACKET_HEAD_SIZE 6U -#if !defined(STM32F4) && !defined(STM32F2) +#if !defined(STM32F4) #define CANFD #define CANPACKET_DATA_SIZE_MAX 64U #else #define CANPACKET_DATA_SIZE_MAX 8U #endif -#ifndef STM32F2 typedef struct { unsigned char reserved : 1; unsigned char bus : 3; @@ -27,7 +26,6 @@ typedef struct { unsigned char checksum; unsigned char data[CANPACKET_DATA_SIZE_MAX]; } __attribute__((packed, aligned(4))) CANPacket_t; -#endif const unsigned char dlc_to_len[] = {0U, 1U, 2U, 3U, 4U, 5U, 6U, 7U, 8U, 12U, 16U, 20U, 24U, 32U, 48U, 64U}; diff --git a/board/config.h b/board/config.h index fc87bc1c3b..0adcc3e09a 100644 --- a/board/config.h +++ b/board/config.h @@ -36,7 +36,7 @@ // platform includes #ifdef STM32H7 #include "stm32h7/stm32h7_config.h" -#elif defined(STM32F2) || defined(STM32F4) +#elif defined(STM32F4) #include "stm32fx/stm32fx_config.h" #else // TODO: uncomment this, cppcheck complains diff --git a/board/drivers/usb.h b/board/drivers/usb.h index ed74b93287..dec7ba8122 100644 --- a/board/drivers/usb.h +++ b/board/drivers/usb.h @@ -198,13 +198,8 @@ uint16_t string_product_desc[] = { // default serial number when we're not a panda uint16_t string_serial_desc[] = { -#ifdef PEDAL - STRING_DESCRIPTOR_HEADER(5), - 'p', 'e', 'd', 'a', 'l' -#else STRING_DESCRIPTOR_HEADER(4), 'n', 'o', 'n', 'e' -#endif }; // a string containing the default configuration index diff --git a/board/drivers/watchdog.h b/board/drivers/watchdog.h index d0ee32cb2d..89cf01e07e 100644 --- a/board/drivers/watchdog.h +++ b/board/drivers/watchdog.h @@ -1,9 +1,3 @@ -// TODO: why doesn't it define these? -#ifdef STM32F2 -#define IWDG_PR_PR_Msk 0x7U -#define IWDG_RLR_RL_Msk 0xFFFU -#endif - typedef enum { WATCHDOG_50_MS = (400U - 1U), WATCHDOG_500_MS = 4000U, diff --git a/board/flasher.h b/board/flasher.h index eec0ec5d75..52906f9df1 100644 --- a/board/flasher.h +++ b/board/flasher.h @@ -50,23 +50,19 @@ int comms_control_handler(ControlPacket_t *req, uint8_t *resp) { break; // **** 0xc3: fetch MCU UID case 0xc3: - #ifdef UID_BASE - (void)memcpy(resp, ((uint8_t *)UID_BASE), 12); - resp_len = 12; - #endif + (void)memcpy(resp, ((uint8_t *)UID_BASE), 12); + resp_len = 12; break; // **** 0xd0: fetch serial number case 0xd0: - #ifndef STM32F2 - // addresses are OTP - if (req->param1 == 1) { - memcpy(resp, (void *)DEVICE_SERIAL_NUMBER_ADDRESS, 0x10); - resp_len = 0x10; - } else { - get_provision_chunk(resp); - resp_len = PROVISION_CHUNK_LEN; - } - #endif + // addresses are OTP + if (req->param1 == 1) { + memcpy(resp, (void *)DEVICE_SERIAL_NUMBER_ADDRESS, 0x10); + resp_len = 0x10; + } else { + get_provision_chunk(resp); + resp_len = PROVISION_CHUNK_LEN; + } break; // **** 0xd1: enter bootloader mode case 0xd1: @@ -147,149 +143,13 @@ int spi_cb_rx(uint8_t *data, int len, uint8_t *data_out) { return resp_len; } -#ifdef PEDAL - -#include "stm32fx/llbxcan.h" -#define CANx CAN1 - -#define CAN_BL_INPUT 0x1 -#define CAN_BL_OUTPUT 0x2 - -void CAN1_TX_IRQ_Handler(void) { - // clear interrupt - CANx->TSR |= CAN_TSR_RQCP0; -} - -#define ISOTP_BUF_SIZE 0x110 - -uint8_t isotp_buf[ISOTP_BUF_SIZE]; -uint8_t *isotp_buf_ptr = NULL; -int isotp_buf_remain = 0; - -uint8_t isotp_buf_out[ISOTP_BUF_SIZE]; -uint8_t *isotp_buf_out_ptr = NULL; -int isotp_buf_out_remain = 0; -int isotp_buf_out_idx = 0; - -void bl_can_send(uint8_t *odat) { - // wait for send - while (!(CANx->TSR & CAN_TSR_TME0)); - - // send continue - CANx->sTxMailBox[0].TDLR = ((uint32_t*)odat)[0]; - CANx->sTxMailBox[0].TDHR = ((uint32_t*)odat)[1]; - CANx->sTxMailBox[0].TDTR = 8; - CANx->sTxMailBox[0].TIR = (CAN_BL_OUTPUT << 21) | 1; -} - -void CAN1_RX0_IRQ_Handler(void) { - while (CANx->RF0R & CAN_RF0R_FMP0) { - if ((CANx->sFIFOMailBox[0].RIR>>21) == CAN_BL_INPUT) { - uint8_t dat[8]; - for (int i = 0; i < 8; i++) { - dat[i] = GET_MAILBOX_BYTE(&CANx->sFIFOMailBox[0], i); - } - uint8_t odat[8]; - uint8_t type = dat[0] & 0xF0; - if (type == 0x30) { - // continue - while (isotp_buf_out_remain > 0) { - // wait for send - while (!(CANx->TSR & CAN_TSR_TME0)); - - odat[0] = 0x20 | isotp_buf_out_idx; - memcpy(odat+1, isotp_buf_out_ptr, 7); - isotp_buf_out_remain -= 7; - isotp_buf_out_ptr += 7; - isotp_buf_out_idx++; - - bl_can_send(odat); - } - } else if (type == 0x20) { - if (isotp_buf_remain > 0) { - memcpy(isotp_buf_ptr, dat+1, 7); - isotp_buf_ptr += 7; - isotp_buf_remain -= 7; - } - if (isotp_buf_remain <= 0) { - int len = isotp_buf_ptr - isotp_buf + isotp_buf_remain; - - // call the function - memset(isotp_buf_out, 0, ISOTP_BUF_SIZE); - isotp_buf_out_remain = spi_cb_rx(isotp_buf, len, isotp_buf_out); - isotp_buf_out_ptr = isotp_buf_out; - isotp_buf_out_idx = 0; - - // send initial - if (isotp_buf_out_remain <= 7) { - odat[0] = isotp_buf_out_remain; - memcpy(odat+1, isotp_buf_out_ptr, isotp_buf_out_remain); - } else { - odat[0] = 0x10 | (isotp_buf_out_remain>>8); - odat[1] = isotp_buf_out_remain & 0xFF; - memcpy(odat+2, isotp_buf_out_ptr, 6); - isotp_buf_out_remain -= 6; - isotp_buf_out_ptr += 6; - isotp_buf_out_idx++; - } - - bl_can_send(odat); - } - } else if (type == 0x10) { - int len = ((dat[0]&0xF)<<8) | dat[1]; - - // setup buffer - isotp_buf_ptr = isotp_buf; - memcpy(isotp_buf_ptr, dat+2, 6); - - if (len < (ISOTP_BUF_SIZE-0x10)) { - isotp_buf_ptr += 6; - isotp_buf_remain = len-6; - } - - memset(odat, 0, 8); - odat[0] = 0x30; - bl_can_send(odat); - } - } - // next - CANx->RF0R |= CAN_RF0R_RFOM0; - } -} - -void CAN1_SCE_IRQ_Handler(void) { - llcan_clear_send(CANx); -} - -#endif - void soft_flasher_start(void) { - #ifdef PEDAL - REGISTER_INTERRUPT(CAN1_TX_IRQn, CAN1_TX_IRQ_Handler, CAN_INTERRUPT_RATE, FAULT_INTERRUPT_RATE_CAN_1) - REGISTER_INTERRUPT(CAN1_RX0_IRQn, CAN1_RX0_IRQ_Handler, CAN_INTERRUPT_RATE, FAULT_INTERRUPT_RATE_CAN_1) - REGISTER_INTERRUPT(CAN1_SCE_IRQn, CAN1_SCE_IRQ_Handler, CAN_INTERRUPT_RATE, FAULT_INTERRUPT_RATE_CAN_1) - #endif - print("\n\n\n************************ FLASHER START ************************\n"); enter_bootloader_mode = 0; flasher_peripherals_init(); -// pedal has the canloader -#ifdef PEDAL - RCC->APB1ENR |= RCC_APB1ENR_CAN1EN; - - // B8,B9: CAN 1 - set_gpio_alternate(GPIOB, 8, GPIO_AF9_CAN1); - set_gpio_alternate(GPIOB, 9, GPIO_AF9_CAN1); - current_board->enable_can_transceiver(1, true); - - // init can - llcan_set_speed(CANx, 5000, false, false); - llcan_init(CANx); -#endif - gpio_usart2_init(); gpio_usb_init(); diff --git a/board/pedal/.gitignore b/board/pedal/.gitignore deleted file mode 100644 index 94053f2925..0000000000 --- a/board/pedal/.gitignore +++ /dev/null @@ -1 +0,0 @@ -obj/* diff --git a/board/pedal/README.md b/board/pedal/README.md deleted file mode 100644 index 9e004d6bd8..0000000000 --- a/board/pedal/README.md +++ /dev/null @@ -1,28 +0,0 @@ -# pedal - -This is the firmware for the comma pedal. - -The comma pedal is a gas pedal interceptor for Honda/Acura and Toyota/Lexus. It allows you to "virtually" press the pedal and borrows a lot from panda. - -== Test Plan == - -* Startup -** Confirm STATE_FAULT_STARTUP -* Timeout -** Send value -** Confirm value is output -** Stop sending messages -** Confirm value is passthru after 100ms -** Confirm STATE_FAULT_TIMEOUT -* Random values -** Send random 6 byte messages -** Confirm random values cause passthru -** Confirm STATE_FAULT_BAD_CHECKSUM -* Same message lockout -** Send same message repeated -** Confirm timeout behavior -* Don't set enable -** Confirm no output -* Set enable and values -** Confirm output - diff --git a/board/pedal/SConscript b/board/pedal/SConscript deleted file mode 100644 index bfa3c2c19d..0000000000 --- a/board/pedal/SConscript +++ /dev/null @@ -1,28 +0,0 @@ -import copy - -Import('build_project') - -build_projects = {} - -build_projects["pedal"] = { - "MAIN": "main.c", - "BOOTSTUB": "../bootstub.c", - "STARTUP_FILE": "../stm32fx/startup_stm32f205xx.s", - "LINKER_SCRIPT": "../stm32fx/stm32f2_flash.ld", - "APP_START_ADDRESS": "0x8004000", - "PROJECT_FLAGS": [ - "-mcpu=cortex-m3", - "-msoft-float", - "-DSTM32F2", - "-DSTM32F205xx", - "-O2", - "-DPEDAL", - ], -} - -# build with the USB driver enabled -build_projects["pedal_usb"] = copy.deepcopy(build_projects["pedal"]) -build_projects["pedal_usb"]["PROJECT_FLAGS"].append("-DPEDAL_USB") - -for project_name, project in build_projects.items(): - build_project(project_name, project, []) diff --git a/board/pedal/flash_can.sh b/board/pedal/flash_can.sh deleted file mode 100755 index b9edf25f12..0000000000 --- a/board/pedal/flash_can.sh +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env sh -set -e - -cd .. -scons -u -j$(nproc) -cd pedal - -../../tests/pedal/enter_canloader.py obj/pedal.bin.signed diff --git a/board/pedal/main.c b/board/pedal/main.c deleted file mode 100644 index b738a95980..0000000000 --- a/board/pedal/main.c +++ /dev/null @@ -1,319 +0,0 @@ -// ********************* Includes ********************* -//#define PEDAL_USB -#include "../config.h" - -#include "early_init.h" -#include "crc.h" - -#define CAN CAN1 - -#ifdef PEDAL_USB - #include "drivers/usb.h" -#else - // no serial either - void print(const char *a) { - UNUSED(a); - } - void puth(unsigned int i) { - UNUSED(i); - } - void puth2(unsigned int i) { - UNUSED(i); - } -#endif - -#define ENTER_BOOTLOADER_MAGIC 0xdeadbeefU -uint32_t enter_bootloader_mode; - -// cppcheck-suppress unusedFunction ; used in headers not included in cppcheck -void __initialize_hardware_early(void) { - early_initialization(); -} - -// ********************* serial debugging ********************* - -#ifdef PEDAL_USB - -void debug_ring_callback(uart_ring *ring) { - char rcv; - while (get_char(ring, &rcv) != 0) { - (void)put_char(ring, rcv); - } -} - -int comms_can_read(uint8_t *data, uint32_t max_len) { - UNUSED(data); - UNUSED(max_len); - return 0; -} -void comms_can_write(const uint8_t *data, uint32_t len) { - UNUSED(data); - UNUSED(len); -} -void comms_endpoint2_write(const uint8_t *data, uint32_t len) { - UNUSED(data); - UNUSED(len); -} -void refresh_can_tx_slots_available(void) {} - -int comms_control_handler(ControlPacket_t *req, uint8_t *resp) { - unsigned int resp_len = 0; - uart_ring *ur = NULL; - switch (req->request) { - // **** 0xc1: get hardware type - case 0xc1: - resp[0] = hw_type; - resp_len = 1; - break; - // **** 0xe0: uart read - case 0xe0: - ur = get_ring_by_number(req->param1); - if (!ur) { - break; - } - // read - while ((resp_len < MIN(req->length, USBPACKET_MAX_SIZE)) && - get_char(ur, (char*)&resp[resp_len])) { - ++resp_len; - } - break; - default: - print("NO HANDLER "); - puth(req->request); - print("\n"); - break; - } - return resp_len; -} - -#endif - -// ***************************** can port ***************************** - -// addresses to be used on CAN -#define CAN_GAS_INPUT 0x200 -#define CAN_GAS_OUTPUT 0x201UL -#define CAN_GAS_SIZE 6 -#define COUNTER_CYCLE 0xFU - -void CAN1_TX_IRQ_Handler(void) { - // clear interrupt - CAN->TSR |= CAN_TSR_RQCP0; -} - -// two independent values -uint16_t gas_set_0 = 0; -uint16_t gas_set_1 = 0; - -#define MAX_TIMEOUT 10U -uint32_t timeout = 0; -uint32_t current_index = 0; - -#define NO_FAULT 0U -#define FAULT_BAD_CHECKSUM 1U -#define FAULT_SEND 2U -#define FAULT_SCE 3U -#define FAULT_STARTUP 4U -#define FAULT_TIMEOUT 5U -#define FAULT_INVALID 6U -uint8_t state = FAULT_STARTUP; -const uint8_t crc_poly = 0xD5U; // standard crc8 - -void CAN1_RX0_IRQ_Handler(void) { - while ((CAN->RF0R & CAN_RF0R_FMP0) != 0) { - #ifdef DEBUG - print("CAN RX\n"); - #endif - int address = CAN->sFIFOMailBox[0].RIR >> 21; - if (address == CAN_GAS_INPUT) { - // softloader entry - if (GET_MAILBOX_BYTES_04(&CAN->sFIFOMailBox[0]) == 0xdeadfaceU) { - if (GET_MAILBOX_BYTES_48(&CAN->sFIFOMailBox[0]) == 0x0ab00b1e) { - enter_bootloader_mode = ENTER_SOFTLOADER_MAGIC; - NVIC_SystemReset(); - } else if (GET_MAILBOX_BYTES_48(&CAN->sFIFOMailBox[0]) == 0x02b00b1e) { - enter_bootloader_mode = ENTER_BOOTLOADER_MAGIC; - NVIC_SystemReset(); - } else { - print("Failed entering Softloader or Bootloader\n"); - } - } - - // normal packet - uint8_t dat[8]; - for (int i=0; i<8; i++) { - dat[i] = GET_MAILBOX_BYTE(&CAN->sFIFOMailBox[0], i); - } - uint16_t value_0 = (dat[0] << 8) | dat[1]; - uint16_t value_1 = (dat[2] << 8) | dat[3]; - bool enable = ((dat[4] >> 7) & 1U) != 0U; - uint8_t index = dat[4] & COUNTER_CYCLE; - if (crc_checksum(dat, CAN_GAS_SIZE - 1, crc_poly) == dat[5]) { - if (((current_index + 1U) & COUNTER_CYCLE) == index) { - #ifdef DEBUG - print("setting gas "); - puth(value_0); - print("\n"); - #endif - if (enable) { - gas_set_0 = value_0; - gas_set_1 = value_1; - } else { - // clear the fault state if values are 0 - if ((value_0 == 0U) && (value_1 == 0U)) { - state = NO_FAULT; - } else { - state = FAULT_INVALID; - } - gas_set_0 = 0; - gas_set_1 = 0; - } - // clear the timeout - timeout = 0; - } - current_index = index; - } else { - // wrong checksum = fault - state = FAULT_BAD_CHECKSUM; - } - } - // next - CAN->RF0R |= CAN_RF0R_RFOM0; - } -} - -void CAN1_SCE_IRQ_Handler(void) { - state = FAULT_SCE; - llcan_clear_send(CAN); -} - -uint32_t pdl0 = 0; -uint32_t pdl1 = 0; -unsigned int pkt_idx = 0; - -int led_value = 0; - -void TIM3_IRQ_Handler(void) { - #ifdef DEBUG - puth(TIM3->CNT); - print(" "); - puth(pdl0); - print(" "); - puth(pdl1); - print("\n"); - #endif - - // check timer for sending the user pedal and clearing the CAN - if ((CAN->TSR & CAN_TSR_TME0) == CAN_TSR_TME0) { - uint8_t dat[8]; - dat[0] = (pdl0 >> 8) & 0xFFU; - dat[1] = (pdl0 >> 0) & 0xFFU; - dat[2] = (pdl1 >> 8) & 0xFFU; - dat[3] = (pdl1 >> 0) & 0xFFU; - dat[4] = ((state & 0xFU) << 4) | pkt_idx; - dat[5] = crc_checksum(dat, CAN_GAS_SIZE - 1, crc_poly); - CAN->sTxMailBox[0].TDLR = dat[0] | (dat[1] << 8) | (dat[2] << 16) | (dat[3] << 24); - CAN->sTxMailBox[0].TDHR = dat[4] | (dat[5] << 8); - CAN->sTxMailBox[0].TDTR = 6; // len of packet is 5 - CAN->sTxMailBox[0].TIR = (CAN_GAS_OUTPUT << 21) | 1U; - ++pkt_idx; - pkt_idx &= COUNTER_CYCLE; - } else { - // old can packet hasn't sent! - state = FAULT_SEND; - #ifdef DEBUG - print("CAN MISS\n"); - #endif - } - - // blink the LED - current_board->set_led(LED_GREEN, led_value); - led_value = !led_value; - - TIM3->SR = 0; - - // up timeout for gas set - if (timeout == MAX_TIMEOUT) { - state = FAULT_TIMEOUT; - } else { - timeout += 1U; - } -} - -// ***************************** main code ***************************** - -#define ADCCHAN_ACCEL0 10 -#define ADCCHAN_ACCEL1 11 - -void pedal(void) { - // read/write - pdl0 = adc_get_raw(ADCCHAN_ACCEL0); - pdl1 = adc_get_raw(ADCCHAN_ACCEL1); - - // write the pedal to the DAC - if (state == NO_FAULT) { - dac_set(0, MAX(gas_set_0, pdl0)); - dac_set(1, MAX(gas_set_1, pdl1)); - } else { - dac_set(0, pdl0); - dac_set(1, pdl1); - } - - watchdog_feed(); -} - -int main(void) { - // Init interrupt table - init_interrupts(true); - - REGISTER_INTERRUPT(CAN1_TX_IRQn, CAN1_TX_IRQ_Handler, CAN_INTERRUPT_RATE, FAULT_INTERRUPT_RATE_CAN_1) - REGISTER_INTERRUPT(CAN1_RX0_IRQn, CAN1_RX0_IRQ_Handler, CAN_INTERRUPT_RATE, FAULT_INTERRUPT_RATE_CAN_1) - REGISTER_INTERRUPT(CAN1_SCE_IRQn, CAN1_SCE_IRQ_Handler, CAN_INTERRUPT_RATE, FAULT_INTERRUPT_RATE_CAN_1) - - // Should run at around 732Hz (see init below) - REGISTER_INTERRUPT(TIM3_IRQn, TIM3_IRQ_Handler, 1000U, FAULT_INTERRUPT_RATE_TIM3) - - disable_interrupts(); - - // init devices - clock_init(); - peripherals_init(); - detect_board_type(); - - // init board - current_board->init(); - -#ifdef PEDAL_USB - // enable USB - usb_init(); -#endif - - // pedal stuff - dac_init(); - adc_init(); - - // init can - bool llcan_speed_set = llcan_set_speed(CAN, 5000, false, false); - if (!llcan_speed_set) { - print("Failed to set llcan speed"); - } - - bool ret = llcan_init(CAN); - UNUSED(ret); - - // 48mhz / 65536 ~= 732 - timer_init(TIM3, 15); - NVIC_EnableIRQ(TIM3_IRQn); - - watchdog_init(WATCHDOG_50_MS); - - print("**** INTERRUPTS ON ****\n"); - enable_interrupts(); - - // main pedal loop - while (1) { - pedal(); - } - - return 0; -} diff --git a/board/pedal/main_declarations.h b/board/pedal/main_declarations.h deleted file mode 100644 index 33e4227357..0000000000 --- a/board/pedal/main_declarations.h +++ /dev/null @@ -1,11 +0,0 @@ -// ******************** Prototypes ******************** -void print(const char *a); -void puth(unsigned int i); -void puth2(unsigned int i); -void puth4(unsigned int i); -typedef struct board board; -typedef struct harness_configuration harness_configuration; - -// ********************* Globals ********************** -uint8_t hw_type = 0; -const board *current_board; diff --git a/board/pedal/recover.sh b/board/pedal/recover.sh deleted file mode 100755 index d7fe0aff5f..0000000000 --- a/board/pedal/recover.sh +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env sh -set -e - -DFU_UTIL="dfu-util" - -cd .. -scons -u -j$(nproc) -cd pedal - -$DFU_UTIL -d 0483:df11 -a 0 -s 0x08004000 -D obj/pedal.bin.signed -$DFU_UTIL -d 0483:df11 -a 0 -s 0x08000000:leave -D obj/bootstub.pedal.bin diff --git a/board/stm32fx/board.h b/board/stm32fx/board.h index 76593a5294..808f773829 100644 --- a/board/stm32fx/board.h +++ b/board/stm32fx/board.h @@ -7,49 +7,35 @@ // ///// Board definition and detection ///// // #include "stm32fx/lladc.h" #include "drivers/harness.h" -#ifdef PANDA - #include "drivers/fan.h" - #include "stm32fx/llfan.h" - #include "stm32fx/llrtc.h" - #include "drivers/rtc.h" - #include "drivers/clock_source.h" - #include "boards/white.h" - #include "boards/grey.h" - #include "boards/black.h" - #include "boards/uno.h" - #include "boards/dos.h" -#else - #include "boards/pedal.h" -#endif +#include "drivers/fan.h" +#include "stm32fx/llfan.h" +#include "stm32fx/llrtc.h" +#include "drivers/rtc.h" +#include "drivers/clock_source.h" +#include "boards/white.h" +#include "boards/grey.h" +#include "boards/black.h" +#include "boards/uno.h" +#include "boards/dos.h" void detect_board_type(void) { - #ifdef PANDA - // SPI lines floating: white (TODO: is this reliable? Not really, we have to enable ESP/GPS to be able to detect this on the UART) - set_gpio_output(GPIOC, 14, 1); - set_gpio_output(GPIOC, 5, 1); - if(!detect_with_pull(GPIOB, 1, PULL_UP) && !detect_with_pull(GPIOB, 7, PULL_UP)){ - hw_type = HW_TYPE_DOS; - current_board = &board_dos; - } else if((detect_with_pull(GPIOA, 4, PULL_DOWN)) || (detect_with_pull(GPIOA, 5, PULL_DOWN)) || (detect_with_pull(GPIOA, 6, PULL_DOWN)) || (detect_with_pull(GPIOA, 7, PULL_DOWN))){ - hw_type = HW_TYPE_WHITE_PANDA; - current_board = &board_white; - } else if(detect_with_pull(GPIOA, 13, PULL_DOWN)) { // Rev AB deprecated, so no pullup means black. In REV C, A13 is pulled up to 5V with a 10K - hw_type = HW_TYPE_GREY_PANDA; - current_board = &board_grey; - } else if(!detect_with_pull(GPIOB, 15, PULL_UP)) { - hw_type = HW_TYPE_UNO; - current_board = &board_uno; - } else { - hw_type = HW_TYPE_BLACK_PANDA; - current_board = &board_black; - } - #else - #ifdef PEDAL - hw_type = HW_TYPE_PEDAL; - current_board = &board_pedal; - #else - hw_type = HW_TYPE_UNKNOWN; - print("Hardware type is UNKNOWN!\n"); - #endif - #endif + // SPI lines floating: white (TODO: is this reliable? Not really, we have to enable ESP/GPS to be able to detect this on the UART) + set_gpio_output(GPIOC, 14, 1); + set_gpio_output(GPIOC, 5, 1); + if(!detect_with_pull(GPIOB, 1, PULL_UP) && !detect_with_pull(GPIOB, 7, PULL_UP)){ + hw_type = HW_TYPE_DOS; + current_board = &board_dos; + } else if((detect_with_pull(GPIOA, 4, PULL_DOWN)) || (detect_with_pull(GPIOA, 5, PULL_DOWN)) || (detect_with_pull(GPIOA, 6, PULL_DOWN)) || (detect_with_pull(GPIOA, 7, PULL_DOWN))){ + hw_type = HW_TYPE_WHITE_PANDA; + current_board = &board_white; + } else if(detect_with_pull(GPIOA, 13, PULL_DOWN)) { // Rev AB deprecated, so no pullup means black. In REV C, A13 is pulled up to 5V with a 10K + hw_type = HW_TYPE_GREY_PANDA; + current_board = &board_grey; + } else if(!detect_with_pull(GPIOB, 15, PULL_UP)) { + hw_type = HW_TYPE_UNO; + current_board = &board_uno; + } else { + hw_type = HW_TYPE_BLACK_PANDA; + current_board = &board_black; + } } diff --git a/board/stm32fx/interrupt_handlers.h b/board/stm32fx/interrupt_handlers.h index 3b40f4ee52..41d7427d71 100644 --- a/board/stm32fx/interrupt_handlers.h +++ b/board/stm32fx/interrupt_handlers.h @@ -1,5 +1,5 @@ // ********************* Bare interrupt handlers ********************* -// Only implemented the STM32F413 interrupts for now, the STM32F203 specific ones do not fall into the scope of SIL2 +// Only implemented the STM32F413 interrupts for now void WWDG_IRQHandler(void) {handle_interrupt(WWDG_IRQn);} void PVD_IRQHandler(void) {handle_interrupt(PVD_IRQn);} @@ -73,28 +73,26 @@ void DMA2_Stream7_IRQHandler(void) {handle_interrupt(DMA2_Stream7_IRQn);} void USART6_IRQHandler(void) {handle_interrupt(USART6_IRQn);} void I2C3_EV_IRQHandler(void) {handle_interrupt(I2C3_EV_IRQn);} void I2C3_ER_IRQHandler(void) {handle_interrupt(I2C3_ER_IRQn);} -#ifdef STM32F4 - void DFSDM1_FLT0_IRQHandler(void) {handle_interrupt(DFSDM1_FLT0_IRQn);} - void DFSDM1_FLT1_IRQHandler(void) {handle_interrupt(DFSDM1_FLT1_IRQn);} - void CAN3_TX_IRQHandler(void) {handle_interrupt(CAN3_TX_IRQn);} - void CAN3_RX0_IRQHandler(void) {handle_interrupt(CAN3_RX0_IRQn);} - void CAN3_RX1_IRQHandler(void) {handle_interrupt(CAN3_RX1_IRQn);} - void CAN3_SCE_IRQHandler(void) {handle_interrupt(CAN3_SCE_IRQn);} - void RNG_IRQHandler(void) {handle_interrupt(RNG_IRQn);} - void FPU_IRQHandler(void) {handle_interrupt(FPU_IRQn);} - void UART7_IRQHandler(void) {handle_interrupt(UART7_IRQn);} - void UART8_IRQHandler(void) {handle_interrupt(UART8_IRQn);} - void SPI4_IRQHandler(void) {handle_interrupt(SPI4_IRQn);} - void SPI5_IRQHandler(void) {handle_interrupt(SPI5_IRQn);} - void SAI1_IRQHandler(void) {handle_interrupt(SAI1_IRQn);} - void UART9_IRQHandler(void) {handle_interrupt(UART9_IRQn);} - void UART10_IRQHandler(void) {handle_interrupt(UART10_IRQn);} - void QUADSPI_IRQHandler(void) {handle_interrupt(QUADSPI_IRQn);} - void FMPI2C1_EV_IRQHandler(void) {handle_interrupt(FMPI2C1_EV_IRQn);} - void FMPI2C1_ER_IRQHandler(void) {handle_interrupt(FMPI2C1_ER_IRQn);} - void LPTIM1_IRQHandler(void) {handle_interrupt(LPTIM1_IRQn);} - void DFSDM2_FLT0_IRQHandler(void) {handle_interrupt(DFSDM2_FLT0_IRQn);} - void DFSDM2_FLT1_IRQHandler(void) {handle_interrupt(DFSDM2_FLT1_IRQn);} - void DFSDM2_FLT2_IRQHandler(void) {handle_interrupt(DFSDM2_FLT2_IRQn);} - void DFSDM2_FLT3_IRQHandler(void) {handle_interrupt(DFSDM2_FLT3_IRQn);} -#endif +void DFSDM1_FLT0_IRQHandler(void) {handle_interrupt(DFSDM1_FLT0_IRQn);} +void DFSDM1_FLT1_IRQHandler(void) {handle_interrupt(DFSDM1_FLT1_IRQn);} +void CAN3_TX_IRQHandler(void) {handle_interrupt(CAN3_TX_IRQn);} +void CAN3_RX0_IRQHandler(void) {handle_interrupt(CAN3_RX0_IRQn);} +void CAN3_RX1_IRQHandler(void) {handle_interrupt(CAN3_RX1_IRQn);} +void CAN3_SCE_IRQHandler(void) {handle_interrupt(CAN3_SCE_IRQn);} +void RNG_IRQHandler(void) {handle_interrupt(RNG_IRQn);} +void FPU_IRQHandler(void) {handle_interrupt(FPU_IRQn);} +void UART7_IRQHandler(void) {handle_interrupt(UART7_IRQn);} +void UART8_IRQHandler(void) {handle_interrupt(UART8_IRQn);} +void SPI4_IRQHandler(void) {handle_interrupt(SPI4_IRQn);} +void SPI5_IRQHandler(void) {handle_interrupt(SPI5_IRQn);} +void SAI1_IRQHandler(void) {handle_interrupt(SAI1_IRQn);} +void UART9_IRQHandler(void) {handle_interrupt(UART9_IRQn);} +void UART10_IRQHandler(void) {handle_interrupt(UART10_IRQn);} +void QUADSPI_IRQHandler(void) {handle_interrupt(QUADSPI_IRQn);} +void FMPI2C1_EV_IRQHandler(void) {handle_interrupt(FMPI2C1_EV_IRQn);} +void FMPI2C1_ER_IRQHandler(void) {handle_interrupt(FMPI2C1_ER_IRQn);} +void LPTIM1_IRQHandler(void) {handle_interrupt(LPTIM1_IRQn);} +void DFSDM2_FLT0_IRQHandler(void) {handle_interrupt(DFSDM2_FLT0_IRQn);} +void DFSDM2_FLT1_IRQHandler(void) {handle_interrupt(DFSDM2_FLT1_IRQn);} +void DFSDM2_FLT2_IRQHandler(void) {handle_interrupt(DFSDM2_FLT2_IRQn);} +void DFSDM2_FLT3_IRQHandler(void) {handle_interrupt(DFSDM2_FLT3_IRQn);} diff --git a/board/stm32fx/llbxcan.h b/board/stm32fx/llbxcan.h index a6c5936f05..72523cf1bc 100644 --- a/board/stm32fx/llbxcan.h +++ b/board/stm32fx/llbxcan.h @@ -84,12 +84,10 @@ void llcan_irq_disable(const CAN_TypeDef *CANx) { NVIC_DisableIRQ(CAN2_TX_IRQn); NVIC_DisableIRQ(CAN2_RX0_IRQn); NVIC_DisableIRQ(CAN2_SCE_IRQn); - #ifdef CAN3 - } else if (CANx == CAN3) { - NVIC_DisableIRQ(CAN3_TX_IRQn); - NVIC_DisableIRQ(CAN3_RX0_IRQn); - NVIC_DisableIRQ(CAN3_SCE_IRQn); - #endif + } else if (CANx == CAN3) { + NVIC_DisableIRQ(CAN3_TX_IRQn); + NVIC_DisableIRQ(CAN3_RX0_IRQn); + NVIC_DisableIRQ(CAN3_SCE_IRQn); } else { } } @@ -103,12 +101,10 @@ void llcan_irq_enable(const CAN_TypeDef *CANx) { NVIC_EnableIRQ(CAN2_TX_IRQn); NVIC_EnableIRQ(CAN2_RX0_IRQn); NVIC_EnableIRQ(CAN2_SCE_IRQn); - #ifdef CAN3 - } else if (CANx == CAN3) { - NVIC_EnableIRQ(CAN3_TX_IRQn); - NVIC_EnableIRQ(CAN3_RX0_IRQn); - NVIC_EnableIRQ(CAN3_SCE_IRQn); - #endif + } else if (CANx == CAN3) { + NVIC_EnableIRQ(CAN3_TX_IRQn); + NVIC_EnableIRQ(CAN3_RX0_IRQn); + NVIC_EnableIRQ(CAN3_SCE_IRQn); } else { } } diff --git a/board/stm32fx/lldac.h b/board/stm32fx/lldac.h deleted file mode 100644 index 6cd2f8ca2c..0000000000 --- a/board/stm32fx/lldac.h +++ /dev/null @@ -1,16 +0,0 @@ -void dac_init(void) { - // No buffers required since we have an opamp - register_set(&(DAC->DHR12R1), 0U, 0xFFFU); - register_set(&(DAC->DHR12R2), 0U, 0xFFFU); - register_set(&(DAC->CR), DAC_CR_EN1 | DAC_CR_EN2, 0x3FFF3FFFU); -} - -void dac_set(int channel, uint32_t value) { - if (channel == 0) { - register_set(&(DAC->DHR12R1), value, 0xFFFU); - } else if (channel == 1) { - register_set(&(DAC->DHR12R2), value, 0xFFFU); - } else { - print("Failed to set DAC: invalid channel value: 0x"); puth(value); print("\n"); - } -} diff --git a/board/stm32fx/llusb.h b/board/stm32fx/llusb.h index b6eea1dad2..20c980864b 100644 --- a/board/stm32fx/llusb.h +++ b/board/stm32fx/llusb.h @@ -42,7 +42,6 @@ void usb_init(void) { USBx->GUSBCFG |= ((USBD_FS_TRDT_VALUE << 10) & USB_OTG_GUSBCFG_TRDT); // power up the PHY -#ifdef STM32F4 USBx->GCCFG = USB_OTG_GCCFG_PWRDWN; //USBx->GCCFG |= USB_OTG_GCCFG_VBDEN | USB_OTG_GCCFG_SDEN |USB_OTG_GCCFG_PDEN | USB_OTG_GCCFG_DCDEN; @@ -50,9 +49,6 @@ void usb_init(void) { /* B-peripheral session valid override enable*/ USBx->GOTGCTL |= USB_OTG_GOTGCTL_BVALOVAL; USBx->GOTGCTL |= USB_OTG_GOTGCTL_BVALOEN; -#else - USBx->GCCFG = USB_OTG_GCCFG_PWRDWN | USB_OTG_GCCFG_NOVBUSSENS; -#endif // be a device, slowest timings //USBx->GUSBCFG = USB_OTG_GUSBCFG_FDMOD | USB_OTG_GUSBCFG_PHYSEL | USB_OTG_GUSBCFG_TRDT | USB_OTG_GUSBCFG_TOCAL; diff --git a/board/stm32fx/peripherals.h b/board/stm32fx/peripherals.h index 5bdb8a056c..79ac3c6e4c 100644 --- a/board/stm32fx/peripherals.h +++ b/board/stm32fx/peripherals.h @@ -36,14 +36,9 @@ void common_init_gpio(void) { gpio_usb_init(); - // B8,B9: CAN 1 - #ifdef STM32F4 - set_gpio_alternate(GPIOB, 8, GPIO_AF8_CAN1); - set_gpio_alternate(GPIOB, 9, GPIO_AF8_CAN1); - #else - set_gpio_alternate(GPIOB, 8, GPIO_AF9_CAN1); - set_gpio_alternate(GPIOB, 9, GPIO_AF9_CAN1); - #endif + // B8,B9: CAN 1 + set_gpio_alternate(GPIOB, 8, GPIO_AF8_CAN1); + set_gpio_alternate(GPIOB, 9, GPIO_AF8_CAN1); } void flasher_peripherals_init(void) { @@ -71,14 +66,10 @@ void peripherals_init(void) { RCC->AHB2ENR |= RCC_AHB2ENR_OTGFSEN; RCC->APB1ENR |= RCC_APB1ENR_USART2EN; RCC->APB1ENR |= RCC_APB1ENR_USART3EN; - #ifndef PEDAL - RCC->APB1ENR |= RCC_APB1ENR_UART5EN; - #endif + RCC->APB1ENR |= RCC_APB1ENR_UART5EN; RCC->APB1ENR |= RCC_APB1ENR_CAN1EN; RCC->APB1ENR |= RCC_APB1ENR_CAN2EN; - #ifdef CAN3 - RCC->APB1ENR |= RCC_APB1ENR_CAN3EN; - #endif + RCC->APB1ENR |= RCC_APB1ENR_CAN3EN; // Analog RCC->APB2ENR |= RCC_APB2ENR_ADC1EN; diff --git a/board/stm32fx/stm32fx_config.h b/board/stm32fx/stm32fx_config.h index b470119210..8b59da28f0 100644 --- a/board/stm32fx/stm32fx_config.h +++ b/board/stm32fx/stm32fx_config.h @@ -1,12 +1,7 @@ -#ifdef STM32F4 - #include "stm32fx/inc/stm32f4xx.h" - #include "stm32fx/inc/stm32f4xx_hal_gpio_ex.h" - #define MCU_IDCODE 0x463U -#else - #include "stm32fx/inc/stm32f2xx.h" - #include "stm32fx/inc/stm32f2xx_hal_gpio_ex.h" - #define MCU_IDCODE 0x411U -#endif +#include "stm32fx/inc/stm32f4xx.h" +#include "stm32fx/inc/stm32f4xx_hal_gpio_ex.h" +#define MCU_IDCODE 0x463U + // from the linker script #define APP_START_ADDRESS 0x8004000U @@ -42,11 +37,7 @@ #include "comms_definitions.h" #ifndef BOOTSTUB - #ifdef PEDAL - #include "pedal/main_declarations.h" - #else - #include "main_declarations.h" - #endif + #include "main_declarations.h" #else #include "bootstub_declarations.h" #endif @@ -66,12 +57,10 @@ #include "stm32fx/clock.h" #include "drivers/watchdog.h" -#if !defined(PEDAL) || defined(BOOTSTUB) - #include "drivers/spi.h" - #include "stm32fx/llspi.h" -#endif +#include "drivers/spi.h" +#include "stm32fx/llspi.h" -#if !defined(BOOTSTUB) && (!defined(PEDAL) || defined(PEDAL_USB)) +#if !defined(BOOTSTUB) #include "drivers/uart.h" #include "stm32fx/lluart.h" #endif @@ -86,13 +75,7 @@ #include "stm32fx/llbxcan.h" #endif -#if !defined(PEDAL) || defined(PEDAL_USB) || defined(BOOTSTUB) - #include "stm32fx/llusb.h" -#endif - -#ifdef PEDAL - #include "stm32fx/lldac.h" -#endif +#include "stm32fx/llusb.h" void early_gpio_float(void) { RCC->AHB1ENR = RCC_AHB1ENR_GPIOAEN | RCC_AHB1ENR_GPIOBEN | RCC_AHB1ENR_GPIOCEN; diff --git a/python/__init__.py b/python/__init__.py index 08a18c9768..acf6ea4834 100644 --- a/python/__init__.py +++ b/python/__init__.py @@ -175,7 +175,6 @@ class Panda: HEALTH_STRUCT = struct.Struct(" McuType: hw_type = self.get_type() - if hw_type in Panda.F2_DEVICES: - return McuType.F2 - elif hw_type in Panda.F4_DEVICES: + if hw_type in Panda.F4_DEVICES: return McuType.F4 elif hw_type in Panda.H7_DEVICES: return McuType.H7 diff --git a/python/constants.py b/python/constants.py index 8078da3e62..fede52424c 100644 --- a/python/constants.py +++ b/python/constants.py @@ -24,7 +24,11 @@ def sector_address(self, i): # assume bootstub is in sector 0 return self.bootstub_address + sum(self.sector_sizes[:i]) -Fx = ( +F4Config = McuConfig( + "STM32F4", + 0x463, + [0x4000 for _ in range(4)] + [0x10000] + [0x20000 for _ in range(11)], + 16, 0x1FFF7A10, 0x800, 0x1FFF79C0, @@ -33,8 +37,6 @@ def sector_address(self, i): 0x8000000, "bootstub.panda.bin", ) -F2Config = McuConfig("STM32F2", 0x411, [0x4000 for _ in range(4)] + [0x10000] + [0x20000 for _ in range(7)], 12, *Fx) -F4Config = McuConfig("STM32F4", 0x463, [0x4000 for _ in range(4)] + [0x10000] + [0x20000 for _ in range(11)], 16, *Fx) H7Config = McuConfig( "STM32H7", @@ -53,7 +55,6 @@ def sector_address(self, i): @enum.unique class McuType(enum.Enum): - F2 = F2Config F4 = F4Config H7 = H7Config diff --git a/python/spi.py b/python/spi.py index 699431bf0c..48dc84d49e 100644 --- a/python/spi.py +++ b/python/spi.py @@ -13,7 +13,6 @@ from .base import BaseHandle, BaseSTBootloaderHandle, TIMEOUT from .constants import McuType, MCU_TYPE_BY_IDCODE, USBPACKET_MAX_SIZE -from .utils import crc8_pedal try: import spidev @@ -35,6 +34,20 @@ DEV_PATH = "/dev/spidev0.0" +def crc8(data): + crc = 0xFF # standard init value + poly = 0xD5 # standard crc8: x8+x7+x6+x4+x2+1 + size = len(data) + for i in range(size - 1, -1, -1): + crc ^= data[i] + for _ in range(8): + if ((crc & 0x80) != 0): + crc = ((crc << 1) ^ poly) & 0xFF + else: + crc <<= 1 + return crc + + class PandaSpiException(Exception): pass @@ -248,7 +261,7 @@ def _get_version(spi) -> bytes: # get response dat = spi.readbytes(rlen + 1) resp = dat[:-1] - calculated_crc = crc8_pedal(bytes(version_bytes + resp)) + calculated_crc = crc8(bytes(version_bytes + resp)) if calculated_crc != dat[-1]: raise PandaSpiBadChecksum return bytes(resp) diff --git a/python/utils.py b/python/utils.py deleted file mode 100644 index f91da64130..0000000000 --- a/python/utils.py +++ /dev/null @@ -1,12 +0,0 @@ -def crc8_pedal(data): - crc = 0xFF # standard init value - poly = 0xD5 # standard crc8: x8+x7+x6+x4+x2+1 - size = len(data) - for i in range(size - 1, -1, -1): - crc ^= data[i] - for _ in range(8): - if ((crc & 0x80) != 0): - crc = ((crc << 1) ^ poly) & 0xFF - else: - crc <<= 1 - return crc diff --git a/tests/misra/test_misra.sh b/tests/misra/test_misra.sh index cfc53bac40..0798058e64 100755 --- a/tests/misra/test_misra.sh +++ b/tests/misra/test_misra.sh @@ -45,12 +45,9 @@ cppcheck() { } printf "\n${GREEN}** PANDA F4 CODE **${NC}\n" -cppcheck -DCAN3 -DPANDA -DSTM32F4 -UPEDAL -DUID_BASE $PANDA_DIR/board/main.c +cppcheck -DPANDA -DSTM32F4 -DUID_BASE $PANDA_DIR/board/main.c printf "\n${GREEN}** PANDA H7 CODE **${NC}\n" -cppcheck -DCAN3 -DPANDA -DSTM32H7 -UPEDAL -DUID_BASE $PANDA_DIR/board/main.c - -printf "\n${GREEN}** PEDAL CODE **${NC}\n" -cppcheck -UCAN3 -UPANDA -DSTM32F2 -DPEDAL -UUID_BASE $PANDA_DIR/board/pedal/main.c +cppcheck -DPANDA -DSTM32H7 -DUID_BASE $PANDA_DIR/board/main.c printf "\n${GREEN}Success!${NC} took $SECONDS seconds\n" diff --git a/tests/pedal/enter_canloader.py b/tests/pedal/enter_canloader.py deleted file mode 100755 index 7465c0a072..0000000000 --- a/tests/pedal/enter_canloader.py +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env python3 -import time -import argparse -from panda import Panda, CanHandle, McuType - - -if __name__ == "__main__": - parser = argparse.ArgumentParser(description='Flash pedal over can') - parser.add_argument('--recover', action='store_true') - parser.add_argument("fn", type=str, nargs='?', help="flash file") - args = parser.parse_args() - - p = Panda() - p.set_safety_mode(Panda.SAFETY_ALLOUTPUT) - - while 1: - if len(p.can_recv()) == 0: - break - - if args.recover: - p.can_send(0x200, b"\xce\xfa\xad\xde\x1e\x0b\xb0\x02", 0) - exit(0) - else: - p.can_send(0x200, b"\xce\xfa\xad\xde\x1e\x0b\xb0\x0a", 0) - - if args.fn: - time.sleep(0.1) - print("flashing", args.fn) - code = open(args.fn, "rb").read() - Panda.flash_static(CanHandle(p, 0), code, mcu_type=McuType.F2) - - print("can flash done") diff --git a/tests/pedal/test_pedal.py b/tests/pedal/test_pedal.py deleted file mode 100755 index 0d0676c45a..0000000000 --- a/tests/pedal/test_pedal.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python3 -import os -import time -import unittest - -from panda import Panda, PandaJungle, CanHandle, McuType, BASEDIR - - -JUNGLE_SERIAL = os.getenv("PEDAL_JUNGLE") -PEDAL_BUS = 1 - -class TestPedal(unittest.TestCase): - - def setUp(self): - self.jungle = PandaJungle(JUNGLE_SERIAL) - self.jungle.set_panda_power(True) - self.jungle.set_ignition(False) - - def tearDown(self): - self.jungle.close() - - def _flash_over_can(self, bus, fw_file): - print(f"Flashing {fw_file}") - while len(self.jungle.can_recv()) != 0: - continue - self.jungle.can_send(0x200, b"\xce\xfa\xad\xde\x1e\x0b\xb0\x0a", bus) - - time.sleep(0.1) - with open(fw_file, "rb") as code: - PandaJungle.flash_static(CanHandle(self.jungle, bus), code.read(), McuType.F2) - - def _listen_can_frames(self): - self.jungle.can_clear(0xFFFF) - msgs = 0 - for _ in range(10): - incoming = self.jungle.can_recv() - for message in incoming: - address, _, _, bus = message - if address == 0x201 and bus == PEDAL_BUS: - msgs += 1 - time.sleep(0.1) - return msgs - - def test_usb_fw(self): - self._flash_over_can(PEDAL_BUS, f"{BASEDIR}/board/pedal/obj/pedal_usb.bin.signed") - time.sleep(2) - with Panda('pedal') as p: - self.assertTrue(p.get_type() == Panda.HW_TYPE_PEDAL) - self.assertTrue(self._listen_can_frames() > 40) - - def test_nonusb_fw(self): - self._flash_over_can(PEDAL_BUS, f"{BASEDIR}board/pedal/obj/pedal.bin.signed") - time.sleep(2) - self.assertTrue(self._listen_can_frames() > 40) - - -if __name__ == '__main__': - unittest.main() From 7bfba5eff21b41a89ef6a7396a6d5d0bc3fa338b Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Fri, 16 Feb 2024 23:00:45 -0800 Subject: [PATCH 02/15] remove STM32F2 sources (#1873) --- board/stm32fx/inc/stm32f205xx.h | 7668 --------------------- board/stm32fx/inc/stm32f2xx.h | 209 - board/stm32fx/inc/stm32f2xx_hal_def.h | 181 - board/stm32fx/inc/stm32f2xx_hal_gpio_ex.h | 299 - board/stm32fx/inc/system_stm32f2xx.h | 122 - board/stm32fx/startup_stm32f205xx.s | 511 -- board/stm32fx/stm32f2_flash.ld | 165 - 7 files changed, 9155 deletions(-) delete mode 100644 board/stm32fx/inc/stm32f205xx.h delete mode 100644 board/stm32fx/inc/stm32f2xx.h delete mode 100644 board/stm32fx/inc/stm32f2xx_hal_def.h delete mode 100644 board/stm32fx/inc/stm32f2xx_hal_gpio_ex.h delete mode 100644 board/stm32fx/inc/system_stm32f2xx.h delete mode 100644 board/stm32fx/startup_stm32f205xx.s delete mode 100644 board/stm32fx/stm32f2_flash.ld diff --git a/board/stm32fx/inc/stm32f205xx.h b/board/stm32fx/inc/stm32f205xx.h deleted file mode 100644 index 368bcf39e8..0000000000 --- a/board/stm32fx/inc/stm32f205xx.h +++ /dev/null @@ -1,7668 +0,0 @@ -/** - ****************************************************************************** - * @file stm32f205xx.h - * @author MCD Application Team - * @version V2.1.2 - * @date 29-June-2016 - * @brief CMSIS STM32F205xx Device Peripheral Access Layer Header File. - * This file contains : - * - Data structures and the address mapping for all peripherals - * - Peripherals registers declarations and bits definition - * - Macros to access peripheral's registers hardware - * - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2016 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ - -/** @addtogroup CMSIS - * @{ - */ - -/** @addtogroup stm32f205xx - * @{ - */ - -#ifndef __STM32F205xx_H -#define __STM32F205xx_H - -#ifdef __cplusplus - extern "C" { -#endif /* __cplusplus */ - - -/** @addtogroup Configuration_section_for_CMSIS - * @{ - */ - -/** - * @brief Configuration of the Cortex-M3 Processor and Core Peripherals - */ -#define __CM3_REV 0x0200U /*!< Core revision r0p1 */ -#define __MPU_PRESENT 1U /*!< STM32F2XX provides an MPU */ -#define __NVIC_PRIO_BITS 4U /*!< STM32F2XX uses 4 Bits for the Priority Levels */ -#define __Vendor_SysTickConfig 0U /*!< Set to 1 if different SysTick Config is used */ - -/** - * @} - */ - -/** @addtogroup Peripheral_interrupt_number_definition - * @{ - */ - -/** - * @brief STM32F2XX Interrupt Number Definition, according to the selected device - * in @ref Library_configuration_section - */ -typedef enum -{ -/****** Cortex-M3 Processor Exceptions Numbers ****************************************************************/ - NonMaskableInt_IRQn = -14, /*!< 2 Non Maskable Interrupt */ - MemoryManagement_IRQn = -12, /*!< 4 Cortex-M3 Memory Management Interrupt */ - BusFault_IRQn = -11, /*!< 5 Cortex-M3 Bus Fault Interrupt */ - UsageFault_IRQn = -10, /*!< 6 Cortex-M3 Usage Fault Interrupt */ - SVCall_IRQn = -5, /*!< 11 Cortex-M3 SV Call Interrupt */ - DebugMonitor_IRQn = -4, /*!< 12 Cortex-M3 Debug Monitor Interrupt */ - PendSV_IRQn = -2, /*!< 14 Cortex-M3 Pend SV Interrupt */ - SysTick_IRQn = -1, /*!< 15 Cortex-M3 System Tick Interrupt */ -/****** STM32 specific Interrupt Numbers **********************************************************************/ - WWDG_IRQn = 0, /*!< Window WatchDog Interrupt */ - PVD_IRQn = 1, /*!< PVD through EXTI Line detection Interrupt */ - TAMP_STAMP_IRQn = 2, /*!< Tamper and TimeStamp interrupts through the EXTI line */ - RTC_WKUP_IRQn = 3, /*!< RTC Wakeup interrupt through the EXTI line */ - FLASH_IRQn = 4, /*!< FLASH global Interrupt */ - RCC_IRQn = 5, /*!< RCC global Interrupt */ - EXTI0_IRQn = 6, /*!< EXTI Line0 Interrupt */ - EXTI1_IRQn = 7, /*!< EXTI Line1 Interrupt */ - EXTI2_IRQn = 8, /*!< EXTI Line2 Interrupt */ - EXTI3_IRQn = 9, /*!< EXTI Line3 Interrupt */ - EXTI4_IRQn = 10, /*!< EXTI Line4 Interrupt */ - DMA1_Stream0_IRQn = 11, /*!< DMA1 Stream 0 global Interrupt */ - DMA1_Stream1_IRQn = 12, /*!< DMA1 Stream 1 global Interrupt */ - DMA1_Stream2_IRQn = 13, /*!< DMA1 Stream 2 global Interrupt */ - DMA1_Stream3_IRQn = 14, /*!< DMA1 Stream 3 global Interrupt */ - DMA1_Stream4_IRQn = 15, /*!< DMA1 Stream 4 global Interrupt */ - DMA1_Stream5_IRQn = 16, /*!< DMA1 Stream 5 global Interrupt */ - DMA1_Stream6_IRQn = 17, /*!< DMA1 Stream 6 global Interrupt */ - ADC_IRQn = 18, /*!< ADC1, ADC2 and ADC3 global Interrupts */ - CAN1_TX_IRQn = 19, /*!< CAN1 TX Interrupt */ - CAN1_RX0_IRQn = 20, /*!< CAN1 RX0 Interrupt */ - CAN1_RX1_IRQn = 21, /*!< CAN1 RX1 Interrupt */ - CAN1_SCE_IRQn = 22, /*!< CAN1 SCE Interrupt */ - EXTI9_5_IRQn = 23, /*!< External Line[9:5] Interrupts */ - TIM1_BRK_TIM9_IRQn = 24, /*!< TIM1 Break interrupt and TIM9 global interrupt */ - TIM1_UP_TIM10_IRQn = 25, /*!< TIM1 Update Interrupt and TIM10 global interrupt */ - TIM1_TRG_COM_TIM11_IRQn = 26, /*!< TIM1 Trigger and Commutation Interrupt and TIM11 global interrupt */ - TIM1_CC_IRQn = 27, /*!< TIM1 Capture Compare Interrupt */ - TIM2_IRQn = 28, /*!< TIM2 global Interrupt */ - TIM3_IRQn = 29, /*!< TIM3 global Interrupt */ - TIM4_IRQn = 30, /*!< TIM4 global Interrupt */ - I2C1_EV_IRQn = 31, /*!< I2C1 Event Interrupt */ - I2C1_ER_IRQn = 32, /*!< I2C1 Error Interrupt */ - I2C2_EV_IRQn = 33, /*!< I2C2 Event Interrupt */ - I2C2_ER_IRQn = 34, /*!< I2C2 Error Interrupt */ - SPI1_IRQn = 35, /*!< SPI1 global Interrupt */ - SPI2_IRQn = 36, /*!< SPI2 global Interrupt */ - USART1_IRQn = 37, /*!< USART1 global Interrupt */ - USART2_IRQn = 38, /*!< USART2 global Interrupt */ - USART3_IRQn = 39, /*!< USART3 global Interrupt */ - EXTI15_10_IRQn = 40, /*!< External Line[15:10] Interrupts */ - RTC_Alarm_IRQn = 41, /*!< RTC Alarm (A and B) through EXTI Line Interrupt */ - OTG_FS_WKUP_IRQn = 42, /*!< USB OTG FS Wakeup through EXTI line interrupt */ - TIM8_BRK_TIM12_IRQn = 43, /*!< TIM8 Break Interrupt and TIM12 global interrupt */ - TIM8_UP_TIM13_IRQn = 44, /*!< TIM8 Update Interrupt and TIM13 global interrupt */ - TIM8_TRG_COM_TIM14_IRQn = 45, /*!< TIM8 Trigger and Commutation Interrupt and TIM14 global interrupt */ - TIM8_CC_IRQn = 46, /*!< TIM8 Capture Compare Interrupt */ - DMA1_Stream7_IRQn = 47, /*!< DMA1 Stream7 Interrupt */ - FSMC_IRQn = 48, /*!< FSMC global Interrupt */ - SDIO_IRQn = 49, /*!< SDIO global Interrupt */ - TIM5_IRQn = 50, /*!< TIM5 global Interrupt */ - SPI3_IRQn = 51, /*!< SPI3 global Interrupt */ - UART4_IRQn = 52, /*!< UART4 global Interrupt */ - UART5_IRQn = 53, /*!< UART5 global Interrupt */ - TIM6_DAC_IRQn = 54, /*!< TIM6 global and DAC1&2 underrun error interrupts */ - TIM7_IRQn = 55, /*!< TIM7 global interrupt */ - DMA2_Stream0_IRQn = 56, /*!< DMA2 Stream 0 global Interrupt */ - DMA2_Stream1_IRQn = 57, /*!< DMA2 Stream 1 global Interrupt */ - DMA2_Stream2_IRQn = 58, /*!< DMA2 Stream 2 global Interrupt */ - DMA2_Stream3_IRQn = 59, /*!< DMA2 Stream 3 global Interrupt */ - DMA2_Stream4_IRQn = 60, /*!< DMA2 Stream 4 global Interrupt */ - CAN2_TX_IRQn = 63, /*!< CAN2 TX Interrupt */ - CAN2_RX0_IRQn = 64, /*!< CAN2 RX0 Interrupt */ - CAN2_RX1_IRQn = 65, /*!< CAN2 RX1 Interrupt */ - CAN2_SCE_IRQn = 66, /*!< CAN2 SCE Interrupt */ - OTG_FS_IRQn = 67, /*!< USB OTG FS global Interrupt */ - DMA2_Stream5_IRQn = 68, /*!< DMA2 Stream 5 global interrupt */ - DMA2_Stream6_IRQn = 69, /*!< DMA2 Stream 6 global interrupt */ - DMA2_Stream7_IRQn = 70, /*!< DMA2 Stream 7 global interrupt */ - USART6_IRQn = 71, /*!< USART6 global interrupt */ - I2C3_EV_IRQn = 72, /*!< I2C3 event interrupt */ - I2C3_ER_IRQn = 73, /*!< I2C3 error interrupt */ - OTG_HS_EP1_OUT_IRQn = 74, /*!< USB OTG HS End Point 1 Out global interrupt */ - OTG_HS_EP1_IN_IRQn = 75, /*!< USB OTG HS End Point 1 In global interrupt */ - OTG_HS_WKUP_IRQn = 76, /*!< USB OTG HS Wakeup through EXTI interrupt */ - OTG_HS_IRQn = 77, /*!< USB OTG HS global interrupt */ - HASH_RNG_IRQn = 80 /*!< Hash and RNG global interrupt */ -} IRQn_Type; - -/** - * @} - */ - -#include "core_cm3.h" -#include "system_stm32f2xx.h" -#include - -/** @addtogroup Peripheral_registers_structures - * @{ - */ - -/** - * @brief Analog to Digital Converter - */ - -typedef struct -{ - __IO uint32_t SR; /*!< ADC status register, Address offset: 0x00 */ - __IO uint32_t CR1; /*!< ADC control register 1, Address offset: 0x04 */ - __IO uint32_t CR2; /*!< ADC control register 2, Address offset: 0x08 */ - __IO uint32_t SMPR1; /*!< ADC sample time register 1, Address offset: 0x0C */ - __IO uint32_t SMPR2; /*!< ADC sample time register 2, Address offset: 0x10 */ - __IO uint32_t JOFR1; /*!< ADC injected channel data offset register 1, Address offset: 0x14 */ - __IO uint32_t JOFR2; /*!< ADC injected channel data offset register 2, Address offset: 0x18 */ - __IO uint32_t JOFR3; /*!< ADC injected channel data offset register 3, Address offset: 0x1C */ - __IO uint32_t JOFR4; /*!< ADC injected channel data offset register 4, Address offset: 0x20 */ - __IO uint32_t HTR; /*!< ADC watchdog higher threshold register, Address offset: 0x24 */ - __IO uint32_t LTR; /*!< ADC watchdog lower threshold register, Address offset: 0x28 */ - __IO uint32_t SQR1; /*!< ADC regular sequence register 1, Address offset: 0x2C */ - __IO uint32_t SQR2; /*!< ADC regular sequence register 2, Address offset: 0x30 */ - __IO uint32_t SQR3; /*!< ADC regular sequence register 3, Address offset: 0x34 */ - __IO uint32_t JSQR; /*!< ADC injected sequence register, Address offset: 0x38*/ - __IO uint32_t JDR1; /*!< ADC injected data register 1, Address offset: 0x3C */ - __IO uint32_t JDR2; /*!< ADC injected data register 2, Address offset: 0x40 */ - __IO uint32_t JDR3; /*!< ADC injected data register 3, Address offset: 0x44 */ - __IO uint32_t JDR4; /*!< ADC injected data register 4, Address offset: 0x48 */ - __IO uint32_t DR; /*!< ADC regular data register, Address offset: 0x4C */ -} ADC_TypeDef; - -typedef struct -{ - __IO uint32_t CSR; /*!< ADC Common status register, Address offset: ADC1 base address + 0x300 */ - __IO uint32_t CCR; /*!< ADC common control register, Address offset: ADC1 base address + 0x304 */ - __IO uint32_t CDR; /*!< ADC common regular data register for dual - AND triple modes, Address offset: ADC1 base address + 0x308 */ -} ADC_Common_TypeDef; - - -/** - * @brief Controller Area Network TxMailBox - */ - -typedef struct -{ - __IO uint32_t TIR; /*!< CAN TX mailbox identifier register */ - __IO uint32_t TDTR; /*!< CAN mailbox data length control and time stamp register */ - __IO uint32_t TDLR; /*!< CAN mailbox data low register */ - __IO uint32_t TDHR; /*!< CAN mailbox data high register */ -} CAN_TxMailBox_TypeDef; - -/** - * @brief Controller Area Network FIFOMailBox - */ - -typedef struct -{ - __IO uint32_t RIR; /*!< CAN receive FIFO mailbox identifier register */ - __IO uint32_t RDTR; /*!< CAN receive FIFO mailbox data length control and time stamp register */ - __IO uint32_t RDLR; /*!< CAN receive FIFO mailbox data low register */ - __IO uint32_t RDHR; /*!< CAN receive FIFO mailbox data high register */ -} CAN_FIFOMailBox_TypeDef; - -/** - * @brief Controller Area Network FilterRegister - */ - -typedef struct -{ - __IO uint32_t FR1; /*!< CAN Filter bank register 1 */ - __IO uint32_t FR2; /*!< CAN Filter bank register 1 */ -} CAN_FilterRegister_TypeDef; - -/** - * @brief Controller Area Network - */ - -typedef struct -{ - __IO uint32_t MCR; /*!< CAN master control register, Address offset: 0x00 */ - __IO uint32_t MSR; /*!< CAN master status register, Address offset: 0x04 */ - __IO uint32_t TSR; /*!< CAN transmit status register, Address offset: 0x08 */ - __IO uint32_t RF0R; /*!< CAN receive FIFO 0 register, Address offset: 0x0C */ - __IO uint32_t RF1R; /*!< CAN receive FIFO 1 register, Address offset: 0x10 */ - __IO uint32_t IER; /*!< CAN interrupt enable register, Address offset: 0x14 */ - __IO uint32_t ESR; /*!< CAN error status register, Address offset: 0x18 */ - __IO uint32_t BTR; /*!< CAN bit timing register, Address offset: 0x1C */ - uint32_t RESERVED0[88]; /*!< Reserved, 0x020 - 0x17F */ - CAN_TxMailBox_TypeDef sTxMailBox[3]; /*!< CAN Tx MailBox, Address offset: 0x180 - 0x1AC */ - CAN_FIFOMailBox_TypeDef sFIFOMailBox[2]; /*!< CAN FIFO MailBox, Address offset: 0x1B0 - 0x1CC */ - uint32_t RESERVED1[12]; /*!< Reserved, 0x1D0 - 0x1FF */ - __IO uint32_t FMR; /*!< CAN filter master register, Address offset: 0x200 */ - __IO uint32_t FM1R; /*!< CAN filter mode register, Address offset: 0x204 */ - uint32_t RESERVED2; /*!< Reserved, 0x208 */ - __IO uint32_t FS1R; /*!< CAN filter scale register, Address offset: 0x20C */ - uint32_t RESERVED3; /*!< Reserved, 0x210 */ - __IO uint32_t FFA1R; /*!< CAN filter FIFO assignment register, Address offset: 0x214 */ - uint32_t RESERVED4; /*!< Reserved, 0x218 */ - __IO uint32_t FA1R; /*!< CAN filter activation register, Address offset: 0x21C */ - uint32_t RESERVED5[8]; /*!< Reserved, 0x220-0x23F */ - CAN_FilterRegister_TypeDef sFilterRegister[28]; /*!< CAN Filter Register, Address offset: 0x240-0x31C */ -} CAN_TypeDef; - -/** - * @brief CRC calculation unit - */ - -typedef struct -{ - __IO uint32_t DR; /*!< CRC Data register, Address offset: 0x00 */ - __IO uint8_t IDR; /*!< CRC Independent data register, Address offset: 0x04 */ - uint8_t RESERVED0; /*!< Reserved, 0x05 */ - uint16_t RESERVED1; /*!< Reserved, 0x06 */ - __IO uint32_t CR; /*!< CRC Control register, Address offset: 0x08 */ -} CRC_TypeDef; - -/** - * @brief Digital to Analog Converter - */ - -typedef struct -{ - __IO uint32_t CR; /*!< DAC control register, Address offset: 0x00 */ - __IO uint32_t SWTRIGR; /*!< DAC software trigger register, Address offset: 0x04 */ - __IO uint32_t DHR12R1; /*!< DAC channel1 12-bit right-aligned data holding register, Address offset: 0x08 */ - __IO uint32_t DHR12L1; /*!< DAC channel1 12-bit left aligned data holding register, Address offset: 0x0C */ - __IO uint32_t DHR8R1; /*!< DAC channel1 8-bit right aligned data holding register, Address offset: 0x10 */ - __IO uint32_t DHR12R2; /*!< DAC channel2 12-bit right aligned data holding register, Address offset: 0x14 */ - __IO uint32_t DHR12L2; /*!< DAC channel2 12-bit left aligned data holding register, Address offset: 0x18 */ - __IO uint32_t DHR8R2; /*!< DAC channel2 8-bit right-aligned data holding register, Address offset: 0x1C */ - __IO uint32_t DHR12RD; /*!< Dual DAC 12-bit right-aligned data holding register, Address offset: 0x20 */ - __IO uint32_t DHR12LD; /*!< DUAL DAC 12-bit left aligned data holding register, Address offset: 0x24 */ - __IO uint32_t DHR8RD; /*!< DUAL DAC 8-bit right aligned data holding register, Address offset: 0x28 */ - __IO uint32_t DOR1; /*!< DAC channel1 data output register, Address offset: 0x2C */ - __IO uint32_t DOR2; /*!< DAC channel2 data output register, Address offset: 0x30 */ - __IO uint32_t SR; /*!< DAC status register, Address offset: 0x34 */ -} DAC_TypeDef; - -/** - * @brief Debug MCU - */ - -typedef struct -{ - __IO uint32_t IDCODE; /*!< MCU device ID code, Address offset: 0x00 */ - __IO uint32_t CR; /*!< Debug MCU configuration register, Address offset: 0x04 */ - __IO uint32_t APB1FZ; /*!< Debug MCU APB1 freeze register, Address offset: 0x08 */ - __IO uint32_t APB2FZ; /*!< Debug MCU APB2 freeze register, Address offset: 0x0C */ -}DBGMCU_TypeDef; - - -/** - * @brief DMA Controller - */ - -typedef struct -{ - __IO uint32_t CR; /*!< DMA stream x configuration register */ - __IO uint32_t NDTR; /*!< DMA stream x number of data register */ - __IO uint32_t PAR; /*!< DMA stream x peripheral address register */ - __IO uint32_t M0AR; /*!< DMA stream x memory 0 address register */ - __IO uint32_t M1AR; /*!< DMA stream x memory 1 address register */ - __IO uint32_t FCR; /*!< DMA stream x FIFO control register */ -} DMA_Stream_TypeDef; - -typedef struct -{ - __IO uint32_t LISR; /*!< DMA low interrupt status register, Address offset: 0x00 */ - __IO uint32_t HISR; /*!< DMA high interrupt status register, Address offset: 0x04 */ - __IO uint32_t LIFCR; /*!< DMA low interrupt flag clear register, Address offset: 0x08 */ - __IO uint32_t HIFCR; /*!< DMA high interrupt flag clear register, Address offset: 0x0C */ -} DMA_TypeDef; - - -/** - * @brief External Interrupt/Event Controller - */ - -typedef struct -{ - __IO uint32_t IMR; /*!< EXTI Interrupt mask register, Address offset: 0x00 */ - __IO uint32_t EMR; /*!< EXTI Event mask register, Address offset: 0x04 */ - __IO uint32_t RTSR; /*!< EXTI Rising trigger selection register, Address offset: 0x08 */ - __IO uint32_t FTSR; /*!< EXTI Falling trigger selection register, Address offset: 0x0C */ - __IO uint32_t SWIER; /*!< EXTI Software interrupt event register, Address offset: 0x10 */ - __IO uint32_t PR; /*!< EXTI Pending register, Address offset: 0x14 */ -} EXTI_TypeDef; - -/** - * @brief FLASH Registers - */ - -typedef struct -{ - __IO uint32_t ACR; /*!< FLASH access control register, Address offset: 0x00 */ - __IO uint32_t KEYR; /*!< FLASH key register, Address offset: 0x04 */ - __IO uint32_t OPTKEYR; /*!< FLASH option key register, Address offset: 0x08 */ - __IO uint32_t SR; /*!< FLASH status register, Address offset: 0x0C */ - __IO uint32_t CR; /*!< FLASH control register, Address offset: 0x10 */ - __IO uint32_t OPTCR; /*!< FLASH option control register, Address offset: 0x14 */ -} FLASH_TypeDef; - - -/** - * @brief Flexible Static Memory Controller - */ - -typedef struct -{ - __IO uint32_t BTCR[8]; /*!< NOR/PSRAM chip-select control register(BCR) and chip-select timing register(BTR), Address offset: 0x00-1C */ -} FSMC_Bank1_TypeDef; - -/** - * @brief Flexible Static Memory Controller Bank1E - */ - -typedef struct -{ - __IO uint32_t BWTR[7]; /*!< NOR/PSRAM write timing registers, Address offset: 0x104-0x11C */ -} FSMC_Bank1E_TypeDef; - -/** - * @brief Flexible Static Memory Controller Bank2 - */ - -typedef struct -{ - __IO uint32_t PCR2; /*!< NAND Flash control register 2, Address offset: 0x60 */ - __IO uint32_t SR2; /*!< NAND Flash FIFO status and interrupt register 2, Address offset: 0x64 */ - __IO uint32_t PMEM2; /*!< NAND Flash Common memory space timing register 2, Address offset: 0x68 */ - __IO uint32_t PATT2; /*!< NAND Flash Attribute memory space timing register 2, Address offset: 0x6C */ - uint32_t RESERVED0; /*!< Reserved, 0x70 */ - __IO uint32_t ECCR2; /*!< NAND Flash ECC result registers 2, Address offset: 0x74 */ - uint32_t RESERVED1; /*!< Reserved, 0x78 */ - uint32_t RESERVED2; /*!< Reserved, 0x7C */ - __IO uint32_t PCR3; /*!< NAND Flash control register 3, Address offset: 0x80 */ - __IO uint32_t SR3; /*!< NAND Flash FIFO status and interrupt register 3, Address offset: 0x84 */ - __IO uint32_t PMEM3; /*!< NAND Flash Common memory space timing register 3, Address offset: 0x88 */ - __IO uint32_t PATT3; /*!< NAND Flash Attribute memory space timing register 3, Address offset: 0x8C */ - uint32_t RESERVED3; /*!< Reserved, 0x90 */ - __IO uint32_t ECCR3; /*!< NAND Flash ECC result registers 3, Address offset: 0x94 */ -} FSMC_Bank2_3_TypeDef; - -/** - * @brief Flexible Static Memory Controller Bank4 - */ - -typedef struct -{ - __IO uint32_t PCR4; /*!< PC Card control register 4, Address offset: 0xA0 */ - __IO uint32_t SR4; /*!< PC Card FIFO status and interrupt register 4, Address offset: 0xA4 */ - __IO uint32_t PMEM4; /*!< PC Card Common memory space timing register 4, Address offset: 0xA8 */ - __IO uint32_t PATT4; /*!< PC Card Attribute memory space timing register 4, Address offset: 0xAC */ - __IO uint32_t PIO4; /*!< PC Card I/O space timing register 4, Address offset: 0xB0 */ -} FSMC_Bank4_TypeDef; - - -/** - * @brief General Purpose I/O - */ - -typedef struct -{ - __IO uint32_t MODER; /*!< GPIO port mode register, Address offset: 0x00 */ - __IO uint32_t OTYPER; /*!< GPIO port output type register, Address offset: 0x04 */ - __IO uint32_t OSPEEDR; /*!< GPIO port output speed register, Address offset: 0x08 */ - __IO uint32_t PUPDR; /*!< GPIO port pull-up/pull-down register, Address offset: 0x0C */ - __IO uint32_t IDR; /*!< GPIO port input data register, Address offset: 0x10 */ - __IO uint32_t ODR; /*!< GPIO port output data register, Address offset: 0x14 */ - __IO uint32_t BSRR; /*!< GPIO port bit set/reset register, Address offset: 0x18 */ - __IO uint32_t LCKR; /*!< GPIO port configuration lock register, Address offset: 0x1C */ - __IO uint32_t AFR[2]; /*!< GPIO alternate function registers, Address offset: 0x20-0x24 */ -} GPIO_TypeDef; - -/** - * @brief System configuration controller - */ - -typedef struct -{ - __IO uint32_t MEMRMP; /*!< SYSCFG memory remap register, Address offset: 0x00 */ - __IO uint32_t PMC; /*!< SYSCFG peripheral mode configuration register, Address offset: 0x04 */ - __IO uint32_t EXTICR[4]; /*!< SYSCFG external interrupt configuration registers, Address offset: 0x08-0x14 */ - uint32_t RESERVED[2]; /*!< Reserved, 0x18-0x1C */ - __IO uint32_t CMPCR; /*!< SYSCFG Compensation cell control register, Address offset: 0x20 */ -} SYSCFG_TypeDef; - -/** - * @brief Inter-integrated Circuit Interface - */ - -typedef struct -{ - __IO uint32_t CR1; /*!< I2C Control register 1, Address offset: 0x00 */ - __IO uint32_t CR2; /*!< I2C Control register 2, Address offset: 0x04 */ - __IO uint32_t OAR1; /*!< I2C Own address register 1, Address offset: 0x08 */ - __IO uint32_t OAR2; /*!< I2C Own address register 2, Address offset: 0x0C */ - __IO uint32_t DR; /*!< I2C Data register, Address offset: 0x10 */ - __IO uint32_t SR1; /*!< I2C Status register 1, Address offset: 0x14 */ - __IO uint32_t SR2; /*!< I2C Status register 2, Address offset: 0x18 */ - __IO uint32_t CCR; /*!< I2C Clock control register, Address offset: 0x1C */ - __IO uint32_t TRISE; /*!< I2C TRISE register, Address offset: 0x20 */ -} I2C_TypeDef; - -/** - * @brief Independent WATCHDOG - */ - -typedef struct -{ - __IO uint32_t KR; /*!< IWDG Key register, Address offset: 0x00 */ - __IO uint32_t PR; /*!< IWDG Prescaler register, Address offset: 0x04 */ - __IO uint32_t RLR; /*!< IWDG Reload register, Address offset: 0x08 */ - __IO uint32_t SR; /*!< IWDG Status register, Address offset: 0x0C */ -} IWDG_TypeDef; - -/** - * @brief Power Control - */ - -typedef struct -{ - __IO uint32_t CR; /*!< PWR power control register, Address offset: 0x00 */ - __IO uint32_t CSR; /*!< PWR power control/status register, Address offset: 0x04 */ -} PWR_TypeDef; - -/** - * @brief Reset and Clock Control - */ - -typedef struct -{ - __IO uint32_t CR; /*!< RCC clock control register, Address offset: 0x00 */ - __IO uint32_t PLLCFGR; /*!< RCC PLL configuration register, Address offset: 0x04 */ - __IO uint32_t CFGR; /*!< RCC clock configuration register, Address offset: 0x08 */ - __IO uint32_t CIR; /*!< RCC clock interrupt register, Address offset: 0x0C */ - __IO uint32_t AHB1RSTR; /*!< RCC AHB1 peripheral reset register, Address offset: 0x10 */ - __IO uint32_t AHB2RSTR; /*!< RCC AHB2 peripheral reset register, Address offset: 0x14 */ - __IO uint32_t AHB3RSTR; /*!< RCC AHB3 peripheral reset register, Address offset: 0x18 */ - uint32_t RESERVED0; /*!< Reserved, 0x1C */ - __IO uint32_t APB1RSTR; /*!< RCC APB1 peripheral reset register, Address offset: 0x20 */ - __IO uint32_t APB2RSTR; /*!< RCC APB2 peripheral reset register, Address offset: 0x24 */ - uint32_t RESERVED1[2]; /*!< Reserved, 0x28-0x2C */ - __IO uint32_t AHB1ENR; /*!< RCC AHB1 peripheral clock register, Address offset: 0x30 */ - __IO uint32_t AHB2ENR; /*!< RCC AHB2 peripheral clock register, Address offset: 0x34 */ - __IO uint32_t AHB3ENR; /*!< RCC AHB3 peripheral clock register, Address offset: 0x38 */ - uint32_t RESERVED2; /*!< Reserved, 0x3C */ - __IO uint32_t APB1ENR; /*!< RCC APB1 peripheral clock enable register, Address offset: 0x40 */ - __IO uint32_t APB2ENR; /*!< RCC APB2 peripheral clock enable register, Address offset: 0x44 */ - uint32_t RESERVED3[2]; /*!< Reserved, 0x48-0x4C */ - __IO uint32_t AHB1LPENR; /*!< RCC AHB1 peripheral clock enable in low power mode register, Address offset: 0x50 */ - __IO uint32_t AHB2LPENR; /*!< RCC AHB2 peripheral clock enable in low power mode register, Address offset: 0x54 */ - __IO uint32_t AHB3LPENR; /*!< RCC AHB3 peripheral clock enable in low power mode register, Address offset: 0x58 */ - uint32_t RESERVED4; /*!< Reserved, 0x5C */ - __IO uint32_t APB1LPENR; /*!< RCC APB1 peripheral clock enable in low power mode register, Address offset: 0x60 */ - __IO uint32_t APB2LPENR; /*!< RCC APB2 peripheral clock enable in low power mode register, Address offset: 0x64 */ - uint32_t RESERVED5[2]; /*!< Reserved, 0x68-0x6C */ - __IO uint32_t BDCR; /*!< RCC Backup domain control register, Address offset: 0x70 */ - __IO uint32_t CSR; /*!< RCC clock control & status register, Address offset: 0x74 */ - uint32_t RESERVED6[2]; /*!< Reserved, 0x78-0x7C */ - __IO uint32_t SSCGR; /*!< RCC spread spectrum clock generation register, Address offset: 0x80 */ - __IO uint32_t PLLI2SCFGR; /*!< RCC PLLI2S configuration register, Address offset: 0x84 */ - -} RCC_TypeDef; - -/** - * @brief Real-Time Clock - */ - -typedef struct -{ - __IO uint32_t TR; /*!< RTC time register, Address offset: 0x00 */ - __IO uint32_t DR; /*!< RTC date register, Address offset: 0x04 */ - __IO uint32_t CR; /*!< RTC control register, Address offset: 0x08 */ - __IO uint32_t ISR; /*!< RTC initialization and status register, Address offset: 0x0C */ - __IO uint32_t PRER; /*!< RTC prescaler register, Address offset: 0x10 */ - __IO uint32_t WUTR; /*!< RTC wakeup timer register, Address offset: 0x14 */ - __IO uint32_t CALIBR; /*!< RTC calibration register, Address offset: 0x18 */ - __IO uint32_t ALRMAR; /*!< RTC alarm A register, Address offset: 0x1C */ - __IO uint32_t ALRMBR; /*!< RTC alarm B register, Address offset: 0x20 */ - __IO uint32_t WPR; /*!< RTC write protection register, Address offset: 0x24 */ - uint32_t RESERVED1; /*!< Reserved, 0x28 */ - uint32_t RESERVED2; /*!< Reserved, 0x2C */ - __IO uint32_t TSTR; /*!< RTC time stamp time register, Address offset: 0x30 */ - __IO uint32_t TSDR; /*!< RTC time stamp date register, Address offset: 0x34 */ - uint32_t RESERVED3; /*!< Reserved, 0x38 */ - uint32_t RESERVED4; /*!< Reserved, 0x3C */ - __IO uint32_t TAFCR; /*!< RTC tamper and alternate function configuration register, Address offset: 0x40 */ - uint32_t RESERVED5; /*!< Reserved, 0x44 */ - uint32_t RESERVED6; /*!< Reserved, 0x48 */ - uint32_t RESERVED7; /*!< Reserved, 0x4C */ - __IO uint32_t BKP0R; /*!< RTC backup register 1, Address offset: 0x50 */ - __IO uint32_t BKP1R; /*!< RTC backup register 1, Address offset: 0x54 */ - __IO uint32_t BKP2R; /*!< RTC backup register 2, Address offset: 0x58 */ - __IO uint32_t BKP3R; /*!< RTC backup register 3, Address offset: 0x5C */ - __IO uint32_t BKP4R; /*!< RTC backup register 4, Address offset: 0x60 */ - __IO uint32_t BKP5R; /*!< RTC backup register 5, Address offset: 0x64 */ - __IO uint32_t BKP6R; /*!< RTC backup register 6, Address offset: 0x68 */ - __IO uint32_t BKP7R; /*!< RTC backup register 7, Address offset: 0x6C */ - __IO uint32_t BKP8R; /*!< RTC backup register 8, Address offset: 0x70 */ - __IO uint32_t BKP9R; /*!< RTC backup register 9, Address offset: 0x74 */ - __IO uint32_t BKP10R; /*!< RTC backup register 10, Address offset: 0x78 */ - __IO uint32_t BKP11R; /*!< RTC backup register 11, Address offset: 0x7C */ - __IO uint32_t BKP12R; /*!< RTC backup register 12, Address offset: 0x80 */ - __IO uint32_t BKP13R; /*!< RTC backup register 13, Address offset: 0x84 */ - __IO uint32_t BKP14R; /*!< RTC backup register 14, Address offset: 0x88 */ - __IO uint32_t BKP15R; /*!< RTC backup register 15, Address offset: 0x8C */ - __IO uint32_t BKP16R; /*!< RTC backup register 16, Address offset: 0x90 */ - __IO uint32_t BKP17R; /*!< RTC backup register 17, Address offset: 0x94 */ - __IO uint32_t BKP18R; /*!< RTC backup register 18, Address offset: 0x98 */ - __IO uint32_t BKP19R; /*!< RTC backup register 19, Address offset: 0x9C */ -} RTC_TypeDef; - - -/** - * @brief SD host Interface - */ - -typedef struct -{ - __IO uint32_t POWER; /*!< SDIO power control register, Address offset: 0x00 */ - __IO uint32_t CLKCR; /*!< SDI clock control register, Address offset: 0x04 */ - __IO uint32_t ARG; /*!< SDIO argument register, Address offset: 0x08 */ - __IO uint32_t CMD; /*!< SDIO command register, Address offset: 0x0C */ - __IO const uint32_t RESPCMD; /*!< SDIO command response register, Address offset: 0x10 */ - __IO const uint32_t RESP1; /*!< SDIO response 1 register, Address offset: 0x14 */ - __IO const uint32_t RESP2; /*!< SDIO response 2 register, Address offset: 0x18 */ - __IO const uint32_t RESP3; /*!< SDIO response 3 register, Address offset: 0x1C */ - __IO const uint32_t RESP4; /*!< SDIO response 4 register, Address offset: 0x20 */ - __IO uint32_t DTIMER; /*!< SDIO data timer register, Address offset: 0x24 */ - __IO uint32_t DLEN; /*!< SDIO data length register, Address offset: 0x28 */ - __IO uint32_t DCTRL; /*!< SDIO data control register, Address offset: 0x2C */ - __IO const uint32_t DCOUNT; /*!< SDIO data counter register, Address offset: 0x30 */ - __IO const uint32_t STA; /*!< SDIO status register, Address offset: 0x34 */ - __IO uint32_t ICR; /*!< SDIO interrupt clear register, Address offset: 0x38 */ - __IO uint32_t MASK; /*!< SDIO mask register, Address offset: 0x3C */ - uint32_t RESERVED0[2]; /*!< Reserved, 0x40-0x44 */ - __IO const uint32_t FIFOCNT; /*!< SDIO FIFO counter register, Address offset: 0x48 */ - uint32_t RESERVED1[13]; /*!< Reserved, 0x4C-0x7C */ - __IO uint32_t FIFO; /*!< SDIO data FIFO register, Address offset: 0x80 */ -} SDIO_TypeDef; - -/** - * @brief Serial Peripheral Interface - */ - -typedef struct -{ - __IO uint32_t CR1; /*!< SPI control register 1 (not used in I2S mode), Address offset: 0x00 */ - __IO uint32_t CR2; /*!< SPI control register 2, Address offset: 0x04 */ - __IO uint32_t SR; /*!< SPI status register, Address offset: 0x08 */ - __IO uint32_t DR; /*!< SPI data register, Address offset: 0x0C */ - __IO uint32_t CRCPR; /*!< SPI CRC polynomial register (not used in I2S mode), Address offset: 0x10 */ - __IO uint32_t RXCRCR; /*!< SPI RX CRC register (not used in I2S mode), Address offset: 0x14 */ - __IO uint32_t TXCRCR; /*!< SPI TX CRC register (not used in I2S mode), Address offset: 0x18 */ - __IO uint32_t I2SCFGR; /*!< SPI_I2S configuration register, Address offset: 0x1C */ - __IO uint32_t I2SPR; /*!< SPI_I2S prescaler register, Address offset: 0x20 */ -} SPI_TypeDef; - -/** - * @brief TIM - */ - -typedef struct -{ - __IO uint32_t CR1; /*!< TIM control register 1, Address offset: 0x00 */ - __IO uint32_t CR2; /*!< TIM control register 2, Address offset: 0x04 */ - __IO uint32_t SMCR; /*!< TIM slave mode control register, Address offset: 0x08 */ - __IO uint32_t DIER; /*!< TIM DMA/interrupt enable register, Address offset: 0x0C */ - __IO uint32_t SR; /*!< TIM status register, Address offset: 0x10 */ - __IO uint32_t EGR; /*!< TIM event generation register, Address offset: 0x14 */ - __IO uint32_t CCMR1; /*!< TIM capture/compare mode register 1, Address offset: 0x18 */ - __IO uint32_t CCMR2; /*!< TIM capture/compare mode register 2, Address offset: 0x1C */ - __IO uint32_t CCER; /*!< TIM capture/compare enable register, Address offset: 0x20 */ - __IO uint32_t CNT; /*!< TIM counter register, Address offset: 0x24 */ - __IO uint32_t PSC; /*!< TIM prescaler, Address offset: 0x28 */ - __IO uint32_t ARR; /*!< TIM auto-reload register, Address offset: 0x2C */ - __IO uint32_t RCR; /*!< TIM repetition counter register, Address offset: 0x30 */ - __IO uint32_t CCR1; /*!< TIM capture/compare register 1, Address offset: 0x34 */ - __IO uint32_t CCR2; /*!< TIM capture/compare register 2, Address offset: 0x38 */ - __IO uint32_t CCR3; /*!< TIM capture/compare register 3, Address offset: 0x3C */ - __IO uint32_t CCR4; /*!< TIM capture/compare register 4, Address offset: 0x40 */ - __IO uint32_t BDTR; /*!< TIM break and dead-time register, Address offset: 0x44 */ - __IO uint32_t DCR; /*!< TIM DMA control register, Address offset: 0x48 */ - __IO uint32_t DMAR; /*!< TIM DMA address for full transfer, Address offset: 0x4C */ - __IO uint32_t OR; /*!< TIM option register, Address offset: 0x50 */ -} TIM_TypeDef; - -/** - * @brief Universal Synchronous Asynchronous Receiver Transmitter - */ - -typedef struct -{ - __IO uint32_t SR; /*!< USART Status register, Address offset: 0x00 */ - __IO uint32_t DR; /*!< USART Data register, Address offset: 0x04 */ - __IO uint32_t BRR; /*!< USART Baud rate register, Address offset: 0x08 */ - __IO uint32_t CR1; /*!< USART Control register 1, Address offset: 0x0C */ - __IO uint32_t CR2; /*!< USART Control register 2, Address offset: 0x10 */ - __IO uint32_t CR3; /*!< USART Control register 3, Address offset: 0x14 */ - __IO uint32_t GTPR; /*!< USART Guard time and prescaler register, Address offset: 0x18 */ -} USART_TypeDef; - -/** - * @brief Window WATCHDOG - */ - -typedef struct -{ - __IO uint32_t CR; /*!< WWDG Control register, Address offset: 0x00 */ - __IO uint32_t CFR; /*!< WWDG Configuration register, Address offset: 0x04 */ - __IO uint32_t SR; /*!< WWDG Status register, Address offset: 0x08 */ -} WWDG_TypeDef; - - -/** - * @brief RNG - */ - -typedef struct -{ - __IO uint32_t CR; /*!< RNG control register, Address offset: 0x00 */ - __IO uint32_t SR; /*!< RNG status register, Address offset: 0x04 */ - __IO uint32_t DR; /*!< RNG data register, Address offset: 0x08 */ -} RNG_TypeDef; - - - -/** - * @brief __USB_OTG_Core_register - */ -typedef struct -{ - __IO uint32_t GOTGCTL; /*!< USB_OTG Control and Status Register Address offset : 0x00 */ - __IO uint32_t GOTGINT; /*!< USB_OTG Interrupt Register Address offset : 0x04 */ - __IO uint32_t GAHBCFG; /*!< Core AHB Configuration Register Address offset : 0x08 */ - __IO uint32_t GUSBCFG; /*!< Core USB Configuration Register Address offset : 0x0C */ - __IO uint32_t GRSTCTL; /*!< Core Reset Register Address offset : 0x10 */ - __IO uint32_t GINTSTS; /*!< Core Interrupt Register Address offset : 0x14 */ - __IO uint32_t GINTMSK; /*!< Core Interrupt Mask Register Address offset : 0x18 */ - __IO uint32_t GRXSTSR; /*!< Receive Sts Q Read Register Address offset : 0x1C */ - __IO uint32_t GRXSTSP; /*!< Receive Sts Q Read & POP Register Address offset : 0x20 */ - __IO uint32_t GRXFSIZ; /* Receive FIFO Size Register Address offset : 0x24 */ - __IO uint32_t DIEPTXF0_HNPTXFSIZ; /*!< EP0 / Non Periodic Tx FIFO Size Register Address offset : 0x28 */ - __IO uint32_t HNPTXSTS; /*!< Non Periodic Tx FIFO/Queue Sts reg Address offset : 0x2C */ - uint32_t Reserved30[2]; /* Reserved Address offset : 0x30 */ - __IO uint32_t GCCFG; /*!< General Purpose IO Register Address offset : 0x38 */ - __IO uint32_t CID; /*!< User ID Register Address offset : 0x3C */ - uint32_t Reserved40[48]; /*!< Reserved Address offset : 0x40-0xFF */ - __IO uint32_t HPTXFSIZ; /*!< Host Periodic Tx FIFO Size Reg Address offset : 0x100 */ - __IO uint32_t DIEPTXF[0x0F]; /*!< dev Periodic Transmit FIFO */ -} -USB_OTG_GlobalTypeDef; - - - -/** - * @brief __device_Registers - */ -typedef struct -{ - __IO uint32_t DCFG; /*!< dev Configuration Register Address offset : 0x800 */ - __IO uint32_t DCTL; /*!< dev Control Register Address offset : 0x804 */ - __IO uint32_t DSTS; /*!< dev Status Register (RO) Address offset : 0x808 */ - uint32_t Reserved0C; /*!< Reserved Address offset : 0x80C */ - __IO uint32_t DIEPMSK; /* !< dev IN Endpoint Mask Address offset : 0x810 */ - __IO uint32_t DOEPMSK; /*!< dev OUT Endpoint Mask Address offset : 0x814 */ - __IO uint32_t DAINT; /*!< dev All Endpoints Itr Reg Address offset : 0x818 */ - __IO uint32_t DAINTMSK; /*!< dev All Endpoints Itr Mask Address offset : 0x81C */ - uint32_t Reserved20; /*!< Reserved Address offset : 0x820 */ - uint32_t Reserved9; /*!< Reserved Address offset : 0x824 */ - __IO uint32_t DVBUSDIS; /*!< dev VBUS discharge Register Address offset : 0x828 */ - __IO uint32_t DVBUSPULSE; /*!< dev VBUS Pulse Register Address offset : 0x82C */ - __IO uint32_t DTHRCTL; /*!< dev thr Address offset : 0x830 */ - __IO uint32_t DIEPEMPMSK; /*!< dev empty msk Address offset : 0x834 */ - __IO uint32_t DEACHINT; /*!< dedicated EP interrupt Address offset : 0x838 */ - __IO uint32_t DEACHMSK; /*!< dedicated EP msk Address offset : 0x83C */ - uint32_t Reserved40; /*!< dedicated EP mask Address offset : 0x840 */ - __IO uint32_t DINEP1MSK; /*!< dedicated EP mask Address offset : 0x844 */ - uint32_t Reserved44[15]; /*!< Reserved Address offset : 0x844-0x87C */ - __IO uint32_t DOUTEP1MSK; /*!< dedicated EP msk Address offset : 0x884 */ -} -USB_OTG_DeviceTypeDef; - - -/** - * @brief __IN_Endpoint-Specific_Register - */ -typedef struct -{ - __IO uint32_t DIEPCTL; /* dev IN Endpoint Control Reg 900h + (ep_num * 20h) + 00h */ - uint32_t Reserved04; /* Reserved 900h + (ep_num * 20h) + 04h */ - __IO uint32_t DIEPINT; /* dev IN Endpoint Itr Reg 900h + (ep_num * 20h) + 08h */ - uint32_t Reserved0C; /* Reserved 900h + (ep_num * 20h) + 0Ch */ - __IO uint32_t DIEPTSIZ; /* IN Endpoint Txfer Size 900h + (ep_num * 20h) + 10h */ - __IO uint32_t DIEPDMA; /* IN Endpoint DMA Address Reg 900h + (ep_num * 20h) + 14h */ - __IO uint32_t DTXFSTS; /*IN Endpoint Tx FIFO Status Reg 900h + (ep_num * 20h) + 18h */ - uint32_t Reserved18; /* Reserved 900h+(ep_num*20h)+1Ch-900h+ (ep_num * 20h) + 1Ch */ -} -USB_OTG_INEndpointTypeDef; - - -/** - * @brief __OUT_Endpoint-Specific_Registers - */ -typedef struct -{ - __IO uint32_t DOEPCTL; /* dev OUT Endpoint Control Reg B00h + (ep_num * 20h) + 00h*/ - uint32_t Reserved04; /* Reserved B00h + (ep_num * 20h) + 04h*/ - __IO uint32_t DOEPINT; /* dev OUT Endpoint Itr Reg B00h + (ep_num * 20h) + 08h*/ - uint32_t Reserved0C; /* Reserved B00h + (ep_num * 20h) + 0Ch*/ - __IO uint32_t DOEPTSIZ; /* dev OUT Endpoint Txfer Size B00h + (ep_num * 20h) + 10h*/ - __IO uint32_t DOEPDMA; /* dev OUT Endpoint DMA Address B00h + (ep_num * 20h) + 14h*/ - uint32_t Reserved18[2]; /* Reserved B00h + (ep_num * 20h) + 18h - B00h + (ep_num * 20h) + 1Ch*/ -} -USB_OTG_OUTEndpointTypeDef; - - -/** - * @brief __Host_Mode_Register_Structures - */ -typedef struct -{ - __IO uint32_t HCFG; /* Host Configuration Register 400h*/ - __IO uint32_t HFIR; /* Host Frame Interval Register 404h*/ - __IO uint32_t HFNUM; /* Host Frame Nbr/Frame Remaining 408h*/ - uint32_t Reserved40C; /* Reserved 40Ch*/ - __IO uint32_t HPTXSTS; /* Host Periodic Tx FIFO/ Queue Status 410h*/ - __IO uint32_t HAINT; /* Host All Channels Interrupt Register 414h*/ - __IO uint32_t HAINTMSK; /* Host All Channels Interrupt Mask 418h*/ -} -USB_OTG_HostTypeDef; - - -/** - * @brief __Host_Channel_Specific_Registers - */ -typedef struct -{ - __IO uint32_t HCCHAR; - __IO uint32_t HCSPLT; - __IO uint32_t HCINT; - __IO uint32_t HCINTMSK; - __IO uint32_t HCTSIZ; - __IO uint32_t HCDMA; - uint32_t Reserved[2]; -} -USB_OTG_HostChannelTypeDef; - - -/** - * @brief Peripheral_memory_map - */ -#define FLASH_BASE 0x08000000U /*!< FLASH(up to 1 MB) base address in the alias region */ -#define SRAM1_BASE 0x20000000U /*!< SRAM1(112 KB) base address in the alias region */ -#define SRAM2_BASE 0x2001C000U /*!< SRAM2(16 KB) base address in the alias region */ -#define PERIPH_BASE 0x40000000U /*!< Peripheral base address in the alias region */ -#define BKPSRAM_BASE 0x40024000U /*!< Backup SRAM(4 KB) base address in the alias region */ -#define FSMC_R_BASE 0xA0000000U /*!< FSMC registers base address */ -#define SRAM1_BB_BASE 0x22000000U /*!< SRAM1(112 KB) base address in the bit-band region */ -#define SRAM2_BB_BASE 0x22380000U /*!< SRAM2(16 KB) base address in the bit-band region */ -#define PERIPH_BB_BASE 0x42000000U /*!< Peripheral base address in the bit-band region */ -#define BKPSRAM_BB_BASE 0x42480000U /*!< Backup SRAM(4 KB) base address in the bit-band region */ -#define FLASH_END 0x080FFFFFU /*!< FLASH end address */ - -/* Legacy defines */ -#define SRAM_BASE SRAM1_BASE -#define SRAM_BB_BASE SRAM1_BB_BASE - - -/*!< Peripheral memory map */ -#define APB1PERIPH_BASE PERIPH_BASE -#define APB2PERIPH_BASE (PERIPH_BASE + 0x00010000U) -#define AHB1PERIPH_BASE (PERIPH_BASE + 0x00020000U) -#define AHB2PERIPH_BASE (PERIPH_BASE + 0x10000000U) - -/*!< APB1 peripherals */ -#define TIM2_BASE (APB1PERIPH_BASE + 0x0000U) -#define TIM3_BASE (APB1PERIPH_BASE + 0x0400U) -#define TIM4_BASE (APB1PERIPH_BASE + 0x0800U) -#define TIM5_BASE (APB1PERIPH_BASE + 0x0C00U) -#define TIM6_BASE (APB1PERIPH_BASE + 0x1000U) -#define TIM7_BASE (APB1PERIPH_BASE + 0x1400U) -#define TIM12_BASE (APB1PERIPH_BASE + 0x1800U) -#define TIM13_BASE (APB1PERIPH_BASE + 0x1C00U) -#define TIM14_BASE (APB1PERIPH_BASE + 0x2000U) -#define RTC_BASE (APB1PERIPH_BASE + 0x2800U) -#define WWDG_BASE (APB1PERIPH_BASE + 0x2C00U) -#define IWDG_BASE (APB1PERIPH_BASE + 0x3000U) -#define SPI2_BASE (APB1PERIPH_BASE + 0x3800U) -#define SPI3_BASE (APB1PERIPH_BASE + 0x3C00U) -#define USART2_BASE (APB1PERIPH_BASE + 0x4400U) -#define USART3_BASE (APB1PERIPH_BASE + 0x4800U) -#define UART4_BASE (APB1PERIPH_BASE + 0x4C00U) -#define UART5_BASE (APB1PERIPH_BASE + 0x5000U) -#define I2C1_BASE (APB1PERIPH_BASE + 0x5400U) -#define I2C2_BASE (APB1PERIPH_BASE + 0x5800U) -#define I2C3_BASE (APB1PERIPH_BASE + 0x5C00U) -#define CAN1_BASE (APB1PERIPH_BASE + 0x6400U) -#define CAN2_BASE (APB1PERIPH_BASE + 0x6800U) -#define PWR_BASE (APB1PERIPH_BASE + 0x7000U) -#define DAC_BASE (APB1PERIPH_BASE + 0x7400U) - -/*!< APB2 peripherals */ -#define TIM1_BASE (APB2PERIPH_BASE + 0x0000U) -#define TIM8_BASE (APB2PERIPH_BASE + 0x0400U) -#define USART1_BASE (APB2PERIPH_BASE + 0x1000U) -#define USART6_BASE (APB2PERIPH_BASE + 0x1400U) -#define ADC1_BASE (APB2PERIPH_BASE + 0x2000U) -#define ADC2_BASE (APB2PERIPH_BASE + 0x2100U) -#define ADC3_BASE (APB2PERIPH_BASE + 0x2200U) -#define ADC_BASE (APB2PERIPH_BASE + 0x2300U) -#define SDIO_BASE (APB2PERIPH_BASE + 0x2C00U) -#define SPI1_BASE (APB2PERIPH_BASE + 0x3000U) -#define SYSCFG_BASE (APB2PERIPH_BASE + 0x3800U) -#define EXTI_BASE (APB2PERIPH_BASE + 0x3C00U) -#define TIM9_BASE (APB2PERIPH_BASE + 0x4000U) -#define TIM10_BASE (APB2PERIPH_BASE + 0x4400U) -#define TIM11_BASE (APB2PERIPH_BASE + 0x4800U) - -/*!< AHB1 peripherals */ -#define GPIOA_BASE (AHB1PERIPH_BASE + 0x0000U) -#define GPIOB_BASE (AHB1PERIPH_BASE + 0x0400U) -#define GPIOC_BASE (AHB1PERIPH_BASE + 0x0800U) -#define GPIOD_BASE (AHB1PERIPH_BASE + 0x0C00U) -#define GPIOE_BASE (AHB1PERIPH_BASE + 0x1000U) -#define GPIOF_BASE (AHB1PERIPH_BASE + 0x1400U) -#define GPIOG_BASE (AHB1PERIPH_BASE + 0x1800U) -#define GPIOH_BASE (AHB1PERIPH_BASE + 0x1C00U) -#define GPIOI_BASE (AHB1PERIPH_BASE + 0x2000U) -#define CRC_BASE (AHB1PERIPH_BASE + 0x3000U) -#define RCC_BASE (AHB1PERIPH_BASE + 0x3800U) -#define FLASH_R_BASE (AHB1PERIPH_BASE + 0x3C00U) -#define DMA1_BASE (AHB1PERIPH_BASE + 0x6000U) -#define DMA1_Stream0_BASE (DMA1_BASE + 0x010U) -#define DMA1_Stream1_BASE (DMA1_BASE + 0x028U) -#define DMA1_Stream2_BASE (DMA1_BASE + 0x040U) -#define DMA1_Stream3_BASE (DMA1_BASE + 0x058U) -#define DMA1_Stream4_BASE (DMA1_BASE + 0x070U) -#define DMA1_Stream5_BASE (DMA1_BASE + 0x088U) -#define DMA1_Stream6_BASE (DMA1_BASE + 0x0A0U) -#define DMA1_Stream7_BASE (DMA1_BASE + 0x0B8U) -#define DMA2_BASE (AHB1PERIPH_BASE + 0x6400U) -#define DMA2_Stream0_BASE (DMA2_BASE + 0x010U) -#define DMA2_Stream1_BASE (DMA2_BASE + 0x028U) -#define DMA2_Stream2_BASE (DMA2_BASE + 0x040U) -#define DMA2_Stream3_BASE (DMA2_BASE + 0x058U) -#define DMA2_Stream4_BASE (DMA2_BASE + 0x070U) -#define DMA2_Stream5_BASE (DMA2_BASE + 0x088U) -#define DMA2_Stream6_BASE (DMA2_BASE + 0x0A0U) -#define DMA2_Stream7_BASE (DMA2_BASE + 0x0B8U) - -/*!< AHB2 peripherals */ -#define RNG_BASE (AHB2PERIPH_BASE + 0x60800U) - -/*!< FSMC Bankx registers base address */ -#define FSMC_Bank1_R_BASE (FSMC_R_BASE + 0x0000U) -#define FSMC_Bank1E_R_BASE (FSMC_R_BASE + 0x0104U) -#define FSMC_Bank2_3_R_BASE (FSMC_R_BASE + 0x0060U) -#define FSMC_Bank4_R_BASE (FSMC_R_BASE + 0x00A0U) - -/* Debug MCU registers base address */ -#define DBGMCU_BASE 0xE0042000U - -/*!< USB registers base address */ -#define USB_OTG_HS_PERIPH_BASE 0x40040000U -#define USB_OTG_FS_PERIPH_BASE 0x50000000U - -#define USB_OTG_GLOBAL_BASE 0x000U -#define USB_OTG_DEVICE_BASE 0x800U -#define USB_OTG_IN_ENDPOINT_BASE 0x900U -#define USB_OTG_OUT_ENDPOINT_BASE 0xB00U -#define USB_OTG_EP_REG_SIZE 0x20U -#define USB_OTG_HOST_BASE 0x400U -#define USB_OTG_HOST_PORT_BASE 0x440U -#define USB_OTG_HOST_CHANNEL_BASE 0x500U -#define USB_OTG_HOST_CHANNEL_SIZE 0x20U -#define USB_OTG_PCGCCTL_BASE 0xE00U -#define USB_OTG_FIFO_BASE 0x1000U -#define USB_OTG_FIFO_SIZE 0x1000U - -/** - * @} - */ - -/** @addtogroup Peripheral_declaration - * @{ - */ -#define TIM2 ((TIM_TypeDef *) TIM2_BASE) -#define TIM3 ((TIM_TypeDef *) TIM3_BASE) -#define TIM4 ((TIM_TypeDef *) TIM4_BASE) -#define TIM5 ((TIM_TypeDef *) TIM5_BASE) -#define TIM6 ((TIM_TypeDef *) TIM6_BASE) -#define TIM7 ((TIM_TypeDef *) TIM7_BASE) -#define TIM12 ((TIM_TypeDef *) TIM12_BASE) -#define TIM13 ((TIM_TypeDef *) TIM13_BASE) -#define TIM14 ((TIM_TypeDef *) TIM14_BASE) -#define RTC ((RTC_TypeDef *) RTC_BASE) -#define WWDG ((WWDG_TypeDef *) WWDG_BASE) -#define IWDG ((IWDG_TypeDef *) IWDG_BASE) -#define SPI2 ((SPI_TypeDef *) SPI2_BASE) -#define SPI3 ((SPI_TypeDef *) SPI3_BASE) -#define USART2 ((USART_TypeDef *) USART2_BASE) -#define USART3 ((USART_TypeDef *) USART3_BASE) -#define UART4 ((USART_TypeDef *) UART4_BASE) -#define UART5 ((USART_TypeDef *) UART5_BASE) -#define I2C1 ((I2C_TypeDef *) I2C1_BASE) -#define I2C2 ((I2C_TypeDef *) I2C2_BASE) -#define I2C3 ((I2C_TypeDef *) I2C3_BASE) -#define CAN1 ((CAN_TypeDef *) CAN1_BASE) -#define CAN2 ((CAN_TypeDef *) CAN2_BASE) -#define PWR ((PWR_TypeDef *) PWR_BASE) -#define DAC ((DAC_TypeDef *) DAC_BASE) -#define TIM1 ((TIM_TypeDef *) TIM1_BASE) -#define TIM8 ((TIM_TypeDef *) TIM8_BASE) -#define USART1 ((USART_TypeDef *) USART1_BASE) -#define USART6 ((USART_TypeDef *) USART6_BASE) -#define ADC ((ADC_Common_TypeDef *) ADC_BASE) -#define ADC1 ((ADC_TypeDef *) ADC1_BASE) -#define ADC2 ((ADC_TypeDef *) ADC2_BASE) -#define ADC3 ((ADC_TypeDef *) ADC3_BASE) -#define SDIO ((SDIO_TypeDef *) SDIO_BASE) -#define SPI1 ((SPI_TypeDef *) SPI1_BASE) -#define SYSCFG ((SYSCFG_TypeDef *) SYSCFG_BASE) -#define EXTI ((EXTI_TypeDef *) EXTI_BASE) -#define TIM9 ((TIM_TypeDef *) TIM9_BASE) -#define TIM10 ((TIM_TypeDef *) TIM10_BASE) -#define TIM11 ((TIM_TypeDef *) TIM11_BASE) -#define GPIOA ((GPIO_TypeDef *) GPIOA_BASE) -#define GPIOB ((GPIO_TypeDef *) GPIOB_BASE) -#define GPIOC ((GPIO_TypeDef *) GPIOC_BASE) -#define GPIOD ((GPIO_TypeDef *) GPIOD_BASE) -#define GPIOE ((GPIO_TypeDef *) GPIOE_BASE) -#define GPIOF ((GPIO_TypeDef *) GPIOF_BASE) -#define GPIOG ((GPIO_TypeDef *) GPIOG_BASE) -#define GPIOH ((GPIO_TypeDef *) GPIOH_BASE) -#define GPIOI ((GPIO_TypeDef *) GPIOI_BASE) -#define CRC ((CRC_TypeDef *) CRC_BASE) -#define RCC ((RCC_TypeDef *) RCC_BASE) -#define FLASH ((FLASH_TypeDef *) FLASH_R_BASE) -#define DMA1 ((DMA_TypeDef *) DMA1_BASE) -#define DMA1_Stream0 ((DMA_Stream_TypeDef *) DMA1_Stream0_BASE) -#define DMA1_Stream1 ((DMA_Stream_TypeDef *) DMA1_Stream1_BASE) -#define DMA1_Stream2 ((DMA_Stream_TypeDef *) DMA1_Stream2_BASE) -#define DMA1_Stream3 ((DMA_Stream_TypeDef *) DMA1_Stream3_BASE) -#define DMA1_Stream4 ((DMA_Stream_TypeDef *) DMA1_Stream4_BASE) -#define DMA1_Stream5 ((DMA_Stream_TypeDef *) DMA1_Stream5_BASE) -#define DMA1_Stream6 ((DMA_Stream_TypeDef *) DMA1_Stream6_BASE) -#define DMA1_Stream7 ((DMA_Stream_TypeDef *) DMA1_Stream7_BASE) -#define DMA2 ((DMA_TypeDef *) DMA2_BASE) -#define DMA2_Stream0 ((DMA_Stream_TypeDef *) DMA2_Stream0_BASE) -#define DMA2_Stream1 ((DMA_Stream_TypeDef *) DMA2_Stream1_BASE) -#define DMA2_Stream2 ((DMA_Stream_TypeDef *) DMA2_Stream2_BASE) -#define DMA2_Stream3 ((DMA_Stream_TypeDef *) DMA2_Stream3_BASE) -#define DMA2_Stream4 ((DMA_Stream_TypeDef *) DMA2_Stream4_BASE) -#define DMA2_Stream5 ((DMA_Stream_TypeDef *) DMA2_Stream5_BASE) -#define DMA2_Stream6 ((DMA_Stream_TypeDef *) DMA2_Stream6_BASE) -#define DMA2_Stream7 ((DMA_Stream_TypeDef *) DMA2_Stream7_BASE) -#define RNG ((RNG_TypeDef *) RNG_BASE) -#define FSMC_Bank1 ((FSMC_Bank1_TypeDef *) FSMC_Bank1_R_BASE) -#define FSMC_Bank1E ((FSMC_Bank1E_TypeDef *) FSMC_Bank1E_R_BASE) -#define FSMC_Bank2_3 ((FSMC_Bank2_3_TypeDef *) FSMC_Bank2_3_R_BASE) -#define FSMC_Bank4 ((FSMC_Bank4_TypeDef *) FSMC_Bank4_R_BASE) - -#define DBGMCU ((DBGMCU_TypeDef *) DBGMCU_BASE) - -#define USB_OTG_FS ((USB_OTG_GlobalTypeDef *) USB_OTG_FS_PERIPH_BASE) -#define USB_OTG_HS ((USB_OTG_GlobalTypeDef *) USB_OTG_HS_PERIPH_BASE) - -/** - * @} - */ - -/** @addtogroup Exported_constants - * @{ - */ - - /** @addtogroup Peripheral_Registers_Bits_Definition - * @{ - */ - -/******************************************************************************/ -/* Peripheral Registers_Bits_Definition */ -/******************************************************************************/ - -/******************************************************************************/ -/* */ -/* Analog to Digital Converter */ -/* */ -/******************************************************************************/ -/******************** Bit definition for ADC_SR register ********************/ -#define ADC_SR_AWD 0x00000001U /*!
© COPYRIGHT(c) 2016 STMicroelectronics
- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ - -/** @addtogroup CMSIS - * @{ - */ - -/** @addtogroup stm32f2xx - * @{ - */ - -#ifndef __STM32F2xx_H -#define __STM32F2xx_H - -#ifdef __cplusplus - extern "C" { -#endif /* __cplusplus */ - -/** @addtogroup Library_configuration_section - * @{ - */ - -/** - * @brief STM32 Family - */ -#if !defined (STM32F2) -#define STM32F2 -#endif /* STM32F2 */ - -/* Uncomment the line below according to the target STM32 device used in your - application - */ -/* #if !defined (STM32F205xx) && !defined (STM32F215xx) && !defined (STM32F207xx) && !defined (STM32F217xx) */ - - /* #define STM32F205xx */ /*!< STM32F205RG, STM32F205VG, STM32F205ZG, STM32F205RF, STM32F205VF, STM32F205ZF, - STM32F205RE, STM32F205VE, STM32F205ZE, STM32F205RC, STM32F205VC, STM32F205ZC, - STM32F205RB and STM32F205VB Devices */ - /* #define STM32F215xx */ /*!< STM32F215RG, STM32F215VG, STM32F215ZG, STM32F215RE, STM32F215VE and STM32F215ZE Devices */ - /* #define STM32F207xx */ /*!< STM32F207VG, STM32F207ZG, STM32F207IG, STM32F207VF, STM32F207ZF, STM32F207IF, - STM32F207VE, STM32F207ZE, STM32F207IE, STM32F207VC, STM32F207ZC and STM32F207IC Devices */ - /* #define STM32F217xx */ /*!< STM32F217VG, STM32F217ZG, STM32F217IG, STM32F217VE, STM32F217ZE and STM32F217IE Devices */ - -//#endif - -/* Tip: To avoid modifying this file each time you need to switch between these - devices, you can define the device in your toolchain compiler preprocessor. - */ -#if !defined (USE_HAL_DRIVER) -/** - * @brief Comment the line below if you will not use the peripherals drivers. - In this case, these drivers will not be included and the application code will - be based on direct access to peripherals registers - */ - /*#define USE_HAL_DRIVER */ -#endif /* USE_HAL_DRIVER */ - -/** - * @brief CMSIS Device version number V2.1.2 - */ -#define __STM32F2xx_CMSIS_VERSION_MAIN (0x02U) /*!< [31:24] main version */ -#define __STM32F2xx_CMSIS_VERSION_SUB1 (0x01U) /*!< [23:16] sub1 version */ -#define __STM32F2xx_CMSIS_VERSION_SUB2 (0x02U) /*!< [15:8] sub2 version */ -#define __STM32F2xx_CMSIS_VERSION_RC (0x00U) /*!< [7:0] release candidate */ -#define __STM32F2xx_CMSIS_VERSION ((__STM32F2xx_CMSIS_VERSION_MAIN << 24)\ - |(__STM32F2xx_CMSIS_VERSION_SUB1 << 16)\ - |(__STM32F2xx_CMSIS_VERSION_SUB2 << 8 )\ - |(__STM32F2xx_CMSIS_VERSION)) - -/** - * @} - */ - -/** @addtogroup Device_Included - * @{ - */ - -#if defined(STM32F215xx) - #include "stm32f215xx.h" -#elif defined(STM32F205xx) - #include "stm32f205xx.h" -// #elif defined(STM32F207xx) -// #include "stm32f207xx.h" -// #elif defined(STM32F217xx) -// #include "stm32f217xx.h" -#else - #error "Please select first the target STM32F2xx device used in your application (in stm32f2xx.h file)" -#endif - -/** - * @} - */ - -/** @addtogroup Exported_types - * @{ - */ -typedef enum -{ - RESET = 0, - SET = !RESET -} FlagStatus, ITStatus; - -typedef enum -{ - DISABLE = 0, - ENABLE = !DISABLE -} FunctionalState; -#define IS_FUNCTIONAL_STATE(STATE) (((STATE) == DISABLE) || ((STATE) == ENABLE)) - -typedef enum -{ - ERROR = 0, - SUCCESS = !ERROR -} ErrorStatus; - -/** - * @} - */ - - -/** @addtogroup Exported_macro - * @{ - */ -#define SET_BIT(REG, BIT) ((REG) |= (BIT)) - -#define CLEAR_BIT(REG, BIT) ((REG) &= ~(BIT)) - -#define READ_BIT(REG, BIT) ((REG) & (BIT)) - -#define CLEAR_REG(REG) ((REG) = (0x0)) - -#define WRITE_REG(REG, VAL) ((REG) = (VAL)) - -#define READ_REG(REG) ((REG)) - -#define MODIFY_REG(REG, CLEARMASK, SETMASK) WRITE_REG((REG), (((READ_REG(REG)) & (~(CLEARMASK))) | (SETMASK))) - -#define POSITION_VAL(VAL) (__CLZ(__RBIT(VAL))) - - -/** - * @} - */ - -#if defined (USE_HAL_DRIVER) - #include "stm32f2xx_hal.h" -#endif /* USE_HAL_DRIVER */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* __STM32F2xx_H */ - -/** - * @} - */ - -/** - * @} - */ - - - - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/board/stm32fx/inc/stm32f2xx_hal_def.h b/board/stm32fx/inc/stm32f2xx_hal_def.h deleted file mode 100644 index dfef07939c..0000000000 --- a/board/stm32fx/inc/stm32f2xx_hal_def.h +++ /dev/null @@ -1,181 +0,0 @@ -/** - ****************************************************************************** - * @file stm32f2xx_hal_def.h - * @author MCD Application Team - * @version V1.1.3 - * @date 29-June-2016 - * @brief This file contains HAL common defines, enumeration, macros and - * structures definitions. - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2016 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ - -/* Define to prevent recursive inclusion -------------------------------------*/ -#ifndef __STM32F2xx_HAL_DEF -#define __STM32F2xx_HAL_DEF - -#ifdef __cplusplus - extern "C" { -#endif - -/* Includes ------------------------------------------------------------------*/ -#include "stm32f2xx.h" -//#include "Legacy/stm32_hal_legacy.h" -//#include - -/* Exported types ------------------------------------------------------------*/ - -/** - * @brief HAL Status structures definition - */ -typedef enum -{ - HAL_OK = 0x00U, - HAL_ERROR = 0x01U, - HAL_BUSY = 0x02U, - HAL_TIMEOUT = 0x03U -} HAL_StatusTypeDef; - -/** - * @brief HAL Lock structures definition - */ -typedef enum -{ - HAL_UNLOCKED = 0x00U, - HAL_LOCKED = 0x01U -} HAL_LockTypeDef; - -/* Exported macro ------------------------------------------------------------*/ -#define HAL_MAX_DELAY 0xFFFFFFFFU - -#define HAL_IS_BIT_SET(REG, BIT) (((REG) & (BIT)) != RESET) -#define HAL_IS_BIT_CLR(REG, BIT) (((REG) & (BIT)) == RESET) - -#define __HAL_LINKDMA(__HANDLE__, __PPP_DMA_FIELD_, __DMA_HANDLE_) \ - do{ \ - (__HANDLE__)->__PPP_DMA_FIELD_ = &(__DMA_HANDLE_); \ - (__DMA_HANDLE_).Parent = (__HANDLE__); \ - } while(0) - -#define UNUSED(x) ((void)(x)) - -/** @brief Reset the Handle's State field. - * @param __HANDLE__: specifies the Peripheral Handle. - * @note This macro can be used for the following purpose: - * - When the Handle is declared as local variable; before passing it as parameter - * to HAL_PPP_Init() for the first time, it is mandatory to use this macro - * to set to 0 the Handle's "State" field. - * Otherwise, "State" field may have any random value and the first time the function - * HAL_PPP_Init() is called, the low level hardware initialization will be missed - * (i.e. HAL_PPP_MspInit() will not be executed). - * - When there is a need to reconfigure the low level hardware: instead of calling - * HAL_PPP_DeInit() then HAL_PPP_Init(), user can make a call to this macro then HAL_PPP_Init(). - * In this later function, when the Handle's "State" field is set to 0, it will execute the function - * HAL_PPP_MspInit() which will reconfigure the low level hardware. - * @retval None - */ -#define __HAL_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = 0U) - -#if (USE_RTOS == 1) - /* Reserved for future use */ - #error " USE_RTOS should be 0 in the current HAL release " -#else - #define __HAL_LOCK(__HANDLE__) \ - do{ \ - if((__HANDLE__)->Lock == HAL_LOCKED) \ - { \ - return HAL_BUSY; \ - } \ - else \ - { \ - (__HANDLE__)->Lock = HAL_LOCKED; \ - } \ - }while (0) - - #define __HAL_UNLOCK(__HANDLE__) \ - do{ \ - (__HANDLE__)->Lock = HAL_UNLOCKED; \ - }while (0) -#endif /* USE_RTOS */ - -#if defined ( __GNUC__ ) - #ifndef __weak - #define __weak __attribute__((weak)) - #endif /* __weak */ - #ifndef __packed - #define __packed __attribute__((__packed__)) - #endif /* __packed */ -#endif /* __GNUC__ */ - - -/* Macro to get variable aligned on 4-bytes, for __ICCARM__ the directive "#pragma data_alignment=4" must be used instead */ -#if defined (__GNUC__) /* GNU Compiler */ - #ifndef __ALIGN_END - #define __ALIGN_END __attribute__ ((aligned (4))) - #endif /* __ALIGN_END */ - #ifndef __ALIGN_BEGIN - #define __ALIGN_BEGIN - #endif /* __ALIGN_BEGIN */ -#else - #ifndef __ALIGN_END - #define __ALIGN_END - #endif /* __ALIGN_END */ - #ifndef __ALIGN_BEGIN - #if defined (__CC_ARM) /* ARM Compiler */ - #define __ALIGN_BEGIN __align(4) - #elif defined (__ICCARM__) /* IAR Compiler */ - #define __ALIGN_BEGIN - #endif /* __CC_ARM */ - #endif /* __ALIGN_BEGIN */ -#endif /* __GNUC__ */ - -/** - * @brief __NOINLINE definition - */ -#if defined ( __CC_ARM ) || defined ( __GNUC__ ) -/* ARM & GNUCompiler - ---------------- -*/ -#define __NOINLINE __attribute__ ( (noinline) ) - -#elif defined ( __ICCARM__ ) -/* ICCARM Compiler - --------------- -*/ -#define __NOINLINE _Pragma("optimize = no_inline") - -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* ___STM32F2xx_HAL_DEF */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/board/stm32fx/inc/stm32f2xx_hal_gpio_ex.h b/board/stm32fx/inc/stm32f2xx_hal_gpio_ex.h deleted file mode 100644 index 7cef9a648b..0000000000 --- a/board/stm32fx/inc/stm32f2xx_hal_gpio_ex.h +++ /dev/null @@ -1,299 +0,0 @@ -/** - ****************************************************************************** - * @file stm32f2xx_hal_gpio_ex.h - * @author MCD Application Team - * @version V1.1.3 - * @date 29-June-2016 - * @brief Header file of GPIO HAL Extension module. - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2016 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ - -/* Define to prevent recursive inclusion -------------------------------------*/ -#ifndef __STM32F2xx_HAL_GPIO_EX_H -#define __STM32F2xx_HAL_GPIO_EX_H - -#ifdef __cplusplus - extern "C" { -#endif - -/* Includes ------------------------------------------------------------------*/ -#include "stm32f2xx_hal_def.h" - -/** @addtogroup STM32F2xx_HAL_Driver - * @{ - */ - -/** @defgroup GPIOEx GPIOEx - * @{ - */ - -/* Exported types ------------------------------------------------------------*/ -/* Exported constants --------------------------------------------------------*/ -/* Exported constants --------------------------------------------------------*/ - -/** @defgroup GPIOEx_Exported_Constants GPIO Exported Constants - * @{ - */ - -/** @defgroup GPIO_Alternate_function_selection GPIO Alternate function selection - * @{ - */ - -/** - * @brief AF 0 selection - */ -#define GPIO_AF0_RTC_50Hz ((uint8_t)0x00U) /* RTC_50Hz Alternate Function mapping */ -#define GPIO_AF0_MCO ((uint8_t)0x00U) /* MCO (MCO1 and MCO2) Alternate Function mapping */ -#define GPIO_AF0_TAMPER ((uint8_t)0x00U) /* TAMPER (TAMPER_1 and TAMPER_2) Alternate Function mapping */ -#define GPIO_AF0_SWJ ((uint8_t)0x00U) /* SWJ (SWD and JTAG) Alternate Function mapping */ -#define GPIO_AF0_TRACE ((uint8_t)0x00U) /* TRACE Alternate Function mapping */ - -/** - * @brief AF 1 selection - */ -#define GPIO_AF1_TIM1 ((uint8_t)0x01U) /* TIM1 Alternate Function mapping */ -#define GPIO_AF1_TIM2 ((uint8_t)0x01U) /* TIM2 Alternate Function mapping */ - -/** - * @brief AF 2 selection - */ -#define GPIO_AF2_TIM3 ((uint8_t)0x02U) /* TIM3 Alternate Function mapping */ -#define GPIO_AF2_TIM4 ((uint8_t)0x02U) /* TIM4 Alternate Function mapping */ -#define GPIO_AF2_TIM5 ((uint8_t)0x02U) /* TIM5 Alternate Function mapping */ - -/** - * @brief AF 3 selection - */ -#define GPIO_AF3_TIM8 ((uint8_t)0x03U) /* TIM8 Alternate Function mapping */ -#define GPIO_AF3_TIM9 ((uint8_t)0x03U) /* TIM9 Alternate Function mapping */ -#define GPIO_AF3_TIM10 ((uint8_t)0x03U) /* TIM10 Alternate Function mapping */ -#define GPIO_AF3_TIM11 ((uint8_t)0x03U) /* TIM11 Alternate Function mapping */ - -/** - * @brief AF 4 selection - */ -#define GPIO_AF4_I2C1 ((uint8_t)0x04U) /* I2C1 Alternate Function mapping */ -#define GPIO_AF4_I2C2 ((uint8_t)0x04U) /* I2C2 Alternate Function mapping */ -#define GPIO_AF4_I2C3 ((uint8_t)0x04U) /* I2C3 Alternate Function mapping */ - -/** - * @brief AF 5 selection - */ -#define GPIO_AF5_SPI1 ((uint8_t)0x05U) /* SPI1 Alternate Function mapping */ -#define GPIO_AF5_SPI2 ((uint8_t)0x05U) /* SPI2/I2S2 Alternate Function mapping */ -/** - * @brief AF 6 selection - */ -#define GPIO_AF6_SPI3 ((uint8_t)0x06U) /* SPI3/I2S3 Alternate Function mapping */ - -/** - * @brief AF 7 selection - */ -#define GPIO_AF7_USART1 ((uint8_t)0x07U) /* USART1 Alternate Function mapping */ -#define GPIO_AF7_USART2 ((uint8_t)0x07U) /* USART2 Alternate Function mapping */ -#define GPIO_AF7_USART3 ((uint8_t)0x07U) /* USART3 Alternate Function mapping */ - -/** - * @brief AF 8 selection - */ -#define GPIO_AF8_UART4 ((uint8_t)0x08U) /* UART4 Alternate Function mapping */ -#define GPIO_AF8_UART5 ((uint8_t)0x08U) /* UART5 Alternate Function mapping */ -#define GPIO_AF8_USART6 ((uint8_t)0x08U) /* USART6 Alternate Function mapping */ - -/** - * @brief AF 9 selection - */ -#define GPIO_AF9_CAN1 ((uint8_t)0x09U) /* CAN1 Alternate Function mapping */ -#define GPIO_AF9_CAN2 ((uint8_t)0x09U) /* CAN2 Alternate Function mapping */ -#define GPIO_AF9_TIM12 ((uint8_t)0x09U) /* TIM12 Alternate Function mapping */ -#define GPIO_AF9_TIM13 ((uint8_t)0x09U) /* TIM13 Alternate Function mapping */ -#define GPIO_AF9_TIM14 ((uint8_t)0x09U) /* TIM14 Alternate Function mapping */ - -/** - * @brief AF 10 selection - */ -#define GPIO_AF10_OTG_FS ((uint8_t)0xAU) /* OTG_FS Alternate Function mapping */ -#define GPIO_AF10_OTG_HS ((uint8_t)0xAU) /* OTG_HS Alternate Function mapping */ - -/** - * @brief AF 11 selection - */ -#if defined(STM32F207xx) || defined(STM32F217xx) -#define GPIO_AF11_ETH ((uint8_t)0x0BU) /* ETHERNET Alternate Function mapping */ -#endif /* STM32F207xx || STM32F217xx */ - -/** - * @brief AF 12 selection - */ -#define GPIO_AF12_FSMC ((uint8_t)0xCU) /* FSMC Alternate Function mapping */ -#define GPIO_AF12_OTG_HS_FS ((uint8_t)0xCU) /* OTG HS configured in FS, Alternate Function mapping */ -#define GPIO_AF12_SDIO ((uint8_t)0xCU) /* SDIO Alternate Function mapping */ - -/** - * @brief AF 13 selection - */ -#if defined(STM32F207xx) || defined(STM32F217xx) -#define GPIO_AF13_DCMI ((uint8_t)0x0DU) /* DCMI Alternate Function mapping */ -#endif /* STM32F207xx || STM32F217xx */ - -/** - * @brief AF 15 selection - */ -#define GPIO_AF15_EVENTOUT ((uint8_t)0x0FU) /* EVENTOUT Alternate Function mapping */ - -/** - * @} - */ - -/** - * @} - */ - -/* Exported macro ------------------------------------------------------------*/ -/** @defgroup GPIOEx_Exported_Macros GPIO Exported Macros - * @{ - */ -/** - * @} - */ - -/* Exported functions --------------------------------------------------------*/ -/** @defgroup GPIOEx_Exported_Functions GPIO Exported Functions - * @{ - */ -/** - * @} - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/** @defgroup GPIOEx_Private_Constants GPIO Private Constants - * @{ - */ -/** - * @} - */ - -/* Private macros ------------------------------------------------------------*/ -/** @defgroup GPIOEx_Private_Macros GPIO Private Macros - * @{ - */ -/** @defgroup GPIOEx_Get_Port_Index GPIO Get Port Index - * @{ - */ -#define GPIO_GET_INDEX(__GPIOx__) (uint8_t)(((__GPIOx__) == (GPIOA))? 0U :\ - ((__GPIOx__) == (GPIOB))? 1U :\ - ((__GPIOx__) == (GPIOC))? 2U :\ - ((__GPIOx__) == (GPIOD))? 3U :\ - ((__GPIOx__) == (GPIOE))? 4U :\ - ((__GPIOx__) == (GPIOF))? 5U :\ - ((__GPIOx__) == (GPIOG))? 6U :\ - ((__GPIOx__) == (GPIOH))? 7U :\ - ((__GPIOx__) == (GPIOI))? 8U : 9U) -/** - * @} - */ - -/** @defgroup GPIOEx_IS_Alternat_function_selection GPIO Check Alternate Function - * @{ - */ -#if defined(STM32F207xx) || defined(STM32F217xx) - -#define IS_GPIO_AF(AF) (((AF) == GPIO_AF0_RTC_50Hz) || ((AF) == GPIO_AF9_TIM14) || \ - ((AF) == GPIO_AF0_MCO) || ((AF) == GPIO_AF0_TAMPER) || \ - ((AF) == GPIO_AF0_SWJ) || ((AF) == GPIO_AF0_TRACE) || \ - ((AF) == GPIO_AF1_TIM1) || ((AF) == GPIO_AF1_TIM2) || \ - ((AF) == GPIO_AF2_TIM3) || ((AF) == GPIO_AF2_TIM4) || \ - ((AF) == GPIO_AF2_TIM5) || ((AF) == GPIO_AF3_TIM8) || \ - ((AF) == GPIO_AF4_I2C1) || ((AF) == GPIO_AF4_I2C2) || \ - ((AF) == GPIO_AF4_I2C3) || ((AF) == GPIO_AF5_SPI1) || \ - ((AF) == GPIO_AF5_SPI2) || ((AF) == GPIO_AF9_TIM13) || \ - ((AF) == GPIO_AF6_SPI3) || ((AF) == GPIO_AF9_TIM12) || \ - ((AF) == GPIO_AF7_USART1) || ((AF) == GPIO_AF7_USART2) || \ - ((AF) == GPIO_AF7_USART3) || ((AF) == GPIO_AF8_UART4) || \ - ((AF) == GPIO_AF8_UART5) || ((AF) == GPIO_AF8_USART6) || \ - ((AF) == GPIO_AF9_CAN1) || ((AF) == GPIO_AF9_CAN2) || \ - ((AF) == GPIO_AF10_OTG_FS) || ((AF) == GPIO_AF10_OTG_HS) || \ - ((AF) == GPIO_AF11_ETH) || ((AF) == GPIO_AF12_OTG_HS_FS) || \ - ((AF) == GPIO_AF12_SDIO) || ((AF) == GPIO_AF13_DCMI) || \ - ((AF) == GPIO_AF12_FSMC) || ((AF) == GPIO_AF15_EVENTOUT)) -#else /* STM32F207xx || STM32F217xx */ -#define IS_GPIO_AF(AF) (((AF) == GPIO_AF0_RTC_50Hz) || ((AF) == GPIO_AF9_TIM14) || \ - ((AF) == GPIO_AF0_MCO) || ((AF) == GPIO_AF0_TAMPER) || \ - ((AF) == GPIO_AF0_SWJ) || ((AF) == GPIO_AF0_TRACE) || \ - ((AF) == GPIO_AF1_TIM1) || ((AF) == GPIO_AF1_TIM2) || \ - ((AF) == GPIO_AF2_TIM3) || ((AF) == GPIO_AF2_TIM4) || \ - ((AF) == GPIO_AF2_TIM5) || ((AF) == GPIO_AF3_TIM8) || \ - ((AF) == GPIO_AF4_I2C1) || ((AF) == GPIO_AF4_I2C2) || \ - ((AF) == GPIO_AF4_I2C3) || ((AF) == GPIO_AF5_SPI1) || \ - ((AF) == GPIO_AF5_SPI2) || ((AF) == GPIO_AF9_TIM13) || \ - ((AF) == GPIO_AF6_SPI3) || ((AF) == GPIO_AF9_TIM12) || \ - ((AF) == GPIO_AF7_USART1) || ((AF) == GPIO_AF7_USART2) || \ - ((AF) == GPIO_AF7_USART3) || ((AF) == GPIO_AF8_UART4) || \ - ((AF) == GPIO_AF8_UART5) || ((AF) == GPIO_AF8_USART6) || \ - ((AF) == GPIO_AF9_CAN1) || ((AF) == GPIO_AF9_CAN2) || \ - ((AF) == GPIO_AF10_OTG_FS) || ((AF) == GPIO_AF10_OTG_HS) || \ - ((AF) == GPIO_AF12_OTG_HS_FS) || ((AF) == GPIO_AF12_SDIO) || \ - ((AF) == GPIO_AF12_FSMC) || ((AF) == GPIO_AF15_EVENTOUT)) -#endif /* STM32F207xx || STM32F217xx */ - -/** - * @} - */ - -/** - * @} - */ - -/* Private functions ---------------------------------------------------------*/ -/** @defgroup GPIOEx_Private_Functions GPIO Private Functions - * @{ - */ - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -#ifdef __cplusplus -} -#endif - -#endif /* __STM32F2xx_HAL_GPIO_EX_H */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/board/stm32fx/inc/system_stm32f2xx.h b/board/stm32fx/inc/system_stm32f2xx.h deleted file mode 100644 index cd4b83c570..0000000000 --- a/board/stm32fx/inc/system_stm32f2xx.h +++ /dev/null @@ -1,122 +0,0 @@ -/** - ****************************************************************************** - * @file system_stm32f2xx.h - * @author MCD Application Team - * @version V2.1.2 - * @date 29-June-2016 - * @brief CMSIS Cortex-M3 Device System Source File for STM32F2xx devices. -****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2016 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ - -/** @addtogroup CMSIS - * @{ - */ - -/** @addtogroup stm32f2xx_system - * @{ - */ - -/** - * @brief Define to prevent recursive inclusion - */ -#ifndef __SYSTEM_STM32F2XX_H -#define __SYSTEM_STM32F2XX_H - -#ifdef __cplusplus - extern "C" { -#endif - -/** @addtogroup STM32F2xx_System_Includes - * @{ - */ - -/** - * @} - */ - - -/** @addtogroup STM32F2xx_System_Exported_types - * @{ - */ - /* This variable is updated in three ways: - 1) by calling CMSIS function SystemCoreClockUpdate() - 2) by calling HAL API function HAL_RCC_GetSysClockFreq() - 3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency - Note: If you use this function to configure the system clock; then there - is no need to call the 2 first functions listed above, since SystemCoreClock - variable is updated automatically. - */ -extern uint32_t SystemCoreClock; /*!< System Clock Frequency (Core Clock) */ - - -/** - * @} - */ - -/** @addtogroup STM32F2xx_System_Exported_Constants - * @{ - */ - -/** - * @} - */ - -/** @addtogroup STM32F2xx_System_Exported_Macros - * @{ - */ - -/** - * @} - */ - -/** @addtogroup STM32F2xx_System_Exported_Functions - * @{ - */ - -extern void SystemInit(void); -extern void SystemCoreClockUpdate(void); -/** - * @} - */ - -#ifdef __cplusplus -} -#endif - -#endif /*__SYSTEM_STM32F2XX_H */ - -/** - * @} - */ - -/** - * @} - */ -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/board/stm32fx/startup_stm32f205xx.s b/board/stm32fx/startup_stm32f205xx.s deleted file mode 100644 index 7554efc4c1..0000000000 --- a/board/stm32fx/startup_stm32f205xx.s +++ /dev/null @@ -1,511 +0,0 @@ -/** - ****************************************************************************** - * @file startup_stm32f205xx.s - * @author MCD Application Team - * @version V2.1.2 - * @date 29-June-2016 - * @brief STM32F205xx Devices vector table for Atollic TrueSTUDIO toolchain. - * This module performs: - * - Set the initial SP - * - Set the initial PC == Reset_Handler, - * - Set the vector table entries with the exceptions ISR address - * - Branches to main in the C library (which eventually - * calls main()). - * After Reset the Cortex-M3 processor is in Thread mode, - * priority is Privileged, and the Stack is set to Main. - ****************************************************************************** - * @attention - * - *

© COPYRIGHT 2016 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ - - .syntax unified - .cpu cortex-m3 - .thumb - -.global g_pfnVectors -.global Default_Handler - -/* start address for the initialization values of the .data section. -defined in linker script */ -.word _sidata -/* start address for the .data section. defined in linker script */ -.word _sdata -/* end address for the .data section. defined in linker script */ -.word _edata -/* start address for the .bss section. defined in linker script */ -.word _sbss -/* end address for the .bss section. defined in linker script */ -.word _ebss -/* stack used for SystemInit_ExtMemCtl; always internal RAM used */ - -/** - * @brief This is the code that gets called when the processor first - * starts execution following a reset event. Only the absolutely - * necessary set is performed, after which the application - * supplied main() routine is called. - * @param None - * @retval : None -*/ - - .section .text.Reset_Handler - .weak Reset_Handler - .type Reset_Handler, %function -Reset_Handler: - ldr sp, =_estack /* set stack pointer */ - bl __initialize_hardware_early - -/* Copy the data segment initializers from flash to SRAM */ - movs r1, #0 - b LoopCopyDataInit - -CopyDataInit: - ldr r3, =_sidata - ldr r3, [r3, r1] - str r3, [r0, r1] - adds r1, r1, #4 - -LoopCopyDataInit: - ldr r0, =_sdata - ldr r3, =_edata - adds r2, r0, r1 - cmp r2, r3 - bcc CopyDataInit - ldr r2, =_sbss - b LoopFillZerobss -/* Zero fill the bss segment. */ -FillZerobss: - movs r3, #0 - str r3, [r2], #4 - -LoopFillZerobss: - ldr r3, = _ebss - cmp r2, r3 - bcc FillZerobss - -/* Call the clock system initialization function.*/ - /*bl SystemInit */ -/* Call static constructors */ - /*bl __libc_init_array*/ -/* Call the application's entry point.*/ - bl main - bx lr -.size Reset_Handler, .-Reset_Handler - -/** - * @brief This is the code that gets called when the processor receives an - * unexpected interrupt. This simply enters an infinite loop, preserving - * the system state for examination by a debugger. - * @param None - * @retval None -*/ - .section .text.Default_Handler,"ax",%progbits -Default_Handler: -Infinite_Loop: - b Infinite_Loop - .size Default_Handler, .-Default_Handler -/****************************************************************************** -* -* The minimal vector table for a Cortex M3. Note that the proper constructs -* must be placed on this to ensure that it ends up at physical address -* 0x0000.0000. -* -*******************************************************************************/ - .section .isr_vector,"a",%progbits - .type g_pfnVectors, %object - .size g_pfnVectors, .-g_pfnVectors - - - -g_pfnVectors: - .word _estack - .word Reset_Handler - - .word NMI_Handler - .word HardFault_Handler - .word MemManage_Handler - .word BusFault_Handler - .word UsageFault_Handler - .word 0 - .word 0 - .word 0 - .word 0 - .word SVC_Handler - .word DebugMon_Handler - .word 0 - .word PendSV_Handler - .word SysTick_Handler - - /* External Interrupts */ - .word WWDG_IRQHandler /* Window WatchDog */ - .word PVD_IRQHandler /* PVD through EXTI Line detection */ - .word TAMP_STAMP_IRQHandler /* Tamper and TimeStamps through the EXTI line */ - .word RTC_WKUP_IRQHandler /* RTC Wakeup through the EXTI line */ - .word FLASH_IRQHandler /* FLASH */ - .word RCC_IRQHandler /* RCC */ - .word EXTI0_IRQHandler /* EXTI Line0 */ - .word EXTI1_IRQHandler /* EXTI Line1 */ - .word EXTI2_IRQHandler /* EXTI Line2 */ - .word EXTI3_IRQHandler /* EXTI Line3 */ - .word EXTI4_IRQHandler /* EXTI Line4 */ - .word DMA1_Stream0_IRQHandler /* DMA1 Stream 0 */ - .word DMA1_Stream1_IRQHandler /* DMA1 Stream 1 */ - .word DMA1_Stream2_IRQHandler /* DMA1 Stream 2 */ - .word DMA1_Stream3_IRQHandler /* DMA1 Stream 3 */ - .word DMA1_Stream4_IRQHandler /* DMA1 Stream 4 */ - .word DMA1_Stream5_IRQHandler /* DMA1 Stream 5 */ - .word DMA1_Stream6_IRQHandler /* DMA1 Stream 6 */ - .word ADC_IRQHandler /* ADC1, ADC2 and ADC3s */ - .word CAN1_TX_IRQHandler /* CAN1 TX */ - .word CAN1_RX0_IRQHandler /* CAN1 RX0 */ - .word CAN1_RX1_IRQHandler /* CAN1 RX1 */ - .word CAN1_SCE_IRQHandler /* CAN1 SCE */ - .word EXTI9_5_IRQHandler /* External Line[9:5]s */ - .word TIM1_BRK_TIM9_IRQHandler /* TIM1 Break and TIM9 */ - .word TIM1_UP_TIM10_IRQHandler /* TIM1 Update and TIM10 */ - .word TIM1_TRG_COM_TIM11_IRQHandler /* TIM1 Trigger and Commutation and TIM11 */ - .word TIM1_CC_IRQHandler /* TIM1 Capture Compare */ - .word TIM2_IRQHandler /* TIM2 */ - .word TIM3_IRQHandler /* TIM3 */ - .word TIM4_IRQHandler /* TIM4 */ - .word I2C1_EV_IRQHandler /* I2C1 Event */ - .word I2C1_ER_IRQHandler /* I2C1 Error */ - .word I2C2_EV_IRQHandler /* I2C2 Event */ - .word I2C2_ER_IRQHandler /* I2C2 Error */ - .word SPI1_IRQHandler /* SPI1 */ - .word SPI2_IRQHandler /* SPI2 */ - .word USART1_IRQHandler /* USART1 */ - .word USART2_IRQHandler /* USART2 */ - .word USART3_IRQHandler /* USART3 */ - .word EXTI15_10_IRQHandler /* External Line[15:10]s */ - .word RTC_Alarm_IRQHandler /* RTC Alarm (A and B) through EXTI Line */ - .word OTG_FS_WKUP_IRQHandler /* USB OTG FS Wakeup through EXTI line */ - .word TIM8_BRK_TIM12_IRQHandler /* TIM8 Break and TIM12 */ - .word TIM8_UP_TIM13_IRQHandler /* TIM8 Update and TIM13 */ - .word TIM8_TRG_COM_TIM14_IRQHandler /* TIM8 Trigger and Commutation and TIM14 */ - .word TIM8_CC_IRQHandler /* TIM8 Capture Compare */ - .word DMA1_Stream7_IRQHandler /* DMA1 Stream7 */ - .word FSMC_IRQHandler /* FSMC */ - .word SDIO_IRQHandler /* SDIO */ - .word TIM5_IRQHandler /* TIM5 */ - .word SPI3_IRQHandler /* SPI3 */ - .word UART4_IRQHandler /* UART4 */ - .word UART5_IRQHandler /* UART5 */ - .word TIM6_DAC_IRQHandler /* TIM6 and DAC1&2 underrun errors */ - .word TIM7_IRQHandler /* TIM7 */ - .word DMA2_Stream0_IRQHandler /* DMA2 Stream 0 */ - .word DMA2_Stream1_IRQHandler /* DMA2 Stream 1 */ - .word DMA2_Stream2_IRQHandler /* DMA2 Stream 2 */ - .word DMA2_Stream3_IRQHandler /* DMA2 Stream 3 */ - .word DMA2_Stream4_IRQHandler /* DMA2 Stream 4 */ - .word 0 /* Reserved */ - .word 0 /* Reserved */ - .word CAN2_TX_IRQHandler /* CAN2 TX */ - .word CAN2_RX0_IRQHandler /* CAN2 RX0 */ - .word CAN2_RX1_IRQHandler /* CAN2 RX1 */ - .word CAN2_SCE_IRQHandler /* CAN2 SCE */ - .word OTG_FS_IRQHandler /* USB OTG FS */ - .word DMA2_Stream5_IRQHandler /* DMA2 Stream 5 */ - .word DMA2_Stream6_IRQHandler /* DMA2 Stream 6 */ - .word DMA2_Stream7_IRQHandler /* DMA2 Stream 7 */ - .word USART6_IRQHandler /* USART6 */ - .word I2C3_EV_IRQHandler /* I2C3 event */ - .word I2C3_ER_IRQHandler /* I2C3 error */ - .word OTG_HS_EP1_OUT_IRQHandler /* USB OTG HS End Point 1 Out */ - .word OTG_HS_EP1_IN_IRQHandler /* USB OTG HS End Point 1 In */ - .word OTG_HS_WKUP_IRQHandler /* USB OTG HS Wakeup through EXTI */ - .word OTG_HS_IRQHandler /* USB OTG HS */ - .word 0 /* Reserved */ - .word 0 /* Reserved */ - .word HASH_RNG_IRQHandler /* Hash and Rng */ - -/******************************************************************************* -* -* Provide weak aliases for each Exception handler to the Default_Handler. -* As they are weak aliases, any function with the same name will override -* this definition. -* -*******************************************************************************/ - .weak NMI_Handler - .thumb_set NMI_Handler,Default_Handler - - .weak HardFault_Handler - .thumb_set HardFault_Handler,Default_Handler - - .weak MemManage_Handler - .thumb_set MemManage_Handler,Default_Handler - - .weak BusFault_Handler - .thumb_set BusFault_Handler,Default_Handler - - .weak UsageFault_Handler - .thumb_set UsageFault_Handler,Default_Handler - - .weak SVC_Handler - .thumb_set SVC_Handler,Default_Handler - - .weak DebugMon_Handler - .thumb_set DebugMon_Handler,Default_Handler - - .weak PendSV_Handler - .thumb_set PendSV_Handler,Default_Handler - - .weak SysTick_Handler - .thumb_set SysTick_Handler,Default_Handler - - .weak WWDG_IRQHandler - .thumb_set WWDG_IRQHandler,Default_Handler - - .weak PVD_IRQHandler - .thumb_set PVD_IRQHandler,Default_Handler - - .weak TAMP_STAMP_IRQHandler - .thumb_set TAMP_STAMP_IRQHandler,Default_Handler - - .weak RTC_WKUP_IRQHandler - .thumb_set RTC_WKUP_IRQHandler,Default_Handler - - .weak FLASH_IRQHandler - .thumb_set FLASH_IRQHandler,Default_Handler - - .weak RCC_IRQHandler - .thumb_set RCC_IRQHandler,Default_Handler - - .weak EXTI0_IRQHandler - .thumb_set EXTI0_IRQHandler,Default_Handler - - .weak EXTI1_IRQHandler - .thumb_set EXTI1_IRQHandler,Default_Handler - - .weak EXTI2_IRQHandler - .thumb_set EXTI2_IRQHandler,Default_Handler - - .weak EXTI3_IRQHandler - .thumb_set EXTI3_IRQHandler,Default_Handler - - .weak EXTI4_IRQHandler - .thumb_set EXTI4_IRQHandler,Default_Handler - - .weak DMA1_Stream0_IRQHandler - .thumb_set DMA1_Stream0_IRQHandler,Default_Handler - - .weak DMA1_Stream1_IRQHandler - .thumb_set DMA1_Stream1_IRQHandler,Default_Handler - - .weak DMA1_Stream2_IRQHandler - .thumb_set DMA1_Stream2_IRQHandler,Default_Handler - - .weak DMA1_Stream3_IRQHandler - .thumb_set DMA1_Stream3_IRQHandler,Default_Handler - - .weak DMA1_Stream4_IRQHandler - .thumb_set DMA1_Stream4_IRQHandler,Default_Handler - - .weak DMA1_Stream5_IRQHandler - .thumb_set DMA1_Stream5_IRQHandler,Default_Handler - - .weak DMA1_Stream6_IRQHandler - .thumb_set DMA1_Stream6_IRQHandler,Default_Handler - - .weak ADC_IRQHandler - .thumb_set ADC_IRQHandler,Default_Handler - - .weak CAN1_TX_IRQHandler - .thumb_set CAN1_TX_IRQHandler,Default_Handler - - .weak CAN1_RX0_IRQHandler - .thumb_set CAN1_RX0_IRQHandler,Default_Handler - - .weak CAN1_RX1_IRQHandler - .thumb_set CAN1_RX1_IRQHandler,Default_Handler - - .weak CAN1_SCE_IRQHandler - .thumb_set CAN1_SCE_IRQHandler,Default_Handler - - .weak EXTI9_5_IRQHandler - .thumb_set EXTI9_5_IRQHandler,Default_Handler - - .weak TIM1_BRK_TIM9_IRQHandler - .thumb_set TIM1_BRK_TIM9_IRQHandler,Default_Handler - - .weak TIM1_UP_TIM10_IRQHandler - .thumb_set TIM1_UP_TIM10_IRQHandler,Default_Handler - - .weak TIM1_TRG_COM_TIM11_IRQHandler - .thumb_set TIM1_TRG_COM_TIM11_IRQHandler,Default_Handler - - .weak TIM1_CC_IRQHandler - .thumb_set TIM1_CC_IRQHandler,Default_Handler - - .weak TIM2_IRQHandler - .thumb_set TIM2_IRQHandler,Default_Handler - - .weak TIM3_IRQHandler - .thumb_set TIM3_IRQHandler,Default_Handler - - .weak TIM4_IRQHandler - .thumb_set TIM4_IRQHandler,Default_Handler - - .weak I2C1_EV_IRQHandler - .thumb_set I2C1_EV_IRQHandler,Default_Handler - - .weak I2C1_ER_IRQHandler - .thumb_set I2C1_ER_IRQHandler,Default_Handler - - .weak I2C2_EV_IRQHandler - .thumb_set I2C2_EV_IRQHandler,Default_Handler - - .weak I2C2_ER_IRQHandler - .thumb_set I2C2_ER_IRQHandler,Default_Handler - - .weak SPI1_IRQHandler - .thumb_set SPI1_IRQHandler,Default_Handler - - .weak SPI2_IRQHandler - .thumb_set SPI2_IRQHandler,Default_Handler - - .weak USART1_IRQHandler - .thumb_set USART1_IRQHandler,Default_Handler - - .weak USART2_IRQHandler - .thumb_set USART2_IRQHandler,Default_Handler - - .weak USART3_IRQHandler - .thumb_set USART3_IRQHandler,Default_Handler - - .weak EXTI15_10_IRQHandler - .thumb_set EXTI15_10_IRQHandler,Default_Handler - - .weak RTC_Alarm_IRQHandler - .thumb_set RTC_Alarm_IRQHandler,Default_Handler - - .weak OTG_FS_WKUP_IRQHandler - .thumb_set OTG_FS_WKUP_IRQHandler,Default_Handler - - .weak TIM8_BRK_TIM12_IRQHandler - .thumb_set TIM8_BRK_TIM12_IRQHandler,Default_Handler - - .weak TIM8_UP_TIM13_IRQHandler - .thumb_set TIM8_UP_TIM13_IRQHandler,Default_Handler - - .weak TIM8_TRG_COM_TIM14_IRQHandler - .thumb_set TIM8_TRG_COM_TIM14_IRQHandler,Default_Handler - - .weak TIM8_CC_IRQHandler - .thumb_set TIM8_CC_IRQHandler,Default_Handler - - .weak DMA1_Stream7_IRQHandler - .thumb_set DMA1_Stream7_IRQHandler,Default_Handler - - .weak FSMC_IRQHandler - .thumb_set FSMC_IRQHandler,Default_Handler - - .weak SDIO_IRQHandler - .thumb_set SDIO_IRQHandler,Default_Handler - - .weak TIM5_IRQHandler - .thumb_set TIM5_IRQHandler,Default_Handler - - .weak SPI3_IRQHandler - .thumb_set SPI3_IRQHandler,Default_Handler - - .weak UART4_IRQHandler - .thumb_set UART4_IRQHandler,Default_Handler - - .weak UART5_IRQHandler - .thumb_set UART5_IRQHandler,Default_Handler - - .weak TIM6_DAC_IRQHandler - .thumb_set TIM6_DAC_IRQHandler,Default_Handler - - .weak TIM7_IRQHandler - .thumb_set TIM7_IRQHandler,Default_Handler - - .weak DMA2_Stream0_IRQHandler - .thumb_set DMA2_Stream0_IRQHandler,Default_Handler - - .weak DMA2_Stream1_IRQHandler - .thumb_set DMA2_Stream1_IRQHandler,Default_Handler - - .weak DMA2_Stream2_IRQHandler - .thumb_set DMA2_Stream2_IRQHandler,Default_Handler - - .weak DMA2_Stream3_IRQHandler - .thumb_set DMA2_Stream3_IRQHandler,Default_Handler - - .weak DMA2_Stream4_IRQHandler - .thumb_set DMA2_Stream4_IRQHandler,Default_Handler - - .weak CAN2_TX_IRQHandler - .thumb_set CAN2_TX_IRQHandler,Default_Handler - - .weak CAN2_RX0_IRQHandler - .thumb_set CAN2_RX0_IRQHandler,Default_Handler - - .weak CAN2_RX1_IRQHandler - .thumb_set CAN2_RX1_IRQHandler,Default_Handler - - .weak CAN2_SCE_IRQHandler - .thumb_set CAN2_SCE_IRQHandler,Default_Handler - - .weak OTG_FS_IRQHandler - .thumb_set OTG_FS_IRQHandler,Default_Handler - - .weak DMA2_Stream5_IRQHandler - .thumb_set DMA2_Stream5_IRQHandler,Default_Handler - - .weak DMA2_Stream6_IRQHandler - .thumb_set DMA2_Stream6_IRQHandler,Default_Handler - - .weak DMA2_Stream7_IRQHandler - .thumb_set DMA2_Stream7_IRQHandler,Default_Handler - - .weak USART6_IRQHandler - .thumb_set USART6_IRQHandler,Default_Handler - - .weak I2C3_EV_IRQHandler - .thumb_set I2C3_EV_IRQHandler,Default_Handler - - .weak I2C3_ER_IRQHandler - .thumb_set I2C3_ER_IRQHandler,Default_Handler - - .weak OTG_HS_EP1_OUT_IRQHandler - .thumb_set OTG_HS_EP1_OUT_IRQHandler,Default_Handler - - .weak OTG_HS_EP1_IN_IRQHandler - .thumb_set OTG_HS_EP1_IN_IRQHandler,Default_Handler - - .weak OTG_HS_WKUP_IRQHandler - .thumb_set OTG_HS_WKUP_IRQHandler,Default_Handler - - .weak OTG_HS_IRQHandler - .thumb_set OTG_HS_IRQHandler,Default_Handler - - .weak HASH_RNG_IRQHandler - .thumb_set HASH_RNG_IRQHandler,Default_Handler - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/board/stm32fx/stm32f2_flash.ld b/board/stm32fx/stm32f2_flash.ld deleted file mode 100644 index bdc23bc8ce..0000000000 --- a/board/stm32fx/stm32f2_flash.ld +++ /dev/null @@ -1,165 +0,0 @@ -/* -***************************************************************************** -** -** File : stm32f4_flash.ld -** -** Abstract : Linker script for STM32F407VG Device with -** 1024KByte FLASH, 192KByte RAM -** -** Set heap size, stack size and stack location according -** to application requirements. -** -** Set memory bank area and size if external memory is used. -** -** Target : STMicroelectronics STM32 -** -** Environment : Atollic TrueSTUDIO(R) -** -** Distribution: The file is distributed "as is," without any warranty -** of any kind. -** -** (c)Copyright Atollic AB. -** You may use this file as-is or modify it according to the needs of your -** project. Distribution of this file (unmodified or modified) is not -** permitted. Atollic AB permit registered Atollic TrueSTUDIO(R) users the -** rights to distribute the assembled, compiled & linked contents of this -** file as part of an application binary file, provided that it is built -** using the Atollic TrueSTUDIO(R) toolchain. -** -***************************************************************************** -*/ - -/* Entry Point */ -ENTRY(Reset_Handler) - -/* Highest address of the user mode stack */ -enter_bootloader_mode = 0x2001FFFC; -_estack = 0x2001FFFC; /* end of 128K RAM on AHB bus*/ -_app_start = 0x08004000; /* Reserve Sector 0(16K) for bootloader */ - -/* Generate a link error if heap and stack don't fit into RAM */ -_Min_Heap_Size = 0; /* required amount of heap */ -_Min_Stack_Size = 0x400; /* required amount of stack */ - -/* Specify the memory areas */ -MEMORY -{ - FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 128K - RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 128K - MEMORY_B1 (rx) : ORIGIN = 0x60000000, LENGTH = 0K -} - -/* Define output sections */ -SECTIONS -{ - /* The startup code goes first into FLASH */ - .isr_vector : - { - . = ALIGN(4); - KEEP(*(.isr_vector)) /* Startup code */ - . = ALIGN(4); - } >FLASH - - /* The program code and other data goes into FLASH */ - .text : - { - . = ALIGN(4); - *(.text) /* .text sections (code) */ - *(.text*) /* .text* sections (code) */ - *(.rodata) /* .rodata sections (constants, strings, etc.) */ - *(.rodata*) /* .rodata* sections (constants, strings, etc.) */ - *(.glue_7) /* glue arm to thumb code */ - *(.glue_7t) /* glue thumb to arm code */ - *(.eh_frame) - - KEEP (*(.init)) - KEEP (*(.fini)) - - . = ALIGN(4); - _etext = .; /* define a global symbols at end of code */ - _exit = .; - } >FLASH - - - .ARM.extab : { *(.ARM.extab* .gnu.linkonce.armextab.*) } >FLASH - .ARM : { - __exidx_start = .; - *(.ARM.exidx*) - __exidx_end = .; - } >FLASH - - .preinit_array : - { - PROVIDE_HIDDEN (__preinit_array_start = .); - KEEP (*(.preinit_array*)) - PROVIDE_HIDDEN (__preinit_array_end = .); - } >FLASH - .init_array : - { - PROVIDE_HIDDEN (__init_array_start = .); - KEEP (*(SORT(.init_array.*))) - KEEP (*(.init_array*)) - PROVIDE_HIDDEN (__init_array_end = .); - } >FLASH - .fini_array : - { - PROVIDE_HIDDEN (__fini_array_start = .); - KEEP (*(.fini_array*)) - KEEP (*(SORT(.fini_array.*))) - PROVIDE_HIDDEN (__fini_array_end = .); - } >FLASH - - /* used by the startup to initialize data */ - _sidata = .; - - /* Initialized data sections goes into RAM, load LMA copy after code */ - .data : AT ( _sidata ) - { - . = ALIGN(4); - _sdata = .; /* create a global symbol at data start */ - *(.data) /* .data sections */ - *(.data*) /* .data* sections */ - - . = ALIGN(4); - _edata = .; /* define a global symbol at data end */ - } >RAM - - /* Uninitialized data section */ - . = ALIGN(4); - .bss : - { - /* This is used by the startup in order to initialize the .bss secion */ - _sbss = .; /* define a global symbol at bss start */ - __bss_start__ = _sbss; - *(.bss) - *(.bss*) - *(COMMON) - - . = ALIGN(4); - _ebss = .; /* define a global symbol at bss end */ - __bss_end__ = _ebss; - } >RAM - - /* User_heap_stack section, used to check that there is enough RAM left */ - ._user_heap_stack : - { - . = ALIGN(4); - PROVIDE ( end = . ); - PROVIDE ( _end = . ); - . = . + _Min_Heap_Size; - . = . + _Min_Stack_Size; - . = ALIGN(4); - } >RAM - - /* MEMORY_bank1 section, code must be located here explicitly */ - /* Example: extern int foo(void) __attribute__ ((section (".mb1text"))); */ - .memory_b1_text : - { - *(.mb1text) /* .mb1text sections (code) */ - *(.mb1text*) /* .mb1text* sections (code) */ - *(.mb1rodata) /* read-only data (constants) */ - *(.mb1rodata*) - } >MEMORY_B1 - - .ARM.attributes 0 : { *(.ARM.attributes) } -} From b66eaa2beb7f3ea95a5e8e8cacd9fda129fe22d1 Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Sat, 17 Feb 2024 12:32:48 -0800 Subject: [PATCH 03/15] HITL tests: no xdist (#1874) --- Jenkinsfile | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index cbb20d192f..25b8490a00 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -82,7 +82,7 @@ pipeline { ["build", "scons -j4"], ["flash", "cd tests/ && ./reflash_internal_panda.py"], ["flash jungle", "cd board/jungle && ./flash.py"], - ["test", "cd tests/hitl && HW_TYPES=6 pytest --durations=0 [2-7]*.py -k 'not test_send_recv'"], + ["test", "cd tests/hitl && HW_TYPES=6 pytest -n0 --durations=0 [2-7]*.py -k 'not test_send_recv'"], ]) } } @@ -94,7 +94,7 @@ pipeline { ["build", "scons -j4"], ["flash", "cd tests/ && ./reflash_internal_panda.py"], ["flash jungle", "cd board/jungle && ./flash.py"], - ["test", "cd tests/hitl && HW_TYPES=9 pytest --durations=0 2*.py [5-9]*.py"], + ["test", "cd tests/hitl && HW_TYPES=9 pytest -n0 --durations=0 2*.py [5-9]*.py"], ]) } } @@ -126,7 +126,7 @@ pipeline { stage('bootkick tests') { steps { script { - docker_run("test", 10, "pytest ./tests/som/test_bootkick.py") + docker_run("test", 10, "pytest -n0 ./tests/som/test_bootkick.py") } } } From 997b0753499294cf3a4a752ae73f874224263b76 Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Sat, 17 Feb 2024 12:53:28 -0800 Subject: [PATCH 04/15] misra: catch more cppcheck errors that don't change exit code --- tests/misra/test_misra.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/misra/test_misra.sh b/tests/misra/test_misra.sh index 0798058e64..35a98db215 100755 --- a/tests/misra/test_misra.sh +++ b/tests/misra/test_misra.sh @@ -39,7 +39,7 @@ cppcheck() { # cppcheck bug: some MISRA errors won't result in the error exit code, # so check the output (https://trac.cppcheck.net/ticket/12440#no1) - if grep "misra violation" $OUTPUT > /dev/null; then + if grep -e "misra violation" -e "error" $OUTPUT > /dev/null; then exit 1 fi } From 6eed0364733d03851bd0df86f9be869592526d7c Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Sat, 17 Feb 2024 14:16:15 -0800 Subject: [PATCH 05/15] (almost) enable cppcheck unusedFunction (#1875) * remove some unused * more * kinda works * rest are false positives * disable for now * add back exhaustive --- board/boards/dos.h | 4 ---- board/boards/unused_funcs.h | 4 ---- board/bootstub.c | 1 + board/drivers/gmlan_alt.h | 26 -------------------------- board/drivers/interrupts.h | 2 +- board/drivers/uart.h | 15 --------------- board/flasher.h | 27 --------------------------- board/provision.h | 6 ------ board/stm32fx/lluart.h | 29 ----------------------------- tests/libpanda/safety_helpers.h | 10 ---------- tests/misra/suppressions.txt | 6 +++--- tests/misra/test_misra.sh | 21 ++++++++++++++------- 12 files changed, 19 insertions(+), 132 deletions(-) diff --git a/board/boards/dos.h b/board/boards/dos.h index d0a9bbaf49..428bbf2a5e 100644 --- a/board/boards/dos.h +++ b/board/boards/dos.h @@ -90,10 +90,6 @@ bool dos_check_ignition(void){ return harness_check_ignition(); } -void dos_set_usb_switch(bool phone){ - set_gpio_output(GPIOB, 3, phone); -} - void dos_set_ir_power(uint8_t percentage){ pwm_set(TIM4, 2, percentage); } diff --git a/board/boards/unused_funcs.h b/board/boards/unused_funcs.h index 689b5b7c42..7bfde01391 100644 --- a/board/boards/unused_funcs.h +++ b/board/boards/unused_funcs.h @@ -13,10 +13,6 @@ void unused_set_siren(bool enabled) { UNUSED(enabled); } -uint32_t unused_read_voltage(void) { - return 0U; -} - uint32_t unused_read_current(void) { return 0U; } diff --git a/board/bootstub.c b/board/bootstub.c index e2977e938c..aee665e7e0 100644 --- a/board/bootstub.c +++ b/board/bootstub.c @@ -19,6 +19,7 @@ #include "obj/gitversion.h" #include "flasher.h" +// cppcheck-suppress unusedFunction ; used in headers not included in cppcheck void __initialize_hardware_early(void) { early_initialization(); } diff --git a/board/drivers/gmlan_alt.h b/board/drivers/gmlan_alt.h index 407062bbbd..a4377a675e 100644 --- a/board/drivers/gmlan_alt.h +++ b/board/drivers/gmlan_alt.h @@ -147,32 +147,6 @@ int inverted_bit_to_send = GMLAN_HIGH; int gmlan_switch_below_timeout = -1; int gmlan_switch_timeout_enable = 0; -void gmlan_switch_init(int timeout_enable) { - gmlan_switch_timeout_enable = timeout_enable; - gmlan_alt_mode = GPIO_SWITCH; - gmlan_switch_below_timeout = 1; - set_gpio_mode(GPIOB, 13, MODE_OUTPUT); - - setup_timer(); - - inverted_bit_to_send = GMLAN_LOW; //We got initialized, set the output low -} - -void set_gmlan_digital_output(int to_set) { - inverted_bit_to_send = to_set; - /* - print("Writing "); - puth(inverted_bit_to_send); - print("\n"); - */ -} - -void reset_gmlan_switch_timeout(void) { - can_timeout_counter = GMLAN_TICKS_PER_SECOND; - gmlan_switch_below_timeout = 1; - gmlan_alt_mode = GPIO_SWITCH; -} - void set_bitbanged_gmlan(int val) { if (val != 0) { register_set_bits(&(GPIOB->ODR), (1UL << 13)); diff --git a/board/drivers/interrupts.h b/board/drivers/interrupts.h index 9cb46d4b29..79c87cccc2 100644 --- a/board/drivers/interrupts.h +++ b/board/drivers/interrupts.h @@ -78,7 +78,7 @@ void interrupt_timer_handler(void) { // Calculate interrupt load // The bootstub does not have the FPU enabled, so can't do float operations. -#if !defined(PEDAL) && !defined(BOOTSTUB) +#if !defined(BOOTSTUB) interrupt_load = ((busy_time + idle_time) > 0U) ? ((float) busy_time) / (busy_time + idle_time) : 0.0f; #endif idle_time = 0U; diff --git a/board/drivers/uart.h b/board/drivers/uart.h index e37dfcd6bd..01d8c2ac05 100644 --- a/board/drivers/uart.h +++ b/board/drivers/uart.h @@ -129,21 +129,6 @@ bool put_char(uart_ring *q, char elem) { return ret; } -// Seems dangerous to use (might lock CPU if called with interrupts disabled f.e.) -// TODO: Remove? Not used anyways -void uart_flush(const uart_ring *q) { - while (q->w_ptr_tx != q->r_ptr_tx) { - __WFI(); - } -} - -void uart_flush_sync(uart_ring *q) { - // empty the TX buffer - while (q->w_ptr_tx != q->r_ptr_tx) { - uart_tx_ring(q); - } -} - void clear_uart_buff(uart_ring *q) { ENTER_CRITICAL(); q->w_ptr_tx = 0; diff --git a/board/flasher.h b/board/flasher.h index 52906f9df1..d6c2c40211 100644 --- a/board/flasher.h +++ b/board/flasher.h @@ -4,10 +4,6 @@ bool unlocked = false; void spi_init(void); -#ifdef uart_ring -void debug_ring_callback(uart_ring *ring) {} -#endif - int comms_control_handler(ControlPacket_t *req, uint8_t *resp) { int resp_len = 0; @@ -120,29 +116,6 @@ void comms_endpoint2_write(const uint8_t *data, uint32_t len) { } -int spi_cb_rx(uint8_t *data, int len, uint8_t *data_out) { - UNUSED(len); - ControlPacket_t control_req; - - int resp_len = 0; - switch (data[0]) { - case 0: - // control transfer - control_req.request = ((USB_Setup_TypeDef *)(data+4))->b.bRequest; - control_req.param1 = ((USB_Setup_TypeDef *)(data+4))->b.wValue.w; - control_req.param2 = ((USB_Setup_TypeDef *)(data+4))->b.wIndex.w; - control_req.length = ((USB_Setup_TypeDef *)(data+4))->b.wLength.w; - - resp_len = comms_control_handler(&control_req, data_out); - break; - case 2: - // ep 2, flash! - comms_endpoint2_write(data+4, data[2]); - break; - } - return resp_len; -} - void soft_flasher_start(void) { print("\n\n\n************************ FLASHER START ************************\n"); diff --git a/board/provision.h b/board/provision.h index db22ff63fa..02768c93d0 100644 --- a/board/provision.h +++ b/board/provision.h @@ -11,9 +11,3 @@ void get_provision_chunk(uint8_t *resp) { (void)memcpy(resp, "unprovisioned\x00\x00\x00testing123\x00\x00\xa3\xa6\x99\xec", 0x20); } } - -uint8_t chunk[PROVISION_CHUNK_LEN]; -bool is_provisioned(void) { - (void)memcpy(chunk, (uint8_t *)PROVISION_CHUNK_ADDRESS, PROVISION_CHUNK_LEN); - return (memcmp(chunk, unprovisioned_text, 0x20) != 0); -} diff --git a/board/stm32fx/lluart.h b/board/stm32fx/lluart.h index 1e4e9015df..ffe7e74da0 100644 --- a/board/stm32fx/lluart.h +++ b/board/stm32fx/lluart.h @@ -90,32 +90,3 @@ void USART2_IRQ_Handler(void) { uart_interrupt_handler(&uart_ring_debug); } void uart_set_baud(USART_TypeDef *u, unsigned int baud) { u->BRR = USART_BRR_(APB1_FREQ*1000000U, baud); } - -void uart_init(uart_ring *q, int baud) { - if(q->uart != NULL){ - // Register interrupts (max data rate: 115200 baud) - if (q->uart == USART2){ - REGISTER_INTERRUPT(USART2_IRQn, USART2_IRQ_Handler, 150000U, FAULT_INTERRUPT_RATE_UART_2) - } else { - // UART not used. Skip registering interrupts - } - - // Set baud and enable peripheral with TX and RX mode - uart_set_baud(q->uart, baud); - q->uart->CR1 = USART_CR1_UE | USART_CR1_TE | USART_CR1_RE; - if ((q->uart == USART2) || (q->uart == USART3) || (q->uart == UART5)) { - q->uart->CR1 |= USART_CR1_RXNEIE; - } - - // Enable UART interrupts - if (q->uart == USART2){ - NVIC_EnableIRQ(USART2_IRQn); - } else if (q->uart == USART3){ - NVIC_EnableIRQ(USART3_IRQn); - } else if (q->uart == UART5){ - NVIC_EnableIRQ(UART5_IRQn); - } else { - // UART not used. Skip enabling interrupts - } - } -} diff --git a/tests/libpanda/safety_helpers.h b/tests/libpanda/safety_helpers.h index ae150a8389..074463d319 100644 --- a/tests/libpanda/safety_helpers.h +++ b/tests/libpanda/safety_helpers.h @@ -193,13 +193,3 @@ void init_tests(void){ valid_steer_req_count = 0; invalid_steer_req_count = 0; } - -void set_gmlan_digital_output(int to_set){ -} - -void reset_gmlan_switch_timeout(void){ -} - -void gmlan_switch_init(int timeout_enable){ -} - diff --git a/tests/misra/suppressions.txt b/tests/misra/suppressions.txt index 2c91f868ab..d79064f1f2 100644 --- a/tests/misra/suppressions.txt +++ b/tests/misra/suppressions.txt @@ -12,12 +12,12 @@ misra-c2012-20.10 # needed since not all of these suppressions are applicable to all builds unmatchedSuppression +# All interrupt handlers are defined, including ones we don't use +unusedFunction:*/interrupt_handlers*.h + # all of the below suppressions are from new checks introduced after updating # cppcheck from 2.5 -> 2.13. they are listed here to separate the update from # fixing the violations and all are intended to be removed soon after - -unusedFunction - misra-config misra-c2012-1.2 # this is from the extensions (e.g. __typeof__) used in the MIN, MAX, ABS, and CLAMP macros misra-c2012-2.5 diff --git a/tests/misra/test_misra.sh b/tests/misra/test_misra.sh index 35a98db215..15bd6aca8a 100755 --- a/tests/misra/test_misra.sh +++ b/tests/misra/test_misra.sh @@ -2,7 +2,7 @@ set -e DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" -PANDA_DIR=$DIR/../../ +PANDA_DIR=$(realpath $DIR/../../) GREEN="\e[1;32m" NC='\033[0m' @@ -31,23 +31,30 @@ fi cppcheck() { # note that cppcheck build cache results in inconsistent results as of v2.13.0 OUTPUT=$DIR/.output.log - $CPPCHECK_DIR/cppcheck --enable=all --force --inline-suppr -I $PANDA_DIR/board/ \ + $CPPCHECK_DIR/cppcheck --force --inline-suppr -I $PANDA_DIR/board/ \ -I $gcc_inc "$(arm-none-eabi-gcc -print-file-name=include)" \ --suppressions-list=$DIR/suppressions.txt --suppress=*:*inc/* \ - --suppress=*:*include/* --error-exitcode=2 --addon=misra \ - --check-level=exhaustive "$@" |& tee $OUTPUT + --suppress=*:*include/* --error-exitcode=2 --check-level=exhaustive \ + "$@" |& tee $OUTPUT # cppcheck bug: some MISRA errors won't result in the error exit code, # so check the output (https://trac.cppcheck.net/ticket/12440#no1) - if grep -e "misra violation" -e "error" $OUTPUT > /dev/null; then + if grep -e "misra violation" -e "error" -e "style: " $OUTPUT > /dev/null; then exit 1 fi } +PANDA_OPTS="--enable=all --disable=unusedFunction -DPANDA --addon=misra" + printf "\n${GREEN}** PANDA F4 CODE **${NC}\n" -cppcheck -DPANDA -DSTM32F4 -DUID_BASE $PANDA_DIR/board/main.c +cppcheck $PANDA_OPTS -DSTM32F4 -DUID_BASE $PANDA_DIR/board/main.c printf "\n${GREEN}** PANDA H7 CODE **${NC}\n" -cppcheck -DPANDA -DSTM32H7 -DUID_BASE $PANDA_DIR/board/main.c +cppcheck $PANDA_OPTS -DSTM32H7 -DUID_BASE $PANDA_DIR/board/main.c + +# unused needs to run globally +#printf "\n${GREEN}** UNUSED ALL CODE **${NC}\n" +#cppcheck --enable=unusedFunction --quiet $PANDA_DIR/board/ printf "\n${GREEN}Success!${NC} took $SECONDS seconds\n" + From 00fab5e18e6d14378abb755d49221fc605195741 Mon Sep 17 00:00:00 2001 From: Jason Young <46612682+jyoung8607@users.noreply.github.com> Date: Sun, 18 Feb 2024 14:03:30 -0500 Subject: [PATCH 06/15] refactor GET_BIT to be MISRA friendly (#1877) * refactor GET_BIT to be MISRA friendly * better fix for ternary op * remove whitespace that crept in --- board/safety/safety_chrysler.h | 4 ++-- board/safety/safety_ford.h | 8 ++++---- board/safety/safety_gm.h | 6 +++--- board/safety/safety_honda.h | 12 ++++++------ board/safety/safety_hyundai.h | 14 +++++++------- board/safety/safety_hyundai_canfd.h | 8 ++++---- board/safety/safety_subaru.h | 8 ++++---- board/safety/safety_subaru_preglobal.h | 4 ++-- board/safety/safety_toyota.h | 18 +++++++++--------- board/safety/safety_volkswagen_mqb.h | 4 ++-- board/safety/safety_volkswagen_pq.h | 2 +- board/safety_declarations.h | 2 +- 12 files changed, 45 insertions(+), 45 deletions(-) diff --git a/board/safety/safety_chrysler.h b/board/safety/safety_chrysler.h index 1e11871286..fa0e1532d5 100644 --- a/board/safety/safety_chrysler.h +++ b/board/safety/safety_chrysler.h @@ -185,7 +185,7 @@ static void chrysler_rx_hook(const CANPacket_t *to_push) { // enter controls on rising edge of ACC, exit controls on ACC off const int das_3_bus = (chrysler_platform == CHRYSLER_PACIFICA) ? 0 : 2; if ((bus == das_3_bus) && (addr == chrysler_addrs->DAS_3)) { - bool cruise_engaged = GET_BIT(to_push, 21U) == 1U; + bool cruise_engaged = GET_BIT(to_push, 21U); pcm_cruise_check(cruise_engaged); } @@ -226,7 +226,7 @@ static bool chrysler_tx_hook(const CANPacket_t *to_send) { const SteeringLimits limits = (chrysler_platform == CHRYSLER_PACIFICA) ? CHRYSLER_STEERING_LIMITS : (chrysler_platform == CHRYSLER_RAM_DT) ? CHRYSLER_RAM_DT_STEERING_LIMITS : CHRYSLER_RAM_HD_STEERING_LIMITS; - bool steer_req = (chrysler_platform == CHRYSLER_PACIFICA) ? (GET_BIT(to_send, 4U) != 0U) : ((GET_BYTE(to_send, 3) & 0x7U) == 2U); + bool steer_req = (chrysler_platform == CHRYSLER_PACIFICA) ? GET_BIT(to_send, 4U) : (GET_BYTE(to_send, 3) & 0x7U) == 2U; if (steer_torque_cmd_checks(desired_torque, steer_req, limits)) { tx = false; } diff --git a/board/safety/safety_ford.h b/board/safety/safety_ford.h index 0424b9d09c..2f11863b49 100644 --- a/board/safety/safety_ford.h +++ b/board/safety/safety_ford.h @@ -280,7 +280,7 @@ static bool ford_tx_hook(const CANPacket_t *to_send) { // Signal: AccBrkTot_A_Rq int accel = ((GET_BYTE(to_send, 0) & 0x1FU) << 8) | GET_BYTE(to_send, 1); // Signal: CmbbDeny_B_Actl - int cmbb_deny = GET_BIT(to_send, 37U); + bool cmbb_deny = GET_BIT(to_send, 37U); bool violation = false; violation |= longitudinal_accel_checks(accel, FORD_LONG_LIMITS); @@ -288,7 +288,7 @@ static bool ford_tx_hook(const CANPacket_t *to_send) { violation |= longitudinal_gas_checks(gas_pred, FORD_LONG_LIMITS); // Safety check for stock AEB - violation |= cmbb_deny != 0; // do not prevent stock AEB actuation + violation |= cmbb_deny; // do not prevent stock AEB actuation if (violation) { tx = false; @@ -302,8 +302,8 @@ static bool ford_tx_hook(const CANPacket_t *to_send) { // Violation if resume button is pressed while controls not allowed, or // if cancel button is pressed when cruise isn't engaged. bool violation = false; - violation |= (GET_BIT(to_send, 8U) == 1U) && !cruise_engaged_prev; // Signal: CcAslButtnCnclPress (cancel) - violation |= (GET_BIT(to_send, 25U) == 1U) && !controls_allowed; // Signal: CcAsllButtnResPress (resume) + violation |= GET_BIT(to_send, 8U) && !cruise_engaged_prev; // Signal: CcAslButtnCnclPress (cancel) + violation |= GET_BIT(to_send, 25U) && !controls_allowed; // Signal: CcAsllButtnResPress (resume) if (violation) { tx = false; diff --git a/board/safety/safety_gm.h b/board/safety/safety_gm.h index fd944761e6..d1e4dd216f 100644 --- a/board/safety/safety_gm.h +++ b/board/safety/safety_gm.h @@ -108,7 +108,7 @@ static void gm_rx_hook(const CANPacket_t *to_push) { } if ((addr == 0xC9) && (gm_hw == GM_CAM)) { - brake_pressed = GET_BIT(to_push, 40U) != 0U; + brake_pressed = GET_BIT(to_push, 40U); } if (addr == 0x1C4) { @@ -153,7 +153,7 @@ static bool gm_tx_hook(const CANPacket_t *to_send) { int desired_torque = ((GET_BYTE(to_send, 0) & 0x7U) << 8) + GET_BYTE(to_send, 1); desired_torque = to_signed(desired_torque, 11); - bool steer_req = (GET_BIT(to_send, 3U) != 0U); + bool steer_req = GET_BIT(to_send, 3U); if (steer_torque_cmd_checks(desired_torque, steer_req, GM_STEERING_LIMITS)) { tx = false; @@ -162,7 +162,7 @@ static bool gm_tx_hook(const CANPacket_t *to_send) { // GAS/REGEN: safety check if (addr == 0x2CB) { - bool apply = GET_BIT(to_send, 0U) != 0U; + bool apply = GET_BIT(to_send, 0U); int gas_regen = ((GET_BYTE(to_send, 2) & 0x7FU) << 5) + ((GET_BYTE(to_send, 3) & 0xF8U) >> 3); bool violation = false; diff --git a/board/safety/safety_honda.h b/board/safety/safety_honda.h index 968a1a446d..3881db745e 100644 --- a/board/safety/safety_honda.h +++ b/board/safety/safety_honda.h @@ -166,7 +166,7 @@ static void honda_rx_hook(const CANPacket_t *to_push) { // enter controls when PCM enters cruise state if (pcm_cruise && (addr == 0x17C)) { - const bool cruise_engaged = GET_BIT(to_push, 38U) != 0U; + const bool cruise_engaged = GET_BIT(to_push, 38U); // engage on rising edge if (cruise_engaged && !cruise_engaged_prev) { controls_allowed = true; @@ -207,13 +207,13 @@ static void honda_rx_hook(const CANPacket_t *to_push) { // accord, crv: 0x1BE if (honda_alt_brake_msg) { if (addr == 0x1BE) { - brake_pressed = GET_BIT(to_push, 4U) != 0U; + brake_pressed = GET_BIT(to_push, 4U); } } else { if (addr == 0x17C) { // also if brake switch is 1 for two CAN frames, as brake pressed is delayed - const bool brake_switch = GET_BIT(to_push, 32U) != 0U; - brake_pressed = (GET_BIT(to_push, 53U) != 0U) || (brake_switch && honda_brake_switch_prev); + const bool brake_switch = GET_BIT(to_push, 32U); + brake_pressed = (GET_BIT(to_push, 53U)) || (brake_switch && honda_brake_switch_prev); honda_brake_switch_prev = brake_switch; } } @@ -234,7 +234,7 @@ static void honda_rx_hook(const CANPacket_t *to_push) { // disable stock Honda AEB in alternative experience if (!(alternative_experience & ALT_EXP_DISABLE_STOCK_AEB)) { if ((bus == 2) && (addr == 0x1FA)) { - bool honda_stock_aeb = GET_BIT(to_push, 29U) != 0U; + bool honda_stock_aeb = GET_BIT(to_push, 29U); int honda_stock_brake = (GET_BYTE(to_push, 0) << 2) | (GET_BYTE(to_push, 1) >> 6); // Forward AEB when stock braking is higher than openpilot braking @@ -383,7 +383,7 @@ static safety_config honda_nidec_init(uint16_t param) { enable_gas_interceptor = GET_FLAG(param, HONDA_PARAM_GAS_INTERCEPTOR); safety_config ret; - + bool enable_nidec_alt = GET_FLAG(param, HONDA_PARAM_NIDEC_ALT); if (enable_nidec_alt) { enable_gas_interceptor ? SET_RX_CHECKS(honda_nidec_alt_interceptor_rx_checks, ret) : \ diff --git a/board/safety/safety_hyundai.h b/board/safety/safety_hyundai.h index d88762c0d0..5a324bff29 100644 --- a/board/safety/safety_hyundai.h +++ b/board/safety/safety_hyundai.h @@ -178,7 +178,7 @@ static void hyundai_rx_hook(const CANPacket_t *to_push) { // ACC steering wheel buttons if (addr == 0x4F1) { int cruise_button = GET_BYTE(to_push, 0) & 0x7U; - int main_button = GET_BIT(to_push, 3U); + bool main_button = GET_BIT(to_push, 3U); hyundai_common_cruise_buttons_check(cruise_button, main_button); } @@ -221,10 +221,10 @@ static bool hyundai_tx_hook(const CANPacket_t *to_send) { // FCA11: Block any potential actuation if (addr == 0x38D) { int CR_VSM_DecCmd = GET_BYTE(to_send, 1); - int FCA_CmdAct = GET_BIT(to_send, 20U); - int CF_VSM_DecCmdAct = GET_BIT(to_send, 31U); + bool FCA_CmdAct = GET_BIT(to_send, 20U); + bool CF_VSM_DecCmdAct = GET_BIT(to_send, 31U); - if ((CR_VSM_DecCmd != 0) || (FCA_CmdAct != 0) || (CF_VSM_DecCmdAct != 0)) { + if ((CR_VSM_DecCmd != 0) || FCA_CmdAct || CF_VSM_DecCmdAct) { tx = false; } } @@ -235,14 +235,14 @@ static bool hyundai_tx_hook(const CANPacket_t *to_send) { int desired_accel_val = ((GET_BYTE(to_send, 5) << 3) | (GET_BYTE(to_send, 4) >> 5)) - 1023U; int aeb_decel_cmd = GET_BYTE(to_send, 2); - int aeb_req = GET_BIT(to_send, 54U); + bool aeb_req = GET_BIT(to_send, 54U); bool violation = false; violation |= longitudinal_accel_checks(desired_accel_raw, HYUNDAI_LONG_LIMITS); violation |= longitudinal_accel_checks(desired_accel_val, HYUNDAI_LONG_LIMITS); violation |= (aeb_decel_cmd != 0); - violation |= (aeb_req != 0); + violation |= aeb_req; if (violation) { tx = false; @@ -252,7 +252,7 @@ static bool hyundai_tx_hook(const CANPacket_t *to_send) { // LKA STEER: safety check if (addr == 0x340) { int desired_torque = ((GET_BYTES(to_send, 0, 4) >> 16) & 0x7ffU) - 1024U; - bool steer_req = GET_BIT(to_send, 27U) != 0U; + bool steer_req = GET_BIT(to_send, 27U); const SteeringLimits limits = hyundai_alt_limits ? HYUNDAI_STEERING_LIMITS_ALT : HYUNDAI_STEERING_LIMITS; if (steer_torque_cmd_checks(desired_torque, steer_req, limits)) { diff --git a/board/safety/safety_hyundai_canfd.h b/board/safety/safety_hyundai_canfd.h index be026a9840..0744a6e20e 100644 --- a/board/safety/safety_hyundai_canfd.h +++ b/board/safety/safety_hyundai_canfd.h @@ -186,15 +186,15 @@ static void hyundai_canfd_rx_hook(const CANPacket_t *to_push) { if ((addr == 0x35) && hyundai_ev_gas_signal) { gas_pressed = GET_BYTE(to_push, 5) != 0U; } else if ((addr == 0x105) && hyundai_hybrid_gas_signal) { - gas_pressed = (GET_BIT(to_push, 103U) != 0U) || (GET_BYTE(to_push, 13) != 0U) || (GET_BIT(to_push, 112U) != 0U); + gas_pressed = GET_BIT(to_push, 103U) || (GET_BYTE(to_push, 13) != 0U) || GET_BIT(to_push, 112U); } else if ((addr == 0x100) && !hyundai_ev_gas_signal && !hyundai_hybrid_gas_signal) { - gas_pressed = GET_BIT(to_push, 176U) != 0U; + gas_pressed = GET_BIT(to_push, 176U); } else { } // brake press if (addr == 0x175) { - brake_pressed = GET_BIT(to_push, 81U) != 0U; + brake_pressed = GET_BIT(to_push, 81U); } // vehicle moving @@ -235,7 +235,7 @@ static bool hyundai_canfd_tx_hook(const CANPacket_t *to_send) { const int steer_addr = (hyundai_canfd_hda2 && !hyundai_longitudinal) ? hyundai_canfd_hda2_get_lkas_addr() : 0x12a; if (addr == steer_addr) { int desired_torque = (((GET_BYTE(to_send, 6) & 0xFU) << 7U) | (GET_BYTE(to_send, 5) >> 1U)) - 1024U; - bool steer_req = GET_BIT(to_send, 52U) != 0U; + bool steer_req = GET_BIT(to_send, 52U); if (steer_torque_cmd_checks(desired_torque, steer_req, HYUNDAI_CANFD_STEERING_LIMITS)) { tx = false; diff --git a/board/safety/safety_subaru.h b/board/safety/safety_subaru.h index 201c6fe5e7..c445bc435e 100644 --- a/board/safety/safety_subaru.h +++ b/board/safety/safety_subaru.h @@ -152,7 +152,7 @@ static void subaru_rx_hook(const CANPacket_t *to_push) { // enter controls on rising edge of ACC, exit controls on ACC off if ((addr == MSG_SUBARU_CruiseControl) && (bus == alt_main_bus)) { - bool cruise_engaged = GET_BIT(to_push, 41U) != 0U; + bool cruise_engaged = GET_BIT(to_push, 41U); pcm_cruise_check(cruise_engaged); } @@ -169,7 +169,7 @@ static void subaru_rx_hook(const CANPacket_t *to_push) { } if ((addr == MSG_SUBARU_Brake_Status) && (bus == alt_main_bus)) { - brake_pressed = GET_BIT(to_push, 62U) != 0U; + brake_pressed = GET_BIT(to_push, 62U); } if ((addr == MSG_SUBARU_Throttle) && (bus == SUBARU_MAIN_BUS)) { @@ -189,7 +189,7 @@ static bool subaru_tx_hook(const CANPacket_t *to_send) { int desired_torque = ((GET_BYTES(to_send, 0, 4) >> 16) & 0x1FFFU); desired_torque = -1 * to_signed(desired_torque, 13); - bool steer_req = GET_BIT(to_send, 29U) != 0U; + bool steer_req = GET_BIT(to_send, 29U); const SteeringLimits limits = subaru_gen2 ? SUBARU_GEN2_STEERING_LIMITS : SUBARU_STEERING_LIMITS; violation |= steer_torque_cmd_checks(desired_torque, steer_req, limits); @@ -204,7 +204,7 @@ static bool subaru_tx_hook(const CANPacket_t *to_send) { // check es_distance cruise_throttle limits if (addr == MSG_SUBARU_ES_Distance) { int cruise_throttle = (GET_BYTES(to_send, 2, 2) & 0x1FFFU); - bool cruise_cancel = GET_BIT(to_send, 56U) != 0U; + bool cruise_cancel = GET_BIT(to_send, 56U); if (subaru_longitudinal) { violation |= longitudinal_gas_checks(cruise_throttle, SUBARU_LONG_LIMITS); diff --git a/board/safety/safety_subaru_preglobal.h b/board/safety/safety_subaru_preglobal.h index 37e389afb2..1549d595b3 100644 --- a/board/safety/safety_subaru_preglobal.h +++ b/board/safety/safety_subaru_preglobal.h @@ -56,7 +56,7 @@ static void subaru_preglobal_rx_hook(const CANPacket_t *to_push) { // enter controls on rising edge of ACC, exit controls on ACC off if (addr == MSG_SUBARU_PG_CruiseControl) { - bool cruise_engaged = GET_BIT(to_push, 49U) != 0U; + bool cruise_engaged = GET_BIT(to_push, 49U); pcm_cruise_check(cruise_engaged); } @@ -86,7 +86,7 @@ static bool subaru_preglobal_tx_hook(const CANPacket_t *to_send) { int desired_torque = ((GET_BYTES(to_send, 0, 4) >> 8) & 0x1FFFU); desired_torque = -1 * to_signed(desired_torque, 13); - bool steer_req = (GET_BIT(to_send, 24U) != 0U); + bool steer_req = GET_BIT(to_send, 24U); if (steer_torque_cmd_checks(desired_torque, steer_req, SUBARU_PG_STEERING_LIMITS)) { tx = false; diff --git a/board/safety/safety_toyota.h b/board/safety/safety_toyota.h index 4256f1258d..f6bfc08091 100644 --- a/board/safety/safety_toyota.h +++ b/board/safety/safety_toyota.h @@ -138,7 +138,7 @@ static bool toyota_get_quality_flag_valid(const CANPacket_t *to_push) { bool valid = false; if (addr == 0x260) { - valid = GET_BIT(to_push, 3U) == 0U; // STEER_ANGLE_INITIALIZING + valid = !GET_BIT(to_push, 3U); // STEER_ANGLE_INITIALIZING } return valid; } @@ -169,7 +169,7 @@ static void toyota_rx_hook(const CANPacket_t *to_push) { // LTA request angle should match current angle while inactive, clipped to max accepted angle. // note that angle can be relative to init angle on some TSS2 platforms, LTA has the same offset - bool steer_angle_initializing = GET_BIT(to_push, 3U) != 0U; + bool steer_angle_initializing = GET_BIT(to_push, 3U); if (!steer_angle_initializing) { int angle_meas_new = (GET_BYTE(to_push, 3) << 8U) | GET_BYTE(to_push, 4); angle_meas_new = CLAMP(to_signed(angle_meas_new, 16), -TOYOTA_LTA_MAX_ANGLE, TOYOTA_LTA_MAX_ANGLE); @@ -181,12 +181,12 @@ static void toyota_rx_hook(const CANPacket_t *to_push) { // exit controls on rising edge of gas press if (addr == 0x1D2) { // 5th bit is CRUISE_ACTIVE - bool cruise_engaged = GET_BIT(to_push, 5U) != 0U; + bool cruise_engaged = GET_BIT(to_push, 5U); pcm_cruise_check(cruise_engaged); // sample gas pedal if (!enable_gas_interceptor) { - gas_pressed = GET_BIT(to_push, 4U) == 0U; + gas_pressed = !GET_BIT(to_push, 4U); } } @@ -207,7 +207,7 @@ static void toyota_rx_hook(const CANPacket_t *to_push) { // most cars have brake_pressed on 0x226, corolla and rav4 on 0x224 if (((addr == 0x224) && toyota_alt_brake) || ((addr == 0x226) && !toyota_alt_brake)) { uint8_t bit = (addr == 0x224) ? 5U : 37U; - brake_pressed = GET_BIT(to_push, bit) != 0U; + brake_pressed = GET_BIT(to_push, bit); } // sample gas interceptor @@ -252,7 +252,7 @@ static bool toyota_tx_hook(const CANPacket_t *to_send) { // only ACC messages that cancel are allowed when openpilot is not controlling longitudinal if (toyota_stock_longitudinal) { - bool cancel_req = GET_BIT(to_send, 24U) != 0U; + bool cancel_req = GET_BIT(to_send, 24U); if (!cancel_req) { violation = true; } @@ -278,8 +278,8 @@ static bool toyota_tx_hook(const CANPacket_t *to_send) { // LTA angle steering check if (addr == 0x191) { // check the STEER_REQUEST, STEER_REQUEST_2, TORQUE_WIND_DOWN, STEER_ANGLE_CMD signals - bool lta_request = GET_BIT(to_send, 0U) != 0U; - bool lta_request2 = GET_BIT(to_send, 25U) != 0U; + bool lta_request = GET_BIT(to_send, 0U); + bool lta_request2 = GET_BIT(to_send, 25U); int torque_wind_down = GET_BYTE(to_send, 5); int lta_angle = (GET_BYTE(to_send, 1) << 8) | GET_BYTE(to_send, 2); lta_angle = to_signed(lta_angle, 16); @@ -327,7 +327,7 @@ static bool toyota_tx_hook(const CANPacket_t *to_send) { if (addr == 0x2E4) { int desired_torque = (GET_BYTE(to_send, 1) << 8) | GET_BYTE(to_send, 2); desired_torque = to_signed(desired_torque, 16); - bool steer_req = GET_BIT(to_send, 0U) != 0U; + bool steer_req = GET_BIT(to_send, 0U); // When using LTA (angle control), assert no actuation on LKA message if (!toyota_lta) { if (steer_torque_cmd_checks(desired_torque, steer_req, TOYOTA_STEERING_LIMITS)) { diff --git a/board/safety/safety_volkswagen_mqb.h b/board/safety/safety_volkswagen_mqb.h index 10adc679d2..d880a69a6e 100644 --- a/board/safety/safety_volkswagen_mqb.h +++ b/board/safety/safety_volkswagen_mqb.h @@ -170,7 +170,7 @@ static void volkswagen_mqb_rx_hook(const CANPacket_t *to_push) { } // Always exit controls on rising edge of Cancel // Signal: GRA_ACC_01.GRA_Abbrechen - if (GET_BIT(to_push, 13U) == 1U) { + if (GET_BIT(to_push, 13U)) { controls_allowed = false; } } @@ -210,7 +210,7 @@ static bool volkswagen_mqb_tx_hook(const CANPacket_t *to_send) { desired_torque *= -1; } - bool steer_req = GET_BIT(to_send, 30U) != 0U; + bool steer_req = GET_BIT(to_send, 30U); if (steer_torque_cmd_checks(desired_torque, steer_req, VOLKSWAGEN_MQB_STEERING_LIMITS)) { tx = false; diff --git a/board/safety/safety_volkswagen_pq.h b/board/safety/safety_volkswagen_pq.h index b9a2eedd72..1922cf4671 100644 --- a/board/safety/safety_volkswagen_pq.h +++ b/board/safety/safety_volkswagen_pq.h @@ -141,7 +141,7 @@ static void volkswagen_pq_rx_hook(const CANPacket_t *to_push) { volkswagen_resume_button_prev = resume_button; // Exit controls on rising edge of Cancel, override Set/Resume if present simultaneously // Signal: GRA_ACC_01.GRA_Abbrechen - if (GET_BIT(to_push, 9U) == 1U) { + if (GET_BIT(to_push, 9U)) { controls_allowed = false; } } diff --git a/board/safety_declarations.h b/board/safety_declarations.h index eb4ece4741..39dcabf9b9 100644 --- a/board/safety_declarations.h +++ b/board/safety_declarations.h @@ -1,6 +1,6 @@ #pragma once -#define GET_BIT(msg, b) (((msg)->data[((b) / 8U)] >> ((b) % 8U)) & 0x1U) +#define GET_BIT(msg, b) ((bool)!!(((msg)->data[((b) / 8U)] >> ((b) % 8U)) & 0x1U)) #define GET_BYTE(msg, b) ((msg)->data[(b)]) #define GET_FLAG(value, mask) (((__typeof__(mask))(value) & (mask)) == (mask)) From 546db7b73b7917474c2220ba8e2584472eadd54e Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Sun, 18 Feb 2024 11:43:25 -0800 Subject: [PATCH 07/15] set cppcheck platform --- tests/misra/test_misra.sh | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/misra/test_misra.sh b/tests/misra/test_misra.sh index 15bd6aca8a..9fdbea1df7 100755 --- a/tests/misra/test_misra.sh +++ b/tests/misra/test_misra.sh @@ -35,6 +35,7 @@ cppcheck() { -I $gcc_inc "$(arm-none-eabi-gcc -print-file-name=include)" \ --suppressions-list=$DIR/suppressions.txt --suppress=*:*inc/* \ --suppress=*:*include/* --error-exitcode=2 --check-level=exhaustive \ + --platform=arm32-wchar_t2 \ "$@" |& tee $OUTPUT # cppcheck bug: some MISRA errors won't result in the error exit code, From b4442a7c930aac112cdd82cddfc3dd12254a56e1 Mon Sep 17 00:00:00 2001 From: Aryan <53595853+0x41head@users.noreply.github.com> Date: Mon, 19 Feb 2024 01:26:44 +0530 Subject: [PATCH 08/15] enable misra-c2012-10.3 (#1852) * enable misra-c2012-10.3 * fix that * cleanup * little more * one more --------- Co-authored-by: Adeeb Shihadeh --- board/drivers/can_common.h | 4 ++-- board/drivers/gmlan_alt.h | 4 ++-- board/drivers/interrupts.h | 2 +- board/drivers/usb.h | 6 +++--- board/main_comms.h | 2 +- board/safety.h | 4 ++-- board/safety/safety_gm.h | 2 +- board/safety/safety_honda.h | 8 ++++---- board/safety/safety_hyundai_canfd.h | 2 +- board/safety/safety_hyundai_common.h | 7 +++---- board/safety/safety_nissan.h | 4 ++-- board/safety/safety_subaru_preglobal.h | 2 +- board/safety/safety_toyota.h | 6 +++--- board/safety_declarations.h | 2 +- board/stm32h7/llfdcan.h | 8 ++++---- tests/misra/suppressions.txt | 1 - 16 files changed, 31 insertions(+), 33 deletions(-) diff --git a/board/drivers/can_common.h b/board/drivers/can_common.h index db77617e75..bc9adde7ce 100644 --- a/board/drivers/can_common.h +++ b/board/drivers/can_common.h @@ -28,8 +28,8 @@ extern int can_live; extern int pending_can_live; // must reinit after changing these -extern int can_loopback; extern int can_silent; +extern bool can_loopback; // Ignition detected from CAN meessages bool ignition_can = false; @@ -40,8 +40,8 @@ uint32_t ignition_can_cnt = 0U; int can_live = 0; int pending_can_live = 0; -int can_loopback = 0; int can_silent = ALL_CAN_SILENT; +bool can_loopback = false; // ******************* functions prototypes ********************* bool can_init(uint8_t can_number); diff --git a/board/drivers/gmlan_alt.h b/board/drivers/gmlan_alt.h index a4377a675e..2dbc381bd2 100644 --- a/board/drivers/gmlan_alt.h +++ b/board/drivers/gmlan_alt.h @@ -26,14 +26,14 @@ int do_bitstuff(char *out, const char *in, int in_len) { bit_cnt++; if (bit_cnt == 5) { // 5 in a row the same, do stuff - last_bit = !bit; + last_bit = !bit ? 1 : 0; out[j] = last_bit; j++; bit_cnt = 1; } } else { // this is a new bit - last_bit = bit; + last_bit = (int)bit; bit_cnt = 1; } } diff --git a/board/drivers/interrupts.h b/board/drivers/interrupts.h index 79c87cccc2..d4c72be1df 100644 --- a/board/drivers/interrupts.h +++ b/board/drivers/interrupts.h @@ -79,7 +79,7 @@ void interrupt_timer_handler(void) { // Calculate interrupt load // The bootstub does not have the FPU enabled, so can't do float operations. #if !defined(BOOTSTUB) - interrupt_load = ((busy_time + idle_time) > 0U) ? ((float) busy_time) / (busy_time + idle_time) : 0.0f; + interrupt_load = ((busy_time + idle_time) > 0U) ? ((float) (((float) busy_time) / (busy_time + idle_time))) : 0.0f; #endif idle_time = 0U; busy_time = 0U; diff --git a/board/drivers/usb.h b/board/drivers/usb.h index dec7ba8122..1872dd5276 100644 --- a/board/drivers/usb.h +++ b/board/drivers/usb.h @@ -461,12 +461,12 @@ void usb_reset(void) { USBx_OUTEP(0)->DOEPTSIZ = USB_OTG_DOEPTSIZ_STUPCNT | (USB_OTG_DOEPTSIZ_PKTCNT & (1UL << 19)) | (3U << 3); } -char to_hex_char(int a) { +char to_hex_char(uint8_t a) { char ret; - if (a < 10) { + if (a < 10U) { ret = '0' + a; } else { - ret = 'a' + (a - 10); + ret = 'a' + (a - 10U); } return ret; } diff --git a/board/main_comms.h b/board/main_comms.h index 096f7b1a89..c0d5c516fb 100644 --- a/board/main_comms.h +++ b/board/main_comms.h @@ -360,7 +360,7 @@ int comms_control_handler(ControlPacket_t *req, uint8_t *resp) { break; // **** 0xe5: set CAN loopback (for testing) case 0xe5: - can_loopback = (req->param1 > 0U); + can_loopback = req->param1 > 0U; can_init_all(); break; // **** 0xe6: set custom clock source period diff --git a/board/safety.h b/board/safety.h index 50669e3bfb..1e95244099 100644 --- a/board/safety.h +++ b/board/safety.h @@ -94,8 +94,8 @@ bool get_longitudinal_allowed(void) { // Given a CRC-8 poly, generate a static lookup table to use with a fast CRC-8 // algorithm. Called at init time for safety modes using CRC-8. void gen_crc_lookup_table_8(uint8_t poly, uint8_t crc_lut[]) { - for (int i = 0; i < 256; i++) { - uint8_t crc = i; + for (uint16_t i = 0U; i <= 0xFFU; i++) { + uint8_t crc = (uint8_t)i; for (int j = 0; j < 8; j++) { if ((crc & 0x80U) != 0U) { crc = (uint8_t)((crc << 1) ^ poly); diff --git a/board/safety/safety_gm.h b/board/safety/safety_gm.h index d1e4dd216f..82a5d9cd3e 100644 --- a/board/safety/safety_gm.h +++ b/board/safety/safety_gm.h @@ -204,7 +204,7 @@ static int gm_fwd_hook(int bus_num, int addr) { // block lkas message and acc messages if gm_cam_long, forward all others bool is_lkas_msg = (addr == 0x180); bool is_acc_msg = (addr == 0x315) || (addr == 0x2CB) || (addr == 0x370); - int block_msg = is_lkas_msg || (is_acc_msg && gm_cam_long); + bool block_msg = is_lkas_msg || (is_acc_msg && gm_cam_long); if (!block_msg) { bus_fwd = 0; } diff --git a/board/safety/safety_honda.h b/board/safety/safety_honda.h index 3881db745e..78bbb7f0bf 100644 --- a/board/safety/safety_honda.h +++ b/board/safety/safety_honda.h @@ -114,11 +114,11 @@ static uint32_t honda_compute_checksum(const CANPacket_t *to_push) { uint8_t checksum = 0U; unsigned int addr = GET_ADDR(to_push); while (addr > 0U) { - checksum += (addr & 0xFU); addr >>= 4; + checksum += (uint8_t)(addr & 0xFU); addr >>= 4; } for (int j = 0; j < len; j++) { uint8_t byte = GET_BYTE(to_push, j); - checksum += (byte & 0xFU) + (byte >> 4U); + checksum += (uint8_t)(byte & 0xFU) + (byte >> 4U); if (j == (len - 1)) { checksum -= (byte & 0xFU); // remove checksum in message } @@ -465,8 +465,8 @@ static int honda_bosch_fwd_hook(int bus_num, int addr) { bus_fwd = 2; } if (bus_num == 2) { - int is_lkas_msg = (addr == 0xE4) || (addr == 0xE5) || (addr == 0x33D) || (addr == 0x33DA) || (addr == 0x33DB); - int is_acc_msg = ((addr == 0x1C8) || (addr == 0x30C)) && honda_bosch_radarless && honda_bosch_long; + bool is_lkas_msg = (addr == 0xE4) || (addr == 0xE5) || (addr == 0x33D) || (addr == 0x33DA) || (addr == 0x33DB); + bool is_acc_msg = ((addr == 0x1C8) || (addr == 0x30C)) && honda_bosch_radarless && honda_bosch_long; bool block_msg = is_lkas_msg || is_acc_msg; if (!block_msg) { bus_fwd = 0; diff --git a/board/safety/safety_hyundai_canfd.h b/board/safety/safety_hyundai_canfd.h index 0744a6e20e..fb6ccf55a0 100644 --- a/board/safety/safety_hyundai_canfd.h +++ b/board/safety/safety_hyundai_canfd.h @@ -170,7 +170,7 @@ static void hyundai_canfd_rx_hook(const CANPacket_t *to_push) { // cruise buttons const int button_addr = hyundai_canfd_alt_buttons ? 0x1aa : 0x1cf; if (addr == button_addr) { - int main_button = 0; + bool main_button = false; int cruise_button = 0; if (addr == 0x1cf) { cruise_button = GET_BYTE(to_push, 2) & 0x7U; diff --git a/board/safety/safety_hyundai_common.h b/board/safety/safety_hyundai_common.h index 2c89bfb7a8..54ea0f024a 100644 --- a/board/safety/safety_hyundai_common.h +++ b/board/safety/safety_hyundai_common.h @@ -45,7 +45,7 @@ void hyundai_common_init(uint16_t param) { #endif } -void hyundai_common_cruise_state_check(const int cruise_engaged) { +void hyundai_common_cruise_state_check(const bool cruise_engaged) { // some newer HKG models can re-enable after spamming cancel button, // so keep track of user button presses to deny engagement if no interaction @@ -62,9 +62,8 @@ void hyundai_common_cruise_state_check(const int cruise_engaged) { } } -void hyundai_common_cruise_buttons_check(const int cruise_button, const int main_button) { - if ((cruise_button == HYUNDAI_BTN_RESUME) || (cruise_button == HYUNDAI_BTN_SET) || (cruise_button == HYUNDAI_BTN_CANCEL) || - (main_button != 0)) { +void hyundai_common_cruise_buttons_check(const int cruise_button, const bool main_button) { + if ((cruise_button == HYUNDAI_BTN_RESUME) || (cruise_button == HYUNDAI_BTN_SET) || (cruise_button == HYUNDAI_BTN_CANCEL) || main_button) { hyundai_last_button_interaction = 0U; } else { hyundai_last_button_interaction = MIN(hyundai_last_button_interaction + 1U, HYUNDAI_PREV_BUTTON_SAMPLES); diff --git a/board/safety/safety_nissan.h b/board/safety/safety_nissan.h index 2317727385..c2406260fe 100644 --- a/board/safety/safety_nissan.h +++ b/board/safety/safety_nissan.h @@ -129,7 +129,7 @@ static int nissan_fwd_hook(int bus_num, int addr) { int bus_fwd = -1; if (bus_num == 0) { - int block_msg = (addr == 0x280); // CANCEL_MSG + bool block_msg = (addr == 0x280); // CANCEL_MSG if (!block_msg) { bus_fwd = 2; // ADAS } @@ -137,7 +137,7 @@ static int nissan_fwd_hook(int bus_num, int addr) { if (bus_num == 2) { // 0x169 is LKAS, 0x2b1 LKAS_HUD, 0x4cc LKAS_HUD_INFO_MSG - int block_msg = ((addr == 0x169) || (addr == 0x2b1) || (addr == 0x4cc)); + bool block_msg = ((addr == 0x169) || (addr == 0x2b1) || (addr == 0x4cc)); if (!block_msg) { bus_fwd = 0; // V-CAN } diff --git a/board/safety/safety_subaru_preglobal.h b/board/safety/safety_subaru_preglobal.h index 1549d595b3..1047814ac3 100644 --- a/board/safety/safety_subaru_preglobal.h +++ b/board/safety/safety_subaru_preglobal.h @@ -104,7 +104,7 @@ static int subaru_preglobal_fwd_hook(int bus_num, int addr) { } if (bus_num == SUBARU_PG_CAM_BUS) { - int block_msg = ((addr == MSG_SUBARU_PG_ES_Distance) || (addr == MSG_SUBARU_PG_ES_LKAS)); + bool block_msg = ((addr == MSG_SUBARU_PG_ES_Distance) || (addr == MSG_SUBARU_PG_ES_LKAS)); if (!block_msg) { bus_fwd = SUBARU_PG_MAIN_BUS; // Main CAN } diff --git a/board/safety/safety_toyota.h b/board/safety/safety_toyota.h index f6bfc08091..50c00b38a8 100644 --- a/board/safety/safety_toyota.h +++ b/board/safety/safety_toyota.h @@ -394,10 +394,10 @@ static int toyota_fwd_hook(int bus_num, int addr) { if (bus_num == 2) { // block stock lkas messages and stock acc messages (if OP is doing ACC) // in TSS2, 0x191 is LTA which we need to block to avoid controls collision - int is_lkas_msg = ((addr == 0x2E4) || (addr == 0x412) || (addr == 0x191)); + bool is_lkas_msg = ((addr == 0x2E4) || (addr == 0x412) || (addr == 0x191)); // in TSS2 the camera does ACC as well, so filter 0x343 - int is_acc_msg = (addr == 0x343); - int block_msg = is_lkas_msg || (is_acc_msg && !toyota_stock_longitudinal); + bool is_acc_msg = (addr == 0x343); + bool block_msg = is_lkas_msg || (is_acc_msg && !toyota_stock_longitudinal); if (!block_msg) { bus_fwd = 0; } diff --git a/board/safety_declarations.h b/board/safety_declarations.h index 39dcabf9b9..64b55f2033 100644 --- a/board/safety_declarations.h +++ b/board/safety_declarations.h @@ -15,7 +15,7 @@ uint32_t GET_BYTES(const CANPacket_t *msg, int start, int len) { uint32_t ret = 0U; for (int i = 0; i < len; i++) { - const uint8_t shift = i * 8; + const uint32_t shift = i * 8; ret |= (((uint32_t)msg->data[start + i]) << shift); } return ret; diff --git a/board/stm32h7/llfdcan.h b/board/stm32h7/llfdcan.h index cdce0c4480..4bb6d3d04e 100644 --- a/board/stm32h7/llfdcan.h +++ b/board/stm32h7/llfdcan.h @@ -112,10 +112,10 @@ bool llcan_set_speed(FDCAN_GlobalTypeDef *FDCANx, uint32_t speed, uint32_t data_ } // Set the nominal bit timing values - uint16_t tq = CAN_QUANTA(speed, prescaler); - uint16_t sp = CAN_SP_NOMINAL; - uint8_t seg1 = CAN_SEG1(tq, sp); - uint8_t seg2 = CAN_SEG2(tq, sp); + uint32_t tq = CAN_QUANTA(speed, prescaler); + uint32_t sp = CAN_SP_NOMINAL; + uint32_t seg1 = CAN_SEG1(tq, sp); + uint32_t seg2 = CAN_SEG2(tq, sp); uint8_t sjw = MIN(127U, seg2); FDCANx->NBTP = (((sjw & 0x7FU)-1U)< Date: Tue, 20 Feb 2024 10:59:05 -0800 Subject: [PATCH 09/15] Universal Measurement and Calibration Protocol (XCP) python library (#760) * first few commands * fix transport_version Co-authored-by: Willem Melching * add more xcp functions * more commands * configurable timeout --------- Co-authored-by: Willem Melching --- python/xcp.py | 259 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 259 insertions(+) create mode 100644 python/xcp.py diff --git a/python/xcp.py b/python/xcp.py new file mode 100644 index 0000000000..5ba3e35c50 --- /dev/null +++ b/python/xcp.py @@ -0,0 +1,259 @@ +#!/usr/bin/env python3 +import sys +import time +import struct +from enum import IntEnum + +class COMMAND_CODE(IntEnum): + CONNECT = 0xFF + DISCONNECT = 0xFE + GET_STATUS = 0xFD + SYNCH = 0xFC + GET_COMM_MODE_INFO = 0xFB + GET_ID = 0xFA + SET_REQUEST = 0xF9 + GET_SEED = 0xF8 + UNLOCK = 0xF7 + SET_MTA = 0xF6 + UPLOAD = 0xF5 + SHORT_UPLOAD = 0xF4 + BUILD_CHECKSUM = 0xF3 + TRANSPORT_LAYER_CMD = 0xF2 + USER_CMD = 0xF1 + DOWNLOAD = 0xF0 + DOWNLOAD_NEXT = 0xEF + DOWNLOAD_MAX = 0xEE + SHORT_DOWNLOAD = 0xED + MODIFY_BITS = 0xEC + SET_CAL_PAGE = 0xEB + GET_CAL_PAGE = 0xEA + GET_PAG_PROCESSOR_INFO = 0xE9 + GET_SEGMENT_INFO = 0xE8 + GET_PAGE_INFO = 0xE7 + SET_SEGMENT_MODE = 0xE6 + GET_SEGMENT_MODE = 0xE5 + COPY_CAL_PAGE = 0xE4 + CLEAR_DAQ_LIST = 0xE3 + SET_DAQ_PTR = 0xE2 + WRITE_DAQ = 0xE1 + SET_DAQ_LIST_MODE = 0xE0 + GET_DAQ_LIST_MODE = 0xDF + START_STOP_DAQ_LIST = 0xDE + START_STOP_SYNCH = 0xDD + GET_DAQ_CLOCK = 0xDC + READ_DAQ = 0xDB + GET_DAQ_PROCESSOR_INFO = 0xDA + GET_DAQ_RESOLUTION_INFO = 0xD9 + GET_DAQ_LIST_INFO = 0xD8 + GET_DAQ_EVENT_INFO = 0xD7 + FREE_DAQ = 0xD6 + ALLOC_DAQ = 0xD5 + ALLOC_ODT = 0xD4 + ALLOC_ODT_ENTRY = 0xD3 + PROGRAM_START = 0xD2 + PROGRAM_CLEAR = 0xD1 + PROGRAM = 0xD0 + PROGRAM_RESET = 0xCF + GET_PGM_PROCESSOR_INFO = 0xCE + GET_SECTOR_INFO = 0xCD + PROGRAM_PREPARE = 0xCC + PROGRAM_FORMAT = 0xCB + PROGRAM_NEXT = 0xCA + PROGRAM_MAX = 0xC9 + PROGRAM_VERIFY = 0xC8 + +ERROR_CODES = { + 0x00: "Command processor synchronization", + 0x10: "Command was not executed", + 0x11: "Command rejected because DAQ is running", + 0x12: "Command rejected because PGM is running", + 0x20: "Unknown command or not implemented optional command", + 0x21: "Command syntax invalid", + 0x22: "Command syntax valid but command parameter(s) out of range", + 0x23: "The memory location is write protected", + 0x24: "The memory location is not accessible", + 0x25: "Access denied, Seed & Key is required", + 0x26: "Selected page not available", + 0x27: "Selected page mode not available", + 0x28: "Selected segment not valid", + 0x29: "Sequence error", + 0x2A: "DAQ configuration not valid", + 0x30: "Memory overflow error", + 0x31: "Generic error", + 0x32: "The slave internal program verify routine detects an error", +} + +class CONNECT_MODE(IntEnum): + NORMAL = 0x00, + USER_DEFINED = 0x01, + +class GET_ID_REQUEST_TYPE(IntEnum): + ASCII = 0x00, + ASAM_MC2_FILE = 0x01, + ASAM_MC2_PATH = 0x02, + ASAM_MC2_URL = 0x03, + ASAM_MC2_UPLOAD = 0x04, + # 128-255 user defined + +class CommandTimeoutError(Exception): + pass + +class CommandCounterError(Exception): + pass + +class CommandResponseError(Exception): + def __init__(self, message, return_code): + super().__init__() + self.message = message + self.return_code = return_code + + def __str__(self): + return self.message + +class XcpClient(): + def __init__(self, panda, tx_addr: int, rx_addr: int, bus: int=0, timeout: float=0.1, debug=False, pad=True): + self.tx_addr = tx_addr + self.rx_addr = rx_addr + self.can_bus = bus + self.timeout = timeout + self.debug = debug + self._panda = panda + self._byte_order = ">" + self._max_cto = 8 + self._max_dto = 8 + self.pad = pad + + def _send_cto(self, cmd: int, dat: bytes = b"") -> None: + tx_data = (bytes([cmd]) + dat) + + # Some ECUs don't respond if the packets are not padded to 8 bytes + if self.pad: + tx_data = tx_data.ljust(8, b"\x00") + + if self.debug: + print("CAN-CLEAR: TX") + self._panda.can_clear(self.can_bus) + if self.debug: + print("CAN-CLEAR: RX") + self._panda.can_clear(0xFFFF) + if self.debug: + print(f"CAN-TX: {hex(self.tx_addr)} - 0x{bytes.hex(tx_data)}") + self._panda.can_send(self.tx_addr, tx_data, self.can_bus) + + def _recv_dto(self, timeout: float) -> bytes: + start_time = time.time() + while time.time() - start_time < timeout: + msgs = self._panda.can_recv() or [] + if len(msgs) >= 256: + print("CAN RX buffer overflow!!!", file=sys.stderr) + for rx_addr, _, rx_data, rx_bus in msgs: + if rx_bus == self.can_bus and rx_addr == self.rx_addr: + rx_data = bytes(rx_data) # convert bytearray to bytes + if self.debug: + print(f"CAN-RX: {hex(rx_addr)} - 0x{bytes.hex(rx_data)}") + + pid = rx_data[0] + if pid == 0xFE: + err = rx_data[1] + err_desc = ERROR_CODES.get(err, "unknown error") + dat = rx_data[2:] + raise CommandResponseError(f"{hex(err)} - {err_desc} {dat}", err) + + return rx_data[1:] + time.sleep(0.001) + + raise CommandTimeoutError("timeout waiting for response") + + # commands + def connect(self, connect_mode: CONNECT_MODE=CONNECT_MODE.NORMAL) -> dict: + self._send_cto(COMMAND_CODE.CONNECT, bytes([connect_mode])) + resp = self._recv_dto(self.timeout) + assert len(resp) == 7, f"incorrect data length: {len(resp)}" + self._byte_order = ">" if resp[1] & 0x01 else "<" + self._slave_block_mode = resp[1] & 0x40 != 0 + self._max_cto = resp[2] + self._max_dto = struct.unpack(f"{self._byte_order}H", resp[3:5])[0] + return { + "cal_support": resp[0] & 0x01 != 0, + "daq_support": resp[0] & 0x04 != 0, + "stim_support": resp[0] & 0x08 != 0, + "pgm_support": resp[0] & 0x10 != 0, + "byte_order": self._byte_order, + "address_granularity": 2**((resp[1] & 0x06) >> 1), + "slave_block_mode": self._slave_block_mode, + "optional": resp[1] & 0x80 != 0, + "max_cto": self._max_cto, + "max_dto": self._max_dto, + "protocol_version": resp[5], + "transport_version": resp[6], + } + + def disconnect(self) -> None: + self._send_cto(COMMAND_CODE.DISCONNECT) + resp = self._recv_dto(self.timeout) + assert len(resp) == 0, f"incorrect data length: {len(resp)}" + + def get_id(self, req_id_type: GET_ID_REQUEST_TYPE = GET_ID_REQUEST_TYPE.ASCII) -> dict: + if req_id_type > 255: + raise ValueError("request id type must be less than 255") + self._send_cto(COMMAND_CODE.GET_ID, bytes([req_id_type])) + resp = self._recv_dto(self.timeout) + return { + # mode = 0 means MTA was set + # mode = 1 means data is at end (only CAN-FD has space for this) + "mode": resp[0], + "length": struct.unpack(f"{self._byte_order}I", resp[3:7])[0], + "identifier": resp[7:] if self._max_cto > 8 else None + } + + def get_seed(self, mode: int = 0) -> bytes: + if mode > 255: + raise ValueError("mode must be less than 255") + self._send_cto(COMMAND_CODE.GET_SEED, bytes([0, mode])) + + # TODO: add support for longer seeds spread over multiple blocks + ret = self._recv_dto(self.timeout) + length = ret[0] + return ret[1:length+1] + + def unlock(self, key: bytes) -> bytes: + # TODO: add support for longer keys spread over multiple blocks + self._send_cto(COMMAND_CODE.UNLOCK, bytes([len(key)]) + key) + return self._recv_dto(self.timeout) + + def set_mta(self, addr: int, addr_ext: int = 0) -> bytes: + if addr_ext > 255: + raise ValueError("address extension must be less than 256") + # TODO: this looks broken (missing addr extension) + self._send_cto(COMMAND_CODE.SET_MTA, bytes([0x00, 0x00, addr_ext]) + struct.pack(f"{self._byte_order}I", addr)) + return self._recv_dto(self.timeout) + + def upload(self, size: int) -> bytes: + if size > 255: + raise ValueError("size must be less than 256") + if not self._slave_block_mode and size > self._max_dto - 1: + raise ValueError("block mode not supported") + + self._send_cto(COMMAND_CODE.UPLOAD, bytes([size])) + resp = b"" + while len(resp) < size: + resp += self._recv_dto(self.timeout)[:size - len(resp) + 1] + return resp[:size] # trim off bytes with undefined values + + def short_upload(self, size: int, addr_ext: int, addr: int) -> bytes: + if size > 6: + raise ValueError("size must be less than 7") + if addr_ext > 255: + raise ValueError("address extension must be less than 256") + self._send_cto(COMMAND_CODE.SHORT_UPLOAD, bytes([size, 0x00, addr_ext]) + struct.pack(f"{self._byte_order}I", addr)) + return self._recv_dto(self.timeout)[:size] # trim off bytes with undefined values + + def download(self, data: bytes) -> bytes: + size = len(data) + if size > 255: + raise ValueError("size must be less than 256") + if not self._slave_block_mode and size > self._max_dto - 2: + raise ValueError("block mode not supported") + + self._send_cto(COMMAND_CODE.DOWNLOAD, bytes([size]) + data) + return self._recv_dto(self.timeout)[:size] From d2d683a04c89e67bce5e5196cf9fcaaebad71301 Mon Sep 17 00:00:00 2001 From: Jason Young <46612682+jyoung8607@users.noreply.github.com> Date: Tue, 20 Feb 2024 13:41:48 -0600 Subject: [PATCH 10/15] fix test issues in xcp.py (#1882) remove shebang, fix typing --- python/xcp.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/python/xcp.py b/python/xcp.py index 5ba3e35c50..bb294046ec 100644 --- a/python/xcp.py +++ b/python/xcp.py @@ -1,4 +1,3 @@ -#!/usr/bin/env python3 import sys import time import struct @@ -159,7 +158,7 @@ def _recv_dto(self, timeout: float) -> bytes: dat = rx_data[2:] raise CommandResponseError(f"{hex(err)} - {err_desc} {dat}", err) - return rx_data[1:] + return bytes(rx_data[1:]) time.sleep(0.001) raise CommandTimeoutError("timeout waiting for response") From 70578a11f06a280e5f877d70e8998ba4ff001377 Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Tue, 20 Feb 2024 15:02:11 -0800 Subject: [PATCH 11/15] pre-commit: autoupdate hooks (#1881) Update pre-commit hook versions Co-authored-by: adeebshihadeh --- .pre-commit-config.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 5788e16b2c..1f978433e2 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -15,6 +15,6 @@ repos: additional_dependencies: ['git+https://github.com/numpy/numpy-stubs', 'types-requests', 'types-atomicwrites', 'types-pycurl'] - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.2.1 + rev: v0.2.2 hooks: - id: ruff From cd11c7f9a47a8e0c72130c56dfa79d6e77cb939f Mon Sep 17 00:00:00 2001 From: Jason Young <46612682+jyoung8607@users.noreply.github.com> Date: Thu, 22 Feb 2024 16:56:14 -0600 Subject: [PATCH 12/15] VW PQ: Allow either HCA mode (#1885) * write the test first, like a grownup * pass the test! --- board/safety/safety_volkswagen_pq.h | 2 +- tests/safety/test_volkswagen_pq.py | 10 ++++++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/board/safety/safety_volkswagen_pq.h b/board/safety/safety_volkswagen_pq.h index 1922cf4671..de147cb58a 100644 --- a/board/safety/safety_volkswagen_pq.h +++ b/board/safety/safety_volkswagen_pq.h @@ -185,7 +185,7 @@ static bool volkswagen_pq_tx_hook(const CANPacket_t *to_send) { } uint32_t hca_status = ((GET_BYTE(to_send, 1) >> 4) & 0xFU); - bool steer_req = (hca_status == 5U); + bool steer_req = ((hca_status == 5U) || (hca_status == 7U)); if (steer_torque_cmd_checks(desired_torque, steer_req, VOLKSWAGEN_PQ_STEERING_LIMITS)) { tx = false; diff --git a/tests/safety/test_volkswagen_pq.py b/tests/safety/test_volkswagen_pq.py index 68def8bf62..f2bc317868 100755 --- a/tests/safety/test_volkswagen_pq.py +++ b/tests/safety/test_volkswagen_pq.py @@ -69,8 +69,8 @@ def _torque_driver_msg(self, torque): return self.packer.make_can_msg_panda("Lenkhilfe_3", 0, values) # openpilot steering output torque - def _torque_cmd_msg(self, torque, steer_req=1): - values = {"LM_Offset": abs(torque), "LM_OffSign": torque < 0, "HCA_Status": 5 if steer_req else 3} + def _torque_cmd_msg(self, torque, steer_req=1, hca_status=5): + values = {"LM_Offset": abs(torque), "LM_OffSign": torque < 0, "HCA_Status": hca_status if steer_req else 3} return self.packer.make_can_msg_panda("HCA_1", 0, values) # ACC engagement and brake light switch status @@ -188,6 +188,12 @@ def test_main_switch(self): self._rx(self._motor_5_msg(main_switch=False)) self.assertFalse(self.safety.get_controls_allowed(), "controls allowed after ACC main switch off") + def test_torque_cmd_enable_variants(self): + # The EPS rack accepts either 5 or 7 for an enabled status, with different low speed tuning behavior + self.safety.set_controls_allowed(1) + for enabled_status in (5, 7): + self.assertTrue(self._tx(self._torque_cmd_msg(self.MAX_RATE_UP, steer_req=1, hca_status=enabled_status)), + f"torque cmd rejected with {enabled_status=}") if __name__ == "__main__": unittest.main() From 6aa4b550336136bc20a6abb307cf310e876eba28 Mon Sep 17 00:00:00 2001 From: Shane Smiskol Date: Fri, 23 Feb 2024 21:08:12 -0600 Subject: [PATCH 13/15] Ford: ignore 2nd speed checksum (#1887) * ignore cs * fix test * fix coverage * no dead code, remove todo * typo --- board/safety/safety_ford.h | 14 ++++---------- tests/safety/test_ford.py | 8 ++++---- 2 files changed, 8 insertions(+), 14 deletions(-) diff --git a/board/safety/safety_ford.h b/board/safety/safety_ford.h index 2f11863b49..d6ee208036 100644 --- a/board/safety/safety_ford.h +++ b/board/safety/safety_ford.h @@ -59,8 +59,10 @@ const CanMsg FORD_CANFD_LONG_TX_MSGS[] = { // this may be the cause of blocked messages RxCheck ford_rx_checks[] = { {.msg = {{FORD_BrakeSysFeatures, 0, 8, .check_checksum = true, .max_counter = 15U, .quality_flag=true, .frequency = 50U}, { 0 }, { 0 }}}, - // TODO: FORD_EngVehicleSpThrottle2 has a counter that skips by 2, understand and enable counter check - {.msg = {{FORD_EngVehicleSpThrottle2, 0, 8, .check_checksum = true, .quality_flag=true, .frequency = 50U}, { 0 }, { 0 }}}, + // FORD_EngVehicleSpThrottle2 has a counter that either randomly skips or by 2, likely ECU bug + // Some hybrid models also experience a bug where this checksum mismatches for one or two frames under heavy acceleration with ACC + // It has been confirmed that the Bronco Sport's camera only disallows ACC for bad quality flags, not counters or checksums, so we match that + {.msg = {{FORD_EngVehicleSpThrottle2, 0, 8, .check_checksum = false, .quality_flag=true, .frequency = 50U}, { 0 }, { 0 }}}, {.msg = {{FORD_Yaw_Data_FD1, 0, 8, .check_checksum = true, .max_counter = 255U, .quality_flag=true, .frequency = 100U}, { 0 }, { 0 }}}, // These messages have no counter or checksum {.msg = {{FORD_EngBrakeData, 0, 8, .frequency = 10U}, { 0 }, { 0 }}}, @@ -90,9 +92,6 @@ static uint32_t ford_get_checksum(const CANPacket_t *to_push) { if (addr == FORD_BrakeSysFeatures) { // Signal: VehVActlBrk_No_Cs chksum = GET_BYTE(to_push, 3); - } else if (addr == FORD_EngVehicleSpThrottle2) { - // Signal: VehVActlEng_No_Cs - chksum = GET_BYTE(to_push, 1); } else if (addr == FORD_Yaw_Data_FD1) { // Signal: VehRollYawW_No_Cs chksum = GET_BYTE(to_push, 4); @@ -110,11 +109,6 @@ static uint32_t ford_compute_checksum(const CANPacket_t *to_push) { chksum += GET_BYTE(to_push, 2) >> 6; // VehVActlBrk_D_Qf chksum += (GET_BYTE(to_push, 2) >> 2) & 0xFU; // VehVActlBrk_No_Cnt chksum = 0xFFU - chksum; - } else if (addr == FORD_EngVehicleSpThrottle2) { - chksum += (GET_BYTE(to_push, 2) >> 3) & 0xFU; // VehVActlEng_No_Cnt - chksum += (GET_BYTE(to_push, 4) >> 5) & 0x3U; // VehVActlEng_D_Qf - chksum += GET_BYTE(to_push, 6) + GET_BYTE(to_push, 7); // Veh_V_ActlEng - chksum = 0xFFU - chksum; } else if (addr == FORD_Yaw_Data_FD1) { chksum += GET_BYTE(to_push, 0) + GET_BYTE(to_push, 1); // VehRol_W_Actl chksum += GET_BYTE(to_push, 2) + GET_BYTE(to_push, 3); // VehYaw_W_Actl diff --git a/tests/safety/test_ford.py b/tests/safety/test_ford.py index 14e656b88e..1be3a273cc 100755 --- a/tests/safety/test_ford.py +++ b/tests/safety/test_ford.py @@ -215,11 +215,11 @@ def test_rx_hook(self): self.assertEqual(quality_flag, self._rx(to_push)) self.assertEqual(quality_flag, self.safety.get_controls_allowed()) - # Mess with checksum to make it fail - to_push[0].data[1] = 0 # Speed 2 checksum + # Mess with checksum to make it fail, checksum is not checked for 2nd speed to_push[0].data[3] = 0 # Speed checksum & half of yaw signal - self.assertFalse(self._rx(to_push)) - self.assertFalse(self.safety.get_controls_allowed()) + should_rx = msg == "speed_2" and quality_flag + self.assertEqual(should_rx, self._rx(to_push)) + self.assertEqual(should_rx, self.safety.get_controls_allowed()) def test_rx_hook_speed_mismatch(self): # Ford relies on speed for driver curvature limiting, so it checks two sources From 96a3099398a0a13b16225ca96e4b91e4fc085755 Mon Sep 17 00:00:00 2001 From: Jason Young <46612682+jyoung8607@users.noreply.github.com> Date: Sat, 24 Feb 2024 12:03:45 -0600 Subject: [PATCH 14/15] fix forwarded bus logging for CAN-FD hardware (#1884) --- board/drivers/fdcan.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/board/drivers/fdcan.h b/board/drivers/fdcan.h index bc4c2a532e..9e2e0df7f0 100644 --- a/board/drivers/fdcan.h +++ b/board/drivers/fdcan.h @@ -126,7 +126,7 @@ void process_can(uint8_t can_number) { to_push.rejected = 0U; to_push.extended = to_send.extended; to_push.addr = to_send.addr; - to_push.bus = to_send.bus; + to_push.bus = bus_number; to_push.data_len_code = to_send.data_len_code; (void)memcpy(to_push.data, to_send.data, dlc_to_len[to_push.data_len_code]); can_set_checksum(&to_push); From 0c7d5f11d7187904022ea49b6a76b54d7b280345 Mon Sep 17 00:00:00 2001 From: Cameron Clough Date: Sat, 24 Feb 2024 21:56:28 +0000 Subject: [PATCH 15/15] use pyupgrade to update syntax (#1889) --- board/jungle/__init__.py | 3 +- board/jungle/scripts/get_version.py | 2 +- examples/can_bit_transition.py | 2 +- examples/can_unique.py | 6 +- examples/query_fw_versions.py | 3 +- pyproject.toml | 6 +- python/__init__.py | 9 ++- python/constants.py | 4 +- python/dfu.py | 25 ++++---- python/isotp.py | 4 +- python/serial.py | 2 +- python/spi.py | 6 +- python/uds.py | 89 +++++++++++++++-------------- setup.py | 2 - tests/bulk_write_test.py | 4 +- tests/elm_car_simulator.py | 4 +- tests/elm_throughput.py | 2 +- tests/fan/fan_tuning.py | 2 +- tests/get_version.py | 2 +- tests/gmbitbang/recv.py | 3 +- tests/hitl/4_can_loopback.py | 4 +- tests/hitl/helpers.py | 3 +- tests/libpanda/libpanda_py.py | 4 +- tests/message_drop_test.py | 8 +-- tests/read_winusb_descriptors.py | 8 +-- tests/safety/common.py | 28 ++++----- tests/safety/hyundai_common.py | 5 +- tests/safety/test_gm.py | 5 +- tests/safety/test_honda.py | 7 +-- 29 files changed, 122 insertions(+), 130 deletions(-) diff --git a/board/jungle/__init__.py b/board/jungle/__init__.py index 77a6e3c7cc..a95ddfa927 100644 --- a/board/jungle/__init__.py +++ b/board/jungle/__init__.py @@ -2,7 +2,6 @@ import os import struct from functools import wraps -from typing import Optional from panda import Panda, PandaDFU from panda.python.constants import McuType @@ -57,7 +56,7 @@ def flash(self, fn=None, code=None, reconnect=True): fn = os.path.join(FW_PATH, self._mcu_type.config.app_fn.replace("panda", "panda_jungle")) super().flash(fn=fn, code=code, reconnect=reconnect) - def recover(self, timeout: Optional[int] = 60, reset: bool = True) -> bool: + def recover(self, timeout: int | None = 60, reset: bool = True) -> bool: dfu_serial = self.get_dfu_serial() if reset: diff --git a/board/jungle/scripts/get_version.py b/board/jungle/scripts/get_version.py index ad4a1c4264..4fc9d30bef 100755 --- a/board/jungle/scripts/get_version.py +++ b/board/jungle/scripts/get_version.py @@ -4,6 +4,6 @@ if __name__ == "__main__": for p in PandaJungle.list(): pp = PandaJungle(p) - print("%s: %s" % (pp.get_serial()[0], pp.get_version())) + print(f"{pp.get_serial()[0]}: {pp.get_version()}") diff --git a/examples/can_bit_transition.py b/examples/can_bit_transition.py index bc9b68ae89..1e7bad54e7 100755 --- a/examples/can_bit_transition.py +++ b/examples/can_bit_transition.py @@ -66,7 +66,7 @@ def load(self, filename, start, end): message_id = message_id[2:] # remove leading '0x' else: message_id = hex(int(message_id))[2:] # old message IDs are in decimal - message_id = '%s:%s' % (bus, message_id) + message_id = f'{bus}:{message_id}' data = row[CSV_KEYS[dtype]["data"]] if data.startswith('0x'): diff --git a/examples/can_unique.py b/examples/can_unique.py index bc582f016f..05977afb0a 100755 --- a/examples/can_unique.py +++ b/examples/can_unique.py @@ -52,7 +52,7 @@ def __init__(self): def load(self, filename): """Given a CSV file, adds information about message IDs and their values.""" - with open(filename, 'r') as inp: + with open(filename) as inp: reader = csv.reader(inp) header = next(reader, None) if header[0] == 'time': @@ -64,7 +64,7 @@ def cabana(self, reader): for row in reader: bus = row[2] message_id = hex(int(row[1]))[2:] - message_id = '%s:%s' % (bus, message_id) + message_id = f'{bus}:{message_id}' data = row[3] self.store(message_id, data) @@ -75,7 +75,7 @@ def logger(self, reader): message_id = row[1][2:] # remove leading '0x' else: message_id = hex(int(row[1]))[2:] # old message IDs are in decimal - message_id = '%s:%s' % (bus, message_id) + message_id = f'{bus}:{message_id}' if row[1].startswith('0x'): data = row[2][2:] # remove leading '0x' else: diff --git a/examples/query_fw_versions.py b/examples/query_fw_versions.py index 4f4e3fa66b..fe70bf96ab 100755 --- a/examples/query_fw_versions.py +++ b/examples/query_fw_versions.py @@ -1,6 +1,5 @@ #!/usr/bin/env python3 import argparse -from typing import List, Optional from tqdm import tqdm from panda import Panda from panda.python.uds import UdsClient, MessageTimeoutError, NegativeResponseError, InvalidSubAddressError, \ @@ -25,7 +24,7 @@ addrs += [0x18da0000 + (i << 8) + 0xf1 for i in range(256)] results = {} - sub_addrs: List[Optional[int]] = [None] + sub_addrs: list[int | None] = [None] if args.sub_addr: if args.sub_addr == "scan": sub_addrs = list(range(0xff + 1)) diff --git a/pyproject.toml b/pyproject.toml index 72bce22bec..ee89db28ec 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,9 +1,11 @@ # https://beta.ruff.rs/docs/configuration/#using-pyprojecttoml [tool.ruff] -select = ["E", "F", "W", "PIE", "C4", "ISC", "RUF100", "A"] -ignore = ["W292", "E741", "E402", "C408", "ISC003"] line-length = 160 target-version="py311" + +[tool.ruff.lint] +select = ["E", "F", "W", "PIE", "C4", "ISC", "RUF100", "A"] +ignore = ["W292", "E741", "E402", "C408", "ISC003"] flake8-implicit-str-concat.allow-multiline=false [tool.pytest.ini_options] diff --git a/python/__init__.py b/python/__init__.py index acf6ea4834..6e614775d9 100644 --- a/python/__init__.py +++ b/python/__init__.py @@ -9,7 +9,6 @@ import datetime import logging from functools import wraps, partial -from typing import Optional from itertools import accumulate from .base import BaseHandle @@ -234,7 +233,7 @@ class Panda: FLAG_FORD_LONG_CONTROL = 1 FLAG_FORD_CANFD = 2 - def __init__(self, serial: Optional[str] = None, claim: bool = True, disable_checks: bool = True, can_speed_kbps: int = 500): + def __init__(self, serial: str | None = None, claim: bool = True, disable_checks: bool = True, can_speed_kbps: int = 500): self._connect_serial = serial self._disable_checks = disable_checks @@ -530,7 +529,7 @@ def flash(self, fn=None, code=None, reconnect=True): if reconnect: self.reconnect() - def recover(self, timeout: Optional[int] = 60, reset: bool = True) -> bool: + def recover(self, timeout: int | None = 60, reset: bool = True) -> bool: dfu_serial = self.get_dfu_serial() if reset: @@ -549,7 +548,7 @@ def recover(self, timeout: Optional[int] = 60, reset: bool = True) -> bool: return True @staticmethod - def wait_for_dfu(dfu_serial: Optional[str], timeout: Optional[int] = None) -> bool: + def wait_for_dfu(dfu_serial: str | None, timeout: int | None = None) -> bool: t_start = time.monotonic() dfu_list = PandaDFU.list() while (dfu_serial is None and len(dfu_list) == 0) or (dfu_serial is not None and dfu_serial not in dfu_list): @@ -561,7 +560,7 @@ def wait_for_dfu(dfu_serial: Optional[str], timeout: Optional[int] = None) -> bo return True @staticmethod - def wait_for_panda(serial: Optional[str], timeout: int) -> bool: + def wait_for_panda(serial: str | None, timeout: int) -> bool: t_start = time.monotonic() serials = Panda.list() while (serial is None and len(serials) == 0) or (serial is not None and serial not in serials): diff --git a/python/constants.py b/python/constants.py index fede52424c..8b09593084 100644 --- a/python/constants.py +++ b/python/constants.py @@ -1,6 +1,6 @@ import os import enum -from typing import List, NamedTuple +from typing import NamedTuple BASEDIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), "../") FW_PATH = os.path.join(BASEDIR, "board/obj/") @@ -10,7 +10,7 @@ class McuConfig(NamedTuple): mcu: str mcu_idcode: int - sector_sizes: List[int] + sector_sizes: list[int] sector_count: int # total sector count, used for MCU identification in DFU mode uid_address: int block_size: int diff --git a/python/dfu.py b/python/dfu.py index 01ff037f84..9beba45e55 100644 --- a/python/dfu.py +++ b/python/dfu.py @@ -2,7 +2,6 @@ import usb1 import struct import binascii -from typing import List, Optional from .base import BaseSTBootloaderHandle from .spi import STBootloaderSPIHandle, PandaSpiException @@ -11,9 +10,9 @@ class PandaDFU: - def __init__(self, dfu_serial: Optional[str]): + def __init__(self, dfu_serial: str | None): # try USB, then SPI - handle: Optional[BaseSTBootloaderHandle] + handle: BaseSTBootloaderHandle | None self._context, handle = PandaDFU.usb_connect(dfu_serial) if handle is None: self._context, handle = PandaDFU.spi_connect(dfu_serial) @@ -38,7 +37,7 @@ def close(self): self._context.close() @staticmethod - def usb_connect(dfu_serial: Optional[str]): + def usb_connect(dfu_serial: str | None): handle = None context = usb1.USBContext() context.open() @@ -56,7 +55,7 @@ def usb_connect(dfu_serial: Optional[str]): return context, handle @staticmethod - def spi_connect(dfu_serial: Optional[str]): + def spi_connect(dfu_serial: str | None): handle = None this_dfu_serial = None @@ -72,13 +71,7 @@ def spi_connect(dfu_serial: Optional[str]): return None, handle @staticmethod - def list() -> List[str]: - ret = PandaDFU.usb_list() - ret += PandaDFU.spi_list() - return list(set(ret)) - - @staticmethod - def usb_list() -> List[str]: + def usb_list() -> list[str]: dfu_serials = [] try: with usb1.USBContext() as context: @@ -93,7 +86,7 @@ def usb_list() -> List[str]: return dfu_serials @staticmethod - def spi_list() -> List[str]: + def spi_list() -> list[str]: try: _, h = PandaDFU.spi_connect(None) if h is not None: @@ -134,3 +127,9 @@ def recover(self): code = f.read() self.program_bootstub(code) self.reset() + + @staticmethod + def list() -> list[str]: + ret = PandaDFU.usb_list() + ret += PandaDFU.spi_list() + return list(set(ret)) diff --git a/python/isotp.py b/python/isotp.py index 3334deb8ed..d0bef7d942 100644 --- a/python/isotp.py +++ b/python/isotp.py @@ -79,10 +79,10 @@ def isotp_send(panda, x, addr, bus=0, recvaddr=None, subaddr=None, rate=None): sends = [] while len(x) > 0: if subaddr: - sends.append(((bytes([subaddr, 0x20 + (idx & 0xF)]) + x[0:6]).ljust(8, b"\x00"))) + sends.append((bytes([subaddr, 0x20 + (idx & 0xF)]) + x[0:6]).ljust(8, b"\x00")) x = x[6:] else: - sends.append(((bytes([0x20 + (idx & 0xF)]) + x[0:7]).ljust(8, b"\x00"))) + sends.append((bytes([0x20 + (idx & 0xF)]) + x[0:7]).ljust(8, b"\x00")) x = x[7:] idx += 1 diff --git a/python/serial.py b/python/serial.py index 9ac58862b5..c2e965b76c 100644 --- a/python/serial.py +++ b/python/serial.py @@ -1,5 +1,5 @@ # mimic a python serial port -class PandaSerial(object): +class PandaSerial: def __init__(self, panda, port, baud): self.panda = panda self.port = port diff --git a/python/spi.py b/python/spi.py index 48dc84d49e..d34a61d565 100644 --- a/python/spi.py +++ b/python/spi.py @@ -9,7 +9,7 @@ import threading from contextlib import contextmanager from functools import reduce -from typing import Callable, List, Optional +from collections.abc import Callable from .base import BaseHandle, BaseSTBootloaderHandle, TIMEOUT from .constants import McuType, MCU_TYPE_BY_IDCODE, USBPACKET_MAX_SIZE @@ -341,7 +341,7 @@ def _get_ack(self, spi, timeout=1.0): elif data != self.ACK: raise PandaSpiMissingAck - def _cmd_no_retry(self, cmd: int, data: Optional[List[bytes]] = None, read_bytes: int = 0, predata=None) -> bytes: + def _cmd_no_retry(self, cmd: int, data: list[bytes] | None = None, read_bytes: int = 0, predata=None) -> bytes: ret = b"" with self.dev.acquire() as spi: # sync + command @@ -371,7 +371,7 @@ def _cmd_no_retry(self, cmd: int, data: Optional[List[bytes]] = None, read_bytes return bytes(ret) - def _cmd(self, cmd: int, data: Optional[List[bytes]] = None, read_bytes: int = 0, predata=None) -> bytes: + def _cmd(self, cmd: int, data: list[bytes] | None = None, read_bytes: int = 0, predata=None) -> bytes: exc = PandaSpiException() for n in range(MAX_XFER_RETRY_COUNT): try: diff --git a/python/uds.py b/python/uds.py index aaa0697f90..12b4fcdc23 100644 --- a/python/uds.py +++ b/python/uds.py @@ -1,7 +1,8 @@ import time import struct from collections import deque -from typing import Callable, NamedTuple, Tuple, List, Deque, Generator, Optional, cast +from typing import NamedTuple, Deque, cast +from collections.abc import Callable, Generator from enum import IntEnum from functools import partial @@ -300,8 +301,8 @@ def get_dtc_status_names(status): return result class CanClient(): - def __init__(self, can_send: Callable[[int, bytes, int], None], can_recv: Callable[[], List[Tuple[int, int, bytes, int]]], - tx_addr: int, rx_addr: int, bus: int, sub_addr: Optional[int] = None, debug: bool = False): + def __init__(self, can_send: Callable[[int, bytes, int], None], can_recv: Callable[[], list[tuple[int, int, bytes, int]]], + tx_addr: int, rx_addr: int, bus: int, sub_addr: int | None = None, debug: bool = False): self.tx = can_send self.rx = can_recv self.tx_addr = tx_addr @@ -335,7 +336,7 @@ def _recv_buffer(self, drain: bool = False) -> None: msgs = self.rx() if drain: if self.debug: - print("CAN-RX: drain - {}".format(len(msgs))) + print(f"CAN-RX: drain - {len(msgs)}") self.rx_buff.clear() else: for rx_addr, _, rx_data, rx_bus in msgs or []: @@ -366,7 +367,7 @@ def recv(self, drain: bool = False) -> Generator[bytes, None, None]: except IndexError: pass # empty - def send(self, msgs: List[bytes], delay: float = 0) -> None: + def send(self, msgs: list[bytes], delay: float = 0) -> None: for i, msg in enumerate(msgs): if delay and i != 0: if self.debug: @@ -443,7 +444,7 @@ def _tx_first_frame(self, setup_only: bool = False) -> None: if not setup_only: self._can_client.send([msg]) - def recv(self, timeout=None) -> Tuple[Optional[bytes], bool]: + def recv(self, timeout=None) -> tuple[bytes | None, bool]: if timeout is None: timeout = self.timeout @@ -566,11 +567,11 @@ def get_rx_addr_for_tx_addr(tx_addr, rx_offset=0x8): # standard 29 bit response addr (flip last two bytes) return (tx_addr & 0xFFFF0000) + (tx_addr << 8 & 0xFF00) + (tx_addr >> 8 & 0xFF) - raise ValueError("invalid tx_addr: {}".format(tx_addr)) + raise ValueError(f"invalid tx_addr: {tx_addr}") class UdsClient(): - def __init__(self, panda, tx_addr: int, rx_addr: Optional[int] = None, bus: int = 0, sub_addr: Optional[int] = None, timeout: float = 1, + def __init__(self, panda, tx_addr: int, rx_addr: int | None = None, bus: int = 0, sub_addr: int | None = None, timeout: float = 1, debug: bool = False, tx_timeout: float = 1, response_pending_timeout: float = 10): self.bus = bus self.tx_addr = tx_addr @@ -583,7 +584,7 @@ def __init__(self, panda, tx_addr: int, rx_addr: Optional[int] = None, bus: int self.response_pending_timeout = response_pending_timeout # generic uds request - def _uds_request(self, service_type: SERVICE_TYPE, subfunction: Optional[int] = None, data: Optional[bytes] = None) -> bytes: + def _uds_request(self, service_type: SERVICE_TYPE, subfunction: int | None = None, data: bytes | None = None) -> bytes: req = bytes([service_type]) if subfunction is not None: req += bytes([subfunction]) @@ -623,12 +624,12 @@ def _uds_request(self, service_type: SERVICE_TYPE, subfunction: Optional[int] = if self.debug: print("UDS-RX: response pending") continue - raise NegativeResponseError('{} - {}'.format(service_desc, error_desc), service_id, error_code) + raise NegativeResponseError(f'{service_desc} - {error_desc}', service_id, error_code) # positive response if service_type + 0x40 != resp_sid: resp_sid_hex = hex(resp_sid) if resp_sid is not None else None - raise InvalidServiceIdError('invalid response service id: {}'.format(resp_sid_hex)) + raise InvalidServiceIdError(f'invalid response service id: {resp_sid_hex}') if subfunction is not None: resp_sfn = resp[1] if len(resp) > 1 else None @@ -671,7 +672,7 @@ def communication_control(self, control_type: CONTROL_TYPE, message_type: MESSAG def tester_present(self, ): self._uds_request(SERVICE_TYPE.TESTER_PRESENT, subfunction=0x00) - def access_timing_parameter(self, timing_parameter_type: TIMING_PARAMETER_TYPE, parameter_values: Optional[bytes] = None): + def access_timing_parameter(self, timing_parameter_type: TIMING_PARAMETER_TYPE, parameter_values: bytes | None = None): write_custom_values = timing_parameter_type == TIMING_PARAMETER_TYPE.SET_TO_GIVEN_VALUES read_values = (timing_parameter_type == TIMING_PARAMETER_TYPE.READ_CURRENTLY_ACTIVE or timing_parameter_type == TIMING_PARAMETER_TYPE.READ_EXTENDED_SET) @@ -714,8 +715,8 @@ def response_on_event(self, response_event_type: RESPONSE_EVENT_TYPE, store_even "data": resp[2:], # TODO: parse the reset of response } - def link_control(self, link_control_type: LINK_CONTROL_TYPE, baud_rate_type: Optional[BAUD_RATE_TYPE] = None): - data: Optional[bytes] + def link_control(self, link_control_type: LINK_CONTROL_TYPE, baud_rate_type: BAUD_RATE_TYPE | None = None): + data: bytes | None if link_control_type == LINK_CONTROL_TYPE.VERIFY_BAUDRATE_TRANSITION_WITH_FIXED_BAUDRATE: # baud_rate_type = BAUD_RATE_TYPE @@ -733,21 +734,21 @@ def read_data_by_identifier(self, data_identifier_type: DATA_IDENTIFIER_TYPE): resp = self._uds_request(SERVICE_TYPE.READ_DATA_BY_IDENTIFIER, subfunction=None, data=data) resp_id = struct.unpack('!H', resp[0:2])[0] if len(resp) >= 2 else None if resp_id != data_identifier_type: - raise ValueError('invalid response data identifier: {} expected: {}'.format(hex(resp_id), hex(data_identifier_type))) + raise ValueError(f'invalid response data identifier: {hex(resp_id)} expected: {hex(data_identifier_type)}') return resp[2:] def read_memory_by_address(self, memory_address: int, memory_size: int, memory_address_bytes: int = 4, memory_size_bytes: int = 1): if memory_address_bytes < 1 or memory_address_bytes > 4: - raise ValueError('invalid memory_address_bytes: {}'.format(memory_address_bytes)) + raise ValueError(f'invalid memory_address_bytes: {memory_address_bytes}') if memory_size_bytes < 1 or memory_size_bytes > 4: - raise ValueError('invalid memory_size_bytes: {}'.format(memory_size_bytes)) + raise ValueError(f'invalid memory_size_bytes: {memory_size_bytes}') data = bytes([memory_size_bytes << 4 | memory_address_bytes]) if memory_address >= 1 << (memory_address_bytes * 8): - raise ValueError('invalid memory_address: {}'.format(memory_address)) + raise ValueError(f'invalid memory_address: {memory_address}') data += struct.pack('!I', memory_address)[4 - memory_address_bytes:] if memory_size >= 1 << (memory_size_bytes * 8): - raise ValueError('invalid memory_size: {}'.format(memory_size)) + raise ValueError(f'invalid memory_size: {memory_size}') data += struct.pack('!I', memory_size)[4 - memory_size_bytes:] resp = self._uds_request(SERVICE_TYPE.READ_MEMORY_BY_ADDRESS, subfunction=None, data=data) @@ -758,7 +759,7 @@ def read_scaling_data_by_identifier(self, data_identifier_type: DATA_IDENTIFIER_ resp = self._uds_request(SERVICE_TYPE.READ_SCALING_DATA_BY_IDENTIFIER, subfunction=None, data=data) resp_id = struct.unpack('!H', resp[0:2])[0] if len(resp) >= 2 else None if resp_id != data_identifier_type: - raise ValueError('invalid response data identifier: {}'.format(hex(resp_id))) + raise ValueError(f'invalid response data identifier: {hex(resp_id)}') return resp[2:] # TODO: parse the response def read_data_by_periodic_identifier(self, transmission_mode_type: TRANSMISSION_MODE_TYPE, periodic_data_identifier: int): @@ -767,11 +768,11 @@ def read_data_by_periodic_identifier(self, transmission_mode_type: TRANSMISSION_ self._uds_request(SERVICE_TYPE.READ_DATA_BY_PERIODIC_IDENTIFIER, subfunction=None, data=data) def dynamically_define_data_identifier(self, dynamic_definition_type: DYNAMIC_DEFINITION_TYPE, dynamic_data_identifier: int, - source_definitions: List[DynamicSourceDefinition], memory_address_bytes: int = 4, memory_size_bytes: int = 1): + source_definitions: list[DynamicSourceDefinition], memory_address_bytes: int = 4, memory_size_bytes: int = 1): if memory_address_bytes < 1 or memory_address_bytes > 4: - raise ValueError('invalid memory_address_bytes: {}'.format(memory_address_bytes)) + raise ValueError(f'invalid memory_address_bytes: {memory_address_bytes}') if memory_size_bytes < 1 or memory_size_bytes > 4: - raise ValueError('invalid memory_size_bytes: {}'.format(memory_size_bytes)) + raise ValueError(f'invalid memory_size_bytes: {memory_size_bytes}') data = struct.pack('!H', dynamic_data_identifier) if dynamic_definition_type == DYNAMIC_DEFINITION_TYPE.DEFINE_BY_IDENTIFIER: @@ -781,15 +782,15 @@ def dynamically_define_data_identifier(self, dynamic_definition_type: DYNAMIC_DE data += bytes([memory_size_bytes << 4 | memory_address_bytes]) for s in source_definitions: if s.memory_address >= 1 << (memory_address_bytes * 8): - raise ValueError('invalid memory_address: {}'.format(s.memory_address)) + raise ValueError(f'invalid memory_address: {s.memory_address}') data += struct.pack('!I', s.memory_address)[4 - memory_address_bytes:] if s.memory_size >= 1 << (memory_size_bytes * 8): - raise ValueError('invalid memory_size: {}'.format(s.memory_size)) + raise ValueError(f'invalid memory_size: {s.memory_size}') data += struct.pack('!I', s.memory_size)[4 - memory_size_bytes:] elif dynamic_definition_type == DYNAMIC_DEFINITION_TYPE.CLEAR_DYNAMICALLY_DEFINED_DATA_IDENTIFIER: pass else: - raise ValueError('invalid dynamic identifier type: {}'.format(hex(dynamic_definition_type))) + raise ValueError(f'invalid dynamic identifier type: {hex(dynamic_definition_type)}') self._uds_request(SERVICE_TYPE.DYNAMICALLY_DEFINE_DATA_IDENTIFIER, subfunction=dynamic_definition_type, data=data) def write_data_by_identifier(self, data_identifier_type: DATA_IDENTIFIER_TYPE, data_record: bytes): @@ -797,20 +798,20 @@ def write_data_by_identifier(self, data_identifier_type: DATA_IDENTIFIER_TYPE, d resp = self._uds_request(SERVICE_TYPE.WRITE_DATA_BY_IDENTIFIER, subfunction=None, data=data) resp_id = struct.unpack('!H', resp[0:2])[0] if len(resp) >= 2 else None if resp_id != data_identifier_type: - raise ValueError('invalid response data identifier: {}'.format(hex(resp_id))) + raise ValueError(f'invalid response data identifier: {hex(resp_id)}') def write_memory_by_address(self, memory_address: int, memory_size: int, data_record: bytes, memory_address_bytes: int = 4, memory_size_bytes: int = 1): if memory_address_bytes < 1 or memory_address_bytes > 4: - raise ValueError('invalid memory_address_bytes: {}'.format(memory_address_bytes)) + raise ValueError(f'invalid memory_address_bytes: {memory_address_bytes}') if memory_size_bytes < 1 or memory_size_bytes > 4: - raise ValueError('invalid memory_size_bytes: {}'.format(memory_size_bytes)) + raise ValueError(f'invalid memory_size_bytes: {memory_size_bytes}') data = bytes([memory_size_bytes << 4 | memory_address_bytes]) if memory_address >= 1 << (memory_address_bytes * 8): - raise ValueError('invalid memory_address: {}'.format(memory_address)) + raise ValueError(f'invalid memory_address: {memory_address}') data += struct.pack('!I', memory_address)[4 - memory_address_bytes:] if memory_size >= 1 << (memory_size_bytes * 8): - raise ValueError('invalid memory_size: {}'.format(memory_size)) + raise ValueError(f'invalid memory_size: {memory_size}') data += struct.pack('!I', memory_size)[4 - memory_size_bytes:] data += data_record @@ -864,7 +865,7 @@ def input_output_control_by_identifier(self, data_identifier_type: DATA_IDENTIFI resp = self._uds_request(SERVICE_TYPE.INPUT_OUTPUT_CONTROL_BY_IDENTIFIER, subfunction=None, data=data) resp_id = struct.unpack('!H', resp[0:2])[0] if len(resp) >= 2 else None if resp_id != data_identifier_type: - raise ValueError('invalid response data identifier: {}'.format(hex(resp_id))) + raise ValueError(f'invalid response data identifier: {hex(resp_id)}') return resp[2:] def routine_control(self, routine_control_type: ROUTINE_CONTROL_TYPE, routine_identifier_type: ROUTINE_IDENTIFIER_TYPE, routine_option_record: bytes = b''): @@ -872,23 +873,23 @@ def routine_control(self, routine_control_type: ROUTINE_CONTROL_TYPE, routine_id resp = self._uds_request(SERVICE_TYPE.ROUTINE_CONTROL, subfunction=routine_control_type, data=data) resp_id = struct.unpack('!H', resp[0:2])[0] if len(resp) >= 2 else None if resp_id != routine_identifier_type: - raise ValueError('invalid response routine identifier: {}'.format(hex(resp_id))) + raise ValueError(f'invalid response routine identifier: {hex(resp_id)}') return resp[2:] def request_download(self, memory_address: int, memory_size: int, memory_address_bytes: int = 4, memory_size_bytes: int = 4, data_format: int = 0x00): data = bytes([data_format]) if memory_address_bytes < 1 or memory_address_bytes > 4: - raise ValueError('invalid memory_address_bytes: {}'.format(memory_address_bytes)) + raise ValueError(f'invalid memory_address_bytes: {memory_address_bytes}') if memory_size_bytes < 1 or memory_size_bytes > 4: - raise ValueError('invalid memory_size_bytes: {}'.format(memory_size_bytes)) + raise ValueError(f'invalid memory_size_bytes: {memory_size_bytes}') data += bytes([memory_size_bytes << 4 | memory_address_bytes]) if memory_address >= 1 << (memory_address_bytes * 8): - raise ValueError('invalid memory_address: {}'.format(memory_address)) + raise ValueError(f'invalid memory_address: {memory_address}') data += struct.pack('!I', memory_address)[4 - memory_address_bytes:] if memory_size >= 1 << (memory_size_bytes * 8): - raise ValueError('invalid memory_size: {}'.format(memory_size)) + raise ValueError(f'invalid memory_size: {memory_size}') data += struct.pack('!I', memory_size)[4 - memory_size_bytes:] resp = self._uds_request(SERVICE_TYPE.REQUEST_DOWNLOAD, subfunction=None, data=data) @@ -896,7 +897,7 @@ def request_download(self, memory_address: int, memory_size: int, memory_address if max_num_bytes_len >= 1 and max_num_bytes_len <= 4: max_num_bytes = struct.unpack('!I', (b"\x00" * (4 - max_num_bytes_len)) + resp[1:max_num_bytes_len + 1])[0] else: - raise ValueError('invalid max_num_bytes_len: {}'.format(max_num_bytes_len)) + raise ValueError(f'invalid max_num_bytes_len: {max_num_bytes_len}') return max_num_bytes # max number of bytes per transfer data request @@ -904,16 +905,16 @@ def request_upload(self, memory_address: int, memory_size: int, memory_address_b data = bytes([data_format]) if memory_address_bytes < 1 or memory_address_bytes > 4: - raise ValueError('invalid memory_address_bytes: {}'.format(memory_address_bytes)) + raise ValueError(f'invalid memory_address_bytes: {memory_address_bytes}') if memory_size_bytes < 1 or memory_size_bytes > 4: - raise ValueError('invalid memory_size_bytes: {}'.format(memory_size_bytes)) + raise ValueError(f'invalid memory_size_bytes: {memory_size_bytes}') data += bytes([memory_size_bytes << 4 | memory_address_bytes]) if memory_address >= 1 << (memory_address_bytes * 8): - raise ValueError('invalid memory_address: {}'.format(memory_address)) + raise ValueError(f'invalid memory_address: {memory_address}') data += struct.pack('!I', memory_address)[4 - memory_address_bytes:] if memory_size >= 1 << (memory_size_bytes * 8): - raise ValueError('invalid memory_size: {}'.format(memory_size)) + raise ValueError(f'invalid memory_size: {memory_size}') data += struct.pack('!I', memory_size)[4 - memory_size_bytes:] resp = self._uds_request(SERVICE_TYPE.REQUEST_UPLOAD, subfunction=None, data=data) @@ -921,7 +922,7 @@ def request_upload(self, memory_address: int, memory_size: int, memory_address_b if max_num_bytes_len >= 1 and max_num_bytes_len <= 4: max_num_bytes = struct.unpack('!I', (b"\x00" * (4 - max_num_bytes_len)) + resp[1:max_num_bytes_len + 1])[0] else: - raise ValueError('invalid max_num_bytes_len: {}'.format(max_num_bytes_len)) + raise ValueError(f'invalid max_num_bytes_len: {max_num_bytes_len}') return max_num_bytes # max number of bytes per transfer data request @@ -930,7 +931,7 @@ def transfer_data(self, block_sequence_count: int, data: bytes = b''): resp = self._uds_request(SERVICE_TYPE.TRANSFER_DATA, subfunction=None, data=data) resp_id = resp[0] if len(resp) > 0 else None if resp_id != block_sequence_count: - raise ValueError('invalid block_sequence_count: {}'.format(resp_id)) + raise ValueError(f'invalid block_sequence_count: {resp_id}') return resp[1:] def request_transfer_exit(self): diff --git a/setup.py b/setup.py index c419056a94..25ee669236 100644 --- a/setup.py +++ b/setup.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - """ Panda CAN Controller Dongle ~~~~~ diff --git a/tests/bulk_write_test.py b/tests/bulk_write_test.py index bc5bad3317..278766a199 100755 --- a/tests/bulk_write_test.py +++ b/tests/bulk_write_test.py @@ -2,7 +2,7 @@ import os import time import threading -from typing import Any, List +from typing import Any from panda import Panda @@ -38,7 +38,7 @@ def flood_tx(panda): threading.Thread(target=flood_tx, args=(sender,)).start() # Receive as much as we can in a few second time period - rx: List[Any] = [] + rx: list[Any] = [] old_len = 0 start_time = time.time() while time.time() - start_time < 3 or len(rx) > old_len: diff --git a/tests/elm_car_simulator.py b/tests/elm_car_simulator.py index 119c6b682a..56e825f5dd 100755 --- a/tests/elm_car_simulator.py +++ b/tests/elm_car_simulator.py @@ -190,7 +190,7 @@ def _process_obd(self, mode, pid): if pid == 0x02: # Show VIN return b"1D4GP00R55B123456" if pid == 0xFC: # test long multi message. Ligned up for LIN responses - return b''.join((struct.pack(">BBH", 0xAA, 0xAA, num + 1) for num in range(80))) + return b''.join(struct.pack(">BBH", 0xAA, 0xAA, num + 1) for num in range(80)) if pid == 0xFD: # test long multi message parts = (b'\xAA\xAA\xAA' + struct.pack(">I", num) for num in range(80)) return b'\xAA\xAA\xAA' + b''.join(parts) @@ -199,7 +199,7 @@ def _process_obd(self, mode, pid): return b'\xAA\xAA\xAA' + b''.join(parts) + b'\xAA' if pid == 0xFF: return b'\xAA\x00\x00' + \ - b"".join(((b'\xAA' * 5) + struct.pack(">H", num + 1) for num in range(584))) + b"".join((b'\xAA' * 5) + struct.pack(">H", num + 1) for num in range(584)) #return b"\xAA"*100#(0xFFF-3) diff --git a/tests/elm_throughput.py b/tests/elm_throughput.py index 75fb1c652b..983d4a1416 100755 --- a/tests/elm_throughput.py +++ b/tests/elm_throughput.py @@ -6,7 +6,7 @@ class Reader(threading.Thread): def __init__(self, s, *args, **kwargs): - super(Reader, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self._s = s self.__stop = False diff --git a/tests/fan/fan_tuning.py b/tests/fan/fan_tuning.py index e9158d609d..2bdfab79a2 100755 --- a/tests/fan/fan_tuning.py +++ b/tests/fan/fan_tuning.py @@ -33,7 +33,7 @@ def logger(event): for l in drain_serial(p)[::-1]: ns = l.decode('utf8').strip().split(' ') if len(ns) == 4: - target_rpm, rpm_fast, power, stall_count = [int(n, 16) for n in ns] + target_rpm, rpm_fast, power, stall_count = (int(n, 16) for n in ns) break dat = { diff --git a/tests/get_version.py b/tests/get_version.py index 116d8abecd..a0138122ba 100755 --- a/tests/get_version.py +++ b/tests/get_version.py @@ -4,4 +4,4 @@ if __name__ == "__main__": for p in Panda.list(): pp = Panda(p) - print("%s: %s" % (pp.get_serial()[0], pp.get_version())) + print(f"{pp.get_serial()[0]}: {pp.get_version()}") diff --git a/tests/gmbitbang/recv.py b/tests/gmbitbang/recv.py index 73285e7e59..8dc594de46 100755 --- a/tests/gmbitbang/recv.py +++ b/tests/gmbitbang/recv.py @@ -1,5 +1,4 @@ #!/usr/bin/env python3 -from typing import Optional from panda import Panda @@ -8,7 +7,7 @@ p.set_safety_mode(Panda.SAFETY_ALLOUTPUT) p.set_gmlan(bus=2) #p.can_send(0xaaa, b"\x00\x00", bus=3) - last_add: Optional[int] = None + last_add: int | None = None while True: ret = p.can_recv() if len(ret) > 0: diff --git a/tests/hitl/4_can_loopback.py b/tests/hitl/4_can_loopback.py index f00bc95471..a7e1aea1ee 100644 --- a/tests/hitl/4_can_loopback.py +++ b/tests/hitl/4_can_loopback.py @@ -24,7 +24,7 @@ def test(p_send, p_recv): saturation_pct = (comp_kbps / speed) * 100.0 assert 80 < saturation_pct < 100 - print("two pandas bus {}, 100 messages at speed {:4d}, comp speed is {:7.2f}, {:6.2f}%".format(bus, speed, comp_kbps, saturation_pct)) + print(f"two pandas bus {bus}, 100 messages at speed {speed:4d}, comp speed is {comp_kbps:7.2f}, {saturation_pct:6.2f}%") # Run tests in both directions p.set_safety_mode(Panda.SAFETY_ALLOUTPUT) @@ -59,7 +59,7 @@ def test(p_send, p_recv): r_echo = p_send.can_recv() if len(r) == 0 or len(r_echo) == 0: - print("r: {}, r_echo: {}".format(r, r_echo)) + print(f"r: {r}, r_echo: {r_echo}") assert len(r) == 1 assert len(r_echo) == 1 diff --git a/tests/hitl/helpers.py b/tests/hitl/helpers.py index d7ac4da0d6..4eee437311 100644 --- a/tests/hitl/helpers.py +++ b/tests/hitl/helpers.py @@ -1,6 +1,5 @@ import time import random -from typing import Optional def get_random_can_messages(n): @@ -52,7 +51,7 @@ def time_many_sends(p, bus, p_recv=None, msg_count=100, two_pandas=False, msg_le return comp_kbps -def clear_can_buffers(panda, speed: Optional[int] = None): +def clear_can_buffers(panda, speed: int | None = None): if speed is not None: for bus in range(3): panda.set_can_speed_kbps(bus, speed) diff --git a/tests/libpanda/libpanda_py.py b/tests/libpanda/libpanda_py.py index 1b07543d63..8f876c5512 100644 --- a/tests/libpanda/libpanda_py.py +++ b/tests/libpanda/libpanda_py.py @@ -1,6 +1,6 @@ import os from cffi import FFI -from typing import Any, List, Protocol +from typing import Any, Protocol from panda import LEN_TO_DLC from panda.tests.libpanda.safety_helpers import PandaSafety, setup_safety_helpers @@ -64,7 +64,7 @@ class CANPacket: returned: int extended: int addr: int - data: List[int] + data: list[int] class Panda(PandaSafety, Protocol): # CAN diff --git a/tests/message_drop_test.py b/tests/message_drop_test.py index 99d35b043d..bf485e4545 100755 --- a/tests/message_drop_test.py +++ b/tests/message_drop_test.py @@ -5,7 +5,7 @@ import struct import itertools import threading -from typing import Any, Union, List +from typing import Any from panda import Panda @@ -16,7 +16,7 @@ # Generate unique messages NUM_MESSAGES_PER_BUS = 10000 messages = [bytes(struct.pack("Q", i)) for i in range(NUM_MESSAGES_PER_BUS)] -tx_messages = list(itertools.chain.from_iterable(([[0xaa, None, msg, 0], [0xaa, None, msg, 1], [0xaa, None, msg, 2]] for msg in messages))) +tx_messages = list(itertools.chain.from_iterable([[0xaa, None, msg, 0], [0xaa, None, msg, 1], [0xaa, None, msg, 2]] for msg in messages)) def flood_tx(panda): print('Sending!') @@ -35,7 +35,7 @@ def flood_tx(panda): if __name__ == "__main__": serials = Panda.list() - receiver: Union[Panda, PandaJungle] + receiver: Panda | PandaJungle if JUNGLE: sender = Panda() receiver = PandaJungle() @@ -52,7 +52,7 @@ def flood_tx(panda): threading.Thread(target=flood_tx, args=(sender,)).start() # Receive as much as we can, and stop when there hasn't been anything for a second - rx: List[Any] = [] + rx: list[Any] = [] old_len = 0 last_change = time.monotonic() while time.monotonic() - last_change < 1: diff --git a/tests/read_winusb_descriptors.py b/tests/read_winusb_descriptors.py index ec0534ebab..5d311c9ea9 100755 --- a/tests/read_winusb_descriptors.py +++ b/tests/read_winusb_descriptors.py @@ -12,23 +12,23 @@ print('Microsoft OS String Descriptor') dat = p._handle.controlRead(Panda.REQUEST_IN, 0x06, 3 << 8 | 238, 0, length[0]) if DEBUG: - print('LEN: {}'.format(hex(length[0]))) + print(f'LEN: {hex(length[0])}') hexdump("".join(map(chr, dat))) ms_vendor_code = dat[16] if DEBUG: - print('MS_VENDOR_CODE: {}'.format(hex(length[0]))) + print(f'MS_VENDOR_CODE: {hex(length[0])}') print('\nMicrosoft Compatible ID Feature Descriptor') length = p._handle.controlRead(Panda.REQUEST_IN, ms_vendor_code, 0, 4, 1) if DEBUG: - print('LEN: {}'.format(hex(length[0]))) + print(f'LEN: {hex(length[0])}') dat = p._handle.controlRead(Panda.REQUEST_IN, ms_vendor_code, 0, 4, length[0]) hexdump("".join(map(chr, dat))) print('\nMicrosoft Extended Properties Feature Descriptor') length = p._handle.controlRead(Panda.REQUEST_IN, ms_vendor_code, 0, 5, 1) if DEBUG: - print('LEN: {}'.format(hex(length[0]))) + print(f'LEN: {hex(length[0])}') dat = p._handle.controlRead(Panda.REQUEST_IN, ms_vendor_code, 0, 5, length[0]) hexdump("".join(map(chr, dat))) diff --git a/tests/safety/common.py b/tests/safety/common.py index 8b70966aea..a3c22dffb9 100644 --- a/tests/safety/common.py +++ b/tests/safety/common.py @@ -3,7 +3,7 @@ import unittest import importlib import numpy as np -from typing import Callable, Dict, List, Optional, Tuple +from collections.abc import Callable from opendbc.can.packer import CANPacker # pylint: disable=import-error from panda import ALTERNATIVE_EXPERIENCE @@ -77,7 +77,7 @@ def _tx(self, msg): def _generic_limit_safety_check(self, msg_function: MessageFunction, min_allowed_value: float, max_allowed_value: float, min_possible_value: float, max_possible_value: float, test_delta: float = 1, inactive_value: float = 0, - msg_allowed = True, additional_setup: Optional[Callable[[float], None]] = None): + msg_allowed = True, additional_setup: Callable[[float], None] | None = None): """ Enforces that a signal within a message is only allowed to be sent within a specific range, min_allowed_value -> max_allowed_value. Tests the range of min_possible_value -> max_possible_value with a delta of test_delta. @@ -245,13 +245,13 @@ def test_accel_actuation_limits(self, stock_longitudinal=False): class LongitudinalGasBrakeSafetyTest(PandaSafetyTestBase, abc.ABC): MIN_BRAKE: int = 0 - MAX_BRAKE: Optional[int] = None - MAX_POSSIBLE_BRAKE: Optional[int] = None + MAX_BRAKE: int | None = None + MAX_POSSIBLE_BRAKE: int | None = None MIN_GAS: int = 0 - MAX_GAS: Optional[int] = None + MAX_GAS: int | None = None INACTIVE_GAS = 0 - MAX_POSSIBLE_GAS: Optional[int] = None + MAX_POSSIBLE_GAS: int | None = None def test_gas_brake_limits_correct(self): self.assertIsNotNone(self.MAX_POSSIBLE_BRAKE) @@ -665,9 +665,9 @@ def test_reset_torque_measurements(self): class AngleSteeringSafetyTest(PandaSafetyTestBase): DEG_TO_CAN: float - ANGLE_RATE_BP: List[float] - ANGLE_RATE_UP: List[float] # windup limit - ANGLE_RATE_DOWN: List[float] # unwind limit + ANGLE_RATE_BP: list[float] + ANGLE_RATE_UP: list[float] # windup limit + ANGLE_RATE_DOWN: list[float] # unwind limit @classmethod def setUpClass(cls): @@ -771,14 +771,14 @@ def test_angle_cmd_when_disabled(self): class PandaSafetyTest(PandaSafetyTestBase): - TX_MSGS: Optional[List[List[int]]] = None + TX_MSGS: list[list[int]] | None = None SCANNED_ADDRS = [*range(0x800), # Entire 11-bit CAN address space *range(0x18DA00F1, 0x18DB00F1, 0x100), # 29-bit UDS physical addressing *range(0x18DB00F1, 0x18DC00F1, 0x100), # 29-bit UDS functional addressing *range(0x3300, 0x3400), # Honda 0x10400060, 0x104c006c] # GMLAN (exceptions, range/format unclear) - FWD_BLACKLISTED_ADDRS: Dict[int, List[int]] = {} # {bus: [addr]} - FWD_BUS_LOOKUP: Dict[int, int] = {} + FWD_BLACKLISTED_ADDRS: dict[int, list[int]] = {} # {bus: [addr]} + FWD_BUS_LOOKUP: dict[int, int] = {} @classmethod def setUpClass(cls): @@ -895,9 +895,9 @@ def test_tx_hook_on_wrong_safety_mode(self): @add_regen_tests class PandaCarSafetyTest(PandaSafetyTest): - STANDSTILL_THRESHOLD: Optional[float] = None + STANDSTILL_THRESHOLD: float | None = None GAS_PRESSED_THRESHOLD = 0 - RELAY_MALFUNCTION_ADDRS: Optional[Dict[int, Tuple[int, ...]]] = None + RELAY_MALFUNCTION_ADDRS: dict[int, tuple[int, ...]] | None = None @classmethod def setUpClass(cls): diff --git a/tests/safety/hyundai_common.py b/tests/safety/hyundai_common.py index 3fd36a0e1a..da18671af5 100644 --- a/tests/safety/hyundai_common.py +++ b/tests/safety/hyundai_common.py @@ -1,4 +1,3 @@ -from typing import Tuple import unittest import panda.tests.safety.common as common @@ -77,8 +76,8 @@ def test_sampling_cruise_buttons(self): class HyundaiLongitudinalBase(common.LongitudinalAccelSafetyTest): # pylint: disable=no-member,abstract-method - DISABLED_ECU_UDS_MSG: Tuple[int, int] - DISABLED_ECU_ACTUATION_MSG: Tuple[int, int] + DISABLED_ECU_UDS_MSG: tuple[int, int] + DISABLED_ECU_ACTUATION_MSG: tuple[int, int] @classmethod def setUpClass(cls): diff --git a/tests/safety/test_gm.py b/tests/safety/test_gm.py index 587aa3f1cf..28b2ad50ec 100755 --- a/tests/safety/test_gm.py +++ b/tests/safety/test_gm.py @@ -1,6 +1,5 @@ #!/usr/bin/env python3 import unittest -from typing import Dict, List from panda import Panda from panda.tests.libpanda import libpanda_py import panda.tests.safety.common as common @@ -147,8 +146,8 @@ class TestGmAscmSafety(GmLongitudinalBase, TestGmSafetyBase): [0xA1, 1], [0x306, 1], [0x308, 1], [0x310, 1], # obs bus [0x315, 2], # ch bus [0x104c006c, 3], [0x10400060, 3]] # gmlan - FWD_BLACKLISTED_ADDRS: Dict[int, List[int]] = {} - FWD_BUS_LOOKUP: Dict[int, int] = {} + FWD_BLACKLISTED_ADDRS: dict[int, list[int]] = {} + FWD_BUS_LOOKUP: dict[int, int] = {} BRAKE_BUS = 2 MAX_GAS = 3072 diff --git a/tests/safety/test_honda.py b/tests/safety/test_honda.py index 08d069b5ed..45f190c36a 100755 --- a/tests/safety/test_honda.py +++ b/tests/safety/test_honda.py @@ -1,7 +1,6 @@ #!/usr/bin/env python3 import unittest import numpy as np -from typing import Optional from panda import Panda from panda.tests.libpanda import libpanda_py @@ -170,9 +169,9 @@ def test_buttons(self): class HondaBase(common.PandaCarSafetyTest): MAX_BRAKE = 255 - PT_BUS: Optional[int] = None # must be set when inherited - STEER_BUS: Optional[int] = None # must be set when inherited - BUTTONS_BUS: Optional[int] = None # must be set when inherited, tx on this bus, rx on PT_BUS + PT_BUS: int | None = None # must be set when inherited + STEER_BUS: int | None = None # must be set when inherited + BUTTONS_BUS: int | None = None # must be set when inherited, tx on this bus, rx on PT_BUS STANDSTILL_THRESHOLD = 0 RELAY_MALFUNCTION_ADDRS = {0: (0xE4, 0x194)} # STEERING_CONTROL