Skip to content
C

feat: add explicit SimHub USB mode

YU CHIH CHANGef45276ec8af
diff --git a/.github/workflows/telemetry-tests.yml b/.github/workflows/telemetry-tests.yml
new file mode 100644
index 0000000..addc44b
--- /dev/null
+++ b/.github/workflows/telemetry-tests.yml
@@ -0,0 +1,16 @@
+name: Telemetry protocol tests
+on:
+ push:
+ paths: ['src/**', 'simhub/**', 'tests/**', '.github/workflows/telemetry-tests.yml']
+ pull_request:
+ paths: ['src/**', 'simhub/**', 'tests/**', '.github/workflows/telemetry-tests.yml']
+permissions:
+ contents: read
+jobs:
+ test:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v6
+ - run: node --test tests/simhub-formula.test.mjs
+ - run: g++ -std=c++11 -Wall -Wextra -pedantic -fsanitize=address,undefined tests/telemetry.cpp -o /tmp/telemetry-tests
+ - run: /tmp/telemetry-tests
diff --git a/README.md b/README.md
index 47919cf..1ee2465 100644
--- a/README.md
+++ b/README.md
@@ -5,8 +5,10 @@
> **Theme development:** See the [theme guide](docs/THEME_DEVELOPMENT.md) and [implementation plan](docs/THEME_SWITCH_PLAN.md) for architecture, workflow and hardware acceptance checks.
-A standalone **Gran Turismo 7 dashboard** running entirely on an ESP32.
-No SimHub • No PC • Auto PS5 Discovery
+An ESP32 dashboard with **direct GT7 Wi-Fi** and **SimHub USB** telemetry.
+GT7 needs no PC or SimHub; PC games use the bundled SimHub Custom Protocol.
+
+> **Source-tree feature:** Dual-source support requires a build of this source. The web installer continues to serve published releases. See [SimHub USB setup](SIMHUB_README.md).
<p align="center">
<img src="photos/001.jpg" width="900" alt="ESP32 GT7 Dashboard">
@@ -41,8 +43,8 @@ Simply connect your ESP32 to the same Wi-Fi network as your PS5 and enjoy real-t
- 🚗 Direct GT7 telemetry over Wi-Fi
- 📡 Automatic PS5 discovery
- 🔍 No IP address configuration required
-- ⚡ No SimHub required
-- 💻 No PC required after installation
+- 🔌 Optional SimHub USB for PC games, with [one formula for all themes](simhub/custom-protocol.txt)
+- ⚡ No SimHub or PC required for direct GT7 after installation
- 📶 Built-in Wi-Fi configuration portal
- 🏁 Current, Last and Best lap times
- ⏱ Live Delta
@@ -117,46 +119,24 @@ procedure in [docs/RELEASING.md](docs/RELEASING.md).
### First Time Setup
-When powered on for the first time (or after resetting Wi-Fi), the dashboard automatically starts Wi-Fi setup mode.
-
-1. Connect your phone or computer to the Wi-Fi network:
-
-```
-GT7-DASH-SETUP
-```
-
-2. A configuration page should open automatically.
-
-If it doesn't, open:
+On a fresh device, complete Touch Setup first, then choose **DIRECT GT7** or **SIMHUB USB**. The selected connection is saved for later boots.
-```
-http://192.168.4.1
-```
-
-3. Select your home Wi-Fi network.
-4. Enter the Wi-Fi password.
-5. Click **Save**.
-6. The dashboard will reboot automatically.
-7. Launch **Gran Turismo 7**.
-
-<p align="center">
- <img src="photos/002.jpg" width="900" alt="ESP32 GT7 Dashboard">
-</p>
+- **SimHub USB:** Wi-Fi stays off. Connect a data-capable USB cable to the PC and follow [SimHub setup](SIMHUB_README.md).
+- **Direct GT7:** if no network is saved, the firmware opens Wi-Fi Setup automatically. Join **GT7-DASH-SETUP** on a phone, open **http://192.168.4.1**, choose the network shared with the PS5 and save.
+The two connection paths are separate. Use **DEVICE SETTINGS → CHANGE CONNECTION** when moving between Direct GT7 and SimHub USB.
-The dashboard will automatically discover your PS5 on the local network.
+**RESET TO DEFAULT** clears Wi-Fi, connection, touch, theme and brightness settings, then returns to Touch Setup.
-No IP address configuration is required.
+All seven themes work with either source. Missing values show `--` or disable the relevant indicator; game-specific GT7 calculations are not applied to SimHub data.
### Touch Orientation Setup
-If the display looks correct but touch input is rotated, use **TOUCH SETUP** at the
-top of the waiting-for-telemetry screen:
+Touch Setup runs before connection selection on a fresh device or after Reset to Default:
-1. Tap **TOUCH SETUP** once; the prompt changes to **TOUCH AGAIN**.
-2. Tap the same physical area again within three seconds.
-3. Tap the target shown on the Touch Setup screen to verify the detected orientation.
-4. Select **SAVE** to store it, or **CANCEL** to keep the previous orientation.
+1. Tap the asymmetric target on the first screen so the firmware can detect orientation.
+2. Tap the verification target.
+3. Select **SAVE**, then choose Direct GT7 or SimHub USB.
An incomplete setup times out without saving, and incoming GT7 telemetry closes the
setup immediately so it never holds the dashboard open. If an incorrect orientation is
@@ -175,7 +155,7 @@ saved, repeat the same procedure from the waiting screen to replace it.
- Wake the display when it is asleep; the first tap does not also open Settings.
- Select and save the Classic, GT3, Retro, Radar, Mono, Pocket, or Endurance dashboard theme.
- Open **DEVICE SETTINGS** to adjust brightness from 20% to 100% in 10% steps.
-- Reset saved Wi-Fi from Device Settings through a separate confirmation screen.
+- Switch transport under **DEVICE SETTINGS → CHANGE CONNECTION**, or clear all setup with **RESET TO DEFAULT**.
Brightness defaults to 80%, is saved after adjustment, and is restored after reboot or wake. Automatic sleep still turns the backlight fully off.
@@ -269,7 +249,7 @@ This project would not have been possible without the following open-source proj
https://github.com/1achy/https---github.com-1achy-SIMHUB-ESP32---SUNTON-screen
This project originally started as a fork of the SIMHUB ESP32 SUNTON Screen project.
-It has since been substantially rewritten into a standalone GT7 dashboard with direct PS5 telemetry support and no longer depends on SimHub.
+It has since been substantially rewritten with direct PS5 telemetry and shared dashboard themes. GT7 remains standalone; SimHub USB is an optional second telemetry source.
### gt7-udp
diff --git a/README.zh-TW.md b/README.zh-TW.md
index 0ff5902..d4c5954 100644
--- a/README.zh-TW.md
+++ b/README.zh-TW.md
@@ -6,7 +6,9 @@
一個專為 **Gran Turismo 7** 打造、完全運行於 **ESP32** 的獨立儀表板。
-**不需要 SimHub • 不需要 PC • 自動搜尋 PS5**
+**GT7 直連不需要 SimHub 或 PC;PC 遊戲可使用 SimHub USB。**
+
+> **原始碼新功能:** 雙來源功能需編譯此份原始碼;網站安裝器仍提供已發布版本。請參閱 [SimHub USB 設定](SIMHUB_README.zh-TW.md)。
<p align="center">
<img src="photos/001.jpg" width="900" alt="ESP32 GT7 Dashboard">
@@ -42,7 +44,8 @@
- 🚗 透過 Wi-Fi 直接接收 GT7 遙測資料
- 📡 自動搜尋並連線 PS5
- 🔍 不需要手動設定 PS5 IP 位址
-- ⚡ 不需要 SimHub
+- 🔌 可選 SimHub USB,所有主題共用[一份公式](simhub/custom-protocol.txt)
+- ⚡ GT7 直連不需要 SimHub
- 💻 安裝完成後不需要電腦
- 📶 內建 Wi-Fi 設定頁面
- 🏁 目前圈速、上一圈、最佳圈
@@ -117,7 +120,18 @@
### 首次設定
-第一次開機(或重設 Wi-Fi 後),裝置會自動進入 Wi-Fi 設定模式。
+全新裝置會先進行觸控設定,再選擇 **DIRECT GT7** 或 **SIMHUB USB**;選擇會保存供後續開機使用。
+
+- **SimHub USB:** 用可傳資料的 USB 線連接 PC,依 [SimHub 設定說明](SIMHUB_README.zh-TW.md) 貼入公式,不必配網。
+- **DIRECT GT7:** 只啟用 Wi-Fi 與 GT7 UDP;沒有已存網路時會自動開啟 Wi-Fi Setup。
+- **SIMHUB USB:** 只啟用 USB Custom Protocol,Wi-Fi 保持關閉。
+- **GT7:** 沒有網路或已儲存網路連線失敗時提供配網,依下方步驟設定。
+
+兩條連線路徑彼此獨立。需要更換平台時,使用 **DEVICE SETTINGS → CHANGE CONNECTION**。
+
+七個主題共用兩種來源,缺值顯示 `--` 或停用對應提示。GT7 專用推算不會套用到 SimHub。
+
+GT7 Wi-Fi 設定步驟:
1. 使用手機或電腦連接下列 Wi-Fi:
@@ -136,7 +150,7 @@ http://192.168.4.1
3. 選擇家中的 Wi-Fi。
4. 輸入 Wi-Fi 密碼。
5. 點擊 **Save**。
-6. 裝置會自動重新啟動。
+6. 裝置背景連線成功後自動關閉首次設定畫面,不必重新啟動。
7. 開啟 **Gran Turismo 7**。
<p align="center">
@@ -168,7 +182,8 @@ http://192.168.4.1
- 螢幕休眠時只喚醒顯示,第一次點擊不會同時進入設定。
- 選擇並儲存 Classic、GT3、Retro、Radar、Mono、Pocket 或 Endurance 儀表主題。
- 進入 **DEVICE SETTINGS**,以 10% 級距調整 20%~100% 的亮度。
-- 從 Device Settings 透過獨立確認畫面重設已儲存的 Wi-Fi。
+- **CHANGE CONNECTION** 可切換 Direct GT7/SimHub USB,保留其他設定。
+- **RESET TO DEFAULT** 會清除 Wi-Fi、連線模式、觸控方向、主題與亮度,然後回到首次觸控設定。
亮度預設為 80%,調整後會儲存,重新開機或喚醒時會恢復;自動休眠仍會完全關閉背光。
diff --git a/SIMHUB_README.md b/SIMHUB_README.md
new file mode 100644
index 0000000..9a271d3
--- /dev/null
+++ b/SIMHUB_README.md
@@ -0,0 +1,58 @@
+# SimHub USB setup
+
+The dashboard supports **Direct GT7** over Wi-Fi and **SimHub USB** for PC games. SimHub USB does not require Wi-Fi. All dashboard themes use the same Custom Protocol formula.
+
+## 1. Prepare the dashboard
+
+1. Connect the dashboard to the PC with a data-capable USB cable.
+2. Select **SIMHUB USB** on the dashboard. If it is currently in GT7 mode, open **Settings → Device Settings → Change Connection → SIMHUB USB**.
+3. Close Arduino Serial Monitor, PlatformIO Serial Monitor, and any other application using the same COM port.
+
+## 2. Let SimHub detect the dashboard
+
+1. Open SimHub and go to **Arduino**.
+2. Open the **Multiple Arduino** or **Multiple USB** devices page. The label varies slightly between SimHub versions; use this page even when only one dashboard is connected.
+3. Enable Arduino support so SimHub scans the USB devices.
+4. Find the dashboard's COM port, then add or enable that device. Its firmware identification is `GT7 SimHub Dash`.
+5. Wait for SimHub to show the device as connected. Detecting the COM port only confirms the USB connection; telemetry requires the Custom Protocol in the next section.
+
+The initial connection uses 19200 baud and SimHub negotiates the later rate automatically. No virtual COM port, TCP bridge, or extra plugin is required.
+
+## 3. Add the Custom Protocol
+
+1. Open **Custom Protocol** or its formula editor for the Arduino device you just added.
+2. Enable **Use JavaScript**.
+3. Open [simhub/custom-protocol.txt](simhub/custom-protocol.txt), copy its **entire contents**, and paste them into the formula field.
+4. Select Apply or Save and verify that the protocol is enabled for the correct COM device.
+5. Do not append `\n`; SimHub adds the line ending automatically.
+
+This uses SimHub's **Arduino Custom Protocol**, not the Custom Serial Devices plugin. Do not use SimHub's generic Arduino sketch upload because it would overwrite the dashboard firmware.
+
+## 4. Start the game
+
+1. Start or select a supported PC game in SimHub.
+2. Confirm that SimHub is receiving game data.
+3. The dashboard changes from **Waiting for SimHub** to the selected theme.
+
+If SimHub detects the device but the dashboard remains on Waiting:
+
+- **USB linked: set Custom Protocol**: USB and SimHub are linked, but no valid formula data has arrived. Enable **Use JavaScript**, paste the complete formula, and select Apply or Save.
+- **Check Custom Protocol (DSH1)**: the formula has the wrong format or version. Paste [simhub/custom-protocol.txt](simhub/custom-protocol.txt) again.
+- **Waiting for SimHub** remains: verify the data cable, selected COM port, serial-port ownership, and that SimHub is receiving live game data.
+- Individual values show `--`: the current game may not expose those properties; other supported values still work.
+- Fuel never changes: paste the latest [simhub/custom-protocol.txt](simhub/custom-protocol.txt) again. The current formula prioritizes the active game's full FuelPercent property and falls back to Fuel divided by FuelCapacity.
+- A brief neutral value during a gear change is filtered for eight formula updates. A sustained or initial neutral still displays `N`.
+
+## Notes
+
+- All seven themes use the same formula. Changing themes does not require another SimHub setup.
+- The current connection choice is saved. Use **Change Connection** to switch between Direct GT7 and SimHub USB.
+- **Reset to Default** clears Wi-Fi and all dashboard preferences, then restarts first-time setup.
+- Historical formulas elsewhere in the repository use an older packet format. For this firmware, use only [simhub/custom-protocol.txt](simhub/custom-protocol.txt).
+
+## References
+
+- [Traditional Chinese guide](SIMHUB_README.zh-TW.md)
+- [SimHub Custom Arduino Hardware Support](https://github.com/SHWotever/SimHub/wiki/Custom-Arduino-hardware-support)
+- [SimHub JavaScript Formula Engine](https://github.com/SHWotever/SimHub/wiki/Javascript-Formula-Engine)
+- [Telemetry protocol and validation](docs/TELEMETRY_PROTOCOL.md)
diff --git a/SIMHUB_README.zh-TW.md b/SIMHUB_README.zh-TW.md
new file mode 100644
index 0000000..077f9be
--- /dev/null
+++ b/SIMHUB_README.zh-TW.md
@@ -0,0 +1,58 @@
+# SimHub USB 設定
+
+本儀表支援透過 Wi-Fi 直連 **GT7**,也支援 PC 遊戲使用 **SimHub USB**。SimHub USB 不需要 Wi-Fi,而且所有儀表主題共用同一份 Custom Protocol。
+
+## 1. 準備儀表
+
+1. 使用可傳輸資料的 USB 線把儀表接到電腦。
+2. 在儀表選擇 **SIMHUB USB**。若目前是 GT7 模式,開啟 **Settings → Device Settings → Change Connection → SIMHUB USB**。
+3. 關閉 Arduino Serial Monitor、PlatformIO Serial Monitor,以及其他可能占用相同 COM 埠的程式。
+
+## 2. 讓 SimHub 偵測儀表
+
+1. 開啟 SimHub,進入 **Arduino** 頁面。
+2. 打開 **Multiple Arduino**/**Multiple USB** 裝置頁面。不同 SimHub 版本的名稱可能略有差異;即使只有一台儀表,也使用多裝置頁面。
+3. 啟用 Arduino 功能,讓 SimHub 掃描 USB 裝置。
+4. 找到儀表所在的 COM 埠,並加入或啟用該裝置。韌體識別名稱為 `GT7 SimHub Dash`。
+5. 等待 SimHub 顯示裝置已連線。看到 COM 埠只代表 USB 已偵測到;還要完成下一段 Custom Protocol 設定才會有遙測資料。
+
+初始連線速度為 19200 baud,之後由 SimHub 自動協商,不需要手動建立虛擬 COM、TCP 連線或安裝額外外掛。
+
+## 3. 加入 Custom Protocol
+
+1. 在剛加入的 Arduino 裝置中,找到 **Custom Protocol** 設定或公式編輯器。
+2. 啟用 **Use JavaScript**。
+3. 開啟 [simhub/custom-protocol.txt](simhub/custom-protocol.txt),複製檔案的**全部內容**並貼入公式欄位。
+4. 按下 Apply/Save,並確認 Custom Protocol 已啟用在正確的 COM 裝置上。
+5. 不要自行在公式尾端加入 `\n`;SimHub 會自動送出換行。
+
+這是 SimHub 的 **Arduino Custom Protocol**,不是 Custom Serial Devices 外掛。請勿使用 SimHub 的一般 Arduino sketch upload,否則會覆蓋本儀表韌體。
+
+## 4. 開始遊戲
+
+1. 在 SimHub 中啟動或選取支援的 PC 遊戲。
+2. 確認 SimHub 已收到遊戲資料。
+3. 儀表會從 **Waiting for SimHub** 切換至所選主題。
+
+若 SimHub 已認出裝置,但儀表仍停在 Waiting:
+
+- **USB linked: set Custom Protocol**:USB 與 SimHub 已連線,但尚未收到有效公式資料。確認已啟用 **Use JavaScript**、貼入完整公式並按下 Apply/Save。
+- **Check Custom Protocol (DSH1)**:公式格式或版本不正確。重新貼入 [simhub/custom-protocol.txt](simhub/custom-protocol.txt)。
+- 一直顯示 **Waiting for SimHub**:確認使用資料線、選對 COM 埠、沒有其他程式占用序列埠,而且 SimHub 正在收到遊戲資料。
+- 個別欄位顯示 `--`:該遊戲可能沒有提供對應屬性;其他支援欄位仍可正常使用。
+- 油量一直不變:重新貼入最新版 [simhub/custom-protocol.txt](simhub/custom-protocol.txt)。目前公式會優先讀取遊戲的完整 FuelPercent 屬性,沒有時才用 Fuel 除以 FuelCapacity 計算。
+- 換檔瞬間出現的空檔值會過濾八筆;持續保持空檔或啟動時就在空檔,仍會正常顯示 `N`。
+
+## 注意事項
+
+- 七個主題共用同一份公式,切換主題後不需要重新設定 SimHub。
+- 儀表會保存目前的連線選擇。使用 **Change Connection** 可切換 Direct GT7 與 SimHub USB。
+- **Reset to Default** 會清除 Wi-Fi 與所有儀表設定,然後重新開始首次設定流程。
+- Repo 其他位置的歷史公式使用舊封包格式;本韌體只能使用 [simhub/custom-protocol.txt](simhub/custom-protocol.txt)。
+
+## 參考資料
+
+- [English guide](SIMHUB_README.md)
+- [SimHub Custom Arduino Hardware Support](https://github.com/SHWotever/SimHub/wiki/Custom-Arduino-hardware-support)
+- [SimHub JavaScript Formula Engine](https://github.com/SHWotever/SimHub/wiki/Javascript-Formula-Engine)
+- [Telemetry protocol and validation](docs/TELEMETRY_PROTOCOL.md)
diff --git a/docs/TELEMETRY_PROTOCOL.md b/docs/TELEMETRY_PROTOCOL.md
new file mode 100644
index 0000000..63b66c0
--- /dev/null
+++ b/docs/TELEMETRY_PROTOCOL.md
@@ -0,0 +1,75 @@
+# Telemetry sources and DSH1
+
+User-facing installation steps, including Multiple Arduino/Multiple USB device discovery and the Custom Protocol editor, are available in the [English](../SIMHUB_README.md) and [Traditional Chinese](../SIMHUB_README.zh-TW.md) SimHub USB guides.
+
+The firmware has two inputs: validated GT7 UDP and SimHub Arduino Custom Protocol over physical USB serial. Transport adapters retain separate snapshots. `TelemetrySelector` chooses one snapshot; every theme renders the same `DashboardState`. Renderer animation caches are preserved between updates and invalidated on source changes. GT7 derived metrics reset on source changes or a stale GT7 stream.
+
+## USB framing
+
+Keep the existing SimHub Arduino ARQ framing and command handshake. Command `P` begins a bounded, incremental line receiver. SimHub appends LF; CRLF is accepted. The custom-command `0x15` acknowledgement follows the complete line (or abort), not its first fragment. Max payload is 383 ASCII characters excluding LF; the line has exactly 25 semicolon-separated fields, with **no trailing semicolon**. Idle fragments time out after 300 ms, or 1500 ms total. Invalid/overflow/incomplete lines never update the snapshot or liveness. Unsupported versions are rejected, not guessed. The lower ARQ layer accepts at most 32 bytes per CRC-validated frame and never overwrites unread payload.
+
+| Index | Field | Unit / format |
+|---|---|---|
+| 0 | Version | literal `DSH1` |
+| 1 | Sequence | uint32, changes every formula evaluation |
+| 2 | Game running | required `0` / `1` |
+| 3 | Speed | 0–1500 km/h |
+| 4 | Gear | `N`, `R`, `1`–`9` |
+| 5 | Engine RPM | 0–30000 |
+| 6 | Displayed RPM | 0–100 % |
+| 7 | Redline | 0–100 %; 0 disables the alert |
+| 8–10 | Current / last / best lap | `mm:ss.fff`; up to 999 minutes |
+| 11 | Remaining fuel laps | 0–9999 laps |
+| 12 | Position | integer 0–9999 |
+| 13–14 | Current / total laps | integer 0–9999 |
+| 15 | Fuel | 0–100 % |
+| 16–17 | Throttle / brake | 0–100 % |
+| 18–20 | TC active / ABS active / invalid lap | `0` / `1` |
+| 21–24 | Tyre temperature FL / FR / RL / RR | −100–1000 °C |
+
+Every field from index 3 onward may be `--`. Empty strings, NaN, infinity, malformed numbers, unknown gear strings and out-of-range values are invalid. Optional fields may become available/unavailable each packet. Boolean strings are normalized by the sender to `0` / `1`. Sequence repetition is ignored for liveness; sequence changes (including wraparound and SimHub restart) are accepted. No ordering assumption across PC restarts.
+
+Example:
+
+```text
+DSH1;42;1;140;4;5600;68;90;01:24.631;01:25.104;01:24.382;4.5;5;3;10;80;68;36;0;1;0;82;79;76;78
+```
+
+## Connection selection and persistence
+
+- First setup runs touch orientation before presenting explicit **Direct GT7** and **SimHub USB** choices. The connection choice is persisted.
+- Direct GT7 enables Wi-Fi and GT7 UDP only. With no saved network it opens the setup portal; Wi-Fi cannot be skipped in this mode.
+- SimHub USB keeps the Wi-Fi radio off and accepts only valid DSH1 frames over physical USB serial.
+- Change Connection preserves other preferences. Reset to Default clears the connection, Wi-Fi credentials, touch orientation, theme and brightness, then returns to Touch Setup.
+- Handshake/USB presence alone never affects telemetry freshness. Continued idle frames maintain an existing lock; disconnect the idle sender to release it immediately.
+- Wi-Fi work runs on a separate FreeRTOS task because portal scans/saves can wait internally. Task-owned WiFiManager communicates with the main USB/render loop using bounded command/status queues. GT7 UDP is owned by the main loop.
+- Device Settings exposes Change Connection and Reset to Default. Reset does not require an MCU restart.
+
+## Validation
+
+Run formula tests with:
+
+```sh
+node --test tests/simhub-formula.test.mjs
+```
+
+Run the actual C++ parser and selector tests on a host with g++:
+
+```sh
+g++ -std=c++11 -Wall -Wextra -pedantic -fsanitize=address,undefined tests/telemetry.cpp -o telemetry-tests
+./telemetry-tests
+```
+
+The `Telemetry protocol tests` CI workflow runs both. Formula tests use mocked property values, not an installed SimHub session. C++ tests cover malformed/missing fields, range validation, idle sources, source contention, manual selection, expiry and timer wraparound. Build both panels with `pio run -e esp32 -e esp32-st7789`.
+
+### Hardware acceptance (still required before release)
+
+- Fresh NVS: verify Touch Setup precedes connection selection. Direct GT7 opens Wi-Fi Setup when needed; SimHub USB leaves Wi-Fi off.
+- Upgrade without a saved connection choice: preserve existing preferences and show connection selection.
+- Confirm SimHub discovery at 19200, baud negotiation, Custom Protocol evaluation, all 25 property mappings, and continuous stationary/paused frames.
+- Run GT7 only, USB only, both, wrong Wi-Fi credentials, no formula, invalid formula, unplug/reconnect, and SimHub restart.
+- While USB telemetry runs, scan/save/reset Wi-Fi; verify responsive rendering and no USB reconnect, protocol loss or mixed-source values.
+- Exercise both display controllers and every theme with valid/missing fuel, temperatures, RPM, pedals and aids; verify sleep/wake, preview, source change and memory stability.
+- Confirm settings are reachable while waiting, during play and after resetting Wi-Fi; verify portal cancellation and retries.
+
+This protocol is intentionally incompatible with the historical unversioned `custProtocol.txt` and upstream tyre-pressure mapping. Install the new formula together with the new firmware.
diff --git a/docs/THEME_DEVELOPMENT.md b/docs/THEME_DEVELOPMENT.md
index 6147a90..037f6bf 100644
--- a/docs/THEME_DEVELOPMENT.md
+++ b/docs/THEME_DEVELOPMENT.md
@@ -6,7 +6,7 @@ This guide explains how to add or maintain a dashboard theme without duplicating
The dashboard has three layers:
-1. GT7 parsing and derived metrics update the canonical `DashboardState`.
+1. GT7 and SimHub adapters retain independent snapshots; the source selector updates the canonical `DashboardState`. GT7 derived metrics remain specific to GT7.
2. `renderDashboard()` selects a renderer from the persisted `DashboardTheme` enum.
3. Each renderer reads the same state and controls presentation only.
@@ -45,6 +45,8 @@ Display brightness is stored separately in the same `gt7dash` Preferences namesp
- ABS and TCS state
- game-running state
+All themes support both telemetry sources. Optional SimHub text fields use `--`, missing tyre temperatures use `NAN`, and missing numeric engine RPM uses `-1`. Missing RPM percentage disables the bar/alerts; unsupported aid flags must not activate indicators. See [the protocol contract](TELEMETRY_PROTOCOL.md). Never render an unknown numeric value as a real zero.
+
If a new telemetry field is genuinely required by every theme, add it to the shared state and populate it in the parser/derived-data layer. Do not obtain it inside one renderer. A theme should not invent unsupported values merely to match a reference image.
## Adding a theme
diff --git a/lib/GT7Udp/src/GT7UDPParser.cpp b/lib/GT7Udp/src/GT7UDPParser.cpp
index 663f028..8b9f7a2 100644
--- a/lib/GT7Udp/src/GT7UDPParser.cpp
+++ b/lib/GT7Udp/src/GT7UDPParser.cpp
@@ -138,7 +138,7 @@ Packet GT7_UDP_Parser::readData() {
} else if (byteStream == PACKET_C_SIZE) {
detectedPacketVersion = 'C';
} else {
- detectedPacketVersion = ' ';
+ return packet;
}
int iv1 = *reinterpret_cast<int*>(&recvBuffer[0x40]); // Seed IV is always located there
@@ -170,6 +170,11 @@ Packet GT7_UDP_Parser::readData() {
std::array<uint8_t, sizeof(packet.packetContent)> decryptedData;
salsa20.processBytes((recvBuffer), decryptedData.data(), byteStream);
+ uint32_t magic = 0;
+ memcpy(&magic, decryptedData.data(), sizeof(magic));
+ if (magic != 0x47375330) return packet;
+ // Zero fields absent in shorter packet variants instead of retaining old data.
+ memset(&packet.packetContent, 0, sizeof(packet.packetContent));
memcpy(&packet.packetContent, decryptedData.data(), byteStream);
return packet;
}
diff --git a/lib/GT7Udp/src/GT7UDPParser.h b/lib/GT7Udp/src/GT7UDPParser.h
index 2fd92f8..25ff597 100644
--- a/lib/GT7Udp/src/GT7UDPParser.h
+++ b/lib/GT7Udp/src/GT7UDPParser.h
@@ -118,6 +118,7 @@ class GT7_UDP_Parser {
public:
void begin(const IPAddress playstationIP, const char packetVersion = 'A');
void sendHeartbeat();
+ void stop() { Udp.stop(); packet = {}; }
uint8_t getFlag(int index);
uint8_t getCurrentGearFromByte(void);
uint8_t getSuggestedGearFromByte(void);
@@ -128,7 +129,7 @@ class GT7_UDP_Parser {
private:
WiFiUDP Udp;
IPAddress remoteIP;
- Packet packet;
+ Packet packet = {};
int iv2;
char detectedPacketVersion;
char heartbeatMsg;
diff --git a/platformio.ini b/platformio.ini
index 6c1c125..f0cb3a7 100644
--- a/platformio.ini
+++ b/platformio.ini
@@ -86,6 +86,7 @@ lib_deps =
locoduino/RingBuffer@^1.0.4
https://github.com/paulo-raca/ArduinoBufferedStreams.git#5e3a1a3d140955384a07878c64808e77fa2a7521
tzapu/WiFiManager@^2.0.17
#lemmingdev/ESP32-BLE-Gamepad@^0.5.2 #liberia per bluettoth
#h2zero/NimBLE-Arduino@^1.4.0 #liberia nible usata per bluettoth
diff --git a/simhub/custom-protocol.txt b/simhub/custom-protocol.txt
new file mode 100644
index 0000000..e1a0516
--- /dev/null
+++ b/simhub/custom-protocol.txt
@@ -0,0 +1,89 @@
+// Paste into the Arduino Custom Protocol formula with "Use JavaScript" enabled.
+// One formula serves every dashboard theme. Do not append a newline yourself.
+// Revision: DSH1-20260927.2 (calculated fuel percent + shift neutral filter)
+function prop(name) {
+ try { return $prop(name); } catch (e) { return null; }
+}
+function first(names) {
+ for (var i = 0; i < names.length; i++) {
+ var v = prop(names[i]);
+ if (v !== null && v !== undefined && String(v) !== '') return v;
+ }
+ return null;
+}
+function numeric(v, min, max, digits) {
+ if (v === null || v === undefined || String(v) === '') return '--';
+ var n = Number(v);
+ return isFinite(n) && n >= min && n <= max ? n.toFixed(digits) : '--';
+}
+function flag(v) {
+ if (v === true || v === 1 || String(v).toLowerCase() === 'true' || v === '1') return '1';
+ if (v === false || v === 0 || String(v).toLowerCase() === 'false' || v === '0') return '0';
+ return '--';
+}
+function lap(v) {
+ if (v === null || v === undefined) return '--';
+ var m = /^(?:(\d+):)?(\d{1,2}):(\d{2})(?:\.(\d+))?$/.exec(String(v));
+ if (!m) return '--';
+ var minutes = Number(m[1] || 0) * 60 + Number(m[2]);
+ if (minutes > 999 || Number(m[3]) >= 60) return '--';
+ return (minutes < 10 ? '0' : '') + minutes + ':' + m[3] + '.' + ((m[4] || '') + '000').substring(0, 3);
+}
+function data(name) {
+ return first(['DataCorePlugin.GameData.NewData.' + name, 'DataCorePlugin.GameData.' + name, name]);
+}
+root.dashSequence = ((root.dashSequence || 0) + 1) % 4294967296;
+var gear = data('Gear');
+gear = gear === null ? '--' : String(gear).toUpperCase();
+if (gear === '-1') gear = 'R';
+if (gear === '0') gear = 'N';
+if (!/^(N|R|[1-9])$/.test(gear)) gear = '--';
+// Some games briefly report neutral between two gears. Keep the previous
+// valid gear through a normal shift, but still allow a sustained neutral.
+if (gear === 'N' && root.dashLastGear && root.dashLastGear !== 'N') {
+ root.dashNeutralFrames = (root.dashNeutralFrames || 0) + 1;
+ if (root.dashNeutralFrames <= 8) gear = root.dashLastGear;
+} else {
+ root.dashNeutralFrames = 0;
+}
+if (gear !== '--') root.dashLastGear = gear;
+var fuelRaw = data('Fuel');
+var fuel = Number(fuelRaw);
+var fuelCapacityRaw = first([
+ 'DataCorePlugin.GameData.NewData.FuelCapacity',
+ 'DataCorePlugin.GameData.FuelCapacity',
+ 'DataCorePlugin.GameData.NewData.MaxFuel',
+ 'DataCorePlugin.GameData.MaxFuel',
+ 'FuelCapacity', 'MaxFuel'
+]);
+var fuelCapacity = Number(fuelCapacityRaw);
+var fuelPercentRaw = data('FuelPercent');
+var calculatedFuelPercent = fuelRaw !== null && fuelCapacityRaw !== null &&
+ isFinite(fuel) && isFinite(fuelCapacity) && fuelCapacity > 0
+ ? fuel / fuelCapacity * 100 : null;
+// Some games expose a FuelPercent alias that stops updating. Prefer the
+// percentage calculated from live fuel litres and tank capacity when possible.
+var fuelPercent = calculatedFuelPercent !== null ? calculatedFuelPercent : fuelPercentRaw;
+var perLapRaw = prop('DataCorePlugin.Computed.Fuel_LitersPerLap');
+var perLap = Number(perLapRaw);
+var remaining = fuelRaw !== null && perLapRaw !== null && isFinite(fuel) && perLap > 0 ? fuel / perLap : null;
+var running = flag(prop('DataCorePlugin.GameRunning'));
+return [
+ 'DSH1', root.dashSequence, running === '1' ? '1' : '0',
+ numeric(data('SpeedKmh'), 0, 1500, 0), gear,
+ numeric(data('Rpms'), 0, 30000, 0),
+ numeric(prop('CarSettings_CurrentDisplayedRPMPercent'), 0, 100, 0),
+ numeric(prop('CarSettings_RPMRedLineSetting'), 0, 100, 0),
+ lap(data('CurrentLapTime')), lap(data('LastLapTime')), lap(data('BestLapTime')),
+ numeric(remaining, 0, 9999, 1),
+ numeric(data('Position'), 0, 9999, 0),
+ numeric(data('CurrentLap'), 0, 9999, 0),
+ numeric(data('TotalLaps'), 0, 9999, 0),
+ numeric(fuelPercent, 0, 100, 0),
+ numeric(data('Throttle'), 0, 100, 0), numeric(data('Brake'), 0, 100, 0),
+ flag(data('TCActive')), flag(data('ABSActive')), flag(data('LapInvalidated')),
+ numeric(data('TyreTemperatureFrontLeft'), -100, 1000, 1),
+ numeric(data('TyreTemperatureFrontRight'), -100, 1000, 1),
+ numeric(data('TyreTemperatureRearLeft'), -100, 1000, 1),
+ numeric(data('TyreTemperatureRearRight'), -100, 1000, 1)
+].join(';');
diff --git a/src/ArqSerial.h b/src/ArqSerial.h
index 0af2034..bc90986 100644
--- a/src/ArqSerial.h
+++ b/src/ArqSerial.h
@@ -22,7 +22,7 @@ class ARQSerial
{
private:
- byte partialdatabuffer[24];
+ byte partialdatabuffer[32];
int Arq_LastValidPacket = 255;
RingBuf<uint8_t, 32> DataBuffer;
IdleFunction idleFunction = 0;
@@ -32,114 +32,48 @@ private:
int testfailidx2 = 0;
#endif
- int Arq_TimedRead()
- {
- int c;
- unsigned long fsr_startMillis = millis();
- do {
- if (idleFunction != 0) idleFunction(true);
- c = StreamRead();
- if (c >= 0) {
-#ifdef TESTFAIL
- testfailidx = (testfailidx + 1) % 5000;
- if (testfailidx == 500)
- return random(255);
-
- if (testfailidx == 1000)
- return -1;
-#endif
- return c;
- }
- } while (millis() - fsr_startMillis < 100);
- return -1;
- }
-
- void ProcessIncomingData() {
- int packetID, length, header, res, i, crc, nextpacketid;
- byte currentCrc;
-
- while (StreamAvailable() > 0) {
- header = Arq_TimedRead();
- //DebugPrintLn("hello1");
- currentCrc = 0;
-
- if (header == 0x01) {
- byte failureReason = 0x00;
-
- header = Arq_TimedRead();
- if (header != 0x01) {
- return;
- }
-
- // read id of packet
- packetID = Arq_TimedRead(); // ?
- if (packetID < 0) {
- failureReason = 0x01; // bad id
- SendNAcq(Arq_LastValidPacket, failureReason);
- continue;
- }
-
- // read length of data
- length = Arq_TimedRead(); // 1
- if (length <= 0 || length > 32) {
- failureReason = 0x02; // bad length
- SendNAcq(Arq_LastValidPacket, failureReason);
- continue;
- }
-
- // read data
- for (i = 0; i < length && !failureReason; i++) {
- res = Arq_TimedRead(); // 3 49 16
- partialdatabuffer[i] = res;
- if (res < 0) {
- failureReason = 0x05; // bad data
- SendNAcq(Arq_LastValidPacket, failureReason);
- continue;
- }
- }
-
- // read checksum
- crc = Arq_TimedRead(); // 106
- if (crc < 0) {
- failureReason = 0x03; // bad data b/c no checksum
- SendNAcq(Arq_LastValidPacket, failureReason);
- continue;
- }
-
- // generate checksum for received data and check it with received checksum
- currentCrc = updateCrc(currentCrc, packetID);
- currentCrc = updateCrc(currentCrc, length);
- for (i = 0; i < length; i++) {
- currentCrc = updateCrc(currentCrc, partialdatabuffer[i]);
- }
-
- if (crc != currentCrc) {
- failureReason = 0x04; // bad data b/c checksum doesnt match
- SendNAcq(Arq_LastValidPacket, failureReason);
- continue;
- }
-
- // push valid data and set state for next packet
- nextpacketid = Arq_LastValidPacket > 127 ? 0 : Arq_LastValidPacket + 1;
- if (packetID == nextpacketid || packetID == 255) {
- for (i = 0; i < length; i++) {
- // save valid data to buffer
- DataBuffer.push(partialdatabuffer[i]);
- }
- // save valid packet id
- Arq_LastValidPacket = packetID;
- }
-#ifdef TESTFAIL
- testfailidx = (testfailidx + 1) % 5000;
- if (testfailidx != 788) {
- SendAcq(packetID);
- }
-#else
- SendAcq(packetID);
-#endif
- }
- }
- }
+ uint8_t rxStage = 0, rxId = 0, rxLength = 0, rxOffset = 0, rxCrc = 0;
+ uint32_t rxLastByte = 0;
+
+ void ProcessIncomingData() {
+ if (rxStage && uint32_t(millis() - rxLastByte) > 100) {
+ rxStage = 0;
+ SendNAcq(Arq_LastValidPacket, 0x05);
+ }
+ // Decode one ARQ frame at a time. Never overwrite unconsumed payload.
+ if (DataBuffer.size() != 0) return;
+ while (StreamAvailable() > 0) {
+ const int value = StreamRead();
+ if (value < 0) return;
+ const uint8_t c = static_cast<uint8_t>(value);
+ rxLastByte = millis();
+ if (rxStage == 0) { if (c == 1) rxStage = 1; }
+ else if (rxStage == 1) { rxStage = c == 1 ? 2 : 0; }
+ else if (rxStage == 2) {
+ rxId = c; rxCrc = updateCrc(0, c); rxStage = 3;
+ } else if (rxStage == 3) {
+ if (c == 0 || c > sizeof(partialdatabuffer)) {
+ rxStage = 0; SendNAcq(Arq_LastValidPacket, 0x02); continue;
+ }
+ rxLength = c; rxOffset = 0;
+ rxCrc = updateCrc(rxCrc, c); rxStage = 4;
+ } else if (rxStage == 4) {
+ partialdatabuffer[rxOffset++] = c;
+ rxCrc = updateCrc(rxCrc, c);
+ if (rxOffset == rxLength) rxStage = 5;
+ } else {
+ rxStage = 0;
+ if (c != rxCrc) { SendNAcq(Arq_LastValidPacket, 0x04); continue; }
+ const int nextId = Arq_LastValidPacket > 127 ? 0 : Arq_LastValidPacket + 1;
+ if (rxId == nextId || rxId == 255) {
+ for (unsigned i = 0; i < rxLength; ++i) DataBuffer.push(partialdatabuffer[i]);
+ Arq_LastValidPacket = rxId;
+ }
+ SendAcq(rxId);
+ return;
+ }
+ }
+ }
void SendAcq(uint8_t packetId)
{
diff --git a/src/DashboardNetwork.h b/src/DashboardNetwork.h
new file mode 100644
index 0000000..8b863f7
--- /dev/null
+++ b/src/DashboardNetwork.h
@@ -0,0 +1,115 @@
+#pragma once
+#include <WiFi.h>
+#include <WiFiManager.h>
+#include <freertos/FreeRTOS.h>
+#include <freertos/task.h>
+#include <freertos/queue.h>
+#include "TelemetrySource.h"
+#include "DashboardWiFiCredentials.h"
+
+// WiFiManager can wait during HTTP scans and credential saves even in its
+// nonblocking portal mode. Keep that work off the USB/render loop. Only this
+// task owns WiFiManager; commands/status cross queues, never shared Strings.
+class DashboardNetwork {
+public:
+ enum class Action : uint8_t { Configure, Reset, StartPortal, StopPortal };
+ struct Command { Action action; TelemetryMode mode; bool firstRun; };
+ struct Status { bool connected; bool portal; bool configured; char message[64]; };
+ bool begin() {
+ commands = xQueueCreate(8, sizeof(Command));
+ statuses = xQueueCreate(1, sizeof(Status));
+ if (commands && statuses &&
+ xTaskCreatePinnedToCore(taskEntry, "dash-wifi", 6144, this, 1, nullptr, 0) == pdPASS) return true;
+ if (commands) vQueueDelete(commands);
+ if (statuses) vQueueDelete(statuses);
+ commands = statuses = nullptr;
+ return false;
+ }
+ bool send(Action action, TelemetryMode mode, bool firstRun = false) {
+ Command command{action, mode, firstRun};
+ return commands && xQueueSend(commands, &command, 0) == pdTRUE;
+ }
+ bool receive(Status &status) { return statuses && xQueueReceive(statuses, &status, 0) == pdTRUE; }
+private:
+ QueueHandle_t commands = nullptr, statuses = nullptr;
+ static void taskEntry(void *self) { static_cast<DashboardNetwork *>(self)->run(); }
+ void run() {
+ WiFiManager manager;
+ manager.setDebugOutput(false);
+ manager.setConfigPortalBlocking(false);
+ manager.setConnectTimeout(2);
+ manager.setSaveConnectTimeout(2);
+ manager.setConfigPortalTimeout(180);
+ manager.setBreakAfterConfig(true);
+ manager.setClass("invert");
+ manager.setTitle("GT7 DASH SETUP");
+ std::vector<const char *> menu = {"wifi", "info", "exit"};
+ manager.setMenu(menu);
+ TelemetryMode mode = TelemetryMode::SimHub;
+ bool enabled = false, offerSetup = false;
+ uint32_t attemptTime = 0;
+ const auto stopPortal = [&]() {
+ if (manager.getConfigPortalActive()) manager.stopConfigPortal();
+ if (WiFi.getMode() != WIFI_OFF) WiFi.softAPdisconnect(true);
+ };
+ const auto startPortal = [&]() {
+ if (enabled && !manager.getConfigPortalActive()) manager.startConfigPortal("GT7-DASH-SETUP");
+ };
+ for (;;) {
+ Command command;
+ while (xQueueReceive(commands, &command, 0) == pdTRUE) {
+ if (command.action == Action::Configure) {
+ stopPortal();
+ mode = command.mode;
+ enabled = mode == TelemetryMode::GT7;
+ offerSetup = enabled && command.firstRun;
+ if (!enabled) WiFi.mode(WIFI_OFF);
+ else {
+ WiFi.mode(WIFI_STA); WiFi.setAutoReconnect(true);
+ attemptTime = millis();
+ if (dashboardHasSavedWifi()) WiFi.begin();
+ else if (offerSetup) { startPortal(); offerSetup = false; }
+ }
+ } else if (command.action == Action::Reset) {
+ stopPortal(); WiFi.persistent(true); WiFi.mode(WIFI_STA);
+ esp_wifi_set_storage(WIFI_STORAGE_FLASH);
+ WiFi.setAutoReconnect(false); WiFi.disconnect(true, true);
+ offerSetup = false;
+ enabled = false;
+ WiFi.mode(WIFI_OFF);
+ } else if (command.action == Action::StartPortal) {
+ // Wi-Fi setup is independent from the telemetry mode. A
+ // SimHub-only user may configure credentials now and
+ // switch to Auto/GT7 later.
+ enabled = true;
+ WiFi.mode(WIFI_STA);
+ WiFi.setAutoReconnect(true);
+ startPortal(); offerSetup = false;
+ } else {
+ stopPortal(); offerSetup = false;
+ if (!dashboardHasSavedWifi()) { enabled = false; WiFi.mode(WIFI_OFF); }
+ }
+ }
+ if (manager.getConfigPortalActive()) manager.process();
+ const bool connected = enabled && WiFi.status() == WL_CONNECTED;
+ if (connected) offerSetup = false;
+ if (offerSetup && !connected && uint32_t(millis() - attemptTime) > 8000) {
+ startPortal(); offerSetup = false;
+ }
+ if (enabled && !connected && !manager.getConfigPortalActive() &&
+ uint32_t(millis() - attemptTime) > 15000 && dashboardHasSavedWifi()) {
+ attemptTime = millis(); WiFi.begin();
+ }
+ Status status{};
+ status.connected = connected;
+ status.portal = manager.getConfigPortalActive();
+ status.configured = dashboardHasSavedWifi();
+ String message = !enabled ? "Wi-Fi not used" : status.portal ? "Wi-Fi setup is open" :
+ connected ? WiFi.localIP().toString() : dashboardHasSavedWifi() ?
+ "Wi-Fi disconnected / retrying" : "GT7 Wi-Fi not configured";
+ message.toCharArray(status.message, sizeof(status.message));
+ xQueueOverwrite(statuses, &status);
+ vTaskDelay(pdMS_TO_TICKS(20));
+ }
+ }
+};
diff --git a/src/DashboardWiFiCredentials.h b/src/DashboardWiFiCredentials.h
new file mode 100644
index 0000000..b7c89af
--- /dev/null
+++ b/src/DashboardWiFiCredentials.h
@@ -0,0 +1,9 @@
+#pragma once
+#include <esp_wifi.h>
+
+// WiFi.SSID() reports the currently associated AP, not saved credentials.
+// Call only after the STA driver has been initialized.
+inline bool dashboardHasSavedWifi() {
+ wifi_config_t config{};
+ return esp_wifi_get_config(WIFI_IF_STA, &config) == ESP_OK && config.sta.ssid[0] != 0;
+}
diff --git a/src/SHCommands.h b/src/SHCommands.h
index c0f70ea..687222c 100644
--- a/src/SHCommands.h
+++ b/src/SHCommands.h
@@ -421,6 +421,5 @@ void Command_I2CLCDData() {
}
void Command_CustomProtocolData() {
- shCustomProtocol.read();
- FlowSerialWrite(0x15);
+ shCustomProtocol.read(); // ACK follows the complete custom line, asynchronously.
}
diff --git a/src/SHCustomProtocol.h b/src/SHCustomProtocol.h
index b721f2e..4c64365 100644
--- a/src/SHCustomProtocol.h
+++ b/src/SHCustomProtocol.h
@@ -1,3 +1,7 @@
+#include "TelemetrySource.h"
+#include "SimHubProtocol.h"
+#include "DashboardWiFiCredentials.h"
+#include <qrcode.h>
#ifndef __SHCUSTOMPROTOCOL_H__
#define __SHCUSTOMPROTOCOL_H__
@@ -17,7 +21,6 @@
static LGFX tft;
-static const int RESET_WAITING_TIME = 3;
static const int SCREEN_WIDTH = 320;
static const int SCREEN_HEIGHT = 240;
static const int X_CENTER = SCREEN_WIDTH / 2;
@@ -124,7 +127,6 @@ namespace DashboardLayout
#ifndef GT7_DASHBOARD_LEGACY_UI
#define GT7_DASHBOARD_LEGACY_UI 0
#endif
-
// Stable persisted values. Never reorder or reuse an existing numeric value.
enum class DashboardTheme : uint8_t
{
@@ -232,48 +234,28 @@ static void showWifiConnectionFailedScreen()
tft.drawString("Setup portal will restart", 160, 205);
}
-static void showWifiSetupScreen()
-{
- tft.fillScreen(TFT_BLACK);
-
- tft.setTextDatum(MC_DATUM);
-
- tft.setTextColor(TFT_CYAN, TFT_BLACK);
- tft.setTextSize(2);
- tft.drawString("WI-FI SETUP", 160, 35);
-
- tft.setTextColor(TFT_WHITE, TFT_BLACK);
- tft.setTextSize(1.5);
- tft.drawString("Connect phone to:", 160, 85);
-
- tft.setTextColor(TFT_YELLOW, TFT_BLACK);
- tft.setTextSize(2);
- tft.drawString("GT7-DASH-SETUP", 160, 120);
-
- tft.setTextColor(TFT_WHITE, TFT_BLACK);
- tft.setTextSize(1.5);
- tft.drawString("Open:", 160, 160);
-
- tft.setTextColor(TFT_GREEN, TFT_BLACK);
- tft.setTextSize(2);
- tft.drawString("192.168.4.1", 160, 195);
-
- tft.setTextColor(TFT_WHITE, TFT_BLACK);
- tft.setTextSize(1);
- tft.drawCentreString(
- String("v") + GT7_DASH_VERSION,
- SCREEN_WIDTH / 2,
- SCREEN_HEIGHT - 12,
- 1);
-}
-
int currentPage = 1; // Variabile per tenere traccia della pagina corrente
bool forceUpdate = false; // Variabile per forzare l'aggiornamento delle celle
class SHCustomProtocol : private DashboardState
{
private:
- Preferences dashboardPreferences;
+ TelemetrySelector telemetry;
+ DashboardState gt7State, simhubState;
+ bool gt7Dirty = false, simhubDirty = false;
+ bool firstRun = false, networkChanged = true, gt7TransportReady = false;
+ bool wifiConfigured = false;
+ bool wifiStopRequested = false, wifiPortalActive = false;
+ bool touchSetupRequired = false;
+ bool connectionChoiceCanCancel = false;
+ String networkStatus = "Wi-Fi not configured";
+ bool receivingCustom = false, customOverflow = false, customProtocolError = false;
+ char customLine[SimHubProtocol::maxLength] = {};
+ unsigned customLength = 0;
+ uint32_t customStarted = 0, customLastByte = 0, lastSimHubSequence = 0;
+ bool haveSimHubSequence = false, usbSeen = false;
+ uint32_t lastUsbCommandTime = 0, settingsStatusRefresh = 0;
+ Preferences dashboardPreferences;
DashboardTheme activeDashboardTheme = DashboardTheme::GT3;
DashboardTheme renderedDashboardTheme = DashboardTheme::GT3;
DashboardTheme previewDashboardTheme = DashboardTheme::GT3;
@@ -296,9 +278,6 @@ private:
TouchRotation touchRotation = TouchRotation::Deg0;
TouchRotation pendingTouchRotation = TouchRotation::Deg0;
bool touchCalibrationVerified = false;
- bool touchCalibrationEntryArmed = false;
- bool touchCalibrationAwaitingSecondTap = false;
- unsigned long touchCalibrationFirstTapTime = 0;
uint16_t originalTouchX = 0;
uint16_t originalTouchY = 0;
@@ -312,7 +291,7 @@ private:
static constexpr unsigned long BRIGHTNESS_SAVE_DELAY_MS = 750UL;
static constexpr bool TOUCH_SCREEN_CONTROL_ENABLED = true;
- // Connecting 畫面動畫設定
+ // Connecting ?恍?閮剖?
static constexpr unsigned long CONNECT_ANIMATION_INTERVAL = 1000;
static constexpr int CONNECT_DOT_COUNT = 5;
@@ -325,7 +304,7 @@ private:
bool gameStoppedTimerStarted = false;
bool screenSleeping = false;
- // 是否由使用者手動關閉
+ // ?臬?曹蝙?刻€?????
bool screenOffByUser = false;
// Tap the active dashboard to open the touch-driven Settings menu.
@@ -335,23 +314,24 @@ private:
Main,
ThemeSelection,
DeviceSettings,
- WifiResetConfirmation,
+ InitialTouch,
+ ConnectionChoice,
+ WifiSettings,
+ ResetConfirmation,
TouchCalibration,
};
static constexpr unsigned long SETTINGS_TIMEOUT_MS = 15000UL;
- static constexpr unsigned long TOUCH_CALIBRATION_DOUBLE_TAP_MS = 3000UL;
SettingsScreen settingsScreen = SettingsScreen::Closed;
unsigned long settingsLastInteractionTime = 0;
int settingsPressedButton = -1;
bool wifiResetConfirmOpen = false;
bool wifiResetRequested = false;
- // 記錄上一筆 GT7 執行狀態,用來偵測 False -> True
+ // 閮?銝?蝑?GT7 ?瑁??€???其??菜葫 False -> True
bool previousGameRunning = false;
- // 避免第一筆資料被誤判為狀態切換
- bool gameRunningInitialized = false;
+ // ?踹?蝚砌?蝑??◤隤文?箇?????
static bool isValidDashboardTheme(uint8_t value)
{
@@ -415,12 +395,10 @@ private:
}
}
- int calibrationRotationForTouch(uint16_t rawX, uint16_t rawY) const
+ int calibrationRotationForTouch(uint16_t rawX, uint16_t rawY,
+ int targetX = SCREEN_WIDTH / 2, int targetY = 18,
+ int hitHalfWidth = 48, int hitHalfHeight = 18) const
{
- constexpr int targetX = SCREEN_WIDTH / 2;
- constexpr int targetY = 18;
- constexpr int hitHalfWidth = 48;
- constexpr int hitHeight = 26;
int closestRotation = -1;
uint32_t closestDistance = UINT32_MAX;
for (uint8_t value = 0; value < 4; ++value)
@@ -430,7 +408,7 @@ private:
applyTouchRotation(rawX, rawY,
static_cast<TouchRotation>(value), candidateX, candidateY);
if (abs(static_cast<int>(candidateX) - targetX) > hitHalfWidth ||
- candidateY > hitHeight)
+ abs(static_cast<int>(candidateY) - targetY) > hitHalfHeight)
continue;
const int dx = static_cast<int>(candidateX) - targetX;
const int dy = static_cast<int>(candidateY) - targetY;
@@ -530,6 +508,7 @@ private:
uint8_t storedTheme = static_cast<uint8_t>(DashboardTheme::GT3);
if (dashboardPreferencesReady)
{
+ touchSetupRequired = !dashboardPreferences.isKey("touchRot");
storedTheme = dashboardPreferences.getUChar(
"theme", static_cast<uint8_t>(DashboardTheme::GT3));
const uint8_t storedBrightness = dashboardPreferences.getUChar(
@@ -544,6 +523,10 @@ private:
? static_cast<TouchRotation>(storedTouchRotation)
: TouchRotation::Deg0;
}
+ else
+ {
+ touchSetupRequired = true;
+ }
pendingTouchRotation = touchRotation;
activeDashboardTheme = isValidDashboardTheme(storedTheme)
@@ -560,13 +543,13 @@ private:
}
#if INCLUDE_GT7_WIFI
- // 最近一次真正收到新 GT7 UDP 封包的時間
+ // ?€餈?甈∠?甇??唳 GT7 UDP 撠?????
uint32_t lastGT7PacketTime = 0;
int32_t lastGT7PacketId = -1;
bool hasReceivedGT7Packet = false;
bool gt7CarOnTrack = false;
- // GT7 衍生數據:ABS 與剩餘油量圈數。
+ // GT7 銵??豢?嚗BS ?擗硃???詻€?
GT7DerivedMetrics derivedMetrics;
#endif
@@ -575,7 +558,7 @@ private:
{
previousBestLapMs = -1;
lastProcessedLapMs = -1;
- sessionBestLiveDeltaSeconds = "+0.000";
+ gt7LapDifference = "+0.000";
}
String formatLapTimeMs(int32_t milliseconds)
@@ -661,7 +644,7 @@ private:
return minutes * 60000L + seconds * 1000L + millisText.toInt();
}
- // Connecting 畫面狀態
+ // Connecting ?恍?€??
bool connectingScreenActive = false;
// int connectingDotIndex = 0;
int connectingAnimationStep = 0;
@@ -724,42 +707,46 @@ public:
}
#if INCLUDE_GT7_WIFI
- bool readGT7Wifi()
+ bool readGT7Wifi(DashboardState &state)
{
gt7Packet = gt7Telem.readData();
+ // A stopped/reopened socket has no sample until a validated packet arrives.
+ if (gt7Packet.packetContent.magic != 0x47375330) return false;
+
const int32_t packetId =
gt7Packet.packetContent.packetId;
/*
- * readData() 沒收到新資料時會保留上一筆 Packet。
- * 因此用 packetId 是否改變,判斷這一圈是否真的收到新封包。
+ * readData() 瘝?唳鞈???靽?銝?蝑?Packet??
+ * ?迨??packetId ?臬?寡?嚗?琿€???衣???唳撠???
*/
if (hasReceivedGT7Packet && packetId == lastGT7PacketId)
{
return false;
}
- // 尚未收到任何有效資料時,忽略初始化的空 Packet。
+ // 撠?嗅隞颱???鞈???敹賜????蝛?Packet??
if (!hasReceivedGT7Packet && packetId == 0 &&
gt7Packet.packetContent.magic == 0)
{
return false;
}
+ if (!telemetry.gt7.alive(millis())) { derivedMetrics.reset(); resetLapDifference(); }
hasReceivedGT7Packet = true;
lastGT7PacketId = packetId;
lastGT7PacketTime = millis();
const auto &data = gt7Packet.packetContent;
- // 速度與檔位
- speed = String(static_cast<int>(data.speed * 3.6f));
+ // ?漲??雿?
+ state.speed = String(static_cast<int>(data.speed * 3.6f));
const int currentGear =
gt7Telem.getCurrentGearFromByte();
- gear = currentGear == 0
+ state.gear = currentGear == 0
? "N"
: String(currentGear);
@@ -767,7 +754,7 @@ public:
const float rpm = data.EngineRPM;
const float maxRpm = data.maxAlertRPM;
const float redLineRpm = data.minAlertRPM;
- engineRpm = max(0, static_cast<int>(lroundf(rpm)));
+ state.engineRpm = max(0, static_cast<int>(lroundf(rpm)));
static constexpr float FALLBACK_MAX_RPM = 10000.0f;
static constexpr float MIN_REASONABLE_MAX_RPM = 1000.0f;
static constexpr float MAX_REASONABLE_MAX_RPM = 25000.0f;
@@ -775,59 +762,59 @@ public:
maxRpm <= MAX_REASONABLE_MAX_RPM;
const float effectiveMaxRpm = maxRpmValid ? maxRpm : FALLBACK_MAX_RPM;
- rpmAlertRangeValid = maxRpmValid && redLineRpm > 0.0f &&
+ state.rpmAlertRangeValid = maxRpmValid && redLineRpm > 0.0f &&
redLineRpm < maxRpm;
- rpmPercent = constrain(
+ state.rpmPercent = constrain(
static_cast<int>((rpm / effectiveMaxRpm) * 100.0f),
0,
100);
- rpmRedLineSetting = rpmAlertRangeValid
+ state.rpmRedLineSetting = state.rpmAlertRangeValid
? constrain(
static_cast<int>((redLineRpm / maxRpm) * 100.0f),
1,
99)
: 90;
- // 圈速:currentLap 只有使用 C Packet 時才有值
- currentLapTime = formatLapTimeMs(data.currentLap);
- lastLapTime = formatLapTimeMs(data.lastLaptime);
- bestLapTime = formatLapTimeMs(data.bestLaptime);
+ // ?€?currentLap ?芣?雿輻 C Packet ???€?
+ state.currentLapTime = formatLapTimeMs(data.currentLap);
+ state.lastLapTime = formatLapTimeMs(data.lastLaptime);
+ state.bestLapTime = formatLapTimeMs(data.bestLaptime);
- // 圈數
+ // ?
const int currentLap = max(0, static_cast<int>(data.lapCount));
const int totalLapCount = max(0, static_cast<int>(data.totalLaps));
- // 上一圈與最佳圈的圈速差。新最佳圈會顯示 +0.000。
- sessionBestLiveDeltaSeconds =
+ // 銝????€雿喳????榆??€雿喳??*蝷?+0.000??
+ state.sessionBestLiveDeltaSeconds =
updateLastBestDifference(
data.lastLaptime,
data.bestLaptime);
- // 此欄位不再顯示 Delta P,畫面改為油門/煞車圖條。
- sessionBestLiveDeltaProgressSeconds = "";
+ // 甇斗?雿??*蝷?Delta P嚗?X?箸硃?€嚗?頠?璇€?
+ state.sessionBestLiveDeltaProgressSeconds = "";
if (totalLapCount > 0)
{
- tyrePressureRearLeft = String(currentLap) + "/" + String(totalLapCount);
+ state.tyrePressureRearLeft = String(currentLap) + "/" + String(totalLapCount);
}
else
{
- tyrePressureRearLeft = String(currentLap);
+ state.tyrePressureRearLeft = String(currentLap);
}
- // 目前封包只有賽前起跑位置,沒有比賽中的即時排名
+ // ?桀?撠??芣?鞈賢?韏瑁?雿蔭嚗???鞈賭葉?????
if (data.RaceStartPosition > 0)
{
- tyrePressureFrontRight = String(data.RaceStartPosition);
+ state.tyrePressureFrontRight = String(data.RaceStartPosition);
}
else
{
- tyrePressureFrontRight = "--";
+ state.tyrePressureFrontRight = "--";
}
- // 油量百分比
+ // 瘝寥??曉?瘥?
// Normalize ICE and EV energy into separate display and progress values.
// For EVs, fuelLevel is treated as remaining kWh. The fixed 60 kWh
// reference is only a visual scale because GT7 does not expose capacity.
@@ -850,23 +837,23 @@ public:
const bool nextFuelValueValid = validEvFuel || validIceFuel;
const String nextFuelLabel = detectedEV ? "EV" : "FUEL";
- if (fuelIsEV != detectedEV || fuelValueValid != nextFuelValueValid)
+ if (state.fuelIsEV != detectedEV || state.fuelValueValid != nextFuelValueValid)
{
derivedMetrics.fuel.reset();
- if (fuelLabel != nextFuelLabel)
+ if (state.fuelLabel != nextFuelLabel)
forceUpdate = true;
}
- fuelIsEV = detectedEV;
- fuelValueValid = nextFuelValueValid;
- fuelLabel = nextFuelLabel;
+ state.fuelIsEV = detectedEV;
+ state.fuelValueValid = nextFuelValueValid;
+ state.fuelLabel = nextFuelLabel;
if (validEvFuel)
{
// GT7 updates EV energy in coarse steps. A whole-number display keeps
// every theme compact and avoids implying unavailable precision.
- fuelDisplayValue = String(data.fuelLevel, 0);
- fuelProgressPercent = constrain(
+ state.fuelDisplayValue = String(data.fuelLevel, 0);
+ state.fuelProgressPercent = constrain(
static_cast<int>(lroundf(
data.fuelLevel / EV_VISUAL_FULL_KWH * 100.0f)),
0,
@@ -878,27 +865,27 @@ public:
(data.fuelLevel / data.fuelCapacity) * 100.0f,
0.0f,
100.0f);
- fuelDisplayValue = String(fuelPercent, 0);
- fuelProgressPercent = constrain(
+ state.fuelDisplayValue = String(fuelPercent, 0);
+ state.fuelProgressPercent = constrain(
static_cast<int>(lroundf(fuelPercent)), 0, 100);
}
else
{
- fuelDisplayValue = "--";
- fuelProgressPercent = 100;
+ state.fuelDisplayValue = "--";
+ state.fuelProgressPercent = 100;
}
// Keep legacy fields synchronized for existing protocol helpers.
- brakeBias = fuelDisplayValue;
- fuelAlertActive = String(fuelProgressPercent);
+ state.brakeBias = state.fuelDisplayValue;
+ state.fuelAlertActive = String(state.fuelProgressPercent);
for (int tyreIndex = 0; tyreIndex < 4; tyreIndex++)
{
- tyreTemperatures[tyreIndex] = data.tyreTemp[tyreIndex];
+ state.tyreTemperatures[tyreIndex] = data.tyreTemp[tyreIndex];
}
- // 由獨立 library 估算剩餘油量圈數。
- // 注意:GT7FuelEstimator 接收的是公升,不是百分比。
+ // ?梁蝡?library 隡啁??拚?瘝寥????
+ // 瘜冽?嚗T7FuelEstimator ?交??砍?嚗??舐????
if (validIceFuel)
derivedMetrics.fuel.update(data.fuelLevel, currentLap);
@@ -906,44 +893,46 @@ public:
? derivedMetrics.fuel.remainingLaps()
: -1.0f;
- if (!fuelIsEV && estimatedFuelLaps >= 0.0f)
+ if (!state.fuelIsEV && estimatedFuelLaps >= 0.0f)
{
- tyrePressureFrontLeft = String(estimatedFuelLaps, 1);
+ state.tyrePressureFrontLeft = String(estimatedFuelLaps, 1);
}
else
{
- tyrePressureFrontLeft = "--";
+ state.tyrePressureFrontLeft = "--";
}
- // 油門、煞車:UDP 範圍 0~255,轉為百分比
+ // 瘝寥???頠?UDP 蝭? 0嚚?55嚗??箇??
const int throttlePercent =
constrain(static_cast<int>(data.throttle * 100.0f / 255.0f), 0, 100);
const int brakePercent =
constrain(static_cast<int>(data.brake * 100.0f / 255.0f), 0, 100);
- tcLevel = String(throttlePercent);
- absLevel = String(brakePercent);
+ state.tcLevel = String(throttlePercent);
+ state.absLevel = String(brakePercent);
// GT7 exposes both driver pedal position and the filtered output actually
// applied by the simulation (after traction/ABS intervention).
- tcFilteredLevel = String(constrain(
+ state.tcFilteredLevel = String(constrain(
static_cast<int>(data.throttleFiltered * 100.0f / 255.0f), 0, 100));
- absFilteredLevel = String(constrain(
+ state.absFilteredLevel = String(constrain(
static_cast<int>(data.brakeFiltered * 100.0f / 255.0f), 0, 100));
const uint16_t flags = static_cast<uint16_t>(data.flags);
- revLimitAlertActive =
+ state.revLimitAlertActive =
(flags & static_cast<uint16_t>(SimulatorFlags::RevLimiterBlinkAlertActive)) != 0;
- // GT7 flags bit 0:車輛目前位於賽道/駕駛畫面中。
- // 回到選單、離開賽道或載入畫面時會變成 false。
- gt7CarOnTrack = (flags & (1U << 0)) != 0;
+ // GT7 flags bit 0嚗?頛???潸魚??擏??恍銝准€?
+ // ??詨??魚??頛?恍??霈? false??
+ gt7CarOnTrack = (flags & (1U << 0)) != 0;
+ telemetry.gt7.received = true; telemetry.gt7.time = millis(); telemetry.gt7.running = gt7CarOnTrack;
+ state.gameRunning = gt7CarOnTrack ? "True" : "False";
const bool tcsIsActive = (flags & (1U << 11)) != 0;
- tcActive = tcsIsActive ? "True" : "False";
+ state.tcActive = tcsIsActive ? "True" : "False";
- // GT7 沒有直接提供 ABS Active,使用四輪角速度與實際輪胎半徑估算。
+ // GT7 瘝??湔?? ABS Active嚗蝙?典?頛芾??漲?祕?憚??敺摯蝞€?
derivedMetrics.abs.update(
data.speed * 3.6f,
static_cast<float>(brakePercent),
@@ -951,256 +940,185 @@ public:
data.tyreRadius,
millis());
- absActive = derivedMetrics.abs.isActive()
+ state.absActive = derivedMetrics.abs.isActive()
? "True"
: "False";
- isTCCutNull = "True";
- tcTcCut = "0";
- brake = "0";
- lapInvalidated = "False";
+ state.isTCCutNull = "True";
+ state.tcTcCut = "0";
+ state.brake = "0";
+ state.lapInvalidated = "False";
return true;
}
#endif
- void read()
- {
-#if !INCLUDE_GT7_WIFI
-
- // 1~9:主要行車及圈速資料
- speed = FlowSerialReadStringUntil(';').toInt();
- gear = FlowSerialReadStringUntil(';');
- rpmPercent = FlowSerialReadStringUntil(';').toInt();
- rpmRedLineSetting = FlowSerialReadStringUntil(';').toInt();
-
- currentLapTime = FlowSerialReadStringUntil(';');
- lastLapTime = FlowSerialReadStringUntil(';');
- bestLapTime = FlowSerialReadStringUntil(';');
-
- sessionBestLiveDeltaSeconds =
- FlowSerialReadStringUntil(';');
-
- sessionBestLiveDeltaProgressSeconds =
- FlowSerialReadStringUntil(';');
-
- // Delta 欄改為上一圈-最佳圈;仍讀取舊欄位以維持 Protocol 相容。
- sessionBestLiveDeltaSeconds = formatLastBestDifference(
- parseLapTimeStringMs(lastLapTime),
- parseLapTimeStringMs(bestLapTime));
-
- // 10:預估剩餘油量圈數
- tyrePressureFrontLeft =
- FlowSerialReadStringUntil(';');
-
- // 11:起跑位置/排位位置
- tyrePressureFrontRight =
- FlowSerialReadStringUntil(';');
-
- // 12:目前圈數/總圈數,例如 3/10
- tyrePressureRearLeft =
- FlowSerialReadStringUntil(';');
-
- // 13:低油量警示
- fuelAlertActive =
- FlowSerialReadStringUntil(';');
-
- // 14:油門百分比
- tcLevel =
- FlowSerialReadStringUntil(';');
-
- // 15:TC 是否介入
- tcActive =
- FlowSerialReadStringUntil(';');
-
- // 16:煞車百分比
- absLevel =
- FlowSerialReadStringUntil(';');
- // SimHub's existing protocol has no separate filtered pedal channels.
- // Mirror the input so the dual-layer renderer remains backward compatible.
- tcFilteredLevel = tcLevel;
- absFilteredLevel = absLevel;
-
- // 17:ABS 是否介入
- absActive =
- FlowSerialReadStringUntil(';');
-
- // 18:固定為 True
- isTCCutNull =
- FlowSerialReadStringUntil(';');
-
- // 19:保留欄位,固定為 0
- tcTcCut =
- FlowSerialReadStringUntil(';');
-
- // 20:剩餘油量百分比
- brakeBias =
- FlowSerialReadStringUntil(';');
- fuelIsEV = false;
- fuelValueValid = brakeBias != "--" && brakeBias.length() > 0;
- fuelLabel = "FUEL";
- fuelDisplayValue = brakeBias;
- fuelProgressPercent = fuelValueValid
- ? constrain(static_cast<int>(lroundf(fuelAlertActive.toFloat())), 0, 100)
- : 100;
-
- // 21:保留欄位,固定為 0
- brake =
- FlowSerialReadStringUntil(';');
-
- // 22:本圈是否無效
- lapInvalidated =
- FlowSerialReadStringUntil(';');
-
- // 23:SimHub 是否正在接收遊戲資料
- gameRunning =
- FlowSerialReadStringUntil(';');
-
- // 清除可能存在的空白、\r
- gameRunning.trim();
-
- // Protocol 最後一欄也有分號,因此再讀掉封包結尾的換行
- FlowSerialReadStringUntil('\n');
-#endif
- const bool isGameRunning =
- gameRunning == "True" ||
- gameRunning == "true" ||
- gameRunning == "TRUE" ||
- gameRunning == "1";
-
- /*
- * 只有狀態真的從 False -> True,
- * 才視為 GT7 新的一次啟動。
- */
- bool gameJustStarted = false;
-
- if (gameRunningInitialized)
- {
- gameJustStarted =
- !previousGameRunning &&
- isGameRunning;
- }
- else
- {
- // 第一筆資料只用來建立初始狀態
- gameRunningInitialized = true;
- }
-
- /*
- * GT7 從未執行變成執行:
- * 無論之前是自動或手動關屏,都自動亮起。
- */
- if (gameJustStarted)
- {
- resetLapDifference();
-
- screenSleeping = false;
- screenOffByUser = false;
-
- fadeScreenOn();
-
- forceUpdate = true;
- gameStoppedTimerStarted = false;
- }
-
- if (isGameRunning)
- {
- /*
- * 遊戲持續執行時,只取消自動休眠倒數。
- * 不直接開背光,避免手動關屏後馬上又亮。
- */
- gameStoppedTimerStarted = false;
- }
- else
- {
- /*
- * GT7 未執行時開始五分鐘倒數。
- */
- if (!gameStoppedTimerStarted)
- {
- gameStoppedTimerStarted = true;
- gameStoppedTime = millis();
- }
- }
-
- // 最後再保存本次狀態,供下一筆資料比較
- previousGameRunning = isGameRunning;
- }
-
-#if INCLUDE_GT7_WIFI
- void updateGT7GameState()
- {
- const bool telemetryIsAlive =
- lastGT7PacketTime != 0 &&
- millis() - lastGT7PacketTime < RESET_WAITING_TIME * 1000;
-
- // 不只要求 UDP 還活著,也要求車輛真的在賽道上。
- // 因此離開賽道但 GT7 仍持續送封包時,也會切回等待畫面。
- const bool isGameRunning =
- telemetryIsAlive && gt7CarOnTrack;
-
- bool gameJustStarted = false;
-
- if (gameRunningInitialized)
- {
- gameJustStarted =
- !previousGameRunning &&
- isGameRunning;
- }
- else
- {
- gameRunningInitialized = true;
-
- // 開機時 GT7 已經在執行,也直接亮屏
- gameJustStarted = isGameRunning;
- }
-
- if (gameJustStarted)
- {
- resetLapDifference();
- screenSleeping = false;
- screenOffByUser = false;
-
- fadeScreenOn();
-
- forceUpdate = true;
- gameStoppedTimerStarted = false;
- }
-
- if (isGameRunning)
- {
- gameStoppedTimerStarted = false;
- }
- else if (!gameStoppedTimerStarted)
- {
- gameStoppedTimerStarted = true;
- gameStoppedTime = millis();
- }
-
- previousGameRunning = isGameRunning;
- }
-
-#endif
+ const char *sourceName() const {
+ return telemetry.active == TelemetrySource::GT7 ? "GT7 Wi-Fi" : telemetry.active == TelemetrySource::SimHub ? "SimHub USB" : "Waiting";
+ }
+ TelemetryMode telemetryMode() const { return telemetry.mode; }
+ bool needsFirstSetup() const {
+ return telemetry.mode == TelemetryMode::GT7 && !wifiConfigured;
+ }
+ bool takeNetworkChange() { bool v = networkChanged; networkChanged = false; return v; }
+ bool takeWifiStopRequest() { bool v = wifiStopRequested; wifiStopRequested = false; return v; }
+ void networkState(const String &status, bool portal, bool connected, bool configured = false) {
+ // Wi-Fi is intentionally powered off in SimHub mode. In that state
+ // esp_wifi_get_config cannot report the credentials that remain saved
+ // in flash, so a false status must not erase our cached result.
+ if (telemetry.mode == TelemetryMode::GT7 || configured)
+ wifiConfigured = configured;
+ if (connected && settingsScreen == SettingsScreen::WifiSettings) closeSettings();
+ if (networkStatus != status || wifiPortalActive != portal) {
+ networkStatus = status; wifiPortalActive = portal; connectingScreenActive = false;
+ }
+ }
+ void initializeTelemetry() {
+ WiFi.mode(WIFI_STA);
+ const bool hasSavedWifi = dashboardHasSavedWifi();
+ wifiConfigured = hasSavedWifi;
+ WiFi.mode(WIFI_OFF);
+ uint8_t storedConnection = 0;
+ if (dashboardPreferencesReady)
+ storedConnection = dashboardPreferences.getUChar("connection", 0);
+ // Existing dual-source builds have no explicit connection choice.
+ // Run the new onboarding from Touch Setup so migration follows the
+ // same deterministic path as a fresh device.
+ if (storedConnection == 0) touchSetupRequired = true;
+ telemetry.mode = storedConnection == static_cast<uint8_t>(TelemetryMode::GT7)
+ ? TelemetryMode::GT7 : storedConnection == static_cast<uint8_t>(TelemetryMode::SimHub)
+ ? TelemetryMode::SimHub : TelemetryMode::Auto;
+ firstRun = touchSetupRequired || telemetry.mode == TelemetryMode::Auto;
+ if (touchSetupRequired) showSettingsScreen(SettingsScreen::InitialTouch);
+ else if (telemetry.mode == TelemetryMode::Auto)
+ showSettingsScreen(SettingsScreen::ConnectionChoice);
+ else if (telemetry.mode == TelemetryMode::GT7 && !hasSavedWifi)
+ showSettingsScreen(SettingsScreen::WifiSettings);
+ networkChanged = true;
+ }
+ void setGT7TransportReady(bool ready) { gt7TransportReady = ready; }
+ void selectConnection(TelemetryMode mode) {
+ telemetry.mode = mode;
+ telemetry.active = TelemetrySource::None;
+ firstRun = false;
+ if (dashboardPreferencesReady)
+ dashboardPreferences.putUChar("connection", static_cast<uint8_t>(mode));
+ networkChanged = true;
+ connectingScreenActive = false;
+ forceUpdate = true;
+ if (mode == TelemetryMode::GT7 && !wifiConfigured)
+ showSettingsScreen(SettingsScreen::WifiSettings);
+ else closeSettings();
+ }
+ void noteUsbCommand() { if (!usbSeen) connectingScreenActive = false; usbSeen = true; lastUsbCommandTime = millis(); }
+ bool customReadPending() const { return receivingCustom; }
+ void read() {
+ receivingCustom = true; customLength = 0; customOverflow = false;
+ customStarted = customLastByte = millis();
+ }
+ void pollCustomProtocol() {
+ if (!receivingCustom) return;
+ unsigned budget = 512;
+ while (budget-- && FlowSerialAvailable() > 0) {
+ const int c = FlowSerialTimedRead();
+ if (c < 0) break;
+ customLastByte = millis();
+ if (c == '\n') {
+ customLine[customLength] = 0; receivingCustom = false;
+ const bool error = customOverflow || !acceptSimHubFrame();
+ if (customProtocolError != error) connectingScreenActive = false;
+ customProtocolError = error;
+ FlowSerialWrite(0x15); return;
+ }
+ if (c == '\r') continue;
+ if (c < 32 || c > 126 || customLength + 1 >= sizeof(customLine)) customOverflow = true;
+ else if (!customOverflow) customLine[customLength++] = static_cast<char>(c);
+ }
+ if (uint32_t(millis() - customLastByte) > 300 || uint32_t(millis() - customStarted) > 1500) {
+ receivingCustom = false; customProtocolError = true; connectingScreenActive = false;
+ FlowSerialWrite(0x15);
+ }
+ }
+ bool acceptSimHubFrame() {
+ SimHubProtocol::Frame frame;
+ if (!SimHubProtocol::parse(customLine, frame)) return false;
+ const uint32_t sequence = static_cast<uint32_t>(frame.values[1]);
+ if (haveSimHubSequence && sequence == lastSimHubSequence) return true;
+ lastSimHubSequence = sequence; haveSimHubSequence = true;
+ if (firstRun || telemetry.mode != TelemetryMode::SimHub) return true;
+ DashboardState next;
+ const auto text = [&](unsigned i) { return String(frame.fields[i]); };
+ const auto integer = [&](unsigned i) { return isfinite(frame.values[i]) ? static_cast<int>(lround(frame.values[i])) : 0; };
+ next.gameRunning = frame.values[2] == 1 ? "True" : "False";
+ next.speed = isfinite(frame.values[3]) ? String(integer(3)) : "--"; next.gear = text(4);
+ next.engineRpm = isfinite(frame.values[5]) ? integer(5) : -1;
+ next.rpmPercent = integer(6); next.rpmRedLineSetting = isfinite(frame.values[7]) ? integer(7) : 90;
+ next.rpmAlertRangeValid = isfinite(frame.values[6]) && isfinite(frame.values[7]) && frame.values[7] > 0;
+ next.revLimitAlertActive = next.rpmAlertRangeValid && next.rpmPercent >= next.rpmRedLineSetting;
+ next.currentLapTime = text(8); next.lastLapTime = text(9); next.bestLapTime = text(10);
+ next.sessionBestLiveDeltaSeconds = text(9) == "--" || text(10) == "--" ? "--" :
+ formatLastBestDifference(parseLapTimeStringMs(text(9)), parseLapTimeStringMs(text(10)));
+ next.tyrePressureFrontLeft = text(11); next.tyrePressureFrontRight = text(12);
+ next.tyrePressureRearLeft = text(13) + "/" + text(14);
+ next.fuelValueValid = isfinite(frame.values[15]);
+ next.fuelDisplayValue = next.fuelValueValid ? String(integer(15)) : "--";
+ next.fuelProgressPercent = next.fuelValueValid ? integer(15) : 100;
+ next.brakeBias = next.fuelDisplayValue; next.fuelAlertActive = String(next.fuelProgressPercent);
+ next.tcLevel = next.tcFilteredLevel = text(16); next.absLevel = next.absFilteredLevel = text(17);
+ next.tcActive = text(18); next.absActive = text(19); next.lapInvalidated = frame.values[20] == 1 ? "True" : frame.values[20] == 0 ? "False" : "--";
+ for (unsigned i = 0; i < 4; ++i) next.tyreTemperatures[i] = frame.values[21 + i];
+ simhubState = next; simhubDirty = true;
+ telemetry.simhub.received = true; telemetry.simhub.time = millis(); telemetry.simhub.running = frame.values[2] == 1;
+ return true;
+ }
+ void applyTelemetryState(const DashboardState &next) {
+ // Preserve renderer animation caches across telemetry updates.
+ DashboardState &state = static_cast<DashboardState &>(*this);
+ const String oldGear = state.prev_gear; const int oldRpm = state.prev_rpmPercent;
+ const bool oldRev = state.revLimitAlertWasActive, oldPulse = state.rpmPulseWasActive;
+ const uint8_t oldMix = state.lastRpmPulseWhiteMix;
+ const uint32_t oldFrame = state.lastRpmPulseFrameTime, oldStart = state.rpmPulseStartTime;
+ state = next; state.prev_gear = oldGear; state.prev_rpmPercent = oldRpm;
+ state.revLimitAlertWasActive = oldRev; state.rpmPulseWasActive = oldPulse;
+ state.lastRpmPulseWhiteMix = oldMix; state.lastRpmPulseFrameTime = oldFrame; state.rpmPulseStartTime = oldStart;
+ }
+ void updateTelemetry() {
+ uint32_t now = millis();
+ if (!firstRun && gt7TransportReady && telemetry.mode != TelemetryMode::SimHub && WiFi.status() == WL_CONNECTED) {
+ static uint32_t lastHeartbeat = 0;
+ if (uint32_t(now - lastHeartbeat) >= 500) { lastHeartbeat = now; gt7Telem.sendHeartbeat(); }
+ gt7Dirty = readGT7Wifi(gt7State) || gt7Dirty;
+ }
+ // Packet parsing timestamps the sample; compare against a time captured
+ // afterwards so a newly arrived frame never looks uint32-wrap stale.
+ now = millis();
+ const TelemetrySource before = telemetry.active;
+ const TelemetrySource selected = firstRun ? TelemetrySource::None : telemetry.update(now);
+ if (before != selected) {
+ resetLapDifference(); derivedMetrics.reset();
+ static_cast<DashboardState &>(*this) = DashboardState();
+ if (settingsScreen == SettingsScreen::Closed) invalidateDashboardRenderer();
+ else { connectingScreenActive = false; forceUpdate = true; }
+ }
+ if (selected == TelemetrySource::GT7 && (gt7Dirty || before != selected)) applyTelemetryState(gt7State);
+ if (selected == TelemetrySource::SimHub && (simhubDirty || before != selected)) applyTelemetryState(simhubState);
+ gt7Dirty = simhubDirty = false;
+ const bool running = selected == TelemetrySource::GT7 ? telemetry.gt7.running : selected == TelemetrySource::SimHub ? telemetry.simhub.running : false;
+ gameRunning = running ? "True" : "False";
+ if (running && !previousGameRunning) { screenSleeping = false; screenOffByUser = false; fadeScreenOn(); forceUpdate = true; }
+ if (running) gameStoppedTimerStarted = false;
+ else if (!gameStoppedTimerStarted) { gameStoppedTimerStarted = true; gameStoppedTime = now; }
+ previousGameRunning = running;
+ }
void loop()
{
-#if INCLUDE_GT7_WIFI
- static uint32_t lastHeartbeatTime = 0;
- const uint32_t now = millis();
- // GT7 需要持續收到 heartbeat 才會繼續傳送遙測資料。
- if (now - lastHeartbeatTime >= 500)
- {
- lastHeartbeatTime = now;
- gt7Telem.sendHeartbeat();
- }
+ updateTelemetry();
- readGT7Wifi();
- updateGT7GameState();
-#endif
/*
- * GT7 停止五分鐘,自動關閉背光。
+ * GT7 ?迫鈭????芸???????
*/
if (!screenSleeping &&
gameStoppedTimerStarted &&
@@ -1221,9 +1139,17 @@ public:
// Keep reading touch while asleep so a tap can wake the display and a
// long press can open Settings.
- readTouch();
-
- // 確認畫面開啟時,不讓 Dashboard 或 Connecting 畫面蓋回來。
+ readTouch();
+ if (settingsScreen == SettingsScreen::WifiSettings &&
+ settingsPressedButton < 0 && millis() - settingsStatusRefresh > 1000) {
+ settingsStatusRefresh = millis();
+ const String currentStatus = String(sourceName()) + ":" + networkStatus;
+ if (prevData["connectionStatus"] != currentStatus) {
+ prevData["connectionStatus"] = currentStatus; drawSettingsScreen();
+ }
+ }
+
+ // 蝣箄??恍????銝? Dashboard ??Connecting ?恍??靘€?
if (settingsScreen != SettingsScreen::Closed)
{
return;
@@ -1234,14 +1160,14 @@ public:
return;
}
- // 還沒收到 GT7 Telemetry 時顯示等待畫面。
+ // ???嗅 GT7 Telemetry ?*蝷箇?敺?U€?
if (!previousGameRunning)
{
updateConnectingScreen();
return;
}
- // 從 Connecting 切回主儀表時,完整重畫一次。
+ // 敺?Connecting ??銝餃?銵冽?嚗??湧??思?甈~€?
if (connectingScreenActive)
{
connectingScreenActive = false;
@@ -1389,29 +1315,6 @@ public:
prevData[cacheKey] = liveState;
}
- void drawTouchCalibrationHint(bool confirm)
- {
- const char *label = confirm ? "TOUCH AGAIN" : "TOUCH SETUP";
- const uint16_t textColor = confirm
- ? tft.color565(218, 111, 148)
- : tft.color565(105, 105, 105);
- constexpr int iconRadius = 4;
- constexpr int iconGap = 5;
- tft.setTextFont(1);
- const int textWidth = tft.textWidth(label);
- const int groupWidth = iconRadius * 2 + iconGap + textWidth;
- const int groupX = X_CENTER - groupWidth / 2;
- const int iconX = groupX + iconRadius - 2;
- const int textX = groupX + iconRadius * 2 + iconGap;
-
- tft.fillRect(62, 4, 196, 29, TFT_BLACK);
- tft.drawCircle(iconX, 17, iconRadius, textColor);
- tft.fillCircle(iconX, 17, 1, textColor);
- tft.setTextDatum(ML_DATUM);
- tft.setTextColor(textColor, TFT_BLACK);
- tft.drawString(label, textX, 18, 1);
- }
-
void drawConnectingScreenBase()
{
tft.fillScreen(TFT_BLACK);
@@ -1421,7 +1324,7 @@ public:
tft.setTextColor(TFT_WHITE, TFT_BLACK);
tft.drawCentreString(
- "GT7 DASH",
+ telemetry.mode == TelemetryMode::SimHub ? "SIMHUB DASH" : "GT7 DASH",
SCREEN_WIDTH / 2,
75,
4);
@@ -1430,16 +1333,21 @@ public:
tft.color565(120, 120, 120),
TFT_BLACK);
- // The asymmetric top-centre label lets a mismatched touch rotation be
- // inferred after two matching intentional taps while telemetry is idle.
- drawTouchCalibrationHint(false);
-
tft.drawCentreString(
- "Waiting for Telemetry",
+ telemetry.mode == TelemetryMode::SimHub ? "Waiting for SimHub" : "Waiting for GT7",
SCREEN_WIDTH / 2,
120,
2);
+ const bool usbActive = usbSeen && uint32_t(millis() - lastUsbCommandTime) < 5000;
+ const String hint = telemetry.mode == TelemetryMode::SimHub
+ ? (customProtocolError ? "Check Custom Protocol (DSH1)" :
+ usbActive && !telemetry.simhub.alive(millis()) ? "USB linked: set Custom Protocol" :
+ "Connect USB and start SimHub")
+ : (wifiConfigured ? networkStatus : "Wi-Fi setup required");
+ tft.setTextColor(tft.color565(120, 120, 120), TFT_BLACK);
+ tft.drawCentreString(hint, X_CENTER, 183, 1);
+
const int barWidth = 110;
const int barHeight = 3;
const int barX = (SCREEN_WIDTH - barWidth) / 2;
@@ -1473,7 +1381,7 @@ public:
const int barX = (SCREEN_WIDTH - barWidth) / 2;
const int barY = 162;
- // 每次先重畫整條深灰底
+ // 瘥活???急璇楛?啣?
tft.fillRect(
barX,
barY,
@@ -1483,17 +1391,17 @@ public:
const int highlightWidth = 32;
- // 讓流光可以從左側外面進入,再從右側離開
+ // 霈??隞亙?撌血憭?脣嚗?敺?湧??
const int travelWidth = barWidth + highlightWidth * 2;
const int highlightX =
(connectingAnimationStep % travelWidth) - highlightWidth;
/*
- * 將亮區切成多段灰階:
+ * 撠漁?€??憭挾?圈?嚗?
*
- * 暗 → 灰 → 亮灰 → 灰 → 暗
+ * ????????鈭桃 ????????
*
- * 因為高度只有 3px,看起來會像柔和的流光。
+ * ?擃漲?芣? 3px嚗?韏瑚????????€?
*/
const int segmentCount = 16;
const int segmentWidth =
@@ -1504,11 +1412,11 @@ public:
const float position =
(float)i / (segmentCount - 1);
- // 三角形亮度,中央最亮、兩側漸暗
+ // 銝?敶V漁摨佗?銝剖亢?€鈭柴€?湔撓??
float brightness =
1.0f - fabsf(position * 2.0f - 1.0f);
- // 亮度範圍約 45~190,避免白得太搶眼
+ // 鈭桀漲蝭?蝝?45嚚?90嚗?敺云?嗥
uint8_t gray =
45 + (uint8_t)(brightness * 145);
@@ -1517,14 +1425,14 @@ public:
int drawWidth = segmentWidth + 1;
- // 裁切左邊界
+ // 鋆?撌阡???
if (segmentX < barX)
{
drawWidth -= barX - segmentX;
segmentX = barX;
}
- // 裁切右邊界
+ // 鋆??喲???
if (segmentX + drawWidth > barX + barWidth)
{
drawWidth =
@@ -1556,7 +1464,7 @@ public:
const unsigned long now = millis();
- // 數值越大,動畫移動越慢
+ // ?詨€潸?憭改??蝘餃?頞
if (now - lastConnectingAnimationTime >= 65)
{
lastConnectingAnimationTime = now;
@@ -1588,6 +1496,7 @@ public:
int32_t previousBestLapMs = -1;
int32_t lastProcessedLapMs = -1;
+ String gt7LapDifference = "+0.000";
String updateLastBestDifference(
int32_t lastLapMs,
@@ -1598,10 +1507,10 @@ public:
return "+0.000";
}
- // 同一個上一圈可能每個封包重複傳送,只處理一次。
+ // ????銝€??賣?????銴???芾???甈~€?
if (lastLapMs == lastProcessedLapMs)
{
- return sessionBestLiveDeltaSeconds;
+ return gt7LapDifference;
}
lastProcessedLapMs = lastLapMs;
@@ -1614,8 +1523,9 @@ public:
static_cast<float>(lastLapMs - previousBestLapMs) / 1000.0f);
}
- // 本圈處理完後,才更新保存的最佳圈。
+ // ?砍???摰?嚗??湔靽???雿喳???
previousBestLapMs = bestLapMs;
+ gt7LapDifference = result;
return result;
}
@@ -1652,29 +1562,8 @@ public:
void drawDeviceBrightnessValue()
{
- static LGFX_Sprite brightnessSprite(&tft);
- static bool spriteCreated = false;
- if (!spriteCreated)
- {
- brightnessSprite.setColorDepth(16);
- spriteCreated = brightnessSprite.createSprite(116, 48) != nullptr;
- }
- if (spriteCreated)
- {
- brightnessSprite.fillSprite(TFT_BLACK);
- brightnessSprite.setTextColor(TFT_WHITE, TFT_BLACK);
- brightnessSprite.setTextDatum(MC_DATUM);
- brightnessSprite.drawString(
- String(userBrightnessPercent) + "%", 58, 24, 4);
- brightnessSprite.pushSprite(102, 72);
- }
- else
- {
- tft.fillRect(102, 72, 116, 48, TFT_BLACK);
- tft.setTextColor(TFT_WHITE, TFT_BLACK);
- tft.setTextDatum(MC_DATUM);
- tft.drawString(String(userBrightnessPercent) + "%", X_CENTER, 96, 4);
- }
+ drawSettingsButton(88, 58, 144, 42,
+ String("BRIGHTNESS ") + userBrightnessPercent + "%", false);
}
void clearThemePreviewRenderCache()
@@ -1790,12 +1679,41 @@ public:
tft.drawFastHLine(232, 104, 41, targetColor);
tft.drawFastVLine(252, 84, 41, targetColor);
- drawSettingsButton(25, 169, 125, 50, "CANCEL", pressedButton == 1);
- drawSettingsButton(170, 169, 125, 50, "SAVE", pressedButton == 2,
+ if (!touchSetupRequired)
+ drawSettingsButton(25, 169, 125, 50, "CANCEL", pressedButton == 1);
+ drawSettingsButton(touchSetupRequired ? 80 : 170, 169,
+ touchSetupRequired ? 160 : 125, 50, "SAVE", pressedButton == 2,
touchCalibrationVerified);
tft.setTextDatum(TL_DATUM);
}
+ void drawWifiSetupQrCode()
+ {
+ static constexpr uint8_t QR_VERSION = 3;
+ static constexpr int QR_SCALE = 4;
+ static constexpr int QR_QUIET_MODULES = 4;
+ static constexpr int QR_X = 10;
+ static constexpr int QR_Y = 47;
+ uint8_t qrData[128] = {};
+ QRCode qr;
+ if (qrcode_initText(&qr, qrData, QR_VERSION, ECC_LOW,
+ "WIFI:T:nopass;S:GT7-DASH-SETUP;;") != 0) return;
+
+ const int outerSize = (qr.size + QR_QUIET_MODULES * 2) * QR_SCALE;
+ tft.fillRect(QR_X, QR_Y, outerSize, outerSize, TFT_WHITE);
+ for (uint8_t y = 0; y < qr.size; ++y)
+ {
+ for (uint8_t x = 0; x < qr.size; ++x)
+ {
+ if (!qrcode_getModule(&qr, x, y)) continue;
+ tft.fillRect(
+ QR_X + (x + QR_QUIET_MODULES) * QR_SCALE,
+ QR_Y + (y + QR_QUIET_MODULES) * QR_SCALE,
+ QR_SCALE, QR_SCALE, TFT_BLACK);
+ }
+ }
+ }
+
void drawSettingsScreen(int pressedButton = -1)
{
tft.fillScreen(TFT_BLACK);
@@ -1810,6 +1728,43 @@ public:
drawSettingsButton(30, 113, 260, 48, "DEVICE SETTINGS", pressedButton == 1);
drawSettingsButton(30, 171, 260, 48, "BACK", pressedButton == 2);
}
+ else if (settingsScreen == SettingsScreen::InitialTouch) {
+ tft.setTextColor(TFT_WHITE, TFT_BLACK);
+ tft.drawString("TOUCH SETUP", X_CENTER, 34, 4);
+ tft.setTextColor(TFT_LIGHTGREY, TFT_BLACK);
+ tft.drawString("Tap the target to begin", X_CENTER, 70, 2);
+ const uint16_t color = tft.color565(210, 82, 126);
+ tft.drawCircle(252, 120, 18, color);
+ tft.drawCircle(252, 120, 8, color);
+ tft.drawFastHLine(228, 120, 49, color);
+ tft.drawFastVLine(252, 96, 49, color);
+ tft.setTextColor(TFT_DARKGREY, TFT_BLACK);
+ tft.drawString("Required once before setup", X_CENTER, 188, 1);
+ }
+ else if (settingsScreen == SettingsScreen::ConnectionChoice) {
+ tft.setTextColor(TFT_WHITE, TFT_BLACK);
+ tft.drawString("CHOOSE CONNECTION", X_CENTER, 24, 4);
+ drawSettingsButton(25, 62, 270, 58, "DIRECT GT7", pressedButton == 0);
+ drawSettingsButton(25, 132, 270, 58, "SIMHUB USB", pressedButton == 1);
+ if (connectionChoiceCanCancel)
+ drawSettingsButton(105, 202, 110, 30, "BACK", pressedButton == 2);
+ }
+ else if (settingsScreen == SettingsScreen::WifiSettings) {
+ tft.setTextColor(TFT_WHITE, TFT_BLACK); tft.drawString("WI-FI SETUP", X_CENTER, 18, 4);
+ drawWifiSetupQrCode();
+ tft.setTextColor(TFT_LIGHTGREY, TFT_BLACK);
+ tft.drawString("Scan to join", 235, 53, 2);
+ tft.drawString("or connect manually", 235, 75, 1);
+ tft.drawString("Wi-Fi", 235, 94, 1);
+ tft.setTextColor(TFT_CYAN, TFT_BLACK);
+ tft.drawString("GT7-DASH-SETUP", 235, 116, 2);
+ tft.setTextColor(TFT_LIGHTGREY, TFT_BLACK);
+ tft.drawString("Then open", 235, 143, 1);
+ tft.setTextColor(TFT_WHITE, TFT_BLACK);
+ tft.drawString("192.168.4.1", 235, 164, 2);
+ tft.setTextColor(TFT_LIGHTGREY, TFT_BLACK);
+ tft.drawString("Direct GT7 requires Wi-Fi", X_CENTER, 218, 1);
+ }
else if (settingsScreen == SettingsScreen::ThemeSelection)
{
renderThemePreview();
@@ -1818,21 +1773,20 @@ public:
{
tft.setTextColor(TFT_WHITE, TFT_BLACK);
tft.drawString("DEVICE SETTINGS", X_CENTER, 20, 4);
- tft.setTextColor(TFT_LIGHTGREY, TFT_BLACK);
- tft.drawString("BRIGHTNESS", X_CENTER, 53, 2);
- drawSettingsButton(30, 72, 70, 48, "-", pressedButton == 0);
- drawSettingsButton(220, 72, 70, 48, "+", pressedButton == 1);
+ drawSettingsButton(30, 58, 52, 42, "-", pressedButton == 0);
drawDeviceBrightnessValue();
- drawSettingsButton(30, 132, 260, 38, "RESET WIFI", pressedButton == 2,
- false, true);
- drawSettingsButton(30, 182, 260, 38, "BACK", pressedButton == 3);
+ drawSettingsButton(238, 58, 52, 42, "+", pressedButton == 1);
+ drawSettingsButton(30, 106, 260, 42, "CHANGE CONNECTION", pressedButton == 2);
+ drawSettingsButton(30, 154, 260, 42, "RESET TO DEFAULT", pressedButton == 3, false, true);
+ drawSettingsButton(105, 204, 110, 28, "BACK", pressedButton == 4);
}
- else if (settingsScreen == SettingsScreen::WifiResetConfirmation)
+ else if (settingsScreen == SettingsScreen::ResetConfirmation)
{
tft.setTextColor(TFT_WHITE, TFT_BLACK);
- tft.drawString("Reset saved Wi-Fi?", X_CENTER, 60, 4);
+ tft.drawString("RESET TO DEFAULT?", X_CENTER, 48, 4);
tft.setTextColor(TFT_DARKGREY, TFT_BLACK);
- tft.drawString("Device will restart", X_CENTER, 95, 2);
+ tft.drawString("All settings and Wi-Fi", X_CENTER, 86, 2);
+ tft.drawString("will be cleared", X_CENTER, 108, 2);
drawSettingsButton(25, 135, 120, 62, "CANCEL", pressedButton == 0);
drawSettingsButton(175, 135, 120, 62, "RESET", pressedButton == 1,
false, true);
@@ -1845,8 +1799,15 @@ public:
tft.setTextDatum(TL_DATUM);
}
- void redrawSettingsButton(int button, bool pressed)
- {
+ void redrawSettingsButton(int button, bool pressed)
+ {
+ if (settingsScreen == SettingsScreen::InitialTouch) return;
+ if (settingsScreen == SettingsScreen::ConnectionChoice) {
+ drawSettingsScreen(pressed ? button : -1); return;
+ }
+ if (settingsScreen == SettingsScreen::WifiSettings) {
+ drawSettingsScreen(pressed ? button : -1); return;
+ }
if (settingsScreen == SettingsScreen::Main)
{
if (button == 0)
@@ -1864,16 +1825,17 @@ public:
else if (settingsScreen == SettingsScreen::DeviceSettings)
{
if (button == 0)
- drawSettingsButton(30, 72, 70, 48, "-", pressed);
+ drawSettingsButton(30, 58, 52, 42, "-", pressed);
else if (button == 1)
- drawSettingsButton(220, 72, 70, 48, "+", pressed);
+ drawSettingsButton(238, 58, 52, 42, "+", pressed);
else if (button == 2)
- drawSettingsButton(30, 132, 260, 38, "RESET WIFI", pressed,
- false, true);
+ drawSettingsButton(30, 106, 260, 42, "CHANGE CONNECTION", pressed);
else if (button == 3)
- drawSettingsButton(30, 182, 260, 38, "BACK", pressed);
+ drawSettingsButton(30, 154, 260, 42, "RESET TO DEFAULT", pressed, false, true);
+ else if (button == 4)
+ drawSettingsButton(105, 204, 110, 28, "BACK", pressed);
}
- else if (settingsScreen == SettingsScreen::WifiResetConfirmation)
+ else if (settingsScreen == SettingsScreen::ResetConfirmation)
{
if (button == 0)
drawSettingsButton(25, 135, 120, 62, "CANCEL", pressed);
@@ -1883,10 +1845,11 @@ public:
}
else if (settingsScreen == SettingsScreen::TouchCalibration)
{
- if (button == 1)
+ if (button == 1 && !touchSetupRequired)
drawSettingsButton(25, 169, 125, 50, "CANCEL", pressed);
else if (button == 2)
- drawSettingsButton(170, 169, 125, 50, "SAVE", pressed,
+ drawSettingsButton(touchSetupRequired ? 80 : 170, 169,
+ touchSetupRequired ? 160 : 125, 50, "SAVE", pressed,
touchCalibrationVerified);
}
tft.setTextDatum(TL_DATUM);
@@ -1905,7 +1868,7 @@ public:
previewFullscreen = false;
}
settingsScreen = screen;
- wifiResetConfirmOpen = screen == SettingsScreen::WifiResetConfirmation;
+ wifiResetConfirmOpen = screen == SettingsScreen::ResetConfirmation;
settingsPressedButton = -1;
settingsLastInteractionTime = millis();
drawSettingsScreen();
@@ -1918,10 +1881,12 @@ public:
wifiResetConfirmOpen = false;
settingsPressedButton = -1;
touchCalibrationVerified = false;
- touchCalibrationEntryArmed = false;
- touchCalibrationAwaitingSecondTap = false;
- touchCalibrationFirstTapTime = 0;
pendingTouchRotation = touchRotation;
+ if (firstRun) {
+ if (touchSetupRequired) showSettingsScreen(SettingsScreen::InitialTouch);
+ else showSettingsScreen(SettingsScreen::ConnectionChoice);
+ return;
+ }
redrawAfterWifiResetDialog();
}
@@ -1934,13 +1899,13 @@ public:
void showWifiResetConfirm()
{
- showSettingsScreen(SettingsScreen::WifiResetConfirmation);
+ showSettingsScreen(SettingsScreen::ResetConfirmation);
}
#if 0
void showWifiResetConfirmLegacy()
{
- // 即使原本處於暗屏,也要先亮起確認畫面。
+ // ?喃蝙????嚗?閬?鈭株絲蝣箄??恍??
screenSleeping = false;
screenOffByUser = false;
tft.setBrightness(normalBrightness());
@@ -1954,7 +1919,7 @@ public:
tft.drawString("Reset saved Wi-Fi?", SCREEN_WIDTH / 2, 60, 4);
tft.setTextColor(TFT_DARKGREY, TFT_BLACK);
- tft.drawString("Device will restart", SCREEN_WIDTH / 2, 95, 2);
+ tft.drawString("Other settings will be kept", SCREEN_WIDTH / 2, 95, 2);
const int buttonY = 135;
const int buttonHeight = 62;
@@ -1987,7 +1952,7 @@ public:
tft.drawString("WI-FI RESET", SCREEN_WIDTH / 2, 90, 4);
tft.setTextColor(TFT_WHITE, TFT_BLACK);
- tft.drawString("Restarting...", SCREEN_WIDTH / 2, 145, 2);
+ tft.drawString("Clearing saved network...", SCREEN_WIDTH / 2, 145, 2);
tft.setTextDatum(TL_DATUM);
}
@@ -2005,6 +1970,16 @@ public:
int settingsButtonAtTouch() const
{
+ if (settingsScreen == SettingsScreen::InitialTouch) return -1;
+ if (settingsScreen == SettingsScreen::ConnectionChoice) {
+ if (touchInside(25, 62, 270, 58)) return 0;
+ if (touchInside(25, 132, 270, 58)) return 1;
+ if (connectionChoiceCanCancel && touchInside(105, 202, 110, 30)) return 2;
+ return -1;
+ }
+ if (settingsScreen == SettingsScreen::WifiSettings) {
+ return -1;
+ }
if (settingsScreen == SettingsScreen::Main)
{
if (touchInside(30, 55, 260, 48)) return 0;
@@ -2023,12 +1998,13 @@ public:
}
else if (settingsScreen == SettingsScreen::DeviceSettings)
{
- if (touchInside(30, 72, 70, 48)) return 0;
- if (touchInside(220, 72, 70, 48)) return 1;
- if (touchInside(30, 132, 260, 38)) return 2;
- if (touchInside(30, 182, 260, 38)) return 3;
+ if (touchInside(30, 58, 52, 42)) return 0;
+ if (touchInside(238, 58, 52, 42)) return 1;
+ if (touchInside(30, 106, 260, 42)) return 2;
+ if (touchInside(30, 154, 260, 42)) return 3;
+ if (touchInside(105, 204, 110, 28)) return 4;
}
- else if (settingsScreen == SettingsScreen::WifiResetConfirmation)
+ else if (settingsScreen == SettingsScreen::ResetConfirmation)
{
if (touchInside(25, 135, 120, 62)) return 0;
if (touchInside(175, 135, 120, 62)) return 1;
@@ -2039,15 +2015,22 @@ public:
const bool originalCancel =
originalTouchX >= 25 && originalTouchX < 150 &&
originalTouchY >= 169 && originalTouchY < 219;
- if (touchInside(25, 169, 125, 50) || originalCancel) return 1;
- if (touchCalibrationVerified && touchInside(170, 169, 125, 50)) return 2;
+ if (!touchSetupRequired && (touchInside(25, 169, 125, 50) || originalCancel)) return 1;
+ if (touchCalibrationVerified && touchInside(touchSetupRequired ? 80 : 170,
+ 169, touchSetupRequired ? 160 : 125, 50)) return 2;
}
return -1;
}
void activateSettingsButton(int button)
{
- if (settingsScreen == SettingsScreen::Main)
+ if (settingsScreen == SettingsScreen::ConnectionChoice)
+ {
+ if (button == 0) selectConnection(TelemetryMode::GT7);
+ else if (button == 1) selectConnection(TelemetryMode::SimHub);
+ else if (button == 2 && connectionChoiceCanCancel) closeSettings();
+ }
+ else if (settingsScreen == SettingsScreen::Main)
{
if (button == 0)
showSettingsScreen(SettingsScreen::ThemeSelection);
@@ -2114,25 +2097,30 @@ public:
}
else if (button == 2)
{
- showWifiResetConfirm();
- }
- else if (button == 3)
- {
- showSettingsScreen(SettingsScreen::Main);
- }
- }
- else if (settingsScreen == SettingsScreen::WifiResetConfirmation)
- {
- if (button == 0)
- {
- showSettingsScreen(SettingsScreen::DeviceSettings);
+ connectionChoiceCanCancel = true;
+ showSettingsScreen(SettingsScreen::ConnectionChoice);
}
- else if (button == 1)
- {
- showWifiResettingScreen();
- wifiResetRequested = true;
- }
- }
+ else if (button == 3) showWifiResetConfirm();
+ else if (button == 4) showSettingsScreen(SettingsScreen::Main);
+ }
+ else if (settingsScreen == SettingsScreen::ResetConfirmation) {
+ if (button == 1) {
+ if (dashboardPreferencesReady) dashboardPreferences.clear();
+ activeDashboardTheme = renderedDashboardTheme = previewDashboardTheme = DashboardTheme::GT3;
+ userBrightnessPercent = DEFAULT_BRIGHTNESS_PERCENT;
+ touchRotation = pendingTouchRotation = TouchRotation::Deg0;
+ touchSetupRequired = true;
+ connectionChoiceCanCancel = false;
+ telemetry.mode = TelemetryMode::Auto;
+ telemetry.active = TelemetrySource::None;
+ firstRun = true;
+ wifiConfigured = false;
+ wifiResetRequested = true;
+ networkChanged = true;
+ tft.setBrightness(normalBrightness());
+ showSettingsScreen(SettingsScreen::InitialTouch);
+ } else showSettingsScreen(SettingsScreen::DeviceSettings);
+ }
else if (settingsScreen == SettingsScreen::TouchCalibration)
{
if (button == 0)
@@ -2143,7 +2131,7 @@ public:
}
else if (button == 1)
{
- closeSettings();
+ if (!touchSetupRequired) closeSettings();
}
else if (button == 2 && touchCalibrationVerified)
{
@@ -2151,7 +2139,11 @@ public:
if (dashboardPreferencesReady)
dashboardPreferences.putUChar(
"touchRot", static_cast<uint8_t>(touchRotation));
- closeSettings();
+ if (touchSetupRequired) {
+ touchSetupRequired = false;
+ connectionChoiceCanCancel = false;
+ showSettingsScreen(SettingsScreen::ConnectionChoice);
+ } else closeSettings();
}
}
}
@@ -2166,11 +2158,14 @@ public:
static bool wasTouched = false;
static bool waitForReleaseAfterScreenChange = false;
+ static uint16_t initialTouchRawX = 0, initialTouchRawY = 0;
uint16_t rawTouchX = 0;
uint16_t rawTouchY = 0;
const bool isTouched = tft.getTouch(&rawTouchX, &rawTouchY);
if (isTouched)
{
+ initialTouchRawX = rawTouchX;
+ initialTouchRawY = rawTouchY;
applyTouchRotation(
rawTouchX, rawTouchY, touchRotation, originalTouchX, originalTouchY);
const TouchRotation effectiveRotation =
@@ -2181,15 +2176,16 @@ public:
rawTouchX, rawTouchY, effectiveRotation, touchX, touchY);
}
- if (touchCalibrationAwaitingSecondTap &&
- millis() - touchCalibrationFirstTapTime > TOUCH_CALIBRATION_DOUBLE_TAP_MS)
+ if (settingsScreen == SettingsScreen::InitialTouch)
{
- touchCalibrationAwaitingSecondTap = false;
- touchCalibrationFirstTapTime = 0;
- pendingTouchRotation = touchRotation;
- if (!previousGameRunning && !screenSleeping &&
- settingsScreen == SettingsScreen::Closed)
- drawTouchCalibrationHint(false);
+ if (!isTouched && wasTouched)
+ {
+ const int candidate = calibrationRotationForTouch(
+ initialTouchRawX, initialTouchRawY, 252, 120, 34, 34);
+ if (candidate >= 0) showTouchCalibration(static_cast<TouchRotation>(candidate));
+ }
+ wasTouched = isTouched;
+ return;
}
if (waitForReleaseAfterScreenChange)
@@ -2233,26 +2229,11 @@ public:
{
gameStoppedTimerStarted = true;
gameStoppedTime = millis();
- if (settingsScreen == SettingsScreen::Closed)
- {
- const int candidate = calibrationRotationForTouch(rawTouchX, rawTouchY);
- touchCalibrationEntryArmed = candidate >= 0;
- if (candidate >= 0)
- {
- if (touchCalibrationAwaitingSecondTap &&
- candidate != static_cast<int>(pendingTouchRotation))
- {
- touchCalibrationAwaitingSecondTap = false;
- touchCalibrationFirstTapTime = 0;
- }
- pendingTouchRotation = static_cast<TouchRotation>(candidate);
- }
- }
}
if (settingsScreen != SettingsScreen::Closed)
{
- if (!isTouched && settingsLastInteractionTime != 0 &&
+ if (!firstRun && settingsScreen != SettingsScreen::WifiSettings && !isTouched && settingsLastInteractionTime != 0 &&
millis() - settingsLastInteractionTime >= SETTINGS_TIMEOUT_MS)
{
closeSettings();
@@ -2284,28 +2265,7 @@ public:
if (!isTouched && wasTouched)
{
- if (touchCalibrationEntryArmed)
- {
- if (touchCalibrationAwaitingSecondTap &&
- millis() - touchCalibrationFirstTapTime <= TOUCH_CALIBRATION_DOUBLE_TAP_MS)
- {
- touchCalibrationAwaitingSecondTap = false;
- showTouchCalibration(pendingTouchRotation);
- }
- else
- {
- touchCalibrationAwaitingSecondTap = true;
- touchCalibrationFirstTapTime = millis();
- drawTouchCalibrationHint(true);
- }
- }
- else
- {
- touchCalibrationAwaitingSecondTap = false;
- touchCalibrationFirstTapTime = 0;
- showSettingsScreen(SettingsScreen::Main);
- }
- touchCalibrationEntryArmed = false;
+ showSettingsScreen(SettingsScreen::Main);
waitForReleaseAfterScreenChange = true;
}
@@ -2327,7 +2287,7 @@ public:
const bool isTouched = tft.getTouch(&touchX, &touchY);
- // 長按開啟確認畫面後,必須先放開,避免同一次觸控誤按 YES/NO。
+ // ?瑟???蝣箄??恍敺?敹?????踹???甈∟孛?扯炊??YES嚗O??
if (waitForReleaseAfterDialog)
{
if (!isTouched)
@@ -2338,7 +2298,7 @@ public:
return;
}
- // 確認畫面中的按鈕處理。
+ // 蝣箄??恍銝剔???????
if (wifiResetConfirmOpen)
{
if (isTouched && !wasTouched)
@@ -2378,14 +2338,14 @@ public:
return;
}
- // 手指剛碰到螢幕:開始計算長按時間。
+ // ???1?啗撟???閮??瑟?????
if (isTouched && !wasTouched)
{
touchStartTime = millis();
longPressTriggered = false;
}
- // 全螢幕持續按住 6 秒:顯示 Wi-Fi 重設確認畫面。
+ // ?刻撟?蝥?雿?6 蝘?憿舐內 Wi-Fi ?身蝣箄??恍??
if (isTouched &&
!longPressTriggered &&
millis() - touchStartTime >= WIFI_RESET_HOLD_MS)
@@ -2398,7 +2358,7 @@ public:
return;
}
- // 未達 6 秒便放開:維持原本的短按亮屏/熄屏功能。
+ // ?芷? 6 蝘噶?暸?嚗雁???祉??剜?鈭桀?嚗?撅??賬€?
if (!isTouched && wasTouched && !longPressTriggered)
{
if (screenSleeping)
diff --git a/src/SimHubProtocol.h b/src/SimHubProtocol.h
new file mode 100644
index 0000000..5f3a796
--- /dev/null
+++ b/src/SimHubProtocol.h
@@ -0,0 +1,77 @@
+#pragma once
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+#include <math.h>
+
+namespace SimHubProtocol {
+// DSH1;sequence;running;speed;gear;rpm;rpm%;redline%;current;last;best;
+// remainingLaps;position;lap;total;fuel%;throttle%;brake%;tc;abs;
+// invalidLap;temperatureFL;FR;RL;RR
+static constexpr unsigned fieldCount = 25;
+static constexpr unsigned maxLength = 384;
+struct Frame {
+ char *fields[fieldCount];
+ double values[fieldCount];
+};
+inline bool number(const char *s, double &value) {
+ if (!s || !*s) return false;
+ for (const char *p = s; *p; ++p)
+ if ((*p < '0' || *p > '9') && *p != '-' && *p != '+' && *p != '.') return false;
+ char *end = nullptr;
+ value = strtod(s, &end);
+ return end != s && *end == 0 && isfinite(value);
+}
+inline bool lapTime(const char *s) {
+ if (strcmp(s, "--") == 0) return true;
+ unsigned minutes = 0, seconds = 0, fraction = 0;
+ const char *p = s;
+ while (*p >= '0' && *p <= '9') { ++minutes; ++p; }
+ if (minutes == 0 || minutes > 3 || *p++ != ':') return false;
+ for (int i = 0; i < 2; ++i) {
+ if (*p < '0' || *p > '9') return false;
+ seconds = seconds * 10 + (*p++ - '0');
+ }
+ if (seconds >= 60 || *p++ != '.') return false;
+ while (*p >= '0' && *p <= '9') { ++fraction; ++p; }
+ return *p == 0 && fraction > 0 && fraction <= 3;
+}
+// Destructive split into a bounded caller-owned buffer; atomic commit by caller.
+inline bool parse(char *line, Frame &out) {
+ if (strlen(line) >= maxLength) return false;
+ unsigned count = 1;
+ out.fields[0] = line;
+ for (char *p = line; *p; ++p) {
+ if (*p == ';') {
+ if (count == fieldCount) return false;
+ *p = 0;
+ out.fields[count++] = p + 1;
+ }
+ }
+ if (count != fieldCount || strcmp(out.fields[0], "DSH1") != 0) return false;
+ for (unsigned i = 1; i < fieldCount; ++i) {
+ const char *s = out.fields[i];
+ out.values[i] = NAN;
+ if (i >= 8 && i <= 10) { if (!lapTime(s)) return false; continue; }
+ if (i == 4) {
+ if (strcmp(s, "--") && strcmp(s, "N") && strcmp(s, "R") &&
+ !(strlen(s) == 1 && s[0] >= '1' && s[0] <= '9')) return false;
+ continue;
+ }
+ if (i > 2 && strcmp(s, "--") == 0) continue;
+ double v;
+ if (!number(s, v)) return false;
+ double lo = 0, hi = 100;
+ if (i == 1) hi = 4294967295.0;
+ else if (i == 2 || (i >= 18 && i <= 20)) hi = 1;
+ else if (i == 3) hi = 1500;
+ else if (i == 5) hi = 30000;
+ else if (i >= 11 && i <= 14) hi = 9999;
+ else if (i >= 21) { lo = -100; hi = 1000; }
+ if (v < lo || v > hi) return false;
+ if ((i == 1 || i == 2 || (i >= 12 && i <= 14) || (i >= 18 && i <= 20)) && floor(v) != v) return false;
+ out.values[i] = v;
+ }
+ return true;
+}
+}
diff --git a/src/TelemetrySource.h b/src/TelemetrySource.h
new file mode 100644
index 0000000..c158827
--- /dev/null
+++ b/src/TelemetrySource.h
@@ -0,0 +1,41 @@
+#pragma once
+#include <stdint.h>
+
+enum class TelemetryMode : uint8_t { Auto = 0, GT7 = 1, SimHub = 2 };
+enum class TelemetrySource : uint8_t { None, GT7, SimHub };
+
+// Keep transport liveness separate from driving/session state. An idle source
+// cannot acquire Auto, but menus or a stopped car do not steal an existing lock.
+class TelemetrySelector {
+public:
+ static constexpr uint32_t timeoutMs = 4000;
+ struct Status {
+ bool received = false;
+ bool running = false;
+ uint32_t time = 0;
+ bool alive(uint32_t now) const { return received && uint32_t(now - time) < timeoutMs; }
+ };
+ Status gt7, simhub;
+ TelemetryMode mode = TelemetryMode::Auto;
+ TelemetrySource active = TelemetrySource::None;
+
+ TelemetrySource update(uint32_t now) {
+ if (mode == TelemetryMode::GT7)
+ return active = gt7.alive(now) ? TelemetrySource::GT7 : TelemetrySource::None;
+ if (mode == TelemetryMode::SimHub)
+ return active = simhub.alive(now) ? TelemetrySource::SimHub : TelemetrySource::None;
+ if (active == TelemetrySource::GT7 && gt7.alive(now)) {
+ if (!gt7.running && simhub.alive(now) && simhub.running)
+ return active = TelemetrySource::SimHub;
+ return active;
+ }
+ if (active == TelemetrySource::SimHub && simhub.alive(now)) {
+ if (!simhub.running && gt7.alive(now) && gt7.running)
+ return active = TelemetrySource::GT7;
+ return active;
+ }
+ if (gt7.alive(now) && gt7.running) return active = TelemetrySource::GT7;
+ if (simhub.alive(now) && simhub.running) return active = TelemetrySource::SimHub;
+ return active = TelemetrySource::None;
+ }
+};
diff --git a/src/dashboard/themes/ClassicTheme.inc b/src/dashboard/themes/ClassicTheme.inc
index 487566d..ad12297 100644
--- a/src/dashboard/themes/ClassicTheme.inc
+++ b/src/dashboard/themes/ClassicTheme.inc
@@ -70,9 +70,9 @@
ROW[2],
CELL_WIDTH * 2 - 2,
CELL_HEIGHT - 1,
- constrain(state.tcLevel.toInt(), 0, 100),
+ state.tcLevel == "--" ? -1 : constrain(state.tcLevel.toInt(), 0, 100),
constrain(state.tcFilteredLevel.toInt(), 0, 100),
- constrain(state.absLevel.toInt(), 0, 100),
+ state.absLevel == "--" ? -1 : constrain(state.absLevel.toInt(), 0, 100),
constrain(state.absFilteredLevel.toInt(), 0, 100),
forceUpdate);
@@ -772,9 +772,9 @@
int brakeAppliedPercent,
bool forceUpdate = false)
{
- throttlePercent = constrain(throttlePercent, 0, 100);
+ throttlePercent = constrain(throttlePercent, -1, 100);
throttleAppliedPercent = constrain(throttleAppliedPercent, 0, 100);
- brakePercent = constrain(brakePercent, 0, 100);
+ brakePercent = constrain(brakePercent, -1, 100);
brakeAppliedPercent = constrain(brakeAppliedPercent, 0, 100);
// 上下兩格,而不是左右兩格。
@@ -790,6 +790,16 @@
const char *id,
uint16_t color)
{
+ if (percent < 0) {
+ if (forceUpdate || prevData[id] != "--") {
+ tft.fillRect(x, cellY, totalWidth, cellHeight, TFT_BLACK);
+ tft.drawRoundRect(x, cellY, totalWidth, cellHeight, 5, TFT_DARKGREY);
+ tft.setTextColor(TFT_LIGHTGREY, TFT_BLACK); tft.setTextDatum(MC_DATUM);
+ tft.drawString("--", x + totalWidth / 2, cellY + cellHeight / 2, 2);
+ prevData[id] = "--";
+ }
+ return;
+ }
const String state = String(percent) + ":" + String(appliedPercent);
const bool firstDraw = true;
const int oldPercent = 0;
diff --git a/src/dashboard/themes/EnduranceTheme.inc b/src/dashboard/themes/EnduranceTheme.inc
index 26fe72b..a0af268 100644
--- a/src/dashboard/themes/EnduranceTheme.inc
+++ b/src/dashboard/themes/EnduranceTheme.inc
@@ -235,7 +235,7 @@
const int brakeApplied = constrain(state.absFilteredLevel.toInt(), 0, 100);
const int throttleInput = constrain(state.tcLevel.toInt(), 0, 100);
const int throttleApplied = constrain(state.tcFilteredLevel.toInt(), 0, 100);
- const String cacheState = String(brakeInput) + ":" +
+ const String cacheState = state.absLevel + ":" + state.tcLevel + ":" + String(brakeInput) + ":" +
String(brakeApplied) + ":" + String(throttleInput) + ":" +
String(throttleApplied);
if (!forceUpdate && prevData["endurancePedals"] == cacheState) return;
@@ -269,7 +269,7 @@
pedalSprite.drawString(labels[i], x + 21, 0, 1);
pedalSprite.setTextColor(TFT_WHITE, TFT_BLACK);
pedalSprite.setTextDatum(MC_DATUM);
- pedalSprite.drawString(String(input[i]), x + 21, 16, 2);
+ pedalSprite.drawString(((i == 0 ? state.absLevel : state.tcLevel) == "--" ? String("--") : String(input[i])), x + 21, 16, 2);
pedalSprite.fillRect(x + 4, 24, 34, 2, tft.color565(38, 40, 40));
pedalSprite.fillRect(x + 4, 24,
34 * input[i] / 100, 2, dimColors[i]);
@@ -291,7 +291,7 @@
tft.drawString(labels[i], x + 21, 150, 1);
tft.setTextColor(TFT_WHITE, TFT_BLACK);
tft.setTextDatum(MC_DATUM);
- tft.drawString(String(input[i]), x + 21, 166, 2);
+ tft.drawString(((i == 0 ? state.absLevel : state.tcLevel) == "--" ? String("--") : String(input[i])), x + 21, 166, 2);
tft.fillRect(x + 4, 174, 34, 2, tft.color565(38, 40, 40));
tft.fillRect(x + 4, 174, 34 * input[i] / 100, 2, dimColors[i]);
tft.fillRect(x + 4, 176, 34 * applied[i] / 100, 2, colors[i]);
@@ -468,7 +468,7 @@
const int displayedRpm = ((state.engineRpm + 25) / 50) * 50;
const uint16_t rpmColor = state.revLimitAlertActive ? red : muted;
drawEnduranceValueBuffered(99, 163, 91, 14,
- String(displayedRpm) + " RPM", "enduranceRpm",
+ (state.engineRpm < 0 ? String("--") : String(displayedRpm)) + " RPM", "enduranceRpm",
rpmColor, TFT_BLACK, &fonts::FreeSans9pt7b,
MC_DATUM, redraw, rpmSprite, rpmSpriteCreated, 0.61f, 0.62f);
diff --git a/src/dashboard/themes/GT3Theme.inc b/src/dashboard/themes/GT3Theme.inc
index 9883ff1..7253c2e 100644
--- a/src/dashboard/themes/GT3Theme.inc
+++ b/src/dashboard/themes/GT3Theme.inc
@@ -77,11 +77,11 @@
state.gear, state.tyreTemperatures, forceUpdate, 1);
drawPedalProgress(DashboardLayout::BRAKE_BAR_X, DashboardLayout::PEDAL_BAR_Y,
DashboardLayout::PEDAL_BAR_W, DashboardLayout::PEDAL_BAR_H,
- state.absLevel.toInt(), state.absFilteredLevel.toInt(), "gt3BrakeBar",
+ state.absLevel == "--" ? -1 : state.absLevel.toInt(), state.absFilteredLevel.toInt(), "gt3BrakeBar",
tft.color565(218, 220, 224), forceUpdate);
drawPedalProgress(DashboardLayout::THROTTLE_BAR_X, DashboardLayout::PEDAL_BAR_Y,
DashboardLayout::PEDAL_BAR_W, DashboardLayout::PEDAL_BAR_H,
- state.tcLevel.toInt(), state.tcFilteredLevel.toInt(), "gt3ThrottleBar",
+ state.tcLevel == "--" ? -1 : state.tcLevel.toInt(), state.tcFilteredLevel.toInt(), "gt3ThrottleBar",
tft.color565(218, 220, 224), forceUpdate);
drawDashboardValue(DashboardLayout::RIGHT_TEXT_X, DashboardLayout::LAP_VALUE_Y[0],
@@ -443,6 +443,16 @@
int inputPercent, int appliedPercent, const String &id,
uint16_t appliedColor, bool forceUpdate)
{
+ if (inputPercent < 0) {
+ if (forceUpdate || prevData[id] != "--") {
+ tft.fillRect(x, y, width, height, TFT_BLACK);
+ tft.drawRoundRect(x, y, width, height, 3, TFT_DARKGREY);
+ tft.setTextColor(TFT_LIGHTGREY, TFT_BLACK); tft.setTextDatum(MC_DATUM);
+ tft.drawString("--", x + width / 2, y + height / 2, 1);
+ prevData[id] = "--";
+ }
+ return;
+ }
inputPercent = constrain(inputPercent, 0, 100);
appliedPercent = constrain(appliedPercent, 0, 100);
const String state = String(inputPercent) + ":" + String(appliedPercent);
@@ -518,7 +528,7 @@
String(state.rpmAlertRangeValid ? 1 : 0);
const bool redlineChanged = prevData["gt3Redline"] != gradientState;
const int displayedRpm = ((state.engineRpm + 25) / 50) * 50;
- const String rpmValueText = String(displayedRpm);
+ const String rpmValueText = state.engineRpm < 0 ? "--" : String(displayedRpm);
const uint32_t now = millis();
const bool rpmWarningActive = state.rpmAlertRangeValid &&
state.rpmPercent >= state.rpmRedLineSetting;
diff --git a/src/dashboard/themes/MonoTheme.inc b/src/dashboard/themes/MonoTheme.inc
index ce24473..8998e39 100644
--- a/src/dashboard/themes/MonoTheme.inc
+++ b/src/dashboard/themes/MonoTheme.inc
@@ -228,7 +228,7 @@
const int brakeApplied = constrain(state.absFilteredLevel.toInt(), 0, 100);
const int throttleInput = constrain(state.tcLevel.toInt(), 0, 100);
const int throttleApplied = constrain(state.tcFilteredLevel.toInt(), 0, 100);
- const String cacheState = String(brakeInput) + ":" + String(brakeApplied) +
+ const String cacheState = state.absLevel + ":" + state.tcLevel + ":" + String(brakeInput) + ":" + String(brakeApplied) +
":" + String(throttleInput) + ":" + String(throttleApplied);
if (!forceUpdate && prevData["monoPedals"] == cacheState) return;
@@ -254,6 +254,7 @@
{
const int y = 2 + row * 10;
sprite.drawRect(12, y, 124, 7, frame);
+ if ((row == 0 ? state.absLevel : state.tcLevel) == "--") sprite.drawString("--", 65, y, 1);
const int inputW = 122 * values[row][0] / 100;
const int appliedW = 122 * values[row][1] / 100;
if (inputW > 0) sprite.fillRect(13, y + 1, inputW, 5, input);
diff --git a/src/dashboard/themes/PocketTheme.inc b/src/dashboard/themes/PocketTheme.inc
index b780dc3..e2e6b31 100644
--- a/src/dashboard/themes/PocketTheme.inc
+++ b/src/dashboard/themes/PocketTheme.inc
@@ -329,6 +329,7 @@
const int y = 218 + row * 9;
tft.drawString(row == 0 ? "B" : "T", 179, y + 4, 1);
tft.drawRect(190, y, 122, 7, dark);
+ if ((row == 0 ? state.absLevel : state.tcLevel) == "--") tft.drawString("--", 240, y + 4, 1);
if (fallbackValues[row] > 0)
tft.fillRect(191, y + 1,
120 * fallbackValues[row] / 100, 5, darkest);
@@ -356,6 +357,7 @@
const int y = 2 + row * 9;
sprite.drawString(row == 0 ? "B" : "T", 174, y + 4, 1);
sprite.drawRect(185, y, 122, 7, dark);
+ if ((row == 0 ? state.absLevel : state.tcLevel) == "--") sprite.drawString("--", 235, y + 4, 1);
if (values[row] > 0)
sprite.fillRect(186, y + 1, 120 * values[row] / 100, 5, darkest);
}
diff --git a/src/dashboard/themes/RadarTheme.inc b/src/dashboard/themes/RadarTheme.inc
index 91a1b61..01a8196 100644
--- a/src/dashboard/themes/RadarTheme.inc
+++ b/src/dashboard/themes/RadarTheme.inc
@@ -87,7 +87,7 @@
const int brakeApplied = constrain(state.absFilteredLevel.toInt(), 0, 100);
const int throttleInput = constrain(state.tcLevel.toInt(), 0, 100);
const int throttleApplied = constrain(state.tcFilteredLevel.toInt(), 0, 100);
- const String cacheState = String(brakeInput) + ":" + String(brakeApplied) +
+ const String cacheState = state.absLevel + ":" + state.tcLevel + ":" + String(brakeInput) + ":" + String(brakeApplied) +
":" + String(throttleInput) + ":" + String(throttleApplied);
if (!forceUpdate && prevData["radarPedals"] == cacheState) return;
@@ -113,6 +113,7 @@
{
const int y = 2 + row * 12;
pedalSprite.drawRect(10, y, 45, 7, frame);
+ if ((row == 0 ? state.absLevel : state.tcLevel) == "--") pedalSprite.drawString("--", 25, y, 1);
const int inputWidth = 43 * values[row][0] / 100;
const int appliedWidth = 43 * values[row][1] / 100;
if (inputWidth > 0)
diff --git a/src/dashboard/themes/RetroTheme.inc b/src/dashboard/themes/RetroTheme.inc
index 94c0373..6c2c123 100644
--- a/src/dashboard/themes/RetroTheme.inc
+++ b/src/dashboard/themes/RetroTheme.inc
@@ -145,7 +145,7 @@
}
const int displayedRpm = ((state.engineRpm + 25) / 50) * 50;
- drawRetroTextValue(5, 25, 49, 20, String(displayedRpm), "retroRpm",
+ drawRetroTextValue(5, 25, 49, 20, state.engineRpm < 0 ? "--" : String(displayedRpm), "retroRpm",
pulse ? alert : ink, 2, MC_DATUM, forceUpdate);
previousActive = active;
previousPulse = pulse;
@@ -159,7 +159,7 @@
const int brakeApplied = constrain(state.absFilteredLevel.toInt(), 0, 100);
const int throttleInput = constrain(state.tcLevel.toInt(), 0, 100);
const int throttleApplied = constrain(state.tcFilteredLevel.toInt(), 0, 100);
- const String value = String(brakeInput) + ":" + String(brakeApplied) + ":" +
+ const String value = state.absLevel + ":" + state.tcLevel + ":" + String(brakeInput) + ":" + String(brakeApplied) + ":" +
String(throttleInput) + ":" + String(throttleApplied);
if (!forceUpdate && prevData["retroPedals"] == value) return;
const uint16_t paper = tft.color565(198, 186, 152);
@@ -188,6 +188,7 @@
{
const int y = 211 + row * 13;
tft.drawRect(164, y, 68, 7, faint);
+ if ((row == 0 ? state.absLevel : state.tcLevel) == "--") tft.drawString("--", 189, y, 1);
const int inputW = 66 * values[row][0] / 100;
const int appliedW = 66 * values[row][1] / 100;
if (inputW > 0) tft.fillRect(165, y + 1, inputW, 5, ink);
@@ -210,6 +211,7 @@
{
const int y = 7 + row * 13;
pedalSprite.drawRect(barX, y, barW, barH, faint);
+ if ((row == 0 ? state.absLevel : state.tcLevel) == "--") pedalSprite.drawString("--", barX + 25, y, 1);
const int inputW = (barW - 2) * values[row][0] / 100;
const int appliedW = (barW - 2) * values[row][1] / 100;
if (inputW > 0) pedalSprite.fillRect(barX + 1, y + 1, inputW, barH - 2, ink);
diff --git a/src/main.cpp b/src/main.cpp
index 2aa9ca4..9c31f49 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -41,7 +41,7 @@ FullLoopbackStream incomingStream;
static constexpr const char *GT7_SETUP_AP_NAME = "GT7-DASH-SETUP";
#endif
-#define DEVICE_NAME "HelloWorldEsp" //{"Group":"General","Name":"DEVICE_NAME","Title":"Device name,\r\n make sure to use a unique name when using multiple arduinos","DefaultValue":"SimHub Dash","Type":"string","Template":"#define DEVICE_NAME \"{0}\""}
+#define DEVICE_NAME "GT7 SimHub Dash" //{"Group":"General","Name":"DEVICE_NAME","Title":"Device name,\r\n make sure to use a unique name when using multiple arduinos","DefaultValue":"SimHub Dash","Type":"string","Template":"#define DEVICE_NAME \"{0}\""}
// Known working features:
//
@@ -1124,6 +1124,38 @@ void buttonMatrixStatusChanged(int buttonId, byte Status) {
+#include "DashboardNetwork.h"
+DashboardNetwork dashboardNetwork;
+bool dashboardNetworkReady = false;
+bool gt7SocketReady = false;
+void setupDashboardNetwork() {
+ dashboardNetworkReady = dashboardNetwork.begin();
+}
+void serviceDashboardNetwork() {
+ if (!dashboardNetworkReady) {
+ shCustomProtocol.networkState("Wi-Fi unavailable; USB ready", false, false); return;
+ }
+ const auto mode = shCustomProtocol.telemetryMode();
+ if (shCustomProtocol.takeNetworkChange()) {
+ gt7Telem.stop(); gt7SocketReady = false;
+ dashboardNetwork.send(DashboardNetwork::Action::Configure, mode, shCustomProtocol.needsFirstSetup());
+ }
+ if (shCustomProtocol.takeWifiResetRequest()) {
+ gt7Telem.stop(); gt7SocketReady = false;
+ dashboardNetwork.send(DashboardNetwork::Action::Reset, mode);
+ }
+ if (shCustomProtocol.takeWifiStopRequest()) dashboardNetwork.send(DashboardNetwork::Action::StopPortal, mode);
+ DashboardNetwork::Status status;
+ if (dashboardNetwork.receive(status)) {
+ shCustomProtocol.networkState(status.message, status.portal, status.connected, status.configured);
+ const bool connected = mode == TelemetryMode::GT7 && status.connected;
+ if (connected && !gt7SocketReady) {
+ gt7Telem.begin(IPAddress(255,255,255,255), 'C'); gt7SocketReady = true;
+ } else if (!connected && gt7SocketReady) { gt7Telem.stop(); gt7SocketReady = false; }
+ }
+ shCustomProtocol.setGT7TransportReady(gt7SocketReady);
+}
+
void setup()
{
#if INCLUDE_WIFI
@@ -1144,11 +1176,8 @@ void setup()
shFUELPIN.SetValue((int)80);
#endif
-#if INCLUDE_GT7_WIFI
- FlowSerialBegin(115200);
-#else
- FlowSerialBegin(19200);
-#endif
+ Serial.setRxBufferSize(1024);
+ FlowSerialBegin(19200); // SimHub discovers at 19200, then negotiates its baud rate.
#ifdef INCLUDE_GAMEPAD
@@ -1314,91 +1343,8 @@ void setup()
shCustomProtocol.setup();
arqserial.setIdleFunction(idle);
-#if INCLUDE_GT7_WIFI
- delay(1000);
-
- WiFi.mode(WIFI_STA);
-
- WiFiManager wifiManager;
- // for test reset
- // wifiManager.resetSettings();
-
- wifiManager.setConnectTimeout(6);
- wifiManager.setConfigPortalBlocking(true);
- wifiManager.setClass("invert");
- wifiManager.setTitle("GT7 DASH SETUP");
- std::vector<const char *> menu = {
- "wifi",
- "restart",
- "info"
- };
- wifiManager.setMenu(menu);
- Serial.println();
- Serial.println("Connecting to saved Wi-Fi...");
- Serial.print("If connection fails, connect your phone to: ");
- Serial.println(GT7_SETUP_AP_NAME);
- Serial.println("Then open http://192.168.4.1 if the setup page does not appear automatically.");
-
- wifiManager.setAPCallback([](WiFiManager *manager)
- {
- Serial.println("=== WiFi setup portal started ===");
- showWifiSetupScreen(); });
-
- wifiManager.setBreakAfterConfig(true);
-
- while (WiFi.status() != WL_CONNECTED)
- {
- Serial.println("Starting Wi-Fi setup portal...");
-
- const bool portalResult =
- wifiManager.autoConnect(GT7_SETUP_AP_NAME);
-
- Serial.print("autoConnect result: ");
- Serial.println(portalResult ? "true" : "false");
-
- Serial.print("WiFi status: ");
- Serial.println(WiFi.status());
-
- // 不看 autoConnect() 回傳值,只確認 ESP32 是否真的連上
- if (WiFi.status() == WL_CONNECTED)
- {
- break;
- }
-
- Serial.println("Wi-Fi connection failed.");
- showWifiConnectionFailedScreen();
-
- delay(100);
- }
-
- Serial.println("Wi-Fi connected.");
- Serial.print("SSID: ");
- Serial.println(WiFi.SSID());
- Serial.print("ESP32 IP: ");
- Serial.println(WiFi.localIP());
-
- // Phase 1 keeps the existing fixed PS5 IP. Auto discovery comes next.
- // IPAddress ps5IP(192, 168, 1, 145);
- // gt7Telem.begin(ps5IP, 'C');
- // Serial.print("PS5 IP: ");
- // Serial.println(ps5IP);
-
- IPAddress gt7BroadcastIP(255, 255, 255, 255);
-
- gt7Telem.begin(gt7BroadcastIP, 'C');
-
- Serial.println("GT7 auto discovery enabled");
- Serial.print("Broadcast address: ");
- Serial.println(gt7BroadcastIP);
-
- // 明確停止 WiFiManager portal
- wifiManager.stopConfigPortal();
- // 關閉設定用的 SoftAP,只保留 STA
- WiFi.softAPdisconnect(true);
- WiFi.mode(WIFI_STA);
-#endif
-
-delay(1000);
+ shCustomProtocol.initializeTelemetry();
+ setupDashboardNetwork();
#if(GAMEPAD_AXIS_01_ENABLED == 1)
SHGAMEPADAXIS01.SetJoystick(&Joystick);
@@ -1507,23 +1453,15 @@ void loop() {
UpdateGamepadState();
#endif
shCustomProtocol.loop();
-#if INCLUDE_GT7_WIFI
- if (shCustomProtocol.takeWifiResetRequest())
- {
- Serial.println("Clearing saved Wi-Fi settings...");
-
- WiFiManager wifiManager;
- wifiManager.resetSettings();
+ serviceDashboardNetwork();
+ shCustomProtocol.pollCustomProtocol();
- delay(1000);
- ESP.restart();
- }
-#endif
// Wait for data
- if (FlowSerialAvailable() > 0) {
+ if (!shCustomProtocol.customReadPending() && FlowSerialAvailable() > 0) {
if (FlowSerialTimedRead() == MESSAGE_HEADER)
{
lastSerialActivity = millis();
+ shCustomProtocol.noteUsbCommand();
// Read command
loop_opt = FlowSerialTimedRead();
diff --git a/tests/simhub-formula.test.mjs b/tests/simhub-formula.test.mjs
new file mode 100644
index 0000000..f629ce7
--- /dev/null
+++ b/tests/simhub-formula.test.mjs
@@ -0,0 +1,90 @@
+import { readFileSync } from 'node:fs';
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+
+const formula = new Function('$prop', 'root', readFileSync(new URL('../simhub/custom-protocol.txt', import.meta.url), 'utf8'));
+const props = {
+ 'DataCorePlugin.GameRunning': true,
+ SpeedKmh: 140, Gear: '4', Rpms: 5600,
+ CarSettings_CurrentDisplayedRPMPercent: 68, CarSettings_RPMRedLineSetting: 90,
+ CurrentLapTime: '00:01:24.6310000', LastLapTime: '00:01:25.104', BestLapTime: '01:24.382',
+ Fuel: 30, 'DataCorePlugin.Computed.Fuel_LitersPerLap': 2.5, FuelPercent: 80,
+ Position: 5, CurrentLap: 3, TotalLaps: 10, Throttle: 68, Brake: 36,
+ TCActive: false, ABSActive: true, LapInvalidated: false,
+ TyreTemperatureFrontLeft: 82, TyreTemperatureFrontRight: 79,
+ TyreTemperatureRearLeft: 76, TyreTemperatureRearRight: 78,
+};
+const run = (values, root = {}) => formula(k => values[k] ?? null, root).split(';');
+
+test('formula emits the versioned 25-field contract with units and normalized times', () => {
+ const result = run(props);
+ assert.deepEqual(result, ['DSH1', '1', '1', '140', '4', '5600', '68', '90',
+ '01:24.631', '01:25.104', '01:24.382', '12.0', '5', '3', '10', '80',
+ '68', '36', '0', '1', '0', '82.0', '79.0', '76.0', '78.0']);
+ assert.ok(result.join(';').length < 384);
+});
+test('unchanging/paused telemetry still emits a new sequence; wraps safely', () => {
+ const root = {};
+ assert.equal(run(props, root)[1], '1');
+ assert.equal(run(props, root)[1], '2');
+ root.dashSequence = 4294967295;
+ assert.equal(run(props, root)[1], '0');
+});
+test('unsupported properties remain missing, not fabricated zero readings', () => {
+ const result = run({});
+ assert.deepEqual(result.slice(0, 3), ['DSH1', '1', '0']);
+ assert.ok(result.slice(3).every(v => v === '--'));
+ assert.equal(formula(() => { throw Error('missing'); }, {}).split(';').length, 25);
+});
+test('zero inputs are real readings, invalid/out-of-range values are missing', () => {
+ const result = run({ ...props, SpeedKmh: 0, Gear: -1, Throttle: 0, Brake: 101,
+ FuelPercent: NaN, Rpms: Infinity, TCActive: 'unknown' });
+ assert.equal(result[3], '0'); assert.equal(result[4], 'R');
+ assert.equal(result[5], '--'); assert.equal(result[15], '--');
+ assert.equal(result[16], '0'); assert.equal(result[17], '--'); assert.equal(result[18], '--');
+});
+test('null fuel cannot produce zero remaining laps and times cannot inject fields', () => {
+ const result = run({ ...props, Fuel: null, CurrentLapTime: '00:00:01;BAD', LastLapTime: '01:99.000' });
+ assert.equal(result[11], '--'); assert.equal(result[8], '--'); assert.equal(result[9], '--');
+});
+test('full NewData properties work without short aliases', () => {
+ const result = run({ 'DataCorePlugin.GameRunning': true,
+ 'DataCorePlugin.GameData.NewData.SpeedKmh': 123,
+ 'DataCorePlugin.GameData.NewData.Gear': 'N',
+ 'DataCorePlugin.GameData.NewData.CurrentLapTime': '00:03:02.050' });
+ assert.equal(result[3], '123'); assert.equal(result[4], 'N'); assert.equal(result[8], '03:02.050');
+});
+test('GameData properties used by the historical configuration remain supported', () => {
+ const result = run({ 'DataCorePlugin.GameRunning': true,
+ 'DataCorePlugin.GameData.CurrentLap': 3,
+ 'DataCorePlugin.GameData.TotalLaps': 10,
+ 'DataCorePlugin.GameData.Throttle': 50 });
+ assert.equal(result[13], '3'); assert.equal(result[14], '10'); assert.equal(result[16], '50');
+});
+test('live game fuel percent overrides a stale short alias when capacity is unavailable', () => {
+ const result = run({ FuelPercent: 47,
+ 'DataCorePlugin.GameData.NewData.FuelPercent': 72 });
+ assert.equal(result[15], '72');
+});
+test('fuel percent falls back to fuel divided by tank capacity', () => {
+ const result = run({ Fuel: 30, FuelCapacity: 60 });
+ assert.equal(result[15], '50');
+});
+test('calculated fuel percent overrides a stale reported percentage', () => {
+ const result = run({ Fuel: 24, FuelCapacity: 60,
+ 'DataCorePlugin.GameData.NewData.FuelPercent': 47 });
+ assert.equal(result[15], '40');
+});
+test('brief neutral reports between gears do not flicker the dashboard', () => {
+ const root = {};
+ assert.equal(run({ Gear: 3 }, root)[4], '3');
+ for (let i = 0; i < 8; i++) assert.equal(run({ Gear: 0 }, root)[4], '3');
+ assert.equal(run({ Gear: 4 }, root)[4], '4');
+});
+test('a sustained or initial neutral still displays as neutral', () => {
+ const root = {};
+ assert.equal(run({ Gear: 0 }, root)[4], 'N');
+ assert.equal(run({ Gear: 2 }, root)[4], '2');
+ for (let i = 0; i < 8; i++) assert.equal(run({ Gear: 0 }, root)[4], '2');
+ assert.equal(run({ Gear: 0 }, root)[4], 'N');
+});
diff --git a/tests/telemetry.cpp b/tests/telemetry.cpp
new file mode 100644
index 0000000..5209bfe
--- /dev/null
+++ b/tests/telemetry.cpp
@@ -0,0 +1,71 @@
+#include "../src/TelemetrySource.h"
+#include "../src/SimHubProtocol.h"
+#include <assert.h>
+#include <string>
+
+static bool parse(const std::string &input) {
+ if (input.size() >= SimHubProtocol::maxLength) return false;
+ char buffer[SimHubProtocol::maxLength];
+ memcpy(buffer, input.c_str(), input.size() + 1);
+ SimHubProtocol::Frame frame;
+ return SimHubProtocol::parse(buffer, frame);
+}
+static std::string replaceField(const std::string &line, unsigned index, const std::string &value) {
+ size_t a = 0;
+ while (index--) a = line.find(';', a) + 1;
+ size_t b = line.find(';', a);
+ return line.substr(0, a) + value + (b == std::string::npos ? "" : line.substr(b));
+}
+int main() {
+ const std::string valid = "DSH1;42;1;140;4;5600;68;90;01:24.631;01:25.104;01:24.382;4.5;5;3;10;80;68;36;0;1;0;82;79;76;78";
+ assert(parse(valid));
+ assert(parse("DSH1;0;0;--;--;--;--;--;--;--;--;--;--;--;--;--;--;--;--;--;--;--;--;--;--"));
+ assert(!parse(valid + ";"));
+ assert(!parse(valid.substr(0, valid.rfind(';'))));
+ assert(!parse(replaceField(valid, 0, "DSH2")));
+ assert(!parse(replaceField(valid, 1, "4294967296")));
+ assert(!parse(replaceField(valid, 2, "--")));
+ assert(!parse(replaceField(valid, 2, "0.5")));
+ assert(!parse(replaceField(valid, 3, "NaN")));
+ assert(!parse(replaceField(valid, 3, "140garbage")));
+ assert(!parse(replaceField(valid, 4, "12")));
+ assert(!parse(replaceField(valid, 8, "01:60.000")));
+ assert(!parse(replaceField(valid, 8, "01")));
+ assert(!parse(replaceField(valid, 15, "101")));
+ assert(!parse(replaceField(valid, 16, "-1")));
+ assert(!parse(replaceField(valid, 24, "inf")));
+ assert(!parse(replaceField(valid, 8, std::string(400, '0'))));
+ assert(parse(replaceField(valid, 21, "-10.5")));
+ assert(parse(replaceField(valid, 4, "R")));
+ assert(parse(replaceField(valid, 1, "4294967295")));
+
+ TelemetrySelector selector;
+ assert(selector.update(0) == TelemetrySource::None);
+ selector.simhub.received = true; selector.simhub.time = 100;
+ assert(selector.update(100) == TelemetrySource::None); // idle SimHub cannot acquire
+ selector.simhub.running = true;
+ assert(selector.update(100) == TelemetrySource::SimHub);
+ selector.gt7.received = true; selector.gt7.running = true; selector.gt7.time = 200;
+ assert(selector.update(200) == TelemetrySource::SimHub); // no preemption
+ selector.simhub.running = false;
+ assert(selector.update(300) == TelemetrySource::GT7); // running source replaces idle source
+ selector.gt7.running = false; selector.simhub.running = true; selector.simhub.time = 350;
+ assert(selector.update(350) == TelemetrySource::SimHub); // switching works both ways
+ selector.simhub.running = false; selector.gt7.running = true;
+ assert(selector.update(400) == TelemetrySource::GT7);
+ selector.gt7.running = false;
+ selector.gt7.time = 4099;
+ assert(selector.update(4099) == TelemetrySource::GT7); // idle source stays selected without replacement
+ assert(selector.update(4100) == TelemetrySource::None); // both sources expired
+ selector.gt7.running = true;
+ selector.active = TelemetrySource::None; selector.simhub.running = true; selector.simhub.time = 4100;
+ assert(selector.update(4100) == TelemetrySource::GT7); // initial tie
+ selector.mode = TelemetryMode::SimHub;
+ assert(selector.update(4100) == TelemetrySource::SimHub);
+ selector.mode = TelemetryMode::GT7; selector.gt7.received = false;
+ assert(selector.update(4100) == TelemetrySource::None); // manual does not fall back
+ selector.mode = TelemetryMode::Auto; selector.active = TelemetrySource::None;
+ selector.simhub.time = 0xfffffff0u;
+ assert(selector.update(20) == TelemetrySource::SimHub); // millis wraparound
+ assert(selector.update(4000) == TelemetrySource::None);
+}