From 94418a0d93ab5e17f72bc133611446d544d5e22d Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Tue, 6 Feb 2024 11:14:58 -0800 Subject: [PATCH 01/67] pre-commit: autoupdate hooks (#1857) 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 bffb7447e..5788e16b2 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.1.15 + rev: v0.2.1 hooks: - id: ruff From 5c5287dabb50f31aa53ad6d17319fea8699dfb2f Mon Sep 17 00:00:00 2001 From: dzid26 Date: Tue, 6 Feb 2024 19:15:22 +0000 Subject: [PATCH 02/67] Fix CAN comment (#1854) --- board/boards/black.h | 2 +- board/boards/dos.h | 2 +- board/boards/red.h | 2 +- board/boards/red_chiplet.h | 2 +- board/boards/uno.h | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/board/boards/black.h b/board/boards/black.h index 2e5015700..bf8d5bd74 100644 --- a/board/boards/black.h +++ b/board/boards/black.h @@ -136,7 +136,7 @@ void black_init(void) { // Set normal CAN mode black_set_can_mode(CAN_MODE_NORMAL); - // flip CAN0 and CAN2 if we are flipped + // change CAN mapping when flipped if (harness.status == HARNESS_STATUS_FLIPPED) { can_flip_buses(0, 2); } diff --git a/board/boards/dos.h b/board/boards/dos.h index b234d51a8..69e9169c2 100644 --- a/board/boards/dos.h +++ b/board/boards/dos.h @@ -168,7 +168,7 @@ void dos_init(void) { // Set normal CAN mode dos_set_can_mode(CAN_MODE_NORMAL); - // flip CAN0 and CAN2 if we are flipped + // change CAN mapping when flipped if (harness.status == HARNESS_STATUS_FLIPPED) { can_flip_buses(0, 2); } diff --git a/board/boards/red.h b/board/boards/red.h index 05e6e7530..1bf33d609 100644 --- a/board/boards/red.h +++ b/board/boards/red.h @@ -150,7 +150,7 @@ void red_init(void) { // Set normal CAN mode red_set_can_mode(CAN_MODE_NORMAL); - // flip CAN0 and CAN2 if we are flipped + // change CAN mapping when flipped if (harness.status == HARNESS_STATUS_FLIPPED) { can_flip_buses(0, 2); } diff --git a/board/boards/red_chiplet.h b/board/boards/red_chiplet.h index 1301cd3e5..205574f20 100644 --- a/board/boards/red_chiplet.h +++ b/board/boards/red_chiplet.h @@ -133,7 +133,7 @@ void red_chiplet_init(void) { // Set normal CAN mode red_chiplet_set_can_mode(CAN_MODE_NORMAL); - // flip CAN0 and CAN2 if we are flipped + // change CAN mapping when flipped if (harness.status == HARNESS_STATUS_FLIPPED) { can_flip_buses(0, 2); } diff --git a/board/boards/uno.h b/board/boards/uno.h index 947d60d13..29f0a0c59 100644 --- a/board/boards/uno.h +++ b/board/boards/uno.h @@ -161,7 +161,7 @@ void uno_init(void) { // Set normal CAN mode uno_set_can_mode(CAN_MODE_NORMAL); - // flip CAN0 and CAN2 if we are flipped + // change CAN mapping when flipped if (harness.status == HARNESS_STATUS_FLIPPED) { can_flip_buses(0, 2); } From 04c5a00a9ecc96401d2e59a06bd15c84abd641de Mon Sep 17 00:00:00 2001 From: dzid26 Date: Tue, 6 Feb 2024 19:15:46 +0000 Subject: [PATCH 03/67] Board chip type (#1853) Board chip type title --- board/boards/black.h | 6 +++--- board/boards/cuatro.h | 4 ++++ board/boards/dos.h | 6 +++--- board/boards/grey.h | 6 +++--- board/boards/pedal.h | 6 +++--- board/boards/red.h | 6 +++--- board/boards/red_chiplet.h | 6 +++--- board/boards/tres.h | 6 +++--- board/boards/uno.h | 6 +++--- board/boards/white.h | 6 +++--- board/jungle/boards/board_v1.h | 3 +++ board/jungle/boards/board_v2.h | 3 +++ 12 files changed, 37 insertions(+), 27 deletions(-) diff --git a/board/boards/black.h b/board/boards/black.h index bf8d5bd74..d72ab39aa 100644 --- a/board/boards/black.h +++ b/board/boards/black.h @@ -1,6 +1,6 @@ -// ///////////////////// // -// Black Panda + Harness // -// ///////////////////// // +// /////////////////////////////// // +// Black Panda (STM32F4) + Harness // +// /////////////////////////////// // void black_enable_can_transceiver(uint8_t transceiver, bool enabled) { switch (transceiver){ diff --git a/board/boards/cuatro.h b/board/boards/cuatro.h index 0950e1e53..049e6e20a 100644 --- a/board/boards/cuatro.h +++ b/board/boards/cuatro.h @@ -1,3 +1,7 @@ +// ////////////////////////// // +// Cuatro (STM32H7) + Harness // +// ////////////////////////// // + void cuatro_set_led(uint8_t color, bool enabled) { switch (color) { case LED_RED: diff --git a/board/boards/dos.h b/board/boards/dos.h index 69e9169c2..e93c01591 100644 --- a/board/boards/dos.h +++ b/board/boards/dos.h @@ -1,6 +1,6 @@ -// ///////////// // -// Dos + Harness // -// ///////////// // +// /////////////////////// // +// Dos (STM32F4) + Harness // +// /////////////////////// // void dos_enable_can_transceiver(uint8_t transceiver, bool enabled) { switch (transceiver){ diff --git a/board/boards/grey.h b/board/boards/grey.h index a7a4cc044..e8f90e263 100644 --- a/board/boards/grey.h +++ b/board/boards/grey.h @@ -1,6 +1,6 @@ -// ////////// // -// Grey Panda // -// ////////// // +// //////////////////// // +// Grey Panda (STM32F4) // +// //////////////////// // // Most hardware functionality is similar to white panda diff --git a/board/boards/pedal.h b/board/boards/pedal.h index c1569beac..2b653e9ed 100644 --- a/board/boards/pedal.h +++ b/board/boards/pedal.h @@ -1,6 +1,6 @@ -// ///// // -// Pedal // -// ///// // +// ///////////// // +// Pedal STM32F2 // +// ///////////// // void pedal_enable_can_transceiver(uint8_t transceiver, bool enabled) { switch (transceiver){ diff --git a/board/boards/red.h b/board/boards/red.h index 1bf33d609..58410894b 100644 --- a/board/boards/red.h +++ b/board/boards/red.h @@ -1,6 +1,6 @@ -// ///////////////////// // -// Red Panda + Harness // -// ///////////////////// // +// ///////////////////////////// // +// Red Panda (STM32H7) + Harness // +// ///////////////////////////// // void red_enable_can_transceiver(uint8_t transceiver, bool enabled) { switch (transceiver) { diff --git a/board/boards/red_chiplet.h b/board/boards/red_chiplet.h index 205574f20..eec3d95cd 100644 --- a/board/boards/red_chiplet.h +++ b/board/boards/red_chiplet.h @@ -1,6 +1,6 @@ -// ///////////////////// // -// Red Panda chiplet + Harness // -// ///////////////////// // +// ///////////////////////////////////// // +// Red Panda chiplet (STM32H7) + Harness // +// ///////////////////////////////////// // // Most hardware functionality is similar to red panda diff --git a/board/boards/tres.h b/board/boards/tres.h index 3a5d89618..4e8564b20 100644 --- a/board/boards/tres.h +++ b/board/boards/tres.h @@ -1,6 +1,6 @@ -// ///////////////// -// Tres + Harness // -// ///////////////// +// /////////////////////////// +// Tres (STM32H7) + Harness // +// /////////////////////////// bool tres_ir_enabled; bool tres_fan_enabled; diff --git a/board/boards/uno.h b/board/boards/uno.h index 29f0a0c59..5f8af593d 100644 --- a/board/boards/uno.h +++ b/board/boards/uno.h @@ -1,6 +1,6 @@ -// ///////////// // -// Uno + Harness // -// ///////////// // +// /////////////////////// // +// Uno (STM32F4) + Harness // +// /////////////////////// // void uno_enable_can_transceiver(uint8_t transceiver, bool enabled) { switch (transceiver){ diff --git a/board/boards/white.h b/board/boards/white.h index 680e3cb05..5048c0779 100644 --- a/board/boards/white.h +++ b/board/boards/white.h @@ -1,6 +1,6 @@ -// /////////// // -// White Panda // -// /////////// // +// ///////////////////// // +// White Panda (STM32F4) // +// ///////////////////// // void white_enable_can_transceiver(uint8_t transceiver, bool enabled) { switch (transceiver){ diff --git a/board/jungle/boards/board_v1.h b/board/jungle/boards/board_v1.h index 29c23d6df..9581686e2 100644 --- a/board/jungle/boards/board_v1.h +++ b/board/jungle/boards/board_v1.h @@ -1,3 +1,6 @@ +// ///////////////////////// // +// Jungle board v1 (STM32F4) // +// ///////////////////////// // void board_v1_set_led(uint8_t color, bool enabled) { switch (color) { diff --git a/board/jungle/boards/board_v2.h b/board/jungle/boards/board_v2.h index 7bce61ebb..095114825 100644 --- a/board/jungle/boards/board_v2.h +++ b/board/jungle/boards/board_v2.h @@ -1,3 +1,6 @@ +// ///////////////////////// // +// Jungle board v2 (STM32H7) // +// ///////////////////////// // const gpio_t power_pins[] = { {.bank = GPIOA, .pin = 0}, From ad0f372adabef438d67340c6b9c76ba7146d0671 Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Tue, 6 Feb 2024 22:29:42 -0800 Subject: [PATCH 04/67] cuatro can fixes (#1858) * more can * other af * cleanup * misra fix --------- Co-authored-by: Comma Device --- board/boards/cuatro.h | 43 ++++++++++++++++++++++++++++++++----------- 1 file changed, 32 insertions(+), 11 deletions(-) diff --git a/board/boards/cuatro.h b/board/boards/cuatro.h index 049e6e20a..ed120bb05 100644 --- a/board/boards/cuatro.h +++ b/board/boards/cuatro.h @@ -19,29 +19,50 @@ void cuatro_set_led(uint8_t color, bool enabled) { } void cuatro_enable_can_transceiver(uint8_t transceiver, bool enabled) { - if (transceiver == 1U) { - set_gpio_output(GPIOB, 7, !enabled); - } else if (transceiver == 3U) { - set_gpio_output(GPIOD, 8, !enabled); - } else { - red_enable_can_transceiver(transceiver, enabled); + switch (transceiver) { + case 1U: + set_gpio_output(GPIOB, 7, !enabled); + break; + case 2U: + set_gpio_output(GPIOB, 10, !enabled); + break; + case 3U: + set_gpio_output(GPIOD, 8, !enabled); + break; + case 4U: + set_gpio_output(GPIOB, 11, !enabled); + break; + default: + break; + } +} + +void cuatro_enable_can_transceivers(bool enabled) { + uint8_t main_bus = (harness.status == HARNESS_STATUS_FLIPPED) ? 3U : 1U; + for (uint8_t i=1U; i<=4U; i++) { + // Leave main CAN always on for CAN-based ignition detection + if (i == main_bus) { + cuatro_enable_can_transceiver(i, true); + } else { + cuatro_enable_can_transceiver(i, enabled); + } } } void cuatro_init(void) { red_chiplet_init(); - // CAN FD 0 transceiver enable (rest are done in red init) + // CAN transceiver enables set_gpio_pullup(GPIOB, 7, PULL_NONE); set_gpio_mode(GPIOB, 7, MODE_OUTPUT); set_gpio_pullup(GPIOD, 8, PULL_NONE); set_gpio_mode(GPIOD, 8, MODE_OUTPUT); - // FDCAN2 + // FDCAN3, different pins on this package than the rest of the reds set_gpio_pullup(GPIOD, 12, PULL_NONE); - set_gpio_alternate(GPIOD, 12, GPIO_AF9_FDCAN2); + set_gpio_alternate(GPIOD, 12, GPIO_AF5_FDCAN3); set_gpio_pullup(GPIOD, 13, PULL_NONE); - set_gpio_alternate(GPIOD, 13, GPIO_AF9_FDCAN2); + set_gpio_alternate(GPIOD, 13, GPIO_AF5_FDCAN3); // C2: SOM GPIO used as input (fan control at boot) set_gpio_mode(GPIOC, 2, MODE_INPUT); @@ -83,7 +104,7 @@ const board board_cuatro = { .init = cuatro_init, .init_bootloader = unused_init_bootloader, .enable_can_transceiver = cuatro_enable_can_transceiver, - .enable_can_transceivers = red_chiplet_enable_can_transceivers, + .enable_can_transceivers = cuatro_enable_can_transceivers, .set_led = cuatro_set_led, .set_can_mode = red_chiplet_set_can_mode, .check_ignition = red_check_ignition, From 32301a855a2305534303764c078d4946c430c4c1 Mon Sep 17 00:00:00 2001 From: dzid26 Date: Fri, 9 Feb 2024 06:33:26 +0000 Subject: [PATCH 05/67] USB-C cable orientation clarification (#1860) --- board/drivers/harness.h | 1 + 1 file changed, 1 insertion(+) diff --git a/board/drivers/harness.h b/board/drivers/harness.h index 2b6b5e6d8..60f99fc85 100644 --- a/board/drivers/harness.h +++ b/board/drivers/harness.h @@ -95,6 +95,7 @@ uint8_t harness_detect_orientation(void) { ret = HARNESS_STATUS_FLIPPED; } else { // orientation normal (PANDA_SBU2->HARNESS_SBU1(relay), PANDA_SBU1->HARNESS_SBU2(ign)) + // (SBU1->SBU2 is the normal orientation connection per USB-C cable spec) ret = HARNESS_STATUS_NORMAL; } } else { From 54459e694eaa6dcc3f5eab0c4c9a15c6a88aa93d Mon Sep 17 00:00:00 2001 From: Aryan <53595853+0x41head@users.noreply.github.com> Date: Sun, 11 Feb 2024 04:20:36 +0530 Subject: [PATCH 06/67] update cppcheck (#1859) * update cppcheck * Update tests/misra/install.sh * delete cppcheck cache * remove misra 5.8 erroors * fixed uninitialized data error * suppress misra-c2012-2.3 and misra-c2012-2.4 * reinstate cache to fix mutation test * rerun for mutation test * increase timeout for mutation test * styling * comments + variable name changes * Update tests/misra/install.sh Co-authored-by: Adeeb Shihadeh * Update install.sh * more variable name changes * condition on defining CANPacket_t * just cherry pick * fix build --------- Co-authored-by: Adeeb Shihadeh --- .github/workflows/test.yaml | 2 +- board/can_definitions.h | 2 ++ board/drivers/can_common.h | 4 ++-- board/drivers/usb.h | 34 +++++++++++++++++----------------- board/health.h | 6 +++--- board/main_comms.h | 6 +++--- tests/misra/install.sh | 5 ++++- 7 files changed, 32 insertions(+), 27 deletions(-) diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index 718aaa8a6..5f65560dd 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -120,7 +120,7 @@ jobs: timeout-minutes: 1 run: ${{ env.RUN }} "cd tests/misra && ./test_misra.sh" - name: MISRA mutation tests - timeout-minutes: 3 + timeout-minutes: 4 run: ${{ env.RUN }} "cd tests/misra && ./test_mutation.py" python_linter: diff --git a/board/can_definitions.h b/board/can_definitions.h index daae4d044..db3d62170 100644 --- a/board/can_definitions.h +++ b/board/can_definitions.h @@ -15,6 +15,7 @@ const uint8_t PANDA_BUS_CNT = 4U; #define CANPACKET_DATA_SIZE_MAX 8U #endif +#ifndef STM32F2 typedef struct { unsigned char reserved : 1; unsigned char bus : 3; @@ -26,6 +27,7 @@ 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/drivers/can_common.h b/board/drivers/can_common.h index 574c7cfd5..db77617e7 100644 --- a/board/drivers/can_common.h +++ b/board/drivers/can_common.h @@ -277,10 +277,10 @@ void can_send(CANPacket_t *to_push, uint8_t bus_number, bool skip_tx_hook) { } } -bool is_speed_valid(uint32_t speed, const uint32_t *speeds, uint8_t len) { +bool is_speed_valid(uint32_t speed, const uint32_t *all_speeds, uint8_t len) { bool ret = false; for (uint8_t i = 0U; i < len; i++) { - if (speeds[i] == speed) { + if (all_speeds[i] == speed) { ret = true; } } diff --git a/board/drivers/usb.h b/board/drivers/usb.h index 99ba126ce..ed74b9328 100644 --- a/board/drivers/usb.h +++ b/board/drivers/usb.h @@ -79,7 +79,7 @@ void refresh_can_tx_slots_available(void); #define STS_SETUP_COMP 4 #define STS_SETUP_UPDT 6 -uint8_t resp[USBPACKET_MAX_SIZE]; +uint8_t response[USBPACKET_MAX_SIZE]; // for the repeating interfaces #define DSCR_INTERFACE_LEN 9 @@ -557,19 +557,19 @@ void usb_setup(void) { break; case STRING_OFFSET_ISERIAL: #ifdef UID_BASE - resp[0] = 0x02 + (12 * 4); - resp[1] = 0x03; + response[0] = 0x02 + (12 * 4); + response[1] = 0x03; // 96 bits = 12 bytes for (int i = 0; i < 12; i++){ uint8_t cc = ((uint8_t *)UID_BASE)[i]; - resp[2 + (i * 4)] = to_hex_char((cc >> 4) & 0xFU); - resp[2 + (i * 4) + 1] = '\0'; - resp[2 + (i * 4) + 2] = to_hex_char((cc >> 0) & 0xFU); - resp[2 + (i * 4) + 3] = '\0'; + response[2 + (i * 4)] = to_hex_char((cc >> 4) & 0xFU); + response[2 + (i * 4) + 1] = '\0'; + response[2 + (i * 4) + 2] = to_hex_char((cc >> 0) & 0xFU); + response[2 + (i * 4) + 3] = '\0'; } - USB_WritePacket(resp, MIN(resp[0], setup.b.wLength.w), 0); + USB_WritePacket(response, MIN(response[0], setup.b.wLength.w), 0); #else USB_WritePacket((const uint8_t *)string_serial_desc, MIN(sizeof(string_serial_desc), setup.b.wLength.w), 0); #endif @@ -599,10 +599,10 @@ void usb_setup(void) { } break; case USB_REQ_GET_STATUS: - // empty resp? - resp[0] = 0; - resp[1] = 0; - USB_WritePacket((void*)&resp, 2, 0); + // empty response? + response[0] = 0; + response[1] = 0; + USB_WritePacket((void*)&response, 2, 0); USBx_OUTEP(0)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; break; case USB_REQ_SET_INTERFACE: @@ -648,10 +648,10 @@ void usb_setup(void) { control_req.param2 = setup.b.wIndex.w; control_req.length = setup.b.wLength.w; - resp_len = comms_control_handler(&control_req, resp); + resp_len = comms_control_handler(&control_req, response); // response pending if -1 was returned if (resp_len != -1) { - USB_WritePacket(resp, MIN(resp_len, setup.b.wLength.w), 0); + USB_WritePacket(response, MIN(resp_len, setup.b.wLength.w), 0); USBx_OUTEP(0)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; } } @@ -877,7 +877,7 @@ void usb_irqhandler(void) { print(" IN PACKET QUEUE\n"); #endif // TODO: always assuming max len, can we get the length? - USB_WritePacket((void *)resp, comms_can_read(resp, 0x40), 1); + USB_WritePacket((void *)response, comms_can_read(response, 0x40), 1); } break; @@ -888,9 +888,9 @@ void usb_irqhandler(void) { print(" IN PACKET QUEUE\n"); #endif // TODO: always assuming max len, can we get the length? - int len = comms_can_read(resp, 0x40); + int len = comms_can_read(response, 0x40); if (len > 0) { - USB_WritePacket((void *)resp, len, 1); + USB_WritePacket((void *)response, len, 1); } } break; diff --git a/board/health.h b/board/health.h index 8745cb0e7..fc7661ca9 100644 --- a/board/health.h +++ b/board/health.h @@ -21,10 +21,10 @@ struct __attribute__((packed)) health_t { uint8_t power_save_enabled_pkt; uint8_t heartbeat_lost_pkt; uint16_t alternative_experience_pkt; - float interrupt_load; + float interrupt_load_pkt; uint8_t fan_power; - uint8_t safety_rx_checks_invalid; - uint16_t spi_checksum_error_count; + uint8_t safety_rx_checks_invalid_pkt; + uint16_t spi_checksum_error_count_pkt; uint8_t fan_stall_count; uint16_t sbu1_voltage_mV; uint16_t sbu2_voltage_mV; diff --git a/board/main_comms.h b/board/main_comms.h index 116f95d0e..f535af662 100644 --- a/board/main_comms.h +++ b/board/main_comms.h @@ -28,14 +28,14 @@ int get_health_pkt(void *dat) { health->alternative_experience_pkt = alternative_experience; health->power_save_enabled_pkt = power_save_status == POWER_SAVE_STATUS_ENABLED; health->heartbeat_lost_pkt = heartbeat_lost; - health->safety_rx_checks_invalid = safety_rx_checks_invalid; + health->safety_rx_checks_invalid_pkt = safety_rx_checks_invalid; - health->spi_checksum_error_count = spi_checksum_error_count; + health->spi_checksum_error_count_pkt = spi_checksum_error_count; health->fault_status_pkt = fault_status; health->faults_pkt = faults; - health->interrupt_load = interrupt_load; + health->interrupt_load_pkt = interrupt_load; health->fan_power = fan_state.power; health->fan_stall_count = fan_state.total_stall_count; diff --git a/tests/misra/install.sh b/tests/misra/install.sh index 213962645..a29b11117 100755 --- a/tests/misra/install.sh +++ b/tests/misra/install.sh @@ -9,8 +9,11 @@ if [ ! -d "$CPPCHECK_DIR" ]; then fi cd $CPPCHECK_DIR + VERS="2.13.0" -git fetch --tags origin $VERS +git fetch --all --tags git checkout $VERS +git cherry-pick -n f6b538e855f0bacea33c4074664628024ef39dc6 + #make clean make MATCHCOMPILTER=yes CXXFLAGS="-O2" -j8 From 87f87d49ac24e016d9b2d775c331ad8238d262b2 Mon Sep 17 00:00:00 2001 From: Jason Young <46612682+jyoung8607@users.noreply.github.com> Date: Tue, 13 Feb 2024 17:28:21 -0500 Subject: [PATCH 07/67] invoke system browser for coverage reports (#1862) --- tests/safety/test_coverage.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/safety/test_coverage.sh b/tests/safety/test_coverage.sh index a1dc1f046..fa27716a7 100755 --- a/tests/safety/test_coverage.sh +++ b/tests/safety/test_coverage.sh @@ -12,7 +12,7 @@ scons -j$(nproc) -D --coverage if [ "$1" == "--report" ]; then geninfo ../libpanda/ -o coverage.info genhtml coverage.info -o coverage-out - browse coverage-out/index.html + sensible-browser coverage-out/index.html fi # test coverage From e41c157a2469a93764bb24f3ffe9626b6de27436 Mon Sep 17 00:00:00 2001 From: Shane Smiskol Date: Tue, 13 Feb 2024 18:48:17 -0600 Subject: [PATCH 08/67] fix pytest loop (#1863) * fix pytest loop * auto * Revert "auto" This reverts commit 8fa51c8e986627b3f4731b731b2edde5e0bcfb52. --- pyproject.toml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index bac2d7f08..0d8709db3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -5,3 +5,7 @@ ignore = ["W292", "E741", "E402", "C408", "ISC003"] line-length = 160 target-version="py311" flake8-implicit-str-concat.allow-multiline=false + +[tool.pytest.ini_options] +# FIXME: pytest 8.0.0 now collects all files, stop pytest-cpp from running these +addopts = "--ignore=test.sh --ignore=test_coverage.sh" From a99387d52da1fd34086c52e8ff15c82ea151f4ad Mon Sep 17 00:00:00 2001 From: Shane Smiskol Date: Tue, 13 Feb 2024 18:57:45 -0600 Subject: [PATCH 09/67] pytest improvements (#1864) * move these to pyproject so you can do pytest . * add comment for bug * add comment for bug --- pyproject.toml | 3 ++- tests/safety/test.sh | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 0d8709db3..2b5b18c36 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -8,4 +8,5 @@ flake8-implicit-str-concat.allow-multiline=false [tool.pytest.ini_options] # FIXME: pytest 8.0.0 now collects all files, stop pytest-cpp from running these -addopts = "--ignore=test.sh --ignore=test_coverage.sh" +# the `not Base` filter is needed due to a bug in pytest w/ unittest: https://github.com/pytest-dev/pytest/issues/11552 +addopts = "--ignore=test.sh --ignore=test_coverage.sh -n auto -k 'not Base'" diff --git a/tests/safety/test.sh b/tests/safety/test.sh index d01c5009c..22620dfe9 100755 --- a/tests/safety/test.sh +++ b/tests/safety/test.sh @@ -7,5 +7,5 @@ cd $DIR HW_TYPES=( 6 9 ) for hw_type in "${HW_TYPES[@]}"; do echo "Testing HW_TYPE: $hw_type" - HW_TYPE=$hw_type pytest -n auto test_*.py -k 'not Base' + HW_TYPE=$hw_type pytest test_*.py done From aca33b83a4a038b9e72ec77db9d7f3c23972e243 Mon Sep 17 00:00:00 2001 From: Shane Smiskol Date: Tue, 13 Feb 2024 19:27:19 -0600 Subject: [PATCH 10/67] tests: one file for safety and coverage tests (#1865) * one file for all tests * clean up * unreachable * Revert "unreachable" This reverts commit 4b792b1f9b5290b57975d21c24be5029be16b0e3. --- .github/workflows/test.yaml | 17 ----------------- pyproject.toml | 2 +- tests/safety/test.sh | 23 +++++++++++++++++++++++ tests/safety/test_coverage.sh | 27 --------------------------- 4 files changed, 24 insertions(+), 45 deletions(-) delete mode 100755 tests/safety/test_coverage.sh diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index 5f65560dd..8f1c5f019 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -89,23 +89,6 @@ jobs: scons -j$(nproc) ${{ matrix.flags }} && \ tests/safety/test.sh" - safety_coverage: - name: safety coverage - runs-on: ubuntu-20.04 - timeout-minutes: 20 - steps: - - uses: actions/checkout@v2 - - name: Build Docker image - run: eval "$BUILD" - - name: Run safety coverage test - timeout-minutes: 5 - run: | - ${{ env.RUN }} "cd .. && \ - scons -c && \ - scons -j$(nproc) opendbc/ cereal/ && \ - cd panda/tests/safety && \ - ./test_coverage.sh" - misra: name: MISRA C:2012 runs-on: ubuntu-20.04 diff --git a/pyproject.toml b/pyproject.toml index 2b5b18c36..72bce22be 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -9,4 +9,4 @@ flake8-implicit-str-concat.allow-multiline=false [tool.pytest.ini_options] # FIXME: pytest 8.0.0 now collects all files, stop pytest-cpp from running these # the `not Base` filter is needed due to a bug in pytest w/ unittest: https://github.com/pytest-dev/pytest/issues/11552 -addopts = "--ignore=test.sh --ignore=test_coverage.sh -n auto -k 'not Base'" +addopts = "--ignore=test.sh -n auto -k 'not Base'" diff --git a/tests/safety/test.sh b/tests/safety/test.sh index 22620dfe9..13703b26a 100755 --- a/tests/safety/test.sh +++ b/tests/safety/test.sh @@ -4,8 +4,31 @@ set -e DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null && pwd)" cd $DIR +# reset coverage data and generate gcc note file +rm -f ../libpanda/*.gcda +scons -j$(nproc) -D --coverage + +# run safety tests and generate coverage data HW_TYPES=( 6 9 ) for hw_type in "${HW_TYPES[@]}"; do echo "Testing HW_TYPE: $hw_type" HW_TYPE=$hw_type pytest test_*.py done + +# generate and open report +if [ "$1" == "--report" ]; then + geninfo ../libpanda/ -o coverage.info + genhtml coverage.info -o coverage-out + sensible-browser coverage-out/index.html +fi + +# test coverage +GCOV_OUTPUT=$(gcov -n ../libpanda/panda.c) +INCOMPLETE_COVERAGE=$(echo "$GCOV_OUTPUT" | paste -s -d' \n' | grep -E "File.*(safety\/safety_.*)|(safety)\.h" | grep -v "100.00%" || true) +if [ -n "$INCOMPLETE_COVERAGE" ]; then + echo "FAILED: Some files have less than 100% coverage:" + echo "$INCOMPLETE_COVERAGE" + exit 1 +else + echo "SUCCESS: All checked files have 100% coverage!" +fi diff --git a/tests/safety/test_coverage.sh b/tests/safety/test_coverage.sh deleted file mode 100755 index fa27716a7..000000000 --- a/tests/safety/test_coverage.sh +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env bash -set -e - -# reset coverage data and generate gcc note file -rm -f ../libpanda/*.gcda -scons -j$(nproc) -D --coverage - -# run safety tests to generate coverage data -./test.sh - -# generate and open report -if [ "$1" == "--report" ]; then - geninfo ../libpanda/ -o coverage.info - genhtml coverage.info -o coverage-out - sensible-browser coverage-out/index.html -fi - -# test coverage -GCOV_OUTPUT=$(gcov -n ../libpanda/panda.c) -INCOMPLETE_COVERAGE=$(echo "$GCOV_OUTPUT" | paste -s -d' \n' | grep -E "File.*(safety\/safety_.*)|(safety)\.h" | grep -v "100.00%" || true) -if [ -n "$INCOMPLETE_COVERAGE" ]; then - echo "FAILED: Some files have less than 100% coverage:" - echo "$INCOMPLETE_COVERAGE" - exit 1 -else - echo "SUCCESS: All checked files have 100% coverage!" -fi From be7c4059a244b3ad74b7135142d7aaaa1e765160 Mon Sep 17 00:00:00 2001 From: Jason Young <46612682+jyoung8607@users.noreply.github.com> Date: Wed, 14 Feb 2024 11:25:03 -0500 Subject: [PATCH 11/67] VW MQB: RxChecks for GRA_ACC_01 (#1866) --- board/safety/safety_volkswagen_mqb.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/board/safety/safety_volkswagen_mqb.h b/board/safety/safety_volkswagen_mqb.h index 3145ea907..10adc679d 100644 --- a/board/safety/safety_volkswagen_mqb.h +++ b/board/safety/safety_volkswagen_mqb.h @@ -46,6 +46,7 @@ RxCheck volkswagen_mqb_rx_checks[] = { {.msg = {{MSG_TSK_06, 0, 8, .check_checksum = true, .max_counter = 15U, .frequency = 50U}, { 0 }, { 0 }}}, {.msg = {{MSG_MOTOR_20, 0, 8, .check_checksum = true, .max_counter = 15U, .frequency = 50U}, { 0 }, { 0 }}}, {.msg = {{MSG_MOTOR_14, 0, 8, .check_checksum = false, .max_counter = 0U, .frequency = 10U}, { 0 }, { 0 }}}, + {.msg = {{MSG_GRA_ACC_01, 0, 8, .check_checksum = true, .max_counter = 15U, .frequency = 33U}, { 0 }, { 0 }}}, }; uint8_t volkswagen_crc8_lut_8h2f[256]; // Static lookup table for CRC8 poly 0x2F, aka 8H2F/AUTOSAR @@ -83,6 +84,8 @@ static uint32_t volkswagen_mqb_compute_crc(const CANPacket_t *to_push) { crc ^= (uint8_t[]){0xC4,0xE2,0x4F,0xE4,0xF8,0x2F,0x56,0x81,0x9F,0xE5,0x83,0x44,0x05,0x3F,0x97,0xDF}[counter]; } else if (addr == MSG_MOTOR_20) { crc ^= (uint8_t[]){0xE9,0x65,0xAE,0x6B,0x7B,0x35,0xE5,0x5F,0x4E,0xC7,0x86,0xA2,0xBB,0xDD,0xEB,0xB4}[counter]; + } else if (addr == MSG_GRA_ACC_01) { + crc ^= (uint8_t[]){0x6A,0x38,0xB4,0x27,0x22,0xEF,0xE1,0xBB,0xF8,0x80,0x84,0x49,0xC7,0x9E,0x1E,0x2B}[counter]; } else { // Undefined CAN message, CRC check expected to fail } From ef68fea95ed0633b05752e56b3fb9f43e324a01b Mon Sep 17 00:00:00 2001 From: Aryan <53595853+0x41head@users.noreply.github.com> Date: Wed, 14 Feb 2024 22:05:14 +0530 Subject: [PATCH 12/67] Make MISRA results consistent across cppcheck runs (#1867) * fixed uninitialized data error * update ci * revert old changes * add styling * switch misra.py to misra * remove cache from mutation.py * works on local * jobs increased to 8 for mutation test * works locally * add env variable back * removed env variable * cleanup --------- Co-authored-by: Adeeb Shihadeh --- tests/misra/.gitignore | 1 + tests/misra/test_misra.sh | 15 +++++++++------ tests/misra/test_mutation.py | 28 ++++++++++------------------ 3 files changed, 20 insertions(+), 24 deletions(-) diff --git a/tests/misra/.gitignore b/tests/misra/.gitignore index 8432f605a..fc9ac228c 100644 --- a/tests/misra/.gitignore +++ b/tests/misra/.gitignore @@ -1,4 +1,5 @@ *.pdf *.txt +.output.log new_table cppcheck/ diff --git a/tests/misra/test_misra.sh b/tests/misra/test_misra.sh index 5504e3cd8..cfc53bac4 100755 --- a/tests/misra/test_misra.sh +++ b/tests/misra/test_misra.sh @@ -29,16 +29,19 @@ if [ -z "${SKIP_BUILD}" ]; then fi cppcheck() { - hashed_args=$(echo -n "$@$DIR" | md5sum | awk '{print $1}') - build_dir=/tmp/cppcheck_build/$hashed_args - mkdir -p $build_dir - + # 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/ \ -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 --cppcheck-build-dir=$build_dir \ - "$@" + --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 "misra violation" $OUTPUT > /dev/null; then + exit 1 + fi } printf "\n${GREEN}** PANDA F4 CODE **${NC}\n" diff --git a/tests/misra/test_mutation.py b/tests/misra/test_mutation.py index f50d27c7f..cc3666f13 100755 --- a/tests/misra/test_mutation.py +++ b/tests/misra/test_mutation.py @@ -5,7 +5,6 @@ import pytest import shutil import subprocess import tempfile -import hashlib import random HERE = os.path.abspath(os.path.dirname(__file__)) @@ -68,25 +67,18 @@ for p in patterns: @pytest.mark.parametrize("fn, patch, should_fail", mutations) def test_misra_mutation(fn, patch, should_fail): - key = hashlib.md5((str(fn) + str(patch)).encode()).hexdigest() - tmp = os.path.join(tempfile.gettempdir(), key) + with tempfile.TemporaryDirectory() as tmp: + shutil.copytree(ROOT, tmp, dirs_exist_ok=True) - if os.path.exists(tmp): - shutil.rmtree(tmp) - shutil.copytree(ROOT, tmp) + # apply patch + if fn is not None: + r = os.system(f"cd {tmp} && sed -i '{patch}' {fn}") + assert r == 0 - # apply patch - if fn is not None: - r = os.system(f"cd {tmp} && sed -i '{patch}' {fn}") - assert r == 0 - - # run test - env = {'SKIP_BUILD': '1'} | os.environ.copy() - r = subprocess.run("tests/misra/test_misra.sh", cwd=tmp, shell=True, env=env) - failed = r.returncode != 0 - assert failed == should_fail - - shutil.rmtree(tmp) + # run test + r = subprocess.run("tests/misra/test_misra.sh", cwd=tmp, shell=True) + failed = r.returncode != 0 + assert failed == should_fail if __name__ == "__main__": pytest.main([__file__, "-n 8"]) From 27768f5ef3b9eeca66bca93d9f49ae368fdd738a Mon Sep 17 00:00:00 2001 From: Shane Smiskol Date: Wed, 14 Feb 2024 23:51:42 -0600 Subject: [PATCH 13/67] Toyota: check ACC_CONTROL for relay malfunction (#1870) * check acc relay malfunction * do what they do --- board/safety/safety_toyota.h | 6 +++++- tests/safety/test_toyota.py | 5 +++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/board/safety/safety_toyota.h b/board/safety/safety_toyota.h index 0f7e671c4..33b71d9c8 100644 --- a/board/safety/safety_toyota.h +++ b/board/safety/safety_toyota.h @@ -209,7 +209,11 @@ static void toyota_rx_hook(const CANPacket_t *to_push) { gas_interceptor_prev = gas_interceptor; } - generic_rx_checks((addr == 0x2E4)); + bool stock_ecu_detected = addr == 0x2E4; // STEERING_LKA + if (!toyota_stock_longitudinal && (addr == 0x343)) { + stock_ecu_detected = true; // ACC_CONTROL + } + generic_rx_checks(stock_ecu_detected); } } diff --git a/tests/safety/test_toyota.py b/tests/safety/test_toyota.py index 8ef07eea1..d3574442f 100755 --- a/tests/safety/test_toyota.py +++ b/tests/safety/test_toyota.py @@ -20,7 +20,7 @@ class TestToyotaSafetyBase(common.PandaCarSafetyTest, common.LongitudinalAccelSa TX_MSGS = TOYOTA_COMMON_TX_MSGS STANDSTILL_THRESHOLD = 0 # kph - RELAY_MALFUNCTION_ADDRS = {0: (0x2E4,)} + RELAY_MALFUNCTION_ADDRS = {0: (0x2E4, 0x343)} FWD_BLACKLISTED_ADDRS = {2: [0x2E4, 0x412, 0x191, 0x343]} FWD_BUS_LOOKUP = {0: 2, 2: 0} EPS_SCALE = 73 @@ -311,7 +311,8 @@ class TestToyotaAltBrakeSafetyGasInterceptor(TestToyotaSafetyGasInterceptorBase, class TestToyotaStockLongitudinalBase(TestToyotaSafetyBase): - # Base fwd addresses minus ACC_CONTROL (0x343) + # Base addresses minus ACC_CONTROL (0x343) + RELAY_MALFUNCTION_ADDRS = {0: (0x2E4,)} FWD_BLACKLISTED_ADDRS = {2: [0x2E4, 0x412, 0x191]} def test_accel_actuation_limits(self, stock_longitudinal=True): From a037eebf389f2903ddb766c0a909e3689b031f65 Mon Sep 17 00:00:00 2001 From: Shane Smiskol Date: Thu, 15 Feb 2024 00:16:51 -0600 Subject: [PATCH 14/67] Toyota: longitudinal msgs behind safety param (#1871) * long is fully behind safety param * fix * spacing --- board/safety/safety_toyota.h | 32 ++++++++++++++++++++++++-------- tests/safety/test_toyota.py | 22 +++++++++++++--------- 2 files changed, 37 insertions(+), 17 deletions(-) diff --git a/board/safety/safety_toyota.h b/board/safety/safety_toyota.h index 33b71d9c8..9368f4ed6 100644 --- a/board/safety/safety_toyota.h +++ b/board/safety/safety_toyota.h @@ -43,17 +43,26 @@ const LongitudinalLimits TOYOTA_LONG_LIMITS = { const int TOYOTA_GAS_INTERCEPTOR_THRSLD = 805; #define TOYOTA_GET_INTERCEPTOR(msg) (((GET_BYTE((msg), 0) << 8) + GET_BYTE((msg), 1) + (GET_BYTE((msg), 2) << 8) + GET_BYTE((msg), 3)) / 2U) // avg between 2 tracks -#define TOYOTA_COMMON_TX_MSGS \ +// Stock longitudinal +#define TOYOTA_COMMON_TX_MSGS \ + {0x2E4, 0, 5}, {0x191, 0, 8}, {0x412, 0, 8}, {0x343, 0, 8}, {0x1D2, 0, 8}, /* LKAS + LTA + ACC & PCM cancel cmds */ \ + +#define TOYOTA_COMMON_LONG_TX_MSGS \ + TOYOTA_COMMON_TX_MSGS \ {0x283, 0, 7}, {0x2E6, 0, 8}, {0x2E7, 0, 8}, {0x33E, 0, 7}, {0x344, 0, 8}, {0x365, 0, 7}, {0x366, 0, 7}, {0x4CB, 0, 8}, /* DSU bus 0 */ \ {0x128, 1, 6}, {0x141, 1, 4}, {0x160, 1, 8}, {0x161, 1, 7}, {0x470, 1, 4}, /* DSU bus 1 */ \ - {0x2E4, 0, 5}, {0x191, 0, 8}, {0x411, 0, 8}, {0x412, 0, 8}, {0x343, 0, 8}, {0x1D2, 0, 8}, /* LKAS + ACC */ \ + {0x411, 0, 8}, /* PCS_HUD */ \ const CanMsg TOYOTA_TX_MSGS[] = { TOYOTA_COMMON_TX_MSGS }; +const CanMsg TOYOTA_LONG_TX_MSGS[] = { + TOYOTA_COMMON_LONG_TX_MSGS +}; + const CanMsg TOYOTA_INTERCEPTOR_TX_MSGS[] = { - TOYOTA_COMMON_TX_MSGS + TOYOTA_COMMON_LONG_TX_MSGS {0x200, 0, 6}, // gas interceptor }; @@ -347,12 +356,19 @@ static safety_config toyota_init(uint16_t param) { } safety_config ret; - if (toyota_lta) { - ret = enable_gas_interceptor ? BUILD_SAFETY_CFG(toyota_lta_interceptor_rx_checks, TOYOTA_INTERCEPTOR_TX_MSGS) : \ - BUILD_SAFETY_CFG(toyota_lta_rx_checks, TOYOTA_TX_MSGS); + if (toyota_stock_longitudinal) { + SET_TX_MSGS(TOYOTA_TX_MSGS, ret); } else { - ret = enable_gas_interceptor ? BUILD_SAFETY_CFG(toyota_lka_interceptor_rx_checks, TOYOTA_INTERCEPTOR_TX_MSGS) : \ - BUILD_SAFETY_CFG(toyota_lka_rx_checks, TOYOTA_TX_MSGS); + enable_gas_interceptor ? SET_TX_MSGS(TOYOTA_INTERCEPTOR_TX_MSGS, ret) : \ + SET_TX_MSGS(TOYOTA_LONG_TX_MSGS, ret); + } + + if (enable_gas_interceptor) { + toyota_lta ? SET_RX_CHECKS(toyota_lta_interceptor_rx_checks, ret) : \ + SET_RX_CHECKS(toyota_lka_interceptor_rx_checks, ret); + } else { + toyota_lta ? SET_RX_CHECKS(toyota_lta_rx_checks, ret) : \ + SET_RX_CHECKS(toyota_lka_rx_checks, ret); } return ret; } diff --git a/tests/safety/test_toyota.py b/tests/safety/test_toyota.py index d3574442f..c9fefdea6 100755 --- a/tests/safety/test_toyota.py +++ b/tests/safety/test_toyota.py @@ -9,16 +9,16 @@ from panda.tests.libpanda import libpanda_py import panda.tests.safety.common as common from panda.tests.safety.common import CANPackerPanda - -TOYOTA_COMMON_TX_MSGS = [[0x283, 0], [0x2E6, 0], [0x2E7, 0], [0x33E, 0], [0x344, 0], [0x365, 0], [0x366, 0], [0x4CB, 0], # DSU bus 0 - [0x128, 1], [0x141, 1], [0x160, 1], [0x161, 1], [0x470, 1], # DSU bus 1 - [0x2E4, 0], [0x191, 0], [0x411, 0], [0x412, 0], [0x343, 0], [0x1D2, 0], # LKAS + ACC - [0x750, 0]] # blindspot monitor +TOYOTA_COMMON_TX_MSGS = [[0x2E4, 0], [0x191, 0], [0x412, 0], [0x343, 0], [0x1D2, 0]] # LKAS + LTA + ACC & PCM cancel cmds +TOYOTA_COMMON_LONG_TX_MSGS = [[0x283, 0], [0x2E6, 0], [0x2E7, 0], [0x33E, 0], [0x344, 0], [0x365, 0], [0x366, 0], [0x4CB, 0], # DSU bus 0 + [0x128, 1], [0x141, 1], [0x160, 1], [0x161, 1], [0x470, 1], # DSU bus 1 + [0x411, 0]] # PCS_HUD +GAS_INTERCEPTOR_TX_MSGS = [[0x200, 0]] class TestToyotaSafetyBase(common.PandaCarSafetyTest, common.LongitudinalAccelSafetyTest): - TX_MSGS = TOYOTA_COMMON_TX_MSGS + TX_MSGS = TOYOTA_COMMON_TX_MSGS + TOYOTA_COMMON_LONG_TX_MSGS STANDSTILL_THRESHOLD = 0 # kph RELAY_MALFUNCTION_ADDRS = {0: (0x2E4, 0x343)} FWD_BLACKLISTED_ADDRS = {2: [0x2E4, 0x412, 0x191, 0x343]} @@ -80,7 +80,7 @@ class TestToyotaSafetyBase(common.PandaCarSafetyTest, common.LongitudinalAccelSa values = {"CRUISE_ACTIVE": enable} return self.packer.make_can_msg_panda("PCM_CRUISE", 0, values) - def test_block_aeb(self): + def test_block_aeb(self, stock_longitudinal: bool = False): for controls_allowed in (True, False): for bad in (True, False): for _ in range(10): @@ -89,7 +89,7 @@ class TestToyotaSafetyBase(common.PandaCarSafetyTest, common.LongitudinalAccelSa if not bad: dat = [0]*6 + dat[-1:] msg = libpanda_py.make_CANPacket(0x283, 0, bytes(dat)) - self.assertEqual(not bad, self._tx(msg)) + self.assertEqual(not bad and not stock_longitudinal, self._tx(msg)) # Only allow LTA msgs with no actuation def test_lta_steer_cmd(self): @@ -121,7 +121,7 @@ class TestToyotaSafetyBase(common.PandaCarSafetyTest, common.LongitudinalAccelSa class TestToyotaSafetyGasInterceptorBase(common.GasInterceptorSafetyTest, TestToyotaSafetyBase): - TX_MSGS = TOYOTA_COMMON_TX_MSGS + [[0x200, 0]] + TX_MSGS = TOYOTA_COMMON_TX_MSGS + TOYOTA_COMMON_LONG_TX_MSGS + GAS_INTERCEPTOR_TX_MSGS INTERCEPTOR_THRESHOLD = 805 def setUp(self): @@ -311,10 +311,14 @@ class TestToyotaAltBrakeSafetyGasInterceptor(TestToyotaSafetyGasInterceptorBase, class TestToyotaStockLongitudinalBase(TestToyotaSafetyBase): + TX_MSGS = TOYOTA_COMMON_TX_MSGS # Base addresses minus ACC_CONTROL (0x343) RELAY_MALFUNCTION_ADDRS = {0: (0x2E4,)} FWD_BLACKLISTED_ADDRS = {2: [0x2E4, 0x412, 0x191]} + def test_block_aeb(self, stock_longitudinal: bool = True): + super().test_block_aeb(stock_longitudinal=stock_longitudinal) + def test_accel_actuation_limits(self, stock_longitudinal=True): super().test_accel_actuation_limits(stock_longitudinal=stock_longitudinal) From 0a1ec8580ecbde1f73b424f63b9fb8fbe29ddf09 Mon Sep 17 00:00:00 2001 From: Shane Smiskol Date: Thu, 15 Feb 2024 01:22:06 -0600 Subject: [PATCH 15/67] Toyota: radar disable safety (#1611) * toyota: add safety for tester present * block ACC_HUD * check stock ECU * add test * and now pass test * check ACC_CONTROL for relay malfunction * not needed * split tx msgs, test_panda_safety_tx_cases was really helpful! * now don't need this * 0x343 is expected to be on bus 0 if stock long * better as cases * swap * always block pre_collision if stock (used for dsu removal) * do tx msgs * fix comment --- board/safety/safety_toyota.h | 10 ++++++++++ tests/safety/test_toyota.py | 13 ++++++++++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/board/safety/safety_toyota.h b/board/safety/safety_toyota.h index 9368f4ed6..4256f1258 100644 --- a/board/safety/safety_toyota.h +++ b/board/safety/safety_toyota.h @@ -52,6 +52,7 @@ const int TOYOTA_GAS_INTERCEPTOR_THRSLD = 805; {0x283, 0, 7}, {0x2E6, 0, 8}, {0x2E7, 0, 8}, {0x33E, 0, 7}, {0x344, 0, 8}, {0x365, 0, 7}, {0x366, 0, 7}, {0x4CB, 0, 8}, /* DSU bus 0 */ \ {0x128, 1, 6}, {0x141, 1, 4}, {0x160, 1, 8}, {0x161, 1, 7}, {0x470, 1, 4}, /* DSU bus 1 */ \ {0x411, 0, 8}, /* PCS_HUD */ \ + {0x750, 0, 8}, /* radar diagnostic address */ \ const CanMsg TOYOTA_TX_MSGS[] = { TOYOTA_COMMON_TX_MSGS @@ -340,6 +341,15 @@ static bool toyota_tx_hook(const CANPacket_t *to_send) { } } + // UDS: Only tester present ("\x0F\x02\x3E\x00\x00\x00\x00\x00") allowed on diagnostics address + if (addr == 0x750) { + // this address is sub-addressed. only allow tester present to radar (0xF) + bool invalid_uds_msg = (GET_BYTES(to_send, 0, 4) != 0x003E020FU) || (GET_BYTES(to_send, 4, 4) != 0x0U); + if (invalid_uds_msg) { + tx = 0; + } + } + return tx; } diff --git a/tests/safety/test_toyota.py b/tests/safety/test_toyota.py index c9fefdea6..0743c67e8 100755 --- a/tests/safety/test_toyota.py +++ b/tests/safety/test_toyota.py @@ -12,7 +12,8 @@ from panda.tests.safety.common import CANPackerPanda TOYOTA_COMMON_TX_MSGS = [[0x2E4, 0], [0x191, 0], [0x412, 0], [0x343, 0], [0x1D2, 0]] # LKAS + LTA + ACC & PCM cancel cmds TOYOTA_COMMON_LONG_TX_MSGS = [[0x283, 0], [0x2E6, 0], [0x2E7, 0], [0x33E, 0], [0x344, 0], [0x365, 0], [0x366, 0], [0x4CB, 0], # DSU bus 0 [0x128, 1], [0x141, 1], [0x160, 1], [0x161, 1], [0x470, 1], # DSU bus 1 - [0x411, 0]] # PCS_HUD + [0x411, 0], # PCS_HUD + [0x750, 0]] # radar diagnostic address GAS_INTERCEPTOR_TX_MSGS = [[0x200, 0]] @@ -80,6 +81,13 @@ class TestToyotaSafetyBase(common.PandaCarSafetyTest, common.LongitudinalAccelSa values = {"CRUISE_ACTIVE": enable} return self.packer.make_can_msg_panda("PCM_CRUISE", 0, values) + def test_diagnostics(self, stock_longitudinal: bool = False): + for should_tx, msg in ((False, b"\x6D\x02\x3E\x00\x00\x00\x00\x00"), # fwdCamera tester present + (False, b"\x0F\x03\xAA\xAA\x00\x00\x00\x00"), # non-tester present + (True, b"\x0F\x02\x3E\x00\x00\x00\x00\x00")): + tester_present = libpanda_py.make_CANPacket(0x750, 0, msg) + self.assertEqual(should_tx and not stock_longitudinal, self._tx(tester_present)) + def test_block_aeb(self, stock_longitudinal: bool = False): for controls_allowed in (True, False): for bad in (True, False): @@ -316,6 +324,9 @@ class TestToyotaStockLongitudinalBase(TestToyotaSafetyBase): RELAY_MALFUNCTION_ADDRS = {0: (0x2E4,)} FWD_BLACKLISTED_ADDRS = {2: [0x2E4, 0x412, 0x191]} + def test_diagnostics(self, stock_longitudinal: bool = True): + super().test_diagnostics(stock_longitudinal=stock_longitudinal) + def test_block_aeb(self, stock_longitudinal: bool = True): super().test_block_aeb(stock_longitudinal=stock_longitudinal) From 3cd0023bc16eee7d4c0b4f2aef3da1676a6bff71 Mon Sep 17 00:00:00 2001 From: Robbe Derks Date: Thu, 15 Feb 2024 13:49:06 -0800 Subject: [PATCH 16/67] cuatro power readout (#1869) * refactor voltage / current reading * fix bug and add readout to cuatro * fix misra? * just suppress then --------- Co-authored-by: Comma Device --- board/boards/black.h | 3 ++- board/boards/board_declarations.h | 6 ++++-- board/boards/cuatro.h | 15 ++++++++++++++- board/boards/dos.h | 3 ++- board/boards/grey.h | 3 ++- board/boards/pedal.h | 3 ++- board/boards/red.h | 7 ++++++- board/boards/tres.h | 3 ++- board/boards/uno.h | 5 +++-- board/boards/unused_funcs.h | 4 ++++ board/boards/white.h | 15 ++++++++++----- board/config.h | 2 -- board/main_comms.h | 4 ++-- board/pedal/main.c | 3 +++ board/stm32fx/lladc.h | 9 --------- board/stm32h7/clock.h | 3 ++- board/stm32h7/lladc.h | 7 +++---- 17 files changed, 61 insertions(+), 34 deletions(-) diff --git a/board/boards/black.h b/board/boards/black.h index d72ab39aa..ea636334d 100644 --- a/board/boards/black.h +++ b/board/boards/black.h @@ -180,7 +180,8 @@ const board board_black = { .set_led = black_set_led, .set_can_mode = black_set_can_mode, .check_ignition = black_check_ignition, - .read_current = unused_read_current, + .read_voltage_mV = white_read_voltage_mV, + .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, diff --git a/board/boards/board_declarations.h b/board/boards/board_declarations.h index 06382ceb7..600dc2884 100644 --- a/board/boards/board_declarations.h +++ b/board/boards/board_declarations.h @@ -12,7 +12,8 @@ typedef void (*board_enable_can_transceivers)(bool enabled); typedef void (*board_set_led)(uint8_t color, bool enabled); typedef void (*board_set_can_mode)(uint8_t mode); typedef bool (*board_check_ignition)(void); -typedef uint32_t (*board_read_current)(void); +typedef uint32_t (*board_read_voltage_mV)(void); +typedef uint32_t (*board_read_current_mA)(void); typedef void (*board_set_ir_power)(uint8_t percentage); typedef void (*board_set_fan_enabled)(bool enabled); typedef void (*board_set_siren)(bool enabled); @@ -36,7 +37,8 @@ struct board { board_set_led set_led; board_set_can_mode set_can_mode; board_check_ignition check_ignition; - board_read_current read_current; + board_read_voltage_mV read_voltage_mV; + board_read_current_mA read_current_mA; board_set_ir_power set_ir_power; board_set_fan_enabled set_fan_enabled; board_set_siren set_siren; diff --git a/board/boards/cuatro.h b/board/boards/cuatro.h index ed120bb05..b8cd3d035 100644 --- a/board/boards/cuatro.h +++ b/board/boards/cuatro.h @@ -49,9 +49,21 @@ void cuatro_enable_can_transceivers(bool enabled) { } } +uint32_t cuatro_read_voltage_mV(void) { + return adc_get_mV(8) * 11U; +} + +uint32_t cuatro_read_current_mA(void) { + return adc_get_mV(3) * 2U; +} + void cuatro_init(void) { red_chiplet_init(); + // Power readout + set_gpio_mode(GPIOC, 5, MODE_ANALOG); + set_gpio_mode(GPIOA, 6, MODE_ANALOG); + // CAN transceiver enables set_gpio_pullup(GPIOB, 7, PULL_NONE); set_gpio_mode(GPIOB, 7, MODE_OUTPUT); @@ -108,7 +120,8 @@ const board board_cuatro = { .set_led = cuatro_set_led, .set_can_mode = red_chiplet_set_can_mode, .check_ignition = red_check_ignition, - .read_current = unused_read_current, + .read_voltage_mV = cuatro_read_voltage_mV, + .read_current_mA = cuatro_read_current_mA, .set_fan_enabled = tres_set_fan_enabled, .set_ir_power = tres_set_ir_power, .set_siren = unused_set_siren, diff --git a/board/boards/dos.h b/board/boards/dos.h index e93c01591..d0a9bbaf4 100644 --- a/board/boards/dos.h +++ b/board/boards/dos.h @@ -212,7 +212,8 @@ const board board_dos = { .set_led = dos_set_led, .set_can_mode = dos_set_can_mode, .check_ignition = dos_check_ignition, - .read_current = unused_read_current, + .read_voltage_mV = white_read_voltage_mV, + .read_current_mA = unused_read_current, .set_fan_enabled = dos_set_fan_enabled, .set_ir_power = dos_set_ir_power, .set_siren = dos_set_siren, diff --git a/board/boards/grey.h b/board/boards/grey.h index e8f90e263..8b3bd8aed 100644 --- a/board/boards/grey.h +++ b/board/boards/grey.h @@ -22,7 +22,8 @@ const board board_grey = { .set_led = white_set_led, .set_can_mode = white_set_can_mode, .check_ignition = white_check_ignition, - .read_current = white_read_current, + .read_voltage_mV = white_read_voltage_mV, + .read_current_mA = white_read_current_mA, .set_fan_enabled = unused_set_fan_enabled, .set_ir_power = unused_set_ir_power, .set_siren = unused_set_siren, diff --git a/board/boards/pedal.h b/board/boards/pedal.h index 2b653e9ed..c4adaf866 100644 --- a/board/boards/pedal.h +++ b/board/boards/pedal.h @@ -84,7 +84,8 @@ const board board_pedal = { .set_led = pedal_set_led, .set_can_mode = pedal_set_can_mode, .check_ignition = pedal_check_ignition, - .read_current = unused_read_current, + .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, diff --git a/board/boards/red.h b/board/boards/red.h index 58410894b..aa8c91be7 100644 --- a/board/boards/red.h +++ b/board/boards/red.h @@ -96,6 +96,10 @@ bool red_check_ignition(void) { return harness_check_ignition(); } +uint32_t red_read_voltage_mV(void){ + return adc_get_mV(2) * 11U; // TODO: is this correct? +} + void red_init(void) { common_init_gpio(); @@ -188,7 +192,8 @@ const board board_red = { .set_led = red_set_led, .set_can_mode = red_set_can_mode, .check_ignition = red_check_ignition, - .read_current = unused_read_current, + .read_voltage_mV = red_read_voltage_mV, + .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, diff --git a/board/boards/tres.h b/board/boards/tres.h index 4e8564b20..959c93b5d 100644 --- a/board/boards/tres.h +++ b/board/boards/tres.h @@ -87,7 +87,8 @@ const board board_tres = { .set_led = red_set_led, .set_can_mode = red_chiplet_set_can_mode, .check_ignition = red_check_ignition, - .read_current = unused_read_current, + .read_voltage_mV = red_read_voltage_mV, + .read_current_mA = unused_read_current, .set_fan_enabled = tres_set_fan_enabled, .set_ir_power = tres_set_ir_power, .set_siren = fake_siren_set, diff --git a/board/boards/uno.h b/board/boards/uno.h index 5f8af593d..f4e2016bd 100644 --- a/board/boards/uno.h +++ b/board/boards/uno.h @@ -167,7 +167,7 @@ void uno_init(void) { } // Switch to phone usb mode if harness connection is powered by less than 7V - if((adc_get_mV(ADCCHAN_VIN) * VIN_READOUT_DIVIDER) < 7000U){ + if(white_read_voltage_mV() < 7000U){ uno_set_usb_switch(true); } else { uno_set_usb_switch(false); @@ -215,7 +215,8 @@ const board board_uno = { .set_led = uno_set_led, .set_can_mode = uno_set_can_mode, .check_ignition = uno_check_ignition, - .read_current = unused_read_current, + .read_voltage_mV = white_read_voltage_mV, + .read_current_mA = unused_read_current, .set_fan_enabled = uno_set_fan_enabled, .set_ir_power = uno_set_ir_power, .set_siren = unused_set_siren, diff --git a/board/boards/unused_funcs.h b/board/boards/unused_funcs.h index 7bfde0139..689b5b7c4 100644 --- a/board/boards/unused_funcs.h +++ b/board/boards/unused_funcs.h @@ -13,6 +13,10 @@ 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/boards/white.h b/board/boards/white.h index 5048c0779..0de29a39b 100644 --- a/board/boards/white.h +++ b/board/boards/white.h @@ -124,8 +124,13 @@ void white_set_can_mode(uint8_t mode){ } } -uint32_t white_read_current(void){ - return adc_get_raw(ADCCHAN_CURRENT); +uint32_t white_read_voltage_mV(void){ + return adc_get_mV(12) * 11U; +} + +uint32_t white_read_current_mA(void){ + // This isn't in mA, but we're keeping it for backwards compatibility + return adc_get_raw(13); } bool white_check_ignition(void){ @@ -197,10 +202,9 @@ void white_grey_init(void) { white_set_can_mode(CAN_MODE_NORMAL); // Init usb power mode - uint32_t voltage = adc_get_mV(ADCCHAN_VIN) * VIN_READOUT_DIVIDER; // Init in CDP mode only if panda is powered by 12V. // Otherwise a PC would not be able to flash a standalone panda - if (voltage > 8000U) { // 8V threshold + if (white_read_voltage_mV() > 8000U) { // 8V threshold white_set_usb_power_mode(USB_POWER_CDP); } else { white_set_usb_power_mode(USB_POWER_CLIENT); @@ -239,7 +243,8 @@ const board board_white = { .set_led = white_set_led, .set_can_mode = white_set_can_mode, .check_ignition = white_check_ignition, - .read_current = white_read_current, + .read_voltage_mV = white_read_voltage_mV, + .read_current_mA = white_read_current_mA, .set_fan_enabled = unused_set_fan_enabled, .set_ir_power = unused_set_ir_power, .set_siren = unused_set_siren, diff --git a/board/config.h b/board/config.h index 507d19e7d..fc87bc1c3 100644 --- a/board/config.h +++ b/board/config.h @@ -16,8 +16,6 @@ #define MAX_CAN_MSGS_PER_USB_BULK_TRANSFER 51U #define MAX_CAN_MSGS_PER_SPI_BULK_TRANSFER 170U -#define VIN_READOUT_DIVIDER 11U - // USB definitions #define USB_VID 0xBBAAU diff --git a/board/main_comms.h b/board/main_comms.h index f535af662..096f7b1a8 100644 --- a/board/main_comms.h +++ b/board/main_comms.h @@ -9,8 +9,8 @@ int get_health_pkt(void *dat) { struct health_t * health = (struct health_t*)dat; health->uptime_pkt = uptime_cnt; - health->voltage_pkt = adc_get_mV(ADCCHAN_VIN) * VIN_READOUT_DIVIDER; - health->current_pkt = current_board->read_current(); + health->voltage_pkt = current_board->read_voltage_mV(); + health->current_pkt = current_board->read_current_mA(); // Use the GPIO pin to determine ignition or use a CAN based logic health->ignition_line_pkt = (uint8_t)(current_board->check_ignition()); diff --git a/board/pedal/main.c b/board/pedal/main.c index 704ee5436..b738a9598 100644 --- a/board/pedal/main.c +++ b/board/pedal/main.c @@ -242,6 +242,9 @@ void TIM3_IRQ_Handler(void) { // ***************************** main code ***************************** +#define ADCCHAN_ACCEL0 10 +#define ADCCHAN_ACCEL1 11 + void pedal(void) { // read/write pdl0 = adc_get_raw(ADCCHAN_ACCEL0); diff --git a/board/stm32fx/lladc.h b/board/stm32fx/lladc.h index 31c17f4b2..c2df10f1b 100644 --- a/board/stm32fx/lladc.h +++ b/board/stm32fx/lladc.h @@ -1,12 +1,3 @@ -// ACCEL1 = ADC10 -// ACCEL2 = ADC11 -// VOLT_S = ADC12 -// CURR_S = ADC13 - -#define ADCCHAN_ACCEL0 10 -#define ADCCHAN_ACCEL1 11 -#define ADCCHAN_VIN 12 -#define ADCCHAN_CURRENT 13 void register_set(volatile uint32_t *addr, uint32_t val, uint32_t mask); diff --git a/board/stm32h7/clock.h b/board/stm32h7/clock.h index fc221c552..7d65d080e 100644 --- a/board/stm32h7/clock.h +++ b/board/stm32h7/clock.h @@ -21,11 +21,12 @@ void clock_init(void) { // Set power mode to direct SMPS power supply(depends on the board layout) #ifndef STM32H723 register_set(&(PWR->CR3), PWR_CR3_SMPSEN, 0xFU); // powered only by SMPS +#endif // Set VOS level (VOS3 to 170Mhz, VOS2 to 300Mhz, VOS1 to 400Mhz, VOS0 to 550Mhz) register_set(&(PWR->D3CR), PWR_D3CR_VOS_1 | PWR_D3CR_VOS_0, 0xC000U); //VOS1, needed for 80Mhz CAN FD while ((PWR->CSR1 & PWR_CSR1_ACTVOSRDY) == 0); while ((PWR->CSR1 & PWR_CSR1_ACTVOS) != (PWR->D3CR & PWR_D3CR_VOS)); // check that VOS level was actually set -#endif + // Configure Flash ACR register LATENCY and WRHIGHFREQ (VOS0 range!) register_set(&(FLASH->ACR), FLASH_ACR_LATENCY_2WS | 0x20U, 0x3FU); // VOS2, AXI 100MHz-150MHz // enable external oscillator HSE diff --git a/board/stm32h7/lladc.h b/board/stm32h7/lladc.h index 0a52b78d3..1f5a082bd 100644 --- a/board/stm32h7/lladc.h +++ b/board/stm32h7/lladc.h @@ -1,6 +1,3 @@ -// 5VOUT_S = ADC12_INP5 -// VOLT_S = ADC1_INP2 -#define ADCCHAN_VIN 2 void adc_init(void) { ADC1->CR &= ~(ADC_CR_DEEPPWD); //Reset deep-power-down mode @@ -18,17 +15,19 @@ void adc_init(void) { } uint16_t adc_get_raw(uint8_t channel) { + uint16_t res = 0U; ADC1->SQR1 &= ~(ADC_SQR1_L); ADC1->SQR1 = ((uint32_t) channel << 6U); ADC1->SMPR1 = (0x2U << (channel * 3U)); + // cppcheck-suppress misra-c2012-12.2; don't know how to fix this. if statement to check channel range does not work ADC1->PCSEL_RES0 = (0x1U << channel); ADC1->CFGR2 = (127U << ADC_CFGR2_OVSR_Pos) | (0x7U << ADC_CFGR2_OVSS_Pos) | ADC_CFGR2_ROVSE; ADC1->CR |= ADC_CR_ADSTART; while (!(ADC1->ISR & ADC_ISR_EOC)); - uint16_t res = ADC1->DR; + res = ADC1->DR; while (!(ADC1->ISR & ADC_ISR_EOS)); ADC1->ISR |= ADC_ISR_EOS; From 39671c3dd663b9041564ec577c01ebd2009786df Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Thu, 15 Feb 2024 13:52:24 -0800 Subject: [PATCH 17/67] remove 12.2 suppression added in 3cd0023 --- board/stm32h7/lladc.h | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/board/stm32h7/lladc.h b/board/stm32h7/lladc.h index 1f5a082bd..01342a4d0 100644 --- a/board/stm32h7/lladc.h +++ b/board/stm32h7/lladc.h @@ -20,8 +20,7 @@ uint16_t adc_get_raw(uint8_t channel) { ADC1->SQR1 = ((uint32_t) channel << 6U); ADC1->SMPR1 = (0x2U << (channel * 3U)); - // cppcheck-suppress misra-c2012-12.2; don't know how to fix this. if statement to check channel range does not work - ADC1->PCSEL_RES0 = (0x1U << channel); + ADC1->PCSEL_RES0 = (0x1UL << channel); ADC1->CFGR2 = (127U << ADC_CFGR2_OVSR_Pos) | (0x7U << ADC_CFGR2_OVSS_Pos) | ADC_CFGR2_ROVSE; ADC1->CR |= ADC_CR_ADSTART; From c076a9f2f679ee796ce5524526001782c7a550c3 Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Fri, 16 Feb 2024 22:58:01 -0800 Subject: [PATCH 18/67] 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 8f1c5f019..968ee3ecf 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 bf680d33a..cbb20d192 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 330a94741..10e66cf40 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 1a79e3880..357daba95 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 81f1ef84a..93fd47b07 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 c4adaf866..000000000 --- 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 db3d62170..b3631d807 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 fc87bc1c3..0adcc3e09 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 ed74b9328..dec7ba812 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 d0ee32cb2..89cf01e07 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 eec0ec5d7..52906f9df 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 94053f292..000000000 --- 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 9e004d6bd..000000000 --- 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 bfa3c2c19..000000000 --- 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 b9edf25f1..000000000 --- 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 b738a9598..000000000 --- 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 33e422735..000000000 --- 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 d7fe0aff5..000000000 --- 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 76593a529..808f77382 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 3b40f4ee5..41d7427d7 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 a6c5936f0..72523cf1b 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 6cd2f8ca2..000000000 --- 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 b6eea1dad..20c980864 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 5bdb8a056..79ac3c6e4 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 b47011921..8b59da28f 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 08a18c976..acf6ea483 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 8078da3e6..fede52424 100644 --- a/python/constants.py +++ b/python/constants.py @@ -24,7 +24,11 @@ class McuConfig(NamedTuple): # 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 @@ Fx = ( 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 @@ H7Config = McuConfig( @enum.unique class McuType(enum.Enum): - F2 = F2Config F4 = F4Config H7 = H7Config diff --git a/python/spi.py b/python/spi.py index 699431bf0..48dc84d49 100644 --- a/python/spi.py +++ b/python/spi.py @@ -13,7 +13,6 @@ from typing import Callable, List, Optional 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 @@ XFER_SIZE = 0x40*31 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 @@ class PandaSpiHandle(BaseHandle): # 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 f91da6413..000000000 --- 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 cfc53bac4..0798058e6 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 7465c0a07..000000000 --- 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 0d0676c45..000000000 --- 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 19/67] 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 368bcf39e..000000000 --- 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 dfef07939..000000000 --- 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 7cef9a648..000000000 --- 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 cd4b83c57..000000000 --- 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 7554efc4c..000000000 --- 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 bdc23bc8c..000000000 --- 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 20/67] HITL tests: no xdist (#1874) --- Jenkinsfile | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index cbb20d192..25b8490a0 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 21/67] 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 0798058e6..35a98db21 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 22/67] (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 d0a9bbaf4..428bbf2a5 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 689b5b7c4..7bfde0139 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 e2977e938..aee665e7e 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 407062bbb..a4377a675 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 9cb46d4b2..79c87cccc 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 e37dfcd6b..01d8c2ac0 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 52906f9df..d6c2c4021 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 db22ff63f..02768c93d 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 1e4e9015d..ffe7e74da 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 ae150a838..074463d31 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 2c91f868a..d79064f1f 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 35a98db21..15bd6aca8 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 23/67] 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 1e1187128..fa0e1532d 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 0424b9d09..2f11863b4 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 fd944761e..d1e4dd216 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 968a1a446..3881db745 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 d88762c0d..5a324bff2 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 be026a984..0744a6e20 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 201c6fe5e..c445bc435 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 37e389afb..1549d595b 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 4256f1258..f6bfc0809 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 10adc679d..d880a69a6 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 b9a2eedd7..1922cf467 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 eb4ece474..39dcabf9b 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 24/67] 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 15bd6aca8..9fdbea1df 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 25/67] 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 db77617e7..bc9adde7c 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 a4377a675..2dbc381bd 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 79c87cccc..d4c72be1d 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 dec7ba812..1872dd527 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 096f7b1a8..c0d5c516f 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 50669e3bf..1e9524409 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 d1e4dd216..82a5d9cd3 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 3881db745..78bbb7f0b 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 0744a6e20..fb6ccf55a 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 2c89bfb7a..54ea0f024 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 231772738..c2406260f 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 1549d595b..1047814ac 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 f6bfc0809..50c00b38a 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 39dcabf9b..64b55f203 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 cdce0c448..4bb6d3d04 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 26/67] 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 000000000..5ba3e35c5 --- /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 27/67] 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 5ba3e35c5..bb294046e 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 @@ class XcpClient(): 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 28/67] 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 5788e16b2..1f978433e 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 29/67] 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 1922cf467..de147cb58 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 68def8bf6..f2bc31786 100755 --- a/tests/safety/test_volkswagen_pq.py +++ b/tests/safety/test_volkswagen_pq.py @@ -69,8 +69,8 @@ class TestVolkswagenPqSafety(common.PandaCarSafetyTest, common.DriverTorqueSteer 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 @@ class TestVolkswagenPqLongSafety(TestVolkswagenPqSafety, common.LongitudinalAcce 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 30/67] 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 2f11863b4..d6ee20803 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 14e656b88..1be3a273c 100755 --- a/tests/safety/test_ford.py +++ b/tests/safety/test_ford.py @@ -215,11 +215,11 @@ class TestFordSafetyBase(common.PandaCarSafetyTest): 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 31/67] 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 bc4c2a532..9e2e0df7f 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 32/67] 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 77a6e3c7c..a95ddfa92 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 @@ class PandaJungle(Panda): 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 ad4a1c426..4fc9d30be 100755 --- a/board/jungle/scripts/get_version.py +++ b/board/jungle/scripts/get_version.py @@ -4,6 +4,6 @@ from panda import PandaJungle 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 bc9b68ae8..1e7bad54e 100755 --- a/examples/can_bit_transition.py +++ b/examples/can_bit_transition.py @@ -66,7 +66,7 @@ class Info(): 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 bc582f016..05977afb0 100755 --- a/examples/can_unique.py +++ b/examples/can_unique.py @@ -52,7 +52,7 @@ class Info(): 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 @@ class Info(): 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 @@ class Info(): 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 4f4e3fa66..fe70bf96a 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 @@ if __name__ == "__main__": 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 72bce22be..ee89db28e 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 acf6ea483..6e614775d 100644 --- a/python/__init__.py +++ b/python/__init__.py @@ -9,7 +9,6 @@ import binascii 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 @@ class Panda: 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 @@ class Panda: 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 @@ class Panda: 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 fede52424..8b0959308 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 @@ USBPACKET_MAX_SIZE = 0x40 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 01ff037f8..9beba45e5 100644 --- a/python/dfu.py +++ b/python/dfu.py @@ -2,7 +2,6 @@ import os import usb1 import struct import binascii -from typing import List, Optional from .base import BaseSTBootloaderHandle from .spi import STBootloaderSPIHandle, PandaSpiException @@ -11,9 +10,9 @@ from .constants import FW_PATH, McuType 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 @@ class PandaDFU: 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 @@ class PandaDFU: 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 @@ class PandaDFU: 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 @@ class PandaDFU: 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 @@ class PandaDFU: 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 3334deb8e..d0bef7d94 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 9ac58862b..c2e965b76 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 48dc84d49..d34a61d56 100644 --- a/python/spi.py +++ b/python/spi.py @@ -9,7 +9,7 @@ import logging 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 @@ class STBootloaderSPIHandle(BaseSTBootloaderHandle): 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 @@ class STBootloaderSPIHandle(BaseSTBootloaderHandle): 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 aaa0697f9..12b4fcdc2 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 @@ class CanClient(): 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 @@ class CanClient(): 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 @@ class IsoTpMessage(): 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 @@ class UdsClient(): 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 @@ class UdsClient(): 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 @@ class UdsClient(): 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 @@ class UdsClient(): "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 @@ class UdsClient(): 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 @@ class UdsClient(): 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 @@ class UdsClient(): 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 @@ class UdsClient(): 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 @@ class UdsClient(): 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 @@ class UdsClient(): 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 @@ class UdsClient(): 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 @@ class UdsClient(): 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 @@ class UdsClient(): 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 @@ class UdsClient(): 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 @@ class UdsClient(): 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 c419056a9..25ee66923 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 bc5bad331..278766a19 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 @@ if __name__ == "__main__": 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 119c6b682..56e825f5d 100755 --- a/tests/elm_car_simulator.py +++ b/tests/elm_car_simulator.py @@ -190,7 +190,7 @@ class ELMCarSimulator(): 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 @@ class ELMCarSimulator(): 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 75fb1c652..983d4a141 100755 --- a/tests/elm_throughput.py +++ b/tests/elm_throughput.py @@ -6,7 +6,7 @@ import select 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 e9158d609..2bdfab79a 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 116d8abec..a0138122b 100755 --- a/tests/get_version.py +++ b/tests/get_version.py @@ -4,4 +4,4 @@ from panda import Panda 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 73285e7e5..8dc594de4 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 @@ if __name__ == "__main__": 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 f00bc9547..a7e1aea1e 100644 --- a/tests/hitl/4_can_loopback.py +++ b/tests/hitl/4_can_loopback.py @@ -24,7 +24,7 @@ def test_send_recv(p, panda_jungle): 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_latency(p, panda_jungle): 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 d7ac4da0d..4eee43731 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 1b07543d6..8f876c551 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 99d35b043..bf485e454 100755 --- a/tests/message_drop_test.py +++ b/tests/message_drop_test.py @@ -5,7 +5,7 @@ import time import struct import itertools import threading -from typing import Any, Union, List +from typing import Any from panda import Panda @@ -16,7 +16,7 @@ if JUNGLE: # 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 @@ if __name__ == "__main__": 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 ec0534eba..5d311c9ea 100755 --- a/tests/read_winusb_descriptors.py +++ b/tests/read_winusb_descriptors.py @@ -12,23 +12,23 @@ if __name__ == "__main__": 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 8b70966ae..a3c22dffb 100644 --- a/tests/safety/common.py +++ b/tests/safety/common.py @@ -3,7 +3,7 @@ import abc 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 @@ class PandaSafetyTestBase(unittest.TestCase): 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 @@ class LongitudinalAccelSafetyTest(PandaSafetyTestBase, abc.ABC): 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 @@ class MotorTorqueSteeringSafetyTest(TorqueSteeringSafetyTestBase, abc.ABC): 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 @@ class AngleSteeringSafetyTest(PandaSafetyTestBase): 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 @@ class PandaSafetyTest(PandaSafetyTestBase): @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 3fd36a0e1..da18671af 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 @@ class HyundaiButtonBase: 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 587aa3f1c..28b2ad50e 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 08d069b5e..45f190c36 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 @@ class HondaPcmEnableBase(common.PandaCarSafetyTest): 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 From 4303ae1387d91be82314945209ac0d2ff7199e46 Mon Sep 17 00:00:00 2001 From: Aryan <53595853+0x41head@users.noreply.github.com> Date: Wed, 28 Feb 2024 00:02:28 +0530 Subject: [PATCH 33/67] enable misra-c2012-10.6 (#1811) * misra-c2012-10.6 * fixed uninitialized data error * revert false positive * enable 10.6 * update install.sh * cleanup * bug fix * better fix ? --- board/drivers/usb.h | 6 +++--- tests/misra/install.sh | 2 +- tests/misra/suppressions.txt | 1 - 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/board/drivers/usb.h b/board/drivers/usb.h index 1872dd527..5ecbea219 100644 --- a/board/drivers/usb.h +++ b/board/drivers/usb.h @@ -364,7 +364,7 @@ int current_int0_alt_setting = 0; void *USB_ReadPacket(void *dest, uint16_t len) { uint32_t *dest_copy = (uint32_t *)dest; - uint32_t count32b = (len + 3U) / 4U; + uint32_t count32b = ((uint32_t)len + 3U) / 4U; for (uint32_t i = 0; i < count32b; i++) { *dest_copy = USBx_DFIFO(0); @@ -379,9 +379,9 @@ void USB_WritePacket(const void *src, uint16_t len, uint32_t ep) { hexdump(src, len); #endif - uint32_t numpacket = (len + (USBPACKET_MAX_SIZE - 1U)) / USBPACKET_MAX_SIZE; + uint32_t numpacket = ((uint32_t)len + (USBPACKET_MAX_SIZE - 1U)) / USBPACKET_MAX_SIZE; uint32_t count32b = 0; - count32b = (len + 3U) / 4U; + count32b = ((uint32_t)len + 3U) / 4U; // TODO: revisit this USBx_INEP(ep)->DIEPTSIZ = ((numpacket << 19) & USB_OTG_DIEPTSIZ_PKTCNT) | diff --git a/tests/misra/install.sh b/tests/misra/install.sh index a29b11117..ecc0b3f0d 100755 --- a/tests/misra/install.sh +++ b/tests/misra/install.sh @@ -13,7 +13,7 @@ cd $CPPCHECK_DIR VERS="2.13.0" git fetch --all --tags git checkout $VERS -git cherry-pick -n f6b538e855f0bacea33c4074664628024ef39dc6 +git cherry-pick -n f6b538e855f0bacea33c4074664628024ef39dc6 b11b42087ff29569bc3740f5aa07eb6616ea4f63 #make clean make MATCHCOMPILTER=yes CXXFLAGS="-O2" -j8 diff --git a/tests/misra/suppressions.txt b/tests/misra/suppressions.txt index be4b0e026..d5b14c836 100644 --- a/tests/misra/suppressions.txt +++ b/tests/misra/suppressions.txt @@ -23,5 +23,4 @@ misra-c2012-1.2 # this is from the extensions (e.g. __typeof__) used in the MIN misra-c2012-2.5 misra-c2012-8.7 misra-c2012-8.4 -misra-c2012-10.6 misra-c2012-21.15 From ea156f7c628a371bea9a15a29f9068d5392534ba Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Wed, 28 Feb 2024 20:31:47 -0800 Subject: [PATCH 34/67] revert that for now --- board/stm32h7/clock.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/board/stm32h7/clock.h b/board/stm32h7/clock.h index 7d65d080e..a0ac01d0d 100644 --- a/board/stm32h7/clock.h +++ b/board/stm32h7/clock.h @@ -21,11 +21,11 @@ void clock_init(void) { // Set power mode to direct SMPS power supply(depends on the board layout) #ifndef STM32H723 register_set(&(PWR->CR3), PWR_CR3_SMPSEN, 0xFU); // powered only by SMPS -#endif // Set VOS level (VOS3 to 170Mhz, VOS2 to 300Mhz, VOS1 to 400Mhz, VOS0 to 550Mhz) register_set(&(PWR->D3CR), PWR_D3CR_VOS_1 | PWR_D3CR_VOS_0, 0xC000U); //VOS1, needed for 80Mhz CAN FD while ((PWR->CSR1 & PWR_CSR1_ACTVOSRDY) == 0); while ((PWR->CSR1 & PWR_CSR1_ACTVOS) != (PWR->D3CR & PWR_D3CR_VOS)); // check that VOS level was actually set +#endif // Configure Flash ACR register LATENCY and WRHIGHFREQ (VOS0 range!) register_set(&(FLASH->ACR), FLASH_ACR_LATENCY_2WS | 0x20U, 0x3FU); // VOS2, AXI 100MHz-150MHz From 41e9610ff841e4cf62051c6df09c1870f5d12477 Mon Sep 17 00:00:00 2001 From: Robbe Derks Date: Wed, 6 Mar 2024 21:13:13 +0100 Subject: [PATCH 35/67] Tesla Raven (#1886) * raven uses a different steering angle sensor * add raven flag * raven test * bump opendbc ref --- Dockerfile | 2 +- board/safety/safety_tesla.h | 31 +++++++++++++++++++++++-------- python/__init__.py | 1 + tests/safety/test_tesla.py | 11 +++++++++++ 4 files changed, 36 insertions(+), 9 deletions(-) diff --git a/Dockerfile b/Dockerfile index b2c207329..99bedcf08 100644 --- a/Dockerfile +++ b/Dockerfile @@ -52,7 +52,7 @@ ENV PATH="/root/.pyenv/bin:/root/.pyenv/shims:${PATH}" ENV PANDA_PATH=/tmp/openpilot/panda ENV OPENPILOT_REF="5690386d8d731c9bebda536a5c71c890f6dfe98c" -ENV OPENDBC_REF="40d9c723d48496229fecc436046538a53af19c11" +ENV OPENDBC_REF="1745ab51825055cd18748013c4a5e3377319e390" COPY requirements.txt /tmp/ RUN pyenv install 3.11.4 && \ diff --git a/board/safety/safety_tesla.h b/board/safety/safety_tesla.h index 4fa0df84a..652161ff2 100644 --- a/board/safety/safety_tesla.h +++ b/board/safety/safety_tesla.h @@ -19,6 +19,7 @@ const LongitudinalLimits TESLA_LONG_LIMITS = { const int TESLA_FLAG_POWERTRAIN = 1; const int TESLA_FLAG_LONGITUDINAL_CONTROL = 2; +const int TESLA_FLAG_RAVEN = 4; const CanMsg TESLA_TX_MSGS[] = { {0x488, 0, 4}, // DAS_steeringControl @@ -41,6 +42,16 @@ RxCheck tesla_rx_checks[] = { {.msg = {{0x318, 0, 8, .frequency = 10U}, { 0 }, { 0 }}}, // GTW_carState }; +RxCheck tesla_raven_rx_checks[] = { + {.msg = {{0x2b9, 2, 8, .frequency = 25U}, { 0 }, { 0 }}}, // DAS_control + {.msg = {{0x131, 2, 8, .frequency = 100U}, { 0 }, { 0 }}}, // EPAS3P_sysStatus + {.msg = {{0x108, 0, 8, .frequency = 100U}, { 0 }, { 0 }}}, // DI_torque1 + {.msg = {{0x118, 0, 6, .frequency = 100U}, { 0 }, { 0 }}}, // DI_torque2 + {.msg = {{0x20a, 0, 8, .frequency = 50U}, { 0 }, { 0 }}}, // BrakeMessage + {.msg = {{0x368, 0, 8, .frequency = 10U}, { 0 }, { 0 }}}, // DI_state + {.msg = {{0x318, 0, 8, .frequency = 10U}, { 0 }, { 0 }}}, // GTW_carState +}; + RxCheck tesla_pt_rx_checks[] = { {.msg = {{0x106, 0, 8, .frequency = 100U}, { 0 }, { 0 }}}, // DI_torque1 {.msg = {{0x116, 0, 6, .frequency = 100U}, { 0 }, { 0 }}}, // DI_torque2 @@ -51,6 +62,7 @@ RxCheck tesla_pt_rx_checks[] = { bool tesla_longitudinal = false; bool tesla_powertrain = false; // Are we the second panda intercepting the powertrain bus? +bool tesla_raven = false; bool tesla_stock_aeb = false; @@ -58,16 +70,16 @@ static void tesla_rx_hook(const CANPacket_t *to_push) { int bus = GET_BUS(to_push); int addr = GET_ADDR(to_push); - if(bus == 0) { - if (!tesla_powertrain) { - if(addr == 0x370) { - // Steering angle: (0.1 * val) - 819.2 in deg. - // Store it 1/10 deg to match steering request - int angle_meas_new = (((GET_BYTE(to_push, 4) & 0x3FU) << 8) | GET_BYTE(to_push, 5)) - 8192U; - update_sample(&angle_meas, angle_meas_new); - } + if (!tesla_powertrain) { + if((!tesla_raven && (addr == 0x370) && (bus == 0)) || (tesla_raven && (addr == 0x131) && (bus == 2))) { + // Steering angle: (0.1 * val) - 819.2 in deg. + // Store it 1/10 deg to match steering request + int angle_meas_new = (((GET_BYTE(to_push, 4) & 0x3FU) << 8) | GET_BYTE(to_push, 5)) - 8192U; + update_sample(&angle_meas, angle_meas_new); } + } + if(bus == 0) { if(addr == (tesla_powertrain ? 0x116 : 0x118)) { // Vehicle speed: ((0.05 * val) - 25) * MPH_TO_MPS float speed = (((((GET_BYTE(to_push, 3) & 0x0FU) << 8) | (GET_BYTE(to_push, 2))) * 0.05) - 25) * 0.447; @@ -206,12 +218,15 @@ static int tesla_fwd_hook(int bus_num, int addr) { static safety_config tesla_init(uint16_t param) { tesla_powertrain = GET_FLAG(param, TESLA_FLAG_POWERTRAIN); tesla_longitudinal = GET_FLAG(param, TESLA_FLAG_LONGITUDINAL_CONTROL); + tesla_raven = GET_FLAG(param, TESLA_FLAG_RAVEN); tesla_stock_aeb = false; safety_config ret; if (tesla_powertrain) { ret = BUILD_SAFETY_CFG(tesla_pt_rx_checks, TESLA_PT_TX_MSGS); + } else if (tesla_raven) { + ret = BUILD_SAFETY_CFG(tesla_raven_rx_checks, TESLA_TX_MSGS); } else { ret = BUILD_SAFETY_CFG(tesla_rx_checks, TESLA_TX_MSGS); } diff --git a/python/__init__.py b/python/__init__.py index 6e614775d..304aa1352 100644 --- a/python/__init__.py +++ b/python/__init__.py @@ -214,6 +214,7 @@ class Panda: FLAG_TESLA_POWERTRAIN = 1 FLAG_TESLA_LONG_CONTROL = 2 + FLAG_TESLA_RAVEN = 4 FLAG_VOLKSWAGEN_LONG_CONTROL = 1 diff --git a/tests/safety/test_tesla.py b/tests/safety/test_tesla.py index 0b425ae19..9461ff68f 100755 --- a/tests/safety/test_tesla.py +++ b/tests/safety/test_tesla.py @@ -108,6 +108,17 @@ class TestTeslaSteeringSafety(TestTeslaSafety, common.AngleSteeringSafetyTest): self.assertEqual(tx, should_tx) +class TestTeslaRavenSteeringSafety(TestTeslaSteeringSafety): + def setUp(self): + self.packer = CANPackerPanda("tesla_can") + self.safety = libpanda_py.libpanda + self.safety.set_safety_hooks(Panda.SAFETY_TESLA, Panda.FLAG_TESLA_RAVEN) + self.safety.init_tests() + + def _angle_meas_msg(self, angle: float): + values = {"EPAS_internalSAS": angle} + return self.packer.make_can_msg_panda("EPAS3P_sysStatus", 2, values) + class TestTeslaLongitudinalSafety(TestTeslaSafety): def setUp(self): raise unittest.SkipTest From 01984e5b443ce9a8d77a3e92431fdf9f39a4aac3 Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Thu, 7 Mar 2024 13:57:02 -0800 Subject: [PATCH 36/67] pre-commit: autoupdate hooks (#1892) 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 1f978433e..402bdc3a1 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.2 + rev: v0.3.0 hooks: - id: ruff From 4b6f6ac1629d001ced6e86f43579d399230af614 Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Fri, 8 Mar 2024 14:57:33 -0800 Subject: [PATCH 37/67] 723 power init (#1891) LDO only This reverts commit ea156f7c628a371bea9a15a29f9068d5392534ba. Co-authored-by: Comma Device --- board/stm32h7/clock.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/board/stm32h7/clock.h b/board/stm32h7/clock.h index a0ac01d0d..94e08ca60 100644 --- a/board/stm32h7/clock.h +++ b/board/stm32h7/clock.h @@ -21,11 +21,13 @@ void clock_init(void) { // Set power mode to direct SMPS power supply(depends on the board layout) #ifndef STM32H723 register_set(&(PWR->CR3), PWR_CR3_SMPSEN, 0xFU); // powered only by SMPS +#else + register_set(&(PWR->CR3), PWR_CR3_LDOEN, 0xFU); +#endif // Set VOS level (VOS3 to 170Mhz, VOS2 to 300Mhz, VOS1 to 400Mhz, VOS0 to 550Mhz) register_set(&(PWR->D3CR), PWR_D3CR_VOS_1 | PWR_D3CR_VOS_0, 0xC000U); //VOS1, needed for 80Mhz CAN FD while ((PWR->CSR1 & PWR_CSR1_ACTVOSRDY) == 0); while ((PWR->CSR1 & PWR_CSR1_ACTVOS) != (PWR->D3CR & PWR_D3CR_VOS)); // check that VOS level was actually set -#endif // Configure Flash ACR register LATENCY and WRHIGHFREQ (VOS0 range!) register_set(&(FLASH->ACR), FLASH_ACR_LATENCY_2WS | 0x20U, 0x3FU); // VOS2, AXI 100MHz-150MHz From 6dfd4db4ab907f8bb8537522ee401166c2780c7d Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Mon, 11 Mar 2024 16:08:43 -0700 Subject: [PATCH 38/67] remove rtc (#1897) * remove rtc * fix build * rm taht * revert that --- board/boards/black.h | 3 -- board/boards/board_declarations.h | 1 - board/boards/cuatro.h | 1 - board/boards/dos.h | 3 -- board/boards/grey.h | 1 - board/boards/red.h | 3 -- board/boards/red_chiplet.h | 2 - board/boards/tres.h | 1 - board/boards/uno.h | 3 -- board/boards/white.h | 3 -- board/drivers/rtc.h | 79 ------------------------------- board/main.c | 22 --------- board/main_comms.h | 53 --------------------- board/stm32fx/board.h | 2 - board/stm32fx/llrtc.h | 69 --------------------------- board/stm32h7/board.h | 2 - board/stm32h7/llrtc.h | 69 --------------------------- python/__init__.py | 16 ------- tests/rtc_test.py | 10 ---- 19 files changed, 343 deletions(-) delete mode 100644 board/drivers/rtc.h delete mode 100644 board/stm32fx/llrtc.h delete mode 100644 board/stm32h7/llrtc.h delete mode 100755 tests/rtc_test.py diff --git a/board/boards/black.h b/board/boards/black.h index ea636334d..917193893 100644 --- a/board/boards/black.h +++ b/board/boards/black.h @@ -122,8 +122,6 @@ void black_init(void) { // Initialize harness harness_init(); - // Initialize RTC - rtc_init(); // Enable CAN transceivers black_enable_can_transceivers(true); @@ -168,7 +166,6 @@ const board board_black = { .has_obd = true, .has_spi = false, .has_canfd = false, - .has_rtc_battery = false, .fan_max_rpm = 0U, .avdd_mV = 3300U, .fan_stall_recovery = false, diff --git a/board/boards/board_declarations.h b/board/boards/board_declarations.h index 600dc2884..f30216a0d 100644 --- a/board/boards/board_declarations.h +++ b/board/boards/board_declarations.h @@ -25,7 +25,6 @@ struct board { const bool has_obd; const bool has_spi; const bool has_canfd; - const bool has_rtc_battery; const uint16_t fan_max_rpm; const uint16_t avdd_mV; const bool fan_stall_recovery; diff --git a/board/boards/cuatro.h b/board/boards/cuatro.h index b8cd3d035..f497f3f69 100644 --- a/board/boards/cuatro.h +++ b/board/boards/cuatro.h @@ -108,7 +108,6 @@ const board board_cuatro = { .has_obd = true, .has_spi = true, .has_canfd = true, - .has_rtc_battery = true, .fan_max_rpm = 6600U, .avdd_mV = 1800U, .fan_stall_recovery = false, diff --git a/board/boards/dos.h b/board/boards/dos.h index 428bbf2a5..ca98ad967 100644 --- a/board/boards/dos.h +++ b/board/boards/dos.h @@ -147,8 +147,6 @@ void dos_init(void) { // Initialize harness harness_init(); - // Initialize RTC - rtc_init(); // Enable CAN transceivers dos_enable_can_transceivers(true); @@ -196,7 +194,6 @@ const board board_dos = { .has_spi = false, #endif .has_canfd = false, - .has_rtc_battery = true, .fan_max_rpm = 6500U, .avdd_mV = 3300U, .fan_stall_recovery = true, diff --git a/board/boards/grey.h b/board/boards/grey.h index 8b3bd8aed..75273c1ad 100644 --- a/board/boards/grey.h +++ b/board/boards/grey.h @@ -10,7 +10,6 @@ const board board_grey = { .has_obd = false, .has_spi = false, .has_canfd = false, - .has_rtc_battery = false, .fan_max_rpm = 0U, .avdd_mV = 3300U, .fan_stall_recovery = false, diff --git a/board/boards/red.h b/board/boards/red.h index aa8c91be7..2ba9f3566 100644 --- a/board/boards/red.h +++ b/board/boards/red.h @@ -140,8 +140,6 @@ void red_init(void) { // Initialize harness harness_init(); - // Initialize RTC - rtc_init(); // Enable CAN transceivers red_enable_can_transceivers(true); @@ -180,7 +178,6 @@ const board board_red = { .has_obd = true, .has_spi = false, .has_canfd = true, - .has_rtc_battery = false, .fan_max_rpm = 0U, .avdd_mV = 3300U, .fan_stall_recovery = false, diff --git a/board/boards/red_chiplet.h b/board/boards/red_chiplet.h index eec3d95cd..8b0f9333f 100644 --- a/board/boards/red_chiplet.h +++ b/board/boards/red_chiplet.h @@ -119,8 +119,6 @@ void red_chiplet_init(void) { // Initialize harness harness_init(); - // Initialize RTC - rtc_init(); // Enable CAN transceivers red_chiplet_enable_can_transceivers(true); diff --git a/board/boards/tres.h b/board/boards/tres.h index 959c93b5d..50d55e280 100644 --- a/board/boards/tres.h +++ b/board/boards/tres.h @@ -75,7 +75,6 @@ const board board_tres = { .has_obd = true, .has_spi = true, .has_canfd = true, - .has_rtc_battery = true, .fan_max_rpm = 6600U, .avdd_mV = 1800U, .fan_stall_recovery = false, diff --git a/board/boards/uno.h b/board/boards/uno.h index f4e2016bd..3c6ce177b 100644 --- a/board/boards/uno.h +++ b/board/boards/uno.h @@ -147,8 +147,6 @@ void uno_init(void) { // Initialize harness harness_init(); - // Initialize RTC - rtc_init(); // Enable CAN transceivers uno_enable_can_transceivers(true); @@ -203,7 +201,6 @@ const board board_uno = { .has_obd = true, .has_spi = false, .has_canfd = false, - .has_rtc_battery = true, .fan_max_rpm = 5100U, .avdd_mV = 3300U, .fan_stall_recovery = false, diff --git a/board/boards/white.h b/board/boards/white.h index 0de29a39b..362f525a5 100644 --- a/board/boards/white.h +++ b/board/boards/white.h @@ -187,8 +187,6 @@ void white_grey_init(void) { set_gpio_alternate(GPIOC, 11, GPIO_AF7_USART3); set_gpio_pullup(GPIOC, 11, PULL_UP); - // Initialize RTC - rtc_init(); // Enable CAN transceivers white_enable_can_transceivers(true); @@ -231,7 +229,6 @@ const board board_white = { .has_obd = false, .has_spi = false, .has_canfd = false, - .has_rtc_battery = false, .fan_max_rpm = 0U, .avdd_mV = 3300U, .fan_stall_recovery = false, diff --git a/board/drivers/rtc.h b/board/drivers/rtc.h deleted file mode 100644 index df121e3e8..000000000 --- a/board/drivers/rtc.h +++ /dev/null @@ -1,79 +0,0 @@ -#define YEAR_OFFSET 2000U - -typedef struct __attribute__((packed)) timestamp_t { - uint16_t year; - uint8_t month; - uint8_t day; - uint8_t weekday; - uint8_t hour; - uint8_t minute; - uint8_t second; -} timestamp_t; - -uint8_t to_bcd(uint16_t value){ - return (((value / 10U) & 0x0FU) << 4U) | ((value % 10U) & 0x0FU); -} - -uint16_t from_bcd(uint8_t value){ - return (((value & 0xF0U) >> 4U) * 10U) + (value & 0x0FU); -} - -void rtc_set_time(timestamp_t time){ - print("Setting RTC time\n"); - - // Disable write protection - disable_bdomain_protection(); - RTC->WPR = 0xCA; - RTC->WPR = 0x53; - - // Enable initialization mode - register_set_bits(&(RTC->ISR), RTC_ISR_INIT); - while((RTC->ISR & RTC_ISR_INITF) == 0){} - - // Set time - RTC->TR = (to_bcd(time.hour) << RTC_TR_HU_Pos) | (to_bcd(time.minute) << RTC_TR_MNU_Pos) | (to_bcd(time.second) << RTC_TR_SU_Pos); - RTC->DR = (to_bcd(time.year - YEAR_OFFSET) << RTC_DR_YU_Pos) | (time.weekday << RTC_DR_WDU_Pos) | (to_bcd(time.month) << RTC_DR_MU_Pos) | (to_bcd(time.day) << RTC_DR_DU_Pos); - - // Set options - register_set(&(RTC->CR), 0U, 0xFCFFFFU); - - // Disable initalization mode - register_clear_bits(&(RTC->ISR), RTC_ISR_INIT); - - // Wait for synchronization - while((RTC->ISR & RTC_ISR_RSF) == 0){} - - // Re-enable write protection - RTC->WPR = 0x00; - enable_bdomain_protection(); -} - -timestamp_t rtc_get_time(void){ - timestamp_t result; - // Init with zero values in case there is no RTC running - result.year = 0U; - result.month = 0U; - result.day = 0U; - result.weekday = 0U; - result.hour = 0U; - result.minute = 0U; - result.second = 0U; - - // Wait until the register sync flag is set - while((RTC->ISR & RTC_ISR_RSF) == 0){} - - // Read time and date registers. Since our HSE > 7*LSE, this should be fine. - uint32_t time = RTC->TR; - uint32_t date = RTC->DR; - - // Parse values - result.year = from_bcd((date & (RTC_DR_YT | RTC_DR_YU)) >> RTC_DR_YU_Pos) + YEAR_OFFSET; - result.month = from_bcd((date & (RTC_DR_MT | RTC_DR_MU)) >> RTC_DR_MU_Pos); - result.day = from_bcd((date & (RTC_DR_DT | RTC_DR_DU)) >> RTC_DR_DU_Pos); - result.weekday = ((date & RTC_DR_WDU) >> RTC_DR_WDU_Pos); - result.hour = from_bcd((time & (RTC_TR_HT | RTC_TR_HU)) >> RTC_TR_HU_Pos); - result.minute = from_bcd((time & (RTC_TR_MNT | RTC_TR_MNU)) >> RTC_TR_MNU_Pos); - result.second = from_bcd((time & (RTC_TR_ST | RTC_TR_SU)) >> RTC_TR_SU_Pos); - - return result; -} diff --git a/board/main.c b/board/main.c index 061a91381..00429e32a 100644 --- a/board/main.c +++ b/board/main.c @@ -294,24 +294,6 @@ void EXTI_IRQ_Handler(void) { } } -uint8_t rtc_counter = 0; -void RTC_WKUP_IRQ_Handler(void) { - exti_irq_clear(); - clock_init(); - - rtc_counter++; - if ((rtc_counter % 2U) == 0U) { - current_board->set_led(LED_BLUE, false); - } else { - current_board->set_led(LED_BLUE, true); - } - - if (rtc_counter == __UINT8_MAX__) { - rtc_counter = 1U; - } -} - - int main(void) { // Init interrupt table init_interrupts(true); @@ -422,10 +404,6 @@ int main(void) { // Init IRQs for CAN transceiver and ignition line exti_irq_init(); - // Init RTC Wakeup event on EXTI22 - REGISTER_INTERRUPT(RTC_WKUP_IRQn, RTC_WKUP_IRQ_Handler, 10U, FAULT_INTERRUPT_RATE_EXTI) - rtc_wakeup_init(); - // STOP mode SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; } diff --git a/board/main_comms.h b/board/main_comms.h index c0d5c516f..2c8bf165b 100644 --- a/board/main_comms.h +++ b/board/main_comms.h @@ -48,12 +48,6 @@ int get_health_pkt(void *dat) { return sizeof(*health); } -int get_rtc_pkt(void *dat) { - timestamp_t t = rtc_get_time(); - (void)memcpy(dat, &t, sizeof(t)); - return sizeof(t); -} - // send on serial, first byte to select the ring void comms_endpoint2_write(const uint8_t *data, uint32_t len) { uart_ring *ur = get_ring_by_number(data[0]); @@ -71,7 +65,6 @@ void comms_endpoint2_write(const uint8_t *data, uint32_t len) { int comms_control_handler(ControlPacket_t *req, uint8_t *resp) { unsigned int resp_len = 0; uart_ring *ur = NULL; - timestamp_t t; uint32_t time; #ifdef DEBUG_COMMS @@ -82,52 +75,6 @@ int comms_control_handler(ControlPacket_t *req, uint8_t *resp) { #endif switch (req->request) { - // **** 0xa0: get rtc time - case 0xa0: - resp_len = get_rtc_pkt(resp); - break; - // **** 0xa1: set rtc year - case 0xa1: - t = rtc_get_time(); - t.year = req->param1; - rtc_set_time(t); - break; - // **** 0xa2: set rtc month - case 0xa2: - t = rtc_get_time(); - t.month = req->param1; - rtc_set_time(t); - break; - // **** 0xa3: set rtc day - case 0xa3: - t = rtc_get_time(); - t.day = req->param1; - rtc_set_time(t); - break; - // **** 0xa4: set rtc weekday - case 0xa4: - t = rtc_get_time(); - t.weekday = req->param1; - rtc_set_time(t); - break; - // **** 0xa5: set rtc hour - case 0xa5: - t = rtc_get_time(); - t.hour = req->param1; - rtc_set_time(t); - break; - // **** 0xa6: set rtc minute - case 0xa6: - t = rtc_get_time(); - t.minute = req->param1; - rtc_set_time(t); - break; - // **** 0xa7: set rtc second - case 0xa7: - t = rtc_get_time(); - t.second = req->param1; - rtc_set_time(t); - break; // **** 0xa8: get microsecond timer case 0xa8: time = microsecond_timer_get(); diff --git a/board/stm32fx/board.h b/board/stm32fx/board.h index 808f77382..810361189 100644 --- a/board/stm32fx/board.h +++ b/board/stm32fx/board.h @@ -9,8 +9,6 @@ #include "drivers/harness.h" #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" diff --git a/board/stm32fx/llrtc.h b/board/stm32fx/llrtc.h deleted file mode 100644 index a9b61917e..000000000 --- a/board/stm32fx/llrtc.h +++ /dev/null @@ -1,69 +0,0 @@ -void enable_bdomain_protection(void) { - register_clear_bits(&(PWR->CR), PWR_CR_DBP); -} - -void disable_bdomain_protection(void) { - register_set_bits(&(PWR->CR), PWR_CR_DBP); -} - -void rtc_init(void){ - uint32_t bdcr_opts = RCC_BDCR_RTCEN; - uint32_t bdcr_mask = (RCC_BDCR_RTCEN | RCC_BDCR_RTCSEL); - if (current_board->has_rtc_battery) { - bdcr_opts |= (RCC_BDCR_RTCSEL_0 | RCC_BDCR_LSEON); - bdcr_mask |= (RCC_BDCR_LSEMOD | RCC_BDCR_LSEBYP | RCC_BDCR_LSEON); - } else { - bdcr_opts |= RCC_BDCR_RTCSEL_1; - RCC->CSR |= RCC_CSR_LSION; - while((RCC->CSR & RCC_CSR_LSIRDY) == 0){} - } - - // Initialize RTC module and clock if not done already. - if((RCC->BDCR & bdcr_mask) != bdcr_opts){ - print("Initializing RTC\n"); - // Reset backup domain - register_set_bits(&(RCC->BDCR), RCC_BDCR_BDRST); - - // Disable write protection - disable_bdomain_protection(); - - // Clear backup domain reset - register_clear_bits(&(RCC->BDCR), RCC_BDCR_BDRST); - - // Set RTC options - register_set(&(RCC->BDCR), bdcr_opts, bdcr_mask); - - // Enable write protection - enable_bdomain_protection(); - } -} - -void rtc_wakeup_init(void) { - EXTI->IMR |= EXTI_IMR_MR22; - EXTI->RTSR |= EXTI_RTSR_TR22; // rising edge - EXTI->FTSR &= ~EXTI_FTSR_TR22; // falling edge - - NVIC_DisableIRQ(RTC_WKUP_IRQn); - - // Disable write protection - disable_bdomain_protection(); - RTC->WPR = 0xCA; - RTC->WPR = 0x53; - - RTC->CR &= ~RTC_CR_WUTE; - while((RTC->ISR & RTC_ISR_WUTWF) == 0){} - - RTC->CR &= ~RTC_CR_WUTIE; - RTC->ISR &= ~RTC_ISR_WUTF; - //PWR->CR |= PWR_CR_CWUF; - - RTC->WUTR = DEEPSLEEP_WAKEUP_DELAY; - // Wakeup timer interrupt enable, wakeup timer enable, select 1Hz rate - RTC->CR |= RTC_CR_WUTE | RTC_CR_WUTIE | RTC_CR_WUCKSEL_2; - - // Re-enable write protection - RTC->WPR = 0x00; - enable_bdomain_protection(); - - NVIC_EnableIRQ(RTC_WKUP_IRQn); -} diff --git a/board/stm32h7/board.h b/board/stm32h7/board.h index d293a54cf..f5a8e55aa 100644 --- a/board/stm32h7/board.h +++ b/board/stm32h7/board.h @@ -9,10 +9,8 @@ #include "drivers/harness.h" #include "drivers/fan.h" #include "stm32h7/llfan.h" -#include "stm32h7/llrtc.h" #include "stm32h7/lldac.h" #include "drivers/fake_siren.h" -#include "drivers/rtc.h" #include "drivers/clock_source.h" #include "boards/red.h" #include "boards/red_chiplet.h" diff --git a/board/stm32h7/llrtc.h b/board/stm32h7/llrtc.h deleted file mode 100644 index 03787d0db..000000000 --- a/board/stm32h7/llrtc.h +++ /dev/null @@ -1,69 +0,0 @@ -void enable_bdomain_protection(void) { - register_clear_bits(&(PWR->CR1), PWR_CR1_DBP); -} - -void disable_bdomain_protection(void) { - register_set_bits(&(PWR->CR1), PWR_CR1_DBP); -} - -void rtc_init(void){ - uint32_t bdcr_opts = RCC_BDCR_RTCEN; - uint32_t bdcr_mask = (RCC_BDCR_RTCEN | RCC_BDCR_RTCSEL); - if (current_board->has_rtc_battery) { - bdcr_opts |= (RCC_BDCR_LSEDRV_1 | RCC_BDCR_RTCSEL_0 | RCC_BDCR_LSEON); - bdcr_mask |= (RCC_BDCR_LSEDRV | RCC_BDCR_LSEBYP | RCC_BDCR_LSEON); - } else { - bdcr_opts |= RCC_BDCR_RTCSEL_1; - RCC->CSR |= RCC_CSR_LSION; - while((RCC->CSR & RCC_CSR_LSIRDY) == 0){} - } - - // Initialize RTC module and clock if not done already. - if((RCC->BDCR & bdcr_mask) != bdcr_opts){ - print("Initializing RTC\n"); - // Reset backup domain - register_set_bits(&(RCC->BDCR), RCC_BDCR_BDRST); - - // Disable write protection - disable_bdomain_protection(); - - // Clear backup domain reset - register_clear_bits(&(RCC->BDCR), RCC_BDCR_BDRST); - - // Set RTC options - register_set(&(RCC->BDCR), bdcr_opts, bdcr_mask); - - // Enable write protection - enable_bdomain_protection(); - } -} - -void rtc_wakeup_init(void) { - EXTI->IMR1 |= EXTI_IMR1_IM19; - EXTI->RTSR1 |= EXTI_RTSR1_TR19; // rising edge - EXTI->FTSR1 &= ~EXTI_FTSR1_TR19; // falling edge - - NVIC_DisableIRQ(RTC_WKUP_IRQn); - - // Disable write protection - disable_bdomain_protection(); - RTC->WPR = 0xCA; - RTC->WPR = 0x53; - - RTC->CR &= ~RTC_CR_WUTE; - while((RTC->ISR & RTC_ISR_WUTWF) == 0){} - - RTC->CR &= ~RTC_CR_WUTIE; - RTC->ISR &= ~RTC_ISR_WUTF; - //PWR->CR1 |= PWR_CR1_CWUF; - - RTC->WUTR = DEEPSLEEP_WAKEUP_DELAY; - // Wakeup timer interrupt enable, wakeup timer enable, select 1Hz rate - RTC->CR |= RTC_CR_WUTE | RTC_CR_WUTIE | RTC_CR_WUCKSEL_2; - - // Re-enable write protection - RTC->WPR = 0x00; - enable_bdomain_protection(); - - NVIC_EnableIRQ(RTC_WKUP_IRQn); -} diff --git a/python/__init__.py b/python/__init__.py index 304aa1352..063602f4d 100644 --- a/python/__init__.py +++ b/python/__init__.py @@ -6,7 +6,6 @@ import usb1 import struct import hashlib import binascii -import datetime import logging from functools import wraps, partial from itertools import accumulate @@ -894,21 +893,6 @@ class Panda: def set_heartbeat_disabled(self): self._handle.controlWrite(Panda.REQUEST_OUT, 0xf8, 0, 0, b'') - # ******************* RTC ******************* - def set_datetime(self, dt): - self._handle.controlWrite(Panda.REQUEST_OUT, 0xa1, int(dt.year), 0, b'') - self._handle.controlWrite(Panda.REQUEST_OUT, 0xa2, int(dt.month), 0, b'') - self._handle.controlWrite(Panda.REQUEST_OUT, 0xa3, int(dt.day), 0, b'') - self._handle.controlWrite(Panda.REQUEST_OUT, 0xa4, int(dt.isoweekday()), 0, b'') - self._handle.controlWrite(Panda.REQUEST_OUT, 0xa5, int(dt.hour), 0, b'') - self._handle.controlWrite(Panda.REQUEST_OUT, 0xa6, int(dt.minute), 0, b'') - self._handle.controlWrite(Panda.REQUEST_OUT, 0xa7, int(dt.second), 0, b'') - - def get_datetime(self): - dat = self._handle.controlRead(Panda.REQUEST_IN, 0xa0, 0, 0, 8) - a = struct.unpack("HBBBBBB", dat) - return datetime.datetime(a[0], a[1], a[2], a[4], a[5], a[6]) - # ****************** Timer ***************** def get_microsecond_timer(self): dat = self._handle.controlRead(Panda.REQUEST_IN, 0xa8, 0, 0, 4) diff --git a/tests/rtc_test.py b/tests/rtc_test.py deleted file mode 100755 index 01c9f4ddd..000000000 --- a/tests/rtc_test.py +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env python -import datetime - -from panda import Panda - -if __name__ == "__main__": - p = Panda() - - p.set_datetime(datetime.datetime.now()) - print(p.get_datetime()) From 895a7001c9d21ac7c4ace65debe70dfaee017443 Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Mon, 11 Mar 2024 16:18:56 -0700 Subject: [PATCH 39/67] Rename stm32fx/ -> stm32f4/ (#1898) * Rename stm32fx/ -> stm32f4/ * jungle too --- SConscript | 6 ++--- board/config.h | 2 +- board/jungle/{stm32fx => stm32f4}/board.h | 0 board/{stm32fx => stm32f4}/board.h | 4 ++-- board/{stm32fx => stm32f4}/clock.h | 0 .../{stm32fx => stm32f4}/inc/cmsis_compiler.h | 0 board/{stm32fx => stm32f4}/inc/cmsis_gcc.h | 0 .../{stm32fx => stm32f4}/inc/cmsis_version.h | 0 board/{stm32fx => stm32f4}/inc/core_cm3.h | 0 board/{stm32fx => stm32f4}/inc/core_cm4.h | 0 board/{stm32fx => stm32f4}/inc/mpu_armv7.h | 0 board/{stm32fx => stm32f4}/inc/stm32f413xx.h | 0 board/{stm32fx => stm32f4}/inc/stm32f4xx.h | 0 .../inc/stm32f4xx_hal_def.h | 0 .../inc/stm32f4xx_hal_gpio_ex.h | 0 .../inc/system_stm32f4xx.h | 0 .../{stm32fx => stm32f4}/interrupt_handlers.h | 0 board/{stm32fx => stm32f4}/lladc.h | 0 board/{stm32fx => stm32f4}/llbxcan.h | 0 board/{stm32fx => stm32f4}/llexti.h | 0 board/{stm32fx => stm32f4}/llfan.h | 0 board/{stm32fx => stm32f4}/llflash.h | 0 board/{stm32fx => stm32f4}/llspi.h | 0 board/{stm32fx => stm32f4}/lluart.h | 0 board/{stm32fx => stm32f4}/llusb.h | 0 board/{stm32fx => stm32f4}/peripherals.h | 0 .../startup_stm32f413xx.s | 0 .../stm32f4_config.h} | 24 +++++++++---------- board/{stm32fx => stm32f4}/stm32f4_flash.ld | 0 tests/misra/test_mutation.py | 8 +++---- 30 files changed, 22 insertions(+), 22 deletions(-) rename board/jungle/{stm32fx => stm32f4}/board.h (100%) rename board/{stm32fx => stm32f4}/board.h (96%) rename board/{stm32fx => stm32f4}/clock.h (100%) rename board/{stm32fx => stm32f4}/inc/cmsis_compiler.h (100%) rename board/{stm32fx => stm32f4}/inc/cmsis_gcc.h (100%) rename board/{stm32fx => stm32f4}/inc/cmsis_version.h (100%) rename board/{stm32fx => stm32f4}/inc/core_cm3.h (100%) rename board/{stm32fx => stm32f4}/inc/core_cm4.h (100%) rename board/{stm32fx => stm32f4}/inc/mpu_armv7.h (100%) rename board/{stm32fx => stm32f4}/inc/stm32f413xx.h (100%) rename board/{stm32fx => stm32f4}/inc/stm32f4xx.h (100%) rename board/{stm32fx => stm32f4}/inc/stm32f4xx_hal_def.h (100%) rename board/{stm32fx => stm32f4}/inc/stm32f4xx_hal_gpio_ex.h (100%) rename board/{stm32fx => stm32f4}/inc/system_stm32f4xx.h (100%) rename board/{stm32fx => stm32f4}/interrupt_handlers.h (100%) rename board/{stm32fx => stm32f4}/lladc.h (100%) rename board/{stm32fx => stm32f4}/llbxcan.h (100%) rename board/{stm32fx => stm32f4}/llexti.h (100%) rename board/{stm32fx => stm32f4}/llfan.h (100%) rename board/{stm32fx => stm32f4}/llflash.h (100%) rename board/{stm32fx => stm32f4}/llspi.h (100%) rename board/{stm32fx => stm32f4}/lluart.h (100%) rename board/{stm32fx => stm32f4}/llusb.h (100%) rename board/{stm32fx => stm32f4}/peripherals.h (100%) rename board/{stm32fx => stm32f4}/startup_stm32f413xx.s (100%) rename board/{stm32fx/stm32fx_config.h => stm32f4/stm32f4_config.h} (82%) rename board/{stm32fx => stm32f4}/stm32f4_flash.ld (100%) diff --git a/SConscript b/SConscript index 357daba95..f44105fd2 100644 --- a/SConscript +++ b/SConscript @@ -84,7 +84,7 @@ def build_project(project_name, project, extra_flags): '..', panda_root, f"{panda_root}/board/", - f"{panda_root}/board/stm32fx/inc", + f"{panda_root}/board/stm32f4/inc", f"{panda_root}/board/stm32h7/inc", ] @@ -130,8 +130,8 @@ def build_project(project_name, project, extra_flags): base_project_f4 = { "MAIN": "main.c", - "STARTUP_FILE": File("./board/stm32fx/startup_stm32f413xx.s"), - "LINKER_SCRIPT": File("./board/stm32fx/stm32f4_flash.ld"), + "STARTUP_FILE": File("./board/stm32f4/startup_stm32f413xx.s"), + "LINKER_SCRIPT": File("./board/stm32f4/stm32f4_flash.ld"), "APP_START_ADDRESS": "0x8004000", "PROJECT_FLAGS": [ "-mcpu=cortex-m4", diff --git a/board/config.h b/board/config.h index 0adcc3e09..56703522b 100644 --- a/board/config.h +++ b/board/config.h @@ -37,7 +37,7 @@ #ifdef STM32H7 #include "stm32h7/stm32h7_config.h" #elif defined(STM32F4) - #include "stm32fx/stm32fx_config.h" + #include "stm32f4/stm32f4_config.h" #else // TODO: uncomment this, cppcheck complains // building for tests diff --git a/board/jungle/stm32fx/board.h b/board/jungle/stm32f4/board.h similarity index 100% rename from board/jungle/stm32fx/board.h rename to board/jungle/stm32f4/board.h diff --git a/board/stm32fx/board.h b/board/stm32f4/board.h similarity index 96% rename from board/stm32fx/board.h rename to board/stm32f4/board.h index 810361189..bf95d58ea 100644 --- a/board/stm32fx/board.h +++ b/board/stm32f4/board.h @@ -5,10 +5,10 @@ #include "boards/unused_funcs.h" // ///// Board definition and detection ///// // -#include "stm32fx/lladc.h" +#include "stm32f4/lladc.h" #include "drivers/harness.h" #include "drivers/fan.h" -#include "stm32fx/llfan.h" +#include "stm32f4/llfan.h" #include "drivers/clock_source.h" #include "boards/white.h" #include "boards/grey.h" diff --git a/board/stm32fx/clock.h b/board/stm32f4/clock.h similarity index 100% rename from board/stm32fx/clock.h rename to board/stm32f4/clock.h diff --git a/board/stm32fx/inc/cmsis_compiler.h b/board/stm32f4/inc/cmsis_compiler.h similarity index 100% rename from board/stm32fx/inc/cmsis_compiler.h rename to board/stm32f4/inc/cmsis_compiler.h diff --git a/board/stm32fx/inc/cmsis_gcc.h b/board/stm32f4/inc/cmsis_gcc.h similarity index 100% rename from board/stm32fx/inc/cmsis_gcc.h rename to board/stm32f4/inc/cmsis_gcc.h diff --git a/board/stm32fx/inc/cmsis_version.h b/board/stm32f4/inc/cmsis_version.h similarity index 100% rename from board/stm32fx/inc/cmsis_version.h rename to board/stm32f4/inc/cmsis_version.h diff --git a/board/stm32fx/inc/core_cm3.h b/board/stm32f4/inc/core_cm3.h similarity index 100% rename from board/stm32fx/inc/core_cm3.h rename to board/stm32f4/inc/core_cm3.h diff --git a/board/stm32fx/inc/core_cm4.h b/board/stm32f4/inc/core_cm4.h similarity index 100% rename from board/stm32fx/inc/core_cm4.h rename to board/stm32f4/inc/core_cm4.h diff --git a/board/stm32fx/inc/mpu_armv7.h b/board/stm32f4/inc/mpu_armv7.h similarity index 100% rename from board/stm32fx/inc/mpu_armv7.h rename to board/stm32f4/inc/mpu_armv7.h diff --git a/board/stm32fx/inc/stm32f413xx.h b/board/stm32f4/inc/stm32f413xx.h similarity index 100% rename from board/stm32fx/inc/stm32f413xx.h rename to board/stm32f4/inc/stm32f413xx.h diff --git a/board/stm32fx/inc/stm32f4xx.h b/board/stm32f4/inc/stm32f4xx.h similarity index 100% rename from board/stm32fx/inc/stm32f4xx.h rename to board/stm32f4/inc/stm32f4xx.h diff --git a/board/stm32fx/inc/stm32f4xx_hal_def.h b/board/stm32f4/inc/stm32f4xx_hal_def.h similarity index 100% rename from board/stm32fx/inc/stm32f4xx_hal_def.h rename to board/stm32f4/inc/stm32f4xx_hal_def.h diff --git a/board/stm32fx/inc/stm32f4xx_hal_gpio_ex.h b/board/stm32f4/inc/stm32f4xx_hal_gpio_ex.h similarity index 100% rename from board/stm32fx/inc/stm32f4xx_hal_gpio_ex.h rename to board/stm32f4/inc/stm32f4xx_hal_gpio_ex.h diff --git a/board/stm32fx/inc/system_stm32f4xx.h b/board/stm32f4/inc/system_stm32f4xx.h similarity index 100% rename from board/stm32fx/inc/system_stm32f4xx.h rename to board/stm32f4/inc/system_stm32f4xx.h diff --git a/board/stm32fx/interrupt_handlers.h b/board/stm32f4/interrupt_handlers.h similarity index 100% rename from board/stm32fx/interrupt_handlers.h rename to board/stm32f4/interrupt_handlers.h diff --git a/board/stm32fx/lladc.h b/board/stm32f4/lladc.h similarity index 100% rename from board/stm32fx/lladc.h rename to board/stm32f4/lladc.h diff --git a/board/stm32fx/llbxcan.h b/board/stm32f4/llbxcan.h similarity index 100% rename from board/stm32fx/llbxcan.h rename to board/stm32f4/llbxcan.h diff --git a/board/stm32fx/llexti.h b/board/stm32f4/llexti.h similarity index 100% rename from board/stm32fx/llexti.h rename to board/stm32f4/llexti.h diff --git a/board/stm32fx/llfan.h b/board/stm32f4/llfan.h similarity index 100% rename from board/stm32fx/llfan.h rename to board/stm32f4/llfan.h diff --git a/board/stm32fx/llflash.h b/board/stm32f4/llflash.h similarity index 100% rename from board/stm32fx/llflash.h rename to board/stm32f4/llflash.h diff --git a/board/stm32fx/llspi.h b/board/stm32f4/llspi.h similarity index 100% rename from board/stm32fx/llspi.h rename to board/stm32f4/llspi.h diff --git a/board/stm32fx/lluart.h b/board/stm32f4/lluart.h similarity index 100% rename from board/stm32fx/lluart.h rename to board/stm32f4/lluart.h diff --git a/board/stm32fx/llusb.h b/board/stm32f4/llusb.h similarity index 100% rename from board/stm32fx/llusb.h rename to board/stm32f4/llusb.h diff --git a/board/stm32fx/peripherals.h b/board/stm32f4/peripherals.h similarity index 100% rename from board/stm32fx/peripherals.h rename to board/stm32f4/peripherals.h diff --git a/board/stm32fx/startup_stm32f413xx.s b/board/stm32f4/startup_stm32f413xx.s similarity index 100% rename from board/stm32fx/startup_stm32f413xx.s rename to board/stm32f4/startup_stm32f413xx.s diff --git a/board/stm32fx/stm32fx_config.h b/board/stm32f4/stm32f4_config.h similarity index 82% rename from board/stm32fx/stm32fx_config.h rename to board/stm32f4/stm32f4_config.h index 8b59da28f..3c6e547c9 100644 --- a/board/stm32fx/stm32fx_config.h +++ b/board/stm32f4/stm32f4_config.h @@ -1,5 +1,5 @@ -#include "stm32fx/inc/stm32f4xx.h" -#include "stm32fx/inc/stm32f4xx_hal_gpio_ex.h" +#include "stm32f4/inc/stm32f4xx.h" +#include "stm32f4/inc/stm32f4xx_hal_gpio_ex.h" #define MCU_IDCODE 0x463U // from the linker script @@ -50,32 +50,32 @@ #include "drivers/registers.h" #include "drivers/interrupts.h" #include "drivers/gpio.h" -#include "stm32fx/peripherals.h" -#include "stm32fx/interrupt_handlers.h" +#include "stm32f4/peripherals.h" +#include "stm32f4/interrupt_handlers.h" #include "drivers/timers.h" -#include "stm32fx/board.h" -#include "stm32fx/clock.h" +#include "stm32f4/board.h" +#include "stm32f4/clock.h" #include "drivers/watchdog.h" #include "drivers/spi.h" -#include "stm32fx/llspi.h" +#include "stm32f4/llspi.h" #if !defined(BOOTSTUB) #include "drivers/uart.h" - #include "stm32fx/lluart.h" + #include "stm32f4/lluart.h" #endif #if defined(PANDA) && !defined(BOOTSTUB) - #include "stm32fx/llexti.h" + #include "stm32f4/llexti.h" #endif #ifdef BOOTSTUB - #include "stm32fx/llflash.h" + #include "stm32f4/llflash.h" #else - #include "stm32fx/llbxcan.h" + #include "stm32f4/llbxcan.h" #endif -#include "stm32fx/llusb.h" +#include "stm32f4/llusb.h" void early_gpio_float(void) { RCC->AHB1ENR = RCC_AHB1ENR_GPIOAEN | RCC_AHB1ENR_GPIOBEN | RCC_AHB1ENR_GPIOCEN; diff --git a/board/stm32fx/stm32f4_flash.ld b/board/stm32f4/stm32f4_flash.ld similarity index 100% rename from board/stm32fx/stm32f4_flash.ld rename to board/stm32f4/stm32f4_flash.ld diff --git a/tests/misra/test_mutation.py b/tests/misra/test_mutation.py index cc3666f13..9e778e88b 100755 --- a/tests/misra/test_mutation.py +++ b/tests/misra/test_mutation.py @@ -14,21 +14,21 @@ IGNORED_PATHS = ( 'board/obj', 'board/jungle', 'board/stm32h7/inc', - 'board/stm32fx/inc', + 'board/stm32f4/inc', 'board/fake_stm.h', # bootstub only files 'board/flasher.h', 'board/bootstub.c', 'board/bootstub_declarations.h', - 'board/stm32fx/llflash.h' + 'board/stm32f4/llflash.h' ) mutations = [ # default (None, None, False), # F4 only - ("board/stm32fx/llbxcan.h", "s/1U/1/g", True), + ("board/stm32f4/llbxcan.h", "s/1U/1/g", True), # H7 only ("board/stm32h7/llfdcan.h", "s/return ret;/if (true) { return ret; } else { return false; }/g", True), # general safety @@ -60,7 +60,7 @@ patterns = [ all_files = glob.glob('board/**', root_dir=ROOT, recursive=True) files = [f for f in all_files if f.endswith(('.c', '.h')) and not f.startswith(IGNORED_PATHS)] -assert len(files) > 70, all(d in files for d in ('board/main.c', 'board/stm32fx/llbxcan.h', 'board/stm32h7/llfdcan.h', 'board/safety/safety_toyota.h')) +assert len(files) > 70, all(d in files for d in ('board/main.c', 'board/stm32f4/llbxcan.h', 'board/stm32h7/llfdcan.h', 'board/safety/safety_toyota.h')) for p in patterns: mutations.append((random.choice(files), p, True)) From 15dac19827ad003c095e43d949254749944a491a Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Wed, 13 Mar 2024 14:51:40 -0700 Subject: [PATCH 40/67] fix bootkick test, no more datetime (#1901) * fix bootkick test, no more datetime * debug * try that --- tests/som/on-device.py | 4 ++-- tests/som/test_bootkick.py | 5 ++--- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/tests/som/on-device.py b/tests/som/on-device.py index f88d5a99b..421271d6a 100755 --- a/tests/som/on-device.py +++ b/tests/som/on-device.py @@ -16,8 +16,8 @@ if __name__ == "__main__": flag_set = True # shutdown when told - dt = p.get_datetime() - if dt.year == 2040 and dt.month == 8: + ch = p.can_health(0) + if ch['can_data_speed'] == 1000: os.system("sudo poweroff") except Exception as e: print(str(e)) diff --git a/tests/som/test_bootkick.py b/tests/som/test_bootkick.py index 6c08e1a84..98d3f95b8 100644 --- a/tests/som/test_bootkick.py +++ b/tests/som/test_bootkick.py @@ -1,6 +1,5 @@ import time import pytest -import datetime from panda import Panda, PandaJungle @@ -19,7 +18,7 @@ def pj(): yield jungle - jungle.set_panda_power(False) + #jungle.set_panda_power(False) jungle.close() @pytest.fixture(scope="function") @@ -86,7 +85,7 @@ def check_som_boot_flag(panda): return h['safety_mode'] == Panda.SAFETY_ELM327 and h['safety_param'] == 30 def set_som_shutdown_flag(panda): - panda.set_datetime(datetime.datetime(year=2040, month=8, day=23)) + panda.set_can_data_speed_kbps(0, 1000) def wait_for_boot(panda, jungle, reset_expected=False, bootkick=False, timeout=120): st = time.monotonic() From b1d988933e35ca3a3c41ca42ee89e3643d17d41e Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Sun, 17 Mar 2024 16:51:57 -0700 Subject: [PATCH 41/67] pre-commit: autoupdate hooks (#1899) Update pre-commit hook versions Co-authored-by: adeebshihadeh --- .pre-commit-config.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 402bdc3a1..2144d3553 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -9,12 +9,12 @@ repos: - id: check-executables-have-shebangs - id: check-shebang-scripts-are-executable - repo: https://github.com/pre-commit/mirrors-mypy - rev: v1.8.0 + rev: v1.9.0 hooks: - id: mypy 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.3.0 + rev: v0.3.2 hooks: - id: ruff From 567dbfe6d86ddda6d803da371942603c6dbe36c8 Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Sun, 17 Mar 2024 22:22:46 -0700 Subject: [PATCH 42/67] remove comma pedal (#1902) --- board/safety.h | 6 --- board/safety/safety_honda.h | 71 ++++---------------------- board/safety/safety_toyota.h | 73 ++------------------------- board/safety_declarations.h | 3 -- python/__init__.py | 2 - tests/libpanda/safety_helpers.h | 4 -- tests/libpanda/safety_helpers.py | 2 - tests/safety/common.py | 85 -------------------------------- tests/safety/test_honda.py | 44 ----------------- tests/safety/test_toyota.py | 39 --------------- 10 files changed, 14 insertions(+), 315 deletions(-) diff --git a/board/safety.h b/board/safety.h index 1e9524409..048d7cca4 100644 --- a/board/safety.h +++ b/board/safety.h @@ -327,8 +327,6 @@ int set_safety_hooks(uint16_t mode, uint16_t param) { // reset state set by safety mode safety_mode_cnt = 0U; relay_malfunction = false; - enable_gas_interceptor = false; - gas_interceptor_prev = 0; gas_pressed = false; gas_pressed_prev = false; brake_pressed = false; @@ -543,10 +541,6 @@ bool longitudinal_brake_checks(int desired_brake, const LongitudinalLimits limit return violation; } -bool longitudinal_interceptor_checks(const CANPacket_t *to_send) { - return !get_longitudinal_allowed() && (GET_BYTE(to_send, 0) || GET_BYTE(to_send, 1)); -} - // Safety checks for torque-based steering commands bool steer_torque_cmd_checks(int desired_torque, int steer_req, const SteeringLimits limits) { bool violation = false; diff --git a/board/safety/safety_honda.h b/board/safety/safety_honda.h index 78bbb7f0b..3c93ab9d1 100644 --- a/board/safety/safety_honda.h +++ b/board/safety/safety_honda.h @@ -1,16 +1,9 @@ const CanMsg HONDA_N_TX_MSGS[] = {{0xE4, 0, 5}, {0x194, 0, 4}, {0x1FA, 0, 8}, {0x30C, 0, 8}, {0x33D, 0, 5}}; -const CanMsg HONDA_N_INTERCEPTOR_TX_MSGS[] = {{0xE4, 0, 5}, {0x194, 0, 4}, {0x1FA, 0, 8}, {0x200, 0, 6}, {0x30C, 0, 8}, {0x33D, 0, 5}}; const CanMsg HONDA_BOSCH_TX_MSGS[] = {{0xE4, 0, 5}, {0xE5, 0, 8}, {0x296, 1, 4}, {0x33D, 0, 5}, {0x33DA, 0, 5}, {0x33DB, 0, 8}}; // Bosch const CanMsg HONDA_BOSCH_LONG_TX_MSGS[] = {{0xE4, 1, 5}, {0x1DF, 1, 8}, {0x1EF, 1, 8}, {0x1FA, 1, 8}, {0x30C, 1, 8}, {0x33D, 1, 5}, {0x33DA, 1, 5}, {0x33DB, 1, 8}, {0x39F, 1, 8}, {0x18DAB0F1, 1, 8}}; // Bosch w/ gas and brakes const CanMsg HONDA_RADARLESS_TX_MSGS[] = {{0xE4, 0, 5}, {0x296, 2, 4}, {0x33D, 0, 8}}; // Bosch radarless const CanMsg HONDA_RADARLESS_LONG_TX_MSGS[] = {{0xE4, 0, 5}, {0x33D, 0, 8}, {0x1C8, 0, 8}, {0x30C, 0, 8}}; // Bosch radarless w/ gas and brakes -// panda interceptor threshold needs to be equivalent to openpilot threshold to avoid controls mismatches -// If thresholds are mismatched then it is possible for panda to see the gas fall and rise while openpilot is in the pre-enabled state -// Threshold calculated from DBC gains: round(((83.3 / 0.253984064) + (83.3 / 0.126992032)) / 2) = 492 -const int HONDA_GAS_INTERCEPTOR_THRESHOLD = 492; -#define HONDA_GET_INTERCEPTOR(msg) (((GET_BYTE((msg), 0) << 8) + GET_BYTE((msg), 1) + (GET_BYTE((msg), 2) << 8) + GET_BYTE((msg), 3)) / 2U) // avg between 2 tracks - const LongitudinalLimits HONDA_BOSCH_LONG_LIMITS = { .max_accel = 200, // accel is used for brakes .min_accel = -350, @@ -47,11 +40,6 @@ RxCheck honda_common_rx_checks[] = { HONDA_COMMON_RX_CHECKS(0) }; -RxCheck honda_common_interceptor_rx_checks[] = { - HONDA_COMMON_RX_CHECKS(0) - {.msg = {{0x201, 0, 6, .check_checksum = false, .max_counter = 15U, .frequency = 50U}, { 0 }, { 0 }}}, -}; - RxCheck honda_common_alt_brake_rx_checks[] = { HONDA_COMMON_RX_CHECKS(0) HONDA_ALT_BRAKE_ADDR_CHECK(0) @@ -62,11 +50,6 @@ RxCheck honda_nidec_alt_rx_checks[] = { HONDA_COMMON_NO_SCM_FEEDBACK_RX_CHECKS(0) }; -RxCheck honda_nidec_alt_interceptor_rx_checks[] = { - HONDA_COMMON_NO_SCM_FEEDBACK_RX_CHECKS(0) - {.msg = {{0x201, 0, 6, .check_checksum = false, .max_counter = 15U, .frequency = 50U}, { 0 }, { 0 }}}, -}; - // Bosch has pt on bus 1, verified 0x1A6 does not exist RxCheck honda_bosch_rx_checks[] = { HONDA_COMMON_RX_CHECKS(1) @@ -81,7 +64,6 @@ const uint16_t HONDA_PARAM_ALT_BRAKE = 1; const uint16_t HONDA_PARAM_BOSCH_LONG = 2; const uint16_t HONDA_PARAM_NIDEC_ALT = 4; const uint16_t HONDA_PARAM_RADARLESS = 8; -const uint16_t HONDA_PARAM_GAS_INTERCEPTOR = 16; enum { HONDA_BTN_NONE = 0, @@ -127,26 +109,15 @@ static uint32_t honda_compute_checksum(const CANPacket_t *to_push) { } static uint8_t honda_get_counter(const CANPacket_t *to_push) { - int addr = GET_ADDR(to_push); - - uint8_t cnt = 0U; - if (addr == 0x201) { - // Signal: COUNTER_PEDAL - cnt = GET_BYTE(to_push, 4) & 0x0FU; - } else { - int counter_byte = GET_LEN(to_push) - 1U; - cnt = (GET_BYTE(to_push, counter_byte) >> 4U) & 0x3U; - } - return cnt; + int counter_byte = GET_LEN(to_push) - 1U; + return (GET_BYTE(to_push, counter_byte) >> 4U) & 0x3U; } static void honda_rx_hook(const CANPacket_t *to_push) { - const bool pcm_cruise = ((honda_hw == HONDA_BOSCH) && !honda_bosch_long) || \ - ((honda_hw == HONDA_NIDEC) && !enable_gas_interceptor); + const bool pcm_cruise = ((honda_hw == HONDA_BOSCH) && !honda_bosch_long) || (honda_hw == HONDA_NIDEC); int pt_bus = honda_get_pt_bus(); int addr = GET_ADDR(to_push); - int len = GET_LEN(to_push); int bus = GET_BUS(to_push); // sample speed @@ -218,17 +189,8 @@ static void honda_rx_hook(const CANPacket_t *to_push) { } } - // length check because bosch hardware also uses this id (0x201 w/ len = 8) - if ((addr == 0x201) && (len == 6) && enable_gas_interceptor) { - int gas_interceptor = HONDA_GET_INTERCEPTOR(to_push); - gas_pressed = gas_interceptor > HONDA_GAS_INTERCEPTOR_THRESHOLD; - gas_interceptor_prev = gas_interceptor; - } - - if (!enable_gas_interceptor) { - if (addr == 0x17C) { - gas_pressed = GET_BYTE(to_push, 0) != 0U; - } + if (addr == 0x17C) { + gas_pressed = GET_BYTE(to_push, 0) != 0U; } // disable stock Honda AEB in alternative experience @@ -346,13 +308,6 @@ static bool honda_tx_hook(const CANPacket_t *to_send) { } } - // GAS: safety check (interceptor) - if (addr == 0x200) { - if (longitudinal_interceptor_checks(to_send)) { - tx = false; - } - } - // FORCE CANCEL: safety check only relevant when spamming the cancel button in Bosch HW // ensuring that only the cancel button press is sent (VAL 2) when controls are off. // This avoids unintended engagements while still allowing resume spam @@ -380,24 +335,18 @@ static safety_config honda_nidec_init(uint16_t param) { honda_alt_brake_msg = false; honda_bosch_long = false; honda_bosch_radarless = false; - 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) : \ - SET_RX_CHECKS(honda_nidec_alt_rx_checks, ret); - } else { - enable_gas_interceptor ? SET_RX_CHECKS(honda_common_interceptor_rx_checks, ret) : \ - SET_RX_CHECKS(honda_common_rx_checks, ret); - } - if (enable_gas_interceptor) { - SET_TX_MSGS(HONDA_N_INTERCEPTOR_TX_MSGS, ret); + if (enable_nidec_alt) { + SET_RX_CHECKS(honda_nidec_alt_rx_checks, ret); } else { - SET_TX_MSGS(HONDA_N_TX_MSGS, ret); + SET_RX_CHECKS(honda_common_rx_checks, ret); } + SET_TX_MSGS(HONDA_N_TX_MSGS, ret); + return ret; } diff --git a/board/safety/safety_toyota.h b/board/safety/safety_toyota.h index 50c00b38a..05f84e460 100644 --- a/board/safety/safety_toyota.h +++ b/board/safety/safety_toyota.h @@ -37,12 +37,6 @@ const LongitudinalLimits TOYOTA_LONG_LIMITS = { .min_accel = -3500, // -3.5 m/s2 }; -// panda interceptor threshold needs to be equivalent to openpilot threshold to avoid controls mismatches -// If thresholds are mismatched then it is possible for panda to see the gas fall and rise while openpilot is in the pre-enabled state -// Threshold calculated from DBC gains: round((((15 + 75.555) / 0.159375) + ((15 + 151.111) / 0.159375)) / 2) = 805 -const int TOYOTA_GAS_INTERCEPTOR_THRSLD = 805; -#define TOYOTA_GET_INTERCEPTOR(msg) (((GET_BYTE((msg), 0) << 8) + GET_BYTE((msg), 1) + (GET_BYTE((msg), 2) << 8) + GET_BYTE((msg), 3)) / 2U) // avg between 2 tracks - // Stock longitudinal #define TOYOTA_COMMON_TX_MSGS \ {0x2E4, 0, 5}, {0x191, 0, 8}, {0x412, 0, 8}, {0x343, 0, 8}, {0x1D2, 0, 8}, /* LKAS + LTA + ACC & PCM cancel cmds */ \ @@ -62,11 +56,6 @@ const CanMsg TOYOTA_LONG_TX_MSGS[] = { TOYOTA_COMMON_LONG_TX_MSGS }; -const CanMsg TOYOTA_INTERCEPTOR_TX_MSGS[] = { - TOYOTA_COMMON_LONG_TX_MSGS - {0x200, 0, 6}, // gas interceptor -}; - #define TOYOTA_COMMON_RX_CHECKS(lta) \ {.msg = {{ 0xaa, 0, 8, .check_checksum = false, .frequency = 83U}, { 0 }, { 0 }}}, \ {.msg = {{0x260, 0, 8, .check_checksum = true, .quality_flag = (lta), .frequency = 50U}, { 0 }, { 0 }}}, \ @@ -78,21 +67,11 @@ RxCheck toyota_lka_rx_checks[] = { TOYOTA_COMMON_RX_CHECKS(false) }; -RxCheck toyota_lka_interceptor_rx_checks[] = { - TOYOTA_COMMON_RX_CHECKS(false) - {.msg = {{0x201, 0, 6, .check_checksum = false, .max_counter = 15U, .frequency = 50U}, { 0 }, { 0 }}}, -}; - // Check the quality flag for angle measurement when using LTA, since it's not set on TSS-P cars RxCheck toyota_lta_rx_checks[] = { TOYOTA_COMMON_RX_CHECKS(true) }; -RxCheck toyota_lta_interceptor_rx_checks[] = { - TOYOTA_COMMON_RX_CHECKS(true) - {.msg = {{0x201, 0, 6, .check_checksum = false, .max_counter = 15U, .frequency = 50U}, { 0 }, { 0 }}}, -}; - // safety param flags // first byte is for EPS factor, second is for flags const uint32_t TOYOTA_PARAM_OFFSET = 8U; @@ -100,7 +79,6 @@ const uint32_t TOYOTA_EPS_FACTOR = (1UL << TOYOTA_PARAM_OFFSET) - 1U; const uint32_t TOYOTA_PARAM_ALT_BRAKE = 1UL << TOYOTA_PARAM_OFFSET; const uint32_t TOYOTA_PARAM_STOCK_LONGITUDINAL = 2UL << TOYOTA_PARAM_OFFSET; const uint32_t TOYOTA_PARAM_LTA = 4UL << TOYOTA_PARAM_OFFSET; -const uint32_t TOYOTA_PARAM_GAS_INTERCEPTOR = 8UL << TOYOTA_PARAM_OFFSET; bool toyota_alt_brake = false; bool toyota_stock_longitudinal = false; @@ -122,17 +100,6 @@ static uint32_t toyota_get_checksum(const CANPacket_t *to_push) { return (uint8_t)(GET_BYTE(to_push, checksum_byte)); } -static uint8_t toyota_get_counter(const CANPacket_t *to_push) { - int addr = GET_ADDR(to_push); - - uint8_t cnt = 0U; - if (addr == 0x201) { - // Signal: COUNTER_PEDAL - cnt = GET_BYTE(to_push, 4) & 0x0FU; - } - return cnt; -} - static bool toyota_get_quality_flag_valid(const CANPacket_t *to_push) { int addr = GET_ADDR(to_push); @@ -185,9 +152,7 @@ static void toyota_rx_hook(const CANPacket_t *to_push) { pcm_cruise_check(cruise_engaged); // sample gas pedal - if (!enable_gas_interceptor) { - gas_pressed = !GET_BIT(to_push, 4U); - } + gas_pressed = !GET_BIT(to_push, 4U); } // sample speed @@ -210,15 +175,6 @@ static void toyota_rx_hook(const CANPacket_t *to_push) { brake_pressed = GET_BIT(to_push, bit); } - // sample gas interceptor - if ((addr == 0x201) && enable_gas_interceptor) { - int gas_interceptor = TOYOTA_GET_INTERCEPTOR(to_push); - gas_pressed = gas_interceptor > TOYOTA_GAS_INTERCEPTOR_THRSLD; - - // TODO: remove this, only left in for gas_interceptor_prev test - gas_interceptor_prev = gas_interceptor; - } - bool stock_ecu_detected = addr == 0x2E4; // STEERING_LKA if (!toyota_stock_longitudinal && (addr == 0x343)) { stock_ecu_detected = true; // ACC_CONTROL @@ -234,14 +190,6 @@ static bool toyota_tx_hook(const CANPacket_t *to_send) { // Check if msg is sent on BUS 0 if (bus == 0) { - - // GAS PEDAL: safety check - if (addr == 0x200) { - if (longitudinal_interceptor_checks(to_send)) { - tx = false; - } - } - // ACCEL: safety check on byte 1-2 if (addr == 0x343) { int desired_accel = (GET_BYTE(to_send, 0) << 8) | GET_BYTE(to_send, 1); @@ -357,29 +305,17 @@ static safety_config toyota_init(uint16_t param) { toyota_alt_brake = GET_FLAG(param, TOYOTA_PARAM_ALT_BRAKE); toyota_stock_longitudinal = GET_FLAG(param, TOYOTA_PARAM_STOCK_LONGITUDINAL); toyota_lta = GET_FLAG(param, TOYOTA_PARAM_LTA); - enable_gas_interceptor = GET_FLAG(param, TOYOTA_PARAM_GAS_INTERCEPTOR); toyota_dbc_eps_torque_factor = param & TOYOTA_EPS_FACTOR; - // Gas interceptor should not be used if openpilot is not controlling longitudinal - if (toyota_stock_longitudinal) { - enable_gas_interceptor = false; - } - safety_config ret; if (toyota_stock_longitudinal) { SET_TX_MSGS(TOYOTA_TX_MSGS, ret); } else { - enable_gas_interceptor ? SET_TX_MSGS(TOYOTA_INTERCEPTOR_TX_MSGS, ret) : \ - SET_TX_MSGS(TOYOTA_LONG_TX_MSGS, ret); + SET_TX_MSGS(TOYOTA_LONG_TX_MSGS, ret); } - if (enable_gas_interceptor) { - toyota_lta ? SET_RX_CHECKS(toyota_lta_interceptor_rx_checks, ret) : \ - SET_RX_CHECKS(toyota_lka_interceptor_rx_checks, ret); - } else { - toyota_lta ? SET_RX_CHECKS(toyota_lta_rx_checks, ret) : \ - SET_RX_CHECKS(toyota_lka_rx_checks, ret); - } + toyota_lta ? SET_RX_CHECKS(toyota_lta_rx_checks, ret) : \ + SET_RX_CHECKS(toyota_lka_rx_checks, ret); return ret; } @@ -413,6 +349,5 @@ const safety_hooks toyota_hooks = { .fwd = toyota_fwd_hook, .get_checksum = toyota_get_checksum, .compute_checksum = toyota_compute_checksum, - .get_counter = toyota_get_counter, .get_quality_flag_valid = toyota_get_quality_flag_valid, }; diff --git a/board/safety_declarations.h b/board/safety_declarations.h index 64b55f203..4140f56e3 100644 --- a/board/safety_declarations.h +++ b/board/safety_declarations.h @@ -203,7 +203,6 @@ bool longitudinal_speed_checks(int desired_speed, const LongitudinalLimits limit bool longitudinal_gas_checks(int desired_gas, const LongitudinalLimits limits); bool longitudinal_transmission_rpm_checks(int desired_transmission_rpm, const LongitudinalLimits limits); bool longitudinal_brake_checks(int desired_brake, const LongitudinalLimits limits); -bool longitudinal_interceptor_checks(const CANPacket_t *to_send); void pcm_cruise_check(bool cruise_engaged); void safety_tick(const safety_config *safety_config); @@ -211,8 +210,6 @@ void safety_tick(const safety_config *safety_config); // This can be set by the safety hooks bool controls_allowed = false; bool relay_malfunction = false; -bool enable_gas_interceptor = false; -int gas_interceptor_prev = 0; bool gas_pressed = false; bool gas_pressed_prev = false; bool brake_pressed = false; diff --git a/python/__init__.py b/python/__init__.py index 063602f4d..97c967f22 100644 --- a/python/__init__.py +++ b/python/__init__.py @@ -194,13 +194,11 @@ class Panda: FLAG_TOYOTA_ALT_BRAKE = (1 << 8) FLAG_TOYOTA_STOCK_LONGITUDINAL = (2 << 8) FLAG_TOYOTA_LTA = (4 << 8) - FLAG_TOYOTA_GAS_INTERCEPTOR = (8 << 8) FLAG_HONDA_ALT_BRAKE = 1 FLAG_HONDA_BOSCH_LONG = 2 FLAG_HONDA_NIDEC_ALT = 4 FLAG_HONDA_RADARLESS = 8 - FLAG_HONDA_GAS_INTERCEPTOR = 16 FLAG_HYUNDAI_EV_GAS = 1 FLAG_HYUNDAI_HYBRID_GAS = 2 diff --git a/tests/libpanda/safety_helpers.h b/tests/libpanda/safety_helpers.h index 074463d31..36887c896 100644 --- a/tests/libpanda/safety_helpers.h +++ b/tests/libpanda/safety_helpers.h @@ -43,10 +43,6 @@ bool get_relay_malfunction(void){ return relay_malfunction; } -int get_gas_interceptor_prev(void){ - return gas_interceptor_prev; -} - bool get_gas_pressed_prev(void){ return gas_pressed_prev; } diff --git a/tests/libpanda/safety_helpers.py b/tests/libpanda/safety_helpers.py index 28f3349dc..ea41264ae 100644 --- a/tests/libpanda/safety_helpers.py +++ b/tests/libpanda/safety_helpers.py @@ -10,7 +10,6 @@ def setup_safety_helpers(ffi): int get_alternative_experience(void); void set_relay_malfunction(bool c); bool get_relay_malfunction(void); - int get_gas_interceptor_prev(void); bool get_gas_pressed_prev(void); bool get_brake_pressed_prev(void); bool get_regen_braking_prev(void); @@ -61,7 +60,6 @@ class PandaSafety(Protocol): def get_alternative_experience(self) -> int: ... def set_relay_malfunction(self, c: bool) -> None: ... def get_relay_malfunction(self) -> bool: ... - def get_gas_interceptor_prev(self) -> int: ... def get_gas_pressed_prev(self) -> bool: ... def get_brake_pressed_prev(self) -> bool: ... def get_regen_braking_prev(self) -> bool: ... diff --git a/tests/safety/common.py b/tests/safety/common.py index a3c22dffb..8179cff1f 100644 --- a/tests/safety/common.py +++ b/tests/safety/common.py @@ -118,91 +118,6 @@ class PandaSafetyTestBase(unittest.TestCase): self.assertEqual(meas_max_func(), 0) -class GasInterceptorSafetyTest(PandaSafetyTestBase): - - INTERCEPTOR_THRESHOLD = 0 - - cnt_gas_cmd = 0 - cnt_user_gas = 0 - - packer: CANPackerPanda - - @classmethod - def setUpClass(cls): - if cls.__name__ == "GasInterceptorSafetyTest" or cls.__name__.endswith("Base"): - cls.safety = None - raise unittest.SkipTest - - def _interceptor_gas_cmd(self, gas: int): - values: dict[str, float | int] = {"COUNTER_PEDAL": self.__class__.cnt_gas_cmd & 0xF} - if gas > 0: - values["GAS_COMMAND"] = gas * 255. - values["GAS_COMMAND2"] = gas * 255. - self.__class__.cnt_gas_cmd += 1 - return self.packer.make_can_msg_panda("GAS_COMMAND", 0, values) - - def _interceptor_user_gas(self, gas: int): - values = {"INTERCEPTOR_GAS": gas, "INTERCEPTOR_GAS2": gas, - "COUNTER_PEDAL": self.__class__.cnt_user_gas} - self.__class__.cnt_user_gas += 1 - return self.packer.make_can_msg_panda("GAS_SENSOR", 0, values) - - # Skip non-interceptor user gas tests - def test_prev_gas(self): - pass - - def test_disengage_on_gas(self): - pass - - def test_alternative_experience_no_disengage_on_gas(self): - pass - - def test_prev_gas_interceptor(self): - self._rx(self._interceptor_user_gas(0x0)) - self.assertFalse(self.safety.get_gas_interceptor_prev()) - self._rx(self._interceptor_user_gas(0x1000)) - self.assertTrue(self.safety.get_gas_interceptor_prev()) - self._rx(self._interceptor_user_gas(0x0)) - - def test_disengage_on_gas_interceptor(self): - for g in range(0x1000): - self._rx(self._interceptor_user_gas(0)) - self.safety.set_controls_allowed(True) - self._rx(self._interceptor_user_gas(g)) - remain_enabled = g <= self.INTERCEPTOR_THRESHOLD - self.assertEqual(remain_enabled, self.safety.get_controls_allowed()) - self._rx(self._interceptor_user_gas(0)) - - def test_alternative_experience_no_disengage_on_gas_interceptor(self): - self.safety.set_controls_allowed(True) - self.safety.set_alternative_experience(ALTERNATIVE_EXPERIENCE.DISABLE_DISENGAGE_ON_GAS) - for g in range(0x1000): - self._rx(self._interceptor_user_gas(g)) - # Test we allow lateral, but not longitudinal - self.assertTrue(self.safety.get_controls_allowed()) - self.assertEqual(g <= self.INTERCEPTOR_THRESHOLD, self.safety.get_longitudinal_allowed()) - # Make sure we can re-gain longitudinal actuation - self._rx(self._interceptor_user_gas(0)) - self.assertTrue(self.safety.get_longitudinal_allowed()) - - def test_allow_engage_with_gas_interceptor_pressed(self): - self._rx(self._interceptor_user_gas(0x1000)) - self.safety.set_controls_allowed(1) - self._rx(self._interceptor_user_gas(0x1000)) - self.assertTrue(self.safety.get_controls_allowed()) - self._rx(self._interceptor_user_gas(0)) - - def test_gas_interceptor_safety_check(self): - for gas in np.arange(0, 4000, 100): - for controls_allowed in [True, False]: - self.safety.set_controls_allowed(controls_allowed) - if controls_allowed: - send = True - else: - send = gas == 0 - self.assertEqual(send, self._tx(self._interceptor_gas_cmd(gas))) - - class LongitudinalAccelSafetyTest(PandaSafetyTestBase, abc.ABC): MAX_ACCEL: float = 2.0 diff --git a/tests/safety/test_honda.py b/tests/safety/test_honda.py index 45f190c36..082199c02 100755 --- a/tests/safety/test_honda.py +++ b/tests/safety/test_honda.py @@ -24,8 +24,6 @@ HONDA_BOSCH = 1 # * Nidec # * normal (PCM-enable) # * alt SCM messages (PCM-enable) -# * gas interceptor (button-enable) -# * gas interceptor with alt SCM messages (button-enable) # * Bosch # * Bosch with Longitudinal Support # * Bosch Radarless @@ -352,21 +350,6 @@ class TestHondaNidecPcmSafety(HondaPcmEnableBase, TestHondaNidecSafetyBase): pass -class TestHondaNidecGasInterceptorSafety(common.GasInterceptorSafetyTest, HondaButtonEnableBase, TestHondaNidecSafetyBase): - """ - Covers the Honda Nidec safety mode with a gas interceptor, switches to a button-enable car - """ - - TX_MSGS = HONDA_N_COMMON_TX_MSGS + [[0x200, 0]] - INTERCEPTOR_THRESHOLD = 492 - - def setUp(self): - self.packer = CANPackerPanda("honda_civic_touring_2016_can_generated") - self.safety = libpanda_py.libpanda - self.safety.set_safety_hooks(Panda.SAFETY_HONDA_NIDEC, Panda.FLAG_HONDA_GAS_INTERCEPTOR) - self.safety.init_tests() - - class TestHondaNidecPcmAltSafety(TestHondaNidecPcmSafety): """ Covers the Honda Nidec safety mode with alt SCM messages @@ -389,33 +372,6 @@ class TestHondaNidecPcmAltSafety(TestHondaNidecPcmSafety): return self.packer.make_can_msg_panda("SCM_BUTTONS", bus, values) -class TestHondaNidecAltGasInterceptorSafety(common.GasInterceptorSafetyTest, HondaButtonEnableBase, TestHondaNidecSafetyBase): - """ - Covers the Honda Nidec safety mode with alt SCM messages and gas interceptor, switches to a button-enable car - """ - - TX_MSGS = HONDA_N_COMMON_TX_MSGS + [[0x200, 0]] - INTERCEPTOR_THRESHOLD = 492 - - def setUp(self): - self.packer = CANPackerPanda("acura_ilx_2016_can_generated") - self.safety = libpanda_py.libpanda - self.safety.set_safety_hooks(Panda.SAFETY_HONDA_NIDEC, Panda.FLAG_HONDA_NIDEC_ALT | Panda.FLAG_HONDA_GAS_INTERCEPTOR) - self.safety.init_tests() - - def _acc_state_msg(self, main_on): - values = {"MAIN_ON": main_on, "COUNTER": self.cnt_acc_state % 4} - self.__class__.cnt_acc_state += 1 - return self.packer.make_can_msg_panda("SCM_BUTTONS", self.PT_BUS, values) - - def _button_msg(self, buttons, main_on=False, bus=None): - bus = self.PT_BUS if bus is None else bus - values = {"CRUISE_BUTTONS": buttons, "MAIN_ON": main_on, "COUNTER": self.cnt_button % 4} - self.__class__.cnt_button += 1 - return self.packer.make_can_msg_panda("SCM_BUTTONS", bus, values) - - - # ********************* Honda Bosch ********************** diff --git a/tests/safety/test_toyota.py b/tests/safety/test_toyota.py index 0743c67e8..80bf9ce9a 100755 --- a/tests/safety/test_toyota.py +++ b/tests/safety/test_toyota.py @@ -14,7 +14,6 @@ TOYOTA_COMMON_LONG_TX_MSGS = [[0x283, 0], [0x2E6, 0], [0x2E7, 0], [0x33E, 0], [0 [0x128, 1], [0x141, 1], [0x160, 1], [0x161, 1], [0x470, 1], # DSU bus 1 [0x411, 0], # PCS_HUD [0x750, 0]] # radar diagnostic address -GAS_INTERCEPTOR_TX_MSGS = [[0x200, 0]] class TestToyotaSafetyBase(common.PandaCarSafetyTest, common.LongitudinalAccelSafetyTest): @@ -127,32 +126,6 @@ class TestToyotaSafetyBase(common.PandaCarSafetyTest, common.LongitudinalAccelSa self.assertFalse(self.safety.get_controls_allowed()) -class TestToyotaSafetyGasInterceptorBase(common.GasInterceptorSafetyTest, TestToyotaSafetyBase): - - TX_MSGS = TOYOTA_COMMON_TX_MSGS + TOYOTA_COMMON_LONG_TX_MSGS + GAS_INTERCEPTOR_TX_MSGS - INTERCEPTOR_THRESHOLD = 805 - - def setUp(self): - super().setUp() - self.safety.set_safety_hooks(Panda.SAFETY_TOYOTA, self.safety.get_current_safety_param() | - Panda.FLAG_TOYOTA_GAS_INTERCEPTOR) - self.safety.init_tests() - - def test_stock_longitudinal(self): - # If stock longitudinal is set, the gas interceptor safety param should not be respected - self.safety.set_safety_hooks(Panda.SAFETY_TOYOTA, self.safety.get_current_safety_param() | - Panda.FLAG_TOYOTA_STOCK_LONGITUDINAL) - self.safety.init_tests() - - # Spot check a few gas interceptor tests: (1) reading interceptor, - # (2) behavior around interceptor, and (3) txing interceptor msgs - for test in (self.test_prev_gas_interceptor, self.test_disengage_on_gas_interceptor, - self.test_gas_interceptor_safety_check): - with self.subTest(test=test.__name__): - with self.assertRaises(AssertionError): - test() - - class TestToyotaSafetyTorque(TestToyotaSafetyBase, common.MotorTorqueSteeringSafetyTest, common.SteerRequestCutSafetyTest): MAX_RATE_UP = 15 @@ -175,10 +148,6 @@ class TestToyotaSafetyTorque(TestToyotaSafetyBase, common.MotorTorqueSteeringSaf self.safety.init_tests() -class TestToyotaSafetyTorqueGasInterceptor(TestToyotaSafetyGasInterceptorBase, TestToyotaSafetyTorque): - pass - - class TestToyotaSafetyAngle(TestToyotaSafetyBase, common.AngleSteeringSafetyTest): # Angle control limits @@ -292,10 +261,6 @@ class TestToyotaSafetyAngle(TestToyotaSafetyBase, common.AngleSteeringSafetyTest self.assertEqual(self.safety.get_angle_meas_max(), 0) -class TestToyotaSafetyAngleGasInterceptor(TestToyotaSafetyGasInterceptorBase, TestToyotaSafetyAngle): - pass - - class TestToyotaAltBrakeSafety(TestToyotaSafetyTorque): def setUp(self): @@ -313,10 +278,6 @@ class TestToyotaAltBrakeSafety(TestToyotaSafetyTorque): pass -class TestToyotaAltBrakeSafetyGasInterceptor(TestToyotaSafetyGasInterceptorBase, TestToyotaAltBrakeSafety): - pass - - class TestToyotaStockLongitudinalBase(TestToyotaSafetyBase): TX_MSGS = TOYOTA_COMMON_TX_MSGS From 16bd1382dfe13176b172da9fdc749e7f6567c56d Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Wed, 20 Mar 2024 19:36:42 -0700 Subject: [PATCH 43/67] reduce SPI timeouts in python lib (#1906) * reduce SPI timeouts in python lib * increase * little more --------- Co-authored-by: Comma Device --- python/spi.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/python/spi.py b/python/spi.py index d34a61d56..be4f7dcf4 100644 --- a/python/spi.py +++ b/python/spi.py @@ -251,7 +251,7 @@ class PandaSpiHandle(BaseHandle): version_bytes = spi.readbytes(len(vers_str) + 2) if bytes(version_bytes).startswith(vers_str): break - if (time.monotonic() - start) > 0.01: + if (time.monotonic() - start) > 0.001: raise PandaSpiMissingAck rlen = struct.unpack(" Date: Thu, 21 Mar 2024 11:04:51 -0700 Subject: [PATCH 44/67] pre-commit: autoupdate hooks (#1904) 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 2144d3553..09fcffbc0 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.3.2 + rev: v0.3.3 hooks: - id: ruff From 74e6a545032885f5811da5c8b682120bc2d1b920 Mon Sep 17 00:00:00 2001 From: Andrei Radulescu Date: Thu, 21 Mar 2024 21:45:47 +0200 Subject: [PATCH 45/67] jungle: assume F4 MCU (#1907) --- board/jungle/__init__.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/board/jungle/__init__.py b/board/jungle/__init__.py index a95ddfa92..688a8f91f 100644 --- a/board/jungle/__init__.py +++ b/board/jungle/__init__.py @@ -80,6 +80,12 @@ class PandaJungle(Panda): return McuType.F4 elif hw_type in PandaJungle.H7_DEVICES: return McuType.H7 + else: + # have to assume F4, see comment in Panda.connect + # initially Jungle V1 has HW type: bytearray(b'') + if hw_type == b'' or self._assume_f4_mcu: + return McuType.F4 + raise ValueError(f"unknown HW type: {hw_type}") def up_to_date(self, fn=None) -> bool: From cccceabf8abeb612c973e0bd26d06cfc7bcefcc7 Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Thu, 21 Mar 2024 13:04:45 -0700 Subject: [PATCH 46/67] exit flashing scripts with error if no pandas --- board/flash.py | 1 + board/jungle/flash.py | 2 ++ board/jungle/recover.py | 1 + board/recover.py | 1 + 4 files changed, 5 insertions(+) diff --git a/board/flash.py b/board/flash.py index d1a78e2c5..903a6a645 100755 --- a/board/flash.py +++ b/board/flash.py @@ -15,3 +15,4 @@ if __name__ == "__main__": print("flashing", s) with Panda(serial=s) as p: p.flash() + exit(1 if len(serials) == 0 else 0) diff --git a/board/jungle/flash.py b/board/jungle/flash.py index 75a7f0c8e..5b6c6e904 100755 --- a/board/jungle/flash.py +++ b/board/jungle/flash.py @@ -15,3 +15,5 @@ if __name__ == "__main__": print("flashing", s) with PandaJungle(serial=s) as p: p.flash() + + exit(1 if len(serials) == 0 else 0) diff --git a/board/jungle/recover.py b/board/jungle/recover.py index 98afb0674..19666c3ed 100755 --- a/board/jungle/recover.py +++ b/board/jungle/recover.py @@ -24,3 +24,4 @@ if __name__ == "__main__": for s in dfu_serials: print("flashing", s) PandaJungleDFU(s).recover() + exit(1 if len(dfu_serials) == 0 else 0) diff --git a/board/recover.py b/board/recover.py index 5284a4e29..0a248525a 100755 --- a/board/recover.py +++ b/board/recover.py @@ -24,3 +24,4 @@ if __name__ == "__main__": for s in dfu_serials: print("flashing", s) PandaDFU(s).recover() + exit(1 if len(dfu_serials) == 0 else 0) From de061e4f7317dbacc206ef5f038d35a17e8ef0e7 Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Thu, 21 Mar 2024 13:56:36 -0700 Subject: [PATCH 47/67] remove rest of gmlan (#1908) * remove rest of gmlan * fix * update struct * update --- board/boards/board_declarations.h | 4 +- board/boards/white.h | 69 ++---- board/can_definitions.h | 2 +- board/drivers/can_common.h | 19 +- board/drivers/gmlan_alt.h | 270 ----------------------- board/faults.h | 2 +- board/health.h | 3 +- board/jungle/boards/board_declarations.h | 2 - board/jungle/main.c | 1 - board/main.c | 1 - board/main_comms.h | 5 +- board/safety/safety_gm.h | 3 +- board/stm32f4/peripherals.h | 1 - python/__init__.py | 54 ++--- tests/black_white_loopback_test.py | 2 +- tests/black_white_relay_endurance.py | 2 +- tests/black_white_relay_test.py | 2 +- tests/gmbitbang/recv.py | 18 -- tests/gmbitbang/rigol.py | 36 --- tests/gmbitbang/test.py | 32 --- tests/gmbitbang/test_one.py | 22 -- tests/gmbitbang/test_packer.c | 28 --- tests/gmlan_harness_test.py | 78 ------- tests/hitl/3_usb_to_can.py | 41 ---- tests/hitl/conftest.py | 6 +- tests/libpanda/libpanda_py.py | 2 - tests/libpanda/panda.c | 2 - tests/loopback_test.py | 12 +- tests/safety/common.py | 3 +- tests/safety/test_gm.py | 3 +- tests/tucan_loopback.py | 92 -------- tests/usbprotocol/test_comms.py | 4 +- 32 files changed, 62 insertions(+), 759 deletions(-) delete mode 100644 board/drivers/gmlan_alt.h delete mode 100755 tests/gmbitbang/recv.py delete mode 100755 tests/gmbitbang/rigol.py delete mode 100755 tests/gmbitbang/test.py delete mode 100755 tests/gmbitbang/test_one.py delete mode 100644 tests/gmbitbang/test_packer.c delete mode 100755 tests/gmlan_harness_test.py delete mode 100755 tests/tucan_loopback.py diff --git a/board/boards/board_declarations.h b/board/boards/board_declarations.h index f30216a0d..ac0c14136 100644 --- a/board/boards/board_declarations.h +++ b/board/boards/board_declarations.h @@ -72,6 +72,4 @@ struct board { // CAN modes #define CAN_MODE_NORMAL 0U -#define CAN_MODE_GMLAN_CAN2 1U -#define CAN_MODE_GMLAN_CAN3 2U -#define CAN_MODE_OBD_CAN2 3U +#define CAN_MODE_OBD_CAN2 1U diff --git a/board/boards/white.h b/board/boards/white.h index 362f525a5..690334568 100644 --- a/board/boards/white.h +++ b/board/boards/white.h @@ -66,61 +66,22 @@ void white_set_usb_power_mode(uint8_t mode){ } void white_set_can_mode(uint8_t mode){ - switch (mode) { - case CAN_MODE_NORMAL: - // B12,B13: disable GMLAN mode - set_gpio_mode(GPIOB, 12, MODE_INPUT); - set_gpio_mode(GPIOB, 13, MODE_INPUT); + if (mode == CAN_MODE_NORMAL) { + // B12,B13: disable GMLAN mode + set_gpio_mode(GPIOB, 12, MODE_INPUT); + set_gpio_mode(GPIOB, 13, MODE_INPUT); - // B3,B4: disable GMLAN mode - set_gpio_mode(GPIOB, 3, MODE_INPUT); - set_gpio_mode(GPIOB, 4, MODE_INPUT); + // B3,B4: disable GMLAN mode + set_gpio_mode(GPIOB, 3, MODE_INPUT); + set_gpio_mode(GPIOB, 4, MODE_INPUT); - // B5,B6: normal CAN2 mode - set_gpio_alternate(GPIOB, 5, GPIO_AF9_CAN2); - set_gpio_alternate(GPIOB, 6, GPIO_AF9_CAN2); + // B5,B6: normal CAN2 mode + set_gpio_alternate(GPIOB, 5, GPIO_AF9_CAN2); + set_gpio_alternate(GPIOB, 6, GPIO_AF9_CAN2); - // A8,A15: normal CAN3 mode - set_gpio_alternate(GPIOA, 8, GPIO_AF11_CAN3); - set_gpio_alternate(GPIOA, 15, GPIO_AF11_CAN3); - break; - case CAN_MODE_GMLAN_CAN2: - // B5,B6: disable CAN2 mode - set_gpio_mode(GPIOB, 5, MODE_INPUT); - set_gpio_mode(GPIOB, 6, MODE_INPUT); - - // B3,B4: disable GMLAN mode - set_gpio_mode(GPIOB, 3, MODE_INPUT); - set_gpio_mode(GPIOB, 4, MODE_INPUT); - - // B12,B13: GMLAN mode - set_gpio_alternate(GPIOB, 12, GPIO_AF9_CAN2); - set_gpio_alternate(GPIOB, 13, GPIO_AF9_CAN2); - - // A8,A15: normal CAN3 mode - set_gpio_alternate(GPIOA, 8, GPIO_AF11_CAN3); - set_gpio_alternate(GPIOA, 15, GPIO_AF11_CAN3); - break; - case CAN_MODE_GMLAN_CAN3: - // A8,A15: disable CAN3 mode - set_gpio_mode(GPIOA, 8, MODE_INPUT); - set_gpio_mode(GPIOA, 15, MODE_INPUT); - - // B12,B13: disable GMLAN mode - set_gpio_mode(GPIOB, 12, MODE_INPUT); - set_gpio_mode(GPIOB, 13, MODE_INPUT); - - // B3,B4: GMLAN mode - set_gpio_alternate(GPIOB, 3, GPIO_AF11_CAN3); - set_gpio_alternate(GPIOB, 4, GPIO_AF11_CAN3); - - // B5,B6: normal CAN2 mode - set_gpio_alternate(GPIOB, 5, GPIO_AF9_CAN2); - set_gpio_alternate(GPIOB, 6, GPIO_AF9_CAN2); - break; - default: - print("Tried to set unsupported CAN mode: "); puth(mode); print("\n"); - break; + // A8,A15: normal CAN3 mode + set_gpio_alternate(GPIOA, 8, GPIO_AF11_CAN3); + set_gpio_alternate(GPIOA, 15, GPIO_AF11_CAN3); } } @@ -168,8 +129,8 @@ void white_grey_init(void) { 0 1 high voltage wakeup 1 1 33kbit (normal) */ - set_gpio_output(GPIOB, 14, 1); - set_gpio_output(GPIOB, 15, 1); + set_gpio_output(GPIOB, 14, 0); + set_gpio_output(GPIOB, 15, 0); // B7: K-line enable set_gpio_output(GPIOB, 7, 1); diff --git a/board/can_definitions.h b/board/can_definitions.h index b3631d807..f3ce43782 100644 --- a/board/can_definitions.h +++ b/board/can_definitions.h @@ -1,7 +1,7 @@ #pragma once const uint8_t PANDA_CAN_CNT = 3U; -const uint8_t PANDA_BUS_CNT = 4U; +const uint8_t PANDA_BUS_CNT = 3U; // bump this when changing the CAN packet #define CAN_PACKET_VERSION 4 diff --git a/board/drivers/can_common.h b/board/drivers/can_common.h index bc9adde7c..57d2508cc 100644 --- a/board/drivers/can_common.h +++ b/board/drivers/can_common.h @@ -20,7 +20,6 @@ uint32_t safety_tx_blocked = 0; uint32_t safety_rx_invalid = 0; uint32_t tx_buffer_overflow = 0; uint32_t rx_buffer_overflow = 0; -uint32_t gmlan_send_errs = 0; can_health_t can_health[] = {{0}, {0}, {0}}; @@ -54,7 +53,6 @@ void process_can(uint8_t can_number); #define CAN_RX_BUFFER_SIZE 4096U #define CAN_TX_BUFFER_SIZE 416U -#define GMLAN_TX_BUFFER_SIZE 416U #ifdef STM32H7 // ITCM RAM and DTCM RAM are the fastest for Cortex-M7 core access @@ -67,10 +65,10 @@ can_buffer(tx1_q, CAN_TX_BUFFER_SIZE) can_buffer(tx2_q, CAN_TX_BUFFER_SIZE) #endif can_buffer(tx3_q, CAN_TX_BUFFER_SIZE) -can_buffer(txgmlan_q, GMLAN_TX_BUFFER_SIZE) + // FIXME: // cppcheck-suppress misra-c2012-9.3 -can_ring *can_queues[] = {&can_tx1_q, &can_tx2_q, &can_tx3_q, &can_txgmlan_q}; +can_ring *can_queues[] = {&can_tx1_q, &can_tx2_q, &can_tx3_q}; // helpers #define WORD_TO_BYTE_ARRAY(dst8, src32) 0[dst8] = ((src32) & 0xFFU); 1[dst8] = (((src32) >> 8U) & 0xFFU); 2[dst8] = (((src32) >> 16U) & 0xFFU); 3[dst8] = (((src32) >> 24U) & 0xFFU) @@ -122,8 +120,6 @@ bool can_push(can_ring *q, const CANPacket_t *elem) { print("can_tx2_q"); } else if (q == &can_tx3_q) { print("can_tx3_q"); - } else if (q == &can_txgmlan_q) { - print("can_txgmlan_q"); } else { print("unknown"); } @@ -234,8 +230,7 @@ bool can_tx_check_min_slots_free(uint32_t min) { return (can_slots_empty(&can_tx1_q) >= min) && (can_slots_empty(&can_tx2_q) >= min) && - (can_slots_empty(&can_tx3_q) >= min) && - (can_slots_empty(&can_txgmlan_q) >= min); + (can_slots_empty(&can_tx3_q) >= min); } uint8_t calculate_checksum(const uint8_t *dat, uint32_t len) { @@ -259,12 +254,8 @@ void can_send(CANPacket_t *to_push, uint8_t bus_number, bool skip_tx_hook) { if (skip_tx_hook || safety_tx_hook(to_push) != 0) { if (bus_number < PANDA_BUS_CNT) { // add CAN packet to send queue - if ((bus_number == 3U) && (bus_config[3].can_num_lookup == 0xFFU)) { - gmlan_send_errs += bitbang_gmlan(to_push) ? 0U : 1U; - } else { - tx_buffer_overflow += can_push(can_queues[bus_number], to_push) ? 0U : 1U; - process_can(CAN_NUM_FROM_BUS_NUM(bus_number)); - } + tx_buffer_overflow += can_push(can_queues[bus_number], to_push) ? 0U : 1U; + process_can(CAN_NUM_FROM_BUS_NUM(bus_number)); } } else { safety_tx_blocked += 1U; diff --git a/board/drivers/gmlan_alt.h b/board/drivers/gmlan_alt.h deleted file mode 100644 index 2dbc381bd..000000000 --- a/board/drivers/gmlan_alt.h +++ /dev/null @@ -1,270 +0,0 @@ -#define GMLAN_TICKS_PER_SECOND 33300 //1sec @ 33.3kbps -#define GMLAN_TICKS_PER_TIMEOUT_TICKLE 500 //15ms @ 33.3kbps -#define GMLAN_HIGH 0 //0 is high on bus (dominant) -#define GMLAN_LOW 1 //1 is low on bus - -#define DISABLED -1 -#define BITBANG 0 -#define GPIO_SWITCH 1 - -#define MAX_BITS_CAN_PACKET (200) - -int gmlan_alt_mode = DISABLED; - -// returns out_len -int do_bitstuff(char *out, const char *in, int in_len) { - int last_bit = -1; - int bit_cnt = 0; - int j = 0; - for (int i = 0; i < in_len; i++) { - char bit = in[i]; - out[j] = bit; - j++; - - // do the stuffing - if (bit == (char)last_bit) { - bit_cnt++; - if (bit_cnt == 5) { - // 5 in a row the same, do stuff - last_bit = !bit ? 1 : 0; - out[j] = last_bit; - j++; - bit_cnt = 1; - } - } else { - // this is a new bit - last_bit = (int)bit; - bit_cnt = 1; - } - } - return j; -} - -int append_crc(char *in, int in_len) { - unsigned int crc = 0; - for (int i = 0; i < in_len; i++) { - crc <<= 1; - if (((unsigned int)(in[i]) ^ ((crc >> 15) & 1U)) != 0U) { - crc = crc ^ 0x4599U; - } - crc &= 0x7fffU; - } - int in_len_copy = in_len; - for (int i = 14; i >= 0; i--) { - in[in_len_copy] = (crc >> (unsigned int)(i)) & 1U; - in_len_copy++; - } - return in_len_copy; -} - -int append_bits(char *in, int in_len, const char *app, int app_len) { - int in_len_copy = in_len; - for (int i = 0; i < app_len; i++) { - in[in_len_copy] = app[i]; - in_len_copy++; - } - return in_len_copy; -} - -int append_int(char *in, int in_len, int val, int val_len) { - int in_len_copy = in_len; - for (int i = val_len - 1; i >= 0; i--) { - in[in_len_copy] = ((unsigned int)(val) & (1U << (unsigned int)(i))) != 0U; - in_len_copy++; - } - return in_len_copy; -} - -int get_bit_message(char *out, const CANPacket_t *to_bang) { - char pkt[MAX_BITS_CAN_PACKET]; - char footer[] = { - 1, // CRC delimiter - 1, // ACK - 1, // ACK delimiter - 1,1,1,1,1,1,1, // EOF - 1,1,1, // IFS - }; - - int len = 0; - - // test packet - int dlc_len = GET_LEN(to_bang); - len = append_int(pkt, len, 0, 1); // Start-of-frame - - if (to_bang->extended != 0U) { - // extended identifier - len = append_int(pkt, len, GET_ADDR(to_bang) >> 18, 11); // Identifier - len = append_int(pkt, len, 3, 2); // SRR+IDE - len = append_int(pkt, len, (GET_ADDR(to_bang)) & ((1UL << 18) - 1U), 18); // Identifier - len = append_int(pkt, len, 0, 3); // RTR+r1+r0 - } else { - // standard identifier - len = append_int(pkt, len, GET_ADDR(to_bang), 11); // Identifier - len = append_int(pkt, len, 0, 3); // RTR+IDE+reserved - } - - len = append_int(pkt, len, dlc_len, 4); // Data length code - - // append data - for (int i = 0; i < dlc_len; i++) { - len = append_int(pkt, len, to_bang->data[i], 8); - } - - // append crc - len = append_crc(pkt, len); - - // do bitstuffing - len = do_bitstuff(out, pkt, len); - - // append footer - len = append_bits(out, len, footer, sizeof(footer)); - return len; -} - -void TIM12_IRQ_Handler(void); - -void setup_timer(void) { - // register interrupt - REGISTER_INTERRUPT(TIM8_BRK_TIM12_IRQn, TIM12_IRQ_Handler, 40000U, FAULT_INTERRUPT_RATE_GMLAN) - - // setup - register_set(&(TIM12->PSC), (APB1_TIMER_FREQ-1U), 0xFFFFU); // Tick on 1 us - register_set(&(TIM12->CR1), TIM_CR1_CEN, 0x3FU); // Enable - register_set(&(TIM12->ARR), (30U-1U), 0xFFFFU); // 33.3 kbps - - // in case it's disabled - NVIC_EnableIRQ(TIM8_BRK_TIM12_IRQn); - - // run the interrupt - register_set(&(TIM12->DIER), TIM_DIER_UIE, 0x5F5FU); // Update interrupt - TIM12->SR = 0; -} - -int gmlan_timeout_counter = GMLAN_TICKS_PER_TIMEOUT_TICKLE; //GMLAN transceiver times out every 17ms held high; tickle every 15ms -int can_timeout_counter = GMLAN_TICKS_PER_SECOND; //1 second - -int inverted_bit_to_send = GMLAN_HIGH; -int gmlan_switch_below_timeout = -1; -int gmlan_switch_timeout_enable = 0; - -void set_bitbanged_gmlan(int val) { - if (val != 0) { - register_set_bits(&(GPIOB->ODR), (1UL << 13)); - } else { - register_clear_bits(&(GPIOB->ODR), (1UL << 13)); - } -} - -char pkt_stuffed[MAX_BITS_CAN_PACKET]; -int gmlan_sending = -1; -int gmlan_sendmax = -1; -bool gmlan_send_ok = true; - -int gmlan_silent_count = 0; -int gmlan_fail_count = 0; -#define REQUIRED_SILENT_TIME 10 -#define MAX_FAIL_COUNT 10 - -void TIM12_IRQ_Handler(void) { - if (gmlan_alt_mode == BITBANG) { - if ((TIM12->SR & TIM_SR_UIF) && (gmlan_sendmax != -1)) { - int read = get_gpio_input(GPIOB, 12); - if (gmlan_silent_count < REQUIRED_SILENT_TIME) { - if (read == 0) { - gmlan_silent_count = 0; - } else { - gmlan_silent_count++; - } - } else { - bool retry = 0; - // in send loop - if ((gmlan_sending > 0) && // not first bit - ((read == 0) && (pkt_stuffed[gmlan_sending-1] == (char)1)) && // bus wrongly dominant - (gmlan_sending != (gmlan_sendmax - 11))) { //not ack bit - print("GMLAN ERR: bus driven at "); - puth(gmlan_sending); - print("\n"); - retry = 1; - } else if ((read == 1) && (gmlan_sending == (gmlan_sendmax - 11))) { // recessive during ACK - print("GMLAN ERR: didn't recv ACK\n"); - retry = 1; - } else { - // do not retry - } - if (retry) { - // reset sender (retry after 7 silent) - set_bitbanged_gmlan(1); // recessive - gmlan_silent_count = 0; - gmlan_sending = 0; - gmlan_fail_count++; - if (gmlan_fail_count == MAX_FAIL_COUNT) { - print("GMLAN ERR: giving up send\n"); - gmlan_send_ok = false; - } - } else { - set_bitbanged_gmlan(pkt_stuffed[gmlan_sending]); - gmlan_sending++; - } - } - if ((gmlan_sending == gmlan_sendmax) || (gmlan_fail_count == MAX_FAIL_COUNT)) { - set_bitbanged_gmlan(1); // recessive - set_gpio_mode(GPIOB, 13, MODE_INPUT); - register_clear_bits(&(TIM12->DIER), TIM_DIER_UIE); // No update interrupt - register_set(&(TIM12->CR1), 0U, 0x3FU); // Disable timer - gmlan_sendmax = -1; // exit - } - } - } else if (gmlan_alt_mode == GPIO_SWITCH) { - if ((TIM12->SR & TIM_SR_UIF) && (gmlan_switch_below_timeout != -1)) { - if ((can_timeout_counter == 0) && gmlan_switch_timeout_enable) { - //it has been more than 1 second since timeout was reset; disable timer and restore the GMLAN output - set_gpio_output(GPIOB, 13, GMLAN_LOW); - gmlan_switch_below_timeout = -1; - gmlan_timeout_counter = GMLAN_TICKS_PER_TIMEOUT_TICKLE; - gmlan_alt_mode = DISABLED; - } - else { - can_timeout_counter--; - if (gmlan_timeout_counter == 0) { - //Send a 1 (bus low) every 15ms to reset the GMLAN transceivers timeout - gmlan_timeout_counter = GMLAN_TICKS_PER_TIMEOUT_TICKLE; - set_gpio_output(GPIOB, 13, GMLAN_LOW); - } - else { - set_gpio_output(GPIOB, 13, inverted_bit_to_send); - gmlan_timeout_counter--; - } - } - } - } else { - // Invalid GMLAN mode. Do not put a print statement here, way too fast to keep up with - } - TIM12->SR = 0; -} - -bool bitbang_gmlan(const CANPacket_t *to_bang) { - gmlan_send_ok = true; - gmlan_alt_mode = BITBANG; - -#ifdef HW_TYPE_DOS - if (hw_type == HW_TYPE_DOS) { - if (gmlan_sendmax == -1) { - int len = get_bit_message(pkt_stuffed, to_bang); - gmlan_fail_count = 0; - gmlan_silent_count = 0; - gmlan_sending = 0; - gmlan_sendmax = len; - // setup for bitbang loop - set_bitbanged_gmlan(1); // recessive - set_gpio_mode(GPIOB, 13, MODE_OUTPUT); - - // 33kbps - setup_timer(); - } - } -#else - UNUSED(to_bang); -#endif - - return gmlan_send_ok; -} diff --git a/board/faults.h b/board/faults.h index a7f437dee..dc6c1f2aa 100644 --- a/board/faults.h +++ b/board/faults.h @@ -9,7 +9,7 @@ #define FAULT_INTERRUPT_RATE_CAN_2 (1UL << 3) #define FAULT_INTERRUPT_RATE_CAN_3 (1UL << 4) #define FAULT_INTERRUPT_RATE_TACH (1UL << 5) -#define FAULT_INTERRUPT_RATE_GMLAN (1UL << 6) +#define FAULT_INTERRUPT_RATE_GMLAN (1UL << 6) // deprecated #define FAULT_INTERRUPT_RATE_INTERRUPTS (1UL << 7) #define FAULT_INTERRUPT_RATE_SPI_DMA (1UL << 8) #define FAULT_INTERRUPT_RATE_SPI_CS (1UL << 9) diff --git a/board/health.h b/board/health.h index fc7661ca9..74d822dc6 100644 --- a/board/health.h +++ b/board/health.h @@ -1,6 +1,6 @@ // When changing these structs, python/__init__.py needs to be kept up to date! -#define HEALTH_PACKET_VERSION 15 +#define HEALTH_PACKET_VERSION 16 struct __attribute__((packed)) health_t { uint32_t uptime_pkt; uint32_t voltage_pkt; @@ -9,7 +9,6 @@ struct __attribute__((packed)) health_t { uint32_t safety_rx_invalid_pkt; uint32_t tx_buffer_overflow_pkt; uint32_t rx_buffer_overflow_pkt; - uint32_t gmlan_send_errs_pkt; uint32_t faults_pkt; uint8_t ignition_line_pkt; uint8_t ignition_can_pkt; diff --git a/board/jungle/boards/board_declarations.h b/board/jungle/boards/board_declarations.h index 925918921..2f65ff4a8 100644 --- a/board/jungle/boards/board_declarations.h +++ b/board/jungle/boards/board_declarations.h @@ -49,8 +49,6 @@ struct board { // CAN modes #define CAN_MODE_NORMAL 0U -#define CAN_MODE_GMLAN_CAN2 1U -#define CAN_MODE_GMLAN_CAN3 2U #define CAN_MODE_OBD_CAN2 3U // Harness states diff --git a/board/jungle/main.c b/board/jungle/main.c index f0a09dfbd..0359be968 100644 --- a/board/jungle/main.c +++ b/board/jungle/main.c @@ -2,7 +2,6 @@ #include "board/config.h" #include "board/safety.h" -#include "board/drivers/gmlan_alt.h" #include "board/drivers/pwm.h" #include "board/drivers/usb.h" diff --git a/board/main.c b/board/main.c index 00429e32a..3649cc920 100644 --- a/board/main.c +++ b/board/main.c @@ -3,7 +3,6 @@ #include "drivers/pwm.h" #include "drivers/usb.h" -#include "drivers/gmlan_alt.h" #include "drivers/simple_watchdog.h" #include "drivers/bootkick.h" diff --git a/board/main_comms.h b/board/main_comms.h index 2c8bf165b..830ef83b4 100644 --- a/board/main_comms.h +++ b/board/main_comms.h @@ -21,7 +21,6 @@ int get_health_pkt(void *dat) { health->safety_rx_invalid_pkt = safety_rx_invalid; health->tx_buffer_overflow_pkt = tx_buffer_overflow; health->rx_buffer_overflow_pkt = rx_buffer_overflow; - health->gmlan_send_errs_pkt = gmlan_send_errs; health->car_harness_status_pkt = harness.status; health->safety_mode_pkt = (uint8_t)(current_safety_mode); health->safety_param_pkt = current_safety_param; @@ -211,9 +210,9 @@ int comms_control_handler(ControlPacket_t *req, uint8_t *resp) { case 0xd8: NVIC_SystemReset(); break; - // **** 0xdb: set GMLAN (white/grey) or OBD CAN (black) multiplexing mode + // **** 0xdb: set OBD CAN multiplexing mode case 0xdb: - if(current_board->has_obd){ + if (current_board->has_obd) { if (req->param1 == 1U) { // Enable OBD CAN current_board->set_can_mode(CAN_MODE_OBD_CAN2); diff --git a/board/safety/safety_gm.h b/board/safety/safety_gm.h index 82a5d9cd3..7f8ad72c7 100644 --- a/board/safety/safety_gm.h +++ b/board/safety/safety_gm.h @@ -29,8 +29,7 @@ const int GM_STANDSTILL_THRSLD = 10; // 0.311kph const CanMsg GM_ASCM_TX_MSGS[] = {{0x180, 0, 4}, {0x409, 0, 7}, {0x40A, 0, 7}, {0x2CB, 0, 8}, {0x370, 0, 6}, // pt bus {0xA1, 1, 7}, {0x306, 1, 8}, {0x308, 1, 7}, {0x310, 1, 2}, // obs bus - {0x315, 2, 5}, // ch bus - {0x104c006c, 3, 3}, {0x10400060, 3, 5}}; // gmlan + {0x315, 2, 5}}; // ch bus const CanMsg GM_CAM_TX_MSGS[] = {{0x180, 0, 4}, // pt bus {0x1E1, 2, 7}, {0x184, 2, 8}}; // camera bus diff --git a/board/stm32f4/peripherals.h b/board/stm32f4/peripherals.h index 79ac3c6e4..711f1b82a 100644 --- a/board/stm32f4/peripherals.h +++ b/board/stm32f4/peripherals.h @@ -83,7 +83,6 @@ void peripherals_init(void) { RCC->APB1ENR |= RCC_APB1ENR_TIM5EN; // k-line init RCC->APB1ENR |= RCC_APB1ENR_TIM6EN; // interrupt timer RCC->APB2ENR |= RCC_APB2ENR_TIM9EN; // slow loop - RCC->APB1ENR |= RCC_APB1ENR_TIM12EN; // gmlan_alt } void enable_interrupt_timer(void) { diff --git a/python/__init__.py b/python/__init__.py index 97c967f22..c2bfa5a03 100644 --- a/python/__init__.py +++ b/python/__init__.py @@ -148,9 +148,6 @@ class Panda: SERIAL_LIN2 = 3 SERIAL_SOM_DEBUG = 4 - GMLAN_CAN2 = 1 - GMLAN_CAN3 = 2 - USB_PIDS = (0xddee, 0xddcc) REQUEST_IN = usb1.ENDPOINT_IN | usb1.TYPE_VENDOR | usb1.RECIPIENT_DEVICE REQUEST_OUT = usb1.ENDPOINT_OUT | usb1.TYPE_VENDOR | usb1.RECIPIENT_DEVICE @@ -168,9 +165,9 @@ class Panda: HW_TYPE_CUATRO = b'\x0a' CAN_PACKET_VERSION = 4 - HEALTH_PACKET_VERSION = 15 + HEALTH_PACKET_VERSION = 16 CAN_HEALTH_PACKET_VERSION = 5 - HEALTH_STRUCT = struct.Struct(" 0: - add = ret[0][0] - if last_add is not None and add != last_add + 1: - print("MISS: ", last_add, add) - last_add = add - print(ret) diff --git a/tests/gmbitbang/rigol.py b/tests/gmbitbang/rigol.py deleted file mode 100755 index 818df748f..000000000 --- a/tests/gmbitbang/rigol.py +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env python3 -# pylint: skip-file -# type: ignore -import numpy as np -import visa -import matplotlib.pyplot as plt - -resources = visa.ResourceManager() -print(resources.list_resources()) - -scope = resources.open_resource('USB0::0x1AB1::0x04CE::DS1ZA184652242::INSTR', timeout=2000, chunk_size=1024000) -print(scope.query('*IDN?').strip()) - -#voltscale = scope.ask_for_values(':CHAN1:SCAL?')[0] -#voltoffset = scope.ask_for_values(":CHAN1:OFFS?")[0] - -#scope.write(":STOP") -scope.write(":WAV:POIN:MODE RAW") -scope.write(":WAV:DATA? CHAN1")[10:] -rawdata = scope.read_raw() -data = np.frombuffer(rawdata, 'B') -print(data.shape) - -s1 = data[0:650] -s2 = data[650:] -s1i = np.argmax(s1 > 100) -s2i = np.argmax(s2 > 100) -s1 = s1[s1i:] -s2 = s2[s2i:] - -plt.plot(s1) -plt.plot(s2) -plt.show() -#data = (data - 130.0 - voltoffset/voltscale*25) / 25 * voltscale - -print(data) diff --git a/tests/gmbitbang/test.py b/tests/gmbitbang/test.py deleted file mode 100755 index b8041136d..000000000 --- a/tests/gmbitbang/test.py +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env python3 -import time -from panda import Panda - -p1 = Panda('380016000551363338383037') -p2 = Panda('430026000951363338383037') - -# this is a test, no safety -p1.set_safety_mode(Panda.SAFETY_ALLOUTPUT) -p2.set_safety_mode(Panda.SAFETY_ALLOUTPUT) - -# get versions -print(p1.get_version()) -print(p2.get_version()) - -# this sets bus 2 to actually be GMLAN -p2.set_gmlan(bus=2) - -# send w bitbang then without -#iden = 123 -iden = 18000 -#dat = "\x01\x02" -dat = "\x01\x02\x03\x04\x05\x06\x07\x08" -while 1: - iden += 1 - p1.set_gmlan(bus=None) - p1.can_send(iden, dat, bus=3) - #p1.set_gmlan(bus=2) - #p1.can_send(iden, dat, bus=3) - time.sleep(0.01) - print(p2.can_recv()) - #exit(0) diff --git a/tests/gmbitbang/test_one.py b/tests/gmbitbang/test_one.py deleted file mode 100755 index 981edc523..000000000 --- a/tests/gmbitbang/test_one.py +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env python3 -import time -from panda import Panda - -p = Panda() -p.set_safety_mode(Panda.SAFETY_ALLOUTPUT) - -# hack anything on bus -p.set_gmlan(bus=2) -time.sleep(0.1) -while len(p.can_recv()) > 0: - print("clearing") - time.sleep(0.1) -print("cleared") -p.set_gmlan(bus=None) - -iden = 18000 -dat = "\x01\x02\x03\x04\x05\x06\x07\x08" -while 1: - iden += 1 - p.can_send(iden, dat, bus=3) - time.sleep(0.01) diff --git a/tests/gmbitbang/test_packer.c b/tests/gmbitbang/test_packer.c deleted file mode 100644 index 63c013100..000000000 --- a/tests/gmbitbang/test_packer.c +++ /dev/null @@ -1,28 +0,0 @@ -#include -#include - -#define CANPACKET_DATA_SIZE_MAX 8 -#include "../../board/can_definitions.h" - -#include "../../board/drivers/canbitbang.h" - -int main() { - char out[300]; - CANPacket_t to_bang = {0}; - to_bang.addr = 20 << 18; - to_bang.data_len_code = 1; - to_bang.data[0] = 1; - - int len = get_bit_message(out, &to_bang); - printf("T:"); - for (int i = 0; i < len; i++) { - printf("%d", out[i]); - } - printf("\n"); - printf("R:0000010010100000100010000010011110111010100111111111111111"); - printf("\n"); - return 0; -} - - - diff --git a/tests/gmlan_harness_test.py b/tests/gmlan_harness_test.py deleted file mode 100755 index 950918cff..000000000 --- a/tests/gmlan_harness_test.py +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/env python3 - -import time - -from panda import Panda - -WHITE_GMLAN_BUS = 3 -OTHER_GMLAN_BUS = 1 - -def set_gmlan(p): - if p.get_type() == Panda.HW_TYPE_WHITE_PANDA: - p.set_gmlan(2) - else: - p.set_obd(True) - -def set_speed_kbps(p, speed): - if p.get_type() == Panda.HW_TYPE_WHITE_PANDA: - p.set_can_speed_kbps(WHITE_GMLAN_BUS, speed) - else: - p.set_can_speed_kbps(OTHER_GMLAN_BUS, speed) - -def send(p, id_, msg): - if p.get_type() == Panda.HW_TYPE_WHITE_PANDA: - p.can_send(id_, msg, WHITE_GMLAN_BUS) - else: - p.can_send(id_, msg, OTHER_GMLAN_BUS) - -if __name__ == "__main__": - pl = Panda.list() - assert(len(pl) == 2) - p0 = Panda(pl[1]) - p1 = Panda(pl[0]) - - p0.set_safety_mode(Panda.SAFETY_ALLOUTPUT) - p1.set_safety_mode(Panda.SAFETY_ALLOUTPUT) - - print("0: ", p0.get_type()) - print("1: ", p1.get_type()) - - set_gmlan(p0) - set_gmlan(p1) - - p0.can_clear(0xFFFF) - p1.can_clear(0xFFFF) - - try: - loops = 0 - while True: - for speed in [33.3, 83.3]: - set_speed_kbps(p0, speed) - set_speed_kbps(p1, speed) - p0.can_clear(0xFFFF) - p1.can_clear(0xFFFF) - - print(f"Speed: {speed}") - time.sleep(0.1) - - print("Send 1 -> 0") - send(p1, 1, b"1to0:" + bytes(str(loops%100), "utf-8")) - time.sleep(0.05) - rx = list(filter(lambda x: x[3] < 128, p0.can_recv())) - print(rx) - assert(len(rx) == 1) - - print("Send 0 -> 1") - send(p0, 1, b"0to1:" + bytes(str(loops%100), "utf-8")) - time.sleep(0.05) - rx = list(filter(lambda x: x[3] < 128, p1.can_recv())) - print(rx) - assert(len(rx) == 1) - - time.sleep(0.5) - - - loops += 1 - print(f"Completed {loops} loops") - except Exception: - print("Test failed somehow. Did you power the black panda using the GMLAN harness?") diff --git a/tests/hitl/3_usb_to_can.py b/tests/hitl/3_usb_to_can.py index 9321eb4e8..c0a9035fe 100644 --- a/tests/hitl/3_usb_to_can.py +++ b/tests/hitl/3_usb_to_can.py @@ -1,9 +1,7 @@ import time -import pytest from flaky import flaky from panda import Panda -from panda.tests.hitl.conftest import SPEED_NORMAL, SPEED_GMLAN, PandaGroup from panda.tests.hitl.helpers import time_many_sends def test_can_loopback(p): @@ -81,45 +79,6 @@ def test_throughput(p): print("loopback 100 messages at speed %d, comp speed is %.2f, percent %.2f" % (speed, comp_kbps, saturation_pct)) -@pytest.mark.test_panda_types(PandaGroup.GMLAN) -def test_gmlan(p): - p.set_safety_mode(Panda.SAFETY_ALLOUTPUT) - p.set_can_loopback(True) - - # set gmlan on CAN2 - for bus in [Panda.GMLAN_CAN2, Panda.GMLAN_CAN3, Panda.GMLAN_CAN2, Panda.GMLAN_CAN3]: - p.set_gmlan(bus) - comp_kbps_gmlan = time_many_sends(p, 3) - assert comp_kbps_gmlan > (0.8 * SPEED_GMLAN) - assert comp_kbps_gmlan < (1.0 * SPEED_GMLAN) - - p.set_gmlan(None) - comp_kbps_normal = time_many_sends(p, bus) - assert comp_kbps_normal > (0.8 * SPEED_NORMAL) - assert comp_kbps_normal < (1.0 * SPEED_NORMAL) - - print("%d: %.2f kbps vs %.2f kbps" % (bus, comp_kbps_gmlan, comp_kbps_normal)) - -@pytest.mark.test_panda_types(PandaGroup.GMLAN) -def test_gmlan_bad_toggle(p): - p.set_safety_mode(Panda.SAFETY_ALLOUTPUT) - p.set_can_loopback(True) - - # GMLAN_CAN2 - for bus in [Panda.GMLAN_CAN2, Panda.GMLAN_CAN3]: - p.set_gmlan(bus) - comp_kbps_gmlan = time_many_sends(p, 3) - assert comp_kbps_gmlan > (0.6 * SPEED_GMLAN) - assert comp_kbps_gmlan < (1.0 * SPEED_GMLAN) - - # normal - for bus in [Panda.GMLAN_CAN2, Panda.GMLAN_CAN3]: - p.set_gmlan(None) - comp_kbps_normal = time_many_sends(p, bus) - assert comp_kbps_normal > (0.6 * SPEED_NORMAL) - assert comp_kbps_normal < (1.0 * SPEED_NORMAL) - - # this will fail if you have hardware serial connected def test_serial_debug(p): _ = p.serial_read(Panda.SERIAL_DEBUG) # junk diff --git a/tests/hitl/conftest.py b/tests/hitl/conftest.py index b7844354f..7a6e1b100 100644 --- a/tests/hitl/conftest.py +++ b/tests/hitl/conftest.py @@ -11,8 +11,7 @@ if "DEBUG" in os.environ: sys.stdout = sys.stderr SPEED_NORMAL = 500 -SPEED_GMLAN = 33.3 -BUS_SPEEDS = [(0, SPEED_NORMAL), (1, SPEED_NORMAL), (2, SPEED_NORMAL), (3, SPEED_GMLAN)] +BUS_SPEEDS = [(0, SPEED_NORMAL), (1, SPEED_NORMAL), (2, SPEED_NORMAL)] JUNGLE_SERIAL = os.getenv("PANDAS_JUNGLE") @@ -28,8 +27,6 @@ if PARALLEL: class PandaGroup: H7 = (Panda.HW_TYPE_RED_PANDA, Panda.HW_TYPE_RED_PANDA_V2, Panda.HW_TYPE_TRES) GEN2 = (Panda.HW_TYPE_BLACK_PANDA, Panda.HW_TYPE_UNO, Panda.HW_TYPE_DOS) + H7 - GMLAN = (Panda.HW_TYPE_WHITE_PANDA, Panda.HW_TYPE_GREY_PANDA) - TESTED = (Panda.HW_TYPE_WHITE_PANDA, Panda.HW_TYPE_BLACK_PANDA, Panda.HW_TYPE_RED_PANDA, Panda.HW_TYPE_RED_PANDA_V2, Panda.HW_TYPE_UNO) if HW_TYPES is not None: @@ -201,7 +198,6 @@ def fixture_panda_setup(request): p.reset(reconnect=True) p.set_can_loopback(False) - p.set_gmlan(None) p.set_power_save(False) for bus, speed in BUS_SPEEDS: p.set_can_speed_kbps(bus, speed) diff --git a/tests/libpanda/libpanda_py.py b/tests/libpanda/libpanda_py.py index 8f876c551..6f888ac60 100644 --- a/tests/libpanda/libpanda_py.py +++ b/tests/libpanda/libpanda_py.py @@ -40,7 +40,6 @@ typedef struct { } can_ring; extern can_ring *rx_q; -extern can_ring *txgmlan_q; extern can_ring *tx1_q; extern can_ring *tx2_q; extern can_ring *tx3_q; @@ -71,7 +70,6 @@ class Panda(PandaSafety, Protocol): tx1_q: Any tx2_q: Any tx3_q: Any - txgmlan_q: Any def can_set_checksum(self, p: CANPacket) -> None: ... # safety diff --git a/tests/libpanda/panda.c b/tests/libpanda/panda.c index 8efb6de4d..f34c02804 100644 --- a/tests/libpanda/panda.c +++ b/tests/libpanda/panda.c @@ -2,7 +2,6 @@ #include "config.h" #include "can_definitions.h" -bool bitbang_gmlan(CANPacket_t *to_bang) { return true; } bool can_init(uint8_t can_number) { return true; } void process_can(uint8_t can_number) { } //int safety_tx_hook(CANPacket_t *to_send) { return 1; } @@ -21,7 +20,6 @@ void can_tx_comms_resume_spi(void) { }; #include "drivers/can_common.h" can_ring *rx_q = &can_rx_q; -can_ring *txgmlan_q = &can_txgmlan_q; can_ring *tx1_q = &can_tx1_q; can_ring *tx2_q = &can_tx2_q; can_ring *tx3_q = &can_tx3_q; diff --git a/tests/loopback_test.py b/tests/loopback_test.py index d4f8bebf8..a95c2ea22 100755 --- a/tests/loopback_test.py +++ b/tests/loopback_test.py @@ -37,18 +37,18 @@ def run_test_w_pandas(pandas, sleep_duration): print("health", ho[0], h[ho[0]].health()) # **** test can line loopback **** - for bus, gmlan in [(0, False), (1, False), (2, False), (1, True), (2, True)]: + for bus, obd in [(0, False), (1, False), (2, False), (1, True), (2, True)]: print("\ntest can", bus) # flush cans_echo = panda0.can_recv() cans_loop = panda1.can_recv() - panda0.set_gmlan(None) - panda1.set_gmlan(None) + panda0.set_obd(None) + panda1.set_obd(None) - if gmlan is True: - panda0.set_gmlan(bus) - panda1.set_gmlan(bus) + if obd is True: + panda0.set_obd(bus) + panda1.set_obd(bus) bus = 3 # send the characters diff --git a/tests/safety/common.py b/tests/safety/common.py index 8179cff1f..e111ff7ef 100644 --- a/tests/safety/common.py +++ b/tests/safety/common.py @@ -690,8 +690,7 @@ class PandaSafetyTest(PandaSafetyTestBase): 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) + *range(0x3300, 0x3400)] # Honda FWD_BLACKLISTED_ADDRS: dict[int, list[int]] = {} # {bus: [addr]} FWD_BUS_LOOKUP: dict[int, int] = {} diff --git a/tests/safety/test_gm.py b/tests/safety/test_gm.py index 28b2ad50e..c6c5ac6b3 100755 --- a/tests/safety/test_gm.py +++ b/tests/safety/test_gm.py @@ -144,8 +144,7 @@ class TestGmSafetyBase(common.PandaCarSafetyTest, common.DriverTorqueSteeringSaf class TestGmAscmSafety(GmLongitudinalBase, TestGmSafetyBase): TX_MSGS = [[0x180, 0], [0x409, 0], [0x40A, 0], [0x2CB, 0], [0x370, 0], # pt bus [0xA1, 1], [0x306, 1], [0x308, 1], [0x310, 1], # obs bus - [0x315, 2], # ch bus - [0x104c006c, 3], [0x10400060, 3]] # gmlan + [0x315, 2]] # ch bus FWD_BLACKLISTED_ADDRS: dict[int, list[int]] = {} FWD_BUS_LOOKUP: dict[int, int] = {} BRAKE_BUS = 2 diff --git a/tests/tucan_loopback.py b/tests/tucan_loopback.py deleted file mode 100755 index 457facdff..000000000 --- a/tests/tucan_loopback.py +++ /dev/null @@ -1,92 +0,0 @@ -#!/usr/bin/env python3 - -import os -import time -import random -import argparse -from itertools import permutations - -from panda import Panda - -def get_test_string(): - return b"test" + os.urandom(10) - -def run_test(sleep_duration): - pandas = Panda.list() - print(pandas) - - if len(pandas) < 2: - raise Exception("Two pandas are needed for test") - - run_test_w_pandas(pandas, sleep_duration) - -def run_test_w_pandas(pandas, sleep_duration): - h = [Panda(x) for x in pandas] - print("H", h) - - for hh in h: - hh.set_safety_mode(Panda.SAFETY_ALLOUTPUT) - - # test both directions - for ho in permutations(list(range(len(h))), r=2): - print("***************** TESTING", ho) - - panda0, panda1 = h[ho[0]], h[ho[1]] - - # **** test health packet **** - print("health", ho[0], h[ho[0]].health()) - - # **** test can line loopback **** - # for bus, gmlan in [(0, None), (1, False), (2, False), (1, True), (2, True)]: - for bus, gmlan in [(0, None), (1, None)]: - print("\ntest can", bus) - # flush - cans_echo = panda0.can_recv() - cans_loop = panda1.can_recv() - - if gmlan is not None: - panda0.set_gmlan(gmlan, bus) - panda1.set_gmlan(gmlan, bus) - - # send the characters - # pick addresses high enough to not conflict with honda code - at = random.randint(1024, 2000) - st = get_test_string()[0:8] - panda0.can_send(at, st, bus) - time.sleep(0.1) - - # check for receive - cans_echo = panda0.can_recv() - cans_loop = panda1.can_recv() - - print("Bus", bus, "echo", cans_echo, "loop", cans_loop) - - assert len(cans_echo) == 1 - assert len(cans_loop) == 1 - - assert cans_echo[0][0] == at - assert cans_loop[0][0] == at - - assert cans_echo[0][2] == st - assert cans_loop[0][2] == st - - assert cans_echo[0][3] == 0x80 | bus - if cans_loop[0][3] != bus: - print("EXPECTED %d GOT %d" % (bus, cans_loop[0][3])) - assert cans_loop[0][3] == bus - - print("CAN pass", bus, ho) - time.sleep(sleep_duration) - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument("-n", type=int, help="Number of test iterations to run") - parser.add_argument("-sleep", type=int, help="Sleep time between tests", default=0) - args = parser.parse_args() - - if args.n is None: - while True: - run_test(sleep_duration=args.sleep) - else: - for _ in range(args.n): - run_test(sleep_duration=args.sleep) diff --git a/tests/usbprotocol/test_comms.py b/tests/usbprotocol/test_comms.py index c08551b70..8efefef7c 100755 --- a/tests/usbprotocol/test_comms.py +++ b/tests/usbprotocol/test_comms.py @@ -8,7 +8,7 @@ from panda.tests.libpanda import libpanda_py lpp = libpanda_py.libpanda CHUNK_SIZE = USBPACKET_MAX_SIZE -TX_QUEUES = (lpp.tx1_q, lpp.tx2_q, lpp.tx3_q, lpp.txgmlan_q) +TX_QUEUES = (lpp.tx1_q, lpp.tx2_q, lpp.tx3_q) def unpackage_can_msg(pkt): @@ -33,7 +33,7 @@ class TestPandaComms(unittest.TestCase): lpp.comms_can_reset() def test_tx_queues(self): - for bus in range(4): + for bus in range(len(TX_QUEUES)): message = (0x100, 0, b"test", bus) can_pkt_tx = libpanda_py.make_CANPacket(message[0], message[3], message[2]) From 8a845b973ea9fbe5daa09ef92dfc8938a4fbe789 Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Thu, 21 Mar 2024 20:28:44 -0700 Subject: [PATCH 48/67] boot time test (#1909) * test * usb serial * just test for now * time * close * close after --- Jenkinsfile | 2 +- python/__init__.py | 2 ++ tests/hitl/8_misc.py | 10 ++++++++++ 3 files changed, 13 insertions(+), 1 deletion(-) create mode 100644 tests/hitl/8_misc.py diff --git a/Jenkinsfile b/Jenkinsfile index 25b8490a0..23a249b30 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 -n0 --durations=0 [2-7]*.py -k 'not test_send_recv'"], + ["test", "cd tests/hitl && HW_TYPES=6 pytest -n0 --durations=0 [2-9]*.py -k 'not test_send_recv'"], ]) } } diff --git a/python/__init__.py b/python/__init__.py index c2bfa5a03..f97f608ad 100644 --- a/python/__init__.py +++ b/python/__init__.py @@ -433,6 +433,8 @@ class Panda: self._handle.controlWrite(Panda.REQUEST_IN, 0xd8, 0, 0, b'', timeout=timeout, expect_disconnect=True) except Exception: pass + + self.close() if not enter_bootloader and reconnect: self.reconnect() diff --git a/tests/hitl/8_misc.py b/tests/hitl/8_misc.py new file mode 100644 index 000000000..63e1c3e8c --- /dev/null +++ b/tests/hitl/8_misc.py @@ -0,0 +1,10 @@ +import time + +from panda import Panda + +def test_boot_time(p): + # boot time should be instant + st = time.monotonic() + p.reset(reconnect=False) + assert Panda.wait_for_panda(p.get_usb_serial(), timeout=3.0) + assert time.monotonic() - st < 3.0 From 0714642491c6b0b4a48a6c3e6d95ab593ba0da48 Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Thu, 21 Mar 2024 21:56:24 -0700 Subject: [PATCH 49/67] remove old disable tests from jenkinsfile --- Jenkinsfile | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index 23a249b30..2d4c615df 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -130,24 +130,6 @@ pipeline { } } } - - /* - stage('HITL tests') { - steps { - script { - docker_run("parallel tests", 5, 'PANDAS_JUNGLE=23002d000851393038373731 PANDAS_EXCLUDE="1d0002000c51303136383232 2f002e000c51303136383232" ./tests/hitl/run_parallel_tests.sh') - docker_run("serial tests", 9, 'PANDAS_JUNGLE=23002d000851393038373731 PANDAS_EXCLUDE="1d0002000c51303136383232 2f002e000c51303136383232" ./tests/hitl/run_serial_tests.sh') - } - } - } - stage('CANFD tests') { - steps { - script { - docker_run("CANFD tets", 6, 'JUNGLE=058010800f51363038363036 H7_PANDAS_EXCLUDE="080021000c51303136383232 33000e001051393133353939" ./tests/canfd/test_canfd.py') - } - } - } - */ } } } From 6b40f82bc4e38ca5aca3f930cad579d77777a01f Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Fri, 22 Mar 2024 10:30:02 -0700 Subject: [PATCH 50/67] harness HITL test refactor (#1911) * harness HITL tests * cleanup * oops * unused --- tests/hitl/2_health.py | 60 ----------------------------------------- tests/hitl/9_harness.py | 51 +++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 60 deletions(-) create mode 100644 tests/hitl/9_harness.py diff --git a/tests/hitl/2_health.py b/tests/hitl/2_health.py index acb993f50..12c75f561 100644 --- a/tests/hitl/2_health.py +++ b/tests/hitl/2_health.py @@ -2,66 +2,6 @@ import time import pytest from panda import Panda -from panda import PandaJungle -from panda.tests.hitl.conftest import PandaGroup - - -def test_ignition(p, panda_jungle): - # Set harness orientation to #2, since the ignition line is on the wrong SBU bus :/ - panda_jungle.set_harness_orientation(PandaJungle.HARNESS_ORIENTATION_2) - p.reset() - - for ign in (True, False): - panda_jungle.set_ignition(ign) - time.sleep(0.1) - assert p.health()['ignition_line'] == ign - - -@pytest.mark.test_panda_types(PandaGroup.GEN2) -def test_harness_status(p, panda_jungle): - flipped = None - for ignition in [True, False]: - for orientation in [Panda.HARNESS_STATUS_NC, Panda.HARNESS_STATUS_NORMAL, Panda.HARNESS_STATUS_FLIPPED]: - panda_jungle.set_harness_orientation(orientation) - panda_jungle.set_ignition(ignition) - time.sleep(1) - - health = p.health() - detected_orientation = health['car_harness_status'] - print(f"set: {orientation} detected: {detected_orientation}") - - # Orientation - if orientation == Panda.HARNESS_STATUS_NC: - assert detected_orientation == Panda.HARNESS_STATUS_NC - else: - if flipped is None: - flipped = (detected_orientation != orientation) - - if orientation == Panda.HARNESS_STATUS_NORMAL: - assert detected_orientation == (Panda.HARNESS_STATUS_FLIPPED if flipped else Panda.HARNESS_STATUS_NORMAL) - else: - assert detected_orientation == (Panda.HARNESS_STATUS_NORMAL if flipped else Panda.HARNESS_STATUS_FLIPPED) - - # Line ignition - assert health['ignition_line'] == (False if orientation == Panda.HARNESS_STATUS_NC else ignition) - - # SBU voltages - supply_voltage_mV = 1800 if p.get_type() in [Panda.HW_TYPE_TRES, ] else 3300 - - if orientation == Panda.HARNESS_STATUS_NC: - assert health['sbu1_voltage_mV'] > 0.9 * supply_voltage_mV - assert health['sbu2_voltage_mV'] > 0.9 * supply_voltage_mV - else: - relay_line = 'sbu1_voltage_mV' if (detected_orientation == Panda.HARNESS_STATUS_FLIPPED) else 'sbu2_voltage_mV' - ignition_line = 'sbu2_voltage_mV' if (detected_orientation == Panda.HARNESS_STATUS_FLIPPED) else 'sbu1_voltage_mV' - - assert health[relay_line] < 0.1 * supply_voltage_mV - assert health[ignition_line] > health[relay_line] - if ignition: - assert health[ignition_line] < 0.3 * supply_voltage_mV - else: - assert health[ignition_line] > 0.9 * supply_voltage_mV - @pytest.mark.skip_panda_types((Panda.HW_TYPE_DOS, )) diff --git a/tests/hitl/9_harness.py b/tests/hitl/9_harness.py new file mode 100644 index 000000000..54cf5b309 --- /dev/null +++ b/tests/hitl/9_harness.py @@ -0,0 +1,51 @@ +import time +import pytest + +from panda import Panda +from panda.tests.hitl.conftest import PandaGroup + + +@pytest.mark.parametrize("ignition", [True, False]) +@pytest.mark.parametrize("orientation", [Panda.HARNESS_STATUS_NC, Panda.HARNESS_STATUS_NORMAL, Panda.HARNESS_STATUS_FLIPPED]) +@pytest.mark.test_panda_types(PandaGroup.GEN2) +def test_harness_status(p, panda_jungle, ignition, orientation): + flipped = None + panda_jungle.set_harness_orientation(orientation) + panda_jungle.set_ignition(ignition) + time.sleep(0.25) # updated at 8Hz + + health = p.health() + detected_orientation = health['car_harness_status'] + print(f"set: {orientation} detected: {detected_orientation}") + + # Orientation + if orientation == Panda.HARNESS_STATUS_NC: + assert detected_orientation == Panda.HARNESS_STATUS_NC + else: + if flipped is None: + flipped = (detected_orientation != orientation) + + if orientation == Panda.HARNESS_STATUS_NORMAL: + assert detected_orientation == (Panda.HARNESS_STATUS_FLIPPED if flipped else Panda.HARNESS_STATUS_NORMAL) + else: + assert detected_orientation == (Panda.HARNESS_STATUS_NORMAL if flipped else Panda.HARNESS_STATUS_FLIPPED) + + # Line ignition + assert health['ignition_line'] == (False if orientation == Panda.HARNESS_STATUS_NC else ignition) + + # SBU voltages + supply_voltage_mV = 1800 if p.get_type() in [Panda.HW_TYPE_TRES, ] else 3300 + + if orientation == Panda.HARNESS_STATUS_NC: + assert health['sbu1_voltage_mV'] > 0.9 * supply_voltage_mV + assert health['sbu2_voltage_mV'] > 0.9 * supply_voltage_mV + else: + relay_line = 'sbu1_voltage_mV' if (detected_orientation == Panda.HARNESS_STATUS_FLIPPED) else 'sbu2_voltage_mV' + ignition_line = 'sbu2_voltage_mV' if (detected_orientation == Panda.HARNESS_STATUS_FLIPPED) else 'sbu1_voltage_mV' + + assert health[relay_line] < 0.1 * supply_voltage_mV + assert health[ignition_line] > health[relay_line] + if ignition: + assert health[ignition_line] < 0.3 * supply_voltage_mV + else: + assert health[ignition_line] > 0.9 * supply_voltage_mV From b46a9eb2c9f5c671797a7b17b8a35a11e510dfde Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Fri, 22 Mar 2024 13:32:31 -0700 Subject: [PATCH 51/67] CAN orientation HITL test (#1912) test Co-authored-by: Comma Device --- tests/hitl/9_harness.py | 104 +++++++++++++++++++++++++--------------- tests/hitl/conftest.py | 3 +- 2 files changed, 68 insertions(+), 39 deletions(-) diff --git a/tests/hitl/9_harness.py b/tests/hitl/9_harness.py index 54cf5b309..4931b77fb 100644 --- a/tests/hitl/9_harness.py +++ b/tests/hitl/9_harness.py @@ -1,51 +1,79 @@ import time import pytest +import itertools from panda import Panda from panda.tests.hitl.conftest import PandaGroup -@pytest.mark.parametrize("ignition", [True, False]) -@pytest.mark.parametrize("orientation", [Panda.HARNESS_STATUS_NC, Panda.HARNESS_STATUS_NORMAL, Panda.HARNESS_STATUS_FLIPPED]) +@pytest.mark.panda_expect_can_error @pytest.mark.test_panda_types(PandaGroup.GEN2) -def test_harness_status(p, panda_jungle, ignition, orientation): - flipped = None - panda_jungle.set_harness_orientation(orientation) - panda_jungle.set_ignition(ignition) - time.sleep(0.25) # updated at 8Hz +def test_harness_status(p, panda_jungle): + # map from jungle orientations to panda orientations + orientation_map = { + Panda.HARNESS_STATUS_NC: Panda.HARNESS_STATUS_NC, + } - health = p.health() - detected_orientation = health['car_harness_status'] - print(f"set: {orientation} detected: {detected_orientation}") + # this shouldn't be parameterized since we don't want the panda to be reset + # between the tests. + for ignition, orientation in itertools.product([True, False], [Panda.HARNESS_STATUS_NC, Panda.HARNESS_STATUS_NORMAL, Panda.HARNESS_STATUS_FLIPPED]): + print() + p.set_safety_mode(Panda.SAFETY_ELM327) + panda_jungle.set_harness_orientation(orientation) + panda_jungle.set_ignition(ignition) - # Orientation - if orientation == Panda.HARNESS_STATUS_NC: - assert detected_orientation == Panda.HARNESS_STATUS_NC - else: - if flipped is None: - flipped = (detected_orientation != orientation) + # wait for orientation detection + time.sleep(0.25) - if orientation == Panda.HARNESS_STATUS_NORMAL: - assert detected_orientation == (Panda.HARNESS_STATUS_FLIPPED if flipped else Panda.HARNESS_STATUS_NORMAL) + health = p.health() + detected_orientation = health['car_harness_status'] + print(f"orientation set: {orientation} detected: {detected_orientation}") + + if detected_orientation not in orientation_map: + assert detected_orientation != Panda.HARNESS_STATUS_NC + other = {Panda.HARNESS_STATUS_NORMAL: Panda.HARNESS_STATUS_FLIPPED, Panda.HARNESS_STATUS_FLIPPED: Panda.HARNESS_STATUS_NORMAL} + orientation_map.update({ + orientation: detected_orientation, + other[orientation]: other[detected_orientation], + }) + + # Orientation + assert orientation_map[detected_orientation] == orientation + + # Line ignition + assert health['ignition_line'] == (False if orientation == Panda.HARNESS_STATUS_NC else ignition) + + # TODO: also test relay + # CAN traffic + if orientation != Panda.HARNESS_STATUS_NC: + for bus in range(3): + panda_jungle.can_send(0x123, f"{bus}".encode(), bus) + time.sleep(0.5) + + msgs = p.can_recv() + buses = {int(dat): bus for _, _, dat, bus in msgs if bus <= 3} + + print(msgs) + print(buses) + + # FIXME: CAN orientation doesn't update live in panda + # jungle doesn't actually switch buses when switching orientation + assert buses[0] == 0 + assert buses[2] == 2 + + # SBU voltages + supply_voltage_mV = 1800 if p.get_type() in [Panda.HW_TYPE_TRES, ] else 3300 + + if orientation == Panda.HARNESS_STATUS_NC: + assert health['sbu1_voltage_mV'] > 0.9 * supply_voltage_mV + assert health['sbu2_voltage_mV'] > 0.9 * supply_voltage_mV else: - assert detected_orientation == (Panda.HARNESS_STATUS_NORMAL if flipped else Panda.HARNESS_STATUS_FLIPPED) + relay_line = 'sbu1_voltage_mV' if (detected_orientation == Panda.HARNESS_STATUS_FLIPPED) else 'sbu2_voltage_mV' + ignition_line = 'sbu2_voltage_mV' if (detected_orientation == Panda.HARNESS_STATUS_FLIPPED) else 'sbu1_voltage_mV' - # Line ignition - assert health['ignition_line'] == (False if orientation == Panda.HARNESS_STATUS_NC else ignition) - - # SBU voltages - supply_voltage_mV = 1800 if p.get_type() in [Panda.HW_TYPE_TRES, ] else 3300 - - if orientation == Panda.HARNESS_STATUS_NC: - assert health['sbu1_voltage_mV'] > 0.9 * supply_voltage_mV - assert health['sbu2_voltage_mV'] > 0.9 * supply_voltage_mV - else: - relay_line = 'sbu1_voltage_mV' if (detected_orientation == Panda.HARNESS_STATUS_FLIPPED) else 'sbu2_voltage_mV' - ignition_line = 'sbu2_voltage_mV' if (detected_orientation == Panda.HARNESS_STATUS_FLIPPED) else 'sbu1_voltage_mV' - - assert health[relay_line] < 0.1 * supply_voltage_mV - assert health[ignition_line] > health[relay_line] - if ignition: - assert health[ignition_line] < 0.3 * supply_voltage_mV - else: - assert health[ignition_line] > 0.9 * supply_voltage_mV + assert health[relay_line] < 0.1 * supply_voltage_mV + assert health[ignition_line] > health[relay_line] + if ignition: + assert health[ignition_line] < 0.3 * supply_voltage_mV + else: + assert health[ignition_line] > 0.9 * supply_voltage_mV diff --git a/tests/hitl/conftest.py b/tests/hitl/conftest.py index 7a6e1b100..1c4db1e92 100644 --- a/tests/hitl/conftest.py +++ b/tests/hitl/conftest.py @@ -133,7 +133,8 @@ def func_fixture_panda(request, module_panda): if _all_pandas[p.get_usb_serial()] in skip_types: pytest.skip(f"Not applicable to {skip_types}") - # TODO: reset is slow (2+ seconds) + # this is 2+ seconds on USB pandas due to slow + # enumeration on the host side p.reset() # ensure FW hasn't changed From 091773f44816bf66a55ae25fc455effb2ec20979 Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Fri, 22 Mar 2024 14:00:13 -0700 Subject: [PATCH 52/67] Adjust CAN bus orientation live with harness orientation (#1913) * set orientation in one place * no flip * cleanup * more explict on startup --------- Co-authored-by: Comma Device --- board/boards/black.h | 5 ----- board/boards/dos.h | 5 ----- board/boards/red.h | 5 ----- board/boards/red_chiplet.h | 5 ----- board/boards/uno.h | 5 ----- board/bootstub_declarations.h | 2 -- board/drivers/can_common.h | 16 +++++++--------- board/main.c | 13 +++++++++++++ board/main_declarations.h | 1 - tests/hitl/9_harness.py | 10 ++++------ 10 files changed, 24 insertions(+), 43 deletions(-) diff --git a/board/boards/black.h b/board/boards/black.h index 917193893..858ade2e2 100644 --- a/board/boards/black.h +++ b/board/boards/black.h @@ -133,11 +133,6 @@ void black_init(void) { // Set normal CAN mode black_set_can_mode(CAN_MODE_NORMAL); - - // change CAN mapping when flipped - if (harness.status == HARNESS_STATUS_FLIPPED) { - can_flip_buses(0, 2); - } } void black_init_bootloader(void) { diff --git a/board/boards/dos.h b/board/boards/dos.h index ca98ad967..381ce8413 100644 --- a/board/boards/dos.h +++ b/board/boards/dos.h @@ -162,11 +162,6 @@ void dos_init(void) { // Set normal CAN mode dos_set_can_mode(CAN_MODE_NORMAL); - // change CAN mapping when flipped - if (harness.status == HARNESS_STATUS_FLIPPED) { - can_flip_buses(0, 2); - } - // Init clock source (camera strobe) using PWM clock_source_init(); } diff --git a/board/boards/red.h b/board/boards/red.h index 2ba9f3566..90d97c4f1 100644 --- a/board/boards/red.h +++ b/board/boards/red.h @@ -151,11 +151,6 @@ void red_init(void) { // Set normal CAN mode red_set_can_mode(CAN_MODE_NORMAL); - - // change CAN mapping when flipped - if (harness.status == HARNESS_STATUS_FLIPPED) { - can_flip_buses(0, 2); - } } const harness_configuration red_harness_config = { diff --git a/board/boards/red_chiplet.h b/board/boards/red_chiplet.h index 8b0f9333f..f6c028be1 100644 --- a/board/boards/red_chiplet.h +++ b/board/boards/red_chiplet.h @@ -130,11 +130,6 @@ void red_chiplet_init(void) { // Set normal CAN mode red_chiplet_set_can_mode(CAN_MODE_NORMAL); - - // change CAN mapping when flipped - if (harness.status == HARNESS_STATUS_FLIPPED) { - can_flip_buses(0, 2); - } } const harness_configuration red_chiplet_harness_config = { diff --git a/board/boards/uno.h b/board/boards/uno.h index 3c6ce177b..ce69f6cfe 100644 --- a/board/boards/uno.h +++ b/board/boards/uno.h @@ -159,11 +159,6 @@ void uno_init(void) { // Set normal CAN mode uno_set_can_mode(CAN_MODE_NORMAL); - // change CAN mapping when flipped - if (harness.status == HARNESS_STATUS_FLIPPED) { - can_flip_buses(0, 2); - } - // Switch to phone usb mode if harness connection is powered by less than 7V if(white_read_voltage_mV() < 7000U){ uno_set_usb_switch(true); diff --git a/board/bootstub_declarations.h b/board/bootstub_declarations.h index ae115d2eb..f61fb310c 100644 --- a/board/bootstub_declarations.h +++ b/board/bootstub_declarations.h @@ -6,8 +6,6 @@ void puth4(uint8_t i){ UNUSED(i); } void hexdump(const void *a, int l){ UNUSED(a); UNUSED(l); } typedef struct board board; typedef struct harness_configuration harness_configuration; -// No CAN support on bootloader -void can_flip_buses(uint8_t bus1, uint8_t bus2){UNUSED(bus1); UNUSED(bus2);} void pwm_init(TIM_TypeDef *TIM, uint8_t channel); void pwm_set(TIM_TypeDef *TIM, uint8_t channel, uint8_t percentage); // No UART support in bootloader diff --git a/board/drivers/can_common.h b/board/drivers/can_common.h index 57d2508cc..6b9b41fd9 100644 --- a/board/drivers/can_common.h +++ b/board/drivers/can_common.h @@ -153,7 +153,7 @@ void can_clear(can_ring *q) { } // assign CAN numbering -// bus num: Can bus number on ODB connector. Sent to/from USB +// bus num: CAN Bus numbers in panda, sent to/from USB // Min: 0; Max: 127; Bit 7 marks message as receipt (bus 129 is receipt for but 1) // cans: Look up MCU can interface from bus number // can number: numeric lookup for MCU CAN interfaces (0 = CAN1, 1 = CAN2, etc); @@ -175,22 +175,20 @@ bus_config_t bus_config[] = { #define CAN_NUM_FROM_BUS_NUM(num) (bus_config[num].can_num_lookup) void can_init_all(void) { - bool ret = true; for (uint8_t i=0U; i < PANDA_CAN_CNT; i++) { if (!current_board->has_canfd) { bus_config[i].can_data_speed = 0U; } can_clear(can_queues[i]); - ret &= can_init(i); + (void)can_init(i); } - UNUSED(ret); } -void can_flip_buses(uint8_t bus1, uint8_t bus2){ - bus_config[bus1].bus_lookup = bus2; - bus_config[bus2].bus_lookup = bus1; - bus_config[bus1].can_num_lookup = bus2; - bus_config[bus2].can_num_lookup = bus1; +void can_set_orientation(bool flipped) { + bus_config[0].bus_lookup = flipped ? 2U : 0U; + bus_config[0].can_num_lookup = flipped ? 2U : 0U; + bus_config[2].bus_lookup = flipped ? 0U : 2U; + bus_config[2].can_num_lookup = flipped ? 0U : 2U; } void can_set_forwarding(uint8_t from, uint8_t to) { diff --git a/board/main.c b/board/main.c index 3649cc920..0d66b52d7 100644 --- a/board/main.c +++ b/board/main.c @@ -144,8 +144,10 @@ void __attribute__ ((noinline)) enable_fpu(void) { // called at 8Hz uint8_t loop_counter = 0U; +uint8_t prev_harness_status = HARNESS_STATUS_NC; void tick_handler(void) { if (TICK_TIMER->SR != 0) { + // siren current_board->set_siren((loop_counter & 1U) && (siren_enabled || (siren_countdown > 0U))); @@ -155,6 +157,17 @@ void tick_handler(void) { harness_tick(); simple_watchdog_kick(); + // re-init everything that uses harness status + if (harness.status != prev_harness_status) { + prev_harness_status = harness.status; + can_set_orientation(harness.status == HARNESS_STATUS_FLIPPED); + + // re-init everything that uses harness status + can_init_all(); + set_safety_mode(current_safety_mode, current_safety_param); + set_power_save_state(power_save_status); + } + // decimated to 1Hz if (loop_counter == 0U) { can_live = pending_can_live; diff --git a/board/main_declarations.h b/board/main_declarations.h index 4570c6e67..55e37636b 100644 --- a/board/main_declarations.h +++ b/board/main_declarations.h @@ -6,7 +6,6 @@ void puth4(unsigned int i); void hexdump(const void *a, int l); typedef struct board board; typedef struct harness_configuration harness_configuration; -void can_flip_buses(uint8_t bus1, uint8_t bus2); void pwm_init(TIM_TypeDef *TIM, uint8_t channel); void pwm_set(TIM_TypeDef *TIM, uint8_t channel, uint8_t percentage); diff --git a/tests/hitl/9_harness.py b/tests/hitl/9_harness.py index 4931b77fb..5689892b8 100644 --- a/tests/hitl/9_harness.py +++ b/tests/hitl/9_harness.py @@ -5,6 +5,7 @@ import itertools from panda import Panda from panda.tests.hitl.conftest import PandaGroup +# TODO: test relay @pytest.mark.panda_expect_can_error @pytest.mark.test_panda_types(PandaGroup.GEN2) @@ -43,7 +44,6 @@ def test_harness_status(p, panda_jungle): # Line ignition assert health['ignition_line'] == (False if orientation == Panda.HARNESS_STATUS_NC else ignition) - # TODO: also test relay # CAN traffic if orientation != Panda.HARNESS_STATUS_NC: for bus in range(3): @@ -52,14 +52,12 @@ def test_harness_status(p, panda_jungle): msgs = p.can_recv() buses = {int(dat): bus for _, _, dat, bus in msgs if bus <= 3} - print(msgs) - print(buses) - # FIXME: CAN orientation doesn't update live in panda # jungle doesn't actually switch buses when switching orientation - assert buses[0] == 0 - assert buses[2] == 2 + flipped = orientation == Panda.HARNESS_STATUS_FLIPPED + assert buses[0] == (2 if flipped else 0) + assert buses[2] == (0 if flipped else 2) # SBU voltages supply_voltage_mV = 1800 if p.get_type() in [Panda.HW_TYPE_TRES, ] else 3300 From dd82382d5f9fcfbf9958238ee33739693fd3f6fa Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Fri, 22 Mar 2024 14:01:44 -0700 Subject: [PATCH 53/67] instant boot (#1910) no more boot time :P --- board/drivers/harness.h | 5 ----- python/__init__.py | 4 ++++ tests/hitl/8_misc.py | 5 ++++- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/board/drivers/harness.h b/board/drivers/harness.h index 60f99fc85..bfe61050a 100644 --- a/board/drivers/harness.h +++ b/board/drivers/harness.h @@ -117,11 +117,6 @@ void harness_tick(void) { } void harness_init(void) { - // delay such that the connection is fully made before trying orientation detection - current_board->set_led(LED_BLUE, true); - delay(10000000); - current_board->set_led(LED_BLUE, false); - // try to detect orientation harness.status = harness_detect_orientation(); if (harness.status != HARNESS_STATUS_NC) { diff --git a/python/__init__.py b/python/__init__.py index f97f608ad..ba1f107d2 100644 --- a/python/__init__.py +++ b/python/__init__.py @@ -304,6 +304,10 @@ class Panda: for bus in range(PANDA_BUS_CNT): self.set_can_speed_kbps(bus, self._can_speed_kbps) + @property + def spi(self) -> bool: + return isinstance(self._handle, PandaSpiHandle) + @classmethod def spi_connect(cls, serial, ignore_version=False): # get UID to confirm slave is present and up diff --git a/tests/hitl/8_misc.py b/tests/hitl/8_misc.py index 63e1c3e8c..3c47ed492 100644 --- a/tests/hitl/8_misc.py +++ b/tests/hitl/8_misc.py @@ -7,4 +7,7 @@ def test_boot_time(p): st = time.monotonic() p.reset(reconnect=False) assert Panda.wait_for_panda(p.get_usb_serial(), timeout=3.0) - assert time.monotonic() - st < 3.0 + + # USB enumeration is slow, so SPI is faster + assert time.monotonic() - st < (1.0 if p.spi else 5.0) + From a727cecdb8eceddb233efa2df66c91b5017226eb Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Fri, 22 Mar 2024 14:48:49 -0700 Subject: [PATCH 54/67] remove unused deepsleep stuff (#1914) --- board/config.h | 1 - board/main.c | 27 --------------- board/main_comms.h | 4 --- board/main_declarations.h | 4 --- board/stm32f4/llexti.h | 56 ------------------------------ board/stm32f4/stm32f4_config.h | 4 --- board/stm32h7/llexti.h | 63 ---------------------------------- board/stm32h7/stm32h7_config.h | 4 --- python/__init__.py | 3 -- 9 files changed, 166 deletions(-) delete mode 100644 board/stm32f4/llexti.h delete mode 100644 board/stm32h7/llexti.h diff --git a/board/config.h b/board/config.h index 56703522b..ef9ffcb8d 100644 --- a/board/config.h +++ b/board/config.h @@ -11,7 +11,6 @@ //#define DEBUG_FAN #define CAN_INIT_TIMEOUT_MS 500U -#define DEEPSLEEP_WAKEUP_DELAY 3U #define USBPACKET_MAX_SIZE 0x40U #define MAX_CAN_MSGS_PER_USB_BULK_TRANSFER 51U #define MAX_CAN_MSGS_PER_SPI_BULK_TRANSFER 170U diff --git a/board/main.c b/board/main.c index 0d66b52d7..8e6434e69 100644 --- a/board/main.c +++ b/board/main.c @@ -33,7 +33,6 @@ bool check_started(void) { bool started = current_board->check_ignition() || ignition_can; - ignition_seen |= started; return started; } @@ -292,20 +291,6 @@ void tick_handler(void) { TICK_TIMER->SR = 0; } -void EXTI_IRQ_Handler(void) { - if (check_exti_irq()) { - exti_irq_clear(); - clock_init(); - - set_power_save_state(POWER_SAVE_STATUS_DISABLED); - deepsleep_allowed = false; - heartbeat_counter = 0U; - usb_soft_disconnect(false); - - NVIC_EnableIRQ(TICK_TIMER_IRQ); - } -} - int main(void) { // Init interrupt table init_interrupts(true); @@ -407,18 +392,6 @@ int main(void) { } #endif } else { - if (deepsleep_allowed && !usb_enumerated && !check_started() && ignition_seen && (heartbeat_counter > 20U)) { - usb_soft_disconnect(true); - fan_set_power(0U); - NVIC_DisableIRQ(TICK_TIMER_IRQ); - delay(512000U); - - // Init IRQs for CAN transceiver and ignition line - exti_irq_init(); - - // STOP mode - SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; - } __WFI(); SCB->SCR &= ~SCB_SCR_SLEEPDEEP_Msk; } diff --git a/board/main_comms.h b/board/main_comms.h index 830ef83b4..4c5d50962 100644 --- a/board/main_comms.h +++ b/board/main_comms.h @@ -374,10 +374,6 @@ int comms_control_handler(ControlPacket_t *req, uint8_t *resp) { UNUSED(ret); } break; - // **** 0xfb: allow highest power saving mode (stop) to be entered - case 0xfb: - deepsleep_allowed = true; - break; // **** 0xfc: set CAN FD non-ISO mode case 0xfc: if ((req->param1 < PANDA_CAN_CNT) && current_board->has_canfd) { diff --git a/board/main_declarations.h b/board/main_declarations.h index 55e37636b..fa860b86c 100644 --- a/board/main_declarations.h +++ b/board/main_declarations.h @@ -20,10 +20,6 @@ uint32_t heartbeat_counter = 0; bool heartbeat_lost = false; bool heartbeat_disabled = false; // set over USB -// Enter deep sleep mode -bool deepsleep_allowed = false; -bool ignition_seen = false; - // siren state bool siren_enabled = false; uint32_t siren_countdown = 0; // siren plays while countdown > 0 diff --git a/board/stm32f4/llexti.h b/board/stm32f4/llexti.h deleted file mode 100644 index 6de13ab7f..000000000 --- a/board/stm32f4/llexti.h +++ /dev/null @@ -1,56 +0,0 @@ -void EXTI_IRQ_Handler(void); - -void exti_irq_init(void) { - SYSCFG->EXTICR[2] &= ~(SYSCFG_EXTICR3_EXTI8_Msk); - if (harness.status == HARNESS_STATUS_FLIPPED) { - // CAN2_RX - current_board->enable_can_transceiver(3U, false); - SYSCFG->EXTICR[2] |= (SYSCFG_EXTICR3_EXTI8_PA); - - // IRQ on falling edge for PC3 (SBU2, EXTI3) - SYSCFG->EXTICR[0] &= ~(SYSCFG_EXTICR1_EXTI3_Msk); - SYSCFG->EXTICR[0] |= (SYSCFG_EXTICR1_EXTI3_PC); - EXTI->IMR |= EXTI_IMR_MR3; - EXTI->RTSR &= ~EXTI_RTSR_TR3; // rising edge - EXTI->FTSR |= EXTI_FTSR_TR3; // falling edge - REGISTER_INTERRUPT(EXTI3_IRQn, EXTI_IRQ_Handler, 100U, FAULT_INTERRUPT_RATE_EXTI) - NVIC_EnableIRQ(EXTI3_IRQn); - } else { - // CAN0_RX - current_board->enable_can_transceiver(1U, false); - SYSCFG->EXTICR[2] |= (SYSCFG_EXTICR3_EXTI8_PB); - - // IRQ on falling edge for PC0 (SBU1, EXTI0) - SYSCFG->EXTICR[0] &= ~(SYSCFG_EXTICR1_EXTI0_Msk); - SYSCFG->EXTICR[0] |= (SYSCFG_EXTICR1_EXTI0_PC); - EXTI->IMR |= EXTI_IMR_MR0; - EXTI->RTSR &= ~EXTI_RTSR_TR0; // rising edge - EXTI->FTSR |= EXTI_FTSR_TR0; // falling edge - REGISTER_INTERRUPT(EXTI0_IRQn, EXTI_IRQ_Handler, 100U, FAULT_INTERRUPT_RATE_EXTI) - NVIC_EnableIRQ(EXTI0_IRQn); - } - // CAN0 or CAN2 IRQ on falling edge (EXTI8) - EXTI->IMR |= EXTI_IMR_MR8; - EXTI->RTSR &= ~EXTI_RTSR_TR8; // rising edge - EXTI->FTSR |= EXTI_FTSR_TR8; // falling edge - REGISTER_INTERRUPT(EXTI9_5_IRQn, EXTI_IRQ_Handler, 100U, FAULT_INTERRUPT_RATE_EXTI) - NVIC_EnableIRQ(EXTI9_5_IRQn); -} - -bool check_exti_irq(void) { - return ((EXTI->PR & EXTI_PR_PR8) || (EXTI->PR & EXTI_PR_PR3) || (EXTI->PR & EXTI_PR_PR0)); -} - -void exti_irq_clear(void) { - // Clear pending bits - EXTI->PR |= EXTI_PR_PR8; - EXTI->PR |= EXTI_PR_PR0; - EXTI->PR |= EXTI_PR_PR3; - EXTI->PR |= EXTI_PR_PR22; - - // Disable all active EXTI IRQs - EXTI->IMR &= ~EXTI_IMR_MR8; - EXTI->IMR &= ~EXTI_IMR_MR0; - EXTI->IMR &= ~EXTI_IMR_MR3; - EXTI->IMR &= ~EXTI_IMR_MR22; -} diff --git a/board/stm32f4/stm32f4_config.h b/board/stm32f4/stm32f4_config.h index 3c6e547c9..85baff25b 100644 --- a/board/stm32f4/stm32f4_config.h +++ b/board/stm32f4/stm32f4_config.h @@ -65,10 +65,6 @@ #include "stm32f4/lluart.h" #endif -#if defined(PANDA) && !defined(BOOTSTUB) - #include "stm32f4/llexti.h" -#endif - #ifdef BOOTSTUB #include "stm32f4/llflash.h" #else diff --git a/board/stm32h7/llexti.h b/board/stm32h7/llexti.h deleted file mode 100644 index 46d0acab6..000000000 --- a/board/stm32h7/llexti.h +++ /dev/null @@ -1,63 +0,0 @@ -void EXTI_IRQ_Handler(void); - -void exti_irq_init(void) { - if (harness.status == HARNESS_STATUS_FLIPPED) { - // CAN2_RX IRQ on falling edge (EXTI10) - current_board->enable_can_transceiver(3U, false); - SYSCFG->EXTICR[2] &= ~(SYSCFG_EXTICR3_EXTI10_Msk); - SYSCFG->EXTICR[2] |= (SYSCFG_EXTICR3_EXTI10_PG); - EXTI->IMR1 |= EXTI_IMR1_IM10; - EXTI->RTSR1 &= ~EXTI_RTSR1_TR10; // rising edge - EXTI->FTSR1 |= EXTI_FTSR1_TR10; // falling edge - - // IRQ on falling edge for PA1 (SBU2, EXTI1) - SYSCFG->EXTICR[0] &= ~(SYSCFG_EXTICR1_EXTI1_Msk); - SYSCFG->EXTICR[0] |= (SYSCFG_EXTICR1_EXTI1_PA); - EXTI->IMR1 |= EXTI_IMR1_IM1; - EXTI->RTSR1 &= ~EXTI_RTSR1_TR1; // rising edge - EXTI->FTSR1 |= EXTI_FTSR1_TR1; // falling edge - REGISTER_INTERRUPT(EXTI1_IRQn, EXTI_IRQ_Handler, 100U, FAULT_INTERRUPT_RATE_EXTI) - NVIC_EnableIRQ(EXTI1_IRQn); - REGISTER_INTERRUPT(EXTI15_10_IRQn, EXTI_IRQ_Handler, 100U, FAULT_INTERRUPT_RATE_EXTI) - NVIC_EnableIRQ(EXTI15_10_IRQn); - } else { - // CAN0_RX IRQ on falling edge (EXTI8) - current_board->enable_can_transceiver(1U, false); - SYSCFG->EXTICR[2] &= ~(SYSCFG_EXTICR3_EXTI8_Msk); - SYSCFG->EXTICR[2] |= (SYSCFG_EXTICR3_EXTI8_PB); - EXTI->IMR1 |= EXTI_IMR1_IM8; - EXTI->RTSR1 &= ~EXTI_RTSR1_TR8; // rising edge - EXTI->FTSR1 |= EXTI_FTSR1_TR8; // falling edge - - // IRQ on falling edge for PC4 (SBU1, EXTI4) - SYSCFG->EXTICR[1] &= ~(SYSCFG_EXTICR2_EXTI4_Msk); - SYSCFG->EXTICR[1] |= (SYSCFG_EXTICR2_EXTI4_PC); - EXTI->IMR1 |= EXTI_IMR1_IM4; - EXTI->RTSR1 &= ~EXTI_RTSR1_TR4; // rising edge - EXTI->FTSR1 |= EXTI_FTSR1_TR4; // falling edge - REGISTER_INTERRUPT(EXTI4_IRQn, EXTI_IRQ_Handler, 100U, FAULT_INTERRUPT_RATE_EXTI) - NVIC_EnableIRQ(EXTI4_IRQn); - REGISTER_INTERRUPT(EXTI9_5_IRQn, EXTI_IRQ_Handler, 100U, FAULT_INTERRUPT_RATE_EXTI) - NVIC_EnableIRQ(EXTI9_5_IRQn); - } -} - -bool check_exti_irq(void) { - return ((EXTI->PR1 & EXTI_PR1_PR8) || (EXTI->PR1 & EXTI_PR1_PR10) || (EXTI->PR1 & EXTI_PR1_PR1) || (EXTI->PR1 & EXTI_PR1_PR4)); -} - -void exti_irq_clear(void) { - // Clear pending bits - EXTI->PR1 |= EXTI_PR1_PR8; - EXTI->PR1 |= EXTI_PR1_PR10; - EXTI->PR1 |= EXTI_PR1_PR4; - EXTI->PR1 |= EXTI_PR1_PR1; // works - EXTI->PR1 |= EXTI_PR1_PR19; // works - - // Disable all active EXTI IRQs - EXTI->IMR1 &= ~EXTI_IMR1_IM8; - EXTI->IMR1 &= ~EXTI_IMR1_IM10; - EXTI->IMR1 &= ~EXTI_IMR1_IM4; - EXTI->IMR1 &= ~EXTI_IMR1_IM1; - EXTI->IMR1 &= ~EXTI_IMR1_IM19; -} diff --git a/board/stm32h7/stm32h7_config.h b/board/stm32h7/stm32h7_config.h index 6f36a5aaf..64f149848 100644 --- a/board/stm32h7/stm32h7_config.h +++ b/board/stm32h7/stm32h7_config.h @@ -76,10 +76,6 @@ separate IRQs for RX and TX. #include "stm32h7/board.h" #include "stm32h7/clock.h" -#if !defined(BOOTSTUB) && defined(PANDA) - #include "stm32h7/llexti.h" -#endif - #ifdef BOOTSTUB #include "stm32h7/llflash.h" #else diff --git a/python/__init__.py b/python/__init__.py index ba1f107d2..b69b30eae 100644 --- a/python/__init__.py +++ b/python/__init__.py @@ -751,9 +751,6 @@ class Panda: def set_power_save(self, power_save_enabled=0): self._handle.controlWrite(Panda.REQUEST_OUT, 0xe7, int(power_save_enabled), 0, b'') - def enable_deepsleep(self): - self._handle.controlWrite(Panda.REQUEST_OUT, 0xfb, 0, 0, b'') - def set_safety_mode(self, mode=SAFETY_SILENT, param=0): self._handle.controlWrite(Panda.REQUEST_OUT, 0xdc, mode, param, b'') From b08bc43a218a364d085c5dcc27ad5dfccc8c1594 Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Sat, 23 Mar 2024 18:23:44 -0700 Subject: [PATCH 55/67] update cppcheck to 2.13.4 (#1915) --- tests/misra/install.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/misra/install.sh b/tests/misra/install.sh index ecc0b3f0d..8b264aa61 100755 --- a/tests/misra/install.sh +++ b/tests/misra/install.sh @@ -10,7 +10,7 @@ fi cd $CPPCHECK_DIR -VERS="2.13.0" +VERS="2.13.4" git fetch --all --tags git checkout $VERS git cherry-pick -n f6b538e855f0bacea33c4074664628024ef39dc6 b11b42087ff29569bc3740f5aa07eb6616ea4f63 From dcc7b8400161b42493f2d334875436ac2b665e78 Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Sun, 24 Mar 2024 10:59:51 -0700 Subject: [PATCH 56/67] UID_BASE is always defined now --- board/drivers/spi.h | 2 -- board/drivers/usb.h | 26 +++++++++++--------------- 2 files changed, 11 insertions(+), 17 deletions(-) diff --git a/board/drivers/spi.h b/board/drivers/spi.h index 1a7b9be59..efccfc98c 100644 --- a/board/drivers/spi.h +++ b/board/drivers/spi.h @@ -73,10 +73,8 @@ uint16_t spi_version_packet(uint8_t *out) { uint16_t data_pos = 7U + 2U; // write serial - #ifdef UID_BASE (void)memcpy(&out[data_pos], ((uint8_t *)UID_BASE), 12); data_len += 12U; - #endif // HW type out[data_pos + data_len] = hw_type; diff --git a/board/drivers/usb.h b/board/drivers/usb.h index 5ecbea219..9ed500f81 100644 --- a/board/drivers/usb.h +++ b/board/drivers/usb.h @@ -551,23 +551,19 @@ void usb_setup(void) { USB_WritePacket((uint8_t*)string_product_desc, MIN(sizeof(string_product_desc), setup.b.wLength.w), 0); break; case STRING_OFFSET_ISERIAL: - #ifdef UID_BASE - response[0] = 0x02 + (12 * 4); - response[1] = 0x03; + response[0] = 0x02 + (12 * 4); + response[1] = 0x03; - // 96 bits = 12 bytes - for (int i = 0; i < 12; i++){ - uint8_t cc = ((uint8_t *)UID_BASE)[i]; - response[2 + (i * 4)] = to_hex_char((cc >> 4) & 0xFU); - response[2 + (i * 4) + 1] = '\0'; - response[2 + (i * 4) + 2] = to_hex_char((cc >> 0) & 0xFU); - response[2 + (i * 4) + 3] = '\0'; - } + // 96 bits = 12 bytes + for (int i = 0; i < 12; i++){ + uint8_t cc = ((uint8_t *)UID_BASE)[i]; + response[2 + (i * 4)] = to_hex_char((cc >> 4) & 0xFU); + response[2 + (i * 4) + 1] = '\0'; + response[2 + (i * 4) + 2] = to_hex_char((cc >> 0) & 0xFU); + response[2 + (i * 4) + 3] = '\0'; + } - USB_WritePacket(response, MIN(response[0], setup.b.wLength.w), 0); - #else - USB_WritePacket((const uint8_t *)string_serial_desc, MIN(sizeof(string_serial_desc), setup.b.wLength.w), 0); - #endif + USB_WritePacket(response, MIN(response[0], setup.b.wLength.w), 0); break; case STRING_OFFSET_ICONFIGURATION: USB_WritePacket((uint8_t*)string_configuration_desc, MIN(sizeof(string_configuration_desc), setup.b.wLength.w), 0); From 418fca3583675a308a82e1043a5b11a7821e8c07 Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Sun, 24 Mar 2024 12:10:37 -0700 Subject: [PATCH 57/67] enable misra-config checks (#1879) * mostly done * fix rest of misra-config * do other two in next pr --- board/boards/tres.h | 2 +- board/drivers/bxcan.h | 6 +- board/drivers/clock_source.h | 4 +- board/drivers/fake_siren.h | 6 +- board/drivers/fdcan.h | 14 ++-- board/drivers/interrupts.h | 2 +- board/drivers/spi.h | 2 +- board/drivers/usb.h | 136 ++++++++++++++++----------------- board/main.c | 4 +- board/safety/safety_chrysler.h | 5 +- board/safety/safety_gm.h | 6 +- board/safety/safety_honda.h | 3 +- board/stm32f4/clock.h | 4 +- board/stm32f4/lluart.h | 4 +- board/stm32f4/llusb.h | 4 +- board/stm32h7/clock.h | 8 +- board/stm32h7/lladc.h | 8 +- board/stm32h7/llfdcan.h | 8 +- board/stm32h7/lli2c.h | 10 +-- board/stm32h7/llspi.h | 2 +- board/stm32h7/lluart.h | 2 +- board/stm32h7/llusb.h | 2 +- tests/misra/suppressions.txt | 9 ++- tests/misra/test_misra.sh | 14 ++-- 24 files changed, 139 insertions(+), 126 deletions(-) diff --git a/board/boards/tres.h b/board/boards/tres.h index 50d55e280..14a02bea7 100644 --- a/board/boards/tres.h +++ b/board/boards/tres.h @@ -33,7 +33,7 @@ void tres_init(void) { // Enable USB 3.3V LDO for USB block register_set_bits(&(PWR->CR3), PWR_CR3_USBREGEN); register_set_bits(&(PWR->CR3), PWR_CR3_USB33DEN); - while ((PWR->CR3 & PWR_CR3_USB33RDY) == 0); + while ((PWR->CR3 & PWR_CR3_USB33RDY) == 0U); red_chiplet_init(); diff --git a/board/drivers/bxcan.h b/board/drivers/bxcan.h index ea2705d9d..27ffcee52 100644 --- a/board/drivers/bxcan.h +++ b/board/drivers/bxcan.h @@ -48,7 +48,7 @@ void update_can_health_pkt(uint8_t can_number, uint32_t ir_reg) { can_health[can_number].total_error_cnt += 1U; // RX message lost due to FIFO overrun - if ((CANx->RF0R & (CAN_RF0R_FOVR0)) != 0) { + if ((CANx->RF0R & (CAN_RF0R_FOVR0)) != 0U) { can_health[can_number].total_rx_lost_cnt += 1U; CANx->RF0R &= ~(CAN_RF0R_FOVR0); } @@ -74,7 +74,7 @@ void process_can(uint8_t can_number) { // check for empty mailbox CANPacket_t to_send; - if ((CANx->TSR & (CAN_TSR_TERR0 | CAN_TSR_ALST0)) != 0) { // last TX failed due to error arbitration lost + if ((CANx->TSR & (CAN_TSR_TERR0 | CAN_TSR_ALST0)) != 0U) { // last TX failed due to error arbitration lost can_health[can_number].total_tx_lost_cnt += 1U; CANx->TSR |= (CAN_TSR_TERR0 | CAN_TSR_ALST0); } @@ -129,7 +129,7 @@ void can_rx(uint8_t can_number) { CAN_TypeDef *CANx = CANIF_FROM_CAN_NUM(can_number); uint8_t bus_number = BUS_NUM_FROM_CAN_NUM(can_number); - while ((CANx->RF0R & CAN_RF0R_FMP0) != 0) { + while ((CANx->RF0R & CAN_RF0R_FMP0) != 0U) { can_health[can_number].total_rx_cnt += 1U; // can is live diff --git a/board/drivers/clock_source.h b/board/drivers/clock_source.h index 11b2fa324..5d6fdc8a7 100644 --- a/board/drivers/clock_source.h +++ b/board/drivers/clock_source.h @@ -26,8 +26,8 @@ void clock_source_init(void) { set_gpio_alternate(GPIOB, 15, GPIO_AF1_TIM1); // Set PWM mode - register_set(&(TIM1->CCMR1), (0b110 << TIM_CCMR1_OC2M_Pos), 0xFFFFU); - register_set(&(TIM1->CCMR2), (0b110 << TIM_CCMR2_OC3M_Pos), 0xFFFFU); + register_set(&(TIM1->CCMR1), (0b110UL << TIM_CCMR1_OC2M_Pos), 0xFFFFU); + register_set(&(TIM1->CCMR2), (0b110UL << TIM_CCMR2_OC3M_Pos), 0xFFFFU); // Enable output register_set(&(TIM1->BDTR), TIM_BDTR_MOE, 0xFFFFU); diff --git a/board/drivers/fake_siren.h b/board/drivers/fake_siren.h index 38c87deb0..7c73be0b1 100644 --- a/board/drivers/fake_siren.h +++ b/board/drivers/fake_siren.h @@ -59,13 +59,13 @@ void fake_siren_init(void) { register_set(&DMA1_Stream1->PAR, (uint32_t) &(DAC1->DHR8R1), 0xFFFFFFFFU); DMA1_Stream1->NDTR = sizeof(fake_siren_lut); register_set(&DMA1_Stream1->FCR, 0U, 0x00000083U); - DMA1_Stream1->CR = (0b11 << DMA_SxCR_PL_Pos); - DMA1_Stream1->CR |= DMA_SxCR_MINC | DMA_SxCR_CIRC | (1 << DMA_SxCR_DIR_Pos); + DMA1_Stream1->CR = (0b11UL << DMA_SxCR_PL_Pos); + DMA1_Stream1->CR |= DMA_SxCR_MINC | DMA_SxCR_CIRC | (1U << DMA_SxCR_DIR_Pos); // Init trigger timer (around 2.5kHz) register_set(&TIM7->PSC, 0U, 0xFFFFU); register_set(&TIM7->ARR, 133U, 0xFFFFU); - register_set(&TIM7->CR2, (0b10 << TIM_CR2_MMS_Pos), TIM_CR2_MMS_Msk); + register_set(&TIM7->CR2, (0b10U << TIM_CR2_MMS_Pos), TIM_CR2_MMS_Msk); register_set(&TIM7->CR1, TIM_CR1_ARPE | TIM_CR1_URS, 0x088EU); TIM7->SR = 0U; TIM7->CR1 |= TIM_CR1_CEN; diff --git a/board/drivers/fdcan.h b/board/drivers/fdcan.h index 9e2e0df7f..0ba228a9e 100644 --- a/board/drivers/fdcan.h +++ b/board/drivers/fdcan.h @@ -67,14 +67,14 @@ void update_can_health_pkt(uint8_t can_number, uint32_t ir_reg) { FDCANx->IR |= (FDCAN_IR_PED | FDCAN_IR_PEA | FDCAN_IR_EP | FDCAN_IR_BO | FDCAN_IR_RF0L); can_health[can_number].total_error_cnt += 1U; // Check for RX FIFO overflow - if ((ir_reg & (FDCAN_IR_RF0L)) != 0) { + if ((ir_reg & (FDCAN_IR_RF0L)) != 0U) { can_health[can_number].total_rx_lost_cnt += 1U; } // Cases: // 1. while multiplexing between buses 1 and 3 we are getting ACK errors that overwhelm CAN core, by resetting it recovers faster // 2. H7 gets stuck in bus off recovery state indefinitely if ((((can_health[can_number].last_error == CAN_ACK_ERROR) || (can_health[can_number].last_data_error == CAN_ACK_ERROR)) && (can_health[can_number].transmit_error_cnt > 127U)) || - ((ir_reg & FDCAN_IR_BO) != 0)) { + ((ir_reg & FDCAN_IR_BO) != 0U)) { can_health[can_number].can_core_reset_cnt += 1U; can_health[can_number].total_tx_lost_cnt += (FDCAN_TX_FIFO_EL_CNT - (FDCANx->TXFQS & FDCAN_TXFQS_TFFL)); // TX FIFO msgs will be lost after reset llcan_clear_send(FDCANx); @@ -93,7 +93,7 @@ void process_can(uint8_t can_number) { FDCANx->IR |= FDCAN_IR_TFE; // Clear Tx FIFO Empty flag - if ((FDCANx->TXFQS & FDCAN_TXFQS_TFQF) == 0) { + if ((FDCANx->TXFQS & FDCAN_TXFQS_TFQF) == 0U) { CANPacket_t to_send; if (can_pop(can_queues[bus_number], &to_send)) { if (can_check_checksum(&to_send)) { @@ -101,7 +101,7 @@ void process_can(uint8_t can_number) { uint32_t TxFIFOSA = FDCAN_START_ADDRESS + (can_number * FDCAN_OFFSET) + (FDCAN_RX_FIFO_0_EL_CNT * FDCAN_RX_FIFO_0_EL_SIZE); // get the index of the next TX FIFO element (0 to FDCAN_TX_FIFO_EL_CNT - 1) - uint32_t tx_index = (FDCANx->TXFQS >> FDCAN_TXFQS_TFQPI_Pos) & 0x1F; + uint32_t tx_index = (FDCANx->TXFQS >> FDCAN_TXFQS_TFQPI_Pos) & 0x1FU; // only send if we have received a packet canfd_fifo *fifo; fifo = (canfd_fifo *)(TxFIFOSA + (tx_index * FDCAN_TX_FIFO_EL_SIZE)); @@ -153,14 +153,14 @@ void can_rx(uint8_t can_number) { // Clear all new messages from Rx FIFO 0 FDCANx->IR |= FDCAN_IR_RF0N; - while((FDCANx->RXF0S & FDCAN_RXF0S_F0FL) != 0) { + while((FDCANx->RXF0S & FDCAN_RXF0S_F0FL) != 0U) { can_health[can_number].total_rx_cnt += 1U; // can is live pending_can_live = 1; // get the index of the next RX FIFO element (0 to FDCAN_RX_FIFO_0_EL_CNT - 1) - uint32_t rx_fifo_idx = (uint8_t)((FDCANx->RXF0S >> FDCAN_RXF0S_F0GI_Pos) & 0x3F); + uint32_t rx_fifo_idx = (uint8_t)((FDCANx->RXF0S >> FDCAN_RXF0S_F0GI_Pos) & 0x3FU); // Recommended to offset get index by at least +1 if RX FIFO is in overwrite mode and full (datasheet) if((FDCANx->RXF0S & FDCAN_RXF0S_F0F) == FDCAN_RXF0S_F0F) { @@ -232,7 +232,7 @@ void can_rx(uint8_t can_number) { } // Error handling - if ((ir_reg & (FDCAN_IR_PED | FDCAN_IR_PEA | FDCAN_IR_EP | FDCAN_IR_BO | FDCAN_IR_RF0L)) != 0) { + if ((ir_reg & (FDCAN_IR_PED | FDCAN_IR_PEA | FDCAN_IR_EP | FDCAN_IR_BO | FDCAN_IR_RF0L)) != 0U) { update_can_health_pkt(can_number, ir_reg); } } diff --git a/board/drivers/interrupts.h b/board/drivers/interrupts.h index d4c72be1d..77988f6e4 100644 --- a/board/drivers/interrupts.h +++ b/board/drivers/interrupts.h @@ -64,7 +64,7 @@ void handle_interrupt(IRQn_Type irq_type){ // Every second void interrupt_timer_handler(void) { - if (INTERRUPT_TIMER->SR != 0) { + if (INTERRUPT_TIMER->SR != 0U) { for (uint16_t i = 0U; i < NUM_INTERRUPTS; i++) { // Log IRQ call rate faults if (check_interrupt_rate && (interrupts[i].call_counter > interrupts[i].max_call_rate)) { diff --git a/board/drivers/spi.h b/board/drivers/spi.h index efccfc98c..e1ae010f7 100644 --- a/board/drivers/spi.h +++ b/board/drivers/spi.h @@ -230,7 +230,7 @@ void spi_rx_done(void) { llspi_miso_dma(spi_buf_tx, response_len); spi_state = next_rx_state; - if (!checksum_valid && (spi_checksum_error_count < __UINT16_MAX__)) { + if (!checksum_valid && (spi_checksum_error_count < UINT16_MAX)) { spi_checksum_error_count += 1U; } } diff --git a/board/drivers/usb.h b/board/drivers/usb.h index 9ed500f81..ddd6b29c3 100644 --- a/board/drivers/usb.h +++ b/board/drivers/usb.h @@ -367,7 +367,7 @@ void *USB_ReadPacket(void *dest, uint16_t len) { uint32_t count32b = ((uint32_t)len + 3U) / 4U; for (uint32_t i = 0; i < count32b; i++) { - *dest_copy = USBx_DFIFO(0); + *dest_copy = USBx_DFIFO(0U); dest_copy++; } return ((void *)dest_copy); @@ -414,7 +414,7 @@ void USB_WritePacket_EP0(uint8_t *src, uint16_t len) { ep0_txlen = len - wplen; USBx_DEVICE->DIEPEMPMSK |= 1; } else { - USBx_OUTEP(0)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; + USBx_OUTEP(0U)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; } } @@ -431,8 +431,8 @@ void usb_reset(void) { USBx_DEVICE->DOEPMSK = 0xFFFFFFFFU; // clear interrupts - USBx_INEP(0)->DIEPINT = 0xFF; - USBx_OUTEP(0)->DOEPINT = 0xFF; + USBx_INEP(0U)->DIEPINT = 0xFF; + USBx_OUTEP(0U)->DOEPINT = 0xFF; // unset the address USBx_DEVICE->DCFG &= ~USB_OTG_DCFG_DAD; @@ -458,7 +458,7 @@ void usb_reset(void) { USBx_DEVICE->DCTL |= USB_OTG_DCTL_CGINAK; // ready to receive setup packets - USBx_OUTEP(0)->DOEPTSIZ = USB_OTG_DOEPTSIZ_STUPCNT | (USB_OTG_DOEPTSIZ_PKTCNT & (1UL << 19)) | (3U << 3); + USBx_OUTEP(0U)->DOEPTSIZ = USB_OTG_DOEPTSIZ_STUPCNT | (USB_OTG_DOEPTSIZ_PKTCNT & (1UL << 19)) | (3U << 3); } char to_hex_char(uint8_t a) { @@ -485,26 +485,26 @@ void usb_setup(void) { switch (setup.b.bRequest) { case USB_REQ_SET_CONFIGURATION: // enable other endpoints, has to be here? - USBx_INEP(1)->DIEPCTL = (0x40U & USB_OTG_DIEPCTL_MPSIZ) | (2UL << 18) | (1UL << 22) | + USBx_INEP(1U)->DIEPCTL = (0x40U & USB_OTG_DIEPCTL_MPSIZ) | (2UL << 18) | (1UL << 22) | USB_OTG_DIEPCTL_SD0PID_SEVNFRM | USB_OTG_DIEPCTL_USBAEP; - USBx_INEP(1)->DIEPINT = 0xFF; + USBx_INEP(1U)->DIEPINT = 0xFF; - USBx_OUTEP(2)->DOEPTSIZ = (1UL << 19) | 0x40U; - USBx_OUTEP(2)->DOEPCTL = (0x40U & USB_OTG_DOEPCTL_MPSIZ) | (2UL << 18) | + USBx_OUTEP(2U)->DOEPTSIZ = (1UL << 19) | 0x40U; + USBx_OUTEP(2U)->DOEPCTL = (0x40U & USB_OTG_DOEPCTL_MPSIZ) | (2UL << 18) | USB_OTG_DOEPCTL_SD0PID_SEVNFRM | USB_OTG_DOEPCTL_USBAEP; - USBx_OUTEP(2)->DOEPINT = 0xFF; + USBx_OUTEP(2U)->DOEPINT = 0xFF; - USBx_OUTEP(3)->DOEPTSIZ = (32UL << 19) | 0x800U; - USBx_OUTEP(3)->DOEPCTL = (0x40U & USB_OTG_DOEPCTL_MPSIZ) | (2UL << 18) | + USBx_OUTEP(3U)->DOEPTSIZ = (32UL << 19) | 0x800U; + USBx_OUTEP(3U)->DOEPCTL = (0x40U & USB_OTG_DOEPCTL_MPSIZ) | (2UL << 18) | USB_OTG_DOEPCTL_SD0PID_SEVNFRM | USB_OTG_DOEPCTL_USBAEP; - USBx_OUTEP(3)->DOEPINT = 0xFF; + USBx_OUTEP(3U)->DOEPINT = 0xFF; // mark ready to receive - USBx_OUTEP(2)->DOEPCTL |= USB_OTG_DOEPCTL_EPENA | USB_OTG_DOEPCTL_CNAK; - USBx_OUTEP(3)->DOEPCTL |= USB_OTG_DOEPCTL_EPENA | USB_OTG_DOEPCTL_CNAK; + USBx_OUTEP(2U)->DOEPCTL |= USB_OTG_DOEPCTL_EPENA | USB_OTG_DOEPCTL_CNAK; + USBx_OUTEP(3U)->DOEPCTL |= USB_OTG_DOEPCTL_EPENA | USB_OTG_DOEPCTL_CNAK; USB_WritePacket(0, 0, 0); - USBx_OUTEP(0)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; + USBx_OUTEP(0U)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; break; case USB_REQ_SET_ADDRESS: // set now? @@ -515,7 +515,7 @@ void usb_setup(void) { #endif USB_WritePacket(0, 0, 0); - USBx_OUTEP(0)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; + USBx_OUTEP(0U)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; break; case USB_REQ_GET_DESCRIPTOR: @@ -527,17 +527,17 @@ void usb_setup(void) { device_desc[13] = hw_type; // setup transfer USB_WritePacket(device_desc, MIN(sizeof(device_desc), setup.b.wLength.w), 0); - USBx_OUTEP(0)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; + USBx_OUTEP(0U)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; //print("D"); break; case USB_DESC_TYPE_CONFIGURATION: USB_WritePacket(configuration_desc, MIN(sizeof(configuration_desc), setup.b.wLength.w), 0); - USBx_OUTEP(0)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; + USBx_OUTEP(0U)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; break; case USB_DESC_TYPE_DEVICE_QUALIFIER: USB_WritePacket(device_qualifier, MIN(sizeof(device_qualifier), setup.b.wLength.w), 0); - USBx_OUTEP(0)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; + USBx_OUTEP(0U)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; break; case USB_DESC_TYPE_STRING: switch (setup.b.wValue.bw.msb) { @@ -576,16 +576,16 @@ void usb_setup(void) { USB_WritePacket(0, 0, 0); break; } - USBx_OUTEP(0)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; + USBx_OUTEP(0U)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; break; case USB_DESC_TYPE_BINARY_OBJECT_STORE: USB_WritePacket(binary_object_store_desc, MIN(sizeof(binary_object_store_desc), setup.b.wLength.w), 0); - USBx_OUTEP(0)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; + USBx_OUTEP(0U)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; break; default: // nothing here? USB_WritePacket(0, 0, 0); - USBx_OUTEP(0)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; + USBx_OUTEP(0U)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; break; } break; @@ -594,24 +594,24 @@ void usb_setup(void) { response[0] = 0; response[1] = 0; USB_WritePacket((void*)&response, 2, 0); - USBx_OUTEP(0)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; + USBx_OUTEP(0U)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; break; case USB_REQ_SET_INTERFACE: // Store the alt setting number for IN EP behavior. current_int0_alt_setting = setup.b.wValue.w; USB_WritePacket(0, 0, 0); - USBx_OUTEP(0)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; + USBx_OUTEP(0U)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; break; case WEBUSB_VENDOR_CODE: switch (setup.b.wIndex.w) { case WEBUSB_REQ_GET_URL: USB_WritePacket(webusb_url_descriptor, MIN(sizeof(webusb_url_descriptor), setup.b.wLength.w), 0); - USBx_OUTEP(0)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; + USBx_OUTEP(0U)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; break; default: // probably asking for allowed origins, which was removed from the spec USB_WritePacket(0, 0, 0); - USBx_OUTEP(0)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; + USBx_OUTEP(0U)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; break; } break; @@ -643,7 +643,7 @@ void usb_setup(void) { // response pending if -1 was returned if (resp_len != -1) { USB_WritePacket(response, MIN(resp_len, setup.b.wLength.w), 0); - USBx_OUTEP(0)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; + USBx_OUTEP(0U)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; } } } @@ -671,23 +671,23 @@ void usb_irqhandler(void) { print(" USB interrupt!\n"); #endif - if ((gintsts & USB_OTG_GINTSTS_CIDSCHG) != 0) { + if ((gintsts & USB_OTG_GINTSTS_CIDSCHG) != 0U) { print("connector ID status change\n"); } - if ((gintsts & USB_OTG_GINTSTS_USBRST) != 0) { + if ((gintsts & USB_OTG_GINTSTS_USBRST) != 0U) { print("USB reset\n"); usb_reset(); } - if ((gintsts & USB_OTG_GINTSTS_ENUMDNE) != 0) { + if ((gintsts & USB_OTG_GINTSTS_ENUMDNE) != 0U) { print("enumeration done"); // Full speed, ENUMSPD //puth(USBx_DEVICE->DSTS); print("\n"); } - if ((gintsts & USB_OTG_GINTSTS_OTGINT) != 0) { + if ((gintsts & USB_OTG_GINTSTS_OTGINT) != 0U) { print("OTG int:"); puth(USBx->GOTGINT); print("\n"); @@ -697,7 +697,7 @@ void usb_irqhandler(void) { } // RX FIFO first - if ((gintsts & USB_OTG_GINTSTS_RXFLVL) != 0) { + if ((gintsts & USB_OTG_GINTSTS_RXFLVL) != 0U) { // 1. Read the Receive status pop register volatile unsigned int rxst = USBx->GRXSTSP; int status = (rxst & USB_OTG_GRXSTSP_PKTSTS) >> 17; @@ -763,7 +763,7 @@ void usb_irqhandler(void) { USBx_DEVICE->DCTL |= USB_OTG_DCTL_CGONAK | USB_OTG_DCTL_CGINAK; } - if ((gintsts & USB_OTG_GINTSTS_SRQINT) != 0) { + if ((gintsts & USB_OTG_GINTSTS_SRQINT) != 0U) { // we want to do "A-device host negotiation protocol" since we are the A-device /*print("start request\n"); puth(USBx->GOTGCTL); @@ -774,76 +774,76 @@ void usb_irqhandler(void) { } // out endpoint hit - if ((gintsts & USB_OTG_GINTSTS_OEPINT) != 0) { + if ((gintsts & USB_OTG_GINTSTS_OEPINT) != 0U) { #ifdef DEBUG_USB print(" 0:"); - puth(USBx_OUTEP(0)->DOEPINT); + puth(USBx_OUTEP(0U)->DOEPINT); print(" 2:"); - puth(USBx_OUTEP(2)->DOEPINT); + puth(USBx_OUTEP(2U)->DOEPINT); print(" 3:"); - puth(USBx_OUTEP(3)->DOEPINT); + puth(USBx_OUTEP(3U)->DOEPINT); print(" "); - puth(USBx_OUTEP(3)->DOEPCTL); + puth(USBx_OUTEP(3U)->DOEPCTL); print(" 4:"); puth(USBx_OUTEP(4)->DOEPINT); print(" OUT ENDPOINT\n"); #endif - if ((USBx_OUTEP(2)->DOEPINT & USB_OTG_DOEPINT_XFRC) != 0) { + if ((USBx_OUTEP(2U)->DOEPINT & USB_OTG_DOEPINT_XFRC) != 0U) { #ifdef DEBUG_USB print(" OUT2 PACKET XFRC\n"); #endif - USBx_OUTEP(2)->DOEPTSIZ = (1UL << 19) | 0x40U; - USBx_OUTEP(2)->DOEPCTL |= USB_OTG_DOEPCTL_EPENA | USB_OTG_DOEPCTL_CNAK; + USBx_OUTEP(2U)->DOEPTSIZ = (1UL << 19) | 0x40U; + USBx_OUTEP(2U)->DOEPCTL |= USB_OTG_DOEPCTL_EPENA | USB_OTG_DOEPCTL_CNAK; } - if ((USBx_OUTEP(3)->DOEPINT & USB_OTG_DOEPINT_XFRC) != 0) { + if ((USBx_OUTEP(3U)->DOEPINT & USB_OTG_DOEPINT_XFRC) != 0U) { #ifdef DEBUG_USB print(" OUT3 PACKET XFRC\n"); #endif // NAK cleared by process_can (if tx buffers have room) outep3_processing = false; refresh_can_tx_slots_available(); - } else if ((USBx_OUTEP(3)->DOEPINT & 0x2000) != 0) { + } else if ((USBx_OUTEP(3U)->DOEPINT & 0x2000U) != 0U) { #ifdef DEBUG_USB print(" OUT3 PACKET WTF\n"); #endif // if NAK was set trigger this, unknown interrupt // TODO: why was this here? fires when TX buffers when we can't clear NAK - // USBx_OUTEP(3)->DOEPTSIZ = (1U << 19) | 0x40U; - // USBx_OUTEP(3)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; - } else if ((USBx_OUTEP(3)->DOEPINT) != 0) { + // USBx_OUTEP(3U)->DOEPTSIZ = (1U << 19) | 0x40U; + // USBx_OUTEP(3U)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; + } else if ((USBx_OUTEP(3U)->DOEPINT) != 0U) { #ifdef DEBUG_USB print("OUTEP3 error "); - puth(USBx_OUTEP(3)->DOEPINT); + puth(USBx_OUTEP(3U)->DOEPINT); print("\n"); #endif } else { - // USBx_OUTEP(3)->DOEPINT is 0, ok to skip + // USBx_OUTEP(3U)->DOEPINT is 0, ok to skip } - if ((USBx_OUTEP(0)->DOEPINT & USB_OTG_DIEPINT_XFRC) != 0) { + if ((USBx_OUTEP(0U)->DOEPINT & USB_OTG_DIEPINT_XFRC) != 0U) { // ready for next packet - USBx_OUTEP(0)->DOEPTSIZ = USB_OTG_DOEPTSIZ_STUPCNT | (USB_OTG_DOEPTSIZ_PKTCNT & (1UL << 19)) | (1U << 3); + USBx_OUTEP(0U)->DOEPTSIZ = USB_OTG_DOEPTSIZ_STUPCNT | (USB_OTG_DOEPTSIZ_PKTCNT & (1UL << 19)) | (1U << 3); } // respond to setup packets - if ((USBx_OUTEP(0)->DOEPINT & USB_OTG_DOEPINT_STUP) != 0) { + if ((USBx_OUTEP(0U)->DOEPINT & USB_OTG_DOEPINT_STUP) != 0U) { usb_setup(); } - USBx_OUTEP(0)->DOEPINT = USBx_OUTEP(0)->DOEPINT; - USBx_OUTEP(2)->DOEPINT = USBx_OUTEP(2)->DOEPINT; - USBx_OUTEP(3)->DOEPINT = USBx_OUTEP(3)->DOEPINT; + USBx_OUTEP(0U)->DOEPINT = USBx_OUTEP(0U)->DOEPINT; + USBx_OUTEP(2U)->DOEPINT = USBx_OUTEP(2U)->DOEPINT; + USBx_OUTEP(3U)->DOEPINT = USBx_OUTEP(3U)->DOEPINT; } // interrupt endpoint hit (Page 1221) - if ((gintsts & USB_OTG_GINTSTS_IEPINT) != 0) { + if ((gintsts & USB_OTG_GINTSTS_IEPINT) != 0U) { #ifdef DEBUG_USB print(" "); - puth(USBx_INEP(0)->DIEPINT); + puth(USBx_INEP(0U)->DIEPINT); print(" "); - puth(USBx_INEP(1)->DIEPINT); + puth(USBx_INEP(1U)->DIEPINT); print(" IN ENDPOINT\n"); #endif @@ -863,7 +863,7 @@ void usb_irqhandler(void) { switch (current_int0_alt_setting) { case 0: ////// Bulk config // *** IN token received when TxFIFO is empty - if ((USBx_INEP(1)->DIEPINT & USB_OTG_DIEPMSK_ITTXFEMSK) != 0) { + if ((USBx_INEP(1U)->DIEPINT & USB_OTG_DIEPMSK_ITTXFEMSK) != 0U) { #ifdef DEBUG_USB print(" IN PACKET QUEUE\n"); #endif @@ -874,7 +874,7 @@ void usb_irqhandler(void) { case 1: ////// Interrupt config // *** IN token received when TxFIFO is empty - if ((USBx_INEP(1)->DIEPINT & USB_OTG_DIEPMSK_ITTXFEMSK) != 0) { + if ((USBx_INEP(1U)->DIEPINT & USB_OTG_DIEPMSK_ITTXFEMSK) != 0U) { #ifdef DEBUG_USB print(" IN PACKET QUEUE\n"); #endif @@ -890,12 +890,12 @@ void usb_irqhandler(void) { break; } - if ((USBx_INEP(0)->DIEPINT & USB_OTG_DIEPMSK_ITTXFEMSK) != 0) { + if ((USBx_INEP(0U)->DIEPINT & USB_OTG_DIEPMSK_ITTXFEMSK) != 0U) { #ifdef DEBUG_USB print(" IN PACKET QUEUE\n"); #endif - if ((ep0_txlen != 0U) && ((USBx_INEP(0)->DTXFSTS & USB_OTG_DTXFSTS_INEPTFSAV) >= 0x40U)) { + if ((ep0_txlen != 0U) && ((USBx_INEP(0U)->DTXFSTS & USB_OTG_DTXFSTS_INEPTFSAV) >= 0x40U)) { uint16_t len = MIN(ep0_txlen, 0x40); USB_WritePacket(ep0_txdata, len, 0); ep0_txdata = &ep0_txdata[len]; @@ -903,14 +903,14 @@ void usb_irqhandler(void) { if (ep0_txlen == 0U) { ep0_txdata = NULL; USBx_DEVICE->DIEPEMPMSK &= ~1; - USBx_OUTEP(0)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; + USBx_OUTEP(0U)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; } } } // clear interrupts - USBx_INEP(0)->DIEPINT = USBx_INEP(0)->DIEPINT; // Why ep0? - USBx_INEP(1)->DIEPINT = USBx_INEP(1)->DIEPINT; + USBx_INEP(0U)->DIEPINT = USBx_INEP(0U)->DIEPINT; // Why ep0? + USBx_INEP(1U)->DIEPINT = USBx_INEP(1U)->DIEPINT; } // clear all interrupts we handled @@ -923,9 +923,9 @@ void usb_irqhandler(void) { void can_tx_comms_resume_usb(void) { ENTER_CRITICAL(); - if (!outep3_processing && (USBx_OUTEP(3)->DOEPCTL & USB_OTG_DOEPCTL_NAKSTS) != 0) { - USBx_OUTEP(3)->DOEPTSIZ = (32UL << 19) | 0x800U; - USBx_OUTEP(3)->DOEPCTL |= USB_OTG_DOEPCTL_EPENA | USB_OTG_DOEPCTL_CNAK; + if (!outep3_processing && (USBx_OUTEP(3U)->DOEPCTL & USB_OTG_DOEPCTL_NAKSTS) != 0U) { + USBx_OUTEP(3U)->DOEPTSIZ = (32UL << 19) | 0x800U; + USBx_OUTEP(3U)->DOEPCTL |= USB_OTG_DOEPCTL_EPENA | USB_OTG_DOEPCTL_CNAK; } EXIT_CRITICAL(); } diff --git a/board/main.c b/board/main.c index 8e6434e69..4bd784bf0 100644 --- a/board/main.c +++ b/board/main.c @@ -145,7 +145,7 @@ void __attribute__ ((noinline)) enable_fpu(void) { uint8_t loop_counter = 0U; uint8_t prev_harness_status = HARNESS_STATUS_NC; void tick_handler(void) { - if (TICK_TIMER->SR != 0) { + if (TICK_TIMER->SR != 0U) { // siren current_board->set_siren((loop_counter & 1U) && (siren_enabled || (siren_countdown > 0U))); @@ -198,7 +198,7 @@ void tick_handler(void) { bootkick_tick(check_started(), recent_heartbeat); // increase heartbeat counter and cap it at the uint32 limit - if (heartbeat_counter < __UINT32_MAX__) { + if (heartbeat_counter < UINT32_MAX) { heartbeat_counter += 1U; } diff --git a/board/safety/safety_chrysler.h b/board/safety/safety_chrysler.h index fa0e1532d..be27832c9 100644 --- a/board/safety/safety_chrysler.h +++ b/board/safety/safety_chrysler.h @@ -123,11 +123,12 @@ RxCheck chrysler_ram_hd_rx_checks[] = { const uint32_t CHRYSLER_PARAM_RAM_DT = 1U; // set for Ram DT platform const uint32_t CHRYSLER_PARAM_RAM_HD = 2U; // set for Ram HD platform -enum { +typedef enum { CHRYSLER_RAM_DT, CHRYSLER_RAM_HD, CHRYSLER_PACIFICA, // plus Jeep -} chrysler_platform = CHRYSLER_PACIFICA; +} ChryslerPlatform; +ChryslerPlatform chrysler_platform = CHRYSLER_PACIFICA; const ChryslerAddrs *chrysler_addrs = &CHRYSLER_ADDRS; static uint32_t chrysler_get_checksum(const CANPacket_t *to_push) { diff --git a/board/safety/safety_gm.h b/board/safety/safety_gm.h index 7f8ad72c7..09ac34ecb 100644 --- a/board/safety/safety_gm.h +++ b/board/safety/safety_gm.h @@ -59,7 +59,11 @@ enum { GM_BTN_CANCEL = 6, }; -enum {GM_ASCM, GM_CAM} gm_hw = GM_ASCM; +typedef enum { + GM_ASCM, + GM_CAM +} GmHardware; +GmHardware gm_hw = GM_ASCM; bool gm_cam_long = false; bool gm_pcm_cruise = false; diff --git a/board/safety/safety_honda.h b/board/safety/safety_honda.h index 3c93ab9d1..630f6d731 100644 --- a/board/safety/safety_honda.h +++ b/board/safety/safety_honda.h @@ -79,7 +79,8 @@ bool honda_alt_brake_msg = false; bool honda_fwd_brake = false; bool honda_bosch_long = false; bool honda_bosch_radarless = false; -enum {HONDA_NIDEC, HONDA_BOSCH} honda_hw = HONDA_NIDEC; +typedef enum {HONDA_NIDEC, HONDA_BOSCH} HondaHw; +HondaHw honda_hw = HONDA_NIDEC; int honda_get_pt_bus(void) { diff --git a/board/stm32f4/clock.h b/board/stm32f4/clock.h index 19be57443..f0084facc 100644 --- a/board/stm32f4/clock.h +++ b/board/stm32f4/clock.h @@ -1,7 +1,7 @@ void clock_init(void) { // enable external oscillator register_set_bits(&(RCC->CR), RCC_CR_HSEON); - while ((RCC->CR & RCC_CR_HSERDY) == 0); + while ((RCC->CR & RCC_CR_HSERDY) == 0U); // divide things // AHB = 96MHz @@ -20,7 +20,7 @@ void clock_init(void) { // start PLL register_set_bits(&(RCC->CR), RCC_CR_PLLON); - while ((RCC->CR & RCC_CR_PLLRDY) == 0); + while ((RCC->CR & RCC_CR_PLLRDY) == 0U); // Configure Flash prefetch, Instruction cache, Data cache and wait state // *** without this, it breaks *** diff --git a/board/stm32f4/lluart.h b/board/stm32f4/lluart.h index ffe7e74da..64094119f 100644 --- a/board/stm32f4/lluart.h +++ b/board/stm32f4/lluart.h @@ -5,7 +5,7 @@ void uart_tx_ring(uart_ring *q){ // Send out next byte of TX buffer if (q->w_ptr_tx != q->r_ptr_tx) { // Only send if transmit register is empty (aka last byte has been sent) - if ((q->uart->SR & USART_SR_TXE) != 0) { + if ((q->uart->SR & USART_SR_TXE) != 0U) { q->uart->DR = q->elems_tx[q->r_ptr_tx]; // This clears TXE q->r_ptr_tx = (q->r_ptr_tx + 1U) % q->tx_fifo_size; } @@ -46,7 +46,7 @@ void uart_rx_ring(uart_ring *q){ } void uart_send_break(uart_ring *u) { - while ((u->uart->CR1 & USART_CR1_SBK) != 0); + while ((u->uart->CR1 & USART_CR1_SBK) != 0U); u->uart->CR1 |= USART_CR1_SBK; } diff --git a/board/stm32f4/llusb.h b/board/stm32f4/llusb.h index 20c980864..6f15c89e1 100644 --- a/board/stm32f4/llusb.h +++ b/board/stm32f4/llusb.h @@ -8,7 +8,7 @@ USB_OTG_GlobalTypeDef *USBx = USB_OTG_FS; #define USBx_PCGCCTL *(__IO uint32_t *)((uint32_t)USBx + USB_OTG_PCGCCTL_BASE) #define USBD_FS_TRDT_VALUE 5UL -#define USB_OTG_SPEED_FULL 3 +#define USB_OTG_SPEED_FULL 3UL void usb_irqhandler(void); @@ -27,7 +27,7 @@ void usb_init(void) { // full speed PHY, do reset and remove power down /*puth(USBx->GRSTCTL); print(" resetting PHY\n");*/ - while ((USBx->GRSTCTL & USB_OTG_GRSTCTL_AHBIDL) == 0); + while ((USBx->GRSTCTL & USB_OTG_GRSTCTL_AHBIDL) == 0U); //print("AHB idle\n"); // reset PHY here diff --git a/board/stm32h7/clock.h b/board/stm32h7/clock.h index 94e08ca60..2e3ab701d 100644 --- a/board/stm32h7/clock.h +++ b/board/stm32h7/clock.h @@ -26,17 +26,17 @@ void clock_init(void) { #endif // Set VOS level (VOS3 to 170Mhz, VOS2 to 300Mhz, VOS1 to 400Mhz, VOS0 to 550Mhz) register_set(&(PWR->D3CR), PWR_D3CR_VOS_1 | PWR_D3CR_VOS_0, 0xC000U); //VOS1, needed for 80Mhz CAN FD - while ((PWR->CSR1 & PWR_CSR1_ACTVOSRDY) == 0); + while ((PWR->CSR1 & PWR_CSR1_ACTVOSRDY) == 0U); while ((PWR->CSR1 & PWR_CSR1_ACTVOS) != (PWR->D3CR & PWR_D3CR_VOS)); // check that VOS level was actually set // Configure Flash ACR register LATENCY and WRHIGHFREQ (VOS0 range!) register_set(&(FLASH->ACR), FLASH_ACR_LATENCY_2WS | 0x20U, 0x3FU); // VOS2, AXI 100MHz-150MHz // enable external oscillator HSE register_set_bits(&(RCC->CR), RCC_CR_HSEON); - while ((RCC->CR & RCC_CR_HSERDY) == 0); + while ((RCC->CR & RCC_CR_HSERDY) == 0U); // enable internal HSI48 for USB FS kernel register_set_bits(&(RCC->CR), RCC_CR_HSI48ON); - while ((RCC->CR & RCC_CR_HSI48RDY) == 0); + while ((RCC->CR & RCC_CR_HSI48RDY) == 0U); // Specify the frequency source for PLL1, divider for DIVM1, DIVM2, DIVM3 : HSE, 5, 5, 5 register_set(&(RCC->PLLCKSELR), RCC_PLLCKSELR_PLLSRC_HSE | RCC_PLLCKSELR_DIVM1_0 | RCC_PLLCKSELR_DIVM1_2 | RCC_PLLCKSELR_DIVM2_0 | RCC_PLLCKSELR_DIVM2_2 | RCC_PLLCKSELR_DIVM3_0 | RCC_PLLCKSELR_DIVM3_2, 0x3F3F3F3U); @@ -47,7 +47,7 @@ void clock_init(void) { register_set(&(RCC->PLLCFGR), RCC_PLLCFGR_PLL1RGE_2 | RCC_PLLCFGR_DIVP1EN | RCC_PLLCFGR_DIVQ1EN | RCC_PLLCFGR_DIVR1EN, 0x7000CU); // Enable PLL1 register_set_bits(&(RCC->CR), RCC_CR_PLL1ON); - while((RCC->CR & RCC_CR_PLL1RDY) == 0); + while((RCC->CR & RCC_CR_PLL1RDY) == 0U); // *** PLL1 end *** //////////////OTHER CLOCKS//////////////////// diff --git a/board/stm32h7/lladc.h b/board/stm32h7/lladc.h index 01342a4d0..7d818f27a 100644 --- a/board/stm32h7/lladc.h +++ b/board/stm32h7/lladc.h @@ -7,7 +7,7 @@ void adc_init(void) { ADC1->CR &= ~(ADC_CR_ADCALDIF); // Choose single-ended calibration ADC1->CR |= ADC_CR_ADCALLIN; // Lineriality calibration ADC1->CR |= ADC_CR_ADCAL; // Start calibrtation - while((ADC1->CR & ADC_CR_ADCAL) != 0); + while((ADC1->CR & ADC_CR_ADCAL) != 0U); ADC1->ISR |= ADC_ISR_ADRDY; ADC1->CR |= ADC_CR_ADEN; @@ -17,11 +17,11 @@ void adc_init(void) { uint16_t adc_get_raw(uint8_t channel) { uint16_t res = 0U; ADC1->SQR1 &= ~(ADC_SQR1_L); - ADC1->SQR1 = ((uint32_t) channel << 6U); + ADC1->SQR1 = (uint32_t)channel << 6U; - ADC1->SMPR1 = (0x2U << (channel * 3U)); + ADC1->SMPR1 = 0x2UL << (channel * 3UL); ADC1->PCSEL_RES0 = (0x1UL << channel); - ADC1->CFGR2 = (127U << ADC_CFGR2_OVSR_Pos) | (0x7U << ADC_CFGR2_OVSS_Pos) | ADC_CFGR2_ROVSE; + ADC1->CFGR2 = (127UL << ADC_CFGR2_OVSR_Pos) | (0x7U << ADC_CFGR2_OVSS_Pos) | ADC_CFGR2_ROVSE; ADC1->CR |= ADC_CR_ADSTART; while (!(ADC1->ISR & ADC_ISR_EOC)); diff --git a/board/stm32h7/llfdcan.h b/board/stm32h7/llfdcan.h index 4bb6d3d04..db42024c4 100644 --- a/board/stm32h7/llfdcan.h +++ b/board/stm32h7/llfdcan.h @@ -55,7 +55,7 @@ bool fdcan_request_init(FDCAN_GlobalTypeDef *FDCANx) { // Request init uint32_t timeout_counter = 0U; FDCANx->CCCR |= FDCAN_CCCR_INIT; - while ((FDCANx->CCCR & FDCAN_CCCR_INIT) == 0) { + while ((FDCANx->CCCR & FDCAN_CCCR_INIT) == 0U) { // Delay for about 1ms delay(10000); timeout_counter++; @@ -73,7 +73,7 @@ bool fdcan_exit_init(FDCAN_GlobalTypeDef *FDCANx) { FDCANx->CCCR &= ~(FDCAN_CCCR_INIT); uint32_t timeout_counter = 0U; - while ((FDCANx->CCCR & FDCAN_CCCR_INIT) != 0) { + while ((FDCANx->CCCR & FDCAN_CCCR_INIT) != 0U) { // Delay for about 1ms delay(10000); timeout_counter++; @@ -118,7 +118,7 @@ bool llcan_set_speed(FDCAN_GlobalTypeDef *FDCANx, uint32_t speed, uint32_t data_ uint32_t seg2 = CAN_SEG2(tq, sp); uint8_t sjw = MIN(127U, seg2); - FDCANx->NBTP = (((sjw & 0x7FU)-1U)<NBTP = (((sjw & 0x7FUL)-1U)<DBTP = (((sjw & 0xFU)-1U)<DBTP = (((sjw & 0xFUL)-1U)<CR2, I2C_CR2_ADD10); - I2C->CR2 = ((addr << 1U) & I2C_CR2_SADD_Msk); + I2C->CR2 = ((uint32_t)addr << 1U) & I2C_CR2_SADD_Msk; register_clear_bits(&I2C->CR2, I2C_CR2_RD_WRN); register_set_bits(&I2C->CR2, I2C_CR2_AUTOEND); - I2C->CR2 |= (2 << I2C_CR2_NBYTES_Pos); + I2C->CR2 |= 2UL << I2C_CR2_NBYTES_Pos; I2C->CR2 |= I2C_CR2_START; if(!i2c_status_wait(&I2C->CR2, I2C_CR2_START, 0U)) { @@ -61,10 +61,10 @@ bool i2c_read_reg(I2C_TypeDef *I2C, uint8_t addr, uint8_t reg, uint8_t *value) { bool ret = false; for(uint32_t i=0U; i<10U; i++) { register_clear_bits(&I2C->CR2, I2C_CR2_ADD10); - I2C->CR2 = ((addr << 1U) & I2C_CR2_SADD_Msk); + I2C->CR2 = ((uint32_t)addr << 1U) & I2C_CR2_SADD_Msk; register_clear_bits(&I2C->CR2, I2C_CR2_RD_WRN); register_clear_bits(&I2C->CR2, I2C_CR2_AUTOEND); - I2C->CR2 |= (1 << I2C_CR2_NBYTES_Pos); + I2C->CR2 |= 1UL << I2C_CR2_NBYTES_Pos; I2C->CR2 |= I2C_CR2_START; if(!i2c_status_wait(&I2C->CR2, I2C_CR2_START, 0U)) { @@ -92,7 +92,7 @@ bool i2c_read_reg(I2C_TypeDef *I2C, uint8_t addr, uint8_t reg, uint8_t *value) { I2C->TXDR = reg; // Restart - I2C->CR2 = (((addr << 1) | 0x1U) & I2C_CR2_SADD_Msk) | (1U << I2C_CR2_NBYTES_Pos) | I2C_CR2_RD_WRN | I2C_CR2_START; + I2C->CR2 = (((addr << 1) | 0x1U) & I2C_CR2_SADD_Msk) | (1UL << I2C_CR2_NBYTES_Pos) | I2C_CR2_RD_WRN | I2C_CR2_START; ret = i2c_status_wait(&I2C->CR2, I2C_CR2_START, 0U); if(!ret) { goto end; diff --git a/board/stm32h7/llspi.h b/board/stm32h7/llspi.h index 1947803ac..903f6a5ec 100644 --- a/board/stm32h7/llspi.h +++ b/board/stm32h7/llspi.h @@ -71,7 +71,7 @@ void SPI4_IRQ_Handler(void) { // clear flag SPI4->IFCR |= (0x1FFU << 3U); - if (spi_tx_dma_done && ((SPI4->SR & SPI_SR_TXC) != 0)) { + if (spi_tx_dma_done && ((SPI4->SR & SPI_SR_TXC) != 0U)) { spi_tx_dma_done = false; spi_tx_done(false); } diff --git a/board/stm32h7/lluart.h b/board/stm32h7/lluart.h index 0ad7b6a86..6ca6dcec3 100644 --- a/board/stm32h7/lluart.h +++ b/board/stm32h7/lluart.h @@ -29,7 +29,7 @@ void uart_tx_ring(uart_ring *q){ // Send out next byte of TX buffer if (q->w_ptr_tx != q->r_ptr_tx) { // Only send if transmit register is empty (aka last byte has been sent) - if ((q->uart->ISR & USART_ISR_TXE_TXFNF) != 0) { + if ((q->uart->ISR & USART_ISR_TXE_TXFNF) != 0U) { q->uart->TDR = q->elems_tx[q->r_ptr_tx]; // This clears TXE q->r_ptr_tx = (q->r_ptr_tx + 1U) % q->tx_fifo_size; } diff --git a/board/stm32h7/llusb.h b/board/stm32h7/llusb.h index ada1630f8..2975f62be 100644 --- a/board/stm32h7/llusb.h +++ b/board/stm32h7/llusb.h @@ -32,7 +32,7 @@ void usb_init(void) { USBx->GUSBCFG |= USB_OTG_GUSBCFG_FDMOD; delay(250000); // Wait for about 25ms (explicitly stated in H7 ref manual) // Wait for AHB master IDLE state. - while ((USBx->GRSTCTL & USB_OTG_GRSTCTL_AHBIDL) == 0); + while ((USBx->GRSTCTL & USB_OTG_GRSTCTL_AHBIDL) == 0U); // Core Soft Reset USBx->GRSTCTL |= USB_OTG_GRSTCTL_CSRST; while ((USBx->GRSTCTL & USB_OTG_GRSTCTL_CSRST) == USB_OTG_GRSTCTL_CSRST); diff --git a/tests/misra/suppressions.txt b/tests/misra/suppressions.txt index d5b14c836..b16194e6b 100644 --- a/tests/misra/suppressions.txt +++ b/tests/misra/suppressions.txt @@ -18,9 +18,12 @@ 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 -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 +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 # unused macros. a few legit, rest aren't common between F4/H7 builds. should we do this in the unusedFunction pass? misra-c2012-8.7 misra-c2012-8.4 +misra-c2012-11.8 misra-c2012-21.15 + +# FIXME: violations are in ST's F4 headers +misra-c2012-12.2 diff --git a/tests/misra/test_misra.sh b/tests/misra/test_misra.sh index 9fdbea1df..482eba241 100755 --- a/tests/misra/test_misra.sh +++ b/tests/misra/test_misra.sh @@ -29,13 +29,17 @@ if [ -z "${SKIP_BUILD}" ]; then fi cppcheck() { + # get all gcc defines: arm-none-eabi-gcc -dM -E - < /dev/null + COMMON_DEFINES="-D__GNUC__=9 -UCMSIS_NVIC_VIRTUAL -UCMSIS_VECTAB_VIRTUAL" + # note that cppcheck build cache results in inconsistent results as of v2.13.0 OUTPUT=$DIR/.output.log - $CPPCHECK_DIR/cppcheck --force --inline-suppr -I $PANDA_DIR/board/ \ - -I $gcc_inc "$(arm-none-eabi-gcc -print-file-name=include)" \ + $CPPCHECK_DIR/cppcheck --inline-suppr -I $PANDA_DIR/board/ \ + -I "$(arm-none-eabi-gcc -print-file-name=include)" \ + -I $PANDA_DIR/board/stm32f4/inc/ -I $PANDA_DIR/board/stm32h7/inc/ \ --suppressions-list=$DIR/suppressions.txt --suppress=*:*inc/* \ --suppress=*:*include/* --error-exitcode=2 --check-level=exhaustive \ - --platform=arm32-wchar_t2 \ + --platform=arm32-wchar_t4 $COMMON_DEFINES \ "$@" |& tee $OUTPUT # cppcheck bug: some MISRA errors won't result in the error exit code, @@ -48,10 +52,10 @@ cppcheck() { PANDA_OPTS="--enable=all --disable=unusedFunction -DPANDA --addon=misra" printf "\n${GREEN}** PANDA F4 CODE **${NC}\n" -cppcheck $PANDA_OPTS -DSTM32F4 -DUID_BASE $PANDA_DIR/board/main.c +cppcheck $PANDA_OPTS -DSTM32F4 -DSTM32F413xx $PANDA_DIR/board/main.c printf "\n${GREEN}** PANDA H7 CODE **${NC}\n" -cppcheck $PANDA_OPTS -DSTM32H7 -DUID_BASE $PANDA_DIR/board/main.c +cppcheck $PANDA_OPTS -DSTM32H7 -DSTM32H725xx $PANDA_DIR/board/main.c # unused needs to run globally #printf "\n${GREEN}** UNUSED ALL CODE **${NC}\n" From 01c54d11990fb82b85acc322a6e2e34a4b7ee389 Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Sun, 24 Mar 2024 12:38:25 -0700 Subject: [PATCH 58/67] enable misra-c2012-11.8 (#1916) * fix up harness_config definition * enable misra-c2012-11.8 --- board/boards/black.h | 4 ++-- board/boards/board_declarations.h | 2 +- board/boards/cuatro.h | 2 +- board/boards/dos.h | 4 ++-- board/boards/grey.h | 2 +- board/boards/red.h | 4 ++-- board/boards/red_chiplet.h | 2 +- board/boards/tres.h | 2 +- board/boards/uno.h | 4 ++-- board/boards/white.h | 4 ++-- board/bootstub_declarations.h | 2 +- board/drivers/gpio.h | 6 +++--- board/drivers/harness.h | 20 ++++++++++---------- board/jungle/boards/board_v1.h | 2 +- board/jungle/boards/board_v2.h | 16 ++++++++-------- board/main_declarations.h | 2 +- tests/misra/suppressions.txt | 1 - 17 files changed, 39 insertions(+), 40 deletions(-) diff --git a/board/boards/black.h b/board/boards/black.h index 858ade2e2..c860d1401 100644 --- a/board/boards/black.h +++ b/board/boards/black.h @@ -141,7 +141,7 @@ void black_init_bootloader(void) { set_gpio_output(GPIOC, 12, 0); } -const harness_configuration black_harness_config = { +harness_configuration black_harness_config = { .has_harness = true, .GPIO_SBU1 = GPIOC, .GPIO_SBU2 = GPIOC, @@ -155,7 +155,7 @@ const harness_configuration black_harness_config = { .adc_channel_SBU2 = 13 }; -const board board_black = { +board board_black = { .set_bootkick = unused_set_bootkick, .harness_config = &black_harness_config, .has_obd = true, diff --git a/board/boards/board_declarations.h b/board/boards/board_declarations.h index ac0c14136..a9ff9297b 100644 --- a/board/boards/board_declarations.h +++ b/board/boards/board_declarations.h @@ -21,7 +21,7 @@ typedef void (*board_set_bootkick)(BootState state); typedef bool (*board_read_som_gpio)(void); struct board { - const harness_configuration *harness_config; + harness_configuration *harness_config; const bool has_obd; const bool has_spi; const bool has_canfd; diff --git a/board/boards/cuatro.h b/board/boards/cuatro.h index f497f3f69..43a5dfc50 100644 --- a/board/boards/cuatro.h +++ b/board/boards/cuatro.h @@ -103,7 +103,7 @@ void cuatro_init(void) { clock_source_init(); } -const board board_cuatro = { +board board_cuatro = { .harness_config = &red_chiplet_harness_config, .has_obd = true, .has_spi = true, diff --git a/board/boards/dos.h b/board/boards/dos.h index 381ce8413..0164f2b26 100644 --- a/board/boards/dos.h +++ b/board/boards/dos.h @@ -166,7 +166,7 @@ void dos_init(void) { clock_source_init(); } -const harness_configuration dos_harness_config = { +harness_configuration dos_harness_config = { .has_harness = true, .GPIO_SBU1 = GPIOC, .GPIO_SBU2 = GPIOC, @@ -180,7 +180,7 @@ const harness_configuration dos_harness_config = { .adc_channel_SBU2 = 13 }; -const board board_dos = { +board board_dos = { .harness_config = &dos_harness_config, .has_obd = true, #ifdef ENABLE_SPI diff --git a/board/boards/grey.h b/board/boards/grey.h index 75273c1ad..516d0fa70 100644 --- a/board/boards/grey.h +++ b/board/boards/grey.h @@ -4,7 +4,7 @@ // Most hardware functionality is similar to white panda -const board board_grey = { +board board_grey = { .set_bootkick = unused_set_bootkick, .harness_config = &white_harness_config, .has_obd = false, diff --git a/board/boards/red.h b/board/boards/red.h index 90d97c4f1..746c54b62 100644 --- a/board/boards/red.h +++ b/board/boards/red.h @@ -153,7 +153,7 @@ void red_init(void) { red_set_can_mode(CAN_MODE_NORMAL); } -const harness_configuration red_harness_config = { +harness_configuration red_harness_config = { .has_harness = true, .GPIO_SBU1 = GPIOC, .GPIO_SBU2 = GPIOA, @@ -167,7 +167,7 @@ const harness_configuration red_harness_config = { .adc_channel_SBU2 = 17 //ADC1_INP17 }; -const board board_red = { +board board_red = { .set_bootkick = unused_set_bootkick, .harness_config = &red_harness_config, .has_obd = true, diff --git a/board/boards/red_chiplet.h b/board/boards/red_chiplet.h index f6c028be1..d79f8f83a 100644 --- a/board/boards/red_chiplet.h +++ b/board/boards/red_chiplet.h @@ -132,7 +132,7 @@ void red_chiplet_init(void) { red_chiplet_set_can_mode(CAN_MODE_NORMAL); } -const harness_configuration red_chiplet_harness_config = { +harness_configuration red_chiplet_harness_config = { .has_harness = true, .GPIO_SBU1 = GPIOC, .GPIO_SBU2 = GPIOA, diff --git a/board/boards/tres.h b/board/boards/tres.h index 14a02bea7..91b94f68e 100644 --- a/board/boards/tres.h +++ b/board/boards/tres.h @@ -70,7 +70,7 @@ void tres_init(void) { clock_source_init(); } -const board board_tres = { +board board_tres = { .harness_config = &red_chiplet_harness_config, .has_obd = true, .has_spi = true, diff --git a/board/boards/uno.h b/board/boards/uno.h index ce69f6cfe..a2e1e9835 100644 --- a/board/boards/uno.h +++ b/board/boards/uno.h @@ -177,7 +177,7 @@ void uno_init_bootloader(void) { set_gpio_output(GPIOC, 12, 0); } -const harness_configuration uno_harness_config = { +harness_configuration uno_harness_config = { .has_harness = true, .GPIO_SBU1 = GPIOC, .GPIO_SBU2 = GPIOC, @@ -191,7 +191,7 @@ const harness_configuration uno_harness_config = { .adc_channel_SBU2 = 13 }; -const board board_uno = { +board board_uno = { .harness_config = &uno_harness_config, .has_obd = true, .has_spi = false, diff --git a/board/boards/white.h b/board/boards/white.h index 690334568..8d22afbc9 100644 --- a/board/boards/white.h +++ b/board/boards/white.h @@ -180,11 +180,11 @@ void white_grey_init_bootloader(void) { set_gpio_output(GPIOC, 14, 0); } -const harness_configuration white_harness_config = { +harness_configuration white_harness_config = { .has_harness = false }; -const board board_white = { +board board_white = { .set_bootkick = unused_set_bootkick, .harness_config = &white_harness_config, .has_obd = false, diff --git a/board/bootstub_declarations.h b/board/bootstub_declarations.h index f61fb310c..5cdec508e 100644 --- a/board/bootstub_declarations.h +++ b/board/bootstub_declarations.h @@ -15,4 +15,4 @@ void uart_init(uart_ring *q, int baud) { UNUSED(q); UNUSED(baud); } // ********************* Globals ********************** uint8_t hw_type = 0; -const board *current_board; +board *current_board; diff --git a/board/drivers/gpio.h b/board/drivers/gpio.h index bf96a0326..0b8fc091b 100644 --- a/board/drivers/gpio.h +++ b/board/drivers/gpio.h @@ -11,7 +11,7 @@ #define OUTPUT_TYPE_OPEN_DRAIN 1U typedef struct { - GPIO_TypeDef *bank; + GPIO_TypeDef * const bank; uint8_t pin; } gpio_t; @@ -68,13 +68,13 @@ int get_gpio_input(const GPIO_TypeDef *GPIO, unsigned int pin) { return (GPIO->IDR & (1UL << pin)) == (1UL << pin); } -void gpio_set_all_output(const gpio_t *pins, uint8_t num_pins, bool enabled) { +void gpio_set_all_output(gpio_t *pins, uint8_t num_pins, bool enabled) { for (uint8_t i = 0; i < num_pins; i++) { set_gpio_output(pins[i].bank, pins[i].pin, enabled); } } -void gpio_set_bitmask(const gpio_t *pins, uint8_t num_pins, uint32_t bitmask) { +void gpio_set_bitmask(gpio_t *pins, uint8_t num_pins, uint32_t bitmask) { for (uint8_t i = 0; i < num_pins; i++) { set_gpio_output(pins[i].bank, pins[i].pin, (bitmask >> i) & 1U); } diff --git a/board/drivers/harness.h b/board/drivers/harness.h index bfe61050a..f8f0ccb7d 100644 --- a/board/drivers/harness.h +++ b/board/drivers/harness.h @@ -13,16 +13,16 @@ struct harness_t harness; struct harness_configuration { const bool has_harness; - GPIO_TypeDef *GPIO_SBU1; - GPIO_TypeDef *GPIO_SBU2; - GPIO_TypeDef *GPIO_relay_SBU1; - GPIO_TypeDef *GPIO_relay_SBU2; - uint8_t pin_SBU1; - uint8_t pin_SBU2; - uint8_t pin_relay_SBU1; - uint8_t pin_relay_SBU2; - uint8_t adc_channel_SBU1; - uint8_t adc_channel_SBU2; + GPIO_TypeDef * const GPIO_SBU1; + GPIO_TypeDef * const GPIO_SBU2; + GPIO_TypeDef * const GPIO_relay_SBU1; + GPIO_TypeDef * const GPIO_relay_SBU2; + const uint8_t pin_SBU1; + const uint8_t pin_SBU2; + const uint8_t pin_relay_SBU1; + const uint8_t pin_relay_SBU2; + const uint8_t adc_channel_SBU1; + const uint8_t adc_channel_SBU2; }; // The ignition relay is only used for testing purposes diff --git a/board/jungle/boards/board_v1.h b/board/jungle/boards/board_v1.h index 9581686e2..efaacf60c 100644 --- a/board/jungle/boards/board_v1.h +++ b/board/jungle/boards/board_v1.h @@ -157,7 +157,7 @@ void board_v1_init(void) { void board_v1_tick(void) {} -const board board_v1 = { +board board_v1 = { .has_canfd = false, .has_sbu_sense = false, .avdd_mV = 3300U, diff --git a/board/jungle/boards/board_v2.h b/board/jungle/boards/board_v2.h index 095114825..ae4b2fc8d 100644 --- a/board/jungle/boards/board_v2.h +++ b/board/jungle/boards/board_v2.h @@ -2,7 +2,7 @@ // Jungle board v2 (STM32H7) // // ///////////////////////// // -const gpio_t power_pins[] = { +gpio_t power_pins[] = { {.bank = GPIOA, .pin = 0}, {.bank = GPIOA, .pin = 1}, {.bank = GPIOF, .pin = 12}, @@ -11,7 +11,7 @@ const gpio_t power_pins[] = { {.bank = GPIOB, .pin = 2}, }; -const gpio_t sbu1_ignition_pins[] = { +gpio_t sbu1_ignition_pins[] = { {.bank = GPIOD, .pin = 0}, {.bank = GPIOD, .pin = 5}, {.bank = GPIOD, .pin = 12}, @@ -20,7 +20,7 @@ const gpio_t sbu1_ignition_pins[] = { {.bank = GPIOE, .pin = 9}, }; -const gpio_t sbu1_relay_pins[] = { +gpio_t sbu1_relay_pins[] = { {.bank = GPIOD, .pin = 1}, {.bank = GPIOD, .pin = 6}, {.bank = GPIOD, .pin = 11}, @@ -29,7 +29,7 @@ const gpio_t sbu1_relay_pins[] = { {.bank = GPIOE, .pin = 10}, }; -const gpio_t sbu2_ignition_pins[] = { +gpio_t sbu2_ignition_pins[] = { {.bank = GPIOD, .pin = 3}, {.bank = GPIOD, .pin = 8}, {.bank = GPIOD, .pin = 9}, @@ -38,7 +38,7 @@ const gpio_t sbu2_ignition_pins[] = { {.bank = GPIOE, .pin = 11}, }; -const gpio_t sbu2_relay_pins[] = { +gpio_t sbu2_relay_pins[] = { {.bank = GPIOD, .pin = 4}, {.bank = GPIOD, .pin = 10}, {.bank = GPIOD, .pin = 13}, @@ -47,7 +47,7 @@ const gpio_t sbu2_relay_pins[] = { {.bank = GPIOE, .pin = 12}, }; -const adc_channel_t sbu1_channels[] = { +adc_channel_t sbu1_channels[] = { {.adc = ADC3, .channel = 12}, {.adc = ADC3, .channel = 2}, {.adc = ADC3, .channel = 4}, @@ -56,7 +56,7 @@ const adc_channel_t sbu1_channels[] = { {.adc = ADC3, .channel = 10}, }; -const adc_channel_t sbu2_channels[] = { +adc_channel_t sbu2_channels[] = { {.adc = ADC1, .channel = 13}, {.adc = ADC3, .channel = 3}, {.adc = ADC3, .channel = 5}, @@ -307,7 +307,7 @@ void board_v2_init(void) { void board_v2_tick(void) {} -const board board_v2 = { +board board_v2 = { .has_canfd = true, .has_sbu_sense = true, .avdd_mV = 3300U, diff --git a/board/main_declarations.h b/board/main_declarations.h index fa860b86c..a1496c0d0 100644 --- a/board/main_declarations.h +++ b/board/main_declarations.h @@ -11,7 +11,7 @@ void pwm_set(TIM_TypeDef *TIM, uint8_t channel, uint8_t percentage); // ********************* Globals ********************** uint8_t hw_type = 0; -const board *current_board; +board *current_board; uint32_t uptime_cnt = 0; bool green_led_enabled = false; diff --git a/tests/misra/suppressions.txt b/tests/misra/suppressions.txt index b16194e6b..c3e260dfb 100644 --- a/tests/misra/suppressions.txt +++ b/tests/misra/suppressions.txt @@ -22,7 +22,6 @@ misra-c2012-1.2 # this is from the extensions (e.g. __typeof__) used in the MI misra-c2012-2.5 # unused macros. a few legit, rest aren't common between F4/H7 builds. should we do this in the unusedFunction pass? misra-c2012-8.7 misra-c2012-8.4 -misra-c2012-11.8 misra-c2012-21.15 # FIXME: violations are in ST's F4 headers From 18f0bdff4bfb178c5cb5613fe91f0bb424791a93 Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Fri, 29 Mar 2024 03:11:26 -0700 Subject: [PATCH 59/67] pre-commit: autoupdate hooks (#1921) 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 09fcffbc0..0a2f32685 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.3.3 + rev: v0.3.4 hooks: - id: ruff From 78f67d3526f2eb6a634455a4bfd15c17975166d3 Mon Sep 17 00:00:00 2001 From: Shane Smiskol Date: Mon, 8 Apr 2024 18:23:27 -0700 Subject: [PATCH 60/67] pytest bugs are fixed (#1925) * bugs fixed * bump to uncache * bump --- Dockerfile | 2 +- pyproject.toml | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/Dockerfile b/Dockerfile index 99bedcf08..63601740e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -51,7 +51,7 @@ RUN curl -L https://github.com/pyenv/pyenv-installer/raw/master/bin/pyenv-instal ENV PATH="/root/.pyenv/bin:/root/.pyenv/shims:${PATH}" ENV PANDA_PATH=/tmp/openpilot/panda -ENV OPENPILOT_REF="5690386d8d731c9bebda536a5c71c890f6dfe98c" +ENV OPENPILOT_REF="bc4b75822a609e6897058bc83688c84004f29093" ENV OPENDBC_REF="1745ab51825055cd18748013c4a5e3377319e390" COPY requirements.txt /tmp/ diff --git a/pyproject.toml b/pyproject.toml index ee89db28e..661e775f0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -9,6 +9,4 @@ ignore = ["W292", "E741", "E402", "C408", "ISC003"] flake8-implicit-str-concat.allow-multiline=false [tool.pytest.ini_options] -# FIXME: pytest 8.0.0 now collects all files, stop pytest-cpp from running these -# the `not Base` filter is needed due to a bug in pytest w/ unittest: https://github.com/pytest-dev/pytest/issues/11552 -addopts = "--ignore=test.sh -n auto -k 'not Base'" +addopts = "-n auto" From 2eb85781960ec4e69019222d8eea658f9e63d4c1 Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Tue, 9 Apr 2024 11:02:22 -0700 Subject: [PATCH 61/67] pre-commit: autoupdate hooks (#1924) Update pre-commit hook versions Co-authored-by: adeebshihadeh --- .pre-commit-config.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 0a2f32685..85e9a68af 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,6 +1,6 @@ repos: - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.5.0 + rev: v4.6.0 hooks: - id: check-ast - id: check-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.3.4 + rev: v0.3.5 hooks: - id: ruff From 714642ec9a9795cab58c67a98bd2828f48e778d9 Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Wed, 17 Apr 2024 10:15:40 -0700 Subject: [PATCH 62/67] Remove WebUSB popup (#1932) --- board/drivers/usb.h | 21 +++------------------ 1 file changed, 3 insertions(+), 18 deletions(-) diff --git a/board/drivers/usb.h b/board/drivers/usb.h index ddd6b29c3..e00637221 100644 --- a/board/drivers/usb.h +++ b/board/drivers/usb.h @@ -304,13 +304,6 @@ uint8_t binary_object_store_desc[] = { MS_VENDOR_CODE, 0x00 // vendor code, no alternate enumeration }; -uint8_t webusb_url_descriptor[] = { - 0x14, /* bLength */ - WEBUSB_DESC_TYPE_URL, // bDescriptorType - WEBUSB_URL_SCHEME_HTTPS, // bScheme - 'u', 's', 'b', 'p', 'a', 'n', 'd', 'a', '.', 'c', 'o', 'm', 'm', 'a', '.', 'a', 'i' -}; - // WinUSB 2.0 descriptor. This is what modern systems use // https://github.com/sowbug/weblight/blob/192ad7a0e903542e2aa28c607d98254a12a6399d/firmware/webusb.c // http://janaxelson.com/files/ms_os_20_descriptors.c @@ -603,17 +596,9 @@ void usb_setup(void) { USBx_OUTEP(0U)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; break; case WEBUSB_VENDOR_CODE: - switch (setup.b.wIndex.w) { - case WEBUSB_REQ_GET_URL: - USB_WritePacket(webusb_url_descriptor, MIN(sizeof(webusb_url_descriptor), setup.b.wLength.w), 0); - USBx_OUTEP(0U)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; - break; - default: - // probably asking for allowed origins, which was removed from the spec - USB_WritePacket(0, 0, 0); - USBx_OUTEP(0U)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; - break; - } + // probably asking for allowed origins, which was removed from the spec + USB_WritePacket(0, 0, 0); + USBx_OUTEP(0U)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; break; case MS_VENDOR_CODE: switch (setup.b.wIndex.w) { From edcd0fe4d41be59b7a5f046e68fee93e6898357f Mon Sep 17 00:00:00 2001 From: Shane Smiskol Date: Wed, 17 Apr 2024 23:23:50 -0700 Subject: [PATCH 63/67] IsoTpMessage: extend timeout on first frame response (#1933) * extend on first frame too * debug/checks * fix able to go from single to first to single etc forever * more clean up * more clean up * comments! --- python/uds.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/python/uds.py b/python/uds.py index 12b4fcdc2..32b0de096 100644 --- a/python/uds.py +++ b/python/uds.py @@ -455,7 +455,8 @@ class IsoTpMessage(): for msg in self._can_client.recv(): frame_type = self._isotp_rx_next(msg) start_time = time.monotonic() - rx_in_progress = frame_type == ISOTP_FRAME_TYPE.CONSECUTIVE + # Anything that signifies we're building a response + rx_in_progress = frame_type in (ISOTP_FRAME_TYPE.FIRST, ISOTP_FRAME_TYPE.CONSECUTIVE) if self.tx_done and self.rx_done: return self.rx_dat, False # no timeout indicates non-blocking @@ -473,6 +474,7 @@ class IsoTpMessage(): # assert len(rx_data) == self.max_len, f"isotp - rx: invalid CAN frame length: {len(rx_data)}" if rx_data[0] >> 4 == ISOTP_FRAME_TYPE.SINGLE: + assert self.rx_dat == b"" or self.rx_done, "isotp - rx: single frame with active frame" self.rx_len = rx_data[0] & 0x0F assert self.rx_len < self.max_len, f"isotp - rx: invalid single frame length: {self.rx_len}" self.rx_dat = rx_data[1:1 + self.rx_len] @@ -483,8 +485,11 @@ class IsoTpMessage(): return ISOTP_FRAME_TYPE.SINGLE elif rx_data[0] >> 4 == ISOTP_FRAME_TYPE.FIRST: + # Once a first frame is received, further frames must be consecutive + assert self.rx_dat == b"" or self.rx_done, "isotp - rx: first frame with active frame" self.rx_len = ((rx_data[0] & 0x0F) << 8) + rx_data[1] - assert self.max_len <= self.rx_len, f"isotp - rx: invalid first frame length: {self.rx_len}" + assert self.rx_len >= self.max_len, f"isotp - rx: invalid first frame length: {self.rx_len}" + assert len(rx_data) == self.max_len, f"isotp - rx: invalid CAN frame length: {len(rx_data)}" self.rx_dat = rx_data[2:] self.rx_idx = 0 self.rx_done = False From 4d60ae9c6202be1b277a03cbb670c7f2639ad7cd Mon Sep 17 00:00:00 2001 From: Justin Newberry Date: Thu, 18 Apr 2024 17:59:33 -0700 Subject: [PATCH 64/67] CI: fix misra mutation tests (#1934) * fix that * skip build, install first * Revert "skip build, install first" This reverts commit 01efdb77ce3d834b55bbed1172ca83bb0103bfc8. * prune --- .github/workflows/test.yaml | 2 +- pyproject.toml | 3 +++ tests/misra/install.sh | 1 + tests/misra/test_mutation.py | 3 --- 4 files changed, 5 insertions(+), 4 deletions(-) diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index 968ee3ecf..ffe597abf 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -104,7 +104,7 @@ jobs: run: ${{ env.RUN }} "cd tests/misra && ./test_misra.sh" - name: MISRA mutation tests timeout-minutes: 4 - run: ${{ env.RUN }} "cd tests/misra && ./test_mutation.py" + run: ${{ env.RUN }} "cd tests/misra && pytest -n8 test_mutation.py" python_linter: name: python linter diff --git a/pyproject.toml b/pyproject.toml index 661e775f0..375885e54 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -8,5 +8,8 @@ select = ["E", "F", "W", "PIE", "C4", "ISC", "RUF100", "A"] ignore = ["W292", "E741", "E402", "C408", "ISC003"] flake8-implicit-str-concat.allow-multiline=false +[tool.ruff.lint.flake8-tidy-imports.banned-api] +"pytest.main".msg = "pytest.main requires special handling that is easy to mess up!" + [tool.pytest.ini_options] addopts = "-n auto" diff --git a/tests/misra/install.sh b/tests/misra/install.sh index 8b264aa61..6a8a9acb3 100755 --- a/tests/misra/install.sh +++ b/tests/misra/install.sh @@ -11,6 +11,7 @@ fi cd $CPPCHECK_DIR VERS="2.13.4" +git remote prune origin git fetch --all --tags git checkout $VERS git cherry-pick -n f6b538e855f0bacea33c4074664628024ef39dc6 b11b42087ff29569bc3740f5aa07eb6616ea4f63 diff --git a/tests/misra/test_mutation.py b/tests/misra/test_mutation.py index 9e778e88b..cf23cf8c6 100755 --- a/tests/misra/test_mutation.py +++ b/tests/misra/test_mutation.py @@ -79,6 +79,3 @@ def test_misra_mutation(fn, patch, should_fail): r = subprocess.run("tests/misra/test_misra.sh", cwd=tmp, shell=True) failed = r.returncode != 0 assert failed == should_fail - -if __name__ == "__main__": - pytest.main([__file__, "-n 8"]) From 698d17e02127498181c97be8ef2e380c887e944f Mon Sep 17 00:00:00 2001 From: Justin Newberry Date: Mon, 22 Apr 2024 10:28:53 -0700 Subject: [PATCH 65/67] fix inconsistent misra mutation tests (#1935) * revert * fix --- .github/workflows/test.yaml | 2 +- Dockerfile | 2 ++ tests/misra/install.sh | 1 - tests/misra/test_misra.sh | 2 +- tests/misra/test_mutation.py | 3 ++- 5 files changed, 6 insertions(+), 4 deletions(-) diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index ffe597abf..1319ebaf2 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -103,7 +103,7 @@ jobs: timeout-minutes: 1 run: ${{ env.RUN }} "cd tests/misra && ./test_misra.sh" - name: MISRA mutation tests - timeout-minutes: 4 + timeout-minutes: 5 run: ${{ env.RUN }} "cd tests/misra && pytest -n8 test_mutation.py" python_linter: diff --git a/Dockerfile b/Dockerfile index 63601740e..ffd5a00a8 100644 --- a/Dockerfile +++ b/Dockerfile @@ -63,6 +63,8 @@ RUN pyenv install 3.11.4 && \ ENV CPPCHECK_DIR=/tmp/cppcheck COPY tests/misra/install.sh /tmp/ RUN /tmp/install.sh +# don't try to install again +ENV SKIP_CPPCHECK_INSTALL=1 RUN git config --global --add safe.directory /tmp/openpilot/panda RUN cd /tmp && \ diff --git a/tests/misra/install.sh b/tests/misra/install.sh index 6a8a9acb3..8b264aa61 100755 --- a/tests/misra/install.sh +++ b/tests/misra/install.sh @@ -11,7 +11,6 @@ fi cd $CPPCHECK_DIR VERS="2.13.4" -git remote prune origin git fetch --all --tags git checkout $VERS git cherry-pick -n f6b538e855f0bacea33c4074664628024ef39dc6 b11b42087ff29569bc3740f5aa07eb6616ea4f63 diff --git a/tests/misra/test_misra.sh b/tests/misra/test_misra.sh index 482eba241..982a62e74 100755 --- a/tests/misra/test_misra.sh +++ b/tests/misra/test_misra.sh @@ -10,7 +10,7 @@ NC='\033[0m' : "${CPPCHECK_DIR:=$DIR/cppcheck/}" # install cppcheck if missing -if [ -z "${SKIP_BUILD}" ]; then +if [ -z "${SKIP_CPPCHECK_INSTALL}" ]; then $DIR/install.sh fi diff --git a/tests/misra/test_mutation.py b/tests/misra/test_mutation.py index cf23cf8c6..06ce266e8 100755 --- a/tests/misra/test_mutation.py +++ b/tests/misra/test_mutation.py @@ -21,7 +21,8 @@ IGNORED_PATHS = ( 'board/flasher.h', 'board/bootstub.c', 'board/bootstub_declarations.h', - 'board/stm32f4/llflash.h' + 'board/stm32h7/llflash.h', + 'board/stm32f4/llflash.h', ) mutations = [ From 58fc949f72056d4e412256a752350209ed8fbdbf Mon Sep 17 00:00:00 2001 From: commaci-public <60409688+commaci-public@users.noreply.github.com> Date: Tue, 23 Apr 2024 08:07:33 -0700 Subject: [PATCH 66/67] pre-commit: autoupdate hooks (#1939) 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 85e9a68af..a9d1d8166 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.3.5 + rev: v0.4.1 hooks: - id: ruff From 6f9e2c5159cc7ed3bb945faec5acb9433c5163c0 Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Tue, 23 Apr 2024 20:39:40 -0700 Subject: [PATCH 67/67] show USB list + connector errors --- python/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python/__init__.py b/python/__init__.py index b69b30eae..8567118f2 100644 --- a/python/__init__.py +++ b/python/__init__.py @@ -361,7 +361,7 @@ class Panda: try: this_serial = device.getSerialNumber() except Exception: - continue + logging.exception("failed to get serial number of panda") if serial is None or this_serial == serial: logging.debug("opening device %s %s", this_serial, hex(device.getProductID())) @@ -412,7 +412,7 @@ class Panda: else: logging.warning(f"found device with panda descriptors but invalid serial: {serial}", RuntimeWarning) except Exception: - continue + logging.exception("error connecting to panda") except Exception: logging.exception("exception while listing pandas") return ret