Compare commits

..

4 Commits
0.8.7 ... 0.8.8

Author SHA1 Message Date
Kumar
9ba9cc0cd3 Merge pull request #103 from wer5lcy/0.8.8
Re-tune DP Accel Profile
2021-09-22 07:53:51 -07:00
wer5lcy
7de523b8a2 Re-tune Accel Profile
Acceleration profile is tuned to fit the 98HP 8ZR-FXE engine. 
- The normal mode uses the whole ECO range, so that the engine won't roar.
- The eco mode uses 70% of the ECO range, providing best fuel effiency.
- The sport mode uses the full engine power. 
Acceleration profile is not always working, my car could still accelerate 1.8m/s^2 on 30-50km/h through the set value is 1.4m/s^2.

Deceleration profile is changed such that the car could stop at static vehicles before traffic lights. 
- In previous version, using both accel profile "ECO" and following profile "1.2s" could cause your car unable to stop.
- The default max deceleration is 1.2m/s^2 in stock openpilot, any value in the custom profile should be no less than 1.2 unless necessary.
2021-09-22 16:21:34 +08:00
Kumar
1412691630 dragonpilot mod for 0.8.8-2 2021-09-11 06:43:38 -07:00
Vehicle Researcher
baffaeee93 openpilot v0.8.8 release 2021-08-22 22:13:11 -07:00
259 changed files with 66574 additions and 2375 deletions

2
.gitignore vendored
View File

@@ -41,8 +41,6 @@ selfdrive/boardd/boardd
selfdrive/logcatd/logcatd
selfdrive/mapd/default_speeds_by_region.json
selfdrive/proclogd/proclogd
selfdrive/test/longitudinal_maneuvers/out
selfdrive/visiond/visiond
selfdrive/loggerd/loggerd

View File

@@ -1,3 +1,22 @@
dragonpilot 0.8.8-2
========================
* ADDED: newer faster and modularized mapd and slow down for curve. (Thanks to @move-fast)
* ADDED: Street name on the bottom bar.
* ADDED: Now supports 1+3t / C2 / C3 / Jetson Xavier NX.
* ADDED: Smoother tune for PRIUS_TSS2.
* Bug fixes.
dragonpilot 0.8.8-1
========================
** BETA TESTING ONLY **
* Based on openpilot 0.8.8 devel.
* FIXED: dashcam issue.
* FIXED: some VW vehicles issue. (Thanks to @yayism)
* FIXED: white panda + j533 acc issue. (Thanks to @lirudy)
* ADDED: Auto fake black panda.
* ADDED: 2018 chinese camry hybrid fingerprint (Thanks to @stingshen)
* WIP: mapd.
dragonpilot 0.8.7-4
========================
* 2017 JADE w/ Added Comma Pedal Support. (Thanks to @lijunhao731)
@@ -18,7 +37,7 @@ dragonpilot 0.8.7-2
* Changed gpx logs to OSM compatible format.
* HONDA: Added BSM support for CRV-Hybrid.
* HONDA: Added toggle to force displaying km/h in HUD.
* TOYOTA: Add new Toggles under DP - Cars to enable/disable Following Modes / Accel Modes with physical button feature.
* TOYOTA: Add new Toggles under DP - Cars to enable/disable Following Modes / Accel Modes with physical button feature.
dragonpilot 0.8.7-1
========================
@@ -70,7 +89,7 @@ dragonpilot 0.8.5-1
========================
* Based on openpilot 0.8.5 devel.
* 基於 openpilot 0.8.5 devel.
* Support 1+3t / C2 / Jetson Xavier NX.
* Support 1+3t / C2 / Jetson Xavier NX.
* 支持 1+3t / C2 / Jetson Xavier NX.
* No White/Grey Panda Support.
* 不支持白灰熊.
@@ -137,7 +156,7 @@ dragonpilot 0.7.10.1
* 加入 Dynamic gas Lite。(感謝 @toyboxZ 提供)
* Added Dynamic Gas Lite. (Thanks to @toyboxZ)
* 加入來自 afa 的 Honda inspire, accord, crv SnG 優化。(感謝 @menwenliang 提供)
* Added Honda inspire, accord, crv SnG optimisation from afa fork. (Thanks to @menwenliang)
* Added Honda inspire, accord, crv SnG optimisation from afa fork. (Thanks to @menwenliang)
* 加入 dp_toyota_lowest_cruise_override_vego。(感謝 @toyboxZ 提供)
* Added dp_toyota_lowest_cruise_override_vego. (Thanks to @toyboxZ)
@@ -199,7 +218,7 @@ dragonpilot 0.7.8.0
* 將警示訊息更改為類似於概念 UI 的設計。
* Alert messages changed to concept UI alike design.
* 當 manager 出現錯誤後,按 Exit 按鈕會執行 reset_update 腳本。
* Added ability to execute reset_update.sh when press "Exit" button once manager returned errors.
* Added ability to execute reset_update.sh when press "Exit" button once manager returned errors.
dragonpilot 0.7.7.3
========================
@@ -238,7 +257,7 @@ dragonpilot 0.7.7.1
* 加入回調校介面。(感謝 @Kent)
* Re-added Dev UI. (Thanks to @Kent)
* 加入 "dp_lqr" 設定來強制使用 RAV4 的 lqr 調校。(感謝 @eisenheim)
* Added "dp_lqr" setting to force enable lqr tuning from RAV4. (Thanks to eisenheim)
* Added "dp_lqr" setting to force enable lqr tuning from RAV4. (Thanks to eisenheim)
dragonpilot 0.7.7.0
========================
@@ -291,7 +310,7 @@ dragonpilot 0.7.5.3
* C2 支援自動關機「DragonAutoShutdownAt」參數。(感謝 @cgw1968 建議)
* C2 to support auto shutdown "DragonAutoShutDownAt" param. (Thanks to @cgw1968)
* 修正出現「pedalPressed」的錯誤。(感謝 @Wei 回報)
* Fixed issue showing "pedalPressed" error. (Thanks to @Wei)
* Fixed issue showing "pedalPressed" error. (Thanks to @Wei)
* 將剎車狀熊顯示於 dp 資訊欄。
* Added brake indicator to dp infobar.
* 修正「溫度監控」燈示。
@@ -299,7 +318,7 @@ dragonpilot 0.7.5.3
* 加入「方向燈取消控制」延遲控制設。(感謝 @wabes 建議)
* Added delay config to "Disable Lat Control on Blinker". (Thanks to @wabes)
* 加入巴西版 2020 Corolla Hybrid 指紋v2。(感謝 @berno22 提供)
* Added Brazil 2020 Corolla Hybrid FPv2. (Thanks to @berno22)
* Added Brazil 2020 Corolla Hybrid FPv2. (Thanks to @berno22)
dragonpilot 0.7.5.2
========================
@@ -314,7 +333,7 @@ dragonpilot 0.7.5.2
* 修正「位智模式」無法顯示警示的問題。(感謝 @axandres 回報)
* Fixed alert issue in waze mode. (Thanks to @axandres)
* 修正無法顯示更新中圖示的問題。
* Fixed unable to display "UPDATING" icon issue.
* Fixed unable to display "UPDATING" icon issue.
* 加入「允許多次自動換道」功能。(感謝 @阿濤 建議)
* Added "Allow Continuous Auto Lane Change" Toggle. (Thanks to @阿濤)
* 修正開機後設定頁面有時會錯誤的問題。(感謝 @salmankhan@Wei 回報)
@@ -352,14 +371,14 @@ dragonpilot 0.7.5.0
* 簡/繁中文版和 i18n 整合成為單一版本。
* Merged zhs/zht/i18n versions into one.
* 新增大陸版 CAMRY HYBRID 指紋v2。(感謝 @杜子腾)
* Added China Camery Hybrid FPv2. (Thanks to @杜子腾)
* Added China Camery Hybrid FPv2. (Thanks to @杜子腾)
* 新增台灣版 Altis HYBRID 指紋v1。(感謝 @Fish)
* Added Taiwan Altis Hybrid FPv1. (Thanks to @Fish)
* 新增行駛時關閉畫面功能。
* Added Screen off while driving feature.
* 新增倒車時關閉畫面功能。
* Added Screen off while reversing feature.
* 新增駕駛介面加入「加速模式」切換鈕。
* 新增駕駛介面加入「加速模式」切換鈕。
* Added acceleration profile toggle onto driving UI.
* 新增自定車型功能,取代指紋暫存功能。
* Replaced fingerprint cache with custom car model selector.
@@ -378,7 +397,7 @@ dragonpilot 0.7.5.0
* 新增 CAMERY HIBRID 指紋。(感謝 @杜子腾)
* 新增行駛時關閉畫面功能。
* 新增倒車時關閉畫面功能。
* 新增駕駛介面加入「加速模式」切換鈕。
* 新增駕駛介面加入「加速模式」切換鈕。
* 新增自定義車型。
2020-04-16
@@ -487,7 +506,7 @@ dragonpilot 0.7.5.0
2020-01-19
========================
* [DEVEL] 更新至最新的 commaai:devel (0.7.1)。
* [DEVEL] 調整 appd 和 ALC 邏輯。
* [DEVEL] 調整 appd 和 ALC 邏輯。
2020-01-14
========================
@@ -612,7 +631,7 @@ dragonpilot 0.7.5.0
========================
* [DEVEL] 加入彎道減速功能開關。
* [DEVEL] 強迫使用 dp 版 Panda 韌體。
* [DEVEL] 更新至最新的 commaai:devel (0.6.5)。
* [DEVEL] 更新至最新的 commaai:devel (0.6.5)。
2019-10-17
========================
@@ -636,7 +655,7 @@ dragonpilot 0.7.5.0
2019-10-11
========================
* [DEVEL] 更新至最新的 commaai:devel (0.6.5)。
* [DEVEL] 更新至最新的 commaai:devel (0.6.5)。
* [DEVEL] 加入台灣 2019 RAV4 汽油版指紋。 (感謝 Max Duan / CloudJ 提供)
2019-10-09
@@ -655,12 +674,12 @@ dragonpilot 0.7.5.0
2019-10-05
========================
* [DEVEL] 移除 curvature learner: 轉角明顯比原廠小。
* [DEVEL] 更新至最新的 commaai:devel (0.6.4)。
* [DEVEL] 更新至最新的 commaai:devel (0.6.4)。
2019-09-30
========================
* [DEVEL] 更新 curvature learner 版本至 v4。
* [DEVEL] Lexus ISH 使用更精確的 EPS Steering Angle Sensor
* [DEVEL] Lexus ISH 使用更精確的 EPS Steering Angle Sensor
2019-09-27
========================

View File

