From 5eb75de2494610e18d66d33fb3452ab879014f3a Mon Sep 17 00:00:00 2001 From: Vehicle Researcher Date: Sat, 23 Dec 2017 17:10:42 -0800 Subject: [PATCH] Squashed 'panda/' content from commit c371fe6 git-subtree-dir: panda git-subtree-split: c371fe688dbad4c53635905d3471a01c185e811d old-commit-hash: c251b312d87d26b5ed347b267f6f1570793f9b91 --- .gitattributes | 87 + .gitignore | 12 + .travis.yml | 20 + LICENSE | 7 + README.md | 89 + TODO | 31 + UPDATING.md | 9 + VERSION | 1 + __init__.py | 1 + board/Makefile | 8 + board/Makefile.legacy | 9 + board/README.md | 41 + board/__init__.py | 0 board/bootstub.c | 91 + board/build.mk | 59 + board/config.h | 40 + board/drivers/adc.h | 38 + board/drivers/can.h | 401 +++++ board/drivers/dac.h | 16 + board/drivers/drivers.h | 141 ++ board/drivers/llgpio.h | 35 + board/drivers/spi.h | 120 ++ board/drivers/timer.h | 7 + board/drivers/uart.h | 224 +++ board/drivers/usb.h | 705 ++++++++ board/get_sdk.sh | 3 + board/get_sdk_mac.sh | 5 + board/gpio.h | 450 +++++ board/inc/cmsis_gcc.h | 3 + board/inc/core_cm3.h | 3 + board/inc/core_cm4.h | 3 + board/inc/core_cmFunc.h | 3 + board/inc/core_cmInstr.h | 3 + board/inc/core_cmSimd.h | 3 + board/inc/stm32f205xx.h | 3 + board/inc/stm32f2xx.h | 3 + board/inc/stm32f2xx_hal_def.h | 3 + board/inc/stm32f2xx_hal_gpio_ex.h | 3 + board/inc/stm32f413xx.h | 3 + board/inc/stm32f4xx.h | 3 + board/inc/stm32f4xx_hal_def.h | 3 + board/inc/stm32f4xx_hal_gpio_ex.h | 3 + board/inc/system_stm32f2xx.h | 3 + board/inc/system_stm32f4xx.h | 3 + board/libc.h | 51 + board/main.c | 644 +++++++ board/obj/.placeholder | 0 board/provision.h | 13 + board/safety.h | 73 + board/safety/safety_defaults.h | 44 + board/safety/safety_elm327.h | 39 + board/safety/safety_honda.h | 128 ++ board/safety/safety_toyota.h | 179 ++ board/spi_flasher.h | 186 ++ board/startup_stm32f205xx.s | 511 ++++++ board/startup_stm32f413xx.s | 583 ++++++ board/stm32_flash.ld | 165 ++ board/tests/test_rsa.c | 35 + board/tools/dfu-util-aarch64 | 3 + board/tools/dfu-util-aarch64-linux | 3 + board/tools/dfu-util-x86_64-linux | 3 + board/tools/enter_download_mode.py | 33 + boardesp/.gitignore | 8 + boardesp/ELM327.md | 101 ++ boardesp/Makefile | 74 + boardesp/README.md | 22 + boardesp/elm327.c | 1576 ++++++++++++++++ boardesp/get_sdk.sh | 12 + boardesp/get_sdk_mac.sh | 32 + boardesp/include/espmissingincludes.h | 78 + boardesp/obj/.placeholder | 0 boardesp/proxy.c | 361 ++++ boardesp/user_config.h | 0 boardesp/webserver.c | 373 ++++ buy.png | 3 + certs/debug | 15 + certs/debug.pub | 1 + certs/debugesp | 15 + certs/debugesp.pub | 1 + certs/release.pub | 1 + certs/releaseesp.pub | 1 + common/version.mk | 18 + crypto/getcertheader.py | 46 + crypto/hash-internal.h | 63 + crypto/rsa.c | 294 +++ crypto/rsa.h | 58 + crypto/sha.c | 153 ++ crypto/sha.h | 51 + crypto/sign.py | 29 + crypto/stdint.h | 4 + docs/guide.pdf | 3 + drivers/linux/.gitignore | 6 + drivers/linux/Makefile | 18 + drivers/linux/README.md | 19 + drivers/linux/dkms.conf | 6 + drivers/linux/panda.c | 613 +++++++ drivers/linux/test/Makefile | 2 + drivers/linux/test/main.c | 120 ++ drivers/linux/test/run.sh | 4 + drivers/windows/.gitignore | 306 ++++ drivers/windows/ECUsim CLI/ECUsim CLI.cpp | 38 + drivers/windows/ECUsim CLI/ECUsim CLI.vcxproj | 178 ++ .../ECUsim CLI/ECUsim CLI.vcxproj.filters | 36 + drivers/windows/ECUsim CLI/stdafx.cpp | 8 + drivers/windows/ECUsim CLI/stdafx.h | 15 + drivers/windows/ECUsim CLI/targetver.h | 8 + drivers/windows/ECUsim DLL/ECUsim DLL.vcxproj | 197 ++ .../ECUsim DLL/ECUsim DLL.vcxproj.filters | 42 + drivers/windows/ECUsim DLL/ECUsim.cpp | 261 +++ drivers/windows/ECUsim DLL/ECUsim.h | 50 + drivers/windows/ECUsim DLL/dllmain.cpp | 19 + drivers/windows/ECUsim DLL/stdafx.cpp | 8 + drivers/windows/ECUsim DLL/stdafx.h | 16 + drivers/windows/ECUsim DLL/targetver.h | 8 + drivers/windows/README.md | 177 ++ drivers/windows/docs/Message_Size.png | 3 + drivers/windows/docs/RxBits_defs.jpg | 3 + drivers/windows/docs/RxBits_valid.png | 3 + drivers/windows/docs/bus_init_signla.png | 3 + drivers/windows/docs/connection_flags.png | 3 + drivers/windows/docs/iso15765_ioctls.png | 3 + drivers/windows/docs/message_send.png | 3 + drivers/windows/docs/msg_filter_passfail.png | 3 + drivers/windows/docs/other notes.txt | 347 ++++ drivers/windows/docs/read_msg_flags.png | 3 + drivers/windows/docs/reginfo.txt | 2 + drivers/windows/docs/start_msg_filter.png | 3 + drivers/windows/docs/start_msg_filter2.png | 3 + drivers/windows/docs/start_msg_filter3.png | 3 + drivers/windows/docs/start_msg_filter4.png | 3 + drivers/windows/docs/timeout_info.txt | 42 + .../panda Driver Package.vcxproj | 99 + .../panda Driver Package.vcxproj.filters | 14 + .../windows/panda Driver Package/panda.inf | Bin 0 -> 4242 bytes drivers/windows/panda.ico | 3 + drivers/windows/panda.sln | 90 + drivers/windows/panda/device.cpp | 166 ++ drivers/windows/panda/device.h | 33 + drivers/windows/panda/dllmain.cpp | 19 + drivers/windows/panda/main.cpp | 79 + drivers/windows/panda/panda.cpp | 479 +++++ drivers/windows/panda/panda.h | 214 +++ drivers/windows/panda/panda.ico | 3 + drivers/windows/panda/panda.rc | Bin 0 -> 5150 bytes drivers/windows/panda/panda.vcxproj | 193 ++ drivers/windows/panda/panda.vcxproj.filters | 58 + drivers/windows/panda/resource.h | Bin 0 -> 898 bytes drivers/windows/panda/stdafx.cpp | 8 + drivers/windows/panda/stdafx.h | 19 + drivers/windows/panda/targetver.h | 13 + .../pandaJ2534DLL Test/ECUsim_tests.cpp | 87 + .../windows/pandaJ2534DLL Test/Loader4.cpp | 240 +++ drivers/windows/pandaJ2534DLL Test/Loader4.h | 55 + .../pandaJ2534DLL Test/TestHelpers.cpp | 254 +++ .../windows/pandaJ2534DLL Test/TestHelpers.h | 48 + drivers/windows/pandaJ2534DLL Test/Timer.cpp | 21 + drivers/windows/pandaJ2534DLL Test/Timer.h | 20 + .../pandaJ2534DLL Test/j2534_tests.cpp | 1602 +++++++++++++++++ .../pandaJ2534DLL Test.vcxproj | 125 ++ .../pandaJ2534DLL Test.vcxproj.filters | 63 + .../pandaJ2534DLL Test/panda_tests.cpp | 187 ++ drivers/windows/pandaJ2534DLL Test/stdafx.cpp | 8 + drivers/windows/pandaJ2534DLL Test/stdafx.h | 14 + .../windows/pandaJ2534DLL Test/targetver.h | 8 + drivers/windows/pandaJ2534DLL/Action.h | 57 + .../windows/pandaJ2534DLL/J2534Connection.cpp | 257 +++ .../windows/pandaJ2534DLL/J2534Connection.h | 141 ++ .../pandaJ2534DLL/J2534Connection_CAN.cpp | 41 + .../pandaJ2534DLL/J2534Connection_CAN.h | 43 + .../J2534Connection_ISO15765.cpp | 229 +++ .../pandaJ2534DLL/J2534Connection_ISO15765.h | 65 + drivers/windows/pandaJ2534DLL/J2534Frame.h | 48 + .../pandaJ2534DLL/J2534MessageFilter.cpp | 104 ++ .../pandaJ2534DLL/J2534MessageFilter.h | 47 + drivers/windows/pandaJ2534DLL/J2534_v0404.h | 428 +++++ .../pandaJ2534DLL/J2534register_x64.reg | Bin 0 -> 1056 bytes .../windows/pandaJ2534DLL/MessagePeriodic.cpp | 30 + .../windows/pandaJ2534DLL/MessagePeriodic.h | 33 + drivers/windows/pandaJ2534DLL/MessageRx.h | 61 + drivers/windows/pandaJ2534DLL/MessageTx.h | 25 + .../pandaJ2534DLL/MessageTxTimeout.cpp | 43 + .../windows/pandaJ2534DLL/MessageTxTimeout.h | 52 + .../windows/pandaJ2534DLL/MessageTx_CAN.cpp | 44 + drivers/windows/pandaJ2534DLL/MessageTx_CAN.h | 33 + .../pandaJ2534DLL/MessageTx_ISO15765.cpp | 180 ++ .../pandaJ2534DLL/MessageTx_ISO15765.h | 54 + .../pandaJ2534DLL/PandaJ2534Device.cpp | 214 +++ .../windows/pandaJ2534DLL/PandaJ2534Device.h | 77 + drivers/windows/pandaJ2534DLL/Timer.cpp | 17 + drivers/windows/pandaJ2534DLL/Timer.h | 18 + .../pandaJ2534DLL/constants_ISO15765.h | 20 + drivers/windows/pandaJ2534DLL/dllmain.cpp | 22 + drivers/windows/pandaJ2534DLL/dllmain.h | 4 + .../windows/pandaJ2534DLL/pandaJ2534DLL.cpp | 433 +++++ .../windows/pandaJ2534DLL/pandaJ2534DLL.rc | Bin 0 -> 4630 bytes .../pandaJ2534DLL/pandaJ2534DLL.vcxproj | 152 ++ .../pandaJ2534DLL.vcxproj.filters | 155 ++ drivers/windows/pandaJ2534DLL/resource.h | 14 + drivers/windows/pandaJ2534DLL/stdafx.cpp | 8 + drivers/windows/pandaJ2534DLL/stdafx.h | 14 + drivers/windows/pandaJ2534DLL/synchronize.h | 56 + drivers/windows/pandaJ2534DLL/targetver.h | 13 + drivers/windows/panda_install.nsi | 212 +++ drivers/windows/panda_playground/ReadMe.txt | 40 + .../panda_playground/panda_playground.cpp | 86 + .../panda_playground/panda_playground.vcxproj | 191 ++ .../panda_playground.vcxproj.filters | 45 + drivers/windows/panda_playground/stdafx.cpp | 8 + drivers/windows/panda_playground/stdafx.h | 17 + drivers/windows/panda_playground/targetver.h | 8 + drivers/windows/panda_remove.ico | 3 + drivers/windows/redist/.gitignore | 2 + drivers/windows/redist/README.md | 7 + .../windows/redist/vscruntimeinfo.nsh.sample | 13 + .../windows/test certs/commaaiCertStore.pvk | Bin 0 -> 1196 bytes drivers/windows/test certs/commaaicert.cer | Bin 0 -> 756 bytes examples/__init__.py | 0 examples/can_logger.py | 54 + examples/can_unique.md | 103 ++ examples/can_unique.py | 91 + examples/isotp.py | 77 + examples/query_vin_and_stats.py | 59 + examples/tesla_tester.py | 63 + panda.png | 3 + python/__init__.py | 484 +++++ python/dfu.py | 122 ++ python/esptool.py | 1314 ++++++++++++++ python/flash_release.py | 95 + python/update.py | 44 + release/.gitignore | 1 + release/make_release.sh | 40 + release/ota_release.sh | 18 + requirements.txt | 4 + run_automated_tests.sh | 3 + setup.cfg | 2 + setup.py | 65 + tests/__init__.py | 0 tests/all_wifi_test.py | 29 + tests/automated/0_builds.py | 15 + tests/automated/1_program.py | 11 + tests/automated/2_usb_to_can.py | 186 ++ tests/automated/3_wifi.py | 33 + tests/automated/4_wifi_functionality.py | 52 + tests/automated/5_wifi_udp.py | 39 + tests/automated/__init__.py | 0 tests/automated/elm_wifi.py | 669 +++++++ tests/automated/helpers.py | 75 + tests/can_printer.py | 37 + tests/debug_console.py | 41 + tests/disable_esp.py | 4 + tests/elm_car_simulator.py | 325 ++++ tests/elm_throughput.py | 46 + tests/flashing_loop.sh | 9 + tests/get_version.py | 9 + tests/loopback_test.py | 127 ++ tests/read_st_flash.sh | 6 + tests/standalone_test.py | 38 + tests/throughput_test.py | 64 + 258 files changed, 23912 insertions(+) create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 .travis.yml create mode 100644 LICENSE create mode 100644 README.md create mode 100644 TODO create mode 100644 UPDATING.md create mode 100644 VERSION create mode 100644 __init__.py create mode 100644 board/Makefile create mode 100644 board/Makefile.legacy create mode 100644 board/README.md create mode 100644 board/__init__.py create mode 100644 board/bootstub.c create mode 100644 board/build.mk create mode 100644 board/config.h create mode 100644 board/drivers/adc.h create mode 100644 board/drivers/can.h create mode 100644 board/drivers/dac.h create mode 100644 board/drivers/drivers.h create mode 100644 board/drivers/llgpio.h create mode 100644 board/drivers/spi.h create mode 100644 board/drivers/timer.h create mode 100644 board/drivers/uart.h create mode 100644 board/drivers/usb.h create mode 100755 board/get_sdk.sh create mode 100644 board/get_sdk_mac.sh create mode 100644 board/gpio.h create mode 100644 board/inc/cmsis_gcc.h create mode 100644 board/inc/core_cm3.h create mode 100644 board/inc/core_cm4.h create mode 100644 board/inc/core_cmFunc.h create mode 100644 board/inc/core_cmInstr.h create mode 100644 board/inc/core_cmSimd.h create mode 100644 board/inc/stm32f205xx.h create mode 100644 board/inc/stm32f2xx.h create mode 100644 board/inc/stm32f2xx_hal_def.h create mode 100644 board/inc/stm32f2xx_hal_gpio_ex.h create mode 100644 board/inc/stm32f413xx.h create mode 100644 board/inc/stm32f4xx.h create mode 100644 board/inc/stm32f4xx_hal_def.h create mode 100644 board/inc/stm32f4xx_hal_gpio_ex.h create mode 100644 board/inc/system_stm32f2xx.h create mode 100644 board/inc/system_stm32f4xx.h create mode 100644 board/libc.h create mode 100644 board/main.c create mode 100644 board/obj/.placeholder create mode 100644 board/provision.h create mode 100644 board/safety.h create mode 100644 board/safety/safety_defaults.h create mode 100644 board/safety/safety_elm327.h create mode 100644 board/safety/safety_honda.h create mode 100644 board/safety/safety_toyota.h create mode 100644 board/spi_flasher.h create mode 100644 board/startup_stm32f205xx.s create mode 100644 board/startup_stm32f413xx.s create mode 100644 board/stm32_flash.ld create mode 100644 board/tests/test_rsa.c create mode 100755 board/tools/dfu-util-aarch64 create mode 100755 board/tools/dfu-util-aarch64-linux create mode 100755 board/tools/dfu-util-x86_64-linux create mode 100755 board/tools/enter_download_mode.py create mode 100644 boardesp/.gitignore create mode 100644 boardesp/ELM327.md create mode 100644 boardesp/Makefile create mode 100644 boardesp/README.md create mode 100644 boardesp/elm327.c create mode 100755 boardesp/get_sdk.sh create mode 100755 boardesp/get_sdk_mac.sh create mode 100644 boardesp/include/espmissingincludes.h create mode 100644 boardesp/obj/.placeholder create mode 100644 boardesp/proxy.c create mode 100644 boardesp/user_config.h create mode 100644 boardesp/webserver.c create mode 100644 buy.png create mode 100644 certs/debug create mode 100644 certs/debug.pub create mode 100644 certs/debugesp create mode 100644 certs/debugesp.pub create mode 100644 certs/release.pub create mode 100644 certs/releaseesp.pub create mode 100644 common/version.mk create mode 100755 crypto/getcertheader.py create mode 100644 crypto/hash-internal.h create mode 100644 crypto/rsa.c create mode 100644 crypto/rsa.h create mode 100644 crypto/sha.c create mode 100644 crypto/sha.h create mode 100755 crypto/sign.py create mode 100644 crypto/stdint.h create mode 100644 docs/guide.pdf create mode 100644 drivers/linux/.gitignore create mode 100644 drivers/linux/Makefile create mode 100644 drivers/linux/README.md create mode 100644 drivers/linux/dkms.conf create mode 100644 drivers/linux/panda.c create mode 100644 drivers/linux/test/Makefile create mode 100644 drivers/linux/test/main.c create mode 100755 drivers/linux/test/run.sh create mode 100644 drivers/windows/.gitignore create mode 100644 drivers/windows/ECUsim CLI/ECUsim CLI.cpp create mode 100644 drivers/windows/ECUsim CLI/ECUsim CLI.vcxproj create mode 100644 drivers/windows/ECUsim CLI/ECUsim CLI.vcxproj.filters create mode 100644 drivers/windows/ECUsim CLI/stdafx.cpp create mode 100644 drivers/windows/ECUsim CLI/stdafx.h create mode 100644 drivers/windows/ECUsim CLI/targetver.h create mode 100644 drivers/windows/ECUsim DLL/ECUsim DLL.vcxproj create mode 100644 drivers/windows/ECUsim DLL/ECUsim DLL.vcxproj.filters create mode 100644 drivers/windows/ECUsim DLL/ECUsim.cpp create mode 100644 drivers/windows/ECUsim DLL/ECUsim.h create mode 100644 drivers/windows/ECUsim DLL/dllmain.cpp create mode 100644 drivers/windows/ECUsim DLL/stdafx.cpp create mode 100644 drivers/windows/ECUsim DLL/stdafx.h create mode 100644 drivers/windows/ECUsim DLL/targetver.h create mode 100644 drivers/windows/README.md create mode 100644 drivers/windows/docs/Message_Size.png create mode 100644 drivers/windows/docs/RxBits_defs.jpg create mode 100644 drivers/windows/docs/RxBits_valid.png create mode 100644 drivers/windows/docs/bus_init_signla.png create mode 100644 drivers/windows/docs/connection_flags.png create mode 100644 drivers/windows/docs/iso15765_ioctls.png create mode 100644 drivers/windows/docs/message_send.png create mode 100644 drivers/windows/docs/msg_filter_passfail.png create mode 100644 drivers/windows/docs/other notes.txt create mode 100644 drivers/windows/docs/read_msg_flags.png create mode 100644 drivers/windows/docs/reginfo.txt create mode 100644 drivers/windows/docs/start_msg_filter.png create mode 100644 drivers/windows/docs/start_msg_filter2.png create mode 100644 drivers/windows/docs/start_msg_filter3.png create mode 100644 drivers/windows/docs/start_msg_filter4.png create mode 100644 drivers/windows/docs/timeout_info.txt create mode 100644 drivers/windows/panda Driver Package/panda Driver Package.vcxproj create mode 100644 drivers/windows/panda Driver Package/panda Driver Package.vcxproj.filters create mode 100644 drivers/windows/panda Driver Package/panda.inf create mode 100644 drivers/windows/panda.ico create mode 100644 drivers/windows/panda.sln create mode 100644 drivers/windows/panda/device.cpp create mode 100644 drivers/windows/panda/device.h create mode 100644 drivers/windows/panda/dllmain.cpp create mode 100644 drivers/windows/panda/main.cpp create mode 100644 drivers/windows/panda/panda.cpp create mode 100644 drivers/windows/panda/panda.h create mode 100644 drivers/windows/panda/panda.ico create mode 100644 drivers/windows/panda/panda.rc create mode 100644 drivers/windows/panda/panda.vcxproj create mode 100644 drivers/windows/panda/panda.vcxproj.filters create mode 100644 drivers/windows/panda/resource.h create mode 100644 drivers/windows/panda/stdafx.cpp create mode 100644 drivers/windows/panda/stdafx.h create mode 100644 drivers/windows/panda/targetver.h create mode 100644 drivers/windows/pandaJ2534DLL Test/ECUsim_tests.cpp create mode 100644 drivers/windows/pandaJ2534DLL Test/Loader4.cpp create mode 100644 drivers/windows/pandaJ2534DLL Test/Loader4.h create mode 100644 drivers/windows/pandaJ2534DLL Test/TestHelpers.cpp create mode 100644 drivers/windows/pandaJ2534DLL Test/TestHelpers.h create mode 100644 drivers/windows/pandaJ2534DLL Test/Timer.cpp create mode 100644 drivers/windows/pandaJ2534DLL Test/Timer.h create mode 100644 drivers/windows/pandaJ2534DLL Test/j2534_tests.cpp create mode 100644 drivers/windows/pandaJ2534DLL Test/pandaJ2534DLL Test.vcxproj create mode 100644 drivers/windows/pandaJ2534DLL Test/pandaJ2534DLL Test.vcxproj.filters create mode 100644 drivers/windows/pandaJ2534DLL Test/panda_tests.cpp create mode 100644 drivers/windows/pandaJ2534DLL Test/stdafx.cpp create mode 100644 drivers/windows/pandaJ2534DLL Test/stdafx.h create mode 100644 drivers/windows/pandaJ2534DLL Test/targetver.h create mode 100644 drivers/windows/pandaJ2534DLL/Action.h create mode 100644 drivers/windows/pandaJ2534DLL/J2534Connection.cpp create mode 100644 drivers/windows/pandaJ2534DLL/J2534Connection.h create mode 100644 drivers/windows/pandaJ2534DLL/J2534Connection_CAN.cpp create mode 100644 drivers/windows/pandaJ2534DLL/J2534Connection_CAN.h create mode 100644 drivers/windows/pandaJ2534DLL/J2534Connection_ISO15765.cpp create mode 100644 drivers/windows/pandaJ2534DLL/J2534Connection_ISO15765.h create mode 100644 drivers/windows/pandaJ2534DLL/J2534Frame.h create mode 100644 drivers/windows/pandaJ2534DLL/J2534MessageFilter.cpp create mode 100644 drivers/windows/pandaJ2534DLL/J2534MessageFilter.h create mode 100644 drivers/windows/pandaJ2534DLL/J2534_v0404.h create mode 100644 drivers/windows/pandaJ2534DLL/J2534register_x64.reg create mode 100644 drivers/windows/pandaJ2534DLL/MessagePeriodic.cpp create mode 100644 drivers/windows/pandaJ2534DLL/MessagePeriodic.h create mode 100644 drivers/windows/pandaJ2534DLL/MessageRx.h create mode 100644 drivers/windows/pandaJ2534DLL/MessageTx.h create mode 100644 drivers/windows/pandaJ2534DLL/MessageTxTimeout.cpp create mode 100644 drivers/windows/pandaJ2534DLL/MessageTxTimeout.h create mode 100644 drivers/windows/pandaJ2534DLL/MessageTx_CAN.cpp create mode 100644 drivers/windows/pandaJ2534DLL/MessageTx_CAN.h create mode 100644 drivers/windows/pandaJ2534DLL/MessageTx_ISO15765.cpp create mode 100644 drivers/windows/pandaJ2534DLL/MessageTx_ISO15765.h create mode 100644 drivers/windows/pandaJ2534DLL/PandaJ2534Device.cpp create mode 100644 drivers/windows/pandaJ2534DLL/PandaJ2534Device.h create mode 100644 drivers/windows/pandaJ2534DLL/Timer.cpp create mode 100644 drivers/windows/pandaJ2534DLL/Timer.h create mode 100644 drivers/windows/pandaJ2534DLL/constants_ISO15765.h create mode 100644 drivers/windows/pandaJ2534DLL/dllmain.cpp create mode 100644 drivers/windows/pandaJ2534DLL/dllmain.h create mode 100644 drivers/windows/pandaJ2534DLL/pandaJ2534DLL.cpp create mode 100644 drivers/windows/pandaJ2534DLL/pandaJ2534DLL.rc create mode 100644 drivers/windows/pandaJ2534DLL/pandaJ2534DLL.vcxproj create mode 100644 drivers/windows/pandaJ2534DLL/pandaJ2534DLL.vcxproj.filters create mode 100644 drivers/windows/pandaJ2534DLL/resource.h create mode 100644 drivers/windows/pandaJ2534DLL/stdafx.cpp create mode 100644 drivers/windows/pandaJ2534DLL/stdafx.h create mode 100644 drivers/windows/pandaJ2534DLL/synchronize.h create mode 100644 drivers/windows/pandaJ2534DLL/targetver.h create mode 100644 drivers/windows/panda_install.nsi create mode 100644 drivers/windows/panda_playground/ReadMe.txt create mode 100644 drivers/windows/panda_playground/panda_playground.cpp create mode 100644 drivers/windows/panda_playground/panda_playground.vcxproj create mode 100644 drivers/windows/panda_playground/panda_playground.vcxproj.filters create mode 100644 drivers/windows/panda_playground/stdafx.cpp create mode 100644 drivers/windows/panda_playground/stdafx.h create mode 100644 drivers/windows/panda_playground/targetver.h create mode 100644 drivers/windows/panda_remove.ico create mode 100644 drivers/windows/redist/.gitignore create mode 100644 drivers/windows/redist/README.md create mode 100644 drivers/windows/redist/vscruntimeinfo.nsh.sample create mode 100644 drivers/windows/test certs/commaaiCertStore.pvk create mode 100644 drivers/windows/test certs/commaaicert.cer create mode 100644 examples/__init__.py create mode 100755 examples/can_logger.py create mode 100644 examples/can_unique.md create mode 100755 examples/can_unique.py create mode 100644 examples/isotp.py create mode 100755 examples/query_vin_and_stats.py create mode 100644 examples/tesla_tester.py create mode 100644 panda.png create mode 100644 python/__init__.py create mode 100644 python/dfu.py create mode 100755 python/esptool.py create mode 100755 python/flash_release.py create mode 100755 python/update.py create mode 100644 release/.gitignore create mode 100755 release/make_release.sh create mode 100755 release/ota_release.sh create mode 100644 requirements.txt create mode 100755 run_automated_tests.sh create mode 100644 setup.cfg create mode 100644 setup.py create mode 100644 tests/__init__.py create mode 100755 tests/all_wifi_test.py create mode 100644 tests/automated/0_builds.py create mode 100644 tests/automated/1_program.py create mode 100644 tests/automated/2_usb_to_can.py create mode 100644 tests/automated/3_wifi.py create mode 100644 tests/automated/4_wifi_functionality.py create mode 100644 tests/automated/5_wifi_udp.py create mode 100644 tests/automated/__init__.py create mode 100644 tests/automated/elm_wifi.py create mode 100644 tests/automated/helpers.py create mode 100755 tests/can_printer.py create mode 100755 tests/debug_console.py create mode 100755 tests/disable_esp.py create mode 100755 tests/elm_car_simulator.py create mode 100755 tests/elm_throughput.py create mode 100755 tests/flashing_loop.sh create mode 100755 tests/get_version.py create mode 100755 tests/loopback_test.py create mode 100755 tests/read_st_flash.sh create mode 100755 tests/standalone_test.py create mode 100755 tests/throughput_test.py diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000..cadb2c30d4 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,87 @@ +*.ico filter=lfs diff=lfs merge=lfs -text +*.dlc filter=lfs diff=lfs merge=lfs -text +*.onnx filter=lfs diff=lfs merge=lfs -text +*.svg filter=lfs diff=lfs merge=lfs -text +*.png filter=lfs diff=lfs merge=lfs -text +*.gif filter=lfs diff=lfs merge=lfs -text +*.ttf filter=lfs diff=lfs merge=lfs -text +*.wav filter=lfs diff=lfs merge=lfs -text +system/hardware/tici/updater filter=lfs diff=lfs merge=lfs -text +selfdrive/ui/qt/spinner_larch64 filter=lfs diff=lfs merge=lfs -text +selfdrive/ui/qt/text_larch64 filter=lfs diff=lfs merge=lfs -text +third_party/**/*.a filter=lfs diff=lfs merge=lfs -text +third_party/**/*.so filter=lfs diff=lfs merge=lfs -text +third_party/**/*.so.* filter=lfs diff=lfs merge=lfs -text +third_party/**/*.dylib filter=lfs diff=lfs merge=lfs -text +third_party/acados/*/t_renderer filter=lfs diff=lfs merge=lfs -text +third_party/qt5/larch64/bin/lrelease filter=lfs diff=lfs merge=lfs -text +third_party/qt5/larch64/bin/lupdate filter=lfs diff=lfs merge=lfs -text +third_party/catch2/include/catch2/catch.hpp filter=lfs diff=lfs merge=lfs -text +*.apk filter=lfs diff=lfs merge=lfs -text +*.apkpatch filter=lfs diff=lfs merge=lfs -text +*.jar filter=lfs diff=lfs merge=lfs -text +*.pdf filter=lfs diff=lfs merge=lfs -text +*.jpg filter=lfs diff=lfs merge=lfs -text +*.mp3 filter=lfs diff=lfs merge=lfs -text +*.thneed filter=lfs diff=lfs merge=lfs -text +*.tar.gz filter=lfs diff=lfs merge=lfs -text +*.npy filter=lfs diff=lfs merge=lfs -text +*.csv filter=lfs diff=lfs merge=lfs -text +*.a filter=lfs diff=lfs merge=lfs -text +*.so* filter=lfs diff=lfs merge=lfs -text +*.dylib filter=lfs diff=lfs merge=lfs -text +*.o filter=lfs diff=lfs merge=lfs -text +*.b64 filter=lfs diff=lfs merge=lfs -text +selfdrive/hardware/tici/updater filter=lfs diff=lfs merge=lfs -text +selfdrive/boardd/tests/test_boardd filter=lfs diff=lfs merge=lfs -text +selfdrive/ui/qt/spinner_aarch64 filter=lfs diff=lfs merge=lfs -text +installer/updater/updater filter=lfs diff=lfs merge=lfs -text +selfdrive/debug/profiling/simpleperf/**/* filter=lfs diff=lfs merge=lfs -text +selfdrive/hardware/eon/updater filter=lfs diff=lfs merge=lfs -text +selfdrive/ui/qt/text_aarch64 filter=lfs diff=lfs merge=lfs -text +selfdrive/debug/profiling/pyflame/**/* filter=lfs diff=lfs merge=lfs -text +installer/installers/installer_openpilot filter=lfs diff=lfs merge=lfs -text +installer/installers/installer_dashcam filter=lfs diff=lfs merge=lfs -text +selfdrive/ui/text/text filter=lfs diff=lfs merge=lfs -text +selfdrive/ui/android/text/text filter=lfs diff=lfs merge=lfs -text +selfdrive/ui/spinner/spinner filter=lfs diff=lfs merge=lfs -text +selfdrive/visiond/visiond filter=lfs diff=lfs merge=lfs -text +selfdrive/loggerd/loggerd filter=lfs diff=lfs merge=lfs -text +selfdrive/sensord/sensord filter=lfs diff=lfs merge=lfs -text +selfdrive/sensord/gpsd filter=lfs diff=lfs merge=lfs -text +selfdrive/ui/android/spinner/spinner filter=lfs diff=lfs merge=lfs -text +selfdrive/ui/qt/spinner filter=lfs diff=lfs merge=lfs -text +selfdrive/ui/qt/text filter=lfs diff=lfs merge=lfs -text +_stringdefs.py filter=lfs diff=lfs merge=lfs -text +dfu-util-aarch64-linux filter=lfs diff=lfs merge=lfs -text +dfu-util-aarch64 filter=lfs diff=lfs merge=lfs -text +dfu-util-x86_64-linux filter=lfs diff=lfs merge=lfs -text +dfu-util-x86_64 filter=lfs diff=lfs merge=lfs -text +stb_image.h filter=lfs diff=lfs merge=lfs -text +clpeak3 filter=lfs diff=lfs merge=lfs -text +clwaste filter=lfs diff=lfs merge=lfs -text +apk/**/* filter=lfs diff=lfs merge=lfs -text +external/**/* filter=lfs diff=lfs merge=lfs -text +phonelibs/**/* filter=lfs diff=lfs merge=lfs -text +third_party/boringssl/**/* filter=lfs diff=lfs merge=lfs -text +pyextra/**/* filter=lfs diff=lfs merge=lfs -text +panda/board/**/inc/*.h filter=lfs diff=lfs merge=lfs -text +panda/board/obj/*.elf filter=lfs diff=lfs merge=lfs -text +board/inc/*.h filter=lfs diff=lfs merge=lfs -text +third_party/nanovg/**/* filter=lfs diff=lfs merge=lfs -text +selfdrive/controls/lib/lateral_mpc/lib_mpc_export/**/* filter=lfs diff=lfs merge=lfs -text +third_party/android_hardware_libhardware/**/* filter=lfs diff=lfs merge=lfs -text +selfdrive/controls/lib/lead_mpc_lib/lib_mpc_export/**/* filter=lfs diff=lfs merge=lfs -text +*.pro filter=lfs diff=lfs merge=lfs -text +selfdrive/controls/lib/longitudinal_mpc/lib_mpc_export/**/* filter=lfs diff=lfs merge=lfs -text +selfdrive/controls/lib/lateral_mpc/mpc_export/**/* filter=lfs diff=lfs merge=lfs -text +third_party/curl/**/* filter=lfs diff=lfs merge=lfs -text +selfdrive/modeld/thneed/debug/**/* filter=lfs diff=lfs merge=lfs -text +selfdrive/modeld/thneed/include/**/* filter=lfs diff=lfs merge=lfs -text +third_party/openmax/**/* filter=lfs diff=lfs merge=lfs -text +selfdrive/controls/lib/longitudinal_mpc/mpc_export/**/* filter=lfs diff=lfs merge=lfs -text +selfdrive/controls/lib/longitudinal_mpc_model/lib_mpc_export/**/* filter=lfs diff=lfs merge=lfs -text +Pipfile filter=lfs diff=lfs merge=lfs -text +Pipfile.lock filter=lfs diff=lfs merge=lfs -text +poetry.lock filter=lfs diff=lfs merge=lfs -text +*.qm filter=lfs diff=lfs merge=lfs -text diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000..c589cb1c80 --- /dev/null +++ b/.gitignore @@ -0,0 +1,12 @@ +*.pyc +.*.swp +.*.swo +*.o +a.out +*~ +.#* +dist/ +pandacan.egg-info/ +board/obj/ +examples/output.csv +.DS_Store diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000000..603848fd24 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,20 @@ +language: python + +cache: + directories: + - build/commaai/panda/boardesp/esp-open-sdk/crosstool-NG + +addons: + apt: + packages: + - gcc-arm-none-eabi + - libnewlib-arm-none-eabi + - gperf + - texinfo + - help2man + +script: + - python setup.py install + - pushd board && make bin && popd + - pushd boardesp && git clone --recursive https://github.com/pfalcon/esp-open-sdk.git && pushd esp-open-sdk && git checkout 03f5e898a059451ec5f3de30e7feff30455f7cec && LD_LIBRARY_PATH="" make STANDALONE=y && popd && popd + - pushd boardesp && make user1.bin && popd diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000..8a6c6976b7 --- /dev/null +++ b/LICENSE @@ -0,0 +1,7 @@ +Copyright (c) 2016, Comma.ai, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000000..75424f9ce6 --- /dev/null +++ b/README.md @@ -0,0 +1,89 @@ +Welcome to panda +====== + +[panda](http://github.com/commaai/panda) is the nicest universal car interface ever. + + + + + +It supports 3x CAN, 2x LIN, and 1x GMLAN. It also charges a phone. On the computer side, it has both USB and Wi-Fi. + +It uses an [STM32F413](http://www.st.com/en/microcontrollers/stm32f413-423.html?querycriteria=productId=LN2004) for low level stuff and an [ESP8266](https://en.wikipedia.org/wiki/ESP8266) for Wi-Fi. They are connected over high speed SPI, so the panda is actually capable of dumping the full contents of the busses over Wi-Fi, unlike every other dongle on amazon. ELM327 is weak, panda is strong. + +It is 2nd gen hardware, reusing code and parts from the [NEO](https://github.com/commaai/neo) interface board. + +[![Build Status](https://travis-ci.org/commaai/panda.svg?branch=master)](https://travis-ci.org/commaai/panda) + +Usage +------ + +To install the library: +``` +# pip install pandacan +``` + +See [this class](https://github.com/commaai/panda/blob/master/python/__init__.py#L80) for how to interact with the panda. + +For example, to receive CAN messages: +``` +>>> from panda import Panda +>>> panda = Panda() +>>> panda.can_recv() +``` +And to send one on bus 0: +``` +>>> panda.can_send(0x1aa, "message", 0) +``` +More examples coming soon + +Software interface support +------ + +As a universal car interface, it should support every reasonable software interface. + +- User space ([done](https://github.com/commaai/panda/tree/master/python)) +- socketcan in kernel ([alpha](https://github.com/commaai/panda/tree/master/drivers/linux)) +- ELM327 ([done](https://github.com/commaai/panda/blob/master/boardesp/elm327.c)) +- Windows J2534 ([alpha](https://github.com/commaai/panda/tree/master/drivers/windows)) + +Directory structure +------ + +- board -- Code that runs on the STM32 +- boardesp -- Code that runs on the ESP8266 +- drivers -- Drivers (not needed for use with python) +- python   -- Python userspace library for interfacing with the panda +- tests -- Tests and helper programs for panda + +Programming (over USB) +------ + +[Programming the Board (STM32)](board/README.md) + +[Programming the ESP](boardesp/README.md) + + +Debugging +------ + +To print out the serial console from the STM32, run tests/debug_console.py + +To print out the serial console from the ESP8266, run PORT=1 tests/debug_console.py + +Safety Model +------ + +When a panda powers up, by default it's in "SAFETY_NOOUTPUT" mode. While in no output mode, the buses are also forced to be silent. In order to send messages, you have to select a safety mode. Currently, setting safety modes is only supported over USB. + +Safety modes can also optionally support "controls_allowed", which allows or blocks a subset of messages based on a piece of state in the board. + +Hardware +------ + +Check out the hardware [guide](https://github.com/commaai/panda/blob/master/docs/guide.pdf) + +Licensing +------ + +panda software is released under the MIT license unless otherwise specified. diff --git a/TODO b/TODO new file mode 100644 index 0000000000..4e4a355154 --- /dev/null +++ b/TODO @@ -0,0 +1,31 @@ +** Projects ** + +== ELM327 Emulator == + +Write an elm327 emulator in boardesp/elm327.c and make it work with Torque + +You'll find a start at this in the "elm327" branch. + +== socketcan Kernel Driver == + +Write a kernel driver version of lib/panda.py that exposes the Panda on socketcan and makes it work with those tools. + +You may want to switch to interrupt endpoint first. Should LIN be exposed as a serial interface? + +== Windows J2534 DLL == + +Write a Windows DLL that exposes the J2534 API. + +Will make the Panda work with car diagnostic software. + + +** Refactors ** + +== USB Interrupt Endpoint == + +Switch USB to use an interrupt endpoint instead of a bulk endpoint for can recv + +== WebSocket Support == + +Add CAN streaming over WebSocket to the ELM code in addition to the UDP pipe. + diff --git a/UPDATING.md b/UPDATING.md new file mode 100644 index 0000000000..100acc6bab --- /dev/null +++ b/UPDATING.md @@ -0,0 +1,9 @@ +# Updating your panda + +Panda should update automatically via the [Chffr](http://chffr.comma.ai/) app ([apple](https://itunes.apple.com/us/app/chffr-dash-cam-that-remembers/id1146683979) and [android](https://play.google.com/store/apps/details?id=ai.comma.chffr)) + +If it doesn't however, you can use the following commands on linux or Mac OSX + `sudo pip install --upgrade pandacan` +` PYTHONPATH="" sudo python -c "import panda; panda.flash_release()"` + +(You'll need to have `pip` and `sudo` installed.) diff --git a/VERSION b/VERSION new file mode 100644 index 0000000000..13637f44ae --- /dev/null +++ b/VERSION @@ -0,0 +1 @@ +v1.0.3 \ No newline at end of file diff --git a/__init__.py b/__init__.py new file mode 100644 index 0000000000..912b4427cc --- /dev/null +++ b/__init__.py @@ -0,0 +1 @@ +from .python import Panda, PandaWifiStreaming, PandaDFU, ESPROM, CesantaFlasher, flash_release, BASEDIR, ensure_st_up_to_date, build_st diff --git a/board/Makefile b/board/Makefile new file mode 100644 index 0000000000..af274d2b27 --- /dev/null +++ b/board/Makefile @@ -0,0 +1,8 @@ +PROJ_NAME = panda +CFLAGS = -g -Wall + +CFLAGS += -mlittle-endian -mthumb -mcpu=cortex-m4 +CFLAGS += -mhard-float -DSTM32F4 -DSTM32F413xx +STARTUP_FILE = startup_stm32f413xx + +include build.mk diff --git a/board/Makefile.legacy b/board/Makefile.legacy new file mode 100644 index 0000000000..f6f9f9f328 --- /dev/null +++ b/board/Makefile.legacy @@ -0,0 +1,9 @@ +# :set noet +PROJ_NAME = comma +CFLAGS = -g -Wall + +CFLAGS += -mlittle-endian -mthumb -mcpu=cortex-m3 +CFLAGS += -msoft-float -DSTM32F2 -DSTM32F205xx +STARTUP_FILE = startup_stm32f205xx + +include build.mk diff --git a/board/README.md b/board/README.md new file mode 100644 index 0000000000..b3be654be3 --- /dev/null +++ b/board/README.md @@ -0,0 +1,41 @@ +Dependencies +-------- + +**Mac** + +``` +./get_sdk_mac.sh +``` + +**Debian / Ubuntu** + +``` +./get_sdk.sh +``` + + +Programming +---- + +**Panda** + +``` +make +``` + +**NEO** + +``` +make -f Makefile.legacy +``` + +Troubleshooting +---- + +If your panda will not flash and is quickly blinking a single Green LED, use: +``` +make recover +``` + + +[dfu-util](http://github.com/dsigma/dfu-util.git) for flashing diff --git a/board/__init__.py b/board/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/board/bootstub.c b/board/bootstub.c new file mode 100644 index 0000000000..147d75a010 --- /dev/null +++ b/board/bootstub.c @@ -0,0 +1,91 @@ +#define BOOTSTUB + +#include "config.h" +#include "obj/gitversion.h" + +#ifdef STM32F4 + #define PANDA + #include "stm32f4xx.h" + #include "stm32f4xx_hal_gpio_ex.h" +#else + #include "stm32f2xx.h" + #include "stm32f2xx_hal_gpio_ex.h" +#endif + +#include "libc.h" +#include "provision.h" + +#include "drivers/drivers.h" + +#include "drivers/llgpio.h" +#include "gpio.h" + +#include "drivers/spi.h" +#include "drivers/usb.h" +//#include "drivers/uart.h" + +int puts(const char *a) { return 0; } +void puth(unsigned int i) {} + +#include "crypto/rsa.h" +#include "crypto/sha.h" + +#include "obj/cert.h" + +#include "spi_flasher.h" + +void __initialize_hardware_early() { + early(); +} + +void fail() { + soft_flasher_start(); +} + +// know where to sig check +extern void *_app_start[]; + +int main() { + __disable_irq(); + clock_init(); + detect(); + + if (revision == PANDA_REV_C) { + set_usb_power_mode(USB_POWER_CLIENT); + } + + if (enter_bootloader_mode == ENTER_SOFTLOADER_MAGIC) { + enter_bootloader_mode = 0; + soft_flasher_start(); + } + + // validate length + int len = (int)_app_start[0]; + if ((len < 8) || (len > (0x1000000 - 0x4000 - 4 - RSANUMBYTES))) goto fail; + + // compute SHA hash + uint8_t digest[SHA_DIGEST_SIZE]; + SHA_hash(&_app_start[1], len-4, digest); + + // verify RSA signature + if (RSA_verify(&release_rsa_key, ((void*)&_app_start[0]) + len, RSANUMBYTES, digest, SHA_DIGEST_SIZE)) { + goto good; + } + + // allow debug if built from source +#ifdef ALLOW_DEBUG + if (RSA_verify(&debug_rsa_key, ((void*)&_app_start[0]) + len, RSANUMBYTES, digest, SHA_DIGEST_SIZE)) { + goto good; + } +#endif + +// here is a failure +fail: + fail(); + return 0; +good: + // jump to flash + ((void(*)()) _app_start[1])(); + return 0; +} + diff --git a/board/build.mk b/board/build.mk new file mode 100644 index 0000000000..7b3e271915 --- /dev/null +++ b/board/build.mk @@ -0,0 +1,59 @@ +CFLAGS += -I inc -I ../ -nostdlib -fno-builtin -std=gnu11 -O0 +CFLAGS += -Tstm32_flash.ld + +CC = arm-none-eabi-gcc +OBJCOPY = arm-none-eabi-objcopy +OBJDUMP = arm-none-eabi-objdump + +ifeq ($(RELEASE),1) + CERT = ../../pandaextra/certs/release +else + # enable the debug cert + CERT = ../certs/debug + CFLAGS += "-DALLOW_DEBUG" +endif + +DFU_UTIL = "dfu-util" + +# this no longer pushes the bootstub +flash: obj/$(PROJ_NAME).bin + PYTHONPATH=../ python -c "from panda import Panda; Panda().flash('obj/$(PROJ_NAME).bin')" + +ota: obj/$(PROJ_NAME).bin + curl http://192.168.0.10/stupdate --upload-file $< + +bin: obj/$(PROJ_NAME).bin + +# this flashes everything +recover: obj/bootstub.$(PROJ_NAME).bin obj/$(PROJ_NAME).bin + -PYTHONPATH=../ python -c "from panda import Panda; Panda().reset(enter_bootloader=True)" + sleep 1.0 + $(DFU_UTIL) -d 0483:df11 -a 0 -s 0x08004000 -D obj/$(PROJ_NAME).bin + $(DFU_UTIL) -d 0483:df11 -a 0 -s 0x08000000:leave -D obj/bootstub.$(PROJ_NAME).bin + +include ../common/version.mk + +obj/cert.h: ../crypto/getcertheader.py + ../crypto/getcertheader.py ../certs/debug.pub ../certs/release.pub > $@ + +obj/%.$(PROJ_NAME).o: %.c obj/cert.h obj/gitversion.h config.h drivers/*.h gpio.h libc.h provision.h safety.h safety/*.h spi_flasher.h + $(CC) $(CFLAGS) -o $@ -c $< + +obj/%.$(PROJ_NAME).o: ../crypto/%.c + $(CC) $(CFLAGS) -o $@ -c $< + +obj/$(STARTUP_FILE).o: $(STARTUP_FILE).s + $(CC) $(CFLAGS) -o $@ -c $< + +obj/$(PROJ_NAME).bin: obj/$(STARTUP_FILE).o obj/main.$(PROJ_NAME).o + # hack + $(CC) -Wl,--section-start,.isr_vector=0x8004000 $(CFLAGS) -o obj/$(PROJ_NAME).elf $^ + $(OBJCOPY) -v -O binary obj/$(PROJ_NAME).elf obj/code.bin + SETLEN=1 ../crypto/sign.py obj/code.bin $@ $(CERT) + +obj/bootstub.$(PROJ_NAME).bin: obj/$(STARTUP_FILE).o obj/bootstub.$(PROJ_NAME).o obj/sha.$(PROJ_NAME).o obj/rsa.$(PROJ_NAME).o + $(CC) $(CFLAGS) -o obj/bootstub.$(PROJ_NAME).elf $^ + $(OBJCOPY) -v -O binary obj/bootstub.$(PROJ_NAME).elf $@ + +clean: + @rm -f obj/* diff --git a/board/config.h b/board/config.h new file mode 100644 index 0000000000..e83429980d --- /dev/null +++ b/board/config.h @@ -0,0 +1,40 @@ +#ifndef PANDA_CONFIG_H +#define PANDA_CONFIG_H + +//#define DEBUG +//#define DEBUG_USB +//#define DEBUG_SPI + +#ifdef STM32F4 + #define PANDA + #include "stm32f4xx.h" +#else + #include "stm32f2xx.h" +#endif + +#define USB_VID 0xbbaa + +#ifdef BOOTSTUB +#define USB_PID 0xddee +#else +#define USB_PID 0xddcc +#endif + +#include +#define NULL ((void*)0) +#define COMPILE_TIME_ASSERT(pred) switch(0){case 0:case pred:;} + +#define min(a,b) \ + ({ __typeof__ (a) _a = (a); \ + __typeof__ (b) _b = (b); \ + _a < _b ? _a : _b; }) + +#define max(a,b) \ + ({ __typeof__ (a) _a = (a); \ + __typeof__ (b) _b = (b); \ + _a > _b ? _a : _b; }) + +#define MAX_RESP_LEN 0x40 + +#endif + diff --git a/board/drivers/adc.h b/board/drivers/adc.h new file mode 100644 index 0000000000..cb2aeede03 --- /dev/null +++ b/board/drivers/adc.h @@ -0,0 +1,38 @@ +// ACCEL1 = ADC10 +// ACCEL2 = ADC11 +// VOLT_S = ADC12 +// CURR_S = ADC13 + +#define ADCCHAN_ACCEL0 10 +#define ADCCHAN_ACCEL1 11 +#define ADCCHAN_VOLTAGE 12 +#define ADCCHAN_CURRENT 13 + +void adc_init() { + // global setup + ADC->CCR = ADC_CCR_TSVREFE | ADC_CCR_VBATE; + //ADC1->CR2 = ADC_CR2_ADON | ADC_CR2_EOCS | ADC_CR2_DDS; + ADC1->CR2 = ADC_CR2_ADON; + + // long + //ADC1->SMPR1 = ADC_SMPR1_SMP10 | ADC_SMPR1_SMP11 | ADC_SMPR1_SMP12 | ADC_SMPR1_SMP13; + ADC1->SMPR1 = ADC_SMPR1_SMP12 | ADC_SMPR1_SMP13; +} + +uint32_t adc_get(int channel) { + // includes length + //ADC1->SQR1 = 0; + + // select channel + ADC1->JSQR = channel << 15; + + //ADC1->CR1 = ADC_CR1_DISCNUM_0; + //ADC1->CR1 = ADC_CR1_EOCIE; + + ADC1->SR &= ~(ADC_SR_JEOC); + ADC1->CR2 |= ADC_CR2_JSWSTART; + while (!(ADC1->SR & ADC_SR_JEOC)); + + return ADC1->JDR1; +} + diff --git a/board/drivers/can.h b/board/drivers/can.h new file mode 100644 index 0000000000..422da965cf --- /dev/null +++ b/board/drivers/can.h @@ -0,0 +1,401 @@ +// IRQs: CAN1_TX, CAN1_RX0, CAN1_SCE, CAN2_TX, CAN2_RX0, CAN2_SCE, CAN3_TX, CAN3_RX0, CAN3_SCE +#define ALL_CAN_SILENT 0xFF +#define ALL_CAN_BUT_MAIN_SILENT 0xFE +#define ALL_CAN_LIVE 0 + +int can_live = 0, pending_can_live = 0, can_loopback = 0, can_silent = ALL_CAN_SILENT; + +// ********************* instantiate queues ********************* + +#define can_buffer(x, size) \ + CAN_FIFOMailBox_TypeDef elems_##x[size]; \ + can_ring can_##x = { .w_ptr = 0, .r_ptr = 0, .fifo_size = size, .elems = (CAN_FIFOMailBox_TypeDef *)&elems_##x }; + +can_buffer(rx_q, 0x1000) +can_buffer(tx1_q, 0x100) +can_buffer(tx2_q, 0x100) + +#ifdef PANDA + can_buffer(tx3_q, 0x100) + can_buffer(txgmlan_q, 0x100) + can_ring *can_queues[] = {&can_tx1_q, &can_tx2_q, &can_tx3_q, &can_txgmlan_q}; +#else + can_ring *can_queues[] = {&can_tx1_q, &can_tx2_q}; +#endif + +// ********************* interrupt safe queue ********************* + +int can_pop(can_ring *q, CAN_FIFOMailBox_TypeDef *elem) { + int ret = 0; + + enter_critical_section(); + if (q->w_ptr != q->r_ptr) { + *elem = q->elems[q->r_ptr]; + if ((q->r_ptr + 1) == q->fifo_size) q->r_ptr = 0; + else q->r_ptr += 1; + ret = 1; + } + exit_critical_section(); + + return ret; +} + +int can_push(can_ring *q, CAN_FIFOMailBox_TypeDef *elem) { + int ret = 0; + uint32_t next_w_ptr; + + enter_critical_section(); + if ((q->w_ptr + 1) == q->fifo_size) next_w_ptr = 0; + else next_w_ptr = q->w_ptr + 1; + if (next_w_ptr != q->r_ptr) { + q->elems[q->w_ptr] = *elem; + q->w_ptr = next_w_ptr; + ret = 1; + } + exit_critical_section(); + if (ret == 0) puts("can_push failed!\n"); + return ret; +} + +void can_clear(can_ring *q) { + enter_critical_section(); + q->w_ptr = 0; + q->r_ptr = 0; + exit_critical_section(); +} + +// assign CAN numbering +// bus num: Can bus number on ODB connector. 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); +// bus_lookup: Translates from 'can number' to 'bus number'. +// can_num_lookup: Translates from 'bus number' to 'can number'. +// can_forwarding: Given a bus num, lookup bus num to forward to. -1 means no forward. + +int can_rx_cnt = 0; +int can_tx_cnt = 0; +int can_txd_cnt = 0; +int can_err_cnt = 0; + +// NEO: Bus 1=CAN1 Bus 2=CAN2 +// Panda: Bus 0=CAN1 Bus 1=CAN2 Bus 2=CAN3 +#ifdef PANDA + CAN_TypeDef *cans[] = {CAN1, CAN2, CAN3}; + uint8_t bus_lookup[] = {0,1,2}; + uint8_t can_num_lookup[] = {0,1,2,-1}; + int8_t can_forwarding[] = {-1,-1,-1,-1}; + uint32_t can_speed[] = {5000, 5000, 5000, 333}; + #define CAN_MAX 3 +#else + CAN_TypeDef *cans[] = {CAN1, CAN2}; + uint8_t bus_lookup[] = {1,0}; + uint8_t can_num_lookup[] = {1,0}; + int8_t can_forwarding[] = {-1,-1}; + uint32_t can_speed[] = {5000, 5000}; + #define CAN_MAX 2 +#endif + +#define CANIF_FROM_CAN_NUM(num) (cans[num]) +#define BUS_NUM_FROM_CAN_NUM(num) (bus_lookup[num]) +#define CAN_NUM_FROM_BUS_NUM(num) (can_num_lookup[num]) + +// other option +/*#define CAN_QUANTA 16 +#define CAN_SEQ1 13 +#define CAN_SEQ2 2*/ + +// this is needed for 1 mbps support +#define CAN_QUANTA 8 +#define CAN_SEQ1 6 // roundf(quanta * 0.875f) - 1; +#define CAN_SEQ2 1 // roundf(quanta * 0.125f); + +#define CAN_PCLK 24000 +// 333 = 33.3 kbps +// 5000 = 500 kbps +#define can_speed_to_prescaler(x) (CAN_PCLK / CAN_QUANTA * 10 / (x)) + +void process_can(uint8_t can_number); + +void can_init(uint8_t can_number) { + if (can_number == 0xff) return; + + CAN_TypeDef *CAN = CANIF_FROM_CAN_NUM(can_number); + set_can_enable(CAN, 1); + + CAN->MCR = CAN_MCR_TTCM | CAN_MCR_INRQ; + while((CAN->MSR & CAN_MSR_INAK) != CAN_MSR_INAK); + + // set time quanta from defines + CAN->BTR = (CAN_BTR_TS1_0 * (CAN_SEQ1-1)) | + (CAN_BTR_TS2_0 * (CAN_SEQ2-1)) | + (can_speed_to_prescaler(can_speed[BUS_NUM_FROM_CAN_NUM(can_number)]) - 1); + + // silent loopback mode for debugging + if (can_loopback) { + CAN->BTR |= CAN_BTR_SILM | CAN_BTR_LBKM; + } + + if (can_silent & (1 << can_number)) { + CAN->BTR |= CAN_BTR_SILM; + } + + // reset + CAN->MCR = CAN_MCR_TTCM | CAN_MCR_ABOM; + + #define CAN_TIMEOUT 1000000 + int tmp = 0; + while((CAN->MSR & CAN_MSR_INAK) == CAN_MSR_INAK && tmp < CAN_TIMEOUT) tmp++; + + if (tmp == CAN_TIMEOUT) { + puts("CAN init FAILED!!!!!\n"); + puth(can_number); puts(" "); + puth(BUS_NUM_FROM_CAN_NUM(can_number)); puts("\n"); + } + + // accept all filter + CAN->FMR |= CAN_FMR_FINIT; + + // no mask + CAN->sFilterRegister[0].FR1 = 0; + CAN->sFilterRegister[0].FR2 = 0; + CAN->sFilterRegister[14].FR1 = 0; + CAN->sFilterRegister[14].FR2 = 0; + CAN->FA1R |= 1 | (1 << 14); + + CAN->FMR &= ~(CAN_FMR_FINIT); + + // enable certain CAN interrupts + CAN->IER = CAN_IER_TMEIE | CAN_IER_FMPIE0; + + switch (can_number) { + case 0: + NVIC_EnableIRQ(CAN1_TX_IRQn); + NVIC_EnableIRQ(CAN1_RX0_IRQn); + NVIC_EnableIRQ(CAN1_SCE_IRQn); + break; + case 1: + NVIC_EnableIRQ(CAN2_TX_IRQn); + NVIC_EnableIRQ(CAN2_RX0_IRQn); + NVIC_EnableIRQ(CAN2_SCE_IRQn); + break; +#ifdef CAN3 + case 2: + NVIC_EnableIRQ(CAN3_TX_IRQn); + NVIC_EnableIRQ(CAN3_RX0_IRQn); + NVIC_EnableIRQ(CAN3_SCE_IRQn); + break; +#endif + } + + // in case there are queued up messages + process_can(can_number); +} + +void can_init_all() { + for (int i=0; i < CAN_MAX; i++) { + can_init(i); + } +} + +void can_set_gmlan(int bus) { + if (bus == -1 || bus != can_num_lookup[3]) { + // GMLAN OFF + switch (can_num_lookup[3]) { + case 1: + puts("disable GMLAN on CAN2\n"); + set_can_mode(1, 0); + bus_lookup[1] = 1; + can_num_lookup[1] = 1; + can_num_lookup[3] = -1; + can_init(1); + break; + case 2: + puts("disable GMLAN on CAN3\n"); + set_can_mode(2, 0); + bus_lookup[2] = 2; + can_num_lookup[2] = 2; + can_num_lookup[3] = -1; + can_init(2); + break; + } + } + + if (bus == 1) { + puts("GMLAN on CAN2\n"); + // GMLAN on CAN2 + set_can_mode(1, 1); + bus_lookup[1] = 3; + can_num_lookup[1] = -1; + can_num_lookup[3] = 1; + can_init(1); + } else if (bus == 2 && revision == PANDA_REV_C) { + puts("GMLAN on CAN3\n"); + // GMLAN on CAN3 + set_can_mode(2, 1); + bus_lookup[2] = 3; + can_num_lookup[2] = -1; + can_num_lookup[3] = 2; + can_init(2); + } +} + +// CAN error +void can_sce(CAN_TypeDef *CAN) { + can_err_cnt += 1; + #ifdef DEBUG + if (CAN==CAN1) puts("CAN1: "); + if (CAN==CAN2) puts("CAN2: "); + #ifdef CAN3 + if (CAN==CAN3) puts("CAN3: "); + #endif + puts("MSR:"); + puth(CAN->MSR); + puts(" TSR:"); + puth(CAN->TSR); + puts(" RF0R:"); + puth(CAN->RF0R); + puts(" RF1R:"); + puth(CAN->RF1R); + puts(" ESR:"); + puth(CAN->ESR); + puts("\n"); + #endif + + // clear current send + CAN->TSR |= CAN_TSR_ABRQ0; + CAN->MSR = CAN->MSR; +} + +// ***************************** CAN ***************************** + +void process_can(uint8_t can_number) { + if (can_number == 0xff) return; + + enter_critical_section(); + + CAN_TypeDef *CAN = CANIF_FROM_CAN_NUM(can_number); + uint8_t bus_number = BUS_NUM_FROM_CAN_NUM(can_number); + #ifdef DEBUG + puts("process CAN TX\n"); + #endif + + // check for empty mailbox + CAN_FIFOMailBox_TypeDef to_send; + if ((CAN->TSR & CAN_TSR_TME0) == CAN_TSR_TME0) { + // add successfully transmitted message to my fifo + if ((CAN->TSR & CAN_TSR_RQCP0) == CAN_TSR_RQCP0) { + can_txd_cnt += 1; + + if ((CAN->TSR & CAN_TSR_TXOK0) == CAN_TSR_TXOK0) { + CAN_FIFOMailBox_TypeDef to_push; + to_push.RIR = CAN->sTxMailBox[0].TIR; + to_push.RDTR = (CAN->sTxMailBox[0].TDTR & 0xFFFF000F) | ((CAN_BUS_RET_FLAG | bus_number) << 4); + to_push.RDLR = CAN->sTxMailBox[0].TDLR; + to_push.RDHR = CAN->sTxMailBox[0].TDHR; + can_push(&can_rx_q, &to_push); + } + + if ((CAN->TSR & CAN_TSR_TERR0) == CAN_TSR_TERR0) { + #ifdef DEBUG + puts("CAN TX ERROR!\n"); + #endif + } + + if ((CAN->TSR & CAN_TSR_ALST0) == CAN_TSR_ALST0) { + #ifdef DEBUG + puts("CAN TX ARBITRATION LOST!\n"); + #endif + } + + // clear interrupt + // careful, this can also be cleared by requesting a transmission + CAN->TSR |= CAN_TSR_RQCP0; + } + + if (can_pop(can_queues[bus_number], &to_send)) { + can_tx_cnt += 1; + // only send if we have received a packet + CAN->sTxMailBox[0].TDLR = to_send.RDLR; + CAN->sTxMailBox[0].TDHR = to_send.RDHR; + CAN->sTxMailBox[0].TDTR = to_send.RDTR; + CAN->sTxMailBox[0].TIR = to_send.RIR; + } + } + + exit_critical_section(); +} + +// CAN receive handlers +// blink blue when we are receiving CAN messages +void can_rx(uint8_t can_number) { + CAN_TypeDef *CAN = CANIF_FROM_CAN_NUM(can_number); + uint8_t bus_number = BUS_NUM_FROM_CAN_NUM(can_number); + while (CAN->RF0R & CAN_RF0R_FMP0) { + can_rx_cnt += 1; + + // can is live + pending_can_live = 1; + + // add to my fifo + CAN_FIFOMailBox_TypeDef to_push; + to_push.RIR = CAN->sFIFOMailBox[0].RIR; + to_push.RDTR = CAN->sFIFOMailBox[0].RDTR; + to_push.RDLR = CAN->sFIFOMailBox[0].RDLR; + to_push.RDHR = CAN->sFIFOMailBox[0].RDHR; + + // forwarding (panda only) + #ifdef PANDA + if (can_forwarding[bus_number] != -1) { + CAN_FIFOMailBox_TypeDef to_send; + to_send.RIR = to_push.RIR | 1; // TXRQ + to_send.RDTR = to_push.RDTR; + to_send.RDLR = to_push.RDLR; + to_send.RDHR = to_push.RDHR; + can_send(&to_send, can_forwarding[bus_number]); + } + #endif + + // modify RDTR for our API + to_push.RDTR = (to_push.RDTR & 0xFFFF000F) | (bus_number << 4); + safety_rx_hook(&to_push); + + #ifdef PANDA + set_led(LED_BLUE, 1); + #endif + can_push(&can_rx_q, &to_push); + + // next + CAN->RF0R |= CAN_RF0R_RFOM0; + } +} + +void CAN1_TX_IRQHandler() { process_can(0); } +void CAN1_RX0_IRQHandler() { can_rx(0); } +void CAN1_SCE_IRQHandler() { can_sce(CAN1); } + +void CAN2_TX_IRQHandler() { process_can(1); } +void CAN2_RX0_IRQHandler() { can_rx(1); } +void CAN2_SCE_IRQHandler() { can_sce(CAN2); } + +#ifdef CAN3 +void CAN3_TX_IRQHandler() { process_can(2); } +void CAN3_RX0_IRQHandler() { can_rx(2); } +void CAN3_SCE_IRQHandler() { can_sce(CAN3); } +#endif + +void can_send(CAN_FIFOMailBox_TypeDef *to_push, uint8_t bus_number) { + if (safety_tx_hook(to_push)) { + if (bus_number < BUS_MAX) { + // add CAN packet to send queue + // bus number isn't passed through + to_push->RDTR &= 0xF; + can_push(can_queues[bus_number], to_push); + process_can(CAN_NUM_FROM_BUS_NUM(bus_number)); + } + } +} + +void can_set_forwarding(int from, int to) { + can_forwarding[from] = to; +} diff --git a/board/drivers/dac.h b/board/drivers/dac.h new file mode 100644 index 0000000000..b8833dc4a6 --- /dev/null +++ b/board/drivers/dac.h @@ -0,0 +1,16 @@ +void dac_init() { + // no buffers required since we have an opamp + //DAC->CR = DAC_CR_EN1 | DAC_CR_BOFF1 | DAC_CR_EN2 | DAC_CR_BOFF2; + DAC->DHR12R1 = 0; + DAC->DHR12R2 = 0; + DAC->CR = DAC_CR_EN1 | DAC_CR_EN2; +} + +void dac_set(int channel, uint32_t value) { + if (channel == 0) { + DAC->DHR12R1 = value; + } else if (channel == 1) { + DAC->DHR12R2 = value; + } +} + diff --git a/board/drivers/drivers.h b/board/drivers/drivers.h new file mode 100644 index 0000000000..871ee8fcf1 --- /dev/null +++ b/board/drivers/drivers.h @@ -0,0 +1,141 @@ +#ifndef PANDA_DRIVERS_H +#define PANDA_DRIVERS_H + +// ********************* LLGPIO ********************* + +#define MODE_INPUT 0 +#define MODE_OUTPUT 1 +#define MODE_ALTERNATE 2 +#define MODE_ANALOG 3 + +#define PULL_NONE 0 +#define PULL_UP 1 +#define PULL_DOWN 2 + +void set_gpio_mode(GPIO_TypeDef *GPIO, int pin, int mode); +void set_gpio_output(GPIO_TypeDef *GPIO, int pin, int val); +void set_gpio_alternate(GPIO_TypeDef *GPIO, int pin, int mode); +void set_gpio_pullup(GPIO_TypeDef *GPIO, int pin, int mode); + +int get_gpio_input(GPIO_TypeDef *GPIO, int pin); + + +// ********************* USB ********************* +// IRQs: OTG_FS + +typedef union { + uint16_t w; + struct BW { + uint8_t msb; + uint8_t lsb; + } + bw; +} +uint16_t_uint8_t; + +typedef union _USB_Setup { + uint32_t d8[2]; + struct _SetupPkt_Struc + { + uint8_t bmRequestType; + uint8_t bRequest; + uint16_t_uint8_t wValue; + uint16_t_uint8_t wIndex; + uint16_t_uint8_t wLength; + } b; +} +USB_Setup_TypeDef; + +void usb_init(); +int usb_cb_control_msg(USB_Setup_TypeDef *setup, uint8_t *resp, int hardwired); +int usb_cb_ep1_in(uint8_t *usbdata, int len, int hardwired); +void usb_cb_ep2_out(uint8_t *usbdata, int len, int hardwired); +void usb_cb_ep3_out(uint8_t *usbdata, int len, int hardwired); +void usb_cb_enumeration_complete(); + + +// ********************* UART ********************* +// IRQs: USART1, USART2, USART3, UART5 + +#define FIFO_SIZE 0x100 +typedef struct uart_ring { + uint8_t w_ptr_tx; + uint8_t r_ptr_tx; + uint8_t elems_tx[FIFO_SIZE]; + uint8_t w_ptr_rx; + uint8_t r_ptr_rx; + uint8_t elems_rx[FIFO_SIZE]; + USART_TypeDef *uart; + void (*callback)(struct uart_ring*); +} uart_ring; + +void uart_init(USART_TypeDef *u, int baud); + +int getc(uart_ring *q, char *elem); +int putc(uart_ring *q, char elem); + +int puts(const char *a); +void puth(unsigned int i); +void hexdump(const void *a, int l); + + +// ********************* ADC ********************* + +void adc_init(); +uint32_t adc_get(int channel); + + +// ********************* DAC ********************* + +void dac_init(); +uint32_t dac_set(int channel, uint32_t value); + + +// ********************* TIMER ********************* + +void timer_init(TIM_TypeDef *TIM, int psc); + + +// ********************* SPI ********************* +// IRQs: DMA2_Stream2, DMA2_Stream3, EXTI4 + +void spi_init(); +int spi_cb_rx(uint8_t *data, int len, uint8_t *data_out); + + +// ********************* CAN ********************* +// IRQs: CAN1_TX, CAN1_RX0, CAN1_SCE +// CAN2_TX, CAN2_RX0, CAN2_SCE +// CAN3_TX, CAN3_RX0, CAN3_SCE + +typedef struct { + uint32_t w_ptr; + uint32_t r_ptr; + uint32_t fifo_size; + CAN_FIFOMailBox_TypeDef *elems; +} can_ring; + +#define CAN_BUS_RET_FLAG 0x80 +#define CAN_BUS_NUM_MASK 0x7F + +#ifdef PANDA + #define BUS_MAX 4 +#else + #define BUS_MAX 2 +#endif + +extern int can_live, pending_can_live; + +// must reinit after changing these +extern int can_loopback, can_silent; +extern uint32_t can_speed[]; + +void can_set_forwarding(int from, int to); + +void can_init(uint8_t can_number); +void can_init_all(); +void can_send(CAN_FIFOMailBox_TypeDef *to_push, uint8_t bus_number); +int can_pop(can_ring *q, CAN_FIFOMailBox_TypeDef *elem); + +#endif + diff --git a/board/drivers/llgpio.h b/board/drivers/llgpio.h new file mode 100644 index 0000000000..e1835ec0f4 --- /dev/null +++ b/board/drivers/llgpio.h @@ -0,0 +1,35 @@ +void set_gpio_mode(GPIO_TypeDef *GPIO, int pin, int mode) { + uint32_t tmp = GPIO->MODER; + tmp &= ~(3 << (pin*2)); + tmp |= (mode << (pin*2)); + GPIO->MODER = tmp; +} + +void set_gpio_output(GPIO_TypeDef *GPIO, int pin, int val) { + if (val) { + GPIO->ODR |= (1 << pin); + } else { + GPIO->ODR &= ~(1 << pin); + } + set_gpio_mode(GPIO, pin, MODE_OUTPUT); +} + +void set_gpio_alternate(GPIO_TypeDef *GPIO, int pin, int mode) { + uint32_t tmp = GPIO->AFR[pin>>3]; + tmp &= ~(0xF << ((pin&7)*4)); + tmp |= mode << ((pin&7)*4); + GPIO->AFR[pin>>3] = tmp; + set_gpio_mode(GPIO, pin, MODE_ALTERNATE); +} + +void set_gpio_pullup(GPIO_TypeDef *GPIO, int pin, int mode) { + uint32_t tmp = GPIO->PUPDR; + tmp &= ~(3 << (pin*2)); + tmp |= (mode << (pin*2)); + GPIO->PUPDR = tmp; +} + +int get_gpio_input(GPIO_TypeDef *GPIO, int pin) { + return (GPIO->IDR & (1 << pin)) == (1 << pin); +} + diff --git a/board/drivers/spi.h b/board/drivers/spi.h new file mode 100644 index 0000000000..fc6a5ab26d --- /dev/null +++ b/board/drivers/spi.h @@ -0,0 +1,120 @@ +// IRQs: DMA2_Stream2, DMA2_Stream3, EXTI4 + +#define SPI_BUF_SIZE 256 +uint8_t spi_buf[SPI_BUF_SIZE]; +int spi_buf_count = 0; +int spi_total_count = 0; + +void spi_init() { + //puts("SPI init\n"); + SPI1->CR1 = SPI_CR1_SPE; + + // enable SPI interrupts + //SPI1->CR2 = SPI_CR2_RXNEIE | SPI_CR2_ERRIE | SPI_CR2_TXEIE; + SPI1->CR2 = SPI_CR2_RXNEIE; + + NVIC_EnableIRQ(DMA2_Stream2_IRQn); + NVIC_EnableIRQ(DMA2_Stream3_IRQn); + //NVIC_EnableIRQ(SPI1_IRQn); + + // reset handshake back to pull up + set_gpio_mode(GPIOB, 0, MODE_INPUT); + set_gpio_pullup(GPIOB, 0, PULL_UP); + + // setup interrupt on falling edge of SPI enable (on PA4) + SYSCFG->EXTICR[2] = SYSCFG_EXTICR2_EXTI4_PA; + EXTI->IMR = (1 << 4); + EXTI->FTSR = (1 << 4); + NVIC_EnableIRQ(EXTI4_IRQn); +} + +void spi_tx_dma(void *addr, int len) { + // disable DMA + SPI1->CR2 &= ~SPI_CR2_TXDMAEN; + DMA2_Stream3->CR &= ~DMA_SxCR_EN; + + // DMA2, stream 3, channel 3 + DMA2_Stream3->M0AR = (uint32_t)addr; + DMA2_Stream3->NDTR = len; + DMA2_Stream3->PAR = (uint32_t)&(SPI1->DR); + + // channel3, increment memory, memory -> periph, enable + DMA2_Stream3->CR = DMA_SxCR_CHSEL_1 | DMA_SxCR_CHSEL_0 | DMA_SxCR_MINC | DMA_SxCR_DIR_0 | DMA_SxCR_EN; + DMA2_Stream3->CR |= DMA_SxCR_TCIE; + + SPI1->CR2 |= SPI_CR2_TXDMAEN; + + // signal data is ready by driving low + // esp must be configured as input by this point + set_gpio_output(GPIOB, 0, 0); +} + +void spi_rx_dma(void *addr, int len) { + // disable DMA + SPI1->CR2 &= ~SPI_CR2_RXDMAEN; + DMA2_Stream2->CR &= ~DMA_SxCR_EN; + + // drain the bus + volatile uint8_t dat = SPI1->DR; + (void)dat; + + // DMA2, stream 2, channel 3 + DMA2_Stream2->M0AR = (uint32_t)addr; + DMA2_Stream2->NDTR = len; + DMA2_Stream2->PAR = (uint32_t)&(SPI1->DR); + + // channel3, increment memory, periph -> memory, enable + DMA2_Stream2->CR = DMA_SxCR_CHSEL_1 | DMA_SxCR_CHSEL_0 | DMA_SxCR_MINC | DMA_SxCR_EN; + DMA2_Stream2->CR |= DMA_SxCR_TCIE; + + SPI1->CR2 |= SPI_CR2_RXDMAEN; +} + +// ***************************** SPI IRQs ***************************** + +// can't go on the stack cause it's DMAed +uint8_t spi_tx_buf[0x44]; + +// SPI RX +void DMA2_Stream2_IRQHandler(void) { + int *resp_len = (int*)spi_tx_buf; + memset(spi_tx_buf, 0xaa, 0x44); + *resp_len = spi_cb_rx(spi_buf, 0x14, spi_tx_buf+4); + #ifdef DEBUG_SPI + puts("SPI write: "); + puth(*resp_len); + puts("\n"); + #endif + spi_tx_dma(spi_tx_buf, *resp_len + 4); + + // ack + DMA2->LIFCR = DMA_LIFCR_CTCIF2; +} + +// SPI TX +void DMA2_Stream3_IRQHandler(void) { + #ifdef DEBUG_SPI + puts("SPI handshake\n"); + #endif + + // reset handshake back to pull up + set_gpio_mode(GPIOB, 0, MODE_INPUT); + set_gpio_pullup(GPIOB, 0, PULL_UP); + + // ack + DMA2->LIFCR = DMA_LIFCR_CTCIF3; +} + +void EXTI4_IRQHandler(void) { + volatile int pr = EXTI->PR; + #ifdef DEBUG_SPI + puts("exti4\n"); + #endif + // SPI CS falling + if (pr & (1 << 4)) { + spi_total_count = 0; + spi_rx_dma(spi_buf, 0x14); + } + EXTI->PR = pr; +} + diff --git a/board/drivers/timer.h b/board/drivers/timer.h new file mode 100644 index 0000000000..a14b619e4b --- /dev/null +++ b/board/drivers/timer.h @@ -0,0 +1,7 @@ +void timer_init(TIM_TypeDef *TIM, int psc) { + TIM->PSC = psc-1; + TIM->DIER = TIM_DIER_UIE; + TIM->CR1 = TIM_CR1_CEN; + TIM->SR = 0; +} + diff --git a/board/drivers/uart.h b/board/drivers/uart.h new file mode 100644 index 0000000000..85bab0e78d --- /dev/null +++ b/board/drivers/uart.h @@ -0,0 +1,224 @@ +// IRQs: USART1, USART2, USART3, UART5 + +// ***************************** serial port queues ***************************** + +// esp = USART1 +uart_ring esp_ring = { .w_ptr_tx = 0, .r_ptr_tx = 0, + .w_ptr_rx = 0, .r_ptr_rx = 0, + .uart = USART1 }; + +// lin1, K-LINE = UART5 +// lin2, L-LINE = USART3 +uart_ring lin1_ring = { .w_ptr_tx = 0, .r_ptr_tx = 0, + .w_ptr_rx = 0, .r_ptr_rx = 0, + .uart = UART5 }; +uart_ring lin2_ring = { .w_ptr_tx = 0, .r_ptr_tx = 0, + .w_ptr_rx = 0, .r_ptr_rx = 0, + .uart = USART3 }; + +// debug = USART2 +void debug_ring_callback(uart_ring *ring); +uart_ring debug_ring = { .w_ptr_tx = 0, .r_ptr_tx = 0, + .w_ptr_rx = 0, .r_ptr_rx = 0, + .uart = USART2, + .callback = debug_ring_callback}; + + +uart_ring *get_ring_by_number(int a) { + switch(a) { + case 0: + return &debug_ring; + case 1: + return &esp_ring; + case 2: + return &lin1_ring; + case 3: + return &lin2_ring; + default: + return NULL; + } +} + +// ***************************** serial port ***************************** + +void uart_ring_process(uart_ring *q) { + enter_critical_section(); + // TODO: check if external serial is connected + int sr = q->uart->SR; + + if (q->w_ptr_tx != q->r_ptr_tx) { + if (sr & USART_SR_TXE) { + q->uart->DR = q->elems_tx[q->r_ptr_tx]; + q->r_ptr_tx += 1; + } else { + // push on interrupt later + q->uart->CR1 |= USART_CR1_TXEIE; + } + } else { + // nothing to send + q->uart->CR1 &= ~USART_CR1_TXEIE; + } + + if (sr & USART_SR_RXNE) { + uint8_t c = q->uart->DR; // TODO: can drop packets + uint8_t next_w_ptr = q->w_ptr_rx + 1; + if (next_w_ptr != q->r_ptr_rx) { + q->elems_rx[q->w_ptr_rx] = c; + q->w_ptr_rx = next_w_ptr; + if (q->callback) q->callback(q); + } + } + exit_critical_section(); +} + +// interrupt boilerplate + +void USART1_IRQHandler(void) { uart_ring_process(&esp_ring); } +void USART2_IRQHandler(void) { uart_ring_process(&debug_ring); } +void USART3_IRQHandler(void) { uart_ring_process(&lin2_ring); } +void UART5_IRQHandler(void) { uart_ring_process(&lin1_ring); } + +int getc(uart_ring *q, char *elem) { + int ret = 0; + + enter_critical_section(); + if (q->w_ptr_rx != q->r_ptr_rx) { + *elem = q->elems_rx[q->r_ptr_rx]; + q->r_ptr_rx += 1; + ret = 1; + } + exit_critical_section(); + + return ret; +} + +int injectc(uart_ring *q, char elem) { + int ret = 0; + uint8_t next_w_ptr; + + enter_critical_section(); + next_w_ptr = q->w_ptr_rx + 1; + if (next_w_ptr != q->r_ptr_rx) { + q->elems_rx[q->w_ptr_rx] = elem; + q->w_ptr_rx = next_w_ptr; + ret = 1; + } + exit_critical_section(); + + return ret; +} + +int putc(uart_ring *q, char elem) { + int ret = 0; + uint8_t next_w_ptr; + + enter_critical_section(); + next_w_ptr = q->w_ptr_tx + 1; + if (next_w_ptr != q->r_ptr_tx) { + q->elems_tx[q->w_ptr_tx] = elem; + q->w_ptr_tx = next_w_ptr; + ret = 1; + } + exit_critical_section(); + + uart_ring_process(q); + + return ret; +} + +void clear_uart_buff(uart_ring *q) { + enter_critical_section(); + q->w_ptr_tx = 0; + q->r_ptr_tx = 0; + q->w_ptr_rx = 0; + q->r_ptr_rx = 0; + exit_critical_section(); +} + +// ***************************** start UART code ***************************** + +#define __DIV(_PCLK_, _BAUD_) (((_PCLK_)*25)/(4*(_BAUD_))) +#define __DIVMANT(_PCLK_, _BAUD_) (__DIV((_PCLK_), (_BAUD_))/100) +#define __DIVFRAQ(_PCLK_, _BAUD_) (((__DIV((_PCLK_), (_BAUD_)) - (__DIVMANT((_PCLK_), (_BAUD_)) * 100)) * 16 + 50) / 100) +#define __USART_BRR(_PCLK_, _BAUD_) ((__DIVMANT((_PCLK_), (_BAUD_)) << 4)|(__DIVFRAQ((_PCLK_), (_BAUD_)) & 0x0F)) + +void uart_set_baud(USART_TypeDef *u, int baud) { + if (u == USART1) { + // USART1 is on APB2 + u->BRR = __USART_BRR(48000000, baud); + } else { + u->BRR = __USART_BRR(24000000, baud); + } +} + +void uart_init(USART_TypeDef *u, int baud) { + // enable uart and tx+rx mode + u->CR1 = USART_CR1_UE; + uart_set_baud(u, baud); + + u->CR1 |= USART_CR1_TE | USART_CR1_RE; + //u->CR2 = USART_CR2_STOP_0 | USART_CR2_STOP_1; + //u->CR2 = USART_CR2_STOP_0; + // ** UART is ready to work ** + + // enable interrupts + u->CR1 |= USART_CR1_RXNEIE; + + if (u == USART1) { + NVIC_EnableIRQ(USART1_IRQn); + } else if (u == USART2) { + NVIC_EnableIRQ(USART2_IRQn); + } else if (u == USART3) { + NVIC_EnableIRQ(USART3_IRQn); + } else if (u == UART5) { + NVIC_EnableIRQ(UART5_IRQn); + } +} + +void putch(const char a) { + if (has_external_debug_serial) { + /*while ((debug_ring.uart->SR & USART_SR_TXE) == 0); + debug_ring.uart->DR = a;*/ + + // assuming debugging is important if there's external serial connected + while (!putc(&debug_ring, a)); + + //putc(&debug_ring, a); + } else { + injectc(&debug_ring, a); + } +} + +int puts(const char *a) { + for (;*a;a++) { + if (*a == '\n') putch('\r'); + putch(*a); + } + return 0; +} + +void puth(unsigned int i) { + int pos; + char c[] = "0123456789abcdef"; + for (pos = 28; pos != -4; pos -= 4) { + putch(c[(i >> pos) & 0xF]); + } +} + +void puth2(unsigned int i) { + int pos; + char c[] = "0123456789abcdef"; + for (pos = 4; pos != -4; pos -= 4) { + putch(c[(i >> pos) & 0xF]); + } +} + +void hexdump(const void *a, int l) { + int i; + for (i=0;i>8)&0xFF) + +uint8_t device_desc[] = { + DSCR_DEVICE_LEN, DSCR_DEVICE_TYPE, 0x00, 0x01, //Length, Type, bcdUSB + 0xFF, 0xFF, 0xFF, 0x40, // Class, Subclass, Protocol, Max Packet Size + TOUSBORDER(USB_VID), // idVendor + TOUSBORDER(USB_PID), // idProduct +#ifdef STM32F4 + 0x00, 0x23, // bcdDevice +#else + 0x00, 0x22, // bcdDevice +#endif + 0x01, 0x02, // Manufacturer, Product + 0x03, 0x01 // Serial Number, Num Configurations +}; + +#define ENDPOINT_RCV 0x80 +#define ENDPOINT_SND 0x00 + +uint8_t configuration_desc[] = { + DSCR_CONFIG_LEN, DSCR_CONFIG_TYPE, // Length, Type, + TOUSBORDER(0x0045), // Total Len (uint16) + 0x01, 0x01, 0x00, // Num Interface, Config Value, Configuration + 0xc0, 0x32, // Attributes, Max Power + // interface 0 ALT 0 + DSCR_INTERFACE_LEN, DSCR_INTERFACE_TYPE, // Length, Type + 0x00, 0x00, 0x03, // Index, Alt Index idx, Endpoint count + 0XFF, 0xFF, 0xFF, // Class, Subclass, Protocol + 0x00, // Interface + // endpoint 1, read CAN + DSCR_ENDPOINT_LEN, DSCR_ENDPOINT_TYPE, // Length, Type + ENDPOINT_RCV | 1, ENDPOINT_TYPE_BULK, // Endpoint Num/Direction, Type + TOUSBORDER(0x0040), // Max Packet (0x0040) + 0x00, // Polling Interval (NA) + // endpoint 2, send serial + DSCR_ENDPOINT_LEN, DSCR_ENDPOINT_TYPE, // Length, Type + ENDPOINT_SND | 2, ENDPOINT_TYPE_BULK, // Endpoint Num/Direction, Type + TOUSBORDER(0x0040), // Max Packet (0x0040) + 0x00, // Polling Interval + // endpoint 3, send CAN + DSCR_ENDPOINT_LEN, DSCR_ENDPOINT_TYPE, // Length, Type + ENDPOINT_SND | 3, ENDPOINT_TYPE_BULK, // Endpoint Num/Direction, Type + TOUSBORDER(0x0040), // Max Packet (0x0040) + 0x00, // Polling Interval + // interface 0 ALT 1 + DSCR_INTERFACE_LEN, DSCR_INTERFACE_TYPE, // Length, Type + 0x00, 0x01, 0x03, // Index, Alt Index idx, Endpoint count + 0XFF, 0xFF, 0xFF, // Class, Subclass, Protocol + 0x00, // Interface + // endpoint 1, read CAN + DSCR_ENDPOINT_LEN, DSCR_ENDPOINT_TYPE, // Length, Type + ENDPOINT_RCV | 1, ENDPOINT_TYPE_INT, // Endpoint Num/Direction, Type + TOUSBORDER(0x0040), // Max Packet (0x0040) + 0x05, // Polling Interval (5 frames) + // endpoint 2, send serial + DSCR_ENDPOINT_LEN, DSCR_ENDPOINT_TYPE, // Length, Type + ENDPOINT_SND | 2, ENDPOINT_TYPE_BULK, // Endpoint Num/Direction, Type + TOUSBORDER(0x0040), // Max Packet (0x0040) + 0x00, // Polling Interval + // endpoint 3, send CAN + DSCR_ENDPOINT_LEN, DSCR_ENDPOINT_TYPE, // Length, Type + ENDPOINT_SND | 3, ENDPOINT_TYPE_BULK, // Endpoint Num/Direction, Type + TOUSBORDER(0x0040), // Max Packet (0x0040) + 0x00, // Polling Interval +}; + +uint8_t string_0_desc[] = { + 0x04, DSCR_STRING_TYPE, 0x09, 0x04 +}; + +uint16_t string_1_desc[] = { + 0x0312, + 'c', 'o', 'm', 'm', 'a', '.', 'a', 'i' +}; + +#ifdef PANDA +uint16_t string_2_desc[] = { + 0x030c, + 'p', 'a', 'n', 'd', 'a' +}; +#else +uint16_t string_2_desc[] = { + 0x030c, + 'N', 'E', 'O', 'v', '1' +}; +#endif + +uint16_t string_3_desc[] = { + 0x030a, + 'n', 'o', 'n', 'e' +}; + +// current packet +USB_Setup_TypeDef setup; +uint8_t usbdata[0x100]; + +// Store the current interface alt setting. +int current_int0_alt_setting = 0; + +// packet read and write + +void *USB_ReadPacket(void *dest, uint16_t len) { + uint32_t i=0; + uint32_t count32b = (len + 3) / 4; + + for ( i = 0; i < count32b; i++, dest += 4 ) { + // packed? + *(__attribute__((__packed__)) uint32_t *)dest = USBx_DFIFO(0); + } + return ((void *)dest); +} + +void USB_WritePacket(const uint8_t *src, uint16_t len, uint32_t ep) { + #ifdef DEBUG_USB + puts("writing "); + hexdump(src, len); + #endif + + uint8_t numpacket = (len+(MAX_RESP_LEN-1))/MAX_RESP_LEN; + uint32_t count32b = 0, i = 0; + count32b = (len + 3) / 4; + + // bullshit + USBx_INEP(ep)->DIEPTSIZ = ((numpacket << 19) & USB_OTG_DIEPTSIZ_PKTCNT) | + (len & USB_OTG_DIEPTSIZ_XFRSIZ); + USBx_INEP(ep)->DIEPCTL |= (USB_OTG_DIEPCTL_CNAK | USB_OTG_DIEPCTL_EPENA); + + // load the FIFO + for (i = 0; i < count32b; i++, src += 4) { + USBx_DFIFO(ep) = *((__attribute__((__packed__)) uint32_t *)src); + } +} + +void usb_reset() { + // unmask endpoint interrupts, so many sets + USBx_DEVICE->DAINT = 0xFFFFFFFF; + USBx_DEVICE->DAINTMSK = 0xFFFFFFFF; + //USBx_DEVICE->DOEPMSK = (USB_OTG_DOEPMSK_STUPM | USB_OTG_DOEPMSK_XFRCM | USB_OTG_DOEPMSK_EPDM); + //USBx_DEVICE->DIEPMSK = (USB_OTG_DIEPMSK_TOM | USB_OTG_DIEPMSK_XFRCM | USB_OTG_DIEPMSK_EPDM | USB_OTG_DIEPMSK_ITTXFEMSK); + //USBx_DEVICE->DIEPMSK = (USB_OTG_DIEPMSK_TOM | USB_OTG_DIEPMSK_XFRCM | USB_OTG_DIEPMSK_EPDM); + + // all interrupts for debugging + USBx_DEVICE->DIEPMSK = 0xFFFFFFFF; + USBx_DEVICE->DOEPMSK = 0xFFFFFFFF; + + // clear interrupts + USBx_INEP(0)->DIEPINT = 0xFF; + USBx_OUTEP(0)->DOEPINT = 0xFF; + + // unset the address + USBx_DEVICE->DCFG &= ~USB_OTG_DCFG_DAD; + + // set up USB FIFOs + // RX start address is fixed to 0 + USBx->GRXFSIZ = 0x40; + + // 0x100 to offset past GRXFSIZ + USBx->DIEPTXF0_HNPTXFSIZ = (0x40 << 16) | 0x40; + + // EP1, massive + USBx->DIEPTXF[0] = (0x40 << 16) | 0x80; + + // flush TX fifo + USBx->GRSTCTL = USB_OTG_GRSTCTL_TXFFLSH | USB_OTG_GRSTCTL_TXFNUM_4; + while ((USBx->GRSTCTL & USB_OTG_GRSTCTL_TXFFLSH) == USB_OTG_GRSTCTL_TXFFLSH); + // flush RX FIFO + USBx->GRSTCTL = USB_OTG_GRSTCTL_RXFFLSH; + while ((USBx->GRSTCTL & USB_OTG_GRSTCTL_RXFFLSH) == USB_OTG_GRSTCTL_RXFFLSH); + + // no global NAK + USBx_DEVICE->DCTL |= USB_OTG_DCTL_CGINAK; + + // ready to receive setup packets + USBx_OUTEP(0)->DOEPTSIZ = USB_OTG_DOEPTSIZ_STUPCNT | (USB_OTG_DOEPTSIZ_PKTCNT & (1 << 19)) | (3 * 8); +} + +char to_hex_char(int a) { + if (a < 10) { + return '0' + a; + } else { + return 'a' + (a-10); + } +} + +void usb_setup() { + int resp_len; + // setup packet is ready + switch (setup.b.bRequest) { + case USB_REQ_SET_CONFIGURATION: + // enable other endpoints, has to be here? + USBx_INEP(1)->DIEPCTL = (0x40 & USB_OTG_DIEPCTL_MPSIZ) | (2 << 18) | (1 << 22) | + USB_OTG_DIEPCTL_SD0PID_SEVNFRM | USB_OTG_DIEPCTL_USBAEP; + USBx_INEP(1)->DIEPINT = 0xFF; + + USBx_OUTEP(2)->DOEPTSIZ = (1 << 19) | 0x40; + USBx_OUTEP(2)->DOEPCTL = (0x40 & USB_OTG_DOEPCTL_MPSIZ) | (2 << 18) | + USB_OTG_DOEPCTL_SD0PID_SEVNFRM | USB_OTG_DOEPCTL_USBAEP; + USBx_OUTEP(2)->DOEPINT = 0xFF; + + USBx_OUTEP(3)->DOEPTSIZ = (1 << 19) | 0x40; + USBx_OUTEP(3)->DOEPCTL = (0x40 & USB_OTG_DOEPCTL_MPSIZ) | (2 << 18) | + USB_OTG_DOEPCTL_SD0PID_SEVNFRM | USB_OTG_DOEPCTL_USBAEP; + USBx_OUTEP(3)->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; + + USB_WritePacket(0, 0, 0); + USBx_OUTEP(0)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; + break; + case USB_REQ_SET_ADDRESS: + // set now? + USBx_DEVICE->DCFG |= ((setup.b.wValue.w & 0x7f) << 4); + + #ifdef DEBUG_USB + puts(" set address\n"); + #endif + + // TODO: this isn't enumeration complete + // moved here to work better on OS X + usb_cb_enumeration_complete(); + + USB_WritePacket(0, 0, 0); + USBx_OUTEP(0)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; + + break; + case USB_REQ_GET_DESCRIPTOR: + switch (setup.b.wValue.bw.lsb) { + case USB_DESC_TYPE_DEVICE: + //puts(" writing device descriptor\n"); + + // setup transfer + USB_WritePacket(device_desc, min(sizeof(device_desc), setup.b.wLength.w), 0); + USBx_OUTEP(0)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; + + //puts("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; + break; + case USB_DESC_TYPE_STRING: + switch (setup.b.wValue.bw.msb) { + case 0: + USB_WritePacket((uint8_t*)string_0_desc, min(sizeof(string_0_desc), setup.b.wLength.w), 0); + break; + case 1: + USB_WritePacket((uint8_t*)string_1_desc, min(sizeof(string_1_desc), setup.b.wLength.w), 0); + break; + case 2: + USB_WritePacket((uint8_t*)string_2_desc, min(sizeof(string_2_desc), setup.b.wLength.w), 0); + break; + case 3: + #ifdef PANDA + resp[0] = 0x02 + 12*4; + resp[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 + 0] = to_hex_char((cc>>4)&0xF); + resp[2 + i*4 + 1] = '\0'; + resp[2 + i*4 + 2] = to_hex_char((cc>>0)&0xF); + resp[2 + i*4 + 3] = '\0'; + } + + USB_WritePacket(resp, min(resp[0], setup.b.wLength.w), 0); + #else + USB_WritePacket((const uint8_t *)string_3_desc, min(sizeof(string_3_desc), setup.b.wLength.w), 0); + #endif + break; + default: + // nothing + USB_WritePacket(0, 0, 0); + break; + } + USBx_OUTEP(0)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; + break; + default: + // nothing here? + USB_WritePacket(0, 0, 0); + USBx_OUTEP(0)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; + break; + } + break; + case USB_REQ_GET_STATUS: + // empty resp? + resp[0] = 0; + resp[1] = 0; + USB_WritePacket((void*)&resp, 2, 0); + USBx_OUTEP(0)->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; + break; + default: + resp_len = usb_cb_control_msg(&setup, resp, 1); + USB_WritePacket(resp, min(resp_len, setup.b.wLength.w), 0); + USBx_OUTEP(0)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; + } +} + +void usb_init() { + // full speed PHY, do reset and remove power down + /*puth(USBx->GRSTCTL); + puts(" resetting PHY\n");*/ + while ((USBx->GRSTCTL & USB_OTG_GRSTCTL_AHBIDL) == 0); + //puts("AHB idle\n"); + + // reset PHY here + USBx->GRSTCTL |= USB_OTG_GRSTCTL_CSRST; + while ((USBx->GRSTCTL & USB_OTG_GRSTCTL_CSRST) == USB_OTG_GRSTCTL_CSRST); + //puts("reset done\n"); + + // internal PHY, force device mode + USBx->GUSBCFG = USB_OTG_GUSBCFG_PHYSEL | USB_OTG_GUSBCFG_FDMOD; + + // slowest timings + USBx->GUSBCFG |= (uint32_t)((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; + + /* 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; + //USBx->GUSBCFG |= (uint32_t)((USBD_FS_TRDT_VALUE << 10) & USB_OTG_GUSBCFG_TRDT); + //USBx->GUSBCFG = USB_OTG_GUSBCFG_PHYSEL | USB_OTG_GUSBCFG_TRDT | USB_OTG_GUSBCFG_TOCAL; + + // **** for debugging, doesn't seem to work **** + //USBx->GUSBCFG |= USB_OTG_GUSBCFG_CTXPKT; + + // reset PHY clock + USBx_PCGCCTL = 0; + + // enable the fancy OTG things + // DCFG_FRAME_INTERVAL_80 is 0 + //USBx->GUSBCFG |= USB_OTG_GUSBCFG_HNPCAP | USB_OTG_GUSBCFG_SRPCAP; + USBx_DEVICE->DCFG |= USB_OTG_SPEED_FULL | USB_OTG_DCFG_NZLSOHSK; + + //USBx_DEVICE->DCFG = USB_OTG_DCFG_NZLSOHSK | USB_OTG_DCFG_DSPD; + //USBx_DEVICE->DCFG = USB_OTG_DCFG_DSPD; + + // clear pending interrupts + USBx->GINTSTS = 0xBFFFFFFFU; + + // setup USB interrupts + // all interrupts except TXFIFO EMPTY + //USBx->GINTMSK = 0xFFFFFFFF & ~(USB_OTG_GINTMSK_NPTXFEM | USB_OTG_GINTMSK_PTXFEM | USB_OTG_GINTSTS_SOF | USB_OTG_GINTSTS_EOPF); + //USBx->GINTMSK = 0xFFFFFFFF & ~(USB_OTG_GINTMSK_NPTXFEM | USB_OTG_GINTMSK_PTXFEM); + USBx->GINTMSK = USB_OTG_GINTMSK_USBRST | USB_OTG_GINTMSK_ENUMDNEM | USB_OTG_GINTMSK_OTGINT | + USB_OTG_GINTMSK_RXFLVLM | USB_OTG_GINTMSK_GONAKEFFM | USB_OTG_GINTMSK_GINAKEFFM | + USB_OTG_GINTMSK_OEPINT | USB_OTG_GINTMSK_IEPINT | USB_OTG_GINTMSK_USBSUSPM | + USB_OTG_GINTMSK_CIDSCHGM | USB_OTG_GINTMSK_SRQIM | USB_OTG_GINTMSK_MMISM; + + USBx->GAHBCFG = USB_OTG_GAHBCFG_GINT; + + // DCTL startup value is 2 on new chip, 0 on old chip + // THIS IS FUCKING BULLSHIT + USBx_DEVICE->DCTL = 0; + + // enable the IRQ + NVIC_EnableIRQ(OTG_FS_IRQn); +} + +// ***************************** USB port ***************************** + +void usb_irqhandler(void) { + //USBx->GINTMSK = 0; + + unsigned int gintsts = USBx->GINTSTS; + unsigned int gotgint = USBx->GOTGINT; + unsigned int daint = USBx_DEVICE->DAINT; + + // gintsts SUSPEND? 04008428 + #ifdef DEBUG_USB + puth(gintsts); + puts(" "); + /*puth(USBx->GCCFG); + puts(" ");*/ + puth(gotgint); + puts(" ep "); + puth(daint); + puts(" USB interrupt!\n"); + #endif + + if (gintsts & USB_OTG_GINTSTS_CIDSCHG) { + puts("connector ID status change\n"); + } + + if (gintsts & USB_OTG_GINTSTS_ESUSP) { + puts("ESUSP detected\n"); + } + + if (gintsts & USB_OTG_GINTSTS_USBRST) { + puts("USB reset\n"); + usb_reset(); + } + + if (gintsts & USB_OTG_GINTSTS_ENUMDNE) { + puts("enumeration done"); + // Full speed, ENUMSPD + //puth(USBx_DEVICE->DSTS); + puts("\n"); + } + + if (gintsts & USB_OTG_GINTSTS_OTGINT) { + puts("OTG int:"); + puth(USBx->GOTGINT); + puts("\n"); + + // getting ADTOCHG + //USBx->GOTGINT = USBx->GOTGINT; + } + + // RX FIFO first + if (gintsts & USB_OTG_GINTSTS_RXFLVL) { + // 1. Read the Receive status pop register + volatile unsigned int rxst = USBx->GRXSTSP; + + #ifdef DEBUG_USB + puts(" RX FIFO:"); + puth(rxst); + puts(" status: "); + puth((rxst & USB_OTG_GRXSTSP_PKTSTS) >> 17); + puts(" len: "); + puth((rxst & USB_OTG_GRXSTSP_BCNT) >> 4); + puts("\n"); + #endif + + if (((rxst & USB_OTG_GRXSTSP_PKTSTS) >> 17) == STS_DATA_UPDT) { + int endpoint = (rxst & USB_OTG_GRXSTSP_EPNUM); + int len = (rxst & USB_OTG_GRXSTSP_BCNT) >> 4; + USB_ReadPacket(&usbdata, len); + #ifdef DEBUG_USB + puts(" data "); + puth(len); + puts("\n"); + hexdump(&usbdata, len); + #endif + + if (endpoint == 2) { + usb_cb_ep2_out(usbdata, len, 1); + } + + if (endpoint == 3) { + usb_cb_ep3_out(usbdata, len, 1); + } + } else if (((rxst & USB_OTG_GRXSTSP_PKTSTS) >> 17) == STS_SETUP_UPDT) { + USB_ReadPacket(&setup, 8); + #ifdef DEBUG_USB + puts(" setup "); + hexdump(&setup, 8); + puts("\n"); + #endif + } + } + + /*if (gintsts & USB_OTG_GINTSTS_HPRTINT) { + // host + puts("HPRT:"); + puth(USBx_HOST_PORT->HPRT); + puts("\n"); + if (USBx_HOST_PORT->HPRT & USB_OTG_HPRT_PCDET) { + USBx_HOST_PORT->HPRT |= USB_OTG_HPRT_PRST; + USBx_HOST_PORT->HPRT |= USB_OTG_HPRT_PCDET; + } + + }*/ + + if ((gintsts & USB_OTG_GINTSTS_BOUTNAKEFF) || (gintsts & USB_OTG_GINTSTS_GINAKEFF)) { + // no global NAK, why is this getting set? + #ifdef DEBUG_USB + puts("GLOBAL NAK\n"); + #endif + USBx_DEVICE->DCTL |= USB_OTG_DCTL_CGONAK | USB_OTG_DCTL_CGINAK; + } + + if (gintsts & USB_OTG_GINTSTS_SRQINT) { + // we want to do "A-device host negotiation protocol" since we are the A-device + /*puts("start request\n"); + puth(USBx->GOTGCTL); + puts("\n");*/ + //USBx->GUSBCFG |= USB_OTG_GUSBCFG_FDMOD; + //USBx_HOST_PORT->HPRT = USB_OTG_HPRT_PPWR | USB_OTG_HPRT_PENA; + //USBx->GOTGCTL |= USB_OTG_GOTGCTL_SRQ; + } + + // out endpoint hit + if (gintsts & USB_OTG_GINTSTS_OEPINT) { + #ifdef DEBUG_USB + puts(" 0:"); + puth(USBx_OUTEP(0)->DOEPINT); + puts(" 2:"); + puth(USBx_OUTEP(2)->DOEPINT); + puts(" 3:"); + puth(USBx_OUTEP(3)->DOEPINT); + puts(" "); + puth(USBx_OUTEP(3)->DOEPCTL); + puts(" 4:"); + puth(USBx_OUTEP(4)->DOEPINT); + puts(" OUT ENDPOINT\n"); + #endif + + if (USBx_OUTEP(2)->DOEPINT & USB_OTG_DOEPINT_XFRC) { + #ifdef DEBUG_USB + puts(" OUT2 PACKET XFRC\n"); + #endif + USBx_OUTEP(2)->DOEPTSIZ = (1 << 19) | 0x40; + USBx_OUTEP(2)->DOEPCTL |= USB_OTG_DOEPCTL_EPENA | USB_OTG_DOEPCTL_CNAK; + } + + if (USBx_OUTEP(3)->DOEPINT & USB_OTG_DOEPINT_XFRC) { + #ifdef DEBUG_USB + puts(" OUT3 PACKET XFRC\n"); + #endif + USBx_OUTEP(3)->DOEPTSIZ = (1 << 19) | 0x40; + USBx_OUTEP(3)->DOEPCTL |= USB_OTG_DOEPCTL_EPENA | USB_OTG_DOEPCTL_CNAK; + } else if (USBx_OUTEP(3)->DOEPINT & 0x2000) { + #ifdef DEBUG_USB + puts(" OUT3 PACKET WTF\n"); + #endif + // if NAK was set trigger this, unknown interrupt + USBx_OUTEP(3)->DOEPTSIZ = (1 << 19) | 0x40; + USBx_OUTEP(3)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK; + } else if (USBx_OUTEP(3)->DOEPINT) { + puts("OUTEP3 error "); + puth(USBx_OUTEP(3)->DOEPINT); + puts("\n"); + } + + if (USBx_OUTEP(0)->DOEPINT & USB_OTG_DIEPINT_XFRC) { + // ready for next packet + USBx_OUTEP(0)->DOEPTSIZ = USB_OTG_DOEPTSIZ_STUPCNT | (USB_OTG_DOEPTSIZ_PKTCNT & (1 << 19)) | (1 * 8); + } + + // respond to setup packets + if (USBx_OUTEP(0)->DOEPINT & USB_OTG_DOEPINT_STUP) { + 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; + } + + // interrupt endpoint hit (Page 1221) + if (gintsts & USB_OTG_GINTSTS_IEPINT) { + #ifdef DEBUG_USB + puts(" "); + puth(USBx_INEP(0)->DIEPINT); + puts(" "); + puth(USBx_INEP(1)->DIEPINT); + puts(" IN ENDPOINT\n"); + #endif + + // Should likely check the EP of the IN request even if there is + // only one IN endpoint. + + // No need to set NAK in OTG_DIEPCTL0 when nothing to send, + // Appears USB core automatically sets NAK. WritePacket clears it. + + // Handle the two interface alternate settings. Setting 0 is has + // EP1 as bulk. Setting 1 has EP1 as interrupt. The code to handle + // these two EP variations are very similar and can be + // restructured for smaller code footprint. Keeping split out for + // now for clarity. + + //TODO add default case. Should it NAK? + 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) { + #ifdef DEBUG_USB + puts(" IN PACKET QUEUE\n"); + #endif + // TODO: always assuming max len, can we get the length? + USB_WritePacket((void *)resp, usb_cb_ep1_in(resp, 0x40, 1), 1); + } + break; + + case 1: ////// Interrupt config + // *** IN token received when TxFIFO is empty + if (USBx_INEP(1)->DIEPINT & USB_OTG_DIEPMSK_ITTXFEMSK) { + #ifdef DEBUG_USB + puts(" IN PACKET QUEUE\n"); + #endif + // TODO: always assuming max len, can we get the length? + int len = usb_cb_ep1_in(resp, 0x40, 1); + if (len > 0) { + USB_WritePacket((void *)resp, len, 1); + } + } + break; + } + + // clear interrupts + USBx_INEP(0)->DIEPINT = USBx_INEP(0)->DIEPINT; // Why ep0? + USBx_INEP(1)->DIEPINT = USBx_INEP(1)->DIEPINT; + } + + // clear all interrupts we handled + USBx_DEVICE->DAINT = daint; + USBx->GOTGINT = gotgint; + USBx->GINTSTS = gintsts; + + //USBx->GINTMSK = 0xFFFFFFFF & ~(USB_OTG_GINTMSK_NPTXFEM | USB_OTG_GINTMSK_PTXFEM | USB_OTG_GINTSTS_SOF | USB_OTG_GINTSTS_EOPF); +} + +void OTG_FS_IRQHandler(void) { + NVIC_DisableIRQ(OTG_FS_IRQn); + //__disable_irq(); + usb_irqhandler(); + //__enable_irq(); + NVIC_EnableIRQ(OTG_FS_IRQn); +} + diff --git a/board/get_sdk.sh b/board/get_sdk.sh new file mode 100755 index 0000000000..2248d1b9ec --- /dev/null +++ b/board/get_sdk.sh @@ -0,0 +1,3 @@ +#!/bin/bash +sudo apt-get install gcc-arm-none-eabi python-pip +sudo pip2 install libusb1 diff --git a/board/get_sdk_mac.sh b/board/get_sdk_mac.sh new file mode 100644 index 0000000000..1c4c74ff8c --- /dev/null +++ b/board/get_sdk_mac.sh @@ -0,0 +1,5 @@ +#!/bin/bash +# Need formula for gcc +brew tap ArmMbed/homebrew-formulae +brew install python dfu-util arm-none-eabi-gcc +pip2 install libusb1 diff --git a/board/gpio.h b/board/gpio.h new file mode 100644 index 0000000000..0e15e3ba45 --- /dev/null +++ b/board/gpio.h @@ -0,0 +1,450 @@ +#ifdef STM32F4 + #include "stm32f4xx_hal_gpio_ex.h" +#else + #include "stm32f2xx_hal_gpio_ex.h" +#endif + +// ********************* dynamic configuration detection ********************* + +#define PANDA_REV_AB 0 +#define PANDA_REV_C 1 + +#define PULL_EFFECTIVE_DELAY 10 + +int has_external_debug_serial = 0; +int is_giant_panda = 0; +int is_entering_bootmode = 0; +int revision = PANDA_REV_AB; + +int detect_with_pull(GPIO_TypeDef *GPIO, int pin, int mode) { + set_gpio_mode(GPIO, pin, MODE_INPUT); + set_gpio_pullup(GPIO, pin, mode); + for (volatile int i=0; iCR |= RCC_CR_HSEON; + while ((RCC->CR & RCC_CR_HSERDY) == 0); + + // divide shit + RCC->CFGR = RCC_CFGR_HPRE_DIV1 | RCC_CFGR_PPRE2_DIV2 | RCC_CFGR_PPRE1_DIV4; + #ifdef PANDA + RCC->PLLCFGR = RCC_PLLCFGR_PLLQ_2 | RCC_PLLCFGR_PLLM_3 | + RCC_PLLCFGR_PLLN_6 | RCC_PLLCFGR_PLLN_5 | RCC_PLLCFGR_PLLSRC_HSE; + #else + RCC->PLLCFGR = RCC_PLLCFGR_PLLQ_2 | RCC_PLLCFGR_PLLM_3 | + RCC_PLLCFGR_PLLN_7 | RCC_PLLCFGR_PLLN_6 | RCC_PLLCFGR_PLLSRC_HSE; + #endif + + // start PLL + RCC->CR |= RCC_CR_PLLON; + while ((RCC->CR & RCC_CR_PLLRDY) == 0); + + // Configure Flash prefetch, Instruction cache, Data cache and wait state + // *** without this, it breaks *** + FLASH->ACR = FLASH_ACR_ICEN | FLASH_ACR_DCEN | FLASH_ACR_LATENCY_5WS; + + // switch to PLL + RCC->CFGR |= RCC_CFGR_SW_PLL; + while ((RCC->CFGR & RCC_CFGR_SWS) != RCC_CFGR_SWS_PLL); + + // *** running on PLL *** +} + +void periph_init() { + // enable GPIOB, UART2, CAN, USB clock + RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN; + RCC->AHB1ENR |= RCC_AHB1ENR_GPIOBEN; + RCC->AHB1ENR |= RCC_AHB1ENR_GPIOCEN; + RCC->AHB1ENR |= RCC_AHB1ENR_GPIODEN; + + RCC->AHB1ENR |= RCC_AHB1ENR_DMA2EN; + RCC->APB1ENR |= RCC_APB1ENR_USART2EN; + RCC->APB1ENR |= RCC_APB1ENR_USART3EN; + #ifdef PANDA + RCC->APB1ENR |= RCC_APB1ENR_UART5EN; + #endif + RCC->APB1ENR |= RCC_APB1ENR_CAN1EN; + RCC->APB1ENR |= RCC_APB1ENR_CAN2EN; + #ifdef CAN3 + RCC->APB1ENR |= RCC_APB1ENR_CAN3EN; + #endif + RCC->APB1ENR |= RCC_APB1ENR_DACEN; + RCC->APB1ENR |= RCC_APB1ENR_TIM2EN; + RCC->APB1ENR |= RCC_APB1ENR_TIM3EN; + //RCC->APB1ENR |= RCC_APB1ENR_TIM4EN; + RCC->APB2ENR |= RCC_APB2ENR_USART1EN; + RCC->AHB2ENR |= RCC_AHB2ENR_OTGFSEN; + RCC->APB2ENR |= RCC_APB2ENR_TIM1EN; + RCC->APB2ENR |= RCC_APB2ENR_ADC1EN; + RCC->APB2ENR |= RCC_APB2ENR_SPI1EN; + + // needed? + RCC->APB2ENR |= RCC_APB2ENR_SYSCFGEN; +} + +// ********************* setters ********************* + +void set_can_enable(CAN_TypeDef *CAN, int enabled) { + // enable CAN busses + if (CAN == CAN1) { + #ifdef PANDA + // CAN1_EN + set_gpio_output(GPIOC, 1, !enabled); + #else + // CAN1_EN + set_gpio_output(GPIOB, 3, enabled); + #endif + } else if (CAN == CAN2) { + #ifdef PANDA + // CAN2_EN + set_gpio_output(GPIOC, 13, !enabled); + #else + // CAN2_EN + set_gpio_output(GPIOB, 4, enabled); + #endif + #ifdef CAN3 + } else if (CAN == CAN3) { + // CAN3_EN + set_gpio_output(GPIOA, 0, !enabled); + #endif + } +} + +#ifdef PANDA + #define LED_RED 9 + #define LED_GREEN 7 + #define LED_BLUE 6 +#else + #define LED_RED 10 + #define LED_GREEN 11 + #define LED_BLUE -1 +#endif + +void set_led(int led_num, int on) { + if (led_num == -1) return; + + #ifdef PANDA + set_gpio_output(GPIOC, led_num, !on); + #else + set_gpio_output(GPIOB, led_num, !on); + #endif +} + +void set_can_mode(int can, int use_gmlan) { + // connects to CAN2 xcvr or GMLAN xcvr + if (use_gmlan) { + if (can == 1) { + // B5,B6: disable normal mode + set_gpio_mode(GPIOB, 5, MODE_INPUT); + set_gpio_mode(GPIOB, 6, MODE_INPUT); + + // B12,B13: gmlan mode + set_gpio_alternate(GPIOB, 12, GPIO_AF9_CAN2); + set_gpio_alternate(GPIOB, 13, GPIO_AF9_CAN2); +#ifdef CAN3 + } else if (revision == PANDA_REV_C && can == 2) { + // A8,A15: disable normal mode + set_gpio_mode(GPIOA, 8, MODE_INPUT); + set_gpio_mode(GPIOA, 15, MODE_INPUT); + + // B3,B4: enable gmlan mode + set_gpio_alternate(GPIOB, 3, GPIO_AF11_CAN3); + set_gpio_alternate(GPIOB, 4, GPIO_AF11_CAN3); +#endif + } + } else { + if (can == 1) { + // B12,B13: disable gmlan mode + set_gpio_mode(GPIOB, 12, MODE_INPUT); + set_gpio_mode(GPIOB, 13, MODE_INPUT); + + // B5,B6: normal mode + set_gpio_alternate(GPIOB, 5, GPIO_AF9_CAN2); + set_gpio_alternate(GPIOB, 6, GPIO_AF9_CAN2); +#ifdef CAN3 + } else if (can == 2) { + if(revision == PANDA_REV_C){ + // B3,B4: disable gmlan mode + set_gpio_mode(GPIOB, 3, MODE_INPUT); + set_gpio_mode(GPIOB, 4, MODE_INPUT); + } + // A8,A15: normal mode + set_gpio_alternate(GPIOA, 8, GPIO_AF11_CAN3); + set_gpio_alternate(GPIOA, 15, GPIO_AF11_CAN3); +#endif + } + } +} + +#define USB_POWER_NONE 0 +#define USB_POWER_CLIENT 1 +#define USB_POWER_CDP 2 +#define USB_POWER_DCP 3 + +int usb_power_mode = USB_POWER_NONE; + +void set_usb_power_mode(int mode) { + switch (mode) { + case USB_POWER_CLIENT: + // B2,A13: set client mode + set_gpio_output(GPIOB, 2, 0); + set_gpio_output(GPIOA, 13, 1); + break; + case USB_POWER_CDP: + // B2,A13: set CDP mode + set_gpio_output(GPIOB, 2, 1); + set_gpio_output(GPIOA, 13, 1); + break; + case USB_POWER_DCP: + // B2,A13: set DCP mode on the charger (breaks USB!) + set_gpio_output(GPIOB, 2, 0); + set_gpio_output(GPIOA, 13, 0); + break; + } + usb_power_mode = mode; +} + +#define ESP_DISABLED 0 +#define ESP_ENABLED 1 +#define ESP_BOOTMODE 2 + +void set_esp_mode(int mode) { + switch (mode) { + case ESP_DISABLED: + // ESP OFF + set_gpio_output(GPIOC, 14, 0); + set_gpio_output(GPIOC, 5, 0); + break; + case ESP_ENABLED: + // ESP ON + set_gpio_output(GPIOC, 14, 1); + set_gpio_output(GPIOC, 5, 1); + break; + case ESP_BOOTMODE: + set_gpio_output(GPIOC, 14, 1); + set_gpio_output(GPIOC, 5, 0); + break; + } +} + +// ********************* big init function ********************* + +// board specific +void gpio_init() { + // pull low to hold ESP in reset?? + // enable OTG out tied to ground + GPIOA->ODR = 0; + GPIOB->ODR = 0; + GPIOA->PUPDR = 0; + //GPIOC->ODR = 0; + GPIOB->AFR[0] = 0; + GPIOB->AFR[1] = 0; + + // C2,C3: analog mode, voltage and current sense + set_gpio_mode(GPIOC, 2, MODE_ANALOG); + set_gpio_mode(GPIOC, 3, MODE_ANALOG); + + // C8: FAN aka TIM3_CH4 + set_gpio_alternate(GPIOC, 8, GPIO_AF2_TIM3); + + // turn off LEDs and set mode + set_led(LED_RED, 0); + set_led(LED_GREEN, 0); + set_led(LED_BLUE, 0); + + // A11,A12: USB + set_gpio_alternate(GPIOA, 11, GPIO_AF10_OTG_FS); + set_gpio_alternate(GPIOA, 12, GPIO_AF10_OTG_FS); + GPIOA->OSPEEDR = GPIO_OSPEEDER_OSPEEDR11 | GPIO_OSPEEDER_OSPEEDR12; + +#ifdef PANDA + // enable started_alt on the panda + set_gpio_pullup(GPIOA, 1, PULL_UP); + + // A2,A3: USART 2 for debugging + set_gpio_alternate(GPIOA, 2, GPIO_AF7_USART2); + set_gpio_alternate(GPIOA, 3, GPIO_AF7_USART2); + + // A9,A10: USART 1 for talking to the ESP + set_gpio_alternate(GPIOA, 9, GPIO_AF7_USART1); + set_gpio_alternate(GPIOA, 10, GPIO_AF7_USART1); + + // B12: GMLAN, ignition sense, pull up + set_gpio_pullup(GPIOB, 12, PULL_UP); + + // A4,A5,A6,A7: setup SPI + set_gpio_alternate(GPIOA, 4, GPIO_AF5_SPI1); + set_gpio_alternate(GPIOA, 5, GPIO_AF5_SPI1); + set_gpio_alternate(GPIOA, 6, GPIO_AF5_SPI1); + set_gpio_alternate(GPIOA, 7, GPIO_AF5_SPI1); +#endif + + // 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 + set_can_enable(CAN1, 1); + + // B5,B6: CAN 2 + set_can_mode(1, 0); + set_can_enable(CAN2, 1); + + // A8,A15: CAN 3 + #ifdef CAN3 + set_can_mode(2, 0); + set_can_enable(CAN3, 1); + #endif + + /* GMLAN mode pins: + M0(B15) M1(B14) mode + ======================= + 0 0 sleep + 1 0 100kbit + 0 1 high voltage wakeup + 1 1 33kbit (normal) + */ + + // put gmlan transceiver in normal mode + set_gpio_output(GPIOB, 14, 1); + set_gpio_output(GPIOB, 15, 1); + + #ifdef PANDA + // K-line enable moved from B4->B7 to make room for GMLAN on CAN3 + if (revision == PANDA_REV_C) { + set_gpio_output(GPIOB, 7, 1); // REV C + } else { + set_gpio_output(GPIOB, 4, 1); // REV AB + } + + // C12,D2: K-Line setup on UART 5 + set_gpio_alternate(GPIOC, 12, GPIO_AF8_UART5); + set_gpio_alternate(GPIOD, 2, GPIO_AF8_UART5); + set_gpio_pullup(GPIOD, 2, PULL_UP); + + // L-line enable + set_gpio_output(GPIOA, 14, 1); + + // C10,C11: L-Line setup on USART 3 + set_gpio_alternate(GPIOC, 10, GPIO_AF7_USART3); + set_gpio_alternate(GPIOC, 11, GPIO_AF7_USART3); + set_gpio_pullup(GPIOC, 11, PULL_UP); + #endif + + if (revision == PANDA_REV_C) { + set_usb_power_mode(USB_POWER_CLIENT); + } +} + +// ********************* early bringup ********************* + +#define ENTER_BOOTLOADER_MAGIC 0xdeadbeef +#define ENTER_SOFTLOADER_MAGIC 0xdeadc0de +#define BOOT_NORMAL 0xdeadb111 + +extern void *g_pfnVectors; +extern uint32_t enter_bootloader_mode; + +void jump_to_bootloader() { + // do enter bootloader + enter_bootloader_mode = 0; + void (*bootloader)(void) = (void (*)(void)) (*((uint32_t *)0x1fff0004)); + + // jump to bootloader + bootloader(); + + // reset on exit + enter_bootloader_mode = BOOT_NORMAL; + NVIC_SystemReset(); +} + +void early() { + // after it's been in the bootloader, things are initted differently, so we reset + if (enter_bootloader_mode != BOOT_NORMAL && + enter_bootloader_mode != ENTER_BOOTLOADER_MAGIC && + enter_bootloader_mode != ENTER_SOFTLOADER_MAGIC) { + enter_bootloader_mode = BOOT_NORMAL; + NVIC_SystemReset(); + } + + // if wrong chip, reboot + volatile unsigned int id = DBGMCU->IDCODE; + #ifdef STM32F4 + if ((id&0xFFF) != 0x463) enter_bootloader_mode = ENTER_BOOTLOADER_MAGIC; + #else + if ((id&0xFFF) != 0x411) enter_bootloader_mode = ENTER_BOOTLOADER_MAGIC; + #endif + + // setup interrupt table + SCB->VTOR = (uint32_t)&g_pfnVectors; + + // early GPIOs float everything + RCC->AHB1ENR = RCC_AHB1ENR_GPIOAEN | RCC_AHB1ENR_GPIOBEN | RCC_AHB1ENR_GPIOCEN; + + GPIOA->MODER = 0; GPIOB->MODER = 0; GPIOC->MODER = 0; + GPIOA->ODR = 0; GPIOB->ODR = 0; GPIOC->ODR = 0; + GPIOA->PUPDR = 0; GPIOB->PUPDR = 0; GPIOC->PUPDR = 0; + + detect(); + + #ifdef PANDA + // enable the ESP, disable ESP boot mode + // unless we are on a giant panda, then there's no ESP + if (is_giant_panda) { + set_esp_mode(ESP_DISABLED); + } else { + set_esp_mode(ESP_ENABLED); + } + #endif + + + if (enter_bootloader_mode == ENTER_BOOTLOADER_MAGIC) { + set_esp_mode(ESP_DISABLED); + set_led(LED_GREEN, 1); + + jump_to_bootloader(); + } + + if (is_entering_bootmode) { + enter_bootloader_mode = ENTER_SOFTLOADER_MAGIC; + } +} + diff --git a/board/inc/cmsis_gcc.h b/board/inc/cmsis_gcc.h new file mode 100644 index 0000000000..94e69eedf9 --- /dev/null +++ b/board/inc/cmsis_gcc.h @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6c7e75d09887cb3035f18bc6f4fdbd7392a50379cd556315deb3bcb762d99078 +size 40062 diff --git a/board/inc/core_cm3.h b/board/inc/core_cm3.h new file mode 100644 index 0000000000..2ec8c848a9 --- /dev/null +++ b/board/inc/core_cm3.h @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:03a80f17ff18c5d0e3b234009f98698cd402b8ea972df687a6cfafd8b8a78654 +size 102146 diff --git a/board/inc/core_cm4.h b/board/inc/core_cm4.h new file mode 100644 index 0000000000..f3a7ca0e48 --- /dev/null +++ b/board/inc/core_cm4.h @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:83c5d601dd5640a863fe4dc43cd228b46239bbf9f07b51102bf0c1c8f235cdfa +size 112561 diff --git a/board/inc/core_cmFunc.h b/board/inc/core_cmFunc.h new file mode 100644 index 0000000000..6f4be85719 --- /dev/null +++ b/board/inc/core_cmFunc.h @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1fdd226d82bde2a90231ba47a59377158b8907e4cada2a6215f32dcf13ab35cd +size 3533 diff --git a/board/inc/core_cmInstr.h b/board/inc/core_cmInstr.h new file mode 100644 index 0000000000..226e8a75e5 --- /dev/null +++ b/board/inc/core_cmInstr.h @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c9b8e36d05097da5d493f197aa7f81ce517f4532536925b568ccbd6e2c01eb8a +size 3549 diff --git a/board/inc/core_cmSimd.h b/board/inc/core_cmSimd.h new file mode 100644 index 0000000000..fbec148892 --- /dev/null +++ b/board/inc/core_cmSimd.h @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5d338d36730ccbd138126078e17f69c308a015f0a88d85bd639af072e527d53d +size 3566 diff --git a/board/inc/stm32f205xx.h b/board/inc/stm32f205xx.h new file mode 100644 index 0000000000..31ec924dc5 --- /dev/null +++ b/board/inc/stm32f205xx.h @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:65ac7a82a58b702c8c8b99cf7ee965c71cd59d5dfa663d3729a602bdea8ec4cd +size 601889 diff --git a/board/inc/stm32f2xx.h b/board/inc/stm32f2xx.h new file mode 100644 index 0000000000..83bb93ef1e --- /dev/null +++ b/board/inc/stm32f2xx.h @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9591dc7b364d8e963152a4a15f0435e8631a9d4eacc95fca022574269047dada +size 6738 diff --git a/board/inc/stm32f2xx_hal_def.h b/board/inc/stm32f2xx_hal_def.h new file mode 100644 index 0000000000..f4f8cb02df --- /dev/null +++ b/board/inc/stm32f2xx_hal_def.h @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a312bdc79b5ac3c780f700869f73237256047e1f134310087cd1c4d3ef8255fd +size 7352 diff --git a/board/inc/stm32f2xx_hal_gpio_ex.h b/board/inc/stm32f2xx_hal_gpio_ex.h new file mode 100644 index 0000000000..11b5823863 --- /dev/null +++ b/board/inc/stm32f2xx_hal_gpio_ex.h @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e320fb1b6f44dadb3b819146ffce5cf4d1d5b0482d2ba7cddc4845899e47290c +size 12933 diff --git a/board/inc/stm32f413xx.h b/board/inc/stm32f413xx.h new file mode 100644 index 0000000000..af1a5764a4 --- /dev/null +++ b/board/inc/stm32f413xx.h @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:21e5ea5bc19e8d45cf4f32d451ea7f79a62c50e5a6c0e07cc7752ed0c9d295c3 +size 1288438 diff --git a/board/inc/stm32f4xx.h b/board/inc/stm32f4xx.h new file mode 100644 index 0000000000..c86ad0af71 --- /dev/null +++ b/board/inc/stm32f4xx.h @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7ccd163515bc57fa7a1ce31361ec1bc70a1b3e2c82873e940dfaaaf1072b4d3d +size 10525 diff --git a/board/inc/stm32f4xx_hal_def.h b/board/inc/stm32f4xx_hal_def.h new file mode 100644 index 0000000000..b3b1090dc9 --- /dev/null +++ b/board/inc/stm32f4xx_hal_def.h @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8f2c6a79cf25619734b65bd7e1babaeb9702fa86c89a221c3f7ea2c7ab8c2146 +size 8325 diff --git a/board/inc/stm32f4xx_hal_gpio_ex.h b/board/inc/stm32f4xx_hal_gpio_ex.h new file mode 100644 index 0000000000..cf5c9e5dcc --- /dev/null +++ b/board/inc/stm32f4xx_hal_gpio_ex.h @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2600c6ad35c8accf5aa0878a151aa69a3e21859fb7675b3ce71c0fb44ef7f521 +size 81942 diff --git a/board/inc/system_stm32f2xx.h b/board/inc/system_stm32f2xx.h new file mode 100644 index 0000000000..d5ce15cc00 --- /dev/null +++ b/board/inc/system_stm32f2xx.h @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:75bc5bac6341c0e088408c2b1548eafa24b80287bd37f6807cf52cf652984fa3 +size 3556 diff --git a/board/inc/system_stm32f4xx.h b/board/inc/system_stm32f4xx.h new file mode 100644 index 0000000000..c4497d6c7c --- /dev/null +++ b/board/inc/system_stm32f4xx.h @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a631a141f5e85b8fcef77b5f756392d1b9546c336fae6a565f037d84dcbe3df7 +size 3724 diff --git a/board/libc.h b/board/libc.h new file mode 100644 index 0000000000..8d80a3aad8 --- /dev/null +++ b/board/libc.h @@ -0,0 +1,51 @@ +// **** shitty libc **** + +void delay(int a) { + volatile int i; + for (i=0;iCCMR2 = TIM_CCMR2_OC3M_2 | TIM_CCMR2_OC3M_1; + TIM3->CCER = TIM_CCER_CC3E; + timer_init(TIM3, 10); +} + +void fan_set_speed(int fan_speed) { + TIM3->CCR3 = fan_speed; +} + +// ********************* serial debugging ********************* + +void debug_ring_callback(uart_ring *ring) { + char rcv; + while (getc(ring, &rcv)) { + putc(ring, rcv); + + // jump to DFU flash + if (rcv == 'z') { + enter_bootloader_mode = ENTER_BOOTLOADER_MAGIC; + NVIC_SystemReset(); + } + + // normal reset + if (rcv == 'x') { + NVIC_SystemReset(); + } + + // enable CDP mode + if (rcv == 'C') { + puts("switching USB to CDP mode\n"); + set_usb_power_mode(USB_POWER_CDP); + } + if (rcv == 'c') { + puts("switching USB to client mode\n"); + set_usb_power_mode(USB_POWER_CLIENT); + } + if (rcv == 'D') { + puts("switching USB to DCP mode\n"); + set_usb_power_mode(USB_POWER_DCP); + } + } +} + +// ***************************** USB port ***************************** + +int get_health_pkt(void *dat) { + struct __attribute__((packed)) { + uint32_t voltage; + uint32_t current; + uint8_t started; + uint8_t controls_allowed; + uint8_t gas_interceptor_detected; + uint8_t started_signal_detected; + uint8_t started_alt; + } *health = dat; + + //Voltage will be measured in mv. 5000 = 5V + uint32_t voltage = adc_get(ADCCHAN_VOLTAGE); + if (revision == PANDA_REV_AB) { + //REVB has a 100, 27 (27/127) voltage divider + //Here is the calculation for the scale + //ADCV = VIN_S * (27/127) * (4095/3.3) + //RETVAL = ADCV * s = VIN_S*1000 + //s = 1000/((4095/3.3)*(27/127)) = 3.79053046 + + //Avoid needing floating point math + health->voltage = (voltage * 3791) / 1000; + } else { + //REVC has a 10, 1 (1/11) voltage divider + //Here is the calculation for the scale (s) + //ADCV = VIN_S * (1/11) * (4095/3.3) + //RETVAL = ADCV * s = VIN_S*1000 + //s = 1000/((4095/3.3)*(1/11)) = 8.8623046875 + + //Avoid needing floating point math + health->voltage = (voltage * 8862) / 1000; + } + +#ifdef PANDA + health->current = adc_get(ADCCHAN_CURRENT); + health->started = (GPIOA->IDR & (1 << 1)) == 0; +#else + health->current = 0; + health->started = (GPIOC->IDR & (1 << 13)) != 0; +#endif + + health->controls_allowed = controls_allowed; + health->gas_interceptor_detected = gas_interceptor_detected; + + // DEPRECATED + health->started_alt = 0; + health->started_signal_detected = 0; + + return sizeof(*health); +} + +int usb_cb_ep1_in(uint8_t *usbdata, int len, int hardwired) { + CAN_FIFOMailBox_TypeDef *reply = (CAN_FIFOMailBox_TypeDef *)usbdata; + int ilen = 0; + while (ilen < min(len/0x10, 4) && can_pop(&can_rx_q, &reply[ilen])) ilen++; + return ilen*0x10; +} + +// send on serial, first byte to select the ring +void usb_cb_ep2_out(uint8_t *usbdata, int len, int hardwired) { + if (len == 0) return; + uart_ring *ur = get_ring_by_number(usbdata[0]); + if (!ur) return; + if ((usbdata[0] < 2) || safety_tx_lin_hook(usbdata[0]-2, usbdata+1, len-1)) { + for (int i = 1; i < len; i++) while (!putc(ur, usbdata[i])); + } +} + +// send on CAN +void usb_cb_ep3_out(uint8_t *usbdata, int len, int hardwired) { + int dpkt = 0; + for (dpkt = 0; dpkt < len; dpkt += 0x10) { + uint32_t *tf = (uint32_t*)(&usbdata[dpkt]); + + // make a copy + CAN_FIFOMailBox_TypeDef to_push; + to_push.RDHR = tf[3]; + to_push.RDLR = tf[2]; + to_push.RDTR = tf[1]; + to_push.RIR = tf[0]; + + uint8_t bus_number = (to_push.RDTR >> 4) & CAN_BUS_NUM_MASK; + can_send(&to_push, bus_number); + } +} + +int is_enumerated = 0; + +void usb_cb_enumeration_complete() { + puts("USB enumeration complete\n"); + is_enumerated = 1; +} + +int usb_cb_control_msg(USB_Setup_TypeDef *setup, uint8_t *resp, int hardwired) { + int resp_len = 0; + uart_ring *ur = NULL; + int i; + switch (setup->b.bRequest) { + // **** 0xc0: get CAN debug info + case 0xc0: + puts("can tx: "); puth(can_tx_cnt); + puts(" txd: "); puth(can_txd_cnt); + puts(" rx: "); puth(can_rx_cnt); + puts(" err: "); puth(can_err_cnt); + puts("\n"); + break; + // **** 0xd0: fetch serial number + case 0xd0: + #ifdef PANDA + // addresses are OTP + if (setup->b.wValue.w == 1) { + memcpy(resp, (void *)0x1fff79c0, 0x10); + resp_len = 0x10; + } else { + get_provision_chunk(resp); + resp_len = PROVISION_CHUNK_LEN; + } + #endif + break; + // **** 0xd1: enter bootloader mode + case 0xd1: + // this allows reflashing of the bootstub + // so it's blocked over wifi + switch (setup->b.wValue.w) { + case 0: + if (hardwired) { + puts("-> entering bootloader\n"); + enter_bootloader_mode = ENTER_BOOTLOADER_MAGIC; + NVIC_SystemReset(); + } + break; + case 1: + puts("-> entering softloader\n"); + enter_bootloader_mode = ENTER_SOFTLOADER_MAGIC; + NVIC_SystemReset(); + break; + } + break; + // **** 0xd2: get health packet + case 0xd2: + resp_len = get_health_pkt(resp); + break; + // **** 0xd3: set fan speed + case 0xd3: + fan_set_speed(setup->b.wValue.w); + break; + // **** 0xd6: get version + case 0xd6: + COMPILE_TIME_ASSERT(sizeof(gitversion) <= MAX_RESP_LEN) + memcpy(resp, gitversion, sizeof(gitversion)); + resp_len = sizeof(gitversion)-1; + break; + // **** 0xd8: reset ST + case 0xd8: + NVIC_SystemReset(); + break; + // **** 0xd9: set ESP power + case 0xd9: + if (setup->b.wValue.w == 1) { + set_esp_mode(ESP_ENABLED); + } else { + set_esp_mode(ESP_DISABLED); + } + break; + // **** 0xda: reset ESP, with optional boot mode + case 0xda: + set_esp_mode(ESP_DISABLED); + delay(1000000); + if (setup->b.wValue.w == 1) { + set_esp_mode(ESP_BOOTMODE); + } else { + set_esp_mode(ESP_ENABLED); + } + delay(1000000); + set_esp_mode(ESP_ENABLED); + break; + // **** 0xdb: set GMLAN multiplexing mode + case 0xdb: + #ifdef PANDA + if (setup->b.wValue.w == 1) { + // GMLAN ON + if (setup->b.wIndex.w == 1) { + can_set_gmlan(1); + } else if (setup->b.wIndex.w == 2) { + // might be ignored on rev b panda + can_set_gmlan(2); + } + } else { + can_set_gmlan(-1); + } + #endif + break; + // **** 0xdc: set safety mode + case 0xdc: + // this is the only way to leave silent mode + // and it's blocked over WiFi + // Allow ELM security mode to be set over wifi. + if (hardwired || setup->b.wValue.w == SAFETY_NOOUTPUT || setup->b.wValue.w == SAFETY_ELM327) { + safety_set_mode(setup->b.wValue.w); + switch (setup->b.wValue.w) { + case SAFETY_NOOUTPUT: + can_silent = ALL_CAN_SILENT; + break; + case SAFETY_ELM327: + can_silent = ALL_CAN_BUT_MAIN_SILENT; + break; + default: + can_silent = ALL_CAN_LIVE; + break; + } + can_init_all(); + } + break; + // **** 0xdd: enable can forwarding + case 0xdd: + // wValue = Can Bus Num to forward from + // wIndex = Can Bus Num to forward to + if (setup->b.wValue.w < BUS_MAX && setup->b.wIndex.w < BUS_MAX && + setup->b.wValue.w != setup->b.wIndex.w) { // set forwarding + can_set_forwarding(setup->b.wValue.w, setup->b.wIndex.w & CAN_BUS_NUM_MASK); + } else if(setup->b.wValue.w < BUS_MAX && setup->b.wIndex.w == 0xFF){ //Clear Forwarding + can_set_forwarding(setup->b.wValue.w, -1); + } + break; + // **** 0xde: set can bitrate + case 0xde: + if (setup->b.wValue.w < BUS_MAX) { + can_speed[setup->b.wValue.w] = setup->b.wIndex.w; + can_init(CAN_NUM_FROM_BUS_NUM(setup->b.wValue.w)); + } + break; + // **** 0xe0: uart read + case 0xe0: + ur = get_ring_by_number(setup->b.wValue.w); + if (!ur) break; + // read + while ((resp_len < min(setup->b.wLength.w, MAX_RESP_LEN)) && + getc(ur, (char*)&resp[resp_len])) { + ++resp_len; + } + break; + // **** 0xe1: uart set baud rate + case 0xe1: + ur = get_ring_by_number(setup->b.wValue.w); + if (!ur) break; + uart_set_baud(ur->uart, setup->b.wIndex.w); + break; + // **** 0xe2: uart set parity + case 0xe2: + ur = get_ring_by_number(setup->b.wValue.w); + if (!ur) break; + switch (setup->b.wIndex.w) { + case 0: + // disable parity, 8-bit + ur->uart->CR1 &= ~(USART_CR1_PCE | USART_CR1_M); + break; + case 1: + // even parity, 9-bit + ur->uart->CR1 &= ~USART_CR1_PS; + ur->uart->CR1 |= USART_CR1_PCE | USART_CR1_M; + break; + case 2: + // odd parity, 9-bit + ur->uart->CR1 |= USART_CR1_PS; + ur->uart->CR1 |= USART_CR1_PCE | USART_CR1_M; + break; + default: + break; + } + break; + // **** 0xe4: uart set baud rate extended + case 0xe4: + ur = get_ring_by_number(setup->b.wValue.w); + if (!ur) break; + uart_set_baud(ur->uart, (int)setup->b.wIndex.w*300); + break; + // **** 0xe5: set CAN loopback (for testing) + case 0xe5: + can_loopback = (setup->b.wValue.w > 0); + can_init_all(); + break; + // **** 0xe6: set USB power + case 0xe6: + if (revision == PANDA_REV_C) { + if (setup->b.wValue.w == 1) { + puts("user setting CDP mode\n"); + set_usb_power_mode(USB_POWER_CDP); + } else if (setup->b.wValue.w == 2) { + puts("user setting DCP mode\n"); + set_usb_power_mode(USB_POWER_DCP); + } else { + puts("user setting CLIENT mode\n"); + set_usb_power_mode(USB_POWER_CLIENT); + } + } + break; + // **** 0xf0: do k-line wValue pulse on uart2 for Acura + case 0xf0: + if (setup->b.wValue.w == 1) { + GPIOC->ODR &= ~(1 << 10); + GPIOC->MODER &= ~GPIO_MODER_MODER10_1; + GPIOC->MODER |= GPIO_MODER_MODER10_0; + } else { + GPIOC->ODR &= ~(1 << 12); + GPIOC->MODER &= ~GPIO_MODER_MODER12_1; + GPIOC->MODER |= GPIO_MODER_MODER12_0; + } + + for (i = 0; i < 80; i++) { + delay(8000); + if (setup->b.wValue.w == 1) { + GPIOC->ODR |= (1 << 10); + GPIOC->ODR &= ~(1 << 10); + } else { + GPIOC->ODR |= (1 << 12); + GPIOC->ODR &= ~(1 << 12); + } + } + + if (setup->b.wValue.w == 1) { + GPIOC->MODER &= ~GPIO_MODER_MODER10_0; + GPIOC->MODER |= GPIO_MODER_MODER10_1; + } else { + GPIOC->MODER &= ~GPIO_MODER_MODER12_0; + GPIOC->MODER |= GPIO_MODER_MODER12_1; + } + + delay(140 * 9000); + break; + // **** 0xf1: Clear CAN ring buffer. + case 0xf1: + if (setup->b.wValue.w == 0xFFFF) { + puts("Clearing CAN Rx queue\n"); + can_clear(&can_rx_q); + } else if (setup->b.wValue.w < BUS_MAX) { + puts("Clearing CAN Tx queue\n"); + can_clear(can_queues[setup->b.wValue.w]); + } + break; + // **** 0xf2: Clear UART ring buffer. + case 0xf2: + { + uart_ring * rb = get_ring_by_number(setup->b.wValue.w); + if (rb) { + puts("Clearing UART queue.\n"); + clear_uart_buff(rb); + } + break; + } + default: + puts("NO HANDLER "); + puth(setup->b.bRequest); + puts("\n"); + break; + } + return resp_len; +} + +#ifdef PANDA +int spi_cb_rx(uint8_t *data, int len, uint8_t *data_out) { + // data[0] = endpoint + // data[2] = length + // data[4:] = data + + int resp_len = 0; + switch (data[0]) { + case 0: + // control transfer + resp_len = usb_cb_control_msg((USB_Setup_TypeDef *)(data+4), data_out, 0); + break; + case 1: + // ep 1, read + resp_len = usb_cb_ep1_in(data_out, 0x40, 0); + break; + case 2: + // ep 2, send serial + usb_cb_ep2_out(data+4, data[2], 0); + break; + case 3: + // ep 3, send CAN + usb_cb_ep3_out(data+4, data[2], 0); + break; + } + return resp_len; +} + +#else + +int spi_cb_rx(uint8_t *data, int len, uint8_t *data_out) { return 0; }; + +#endif + + +// ***************************** main code ***************************** + +void __initialize_hardware_early() { + early(); +} + +int main() { + // shouldn't have interrupts here, but just in case + __disable_irq(); + + // init early devices + clock_init(); + periph_init(); + detect(); + + // print hello + puts("\n\n\n************************ MAIN START ************************\n"); + + // detect the revision and init the GPIOs + puts("config:\n"); + #ifdef PANDA + puts(revision == PANDA_REV_C ? " panda rev c\n" : " panda rev a or b\n"); + #else + puts(" legacy\n"); + #endif + puts(has_external_debug_serial ? " real serial\n" : " USB serial\n"); + puts(is_giant_panda ? " GIANTpanda detected\n" : " not GIANTpanda\n"); + puts(is_entering_bootmode ? " ESP wants bootmode\n" : " no bootmode\n"); + gpio_init(); + + // enable main uart if it's connected + if (has_external_debug_serial) { + // WEIRDNESS: without this gate around the UART, it would "crash", but only if the ESP is enabled + // assuming it's because the lines were left floating and spurious noise was on them + uart_init(USART2, 115200); + } + +#ifdef PANDA + // enable ESP uart + uart_init(USART1, 115200); + + // enable LIN + uart_init(UART5, 10400); + UART5->CR2 |= USART_CR2_LINEN; + uart_init(USART3, 10400); + USART3->CR2 |= USART_CR2_LINEN; +#endif + + // init microsecond system timer + // increments 1000000 times per second + // generate an update to set the prescaler + TIM2->PSC = 48-1; + TIM2->CR1 = TIM_CR1_CEN; + TIM2->EGR = TIM_EGR_UG; + // use TIM2->CNT to read + + // enable USB + usb_init(); + + // default to silent mode to prevent issues with Ford + safety_set_mode(SAFETY_NOOUTPUT); + can_silent = ALL_CAN_SILENT; + can_init_all(); + + adc_init(); + +#ifdef PANDA + spi_init(); +#endif + + // set PWM + fan_init(); + fan_set_speed(0); + + puts("**** INTERRUPTS ON ****\n"); + + __enable_irq(); + + // LED should keep on blinking all the time + uint64_t cnt = 0; + + #ifdef PANDA + uint64_t marker = 0; + #define CURRENT_THRESHOLD 0xF00 + #define CLICKS 8 + #endif + + for (cnt=0;;cnt++) { + can_live = pending_can_live; + + #ifdef PANDA + int current = adc_get(ADCCHAN_CURRENT); + + switch (usb_power_mode) { + case USB_POWER_CLIENT: + if ((cnt-marker) >= CLICKS) { + if (!is_enumerated) { + puts("USBP: didn't enumerate, switching to CDP mode\n"); + // switch to CDP + set_usb_power_mode(USB_POWER_CDP); + marker = cnt; + } + } + // keep resetting the timer if it's enumerated + if (is_enumerated) { + marker = cnt; + } + break; + case USB_POWER_CDP: + // been CLICKS clicks since we switched to CDP + if ((cnt-marker) >= CLICKS) { + // measure current draw, if positive and no enumeration, switch to DCP + if (!is_enumerated && current < CURRENT_THRESHOLD) { + puts("USBP: no enumeration with current draw, switching to DCP mode\n"); + set_usb_power_mode(USB_POWER_DCP); + marker = cnt; + } + } + // keep resetting the timer if there's no current draw in CDP + if (current >= CURRENT_THRESHOLD) { + marker = cnt; + } + break; + case USB_POWER_DCP: + // been at least CLICKS clicks since we switched to DCP + if ((cnt-marker) >= CLICKS) { + // if no current draw, switch back to CDP + if (current >= CURRENT_THRESHOLD) { + puts("USBP: no current draw, switching back to CDP mode\n"); + set_usb_power_mode(USB_POWER_CDP); + marker = cnt; + } + } + // keep resetting the timer if there's current draw in DCP + if (current < CURRENT_THRESHOLD) { + marker = cnt; + } + break; + } + + // ~0x9a = 500 ma + /*puth(current); + puts("\n");*/ + #endif + + // reset this every 16th pass + if ((cnt&0xF) == 0) pending_can_live = 0; + + #ifdef DEBUG + puts("** blink "); + puth(can_rx_q.r_ptr); puts(" "); puth(can_rx_q.w_ptr); puts(" "); + puth(can_tx1_q.r_ptr); puts(" "); puth(can_tx1_q.w_ptr); puts(" "); + puth(can_tx2_q.r_ptr); puts(" "); puth(can_tx2_q.w_ptr); puts("\n"); + #endif + + // set green LED to be controls allowed + set_led(LED_GREEN, controls_allowed); + + // blink the red LED + int div_mode = ((usb_power_mode == USB_POWER_DCP) ? 4 : 1); + + for (int div_mode_loop = 0; div_mode_loop < div_mode; div_mode_loop++) { + for (int fade = 0; fade < 1024; fade += 8) { + for (int i = 0; i < 128/div_mode; i++) { + set_led(LED_RED, 0); + if (fade < 512) { delay(512-fade); } else { delay(fade-512); } + set_led(LED_RED, 1); + if (fade < 512) { delay(fade); } else { delay(1024-fade); } + } + } + } + + // turn off the blue LED, turned on by CAN + #ifdef PANDA + set_led(LED_BLUE, 0); + #endif + } + + return 0; +} diff --git a/board/obj/.placeholder b/board/obj/.placeholder new file mode 100644 index 0000000000..e69de29bb2 diff --git a/board/provision.h b/board/provision.h new file mode 100644 index 0000000000..2fad513508 --- /dev/null +++ b/board/provision.h @@ -0,0 +1,13 @@ +#define PROVISION_CHUNK_LEN 0x20 + +// WiFi SSID = 0x0 - 0x10 +// WiFi password = 0x10 - 0x1C +// SHA1 checksum = 0x1C - 0x20 + +void get_provision_chunk(uint8_t *resp) { + memcpy(resp, (void *)0x1fff79e0, PROVISION_CHUNK_LEN); + if (memcmp(resp, "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff", 0x20) == 0) { + memcpy(resp, "unprovisioned\x00\x00\x00testing123\x00\x00\xa3\xa6\x99\xec", 0x20); + } +} + diff --git a/board/safety.h b/board/safety.h new file mode 100644 index 0000000000..dc4631f460 --- /dev/null +++ b/board/safety.h @@ -0,0 +1,73 @@ +void safety_rx_hook(CAN_FIFOMailBox_TypeDef *to_push); +int safety_tx_hook(CAN_FIFOMailBox_TypeDef *to_send); +int safety_tx_lin_hook(int lin_num, uint8_t *data, int len); + +typedef void (*safety_hook_init)(); +typedef void (*rx_hook)(CAN_FIFOMailBox_TypeDef *to_push); +typedef int (*tx_hook)(CAN_FIFOMailBox_TypeDef *to_send); +typedef int (*tx_lin_hook)(int lin_num, uint8_t *data, int len); + +typedef struct { + safety_hook_init init; + rx_hook rx; + tx_hook tx; + tx_lin_hook tx_lin; +} safety_hooks; + +// This can be set by the safety hooks. +int controls_allowed = 0; + +// Include the actual safety policies. +#include "safety/safety_defaults.h" +#include "safety/safety_honda.h" +#include "safety/safety_toyota.h" +#include "safety/safety_elm327.h" + +const safety_hooks *current_hooks = &nooutput_hooks; + +void safety_rx_hook(CAN_FIFOMailBox_TypeDef *to_push){ + current_hooks->rx(to_push); +} + +int safety_tx_hook(CAN_FIFOMailBox_TypeDef *to_send) { + return current_hooks->tx(to_send); +} + +int safety_tx_lin_hook(int lin_num, uint8_t *data, int len){ + return current_hooks->tx_lin(lin_num, data, len); +} + +typedef struct { + uint16_t id; + const safety_hooks *hooks; +} safety_hook_config; + +#define SAFETY_NOOUTPUT 0 +#define SAFETY_HONDA 1 +#define SAFETY_TOYOTA 2 +#define SAFETY_TOYOTA_NOLIMITS 0x1336 +#define SAFETY_ALLOUTPUT 0x1337 +#define SAFETY_ELM327 0xE327 + +const safety_hook_config safety_hook_registry[] = { + {SAFETY_NOOUTPUT, &nooutput_hooks}, + {SAFETY_HONDA, &honda_hooks}, + {SAFETY_TOYOTA, &toyota_hooks}, + {SAFETY_TOYOTA_NOLIMITS, &toyota_nolimits_hooks}, + {SAFETY_ALLOUTPUT, &alloutput_hooks}, + {SAFETY_ELM327, &elm327_hooks}, +}; + +#define HOOK_CONFIG_COUNT (sizeof(safety_hook_registry)/sizeof(safety_hook_config)) + +int safety_set_mode(uint16_t mode) { + for (int i = 0; i < HOOK_CONFIG_COUNT; i++) { + if (safety_hook_registry[i].id == mode) { + current_hooks = safety_hook_registry[i].hooks; + if (current_hooks->init) current_hooks->init(); + return 0; + } + } + return -1; +} + diff --git a/board/safety/safety_defaults.h b/board/safety/safety_defaults.h new file mode 100644 index 0000000000..86155f32b9 --- /dev/null +++ b/board/safety/safety_defaults.h @@ -0,0 +1,44 @@ +void default_rx_hook(CAN_FIFOMailBox_TypeDef *to_push) {} + +// *** no output safety mode *** + +static void nooutput_init() { + controls_allowed = 0; +} + +static int nooutput_tx_hook(CAN_FIFOMailBox_TypeDef *to_send) { + return false; +} + +static int nooutput_tx_lin_hook(int lin_num, uint8_t *data, int len) { + return false; +} + +const safety_hooks nooutput_hooks = { + .init = nooutput_init, + .rx = default_rx_hook, + .tx = nooutput_tx_hook, + .tx_lin = nooutput_tx_lin_hook, +}; + +// *** all output safety mode *** + +static void alloutput_init() { + controls_allowed = 1; +} + +static int alloutput_tx_hook(CAN_FIFOMailBox_TypeDef *to_send) { + return true; +} + +static int alloutput_tx_lin_hook(int lin_num, uint8_t *data, int len) { + return true; +} + +const safety_hooks alloutput_hooks = { + .init = alloutput_init, + .rx = default_rx_hook, + .tx = alloutput_tx_hook, + .tx_lin = alloutput_tx_lin_hook, +}; + diff --git a/board/safety/safety_elm327.h b/board/safety/safety_elm327.h new file mode 100644 index 0000000000..ddacc27be0 --- /dev/null +++ b/board/safety/safety_elm327.h @@ -0,0 +1,39 @@ +static void elm327_rx_hook(CAN_FIFOMailBox_TypeDef *to_push) {} + +static int elm327_tx_hook(CAN_FIFOMailBox_TypeDef *to_send) { + //All ELM traffic must appear on CAN0 + if(((to_send->RDTR >> 4) & 0xf) != 0) return 0; + //All ISO 15765-4 messages must be 8 bytes long + if((to_send->RDTR & 0xf) != 8) return 0; + + if(to_send->RIR & 4){ + uint32_t addr = to_send->RIR >> 3; + //Check valid 29 bit send addresses for ISO 15765-4 + if(!(addr == 0x18DB33F1 || (addr & 0x1FFF00FF) == 0x18DA00F1)) return 0; + } else { + uint32_t addr = to_send->RIR >> 21; + //Check valid 11 bit send addresses for ISO 15765-4 + if(!(addr == 0x7DF || (addr & 0x7F8) == 0x7E0)) return 0; + } + + return true; +} + +static int elm327_tx_lin_hook(int lin_num, uint8_t *data, int len) { + if(lin_num != 0) return false; //Only operate on LIN 0, aka serial 2 + if(len < 5 || len > 11) return false; //Valid KWP size + if(!((data[0] & 0xF8) == 0xC0 && (data[0] & 0x07) > 0 && + data[1] == 0x33 && data[2] == 0xF1)) return false; //Bad msg + return true; +} + +static void elm327_init() { + controls_allowed = 1; +} + +const safety_hooks elm327_hooks = { + .init = elm327_init, + .rx = elm327_rx_hook, + .tx = elm327_tx_hook, + .tx_lin = elm327_tx_lin_hook, +}; diff --git a/board/safety/safety_honda.h b/board/safety/safety_honda.h new file mode 100644 index 0000000000..55ef003e5f --- /dev/null +++ b/board/safety/safety_honda.h @@ -0,0 +1,128 @@ +// board enforces +// in-state +// accel set/resume +// out-state +// cancel button +// accel rising edge +// brake rising edge +// brake > 0mph + +// these are set in the Honda safety hooks...this is the wrong place +int gas_interceptor_detected = 0; +int brake_prev = 0; +int gas_prev = 0; +int gas_interceptor_prev = 0; +int ego_speed = 0; + +static void honda_rx_hook(CAN_FIFOMailBox_TypeDef *to_push) { + + // sample speed + if ((to_push->RIR>>21) == 0x158) { + // first 2 bytes + ego_speed = to_push->RDLR & 0xFFFF; + } + + // state machine to enter and exit controls + // 0x1A6 for the ILX, 0x296 for the Civic Touring + if ((to_push->RIR>>21) == 0x1A6 || (to_push->RIR>>21) == 0x296) { + int buttons = (to_push->RDLR & 0xE0) >> 5; + if (buttons == 4 || buttons == 3) { + controls_allowed = 1; + } else if (buttons == 2) { + controls_allowed = 0; + } + } + + // exit controls on rising edge of brake press or on brake press when + // speed > 0 + if ((to_push->RIR>>21) == 0x17C) { + // bit 53 + int brake = to_push->RDHR & 0x200000; + if (brake && (!(brake_prev) || ego_speed)) { + controls_allowed = 0; + } + brake_prev = brake; + } + + // exit controls on rising edge of gas press if interceptor + if ((to_push->RIR>>21) == 0x201) { + gas_interceptor_detected = 1; + int gas_interceptor = ((to_push->RDLR & 0xFF) << 8) | ((to_push->RDLR & 0xFF00) >> 8); + if ((gas_interceptor > 328) && (gas_interceptor_prev <= 328)) { + controls_allowed = 0; + } + gas_interceptor_prev = gas_interceptor; + } + + // exit controls on rising edge of gas press if no interceptor + if (!gas_interceptor_detected) { + if ((to_push->RIR>>21) == 0x17C) { + int gas = to_push->RDLR & 0xFF; + if (gas && !(gas_prev)) { + controls_allowed = 0; + } + gas_prev = gas; + } + } +} + +// all commands: gas, brake and steering +// if controls_allowed and no pedals pressed +// allow all commands up to limit +// else +// block all commands that produce actuation + +static int honda_tx_hook(CAN_FIFOMailBox_TypeDef *to_send) { + + // disallow actuator commands if gas or brake (with vehicle moving) are pressed + // and the the latching controls_allowed flag is True + int pedal_pressed = gas_prev || gas_interceptor_prev || (brake_prev && ego_speed); + int current_controls_allowed = controls_allowed && !(pedal_pressed); + + // BRAKE: safety check + if ((to_send->RIR>>21) == 0x1FA) { + if (current_controls_allowed) { + if ((to_send->RDLR & 0xFFFFFF3F) != to_send->RDLR) return 0; + } else { + if ((to_send->RDLR & 0xFFFF0000) != to_send->RDLR) return 0; + } + } + + // STEER: safety check + if ((to_send->RIR>>21) == 0xE4 || (to_send->RIR>>21) == 0x194) { + if (current_controls_allowed) { + // all messages are fine here + } else { + if ((to_send->RDLR & 0xFFFF0000) != to_send->RDLR) return 0; + } + } + + // GAS: safety check + if ((to_send->RIR>>21) == 0x200) { + if (current_controls_allowed) { + // all messages are fine here + } else { + if ((to_send->RDLR & 0xFFFF0000) != to_send->RDLR) return 0; + } + } + + // 1 allows the message through + return true; +} + +static int honda_tx_lin_hook(int lin_num, uint8_t *data, int len) { + // TODO: add safety if using LIN + return true; +} + +static void honda_init() { + controls_allowed = 0; +} + +const safety_hooks honda_hooks = { + .init = honda_init, + .rx = honda_rx_hook, + .tx = honda_tx_hook, + .tx_lin = honda_tx_lin_hook, +}; + diff --git a/board/safety/safety_toyota.h b/board/safety/safety_toyota.h new file mode 100644 index 0000000000..0dab4b91cb --- /dev/null +++ b/board/safety/safety_toyota.h @@ -0,0 +1,179 @@ +// track the torque measured for limiting +int16_t torque_meas[3] = {0, 0, 0}; // last 3 motor torques produced by the eps +int16_t torque_meas_min = 0, torque_meas_max = 0; + +// global torque limit +const int32_t MAX_TORQUE = 1500; // max torque cmd allowed ever + +// rate based torque limit + stay within actually applied +// packet is sent at 100hz, so this limit is 1000/sec +const int32_t MAX_RATE_UP = 10; // ramp up slow +const int32_t MAX_RATE_DOWN = 25; // ramp down fast +const int32_t MAX_TORQUE_ERROR = 500; // max torque cmd in excess of torque motor + +// real time torque limit to prevent controls spamming +// the real time limit is 1500/sec +const int32_t MAX_RT_DELTA = 375; // max delta torque allowed for real time checks +const int32_t RT_INTERVAL = 250000; // 250ms between real time checks + +// longitudinal limits +const int16_t MAX_ACCEL = 1500; // 1.5 m/s2 +const int16_t MIN_ACCEL = -3000; // 3.0 m/s2 + +// global actuation limit state +int actuation_limits = 1; // by default steer limits are imposed + +// state of torque limits +int16_t desired_torque_last = 0; // last desired steer torque +int16_t rt_torque_last = 0; // last desired torque for real time check +uint32_t ts_last = 0; + +static void toyota_rx_hook(CAN_FIFOMailBox_TypeDef *to_push) { + // get eps motor torque (0.66 factor in dbc) + if ((to_push->RIR>>21) == 0x260) { + int16_t torque_meas_new = (((to_push->RDHR) & 0xFF00) | ((to_push->RDHR >> 16) & 0xFF)); + + // increase torque_meas by 1 to be conservative on rounding + torque_meas_new = (torque_meas_new / 3 + (torque_meas_new > 0 ? 1 : -1)) * 2; + + // shift the array + for (int i = sizeof(torque_meas)/sizeof(torque_meas[0]) - 1; i > 0; i--) { + torque_meas[i] = torque_meas[i-1]; + } + torque_meas[0] = torque_meas_new; + + // get the minimum and maximum measured torque over the last 3 frames + torque_meas_min = torque_meas_max = torque_meas[0]; + for (int i = 1; i < sizeof(torque_meas)/sizeof(torque_meas[0]); i++) { + if (torque_meas[i] < torque_meas_min) torque_meas_min = torque_meas[i]; + if (torque_meas[i] > torque_meas_max) torque_meas_max = torque_meas[i]; + } + } + + // exit controls on ACC off + if ((to_push->RIR>>21) == 0x1D2) { + // 4 bits: 55-52 + if (to_push->RDHR & 0xF00000) { + controls_allowed = 1; + } else { + controls_allowed = 0; + } + } +} + +static int toyota_tx_hook(CAN_FIFOMailBox_TypeDef *to_send) { + + // Check if msg is sent on BUS 0 + if (((to_send->RDTR >> 4) & 0xF) == 0) { + + // ACCEL: safety check on byte 1-2 + if ((to_send->RIR>>21) == 0x343) { + int16_t desired_accel = ((to_send->RDLR & 0xFF) << 8) | ((to_send->RDLR >> 8) & 0xFF); + if (controls_allowed && actuation_limits) { + if ((desired_accel > MAX_ACCEL) || (desired_accel < MIN_ACCEL)) { + return 0; + } + } else if (!controls_allowed && (desired_accel != 0)) { + return 0; + } + } + + // STEER: safety check on bytes 2-3 + if ((to_send->RIR>>21) == 0x2E4) { + int16_t desired_torque = (to_send->RDLR & 0xFF00) | ((to_send->RDLR >> 16) & 0xFF); + int16_t violation = 0; + + uint32_t ts = TIM2->CNT; + + // only check if controls are allowed and actuation_limits are imposed + if (controls_allowed && actuation_limits) { + + // *** global torque limit check *** + if (desired_torque < -MAX_TORQUE) violation = 1; + if (desired_torque > MAX_TORQUE) violation = 1; + + + // *** torque rate limit check *** + int16_t highest_allowed_torque = max(desired_torque_last, 0) + MAX_RATE_UP; + int16_t lowest_allowed_torque = min(desired_torque_last, 0) - MAX_RATE_UP; + + // if we've exceeded the applied torque, we must start moving toward 0 + highest_allowed_torque = min(highest_allowed_torque, max(desired_torque_last - MAX_RATE_DOWN, max(torque_meas_max, 0) + MAX_TORQUE_ERROR)); + lowest_allowed_torque = max(lowest_allowed_torque, min(desired_torque_last + MAX_RATE_DOWN, min(torque_meas_min, 0) - MAX_TORQUE_ERROR)); + + // check for violation + if ((desired_torque < lowest_allowed_torque) || (desired_torque > highest_allowed_torque)) { + violation = 1; + } + + // used next time + desired_torque_last = desired_torque; + + + // *** torque real time rate limit check *** + int16_t highest_rt_torque = max(rt_torque_last, 0) + MAX_RT_DELTA; + int16_t lowest_rt_torque = min(rt_torque_last, 0) - MAX_RT_DELTA; + + // check for violation + if ((desired_torque < lowest_rt_torque) || (desired_torque > highest_rt_torque)) { + violation = 1; + } + + // every RT_INTERVAL set the new limits + uint32_t ts_elapsed = ts > ts_last ? ts - ts_last : (0xFFFFFFFF - ts_last) + 1 + ts; + if (ts_elapsed > RT_INTERVAL) { + rt_torque_last = desired_torque; + ts_last = ts; + } + } + + // no torque if controls is not allowed + if (!controls_allowed && (desired_torque != 0)) { + violation = 1; + } + + // reset to 0 if either controls is not allowed or there's a violation + if (violation || !controls_allowed) { + desired_torque_last = 0; + rt_torque_last = 0; + ts_last = ts; + } + + if (violation) { + return false; + } + } + } + + // 1 allows the message through + return true; +} + +static int toyota_tx_lin_hook(int lin_num, uint8_t *data, int len) { + // TODO: add safety if using LIN + return true; +} + +static void toyota_init() { + controls_allowed = 0; + actuation_limits = 1; +} + +const safety_hooks toyota_hooks = { + .init = toyota_init, + .rx = toyota_rx_hook, + .tx = toyota_tx_hook, + .tx_lin = toyota_tx_lin_hook, +}; + +static void toyota_nolimits_init() { + controls_allowed = 0; + actuation_limits = 0; +} + +const safety_hooks toyota_nolimits_hooks = { + .init = toyota_nolimits_init, + .rx = toyota_rx_hook, + .tx = toyota_tx_hook, + .tx_lin = toyota_tx_lin_hook, +}; diff --git a/board/spi_flasher.h b/board/spi_flasher.h new file mode 100644 index 0000000000..5d979a09d2 --- /dev/null +++ b/board/spi_flasher.h @@ -0,0 +1,186 @@ +// flasher state variables +uint32_t *prog_ptr = NULL; +int unlocked = 0; + +void debug_ring_callback(uart_ring *ring) {} + +int usb_cb_control_msg(USB_Setup_TypeDef *setup, uint8_t *resp, int hardwired) { + int resp_len = 0; + + // flasher machine + memset(resp, 0, 4); + memcpy(resp+4, "\xde\xad\xd0\x0d", 4); + resp[0] = 0xff; + resp[2] = setup->b.bRequest; + resp[3] = ~setup->b.bRequest; + *((uint32_t **)&resp[8]) = prog_ptr; + resp_len = 0xc; + + int sec; + switch (setup->b.bRequest) { + // **** 0xb0: flasher echo + case 0xb0: + resp[1] = 0xff; + break; + // **** 0xb1: unlock flash + case 0xb1: + if (FLASH->CR & FLASH_CR_LOCK) { + FLASH->KEYR = 0x45670123; + FLASH->KEYR = 0xCDEF89AB; + resp[1] = 0xff; + } + set_led(LED_GREEN, 1); + unlocked = 1; + prog_ptr = (uint32_t *)0x8004000; + break; + // **** 0xb2: erase sector + case 0xb2: + sec = setup->b.wValue.w; + // don't erase the bootloader + if (sec != 0 && sec < 12 && unlocked) { + FLASH->CR = (sec << 3) | FLASH_CR_SER; + FLASH->CR |= FLASH_CR_STRT; + while (FLASH->SR & FLASH_SR_BSY); + resp[1] = 0xff; + } + break; + // **** 0xd0: fetch serial number + case 0xd0: + #ifdef PANDA + // addresses are OTP + if (setup->b.wValue.w == 1) { + memcpy(resp, (void *)0x1fff79c0, 0x10); + resp_len = 0x10; + } else { + get_provision_chunk(resp); + resp_len = PROVISION_CHUNK_LEN; + } + #endif + break; + // **** 0xd1: enter bootloader mode + case 0xd1: + // this allows reflashing of the bootstub + // so it's blocked over wifi + switch (setup->b.wValue.w) { + case 0: + if (hardwired) { + puts("-> entering bootloader\n"); + enter_bootloader_mode = ENTER_BOOTLOADER_MAGIC; + NVIC_SystemReset(); + } + break; + case 1: + puts("-> entering softloader\n"); + enter_bootloader_mode = ENTER_SOFTLOADER_MAGIC; + NVIC_SystemReset(); + break; + } + break; + // **** 0xd6: get version + case 0xd6: + COMPILE_TIME_ASSERT(sizeof(gitversion) <= MAX_RESP_LEN) + memcpy(resp, gitversion, sizeof(gitversion)); + resp_len = sizeof(gitversion); + break; + // **** 0xd8: reset ST + case 0xd8: + NVIC_SystemReset(); + break; + } + return resp_len; +} + +int usb_cb_ep1_in(uint8_t *usbdata, int len, int hardwired) { return 0; } +void usb_cb_ep3_out(uint8_t *usbdata, int len, int hardwired) { } + +int is_enumerated = 0; +void usb_cb_enumeration_complete() { + puts("USB enumeration complete\n"); + is_enumerated = 1; +} + +void usb_cb_ep2_out(uint8_t *usbdata, int len, int hardwired) { + set_led(LED_RED, 0); + for (int i = 0; i < len/4; i++) { + // program byte 1 + FLASH->CR = FLASH_CR_PSIZE_1 | FLASH_CR_PG; + + *prog_ptr = *(uint32_t*)(usbdata+(i*4)); + while (FLASH->SR & FLASH_SR_BSY); + + //*(uint64_t*)(&spi_tx_buf[0x30+(i*4)]) = *prog_ptr; + prog_ptr++; + } + set_led(LED_RED, 1); +} + + +int spi_cb_rx(uint8_t *data, int len, uint8_t *data_out) { + int resp_len = 0; + switch (data[0]) { + case 0: + // control transfer + resp_len = usb_cb_control_msg((USB_Setup_TypeDef *)(data+4), data_out, 0); + break; + case 2: + // ep 2, flash! + usb_cb_ep2_out(data+4, data[2], 0); + break; + } + return resp_len; +} + +void soft_flasher_start() { + puts("\n\n\n************************ FLASHER START ************************\n"); + + enter_bootloader_mode = 0; + + RCC->AHB1ENR |= RCC_AHB1ENR_DMA2EN; + RCC->APB2ENR |= RCC_APB2ENR_SPI1EN; + RCC->AHB2ENR |= RCC_AHB2ENR_OTGFSEN; + RCC->APB1ENR |= RCC_APB1ENR_USART2EN; + + // A4,A5,A6,A7: setup SPI + set_gpio_alternate(GPIOA, 4, GPIO_AF5_SPI1); + set_gpio_alternate(GPIOA, 5, GPIO_AF5_SPI1); + set_gpio_alternate(GPIOA, 6, GPIO_AF5_SPI1); + set_gpio_alternate(GPIOA, 7, GPIO_AF5_SPI1); + + // A2,A3: USART 2 for debugging + set_gpio_alternate(GPIOA, 2, GPIO_AF7_USART2); + set_gpio_alternate(GPIOA, 3, GPIO_AF7_USART2); + + // A11,A12: USB + set_gpio_alternate(GPIOA, 11, GPIO_AF10_OTG_FS); + set_gpio_alternate(GPIOA, 12, GPIO_AF10_OTG_FS); + GPIOA->OSPEEDR = GPIO_OSPEEDER_OSPEEDR11 | GPIO_OSPEEDER_OSPEEDR12; + + // flasher + spi_init(); + + // enable USB + usb_init(); + + // green LED on for flashing + set_led(LED_GREEN, 1); + + __enable_irq(); + + uint64_t cnt = 0; + + for (cnt=0;;cnt++) { + if (cnt == 35 && !is_enumerated && usb_power_mode == USB_POWER_CLIENT) { + // if you are connected through a hub to the phone + // you need power to be able to see the device + puts("USBP: didn't enumerate, switching to CDP mode\n"); + set_usb_power_mode(USB_POWER_CDP); + set_led(LED_BLUE, 1); + } + // blink the green LED fast + set_led(LED_GREEN, 0); + delay(500000); + set_led(LED_GREEN, 1); + delay(500000); + } +} + diff --git a/board/startup_stm32f205xx.s b/board/startup_stm32f205xx.s new file mode 100644 index 0000000000..f4b6c6cb74 --- /dev/null +++ b/board/startup_stm32f205xx.s @@ -0,0 +1,511 @@ +/** + ****************************************************************************** + * @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/startup_stm32f413xx.s b/board/startup_stm32f413xx.s new file mode 100644 index 0000000000..00b645d11b --- /dev/null +++ b/board/startup_stm32f413xx.s @@ -0,0 +1,583 @@ +/** + ****************************************************************************** + * @file startup_stm32f413xx.s + * @author MCD Application Team + * @version V2.6.0 + * @date 04-November-2016 + * @brief STM32F413xx Devices vector table for GCC based toolchains. + * 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-M4 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-m4 + .fpu softvfp + .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 intitialization 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, DAC1 and DAC2 */ + .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 DFSDM1_FLT0_IRQHandler /* DFSDM1 Filter0 */ + .word DFSDM1_FLT1_IRQHandler /* DFSDM1 Filter1 */ + .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 CAN3_TX_IRQHandler /* CAN3 TX */ + .word CAN3_RX0_IRQHandler /* CAN3 RX0 */ + .word CAN3_RX1_IRQHandler /* CAN3 RX1 */ + .word CAN3_SCE_IRQHandler /* CAN3 SCE */ + .word 0 /* Reserved */ + .word 0 /* Reserved */ + .word RNG_IRQHandler /* RNG */ + .word FPU_IRQHandler /* FPU */ + .word UART7_IRQHandler /* UART7 */ + .word UART8_IRQHandler /* UART8 */ + .word SPI4_IRQHandler /* SPI4 */ + .word SPI5_IRQHandler /* SPI5 */ + .word 0 /* Reserved */ + .word SAI1_IRQHandler /* SAI1 */ + .word UART9_IRQHandler /* UART9 */ + .word UART10_IRQHandler /* UART10 */ + .word 0 /* Reserved */ + .word 0 /* Reserved */ + .word QUADSPI_IRQHandler /* QuadSPI */ + .word 0 /* Reserved */ + .word 0 /* Reserved */ + .word FMPI2C1_EV_IRQHandler /* FMPI2C1 Event */ + .word FMPI2C1_ER_IRQHandler /* FMPI2C1 Error */ + .word LPTIM1_IRQHandler /* LPTIM1 */ + .word DFSDM2_FLT0_IRQHandler /* DFSDM2 Filter0 */ + .word DFSDM2_FLT1_IRQHandler /* DFSDM2 Filter1 */ + .word DFSDM2_FLT2_IRQHandler /* DFSDM2 Filter2 */ + .word DFSDM2_FLT3_IRQHandler /* DFSDM2 Filter3 */ + +/******************************************************************************* +* +* 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 DFSDM1_FLT0_IRQHandler + .thumb_set DFSDM1_FLT0_IRQHandler,Default_Handler + + .weak DFSDM1_FLT1_IRQHandler + .thumb_set DFSDM1_FLT1_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 CAN3_TX_IRQHandler + .thumb_set CAN3_TX_IRQHandler,Default_Handler + + .weak CAN3_RX0_IRQHandler + .thumb_set CAN3_RX0_IRQHandler,Default_Handler + + .weak CAN3_RX1_IRQHandler + .thumb_set CAN3_RX1_IRQHandler,Default_Handler + + .weak CAN3_SCE_IRQHandler + .thumb_set CAN3_SCE_IRQHandler,Default_Handler + + .weak RNG_IRQHandler + .thumb_set RNG_IRQHandler,Default_Handler + + .weak FPU_IRQHandler + .thumb_set FPU_IRQHandler,Default_Handler + + .weak UART7_IRQHandler + .thumb_set UART7_IRQHandler,Default_Handler + + .weak UART8_IRQHandler + .thumb_set UART8_IRQHandler,Default_Handler + + .weak SPI4_IRQHandler + .thumb_set SPI4_IRQHandler,Default_Handler + + .weak SPI5_IRQHandler + .thumb_set SPI5_IRQHandler,Default_Handler + + .weak SAI1_IRQHandler + .thumb_set SAI1_IRQHandler,Default_Handler + + .weak UART9_IRQHandler + .thumb_set UART9_IRQHandler,Default_Handler + + .weak UART10_IRQHandler + .thumb_set UART10_IRQHandler,Default_Handler + + .weak QUADSPI_IRQHandler + .thumb_set QUADSPI_IRQHandler,Default_Handler + + .weak FMPI2C1_EV_IRQHandler + .thumb_set FMPI2C1_EV_IRQHandler,Default_Handler + + .weak FMPI2C1_ER_IRQHandler + .thumb_set FMPI2C1_ER_IRQHandler,Default_Handler + + .weak LPTIM1_IRQHandler + .thumb_set LPTIM1_IRQHandler,Default_Handler + + .weak DFSDM2_FLT0_IRQHandler + .thumb_set DFSDM2_FLT0_IRQHandler,Default_Handler + + .weak DFSDM2_FLT1_IRQHandler + .thumb_set DFSDM2_FLT1_IRQHandler,Default_Handler + + .weak DFSDM2_FLT2_IRQHandler + .thumb_set DFSDM2_FLT2_IRQHandler,Default_Handler + + .weak DFSDM2_FLT3_IRQHandler + .thumb_set DFSDM2_FLT3_IRQHandler,Default_Handler +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/board/stm32_flash.ld b/board/stm32_flash.ld new file mode 100644 index 0000000000..500319377e --- /dev/null +++ b/board/stm32_flash.ld @@ -0,0 +1,165 @@ +/* +***************************************************************************** +** +** File : stm32_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 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) } +} diff --git a/board/tests/test_rsa.c b/board/tests/test_rsa.c new file mode 100644 index 0000000000..f4a7d6be0f --- /dev/null +++ b/board/tests/test_rsa.c @@ -0,0 +1,35 @@ +/* +gcc -DTEST_RSA test_rsa.c ../crypto/rsa.c ../crypto/sha.c && ./a.out +*/ + +#include +#include + +#define MAX_LEN 0x40000 +char buf[MAX_LEN]; + +#include "../crypto/sha.h" +#include "../crypto/rsa.h" +#include "../obj/cert.h" + +int main() { + FILE *f = fopen("../obj/panda.bin", "rb"); + int tlen = fread(buf, 1, MAX_LEN, f); + fclose(f); + printf("read %d\n", tlen); + uint32_t *_app_start = (uint32_t *)buf; + + int len = _app_start[0]; + char digest[SHA_DIGEST_SIZE]; + SHA_hash(&_app_start[1], len-4, digest); + printf("SHA hash done\n"); + + if (!RSA_verify(&rsa_key, ((void*)&_app_start[0]) + len, RSANUMBYTES, digest, SHA_DIGEST_SIZE)) { + printf("RSA fail\n"); + } else { + printf("RSA match!!!\n"); + } + + return 0; +} + diff --git a/board/tools/dfu-util-aarch64 b/board/tools/dfu-util-aarch64 new file mode 100755 index 0000000000..73836c3598 --- /dev/null +++ b/board/tools/dfu-util-aarch64 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:76a07bd598aacbfbc81b95b9b33ef1282fedfe6e49819179445a457c4982a979 +size 116048 diff --git a/board/tools/dfu-util-aarch64-linux b/board/tools/dfu-util-aarch64-linux new file mode 100755 index 0000000000..81681471dd --- /dev/null +++ b/board/tools/dfu-util-aarch64-linux @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ea03146271626a42997a38a0c2d53000b7c788347bb7ead973b7aeb652168bae +size 159256 diff --git a/board/tools/dfu-util-x86_64-linux b/board/tools/dfu-util-x86_64-linux new file mode 100755 index 0000000000..2167cdf686 --- /dev/null +++ b/board/tools/dfu-util-x86_64-linux @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d33372170341cf50a79ec72e6c0dca51d6116c73203beaaf307c729d2753d178 +size 152156 diff --git a/board/tools/enter_download_mode.py b/board/tools/enter_download_mode.py new file mode 100755 index 0000000000..ff3cf84ca9 --- /dev/null +++ b/board/tools/enter_download_mode.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python +from __future__ import print_function + +import sys +import time +import usb1 + +def enter_download_mode(device): + handle = device.open() + handle.claimInterface(0) + + try: + handle.controlWrite(usb1.TYPE_VENDOR | usb1.RECIPIENT_DEVICE, 0xd1, 0, 0, b'') + except (usb1.USBErrorIO, usb1.USBErrorPipe) as e: + print("Device download mode enabled.") + time.sleep(1) + else: + print("Device failed to enter download mode.") + sys.exit(1) + +def find_first_panda(context=None): + context = context or usb1.USBContext() + for device in context.getDeviceList(skip_on_error=True): + if device.getVendorID() == 0xbbaa and device.getProductID()&0xFF00 == 0xdd00: + return device + +if __name__ == "__main__": + panda_dev = find_first_panda() + if panda_dev == None: + print("no device found") + sys.exit(0) + print("found device") + enter_download_mode(panda_dev) diff --git a/boardesp/.gitignore b/boardesp/.gitignore new file mode 100644 index 0000000000..75255a5851 --- /dev/null +++ b/boardesp/.gitignore @@ -0,0 +1,8 @@ +proxy +*.bin +esp-open-sdk +a.out +cert.h +gitversion.h +esp-open-sdk.dmg +obj/* diff --git a/boardesp/ELM327.md b/boardesp/ELM327.md new file mode 100644 index 0000000000..6453b35ca4 --- /dev/null +++ b/boardesp/ELM327.md @@ -0,0 +1,101 @@ +ELM327 support for panda +====== +The panda now has basic ELM327 support. + +### What is ELM327? + +ELM327 is a command protocol for interfacing with cars using an OBD-II +port to read [list](standard vehicle diagnostic codes). ELM327 +originally referred to a line of programmable microcontrollers that +implemented the ELM327 command protocol, and are still being +developed. + +ELM327 devices present a shell and commands are sent via a UART. The +official ELM327 chips only support raw UART communication, but most +devices built with the ELM327 devices (official or clones) expose the +UART in a more modern way (Wifi, USB, etc). + +Mechanics use ELM to diagnose vehicles, and reset fault codes in the +car's computer after fixing the issue (turning off the dreaded check +engine light). Car owners can use ELM devices to perform the same +diagnostics in their garage using either a raw terminal to send +commands to the ELM device directly, or using a GUI (like one of +several popular smart phone apps) to translate the OBD error codes +into readable messages. These GUIs also often allow monitoring of the +performance of the car's speed, engine rpm, etc. + +The panda natively supports sending all the important OBD diagnostic +messages, but ELM327 support removes the need for the user to manually +craft CAN or LIN packets using the native panda API, and grants +compatibility with many existing tools. + +[Wikipedia](https://en.wikipedia.org/wiki/ELM327) can provide +additional information. + +### OBD Protocols? + +While the commands that the OBD standard describe are in fact +standard, there are several different protocols that those messages +can be sent and received with. All cars after 1991 support one of +these protocols. Which one depends on the car's year and country, as +legal requirements change over the years. + +The panda supports the most popular/modern of these protocols, and all +but two can be added as needed. Below is a chart of the OBD-II +protocols supported by the panda. + +| Protocol | Support Status | +| --- | --- | +| SAE J1850 PWM (41.6 kbit/s) | Never/Obsolete | +| SAE J1850 VPW (10.4 kbit/s) | Never/Obsolete | +| ISO 9141-2 (5 baud init, 10.4 kbit/s) | Unsupported | +| ISO 14230-4 KWP (5 baud init, 10.4 kbit/s) | Unsupported | +| ISO 14230-4 KWP (fast init, 10.4 kbit/s) | Supported | +| ISO 15765-4 CAN (11 bit ID, 500 kbit/s) | Supported | +| ISO 15765-4 CAN (29 bit ID, 500 kbit/s) | Supported | +| ISO 15765-4 CAN (11 bit ID, 250 kbit/s) | Supported | +| ISO 15765-4 CAN (29 bit ID, 250 kbit/s) | Supported | +| SAE J1939 (250kbps) | Unsupported | + +### The Implementation + +The panda ELM327 implementation is not a full implementation of all +the features of the official ELM327 microcontroller. Like most ELM327 +clones, the panda reports its ELM version as the unreleased version +1.5, despite only implementing commands from protocol version 1.0. + + +### Testing + +These tests require two pandas. One to be tested, and the second to +simulate the vehicle. + +The panda used to simulate the vehicle must be plugged into a USB port +of the testing computer. + +The computer running the tests must be connected to the panda being +tested's wifi network. + +The following command will run the tests (nosetest should work fine +instead of pytest if you still prefer using that). The CANSIMSERIAL +environment variable will force the car simulator to use the correct +panda as the simulator if multiple pandas are attached via usb to the +host computer. + +``` +CANSIMSERIAL=car_sim_panda_serial pytest tests/automated/elm_wifi.py +``` + +A single test can be run by putting the test name after the file name +and two colons, like so: + +``` +CANSIMSERIAL=car_sim_panda_serial pytest tests/automated/elm_wifi.py::test_important_thing +``` + +For more detail, provide the -s (show output) and the -vv (very +verbose) flags. + +``` +CANSIMSERIAL=car_sim_panda_serial pytest -s -vv tests/automated/elm_wifi.py +``` diff --git a/boardesp/Makefile b/boardesp/Makefile new file mode 100644 index 0000000000..0b8fe32b69 --- /dev/null +++ b/boardesp/Makefile @@ -0,0 +1,74 @@ +PATH := esp-open-sdk/xtensa-lx106-elf/bin:$(PATH) +CC = esp-open-sdk/xtensa-lx106-elf/bin/xtensa-lx106-elf-gcc +CFLAGS = -Iinclude/ -I. -I../ -mlongcalls -Iesp-open-sdk/ESP8266_NONOS_SDK_V1.5.4_16_05_20/driver_lib/include -std=c99 -DICACHE_FLASH +LDLIBS = -nostdlib -Wl,--start-group -lmain -lnet80211 -lwpa -llwip -lpp -lphy -Wl,--end-group -lgcc -ldriver -Wl,--gc-sections +LDFLAGS = -Teagle.app.v6.ld +OBJCP = esp-open-sdk/xtensa-lx106-elf/bin/xtensa-lx106-elf-objcopy +SDK_BASE = esp-open-sdk/ESP8266_NONOS_SDK_V1.5.4_16_05_20 + +ifeq ($(RELEASE),1) + CERT = ../../pandaextra/certs/releaseesp +else + CERT = ../certs/debugesp + CFLAGS += "-DALLOW_DEBUG" +endif + +flashall: user1.bin user2.bin + ../python/esptool.py write_flash 0 $(SDK_BASE)/bin/boot_v1.5.bin 0x01000 user1.bin 0x81000 user2.bin 0x3FE000 $(SDK_BASE)/bin/blank.bin + +proxy-0x00000.bin: proxy + ../python/esptool.py elf2image $^ + +proxy: proxy.o elm327.o webserver.o sha.o + +obj/proxy.o: proxy.c + $(CC) $(CFLAGS) -c $^ -o $@ + +obj/elm327.o: elm327.c + $(CC) $(CFLAGS) -c $^ -o $@ + +obj/webserver.o: webserver.c obj/cert.h obj/gitversion.h + $(CC) $(CFLAGS) -c $< -o $@ + +obj/cert.h: ../crypto/getcertheader.py + ../crypto/getcertheader.py ../certs/debugesp.pub ../certs/releaseesp.pub > obj/cert.h + +include ../common/version.mk + +obj/sha.o: ../crypto/sha.c + $(CC) $(CFLAGS) -c $^ -o $@ + +obj/rsa.o: ../crypto/rsa.c + $(CC) $(CFLAGS) -c $^ -o $@ + +oldflash: proxy-0x00000.bin + ../python/esptool.py write_flash 0 proxy-0x00000.bin 0x40000 proxy-0x40000.bin + +user1.bin: obj/proxy.o obj/elm327.o obj/webserver.o obj/sha.o obj/rsa.o + $(CC) $(CFLAGS) $^ -o a.out -L$(SDK_BASE)/ld -T$(SDK_BASE)/ld/eagle.app.v6.new.1024.app1.ld $(LDLIBS) + $(OBJCP) --only-section .text -O binary a.out eagle.app.v6.text.bin + $(OBJCP) --only-section .data -O binary a.out eagle.app.v6.data.bin + $(OBJCP) --only-section .rodata -O binary a.out eagle.app.v6.rodata.bin + $(OBJCP) --only-section .irom0.text -O binary a.out eagle.app.v6.irom0text.bin + COMPILE=gcc python ./esp-open-sdk/ESP8266_NONOS_SDK_V1.5.4_16_05_20/tools/gen_appbin.py a.out 2 0 32 4 0 + rm -f eagle.app.v6.*.bin + mv eagle.app.flash.bin $@ + ../crypto/sign.py $@ $@ $(CERT) + +user2.bin: obj/proxy.o obj/elm327.o obj/webserver.o obj/sha.o obj/rsa.o + $(CC) $(CFLAGS) $^ -o a.out -L$(SDK_BASE)/ld -T$(SDK_BASE)/ld/eagle.app.v6.new.1024.app2.ld $(LDLIBS) + $(OBJCP) --only-section .text -O binary a.out eagle.app.v6.text.bin + $(OBJCP) --only-section .data -O binary a.out eagle.app.v6.data.bin + $(OBJCP) --only-section .rodata -O binary a.out eagle.app.v6.rodata.bin + $(OBJCP) --only-section .irom0.text -O binary a.out eagle.app.v6.irom0text.bin + COMPILE=gcc python ./esp-open-sdk/ESP8266_NONOS_SDK_V1.5.4_16_05_20/tools/gen_appbin.py a.out 2 0 32 4 0 + rm -f eagle.app.v6.*.bin + mv eagle.app.flash.bin $@ + ../crypto/sign.py $@ $@ $(CERT) + +ota: user1.bin user2.bin + curl http://192.168.0.10/espupdate1 --upload-file user1.bin + curl http://192.168.0.10/espupdate2 --upload-file user2.bin + +clean: + rm -f proxy proxy.o proxy-0x00000.bin proxy-0x40000.bin eagle.app.* user1.bin user2.bin a.out obj/* diff --git a/boardesp/README.md b/boardesp/README.md new file mode 100644 index 0000000000..9b15ef2351 --- /dev/null +++ b/boardesp/README.md @@ -0,0 +1,22 @@ + +Dependencies +----- + +**Mac** + +``` +./get_sdk.sh +``` + +**Debian / Ubuntu** + +``` +./get_sdk_mac.sh +``` + +Programming +----- + +``` +make +``` diff --git a/boardesp/elm327.c b/boardesp/elm327.c new file mode 100644 index 0000000000..993dc8460a --- /dev/null +++ b/boardesp/elm327.c @@ -0,0 +1,1576 @@ +#include "ets_sys.h" +#include "osapi.h" +#include "gpio.h" +#include "os_type.h" +#include "user_interface.h" +#include "espconn.h" +#include "mem.h" + +#include "driver/uart.h" + +//#define ELM_DEBUG + +#define min(a,b) ((a) < (b) ? (a) : (b)) +#define max(a,b) ((a) > (b) ? (a) : (b)) +int ICACHE_FLASH_ATTR spi_comm(char *dat, int len, uint32_t *recvData, int recvDataLen); + +#define ELM_PORT 35000 + +//Version 1.5 is an invalid version used by many pirate clones +//that only partially support 1.0. +#define IDENT_MSG "ELM327 v1.5\r\r" +#define DEVICE_DESC "Panda\n\n" + +#define SHOW_CONNECTION(msg, p_conn) os_printf("%s %p, proto %p, %d.%d.%d.%d:%d disconnect\r\n", \ + msg, p_conn, (p_conn)->proto.tcp, (p_conn)->proto.tcp->remote_ip[0], \ + (p_conn)->proto.tcp->remote_ip[1], (p_conn)->proto.tcp->remote_ip[2], \ + (p_conn)->proto.tcp->remote_ip[3], (p_conn)->proto.tcp->remote_port) + +const static char hex_lookup[] = {'0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; + +typedef struct __attribute__((packed)) { + bool tx : 1; + bool : 1; + bool ext : 1; + uint32_t addr : 29; + + uint8_t len : 4; + uint8_t bus : 8; + uint8_t : 4; //unused + uint16_t ts : 16; + uint8_t data[8]; +} panda_can_msg_t; + +//TODO: Masking is likely unnecessary for these bit fields. Check. +#define panda_get_can_addr(recv) (((recv)->ext) ? ((recv)->addr & 0x1FFFFFFF) :\ + (((recv)->addr >> 18) & 0x7FF)) + +#define PANDA_CAN_FLAG_TRANSMIT 1 +#define PANDA_CAN_FLAG_EXTENDED 4 + +#define PANDA_USB_CAN_WRITE_BUS_NUM 3 +#define PANDA_USB_LIN_WRITE_BUS_NUM 2 + +typedef struct _elm_tcp_conn { + struct espconn *conn; + struct _elm_tcp_conn *next; +} elm_tcp_conn_t; + +typedef struct __attribute__((packed)) { + uint8_t len; + uint8_t dat[7]; //mode and data +} elm_can_obd_msg; + +typedef struct __attribute__((packed)) { + uint8_t priority; + uint8_t receiver; + uint8_t sender; + + uint8_t dat[8]; //mode, data, and checksum +} elm_lin_obd_msg; + +typedef struct __attribute__((packed)) { + uint16_t usb_ep_num; + uint16_t payload_len; + + uint8_t serial_port; + //uint8_t msg[8+3]; + elm_lin_obd_msg msg; +} elm_lin_usb_msg; + +static struct espconn elm_conn; +static esp_tcp elm_proto; +static elm_tcp_conn_t *connection_list = NULL; + +static char stripped_msg[0x100]; +static uint16 stripped_msg_len = 0; + +static char in_msg[0x100]; +static uint16 in_msg_len = 0; + +static char rsp_buff[536]; //TCP min MTU +static uint16 rsp_buff_len = 0; + +static uint8_t pandaSendData[0x14] = {0}; +static uint32_t pandaRecvData[0x40] = {0}; +static uint32_t pandaRecvDataDummy[0x40] = {0}; // Used for CAN write operations (no received data) + +#define ELM_MODE_SELECTED_PROTOCOL_DEFAULT 6 +#define ELM_MODE_TIMEOUT_DEFAULT 20; +#define ELM_MODE_KEEPALIVE_PERIOD_DEFAULT (0x92*20) + +static bool elm_mode_echo = true; +static bool elm_mode_linefeed = false; +static bool elm_mode_additional_headers = false; +static bool elm_mode_auto_protocol = true; +static uint8_t elm_selected_protocol = ELM_MODE_SELECTED_PROTOCOL_DEFAULT; +static bool elm_mode_print_spaces = true; +static uint8_t elm_mode_adaptive_timing = 1; +static bool elm_mode_allow_long = false; +static uint16_t elm_mode_timeout = ELM_MODE_TIMEOUT_DEFAULT; +static uint16_t elm_mode_keepalive_period = ELM_MODE_KEEPALIVE_PERIOD_DEFAULT; + +bool lin_bus_initialized = false; + +/*********************************************** + *** ELM CLI response functions *** + *** (for sending data back to the terminal) *** + ***********************************************/ + +// All ELM operations are global, so send data out to all connections +void ICACHE_FLASH_ATTR elm_tcp_tx_flush() { + if(!rsp_buff_len) return; // Was causing small error messages + + for(elm_tcp_conn_t *iter = connection_list; iter != NULL; iter = iter->next){ + int8_t err = espconn_send(iter->conn, rsp_buff, rsp_buff_len); + if(err){ + os_printf(" Wifi %p TX error code %d\n", iter->conn, err); + if(err == ESPCONN_ARG) { + if(iter == connection_list) { + connection_list = iter->next; + } else { + for(elm_tcp_conn_t *iter2 = connection_list; iter2 != NULL; iter2 = iter2->next) + if(iter2->next == iter) { + iter2->next = iter->next; + break; + } + } + os_printf(" deleting orphaned connection. iter: %p; conn: %p\n", iter, iter->conn); + os_free(iter); + } + } + } + rsp_buff_len = 0; +} + +static void ICACHE_FLASH_ATTR elm_append_rsp(const char *data, uint16_t len) { + uint16_t overflow_len = 0; + if(rsp_buff_len + len > sizeof(rsp_buff)) { + overflow_len = rsp_buff_len + len - sizeof(rsp_buff); + len = sizeof(rsp_buff) - rsp_buff_len; + } + if(!elm_mode_linefeed) { + memcpy(rsp_buff + rsp_buff_len, data, len); + rsp_buff_len += len; + } else { + for(int i=0; i < len && rsp_buff_len < sizeof(rsp_buff); i++){ + rsp_buff[rsp_buff_len++] = data[i]; + if(data[i] == '\r' && rsp_buff_len < sizeof(rsp_buff)) + rsp_buff[rsp_buff_len++] = '\n'; + } + } + if(overflow_len) { + os_printf("Packet full, sending\n"); + elm_tcp_tx_flush(); + elm_append_rsp(data + len, overflow_len); + } +} + +#define elm_append_rsp_const(str) elm_append_rsp(str, sizeof(str)-1) + +static void ICACHE_FLASH_ATTR elm_append_rsp_hex_byte(uint8_t num) { + elm_append_rsp(&hex_lookup[num >> 4], 1); + elm_append_rsp(&hex_lookup[num & 0xF], 1); + if(elm_mode_print_spaces) elm_append_rsp_const(" "); +} + +void ICACHE_FLASH_ATTR elm_append_rsp_can_msg_addr(const panda_can_msg_t *recv) { + //Show address + uint32_t addr = panda_get_can_addr(recv); + if(recv->ext){ + elm_append_rsp_hex_byte(addr>>24); + elm_append_rsp_hex_byte(addr>>16); + elm_append_rsp_hex_byte(addr>>8); + elm_append_rsp_hex_byte(addr); + } else { + elm_append_rsp(&hex_lookup[addr>>8], 1); + elm_append_rsp_hex_byte(addr); + } +} + +/*************************************** + *** Panda communication functions *** + *** (for controlling the Panda MCU) *** + ***************************************/ + +static int ICACHE_FLASH_ATTR panda_usbemu_ctrl_write(uint8_t request_type, uint8_t request, + uint16_t value, uint16_t index, uint16_t length) { + //self.sock.send(struct.pack("HHBBHHH", 0, 0, request_type, request, value, index, length)); + *(uint16_t*)(pandaSendData) = 0; + *(uint16_t*)(pandaSendData+2) = 0; + pandaSendData[4] = request_type; + pandaSendData[5] = request; + *(uint16_t*)(pandaSendData+6) = value; + *(uint16_t*)(pandaSendData+8) = index; + *(uint16_t*)(pandaSendData+10) = length; + + int returned_count = spi_comm(pandaSendData, 0x10, pandaRecvData, 0x40); + if(returned_count > 0x40 || returned_count < 0) + return -1; + return returned_count; +} + +#define panda_set_can0_cbaud(cbps) panda_usbemu_ctrl_write(0x40, 0xde, 0, cbps, 0) +#define panda_set_can0_kbaud(kbps) panda_usbemu_ctrl_write(0x40, 0xde, 0, kbps*10, 0) +#define panda_set_safety_mode(mode) panda_usbemu_ctrl_write(0x40, 0xdc, mode, 0, 0) +#define panda_kline_wakeup_pulse() panda_usbemu_ctrl_write(0x40, 0xf0, 0, 0, 0) +#define panda_clear_can_rx() panda_usbemu_ctrl_write(0x40, 0xf1, 0xFFFF, 0, 0) +#define panda_clear_lin_txrx() panda_usbemu_ctrl_write(0x40, 0xf2, 2, 0, 0) + +static int ICACHE_FLASH_ATTR panda_usbemu_can_read(panda_can_msg_t** can_msgs) { + int returned_count = spi_comm((uint8_t *)((const uint16 []){1,0}), 4, pandaRecvData, 0x40); + if(returned_count > 0x40 || returned_count < 0){ + os_printf("CAN read got invalid length\n"); + return -1; + } + *can_msgs = (panda_can_msg_t*)(pandaRecvData+1); + return returned_count/sizeof(panda_can_msg_t); +} + +static int ICACHE_FLASH_ATTR panda_usbemu_can_write(bool ext, uint32_t addr, + char *candata, uint8_t canlen) { + uint32_t rir; + + if(canlen > 8) return 0; + + if(ext || addr >= 0x800){ + rir = (addr << 3) | PANDA_CAN_FLAG_TRANSMIT | PANDA_CAN_FLAG_EXTENDED; + }else{ + rir = (addr << 21) | PANDA_CAN_FLAG_TRANSMIT; + } + + #define MAX_CAN_LEN 8 + + //Wifi USB Wrapper + *(uint16_t*)(pandaSendData) = PANDA_USB_CAN_WRITE_BUS_NUM; //USB Bulk Endpoint ID. + *(uint16_t*)(pandaSendData+2) = MAX_CAN_LEN; + //BULK MESSAGE + *(uint32_t*)(pandaSendData+4) = rir; + *(uint32_t*)(pandaSendData+8) = MAX_CAN_LEN | (0 << 4); //0 is CAN bus number. + //CAN DATA + memcpy(pandaSendData+12, candata, canlen); + memset(pandaSendData+12+canlen, 0, MAX_CAN_LEN-canlen); + for(int i = 12+canlen; i < 20; i++) pandaSendData[i] = 0; //Zero the rest + + /* spi_comm will erase data in the recv buffer even if you are only + * interested in sending data that gets no response (like writing + * can data). This behavior becomes problematic when trying to send + * a can message while processsing received can messages. A dummy + * recv buffer is used here so received data is not overwritten. */ + int returned_count = spi_comm(pandaSendData, 0x14, pandaRecvDataDummy, 0x40); + if(returned_count) + os_printf("ELM Can send expected 0 bytes back from panda. Got %d bytes instead\n", returned_count); + if(returned_count > 0x40) return 0; + return returned_count; +} + +elm_lin_obd_msg lin_last_sent_msg; +uint16_t lin_last_sent_msg_len = 0; +bool lin_await_msg_echo = false; + +static int ICACHE_FLASH_ATTR panda_usbemu_kline_read(uint16_t len) { + int returned_count = panda_usbemu_ctrl_write(0xC0, 0xE0, 2, 0, len); + if(returned_count > len || returned_count < 0){ + os_printf("LIN read got invalid length\n"); + return -1; + } + + #ifdef ELM_DEBUG + if(returned_count) { + os_printf("LIN Received %d bytes\n", returned_count); + os_printf(" Data: "); + for(int i = 0; i < returned_count; i++) + os_printf("%02x ", ((char*)(pandaRecvData+1))[i]); + os_printf("\n"); + } + #endif + return returned_count; +} + +static int ICACHE_FLASH_ATTR panda_usbemu_kline_write(elm_lin_obd_msg *msg) { + elm_lin_usb_msg usb_msg = {}; + + usb_msg.usb_ep_num = PANDA_USB_LIN_WRITE_BUS_NUM; //USB Bulk Endpoint ID. + usb_msg.payload_len = (msg->priority & 0x07) + 4 + 1; //The +1 is for serial_port + usb_msg.serial_port = 2; + memcpy(&usb_msg.msg, msg, sizeof(elm_lin_obd_msg)); + + /* spi_comm will erase data in the recv buffer even if you are only + * interested in sending data that gets no response (like writing + * can data). This behavior becomes problematic when trying to send + * a can message while processsing received can messages. A dummy + * recv buffer is used here so received data is not overwritten. */ + int returned_count = spi_comm((char*)&usb_msg, sizeof(elm_lin_usb_msg), pandaRecvDataDummy, 0x40); + + if(returned_count) + os_printf("ELM LIN send expected 0 bytes back from panda. Got %d bytes instead\n", returned_count); + if(returned_count > 0x40) return 0; + + return returned_count; +} + +/**************************************** + *** Ringbuffer *** + ****************************************/ + +//LIN data is delivered in chunks of arbitrary size. Using a +//ringbuffer to handle it. +uint8_t lin_ringbuff[0x20]; +uint8_t lin_ringbuff_start = 0; +uint8_t lin_ringbuff_end = 0; +#define lin_ringbuff_len \ + (((sizeof(lin_ringbuff) + lin_ringbuff_end) - lin_ringbuff_start)% sizeof(lin_ringbuff)) +#define lin_ringbuff_get(index) (lin_ringbuff[(lin_ringbuff_start + index) % sizeof(lin_ringbuff)]) +#define lin_ringbuff_consume(len) lin_ringbuff_start = ((lin_ringbuff_start + len) % sizeof(lin_ringbuff)) +#define lin_ringbuff_clear()\ + {lin_ringbuff_start = 0; \ + lin_ringbuff_end = 0;} + +int ICACHE_FLASH_ATTR elm_LIN_ringbuff_memcmp(uint8_t *data, uint16_t len) { + if(len > lin_ringbuff_len) return 1; + for(int i = 0; i < len; i++) + if(lin_ringbuff_get(i) != data[i]) return 1; + return 0; // Going with memcpy ret format where 0 means 'equal' +} + +uint16_t ICACHE_FLASH_ATTR elm_LIN_read_into_ringbuff() { + int bytelen = panda_usbemu_kline_read((sizeof(lin_ringbuff) - lin_ringbuff_len) - 1); + if(bytelen < 0) return 0; + for(int j = 0; j < bytelen; j++) { + lin_ringbuff[lin_ringbuff_end % sizeof(lin_ringbuff)] = ((char*)(pandaRecvData+1))[j]; + lin_ringbuff_end = (lin_ringbuff_end + 1) % sizeof(lin_ringbuff); + if(lin_ringbuff_start == lin_ringbuff_end) lin_ringbuff_start++; + } + + #ifdef ELM_DEBUG + if(bytelen){ + os_printf(" RB Data (%d %d %d): ", lin_ringbuff_start, lin_ringbuff_end, lin_ringbuff_len); + for(int i = 0; i < sizeof(lin_ringbuff); i++) + os_printf("%02x ", lin_ringbuff[i]); + os_printf("\n"); + } + #endif + + return bytelen; +} + +/**************************************** + *** String parsing utility functions *** + ****************************************/ + +static int8_t ICACHE_FLASH_ATTR elm_decode_hex_char(char b){ + if(b >= '0' && b <= '9') return b - '0'; + if(b >= 'A' && b <= 'F') return (b - 'A') + 10; + if(b >= 'a' && b <= 'f') return (b - 'a') + 10; + return -1; +} + +static uint8_t ICACHE_FLASH_ATTR elm_decode_hex_byte(const char* data) { + return (elm_decode_hex_char(data[0]) << 4) | elm_decode_hex_char(data[1]); +} + +static bool ICACHE_FLASH_ATTR elm_check_valid_hex_chars(const char* data, uint8_t len) { + for(int i = 0; i < len; i++){ + char b = data[i]; + if(!((b >= '0' && b <= '9') || (b >= 'A' && b <= 'F') || (b >= 'a' && b <= 'f'))) + return 0; + } + return 1; +} + +static uint16_t ICACHE_FLASH_ATTR elm_strip(const char *data, uint16_t lenin, + char *outbuff, uint16_t outbufflen) { + uint16_t count = 0; + for(uint16_t i = 0; i < lenin; i++) { + if(count >= outbufflen) break; + if(data[i] == ' ') continue; + if(data[i] >= 'a' && data[i] <= 'z'){ + outbuff[count++] = data[i] - ('a' - 'A'); + } else { + outbuff[count++] = data[i]; + } + if(data[i] == '\r') break; + } + return count; +} + +static int ICACHE_FLASH_ATTR elm_msg_find_cr_or_eos(char *data, uint16_t len){ + uint16_t i; + for(i = 0; i < len; i++) + if(data[i] == '\r') { + i++; + break; + } + return i; +} + +/***************************************************** + *** ELM protocol specification and implementation *** + *****************************************************/ + +typedef enum { + AUTO, LIN, CAN11, CAN29, NA +} elm_proto_type_t; + +typedef struct elm_protocol { + bool supported; + elm_proto_type_t type; + uint16_t cbaud; //Centibaud (cbaud * 10 = kbaud) + void (*process_obd)(const struct elm_protocol*, const char*, uint16_t); + //init is used to init and de-init a protocol. Init functions should + //not do things that would leave a new protocol in an invalid state + //after the new protocol's init is called (e.g. No arming timers). + void (*init)(const struct elm_protocol*); + char* name; +} elm_protocol_t; + +static const elm_protocol_t* ICACHE_FLASH_ATTR elm_current_proto(); +void ICACHE_FLASH_ATTR elm_reset_aux_timer(); +static void ICACHE_FLASH_ATTR elm_autodetect_cb(bool); + +static const elm_protocol_t elm_protocols[]; +//(sizeof(elm_protocols)/sizeof(elm_protocol_t)) +#define ELM_PROTOCOL_COUNT 13 + +#define LOOPCOUNT_FULL 4 +static int loopcount = 0; +static volatile os_timer_t elm_timeout; +static volatile os_timer_t elm_proto_aux_timeout; + +static bool is_auto_detecting = false; + +// Used only by elm_timer_cb, so not volatile +static bool did_multimessage = false; +static bool got_msg_this_run = false; +static bool can_tx_worked = false; +static uint8_t elm_msg_mode_ret_filter; +static uint8_t elm_msg_pid_ret_filter; + +/***************************************************** + *** ELM protocol specification and implementation *** + *** -> SAE J1850 implementation (Unsupported) *** + *****************************************************/ + +static void ICACHE_FLASH_ATTR elm_process_obd_cmd_J1850(const elm_protocol_t* proto, + const char *cmd, uint16_t len) { + elm_append_rsp_const("NO DATA\r\r>"); +} + +/***************************************************** + *** ELM protocol specification and implementation *** + *** -> ISO 14230-4 implementation *** + *****************************************************/ + +const char *lin_cmd_backup = NULL; //Holds msg while bus init is done +uint16_t lin_cmd_backup_len = 0; +bool lin_waiting_keepalive_echo = false; + +static void ICACHE_FLASH_ATTR elm_process_obd_cmd_LIN5baud(const elm_protocol_t* proto, + const char *cmd, uint16_t len) { + elm_append_rsp_const("BUS INIT: ...ERROR\r\r>"); +} + +bool ICACHE_FLASH_ATTR elm_lin_keepalive_echo() { + if(lin_waiting_keepalive_echo) { + for(int pass = 0; pass < 4 && lin_ringbuff_len < 5; pass++) { + elm_LIN_read_into_ringbuff(); + } + + lin_waiting_keepalive_echo = false; + //keepalive Echo should always come before other message echo. + if(lin_ringbuff_len >= 5 && !elm_LIN_ringbuff_memcmp("\xc1\x33\xf1\x3e\x23", 5)){ + lin_ringbuff_consume(5); + return true; + } else { + os_printf("Keep alive echo failed\n"); + return false; + } + } + return true; +} + +void ICACHE_FLASH_ATTR elm_LINFast_keepalive_timer_cb(void *arg) { + if(!lin_bus_initialized) { + os_printf("WARNING! Elm LIN keepalive timer running while bus is not initialized\n"); + return; + } + if(loopcount) { + os_printf("WARNING! Elm LIN keepalive timer during a tx/rx loop!\n"); + return; + } + if(lin_ringbuff_len) { + os_printf("WARNING! lin_ringbuff_len should be 0 when a keepalive echo is processed.\n"); + return; + } + + if(!elm_lin_keepalive_echo()) { + lin_bus_initialized = false; + return; + } + + elm_lin_obd_msg msg = {}; + + msg.priority = 0xC0 | 1; + msg.receiver = 0x33; + msg.sender = 0xF1; + msg.dat[0] = 0x3E; + msg.dat[1] = msg.dat[0] + msg.priority + msg.receiver + msg.sender; // checksum + + #ifdef ELM_DEBUG + os_printf("Sending LIN KEEPALIVE: Priority: %02x; RecvAddr: %02x; SendAddr: %02x; (%02x); ", + msg.priority, msg.receiver, msg.sender, 1); + for(int i = 0; i < 2; i++) os_printf("%02x ", msg.dat[i]); + os_printf("\n"); + #endif + + lin_waiting_keepalive_echo = true; + + panda_usbemu_kline_write(&msg); + elm_reset_aux_timer(); +} + +static void ICACHE_FLASH_ATTR elm_init_LINFast(const elm_protocol_t* proto){ + os_timer_disarm(&elm_proto_aux_timeout); + os_timer_setfn(&elm_proto_aux_timeout, (os_timer_func_t *)elm_LINFast_keepalive_timer_cb, proto); + + lin_bus_initialized = false; + lin_await_msg_echo = false; + lin_waiting_keepalive_echo = false; + + lin_cmd_backup = NULL; + lin_cmd_backup_len = 0; + + lin_ringbuff_clear(); + panda_clear_lin_txrx(); +} + +int ICACHE_FLASH_ATTR elm_LINFast_process_echo() { + if(!elm_lin_keepalive_echo()) { + os_printf("Keepalive echo not detected.\n"); + lin_ringbuff_clear(); + return -1; + } + + if(!lin_await_msg_echo) { + os_printf("Echo abort. Nothing waiting echo\n"); + return 1; + } + + for(int i = 0; i < 4; i++){ + if(lin_ringbuff_len < lin_last_sent_msg_len) elm_LIN_read_into_ringbuff(); + + if(lin_ringbuff_len >= lin_last_sent_msg_len){ + #ifdef ELM_DEBUG + os_printf("Got enough data %d\n", lin_last_sent_msg_len); + #endif + if(!elm_LIN_ringbuff_memcmp((uint8_t*)&lin_last_sent_msg, lin_last_sent_msg_len)) { + #ifdef ELM_DEBUG + os_printf("LIN data was sent successfully.\n"); + #endif + lin_ringbuff_consume(lin_last_sent_msg_len); + lin_await_msg_echo = false; + return 1; + } else { + #ifdef ELM_DEBUG + os_printf("Echo not correct.\n"); + os_printf(" RB Data (%d %d %d): ", lin_ringbuff_start, lin_ringbuff_end, lin_ringbuff_len); + for(int i = 0; i < sizeof(lin_ringbuff); i++) + os_printf("%02x ", lin_ringbuff[i]); + os_printf("\n"); + os_printf(" MSG Data (%d): ", lin_last_sent_msg_len); + for(int i = 0; i < lin_last_sent_msg_len; i++) + os_printf("%02x ", ((uint8_t*)&lin_last_sent_msg)[i]); + os_printf("\n"); + #endif + + if(lin_bus_initialized || loopcount == 0 && i == 4) { + lin_ringbuff_clear(); + return -1; + } else { + os_printf("Lin init echo misaligned? Consuming byte (%02x). Retry.\n", lin_ringbuff_get(0)); + lin_ringbuff_consume(1); + continue; + } + } + } + } + + return !lin_await_msg_echo; //true if echo handled +} + +void ICACHE_FLASH_ATTR elm_LINFast_timer_cb(void *arg){ + const elm_protocol_t* proto = (const elm_protocol_t*) arg; + loopcount--; + #ifdef ELM_DEBUG + os_printf("LIN CB call\n"); + #endif + + if(!lin_bus_initialized) { + os_printf("WARNING: LIN CB called without bus initialized!"); + return; // TODO: shoulnd't ever happen. Handle? + } + + int echo_result = elm_LINFast_process_echo(); + + if(echo_result == -1 || (echo_result == 0 && loopcount == 0)) { + if(!is_auto_detecting){ + elm_append_rsp_const("BUS ERROR\r\r>"); + elm_tcp_tx_flush(); + } + loopcount = 0; + lin_bus_initialized = false; + return; + } + + if(echo_result == 0) { + #ifdef ELM_DEBUG + os_printf("Not ready to process\n"); + #endif + os_timer_arm(&elm_timeout, 30, 0); + return; // Not ready to go on + } + + #ifdef ELM_DEBUG + os_printf("Processing ELM %d\n", lin_ringbuff_len); + #endif + + if(loopcount>0) { + for(int pass = 0; pass < 16 && loopcount; pass++){ + elm_LIN_read_into_ringbuff(); + + while(lin_ringbuff_len > 0){ + //if(lin_ringbuff_len > 0){ + if(lin_ringbuff_get(0) & 0x80 != 0x80){ + os_printf("Resetting LIN bus due to bad first byte.\n"); + loopcount = 0; + lin_bus_initialized = false; + lin_ringbuff_clear(); + + if(!is_auto_detecting){ + elm_append_rsp_const("ERROR\r\r>"); + elm_tcp_tx_flush(); + } + return; + } + + uint8_t newmsg_len = 4 + (lin_ringbuff_get(0) & 0x7); + if(lin_ringbuff_len >= newmsg_len) { + #ifdef ELM_DEBUG + os_printf("Processing LIN MSG. BuffLen %d; expect %d. Dat: ", lin_ringbuff_len, newmsg_len); + for(int i = 0; i < newmsg_len; i++) os_printf("%02x ", lin_ringbuff_get(i)); + os_printf("\n"); + #endif + got_msg_this_run = true; + loopcount = LOOPCOUNT_FULL; + + if(!is_auto_detecting){ + if(elm_mode_additional_headers){ + for(int i = 0; i < newmsg_len; i++) elm_append_rsp_hex_byte(lin_ringbuff_get(i)); + } else { + for(int i = 3; i < newmsg_len - 1; i++) elm_append_rsp_hex_byte(lin_ringbuff_get(i)); + } + elm_append_rsp_const("\r"); + } + + lin_ringbuff_consume(newmsg_len); + //elm_reset_aux_timer(); + } else { + break; //Stop consuming data if there is not enough data for the next msg. + } + } + } + os_timer_arm(&elm_timeout, 50, 0); + } else { + bool got_msg_this_run_backup = got_msg_this_run; + if(!got_msg_this_run) { + #ifdef ELM_DEBUG + os_printf(" No data collected\n"); + #endif + if(!is_auto_detecting) { + elm_append_rsp_const("NO DATA\r"); + } + } + got_msg_this_run = false; + + if(!is_auto_detecting) { + elm_append_rsp_const("\r>"); + elm_tcp_tx_flush(); + } else { + elm_autodetect_cb(got_msg_this_run_backup); + } + + //TX RX over, resume Keepalive timer + elm_reset_aux_timer(); + } +} + +void ICACHE_FLASH_ATTR elm_LINFast_businit_timer_cb(void *arg){ + const elm_protocol_t* proto = (const elm_protocol_t*) arg; + loopcount--; + #ifdef ELM_DEBUG + os_printf("LIN INIT CB call\n"); + #endif + + int echo_result = elm_LINFast_process_echo(); + + if(echo_result == -1 || (echo_result == 0 && loopcount == 0)) { + #ifdef ELM_DEBUG + os_printf("Init failed with echo test\n"); + #endif + + loopcount = 0; + lin_bus_initialized = 0; + + if(!is_auto_detecting){ + if(echo_result == -1) + elm_append_rsp_const("BUS ERROR\r\r>"); + else + elm_append_rsp_const("ERROR\r\r>"); + elm_tcp_tx_flush(); + } else { + elm_autodetect_cb(false); + } + return; + } + + if(echo_result == 0) { + #ifdef ELM_DEBUG + os_printf("Not ready to process\n"); + #endif + os_timer_arm(&elm_timeout, elm_mode_timeout, 0); + return; // Not ready to go on + } + + #ifdef ELM_DEBUG + os_printf("Bus init ready to process %d bytes\n", lin_ringbuff_len); + #endif + + if(lin_bus_initialized) return; // TODO: shoulnd't ever happen. Handle? + + if(loopcount>0) { + //Keep waiting for response + for(int i = 0; i < 4; i++){ + elm_LIN_read_into_ringbuff(); + + if(lin_ringbuff_len > 0){ + if(lin_ringbuff_get(0) & 0x80 != 0x80){ + os_printf("Resetting LIN bus due to bad first byte.\n"); + loopcount = 0; + lin_ringbuff_clear(); + + if(!is_auto_detecting){ + elm_append_rsp_const("ERROR\r\r>"); + elm_tcp_tx_flush(); + } else { + elm_autodetect_cb(false); + } + return; + } + + uint8_t newmsg_len = 4 + (lin_ringbuff_get(0) & 0x7); + if(lin_ringbuff_len < newmsg_len) { + os_printf("Resetting LIN because returned init data was wrong.\n"); + loopcount = 0; + lin_ringbuff_clear(); + + if(!is_auto_detecting){ + elm_append_rsp_const("ERROR\r\r>"); + elm_tcp_tx_flush(); + } else { + elm_autodetect_cb(false); + } + return; + } + + if(!elm_LIN_ringbuff_memcmp("\x83\xF1\x10\xC1\x8F\xE9\xBD", 7)) { + lin_ringbuff_consume(7); + lin_bus_initialized = true; + //lin_ringbuff_clear(); + + os_printf("BUS INITIALIZED\n"); + + elm_reset_aux_timer(); + + if(!is_auto_detecting) { + elm_append_rsp_const("OK\r"); + + //Do the send that was delayed + if(lin_cmd_backup_len) { + elm_tcp_tx_flush(); + proto->process_obd(proto, lin_cmd_backup, lin_cmd_backup_len); + } else { + elm_append_rsp_const("\r>"); + elm_tcp_tx_flush(); + } + } else { + #ifdef ELM_DEBUG + os_printf("LIN success. Silent because in autodetect.\n"); + #endif + elm_autodetect_cb(true); + // TODO: Since bus init is good, is it ok to skip sending the '0100' msg? + } + return; + } + } + } + os_timer_arm(&elm_timeout, elm_mode_timeout, 0); + } else { + #ifdef ELM_DEBUG + os_printf("Fall through on bus init\n"); + #endif + if(!is_auto_detecting){ + elm_append_rsp_const("ERROR\r\r>"); + elm_tcp_tx_flush(); + } else { + elm_autodetect_cb(false); + } + elm_reset_aux_timer(); + } +} + +static void ICACHE_FLASH_ATTR elm_process_obd_cmd_LINFast(const elm_protocol_t* proto, + const char *cmd, uint16_t len) { + elm_lin_obd_msg msg = {}; + uint8_t bytelen = (len-1)/2; + if((bytelen > 7 && !elm_mode_allow_long) || bytelen > 8) { + elm_append_rsp_const("?\r\r>"); + return; + } + + os_timer_disarm(&elm_proto_aux_timeout); + + if(!lin_bus_initialized) { + panda_clear_lin_txrx(); + + if(!is_auto_detecting) + elm_append_rsp_const("BUS INIT: "); + + lin_cmd_backup = cmd; + lin_cmd_backup_len = len; + + bytelen = 1; + msg.dat[0] = 0x81; + msg.dat[1] = 0x81; // checksum + + panda_kline_wakeup_pulse(); + } else { + bytelen = min(bytelen, 7); + for(int i = 0; i < bytelen; i++){ + msg.dat[i] = elm_decode_hex_byte(&cmd[i*2]); + msg.dat[bytelen] += msg.dat[i]; + } + + elm_msg_mode_ret_filter = msg.dat[0]; + elm_msg_pid_ret_filter = msg.dat[1]; + } + + msg.priority = 0xC0 | bytelen; + msg.receiver = 0x33; + msg.sender = 0xF1; + msg.dat[bytelen] += msg.priority + msg.receiver + msg.sender; // checksum + + #ifdef ELM_DEBUG + os_printf("Sending LIN OBD: Priority: %02x; RecvAddr: %02x; SendAddr: %02x; (%02x); ", + msg.priority, msg.receiver, msg.sender, bytelen); + for(int i = 0; i < 8; i++) os_printf("%02x ", msg.dat[i]); + os_printf("\n"); + #endif + + lin_last_sent_msg_len = (msg.priority & 0x07) + 4; + memcpy(&lin_last_sent_msg, &msg, lin_last_sent_msg_len); + lin_await_msg_echo = true; + panda_usbemu_kline_write(&msg); + + loopcount = LOOPCOUNT_FULL + 1; + os_timer_disarm(&elm_timeout); + + if(lin_bus_initialized) { + os_timer_setfn(&elm_timeout, (os_timer_func_t *)elm_LINFast_timer_cb, proto); + elm_LINFast_timer_cb((void*)proto); + } else { + os_timer_setfn(&elm_timeout, (os_timer_func_t *)elm_LINFast_businit_timer_cb, proto); + elm_LINFast_businit_timer_cb((void*)proto); + } +} + +/***************************************************** + *** ELM protocol specification and implementation *** + *** -> ISO 15765-4 implementation *** + *****************************************************/ + +void ICACHE_FLASH_ATTR elm_ISO15765_timer_cb(void *arg){ + const elm_protocol_t* proto = (const elm_protocol_t*) arg; + loopcount--; + if(loopcount>0) { + for(int pass = 0; pass < 16 && loopcount; pass++){ + panda_can_msg_t *can_msgs; + int num_can_msgs = panda_usbemu_can_read(&can_msgs); + + #ifdef ELM_DEBUG + if(num_can_msgs) os_printf(" Received %d can messages\n", num_can_msgs); + #endif + + if(num_can_msgs < 0) continue; + if(!num_can_msgs) break; + + for(int i = 0; i < num_can_msgs; i++){ + + panda_can_msg_t *recv = &can_msgs[i]; + + #ifdef ELM_DEBUG + os_printf(" RECV: Bus: %d; Addr: %08x; ext: %d; tx: %d; Len: %d; ", + recv->bus, panda_get_can_addr(recv), recv->ext, recv->tx, recv->len); + for(int j = 0; j < recv->len; j++) os_printf("%02x ", recv->data[j]); + os_printf("Ts: %d\n", recv->ts); + #endif + + if (recv->bus==0 && recv->len == 8 && + ( + (proto->type == CAN11 && !recv->ext && (panda_get_can_addr(recv) & 0x7F8) == 0x7E8) || + (proto->type == CAN29 && recv->ext && (panda_get_can_addr(recv) & 0x1FFFFF00) == 0x18DAF100) + ) + ) { + if(recv->data[0] <= 7 && + recv->data[1] == (0x40|elm_msg_mode_ret_filter) && + recv->data[2] == elm_msg_pid_ret_filter) { + got_msg_this_run = true; + loopcount = LOOPCOUNT_FULL; + + #ifdef ELM_DEBUG + os_printf(" CAN msg response, index: %d\n", i); + #endif + + if(!is_auto_detecting){ + if(elm_mode_additional_headers){ + elm_append_rsp_can_msg_addr(recv); + for(int j = 0; j < recv->data[0]+1; j++) elm_append_rsp_hex_byte(recv->data[j]); + } else { + for(int j = 1; j < recv->data[0]+1; j++) elm_append_rsp_hex_byte(recv->data[j]); + } + + elm_append_rsp_const("\r"); + elm_tcp_tx_flush(); + } + + } else if((recv->data[0] & 0xF0) == 0x10 && + recv->data[2] == (0x40|elm_msg_mode_ret_filter) && + recv->data[3] == elm_msg_pid_ret_filter) { + got_msg_this_run = true; + loopcount = LOOPCOUNT_FULL; + panda_usbemu_can_write(0, + (proto->type==CAN11) ? + 0x7E0 | (panda_get_can_addr(recv)&0x7) : + (0x18DA00F1 | (((panda_get_can_addr(recv))&0xFF)<<8)), + "\x30\x00\x00", 3); + + did_multimessage = true; + + #ifdef ELM_DEBUG + os_printf(" CAN multimsg start response, index: %d, len %d\n", i, + ((recv->data[0]&0xF)<<8) | recv->data[1]); + #endif + + if(!is_auto_detecting){ + if(!elm_mode_additional_headers) { + elm_append_rsp(&hex_lookup[recv->data[0]&0xF], 1); + elm_append_rsp_hex_byte(recv->data[1]); + elm_append_rsp_const("\r0:"); + if(elm_mode_print_spaces) elm_append_rsp_const(" "); + for(int j = 2; j < 8; j++) elm_append_rsp_hex_byte(recv->data[j]); + } else { + elm_append_rsp_can_msg_addr(recv); + for(int j = 0; j < 8; j++) elm_append_rsp_hex_byte(recv->data[j]); + } + + elm_append_rsp_const("\r"); + elm_tcp_tx_flush(); + } + + } else if (did_multimessage && (recv->data[0] & 0xF0) == 0x20) { + got_msg_this_run = true; + loopcount = LOOPCOUNT_FULL; + #ifdef ELM_DEBUG + os_printf(" CAN multimsg data response, index: %d\n", i); + #endif + + if(!is_auto_detecting){ + if(!elm_mode_additional_headers) { + elm_append_rsp(&hex_lookup[recv->data[0] & 0xF], 1); + elm_append_rsp_const(":"); + if(elm_mode_print_spaces) elm_append_rsp_const(" "); + for(int j = 1; j < 8; j++) elm_append_rsp_hex_byte(recv->data[j]); + } else { + elm_append_rsp_can_msg_addr(recv); + for(int j = 0; j < 8; j++) elm_append_rsp_hex_byte(recv->data[j]); + } + elm_append_rsp_const("\r"); + } + } + } else if (recv->bus == 0x80 && recv->len == 8 && + (panda_get_can_addr(recv) == ((proto->type==CAN11) ? 0x7DF : 0x18DB33F1)) + ) { + //Can send receipt + #ifdef ELM_DEBUG + os_printf(" Got CAN tx receipt\n"); + #endif + can_tx_worked = true; + } + } + } + os_timer_arm(&elm_timeout, elm_mode_timeout, 0); + } else { + bool got_msg_this_run_backup = got_msg_this_run; + if(did_multimessage) { + os_printf(" End of multi message\n"); + } else if(!got_msg_this_run) { + os_printf(" No data collected\n"); + if(!is_auto_detecting) { + if(can_tx_worked) { + elm_append_rsp_const("NO DATA\r"); + } else { + elm_append_rsp_const("CAN ERROR\r"); + } + } + } + did_multimessage = false; + got_msg_this_run = false; + can_tx_worked = false; + + if(!is_auto_detecting) { + elm_append_rsp_const("\r>"); + elm_tcp_tx_flush(); + } else { + elm_autodetect_cb(got_msg_this_run_backup); + } + } +} + +static void ICACHE_FLASH_ATTR elm_init_ISO15765(const elm_protocol_t* proto){ + panda_set_can0_cbaud(proto->cbaud); +} + +static void ICACHE_FLASH_ATTR elm_process_obd_cmd_ISO15765(const elm_protocol_t* proto, + const char *cmd, uint16_t len) { + elm_can_obd_msg msg = {}; + msg.len = (len-1)/2; + if((msg.len > 7 && !elm_mode_allow_long) || msg.len > 8) { + elm_append_rsp_const("?\r\r>"); + return; + } + + msg.len = min(msg.len, 7); + + for(int i = 0; i < msg.len; i++) + msg.dat[i] = elm_decode_hex_byte(&cmd[i*2]); + + elm_msg_mode_ret_filter = msg.dat[0]; + elm_msg_pid_ret_filter = msg.dat[1]; + + #ifdef ELM_DEBUG + os_printf("Sending CAN OBD: %02x; ", msg.len); + for(int i = 0; i < 7; i++) + os_printf("%02x ", msg.dat[i]); + os_printf("\n"); + #endif + + panda_clear_can_rx(); + + panda_usbemu_can_write(0, (proto->type==CAN11) ? 0x7DF : 0x18DB33F1, + (uint8_t*)&msg, msg.len+1); + + #ifdef ELM_DEBUG + os_printf("Starting up timer\n"); + #endif + + loopcount = LOOPCOUNT_FULL; + os_timer_disarm(&elm_timeout); + os_timer_setfn(&elm_timeout, (os_timer_func_t *)elm_ISO15765_timer_cb, proto); + os_timer_arm(&elm_timeout, elm_mode_timeout, 0); +} + +/***************************************************** + *** ELM protocol specification and implementation *** + *** -> Stuf for unsupported CAN protocols *** + *****************************************************/ + +static void ICACHE_FLASH_ATTR elm_process_obd_cmd_CANGen(const elm_protocol_t* proto, + const char *cmd, uint16_t len) { + elm_append_rsp_const("NO DATA\r\r>"); +} + +/***************************************************** + *** ELM protocol specification and implementation *** + *** -> AUTO Detect implementation *** + *****************************************************/ + +static int elm_autodetect_proto_iter; +static uint16_t elm_staged_auto_msg_len; +static const char* elm_staged_auto_msg; + +static void ICACHE_FLASH_ATTR elm_autodetect_cb(bool proto_worked){ + if(proto_worked) { + os_printf("Autodetect proto success\n"); + is_auto_detecting = false; + elm_selected_protocol = elm_autodetect_proto_iter; + elm_current_proto()->process_obd(elm_current_proto(), + elm_staged_auto_msg, elm_staged_auto_msg_len); + } else { + for(elm_autodetect_proto_iter++; elm_autodetect_proto_iter < ELM_PROTOCOL_COUNT; + elm_autodetect_proto_iter++){ + const elm_protocol_t *proto = &elm_protocols[elm_autodetect_proto_iter]; + if(proto->supported && proto->type != AUTO) { + os_printf("*** AUTO trying '%s'\n", proto->name); + proto->init(proto); + proto->process_obd(proto, "0100\r", 5); // Try sending on the bus + return; + } + } + + //if(elm_autodetect_main()) return; + is_auto_detecting = false; + os_printf("Autodetect failed\n"); + elm_append_rsp_const("UNABLE TO CONNECT\r\r>"); + elm_tcp_tx_flush(); + } +} + +static void ICACHE_FLASH_ATTR elm_process_obd_cmd_AUTO(const elm_protocol_t* proto, + const char *cmd, uint16_t len) { + elm_append_rsp_const("SEARCHING...\r"); + elm_staged_auto_msg_len = len; + elm_staged_auto_msg = cmd; + is_auto_detecting = true; + + elm_autodetect_proto_iter = 0; + elm_autodetect_cb(false); +} + +/***************************************************** + *** ELM protocol specification and implementation *** + *** -> Protocol Registry and related functions. *** + *****************************************************/ + +static const elm_protocol_t elm_protocols[] = { + {true, AUTO, 0, elm_process_obd_cmd_AUTO, NULL, "AUTO", }, + {false, NA, 416, elm_process_obd_cmd_J1850, NULL, "SAE J1850 PWM", }, + {false, NA, 104, elm_process_obd_cmd_J1850, NULL, "SAE J1850 VPW", }, + {false, LIN, 104, elm_process_obd_cmd_LIN5baud, NULL, "ISO 9141-2", }, + {false, LIN, 104, elm_process_obd_cmd_LIN5baud, NULL, "ISO 14230-4 (KWP 5BAUD)", }, + {true, LIN, 104, elm_process_obd_cmd_LINFast, elm_init_LINFast, "ISO 14230-4 (KWP FAST)", }, + {true, CAN11, 5000, elm_process_obd_cmd_ISO15765, elm_init_ISO15765, "ISO 15765-4 (CAN 11/500)",}, + {true, CAN29, 5000, elm_process_obd_cmd_ISO15765, elm_init_ISO15765, "ISO 15765-4 (CAN 29/500)",}, + {true, CAN11, 2500, elm_process_obd_cmd_ISO15765, elm_init_ISO15765, "ISO 15765-4 (CAN 11/250)",}, + {true, CAN29, 2500, elm_process_obd_cmd_ISO15765, elm_init_ISO15765, "ISO 15765-4 (CAN 29/250)",}, + {false, CAN29, 2500, elm_process_obd_cmd_CANGen, NULL, "SAE J1939 (CAN 29/250)", }, + {false, CAN11, 1250, elm_process_obd_cmd_CANGen, NULL, "USER1 (CAN 11/125)", }, + {false, CAN11, 500, elm_process_obd_cmd_CANGen, NULL, "USER2 (CAN 11/50)", }, +}; + +static const elm_protocol_t* ICACHE_FLASH_ATTR elm_current_proto() { + return &elm_protocols[elm_selected_protocol]; +} + +void ICACHE_FLASH_ATTR elm_reset_aux_timer() { + os_timer_disarm(&elm_proto_aux_timeout); + if(elm_mode_keepalive_period) + os_timer_arm(&elm_proto_aux_timeout, elm_mode_keepalive_period, 0); +} + +void ICACHE_FLASH_ATTR elm_proto_reinit(const elm_protocol_t *proto) { + if(proto->init) proto->init(proto); +} + +/******************************************* + *** ELM AT command parsing and handling *** + *******************************************/ + +enum at_cmd_ids_t { // FULL ELM 1.0 list + AT_INVALID, //Fake + + AT_AMP1, + AT_AL, + AT_AT0, AT_AT1, AT_AT2, // Added ELM 1.2, expected by Torque + AT_BD, + AT_BI, + AT_CAF0, AT_CAF1, + AT_CF_8, AT_CF_3, + AT_CFC0, AT_CFC1, + AT_CM_8, AT_CM_3, + AT_CP, + AT_CS, + AT_CV, + AT_D, + AT_DP, AT_DPN, + AT_E0, AT_E1, + AT_H0, AT_H1, + AT_I, + AT_IB10, + AT_IB96, + AT_L0, AT_L1, + AT_M0, AT_M1, AT_MA, + AT_MR, + AT_MT, + AT_NL, + AT_PC, + AT_R0, AT_R1, + AT_RV, + AT_S0, AT_S1, // Added ELM 1.3, expected by Torque + AT_SH_6, AT_SH_3, + AT_SPA, AT_SP, + AT_ST, + AT_SW, + AT_TPA, AT_TP, + AT_WM_XYZA, AT_WM_XYZAB, AT_WM_XYZABC, + AT_WS, + AT_Z, +}; + +typedef struct { + char* name; + uint8_t name_len; + uint8_t cmd_len; + enum at_cmd_ids_t id; +} at_cmd_reg_t; + +static const at_cmd_reg_t at_cmd_reg[] = { + {"@1", 2, 2, AT_AMP1}, + {"AL", 2, 2, AT_AL}, + {"AT0", 3, 3, AT_AT0}, // Added ELM 1.2, expected by Torque + {"AT1", 3, 3, AT_AT1}, // Added ELM 1.2, expected by Torque + {"AT2", 3, 3, AT_AT2}, // Added ELM 1.2, expected by Torque + {"DP", 2, 2, AT_DP}, + {"DPN", 3, 3, AT_DPN}, + {"E0", 2, 2, AT_E0}, + {"E1", 2, 2, AT_E1}, + {"H0", 2, 2, AT_H0}, + {"H1", 2, 2, AT_H1}, + {"I", 1, 1, AT_I}, + {"L0", 2, 2, AT_L0}, + {"L1", 2, 2, AT_L1}, + {"M0", 2, 2, AT_M0}, + //{"M1", 2, 2, AT_M1}, + {"NL", 2, 2, AT_NL}, + {"PC", 2, 2, AT_PC}, + {"S0", 2, 2, AT_S0}, // Added ELM 1.3, expected by Torque + {"S1", 2, 2, AT_S1}, // Added ELM 1.3, expected by Torque + {"SP", 2, 3, AT_SP}, + {"SPA", 3, 4, AT_SPA}, + {"ST", 2, 4, AT_ST}, + {"SW", 2, 4, AT_SW}, + {"Z", 1, 1, AT_Z}, +}; +#define AT_CMD_REG_LEN (sizeof(at_cmd_reg)/sizeof(at_cmd_reg_t)) + +static enum at_cmd_ids_t ICACHE_FLASH_ATTR elm_parse_at_cmd(char *cmd, uint16_t len){ + int i; + for(i=0; i7 BYTES) + elm_mode_allow_long = true; + break; + case AT_AT0: //DISABLE ADAPTIVE TIMING + elm_mode_adaptive_timing = 0; + break; + case AT_AT1: //SET ADAPTIVE TIMING TO AUTO1 + elm_mode_adaptive_timing = 1; + break; + case AT_AT2: //SET ADAPTIVE TIMING TO AUTO2 + elm_mode_adaptive_timing = 2; + break; + case AT_DP: //DESCRIBE THE PROTOCOL BY NAME + if(elm_mode_auto_protocol && elm_selected_protocol != 0) + elm_append_rsp_const("AUTO, "); + elm_append_rsp(elm_current_proto()->name, + strlen(elm_current_proto()->name)); + elm_append_rsp_const("\r\r"); + return; + case AT_DPN: //DESCRIBE THE PROTOCOL BY NUMBER + //TODO: Required. Report currently selected protocol + if(elm_mode_auto_protocol) + elm_append_rsp_const("A"); + elm_append_rsp(&hex_lookup[elm_selected_protocol], 1); + elm_append_rsp_const("\r\r"); + return; // Don't display 'OK' + case AT_E0: //ECHO OFF + elm_mode_echo = false; + break; + case AT_E1: //ECHO ON + elm_mode_echo = true; + break; + case AT_H0: //SHOW FULL CAN HEADERS OFF + elm_mode_additional_headers = false; + break; + case AT_H1: //SHOW FULL CAN HEADERS ON + elm_mode_additional_headers = true; + break; + case AT_I: //IDENTIFY SELF + elm_append_rsp_const(IDENT_MSG); + return; + case AT_L0: //LINEFEED OFF + elm_mode_linefeed = false; + break; + case AT_L1: //LINEFEED ON + elm_mode_linefeed = true; + break; + case AT_M0: //DISABLE NONVOLATILE STORAGE + //Memory storage is likely unnecessary + break; + case AT_NL: //DISABLE LONG MESSAGE SUPPORT (>7 BYTES) + elm_mode_allow_long = false; + break; + case AT_PC: //PROTOCOL CANCEL (Stop timers and stuff) + { + //Init functions should idenpotently prepare the protocol to be used. + //Thus, the init function can be used as a protocol cancel function + elm_proto_reinit(elm_current_proto()); + break; + } + case AT_S0: //DISABLE PRINTING SPACES IN ECU RESPONSES + elm_mode_print_spaces = false; + break; + case AT_S1: //ENABLE PRINTING SPACES IN ECU RESPONSES + elm_mode_print_spaces = true; + break; + case AT_SP: //SET PROTOCOL + tmp = elm_decode_hex_char(cmd[2]); + if(tmp == -1 || tmp >= ELM_PROTOCOL_COUNT) { + elm_append_rsp_const("?\r\r"); + return; + } + + //De-Init previous protocol + elm_proto_reinit(elm_current_proto()); + + elm_selected_protocol = tmp; + elm_mode_auto_protocol = (tmp == 0); + + //Init new protocol + elm_proto_reinit(elm_current_proto()); + break; + case AT_SPA: //SET PROTOCOL WITH AUTO FALLBACK + tmp = elm_decode_hex_char(cmd[3]); + if(tmp == -1 || tmp >= ELM_PROTOCOL_COUNT) { + elm_append_rsp_const("?\r\r"); + return; + } + + //De-Init previous protocol + elm_proto_reinit(elm_current_proto()); + + elm_selected_protocol = tmp; + elm_mode_auto_protocol = true; + + //Init new protocol + elm_proto_reinit(elm_current_proto()); + break; + case AT_ST: //SET TIMEOUT + if(!elm_check_valid_hex_chars(&cmd[2], 2)) { + elm_append_rsp_const("?\r\r"); + return; + } + + tmp = elm_decode_hex_byte(&cmd[2]); + //20 for CAN, 4 for LIN + elm_mode_timeout = tmp ? tmp*20 : ELM_MODE_TIMEOUT_DEFAULT; + break; + case AT_SW: //SET WAKEUP TIME INTERVAL + if(!elm_check_valid_hex_chars(&cmd[2], 2)) { + elm_append_rsp_const("?\r\r"); + return; + } + + tmp = elm_decode_hex_byte(&cmd[2]); + elm_mode_keepalive_period = tmp ? max(tmp, 0x20) * 20 : 0; + + if(lin_bus_initialized){ + os_timer_disarm(&elm_proto_aux_timeout); + if(elm_mode_keepalive_period) + os_timer_arm(&elm_proto_aux_timeout, elm_mode_keepalive_period, 0); + } + break; + case AT_Z: //RESET + elm_mode_echo = true; + elm_mode_linefeed = false; + elm_mode_additional_headers = false; + elm_mode_auto_protocol = true; + elm_selected_protocol = ELM_MODE_SELECTED_PROTOCOL_DEFAULT; + elm_mode_print_spaces = true; + elm_mode_adaptive_timing = 1; + elm_mode_allow_long = false; + elm_mode_timeout = ELM_MODE_TIMEOUT_DEFAULT; + elm_mode_keepalive_period = ELM_MODE_KEEPALIVE_PERIOD_DEFAULT; + + elm_append_rsp_const("\r\r"); + elm_append_rsp_const(IDENT_MSG); + panda_set_safety_mode(0xE327); + + elm_proto_reinit(elm_current_proto()); + return; + default: + elm_append_rsp_const("?\r\r"); + return; + } + + elm_append_rsp_const("OK\r\r"); +} + +/************************************* + *** Connection and cli management *** + *************************************/ + +static void ICACHE_FLASH_ATTR elm_append_in_msg(char *data, uint16_t len) { + if(in_msg_len + len > sizeof(in_msg)) + len = sizeof(in_msg) - in_msg_len; + memcpy(in_msg + in_msg_len, data, len); + in_msg_len += len; +} + +static int ICACHE_FLASH_ATTR elm_msg_is_at_cmd(char *data, uint16_t len){ + return len >= 4 && data[0] == 'A' && data[1] == 'T'; +} + +static void ICACHE_FLASH_ATTR elm_rx_cb(void *arg, char *data, uint16_t len) { + #ifdef ELM_DEBUG + //os_printf("\nGot ELM Data In: '%s'\n", data); + #endif + + rsp_buff_len = 0; + len = elm_msg_find_cr_or_eos(data, len); + + if(loopcount){ + os_timer_disarm(&elm_timeout); + loopcount = 0; + got_msg_this_run = false; + can_tx_worked = false; + did_multimessage = false; + + os_printf("Interrupting operation, stopping timer. msg len: %d\n", len); + elm_append_rsp_const("STOPPED\r\r>"); + if(len == 1 && data[0] == '\r') { + os_printf("Empty msg source of interrupt.\n"); + elm_tcp_tx_flush(); + return; + } + } + + if(!(len == 1 && data[0] == '\r') && in_msg_len && in_msg[in_msg_len-1] == '\r'){ + in_msg_len = 0; + } + + if(!(len == 1 && data[0] == '\r' && in_msg_len && in_msg[in_msg_len-1] == '\r')) { + // Not Repeating last message + elm_append_in_msg(data, len); //Aim to remove this memcpy + } + if(elm_mode_echo) + elm_append_rsp(in_msg, in_msg_len); + + if(in_msg_len > 0 && in_msg[in_msg_len-1] == '\r') { //Got a full line + stripped_msg_len = elm_strip(in_msg, in_msg_len, stripped_msg, sizeof(stripped_msg)); + + if(elm_msg_is_at_cmd(stripped_msg, stripped_msg_len)) { + elm_process_at_cmd(stripped_msg+2, stripped_msg_len-2); + elm_append_rsp_const(">"); + } else if(elm_check_valid_hex_chars(stripped_msg, stripped_msg_len - 1)) { + elm_current_proto()->process_obd(elm_current_proto(), stripped_msg, stripped_msg_len); + } else { + elm_append_rsp_const("?\r\r>"); + } + } + + elm_tcp_tx_flush(); + + //Just clear the buffer if full with no termination + if(in_msg_len == sizeof(in_msg) && in_msg[in_msg_len-1] != '\r') + in_msg_len = 0; +} + +void ICACHE_FLASH_ATTR elm_tcp_disconnect_cb(void *arg){ + struct espconn *pesp_conn = (struct espconn *)arg; + + elm_tcp_conn_t * prev = NULL; + for(elm_tcp_conn_t *iter = connection_list; iter != NULL; iter=iter->next){ + struct espconn *conn = iter->conn; + //SHOW_CONNECTION("Considering Disconnecting", conn); + if(!memcmp(pesp_conn->proto.tcp->remote_ip, conn->proto.tcp->remote_ip, 4) && + pesp_conn->proto.tcp->remote_port == conn->proto.tcp->remote_port){ + os_printf("Deleting ELM Connection!\n"); + if(prev){ + prev->next = iter->next; + } else { + connection_list = iter->next; + } + os_free(iter); + break; + } + + prev = iter; + } + + if(connection_list == NULL) { + //If all clients are disconnected, reset the protocol (cancels + //keep alive timers). This will not detect inproperly killed + //connections. In this case, periodic events associated with the + //current protocol will continue until a new client attaches, a + //command is sent generating a response (ELM will try to responde + //to the dead connection, and remove it upon error), and finally, + //the new client disconnects. OFC a power cycle is also an option. + elm_proto_reinit(elm_current_proto()); + } +} + +void ICACHE_FLASH_ATTR elm_tcp_connect_cb(void *arg) { + struct espconn *pesp_conn = (struct espconn *)arg; + //SHOW_CONNECTION("New connection", pesp_conn); + espconn_set_opt(&elm_conn, ESPCONN_NODELAY); + espconn_regist_recvcb(pesp_conn, elm_rx_cb); + //Allow several sends to be queued at a time. + espconn_tcp_set_buf_count(pesp_conn, 3); + + bool connection_address_already_there = false; + for(elm_tcp_conn_t *iter2 = connection_list; iter2 != NULL; iter2 = iter2->next) + if(iter2->conn == pesp_conn){connection_address_already_there = true; break;} + + if(connection_address_already_there) { + os_printf("ELM WIFI: Memory reuse of recently killed connection\n"); + } else { + os_printf("ELM WIFI: Adding connection\n"); + elm_tcp_conn_t *newconn = os_malloc(sizeof(elm_tcp_conn_t)); + if(!newconn) { + os_printf("Failed to allocate place for connection\n"); + } else { + newconn->next = connection_list; + newconn->conn = pesp_conn; + connection_list = newconn; + } + } +} + +void ICACHE_FLASH_ATTR elm327_init() { + // control listener + elm_proto.local_port = ELM_PORT; + elm_conn.type = ESPCONN_TCP; + elm_conn.state = ESPCONN_NONE; + elm_conn.proto.tcp = &elm_proto; + espconn_regist_connectcb(&elm_conn, elm_tcp_connect_cb); + espconn_regist_disconcb(&elm_conn, elm_tcp_disconnect_cb); + espconn_accept(&elm_conn); + espconn_regist_time(&elm_conn, 0, 0); // 60s timeout for all connections +} diff --git a/boardesp/get_sdk.sh b/boardesp/get_sdk.sh new file mode 100755 index 0000000000..adccf678f9 --- /dev/null +++ b/boardesp/get_sdk.sh @@ -0,0 +1,12 @@ +#!/bin/bash +sudo apt-get install make unrar-free autoconf automake libtool gcc g++ gperf \ + flex bison texinfo gawk ncurses-dev libexpat-dev python-dev python python-serial \ + sed git unzip bash help2man wget bzip2 +# huh? +sudo apt-get install libtool +sudo apt-get install libtool-bin +git clone --recursive https://github.com/pfalcon/esp-open-sdk.git +cd esp-open-sdk +git checkout 03f5e898a059451ec5f3de30e7feff30455f7cec +LD_LIBRARY_PATH="" make STANDALONE=y + diff --git a/boardesp/get_sdk_mac.sh b/boardesp/get_sdk_mac.sh new file mode 100755 index 0000000000..a8c2d709d4 --- /dev/null +++ b/boardesp/get_sdk_mac.sh @@ -0,0 +1,32 @@ +#!/bin/bash + +# from http://www.esp8266.com/wiki/doku.php?id=setup-osx-compiler-esp8266 + +brew install gnu-sed --with-default-names +brew tap homebrew/dupes +brew install gperf +brew install grep +brew install autoconf +brew install binutils +brew install gawk +brew install wget +brew install automake +brew install libtool +brew install help2man + +brew uninstall gperf + +hdiutil create esp-open-sdk.dmg -volname "esp-open-sdk" -size 10g -fs "Case-sensitive HFS+" +hdiutil mount esp-open-sdk.dmg +ln -s /Volumes/esp-open-sdk esp-open-sdk +cd esp-open-sdk + +git init +git remote add origin https://github.com/pfalcon/esp-open-sdk.git +git fetch origin +git checkout 03f5e898a059451ec5f3de30e7feff30455f7cec +git submodule init +git submodule update --recursive + +make STANDALONE=y + diff --git a/boardesp/include/espmissingincludes.h b/boardesp/include/espmissingincludes.h new file mode 100644 index 0000000000..51672d3f50 --- /dev/null +++ b/boardesp/include/espmissingincludes.h @@ -0,0 +1,78 @@ +#ifndef ESPMISSINGINCLUDES_H +#define ESPMISSINGINCLUDES_H + +#include +#include +#include + + +int strcasecmp(const char *a, const char *b); +#ifndef FREERTOS +#include +#include +//Missing function prototypes in include folders. Gcc will warn on these if we don't define 'em anywhere. +//MOST OF THESE ARE GUESSED! but they seem to swork and shut up the compiler. +typedef struct espconn espconn; + +int atoi(const char *nptr); +void ets_install_putc1(void *routine); +void ets_isr_attach(int intr, void *handler, void *arg); +void ets_isr_mask(unsigned intr); +void ets_isr_unmask(unsigned intr); +int ets_memcmp(const void *s1, const void *s2, size_t n); +void *ets_memcpy(void *dest, const void *src, size_t n); +void *ets_memset(void *s, int c, size_t n); +int ets_sprintf(char *str, const char *format, ...) __attribute__ ((format (printf, 2, 3))); +int ets_str2macaddr(void *, void *); +int ets_strcmp(const char *s1, const char *s2); +char *ets_strcpy(char *dest, const char *src); +size_t ets_strlen(const char *s); +int ets_strncmp(const char *s1, const char *s2, int len); +char *ets_strncpy(char *dest, const char *src, size_t n); +char *ets_strstr(const char *haystack, const char *needle); +void ets_timer_arm_new(os_timer_t *a, int b, int c, int isMstimer); +void ets_timer_disarm(os_timer_t *a); +void ets_timer_setfn(os_timer_t *t, ETSTimerFunc *fn, void *parg); +void ets_update_cpu_frequency(int freqmhz); +void *os_memmove(void *dest, const void *src, size_t n); +int os_printf(const char *format, ...) __attribute__ ((format (printf, 1, 2))); +int os_snprintf(char *str, size_t size, const char *format, ...) __attribute__ ((format (printf, 3, 4))); +int os_printf_plus(const char *format, ...) __attribute__ ((format (printf, 1, 2))); +void uart_div_modify(int no, unsigned int freq); +uint8 wifi_get_opmode(void); +uint32 system_get_time(); +int rand(void); +void ets_bzero(void *s, size_t n); +void ets_delay_us(int ms); + +//Hack: this is defined in SDK 1.4.0 and undefined in 1.3.0. It's only used for this, the symbol itself +//has no meaning here. +#ifndef RC_LIMIT_P2P_11N +//Defs for SDK <1.4.0 +void *pvPortMalloc(size_t xWantedSize); +void *pvPortZalloc(size_t); +void vPortFree(void *ptr); +void *vPortMalloc(size_t xWantedSize); +void pvPortFree(void *ptr); +#else +void *pvPortMalloc(size_t xWantedSize, const char *file, int line); +void *pvPortZalloc(size_t, const char *file, int line); +void vPortFree(void *ptr, const char *file, int line); +void *vPortMalloc(size_t xWantedSize, const char *file, int line); +void pvPortFree(void *ptr, const char *file, int line); +#endif + +//Standard PIN_FUNC_SELECT gives a warning. Replace by a non-warning one. +#ifdef PIN_FUNC_SELECT +#undef PIN_FUNC_SELECT +#define PIN_FUNC_SELECT(PIN_NAME, FUNC) do { \ + WRITE_PERI_REG(PIN_NAME, \ + (READ_PERI_REG(PIN_NAME) \ + & (~(PERIPHS_IO_MUX_FUNC< _b ? _a : _b; }) + +char ssid[32]; +static const int pin = 2; + +// Structure holding the TCP connection information. +struct espconn tcp_conn; +// TCP specific protocol structure. +esp_tcp tcp_proto; + +// interrupt communication on port 1338, UDP! +struct espconn inter_conn; +esp_udp inter_proto; + +uint32_t sendData[0x14] = {0}; +uint32_t recvData[0x40] = {0}; + +static int ICACHE_FLASH_ATTR __spi_comm(char *dat, int len, uint32_t *recvData, int recvDataLen) { + unsigned int length = 0; + + SpiData spiData; + + spiData.cmd = 2; + spiData.cmdLen = 0; + spiData.addr = NULL; + spiData.addrLen = 0; + + // float boot pin + gpio_output_set(0, 0, 0, (1 << 4)); + + // manual CS pin + gpio_output_set(0, (1 << 5), 0, 0); + memset(sendData, 0xCC, 0x14); + + // wait for ST to respond to CS interrupt + os_delay_us(50); + + // send request + memcpy(((void*)sendData), dat, len); + spiData.data = sendData; + spiData.dataLen = 0x14; + SPIMasterSendData(SpiNum_HSPI, &spiData); + + #define SPI_TIMEOUT 50000 + // give the ST time to be ready, up to 500ms + int i; + for (i = 0; (gpio_input_get() & (1 << 4)) && i < SPI_TIMEOUT; i++) { + os_delay_us(10); + system_soft_wdt_feed(); + } + + // TODO: handle this better + if (i == SPI_TIMEOUT) { + os_printf("ERROR: SPI receive failed\n"); + goto fail; + } + + // blank out recvData + memset(recvData, 0x00, 0x44); + + // receive the length + spiData.data = recvData; + spiData.dataLen = 4; + if(SPIMasterRecvData(SpiNum_HSPI, &spiData) == -1) { + // TODO: Handle gracefully. Maybe fail if len read fails? + os_printf("SPI: Failed to recv length\n"); + goto fail; + } + + length = recvData[0]; + if (length > 0x40) { + os_printf("SPI: BAD LENGTH RECEIVED %x\n", length); + length = 0; + goto fail; + } + + // got response, 0x40 works, 0x44 does not + spiData.data = recvData+1; + spiData.dataLen = (length+3)&(~3); // recvDataLen; + if(SPIMasterRecvData(SpiNum_HSPI, &spiData) == -1) { + // TODO: Handle gracefully. Maybe retry if payload failed. + os_printf("SPI: Failed to recv payload\n"); + length = 0; + goto fail; + } + +fail: + // clear CS + gpio_output_set((1 << 5), 0, 0, 0); + + // set boot pin back + gpio_output_set((1 << 4), 0, (1 << 4), 0); + + return length; +} + +int ICACHE_FLASH_ATTR spi_comm(char *dat, int len, uint32_t *recvData, int recvDataLen) { + // blink the led during SPI comm + if (GPIO_REG_READ(GPIO_OUT_ADDRESS) & (1 << pin)) { + // set gpio low + gpio_output_set(0, (1 << pin), 0, 0); + } else { + // set gpio high + gpio_output_set((1 << pin), 0, 0, 0); + } + + return __spi_comm(dat, len, recvData, recvDataLen); +} + +static void ICACHE_FLASH_ATTR tcp_rx_cb(void *arg, char *data, uint16_t len) { + // nothing too big + if (len > 0x14) return; + + // do the SPI comm + spi_comm(data, len, recvData, 0x40); + + espconn_send(&tcp_conn, recvData, 0x44); +} + +void ICACHE_FLASH_ATTR tcp_connect_cb(void *arg) { + struct espconn *conn = (struct espconn *)arg; + espconn_set_opt(&tcp_conn, ESPCONN_NODELAY); + espconn_regist_recvcb(conn, tcp_rx_cb); +} + +// must be 0x44, because we can fit 4 more +uint8_t buf[0x44*0x10]; +int queue_send_len = -1; + +void ICACHE_FLASH_ATTR poll_can(void *arg) { + uint8_t timerRecvData[0x44] = {0}; + int i = 0; + int j; + + while (i < 0x40) { + int len = spi_comm("\x01\x00\x00\x00", 4, timerRecvData, 0x40); + if (len == 0) break; + if (len > 0x40) { os_printf("SPI LENGTH ERROR!"); break; } + + // if it sends it, assume it's valid CAN + for (j = 0; j < len; j += 0x10) { + memcpy(buf + i*0x10, (timerRecvData+4)+j, 0x10); + i++; + } + } + + if (i != 0) { + int ret = espconn_sendto(&inter_conn, buf, i*0x10); + if (ret != 0) { + os_printf("send failed: %d\n", ret); + queue_send_len = i*0x10; + } else { + queue_send_len = -1; + } + } +} + +int udp_countdown = 0; + +static volatile os_timer_t udp_callback; +void ICACHE_FLASH_ATTR udp_callback_func(void *arg) { + if (queue_send_len == -1) { + poll_can(NULL); + } else { + int ret = espconn_sendto(&inter_conn, buf, queue_send_len); + if (ret == 0) { + queue_send_len = -1; + } + } + if (udp_countdown > 0) { + os_timer_arm(&udp_callback, 5, 0); + udp_countdown--; + } else { + os_printf("UDP timeout\n"); + } +} + +void ICACHE_FLASH_ATTR inter_recv_cb(void *arg, char *pusrdata, unsigned short length) { + remot_info *premot = NULL; + if (espconn_get_connection_info(&inter_conn,&premot,0) == ESPCONN_OK) { + inter_conn.proto.udp->remote_port = premot->remote_port; + inter_conn.proto.udp->remote_ip[0] = premot->remote_ip[0]; + inter_conn.proto.udp->remote_ip[1] = premot->remote_ip[1]; + inter_conn.proto.udp->remote_ip[2] = premot->remote_ip[2]; + inter_conn.proto.udp->remote_ip[3] = premot->remote_ip[3]; + + + if (udp_countdown == 0) { + os_printf("UDP recv\n"); + udp_countdown = 200*5; + + // start 5 second timer + os_timer_disarm(&udp_callback); + os_timer_setfn(&udp_callback, (os_timer_func_t *)udp_callback_func, NULL); + os_timer_arm(&udp_callback, 5, 0); + } else { + udp_countdown = 200*5; + } + } +} + +void ICACHE_FLASH_ATTR wifi_init() { + // default ssid and password + memset(ssid, 0, 32); + os_sprintf(ssid, "panda-%08x-BROKEN", system_get_chip_id()); + char password[] = "testing123"; + + // fetch secure ssid and password + // update, try 3 times + for (int i = 0; i < 3; i++) { + uint8_t digest[SHA_DIGEST_SIZE]; + char resp[0x20]; + __spi_comm("\x00\x00\x00\x00\x40\xD0\x00\x00\x00\x00\x20\x00", 0xC, recvData, 0x40); + memcpy(resp, recvData+1, 0x20); + + SHA_hash(resp, 0x1C, digest); + if (memcmp(digest, resp+0x1C, 4) == 0) { + // OTP is valid + memcpy(ssid+6, resp, 0x10); + memcpy(password, resp+0x10, 10); + break; + } + os_delay_us(50000); + } + + // start wifi AP + wifi_set_opmode(SOFTAP_MODE); + struct softap_config config; + wifi_softap_get_config(&config); + strcpy(config.ssid, ssid); + strcpy(config.password, password); + config.ssid_len = strlen(ssid); + config.authmode = AUTH_WPA2_PSK; + config.beacon_interval = 100; + config.max_connection = 10; + wifi_softap_set_config(&config); + + //set IP + wifi_softap_dhcps_stop(); //stop DHCP before setting static IP + struct ip_info ip_config; + IP4_ADDR(&ip_config.ip, 192, 168, 0, 10); + IP4_ADDR(&ip_config.gw, 0, 0, 0, 0); + IP4_ADDR(&ip_config.netmask, 255, 255, 255, 0); + wifi_set_ip_info(SOFTAP_IF, &ip_config); + int stupid_gateway = 0; + wifi_softap_set_dhcps_offer_option(OFFER_ROUTER, &stupid_gateway); + wifi_softap_dhcps_start(); + + // setup tcp server + tcp_proto.local_port = 1337; + tcp_conn.type = ESPCONN_TCP; + tcp_conn.state = ESPCONN_NONE; + tcp_conn.proto.tcp = &tcp_proto; + espconn_regist_connectcb(&tcp_conn, tcp_connect_cb); + espconn_accept(&tcp_conn); + espconn_regist_time(&tcp_conn, 60, 0); // 60s timeout for all connections + + // setup inter server + inter_proto.local_port = 1338; + const char udp_remote_ip[4] = {255, 255, 255, 255}; + os_memcpy(inter_proto.remote_ip, udp_remote_ip, 4); + inter_proto.remote_port = 1338; + + inter_conn.type = ESPCONN_UDP; + inter_conn.proto.udp = &inter_proto; + + espconn_regist_recvcb(&inter_conn, inter_recv_cb); + + espconn_create(&inter_conn); +} + +#define LOOP_PRIO 2 +#define QUEUE_SIZE 1 +static os_event_t my_queue[QUEUE_SIZE]; +void loop(); + +void ICACHE_FLASH_ATTR web_init(); +void ICACHE_FLASH_ATTR elm327_init(); + +void ICACHE_FLASH_ATTR user_init() { + // init gpio subsystem + gpio_init(); + + // configure UART TXD to be GPIO1, set as output + PIN_FUNC_SELECT(PERIPHS_IO_MUX_U0TXD_U, FUNC_GPIO1); + gpio_output_set(0, 0, (1 << pin), 0); + + // configure SPI + SpiAttr hSpiAttr; + hSpiAttr.bitOrder = SpiBitOrder_MSBFirst; + hSpiAttr.speed = SpiSpeed_10MHz; + hSpiAttr.mode = SpiMode_Master; + hSpiAttr.subMode = SpiSubMode_0; + + // TODO: is one of these CS? + WRITE_PERI_REG(PERIPHS_IO_MUX, 0x105); + PIN_FUNC_SELECT(PERIPHS_IO_MUX_MTDI_U, 2); // configure io to spi mode + PIN_FUNC_SELECT(PERIPHS_IO_MUX_MTCK_U, 2); // configure io to spi mode + PIN_FUNC_SELECT(PERIPHS_IO_MUX_MTMS_U, 2); // configure io to spi mode + PIN_FUNC_SELECT(PERIPHS_IO_MUX_MTDO_U, 2); // configure io to spi mode + SPIInit(SpiNum_HSPI, &hSpiAttr); + //SPICsPinSelect(SpiNum_HSPI, SpiPinCS_1); + + // configure UART TXD to be GPIO1, set as output + PIN_FUNC_SELECT(PERIPHS_IO_MUX_GPIO5_U, FUNC_GPIO5); + gpio_output_set(0, 0, (1 << 5), 0); + gpio_output_set((1 << 5), 0, 0, 0); + + // uart init + uart_init(BIT_RATE_115200, BIT_RATE_115200); + + // led init + PIN_FUNC_SELECT(PERIPHS_IO_MUX_GPIO2_U, FUNC_GPIO2); + gpio_output_set(0, (1 << pin), (1 << pin), 0); + + os_printf("hello\n"); + + // needs SPI + wifi_init(); + + // support ota upgrades + elm327_init(); + web_init(); + + // set gpio high, so LED is off by default + for (int i = 0; i < 5; i++) { + gpio_output_set(0, (1 << pin), 0, 0); + os_delay_us(50000); + gpio_output_set((1 << pin), 0, 0, 0); + os_delay_us(50000); + } + + // jump to OS + system_os_task(loop, LOOP_PRIO, my_queue, QUEUE_SIZE); + system_os_post(LOOP_PRIO, 0, 0); +} + + +void ICACHE_FLASH_ATTR loop(os_event_t *events) { + system_os_post(LOOP_PRIO, 0, 0); +} + diff --git a/boardesp/user_config.h b/boardesp/user_config.h new file mode 100644 index 0000000000..e69de29bb2 diff --git a/boardesp/webserver.c b/boardesp/webserver.c new file mode 100644 index 0000000000..66b1185fef --- /dev/null +++ b/boardesp/webserver.c @@ -0,0 +1,373 @@ +#include "stdlib.h" +#include "ets_sys.h" +#include "osapi.h" +#include "gpio.h" +#include "mem.h" +#include "os_type.h" +#include "user_interface.h" +#include "espconn.h" +#include "upgrade.h" + +#include "crypto/rsa.h" +#include "crypto/sha.h" + +#include "obj/gitversion.h" +#include "obj/cert.h" + +#define max(a,b) ((a) > (b) ? (a) : (b)) +#define min(a,b) ((a) < (b) ? (a) : (b)) +#define espconn_send_string(conn, x) espconn_send(conn, x, strlen(x)) + +#define MAX_RESP 0x800 +char resp[MAX_RESP]; +char pageheader[] = "HTTP/1.0 200 OK\nContent-Type: text/html\n\n" +"\n" +"\n" +"\n" +"Panda\n" +"\n" +"\n" +"
This is your comma.ai panda\n\n"
+"It's open source. Find the code here\n"
+"Designed to work with our dashcam, chffr\n";
+
+char pagefooter[] = "
\n" +"\n" +"\n"; + +char OK_header[] = "HTTP/1.0 200 OK\nContent-Type: text/html\n\n"; + +static struct espconn web_conn; +static esp_tcp web_proto; +extern char ssid[]; + +char *st_firmware; +int real_content_length, content_length = 0; +char *st_firmware_ptr; +LOCAL os_timer_t ota_reboot_timer; + +#define FIRMWARE_SIZE 503808 + +typedef struct { + uint16_t ep; + uint16_t extra_len; + union { + struct { + uint8_t request_type; + uint8_t request; + uint16_t value; + uint16_t index; + uint16_t length; + } control; + uint8_t data[0x10]; + } u; +} usb_msg; + +int ICACHE_FLASH_ATTR usb_cmd(int ep, int len, int request, + int value, int index, char *data) { + usb_msg usb = {0}; + + usb.ep = ep; + usb.extra_len = (ep == 0) ? 0 : len; + if (ep == 0) { + usb.u.control.request_type = 0xc0; + usb.u.control.request = request; + usb.u.control.value = value; + usb.u.control.index = index; + } else { + memcpy(&usb.u.data, data, usb.extra_len); + } + + uint32_t recv[0x44/4]; + spi_comm(&usb, sizeof(usb), recv, 0x40); + + return recv[0]; +} + + +void ICACHE_FLASH_ATTR st_flash() { + if (st_firmware != NULL) { + // boot mode + os_printf("st_flash: enter boot mode\n"); + st_set_boot_mode(1); + + // echo + os_printf("st_flash: wait for echo\n"); + for (int i = 0; i < 10; i++) { + os_printf(" attempt: %d\n", i); + if (usb_cmd(0, 0, 0xb0, 0, 0, NULL) > 0) break; + } + + // unlock flash + os_printf("st_flash: unlock flash\n"); + usb_cmd(0, 0, 0xb1, 0, 0, NULL); + + // erase sector 1 + os_printf("st_flash: erase sector 1\n"); + usb_cmd(0, 0, 0xb2, 1, 0, NULL); + + if (real_content_length >= 16384) { + // erase sector 2 + os_printf("st_flash: erase sector 2\n"); + usb_cmd(0, 0, 0xb2, 2, 0, NULL); + } + + // real content length will always be 0x10 aligned + os_printf("st_flash: flashing\n"); + for (int i = 0; i < real_content_length; i += 0x10) { + int rl = min(0x10, real_content_length-i); + usb_cmd(2, rl, 0, 0, 0, &st_firmware[i]); + system_soft_wdt_feed(); + } + + // reboot into normal mode + os_printf("st_flash: rebooting\n"); + usb_cmd(0, 0, 0xd8, 0, 0, NULL); + + // done with this + os_free(st_firmware); + st_firmware = NULL; + } +} + +typedef enum { + NOT_STARTED, + CONNECTION_ESTABLISHED, + RECEIVING_HEADER, + RECEIVING_ST_FIRMWARE, + RECEIVING_ESP_FIRMWARE, + REBOOTING, + ERROR +} web_state_t; + +web_state_t state = NOT_STARTED; +int esp_address, esp_address_erase_limit, start_address; + +void ICACHE_FLASH_ATTR hexdump(char *data, int len) { + int i; + for (i=0;iClient" + "" + "\n"); + + ets_strcat(resp, pagefooter); + + espconn_send_string(&web_conn, resp); + espconn_disconnect(conn); + + } else if (memcmp(data, "GET /set_property?usb_mode=", 27) == 0) { + char mode_value = data[27] - '0'; + if (mode_value >= '\x00' && mode_value <= '\x02') { + memset(resp, 0, MAX_RESP); + char set_usb_mode_packet[] = "\x00\x00\x00\x00\x40\xE6\x00\x00\x00\x00\x40\x00"; + set_usb_mode_packet[6] = mode_value; + uint32_t recvData[1]; + spi_comm(set_usb_mode_packet, 0xC, recvData, 0); + os_sprintf(resp, "%sUSB Mode set to %02x\n\n", OK_header, mode_value); + espconn_send_string(&web_conn, resp); + espconn_disconnect(conn); + } + } else if (memcmp(data, "PUT /stupdate ", 14) == 0) { + os_printf("init st firmware\n"); + char *cl = strstr(data, "Content-Length: "); + if (cl != NULL) { + // get content length + cl += strlen("Content-Length: "); + content_length = skip_atoi(&cl); + os_printf("with content length %d\n", content_length); + + // should be small enough to fit in RAM + real_content_length = (content_length+0xF)&(~0xF); + st_firmware_ptr = st_firmware = os_malloc(real_content_length); + memset(st_firmware, 0, real_content_length); + state = RECEIVING_ST_FIRMWARE; + } + + } else if ((memcmp(data, "PUT /espupdate1 ", 16) == 0) || + (memcmp(data, "PUT /espupdate2 ", 16) == 0)) { + // 0x1000 = user1.bin + // 0x81000 = user2.bin + // 0x3FE000 = blank.bin + os_printf("init esp firmware\n"); + char *cl = strstr(data, "Content-Length: "); + if (cl != NULL) { + // get content length + cl += strlen("Content-Length: "); + content_length = skip_atoi(&cl); + os_printf("with content length %d\n", content_length); + + // setup flashing + uint8_t current = system_upgrade_userbin_check(); + if (data[14] == '2' && current == UPGRADE_FW_BIN1) { + os_printf("flashing boot2.bin\n"); + state = RECEIVING_ESP_FIRMWARE; + esp_address = 4*1024 + FIRMWARE_SIZE + 16*1024 + 4*1024; + } else if (data[14] == '1' && current == UPGRADE_FW_BIN2) { + os_printf("flashing boot1.bin\n"); + state = RECEIVING_ESP_FIRMWARE; + esp_address = 4*1024; + } else { + espconn_send_string(&web_conn, "HTTP/1.0 404 Not Found\nContent-Type: text/html\n\nwrong!\n"); + espconn_disconnect(conn); + } + esp_address_erase_limit = esp_address; + start_address = esp_address; + } + } else { + espconn_send_string(&web_conn, "HTTP/1.0 404 Not Found\nContent-Type: text/html\n\n404 Not Found!\n"); + espconn_disconnect(conn); + } + } else if (state == RECEIVING_ST_FIRMWARE) { + os_printf("receiving st firmware: %d/%d\n", len, content_length); + memcpy(st_firmware_ptr, data, min(content_length, len)); + st_firmware_ptr += len; + content_length -= len; + + if (content_length <= 0 && real_content_length > 1000) { + state = NOT_STARTED; + os_printf("done!\n"); + espconn_send_string(&web_conn, "HTTP/1.0 200 OK\nContent-Type: text/html\n\nsuccess!\n"); + espconn_disconnect(conn); + + // reboot + os_printf("Scheduling st_flash in 100ms.\n"); + os_timer_disarm(&ota_reboot_timer); + os_timer_setfn(&ota_reboot_timer, (os_timer_func_t *)st_flash, NULL); + os_timer_arm(&ota_reboot_timer, 100, 0); + } + } else if (state == RECEIVING_ESP_FIRMWARE) { + if ((esp_address+len) < (start_address + FIRMWARE_SIZE)) { + os_printf("receiving esp firmware: %d/%d -- 0x%x - 0x%x\n", len, content_length, + esp_address, esp_address_erase_limit); + content_length -= len; + while (esp_address_erase_limit < (esp_address + len)) { + os_printf("erasing 0x%X\n", esp_address_erase_limit); + spi_flash_erase_sector(esp_address_erase_limit / SPI_FLASH_SEC_SIZE); + esp_address_erase_limit += SPI_FLASH_SEC_SIZE; + } + SpiFlashOpResult res = spi_flash_write(esp_address, data, len); + if (res != SPI_FLASH_RESULT_OK) { + os_printf("flash fail @ 0x%x\n", esp_address); + } + esp_address += len; + + if (content_length == 0) { + + char digest[SHA_DIGEST_SIZE]; + uint32_t rsa[RSANUMBYTES/4]; + uint32_t dat[0x80/4]; + int ll; + spi_flash_read(esp_address-RSANUMBYTES, rsa, RSANUMBYTES); + + // 32-bit aligned accesses only + SHA_CTX ctx; + SHA_init(&ctx); + for (ll = start_address; ll < esp_address-RSANUMBYTES; ll += 0x80) { + spi_flash_read(ll, dat, 0x80); + SHA_update(&ctx, dat, min((esp_address-RSANUMBYTES)-ll, 0x80)); + } + memcpy(digest, SHA_final(&ctx), SHA_DIGEST_SIZE); + + if (RSA_verify(&releaseesp_rsa_key, rsa, RSANUMBYTES, digest, SHA_DIGEST_SIZE) || + #ifdef ALLOW_DEBUG + RSA_verify(&debugesp_rsa_key, rsa, RSANUMBYTES, digest, SHA_DIGEST_SIZE) + #else + false + #endif + ) { + os_printf("RSA verify success!\n"); + espconn_send_string(&web_conn, "HTTP/1.0 200 OK\nContent-Type: text/html\n\nsuccess!\n"); + system_upgrade_flag_set(UPGRADE_FLAG_FINISH); + + // reboot + os_printf("Scheduling reboot.\n"); + os_timer_disarm(&ota_reboot_timer); + os_timer_setfn(&ota_reboot_timer, (os_timer_func_t *)system_upgrade_reboot, NULL); + os_timer_arm(&ota_reboot_timer, 2000, 0); + } else { + os_printf("RSA verify FAILURE\n"); + espconn_send_string(&web_conn, "HTTP/1.0 500 Internal Server Error\nContent-Type: text/html\n\nrsa verify fail\n"); + } + espconn_disconnect(conn); + } + } + } +} + +void ICACHE_FLASH_ATTR web_tcp_connect_cb(void *arg) { + state = CONNECTION_ESTABLISHED; + struct espconn *conn = (struct espconn *)arg; + espconn_set_opt(&web_conn, ESPCONN_NODELAY); + espconn_regist_recvcb(conn, web_rx_cb); +} + +void ICACHE_FLASH_ATTR web_init() { + web_proto.local_port = 80; + web_conn.type = ESPCONN_TCP; + web_conn.state = ESPCONN_NONE; + web_conn.proto.tcp = &web_proto; + espconn_regist_connectcb(&web_conn, web_tcp_connect_cb); + espconn_accept(&web_conn); +} + diff --git a/buy.png b/buy.png new file mode 100644 index 0000000000..72ffd3cbe8 --- /dev/null +++ b/buy.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cbecb2af4e0c8653824353eed703bf6b4caa201940f915f1a7491ab07a42aef4 +size 4107 diff --git a/certs/debug b/certs/debug new file mode 100644 index 0000000000..39864b6b1a --- /dev/null +++ b/certs/debug @@ -0,0 +1,15 @@ +-----BEGIN RSA PRIVATE KEY----- +MIICXQIBAAKBgQC948lnRo4x44Rd7Y8bQAML4aKDC4XRx958fHV8K6+FbCaP1Z42 +U2kX0yygak0LjoDutpgObmGHZA+Iz3HeUD6VGjr/teN24vPk+A95cRsjt8rgmGQ9 +6HNjaNgjR+gl1F9XxFimMzir82Xpl1ekTueJNXa7ia5HVH1nFdiksOKHGQIDAQAB +AoGAQuPw2I6EHJLW1/eNB75e1FqhUqRGeYV8nEGDaUBCTi+wzc4kM2LijF/5QnDv +vvht9qkfm0XK2VSoHDtnEzcVM/l1ksb68n4R/1nUooAWY6cQI7dCSk/A6yS1EJFg +BXsgGbT/65khw9pzBW2zVtMVcVNWFayqfCO1I9WcDdA1x1kCQQDfrhoZTZNoDEUE +JKM4fiUdWr1h3Aw8KLJFFexSWeGDwo+qqnujYcKWkHa9qaH1RG5x8Kir9s9Oi4Js +mzKwov8fAkEA2VPJPWxJ4vVQpXle6wC1nyoL7s739yxMWFcabvkzDDhlIVBNdVJd +gZKsFWV7QnVNdDMjn9D27FwKu3i2D+kKxwJBANp1SMojqO765MEKI1t+YDNONx6H +cm+i85Fjuv4nCIjOEdCGVuCYDxtMFpxgO2y3HAMuHx5sm8XDnWsDHLvFRdMCQD7V +XqWHnYUk8AAnqy2+ssQl3/VXmZG5GQmhhV74Za3u0C5ljT+SZL6FrYMyKAT67T3f +WzllrT6BDglNyTWoZxkCQQCt0XSoGM3603GGYNt6AUlGSgtXSo/2Px7odGUtQoKA +FH9q6FVMYpQJ38spZxIGufZJmLP8LLg6YIWJj1F+akxr +-----END RSA PRIVATE KEY----- diff --git a/certs/debug.pub b/certs/debug.pub new file mode 100644 index 0000000000..00e219d7bb --- /dev/null +++ b/certs/debug.pub @@ -0,0 +1 @@ +ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQC948lnRo4x44Rd7Y8bQAML4aKDC4XRx958fHV8K6+FbCaP1Z42U2kX0yygak0LjoDutpgObmGHZA+Iz3HeUD6VGjr/teN24vPk+A95cRsjt8rgmGQ96HNjaNgjR+gl1F9XxFimMzir82Xpl1ekTueJNXa7ia5HVH1nFdiksOKHGQ== batman@y840 diff --git a/certs/debugesp b/certs/debugesp new file mode 100644 index 0000000000..789beaac19 --- /dev/null +++ b/certs/debugesp @@ -0,0 +1,15 @@ +-----BEGIN RSA PRIVATE KEY----- +MIICXAIBAAKBgQCjIHvrSCWN0Nec6ozbImYik30PIF7JSWgdwDKTxSJ05RM3pj5E +LQEGt3qcaVrTokO68tpt5Gu1p6ZsNqWg7iVTW9M7Qj7IH45YDzQP/PSRjgSosQA6 +6f5Gokba5QrW38myqimvj+0p+YH+CNGCBRlTUQGCO8uLCspMZneRSLPW9QIDAQAB +AoGADaUn+HRef9BaWMvd4G6uMHI54cwJYbj8NpDfKjExQqnuw5bqWnWRQmiSnwbJ +DC7kj3zE/LBAuj890ot3q1CAWqh47ZICZfoX9Qbi5TpvIHFCGy6YkOliF6iIQhR2 +4+zNKTAA0zNKskOM25PdI+grK1Ni/bEofSA6TrqvEwsmxnkCQQDVp9FUUor2Bo/h +/3oAIP51LTw7vfpztYbJr+BDV63czV2DLXzSwzeNrwH4sA3oy1mjUgMBBgAarNGE +DYlc4H5jAkEAw3UCHzzXPlxkw2QGp7nBly5y3p80Uqc31NuYz8rdX/U8KTngi2No +Ft/SGCEXNpeYbToj+WK3RJJ2Ey0mK8+IxwJAcpGd/5CPsaQNLcw4WK9Yo+8Q2Jxk +G/4gfDCSmqn+smNxnLEcuUwzkwdgkEGgA9BfjeOhdsAH+EXpx90WZrZ/LwJBAK0k +jq+rTqUQZbZsejTEKYjJ/bnV4BzDwoKN0Q1pkLc7X4LJoW74rTFuLgdv8MdMfRtt +IIb/eoeFEpGkMicnHesCQHgR7BTUGBM6Uxam7RCdsgVsxoHBma21E/44ivWUMZzN +3oVt0mPnjS4speOlqwED5pCJ7yw7jwLPFMs8kNxuIKU= +-----END RSA PRIVATE KEY----- diff --git a/certs/debugesp.pub b/certs/debugesp.pub new file mode 100644 index 0000000000..3afcf3988e --- /dev/null +++ b/certs/debugesp.pub @@ -0,0 +1 @@ +ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQCjIHvrSCWN0Nec6ozbImYik30PIF7JSWgdwDKTxSJ05RM3pj5ELQEGt3qcaVrTokO68tpt5Gu1p6ZsNqWg7iVTW9M7Qj7IH45YDzQP/PSRjgSosQA66f5Gokba5QrW38myqimvj+0p+YH+CNGCBRlTUQGCO8uLCspMZneRSLPW9Q== batman@y840 diff --git a/certs/release.pub b/certs/release.pub new file mode 100644 index 0000000000..19066e29a7 --- /dev/null +++ b/certs/release.pub @@ -0,0 +1 @@ +ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDGN9GU2nOc0kKq6vdZI5qUMzHt234ngqofrgCFFxL0D2Whex0zACp9gar0HZp+bvtpoSgU/Ev8wexNKr+A9QTradljiuxi5ctrOra9k+wxqNj63Wrcu4+wU5UnJEVf/buV4jCOFffMT8z3PO4imt8LzHuEIC/m/ASKVYyvuvBRQQ== batman@y840 diff --git a/certs/releaseesp.pub b/certs/releaseesp.pub new file mode 100644 index 0000000000..1d1d54bb7e --- /dev/null +++ b/certs/releaseesp.pub @@ -0,0 +1 @@ +ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDN4pVyGuJJSde1l3Fjay8qPxog09DsAJZtYPk+armoYO1L6YKReUTcMNyHQYZZMZFmhCdgjCgTIF2QYWMoP4KSe8l6JF04YPP51dIgefc6UXjtlSI8Pyutr0v9xXjSfsVm3RAJxDSHgzs9AoMsluKCL+LhAR1nd7cuHXITJ80O4w== batman@y840 diff --git a/common/version.mk b/common/version.mk new file mode 100644 index 0000000000..cc42223da3 --- /dev/null +++ b/common/version.mk @@ -0,0 +1,18 @@ +ifeq ($(RELEASE),1) + BUILD_TYPE = "RELEASE" +else + BUILD_TYPE = "DEBUG" +endif + +ifneq ($(wildcard ../.git/HEAD),) +obj/gitversion.h: ../VERSION ../.git/HEAD ../.git/index + echo "const uint8_t gitversion[] = \"$(shell cat ../VERSION)-$(shell git rev-parse --short=8 HEAD)-$(BUILD_TYPE)\";" > $@ +else +ifneq ($(wildcard ../../.git/modules/panda/HEAD),) +obj/gitversion.h: ../VERSION ../../.git/modules/panda/HEAD ../../.git/modules/panda/index + echo "const uint8_t gitversion[] = \"$(shell cat ../VERSION)-$(shell git rev-parse --short=8 HEAD)-$(BUILD_TYPE)\";" > $@ +else +obj/gitversion.h: ../VERSION + echo "const uint8_t gitversion[] = \"$(shell cat ../VERSION)-unknown-$(BUILD_TYPE)\";" > $@ +endif +endif diff --git a/crypto/getcertheader.py b/crypto/getcertheader.py new file mode 100755 index 0000000000..75d04e977a --- /dev/null +++ b/crypto/getcertheader.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python +import sys +import struct +from Crypto.PublicKey import RSA + +def egcd(a, b): + if a == 0: + return (b, 0, 1) + else: + g, y, x = egcd(b % a, a) + return (g, x - (b // a) * y, y) + +def modinv(a, m): + g, x, y = egcd(a, m) + if g != 1: + raise Exception('modular inverse does not exist') + else: + return x % m + +def to_c_string(x): + mod = (hex(x)[2:-1].rjust(0x100, '0')) + hh = ''.join('\\x'+mod[i:i+2] for i in range(0, 0x100, 2)) + return hh + +def to_c_uint32(x): + nums = [] + for i in range(0x20): + nums.append(x%(2**32)) + x /= (2**32) + return "{"+'U,'.join(map(str, nums))+"U}" + +for fn in sys.argv[1:]: + rsa = RSA.importKey(open(fn).read()) + rr = pow(2**1024, 2, rsa.n) + n0inv = 2**32 - modinv(rsa.n, 2**32) + + cname = fn.split("/")[-1].split(".")[0] + "_rsa_key" + + print 'RSAPublicKey '+cname+' = {.len = 0x20,' + print ' .n0inv = %dU,' % n0inv + print ' .n = %s,' % to_c_uint32(rsa.n) + print ' .rr = %s,' % to_c_uint32(rr) + print ' .exponent = %d,' % rsa.e + print '};' + + diff --git a/crypto/hash-internal.h b/crypto/hash-internal.h new file mode 100644 index 0000000000..05ec3ec9fd --- /dev/null +++ b/crypto/hash-internal.h @@ -0,0 +1,63 @@ +/* + * Copyright 2007 The Android Open Source Project + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * 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. + * * Neither the name of Google Inc. 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 Google Inc. ``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 Google Inc. 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. + */ + +#ifndef SYSTEM_CORE_INCLUDE_MINCRYPT_HASH_INTERNAL_H_ +#define SYSTEM_CORE_INCLUDE_MINCRYPT_HASH_INTERNAL_H_ + +#include "stdint.h" + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +struct HASH_CTX; // forward decl + +typedef struct HASH_VTAB { + void (* const init)(struct HASH_CTX*); + void (* const update)(struct HASH_CTX*, const void*, int); + const uint8_t* (* const final)(struct HASH_CTX*); + const uint8_t* (* const hash)(const void*, int, uint8_t*); + int size; +} HASH_VTAB; + +typedef struct HASH_CTX { + const HASH_VTAB * f; + uint64_t count; + uint8_t buf[64]; + uint32_t state[8]; // upto SHA2 +} HASH_CTX; + +#define HASH_init(ctx) (ctx)->f->init(ctx) +#define HASH_update(ctx, data, len) (ctx)->f->update(ctx, data, len) +#define HASH_final(ctx) (ctx)->f->final(ctx) +#define HASH_hash(data, len, digest) (ctx)->f->hash(data, len, digest) +#define HASH_size(ctx) (ctx)->f->size + +#ifdef __cplusplus +} +#endif // __cplusplus + +#endif // SYSTEM_CORE_INCLUDE_MINCRYPT_HASH_INTERNAL_H_ diff --git a/crypto/rsa.c b/crypto/rsa.c new file mode 100644 index 0000000000..24171e8790 --- /dev/null +++ b/crypto/rsa.c @@ -0,0 +1,294 @@ +/* rsa.c +** +** Copyright 2012, The Android Open Source Project +** +** Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * 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. +** * Neither the name of Google Inc. 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 Google Inc. ``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 Google Inc. 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. +*/ + +#include "rsa.h" +#include "sha.h" + +// a[] -= mod +static void subM(const RSAPublicKey* key, + uint32_t* a) { + int64_t A = 0; + int i; + for (i = 0; i < key->len; ++i) { + A += (uint64_t)a[i] - key->n[i]; + a[i] = (uint32_t)A; + A >>= 32; + } +} + +// return a[] >= mod +static int geM(const RSAPublicKey* key, + const uint32_t* a) { + int i; + for (i = key->len; i;) { + --i; + if (a[i] < key->n[i]) return 0; + if (a[i] > key->n[i]) return 1; + } + return 1; // equal +} + +// montgomery c[] += a * b[] / R % mod +static void montMulAdd(const RSAPublicKey* key, + uint32_t* c, + const uint32_t a, + const uint32_t* b) { + uint64_t A = (uint64_t)a * b[0] + c[0]; + uint32_t d0 = (uint32_t)A * key->n0inv; + uint64_t B = (uint64_t)d0 * key->n[0] + (uint32_t)A; + int i; + + for (i = 1; i < key->len; ++i) { + A = (A >> 32) + (uint64_t)a * b[i] + c[i]; + B = (B >> 32) + (uint64_t)d0 * key->n[i] + (uint32_t)A; + c[i - 1] = (uint32_t)B; + } + + A = (A >> 32) + (B >> 32); + + c[i - 1] = (uint32_t)A; + + if (A >> 32) { + subM(key, c); + } +} + +// montgomery c[] = a[] * b[] / R % mod +static void montMul(const RSAPublicKey* key, + uint32_t* c, + const uint32_t* a, + const uint32_t* b) { + int i; + for (i = 0; i < key->len; ++i) { + c[i] = 0; + } + for (i = 0; i < key->len; ++i) { + montMulAdd(key, c, a[i], b); + } +} + +// In-place public exponentiation. +// Input and output big-endian byte array in inout. +static void modpow(const RSAPublicKey* key, + uint8_t* inout) { + uint32_t a[RSANUMWORDS]; + uint32_t aR[RSANUMWORDS]; + uint32_t aaR[RSANUMWORDS]; + uint32_t* aaa = 0; + int i; + + // Convert from big endian byte array to little endian word array. + for (i = 0; i < key->len; ++i) { + uint32_t tmp = + (inout[((key->len - 1 - i) * 4) + 0] << 24) | + (inout[((key->len - 1 - i) * 4) + 1] << 16) | + (inout[((key->len - 1 - i) * 4) + 2] << 8) | + (inout[((key->len - 1 - i) * 4) + 3] << 0); + a[i] = tmp; + } + + if (key->exponent == 65537) { + aaa = aaR; // Re-use location. + montMul(key, aR, a, key->rr); // aR = a * RR / R mod M + for (i = 0; i < 16; i += 2) { + montMul(key, aaR, aR, aR); // aaR = aR * aR / R mod M + montMul(key, aR, aaR, aaR); // aR = aaR * aaR / R mod M + } + montMul(key, aaa, aR, a); // aaa = aR * a / R mod M + } else if (key->exponent == 3) { + aaa = aR; // Re-use location. + montMul(key, aR, a, key->rr); /* aR = a * RR / R mod M */ + montMul(key, aaR, aR, aR); /* aaR = aR * aR / R mod M */ + montMul(key, aaa, aaR, a); /* aaa = aaR * a / R mod M */ + } + + // Make sure aaa < mod; aaa is at most 1x mod too large. + if (geM(key, aaa)) { + subM(key, aaa); + } + + // Convert to bigendian byte array + for (i = key->len - 1; i >= 0; --i) { + uint32_t tmp = aaa[i]; + *inout++ = tmp >> 24; + *inout++ = tmp >> 16; + *inout++ = tmp >> 8; + *inout++ = tmp >> 0; + } +} + +// Expected PKCS1.5 signature padding bytes, for a keytool RSA signature. +// Has the 0-length optional parameter encoded in the ASN1 (as opposed to the +// other flavor which omits the optional parameter entirely). This code does not +// accept signatures without the optional parameter. + +/* +static const uint8_t sha_padding[RSANUMBYTES] = { + 0x00, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0x00, 0x30, 0x21, 0x30, + 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, + 0x05, 0x00, 0x04, 0x14, + + // 20 bytes of hash go here. + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 +}; +*/ + +static const uint8_t sha_padding_1024[RSANUMBYTES] = { + 0x00, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0x00, + + // 20 bytes of hash go here. + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 +}; + +// SHA-1 of PKCS1.5 signature sha_padding for 2048 bit, as above. +// At the location of the bytes of the hash all 00 are hashed. +/*static const uint8_t kExpectedPadShaRsa2048[SHA_DIGEST_SIZE] = { + 0xdc, 0xbd, 0xbe, 0x42, 0xd5, 0xf5, 0xa7, 0x2e, + 0x6e, 0xfc, 0xf5, 0x5d, 0xaf, 0x9d, 0xea, 0x68, + 0x7c, 0xfb, 0xf1, 0x67 +};*/ + +// Verify a 2048-bit RSA PKCS1.5 signature against an expected hash. +// Both e=3 and e=65537 are supported. hash_len may be +// SHA_DIGEST_SIZE (== 20) to indicate a SHA-1 hash, or +// SHA256_DIGEST_SIZE (== 32) to indicate a SHA-256 hash. No other +// values are supported. +// +// Returns 1 on successful verification, 0 on failure. +int RSA_verify(const RSAPublicKey *key, + const uint8_t *signature, + const int len, + const uint8_t *hash, + const int hash_len) { + uint8_t buf[RSANUMBYTES]; + int i; + //const uint8_t* padding_hash; + + if (key->len != RSANUMWORDS) { + return 0; // Wrong key passed in. + } + + if (len != sizeof(buf)) { + return 0; // Wrong input length. + } + + if (hash_len != SHA_DIGEST_SIZE) { + return 0; // Unsupported hash. + } + + if (key->exponent != 3 && key->exponent != 65537) { + return 0; // Unsupported exponent. + } + + for (i = 0; i < len; ++i) { // Copy input to local workspace. + buf[i] = signature[i]; + } + + modpow(key, buf); // In-place exponentiation. + +#ifdef TEST_RSA + printf("sig\n"); + for (i=0;i> (32 - (bits)))) + +static void SHA1_Transform(SHA_CTX* ctx) { + uint32_t W[80]; + uint32_t A, B, C, D, E; + uint8_t* p = ctx->buf; + int t; + + for(t = 0; t < 16; ++t) { + uint32_t tmp = *p++ << 24; + tmp |= *p++ << 16; + tmp |= *p++ << 8; + tmp |= *p++; + W[t] = tmp; + } + + for(; t < 80; t++) { + W[t] = rol(1,W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]); + } + + A = ctx->state[0]; + B = ctx->state[1]; + C = ctx->state[2]; + D = ctx->state[3]; + E = ctx->state[4]; + + for(t = 0; t < 80; t++) { + uint32_t tmp = rol(5,A) + E + W[t]; + + if (t < 20) + tmp += (D^(B&(C^D))) + 0x5A827999; + else if ( t < 40) + tmp += (B^C^D) + 0x6ED9EBA1; + else if ( t < 60) + tmp += ((B&C)|(D&(B|C))) + 0x8F1BBCDC; + else + tmp += (B^C^D) + 0xCA62C1D6; + + E = D; + D = C; + C = rol(30,B); + B = A; + A = tmp; + } + + ctx->state[0] += A; + ctx->state[1] += B; + ctx->state[2] += C; + ctx->state[3] += D; + ctx->state[4] += E; +} + +static const HASH_VTAB SHA_VTAB = { + SHA_init, + SHA_update, + SHA_final, + SHA_hash, + SHA_DIGEST_SIZE +}; + +void SHA_init(SHA_CTX* ctx) { + ctx->f = &SHA_VTAB; + ctx->state[0] = 0x67452301; + ctx->state[1] = 0xEFCDAB89; + ctx->state[2] = 0x98BADCFE; + ctx->state[3] = 0x10325476; + ctx->state[4] = 0xC3D2E1F0; + ctx->count = 0; +} + + +void SHA_update(SHA_CTX* ctx, const void* data, int len) { + int i = (int) (ctx->count & 63); + const uint8_t* p = (const uint8_t*)data; + + ctx->count += len; + + while (len--) { + ctx->buf[i++] = *p++; + if (i == 64) { + SHA1_Transform(ctx); + i = 0; + } + } +} + + +const uint8_t* SHA_final(SHA_CTX* ctx) { + uint8_t *p = ctx->buf; + uint64_t cnt = ctx->count * 8; + int i; + + SHA_update(ctx, (uint8_t*)"\x80", 1); + while ((ctx->count & 63) != 56) { + SHA_update(ctx, (uint8_t*)"\0", 1); + } + for (i = 0; i < 8; ++i) { + uint8_t tmp = (uint8_t) (cnt >> ((7 - i) * 8)); + SHA_update(ctx, &tmp, 1); + } + + for (i = 0; i < 5; i++) { + uint32_t tmp = ctx->state[i]; + *p++ = tmp >> 24; + *p++ = tmp >> 16; + *p++ = tmp >> 8; + *p++ = tmp >> 0; + } + + return ctx->buf; +} + +/* Convenience function */ +const uint8_t* SHA_hash(const void* data, int len, uint8_t* digest) { + SHA_CTX ctx; + SHA_init(&ctx); + SHA_update(&ctx, data, len); + memcpy(digest, SHA_final(&ctx), SHA_DIGEST_SIZE); + return digest; +} diff --git a/crypto/sha.h b/crypto/sha.h new file mode 100644 index 0000000000..4b51a531bf --- /dev/null +++ b/crypto/sha.h @@ -0,0 +1,51 @@ +/* + * Copyright 2005 The Android Open Source Project + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * 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. + * * Neither the name of Google Inc. 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 Google Inc. ``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 Google Inc. 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. + */ +#ifndef SYSTEM_CORE_INCLUDE_MINCRYPT_SHA1_H_ +#define SYSTEM_CORE_INCLUDE_MINCRYPT_SHA1_H_ + +#include "hash-internal.h" + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +typedef HASH_CTX SHA_CTX; + +void SHA_init(SHA_CTX* ctx); +void SHA_update(SHA_CTX* ctx, const void* data, int len); +const uint8_t* SHA_final(SHA_CTX* ctx); + +// Convenience method. Returns digest address. +// NOTE: *digest needs to hold SHA_DIGEST_SIZE bytes. +const uint8_t* SHA_hash(const void* data, int len, uint8_t* digest); + +#define SHA_DIGEST_SIZE 20 + +#ifdef __cplusplus +} +#endif // __cplusplus + +#endif // SYSTEM_CORE_INCLUDE_MINCRYPT_SHA1_H_ diff --git a/crypto/sign.py b/crypto/sign.py new file mode 100755 index 0000000000..159299271e --- /dev/null +++ b/crypto/sign.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python +import os +import sys +import struct +import hashlib +from Crypto.PublicKey import RSA + +rsa = RSA.importKey(open(sys.argv[3]).read()) + +with open(sys.argv[1]) as f: + dat = f.read() + +print "signing", len(dat), "bytes" + +with open(sys.argv[2], "wb") as f: + if os.getenv("SETLEN") is not None: + x = struct.pack("I", len(dat)) + dat[4:] + # mock signature of dat[4:] + dd = hashlib.sha1(dat[4:]).digest() + else: + x = dat + dd = hashlib.sha1(dat).digest() + print "hash:",dd.encode("hex") + dd = "\x00\x01" + "\xff"*0x69 + "\x00" + dd + rsa_out = pow(int(dd.encode("hex"), 16), rsa.d, rsa.n) + sig = (hex(rsa_out)[2:-1].rjust(0x100, '0')).decode("hex") + x += sig + f.write(x) + diff --git a/crypto/stdint.h b/crypto/stdint.h new file mode 100644 index 0000000000..67ac93ed75 --- /dev/null +++ b/crypto/stdint.h @@ -0,0 +1,4 @@ +#define uint8_t unsigned char +#define uint32_t unsigned int +#define int64_t long long +#define uint64_t unsigned long long diff --git a/docs/guide.pdf b/docs/guide.pdf new file mode 100644 index 0000000000..d5f38cfb62 --- /dev/null +++ b/docs/guide.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ca8d540a8c4fb43bbbc98441718c8777026e4503f1341b7c11f3187a370b92e8 +size 2873505 diff --git a/drivers/linux/.gitignore b/drivers/linux/.gitignore new file mode 100644 index 0000000000..93a6cde763 --- /dev/null +++ b/drivers/linux/.gitignore @@ -0,0 +1,6 @@ +.*.cmd +*.ko +.tmp_versions +Module.symvers +modules.order +*.mod.c diff --git a/drivers/linux/Makefile b/drivers/linux/Makefile new file mode 100644 index 0000000000..e5b1ec4219 --- /dev/null +++ b/drivers/linux/Makefile @@ -0,0 +1,18 @@ +VERSION=0.0.1 +obj-m+=panda.o + +link: + sudo dkms add `pwd` + +build: + sudo dkms build panda/$(VERSION) + +install: + sudo dkms install panda/$(VERSION) + +all: build install + +uninstall: + sudo dkms uninstall panda/$(VERSION) + sudo dkms remove panda/$(VERSION) --all + diff --git a/drivers/linux/README.md b/drivers/linux/README.md new file mode 100644 index 0000000000..81e95523ac --- /dev/null +++ b/drivers/linux/README.md @@ -0,0 +1,19 @@ +Installs the panda linux kernel driver using DKMS. + +This will allow the panda to work with tools such as `can-utils` + +prerequisites: + - `apt-get install dkms gcc linux-headers-$(uname -r) make sudo` + +installation: + - `make link` (only needed the first time. It will report an error on subsequent attempts to link) + - `make all` + - `make install` + +uninstall: + - `make uninstall` + +usage: + +You will need to bring it up using `sudo ifconfig can0 up` or +`sudo ip link set dev can0 up`, depending on your platform. diff --git a/drivers/linux/dkms.conf b/drivers/linux/dkms.conf new file mode 100644 index 0000000000..da9cba04a2 --- /dev/null +++ b/drivers/linux/dkms.conf @@ -0,0 +1,6 @@ +PACKAGE_NAME="panda" +PACKAGE_VERSION="0.0.1" +BUILT_MODULE_NAME[0]="panda" +DEST_MODULE_LOCATION[0]="/kernel/drivers/net/panda/" +AUTOINSTALL="yes" + diff --git a/drivers/linux/panda.c b/drivers/linux/panda.c new file mode 100644 index 0000000000..4c5980a9d2 --- /dev/null +++ b/drivers/linux/panda.c @@ -0,0 +1,613 @@ +/** + * @file panda.c + * @author Jessy Diamond Exum + * @date 16 June 2017 + * @version 0.1 + * @brief Driver for the Comma.ai Panda CAN adapter to allow it to be controlled via + * the Linux SocketCAN interface. + * @see https://github.com/commaai/panda for the full project. + * @see Inspired by net/can/usb/mcba_usb.c from Linux Kernel 4.12-rc4. + */ + +#include +#include +#include +#include // Macros used to mark up functions e.g., __init __exit +#include // Contains types, macros, functions for the kernel +#include // Core header for loading LKMs into the kernel +#include +#include + +/* vendor and product id */ +#define PANDA_MODULE_NAME "panda" +#define PANDA_VENDOR_ID 0XBBAA +#define PANDA_PRODUCT_ID 0XDDCC + +#define PANDA_MAX_TX_URBS 20 +#define PANDA_CTX_FREE PANDA_MAX_TX_URBS + +#define PANDA_USB_RX_BUFF_SIZE 0x40 +#define PANDA_USB_TX_BUFF_SIZE (sizeof(struct panda_usb_can_msg)) + +#define PANDA_NUM_CAN_INTERFACES 3 + +#define PANDA_CAN_TRANSMIT 1 +#define PANDA_CAN_EXTENDED 4 + +#define PANDA_BITRATE 500000 + +#define PANDA_DLC_MASK 0x0F + +struct panda_usb_ctx { + struct panda_inf_priv *priv; + u32 ndx; + u8 dlc; +}; + +struct panda_dev_priv; + +struct panda_inf_priv { + struct can_priv can; + struct panda_usb_ctx tx_context[PANDA_MAX_TX_URBS]; + struct net_device *netdev; + struct usb_anchor tx_submitted; + atomic_t free_ctx_cnt; + u8 interface_num; + u8 mcu_can_ifnum; + struct panda_dev_priv *priv_dev; +}; + +struct panda_dev_priv { + struct usb_device *udev; + struct device *dev; + struct usb_anchor rx_submitted; + struct panda_inf_priv *interfaces[PANDA_NUM_CAN_INTERFACES]; +}; + +struct __packed panda_usb_can_msg { + u32 rir; + u32 bus_dat_len; + u8 data[8]; +}; + +static const struct usb_device_id panda_usb_table[] = { + { USB_DEVICE(PANDA_VENDOR_ID, PANDA_PRODUCT_ID) }, + {} /* Terminating entry */ +}; + +MODULE_DEVICE_TABLE(usb, panda_usb_table); + + +// panda: CAN1 = 0 CAN2 = 1 CAN3 = 4 +const int can_numbering[] = {0,1,4}; + +struct panda_inf_priv * +panda_get_inf_from_bus_id(struct panda_dev_priv *priv_dev, int bus_id){ + int inf_num; + for(inf_num = 0; inf_num < PANDA_NUM_CAN_INTERFACES; inf_num++) + if(can_numbering[inf_num] == bus_id) + return priv_dev->interfaces[inf_num]; + return NULL; +} + +// CTX handling shamlessly ripped from mcba_usb.c linux driver +static inline void panda_init_ctx(struct panda_inf_priv *priv) +{ + int i = 0; + + for (i = 0; i < PANDA_MAX_TX_URBS; i++) { + priv->tx_context[i].ndx = PANDA_CTX_FREE; + priv->tx_context[i].priv = priv; + } + + atomic_set(&priv->free_ctx_cnt, ARRAY_SIZE(priv->tx_context)); +} + +static inline struct panda_usb_ctx *panda_usb_get_free_ctx(struct panda_inf_priv *priv, + struct can_frame *cf) +{ + int i = 0; + struct panda_usb_ctx *ctx = NULL; + + for (i = 0; i < PANDA_MAX_TX_URBS; i++) { + if (priv->tx_context[i].ndx == PANDA_CTX_FREE) { + ctx = &priv->tx_context[i]; + ctx->ndx = i; + ctx->dlc = cf->can_dlc; + + atomic_dec(&priv->free_ctx_cnt); + break; + } + } + + printk("CTX num %d\n", atomic_read(&priv->free_ctx_cnt)); + if (!atomic_read(&priv->free_ctx_cnt)){ + /* That was the last free ctx. Slow down tx path */ + printk("SENDING TOO FAST\n"); + netif_stop_queue(priv->netdev); + } + + return ctx; +} + +/* panda_usb_free_ctx and panda_usb_get_free_ctx are executed by different + * threads. The order of execution in below function is important. + */ +static inline void panda_usb_free_ctx(struct panda_usb_ctx *ctx) +{ + /* Increase number of free ctxs before freeing ctx */ + atomic_inc(&ctx->priv->free_ctx_cnt); + + ctx->ndx = PANDA_CTX_FREE; + + /* Wake up the queue once ctx is marked free */ + netif_wake_queue(ctx->priv->netdev); +} + + + +static void panda_urb_unlink(struct panda_inf_priv *priv) +{ + usb_kill_anchored_urbs(&priv->priv_dev->rx_submitted); + usb_kill_anchored_urbs(&priv->tx_submitted); +} + +static int panda_set_output_enable(struct panda_inf_priv* priv, bool enable){ + return usb_control_msg(priv->priv_dev->udev, + usb_sndctrlpipe(priv->priv_dev->udev, 0), + 0xDC, USB_TYPE_VENDOR | USB_RECIP_DEVICE, + enable ? 0x1337 : 0, 0, NULL, 0, USB_CTRL_SET_TIMEOUT); +} + +static void panda_usb_write_bulk_callback(struct urb *urb) +{ + struct panda_usb_ctx *ctx = urb->context; + struct net_device *netdev; + + WARN_ON(!ctx); + + netdev = ctx->priv->netdev; + + /* free up our allocated buffer */ + usb_free_coherent(urb->dev, urb->transfer_buffer_length, + urb->transfer_buffer, urb->transfer_dma); + + if (!netif_device_present(netdev)) + return; + + netdev->stats.tx_packets++; + netdev->stats.tx_bytes += ctx->dlc; + + can_get_echo_skb(netdev, ctx->ndx); + + if (urb->status) + netdev_info(netdev, "Tx URB aborted (%d)\n", urb->status); + + /* Release the context */ + panda_usb_free_ctx(ctx); +} + + +static netdev_tx_t panda_usb_xmit(struct panda_inf_priv *priv, + struct panda_usb_can_msg *usb_msg, + struct panda_usb_ctx *ctx) +{ + struct urb *urb; + u8 *buf; + int err; + + /* create a URB, and a buffer for it, and copy the data to the URB */ + urb = usb_alloc_urb(0, GFP_ATOMIC); + if (!urb) + return -ENOMEM; + + buf = usb_alloc_coherent(priv->priv_dev->udev, + PANDA_USB_TX_BUFF_SIZE, GFP_ATOMIC, + &urb->transfer_dma); + if (!buf) { + err = -ENOMEM; + goto nomembuf; + } + + memcpy(buf, usb_msg, PANDA_USB_TX_BUFF_SIZE); + + usb_fill_bulk_urb(urb, priv->priv_dev->udev, + usb_sndbulkpipe(priv->priv_dev->udev, 3), buf, + PANDA_USB_TX_BUFF_SIZE, panda_usb_write_bulk_callback, + ctx); + + urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; + usb_anchor_urb(urb, &priv->tx_submitted); + + err = usb_submit_urb(urb, GFP_ATOMIC); + if (unlikely(err)) + goto failed; + + /* Release our reference to this URB, the USB core will eventually free it entirely. */ + usb_free_urb(urb); + + return 0; + + failed: + usb_unanchor_urb(urb); + usb_free_coherent(priv->priv_dev->udev, PANDA_USB_TX_BUFF_SIZE, buf, urb->transfer_dma); + + if (err == -ENODEV) + netif_device_detach(priv->netdev); + else + netdev_warn(priv->netdev, "failed tx_urb %d\n", err); + + nomembuf: + usb_free_urb(urb); + + return err; +} + +static void panda_usb_process_can_rx(struct panda_dev_priv *priv_dev, + struct panda_usb_can_msg *msg) +{ + struct can_frame *cf; + struct sk_buff *skb; + int bus_num; + struct panda_inf_priv *priv_inf; + struct net_device_stats *stats; + + bus_num = (msg->bus_dat_len >> 4) & 0xf; + priv_inf = panda_get_inf_from_bus_id(priv_dev, bus_num); + if(!priv_inf){ + printk("Got something on an unused interface %d\n", bus_num); + return; + } + printk("Recv bus %d\n", bus_num); + + stats = &priv_inf->netdev->stats; + //u16 sid; + + if (!netif_device_present(priv_inf->netdev)) + return; + + skb = alloc_can_skb(priv_inf->netdev, &cf); + if (!skb) + return; + + if(msg->rir & PANDA_CAN_EXTENDED){ + cf->can_id = (msg->rir >> 3) | CAN_EFF_FLAG; + }else{ + cf->can_id = (msg->rir >> 21); + } + + // TODO: Handle Remote Frames + //if (msg->dlc & MCBA_DLC_RTR_MASK) + // cf->can_id |= CAN_RTR_FLAG; + + cf->can_dlc = get_can_dlc(msg->bus_dat_len & PANDA_DLC_MASK); + + memcpy(cf->data, msg->data, cf->can_dlc); + + stats->rx_packets++; + stats->rx_bytes += cf->can_dlc; + + netif_rx(skb); +} + +static void panda_usb_read_int_callback(struct urb *urb) +{ + struct panda_dev_priv *priv_dev = urb->context; + int retval; + int pos = 0; + int inf_num; + + switch (urb->status) { + case 0: /* success */ + break; + case -ENOENT: + case -ESHUTDOWN: + return; + default: + dev_info(priv_dev->dev, "Rx URB aborted (%d)\n", urb->status); + goto resubmit_urb; + } + + while (pos < urb->actual_length) { + struct panda_usb_can_msg *msg; + + if (pos + sizeof(struct panda_usb_can_msg) > urb->actual_length) { + dev_err(priv_dev->dev, "format error\n"); + break; + } + + msg = (struct panda_usb_can_msg *)(urb->transfer_buffer + pos); + + panda_usb_process_can_rx(priv_dev, msg); + + pos += sizeof(struct panda_usb_can_msg); + } + + resubmit_urb: + usb_fill_int_urb(urb, priv_dev->udev, + usb_rcvintpipe(priv_dev->udev, 1), + urb->transfer_buffer, PANDA_USB_RX_BUFF_SIZE, + panda_usb_read_int_callback, priv_dev, 5); + + retval = usb_submit_urb(urb, GFP_ATOMIC); + + if (retval == -ENODEV){ + for(inf_num = 0; inf_num < PANDA_NUM_CAN_INTERFACES; inf_num++) + if(priv_dev->interfaces[inf_num]) + netif_device_detach(priv_dev->interfaces[inf_num]->netdev); + }else if (retval) + dev_err(priv_dev->dev, "failed resubmitting read bulk urb: %d\n", retval); +} + + +static int panda_usb_start(struct panda_dev_priv *priv_dev) +{ + int err; + struct urb *urb = NULL; + u8 *buf; + int inf_num; + + for(inf_num = 0; inf_num < PANDA_NUM_CAN_INTERFACES; inf_num++) + panda_init_ctx(priv_dev->interfaces[inf_num]); + + err = usb_set_interface(priv_dev->udev, 0, 1); + if (err) { + dev_err(priv_dev->dev, "Can not set alternate setting to 1, error: %i", err); + return err; + } + + /* create a URB, and a buffer for it */ + urb = usb_alloc_urb(0, GFP_KERNEL); + if (!urb) { + return -ENOMEM; + } + + buf = usb_alloc_coherent(priv_dev->udev, PANDA_USB_RX_BUFF_SIZE, + GFP_KERNEL, &urb->transfer_dma); + if (!buf) { + dev_err(priv_dev->dev, "No memory left for USB buffer\n"); + usb_free_urb(urb); + return -ENOMEM; + } + + usb_fill_int_urb(urb, priv_dev->udev, + usb_rcvintpipe(priv_dev->udev, 1), + buf, PANDA_USB_RX_BUFF_SIZE, + panda_usb_read_int_callback, priv_dev, 5); + urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; + + usb_anchor_urb(urb, &priv_dev->rx_submitted); + + err = usb_submit_urb(urb, GFP_KERNEL); + if (err) { + usb_unanchor_urb(urb); + usb_free_coherent(priv_dev->udev, PANDA_USB_RX_BUFF_SIZE, + buf, urb->transfer_dma); + usb_free_urb(urb); + dev_err(priv_dev->dev, "Failed in start, while submitting urb.\n"); + return err; + } + + /* Drop reference, USB core will take care of freeing it */ + usb_free_urb(urb); + + + return 0; +} + +/* Open USB device */ +static int panda_usb_open(struct net_device *netdev) +{ + struct panda_inf_priv *priv = netdev_priv(netdev); + int err; + + /* common open */ + err = open_candev(netdev); + if (err) + return err; + + //priv->can_speed_check = true; + priv->can.state = CAN_STATE_ERROR_ACTIVE; + + netif_start_queue(netdev); + + return 0; +} + +/* Close USB device */ +static int panda_usb_close(struct net_device *netdev) +{ + struct panda_inf_priv *priv = netdev_priv(netdev); + + priv->can.state = CAN_STATE_STOPPED; + + netif_stop_queue(netdev); + + /* Stop polling */ + panda_urb_unlink(priv); + + close_candev(netdev); + + return 0; +} + +static netdev_tx_t panda_usb_start_xmit(struct sk_buff *skb, + struct net_device *netdev) +{ + struct panda_inf_priv *priv_inf = netdev_priv(netdev); + struct can_frame *cf = (struct can_frame *)skb->data; + struct panda_usb_ctx *ctx = NULL; + struct net_device_stats *stats = &priv_inf->netdev->stats; + int err; + struct panda_usb_can_msg usb_msg = {}; + int bus = priv_inf->mcu_can_ifnum; + + if (can_dropped_invalid_skb(netdev, skb)){ + printk("Invalid CAN packet"); + return NETDEV_TX_OK; + } + + ctx = panda_usb_get_free_ctx(priv_inf, cf); + + //Warning: cargo cult. Can't tell what this is for, but it is + //everywhere and encouraged in the documentation. + can_put_echo_skb(skb, priv_inf->netdev, ctx->ndx); + + if(cf->can_id & CAN_EFF_FLAG){ + usb_msg.rir = cpu_to_le32(((cf->can_id & 0x1FFFFFFF) << 3) | + PANDA_CAN_TRANSMIT | PANDA_CAN_EXTENDED); + }else{ + usb_msg.rir = cpu_to_le32(((cf->can_id & 0x7FF) << 21) | PANDA_CAN_TRANSMIT); + } + usb_msg.bus_dat_len = cpu_to_le32((cf->can_dlc & 0x0F) | (bus << 4)); + + memcpy(usb_msg.data, cf->data, cf->can_dlc); + + //TODO Handle Remote Frames + //if (cf->can_id & CAN_RTR_FLAG) + // usb_msg.dlc |= PANDA_DLC_RTR_MASK; + + netdev_err(netdev, "Received data from socket. canid: %x; len: %d\n", cf->can_id, cf->can_dlc); + + err = panda_usb_xmit(priv_inf, &usb_msg, ctx); + if (err) + goto xmit_failed; + + return NETDEV_TX_OK; + + xmit_failed: + can_free_echo_skb(priv_inf->netdev, ctx->ndx); + panda_usb_free_ctx(ctx); + dev_kfree_skb(skb); + stats->tx_dropped++; + + return NETDEV_TX_OK; +} + +static const struct net_device_ops panda_netdev_ops = { + .ndo_open = panda_usb_open, + .ndo_stop = panda_usb_close, + .ndo_start_xmit = panda_usb_start_xmit, +}; + +static int panda_usb_probe(struct usb_interface *intf, + const struct usb_device_id *id) +{ + struct net_device *netdev; + struct panda_inf_priv *priv_inf; + int err = -ENOMEM; + int inf_num; + struct panda_dev_priv *priv_dev; + struct usb_device *usbdev = interface_to_usbdev(intf); + + priv_dev = kzalloc(sizeof(struct panda_dev_priv), GFP_KERNEL); + if (!priv_dev) { + dev_err(&intf->dev, "Couldn't alloc priv_dev\n"); + return -ENOMEM; + } + priv_dev->udev = usbdev; + priv_dev->dev = &intf->dev; + usb_set_intfdata(intf, priv_dev); + + ////// Interface privs + for(inf_num = 0; inf_num < PANDA_NUM_CAN_INTERFACES; inf_num++){ + netdev = alloc_candev(sizeof(struct panda_inf_priv), PANDA_MAX_TX_URBS); + if (!netdev) { + dev_err(&intf->dev, "Couldn't alloc candev\n"); + goto cleanup_candev; + } + netdev->netdev_ops = &panda_netdev_ops; + netdev->flags |= IFF_ECHO; /* we support local echo */ + + priv_inf = netdev_priv(netdev); + priv_inf->netdev = netdev; + priv_inf->priv_dev = priv_dev; + priv_inf->interface_num = inf_num; + priv_inf->mcu_can_ifnum = can_numbering[inf_num]; + + init_usb_anchor(&priv_dev->rx_submitted); + init_usb_anchor(&priv_inf->tx_submitted); + + /* Init CAN device */ + priv_inf->can.state = CAN_STATE_STOPPED; + priv_inf->can.bittiming.bitrate = PANDA_BITRATE; + + SET_NETDEV_DEV(netdev, &intf->dev); + + err = register_candev(netdev); + if (err) { + netdev_err(netdev, "couldn't register PANDA CAN device: %d\n", err); + free_candev(priv_inf->netdev); + goto cleanup_candev; + } + + priv_dev->interfaces[inf_num] = priv_inf; + } + + err = panda_usb_start(priv_dev); + if (err) { + dev_err(&intf->dev, "Failed to initialize Comma.ai Panda CAN controller\n"); + goto cleanup_candev; + } + + err = panda_set_output_enable(priv_inf, true); + if (err) { + dev_info(&intf->dev, "Failed to initialize send enable message to Panda.\n"); + goto cleanup_candev; + } + + dev_info(&intf->dev, "Comma.ai Panda CAN controller connected\n"); + + return 0; + + cleanup_candev: + for(inf_num = 0; inf_num < PANDA_NUM_CAN_INTERFACES; inf_num++){ + priv_inf = priv_dev->interfaces[inf_num]; + if(priv_inf){ + unregister_candev(priv_inf->netdev); + free_candev(priv_inf->netdev); + }else + break; + } + + kfree(priv_dev); + + return err; +} + +/* Called by the usb core when driver is unloaded or device is removed */ +static void panda_usb_disconnect(struct usb_interface *intf) +{ + struct panda_dev_priv *priv_dev = usb_get_intfdata(intf); + struct panda_inf_priv *priv_inf; + int inf_num; + + usb_set_intfdata(intf, NULL); + + for(inf_num = 0; inf_num < PANDA_NUM_CAN_INTERFACES; inf_num++){ + priv_inf = priv_dev->interfaces[inf_num]; + if(priv_inf){ + netdev_info(priv_inf->netdev, "device disconnected\n"); + unregister_candev(priv_inf->netdev); + free_candev(priv_inf->netdev); + }else + break; + } + + panda_urb_unlink(priv_inf); + kfree(priv_dev); +} + +static struct usb_driver panda_usb_driver = { + .name = PANDA_MODULE_NAME, + .probe = panda_usb_probe, + .disconnect = panda_usb_disconnect, + .id_table = panda_usb_table, +}; + +module_usb_driver(panda_usb_driver); + +MODULE_LICENSE("GPL"); +MODULE_AUTHOR("Jessy Diamond Exum "); +MODULE_DESCRIPTION("SocketCAN driver for Comma.ai's Panda Adapter."); +MODULE_VERSION("0.1"); diff --git a/drivers/linux/test/Makefile b/drivers/linux/test/Makefile new file mode 100644 index 0000000000..c73945e4cd --- /dev/null +++ b/drivers/linux/test/Makefile @@ -0,0 +1,2 @@ +all: + gcc main.c -o cantest -pthread -lpthread diff --git a/drivers/linux/test/main.c b/drivers/linux/test/main.c new file mode 100644 index 0000000000..1f44efc76e --- /dev/null +++ b/drivers/linux/test/main.c @@ -0,0 +1,120 @@ +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include + +const char *ifname = "can0"; + +static unsigned char payload[] = {0xAA, 0xAA, 0xAA, 0xAA, 0x07, 0x00, 0x00, 0x00}; +int packet_len = 8; +int dir = 0; + +void *write_thread( void *dat ){ + int nbytes; + struct can_frame frame; + int s = *((int*) dat); + + while(1){ + for(int i = 0; i < 1; i ++){ + if(packet_len % 2){ + frame.can_id = 0x8AA | CAN_EFF_FLAG; + }else{ + frame.can_id = 0xAA; + } + + frame.can_dlc = packet_len; + memcpy(frame.data, payload, frame.can_dlc); + + nbytes = write(s, &frame, sizeof(struct can_frame)); + + printf("Wrote %d bytes; addr: %lx; datlen: %d\n", nbytes, frame.can_id, frame.can_dlc); + + if(dir){ + packet_len++; + if(packet_len >= 8) + dir = 0; + }else{ + packet_len--; + if(packet_len <= 0) + dir = 1; + } + } + sleep(2); + } +} + + +int main(void) +{ + pthread_t sndthread; + int err, s, nbytes; + struct sockaddr_can addr; + struct can_frame frame; + struct ifreq ifr; + + if((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) { + perror("Error while opening socket"); + return -1; + } + + strcpy(ifr.ifr_name, ifname); + ioctl(s, SIOCGIFINDEX, &ifr); + + addr.can_family = AF_CAN; + addr.can_ifindex = ifr.ifr_ifindex; + + printf("%s at index %d\n", ifname, ifr.ifr_ifindex); + + if(bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) { + perror("Error in socket bind"); + return -2; + } + + /////// Create Write Thread + + err = pthread_create( &sndthread, NULL, write_thread, (void*) &s); + if(err){ + fprintf(stderr,"Error - pthread_create() return code: %d\n", err); + exit(EXIT_FAILURE); + } + + /////// Listen to socket + while (1) { + struct can_frame framein; + + // Read in a CAN frame + int numBytes = read(s, &framein, CANFD_MTU); + switch (numBytes) { + case CAN_MTU: + if(framein.can_id & 0x80000000) + printf("Received %u byte payload; canid 0x%lx (EXT)\n", + framein.can_dlc, framein.can_id & 0x7FFFFFFF); + else + printf("Received %u byte payload; canid 0x%lx\n", framein.can_dlc, framein.can_id); + break; + case CANFD_MTU: + // TODO: Should make an example for CAN FD + break; + case -1: + // Check the signal value on interrupt + //if (EINTR == errno) + // continue; + + // Delay before continuing + sleep(1); + default: + continue; + } + } + + return 0; +} diff --git a/drivers/linux/test/run.sh b/drivers/linux/test/run.sh new file mode 100755 index 0000000000..5301719b49 --- /dev/null +++ b/drivers/linux/test/run.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +sudo ifconfig can0 up +make +./cantest diff --git a/drivers/windows/.gitignore b/drivers/windows/.gitignore new file mode 100644 index 0000000000..dbe7ad5a91 --- /dev/null +++ b/drivers/windows/.gitignore @@ -0,0 +1,306 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +Debug_x86/ +Debug_x64/ +Release_x86/ +Release_x64/ +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ +**/Properties/launchSettings.json + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Typescript v1 declaration files +typings/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml + +# CodeRush +.cr/ + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# installer +*.exe diff --git a/drivers/windows/ECUsim CLI/ECUsim CLI.cpp b/drivers/windows/ECUsim CLI/ECUsim CLI.cpp new file mode 100644 index 0000000000..6c8a469acc --- /dev/null +++ b/drivers/windows/ECUsim CLI/ECUsim CLI.cpp @@ -0,0 +1,38 @@ +// ECUsim CLI.cpp : Defines the entry point for the console application. +// + +#include "stdafx.h" +#include "ECUsim DLL\ECUsim.h" + +std::unique_ptr sim; + +BOOL CtrlHandler(DWORD fdwCtrlType) +{ + if (fdwCtrlType != CTRL_C_EVENT) return FALSE; + + sim->stop(); + sim->join(); + + return(TRUE); +} + +int main(int argc, // Number of strings in array argv + char *argv[], // Array of command-line argument strings + char *envp[]) // Array of environment variable strings +{ + + int count; + + // Display each command-line argument. + std::cout << "\nCommand-line arguments:\n"; + for (count = 0; count < argc; count++) + std::cout << " argv[" << count << "] " << argv[count] << "\n"; + + SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, TRUE); + + sim.reset(new ECUsim("", 500000)); + sim->join(); + + return 0; +} + diff --git a/drivers/windows/ECUsim CLI/ECUsim CLI.vcxproj b/drivers/windows/ECUsim CLI/ECUsim CLI.vcxproj new file mode 100644 index 0000000000..9ac10e8bc1 --- /dev/null +++ b/drivers/windows/ECUsim CLI/ECUsim CLI.vcxproj @@ -0,0 +1,178 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + {D99E2FCD-21A4-4065-949A-31E34E0E69D1} + Win32Proj + ECUsimCLI + 8.1 + + + + Application + true + v140 + Unicode + + + Application + false + v140 + true + Unicode + + + Application + true + v140 + Unicode + + + Application + false + v140 + true + Unicode + + + + + + + + + + + + + + + + + + + + + true + $(SolutionDir)$(Configuration)_$(PlatformShortName)\ + + + true + $(SolutionDir)$(Configuration)_$(PlatformShortName)\ + + + false + $(SolutionDir)$(Configuration)_$(PlatformShortName)\ + + + false + $(SolutionDir)$(Configuration)_$(PlatformShortName)\ + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + %(AdditionalIncludeDirectories);$(SolutionDir) + + + Console + true + kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies);$(OutDir)ecusim.lib + + + + + Use + Level3 + Disabled + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + %(AdditionalIncludeDirectories);$(SolutionDir) + + + Console + true + kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies);$(OutDir)ecusim.lib + + + + + Level3 + Use + MaxSpeed + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + %(AdditionalIncludeDirectories);$(SolutionDir) + + + Console + true + true + true + kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies);$(OutDir)ecusim.lib + + + + + Level3 + Use + MaxSpeed + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + %(AdditionalIncludeDirectories);$(SolutionDir) + + + Console + true + true + true + kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies);$(OutDir)ecusim.lib + + + + + + + + + + + Create + Create + Create + Create + + + + + {96e0e646-ee76-444d-9a77-a0cd7f781deb} + + + + + + \ No newline at end of file diff --git a/drivers/windows/ECUsim CLI/ECUsim CLI.vcxproj.filters b/drivers/windows/ECUsim CLI/ECUsim CLI.vcxproj.filters new file mode 100644 index 0000000000..ea223e30b2 --- /dev/null +++ b/drivers/windows/ECUsim CLI/ECUsim CLI.vcxproj.filters @@ -0,0 +1,36 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Header Files + + + Header Files + + + Header Files + + + + + Source Files + + + Source Files + + + \ No newline at end of file diff --git a/drivers/windows/ECUsim CLI/stdafx.cpp b/drivers/windows/ECUsim CLI/stdafx.cpp new file mode 100644 index 0000000000..d4a23c3cf7 --- /dev/null +++ b/drivers/windows/ECUsim CLI/stdafx.cpp @@ -0,0 +1,8 @@ +// stdafx.cpp : source file that includes just the standard includes +// ECUsim CLI.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + +// TODO: reference any additional headers you need in STDAFX.H +// and not in this file diff --git a/drivers/windows/ECUsim CLI/stdafx.h b/drivers/windows/ECUsim CLI/stdafx.h new file mode 100644 index 0000000000..b005a839de --- /dev/null +++ b/drivers/windows/ECUsim CLI/stdafx.h @@ -0,0 +1,15 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// + +#pragma once + +#include "targetver.h" + +#include +#include + + + +// TODO: reference additional headers your program requires here diff --git a/drivers/windows/ECUsim CLI/targetver.h b/drivers/windows/ECUsim CLI/targetver.h new file mode 100644 index 0000000000..87c0086de7 --- /dev/null +++ b/drivers/windows/ECUsim CLI/targetver.h @@ -0,0 +1,8 @@ +#pragma once + +// Including SDKDDKVer.h defines the highest available Windows platform. + +// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and +// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h. + +#include diff --git a/drivers/windows/ECUsim DLL/ECUsim DLL.vcxproj b/drivers/windows/ECUsim DLL/ECUsim DLL.vcxproj new file mode 100644 index 0000000000..d50a0a2918 --- /dev/null +++ b/drivers/windows/ECUsim DLL/ECUsim DLL.vcxproj @@ -0,0 +1,197 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + {96E0E646-EE76-444D-9A77-A0CD7F781DEB} + Win32Proj + ECUsimDLL + 8.1 + + + + DynamicLibrary + true + v140 + Unicode + + + DynamicLibrary + false + v140 + true + Unicode + + + DynamicLibrary + true + v140 + Unicode + + + DynamicLibrary + false + v140 + true + Unicode + + + + + + + + + + + + + + + + + + + + + true + ecusim + $(SolutionDir)$(Configuration)_$(PlatformShortName)\ + + + true + ecusim + $(SolutionDir)$(Configuration)_$(PlatformShortName)\ + + + false + ecusim + $(SolutionDir)$(Configuration)_$(PlatformShortName)\ + + + false + ecusim + $(SolutionDir)$(Configuration)_$(PlatformShortName)\ + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_USRDLL;ECUSIMDLL_EXPORTS;%(PreprocessorDefinitions) + true + %(AdditionalIncludeDirectories);$(SolutionDir) + + + Windows + true + kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies);$(OutDir)panda.lib + + + + + Use + Level3 + Disabled + _DEBUG;_WINDOWS;_USRDLL;ECUSIMDLL_EXPORTS;%(PreprocessorDefinitions) + true + %(AdditionalIncludeDirectories);$(SolutionDir) + + + Windows + true + kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies);$(OutDir)panda.lib + + + + + Level3 + Use + MaxSpeed + true + true + WIN32;NDEBUG;_WINDOWS;_USRDLL;ECUSIMDLL_EXPORTS;%(PreprocessorDefinitions) + true + %(AdditionalIncludeDirectories);$(SolutionDir) + + + Windows + true + true + true + kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies);$(OutDir)panda.lib + + + + + Level3 + Use + MaxSpeed + true + true + NDEBUG;_WINDOWS;_USRDLL;ECUSIMDLL_EXPORTS;%(PreprocessorDefinitions) + true + %(AdditionalIncludeDirectories);$(SolutionDir) + + + Windows + true + true + true + kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies);$(OutDir)panda.lib + + + + + + + + + + + false + + + false + + + false + + + false + + + + + + Create + Create + Create + Create + + + + + {5528aefb-638d-49af-b9d4-965154e7d531} + + + + + + \ No newline at end of file diff --git a/drivers/windows/ECUsim DLL/ECUsim DLL.vcxproj.filters b/drivers/windows/ECUsim DLL/ECUsim DLL.vcxproj.filters new file mode 100644 index 0000000000..299d654451 --- /dev/null +++ b/drivers/windows/ECUsim DLL/ECUsim DLL.vcxproj.filters @@ -0,0 +1,42 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + + + Source Files + + + Source Files + + + Source Files + + + \ No newline at end of file diff --git a/drivers/windows/ECUsim DLL/ECUsim.cpp b/drivers/windows/ECUsim DLL/ECUsim.cpp new file mode 100644 index 0000000000..19f2bf360e --- /dev/null +++ b/drivers/windows/ECUsim DLL/ECUsim.cpp @@ -0,0 +1,261 @@ +#include "stdafx.h" +#include "ECUsim.h" + +ECUsim::ECUsim(std::string sn, unsigned long can_baud, bool ext_addr) : + doloop(TRUE), verbose(TRUE), can11b_enabled(TRUE), can29b_enabled(TRUE), ext_addr(ext_addr){ + this->panda = panda::Panda::openPanda(sn); + this->panda->set_can_speed_cbps(panda::PANDA_CAN1, can_baud / 100); //Don't pass in baud where baud%100 != 0 + this->panda->set_safety_mode(panda::SAFETY_ALLOUTPUT); + this->panda->set_can_loopback(FALSE); + this->panda->can_clear(panda::PANDA_CAN_RX); + + DWORD threadid; + this->thread_can = CreateThread(NULL, 0, _canthreadBootstrap, (LPVOID)this, 0, &threadid); +} + +ECUsim::~ECUsim() { + this->stop(); + this->join(); +} + +void ECUsim::stop() { + this->doloop = FALSE; +} + +void ECUsim::join() { + WaitForSingleObject(this->thread_can, INFINITE); +} + +DWORD WINAPI ECUsim::_canthreadBootstrap(LPVOID This) { + return ((ECUsim*)This)->can_recv_thread_function(); +} + +DWORD ECUsim::can_recv_thread_function() { + while (this->doloop) { + auto msgs = this->panda->can_recv(); + for (auto& msg : msgs) { + if (msg.is_receipt) continue; + if (msg.bus == 0 && !msg.is_receipt /*&& msg.len == 8*/ && msg.dat[0] >= 2) { + if (this->verbose) { + printf("Processing message (bus: %d; addr: %X; 29b: %d):\n ", msg.bus, msg.addr, msg.addr_29b); + for (int i = 0; i < msg.len; i++) printf("%02X ", msg.dat[i]); + printf("\n"); + } + this->_CAN_process_msg(msg); + } else { + if (this->verbose) { + printf("Rejecting message (bus: %d; addr: %X; 29b: %d):\n ", msg.bus, msg.addr, msg.addr_29b); + for (int i = 0; i < msg.len; i++) printf("%02X ", msg.dat[i]); + printf("\n"); + } + } + } + } + + return 0; +} + +BOOL ECUsim::_can_addr_matches(panda::PANDA_CAN_MSG& msg) { + if (this->can11b_enabled && !msg.addr_29b && (msg.addr == 0x7DF || (msg.addr & 0x7F8) == 0x7E0)) { + if (!this->ext_addr) { + return TRUE; + } else { + return msg.len >= 1 && msg.dat[0] == 0x13;//13 is an arbitrary address picked to test ext addresses + } + } + if (this->can29b_enabled && msg.addr_29b && ((msg.addr & 0x1FFF00FF) == 0x18DB00F1 || (msg.addr & 0x1FFF00FF) == 0x18da00f1)) { + if (!this->ext_addr) { + return TRUE; + } else { + return msg.len >= 1 && msg.dat[0] == 0x13;//13 is an arbitrary address picked to test ext addresses + } + } + return FALSE; +} + +void ECUsim::_CAN_process_msg(panda::PANDA_CAN_MSG& msg) { + std::string outmsg; + uint32_t outaddr; + uint8_t formatted_msg_buff[8]; + bool doreply = FALSE; + + if (this->_can_addr_matches(msg)) {// && msg.len == 8) { + uint8_t *dat = (this->ext_addr) ? &msg.dat[1] : &msg.dat[0]; + if ((dat[0] & 0xF0) == 0x10) { + printf("Got a multiframe write request\n"); + outaddr = (msg.addr_29b) ? 0x18DAF1EF : 0x7E8; + this->panda->can_send(outaddr, msg.addr_29b, (const uint8_t*)"\x30\x00\x00", 3, panda::PANDA_CAN1); + return; + } + + /////////// Check if Flow Control Msg + if ((dat[0] & 0xF0) == 0x30 && msg.len >= 3 && this->can_multipart_data.size() > 0) { + if (this->verbose) printf("More data requested\n"); + uint8_t block_size = dat[1], sep_time_min = dat[2]; + outaddr = (msg.addr == 0x7DF || msg.addr == 0x7E0) ? 0x7E8 : 0x18DAF1EF; //ext addr 5th byte is just always 0x13 for simplicity + + unsigned int msgnum = 1; + while (this->can_multipart_data.size()) { + unsigned int datalen = this->ext_addr ? + min(6, this->can_multipart_data.size()): //EXT ADDR VALUE + min(7, this->can_multipart_data.size()); //NORMAL ADDR VALUE + + unsigned int idx = 0; + if (this->ext_addr) + formatted_msg_buff[idx++] = 0x13; //EXT ADDR + formatted_msg_buff[idx++] = 0x20 | msgnum; + for (int i = 0; i < datalen; i++) { + formatted_msg_buff[i + idx] = this->can_multipart_data.front(); + this->can_multipart_data.pop(); + } + for (int i = datalen + idx; i < sizeof(formatted_msg_buff); i++) + formatted_msg_buff[i] = 0; + + if (this->verbose) { + printf("Multipart reply to %X.\n ", outaddr); + for (int i = 0; i < datalen + idx; i++) printf("%02X ", formatted_msg_buff[i]); + printf("\n"); + } + + this->panda->can_send(outaddr, msg.addr_29b, formatted_msg_buff, datalen + idx, panda::PANDA_CAN1); + msgnum = (msgnum + 1) % 0x10; + Sleep(10); + } + return; + } + + /////////// Normal message in + outmsg = this->process_obd_msg(dat[1], dat[2], doreply); + if (doreply) { + outaddr = (msg.addr_29b) ? 0x18DAF1EF : 0x7E8; + + if (outmsg.size() <= (this->ext_addr ? 4 : 5)) { + unsigned int idx = 0; + if(this->ext_addr) + formatted_msg_buff[idx++] = 0x13; //EXT ADDR + formatted_msg_buff[idx++] = outmsg.size() + 2; + formatted_msg_buff[idx++] = 0x40 | dat[1]; + formatted_msg_buff[idx++] = dat[2]; //PID + memcpy_s(&formatted_msg_buff[idx], sizeof(formatted_msg_buff) - idx, outmsg.c_str(), outmsg.size()); + for (int i = idx + outmsg.size(); i < 8; i++) + formatted_msg_buff[i] = 0; + + if (this->verbose) { + printf("Replying to %X.\n ", outaddr); + for (int i = 0; i < 8; i++) printf("%02X ", formatted_msg_buff[i]); + printf("\n"); + } + + this->panda->can_send(outaddr, msg.addr_29b, formatted_msg_buff, 8, panda::PANDA_CAN1); //outmsg.size() + 3 + } else { + uint8_t first_msg_len = this->ext_addr ? + min(2, outmsg.size() % 7) : //EXT ADDR VALUES + min(3, outmsg.size() % 7); //NORMAL ADDR VALUES + uint8_t payload_len = outmsg.size() + 3; + + unsigned int idx = 0; + if (this->ext_addr) + formatted_msg_buff[idx++] = 0x13; //EXT ADDR + formatted_msg_buff[idx++] = 0x10 | ((payload_len >> 8) & 0xF); + formatted_msg_buff[idx++] = payload_len & 0xFF; + formatted_msg_buff[idx++] = 0x40 | dat[1]; + formatted_msg_buff[idx++] = dat[2]; //PID + formatted_msg_buff[idx++] = 1; + memcpy_s(&formatted_msg_buff[idx], sizeof(formatted_msg_buff) - idx, outmsg.c_str(), first_msg_len); + + if (this->verbose) { + printf("Replying FIRST FRAME to %X.\n ", outaddr); + for (int i = 0; i < 8; i++) printf("%02X ", formatted_msg_buff[i]); + printf("\n"); + } + + this->panda->can_send(outaddr, msg.addr_29b, formatted_msg_buff, 8, panda::PANDA_CAN1); + for (int i = first_msg_len; i < outmsg.size(); i++) + this->can_multipart_data.push(outmsg[i]); + } + } + } +} + +std::string ECUsim::process_obd_msg(UCHAR mode, UCHAR pid, bool& return_data) { + std::string tmp; + return_data = TRUE; + + switch (mode) { + case 0x01: // Mode : Show current data + switch (pid) { + case 0x00: //List supported things + return "\xff\xff\xff\xfe"; //b"\xBE\x1F\xB8\x10" #Bitfield, random features + case 0x01: // Monitor Status since DTC cleared + return std::string("\x00\x00\x00\x00", 4); //Bitfield, random features + case 0x04: // Calculated engine load + return "\x2f"; + case 0x05: // Engine coolant temperature + return "\x3c"; + case 0x0B: // Intake manifold absolute pressure + return "\x90"; + case 0x0C: // Engine RPM + return "\x1A\xF8"; + case 0x0D: // Vehicle Speed + return "\x53"; + case 0x10: // MAF air flow rate + return "\x01\xA0"; + case 0x11: // Throttle Position + return "\x90"; + case 0x33: // Absolute Barometric Pressure + return "\x90"; + default: + return_data = FALSE; + return ""; + } + case 0x09: // Mode : Request vehicle information + switch (pid) { + case 0x02: // Show VIN + return "1D4GP00R55B123456"; + case 0xFC: // test long multi message.Ligned up for LIN responses + for (int i = 0; i < 80; i++) { + tmp += "\xAA\xAA"; + } + return tmp;//">BBH", 0xAA, 0xAA, num + 1) + case 0xFD: // test long multi message + for (int i = 0; i < 80; i++) { + tmp += "\xAA\xAA\xAA"; + tmp.push_back(i >> 24); + tmp.push_back((i >> 16) & 0xFF); + tmp.push_back((i >> 8) & 0xFF); + tmp.push_back(i & 0xFF); + } + return "\xAA\xAA\xAA" + tmp; + case 0xFE: // test very long multi message + tmp = "\xAA\xAA\xAA"; + for (int i = 0; i < 584; i++) { + tmp += "\xAA\xAA\xAA"; + tmp.push_back(i >> 24); + tmp.push_back((i >> 16) & 0xFF); + tmp.push_back((i >> 8) & 0xFF); + tmp.push_back(i & 0xFF); + } + return tmp + "\xAA"; + case 0xFF: + for (int i = 0; i < 584; i++) { + tmp += "\xAA\xAA\xAA\xAA\xAA"; + tmp.push_back(((i + 1) >> 8) & 0xFF); + tmp.push_back((i + 1) & 0xFF); + } + return std::string("\xAA\x00\x00", 3) + tmp; + default: + return_data = FALSE; + return ""; + } + case 0x3E: + if (pid == 0) { + return_data = TRUE; + return ""; + } + return_data = FALSE; + return ""; + default: + return_data = FALSE; + return ""; + } +} diff --git a/drivers/windows/ECUsim DLL/ECUsim.h b/drivers/windows/ECUsim DLL/ECUsim.h new file mode 100644 index 0000000000..7378e2c581 --- /dev/null +++ b/drivers/windows/ECUsim DLL/ECUsim.h @@ -0,0 +1,50 @@ +#pragma once + +#include +#include "panda\panda.h" +#include + +// The following ifdef block is the standard way of creating macros which make exporting +// from a DLL simpler. All files within this DLL are compiled with the ECUSIMDLL_EXPORTS +// symbol defined on the command line. This symbol should not be defined on any project +// that uses this DLL. This way any other project whose source files include this file see +// ECUSIMDLL_API functions as being imported from a DLL, whereas this DLL sees symbols +// defined with this macro as being exported. +#ifdef ECUSIMDLL_EXPORTS +#define ECUSIMDLL_API __declspec(dllexport) +#else +#define ECUSIMDLL_API __declspec(dllimport) +#endif + +// This class is exported from the ECUsim DLL.dll +class ECUSIMDLL_API ECUsim { +public: + ECUsim(std::string sn, unsigned long can_baud, bool ext_addr = FALSE); + ECUsim(panda::Panda && p, unsigned long can_baud, bool ext_addr = FALSE); + ~ECUsim(); + + void stop(); + void join(); + + // Flag determines if verbose output is enabled + volatile bool verbose; + BOOL ext_addr; +private: + std::unique_ptr panda; + + static DWORD WINAPI _canthreadBootstrap(LPVOID This); + DWORD can_recv_thread_function(); + + BOOL _can_addr_matches(panda::PANDA_CAN_MSG & msg); + + void _CAN_process_msg(panda::PANDA_CAN_MSG & msg); + + std::string process_obd_msg(UCHAR mode, UCHAR pid, bool& return_data); + + HANDLE thread_can; + volatile bool doloop; + std::queue can_multipart_data; + + BOOL can11b_enabled; + BOOL can29b_enabled; +}; diff --git a/drivers/windows/ECUsim DLL/dllmain.cpp b/drivers/windows/ECUsim DLL/dllmain.cpp new file mode 100644 index 0000000000..69b58914b3 --- /dev/null +++ b/drivers/windows/ECUsim DLL/dllmain.cpp @@ -0,0 +1,19 @@ +// dllmain.cpp : Defines the entry point for the DLL application. +#include "stdafx.h" + +BOOL APIENTRY DllMain( HMODULE hModule, + DWORD ul_reason_for_call, + LPVOID lpReserved + ) +{ + switch (ul_reason_for_call) + { + case DLL_PROCESS_ATTACH: + case DLL_THREAD_ATTACH: + case DLL_THREAD_DETACH: + case DLL_PROCESS_DETACH: + break; + } + return TRUE; +} + diff --git a/drivers/windows/ECUsim DLL/stdafx.cpp b/drivers/windows/ECUsim DLL/stdafx.cpp new file mode 100644 index 0000000000..b4056ecd06 --- /dev/null +++ b/drivers/windows/ECUsim DLL/stdafx.cpp @@ -0,0 +1,8 @@ +// stdafx.cpp : source file that includes just the standard includes +// ECUsim DLL.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + +// TODO: reference any additional headers you need in STDAFX.H +// and not in this file diff --git a/drivers/windows/ECUsim DLL/stdafx.h b/drivers/windows/ECUsim DLL/stdafx.h new file mode 100644 index 0000000000..f3a07375c7 --- /dev/null +++ b/drivers/windows/ECUsim DLL/stdafx.h @@ -0,0 +1,16 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// + +#pragma once + +#include "targetver.h" + +#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers +// Windows Header Files: +#include + + + +// TODO: reference additional headers your program requires here diff --git a/drivers/windows/ECUsim DLL/targetver.h b/drivers/windows/ECUsim DLL/targetver.h new file mode 100644 index 0000000000..87c0086de7 --- /dev/null +++ b/drivers/windows/ECUsim DLL/targetver.h @@ -0,0 +1,8 @@ +#pragma once + +// Including SDKDDKVer.h defines the highest available Windows platform. + +// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and +// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h. + +#include diff --git a/drivers/windows/README.md b/drivers/windows/README.md new file mode 100644 index 0000000000..7219abda24 --- /dev/null +++ b/drivers/windows/README.md @@ -0,0 +1,177 @@ +``` + ;" ^; ;' ", +______/\\\\\\\\\\\____/\\\\\\\\\_______/\\\\\\\\\\\\\\\______/\\\\\\\\\\_____________/\\\____ ; s$$$$$$$s ; + _____\/////\\\///___/\\\///////\\\____\/\\\///////////_____/\\\///////\\\__________/\\\\\____ , ss$$$$$$$$$$s ,' + _________\/\\\_____\///______\//\\\___\/\\\_______________\///______/\\\_________/\\\/\\\____ ;s$$$$$$$$$$$$$$$ + _________\/\\\_______________/\\\/____\/\\\\\\\\\\\\_____________/\\\//________/\\\/\/\\\____ $$$$$$$$$$$$$$$$$$ + _________\/\\\____________/\\\//______\////////////\\\__________\////\\\_____/\\\/__\/\\\____ $$$$P""Y$$$Y""W$$$$$ + _________\/\\\_________/\\\//____________________\//\\\____________\//\\\__/\\\\\\\\\\\\\\\\_ $$$$ p"$$$"q $$$$$ + __/\\\___\/\\\_______/\\\/____________/\\\________\/\\\___/\\\______/\\\__\///////////\\\//__ $$$$ .$$$$$. $$$$ + _\//\\\\\\\\\_______/\\\\\\\\\\\\\\\_\//\\\\\\\\\\\\\/___\///\\\\\\\\\/_____________\/\\\____ _ $$$$$$$$$$$$$$$$ + __\/////////_______\///////////////___\/////////////_______\/////////_______________\///_____| | "Y$$$"*"$$$Y" + _ __ __ _ _ __ __| | __ _"$b.$$" + | '_ \ / _` | '_ \ / _` |/ _` | + | |_) | (_| | | | | (_| | (_| | + | .__/ \__,_|_| |_|\__,_|\__,_| + | | A comma.ai product. + |_| (Code by Jessy Diamond Exum) +``` + + +# What is J2534? + +J2534 is an API that tries to provide a consistent way to send/receive +messages over the many different protocols supported by the OBD II +port. The place this is perhaps most obvious, is sending data over +different protocols (each using unique packetizing methods) using the +same data format. + +For each PassThru Device that should be used with J2534 (in this case, +the panda), a 'driver' has to be written that can be loaded by a +client application wanting to send/receive data. + +A lot of J2534 has good ideas behind it, but the standard has some odd choices: + +* Platform Locked: Requires using the Windows Registry to find installed J2534 libraries/drivers. Drivers have to be DLLs. +* Architecture Locked: So far there is only support for x86. +* No device autodetect, and poor support for selecting from multiple devices. +* Constant vague language about important behavior (small differences between vendors). +* Most common differences become standard in later revisions. + +# Why use J2534 with the panda? + +J2534 is the only interface supported by most professional grade +vehicle diagnostics systems (such as HDS). These tools are useful for +diagnosing vehicles, as well as reverse engineering some lesser known +features. + +# What parts are supported with panda? + +- [ ] **J1850VPW** *(Outdated, and not physically supported by the panda)* +- [ ] **J1850PWM** *(Outdated, and not physically supported by the panda)* +- [X] **CAN** +- [X] **ISO15765** +- [ ] **ISO9141** *(This protocol could be implemented if 5 BAUD init support is added to the panda.)* +- [ ] **ISO14230/KWP2000** *(Could be supported with FAST init, 5baud init if panda adds support for 5bps serial)* + +# Building the Project: + +This project was developed with Visual Studio 2015, the Windows SDK, +and the Windows Driver Kit (WDK). At the time of writing, there is not +a stable WDK for Visual Studio 2017, but this project should build +with the new WDK and Visual Studio when it is available. + +The WDK is only required for creating the signed WinUSB inf file. The +WDK may also provide the headers for WinUSB. + +To build all the projects required for the installer, in Visual +Studio, select **Build->Batch Build.** In the project list select: + +- **"panda"** *Release|x86* +- **"panda"** *Release|x64* +- **"panda Driver Package"** Debug|x86 (Note this inf file works with x86/amd64). +- **"pandaJ2534DLL"** *Release|x86* + +The installer is generated with [NullSoft NSIS](http://nsis.sourceforge.net/Main_Page). +Use NSIS to run panda_install.nsi after building all the required projects. + +Before generating the installer, you must go to copy vscruntimeinfo.nsh.sample to +vscruntimeinfo.nsh and follow the instructions to bundle in the Visual Studio C +Runtime required by your version of Visual Studio. Without this runtime, the panda +code will not work, so without this file, the installer will refuse to build. + +# Installing: + +Either build the software yourself by following the steps in the +'Developing' section, or get the panda_installer.exe file and run +it. The wizard should correctly set up the drivers. + +Since this driver is still in development, there are some issues +that may occur. If after you install the driver and then plug in your +panda (unplug it first if it was already plugged in), Windows says +the driver is missing, refer to the section below 'Dealing with self +signed drivers.' + +# Using J2534: + +After installing the J2534 drivers for the panda, you can do... nothing. +You first need to get a J2534 client that can load the drivers and talk to +the panda for you. + +A simple tool for testing J2534 drivers is DrewTech's 'J2534-1 Bus Analysis +Tool' available in the 'Other Support Applications' section of their +[Download Page](http://www.drewtech.com/downloads/). + +# Dealing with self signed drivers: + +Installation would be straightforward were it not for the USB Driver +that needs to be setup. The driver itself is only a WinUSB inf file +(no actual driver), but it still needs to be signed. + +Driver signing is a requirement of Windows starting in 8 (64 bit +versions only for some reason). If your Windows refuses to install +the driver, there are three choices: + +- Self Sign the Driver. +- Disable Driver Signature Verification +- Purchase a certificate signed by a trusted authority. + +Since self signed certificates have no chain of trust to a known +certificate authority, if you self sign, you will have to add your +cert to the root certificate store of your Windows' installation. This +is dangerous because it means anything signed with your cert will be +trusted. If you make your own cert, add a password so someone can't +copy it and screw with your computer's trust. + +Disabling Signature Verification allows you to temporarily install +drivers without a trusted signature. Once you reboot, new drivers will +need to be verified again, but any installed drivers will stay where +they are. This option is irritating if you are installing and +uninstalling the inf driver multiple times, but overall, is safer than +the custom root certificate described above. + +Purchasing a signed certificate is the best long term option, but it +is not useful for open source contributors, since the certificate will +be kept safe by the comma.ai team. Developers should use one of the +other two options. + +**Note that certificate issues apply no matter if you are building + from source or running an insaller .exe file.** + +Some people have reported that the driver installs without needing to +disable driver signing, or that visual studio correctly sets up a +temporary signing key for them. I call witchcraft because I have not +had that happen to me. The signed certificate is still the correct +thing to do in the end. + +Windows 7 will not force driver signing. This software is not tested +on anything before 7. + +# Developing: + +- Edit and merge pandaJ2534DLL\J2534register_x64.reg to register your development J2534 DLL. +- Add your output directory (panda\drivers\windows\Debug_x86) to your system PATH to avoid insanity. + +# ToDo Items: + +- Get official signing key for WinUSB driver inf file. +- Implement TxClear and RxClear. (Requires reading vague specifications). +- Apply a style-guide and consistent naming convention for Classes/Functions/Variables. +- Send multiple messages (each with a different address) from a given connection at the same time. +- Implement ISO14230/KWP2000 FAST (LIN communication is already supported with the raw panda USB driver). +- Find more documentation about SW_CAN_PS (Single Wire CAN, aka GMLAN). +- Find example of client using a _PS version of a protocol (PS is pin select, and may support using different CAN buses). + + +# Known Issues: + +- ISO15765 Multi-frame TX: Hardware delays make transmission overshoot + STMIN by several milliseconds. This does not violate the requirements + of STMIN, it just means it is a little slower than it could be. + +- All Tx messages from a single Connection are serialized. This can be + relaxed to allow serialization of messages based on their address + (making multiple queues, effectively one queue per address). + +# Other: +Panda head ASCII art by dcau \ No newline at end of file diff --git a/drivers/windows/docs/Message_Size.png b/drivers/windows/docs/Message_Size.png new file mode 100644 index 0000000000..544df2b59a --- /dev/null +++ b/drivers/windows/docs/Message_Size.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a5001169b8cd0134bdaabd406587d310d246c7404e261a9cabfc95d79550e68d +size 57389 diff --git a/drivers/windows/docs/RxBits_defs.jpg b/drivers/windows/docs/RxBits_defs.jpg new file mode 100644 index 0000000000..c292a38594 --- /dev/null +++ b/drivers/windows/docs/RxBits_defs.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7da942e643cfd7ff240644282845282f971b744c38d7f902ab23c53799ababa1 +size 356832 diff --git a/drivers/windows/docs/RxBits_valid.png b/drivers/windows/docs/RxBits_valid.png new file mode 100644 index 0000000000..a5062f590e --- /dev/null +++ b/drivers/windows/docs/RxBits_valid.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3a9460894bd6e01e687f24d392eb26e7c9859b7dc9eedd33be9c5a8315604109 +size 114419 diff --git a/drivers/windows/docs/bus_init_signla.png b/drivers/windows/docs/bus_init_signla.png new file mode 100644 index 0000000000..72e7a38caa --- /dev/null +++ b/drivers/windows/docs/bus_init_signla.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ec8cb5779af0269f68462e8015d26a15576e8444e75a1a51f8fc7cddcfadc1a6 +size 109347 diff --git a/drivers/windows/docs/connection_flags.png b/drivers/windows/docs/connection_flags.png new file mode 100644 index 0000000000..dde47431d7 --- /dev/null +++ b/drivers/windows/docs/connection_flags.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ef995a193070b65697bbbd4c805ca73ff588ed20676cfa09c8b1f9013ec8ef88 +size 57588 diff --git a/drivers/windows/docs/iso15765_ioctls.png b/drivers/windows/docs/iso15765_ioctls.png new file mode 100644 index 0000000000..8b5b7e48f9 --- /dev/null +++ b/drivers/windows/docs/iso15765_ioctls.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c5df429d7b8583282af22ffa37a062034d7588b62e1517c17b85423755ee1db4 +size 45301 diff --git a/drivers/windows/docs/message_send.png b/drivers/windows/docs/message_send.png new file mode 100644 index 0000000000..b01c001dab --- /dev/null +++ b/drivers/windows/docs/message_send.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a0fddaf25f6600d74d05c91a4459cc6664fbf06eaf3b786e4ab3c1b9ca81f9c6 +size 95451 diff --git a/drivers/windows/docs/msg_filter_passfail.png b/drivers/windows/docs/msg_filter_passfail.png new file mode 100644 index 0000000000..2d8a247d05 --- /dev/null +++ b/drivers/windows/docs/msg_filter_passfail.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:90c48ae0cdc66d0acd6b8c4f4e568f2c1128b0bdf1f2adf1f3cda71f3c4ba906 +size 111538 diff --git a/drivers/windows/docs/other notes.txt b/drivers/windows/docs/other notes.txt new file mode 100644 index 0000000000..a066d26465 --- /dev/null +++ b/drivers/windows/docs/other notes.txt @@ -0,0 +1,347 @@ +When using the ISO 15765-4 protocol, only SingleFrame messages can be transmitted without a matching +flow control filter. Also, PCI bytes are transparently added by the API. See PassThruStartMsgFilter +and Appendix A for a discussion of flow control filters. + + + +PassThruReadMsgs +This function reads messages and indications from the receive buffer. All messages and indications shall +be read in the order that they occurred on the bus. If a transmit message generated a loopback message +and TxDone indication, the TxDone indication shall always be queued first. Except for loopback messages +and indications, no messages shall be queued for reception without matching a PASS_FILTER +(for non-ISO 15765) or FLOW_CONTROL filter (for ISO 15765). On ISO 15765, PCI bytes are transparently +removed by the API. If the function is successful, a value of STATUS_NOERROR is returned. + + +PassThruWriteMsgs +Write timeout (in milliseconds). When a value of 0 is specified, the function queues as +many of the specified messages as possible and returns immediately. When a value +greater than 0 is specified, the function will block until the Timeout has expired, an error +has occurred, or the desired number of messages have been transmitted on the vehicle +network. Even if the device can buffer only one packet at a time, this function shall be +able to send an arbitrary number of packets if a Timeout value is supplied. Since the +function returns early if all the messages have been sent, there is normally no penalty for +having a large timeout (several seconds). If the number of messages requested have +been written, the function shall not return ERR_TIMEOUT, even if the timeout value is +zero. + +When an ERR_TIMEOUT is returned, only the number of messages that were sent on +the vehicle network is known. The number of messages queued is unknown. Application +writers should avoid this ambiguity by using a Timeout value large enough to work on +slow devices and networks with arbitration delays. + + + +PassThruStartPeriodicMsg +This function will immediately queue the specified message for transmission, and repeat at the specified +interval. Periodic messages are limited in length to a single frame message of 12 bytes or less, including +header or CAN ID. Periodic messages shall have priority over messages queued with +PassThruWriteMsgs, but periodic messages must not violate bus idle timing parameters (e.g. P3_MIN). +Periodic messages shall generate TxDone indications (ISO 15765) and loopback messages (on any +protocol, if enabled). On ISO 15765, periodic messages can be sent during a multi-frame transmission or +reception. If the function is successful, a value of STATUS_NOERROR is returned. The Pass-Thru +device must support a minimum of ten periodic messages. + +PassThruDisconnect shall delete all periodic messages on that channel. PassThruClose shall delete all +periodic messages on all channels for the device. All periodic messages will be stopped on a +PassThruDisconnect for the associated protocol or a PassThruClose for the device. + + + +PASSTHRUSTARTMSGFILTER +This function starts filtering of incoming messages. If the function is successful, a value of +STATUS_NOERROR is returned. A minimum of ten message filters shall be supported by the interface +for each supported protocol. PassThruDisconnect shall delete all message filters on that channel. + +PassThruClose shall delete all filters on all channels for the device. Pattern and Mask messages shall +follow the protocol formats specified in Section 8. However, only the first twelve (12) bytes, including +header or CAN ID, are used by the filter. ERR_INVALID_MSG shall be returned if the filter length +exceeds 12. Note that this function does not clear any messages that may have been received and +queued before the filter was set. Users are cautioned to consider performing a CLEAR_RX_BUFFER +after starting a message filter to be sure that unwanted frames are purged from any receive buffers. + + + + + + + + +FILTER RELATED STUFF +For all protocols except ISO 15765: +• PASS_FILTERs and BLOCK_FILTERs will be applied to all received messages. They shall not be +applied to indications or loopback messages + +• FLOW_CONTROL_FILTERs must not be used and shall cause the interface to return +ERR_INVALID_FILTER_ID + +• Both pMaskMsg and pPatternMsg must have the same DataSize and TxFlags. Otherwise, the +interface shall return ERR_INVALID_MSG + +• The default filter behavior after PassThruConnect is to block all messages, which means no messages +will be placed in the receive queue until a PASS_FILTER has been set. Messages that match a +PASS_FILTER can still be blocked by a BLOCK_FILTER + +• Figure 16 and Figure 17 show how the message filtering mechanism operates + +For ISO 15765: +• PASS_FILTERs and BLOCK_FILTERs must not be used and shall cause the interface to return +ERR_INVALID_FILTER_ID + +• Filters shall not be applied to indications or loopback messages. When loopback is on, the original +message shall be copied to the receive queue upon the last segment being transmitted on the bus. + +• Non-segmented messages do not need to match a FLOW_CONTROL_FILTER. + +• No segmented messages can be transmitted without matching an appropriate FLOW_CONTROL_FILTER. +An appropriate filter is one in which the pFlowControlMsg CAN ID matches the messages to be +transmitted. Also, the ISO 15765_ADDR_TYPE (reference TxFlags in Section 8.7.3) bits must match. +If that bit is set, the first byte after the CAN IDs (the extended address) +must match too. + +• No message (segmented or unsegmented) shall be received without matching an appropriate +FLOW_CONTROL_FILTER. An appropriate filter is one in which the pPatternMsg CAN ID matches +the incoming message ID. If the ISO 15765_ADDR_TYPE (reference TxFlags in Section 8.7.3) bit is +set in the filter, the first byte after the CAN IDs (the extended address) must match too. + +• All 3 message pointers must have the same DataSize and TxFlags. Otherwise, the interface shall +return ERR_INVALID_MSG. + +• Both the pFlowControlMsg ID and the pPatternMsg ID must be unique (not match any IDs in any other +filters). The only exception is that pPatternMsg can equal pFlowControlMsg to allow for receiving +functionally addressed messages. In this case, only non-segmented messages can be received. + +• See Appendix A for a detailed description of flow control filter usage. + + + + +8.4 Format Checks for Messages Passed to the API +The vendor DLL shall validate all PASSTHRU_MSG structures, and return an ERR_INVALID_MSG in the following cases: +• DataSize violates Min Tx or Max Tx columns in Figure 42 + +• Source address (Data[3]) is different from the Node ID (Ioctl SET_CONFIG, Parameter NODE_ADDRESS) on J1850PWM + +• The header length field is incorrect for the number of bytes in the message on ISO14230 + +• The CAN_29_BIT flag of the message does not match the CAN_29_BIT flag passed to +PassThruConnect, unless the CAN_ID_BOTH bit was set on connect + +The vendor DLL shall return ERR_MSG_PROTOCOL_ID when the ProtocolID field in the message does +not match the Protocol ID specified when opening the channel. + + + +8.5 Conventions for Returning Messages from the API +When returning a message in PassThruReadMsg: +– DataSize shall tell the application how many bytes in the Data array are valid. ExtraDataIndex will be +the (non-zero) index of the last byte of the message. If ExtraDataIndex is not equal to DataSize there +are extra data bytes after the message. If loopback is on, RxStatus must be consulted to tell if the +message came via loopback. + +– DataSize will be in the range shown in the Min Rx and Max Rx columns of Figure 42. If the device +receives a message from the vehicle bus that is too long or too short, the message shall be discarded +with no error. + +– For received messages, ExtraDataIndex shall be equal to DataSize, except when the interface is +returning SAE J1850 PWM IFR bytes. In no case shall ExtraDataIndex be larger than DataSize. + +– When receiving a message on an SAE J1850 PWM channel, the message shall have any IFR bytes +appended. In this case, ExtraDataIndex shall be the index of the first IFR byte, and DataSize shall be +the total length of the original message plus all IFR bytes. For example, if there are two IFR bytes, +DataSize will be incremented by two, and ExtraDataIndex will be DataSize - 2. When loopback is on, +the loopback message shall contain any IFR bytes. + + + +8.6 Conventions for Retuning Indications from the API +When returning an indication in PassThruReadMsg: +– ExtraDataIndex must be zero + +– DataSize shall tell the application how many bytes in the Data array are valid + +– RxStatus must be consulted to determine the indication type (See Section 8.4). + +– A TxDone indication (ISO 15765 only) is generated by the DLL after a SingleFrame message is sent, +or the last frame of a multi-segment transmission is sent. DataSize shall be 4 (or 5 when the message +was using Extended Addressing). Data shall contain the CAN ID (and possible Extended Address) of +the message just sent. If loopback is on, the TxDone indication shall precede the loopback message in +the receive queue. + +– An RxBreak indication (SAE J2610/SCI and SAE J1850VPW only) is generated by the DLL if a break +is received. + +– An RxStart indication is generated by the DLL when starting to receive a message on ISO9141 or +ISO14230, or when receiving the FirstFrame signal of a multi-segment ISO 15765 message. + + + +9.1 Naming of Files +Each vendor will provide a different name implementation of the API DLL and a number of these +implementations could simultaneously reside on the same PC. No vendor shall name its implementation +“J2534.DLL”. All implementations shall have the string “32” suffixed to end of the name of the API DLL to +indicate 32-bit. For example, if the company name is “Vendor X” the name could be VENDRX32.DLL. + +For simplicity, an API DLL shall be named in accordance with the file allocation table (FAT) file system +naming convention (which allows up to eight characters for the file name and three characters for the +extension with no spaces anywhere). Note that, given this criteria, the major name of an API DLL can be +no greater than six characters. The OEM application can determine the name of the appropriate vendor’s +DLL using the Win32 Registry mechanism described in this section. + + + + +A.1 Flow Control Overview +ISO 15765-2 was designed to send blocks of up to 4095 bytes on top of the limited 8-byte payload of raw +CAN frames. If the data is small enough, it can fit in a single frame and be transmitted like a raw CAN +message with additional headers. Otherwise, the block is broken up into segments and becomes a +segmented transmission, generating CAN frames in both directions. For flexibility, the receiver of the +segments can control the rate at which the segments are sent. + +Each transmission is actually part of a conversation between two nodes. There is no discovery +mechanism for conversation partners. Therefore, each desired conversation must be pre-defined on each +side before the conversation can start. Conversations are symmetric, meaning that either side can send a +block of data to the other. A conversation can only have one transfer (in one direction) in progress at a +time. One transfer must complete before the next transfer (in the same or in a different direction) can +start. The device must support multiple transfers at once, as long as each one is part of a different +conversation. Raw CAN frames are not allowed when using ISO15765-2. + +A key feature of a conversation is that each side has a unique CAN ID, and each side uses their unique +CAN ID for all transmissions during the conversation. No other CAN IDs are part of the conversation. +Even though the useful data is only flowing in one direction, both sides are transmitting. One side is +sending the flow control message to pace the segments of data coming from the other side. + +For example, during OBD communication, a pass-thru device and an ECU might have a conversation. +The pass-thru device will use the "Tester1" physical CAN ID ($241), and the first ECU will use the +"ECU1" physical CAN ID ($641). During a multi-segment transfer, both sides will be transmitting using +only their respective IDs. It does not matter if the data is being sent by the ECU or by the Tester, the IDs +remain the same. + +It is important to understand the difference between OBD Requests/Responses and ISO 15765-2 +transfers. The OBD Request is transmitted from the Tester to the ECU using functional addressing. +Because segmented transfer is not possible on functional addresses, the message must fit in a single +frame. The OBD Response is a message from the ECU to the Tester using physical addressing. Unlike +other protocols, the responses are not sequential. In fact, the responses can overlap, as if each ECU +were having a private conversation with the Tester. Some of the responses may fit in a single frame, +while others will require a segmented transfer from the ECU to the tester. + + +A.2 Transmitting a Segmented Message +When PassThruWrite is called, the API will search the list of flow control filters, looking for a +pFlowControlMsg that matches the CAN ID (and possible extended address) of the message being sent. +Upon matching a filter, the pass-thru device will: + +• Start the ISO 15765 transfer by sending a FirstFrame on the bus. The CAN ID of this segment was +specified in both the message and the matching pFlowControlMsg. In our example, this is $241. + +• Wait for a FlowControl frame from the conversation partner. The CAN ID to look for is specified in the +corresponding pPatternMsg. In our example, this is $641. + +• Transmit the message data in ConsecutiveFrames according to the FlowControl frame’s instructions +for BS (BlockSize) and STmin (SeparationTime minimum). Again, the pass-thru device transmits using +CAN ID specified in pFlowControlMsg. In our example, this is $241. + +• Repeat the previous two steps as required. + +• When finished, the pass-thru device will place a TxDone indication in the API receive queue. The data +will contain the CAN ID specified in pFlowControlMsg. In our example, this is $241. + +• If loopback is on, the entire message sent will appear in the API receive queue with the +TX_MSG_TYPE bit set to 1 in RxStatus. The loopback shall not precede the TxDone indication. + +Before any multi-segment transfer can take place, the conversation must be set up on both sides. It’s +assumed that the ECU is already setup. The application is responsible for setting up the pass-thru device. +This setup must be done once (and only once) per conversation. The setup involves a single call to +PassThruStartMsgFilter, with the following parameters: + +A.2.2 Data Transmission +Once the conversation is set up, any number of messages (to the conversation partner) can be +transmitted using PassThruWriteMsg. The interface shall handle all aspects of the transfer, including +pacing (slowing) the transmission to the requirements of the receiver. + +When there are multiple conversations setup, the pass-thru device will search all of the flow control filters +for a matching pFlowControlMsg. If there is no match, the message cannot be sent because the pass- +thru device doesn’t know which partner will be pacing the conversation. + +When doing blocking writes, it is important to pick a timeout long enough to cover entire transfer, even if +the ECU is pacing things slowly. Otherwise PassThruWriteMsg will return with a timeout, even though the +transmission is proceeding normally. + + +A.3 Transmitting an Unsegmented Message +As a special case, transfers that fit in a single frame can be transmitted without setting up a conversation. +This is useful during an OBD Request, which is a functionally addressed message that is broadcast to all +ECUs. This message must be small enough to fit into a single frame (including headers) because it is not +possible to do one segmented transfer to multiple ECUs. + +When using functional addressing for an OBD Request, it is important to remember that there can be no +direct reply. Instead, each ECU will send their OBD Response using physical addressing to their +conversation partner (e.g. ECU1 to Tester1, ECU2 to Tester2) as defined by ISO 15765-4. The OBD +Response may be a segmented transfer, or it may be a single frame. + +In this case, no conversation setup is necessary. The call to PassThruWriteMsg is the same as above, +except that the DataSize must be 7 bytes or less (6 bytes or less if extended addressing is turned on). +The pass-thru device will automatically insert a PCI byte before transmission. + + +A.4 Receiving a Segmented Message +Message reception is asynchronous to the application. When a FirstFrame is seen on the bus, the pass- +thru device will search the list of flow control filters, looking for a pPatternMsg message with the same +CAN ID (and possible extended address) as the FirstFrame. Upon matching a filter, the pass-thru device will: + +• Place an RxStart indication in the API receive queue. This indication has the START_OF_MESSAGE +bit set in RxFlags. The message data will contain the CAN ID of the sender. In our example, this is +$641. DataSize will be 4 bytes (5 with extended addressing), and ExtraDataIndex will be zero. + +• Send a FlowControl frame to the conversation partner. The FlowStatus field shall be set to +ontinueToSend. The CAN ID of this segment comes from the filter’s corresponding +pFlowControlMsg. In our example, this CAN ID is $241. The BS (BlockSize) and STmin +(SeparationTime minimum) parameters default to zero, but can be changed with the SET_CONFIGIoctl. + +• Wait for the conversation partner to send C +onsecutiveFrames containing the actual data. The +partner’s CAN ID is specified in pPatternMsg. In our example, this CAN ID is $641. + +• Repeat as necessary until the entire block has been received. When finished, the pass-thru device will +put the assembled message into the API receive queue. The CAN ID of the assembled message will +be the CAN ID of the sender. In our example, this CAN ID is $641. + +If the FirstFrame does not match any flow control filters, then the message must be ignored by the +device. + +Segmented messages cause the API to generate an RxStart indication. This lets the application know +that the device has started message reception. It may take a while before message reception is +complete, especially if the application has increased BS and STmin. + +Once the transfer is complete, the entire message can be read like on any other protocol. Usually, +applications will call PassThruReadMsg again immediately after getting an RxStart indication. Application +writers should not assume that the complete message will always follow the RxStart indication. If multiple +conversations are setup, indications and messages from other conversations can be received in between +the RxStart indication and the actual message. The parameters for PassThruReadMsg are exactly the +same as in the previous section. The only difference is that the DataSize will be larger and +ExtraDataIndex will be non-zero. + + + +A.5 Receiving an Unsegmented Message +No messages can be received until a conversation is setup. Each conversation setup will receive +messages from exactly one CAN ID (and extended address if present). Because setup is bi-directional, +the same PassThruStartMsgFilter call used for transmission will allow for message reception. + +When a SingleFrame is seen on the bus, the pass-thru device will search the list of flow control filters, +looking for a pPatternMsg message with the same C +AN ID (and possible extended address) as the +SingleFrame. Upon matching a filter, the pass-thru device will strip the PCI byte and queue the packet for +reception. If the SingleFrame does not match a flow control filter, it must be discarded. + +The only difference between the previous cases is that single-frame messages do not generate an +RxStart indication. + + + + + + + + + diff --git a/drivers/windows/docs/read_msg_flags.png b/drivers/windows/docs/read_msg_flags.png new file mode 100644 index 0000000000..5ad2030739 --- /dev/null +++ b/drivers/windows/docs/read_msg_flags.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2cb9141d3e34f2ff4e8c4bfaf4a44e767bfadde554668898fedaa49b24cb0a59 +size 68261 diff --git a/drivers/windows/docs/reginfo.txt b/drivers/windows/docs/reginfo.txt new file mode 100644 index 0000000000..03182832b2 --- /dev/null +++ b/drivers/windows/docs/reginfo.txt @@ -0,0 +1,2 @@ +#32 bit: HKEY_LOCAL_MACHINE\SOFTWARE\PassThruSupport +#64 bit: HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\PassThruSupport diff --git a/drivers/windows/docs/start_msg_filter.png b/drivers/windows/docs/start_msg_filter.png new file mode 100644 index 0000000000..219bf38fe9 --- /dev/null +++ b/drivers/windows/docs/start_msg_filter.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e6178c796ef687baf4025ea774441ac1bf1f633b48f7861ef2795bf85fe6e41c +size 71232 diff --git a/drivers/windows/docs/start_msg_filter2.png b/drivers/windows/docs/start_msg_filter2.png new file mode 100644 index 0000000000..a4f03a9d44 --- /dev/null +++ b/drivers/windows/docs/start_msg_filter2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:389b567f15fd3e96ce994d2a2de812de3b720c0568d296a5797868e0dc770be9 +size 70796 diff --git a/drivers/windows/docs/start_msg_filter3.png b/drivers/windows/docs/start_msg_filter3.png new file mode 100644 index 0000000000..498232bdbe --- /dev/null +++ b/drivers/windows/docs/start_msg_filter3.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:64da21aafe74dc29c2afbc77d2d52648f6163e3ffff4f7a0e4ab478d432a2dc1 +size 46516 diff --git a/drivers/windows/docs/start_msg_filter4.png b/drivers/windows/docs/start_msg_filter4.png new file mode 100644 index 0000000000..eb03d73e10 --- /dev/null +++ b/drivers/windows/docs/start_msg_filter4.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6342dc69b7a578c457099cb949eba9a0e0f73efd3e84556dcde362070f9e07b9 +size 46333 diff --git a/drivers/windows/docs/timeout_info.txt b/drivers/windows/docs/timeout_info.txt new file mode 100644 index 0000000000..22cfa2c5d5 --- /dev/null +++ b/drivers/windows/docs/timeout_info.txt @@ -0,0 +1,42 @@ +From focum information on NI hardware: https://forums.ni.com/t5/Automotive-and-Embedded-Networks/15765-2-with-NI-products/td-p/1454256 + +///////////////////////////////////////////////////////////////////// +Timeout Diag Command is the timeout in milliseconds the master +waits for the response to a diagnostic request message. The default is +1000 ms. + +Timeout FC (Bs) is the timeout in milliseconds the master waits +for a Flow Control frame after sending a First Frame or the last +Consecutive Frame of a block. The default is 250 ms. + +Timeout CF (Cr) is the timeout in milliseconds the master waits +for a Consecutive Frame in a multiframe response. The default is +250 ms. + +Receive Block Size (BS) is the number of Consecutive Frames the +slave sends in one block before waiting for the next Flow Control +frame. A value of 0 (default) means all Consecutive Frames are sent +in one run without interruption. + +Wait Time CF (STmin) defines the minimum time for the slave to +wait between sending two Consecutive Frames of a block. Values +from 0 to 127 are wait times in milliseconds. Values 241 to 249 +(Hex F1 to F9) mean wait times of 100 μs to 900 μs, respectively. +All other values are reserved. The default is 5 ms. + +Max Wait Frames (N_WFTmax) is the maximum number of WAIT +frames the master accepts before terminating the connection. The +default is 10. + + +There are no defined lower limits for these values; you can specify any +value down to 0. However, as you correctly pointed out, the timing is +done by Windows, and will be subject to the jitter introduced by the OS +which can easily be in the order of 10s of milliseconds. It is however +hard to give more accurate numbers as the actual jitter is dependent on +the workload of the computer +///////////////////////////////////////////////////////////////////// + +J2534 04.04 does not appear to have default adjustable parameters for +the timeout related fields. For now, these default values shall be used +in the Panda J2534 implementation. diff --git a/drivers/windows/panda Driver Package/panda Driver Package.vcxproj b/drivers/windows/panda Driver Package/panda Driver Package.vcxproj new file mode 100644 index 0000000000..5b448e96a8 --- /dev/null +++ b/drivers/windows/panda Driver Package/panda Driver Package.vcxproj @@ -0,0 +1,99 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + + {BD34DB24-F5DC-4992-A74F-05FAF731ABED} + {a1357fe7-03e0-4d61-85f4-09c7ed38c0c1} + v4.5 + 12.0 + $driverCurrentWindowsConfigurationName$ Debug + Win32 + panda_Driver_Package + $(LatestTargetPlatformVersion) + + + + Windows10 + true + WindowsKernelModeDriver10.0 + Utility + Package + true + + + Windows10 + false + WindowsKernelModeDriver10.0 + Utility + Package + true + + + + + + + + + + + + DbgengRemoteDebugger + + + + False + False + True + + 133563 + $(SolutionDir)$(Configuration)_$(PlatformShortName)\ + + + + DbgengRemoteDebugger + + + + False + False + True + + 133563 + $(SolutionDir)$(Configuration)_$(PlatformShortName)\ + + + + + + + + + + + + + + $(KMDF_VERSION_MAJOR).$(KMDF_VERSION_MINOR) + + + + + + + $(KMDF_VERSION_MAJOR).$(KMDF_VERSION_MINOR) + + + + + + \ No newline at end of file diff --git a/drivers/windows/panda Driver Package/panda Driver Package.vcxproj.filters b/drivers/windows/panda Driver Package/panda Driver Package.vcxproj.filters new file mode 100644 index 0000000000..b4cf077981 --- /dev/null +++ b/drivers/windows/panda Driver Package/panda Driver Package.vcxproj.filters @@ -0,0 +1,14 @@ + + + + + {8E41214B-6785-4CFE-B992-037D68949A14} + inf;inv;inx;mof;mc; + + + + + Driver Files + + + \ No newline at end of file diff --git a/drivers/windows/panda Driver Package/panda.inf b/drivers/windows/panda Driver Package/panda.inf new file mode 100644 index 0000000000000000000000000000000000000000..69390dcbc0616f2c9466d1cfb57dd592395ab6eb GIT binary patch literal 4242 zcmchaTTdHD6vxkVrGAH11brfI%&k!52RlH55+K45q>>6bwxOs5BQK;uQNMcI-+#`I zXT5k6w^E~#y*qQxocnG6{%gy=x9@DrGP|{&-PnNthF$S?Q9vSmkF(tFfM2t6Zkz_Z z6W-sKaD{(nZ*6E}AXhfx-md}PWp~N02bFuELuj=4J+Xy?)&T530__7k=JZLp_Z)sb zPQ^1W-8-?ab!;0tAEDgmDc%YD1sHq4oy%w2V0El*JNC?0Y}uaL8oLc^^0sQ5X#9+~ z4ir|n^%U5u?XsHeH^6V&I_K;5XW;V&4Mu_UAn58`7HuC{Z_w|8XMdvU*bdl#0CTaB zQdW>HN7!T+`LBVsro7MxeiyK#4_aVUS60jMM<63SIxPH^^CpShC$eUhmhZ*Qy;!G< z`*RCj>M)YFZkKM**5hl8OiS299&Xza_I}Bm)105;zCBDLuo?$W{S#hWFF48e19qz= zd!7+L@c4#9BE+mL?JUj%-jIo)cS&zqb8gZ;F#`&Y!c&Hm}#q z<#WBFy=KeRDzf9-NtG=8EhSUsnjOW})2!kj<(6l{ycCj;W_#TARuuHfxciWKE$W%7 z={?o!{ZwT=ARC9^raLu4PEA)4c`8=7ax}MUaUVy$GW8bQ#W_ngS7)<0od?J?cFLUk zTV>fimy!qSZfOcF*V$>?pJKU-8aWq;kA1RX7x-c59$hL|+g`JFh@7|KzYFA$h*==k z6+PE*`x4c%hw5aWWgpk~OO*esyvg#4V)YhPgVej#DN=m=8<|_grq^llm~W2A=yxM> zejIW_^+z523V8%6PuKI#6q-_!j%DiJ1Aj;7nDH?SnsD>p5pg1hcRkV5Y?~yFczG!U z{y(3|vQek`>?$kBg6gI6?`5dB)d_C)K63JDKHYcyzV?06qAK;Vlq$cze0%V(esxCc z3Rj)tiZ0+)N#AeodGYmKC-j8rZjl!>x5(D`EnB8~NYB-Gs%l6t^heQmIil~%_{T+` zRQ>X5euG5nT6_F1kwCeUqmR?5&R^w8Nm`|E|JbQ~-cY}lX0C6PCw0NHOo@i$9Z`W^ b@XfQ2&0bTR_IU5wFUTifr`a;qJbCgThdPlt literal 0 HcmV?d00001 diff --git a/drivers/windows/panda.ico b/drivers/windows/panda.ico new file mode 100644 index 0000000000..2bfeca5bea --- /dev/null +++ b/drivers/windows/panda.ico @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dbc9e8626328efb1cf1167fefe42145425839e4df1c69481641dee7f558a5618 +size 97642 diff --git a/drivers/windows/panda.sln b/drivers/windows/panda.sln new file mode 100644 index 0000000000..a74e4022bf --- /dev/null +++ b/drivers/windows/panda.sln @@ -0,0 +1,90 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.25420.1 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "pandaJ2534DLL", "pandaJ2534DLL\pandaJ2534DLL.vcxproj", "{A2BB18A5-F26B-48D6-BBB5-B83D64473C77}" + ProjectSection(ProjectDependencies) = postProject + {5528AEFB-638D-49AF-B9D4-965154E7D531} = {5528AEFB-638D-49AF-B9D4-965154E7D531} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "panda", "panda\panda.vcxproj", "{5528AEFB-638D-49AF-B9D4-965154E7D531}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "panda_playground", "panda_playground\panda_playground.vcxproj", "{691DB635-C272-4B98-897E-0505B970DCA9}" + ProjectSection(ProjectDependencies) = postProject + {5528AEFB-638D-49AF-B9D4-965154E7D531} = {5528AEFB-638D-49AF-B9D4-965154E7D531} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "panda Driver Package", "panda Driver Package\panda Driver Package.vcxproj", "{BD34DB24-F5DC-4992-A74F-05FAF731ABED}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Tests", "pandaJ2534DLL Test\pandaJ2534DLL Test.vcxproj", "{7912F978-B48C-4C5D-8BFD-5D1E22158E47}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ECUsim DLL", "ECUsim DLL\ECUsim DLL.vcxproj", "{96E0E646-EE76-444D-9A77-A0CD7F781DEB}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ECUsim CLI", "ECUsim CLI\ECUsim CLI.vcxproj", "{D99E2FCD-21A4-4065-949A-31E34E0E69D1}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {A2BB18A5-F26B-48D6-BBB5-B83D64473C77}.Debug|x64.ActiveCfg = Debug|Win32 + {A2BB18A5-F26B-48D6-BBB5-B83D64473C77}.Debug|x86.ActiveCfg = Debug|Win32 + {A2BB18A5-F26B-48D6-BBB5-B83D64473C77}.Debug|x86.Build.0 = Debug|Win32 + {A2BB18A5-F26B-48D6-BBB5-B83D64473C77}.Release|x64.ActiveCfg = Release|Win32 + {A2BB18A5-F26B-48D6-BBB5-B83D64473C77}.Release|x86.ActiveCfg = Release|Win32 + {A2BB18A5-F26B-48D6-BBB5-B83D64473C77}.Release|x86.Build.0 = Release|Win32 + {5528AEFB-638D-49AF-B9D4-965154E7D531}.Debug|x64.ActiveCfg = Debug|x64 + {5528AEFB-638D-49AF-B9D4-965154E7D531}.Debug|x64.Build.0 = Debug|x64 + {5528AEFB-638D-49AF-B9D4-965154E7D531}.Debug|x86.ActiveCfg = Debug|Win32 + {5528AEFB-638D-49AF-B9D4-965154E7D531}.Debug|x86.Build.0 = Debug|Win32 + {5528AEFB-638D-49AF-B9D4-965154E7D531}.Release|x64.ActiveCfg = Release|x64 + {5528AEFB-638D-49AF-B9D4-965154E7D531}.Release|x64.Build.0 = Release|x64 + {5528AEFB-638D-49AF-B9D4-965154E7D531}.Release|x86.ActiveCfg = Release|Win32 + {5528AEFB-638D-49AF-B9D4-965154E7D531}.Release|x86.Build.0 = Release|Win32 + {691DB635-C272-4B98-897E-0505B970DCA9}.Debug|x64.ActiveCfg = Debug|x64 + {691DB635-C272-4B98-897E-0505B970DCA9}.Debug|x64.Build.0 = Debug|x64 + {691DB635-C272-4B98-897E-0505B970DCA9}.Debug|x86.ActiveCfg = Debug|Win32 + {691DB635-C272-4B98-897E-0505B970DCA9}.Debug|x86.Build.0 = Debug|Win32 + {691DB635-C272-4B98-897E-0505B970DCA9}.Release|x64.ActiveCfg = Release|x64 + {691DB635-C272-4B98-897E-0505B970DCA9}.Release|x64.Build.0 = Release|x64 + {691DB635-C272-4B98-897E-0505B970DCA9}.Release|x86.ActiveCfg = Release|Win32 + {691DB635-C272-4B98-897E-0505B970DCA9}.Release|x86.Build.0 = Release|Win32 + {BD34DB24-F5DC-4992-A74F-05FAF731ABED}.Debug|x64.ActiveCfg = Debug|Win32 + {BD34DB24-F5DC-4992-A74F-05FAF731ABED}.Debug|x86.ActiveCfg = Debug|Win32 + {BD34DB24-F5DC-4992-A74F-05FAF731ABED}.Debug|x86.Build.0 = Debug|Win32 + {BD34DB24-F5DC-4992-A74F-05FAF731ABED}.Debug|x86.Deploy.0 = Debug|Win32 + {BD34DB24-F5DC-4992-A74F-05FAF731ABED}.Release|x64.ActiveCfg = Release|Win32 + {BD34DB24-F5DC-4992-A74F-05FAF731ABED}.Release|x86.ActiveCfg = Release|Win32 + {BD34DB24-F5DC-4992-A74F-05FAF731ABED}.Release|x86.Build.0 = Release|Win32 + {BD34DB24-F5DC-4992-A74F-05FAF731ABED}.Release|x86.Deploy.0 = Release|Win32 + {7912F978-B48C-4C5D-8BFD-5D1E22158E47}.Debug|x64.ActiveCfg = Debug|Win32 + {7912F978-B48C-4C5D-8BFD-5D1E22158E47}.Debug|x86.ActiveCfg = Debug|Win32 + {7912F978-B48C-4C5D-8BFD-5D1E22158E47}.Debug|x86.Build.0 = Debug|Win32 + {7912F978-B48C-4C5D-8BFD-5D1E22158E47}.Release|x64.ActiveCfg = Release|Win32 + {7912F978-B48C-4C5D-8BFD-5D1E22158E47}.Release|x86.ActiveCfg = Release|Win32 + {7912F978-B48C-4C5D-8BFD-5D1E22158E47}.Release|x86.Build.0 = Release|Win32 + {96E0E646-EE76-444D-9A77-A0CD7F781DEB}.Debug|x64.ActiveCfg = Debug|x64 + {96E0E646-EE76-444D-9A77-A0CD7F781DEB}.Debug|x64.Build.0 = Debug|x64 + {96E0E646-EE76-444D-9A77-A0CD7F781DEB}.Debug|x86.ActiveCfg = Debug|Win32 + {96E0E646-EE76-444D-9A77-A0CD7F781DEB}.Debug|x86.Build.0 = Debug|Win32 + {96E0E646-EE76-444D-9A77-A0CD7F781DEB}.Release|x64.ActiveCfg = Release|x64 + {96E0E646-EE76-444D-9A77-A0CD7F781DEB}.Release|x64.Build.0 = Release|x64 + {96E0E646-EE76-444D-9A77-A0CD7F781DEB}.Release|x86.ActiveCfg = Release|Win32 + {96E0E646-EE76-444D-9A77-A0CD7F781DEB}.Release|x86.Build.0 = Release|Win32 + {D99E2FCD-21A4-4065-949A-31E34E0E69D1}.Debug|x64.ActiveCfg = Debug|x64 + {D99E2FCD-21A4-4065-949A-31E34E0E69D1}.Debug|x64.Build.0 = Debug|x64 + {D99E2FCD-21A4-4065-949A-31E34E0E69D1}.Debug|x86.ActiveCfg = Debug|Win32 + {D99E2FCD-21A4-4065-949A-31E34E0E69D1}.Debug|x86.Build.0 = Debug|Win32 + {D99E2FCD-21A4-4065-949A-31E34E0E69D1}.Release|x64.ActiveCfg = Release|x64 + {D99E2FCD-21A4-4065-949A-31E34E0E69D1}.Release|x64.Build.0 = Release|x64 + {D99E2FCD-21A4-4065-949A-31E34E0E69D1}.Release|x86.ActiveCfg = Release|Win32 + {D99E2FCD-21A4-4065-949A-31E34E0E69D1}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/drivers/windows/panda/device.cpp b/drivers/windows/panda/device.cpp new file mode 100644 index 0000000000..a204610000 --- /dev/null +++ b/drivers/windows/panda/device.cpp @@ -0,0 +1,166 @@ +#include "stdafx.h" +#include +#include + +#include +#include + +#include "device.h" + +using namespace panda; + +//Returns the last Win32 error, in string format. Returns an empty string if there is no error. +tstring GetLastErrorAsString(){ + //Get the error message, if any. + DWORD errorMessageID = ::GetLastError(); + if (errorMessageID == 0) + return tstring(); //No error message has been recorded + + _TCHAR *messageBuffer = nullptr; + size_t size = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (_TCHAR*)&messageBuffer, 0, NULL); + + tstring message(messageBuffer, size); + + //Free the buffer. + LocalFree(messageBuffer); + + return message; +} + +std::unordered_map panda::detect_pandas() { + HDEVINFO deviceInfo; + HRESULT hr; + SP_DEVINFO_DATA deviceInfoData; + SP_DEVICE_INTERFACE_DATA interfaceData; + unsigned int deviceIndex; + + std::unordered_map map_sn_to_devpath; + + deviceInfo = SetupDiGetClassDevs(&GUID_DEVINTERFACE_panda, + NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); //DIGCF_ALLCLASSES + + if (deviceInfo == INVALID_HANDLE_VALUE) { + hr = HRESULT_FROM_WIN32(GetLastError()); + _tprintf(_T("Failed to get dev handle. HR: %d\n"), hr); + return map_sn_to_devpath; + } + + ZeroMemory(&deviceInfoData, sizeof(SP_DEVINFO_DATA)); + deviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA); + deviceIndex = 0; + + while (SetupDiEnumDeviceInfo(deviceInfo, deviceIndex, &deviceInfoData)) { + deviceIndex++; + _tprintf(_T("Device info index %d\n"), deviceIndex); + + interfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA); + if (SetupDiEnumDeviceInterfaces(deviceInfo, &deviceInfoData, + &GUID_DEVINTERFACE_panda, 0, &interfaceData) == FALSE) { + _tprintf(_T(" Got unexpected error while accessing interface %d\n"), GetLastError()); + continue; + } + + DWORD requiredLength; + if (SetupDiGetDeviceInterfaceDetail(deviceInfo, &interfaceData, NULL, 0, &requiredLength, NULL) == FALSE + && ERROR_INSUFFICIENT_BUFFER != GetLastError()) { + _tprintf(_T(" Got unexpected error while reading interface details %d\n"), GetLastError()); + continue; + } + + PSP_DEVICE_INTERFACE_DETAIL_DATA detailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)LocalAlloc(LMEM_FIXED, requiredLength); + if (NULL == detailData) { + _tprintf(_T(" Failed to allocate %d bytes for interface data\n"), requiredLength); + continue; + } + detailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA); + + DWORD length = requiredLength; + if (SetupDiGetDeviceInterfaceDetail(deviceInfo, &interfaceData, detailData, length, &requiredLength, NULL) == FALSE) { + _tprintf(_T(" Got unexpected error while reading interface details (2nd time) %d. Msg: '%s'\n"), + GetLastError(), GetLastErrorAsString().c_str()); + LocalFree(detailData); + continue; + } + + //_tprintf(_T(" Path: '%s'\n"), detailData->DevicePath); + HANDLE deviceHandle = CreateFile(detailData->DevicePath, + GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ, + NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL); + + if (INVALID_HANDLE_VALUE == deviceHandle) { + _tprintf(_T(" Error opening Device Handle %d. Msg: '%s'\n"), + GetLastError(), GetLastErrorAsString().c_str()); + LocalFree(detailData); + continue; + } + + WINUSB_INTERFACE_HANDLE winusbHandle; + if (WinUsb_Initialize(deviceHandle, &winusbHandle) == FALSE) { + _tprintf(_T(" Error initializing WinUSB %d. Msg: '%s'\n"), + GetLastError(), GetLastErrorAsString().c_str()); + CloseHandle(deviceHandle); + LocalFree(detailData); + continue; + } + + USB_DEVICE_DESCRIPTOR deviceDesc; + unsigned long lengthReceived; + if (WinUsb_GetDescriptor(winusbHandle, USB_DEVICE_DESCRIPTOR_TYPE, 0, 0, + (PBYTE)&deviceDesc, sizeof(deviceDesc), &lengthReceived) == FALSE + || lengthReceived != sizeof(deviceDesc)) { + _tprintf(_T(" Error getting device descriptor %d. Msg: '%s'\n"), + GetLastError(), GetLastErrorAsString().c_str()); + WinUsb_Free(winusbHandle); + CloseHandle(deviceHandle); + LocalFree(detailData); + continue; + } + + #define SNDESCLEN 64 + PUSB_STRING_DESCRIPTOR psnDesc = (PUSB_STRING_DESCRIPTOR)LocalAlloc(LMEM_FIXED, SNDESCLEN); + if (NULL == psnDesc) { + _tprintf(_T(" Failed to allocate %d bytes for sn data\n"), SNDESCLEN); + continue; + } + + if (WinUsb_GetDescriptor(winusbHandle, USB_STRING_DESCRIPTOR_TYPE, deviceDesc.iSerialNumber, + 0x0409 /*Eng*/, (PBYTE)psnDesc, SNDESCLEN, &lengthReceived) == FALSE || lengthReceived == 0) { + _tprintf(_T(" Error getting serial number %d. Msg: '%s'\n"), + GetLastError(), GetLastErrorAsString().c_str()); + LocalFree(psnDesc); + WinUsb_Free(winusbHandle); + CloseHandle(deviceHandle); + LocalFree(detailData); + continue; + } + //The minus 2 is for the two numbers, not the null term. + psnDesc->bString[(psnDesc->bLength - 2) / sizeof(_TCHAR)] = 0; + + char w_to_m_buff[256]; + size_t mbuff_len; + if (wcstombs_s(&mbuff_len, w_to_m_buff, sizeof(w_to_m_buff), psnDesc->bString, 24) != 0) { + _tprintf(_T(" Error generating mb SN string %d. Msg: '%s'\n"), + GetLastError(), GetLastErrorAsString().c_str()); + LocalFree(psnDesc); + WinUsb_Free(winusbHandle); + CloseHandle(deviceHandle); + LocalFree(detailData); + continue; + } + std::string serialnum(w_to_m_buff, mbuff_len-1); + printf(" Device found: seriallen: %d; serial: %s\n", lengthReceived, serialnum.c_str()); + + map_sn_to_devpath[serialnum] = tstring(detailData->DevicePath); + + LocalFree(psnDesc); + WinUsb_Free(winusbHandle); + CloseHandle(deviceHandle); + LocalFree(detailData); + } + + if(deviceInfo) + SetupDiDestroyDeviceInfoList(deviceInfo); + + return map_sn_to_devpath; +} diff --git a/drivers/windows/panda/device.h b/drivers/windows/panda/device.h new file mode 100644 index 0000000000..3b404857cf --- /dev/null +++ b/drivers/windows/panda/device.h @@ -0,0 +1,33 @@ +#ifndef __PANDA_DEVICE +#define __PANDA_DEVICE + +// +// Define below GUIDs +// +#include "stdafx.h" +#include +#include + +#if defined(UNICODE) +#define _tcout std::wcout +#define tstring std::wstring +#else +#define _tcout std::cout +#define tstring std::string +#endif + +// +// Device Interface GUID. +// Used by all WinUsb devices that this application talks to. +// Must match "DeviceInterfaceGUIDs" registry value specified in the INF file. +// cce5291c-a69f-4995-a4c2-2ae57a51ade9 +// +DEFINE_GUID(GUID_DEVINTERFACE_panda, + 0xcce5291c,0xa69f,0x4995,0xa4,0xc2,0x2a,0xe5,0x7a,0x51,0xad,0xe9); + +tstring GetLastErrorAsString(); + +namespace panda { + std::unordered_map __declspec(dllexport) detect_pandas(); +} +#endif diff --git a/drivers/windows/panda/dllmain.cpp b/drivers/windows/panda/dllmain.cpp new file mode 100644 index 0000000000..69b58914b3 --- /dev/null +++ b/drivers/windows/panda/dllmain.cpp @@ -0,0 +1,19 @@ +// dllmain.cpp : Defines the entry point for the DLL application. +#include "stdafx.h" + +BOOL APIENTRY DllMain( HMODULE hModule, + DWORD ul_reason_for_call, + LPVOID lpReserved + ) +{ + switch (ul_reason_for_call) + { + case DLL_PROCESS_ATTACH: + case DLL_THREAD_ATTACH: + case DLL_THREAD_DETACH: + case DLL_PROCESS_DETACH: + break; + } + return TRUE; +} + diff --git a/drivers/windows/panda/main.cpp b/drivers/windows/panda/main.cpp new file mode 100644 index 0000000000..621c600b82 --- /dev/null +++ b/drivers/windows/panda/main.cpp @@ -0,0 +1,79 @@ +#include "stdafx.h" + +#include + +LONG __cdecl +_tmain( + LONG Argc, + LPTSTR * Argv + ) +/*++ + +Routine description: + + Sample program that communicates with a USB device using WinUSB + +--*/ +{ + DEVICE_DATA deviceData; + HRESULT hr; + USB_DEVICE_DESCRIPTOR deviceDesc; + BOOL bResult; + BOOL noDevice; + ULONG lengthReceived; + + UNREFERENCED_PARAMETER(Argc); + UNREFERENCED_PARAMETER(Argv); + + // + // Find a device connected to the system that has WinUSB installed using our + // INF + // + hr = OpenDevice(&deviceData, &noDevice); + + if (FAILED(hr)) { + + if (noDevice) { + + printf(_T("Device not connected or driver not installed\n")); + + } else { + + printf(_T("Failed looking for device, HRESULT 0x%x\n"), hr); + } + + return 0; + } + + // + // Get device descriptor + // + bResult = WinUsb_GetDescriptor(deviceData.WinusbHandle, + USB_DEVICE_DESCRIPTOR_TYPE, + 0, + 0, + (PBYTE) &deviceDesc, + sizeof(deviceDesc), + &lengthReceived); + + if (FALSE == bResult || lengthReceived != sizeof(deviceDesc)) { + + printf(_T("Error among LastError %d or lengthReceived %d\n"), + FALSE == bResult ? GetLastError() : 0, + lengthReceived); + CloseDevice(&deviceData); + return 0; + } + + // + // Print a few parts of the device descriptor + // + printf(_T("Device found: VID_%04X&PID_%04X; bcdUsb %04X; path: %s\n"), + deviceDesc.idVendor, + deviceDesc.idProduct, + deviceDesc.bcdUSB, + deviceData.DevicePath); + + CloseDevice(&deviceData); + return 0; +} diff --git a/drivers/windows/panda/panda.cpp b/drivers/windows/panda/panda.cpp new file mode 100644 index 0000000000..79ec08edc2 --- /dev/null +++ b/drivers/windows/panda/panda.cpp @@ -0,0 +1,479 @@ +// panda.cpp : Defines the exported functions for the DLL application. +// + +#include "stdafx.h" +#include "device.h" +#include "panda.h" + +#define REQUEST_IN 0xC0 +#define REQUEST_OUT 0x40 + +#define CAN_TRANSMIT 1 +#define CAN_EXTENDED 4 + +using namespace panda; + +#pragma pack(1) +typedef struct _PANDA_CAN_MSG_INTERNAL { + uint32_t rir; + uint32_t f2; + uint8_t dat[8]; +} PANDA_CAN_MSG_INTERNAL; + +Panda::Panda( + WINUSB_INTERFACE_HANDLE WinusbHandle, + HANDLE DeviceHandle, + tstring devPath_, + std::string sn_ +) : usbh(WinusbHandle), devh(DeviceHandle), devPath(devPath_), sn(sn_) { + printf("CREATED A PANDA %s\n", this->sn.c_str()); + this->set_can_loopback(FALSE); + this->set_alt_setting(0); +} + +Panda::~Panda() { + WinUsb_Free(this->usbh); + CloseHandle(this->devh); + printf("Cleanup Panda %s\n", this->sn.c_str()); +} + +std::vector Panda::listAvailablePandas() { + std::vector ret; + auto map_sn_to_devpath = detect_pandas(); + + for (auto kv : map_sn_to_devpath) { + ret.push_back(std::string(kv.first)); + } + + return ret; +} + +std::unique_ptr Panda::openPanda(std::string sn) +{ + auto map_sn_to_devpath = detect_pandas(); + + if (map_sn_to_devpath.empty()) return nullptr; + if (map_sn_to_devpath.find(sn) == map_sn_to_devpath.end() && sn != "") return nullptr; + + tstring devpath; + if (sn.empty()) { + sn = map_sn_to_devpath.begin()->first; + devpath = map_sn_to_devpath.begin()->second; + } else { + devpath = map_sn_to_devpath[sn]; + } + + HANDLE deviceHandle = CreateFile(devpath.c_str(), + GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ, + NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL); + + if (INVALID_HANDLE_VALUE == deviceHandle) { + _tprintf(_T(" Error opening Device Handle %d.\n"),// Msg: '%s'\n"), + GetLastError());// , GetLastErrorAsString().c_str()); + return nullptr; + } + + WINUSB_INTERFACE_HANDLE winusbHandle; + if (WinUsb_Initialize(deviceHandle, &winusbHandle) == FALSE) { + _tprintf(_T(" Error initializing WinUSB %d.\n"),// Msg: '%s'\n"), + GetLastError());// , GetLastErrorAsString().c_str()); + CloseHandle(deviceHandle); + return nullptr; + } + + return std::unique_ptr(new Panda(winusbHandle, deviceHandle, map_sn_to_devpath[sn], sn)); +} + +std::string Panda::get_usb_sn() { + return std::string(this->sn); +} + +int Panda::control_transfer( + uint8_t bmRequestType, + uint8_t bRequest, + uint16_t wValue, + uint16_t wIndex, + void * data, + uint16_t wLength, + unsigned int timeout +) { + UNREFERENCED_PARAMETER(timeout); + + WINUSB_SETUP_PACKET SetupPacket; + ZeroMemory(&SetupPacket, sizeof(WINUSB_SETUP_PACKET)); + ULONG cbSent = 0; + + //Create the setup packet + SetupPacket.RequestType = bmRequestType; + SetupPacket.Request = bRequest; + SetupPacket.Value = wValue; + SetupPacket.Index = wIndex; + SetupPacket.Length = wLength; + + //ULONG timeout = 10; // ms + //WinUsb_SetPipePolicy(interfaceHandle, pipeID, PIPE_TRANSFER_TIMEOUT, sizeof(ULONG), &timeout); + + if (WinUsb_ControlTransfer(this->usbh, SetupPacket, (PUCHAR)data, wLength, &cbSent, 0) == FALSE) { + return -1; + } + + return cbSent; +} + +int Panda::bulk_write(UCHAR endpoint, const void * buff, ULONG length, PULONG transferred, ULONG timeout) { + if (this->usbh == INVALID_HANDLE_VALUE || !buff || !length || !transferred) return FALSE; + + if (WinUsb_WritePipe(this->usbh, endpoint, (PUCHAR)buff, length, transferred, NULL) == FALSE) { + _tprintf(_T(" Got error during bulk xfer: %d. Msg: '%s'\n"), + GetLastError(), GetLastErrorAsString().c_str()); + return FALSE; + } + return TRUE; +} + +int Panda::bulk_read(UCHAR endpoint, void * buff, ULONG buff_size, PULONG transferred, ULONG timeout) { + if (this->usbh == INVALID_HANDLE_VALUE || !buff || !buff_size || !transferred) return FALSE; + + if (WinUsb_ReadPipe(this->usbh, endpoint, (PUCHAR)buff, buff_size, transferred, NULL) == FALSE) { + _tprintf(_T(" Got error during bulk xfer: %d. Msg: '%s'\n"), + GetLastError(), GetLastErrorAsString().c_str()); + return FALSE; + } + return TRUE; +} + +bool Panda::set_alt_setting(UCHAR alt_setting) { + if (WinUsb_AbortPipe(this->usbh, 0x81) == FALSE) { + _tprintf(_T(" Error abobrting pipe before setting altsetting. continue. %d, Msg: '%s'\n"), + GetLastError(), GetLastErrorAsString().c_str()); + } + if (WinUsb_SetCurrentAlternateSetting(this->usbh, alt_setting) == FALSE) { + _tprintf(_T(" Error setting usb altsetting %d, Msg: '%s'\n"), + GetLastError(), GetLastErrorAsString().c_str()); + return FALSE; + } + + // Either the panda or the windows usb stack can drop messages + // if an odd number of messages are sent before an interrupt IN + // message is canceled. There are some other odd behaviors, but + // the best solution so far has been to send a few messages + // before using the device to clear out the pipe. No, the windows + // functions for clearing/resetting/etc the pipe did not work. + // This took way too to figure out a workaround. + // New info. The most repeatable behavior is losing the first + // message sent after setting alt setting to 1 (even without + // receiving). Something like this happened on linux sometimes. + bool loopback_backup = this->loopback; + this->set_can_loopback(TRUE); + Sleep(20); // Give time for any sent messages to appear in the RX buffer. + this->can_clear(PANDA_CAN_RX); + for (int i = 0; i < 2; i++) { + printf("Sending PAD %d\n", i); + if (this->can_send(0x7FF, FALSE, {}, 0, PANDA_CAN1) == FALSE) { + auto err = GetLastError(); + printf("Got err on first send: %d\n", err); + } + } + Sleep(10); + //this->can_clear(PANDA_CAN_RX); + + std::vector msg_recv; + if (alt_setting == 1) { + //Read the messages so they do not contaimnate the real message stream. + auto err = this->can_recv_async(NULL, msg_recv, 1000); + } + else { + msg_recv = this->can_recv(); + } + + //this->set_can_loopback(FALSE); + this->set_can_loopback(loopback_backup); + + return TRUE; +} + +UCHAR Panda::get_current_alt_setting() { + UCHAR alt_setting; + if (WinUsb_GetCurrentAlternateSetting(this->usbh, &alt_setting) == FALSE) { + _tprintf(_T(" Error getting usb altsetting %d, Msg: '%s'\n"), + GetLastError(), GetLastErrorAsString().c_str()); + return FALSE; + } + + return alt_setting; +} + +PANDA_HEALTH Panda::get_health() +{ + WINUSB_SETUP_PACKET SetupPacket; + ZeroMemory(&SetupPacket, sizeof(WINUSB_SETUP_PACKET)); + ULONG cbSent = 0; + + //Create the setup packet + SetupPacket.RequestType = REQUEST_IN; + SetupPacket.Request = 0xD2; + SetupPacket.Value = 0; + SetupPacket.Index = 0; + SetupPacket.Length = sizeof(UCHAR); + + //uint8_t health[13]; + PANDA_HEALTH health; + + if (WinUsb_ControlTransfer(this->usbh, SetupPacket, (PUCHAR)&health, sizeof(health), &cbSent, 0) == FALSE) { + _tprintf(_T(" Got unexpected error while reading panda health (2nd time) %d. Msg: '%s'\n"), + GetLastError(), GetLastErrorAsString().c_str()); + } + + return health; +} + +bool Panda::enter_bootloader() { + return this->control_transfer(REQUEST_OUT, 0xd1, 0, 0, NULL, 0, 0) != -1; +} + +std::string Panda::get_version() { + char buff[0x40]; + ZeroMemory(&buff, sizeof(buff)); + + int xferCount = this->control_transfer(REQUEST_IN, 0xd6, 0, 0, buff, 0x40, 0); + if (xferCount == -1) return std::string(); + return std::string(buff); +} + +//TODO: Do hash stuff for calculating the serial. +std::string Panda::get_serial() { + char buff[0x20]; + ZeroMemory(&buff, sizeof(buff)); + + int xferCount = this->control_transfer(REQUEST_IN, 0xD0, 0, 0, buff, 0x20, 0); + if (xferCount == -1) return std::string(); + return std::string(buff); + + //dat = self._handle.controlRead(REQUEST_IN, 0xd0, 0, 0, 0x20); + //hashsig, calc_hash = dat[0x1c:], hashlib.sha1(dat[0:0x1c]).digest()[0:4] + // assert(hashsig == calc_hash) + // return[dat[0:0x10], dat[0x10:0x10 + 10]] +} + +//Secret appears to by raw bytes, not a string. TODO: Change returned type. +std::string Panda::get_secret() { + char buff[0x10]; + ZeroMemory(&buff, sizeof(buff)); + + int xferCount = this->control_transfer(REQUEST_IN, 0xd0, 1, 0, buff, 0x10, 0); + if (xferCount == -1) return std::string(); + return std::string(buff); +} + +bool Panda::set_usb_power(bool on) { + return this->control_transfer(REQUEST_OUT, 0xe6, (int)on, 0, NULL, 0, 0) != -1; +} + +bool Panda::set_esp_power(bool on) { + return this->control_transfer(REQUEST_OUT, 0xd9, (int)on, 0, NULL, 0, 0) != -1; +} + +bool Panda::esp_reset(uint16_t bootmode = 0) { + return this->control_transfer(REQUEST_OUT, 0xda, bootmode, 0, NULL, 0, 0) != -1; +} + +bool Panda::set_safety_mode(PANDA_SAFETY_MODE mode = SAFETY_NOOUTPUT) { + return this->control_transfer(REQUEST_OUT, 0xdc, mode, 0, NULL, 0, 0) != -1; +} + +bool Panda::set_can_forwarding(PANDA_CAN_PORT from_bus, PANDA_CAN_PORT to_bus) { + if (from_bus == PANDA_CAN_UNK) return FALSE; + return this->control_transfer(REQUEST_OUT, 0xdd, from_bus, to_bus, NULL, 0, 0) != -1; +} + +bool Panda::set_gmlan(PANDA_GMLAN_HOST_PORT bus = PANDA_GMLAN_CAN3) { + return this->control_transfer(REQUEST_OUT, 0xdb, 1, (bus == PANDA_GMLAN_CLEAR) ? 0 : bus, NULL, 0, 0) != -1; +} + +bool Panda::set_can_loopback(bool enable) { + this->loopback = enable; + return this->control_transfer(REQUEST_OUT, 0xe5, enable, 0, NULL, 0, 0) != -1; +} + +//Can not use the full range of 16 bit speed. +//cbps means centa bits per second (tento of kbps) +bool Panda::set_can_speed_cbps(PANDA_CAN_PORT bus, uint16_t speed) { + if (bus == PANDA_CAN_UNK) return FALSE; + return this->control_transfer(REQUEST_OUT, 0xde, bus, speed, NULL, 0, 0) != -1; +} + +//Can not use the full range of 16 bit speed. +bool Panda::set_can_speed_kbps(PANDA_CAN_PORT bus, uint16_t speed) { + return set_can_speed_cbps(bus, speed * 10); +} + +//Can not use full 32 bit range of rate +bool Panda::set_uart_baud(PANDA_SERIAL_PORT uart, uint32_t rate) { + return this->control_transfer(REQUEST_OUT, 0xe4, uart, rate / 300, NULL, 0, 0) != -1; +} + +bool Panda::set_uart_parity(PANDA_SERIAL_PORT uart, PANDA_SERIAL_PORT_PARITY parity) { + return this->control_transfer(REQUEST_OUT, 0xe2, uart, parity, NULL, 0, 0) != -1; +} + +bool Panda::can_send_many(const std::vector& can_msgs) { + std::vector formatted_msgs; + formatted_msgs.reserve(can_msgs.size()); + + for (auto msg : can_msgs) { + if (msg.bus == PANDA_CAN_UNK) continue; + if (msg.len > 8) continue; + PANDA_CAN_MSG_INTERNAL tmpmsg = {}; + tmpmsg.rir = (msg.addr_29b) ? + ((msg.addr << 3) | CAN_TRANSMIT | CAN_EXTENDED) : + (((msg.addr & 0x7FF) << 21) | CAN_TRANSMIT); + tmpmsg.f2 = msg.len | (msg.bus << 4); + memcpy(tmpmsg.dat, msg.dat, msg.len); + formatted_msgs.push_back(tmpmsg); + } + + if (formatted_msgs.size() == 0) return FALSE; + + unsigned int retcount; + return this->bulk_write(3, formatted_msgs.data(), + sizeof(PANDA_CAN_MSG_INTERNAL)*formatted_msgs.size(), (PULONG)&retcount, 0); +} + +bool Panda::can_send(uint32_t addr, bool addr_29b, const uint8_t *dat, uint8_t len, PANDA_CAN_PORT bus) { + if (bus == PANDA_CAN_UNK) return FALSE; + if (len > 8) return FALSE; + PANDA_CAN_MSG msg; + msg.addr_29b = addr_29b; + msg.addr = addr; + msg.len = len; + memcpy(msg.dat, dat, msg.len); + msg.bus = bus; + return this->can_send_many(std::vector{msg}); +} + +void Panda::parse_can_recv(std::vector& msg_recv, char *buff, int retcount) { + for (int i = 0; i < retcount; i += sizeof(PANDA_CAN_MSG_INTERNAL)) { + PANDA_CAN_MSG_INTERNAL *in_msg_raw = (PANDA_CAN_MSG_INTERNAL *)(buff + i); + PANDA_CAN_MSG in_msg; + + in_msg.addr_29b = (bool)(in_msg_raw->rir & CAN_EXTENDED); + in_msg.addr = (in_msg.addr_29b) ? (in_msg_raw->rir >> 3) : (in_msg_raw->rir >> 21); + in_msg.recv_time = this->runningTime.getTimePassedUS(); + in_msg.recv_time_point = std::chrono::steady_clock::now(); + //The timestamp from the device is (in_msg_raw->f2 >> 16), + //but this 16 bit value is a little hard to use. Using a + //timer since the initialization of this device. + in_msg.len = in_msg_raw->f2 & 0xF; + memcpy(in_msg.dat, in_msg_raw->dat, 8); + + in_msg.is_receipt = ((in_msg_raw->f2 >> 4) & 0x80) == 0x80; + switch ((in_msg_raw->f2 >> 4) & 0x7F) { + case PANDA_CAN1: + in_msg.bus = PANDA_CAN1; + break; + case PANDA_CAN2: + in_msg.bus = PANDA_CAN2; + break; + case PANDA_CAN3: + in_msg.bus = PANDA_CAN3; + break; + default: + in_msg.bus = PANDA_CAN_UNK; + } + msg_recv.push_back(in_msg); + } +} + +bool Panda::can_recv_async(HANDLE kill_event, std::vector& msg_buff, DWORD timeoutms) { + int retcount; + char buff[sizeof(PANDA_CAN_MSG_INTERNAL) * 4]; + + // Overlapped structure required for async read. + HANDLE m_hReadFinishedEvent = CreateEvent(NULL, TRUE, TRUE, NULL); + OVERLAPPED m_overlappedData; + memset(&m_overlappedData, sizeof(OVERLAPPED), 0); + m_overlappedData.hEvent = m_hReadFinishedEvent; + + HANDLE phSignals[2] = { m_hReadFinishedEvent, kill_event }; + + if (!WinUsb_ReadPipe(this->usbh, 0x81, (PUCHAR)buff, sizeof(buff), (PULONG)&retcount, &m_overlappedData)) { + // An overlapped read will return true if done, or false with an + // error of ERROR_IO_PENDING if the transfer is still in process. + DWORD dwError = GetLastError(); + if (dwError == ERROR_IO_PENDING) { + dwError = WaitForMultipleObjects(kill_event ? 2 : 1, phSignals, FALSE, timeoutms); + + // Check if packet, timeout (nope), or break + if (dwError == WAIT_OBJECT_0) { + // Signal came from our usb object. Read the returned data. + if (!GetOverlappedResult(this->usbh, &m_overlappedData, (PULONG)&retcount, FALSE)) { + // TODO: handle other error cases better. + dwError = GetLastError(); + printf("Got overlap error %d\n", dwError); + + return TRUE; + } + } else { + WinUsb_AbortPipe(this->usbh, 0x81); + + // Return FALSE to show that the optional signal + // was set instead of the wait breaking from a + // message or recoverable error. + if (dwError == (WAIT_OBJECT_0 + 1)) { + return FALSE; + } + return TRUE; + } + } else { // ERROR_BAD_COMMAND happens when device is unplugged. + return FALSE; + } + } + + parse_can_recv(msg_buff, buff, retcount); + return TRUE; +} + +std::vector Panda::can_recv() { + std::vector msg_recv; + int retcount; + char buff[sizeof(PANDA_CAN_MSG_INTERNAL) * 4]; + + if (this->bulk_read(0x81, buff, sizeof(buff), (PULONG)&retcount, 0) == FALSE) + return msg_recv; + + parse_can_recv(msg_recv, buff, retcount); + + return msg_recv; +} + +bool Panda::can_clear(PANDA_CAN_PORT_CLEAR bus) { + /*Clears all messages from the specified internal CAN ringbuffer as though it were drained. + bus(int) : can bus number to clear a tx queue, or 0xFFFF to clear the global can rx queue.*/ + return this->control_transfer(REQUEST_OUT, 0xf1, bus, 0, NULL, 0, 0) != -1; +} + +std::string Panda::serial_read(PANDA_SERIAL_PORT port_number) { + std::string result; + char buff[0x40]; + while (TRUE) { + int retlen = this->control_transfer(REQUEST_IN, 0xe0, port_number, 0, &buff, 0x40, 0); + if (retlen <= 0) + break; + result += std::string(buff, retlen); + if (retlen < 0x40) break; + } + return result; +} + +int Panda::serial_write(PANDA_SERIAL_PORT port_number, const void* buff, uint16_t len) { + std::string dat; + dat += port_number; + dat += std::string((char*)buff, len); + int retcount; + if (this->bulk_write(2, dat.c_str(), len+1, (PULONG)&retcount, 0) == FALSE) return -1; + return retcount; +} + +bool Panda::serial_clear(PANDA_SERIAL_PORT port_number) { + return this->control_transfer(REQUEST_OUT, 0xf2, port_number, 0, NULL, 0, 0) != -1; +} diff --git a/drivers/windows/panda/panda.h b/drivers/windows/panda/panda.h new file mode 100644 index 0000000000..12a4fbb318 --- /dev/null +++ b/drivers/windows/panda/panda.h @@ -0,0 +1,214 @@ +#pragma once + +// The following ifdef block is the standard way of creating macros which make exporting +// from a DLL simpler. All files within this DLL are compiled with the PANDA_EXPORTS +// symbol defined on the command line. This symbol should not be defined on any project +// that uses this DLL. This way any other project whose source files include this file see +// PANDA_API functions as being imported from a DLL, whereas this DLL sees symbols +// defined with this macro as being exported. +#ifdef PANDA_EXPORTS +#define PANDA_API __declspec(dllexport) +#else +#define PANDA_API __declspec(dllimport) +#endif + +#include +#include +#include +#include +#include +#include + +#include +#include + +#if defined(UNICODE) +#define _tcout std::wcout +#define tstring std::wstring +#else +#define _tcout std::cout +#define tstring std::string +#endif + +#define LIN_MSG_MAX_LEN 10 + +//template class __declspec(dllexport) std::basic_string; + +namespace panda { + typedef enum _PANDA_SAFETY_MODE : uint16_t { + SAFETY_NOOUTPUT = 0, + SAFETY_HONDA = 1, + SAFETY_ALLOUTPUT = 0x1337, + } PANDA_SAFETY_MODE; + + typedef enum _PANDA_SERIAL_PORT : uint8_t { + SERIAL_DEBUG = 0, + SERIAL_ESP = 1, + SERIAL_LIN1 = 2, + SERIAL_LIN2 = 3, + } PANDA_SERIAL_PORT; + + typedef enum _PANDA_SERIAL_PORT_PARITY : uint8_t { + PANDA_PARITY_OFF = 0, + PANDA_PARITY_EVEN = 1, + PANDA_PARITY_ODD = 2, + } PANDA_SERIAL_PORT_PARITY; + + typedef enum _PANDA_CAN_PORT : uint8_t { + PANDA_CAN1 = 0, + PANDA_CAN2 = 1, + PANDA_CAN3 = 2, + PANDA_CAN_UNK = 0xFF, + } PANDA_CAN_PORT; + + typedef enum _PANDA_CAN_PORT_CLEAR : uint16_t { + PANDA_CAN1_TX = 0, + PANDA_CAN2_TX = 1, + PANDA_CAN3_TX = 2, + PANDA_CAN_RX = 0xFFFF, + } PANDA_CAN_PORT_CLEAR; + + typedef enum _PANDA_GMLAN_HOST_PORT : uint8_t { + PANDA_GMLAN_CLEAR = 0, + PANDA_GMLAN_CAN2 = 1, + PANDA_GMLAN_CAN3 = 2, + } PANDA_GMLAN_HOST_PORT; + + #pragma pack(1) + typedef struct _PANDA_HEALTH { + uint32_t voltage; + uint32_t current; + uint8_t started; + uint8_t controls_allowed; + uint8_t gas_interceptor_detected; + uint8_t started_signal_detected; + uint8_t started_alt; + } PANDA_HEALTH, *PPANDA_HEALTH; + + typedef struct _PANDA_CAN_MSG { + uint32_t addr; + unsigned long long recv_time; //In microseconds since device initialization + std::chrono::time_point recv_time_point; + uint8_t dat[8]; + uint8_t len; + PANDA_CAN_PORT bus; + bool is_receipt; + bool addr_29b; + } PANDA_CAN_MSG; + + //Copied from https://stackoverflow.com/a/31488113 + class Timer + { + using clock = std::chrono::steady_clock; + using time_point_type = std::chrono::time_point < clock, std::chrono::microseconds >; + public: + Timer() { + start = std::chrono::time_point_cast(clock::now()); + } + + // gets the time elapsed from construction. + unsigned long long /*microseconds*/ Timer::getTimePassedUS() { + // get the new time + auto end = std::chrono::time_point_cast(clock::now()); + + // return the difference of the times + return (end - start).count(); + } + + // gets the time elapsed from construction. + unsigned long long /*milliseconds*/ Timer::getTimePassedMS() { + // get the new time + auto end = std::chrono::time_point_cast(clock::now()); + + // return the difference of the times + auto startms = std::chrono::time_point_cast(start); + return (end - startms).count(); + } + private: + time_point_type start; + }; + + // This class is exported from the panda.dll + class PANDA_API Panda { + public: + static std::vector listAvailablePandas(); + static std::unique_ptr openPanda(std::string sn); + + ~Panda(); + + std::string get_usb_sn(); + bool set_alt_setting(UCHAR alt_setting); + UCHAR get_current_alt_setting(); + + PANDA_HEALTH get_health(); + bool enter_bootloader(); + std::string get_version(); + std::string get_serial(); + std::string get_secret(); + + bool set_usb_power(bool on); + bool set_esp_power(bool on); + bool esp_reset(uint16_t bootmode); + bool set_safety_mode(PANDA_SAFETY_MODE mode); + bool set_can_forwarding(PANDA_CAN_PORT from_bus, PANDA_CAN_PORT to_bus); + bool set_gmlan(PANDA_GMLAN_HOST_PORT bus); + bool set_can_loopback(bool enable); + bool set_can_speed_cbps(PANDA_CAN_PORT bus, uint16_t speed); + bool set_can_speed_kbps(PANDA_CAN_PORT bus, uint16_t speed); + bool set_uart_baud(PANDA_SERIAL_PORT uart, uint32_t rate); + bool set_uart_parity(PANDA_SERIAL_PORT uart, PANDA_SERIAL_PORT_PARITY parity); + + bool can_send_many(const std::vector& can_msgs); + bool can_send(uint32_t addr, bool addr_29b, const uint8_t *dat, uint8_t len, PANDA_CAN_PORT bus); + void parse_can_recv(std::vector& msg_recv, char *buff, int retcount); + bool can_recv_async(HANDLE kill_event, std::vector& msg_buff, DWORD timeoutms = INFINITE); + std::vector can_recv(); + bool can_clear(PANDA_CAN_PORT_CLEAR bus); + + std::string serial_read(PANDA_SERIAL_PORT port_number); + int serial_write(PANDA_SERIAL_PORT port_number, const void* buff, uint16_t len); + bool serial_clear(PANDA_SERIAL_PORT port_number); + private: + Panda( + WINUSB_INTERFACE_HANDLE WinusbHandle, + HANDLE DeviceHandle, + tstring devPath_, + std::string sn_ + ); + + int control_transfer( + uint8_t bmRequestType, + uint8_t bRequest, + uint16_t wValue, + uint16_t wIndex, + void * data, + uint16_t wLength, + unsigned int timeout + ); + + int bulk_write( + UCHAR endpoint, + const void * buff, + ULONG length, + PULONG transferred, + ULONG timeout + ); + + int Panda::bulk_read( + UCHAR endpoint, + void * buff, + ULONG buff_size, + PULONG transferred, + ULONG timeout + ); + + WINUSB_INTERFACE_HANDLE usbh; + HANDLE devh; + tstring devPath; + std::string sn; + bool loopback; + + Timer runningTime; + }; + +} diff --git a/drivers/windows/panda/panda.ico b/drivers/windows/panda/panda.ico new file mode 100644 index 0000000000..9556e87f5c --- /dev/null +++ b/drivers/windows/panda/panda.ico @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:04b18f965180a6782b600c51467a7f044e03cbc7925c47191b65ca7f606d1af3 +size 97642 diff --git a/drivers/windows/panda/panda.rc b/drivers/windows/panda/panda.rc new file mode 100644 index 0000000000000000000000000000000000000000..88cf9f76780799bacfa2773bf8d65b4e9a624a94 GIT binary patch literal 5150 zcmdUzTW=ai6vxkVrGAGgerc2l8z)lL#~27j#l|uhwUQ-7jO`);wz#B?)X(1b_n%?B zyX-;*$pg`7nVp$)&Yb%>%fJ7e+Nn9aw6WdU+@5T~^I%K%`s^)iWkZ{=s@iLYvq!tP z8PA;kCG&{AIkWIqyxsBcSc%%$o`EUb_x2sPocj5M-5IA7phq6Il*2FEA6D|v!aVVC z4<1jn-`llytZO~1S<~7!up6thTjTx8TJ}3T9eywEf}Ixc@qY1ed?RufXJ-xcvZ><- zwDe?C7k3%zwz5d>MC+dA9eQ6c{VNb|2Fv3>o?$K^?!UCiyQ^-SfML<(gSiI z<{MG-k?wKLkvoTVXT;wGOD*sLXFp=|8LJqF9o|AzF6>o-7c5dSHTL@YAro68D89E3 zcvXn04)N0?x~kkfz`I%u(fym@wqkanaf1&Jz`6qemA|#c?iIT|=7#svxD((S&~6f| zzt|gScYwQKC*W*C3^)x@9Xvp?Z1(`gM;}Rk<<{CamkWxcJod(lR8c&RbFS$dQ$vSg8+C@6g0= zoPF}W!^&5yXCQ{YJ5a}@U31sMBHcmZpiAMef1V4pChL1C=!)9itjC^9Hp;8 zFa4DhA|c+;^Om1;+Z0a1ch1Ob@Dq62m*zAlS;3+23!gWKK1=A^NwDRE_{&CU|C4_?e-zNlvGU9A&syp4~^QEhK&PbY;0`^0U0{k;<}!POw`3L>+L|cckY? zRk5G;y0g8$LtZV3qGh#8d&`$ecFisFfE8Z1+@Upxq)$JgrtSJ#&UdeyG>>O3$;3^Zzx00-eNF8C-z4htcyzGIi8$Qu?=v!yy5ao4 JBze1w(toE=W&QvF literal 0 HcmV?d00001 diff --git a/drivers/windows/panda/panda.vcxproj b/drivers/windows/panda/panda.vcxproj new file mode 100644 index 0000000000..147c58ca14 --- /dev/null +++ b/drivers/windows/panda/panda.vcxproj @@ -0,0 +1,193 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + {5528AEFB-638D-49AF-B9D4-965154E7D531} + Win32Proj + panda + 8.1 + + + + DynamicLibrary + true + v140 + Unicode + + + DynamicLibrary + false + v140 + true + Unicode + + + DynamicLibrary + true + v140 + Unicode + + + DynamicLibrary + false + v140 + true + Unicode + + + + + + + + + + + + + + + + + + + + + true + $(SolutionDir)$(Configuration)_$(PlatformShortName)\ + + + true + $(SolutionDir)$(Configuration)_$(PlatformShortName)\ + + + false + $(SolutionDir)$(Configuration)_$(PlatformShortName)\ + + + false + $(SolutionDir)$(Configuration)_$(PlatformShortName)\ + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_USRDLL;PANDA_EXPORTS;%(PreprocessorDefinitions) + true + false + + + Windows + true + kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies);winusb.lib;setupapi.lib + + + + + Use + Level3 + Disabled + _DEBUG;_WINDOWS;_USRDLL;PANDA_EXPORTS;%(PreprocessorDefinitions) + true + + + Windows + true + kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies);winusb.lib;setupapi.lib + + + + + Level3 + Use + MaxSpeed + true + true + WIN32;NDEBUG;_WINDOWS;_USRDLL;PANDA_EXPORTS;%(PreprocessorDefinitions) + true + + + Windows + true + true + true + kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies);winusb.lib;setupapi.lib + + + + + Level3 + Use + MaxSpeed + true + true + NDEBUG;_WINDOWS;_USRDLL;PANDA_EXPORTS;%(PreprocessorDefinitions) + true + + + Windows + true + true + true + kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies);winusb.lib;setupapi.lib + + + + + + + + + + + + + false + + + false + + + false + + + false + + + + + + Create + Create + Create + Create + + + + + + + + + + + + \ No newline at end of file diff --git a/drivers/windows/panda/panda.vcxproj.filters b/drivers/windows/panda/panda.vcxproj.filters new file mode 100644 index 0000000000..cded701a31 --- /dev/null +++ b/drivers/windows/panda/panda.vcxproj.filters @@ -0,0 +1,58 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + + + Resource Files + + + + + Resource Files + + + \ No newline at end of file diff --git a/drivers/windows/panda/resource.h b/drivers/windows/panda/resource.h new file mode 100644 index 0000000000000000000000000000000000000000..bf006ff4b39308a5e03a0ec6a72052338fd83d16 GIT binary patch literal 898 zcmb7@TTjAZ42Iup6aT}PaA_h={R4C3f(X+vN91bZuo(;i!@)z0e_eh00R|0OBu)9+ z(!PD$W?!Fm)%A`fx>2rJ4c(%Nw-QBa;-&gPj&($CT~2L{HPl=)EznX+VqIbjt<={9 zFVYF(^q@jhbWVK9J0dnFG9+t-SKyaKCRnFC9Wt=i*#o_i^F;lW{61N8s<&M1t$7?n zu}%)gF`A^;?;GSA*_(WGma39h+7yi;L&Fb?}_I^>3A+uSYnKuP&+ z>xxJVd*8nDP4AqVhVJ2z%WzU^GOP$Yhe-%RhW&S!wy%qSBil{dNJzK164&VxWRu_^ l^n?jIe%>n94%EZ2*PFCkRO8xy413GkzJQUx^?Lii{cjM-d_n*K literal 0 HcmV?d00001 diff --git a/drivers/windows/panda/stdafx.cpp b/drivers/windows/panda/stdafx.cpp new file mode 100644 index 0000000000..8793e09b40 --- /dev/null +++ b/drivers/windows/panda/stdafx.cpp @@ -0,0 +1,8 @@ +// stdafx.cpp : source file that includes just the standard includes +// panda.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + +// TODO: reference any additional headers you need in STDAFX.H +// and not in this file diff --git a/drivers/windows/panda/stdafx.h b/drivers/windows/panda/stdafx.h new file mode 100644 index 0000000000..cc3d3b9667 --- /dev/null +++ b/drivers/windows/panda/stdafx.h @@ -0,0 +1,19 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// + +#pragma once + +#include "targetver.h" + +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers +#endif +// Windows Header Files: +#include + +#include +#include +#include +#include diff --git a/drivers/windows/panda/targetver.h b/drivers/windows/panda/targetver.h new file mode 100644 index 0000000000..1bf4ee6fee --- /dev/null +++ b/drivers/windows/panda/targetver.h @@ -0,0 +1,13 @@ +#pragma once + +// Including SDKDDKVer.h defines the highest available Windows platform. + +// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and +// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h. + +#include + +#define WINVER _WIN32_WINNT_WIN7 +#define _WIN32_WINNT _WIN32_WINNT_WIN7 + +#include diff --git a/drivers/windows/pandaJ2534DLL Test/ECUsim_tests.cpp b/drivers/windows/pandaJ2534DLL Test/ECUsim_tests.cpp new file mode 100644 index 0000000000..1effc49145 --- /dev/null +++ b/drivers/windows/pandaJ2534DLL Test/ECUsim_tests.cpp @@ -0,0 +1,87 @@ +#include "stdafx.h" +#include "Loader4.h" +#include "pandaJ2534DLL/J2534_v0404.h" +#include "panda/panda.h" +#include "Timer.h" +#include "ECUsim DLL\ECUsim.h" +#include "TestHelpers.h" + +using namespace Microsoft::VisualStudio::CppUnitTestFramework; + +namespace pandaWCUsimTest +{ + + TEST_CLASS(ECUsimTests) + { + public: + + TEST_METHOD(ECUsim_ISO15765_SingleFrameTx_29bStandardAddrPad500k) + { + ECUsim sim("", 500000); + auto p = getPanda(500); + + p->can_send(0x18daeff1, TRUE, (const uint8_t*)"\x02\x01\x00", 3, panda::PANDA_CAN1); + auto msg_recv = panda_recv_loop(p, 2); + check_panda_can_msg(msg_recv[0], 0, 0x18daeff1, TRUE, TRUE, std::string("\x02\x01\x00", 3), LINE_INFO()); + check_panda_can_msg(msg_recv[1], 0, 0x18daf1ef, TRUE, FALSE, std::string("\x06\x41\x00\xff\xff\xff\xfe\x00", 8), LINE_INFO()); + } + + TEST_METHOD(ECUsim_ISO15765_SingleFrameTx_29bStandardAddrPad250k) + { + ECUsim sim("", 250000); + auto p = getPanda(250); + + p->can_send(0x18daeff1, TRUE, (const uint8_t*)"\x02\x01\x00", 3, panda::PANDA_CAN1); + auto msg_recv = panda_recv_loop(p, 2); + check_panda_can_msg(msg_recv[0], 0, 0x18daeff1, TRUE, TRUE, std::string("\x02\x01\x00", 3), LINE_INFO()); + check_panda_can_msg(msg_recv[1], 0, 0x18daf1ef, TRUE, FALSE, std::string("\x06""\x41\x00""\xff\xff\xff\xfe""\x00", 8), LINE_INFO()); + } + + TEST_METHOD(ECUsim_ISO15765_SingleFrameTx_29bExtAddrPad500k) + { + ECUsim sim("", 500000, TRUE); + auto p = getPanda(500); + + p->can_send(0x18daeff1, TRUE, (const uint8_t*)"\x13""\x02\x01\x00", 4, panda::PANDA_CAN1); + auto msg_recv = panda_recv_loop(p, 2); + check_panda_can_msg(msg_recv[0], 0, 0x18daeff1, TRUE, TRUE, std::string("\x13""\x02\x01\x00", 4), LINE_INFO()); + check_panda_can_msg(msg_recv[1], 0, 0x18daf1ef, TRUE, FALSE, std::string("\x13""\x06""\x41\x00""\xff\xff\xff\xfe", 8), LINE_INFO()); + } + + TEST_METHOD(ECUsim_ISO15765_MultiFrameTx_29bStandardAddrPad500k) + { + ECUsim sim("", 500000); + auto p = getPanda(500); + + p->can_send(0x18daeff1, TRUE, (const uint8_t*)"\x02\x09\x02", 3, panda::PANDA_CAN1); + auto msg_recv = panda_recv_loop(p, 2); + check_panda_can_msg(msg_recv[0], 0, 0x18daeff1, TRUE, TRUE, std::string("\x02\x09\x02", 3), LINE_INFO()); + check_panda_can_msg(msg_recv[1], 0, 0x18daf1ef, TRUE, FALSE, std::string("\x10\x14""\x49\x02\x01""1D4", 8), LINE_INFO()); + + p->can_send(0x18daeff1, TRUE, (const uint8_t*)"\x30\x00\x00", 3, panda::PANDA_CAN1); + msg_recv = panda_recv_loop(p, 3); + check_panda_can_msg(msg_recv[0], 0, 0x18daeff1, TRUE, TRUE, std::string("\x30\x0\x0", 3), LINE_INFO()); + check_panda_can_msg(msg_recv[1], 0, 0x18daf1ef, TRUE, FALSE, std::string("\x21""GP00R55", 8), LINE_INFO()); + check_panda_can_msg(msg_recv[2], 0, 0x18daf1ef, TRUE, FALSE, std::string("\x22""B123456", 8), LINE_INFO()); + } + + TEST_METHOD(ECUsim_ISO15765_MultiFrameTx_29bExtAddrPad500k) + { + ECUsim sim("", 500000, TRUE); + auto p = getPanda(500); + + p->can_send(0x18daeff1, TRUE, (const uint8_t*)"\x13""\x02\x09\x02", 4, panda::PANDA_CAN1); + auto msg_recv = panda_recv_loop(p, 2); + check_panda_can_msg(msg_recv[0], 0, 0x18daeff1, TRUE, TRUE, std::string("\x13""\x02\x09\x02", 4), LINE_INFO()); + check_panda_can_msg(msg_recv[1], 0, 0x18daf1ef, TRUE, FALSE, std::string("\x13""\x10\x14""\x49\x02\x01""1D", 8), LINE_INFO()); + + p->can_send(0x18daeff1, TRUE, (const uint8_t*)"\x13""\x30\x00\x00", 4, panda::PANDA_CAN1); + msg_recv = panda_recv_loop(p, 4); + check_panda_can_msg(msg_recv[0], 0, 0x18daeff1, TRUE, TRUE, std::string("\x13""\x30\x0\x0", 4), LINE_INFO()); + check_panda_can_msg(msg_recv[1], 0, 0x18daf1ef, TRUE, FALSE, std::string("\x13""\x21""4GP00R", 8), LINE_INFO()); + check_panda_can_msg(msg_recv[2], 0, 0x18daf1ef, TRUE, FALSE, std::string("\x13""\x22""55B123", 8), LINE_INFO()); + check_panda_can_msg(msg_recv[3], 0, 0x18daf1ef, TRUE, FALSE, std::string("\x13""\x23""456", 5), LINE_INFO()); + } + }; + +} \ No newline at end of file diff --git a/drivers/windows/pandaJ2534DLL Test/Loader4.cpp b/drivers/windows/pandaJ2534DLL Test/Loader4.cpp new file mode 100644 index 0000000000..f4a0b70fa5 --- /dev/null +++ b/drivers/windows/pandaJ2534DLL Test/Loader4.cpp @@ -0,0 +1,240 @@ +// Loader4.cpp +// (c) 2005 National Control Systems, Inc. +// Portions (c) 2004 Drew Technologies, Inc. +// Dynamic J2534 v04.04 dll loader for VB + +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to: +// the Free Software Foundation, Inc. +// 51 Franklin Street, Fifth Floor +// Boston, MA 02110-1301, USA + +// National Control Systems, Inc. +// 10737 Hamburg Rd +// Hamburg, MI 48139 +// 810-231-2901 + +// Drew Technologies, Inc. +// 7012 E.M -36, Suite 3B +// Whitmore Lake, MI 48189 +// 810-231-3171 + +#define STRICT +#include "stdafx.h" +#include +#include "Loader4.h" + +PTOPEN LocalOpen; +PTCLOSE LocalClose; +PTCONNECT LocalConnect; +PTDISCONNECT LocalDisconnect; +PTREADMSGS LocalReadMsgs; +PTWRITEMSGS LocalWriteMsgs; +PTSTARTPERIODICMSG LocalStartPeriodicMsg; +PTSTOPPERIODICMSG LocalStopPeriodicMsg; +PTSTARTMSGFILTER LocalStartMsgFilter; +PTSTOPMSGFILTER LocalStopMsgFilter; +PTSETPROGRAMMINGVOLTAGE LocalSetProgrammingVoltage; +PTREADVERSION LocalReadVersion; +PTGETLASTERROR LocalGetLastError; +PTIOCTL LocalIoctl; + +HINSTANCE hDLL = NULL; +//BOOL bIsCorrectVersion = FALSE; + +BOOL WINAPI DllMain(HINSTANCE hInstA, DWORD dwReason, LPVOID lpvReserved) +{ + switch (dwReason) { + case DLL_PROCESS_ATTACH: + // The DLL is being mapped into the process's address space + + case DLL_THREAD_ATTACH: + // A thread is being created + break; + + case DLL_THREAD_DETACH: + // A thread is exiting cleanly + break; + + case DLL_PROCESS_DETACH: + // The DLL is being unmapped from the process's address space + break; + } + + return TRUE; +} + + +long WINAPI LoadJ2534Dll(char *sLib) +{ + long lFuncList = 0; + + if (hDLL != NULL) UnloadJ2534Dll(); + hDLL = LoadLibraryA (sLib); + if (hDLL == NULL) return ERR_NO_DLL; + + LocalOpen = (PTOPEN)(GetProcAddress(hDLL, "PassThruOpen")); + if (LocalOpen == NULL) lFuncList = lFuncList | ERR_NO_PTOPEN; + + LocalClose = (PTCLOSE)(GetProcAddress(hDLL, "PassThruClose")); + if (LocalClose == NULL) lFuncList = lFuncList | ERR_NO_PTCLOSE; + + LocalConnect = (PTCONNECT)(GetProcAddress(hDLL,"PassThruConnect")); + if (LocalConnect == NULL) lFuncList = lFuncList | ERR_NO_PTCONNECT; + + LocalDisconnect = (PTDISCONNECT)(GetProcAddress(hDLL,"PassThruDisconnect")); + if (LocalDisconnect == NULL) lFuncList = lFuncList | ERR_NO_PTDISCONNECT; + + LocalReadMsgs = (PTREADMSGS)(GetProcAddress(hDLL,"PassThruReadMsgs")); + if (LocalReadMsgs == NULL) lFuncList = lFuncList | ERR_NO_PTREADMSGS; + + LocalWriteMsgs = (PTWRITEMSGS)(GetProcAddress(hDLL,"PassThruWriteMsgs")); + if (LocalWriteMsgs == NULL) lFuncList = lFuncList | ERR_NO_PTWRITEMSGS; + + LocalStartPeriodicMsg = (PTSTARTPERIODICMSG)(GetProcAddress(hDLL,"PassThruStartPeriodicMsg")); + if (LocalStartPeriodicMsg == NULL) lFuncList = lFuncList | ERR_NO_PTSTARTPERIODICMSG; + + LocalStopPeriodicMsg = (PTSTOPPERIODICMSG)(GetProcAddress(hDLL,"PassThruStopPeriodicMsg")); + if (LocalStopPeriodicMsg == NULL) lFuncList = lFuncList | ERR_NO_PTSTOPPERIODICMSG; + + LocalStartMsgFilter = (PTSTARTMSGFILTER)(GetProcAddress(hDLL,"PassThruStartMsgFilter")); + if (LocalStartPeriodicMsg == NULL) lFuncList = lFuncList | ERR_NO_PTSTARTMSGFILTER; + + LocalStopMsgFilter = (PTSTOPMSGFILTER)(GetProcAddress(hDLL,"PassThruStopMsgFilter")); + if (LocalStopMsgFilter == NULL) lFuncList = lFuncList | ERR_NO_PTSTOPMSGFILTER; + + LocalSetProgrammingVoltage = (PTSETPROGRAMMINGVOLTAGE)(GetProcAddress(hDLL,"PassThruSetProgrammingVoltage")); + if (LocalSetProgrammingVoltage == NULL) lFuncList = lFuncList | ERR_NO_PTSETPROGRAMMINGVOLTAGE; + + LocalReadVersion = (PTREADVERSION)(GetProcAddress(hDLL,"PassThruReadVersion")); + if (LocalReadVersion == NULL) lFuncList = lFuncList | ERR_NO_PTREADVERSION; + + LocalGetLastError = (PTGETLASTERROR)(GetProcAddress(hDLL,"PassThruGetLastError")); + if (LocalGetLastError == NULL) lFuncList = lFuncList | ERR_NO_PTGETLASTERROR; + + LocalIoctl = (PTIOCTL)(GetProcAddress(hDLL,"PassThruIoctl")); + if (LocalIoctl == NULL) lFuncList = lFuncList | ERR_NO_PTIOCTL; + + if (lFuncList == ERR_NO_FUNCTIONS) return ERR_WRONG_DLL_VER; + + return lFuncList; +} + +long WINAPI UnloadJ2534Dll() +{ + if (FreeLibrary(hDLL)) + { + hDLL = NULL; + LocalOpen = NULL; + LocalClose = NULL; + LocalConnect = NULL; + LocalDisconnect = NULL; + LocalReadMsgs = NULL; + LocalWriteMsgs = NULL; + LocalStartPeriodicMsg = NULL; + LocalStopPeriodicMsg = NULL; + LocalStartMsgFilter = NULL; + LocalStopMsgFilter = NULL; + LocalSetProgrammingVoltage = NULL; + LocalReadVersion = NULL; + LocalGetLastError = NULL; + LocalIoctl = NULL; + return 0; + } + return ERR_NO_DLL; +} + +long WINAPI PassThruOpen(void *pName, unsigned long *pDeviceID) +{ + if (LocalOpen == NULL) return ERR_FUNC_MISSING; + return LocalOpen(pName, pDeviceID); +} + +long WINAPI PassThruClose(unsigned long DeviceID) +{ + if (LocalOpen == NULL) return ERR_FUNC_MISSING; + return LocalClose(DeviceID); +} + +long WINAPI PassThruConnect(unsigned long DeviceID, unsigned long ProtocolID, unsigned long Flags, unsigned long Baudrate, unsigned long *pChannelID) +{ + if (LocalConnect == NULL) return ERR_FUNC_MISSING; + return LocalConnect(DeviceID, ProtocolID, Flags, Baudrate, pChannelID); +} + +long WINAPI PassThruDisconnect(unsigned long ChannelID) +{ + if (LocalDisconnect == NULL) return ERR_FUNC_MISSING; + return LocalDisconnect(ChannelID); +} + +long WINAPI PassThruReadMsgs(unsigned long ChannelID, PASSTHRU_MSG *pMsg, unsigned long *pNumMsgs, unsigned long Timeout) +{ + if (LocalReadMsgs == NULL) return ERR_FUNC_MISSING; + return LocalReadMsgs(ChannelID, pMsg, pNumMsgs, Timeout); +} + +long WINAPI PassThruWriteMsgs(unsigned long ChannelID, PASSTHRU_MSG *pMsg, unsigned long *pNumMsgs, unsigned long Timeout) +{ + if (LocalWriteMsgs == NULL) return ERR_FUNC_MISSING; + return LocalWriteMsgs(ChannelID, pMsg, pNumMsgs, Timeout); +} + +long WINAPI PassThruStartPeriodicMsg(unsigned long ChannelID, PASSTHRU_MSG *pMsg, unsigned long *pMsgID, unsigned long TimeInterval) +{ + if (LocalStartPeriodicMsg == NULL) return ERR_FUNC_MISSING; + return LocalStartPeriodicMsg(ChannelID, pMsg, pMsgID, TimeInterval); +} + +long WINAPI PassThruStopPeriodicMsg(unsigned long ChannelID, unsigned long MsgID) +{ + if (LocalStopPeriodicMsg == NULL) return ERR_FUNC_MISSING; + return LocalStopPeriodicMsg(ChannelID, MsgID); +} + +long WINAPI PassThruStartMsgFilter(unsigned long ChannelID, unsigned long FilterType, + PASSTHRU_MSG *pMaskMsg, PASSTHRU_MSG *pPatternMsg, PASSTHRU_MSG *pFlowControlMsg, unsigned long *pFilterID) +{ + if (LocalStartMsgFilter == NULL) return ERR_FUNC_MISSING; + return LocalStartMsgFilter(ChannelID, FilterType, pMaskMsg, pPatternMsg, pFlowControlMsg, pFilterID); +} + +long WINAPI PassThruStopMsgFilter(unsigned long ChannelID, unsigned long FilterID) +{ + if (LocalStopMsgFilter == NULL) return ERR_FUNC_MISSING; + return LocalStopMsgFilter(ChannelID, FilterID); +} + +long WINAPI PassThruSetProgrammingVoltage(unsigned long DeviceID, unsigned long PinNumber, unsigned long Voltage) +{ + if (LocalSetProgrammingVoltage == NULL) return ERR_FUNC_MISSING; + return LocalSetProgrammingVoltage(DeviceID, PinNumber, Voltage); +} + +long WINAPI PassThruReadVersion(unsigned long DeviceID, char *pFirmwareVersion, char *pDllVersion, char *pApiVersion) +{ + if (LocalReadVersion == NULL) return ERR_FUNC_MISSING; + return LocalReadVersion(DeviceID, pFirmwareVersion, pDllVersion, pApiVersion); +} + +long WINAPI PassThruGetLastError(char *pErrorDescription) +{ + if (LocalGetLastError == NULL) return ERR_FUNC_MISSING; + return LocalGetLastError(pErrorDescription); +} + +long WINAPI PassThruIoctl(unsigned long ChannelID, unsigned long IoctlID, void *pInput, void *pOutput) +{ + if (LocalIoctl == NULL) return ERR_FUNC_MISSING; + return LocalIoctl(ChannelID, IoctlID, pInput, pOutput); +} \ No newline at end of file diff --git a/drivers/windows/pandaJ2534DLL Test/Loader4.h b/drivers/windows/pandaJ2534DLL Test/Loader4.h new file mode 100644 index 0000000000..9710144141 --- /dev/null +++ b/drivers/windows/pandaJ2534DLL Test/Loader4.h @@ -0,0 +1,55 @@ +// Loader4.h +// (c) 2005 National Control Systems, Inc. +// Portions (c) 2004 Drew Technologies, Inc. + +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to: +// the Free Software Foundation, Inc. +// 51 Franklin Street, Fifth Floor +// Boston, MA 02110-1301, USA + +// National Control Systems, Inc. +// 10737 Hamburg Rd +// Hamburg, MI 48139 +// 810-231-2901 + +// Drew Technologies, Inc. +// 7012 E.M -36, Suite 3B +// Whitmore Lake, MI 48189 +// 810-231-3171 + +#include "pandaJ2534DLL/J2534_v0404.h" + +//Other Functions +long WINAPI LoadJ2534Dll(char *); +long WINAPI UnloadJ2534Dll(); + +// NCS Returns of any functions not found +#define ERR_NO_PTOPEN 0x0001 +#define ERR_NO_PTCLOSE 0x0002 +#define ERR_NO_PTCONNECT 0x0004 +#define ERR_NO_PTDISCONNECT 0x0008 +#define ERR_NO_PTREADMSGS 0x0010 +#define ERR_NO_PTWRITEMSGS 0x0020 +#define ERR_NO_PTSTARTPERIODICMSG 0x0040 +#define ERR_NO_PTSTOPPERIODICMSG 0x0080 +#define ERR_NO_PTSTARTMSGFILTER 0x0100 +#define ERR_NO_PTSTOPMSGFILTER 0x0200 +#define ERR_NO_PTSETPROGRAMMINGVOLTAGE 0x0400 +#define ERR_NO_PTREADVERSION 0x0800 +#define ERR_NO_PTGETLASTERROR 0x1000 +#define ERR_NO_PTIOCTL 0x2000 +#define ERR_NO_FUNCTIONS 0x3fff +#define ERR_NO_DLL -1 +#define ERR_WRONG_DLL_VER -2 +#define ERR_FUNC_MISSING -3 diff --git a/drivers/windows/pandaJ2534DLL Test/TestHelpers.cpp b/drivers/windows/pandaJ2534DLL Test/TestHelpers.cpp new file mode 100644 index 0000000000..62096d1181 --- /dev/null +++ b/drivers/windows/pandaJ2534DLL Test/TestHelpers.cpp @@ -0,0 +1,254 @@ +#include "stdafx.h" +#include "TestHelpers.h" +#include "Loader4.h" +#include "pandaJ2534DLL/J2534_v0404.h" +#include "panda/panda.h" +#include "Timer.h" + +using namespace Microsoft::VisualStudio::CppUnitTestFramework; + +void write_ioctl(unsigned int chanid, unsigned int param, unsigned int val, const __LineInfo* pLineInfo) { + SCONFIG config = { param, val }; + SCONFIG_LIST inconfig = { 1, &config }; + + Assert::AreEqual(STATUS_NOERROR, PassThruIoctl(chanid, SET_CONFIG, &inconfig, NULL), _T("Failed to set IOCTL."), pLineInfo); +} + +std::vector panda_recv_loop_loose(std::unique_ptr& p, unsigned int min_num, unsigned long timeout_ms) { + std::vector ret_messages; + Timer t = Timer(); + + while (t.getTimePassed() < timeout_ms) { + Sleep(10); + std::vectormsg_recv = p->can_recv(); + if (msg_recv.size() > 0) { + ret_messages.insert(std::end(ret_messages), std::begin(msg_recv), std::end(msg_recv)); + } + } + + Assert::IsTrue(min_num <= ret_messages.size(), _T("Received too few messages.")); + return ret_messages; +} + +std::vector panda_recv_loop(std::unique_ptr& p, unsigned int num_expected, unsigned long timeout_ms) { + std::vector ret_messages; + Timer t = Timer(); + + while (t.getTimePassed() < timeout_ms) { + Sleep(10); + std::vectormsg_recv = p->can_recv(); + if (msg_recv.size() > 0) { + ret_messages.insert(std::end(ret_messages), std::begin(msg_recv), std::end(msg_recv)); + } + if (ret_messages.size() >= num_expected) break; + } + + std::ostringstream stringStream; + + stringStream << "j2534_recv_loop Broke at " << t.getTimePassed() << " ms size is " << ret_messages.size() << std::endl; + + if (num_expected != ret_messages.size()) { + stringStream << "Incorrect number of messages received. Displaying the messages:" << std::endl; + for (auto msg : ret_messages) { + stringStream << " TS: " << msg.recv_time << "; Dat: "; + for (int i = 0; i < msg.len; i++) stringStream << std::hex << std::setw(2) << std::setfill('0') << int(msg.dat[i] & 0xFF) << " "; + stringStream << std::endl; + } + } + + Logger::WriteMessage(stringStream.str().c_str()); + + Assert::AreEqual(num_expected, ret_messages.size(), _T("Received wrong number of messages.")); + return ret_messages; +} + +void check_panda_can_msg(panda::PANDA_CAN_MSG& msgin, uint8_t bus, unsigned long addr, bool addr_29b, + bool is_receipt, std::string dat, const __LineInfo* pLineInfo) { + Assert::AreEqual(bus, msgin.bus, _T("Wrong msg bus"), pLineInfo); + Assert::AreEqual(addr, msgin.addr, _T("Wrong msg addr"), pLineInfo); + Assert::AreEqual(addr_29b, msgin.addr_29b, _T("Wrong msg 29b flag"), pLineInfo); + Assert::AreEqual(is_receipt, msgin.is_receipt, _T("Wrong msg receipt flag"), pLineInfo); + + std::ostringstream logmsg; + logmsg << "Expected Hex ("; + for (int i = 0; i < dat.size(); i++) logmsg << std::hex << std::setw(2) << std::setfill('0') << int(dat[i] & 0xFF) << " "; + logmsg << "); Actual Hex ("; + for (int i = 0; i < msgin.len; i++) logmsg << std::hex << std::setw(2) << std::setfill('0') << int(((char*)msgin.dat)[i] & 0xFF) << " "; + logmsg << ")"; + Logger::WriteMessage(logmsg.str().c_str()); + + Assert::AreEqual(dat.size(), msgin.len, _T("Wrong msg len"), pLineInfo); + Assert::AreEqual(dat, std::string((char*)msgin.dat, msgin.len), _T("Wrong msg payload"), pLineInfo); +} + +unsigned long J2534_start_periodic_msg_checked(unsigned long chanid, unsigned long ProtocolID, unsigned long TxFlags, unsigned long DataSize, + unsigned long ExtraDataIndex, const char * Data, unsigned long TimeInterval, const __LineInfo * pLineInfo) { + PASSTHRU_MSG msg = { ProtocolID, 0, TxFlags, 0, DataSize, ExtraDataIndex }; + memcpy_s(msg.Data, 4128, Data, DataSize); + unsigned long msgID; + Assert::AreEqual(STATUS_NOERROR, J2534_start_periodic_msg(chanid, ProtocolID, TxFlags, DataSize, + ExtraDataIndex, Data, TimeInterval, &msgID, pLineInfo), _T("Failed to start Periodic Message."), pLineInfo); + return msgID; +} + +unsigned long J2534_start_periodic_msg(unsigned long chanid, unsigned long ProtocolID, unsigned long TxFlags, unsigned long DataSize, + unsigned long ExtraDataIndex, const char * Data, unsigned long TimeInterval, unsigned long* msgID, const __LineInfo * pLineInfo) { + PASSTHRU_MSG msg = { ProtocolID, 0, TxFlags, 0, DataSize, ExtraDataIndex }; + memcpy_s(msg.Data, 4128, Data, DataSize); + return PassThruStartPeriodicMsg(chanid, &msg, msgID, TimeInterval); +} + +void J2534_send_msg_checked(unsigned long chanid, unsigned long ProtocolID, unsigned long RxStatus, unsigned long TxFlags, + unsigned long Timestamp, unsigned long DataSize, unsigned long ExtraDataIndex, const char* Data, const __LineInfo* pLineInfo) { + + PASSTHRU_MSG msg = { ProtocolID, RxStatus, TxFlags, Timestamp, DataSize, ExtraDataIndex }; + memcpy_s(msg.Data, 4128, Data, DataSize); + unsigned long msgcount = 1; + Assert::AreEqual(STATUS_NOERROR, PassThruWriteMsgs(chanid, &msg, &msgcount, 0), _T("Failed to write message."), pLineInfo); + Assert::AreEqual(1, msgcount, _T("Wrong message count after tx."), pLineInfo); +} + +long J2534_send_msg(unsigned long chanid, unsigned long ProtocolID, unsigned long RxStatus, unsigned long TxFlags, + unsigned long Timestamp, unsigned long DataSize, unsigned long ExtraDataIndex, const char* Data) { + + PASSTHRU_MSG msg = { ProtocolID, RxStatus, TxFlags, Timestamp, DataSize, ExtraDataIndex }; + memcpy_s(msg.Data, 4128, Data, DataSize); + unsigned long msgcount = 1; + return PassThruWriteMsgs(chanid, &msg, &msgcount, 0); +} + +//Allow more messages to come in than the min. +std::vector j2534_recv_loop_loose(unsigned int chanid, unsigned int min_num, unsigned long timeout_ms) { + std::vector ret_messages; + PASSTHRU_MSG recvbuff[4] = {}; + Timer t = Timer(); + + while (t.getTimePassed() < timeout_ms) { + unsigned long msgcount = 4; + unsigned int res = PassThruReadMsgs(chanid, recvbuff, &msgcount, 0); + if (res == ERR_BUFFER_EMPTY) continue; + Assert::IsFalse(msgcount > 4, _T("PassThruReadMsgs returned more data than the buffer could hold.")); + Assert::AreEqual(STATUS_NOERROR, res, _T("Failed to read message.")); + if (msgcount > 0) { + for (unsigned int i = 0; i < msgcount; i++) { + ret_messages.push_back(recvbuff[i]); + } + } + } + + Assert::IsTrue(min_num <= ret_messages.size(), _T("Received too few messages.")); + return ret_messages; +} + +std::vector j2534_recv_loop(unsigned int chanid, unsigned int num_expected, unsigned long timeout_ms) { + std::vector ret_messages; + PASSTHRU_MSG recvbuff[4] = {}; + Timer t = Timer(); + + while (t.getTimePassed() < timeout_ms) { + unsigned long msgcount = 4; + unsigned int res = PassThruReadMsgs(chanid, recvbuff, &msgcount, 0); + if (res == ERR_BUFFER_EMPTY) continue; + Assert::IsFalse(msgcount > 4, _T("PassThruReadMsgs returned more data than the buffer could hold.")); + Assert::AreEqual(STATUS_NOERROR, res, _T("Failed to read message.")); + if (msgcount > 0) { + for (unsigned int i = 0; i < msgcount; i++) { + ret_messages.push_back(recvbuff[i]); + } + } + if (ret_messages.size() >= num_expected) break; + } + + std::ostringstream stringStream; + stringStream << "j2534_recv_loop Broke at " << t.getTimePassed() << " ms size is " << ret_messages.size() << std::endl; + + if (num_expected != ret_messages.size()) { + stringStream << "Incorrect number of messages received. Displaying the messages:" << std::endl; + for (auto msg : ret_messages) { + stringStream << " TS: " << msg.Timestamp << "; Dat: "; + for (int i = 0; i < msg.DataSize; i++) stringStream << std::hex << std::setw(2) << std::setfill('0') << int(msg.Data[i] & 0xFF) << " "; + stringStream << std::endl; + } + } + + Logger::WriteMessage(stringStream.str().c_str()); + + Assert::AreEqual(num_expected, ret_messages.size(), _T("Received wrong number of messages.")); + return ret_messages; +} + +void check_J2534_can_msg(PASSTHRU_MSG& msgin, unsigned long ProtocolID, unsigned long RxStatus, unsigned long TxFlags, + unsigned long DataSize, unsigned long ExtraDataIndex, const char* Data, const __LineInfo* pLineInfo) { + Assert::AreEqual(DataSize, msgin.DataSize, _T("Wrong msg len"), pLineInfo); + + std::ostringstream logmsg; + logmsg << "Expected Hex ("; + for (int i = 0; i < DataSize; i++) logmsg << std::hex << std::setw(2) << std::setfill('0') << int(Data[i] & 0xFF) << " "; + logmsg << "); Actual Hex ("; + for (int i = 0; i < msgin.DataSize; i++) logmsg << std::hex << std::setw(2) << std::setfill('0') << int(((char*)msgin.Data)[i] & 0xFF) << " "; + logmsg << ")"; + Logger::WriteMessage(logmsg.str().c_str()); + Assert::AreEqual(std::string(Data, DataSize), std::string((char*)msgin.Data, msgin.DataSize), _T("Wrong msg payload"), pLineInfo); + + Assert::AreEqual(ProtocolID, msgin.ProtocolID, _T("Wrong msg protocol"), pLineInfo); + Assert::AreEqual(RxStatus, msgin.RxStatus, _T("Wrong msg receipt rxstatus"), pLineInfo); + Assert::AreEqual(TxFlags, msgin.TxFlags, _T("Wrong msg receipt txflag"), pLineInfo); + Assert::AreEqual(ExtraDataIndex, msgin.ExtraDataIndex, _T("Wrong msg ExtraDataIndex"), pLineInfo); +} + +unsigned long J2534_set_PASS_filter(unsigned long chanid, unsigned long ProtocolID, unsigned long tx, + unsigned long len, char* mask, char* pattern, const __LineInfo* pLineInfo) { + unsigned long filterid; + PASSTHRU_MSG mask_msg = { ProtocolID, 0, tx, 0, len, 0, 0 }; + PASSTHRU_MSG pattern_msg = { ProtocolID, 0, tx, 0, len, 0, 0 }; + memcpy(mask_msg.Data, mask, len); + memcpy(pattern_msg.Data, pattern, len); + Assert::AreEqual(STATUS_NOERROR, PassThruStartMsgFilter(chanid, PASS_FILTER, &mask_msg, &pattern_msg, NULL, &filterid), + _T("Failed to create filter."), pLineInfo); + return filterid; +} + +unsigned long J2534_set_BLOCK_filter(unsigned long chanid, unsigned long ProtocolID, unsigned long tx, + unsigned long len, char* mask, char* pattern, const __LineInfo* pLineInfo) { + unsigned long filterid; + PASSTHRU_MSG mask_msg = { ProtocolID, 0, tx, 0, len, 0, 0 }; + PASSTHRU_MSG pattern_msg = { ProtocolID, 0, tx, 0, len, 0, 0 }; + memcpy(mask_msg.Data, mask, len); + memcpy(pattern_msg.Data, pattern, len); + Assert::AreEqual(STATUS_NOERROR, PassThruStartMsgFilter(chanid, BLOCK_FILTER, &mask_msg, &pattern_msg, NULL, &filterid), + _T("Failed to create filter."), pLineInfo); + return filterid; +} + +unsigned long J2534_set_flowctrl_filter(unsigned long chanid, unsigned long tx, + unsigned long len, char* mask, char* pattern, char* flow, const __LineInfo* pLineInfo) { + unsigned long filterid; + PASSTHRU_MSG mask_msg = { ISO15765, 0, tx, 0, len, 0, 0 }; + PASSTHRU_MSG pattern_msg = { ISO15765, 0, tx, 0, len, 0, 0 }; + PASSTHRU_MSG flow_msg = { ISO15765, 0, tx, 0, len, 0, 0 }; + memcpy(mask_msg.Data, mask, len); + memcpy(pattern_msg.Data, pattern, len); + memcpy(flow_msg.Data, flow, len); + Assert::AreEqual(STATUS_NOERROR, PassThruStartMsgFilter(chanid, FLOW_CONTROL_FILTER, &mask_msg, &pattern_msg, &flow_msg, &filterid), + _T("Failed to create filter."), pLineInfo); + return filterid; +} + +std::unique_ptr getPanda(unsigned long kbaud, BOOL loopback) { + auto p = panda::Panda::openPanda(""); + Assert::IsTrue(p != nullptr, _T("Could not open raw panda device to test communication.")); + p->set_can_speed_kbps(panda::PANDA_CAN1, kbaud); + p->set_safety_mode(panda::SAFETY_ALLOUTPUT); + p->set_can_loopback(loopback); + p->can_clear(panda::PANDA_CAN_RX); + return p; +} + +std::vector checked_panda_send(std::unique_ptr& p, uint32_t addr, bool is_29b, + char* msg, uint8_t len, unsigned int num_expected, const __LineInfo* pLineInfo, unsigned long timeout_ms) { + Assert::IsTrue(p->can_send(addr, is_29b, (const uint8_t*)msg, len, panda::PANDA_CAN1), _T("Panda send says it failed."), pLineInfo); + auto panda_msg_recv = panda_recv_loop(p, 1 + num_expected, timeout_ms); + check_panda_can_msg(panda_msg_recv[0], 0, addr, is_29b, TRUE, std::string(msg, len), pLineInfo); + panda_msg_recv.erase(panda_msg_recv.begin()); + return panda_msg_recv; +} diff --git a/drivers/windows/pandaJ2534DLL Test/TestHelpers.h b/drivers/windows/pandaJ2534DLL Test/TestHelpers.h new file mode 100644 index 0000000000..17dcee5f54 --- /dev/null +++ b/drivers/windows/pandaJ2534DLL Test/TestHelpers.h @@ -0,0 +1,48 @@ +#pragma once +#include "stdafx.h" +#include "pandaJ2534DLL/J2534_v0404.h" +#include "panda/panda.h" + +using namespace Microsoft::VisualStudio::CppUnitTestFramework; + +extern void write_ioctl(unsigned int chanid, unsigned int param, unsigned int val, const __LineInfo* pLineInfo = NULL); + +extern std::vector panda_recv_loop_loose(std::unique_ptr& p, unsigned int min_num, unsigned long timeout_ms = 100); + +extern std::vector panda_recv_loop(std::unique_ptr& p, unsigned int num_expected, unsigned long timeout_ms = 100); + +extern void check_panda_can_msg(panda::PANDA_CAN_MSG& msgin, uint8_t bus, unsigned long addr, bool addr_29b, + bool is_receipt, std::string dat, const __LineInfo* pLineInfo = NULL); + +extern unsigned long J2534_start_periodic_msg_checked(unsigned long chanid, unsigned long ProtocolID, unsigned long TxFlags, unsigned long DataSize, + unsigned long ExtraDataIndex, const char * Data, unsigned long TimeInterval, const __LineInfo * pLineInfo); + +extern unsigned long J2534_start_periodic_msg(unsigned long chanid, unsigned long ProtocolID, unsigned long TxFlags, unsigned long DataSize, + unsigned long ExtraDataIndex, const char* Data, unsigned long TimeInterval, unsigned long* msgID, const __LineInfo* pLineInfo = NULL); + +extern void J2534_send_msg_checked(unsigned long chanid, unsigned long ProtocolID, unsigned long RxStatus, unsigned long TxFlags, + unsigned long Timestamp, unsigned long DataSize, unsigned long ExtraDataIndex, const char* Data, const __LineInfo* pLineInfo = NULL); + +extern long J2534_send_msg(unsigned long chanid, unsigned long ProtocolID, unsigned long RxStatus, unsigned long TxFlags, + unsigned long Timestamp, unsigned long DataSize, unsigned long ExtraDataIndex, const char* Data); + +extern std::vector j2534_recv_loop_loose(unsigned int chanid, unsigned int min_num, unsigned long timeout_ms = 100); + +extern std::vector j2534_recv_loop(unsigned int chanid, unsigned int num_expected, unsigned long timeout_ms = 100); + +extern void check_J2534_can_msg(PASSTHRU_MSG& msgin, unsigned long ProtocolID, unsigned long RxStatus, unsigned long TxFlags, + unsigned long DataSize, unsigned long ExtraDataIndex, const char* Data, const __LineInfo* pLineInfo = NULL); + +extern unsigned long J2534_set_PASS_filter(unsigned long chanid, unsigned long ProtocolID, unsigned long tx, + unsigned long len, char* mask, char* pattern, const __LineInfo* pLineInfo = NULL); + +extern unsigned long J2534_set_BLOCK_filter(unsigned long chanid, unsigned long ProtocolID, unsigned long tx, + unsigned long len, char* mask, char* pattern, const __LineInfo* pLineInfo = NULL); + +extern unsigned long J2534_set_flowctrl_filter(unsigned long chanid, unsigned long tx, + unsigned long len, char* mask, char* pattern, char* flow, const __LineInfo* pLineInfo = NULL); + +extern std::unique_ptr getPanda(unsigned long kbaud = 500, BOOL loopback = FALSE); + +extern std::vector checked_panda_send(std::unique_ptr& p, uint32_t addr, bool is_29b, + char* msg, uint8_t len, unsigned int num_expected=0, const __LineInfo* pLineInfo = NULL, unsigned long timeout_ms = 100); diff --git a/drivers/windows/pandaJ2534DLL Test/Timer.cpp b/drivers/windows/pandaJ2534DLL Test/Timer.cpp new file mode 100644 index 0000000000..33d029e844 --- /dev/null +++ b/drivers/windows/pandaJ2534DLL Test/Timer.cpp @@ -0,0 +1,21 @@ +#include "stdafx.h" +#include "Timer.h" + + +Timer::Timer() +{ + reset(); +} + +// gets the time elapsed from construction. +unsigned long long /*milliseconds*/ Timer::getTimePassed(){ + // get the new time + auto end = std::chrono::time_point_cast(clock::now()); + + // return the difference of the times + return (end - start).count(); +} + +void Timer::reset() { + start = std::chrono::time_point_cast(clock::now()); +} \ No newline at end of file diff --git a/drivers/windows/pandaJ2534DLL Test/Timer.h b/drivers/windows/pandaJ2534DLL Test/Timer.h new file mode 100644 index 0000000000..cbf5579a5c --- /dev/null +++ b/drivers/windows/pandaJ2534DLL Test/Timer.h @@ -0,0 +1,20 @@ +#pragma once +#include + +//Copied from https://stackoverflow.com/a/31488113 + +class Timer +{ + using clock = std::chrono::steady_clock; + using time_point_type = std::chrono::time_point < clock, std::chrono::milliseconds >; +public: + Timer(); + + // gets the time elapsed from construction. + unsigned long long /*milliseconds*/ getTimePassed(); + + void reset(); + +private: + time_point_type start; +}; \ No newline at end of file diff --git a/drivers/windows/pandaJ2534DLL Test/j2534_tests.cpp b/drivers/windows/pandaJ2534DLL Test/j2534_tests.cpp new file mode 100644 index 0000000000..774b8ed31c --- /dev/null +++ b/drivers/windows/pandaJ2534DLL Test/j2534_tests.cpp @@ -0,0 +1,1602 @@ +#include "stdafx.h" +#include "Loader4.h" +#include "pandaJ2534DLL/J2534_v0404.h" +#include "panda/panda.h" +#include "Timer.h" +#include "ECUsim DLL\ECUsim.h" +#include "TestHelpers.h" + +using namespace Microsoft::VisualStudio::CppUnitTestFramework; + +namespace pandaJ2534DLLTest +{ + TEST_CLASS(J2534DLLInitialization) + { + public: + + TEST_CLASS_CLEANUP(deinit) { + UnloadJ2534Dll(); + } + + TEST_METHOD(J2534_Driver_Init) + { + long err = LoadJ2534Dll("pandaJ2534_0404_32.dll"); + Assert::IsTrue(err == 0, _T("Library failed to load properly. Check the export names and library location.")); + } + + }; + + TEST_CLASS(J2534DeviceInitialization) + { + public: + + TEST_METHOD_INITIALIZE(init) { + LoadJ2534Dll("pandaJ2534_0404_32.dll"); + } + + TEST_METHOD_CLEANUP(deinit) { + if (didopen) { + PassThruClose(devid); + didopen = FALSE; + } + UnloadJ2534Dll(); + } + + TEST_METHOD(J2534_Device_OpenDevice__Empty) + { + Assert::AreEqual(STATUS_NOERROR, open_dev(""), _T("Failed to open device."), LINE_INFO()); + } + + TEST_METHOD(J2534_Device_OpenDevice__J2534_2) + { + Assert::AreEqual(STATUS_NOERROR, open_dev("J2534-2:"), _T("Failed to open device."), LINE_INFO()); + } + + TEST_METHOD(J2534_Device_OpenDevice__SN) + { + auto pandas_available = panda::Panda::listAvailablePandas(); + Assert::IsTrue(pandas_available.size() > 0, _T("No pandas detected.")); + + Assert::AreEqual(STATUS_NOERROR, open_dev(pandas_available[0].c_str()), _T("Failed to open device."), LINE_INFO()); + + auto pandas_available_2 = panda::Panda::listAvailablePandas(); + for (auto panda_sn : pandas_available_2) + Assert::AreNotEqual(panda_sn, pandas_available[0]); + } + + TEST_METHOD(J2534_Device_CloseDevice) + { + Assert::AreEqual(STATUS_NOERROR, open_dev(""), _T("Failed to open device."), LINE_INFO()); + Assert::AreEqual(STATUS_NOERROR, close_dev(devid), _T("Failed to close device."), LINE_INFO()); + Assert::AreEqual(ERR_INVALID_DEVICE_ID, PassThruClose(devid), _T("The 2nd close should have failed with ERR_INVALID_DEVICE_ID."), LINE_INFO()); + } + + TEST_METHOD(J2534_Device_ConnectDisconnect) + { + unsigned long chanid; + Assert::AreEqual(STATUS_NOERROR, open_dev(""), _T("Failed to open device."), LINE_INFO()); + Assert::AreEqual(STATUS_NOERROR, PassThruConnect(devid, CAN, 0, 500000, &chanid), _T("Failed to open channel."), LINE_INFO()); + + Assert::AreEqual(STATUS_NOERROR, PassThruDisconnect(chanid), _T("Failed to close channel."), LINE_INFO()); + Assert::AreEqual(ERR_INVALID_CHANNEL_ID, PassThruDisconnect(chanid), _T("The 2nd disconnect should have failed with ERR_INVALID_CHANNEL_ID."), LINE_INFO()); + } + + TEST_METHOD(J2534_Device_ConnectInvalidProtocol) + { + unsigned long chanid; + Assert::AreEqual(STATUS_NOERROR, open_dev(""), _T("Failed to open device."), LINE_INFO()); + Assert::AreEqual(ERR_INVALID_PROTOCOL_ID, PassThruConnect(devid, 999, 0, 500000, &chanid), + _T("Did not report ERR_INVALID_PROTOCOL_ID."), LINE_INFO()); + Assert::AreEqual(ERR_INVALID_CHANNEL_ID, PassThruDisconnect(chanid), _T("The channel should not have been created."), LINE_INFO()); + } + + bool didopen = FALSE; + unsigned long devid; + + unsigned long open_dev(const char* name, long assert_err = STATUS_NOERROR, TCHAR* failmsg = _T("Failed to open device.")) { + unsigned int res = PassThruOpen((void*)name, &devid); + if (res == STATUS_NOERROR) didopen = TRUE; + return res; + } + + unsigned long close_dev(unsigned long devid) { + unsigned long res = PassThruClose(devid); + if (res == STATUS_NOERROR) didopen = FALSE; + return res; + } + + }; + + TEST_CLASS(J2534DeviceCAN) + { + public: + + TEST_METHOD_INITIALIZE(init) { + LoadJ2534Dll("pandaJ2534_0404_32.dll"); + } + + TEST_METHOD_CLEANUP(deinit) { + if (didopen) { + PassThruClose(devid); + didopen = FALSE; + } + UnloadJ2534Dll(); + } + + //Test that the BAUD rate of a CAN connection can be changed. + TEST_METHOD(J2534_CAN_SetBaud) + { + auto chanid = J2534_open_and_connect("", CAN, 0, 500000, LINE_INFO()); + write_ioctl(chanid, LOOPBACK, TRUE, LINE_INFO()); // ENABLE J2534 ECHO/LOOPBACK + auto p = getPanda(250); + + J2534_send_msg_checked(chanid, CAN, 0, 0, 0, 4 + 2, 0, "\x0\x0\x3\xAB""HI", LINE_INFO()); + j2534_recv_loop(chanid, 0); + panda_recv_loop(p, 0); + + write_ioctl(chanid, DATA_RATE, 250000, LINE_INFO()); + + auto j2534_msg_recv = j2534_recv_loop(chanid, 1); + check_J2534_can_msg(j2534_msg_recv[0], CAN, TX_MSG_TYPE, 0, 4 + 2, 0, "\x0\x0\x3\xAB""HI", LINE_INFO()); + auto panda_msg_recv = panda_recv_loop(p, 1); + check_panda_can_msg(panda_msg_recv[0], 0, 0x3AB, FALSE, FALSE, "HI", LINE_INFO()); + } + + TEST_METHOD(J2534_CAN_11b_Tx) + { + auto chanid = J2534_open_and_connect("", CAN, 0, 500000, LINE_INFO()); + auto p = getPanda(500); + + J2534_send_msg_checked(chanid, CAN, 0, 0, 0, 6, 6, "\x0\x0\x3\xAB""HI", LINE_INFO()); + + std::vector msg_recv = panda_recv_loop(p, 1); + check_panda_can_msg(msg_recv[0], 0, 0x3AB, FALSE, FALSE, "HI", LINE_INFO()); + + j2534_recv_loop(chanid, 0, 50); // Check no message is returned (since loopback is off) + } + + TEST_METHOD(J2534_CAN_29b_Tx) + { + auto chanid = J2534_open_and_connect("", CAN, CAN_29BIT_ID, 500000, LINE_INFO()); + auto p = getPanda(500); + + Assert::AreEqual(ERR_INVALID_MSG, J2534_send_msg(chanid, CAN, 0, 0, 0, 6, 6, "\x0\x0\x3\xAB""HI"), _T("11b address should fail to tx."), LINE_INFO()); + J2534_send_msg_checked(chanid, CAN, 0, CAN_29BIT_ID, 0, 6, 6, "\x0\x0\x3\xAB""YO", LINE_INFO()); + + std::vector msg_recv = panda_recv_loop(p, 1); + check_panda_can_msg(msg_recv[0], 0, 0x3AB, TRUE, FALSE, "YO", LINE_INFO()); + } + + TEST_METHOD(J2534_CAN_11b29b_Tx) + { + auto chanid = J2534_open_and_connect("", CAN, CAN_ID_BOTH, 500000, LINE_INFO()); + auto p = getPanda(500); + + J2534_send_msg_checked(chanid, CAN, 0, 0, 0, 6, 6, "\x0\x0\x3\xAB""HI", LINE_INFO()); + J2534_send_msg_checked(chanid, CAN, 0, CAN_29BIT_ID, 0, 6, 6, "\x0\x0\x3\xAB""YO", LINE_INFO()); + + std::vector msg_recv = panda_recv_loop(p, 2); + check_panda_can_msg(msg_recv[0], 0, 0x3AB, FALSE, FALSE, "HI", LINE_INFO()); + check_panda_can_msg(msg_recv[1], 0, 0x3AB, TRUE, FALSE, "YO", LINE_INFO()); + } + + TEST_METHOD(J2534_CAN_TxEcho) + { + auto chanid = J2534_open_and_connect("", CAN, 0, 500000, LINE_INFO()); + auto p = getPanda(500); + + J2534_send_msg_checked(chanid, CAN, 0, 0, 0, 9, 9, "\x0\x0\x3\xAB""HIDOG", LINE_INFO()); + + auto msg_recv = panda_recv_loop(p, 1); + check_panda_can_msg(msg_recv[0], 0, 0x3AB, FALSE, FALSE, "HIDOG", LINE_INFO()); + + auto j2534_msg_recv = j2534_recv_loop(chanid, 0); + + ///////////////////////////////// + write_ioctl(chanid, LOOPBACK, TRUE, LINE_INFO()); // ENABLE J2534 ECHO/LOOPBACK + + J2534_send_msg_checked(chanid, CAN, 0, 0, 0, 7, 7, "\x0\x0\x3\xAB""SUP", LINE_INFO()); + + msg_recv = panda_recv_loop(p, 1); + check_panda_can_msg(msg_recv[0], 0, 0x3AB, FALSE, FALSE, "SUP", LINE_INFO()); + + j2534_msg_recv = j2534_recv_loop(chanid, 1); + check_J2534_can_msg(j2534_msg_recv[0], CAN, TX_MSG_TYPE, 0, 3 + 4, 0, "\x0\x0\x3\xAB""SUP", LINE_INFO()); + } + + TEST_METHOD(J2534_CAN_RxAndPassAllFilters) + { + auto chanid = J2534_open_and_connect("", CAN, 0, 500000, LINE_INFO()); + J2534_set_PASS_filter(chanid, CAN, 0, 4, "\x0\x0\x0\x0", "\x0\x0\x0\x0", LINE_INFO()); + auto p = getPanda(500); + + p->can_send(0x1FA, FALSE, (const uint8_t*)"ABCDE", 5, panda::PANDA_CAN1); + p->can_send(0x2AC, FALSE, (const uint8_t*)"HIJKL", 5, panda::PANDA_CAN1); + + auto j2534_msg_recv = j2534_recv_loop(chanid, 2); + check_J2534_can_msg(j2534_msg_recv[0], CAN, 0, 0, 5 + 4, 0, "\x0\x0\x1\xFA""ABCDE", LINE_INFO()); + check_J2534_can_msg(j2534_msg_recv[1], CAN, 0, 0, 5 + 4, 0, "\x0\x0\x2\xAC""HIJKL", LINE_INFO()); + } + + TEST_METHOD(J2534_CAN_RxAndLimitedPassFilter) + { + auto chanid = J2534_open_and_connect("", CAN, 0, 500000, LINE_INFO()); + J2534_set_PASS_filter(chanid, CAN, 0, 4, "\xFF\xFF\xFF\xFF", "\x0\x0\x02\xAC", LINE_INFO()); + auto p = getPanda(500); + + p->can_send(0x1FA, FALSE, (const uint8_t*)"ABCDE", 5, panda::PANDA_CAN1); + p->can_send(0x2AC, FALSE, (const uint8_t*)"HIJKL", 5, panda::PANDA_CAN1); + + auto j2534_msg_recv = j2534_recv_loop(chanid, 1); + check_J2534_can_msg(j2534_msg_recv[0], CAN, 0, 0, 5 + 4, 0, "\x0\x0\x2\xAC""HIJKL", LINE_INFO()); + } + + TEST_METHOD(J2534_CAN_RxAndPassBlockFilter) + { + auto chanid = J2534_open_and_connect("", CAN, 0, 500000, LINE_INFO()); + J2534_set_PASS_filter(chanid, CAN, 0, 4, "\x0\x0\x0\x0", "\x0\x0\x0\x0", LINE_INFO()); + J2534_set_BLOCK_filter(chanid, CAN, 0, 4, "\xFF\xFF\xFF\xFF", "\x0\x0\x02\xAC", LINE_INFO()); + auto p = getPanda(500); + + p->can_send(0x1FA, FALSE, (const uint8_t*)"ABCDE", 5, panda::PANDA_CAN1); + p->can_send(0x2AC, FALSE, (const uint8_t*)"HIJKL", 5, panda::PANDA_CAN1); + p->can_send(0x3FA, FALSE, (const uint8_t*)"MNOPQ", 5, panda::PANDA_CAN1); + + auto j2534_msg_recv = j2534_recv_loop(chanid, 2, 1000); + check_J2534_can_msg(j2534_msg_recv[0], CAN, 0, 0, 5 + 4, 0, "\x0\x0\x1\xFA""ABCDE", LINE_INFO()); + check_J2534_can_msg(j2534_msg_recv[1], CAN, 0, 0, 5 + 4, 0, "\x0\x0\x3\xFA""MNOPQ", LINE_INFO()); + } + + //Check that the order of the pass and block filter do not matter + TEST_METHOD(J2534_CAN_RxAndFilterBlockPass) + { + auto chanid = J2534_open_and_connect("", CAN, 0, 500000, LINE_INFO()); + J2534_set_BLOCK_filter(chanid, CAN, 0, 4, "\xFF\xFF\xFF\xFF", "\x0\x0\x02\xAC", LINE_INFO()); + J2534_set_PASS_filter(chanid, CAN, 0, 4, "\x0\x0\x0\x0", "\x0\x0\x0\x0", LINE_INFO()); + auto p = getPanda(500); + + p->can_send(0x1FA, FALSE, (const uint8_t*)"ABCDE", 5, panda::PANDA_CAN1); + p->can_send(0x2AC, FALSE, (const uint8_t*)"HIJKL", 5, panda::PANDA_CAN1); // Should not pass filter + p->can_send(0x3FA, FALSE, (const uint8_t*)"MNOPQ", 5, panda::PANDA_CAN1); + + auto j2534_msg_recv = j2534_recv_loop(chanid, 2, 2000); + check_J2534_can_msg(j2534_msg_recv[0], CAN, 0, 0, 5 + 4, 0, "\x0\x0\x1\xFA""ABCDE", LINE_INFO()); + check_J2534_can_msg(j2534_msg_recv[1], CAN, 0, 0, 5 + 4, 0, "\x0\x0\x3\xFA""MNOPQ", LINE_INFO()); + } + + //Check that the order of the pass and block filter do not matter + TEST_METHOD(J2534_CAN_RxAndFilterRemoval) + { + auto chanid = J2534_open_and_connect("", CAN, 0, 500000, LINE_INFO()); + auto filterid0 = J2534_set_BLOCK_filter(chanid, CAN, 0, 4, "\xFF\xFF\xFF\xFF", "\x0\x0\x02\xAC", LINE_INFO()); + auto filterid1 = J2534_set_PASS_filter(chanid, CAN, 0, 4, "\x0\x0\x0\x0", "\x0\x0\x0\x0", LINE_INFO()); + + Assert::AreEqual(STATUS_NOERROR, PassThruStopMsgFilter(chanid, filterid0), _T("Failed to delete filter."), LINE_INFO()); + + auto p = getPanda(500); + + p->can_send(0x1FA, FALSE, (const uint8_t*)"ABCDE", 5, panda::PANDA_CAN1); + p->can_send(0x2AC, FALSE, (const uint8_t*)"HIJKL", 5, panda::PANDA_CAN1); + p->can_send(0x3FA, FALSE, (const uint8_t*)"MNOPQ", 5, panda::PANDA_CAN1); + + auto j2534_msg_recv = j2534_recv_loop(chanid, 3, 1000); + check_J2534_can_msg(j2534_msg_recv[0], CAN, 0, 0, 5 + 4, 0, "\x0\x0\x1\xFA""ABCDE", LINE_INFO()); + check_J2534_can_msg(j2534_msg_recv[1], CAN, 0, 0, 5 + 4, 0, "\x0\x0\x2\xAC""HIJKL", LINE_INFO()); + check_J2534_can_msg(j2534_msg_recv[2], CAN, 0, 0, 5 + 4, 0, "\x0\x0\x3\xFA""MNOPQ", LINE_INFO()); + } + + //Check that the order of the pass and block filter do not matter + TEST_METHOD(J2534_CAN_RxWithTimeout) + { + auto chanid = J2534_open_and_connect("", CAN, 0, 500000, LINE_INFO()); + J2534_set_PASS_filter(chanid, CAN, 0, 4, "\x0\x0\x0\x0", "\x0\x0\x0\x0", LINE_INFO()); + auto p = getPanda(500); + + PASSTHRU_MSG recvbuff; + unsigned long msgcount = 1; + unsigned int res = PassThruReadMsgs(chanid, &recvbuff, &msgcount, 100); // Here is where we test the timeout + Assert::AreEqual(ERR_BUFFER_EMPTY, res, _T("No message should be found"), LINE_INFO()); + Assert::AreEqual(0, msgcount, _T("Received wrong number of messages.")); + + //TODO Test that the timings work right instead of just testing it doesn't crash. + } + + TEST_METHOD(J2534_CAN_Baud) + { + auto chanid = J2534_open_and_connect("", CAN, 0, 250000, LINE_INFO()); + auto p = getPanda(250); + + J2534_send_msg_checked(chanid, CAN, 0, 0, 0, 6, 6, "\x0\x0\x3\xAB""HI", LINE_INFO()); + + std::vector msg_recv = panda_recv_loop(p, 1); + check_panda_can_msg(msg_recv[0], 0, 0x3AB, FALSE, FALSE, "HI", LINE_INFO()); + } + + TEST_METHOD(J2534_CAN_PeriodicMessageStartStop) + { + auto chanid = J2534_open_and_connect("", CAN, 0, 500000, LINE_INFO()); + auto p = getPanda(500); + + auto msgid = J2534_start_periodic_msg_checked(chanid, CAN, 0, 6, 0, "\x0\x0\x3\xAB""HI", 100, LINE_INFO()); + + std::vector msg_recv = panda_recv_loop(p, 3, 250); + Assert::AreEqual(STATUS_NOERROR, PassThruStopPeriodicMsg(chanid, msgid), _T("Failed to delete filter."), LINE_INFO()); + check_panda_can_msg(msg_recv[0], 0, 0x3AB, FALSE, FALSE, "HI", LINE_INFO()); + check_panda_can_msg(msg_recv[1], 0, 0x3AB, FALSE, FALSE, "HI", LINE_INFO()); + check_panda_can_msg(msg_recv[2], 0, 0x3AB, FALSE, FALSE, "HI", LINE_INFO()); + + auto timediff_1_0 = msg_recv[1].recv_time - msg_recv[0].recv_time; + auto timediff_2_1 = msg_recv[2].recv_time - msg_recv[1].recv_time; + + std::ostringstream stringStream1; + stringStream1 << "times1: " << timediff_1_0 << ", " << timediff_2_1 << std::endl; + Logger::WriteMessage(stringStream1.str().c_str()); + + Assert::IsTrue(timediff_1_0 > 90000); + Assert::IsTrue(timediff_1_0 < 110000); + Assert::IsTrue(timediff_2_1 > 90000); + Assert::IsTrue(timediff_2_1 < 110000); + + msg_recv = panda_recv_loop(p, 0, 300); + } + + TEST_METHOD(J2534_CAN_PeriodicMessageMultipleStartStop) + { + auto chanid = J2534_open_and_connect("", CAN, 0, 500000, LINE_INFO()); + auto p = getPanda(500); + + auto msgid0 = J2534_start_periodic_msg_checked(chanid, CAN, 0, 6, 0, "\x0\x0\x3\xAB""HI", 100, LINE_INFO()); + auto msgid1 = J2534_start_periodic_msg_checked(chanid, CAN, 0, 6, 0, "\x0\x0\x1\x23""YO", 80, LINE_INFO()); + + std::vector msg_recv = panda_recv_loop(p, 9, 370); + Assert::AreEqual(STATUS_NOERROR, PassThruStopPeriodicMsg(chanid, msgid0), _T("Failed to delete filter."), LINE_INFO()); + Assert::AreEqual(STATUS_NOERROR, PassThruStopPeriodicMsg(chanid, msgid1), _T("Failed to delete filter."), LINE_INFO()); + //time diagram. 10 ms per character. * is send event. : is termination of periodic messages. + //*---------*---------*---------*-----:----* HI + //*-------*-------*-------*-------*---:----* YO + check_panda_can_msg(msg_recv[0], 0, 0x3AB, FALSE, FALSE, "HI", LINE_INFO()); + check_panda_can_msg(msg_recv[1], 0, 0x123, FALSE, FALSE, "YO", LINE_INFO()); + check_panda_can_msg(msg_recv[2], 0, 0x123, FALSE, FALSE, "YO", LINE_INFO()); + check_panda_can_msg(msg_recv[3], 0, 0x3AB, FALSE, FALSE, "HI", LINE_INFO()); + check_panda_can_msg(msg_recv[4], 0, 0x123, FALSE, FALSE, "YO", LINE_INFO()); + check_panda_can_msg(msg_recv[5], 0, 0x3AB, FALSE, FALSE, "HI", LINE_INFO()); + check_panda_can_msg(msg_recv[6], 0, 0x123, FALSE, FALSE, "YO", LINE_INFO()); + check_panda_can_msg(msg_recv[7], 0, 0x3AB, FALSE, FALSE, "HI", LINE_INFO()); + check_panda_can_msg(msg_recv[8], 0, 0x123, FALSE, FALSE, "YO", LINE_INFO()); + + auto timediff_HI_3_0 = msg_recv[3].recv_time - msg_recv[0].recv_time; + auto timediff_HI_5_3 = msg_recv[5].recv_time - msg_recv[3].recv_time; + auto timediff_HI_7_5 = msg_recv[7].recv_time - msg_recv[5].recv_time; + + auto timediff_YO_2_1 = msg_recv[2].recv_time - msg_recv[1].recv_time; + auto timediff_YO_4_2 = msg_recv[4].recv_time - msg_recv[2].recv_time; + auto timediff_YO_6_4 = msg_recv[6].recv_time - msg_recv[4].recv_time; + auto timediff_YO_8_6 = msg_recv[8].recv_time - msg_recv[6].recv_time; + + std::ostringstream stringStreamHi; + stringStreamHi << "HiTimes: " << timediff_HI_3_0 << ", " << timediff_HI_5_3 << ", " << timediff_HI_7_5 << std::endl; + Logger::WriteMessage(stringStreamHi.str().c_str()); + + std::ostringstream stringStreamYo; + stringStreamYo << "HiTimes: " << timediff_YO_2_1 << ", " << timediff_YO_4_2 << ", " << timediff_YO_6_4 << ", " << timediff_YO_8_6 << std::endl; + Logger::WriteMessage(stringStreamYo.str().c_str()); + + Assert::IsTrue(timediff_HI_3_0 > 90000); + Assert::IsTrue(timediff_HI_3_0 < 110000); + Assert::IsTrue(timediff_HI_5_3 > 90000); + Assert::IsTrue(timediff_HI_5_3 < 110000); + Assert::IsTrue(timediff_HI_7_5 > 90000); + Assert::IsTrue(timediff_HI_7_5 < 110000); + + Assert::IsTrue(timediff_YO_2_1 > 80000-10000); + Assert::IsTrue(timediff_YO_2_1 < 80000+1000); + Assert::IsTrue(timediff_YO_4_2 > 80000 - 10000); + Assert::IsTrue(timediff_YO_4_2 < 80000 + 10000); + Assert::IsTrue(timediff_YO_6_4 > 80000 - 10000); + Assert::IsTrue(timediff_YO_6_4 < 80000 + 10000); + Assert::IsTrue(timediff_YO_8_6 > 80000 - 10000); + Assert::IsTrue(timediff_YO_8_6 < 80000 + 10000); + + msg_recv = panda_recv_loop(p, 0, 300); + } + + TEST_METHOD(J2534_CAN_PeriodicMessageStartStop_Loopback) + { + auto chanid = J2534_open_and_connect("", CAN, 0, 500000, LINE_INFO()); + write_ioctl(chanid, LOOPBACK, TRUE, LINE_INFO()); // ENABLE J2534 ECHO/LOOPBACK + auto p = getPanda(500); + auto msgid = J2534_start_periodic_msg_checked(chanid, CAN, 0, 6, 0, "\x0\x0\x3\xAB""HI", 100, LINE_INFO()); + + std::vector msg_recv = panda_recv_loop(p, 3, 250); + Assert::AreEqual(STATUS_NOERROR, PassThruStopPeriodicMsg(chanid, msgid), _T("Failed to delete filter."), LINE_INFO()); + check_panda_can_msg(msg_recv[0], 0, 0x3AB, FALSE, FALSE, "HI", LINE_INFO()); + check_panda_can_msg(msg_recv[1], 0, 0x3AB, FALSE, FALSE, "HI", LINE_INFO()); + check_panda_can_msg(msg_recv[2], 0, 0x3AB, FALSE, FALSE, "HI", LINE_INFO()); + + auto j2534_msg_recv = j2534_recv_loop(chanid, 3); + check_J2534_can_msg(j2534_msg_recv[0], CAN, TX_MSG_TYPE, 0, 6, 0, "\x0\x0\x3\xAB""HI", LINE_INFO()); + check_J2534_can_msg(j2534_msg_recv[1], CAN, TX_MSG_TYPE, 0, 6, 0, "\x0\x0\x3\xAB""HI", LINE_INFO()); + check_J2534_can_msg(j2534_msg_recv[2], CAN, TX_MSG_TYPE, 0, 6, 0, "\x0\x0\x3\xAB""HI", LINE_INFO()); + + auto timediff_1_0 = j2534_msg_recv[1].Timestamp - j2534_msg_recv[0].Timestamp; + auto timediff_2_1 = j2534_msg_recv[2].Timestamp - j2534_msg_recv[1].Timestamp; + + std::ostringstream stringStream1; + stringStream1 << "times1: " << timediff_1_0 << ", " << timediff_2_1 << std::endl; + Logger::WriteMessage(stringStream1.str().c_str()); + + Assert::IsTrue(timediff_1_0 > 90000); + Assert::IsTrue(timediff_1_0 < 110000); + Assert::IsTrue(timediff_2_1 > 90000); + Assert::IsTrue(timediff_2_1 < 110000); + + msg_recv = panda_recv_loop(p, 0, 300); + } + + TEST_METHOD(J2534_CAN_PeriodicMessageWithTx) + { + auto chanid = J2534_open_and_connect("", CAN, 0, 500000, LINE_INFO()); + auto p = getPanda(500); + auto msgid = J2534_start_periodic_msg_checked(chanid, CAN, 0, 6, 0, "\x0\x0\x3\xAB""HI", 100, LINE_INFO()); + + J2534_send_msg(chanid, CAN, 0, 0, 0, 7, 0, "\x0\x0\x3\xAB""LOL"); + + std::vector msg_recv = panda_recv_loop(p, 4, 250); + Assert::AreEqual(STATUS_NOERROR, PassThruStopPeriodicMsg(chanid, msgid), _T("Failed to delete filter."), LINE_INFO()); + check_panda_can_msg(msg_recv[0], 0, 0x3AB, FALSE, FALSE, "HI", LINE_INFO()); + check_panda_can_msg(msg_recv[1], 0, 0x3AB, FALSE, FALSE, "LOL", LINE_INFO());//Staggered write inbetween multiple scheduled TXs + check_panda_can_msg(msg_recv[2], 0, 0x3AB, FALSE, FALSE, "HI", LINE_INFO()); + check_panda_can_msg(msg_recv[3], 0, 0x3AB, FALSE, FALSE, "HI", LINE_INFO()); + + auto timediff_2_0 = msg_recv[2].recv_time - msg_recv[0].recv_time; + auto timediff_3_2 = msg_recv[3].recv_time - msg_recv[2].recv_time; + + std::ostringstream stringStream1; + stringStream1 << "times1: " << timediff_2_0 << ", " << timediff_3_2 << std::endl; + Logger::WriteMessage(stringStream1.str().c_str()); + + Assert::IsTrue(timediff_2_0 > 90000); + Assert::IsTrue(timediff_2_0 < 110000); + Assert::IsTrue(timediff_3_2 > 90000); + Assert::IsTrue(timediff_3_2 < 110000); + + msg_recv = panda_recv_loop(p, 0, 300); + } + + TEST_METHOD(J2534_CAN_BaudInvalid) + { + unsigned long chanid; + Assert::AreEqual(STATUS_NOERROR, open_dev(""), _T("Failed to open device."), LINE_INFO()); + Assert::AreEqual(ERR_INVALID_BAUDRATE, PassThruConnect(devid, CAN, 0, 6000000, &chanid), _T("Baudrate should have been invalid."), LINE_INFO()); + Assert::AreEqual(ERR_INVALID_BAUDRATE, PassThruConnect(devid, CAN, 0, 200, &chanid), _T("Baudrate should have been invalid."), LINE_INFO()); + Assert::AreEqual(ERR_INVALID_BAUDRATE, PassThruConnect(devid, CAN, 0, 250010, &chanid), _T("Baudrate should have been invalid."), LINE_INFO()); + } + + bool didopen = FALSE; + unsigned long devid; + + unsigned long open_dev(const char* name, long assert_err = STATUS_NOERROR, TCHAR* failmsg = _T("Failed to open device.")) { + unsigned int res = PassThruOpen((void*)name, &devid); + if (res == STATUS_NOERROR) didopen = TRUE; + return res; + } + + unsigned long J2534_open_and_connect(const char* name, unsigned long ProtocolID, unsigned long Flags, unsigned long bps, const __LineInfo* pLineInfo = NULL) { + unsigned long chanid; + Assert::AreEqual(STATUS_NOERROR, open_dev(name), _T("Failed to open device."), pLineInfo); + Assert::AreEqual(STATUS_NOERROR, PassThruConnect(devid, ProtocolID, Flags, bps, &chanid), _T("Failed to open channel."), pLineInfo); + write_ioctl(chanid, LOOPBACK, FALSE, LINE_INFO()); // DISABLE J2534 ECHO/LOOPBACK + return chanid; + } + + }; + + TEST_CLASS(J2534DeviceISO15765) + { + public: + + TEST_METHOD_INITIALIZE(init) { + LoadJ2534Dll("pandaJ2534_0404_32.dll"); + } + + TEST_METHOD_CLEANUP(deinit) { + if (didopen) { + PassThruClose(devid); + didopen = FALSE; + } + UnloadJ2534Dll(); + } + + //Test that the BAUD rate of a ISO15765 connection can be changed. + TEST_METHOD(J2534_ISO15765_SetBaud) + { + auto chanid = J2534_open_and_connect("", ISO15765, 0, 500000, LINE_INFO()); + write_ioctl(chanid, LOOPBACK, TRUE, LINE_INFO()); // ENABLE J2534 ECHO/LOOPBACK + auto p = getPanda(250); + + J2534_send_msg_checked(chanid, ISO15765, 0, 0, 0, 4 + 2, 0, "\x0\x0\x3\xAB""HI", LINE_INFO()); + j2534_recv_loop(chanid, 0); + panda_recv_loop(p, 0); + + write_ioctl(chanid, DATA_RATE, 250000, LINE_INFO()); + + auto j2534_msg_recv = j2534_recv_loop(chanid, 2); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, TX_INDICATION, 0, 4, 0, "\x0\x0\x3\xAB", LINE_INFO()); + check_J2534_can_msg(j2534_msg_recv[1], ISO15765, TX_MSG_TYPE, 0, 4 + 2, 0, "\x0\x0\x3\xAB""HI", LINE_INFO()); + auto panda_msg_recv = panda_recv_loop(p, 1); + check_panda_can_msg(panda_msg_recv[0], 0, 0x3AB, FALSE, FALSE, "\x2""HI", LINE_INFO()); + } + + ///////////////////// Tests checking things don't send/receive ///////////////////// + + //Check tx PASSES and rx FAIL WITHOUT a filter. 29 bit. NO Filter. NoPadding. STD address. Single Frame. + TEST_METHOD(J2534_ISO15765_PassTxFailRx_29b_NoFilter_NoPad_STD_SF) + { + auto chanid = J2534_open_and_connect("", ISO15765, CAN_29BIT_ID, 500000, LINE_INFO()); + auto p = getPanda(500); + + //TX: works because all single frame writes should work (with or without a flow contorl filter) + J2534_send_msg_checked(chanid, ISO15765, 0, CAN_29BIT_ID, 0, 11, 0, "\x18\xda\xef\xf1""TX_TEST", LINE_INFO()); + auto j2534_msg_recv = j2534_recv_loop(chanid, 1); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, CAN_29BIT_ID | TX_INDICATION, 0, 4, 0, "\x18\xda\xef\xf1", LINE_INFO()); + + auto panda_msg_recv = panda_recv_loop(p, 1); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x07""TX_TEST", LINE_INFO()); + + //RX: Reads require a flow control filter, and should fail without one. + checked_panda_send(p, 0x18DAF1EF, TRUE, "\x06\x41\x00\xff\xff\xff\xfe", 7, 0, LINE_INFO()); + j2534_recv_loop(chanid, 0); + } + + //Check tx and rx FAIL WITHOUT a filter. 29 bit. NO Filter. NoPadding. STD address. First Frame. + TEST_METHOD(J2534_ISO15765_FailTxRx_29b_NoFilter_NoPad_STD_FF) + { + auto chanid = J2534_open_and_connect("", ISO15765, CAN_29BIT_ID, 500000, LINE_INFO()); + auto p = getPanda(500); + + //TX + Assert::AreEqual(ERR_NO_FLOW_CONTROL, J2534_send_msg(chanid, ISO15765, 0, CAN_29BIT_ID, 0, 12, 0, "\x18\xda\xef\xf1\xA1\xB2\xC3\xD4\xE5\xF6\x09\x1A"), + _T("Should fail to tx without a filter."), LINE_INFO()); + j2534_recv_loop(chanid, 0); + panda_recv_loop(p, 0); + + //RX; Send full response and check didn't receive flow control from J2534 device + checked_panda_send(p, 0x18DAF1EF, TRUE, "\x10\x14\x49\x02\x01""1D4", 8, 0, LINE_INFO()); + checked_panda_send(p, 0x18DAF1EF, TRUE, "\x21""GP00R55", 8, 0, LINE_INFO()); + checked_panda_send(p, 0x18DAF1EF, TRUE, "\x22""B123456", 8, 0, LINE_INFO()); + j2534_recv_loop(chanid, 0);//Check a full message is not accepted. + } + + //Check tx PASSES and rx FAIL with a MISMATCHED filter. 29 bit. Mismatch Filter. NoPadding. STD address. Single Frame. + TEST_METHOD(J2534_ISO15765_PassTxFailRx_29b_MismatchFilter_NoPad_STD_SF) + { + auto chanid = J2534_open_and_connect("", ISO15765, CAN_29BIT_ID, 500000, LINE_INFO()); + J2534_set_flowctrl_filter(chanid, CAN_29BIT_ID, 4, "\xff\xff\xff\xff", "\x18\xda\xf1\xef", "\x18\xda\xef\xf1", LINE_INFO()); + auto p = getPanda(500); + + //TX: works because all single frame writes should work (with or without a flow contorl filter) + J2534_send_msg_checked(chanid, ISO15765, 0, CAN_29BIT_ID, 0, 6, 0, "\x18\xda\xe0\xf1""\x11\x22", LINE_INFO()); + auto j2534_msg_recv = j2534_recv_loop(chanid, 1); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, CAN_29BIT_ID | TX_INDICATION, 0, 4, 0, "\x18\xda\xe0\xf1", LINE_INFO()); + + auto panda_msg_recv = panda_recv_loop(p, 1); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAE0F1, TRUE, FALSE, "\x02""\x11\x22", LINE_INFO()); + + //RX. Send ISO15765 single frame to device. Address still doesn't match filter, so should not be received. + checked_panda_send(p, 0x18DAF1E0, TRUE, "\x06\x41\x00\xff\xff\xff\xfe", 7, 0, LINE_INFO()); + j2534_recv_loop(chanid, 0); + } + + //Check tx and rx FAIL with a MISMATCHED filter. 29 bit. Mismatch Filter. NoPadding. STD address. First Frame. + TEST_METHOD(J2534_ISO15765_FailTxRx_29b_MismatchFilter_NoPad_STD_FF) + { + auto chanid = J2534_open_and_connect("", ISO15765, CAN_29BIT_ID, 500000, LINE_INFO()); + J2534_set_flowctrl_filter(chanid, CAN_29BIT_ID, 4, "\xff\xff\xff\xff", "\x18\xda\xf1\xef", "\x18\xda\xef\xf1", LINE_INFO()); + auto p = getPanda(500); + + //TX + Assert::AreEqual(ERR_NO_FLOW_CONTROL, J2534_send_msg(chanid, ISO15765, 0, CAN_29BIT_ID, 0, 12, 0, "\x18\xda\xe0\xf1""USELESS STUFF"), + _T("Should fail to tx without a filter."), LINE_INFO()); + j2534_recv_loop(chanid, 0); + panda_recv_loop(p, 0); + + //RX; Send a full response and check didn't receive flow control from J2534 device + checked_panda_send(p, 0x18DAF1E0, TRUE, "\x10\x14\x49\x02\x01""1D4", 8, 0, LINE_INFO()); + checked_panda_send(p, 0x18DAF1E0, TRUE, "\x21""GP00R55", 8, 0, LINE_INFO()); + checked_panda_send(p, 0x18DAF1E0, TRUE, "\x22""B123456", 8, 0, LINE_INFO()); + j2534_recv_loop(chanid, 0);//Check a full message is not accepted. + } + + //Check tx FAILS with a MISMATCHED filter 29bit flag. 29 bit. Mismatch Filter. NoPadding. STD address. Single Frame. + TEST_METHOD(J2534_ISO15765_FailTxRx_29b_MismatchFilterFlag29b_NoPad_STD_SF) + { + auto chanid = J2534_open_and_connect("", ISO15765, CAN_29BIT_ID, 500000, LINE_INFO()); + J2534_set_flowctrl_filter(chanid, CAN_29BIT_ID, 4, "\xff\xff\xff\xff", "\x0\x0\x1\xab", "\x0\x0\x1\xcd", LINE_INFO()); + auto p = getPanda(500); + + //TX + Assert::AreEqual(ERR_INVALID_MSG, J2534_send_msg(chanid, ISO15765, 0, 0, 0, 6, 0, "\x0/x0/x1/xcd\x01\x00"), + _T("mismatched address should fail to tx."), LINE_INFO()); + j2534_recv_loop(chanid, 0); + panda_recv_loop(p, 0); + + //RX. Send ISO15765 single frame to device. Address still doesn't match filter, so should not be received. + checked_panda_send(p, 0x1ab, FALSE, "\x06\x41\x00\xff\xff\xff\xfe", 7, 0, LINE_INFO()); + j2534_recv_loop(chanid, 0); + } + + ///////////////////// Tests checking things actually send/receive. Standard Addressing ///////////////////// + + //Check rx passes with filter. 29 bit. Good Filter. NoPadding. STD address. Single Frame. + TEST_METHOD(J2534_ISO15765_SuccessRx_29b_Filter_NoPad_STD_SF) + { + auto chanid = J2534_open_and_connect("", ISO15765, CAN_29BIT_ID, 500000, LINE_INFO()); + J2534_set_flowctrl_filter(chanid, CAN_29BIT_ID, 4, "\xff\xff\xff\xff", "\x18\xda\xf1\xef", "\x18\xda\xef\xf1", LINE_INFO()); + auto p = getPanda(500); + + checked_panda_send(p, 0x18DAF1EF, TRUE, "\x07""ABCD123", 8, 0, LINE_INFO()); + + auto j2534_msg_recv = j2534_recv_loop(chanid, 1); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, CAN_29BIT_ID, 0, 11, 11, "\x18\xda\xf1\xef""ABCD123", LINE_INFO()); + } + + //Check tx passes with filter. 29 bit. Good Filter. NoPadding. STD address. Single Frame. + TEST_METHOD(J2534_ISO15765_SuccessTx_29b_Filter_NoPad_STD_SF) + { + auto chanid = J2534_open_and_connect("", ISO15765, CAN_29BIT_ID, 500000, LINE_INFO()); + J2534_set_flowctrl_filter(chanid, CAN_29BIT_ID, 4, "\xff\xff\xff\xff", "\x18\xda\xf1\xef", "\x18\xda\xef\xf1", LINE_INFO()); + auto p = getPanda(500); + + J2534_send_msg_checked(chanid, ISO15765, 0, CAN_29BIT_ID, 0, 11, 0, "\x18\xda\xef\xf1""TX_TEST", LINE_INFO()); + auto j2534_msg_recv = j2534_recv_loop(chanid, 1); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, CAN_29BIT_ID | TX_INDICATION, 0, 4, 0, "\x18\xda\xef\xf1", LINE_INFO()); + + auto panda_msg_recv = panda_recv_loop(p, 1); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x07""TX_TEST", LINE_INFO()); + } + + //Check tx passes with filter. 29 bit. Good Filter. NoPadding. STD address. Single Frame. Loopback. + TEST_METHOD(J2534_ISO15765_SuccessTx_29b_Filter_NoPad_STD_SF_LOOPBACK) + { + auto chanid = J2534_open_and_connect("", ISO15765, CAN_29BIT_ID, 500000, LINE_INFO()); + J2534_set_flowctrl_filter(chanid, CAN_29BIT_ID, 4, "\xff\xff\xff\xff", "\x18\xda\xf1\xef", "\x18\xda\xef\xf1", LINE_INFO()); + write_ioctl(chanid, LOOPBACK, TRUE, LINE_INFO()); + auto p = getPanda(500); + + J2534_send_msg_checked(chanid, ISO15765, 0, CAN_29BIT_ID, 0, 11, 0, "\x18\xda\xef\xf1""TX_TEST", LINE_INFO()); + auto j2534_msg_recv = j2534_recv_loop(chanid, 2); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, CAN_29BIT_ID | TX_INDICATION, 0, 4, 0, "\x18\xda\xef\xf1", LINE_INFO()); + check_J2534_can_msg(j2534_msg_recv[1], ISO15765, CAN_29BIT_ID | TX_MSG_TYPE, 0, 11, 0, "\x18\xda\xef\xf1""TX_TEST", LINE_INFO()); + + auto panda_msg_recv = panda_recv_loop(p, 1); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x07""TX_TEST", LINE_INFO()); + } + + //Check rx passes with filter. 29 bit. Good Filter. NoPadding. STD address. Multi Frame. + TEST_METHOD(J2534_ISO15765_SuccessRx_29b_Filter_NoPad_STD_FFCF) + { + auto chanid = J2534_open_and_connect("", ISO15765, CAN_29BIT_ID, 500000, LINE_INFO()); + J2534_set_flowctrl_filter(chanid, CAN_29BIT_ID, 4, "\xff\xff\xff\xff", "\x18\xda\xf1\xef", "\x18\xda\xef\xf1", LINE_INFO()); + auto p = getPanda(500); + + //Send first frame, then check we get a flow control frame + auto panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x10\x13""ninete", 8, 1, LINE_INFO()); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, std::string("\x30\x00\x00", 3), LINE_INFO()); + + //Check first frame is registered with J2534 + auto j2534_msg_recv = j2534_recv_loop(chanid, 1); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, CAN_29BIT_ID | START_OF_MESSAGE, 0, 4, 0, "\x18\xda\xf1\xef", LINE_INFO()); + + //Send the rest of the message + checked_panda_send(p, 0x18DAF1EF, TRUE, "\x21""en byte", 8, 0, LINE_INFO()); + checked_panda_send(p, 0x18DAF1EF, TRUE, "\x22""s here", 7, 0, LINE_INFO()); + + //Check J2534 constructed the whole message + j2534_msg_recv = j2534_recv_loop(chanid, 1); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, CAN_29BIT_ID, 0, 4 + 0x13, 4 + 0x13, "\x18\xda\xf1\xef""nineteen bytes here", LINE_INFO()); + } + + //Check multi frame tx passes with filter. 29 bit. Good Filter. NoPadding. STD address. Multi Frame. + TEST_METHOD(J2534_ISO15765_SuccessTx_29b_Filter_NoPad_STD_FFCF) + { + auto chanid = J2534_open_and_connect("", ISO15765, CAN_29BIT_ID, 500000, LINE_INFO()); + J2534_set_flowctrl_filter(chanid, CAN_29BIT_ID, 4, "\xff\xff\xff\xff", "\x18\xda\xf1\xef", "\x18\xda\xef\xf1", LINE_INFO()); + auto p = getPanda(500); + + J2534_send_msg_checked(chanid, ISO15765, 0, CAN_29BIT_ID, 0, 14, 0, "\x18\xda\xef\xf1""\xAA\xBB\xCC\xDD\xEE\xFF\x11\x22\x33\x44", LINE_INFO()); + auto j2534_msg_recv = j2534_recv_loop(chanid, 0); // No TxDone msg until after the final tx frame is sent + + auto panda_msg_recv = panda_recv_loop(p, 1); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x10\x0A""\xAA\xBB\xCC\xDD\xEE\xFF", LINE_INFO()); + + panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x30\x0\x0", 3, 1, LINE_INFO()); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x21""\x11\x22\x33\x44", LINE_INFO()); + + j2534_msg_recv = j2534_recv_loop(chanid, 1); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, CAN_29BIT_ID | TX_INDICATION, 0, 4, 0, "\x18\xda\xef\xf1", LINE_INFO()); + } + + //Check rx passes with filter. 11 bit. Good Filter. NoPadding. STD address. Single Frame. + TEST_METHOD(J2534_ISO15765_SuccessRx_11b_Filter_NoPad_STD_SF) + { + auto chanid = J2534_open_and_connect("", ISO15765, 0, 500000, LINE_INFO()); + J2534_set_flowctrl_filter(chanid, 0, 4, "\xff\xff\xff\xff", "\x0\x0\x1\xab", "\x0\x0\x1\xcd", LINE_INFO()); + auto p = getPanda(500); + + checked_panda_send(p, 0x1ab, FALSE, "\x07""ABCD123", 8, 0, LINE_INFO()); + + auto j2534_msg_recv = j2534_recv_loop(chanid, 1); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, 0, 0, 11, 11, "\x0\x0\x1\xab""ABCD123", LINE_INFO()); + } + + //Check tx passes with filter. 11 bit. Good Filter. NoPadding. STD address. Single Frame. + TEST_METHOD(J2534_ISO15765_SuccessTx_11b_Filter_NoPad_STD_SF) + { + auto chanid = J2534_open_and_connect("", ISO15765, 0, 500000, LINE_INFO()); + J2534_set_flowctrl_filter(chanid, 0, 4, "\xff\xff\xff\xff", "\x0\x0\x1\xab", "\x0\x0\x1\xcd", LINE_INFO()); + auto p = getPanda(500); + + J2534_send_msg_checked(chanid, ISO15765, 0, 0, 0, 11, 0, "\x0\x0\x1\xcd""TX_TEST", LINE_INFO()); + auto j2534_msg_recv = j2534_recv_loop(chanid, 1); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, TX_INDICATION, 0, 4, 0, "\x0\x0\x1\xcd", LINE_INFO()); + + auto panda_msg_recv = panda_recv_loop(p, 1); + check_panda_can_msg(panda_msg_recv[0], 0, 0x1CD, FALSE, FALSE, "\x07""TX_TEST", LINE_INFO()); + } + + //Check tx passes with filter multiple times. 29 bit. Good Filter. NoPadding. STD address. Multiple Single Frames. + TEST_METHOD(J2534_ISO15765_SuccessTx_29b_Filter_NoPad_STD_MultipleSF) + { + auto chanid = J2534_open_and_connect("", ISO15765, CAN_29BIT_ID, 500000, LINE_INFO()); + J2534_set_flowctrl_filter(chanid, CAN_29BIT_ID, 4, "\xff\xff\xff\xff", "\x18\xda\xf1\xef", "\x18\xda\xef\xf1", LINE_INFO()); + write_ioctl(chanid, LOOPBACK, TRUE, LINE_INFO()); + auto p = getPanda(500); + + J2534_send_msg_checked(chanid, ISO15765, 0, CAN_29BIT_ID, 0, 11, 0, "\x18\xda\xef\xf1""TX_TEST", LINE_INFO()); + J2534_send_msg_checked(chanid, ISO15765, 0, CAN_29BIT_ID, 0, 9, 0, "\x18\xda\xef\xf1""HELLO", LINE_INFO()); + auto j2534_msg_recv = j2534_recv_loop(chanid, 4); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, CAN_29BIT_ID | TX_INDICATION, 0, 4, 0, "\x18\xda\xef\xf1", LINE_INFO()); + check_J2534_can_msg(j2534_msg_recv[1], ISO15765, CAN_29BIT_ID | TX_MSG_TYPE, 0, 11, 0, "\x18\xda\xef\xf1""TX_TEST", LINE_INFO()); + check_J2534_can_msg(j2534_msg_recv[2], ISO15765, CAN_29BIT_ID | TX_INDICATION, 0, 4, 0, "\x18\xda\xef\xf1", LINE_INFO()); + check_J2534_can_msg(j2534_msg_recv[3], ISO15765, CAN_29BIT_ID | TX_MSG_TYPE, 0, 9, 0, "\x18\xda\xef\xf1""HELLO", LINE_INFO()); + + auto panda_msg_recv = panda_recv_loop(p, 2); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x07""TX_TEST", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[1], 0, 0x18DAEFF1, TRUE, FALSE, "\x05""HELLO", LINE_INFO()); + } + + //Check that receiver's flow control block size requests are respected. 29 bit. Good Filter. NoPadding. STD address. Multiple Frames with multiple flow control. + TEST_METHOD(J2534_ISO15765_SuccessTx_29b_Filter_NoPad_STD_MF_FLOWCONTROLBlockSize) + { + auto chanid = J2534_open_and_connect("", ISO15765, CAN_29BIT_ID, 500000, LINE_INFO()); + J2534_set_flowctrl_filter(chanid, CAN_29BIT_ID, 4, "\xff\xff\xff\xff", "\x18\xda\xf1\xef", "\x18\xda\xef\xf1", LINE_INFO()); + auto p = getPanda(500); + + J2534_send_msg_checked(chanid, ISO15765, 0, CAN_29BIT_ID, 0, 4 + 52, 0, "\x18\xda\xef\xf1""AABBCCDDEEFFGGHHIIJJKKLLMMNNOOPPQQRRSSTTUUVVWWXXYYZZ", LINE_INFO()); + + auto panda_msg_recv = panda_recv_loop(p, 1); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x10\x34""AABBCC", LINE_INFO()); + + // [flow_status, block_size, st_min] + panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x30\x01\x00", 3, 1, LINE_INFO()); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x21""DDEEFFG", LINE_INFO()); + + panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x30\x02\x00", 3, 2, LINE_INFO()); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x22""GHHIIJJ", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[1], 0, 0x18DAEFF1, TRUE, FALSE, "\x23""KKLLMMN", LINE_INFO()); + + panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x30\x01\x00", 3, 1, LINE_INFO()); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x24""NOOPPQQ", LINE_INFO()); + + panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x30\x00\x00", 3, 3, LINE_INFO()); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x25""RRSSTTU", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[1], 0, 0x18DAEFF1, TRUE, FALSE, "\x26""UVVWWXX", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[2], 0, 0x18DAEFF1, TRUE, FALSE, "\x27""YYZZ", LINE_INFO()); + + auto j2534_msg_recv = j2534_recv_loop(chanid, 1); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, CAN_29BIT_ID | TX_INDICATION, 0, 4, 0, "\x18\xda\xef\xf1", LINE_INFO()); + } + + //Check that receiver's flow control separation time requests are respected. 29 bit. Good Filter. NoPadding. STD address. Multiple Frames with multiple flow control. + TEST_METHOD(J2534_ISO15765_SuccessTx_29b_Filter_NoPad_STD_MF_FLOWCONTROLSTMinMultiFc) + { + auto chanid = J2534_open_and_connect("", ISO15765, CAN_29BIT_ID, 500000, LINE_INFO()); + J2534_set_flowctrl_filter(chanid, CAN_29BIT_ID, 4, "\xff\xff\xff\xff", "\x18\xda\xf1\xef", "\x18\xda\xef\xf1", LINE_INFO()); + auto p = getPanda(500); + + J2534_send_msg_checked(chanid, ISO15765, 0, CAN_29BIT_ID, 0, 4 + 52, 0, "\x18\xda\xef\xf1""AABBCCDDEEFFGGHHIIJJKKLLMMNNOOPPQQRRSSTTUUVVWWXXYYZZ", LINE_INFO()); + + auto panda_msg_recv = panda_recv_loop(p, 1); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x10\x34""AABBCC", LINE_INFO()); + + // [flow_status, block_size, st_min] + panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x30\x03\x0A", 3, 3, LINE_INFO()); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x21""DDEEFFG", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[1], 0, 0x18DAEFF1, TRUE, FALSE, "\x22""GHHIIJJ", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[2], 0, 0x18DAEFF1, TRUE, FALSE, "\x23""KKLLMMN", LINE_INFO()); + auto timediff0_1_0 = panda_msg_recv[1].recv_time - panda_msg_recv[0].recv_time; + auto timediff0_2_1 = panda_msg_recv[2].recv_time - panda_msg_recv[1].recv_time; + + std::ostringstream stringStream0; + stringStream0 << "times0: " << timediff0_1_0 << ", " << timediff0_2_1 << std::endl; + Logger::WriteMessage(stringStream0.str().c_str()); + + Assert::IsTrue(timediff0_1_0 > 10000); + Assert::IsTrue(timediff0_1_0 < 32000);//Flexible, but trying to make sure things don't just all lag for a second or something + Assert::IsTrue(timediff0_2_1 > 10000); + Assert::IsTrue(timediff0_2_1 < 32000); + + panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x30\x04\x20", 3, 4, LINE_INFO(), 500); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x24""NOOPPQQ", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[1], 0, 0x18DAEFF1, TRUE, FALSE, "\x25""RRSSTTU", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[2], 0, 0x18DAEFF1, TRUE, FALSE, "\x26""UVVWWXX", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[3], 0, 0x18DAEFF1, TRUE, FALSE, "\x27""YYZZ", LINE_INFO()); + auto timediff1_1_0 = panda_msg_recv[1].recv_time - panda_msg_recv[0].recv_time; + auto timediff1_2_1 = panda_msg_recv[2].recv_time - panda_msg_recv[1].recv_time; + auto timediff1_3_2 = panda_msg_recv[3].recv_time - panda_msg_recv[2].recv_time; + + std::ostringstream stringStream1; + stringStream1 << "times1: " << timediff1_1_0 << ", " << timediff1_2_1 << ", " << timediff1_3_2 << std::endl; + Logger::WriteMessage(stringStream1.str().c_str()); + + Assert::IsTrue(timediff1_1_0 > 32000); + Assert::IsTrue(timediff1_2_1 > 32000); + Assert::IsTrue(timediff1_3_2 > 32000); + + auto j2534_msg_recv = j2534_recv_loop(chanid, 1); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, CAN_29BIT_ID | TX_INDICATION, 0, 4, 0, "\x18\xda\xef\xf1", LINE_INFO()); + } + + //Check that receiver's flow control separation time requests are respected 2. 29 bit. Good Filter. NoPadding. STD address. Multiple Frames with one flow control. + TEST_METHOD(J2534_ISO15765_SuccessTx_29b_Filter_NoPad_STD_MF_FLOWCONTROLSTMinSingleFc) + { + auto chanid = J2534_open_and_connect("", ISO15765, CAN_29BIT_ID, 500000, LINE_INFO()); + J2534_set_flowctrl_filter(chanid, CAN_29BIT_ID, 4, "\xff\xff\xff\xff", "\x18\xda\xf1\xef", "\x18\xda\xef\xf1", LINE_INFO()); + auto p = getPanda(500); + + J2534_send_msg_checked(chanid, ISO15765, 0, CAN_29BIT_ID, 0, 4 + 52, 0, "\x18\xda\xef\xf1""AABBCCDDEEFFGGHHIIJJKKLLMMNNOOPPQQRRSSTTUUVVWWXXYYZZ", LINE_INFO()); + + auto panda_msg_recv = panda_recv_loop(p, 1); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x10\x34""AABBCC", LINE_INFO()); + + // [flow_status, block_size, st_min] + panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x30\x07\x0A", 3, 7, LINE_INFO(), 500); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x21""DDEEFFG", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[1], 0, 0x18DAEFF1, TRUE, FALSE, "\x22""GHHIIJJ", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[2], 0, 0x18DAEFF1, TRUE, FALSE, "\x23""KKLLMMN", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[3], 0, 0x18DAEFF1, TRUE, FALSE, "\x24""NOOPPQQ", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[4], 0, 0x18DAEFF1, TRUE, FALSE, "\x25""RRSSTTU", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[5], 0, 0x18DAEFF1, TRUE, FALSE, "\x26""UVVWWXX", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[6], 0, 0x18DAEFF1, TRUE, FALSE, "\x27""YYZZ", LINE_INFO()); + + auto timediff_1_0 = panda_msg_recv[1].recv_time - panda_msg_recv[0].recv_time; + auto timediff_2_1 = panda_msg_recv[2].recv_time - panda_msg_recv[1].recv_time; + auto timediff_3_2 = panda_msg_recv[3].recv_time - panda_msg_recv[2].recv_time; + auto timediff_4_3 = panda_msg_recv[4].recv_time - panda_msg_recv[3].recv_time; + auto timediff_5_4 = panda_msg_recv[5].recv_time - panda_msg_recv[4].recv_time; + auto timediff_6_5 = panda_msg_recv[6].recv_time - panda_msg_recv[5].recv_time; + + std::ostringstream stringStream1; + stringStream1 << "times1: " << timediff_1_0 << ", " << timediff_2_1 << ", " << timediff_3_2 << + ", " << timediff_4_3 << ", " << timediff_5_4 << ", " << timediff_6_5 << std::endl; + Logger::WriteMessage(stringStream1.str().c_str()); + + Assert::IsTrue(timediff_1_0 > 10000); + Assert::IsTrue(timediff_2_1 > 10000); + Assert::IsTrue(timediff_3_2 > 10000); + Assert::IsTrue(timediff_4_3 > 10000); + Assert::IsTrue(timediff_5_4 > 10000); + Assert::IsTrue(timediff_6_5 > 10000); + } + + //Check that tx works for messages with more than 16 frames. 29 bit. Good Filter. NoPadding. STD address. Large multiframe message. + TEST_METHOD(J2534_ISO15765_SuccessTx_29b_Filter_NoPad_STD_MF_LotsOfFrames) + { + auto chanid = J2534_open_and_connect("", ISO15765, CAN_29BIT_ID, 500000, LINE_INFO()); + J2534_set_flowctrl_filter(chanid, CAN_29BIT_ID, 4, "\xff\xff\xff\xff", "\x18\xda\xf1\xef", "\x18\xda\xef\xf1", LINE_INFO()); + auto p = getPanda(500); + + J2534_send_msg_checked(chanid, ISO15765, 0, CAN_29BIT_ID, 0, 4 + 125, 0, + "\x18\xda\xef\xf1" + "AABBCC""DDEEFFG""GHHIIJJ""KKLLMMN""NOOPPQQ""RRSSTTU""UVVWWXX""YYZZ112""2334455""6677889" + "900abcd""efghijk""lmnopqr""stuvwxy""z!@#$%^""&*()_+-""=`~ABCD""EFGHIJK", LINE_INFO()); + + auto panda_msg_recv = panda_recv_loop(p, 1); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x10\x7D""AABBCC", LINE_INFO()); + + // [flow_status, block_size, st_min] + panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x30\x00\x00", 3, 17, LINE_INFO(), 1000); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x21""DDEEFFG", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[1], 0, 0x18DAEFF1, TRUE, FALSE, "\x22""GHHIIJJ", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[2], 0, 0x18DAEFF1, TRUE, FALSE, "\x23""KKLLMMN", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[3], 0, 0x18DAEFF1, TRUE, FALSE, "\x24""NOOPPQQ", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[4], 0, 0x18DAEFF1, TRUE, FALSE, "\x25""RRSSTTU", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[5], 0, 0x18DAEFF1, TRUE, FALSE, "\x26""UVVWWXX", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[6], 0, 0x18DAEFF1, TRUE, FALSE, "\x27""YYZZ112", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[7], 0, 0x18DAEFF1, TRUE, FALSE, "\x28""2334455", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[8], 0, 0x18DAEFF1, TRUE, FALSE, "\x29""6677889", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[9], 0, 0x18DAEFF1, TRUE, FALSE, "\x2A""900abcd", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[10], 0, 0x18DAEFF1, TRUE, FALSE, "\x2B""efghijk", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[11], 0, 0x18DAEFF1, TRUE, FALSE, "\x2C""lmnopqr", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[12], 0, 0x18DAEFF1, TRUE, FALSE, "\x2D""stuvwxy", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[13], 0, 0x18DAEFF1, TRUE, FALSE, "\x2E""z!@#$%^", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[14], 0, 0x18DAEFF1, TRUE, FALSE, "\x2F""&*()_+-", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[15], 0, 0x18DAEFF1, TRUE, FALSE, "\x20""=`~ABCD", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[16], 0, 0x18DAEFF1, TRUE, FALSE, "\x21""EFGHIJK", LINE_INFO()); + + auto j2534_msg_recv = j2534_recv_loop(chanid, 1); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, CAN_29BIT_ID | TX_INDICATION, 0, 4, 0, "\x18\xda\xef\xf1", LINE_INFO()); + } + + //Check tx passes with filter multiple times. 29 bit. Good Filter. NoPadding. STD address. Multiple Single Frames. + TEST_METHOD(J2534_ISO15765_SuccessTx_29b_Filter_NoPad_STD_MultipleMFSF) + { + auto chanid = J2534_open_and_connect("", ISO15765, CAN_29BIT_ID, 500000, LINE_INFO()); + J2534_set_flowctrl_filter(chanid, CAN_29BIT_ID, 4, "\xff\xff\xff\xff", "\x18\xda\xf1\xef", "\x18\xda\xef\xf1", LINE_INFO()); + write_ioctl(chanid, LOOPBACK, TRUE, LINE_INFO()); + auto p = getPanda(500); + + J2534_send_msg_checked(chanid, ISO15765, 0, CAN_29BIT_ID, 0, 4 + 23, 0, "\x18\xda\xef\xf1""Long data because I can", LINE_INFO()); + J2534_send_msg_checked(chanid, ISO15765, 0, CAN_29BIT_ID, 0, 9, 0, "\x18\xda\xef\xf1""HELLO", LINE_INFO()); + + auto panda_msg_recv = panda_recv_loop(p, 1); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x10\x17""Long d", LINE_INFO()); + + panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x30\x00\x00", 3, 4, LINE_INFO()); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x21""ata bec", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[1], 0, 0x18DAEFF1, TRUE, FALSE, "\x22""ause I ", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[2], 0, 0x18DAEFF1, TRUE, FALSE, "\x23""can", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[3], 0, 0x18DAEFF1, TRUE, FALSE, "\x05""HELLO", LINE_INFO()); + + auto j2534_msg_recv = j2534_recv_loop(chanid, 4); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, CAN_29BIT_ID | TX_INDICATION, 0, 4, 0, "\x18\xda\xef\xf1", LINE_INFO()); + check_J2534_can_msg(j2534_msg_recv[1], ISO15765, CAN_29BIT_ID | TX_MSG_TYPE, 0, 4 + 23, 0, "\x18\xda\xef\xf1""Long data because I can", LINE_INFO()); + check_J2534_can_msg(j2534_msg_recv[2], ISO15765, CAN_29BIT_ID | TX_INDICATION, 0, 4, 0, "\x18\xda\xef\xf1", LINE_INFO()); + check_J2534_can_msg(j2534_msg_recv[3], ISO15765, CAN_29BIT_ID | TX_MSG_TYPE, 0, 4 + 5, 0, "\x18\xda\xef\xf1""HELLO", LINE_INFO()); + } + + //Check tx passes after message timeout. 29 bit. Good Filter. NoPadding. STD address. Multiple Frame timeout then Single Frame. + TEST_METHOD(J2534_ISO15765_SuccessTx_29b_Filter_NoPad_STD_MFTimeoutSFSuccess) + { + auto chanid = J2534_open_and_connect("", ISO15765, CAN_29BIT_ID, 500000, LINE_INFO()); + J2534_set_flowctrl_filter(chanid, CAN_29BIT_ID, 4, "\xff\xff\xff\xff", "\x18\xda\xf1\xef", "\x18\xda\xef\xf1", LINE_INFO()); + write_ioctl(chanid, LOOPBACK, TRUE, LINE_INFO()); + auto p = getPanda(500); + + J2534_send_msg_checked(chanid, ISO15765, 0, CAN_29BIT_ID, 0, 4 + 23, 0, "\x18\xda\xef\xf1""Long data because I can", LINE_INFO()); + J2534_send_msg_checked(chanid, ISO15765, 0, CAN_29BIT_ID, 0, 9, 0, "\x18\xda\xef\xf1""HELLO", LINE_INFO()); + + auto panda_msg_recv = panda_recv_loop(p, 2, 1000); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x10\x17""Long d", LINE_INFO()); //First Frame. Not replying so it needs to time out. + check_panda_can_msg(panda_msg_recv[1], 0, 0x18DAEFF1, TRUE, FALSE, "\x05""HELLO", LINE_INFO()); //Reply to the next message. + + auto j2534_msg_recv = j2534_recv_loop(chanid, 2); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, CAN_29BIT_ID | TX_INDICATION, 0, 4, 0, "\x18\xda\xef\xf1", LINE_INFO()); + check_J2534_can_msg(j2534_msg_recv[1], ISO15765, CAN_29BIT_ID | TX_MSG_TYPE, 0, 4 + 5, 0, "\x18\xda\xef\xf1""HELLO", LINE_INFO()); + } + + //Check tx passes after mid-message timeout. 29 bit. Good Filter. NoPadding. STD address. Multiple Frame mid-timeout then Single Frame. + TEST_METHOD(J2534_ISO15765_SuccessTx_29b_Filter_NoPad_STD_MFMidTimeoutSFSuccess) + { + auto chanid = J2534_open_and_connect("", ISO15765, CAN_29BIT_ID, 500000, LINE_INFO()); + J2534_set_flowctrl_filter(chanid, CAN_29BIT_ID, 4, "\xff\xff\xff\xff", "\x18\xda\xf1\xef", "\x18\xda\xef\xf1", LINE_INFO()); + write_ioctl(chanid, LOOPBACK, TRUE, LINE_INFO()); + auto p = getPanda(500); + + J2534_send_msg_checked(chanid, ISO15765, 0, CAN_29BIT_ID, 0, 4 + 23, 0, "\x18\xda\xef\xf1""Long data because I can", LINE_INFO()); + J2534_send_msg_checked(chanid, ISO15765, 0, CAN_29BIT_ID, 0, 9, 0, "\x18\xda\xef\xf1""HELLO", LINE_INFO()); + + auto panda_msg_recv = panda_recv_loop(p, 1); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x10\x17""Long d", LINE_INFO()); //First Frame. Not replying so it needs to time out. + + panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x30\x01\x00", 3, 2, LINE_INFO(), 1000);//Start a conversation + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x21""ata bec", LINE_INFO());//Check passthru device sent more data, but don't reply to it + check_panda_can_msg(panda_msg_recv[1], 0, 0x18DAEFF1, TRUE, FALSE, "\x05""HELLO", LINE_INFO()); //Reply to the next message. + + auto j2534_msg_recv = j2534_recv_loop(chanid, 2); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, CAN_29BIT_ID | TX_INDICATION, 0, 4, 0, "\x18\xda\xef\xf1", LINE_INFO()); + check_J2534_can_msg(j2534_msg_recv[1], ISO15765, CAN_29BIT_ID | TX_MSG_TYPE, 0, 4 + 5, 0, "\x18\xda\xef\xf1""HELLO", LINE_INFO()); + } + + //Check slow tx passes without hitting FC timeout. 29 bit. Good Filter. NoPadding. STD address. Long STmin, catches if FC timeout applies before needed. + TEST_METHOD(J2534_ISO15765_SuccessTx_29b_Filter_NoPad_STD_SLOWMF) + { + auto chanid = J2534_open_and_connect("", ISO15765, CAN_29BIT_ID, 500000, LINE_INFO()); + J2534_set_flowctrl_filter(chanid, CAN_29BIT_ID, 4, "\xff\xff\xff\xff", "\x18\xda\xf1\xef", "\x18\xda\xef\xf1", LINE_INFO()); + write_ioctl(chanid, LOOPBACK, TRUE, LINE_INFO()); + auto p = getPanda(500); + + J2534_send_msg_checked(chanid, ISO15765, 0, CAN_29BIT_ID, 0, 4 + 48, 0, "\x18\xda\xef\xf1""AABBCCDDEEFFGGHHIIJJKKLLMMNNOOPPQQRRSSTTUUVVWWXX", LINE_INFO()); + + auto panda_msg_recv = panda_recv_loop(p, 1); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x10\x30""AABBCC", LINE_INFO()); + + panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x30\x06\x7F", 3, 6, LINE_INFO(), 3000);//Start a conversation... but slow. FC timeout is 250 ms. + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x21""DDEEFFG", LINE_INFO());//Check this convo doesn't trigger that timeout. + check_panda_can_msg(panda_msg_recv[1], 0, 0x18DAEFF1, TRUE, FALSE, "\x22""GHHIIJJ", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[2], 0, 0x18DAEFF1, TRUE, FALSE, "\x23""KKLLMMN", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[3], 0, 0x18DAEFF1, TRUE, FALSE, "\x24""NOOPPQQ", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[4], 0, 0x18DAEFF1, TRUE, FALSE, "\x25""RRSSTTU", LINE_INFO());//Some of these should fail to recv if there is an issue. + check_panda_can_msg(panda_msg_recv[5], 0, 0x18DAEFF1, TRUE, FALSE, "\x26""UVVWWXX", LINE_INFO()); + + auto j2534_msg_recv = j2534_recv_loop(chanid, 2); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, CAN_29BIT_ID | TX_INDICATION, 0, 4, 0, "\x18\xda\xef\xf1", LINE_INFO()); + check_J2534_can_msg(j2534_msg_recv[1], ISO15765, CAN_29BIT_ID | TX_MSG_TYPE, 0, 4 + 48, 0, "\x18\xda\xef\xf1""AABBCCDDEEFFGGHHIIJJKKLLMMNNOOPPQQRRSSTTUUVVWWXX", LINE_INFO()); + } + + //Check MF tx can be sent along side of a periodic message. 29 bit. Good Filter. NoPadding. STD address. Long STmin, checks that MF tx and periodic TX don't break each other. + TEST_METHOD(J2534_ISO15765_SuccessTx_29b_Filter_NoPad_STD_SLOWMF_WithPeriodicMsg) + { + auto chanid = J2534_open_and_connect("", ISO15765, CAN_29BIT_ID, 500000, LINE_INFO()); + J2534_set_flowctrl_filter(chanid, CAN_29BIT_ID, 4, "\xff\xff\xff\xff", "\x18\xda\xf1\xef", "\x18\xda\xef\xf1", LINE_INFO()); + write_ioctl(chanid, LOOPBACK, TRUE, LINE_INFO()); + auto p = getPanda(500); + + //Timing diagram of this test. + //* is a periodic msg transfer; F is first frame, L is Flow control, C is Consecutive Frame. + // *~~~~~~~*~~~~~~~*~~~~~~~* (The alignment here is unimportant. The exact order is not checked. + //F C----C----C----C----C----C (100 ms between Cs) + // L + + auto msgid = J2534_start_periodic_msg_checked(chanid, ISO15765, CAN_29BIT_ID, 6, 0, "\x18\xda\xef\xf1""HI", 130, LINE_INFO()); + J2534_send_msg_checked(chanid, ISO15765, 0, CAN_29BIT_ID, 0, 4 + 48, 0, "\x18\xda\xef\xf1""AABBCCDDEEFFGGHHIIJJKKLLMMNNOOPPQQRRSSTTUUVVWWXX", LINE_INFO()); + + auto panda_msg_recv = panda_recv_loop(p, 2); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x02""HI", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[1], 0, 0x18DAEFF1, TRUE, FALSE, "\x10\x30""AABBCC", LINE_INFO()); + + Assert::IsTrue(p->can_send(0x18DAF1EF, TRUE, (const uint8_t*)"\x30\x06\x64", 3, panda::PANDA_CAN1), _T("Panda send says it failed."), LINE_INFO()); + + Timer t_permsg = Timer(); + Timer t_MFmsg = Timer(); + unsigned int MFframesReceived = 0; + unsigned int PeriodicMsgReceived = 1; //Because of the first panda_recv_loop above. + std::array const mfMsgExpectedParts{ "\x21""DDEEFFG", "\x22""GHHIIJJ", "\x23""KKLLMMN", "\x24""NOOPPQQ", "\x25""RRSSTTU", "\x26""UVVWWXX" }; + + while (TRUE) { + std::vectormsg_recv = p->can_recv(); + for (auto msg : msg_recv) { + if (msg.is_receipt) continue; + if ((msg.dat[0] & 0xf0) == 0x20) { + Assert::AreEqual(mfMsgExpectedParts[MFframesReceived], std::string((const char*)msg.dat, msg.len), _T("Got wrong part of MF msg."), LINE_INFO()); + MFframesReceived++; + t_MFmsg.reset(); + } else if (std::string((const char*)msg.dat, msg.len) == "\x02HI") { + PeriodicMsgReceived++; + t_permsg.reset(); + } else { + Assert::IsTrue(FALSE, _T("Got impossible message. Something is very wrong. Check other tests."), LINE_INFO()); + } + } + + if (MFframesReceived >= 6) break; + Assert::IsTrue(300 > t_permsg.getTimePassed(), _T("Timed out waiting for periodic msessage frame."), LINE_INFO()); + Assert::IsTrue(300 > t_MFmsg.getTimePassed(), _T("Timed out waiting for multiframe msessage frame."), LINE_INFO()); + + if (msg_recv.size() == 0) + Sleep(10); + } + + //Stop the periodic message and grab any data it may have sent since we last checked. + //Not sure if this is needed. + Assert::AreEqual(STATUS_NOERROR, PassThruStopPeriodicMsg(chanid, msgid), _T("Failed to delete filter."), LINE_INFO()); + auto extra_panda_msg = panda_recv_loop_loose(p, 0, 200); + for (auto msg : extra_panda_msg) { + if (std::string((const char*)msg.dat, msg.len) == "\x02HI") { + PeriodicMsgReceived++; + Logger::WriteMessage("Received extra periodic message."); + } else { + Assert::IsTrue(FALSE, _T("Got impossible message. Something is very wrong. Check other tests."), LINE_INFO()); + } + } + + Assert::IsTrue(PeriodicMsgReceived > 3, _T("Did not receive enough periodic messages. Likely canceled or delayed."), LINE_INFO()); + + std::ostringstream stringStream; + stringStream << "PeriodicMsgReceived = " << PeriodicMsgReceived << std::endl; + Logger::WriteMessage(stringStream.str().c_str()); + + unsigned int periodicTxIndicationCount = 0; + unsigned int TxIndicationCount = 0; + auto j2534_msg_recv = j2534_recv_loop(chanid, 2 + (PeriodicMsgReceived * 2)); + for (int i = 0; i < PeriodicMsgReceived + 1; i++) { + check_J2534_can_msg(j2534_msg_recv[(i * 2) + 0], ISO15765, CAN_29BIT_ID | TX_INDICATION, 0, 4, 0, "\x18\xda\xef\xf1", LINE_INFO()); + switch (j2534_msg_recv[(i * 2) + 1].DataSize) { + case 4 + 2: + check_J2534_can_msg(j2534_msg_recv[(i * 2) + 1], ISO15765, CAN_29BIT_ID | TX_MSG_TYPE, 0, 4 + 2, 0, "\x18\xda\xef\xf1""HI", LINE_INFO()); + break; + case 4 + 48: + check_J2534_can_msg(j2534_msg_recv[(i * 2) + 1], ISO15765, CAN_29BIT_ID | TX_MSG_TYPE, 0, 4 + 48, 0, "\x18\xda\xef\xf1""AABBCCDDEEFFGGHHIIJJKKLLMMNNOOPPQQRRSSTTUUVVWWXX", LINE_INFO()); + break; + default: + Assert::IsTrue(FALSE, _T("Got unexpected data!"), LINE_INFO()); + } + } + + Assert::AreNotEqual(PeriodicMsgReceived, periodicTxIndicationCount, _T("Wrong number of periodic msgs reported by passthru device."), LINE_INFO()); + Assert::AreNotEqual(1, TxIndicationCount, _T("Wrong number of TX msgs reported by passthru device."), LINE_INFO()); + } + + ///////////////////// Tests checking things break or recover during send/receive ///////////////////// + + //Check rx FAILS when frame is dropped. 29 bit. Good Filter. NoPadding. STD address. Multi Frame. + TEST_METHOD(J2534_ISO15765_FailRx_29b_Filter_NoPad_STD_FFCF_DropFrame) + { + auto chanid = J2534_open_and_connect("", ISO15765, CAN_29BIT_ID, 500000, LINE_INFO()); + J2534_set_flowctrl_filter(chanid, CAN_29BIT_ID, 4, "\xff\xff\xff\xff", "\x18\xda\xf1\xef", "\x18\xda\xef\xf1", LINE_INFO()); + auto p = getPanda(500); + + //Send first frame, then check we get a flow control frame + auto panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x10\x13""ninete", 8, 1, LINE_INFO()); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, std::string("\x30\x00\x00", 3), LINE_INFO()); + + //Check first frame is registered with J2534 + auto j2534_msg_recv = j2534_recv_loop(chanid, 1); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, CAN_29BIT_ID | START_OF_MESSAGE, 0, 4, 0, "\x18\xda\xf1\xef", LINE_INFO()); + + //Send the rest of the message + //Missing the 2nd frame "\x21""en byte" + checked_panda_send(p, 0x18DAF1EF, TRUE, "\x22""s here", 7, 0, LINE_INFO()); + + //Check J2534 DOES NOT construct the incomplete message + j2534_recv_loop(chanid, 0); + } + + //Check rx ignores frames that arrive out of order. 29 bit. Good Filter. NoPadding. STD address. Multi Frame. + TEST_METHOD(J2534_ISO15765_PassRx_29b_Filter_NoPad_STD_FFCF_FrameNumSkip) + { + auto chanid = J2534_open_and_connect("", ISO15765, CAN_29BIT_ID, 500000, LINE_INFO()); + J2534_set_flowctrl_filter(chanid, CAN_29BIT_ID, 4, "\xff\xff\xff\xff", "\x18\xda\xf1\xef", "\x18\xda\xef\xf1", LINE_INFO()); + auto p = getPanda(500); + + //Send first frame, then check we get a flow control frame + auto panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x10\x13""ABCDEF", 8, 1, LINE_INFO()); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, std::string("\x30\x00\x00", 3), LINE_INFO()); + + //Check first frame is registered with J2534 + auto j2534_msg_recv = j2534_recv_loop(chanid, 1); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, CAN_29BIT_ID | START_OF_MESSAGE, 0, 4, 0, "\x18\xda\xf1\xef", LINE_INFO()); + + //Send the rest of the message + checked_panda_send(p, 0x18DAF1EF, TRUE, "\x22""XXXXXX", 7, 0, LINE_INFO()); + checked_panda_send(p, 0x18DAF1EF, TRUE, "\x21""GHIJKLM", 8, 0, LINE_INFO()); + checked_panda_send(p, 0x18DAF1EF, TRUE, "\x23""ZZZZZZ", 7, 0, LINE_INFO()); + checked_panda_send(p, 0x18DAF1EF, TRUE, "\x22""NOPQRS", 7, 0, LINE_INFO()); + + //Check J2534 constructa the complete message from the correctly numbered frames. + j2534_msg_recv = j2534_recv_loop(chanid, 1); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, CAN_29BIT_ID, 0, 4 + 0x13, 4 + 0x13, "\x18\xda\xf1\xef""ABCDEFGHIJKLMNOPQRS", LINE_INFO()); + } + + //Check Single Frame rx RESETS ongoing multiframe transmission. 29 bit. Good Filter. NoPadding. STD address. Multi Frame. + TEST_METHOD(J2534_ISO15765_PassRx_29b_Filter_NoPad_STD_SFRxResetsMFRx) + { + auto chanid = J2534_open_and_connect("", ISO15765, CAN_29BIT_ID, 500000, LINE_INFO()); + J2534_set_flowctrl_filter(chanid, CAN_29BIT_ID, 4, "\xff\xff\xff\xff", "\x18\xda\xf1\xef", "\x18\xda\xef\xf1", LINE_INFO()); + auto p = getPanda(500); + + //Send first frame, then check we get a flow control frame + auto panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x10\x13""ABCDEF", 8, 1, LINE_INFO()); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, std::string("\x30\x00\x00", 3), LINE_INFO()); + + //Check first frame is registered with J2534 + auto j2534_msg_recv = j2534_recv_loop(chanid, 1); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, CAN_29BIT_ID | START_OF_MESSAGE, 0, 4, 0, "\x18\xda\xf1\xef", LINE_INFO()); + + //Send the next part of the message multi message + checked_panda_send(p, 0x18DAF1EF, TRUE, "\x21""GHIJKLM", 8, 0, LINE_INFO()); + + //ABORTING MESSAGE + //Send a NEW single frame message and check the J2534 device gets it (but not the original message it was receiving. + checked_panda_send(p, 0x18DAF1EF, TRUE, "\x06""ABC123", 7, 0, LINE_INFO()); + j2534_msg_recv = j2534_recv_loop(chanid, 1); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, CAN_29BIT_ID, 0, 10, 10, "\x18\xda\xf1\xef""ABC123", LINE_INFO()); + + //Resume sending the old message, and check th eJ2534 device didn't get a message. + checked_panda_send(p, 0x18DAF1EF, TRUE, "\x22""NOPQRS", 7, 0, LINE_INFO()); + j2534_recv_loop(chanid, 0); + } + + //The documentation says that a s ingle channel can not send and receive messages trhough a + //single conversation (flow control filter) at the same time. However, the required behavior + //when this is detected is not described. This test was my best understanding of how it was + //wanted, but I no longer see the point. For now I am disabling it. + /*//Check Single Frame tx RESETS ongoing multiframe rx transmission. 29 bit. Good Filter. NoPadding. STD address. Multi Frame. + TEST_METHOD(J2534_ISO15765_PassRx_29b_Filter_NoPad_STD_SFTxResetsMFRx) + { + auto chanid = J2534_open_and_connect("", ISO15765, CAN_29BIT_ID, 500000, LINE_INFO()); + J2534_set_flowctrl_filter(chanid, CAN_29BIT_ID, 4, "\xff\xff\xff\xff", "\x18\xda\xf1\xef", "\x18\xda\xef\xf1", LINE_INFO()); + auto p = getPanda(500); + + //Send first frame, then check we get a flow control frame + auto panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x10\x13""ABCDEF", 8, 1, LINE_INFO()); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, std::string("\x30\x00\x00", 3), LINE_INFO()); + + //Check first frame is registered with J2534 + auto j2534_msg_recv = j2534_recv_loop(chanid, 1); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, CAN_29BIT_ID | START_OF_MESSAGE, 0, 4, 0, "\x18\xda\xf1\xef", LINE_INFO()); + + //Send the next part of the message multi message + checked_panda_send(p, 0x18DAF1EF, TRUE, "\x21""GHIJKLM", 8, 0, LINE_INFO()); + j2534_recv_loop(chanid, 0); + + //ABORTING MESSAGE + //Send a NEW single frame message and check the J2534 device gets it (but not the original message it was receiving. + J2534_send_msg_checked(chanid, ISO15765, 0, CAN_29BIT_ID, 0, 11, 0, "\x18\xda\xef\xf1""TX_TEST", LINE_INFO()); + j2534_msg_recv = j2534_recv_loop(chanid, 1); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, CAN_29BIT_ID | TX_INDICATION, 0, 4, 0, "\x18\xda\xef\xf1", LINE_INFO()); + + panda_msg_recv = panda_recv_loop(p, 1); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x07""TX_TEST", LINE_INFO()); + /////////////////////////// + + //Resume sending the old message, and check th eJ2534 device didn't get a message. + checked_panda_send(p, 0x18DAF1EF, TRUE, "\x22""NOPQRS", 7, 0, LINE_INFO()); + j2534_recv_loop(chanid, 0); + }*/ + + //TODO check rx is cleared by tx (multi). Or not.... read above note. + + //Check multiframe rx RESETS ongoing multiframe transmission. 29 bit. Good Filter. NoPadding. STD address. Multi Frame. + TEST_METHOD(J2534_ISO15765_PassRx_29b_Filter_NoPad_STD_FFCF_MFRxResetsMFRx) + { + auto chanid = J2534_open_and_connect("", ISO15765, CAN_29BIT_ID, 500000, LINE_INFO()); + J2534_set_flowctrl_filter(chanid, CAN_29BIT_ID, 4, "\xff\xff\xff\xff", "\x18\xda\xf1\xef", "\x18\xda\xef\xf1", LINE_INFO()); + auto p = getPanda(500); + + //Send first frame, then check we get a flow control frame + auto panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x10\x13""ABCDEF", 8, 1, LINE_INFO()); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, std::string("\x30\x00\x00", 3), LINE_INFO()); + + //Check first frame is registered with J2534 + auto j2534_msg_recv = j2534_recv_loop(chanid, 1); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, CAN_29BIT_ID | START_OF_MESSAGE, 0, 4, 0, "\x18\xda\xf1\xef", LINE_INFO()); + + //Send the next part of the multi message A + checked_panda_send(p, 0x18DAF1EF, TRUE, "\x21""GHIJKLM", 8, 0, LINE_INFO()); + + //ABORTING MESSAGE A + //Send a NEW multi frame message (B) and check the J2534 device gets it (but not the original message it was receiving. + //Send first frame, then check we get a flow control frame + panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x10\x13""ninete", 8, 1, LINE_INFO()); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, std::string("\x30\x00\x00", 3), LINE_INFO()); + + //Check first frame is registered with J2534 + j2534_msg_recv = j2534_recv_loop(chanid, 1); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, CAN_29BIT_ID | START_OF_MESSAGE, 0, 4, 0, "\x18\xda\xf1\xef", LINE_INFO()); + + //Send the rest of the message + checked_panda_send(p, 0x18DAF1EF, TRUE, "\x21""en byte", 8, 0, LINE_INFO()); + checked_panda_send(p, 0x18DAF1EF, TRUE, "\x22""s here", 7, 0, LINE_INFO()); + + //Check J2534 constructed the whole message + j2534_msg_recv = j2534_recv_loop(chanid, 1); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, CAN_29BIT_ID, 0, 4 + 0x13, 4 + 0x13, "\x18\xda\xf1\xef""nineteen bytes here", LINE_INFO()); + //////////////////////// End sending B + + //Resume sending the multi message A, and check th eJ2534 device didn't get a message. + checked_panda_send(p, 0x18DAF1EF, TRUE, "\x22""NOPQRS", 7, 0, LINE_INFO()); + j2534_recv_loop(chanid, 0); + } + + //Check rx fails gracefully if final CF of MF rx is too short. 29 bit. Good Filter. NoPadding. STD address. Multi Frame. + TEST_METHOD(J2534_ISO15765_FailRxFinalCFTooShort_29b_Filter_NoPad_STD_FFCF) + { + auto chanid = J2534_open_and_connect("", ISO15765, CAN_29BIT_ID, 500000, LINE_INFO()); + J2534_set_flowctrl_filter(chanid, CAN_29BIT_ID, 4, "\xff\xff\xff\xff", "\x18\xda\xf1\xef", "\x18\xda\xef\xf1", LINE_INFO()); + auto p = getPanda(500); + + //Send first frame, then check we get a flow control frame + auto panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x10\x13""ninete", 8, 1, LINE_INFO()); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, std::string("\x30\x00\x00", 3), LINE_INFO()); + + //Check first frame is registered with J2534 + auto j2534_msg_recv = j2534_recv_loop(chanid, 1); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, CAN_29BIT_ID | START_OF_MESSAGE, 0, 4, 0, "\x18\xda\xf1\xef", LINE_INFO()); + + //Send the rest of the message + checked_panda_send(p, 0x18DAF1EF, TRUE, "\x21""en byte", 8, 0, LINE_INFO()); + checked_panda_send(p, 0x18DAF1EF, TRUE, "\x22""s her", 6, 0, LINE_INFO()); //The transaction should reset here because more data could have been sent. + checked_panda_send(p, 0x18DAF1EF, TRUE, "\x23""e", 2, 0, LINE_INFO()); + + //Check J2534 constructed the whole message + j2534_msg_recv = j2534_recv_loop(chanid, 0); + } + + //Check rx fails gracefully if first frame is too short. 29 bit. Good Filter. NoPadding. STD address. Multi Frame. + TEST_METHOD(J2534_ISO15765_FailRxFFTooShort_29b_Filter_NoPad_STD_FFCF) + { + auto chanid = J2534_open_and_connect("", ISO15765, CAN_29BIT_ID, 500000, LINE_INFO()); + J2534_set_flowctrl_filter(chanid, CAN_29BIT_ID, 4, "\xff\xff\xff\xff", "\x18\xda\xf1\xef", "\x18\xda\xef\xf1", LINE_INFO()); + auto p = getPanda(500); + + //Send first frame, then check we get a flow control frame. The transaction should reset immediately because more data could have been sent in this frame. + checked_panda_send(p, 0x18DAF1EF, TRUE, "\x10\x13""ninet", 7, 0, LINE_INFO()); + j2534_recv_loop(chanid, 0); + + //Send the rest of the message + checked_panda_send(p, 0x18DAF1EF, TRUE, "\x21""een byt", 8, 0, LINE_INFO()); + checked_panda_send(p, 0x18DAF1EF, TRUE, "\x22""es here", 8, 0, LINE_INFO()); + + //Check J2534 constructed the whole message + j2534_recv_loop(chanid, 0); + } + + //Check MF tx will stop upon receiving a flow control ABORT. 29 bit. Good Filter. NoPadding. STD address. Large STmin, then abort, then send SF. + TEST_METHOD(J2534_ISO15765_SuccessTx_29b_Filter_NoPad_STD__MF_FCAbort_SF) + { + auto chanid = J2534_open_and_connect("", ISO15765, CAN_29BIT_ID, 500000, LINE_INFO()); + J2534_set_flowctrl_filter(chanid, CAN_29BIT_ID, 4, "\xff\xff\xff\xff", "\x18\xda\xf1\xef", "\x18\xda\xef\xf1", LINE_INFO()); + write_ioctl(chanid, LOOPBACK, TRUE, LINE_INFO()); + auto p = getPanda(500); + + J2534_send_msg_checked(chanid, ISO15765, 0, CAN_29BIT_ID, 0, 4 + 48, 0, "\x18\xda\xef\xf1""AABBCCDDEEFFGGHHIIJJKKLLMMNNOOPPQQRRSSTTUUVVWWXX", LINE_INFO()); + + auto panda_msg_recv = panda_recv_loop(p, 1); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x10\x30""AABBCC", LINE_INFO()); + + panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x30\x02\x20", 3, 2, LINE_INFO());//Start a conversation. FC timeout is 32 ms. + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x21""DDEEFFG", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[1], 0, 0x18DAEFF1, TRUE, FALSE, "\x22""GHHIIJJ", LINE_INFO()); + + panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x32\x0\x0", 3, 0, LINE_INFO());//Abort the conversation + + J2534_send_msg_checked(chanid, ISO15765, 0, CAN_29BIT_ID, 0, 4 + 4, 0, "\x18\xda\xef\xf1""SUP!", LINE_INFO()); + + auto j2534_msg_recv = j2534_recv_loop(chanid, 2); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, CAN_29BIT_ID | TX_INDICATION, 0, 4, 0, "\x18\xda\xef\xf1", LINE_INFO()); + check_J2534_can_msg(j2534_msg_recv[1], ISO15765, CAN_29BIT_ID | TX_MSG_TYPE, 0, 4 + 4, 0, "\x18\xda\xef\xf1""SUP!", LINE_INFO()); + } + + //Check MF tx will stop upon receiving a flow control ABORT during valid blocksize. 29 bit. Good Filter. NoPadding. STD address. Large STmin, then mid tx abort, then send SF. + TEST_METHOD(J2534_ISO15765_SuccessTx_29b_Filter_NoPad_STD__MF_FCMixTXAbort_SF) + { + auto chanid = J2534_open_and_connect("", ISO15765, CAN_29BIT_ID, 500000, LINE_INFO()); + J2534_set_flowctrl_filter(chanid, CAN_29BIT_ID, 4, "\xff\xff\xff\xff", "\x18\xda\xf1\xef", "\x18\xda\xef\xf1", LINE_INFO()); + write_ioctl(chanid, LOOPBACK, TRUE, LINE_INFO()); + auto p = getPanda(500); + + J2534_send_msg_checked(chanid, ISO15765, 0, CAN_29BIT_ID, 0, 4 + 48, 0, "\x18\xda\xef\xf1""AABBCCDDEEFFGGHHIIJJKKLLMMNNOOPPQQRRSSTTUUVVWWXX", LINE_INFO()); + + auto panda_msg_recv = panda_recv_loop(p, 1); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x10\x30""AABBCC", LINE_INFO()); + + panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x30\x06\x7F", 3, 1, LINE_INFO(), 200);//Start a conversation. FC timeout is 127 ms. + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x21""DDEEFFG", LINE_INFO()); + + panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x32\x0\x0", 3, 0, LINE_INFO());//Abort the conversation + panda_recv_loop(p, 0, 200); + + J2534_send_msg_checked(chanid, ISO15765, 0, CAN_29BIT_ID, 0, 4 + 4, 0, "\x18\xda\xef\xf1""SUP!", LINE_INFO()); + + auto j2534_msg_recv = j2534_recv_loop(chanid, 2); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, CAN_29BIT_ID | TX_INDICATION, 0, 4, 0, "\x18\xda\xef\xf1", LINE_INFO()); + check_J2534_can_msg(j2534_msg_recv[1], ISO15765, CAN_29BIT_ID | TX_MSG_TYPE, 0, 4 + 4, 0, "\x18\xda\xef\xf1""SUP!", LINE_INFO()); + } + + //Check slow tx can be stalled past timeout with CF WAIT frames. 29 bit. Good Filter. NoPadding. STD address. MF tx that would timeout without WAIT frames. + TEST_METHOD(J2534_ISO15765_SuccessTx_29b_Filter_NoPad_STD_MFWithWaitFrames) + { + auto chanid = J2534_open_and_connect("", ISO15765, CAN_29BIT_ID, 500000, LINE_INFO()); + J2534_set_flowctrl_filter(chanid, CAN_29BIT_ID, 4, "\xff\xff\xff\xff", "\x18\xda\xf1\xef", "\x18\xda\xef\xf1", LINE_INFO()); + write_ioctl(chanid, LOOPBACK, TRUE, LINE_INFO()); + write_ioctl(chanid, ISO15765_WFT_MAX, 10, LINE_INFO()); + auto p = getPanda(500); + + J2534_send_msg_checked(chanid, ISO15765, 0, CAN_29BIT_ID, 0, 4 + 48, 0, "\x18\xda\xef\xf1""AABBCCDDEEFFGGHHIIJJKKLLMMNNOOPPQQRRSSTTUUVVWWXX", LINE_INFO()); + + auto panda_msg_recv = panda_recv_loop(p, 1); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x10\x30""AABBCC", LINE_INFO()); + + panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x30\x02\x40", 3, 2, LINE_INFO(), 3000);//Start a conversation. FC timeout is 250 ms. + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x21""DDEEFFG", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[1], 0, 0x18DAEFF1, TRUE, FALSE, "\x22""GHHIIJJ", LINE_INFO()); + + checked_panda_send(p, 0x18DAF1EF, TRUE, "\x31\x0\x0", 3, 0, LINE_INFO(), 100);//Delay the conversation. + Sleep(100); + checked_panda_send(p, 0x18DAF1EF, TRUE, "\x31\x0\x0", 3, 0, LINE_INFO(), 100);//Delay the conversation. + Sleep(100); + checked_panda_send(p, 0x18DAF1EF, TRUE, "\x31\x0\x0", 3, 0, LINE_INFO(), 100);//Delay the conversation. + Sleep(100); + checked_panda_send(p, 0x18DAF1EF, TRUE, "\x31\x0\x0", 3, 0, LINE_INFO(), 100);//Delay the conversation. + Sleep(100); + + panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x30\x0\x0", 3, 4, LINE_INFO(), 3000);//Start a conversation. FC timeout is 250 ms. + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x23""KKLLMMN", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[1], 0, 0x18DAEFF1, TRUE, FALSE, "\x24""NOOPPQQ", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[2], 0, 0x18DAEFF1, TRUE, FALSE, "\x25""RRSSTTU", LINE_INFO());//Some of these should fail to recv if there is an issue. + check_panda_can_msg(panda_msg_recv[3], 0, 0x18DAEFF1, TRUE, FALSE, "\x26""UVVWWXX", LINE_INFO()); + + auto j2534_msg_recv = j2534_recv_loop(chanid, 2); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, CAN_29BIT_ID | TX_INDICATION, 0, 4, 0, "\x18\xda\xef\xf1", LINE_INFO()); + check_J2534_can_msg(j2534_msg_recv[1], ISO15765, CAN_29BIT_ID | TX_MSG_TYPE, 0, 4 + 48, 0, "\x18\xda\xef\xf1""AABBCCDDEEFFGGHHIIJJKKLLMMNNOOPPQQRRSSTTUUVVWWXX", LINE_INFO()); + } + + //Check slow tx can be stalled past timeout with CF WAIT frames during normal TX. 29 bit. Good Filter. NoPadding. STD address. Stalling working MF tx. + TEST_METHOD(J2534_ISO15765_SuccessTx_29b_Filter_NoPad_STD_MFWithMidTXWaitFrames) + { + auto chanid = J2534_open_and_connect("", ISO15765, CAN_29BIT_ID, 500000, LINE_INFO()); + J2534_set_flowctrl_filter(chanid, CAN_29BIT_ID, 4, "\xff\xff\xff\xff", "\x18\xda\xf1\xef", "\x18\xda\xef\xf1", LINE_INFO()); + write_ioctl(chanid, LOOPBACK, TRUE, LINE_INFO()); + write_ioctl(chanid, ISO15765_WFT_MAX, 10, LINE_INFO()); + auto p = getPanda(500); + + J2534_send_msg_checked(chanid, ISO15765, 0, CAN_29BIT_ID, 0, 4 + 48, 0, "\x18\xda\xef\xf1""AABBCCDDEEFFGGHHIIJJKKLLMMNNOOPPQQRRSSTTUUVVWWXX", LINE_INFO()); + + auto panda_msg_recv = panda_recv_loop(p, 1); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x10\x30""AABBCC", LINE_INFO()); + + panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x30\x06\x64", 3, 2, LINE_INFO(), 120);//Start a conversation. STmin 100. FC timeout is 250 ms. + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x21""DDEEFFG", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[1], 0, 0x18DAEFF1, TRUE, FALSE, "\x22""GHHIIJJ", LINE_INFO()); + + panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x31\x0\x0", 3, 0, LINE_INFO(), 100);//Delay the conversation. + Sleep(100); + panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x31\x0\x0", 3, 0, LINE_INFO(), 100);//Delay the conversation. + Sleep(100); + panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x31\x0\x0", 3, 0, LINE_INFO(), 100);//Delay the conversation. + Sleep(100); + panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x31\x0\x0", 3, 0, LINE_INFO(), 100);//Delay the conversation. + Sleep(100); + + panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x30\x0\x0", 3, 4, LINE_INFO(), 3000);//Start a conversation. FC timeout is 250 ms. + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x23""KKLLMMN", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[1], 0, 0x18DAEFF1, TRUE, FALSE, "\x24""NOOPPQQ", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[2], 0, 0x18DAEFF1, TRUE, FALSE, "\x25""RRSSTTU", LINE_INFO());//Some of these should fail to recv if there is an issue. + check_panda_can_msg(panda_msg_recv[3], 0, 0x18DAEFF1, TRUE, FALSE, "\x26""UVVWWXX", LINE_INFO()); + + auto j2534_msg_recv = j2534_recv_loop(chanid, 2); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, CAN_29BIT_ID | TX_INDICATION, 0, 4, 0, "\x18\xda\xef\xf1", LINE_INFO()); + check_J2534_can_msg(j2534_msg_recv[1], ISO15765, CAN_29BIT_ID | TX_MSG_TYPE, 0, 4 + 48, 0, "\x18\xda\xef\xf1""AABBCCDDEEFFGGHHIIJJKKLLMMNNOOPPQQRRSSTTUUVVWWXX", LINE_INFO()); + } + + //Check that too many WAIT frames will abort the transfer. 29 bit. Good Filter. NoPadding. STD address. Too much stalling causes abort. + TEST_METHOD(J2534_ISO15765_SuccessTx_29b_Filter_NoPad_STD_MFTooManyWaitFrames) + { + auto chanid = J2534_open_and_connect("", ISO15765, CAN_29BIT_ID, 500000, LINE_INFO()); + J2534_set_flowctrl_filter(chanid, CAN_29BIT_ID, 4, "\xff\xff\xff\xff", "\x18\xda\xf1\xef", "\x18\xda\xef\xf1", LINE_INFO()); + write_ioctl(chanid, LOOPBACK, TRUE, LINE_INFO()); + write_ioctl(chanid, ISO15765_WFT_MAX, 2, LINE_INFO()); + auto p = getPanda(500); + + J2534_send_msg_checked(chanid, ISO15765, 0, CAN_29BIT_ID, 0, 4 + 48, 0, "\x18\xda\xef\xf1""AABBCCDDEEFFGGHHIIJJKKLLMMNNOOPPQQRRSSTTUUVVWWXX", LINE_INFO()); + + auto panda_msg_recv = panda_recv_loop(p, 1); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x10\x30""AABBCC", LINE_INFO()); + + panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x30\x02\x64", 3, 2, LINE_INFO(), 120);//Start a conversation. STmin 100. FC timeout is 250 ms. + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x21""DDEEFFG", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[1], 0, 0x18DAEFF1, TRUE, FALSE, "\x22""GHHIIJJ", LINE_INFO()); + + panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x31\x0\x0", 3, 0, LINE_INFO(), 100);//Delay the conversation. + Sleep(100); + panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x31\x0\x0", 3, 0, LINE_INFO(), 100);//Delay the conversation. + Sleep(100); + + panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x30\x02\x64", 3, 2, LINE_INFO(), 120);//Resume the conversation. + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x23""KKLLMMN", LINE_INFO()); + check_panda_can_msg(panda_msg_recv[1], 0, 0x18DAEFF1, TRUE, FALSE, "\x24""NOOPPQQ", LINE_INFO()); + + panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x31\x0\x0", 3, 0, LINE_INFO(), 100);//Delay the conversation. + Sleep(100); + panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x31\x0\x0", 3, 0, LINE_INFO(), 100);//Delay the conversation. + Sleep(100); + + //Should not resume because the conversation has been delayed too long. + panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x30\x0\x0", 3, 0, LINE_INFO(), 300); + + //Send a SF message to check the tubes are not clogged. + J2534_send_msg_checked(chanid, ISO15765, 0, CAN_29BIT_ID, 0, 4 + 4, 0, "\x18\xda\xef\xf1""SUP!", LINE_INFO()); + + auto j2534_msg_recv = j2534_recv_loop(chanid, 2); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, CAN_29BIT_ID | TX_INDICATION, 0, 4, 0, "\x18\xda\xef\xf1", LINE_INFO()); + check_J2534_can_msg(j2534_msg_recv[1], ISO15765, CAN_29BIT_ID | TX_MSG_TYPE, 0, 4 + 4, 0, "\x18\xda\xef\xf1""SUP!", LINE_INFO()); + } + + ///////////////////// Tests checking things actually send/receive. Ext 5 byte Addressing ///////////////////// + + //Check rx passes with filter. 29 bit. Good Filter. NoPadding. EXT address. Single Frame. + TEST_METHOD(J2534_ISO15765_SuccessRx_29b_Filter_NoPad_EXT_SF) + { + auto chanid = J2534_open_and_connect("", ISO15765, CAN_29BIT_ID, 500000, LINE_INFO()); + J2534_set_flowctrl_filter(chanid, CAN_29BIT_ID | ISO15765_ADDR_TYPE, 5, "\xff\xff\xff\xff\xff", "\x18\xda\xf1\xef\x13", "\x18\xda\xef\xf1\x13", LINE_INFO()); + auto p = getPanda(500); + + checked_panda_send(p, 0x18DAF1EF, TRUE, "\x13""\x06""ABC123", 8, 0, LINE_INFO()); + + auto j2534_msg_recv = j2534_recv_loop(chanid, 1); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, CAN_29BIT_ID | ISO15765_ADDR_TYPE, 0, 11, 11, "\x18\xda\xf1\xef\x13""ABC123", LINE_INFO()); + } + + //Check tx passes with filter. 29 bit. Good Filter. NoPadding. EXT address. Single Frame. + TEST_METHOD(J2534_ISO15765_SuccessTx_29b_Filter_NoPad_EXT_SF) + { + auto chanid = J2534_open_and_connect("", ISO15765, CAN_29BIT_ID, 500000, LINE_INFO()); + J2534_set_flowctrl_filter(chanid, CAN_29BIT_ID | ISO15765_ADDR_TYPE, 5, "\xff\xff\xff\xff\xff", "\x18\xda\xf1\xef\x13", "\x18\xda\xef\xf1\x13", LINE_INFO()); + auto p = getPanda(500); + + J2534_send_msg_checked(chanid, ISO15765, 0, CAN_29BIT_ID | ISO15765_ADDR_TYPE, 0, 11, 0, "\x18\xda\xef\xf1\x13""DERP!!", LINE_INFO()); + auto j2534_msg_recv = j2534_recv_loop(chanid, 1); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, CAN_29BIT_ID | TX_INDICATION | ISO15765_ADDR_TYPE, 0, 5, 0, "\x18\xda\xef\xf1\x13", LINE_INFO()); + + auto panda_msg_recv = panda_recv_loop(p, 1); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, "\x13""\x06""DERP!!", LINE_INFO()); + } + + //Check rx passes with filter. 29 bit. Good Filter. NoPadding. EXT address. Multi Frame. + TEST_METHOD(J2534_ISO15765_SuccessRx_29b_Filter_NoPad_EXT_FFCF) + { + auto chanid = J2534_open_and_connect("", ISO15765, CAN_29BIT_ID, 500000, LINE_INFO()); + J2534_set_flowctrl_filter(chanid, CAN_29BIT_ID | ISO15765_ADDR_TYPE, 5, "\xff\xff\xff\xff\xff", "\x18\xda\xf1\xef\x13", "\x18\xda\xef\xf1\x13", LINE_INFO()); + auto p = getPanda(500); + + //Send first frame, then check we get a flow control frame + Assert::IsTrue(p->can_send(0x18DAF1EF, TRUE, (const uint8_t*)"\x13""\x10\x13""ninet", 8, panda::PANDA_CAN1), _T("Panda send says it failed."), LINE_INFO()); + + //Check first frame is registered with J2534 + auto j2534_msg_recv = j2534_recv_loop(chanid, 1); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, CAN_29BIT_ID | START_OF_MESSAGE | ISO15765_ADDR_TYPE, 0, 5, 0, "\x18\xda\xf1\xef\x13", LINE_INFO()); + + auto panda_msg_recv = panda_recv_loop(p, 2); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAF1EF, TRUE, TRUE, std::string("\x13""\x10\x13""ninet", 8), LINE_INFO()); + check_panda_can_msg(panda_msg_recv[1], 0, 0x18DAEFF1, TRUE, FALSE, std::string("\x13""\x30\x00\x00", 4), LINE_INFO()); + + //Send the rest of the message + checked_panda_send(p, 0x18DAF1EF, TRUE, "\x13""\x21""een by", 8, 0, LINE_INFO()); + checked_panda_send(p, 0x18DAF1EF, TRUE, "\x13""\x22""tes he", 8, 0, LINE_INFO()); + checked_panda_send(p, 0x18DAF1EF, TRUE, "\x13""\x23""re", 8, 0, LINE_INFO()); + + //Check J2534 constructed the whole message + j2534_msg_recv = j2534_recv_loop(chanid, 1); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, CAN_29BIT_ID | ISO15765_ADDR_TYPE, 0, 5 + 0x13, 5 + 0x13, "\x18\xda\xf1\xef\x13""nineteen bytes here", LINE_INFO()); + } + + //Check tx passes with filter. 29 bit. Good Filter. NoPadding. EXT address. Multi Frame. + /*TEST_METHOD(J2534_ISO15765_SuccessTx_29b_Filter_NoPad_EXT_FFCF) + { //TODO when TX works with flow control}*/ + + ///////////////////// Tests checking things break or recover during send/receive. Ext 5 byte Addressing ///////////////////// + + //Check rx FAILS when frame is dropped. 29 bit. Good Filter. NoPadding. STD address. Multi Frame. + TEST_METHOD(J2534_ISO15765_FailRx_29b_Filter_NoPad_EXT_FFCF_DropFrame) + { + auto chanid = J2534_open_and_connect("", ISO15765, CAN_29BIT_ID, 500000, LINE_INFO()); + J2534_set_flowctrl_filter(chanid, CAN_29BIT_ID | ISO15765_ADDR_TYPE, 5, "\xff\xff\xff\xff\xff", "\x18\xda\xf1\xef\x13", "\x18\xda\xef\xf1\x13", LINE_INFO()); + auto p = getPanda(500); + + //Send first frame, then check we get a flow control frame + auto panda_msg_recv = checked_panda_send(p, 0x18DAF1EF, TRUE, "\x13\x10\x13""ninet", 8, 1, LINE_INFO()); + check_panda_can_msg(panda_msg_recv[0], 0, 0x18DAEFF1, TRUE, FALSE, std::string("\x13\x30\x00\x00", 4), LINE_INFO()); + + //Check first frame is registered with J2534 + auto j2534_msg_recv = j2534_recv_loop(chanid, 1); + check_J2534_can_msg(j2534_msg_recv[0], ISO15765, CAN_29BIT_ID | START_OF_MESSAGE | ISO15765_ADDR_TYPE, 0, 5, 0, "\x18\xda\xf1\xef\x13", LINE_INFO()); + + //Send the rest of the message + //Missing the 2nd frame "\x13""\x21""een by" + checked_panda_send(p, 0x18DAF1EF, TRUE, "\x13""\x22""tes he", 8, 0, LINE_INFO()); + checked_panda_send(p, 0x18DAF1EF, TRUE, "\x13""\x23""re", 8, 0, LINE_INFO()); + + //Check J2534 DOES NOT construct the incomplete message + j2534_recv_loop(chanid, 0); + } + + bool didopen = FALSE; + unsigned long devid; + + unsigned long open_dev(const char* name, long assert_err = STATUS_NOERROR, TCHAR* failmsg = _T("Failed to open device.")) { + unsigned int res = PassThruOpen((void*)name, &devid); + if (res == STATUS_NOERROR) didopen = TRUE; + return res; + } + + unsigned long J2534_open_and_connect(const char* name, unsigned long ProtocolID, unsigned long Flags, unsigned long bps, const __LineInfo* pLineInfo = NULL) { + unsigned long chanid; + Assert::AreEqual(STATUS_NOERROR, open_dev(name), _T("Failed to open device."), pLineInfo); + Assert::AreEqual(STATUS_NOERROR, PassThruConnect(devid, ProtocolID, Flags, bps, &chanid), _T("Failed to open channel."), pLineInfo); + write_ioctl(chanid, LOOPBACK, FALSE, LINE_INFO()); // DISABLE J2534 ECHO/LOOPBACK + return chanid; + } + + }; +} diff --git a/drivers/windows/pandaJ2534DLL Test/pandaJ2534DLL Test.vcxproj b/drivers/windows/pandaJ2534DLL Test/pandaJ2534DLL Test.vcxproj new file mode 100644 index 0000000000..56923823ba --- /dev/null +++ b/drivers/windows/pandaJ2534DLL Test/pandaJ2534DLL Test.vcxproj @@ -0,0 +1,125 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + + {7912F978-B48C-4C5D-8BFD-5D1E22158E47} + Win32Proj + pandaJ2534DLLTest + 8.1 + Tests + + + + DynamicLibrary + true + v140 + Unicode + false + + + DynamicLibrary + false + v140 + true + Unicode + false + + + + + + + + + + + + + + + true + $(SolutionDir)$(Configuration)_$(PlatformShortName)\ + + + true + $(SolutionDir)$(Configuration)_$(PlatformShortName)\ + + + + Use + Level3 + Disabled + $(VCInstallDir)UnitTest\include;%(AdditionalIncludeDirectories);$(SolutionDir) + WIN32;_DEBUG;%(PreprocessorDefinitions) + true + + + Windows + $(VCInstallDir)UnitTest\lib;%(AdditionalLibraryDirectories) + kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies);$(OutDir)panda.lib + + + + + Level3 + Use + MaxSpeed + true + true + $(VCInstallDir)UnitTest\include;%(AdditionalIncludeDirectories);$(SolutionDir) + WIN32;NDEBUG;%(PreprocessorDefinitions) + true + + + Windows + true + true + $(VCInstallDir)UnitTest\lib;%(AdditionalLibraryDirectories) + kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies);$(OutDir)panda.lib + + + + + + + + + + + + + + + + + Create + Create + + + + + + + + {96e0e646-ee76-444d-9a77-a0cd7f781deb} + + + {a2bb18a5-f26b-48d6-bbb5-b83d64473c77} + + + {5528aefb-638d-49af-b9d4-965154e7d531} + + + + + + \ No newline at end of file diff --git a/drivers/windows/pandaJ2534DLL Test/pandaJ2534DLL Test.vcxproj.filters b/drivers/windows/pandaJ2534DLL Test/pandaJ2534DLL Test.vcxproj.filters new file mode 100644 index 0000000000..476ce458d3 --- /dev/null +++ b/drivers/windows/pandaJ2534DLL Test/pandaJ2534DLL Test.vcxproj.filters @@ -0,0 +1,63 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + \ No newline at end of file diff --git a/drivers/windows/pandaJ2534DLL Test/panda_tests.cpp b/drivers/windows/pandaJ2534DLL Test/panda_tests.cpp new file mode 100644 index 0000000000..65e549c50c --- /dev/null +++ b/drivers/windows/pandaJ2534DLL Test/panda_tests.cpp @@ -0,0 +1,187 @@ +#include "stdafx.h" +#include "panda/panda.h" +#include "TestHelpers.h" + +#include + +using namespace Microsoft::VisualStudio::CppUnitTestFramework; +using namespace panda; + +namespace pandaTestNative +{ + TEST_CLASS(DeviceDiscovery) + { + public: + + TEST_METHOD(Panda_DevDiscover_ListDevices) + { + auto pandas_available = Panda::listAvailablePandas(); + Assert::IsTrue(pandas_available.size() > 0, _T("No pandas were found.")); + for (auto sn : pandas_available) { + Assert::IsTrue(sn.size() == 24, _T("panda Serial Number not 24 characters long.")); + } + } + + TEST_METHOD(Panda_DevDiscover_OpenFirstDevice) + { + auto pandas_available = Panda::listAvailablePandas(); + Assert::IsTrue(pandas_available.size() > 0, _T("No pandas were found.")); + + auto p1 = Panda::openPanda(pandas_available[0]); + Assert::IsFalse(p1 == nullptr, _T("Could not open panda.")); + } + + TEST_METHOD(Panda_DevDiscover_OpenDeviceNoName) + { + auto pandas_available = Panda::listAvailablePandas(); + Assert::IsTrue(pandas_available.size() > 0, _T("No pandas were found.")); + + auto p1 = Panda::openPanda(""); + Assert::IsFalse(p1 == nullptr, _T("Could not open panda.")); + Assert::IsTrue(p1->get_usb_sn() == pandas_available[0], _T("Could not open panda.")); + } + + TEST_METHOD(Panda_DevDiscover_OpenDeviceUnavailable) + { + auto p1 = Panda::openPanda("ZZZZZZZZZZZZZZZZZZZZZZZZ"); + Assert::IsTrue(p1 == nullptr, _T("Invalid sn still worked.")); + } + + TEST_METHOD(Panda_DevDiscover_WillNotOpenAlreadyOpenedDevice) + { + auto pandas_available = Panda::listAvailablePandas(); + Assert::IsTrue(pandas_available.size() > 0, _T("No pandas were found.")); + + auto p1 = Panda::openPanda(pandas_available[0]); + Assert::IsFalse(p1 == nullptr, _T("Could not open panda.")); + + auto p2 = Panda::openPanda(pandas_available[0]); + Assert::IsTrue(p2 == nullptr, _T("Opened an already open panda.")); + } + + TEST_METHOD(Panda_DevDiscover_OpenedDeviceNotListed) + { + auto pandas_available = Panda::listAvailablePandas(); + Assert::IsTrue(pandas_available.size() > 0, _T("No pandas were found.")); + + auto p1 = Panda::openPanda(pandas_available[0]); + Assert::IsFalse(p1 == nullptr, _T("Could not open panda.")); + + auto pandas_available2 = Panda::listAvailablePandas(); + for (auto sn : pandas_available2) { + Assert::IsFalse(p1->get_usb_sn() == sn, _T("Opened panda appears in list of available pandas.")); + } + + } + }; + + TEST_CLASS(CANOperations) + { + public: + + TEST_METHOD(Panda_CAN_Echo) + { + auto p0 = getPanda(500, TRUE); + + uint32_t addr = 0xAA; + bool is_29b = FALSE; + uint8_t candata[8]; + + for (auto canbus : { PANDA_CAN1, PANDA_CAN2, PANDA_CAN3 }) { + uint8_t len = (rand() % 8) + 1; + for (size_t i = 0; i < len; i++) + candata[i] = rand() % 256; + + p0->can_send(addr, is_29b, candata, len, canbus); + Sleep(10); + + auto can_msgs = p0->can_recv(); + + Assert::AreEqual(2, can_msgs.size(), _T("Received the wrong number of CAN messages."), LINE_INFO()); + + for (auto msg : can_msgs) { + Assert::IsTrue(msg.addr == addr, _T("Wrong addr.")); + Assert::IsTrue(msg.bus == canbus, _T("Wrong bus.")); + Assert::IsTrue(msg.len == len, _T("Wrong len.")); + Assert::AreEqual(memcmp(msg.dat, candata, msg.len), 0, _T("Received CAN data not equal")); + for (int i = msg.len; i < 8; i++) + Assert::IsTrue(msg.dat[i] == 0, _T("Received CAN data not trailed by 0s")); + } + + Assert::IsTrue(can_msgs[0].is_receipt, _T("Didn't get receipt.")); + Assert::IsFalse(can_msgs[1].is_receipt, _T("Didn't get echo.")); + } + } + + TEST_METHOD(Panda_CAN_ChangeBaud) + { + auto p0 = getPanda(250); + auto p1 = getPanda(500); + + p0->can_send(0xAA, FALSE, (const uint8_t*)"\x1\x2\x3\x4\x5\x6\x7\x8", 8, panda::PANDA_CAN1); + panda_recv_loop(p0, 0); + panda_recv_loop(p1, 0); + + p0->set_can_speed_kbps(panda::PANDA_CAN1, 500); + + auto panda_msg_recv = panda_recv_loop(p0, 1); + check_panda_can_msg(panda_msg_recv[0], 0, 0xAA, FALSE, TRUE, "\x1\x2\x3\x4\x5\x6\x7\x8", LINE_INFO()); + panda_msg_recv = panda_recv_loop(p1, 1); + check_panda_can_msg(panda_msg_recv[0], 0, 0xAA, FALSE, FALSE, "\x1\x2\x3\x4\x5\x6\x7\x8", LINE_INFO()); + + ////////////////// + + p0->set_can_speed_kbps(panda::PANDA_CAN1, 250); + p0->can_send(0xC4, FALSE, (const uint8_t*)"\xA\B\xC\xD\xE\xF\x10\x11", 8, panda::PANDA_CAN1); + panda_recv_loop(p0, 0); + panda_recv_loop(p1, 0); + + p1->set_can_speed_kbps(panda::PANDA_CAN1, 250); + + panda_msg_recv = panda_recv_loop(p0, 1); + check_panda_can_msg(panda_msg_recv[0], 0, 0xC4, FALSE, TRUE, "\xA\B\xC\xD\xE\xF\x10\x11", LINE_INFO()); + panda_msg_recv = panda_recv_loop(p1, 1); + check_panda_can_msg(panda_msg_recv[0], 0, 0xC4, FALSE, FALSE, "\xA\B\xC\xD\xE\xF\x10\x11", LINE_INFO()); + } + + TEST_METHOD(Panda_CAN_ClearClears) + { + auto p0 = getPanda(500, TRUE); + p0->can_send(0xAA, FALSE, (const uint8_t*)"\x0\x1\x2\x3\x4\x5\x6\x7", 8, panda::PANDA_CAN1); + Sleep(100); + p0->can_clear(PANDA_CAN_RX); + + auto can_msgs = p0->can_recv(); + Assert::IsTrue(can_msgs.size() == 0, _T("Received messages after a clear.")); + } + }; + + TEST_CLASS(SerialOperations) + { + public: + + TEST_METHOD(Panda_LIN_Echo) + { + auto p0 = getPanda(500); + + for (auto lin_port : { SERIAL_LIN1, SERIAL_LIN2 }) { + p0->serial_clear(lin_port); + + for (int i = 0; i < 10; i++) { + uint8_t len = (rand() % LIN_MSG_MAX_LEN) + 1; + std::string lindata; + lindata.reserve(len); + + for (size_t j = 0; j < len; j++) + lindata += (const char)(rand() % 256); + + p0->serial_write(lin_port, lindata.c_str(), len); + Sleep(10); + + auto retdata = p0->serial_read(lin_port); + Assert::AreEqual(retdata, lindata); + } + } + } + }; +} \ No newline at end of file diff --git a/drivers/windows/pandaJ2534DLL Test/stdafx.cpp b/drivers/windows/pandaJ2534DLL Test/stdafx.cpp new file mode 100644 index 0000000000..84a1f0aaf3 --- /dev/null +++ b/drivers/windows/pandaJ2534DLL Test/stdafx.cpp @@ -0,0 +1,8 @@ +// stdafx.cpp : source file that includes just the standard includes +// pandaJ2534DLL Test.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + +// TODO: reference any additional headers you need in STDAFX.H +// and not in this file diff --git a/drivers/windows/pandaJ2534DLL Test/stdafx.h b/drivers/windows/pandaJ2534DLL Test/stdafx.h new file mode 100644 index 0000000000..1ac8bd8dcc --- /dev/null +++ b/drivers/windows/pandaJ2534DLL Test/stdafx.h @@ -0,0 +1,14 @@ +#pragma once + +#include "targetver.h" + +#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers +// Windows Header Files: +#include +#include + +// Headers for CppUnitTest +#include "CppUnitTest.h" +#include //Used for formatting in TestHelpers.cpp +#include +#include diff --git a/drivers/windows/pandaJ2534DLL Test/targetver.h b/drivers/windows/pandaJ2534DLL Test/targetver.h new file mode 100644 index 0000000000..87c0086de7 --- /dev/null +++ b/drivers/windows/pandaJ2534DLL Test/targetver.h @@ -0,0 +1,8 @@ +#pragma once + +// Including SDKDDKVer.h defines the highest available Windows platform. + +// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and +// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h. + +#include diff --git a/drivers/windows/pandaJ2534DLL/Action.h b/drivers/windows/pandaJ2534DLL/Action.h new file mode 100644 index 0000000000..e9721c2eda --- /dev/null +++ b/drivers/windows/pandaJ2534DLL/Action.h @@ -0,0 +1,57 @@ +#pragma once +#include + +#include "J2534Frame.h" + +class J2534Connection; + +/** +An Action represents a unit of work that can be scheduled for execution at a later time. +Actions are not guaranteed to be run at their specified time, but a best effort is made. +An Action will never execute early, but can execute later depending on what is in the +queus. +Many different operations are based on this base class. Instead of making a thread, +consider if the work can be offloaded to the Task Queue. +*/ +class Action +{ +public: + Action( + std::weak_ptr connection, + std::chrono::microseconds delay + ) : connection(connection), delay(delay) { }; + + Action( + std::weak_ptr connection + ) : connection(connection), delay(std::chrono::microseconds(0)) { }; + + //The function called by the task runner when this action is to be invoked. + virtual void execute() = 0; + + //Reschedule this Action for now(). + void scheduleImmediate() { + expire = std::chrono::steady_clock::now(); + } + + //Reschedule this Action relative to its last expiration time. + void scheduleDelay() { + expire += this->delay; + } + + //Reschedule this action {delay} after now(). + void scheduleImmediateDelay() { + expire = std::chrono::steady_clock::now() + this->delay; + } + + //Reschedule this Action based on a specific base time. + void schedule(std::chrono::time_point starttine, BOOL adddelayed) { + this->expire = starttine; + if (adddelayed) + expire += this->delay; + } + + std::weak_ptr connection; + std::chrono::microseconds delay; + //The timestamp at which point this Action is ready to be executed. + std::chrono::time_point expire; +}; diff --git a/drivers/windows/pandaJ2534DLL/J2534Connection.cpp b/drivers/windows/pandaJ2534DLL/J2534Connection.cpp new file mode 100644 index 0000000000..358158bcb4 --- /dev/null +++ b/drivers/windows/pandaJ2534DLL/J2534Connection.cpp @@ -0,0 +1,257 @@ +#include "stdafx.h" +#include "J2534Connection.h" +#include "Timer.h" + +J2534Connection::J2534Connection( + std::shared_ptr panda_dev, + unsigned long ProtocolID, + unsigned long Flags, + unsigned long BaudRate +) : panda_dev(panda_dev), ProtocolID(ProtocolID), Flags(Flags), BaudRate(BaudRate), port(0) { } + +unsigned long J2534Connection::validateTxMsg(PASSTHRU_MSG* msg) { + if (msg->DataSize < this->getMinMsgLen() || msg->DataSize > this->getMaxMsgLen()) + return ERR_INVALID_MSG; + return STATUS_NOERROR; +} + +long J2534Connection::PassThruReadMsgs(PASSTHRU_MSG *pMsg, unsigned long *pNumMsgs, unsigned long Timeout) { + //Timeout of 0 means return immediately. Non zero means WAIT for that time then return. Dafuk. + long err_code = STATUS_NOERROR; + Timer t = Timer(); + + unsigned long msgnum = 0; + while (msgnum < *pNumMsgs) { + if (Timeout > 0 && t.getTimePassed() >= Timeout) { + err_code = ERR_TIMEOUT; + break; + } + + //Synchronized won't work where we have to break out of a loop + messageRxBuff_mutex.lock(); + if (this->messageRxBuff.empty()) { + messageRxBuff_mutex.unlock(); + if (Timeout == 0) + break; + continue; + } + + auto msg_in = this->messageRxBuff.front(); + this->messageRxBuff.pop(); + messageRxBuff_mutex.unlock(); + + PASSTHRU_MSG *msg_out = &pMsg[msgnum++]; + msg_out->ProtocolID = this->ProtocolID; + msg_out->DataSize = msg_in.Data.size(); + memcpy(msg_out->Data, msg_in.Data.c_str(), msg_in.Data.size()); + msg_out->Timestamp = msg_in.Timestamp; + msg_out->RxStatus = msg_in.RxStatus; + msg_out->ExtraDataIndex = msg_in.ExtraDataIndex; + msg_out->TxFlags = 0; + if (msgnum == *pNumMsgs) break; + } + + if (msgnum == 0) + err_code = ERR_BUFFER_EMPTY; + *pNumMsgs = msgnum; + return err_code; +} + +long J2534Connection::PassThruWriteMsgs(PASSTHRU_MSG *pMsg, unsigned long *pNumMsgs, unsigned long Timeout) { + //There doesn't seem to be much reason to implement the timeout here. + for (int msgnum = 0; msgnum < *pNumMsgs; msgnum++) { + PASSTHRU_MSG* msg = &pMsg[msgnum]; + if (msg->ProtocolID != this->ProtocolID) { + *pNumMsgs = msgnum; + return ERR_MSG_PROTOCOL_ID; + } + + auto retcode = this->validateTxMsg(msg); + if (retcode != STATUS_NOERROR) { + *pNumMsgs = msgnum; + return retcode; + } + + auto msgtx = this->parseMessageTx(*pMsg); + if (msgtx != nullptr) //Nullptr is supported for unimplemented connection types. + this->schedultMsgTx(std::dynamic_pointer_cast(msgtx)); + } + return STATUS_NOERROR; +} + +//The docs say that a device has to support 10 periodic messages, though more is ok. +//It is easier to store them on the connection, so 10 per connection it is. +long J2534Connection::PassThruStartPeriodicMsg(PASSTHRU_MSG *pMsg, unsigned long *pMsgID, unsigned long TimeInterval) { + if (pMsg->DataSize < getMinMsgLen() || pMsg->DataSize > getMaxMsgSingleFrameLen()) return ERR_INVALID_MSG; + if (pMsg->ProtocolID != this->ProtocolID) return ERR_MSG_PROTOCOL_ID; + if (TimeInterval < 5 || TimeInterval > 65535) return ERR_INVALID_TIME_INTERVAL; + + for (int i = 0; i < this->periodicMessages.size(); i++) { + if (periodicMessages[i] != nullptr) continue; + + *pMsgID = i; + auto msgtx = this->parseMessageTx(*pMsg); + if (msgtx != nullptr) { + periodicMessages[i] = std::make_shared(std::chrono::microseconds(TimeInterval*1000), msgtx); + periodicMessages[i]->scheduleImmediate(); + if (auto panda_dev = this->getPandaDev()) { + panda_dev->insertActionIntoTaskList(periodicMessages[i]); + } + } + return STATUS_NOERROR; + } + return ERR_EXCEEDED_LIMIT; +} + +long J2534Connection::PassThruStopPeriodicMsg(unsigned long MsgID) { + if (MsgID >= this->periodicMessages.size() || this->periodicMessages[MsgID] == nullptr) + return ERR_INVALID_MSG_ID; + this->periodicMessages[MsgID]->cancel(); + this->periodicMessages[MsgID] = nullptr; + return STATUS_NOERROR; +} + +long J2534Connection::PassThruStartMsgFilter(unsigned long FilterType, PASSTHRU_MSG *pMaskMsg, PASSTHRU_MSG *pPatternMsg, + PASSTHRU_MSG *pFlowControlMsg, unsigned long *pFilterID) { + for (int i = 0; i < this->filters.size(); i++) { + if (filters[i] == nullptr) { + try { + auto newfilter = std::make_shared(this, FilterType, pMaskMsg, pPatternMsg, pFlowControlMsg); + for (int check_idx = 0; check_idx < filters.size(); check_idx++) { + if (filters[check_idx] == nullptr) continue; + if (filters[check_idx] == newfilter) { + filters[i] = nullptr; + return ERR_NOT_UNIQUE; + } + } + *pFilterID = i; + filters[i] = newfilter; + return STATUS_NOERROR; + } catch (int e) { + return e; + } + } + } + return ERR_EXCEEDED_LIMIT; +} + +long J2534Connection::PassThruStopMsgFilter(unsigned long FilterID) { + if (FilterID >= this->filters.size() || this->filters[FilterID] == nullptr) + return ERR_INVALID_FILTER_ID; + this->filters[FilterID] = nullptr; + return STATUS_NOERROR; +} + +long J2534Connection::PassThruIoctl(unsigned long IoctlID, void *pInput, void *pOutput) { + return STATUS_NOERROR; +} + +long J2534Connection::init5b(SBYTE_ARRAY* pInput, SBYTE_ARRAY* pOutput) { return STATUS_NOERROR; } +long J2534Connection::initFast(PASSTHRU_MSG* pInput, PASSTHRU_MSG* pOutput) { return STATUS_NOERROR; } +long J2534Connection::clearTXBuff() { return STATUS_NOERROR; } +long J2534Connection::clearRXBuff() { + synchronized(messageRxBuff_mutex) { + this->messageRxBuff = {}; + } + return STATUS_NOERROR; +} +long J2534Connection::clearPeriodicMsgs() { return STATUS_NOERROR; } +long J2534Connection::clearMsgFilters() { + for (auto& filter : this->filters) filter = nullptr; + return STATUS_NOERROR; +} + +void J2534Connection::setBaud(unsigned long baud) { + this->BaudRate = baud; +} + +void J2534Connection::schedultMsgTx(std::shared_ptr msgout) { + if (auto panda_ps = this->panda_dev.lock()) { + synchronized(staged_writes_lock) { + this->txbuff.push(msgout); + panda_ps->registerConnectionTx(shared_from_this()); + } + } +} + +void J2534Connection::rescheduleExistingTxMsgs() { + if (auto panda_ps = this->panda_dev.lock()) { + synchronized(staged_writes_lock) { + panda_ps->unstallConnectionTx(shared_from_this()); + } + } +} + +//Works well as long as the protocol doesn't support flow control. +void J2534Connection::processMessage(const J2534Frame& msg) { + FILTER_RESULT filter_res = FILTER_RESULT_NEUTRAL; + + for (auto filter : this->filters) { + if (filter == nullptr) continue; + FILTER_RESULT current_check_res = filter->check(msg); + if (current_check_res == FILTER_RESULT_BLOCK) return; + if (current_check_res == FILTER_RESULT_PASS) filter_res = FILTER_RESULT_PASS; + } + + if (filter_res == FILTER_RESULT_PASS) { + addMsgToRxQueue(msg); + } +} + +void J2534Connection::processIOCTLSetConfig(unsigned long Parameter, unsigned long Value) { + switch (Parameter) { + case DATA_RATE: // 5-500000 + this->setBaud(Value); + case LOOPBACK: // 0 (OFF), 1 (ON) [0] + this->loopback = (Value != 0); + break; + case ISO15765_WFT_MAX: + break; + case NODE_ADDRESS: // J1850PWM Related (Not supported by panda). HDS requires these to 'work'. + case NETWORK_LINE: + case P1_MIN: // A bunch of stuff relating to ISO9141 and ISO14230 that the panda + case P1_MAX: // currently doesn't support. Don't let HDS know we can't use these. + case P2_MIN: + case P2_MAX: + case P3_MIN: + case P3_MAX: + case P4_MIN: + case P4_MAX: + case W0: + case W1: + case W2: + case W3: + case W4: + case W5: + case TIDLE: + case TINIL: + case TWUP: + case PARITY: + case T1_MAX: // SCI related options. The panda does not appear to support this + case T2_MAX: + case T3_MAX: + case T4_MAX: + case T5_MAX: + break; // Just smile and nod. + default: + printf("Got unknown SET code %X\n", Parameter); + } +} + +unsigned long J2534Connection::processIOCTLGetConfig(unsigned long Parameter) { + switch (Parameter) { + case DATA_RATE: + return this->getBaud(); + case LOOPBACK: + return this->loopback; + break; + case BIT_SAMPLE_POINT: + return 80; + case SYNC_JUMP_WIDTH: + return 15; + default: + // HDS rarely reads off values through ioctl GET_CONFIG, but it often + // just wants the call to pass without erroring, so just don't do anything. + printf("Got unknown code %X\n", Parameter); + } +} diff --git a/drivers/windows/pandaJ2534DLL/J2534Connection.h b/drivers/windows/pandaJ2534DLL/J2534Connection.h new file mode 100644 index 0000000000..cdb215018b --- /dev/null +++ b/drivers/windows/pandaJ2534DLL/J2534Connection.h @@ -0,0 +1,141 @@ +#pragma once +#include "panda/panda.h" +#include "J2534_v0404.h" +#include "synchronize.h" +#include "J2534Frame.h" +#include "PandaJ2534Device.h" +#include "J2534MessageFilter.h" +#include "MessagePeriodic.h" + +class J2534Frame; +class Action; +class PandaJ2534Device; +class J2534MessageFilter; + +#define check_bmask(num, mask)(((num) & mask) == mask) + +/** +Class representing a generic J2534 Connection created by PassThruConnect, +and is associated with a channelID given to the J2534 API user. +Subclasses implement specific J2534 supported protocols. +*/ +class J2534Connection : public std::enable_shared_from_this { + friend class PandaJ2534Device; + +public: + J2534Connection( + std::shared_ptr panda_dev, + unsigned long ProtocolID, + unsigned long Flags, + unsigned long BaudRate + ); + virtual ~J2534Connection() {}; + + //J2534 API functions + + virtual long PassThruReadMsgs(PASSTHRU_MSG *pMsg, unsigned long *pNumMsgs, unsigned long Timeout); + long PassThruWriteMsgs(PASSTHRU_MSG *pMsg, unsigned long *pNumMsgs, unsigned long Timeout); + virtual long PassThruStartPeriodicMsg(PASSTHRU_MSG *pMsg, unsigned long *pMsgID, unsigned long TimeInterval); + virtual long PassThruStopPeriodicMsg(unsigned long MsgID); + + virtual long PassThruStartMsgFilter(unsigned long FilterType, PASSTHRU_MSG *pMaskMsg, PASSTHRU_MSG *pPatternMsg, + PASSTHRU_MSG *pFlowControlMsg, unsigned long *pFilterID); + + virtual long PassThruStopMsgFilter(unsigned long FilterID); + virtual long PassThruIoctl(unsigned long IoctlID, void *pInput, void *pOutput); + + //Functions for parsing messages to be send with PassThruWriteMsgs. + + virtual unsigned long validateTxMsg(PASSTHRU_MSG* msg); + virtual std::shared_ptr parseMessageTx(PASSTHRU_MSG& msg) { return nullptr; }; + + //IOCTL functions + + long init5b(SBYTE_ARRAY* pInput, SBYTE_ARRAY* pOutput); + long initFast(PASSTHRU_MSG* pInput, PASSTHRU_MSG* pOutput); + long clearTXBuff(); + long clearRXBuff(); + long clearPeriodicMsgs(); + long clearMsgFilters(); + + virtual void setBaud(unsigned long baud); + + unsigned long getBaud() { + return this->BaudRate; + } + + unsigned long getProtocol() { + return this->ProtocolID; + }; + + virtual bool isProtoCan() { + return FALSE; + } + + //Port is used in a protocol specific way to differentiate tranceivers. + unsigned long getPort() { + return this->port; + } + + virtual void processIOCTLSetConfig(unsigned long Parameter, unsigned long Value); + + virtual unsigned long processIOCTLGetConfig(unsigned long Parameter); + + //Called when the passthru device has received a message for this connection + //Loopback messages are processed separately. + virtual void processMessage(const J2534Frame& msg); + + //Limitations on message size. Override in every subclass. + + virtual unsigned long getMinMsgLen() { + return 1; + } + + virtual unsigned long getMaxMsgLen() { + return 4128; + } + + virtual unsigned long getMaxMsgSingleFrameLen() { + return 12; + } + + //Add an Action to the Task Queue for future processing. + //The task should be set its expire time before being submitted. + void schedultMsgTx(std::shared_ptr msgout); + + void rescheduleExistingTxMsgs(); + + std::shared_ptr getPandaDev() { + if (auto panda_dev_sp = this->panda_dev.lock()) + return panda_dev_sp; + return nullptr; + } + + //Add a message to the queue read by PassThruReadMsgs(). + void addMsgToRxQueue(const J2534Frame& frame) { + synchronized(messageRxBuff_mutex) { + messageRxBuff.push(frame); + } + } + + bool loopback = FALSE; + +protected: + unsigned long ProtocolID; + unsigned long Flags; + unsigned long BaudRate; + unsigned long port; + + std::weak_ptr panda_dev; + + Mutex messageRxBuff_mutex; + std::queue messageRxBuff; + + std::array, 10> filters; + std::queue> txbuff; + + std::array, 10> periodicMessages; + +private: + Mutex staged_writes_lock; +}; diff --git a/drivers/windows/pandaJ2534DLL/J2534Connection_CAN.cpp b/drivers/windows/pandaJ2534DLL/J2534Connection_CAN.cpp new file mode 100644 index 0000000000..342616900d --- /dev/null +++ b/drivers/windows/pandaJ2534DLL/J2534Connection_CAN.cpp @@ -0,0 +1,41 @@ +#include "stdafx.h" +#include "J2534Connection_CAN.h" +#include "MessageTx_CAN.h" +#include "Timer.h" + +J2534Connection_CAN::J2534Connection_CAN( + std::shared_ptr panda_dev, + unsigned long ProtocolID, + unsigned long Flags, + unsigned long BaudRate + ) : J2534Connection(panda_dev, ProtocolID, Flags, BaudRate) { + this->port = 0; + + if (BaudRate % 100 || BaudRate < 10000 || BaudRate > 5000000) + throw ERR_INVALID_BAUDRATE; + + panda_dev->panda->set_can_speed_cbps(panda::PANDA_CAN1, BaudRate/100); +}; + +unsigned long J2534Connection_CAN::validateTxMsg(PASSTHRU_MSG* msg) { + if ((msg->DataSize < this->getMinMsgLen() || msg->DataSize > this->getMaxMsgLen() || + (val_is_29bit(msg->TxFlags) != this->_is_29bit() && !check_bmask(this->Flags, CAN_ID_BOTH)))) + return ERR_INVALID_MSG; + return STATUS_NOERROR; +} + +std::shared_ptr J2534Connection_CAN::parseMessageTx(PASSTHRU_MSG& msg) { + return std::dynamic_pointer_cast(std::make_shared(shared_from_this(), msg)); +} + +void J2534Connection_CAN::setBaud(unsigned long BaudRate) { + if (auto panda_dev = this->getPandaDev()) { + if (BaudRate % 100 || BaudRate < 10000 || BaudRate > 5000000) + throw ERR_NOT_SUPPORTED; + + panda_dev->panda->set_can_speed_cbps(panda::PANDA_CAN1, (uint16_t)(BaudRate / 100)); + return J2534Connection::setBaud(BaudRate); + } else { + throw ERR_DEVICE_NOT_CONNECTED; + } +} diff --git a/drivers/windows/pandaJ2534DLL/J2534Connection_CAN.h b/drivers/windows/pandaJ2534DLL/J2534Connection_CAN.h new file mode 100644 index 0000000000..4dd950b390 --- /dev/null +++ b/drivers/windows/pandaJ2534DLL/J2534Connection_CAN.h @@ -0,0 +1,43 @@ +#pragma once + +#include "J2534Connection.h" +#include "panda/panda.h" + +#define val_is_29bit(num) check_bmask(num, CAN_29BIT_ID) + +class J2534Connection_CAN : public J2534Connection { +public: + J2534Connection_CAN( + std::shared_ptr panda_dev, + unsigned long ProtocolID, + unsigned long Flags, + unsigned long BaudRate + ); + + virtual unsigned long validateTxMsg(PASSTHRU_MSG* msg); + + virtual std::shared_ptr parseMessageTx(PASSTHRU_MSG& pMsg); + + virtual void setBaud(unsigned long baud); + + virtual unsigned long getMinMsgLen() { + return 4; + } + + virtual unsigned long getMaxMsgLen() { + return 12; + } + + virtual unsigned long getMaxMsgSingleFrameLen() { + return 12; + } + + virtual bool isProtoCan() { + return TRUE; + } + + bool _is_29bit() { + return (this->Flags & CAN_29BIT_ID) == CAN_29BIT_ID; + } + +}; \ No newline at end of file diff --git a/drivers/windows/pandaJ2534DLL/J2534Connection_ISO15765.cpp b/drivers/windows/pandaJ2534DLL/J2534Connection_ISO15765.cpp new file mode 100644 index 0000000000..2b9d97cb64 --- /dev/null +++ b/drivers/windows/pandaJ2534DLL/J2534Connection_ISO15765.cpp @@ -0,0 +1,229 @@ +#include "stdafx.h" +#include "J2534Connection_ISO15765.h" +#include "Timer.h" +#include "constants_ISO15765.h" +#include + +J2534Connection_ISO15765::J2534Connection_ISO15765( + std::shared_ptr panda_dev, + unsigned long ProtocolID, + unsigned long Flags, + unsigned long BaudRate +) : J2534Connection(panda_dev, ProtocolID, Flags, BaudRate), wftMax(0) { + this->port = 0; + + if (BaudRate % 100 || BaudRate < 10000 || BaudRate > 5000000) + throw ERR_INVALID_BAUDRATE; + + panda_dev->panda->set_can_speed_cbps(panda::PANDA_CAN1, (uint16_t)(BaudRate / 100)); +} + +unsigned long J2534Connection_ISO15765::validateTxMsg(PASSTHRU_MSG* msg) { + if ((msg->DataSize < this->getMinMsgLen() + (msg_is_extaddr(msg) ? 1 : 0) || + msg->DataSize > this->getMaxMsgLen() + (msg_is_extaddr(msg) ? 1 : 0) || + (val_is_29bit(msg->TxFlags) != this->_is_29bit() && !check_bmask(this->Flags, CAN_ID_BOTH)))) + return ERR_INVALID_MSG; + + int fid = get_matching_out_fc_filter_id(std::string((const char*)msg->Data, msg->DataSize), msg->TxFlags, 0xFFFFFFFF); + if (msg->DataSize > getMaxMsgSingleFrameLen() && fid == -1) return ERR_NO_FLOW_CONTROL; //11 bytes (4 for CANid, 7 payload) is max length of input frame. + + return STATUS_NOERROR; +} + +std::shared_ptr J2534Connection_ISO15765::parseMessageTx(PASSTHRU_MSG& msg) { + int fid = get_matching_out_fc_filter_id(std::string((const char*)msg.Data, msg.DataSize), msg.TxFlags, 0xFFFFFFFF); + if (msg.DataSize > getMaxMsgSingleFrameLen() && fid == -1) 1; + + return std::dynamic_pointer_cast( + std::make_shared(shared_from_this(), msg, (fid == -1) ? nullptr : this->filters[fid]) + ); +} + +//https://happilyembedded.wordpress.com/2016/02/15/can-multiple-frame-transmission/ +void J2534Connection_ISO15765::processMessage(const J2534Frame& msg) { + if (msg.ProtocolID != CAN) return; + + int fid = get_matching_in_fc_filter_id(msg); + if (fid == -1) return; + + auto filter = this->filters[fid]; + bool is_ext_addr = check_bmask(filter->flags, ISO15765_ADDR_TYPE); + uint8_t addrlen = is_ext_addr ? 5 : 4; + + switch (msg_get_type(msg, addrlen)) { + case FRAME_FLOWCTRL: + { + if (this->txbuff.size() == 0) + return; + if (msg.Data.size() < addrlen + 3) return; + uint8_t flow_status = msg.Data[addrlen] & 0x0F; + uint8_t block_size = msg.Data[addrlen + 1]; + uint8_t st_min = msg.Data[addrlen + 2]; + + auto txConvo = std::static_pointer_cast(this->txbuff.front()); + switch (flow_status) { + case FLOWCTRL_CONTINUE: { + if (st_min > 0xF9) break; + if (st_min >= 0xf1 && st_min <= 0xf9) { + txConvo->flowControlContinue(block_size, std::chrono::microseconds((st_min & 0x0F) * 100)); + } else if(st_min <= 0x7f) { + txConvo->flowControlContinue(block_size, std::chrono::microseconds(st_min * 1000)); + } else { + break; + } + txConvo->scheduleImmediate(); + this->rescheduleExistingTxMsgs(); + break; + } + case FLOWCTRL_WAIT: + txConvo->flowControlWait(this->wftMax); + break; + case FLOWCTRL_ABORT: + txConvo->flowControlAbort(); + break; + } + break; + } + case FRAME_SINGLE: + { + this->rxConversations[fid] = nullptr; //Reset any current transaction. + + if (is_ext_addr) { + if ((msg.Data[5] & 0x0F) > 6) return; + } else { + if ((msg.Data[4] & 0x0F) > 7) return; + } + + J2534Frame outframe(ISO15765, msg.RxStatus, 0, msg.Timestamp); + if (msg.Data.size() != 8 && check_bmask(this->Flags, ISO15765_FRAME_PAD)) + outframe.RxStatus |= ISO15765_PADDING_ERROR; + if (is_ext_addr) + outframe.RxStatus |= ISO15765_ADDR_TYPE; + outframe.Data = msg.Data.substr(0, addrlen) + msg.Data.substr(addrlen + 1, msg.Data[addrlen]); + outframe.ExtraDataIndex = outframe.Data.size(); + + addMsgToRxQueue(outframe); + break; + } + case FRAME_FIRST: + { + if (msg.Data.size() < 12) { + //A frame was received that could have held more data. + //No examples of this protocol show that happening, so + //it will be assumed that it is grounds to reset rx. + this->rxConversations[fid] = nullptr; + return; + } + + J2534Frame outframe(ISO15765, msg.RxStatus | START_OF_MESSAGE, 0, msg.Timestamp); + if (is_ext_addr) + outframe.RxStatus |= ISO15765_ADDR_TYPE; + outframe.Data = msg.Data.substr(0, addrlen); + + addMsgToRxQueue(outframe); + + this->rxConversations[fid] = std::make_shared( + ((msg.Data[addrlen] & 0x0F) << 8) | msg.Data[addrlen + 1], + msg.Data.substr(addrlen + 2, 12 - (addrlen + 2)), + msg.RxStatus, filter); + + //TODO maybe the flow control should also be scheduled in the TX list. + //Doing it this way because the filter can be 5 bytes in ext address mode. + std::string flowfilter = filter->get_flowctrl(); + uint32_t flow_addr = (((uint8_t)flowfilter[0]) << 24) | ((uint8_t)(flowfilter[1]) << 16) | ((uint8_t)(flowfilter[2]) << 8) | ((uint8_t)flowfilter[3]); + + std::string flowstrlresp; + if (flowfilter.size() > 4) + flowstrlresp += flowfilter[4]; + flowstrlresp += std::string("\x30\x00\x00", 3); + + if (auto panda_dev_sp = this->panda_dev.lock()) { + panda_dev_sp->panda->can_send(flow_addr, val_is_29bit(msg.RxStatus), (const uint8_t *)flowstrlresp.c_str(), (uint8_t)flowstrlresp.size(), panda::PANDA_CAN1); + } + break; + } + case FRAME_CONSEC: + { + auto& convo = this->rxConversations[fid]; + if (convo == nullptr) return; + + if (!convo->rx_add_frame(msg.Data[addrlen], (is_ext_addr ? 6 : 7), msg.Data.substr(addrlen + 1))) { + //Delete this conversation. + convo = nullptr; + return; + } + + std::string final_msg; + if (convo->flush_result(final_msg)) { + convo = nullptr; + J2534Frame outframe(ISO15765, msg.RxStatus, 0, msg.Timestamp); + if (is_ext_addr) + outframe.RxStatus |= ISO15765_ADDR_TYPE; + outframe.Data = msg.Data.substr(0, addrlen) + final_msg; + outframe.ExtraDataIndex = outframe.Data.size(); + + addMsgToRxQueue(outframe); + } + break; + } + } +} + +void J2534Connection_ISO15765::setBaud(unsigned long BaudRate) { + if (auto panda_dev = this->getPandaDev()) { + if (BaudRate % 100 || BaudRate < 10000 || BaudRate > 5000000) + throw ERR_NOT_SUPPORTED; + + panda_dev->panda->set_can_speed_cbps(panda::PANDA_CAN1, (uint16_t)(BaudRate / 100)); + return J2534Connection::setBaud(BaudRate); + } else { + throw ERR_DEVICE_NOT_CONNECTED; + } +} + +long J2534Connection_ISO15765::PassThruStartMsgFilter(unsigned long FilterType, PASSTHRU_MSG *pMaskMsg, PASSTHRU_MSG *pPatternMsg, + PASSTHRU_MSG *pFlowControlMsg, unsigned long *pFilterID) { + + if (FilterType != FLOW_CONTROL_FILTER) return ERR_INVALID_FILTER_ID; + return J2534Connection::PassThruStartMsgFilter(FilterType, pMaskMsg, pPatternMsg, pFlowControlMsg, pFilterID); +} + +int J2534Connection_ISO15765::get_matching_out_fc_filter_id(const std::string& msgdata, unsigned long flags, unsigned long flagmask) { + for (unsigned int i = 0; i < this->filters.size(); i++) { + if (this->filters[i] == nullptr) continue; + auto filter = this->filters[i]->get_flowctrl(); + if (filter == msgdata.substr(0, filter.size()) && + (this->filters[i]->flags & flagmask) == (flags & flagmask)) + return i; + } + return -1; +} + +int J2534Connection_ISO15765::get_matching_in_fc_filter_id(const J2534Frame& msg, unsigned long flagmask) { + for (unsigned int i = 0; i < this->filters.size(); i++) { + if (this->filters[i] == nullptr) continue; + if (this->filters[i]->check(msg) == FILTER_RESULT_MATCH && + (this->filters[i]->flags & flagmask) == (msg.RxStatus & flagmask)) + return i; + } + return -1; +} + +void J2534Connection_ISO15765::processIOCTLSetConfig(unsigned long Parameter, unsigned long Value) { + switch (Parameter) { + case ISO15765_WFT_MAX: + this->wftMax = Value; + break; + default: + J2534Connection::processIOCTLSetConfig(Parameter, Value); + } +} + +unsigned long J2534Connection_ISO15765::processIOCTLGetConfig(unsigned long Parameter) { + switch (Parameter) { + case ISO15765_WFT_MAX: + return this->wftMax; + default: + return J2534Connection::processIOCTLGetConfig(Parameter); + } +} diff --git a/drivers/windows/pandaJ2534DLL/J2534Connection_ISO15765.h b/drivers/windows/pandaJ2534DLL/J2534Connection_ISO15765.h new file mode 100644 index 0000000000..ddbf2dc2aa --- /dev/null +++ b/drivers/windows/pandaJ2534DLL/J2534Connection_ISO15765.h @@ -0,0 +1,65 @@ +#pragma once +#include +#include "J2534Connection.h" +#include "J2534Connection_CAN.h" +#include "MessageTx_ISO15765.h" +#include "MessageRx.h" + +class MessageTx_ISO15765; + +typedef struct { + std::string dispatched_msg; + std::string remaining_payload; +} PRESTAGED_WRITE; + +class J2534Connection_ISO15765 : public J2534Connection { +public: + J2534Connection_ISO15765( + std::shared_ptr panda_dev, + unsigned long ProtocolID, + unsigned long Flags, + unsigned long BaudRate + ); + + virtual long PassThruStartMsgFilter(unsigned long FilterType, PASSTHRU_MSG * pMaskMsg, PASSTHRU_MSG * pPatternMsg, PASSTHRU_MSG * pFlowControlMsg, unsigned long * pFilterID); + + int get_matching_out_fc_filter_id(const std::string & msgdata, unsigned long flags, unsigned long flagmask); + + int get_matching_in_fc_filter_id(const J2534Frame& msg, unsigned long flagmask = CAN_29BIT_ID); + + virtual unsigned long validateTxMsg(PASSTHRU_MSG* msg); + + virtual std::shared_ptr parseMessageTx(PASSTHRU_MSG& msg); + + virtual void processMessage(const J2534Frame& msg); + + virtual void setBaud(unsigned long baud); + + virtual void processIOCTLSetConfig(unsigned long Parameter, unsigned long Value); + + virtual unsigned long processIOCTLGetConfig(unsigned long Parameter); + + virtual unsigned long getMinMsgLen() { + return 4; + } + + virtual unsigned long getMaxMsgLen() { + return 4099; + }; + + virtual unsigned long getMaxMsgSingleFrameLen() { + return 11; + } + + virtual bool _is_29bit() { + return (this->Flags & CAN_29BIT_ID) == CAN_29BIT_ID; + } + + virtual bool isProtoCan() { + return TRUE; + } + +private: + std::array, 10> rxConversations; + unsigned int wftMax; +}; diff --git a/drivers/windows/pandaJ2534DLL/J2534Frame.h b/drivers/windows/pandaJ2534DLL/J2534Frame.h new file mode 100644 index 0000000000..5c991c5082 --- /dev/null +++ b/drivers/windows/pandaJ2534DLL/J2534Frame.h @@ -0,0 +1,48 @@ +#pragma once +#include "J2534_v0404.h" +#include "panda/panda.h" + +/*A move convenient container for J2534 Messages than the static buffer provided by default.*/ +class J2534Frame { +public: + J2534Frame(unsigned long ProtocolID, unsigned long RxStatus=0, unsigned long TxFlags=0, unsigned long Timestamp=0) : + ProtocolID(ProtocolID), RxStatus(RxStatus), TxFlags(TxFlags), Timestamp(Timestamp), ExtraDataIndex(0), Data("") { }; + + J2534Frame(const panda::PANDA_CAN_MSG& msg_in) { + ProtocolID = CAN; + ExtraDataIndex = 0; + Data.reserve(msg_in.len + 4); + Data += msg_in.addr >> 24; + Data += (msg_in.addr >> 16) & 0xFF; + Data += (msg_in.addr >> 8) & 0xFF; + Data += msg_in.addr & 0xFF; + Data += std::string((char*)&msg_in.dat, msg_in.len); + Timestamp = msg_in.recv_time; + RxStatus = (msg_in.addr_29b ? CAN_29BIT_ID : 0) | + (msg_in.is_receipt ? TX_MSG_TYPE : 0); + } + + J2534Frame(const PASSTHRU_MSG& msg) { + this->ProtocolID = msg.ProtocolID; + this->RxStatus = msg.RxStatus; + this->TxFlags = msg.TxFlags; + this->Timestamp = msg.Timestamp; + this->ExtraDataIndex = msg.ExtraDataIndex; + this->Data = std::string((const char*)msg.Data, msg.DataSize); + } + + J2534Frame() { + this->ProtocolID = 0; + this->RxStatus = 0; + this->TxFlags = 0; + this->Timestamp = 0; + this->ExtraDataIndex = 0; + } + + unsigned long ProtocolID; + unsigned long RxStatus; + unsigned long TxFlags; + unsigned long Timestamp; + unsigned long ExtraDataIndex; + std::string Data; +}; \ No newline at end of file diff --git a/drivers/windows/pandaJ2534DLL/J2534MessageFilter.cpp b/drivers/windows/pandaJ2534DLL/J2534MessageFilter.cpp new file mode 100644 index 0000000000..2d19e1f4e5 --- /dev/null +++ b/drivers/windows/pandaJ2534DLL/J2534MessageFilter.cpp @@ -0,0 +1,104 @@ +#include "stdafx.h" +#include "J2534MessageFilter.h" +#include "J2534Frame.h" + +J2534MessageFilter::J2534MessageFilter( + J2534Connection *const conn, + unsigned int filtertype, + PASSTHRU_MSG *pMaskMsg, + PASSTHRU_MSG *pPatternMsg, + PASSTHRU_MSG *pFlowControlMsg +) : filtertype(filtertype), flags(0), conn(conn) { + switch (filtertype) { + case PASS_FILTER: + case BLOCK_FILTER: + if (pMaskMsg == NULL || pPatternMsg == NULL) + throw ERR_NULL_PARAMETER; + if (pFlowControlMsg != NULL) + throw ERR_INVALID_FILTER_ID; + if (pMaskMsg->DataSize != pPatternMsg->DataSize) + throw ERR_INVALID_MSG; + break; + case FLOW_CONTROL_FILTER: + if (conn->getProtocol() != ISO15765) throw ERR_MSG_PROTOCOL_ID; //CHECK + if (pFlowControlMsg == NULL || pMaskMsg == NULL || pPatternMsg == NULL) + throw ERR_NULL_PARAMETER; + break; + default: + throw ERR_INVALID_MSG; + } + + if (!(conn->getMinMsgLen() < pMaskMsg->DataSize || pMaskMsg->DataSize < conn->getMaxMsgLen())) + throw ERR_INVALID_MSG; + if (conn->getProtocol() != pMaskMsg->ProtocolID) + throw ERR_MSG_PROTOCOL_ID; + this->maskMsg = std::string((char*)pMaskMsg->Data, pMaskMsg->DataSize); + + if (!(conn->getMinMsgLen() < pPatternMsg->DataSize || pPatternMsg->DataSize < conn->getMaxMsgLen())) + throw ERR_INVALID_MSG; + if (conn->getProtocol() != pPatternMsg->ProtocolID) + throw ERR_MSG_PROTOCOL_ID; + this->patternMsg = std::string((char*)pPatternMsg->Data, pPatternMsg->DataSize); + if (this->maskMsg.size() != this->patternMsg.size()) + throw ERR_INVALID_MSG; + + if (pFlowControlMsg) { + if (!(conn->getMinMsgLen() < pFlowControlMsg->DataSize || pFlowControlMsg->DataSize < conn->getMaxMsgLen())) + throw ERR_INVALID_MSG; + if (conn->getProtocol() != pFlowControlMsg->ProtocolID) + throw ERR_MSG_PROTOCOL_ID; + if (pMaskMsg->TxFlags != pPatternMsg->TxFlags || pMaskMsg->TxFlags != pFlowControlMsg->TxFlags) + throw ERR_INVALID_MSG; + if(pFlowControlMsg->TxFlags & ~(ISO15765_FRAME_PAD | CAN_29BIT_ID | ISO15765_ADDR_TYPE)) + throw ERR_INVALID_MSG; + if ((pFlowControlMsg->TxFlags & ISO15765_ADDR_TYPE) == ISO15765_ADDR_TYPE) { + if(pFlowControlMsg->DataSize != 5) + throw ERR_INVALID_MSG; + } else { + if (pFlowControlMsg->DataSize != 4) + throw ERR_INVALID_MSG; + } + this->flowCtrlMsg = std::string((char*)pFlowControlMsg->Data, pFlowControlMsg->DataSize); + if (this->flowCtrlMsg.size() != this->patternMsg.size()) + throw ERR_INVALID_MSG; + this->flags = pFlowControlMsg->TxFlags; + } +} + +bool J2534MessageFilter::operator ==(const J2534MessageFilter &b) const { + if (this->filtertype != b.filtertype) return FALSE; + if (this->maskMsg != b.maskMsg) return FALSE; + if (this->patternMsg != b.patternMsg) return FALSE; + if (this->flowCtrlMsg != b.flowCtrlMsg) return FALSE; + if (this->flags != b.flags) return FALSE; + return TRUE; +} + +FILTER_RESULT J2534MessageFilter::check(const J2534Frame& msg) { + bool matches = TRUE; + if (msg.Data.size() < this->maskMsg.size()) { + matches = FALSE; + } else { + for (int i = 0; i < this->maskMsg.size(); i++) { + if (this->patternMsg[i] != (msg.Data[i] & this->maskMsg[i])) { + matches = FALSE; + break; + } + } + } + + switch (this->filtertype) { + case PASS_FILTER: + return matches ? FILTER_RESULT_PASS : FILTER_RESULT_NEUTRAL; + case BLOCK_FILTER: + return matches ? FILTER_RESULT_BLOCK: FILTER_RESULT_NEUTRAL; + case FLOW_CONTROL_FILTER: + return matches ? FILTER_RESULT_MATCH : FILTER_RESULT_NOMATCH; + default: + throw std::out_of_range("Filtertype should not be able to be anything but PASS, BLOCK, or FLOW_CONTROL"); + } +} + +std::string J2534MessageFilter::get_flowctrl() { + return std::string(this->flowCtrlMsg); +} diff --git a/drivers/windows/pandaJ2534DLL/J2534MessageFilter.h b/drivers/windows/pandaJ2534DLL/J2534MessageFilter.h new file mode 100644 index 0000000000..c5e9a68390 --- /dev/null +++ b/drivers/windows/pandaJ2534DLL/J2534MessageFilter.h @@ -0,0 +1,47 @@ +#pragma once +#include "J2534_v0404.h" +#include "J2534Connection.h" +#include "J2534Frame.h" + +typedef enum { + FILTER_RESULT_BLOCK, + FILTER_RESULT_NEUTRAL, + FILTER_RESULT_PASS, + FILTER_RESULT_NOMATCH = FILTER_RESULT_BLOCK, + FILTER_RESULT_MATCH = FILTER_RESULT_PASS, +} FILTER_RESULT; + +//Forward declare +class J2534Connection; + +/* Represents a J2534 Message Filter created by PassThruStartMsgFilter. + +J2534 uses filters to sort out messages in a simple and sane way. Except for +flow control filters. J2534 v04.04 uses filters to manage 'conversations' in +protocols that support flow control like ISO15765. The whole solution is a +hack, and J2534 v05.00 greatly simplifies this concept. But we are using +v04.04 so, here we are. +*/ +class J2534MessageFilter { +public: + J2534MessageFilter( + J2534Connection *const conn, + unsigned int filtertype, + PASSTHRU_MSG *pMaskMsg, + PASSTHRU_MSG *pPatternMsg, + PASSTHRU_MSG *pFlowControlMsg + ); + + bool J2534MessageFilter::operator ==(const J2534MessageFilter &b) const; + + FILTER_RESULT check(const J2534Frame& msg); + std::string get_flowctrl(); + + unsigned long flags; + J2534Connection *const conn; +private: + unsigned int filtertype; + std::string maskMsg; + std::string patternMsg; + std::string flowCtrlMsg; +}; \ No newline at end of file diff --git a/drivers/windows/pandaJ2534DLL/J2534_v0404.h b/drivers/windows/pandaJ2534DLL/J2534_v0404.h new file mode 100644 index 0000000000..7cccf6b429 --- /dev/null +++ b/drivers/windows/pandaJ2534DLL/J2534_v0404.h @@ -0,0 +1,428 @@ +// +// Copyright (c) 2015-2016 DashLogic, Inc. +// All Rights Reserved. +// +// http://www.dashlogic.com +// sales@dashlogic.com +// +// Redistribution and use in source and binary forms, with or without +// modification, including use for commercial purposes, 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 the copyright holder nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// 4. Redistributions of any form whatsoever must retain the following +// acknowledgment: 'This product includes software developed by +// "DashLogic, Inc." (http://www.dashlogic.com/).' +// +// 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. +// + + +// +// Formatting: +// Indents: Use tabs only (1 tab per indent) +// Tab Size: 4 spaces +// +// File Revision: +// $Rev: 5216 $ +// $Date: 2016-03-15 09:32:34 -0600 (Tue, 15 Mar 2016) $ +// + +#pragma once + +#ifdef PANDAJ2534DLL_EXPORTS +#define PANDAJ2534DLL_API extern "C" __declspec(dllexport) +#else +#define PANDAJ2534DLL_API +//__declspec(dllimport) +#endif + +// +// Platform-specific Defines: +// +// PTAPI: Define this yourself if you want a specific calling +// convention or other modifiers on the Pass-Thru API +// functions. Typically, on Windows, PTAPI will be defined +// as WINAPI, which enables the __stdcall convention. +// +#define PTAPI __stdcall //WINAPI + +// +// J2534-1 v04.04 ProtocolID Values +// +#define J1850VPW 0x01 +#define J1850PWM 0x02 +#define ISO9141 0x03 +#define ISO14230 0x04 +#define CAN 0x05 +#define ISO15765 0x06 +#define SCI_A_ENGINE 0x07 +#define SCI_A_TRANS 0x08 +#define SCI_B_ENGINE 0x09 +#define SCI_B_TRANS 0x0A + + +// +// J2534-2 ProtocolID Values +// +#define J1850VPW_PS 0x00008000 +#define J1850PWM_PS 0x00008001 +#define ISO9141_PS 0x00008002 +#define ISO14230_PS 0x00008003 +#define CAN_PS 0x00008004 +#define ISO15765_PS 0x00008005 +#define J2610_PS 0x00008006 +#define SW_ISO15765_PS 0x00008007 +#define SW_CAN_PS 0x00008008 +#define GM_UART_PS 0x00008009 +#define CAN_CH1 0x00009000 +#define CAN_CH2 (CAN_CH1 + 1) +#define CAN_CH128 (CAN_CH1 + 127) +#define J1850VPW_CH1 0x00009080 +#define J1850VPW_CH2 (J1850VPW_CH1 + 1) +#define J1850VPW_CH128 (J1850VPW_CH1 + 127) +#define J1850PWM_CH1 0x00009160 +#define J1850PWM_CH2 (J1850PWM_CH1 + 1) +#define J1850PWM_CH128 (J1850PWM_CH1 + 127) +#define ISO9141_CH1 0x00009240 +#define ISO9141_CH2 (ISO9141_CH1 + 1) +#define ISO9141_CH128 (ISO9141_CH1 + 127) +#define ISO14230_CH1 0x00009320 +#define ISO14230_CH2 (ISO14230_CH1 + 1) +#define ISO14230_CH128 (ISO14230_CH1 + 127) +#define ISO15765_CH1 0x00009400 +#define ISO15765_CH2 (ISO15765_CH1 + 1) +#define ISO15765_CH128 (ISO15765_CH1 + 127) +#define SW_CAN_CAN_CH1 0x00009480 +#define SW_CAN_CAN_CH2 (SW_CAN_CAN_CH1 + 1) +#define SW_CAN_CAN_CH128 (SW_CAN_CAN_CH1 + 127) +#define SW_CAN_ISO15765_CH1 0x00009560 +#define SW_CAN_ISO15765_CH2 (SW_CAN_ISO15765_CH1 + 1) +#define SW_CAN_ISO15765_CH128 (SW_CAN_ISO15765_CH1 + 127) +#define J2610_CH1 0x00009640 +#define J2610_CH2 (J2610_CH1 + 1) +#define J2610_CH128 (J2610_CH1 + 127) +#define ANALOG_IN_CH1 0x0000C000 +#define ANALOG_IN_CH2 0x0000C001 +#define ANALOG_IN_CH32 0x0000C01F + + +// +// J2534-1 v04.04 Error Values +// +#define STATUS_NOERROR 0x00 // Function call successful. +#define ERR_NOT_SUPPORTED 0x01 // Device cannot support requested functionality mandated in J2534. Device is not fully SAE J2534 compliant. +#define ERR_INVALID_CHANNEL_ID 0x02 // Invalid ChannelID value. +#define ERR_INVALID_PROTOCOL_ID 0x03 // Invalid or unsupported ProtocolID, or there is a resource conflict (i.e. trying to connect to multiple mutually exclusive protocols such as J1850PWM and J1850VPW, or CAN and SCI, etc.). +#define ERR_NULL_PARAMETER 0x04 // NULL pointer supplied where a valid pointer is required. +#define ERR_INVALID_IOCTL_VALUE 0x05 // Invalid value for Ioctl parameter. +#define ERR_INVALID_FLAGS 0x06 // Invalid flag values. +#define ERR_FAILED 0x07 // Undefined error, use PassThruGetLastError() for text description. +#define ERR_DEVICE_NOT_CONNECTED 0x08 // Unable to communicate with device. +#define ERR_TIMEOUT 0x09 // Read or write timeout: + // PassThruReadMsgs() - No message available to read or could not read the specified number of messages. The actual number of messages read is placed in . + // PassThruWriteMsgs() - Device could not write the specified number of messages. The actual number of messages sent on the vehicle network is placed in . +#define ERR_INVALID_MSG 0x0A // Invalid message structure pointed to by pMsg. +#define ERR_INVALID_TIME_INTERVAL 0x0B // Invalid TimeInterval value. +#define ERR_EXCEEDED_LIMIT 0x0C // Exceeded maximum number of message IDs or allocated space. +#define ERR_INVALID_MSG_ID 0x0D // Invalid MsgID value. +#define ERR_DEVICE_IN_USE 0x0E // Device is currently open. +#define ERR_INVALID_IOCTL_ID 0x0F // Invalid IoctlID value. +#define ERR_BUFFER_EMPTY 0x10 // Protocol message buffer empty, no messages available to read. +#define ERR_BUFFER_FULL 0x11 // Protocol message buffer full. All the messages specified may not have been transmitted. +#define ERR_BUFFER_OVERFLOW 0x12 // Indicates a buffer overflow occurred and messages were lost. +#define ERR_PIN_INVALID 0x13 // Invalid pin number, pin number already in use, or voltage already applied to a different pin. +#define ERR_CHANNEL_IN_USE 0x14 // Channel number is currently connected. +#define ERR_MSG_PROTOCOL_ID 0x15 // Protocol type in the message does not match the protocol associated with the Channel ID +#define ERR_INVALID_FILTER_ID 0x16 // Invalid Filter ID value. +#define ERR_NO_FLOW_CONTROL 0x17 // No flow control filter set or matched (for ProtocolID ISO15765 only). +#define ERR_NOT_UNIQUE 0x18 // A CAN ID in pPatternMsg or pFlowControlMsg matches either ID in an existing FLOW_CONTROL_FILTER +#define ERR_INVALID_BAUDRATE 0x19 // The desired baud rate cannot be achieved within the tolerance specified in SAE J2534-1 Section 6.5 +#define ERR_INVALID_DEVICE_ID 0x1A // Device ID invalid. + + +// +// J2534-1 v04.04 Connect Flags +// +#define CAN_29BIT_ID 0x0100 +#define ISO9141_NO_CHECKSUM 0x0200 +#define CAN_ID_BOTH 0x0800 +#define ISO9141_K_LINE_ONLY 0x1000 + + +// +// J2534-1 v04.04 Filter Type Values +// +#define PASS_FILTER 0x00000001 +#define BLOCK_FILTER 0x00000002 +#define FLOW_CONTROL_FILTER 0x00000003 + + +// +// J2534-1 v04.04 Programming Voltage Pin Numbers +// +#define AUXILIARY_OUTPUT_PIN 0 +#define SAE_J1962_CONNECTOR_PIN_6 6 +#define SAE_J1962_CONNECTOR_PIN_9 9 +#define SAE_J1962_CONNECTOR_PIN_11 11 +#define SAE_J1962_CONNECTOR_PIN_12 12 +#define SAE_J1962_CONNECTOR_PIN_13 13 +#define SAE_J1962_CONNECTOR_PIN_14 14 +#define SAE_J1962_CONNECTOR_PIN_15 15 // Short to ground only + + +// +// J2534-1 v04.04 Programming Voltage Values +// +#define SHORT_TO_GROUND 0xFFFFFFFE +#define VOLTAGE_OFF 0xFFFFFFFF + + +// +// J2534-1 v04.04 API Version Values +// +#define J2534_APIVER_FEBRUARY_2002 "02.02" +#define J2534_APIVER_NOVEMBER_2004 "04.04" + + +// +// J2534-1 v04.04 IOCTL ID Values +// +#define GET_CONFIG 0x01 // pInput = SCONFIG_LIST, pOutput = NULL +#define SET_CONFIG 0x02 // pInput = SCONFIG_LIST, pOutput = NULL +#define READ_VBATT 0x03 // pInput = NULL, pOutput = unsigned long +#define FIVE_BAUD_INIT 0x04 // pInput = SBYTE_ARRAY, pOutput = SBYTE_ARRAY +#define FAST_INIT 0x05 // pInput = PASSTHRU_MSG, pOutput = PASSTHRU_MSG +#define CLEAR_TX_BUFFER 0x07 // pInput = NULL, pOutput = NULL +#define CLEAR_RX_BUFFER 0x08 // pInput = NULL, pOutput = NULL +#define CLEAR_PERIODIC_MSGS 0x09 // pInput = NULL, pOutput = NULL +#define CLEAR_MSG_FILTERS 0x0A // pInput = NULL, pOutput = NULL +#define CLEAR_FUNCT_MSG_LOOKUP_TABLE 0x0B // pInput = NULL, pOutput = NULL +#define ADD_TO_FUNCT_MSG_LOOKUP_TABLE 0x0C // pInput = SBYTE_ARRAY, pOutput = NULL +#define DELETE_FROM_FUNCT_MSG_LOOKUP_TABLE 0x0D // pInput = SBYTE_ARRAY, pOutput = NULL +#define READ_PROG_VOLTAGE 0x0E // pInput = NULL, pOutput = unsigned long + + +// +// J2534-2 IOCTL ID Values +// +#define SW_CAN_HS 0x00008000 // pInput = NULL, pOutput = NULL +#define SW_CAN_NS 0x00008001 // pInput = NULL, pOutput = NULL +#define SET_POLL_RESPONSE 0x00008002 // pInput = SBYTE_ARRAY, pOutput = NULL +#define BECOME_MASTER 0x00008003 // pInput = unsigned char, pOutput = NULL + + +// +// J2534-1 v04.04 Configuration Parameter Values +// Default value is enclosed in square brackets "[" and "]" +// +#define DATA_RATE 0x01 // 5-500000 +#define LOOPBACK 0x03 // 0 (OFF), 1 (ON) [0] +#define NODE_ADDRESS 0x04 // J1850PWM: 0x00-0xFF +#define NETWORK_LINE 0x05 // J1850PWM: 0 (BUS_NORMAL), 1 (BUS_PLUS), 2 (BUS_MINUS) [0] +#define P1_MIN 0x06 // ISO9141 or ISO14230: Not used by interface +#define P1_MAX 0x07 // ISO9141 or ISO14230: 0x1-0xFFFF (.5 ms per bit) [40 (20ms)] +#define P2_MIN 0x08 // ISO9141 or ISO14230: Not used by interface +#define P2_MAX 0x09 // ISO9141 or ISO14230: Not used by interface +#define P3_MIN 0x0A // ISO9141 or ISO14230: 0x0-0xFFFF (.5 ms per bit) [110 (55ms)] +#define P3_MAX 0x0B // ISO9141 or ISO14230: Not used by interface +#define P4_MIN 0x0C // ISO9141 or ISO14230: 0x0-0xFFFF (.5 ms per bit) [10 (5ms)] +#define P4_MAX 0x0D // ISO9141 or ISO14230: Not used by interface +#define W0 0x19 // ISO9141: 0x0-0xFFFF (1 ms per bit) [300] +#define W1 0x0E // ISO9141 or ISO14230: 0x0-0xFFFF (1 ms per bit) [300] +#define W2 0x0F // ISO9141 or ISO14230: 0x0-0xFFFF (1 ms per bit) [20] +#define W3 0x10 // ISO9141 or ISO14230: 0x0-0xFFFF (1 ms per bit) [20] +#define W4 0x11 // ISO9141 or ISO14230: 0x0-0xFFFF (1 ms per bit) [50] +#define W5 0x12 // ISO9141 or ISO14230: 0x0-0xFFFF (1 ms per bit) [300] +#define TIDLE 0x13 // ISO9141 or ISO14230: 0x0-0xFFFF (1 ms per bit) [300] +#define TINIL 0x14 // ISO9141 or ISO14230: 0x0-0xFFFF (1 ms per bit) [25] +#define TWUP 0x15 // ISO9141 or ISO14230: 0x0-0xFFFF (1 ms per bit) [50] +#define PARITY 0x16 // ISO9141 or ISO14230: 0 (NO_PARITY), 1 (ODD_PARITY), 2 (EVEN_PARITY) [0] +#define BIT_SAMPLE_POINT 0x17 // CAN: 0-100 (1% per bit) [80] +#define SYNC_JUMP_WIDTH 0x18 // CAN: 0-100 (1% per bit) [15] +#define T1_MAX 0x1A // SCI: 0x0-0xFFFF (1 ms per bit) [20] +#define T2_MAX 0x1B // SCI: 0x0-0xFFFF (1 ms per bit) [100] +#define T3_MAX 0x24 // SCI: 0x0-0xFFFF (1 ms per bit) [50] +#define T4_MAX 0x1C // SCI: 0x0-0xFFFF (1 ms per bit) [20] +#define T5_MAX 0x1D // SCI: 0x0-0xFFFF (1 ms per bit) [100] +#define ISO15765_BS 0x1E // ISO15765: 0x0-0xFF [0] +#define ISO15765_STMIN 0x1F // ISO15765: 0x0-0xFF [0] +#define ISO15765_BS_TX 0x22 // ISO15765: 0x0-0xFF,0xFFFF [0xFFFF] +#define ISO15765_STMIN_TX 0x23 // ISO15765: 0x0-0xFF,0xFFFF [0xFFFF] +#define DATA_BITS 0x20 // ISO9141 or ISO14230: 0 (8 data bits), 1 (7 data bits) [0] +#define FIVE_BAUD_MOD 0x21 // ISO9141 or ISO14230: 0 (ISO 9141-2/14230-4), 1 (Inv KB2), 2 (Inv Addr), 3 (ISO 9141) [0] +#define ISO15765_WFT_MAX 0x25 // ISO15765: 0x0-0xFF [0] + + +// +// J2534-2 Configuration Parameter Values +// Default value is enclosed in square brackets "[" and "]" +// +#define CAN_MIXED_FORMAT 0x00008000 // See #defines below. [0] +#define J1962_PINS 0x00008001 // 0xPPSS PP: 0x00-0x10 SS: 0x00-0x10 PP!=SS, except 0x0000. Exclude pins 4, 5, and 16. [0] +#define SW_CAN_HS_DATA_RATE 0x00008010 // SWCAN: 5-500000 [83333] +#define SW_CAN_SPEEDCHANGE_ENABLE 0x00008011 // SWCAN: 0 (DISABLE_SPDCHANGE), 1 (ENABLE_SPDCHANGE) [0] +#define SW_CAN_RES_SWITCH 0x00008012 // SWCAN: 0 (DISCONNECT_RESISTOR), 1 (CONNECT_RESISTOR), 2 (AUTO_ RESISTOR) [0] +#define ACTIVE_CHANNELS 0x00008020 // ANALOG: 0-0xFFFFFFFF +#define SAMPLE_RATE 0x00008021 // ANALOG: 0-0xFFFFFFFF [0] (high bit changes meaning from samples/sec to seconds/sample) +#define SAMPLES_PER_READING 0x00008022 // ANALOG: 1-0xFFFFFFFF [1] +#define READINGS_PER_MSG 0x00008023 // ANALOG: 1-0x00000408 (1 - 1032) [1] +#define AVERAGING_METHOD 0x00008024 // ANALOG: 0-0xFFFFFFFF [0] +#define SAMPLE_RESOLUTION 0x00008025 // ANALOG READ-ONLY: 0x1-0x20 (1 - 32) +#define INPUT_RANGE_LOW 0x00008026 // ANALOG READ-ONLY: 0x80000000-0x7FFFFFFF (-2147483648-2147483647) +#define INPUT_RANGE_HIGH 0x00008027 // ANALOG READ-ONLY: 0x80000000-0x7FFFFFFF (-2147483648-2147483647) + + +// +// J2534-2 Mixed-Mode/Format CAN Definitions +// +#define CAN_MIXED_FORMAT_OFF 0 // Messages will be treated as ISO 15765 ONLY. +#define CAN_MIXED_FORMAT_ON 1 // Messages will be treated as either ISO 15765 or an unformatted CAN frame. +#define CAN_MIXED_FORMAT_ALL_FRAMES 2 // Messages will be treated as ISO 15765, an unformatted CAN frame, or both. + + +// +// J2534-2 Analog Channel Averaging Method Definitions +// +#define SIMPLE_AVERAGE 0x00000000 // Simple arithmetic mean +#define MAX_LIMIT_AVERAGE 0x00000001 // Choose the biggest value +#define MIN_LIMIT_AVERAGE 0x00000002 // Choose the lowest value +#define MEDIAN_AVERAGE 0x00000003 // Choose arithmetic median + + +// +// J2534-1 v04.04 RxStatus Definitions +// +#define TX_MSG_TYPE 0x0001 +#define START_OF_MESSAGE 0x0002 +#define RX_BREAK 0x0004 +#define TX_INDICATION 0x0008 +#define ISO15765_PADDING_ERROR 0x0010 +#define ISO15765_ADDR_TYPE 0x0080 +//#define CAN_29BIT_ID 0x0100 // Defined above + + +// +// J2534-2 RxStatus Definitions +// +#define SW_CAN_HV_RX 0x00010000 // SWCAN Channels Only +#define SW_CAN_HS_RX 0x00020000 // SWCAN Channels Only +#define SW_CAN_NS_RX 0x00040000 // SWCAN Channels Only +#define OVERFLOW_ 0x00010000 // Analog Input Channels Only + + +// +// J2534-1 v04.04 TxFlags Definitions +// +#define ISO15765_FRAME_PAD 0x0040 +//#define ISO15765_ADDR_TYPE 0x0080 // Defined above +//#define CAN_29BIT_ID 0x0100 // Defined above +#define WAIT_P3_MIN_ONLY 0x0200 +#define SCI_MODE 0x400000 +#define SCI_TX_VOLTAGE 0x800000 + + +// +// J2534-2 TxFlags Definitions +// +#define SW_CAN_HV_TX 0x00000400 + + +// +// J2534-1 v04.04 Structure Definitions +// +typedef struct +{ + unsigned long Parameter; // Name of parameter + unsigned long Value; // Value of the parameter +} SCONFIG; + + +typedef struct +{ + unsigned long NumOfParams; // Number of SCONFIG elements + SCONFIG* ConfigPtr; // Array of SCONFIG +} SCONFIG_LIST; + + +typedef struct +{ + unsigned long NumOfBytes; // Number of bytes in the array + unsigned char* BytePtr; // Array of bytes +} SBYTE_ARRAY; + + +typedef struct +{ + unsigned long ProtocolID; + unsigned long RxStatus; + unsigned long TxFlags; + unsigned long Timestamp; + unsigned long DataSize; + unsigned long ExtraDataIndex; + unsigned char Data[4128]; +} PASSTHRU_MSG; + +// +// J2534-1 v04.04 Function Prototypes +// +PANDAJ2534DLL_API long PTAPI PassThruOpen(void *pName, unsigned long *pDeviceID); +PANDAJ2534DLL_API long PTAPI PassThruClose(unsigned long DeviceID); +PANDAJ2534DLL_API long PTAPI PassThruConnect(unsigned long DeviceID, unsigned long ProtocolID, unsigned long Flags, unsigned long BaudRate, unsigned long *pChannelID); +PANDAJ2534DLL_API long PTAPI PassThruDisconnect(unsigned long ChannelID); +PANDAJ2534DLL_API long PTAPI PassThruReadMsgs(unsigned long ChannelID, PASSTHRU_MSG *pMsg, unsigned long *pNumMsgs, unsigned long Timeout); +PANDAJ2534DLL_API long PTAPI PassThruWriteMsgs(unsigned long ChannelID, PASSTHRU_MSG *pMsg, unsigned long *pNumMsgs, unsigned long Timeout); +PANDAJ2534DLL_API long PTAPI PassThruStartPeriodicMsg(unsigned long ChannelID, PASSTHRU_MSG *pMsg, unsigned long *pMsgID, unsigned long TimeInterval); +PANDAJ2534DLL_API long PTAPI PassThruStopPeriodicMsg(unsigned long ChannelID, unsigned long MsgID); +PANDAJ2534DLL_API long PTAPI PassThruStartMsgFilter(unsigned long ChannelID, unsigned long FilterType, PASSTHRU_MSG *pMaskMsg, PASSTHRU_MSG *pPatternMsg, PASSTHRU_MSG *pFlowControlMsg, unsigned long *pFilterID); +PANDAJ2534DLL_API long PTAPI PassThruStopMsgFilter(unsigned long ChannelID, unsigned long FilterID); +PANDAJ2534DLL_API long PTAPI PassThruSetProgrammingVoltage(unsigned long DeviceID, unsigned long PinNumber, unsigned long Voltage); +PANDAJ2534DLL_API long PTAPI PassThruReadVersion(unsigned long DeviceID, char *pFirmwareVersion, char *pDllVersion, char *pApiVersion); +PANDAJ2534DLL_API long PTAPI PassThruGetLastError(char *pErrorDescription); +PANDAJ2534DLL_API long PTAPI PassThruIoctl(unsigned long ChannelID, unsigned long IoctlID, void *pInput, void *pOutput); + + +// +// J2534-1 v04.04 Function Typedefs +// These function typedefs allow simpler use of the J2534 API by +// allowing you to do things like this: +// PTCONNECT pPassThruConnectFunc = GetProcAddress(hModule, "PassThruConnect"); +// if (pPassThruConnectFunc == NULL) +// return FALSE; +// pPassThruConnectFunc(DeviceID, CAN, CAN_29BIT_ID, 500000, &ChannelID); +// +typedef long (PTAPI *PTOPEN)(void *pName, unsigned long *pDeviceID); +typedef long (PTAPI *PTCLOSE)(unsigned long DeviceID); +typedef long (PTAPI *PTCONNECT)(unsigned long DeviceID, unsigned long ProtocolID, unsigned long Flags, unsigned long BaudRate, unsigned long *pChannelID); +typedef long (PTAPI *PTDISCONNECT)(unsigned long ChannelID); +typedef long (PTAPI *PTREADMSGS)(unsigned long ChannelID, PASSTHRU_MSG *pMsg, unsigned long *pNumMsgs, unsigned long Timeout); +typedef long (PTAPI *PTWRITEMSGS)(unsigned long ChannelID, PASSTHRU_MSG *pMsg, unsigned long *pNumMsgs, unsigned long Timeout); +typedef long (PTAPI *PTSTARTPERIODICMSG)(unsigned long ChannelID, PASSTHRU_MSG *pMsg, unsigned long *pMsgID, unsigned long TimeInterval); +typedef long (PTAPI *PTSTOPPERIODICMSG)(unsigned long ChannelID, unsigned long MsgID); +typedef long (PTAPI *PTSTARTMSGFILTER)(unsigned long ChannelID, unsigned long FilterType, PASSTHRU_MSG *pMaskMsg, PASSTHRU_MSG *pPatternMsg, PASSTHRU_MSG *pFlowControlMsg, unsigned long *pFilterID); +typedef long (PTAPI *PTSTOPMSGFILTER)(unsigned long ChannelID, unsigned long FilterID); +typedef long (PTAPI *PTSETPROGRAMMINGVOLTAGE)(unsigned long DeviceID, unsigned long PinNumber, unsigned long Voltage); +typedef long (PTAPI *PTREADVERSION)(unsigned long DeviceID, char *pFirmwareVersion, char *pDllVersion, char *pApiVersion); +typedef long (PTAPI *PTGETLASTERROR)(char *pErrorDescription); +typedef long (PTAPI *PTIOCTL)(unsigned long ChannelID, unsigned long IoctlID, void *pInput, void *pOutput); diff --git a/drivers/windows/pandaJ2534DLL/J2534register_x64.reg b/drivers/windows/pandaJ2534DLL/J2534register_x64.reg new file mode 100644 index 0000000000000000000000000000000000000000..120ab391c7bb4da60a85cc97eb72cb312f82ea6e GIT binary patch literal 1056 zcmbu8TTjA35QWdPiT{E0NgpI2#S4iKNW7qc1c=0lX(}L+a0?U(e_s7|+k)`{A!f4e z?#%3*nKQFrpH1~OQb%JgG*dz~b=5;RQ=qAqXs)pKIgL3d^oV_mwam)Qip6u^Cq6=mN{aM(rqP zYch3(l3w|ms^5s*BX5(%fPI_DLBxoO;~<6)hYIKTw^!B@Ua#csvz8Xq;OD3^tTUiS zvu}`x`L8p-gOe=GxNw=`YnEr3N|N^gi7|_o+ce&%u$i?ee^+*=w9fEO(cvn6*vv=R zZwI6T9rfVCqlXpUME%|Uc7rL%6QRB%^5wsf&Fx*0*Gw6n%3J0ecI6zFUDkH|#GQ2M neTL3#z7@}Ch3Ojda*Vh0V}j!OFfTZK@zcoX_p1p#%>;h~jZ2h> literal 0 HcmV?d00001 diff --git a/drivers/windows/pandaJ2534DLL/MessagePeriodic.cpp b/drivers/windows/pandaJ2534DLL/MessagePeriodic.cpp new file mode 100644 index 0000000000..0c3416e0da --- /dev/null +++ b/drivers/windows/pandaJ2534DLL/MessagePeriodic.cpp @@ -0,0 +1,30 @@ +#include "stdafx.h" +#include "MessagePeriodic.h" +#include "J2534Connection.h" + +MessagePeriodic::MessagePeriodic( + std::chrono::microseconds delay, + std::shared_ptr msg +) : Action(msg->connection, delay), msg(msg), runyet(FALSE), active(TRUE) { }; + +void MessagePeriodic::execute() { + if (!this->active) return; + if (this->runyet) { + if (msg->isFinished()) { + msg->reset(); + msg->execute(); + } + } else { + this->runyet = TRUE; + msg->execute(); + } + + if (auto conn_sp = this->connection.lock()) { + if (auto panda_dev_sp = conn_sp->getPandaDev()) { + //Scheduling must be relative to now incase there was a long stall that + //would case it to be super far behind and try to catch up forever. + this->scheduleImmediateDelay(); + panda_dev_sp->insertActionIntoTaskList(shared_from_this()); + } + } +} diff --git a/drivers/windows/pandaJ2534DLL/MessagePeriodic.h b/drivers/windows/pandaJ2534DLL/MessagePeriodic.h new file mode 100644 index 0000000000..40132565c1 --- /dev/null +++ b/drivers/windows/pandaJ2534DLL/MessagePeriodic.h @@ -0,0 +1,33 @@ +#pragma once +#include "Action.h" +#include "MessageTx.h" + +class J2534Connection; + +/* A message that is resent on a given period. Created with calls to PassThruStartPeriodicMessage. + +Instead of making each J2534 protocol implementation have to implement periodic message +functionality, this class takes a message to be sent, and passes along the execute call +to the message, then reschedules itself. +*/ +class MessagePeriodic : public Action, public std::enable_shared_from_this +{ +public: + MessagePeriodic( + std::chrono::microseconds delay, + std::shared_ptr msg + ); + + virtual void execute(); + + void cancel() { + this->active = FALSE; + } + +protected: + std::shared_ptr msg; + +private: + BOOL runyet; + BOOL active; +}; diff --git a/drivers/windows/pandaJ2534DLL/MessageRx.h b/drivers/windows/pandaJ2534DLL/MessageRx.h new file mode 100644 index 0000000000..e22278d4d0 --- /dev/null +++ b/drivers/windows/pandaJ2534DLL/MessageRx.h @@ -0,0 +1,61 @@ +#pragma once + +class MessageRx +{ +public: + MessageRx( + unsigned long size, + std::string piece, + unsigned long rxFlags, + std::shared_ptr filter + ) : expected_size(size & 0xFFF), flags(rxFlags) { + msg.reserve(expected_size); + msg = piece; + next_part = 1; + }; + + bool rx_add_frame(uint8_t pci_byte, unsigned int max_packet_size, const std::string piece) { + if ((pci_byte & 0x0F) != this->next_part) { + //TODO: Maybe this should instantly fail the transaction. + return TRUE; + } + + this->next_part = (this->next_part + 1) % 0x10; + unsigned int payload_len = min(expected_size - msg.size(), max_packet_size); + if (piece.size() < payload_len) { + //A frame was received that could have held more data. + //No examples of this protocol show that happening, so + //it will be assumed that it is grounds to reset rx. + return FALSE; + } + msg += piece.substr(0, payload_len); + + return TRUE; + } + + unsigned int bytes_remaining() { + return this->expected_size - this->msg.size(); + } + + bool is_ready() { + return this->msg.size() == this->expected_size; + } + + bool flush_result(std::string& final_msg) { + if (this->msg.size() == this->expected_size) { + final_msg = this->msg; + return TRUE; + } + return FALSE; + } + + uint8_t getNextConsecutiveFrameId() { + return this->next_part++; + } + + std::weak_ptr filter; + unsigned long flags; + unsigned long expected_size; + std::string msg; + unsigned char next_part; +}; diff --git a/drivers/windows/pandaJ2534DLL/MessageTx.h b/drivers/windows/pandaJ2534DLL/MessageTx.h new file mode 100644 index 0000000000..5315fa058f --- /dev/null +++ b/drivers/windows/pandaJ2534DLL/MessageTx.h @@ -0,0 +1,25 @@ +#pragma once +#include "Action.h" +#include "J2534Frame.h" + +class J2534Connection; + +class MessageTx : public Action, public std::enable_shared_from_this +{ +public: + MessageTx( + std::weak_ptr connection_in, + PASSTHRU_MSG& to_send + ) : Action(connection_in), fullmsg(to_send) { }; + + virtual BOOL checkTxReceipt(J2534Frame frame) = 0; + + virtual BOOL isFinished() = 0; + + virtual BOOL txReady() = 0; + + virtual void reset() = 0; + +protected: + J2534Frame fullmsg; +}; \ No newline at end of file diff --git a/drivers/windows/pandaJ2534DLL/MessageTxTimeout.cpp b/drivers/windows/pandaJ2534DLL/MessageTxTimeout.cpp new file mode 100644 index 0000000000..2e21ba3ce1 --- /dev/null +++ b/drivers/windows/pandaJ2534DLL/MessageTxTimeout.cpp @@ -0,0 +1,43 @@ +#include "stdafx.h" +#include "J2534Connection.h" +#include "MessageTxTimeout.h" + +MessageTxTimeoutable::MessageTxTimeoutable( + std::weak_ptr connection, + PASSTHRU_MSG& to_send +) : MessageTx(connection, to_send), recvCount(0) { }; + +void MessageTxTimeoutable::scheduleTimeout(std::chrono::microseconds timeoutus) { + if (auto conn_sp = this->connection.lock()) { + if (auto panda_dev_sp = conn_sp->getPandaDev()) { + auto timeoutobj = std::make_shared(std::static_pointer_cast(shared_from_this()), timeoutus); + panda_dev_sp->scheduleAction(std::static_pointer_cast(timeoutobj), TRUE); + } + } +} + +void MessageTxTimeoutable::scheduleTimeout(unsigned long timeoutus) { + scheduleTimeout(std::chrono::microseconds(timeoutus)); +} + + + +MessageTxTimeout::MessageTxTimeout( + std::shared_ptr msg, + std::chrono::microseconds timeout +) : Action(msg->connection), msg(msg), lastRecvCount(msg->getRecvCount()) { + delay = timeout; +}; + +MessageTxTimeout::MessageTxTimeout( + std::shared_ptr msg, + unsigned long timeout +) : MessageTxTimeout(msg, std::chrono::microseconds(timeout * 1000)) { }; + +void MessageTxTimeout::execute() { + if (auto msg_sp = this->msg.lock()) { + if (msg_sp->getRecvCount() == this->lastRecvCount) { + msg_sp->onTimeout(); + } + } +} diff --git a/drivers/windows/pandaJ2534DLL/MessageTxTimeout.h b/drivers/windows/pandaJ2534DLL/MessageTxTimeout.h new file mode 100644 index 0000000000..a9c878468c --- /dev/null +++ b/drivers/windows/pandaJ2534DLL/MessageTxTimeout.h @@ -0,0 +1,52 @@ +#pragma once +#include "Action.h" +#include "MessageTx.h" + +class MessageTxTimeout; + +/* A special type of MessageTx for multipart messages that supports being canceled with a timeout.*/ +class MessageTxTimeoutable : public MessageTx +{ +public: + MessageTxTimeoutable( + std::weak_ptr connection, + PASSTHRU_MSG& to_send + ); + + unsigned long getRecvCount() { + return recvCount; + } + + virtual void onTimeout() = 0; + +protected: + unsigned long recvCount; + + void scheduleTimeout(std::chrono::microseconds timeoutus); + + void scheduleTimeout(unsigned long timeoutus); +}; + + +/* An Action that cancels MessageTxTimeoutableif the Timeout Actoin executes +before the MessageTxTimeoutableif renews its timeout. +*/ +class MessageTxTimeout : public Action +{ +public: + MessageTxTimeout( + std::shared_ptr msg, + std::chrono::microseconds timeout + ); + + MessageTxTimeout( + std::shared_ptr msg, + unsigned long timeout + ); + + virtual void execute(); + +private: + std::weak_ptr msg; + unsigned long lastRecvCount; +}; diff --git a/drivers/windows/pandaJ2534DLL/MessageTx_CAN.cpp b/drivers/windows/pandaJ2534DLL/MessageTx_CAN.cpp new file mode 100644 index 0000000000..8217ce539a --- /dev/null +++ b/drivers/windows/pandaJ2534DLL/MessageTx_CAN.cpp @@ -0,0 +1,44 @@ +#include "stdafx.h" +#include "MessageTx_CAN.h" +#include "J2534Connection_CAN.h" + +MessageTx_CAN::MessageTx_CAN( + std::shared_ptr connection_in, + PASSTHRU_MSG& to_send +) : MessageTx(connection_in, to_send), sentyet(FALSE), txInFlight(FALSE) {}; + +void MessageTx_CAN::execute() { + uint32_t addr = ((uint8_t)fullmsg.Data[0]) << 24 | ((uint8_t)fullmsg.Data[1]) << 16 | + ((uint8_t)fullmsg.Data[2]) << 8 | ((uint8_t)fullmsg.Data[3]); + + if (auto conn_sp = std::static_pointer_cast(this->connection.lock())) { + if (auto panda_dev_sp = conn_sp->getPandaDev()) { + auto payload = fullmsg.Data.substr(4); + if (panda_dev_sp->panda->can_send(addr, check_bmask(this->fullmsg.TxFlags, CAN_29BIT_ID), + (const uint8_t*)payload.c_str(), (uint8_t)payload.size(), panda::PANDA_CAN1) == FALSE) { + return; + } + this->txInFlight = TRUE; + this->sentyet = TRUE; + panda_dev_sp->txMsgsAwaitingEcho.push(shared_from_this()); + } + } +} + +//Returns TRUE if receipt is consumed by the msg, FALSE otherwise. +BOOL MessageTx_CAN::checkTxReceipt(J2534Frame frame) { + if (txReady()) return FALSE; + if (frame.Data == fullmsg.Data && ((this->fullmsg.TxFlags & CAN_29BIT_ID) == (frame.RxStatus & CAN_29BIT_ID))) { + txInFlight = FALSE; + if (auto conn_sp = std::static_pointer_cast(this->connection.lock())) + if (conn_sp->loopback) + conn_sp->addMsgToRxQueue(frame); + return TRUE; + } + return FALSE; +} + +void MessageTx_CAN::reset() { + sentyet = FALSE; + txInFlight = FALSE; +} diff --git a/drivers/windows/pandaJ2534DLL/MessageTx_CAN.h b/drivers/windows/pandaJ2534DLL/MessageTx_CAN.h new file mode 100644 index 0000000000..afac75ef81 --- /dev/null +++ b/drivers/windows/pandaJ2534DLL/MessageTx_CAN.h @@ -0,0 +1,33 @@ +#pragma once +#include +#include "MessageTx.h" + +class J2534Connection; + +class MessageTx_CAN : public MessageTx +{ +public: + MessageTx_CAN( + std::shared_ptr connection_in, + PASSTHRU_MSG& to_send + ); + + virtual void execute(); + + //Returns TRUE if receipt is consumed by the msg, FALSE otherwise. + virtual BOOL checkTxReceipt(J2534Frame frame); + + virtual BOOL isFinished() { + return !txInFlight && sentyet; + }; + + virtual BOOL txReady() { + return !sentyet; + }; + + virtual void reset(); + +private: + BOOL sentyet; + BOOL txInFlight; +}; diff --git a/drivers/windows/pandaJ2534DLL/MessageTx_ISO15765.cpp b/drivers/windows/pandaJ2534DLL/MessageTx_ISO15765.cpp new file mode 100644 index 0000000000..abcf3f6a47 --- /dev/null +++ b/drivers/windows/pandaJ2534DLL/MessageTx_ISO15765.cpp @@ -0,0 +1,180 @@ +#include "stdafx.h" +#include "MessageTx_ISO15765.h" +#include "constants_ISO15765.h" + +//in microseconsa +#define TIMEOUT_FC 250000 //Flow Control +#define TIMEOUT_CF 250000 //Consecutive Frames + +MessageTx_ISO15765::MessageTx_ISO15765( + std::shared_ptr connection_in, + PASSTHRU_MSG& to_send, + std::shared_ptr filter +) : MessageTxTimeoutable(connection_in, to_send), filter(filter), frames_sent(0), +consumed_count(0), txInFlight(FALSE), sendAll(FALSE), block_size(0), numWaitFrames(0), didtimeout(FALSE), issuspended(FALSE){ + + CANid = ((uint8_t)fullmsg.Data[0]) << 24 | ((uint8_t)fullmsg.Data[1]) << 16 | + ((uint8_t)fullmsg.Data[2]) << 8 | ((uint8_t)fullmsg.Data[3]); + + payload = fullmsg.Data.substr(addressLength()); + + if (check_bmask(fullmsg.TxFlags, ISO15765_ADDR_TYPE)) + data_prefix = fullmsg.Data[4]; + + if (payload.size() <= (7 - data_prefix.size())) { + isMultipart = FALSE; + auto framepayload = data_prefix + std::string(1, (char)payload.size()) + payload; + if (check_bmask(this->fullmsg.TxFlags, ISO15765_FRAME_PAD)) + framepayload += std::string(8 - framepayload.size(), '\x00'); + framePayloads.push_back(framepayload); + } else { + isMultipart = TRUE; + unsigned long first_payload_len = 6 - data_prefix.size(); // 5 or 6 + std::string framepayload = data_prefix + + (char)(0x10 | ((payload.size() >> 8) & 0xF)) + + (char)(payload.size() & 0xFF) + + payload.substr(0, first_payload_len); + framePayloads.push_back(framepayload); + + unsigned int pktnum = 1; + uint8_t CFDatSize = 7 - data_prefix.size(); + while (TRUE) { + framepayload = data_prefix + (char)(0x20 | (pktnum % 0x10)) + + payload.substr(first_payload_len + (CFDatSize * (pktnum-1)), CFDatSize); + + if (check_bmask(this->fullmsg.TxFlags, ISO15765_FRAME_PAD)) + framepayload += std::string(8 - framepayload.size(), '\x00'); + framePayloads.push_back(framepayload); + if (first_payload_len + (CFDatSize * pktnum) >= payload.size()) break; + pktnum++; + } + + } +}; + +unsigned int MessageTx_ISO15765::addressLength() { + return check_bmask(fullmsg.TxFlags, ISO15765_ADDR_TYPE) ? 5 : 4; +} + +void MessageTx_ISO15765::execute() { + if (didtimeout || issuspended) return; + if (this->frames_sent >= this->framePayloads.size()) return; + if (block_size == 0 && !sendAll && this->frames_sent > 0) return; + if (block_size > 0 && !sendAll) block_size--; + + if (auto conn_sp = this->connection.lock()) { + if (auto panda_dev_sp = conn_sp->getPandaDev()) { + auto& outFramePayload = this->framePayloads[this->frames_sent]; + if (panda_dev_sp->panda->can_send(this->CANid, check_bmask(this->fullmsg.TxFlags, CAN_29BIT_ID), + (const uint8_t*)outFramePayload.c_str(), (uint8_t)outFramePayload.size(), panda::PANDA_CAN1) == FALSE) { + return; + } + + this->txInFlight = TRUE; + this->frames_sent++; + panda_dev_sp->txMsgsAwaitingEcho.push(shared_from_this()); + } + } +} + +//Returns TRUE if receipt is consumed by the msg, FALSE otherwise. +BOOL MessageTx_ISO15765::checkTxReceipt(J2534Frame frame) { + if (!txInFlight) return FALSE; + if (frame.Data.size() >= addressLength() + 1 && (frame.Data[addressLength()] & 0xF0) == FRAME_FLOWCTRL) return FALSE; + + if (frame.Data == fullmsg.Data.substr(0, 4) + framePayloads[frames_sent - 1] && + ((this->fullmsg.TxFlags & CAN_29BIT_ID) == (frame.RxStatus & CAN_29BIT_ID))) { //Check receipt is expected + txInFlight = FALSE; //Received the expected receipt. Allow another msg to be sent. + + if (this->recvCount == 0 && this->framePayloads.size() > 1) + scheduleTimeout(TIMEOUT_FC); + + if (frames_sent == framePayloads.size()) { //Check message done + if (auto conn_sp = std::static_pointer_cast(this->connection.lock())) { + unsigned long flags = (filter == nullptr) ? fullmsg.TxFlags : this->filter->flags; + + J2534Frame outframe(ISO15765); + outframe.Timestamp = frame.Timestamp; + outframe.RxStatus = TX_INDICATION | (flags & (ISO15765_ADDR_TYPE | CAN_29BIT_ID)); + outframe.Data = frame.Data.substr(0, addressLength()); + conn_sp->addMsgToRxQueue(outframe); + + if (conn_sp->loopback) { + J2534Frame outframe(ISO15765); + outframe.Timestamp = frame.Timestamp; + outframe.RxStatus = TX_MSG_TYPE | (flags & (ISO15765_ADDR_TYPE | CAN_29BIT_ID)); + outframe.Data = this->fullmsg.Data; + conn_sp->addMsgToRxQueue(outframe); + } + + } //TODO what if fails + } else { + //Restart timeout if we are waiting for a flow control frame. + //FC frames are required when we are not sending all, the + //current block_size batch has not been sent, a FC message has + //already been received (differentiating from first frame), the + //message is not finished, and there is more than one frame in + //the message. + if (block_size == 0 && recvCount != 0 && !sendAll && !this->isFinished() && this->framePayloads.size() > 1) + scheduleTimeout(TIMEOUT_CF); + } + return TRUE; + } + return FALSE; +} + +BOOL MessageTx_ISO15765::isFinished() { + return this->frames_sent == this->framePayloads.size() && !txInFlight; +} + +BOOL MessageTx_ISO15765::txReady() { + return block_size > 0 || sendAll || this->frames_sent == 0; +} + +void MessageTx_ISO15765::reset() { + frames_sent = 0; + consumed_count = 0; + block_size = 0; + txInFlight = FALSE; + sendAll = FALSE; + numWaitFrames = 0; + didtimeout = FALSE; +} + +void MessageTx_ISO15765::onTimeout() { + didtimeout = TRUE; + if (auto conn_sp = std::static_pointer_cast(this->connection.lock())) { + if (auto panda_dev_sp = conn_sp->getPandaDev()) { + panda_dev_sp->removeConnectionTopAction(conn_sp, shared_from_this()); + } + } +} + +void MessageTx_ISO15765::flowControlContinue(uint8_t block_size, std::chrono::microseconds separation_time) { + this->issuspended = FALSE; + this->block_size = block_size; + this->delay = separation_time; + this->sendAll = block_size == 0; + this->recvCount++; +} + +void MessageTx_ISO15765::flowControlWait(unsigned long N_WFTmax) { + this->issuspended = TRUE; + this->recvCount++; + this->numWaitFrames++; + this->sendAll = FALSE; + this->block_size = block_size; + this->delay = std::chrono::microseconds(0); + //Docs are vague on if 0 means NO WAITS ALLOWED or NO LIMIT TO WAITS. + //It is less likely to cause issue if NO LIMIT is assumed. + if (N_WFTmax > 0 && this->numWaitFrames > N_WFTmax) { + this->onTimeout(); //Trigger self destruction of message. + } else { + scheduleTimeout(TIMEOUT_FC); + } +} + +void MessageTx_ISO15765::flowControlAbort() { + this->recvCount++; //Invalidate future timeout actions. + this->onTimeout(); //Trigger self destruction of message. +} diff --git a/drivers/windows/pandaJ2534DLL/MessageTx_ISO15765.h b/drivers/windows/pandaJ2534DLL/MessageTx_ISO15765.h new file mode 100644 index 0000000000..0113edb8f9 --- /dev/null +++ b/drivers/windows/pandaJ2534DLL/MessageTx_ISO15765.h @@ -0,0 +1,54 @@ +#pragma once +#include "MessageTxTimeout.h" +#include "J2534Connection_ISO15765.h" + +class J2534Connection_ISO15765; + +/** +A specialized message type that can handle J2534 single and multi +frame (with flow control) writes. +*/ +class MessageTx_ISO15765 : public MessageTxTimeoutable +{ +public: + MessageTx_ISO15765( + std::shared_ptr connection, + PASSTHRU_MSG& to_send, + std::shared_ptr filter + ); + + unsigned int addressLength(); + + virtual void execute(); + + virtual BOOL checkTxReceipt(J2534Frame frame); + + virtual BOOL isFinished(); + + virtual BOOL txReady(); + + virtual void reset(); + + virtual void onTimeout(); + + //Functions for ISO15765 flow control + + void MessageTx_ISO15765::flowControlContinue(uint8_t block_size, std::chrono::microseconds separation_time); + void MessageTx_ISO15765::flowControlWait(unsigned long N_WFTmax); + void MessageTx_ISO15765::flowControlAbort(); + + std::shared_ptr filter; + unsigned long frames_sent; + unsigned long consumed_count; + uint8_t block_size; + unsigned long CANid; + std::string data_prefix; + std::string payload; + BOOL isMultipart; + std::vector framePayloads; + BOOL txInFlight; + BOOL sendAll; + unsigned int numWaitFrames; + BOOL didtimeout; + BOOL issuspended; +}; diff --git a/drivers/windows/pandaJ2534DLL/PandaJ2534Device.cpp b/drivers/windows/pandaJ2534DLL/PandaJ2534Device.cpp new file mode 100644 index 0000000000..64da8e2c3d --- /dev/null +++ b/drivers/windows/pandaJ2534DLL/PandaJ2534Device.cpp @@ -0,0 +1,214 @@ +#include "stdafx.h" +#include "PandaJ2534Device.h" +#include "J2534Frame.h" + +PandaJ2534Device::PandaJ2534Device(std::unique_ptr new_panda) : txInProgress(FALSE) { + this->panda = std::move(new_panda); + + this->panda->set_esp_power(FALSE); + this->panda->set_safety_mode(panda::SAFETY_ALLOUTPUT); + this->panda->set_can_loopback(FALSE); + this->panda->set_alt_setting(1); + + DWORD canListenThreadID; + this->thread_kill_event = CreateEvent(NULL, TRUE, FALSE, NULL); + this->can_thread_handle = CreateThread(NULL, 0, _can_recv_threadBootstrap, (LPVOID)this, 0, &canListenThreadID); + + DWORD flowControlSendThreadID; + this->flow_control_wakeup_event = CreateEvent(NULL, TRUE, FALSE, NULL); + this->flow_control_thread_handle = CreateThread(NULL, 0, _msg_tx_threadBootstrap, (LPVOID)this, 0, &flowControlSendThreadID); +}; + +PandaJ2534Device::~PandaJ2534Device() { + SetEvent(this->thread_kill_event); + DWORD res = WaitForSingleObject(this->can_thread_handle, INFINITE); + CloseHandle(this->can_thread_handle); + + res = WaitForSingleObject(this->flow_control_thread_handle, INFINITE); + CloseHandle(this->flow_control_thread_handle); + + CloseHandle(this->flow_control_wakeup_event); + CloseHandle(this->thread_kill_event); +} + +std::shared_ptr PandaJ2534Device::openByName(std::string sn) { + auto p = panda::Panda::openPanda(""); + if (p == nullptr) + return nullptr; + return std::unique_ptr(new PandaJ2534Device(std::move(p))); +} + +DWORD PandaJ2534Device::closeChannel(unsigned long ChannelID) { + if (this->connections.size() <= ChannelID) return ERR_INVALID_CHANNEL_ID; + if (this->connections[ChannelID] == nullptr) return ERR_INVALID_CHANNEL_ID; + this->connections[ChannelID] = nullptr; + return STATUS_NOERROR; +} + +DWORD PandaJ2534Device::addChannel(std::shared_ptr& conn, unsigned long* channel_id) { + int channel_index = -1; + for (unsigned int i = 0; i < this->connections.size(); i++) + if (this->connections[i] == nullptr) { + channel_index = i; + break; + } + + if (channel_index == -1) { + if (this->connections.size() == 0xFFFF) //channelid max 16 bits + return ERR_FAILED; //Too many channels + this->connections.push_back(nullptr); + channel_index = this->connections.size() - 1; + } + + this->connections[channel_index] = conn; + + *channel_id = channel_index; + return STATUS_NOERROR; +} + +DWORD PandaJ2534Device::can_recv_thread() { + DWORD err = TRUE; + while (err) { + std::vector msg_recv; + err = this->panda->can_recv_async(this->thread_kill_event, msg_recv); + for (auto msg_in : msg_recv) { + J2534Frame msg_out(msg_in); + + if (msg_in.is_receipt) { + synchronized(task_queue_mutex) { + if (txMsgsAwaitingEcho.size() > 0) { + auto msgtx = txMsgsAwaitingEcho.front(); + if (auto conn = msgtx->connection.lock()) { + if (conn->isProtoCan() && conn->getPort() == msg_in.bus) { + if (msgtx->checkTxReceipt(msg_out)) { + //Things to check: + // Frame not for this msg: Drop frame and alert. Error? + // Frame is for this msg, more tx frames required after a FC frame: Wait for FC frame to come and trigger next tx. + // Frame is for this msg, more tx frames required: Schedule next tx frame. + // Frame is for this msg, and is the final frame of the msg: Let conn process full msg, If another msg from this conn is available, register it. + txMsgsAwaitingEcho.pop(); //Remove the TX object and schedule record. + + if (msgtx->isFinished()) { + this->removeConnectionTopAction(conn, msgtx); + } else { + if (msgtx->txReady()) { //Not finished, ready to send next frame. + msgtx->schedule(msg_in.recv_time_point, TRUE); + this->insertActionIntoTaskList(msgtx); + } else { + //Not finished, but next frame not ready (maybe waiting for flow control). + //Do not schedule more messages from this connection. + //this->ConnTxSet.erase(conn); + //Removing this means new messages queued can kickstart the queue and overstep the current message. + } + } + } + } + } else { + //Connection has died. Clear out the tx entry from device records. + txMsgsAwaitingEcho.pop(); + this->ConnTxSet.erase(conn); //connection is already dead, no need to schedule future tx msgs. + } + } + } + } else { + for (auto& conn : this->connections) + if (conn->isProtoCan() && conn->getPort() == msg_in.bus) + conn->processMessage(msg_out); + } + } + } + + return 0; +} + +DWORD PandaJ2534Device::msg_tx_thread() { + const HANDLE subscriptions[] = { this->flow_control_wakeup_event, this->thread_kill_event }; + DWORD sleepDuration = INFINITE; + while (TRUE) { + DWORD res = WaitForMultipleObjects(2, subscriptions, FALSE, sleepDuration); + if (res == WAIT_OBJECT_0 + 1) return 0; + if (res != WAIT_OBJECT_0 && res != WAIT_TIMEOUT) { + printf("Got an unexpected wait result in flow_control_write_thread. Res: %d; GetLastError: %d\n. Terminating thread.", res, GetLastError()); + return 0; + } + ResetEvent(this->flow_control_wakeup_event); + + while (TRUE) { + synchronized(task_queue_mutex) { //implemented with for loop. Consumes breaks. + if (this->task_queue.size() == 0) { + sleepDuration = INFINITE; + goto break_flow_ctrl_loop; + } + if (std::chrono::steady_clock::now() >= this->task_queue.front()->expire) { + auto task = this->task_queue.front(); //Get the scheduled tx record. + this->task_queue.pop_front(); + task->execute(); + } else { //Ran out of things that need to be sent now. Sleep! + auto time_diff = std::chrono::duration_cast + (this->task_queue.front()->expire - std::chrono::steady_clock::now()); + sleepDuration = max(1, time_diff.count()); + goto break_flow_ctrl_loop; + } + } + } + break_flow_ctrl_loop: + continue; + } + return 0; +} + +//Place the Action in the task queue based on the Action's expiration time, +//then signal the thread that processes actions. +void PandaJ2534Device::insertActionIntoTaskList(std::shared_ptr action) { + synchronized(task_queue_mutex) { + auto iter = this->task_queue.begin(); + for (; iter != this->task_queue.end(); iter++) { + if (action->expire < (*iter)->expire) break; + } + this->task_queue.insert(iter, action); + } + SetEvent(this->flow_control_wakeup_event); +} + +void PandaJ2534Device::scheduleAction(std::shared_ptr msg, BOOL startdelayed) { + if(startdelayed) + msg->scheduleImmediateDelay(); + else + msg->scheduleImmediate(); + this->insertActionIntoTaskList(msg); +} + +void PandaJ2534Device::registerConnectionTx(std::shared_ptr conn) { + synchronized(connTXSet_mutex) { + auto ret = this->ConnTxSet.insert(conn); + if (ret.second == FALSE) return; //Conn already exists. + this->scheduleAction(conn->txbuff.front()); + } +} + +void PandaJ2534Device::unstallConnectionTx(std::shared_ptr conn) { + synchronized(connTXSet_mutex) { + auto ret = this->ConnTxSet.insert(conn); + if (ret.second == TRUE) return; //Conn already exists. + this->insertActionIntoTaskList(conn->txbuff.front()); + } +} + +void PandaJ2534Device::removeConnectionTopAction(std::shared_ptr conn, std::shared_ptr msg) { + synchronized(task_queue_mutex) { + if (conn->txbuff.size() == 0) + return; + if (conn->txbuff.front() != msg) + return; + conn->txbuff.pop(); //Remove the top TX message from the connection tx queue. + + //Remove the connection from the active connection list if no more messages are scheduled with this connection. + if (conn->txbuff.size() == 0) { + //Update records showing the connection no longer has a tx record scheduled. + this->ConnTxSet.erase(conn); + } else { + //Add the next scheduled tx from this conn + this->scheduleAction(conn->txbuff.front()); + } + } +} diff --git a/drivers/windows/pandaJ2534DLL/PandaJ2534Device.h b/drivers/windows/pandaJ2534DLL/PandaJ2534Device.h new file mode 100644 index 0000000000..3e5880c955 --- /dev/null +++ b/drivers/windows/pandaJ2534DLL/PandaJ2534Device.h @@ -0,0 +1,77 @@ +#pragma once +#include +#include +#include +#include +#include +#include "J2534_v0404.h" +#include "panda/panda.h" +#include "synchronize.h" +#include "Action.h" +#include "MessageTx.h" +#include "J2534Connection.h" + +class J2534Connection; +class Action; +class MessageTx; + +/** +Class representing a physical panda adapter. Instances are created by +PassThruOpen in the J2534 API. A Device can create one or more +J2534Connections. +*/ +class PandaJ2534Device { +public: + PandaJ2534Device(std::unique_ptr new_panda); + + ~PandaJ2534Device(); + + static std::shared_ptr openByName(std::string sn); + + DWORD closeChannel(unsigned long ChannelID); + DWORD addChannel(std::shared_ptr& conn, unsigned long* channel_id); + + std::unique_ptr panda; + std::vector> connections; + + //Place the Action in the task queue based on the Action's expiration time, + //then signal the thread that processes actions. + void insertActionIntoTaskList(std::shared_ptr action); + + void scheduleAction(std::shared_ptr msg, BOOL startdelayed=FALSE); + + void registerConnectionTx(std::shared_ptr conn); + + //Resume sending messages from the provided Connection's TX queue. + void unstallConnectionTx(std::shared_ptr conn); + + //Cleans up several queues after a message completes, is canceled, or otherwise goes away. + void removeConnectionTopAction(std::shared_ptr conn, std::shared_ptr msg); + + //Messages that have been sent on the wire will be echoed by the panda when + //transmission is complete. This tracks what is still waiting to hear an echo. + std::queue> txMsgsAwaitingEcho; + +private: + HANDLE thread_kill_event; + + HANDLE can_thread_handle; + static DWORD WINAPI _can_recv_threadBootstrap(LPVOID This) { + return ((PandaJ2534Device*)This)->can_recv_thread(); + } + DWORD can_recv_thread(); + + HANDLE flow_control_wakeup_event; + HANDLE flow_control_thread_handle; + static DWORD WINAPI _msg_tx_threadBootstrap(LPVOID This) { + return ((PandaJ2534Device*)This)->msg_tx_thread(); + } + DWORD msg_tx_thread(); + std::list> task_queue; + Mutex task_queue_mutex; + + std::queue> ConnTxQueue; + std::set> ConnTxSet; + Mutex connTXSet_mutex; + BOOL txInProgress; +}; diff --git a/drivers/windows/pandaJ2534DLL/Timer.cpp b/drivers/windows/pandaJ2534DLL/Timer.cpp new file mode 100644 index 0000000000..2f20f888ee --- /dev/null +++ b/drivers/windows/pandaJ2534DLL/Timer.cpp @@ -0,0 +1,17 @@ +#include "stdafx.h" +#include "Timer.h" + + +Timer::Timer() +{ + start = std::chrono::time_point_cast(clock::now()); +} + +// gets the time elapsed from construction. +unsigned long long /*milliseconds*/ Timer::getTimePassed(){ + // get the new time + auto end = std::chrono::time_point_cast(clock::now()); + + // return the difference of the times + return (end - start).count(); +} \ No newline at end of file diff --git a/drivers/windows/pandaJ2534DLL/Timer.h b/drivers/windows/pandaJ2534DLL/Timer.h new file mode 100644 index 0000000000..d4888fc5e6 --- /dev/null +++ b/drivers/windows/pandaJ2534DLL/Timer.h @@ -0,0 +1,18 @@ +#pragma once +#include + +//Copied from https://stackoverflow.com/a/31488113 + +class Timer +{ + using clock = std::chrono::steady_clock; + using time_point_type = std::chrono::time_point < clock, std::chrono::milliseconds >; +public: + Timer(); + + // gets the time elapsed from construction. + unsigned long long /*milliseconds*/ getTimePassed(); + +private: + time_point_type start; +}; \ No newline at end of file diff --git a/drivers/windows/pandaJ2534DLL/constants_ISO15765.h b/drivers/windows/pandaJ2534DLL/constants_ISO15765.h new file mode 100644 index 0000000000..86928f1436 --- /dev/null +++ b/drivers/windows/pandaJ2534DLL/constants_ISO15765.h @@ -0,0 +1,20 @@ +#pragma once + +#define msg_is_extaddr(msg) check_bmask(msg->TxFlags, ISO15765_ADDR_TYPE) +#define msg_is_padded(msg) check_bmask(msg->TxFlags, ISO15765_FRAME_PAD) + +#define FRAME_SINGLE 0x00 +#define FRAME_FIRST 0x10 +#define FRAME_CONSEC 0x20 +#define FRAME_FLOWCTRL 0x30 + +#define FLOWCTRL_CONTINUE 0 +#define FLOWCTRL_WAIT 1 +#define FLOWCTRL_ABORT 2 + +#define msg_get_type(msg, addrlen) ((msg).Data[addrlen] & 0xF0) + +#define is_single(msg, addrlen) (msg_get_type(msg, addrlen) == FRAME_SINGLE) +#define is_first(msg, addrlen) (msg_get_type(msg, addrlen) == FRAME_FIRST) +#define is_consecutive(msg, addrlen) (msg_get_type(msg, addrlen) == FRAME_CONSEC) +#define is_flowctrl(msg, addrlen) (msg_get_type(msg, addrlen) == FRAME_FLOWCTRL) \ No newline at end of file diff --git a/drivers/windows/pandaJ2534DLL/dllmain.cpp b/drivers/windows/pandaJ2534DLL/dllmain.cpp new file mode 100644 index 0000000000..d4122e0b1d --- /dev/null +++ b/drivers/windows/pandaJ2534DLL/dllmain.cpp @@ -0,0 +1,22 @@ +// dllmain.cpp : Defines the entry point for the DLL application. +#include "dllmain.h" + +HMODULE thisdll; + +BOOL APIENTRY DllMain( HMODULE hModule, + DWORD ul_reason_for_call, + LPVOID lpReserved + ) +{ + thisdll = hModule; + + switch (ul_reason_for_call) + { + case DLL_PROCESS_ATTACH: + case DLL_THREAD_ATTACH: + case DLL_THREAD_DETACH: + case DLL_PROCESS_DETACH: + break; + } + return TRUE; +} diff --git a/drivers/windows/pandaJ2534DLL/dllmain.h b/drivers/windows/pandaJ2534DLL/dllmain.h new file mode 100644 index 0000000000..f49819e2c4 --- /dev/null +++ b/drivers/windows/pandaJ2534DLL/dllmain.h @@ -0,0 +1,4 @@ +#pragma once +#include "stdafx.h" + +extern HMODULE thisdll; diff --git a/drivers/windows/pandaJ2534DLL/pandaJ2534DLL.cpp b/drivers/windows/pandaJ2534DLL/pandaJ2534DLL.cpp new file mode 100644 index 0000000000..2e706f507d --- /dev/null +++ b/drivers/windows/pandaJ2534DLL/pandaJ2534DLL.cpp @@ -0,0 +1,433 @@ +// pandaJ2534DLL.cpp : Defines the exported functions for the DLL application. +// Protocol derived from the following sites (which shall be referred to as The Protocol Reference #). +// https://web.archive.org/web/20130805013326/https://tunertools.com/prodimages/DrewTech/Manuals/PassThru_API-1.pdf +// http://web.archive.org/web/20170910063536/http://www.tiecar.net/downloads/SAE_J2534_2002.pdf + +#include "stdafx.h" +#include "J2534_v0404.h" +#include "panda/panda.h" +#include "J2534Connection.h" +#include "J2534Connection_CAN.h" +#include "J2534Connection_ISO15765.h" +#include "PandaJ2534Device.h" +#include "dllmain.h" + +// A quick way to avoid the name mangling that __stdcall liked to do +#define EXPORT comment(linker, "/EXPORT:" __FUNCTION__ "=" __FUNCDNAME__) + +std::vector> pandas; + +int J25334LastError = 0; + +std::string GetProductAndVersion(TCHAR* szFilename)//std::string & strProductName, std::string & strProductVersion) +{ + // allocate a block of memory for the version info + DWORD dummy; + DWORD dwSize = GetFileVersionInfoSize(szFilename, &dummy); + if (dwSize == 0) { + return "error"; + } + std::vector data(dwSize); + + // load the version info + if (!GetFileVersionInfo(szFilename, NULL, dwSize, &data[0])) { + return "error"; + } + + // get the name and version strings + LPVOID pvProductName = NULL; + unsigned int iProductNameLen = 0; + LPVOID pvProductVersion = NULL; + unsigned int iProductVersionLen = 0; + + // 040904b0 is a language id. + if (!VerQueryValueA(&data[0], "\\StringFileInfo\\040904b0\\ProductName", &pvProductName, &iProductNameLen) || + !VerQueryValueA(&data[0], "\\StringFileInfo\\040904b0\\ProductVersion", &pvProductVersion, &iProductVersionLen)) { + return "error"; + } + + std::string ver_str = std::string((char*)pvProductVersion, iProductVersionLen-1); + std::string prod_str = std::string((char*)pvProductName, iProductNameLen-1); + std::string full_ver = prod_str + std::string(": ") + ver_str; + return full_ver; +} + +long ret_code(long code) { + J25334LastError = code; + return code; +} + +#define EXTRACT_DID(CID) (CID & 0xFFFF) +#define EXTRACT_CID(CID) ((CID >> 16) & 0xFFFF) + +long check_valid_DeviceID(unsigned long DeviceID) { + uint16_t dev_id = EXTRACT_DID(DeviceID); + if (pandas.size() <= dev_id || pandas[dev_id] == nullptr) + return ret_code(ERR_INVALID_DEVICE_ID); + return ret_code(STATUS_NOERROR); +} + +long check_valid_ChannelID(unsigned long ChannelID) { + uint16_t dev_id = EXTRACT_DID(ChannelID);; + uint16_t con_id = EXTRACT_CID(ChannelID); + + if (pandas.size() <= dev_id || pandas[dev_id] == nullptr) + return ret_code(ERR_INVALID_CHANNEL_ID); + + if (pandas[dev_id]->connections.size() <= con_id) return ret_code(ERR_INVALID_CHANNEL_ID); + if (pandas[dev_id]->connections[con_id] == nullptr) return ret_code(ERR_DEVICE_NOT_CONNECTED); + + return ret_code(STATUS_NOERROR); +} + +//Do not call without checking if the device/channel id exists first. +#define get_device(DeviceID) (pandas[EXTRACT_DID(DeviceID)]) +#define get_channel(ChannelID) (get_device(ChannelID)->connections[EXTRACT_CID(ChannelID)]) + +PANDAJ2534DLL_API long PTAPI PassThruOpen(void *pName, unsigned long *pDeviceID) { + #pragma EXPORT + if (pDeviceID == NULL) return ret_code(ERR_NULL_PARAMETER); + std::string sn = (pName == NULL) ? "" : std::string((char*)pName); + if (sn == "J2534-2:") + sn = ""; + + auto new_panda = PandaJ2534Device::openByName(sn); + if (new_panda == nullptr) { + if(sn == "" && pandas.size() == 1) + return ret_code(ERR_DEVICE_IN_USE); + for (auto& pn : pandas) { + if (pn->panda->get_usb_sn() == sn) + return ret_code(ERR_DEVICE_IN_USE); + } + return ret_code(ERR_DEVICE_NOT_CONNECTED); + } + + int panda_index = -1; + for (unsigned int i = 0; i < pandas.size(); i++) + if (pandas[i] == nullptr) { + panda_index = i; + pandas[panda_index] = std::move(new_panda); + break; + } + + if (panda_index == -1) { + if(pandas.size() == 0xFFFF) //device id will be 16 bit to fit channel next to it. + return ret_code(ERR_FAILED); //Too many pandas. Off the endangered species list. + pandas.push_back(std::move(new_panda)); + panda_index = pandas.size()-1; + } + + *pDeviceID = panda_index; + return ret_code(STATUS_NOERROR); +} +PANDAJ2534DLL_API long PTAPI PassThruClose(unsigned long DeviceID) { + #pragma EXPORT + if (check_valid_DeviceID(DeviceID) != STATUS_NOERROR) return J25334LastError; + get_device(DeviceID) = nullptr; + return ret_code(STATUS_NOERROR); +} +PANDAJ2534DLL_API long PTAPI PassThruConnect(unsigned long DeviceID, unsigned long ProtocolID, + unsigned long Flags, unsigned long BaudRate, unsigned long *pChannelID) { + #pragma EXPORT + if (pChannelID == NULL) return ret_code(ERR_NULL_PARAMETER); + if (check_valid_DeviceID(DeviceID) != STATUS_NOERROR) return J25334LastError; + auto& panda = get_device(DeviceID); + + std::shared_ptr conn; + + //TODO check if channel can be made + try { + switch (ProtocolID) { + //SW seems to refer to Single Wire. https://www.nxp.com/files-static/training_pdf/20451_BUS_COMM_WBT.pdf + //SW_ protocols may be touched on here: https://www.iso.org/obp/ui/#iso:std:iso:22900:-2:ed-1:v1:en + case J1850VPW: //These protocols are outdated and will not be supported. HDS wants them to not fail to open. + case J1850PWM: + case J1850VPW_PS: + case J1850PWM_PS: + case ISO9141: //This protocol could be implemented if 5 BAUD init support is added to the panda. + case ISO9141_PS: + conn = std::make_shared(panda, ProtocolID, Flags, BaudRate); + break; + case ISO14230: //Only supporting Fast init until panda adds support for 5 BAUD init. + case ISO14230_PS: + conn = std::make_shared(panda, ProtocolID, Flags, BaudRate); + break; + case CAN: + case CAN_PS: + //case SW_CAN_PS: + conn = std::make_shared(panda, ProtocolID, Flags, BaudRate); + break; + case ISO15765: + case ISO15765_PS: + conn = std::make_shared(panda, ProtocolID, Flags, BaudRate); + break; + //case SW_ISO15765_PS: // SW = Single Wire. GMLAN is a SW CAN protocol + //case GM_UART_PS: // PS = Pin Select. Handles different ports. + //Looks like SCI based protocols may not be compatible with the panda: + //http://mdhmotors.com/can-communications-vehicle-network-protocols/3/ + //case SCI_A_ENGINE: + //case SCI_A_TRANS: + //case SCI_B_ENGINE: + //case SCI_B_TRANS: + //case J2610_PS: + default: + return ret_code(ERR_INVALID_PROTOCOL_ID); + } + } catch (int e) { + return ret_code(e); + } + + unsigned long channel_index; + unsigned long err = panda->addChannel(conn, &channel_index); + if (err == STATUS_NOERROR) + *pChannelID = (channel_index << 16) | DeviceID; + + return ret_code(err); +} +PANDAJ2534DLL_API long PTAPI PassThruDisconnect(unsigned long ChannelID) { + #pragma EXPORT + unsigned long res = check_valid_DeviceID(ChannelID); + if (res == ERR_INVALID_DEVICE_ID) return ret_code(ERR_INVALID_CHANNEL_ID); + if (res != STATUS_NOERROR) return J25334LastError; + return ret_code(get_device(ChannelID)->closeChannel(EXTRACT_CID(ChannelID))); +} +PANDAJ2534DLL_API long PTAPI PassThruReadMsgs(unsigned long ChannelID, PASSTHRU_MSG *pMsg, + unsigned long *pNumMsgs, unsigned long Timeout) { + #pragma EXPORT + if (pMsg == NULL || pNumMsgs == NULL) return ret_code(ERR_NULL_PARAMETER); + if (check_valid_ChannelID(ChannelID) != STATUS_NOERROR) return J25334LastError; + return ret_code(get_channel(ChannelID)->PassThruReadMsgs(pMsg, pNumMsgs, Timeout)); +} +PANDAJ2534DLL_API long PTAPI PassThruWriteMsgs(unsigned long ChannelID, PASSTHRU_MSG *pMsg, unsigned long *pNumMsgs, unsigned long Timeout) { + #pragma EXPORT + if (pMsg == NULL || pNumMsgs == NULL) return ret_code(ERR_NULL_PARAMETER); + if (check_valid_ChannelID(ChannelID) != STATUS_NOERROR) return J25334LastError; + return ret_code(get_channel(ChannelID)->PassThruWriteMsgs(pMsg, pNumMsgs, Timeout)); +} +PANDAJ2534DLL_API long PTAPI PassThruStartPeriodicMsg(unsigned long ChannelID, PASSTHRU_MSG *pMsg, unsigned long *pMsgID, unsigned long TimeInterval) { + #pragma EXPORT + if (pMsg == NULL || pMsgID == NULL) return ret_code(ERR_NULL_PARAMETER); + if (check_valid_ChannelID(ChannelID) != STATUS_NOERROR) return J25334LastError; + return ret_code(get_channel(ChannelID)->PassThruStartPeriodicMsg(pMsg, pMsgID, TimeInterval)); +} +PANDAJ2534DLL_API long PTAPI PassThruStopPeriodicMsg(unsigned long ChannelID, unsigned long MsgID) { + #pragma EXPORT + if (check_valid_ChannelID(ChannelID) != STATUS_NOERROR) return J25334LastError; + return ret_code(get_channel(ChannelID)->PassThruStopPeriodicMsg(MsgID)); +} +PANDAJ2534DLL_API long PTAPI PassThruStartMsgFilter(unsigned long ChannelID, unsigned long FilterType, PASSTHRU_MSG *pMaskMsg, + PASSTHRU_MSG *pPatternMsg, PASSTHRU_MSG *pFlowControlMsg, unsigned long *pFilterID) { + #pragma EXPORT + if (FilterType != PASS_FILTER && FilterType != BLOCK_FILTER && FilterType != FLOW_CONTROL_FILTER) return ret_code(ERR_NULL_PARAMETER); + if (!pFilterID || (!pMaskMsg && !pPatternMsg && !pFlowControlMsg)) return ret_code(ERR_NULL_PARAMETER); + if (check_valid_ChannelID(ChannelID) != STATUS_NOERROR) return J25334LastError; + return ret_code(get_channel(ChannelID)->PassThruStartMsgFilter(FilterType, pMaskMsg, pPatternMsg, pFlowControlMsg, pFilterID)); +} +PANDAJ2534DLL_API long PTAPI PassThruStopMsgFilter(unsigned long ChannelID, unsigned long FilterID) { + #pragma EXPORT + if (check_valid_ChannelID(ChannelID) != STATUS_NOERROR) return J25334LastError; + return ret_code(get_channel(ChannelID)->PassThruStopMsgFilter(FilterID)); +} +PANDAJ2534DLL_API long PTAPI PassThruSetProgrammingVoltage(unsigned long DeviceID, unsigned long PinNumber, unsigned long Voltage) { + #pragma EXPORT + //Unused + if (check_valid_DeviceID(DeviceID) != STATUS_NOERROR) return J25334LastError; + auto& panda = get_device(DeviceID); + + switch (Voltage) { + case SHORT_TO_GROUND: + break; + case VOLTAGE_OFF: + break; + default: + if (!(5000 <= Voltage && Voltage <= 20000)) + return ret_code(ERR_NOT_SUPPORTED); + break; + } + + return ret_code(STATUS_NOERROR); +} +PANDAJ2534DLL_API long PTAPI PassThruReadVersion(unsigned long DeviceID, char *pFirmwareVersion, char *pDllVersion, char *pApiVersion) { + #pragma EXPORT + if (!pFirmwareVersion || !pDllVersion || !pApiVersion) return ret_code(ERR_NULL_PARAMETER); + if (check_valid_DeviceID(DeviceID) != STATUS_NOERROR) return J25334LastError; + + auto& panda = get_device(DeviceID); + auto fw_version = panda->panda->get_version(); + strcpy_s(pFirmwareVersion, 80, fw_version.c_str()); + + std::string j2534dll_ver; + TCHAR pandalib_filename[MAX_PATH + 1] = { 0 }; + if (GetModuleFileName(thisdll, pandalib_filename, MAX_PATH) == 0) { + j2534dll_ver = "error"; + } else { + j2534dll_ver = GetProductAndVersion(pandalib_filename); + } + std::string pandalib_ver = GetProductAndVersion(_T("panda.dll")); + std::string fullver = "(" + j2534dll_ver + "; " + pandalib_ver + ")"; + strcpy_s(pDllVersion, 80, fullver.c_str()); + + strcpy_s(pApiVersion, 80, J2534_APIVER_NOVEMBER_2004); + return ret_code(STATUS_NOERROR); +} +PANDAJ2534DLL_API long PTAPI PassThruGetLastError(char *pErrorDescription) { + #pragma EXPORT + if (pErrorDescription == NULL) return ret_code(ERR_NULL_PARAMETER); + switch (J25334LastError) { + case STATUS_NOERROR: + strcpy_s(pErrorDescription, 80, "Function call successful."); + break; + case ERR_NOT_SUPPORTED: + strcpy_s(pErrorDescription, 80, "Device cannot support requested functionality mandated in J2534."); + break; + case ERR_INVALID_CHANNEL_ID: + strcpy_s(pErrorDescription, 80, "Invalid ChannelID value."); + break; + case ERR_INVALID_PROTOCOL_ID: + strcpy_s(pErrorDescription, 80, "Invalid or unsupported ProtocolID, or resource conflict."); + break; + case ERR_NULL_PARAMETER: + strcpy_s(pErrorDescription, 80, "NULL pointer supplied where a valid pointer is required."); + break; + case ERR_INVALID_IOCTL_VALUE: + strcpy_s(pErrorDescription, 80, "Invalid value for Ioctl parameter."); + break; + case ERR_INVALID_FLAGS: + strcpy_s(pErrorDescription, 80, "Invalid flag values."); + break; + case ERR_FAILED: + strcpy_s(pErrorDescription, 80, "Undefined error."); + break; + case ERR_DEVICE_NOT_CONNECTED: + strcpy_s(pErrorDescription, 80, "Unable to communicate with device."); + break; + case ERR_TIMEOUT: + strcpy_s(pErrorDescription, 80, "Read or write timeout:"); + // PassThruReadMsgs() - No message available to read or could not read the specified number of messages. The actual number of messages read is placed in . + // PassThruWriteMsgs() - Device could not write the specified number of messages. The actual number of messages sent on the vehicle network is placed in . + break; + case ERR_INVALID_MSG: + strcpy_s(pErrorDescription, 80, "Invalid message structure pointed to by pMsg."); + break; + case ERR_INVALID_TIME_INTERVAL: + strcpy_s(pErrorDescription, 80, "Invalid TimeInterval value."); + break; + case ERR_EXCEEDED_LIMIT: + strcpy_s(pErrorDescription, 80, "Exceeded maximum number of message IDs or allocated space."); + break; + case ERR_INVALID_MSG_ID: + strcpy_s(pErrorDescription, 80, "Invalid MsgID value."); + break; + case ERR_DEVICE_IN_USE: + strcpy_s(pErrorDescription, 80, "Device is currently open."); + break; + case ERR_INVALID_IOCTL_ID: + strcpy_s(pErrorDescription, 80, "Invalid IoctlID value."); + break; + case ERR_BUFFER_EMPTY: + strcpy_s(pErrorDescription, 80, "Protocol message buffer empty."); + break; + case ERR_BUFFER_FULL: + strcpy_s(pErrorDescription, 80, "Protocol message buffer full. Messages may have been lost."); + break; + case ERR_BUFFER_OVERFLOW: + strcpy_s(pErrorDescription, 80, "A buffer overflow occurred and messages were lost."); + break; + case ERR_PIN_INVALID: + strcpy_s(pErrorDescription, 80, "Invalid pin number, or pin number already in use."); + break; + case ERR_CHANNEL_IN_USE: + strcpy_s(pErrorDescription, 80, "Channel number is currently connected."); + break; + case ERR_MSG_PROTOCOL_ID: + strcpy_s(pErrorDescription, 80, "The Message's Protocol does not match the Channel's protocol."); + break; + case ERR_INVALID_FILTER_ID: + strcpy_s(pErrorDescription, 80, "Invalid Filter ID value."); + break; + case ERR_NO_FLOW_CONTROL: + strcpy_s(pErrorDescription, 80, "No flow control filter set or matched."); + break; + case ERR_NOT_UNIQUE: + strcpy_s(pErrorDescription, 80, "This filter already exists."); + break; + case ERR_INVALID_BAUDRATE: + strcpy_s(pErrorDescription, 80, "The desired baud rate cannot be achieved within SAE tolerance."); + break; + case ERR_INVALID_DEVICE_ID: + strcpy_s(pErrorDescription, 80, "Device ID invalid."); + break; + } + return ret_code(STATUS_NOERROR); +} +PANDAJ2534DLL_API long PTAPI PassThruIoctl(unsigned long ChannelID, unsigned long IoctlID, + void *pInput, void *pOutput) { + #pragma EXPORT + if (check_valid_ChannelID(ChannelID) != STATUS_NOERROR) return J25334LastError; + auto& dev_entry = get_device(ChannelID); + //get_channel(ChannelID) + + switch (IoctlID) { + case GET_CONFIG: + { + SCONFIG_LIST *inconfig = (SCONFIG_LIST*)pInput; + if (inconfig == NULL) + return ret_code(ERR_NULL_PARAMETER); + for (unsigned int i = 0; i < inconfig->NumOfParams; i++) { + try { + inconfig->ConfigPtr[i].Value = get_channel(ChannelID)->processIOCTLGetConfig(inconfig->ConfigPtr[i].Parameter); + } catch (int e) { + return ret_code(e); + } + } + break; + } + case SET_CONFIG: + { + SCONFIG_LIST *inconfig = (SCONFIG_LIST*)pInput; + if (inconfig == NULL) + return ret_code(ERR_NULL_PARAMETER); + for (unsigned int i = 0; i < inconfig->NumOfParams; i++) { + try { + get_channel(ChannelID)->processIOCTLSetConfig(inconfig->ConfigPtr[i].Parameter, inconfig->ConfigPtr[i].Value); + } catch (int e) { + return ret_code(e); + } + } + break; + } + case READ_VBATT: + panda::PANDA_HEALTH health = dev_entry->panda->get_health(); + *(unsigned long*)pOutput = health.voltage; + break; + case FIVE_BAUD_INIT: + if (!pInput || !pOutput) return ret_code(ERR_NULL_PARAMETER); + return ret_code(get_channel(ChannelID)->init5b((SBYTE_ARRAY*)pInput, (SBYTE_ARRAY*)pOutput)); + case FAST_INIT: + if (!pInput || !pOutput) return ret_code(ERR_NULL_PARAMETER); + return ret_code(get_channel(ChannelID)->initFast((PASSTHRU_MSG*)pInput, (PASSTHRU_MSG*)pOutput)); + case CLEAR_TX_BUFFER: + return ret_code(get_channel(ChannelID)->clearTXBuff()); + case CLEAR_RX_BUFFER: + return ret_code(get_channel(ChannelID)->clearRXBuff()); + case CLEAR_PERIODIC_MSGS: + return ret_code(get_channel(ChannelID)->clearPeriodicMsgs()); + case CLEAR_MSG_FILTERS: + return ret_code(get_channel(ChannelID)->clearMsgFilters()); + case CLEAR_FUNCT_MSG_LOOKUP_TABLE: // LOOKUP TABLE IS RELATED TO J1850 PWM. Unsupported. + if (!pInput) return ret_code(ERR_NULL_PARAMETER); + return ret_code(STATUS_NOERROR); + case ADD_TO_FUNCT_MSG_LOOKUP_TABLE: // LOOKUP TABLE IS RELATED TO J1850 PWM. Unsupported. + if (!pInput) return ret_code(ERR_NULL_PARAMETER); + return ret_code(STATUS_NOERROR); + case DELETE_FROM_FUNCT_MSG_LOOKUP_TABLE: // LOOKUP TABLE IS RELATED TO J1850 PWM. Unsupported. + return ret_code(STATUS_NOERROR); + case READ_PROG_VOLTAGE: + *(unsigned long*)pOutput = 0; + break; + default: + printf("Got unknown IIOCTL %X\n", IoctlID); + } + + return ret_code(STATUS_NOERROR); +} diff --git a/drivers/windows/pandaJ2534DLL/pandaJ2534DLL.rc b/drivers/windows/pandaJ2534DLL/pandaJ2534DLL.rc new file mode 100644 index 0000000000000000000000000000000000000000..e359044825257ca8767ea76b363260b861f89007 GIT binary patch literal 4630 zcmdUzTW=CU6vxlAiQi$QFE%!`v^B;@3lyvLl0u0lO-Pltk{~ody(E5i_4l7)y1VRB zQ}h9|S!U+Ux!-1%Uq3f()0`bz-#*&dMmFKSvMI0*u!-H;g$-C$?HP}=YrC`|?-=-$ zu?K9-D7sr_ADKH=;?}ntaLV@B9wBAZk841O><+;0dE8QtzHFbY@)UH z@s9k^#_D(c9$q(}zdT@MY`(#z9sTTEf zMs-z@+$Fo3JmUL<$1S96!{d}3?m~40{koUh1bPJYjIrVKG(rMi1KtPJ>TBD8cMH5d zAc1Bcqswln>W~4lWpM_mJ~~+P7OA!Wt``(ndCUoodMo&>7}NRvJ#26IP9bbJdx|^n zxoyq5ui_UxCMxxnWn>g}{F3GSP07ybTjykS=>3V7i!|Cw*IVGuCievN(ym!%2&+d#S@m8Dr z%n2F>yzSh6=$BcnD7m=y)m@MAt2|RegDLUW&Fq>8^|9=dI1SNtG*^wq++tN^xyq6) zd+9Cuz;Cv$6Plvl6nEp;A&$D^$Ok3#)?Mg^({5k!W+8bbFyg{c|GsBFW`?^$zvLWZaw5X{JckgIp$jHPAuH=QhH@8 zGwM@;+t%!@JczHN9P}BY+aTx5#E!(~GIk7jisM=A*CsY!dkKo&4N+6RU2~6_!Y9Nn zzoR=&)!#X`v9Dq;9whU4CPR5G+hT0BO6SYJvhf6YBYbm922Stsq_f1Aj?9oJLjF9& zqgiRo=S6bL$H?U&*}CrFzwwmQx>JV?9W>~h zXq(KmzxdStH}~lD3A$QyS)YExS$E%8QvTMmS{9|Xk!4!P@o&GEb&I_JdpY_tt;K51 VrQzayAJUcdk52yUI3IU$`V9lgBV+&o literal 0 HcmV?d00001 diff --git a/drivers/windows/pandaJ2534DLL/pandaJ2534DLL.vcxproj b/drivers/windows/pandaJ2534DLL/pandaJ2534DLL.vcxproj new file mode 100644 index 0000000000..065fa69adc --- /dev/null +++ b/drivers/windows/pandaJ2534DLL/pandaJ2534DLL.vcxproj @@ -0,0 +1,152 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + + {A2BB18A5-F26B-48D6-BBB5-B83D64473C77} + Win32Proj + pandaJ2534DLL + 8.1 + + + + DynamicLibrary + true + v140 + Unicode + + + DynamicLibrary + false + v140 + true + Unicode + + + + + + + + + + + + + + + true + $(SolutionDir)$(Configuration)_$(PlatformShortName)\ + pandaJ2534_0404_32 + + + false + $(SolutionDir)$(Configuration)_$(PlatformShortName)\ + pandaJ2534_0404_32 + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_USRDLL;PANDAJ2534DLL_EXPORTS;%(PreprocessorDefinitions) + true + $(SolutionDir); + + + Windows + true + kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies);version.lib;$(OutDir)panda.lib + + + + + Level3 + Use + MaxSpeed + true + true + WIN32;NDEBUG;_WINDOWS;_USRDLL;PANDAJ2534DLL_EXPORTS;%(PreprocessorDefinitions) + true + $(SolutionDir); + + + Windows + true + true + true + kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies);version.lib;$(OutDir)panda.lib + + + + + + + + + + + + + + + + + + + + + + + + + + + + + false + + + false + + + + + + + + + + + + + + + Create + Create + + + + + + {5528aefb-638d-49af-b9d4-965154e7d531} + + + + + + + + + + + + \ No newline at end of file diff --git a/drivers/windows/pandaJ2534DLL/pandaJ2534DLL.vcxproj.filters b/drivers/windows/pandaJ2534DLL/pandaJ2534DLL.vcxproj.filters new file mode 100644 index 0000000000..57f7cefb08 --- /dev/null +++ b/drivers/windows/pandaJ2534DLL/pandaJ2534DLL.vcxproj.filters @@ -0,0 +1,155 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + {a4cd0bce-0a2a-43d9-9c9f-b21a3b607e90} + + + {a85ee263-380d-4d37-b167-6629cfd5177f} + + + {010a0176-a146-4d3a-824a-fd683904774d} + + + {71c9502a-ee59-4d5e-873f-c9cc792e7c76} + + + {4fd3183a-c457-430c-b762-f767a5788bca} + + + {53cd179e-22d8-43e2-bc61-516d3861fae6} + + + {08d548b5-4d0b-4ce4-85e6-5ff3fc987758} + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files\J2534_CAN + + + Header Files\J2534_ISO15765 + + + Header Files\depends + + + Header Files\depends + + + Header Files\boilerplate + + + Header Files\boilerplate + + + Header Files\boilerplate + + + Header Files\boilerplate + + + Header Files + + + Header Files\J2534_ISO15765 + + + Header Files + + + Header Files\J2534_ISO15765 + + + Header Files\J2534_CAN + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files\J2534_CAN + + + Source Files\J2534_ISO15765 + + + Source Files\boilerplate + + + Source Files\boilerplate + + + Source Files\J2534_ISO15765 + + + Source Files + + + Source Files\J2534_CAN + + + Source Files + + + + + Resource Files + + + + + + \ No newline at end of file diff --git a/drivers/windows/pandaJ2534DLL/resource.h b/drivers/windows/pandaJ2534DLL/resource.h new file mode 100644 index 0000000000..771e7b80bc --- /dev/null +++ b/drivers/windows/pandaJ2534DLL/resource.h @@ -0,0 +1,14 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by pandaJ2534DLL.rc + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 101 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/drivers/windows/pandaJ2534DLL/stdafx.cpp b/drivers/windows/pandaJ2534DLL/stdafx.cpp new file mode 100644 index 0000000000..c27db9ee2d --- /dev/null +++ b/drivers/windows/pandaJ2534DLL/stdafx.cpp @@ -0,0 +1,8 @@ +// stdafx.cpp : source file that includes just the standard includes +// pandaJ2534DLL.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + +// TODO: reference any additional headers you need in STDAFX.H +// and not in this file diff --git a/drivers/windows/pandaJ2534DLL/stdafx.h b/drivers/windows/pandaJ2534DLL/stdafx.h new file mode 100644 index 0000000000..bd4a4b6f78 --- /dev/null +++ b/drivers/windows/pandaJ2534DLL/stdafx.h @@ -0,0 +1,14 @@ +#pragma once + +#include "targetver.h" + +#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers +// Windows Header Files: +#include + +#include +#include +#include +#include +#include +#include \ No newline at end of file diff --git a/drivers/windows/pandaJ2534DLL/synchronize.h b/drivers/windows/pandaJ2534DLL/synchronize.h new file mode 100644 index 0000000000..446dfc19e3 --- /dev/null +++ b/drivers/windows/pandaJ2534DLL/synchronize.h @@ -0,0 +1,56 @@ +#pragma once +#define WIN32_LEAN_AND_MEAN +#include + +//Inspired/directly copied from https://www.codeproject.com/Articles/12362/A-quot-synchronized-quot-statement-for-C-like-in-J +//Enables easier synchronization +class Mutex { +public: + Mutex() { + InitializeCriticalSectionAndSpinCount(&critSection, 0x00000400); + //InitializeCriticalSection(&critSection); + } + + ~Mutex() { + DeleteCriticalSection(&critSection); + } + + void lock() { + EnterCriticalSection(&critSection); + } + + void unlock() { + LeaveCriticalSection(&critSection); + } + +private: + CRITICAL_SECTION critSection; +}; + +//Synchronization Controller Object +class Lock { +public: + Lock(Mutex &m) : mutex(m), locked(TRUE) { + m.lock(); + } + + ~Lock() { + mutex.unlock(); + } + + operator bool() const { + return locked; + } + + void setUnlock() { + locked = FALSE; + } + +private: + Mutex& mutex; + bool locked; +}; + +//A useful shorthand for locking and unlocking a mutex over a scope. +//CAUTION, implemented with a for loop, so break/continue are consumed. +#define synchronized(M) for(Lock M##_lock = M; M##_lock; M##_lock.setUnlock()) diff --git a/drivers/windows/pandaJ2534DLL/targetver.h b/drivers/windows/pandaJ2534DLL/targetver.h new file mode 100644 index 0000000000..1bf4ee6fee --- /dev/null +++ b/drivers/windows/pandaJ2534DLL/targetver.h @@ -0,0 +1,13 @@ +#pragma once + +// Including SDKDDKVer.h defines the highest available Windows platform. + +// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and +// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h. + +#include + +#define WINVER _WIN32_WINNT_WIN7 +#define _WIN32_WINNT _WIN32_WINNT_WIN7 + +#include diff --git a/drivers/windows/panda_install.nsi b/drivers/windows/panda_install.nsi new file mode 100644 index 0000000000..81ecc3c872 --- /dev/null +++ b/drivers/windows/panda_install.nsi @@ -0,0 +1,212 @@ +!define J2534_Reg_Path "Software\PassThruSupport.04.04\comma.ai - panda" +!define Install_Name "panda J2534 Drivers" + +;NOTE! The panda software requires a VC runtime to be installed in order to work. +;This installer must be bundled with the appropriate runtime installer, and have +;the installation registry key set so the installer can tell if the runtime is +;already installed. Copy vscruntimeinfo.nsh.sample to vscruntimeinfo.nsh and edit +;it for your version of Visual Studio. +!include "redist\vscruntimeinfo.nsh" + +;-------------------------------- +;Include Modern UI +!include "MUI2.nsh" +!include "x64.nsh" + +!define MUI_ICON "panda.ico" +;NSIS is ignoring the unicon unless it is the same as the normal icon +;!define MUI_UNICON "panda_remove.ico" + +;Properly display all languages (Installer will not work on Windows 95, 98 or ME!) +Unicode true + +# Set the installer display name +Name "panda Driver" + +# set the name of the installer +Outfile "panda install.exe" + +; The default installation directory +InstallDir $PROGRAMFILES\comma.ai\panda + +; Request application privileges for UAC +RequestExecutionLevel admin + +; Registry key to check for directory (so if you install again, it will +; overwrite the old one automatically) +InstallDirRegKey HKLM "SOFTWARE\${Install_Name}" "Install_Dir" + +;-------------------------------- +; Pages +!insertmacro MUI_PAGE_WELCOME +!insertmacro MUI_PAGE_LICENSE "..\..\LICENSE" +!insertmacro MUI_PAGE_COMPONENTS +!insertmacro MUI_PAGE_DIRECTORY +!insertmacro MUI_PAGE_INSTFILES + +!insertmacro MUI_UNPAGE_CONFIRM +!insertmacro MUI_UNPAGE_INSTFILES + +!insertmacro MUI_LANGUAGE "English" ;first language is the default language + +; ------------------------------------------------------------------------------------------------- +; Additional info (will appear in the "details" tab of the properties window for the installer) + +VIAddVersionKey /LANG=${LANG_ENGLISH} "ProductName" "panda OBD-II adapter" +VIAddVersionKey /LANG=${LANG_ENGLISH} "Comments" "" +VIAddVersionKey /LANG=${LANG_ENGLISH} "CompanyName" "comma.ai" +VIAddVersionKey /LANG=${LANG_ENGLISH} "LegalTrademarks" "Application released under the MIT license" +;VIAddVersionKey /LANG=${LANG_ENGLISH} "LegalCopyright" "© ${PRODUCT_NAME} Team" +;VIAddVersionKey /LANG=${LANG_ENGLISH} "FileDescription" "Jessy Exum" +;VIAddVersionKey /LANG=${LANG_ENGLISH} "FileVersion" "${PRODUCT_VERSION}" +VIProductVersion "1.0.0.0" + +;-------------------------------- +; Install Sections +Section "panda driver (required)" + + SectionIn RO + + SetOutPath "$INSTDIR" + + + ;If the visual studio version this project is compiled with changes, this section + ;must be revisited. The registry key must be changed, and the VS redistributable + ;binary must be updated to the VS version used. + ClearErrors + ReadRegStr $0 HKLM ${VCRuntimeRegKey} "Version" + ${If} ${Errors} + DetailPrint "Installing Visual Studio C Runtime..." + File "${VCRuntimeSetupPath}\${VCRuntimeSetupFile}" + ExecWait '"$INSTDIR\${VCRuntimeSetupFile}" /passive /norestart' + ${Else} + DetailPrint "Visual Studio C Runtime already installed." + ${EndIf} + + ;Remove the now unnecessary runtime installer. + Delete "$INSTDIR\${VCRuntimeSetupFile}" + + ;Do the rest of the install + SetOutPath "$INSTDIR\driver" + + ; The inf file works for both 32 and 64 bit. + File "Debug_x86\panda Driver Package\panda.inf" + File "Debug_x86\panda Driver Package\panda.cat" + ${DisableX64FSRedirection} + nsExec::ExecToLog '"$SYSDIR\PnPutil.exe" /a "$INSTDIR\driver\panda.inf"' + ${EnableX64FSRedirection} + + SetOutPath $SYSDIR + + File Release_x86\panda.dll + + ${If} ${RunningX64} + ${DisableX64FSRedirection} + ;Note that the x64 VS redistributable is not installed to prevent bloat. + ;If you are the rare person who uses the 64 bit raw panda driver, please + ;install the correct x64 VS runtime manually. + File Release_x64\panda.dll + ${EnableX64FSRedirection} + ${EndIf} + + ; Write the installation path into the registry + WriteRegStr HKLM "SOFTWARE\panda J2534 Drivers" "Install_Dir" "$INSTDIR" + + ; Write the uninstall keys for Windows + ;WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${Install_Name}" "DisplayVersion" "" + WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${Install_Name}" "DisplayIcon" '"$SYSDIR\panda.dll",0' + WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${Install_Name}" "DisplayName" "panda J2534 Drivers" + WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${Install_Name}" "Publisher" "comma.ai" + WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${Install_Name}" "UninstallString" '"$INSTDIR\uninstall.exe"' + WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${Install_Name}" "URLInfoAbout" "https://github.com/commaai/panda/" + WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${Install_Name}" "NoModify" 1 + WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${Install_Name}" "NoRepair" 1 + + SetOutPath $INSTDIR + WriteUninstaller "uninstall.exe" + +SectionEnd + +Section "panda devel lib/header" + + SetOutPath "$INSTDIR\devel" + File panda\panda.h + + SetOutPath "$INSTDIR\devel\x86" + File Release_x86\panda.lib + + SetOutPath "$INSTDIR\devel\x64" + File Release_x64\panda.lib + +SectionEnd + +Section "J2534 Driver" + + SetOutPath $INSTDIR + + File Release_x86\pandaJ2534_0404_32.dll + + SetRegView 32 + WriteRegDWORD HKLM "${J2534_Reg_Path}" "CAN" 00000001 + WriteRegStr HKLM "${J2534_Reg_Path}" "FunctionLibrary" "$INSTDIR\pandaJ2534_0404_32.dll" + WriteRegDWORD HKLM "${J2534_Reg_Path}" "ISO15765" 00000001 + WriteRegDWORD HKLM "${J2534_Reg_Path}" "J1850VPW" 00000000 + WriteRegDWORD HKLM "${J2534_Reg_Path}" "SCI_A_ENGINE" 00000000 + WriteRegDWORD HKLM "${J2534_Reg_Path}" "SCI_A_TRANS" 00000000 + WriteRegDWORD HKLM "${J2534_Reg_Path}" "SCI_B_ENGINE" 00000000 + WriteRegDWORD HKLM "${J2534_Reg_Path}" "SCI_B_TRANS" 00000000 + WriteRegDWORD HKLM "${J2534_Reg_Path}" "J1850PWM" 00000000 + WriteRegDWORD HKLM "${J2534_Reg_Path}" "ISO9141" 00000000 + WriteRegDWORD HKLM "${J2534_Reg_Path}" "ISO14230" 00000001 + WriteRegStr HKLM "${J2534_Reg_Path}" "Name" "panda" + WriteRegStr HKLM "${J2534_Reg_Path}" "Vendor" "comma.ai" + WriteRegStr HKLM "${J2534_Reg_Path}" "ConfigApplication" "" + DetailPrint "Registered J2534 Driver" + +SectionEnd + +;-------------------------------- +; Uninstaller +Section "Uninstall" + + ; Removing the inf file for winusb is not easy to do. + ; The best solution I can find is parsing the output + ; of the pnputil.exe /e command to find the oem#.inf + ; file that lists comma.ai as the provider. Not sure + ; if Microsoft wants these inf files to be removed. + ; Consider https://blog.sverrirs.com/2015/12/creating-windows-installer-and.html + ; These lines just remove the inf backups. + Delete "$INSTDIR\driver\panda.inf" + Delete "$INSTDIR\driver\panda.cat" + RMDir "$INSTDIR\driver" + + ; Remove WinUSB driver library + Delete $SYSDIR\panda.dll + ${If} ${RunningX64} + ${DisableX64FSRedirection} + Delete $SYSDIR\panda.dll + ${EnableX64FSRedirection} + ${EndIf} + + ; Remove devel files + Delete "$INSTDIR\devel\x86\panda.lib" + RMDir "$INSTDIR\devel\x86" + Delete "$INSTDIR\devel\x64\panda.lib" + RMDir "$INSTDIR\devel\x64" + Delete "$INSTDIR\devel\panda.h" + RMDir "$INSTDIR\devel" + + ; Remove registry keys + DeleteRegKey HKLM "${J2534_Reg_Path}" + DeleteRegKey HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${Install_Name}" + DeleteRegKey HKLM "SOFTWARE\${Install_Name}" + + ; Remove files and uninstaller + Delete "$INSTDIR\uninstall.exe" + Delete "$INSTDIR\pandaJ2534_0404_32.dll" + + ; Remove directories used + RMDir "$INSTDIR" + RMDir "$PROGRAMFILES\comma.ai" + +SectionEnd diff --git a/drivers/windows/panda_playground/ReadMe.txt b/drivers/windows/panda_playground/ReadMe.txt new file mode 100644 index 0000000000..37dba5d877 --- /dev/null +++ b/drivers/windows/panda_playground/ReadMe.txt @@ -0,0 +1,40 @@ +======================================================================== + CONSOLE APPLICATION : panda_playground Project Overview +======================================================================== + +AppWizard has created this panda_playground application for you. + +This file contains a summary of what you will find in each of the files that +make up your panda_playground application. + + +panda_playground.vcxproj + This is the main project file for VC++ projects generated using an Application Wizard. + It contains information about the version of Visual C++ that generated the file, and + information about the platforms, configurations, and project features selected with the + Application Wizard. + +panda_playground.vcxproj.filters + This is the filters file for VC++ projects generated using an Application Wizard. + It contains information about the association between the files in your project + and the filters. This association is used in the IDE to show grouping of files with + similar extensions under a specific node (for e.g. ".cpp" files are associated with the + "Source Files" filter). + +panda_playground.cpp + This is the main application source file. + +///////////////////////////////////////////////////////////////////////////// +Other standard files: + +StdAfx.h, StdAfx.cpp + These files are used to build a precompiled header (PCH) file + named panda_playground.pch and a precompiled types file named StdAfx.obj. + +///////////////////////////////////////////////////////////////////////////// +Other notes: + +AppWizard uses "TODO:" comments to indicate parts of the source code you +should add to or customize. + +///////////////////////////////////////////////////////////////////////////// diff --git a/drivers/windows/panda_playground/panda_playground.cpp b/drivers/windows/panda_playground/panda_playground.cpp new file mode 100644 index 0000000000..0f51924dbc --- /dev/null +++ b/drivers/windows/panda_playground/panda_playground.cpp @@ -0,0 +1,86 @@ +// panda_playground.cpp : Defines the entry point for the console application. +// + +#include "stdafx.h" +#include "pandaJ2534DLL Test\Loader4.h" +#include "ECUsim DLL\ECUsim.h" +#include + + +int _tmain(int Argc, _TCHAR *Argv) { + UNREFERENCED_PARAMETER(Argc); + UNREFERENCED_PARAMETER(Argv); + + ECUsim sim("", 500000); + + //if (LoadJ2534Dll("C:\\WINDOWS\\SysWOW64\\op20pt32.dll") != 0) { + if (LoadJ2534Dll("pandaJ2534.dll") != 0) { + auto err = GetLastError(); + return 1; + } + unsigned long did, cid, fid; + PassThruOpen("", &did); + PassThruConnect(did, ISO15765, CAN_29BIT_ID, 500000, &cid); + + PASSTHRU_MSG mask, pattern, flow; + + memcpy(mask.Data, "\xff\xff\xff\xff", 4); + mask.DataSize = 4; + mask.ProtocolID = ISO15765; + mask.TxFlags = CAN_29BIT_ID; + mask.ExtraDataIndex = 0; + mask.RxStatus = 0; + + ////////////////////////18//DA//F1//EF + memcpy(pattern.Data, "\x18\xda\xf1\xef", 4); + pattern.DataSize = 4; + pattern.ProtocolID = ISO15765; + pattern.TxFlags = CAN_29BIT_ID; + pattern.ExtraDataIndex = 0; + pattern.RxStatus = 0; + + memcpy(flow.Data, "\x18\xda\xef\xf1", 4); + flow.DataSize = 4; + flow.ProtocolID = ISO15765; + flow.TxFlags = CAN_29BIT_ID; + flow.ExtraDataIndex = 0; + flow.RxStatus = 0; + + auto res = PassThruStartMsgFilter(cid, FLOW_CONTROL_FILTER, &mask, &pattern, &flow, &fid); + if (res != STATUS_NOERROR) + return 1; + + SCONFIG_LIST list; + SCONFIG config; + config.Parameter = LOOPBACK; + config.Value = 0; + list.ConfigPtr = &config; + list.NumOfParams = 1; + + res = PassThruIoctl(cid, SET_CONFIG, &list, NULL); + if (res != STATUS_NOERROR) + return 1; + + PASSTHRU_MSG outmsg; + memcpy(outmsg.Data, "\x18\xda\xef\xf1""\xAA\xBB\xCC\xDD\xEE\xFF\x11\x22\x33\x44", 4 + 10); + outmsg.DataSize = 4 + 10; + outmsg.ProtocolID = ISO15765; + outmsg.TxFlags = CAN_29BIT_ID; + outmsg.ExtraDataIndex = 0; + outmsg.RxStatus = 0; + + unsigned long msgoutcount = 1; + + res = PassThruWriteMsgs(cid, &outmsg, &msgoutcount, 0); + if (res != STATUS_NOERROR) + return 1; + + PASSTHRU_MSG inmsg[8]; + unsigned long msgincount = 8; + + res = PassThruReadMsgs(cid, inmsg, &msgincount, 1000); + if (res != STATUS_NOERROR) + return 1; + + return 0; +} diff --git a/drivers/windows/panda_playground/panda_playground.vcxproj b/drivers/windows/panda_playground/panda_playground.vcxproj new file mode 100644 index 0000000000..0063bebceb --- /dev/null +++ b/drivers/windows/panda_playground/panda_playground.vcxproj @@ -0,0 +1,191 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + {691DB635-C272-4B98-897E-0505B970DCA9} + Win32Proj + panda_playground + 8.1 + + + + Application + true + v140 + Unicode + + + Application + false + v140 + true + Unicode + + + Application + true + v140 + Unicode + + + Application + false + v140 + true + Unicode + + + + + + + + + + + + + + + + + + + + + true + $(SolutionDir)$(Configuration)_$(PlatformShortName)\ + $(ProjectName)2 + + + true + $(SolutionDir)$(Configuration)_$(PlatformShortName)\ + $(ProjectName) + + + false + $(SolutionDir)$(Configuration)_$(PlatformShortName)\ + + + false + $(SolutionDir)$(Configuration)_$(PlatformShortName)\ + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + %(AdditionalIncludeDirectories);$(SolutionDir) + + + Console + true + kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies);$(OutDir)panda.lib;$(OutDir)ecusim.lib + + + + + Use + Level3 + Disabled + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + %(AdditionalIncludeDirectories);$(SolutionDir) + + + Console + true + kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies);$(OutDir)panda.lib;$(OutDir)ecusim.lib + + + + + Level3 + Use + MaxSpeed + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + %(AdditionalIncludeDirectories);$(SolutionDir) + + + Console + true + true + true + kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies);$(OutDir)panda.lib;$(OutDir)ecusim.lib + + + + + Level3 + Use + MaxSpeed + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + %(AdditionalIncludeDirectories);$(SolutionDir) + + + Console + true + true + true + kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies);$(OutDir)panda.lib;$(OutDir)ecusim.lib + + + + + + + + + + + + + + + + Create + Create + Create + Create + + + + + {96e0e646-ee76-444d-9a77-a0cd7f781deb} + + + {a2bb18a5-f26b-48d6-bbb5-b83d64473c77} + + + {5528aefb-638d-49af-b9d4-965154e7d531} + + + + + + \ No newline at end of file diff --git a/drivers/windows/panda_playground/panda_playground.vcxproj.filters b/drivers/windows/panda_playground/panda_playground.vcxproj.filters new file mode 100644 index 0000000000..b84fc23184 --- /dev/null +++ b/drivers/windows/panda_playground/panda_playground.vcxproj.filters @@ -0,0 +1,45 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + + + Source Files + + + Source Files + + + Source Files + + + \ No newline at end of file diff --git a/drivers/windows/panda_playground/stdafx.cpp b/drivers/windows/panda_playground/stdafx.cpp new file mode 100644 index 0000000000..fefa8d7ec9 --- /dev/null +++ b/drivers/windows/panda_playground/stdafx.cpp @@ -0,0 +1,8 @@ +// stdafx.cpp : source file that includes just the standard includes +// panda_playground.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + +// TODO: reference any additional headers you need in STDAFX.H +// and not in this file diff --git a/drivers/windows/panda_playground/stdafx.h b/drivers/windows/panda_playground/stdafx.h new file mode 100644 index 0000000000..f22759b086 --- /dev/null +++ b/drivers/windows/panda_playground/stdafx.h @@ -0,0 +1,17 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// + +#pragma once + +#include "targetver.h" + +#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers +// Windows Header Files: +#include + +#include +#include +#include +#include diff --git a/drivers/windows/panda_playground/targetver.h b/drivers/windows/panda_playground/targetver.h new file mode 100644 index 0000000000..87c0086de7 --- /dev/null +++ b/drivers/windows/panda_playground/targetver.h @@ -0,0 +1,8 @@ +#pragma once + +// Including SDKDDKVer.h defines the highest available Windows platform. + +// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and +// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h. + +#include diff --git a/drivers/windows/panda_remove.ico b/drivers/windows/panda_remove.ico new file mode 100644 index 0000000000..e513a35fa8 --- /dev/null +++ b/drivers/windows/panda_remove.ico @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:821bc8def403e241ea466e72343e26d5c24186f240bbb391a405c26b4c7b2506 +size 95950 diff --git a/drivers/windows/redist/.gitignore b/drivers/windows/redist/.gitignore new file mode 100644 index 0000000000..90d431bfba --- /dev/null +++ b/drivers/windows/redist/.gitignore @@ -0,0 +1,2 @@ +*.exe +vscruntimeinfo.nsh diff --git a/drivers/windows/redist/README.md b/drivers/windows/redist/README.md new file mode 100644 index 0000000000..69565f11c6 --- /dev/null +++ b/drivers/windows/redist/README.md @@ -0,0 +1,7 @@ +When building the installer, please put the relevant vc_redist.x86.exe file into this folder. +Make sure that the uninstall registry key is correct in the panda_install.nsi file. + +Here is a list of the VC runtime downloads: https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads +An list of the registry keys has been maintained here: https://stackoverflow.com/a/34209692/627525 + +Copy vscruntimeinfo.nsh.sample to vscruntimeinfo.nsh and edit it for your version of Visual Studio. \ No newline at end of file diff --git a/drivers/windows/redist/vscruntimeinfo.nsh.sample b/drivers/windows/redist/vscruntimeinfo.nsh.sample new file mode 100644 index 0000000000..3e74ab1d9c --- /dev/null +++ b/drivers/windows/redist/vscruntimeinfo.nsh.sample @@ -0,0 +1,13 @@ +;NOTE! The panda software requires a VC runtime to be installed in order to work. +;This installer must be bundled with the appropriate runtime installer, and have +;the installation registry key set so the installer can tell if the runtime is +;already installed. + +;Here is a list of the VC runtime downloads: https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads +;An list of the registry keys has been maintained here: https://stackoverflow.com/a/34209692/627525 + + +;Microsoft Visual C++ 2015 Redistributable (x86) - 14.0.24123 +!define VCRuntimeRegKey "SOFTWARE\Classes\Installer\Dependencies\{206898cc-4b41-4d98-ac28-9f9ae57f91fe}" +!define VCRuntimeSetupPath "redist\" +!define VCRuntimeSetupFile "vc_redist.x86.exe" \ No newline at end of file diff --git a/drivers/windows/test certs/commaaiCertStore.pvk b/drivers/windows/test certs/commaaiCertStore.pvk new file mode 100644 index 0000000000000000000000000000000000000000..6db0a7885d2ff41c437cde63b6bff65816aada56 GIT binary patch literal 1196 zcmV;d1XKGS@wKo30000200000000000001#1ONaB0ssI2Bme+XQ$aES2mk;90098) z$Q=n8AQr+fvGImbc+M7XHqNM73KfP=-FedER-*RvGQZ2q6Q%w*G8k_TIT;i!f8 z#0n*v4dOltcMY7ZxHf|sq_PWyDr>*R0gAki9C8_OwNi?Q_`&)y1a6i%T@zm_e4|8? zU}b;F4+HJc!Auu>VG-<=+8wGjLUpqAk^Sg-u}YWxqc_;)H?Q?wL@ZGH6;6P6WH2C@ zi1o_9b*KXPkQQulz&f|&LMNB}%Ndlpx5#8V?YD^XjCFGUy2)I&?XI?0l&`J2>-`*fv2@flfg_@9#zs&ZvD~`*F-2rs3dJ8-#s|G;Dhxpa z2%o0r!3lQw{1>jP>eRT;9UvC_8;IfT7Yi**U23 zZl`tyoH0;x|6!>KJZ)~(W%`Ce$+fJ5ergR9jWEdw^lpv4TvO$+j_k+ZqBTUND5l;; zx}1JEGpT0szPQ$*jJ_HHWXJw)a2y;5>7Gi4zg-@Fa!D%uE;gCHJJm5OKw>b$Ryi$t zT$RZW25B(?9rWA}Its8vxImG}6+b&APEEvC5<~nAS*ONty3Fa#z5^cQcDP$^;7Qsh z?>ikE28jzZ;DdVtRrVPI9-JtA>98H*`5-!P_oIRmLqHavIgm0rA}IJ~NJkZ`yj(Lm z`m06;;@rU)e;`NR$Urn^O7UE3)?*y%xm-lqu!ps5BW{F_cwRDl5+4(M$9o}88y5H^ zIwn$)q`Ahh?KJRTUG~n|& z`XIs%&+4BMbj>6Liqx>>JTjq#_<{5Z(jIOgWohX)Qj-nLm3sc>M)l!eV`D KVY3EA$`2;xzBya~ literal 0 HcmV?d00001 diff --git a/drivers/windows/test certs/commaaicert.cer b/drivers/windows/test certs/commaaicert.cer new file mode 100644 index 0000000000000000000000000000000000000000..8d0a38a7c00f37d385d9b9aa60ee13e6b76ca068 GIT binary patch literal 756 zcmXqLV)|gv#CT@`GZP~dlYl!zV*8nUB1>G?O>2`n`SpzfCmX9aA2X9ID}#Zsp`Zaj z8*?ZNvoJ?;er|4}USg(!oH(zcxq+pDv5}#HnW06LIIpp#p^-5VnOd4!Mq$^~#HeJz z%f_kI=F#?@mywZ?m4Ug5k)HwR4lbr9Mn;CO<@dQ`!dC8$Il1d!QEAVoj_q%)Qci5& zIYsjHpXusOPqtefD9jO?@PlbZ>Hbq+J7y>tq?9-KiT(=Eaf$u9-u&qe^TmIrdu^SWBk4 zan3AH>|8}a+sBOthr|?|1(;&v9`J2FyZ6_RU)R>-3q`SpZWF#p1coysL+YQ#A2sJ!Dz)}MGi6-$ zt1N(r@yoH>f{lWi5_#VXCUKd(Z`g5g|5x6V$@?s{XX@+M2qy6VRC{Xe^*8Ul!y5O~ z&J3GW=iQwZv|R4%Mb8^MW_cF$vfSCkxlTYa$$onH>VNE9hXUFPN~gz}Pfwa<>8)>) zcO$AyobznR^}BOVo(OMbRG5)|lDAq?GjV!({~oE#;yEtwS-#HMSUqjwh1-GI8;heA zSu!3n%gVbMP2K6?F=1WN8~Gn%iM&@ zU;q4NV`Sc(K9jazen%hsgk9m)@MBpct#eE&Jn#=!)iWL^xBC$hC(g;v(%%mNc=kMF literal 0 HcmV?d00001 diff --git a/examples/__init__.py b/examples/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/examples/can_logger.py b/examples/can_logger.py new file mode 100755 index 0000000000..05c28a26df --- /dev/null +++ b/examples/can_logger.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python +from __future__ import print_function +import binascii +import csv +import sys +from panda import Panda + +def can_logger(): + + try: + print("Trying to connect to Panda over USB...") + p = Panda() + + except AssertionError: + print("USB connection failed. Trying WiFi...") + + try: + p = Panda("WIFI") + except: + print("WiFi connection timed out. Please make sure your Panda is connected and try again.") + sys.exit(0) + + try: + outputfile = open('output.csv', 'wb') + csvwriter = csv.writer(outputfile) + #Write Header + csvwriter.writerow(['Bus', 'MessageID', 'Message', 'MessageLength']) + print("Writing csv file output.csv. Press Ctrl-C to exit...\n") + + bus0_msg_cnt = 0 + bus1_msg_cnt = 0 + bus2_msg_cnt = 0 + + while True: + can_recv = p.can_recv() + + for address, _, dat, src in can_recv: + csvwriter.writerow([str(src), str(hex(address)), "0x" + binascii.hexlify(dat), len(dat)]) + + if src == 0: + bus0_msg_cnt += 1 + elif src == 1: + bus1_msg_cnt += 1 + elif src == 2: + bus2_msg_cnt += 1 + + print("Message Counts... Bus 0: " + str(bus0_msg_cnt) + " Bus 1: " + str(bus1_msg_cnt) + " Bus 2: " + str(bus2_msg_cnt), end='\r') + + except KeyboardInterrupt: + print("\nNow exiting. Final message Counts... Bus 0: " + str(bus0_msg_cnt) + " Bus 1: " + str(bus1_msg_cnt) + " Bus 2: " + str(bus2_msg_cnt)) + outputfile.close() + +if __name__ == "__main__": + can_logger() diff --git a/examples/can_unique.md b/examples/can_unique.md new file mode 100644 index 0000000000..bf316940d3 --- /dev/null +++ b/examples/can_unique.md @@ -0,0 +1,103 @@ +# How to use can_unique.py to reverse engineer a single bit field + +Let's say our goal is to find the CAN message indicating that the driver's door is either open or closed. +The following process is great for simple single-bit messages. +However for frequently changing values, such as RPM or speed, Cabana's graphical plots are probably better to use. + + +First record a few minutes of background CAN messages with all the doors closed and save it in background.csv: +``` +./can_logger.py +mv output.csv background.csv +``` +Then run can_logger.py for a few seconds while performing the action you're interested, such as opening and then closing the +front-left door and save it as door-fl-1.csv +Repeat the process and save it as door-f1-2.csv to have an easy way to confirm any suspicions. + +Now we'll use can_unique.py to look for unique bits: +``` +$ ./can_unique.py door-fl-1.csv background* +id 820 new one at byte 2 bitmask 2 +id 520 new one at byte 3 bitmask 7 +id 520 new zero at byte 3 bitmask 8 +id 520 new one at byte 5 bitmask 6 +id 520 new zero at byte 5 bitmask 9 +id 559 new zero at byte 6 bitmask 4 +id 804 new one at byte 5 bitmask 2 +id 804 new zero at byte 5 bitmask 1 + +$ ./can_unique.py door-fl-2.csv background* +id 672 new one at byte 3 bitmask 3 +id 820 new one at byte 2 bitmask 2 +id 520 new one at byte 3 bitmask 7 +id 520 new zero at byte 3 bitmask 8 +id 520 new one at byte 5 bitmask 6 +id 520 new zero at byte 5 bitmask 9 +id 559 new zero at byte 6 bitmask 4 +``` + +One of these bits hopefully indicates that the driver's door is open. +Let's go through each message ID to figure out which one is correct. +We expect any correct bits to have changed in both runs. +We can rule out 804 because it only occurred in the first run. +We can rule out 672 because it only occurred in the second run. +That leaves us with these message IDs: 820, 520, 559. Let's take a closer look at each one. + +``` +$ fgrep ,559, door-fl-1.csv |head +0,559,00ff0000000024f0 +0,559,00ff000000004464 +0,559,00ff0000000054a9 +0,559,00ff0000000064e3 +0,559,00ff00000000742e +0,559,00ff000000008451 +0,559,00ff00000000949c +0,559,00ff00000000a4d6 +0,559,00ff00000000b41b +0,559,00ff00000000c442 +``` +Message ID 559 looks like an incrementing value, so it's not what we're looking for. + +``` +$ fgrep ,520, door-fl-2.csv +0,520,26ff00f8a1890000 +0,520,26ff00f8a2890000 +0,520,26ff00f8a2890000 +0,520,26ff00f8a1890000 +0,520,26ff00f8a2890000 +0,520,26ff00f8a1890000 +0,520,26ff00f8a2890000 +0,520,26ff00f8a1890000 +0,520,26ff00f8a2890000 +0,520,26ff00f8a1890000 +0,520,26ff00f8a2890000 +0,520,26ff00f8a1890000 +``` +Message ID 520 oscillates between two values. However I only opened and closed the door once, so this is probably not it. + +``` +$ fgrep ,820, door-fl-1.csv +0,820,44000100a500c802 +0,820,44000100a500c803 +0,820,44000300a500c803 +0,820,44000300a500c802 +0,820,44000300a500c802 +0,820,44000300a500c802 +0,820,44000100a500c802 +0,820,44000100a500c802 +0,820,44000100a500c802 +``` +Message ID 820 looks promising! It starts off at 44000100a500c802 when the door is closed. +When the door is open it goes to 44000300a500c802. +Then when the door is closed again, it goes back to 44000100a500c802. +Let's confirm by looking at the data from our other run: +``` +$ fgrep ,820, door-fl-2.csv +0,820,44000100a500c802 +0,820,44000300a500c802 +0,820,44000100a500c802 +``` +Perfect! We now know that message id 820 at byte 2 bitmask 2 is set if the driver's door is open. +If we repeat the process with the front passenger's door, +then we'll find that message id 820 at byte 2 bitmask 4 is set if the front-right door is open. +This confirms our finding because it's common for similar signals to be near each other. diff --git a/examples/can_unique.py b/examples/can_unique.py new file mode 100755 index 0000000000..42488c64bb --- /dev/null +++ b/examples/can_unique.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python + +# Given an interesting CSV file of CAN messages and a list of background CAN +# messages, print which bits in the interesting file have never appeared +# in the background files. + +# Expects the CSV file to be in the format from can_logger.py +# Bus,MessageID,Message,MessageLength +# 0,0x292,0x040000001068,6 + +# The old can_logger.py format is also supported: +# Bus,MessageID,Message +# 0,344,c000c00000000000 + + +import binascii +import csv +import sys +from panda import Panda + +class Message(): + """Details about a specific message ID.""" + def __init__(self, message_id): + self.message_id = message_id + self.data = {} # keyed by hex string encoded message data + self.ones = [0] * 8 # bit set if 1 is seen + self.zeros = [0] * 8 # bit set if 0 has been seen + + def printBitDiff(self, other): + """Prints bits that are set or cleared compared to other background.""" + for i in xrange(len(self.ones)): + new_ones = ((~other.ones[i]) & 0xff) & self.ones[i] + if new_ones: + print 'id %s new one at byte %d bitmask %d' % ( + self.message_id, i, new_ones) + new_zeros = ((~other.zeros[i]) & 0xff) & self.zeros[i] + if new_zeros: + print 'id %s new zero at byte %d bitmask %d' % ( + self.message_id, i, new_zeros) + + +class Info(): + """A collection of Messages.""" + + def __init__(self): + self.messages = {} # keyed by MessageID + + def load(self, filename): + """Given a CSV file, adds information about message IDs and their values.""" + with open(filename, 'rb') as input: + reader = csv.reader(input) + next(reader, None) # skip the CSV header + for row in reader: + if row[1].startswith('0x'): + message_id = row[1][2:] # remove leading '0x' + else: + message_id = hex(int(row[1]))[2:] # old message IDs are in decimal + if row[1].startswith('0x'): + data = row[2][2:] # remove leading '0x' + else: + data = row[2] + if message_id not in self.messages: + self.messages[message_id] = Message(message_id) + message = self.messages[message_id] + if data not in self.messages[message_id].data: + message.data[data] = True + bytes = bytearray.fromhex(data) + for i in xrange(len(bytes)): + message.ones[i] = message.ones[i] | int(bytes[i]) + # Inverts the data and masks it to a byte to get the zeros as ones. + message.zeros[i] = message.zeros[i] | ( (~int(bytes[i])) & 0xff) + +def PrintUnique(interesting_file, background_files): + background = Info() + for background_file in background_files: + background.load(background_file) + interesting = Info() + interesting.load(interesting_file) + for message_id in interesting.messages: + if message_id not in background.messages: + print 'New message_id: %s' % message_id + else: + interesting.messages[message_id].printBitDiff( + background.messages[message_id]) + + +if __name__ == "__main__": + if len(sys.argv) < 3: + print 'Usage:\n%s interesting.csv background*.csv' % sys.argv[0] + sys.exit(0) + PrintUnique(sys.argv[1], sys.argv[2:]) diff --git a/examples/isotp.py b/examples/isotp.py new file mode 100644 index 0000000000..8d7a98e773 --- /dev/null +++ b/examples/isotp.py @@ -0,0 +1,77 @@ +DEBUG = False + +def msg(x): + if DEBUG: + print "S:",x.encode("hex") + if len(x) <= 7: + ret = chr(len(x)) + x + else: + assert False + return ret.ljust(8, "\x00") + +def isotp_send(panda, x, addr, bus=0): + if len(x) <= 7: + panda.can_send(addr, msg(x), bus) + else: + ss = chr(0x10 + (len(x)>>8)) + chr(len(x)&0xFF) + x[0:6] + x = x[6:] + idx = 1 + sends = [] + while len(x) > 0: + sends.append(((chr(0x20 + (idx&0xF)) + x[0:7]).ljust(8, "\x00"))) + x = x[7:] + idx += 1 + + # actually send + panda.can_send(addr, ss, bus) + rr = recv(panda, 1, addr+8, bus)[0] + panda.can_send_many([(addr, None, s, 0) for s in sends]) + +kmsgs = [] +def recv(panda, cnt, addr, nbus): + global kmsgs + ret = [] + + while len(ret) < cnt: + kmsgs += panda.can_recv() + nmsgs = [] + for ids, ts, dat, bus in kmsgs: + if ids == addr and bus == nbus and len(ret) < cnt: + ret.append(dat) + else: + pass + kmsgs = nmsgs + return map(str, ret) + +def isotp_recv(panda, addr, bus=0): + msg = recv(panda, 1, addr, bus)[0] + + if ord(msg[0])&0xf0 == 0x10: + # first + tlen = ((ord(msg[0]) & 0xf) << 8) | ord(msg[1]) + dat = msg[2:] + + # 0 block size? + CONTINUE = "\x30" + "\x00"*7 + + panda.can_send(addr-8, CONTINUE, bus) + + idx = 1 + for mm in recv(panda, (tlen-len(dat) + 7)/8, addr, bus): + assert ord(mm[0]) == (0x20 | idx) + dat += mm[1:] + idx += 1 + elif ord(msg[0])&0xf0 == 0x00: + # single + tlen = ord(msg[0]) & 0xf + dat = msg[1:] + else: + assert False + + dat = dat[0:tlen] + + if DEBUG: + print "R:",dat.encode("hex") + + return dat + diff --git a/examples/query_vin_and_stats.py b/examples/query_vin_and_stats.py new file mode 100755 index 0000000000..cd2185b4a6 --- /dev/null +++ b/examples/query_vin_and_stats.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python +import time +import struct +from panda import Panda +from hexdump import hexdump +from isotp import isotp_send, isotp_recv + +# 0x7e0 = Toyota +# 0x18DB33F1 for Honda? + +def get_current_data_for_pid(pid): + # 01 xx = Show current data + isotp_send(panda, "\x01"+chr(pid), 0x7e0) + return isotp_recv(panda, 0x7e8) + +def get_supported_pids(): + ret = [] + pid = 0 + while 1: + supported = struct.unpack(">I", get_current_data_for_pid(pid)[2:])[0] + for i in range(1+pid, 0x21+pid): + if supported & 0x80000000: + ret.append(i) + supported <<= 1 + pid += 0x20 + if pid not in ret: + break + return ret + +if __name__ == "__main__": + panda = Panda() + panda.set_safety_mode(Panda.SAFETY_ELM327) + panda.can_clear(0) + + # 09 02 = Get VIN + isotp_send(panda, "\x09\x02", 0x7e0) + ret = isotp_recv(panda, 0x7e8) + hexdump(ret) + print "VIN: %s" % ret[2:] + + # 03 = get DTCS + isotp_send(panda, "\x03", 0x7e0) + dtcs = isotp_recv(panda, 0x7e8) + print "DTCs:", dtcs[2:].encode("hex") + + supported_pids = get_supported_pids() + print "Supported PIDs:",supported_pids + + while 1: + speed = struct.unpack(">B", get_current_data_for_pid(13)[2:])[0] # kph + rpm = struct.unpack(">H", get_current_data_for_pid(12)[2:])[0]/4.0 # revs + throttle = struct.unpack(">B", get_current_data_for_pid(17)[2:])[0]/255.0 * 100 # percent + temp = struct.unpack(">B", get_current_data_for_pid(5)[2:])[0] - 40 # degrees C + load = struct.unpack(">B", get_current_data_for_pid(4)[2:])[0]/255.0 * 100 # percent + print "%d KPH, %d RPM, %.1f%% Throttle, %d deg C, %.1f%% load" % (speed, rpm, throttle, temp, load) + time.sleep(0.2) + + + diff --git a/examples/tesla_tester.py b/examples/tesla_tester.py new file mode 100644 index 0000000000..b2cbb4d789 --- /dev/null +++ b/examples/tesla_tester.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python +import sys +import binascii +from panda import Panda + +def tesla_tester(): + + try: + print("Trying to connect to Panda over USB...") + p = Panda() + + except AssertionError: + print("USB connection failed. Trying WiFi...") + + try: + p = Panda("WIFI") + except: + print("WiFi connection timed out. Please make sure your Panda is connected and try again.") + sys.exit(0) + + body_bus_speed = 125 # Tesla Body busses (B, BF) are 125kbps, rest are 500kbps + body_bus_num = 1 # My TDC to OBD adapter has PT on bus0 BDY on bus1 and CH on bus2 + p.set_can_speed_kbps(body_bus_num, body_bus_speed) + + # Now set the panda from its default of SAFETY_NOOUTPUT (read only) to SAFETY_ALLOUTPUT + # Careful, as this will let us send any CAN messages we want (which could be very bad!) + print("Setting Panda to output mode...") + p.set_safety_mode(Panda.SAFETY_ALLOUTPUT) + + # BDY 0x248 is the MCU_commands message, which includes folding mirrors, opening the trunk, frunk, setting the cars lock state and more. For our test, we will edit the 3rd byte, which is MCU_lockRequest. 0x01 will lock, 0x02 will unlock: + print("Unlocking Tesla...") + p.can_send(0x248, "\x00\x00\x02\x00\x00\x00\x00\x00", bus_num) + + #Or, we can set the first byte, MCU_frontHoodCommand + MCU_liftgateSwitch, to 0x01 to pop the frunk, or 0x04 to open/close the trunk (0x05 should open both) + print("Opening Frunk...") + p.can_send(0x248, "\x01\x00\x00\x00\x00\x00\x00\x00", bus_num) + + #Back to safety... + print("Disabling output on Panda...") + p.set_safety_mode(Panda.SAFETY_NOOUTPUT) + + print("Reading VIN from 0x568. This is painfully slow and can take up to 3 minutes (1 minute per message; 3 messages needed for full VIN)...") + + cnt = 0 + vin = {} + while True: + #Read the VIN + can_recv = p.can_recv() + for address, _, dat, src in can_recv: + if src == body_bus_num: + if address == 1384: #0x568 is VIN + vin_index = int(binascii.hexlify(dat)[:2]) #first byte is the index, 00, 01, 02 + vin_string = binascii.hexlify(dat)[2:] #rest of the string is the actual VIN data + vin[vin_index] = vin_string.decode("hex") + print("Got VIN index " + str(vin_index) + " data " + vin[vin_index]) + cnt += 1 + #if we have all 3 parts of the VIN, print it and break out of our while loop + if cnt == 3: + print("VIN: " + vin[0] + vin[1] + vin[2][:3]) + break + +if __name__ == "__main__": + tesla_tester() \ No newline at end of file diff --git a/panda.png b/panda.png new file mode 100644 index 0000000000..1c2a49309d --- /dev/null +++ b/panda.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5da391df3865ff37c97b3191e5503bcfacee7a4e48285e3e70d41ba3fd9b2c9e +size 72820 diff --git a/python/__init__.py b/python/__init__.py new file mode 100644 index 0000000000..95a2b89d24 --- /dev/null +++ b/python/__init__.py @@ -0,0 +1,484 @@ +# python library to interface with panda +from __future__ import print_function +import binascii +import struct +import hashlib +import socket +import usb1 +import os +import time +import traceback +from dfu import PandaDFU +from esptool import ESPROM, CesantaFlasher +from flash_release import flash_release +from update import ensure_st_up_to_date + +__version__ = '0.0.6' + +BASEDIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), "../") + +# *** wifi mode *** + +def build_st(target, mkfile="Makefile"): + from panda import BASEDIR + assert(os.system('cd %s && make -f %s clean && make -f %s %s >/dev/null' % (os.path.join(BASEDIR, "board"), mkfile, mkfile, target)) == 0) + +def parse_can_buffer(dat): + ret = [] + for j in range(0, len(dat), 0x10): + ddat = dat[j:j+0x10] + f1, f2 = struct.unpack("II", ddat[0:8]) + extended = 4 + if f1 & extended: + address = f1 >> 3 + else: + address = f1 >> 21 + ret.append((address, f2>>16, ddat[8:8+(f2&0xF)], (f2>>4)&0xFF)) + return ret + +class PandaWifiStreaming(object): + def __init__(self, ip="192.168.0.10", port=1338): + self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + self.sock.setblocking(0) + self.ip = ip + self.port = port + self.kick() + + def kick(self): + # must be called at least every 5 seconds + self.sock.sendto("hello", (self.ip, self.port)) + + def can_recv(self): + ret = [] + while True: + try: + dat, addr = self.sock.recvfrom(0x200*0x10) + if addr == (self.ip, self.port): + ret += parse_can_buffer(dat) + except socket.error as e: + if e.errno != 35 and e.errno != 11: + traceback.print_exc() + break + return ret + +# stupid tunneling of USB over wifi and SPI +class WifiHandle(object): + def __init__(self, ip="192.168.0.10", port=1337): + self.sock = socket.create_connection((ip, port)) + + def __recv(self): + ret = self.sock.recv(0x44) + length = struct.unpack("I", ret[0:4])[0] + return ret[4:4+length] + + def controlWrite(self, request_type, request, value, index, data, timeout=0): + # ignore data in reply, panda doesn't use it + return self.controlRead(request_type, request, value, index, 0, timeout) + + def controlRead(self, request_type, request, value, index, length, timeout=0): + self.sock.send(struct.pack("HHBBHHH", 0, 0, request_type, request, value, index, length)) + return self.__recv() + + def bulkWrite(self, endpoint, data, timeout=0): + if len(data) > 0x10: + raise ValueError("Data must not be longer than 0x10") + self.sock.send(struct.pack("HH", endpoint, len(data))+data) + self.__recv() # to /dev/null + + def bulkRead(self, endpoint, length, timeout=0): + self.sock.send(struct.pack("HH", endpoint, 0)) + return self.__recv() + + def close(self): + self.sock.close() + +# *** normal mode *** + +class Panda(object): + SAFETY_NOOUTPUT = 0 + SAFETY_HONDA = 1 + SAFETY_TOYOTA = 2 + SAFETY_TOYOTA_NOLIMITS = 0x1336 + SAFETY_ALLOUTPUT = 0x1337 + SAFETY_ELM327 = 0xE327 + + SERIAL_DEBUG = 0 + SERIAL_ESP = 1 + SERIAL_LIN1 = 2 + SERIAL_LIN2 = 3 + + GMLAN_CAN2 = 1 + GMLAN_CAN3 = 2 + + REQUEST_IN = usb1.ENDPOINT_IN | usb1.TYPE_VENDOR | usb1.RECIPIENT_DEVICE + REQUEST_OUT = usb1.ENDPOINT_OUT | usb1.TYPE_VENDOR | usb1.RECIPIENT_DEVICE + + def __init__(self, serial=None, claim=True): + self._serial = serial + self._handle = None + self.connect(claim) + + def close(self): + self._handle.close() + self._handle = None + + def connect(self, claim=True, wait=False): + if self._handle != None: + self.close() + + if self._serial == "WIFI": + self._handle = WifiHandle() + print("opening WIFI device") + self.wifi = True + else: + context = usb1.USBContext() + self._handle = None + self.wifi = False + + while 1: + try: + for device in context.getDeviceList(skip_on_error=True): + #print(device) + if device.getVendorID() == 0xbbaa and device.getProductID() in [0xddcc, 0xddee]: + try: + this_serial = device.getSerialNumber() + except Exception: + continue + if self._serial is None or this_serial == self._serial: + self._serial = this_serial + print("opening device", self._serial, hex(device.getProductID())) + self.bootstub = device.getProductID() == 0xddee + self.legacy = (device.getbcdDevice() != 0x2300) + self._handle = device.open() + if claim: + self._handle.claimInterface(0) + #self._handle.setInterfaceAltSetting(0, 0) #Issue in USB stack + break + except Exception as e: + print("exception", e) + traceback.print_exc() + if wait == False or self._handle != None: + break + assert(self._handle != None) + print("connected") + + def reset(self, enter_bootstub=False, enter_bootloader=False): + # reset + try: + if enter_bootloader: + self._handle.controlWrite(Panda.REQUEST_IN, 0xd1, 0, 0, b'') + else: + if enter_bootstub: + self._handle.controlWrite(Panda.REQUEST_IN, 0xd1, 1, 0, b'') + else: + self._handle.controlWrite(Panda.REQUEST_IN, 0xd8, 0, 0, b'') + except Exception: + pass + if not enter_bootloader: + self.close() + time.sleep(1.0) + success = False + # wait up to 15 seconds + for i in range(0, 15): + try: + self.connect() + success = True + break + except Exception: + print("reconnecting is taking %d seconds..." % (i+1)) + try: + dfu = PandaDFU(PandaDFU.st_serial_to_dfu_serial(self._serial)) + dfu.recover() + except Exception: + pass + time.sleep(1.0) + if not success: + raise Exception("reset failed") + + def flash(self, fn=None, code=None): + if not self.bootstub: + self.reset(enter_bootstub=True) + assert(self.bootstub) + + if fn is None and code is None: + if self.legacy: + fn = "obj/comma.bin" + print("building legacy st code") + build_st(fn, "Makefile.legacy") + else: + fn = "obj/panda.bin" + print("building panda st code") + build_st(fn) + fn = os.path.join(BASEDIR, "board", fn) + + if code is None: + with open(fn) as f: + code = f.read() + + # get version + print("flash: version is "+self.get_version()) + + # confirm flasher is present + fr = self._handle.controlRead(Panda.REQUEST_IN, 0xb0, 0, 0, 0xc) + assert fr[4:8] == "\xde\xad\xd0\x0d" + + # unlock flash + print("flash: unlocking") + self._handle.controlWrite(Panda.REQUEST_IN, 0xb1, 0, 0, b'') + + # erase sectors 1 and 2 + print("flash: erasing") + self._handle.controlWrite(Panda.REQUEST_IN, 0xb2, 1, 0, b'') + self._handle.controlWrite(Panda.REQUEST_IN, 0xb2, 2, 0, b'') + + # flash over EP2 + STEP = 0x10 + print("flash: flashing") + for i in range(0, len(code), STEP): + self._handle.bulkWrite(2, code[i:i+STEP]) + + # reset + print("flash: resetting") + self.reset() + + def recover(self): + self.reset(enter_bootloader=True) + while len(PandaDFU.list()) == 0: + print("waiting for DFU...") + time.sleep(0.1) + + dfu = PandaDFU(PandaDFU.st_serial_to_dfu_serial(self._serial)) + dfu.recover() + + # reflash after recover + self.connect(True, True) + self.flash() + + @staticmethod + def flash_ota_st(): + ret = os.system("cd %s && make clean && make ota" % (os.path.join(BASEDIR, "board"))) + time.sleep(1) + return ret==0 + + @staticmethod + def flash_ota_wifi(): + ret = os.system("cd %s && make clean && make ota" % (os.path.join(BASEDIR, "boardesp"))) + time.sleep(1) + return ret==0 + + @staticmethod + def list(): + context = usb1.USBContext() + ret = [] + try: + for device in context.getDeviceList(skip_on_error=True): + if device.getVendorID() == 0xbbaa and device.getProductID() in [0xddcc, 0xddee]: + try: + ret.append(device.getSerialNumber()) + except Exception: + continue + except Exception: + pass + # TODO: detect if this is real + #ret += ["WIFI"] + return ret + + def call_control_api(self, msg): + self._handle.controlWrite(Panda.REQUEST_OUT, msg, 0, 0, b'') + + # ******************* health ******************* + + def health(self): + dat = self._handle.controlRead(Panda.REQUEST_IN, 0xd2, 0, 0, 13) + a = struct.unpack("IIBBBBB", dat) + return {"voltage": a[0], "current": a[1], + "started": a[2], "controls_allowed": a[3], + "gas_interceptor_detected": a[4], + "started_signal_detected": a[5], + "started_alt": a[6]} + + # ******************* control ******************* + + def enter_bootloader(self): + try: + self._handle.controlWrite(Panda.REQUEST_OUT, 0xd1, 0, 0, b'') + except Exception as e: + print(e) + pass + + def get_version(self): + return self._handle.controlRead(Panda.REQUEST_IN, 0xd6, 0, 0, 0x40) + + def get_serial(self): + dat = self._handle.controlRead(Panda.REQUEST_IN, 0xd0, 0, 0, 0x20) + hashsig, calc_hash = dat[0x1c:], hashlib.sha1(dat[0:0x1c]).digest()[0:4] + assert(hashsig == calc_hash) + return [dat[0:0x10], dat[0x10:0x10+10]] + + def get_secret(self): + return self._handle.controlRead(Panda.REQUEST_IN, 0xd0, 1, 0, 0x10) + + # ******************* configuration ******************* + + def set_usb_power(self, on): + self._handle.controlWrite(Panda.REQUEST_OUT, 0xe6, int(on), 0, b'') + + def set_esp_power(self, on): + self._handle.controlWrite(Panda.REQUEST_OUT, 0xd9, int(on), 0, b'') + + def esp_reset(self, bootmode=0): + self._handle.controlWrite(Panda.REQUEST_OUT, 0xda, int(bootmode), 0, b'') + time.sleep(0.2) + + def set_safety_mode(self, mode=SAFETY_NOOUTPUT): + self._handle.controlWrite(Panda.REQUEST_OUT, 0xdc, mode, 0, b'') + + def set_can_forwarding(self, from_bus, to_bus): + # TODO: This feature may not work correctly with saturated buses + self._handle.controlWrite(Panda.REQUEST_OUT, 0xdd, from_bus, to_bus, b'') + + def set_gmlan(self, bus=2): + if bus is None: + self._handle.controlWrite(Panda.REQUEST_OUT, 0xdb, 0, 0, b'') + elif bus in [Panda.GMLAN_CAN2, Panda.GMLAN_CAN3]: + self._handle.controlWrite(Panda.REQUEST_OUT, 0xdb, 1, bus, b'') + + def set_can_loopback(self, enable): + # set can loopback mode for all buses + self._handle.controlWrite(Panda.REQUEST_OUT, 0xe5, int(enable), 0, b'') + + def set_can_speed_kbps(self, bus, speed): + self._handle.controlWrite(Panda.REQUEST_OUT, 0xde, bus, int(speed*10), b'') + + def set_uart_baud(self, uart, rate): + self._handle.controlWrite(Panda.REQUEST_OUT, 0xe4, uart, rate/300, b'') + + def set_uart_parity(self, uart, parity): + # parity, 0=off, 1=even, 2=odd + self._handle.controlWrite(Panda.REQUEST_OUT, 0xe2, uart, parity, b'') + + def set_uart_callback(self, uart, install): + self._handle.controlWrite(Panda.REQUEST_OUT, 0xe3, uart, int(install), b'') + + # ******************* can ******************* + + def can_send_many(self, arr): + snds = [] + transmit = 1 + extended = 4 + for addr, _, dat, bus in arr: + assert len(dat) <= 8 + if addr >= 0x800: + rir = (addr << 3) | transmit | extended + else: + rir = (addr << 21) | transmit + snd = struct.pack("II", rir, len(dat) | (bus << 4)) + dat + snd = snd.ljust(0x10, b'\x00') + snds.append(snd) + + while True: + try: + #print("DAT: %s"%b''.join(snds).__repr__()) + if self.wifi: + for s in snds: + self._handle.bulkWrite(3, s) + else: + self._handle.bulkWrite(3, b''.join(snds)) + break + except (usb1.USBErrorIO, usb1.USBErrorOverflow): + print("CAN: BAD SEND MANY, RETRYING") + + def can_send(self, addr, dat, bus): + self.can_send_many([[addr, None, dat, bus]]) + + def can_recv(self): + dat = bytearray() + while True: + try: + dat = self._handle.bulkRead(1, 0x10*256) + break + except (usb1.USBErrorIO, usb1.USBErrorOverflow): + print("CAN: BAD RECV, RETRYING") + return parse_can_buffer(dat) + + def can_clear(self, bus): + """Clears all messages from the specified internal CAN ringbuffer as + though it were drained. + + Args: + bus (int): can bus number to clear a tx queue, or 0xFFFF to clear the + global can rx queue. + + """ + self._handle.controlWrite(Panda.REQUEST_OUT, 0xf1, bus, 0, b'') + + # ******************* serial ******************* + + def serial_read(self, port_number): + ret = [] + while 1: + lret = bytes(self._handle.controlRead(Panda.REQUEST_IN, 0xe0, port_number, 0, 0x40)) + if len(lret) == 0: + break + ret.append(lret) + return b''.join(ret) + + def serial_write(self, port_number, ln): + return self._handle.bulkWrite(2, struct.pack("B", port_number) + ln) + + def serial_clear(self, port_number): + """Clears all messages (tx and rx) from the specified internal uart + ringbuffer as though it were drained. + + Args: + port_number (int): port number of the uart to clear. + + """ + self._handle.controlWrite(Panda.REQUEST_OUT, 0xf2, port_number, 0, b'') + + # ******************* kline ******************* + + # pulse low for wakeup + def kline_wakeup(self): + self._handle.controlWrite(Panda.REQUEST_OUT, 0xf0, 0, 0, b'') + + def kline_drain(self, bus=2): + # drain buffer + bret = bytearray() + while True: + ret = self._handle.controlRead(Panda.REQUEST_IN, 0xe0, bus, 0, 0x40) + if len(ret) == 0: + break + bret += ret + return bytes(bret) + + def kline_ll_recv(self, cnt, bus=2): + echo = bytearray() + while len(echo) != cnt: + echo += self._handle.controlRead(Panda.REQUEST_OUT, 0xe0, bus, 0, cnt-len(echo)) + return echo + + def kline_send(self, x, bus=2, checksum=True): + def get_checksum(dat): + result = 0 + result += sum(map(ord, dat)) if isinstance(b'dat', str) else sum(dat) + return struct.pack("B", result % 0x100) + + self.kline_drain(bus=bus) + if checksum: + x += get_checksum(x) + for i in range(0, len(x), 0xf): + ts = x[i:i+0xf] + self._handle.bulkWrite(2, chr(bus).encode()+ts) + echo = self.kline_ll_recv(len(ts), bus=bus) + if echo != ts: + print("**** ECHO ERROR %d ****" % i) + print(binascii.hexlify(echo)) + print(binascii.hexlify(ts)) + assert echo == ts + + def kline_recv(self, bus=2): + msg = self.kline_ll_recv(2, bus=bus) + msg += self.kline_ll_recv(ord(msg[1])-2, bus=bus) + return msg + diff --git a/python/dfu.py b/python/dfu.py new file mode 100644 index 0000000000..782b4dca42 --- /dev/null +++ b/python/dfu.py @@ -0,0 +1,122 @@ +from __future__ import print_function +import os +import usb1 +import struct +import time + +# *** DFU mode *** + +DFU_DNLOAD = 1 +DFU_UPLOAD = 2 +DFU_GETSTATUS = 3 +DFU_CLRSTATUS = 4 +DFU_ABORT = 6 + +class PandaDFU(object): + def __init__(self, dfu_serial): + context = usb1.USBContext() + for device in context.getDeviceList(skip_on_error=True): + if device.getVendorID() == 0x0483 and device.getProductID() == 0xdf11: + try: + this_dfu_serial = device._getASCIIStringDescriptor(3) + except Exception: + continue + if this_dfu_serial == dfu_serial or dfu_serial is None: + self._handle = device.open() + self.legacy = "07*128Kg" in self._handle.getASCIIStringDescriptor(4) + return + raise Exception("failed to open "+dfu_serial) + + @staticmethod + def list(): + context = usb1.USBContext() + dfu_serials = [] + try: + for device in context.getDeviceList(skip_on_error=True): + if device.getVendorID() == 0x0483 and device.getProductID() == 0xdf11: + try: + dfu_serials.append(device._getASCIIStringDescriptor(3)) + except Exception: + pass + except Exception: + pass + return dfu_serials + + @staticmethod + def st_serial_to_dfu_serial(st): + if st == None or st == "none": + return None + uid_base = struct.unpack("H"*6, st.decode("hex")) + return struct.pack("!HHH", uid_base[1] + uid_base[5], uid_base[0] + uid_base[4] + 0xA, uid_base[3]).encode("hex").upper() + + + def status(self): + while 1: + dat = str(self._handle.controlRead(0x21, DFU_GETSTATUS, 0, 0, 6)) + if dat[1] == "\x00": + break + + def clear_status(self): + # Clear status + stat = str(self._handle.controlRead(0x21, DFU_GETSTATUS, 0, 0, 6)) + if stat[4] == "\x0a": + self._handle.controlRead(0x21, DFU_CLRSTATUS, 0, 0, 0) + elif stat[4] == "\x09": + self._handle.controlWrite(0x21, DFU_ABORT, 0, 0, "") + self.status() + stat = str(self._handle.controlRead(0x21, DFU_GETSTATUS, 0, 0, 6)) + + def erase(self, address): + self._handle.controlWrite(0x21, DFU_DNLOAD, 0, 0, "\x41" + struct.pack("I", address)) + self.status() + + def program(self, address, dat, block_size=None): + if block_size == None: + block_size = len(dat) + + # Set Address Pointer + self._handle.controlWrite(0x21, DFU_DNLOAD, 0, 0, "\x21" + struct.pack("I", address)) + self.status() + + # Program + dat += "\xFF"*((block_size-len(dat)) % block_size) + for i in range(0, len(dat)/block_size): + ldat = dat[i*block_size:(i+1)*block_size] + print("programming %d with length %d" % (i, len(ldat))) + self._handle.controlWrite(0x21, DFU_DNLOAD, 2+i, 0, ldat) + self.status() + + def program_bootstub(self, code_bootstub): + self.clear_status() + self.erase(0x8004000) + self.erase(0x8000000) + self.program(0x8000000, code_bootstub, 0x800) + self.reset() + + def recover(self): + from panda import BASEDIR, build_st + if self.legacy: + fn = "obj/bootstub.comma.bin" + print("building legacy bootstub") + build_st(fn, "Makefile.legacy") + else: + fn = "obj/bootstub.panda.bin" + print("building panda bootstub") + build_st(fn) + fn = os.path.join(BASEDIR, "board", fn) + + with open(fn) as f: + code = f.read() + + self.program_bootstub(code) + + def reset(self): + # **** Reset **** + self._handle.controlWrite(0x21, DFU_DNLOAD, 0, 0, "\x21" + struct.pack("I", 0x8000000)) + self.status() + try: + self._handle.controlWrite(0x21, DFU_DNLOAD, 2, 0, "") + stat = str(self._handle.controlRead(0x21, DFU_GETSTATUS, 0, 0, 6)) + except Exception: + pass + diff --git a/python/esptool.py b/python/esptool.py new file mode 100755 index 0000000000..970aa3d4d8 --- /dev/null +++ b/python/esptool.py @@ -0,0 +1,1314 @@ +#!/usr/bin/env python +# NB: Before sending a PR to change the above line to '#!/usr/bin/env python2', please read https://github.com/themadinventor/esptool/issues/21 +# +# ESP8266 ROM Bootloader Utility +# https://github.com/themadinventor/esptool +# +# Copyright (C) 2014-2016 Fredrik Ahlberg, Angus Gratton, other contributors as noted. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation; either version 2 of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, write to the Free Software Foundation, Inc., 51 Franklin +# Street, Fifth Floor, Boston, MA 02110-1301 USA. + +import argparse +import hashlib +import inspect +import json +import os +#import serial +import struct +import subprocess +import sys +import tempfile +import time +import traceback +import usb1 + +__version__ = "1.2" + +class FakePort(object): + def __init__(self, serial=None): + from panda import Panda + self.panda = Panda(serial) + + # will only work on new st, old ones will stay @ 921600 + self.baudrate = 230400 + + @property + def baudrate(self): + return self._baudrate + + @baudrate.setter + def baudrate(self, x): + print "set baud to", x + self.panda.set_uart_baud(1, x) + + def write(self, buf): + SEND_STEP = 0x20 + for i in range(0, len(buf), SEND_STEP): + self.panda.serial_write(1, buf[i:i+SEND_STEP]) + + def flushInput(self): + self.panda.serial_clear(1) + + def flushOutput(self): + self.panda.serial_clear(1) + + def read(self, llen): + ret = self.panda._handle.controlRead(usb1.TYPE_VENDOR | usb1.RECIPIENT_DEVICE, 0xe0, 1, 0, 1) + if ret == '': + time.sleep(0.1) + ret = self.panda._handle.controlRead(usb1.TYPE_VENDOR | usb1.RECIPIENT_DEVICE, 0xe0, 1, 0, 1) + return str(ret) + + def reset(self): + self.panda.esp_reset(1) + + def inWaiting(self): + return False + +class ESPROM(object): + # These are the currently known commands supported by the ROM + ESP_FLASH_BEGIN = 0x02 + ESP_FLASH_DATA = 0x03 + ESP_FLASH_END = 0x04 + ESP_MEM_BEGIN = 0x05 + ESP_MEM_END = 0x06 + ESP_MEM_DATA = 0x07 + ESP_SYNC = 0x08 + ESP_WRITE_REG = 0x09 + ESP_READ_REG = 0x0a + + # Maximum block sized for RAM and Flash writes, respectively. + ESP_RAM_BLOCK = 0x1800 + ESP_FLASH_BLOCK = 0x400 + + # Default baudrate. The ROM auto-bauds, so we can use more or less whatever we want. + ESP_ROM_BAUD = 115200 + + # First byte of the application image + ESP_IMAGE_MAGIC = 0xe9 + + # Initial state for the checksum routine + ESP_CHECKSUM_MAGIC = 0xef + + # OTP ROM addresses + ESP_OTP_MAC0 = 0x3ff00050 + ESP_OTP_MAC1 = 0x3ff00054 + ESP_OTP_MAC3 = 0x3ff0005c + + # Flash sector size, minimum unit of erase. + ESP_FLASH_SECTOR = 0x1000 + + def __init__(self, port=None, baud=ESP_ROM_BAUD): + self._port = FakePort(port) + self._slip_reader = slip_reader(self._port) + + """ Read a SLIP packet from the serial port """ + def read(self): + return self._slip_reader.next() + + """ Write bytes to the serial port while performing SLIP escaping """ + def write(self, packet): + buf = '\xc0' \ + + (packet.replace('\xdb','\xdb\xdd').replace('\xc0','\xdb\xdc')) \ + + '\xc0' + self._port.write(buf) + + """ Calculate checksum of a blob, as it is defined by the ROM """ + @staticmethod + def checksum(data, state=ESP_CHECKSUM_MAGIC): + for b in data: + state ^= ord(b) + return state + + """ Send a request and read the response """ + def command(self, op=None, data=None, chk=0): + if op is not None: + pkt = struct.pack('> 16) & 0xff, (mac3 >> 8) & 0xff, mac3 & 0xff) + elif ((mac1 >> 16) & 0xff) == 0: + oui = (0x18, 0xfe, 0x34) + elif ((mac1 >> 16) & 0xff) == 1: + oui = (0xac, 0xd0, 0x74) + else: + raise FatalError("Unknown OUI") + return oui + ((mac1 >> 8) & 0xff, mac1 & 0xff, (mac0 >> 24) & 0xff) + + """ Read Chip ID from OTP ROM - see http://esp8266-re.foogod.com/wiki/System_get_chip_id_%28IoT_RTOS_SDK_0.9.9%29 """ + def chip_id(self): + id0 = self.read_reg(self.ESP_OTP_MAC0) + id1 = self.read_reg(self.ESP_OTP_MAC1) + return (id0 >> 24) | ((id1 & 0xffffff) << 8) + + """ Read SPI flash manufacturer and device id """ + def flash_id(self): + self.flash_begin(0, 0) + self.write_reg(0x60000240, 0x0, 0xffffffff) + self.write_reg(0x60000200, 0x10000000, 0xffffffff) + flash_id = self.read_reg(0x60000240) + return flash_id + + """ Abuse the loader protocol to force flash to be left in write mode """ + def flash_unlock_dio(self): + # Enable flash write mode + self.flash_begin(0, 0) + # Reset the chip rather than call flash_finish(), which would have + # write protected the chip again (why oh why does it do that?!) + self.mem_begin(0,0,0,0x40100000) + self.mem_finish(0x40000080) + + """ Perform a chip erase of SPI flash """ + def flash_erase(self): + # Trick ROM to initialize SFlash + self.flash_begin(0, 0) + + # This is hacky: we don't have a custom stub, instead we trick + # the bootloader to jump to the SPIEraseChip() routine and then halt/crash + # when it tries to boot an unconfigured system. + self.mem_begin(0,0,0,0x40100000) + self.mem_finish(0x40004984) + + # Yup - there's no good way to detect if we succeeded. + # It it on the other hand unlikely to fail. + + def run_stub(self, stub, params, read_output=True): + stub = dict(stub) + stub['code'] = unhexify(stub['code']) + if 'data' in stub: + stub['data'] = unhexify(stub['data']) + + if stub['num_params'] != len(params): + raise FatalError('Stub requires %d params, %d provided' + % (stub['num_params'], len(params))) + + params = struct.pack('<' + ('I' * stub['num_params']), *params) + pc = params + stub['code'] + + # Upload + self.mem_begin(len(pc), 1, len(pc), stub['params_start']) + self.mem_block(pc, 0) + if 'data' in stub: + self.mem_begin(len(stub['data']), 1, len(stub['data']), stub['data_start']) + self.mem_block(stub['data'], 0) + self.mem_finish(stub['entry']) + + if read_output: + print 'Stub executed, reading response:' + while True: + p = self.read() + print hexify(p) + if p == '': + return + + +class ESPBOOTLOADER(object): + """ These are constants related to software ESP bootloader, working with 'v2' image files """ + + # First byte of the "v2" application image + IMAGE_V2_MAGIC = 0xea + + # First 'segment' value in a "v2" application image, appears to be a constant version value? + IMAGE_V2_SEGMENT = 4 + + +def LoadFirmwareImage(filename): + """ Load a firmware image, without knowing what kind of file (v1 or v2) it is. + + Returns a BaseFirmwareImage subclass, either ESPFirmwareImage (v1) or OTAFirmwareImage (v2). + """ + with open(filename, 'rb') as f: + magic = ord(f.read(1)) + f.seek(0) + if magic == ESPROM.ESP_IMAGE_MAGIC: + return ESPFirmwareImage(f) + elif magic == ESPBOOTLOADER.IMAGE_V2_MAGIC: + return OTAFirmwareImage(f) + else: + raise FatalError("Invalid image magic number: %d" % magic) + + +class BaseFirmwareImage(object): + """ Base class with common firmware image functions """ + def __init__(self): + self.segments = [] + self.entrypoint = 0 + + def add_segment(self, addr, data, pad_to=4): + """ Add a segment to the image, with specified address & data + (padded to a boundary of pad_to size) """ + # Data should be aligned on word boundary + l = len(data) + if l % pad_to: + data += b"\x00" * (pad_to - l % pad_to) + if l > 0: + self.segments.append((addr, len(data), data)) + + def load_segment(self, f, is_irom_segment=False): + """ Load the next segment from the image file """ + (offset, size) = struct.unpack(' 0x40200000 or offset < 0x3ffe0000 or size > 65536: + raise FatalError('Suspicious segment 0x%x, length %d' % (offset, size)) + segment_data = f.read(size) + if len(segment_data) < size: + raise FatalError('End of file reading segment 0x%x, length %d (actual length %d)' % (offset, size, len(segment_data))) + segment = (offset, size, segment_data) + self.segments.append(segment) + return segment + + def save_segment(self, f, segment, checksum=None): + """ Save the next segment to the image file, return next checksum value if provided """ + (offset, size, data) = segment + f.write(struct.pack(' 16: + raise FatalError('Invalid firmware image magic=%d segments=%d' % (magic, segments)) + + for i in xrange(segments): + self.load_segment(load_file) + self.checksum = self.read_checksum(load_file) + + def save(self, filename): + with open(filename, 'wb') as f: + self.write_v1_header(f, self.segments) + checksum = ESPROM.ESP_CHECKSUM_MAGIC + for segment in self.segments: + checksum = self.save_segment(f, segment, checksum) + self.append_checksum(f, checksum) + + +class OTAFirmwareImage(BaseFirmwareImage): + """ 'Version 2' firmware image, segments loaded by software bootloader stub + (ie Espressif bootloader or rboot) + """ + def __init__(self, load_file=None): + super(OTAFirmwareImage, self).__init__() + self.version = 2 + if load_file is not None: + (magic, segments, first_flash_mode, first_flash_size_freq, first_entrypoint) = struct.unpack(' 16: + raise FatalError('Invalid V2 second header magic=%d segments=%d' % (magic, segments)) + + # load all the usual segments + for _ in xrange(segments): + self.load_segment(load_file) + self.checksum = self.read_checksum(load_file) + + def save(self, filename): + with open(filename, 'wb') as f: + # Save first header for irom0 segment + f.write(struct.pack(' 0: + esp._port.baudrate = baud_rate + # Read the greeting. + p = esp.read() + if p != 'OHAI': + raise FatalError('Failed to connect to the flasher (got %s)' % hexify(p)) + + def flash_write(self, addr, data, show_progress=False): + assert addr % self._esp.ESP_FLASH_SECTOR == 0, 'Address must be sector-aligned' + assert len(data) % self._esp.ESP_FLASH_SECTOR == 0, 'Length must be sector-aligned' + sys.stdout.write('Writing %d @ 0x%x... ' % (len(data), addr)) + sys.stdout.flush() + self._esp.write(struct.pack(' length: + raise FatalError('Read more than expected') + p = self._esp.read() + if len(p) != 16: + raise FatalError('Expected digest, got: %s' % hexify(p)) + expected_digest = hexify(p).upper() + digest = hashlib.md5(data).hexdigest().upper() + print + if digest != expected_digest: + raise FatalError('Digest mismatch: expected %s, got %s' % (expected_digest, digest)) + p = self._esp.read() + if len(p) != 1: + raise FatalError('Expected status, got: %s' % hexify(p)) + status_code = struct.unpack(', ) or a single +# argument. + +def load_ram(esp, args): + image = LoadFirmwareImage(args.filename) + + print 'RAM boot...' + for (offset, size, data) in image.segments: + print 'Downloading %d bytes at %08x...' % (size, offset), + sys.stdout.flush() + esp.mem_begin(size, div_roundup(size, esp.ESP_RAM_BLOCK), esp.ESP_RAM_BLOCK, offset) + + seq = 0 + while len(data) > 0: + esp.mem_block(data[0:esp.ESP_RAM_BLOCK], seq) + data = data[esp.ESP_RAM_BLOCK:] + seq += 1 + print 'done!' + + print 'All segments done, executing at %08x' % image.entrypoint + esp.mem_finish(image.entrypoint) + + +def read_mem(esp, args): + print '0x%08x = 0x%08x' % (args.address, esp.read_reg(args.address)) + + +def write_mem(esp, args): + esp.write_reg(args.address, args.value, args.mask, 0) + print 'Wrote %08x, mask %08x to %08x' % (args.value, args.mask, args.address) + + +def dump_mem(esp, args): + f = file(args.filename, 'wb') + for i in xrange(args.size / 4): + d = esp.read_reg(args.address + (i * 4)) + f.write(struct.pack('> 16 + args.flash_size = {18: '2m', 19: '4m', 20: '8m', 21: '16m', 22: '32m'}.get(size_id) + if args.flash_size is None: + print 'Warning: Could not auto-detect Flash size (FlashID=0x%x, SizeID=0x%x), defaulting to 4m' % (flash_id, size_id) + args.flash_size = '4m' + else: + print 'Auto-detected Flash size:', args.flash_size + + +def write_flash(esp, args): + detect_flash_size(esp, args) + flash_mode = {'qio':0, 'qout':1, 'dio':2, 'dout': 3}[args.flash_mode] + flash_size_freq = {'4m':0x00, '2m':0x10, '8m':0x20, '16m':0x30, '32m':0x40, '16m-c1': 0x50, '32m-c1':0x60, '32m-c2':0x70}[args.flash_size] + flash_size_freq += {'40m':0, '26m':1, '20m':2, '80m': 0xf}[args.flash_freq] + flash_params = struct.pack('BB', flash_mode, flash_size_freq) + + flasher = CesantaFlasher(esp, args.baud) + + for address, argfile in args.addr_filename: + image = argfile.read() + argfile.seek(0) # rewind in case we need it again + if address + len(image) > int(args.flash_size.split('m')[0]) * (1 << 17): + print 'WARNING: Unlikely to work as data goes beyond end of flash. Hint: Use --flash_size' + # Fix sflash config data. + if address == 0 and image[0] == '\xe9': + print 'Flash params set to 0x%02x%02x' % (flash_mode, flash_size_freq) + image = image[0:2] + flash_params + image[4:] + # Pad to sector size, which is the minimum unit of writing (erasing really). + if len(image) % esp.ESP_FLASH_SECTOR != 0: + image += '\xff' * (esp.ESP_FLASH_SECTOR - (len(image) % esp.ESP_FLASH_SECTOR)) + t = time.time() + flasher.flash_write(address, image, not args.no_progress) + t = time.time() - t + print ('\rWrote %d bytes at 0x%x in %.1f seconds (%.1f kbit/s)...' + % (len(image), address, t, len(image) / t * 8 / 1000)) + print 'Leaving...' + if args.verify: + print 'Verifying just-written flash...' + _verify_flash(flasher, args, flash_params) + flasher.boot_fw() + + +def image_info(args): + image = LoadFirmwareImage(args.filename) + print('Image version: %d' % image.version) + print('Entry point: %08x' % image.entrypoint) if image.entrypoint != 0 else 'Entry point not set' + print '%d segments' % len(image.segments) + print + checksum = ESPROM.ESP_CHECKSUM_MAGIC + for (idx, (offset, size, data)) in enumerate(image.segments): + if image.version == 2 and idx == 0: + print 'Segment 1: %d bytes IROM0 (no load address)' % size + else: + print 'Segment %d: %5d bytes at %08x' % (idx + 1, size, offset) + checksum = ESPROM.checksum(data, checksum) + print + print 'Checksum: %02x (%s)' % (image.checksum, 'valid' if image.checksum == checksum else 'invalid!') + + +def make_image(args): + image = ESPFirmwareImage() + if len(args.segfile) == 0: + raise FatalError('No segments specified') + if len(args.segfile) != len(args.segaddr): + raise FatalError('Number of specified files does not match number of specified addresses') + for (seg, addr) in zip(args.segfile, args.segaddr): + data = file(seg, 'rb').read() + image.add_segment(addr, data) + image.entrypoint = args.entrypoint + image.save(args.output) + + +def elf2image(args): + e = ELFFile(args.input) + if args.version == '1': + image = ESPFirmwareImage() + else: + image = OTAFirmwareImage() + irom_data = e.load_section('.irom0.text') + if len(irom_data) == 0: + raise FatalError(".irom0.text section not found in ELF file - can't create V2 image.") + image.add_segment(0, irom_data, 16) + image.entrypoint = e.get_entry_point() + for section, start in ((".text", "_text_start"), (".data", "_data_start"), (".rodata", "_rodata_start")): + data = e.load_section(section) + image.add_segment(e.get_symbol_addr(start), data) + + image.flash_mode = {'qio':0, 'qout':1, 'dio':2, 'dout': 3}[args.flash_mode] + image.flash_size_freq = {'4m':0x00, '2m':0x10, '8m':0x20, '16m':0x30, '32m':0x40, '16m-c1': 0x50, '32m-c1':0x60, '32m-c2':0x70}[args.flash_size] + image.flash_size_freq += {'40m':0, '26m':1, '20m':2, '80m': 0xf}[args.flash_freq] + + irom_offs = e.get_symbol_addr("_irom0_text_start") - 0x40200000 + + if args.version == '1': + if args.output is None: + args.output = args.input + '-' + image.save(args.output + "0x00000.bin") + data = e.load_section(".irom0.text") + if irom_offs < 0: + raise FatalError('Address of symbol _irom0_text_start in ELF is located before flash mapping address. Bad linker script?') + if (irom_offs & 0xFFF) != 0: # irom0 isn't flash sector aligned + print "WARNING: irom0 section offset is 0x%08x. ELF is probably linked for 'elf2image --version=2'" % irom_offs + with open(args.output + "0x%05x.bin" % irom_offs, "wb") as f: + f.write(data) + f.close() + else: # V2 OTA image + if args.output is None: + args.output = "%s-0x%05x.bin" % (os.path.splitext(args.input)[0], irom_offs & ~(ESPROM.ESP_FLASH_SECTOR - 1)) + image.save(args.output) + + +def read_mac(esp, args): + mac = esp.read_mac() + print 'MAC: %s' % ':'.join(map(lambda x: '%02x' % x, mac)) + + +def chip_id(esp, args): + chipid = esp.chip_id() + print 'Chip ID: 0x%08x' % chipid + + +def erase_flash(esp, args): + flasher = CesantaFlasher(esp, args.baud) + print 'Erasing flash (this may take a while)...' + t = time.time() + flasher.flash_erase_chip() + t = time.time() - t + print 'Erase took %.1f seconds' % t + + +def run(esp, args): + esp.run() + + +def flash_id(esp, args): + flash_id = esp.flash_id() + esp.flash_finish(False) + print 'Manufacturer: %02x' % (flash_id & 0xff) + print 'Device: %02x%02x' % ((flash_id >> 8) & 0xff, (flash_id >> 16) & 0xff) + + +def read_flash(esp, args): + flasher = CesantaFlasher(esp, args.baud) + t = time.time() + data = flasher.flash_read(args.address, args.size, not args.no_progress) + t = time.time() - t + print ('\rRead %d bytes at 0x%x in %.1f seconds (%.1f kbit/s)...' + % (len(data), args.address, t, len(data) / t * 8 / 1000)) + file(args.filename, 'wb').write(data) + + +def _verify_flash(flasher, args, flash_params=None): + differences = False + for address, argfile in args.addr_filename: + image = argfile.read() + argfile.seek(0) # rewind in case we need it again + if address == 0 and image[0] == '\xe9' and flash_params is not None: + image = image[0:2] + flash_params + image[4:] + image_size = len(image) + print 'Verifying 0x%x (%d) bytes @ 0x%08x in flash against %s...' % (image_size, image_size, address, argfile.name) + # Try digest first, only read if there are differences. + digest, _ = flasher.flash_digest(address, image_size) + digest = hexify(digest).upper() + expected_digest = hashlib.md5(image).hexdigest().upper() + if digest == expected_digest: + print '-- verify OK (digest matched)' + continue + else: + differences = True + if getattr(args, 'diff', 'no') != 'yes': + print '-- verify FAILED (digest mismatch)' + continue + + flash = flasher.flash_read(address, image_size) + assert flash != image + diff = [i for i in xrange(image_size) if flash[i] != image[i]] + print '-- verify FAILED: %d differences, first @ 0x%08x' % (len(diff), address + diff[0]) + for d in diff: + print ' %08x %02x %02x' % (address + d, ord(flash[d]), ord(image[d])) + if differences: + raise FatalError("Verify failed.") + + +def verify_flash(esp, args, flash_params=None): + flasher = CesantaFlasher(esp) + _verify_flash(flasher, args, flash_params) + + +def version(args): + print __version__ + +# +# End of operations functions +# + + +def main(): + parser = argparse.ArgumentParser(description='esptool.py v%s - ESP8266 ROM Bootloader Utility' % __version__, prog='esptool') + + parser.add_argument( + '--port', '-p', + help='Serial port device', + default=os.environ.get('ESPTOOL_PORT', None)) + + parser.add_argument( + '--baud', '-b', + help='Serial port baud rate used when flashing/reading', + type=arg_auto_int, + default=os.environ.get('ESPTOOL_BAUD', ESPROM.ESP_ROM_BAUD)) + + subparsers = parser.add_subparsers( + dest='operation', + help='Run esptool {command} -h for additional help') + + parser_load_ram = subparsers.add_parser( + 'load_ram', + help='Download an image to RAM and execute') + parser_load_ram.add_argument('filename', help='Firmware image') + + parser_dump_mem = subparsers.add_parser( + 'dump_mem', + help='Dump arbitrary memory to disk') + parser_dump_mem.add_argument('address', help='Base address', type=arg_auto_int) + parser_dump_mem.add_argument('size', help='Size of region to dump', type=arg_auto_int) + parser_dump_mem.add_argument('filename', help='Name of binary dump') + + parser_read_mem = subparsers.add_parser( + 'read_mem', + help='Read arbitrary memory location') + parser_read_mem.add_argument('address', help='Address to read', type=arg_auto_int) + + parser_write_mem = subparsers.add_parser( + 'write_mem', + help='Read-modify-write to arbitrary memory location') + parser_write_mem.add_argument('address', help='Address to write', type=arg_auto_int) + parser_write_mem.add_argument('value', help='Value', type=arg_auto_int) + parser_write_mem.add_argument('mask', help='Mask of bits to write', type=arg_auto_int) + + def add_spi_flash_subparsers(parent, auto_detect=False): + """ Add common parser arguments for SPI flash properties """ + parent.add_argument('--flash_freq', '-ff', help='SPI Flash frequency', + choices=['40m', '26m', '20m', '80m'], + default=os.environ.get('ESPTOOL_FF', '40m')) + parent.add_argument('--flash_mode', '-fm', help='SPI Flash mode', + choices=['qio', 'qout', 'dio', 'dout'], + default=os.environ.get('ESPTOOL_FM', 'qio')) + choices = ['4m', '2m', '8m', '16m', '32m', '16m-c1', '32m-c1', '32m-c2'] + default = '4m' + if auto_detect: + default = 'detect' + choices.insert(0, 'detect') + parent.add_argument('--flash_size', '-fs', help='SPI Flash size in Mbit', type=str.lower, + choices=choices, + default=os.environ.get('ESPTOOL_FS', default)) + + parser_write_flash = subparsers.add_parser( + 'write_flash', + help='Write a binary blob to flash') + parser_write_flash.add_argument('addr_filename', metavar='
', help='Address followed by binary filename, separated by space', + action=AddrFilenamePairAction) + add_spi_flash_subparsers(parser_write_flash, auto_detect=True) + parser_write_flash.add_argument('--no-progress', '-p', help='Suppress progress output', action="store_true") + parser_write_flash.add_argument('--verify', help='Verify just-written data (only necessary if very cautious, data is already CRCed', action='store_true') + + subparsers.add_parser( + 'run', + help='Run application code in flash') + + parser_image_info = subparsers.add_parser( + 'image_info', + help='Dump headers from an application image') + parser_image_info.add_argument('filename', help='Image file to parse') + + parser_make_image = subparsers.add_parser( + 'make_image', + help='Create an application image from binary files') + parser_make_image.add_argument('output', help='Output image file') + parser_make_image.add_argument('--segfile', '-f', action='append', help='Segment input file') + parser_make_image.add_argument('--segaddr', '-a', action='append', help='Segment base address', type=arg_auto_int) + parser_make_image.add_argument('--entrypoint', '-e', help='Address of entry point', type=arg_auto_int, default=0) + + parser_elf2image = subparsers.add_parser( + 'elf2image', + help='Create an application image from ELF file') + parser_elf2image.add_argument('input', help='Input ELF file') + parser_elf2image.add_argument('--output', '-o', help='Output filename prefix (for version 1 image), or filename (for version 2 single image)', type=str) + parser_elf2image.add_argument('--version', '-e', help='Output image version', choices=['1','2'], default='1') + add_spi_flash_subparsers(parser_elf2image) + + subparsers.add_parser( + 'read_mac', + help='Read MAC address from OTP ROM') + + subparsers.add_parser( + 'chip_id', + help='Read Chip ID from OTP ROM') + + subparsers.add_parser( + 'flash_id', + help='Read SPI flash manufacturer and device ID') + + parser_read_flash = subparsers.add_parser( + 'read_flash', + help='Read SPI flash content') + parser_read_flash.add_argument('address', help='Start address', type=arg_auto_int) + parser_read_flash.add_argument('size', help='Size of region to dump', type=arg_auto_int) + parser_read_flash.add_argument('filename', help='Name of binary dump') + parser_read_flash.add_argument('--no-progress', '-p', help='Suppress progress output', action="store_true") + + parser_verify_flash = subparsers.add_parser( + 'verify_flash', + help='Verify a binary blob against flash') + parser_verify_flash.add_argument('addr_filename', help='Address and binary file to verify there, separated by space', + action=AddrFilenamePairAction) + parser_verify_flash.add_argument('--diff', '-d', help='Show differences', + choices=['no', 'yes'], default='no') + + subparsers.add_parser( + 'erase_flash', + help='Perform Chip Erase on SPI flash') + + subparsers.add_parser( + 'version', help='Print esptool version') + + # internal sanity check - every operation matches a module function of the same name + for operation in subparsers.choices.keys(): + assert operation in globals(), "%s should be a module function" % operation + + args = parser.parse_args() + + print 'esptool.py v%s' % __version__ + + # operation function can take 1 arg (args), 2 args (esp, arg) + # or be a member function of the ESPROM class. + + operation_func = globals()[args.operation] + operation_args,_,_,_ = inspect.getargspec(operation_func) + if operation_args[0] == 'esp': # operation function takes an ESPROM connection object + initial_baud = min(ESPROM.ESP_ROM_BAUD, args.baud) # don't sync faster than the default baud rate + esp = ESPROM(args.port, initial_baud) + esp.connect() + operation_func(esp, args) + else: + operation_func(args) + + +class AddrFilenamePairAction(argparse.Action): + """ Custom parser class for the address/filename pairs passed as arguments """ + def __init__(self, option_strings, dest, nargs='+', **kwargs): + super(AddrFilenamePairAction, self).__init__(option_strings, dest, nargs, **kwargs) + + def __call__(self, parser, namespace, values, option_string=None): + # validate pair arguments + pairs = [] + for i in range(0,len(values),2): + try: + address = int(values[i],0) + except ValueError as e: + raise argparse.ArgumentError(self,'Address "%s" must be a number' % values[i]) + try: + argfile = open(values[i + 1], 'rb') + except IOError as e: + raise argparse.ArgumentError(self, e) + except IndexError: + raise argparse.ArgumentError(self,'Must be pairs of an address and the binary filename to write there') + pairs.append((address, argfile)) + setattr(namespace, self.dest, pairs) + +# This is "wrapped" stub_flasher.c, to be loaded using run_stub. +_CESANTA_FLASHER_STUB = """\ +{"code_start": 1074790404, "code": "080000601C000060000000601000006031FCFF71FCFF\ +81FCFFC02000680332D218C020004807404074DCC48608005823C0200098081BA5A9239245005803\ +1B555903582337350129230B446604DFC6F3FF21EEFFC0200069020DF0000000010078480040004A\ +0040B449004012C1F0C921D911E901DD0209312020B4ED033C2C56C2073020B43C3C56420701F5FF\ +C000003C4C569206CD0EEADD860300202C4101F1FFC0000056A204C2DCF0C02DC0CC6CCAE2D1EAFF\ +0606002030F456D3FD86FBFF00002020F501E8FFC00000EC82D0CCC0C02EC0C73DEB2ADC46030020\ +2C4101E1FFC00000DC42C2DCF0C02DC056BCFEC602003C5C8601003C6C4600003C7C08312D0CD811\ +C821E80112C1100DF0000C180000140010400C0000607418000064180000801800008C1800008418\ +0000881800009018000018980040880F0040A80F0040349800404C4A0040740F0040800F0040980F\ +00400099004012C1E091F5FFC961CD0221EFFFE941F9310971D9519011C01A223902E2D1180C0222\ +6E1D21E4FF31E9FF2AF11A332D0F42630001EAFFC00000C030B43C2256A31621E1FF1A2228022030\ +B43C3256B31501ADFFC00000DD023C4256ED1431D6FF4D010C52D90E192E126E0101DDFFC0000021\ +D2FF32A101C020004802303420C0200039022C0201D7FFC00000463300000031CDFF1A333803D023\ +C03199FF27B31ADC7F31CBFF1A3328030198FFC0000056C20E2193FF2ADD060E000031C6FF1A3328\ +030191FFC0000056820DD2DD10460800000021BEFF1A2228029CE231BCFFC020F51A33290331BBFF\ +C02C411A332903C0F0F4222E1D22D204273D9332A3FFC02000280E27B3F721ABFF381E1A2242A400\ +01B5FFC00000381E2D0C42A40001B3FFC0000056120801B2FFC00000C02000280EC2DC0422D2FCC0\ +2000290E01ADFFC00000222E1D22D204226E1D281E22D204E7B204291E860000126E012198FF32A0\ +042A21C54C003198FF222E1D1A33380337B202C6D6FF2C02019FFFC000002191FF318CFF1A223A31\ +019CFFC00000218DFF1C031A22C549000C02060300003C528601003C624600003C72918BFF9A1108\ +71C861D851E841F83112C1200DF00010000068100000581000007010000074100000781000007C10\ +0000801000001C4B0040803C004091FDFF12C1E061F7FFC961E941F9310971D9519011C01A662906\ +21F3FFC2D1101A22390231F2FF0C0F1A33590331EAFFF26C1AED045C2247B3028636002D0C016DFF\ +C0000021E5FF41EAFF2A611A4469040622000021E4FF1A222802F0D2C0D7BE01DD0E31E0FF4D0D1A\ +3328033D0101E2FFC00000561209D03D2010212001DFFFC000004D0D2D0C3D01015DFFC0000041D5\ +FFDAFF1A444804D0648041D2FF1A4462640061D1FF106680622600673F1331D0FF10338028030C43\ +853A002642164613000041CAFF222C1A1A444804202FC047328006F6FF222C1A273F3861C2FF222C\ +1A1A6668066732B921BDFF3D0C1022800148FFC0000021BAFF1C031A2201BFFFC000000C02460300\ +5C3206020000005C424600005C5291B7FF9A110871C861D851E841F83112C1200DF0B0100000C010\ +0000D010000012C1E091FEFFC961D951E9410971F931CD039011C0ED02DD0431A1FF9C1422A06247\ +B302062D0021F4FF1A22490286010021F1FF1A223902219CFF2AF12D0F011FFFC00000461C0022D1\ +10011CFFC0000021E9FFFD0C1A222802C7B20621E6FF1A22F8022D0E3D014D0F0195FFC000008C52\ +22A063C6180000218BFF3D01102280F04F200111FFC00000AC7D22D1103D014D0F010DFFC0000021\ +D6FF32D110102280010EFFC0000021D3FF1C031A220185FFC00000FAEEF0CCC056ACF821CDFF317A\ +FF1A223A310105FFC0000021C9FF1C031A22017CFFC000002D0C91C8FF9A110871C861D851E841F8\ +3112C1200DF0000200600000001040020060FFFFFF0012C1E00C02290131FAFF21FAFF026107C961\ +C02000226300C02000C80320CC10564CFF21F5FFC02000380221F4FF20231029010C432D010163FF\ +C0000008712D0CC86112C1200DF00080FE3F8449004012C1D0C9A109B17CFC22C1110C13C51C0026\ +1202463000220111C24110B68202462B0031F5FF3022A02802A002002D011C03851A0066820A2801\ +32210105A6FF0607003C12C60500000010212032A01085180066A20F2221003811482105B3FF2241\ +10861A004C1206FDFF2D011C03C5160066B20E280138114821583185CFFF06F7FF005C1286F5FF00\ +10212032A01085140066A20D2221003811482105E1FF06EFFF0022A06146EDFF45F0FFC6EBFF0000\ +01D2FFC0000006E9FF000C022241100C1322C110C50F00220111060600000022C1100C13C50E0022\ +011132C2FA303074B6230206C8FF08B1C8A112C1300DF0000000000010404F484149007519031027\ +000000110040A8100040BC0F0040583F0040CC2E00401CE20040D83900408000004021F4FF12C1E0\ +C961C80221F2FF097129010C02D951C91101F4FFC0000001F3FFC00000AC2C22A3E801F2FFC00000\ +21EAFFC031412A233D0C01EFFFC000003D0222A00001EDFFC00000C1E4FF2D0C01E8FFC000002D01\ +32A004450400C5E7FFDD022D0C01E3FFC00000666D1F4B2131DCFF4600004B22C0200048023794F5\ +31D9FFC0200039023DF08601000001DCFFC000000871C861D85112C1200DF000000012C1F0026103\ +01EAFEC00000083112C1100DF000643B004012C1D0E98109B1C9A1D991F97129013911E2A0C001FA\ +FFC00000CD02E792F40C0DE2A0C0F2A0DB860D00000001F4FFC00000204220E71240F7921C226102\ +01EFFFC0000052A0DC482157120952A0DD571205460500004D0C3801DA234242001BDD3811379DC5\ +C6000000000C0DC2A0C001E3FFC00000C792F608B12D0DC8A1D891E881F87112C1300DF00000", "\ +entry": 1074792180, "num_params": 1, "params_start": 1074790400, "data": "FE0510\ +401A0610403B0610405A0610407A061040820610408C0610408C061040", "data_start": 10736\ +43520} +""" + +if __name__ == '__main__': + try: + main() + except FatalError as e: + print '\nA fatal error occurred: %s' % e + sys.exit(2) diff --git a/python/flash_release.py b/python/flash_release.py new file mode 100755 index 0000000000..51f6a72e7a --- /dev/null +++ b/python/flash_release.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python +from __future__ import print_function +import sys +import time +import requests +import json +import StringIO + +def flash_release(path=None, st_serial=None): + from panda import Panda, PandaDFU, ESPROM, CesantaFlasher + from zipfile import ZipFile + + def status(x): + print("\033[1;32;40m"+x+"\033[00m") + + if st_serial == None: + # look for Panda + panda_list = Panda.list() + if len(panda_list) == 0: + raise Exception("panda not found, make sure it's connected and your user can access it") + elif len(panda_list) > 1: + raise Exception("Please only connect one panda") + st_serial = panda_list[0] + print("Using panda with serial %s" % st_serial) + + if path == None: + print("Fetching latest firmware from github.com/commaai/panda-artifacts") + r = requests.get("https://raw.githubusercontent.com/commaai/panda-artifacts/master/latest.json") + url = json.loads(r.text)['url'] + r = requests.get(url) + print("Fetching firmware from %s" % url) + path = StringIO.StringIO(r.content) + + zf = ZipFile(path) + zf.printdir() + + version = zf.read("version") + status("0. Preparing to flash "+version) + + code_bootstub = zf.read("bootstub.panda.bin") + code_panda = zf.read("panda.bin") + + code_boot_15 = zf.read("boot_v1.5.bin") + code_boot_15 = code_boot_15[0:2] + "\x00\x30" + code_boot_15[4:] + + code_user1 = zf.read("user1.bin") + code_user2 = zf.read("user2.bin") + + # enter DFU mode + status("1. Entering DFU mode") + panda = Panda(st_serial) + panda.enter_bootloader() + time.sleep(1) + + # program bootstub + status("2. Programming bootstub") + dfu = PandaDFU(PandaDFU.st_serial_to_dfu_serial(st_serial)) + dfu.program_bootstub(code_bootstub) + time.sleep(1) + + # flash main code + status("3. Flashing main code") + panda = Panda(st_serial) + panda.flash(code=code_panda) + panda.close() + + # flashing ESP + status("4. Flashing ESP (slow!)") + align = lambda x, sz=0x1000: x+"\xFF"*((sz-len(x)) % sz) + esp = ESPROM(st_serial) + esp.connect() + flasher = CesantaFlasher(esp, 230400) + flasher.flash_write(0x0, align(code_boot_15), True) + flasher.flash_write(0x1000, align(code_user1), True) + flasher.flash_write(0x81000, align(code_user2), True) + flasher.flash_write(0x3FE000, "\xFF"*0x1000) + flasher.boot_fw() + del flasher + del esp + time.sleep(1) + + # check for connection + status("5. Verifying version") + panda = Panda(st_serial) + my_version = panda.get_version() + print("dongle id: %s" % panda.get_serial()[0]) + print(my_version, "should be", version) + assert(str(version) == str(my_version)) + + # done! + status("6. Success!") + +if __name__ == "__main__": + flash_release(*sys.argv[1:]) + diff --git a/python/update.py b/python/update.py new file mode 100755 index 0000000000..d393df9fb4 --- /dev/null +++ b/python/update.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python +import os +import time + +def ensure_st_up_to_date(): + from panda import Panda, PandaDFU, BASEDIR + + with open(os.path.join(BASEDIR, "VERSION")) as f: + repo_version = f.read() + + panda = None + panda_dfu = None + should_flash_recover = False + + while 1: + # break on normal mode Panda + panda_list = Panda.list() + if len(panda_list) > 0: + panda = Panda(panda_list[0]) + break + + # flash on DFU mode Panda + panda_dfu = PandaDFU.list() + if len(panda_dfu) > 0: + panda_dfu = PandaDFU(panda_dfu[0]) + panda_dfu.recover() + + print "waiting for board..." + time.sleep(1) + + if panda.bootstub or not panda.get_version().startswith(repo_version): + panda.flash() + + if panda.bootstub: + panda.recover() + + assert(not panda.bootstub) + version = str(panda.get_version()) + print("%s should be %s" % (version, repo_version)) + assert(version.startswith(repo_version)) + +if __name__ == "__main__": + ensure_st_up_to_date() + diff --git a/release/.gitignore b/release/.gitignore new file mode 100644 index 0000000000..c4c4ffc6aa --- /dev/null +++ b/release/.gitignore @@ -0,0 +1 @@ +*.zip diff --git a/release/make_release.sh b/release/make_release.sh new file mode 100755 index 0000000000..7be994c82c --- /dev/null +++ b/release/make_release.sh @@ -0,0 +1,40 @@ +#!/bin/bash + +if [ ! -d "../../pandaextra" ]; then + echo "No release cert found, cannot build release." + echo "You probably aren't looking to do this anyway." + exit +fi + +export RELEASE=1 + +# make ST + bootstub +pushd . +cd ../board +make clean +make obj/panda.bin +make obj/bootstub.panda.bin +popd + +# make ESP +pushd . +cd ../boardesp +make clean +make user1.bin +make user2.bin +popd + +# make release +mkdir obj +make -f ../common/version.mk +make obj/gitversion.h +RELEASE_NAME=$(python -c "import sys;sys.stdout.write(open('obj/gitversion.h').read().split('\"')[1])") +echo -en $RELEASE_NAME > /tmp/version +rm -rf obj + +# make zip file +pushd . +cd .. +zip -j release/panda-$RELEASE_NAME.zip ~/one/panda/board/obj/bootstub.panda.bin ~/one/panda/board/obj/panda.bin ~/one/panda/boardesp/user?.bin ~/one/panda/boardesp/esp-open-sdk/ESP8266_NONOS_SDK_V1.5.4_16_05_20/bin/boot_v1.5.bin /tmp/version +popd + diff --git a/release/ota_release.sh b/release/ota_release.sh new file mode 100755 index 0000000000..541a196ba7 --- /dev/null +++ b/release/ota_release.sh @@ -0,0 +1,18 @@ +#!/bin/bash +mkdir -p /tmp/panda_firmware +unzip -o $1 -d /tmp/panda_firmware + +curl http://192.168.0.10/ + +echo "flashing user1" +curl http://192.168.0.10/espupdate1 --upload-file /tmp/panda_firmware/user1.bin +echo "flashing user2" +curl http://192.168.0.10/espupdate2 --upload-file /tmp/panda_firmware/user2.bin +echo "waiting 10s for reboot" +sleep 10 +echo "flashing st" +curl http://192.168.0.10/stupdate --upload-file /tmp/panda_firmware/panda.bin +sleep 2 +curl http://192.168.0.10/ +echo "done" + diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000..e968bfb6ba --- /dev/null +++ b/requirements.txt @@ -0,0 +1,4 @@ +libusb1 +hexdump +pycrypto +tqdm diff --git a/run_automated_tests.sh b/run_automated_tests.sh new file mode 100755 index 0000000000..d7b7541902 --- /dev/null +++ b/run_automated_tests.sh @@ -0,0 +1,3 @@ +#!/bin/bash +PYTHONPATH="." nosetests -x -s tests/automated/$1*.py + diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000000..3480374bc2 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,2 @@ +[bdist_wheel] +universal=1 \ No newline at end of file diff --git a/setup.py b/setup.py new file mode 100644 index 0000000000..312fdca42a --- /dev/null +++ b/setup.py @@ -0,0 +1,65 @@ +#-*- coding: utf-8 -*- + +""" + Panda CAN Controller Dongle + ~~~~~ + + Setup + ````` + + $ pip install . # or python setup.py install +""" + +import codecs +import os +import re +from setuptools import setup, Extension + +here = os.path.abspath(os.path.dirname(__file__)) + +def read(*parts): + """Taken from pypa pip setup.py: + intentionally *not* adding an encoding option to open, See: + https://github.com/pypa/virtualenv/issues/201#issuecomment-3145690 + """ + return codecs.open(os.path.join(here, *parts), 'r').read() + + +def find_version(*file_paths): + version_file = read(*file_paths) + version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", + version_file, re.M) + if version_match: + return version_match.group(1) + raise RuntimeError("Unable to find version string.") + +setup( + name='pandacan', + version=find_version("python", "__init__.py"), + url='https://github.com/commaai/panda', + author='comma.ai', + author_email='', + packages=[ + 'panda', + ], + package_dir = {'panda': 'python'}, + platforms='any', + license='MIT', + install_requires=[ + 'libusb1 >= 1.6.4', + 'hexdump >= 3.3', + 'pycrypto >= 2.6.1', + 'tqdm >= 4.14.0', + 'requests' + ], + ext_modules = [], + description="Code powering the comma.ai panda", + long_description='See https://github.com/commaai/panda', + classifiers=[ + 'Development Status :: 2 - Pre-Alpha', + "Natural Language :: English", + "Programming Language :: Python :: 2", + "Programming Language :: Python :: 3", + "Topic :: System :: Hardware", + ], +) diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/all_wifi_test.py b/tests/all_wifi_test.py new file mode 100755 index 0000000000..4e9d3a5318 --- /dev/null +++ b/tests/all_wifi_test.py @@ -0,0 +1,29 @@ +#!/usr/bin/python +import requests +import json +from automated.helpers import _connect_wifi +from panda import Panda +from nose.tools import assert_equal + +if __name__ == "__main__": + print("Fetching latest firmware from github.com/commaai/panda-artifacts") + r = requests.get("https://raw.githubusercontent.com/commaai/panda-artifacts/master/latest.json") + latest_version = json.loads(r.text)['version'] + + for p in Panda.list(): + dongle_id, pw = Panda(p).get_serial() + print dongle_id, pw + assert(dongle_id.isalnum()) + _connect_wifi(dongle_id, pw) + + r = requests.get("http://192.168.0.10/") + print r.text + wifi_dongle_id = r.text.split("ssid: panda-")[1].split("
")[0] + st_version = r.text.split("st version:")[1].strip().split("
")[0] + esp_version = r.text.split("esp version:")[1].strip().split("
")[0] + + assert_equal(str(dongle_id), wifi_dongle_id) + assert_equal(latest_version, st_version) + assert_equal(latest_version, esp_version) + + diff --git a/tests/automated/0_builds.py b/tests/automated/0_builds.py new file mode 100644 index 0000000000..d5e434a2c2 --- /dev/null +++ b/tests/automated/0_builds.py @@ -0,0 +1,15 @@ +import os +from panda import build_st + +def test_build_legacy(): + build_st("obj/comma.bin", "Makefile.legacy") + +def test_build_bootstub_legacy(): + build_st("obj/bootstub.comma.bin", "Makefile.legacy") + +def test_build_panda(): + build_st("obj/panda.bin") + +def test_build_bootstub_panda(): + build_st("obj/bootstub.panda.bin") + diff --git a/tests/automated/1_program.py b/tests/automated/1_program.py new file mode 100644 index 0000000000..7da801bcd5 --- /dev/null +++ b/tests/automated/1_program.py @@ -0,0 +1,11 @@ +import os +from panda import Panda + +def test_recover(): + p = Panda() + p.recover() + +def test_flash(): + p = Panda() + p.flash() + diff --git a/tests/automated/2_usb_to_can.py b/tests/automated/2_usb_to_can.py new file mode 100644 index 0000000000..4815642407 --- /dev/null +++ b/tests/automated/2_usb_to_can.py @@ -0,0 +1,186 @@ +from __future__ import print_function +import os +import sys +import time +from panda import Panda +from nose.tools import timed, assert_equal, assert_less, assert_greater +from helpers import time_many_sends, connect_wo_esp + +SPEED_NORMAL = 500 +SPEED_GMLAN = 33.3 + +def test_can_loopback(): + p = connect_wo_esp() + + # enable output mode + p.set_safety_mode(Panda.SAFETY_ALLOUTPUT) + + # enable CAN loopback mode + p.set_can_loopback(True) + + if p.legacy: + busses = [0,1] + else: + busses = [0,1,2] + + for bus in busses: + # set bus 0 speed to 250 + p.set_can_speed_kbps(bus, 250) + + # send a message on bus 0 + p.can_send(0x1aa, "message", bus) + + # confirm receive both on loopback and send receipt + time.sleep(0.05) + r = p.can_recv() + sr = filter(lambda x: x[3] == 0x80 | bus, r) + lb = filter(lambda x: x[3] == bus, r) + assert len(sr) == 1 + assert len(lb) == 1 + + # confirm data is correct + assert 0x1aa == sr[0][0] == lb[0][0] + assert "message" == sr[0][2] == lb[0][2] + +def test_safety_nooutput(): + p = connect_wo_esp() + + # enable output mode + p.set_safety_mode(Panda.SAFETY_NOOUTPUT) + + # enable CAN loopback mode + p.set_can_loopback(True) + + # send a message on bus 0 + p.can_send(0x1aa, "message", 0) + + # confirm receive nothing + time.sleep(0.05) + r = p.can_recv() + assert len(r) == 0 + +def test_reliability(): + p = connect_wo_esp() + + LOOP_COUNT = 100 + MSG_COUNT = 100 + + # enable output mode + p.set_safety_mode(Panda.SAFETY_ALLOUTPUT) + p.set_can_loopback(True) + p.set_can_speed_kbps(0, 1000) + + addrs = range(100, 100+MSG_COUNT) + ts = [(j, 0, "\xaa"*8, 0) for j in addrs] + + # 100 loops + for i in range(LOOP_COUNT): + st = time.time() + + p.can_send_many(ts) + + r = [] + while len(r) < 200 and (time.time() - st) < 0.5: + r.extend(p.can_recv()) + + sent_echo = filter(lambda x: x[3] == 0x80, r) + loopback_resp = filter(lambda x: x[3] == 0, r) + + assert_equal(sorted(map(lambda x: x[0], loopback_resp)), addrs) + assert_equal(sorted(map(lambda x: x[0], sent_echo)), addrs) + assert_equal(len(r), 200) + + # take sub 20ms + et = (time.time()-st)*1000.0 + assert_less(et, 20) + + sys.stdout.write("P") + sys.stdout.flush() + +def test_throughput(): + p = connect_wo_esp() + + # enable output mode + p.set_safety_mode(Panda.SAFETY_ALLOUTPUT) + + # enable CAN loopback mode + p.set_can_loopback(True) + + for speed in [100,250,500,750,1000]: + # set bus 0 speed to speed + p.set_can_speed_kbps(0, speed) + time.sleep(0.05) + + comp_kbps = time_many_sends(p, 0) + + # bit count from https://en.wikipedia.org/wiki/CAN_bus + saturation_pct = (comp_kbps/speed) * 100.0 + assert_greater(saturation_pct, 80) + assert_less(saturation_pct, 100) + + print("loopback 100 messages at speed %d, comp speed is %.2f, percent %.2f" % (speed, comp_kbps, saturation_pct)) + +def test_gmlan(): + p = connect_wo_esp() + + if p.legacy: + return + + # enable output mode + p.set_safety_mode(Panda.SAFETY_ALLOUTPUT) + + # enable CAN loopback mode + p.set_can_loopback(True) + + p.set_can_speed_kbps(1, SPEED_NORMAL) + p.set_can_speed_kbps(2, SPEED_NORMAL) + p.set_can_speed_kbps(3, SPEED_GMLAN) + + # 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_greater(comp_kbps_gmlan, 0.8 * SPEED_GMLAN) + assert_less(comp_kbps_gmlan, 1.0 * SPEED_GMLAN) + + p.set_gmlan(None) + comp_kbps_normal = time_many_sends(p, bus) + assert_greater(comp_kbps_normal, 0.8 * SPEED_NORMAL) + assert_less(comp_kbps_normal, 1.0 * SPEED_NORMAL) + + print("%d: %.2f kbps vs %.2f kbps" % (bus, comp_kbps_gmlan, comp_kbps_normal)) + +def test_gmlan_bad_toggle(): + p = connect_wo_esp() + + if p.legacy: + return + + # enable output mode + p.set_safety_mode(Panda.SAFETY_ALLOUTPUT) + + # enable CAN loopback mode + 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_greater(comp_kbps_gmlan, 0.6 * SPEED_GMLAN) + assert_less(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_greater(comp_kbps_normal, 0.6 * SPEED_NORMAL) + assert_less(comp_kbps_normal, 1.0 * SPEED_NORMAL) + + +# this will fail if you have hardware serial connected +def test_serial_debug(): + p = connect_wo_esp() + junk = p.serial_read(Panda.SERIAL_DEBUG) + p.call_control_api(0xc0) + assert(p.serial_read(Panda.SERIAL_DEBUG).startswith("can ")) + diff --git a/tests/automated/3_wifi.py b/tests/automated/3_wifi.py new file mode 100644 index 0000000000..c6f4154ba8 --- /dev/null +++ b/tests/automated/3_wifi.py @@ -0,0 +1,33 @@ +from __future__ import print_function +import os +from panda import Panda +from helpers import connect_wifi +import requests + +def test_get_serial(): + p = Panda() + print(p.get_serial()) + +def test_get_serial_in_flash_mode(): + p = Panda() + p.reset(enter_bootstub=True) + assert(p.bootstub) + print(p.get_serial()) + p.reset() + +def test_connect_wifi(): + connect_wifi() + +def test_flash_wifi(): + Panda.flash_ota_wifi() + connect_wifi() + +def test_wifi_flash_st(): + Panda.flash_ota_st() + +def test_webpage_fetch(): + r = requests.get("http://192.168.0.10/") + print(r.text) + + assert "This is your comma.ai panda" in r.text + diff --git a/tests/automated/4_wifi_functionality.py b/tests/automated/4_wifi_functionality.py new file mode 100644 index 0000000000..68686008e3 --- /dev/null +++ b/tests/automated/4_wifi_functionality.py @@ -0,0 +1,52 @@ +from __future__ import print_function +import time +from panda import Panda +from helpers import time_many_sends, connect_wifi +from nose.tools import timed, assert_equal, assert_less, assert_greater + +def test_get_serial_wifi(): + connect_wifi() + + p = Panda("WIFI") + print(p.get_serial()) + +def test_throughput(): + p = Panda() + + # enable output mode + p.set_safety_mode(Panda.SAFETY_ALLOUTPUT) + + # enable CAN loopback mode + p.set_can_loopback(True) + + p = Panda("WIFI") + + for speed in [100,250,500,750,1000]: + # set bus 0 speed to speed + p.set_can_speed_kbps(0, speed) + time.sleep(0.05) + + comp_kbps = time_many_sends(p, 0) + + # bit count from https://en.wikipedia.org/wiki/CAN_bus + saturation_pct = (comp_kbps/speed) * 100.0 + #assert_greater(saturation_pct, 80) + #assert_less(saturation_pct, 100) + + print("WIFI loopback 100 messages at speed %d, comp speed is %.2f, percent %.2f" % (speed, comp_kbps, saturation_pct)) + +def test_recv_only(): + p = Panda() + p.set_safety_mode(Panda.SAFETY_ALLOUTPUT) + p.set_can_loopback(True) + pwifi = Panda("WIFI") + + # TODO: msg_count=1000 drops packets, is this fixable? + for msg_count in [10,100,200]: + speed = 500 + p.set_can_speed_kbps(0, speed) + comp_kbps = time_many_sends(p, 0, pwifi, msg_count) + saturation_pct = (comp_kbps/speed) * 100.0 + + print("HT WIFI loopback %d messages at speed %d, comp speed is %.2f, percent %.2f" % (msg_count, speed, comp_kbps, saturation_pct)) + diff --git a/tests/automated/5_wifi_udp.py b/tests/automated/5_wifi_udp.py new file mode 100644 index 0000000000..7d6ccba660 --- /dev/null +++ b/tests/automated/5_wifi_udp.py @@ -0,0 +1,39 @@ +from __future__ import print_function +import sys +import time +from helpers import time_many_sends, connect_wifi +from panda import Panda, PandaWifiStreaming +from nose.tools import timed, assert_equal, assert_less, assert_greater + +def test_udp_doesnt_drop(): + connect_wifi() + + p = Panda() + p.set_safety_mode(Panda.SAFETY_ALLOUTPUT) + p.set_can_loopback(True) + + pwifi = PandaWifiStreaming() + while 1: + if len(pwifi.can_recv()) == 0: + break + + for msg_count in [1, 100]: + for i in range({1: 0x80, 100: 0x20}[msg_count]): + pwifi.kick() + + speed = 500 + p.set_can_speed_kbps(0, speed) + comp_kbps = time_many_sends(p, 0, pwifi, msg_count=msg_count, msg_id=0x100+i) + saturation_pct = (comp_kbps/speed) * 100.0 + + if msg_count == 1: + sys.stdout.write(".") + sys.stdout.flush() + else: + print("UDP WIFI loopback %d messages at speed %d, comp speed is %.2f, percent %.2f" % (msg_count, speed, comp_kbps, saturation_pct)) + assert_greater(saturation_pct, 40) + assert_less(saturation_pct, 100) + print("") + + + diff --git a/tests/automated/__init__.py b/tests/automated/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/automated/elm_wifi.py b/tests/automated/elm_wifi.py new file mode 100644 index 0000000000..f5a8849833 --- /dev/null +++ b/tests/automated/elm_wifi.py @@ -0,0 +1,669 @@ +from __future__ import print_function +import os +import sys +import time +import socket +import select +import pytest +import struct + +sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..")) +import elm_car_simulator +sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "..")) +from panda import Panda + +def elm_connect(): + s = socket.create_connection(("192.168.0.10", 35000)) + s.setblocking(0) + return s + +def read_or_fail(s): + ready = select.select([s], [], [], 4) + assert ready[0], "Socket did not receive data within the timeout duration." + return s.recv(1000) + +def sendrecv(s, dat): + s.send(dat) + return read_or_fail(s) + +def send_compare(s, dat, ret, timeout=4): + s.send(dat) + res = b'' + while ret.startswith(res) and ret != res: + print("Waiting") + ready = select.select([s], [], [], timeout) + if not ready[0]: + print("current recv data:", repr(res)) + break; + res += s.recv(1000) + #print("final recv data: '%s'" % repr(res)) + assert ret == res#, "Data does not agree (%s) (%s)"%(repr(ret), repr(res)) + +def sync_reset(s): + s.send("ATZ\r") + res = b'' + while not res.endswith("ELM327 v1.5\r\r>"): + res += read_or_fail(s) + print("Reset response is '%s'" % repr(res)) + +def test_reset(): + s = socket.create_connection(("192.168.0.10", 35000)) + s.setblocking(0) + + try: + sync_reset(s) + finally: + s.close() + +def test_elm_cli(): + s = elm_connect() + + try: + sync_reset(s) + + send_compare(s, b'ATI\r', b'ATI\rELM327 v1.5\r\r>') + + #Test Echo Off + #Expected to be misimplimentation, but this is how the reference device behaved. + send_compare(s, b'ATE0\r', b'ATE0\rOK\r\r>') #Here is the odd part + send_compare(s, b'ATE0\r', b'OK\r\r>') #Should prob show this immediately + send_compare(s, b'ATI\r', b'ELM327 v1.5\r\r>') + + #Test Newline On + send_compare(s, b'ATL1\r', b'OK\r\n\r\n>') + send_compare(s, b'ATI\r', b'ELM327 v1.5\r\n\r\n>') + send_compare(s, b'ATL0\r', b'OK\r\r>') + send_compare(s, b'ATI\r', b'ELM327 v1.5\r\r>') + + send_compare(s, b'ATI\r', b'ELM327 v1.5\r\r>') #Test repeat command no echo + send_compare(s, b'\r', b'ELM327 v1.5\r\r>') + + send_compare(s, b'aTi\r', b'ELM327 v1.5\r\r>') #Test different case + + send_compare(s, b' a T i\r', b'ELM327 v1.5\r\r>') #Test with white space + + send_compare(s, b'ATCATHAT\r', b'?\r\r>') #Test Invalid AT command + + send_compare(s, b'01 00 00 00 00 00 00 00\r', b'?\r\r>') #Test Invalid (too long) OBD command + send_compare(s, b'01 GZ\r', b'?\r\r>') #Test Invalid (Non hex chars) OBD command + finally: + s.close() + +def test_elm_setget_protocol(): + s = elm_connect() + + try: + sync_reset(s) + send_compare(s, b'ATE0\r', b'ATE0\rOK\r\r>') # Echo OFF + + send_compare(s, b'ATSP0\r', b"OK\r\r>") # Set auto + send_compare(s, b'ATDP\r', b"AUTO\r\r>") + send_compare(s, b'ATDPN\r', b"A0\r\r>") + + send_compare(s, b'ATSP6\r', b"OK\r\r>") # Set protocol + send_compare(s, b'ATDP\r', b"ISO 15765-4 (CAN 11/500)\r\r>") + send_compare(s, b'ATDPN\r', b"6\r\r>") + + send_compare(s, b'ATSPA6\r', b"OK\r\r>") # Set auto with protocol default + send_compare(s, b'ATDP\r', b"AUTO, ISO 15765-4 (CAN 11/500)\r\r>") + send_compare(s, b'ATDPN\r', b"A6\r\r>") + + send_compare(s, b'ATSP7\r', b"OK\r\r>") + send_compare(s, b'ATDP\r', b"ISO 15765-4 (CAN 29/500)\r\r>") + send_compare(s, b'ATDPN\r', b"7\r\r>") #Test Does not accept invalid protocols + send_compare(s, b'ATSPD\r', b"?\r\r>") + send_compare(s, b'ATDP\r', b"ISO 15765-4 (CAN 29/500)\r\r>") + send_compare(s, b'ATDPN\r', b"7\r\r>") + finally: + s.close() + +def test_elm_protocol_failure(): + s = elm_connect() + + try: + sync_reset(s) + send_compare(s, b'ATE0\r', b'ATE0\rOK\r\r>') # Echo OFF + + send_compare(s, b'ATSP0\r', b"OK\r\r>") + send_compare(s, b'0100\r', b"SEARCHING...\rUNABLE TO CONNECT\r\r>", timeout=10) + + send_compare(s, b'ATSP1\r', b"OK\r\r>") + send_compare(s, b'0100\r', b"NO DATA\r\r>") + + send_compare(s, b'ATSP2\r', b"OK\r\r>") + send_compare(s, b'0100\r', b"NO DATA\r\r>") + + send_compare(s, b'ATSP3\r', b"OK\r\r>") + send_compare(s, b'0100\r', b"BUS INIT: ...ERROR\r\r>") + + send_compare(s, b'ATSP4\r', b"OK\r\r>") + send_compare(s, b'0100\r', b"BUS INIT: ...ERROR\r\r>") + + send_compare(s, b'ATSP5\r', b"OK\r\r>") + send_compare(s, b'0100\r', b"BUS INIT: ERROR\r\r>") + + #send_compare(s, b'ATSP6\r', b"OK\r\r>") + #send_compare(s, b'0100\r', b"NO DATA\r\r>") + # + #send_compare(s, b'ATSP7\r', b"OK\r\r>") + #send_compare(s, b'0100\r', b"NO DATA\r\r>") + # + #send_compare(s, b'ATSP8\r', b"OK\r\r>") + #send_compare(s, b'0100\r', b"NO DATA\r\r>") + # + #send_compare(s, b'ATSP9\r', b"OK\r\r>") + #send_compare(s, b'0100\r', b"NO DATA\r\r>") + # + #send_compare(s, b'ATSPA\r', b"OK\r\r>") + #send_compare(s, b'0100\r', b"NO DATA\r\r>") + # + #send_compare(s, b'ATSPB\r', b"OK\r\r>") + #send_compare(s, b'0100\r', b"NO DATA\r\r>") + # + #send_compare(s, b'ATSPC\r', b"OK\r\r>") + #send_compare(s, b'0100\r', b"NO DATA\r\r>") + finally: + s.close() + +def test_elm_protocol_autodetect_ISO14230_KWP_FAST(): + s = elm_connect() + serial = os.getenv("CANSIMSERIAL") if os.getenv("CANSIMSERIAL") else None + sim = elm_car_simulator.ELMCarSimulator(serial, can=False)#, silent=True) + sim.start() + + try: + sync_reset(s) + send_compare(s, b'ATE0\r', b'ATE0\rOK\r\r>') # Echo OFF + send_compare(s, b'ATH0\r', b'OK\r\r>') # Headers ON + send_compare(s, b'ATS0\r', b"OK\r\r>") + + send_compare(s, b'ATSP0\r', b"OK\r\r>") + send_compare(s, b'010D\r', b"SEARCHING...\r410D53\r\r>", timeout=10) + send_compare(s, b'ATDPN\r', b"A5\r\r>") + finally: + sim.stop() + sim.join() + s.close() + +def test_elm_basic_send_lin(): + s = elm_connect() + serial = os.getenv("CANSIMSERIAL") if os.getenv("CANSIMSERIAL") else None + sim = elm_car_simulator.ELMCarSimulator(serial, can=False)#, silent=True) + sim.start() + + try: + sync_reset(s) + send_compare(s, b'ATSP5\r', b"ATSP5\rOK\r\r>") # Set Proto + + send_compare(s, b'ATE0\r', b'ATE0\rOK\r\r>') # Echo OFF + send_compare(s, b'0100\r', b"BUS INIT: OK\r41 00 FF FF FF FE \r\r>") + send_compare(s, b'010D\r', b"41 0D 53 \r\r>") + + send_compare(s, b'ATS0\r', b'OK\r\r>') # Spaces Off + send_compare(s, b'0100\r', b"4100FFFFFFFE\r\r>") + send_compare(s, b'010D\r', b"410D53\r\r>") + + send_compare(s, b'ATH1\r', b'OK\r\r>') # Spaces Off Headers On + send_compare(s, b'0100\r', b"86F1104100FFFFFFFEC3\r\r>") + send_compare(s, b'010D\r', b"83F110410D5325\r\r>") + + send_compare(s, b'ATS1\r', b'OK\r\r>') # Spaces On Headers On + send_compare(s, b'0100\r', b"86 F1 10 41 00 FF FF FF FE C3 \r\r>") + send_compare(s, b'010D\r', b"83 F1 10 41 0D 53 25 \r\r>") + + send_compare(s, b'1F00\r', b"NO DATA\r\r>") # Unhandled msg, no response. + + # Repeat last check to see if it still works after NO DATA was received + send_compare(s, b'0100\r', b"86 F1 10 41 00 FF FF FF FE C3 \r\r>") + send_compare(s, b'010D\r', b"83 F1 10 41 0D 53 25 \r\r>") + finally: + sim.stop() + sim.join() + s.close() + +def test_elm_send_lin_multiline_msg(): + s = elm_connect() + serial = os.getenv("CANSIMSERIAL") if os.getenv("CANSIMSERIAL") else None + sim = elm_car_simulator.ELMCarSimulator(serial, can=False) + sim.start() + + try: + sync_reset(s) + send_compare(s, b'ATE0\r', b'ATE0\rOK\r\r>') # Echo OFF + send_compare(s, b'ATSP5\r', b"OK\r\r>") # Set Proto + + send_compare(s, b'0902\r', # headers OFF, Spaces ON + b"BUS INIT: OK\r" + "49 02 01 00 00 00 31 \r" + "49 02 02 44 34 47 50 \r" + "49 02 03 30 30 52 35 \r" + "49 02 04 35 42 31 32 \r" + "49 02 05 33 34 35 36 \r\r>") + + send_compare(s, b'ATS0\r', b'OK\r\r>') # Spaces OFF + send_compare(s, b'0902\r', # Headers OFF, Spaces OFF + b"49020100000031\r" + "49020244344750\r" + "49020330305235\r" + "49020435423132\r" + "49020533343536\r\r>") + + send_compare(s, b'ATH1\r', b'OK\r\r>') # Headers ON + send_compare(s, b'0902\r', # Headers ON, Spaces OFF + b"87F1104902010000003105\r" + "87F11049020244344750E4\r" + "87F11049020330305235BD\r" + "87F11049020435423132B1\r" + "87F11049020533343536AA\r\r>") + + send_compare(s, b'ATS1\r', b'OK\r\r>') # Spaces ON + send_compare(s, b'0902\r', # Headers ON, Spaces ON + b"87 F1 10 49 02 01 00 00 00 31 05 \r" + "87 F1 10 49 02 02 44 34 47 50 E4 \r" + "87 F1 10 49 02 03 30 30 52 35 BD \r" + "87 F1 10 49 02 04 35 42 31 32 B1 \r" + "87 F1 10 49 02 05 33 34 35 36 AA \r\r>") + finally: + sim.stop() + sim.join() + s.close() + +def test_elm_send_lin_multiline_msg_throughput(): + s = elm_connect() + serial = os.getenv("CANSIMSERIAL") if os.getenv("CANSIMSERIAL") else None + sim = elm_car_simulator.ELMCarSimulator(serial, can=False, silent=True) + sim.start() + + try: + sync_reset(s) + send_compare(s, b'ATSP5\r', b"ATSP5\rOK\r\r>") # Set Proto + send_compare(s, b'ATE0\r', b'ATE0\rOK\r\r>') # Echo OFF + send_compare(s, b'ATS0\r', b'OK\r\r>') # Spaces OFF + send_compare(s, b'ATH0\r', b'OK\r\r>') # Headers OFF + + send_compare(s, b'09fc\r', # headers OFF, Spaces OFF + b"BUS INIT: OK\r" + + b''.join((b'49FC' + hex(num+1)[2:].upper().zfill(2) + + b'AAAA' + hex(num+1)[2:].upper().zfill(4) + b'\r' + for num in range(80))) + + b"\r>", + timeout=10 + ) + finally: + sim.stop() + sim.join() + s.close() + +def test_elm_panda_safety_mode_KWPFast(): + serial = os.getenv("CANSIMSERIAL") if os.getenv("CANSIMSERIAL") else None + p_car = Panda(serial) # Configure this so the messages will send + p_car.set_safety_mode(Panda.SAFETY_ALLOUTPUT) + p_car.kline_drain() + + p_elm = Panda("WIFI") + p_elm.set_safety_mode(0xE327); + + def get_checksum(dat): + result = 0 + result += sum(map(ord, dat)) if isinstance(b'dat', str) else sum(dat) + return struct.pack("B", result % 0x100) + + def timed_recv_check(p, bus, goodmsg): + t = time.time() + msg = bytearray() + + while time.time()-t < 0.5 and len(msg) != len(goodmsg): + msg += p._handle.controlRead(Panda.REQUEST_OUT, 0xe0, bus, 0, len(goodmsg)-len(msg)) + #print("Received", repr(msg)) + if msg == goodmsg: + return True + time.sleep(0.01) + return False + + def kline_send(p, x, bus=2): + p.kline_drain(bus=bus) + p._handle.bulkWrite(2, chr(bus).encode()+x) + return timed_recv_check(p, bus, x) + + def did_send(priority, toaddr, fromaddr, dat, bus=2, checkbyte=None): + msgout = struct.pack("BBB", priority | len(dat), toaddr, fromaddr) + dat + msgout += get_checksum(msgout) if checkbyte is None else checkbyte + print("Sending", hex(priority), hex(toaddr), hex(fromaddr), repr(msgout)) + + if not kline_send(p_elm, msgout, bus=bus): + return False + return timed_recv_check(p_car, bus, msgout) + + assert not did_send(0xC0, 0x33, 0xF1, b'\x01\x0F', bus=3) #wrong bus + assert not did_send(0xC0, 0x33, 0xF1, b'') #wrong length + assert not did_send(0xB0, 0x33, 0xF1, b'\x01\x0E') #bad priority + assert not did_send(0xC0, 0x00, 0xF1, b'\x01\x0D') #bad addr + assert not did_send(0xC0, 0x33, 0x00, b'\x01\x0C') #bad addr + + assert did_send(0xC0, 0x33, 0xF1, b'\x01\x0B') #good! (obd func req) + +def test_elm_lin_keepalive(): + s = elm_connect() + serial = os.getenv("CANSIMSERIAL") if os.getenv("CANSIMSERIAL") else None + sim = elm_car_simulator.ELMCarSimulator(serial, can=False, silent=True) + sim.start() + + try: + sync_reset(s) + send_compare(s, b'ATSP5\r', b"ATSP5\rOK\r\r>") # Set Proto + send_compare(s, b'ATE0\r', b'ATE0\rOK\r\r>') # Echo OFF + send_compare(s, b'ATS0\r', b'OK\r\r>') # Spaces OFF + send_compare(s, b'ATH0\r', b'OK\r\r>') # Headers OFF + + send_compare(s, b'0100\r', b"BUS INIT: OK\r4100FFFFFFFE\r\r>") + assert sim.lin_active + time.sleep(6) + assert sim.lin_active + + send_compare(s, b'ATPC\r', b"OK\r\r>") #STOP KEEPALIVE + assert sim.lin_active + time.sleep(6) + assert not sim.lin_active + + finally: + sim.stop() + sim.join() + s.close() + +#//////////// +def test_elm_protocol_autodetect_ISO15765(): + s = elm_connect() + serial = os.getenv("CANSIMSERIAL") if os.getenv("CANSIMSERIAL") else None + sim = elm_car_simulator.ELMCarSimulator(serial, lin=False, silent=True) + sim.start() + + try: + sync_reset(s) + send_compare(s, b'ATE0\r', b'ATE0\rOK\r\r>') # Echo OFF + send_compare(s, b'ATH1\r', b'OK\r\r>') # Headers ON + send_compare(s, b'ATS0\r', b"OK\r\r>") + + sim.can_mode_11b() + send_compare(s, b'ATSP0\r', b"OK\r\r>") + send_compare(s, b'010D\r', b"SEARCHING...\r7E803410D53\r\r>", timeout=10) + send_compare(s, b'ATDPN\r', b"A6\r\r>") + + sim.can_mode_29b() + send_compare(s, b'ATSP0\r', b"OK\r\r>") + send_compare(s, b'010D\r', b"SEARCHING...\r18DAF11003410D53\r\r>", timeout=10) + send_compare(s, b'ATDPN\r', b"A7\r\r>") + + sim.change_can_baud(250) + + sim.can_mode_11b() + send_compare(s, b'ATSP0\r', b"OK\r\r>") + send_compare(s, b'010D\r', b"SEARCHING...\r7E803410D53\r\r>", timeout=10) + send_compare(s, b'ATDPN\r', b"A8\r\r>") + + sim.can_mode_29b() + send_compare(s, b'ATSP0\r', b"OK\r\r>") + send_compare(s, b'010D\r', b"SEARCHING...\r18DAF11003410D53\r\r>", timeout=10) + send_compare(s, b'ATDPN\r', b"A9\r\r>") + finally: + sim.stop() + sim.join() + s.close() + +def test_elm_basic_send_can(): + s = elm_connect() + serial = os.getenv("CANSIMSERIAL") if os.getenv("CANSIMSERIAL") else None + sim = elm_car_simulator.ELMCarSimulator(serial, lin=False, silent=True) + sim.start() + + try: + sync_reset(s) + send_compare(s, b'ATSP6\r', b"ATSP6\rOK\r\r>") # Set Proto + + send_compare(s, b'ATE0\r', b'ATE0\rOK\r\r>') # Echo OFF + send_compare(s, b'0100\r', b"41 00 FF FF FF FE \r\r>") + send_compare(s, b'010D\r', b"41 0D 53 \r\r>") + + send_compare(s, b'ATS0\r', b'OK\r\r>') # Spaces Off + send_compare(s, b'0100\r', b"4100FFFFFFFE\r\r>") + send_compare(s, b'010D\r', b"410D53\r\r>") + + send_compare(s, b'ATH1\r', b'OK\r\r>') # Spaces Off Headers On + send_compare(s, b'0100\r', b"7E8064100FFFFFFFE\r\r>") + send_compare(s, b'010D\r', b"7E803410D53\r\r>") + + send_compare(s, b'ATS1\r', b'OK\r\r>') # Spaces On Headers On + send_compare(s, b'0100\r', b"7E8 06 41 00 FF FF FF FE \r\r>") + send_compare(s, b'010D\r', b"7E8 03 41 0D 53 \r\r>") + + send_compare(s, b'1F00\r', b"NO DATA\r\r>") # Unhandled msg, no response. + + # Repeat last check to see if it still works after NO DATA was received + send_compare(s, b'0100\r', b"7E8 06 41 00 FF FF FF FE \r\r>") + send_compare(s, b'010D\r', b"7E8 03 41 0D 53 \r\r>") + finally: + sim.stop() + sim.join() + s.close() + +def test_elm_send_can_multimsg(): + s = elm_connect() + serial = os.getenv("CANSIMSERIAL") if os.getenv("CANSIMSERIAL") else None + sim = elm_car_simulator.ELMCarSimulator(serial, lin=False) + sim.start() + + try: + sync_reset(s) + send_compare(s, b'ATE0\r', b'ATE0\rOK\r\r>') # Echo OFF + send_compare(s, b'ATS1\r', b'OK\r\r>') # Spaces OFF + send_compare(s, b'ATH1\r', b'OK\r\r>') # Headers ON + + send_compare(s, b'ATSP6\r', b"OK\r\r>") # Set Proto ISO 15765-4 (CAN 11/500) + sim.can_add_extra_noise(b'\x03\x41\x0D\xFA', addr=0x7E9)# Inject message into the stream + send_compare(s, b'010D\r', + b"7E8 03 41 0D 53 \r" + "7E9 03 41 0D FA \r\r>") # Check it was ignored. + finally: + sim.stop() + sim.join() + s.close() + +"""The ability to correctly filter out messages with the wrong PID is not +implemented correctly in the reference device.""" +def test_elm_can_check_mode_pid(): + s = elm_connect() + serial = os.getenv("CANSIMSERIAL") if os.getenv("CANSIMSERIAL") else None + sim = elm_car_simulator.ELMCarSimulator(serial, lin=False) + sim.start() + + try: + sync_reset(s) + send_compare(s, b'ATE0\r', b'ATE0\rOK\r\r>') # Echo OFF + send_compare(s, b'ATS0\r', b'OK\r\r>') # Spaces OFF + send_compare(s, b'ATH0\r', b'OK\r\r>') # Headers OFF + + send_compare(s, b'ATSP6\r', b"OK\r\r>") # Set Proto ISO 15765-4 (CAN 11/500) + sim.can_add_extra_noise(b'\x03\x41\x0E\xFA')# Inject message into the stream + send_compare(s, b'010D\r', b"410D53\r\r>") # Check it was ignored. + send_compare(s, b'0100\r', b"4100FFFFFFFE\r\r>") # Check it was ignored again. + finally: + sim.stop() + sim.join() + s.close() + +def test_elm_send_can_multiline_msg(): + s = elm_connect() + serial = os.getenv("CANSIMSERIAL") if os.getenv("CANSIMSERIAL") else None + sim = elm_car_simulator.ELMCarSimulator(serial, lin=False) + sim.start() + + try: + sync_reset(s) + send_compare(s, b'ATSP6\r', b"ATSP6\rOK\r\r>") # Set Proto + send_compare(s, b'ATE0\r', b'ATE0\rOK\r\r>') # Echo OFF + + send_compare(s, b'0902\r', # headers OFF, Spaces ON + b"014 \r" + "0: 49 02 01 31 44 34 \r" + "1: 47 50 30 30 52 35 35 \r" + "2: 42 31 32 33 34 35 36 \r\r>") + + send_compare(s, b'ATS0\r', b'OK\r\r>') # Spaces OFF + send_compare(s, b'0902\r', # Headers OFF, Spaces OFF + b"014\r" + "0:490201314434\r" + "1:47503030523535\r" + "2:42313233343536\r\r>") + + send_compare(s, b'ATH1\r', b'OK\r\r>') # Headers ON + send_compare(s, b'0902\r', # Headers ON, Spaces OFF + b"7E81014490201314434\r" + "7E82147503030523535\r" + "7E82242313233343536\r\r>") + + send_compare(s, b'ATS1\r', b'OK\r\r>') # Spaces ON + send_compare(s, b'0902\r', # Headers ON, Spaces ON + b"7E8 10 14 49 02 01 31 44 34 \r" + "7E8 21 47 50 30 30 52 35 35 \r" + "7E8 22 42 31 32 33 34 35 36 \r\r>") + finally: + sim.stop() + sim.join() + s.close() + +def test_elm_send_can_multiline_msg_throughput(): + s = elm_connect() + serial = os.getenv("CANSIMSERIAL") if os.getenv("CANSIMSERIAL") else None + sim = elm_car_simulator.ELMCarSimulator(serial, lin=False, silent=True) + sim.start() + + try: + sync_reset(s) + send_compare(s, b'ATSP6\r', b"ATSP6\rOK\r\r>") # Set Proto + send_compare(s, b'ATE0\r', b'ATE0\rOK\r\r>') # Echo OFF + send_compare(s, b'ATS0\r', b'OK\r\r>') # Spaces OFF + send_compare(s, b'ATH1\r', b'OK\r\r>') # Headers ON + + rows = 584 + send_compare(s, b'09ff\r', # headers ON, Spaces OFF + ("7E8" + "1" + hex((rows*7)+6)[2:].upper().zfill(3) + "49FF01"+"AA0000\r" + + "".join( + ("7E82"+hex((num+1)%0x10)[2:].upper()+("AA"*5) + + hex(num+1)[2:].upper().zfill(4) + "\r" for num in range(rows)) + ) + "\r>").encode(), + timeout=10 + ) + finally: + sim.stop() + sim.join() + s.close() + +def test_elm_interrupted_obd_cmd_resets_state(): + s = elm_connect() + serial = os.getenv("CANSIMSERIAL") if os.getenv("CANSIMSERIAL") else None + sim = elm_car_simulator.ELMCarSimulator(serial, lin=False, silent=True) + sim.start() + + try: + sync_reset(s) + send_compare(s, b'ATE0\r', b'ATE0\rOK\r\r>') # Echo OFF + send_compare(s, b'ATS0\r', b'OK\r\r>') # Spaces OFF + s.send(b"09fd\r") + ready = select.select([s], [], [], 4) + assert ready[0], "Socket did not receive data within the timeout duration." + s.send(b"ATI\r") + + assert b"236\r0:49FD01AAAAAA\r" in s.recv(10000) + + #Will likely have to be improved to scan for STOPPED if the FW gets more responsive. + ready = select.select([s], [], [], 4) + assert ready[0], "Socket did not receive data within the timeout duration." + + assert b"STOPPED" in s.recv(10000) + + sim.set_enable(False) + send_compare(s, b'09fd\r', b"NO DATA\r\r>") + finally: + sim.stop() + sim.join() + s.close() + +def test_elm_can_baud(): + s = elm_connect() + serial = os.getenv("CANSIMSERIAL") if os.getenv("CANSIMSERIAL") else None + sim = elm_car_simulator.ELMCarSimulator(serial, lin=False) + sim.start() + + try: + sync_reset(s) + send_compare(s, b'ATE0\r', b'ATE0\rOK\r\r>') # Echo OFF + send_compare(s, b'ATS0\r', b'OK\r\r>') # Spaces OFF + send_compare(s, b'ATH1\r', b'OK\r\r>') # Headers ON + + send_compare(s, b'ATSP6\r', b"OK\r\r>") # Set Proto ISO 15765-4 (CAN 11/500) + send_compare(s, b'0100\r', b"7E8064100FFFFFFFE\r\r>") + + send_compare(s, b'ATSP8\r', b"OK\r\r>") # Set Proto ISO 15765-4 (CAN 11/250) + send_compare(s, b'0100\r', b"CAN ERROR\r\r>") + + sim.change_can_baud(250) + + send_compare(s, b'ATSP6\r', b"OK\r\r>") # Set Proto ISO 15765-4 (CAN 11/500) + send_compare(s, b'0100\r', b"CAN ERROR\r\r>") + + send_compare(s, b'ATSP8\r', b"OK\r\r>") # Set Proto ISO 15765-4 (CAN 11/250) + send_compare(s, b'0100\r', b"7E8064100FFFFFFFE\r\r>") + finally: + sim.stop() + sim.join() + s.close() + +def test_elm_panda_safety_mode_ISO15765(): + s = elm_connect() + serial = os.getenv("CANSIMSERIAL") if os.getenv("CANSIMSERIAL") else None + p_car = Panda(serial) # Configure this so the messages will send + p_car.set_can_speed_kbps(0, 500) + p_car.set_safety_mode(Panda.SAFETY_ALLOUTPUT) + + p_elm = Panda("WIFI") + p_elm.set_safety_mode(0xE327); + + #sim = elm_car_simulator.ELMCarSimulator(serial, lin=False) + #sim.start() + + def did_send(p, addr, dat, bus): + p.can_send(addr, dat, bus) + t = time.time() + while time.time()-t < 0.5: + msg = p.can_recv() + for addrin, _, datin, busin in msg: + if (0x80 | bus) == busin and addr == addrin and datin == dat: + return True + time.sleep(0.01) + return False + + try: + sync_reset(s) # Reset elm (which requests the ELM327 safety mode) + + #29 bit + assert not did_send(p_elm, 0x18DB33F1, b'\x02\x01\x00\x00\x00\x00\x00\x00', 1) #wrong canid + assert not did_send(p_elm, 0x18DB33F1, b'\x02\x01\x00', 0) #wrong length + assert not did_send(p_elm, 0x10000000, b'\x02\x01\x00\x00\x00\x00\x00\x00', 0) #bad addr + assert not did_send(p_elm, 0x18DAF133, b'\x02\x01\x00\x00\x00\x00\x00\x00', 0) #bad addr (phy addr) + assert not did_send(p_elm, 0x18DAF000, b'\x02\x01\x00\x00\x00\x00\x00\x00', 0) #bad addr + assert not did_send(p_elm, 0x18DAF1F3, b'\x02\x01\x00\x00\x00\x00\x00\x00', 0) #bad addr! (phys rsp to elm) + + assert did_send(p_elm, 0x18DB33F1, b'\x02\x01\x00\x00\x00\x00\x00\x00', 0) #good! (obd func req) + assert did_send(p_elm, 0x18DA10F1, b'\x02\x01\x00\x00\x00\x00\x00\x00', 0) #good! (phys response) + + #11 bit + assert not did_send(p_elm, 0X7DF, b'\x02\x01\x00\x00\x00\x00\x00\x00', 1) #wrong canid + assert not did_send(p_elm, 0X7DF, b'\x02\x01\x00', 0) #wrong length + assert not did_send(p_elm, 0xAA, b'\x02\x01\x00\x00\x00\x00\x00\x00', 0) #bad addr + assert not did_send(p_elm, 0x7DA, b'\x02\x01\x00\x00\x00\x00\x00\x00', 0) #bad addr (phy addr) + assert not did_send(p_elm, 0x7E8, b'\x02\x01\x00\x00\x00\x00\x00\x00', 0) #bad addr (sending 'response') + + assert did_send(p_elm, 0x7DF, b'\x02\x01\x00\x00\x00\x00\x00\x00', 0) #good! (obd func req) + assert did_send(p_elm, 0x7E1, b'\x02\x01\x00\x00\x00\x00\x00\x00', 0) #good! (phys response) + + finally: + s.close() diff --git a/tests/automated/helpers.py b/tests/automated/helpers.py new file mode 100644 index 0000000000..daa676490d --- /dev/null +++ b/tests/automated/helpers.py @@ -0,0 +1,75 @@ +import os +import sys +import time +import random +import subprocess +from panda import Panda +from nose.tools import timed, assert_equal, assert_less, assert_greater + +def connect_wo_esp(): + # connect to the panda + p = Panda() + + # power down the ESP + p.set_esp_power(False) + + # clear old junk + while len(p.can_recv()) > 0: + pass + + return p + +def connect_wifi(): + p = Panda() + dongle_id, pw = p.get_serial() + assert(dongle_id.isalnum()) + _connect_wifi(dongle_id, pw) + +def _connect_wifi(dongle_id, pw): + ssid = str("panda-" + dongle_id) + + print("WIFI: connecting to %s" % ssid) + + if sys.platform == "darwin": + os.system("networksetup -setairportnetwork en0 %s %s" % (ssid, pw)) + else: + cnt = 0 + MAX_TRIES = 10 + while cnt < MAX_TRIES: + print "WIFI: scanning %d" % cnt + os.system("nmcli device wifi rescan") + wifi_scan = filter(lambda x: ssid in x, subprocess.check_output(["nmcli","dev", "wifi", "list"]).split("\n")) + if len(wifi_scan) != 0: + break + time.sleep(0.1) + # MAX_TRIES tries, ~10 seconds max + cnt += 1 + assert cnt < MAX_TRIES + os.system("nmcli d wifi connect %s password %s" % (ssid, pw)) + + # TODO: confirm that it's connected to the right panda + +def time_many_sends(p, bus, precv=None, msg_count=100, msg_id=None): + if precv == None: + precv = p + if msg_id == None: + msg_id = random.randint(0x100, 0x200) + + st = time.time() + p.can_send_many([(msg_id, 0, "\xaa"*8, bus)]*msg_count) + r = [] + + while len(r) < (msg_count*2) and (time.time() - st) < 3: + r.extend(precv.can_recv()) + + sent_echo = filter(lambda x: x[3] == 0x80 | bus and x[0] == msg_id, r) + loopback_resp = filter(lambda x: x[3] == bus and x[0] == msg_id, r) + + assert_equal(len(sent_echo), msg_count) + assert_equal(len(loopback_resp), msg_count) + + et = (time.time()-st)*1000.0 + comp_kbps = (1+11+1+1+1+4+8*8+15+1+1+1+7)*msg_count / et + + return comp_kbps + diff --git a/tests/can_printer.py b/tests/can_printer.py new file mode 100755 index 0000000000..a74a548109 --- /dev/null +++ b/tests/can_printer.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python +from __future__ import print_function +import os +import sys +import time +from collections import defaultdict + +sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..")) +from panda import Panda + +# fake +def sec_since_boot(): + return time.time() + +def can_printer(): + p = Panda() + + start = sec_since_boot() + lp = sec_since_boot() + msgs = defaultdict(list) + canbus = int(os.getenv("CAN", 0)) + while True: + can_recv = p.can_recv() + for address, _, dat, src in can_recv: + if src == canbus: + msgs[address].append(dat) + + if sec_since_boot() - lp > 0.1: + dd = chr(27) + "[2J" + dd += "%5.2f\n" % (sec_since_boot() - start) + for k,v in sorted(zip(msgs.keys(), map(lambda x: x[-1].encode("hex"), msgs.values()))): + dd += "%s(%6d) %s\n" % ("%04X(%4d)" % (k,k),len(msgs[k]), v) + print(dd) + lp = sec_since_boot() + +if __name__ == "__main__": + can_printer() diff --git a/tests/debug_console.py b/tests/debug_console.py new file mode 100755 index 0000000000..f4db77f091 --- /dev/null +++ b/tests/debug_console.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python +from __future__ import print_function +import os +import sys +import time +import select + +sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..")) +from panda import Panda + +setcolor = ["\033[1;32;40m", "\033[1;31;40m"] +unsetcolor = "\033[00m" + +if __name__ == "__main__": + port_number = int(os.getenv("PORT", 0)) + claim = os.getenv("CLAIM") is not None + + serials = Panda.list() + if os.getenv("SERIAL"): + serials = filter(lambda x: x==os.getenv("SERIAL"), serials) + + pandas = list(map(lambda x: Panda(x, claim=claim), serials)) + + if os.getenv("BAUD") is not None: + for panda in pandas: + panda.set_uart_baud(port_number, int(os.getenv("BAUD"))) + + while True: + for i, panda in enumerate(pandas): + while True: + ret = panda.serial_read(port_number) + if len(ret) > 0: + sys.stdout.write(setcolor[i] + str(ret) + unsetcolor) + sys.stdout.flush() + else: + break + if select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], []): + ln = sys.stdin.readline() + if claim: + panda.serial_write(port_number, ln) + time.sleep(0.01) diff --git a/tests/disable_esp.py b/tests/disable_esp.py new file mode 100755 index 0000000000..abebd9c17b --- /dev/null +++ b/tests/disable_esp.py @@ -0,0 +1,4 @@ +#!/usr/bin/env python +from panda import Panda +Panda().set_esp_power(False) + diff --git a/tests/elm_car_simulator.py b/tests/elm_car_simulator.py new file mode 100755 index 0000000000..f931e66ff4 --- /dev/null +++ b/tests/elm_car_simulator.py @@ -0,0 +1,325 @@ +#!/usr/bin/env python +"""Used to Reverse/Test ELM protocol auto detect and OBD message response without a car.""" +from __future__ import print_function +import sys +import os +import struct +import binascii +import time +import threading +from collections import deque + +sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..")) +from panda import Panda + +def lin_checksum(dat): + return sum(dat) % 0x100 + +class ELMCarSimulator(): + def __init__(self, sn, silent=False, can_kbaud=500, + can=True, can11b=True, can29b=True, + lin=True): + self.__p = Panda(sn if sn else Panda.list()[0]) + self.__on = True + self.__stop = False + self.__silent = silent + + self.__lin_timer = None + self.__lin_active = False + self.__lin_enable = lin + self.__lin_monitor_thread = threading.Thread(target=self.__lin_monitor) + + self.__can_multipart_data = None + self.__can_kbaud = can_kbaud + self.__can_extra_noise_msgs = deque() + self.__can_enable = can + self.__can11b = can11b + self.__can29b = can29b + self.__can_monitor_thread = threading.Thread(target=self.__can_monitor) + + @property + def panda(self): + return self.__p + + def stop(self): + if self.__lin_timer: + self.__lin_timer.cancel() + self.__lin_timeout_handler() + + self.__stop = True + + def join(self): + if self.__lin_monitor_thread.is_alive(): + self.__lin_monitor_thread.join() + if self.__can_monitor_thread.is_alive(): + self.__can_monitor_thread.join() + if self.__p: + print("closing handle") + self.__p.close() + + def set_enable(self, on): + self.__on = on + + def start(self): + self.panda.set_safety_mode(Panda.SAFETY_ALLOUTPUT) + if self.__lin_enable: + self.__lin_monitor_thread.start() + if self.__can_enable: + self.__can_monitor_thread.start() + + ######################### + # LIN related functions # + ######################### + + def __lin_monitor(self): + print("STARTING LIN THREAD") + self.panda.set_uart_baud(2, 10400) + self.panda.kline_drain() # Toss whatever was already there + + lin_buff = bytearray() + + while not self.__stop: + lin_msg = self.panda.serial_read(2) + if not lin_msg: + continue + + lin_buff += lin_msg + #print(" ** Buff", lin_buff) + if lin_buff.endswith(b'\x00\xc1\x33\xf1\x81\x66'): # Leading 0 is wakeup + lin_buff = bytearray() + self.__lin_active = True + print("GOT LIN (KWP FAST) WAKEUP SIGNAL") + self._lin_send(0x10, b'\xC1\x8F\xE9') + self.__reset_lin_timeout() + continue + if self.__lin_active: + msglen = lin_buff[0] & 0x7 + if lin_buff[0] & 0xF8 not in (0x80, 0xC0): + print("Invalid bytes at start of message") + print(" BUFF", lin_buff) + continue + if len(lin_buff) < msglen + 4: continue + if lin_checksum(lin_buff[:-1]) != lin_buff[-1]: continue + self.__lin_process_msg(lin_buff[0] & 0xF8, #Priority + lin_buff[1], lin_buff[2], lin_buff[3:-1]) + lin_buff = bytearray() + + def _lin_send(self, to_addr, msg): + if not self.__silent: + print(" LIN Reply (%x)" % to_addr, binascii.hexlify(msg)) + + PHYS_ADDR = 0x80 + FUNC_ADDR = 0xC0 + RECV = 0xF1 + SEND = 0x33 # Car OBD Functional Address + headers = struct.pack("BBB", PHYS_ADDR | len(msg), RECV, to_addr) + if not self.__silent: + print(" Sending LIN", binascii.hexlify(headers+msg), + hex(sum(bytearray(headers+msg))%0x100)) + self.panda.kline_send(headers + msg) + + def __reset_lin_timeout(self): + if self.__lin_timer: + self.__lin_timer.cancel() + self.__lin_timer = threading.Timer(5, self.__lin_timeout_handler) + self.__lin_timer.start() + + def __lin_timeout_handler(self): + print("LIN TIMEOUT") + self.__lin_timer = None + self.__lin_active = False + + @property + def lin_active(self): + return self.__lin_active + + def __lin_process_msg(self, priority, toaddr, fromaddr, data): + self.__reset_lin_timeout() + + if not self.__silent and data != b'\x3E': + print("LIN MSG", "Addr:", hex(toaddr), "obdLen:", len(data), + binascii.hexlify(data)) + + outmsg = None + #if data == b'\x3E': + # print("KEEP ALIVE") + #el + if len(data) > 1: + outmsg = self._process_obd(data[0], data[1]) + + if outmsg: + obd_header = struct.pack("BB", 0x40 | data[0], data[1]) + if len(outmsg) <= 5: + self._lin_send(0x10, obd_header + outmsg) + else: + first_msg_len = min(4, len(outmsg)%4) or 4 + self._lin_send(0x10, obd_header + b'\x01' + + b'\x00'*(4-first_msg_len) + + outmsg[:first_msg_len]) + + for num, i in enumerate(range(first_msg_len, len(outmsg), 4)): + self._lin_send(0x10, obd_header + + struct.pack('B', (num+2)%0x100) + outmsg[i:i+4]) + + ######################### + # CAN related functions # + ######################### + + def __can_monitor(self): + print("STARTING CAN THREAD") + self.panda.set_can_speed_kbps(0, self.__can_kbaud) + self.panda.can_recv() # Toss whatever was already there + + while not self.__stop: + for address, ts, data, src in self.panda.can_recv(): + if self.__on and src is 0 and len(data) == 8 and data[0] >= 2: + if not self.__silent: + print("Processing CAN message", src, hex(address), binascii.hexlify(data)) + self.__can_process_msg(data[1], data[2], address, ts, data, src) + elif not self.__silent: + print("Rejecting CAN message", src, hex(address), binascii.hexlify(data)) + + def can_mode_11b(self): + self.__can11b = True + self.__can29b = False + + def can_mode_29b(self): + self.__can11b = False + self.__can29b = True + + def can_mode_11b_29b(self): + self.__can11b = True + self.__can29b = True + + def change_can_baud(self, kbaud): + self.__can_kbaud = kbaud + self.panda.set_can_speed_kbps(0, self.__can_kbaud) + + def can_add_extra_noise(self, noise_msg, addr=None): + self.__can_extra_noise_msgs.append((addr, noise_msg)) + + def _can_send(self, addr, msg): + if not self.__silent: + print(" CAN Reply (%x)" % addr, binascii.hexlify(msg)) + self.panda.can_send(addr, msg + b'\x00'*(8-len(msg)), 0) + if self.__can_extra_noise_msgs: + noise = self.__can_extra_noise_msgs.popleft() + self.panda.can_send(noise[0] if noise[0] is not None else addr, + noise[1] + b'\x00'*(8-len(noise[1])), 0) + + def _can_addr_matches(self, addr): + if self.__can11b and (addr == 0x7DF or (addr & 0x7F8) == 0x7E0): + return True + if self.__can29b and (addr == 0x18db33f1 or (addr & 0x1FFF00FF) == 0x18da00f1): + return True + return False + + def __can_process_msg(self, mode, pid, address, ts, data, src): + if not self.__silent: + print("CAN MSG", binascii.hexlify(data[1:1+data[0]]), + "Addr:", hex(address), "Mode:", hex(mode)[2:].zfill(2), + "PID:", hex(pid)[2:].zfill(2), "canLen:", len(data), + binascii.hexlify(data)) + + if self._can_addr_matches(address) and len(data) == 8: + outmsg = None + if data[:3] == b'\x30\x00\x00' and len(self.__can_multipart_data): + if not self.__silent: + print("Request for more data"); + outaddr = 0x7E8 if address == 0x7DF or address == 0x7E0 else 0x18DAF110 + msgnum = 1 + while(self.__can_multipart_data): + datalen = min(7, len(self.__can_multipart_data)) + msgpiece = struct.pack("B", 0x20 | msgnum) + self.__can_multipart_data[:datalen] + self._can_send(outaddr, msgpiece) + self.__can_multipart_data = self.__can_multipart_data[7:] + msgnum = (msgnum+1)%0x10 + time.sleep(0.01) + + else: + outmsg = self._process_obd(mode, pid) + + if outmsg: + outaddr = 0x7E8 if address == 0x7DF or address == 0x7E0 else 0x18DAF110 + + if len(outmsg) <= 5: + self._can_send(outaddr, + struct.pack("BBB", len(outmsg)+2, 0x40|data[1], pid) + outmsg) + else: + first_msg_len = min(3, len(outmsg)%7) + payload_len = len(outmsg)+3 + msgpiece = struct.pack("BBBBB", 0x10 | ((payload_len>>8)&0xF), + payload_len&0xFF, + 0x40|data[1], pid, 1) + outmsg[:first_msg_len] + self._can_send(outaddr, msgpiece) + self.__can_multipart_data = outmsg[first_msg_len:] + + ######################### + # General OBD functions # + ######################### + + def _process_obd(self, mode, pid): + if mode == 0x01: # Mode: Show current data + if pid == 0x00: #List supported things + return b"\xff\xff\xff\xfe"#b"\xBE\x1F\xB8\x10" #Bitfield, random features + elif pid == 0x01: # Monitor Status since DTC cleared + return b"\x00\x00\x00\x00" #Bitfield, random features + elif pid == 0x04: # Calculated engine load + return b"\x2f" + elif pid == 0x05: # Engine coolant temperature + return b"\x3c" + elif pid == 0x0B: # Intake manifold absolute pressure + return b"\x90" + elif pid == 0x0C: # Engine RPM + return b"\x1A\xF8" + elif pid == 0x0D: # Vehicle Speed + return b"\x53" + elif pid == 0x10: # MAF air flow rate + return b"\x01\xA0" + elif pid == 0x11: # Throttle Position + return b"\x90" + elif pid == 0x33: # Absolute Barometric Pressure + return b"\x90" + elif mode == 0x09: # Mode: Request vehicle information + 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))) + 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) + if pid == 0xFE: # test very long multi message + parts = (b'\xAA\xAA\xAA' + struct.pack(">I", num) for num in range(584)) + 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))) + #return b"\xAA"*100#(0xFFF-3) + + +if __name__ == "__main__": + serial = os.getenv("SERIAL") if os.getenv("SERIAL") else None + kbaud = int(os.getenv("CANKBAUD")) if os.getenv("CANKBAUD") else 500 + bitwidth = int(os.getenv("CANBITWIDTH")) if os.getenv("CANBITWIDTH") else 0 + canenable = bool(int(os.getenv("CANENABLE"))) if os.getenv("CANENABLE") else True + linenable = bool(int(os.getenv("LINENABLE"))) if os.getenv("LINENABLE") else True + sim = ELMCarSimulator(serial, can_kbaud=kbaud, can=canenable, lin=linenable) + if(bitwidth == 0): + sim.can_mode_11b_29b() + if(bitwidth == 11): + sim.can_mode_11b() + if(bitwidth == 29): + sim.can_mode_29b() + + import signal + def signal_handler(signal, frame): + print('\nShutting down simulator') + sim.stop() + sim.join() + sys.exit(0) + + signal.signal(signal.SIGINT, signal_handler) + + sim.start() + + signal.pause() diff --git a/tests/elm_throughput.py b/tests/elm_throughput.py new file mode 100755 index 0000000000..3962572889 --- /dev/null +++ b/tests/elm_throughput.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python +from __future__ import print_function +import socket +import threading +import select + +class Reader(threading.Thread): + def __init__(self, s, *args, **kwargs): + super(Reader, self).__init__(*args, **kwargs) + self._s = s + self.__stop = False + + def stop(self): + self.__stop = True + + def run(self): + while not self.__stop: + s.recv(1000) + +def read_or_fail(s): + ready = select.select([s], [], [], 4) + assert ready[0], "Socket did not receive data within the timeout duration." + return s.recv(1000) + +def send_msg(s, msg): + s.send(msg) + res = b'' + while not res.endswith(">"): + res += read_or_fail(s) + return res + +if __name__ == "__main__": + s = socket.create_connection(("192.168.0.10", 35000)) + #t1 = Reader(s) + #t1.start() + send_msg(s, b"ATZ\r") + send_msg(s, b"ATL1\r") + print(send_msg(s, b"ATE0\r")) + print(send_msg(s, b"ATS0\r")) + print(send_msg(s, b"ATSP6\r")) + + print("\nLOOP\n") + + while True: + print(send_msg(s, b"0100\r")) + print(send_msg(s, b"010d\r")) diff --git a/tests/flashing_loop.sh b/tests/flashing_loop.sh new file mode 100755 index 0000000000..2eaf850c83 --- /dev/null +++ b/tests/flashing_loop.sh @@ -0,0 +1,9 @@ +#!/bin/bash +cd ../board +make clean + +while true; do + make ota + sleep 10 +done + diff --git a/tests/get_version.py b/tests/get_version.py new file mode 100755 index 0000000000..0cd7795fdc --- /dev/null +++ b/tests/get_version.py @@ -0,0 +1,9 @@ +#!/usr/bin/env python +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())) + + diff --git a/tests/loopback_test.py b/tests/loopback_test.py new file mode 100755 index 0000000000..a871295ad6 --- /dev/null +++ b/tests/loopback_test.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python +from __future__ import print_function +import os +import sys +import time +import random +import argparse + +from hexdump import hexdump +from itertools import permutations + +sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..")) +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) == 0: + print("NO PANDAS") + assert False + + if len(pandas) == 1: + # if we only have one on USB, assume the other is on wifi + pandas.append("WIFI") + run_test_w_pandas(pandas, sleep_duration) + +def run_test_w_pandas(pandas, sleep_duration): + h = list(map(lambda x: Panda(x), pandas)) + print("H", h) + + for hh in h: + hh.set_safety_mode(Panda.SAFETY_ALLOUTPUT) + + # test both directions + for ho in permutations(range(len(h)), r=2): + print("***************** TESTING", ho) + + panda0, panda1 = h[ho[0]], h[ho[1]] + + if(panda0._serial == "WIFI"): + print(" *** Can not send can data over wifi panda. Skipping! ***") + continue + + # **** test health packet **** + print("health", ho[0], h[ho[0]].health()) + + # **** test K/L line loopback **** + for bus in [2,3]: + # flush the output + h[ho[1]].kline_drain(bus=bus) + + # send the characters + st = get_test_string() + st = b"\xaa"+chr(len(st)+3).encode()+st + h[ho[0]].kline_send(st, bus=bus, checksum=False) + + # check for receive + ret = h[ho[1]].kline_drain(bus=bus) + + print("ST Data:") + hexdump(st) + print("RET Data:") + hexdump(ret) + assert st == ret + print("K/L pass", bus, ho, "\n") + time.sleep(sleep_duration) + + # **** test can line loopback **** + for bus, gmlan 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) + + if gmlan is True: + panda0.set_gmlan(bus) + panda1.set_gmlan(bus) + bus = 3 + + # send the characters + at = random.randint(1, 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 i in range(args.n): + run_test(sleep_duration=args.sleep) diff --git a/tests/read_st_flash.sh b/tests/read_st_flash.sh new file mode 100755 index 0000000000..ffcfd7bbfe --- /dev/null +++ b/tests/read_st_flash.sh @@ -0,0 +1,6 @@ +#!/bin/bash +rm -f /tmp/dump_bootstub +rm -f /tmp/dump_main +dfu-util -a 0 -s 0x08000000 -U /tmp/dump_bootstub +dfu-util -a 0 -s 0x08004000 -U /tmp/dump_main + diff --git a/tests/standalone_test.py b/tests/standalone_test.py new file mode 100755 index 0000000000..76df0235bc --- /dev/null +++ b/tests/standalone_test.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python +import os +import sys +import struct +import time + +sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..")) +from panda import Panda + +if __name__ == "__main__": + if os.getenv("WIFI") is not None: + p = Panda("WIFI") + else: + p = Panda() + print(p.get_serial()) + print(p.health()) + + t1 = time.time() + for i in range(100): + p.get_serial() + t2 = time.time() + print("100 requests took %.2f ms" % ((t2-t1)*1000)) + + p.set_controls_allowed(True) + + a = 0 + while True: + # flood + msg = b"\xaa"*4 + struct.pack("I", a) + p.can_send(0xaa, msg, 0) + p.can_send(0xaa, msg, 1) + p.can_send(0xaa, msg, 4) + time.sleep(0.01) + + dat = p.can_recv() + if len(dat) > 0: + print(dat) + a += 1 diff --git a/tests/throughput_test.py b/tests/throughput_test.py new file mode 100755 index 0000000000..5812ce42c2 --- /dev/null +++ b/tests/throughput_test.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python +from __future__ import print_function +import os +import sys +import struct +import time +from tqdm import tqdm + +sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..")) +from panda import Panda, PandaWifiStreaming + +# test throughput between USB and wifi + +if __name__ == "__main__": + print(Panda.list()) + p_out = Panda("108018800f51363038363036") + print(p_out.get_serial()) + #p_in = Panda("02001b000f51363038363036") + p_in = Panda("WIFI") + print(p_in.get_serial()) + + p_in = PandaWifiStreaming() + + #while True: + # p_in.can_recv() + #sys.exit(0) + + p_out.set_controls_allowed(True) + + set_out, set_in = set(), set() + + # drain + p_out.can_recv() + p_in.can_recv() + + BATCH_SIZE = 16 + for a in tqdm(range(0, 10000, BATCH_SIZE)): + for b in range(0, BATCH_SIZE): + msg = b"\xaa"*4 + struct.pack("I", a+b) + if a%1 == 0: + p_out.can_send(0xaa, msg, 0) + + dat_out, dat_in = p_out.can_recv(), p_in.can_recv() + if len(dat_in) != 0: + print(len(dat_in)) + + num_out = [struct.unpack("I", i[4:])[0] for _, _, i, _ in dat_out] + num_in = [struct.unpack("I", i[4:])[0] for _, _, i, _ in dat_in] + + set_in.update(num_in) + set_out.update(num_out) + + # swag + print("waiting for packets") + time.sleep(2.0) + dat_in = p_in.can_recv() + print(len(dat_in)) + num_in = [struct.unpack("I", i[4:])[0] for _, _, i, _ in dat_in] + set_in.update(num_in) + + if len(set_out - set_in): + print("MISSING %d" % len(set_out - set_in)) + if len(set_out - set_in) < 256: + print(map(hex, sorted(list(set_out - set_in))))