2025年8月5日 星期二

PeakCAN Bus 與 ECU Simulator 通訊利用OpenAI 來找尋DTC 的解釋

在這一篇文章中PeakCAN Bus 與 ECU Simulator 通訊 擷取 DTC Data
得到DTC錯誤代碼但是有太多的錯誤代碼, 本來想說在本機建立一個database來搜尋, 靈機一動想說現在萬物都OpenAI, 於是就在得到DTC時把OpenAI API的功能寫進去來尋找 DTC的意義!
錯誤碼=>所有常見的 OBD2 錯誤代碼:解讀 P、B、C、U 程式碼
在Microsoft Visual Studio中利用NuGet 安裝OpenAI

using OpenAI;
using OpenAI.Chat;

private async void button3_Click(object sender, EventArgs e)
{
    //string dtcCode = txtDTC.Text.Trim();
    string dtcCode = "P0218".Trim();

    if (string.IsNullOrEmpty(dtcCode))
    {
        MessageBox.Show("請輸入 DTC 代碼,例如 P0202");
        return;
    }

    button3.Enabled = false;
    //txtResult.Text = "查詢中,請稍候...";
    CommonData.WriteMessage("查詢中,請稍候...", "", Color.Blue, Color.Red);

    string myApiKey = "your key";

    ChatClient client = new(
        model: "gpt-4.1",  //gpt-4
        apiKey: myApiKey
    );

    try
    {
        var prompt = $"請解釋 OBD2 故障碼 {dtcCode} 的意思,用繁體中文回答";
        
        ChatCompletion completion = await client.CompleteChatAsync(prompt);   
        CommonData.WriteMessage("查詢結果...", completion.Content[0].Text.ToString(), Color.Blue, Color.Red);
    }
    catch (Exception ex)
    {
        //txtResult.Text = "錯誤:" + ex.Message;
    }
    finally
    {
        button3.Enabled = true;
    }
}


還真的可以用!真是方便!!