@@ -4,12 +4,14 @@ Due to the way we manage the source code, it is not possible to see all the cont
If you have contributed to DP project before and your name is not listed here, feel free to send us a PR to update this!
### TEAM
Name | github | Role
------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------
Name | github | Role
------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------
cafe | [cafe](https://github.com/coffice12) | Resource Provider
cgw1968 | [cgw1968](https://github.com/cgw1968-5779) | C2/C3 Toyota Beta Tester
kumar | [rav4kumar](https://github.com/rav4kumar) | Release Maintainer
loveloveses | [loveloveses](https://github.com/loveloveses) | Wiki Maintainer
Rick Lan | [efinilan](https://github.com/efinilan) | Release Maintainer
Stupefacient | [Stupefacient](https://github.com/Stupefacient) | C2/C3 Toyota Beta Tester
### CONTRIBUTORS
Name | github
@@ -18,7 +20,6 @@ andy741217 | [andy741217](http
Arne Schwarck | [arne182](https://github.com/arne182)
berno22 | [berno22](https://github.com/berno22)
Bobbydough | [Bobbydough](https://github.com/bobbydough)
cgw1968 | [cgw1968](https://github.com/cgw1968-5779)
Curtis Jenkins | [actuallylemoncurd](https://github.com/actuallylemoncurd)
DFyffe | [donfyffe](https://github.com/donfyffe)
dinglx | [dingliangxue](https://github.com/dingliangxue)
@@ -28,6 +29,7 @@ lijunhao731 | [lijunhao731](htt
lirudy | [lirudy](https://github.com/lirudy)
LOVEChen | [LOVEChen](https://github.com/LOVEChen)
menwenliang | [menwenliang](https://github.com/menwenliang)
move-fast | [menwenliang](https://github.com/move-fast)
Nelson Chen | [nelsonjchen](https://github.com/nelsonjchen)
rming | [Rming](https://github.com/rming)
sebastian4k | [sebastian4k](https://github.com/sebastian4k)

View File

@@ -3,7 +3,7 @@ How to install on Oneplus 3t?
1. clone dragonpilot to /data/ and make sure it's named openpilot:
(手動安裝切換至 dp)
```
cd /data/ && rm -fr openpilot ; git clone https://github.com/dragonpilot-community/dragonpilot.git openpilot -b 0.8.7
cd /data/ && rm -fr openpilot ; git clone https://github.com/dragonpilot-community/dragonpilot.git openpilot -b 0.8.8
```
2. run command:

18
HOWTO-Translate.md Normal file
View File

@@ -0,0 +1,18 @@
HOW TO Translate dragonpilot
--
If you would like to help to translate dragonpilot into your native language, please:
1. Contact dragonpilot team to generate language files for translation.
2. Start translation, there will be 2 files: (locale = your language code)
* <openpilot>/selfdrive/assets/locales/**locale**/LC_MESSAGES/events.po
* This is for alerts messages. (e.g. on road warning messages)
* <openpilot>/selfdrive/ui/translations/**locale**.ts
* This is for UI. (e.g. settings pages)
We recommended to use a proper editor such as TextMate (mac) / notepad++ (win) / Intellij pyCharm.
3. Submit a PR for your translation.
4. dragonpilot team will review your PR and add it in the next release.

1
Jenkinsfile vendored
View File

@@ -49,7 +49,6 @@ def phone_steps(String device_type, steps) {
pipeline {
agent none
environment {
COMMA_JWT = credentials('athena-test-jwt')
TEST_DIR = "/data/openpilot"
SOURCE_DIR = "/data/openpilot_source/"
}

View File

@@ -67,8 +67,8 @@ Supported Cars
| Acura | ILX 2016-19 | AcuraWatch Plus | openpilot | 25mph<sup>1</sup> | 25mph |
| Acura | RDX 2016-18 | AcuraWatch Plus | openpilot | 25mph<sup>1</sup> | 12mph |
| Acura | RDX 2019-21 | All | Stock | 0mph | 3mph |
| Honda | Accord 2018-20 | All | Stock | 0mph | 3mph |
| Honda | Accord Hybrid 2018-20 | All | Stock | 0mph | 3mph |
| Honda | Accord 2018-21 | All | Stock | 0mph | 3mph |
| Honda | Accord Hybrid 2018-21 | All | Stock | 0mph | 3mph |
| Honda | Civic Hatchback 2017-21 | Honda Sensing | Stock | 0mph | 12mph |
| Honda | Civic Coupe 2016-18 | Honda Sensing | openpilot | 0mph | 12mph |
| Honda | Civic Coupe 2019-20 | All | Stock | 0mph | 2mph<sup>2</sup> |
@@ -110,7 +110,7 @@ Supported Cars
| Toyota | C-HR 2017-20 | All | Stock | 0mph | 0mph |
| Toyota | C-HR Hybrid 2017-19 | All | Stock | 0mph | 0mph |
| Toyota | Corolla 2017-19 | All | Stock<sup>3</sup>| 20mph<sup>1</sup> | 0mph |
| Toyota | Corolla 2020-21 | All | openpilot | 0mph | 0mph |
| Toyota | Corolla 2020-22 | All | openpilot | 0mph | 0mph |
| Toyota | Corolla Hatchback 2019-21 | All | openpilot | 0mph | 0mph |
| Toyota | Corolla Hybrid 2020-21 | All | openpilot | 0mph | 0mph |
| Toyota | Highlander 2017-19 | All | Stock<sup>3</sup>| 0mph | 0mph |
@@ -163,13 +163,16 @@ Community Maintained Cars and Features
| Hyundai | Ioniq PHEV 2020 | SCC + LKAS | Stock | 0mph | 0mph |
| Hyundai | Kona 2020 | SCC + LKAS | Stock | 0mph | 0mph |
| Hyundai | Kona EV 2019 | SCC + LKAS | Stock | 0mph | 0mph |
| Hyundai | Kona Hybrid 2020 | SCC + LKAS | Stock | 0mph | 0mph |
| Hyundai | Santa Fe 2019-20 | All | Stock | 0mph | 0mph |
| Hyundai | Sonata 2018-2019 | SCC + LKAS | Stock | 0mph | 0mph |
| Hyundai | Sonata Hybrid 2021 | All | Stock | 0mph | 0mph |
| Hyundai | Veloster 2019-20 | SCC + LKAS | Stock | 5mph | 0mph |
| Jeep | Grand Cherokee 2016-18 | Adaptive Cruise | Stock | 0mph | 9mph |
| Jeep | Grand Cherokee 2019-20 | Adaptive Cruise | Stock | 0mph | 39mph |
| Kia | Forte 2018-2021 | SCC + LKAS | Stock | 0mph | 0mph |
| Kia | Niro EV 2020 | SCC + LKAS | Stock | 0mph | 0mph |
| Kia | Niro Hybrid 2021 | SCC + LKAS | Stock | 0mph | 0mph |
| Kia | Niro PHEV 2019 | SCC + LKAS | Stock | 10mph | 32mph |
| Kia | Optima 2017 | SCC + LKAS | Stock | 0mph | 32mph |
| Kia | Optima 2019 | SCC + LKAS | Stock | 0mph | 0mph |
@@ -177,6 +180,7 @@ Community Maintained Cars and Features
| Kia | Sorento 2018-19 | SCC + LKAS | Stock | 0mph | 0mph |
| Kia | Stinger 2018 | SCC + LKAS | Stock | 0mph | 0mph |
| Kia | Ceed 2019 | SCC + LKAS | Stock | 0mph | 0mph |
| Kia | Telluride 2020 | SCC + LKAS | Stock | 0mph | 0mph |
| Nissan | Altima 2019-20 | ProPILOT | Stock | 0mph | 0mph |
| Nissan | Leaf 2018-20 | ProPILOT | Stock | 0mph | 0mph |
| Nissan | Rogue 2018-20 | ProPILOT | Stock | 0mph | 0mph |
@@ -184,7 +188,7 @@ Community Maintained Cars and Features
| SEAT | Ateca 2018 | Driver Assistance | Stock | 0mph | 0mph |
| SEAT | Leon 2014-2020 | Driver Assistance | Stock | 0mph | 0mph |
| Škoda | Kodiaq 2018 | Driver Assistance | Stock | 0mph | 0mph |
| Škoda | Octavia 2015, 2019 | Driver Assistance | Stock | 0mph | 0mph |
| Škoda | Octavia 2015, 2018-19 | Driver Assistance | Stock | 0mph | 0mph |
| Škoda | Octavia RS 2016 | Driver Assistance | Stock | 0mph | 0mph |
| Škoda | Scala 2020 | Driver Assistance | Stock | 0mph | 0mph |
| Škoda | Superb 2015-18 | Driver Assistance | Stock | 0mph | 0mph |

View File

@@ -1,3 +1,19 @@
Version 0.8.8 (2021-08-27)
========================
* New driving model with improved laneless performance
* Trained on 5000+ hours of diverse driving data from 3000+ users in 40+ countries
* Better anti-cheating methods during simulator training ensure the model hugs less when in laneless mode
* All new desire ground-truthing stack makes the model better at lane changes
* New driver monitoring model: improved performance on comma three
* NEOS 18 for comma two: update packages
* AGNOS 1.3 for comma three: fix display init at high temperatures
* Improved auto-exposure on comma three
* Honda Accord 2021 support thanks to csouers!
* Honda Accord Hybrid 2021 support thanks to csouers!
* Hyundai Kona Hybrid 2020 support thanks to haram-KONA!
* Hyundai Sonata Hybrid 2021 support thanks to Matt-Wash-Burn!
* Kia Niro Hybrid 2021 support thanks to tetious!
Version 0.8.7 (2021-07-31)
========================
* comma three support!

View File

@@ -15,7 +15,7 @@ used safely** and openpilot is provided with no warranty of fitness for any purp
openpilot is developed in good faith to be compliant with FMVSS requirements and to follow
industry standards of safety for Level 2 Driver Assistance Systems. In particular, we observe
ISO26262 guidelines, including those from [pertinent documents](https://www.nhtsa.gov/sites/nhtsa.dot.gov/files/documents/13498a_812_573_alcsystemreport.pdf)
released by NHTSA. In addition, we impose strict coding guidelines (like [MISRA C : 2012](https://www.misra.org.uk/MISRAHome/MISRAC2012/tabid/196/Default.aspx))
released by NHTSA. In addition, we impose strict coding guidelines (like [MISRA C : 2012](https://www.misra.org.uk/what-is-misra/))
on parts of openpilot that are safety relevant. We also perform software-in-the-loop,
hardware-in-the-loop and in-vehicle tests before each software release.

View File

@@ -184,6 +184,10 @@ else:
if arch != "Darwin":
ldflags += ["-Wl,--as-needed"]
# Enable swaglog include in submodules
cflags += ["-DSWAGLOG"]
cxxflags += ["-DSWAGLOG"]
# change pythonpath to this
lenv["PYTHONPATH"] = Dir("#").path
@@ -363,6 +367,17 @@ if GetOption("clazy"):
zmq = 'zmq'
Export('env', 'qt_env', 'arch', 'real_arch', 'SHARED', 'USE_WEBCAM', 'zmq', 'USE_MIPI')
SConscript(['selfdrive/common/SConscript'])
Import('_common', '_gpucommon', '_gpu_libs')
if SHARED:
common, gpucommon = abspath(common), abspath(gpucommon)
else:
common = [_common, 'json11']
gpucommon = [_gpucommon] + _gpu_libs
Export('common', 'gpucommon')
# cereal and messaging are shared with the system
SConscript(['cereal/SConscript'])
if SHARED:
@@ -373,18 +388,7 @@ else:
messaging = [File('#cereal/libmessaging.a')]
visionipc = [File('#cereal/libvisionipc.a')]
Export('cereal', 'messaging')
SConscript(['selfdrive/common/SConscript'])
Import('_common', '_gpucommon', '_gpu_libs')
if SHARED:
common, gpucommon = abspath(common), abspath(gpucommon)
else:
common = [_common, 'json11']
gpucommon = [_gpucommon] + _gpu_libs
Export('common', 'gpucommon', 'visionipc')
Export('cereal', 'messaging', 'visionipc')
# Build rednose library and ekf models

View File

@@ -1,4 +1,4 @@
Import('env', 'envCython', 'arch', 'zmq')
Import('env', 'envCython', 'arch', 'common', 'zmq')
import shutil
@@ -47,10 +47,10 @@ if arch == "aarch64":
shared_lib_shared_lib = [zmq_static, 'm', 'stdc++', "gnustl_shared", "kj", "capnp"]
env.SharedLibrary('messaging_shared', messaging_objects, LIBS=shared_lib_shared_lib)
env.Program('messaging/bridge', ['messaging/bridge.cc'], LIBS=[messaging_lib, 'zmq'])
env.Program('messaging/bridge', ['messaging/bridge.cc'], LIBS=[messaging_lib, common, 'zmq'])
Depends('messaging/bridge.cc', services_h)
envCython.Program('messaging/messaging_pyx.so', 'messaging/messaging_pyx.pyx', LIBS=envCython["LIBS"]+[messaging_lib, "zmq"])
envCython.Program('messaging/messaging_pyx.so', 'messaging/messaging_pyx.pyx', LIBS=envCython["LIBS"]+[messaging_lib, "zmq", common])
# Build Vision IPC
@@ -70,7 +70,7 @@ vipc_objects = env.SharedObject(vipc_sources)
vipc = env.Library('visionipc', vipc_objects)
libs = envCython["LIBS"]+["OpenCL", "zmq", vipc, messaging_lib]
libs = envCython["LIBS"]+["OpenCL", "zmq", vipc, messaging_lib, common]
if arch == "aarch64":
libs += ["adreno_utils"]
if arch == "Darwin":
@@ -80,5 +80,5 @@ envCython.Program('visionipc/visionipc_pyx.so', 'visionipc/visionipc_pyx.pyx', L
if GetOption('test'):
env.Program('messaging/test_runner', ['messaging/test_runner.cc', 'messaging/msgq_tests.cc'], LIBS=[messaging_lib])
env.Program('visionipc/test_runner', ['visionipc/test_runner.cc', 'visionipc/visionipc_tests.cc'], LIBS=[vipc, messaging_lib, 'zmq', 'pthread', 'OpenCL'])
env.Program('messaging/test_runner', ['messaging/test_runner.cc', 'messaging/msgq_tests.cc'], LIBS=[messaging_lib, common])
env.Program('visionipc/test_runner', ['visionipc/test_runner.cc', 'visionipc/visionipc_tests.cc'], LIBS=[vipc, messaging_lib, 'zmq', 'pthread', 'OpenCL', common])

View File

@@ -108,6 +108,7 @@ struct CarEvent @0x9b1657f34caf3ad3 {
driverCameraError @101;
wideRoadCameraError @102;
localizerMalfunction @103;
highCpuUsage @105;
driverMonitorLowAccDEPRECATED @68;
radarCanErrorDEPRECATED @15;
@@ -131,17 +132,21 @@ struct CarEvent @0x9b1657f34caf3ad3 {
startupOneplusDEPRECATED @82;
#dp
preLaneChangeLeftALC @105;
preLaneChangeRightALC @106;
manualSteeringRequired @107;
manualSteeringRequiredBlinkersOn @108;
leadCarMoving @109;
preLaneChangeLeftALC @106;
preLaneChangeRightALC @107;
manualSteeringRequired @108;
manualSteeringRequiredBlinkersOn @109;
leadCarMoving @110;
# timebomb assist
timebombWarn @110;
timebombBypassing @111;
timebombBypassed @112;
mapdAlert @113;
timebombWarn @111;
timebombBypassing @112;
timebombBypassed @113;
mapdAlert @114;
#mapd
speedLimitActive @115;
speedLimitValueChange @116;
}
}
@@ -169,6 +174,7 @@ struct CarState {
# steering wheel
steeringAngleDeg @7 :Float32;
steeringAngleOffsetDeg @37 :Float32; # Offset betweens sensors in case there multiple
steeringRateDeg @15 :Float32;
steeringTorque @8 :Float32; # TODO: standardize units
steeringTorqueEps @27 :Float32; # TODO: standardize units
@@ -208,9 +214,10 @@ struct CarState {
rightBlindspot @34 :Bool; # Is there something blocking the right lane change
# dp
lkMode @37 :Bool;
stopSteering @38 :Bool; # timebomb - stopSteering
engineRPM @39 :Float32;
lkMode @38 :Bool;
stopSteering @39 :Bool; # timebomb - stopSteering
engineRPM @40 :Float32;
cruiseActualEnabled @41 :Bool;
struct WheelSpeeds {
# optional wheel speeds
@@ -227,6 +234,8 @@ struct CarState {
speedOffset @3 :Float32;
standstill @4 :Bool;
nonAdaptive @5 :Bool;
#mapd
speedLimit @6 :Float32;
}
enum GearShifter {
@@ -320,6 +329,7 @@ struct CarControl {
# range from -1.0 - 1.0
steer @2: Float32;
steeringAngleDeg @3: Float32;
accel @4: Float32; # m/s^2
}
struct CruiseControl {

View File

@@ -14,48 +14,49 @@ struct DragonConf {
dpThermalStarted @0 :Bool;
dpThermalOverheat @1 :Bool;
dpAtl @2 :Bool;
dpDashcamd @3 :Bool;
dpAutoShutdown @4 :Bool;
dpAthenad @5 :Bool;
dpUploader @6 :Bool;
dpLateralMode @7 :UInt8;
dpSignalOffDelay @8 :Float32;
dpLcMinMph @9 :UInt8;
dpLcAutoCont @10 :Bool;
dpLcAutoMinMph @11 :UInt8;
dpLcAutoDelay @12 :Float32;
dpAllowGas @13 :Bool;
dpFollowingProfileCtrl @14 :Bool;
dpFollowingProfile @15 :UInt8;
dpAccelProfileCtrl @16 :Bool;
dpAccelProfile @17 :UInt8;
dpGearCheck @18 :Bool;
dpSpeedCheck @19 :Bool;
dpUiDisplayMode @20 :UInt8;
dpUiSpeed @21 :Bool;
dpUiEvent @22 :Bool;
dpUiMaxSpeed @23 :Bool;
dpUiFace @24 :Bool;
dpUiLane @25 :Bool;
dpUiLead @26 :Bool;
dpUiDev @27 :Bool;
dpUiDevMini @28 :Bool;
dpUiBlinker @29 :Bool;
dpUiBrightness @30 :UInt8;
dpUiVolume @31 :Int8;
dpToyotaLdw @32 :Bool;
dpToyotaSng @33 :Bool;
dpToyotaCruiseOverride @34 :Bool;
dpToyotaCruiseOverrideVego @35 :Bool;
dpToyotaCruiseOverrideAt @36 :Float32;
dpToyotaCruiseOverrideSpeed @37 :Float32;
dpVwTimebombAssist @38 :Bool;
dpIpAddr @39 :Text;
dpCameraOffset @40 :Int8;
dpPathOffset @41 :Int8;
dpLocale @42 :Text;
dpSrLearner @43 :Bool;
dpSrCustom @44 :Float32;
dpAppd @45 :Bool;
dpMapd @46 :Bool;
dpAtlOpLong @3 :Bool;
dpDashcamd @4 :Bool;
dpAutoShutdown @5 :Bool;
dpAthenad @6 :Bool;
dpUploader @7 :Bool;
dpLateralMode @8 :UInt8;
dpSignalOffDelay @9 :Float32;
dpLcMinMph @10 :UInt8;
dpLcAutoCont @11 :Bool;
dpLcAutoMinMph @12 :UInt8;
dpLcAutoDelay @13 :Float32;
dpAllowGas @14 :Bool;
dpFollowingProfileCtrl @15 :Bool;
dpFollowingProfile @16 :UInt8;
dpAccelProfileCtrl @17 :Bool;
dpAccelProfile @18 :UInt8;
dpGearCheck @19 :Bool;
dpSpeedCheck @20 :Bool;
dpUiDisplayMode @21 :UInt8;
dpUiSpeed @22 :Bool;
dpUiEvent @23 :Bool;
dpUiMaxSpeed @24 :Bool;
dpUiFace @25 :Bool;
dpUiLane @26 :Bool;
dpUiLead @27 :Bool;
dpUiSide @28 :Bool;
dpUiTop @29 :Bool;
dpUiBlinker @30 :Bool;
dpUiBrightness @31 :UInt8;
dpUiVolume @32 :Int8;
dpToyotaLdw @33 :Bool;
dpToyotaSng @34 :Bool;
dpToyotaCruiseOverride @35 :Bool;
dpToyotaCruiseOverrideVego @36 :Bool;
dpToyotaCruiseOverrideAt @37 :Float32;
dpToyotaCruiseOverrideSpeed @38 :Float32;
dpVwTimebombAssist @39 :Bool;
dpIpAddr @40 :Text;
dpCameraOffset @41 :Int8;
dpPathOffset @42 :Int8;
dpLocale @43 :Text;
dpSrLearner @44 :Bool;
dpSrCustom @45 :Float32;
dpAppd @46 :Bool;
dpMapd @47 :Bool;
}

View File

@@ -291,15 +291,11 @@ struct CanData {
}
struct DeviceState @0xa4d8b5af2aa492eb {
freeSpacePercent @7 :Float32;
memoryUsagePercent @19 :Int8;
cpuUsagePercent @20 :Int8;
gpuUsagePercent @33 :Int8;
usbOnline @12 :Bool;
networkType @22 :NetworkType;
networkInfo @31 :NetworkInfo;
offroadPowerUsageUwh @23 :UInt32;
networkStrength @24 :NetworkStrength;
offroadPowerUsageUwh @23 :UInt32;
carBatteryCapacityUwh @25 :UInt32;
fanSpeedPercentDesired @10 :UInt16;
@@ -308,6 +304,12 @@ struct DeviceState @0xa4d8b5af2aa492eb {
lastAthenaPingTime @32 :UInt64;
# system utilization
freeSpacePercent @7 :Float32;
memoryUsagePercent @19 :Int8;
gpuUsagePercent @33 :Int8;
cpuUsagePercent @34 :List(Int8); # per-core cpu usage
# power
batteryPercent @8 :Int16;
batteryStatus @9 :Text;
@@ -367,6 +369,7 @@ struct DeviceState @0xa4d8b5af2aa492eb {
gpuDEPRECATED @5 :UInt16;
batDEPRECATED @6 :UInt32;
pa0DEPRECATED @21 :UInt16;
cpuUsagePercentDEPRECATED @20 :Int8;
}
struct PandaState @0xa7649e2575e4591e {
@@ -434,7 +437,7 @@ struct PandaState @0xa7649e2575e4591e {
pedal @4;
uno @5;
dos @6;
red @7;
redPanda @7;
}
enum UsbPowerMode {
@@ -811,12 +814,31 @@ struct LongitudinalPlan @0xe00b5b3eba12876c {
speeds @33 :List(Float32);
jerks @34 :List(Float32);
#mapd
visionTurnControllerState @35 :VisionTurnControllerState;
visionTurnSpeed @36 :Float32;
speedLimitControlState @37 :SpeedLimitControlState;
speedLimit @38 :Float32;
speedLimitOffset @39 :Float32;
distToSpeedLimit @40 :Float32;
isMapSpeedLimit @41 :Bool;
distToTurn @42 :Float32;
turnSpeed @43 :Float32;
turnSpeedControlState @44 :SpeedLimitControlState;
turnSign @45 :Int16;
enum LongitudinalPlanSource {
cruise @0;
lead0 @1;
lead1 @2;
lead2 @3;
e2e @4;
#mapd
turn @5;
limit @6;
turnlimit @7;
}
# deprecated
@@ -852,6 +874,21 @@ struct LongitudinalPlan @0xe00b5b3eba12876c {
x @0 :List(Float32);
y @1 :List(Float32);
}
#mapd
enum SpeedLimitControlState {
inactive @0; # No speed limit set or not enabled by parameter.
tempInactive @1; # User wants to ignore speed limit until it changes.
adapting @2; # Reducing speed to match new speed limit.
active @3; # Cruising at speed limit.
}
enum VisionTurnControllerState {
disabled @0; # No predicted substancial turn on vision range or feature disabled.
entering @1; # A subsantial turn is predicted ahead, adapting speed to turn confort levels.
turning @2; # Actively turning. Managing acceleration to provide a roll on turn feeling.
leaving @3; # Road ahead straightens. Start to allow positive acceleration.
}
}
struct LateralPlan @0xe1e9318e2ae8b51e {
@@ -860,6 +897,9 @@ struct LateralPlan @0xe1e9318e2ae8b51e {
rProb @7 :Float32;
dPathPoints @20 :List(Float32);
dProb @21 :Float32;
#mapd
dPathWLinesX @30 :List(Float32);
dPathWLinesY @31 :List(Float32);
mpcSolutionValid @9 :Bool;
desire @17 :Desire;
@@ -939,7 +979,7 @@ struct LiveLocationKalman {
angularVelocityDevice @8 : Measurement;
# orientationNEDCalibrated transforms to rot matrix: NED_from_calibrated
orientationNEDCalibrated @9 : Measurement;
calibratedOrientationNED @9 : Measurement;
# Calibrated frame is simply device frame
# aligned with the vehicle
@@ -1326,6 +1366,23 @@ struct LiveMapDataDEPRECATED {
mapValid @11 :Bool;
}
struct LiveMapData {
speedLimitValid @0 :Bool;
speedLimit @1 :Float32;
speedLimitAheadValid @2 :Bool;
speedLimitAhead @3 :Float32;
speedLimitAheadDistance @4 :Float32;
turnSpeedLimitValid @5 :Bool;
turnSpeedLimit @6 :Float32;
turnSpeedLimitEndDistance @7 :Float32;
turnSpeedLimitSign @8 :Int16;
turnSpeedLimitsAhead @9 :List(Float32);
turnSpeedLimitsAheadDistances @10 :List(Float32);
turnSpeedLimitsAheadSigns @11 :List(Int16);
lastGpsTimestamp @12 :Int64; # Milliseconds since January 1, 1970.
currentRoadName @13 :Text;
}
struct CameraOdometry {
frameId @4 :UInt32;
timestampEof @5 :UInt64;
@@ -1467,5 +1524,7 @@ struct Event {
gpsLocationDEPRECATED @21 :GpsLocationData;
uiLayoutStateDEPRECATED @57 :Legacy.UiLayoutState;
dragonConf @80 :Dp.DragonConf;
#mapd
liveMapData @81: LiveMapData;
}
}

20
cereal/logger/logger.h Normal file
View File

@@ -0,0 +1,20 @@
#pragma once
#ifdef SWAGLOG
#include "selfdrive/common/swaglog.h"
#else
#define CLOUDLOG_DEBUG 10
#define CLOUDLOG_INFO 20
#define CLOUDLOG_WARNING 30
#define CLOUDLOG_ERROR 40
#define CLOUDLOG_CRITICAL 50
#define cloudlog(lvl, fmt, ...) printf(fmt "\n", ## __VA_ARGS__)
#define LOGD(fmt, ...) cloudlog(CLOUDLOG_DEBUG, fmt, ## __VA_ARGS__)
#define LOG(fmt, ...) cloudlog(CLOUDLOG_INFO, fmt, ## __VA_ARGS__)
#define LOGW(fmt, ...) cloudlog(CLOUDLOG_WARNING, fmt, ## __VA_ARGS__)
#define LOGE(fmt, ...) cloudlog(CLOUDLOG_ERROR, fmt, ## __VA_ARGS__)
#endif

View File

@@ -13,6 +13,7 @@ from cereal.services import service_list
assert MultiplePublishersError
assert MessagingError
NO_TRAVERSAL_LIMIT = 2**64-1
AVG_FREQ_HISTORY = 100
SIMULATION = "SIMULATION" in os.environ
@@ -26,6 +27,9 @@ except ImportError:
context = Context()
def log_from_bytes(dat: bytes) -> capnp.lib.capnp._DynamicStructReader:
return log.Event.from_bytes(dat, traversal_limit_in_words=NO_TRAVERSAL_LIMIT)
def new_message(service: Optional[str] = None, size: Optional[int] = None) -> capnp.lib.capnp._DynamicStructBuilder:
dat = log.Event.new_message()
dat.logMonoTime = int(sec_since_boot() * 1e9)
@@ -83,7 +87,7 @@ def drain_sock(sock: SubSocket, wait_for_one: bool = False) -> List[capnp.lib.ca
if dat is None: # Timeout hit
break
dat = log.Event.from_bytes(dat)
dat = log_from_bytes(dat)
ret.append(dat)
return ret
@@ -106,20 +110,20 @@ def recv_sock(sock: SubSocket, wait: bool = False) -> Union[None, capnp.lib.capn
dat = rcv
if dat is not None:
dat = log.Event.from_bytes(dat)
dat = log_from_bytes(dat)
return dat
def recv_one(sock: SubSocket) -> Union[None, capnp.lib.capnp._DynamicStructReader]:
dat = sock.receive()
if dat is not None:
dat = log.Event.from_bytes(dat)
dat = log_from_bytes(dat)
return dat
def recv_one_or_none(sock: SubSocket) -> Union[None, capnp.lib.capnp._DynamicStructReader]:
dat = sock.receive(non_blocking=True)
if dat is not None:
dat = log.Event.from_bytes(dat)
dat = log_from_bytes(dat)
return dat
def recv_one_retry(sock: SubSocket) -> capnp.lib.capnp._DynamicStructReader:
@@ -127,7 +131,7 @@ def recv_one_retry(sock: SubSocket) -> capnp.lib.capnp._DynamicStructReader:
while True:
dat = sock.receive()
if dat is not None:
return log.Event.from_bytes(dat)
return log_from_bytes(dat)
class SubMaster():
def __init__(self, services: List[str], poll: Optional[List[str]] = None,

View File

@@ -69,7 +69,7 @@ public:
SubMaster(const std::vector<const char *> &service_list,
const char *address = nullptr, const std::vector<const char *> &ignore_alive = {});
void update(int timeout = 1000);
void update_msgs(uint64_t current_time, std::vector<std::pair<std::string, cereal::Event::Reader>> messages);
void update_msgs(uint64_t current_time, const std::vector<std::pair<std::string, cereal::Event::Reader>> &messages);
inline bool allAlive(const std::vector<const char *> &service_list = {}) { return all_(service_list, false, true); }
inline bool allValid(const std::vector<const char *> &service_list = {}) { return all_(service_list, true, false); }
inline bool allAliveAndValid(const std::vector<const char *> &service_list = {}) { return all_(service_list, true, true); }

View File

@@ -92,7 +92,9 @@ void SubMaster::update(int timeout) {
SubMessage *m = messages_.at(s);
m->msg_reader->~FlatArrayMessageReader();
m->msg_reader = new (m->allocated_msg_reader) capnp::FlatArrayMessageReader(m->aligned_buf.align(msg));
capnp::ReaderOptions options;
options.traversalLimitInWords = kj::maxValue; // Don't limit
m->msg_reader = new (m->allocated_msg_reader) capnp::FlatArrayMessageReader(m->aligned_buf.align(msg), options);
delete msg;
messages.push_back({m->name, m->msg_reader->getRoot<cereal::Event>()});
}
@@ -100,7 +102,7 @@ void SubMaster::update(int timeout) {
update_msgs(current_time, messages);
}
void SubMaster::update_msgs(uint64_t current_time, std::vector<std::pair<std::string, cereal::Event::Reader>> messages){
void SubMaster::update_msgs(uint64_t current_time, const std::vector<std::pair<std::string, cereal::Event::Reader>> &messages){
if (++frame == UINT64_MAX) frame = 1;
for(auto &kv : messages) {

View File

@@ -62,9 +62,15 @@ services = {
"managerState": (True, 2., 1),
"uploaderState": (True, 0., 1),
#mapd
"liveMapData": (True, 0.),
# debug
"testJoystick": (False, 0.),
# dp
"thermal": (True, 2., 1),
"dragonConf": (False, 2.),
"dragonConf": (False, 1.),
}
service_list = {name: Service(new_port(idx), *vals) for # type: ignore
idx, (name, vals) in enumerate(services.items())}

View File

@@ -55,8 +55,8 @@ class VisionBuf {
void init_cl(cl_device_id device_id, cl_context ctx);
void init_rgb(size_t width, size_t height, size_t stride);
void init_yuv(size_t width, size_t height);
void sync(int dir);
void free();
int sync(int dir);
int free();
};
void visionbuf_compute_aligned_width_and_height(int width, int height, int *aligned_w, int *aligned_h);

View File

@@ -60,27 +60,36 @@ void VisionBuf::import(){
}
void VisionBuf::sync(int dir) {
int VisionBuf::sync(int dir) {
int err = 0;
if (!this->buf_cl) return;
if (!this->buf_cl) return 0;
if (dir == VISIONBUF_SYNC_FROM_DEVICE) {
err = clEnqueueReadBuffer(this->copy_q, this->buf_cl, CL_FALSE, 0, this->len, this->addr, 0, NULL, NULL);
} else {
err = clEnqueueWriteBuffer(this->copy_q, this->buf_cl, CL_FALSE, 0, this->len, this->addr, 0, NULL, NULL);
}
assert(err == 0);
clFinish(this->copy_q);
}
void VisionBuf::free() {
if (this->buf_cl){
int err = clReleaseMemObject(this->buf_cl);
assert(err == 0);
clReleaseCommandQueue(this->copy_q);
if (err == 0){
err = clFinish(this->copy_q);
}
munmap(this->addr, this->len);
close(this->fd);
return err;
}
int VisionBuf::free() {
int err = 0;
if (this->buf_cl){
err = clReleaseMemObject(this->buf_cl);
if (err != 0) return err;
err = clReleaseCommandQueue(this->copy_q);
if (err != 0) return err;
}
err = munmap(this->addr, this->len);
if (err != 0) return err;
err = close(this->fd);
return err;
}

View File

@@ -104,9 +104,7 @@ void VisionBuf::init_cl(cl_device_id device_id, cl_context ctx) {
}
void VisionBuf::sync(int dir) {
int err;
int VisionBuf::sync(int dir) {
struct ion_flush_data flush_data = {0};
flush_data.handle = this->handle;
flush_data.vaddr = this->addr;
@@ -124,19 +122,23 @@ void VisionBuf::sync(int dir) {
ION_IOC_INV_CACHES : ION_IOC_CLEAN_CACHES;
custom_data.arg = (unsigned long)&flush_data;
err = ioctl(ion_fd, ION_IOC_CUSTOM, &custom_data);
assert(err == 0);
return ioctl(ion_fd, ION_IOC_CUSTOM, &custom_data);
}
void VisionBuf::free() {
int VisionBuf::free() {
int err = 0;
if (this->buf_cl){
int err = clReleaseMemObject(this->buf_cl);
assert(err == 0);
err = clReleaseMemObject(this->buf_cl);
if (err != 0) return err;
}
munmap(this->addr, this->mmap_len);
close(this->fd);
err = munmap(this->addr, this->mmap_len);
if (err != 0) return err;
err = close(this->fd);
if (err != 0) return err;
struct ion_handle_data handle_data = {.handle = this->handle};
ioctl(ion_fd, ION_IOC_FREE, &handle_data);
return ioctl(ion_fd, ION_IOC_FREE, &handle_data);
}

View File

@@ -3,9 +3,10 @@
#include <iostream>
#include <thread>
#include "ipc.h"
#include "visionipc_client.h"
#include "visionipc_server.h"
#include "visionipc/ipc.h"
#include "visionipc/visionipc_client.h"
#include "visionipc/visionipc_server.h"
#include "logger/logger.h"
VisionIpcClient::VisionIpcClient(std::string name, VisionStreamType type, bool conflate, cl_device_id device_id, cl_context ctx) : name(name), type(type), device_id(device_id), ctx(ctx) {
msg_ctx = Context::create();
@@ -21,8 +22,11 @@ bool VisionIpcClient::connect(bool blocking){
// Cleanup old buffers on reconnect
for (size_t i = 0; i < num_buffers; i++){
buffers[i].free();
if (buffers[i].free() != 0) {
LOGE("Failed to free buffer %zu", i);
}
}
num_buffers = 0;
// Connect to server socket and ask for all FDs of type
@@ -101,7 +105,10 @@ VisionBuf * VisionIpcClient::recv(VisionIpcBufExtra * extra, const int timeout_m
*extra = packet->extra;
}
buf->sync(VISIONBUF_SYNC_TO_DEVICE);
if (buf->sync(VISIONBUF_SYNC_TO_DEVICE) != 0) {
LOGE("Failed to sync buffer");
}
delete r;
return buf;
}
@@ -110,7 +117,9 @@ VisionBuf * VisionIpcClient::recv(VisionIpcBufExtra * extra, const int timeout_m
VisionIpcClient::~VisionIpcClient(){
for (size_t i = 0; i < num_buffers; i++){
buffers[i].free();
if (buffers[i].free() != 0) {
LOGE("Failed to free buffer %zu", i);
}
}
delete sock;

View File

@@ -10,6 +10,7 @@
#include "messaging/messaging.h"
#include "visionipc/ipc.h"
#include "visionipc/visionipc_server.h"
#include "logger/logger.h"
std::string get_endpoint_name(std::string name, VisionStreamType type){
if (messaging_use_zmq()){
@@ -145,7 +146,11 @@ VisionBuf * VisionIpcServer::get_buffer(VisionStreamType type){
}
void VisionIpcServer::send(VisionBuf * buf, VisionIpcBufExtra * extra, bool sync){
if (sync) buf->sync(VISIONBUF_SYNC_FROM_DEVICE);
if (sync) {
if (buf->sync(VISIONBUF_SYNC_FROM_DEVICE) != 0) {
LOGE("Failed to sync buffer");
}
}
assert(buffers.count(buf->type));
assert(buf->idx < buffers[buf->type].size());
@@ -165,7 +170,9 @@ VisionIpcServer::~VisionIpcServer(){
// VisionBuf cleanup
for( auto const& [type, buf] : buffers ) {
for (VisionBuf* b : buf){
b->free();
if (b->free() != 0) {
LOGE("Failed to free buffer");
}
delete b;
}
}

View File

@@ -1,8 +1,12 @@
import jwt
import os
import requests
from datetime import datetime, timedelta
from common.basedir import PERSIST
from selfdrive.version import version
from common.params import Params
API_HOST = os.getenv('API_HOST', 'https://api.commadotai.com') if not Params().get_bool("dp_api_custom") else Params().get("dp_api_custom_url", encoding='utf-8')
class Api():
def __init__(self, dongle_id):
@@ -34,12 +38,10 @@ class Api():
def api_get(endpoint, method='GET', timeout=None, access_token=None, **params):
backend = "https://api.commadotai.com/"
headers = {}
if access_token is not None:
headers['Authorization'] = "JWT "+access_token
headers['User-Agent'] = "openpilot-" + version
return requests.request(method, backend+endpoint, timeout=timeout, headers=headers, params=params)
return requests.request(method, API_HOST + "/" + endpoint, timeout=timeout, headers=headers, params=params)

View File

@@ -16,7 +16,12 @@ confs = [
{'name': 'dp_thermal_started', 'default': False, 'type': 'Bool', 'conf_type': ['struct']},
{'name': 'dp_thermal_overheat', 'default': False, 'type': 'Bool', 'conf_type': ['struct']},
# custom api server
{'name': 'dp_api_custom', 'default': False, 'type': 'Bool', 'conf_type': ['param']},
{'name': 'dp_api_custom_url', 'default': 'https://api.retropilot.org', 'type': 'Text', 'depends': [{'name': 'dp_api_custom', 'vals': [True]}], 'conf_type': ['param']},
{'name': 'dp_atl', 'default': False, 'type': 'Bool', 'conf_type': ['param', 'struct'], 'update_once': True},
{'name': 'dp_atl_op_long', 'default': False, 'type': 'Bool', 'depends': [{'name': 'dp_atl', 'vals': [True]}], 'conf_type': ['param', 'struct'], 'update_once': True},
# dashcam related
{'name': 'dp_dashcamd', 'default': False, 'type': 'Bool', 'conf_type': ['param', 'struct']},
# auto shutdown
@@ -38,10 +43,10 @@ confs = [
{'name': 'dp_lc_auto_delay', 'default': 3., 'type': 'Float32', 'min': 0., 'max': 10., 'depends': [{'name': 'dp_lateral_mode', 'vals': [2]}], 'conf_type': ['param', 'struct']},
# long ctrl
{'name': 'dp_allow_gas', 'default': False, 'type': 'Bool', 'depends': [{'name': 'dp_atl', 'vals': [False]}], 'conf_type': ['param', 'struct']},
{'name': 'dp_following_profile_ctrl', 'default': False, 'type': 'Bool', 'depends': [{'name': 'dp_atl', 'vals': [False]}], 'conf_type': ['param', 'struct']},
{'name': 'dp_following_profile', 'default': 0, 'type': 'UInt8', 'min': 0, 'max': 2, 'depends': [{'name': 'dp_atl', 'vals': [False]}, {'name': 'dp_following_profile_ctrl', 'vals': [True]}], 'conf_type': ['param', 'struct']},
{'name': 'dp_accel_profile_ctrl', 'default': False, 'type': 'Bool', 'depends': [{'name': 'dp_atl', 'vals': [False]}], 'conf_type': ['param', 'struct']},
{'name': 'dp_accel_profile', 'default': 0, 'type': 'UInt8', 'min': 0, 'max': 2, 'depends': [{'name': 'dp_atl', 'vals': [False]}, {'name': 'dp_accel_profile_ctrl', 'vals': [True]}], 'conf_type': ['param', 'struct']},
{'name': 'dp_following_profile_ctrl', 'default': False, 'type': 'Bool', 'conf_type': ['param', 'struct']},
{'name': 'dp_following_profile', 'default': 0, 'type': 'UInt8', 'min': 0, 'max': 2, 'depends': [{'name': 'dp_following_profile_ctrl', 'vals': [True]}], 'conf_type': ['param', 'struct']},
{'name': 'dp_accel_profile_ctrl', 'default': False, 'type': 'Bool', 'conf_type': ['param', 'struct']},
{'name': 'dp_accel_profile', 'default': 0, 'type': 'UInt8', 'min': 0, 'max': 2, 'depends': [{'name': 'dp_accel_profile_ctrl', 'vals': [True]}], 'conf_type': ['param', 'struct']},
# safety
{'name': 'dp_gear_check', 'default': True, 'type': 'Bool', 'depends': [{'name': 'dp_atl', 'vals': [False]}], 'conf_type': ['param', 'struct']},
{'name': 'dp_speed_check', 'default': True, 'type': 'Bool', 'conf_type': ['param', 'struct']},
@@ -54,23 +59,23 @@ confs = [
{'name': 'dp_ui_face', 'default': True, 'type': 'Bool', 'conf_type': ['param', 'struct']},
{'name': 'dp_ui_lane', 'default': True, 'type': 'Bool', 'conf_type': ['param', 'struct']},
{'name': 'dp_ui_lead', 'default': True, 'type': 'Bool', 'conf_type': ['param', 'struct']},
{'name': 'dp_ui_dev', 'default': False, 'type': 'Bool', 'conf_type': ['param', 'struct']},
{'name': 'dp_ui_dev_mini', 'default': False, 'type': 'Bool', 'conf_type': ['param', 'struct']},
{'name': 'dp_ui_side', 'default': False, 'type': 'Bool', 'conf_type': ['param', 'struct']},
{'name': 'dp_ui_top', 'default': False, 'type': 'Bool', 'conf_type': ['param', 'struct']},
{'name': 'dp_ui_blinker', 'default': False, 'type': 'Bool', 'conf_type': ['param', 'struct']},
{'name': 'dp_ui_brightness', 'default': 0, 'type': 'UInt8', 'min': 0, 'max': 100, 'conf_type': ['param', 'struct']},
{'name': 'dp_ui_volume', 'default': -5, 'type': 'Int8', 'min': -5, 'max': 100, 'conf_type': ['param', 'struct']},
# toyota
{'name': 'dp_lexus_rx_rpm_fix', 'default': False, 'type': 'Bool', 'depends': [{'name': 'dp_atl', 'vals': [False]}], 'conf_type': ['param']},
{'name': 'dp_lexus_rx_rpm_fix', 'default': False, 'type': 'Bool', 'conf_type': ['param']},
{'name': 'dp_toyota_ldw', 'default': True, 'type': 'Bool', 'conf_type': ['param', 'struct']},
{'name': 'dp_toyota_sng', 'default': False, 'type': 'Bool', 'depends': [{'name': 'dp_atl', 'vals': [False]}], 'conf_type': ['param', 'struct']},
{'name': 'dp_toyota_sng', 'default': False, 'type': 'Bool', 'conf_type': ['param', 'struct']},
{'name': 'dp_toyota_zss', 'default': False, 'type': 'Bool', 'conf_type': ['param']},
{'name': 'dp_toyota_fp_btn_link', 'default': False, 'type': 'Bool', 'conf_type': ['param']},
{'name': 'dp_toyota_ap_btn_link', 'default': False, 'type': 'Bool', 'conf_type': ['param']},
{'name': 'dp_toyota_disable_relay', 'default': False, 'type': 'Bool', 'conf_type': ['param']},
{'name': 'dp_toyota_cruise_override', 'default': False, 'type': 'Bool', 'depends': [{'name': 'dp_atl', 'vals': [False]}], 'conf_type': ['param', 'struct']},
{'name': 'dp_toyota_cruise_override_vego', 'default': False, 'type': 'Bool', 'depends': [{'name': 'dp_atl', 'vals': [False]}, {'name': 'dp_toyota_cruise_override', 'vals': [True]}], 'conf_type': ['param', 'struct']},
{'name': 'dp_toyota_cruise_override_at', 'default': 44, 'type': 'Float32', 'depends': [{'name': 'dp_atl', 'vals': [False]}, {'name': 'dp_toyota_cruise_override', 'vals': [True]}], 'min': 0, 'max': 50., 'conf_type': ['param', 'struct']},
{'name': 'dp_toyota_cruise_override_speed', 'default': 32, 'type': 'Float32', 'depends': [{'name': 'dp_atl', 'vals': [False]}, {'name': 'dp_toyota_cruise_override', 'vals': [True]}], 'min': 0, 'max': 50., 'conf_type': ['param', 'struct']},
{'name': 'dp_toyota_cruise_override', 'default': False, 'type': 'Bool', 'conf_type': ['param', 'struct']},
{'name': 'dp_toyota_cruise_override_vego', 'default': False, 'type': 'Bool', 'depends': [{'name': 'dp_toyota_cruise_override', 'vals': [True]}], 'conf_type': ['param', 'struct']},
{'name': 'dp_toyota_cruise_override_at', 'default': 44, 'type': 'Float32', 'depends': [{'name': 'dp_toyota_cruise_override', 'vals': [True]}], 'min': 0, 'max': 50., 'conf_type': ['param', 'struct']},
{'name': 'dp_toyota_cruise_override_speed', 'default': 32, 'type': 'Float32', 'depends': [{'name': 'dp_toyota_cruise_override', 'vals': [True]}], 'min': 0, 'max': 50., 'conf_type': ['param', 'struct']},
# hyundai
{'name': 'dp_hkg_smart_mdps', 'default': False, 'type': 'Bool', 'conf_type': ['param']},
# honda
@@ -101,8 +106,6 @@ confs = [
{'name': 'dp_car_assigned', 'default': '', 'type': 'Text', 'conf_type': ['param']},
{'name': 'dp_car_list', 'default': '', 'type': 'Text', 'conf_type': ['param']},
{'name': 'dp_no_batt', 'default': False, 'type': 'Bool', 'conf_type': ['param']},
{'name': 'dp_panda_fake_black', 'default': False, 'type': 'Bool', 'conf_type': ['param']},
{'name': 'dp_panda_no_gps', 'default': False, 'type': 'Bool', 'conf_type': ['param']},
{'name': 'dp_last_candidate', 'default': '', 'type': 'Text', 'conf_type': ['param']},
{'name': 'dp_prebuilt', 'default': False, 'type': 'Bool', 'conf_type': ['param']},
{'name': 'dp_gpxd', 'default': False, 'type': 'Bool', 'conf_type': ['param']},

View File

@@ -79,6 +79,25 @@ class NamedTemporaryDir():
self.close()
class CallbackReader:
"""Wraps a file, but overrides the read method to also
call a callback function with the number of bytes read so far."""
def __init__(self, f, callback, *args):
self.f = f
self.callback = callback
self.cb_args = args
self.total_read = 0
def __getattr__(self, attr):
return getattr(self.f, attr)
def read(self, *args, **kwargs):
chunk = self.f.read(*args, **kwargs)
self.total_read += len(chunk)
self.callback(*self.cb_args, self.total_read)
return chunk
def _get_fileobject_func(writer, temp_dir):
def _get_fileobject():
file_obj = writer.get_fileobject(dir=temp_dir)

View File

@@ -1,9 +1,13 @@
class FirstOrderFilter():
class FirstOrderFilter:
# first order filter
def __init__(self, x0, ts, dt):
self.k = (dt / ts) / (1. + dt / ts)
def __init__(self, x0, rc, dt):
self.x = x0
self.dt = dt
self.update_alpha(rc)
def update_alpha(self, rc):
self.alpha = self.dt / (rc + self.dt)
def update(self, x):
self.x = (1. - self.k) * self.x + self.k * x
self.x = (1. - self.alpha) * self.x + self.alpha * x
return self.x

View File

@@ -17,7 +17,7 @@ cdef extern from "selfdrive/common/params.h":
ALL
cdef cppclass Params:
Params(bool) nogil
Params() nogil
Params(string) nogil
string get(string, bool) nogil
bool getBool(string) nogil

View File

@@ -30,11 +30,11 @@ class UnknownKeyName(Exception):
cdef class Params:
cdef c_Params* p
def __cinit__(self, d=None, bool persistent_params=False):
def __cinit__(self, d=None):
cdef string path
if d is None:
with nogil:
self.p = new c_Params(persistent_params)
self.p = new c_Params()
else:
path = <string>d.encode()
with nogil:

View File

@@ -1,4 +0,0 @@
#!/usr/bin/bash
cd /data/openpilot
exec ./launch_openpilot.sh

View File

@@ -0,0 +1,34 @@
#!/data/data/com.termux/files/usr/bin/sh
# Get some needed tools. coreutils for mkdir command, gnugp for the signing key, and apt-transport-https to actually connect to the repo
apt-get update
apt-get --assume-yes upgrade
apt-get --assume-yes install coreutils gnupg
# Make the sources.list.d directory
mkdir -p $PREFIX/etc/apt/sources.list.d
# Write the needed source file
echo "deb https://its-pointless.github.io/files/24 termux extras" > $PREFIX/etc/apt/sources.list.d/pointless.list
# Add signing key from https://its-pointless.github.io/pointless.gpg
curl -sL https://its-pointless.github.io/pointless.gpg | apt-key add -
# Update apt
apt update
# install gfortran
apt install gcc-11 -y
setupclang-gfort-11
# Elf cleaner is needed to remove a DT_ENTRY warning that prints out when gfortran -v is called to get
# its version number and this breaks the pip installation script when fortran is used.
# Build elf cleaner
SCRIPTPATH="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"
ELFCLEANERPATH=$SCRIPTPATH/termux-elf-cleaner/
cd $ELFCLEANERPATH
make
# Perform elf cleaner on gfortran
./termux-elf-cleaner $(which gfortran)

View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{one line to give the program's name and a brief idea of what it does.}
Copyright (C) {year} {name of author}
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 3 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, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
{project} Copyright (C) {year} {fullname}
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

View File

@@ -0,0 +1,16 @@
CXXFLAGS += -std=c++11 -Wall -Wextra -pedantic
PREFIX ?= /usr/local
termux-elf-cleaner: termux-elf-cleaner.cpp
clean:
rm -f termux-elf-cleaner
install: termux-elf-cleaner
mkdir -p $(PREFIX)/bin
install termux-elf-cleaner $(PREFIX)/bin/termux-elf-cleaner
uninstall:
rm -f $(PREFIX)/bin/termux-elf-cleaner
.PHONY: clean install uninstall

View File

@@ -0,0 +1,39 @@
# termux-elf-cleaner
Utility for Android ELF files to remove unused parts that the linker warns about.
## Description
When loading ELF files, the Android linker warns about unsupported dynamic section entries with warnings such as:
WARNING: linker: /data/data/org.kost.nmap.android.networkmapper/bin/nmap: unused DT entry: type 0x6ffffffe arg 0x8a7d4
WARNING: linker: /data/data/org.kost.nmap.android.networkmapper/bin/nmap: unused DT entry: type 0x6fffffff arg 0x3
This utility strips away the following dynamic section entries:
- `DT_RPATH` - not supported in any Android version.
- `DT_RUNPATH` - supported from Android 7.0.
- `DT_VERDEF` - supported from Android 6.0.
- `DT_VERDEFNUM` - supported from Android 6.0.
- `DT_VERNEEDED` - supported from Android 6.0.
- `DT_VERNEEDNUM` - supported from Android 6.0.
- `DT_VERSYM` - supported from Android 6.0.
It also removes the three ELF sections of type:
- `SHT_GNU_verdef`
- `SHT_GNU_verneed`
- `SHT_GNU_versym`
## Usage
```sh
usage: termux-elf-cleaner <filenames>
Processes ELF files to remove unsupported section types and
dynamic section entries which the Android linker warns about.
```
## Author
Fredrik Fornwall ([@fornwall](https://github.com/fornwall)).
## License
SPDX-License-Identifier: [GPL-3.0-or-later](https://spdx.org/licenses/GPL-3.0-or-later.html)

View File

@@ -0,0 +1,211 @@
#ifndef ELF_H_INCLUDED
#define ELF_H_INCLUDED
#include <stdint.h>
/* Type for a 16-bit quantity. */
typedef uint16_t Elf32_Half;
typedef uint16_t Elf64_Half;
/* Types for signed and unsigned 32-bit quantities. */
typedef uint32_t Elf32_Word;
typedef int32_t Elf32_Sword;
typedef uint32_t Elf64_Word;
typedef int32_t Elf64_Sword;
/* Types for signed and unsigned 64-bit quantities. */
typedef uint64_t Elf32_Xword;
typedef int64_t Elf32_Sxword;
typedef uint64_t Elf64_Xword;
typedef int64_t Elf64_Sxword;
/* Type of addresses. */
typedef uint32_t Elf32_Addr;
typedef uint64_t Elf64_Addr;
/* Type of file offsets. */
typedef uint32_t Elf32_Off;
typedef uint64_t Elf64_Off;
/* Type for section indices, which are 16-bit quantities. */
typedef uint16_t Elf32_Section;
typedef uint16_t Elf64_Section;
/* Type for version symbol information. */
typedef Elf32_Half Elf32_Versym;
typedef Elf64_Half Elf64_Versym;
/* The ELF file header. This appears at the start of every ELF file. */
typedef struct {
unsigned char e_ident[16]; /* Magic number and other info */
Elf32_Half e_type; /* Object file type */
Elf32_Half e_machine; /* Architecture */
Elf32_Word e_version; /* Object file version */
Elf32_Addr e_entry; /* Entry point virtual address */
Elf32_Off e_phoff; /* Program header table (usually follows elf header directly) file offset */
Elf32_Off e_shoff; /* Section header table (at end of file) file offset */
Elf32_Word e_flags; /* Processor-specific flags */
Elf32_Half e_ehsize; /* ELF header size in bytes */
Elf32_Half e_phentsize; /* Program header table entry size */
Elf32_Half e_phnum; /* Program header table entry count */
Elf32_Half e_shentsize; /* Section header table entry size */
Elf32_Half e_shnum; /* Section header table entry count */
Elf32_Half e_shstrndx; /* Section header string table index */
} Elf32_Ehdr;
typedef struct {
unsigned char e_ident[16]; /* Magic number and other info */
Elf64_Half e_type; /* Object file type */
Elf64_Half e_machine; /* Architecture */
Elf64_Word e_version; /* Object file version */
Elf64_Addr e_entry; /* Entry point virtual address */
Elf64_Off e_phoff; /* Program header table file offset */
Elf64_Off e_shoff; /* Section header table file offset */
Elf64_Word e_flags; /* Processor-specific flags */
Elf64_Half e_ehsize; /* ELF header size in bytes */
Elf64_Half e_phentsize; /* Program header table entry size */
Elf64_Half e_phnum; /* Program header table entry count */
Elf64_Half e_shentsize; /* Section header table entry size */
Elf64_Half e_shnum; /* Section header table entry count */
Elf64_Half e_shstrndx; /* Section header string table index */
} Elf64_Ehdr;
/* Section header entry. The number of section entries in the file are determined by the "e_shnum" field of the ELF header.*/
typedef struct {
Elf32_Word sh_name; /* Section name (string tbl index) */
Elf32_Word sh_type; /* Section type */
Elf32_Word sh_flags; /* Section flags */
Elf32_Addr sh_addr; /* Section virtual addr at execution */
Elf32_Off sh_offset; /* Section file offset */
Elf32_Word sh_size; /* Section size in bytes */
Elf32_Word sh_link; /* Link to another section */
Elf32_Word sh_info; /* Additional section information */
Elf32_Word sh_addralign; /* Section alignment */
Elf32_Word sh_entsize; /* Entry size if section holds table */
} Elf32_Shdr;
typedef struct {
Elf64_Word sh_name; /* Section name (string tbl index) */
Elf64_Word sh_type; /* Section type */
Elf64_Xword sh_flags; /* Section flags */
Elf64_Addr sh_addr; /* Section virtual addr at execution */
Elf64_Off sh_offset; /* Section file offset */
Elf64_Xword sh_size; /* Section size in bytes */
Elf64_Word sh_link; /* Link to another section */
Elf64_Word sh_info; /* Additional section information */
Elf64_Xword sh_addralign; /* Section alignment */
Elf64_Xword sh_entsize; /* Entry size if section holds table */
} Elf64_Shdr;
/* Legal values for sh_type (section type). */
#define SHT_NULL 0 /* Section header table entry unused */
#define SHT_PROGBITS 1 /* Program data */
#define SHT_SYMTAB 2 /* Symbol table */
#define SHT_STRTAB 3 /* String table */
#define SHT_RELA 4 /* Relocation entries with addends */
#define SHT_HASH 5 /* Symbol hash table */
#define SHT_DYNAMIC 6 /* Dynamic linking information. Contains Elf32_Dyn/Elf64_Dyn entries. */
#define SHT_NOTE 7 /* Notes */
#define SHT_NOBITS 8 /* Program space with no data (bss) */
#define SHT_REL 9 /* Relocation entries, no addends */
#define SHT_SHLIB 10 /* Reserved */
#define SHT_DYNSYM 11 /* Dynamic linker symbol table */
#define SHT_INIT_ARRAY 14 /* Array of constructors */
#define SHT_FINI_ARRAY 15 /* Array of destructors */
#define SHT_PREINIT_ARRAY 16 /* Array of pre-constructors */
#define SHT_GROUP 17 /* Section group */
#define SHT_SYMTAB_SHNDX 18 /* Extended section indeces */
#define SHT_NUM 19 /* Number of defined types. */
#define SHT_LOOS 0x60000000 /* Start OS-specific. */
#define SHT_GNU_ATTRIBUTES 0x6ffffff5 /* Object attributes. */
#define SHT_GNU_HASH 0x6ffffff6 /* GNU-style hash table. */
#define SHT_GNU_LIBLIST 0x6ffffff7 /* Prelink library list */
#define SHT_CHECKSUM 0x6ffffff8 /* Checksum for DSO content. */
#define SHT_LOSUNW 0x6ffffffa /* Sun-specific low bound. */
#define SHT_SUNW_move 0x6ffffffa
#define SHT_SUNW_COMDAT 0x6ffffffb
#define SHT_SUNW_syminfo 0x6ffffffc
#define SHT_GNU_verdef 0x6ffffffd /* Version definition section. */
#define SHT_GNU_verneed 0x6ffffffe /* Version needs section. */
#define SHT_GNU_versym 0x6fffffff /* Version symbol table. */
#define SHT_HISUNW 0x6fffffff /* Sun-specific high bound. */
#define SHT_HIOS 0x6fffffff /* End OS-specific type */
#define SHT_LOPROC 0x70000000 /* Start of processor-specific */
#define SHT_HIPROC 0x7fffffff /* End of processor-specific */
#define SHT_LOUSER 0x80000000 /* Start of application-specific */
#define SHT_HIUSER 0x8fffffff /* End of application-specific */
/* Dynamic section entry. */
typedef struct {
Elf32_Sword d_tag; /* Dynamic entry type */
union { Elf32_Word d_val; Elf32_Addr d_ptr; } d_un; /* Integer or address value */
} Elf32_Dyn;
typedef struct {
Elf64_Sxword d_tag; /* Dynamic entry type */
union { Elf64_Xword d_val; Elf64_Addr d_ptr; } d_un; /* Integer or address value */
} Elf64_Dyn;
/* Legal values for d_tag (dynamic entry type). */
#define DT_NULL 0 /* Marks end of dynamic section */
#define DT_NEEDED 1 /* Name of needed library */
#define DT_PLTRELSZ 2 /* Size in bytes of PLT relocs */
#define DT_PLTGOT 3 /* Processor defined value */
#define DT_HASH 4 /* Address of symbol hash table */
#define DT_STRTAB 5 /* Address of string table */
#define DT_SYMTAB 6 /* Address of symbol table */
#define DT_RELA 7 /* Address of Rela relocs */
#define DT_RELASZ 8 /* Total size of Rela relocs */
#define DT_RELAENT 9 /* Size of one Rela reloc */
#define DT_STRSZ 10 /* Size of string table */
#define DT_SYMENT 11 /* Size of one symbol table entry */
#define DT_INIT 12 /* Address of init function */
#define DT_FINI 13 /* Address of termination function */
#define DT_SONAME 14 /* Name of shared object */
#define DT_RPATH 15 /* Library search path (deprecated) */
#define DT_SYMBOLIC 16 /* Start symbol search here */
#define DT_REL 17 /* Address of Rel relocs */
#define DT_RELSZ 18 /* Total size of Rel relocs */
#define DT_RELENT 19 /* Size of one Rel reloc */
#define DT_PLTREL 20 /* Type of reloc in PLT */
#define DT_DEBUG 21 /* For debugging; unspecified */
#define DT_TEXTREL 22 /* Reloc might modify .text */
#define DT_JMPREL 23 /* Address of PLT relocs */
#define DT_BIND_NOW 24 /* Process relocations of object */
#define DT_INIT_ARRAY 25 /* Array with addresses of init fct */
#define DT_FINI_ARRAY 26 /* Array with addresses of fini fct */
#define DT_INIT_ARRAYSZ 27 /* Size in bytes of DT_INIT_ARRAY */
#define DT_FINI_ARRAYSZ 28 /* Size in bytes of DT_FINI_ARRAY */
#define DT_RUNPATH 29 /* Library search path */
#define DT_FLAGS 30 /* Flags for the object being loaded */
#define DT_ENCODING 32 /* Start of encoded range */
#define DT_PREINIT_ARRAY 32 /* Array with addresses of preinit fct*/
#define DT_PREINIT_ARRAYSZ 33 /* size in bytes of DT_PREINIT_ARRAY */
#define DT_NUM 34 /* Number used */
#define DT_LOOS 0x6000000d /* Start of OS-specific */
#define DT_HIOS 0x6ffff000 /* End of OS-specific */
#define DT_VERDEF 0x6ffffffc
#define DT_VERDEFNUM 0x6ffffffd
#define DT_LOPROC 0x70000000 /* Start of processor-specific */
#define DT_HIPROC 0x7fffffff /* End of processor-specific */
/* Symbol table entry. */
typedef struct {
Elf32_Word st_name; /* Symbol name (string tbl index) */
Elf32_Addr st_value; /* Symbol value */
Elf32_Word st_size; /* Symbol size */
unsigned char st_info; /* Symbol type and binding */
unsigned char st_other; /* Symbol visibility */
Elf32_Section st_shndx; /* Section index */
} Elf32_Sym;
typedef struct {
Elf64_Word st_name; /* Symbol name (string tbl index) */
unsigned char st_info; /* Symbol type and binding */
unsigned char st_other; /* Symbol visibility */
Elf64_Section st_shndx; /* Section index */
Elf64_Addr st_value; /* Symbol value */
Elf64_Xword st_size; /* Symbol size */
} Elf64_Sym;
#endif

View File

@@ -0,0 +1,191 @@
#include <algorithm>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#ifndef __ANDROID_API__
#define __ANDROID_API__ 21
#endif
// Include a local elf.h copy as not all platforms have it.
#include "elf.h"
#define DT_GNU_HASH 0x6ffffef5
#define DT_VERSYM 0x6ffffff0
#define DT_FLAGS_1 0x6ffffffb
#define DT_VERNEEDED 0x6ffffffe
#define DT_VERNEEDNUM 0x6fffffff
#define DF_1_NOW 0x00000001 /* Set RTLD_NOW for this object. */
#define DF_1_GLOBAL 0x00000002 /* Set RTLD_GLOBAL for this object. */
#define DF_1_NODELETE 0x00000008 /* Set RTLD_NODELETE for this object.*/
#if __ANDROID_API__ < 23
#define SUPPORTED_DT_FLAGS_1 (DF_1_NOW | DF_1_GLOBAL)
#else
// The supported DT_FLAGS_1 values as of Android 6.0.
#define SUPPORTED_DT_FLAGS_1 (DF_1_NOW | DF_1_GLOBAL | DF_1_NODELETE)
#endif
template<typename ElfHeaderType /*Elf{32,64}_Ehdr*/,
typename ElfSectionHeaderType /*Elf{32,64}_Shdr*/,
typename ElfDynamicSectionEntryType /* Elf{32,64}_Dyn */>
bool process_elf(uint8_t* bytes, size_t elf_file_size, char const* file_name)
{
if (sizeof(ElfSectionHeaderType) > elf_file_size) {
fprintf(stderr, "termux-elf-cleaner: Elf header for '%s' would end at %zu but file size only %zu\n", file_name, sizeof(ElfSectionHeaderType), elf_file_size);
return false;
}
ElfHeaderType* elf_hdr = reinterpret_cast<ElfHeaderType*>(bytes);
size_t last_section_header_byte = elf_hdr->e_shoff + sizeof(ElfSectionHeaderType) * elf_hdr->e_shnum;
if (last_section_header_byte > elf_file_size) {
fprintf(stderr, "termux-elf-cleaner: Section header for '%s' would end at %zu but file size only %zu\n", file_name, last_section_header_byte, elf_file_size);
return false;
}
ElfSectionHeaderType* section_header_table = reinterpret_cast<ElfSectionHeaderType*>(bytes + elf_hdr->e_shoff);
for (unsigned int i = 1; i < elf_hdr->e_shnum; i++) {
ElfSectionHeaderType* section_header_entry = section_header_table + i;
if (section_header_entry->sh_type == SHT_DYNAMIC) {
size_t const last_dynamic_section_byte = section_header_entry->sh_offset + section_header_entry->sh_size;
if (last_dynamic_section_byte > elf_file_size) {
fprintf(stderr, "termux-elf-cleaner: Dynamic section for '%s' would end at %zu but file size only %zu\n", file_name, last_dynamic_section_byte, elf_file_size);
return false;
}
size_t const dynamic_section_entries = section_header_entry->sh_size / sizeof(ElfDynamicSectionEntryType);
ElfDynamicSectionEntryType* const dynamic_section =
reinterpret_cast<ElfDynamicSectionEntryType*>(bytes + section_header_entry->sh_offset);
unsigned int last_nonnull_entry_idx = 0;
for (unsigned int j = dynamic_section_entries - 1; j > 0; j--) {
ElfDynamicSectionEntryType* dynamic_section_entry = dynamic_section + j;
if (dynamic_section_entry->d_tag != DT_NULL) {
last_nonnull_entry_idx = j;
break;
}
}
for (unsigned int j = 0; j < dynamic_section_entries; j++) {
ElfDynamicSectionEntryType* dynamic_section_entry = dynamic_section + j;
char const* removed_name = nullptr;
switch (dynamic_section_entry->d_tag) {
#if __ANDROID_API__ <= 21
case DT_GNU_HASH: removed_name = "DT_GNU_HASH"; break;
#endif
#if __ANDROID_API__ < 23
case DT_VERSYM: removed_name = "DT_VERSYM"; break;
case DT_VERNEEDED: removed_name = "DT_VERNEEDED"; break;
case DT_VERNEEDNUM: removed_name = "DT_VERNEEDNUM"; break;
case DT_VERDEF: removed_name = "DT_VERDEF"; break;
case DT_VERDEFNUM: removed_name = "DT_VERDEFNUM"; break;
#endif
case DT_RPATH: removed_name = "DT_RPATH"; break;
#if __ANDROID_API__ < 24
case DT_RUNPATH: removed_name = "DT_RUNPATH"; break;
#endif
}
if (removed_name != nullptr) {
printf("termux-elf-cleaner: Removing the %s dynamic section entry from '%s'\n", removed_name, file_name);
// Tag the entry with DT_NULL and put it last:
dynamic_section_entry->d_tag = DT_NULL;
// Decrease j to process new entry index:
std::swap(dynamic_section[j--], dynamic_section[last_nonnull_entry_idx--]);
} else if (dynamic_section_entry->d_tag == DT_FLAGS_1) {
// Remove unsupported DF_1_* flags to avoid linker warnings.
decltype(dynamic_section_entry->d_un.d_val) orig_d_val =
dynamic_section_entry->d_un.d_val;
decltype(dynamic_section_entry->d_un.d_val) new_d_val =
(orig_d_val & SUPPORTED_DT_FLAGS_1);
if (new_d_val != orig_d_val) {
printf("termux-elf-cleaner: Replacing unsupported DF_1_* flags %llu with %llu in '%s'\n",
(unsigned long long) orig_d_val,
(unsigned long long) new_d_val,
file_name);
dynamic_section_entry->d_un.d_val = new_d_val;
}
}
}
}
#if __ANDROID_API__ < 23
else if (section_header_entry->sh_type == SHT_GNU_verdef ||
section_header_entry->sh_type == SHT_GNU_verneed ||
section_header_entry->sh_type == SHT_GNU_versym) {
printf("termux-elf-cleaner: Removing version section from '%s'\n", file_name);
section_header_entry->sh_type = SHT_NULL;
}
#endif
}
return true;
}
int main(int argc, char const** argv)
{
if (argc < 2 || (argc == 2 && strcmp(argv[1], "-h")==0)) {
fprintf(stderr, "usage: %s <filenames>\n", argv[0]);
fprintf(stderr, "\nProcesses ELF files to remove unsupported section types\n"
"and dynamic section entries which the Android linker (API %d)\nwarns about.\n",
__ANDROID_API__);
return 1;
}
for (int i = 1; i < argc; i++) {
char const* file_name = argv[i];
int fd = open(file_name, O_RDWR);
if (fd < 0) {
char* error_message;
if (asprintf(&error_message, "open(\"%s\")", file_name) == -1) error_message = (char*) "open()";
perror(error_message);
return 1;
}
struct stat st;
if (fstat(fd, &st) < 0) { perror("fstat()"); return 1; }
if (st.st_size < (long long) sizeof(Elf32_Ehdr)) {
close(fd);
continue;
}
void* mem = mmap(0, st.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (mem == MAP_FAILED) { perror("mmap()"); return 1; }
uint8_t* bytes = reinterpret_cast<uint8_t*>(mem);
if (!(bytes[0] == 0x7F && bytes[1] == 'E' && bytes[2] == 'L' && bytes[3] == 'F')) {
// Not the ELF magic number.
munmap(mem, st.st_size);
close(fd);
continue;
}
if (bytes[/*EI_DATA*/5] != 1) {
fprintf(stderr, "termux-elf-cleaner: Not little endianness in '%s'\n", file_name);
munmap(mem, st.st_size);
close(fd);
continue;
}
uint8_t const bit_value = bytes[/*EI_CLASS*/4];
if (bit_value == 1) {
if (!process_elf<Elf32_Ehdr, Elf32_Shdr, Elf32_Dyn>(bytes, st.st_size, file_name)) return 1;
} else if (bit_value == 2) {
if (!process_elf<Elf64_Ehdr, Elf64_Shdr, Elf64_Dyn>(bytes, st.st_size, file_name)) return 1;
} else {
printf("termux-elf-cleaner: Incorrect bit value %d in '%s'\n", bit_value, file_name);
return 1;
}
if (msync(mem, st.st_size, MS_SYNC) < 0) { perror("msync()"); return 1; }
munmap(mem, st.st_size);
close(fd);
}
return 0;
}

View File

@@ -1,6 +1,6 @@
{
"ota_url": "https://commadist.azureedge.net/neosupdate/ota-signed-c4f56c62c5603c86e2ae9d83008a8d42a91319979661d0c42fb97b85d9112266.zip",
"ota_hash": "c4f56c62c5603c86e2ae9d83008a8d42a91319979661d0c42fb97b85d9112266",
"ota_url": "https://commadist.azureedge.net/neosupdate/ota-signed-5dc2575d713977666a8e14ae1b43a04d7f63123934c80fa10751d949a107653e.zip",
"ota_hash": "5dc2575d713977666a8e14ae1b43a04d7f63123934c80fa10751d949a107653e",
"recovery_url": "https://commadist.azureedge.net/neosupdate/recovery-db31ffe79dfd60be966fba6d1525a5081a920062b883644dc8f5734bcc6806bb.img",
"recovery_len": 15926572,
"recovery_hash": "db31ffe79dfd60be966fba6d1525a5081a920062b883644dc8f5734bcc6806bb"

View File

@@ -1,7 +1,7 @@
{
"ota_url": "https://commadist.azureedge.net/neosupdate/ota-signed-c4f56c62c5603c86e2ae9d83008a8d42a91319979661d0c42fb97b85d9112266.zip",
"ota_hash": "c4f56c62c5603c86e2ae9d83008a8d42a91319979661d0c42fb97b85d9112266",
"recovery_url": "https://commadist.azureedge.net/neosupdate/recovery-c5db3790c3b09756e8e896187ddb3f1258315eb0a86030468baa187b84a3bbf5.img",
"recovery_len": 15209772,
"recovery_hash": "c5db3790c3b09756e8e896187ddb3f1258315eb0a86030468baa187b84a3bbf5"
"ota_url": "https://commadist.azureedge.net/neosupdate/ota-signed-5dc2575d713977666a8e14ae1b43a04d7f63123934c80fa10751d949a107653e.zip",
"ota_hash": "5dc2575d713977666a8e14ae1b43a04d7f63123934c80fa10751d949a107653e",
"recovery_url": "https://commadist.azureedge.net/neosupdate/recovery-f01a55c9ba52ca57668d1684c6bf4118efd31916b04f8c1fcd8495013d3677eb.img",
"recovery_len": 15222060,
"recovery_hash": "f01a55c9ba52ca57668d1684c6bf4118efd31916b04f8c1fcd8495013d3677eb"
}

View File

@@ -0,0 +1,813 @@
#include <sys/stat.h>
#include <sys/statvfs.h>
#include <unistd.h>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <memory>
#include <mutex>
#include <sstream>
#include <string>
#include <thread>
#include <curl/curl.h>
#include <openssl/sha.h>
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <GLES3/gl3.h>
#include "nanovg.h"
#define NANOVG_GLES3_IMPLEMENTATION
#include "json11.hpp"
#include "nanovg_gl.h"
#include "nanovg_gl_utils.h"
#include "selfdrive/common/framebuffer.h"
#include "selfdrive/common/touch.h"
#include "selfdrive/common/util.h"
#define USER_AGENT "NEOSUpdater-0.2"
#define MANIFEST_URL_NEOS_STAGING "https://github.com/commaai/eon-neos/raw/master/update.staging.json"
#define MANIFEST_URL_NEOS_LOCAL "http://192.168.5.1:8000/neosupdate/update.local.json"
#define MANIFEST_URL_NEOS "https://github.com/commaai/eon-neos/raw/master/update.json"
const char *manifest_url = MANIFEST_URL_NEOS;
#define RECOVERY_DEV "/dev/block/bootdevice/by-name/recovery"
#define RECOVERY_COMMAND "/cache/recovery/command"
#define UPDATE_DIR "/data/neoupdate"
extern const uint8_t bin_opensans_regular[] asm("_binary_opensans_regular_ttf_start");
extern const uint8_t bin_opensans_regular_end[] asm("_binary_opensans_regular_ttf_end");
extern const uint8_t bin_opensans_semibold[] asm("_binary_opensans_semibold_ttf_start");
extern const uint8_t bin_opensans_semibold_end[] asm("_binary_opensans_semibold_ttf_end");
extern const uint8_t bin_opensans_bold[] asm("_binary_opensans_bold_ttf_start");
extern const uint8_t bin_opensans_bold_end[] asm("_binary_opensans_bold_ttf_end");
namespace {
std::string sha256_file(std::string fn, size_t limit=0) {
SHA256_CTX ctx;
SHA256_Init(&ctx);
FILE *file = fopen(fn.c_str(), "rb");
if (!file) return "";
const size_t buf_size = 8192;
std::unique_ptr<char[]> buffer( new char[ buf_size ] );
bool read_limit = (limit != 0);
while (true) {
size_t read_size = buf_size;
if (read_limit) read_size = std::min(read_size, limit);
size_t bytes_read = fread(buffer.get(), 1, read_size, file);
if (!bytes_read) break;
SHA256_Update(&ctx, buffer.get(), bytes_read);
if (read_limit) {
limit -= bytes_read;
if (limit == 0) break;
}
}
uint8_t hash[SHA256_DIGEST_LENGTH];
SHA256_Final(hash, &ctx);
fclose(file);
return util::tohex(hash, sizeof(hash));
}
size_t download_string_write(void *ptr, size_t size, size_t nmeb, void *up) {
size_t sz = size * nmeb;
((std::string*)up)->append((char*)ptr, sz);
return sz;
}
std::string download_string(CURL *curl, std::string url) {
std::string os;
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 0);
curl_easy_setopt(curl, CURLOPT_USERAGENT, USER_AGENT);
curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
curl_easy_setopt(curl, CURLOPT_RESUME_FROM, 0);
curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, download_string_write);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &os);
CURLcode res = curl_easy_perform(curl);
if (res != CURLE_OK) {
return "";
}
return os;
}
size_t download_file_write(void *ptr, size_t size, size_t nmeb, void *up) {
return fwrite(ptr, size, nmeb, (FILE*)up);
}
int battery_capacity() {
std::string bat_cap_s = util::read_file("/sys/class/power_supply/battery/capacity");
return atoi(bat_cap_s.c_str());
}
int battery_current() {
std::string current_now_s = util::read_file("/sys/class/power_supply/battery/current_now");
return atoi(current_now_s.c_str());
}
bool has_no_battery() {
if (FILE *file = fopen("/data/params/d/dp_no_batt", "r")) {
fclose(file);
std::string has_no_batt = util::read_file("/data/params/d/dp_no_batt");
return atoi(has_no_batt.c_str()) == 1;
} else {
return false;
}
}
bool check_battery() {
int bat_cap = battery_capacity();
int current_now = battery_current();
return (has_no_battery())? true : bat_cap > 35 || (current_now < 0 && bat_cap > 10);
}
bool check_space() {
struct statvfs stat;
if (statvfs("/data/", &stat) != 0) {
return false;
}
size_t space = stat.f_bsize * stat.f_bavail;
return space > 2000000000ULL; // 2GB
}
static void start_settings_activity(const char* name) {
char launch_cmd[1024];
snprintf(launch_cmd, sizeof(launch_cmd),
"am start -W --ez :settings:show_fragment_as_subsetting true -n 'com.android.settings/.%s'", name);
system(launch_cmd);
}
bool is_settings_active() {
FILE *fp;
char sys_output[4096];
fp = popen("/bin/dumpsys window windows", "r");
if (fp == NULL) {
return false;
}
bool active = false;
while (fgets(sys_output, sizeof(sys_output), fp) != NULL) {
if (strstr(sys_output, "mCurrentFocus=null") != NULL) {
break;
}
if (strstr(sys_output, "mCurrentFocus=Window") != NULL) {
active = true;
break;
}
}
pclose(fp);
return active;
}
struct Updater {
bool do_exit = false;
TouchState touch;
int fb_w, fb_h;
std::unique_ptr<FrameBuffer> fb;
NVGcontext *vg = NULL;
int font_regular;
int font_semibold;
int font_bold;
std::thread update_thread_handle;
std::mutex lock;
enum UpdateState {
CONFIRMATION,
LOW_BATTERY,
RUNNING,
ERROR,
};
UpdateState state;
std::string progress_text;
float progress_frac;
std::string error_text;
std::string low_battery_text;
std::string low_battery_title;
std::string low_battery_context;
std::string battery_cap_text;
int min_battery_cap = 35;
// button
int b_x, b_w, b_y, b_h;
int balt_x;
// download stage writes these for the installation stage
int recovery_len;
std::string recovery_hash;
std::string recovery_fn;
std::string ota_fn;
CURL *curl = NULL;
void ui_init() {
touch_init(&touch);
fb = std::make_unique<FrameBuffer>("updater", 0x00001000, false, &fb_w, &fb_h);
fb->set_power(HWC_POWER_MODE_NORMAL);
vg = nvgCreateGLES3(NVG_ANTIALIAS | NVG_STENCIL_STROKES | NVG_DEBUG);
assert(vg);
font_regular = nvgCreateFontMem(vg, "opensans_regular", (unsigned char*)bin_opensans_regular, (bin_opensans_regular_end - bin_opensans_regular), 0);
assert(font_regular >= 0);
font_semibold = nvgCreateFontMem(vg, "opensans_semibold", (unsigned char*)bin_opensans_semibold, (bin_opensans_semibold_end - bin_opensans_semibold), 0);
assert(font_semibold >= 0);
font_bold = nvgCreateFontMem(vg, "opensans_bold", (unsigned char*)bin_opensans_bold, (bin_opensans_bold_end - bin_opensans_bold), 0);
assert(font_bold >= 0);
b_w = 640;
balt_x = 200;
b_x = fb_w-b_w-200;
b_y = 720;
b_h = 220;
if (download_stage(true)) {
state = RUNNING;
update_thread_handle = std::thread(&Updater::run_stages, this);
} else {
state = CONFIRMATION;
}
}
int download_file_xferinfo(curl_off_t dltotal, curl_off_t dlno,
curl_off_t ultotal, curl_off_t ulnow) {
{
std::lock_guard<std::mutex> guard(lock);
if (dltotal != 0) {
progress_frac = (float) dlno / dltotal;
}
}
// printf("info: %ld %ld %f\n", dltotal, dlno, progress_frac);
return 0;
}
bool download_file(std::string url, std::string out_fn) {
FILE *of = fopen(out_fn.c_str(), "ab");
assert(of);
CURLcode res;
long last_resume_from = 0;
fseek(of, 0, SEEK_END);
int tries = 4;
bool ret = false;
while (true) {
long resume_from = ftell(of);
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 0);
curl_easy_setopt(curl, CURLOPT_USERAGENT, USER_AGENT);
curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
curl_easy_setopt(curl, CURLOPT_RESUME_FROM, resume_from);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, download_file_write);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, of);
curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
curl_easy_setopt(curl, CURLOPT_XFERINFODATA, this);
curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, &Updater::download_file_xferinfo);
CURLcode res = curl_easy_perform(curl);
long response_code = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
// double content_length = 0.0;
// curl_easy_getinfo(curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &content_length);
printf("download %s res %d, code %ld, resume from %ld\n", url.c_str(), res, response_code, resume_from);
if (res == CURLE_OK) {
ret = true;
break;
} else if (res == CURLE_HTTP_RETURNED_ERROR && response_code == 416) {
// failed because the file is already complete?
ret = true;
break;
} else if (resume_from == last_resume_from) {
// failed and dind't make make forward progress. only retry a couple times
tries--;
if (tries <= 0) {
break;
}
}
last_resume_from = resume_from;
}
// printf("res %d\n", res);
// printf("- %ld %f\n", response_code, content_length);
fclose(of);
return ret;
}
void set_progress(std::string text) {
std::lock_guard<std::mutex> guard(lock);
progress_text = text;
}
void set_error(std::string text) {
std::lock_guard<std::mutex> guard(lock);
error_text = text;
state = ERROR;
}
void set_battery_low() {
std::lock_guard<std::mutex> guard(lock);
state = LOW_BATTERY;
}
void set_running() {
std::lock_guard<std::mutex> guard(lock);
state = RUNNING;
}
std::string download(std::string url, std::string hash, std::string name, bool dry_run) {
std::string out_fn = UPDATE_DIR "/" + util::base_name(url);
std::string fn_hash = sha256_file(out_fn);
if (dry_run) {
return (hash.compare(fn_hash) != 0) ? "" : out_fn;
}
// start or resume downloading if hash doesn't match
if (hash.compare(fn_hash) != 0) {
set_progress("Downloading " + name + "...");
bool r = download_file(url, out_fn);
if (!r) {
set_error("failed to download " + name);
unlink(out_fn.c_str());
return "";
}
fn_hash = sha256_file(out_fn);
}
set_progress("Verifying " + name + "...");
printf("got %s hash: %s\n", name.c_str(), hash.c_str());
if (fn_hash != hash) {
set_error(name + " was corrupt");
unlink(out_fn.c_str());
return "";
}
return out_fn;
}
bool download_stage(bool dry_run = false) {
curl = curl_easy_init();
assert(curl);
// ** quick checks before download **
if (!check_space()) {
if (!dry_run) set_error("2GB of free space required to update");
return false;
}
mkdir(UPDATE_DIR, 0777);
set_progress("Finding latest version...");
std::string manifest_s = download_string(curl, manifest_url);
printf("manifest: %s\n", manifest_s.c_str());
std::string err;
auto manifest = json11::Json::parse(manifest_s, err);
if (manifest.is_null() || !err.empty()) {
set_error("failed to load update manifest");
return false;
}
std::string ota_url = manifest["ota_url"].string_value();
std::string ota_hash = manifest["ota_hash"].string_value();
std::string recovery_url = manifest["recovery_url"].string_value();
recovery_hash = manifest["recovery_hash"].string_value();
recovery_len = manifest["recovery_len"].int_value();
// std::string installer_url = manifest["installer_url"].string_value();
// std::string installer_hash = manifest["installer_hash"].string_value();
if (ota_url.empty() || ota_hash.empty()) {
set_error("invalid update manifest");
return false;
}
// std::string installer_fn = download(installer_url, installer_hash, "installer");
// if (installer_fn.empty()) {
// //error'd
// return;
// }
// ** handle recovery download **
if (recovery_url.empty() || recovery_hash.empty() || recovery_len == 0) {
set_progress("Skipping recovery flash...");
} else {
// only download the recovery if it differs from what's flashed
set_progress("Checking recovery...");
std::string existing_recovery_hash = sha256_file(RECOVERY_DEV, recovery_len);
printf("existing recovery hash: %s\n", existing_recovery_hash.c_str());
if (existing_recovery_hash != recovery_hash) {
recovery_fn = download(recovery_url, recovery_hash, "recovery", dry_run);
if (recovery_fn.empty()) {
// error'd
return false;
}
}
}
// ** handle ota download **
ota_fn = download(ota_url, ota_hash, "update", dry_run);
if (ota_fn.empty()) {
//error'd
return false;
}
// download sucessful
return true;
}
// thread that handles downloading and installing the update
void run_stages() {
printf("run_stages start\n");
// ** download update **
if (!check_battery()) {
set_battery_low();
int battery_cap = battery_capacity();
while(battery_cap < min_battery_cap) {
battery_cap = battery_capacity();
battery_cap_text = std::to_string(battery_cap);
util::sleep_for(1000);
}
set_running();
}
bool sucess = download_stage();
if (!sucess) {
return;
}
// ** install update **
if (!check_battery()) {
set_battery_low();
int battery_cap = battery_capacity();
while(battery_cap < min_battery_cap) {
battery_cap = battery_capacity();
battery_cap_text = std::to_string(battery_cap);
util::sleep_for(1000);
}
set_running();
}
if (!recovery_fn.empty()) {
// flash recovery
set_progress("Flashing recovery...");
FILE *flash_file = fopen(recovery_fn.c_str(), "rb");
if (!flash_file) {
set_error("failed to flash recovery");
return;
}
FILE *recovery_dev = fopen(RECOVERY_DEV, "w+b");
if (!recovery_dev) {
fclose(flash_file);
set_error("failed to flash recovery");
return;
}
const size_t buf_size = 4096;
std::unique_ptr<char[]> buffer( new char[ buf_size ] );
while (true) {
size_t bytes_read = fread(buffer.get(), 1, buf_size, flash_file);
if (!bytes_read) break;
size_t bytes_written = fwrite(buffer.get(), 1, bytes_read, recovery_dev);
if (bytes_read != bytes_written) {
fclose(recovery_dev);
fclose(flash_file);
set_error("failed to flash recovery: write failed");
return;
}
}
fclose(recovery_dev);
fclose(flash_file);
set_progress("Verifying flash...");
std::string new_recovery_hash = sha256_file(RECOVERY_DEV, recovery_len);
printf("new recovery hash: %s\n", new_recovery_hash.c_str());
if (new_recovery_hash != recovery_hash) {
set_error("recovery flash corrupted");
return;
}
}
// write arguments to recovery
FILE *cmd_file = fopen(RECOVERY_COMMAND, "wb");
if (!cmd_file) {
set_error("failed to reboot into recovery");
return;
}
fprintf(cmd_file, "--update_package=%s\n", ota_fn.c_str());
fclose(cmd_file);
set_progress("Rebooting");
// remove the continue.sh so we come back into the setup.
// maybe we should go directly into the installer, but what if we don't come back with internet? :/
//unlink("/data/data/com.termux/files/continue.sh");
// TODO: this should be generic between android versions
// IPowerManager.reboot(confirm=false, reason="recovery", wait=true)
system("service call power 16 i32 0 s16 recovery i32 1");
while (true) pause();
// execl("/system/bin/reboot", "recovery");
// set_error("failed to reboot into recovery");
}
void draw_ack_screen(const char *title, const char *message, const char *button, const char *altbutton) {
nvgFillColor(vg, nvgRGBA(255,255,255,255));
nvgTextAlign(vg, NVG_ALIGN_CENTER | NVG_ALIGN_BASELINE);
nvgFontFace(vg, "opensans_bold");
nvgFontSize(vg, 120.0f);
nvgTextBox(vg, 110, 220, fb_w-240, title, NULL);
nvgFontFace(vg, "opensans_regular");
nvgFontSize(vg, 86.0f);
nvgTextBox(vg, 130, 380, fb_w-260, message, NULL);
// draw button
if (button) {
nvgBeginPath(vg);
nvgFillColor(vg, nvgRGBA(8, 8, 8, 255));
nvgRoundedRect(vg, b_x, b_y, b_w, b_h, 20);
nvgFill(vg);
nvgFillColor(vg, nvgRGBA(255, 255, 255, 255));
nvgFontFace(vg, "opensans_semibold");
nvgTextAlign(vg, NVG_ALIGN_CENTER | NVG_ALIGN_MIDDLE);
nvgText(vg, b_x+b_w/2, b_y+b_h/2, button, NULL);
nvgBeginPath(vg);
nvgStrokeColor(vg, nvgRGBA(255, 255, 255, 50));
nvgStrokeWidth(vg, 5);
nvgRoundedRect(vg, b_x, b_y, b_w, b_h, 20);
nvgStroke(vg);
}
// draw button
if (altbutton) {
nvgBeginPath(vg);
nvgFillColor(vg, nvgRGBA(8, 8, 8, 255));
nvgRoundedRect(vg, balt_x, b_y, b_w, b_h, 20);
nvgFill(vg);
nvgFillColor(vg, nvgRGBA(255, 255, 255, 255));
nvgFontFace(vg, "opensans_semibold");
nvgTextAlign(vg, NVG_ALIGN_CENTER | NVG_ALIGN_MIDDLE);
nvgText(vg, balt_x+b_w/2, b_y+b_h/2, altbutton, NULL);
nvgBeginPath(vg);
nvgStrokeColor(vg, nvgRGBA(255, 255, 255, 50));
nvgStrokeWidth(vg, 5);
nvgRoundedRect(vg, balt_x, b_y, b_w, b_h, 20);
nvgStroke(vg);
}
}
void draw_battery_screen() {
low_battery_title = "Low Battery";
low_battery_text = "Please connect EON to your charger. Update will continue once EON battery reaches 35%.";
low_battery_context = "Current battery charge: " + battery_cap_text + "%";
nvgFillColor(vg, nvgRGBA(255,255,255,255));
nvgTextAlign(vg, NVG_ALIGN_CENTER | NVG_ALIGN_BASELINE);
nvgFontFace(vg, "opensans_bold");
nvgFontSize(vg, 120.0f);
nvgTextBox(vg, 110, 220, fb_w-240, low_battery_title.c_str(), NULL);
nvgFontFace(vg, "opensans_regular");
nvgFontSize(vg, 86.0f);
nvgTextBox(vg, 130, 380, fb_w-260, low_battery_text.c_str(), NULL);
nvgFontFace(vg, "opensans_bold");
nvgFontSize(vg, 86.0f);
nvgTextBox(vg, 130, 700, fb_w-260, low_battery_context.c_str(), NULL);
}
void draw_progress_screen() {
// draw progress message
nvgFontSize(vg, 64.0f);
nvgFillColor(vg, nvgRGBA(255,255,255,255));
nvgTextAlign(vg, NVG_ALIGN_CENTER | NVG_ALIGN_BASELINE);
nvgFontFace(vg, "opensans_bold");
nvgFontSize(vg, 86.0f);
nvgTextBox(vg, 0, 380, fb_w, progress_text.c_str(), NULL);
// draw progress bar
{
int progress_width = 1000;
int progress_x = fb_w/2-progress_width/2;
int progress_y = 520;
int progress_height = 50;
int powerprompt_y = 312;
nvgFontFace(vg, "opensans_regular");
nvgFontSize(vg, 64.0f);
nvgText(vg, fb_w/2, 740, "Ensure your device remains connected to a power source.", NULL);
NVGpaint paint = nvgBoxGradient(
vg, progress_x + 1, progress_y + 1,
progress_width - 2, progress_height, 3, 4, nvgRGB(27, 27, 27), nvgRGB(27, 27, 27));
nvgBeginPath(vg);
nvgRoundedRect(vg, progress_x, progress_y, progress_width, progress_height, 12);
nvgFillPaint(vg, paint);
nvgFill(vg);
float value = std::min(std::max(0.0f, progress_frac), 1.0f);
int bar_pos = ((progress_width - 2) * value);
paint = nvgBoxGradient(
vg, progress_x, progress_y,
bar_pos+1.5f, progress_height-1, 3, 4,
nvgRGB(245, 245, 245), nvgRGB(105, 105, 105));
nvgBeginPath(vg);
nvgRoundedRect(
vg, progress_x+1, progress_y+1,
bar_pos, progress_height-2, 12);
nvgFillPaint(vg, paint);
nvgFill(vg);
}
}
void ui_draw() {
std::lock_guard<std::mutex> guard(lock);
nvgBeginFrame(vg, fb_w, fb_h, 1.0f);
switch (state) {
case CONFIRMATION:
draw_ack_screen("An update to NEOS is required.",
"Your device will now be reset and upgraded. You may want to connect to wifi as download is around 1 GB. Existing data on device should not be lost.",
"Continue",
"Connect to WiFi");
break;
case LOW_BATTERY:
draw_battery_screen();
break;
case RUNNING:
draw_progress_screen();
break;
case ERROR:
draw_ack_screen("There was an error", (error_text).c_str(), NULL, "Reboot");
break;
}
nvgEndFrame(vg);
}
void ui_update() {
std::lock_guard<std::mutex> guard(lock);
if (state == ERROR || state == CONFIRMATION) {
int touch_x = -1, touch_y = -1;
int res = touch_poll(&touch, &touch_x, &touch_y, 0);
if (res == 1 && !is_settings_active()) {
if (touch_x >= b_x && touch_x < b_x+b_w && touch_y >= b_y && touch_y < b_y+b_h) {
if (state == CONFIRMATION) {
state = RUNNING;
update_thread_handle = std::thread(&Updater::run_stages, this);
}
}
if (touch_x >= balt_x && touch_x < balt_x+b_w && touch_y >= b_y && touch_y < b_y+b_h) {
if (state == CONFIRMATION) {
start_settings_activity("Settings$WifiSettingsActivity");
} else if (state == ERROR) {
do_exit = 1;
}
}
}
}
}
void go() {
ui_init();
while (!do_exit) {
ui_update();
glClearColor(0.08, 0.08, 0.08, 1.0);
glClear(GL_STENCIL_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
// background
nvgBeginPath(vg);
NVGpaint bg = nvgLinearGradient(vg, fb_w, 0, fb_w, fb_h,
nvgRGBA(0, 0, 0, 0), nvgRGBA(0, 0, 0, 255));
nvgFillPaint(vg, bg);
nvgRect(vg, 0, 0, fb_w, fb_h);
nvgFill(vg);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
ui_draw();
glDisable(GL_BLEND);
fb->swap();
assert(glGetError() == GL_NO_ERROR);
// no simple way to do 30fps vsync with surfaceflinger...
util::sleep_for(30);
}
if (update_thread_handle.joinable()) {
update_thread_handle.join();
}
// reboot
system("service call power 16 i32 0 i32 0 i32 1");
}
};
}
int main(int argc, char *argv[]) {
bool background_cache = false;
if (argc > 1) {
if (strcmp(argv[1], "local") == 0) {
manifest_url = MANIFEST_URL_NEOS_LOCAL;
} else if (strcmp(argv[1], "staging") == 0) {
manifest_url = MANIFEST_URL_NEOS_STAGING;
} else if (strcmp(argv[1], "bgcache") == 0) {
manifest_url = argv[2];
background_cache = true;
} else {
manifest_url = argv[1];
}
}
printf("updating from %s\n", manifest_url);
Updater updater;
int err = 0;
if (background_cache) {
err = !updater.download_stage();
} else {
updater.go();
}
return err;
}

View File

@@ -16,21 +16,27 @@ fi
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )"
function two_init {
if [ ! -f "/system/fonts/NotoSansTC-Regular.otf" ] || [ -L "/system/fonts/NotoSansTC-Regular.otf" ]; then
mount -o remount,rw /system
find /system/fonts/NotoSans*.otf -type l -delete
cp -frv /usr/share/fonts/NotoSans* /system/fonts/
cp -fr /data/openpilot/selfdrive/dragonpilot/fonts.xml /system/etc/fonts.xml
chmod 644 /system/etc/fonts.xml
chmod 644 /system/fonts/NotoSans*
mount -o remount,r /system
if [ -f "/sdcard/dp_patcher.py" ]; then
/data/data/com.termux/files/usr/bin/python /sdcard/dp_patcher.py
fi
/data/data/com.termux/files/usr/bin/python /data/openpilot/scripts/installers/font_installer.py
/data/data/com.termux/files/usr/bin/python /data/openpilot/scripts/installers/sshkey_installer.py
# Wifi scan
wpa_cli IFNAME=wlan0 SCAN
# set IO scheduler
setprop sys.io.scheduler noop
for f in /sys/block/*/queue/scheduler; do
echo noop > $f
done
# *** shield cores 2-3 ***
# TODO: should we enable this?
# offline cores 2-3 to force recurring timers onto the other cores
#echo 0 > /sys/devices/system/cpu/cpu2/online
#echo 0 > /sys/devices/system/cpu/cpu3/online
#echo 1 > /sys/devices/system/cpu/cpu2/online
#echo 1 > /sys/devices/system/cpu/cpu3/online
# android gets two cores
echo 0-1 > /dev/cpuset/background/cpus
echo 0-1 > /dev/cpuset/system-background/cpus
@@ -92,6 +98,9 @@ function two_init {
# disable bluetooth
service call bluetooth_manager 8
# wifi scan
wpa_cli IFNAME=wlan0 SCAN
# Check for NEOS update
if $(grep -q "letv" /proc/cmdline); then
if [ $(< /VERSION) != "$REQUIRED_NEOS_VERSION" ]; then
@@ -108,8 +117,6 @@ function two_init {
"$DIR/installer/updater/updater" "file://$DIR/installer/updater/update.json"
fi
else
echo -n 0 > /data/params/d/DisableUpdates
fi
# One-time fix for a subset of OP3T with gyro orientation offsets.
@@ -211,16 +218,26 @@ function launch {
tici_init
fi
if [ -f "/sdcard/dp_patcher.py" ]; then
/data/data/com.termux/files/usr/bin/python /sdcard/dp_patcher.py
fi
# write tmux scrollback to a file
tmux capture-pane -pq -S-1000 > /tmp/launch_log
# start manager
cd selfdrive/manager
./build.py && ./manager.py
if [ -f /EON ]; then
if [ ! -f "/system/comma/usr/lib/libgfortran.so.5.0.0" ]; then
mount -o remount,rw /system
tar -zxvf /data/openpilot/selfdrive/mapd/assets/libgfortran.tar.gz -C /system/comma/usr/lib/
mount -o remount,r /system
fi
if [ ! -d "/system/comma/usr/lib/python3.8/site-packages/opspline" ]; then
mount -o remount,rw /system
tar -zxvf /data/openpilot/selfdrive/mapd/assets/opspline.tar.gz -C /system/comma/usr/lib/python3.8/site-packages/
mount -o remount,r /system
fi
./build.py && ./manager.py
else
./custom_dep.py && ./build.py && ./manager.py
fi
# if broken, keep on screen error
while true; do sleep 1; done

View File

@@ -7,11 +7,11 @@ export OPENBLAS_NUM_THREADS=1
export VECLIB_MAXIMUM_THREADS=1
if [ -z "$REQUIRED_NEOS_VERSION" ]; then
export REQUIRED_NEOS_VERSION="17"
export REQUIRED_NEOS_VERSION="18"
fi
if [ -z "$AGNOS_VERSION" ]; then
export AGNOS_VERSION="1.2"
export AGNOS_VERSION="1.3"
fi
if [ -z "$PASSIVE" ]; then

Binary file not shown.

Binary file not shown.

View File

@@ -1 +0,0 @@
v1.7.5

View File

@@ -1,3 +1,9 @@
# flake8: noqa
# pylint: skip-file
from .python import Panda, PandaWifiStreaming, PandaDFU, flash_release, BASEDIR, ensure_st_up_to_date, PandaSerial
from .python import Panda, PandaWifiStreaming, PandaDFU, flash_release, \
BASEDIR, ensure_st_up_to_date, PandaSerial, \
DEFAULT_FW_FN, DEFAULT_H7_FW_FN, MCU_TYPE_H7, MCU_TYPE_F4
from .python.config import BOOTSTUB_ADDRESS, BLOCK_SIZE_FX, APP_ADDRESS_FX, \
BLOCK_SIZE_H7, APP_ADDRESS_H7, DEVICE_SERIAL_NUMBER_ADDR_H7, \
DEVICE_SERIAL_NUMBER_ADDR_FX

View File

@@ -8,6 +8,7 @@ if os.getenv("PEDAL"):
PROJECT = "pedal"
STARTUP_FILE = "stm32fx/startup_stm32f205xx.s"
LINKER_SCRIPT = "stm32fx/stm32fx_flash.ld"
APP_START_ADDRESS = "0x8004000"
MAIN = "pedal/main.c"
PROJECT_FLAGS = [
"-mcpu=cortex-m3",
@@ -18,12 +19,32 @@ if os.getenv("PEDAL"):
"-DPEDAL",
]
if os.getenv("PEDAL_USB"):
PROJECT = "pedal_usb"
PROJECT_FLAGS.append("-DPEDAL_USB")
elif os.getenv("PANDA_H7"):
PROJECT = "panda_h7"
STARTUP_FILE = "stm32h7/startup_stm32h7x5xx.s"
LINKER_SCRIPT = "stm32h7/stm32h7x5_flash.ld"
APP_START_ADDRESS = "0x8020000"
MAIN = "main.c"
PROJECT_FLAGS = [
"-mcpu=cortex-m7",
"-mhard-float",
"-DSTM32H7",
"-DSTM32H725xx",
"-mfpu=fpv5-d16",
"-fsingle-precision-constant",
"-Os",
"-g",
"-DPANDA",
]
else:
PROJECT = "panda"
STARTUP_FILE = "stm32fx/startup_stm32f413xx.s"
LINKER_SCRIPT = "stm32fx/stm32fx_flash.ld"
APP_START_ADDRESS = "0x8004000"
MAIN = "main.c"
PROJECT_FLAGS = [
"-mcpu=cortex-m4",
@@ -42,20 +63,13 @@ else:
if (int(f.read().strip())) == 1:
PROJECT_FLAGS += ['-Dvw']
if FindFile('dp_panda_fake_black', '/data/params/d') != None:
with open('/data/params/d/dp_panda_fake_black') as f:
if (int(f.read().strip())) == 1:
PROJECT_FLAGS += ['-Dfake_black_panda']
def get_version(builder, build_type):
version_file = File('../VERSION').srcnode().abspath
version = open(version_file).read()
try:
git = subprocess.check_output(["git", "rev-parse", "--short=8", "HEAD"], encoding='utf8').strip()
except subprocess.CalledProcessError:
git = "unknown"
return f"{version}-{builder}-{git}-{build_type}"
return f"{builder}-{git}-{build_type}"
def to_c_uint32(x):
@@ -120,6 +134,7 @@ else:
includes = [
"stm32fx/inc",
"stm32h7/inc",
"..",
".",
]
@@ -160,7 +175,7 @@ bootstub_bin = panda_env.Objcopy(f"obj/bootstub.{PROJECT}.bin", bootstub_elf)
# Build main
main_elf = panda_env.Program(f"obj/{PROJECT}.elf", [startup, MAIN],
LINKFLAGS=["-Wl,--section-start,.isr_vector=0x8004000"] + flags)
LINKFLAGS=[f"-Wl,--section-start,.isr_vector={APP_START_ADDRESS}"] + flags)
main_bin = panda_env.Objcopy(f"obj/{PROJECT}.bin", main_elf)
# Sign main

View File

@@ -127,41 +127,11 @@ void black_set_can_mode(uint8_t mode){
}
}
void black_usb_power_mode_tick(uint32_t uptime){
UNUSED(uptime);
// Not applicable
}
bool black_check_ignition(void){
// ignition is checked through harness
return harness_check_ignition();
}
uint32_t black_read_current(void){
// No current sense on black panda
return 0U;
}
void black_set_ir_power(uint8_t percentage){
UNUSED(percentage);
}
void black_set_fan_power(uint8_t percentage){
UNUSED(percentage);
}
void black_set_phone_power(bool enabled){
UNUSED(enabled);
}
void black_set_clock_source_mode(uint8_t mode){
UNUSED(mode);
}
void black_set_siren(bool enabled){
UNUSED(enabled);
}
void black_init(void) {
common_init_gpio();
@@ -244,12 +214,12 @@ const board board_black = {
.set_usb_power_mode = black_set_usb_power_mode,
.set_gps_mode = black_set_gps_mode,
.set_can_mode = black_set_can_mode,
.usb_power_mode_tick = black_usb_power_mode_tick,
.usb_power_mode_tick = unused_usb_power_mode_tick,
.check_ignition = black_check_ignition,
.read_current = black_read_current,
.set_fan_power = black_set_fan_power,
.set_ir_power = black_set_ir_power,
.set_phone_power = black_set_phone_power,
.set_clock_source_mode = black_set_clock_source_mode,
.set_siren = black_set_siren
.read_current = unused_read_current,
.set_fan_power = unused_set_fan_power,
.set_ir_power = unused_set_ir_power,
.set_phone_power = unused_set_phone_power,
.set_clock_source_mode = unused_set_clock_source_mode,
.set_siren = unused_set_siren
};

View File

@@ -49,6 +49,7 @@ struct board {
#define HW_TYPE_PEDAL 4U
#define HW_TYPE_UNO 5U
#define HW_TYPE_DOS 6U
#define HW_TYPE_RED_PANDA 7U
// LED colors
#define LED_RED 0U

View File

@@ -49,18 +49,10 @@ void dos_set_led(uint8_t color, bool enabled) {
}
}
void dos_set_gps_load_switch(bool enabled) {
UNUSED(enabled);
}
void dos_set_bootkick(bool enabled){
set_gpio_output(GPIOC, 4, !enabled);
}
void dos_set_phone_power(bool enabled){
UNUSED(enabled);
}
void dos_set_usb_power_mode(uint8_t mode) {
bool valid = false;
switch (mode) {
@@ -81,10 +73,6 @@ void dos_set_usb_power_mode(uint8_t mode) {
}
}
void dos_set_gps_mode(uint8_t mode) {
UNUSED(mode);
}
void dos_set_can_mode(uint8_t mode){
switch (mode) {
case CAN_MODE_NORMAL:
@@ -113,10 +101,6 @@ void dos_set_can_mode(uint8_t mode){
}
}
void dos_usb_power_mode_tick(uint32_t uptime){
UNUSED(uptime);
}
bool dos_check_ignition(void){
// ignition is checked through harness
return harness_check_ignition();
@@ -136,11 +120,6 @@ void dos_set_fan_power(uint8_t percentage){
fan_set_power(percentage);
}
uint32_t dos_read_current(void){
// No current sense on Dos
return 0U;
}
void dos_set_clock_source_mode(uint8_t mode){
clock_source_init(mode);
}
@@ -235,14 +214,14 @@ const board board_dos = {
.enable_can_transceivers = dos_enable_can_transceivers,
.set_led = dos_set_led,
.set_usb_power_mode = dos_set_usb_power_mode,
.set_gps_mode = dos_set_gps_mode,
.set_gps_mode = unused_set_gps_mode,
.set_can_mode = dos_set_can_mode,
.usb_power_mode_tick = dos_usb_power_mode_tick,
.usb_power_mode_tick = unused_usb_power_mode_tick,
.check_ignition = dos_check_ignition,
.read_current = dos_read_current,
.read_current = unused_read_current,
.set_fan_power = dos_set_fan_power,
.set_ir_power = dos_set_ir_power,
.set_phone_power = dos_set_phone_power,
.set_phone_power = unused_set_phone_power,
.set_clock_source_mode = dos_set_clock_source_mode,
.set_siren = dos_set_siren
};

View File

@@ -48,12 +48,12 @@ const board board_grey = {
.set_usb_power_mode = white_set_usb_power_mode,
.set_gps_mode = grey_set_gps_mode,
.set_can_mode = white_set_can_mode,
.usb_power_mode_tick = white_usb_power_mode_tick,
.usb_power_mode_tick = unused_usb_power_mode_tick,
.check_ignition = white_check_ignition,
.read_current = white_read_current,
.set_fan_power = white_set_fan_power,
.set_ir_power = white_set_ir_power,
.set_phone_power = white_set_phone_power,
.set_clock_source_mode = white_set_clock_source_mode,
.set_siren = white_set_siren
.set_fan_power = unused_set_fan_power,
.set_ir_power = unused_set_ir_power,
.set_phone_power = unused_set_phone_power,
.set_clock_source_mode = unused_set_clock_source_mode,
.set_siren = unused_set_siren
};

View File

@@ -50,41 +50,11 @@ void pedal_set_can_mode(uint8_t mode){
}
}
void pedal_usb_power_mode_tick(uint32_t uptime){
UNUSED(uptime);
// Not applicable
}
bool pedal_check_ignition(void){
// not supported on pedal
return false;
}
uint32_t pedal_read_current(void){
// No current sense on pedal
return 0U;
}
void pedal_set_ir_power(uint8_t percentage){
UNUSED(percentage);
}
void pedal_set_fan_power(uint8_t percentage){
UNUSED(percentage);
}
void pedal_set_phone_power(bool enabled){
UNUSED(enabled);
}
void pedal_set_clock_source_mode(uint8_t mode){
UNUSED(mode);
}
void pedal_set_siren(bool enabled){
UNUSED(enabled);
}
void pedal_init(void) {
common_init_gpio();
@@ -121,12 +91,12 @@ const board board_pedal = {
.set_usb_power_mode = pedal_set_usb_power_mode,
.set_gps_mode = pedal_set_gps_mode,
.set_can_mode = pedal_set_can_mode,
.usb_power_mode_tick = pedal_usb_power_mode_tick,
.usb_power_mode_tick = unused_usb_power_mode_tick,
.check_ignition = pedal_check_ignition,
.read_current = pedal_read_current,
.set_fan_power = pedal_set_fan_power,
.set_ir_power = pedal_set_ir_power,
.set_phone_power = pedal_set_phone_power,
.set_clock_source_mode = pedal_set_clock_source_mode,
.set_siren = pedal_set_siren
.read_current = unused_read_current,
.set_fan_power = unused_set_fan_power,
.set_ir_power = unused_set_ir_power,
.set_phone_power = unused_set_phone_power,
.set_clock_source_mode = unused_set_clock_source_mode,
.set_siren = unused_set_siren
};

202
panda/board/boards/red.h Normal file
View File

@@ -0,0 +1,202 @@
// ///////////////////// //
// Red Panda + Harness //
// ///////////////////// //
void red_enable_can_transceiver(uint8_t transceiver, bool enabled) {
switch (transceiver) {
case 1U:
set_gpio_output(GPIOG, 11, !enabled);
break;
case 2U:
set_gpio_output(GPIOB, 3, !enabled);
break;
case 3U:
set_gpio_output(GPIOD, 7, !enabled);
break;
case 4U:
set_gpio_output(GPIOB, 4, !enabled);
break;
default:
break;
}
}
void red_enable_can_transceivers(bool enabled) {
uint8_t main_bus = (car_harness_status == HARNESS_STATUS_FLIPPED) ? 3U : 1U;
for (uint8_t i=1U; i<=4U; i++) {
// Leave main CAN always on for CAN-based ignition detection
if (i == main_bus) {
red_enable_can_transceiver(i, true);
} else {
red_enable_can_transceiver(i, enabled);
}
}
}
void red_set_led(uint8_t color, bool enabled) {
switch (color) {
case LED_RED:
set_gpio_output(GPIOE, 4, !enabled);
break;
case LED_GREEN:
set_gpio_output(GPIOE, 3, !enabled);
break;
case LED_BLUE:
set_gpio_output(GPIOE, 2, !enabled);
break;
default:
break;
}
}
void red_set_usb_load_switch(bool enabled) {
set_gpio_output(GPIOB, 14, !enabled);
}
void red_set_usb_power_mode(uint8_t mode) {
bool valid = false;
switch (mode) {
case USB_POWER_CLIENT:
red_set_usb_load_switch(false);
valid = true;
break;
case USB_POWER_CDP:
red_set_usb_load_switch(true);
valid = true;
break;
default:
break;
}
if (valid) {
usb_power_mode = mode;
}
}
void red_set_can_mode(uint8_t mode) {
switch (mode) {
case CAN_MODE_NORMAL:
case CAN_MODE_OBD_CAN2:
if ((bool)(mode == CAN_MODE_NORMAL) != (bool)(car_harness_status == HARNESS_STATUS_FLIPPED)) {
// B12,B13: disable normal mode
set_gpio_pullup(GPIOB, 12, PULL_NONE);
set_gpio_mode(GPIOB, 12, MODE_ANALOG);
set_gpio_pullup(GPIOB, 13, PULL_NONE);
set_gpio_mode(GPIOB, 13, MODE_ANALOG);
// B5,B6: FDCAN2 mode
set_gpio_pullup(GPIOB, 5, PULL_NONE);
set_gpio_alternate(GPIOB, 5, GPIO_AF9_FDCAN2);
set_gpio_pullup(GPIOB, 6, PULL_NONE);
set_gpio_alternate(GPIOB, 6, GPIO_AF9_FDCAN2);
} else {
// B5,B6: disable normal mode
set_gpio_pullup(GPIOB, 5, PULL_NONE);
set_gpio_mode(GPIOB, 5, MODE_ANALOG);
set_gpio_pullup(GPIOB, 6, PULL_NONE);
set_gpio_mode(GPIOB, 6, MODE_ANALOG);
// B12,B13: FDCAN2 mode
set_gpio_pullup(GPIOB, 12, PULL_NONE);
set_gpio_alternate(GPIOB, 12, GPIO_AF9_FDCAN2);
set_gpio_pullup(GPIOB, 13, PULL_NONE);
set_gpio_alternate(GPIOB, 13, GPIO_AF9_FDCAN2);
}
break;
default:
break;
}
}
bool red_check_ignition(void) {
// ignition is checked through harness
return harness_check_ignition();
}
void red_init(void) {
common_init_gpio();
//C4,A1: OBD_SBU1, OBD_SBU2
set_gpio_pullup(GPIOC, 4, PULL_NONE);
set_gpio_mode(GPIOC, 4, MODE_ANALOG);
set_gpio_pullup(GPIOA, 1, PULL_NONE);
set_gpio_mode(GPIOA, 1, MODE_ANALOG);
//C10,C11 : OBD_SBU1_RELAY, OBD_SBU2_RELAY
set_gpio_output_type(GPIOC, 10, OUTPUT_TYPE_OPEN_DRAIN);
set_gpio_pullup(GPIOC, 10, PULL_NONE);
set_gpio_mode(GPIOC, 10, MODE_OUTPUT);
set_gpio_output(GPIOC, 10, 1);
set_gpio_output_type(GPIOC, 11, OUTPUT_TYPE_OPEN_DRAIN);
set_gpio_pullup(GPIOC, 11, PULL_NONE);
set_gpio_mode(GPIOC, 11, MODE_OUTPUT);
set_gpio_output(GPIOC, 11, 1);
// Turn on USB load switch.
red_set_usb_load_switch(true);
// Set right power mode
red_set_usb_power_mode(USB_POWER_CDP);
// Initialize harness
harness_init();
// Enable CAN transceivers
red_enable_can_transceivers(true);
// Disable LEDs
red_set_led(LED_RED, false);
red_set_led(LED_GREEN, false);
red_set_led(LED_BLUE, false);
// Set normal CAN mode
red_set_can_mode(CAN_MODE_NORMAL);
// flip CAN0 and CAN2 if we are flipped
if (car_harness_status == HARNESS_STATUS_FLIPPED) {
can_flip_buses(0, 2);
}
}
const harness_configuration red_harness_config = {
.has_harness = true,
.GPIO_SBU1 = GPIOC,
.GPIO_SBU2 = GPIOA,
.GPIO_relay_SBU1 = GPIOC,
.GPIO_relay_SBU2 = GPIOC,
.pin_SBU1 = 4,
.pin_SBU2 = 1,
.pin_relay_SBU1 = 10,
.pin_relay_SBU2 = 11,
.adc_channel_SBU1 = 4, //ADC12_INP4
.adc_channel_SBU2 = 17 //ADC1_INP17
};
const board board_red = {
.board_type = "Red",
.harness_config = &red_harness_config,
.has_gps = false,
.has_hw_gmlan = false,
.has_obd = true,
.has_lin = false,
.has_rtc = false,
.init = red_init,
.enable_can_transceiver = red_enable_can_transceiver,
.enable_can_transceivers = red_enable_can_transceivers,
.set_led = red_set_led,
.set_usb_power_mode = red_set_usb_power_mode,
.set_gps_mode = unused_set_gps_mode,
.set_can_mode = red_set_can_mode,
.usb_power_mode_tick = unused_usb_power_mode_tick,
.check_ignition = red_check_ignition,
.read_current = unused_read_current,
.set_fan_power = unused_set_fan_power,
.set_ir_power = unused_set_ir_power,
.set_phone_power = unused_set_phone_power,
.set_clock_source_mode = unused_set_clock_source_mode,
.set_siren = unused_set_siren
};

View File

@@ -170,19 +170,6 @@ void uno_set_fan_power(uint8_t percentage){
fan_set_power(percentage);
}
uint32_t uno_read_current(void){
// No current sense on Uno
return 0U;
}
void uno_set_clock_source_mode(uint8_t mode){
UNUSED(mode);
}
void uno_set_siren(bool enabled){
UNUSED(enabled);
}
void uno_init(void) {
common_init_gpio();
@@ -289,10 +276,10 @@ const board board_uno = {
.set_can_mode = uno_set_can_mode,
.usb_power_mode_tick = uno_usb_power_mode_tick,
.check_ignition = uno_check_ignition,
.read_current = uno_read_current,
.read_current = unused_read_current,
.set_fan_power = uno_set_fan_power,
.set_ir_power = uno_set_ir_power,
.set_phone_power = uno_set_phone_power,
.set_clock_source_mode = uno_set_clock_source_mode,
.set_siren = uno_set_siren
.set_clock_source_mode = unused_set_clock_source_mode,
.set_siren = unused_set_siren
};

View File

@@ -0,0 +1,31 @@
void unused_set_gps_mode(uint8_t mode) {
UNUSED(mode);
}
void unused_usb_power_mode_tick(uint32_t uptime) {
UNUSED(uptime);
}
void unused_set_ir_power(uint8_t percentage) {
UNUSED(percentage);
}
void unused_set_fan_power(uint8_t percentage) {
UNUSED(percentage);
}
void unused_set_phone_power(bool enabled) {
UNUSED(enabled);
}
void unused_set_clock_source_mode(uint8_t mode) {
UNUSED(mode);
}
void unused_set_siren(bool enabled) {
UNUSED(enabled);
}
uint32_t unused_read_current(void) {
return 0U;
}

View File

@@ -151,35 +151,11 @@ uint32_t white_read_current(void){
return adc_get(ADCCHAN_CURRENT);
}
void white_usb_power_mode_tick(uint32_t uptime){
UNUSED(uptime);
}
void white_set_ir_power(uint8_t percentage){
UNUSED(percentage);
}
void white_set_fan_power(uint8_t percentage){
UNUSED(percentage);
}
bool white_check_ignition(void){
// ignition is on PA1
return !get_gpio_input(GPIOA, 1);
}
void white_set_phone_power(bool enabled){
UNUSED(enabled);
}
void white_set_clock_source_mode(uint8_t mode){
UNUSED(mode);
}
void white_set_siren(bool enabled){
UNUSED(enabled);
}
void white_grey_common_init(void) {
common_init_gpio();
@@ -277,12 +253,12 @@ const board board_white = {
.set_usb_power_mode = white_set_usb_power_mode,
.set_gps_mode = white_set_gps_mode,
.set_can_mode = white_set_can_mode,
.usb_power_mode_tick = white_usb_power_mode_tick,
.usb_power_mode_tick = unused_usb_power_mode_tick,
.check_ignition = white_check_ignition,
.read_current = white_read_current,
.set_fan_power = white_set_fan_power,
.set_ir_power = white_set_ir_power,
.set_phone_power = white_set_phone_power,
.set_clock_source_mode = white_set_clock_source_mode,
.set_siren = white_set_siren
.set_fan_power = unused_set_fan_power,
.set_ir_power = unused_set_ir_power,
.set_phone_power = unused_set_phone_power,
.set_clock_source_mode = unused_set_clock_source_mode,
.set_siren = unused_set_siren
};

View File

@@ -17,7 +17,7 @@
#include "obj/cert.h"
#include "obj/gitversion.h"
#include "spi_flasher.h"
#include "flasher.h"
void __initialize_hardware_early(void) {
early_initialization();

7
panda/board/build_all.sh Executable file
View File

@@ -0,0 +1,7 @@
#!/usr/bin/env sh
set -e
scons -u
PANDA_H7=1 scons -u
PEDAL=1 scons -u
PEDAL=1 PEDAL_USB=1 scons -u

View File

@@ -34,7 +34,21 @@
#define MAX_RESP_LEN 0x40U
#define GET_BUS(msg) (((msg)->RDTR >> 4) & 0xFF)
#define GET_LEN(msg) ((msg)->RDTR & 0xF)
#define GET_ADDR(msg) ((((msg)->RIR & 4) != 0) ? ((msg)->RIR >> 3) : ((msg)->RIR >> 21))
#define GET_BYTE(msg, b) (((int)(b) > 3) ? (((msg)->RDHR >> (8U * ((unsigned int)(b) % 4U))) & 0xFFU) : (((msg)->RDLR >> (8U * (unsigned int)(b))) & 0xFFU))
#define GET_BYTES_04(msg) ((msg)->RDLR)
#define GET_BYTES_48(msg) ((msg)->RDHR)
#define GET_FLAG(value, mask) (((__typeof__(mask))(value) & (mask)) == (mask))
#define CAN_INIT_TIMEOUT_MS 500U
#include <stdbool.h>
#include "stm32fx/stm32fx_config.h"
#ifdef STM32H7
#include "stm32h7/stm32h7_config.h"
#else
#include "stm32fx/stm32fx_config.h"
#endif
#endif

View File

@@ -2,163 +2,7 @@
// CAN2_TX, CAN2_RX0, CAN2_SCE
// CAN3_TX, CAN3_RX0, CAN3_SCE
typedef struct {
volatile uint32_t w_ptr;
volatile uint32_t r_ptr;
uint32_t fifo_size;
CAN_FIFOMailBox_TypeDef *elems;
} can_ring;
#define CAN_BUS_RET_FLAG 0x80U
#define CAN_BUS_NUM_MASK 0x7FU
#define BUS_MAX 4U
uint32_t can_rx_errs = 0;
uint32_t can_send_errs = 0;
uint32_t can_fwd_errs = 0;
uint32_t gmlan_send_errs = 0;
extern int can_live;
extern int pending_can_live;
// must reinit after changing these
extern int can_loopback;
extern int can_silent;
extern uint32_t can_speed[4];
void can_set_forwarding(int from, int to);
bool can_init(uint8_t can_number);
void can_init_all(void);
bool can_tx_check_min_slots_free(uint32_t min);
void can_send(CAN_FIFOMailBox_TypeDef *to_push, uint8_t bus_number, bool skip_tx_hook);
bool can_pop(can_ring *q, CAN_FIFOMailBox_TypeDef *elem);
// Ignition detected from CAN meessages
bool ignition_can = false;
bool ignition_cadillac = false;
uint32_t ignition_can_cnt = 0U;
// end API
#define ALL_CAN_SILENT 0xFF
#define ALL_CAN_LIVE 0
int can_live = 0;
int pending_can_live = 0;
int can_loopback = 0;
int 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)
can_buffer(tx3_q, 0x100)
can_buffer(txgmlan_q, 0x100)
// FIXME:
// cppcheck-suppress misra-c2012-9.3
can_ring *can_queues[] = {&can_tx1_q, &can_tx2_q, &can_tx3_q, &can_txgmlan_q};
// global CAN stats
int can_rx_cnt = 0;
int can_tx_cnt = 0;
int can_txd_cnt = 0;
int can_err_cnt = 0;
int can_overflow_cnt = 0;
// ********************* interrupt safe queue *********************
bool can_pop(can_ring *q, CAN_FIFOMailBox_TypeDef *elem) {
bool ret = 0;
ENTER_CRITICAL();
if (q->w_ptr != q->r_ptr) {
*elem = q->elems[q->r_ptr];
if ((q->r_ptr + 1U) == q->fifo_size) {
q->r_ptr = 0;
} else {
q->r_ptr += 1U;
}
ret = 1;
}
EXIT_CRITICAL();
return ret;
}
bool can_push(can_ring *q, CAN_FIFOMailBox_TypeDef *elem) {
bool ret = false;
uint32_t next_w_ptr;
ENTER_CRITICAL();
if ((q->w_ptr + 1U) == q->fifo_size) {
next_w_ptr = 0;
} else {
next_w_ptr = q->w_ptr + 1U;
}
if (next_w_ptr != q->r_ptr) {
q->elems[q->w_ptr] = *elem;
q->w_ptr = next_w_ptr;
ret = true;
}
EXIT_CRITICAL();
if (!ret) {
can_overflow_cnt++;
#ifdef DEBUG
puts("can_push failed!\n");
#endif
}
return ret;
}
uint32_t can_slots_empty(can_ring *q) {
uint32_t ret = 0;
ENTER_CRITICAL();
if (q->w_ptr >= q->r_ptr) {
ret = q->fifo_size - 1U - q->w_ptr + q->r_ptr;
} else {
ret = q->r_ptr - q->w_ptr - 1U;
}
EXIT_CRITICAL();
return ret;
}
void can_clear(can_ring *q) {
ENTER_CRITICAL();
q->w_ptr = 0;
q->r_ptr = 0;
EXIT_CRITICAL();
}
// 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.
// Panda: Bus 0=CAN1 Bus 1=CAN2 Bus 2=CAN3
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 3U
#define CANIF_FROM_CAN_NUM(num) (cans[num])
#define CAN_NUM_FROM_CANIF(CAN) ((CAN)==CAN1 ? 0 : ((CAN) == CAN2 ? 1 : 2))
#define BUS_NUM_FROM_CAN_NUM(num) (bus_lookup[num])
#define CAN_NUM_FROM_BUS_NUM(num) (can_num_lookup[num])
void process_can(uint8_t can_number);
bool can_set_speed(uint8_t can_number) {
bool ret = true;
@@ -169,22 +13,6 @@ bool can_set_speed(uint8_t can_number) {
return ret;
}
void can_init_all(void) {
bool ret = true;
for (uint8_t i=0U; i < CAN_MAX; i++) {
can_clear(can_queues[i]);
ret &= can_init(i);
}
UNUSED(ret);
}
void can_flip_buses(uint8_t bus1, uint8_t bus2){
bus_lookup[bus1] = bus2;
bus_lookup[bus2] = bus1;
can_num_lookup[bus1] = bus2;
can_num_lookup[bus2] = bus1;
}
// TODO: Cleanup with new abstraction
void can_set_gmlan(uint8_t bus) {
if(current_board->has_hw_gmlan){
@@ -323,34 +151,6 @@ void process_can(uint8_t can_number) {
}
}
void ignition_can_hook(CAN_FIFOMailBox_TypeDef *to_push) {
int bus = GET_BUS(to_push);
int addr = GET_ADDR(to_push);
int len = GET_LEN(to_push);
ignition_can_cnt = 0U; // reset counter
if (bus == 0) {
// TODO: verify on all supported GM models that we can reliably detect ignition using only this signal,
// since the 0x1F1 signal can briefly go low immediately after ignition
if ((addr == 0x160) && (len == 5)) {
// this message isn't all zeros when ignition is on
ignition_cadillac = GET_BYTES_04(to_push) != 0;
}
// GM exception
if ((addr == 0x1F1) && (len == 8)) {
// Bit 5 is ignition "on"
bool ignition_gm = ((GET_BYTE(to_push, 0) & 0x20) != 0);
ignition_can = ignition_gm || ignition_cadillac;
}
// Tesla exception
if ((addr == 0x348) && (len == 8)) {
// GTW_status
ignition_can = (GET_BYTE(to_push, 0) & 0x1) != 0;
}
}
}
// CAN receive handlers
// blink blue when we are receiving CAN messages
void can_rx(uint8_t can_number) {
@@ -406,34 +206,6 @@ void CAN3_TX_IRQ_Handler(void) { process_can(2); }
void CAN3_RX0_IRQ_Handler(void) { can_rx(2); }
void CAN3_SCE_IRQ_Handler(void) { can_sce(CAN3); }
bool can_tx_check_min_slots_free(uint32_t min) {
return
(can_slots_empty(&can_tx1_q) >= min) &&
(can_slots_empty(&can_tx2_q) >= min) &&
(can_slots_empty(&can_tx3_q) >= min) &&
(can_slots_empty(&can_txgmlan_q) >= min);
}
void can_send(CAN_FIFOMailBox_TypeDef *to_push, uint8_t bus_number, bool skip_tx_hook) {
if (skip_tx_hook || safety_tx_hook(to_push) != 0) {
if (bus_number < BUS_MAX) {
// add CAN packet to send queue
// bus number isn't passed through
to_push->RDTR &= 0xF;
if ((bus_number == 3U) && (can_num_lookup[3] == 0xFFU)) {
gmlan_send_errs += bitbang_gmlan(to_push) ? 0U : 1U;
} else {
can_fwd_errs += can_push(can_queues[bus_number], to_push) ? 0U : 1U;
process_can(CAN_NUM_FROM_BUS_NUM(bus_number));
}
}
}
}
void can_set_forwarding(int from, int to) {
can_forwarding[from] = to;
}
bool can_init(uint8_t can_number) {
bool ret = false;

View File

@@ -0,0 +1,222 @@
typedef struct {
volatile uint32_t w_ptr;
volatile uint32_t r_ptr;
uint32_t fifo_size;
CAN_FIFOMailBox_TypeDef *elems;
} can_ring;
#define CAN_BUS_RET_FLAG 0x80U
#define CAN_BUS_NUM_MASK 0x7FU
#define BUS_MAX 4U
uint32_t can_rx_errs = 0;
uint32_t can_send_errs = 0;
uint32_t can_fwd_errs = 0;
uint32_t gmlan_send_errs = 0;
extern int can_live;
extern int pending_can_live;
// must reinit after changing these
extern int can_loopback;
extern int can_silent;
extern uint32_t can_speed[4];
extern uint32_t can_data_speed[3];
// Ignition detected from CAN meessages
bool ignition_can = false;
bool ignition_cadillac = false;
uint32_t ignition_can_cnt = 0U;
#define ALL_CAN_SILENT 0xFF
#define ALL_CAN_LIVE 0
int can_live = 0;
int pending_can_live = 0;
int can_loopback = 0;
int can_silent = ALL_CAN_SILENT;
// ******************* functions prototypes *********************
bool can_init(uint8_t can_number);
void process_can(uint8_t can_number);
// ********************* 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)
can_buffer(tx3_q, 0x100)
can_buffer(txgmlan_q, 0x100)
// FIXME:
// cppcheck-suppress misra-c2012-9.3
can_ring *can_queues[] = {&can_tx1_q, &can_tx2_q, &can_tx3_q, &can_txgmlan_q};
// global CAN stats
int can_rx_cnt = 0;
int can_tx_cnt = 0;
int can_txd_cnt = 0;
int can_err_cnt = 0;
int can_overflow_cnt = 0;
// ********************* interrupt safe queue *********************
bool can_pop(can_ring *q, CAN_FIFOMailBox_TypeDef *elem) {
bool ret = 0;
ENTER_CRITICAL();
if (q->w_ptr != q->r_ptr) {
*elem = q->elems[q->r_ptr];
if ((q->r_ptr + 1U) == q->fifo_size) {
q->r_ptr = 0;
} else {
q->r_ptr += 1U;
}
ret = 1;
}
EXIT_CRITICAL();
return ret;
}
bool can_push(can_ring *q, CAN_FIFOMailBox_TypeDef *elem) {
bool ret = false;
uint32_t next_w_ptr;
ENTER_CRITICAL();
if ((q->w_ptr + 1U) == q->fifo_size) {
next_w_ptr = 0;
} else {
next_w_ptr = q->w_ptr + 1U;
}
if (next_w_ptr != q->r_ptr) {
q->elems[q->w_ptr] = *elem;
q->w_ptr = next_w_ptr;
ret = true;
}
EXIT_CRITICAL();
if (!ret) {
can_overflow_cnt++;
#ifdef DEBUG
puts("can_push failed!\n");
#endif
}
return ret;
}
uint32_t can_slots_empty(can_ring *q) {
uint32_t ret = 0;
ENTER_CRITICAL();
if (q->w_ptr >= q->r_ptr) {
ret = q->fifo_size - 1U - q->w_ptr + q->r_ptr;
} else {
ret = q->r_ptr - q->w_ptr - 1U;
}
EXIT_CRITICAL();
return ret;
}
void can_clear(can_ring *q) {
ENTER_CRITICAL();
q->w_ptr = 0;
q->r_ptr = 0;
EXIT_CRITICAL();
}
// 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.
// Helpers
// Panda: Bus 0=CAN1 Bus 1=CAN2 Bus 2=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};
uint32_t can_data_speed[] = {5000, 5000, 5000}; //For CAN FD with BRS only
#define CAN_MAX 3U
#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])
void can_init_all(void) {
bool ret = true;
for (uint8_t i=0U; i < CAN_MAX; i++) {
can_clear(can_queues[i]);
ret &= can_init(i);
}
UNUSED(ret);
}
void can_flip_buses(uint8_t bus1, uint8_t bus2){
bus_lookup[bus1] = bus2;
bus_lookup[bus2] = bus1;
can_num_lookup[bus1] = bus2;
can_num_lookup[bus2] = bus1;
}
void ignition_can_hook(CAN_FIFOMailBox_TypeDef *to_push) {
int bus = GET_BUS(to_push);
int addr = GET_ADDR(to_push);
int len = GET_LEN(to_push);
ignition_can_cnt = 0U; // reset counter
if (bus == 0) {
// TODO: verify on all supported GM models that we can reliably detect ignition using only this signal,
// since the 0x1F1 signal can briefly go low immediately after ignition
if ((addr == 0x160) && (len == 5)) {
// this message isn't all zeros when ignition is on
ignition_cadillac = GET_BYTES_04(to_push) != 0;
}
// GM exception
if ((addr == 0x1F1) && (len == 8)) {
// Bit 5 is ignition "on"
bool ignition_gm = ((GET_BYTE(to_push, 0) & 0x20) != 0);
ignition_can = ignition_gm || ignition_cadillac;
}
// Tesla exception
if ((addr == 0x348) && (len == 8)) {
// GTW_status
ignition_can = (GET_BYTE(to_push, 0) & 0x1) != 0;
}
}
}
bool can_tx_check_min_slots_free(uint32_t min) {
return
(can_slots_empty(&can_tx1_q) >= min) &&
(can_slots_empty(&can_tx2_q) >= min) &&
(can_slots_empty(&can_tx3_q) >= min) &&
(can_slots_empty(&can_txgmlan_q) >= min);
}
void can_send(CAN_FIFOMailBox_TypeDef *to_push, uint8_t bus_number, bool skip_tx_hook) {
if (skip_tx_hook || safety_tx_hook(to_push) != 0) {
if (bus_number < BUS_MAX) {
// add CAN packet to send queue
// bus number isn't passed through
to_push->RDTR &= 0xF;
if ((bus_number == 3U) && (can_num_lookup[3] == 0xFFU)) {
gmlan_send_errs += bitbang_gmlan(to_push) ? 0U : 1U;
} else {
can_fwd_errs += can_push(can_queues[bus_number], to_push) ? 0U : 1U;
process_can(CAN_NUM_FROM_BUS_NUM(bus_number));
}
}
}
}
void can_set_forwarding(int from, int to) {
can_forwarding[from] = to;
}

203
panda/board/drivers/fdcan.h Normal file
View File

@@ -0,0 +1,203 @@
// IRQs: FDCAN1_IT0, FDCAN1_IT1
// FDCAN2_IT0, FDCAN2_IT1
// FDCAN3_IT0, FDCAN3_IT1
#define BUS_OFF_FAIL_LIMIT 2U
uint8_t bus_off_err[] = {0U, 0U, 0U};
FDCAN_GlobalTypeDef *cans[] = {FDCAN1, FDCAN2, FDCAN3};
bool can_set_speed(uint8_t can_number) {
bool ret = true;
FDCAN_GlobalTypeDef *CANx = CANIF_FROM_CAN_NUM(can_number);
uint8_t bus_number = BUS_NUM_FROM_CAN_NUM(can_number);
ret &= llcan_set_speed(CANx, can_speed[bus_number], can_data_speed[bus_number], can_loopback, (unsigned int)(can_silent) & (1U << can_number));
return ret;
}
void can_set_gmlan(uint8_t bus) {
UNUSED(bus);
puts("GMLAN not available on red panda\n");
}
void cycle_transceiver(uint8_t can_number) {
// FDCAN1 = trans 1, FDCAN3 = trans 3, FDCAN2 = trans 2 normal or 4 flipped harness
uint8_t transceiver_number = can_number;
if (can_number == 2U) {
uint8_t flip = (car_harness_status == HARNESS_STATUS_FLIPPED) ? 2U : 0U;
transceiver_number += flip;
}
current_board->enable_can_transceiver(transceiver_number, false);
delay(20000);
current_board->enable_can_transceiver(transceiver_number, true);
bus_off_err[can_number] = 0U;
puts("Cycled transceiver number: "); puth(transceiver_number); puts("\n");
}
// ***************************** CAN *****************************
void process_can(uint8_t can_number) {
if (can_number != 0xffU) {
ENTER_CRITICAL();
FDCAN_GlobalTypeDef *CANx = CANIF_FROM_CAN_NUM(can_number);
uint8_t bus_number = BUS_NUM_FROM_CAN_NUM(can_number);
CANx->IR |= FDCAN_IR_TFE; // Clear Tx FIFO Empty flag
if ((CANx->TXFQS & FDCAN_TXFQS_TFQF) == 0) {
CAN_FIFOMailBox_TypeDef to_send;
if (can_pop(can_queues[bus_number], &to_send)) {
can_tx_cnt += 1;
uint32_t TxFIFOSA = FDCAN_START_ADDRESS + (can_number * FDCAN_OFFSET) + (FDCAN_RX_FIFO_0_EL_CNT * FDCAN_RX_FIFO_0_EL_SIZE);
uint8_t tx_index = (CANx->TXFQS >> FDCAN_TXFQS_TFQPI_Pos) & 0x1F;
// only send if we have received a packet
CAN_FIFOMailBox_TypeDef *fifo;
fifo = (CAN_FIFOMailBox_TypeDef *)(TxFIFOSA + (tx_index * FDCAN_TX_FIFO_EL_SIZE));
// Convert from "mailbox type"
fifo->RIR = ((to_send.RIR & 0x6) << 28) | (to_send.RIR >> 3); // identifier format and frame type | identifier
//REDEBUG: enable CAN FD and BRS for test purposes
//fifo->RDTR = ((to_send.RDTR & 0xF) << 16) | ((to_send.RDTR) >> 16) | (1U << 21) | (1U << 20); // DLC (length) | timestamp | enable CAN FD | enable BRS
fifo->RDTR = ((to_send.RDTR & 0xF) << 16) | ((to_send.RDTR) >> 16); // DLC (length) | timestamp
fifo->RDLR = to_send.RDLR;
fifo->RDHR = to_send.RDHR;
CANx->TXBAR = (1UL << tx_index);
// Send back to USB
can_txd_cnt += 1;
CAN_FIFOMailBox_TypeDef to_push;
to_push.RIR = to_send.RIR;
to_push.RDTR = (to_send.RDTR & 0xFFFF000FU) | ((CAN_BUS_RET_FLAG | bus_number) << 4);
to_push.RDLR = to_send.RDLR;
to_push.RDHR = to_send.RDHR;
can_send_errs += can_push(&can_rx_q, &to_push) ? 0U : 1U;
if (can_tx_check_min_slots_free(MAX_CAN_MSGS_PER_BULK_TRANSFER)) {
usb_outep3_resume_if_paused();
}
}
}
// Recover after Bus-off state
if (((CANx->PSR & FDCAN_PSR_BO) != 0) && ((CANx->CCCR & FDCAN_CCCR_INIT) != 0)) {
bus_off_err[can_number] += 1U;
puts("CAN is in Bus_Off state! Resetting... CAN number: "); puth(can_number); puts("\n");
if (bus_off_err[can_number] > BUS_OFF_FAIL_LIMIT) {
cycle_transceiver(can_number);
}
CANx->IR = 0xFFC60000U; // Reset all flags(Only errors!)
CANx->CCCR &= ~(FDCAN_CCCR_INIT);
uint32_t timeout_counter = 0U;
while((CANx->CCCR & FDCAN_CCCR_INIT) != 0) {
// Delay for about 1ms
delay(10000);
timeout_counter++;
if(timeout_counter >= CAN_INIT_TIMEOUT_MS){
puts(CAN_NAME_FROM_CANIF(CANx)); puts(" Bus_Off reset timed out!\n");
break;
}
}
}
EXIT_CRITICAL();
}
}
// CAN receive handlers
// blink blue when we are receiving CAN messages
void can_rx(uint8_t can_number) {
FDCAN_GlobalTypeDef *CANx = CANIF_FROM_CAN_NUM(can_number);
uint8_t bus_number = BUS_NUM_FROM_CAN_NUM(can_number);
uint8_t rx_fifo_idx;
// Rx FIFO 0 new message
if((CANx->IR & FDCAN_IR_RF0N) != 0) {
CANx->IR |= FDCAN_IR_RF0N;
while((CANx->RXF0S & FDCAN_RXF0S_F0FL) != 0) {
can_rx_cnt += 1;
// can is live
pending_can_live = 1;
// getting new message index (0 to 63)
rx_fifo_idx = (uint8_t)((CANx->RXF0S >> FDCAN_RXF0S_F0GI_Pos) & 0x3F);
uint32_t RxFIFO0SA = FDCAN_START_ADDRESS + (can_number * FDCAN_OFFSET);
CAN_FIFOMailBox_TypeDef to_push;
CAN_FIFOMailBox_TypeDef *fifo;
// getting address
fifo = (CAN_FIFOMailBox_TypeDef *)(RxFIFO0SA + (rx_fifo_idx * FDCAN_RX_FIFO_0_EL_SIZE));
// Need to convert real CAN frame format to mailbox "type"
to_push.RIR = ((fifo->RIR >> 28) & 0x6) | (fifo->RIR << 3); // identifier format and frame type | identifier
to_push.RDTR = ((fifo->RDTR >> 16) & 0xF) | (fifo->RDTR << 16); // DLC (length) | timestamp
to_push.RDLR = fifo->RDLR;
to_push.RDHR = fifo->RDHR;
// modify RDTR for our API
to_push.RDTR = (to_push.RDTR & 0xFFFF000F) | (bus_number << 4);
// forwarding (panda only)
int bus_fwd_num = (can_forwarding[bus_number] != -1) ? can_forwarding[bus_number] : safety_fwd_hook(bus_number, &to_push);
if (bus_fwd_num != -1) {
CAN_FIFOMailBox_TypeDef to_send;
to_send.RIR = to_push.RIR;
to_send.RDTR = to_push.RDTR;
to_send.RDLR = to_push.RDLR;
to_send.RDHR = to_push.RDHR;
can_send(&to_send, bus_fwd_num, true);
}
can_rx_errs += safety_rx_hook(&to_push) ? 0U : 1U;
ignition_can_hook(&to_push);
current_board->set_led(LED_BLUE, true);
can_send_errs += can_push(&can_rx_q, &to_push) ? 0U : 1U;
// update read index
CANx->RXF0A = rx_fifo_idx;
}
} else if((CANx->IR & (FDCAN_IR_PEA | FDCAN_IR_PED | FDCAN_IR_RF0L | FDCAN_IR_RF0F | FDCAN_IR_EW | FDCAN_IR_MRAF | FDCAN_IR_TOO)) != 0) {
#ifdef DEBUG
puts("FDCAN error, FDCAN_IR: ");puth(CANx->IR);puts("\n");
#endif
CANx->IR |= (FDCAN_IR_PEA | FDCAN_IR_PED | FDCAN_IR_RF0L | FDCAN_IR_RF0F | FDCAN_IR_EW | FDCAN_IR_MRAF | FDCAN_IR_TOO); // Clean all error flags
can_err_cnt += 1;
} else {
}
}
void FDCAN1_IT0_IRQ_Handler(void) { can_rx(0); }
void FDCAN1_IT1_IRQ_Handler(void) { process_can(0); }
void FDCAN2_IT0_IRQ_Handler(void) { can_rx(1); }
void FDCAN2_IT1_IRQ_Handler(void) { process_can(1); }
void FDCAN3_IT0_IRQ_Handler(void) { can_rx(2); }
void FDCAN3_IT1_IRQ_Handler(void) { process_can(2); }
bool can_init(uint8_t can_number) {
bool ret = false;
REGISTER_INTERRUPT(FDCAN1_IT0_IRQn, FDCAN1_IT0_IRQ_Handler, CAN_INTERRUPT_RATE, FAULT_INTERRUPT_RATE_CAN_1)
REGISTER_INTERRUPT(FDCAN1_IT1_IRQn, FDCAN1_IT1_IRQ_Handler, CAN_INTERRUPT_RATE, FAULT_INTERRUPT_RATE_CAN_1)
REGISTER_INTERRUPT(FDCAN2_IT0_IRQn, FDCAN2_IT0_IRQ_Handler, CAN_INTERRUPT_RATE, FAULT_INTERRUPT_RATE_CAN_2)
REGISTER_INTERRUPT(FDCAN2_IT1_IRQn, FDCAN2_IT1_IRQ_Handler, CAN_INTERRUPT_RATE, FAULT_INTERRUPT_RATE_CAN_2)
REGISTER_INTERRUPT(FDCAN3_IT0_IRQn, FDCAN3_IT0_IRQ_Handler, CAN_INTERRUPT_RATE, FAULT_INTERRUPT_RATE_CAN_3)
REGISTER_INTERRUPT(FDCAN3_IT1_IRQn, FDCAN3_IT1_IRQ_Handler, CAN_INTERRUPT_RATE, FAULT_INTERRUPT_RATE_CAN_3)
if (can_number != 0xffU) {
FDCAN_GlobalTypeDef *CANx = CANIF_FROM_CAN_NUM(can_number);
ret &= can_set_speed(can_number);
ret &= llcan_init(CANx);
// in case there are queued up messages
process_can(can_number);
}
return ret;
}

View File

@@ -38,6 +38,7 @@ typedef struct uart_ring {
// ***************************** Function prototypes *****************************
void debug_ring_callback(uart_ring *ring);
void uart_tx_ring(uart_ring *q);
void uart_send_break(uart_ring *u);
// ******************************** UART buffers ********************************
@@ -138,11 +139,6 @@ void uart_flush_sync(uart_ring *q) {
}
}
void uart_send_break(uart_ring *u) {
while ((u->uart->CR1 & USART_CR1_SBK) != 0);
u->uart->CR1 |= USART_CR1_SBK;
}
void clear_uart_buff(uart_ring *q) {
ENTER_CRITICAL();
q->w_ptr_tx = 0;

View File

@@ -123,7 +123,7 @@ uint8_t device_desc[] = {
0xFF, 0xFF, 0xFF, 0x40, // Class, Subclass, Protocol, Max Packet Size
TOUSBORDER(USB_VID), // idVendor
TOUSBORDER(USB_PID), // idProduct
0x00, 0x23, // bcdDevice
0x00, 0x00, // bcdDevice
0x01, 0x02, // Manufacturer, Product
0x03, 0x01 // Serial Number, Num Configurations
};
@@ -526,6 +526,8 @@ void usb_setup(void) {
case USB_DESC_TYPE_DEVICE:
//puts(" writing device descriptor\n");
// set bcdDevice to hardware type
device_desc[13] = hw_type;
// setup transfer
USB_WritePacket(device_desc, MIN(sizeof(device_desc), setup.b.wLength.w), 0);
USBx_OUTEP(0)->DOEPCTL |= USB_OTG_DOEPCTL_CNAK;

5
panda/board/flash_h7.sh Executable file
View File

@@ -0,0 +1,5 @@
#!/usr/bin/env sh
set -e
PANDA_GEN3=1 scons -u
PYTHONPATH=.. python3 -c "from python import Panda; Panda().flash('obj/panda_h7.bin.signed')"

View File

@@ -1,6 +1,6 @@
// flasher state variables
uint32_t *prog_ptr = NULL;
int unlocked = 0;
bool unlocked = false;
#ifdef uart_ring
void debug_ring_callback(uart_ring *ring) {}
@@ -26,32 +26,27 @@ int usb_cb_control_msg(USB_Setup_TypeDef *setup, uint8_t *resp, bool hardwired)
break;
// **** 0xb1: unlock flash
case 0xb1:
if (FLASH->CR & FLASH_CR_LOCK) {
FLASH->KEYR = 0x45670123;
FLASH->KEYR = 0xCDEF89AB;
if (flash_is_locked()) {
flash_unlock();
resp[1] = 0xff;
}
current_board->set_led(LED_GREEN, 1);
unlocked = 1;
prog_ptr = (uint32_t *)0x8004000;
unlocked = true;
prog_ptr = (uint32_t *)APP_START_ADDRESS;
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);
if (flash_erase_sector(sec, unlocked)) {
resp[1] = 0xff;
}
break;
// **** 0xd0: fetch serial number
case 0xd0:
#ifdef STM32F4
#ifndef STM32F2
// addresses are OTP
if (setup->b.wValue.w == 1) {
memcpy(resp, (void *)0x1fff79c0, 0x10);
memcpy(resp, (void *)DEVICE_SERIAL_NUMBER_ADDRESS, 0x10);
resp_len = 0x10;
} else {
get_provision_chunk(resp);
@@ -93,6 +88,7 @@ int usb_cb_control_msg(USB_Setup_TypeDef *setup, uint8_t *resp, bool hardwired)
break;
// **** 0xd8: reset ST
case 0xd8:
flush_write_buffer();
NVIC_SystemReset();
break;
}
@@ -122,11 +118,7 @@ void usb_cb_ep2_out(void *usbdata, int len, bool hardwired) {
UNUSED(hardwired);
current_board->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);
flash_write_word(prog_ptr, *(uint32_t*)(usbdata+(i*4)));
//*(uint64_t*)(&spi_tx_buf[0x30+(i*4)]) = *prog_ptr;
prog_ptr++;
@@ -153,7 +145,7 @@ int spi_cb_rx(uint8_t *data, int len, uint8_t *data_out) {
#ifdef PEDAL
#include "stm32fx/llcan.h"
#include "stm32fx/llbxcan.h"
#define CAN CAN1
#define CAN_BL_INPUT 0x1
@@ -278,10 +270,7 @@ void soft_flasher_start(void) {
enter_bootloader_mode = 0;
RCC->AHB1ENR |= RCC_AHB1ENR_DMA2EN;
RCC->APB2ENR |= RCC_APB2ENR_SPI1EN;
RCC->AHB2ENR |= RCC_AHB2ENR_OTGFSEN;
RCC->APB1ENR |= RCC_APB1ENR_USART2EN;
flasher_peripherals_init();
// pedal has the canloader
#ifdef PEDAL
@@ -297,23 +286,8 @@ void soft_flasher_start(void) {
llcan_init(CAN1);
#endif
// 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();
gpio_usart2_init();
gpio_usb_init();
// enable USB
usb_init();

View File

@@ -12,7 +12,13 @@
#include "power_saving.h"
#include "safety.h"
#include "drivers/can.h"
#include "drivers/can_common.h"
#ifdef STM32H7
#include "drivers/fdcan.h"
#else
#include "drivers/bxcan.h"
#endif
#include "obj/gitversion.h"
@@ -333,11 +339,7 @@ int usb_cb_control_msg(USB_Setup_TypeDef *setup, uint8_t *resp, bool hardwired)
break;
// **** 0xc1: get hardware type
case 0xc1:
#ifdef fake_black_panda
resp[0] = HW_TYPE_BLACK_PANDA;
#else
resp[0] = hw_type;
#endif
resp_len = 1;
break;
// **** 0xd0: fetch serial number
@@ -482,6 +484,7 @@ int usb_cb_control_msg(USB_Setup_TypeDef *setup, uint8_t *resp, bool hardwired)
// **** 0xde: set can bitrate
case 0xde:
if (setup->b.wValue.w < BUS_MAX) {
// TODO: add sanity check, ideally check if value is correct(from array of correct values)
can_speed[setup->b.wValue.w] = setup->b.wIndex.w;
bool ret = can_init(CAN_NUM_FROM_BUS_NUM(setup->b.wValue.w));
UNUSED(ret);
@@ -635,6 +638,15 @@ int usb_cb_control_msg(USB_Setup_TypeDef *setup, uint8_t *resp, bool hardwired)
heartbeat_disabled = true;
break;
#endif
// **** 0xde: set CAN FD data bitrate
case 0xf9:
if (setup->b.wValue.w < CAN_MAX) {
// TODO: add sanity check, ideally check if value is correct(from array of correct values)
can_data_speed[setup->b.wValue.w] = setup->b.wIndex.w;
bool ret = can_init(CAN_NUM_FROM_BUS_NUM(setup->b.wValue.w));
UNUSED(ret);
}
break;
default:
puts("NO HANDLER ");
puth(setup->b.bRequest);

11
panda/board/recover_h7.sh Executable file
View File

@@ -0,0 +1,11 @@
#!/usr/bin/env sh
set -e
DFU_UTIL="dfu-util"
PANDA_H7=1 scons -u
PYTHONPATH=.. python3 -c "from python import Panda; Panda().reset(enter_bootstub=True); Panda().reset(enter_bootloader=True)" || true
sleep 1
$DFU_UTIL -d 0483:df11 -a 0 -s 0x08020000 -D obj/panda_h7.bin.signed
$DFU_UTIL -d 0483:df11 -a 0 -s 0x08000000:leave -D obj/bootstub.panda_h7.bin

View File

@@ -7,8 +7,8 @@
// brake rising edge
// brake > 0mph
const CanMsg HONDA_N_TX_MSGS[] = {{0xE4, 0, 5}, {0x194, 0, 4}, {0x1FA, 0, 8}, {0x200, 0, 6}, {0x30C, 0, 8}, {0x33D, 0, 5}};
const CanMsg HONDA_BG_TX_MSGS[] = {{0xE4, 2, 5}, {0xE5, 2, 8}, {0x296, 0, 4}, {0x33D, 2, 5}}; // Bosch Giraffe
const CanMsg HONDA_BH_TX_MSGS[] = {{0xE4, 0, 5}, {0xE5, 0, 8}, {0x296, 1, 4}, {0x33D, 0, 5}}; // Bosch Harness
const CanMsg HONDA_BG_TX_MSGS[] = {{0xE4, 2, 5}, {0xE5, 2, 8}, {0x296, 0, 4}, {0x33D, 2, 5}, {0x33DA, 2, 5}, {0x33DB, 2, 8}}; // Bosch Giraffe
const CanMsg HONDA_BH_TX_MSGS[] = {{0xE4, 0, 5}, {0xE5, 0, 8}, {0x296, 1, 4}, {0x33D, 0, 5}, {0x33DA, 0, 5}, {0x33DB, 0, 8}}; // Bosch Harness
const CanMsg HONDA_BG_LONG_TX_MSGS[] = {{0xE4, 0, 5}, {0x1DF, 0, 8}, {0x1EF, 0, 8}, {0x1FA, 0, 8}, {0x30C, 0, 8}, {0x33D, 0, 5}, {0x39F, 0, 8}, {0x18DAB0F1, 0, 8}}; // Bosch Giraffe w/ gas and brakes
const CanMsg HONDA_BH_LONG_TX_MSGS[] = {{0xE4, 1, 5}, {0x1DF, 1, 8}, {0x1EF, 1, 8}, {0x1FA, 1, 8}, {0x30C, 1, 8}, {0x33D, 1, 5}, {0x39F, 1, 8}, {0x18DAB0F1, 1, 8}}; // Bosch Harness w/ gas and brakes
@@ -274,7 +274,7 @@ static int honda_tx_hook(CAN_FIFOMailBox_TypeDef *to_send) {
}
}
// Bosch supplemental control check
// Bosch supplemental control check
if (addr == 0xE5) {
if ((GET_BYTES_04(to_send) != 0x10800004) || ((GET_BYTES_48(to_send) & 0x00FFFFFF) != 0x0)) {
tx = 0;
@@ -376,7 +376,7 @@ static int honda_bosch_fwd_hook(int bus_num, CAN_FIFOMailBox_TypeDef *to_fwd) {
}
if (bus_num == bus_rdr_cam) {
int addr = GET_ADDR(to_fwd);
int is_lkas_msg = (addr == 0xE4) || (addr == 0xE5) || (addr == 0x33D);
int is_lkas_msg = (addr == 0xE4) || (addr == 0xE5) || (addr == 0x33D) || (addr == 0x33DA) || (addr == 0x33DB);
if (!is_lkas_msg) {
bus_fwd = bus_rdr_car;
}

View File

@@ -2,6 +2,7 @@
// Hardware abstraction layer for all different supported boards //
// ///////////////////////////////////////////////////////////// //
#include "boards/board_declarations.h"
#include "boards/unused_funcs.h"
// ///// Board definition and detection ///// //
#include "drivers/harness.h"

View File

@@ -10,8 +10,8 @@
* is using in the C source code, usually in main.c. This file contains:
* - Configuration section that allows to select:
* - The STM32F2xx device used in the target application
* - To use or not the peripherals drivers in application code(i.e.
* code will be based on direct access to peripherals registers
* - To use or not the peripherals drivers in application code(i.e.
* code will be based on direct access to peripherals registers
* rather than drivers API), this option is controlled by
* "#define USE_HAL_DRIVER"
*
@@ -74,7 +74,7 @@
/* Uncomment the line below according to the target STM32 device used in your
application
*/
#if !defined (STM32F205xx) && !defined (STM32F215xx) && !defined (STM32F207xx) && !defined (STM32F217xx)
/* #if !defined (STM32F205xx) && !defined (STM32F215xx) && !defined (STM32F207xx) && !defined (STM32F217xx) */
/* #define STM32F205xx */ /*!< STM32F205RG, STM32F205VG, STM32F205ZG, STM32F205RF, STM32F205VF, STM32F205ZF,
STM32F205RE, STM32F205VE, STM32F205ZE, STM32F205RC, STM32F205VC, STM32F205ZC,
@@ -84,7 +84,7 @@
STM32F207VE, STM32F207ZE, STM32F207IE, STM32F207VC, STM32F207ZC and STM32F207IC Devices */
/* #define STM32F217xx */ /*!< STM32F217VG, STM32F217ZG, STM32F217IG, STM32F217VE, STM32F217ZE and STM32F217IE Devices */
#endif
//#endif
/* Tip: To avoid modifying this file each time you need to switch between these
devices, you can define the device in your toolchain compiler preprocessor.
@@ -118,14 +118,14 @@
* @{
*/
#if defined(STM32F205xx)
#include "stm32f205xx.h"
#elif defined(STM32F215xx)
#if defined(STM32F215xx)
#include "stm32f215xx.h"
#elif defined(STM32F207xx)
#include "stm32f207xx.h"
#elif defined(STM32F217xx)
#include "stm32f217xx.h"
#elif defined(STM32F205xx)
#include "stm32f205xx.h"
// #elif defined(STM32F207xx)
// #include "stm32f207xx.h"
// #elif defined(STM32F217xx)
// #include "stm32f217xx.h"
#else
#error "Please select first the target STM32F2xx device used in your application (in stm32f2xx.h file)"
#endif

View File

@@ -10,8 +10,8 @@
* is using in the C source code, usually in main.c. This file contains:
* - Configuration section that allows to select:
* - The STM32F4xx device used in the target application
* - To use or not the peripherals drivers in application code(i.e.
* code will be based on direct access to peripherals registers
* - To use or not the peripherals drivers in application code(i.e.
* code will be based on direct access to peripherals registers
* rather than drivers API), this option is controlled by
* "#define USE_HAL_DRIVER"
*
@@ -74,12 +74,12 @@
/* Uncomment the line below according to the target STM32 device used in your
application
*/
#if !defined (STM32F405xx) && !defined (STM32F415xx) && !defined (STM32F407xx) && !defined (STM32F417xx) && \
/* #if !defined (STM32F405xx) && !defined (STM32F415xx) && !defined (STM32F407xx) && !defined (STM32F417xx) && \
!defined (STM32F427xx) && !defined (STM32F437xx) && !defined (STM32F429xx) && !defined (STM32F439xx) && \
!defined (STM32F401xC) && !defined (STM32F401xE) && !defined (STM32F410Tx) && !defined (STM32F410Cx) && \
!defined (STM32F410Rx) && !defined (STM32F411xE) && !defined (STM32F446xx) && !defined (STM32F469xx) && \
!defined (STM32F479xx) && !defined (STM32F412Cx) && !defined (STM32F412Rx) && !defined (STM32F412Vx) && \
!defined (STM32F412Zx) && !defined (STM32F413xx) && !defined (STM32F423xx)
!defined (STM32F412Zx) && !defined (STM32F413xx) && !defined (STM32F423xx) */
/* #define STM32F405xx */ /*!< STM32F405RG, STM32F405VG and STM32F405ZG Devices */
/* #define STM32F415xx */ /*!< STM32F415RG, STM32F415VG and STM32F415ZG Devices */
/* #define STM32F407xx */ /*!< STM32F407VG, STM32F407VE, STM32F407ZG, STM32F407ZE, STM32F407IG and STM32F407IE Devices */
@@ -109,7 +109,7 @@
/* #define STM32F413xx */ /*!< STM32F413CH, STM32F413MH, STM32F413RH, STM32F413VH, STM32F413ZH, STM32F413CG, STM32F413MG,
STM32F413RG, STM32F413VG and STM32F413ZG Devices */
/* #define STM32F423xx */ /*!< STM32F423CH, STM32F423RH, STM32F423VH and STM32F423ZH Devices */
#endif
//#endif
/* Tip: To avoid modifying this file each time you need to switch between these
devices, you can define the device in your toolchain compiler preprocessor.
@@ -143,51 +143,51 @@
* @{
*/
#if defined(STM32F405xx)
#include "stm32f405xx.h"
#elif defined(STM32F415xx)
#include "stm32f415xx.h"
#elif defined(STM32F407xx)
#include "stm32f407xx.h"
#elif defined(STM32F417xx)
#include "stm32f417xx.h"
#elif defined(STM32F427xx)
#include "stm32f427xx.h"
#elif defined(STM32F437xx)
#include "stm32f437xx.h"
#elif defined(STM32F429xx)
#include "stm32f429xx.h"
#elif defined(STM32F439xx)
#include "stm32f439xx.h"
#elif defined(STM32F401xC)
#include "stm32f401xc.h"
#elif defined(STM32F401xE)
#include "stm32f401xe.h"
#elif defined(STM32F410Tx)
#include "stm32f410tx.h"
#elif defined(STM32F410Cx)
#include "stm32f410cx.h"
#elif defined(STM32F410Rx)
#include "stm32f410rx.h"
#elif defined(STM32F411xE)
#include "stm32f411xe.h"
#elif defined(STM32F446xx)
#include "stm32f446xx.h"
#elif defined(STM32F469xx)
#include "stm32f469xx.h"
#elif defined(STM32F479xx)
#include "stm32f479xx.h"
#elif defined(STM32F412Cx)
#include "stm32f412cx.h"
#elif defined(STM32F412Zx)
#include "stm32f412zx.h"
#elif defined(STM32F412Rx)
#include "stm32f412rx.h"
#elif defined(STM32F412Vx)
#include "stm32f412vx.h"
#elif defined(STM32F413xx)
// #if defined(STM32F405xx)
// #include "stm32f405xx.h"
// #elif defined(STM32F415xx)
// #include "stm32f415xx.h"
// #elif defined(STM32F407xx)
// #include "stm32f407xx.h"
// #elif defined(STM32F417xx)
// #include "stm32f417xx.h"
// #elif defined(STM32F427xx)
// #include "stm32f427xx.h"
// #elif defined(STM32F437xx)
// #include "stm32f437xx.h"
// #elif defined(STM32F429xx)
// #include "stm32f429xx.h"
// #elif defined(STM32F439xx)
// #include "stm32f439xx.h"
// #elif defined(STM32F401xC)
// #include "stm32f401xc.h"
// #elif defined(STM32F401xE)
// #include "stm32f401xe.h"
// #elif defined(STM32F410Tx)
// #include "stm32f410tx.h"
// #elif defined(STM32F410Cx)
// #include "stm32f410cx.h"
// #elif defined(STM32F410Rx)
// #include "stm32f410rx.h"
// #elif defined(STM32F411xE)
// #include "stm32f411xe.h"
// #elif defined(STM32F446xx)
// #include "stm32f446xx.h"
// #elif defined(STM32F469xx)
// #include "stm32f469xx.h"
// #elif defined(STM32F479xx)
// #include "stm32f479xx.h"
// #elif defined(STM32F412Cx)
// #include "stm32f412cx.h"
// #elif defined(STM32F412Zx)
// #include "stm32f412zx.h"
// #elif defined(STM32F412Rx)
// #include "stm32f412rx.h"
// #elif defined(STM32F412Vx)
// #include "stm32f412vx.h"
#if defined(STM32F413xx)
#include "stm32f413xx.h"
#elif defined(STM32F423xx)
#elif defined(STM32F423xx)
#include "stm32f423xx.h"
#else
#error "Please select first the target STM32F4xx device used in your application (in stm32f4xx.h file)"

View File

@@ -8,15 +8,6 @@
// 5000 = 500 kbps
#define can_speed_to_prescaler(x) (CAN_PCLK / CAN_QUANTA * 10U / (x))
#define GET_BUS(msg) (((msg)->RDTR >> 4) & 0xFF)
#define GET_LEN(msg) ((msg)->RDTR & 0xF)
#define GET_ADDR(msg) ((((msg)->RIR & 4) != 0) ? ((msg)->RIR >> 3) : ((msg)->RIR >> 21))
#define GET_BYTE(msg, b) (((int)(b) > 3) ? (((msg)->RDHR >> (8U * ((unsigned int)(b) % 4U))) & 0xFFU) : (((msg)->RDLR >> (8U * (unsigned int)(b))) & 0xFFU))
#define GET_BYTES_04(msg) ((msg)->RDLR)
#define GET_BYTES_48(msg) ((msg)->RDHR)
#define GET_FLAG(value, mask) (((__typeof__(mask))(value) & (mask)) == (mask))
#define CAN_INIT_TIMEOUT_MS 500U
#define CAN_NAME_FROM_CANIF(CAN_DEV) (((CAN_DEV)==CAN1) ? "CAN1" : (((CAN_DEV) == CAN2) ? "CAN2" : "CAN3"))
void puts(const char *a);

View File

@@ -0,0 +1,28 @@
bool flash_is_locked(void) {
return (FLASH->CR & FLASH_CR_LOCK);
}
void flash_unlock(void) {
FLASH->KEYR = 0x45670123;
FLASH->KEYR = 0xCDEF89AB;
}
bool flash_erase_sector(uint8_t sector, bool unlocked) {
// don't erase the bootloader(sector 0)
if (sector != 0 && sector < 12 && unlocked) {
FLASH->CR = (sector << 3) | FLASH_CR_SER;
FLASH->CR |= FLASH_CR_STRT;
while (FLASH->SR & FLASH_SR_BSY);
return true;
}
return false;
}
void flash_write_word(void *prog_ptr, uint32_t data) {
uint32_t *pp = prog_ptr;
FLASH->CR = FLASH_CR_PSIZE_1 | FLASH_CR_PG;
*pp = data;
while (FLASH->SR & FLASH_SR_BSY);
}
void flush_write_buffer(void) { }

View File

@@ -42,6 +42,11 @@ void uart_rx_ring(uart_ring *q){
}
}
void uart_send_break(uart_ring *u) {
while ((u->uart->CR1 & USART_CR1_SBK) != 0);
u->uart->CR1 |= USART_CR1_SBK;
}
// This function should be called on:
// * Half-transfer DMA interrupt
// * Full-transfer DMA interrupt

View File

@@ -1,5 +1,18 @@
void gpio_usb_init(void) {
// 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;
}
void gpio_usart2_init(void) {
// A2,A3: USART 2 for debugging
set_gpio_alternate(GPIOA, 2, GPIO_AF7_USART2);
set_gpio_alternate(GPIOA, 3, GPIO_AF7_USART2);
}
// Common GPIO initialization
void common_init_gpio(void){
void common_init_gpio(void) {
// TODO: Is this block actually doing something???
// pull low to hold ESP in reset??
// enable OTG out tied to ground
@@ -12,10 +25,7 @@ void common_init_gpio(void){
// C2: Voltage sense line
set_gpio_mode(GPIOC, 2, MODE_ANALOG);
// 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;
gpio_usb_init();
// A9,A10: USART 1 for talking to the GPS
set_gpio_alternate(GPIOA, 9, GPIO_AF7_USART1);
@@ -31,8 +41,15 @@ void common_init_gpio(void){
#endif
}
void flasher_peripherals_init(void) {
RCC->AHB1ENR |= RCC_AHB1ENR_DMA2EN;
RCC->APB2ENR |= RCC_APB2ENR_SPI1EN;
RCC->AHB2ENR |= RCC_AHB2ENR_OTGFSEN;
RCC->APB1ENR |= RCC_APB1ENR_USART2EN;
}
// Peripheral initialization
void peripherals_init(void){
void peripherals_init(void) {
// enable GPIOB, UART2, CAN, USB clock
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOBEN;

View File

@@ -67,8 +67,10 @@
#include "stm32fx/lluart.h"
#endif
#ifndef BOOTSTUB
#include "stm32fx/llcan.h"
#ifdef BOOTSTUB
#include "stm32fx/llflash.h"
#else
#include "stm32fx/llbxcan.h"
#endif
#if defined(PANDA) || defined(BOOTSTUB) || defined(PEDAL_USB)

View File

@@ -35,7 +35,7 @@ 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 */
_app_start = 0x08004000; /* Reserve Sector 0(16K) for bootloader */
/* Generate a link error if heap and stack don't fit into RAM */
_Min_Heap_Size = 0; /* required amount of heap */

View File

@@ -0,0 +1,36 @@
// ///////////////////////////////////////////////////////////// //
// Hardware abstraction layer for all different supported boards //
// ///////////////////////////////////////////////////////////// //
#include "boards/board_declarations.h"
#include "boards/unused_funcs.h"
// ///// Board definition and detection ///// //
#include "drivers/harness.h"
#include "drivers/fan.h"
#include "stm32h7/llfan.h"
#include "stm32h7/llrtc.h"
#include "drivers/rtc.h"
#include "boards/red.h"
uint8_t board_id(void) {
return detect_with_pull(GPIOF, 7, PULL_UP) |
(detect_with_pull(GPIOF, 8, PULL_UP) << 1U) |
(detect_with_pull(GPIOF, 9, PULL_UP) << 2U) |
(detect_with_pull(GPIOF, 10, PULL_UP) << 3U);
}
void detect_board_type(void) {
if(board_id() == 0U){
hw_type = HW_TYPE_RED_PANDA;
current_board = &board_red;
} else {
hw_type = HW_TYPE_UNKNOWN;
puts("Hardware type is UNKNOWN!\n");
}
}
bool has_external_debug_serial = 0;
void detect_external_debug_serial(void) {
// detect if external serial debugging is present
has_external_debug_serial = detect_with_pull(GPIOA, 3, PULL_DOWN);
}

View File

@@ -0,0 +1,54 @@
void clock_init(void) {
//Set power mode to direct SMPS power supply(depends on the board layout)
register_set(&(PWR->CR3), PWR_CR3_SMPSEN, 0xFU); // powered only by SMPS
//Set VOS level to VOS0. (VOS3 to 170Mhz, VOS2 to 300Mhz, VOS1 to 400Mhz, VOS0 to 550Mhz)
register_set(&(PWR->D3CR), PWR_D3CR_VOS_1, 0xC000U); //VOS2
while ((PWR->CSR1 & PWR_CSR1_ACTVOSRDY) == 0);
while ((PWR->CSR1 & PWR_CSR1_ACTVOS) != (PWR->D3CR & PWR_D3CR_VOS)); // check that VOS level was actually set
// Configure Flash ACR register LATENCY and WRHIGHFREQ (VOS0 range!)
register_set(&(FLASH->ACR), FLASH_ACR_LATENCY_2WS | 0x20U, 0x3FU); // VOS2, AXI 100MHz-150MHz
// enable external oscillator HSE
register_set_bits(&(RCC->CR), RCC_CR_HSEON);
while ((RCC->CR & RCC_CR_HSERDY) == 0);
// Specify the frequency source for PLL1, divider for DIVM1, divider for DIVM2 : HSE, 5, 5
register_set(&(RCC->PLLCKSELR), RCC_PLLCKSELR_PLLSRC_HSE | RCC_PLLCKSELR_DIVM1_0 | RCC_PLLCKSELR_DIVM1_2 | RCC_PLLCKSELR_DIVM2_0 | RCC_PLLCKSELR_DIVM2_2, 0x3F3F3U);
// *** PLL1 start ***
// Specify multiplier N and dividers P, Q, R for PLL1 : 48, 1, 5, 2
register_set(&(RCC->PLL1DIVR), 0x104002FU, 0x7F7FFFFFU);
// Specify the input and output frequency ranges, enable dividers for PLL1
register_set(&(RCC->PLLCFGR), RCC_PLLCFGR_PLL1RGE_2 | RCC_PLLCFGR_DIVP1EN | RCC_PLLCFGR_DIVQ1EN | RCC_PLLCFGR_DIVR1EN, 0x7000CU);
// Enable PLL1
register_set_bits(&(RCC->CR), RCC_CR_PLL1ON);
while((RCC->CR & RCC_CR_PLL1RDY) == 0);
// *** PLL1 end ***
//////////////OTHER CLOCKS////////////////////
// RCC HCLK Clock Source / RCC APB3 Clock Source / RCC SYS Clock Source
register_set(&(RCC->D1CFGR), RCC_D1CFGR_HPRE_DIV2 | RCC_D1CFGR_D1PPRE_DIV2 | RCC_D1CFGR_D1CPRE_DIV1, 0xF7FU);
// RCC APB1 Clock Source / RCC APB2 Clock Source
register_set(&(RCC->D2CFGR), RCC_D2CFGR_D2PPRE1_DIV2 | RCC_D2CFGR_D2PPRE2_DIV2, 0x770U);
// RCC APB4 Clock Source
register_set(&(RCC->D3CFGR), RCC_D3CFGR_D3PPRE_DIV2, 0x70U);
// PLL2P for ADC
register_clear_bits(&(RCC->D3CFGR), RCC_D3CCIPR_ADCSEL);
// Set SysClock source to PLL
register_set(&(RCC->CFGR), RCC_CFGR_SW_PLL1, 0x7U);
while((RCC->CFGR & RCC_CFGR_SWS) != RCC_CFGR_SWS_PLL1);
// SYSCFG peripheral clock enable
register_set_bits(&(RCC->AHB4ENR), RCC_APB4ENR_SYSCFGEN);
//////////////END OTHER CLOCKS////////////////////
// Configure clock source for USB
register_set(&(RCC->D2CCIP2R), RCC_D2CCIP2R_USBSEL_0, RCC_D2CCIP2R_USBSEL); //PLL1Q
// Configure clock source for FDCAN
register_set(&(RCC->D2CCIP1R), RCC_D2CCIP1R_FDCANSEL_0, RCC_D2CCIP1R_FDCANSEL); //PLL1Q
// Configure clock source for ADC1,2,3
register_set(&(RCC->D3CCIPR), RCC_D3CCIPR_ADCSEL_1, RCC_D3CCIPR_ADCSEL); //per_ck(currently HSE)
//Enable the Clock Security System
register_set_bits(&(RCC->CR), RCC_CR_CSSHSEON);
//Enable Vdd33usb supply level detector
register_set_bits(&(PWR->CR3), PWR_CR3_USB33DEN);
}

View File

@@ -0,0 +1,284 @@
/**************************************************************************//**
* @file cmsis_compiler.h
* @brief CMSIS compiler generic header file
* @version V5.1.0
* @date 09. October 2018
******************************************************************************/
/*
* Copyright (c) 2009-2018 Arm Limited. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the License); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __CMSIS_COMPILER_H
#define __CMSIS_COMPILER_H
#include <stdint.h>
/*
* Arm Compiler 4/5
*/
#if defined ( __CC_ARM )
#include "cmsis_armcc.h"
/*
* Arm Compiler 6.6 LTM (armclang)
*/
#elif defined (__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050) && (__ARMCC_VERSION < 6100100)
#include "cmsis_armclang_ltm.h"
/*
* Arm Compiler above 6.10.1 (armclang)
*/
#elif defined (__ARMCC_VERSION) && (__ARMCC_VERSION >= 6100100)
#include "cmsis_armclang.h"
/*
* GNU Compiler
*/
#elif defined ( __GNUC__ )
#include "cmsis_gcc.h"
/*
* IAR Compiler
*/
#elif defined ( __ICCARM__ )
#include <cmsis_iccarm.h>
/*
* TI Arm Compiler
*/
#elif defined ( __TI_ARM__ )
#include <cmsis_ccs.h>
#ifndef __ASM
#define __ASM __asm
#endif
#ifndef __INLINE
#define __INLINE inline
#endif
#ifndef __STATIC_INLINE
#define __STATIC_INLINE static inline
#endif
#ifndef __STATIC_FORCEINLINE
#define __STATIC_FORCEINLINE __STATIC_INLINE
#endif
#ifndef __NO_RETURN
#define __NO_RETURN __attribute__((noreturn))
#endif
#ifndef __USED
#define __USED __attribute__((used))
#endif
#ifndef __WEAK
#define __WEAK __attribute__((weak))
#endif
#ifndef __PACKED
#define __PACKED __attribute__((packed))
#endif
#ifndef __PACKED_STRUCT
#define __PACKED_STRUCT struct __attribute__((packed))
#endif
#ifndef __PACKED_UNION
#define __PACKED_UNION union __attribute__((packed))
#endif
#ifndef __UNALIGNED_UINT32 /* deprecated */
struct __attribute__((packed)) T_UINT32 { uint32_t v; };
#define __UNALIGNED_UINT32(x) (((struct T_UINT32 *)(x))->v)
#endif
#ifndef __UNALIGNED_UINT16_WRITE
__PACKED_STRUCT T_UINT16_WRITE { uint16_t v; };
#define __UNALIGNED_UINT16_WRITE(addr, val) (void)((((struct T_UINT16_WRITE *)(void*)(addr))->v) = (val))
#endif
#ifndef __UNALIGNED_UINT16_READ
__PACKED_STRUCT T_UINT16_READ { uint16_t v; };
#define __UNALIGNED_UINT16_READ(addr) (((const struct T_UINT16_READ *)(const void *)(addr))->v)
#endif
#ifndef __UNALIGNED_UINT32_WRITE
__PACKED_STRUCT T_UINT32_WRITE { uint32_t v; };
#define __UNALIGNED_UINT32_WRITE(addr, val) (void)((((struct T_UINT32_WRITE *)(void *)(addr))->v) = (val))
#endif
#ifndef __UNALIGNED_UINT32_READ
__PACKED_STRUCT T_UINT32_READ { uint32_t v; };
#define __UNALIGNED_UINT32_READ(addr) (((const struct T_UINT32_READ *)(const void *)(addr))->v)
#endif
#ifndef __ALIGNED
#define __ALIGNED(x) __attribute__((aligned(x)))
#endif
#ifndef __RESTRICT
#define __RESTRICT __restrict
#endif
#ifndef __COMPILER_BARRIER
#warning No compiler specific solution for __COMPILER_BARRIER. __COMPILER_BARRIER is ignored.
#define __COMPILER_BARRIER() (void)0
#endif
/*
* TASKING Compiler
*/
#elif defined ( __TASKING__ )
/*
* The CMSIS functions have been implemented as intrinsics in the compiler.
* Please use "carm -?i" to get an up to date list of all intrinsics,
* Including the CMSIS ones.
*/
#ifndef __ASM
#define __ASM __asm
#endif
#ifndef __INLINE
#define __INLINE inline
#endif
#ifndef __STATIC_INLINE
#define __STATIC_INLINE static inline
#endif
#ifndef __STATIC_FORCEINLINE
#define __STATIC_FORCEINLINE __STATIC_INLINE
#endif
#ifndef __NO_RETURN
#define __NO_RETURN __attribute__((noreturn))
#endif
#ifndef __USED
#define __USED __attribute__((used))
#endif
#ifndef __WEAK
#define __WEAK __attribute__((weak))
#endif
#ifndef __PACKED
#define __PACKED __packed__
#endif
#ifndef __PACKED_STRUCT
#define __PACKED_STRUCT struct __packed__
#endif
#ifndef __PACKED_UNION
#define __PACKED_UNION union __packed__
#endif
#ifndef __UNALIGNED_UINT32 /* deprecated */
struct __packed__ T_UINT32 { uint32_t v; };
#define __UNALIGNED_UINT32(x) (((struct T_UINT32 *)(x))->v)
#endif
#ifndef __UNALIGNED_UINT16_WRITE
__PACKED_STRUCT T_UINT16_WRITE { uint16_t v; };
#define __UNALIGNED_UINT16_WRITE(addr, val) (void)((((struct T_UINT16_WRITE *)(void *)(addr))->v) = (val))
#endif
#ifndef __UNALIGNED_UINT16_READ
__PACKED_STRUCT T_UINT16_READ { uint16_t v; };
#define __UNALIGNED_UINT16_READ(addr) (((const struct T_UINT16_READ *)(const void *)(addr))->v)
#endif
#ifndef __UNALIGNED_UINT32_WRITE
__PACKED_STRUCT T_UINT32_WRITE { uint32_t v; };
#define __UNALIGNED_UINT32_WRITE(addr, val) (void)((((struct T_UINT32_WRITE *)(void *)(addr))->v) = (val))
#endif
#ifndef __UNALIGNED_UINT32_READ
__PACKED_STRUCT T_UINT32_READ { uint32_t v; };
#define __UNALIGNED_UINT32_READ(addr) (((const struct T_UINT32_READ *)(const void *)(addr))->v)
#endif
#ifndef __ALIGNED
#define __ALIGNED(x) __align(x)
#endif
#ifndef __RESTRICT
#warning No compiler specific solution for __RESTRICT. __RESTRICT is ignored.
#define __RESTRICT
#endif
#ifndef __COMPILER_BARRIER
#warning No compiler specific solution for __COMPILER_BARRIER. __COMPILER_BARRIER is ignored.
#define __COMPILER_BARRIER() (void)0
#endif
/*
* COSMIC Compiler
*/
#elif defined ( __CSMC__ )
#include <cmsis_csm.h>
#ifndef __ASM
#define __ASM _asm
#endif
#ifndef __INLINE
#define __INLINE inline
#endif
#ifndef __STATIC_INLINE
#define __STATIC_INLINE static inline
#endif
#ifndef __STATIC_FORCEINLINE
#define __STATIC_FORCEINLINE __STATIC_INLINE
#endif
#ifndef __NO_RETURN
// NO RETURN is automatically detected hence no warning here
#define __NO_RETURN
#endif
#ifndef __USED
#warning No compiler specific solution for __USED. __USED is ignored.
#define __USED
#endif
#ifndef __WEAK
#define __WEAK __weak
#endif
#ifndef __PACKED
#define __PACKED @packed
#endif
#ifndef __PACKED_STRUCT
#define __PACKED_STRUCT @packed struct
#endif
#ifndef __PACKED_UNION
#define __PACKED_UNION @packed union
#endif
#ifndef __UNALIGNED_UINT32 /* deprecated */
@packed struct T_UINT32 { uint32_t v; };
#define __UNALIGNED_UINT32(x) (((struct T_UINT32 *)(x))->v)
#endif
#ifndef __UNALIGNED_UINT16_WRITE
__PACKED_STRUCT T_UINT16_WRITE { uint16_t v; };
#define __UNALIGNED_UINT16_WRITE(addr, val) (void)((((struct T_UINT16_WRITE *)(void *)(addr))->v) = (val))
#endif
#ifndef __UNALIGNED_UINT16_READ
__PACKED_STRUCT T_UINT16_READ { uint16_t v; };
#define __UNALIGNED_UINT16_READ(addr) (((const struct T_UINT16_READ *)(const void *)(addr))->v)
#endif
#ifndef __UNALIGNED_UINT32_WRITE
__PACKED_STRUCT T_UINT32_WRITE { uint32_t v; };
#define __UNALIGNED_UINT32_WRITE(addr, val) (void)((((struct T_UINT32_WRITE *)(void *)(addr))->v) = (val))
#endif
#ifndef __UNALIGNED_UINT32_READ
__PACKED_STRUCT T_UINT32_READ { uint32_t v; };
#define __UNALIGNED_UINT32_READ(addr) (((const struct T_UINT32_READ *)(const void *)(addr))->v)
#endif
#ifndef __ALIGNED
#warning No compiler specific solution for __ALIGNED. __ALIGNED is ignored.
#define __ALIGNED(x)
#endif
#ifndef __RESTRICT
#warning No compiler specific solution for __RESTRICT. __RESTRICT is ignored.
#define __RESTRICT
#endif
#ifndef __COMPILER_BARRIER
#warning No compiler specific solution for __COMPILER_BARRIER. __COMPILER_BARRIER is ignored.
#define __COMPILER_BARRIER() (void)0
#endif
#else
#error Unknown compiler.
#endif
#endif /* __CMSIS_COMPILER_H */

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,40 @@
/**************************************************************************//**
* @file cmsis_version.h
* @brief CMSIS Core(M) Version definitions
* @version V5.0.3
* @date 24. June 2019
******************************************************************************/
/*
* Copyright (c) 2009-2019 ARM Limited. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the License); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if defined ( __ICCARM__ )
#pragma system_include /* treat file as system include file for MISRA check */
#elif defined (__clang__)
#pragma clang system_header /* treat file as system include file */
#endif
#ifndef __CMSIS_VERSION_H
#define __CMSIS_VERSION_H
/* CMSIS Version definitions */
#define __CM_CMSIS_VERSION_MAIN ( 5U) /*!< [31:16] CMSIS Core(M) main version */
#define __CM_CMSIS_VERSION_SUB ( 3U) /*!< [15:0] CMSIS Core(M) sub version */
#define __CM_CMSIS_VERSION ((__CM_CMSIS_VERSION_MAIN << 16U) | \
__CM_CMSIS_VERSION_SUB ) /*!< CMSIS Core(M) version number */
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,346 @@
/******************************************************************************
* @file mpu_armv8.h
* @brief CMSIS MPU API for Armv8-M and Armv8.1-M MPU
* @version V5.1.0
* @date 08. March 2019
******************************************************************************/
/*
* Copyright (c) 2017-2019 Arm Limited. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the License); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if defined ( __ICCARM__ )
#pragma system_include /* treat file as system include file for MISRA check */
#elif defined (__clang__)
#pragma clang system_header /* treat file as system include file */
#endif
#ifndef ARM_MPU_ARMV8_H
#define ARM_MPU_ARMV8_H
/** \brief Attribute for device memory (outer only) */
#define ARM_MPU_ATTR_DEVICE ( 0U )
/** \brief Attribute for non-cacheable, normal memory */
#define ARM_MPU_ATTR_NON_CACHEABLE ( 4U )
/** \brief Attribute for normal memory (outer and inner)
* \param NT Non-Transient: Set to 1 for non-transient data.
* \param WB Write-Back: Set to 1 to use write-back update policy.
* \param RA Read Allocation: Set to 1 to use cache allocation on read miss.
* \param WA Write Allocation: Set to 1 to use cache allocation on write miss.
*/
#define ARM_MPU_ATTR_MEMORY_(NT, WB, RA, WA) \
(((NT & 1U) << 3U) | ((WB & 1U) << 2U) | ((RA & 1U) << 1U) | (WA & 1U))
/** \brief Device memory type non Gathering, non Re-ordering, non Early Write Acknowledgement */
#define ARM_MPU_ATTR_DEVICE_nGnRnE (0U)
/** \brief Device memory type non Gathering, non Re-ordering, Early Write Acknowledgement */
#define ARM_MPU_ATTR_DEVICE_nGnRE (1U)
/** \brief Device memory type non Gathering, Re-ordering, Early Write Acknowledgement */
#define ARM_MPU_ATTR_DEVICE_nGRE (2U)
/** \brief Device memory type Gathering, Re-ordering, Early Write Acknowledgement */
#define ARM_MPU_ATTR_DEVICE_GRE (3U)
/** \brief Memory Attribute
* \param O Outer memory attributes
* \param I O == ARM_MPU_ATTR_DEVICE: Device memory attributes, else: Inner memory attributes
*/
#define ARM_MPU_ATTR(O, I) (((O & 0xFU) << 4U) | (((O & 0xFU) != 0U) ? (I & 0xFU) : ((I & 0x3U) << 2U)))
/** \brief Normal memory non-shareable */
#define ARM_MPU_SH_NON (0U)
/** \brief Normal memory outer shareable */
#define ARM_MPU_SH_OUTER (2U)
/** \brief Normal memory inner shareable */
#define ARM_MPU_SH_INNER (3U)
/** \brief Memory access permissions
* \param RO Read-Only: Set to 1 for read-only memory.
* \param NP Non-Privileged: Set to 1 for non-privileged memory.
*/
#define ARM_MPU_AP_(RO, NP) (((RO & 1U) << 1U) | (NP & 1U))
/** \brief Region Base Address Register value
* \param BASE The base address bits [31:5] of a memory region. The value is zero extended. Effective address gets 32 byte aligned.
* \param SH Defines the Shareability domain for this memory region.
* \param RO Read-Only: Set to 1 for a read-only memory region.
* \param NP Non-Privileged: Set to 1 for a non-privileged memory region.
* \oaram XN eXecute Never: Set to 1 for a non-executable memory region.
*/
#define ARM_MPU_RBAR(BASE, SH, RO, NP, XN) \
((BASE & MPU_RBAR_BASE_Msk) | \
((SH << MPU_RBAR_SH_Pos) & MPU_RBAR_SH_Msk) | \
((ARM_MPU_AP_(RO, NP) << MPU_RBAR_AP_Pos) & MPU_RBAR_AP_Msk) | \
((XN << MPU_RBAR_XN_Pos) & MPU_RBAR_XN_Msk))
/** \brief Region Limit Address Register value
* \param LIMIT The limit address bits [31:5] for this memory region. The value is one extended.
* \param IDX The attribute index to be associated with this memory region.
*/
#define ARM_MPU_RLAR(LIMIT, IDX) \
((LIMIT & MPU_RLAR_LIMIT_Msk) | \
((IDX << MPU_RLAR_AttrIndx_Pos) & MPU_RLAR_AttrIndx_Msk) | \
(MPU_RLAR_EN_Msk))
#if defined(MPU_RLAR_PXN_Pos)
/** \brief Region Limit Address Register with PXN value
* \param LIMIT The limit address bits [31:5] for this memory region. The value is one extended.
* \param PXN Privileged execute never. Defines whether code can be executed from this privileged region.
* \param IDX The attribute index to be associated with this memory region.
*/
#define ARM_MPU_RLAR_PXN(LIMIT, PXN, IDX) \
((LIMIT & MPU_RLAR_LIMIT_Msk) | \
((PXN << MPU_RLAR_PXN_Pos) & MPU_RLAR_PXN_Msk) | \
((IDX << MPU_RLAR_AttrIndx_Pos) & MPU_RLAR_AttrIndx_Msk) | \
(MPU_RLAR_EN_Msk))
#endif
/**
* Struct for a single MPU Region
*/
typedef struct {
uint32_t RBAR; /*!< Region Base Address Register value */
uint32_t RLAR; /*!< Region Limit Address Register value */
} ARM_MPU_Region_t;
/** Enable the MPU.
* \param MPU_Control Default access permissions for unconfigured regions.
*/
__STATIC_INLINE void ARM_MPU_Enable(uint32_t MPU_Control)
{
MPU->CTRL = MPU_Control | MPU_CTRL_ENABLE_Msk;
#ifdef SCB_SHCSR_MEMFAULTENA_Msk
SCB->SHCSR |= SCB_SHCSR_MEMFAULTENA_Msk;
#endif
__DSB();
__ISB();
}
/** Disable the MPU.
*/
__STATIC_INLINE void ARM_MPU_Disable(void)
{
__DMB();
#ifdef SCB_SHCSR_MEMFAULTENA_Msk
SCB->SHCSR &= ~SCB_SHCSR_MEMFAULTENA_Msk;
#endif
MPU->CTRL &= ~MPU_CTRL_ENABLE_Msk;
}
#ifdef MPU_NS
/** Enable the Non-secure MPU.
* \param MPU_Control Default access permissions for unconfigured regions.
*/
__STATIC_INLINE void ARM_MPU_Enable_NS(uint32_t MPU_Control)
{
MPU_NS->CTRL = MPU_Control | MPU_CTRL_ENABLE_Msk;
#ifdef SCB_SHCSR_MEMFAULTENA_Msk
SCB_NS->SHCSR |= SCB_SHCSR_MEMFAULTENA_Msk;
#endif
__DSB();
__ISB();
}
/** Disable the Non-secure MPU.
*/
__STATIC_INLINE void ARM_MPU_Disable_NS(void)
{
__DMB();
#ifdef SCB_SHCSR_MEMFAULTENA_Msk
SCB_NS->SHCSR &= ~SCB_SHCSR_MEMFAULTENA_Msk;
#endif
MPU_NS->CTRL &= ~MPU_CTRL_ENABLE_Msk;
}
#endif
/** Set the memory attribute encoding to the given MPU.
* \param mpu Pointer to the MPU to be configured.
* \param idx The attribute index to be set [0-7]
* \param attr The attribute value to be set.
*/
__STATIC_INLINE void ARM_MPU_SetMemAttrEx(MPU_Type* mpu, uint8_t idx, uint8_t attr)
{
const uint8_t reg = idx / 4U;
const uint32_t pos = ((idx % 4U) * 8U);
const uint32_t mask = 0xFFU << pos;
if (reg >= (sizeof(mpu->MAIR) / sizeof(mpu->MAIR[0]))) {
return; // invalid index
}
mpu->MAIR[reg] = ((mpu->MAIR[reg] & ~mask) | ((attr << pos) & mask));
}
/** Set the memory attribute encoding.
* \param idx The attribute index to be set [0-7]
* \param attr The attribute value to be set.
*/
__STATIC_INLINE void ARM_MPU_SetMemAttr(uint8_t idx, uint8_t attr)
{
ARM_MPU_SetMemAttrEx(MPU, idx, attr);
}
#ifdef MPU_NS
/** Set the memory attribute encoding to the Non-secure MPU.
* \param idx The attribute index to be set [0-7]
* \param attr The attribute value to be set.
*/
__STATIC_INLINE void ARM_MPU_SetMemAttr_NS(uint8_t idx, uint8_t attr)
{
ARM_MPU_SetMemAttrEx(MPU_NS, idx, attr);
}
#endif
/** Clear and disable the given MPU region of the given MPU.
* \param mpu Pointer to MPU to be used.
* \param rnr Region number to be cleared.
*/
__STATIC_INLINE void ARM_MPU_ClrRegionEx(MPU_Type* mpu, uint32_t rnr)
{
mpu->RNR = rnr;
mpu->RLAR = 0U;
}
/** Clear and disable the given MPU region.
* \param rnr Region number to be cleared.
*/
__STATIC_INLINE void ARM_MPU_ClrRegion(uint32_t rnr)
{
ARM_MPU_ClrRegionEx(MPU, rnr);
}
#ifdef MPU_NS
/** Clear and disable the given Non-secure MPU region.
* \param rnr Region number to be cleared.
*/
__STATIC_INLINE void ARM_MPU_ClrRegion_NS(uint32_t rnr)
{
ARM_MPU_ClrRegionEx(MPU_NS, rnr);
}
#endif
/** Configure the given MPU region of the given MPU.
* \param mpu Pointer to MPU to be used.
* \param rnr Region number to be configured.
* \param rbar Value for RBAR register.
* \param rlar Value for RLAR register.
*/
__STATIC_INLINE void ARM_MPU_SetRegionEx(MPU_Type* mpu, uint32_t rnr, uint32_t rbar, uint32_t rlar)
{
mpu->RNR = rnr;
mpu->RBAR = rbar;
mpu->RLAR = rlar;
}
/** Configure the given MPU region.
* \param rnr Region number to be configured.
* \param rbar Value for RBAR register.
* \param rlar Value for RLAR register.
*/
__STATIC_INLINE void ARM_MPU_SetRegion(uint32_t rnr, uint32_t rbar, uint32_t rlar)
{
ARM_MPU_SetRegionEx(MPU, rnr, rbar, rlar);
}
#ifdef MPU_NS
/** Configure the given Non-secure MPU region.
* \param rnr Region number to be configured.
* \param rbar Value for RBAR register.
* \param rlar Value for RLAR register.
*/
__STATIC_INLINE void ARM_MPU_SetRegion_NS(uint32_t rnr, uint32_t rbar, uint32_t rlar)
{
ARM_MPU_SetRegionEx(MPU_NS, rnr, rbar, rlar);
}
#endif
/** Memcopy with strictly ordered memory access, e.g. for register targets.
* \param dst Destination data is copied to.
* \param src Source data is copied from.
* \param len Amount of data words to be copied.
*/
__STATIC_INLINE void ARM_MPU_OrderedMemcpy(volatile uint32_t* dst, const uint32_t* __RESTRICT src, uint32_t len)
{
uint32_t i;
for (i = 0U; i < len; ++i)
{
dst[i] = src[i];
}
}
/** Load the given number of MPU regions from a table to the given MPU.
* \param mpu Pointer to the MPU registers to be used.
* \param rnr First region number to be configured.
* \param table Pointer to the MPU configuration table.
* \param cnt Amount of regions to be configured.
*/
__STATIC_INLINE void ARM_MPU_LoadEx(MPU_Type* mpu, uint32_t rnr, ARM_MPU_Region_t const* table, uint32_t cnt)
{
const uint32_t rowWordSize = sizeof(ARM_MPU_Region_t)/4U;
if (cnt == 1U) {
mpu->RNR = rnr;
ARM_MPU_OrderedMemcpy(&(mpu->RBAR), &(table->RBAR), rowWordSize);
} else {
uint32_t rnrBase = rnr & ~(MPU_TYPE_RALIASES-1U);
uint32_t rnrOffset = rnr % MPU_TYPE_RALIASES;
mpu->RNR = rnrBase;
while ((rnrOffset + cnt) > MPU_TYPE_RALIASES) {
uint32_t c = MPU_TYPE_RALIASES - rnrOffset;
ARM_MPU_OrderedMemcpy(&(mpu->RBAR)+(rnrOffset*2U), &(table->RBAR), c*rowWordSize);
table += c;
cnt -= c;
rnrOffset = 0U;
rnrBase += MPU_TYPE_RALIASES;
mpu->RNR = rnrBase;
}
ARM_MPU_OrderedMemcpy(&(mpu->RBAR)+(rnrOffset*2U), &(table->RBAR), cnt*rowWordSize);
}
}
/** Load the given number of MPU regions from a table.
* \param rnr First region number to be configured.
* \param table Pointer to the MPU configuration table.
* \param cnt Amount of regions to be configured.
*/
__STATIC_INLINE void ARM_MPU_Load(uint32_t rnr, ARM_MPU_Region_t const* table, uint32_t cnt)
{
ARM_MPU_LoadEx(MPU, rnr, table, cnt);
}
#ifdef MPU_NS
/** Load the given number of MPU regions from a table to the Non-secure MPU.
* \param rnr First region number to be configured.
* \param table Pointer to the MPU configuration table.
* \param cnt Amount of regions to be configured.
*/
__STATIC_INLINE void ARM_MPU_Load_NS(uint32_t rnr, ARM_MPU_Region_t const* table, uint32_t cnt)
{
ARM_MPU_LoadEx(MPU_NS, rnr, table, cnt);
}
#endif
#endif

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,243 @@
/**
******************************************************************************
* @file stm32h7xx.h
* @author MCD Application Team
* @brief CMSIS STM32H7xx Device Peripheral Access Layer Header File.
*
* The file is the unique include file that the application programmer
* is using in the C source code, usually in main.c. This file contains:
* - Configuration section that allows to select:
* - The STM32H7xx device used in the target application
* - To use or not the peripherals drivers in application code(i.e.
* code will be based on direct access to peripherals registers
* rather than drivers API), this option is controlled by
* "#define USE_HAL_DRIVER"
*
******************************************************************************
* @attention
*
* <h2><center>&copy; Copyright (c) 2017 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
/** @addtogroup CMSIS
* @{
*/
/** @addtogroup stm32h7xx
* @{
*/
#ifndef STM32H7xx_H
#define STM32H7xx_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/** @addtogroup Library_configuration_section
* @{
*/
/**
* @brief STM32 Family
*/
#if !defined (STM32H7)
#define STM32H7
#endif /* STM32H7 */
/* Uncomment the line below according to the target STM32H7 device used in your
application
*/
/* #if !defined (STM32H743xx) && !defined (STM32H753xx) && !defined (STM32H750xx) && !defined (STM32H742xx) && \
!defined (STM32H745xx) && !defined (STM32H755xx) && !defined (STM32H747xx) && !defined (STM32H757xx) && \
!defined (STM32H7A3xx) && !defined (STM32H7A3xxQ) && !defined (STM32H7B3xx) && !defined (STM32H7B3xxQ) && !defined (STM32H7B0xx) && !defined (STM32H7B0xxQ) && \
!defined (STM32H735xx) && !defined (STM32H733xx) && !defined (STM32H730xx) && !defined (STM32H730xxQ) && !defined (STM32H725xx) && !defined (STM32H723xx) */
/* #define STM32H742xx */ /*!< STM32H742VI, STM32H742ZI, STM32H742AI, STM32H742II, STM32H742BI, STM32H742XI Devices */
/* #define STM32H743xx */ /*!< STM32H743VI, STM32H743ZI, STM32H743AI, STM32H743II, STM32H743BI, STM32H743XI Devices */
/* #define STM32H753xx */ /*!< STM32H753VI, STM32H753ZI, STM32H753AI, STM32H753II, STM32H753BI, STM32H753XI Devices */
/* #define STM32H750xx */ /*!< STM32H750V, STM32H750I, STM32H750X Devices */
/* #define STM32H747xx */ /*!< STM32H747ZI, STM32H747AI, STM32H747II, STM32H747BI, STM32H747XI Devices */
/* #define STM32H757xx */ /*!< STM32H757ZI, STM32H757AI, STM32H757II, STM32H757BI, STM32H757XI Devices */
/* #define STM32H745xx */ /*!< STM32H745ZI, STM32H745II, STM32H745BI, STM32H745XI Devices */
/* #define STM32H755xx */ /*!< STM32H755ZI, STM32H755II, STM32H755BI, STM32H755XI Devices */
/* #define STM32H7B0xx */ /*!< STM32H7B0ABIxQ, STM32H7B0IBTx, STM32H7B0RBTx, STM32H7B0VBTx, STM32H7B0ZBTx, STM32H7B0IBKxQ */
/* #define STM32H7A3xx */ /*!< STM32H7A3IIK6, STM32H7A3IIT6, STM32H7A3NIH6, STM32H7A3RIT6, STM32H7A3VIH6, STM32H7A3VIT6, STM32H7A3ZIT6 */
/* #define STM32H7A3xxQ */ /*!< STM32H7A3QIY6Q, STM32H7A3IIK6Q, STM32H7A3IIT6Q, STM32H7A3LIH6Q, STM32H7A3VIH6Q, STM32H7A3VIT6Q, STM32H7A3AII6Q, STM32H7A3ZIT6Q */
/* #define STM32H7B3xx */ /*!< STM32H7B3IIK6, STM32H7B3IIT6, STM32H7B3NIH6, STM32H7B3RIT6, STM32H7B3VIH6, STM32H7B3VIT6, STM32H7B3ZIT6 */
/* #define STM32H7B3xxQ */ /*!< STM32H7B3QIY6Q, STM32H7B3IIK6Q, STM32H7B3IIT6Q, STM32H7B3LIH6Q, STM32H7B3VIH6Q, STM32H7B3VIT6Q, STM32H7B3AII6Q, STM32H7B3ZIT6Q */
/* #define STM32H735xx */ /*!< STM32H735AGI6, STM32H735IGK6, STM32H735RGV6, STM32H735VGT6, STM32H735VGY6, STM32H735ZGT6 Devices */
/* #define STM32H733xx */ /*!< STM32H733VGH6, STM32H733VGT6, STM32H733ZGI6, STM32H733ZGT6, Devices */
/* #define STM32H730xx */ /*!< STM32H730VBH6, STM32H730VBT6, STM32H730ZBT6, STM32H730ZBI6 Devices */
/* #define STM32H730xxQ */ /*!< STM32H730IBT6Q, STM32H730ABI6Q, STM32H730IBK6Q Devices */
/* #define STM32H725xx */ /*!< STM32H725AGI6, STM32H725IGK6, STM32H725IGT6, STM32H725RGV6, STM32H725VGT6, STM32H725VGY6, STM32H725ZGT6, STM32H725REV6, SM32H725VET6, STM32H725ZET6, STM32H725AEI6, STM32H725IET6, STM32H725IEK6 Devices */
/* #define STM32H723xx */ /*!< STM32H723VGH6, STM32H723VGT6, STM32H723ZGI6, STM32H723ZGT6, STM32H723VET6, STM32H723VEH6, STM32H723ZET6, STM32H723ZEI6 Devices */
/* #endif */
/* Tip: To avoid modifying this file each time you need to switch between these
devices, you can define the device in your toolchain compiler preprocessor.
*/
#if defined(DUAL_CORE) && !defined(CORE_CM4) && !defined(CORE_CM7)
#error "Dual core device, please select CORE_CM4 or CORE_CM7"
#endif
#if !defined (USE_HAL_DRIVER)
/**
* @brief Comment the line below if you will not use the peripherals drivers.
In this case, these drivers will not be included and the application code will
be based on direct access to peripherals registers
*/
/*#define USE_HAL_DRIVER */
#endif /* USE_HAL_DRIVER */
/**
* @brief CMSIS Device version number V1.10.0
*/
#define __STM32H7xx_CMSIS_DEVICE_VERSION_MAIN (0x01) /*!< [31:24] main version */
#define __STM32H7xx_CMSIS_DEVICE_VERSION_SUB1 (0x0A) /*!< [23:16] sub1 version */
#define __STM32H7xx_CMSIS_DEVICE_VERSION_SUB2 (0x00) /*!< [15:8] sub2 version */
#define __STM32H7xx_CMSIS_DEVICE_VERSION_RC (0x00) /*!< [7:0] release candidate */
#define __STM32H7xx_CMSIS_DEVICE_VERSION ((__STM32H7xx_CMSIS_DEVICE_VERSION_MAIN << 24)\
|(__STM32H7xx_CMSIS_DEVICE_VERSION_SUB1 << 16)\
|(__STM32H7xx_CMSIS_DEVICE_VERSION_SUB2 << 8 )\
|(__STM32H7xx_CMSIS_DEVICE_VERSION_RC))
/**
* @}
*/
/** @addtogroup Device_Included
* @{
*/
#if defined(STM32H743xx)
#include "stm32h743xx.h"
// #elif defined(STM32H753xx)
// #include "stm32h753xx.h"
// #elif defined(STM32H750xx)
// #include "stm32h750xx.h"
// #elif defined(STM32H742xx)
// #include "stm32h742xx.h"
// #elif defined(STM32H745xx)
// #include "stm32h745xx.h"
// #elif defined(STM32H755xx)
// #include "stm32h755xx.h"
// #elif defined(STM32H747xx)
// #include "stm32h747xx.h"
// #elif defined(STM32H757xx)
// #include "stm32h757xx.h"
// #elif defined(STM32H7B0xx)
// #include "stm32h7b0xx.h"
// #elif defined(STM32H7B0xxQ)
// #include "stm32h7b0xxq.h"
// #elif defined(STM32H7A3xx)
// #include "stm32h7a3xx.h"
// #elif defined(STM32H7B3xx)
// #include "stm32h7b3xx.h"
// #elif defined(STM32H7A3xxQ)
// #include "stm32h7a3xxq.h"
// #elif defined(STM32H7B3xxQ)
// #include "stm32h7b3xxq.h"
#elif defined(STM32H735xx)
#include "stm32h735xx.h"
// #elif defined(STM32H733xx)
// #include "stm32h733xx.h"
// #elif defined(STM32H730xx)
// #include "stm32h730xx.h"
// #elif defined(STM32H730xxQ)
// #include "stm32h730xxq.h"
#elif defined(STM32H725xx)
#include "stm32h725xx.h"
// #elif defined(STM32H723xx)
// #include "stm32h723xx.h"
#else
#error "Please select first the target STM32H7xx device used in your application (in stm32h7xx.h file)"
#endif
/**
* @}
*/
/** @addtogroup Exported_types
* @{
*/
typedef enum
{
RESET = 0,
SET = !RESET
} FlagStatus, ITStatus;
typedef enum
{
DISABLE = 0,
ENABLE = !DISABLE
} FunctionalState;
#define IS_FUNCTIONAL_STATE(STATE) (((STATE) == DISABLE) || ((STATE) == ENABLE))
typedef enum
{
SUCCESS = 0,
ERROR = !SUCCESS
} ErrorStatus;
/**
* @}
*/
/** @addtogroup Exported_macros
* @{
*/
#define SET_BIT(REG, BIT) ((REG) |= (BIT))
#define CLEAR_BIT(REG, BIT) ((REG) &= ~(BIT))
#define READ_BIT(REG, BIT) ((REG) & (BIT))
#define CLEAR_REG(REG) ((REG) = (0x0))
#define WRITE_REG(REG, VAL) ((REG) = (VAL))
#define READ_REG(REG) ((REG))
#define MODIFY_REG(REG, CLEARMASK, SETMASK) WRITE_REG((REG), (((READ_REG(REG)) & (~(CLEARMASK))) | (SETMASK)))
#define POSITION_VAL(VAL) (__CLZ(__RBIT(VAL)))
/**
* @}
*/
#if defined (USE_HAL_DRIVER)
#include "stm32h7xx_hal.h"
#endif /* USE_HAL_DRIVER */
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* STM32H7xx_H */
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

View File

@@ -0,0 +1,221 @@
/**
******************************************************************************
* @file stm32h7xx_hal_def.h
* @author MCD Application Team
* @brief This file contains HAL common defines, enumeration, macros and
* structures definitions.
******************************************************************************
* @attention
*
* <h2><center>&copy; Copyright (c) 2017 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef STM32H7xx_HAL_DEF
#define STM32H7xx_HAL_DEF
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32h7xx.h"
//#include "Legacy/stm32_hal_legacy.h"
//#include <stddef.h>
//#include <math.h>
/* Exported types ------------------------------------------------------------*/
/**
* @brief HAL Status structures definition
*/
typedef enum
{
HAL_OK = 0x00,
HAL_ERROR = 0x01,
HAL_BUSY = 0x02,
HAL_TIMEOUT = 0x03
} HAL_StatusTypeDef;
/**
* @brief HAL Lock structures definition
*/
typedef enum
{
HAL_UNLOCKED = 0x00,
HAL_LOCKED = 0x01
} HAL_LockTypeDef;
/* Exported macro ------------------------------------------------------------*/
#define HAL_MAX_DELAY 0xFFFFFFFFU
#define HAL_IS_BIT_SET(REG, BIT) (((REG) & (BIT)) == (BIT))
#define HAL_IS_BIT_CLR(REG, BIT) (((REG) & (BIT)) == 0U)
#define __HAL_LINKDMA(__HANDLE__, __PPP_DMA_FIELD__, __DMA_HANDLE__) \
do{ \
(__HANDLE__)->__PPP_DMA_FIELD__ = &(__DMA_HANDLE__); \
(__DMA_HANDLE__).Parent = (__HANDLE__); \
} while(0)
#define UNUSED(x) ((void)(x))
/** @brief Reset the Handle's State field.
* @param __HANDLE__: specifies the Peripheral Handle.
* @note This macro can be used for the following purpose:
* - When the Handle is declared as local variable; before passing it as parameter
* to HAL_PPP_Init() for the first time, it is mandatory to use this macro
* to set to 0 the Handle's "State" field.
* Otherwise, "State" field may have any random value and the first time the function
* HAL_PPP_Init() is called, the low level hardware initialization will be missed
* (i.e. HAL_PPP_MspInit() will not be executed).
* - When there is a need to reconfigure the low level hardware: instead of calling
* HAL_PPP_DeInit() then HAL_PPP_Init(), user can make a call to this macro then HAL_PPP_Init().
* In this later function, when the Handle's "State" field is set to 0, it will execute the function
* HAL_PPP_MspInit() which will reconfigure the low level hardware.
* @retval None
*/
#define __HAL_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = 0)
#if (USE_RTOS == 1)
#error " USE_RTOS should be 0 in the current HAL release "
#else
#define __HAL_LOCK(__HANDLE__) \
do{ \
if((__HANDLE__)->Lock == HAL_LOCKED) \
{ \
return HAL_BUSY; \
} \
else \
{ \
(__HANDLE__)->Lock = HAL_LOCKED; \
} \
}while (0)
#define __HAL_UNLOCK(__HANDLE__) \
do{ \
(__HANDLE__)->Lock = HAL_UNLOCKED; \
}while (0)
#endif /* USE_RTOS */
#if defined (__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050) /* ARM Compiler V6 */
#ifndef __weak
#define __weak __attribute__((weak))
#endif
#ifndef __packed
#define __packed __attribute__((packed))
#endif
#elif defined ( __GNUC__ ) && !defined (__CC_ARM) /* GNU Compiler */
#ifndef __weak
#define __weak __attribute__((weak))
#endif /* __weak */
#ifndef __packed
#define __packed __attribute__((__packed__))
#endif /* __packed */
#endif /* __GNUC__ */
/* Macro to get variable aligned on 4-bytes, for __ICCARM__ the directive "#pragma data_alignment=4" must be used instead */
#if defined (__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050) /* ARM Compiler V6 */
#ifndef __ALIGN_BEGIN
#define __ALIGN_BEGIN
#endif
#ifndef __ALIGN_END
#define __ALIGN_END __attribute__ ((aligned (4)))
#endif
#elif defined ( __GNUC__ ) && !defined (__CC_ARM) /* GNU Compiler */
#ifndef __ALIGN_END
#define __ALIGN_END __attribute__ ((aligned (4)))
#endif /* __ALIGN_END */
#ifndef __ALIGN_BEGIN
#define __ALIGN_BEGIN
#endif /* __ALIGN_BEGIN */
#else
#ifndef __ALIGN_END
#define __ALIGN_END
#endif /* __ALIGN_END */
#ifndef __ALIGN_BEGIN
#if defined (__CC_ARM) /* ARM Compiler V5 */
#define __ALIGN_BEGIN __align(4)
#elif defined (__ICCARM__) /* IAR Compiler */
#define __ALIGN_BEGIN
#endif /* __CC_ARM */
#endif /* __ALIGN_BEGIN */
#endif /* __GNUC__ */
/* Macro to get variable aligned on 32-bytes,needed for cache maintenance purpose */
#if defined (__GNUC__) /* GNU Compiler */
#define ALIGN_32BYTES(buf) buf __attribute__ ((aligned (32)))
#elif defined (__ICCARM__) /* IAR Compiler */
#define ALIGN_32BYTES(buf) _Pragma("data_alignment=32") buf
#elif defined (__CC_ARM) /* ARM Compiler */
#define ALIGN_32BYTES(buf) __align(32) buf
#endif
/**
* @brief __RAM_FUNC definition
*/
#if defined ( __CC_ARM ) || (defined (__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050))
/* ARM Compiler V4/V5 and V6
--------------------------
RAM functions are defined using the toolchain options.
Functions that are executed in RAM should reside in a separate source module.
Using the 'Options for File' dialog you can simply change the 'Code / Const'
area of a module to a memory space in physical RAM.
Available memory areas are declared in the 'Target' tab of the 'Options for Target'
dialog.
*/
#define __RAM_FUNC
#elif defined ( __ICCARM__ )
/* ICCARM Compiler
---------------
RAM functions are defined using a specific toolchain keyword "__ramfunc".
*/
#define __RAM_FUNC __ramfunc
#elif defined ( __GNUC__ )
/* GNU Compiler
------------
RAM functions are defined using a specific toolchain attribute
"__attribute__((section(".RamFunc")))".
*/
#define __RAM_FUNC __attribute__((section(".RamFunc")))
#endif
/**
* @brief __NOINLINE definition
*/
#if defined ( __CC_ARM ) || (defined (__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)) || defined ( __GNUC__ )
/* ARM V4/V5 and V6 & GNU Compiler
-------------------------------
*/
#define __NOINLINE __attribute__ ( (noinline) )
#elif defined ( __ICCARM__ )
/* ICCARM Compiler
---------------
*/
#define __NOINLINE _Pragma("optimize = no_inline")
#endif
#ifdef __cplusplus
}
#endif
#endif /* STM32H7xx_HAL_DEF */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

View File

@@ -0,0 +1,489 @@
/**
******************************************************************************
* @file stm32h7xx_hal_gpio_ex.h
* @author MCD Application Team
* @brief Header file of GPIO HAL Extension module.
******************************************************************************
* @attention
*
* <h2><center>&copy; COPYRIGHT(c) 2017 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef STM32H7xx_HAL_GPIO_EX_H
#define STM32H7xx_HAL_GPIO_EX_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32h7xx_hal_def.h"
/** @addtogroup STM32H7xx_HAL_Driver
* @{
*/
/** @addtogroup GPIOEx GPIOEx
* @{
*/
/* Exported types ------------------------------------------------------------*/
/* Exported constants --------------------------------------------------------*/
/** @defgroup GPIOEx_Exported_Constants GPIO Exported Constants
* @{
*/
/** @defgroup GPIO_Alternate_function_selection GPIO Alternate Function Selection
* @{
*/
/**
* @brief AF 0 selection
*/
#define GPIO_AF0_RTC_50Hz ((uint8_t)0x00) /* RTC_50Hz Alternate Function mapping */
#define GPIO_AF0_MCO ((uint8_t)0x00) /* MCO (MCO1 and MCO2) Alternate Function mapping */
#define GPIO_AF0_SWJ ((uint8_t)0x00) /* SWJ (SWD and JTAG) Alternate Function mapping */
#define GPIO_AF0_LCDBIAS ((uint8_t)0x00) /* LCDBIAS Alternate Function mapping */
#define GPIO_AF0_TRACE ((uint8_t)0x00) /* TRACE Alternate Function mapping */
#if defined (PWR_CPUCR_PDDS_D2) /* PWR D1 and D2 domains exists */
#define GPIO_AF0_C1DSLEEP ((uint8_t)0x00) /* Cortex-M7 Deep Sleep Alternate Function mapping : available on STM32H7 Rev.B and above */
#define GPIO_AF0_C1SLEEP ((uint8_t)0x00) /* Cortex-M7 Sleep Alternate Function mapping : available on STM32H7 Rev.B and above */
#define GPIO_AF0_D1PWREN ((uint8_t)0x00) /* Domain 1 PWR enable Alternate Function mapping : available on STM32H7 Rev.B and above */
#define GPIO_AF0_D2PWREN ((uint8_t)0x00) /* Domain 2 PWR enable Alternate Function mapping : available on STM32H7 Rev.B and above */
#if defined(DUAL_CORE)
#define GPIO_AF0_C2DSLEEP ((uint8_t)0x00) /* Cortex-M4 Deep Sleep Alternate Function mapping : available on STM32H7 Rev.B and above */
#define GPIO_AF0_C2SLEEP ((uint8_t)0x00) /* Cortex-M4 Sleep Alternate Function mapping : available on STM32H7 Rev.B and above */
#endif /* DUAL_CORE */
#endif /* PWR_CPUCR_PDDS_D2 */
/**
* @brief AF 1 selection
*/
#define GPIO_AF1_TIM1 ((uint8_t)0x01) /* TIM1 Alternate Function mapping */
#define GPIO_AF1_TIM2 ((uint8_t)0x01) /* TIM2 Alternate Function mapping */
#define GPIO_AF1_TIM16 ((uint8_t)0x01) /* TIM16 Alternate Function mapping */
#define GPIO_AF1_TIM17 ((uint8_t)0x01) /* TIM17 Alternate Function mapping */
#define GPIO_AF1_LPTIM1 ((uint8_t)0x01) /* LPTIM1 Alternate Function mapping */
#if defined(HRTIM1)
#define GPIO_AF1_HRTIM1 ((uint8_t)0x01) /* HRTIM1 Alternate Function mapping */
#endif /* HRTIM1 */
#if defined(SAI4)
#define GPIO_AF1_SAI4 ((uint8_t)0x01) /* SAI4 Alternate Function mapping : available on STM32H72xxx/STM32H73xxx */
#endif /* SAI4 */
#define GPIO_AF1_FMC ((uint8_t)0x01) /* FMC Alternate Function mapping : available on STM32H72xxx/STM32H73xxx */
/**
* @brief AF 2 selection
*/
#define GPIO_AF2_TIM3 ((uint8_t)0x02) /* TIM3 Alternate Function mapping */
#define GPIO_AF2_TIM4 ((uint8_t)0x02) /* TIM4 Alternate Function mapping */
#define GPIO_AF2_TIM5 ((uint8_t)0x02) /* TIM5 Alternate Function mapping */
#define GPIO_AF2_TIM12 ((uint8_t)0x02) /* TIM12 Alternate Function mapping */
#define GPIO_AF2_SAI1 ((uint8_t)0x02) /* SAI1 Alternate Function mapping */
#if defined(HRTIM1)
#define GPIO_AF2_HRTIM1 ((uint8_t)0x02) /* HRTIM1 Alternate Function mapping */
#endif /* HRTIM1 */
#define GPIO_AF2_TIM15 ((uint8_t)0x02) /* TIM15 Alternate Function mapping : available on STM32H7A3xxx/STM32H7B3xxx/STM32H7B0xxx and STM32H72xxx/STM32H73xxx */
#if defined(FDCAN3)
#define GPIO_AF2_FDCAN3 ((uint8_t)0x02) /* FDCAN3 Alternate Function mapping */
#endif /*FDCAN3*/
/**
* @brief AF 3 selection
*/
#define GPIO_AF3_TIM8 ((uint8_t)0x03) /* TIM8 Alternate Function mapping */
#define GPIO_AF3_LPTIM2 ((uint8_t)0x03) /* LPTIM2 Alternate Function mapping */
#define GPIO_AF3_DFSDM1 ((uint8_t)0x03) /* DFSDM Alternate Function mapping */
#define GPIO_AF3_LPTIM3 ((uint8_t)0x03) /* LPTIM3 Alternate Function mapping */
#define GPIO_AF3_LPTIM4 ((uint8_t)0x03) /* LPTIM4 Alternate Function mapping */
#define GPIO_AF3_LPTIM5 ((uint8_t)0x03) /* LPTIM5 Alternate Function mapping */
#define GPIO_AF3_LPUART ((uint8_t)0x03) /* LPUART Alternate Function mapping */
#if defined(OCTOSPIM)
#define GPIO_AF3_OCTOSPIM_P1 ((uint8_t)0x03) /* OCTOSPI Manager Port 1 Alternate Function mapping */
#define GPIO_AF3_OCTOSPIM_P2 ((uint8_t)0x03) /* OCTOSPI Manager Port 2 Alternate Function mapping */
#endif /* OCTOSPIM */
#if defined(HRTIM1)
#define GPIO_AF3_HRTIM1 ((uint8_t)0x03) /* HRTIM1 Alternate Function mapping */
#endif /* HRTIM1 */
#define GPIO_AF3_LTDC ((uint8_t)0x03) /* LTDC Alternate Function mapping : available on STM32H72xxx/STM32H73xxx */
/**
* @brief AF 4 selection
*/
#define GPIO_AF4_I2C1 ((uint8_t)0x04) /* I2C1 Alternate Function mapping */
#define GPIO_AF4_I2C2 ((uint8_t)0x04) /* I2C2 Alternate Function mapping */
#define GPIO_AF4_I2C3 ((uint8_t)0x04) /* I2C3 Alternate Function mapping */
#define GPIO_AF4_I2C4 ((uint8_t)0x04) /* I2C4 Alternate Function mapping */
#if defined(I2C5)
#define GPIO_AF4_I2C5 ((uint8_t)0x04) /* I2C5 Alternate Function mapping */
#endif /* I2C5*/
#define GPIO_AF4_TIM15 ((uint8_t)0x04) /* TIM15 Alternate Function mapping */
#define GPIO_AF4_CEC ((uint8_t)0x04) /* CEC Alternate Function mapping */
#define GPIO_AF4_LPTIM2 ((uint8_t)0x04) /* LPTIM2 Alternate Function mapping */
#define GPIO_AF4_USART1 ((uint8_t)0x04) /* USART1 Alternate Function mapping */
#if defined(USART10)
#define GPIO_AF4_USART10 ((uint8_t)0x04) /* USART10 Alternate Function mapping : available on STM32H72xxx/STM32H73xxx */
#endif /*USART10*/
#define GPIO_AF4_DFSDM1 ((uint8_t)0x04) /* DFSDM Alternate Function mapping */
#if defined(DFSDM2_BASE)
#define GPIO_AF4_DFSDM2 ((uint8_t)0x04) /* DFSDM2 Alternate Function mapping */
#endif /* DFSDM2_BASE */
#define GPIO_AF4_DCMI ((uint8_t)0x04) /* DCMI Alternate Function mapping : available on STM32H7A3xxx/STM32H7B3xxx/STM32H7B0xxx and STM32H72xxx/STM32H73xxx */
#if defined(PSSI)
#define GPIO_AF4_PSSI ((uint8_t)0x04) /* PSSI Alternate Function mapping */
#endif /* PSSI */
#if defined(OCTOSPIM)
#define GPIO_AF4_OCTOSPIM_P1 ((uint8_t)0x04) /* OCTOSPI Manager Port 1 Alternate Function mapping : available on STM32H72xxx/STM32H73xxx */
#endif /* OCTOSPIM */
/**
* @brief AF 5 selection
*/
#define GPIO_AF5_SPI1 ((uint8_t)0x05) /* SPI1 Alternate Function mapping */
#define GPIO_AF5_SPI2 ((uint8_t)0x05) /* SPI2 Alternate Function mapping */
#define GPIO_AF5_SPI3 ((uint8_t)0x05) /* SPI3 Alternate Function mapping */
#define GPIO_AF5_SPI4 ((uint8_t)0x05) /* SPI4 Alternate Function mapping */
#define GPIO_AF5_SPI5 ((uint8_t)0x05) /* SPI5 Alternate Function mapping */
#define GPIO_AF5_SPI6 ((uint8_t)0x05) /* SPI6 Alternate Function mapping */
#define GPIO_AF5_CEC ((uint8_t)0x05) /* CEC Alternate Function mapping */
#if defined(FDCAN3)
#define GPIO_AF5_FDCAN3 ((uint8_t)0x05) /* FDCAN3 Alternate Function mapping */
#endif /*FDCAN3*/
/**
* @brief AF 6 selection
*/
#define GPIO_AF6_SPI2 ((uint8_t)0x06) /* SPI2 Alternate Function mapping */
#define GPIO_AF6_SPI3 ((uint8_t)0x06) /* SPI3 Alternate Function mapping */
#define GPIO_AF6_SAI1 ((uint8_t)0x06) /* SAI1 Alternate Function mapping */
#define GPIO_AF6_I2C4 ((uint8_t)0x06) /* I2C4 Alternate Function mapping */
#if defined(I2C5)
#define GPIO_AF6_I2C5 ((uint8_t)0x06) /* I2C5 Alternate Function mapping */
#endif /* I2C5*/
#define GPIO_AF6_DFSDM1 ((uint8_t)0x06) /* DFSDM Alternate Function mapping */
#define GPIO_AF6_UART4 ((uint8_t)0x06) /* UART4 Alternate Function mapping */
#if defined(DFSDM2_BASE)
#define GPIO_AF6_DFSDM2 ((uint8_t)0x06) /* DFSDM2 Alternate Function mapping */
#endif /* DFSDM2_BASE */
#if defined(SAI3)
#define GPIO_AF6_SAI3 ((uint8_t)0x06) /* SAI3 Alternate Function mapping */
#endif /* SAI3 */
#if defined(OCTOSPIM)
#define GPIO_AF6_OCTOSPIM_P1 ((uint8_t)0x06) /* OCTOSPI Manager Port 1 Alternate Function mapping */
#endif /* OCTOSPIM */
/**
* @brief AF 7 selection
*/
#define GPIO_AF7_SPI2 ((uint8_t)0x07) /* SPI2 Alternate Function mapping */
#define GPIO_AF7_SPI3 ((uint8_t)0x07) /* SPI3 Alternate Function mapping */
#define GPIO_AF7_SPI6 ((uint8_t)0x07) /* SPI6 Alternate Function mapping */
#define GPIO_AF7_USART1 ((uint8_t)0x07) /* USART1 Alternate Function mapping */
#define GPIO_AF7_USART2 ((uint8_t)0x07) /* USART2 Alternate Function mapping */
#define GPIO_AF7_USART3 ((uint8_t)0x07) /* USART3 Alternate Function mapping */
#define GPIO_AF7_USART6 ((uint8_t)0x07) /* USART6 Alternate Function mapping */
#define GPIO_AF7_UART7 ((uint8_t)0x07) /* UART7 Alternate Function mapping */
#define GPIO_AF7_SDMMC1 ((uint8_t)0x07) /* SDMMC1 Alternate Function mapping */
/**
* @brief AF 8 selection
*/
#define GPIO_AF8_SPI6 ((uint8_t)0x08) /* SPI6 Alternate Function mapping */
#if defined(SAI2)
#define GPIO_AF8_SAI2 ((uint8_t)0x08) /* SAI2 Alternate Function mapping */
#endif /*SAI2*/
#define GPIO_AF8_UART4 ((uint8_t)0x08) /* UART4 Alternate Function mapping */
#define GPIO_AF8_UART5 ((uint8_t)0x08) /* UART5 Alternate Function mapping */
#define GPIO_AF8_UART8 ((uint8_t)0x08) /* UART8 Alternate Function mapping */
#define GPIO_AF8_SPDIF ((uint8_t)0x08) /* SPDIF Alternate Function mapping */
#define GPIO_AF8_LPUART ((uint8_t)0x08) /* LPUART Alternate Function mapping */
#define GPIO_AF8_SDMMC1 ((uint8_t)0x08) /* SDMMC1 Alternate Function mapping */
#if defined(SAI4)
#define GPIO_AF8_SAI4 ((uint8_t)0x08) /* SAI4 Alternate Function mapping */
#endif /* SAI4 */
/**
* @brief AF 9 selection
*/
#define GPIO_AF9_FDCAN1 ((uint8_t)0x09) /* FDCAN1 Alternate Function mapping */
#define GPIO_AF9_FDCAN2 ((uint8_t)0x09) /* FDCAN2 Alternate Function mapping */
#define GPIO_AF9_TIM13 ((uint8_t)0x09) /* TIM13 Alternate Function mapping */
#define GPIO_AF9_TIM14 ((uint8_t)0x09) /* TIM14 Alternate Function mapping */
#define GPIO_AF9_SDMMC2 ((uint8_t)0x09) /* SDMMC2 Alternate Function mapping */
#define GPIO_AF9_LTDC ((uint8_t)0x09) /* LTDC Alternate Function mapping */
#define GPIO_AF9_SPDIF ((uint8_t)0x09) /* SPDIF Alternate Function mapping */
#define GPIO_AF9_FMC ((uint8_t)0x09) /* FMC Alternate Function mapping */
#if defined(QUADSPI)
#define GPIO_AF9_QUADSPI ((uint8_t)0x09) /* QUADSPI Alternate Function mapping */
#endif /* QUADSPI */
#if defined(SAI4)
#define GPIO_AF9_SAI4 ((uint8_t)0x09) /* SAI4 Alternate Function mapping */
#endif /* SAI4 */
#if defined(OCTOSPIM)
#define GPIO_AF9_OCTOSPIM_P1 ((uint8_t)0x09) /* OCTOSPI Manager Port 1 Alternate Function mapping */
#define GPIO_AF9_OCTOSPIM_P2 ((uint8_t)0x09) /* OCTOSPI Manager Port 2 Alternate Function mapping */
#endif /* OCTOSPIM */
/**
* @brief AF 10 selection
*/
#if defined(SAI2)
#define GPIO_AF10_SAI2 ((uint8_t)0x0A) /* SAI2 Alternate Function mapping */
#endif /*SAI2*/
#define GPIO_AF10_SDMMC2 ((uint8_t)0x0A) /* SDMMC2 Alternate Function mapping */
#if defined(USB2_OTG_FS)
#define GPIO_AF10_OTG2_FS ((uint8_t)0x0A) /* OTG2_FS Alternate Function mapping */
#endif /*USB2_OTG_FS*/
#define GPIO_AF10_COMP1 ((uint8_t)0x0A) /* COMP1 Alternate Function mapping */
#define GPIO_AF10_COMP2 ((uint8_t)0x0A) /* COMP2 Alternate Function mapping */
#if defined(LTDC)
#define GPIO_AF10_LTDC ((uint8_t)0x0A) /* LTDC Alternate Function mapping */
#endif /*LTDC*/
#define GPIO_AF10_CRS_SYNC ((uint8_t)0x0A) /* CRS Sync Alternate Function mapping : available on STM32H7 Rev.B and above */
#if defined(QUADSPI)
#define GPIO_AF10_QUADSPI ((uint8_t)0x0A) /* QUADSPI Alternate Function mapping */
#endif /* QUADSPI */
#if defined(SAI4)
#define GPIO_AF10_SAI4 ((uint8_t)0x0A) /* SAI4 Alternate Function mapping */
#endif /* SAI4 */
#if !defined(USB2_OTG_FS)
#define GPIO_AF10_OTG1_FS ((uint8_t)0x0A) /* OTG1_FS Alternate Function mapping : available on STM32H7A3xxx/STM32H7B3xxx/STM32H7B0xxx and STM32H72xxx/STM32H73xxx */
#endif /* !USB2_OTG_FS */
#define GPIO_AF10_OTG1_HS ((uint8_t)0x0A) /* OTG1_HS Alternate Function mapping */
#if defined(OCTOSPIM)
#define GPIO_AF10_OCTOSPIM_P1 ((uint8_t)0x0A) /* OCTOSPI Manager Port 1 Alternate Function mapping */
#endif /* OCTOSPIM */
#define GPIO_AF10_TIM8 ((uint8_t)0x0A) /* TIM8 Alternate Function mapping */
#define GPIO_AF10_FMC ((uint8_t)0x0A) /* FMC Alternate Function mapping : available on STM32H7A3xxx/STM32H7B3xxx/STM32H7B0xxx and STM32H72xxx/STM32H73xxx */
/**
* @brief AF 11 selection
*/
#define GPIO_AF11_SWP ((uint8_t)0x0B) /* SWP Alternate Function mapping */
#define GPIO_AF11_MDIOS ((uint8_t)0x0B) /* MDIOS Alternate Function mapping */
#define GPIO_AF11_UART7 ((uint8_t)0x0B) /* UART7 Alternate Function mapping */
#define GPIO_AF11_SDMMC2 ((uint8_t)0x0B) /* SDMMC2 Alternate Function mapping */
#define GPIO_AF11_DFSDM1 ((uint8_t)0x0B) /* DFSDM1 Alternate Function mapping */
#define GPIO_AF11_COMP1 ((uint8_t)0x0B) /* COMP1 Alternate Function mapping */
#define GPIO_AF11_COMP2 ((uint8_t)0x0B) /* COMP2 Alternate Function mapping */
#define GPIO_AF11_TIM1 ((uint8_t)0x0B) /* TIM1 Alternate Function mapping */
#define GPIO_AF11_TIM8 ((uint8_t)0x0B) /* TIM8 Alternate Function mapping */
#define GPIO_AF11_I2C4 ((uint8_t)0x0B) /* I2C4 Alternate Function mapping */
#if defined(DFSDM2_BASE)
#define GPIO_AF11_DFSDM2 ((uint8_t)0x0B) /* DFSDM2 Alternate Function mapping */
#endif /* DFSDM2_BASE */
#if defined(USART10)
#define GPIO_AF11_USART10 ((uint8_t)0x0B) /* USART10 Alternate Function mapping */
#endif /* USART10 */
#if defined(UART9)
#define GPIO_AF11_UART9 ((uint8_t)0x0B) /* UART9 Alternate Function mapping */
#endif /* UART9 */
#if defined(ETH)
#define GPIO_AF11_ETH ((uint8_t)0x0B) /* ETH Alternate Function mapping */
#endif /* ETH */
#if defined(LTDC)
#define GPIO_AF11_LTDC ((uint8_t)0x0B) /* LTDC Alternate Function mapping : available on STM32H7A3xxx/STM32H7B3xxx/STM32H7B0xxx and STM32H72xxx/STM32H73xxx */
#endif /*LTDC*/
#if defined(OCTOSPIM)
#define GPIO_AF11_OCTOSPIM_P1 ((uint8_t)0x0B) /* OCTOSPI Manager Port 1 Alternate Function mapping */
#endif /* OCTOSPIM */
/**
* @brief AF 12 selection
*/
#define GPIO_AF12_FMC ((uint8_t)0x0C) /* FMC Alternate Function mapping */
#define GPIO_AF12_SDMMC1 ((uint8_t)0x0C) /* SDMMC1 Alternate Function mapping */
#define GPIO_AF12_MDIOS ((uint8_t)0x0C) /* MDIOS Alternate Function mapping */
#define GPIO_AF12_COMP1 ((uint8_t)0x0C) /* COMP1 Alternate Function mapping */
#define GPIO_AF12_COMP2 ((uint8_t)0x0C) /* COMP2 Alternate Function mapping */
#define GPIO_AF12_TIM1 ((uint8_t)0x0C) /* TIM1 Alternate Function mapping */
#define GPIO_AF12_TIM8 ((uint8_t)0x0C) /* TIM8 Alternate Function mapping */
#if defined(LTDC)
#define GPIO_AF12_LTDC ((uint8_t)0x0C) /* LTDC Alternate Function mapping */
#endif /*LTDC*/
#if defined(USB2_OTG_FS)
#define GPIO_AF12_OTG1_FS ((uint8_t)0x0C) /* OTG1_FS Alternate Function mapping */
#endif /* USB2_OTG_FS */
#if defined(OCTOSPIM)
#define GPIO_AF12_OCTOSPIM_P1 ((uint8_t)0x0C) /* OCTOSPI Manager Port 1 Alternate Function mapping */
#endif /* OCTOSPIM */
/**
* @brief AF 13 selection
*/
#define GPIO_AF13_DCMI ((uint8_t)0x0D) /* DCMI Alternate Function mapping */
#define GPIO_AF13_COMP1 ((uint8_t)0x0D) /* COMP1 Alternate Function mapping */
#define GPIO_AF13_COMP2 ((uint8_t)0x0D) /* COMP2 Alternate Function mapping */
#if defined(LTDC)
#define GPIO_AF13_LTDC ((uint8_t)0x0D) /* LTDC Alternate Function mapping */
#endif /*LTDC*/
#if defined(DSI)
#define GPIO_AF13_DSI ((uint8_t)0x0D) /* DSI Alternate Function mapping */
#endif /* DSI */
#if defined(PSSI)
#define GPIO_AF13_PSSI ((uint8_t)0x0D) /* PSSI Alternate Function mapping */
#endif /* PSSI */
#define GPIO_AF13_TIM1 ((uint8_t)0x0D) /* TIM1 Alternate Function mapping */
#if defined(TIM23)
#define GPIO_AF13_TIM23 ((uint8_t)0x0D) /* TIM23 Alternate Function mapping */
#endif /*TIM23*/
/**
* @brief AF 14 selection
*/
#define GPIO_AF14_LTDC ((uint8_t)0x0E) /* LTDC Alternate Function mapping */
#define GPIO_AF14_UART5 ((uint8_t)0x0E) /* UART5 Alternate Function mapping */
#if defined(TIM24)
#define GPIO_AF14_TIM24 ((uint8_t)0x0E) /* TIM24 Alternate Function mapping */
#endif /*TIM24*/
/**
* @brief AF 15 selection
*/
#define GPIO_AF15_EVENTOUT ((uint8_t)0x0F) /* EVENTOUT Alternate Function mapping */
#define IS_GPIO_AF(AF) ((AF) <= (uint8_t)0x0F)
/**
* @}
*/
/**
* @}
*/
/* Exported macro ------------------------------------------------------------*/
/** @defgroup GPIOEx_Exported_Macros GPIO Exported Macros
* @{
*/
/**
* @}
*/
/* Exported functions --------------------------------------------------------*/
/** @defgroup GPIOEx_Exported_Functions GPIO Exported Functions
* @{
*/
/**
* @}
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/** @defgroup GPIOEx_Private_Constants GPIO Private Constants
* @{
*/
/**
* @brief GPIO pin available on the platform
*/
/* Defines the available pins per GPIOs */
#define GPIOA_PIN_AVAILABLE GPIO_PIN_All
#define GPIOB_PIN_AVAILABLE GPIO_PIN_All
#define GPIOC_PIN_AVAILABLE GPIO_PIN_All
#define GPIOD_PIN_AVAILABLE GPIO_PIN_All
#define GPIOE_PIN_AVAILABLE GPIO_PIN_All
#define GPIOF_PIN_AVAILABLE GPIO_PIN_All
#define GPIOG_PIN_AVAILABLE GPIO_PIN_All
#if defined(GPIOI)
#define GPIOI_PIN_AVAILABLE GPIO_PIN_All
#endif /*GPIOI*/
#if defined(GPIOI)
#define GPIOJ_PIN_AVAILABLE GPIO_PIN_All
#else
#define GPIOJ_PIN_AVAILABLE (GPIO_PIN_8 | GPIO_PIN_9 | GPIO_PIN_10 | GPIO_PIN_11 )
#endif /* GPIOI */
#define GPIOH_PIN_AVAILABLE GPIO_PIN_All
#if defined(GPIOI)
#define GPIOK_PIN_AVAILABLE (GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3 | GPIO_PIN_4 | \
GPIO_PIN_5 | GPIO_PIN_6 | GPIO_PIN_7)
#else
#define GPIOK_PIN_AVAILABLE (GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_2 )
#endif /* GPIOI */
/**
* @}
*/
/* Private macros ------------------------------------------------------------*/
/** @defgroup GPIOEx_Private_Macros GPIO Private Macros
* @{
*/
/** @defgroup GPIOEx_Get_Port_Index GPIO Get Port Index
* @{
*/
#if defined(GPIOI)
#define GPIO_GET_INDEX(__GPIOx__) (((__GPIOx__) == (GPIOA))? 0UL :\
((__GPIOx__) == (GPIOB))? 1UL :\
((__GPIOx__) == (GPIOC))? 2UL :\
((__GPIOx__) == (GPIOD))? 3UL :\
((__GPIOx__) == (GPIOE))? 4UL :\
((__GPIOx__) == (GPIOF))? 5UL :\
((__GPIOx__) == (GPIOG))? 6UL :\
((__GPIOx__) == (GPIOH))? 7UL :\
((__GPIOx__) == (GPIOI))? 8UL :\
((__GPIOx__) == (GPIOJ))? 9UL : 10UL)
#else
#define GPIO_GET_INDEX(__GPIOx__) (((__GPIOx__) == (GPIOA))? 0UL :\
((__GPIOx__) == (GPIOB))? 1UL :\
((__GPIOx__) == (GPIOC))? 2UL :\
((__GPIOx__) == (GPIOD))? 3UL :\
((__GPIOx__) == (GPIOE))? 4UL :\
((__GPIOx__) == (GPIOF))? 5UL :\
((__GPIOx__) == (GPIOG))? 6UL :\
((__GPIOx__) == (GPIOH))? 7UL :\
((__GPIOx__) == (GPIOJ))? 9UL : 10UL)
#endif /* GPIOI */
/**
* @}
*/
/** @defgroup GPIOEx_IS_Alternat_function_selection GPIO Check Alternate Function
* @{
*/
/**
* @}
*/
/**
* @}
*/
/* Private functions ---------------------------------------------------------*/
/** @defgroup GPIOEx_Private_Functions GPIO Private Functions
* @{
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* STM32H7xx_HAL_GPIO_EX_H */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

View File

@@ -0,0 +1,105 @@
/**
******************************************************************************
* @file system_stm32h7xx.h
* @author MCD Application Team
* @brief CMSIS Cortex-Mx Device System Source File for STM32H7xx devices.
******************************************************************************
* @attention
*
* <h2><center>&copy; Copyright (c) 2017 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
/** @addtogroup CMSIS
* @{
*/
/** @addtogroup stm32h7xx_system
* @{
*/
/**
* @brief Define to prevent recursive inclusion
*/
#ifndef SYSTEM_STM32H7XX_H
#define SYSTEM_STM32H7XX_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup STM32H7xx_System_Includes
* @{
*/
/**
* @}
*/
/** @addtogroup STM32H7xx_System_Exported_types
* @{
*/
/* This variable is updated in three ways:
1) by calling CMSIS function SystemCoreClockUpdate()
2) by calling HAL API function HAL_RCC_GetSysClockFreq()
3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency
Note: If you use this function to configure the system clock; then there
is no need to call the 2 first functions listed above, since SystemCoreClock
variable is updated automatically.
*/
extern uint32_t SystemCoreClock; /*!< System Domain1 Clock Frequency */
extern uint32_t SystemD2Clock; /*!< System Domain2 Clock Frequency */
extern const uint8_t D1CorePrescTable[16] ; /*!< D1CorePrescTable prescalers table values */
/**
* @}
*/
/** @addtogroup STM32H7xx_System_Exported_Constants
* @{
*/
/**
* @}
*/
/** @addtogroup STM32H7xx_System_Exported_Macros
* @{
*/
/**
* @}
*/
/** @addtogroup STM32H7xx_System_Exported_Functions
* @{
*/
extern void SystemInit(void);
extern void SystemCoreClockUpdate(void);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* SYSTEM_STM32H7XX_H */
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

View File

@@ -0,0 +1,74 @@
// ********************* Bare interrupt handlers *********************
// Interrupts for STM32H7x5
void WWDG_IRQHandler(void) {handle_interrupt(WWDG_IRQn);}
void PVD_AVD_IRQHandler(void) {handle_interrupt(PVD_AVD_IRQn);}
void TAMP_STAMP_IRQHandler(void) {handle_interrupt(TAMP_STAMP_IRQn);}
void RTC_WKUP_IRQHandler(void) {handle_interrupt(RTC_WKUP_IRQn);}
void FLASH_IRQHandler(void) {handle_interrupt(FLASH_IRQn);}
void RCC_IRQHandler(void) {handle_interrupt(RCC_IRQn);}
void EXTI0_IRQHandler(void) {handle_interrupt(EXTI0_IRQn);}
void EXTI1_IRQHandler(void) {handle_interrupt(EXTI1_IRQn);}
void EXTI2_IRQHandler(void) {handle_interrupt(EXTI2_IRQn);}
void EXTI3_IRQHandler(void) {handle_interrupt(EXTI3_IRQn);}
void EXTI4_IRQHandler(void) {handle_interrupt(EXTI4_IRQn);}
void DMA1_Stream0_IRQHandler(void) {handle_interrupt(DMA1_Stream0_IRQn);}
void DMA1_Stream1_IRQHandler(void) {handle_interrupt(DMA1_Stream1_IRQn);}
void DMA1_Stream2_IRQHandler(void) {handle_interrupt(DMA1_Stream2_IRQn);}
void DMA1_Stream3_IRQHandler(void) {handle_interrupt(DMA1_Stream3_IRQn);}
void DMA1_Stream4_IRQHandler(void) {handle_interrupt(DMA1_Stream4_IRQn);}
void DMA1_Stream5_IRQHandler(void) {handle_interrupt(DMA1_Stream5_IRQn);}
void DMA1_Stream6_IRQHandler(void) {handle_interrupt(DMA1_Stream6_IRQn);}
void ADC_IRQHandler(void) {handle_interrupt(ADC_IRQn);}
void EXTI9_5_IRQHandler(void) {handle_interrupt(EXTI9_5_IRQn);}
void TIM1_BRK_IRQHandler(void) {handle_interrupt(TIM1_BRK_IRQn);}
void TIM1_UP_TIM10_IRQHandler(void) {handle_interrupt(TIM1_UP_TIM10_IRQn);}
void TIM1_TRG_COM_IRQHandler(void) {handle_interrupt(TIM1_TRG_COM_IRQn);}
void TIM1_CC_IRQHandler(void) {handle_interrupt(TIM1_CC_IRQn);}
void TIM2_IRQHandler(void) {handle_interrupt(TIM2_IRQn);}
void TIM3_IRQHandler(void) {handle_interrupt(TIM3_IRQn);}
void TIM4_IRQHandler(void) {handle_interrupt(TIM4_IRQn);}
void I2C1_EV_IRQHandler(void) {handle_interrupt(I2C1_EV_IRQn);}
void I2C1_ER_IRQHandler(void) {handle_interrupt(I2C1_ER_IRQn);}
void I2C2_EV_IRQHandler(void) {handle_interrupt(I2C2_EV_IRQn);}
void I2C2_ER_IRQHandler(void) {handle_interrupt(I2C2_ER_IRQn);}
void SPI1_IRQHandler(void) {handle_interrupt(SPI1_IRQn);}
void SPI2_IRQHandler(void) {handle_interrupt(SPI2_IRQn);}
void USART1_IRQHandler(void) {handle_interrupt(USART1_IRQn);}
void USART2_IRQHandler(void) {handle_interrupt(USART2_IRQn);}
void USART3_IRQHandler(void) {handle_interrupt(USART3_IRQn);}
void EXTI15_10_IRQHandler(void) {handle_interrupt(EXTI15_10_IRQn);}
void RTC_Alarm_IRQHandler(void) {handle_interrupt(RTC_Alarm_IRQn);}
void TIM8_BRK_TIM12_IRQHandler(void) {handle_interrupt(TIM8_BRK_TIM12_IRQn);}
void TIM8_UP_TIM13_IRQHandler(void) {handle_interrupt(TIM8_UP_TIM13_IRQn);}
void TIM8_TRG_COM_TIM14_IRQHandler(void) {handle_interrupt(TIM8_TRG_COM_TIM14_IRQn);}
void TIM8_CC_IRQHandler(void) {handle_interrupt(TIM8_CC_IRQn);}
void DMA1_Stream7_IRQHandler(void) {handle_interrupt(DMA1_Stream7_IRQn);}
void TIM5_IRQHandler(void) {handle_interrupt(TIM5_IRQn);}
void SPI3_IRQHandler(void) {handle_interrupt(SPI3_IRQn);}
void UART4_IRQHandler(void) {handle_interrupt(UART4_IRQn);}
void UART5_IRQHandler(void) {handle_interrupt(UART5_IRQn);}
void TIM6_DAC_IRQHandler(void) {handle_interrupt(TIM6_DAC_IRQn);}
void TIM7_IRQHandler(void) {handle_interrupt(TIM7_IRQn);}
void DMA2_Stream0_IRQHandler(void) {handle_interrupt(DMA2_Stream0_IRQn);}
void DMA2_Stream1_IRQHandler(void) {handle_interrupt(DMA2_Stream1_IRQn);}
void DMA2_Stream2_IRQHandler(void) {handle_interrupt(DMA2_Stream2_IRQn);}
void DMA2_Stream3_IRQHandler(void) {handle_interrupt(DMA2_Stream3_IRQn);}
void DMA2_Stream4_IRQHandler(void) {handle_interrupt(DMA2_Stream4_IRQn);}
void DMA2_Stream5_IRQHandler(void) {handle_interrupt(DMA2_Stream5_IRQn);}
void DMA2_Stream6_IRQHandler(void) {handle_interrupt(DMA2_Stream6_IRQn);}
void DMA2_Stream7_IRQHandler(void) {handle_interrupt(DMA2_Stream7_IRQn);}
void USART6_IRQHandler(void) {handle_interrupt(USART6_IRQn);}
void I2C3_EV_IRQHandler(void) {handle_interrupt(I2C3_EV_IRQn);}
void I2C3_ER_IRQHandler(void) {handle_interrupt(I2C3_ER_IRQn);}
void FDCAN1_IT0_IRQHandler(void) {handle_interrupt(FDCAN1_IT0_IRQn);}
void FDCAN1_IT1_IRQHandler(void) {handle_interrupt(FDCAN1_IT1_IRQn);}
void FDCAN2_IT0_IRQHandler(void) {handle_interrupt(FDCAN2_IT0_IRQn);}
void FDCAN2_IT1_IRQHandler(void) {handle_interrupt(FDCAN2_IT1_IRQn);}
void FDCAN3_IT0_IRQHandler(void) {handle_interrupt(FDCAN3_IT0_IRQn);}
void FDCAN3_IT1_IRQHandler(void) {handle_interrupt(FDCAN3_IT1_IRQn);}
void FDCAN_CAL_IRQHandler(void) {handle_interrupt(FDCAN_CAL_IRQn);}
void OTG_HS_EP1_OUT_IRQHandler(void) {handle_interrupt(OTG_HS_EP1_OUT_IRQn);}
void OTG_HS_EP1_IN_IRQHandler(void) {handle_interrupt(OTG_HS_EP1_IN_IRQn);}
void OTG_HS_WKUP_IRQHandler(void) {handle_interrupt(OTG_HS_WKUP_IRQn);}
void OTG_HS_IRQHandler(void) {handle_interrupt(OTG_HS_IRQn);}

View File

@@ -0,0 +1,48 @@
// 5VOUT_S = ADC12_INP5
// VOLT_S = ADC1_INP2
#define ADCCHAN_VOLTAGE 2
void adc_init(void) {
ADC1->CR &= ~(ADC_CR_DEEPPWD); //Reset deep-power-down mode
ADC1->CR |= ADC_CR_ADVREGEN; // Enable ADC regulator
while(!(ADC1->ISR & ADC_ISR_LDORDY));
ADC1->CR &= ~(ADC_CR_ADCALDIF); // Choose single-ended calibration
ADC1->CR |= ADC_CR_ADCALLIN; // Lineriality calibration
ADC1->CR |= ADC_CR_ADCAL; // Start calibrtation
while((ADC1->CR & ADC_CR_ADCAL) != 0);
ADC1->ISR |= ADC_ISR_ADRDY;
ADC1->CR |= ADC_CR_ADEN;
while(!(ADC1->ISR & ADC_ISR_ADRDY));
}
uint32_t adc_get(unsigned int channel) {
ADC1->SQR1 &= ~(ADC_SQR1_L);
ADC1->SQR1 = (channel << 6U);
ADC1->SMPR1 = (0x7U << (channel * 3U) );
ADC1->PCSEL_RES0 = (0x1U << channel);
ADC1->CR |= ADC_CR_ADSTART;
while (!(ADC1->ISR & ADC_ISR_EOC));
uint16_t res = ADC1->DR;
while (!(ADC1->ISR & ADC_ISR_EOS));
ADC1->ISR |= ADC_ISR_EOS;
return res;
}
uint32_t adc_get_voltage(void) {
// REVC has a 10, 1 (1/11) voltage divider
// Here is the calculation for the scale (s)
// ADCV = VIN_S * (1/11) * (65535/3.3)
// RETVAL = ADCV * s = VIN_S*1000
// s = 1000/((65535/3.3)*(1/11)) = 0.553902494
// Avoid needing floating point math, so output in mV
return (adc_get(ADCCHAN_VOLTAGE) * 5539U) / 10000U;
}

View File

@@ -0,0 +1,2 @@
void EXTI2_IRQ_Handler(void) { }
void fan_init(void){ }

View File

@@ -0,0 +1,210 @@
#define FDCAN_MESSAGE_RAM_SIZE 0x2800UL
#define FDCAN_START_ADDRESS 0x4000AC00UL
#define FDCAN_OFFSET 3412UL // bytes for each FDCAN module
#define FDCAN_OFFSET_W 853UL // words for each FDCAN module
#define FDCAN_END_ADDRESS 0x4000D3FCUL // Message RAM has a width of 4 Bytes
// With this settings we can go up to 6Mbit/s
#define CAN_SYNC_JW 1U // 1 to 4
#define CAN_PHASE_SEG1 6U // =(PROP_SEG + PHASE_SEG1) , 1 to 16
#define CAN_PHASE_SEG2 1U // 1 to 8
#define CAN_PCLK 48000U // Sourced from PLL1Q
#define CAN_QUANTA (1U + CAN_PHASE_SEG1 + CAN_PHASE_SEG2)
// Valid speeds in kbps and their prescalers:
// 10=600, 20=300, 50=120, 83.333=72, 100=60, 125=48, 250=24, 500=12, 1000=6, 2000=3, 3000=2, 6000=1
#define can_speed_to_prescaler(x) (CAN_PCLK / CAN_QUANTA * 10U / (x))
// RX FIFO 0
#define FDCAN_RX_FIFO_0_EL_CNT 32UL
#define FDCAN_RX_FIFO_0_HEAD_SIZE 8UL // bytes
#define FDCAN_RX_FIFO_0_DATA_SIZE 8UL // bytes
#define FDCAN_RX_FIFO_0_EL_SIZE (FDCAN_RX_FIFO_0_HEAD_SIZE + FDCAN_RX_FIFO_0_DATA_SIZE)
#define FDCAN_RX_FIFO_0_EL_W_SIZE (FDCAN_RX_FIFO_0_EL_SIZE / 4UL)
#define FDCAN_RX_FIFO_0_OFFSET 0UL
// TX FIFO
#define FDCAN_TX_FIFO_EL_CNT 32UL
#define FDCAN_TX_FIFO_HEAD_SIZE 8UL // bytes
#define FDCAN_TX_FIFO_DATA_SIZE 8UL // bytes
#define FDCAN_TX_FIFO_EL_SIZE (FDCAN_TX_FIFO_HEAD_SIZE + FDCAN_TX_FIFO_DATA_SIZE)
#define FDCAN_TX_FIFO_EL_W_SIZE (FDCAN_TX_FIFO_EL_SIZE / 4UL)
#define FDCAN_TX_FIFO_OFFSET (FDCAN_RX_FIFO_0_OFFSET + (FDCAN_RX_FIFO_0_EL_CNT * FDCAN_RX_FIFO_0_EL_W_SIZE))
#define CAN_NAME_FROM_CANIF(CAN_DEV) (((CAN_DEV)==FDCAN1) ? "FDCAN1" : (((CAN_DEV) == FDCAN2) ? "FDCAN2" : "FDCAN3"))
#define CAN_NUM_FROM_CANIF(CAN_DEV) (((CAN_DEV)==FDCAN1) ? 0UL : (((CAN_DEV) == FDCAN2) ? 1UL : 2UL))
// For backwards compatibility with safety code
typedef struct {
__IO uint32_t RIR; /*!< CAN receive FIFO mailbox identifier register */
__IO uint32_t RDTR; /*!< CAN receive FIFO mailbox data length control and time stamp register */
__IO uint32_t RDLR; /*!< CAN receive FIFO mailbox data low register */
__IO uint32_t RDHR; /*!< CAN receive FIFO mailbox data high register */
} CAN_FIFOMailBox_TypeDef;
void puts(const char *a);
bool fdcan_request_init(FDCAN_GlobalTypeDef *CANx) {
bool ret = true;
// Exit from sleep mode
CANx->CCCR &= ~(FDCAN_CCCR_CSR);
while ((CANx->CCCR & FDCAN_CCCR_CSA) == FDCAN_CCCR_CSA);
// Request init
uint32_t timeout_counter = 0U;
CANx->CCCR |= FDCAN_CCCR_INIT;
while ((CANx->CCCR & FDCAN_CCCR_INIT) == 0) {
// Delay for about 1ms
delay(10000);
timeout_counter++;
if (timeout_counter >= CAN_INIT_TIMEOUT_MS){
ret = false;
break;
}
}
return ret;
}
bool fdcan_exit_init(FDCAN_GlobalTypeDef *CANx) {
bool ret = true;
CANx->CCCR &= ~(FDCAN_CCCR_INIT);
uint32_t timeout_counter = 0U;
while ((CANx->CCCR & FDCAN_CCCR_INIT) != 0) {
// Delay for about 1ms
delay(10000);
timeout_counter++;
if (timeout_counter >= CAN_INIT_TIMEOUT_MS) {
ret = false;
break;
}
}
return ret;
}
bool llcan_set_speed(FDCAN_GlobalTypeDef *CANx, uint32_t speed, uint32_t data_speed, bool loopback, bool silent) {
bool ret = fdcan_request_init(CANx);
if (ret) {
// Enable config change
CANx->CCCR |= FDCAN_CCCR_CCE;
//Reset operation mode to Normal
CANx->CCCR &= ~(FDCAN_CCCR_TEST);
CANx->TEST &= ~(FDCAN_TEST_LBCK);
CANx->CCCR &= ~(FDCAN_CCCR_MON);
CANx->CCCR &= ~(FDCAN_CCCR_ASM);
// Set the nominal bit timing register
CANx->NBTP = ((CAN_SYNC_JW-1U)<<FDCAN_NBTP_NSJW_Pos) | ((CAN_PHASE_SEG1-1U)<<FDCAN_NBTP_NTSEG1_Pos) | ((CAN_PHASE_SEG2-1U)<<FDCAN_NBTP_NTSEG2_Pos) | ((can_speed_to_prescaler(speed)-1U)<<FDCAN_NBTP_NBRP_Pos);
// Set the data bit timing register
CANx->DBTP = ((CAN_SYNC_JW-1U)<<FDCAN_DBTP_DSJW_Pos) | ((CAN_PHASE_SEG1-1U)<<FDCAN_DBTP_DTSEG1_Pos) | ((CAN_PHASE_SEG2-1U)<<FDCAN_DBTP_DTSEG2_Pos) | ((can_speed_to_prescaler(data_speed)-1U)<<FDCAN_DBTP_DBRP_Pos);
// Silent loopback is known as internal loopback in the docs
if (loopback) {
CANx->CCCR |= FDCAN_CCCR_TEST;
CANx->TEST |= FDCAN_TEST_LBCK;
CANx->CCCR |= FDCAN_CCCR_MON;
}
// Silent is known as bus monitoring in the docs
if (silent) {
CANx->CCCR |= FDCAN_CCCR_MON;
}
ret = fdcan_exit_init(CANx);
if (!ret) {
puts(CAN_NAME_FROM_CANIF(CANx)); puts(" set_speed timed out! (2)\n");
}
} else {
puts(CAN_NAME_FROM_CANIF(CANx)); puts(" set_speed timed out! (1)\n");
}
return ret;
}
bool llcan_init(FDCAN_GlobalTypeDef *CANx) {
uint32_t can_number = CAN_NUM_FROM_CANIF(CANx);
bool ret = fdcan_request_init(CANx);
if (ret) {
// Enable config change
CANx->CCCR |= FDCAN_CCCR_CCE;
// Enable automatic retransmission
CANx->CCCR &= ~(FDCAN_CCCR_DAR);
// Enable transmission pause feature
CANx->CCCR |= FDCAN_CCCR_TXP;
// Disable protocol exception handling
CANx->CCCR |= FDCAN_CCCR_PXHD;
// FD with BRS
CANx->CCCR |= (FDCAN_CCCR_FDOE | FDCAN_CCCR_BRSE);
// Set TX mode to FIFO
CANx->TXBC &= ~(FDCAN_TXBC_TFQM);
// Configure TX element size (for now 8 bytes, no need to change)
//CANx->TXESC |= 0x000U;
//Configure RX FIFO0, FIFO1, RX buffer element sizes (no need for now, using classic 8 bytes)
register_set(&(CANx->RXESC), 0x0U, (FDCAN_RXESC_F0DS | FDCAN_RXESC_F1DS | FDCAN_RXESC_RBDS));
// Disable filtering, accept all valid frames received
CANx->XIDFC &= ~(FDCAN_XIDFC_LSE); // No extended filters
CANx->SIDFC &= ~(FDCAN_SIDFC_LSS); // No standard filters
CANx->GFC &= ~(FDCAN_GFC_RRFE); // Accept extended remote frames
CANx->GFC &= ~(FDCAN_GFC_RRFS); // Accept standard remote frames
CANx->GFC &= ~(FDCAN_GFC_ANFE); // Accept extended frames to FIFO 0
CANx->GFC &= ~(FDCAN_GFC_ANFS); // Accept standard frames to FIFO 0
uint32_t RxFIFO0SA = FDCAN_START_ADDRESS + (can_number * FDCAN_OFFSET);
uint32_t TxFIFOSA = RxFIFO0SA + (FDCAN_RX_FIFO_0_EL_CNT * FDCAN_RX_FIFO_0_EL_SIZE);
// RX FIFO 0
CANx->RXF0C = (FDCAN_RX_FIFO_0_OFFSET + (can_number * FDCAN_OFFSET_W)) << FDCAN_RXF0C_F0SA_Pos;
CANx->RXF0C |= FDCAN_RX_FIFO_0_EL_CNT << FDCAN_RXF0C_F0S_Pos;
// RX FIFO 0 switch to non-blocking (overwrite) mode
CANx->RXF0C |= FDCAN_RXF0C_F0OM;
// TX FIFO (mode set earlier)
CANx->TXBC = (FDCAN_TX_FIFO_OFFSET + (can_number * FDCAN_OFFSET_W)) << FDCAN_TXBC_TBSA_Pos;
CANx->TXBC |= FDCAN_TX_FIFO_EL_CNT << FDCAN_TXBC_TFQS_Pos;
// Flush allocated RAM
uint32_t EndAddress = TxFIFOSA + (FDCAN_TX_FIFO_EL_CNT * FDCAN_TX_FIFO_EL_SIZE);
for (uint32_t RAMcounter = RxFIFO0SA; RAMcounter < EndAddress; RAMcounter += 4U) {
*(uint32_t *)(RAMcounter) = 0x00000000;
}
// Enable both interrupts for each module
CANx->ILE = (FDCAN_ILE_EINT0 | FDCAN_ILE_EINT1);
CANx->IE &= 0x0U; // Reset all interrupts
// Messages for INT0
CANx->IE |= FDCAN_IE_RF0NE; // Rx FIFO 0 new message
// Messages for INT1 (Only TFE works??)
CANx->ILS |= FDCAN_ILS_TFEL;
CANx->IE |= FDCAN_IE_TFEE; // Tx FIFO empty
ret = fdcan_exit_init(CANx);
if(!ret) {
puts(CAN_NAME_FROM_CANIF(CANx)); puts(" llcan_init timed out (2)!\n");
}
if (CANx == FDCAN1) {
NVIC_EnableIRQ(FDCAN1_IT0_IRQn);
NVIC_EnableIRQ(FDCAN1_IT1_IRQn);
} else if (CANx == FDCAN2) {
NVIC_EnableIRQ(FDCAN2_IT0_IRQn);
NVIC_EnableIRQ(FDCAN2_IT1_IRQn);
} else if (CANx == FDCAN3) {
NVIC_EnableIRQ(FDCAN3_IT0_IRQn);
NVIC_EnableIRQ(FDCAN3_IT1_IRQn);
} else {
puts("Invalid CAN: initialization failed\n");
}
} else {
puts(CAN_NAME_FROM_CANIF(CANx)); puts(" llcan_init timed out (1)!\n");
}
return ret;
}
void llcan_clear_send(FDCAN_GlobalTypeDef *CANx) {
// From H7 datasheet: Transmit cancellation is not intended for Tx FIFO operation.
UNUSED(CANx);
}

View File

@@ -0,0 +1,33 @@
bool flash_is_locked(void) {
return (FLASH->CR1 & FLASH_CR_LOCK);
}
void flash_unlock(void) {
FLASH->KEYR1 = 0x45670123;
FLASH->KEYR1 = 0xCDEF89AB;
}
bool flash_erase_sector(uint8_t sector, bool unlocked) {
// don't erase the bootloader(sector 0)
if (sector != 0 && sector < 8 && unlocked) {
FLASH->CR1 = (sector << 8) | FLASH_CR_SER;
FLASH->CR1 |= FLASH_CR_START;
while (FLASH->SR1 & FLASH_SR_QW);
return true;
}
return false;
}
void flash_write_word(void *prog_ptr, uint32_t data) {
uint32_t *pp = prog_ptr;
FLASH->CR1 |= FLASH_CR_PG;
*pp = data;
while (FLASH->SR1 & FLASH_SR_QW);
}
void flush_write_buffer(void) {
if (FLASH->SR1 & FLASH_SR_WBNE) {
FLASH->CR1 |= FLASH_CR_FW;
while (FLASH->SR1 & FLASH_CR_FW);
}
}

View File

@@ -0,0 +1,9 @@
#define RCC_BDCR_MASK (RCC_BDCR_RTCEN | RCC_BDCR_RTCSEL | RCC_BDCR_LSEDRV | RCC_BDCR_LSEBYP | RCC_BDCR_LSEON)
void enable_bdomain_protection(void) {
register_clear_bits(&(PWR->CR1), PWR_CR1_DBP);
}
void disable_bdomain_protection(void) {
register_set_bits(&(PWR->CR1), PWR_CR1_DBP);
}

View File

@@ -0,0 +1,5 @@
void uart_init(uart_ring *q, int baud) { UNUSED(q); UNUSED(baud); }
void uart_set_baud(USART_TypeDef *u, unsigned int baud) { UNUSED(u); UNUSED(baud); }
void dma_pointer_handler(uart_ring *q, uint32_t dma_ndtr) { UNUSED(q); UNUSED(dma_ndtr); }
void uart_rx_ring(uart_ring *q) { UNUSED(q); }
void uart_tx_ring(uart_ring *q) { UNUSED(q); }

View File

@@ -0,0 +1,98 @@
typedef struct
{
__IO uint32_t HPRT;
}
USB_OTG_HostPortTypeDef;
USB_OTG_GlobalTypeDef *USBx = USB_OTG_HS;
#define USBx_HOST ((USB_OTG_HostTypeDef *)((uint32_t)USBx + USB_OTG_HOST_BASE))
#define USBx_HOST_PORT ((USB_OTG_HostPortTypeDef *)((uint32_t)USBx + USB_OTG_HOST_PORT_BASE))
#define USBx_DEVICE ((USB_OTG_DeviceTypeDef *)((uint32_t)USBx + USB_OTG_DEVICE_BASE))
#define USBx_INEP(i) ((USB_OTG_INEndpointTypeDef *)((uint32_t)USBx + USB_OTG_IN_ENDPOINT_BASE + ((i) * USB_OTG_EP_REG_SIZE)))
#define USBx_OUTEP(i) ((USB_OTG_OUTEndpointTypeDef *)((uint32_t)USBx + USB_OTG_OUT_ENDPOINT_BASE + ((i) * USB_OTG_EP_REG_SIZE)))
#define USBx_DFIFO(i) *(__IO uint32_t *)((uint32_t)USBx + USB_OTG_FIFO_BASE + ((i) * USB_OTG_FIFO_SIZE))
#define USBx_PCGCCTL *(__IO uint32_t *)((uint32_t)USBx + USB_OTG_PCGCCTL_BASE)
#define USBD_FS_TRDT_VALUE 6U
#define USB_OTG_SPEED_FULL 3U
#define DCFG_FRAME_INTERVAL_80 0U
void usb_irqhandler(void);
void OTG_HS_IRQ_Handler(void) {
NVIC_DisableIRQ(OTG_HS_IRQn);
usb_irqhandler();
NVIC_EnableIRQ(OTG_HS_IRQn);
}
void usb_init(void) {
REGISTER_INTERRUPT(OTG_HS_IRQn, OTG_HS_IRQ_Handler, 1500000U, FAULT_INTERRUPT_RATE_USB) // TODO: Find out a better rate limit for USB. Now it's the 1.5MB/s rate
// Disable global interrupt
USBx->GAHBCFG &= ~(USB_OTG_GAHBCFG_GINT);
// Select FS Embedded PHY
USBx->GUSBCFG |= USB_OTG_GUSBCFG_PHYSEL;
// Force device mode
USBx->GUSBCFG &= ~(USB_OTG_GUSBCFG_FHMOD | USB_OTG_GUSBCFG_FDMOD);
USBx->GUSBCFG |= USB_OTG_GUSBCFG_FDMOD;
delay(250000); // Wait for about 25ms (explicitly stated in H7 ref manual)
// Wait for AHB master IDLE state.
while ((USBx->GRSTCTL & USB_OTG_GRSTCTL_AHBIDL) == 0);
// Core Soft Reset
USBx->GRSTCTL |= USB_OTG_GRSTCTL_CSRST;
while ((USBx->GRSTCTL & USB_OTG_GRSTCTL_CSRST) == USB_OTG_GRSTCTL_CSRST);
// Activate the USB Transceiver
USBx->GCCFG |= USB_OTG_GCCFG_PWRDWN;
for (uint8_t i = 0U; i < 15U; i++) {
USBx->DIEPTXF[i] = 0U;
}
// VBUS Sensing setup
USBx_DEVICE->DCTL |= USB_OTG_DCTL_SDIS;
// Deactivate VBUS Sensing B
USBx->GCCFG &= ~(USB_OTG_GCCFG_VBDEN);
// B-peripheral session valid override enable
USBx->GOTGCTL |= USB_OTG_GOTGCTL_BVALOEN;
USBx->GOTGCTL |= USB_OTG_GOTGCTL_BVALOVAL;
// Restart the Phy Clock
USBx_PCGCCTL = 0U;
// Device mode configuration
USBx_DEVICE->DCFG |= DCFG_FRAME_INTERVAL_80;
USBx_DEVICE->DCFG |= USB_OTG_SPEED_FULL | USB_OTG_DCFG_NZLSOHSK;
// Flush FIFOs
USBx->GRSTCTL = (USB_OTG_GRSTCTL_TXFFLSH | (0x10U << 6));
while ((USBx->GRSTCTL & USB_OTG_GRSTCTL_TXFFLSH) == USB_OTG_GRSTCTL_TXFFLSH);
USBx->GRSTCTL = USB_OTG_GRSTCTL_RXFFLSH;
while ((USBx->GRSTCTL & USB_OTG_GRSTCTL_RXFFLSH) == USB_OTG_GRSTCTL_RXFFLSH);
// Clear all pending Device Interrupts
USBx_DEVICE->DIEPMSK = 0U;
USBx_DEVICE->DOEPMSK = 0U;
USBx_DEVICE->DAINTMSK = 0U;
USBx_DEVICE->DIEPMSK &= ~(USB_OTG_DIEPMSK_TXFURM);
// Disable all interrupts.
USBx->GINTMSK = 0U;
// Clear any pending interrupts
USBx->GINTSTS = 0xBFFFFFFFU;
// Enable interrupts matching to the Device mode ONLY
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 | USB_OTG_GINTMSK_EOPFM;
// Set USB Turnaround time
USBx->GUSBCFG |= ((USBD_FS_TRDT_VALUE << 10) & USB_OTG_GUSBCFG_TRDT);
// Enables the controller's Global Int in the AHB Config reg
USBx->GAHBCFG |= USB_OTG_GAHBCFG_GINT;
// Soft disconnect disable:
USBx_DEVICE->DCTL &= ~(USB_OTG_DCTL_SDIS);
// enable the IRQ
NVIC_EnableIRQ(OTG_HS_IRQn);
}

View File

@@ -0,0 +1,123 @@
void gpio_usb_init(void) {
// A11,A12: USB:
set_gpio_alternate(GPIOA, 11, GPIO_AF10_OTG1_FS);
set_gpio_alternate(GPIOA, 12, GPIO_AF10_OTG1_FS);
GPIOA->OSPEEDR = GPIO_OSPEEDR_OSPEED11 | GPIO_OSPEEDR_OSPEED12;
}
void gpio_usart2_init(void) {
// A2,A3: USART 2 for debugging
set_gpio_alternate(GPIOA, 2, GPIO_AF7_USART2);
set_gpio_alternate(GPIOA, 3, GPIO_AF7_USART2);
}
// Common GPIO initialization
void common_init_gpio(void) {
/// E2,E3,E4: RGB LED
set_gpio_pullup(GPIOE, 2, PULL_NONE);
set_gpio_mode(GPIOE, 2, MODE_OUTPUT);
set_gpio_pullup(GPIOE, 3, PULL_NONE);
set_gpio_mode(GPIOE, 3, MODE_OUTPUT);
set_gpio_pullup(GPIOE, 4, PULL_NONE);
set_gpio_mode(GPIOE, 4, MODE_OUTPUT);
// F7,F8,F9,F10: BOARD ID
set_gpio_pullup(GPIOF, 7, PULL_NONE);
set_gpio_mode(GPIOF, 7, MODE_INPUT);
set_gpio_pullup(GPIOF, 8, PULL_NONE);
set_gpio_mode(GPIOF, 8, MODE_INPUT);
set_gpio_pullup(GPIOF, 9, PULL_NONE);
set_gpio_mode(GPIOF, 9, MODE_INPUT);
set_gpio_pullup(GPIOF, 10, PULL_NONE);
set_gpio_mode(GPIOF, 10, MODE_INPUT);
// G11,B3,D7,B4: transceiver enable
set_gpio_pullup(GPIOG, 11, PULL_NONE);
set_gpio_mode(GPIOG, 11, MODE_OUTPUT);
// Speed was set to high by default after reset, changing to low
GPIOB->OSPEEDR = GPIO_OSPEEDR_OSPEED3;
set_gpio_pullup(GPIOB, 3, PULL_NONE);
set_gpio_mode(GPIOB, 3, MODE_OUTPUT);
set_gpio_pullup(GPIOD, 7, PULL_NONE);
set_gpio_mode(GPIOD, 7, MODE_OUTPUT);
set_gpio_pullup(GPIOB, 4, PULL_NONE);
set_gpio_mode(GPIOB, 4, MODE_OUTPUT);
// B14: usb load switch
set_gpio_pullup(GPIOB, 14, PULL_NONE);
set_gpio_mode(GPIOB, 14, MODE_OUTPUT);
//B1,F11 5VOUT_S, VOLT_S
set_gpio_pullup(GPIOB, 1, PULL_NONE);
set_gpio_mode(GPIOB, 1, MODE_ANALOG);
set_gpio_pullup(GPIOF, 11, PULL_NONE);
set_gpio_mode(GPIOF, 11, MODE_ANALOG);
gpio_usb_init();
// B8,B9: FDCAN1
set_gpio_pullup(GPIOB, 8, PULL_NONE);
set_gpio_alternate(GPIOB, 8, GPIO_AF9_FDCAN1);
set_gpio_pullup(GPIOB, 9, PULL_NONE);
set_gpio_alternate(GPIOB, 9, GPIO_AF9_FDCAN1);
// B5,B6 (mplex to B12,B13): FDCAN2
set_gpio_pullup(GPIOB, 12, PULL_NONE);
set_gpio_pullup(GPIOB, 13, PULL_NONE);
set_gpio_pullup(GPIOB, 5, PULL_NONE);
set_gpio_alternate(GPIOB, 5, GPIO_AF9_FDCAN2);
set_gpio_pullup(GPIOB, 6, PULL_NONE);
set_gpio_alternate(GPIOB, 6, GPIO_AF9_FDCAN2);
// G9,G10: FDCAN3
set_gpio_pullup(GPIOG, 9, PULL_NONE);
set_gpio_alternate(GPIOG, 9, GPIO_AF2_FDCAN3);
set_gpio_pullup(GPIOG, 10, PULL_NONE);
set_gpio_alternate(GPIOG, 10, GPIO_AF2_FDCAN3);
}
void flasher_peripherals_init(void) {
RCC->AHB1ENR |= RCC_AHB1ENR_USB1OTGHSEN;
}
// Peripheral initialization
void peripherals_init(void) {
// enable GPIO(A,B,C,D,E,F,G,H)
RCC->AHB4ENR |= RCC_AHB4ENR_GPIOAEN;
RCC->AHB4ENR |= RCC_AHB4ENR_GPIOBEN;
RCC->AHB4ENR |= RCC_AHB4ENR_GPIOCEN;
RCC->AHB4ENR |= RCC_AHB4ENR_GPIODEN;
RCC->AHB4ENR |= RCC_AHB4ENR_GPIOEEN;
RCC->AHB4ENR |= RCC_AHB4ENR_GPIOFEN;
RCC->AHB4ENR |= RCC_AHB4ENR_GPIOGEN;
RCC->APB1LENR |= RCC_APB1LENR_TIM2EN; // main counter
RCC->APB1LENR |= RCC_APB1LENR_TIM6EN; // interrupt timer
RCC->APB2ENR |= RCC_APB2ENR_TIM8EN; // clock source timer
RCC->APB1LENR |= RCC_APB1LENR_TIM12EN; // slow loop
RCC->APB1HENR |= RCC_APB1HENR_FDCANEN; // FDCAN core enable
RCC->AHB1ENR |= RCC_AHB1ENR_ADC12EN; // Enable ADC clocks
// HS USB enable, also LP is needed for CSleep state(__WFI())
RCC->AHB1ENR |= RCC_AHB1ENR_USB1OTGHSEN;
RCC->AHB1LPENR |= RCC_AHB1LPENR_USB1OTGHSLPEN;
RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_USB1OTGHSULPILPEN);
}
void enable_interrupt_timer(void) {
register_set_bits(&(RCC->APB1LENR), RCC_APB1LENR_TIM6EN); // Enable interrupt timer peripheral
}

Some files were not shown because too many files have changed in this diff Show More