Skip to content
C

init version

YU CHIH CHANG869728be3ee4
diff --git a/lib/GT7DerivedMetrics/GT7DerivedMetrics.cpp b/lib/GT7DerivedMetrics/GT7DerivedMetrics.cpp
new file mode 100644
index 0000000..76bacd1
--- /dev/null
+++ b/lib/GT7DerivedMetrics/GT7DerivedMetrics.cpp
@@ -0,0 +1,94 @@
+#include "GT7DerivedMetrics.h"
+#include <math.h>
+
+void GT7AbsEstimator::update(float vehicleKmh,float brakePercent,
+ const float wheelAngularSpeed[4],
+ const float tyreRadius[4],
+ uint32_t now)
+{
+ if(vehicleKmh < minSpeedKmh || brakePercent < minBrakePercent){
+ active = (now-lastTriggerTime)<sustainMs;
+ return;
+ }
+
+ float maxSlip=0;
+ for(int i=0;i<4;i++){
+ float wheelKmh=fabs(wheelAngularSpeed[i])*tyreRadius[i]*3.6f;
+ float slip=vehicleKmh-wheelKmh;
+ if(slip>maxSlip) maxSlip=slip;
+ }
+
+ if(maxSlip>triggerDiffKmh){
+ lastTriggerTime=now;
+ }
+
+ active=(maxSlip>triggerDiffKmh)||((now-lastTriggerTime)<sustainMs);
+}
+
+bool GT7AbsEstimator::isActive() const { return active; }
+
+float GT7AbsEstimator::intensity(uint32_t now) const{
+ if(!active) return 0;
+ return 70.0f+sinf(now/20.0f)*20.0f;
+}
+
+void GT7FuelEstimator::reset(){
+ lapStartFuel=-1.0f;
+ lastFuel=-1.0f;
+ lastLap=-1;
+ avgFuelPerLap=0.0f;
+ remaining=-1.0f;
+ validSamples=0;
+}
+
+void GT7FuelEstimator::update(float fuelLevel,int currentLap){
+ if(currentLap < 0 || fuelLevel < 0.0f) return;
+
+ if(lastLap < 0){
+ lastLap=currentLap;
+ lapStartFuel=fuelLevel;
+ lastFuel=fuelLevel;
+ return;
+ }
+
+ if(currentLap < lastLap){
+ reset();
+ lastLap=currentLap;
+ lapStartFuel=fuelLevel;
+ lastFuel=fuelLevel;
+ return;
+ }
+
+ // Pit refuel during the same lap: restart the baseline.
+ if(fuelLevel > lastFuel + 0.5f){
+ lapStartFuel=fuelLevel;
+ }
+
+ if(currentLap > lastLap){
+ const float used=lapStartFuel-fuelLevel;
+ if(used > 0.01f){
+ if(validSamples == 0) avgFuelPerLap=used;
+ else avgFuelPerLap=avgFuelPerLap*0.7f+used*0.3f;
+ ++validSamples;
+ }
+ lastLap=currentLap;
+ lapStartFuel=fuelLevel;
+ }
+
+ lastFuel=fuelLevel;
+ remaining=(avgFuelPerLap > 0.01f) ? fuelLevel/avgFuelPerLap : -1.0f;
+}
+
+float GT7FuelEstimator::remainingLaps() const{return remaining;}
+
+void GT7DeltaTracker::reset(){currentDelta=0;projectedDelta=0;}
+void GT7DeltaTracker::beginLap(){}
+void GT7DeltaTracker::sample(float,float,float,uint32_t){}
+void GT7DeltaTracker::endLap(uint32_t){}
+float GT7DeltaTracker::delta() const{return currentDelta;}
+float GT7DeltaTracker::deltaP() const{return projectedDelta;}
+
+void GT7DerivedMetrics::reset(){
+ fuel.reset();
+ delta.reset();
+}
diff --git a/lib/GT7DerivedMetrics/GT7DerivedMetrics.h b/lib/GT7DerivedMetrics/GT7DerivedMetrics.h
new file mode 100644
index 0000000..440ada7
--- /dev/null
+++ b/lib/GT7DerivedMetrics/GT7DerivedMetrics.h
@@ -0,0 +1,69 @@
+#pragma once
+#include <Arduino.h>
+
+struct GT7MetricsResult {
+ float deltaSeconds = 0.0f;
+ float deltaPSeconds = 0.0f;
+ float remainingFuelLaps = 0.0f;
+ bool absActive = false;
+};
+
+class GT7AbsEstimator {
+public:
+ void update(float vehicleKmh,
+ float brakePercent,
+ const float wheelAngularSpeed[4],
+ const float tyreRadius[4],
+ uint32_t now);
+
+ bool isActive() const;
+ float intensity(uint32_t now) const;
+
+private:
+ uint32_t lastTriggerTime = 0;
+ bool active = false;
+
+ static constexpr float triggerDiffKmh = 7.0f;
+ static constexpr float minSpeedKmh = 15.0f;
+ static constexpr float minBrakePercent = 10.0f;
+ static constexpr uint32_t sustainMs = 200;
+};
+
+class GT7FuelEstimator {
+public:
+ void reset();
+ void update(float fuelPercent, int currentLap);
+ float remainingLaps() const;
+
+private:
+ float lapStartFuel = -1.0f;
+ float lastFuel = -1.0f;
+ int lastLap = -1;
+ float avgFuelPerLap = 0.0f;
+ float remaining = -1.0f;
+ uint16_t validSamples = 0;
+};
+
+class GT7DeltaTracker {
+public:
+ void reset();
+ void beginLap();
+ void sample(float x,float y,float z,uint32_t currentLapMs);
+ void endLap(uint32_t lapTimeMs);
+
+ float delta() const;
+ float deltaP() const;
+
+private:
+ float currentDelta = 0;
+ float projectedDelta = 0;
+};
+
+class GT7DerivedMetrics {
+public:
+ void reset();
+
+ GT7AbsEstimator abs;
+ GT7FuelEstimator fuel;
+ GT7DeltaTracker delta;
+};
diff --git a/lib/GT7DerivedMetrics/library.json b/lib/GT7DerivedMetrics/library.json
new file mode 100644
index 0000000..a7fa99c
--- /dev/null
+++ b/lib/GT7DerivedMetrics/library.json
@@ -0,0 +1,6 @@
+{
+ "name":"GT7DerivedMetrics",
+ "version":"0.1.0",
+ "frameworks":"arduino",
+ "platforms":"espressif32"
+}
\ No newline at end of file
diff --git a/platformio.ini b/platformio.ini
index ed95d7a..6355b2d 100644
--- a/platformio.ini
+++ b/platformio.ini
@@ -75,12 +75,14 @@ lib_deps =
#############################################
[env:esp32]
platform = [email protected]
+board_build.partitions = huge_app.csv
# this should be set to your flavor of esp32, for instance wemos_d1_mini32, esp32doit-devkit-v1, seeed_xiao_esp32c3
# BOARD LIST: https://docs.platformio.org/en/latest/boards/index.html#espressif-32
board = esp32doit-devkit-v1
framework = arduino
lib_deps =
moononournation/GFX Library for [email protected]
+ https://github.com/MacManley/gt7-udp.git
locoduino/RingBuffer@^1.0.4
https://github.com/paulo-raca/ArduinoBufferedStreams.git#5e3a1a3d140955384a07878c64808e77fa2a7521
https://github.com/khoih-prog/ESPAsync_WiFiManager
@@ -98,6 +100,6 @@ build_flags =
;upload_speed = 921600
;upload_port = COM10
-upload_port = COM6
-monitor_port = COM6
+upload_port = COM3
+monitor_port = COM3
monitor_speed = 115200
\ No newline at end of file
diff --git a/src/SHCustomProtocol.h b/src/SHCustomProtocol.h
index faabbb0..2263d3c 100644
--- a/src/SHCustomProtocol.h
+++ b/src/SHCustomProtocol.h
@@ -11,6 +11,7 @@
#include <Arduino.h>
#include <map>
#include <BleGamepad.h> // libreria bluetooth
+#include <GT7DerivedMetrics.h>
static LGFX tft;
@@ -97,6 +98,41 @@ private:
// 避免第一筆資料被誤判為狀態切換
bool gameRunningInitialized = false;
+#if INCLUDE_GT7_WIFI
+ // 最近一次真正收到新 GT7 UDP 封包的時間
+ uint32_t lastGT7PacketTime = 0;
+ int32_t lastGT7PacketId = -1;
+ bool hasReceivedGT7Packet = false;
+ bool gt7CarOnTrack = false;
+
+ // GT7 衍生數據:ABS、剩餘油量圈數,以及之後的 Delta。
+ GT7DerivedMetrics derivedMetrics;
+#endif
+
+ String formatLapTimeMs(int32_t milliseconds)
+ {
+ if (milliseconds < 0)
+ {
+ return "--:--.---";
+ }
+
+ const uint32_t value = static_cast<uint32_t>(milliseconds);
+ const uint32_t minutes = value / 60000UL;
+ const uint32_t seconds = (value % 60000UL) / 1000UL;
+ const uint32_t millisPart = value % 1000UL;
+
+ char buffer[16];
+ snprintf(
+ buffer,
+ sizeof(buffer),
+ "%02lu:%02lu.%03lu",
+ static_cast<unsigned long>(minutes),
+ static_cast<unsigned long>(seconds),
+ static_cast<unsigned long>(millisPart));
+
+ return String(buffer);
+ }
+
// Connecting 畫面狀態
bool connectingScreenActive = false;
// int connectingDotIndex = 0;
@@ -141,6 +177,9 @@ public:
tft.fillScreen(TFT_BLACK);
screenSleeping = false;
gameStoppedTimerStarted = false;
+#if INCLUDE_GT7_WIFI
+ derivedMetrics.reset();
+#endif
bleGamepadConfig.setAutoReport(true); // in false non invia i comandi a windows
bleGamepadConfig.setAxesMax(32760);
@@ -156,8 +195,179 @@ public:
// Serial.println("Configurazione BleGamepad completata."); //x debug
}
+#if INCLUDE_GT7_WIFI
+ bool readGT7Wifi()
+ {
+ gt7Packet = gt7Telem.readData();
+
+ const int32_t packetId =
+ gt7Packet.packetContent.packetId;
+
+ /*
+ * readData() 沒收到新資料時會保留上一筆 Packet。
+ * 因此用 packetId 是否改變,判斷這一圈是否真的收到新封包。
+ */
+ if (hasReceivedGT7Packet && packetId == lastGT7PacketId)
+ {
+ return false;
+ }
+
+ // 尚未收到任何有效資料時,忽略初始化的空 Packet。
+ if (!hasReceivedGT7Packet && packetId == 0 &&
+ gt7Packet.packetContent.magic == 0)
+ {
+ return false;
+ }
+
+ hasReceivedGT7Packet = true;
+ lastGT7PacketId = packetId;
+ lastGT7PacketTime = millis();
+
+ const auto &data = gt7Packet.packetContent;
+
+ // 速度與檔位
+ speed = String(static_cast<int>(data.speed * 3.6f));
+
+ const int currentGear =
+ gt7Telem.getCurrentGearFromByte();
+
+ gear = currentGear == 0
+ ? "N"
+ : String(currentGear);
+
+ // RPM Bar
+ const float rpm = data.EngineRPM;
+ const float maxRpm = data.maxAlertRPM;
+ const float redLineRpm = data.minAlertRPM;
+
+ if (maxRpm > 0.0f)
+ {
+ rpmPercent = constrain(
+ static_cast<int>((rpm / maxRpm) * 100.0f),
+ 0,
+ 100);
+
+ rpmRedLineSetting = constrain(
+ static_cast<int>((redLineRpm / maxRpm) * 100.0f),
+ 0,
+ 100);
+ }
+ else
+ {
+ rpmPercent = 0;
+ rpmRedLineSetting = 90;
+ }
+
+ // 圈速:currentLap 只有使用 C Packet 時才有值
+ currentLapTime = formatLapTimeMs(data.currentLap);
+ lastLapTime = formatLapTimeMs(data.lastLaptime);
+ bestLapTime = formatLapTimeMs(data.bestLaptime);
+
+ // GT7DeltaTracker 目前只有介面骨架,尚未建立參考圈資料。
+ // 在完成真正的位置比對前維持 --,避免顯示假的 0.000。
+ sessionBestLiveDeltaSeconds = "--";
+ sessionBestLiveDeltaProgressSeconds = "--";
+
+ // 圈數
+ const int currentLap = max(0, static_cast<int>(data.lapCount));
+ const int totalLapCount = max(0, static_cast<int>(data.totalLaps));
+
+ if (totalLapCount > 0)
+ {
+ tyrePressureRearLeft = String(currentLap) + "/" + String(totalLapCount);
+ }
+ else
+ {
+ tyrePressureRearLeft = String(currentLap);
+ }
+
+ // 目前封包只有賽前起跑位置,沒有比賽中的即時排名
+ if (data.RaceStartPosition > 0)
+ {
+ tyrePressureFrontRight = String(data.RaceStartPosition);
+ }
+ else
+ {
+ tyrePressureFrontRight = "--";
+ }
+
+ // 油量百分比
+ float fuelPercent = 0.0f;
+ if (data.fuelCapacity > 0.0f)
+ {
+ fuelPercent = constrain(
+ (data.fuelLevel / data.fuelCapacity) * 100.0f,
+ 0.0f,
+ 100.0f);
+ }
+
+ brakeBias = String(fuelPercent, 0);
+ fuelAlertActive = String(fuelPercent, 1);
+
+ // 由獨立 library 估算剩餘油量圈數。
+ // 注意:GT7FuelEstimator 接收的是公升,不是百分比。
+ derivedMetrics.fuel.update(
+ data.fuelLevel,
+ currentLap);
+
+ const float estimatedFuelLaps =
+ derivedMetrics.fuel.remainingLaps();
+
+ if (estimatedFuelLaps >= 0.0f)
+ {
+ tyrePressureFrontLeft = String(estimatedFuelLaps, 1);
+ }
+ else
+ {
+ tyrePressureFrontLeft = "--";
+ }
+
+ // 油門、煞車:UDP 範圍 0~255,轉為百分比
+ 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);
+
+ const uint16_t flags = static_cast<uint16_t>(data.flags);
+
+ // GT7 flags bit 0:車輛目前位於賽道/駕駛畫面中。
+ // 回到選單、離開賽道或載入畫面時會變成 false。
+ gt7CarOnTrack = (flags & (1U << 0)) != 0;
+
+ const bool tcsIsActive = (flags & (1U << 11)) != 0;
+
+ tcActive = tcsIsActive ? "True" : "False";
+
+ // GT7 沒有直接提供 ABS Active,使用四輪角速度與實際輪胎半徑估算。
+ derivedMetrics.abs.update(
+ data.speed * 3.6f,
+ static_cast<float>(brakePercent),
+ data.wheelRPS,
+ data.tyreRadius,
+ millis());
+
+ absActive = derivedMetrics.abs.isActive()
+ ? "True"
+ : "False";
+
+ isTCCutNull = "True";
+ tcTcCut = "0";
+ brake = "0";
+ lapInvalidated = "False";
+
+ return true;
+ }
+
+#endif
+
void read()
{
+#if !INCLUDE_GT7_WIFI
+
// 1~9:主要行車及圈速資料
speed = FlowSerialReadStringUntil(';').toInt();
gear = FlowSerialReadStringUntil(';');
@@ -235,7 +445,7 @@ public:
// Protocol 最後一欄也有分號,因此再讀掉封包結尾的換行
FlowSerialReadStringUntil('\n');
-
+#endif
const bool isGameRunning =
gameRunning == "True" ||
gameRunning == "true" ||
@@ -299,8 +509,77 @@ public:
previousGameRunning = isGameRunning;
}
+#if INCLUDE_GT7_WIFI
+ void updateGT7GameState()
+ {
+ const bool telemetryIsAlive =
+ lastGT7PacketTime != 0 &&
+ millis() - lastGT7PacketTime < 3000;
+
+ // 不只要求 UDP 還活著,也要求車輛真的在賽道上。
+ // 因此離開賽道但 GT7 仍持續送封包時,也會切回等待畫面。
+ const bool isGameRunning =
+ telemetryIsAlive && gt7CarOnTrack;
+
+ bool gameJustStarted = false;
+
+ if (gameRunningInitialized)
+ {
+ gameJustStarted =
+ !previousGameRunning &&
+ isGameRunning;
+ }
+ else
+ {
+ gameRunningInitialized = true;
+
+ // 開機時 GT7 已經在執行,也直接亮屏
+ gameJustStarted = isGameRunning;
+ }
+
+ if (gameJustStarted)
+ {
+ screenSleeping = false;
+ screenOffByUser = false;
+
+ fadeScreenOn();
+
+ forceUpdate = true;
+ gameStoppedTimerStarted = false;
+ }
+
+ if (isGameRunning)
+ {
+ gameStoppedTimerStarted = false;
+ }
+ else if (!gameStoppedTimerStarted)
+ {
+ gameStoppedTimerStarted = true;
+ gameStoppedTime = millis();
+ }
+
+ previousGameRunning = isGameRunning;
+ }
+
+#endif
+
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();
+ }
+
+ readGT7Wifi();
+ updateGT7GameState();
+#endif
+
/*
* GT7 停止五分鐘,自動關閉背光。
*/
@@ -605,7 +884,7 @@ public:
drawCell(COL[2], ROW[4], brakeBias, "brakeBias", "FUEL", "center", TFT_MAGENTA, 4, forceUpdate);
// 剩餘圈數、位置、圈數、低油量警示
- drawCell(COL[3], ROW[3], tyrePressureFrontLeft, "tyrePressureFrontLeft", "F/LAP", "center", TFT_CYAN, 4, forceUpdate);
+ drawCell(COL[3], ROW[3], tyrePressureFrontLeft, "tyrePressureFrontLeft", "REM", "center", TFT_CYAN, 4, forceUpdate);
drawCell(COL[4], ROW[3], tyrePressureFrontRight, "tyrePressureFrontRight", "POS", "center", TFT_CYAN, 4, forceUpdate);
drawCell(COL[3], ROW[4], tyrePressureRearLeft, "tyrePressureRearLeft", "LAP", "center", TFT_CYAN, 4, forceUpdate);
drawCell(
diff --git a/src/main.cpp b/src/main.cpp
index a5b97af..dca2ab2 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -1,5 +1,9 @@
#include <Arduino.h>
#include <EspSimHub.h>
+#include <GT7UDPParser.h>
+
+GT7_UDP_Parser gt7Telem;
+Packet gt7Packet;
// No longer have to define whether it's an ESP32 or ESP8266, just do an initial compilation and
// VSCode will pick up the right environment from platformio.ini
@@ -27,6 +31,14 @@ FullLoopbackStream incomingStream;
#endif // INCLUDE_WIFI
+
+#define INCLUDE_GT7_WIFI true
+#if INCLUDE_GT7_WIFI
+ #include <WiFi.h>
+ #define GT7_WIFI_SSID "caahome_3fb 2.4G"
+ #define GT7_WIFI_PASSWORD "caacaacaac"
+#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}\""}
// Known working features:
@@ -1128,7 +1140,30 @@ void setup()
shFUELPIN.SetValue((int)80);
#endif
- FlowSerialBegin(19200);
+#if INCLUDE_GT7_WIFI
+ FlowSerialBegin(115200);
+#else
+ FlowSerialBegin(19200);
+#endif
+ delay(1000);
+#if INCLUDE_GT7_WIFI
+ delay(1000);
+ WiFi.mode(WIFI_STA);
+ WiFi.begin(GT7_WIFI_SSID, GT7_WIFI_PASSWORD);
+ Serial.print("Connecting to WiFi");
+ while (WiFi.status() != WL_CONNECTED)
+ {
+ delay(500);
+ Serial.print(".");
+ }
+ Serial.print("ESP32 IP: ");
+ Serial.println(WiFi.localIP());
+
+ IPAddress ps5IP(192, 168, 1, 145);
+ gt7Telem.begin(ps5IP, 'C');
+ Serial.print("PS5 IP: ");
+ Serial.println(ps5IP);
+#endif
#ifdef INCLUDE_GAMEPAD
Joystick.begin(false);
@@ -1370,6 +1405,7 @@ unsigned long lastSerialActivity = 0;
void loop() {
+
#if INCLUDE_WIFI
ECrowneWifi::loop();
#endif