Compare commits

..

22 Commits

Author SHA1 Message Date
jiangqun.chen
3e617309f7 增加日志,完善逻辑 2026-07-06 16:05:44 +08:00
jiangqun.chen
5b8e9d1a19 修改中文提示 2026-07-03 09:49:53 +08:00
jiangqun.chen
49939dc14c 在增加校验进度 2026-07-02 16:53:17 +08:00
jiangqun.chen
b9e6db147c 去掉没必要的重复内容 2026-07-02 16:47:16 +08:00
chenjiangqun
718cec11a5 加载增加进度条 2026-07-02 15:17:21 +08:00
chenjiangqun
959b4232aa 优化代码 2026-07-02 11:52:53 +08:00
chenjiangqun
40dce42fd7 完善A卡读取不稳问题 2026-07-02 10:58:46 +08:00
chenjiangqun
65a3117d10 修复N卡DDC通道限制导致不能识别超过15字节,导致可能漏判问题 2026-07-01 18:58:36 +08:00
chenjiangqun
fc09f64873 增加日志 2026-07-01 14:12:23 +08:00
chenjiangqun
bb0706e7b7 修复AMD显卡正常时不能升级问题 2026-06-30 20:13:14 +08:00
chenjiangqun
370ab2ea7c 加强一部分逻辑 2026-06-30 18:59:22 +08:00
chenjiangqun
6042411a01 增加指令打印日志 2026-06-30 18:56:58 +08:00
chenjiangqun
32409ebe2b 加 GPU 信息快照日志 2026-06-29 10:55:05 +08:00
chenjiangqun
6d31ffc78d 增加日志 2026-06-29 10:50:43 +08:00
chenjiangqun
39fbf5570c 若升级过程中失败,则下次升级重置提示语 2026-05-13 14:47:25 +08:00
chenjiangqun
2ae1a69422 1.未选择文件禁止升级 2.优化提示 3.文件校验错误禁止升级 2026-05-13 14:09:38 +08:00
chenjiangqun
4023159b47 最新code 2026-05-13 11:33:43 +08:00
chenjiangqun
464832787b 增加防呆 2026-05-09 17:41:36 +08:00
chenjiangqun
f50ce1f474 增加灵活比较 2026-05-08 11:42:28 +08:00
chenjiangqun
ffa1a94902 chore: stop tracking .vscode/ 2026-05-07 16:44:55 +08:00
chenjiangqun
1cbf3c66cb 调整忽视 2026-05-07 16:43:39 +08:00
chenjiangqun
97a5c56424 增加新UI 2026-05-07 16:42:01 +08:00
10 changed files with 3289 additions and 139 deletions

3
.gitignore vendored
View File

@@ -139,4 +139,5 @@ sql/
.builds
*.vspscc
*.vssscc
*.gpState
*.gpState.vs/
.vscode/

View File

@@ -1,13 +0,0 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch WinISP (.NET Framework)",
"type": "clr",
"request": "launch",
"program": "${workspaceFolder}/WinISP/bin/Debug/WinISP.exe",
"cwd": "${workspaceFolder}/WinISP",
"preLaunchTask": "build WinISP"
}
]
}

View File

@@ -1,3 +0,0 @@
{
"dotnet.preferCSharpExtension": true
}

View File

@@ -1,26 +0,0 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "build WinISP",
"type": "shell",
"command": "dotnet",
"args": [
"build",
"${workspaceFolder}/WinISP/WinISP.csproj"
],
"group": {
"kind": "build",
"isDefault": true
},
"problemMatcher": "$msCompile"
},
{
"label": "run WinISP exe",
"type": "shell",
"command": "${workspaceFolder}/WinISP/bin/Debug/WinISP.exe",
"dependsOn": "build WinISP",
"problemMatcher": []
}
]
}

View File

@@ -83,6 +83,40 @@ namespace WinISP.BaseClass
CreateGraphicsCardCtrl();
}
public void ReCreateGraphicCardCtrl(GPUTypes type)
{
FreeGraphicsCardCtrl();
try
{
switch (type)
{
case GPUTypes.AMD:
pGraphicCardCtrl = CreateGraphicCardCtrl((int)GPUTypes.AMD);
break;
case GPUTypes.NVIDIA:
pGraphicCardCtrl = CreateGraphicCardCtrl((int)GPUTypes.NVIDIA);
break;
case GPUTypes.INTEL:
pGraphicCardCtrl = CreateGraphicCardCtrl((int)GPUTypes.INTEL);
break;
default:
pGraphicCardCtrl = CreateGraphicCardCtrl();
break;
}
if (pGraphicCardCtrl != IntPtr.Zero)
_IsInit = true;
}
catch (Exception e)
{
frmISP.WriteLog("ReCreateGraphicCardCtrl(" + type.ToString() + ") Exception: " + e.Message, "debug");
}
}
private void CreateGraphicsCardCtrl()
{
// Declare an instance of the CallBack delegate.
@@ -106,19 +140,169 @@ namespace WinISP.BaseClass
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show(e.Message);
frmISP.WriteLog("CreateGraphicCardCtrl Exception: " + e.Message, "debug");
}
}
private readonly object _graphicsCardLock = new object();
private volatile bool _isDisposing = false;
private void FreeGraphicsCardCtrl()
{
// Free the GCHandle.
frmISP.WriteLog("Free the GCHandle.", "debug");
if (gch.IsAllocated)
gch.Free();
DisposeGraphicCardCtrl();
pGraphicCardCtrl = IntPtr.Zero;
_IsInit = false;
lock (_graphicsCardLock)
{
// 防止重复释放
if (_isDisposing)
{
frmISP.WriteLog("Graphics card control is already being disposed, skipping.", "warn");
return;
}
if (!_IsInit)
{
frmISP.WriteLog("Graphics card control is not initialized, nothing to free.", "debug");
return;
}
_isDisposing = true;
try
{
// 第一步:释放 GCHandle
FreeGCHandle();
// 第二步:释放图形卡控制资源
DisposeGraphicsCardControl();
// 第三步:清空指针
pGraphicCardCtrl = IntPtr.Zero;
// 第四步:更新状态
_IsInit = false;
frmISP.WriteLog("Graphics card control freed successfully.", "info");
}
catch (Exception ex)
{
frmISP.WriteLog($"Error freeing graphics card control: {ex.GetType().Name} - {ex.Message}", "error");
// 即使出错也要尝试清理状态
try
{
pGraphicCardCtrl = IntPtr.Zero;
_IsInit = false;
}
catch (Exception cleanupEx)
{
frmISP.WriteLog($"Error during cleanup after exception: {cleanupEx.Message}", "error");
}
}
finally
{
_isDisposing = false;
}
}
}
/// <summary>
/// 安全释放 GCHandle
/// </summary>
private void FreeGCHandle()
{
try
{
if (gch.IsAllocated)
{
frmISP.WriteLog("Freeing GCHandle...", "debug");
gch.Free();
frmISP.WriteLog("GCHandle freed successfully.", "debug");
}
else
{
frmISP.WriteLog("GCHandle is not allocated, skipping free operation.", "debug");
}
}
catch (InvalidOperationException ex)
{
frmISP.WriteLog($"InvalidOperationException when freeing GCHandle: {ex.Message}", "warn");
}
catch (Exception ex)
{
frmISP.WriteLog($"Unexpected exception when freeing GCHandle: {ex.GetType().Name} - {ex.Message}", "error");
}
}
/// <summary>
/// 安全释放图形卡控制资源
/// </summary>
private void DisposeGraphicsCardControl()
{
try
{
if (pGraphicCardCtrl != IntPtr.Zero)
{
frmISP.WriteLog("Disposing graphics card control...", "debug");
DisposeGraphicCardCtrl();
frmISP.WriteLog("Graphics card control disposed successfully.", "debug");
}
else
{
frmISP.WriteLog("Graphics card control pointer is null, skipping dispose.", "debug");
}
}
catch (AccessViolationException ex)
{
frmISP.WriteLog($"AccessViolationException when disposing graphics card control: {ex.Message}", "error");
}
catch (ObjectDisposedException ex)
{
frmISP.WriteLog($"ObjectDisposedException when disposing graphics card control: {ex.Message}", "warn");
}
catch (Exception ex)
{
frmISP.WriteLog($"Unexpected exception when disposing graphics card control: {ex.GetType().Name} - {ex.Message}", "error");
}
}
/// <summary>
/// 验证图形卡控制是否已正确释放
/// </summary>
public bool IsGraphicsCardControlFreed()
{
lock (_graphicsCardLock)
{
return !_IsInit && pGraphicCardCtrl == IntPtr.Zero && !gch.IsAllocated;
}
}
/// <summary>
/// 强制清理(用于异常恢复)
/// </summary>
public void ForceCleanupGraphicsCardCtrl()
{
lock (_graphicsCardLock)
{
try
{
frmISP.WriteLog("Performing force cleanup of graphics card control...", "warn");
// 强制释放 GCHandle
if (gch.IsAllocated)
{
try { gch.Free(); }
catch { }
}
// 强制清空指针
pGraphicCardCtrl = IntPtr.Zero;
_IsInit = false;
frmISP.WriteLog("Force cleanup completed.", "info");
}
catch (Exception ex)
{
frmISP.WriteLog($"Error during force cleanup: {ex.Message}", "error");
}
}
}
public GraphicCardI2CCtrl()
@@ -214,41 +398,47 @@ namespace WinISP.BaseClass
{
throw new NotImplementedException();
}
public bool WriteData(byte[] data)
{
Byte slvAddr = data[0];
Byte[] wrBuf = new Byte[data.Length - 1];
Array.Copy(data, 1, wrBuf, 0, wrBuf.Length);
const Byte maxWrLen = 16;
int idx = 0;
unsafe
{
fixed (Byte* pArr = wrBuf)
{
return DDCWrite(pGraphicCardCtrl, slvAddr, (uint)(wrBuf.Length), wrBuf);
}
}
bool ret = DDCWrite(pGraphicCardCtrl, slvAddr, (uint)wrBuf.Length, wrBuf);
frmISP.WriteLog($"[DDCWrite] card={GraphicCardType} slv=0x{slvAddr:X2} len={wrBuf.Length} ret={ret}", ret ? "debug" : "error");
return ret;
}
public bool ReadData(byte[] data, byte[] wrCmds = null)
{
uint revlen = (uint)data.Length;
unsafe
if (wrCmds == null || wrCmds.Length == 0)
{
fixed (Byte* pArr = data)
{
return DDCRead(pGraphicCardCtrl, wrCmds[0], revlen, data);
}
frmISP.WriteLog($"[DDCRead] card={GraphicCardType} wrCmds is NULL/empty!", "error");
return false;
}
uint revlen = (uint)data.Length;
bool ret = DDCRead(pGraphicCardCtrl, wrCmds[0], revlen, data);
frmISP.WriteLog($"[DDCRead] card={GraphicCardType} slv=0x{wrCmds[0]:X2} rdLen={revlen} ret={ret} " +
$"first4={(data.Length >= 4 ? BitConverter.ToString(data, 0, 4) : "n/a")}", ret ? "debug" : "error");
return ret;
}
public bool Init()
{
if (_IsInit == true)
return true;
else
if (pGraphicCardCtrl == IntPtr.Zero)
return false;
try
{
return InitGraphicCardCtrl(pGraphicCardCtrl);
}
catch (Exception e)
{
frmISP.WriteLog("Init() Exception: " + e.Message, "debug");
return false;
}
}
public GRAPHIC_CARD GetGraphicCardType

View File

@@ -1,4 +1,6 @@
using System;
using System.Linq;
using WinISP;
namespace MTK
{
@@ -47,9 +49,7 @@ namespace MTK
for (int i = 3; i < wrBuf.Length; ++i)
strData += wrBuf[i].ToString("X2") + " ";
if (ret)
WinISP.frmISP.WriteLog("[Write DDC]" + strData, "debug");
else
if (!ret)
WinISP.frmISP.WriteLog("[Write DDC Fail]" + strData, "debug");
return ret;
@@ -60,38 +60,77 @@ namespace MTK
string strData = "";
for (int i = 0; i < data.Length; ++i)
strData += data[i].ToString("X2") + " ";
if (!DDC_Write(data))
return null;
WinIOLib.DelayUs(delayTime);
const Byte dest = 0x6F;
Byte[] wrCmds = { dest };
Byte[] recvBuf = new Byte[recvLen];
strData = "";
if (_i2cCtrl.ReadData(recvBuf, wrCmds) == true)
const int maxNullRetryCnt = 3;
for (int retry = 0; retry <= maxNullRetryCnt; retry++)
{
for (int i = 0; i < recvBuf.Length; ++i)
strData += recvBuf[i].ToString("X2") + " ";
if ((recvBuf[0] != 0x6E) || (recvBuf[1] <= 0x80))
{
WinISP.frmISP.WriteLog("[Read DDC Fail]" + strData + " I2C Format Error!", "debug");
if (!DDC_Write(data))
return null;
WinIOLib.DelayUs(delayTime * (retry + 1));
const Byte dest = 0x6F;
Byte[] wrCmds = { dest };
Byte[] recvBuf = new Byte[recvLen];
strData = "";
if (_i2cCtrl.ReadData(recvBuf, wrCmds) == true)
{
frmISP.WriteLog(
$"[DDC_Read RAW] cmd=0x{data[1]:X2} recvLen={recvLen} " +
$"raw=[{string.Join(" ", recvBuf.Select(b => b.ToString("X2")))}]",
"debug");
// ────────
for (int i = 0; i < recvBuf.Length; ++i)
strData += recvBuf[i].ToString("X2") + " ";
if ((recvBuf[0] == 0x6E) && (recvBuf[1] == 0x80))
{
if (retry < maxNullRetryCnt)
continue;
WinISP.frmISP.WriteLog("[Read DDC Fail]" + strData + " DDC null response timeout.", "debug");
return null;
}
if ((recvBuf[0] != 0x6E) || (recvBuf[1] < 0x80))
{
WinISP.frmISP.WriteLog("[Read DDC Fail]" + strData + " I2C Format Error!", "debug");
return null;
}
return recvBuf;
}
else
{
WinISP.frmISP.WriteLog("[Read DDC]" + strData, "debug");
return recvBuf;
WinISP.frmISP.WriteLog("[Read DDC Fail]", "debug");
return null;
}
}
else
return null;
}
/// <summary>
/// 从 DDC 0x6F 继续读取数据(不重新发送命令)。
/// 用于 N卡 DP AUX 通道 16 字节限制导致截断时的分段续读。
/// 在 DDC_Read 成功返回后立即调用,尝试读取响应缓冲区中尚未消费的剩余字节。
/// </summary>
/// <param name="recvLen">要读取的字节数</param>
/// <returns>读取到的字节数组,失败返回 null</returns>
public static Byte[] DDC_ReadContinue(int recvLen)
{
const Byte dest = 0x6F;
Byte[] wrCmds = { dest };
Byte[] recvBuf = new Byte[recvLen];
if (_i2cCtrl.ReadData(recvBuf, wrCmds))
{
for (int i = 0; i < recvBuf.Length; ++i)
strData += recvBuf[i].ToString("X2") + " ";
WinISP.frmISP.WriteLog("[Read DDC Fail]", "debug");
return null;
frmISP.WriteLog(
$"[DDC_ReadContinue] rdLen={recvLen} raw=[{string.Join(" ", recvBuf.Select(b => b.ToString("X2")))}]",
"debug");
return recvBuf;
}
frmISP.WriteLog($"[DDC_ReadContinue] rdLen={recvLen} read failed", "debug");
return null;
}
private static Byte CalCheckSum(Byte[] data, int startIdx = 0)

View File

@@ -101,6 +101,7 @@
this.btnAuto.Text = "Auto";
this.btnAuto.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText;
this.btnAuto.UseVisualStyleBackColor = true;
this.btnAuto.Click += new System.EventHandler(this.btnAuto_Click);
//
// btnLoadFile
//

File diff suppressed because it is too large Load Diff

View File

@@ -41,7 +41,7 @@
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>x86</PlatformTarget>
<PlatformTarget>x64</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
@@ -179,11 +179,12 @@
<Folder Include="Img\" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
<Copy SourceFiles="$(MSBuildProjectDirectory)\bin\x86\Release\GraphicsCardCtrl.dll"
DestinationFolder="$(OutputPath)"
Condition="'$(Configuration)' == 'Release' And Exists('$(MSBuildProjectDirectory)\bin\x86\Release\GraphicsCardCtrl.dll')" />
<Copy SourceFiles="$(MSBuildProjectDirectory)\bin\Debug\GraphicsCardCtrl.dll"
DestinationFolder="$(OutputPath)"
Condition="'$(Configuration)' == 'Debug' And Exists('$(MSBuildProjectDirectory)\bin\Debug\GraphicsCardCtrl.dll')" />
</Target>
-->
</Project>

View File

@@ -39,6 +39,10 @@ namespace WinISP
private string _chipName = String.Empty;
private string _u8ChipName = String.Empty;
private string _u8BoardName = String.Empty;
private string _monitorModelName = String.Empty;
private string _monitorChipName = String.Empty;
private string _monitorPanelName = String.Empty;
private string _monitorBoardName = String.Empty;
private bool _IsRunISP = false;
ISimI2CCtrl _simI2cCtrl;
private bool _IsHDMIConnect = false;
@@ -48,6 +52,17 @@ namespace WinISP
private Byte _clientType = 0;
private const int WM_DEVICECHANGE = 0x219;
private const int DBT_DEVNODES_CHANGED = 0x07;
private const byte MStarCommand = 0xCC;
private const byte CmdGetModelName = 0x36;
private const byte CmdGetChipName = 0x41;
private const byte CmdGetPanelName = 0x42;
private const byte CmdGetBoardName = 0x45;
private const int MonitorModelNameLength = 20;
private const int MonitorChipNameLength = 20;
private const int MonitorPanelNameLength = 30;
private const int MonitorBoardNameLength = 20;
private const string PlaceholderMonitorModelName = "MST9U6_PanelCMIM236HGJ_L21";
private const string LegacyMonitorModelName = "MAG 321UPD E14";
object _lockObj = new object();
int _numberOfMonitors;
int _lastNumOfMonitors = 0;
@@ -243,30 +258,61 @@ namespace WinISP
}
}
// 判断u8ModelName和MODEL_NAME_STRING是否一致
private static string NormalizeMonitorInfo(string value)
{
return String.IsNullOrWhiteSpace(value) ? String.Empty : value.Trim();
}
private string NormalizeMonitorModelName(string value)
{
string normalizedValue = NormalizeMonitorInfo(value);
if (string.Equals(normalizedValue, PlaceholderMonitorModelName, StringComparison.OrdinalIgnoreCase))
return LegacyMonitorModelName;
return normalizedValue;
}
private string GetModelMismatchMessage(string binModelName)
{
return "Model不匹配: FW=" + NormalizeMonitorModelName(_monitorModelName) + " BIN=" + NormalizeMonitorInfo(binModelName);
}
private bool IsModelNameMatch(string u8Model_Name)
{
const string MODEL_NAME_STRING = "MAG 321UPD E14";
return string.Equals(MODEL_NAME_STRING, u8Model_Name, StringComparison.Ordinal);
string monitorValue = NormalizeMonitorModelName(_monitorModelName);
if (String.IsNullOrEmpty(monitorValue))
return true;
return string.Equals(monitorValue, NormalizeMonitorInfo(u8Model_Name), StringComparison.Ordinal);
}
private bool IsChipNameMatch(string u8Chi_pName)
{
const string ChipName_STRING = "MST9U";
return string.Equals(ChipName_STRING, u8Chi_pName, StringComparison.Ordinal);
string monitorValue = NormalizeMonitorInfo(_monitorChipName);
if (String.IsNullOrEmpty(monitorValue))
return true;
return string.Equals(monitorValue, NormalizeMonitorInfo(u8Chi_pName), StringComparison.Ordinal);
}
private bool IsPanelNameMatch(string u8Panel_Name)
{
const string PanelName_STRING = "Panel_SG315GD01_2_eDP";
return string.Equals(PanelName_STRING, u8Panel_Name, StringComparison.Ordinal);
string monitorValue = NormalizeMonitorInfo(_monitorPanelName);
if (String.IsNullOrEmpty(monitorValue))
return true;
return string.Equals(monitorValue, NormalizeMonitorInfo(u8Panel_Name), StringComparison.Ordinal);
}
private bool IsBoardNameMatch(string u8Board_Name)
{
const string BoardName_STRING = "FW.010";
if (u8Board_Name[0] == 'F' && u8Board_Name[1] == 'W'&& u8Board_Name[2] == '.' && u8Board_Name[3] == '0')
{
return true;
}
return false;
string monitorValue = NormalizeMonitorInfo(_monitorBoardName);
string binValue = NormalizeMonitorInfo(u8Board_Name);
if (!String.IsNullOrEmpty(monitorValue))
return string.Equals(monitorValue, binValue, StringComparison.Ordinal);
if (binValue.Length < 4)
return false;
return binValue[0] == 'F' && binValue[1] == 'W' && binValue[2] == '.' && binValue[3] == '0';
}
private void btnOpenBin_Click(object sender, EventArgs e)
{
@@ -299,7 +345,8 @@ namespace WinISP
_u8ChipName = Encoding.ASCII.GetString(infoBytes, modenameLen, chipnameLen).TrimEnd('\0');
_u8PanelName = Encoding.ASCII.GetString(infoBytes, modenameLen + chipnameLen, panelnameLen).TrimEnd('\0');
_u8BoardName = Encoding.ASCII.GetString(infoBytes, modenameLen + chipnameLen + panelnameLen, boardnameLen).TrimEnd('\0');
SetStatusMsg("Read Bin OK. Model: " + _u8ModelName + ", Chip: " + _u8ChipName + ", Panel: " + _u8PanelName + ", Board: " + _u8BoardName);
// SetStatusMsg("Read Bin OK. Model: " + _u8ModelName + ", Chip: " + _u8ChipName + ", Panel: " + _u8PanelName + ", Board: " + _u8BoardName);
SetStatusMsg("Please update the firmware.",true);
}
catch (Exception ex)
{
@@ -312,6 +359,45 @@ namespace WinISP
if (flashSectorInfo != null && flashSectorInfo.Count > 0)
flashSectorInfo.Clear();
btnConnect.PerformClick();
if (IsConnect)
{
string verifyMsg = String.Empty;
bool canVerify = false;
var gpuType = ((GraphicCardI2CCtrl)_simI2cCtrl).GetGraphicCardType;
if (gpuType != GraphicCardI2CCtrl.GRAPHIC_CARD.INTEL && gpuType != GraphicCardI2CCtrl.GRAPHIC_CARD.INTEL_IGCL)
{
ClearConnectedMonitorInfo();
QueryConnectedMonitorInfo();
canVerify = !string.IsNullOrWhiteSpace(_monitorModelName)
|| !string.IsNullOrWhiteSpace(_monitorChipName)
|| !string.IsNullOrWhiteSpace(_monitorPanelName);
}
if (!canVerify)
{
verifyMsg = "BIN已加载但当前显卡路径无法立即读取显示器身份信息暂时不能立即判断是否一致。";
}
else if (!IsModelNameMatch(_u8ModelName))
{
verifyMsg = GetModelMismatchMessage(_u8ModelName);
}
else if (!IsChipNameMatch(_u8ChipName))
{
verifyMsg = Properties.Resources.ChipNameErr;
}
else if (!IsPanelNameMatch(_u8PanelName))
{
verifyMsg = Properties.Resources.PanelNameErr;
}
else
{
verifyMsg = "BIN与当前显示器匹配可开始升级。";
}
SetStatusMsg(verifyMsg, true);
}
}
}
@@ -320,6 +406,95 @@ namespace WinISP
WinIOLib._dftI2CDlyTime = Convert.ToInt16(txtDelayUnit.Text);
}
private void QueryConnectedMonitorInfo()
{
// 读取显示器端信息(芯片名、面板名、板卡名、型号名)
try
{
bool legacyRemapped = false;
// 型号名
{
Byte[] cmd = { MStarCommand, CmdGetModelName };
Byte[] recv = MTKDebugCmd.DDC_Read(cmd, MonitorModelNameLength + 2, 500)
?? MTKDebugCmd.DDC_Read(cmd, MonitorModelNameLength + 2, 2000)
?? MTKDebugCmd.DDC_Read(cmd, MonitorModelNameLength + 2, 5000);
if (recv != null && recv.Length >= MonitorModelNameLength + 2)
{
string rawModelName = Encoding.ASCII.GetString(recv, 2, MonitorModelNameLength).TrimEnd('\0');
if (string.Equals(rawModelName.Trim(), PlaceholderMonitorModelName, StringComparison.OrdinalIgnoreCase))
{
legacyRemapped = true;
_monitorModelName = LegacyMonitorModelName;
_monitorChipName = "MST9U";
_monitorPanelName = "Panel_SG315GD01_2_eDP";
WriteLog("Placeholder model detected, legacy remapping: " + rawModelName + " -> " + _monitorModelName + ", Chip=MST9U, Panel=Panel_SG315GD01_2_eDP", "debug");
}
else
{
_monitorModelName = NormalizeMonitorModelName(rawModelName);
}
}
else
_monitorModelName = string.Empty;
}
// 芯片名
if (!legacyRemapped)
{
Byte[] cmd = { MStarCommand, CmdGetChipName };
Byte[] recv = MTKDebugCmd.DDC_Read(cmd, MonitorChipNameLength + 2, 500)
?? MTKDebugCmd.DDC_Read(cmd, MonitorChipNameLength + 2, 2000)
?? MTKDebugCmd.DDC_Read(cmd, MonitorChipNameLength + 2, 5000);
if (recv != null && recv.Length >= MonitorChipNameLength + 2)
_monitorChipName = Encoding.ASCII.GetString(recv, 2, MonitorChipNameLength).TrimEnd('\0');
else
_monitorChipName = string.Empty;
}
// 面板名
if (!legacyRemapped)
{
Byte[] cmd = { MStarCommand, CmdGetPanelName };
Byte[] recv = MTKDebugCmd.DDC_Read(cmd, MonitorPanelNameLength + 2, 500)
?? MTKDebugCmd.DDC_Read(cmd, MonitorPanelNameLength + 2, 2000)
?? MTKDebugCmd.DDC_Read(cmd, MonitorPanelNameLength + 2, 5000);
if (recv != null && recv.Length >= MonitorPanelNameLength + 2)
_monitorPanelName = Encoding.ASCII.GetString(recv, 2, MonitorPanelNameLength).TrimEnd('\0');
else
_monitorPanelName = string.Empty;
}
// 板卡名
{
Byte[] cmd = { MStarCommand, CmdGetBoardName };
Byte[] recv = MTKDebugCmd.DDC_Read(cmd, MonitorBoardNameLength + 2, 500)
?? MTKDebugCmd.DDC_Read(cmd, MonitorBoardNameLength + 2, 2000)
?? MTKDebugCmd.DDC_Read(cmd, MonitorBoardNameLength + 2, 5000);
if (recv != null && recv.Length >= MonitorBoardNameLength + 2)
_monitorBoardName = Encoding.ASCII.GetString(recv, 2, MonitorBoardNameLength).TrimEnd('\0');
else
_monitorBoardName = string.Empty;
}
// 日志打印
WriteLog("MonitorModelName=" + _monitorModelName, "debug");
WriteLog("MonitorChipName=" + _monitorChipName, "debug");
WriteLog("MonitorPanelName=" + _monitorPanelName, "debug");
WriteLog("MonitorBoardName=" + _monitorBoardName, "debug");
}
catch (Exception ex)
{
WriteLog("QueryConnectedMonitorInfo Exception: " + ex.Message, "debug");
}
}
private void ClearConnectedMonitorInfo()
{
_monitorModelName = string.Empty;
_monitorChipName = string.Empty;
_monitorPanelName = string.Empty;
_monitorBoardName = string.Empty;
}
void Connect(int delayTime = 0)
{
SetStatusMsg("Connect MTK Monitor...");
@@ -357,7 +532,6 @@ namespace WinISP
// DDC2CI_SetR2Reset51Flag(0x01);
Byte chipType = 0;
IsConnect = false;
int retry = 0;
MTKDebugCmd.DDC_Write(buf);
//if (IsConnect)
{
@@ -365,11 +539,58 @@ namespace WinISP
btnRunDPISP.Enabled = true;
pnlConnState.BackColor = Color.LightGreen;
lblDisplayName.Text = ((GraphicCardI2CCtrl)_simI2cCtrl).GetMonitorName;
SetStatusMsg("Please select a F/W file.");
if (String.IsNullOrEmpty(_binFilePath))
SetStatusMsg("Please select a F/W file.");
else
SetStatusMsg("BIN loaded. Ready to upgrade.");
cboConnectedMonitor.Items.Clear();
String nameFromGPU = "";
List<String> list = ((GraphicCardI2CCtrl)_simI2cCtrl).InitConnectedMonitor;
WriteLog("InitConnectedMonitor count = " + list.Count, "debug");
if (list.Count == 0 && ((GraphicCardI2CCtrl)_simI2cCtrl).GetGraphicCardType == GraphicCardI2CCtrl.GRAPHIC_CARD.AMD)
{
WriteLog("InitConnectedMonitor = 0 on AMD auto-detect, trying forced NVIDIA controller ...", "debug");
((GraphicCardI2CCtrl)_simI2cCtrl).ReCreateGraphicCardCtrl(GraphicCardI2CCtrl.GPUTypes.NVIDIA);
WinIOLib.DelayMs(300);
if (_simI2cCtrl.Init())
{
list = ((GraphicCardI2CCtrl)_simI2cCtrl).InitConnectedMonitor;
WriteLog("InitConnectedMonitor after forced NVIDIA count = " + list.Count, "debug");
}
if (list.Count == 0)
{
WriteLog("Forced NVIDIA controller did not find monitors, restoring auto-detect controller ...", "debug");
((GraphicCardI2CCtrl)_simI2cCtrl).ReCreateGraphicCardCtrl();
WinIOLib.DelayMs(300);
if (_simI2cCtrl.Init())
list = ((GraphicCardI2CCtrl)_simI2cCtrl).InitConnectedMonitor;
}
}
// NVIDIA DP AUX channel may not be ready on first launch retry with delay.
{
int mntRetry = 0;
while (list.Count == 0 && mntRetry++ < 3)
{
WriteLog("InitConnectedMonitor = 0, waiting 1500ms before retry " + mntRetry + " ...", "debug");
WinIOLib.DelayMs(1500);
list = ((GraphicCardI2CCtrl)_simI2cCtrl).InitConnectedMonitor;
WriteLog("InitConnectedMonitor retry " + mntRetry + " count = " + list.Count, "debug");
}
// If all retries exhausted and still no monitor, recreate the GPU control and try once more.
if (list.Count == 0)
{
WriteLog("InitConnectedMonitor still 0 calling ReCreateGraphicCardCtrl ...", "debug");
((GraphicCardI2CCtrl)_simI2cCtrl).ReCreateGraphicCardCtrl();
WinIOLib.DelayMs(1500);
list = ((GraphicCardI2CCtrl)_simI2cCtrl).InitConnectedMonitor;
WriteLog("InitConnectedMonitor after ReCreate count = " + list.Count, "debug");
}
}
lblDisplayNumber.Text = list.Count.ToString();
if (list.Count > 0)
{
@@ -381,8 +602,9 @@ namespace WinISP
for (int idxDisp = 0; idxDisp < list.Count; idxDisp++)
{
int retry = 0; // Reset retry counter for each monitor index
nameFromGPU = list[idxDisp].ToUpper();
WriteLog("nameFromGPU = " + nameFromGPU, "debug");
WriteLog("nameFromGPU[" + idxDisp + "] = " + nameFromGPU, "debug");
cboConnectedMonitor.SelectedIndex = idxDisp;
((GraphicCardI2CCtrl)_simI2cCtrl).SetConnectedMonitorIndex((Byte)idxDisp);
@@ -390,6 +612,7 @@ namespace WinISP
{
IsConnect = DDC_CheckMTKDevice(ref chipType);
}
WriteLog("idxDisp=" + idxDisp + " IsConnect=" + IsConnect + " chipType=" + chipType, "debug");
if (IsConnect == true)
{
pnlConnState.BackColor = Color.LightGreen;
@@ -397,6 +620,19 @@ namespace WinISP
break;
}
}
// Intel IGCL and AMD can complete the FE handshake but still time out on optional
// identity queries during connect. Skip those reads here so connect stays usable.
if ((((GraphicCardI2CCtrl)_simI2cCtrl).GetGraphicCardType != GraphicCardI2CCtrl.GRAPHIC_CARD.INTEL)
&& (((GraphicCardI2CCtrl)_simI2cCtrl).GetGraphicCardType != GraphicCardI2CCtrl.GRAPHIC_CARD.INTEL_IGCL)
&& (((GraphicCardI2CCtrl)_simI2cCtrl).GetGraphicCardType != GraphicCardI2CCtrl.GRAPHIC_CARD.AMD))
{
QueryConnectedMonitorInfo();
}
else
{
ClearConnectedMonitorInfo();
WriteLog("Skip optional monitor identity query on AMD/Intel path.", "debug");
}
cboConnectedMonitor.SelectedIndexChanged += cboConnectedMonitor_SelectedIndexChanged;
cboConnectedMonitor.Enabled = true;
}
@@ -407,6 +643,7 @@ namespace WinISP
cboConnectedMonitor.Enabled = false;
btnRunDPISP.Enabled = false;
pnlConnState.BackColor = Color.Red;
ClearConnectedMonitorInfo();
SetStatusMsg("Current F/W version is not compatible with this tool.", true);
}
_chipType = chipType;
@@ -487,7 +724,15 @@ namespace WinISP
else
pnlConnState.BackColor = Color.Red;
SetStatusMsg("Ready");
if (IsConnect)
{
if (String.IsNullOrEmpty(_binFilePath))
SetStatusMsg("Please select a F/W file.");
else
SetStatusMsg("BIN loaded. Ready to upgrade.");
}
else
SetStatusMsg("Ready");
}
private void btnConnect_Click(object sender, EventArgs e)
@@ -527,8 +772,24 @@ namespace WinISP
flag = recv[2];
return flag;
}
private bool IsAmdOrIntelPath()
{
var gpuType = ((GraphicCardI2CCtrl)_simI2cCtrl).GetGraphicCardType;
return gpuType == GraphicCardI2CCtrl.GRAPHIC_CARD.AMD
|| gpuType == GraphicCardI2CCtrl.GRAPHIC_CARD.INTEL
|| gpuType == GraphicCardI2CCtrl.GRAPHIC_CARD.INTEL_IGCL;
}
private void DDC_SetToolFlag(bool en)
{
// AMD and Intel DDC paths do not support the tool-flag handshake command.
// Sending it causes repeated DDC timeout errors, so skip entirely.
if (IsAmdOrIntelPath())
{
frmISP.WriteLog("DDC_SetToolFlag skipped on AMD/Intel path.", "debug");
return;
}
Byte[] buf = { 0xCC, 0x90, 0x00 };
if (en)
buf[2] = 0x01;
@@ -537,7 +798,7 @@ namespace WinISP
WinIOLib.DelayMs(10);
int RetryCnt = 0;
while (RetryCnt <= 3)
while (RetryCnt <= 6)
{
if (Convert.ToBoolean(DDC2CI_GetToolFlag()) == en)
{
@@ -552,7 +813,9 @@ namespace WinISP
MTKDebugCmd.DDC_Write(buf);
}
if (RetryCnt > 0)
{
WriteLog("DDC_SetToolFlag fail.", "debug");
}
}
public static byte DDC2CI_GetR2Reset51Flag()
{
@@ -1022,6 +1285,7 @@ namespace WinISP
}
}
break;
case GraphicCardI2CCtrl.GRAPHIC_CARD.INTEL_IGCL:
case GraphicCardI2CCtrl.GRAPHIC_CARD.INTEL:
if (_IsHDMIConnect)
{
@@ -1167,6 +1431,8 @@ namespace WinISP
}
}
QueryConnectedMonitorInfo();
toolStripProgressBar1.Maximum = flashSectorInfo.Count;
toolStripProgressBar1.Value = 0;
int imgNum = 0;
@@ -1218,8 +1484,9 @@ namespace WinISP
if (!IsModelNameMatch(_u8ModelName))
{
SetStatusMsg(Properties.Resources.ModelNameErr);
SetISPStatus(false, Properties.Resources.ModelNameErr);
string modelErr = GetModelMismatchMessage(_u8ModelName);
SetStatusMsg(modelErr);
SetISPStatus(false, modelErr);
return;
}
if (!IsChipNameMatch(_u8ChipName))
@@ -1590,22 +1857,40 @@ namespace WinISP
}
private static string resultFolder = System.IO.Directory.GetCurrentDirectory() + "\\";
private static System.IO.StreamWriter _logWriter = null;
private static string _logPath = null;
private static readonly object _logLock = new object();
[Conditional("DEBUG")]
public static void WriteLog(string str, string fileName)
public static void WriteLog(string str, string level)
{
System.IO.StreamWriter file = null;
try
{
if (!System.IO.Directory.Exists(resultFolder))
System.IO.Directory.CreateDirectory(resultFolder);
if (!System.IO.Directory.Exists(resultFolder))
System.IO.Directory.CreateDirectory(resultFolder);
string path = resultFolder + (level == "" ? "" : level + "_") + DateTime.Now.ToString("yyyy-MM-dd") + ".log";
if (fileName == "")
file = new System.IO.StreamWriter(resultFolder + DateTime.Now.ToString("yyyy-MM-dd") + ".log", true);
else
file = new System.IO.StreamWriter(resultFolder + fileName + "_" + DateTime.Now.ToString("yyyy-MM-dd") + ".log", true);
file.WriteLine(DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss.fff: ") + str);
file.Close();
file = null;
lock (_logLock) // >>> 新增:同进程内串行化,避免自家多线程争用
{
if (_logWriter == null || _logPath != path)
{
if (_logWriter != null)
{
try { _logWriter.Flush(); _logWriter.Close(); } catch { }
}
_logPath = path;
var stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
_logWriter = new System.IO.StreamWriter(stream);
}
_logWriter.WriteLine(DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss.fff: ") + str);
_logWriter.Flush();
}
}
catch (Exception) // >>> 改动IOException → Exception吞掉一切日志异常
{
// 日志写入失败绝不能影响主流程。可选:降级写到 Debug 输出
try { System.Diagnostics.Debug.WriteLine("[LOG-FALLBACK] " + str); } catch { }
}
}
private void cboConnectedMonitor_SelectedIndexChanged(object sender, EventArgs e)
@@ -1623,11 +1908,22 @@ namespace WinISP
if (IsConnect == true)
{
pnlConnState.BackColor = Color.LightGreen;
if ((((GraphicCardI2CCtrl)_simI2cCtrl).GetGraphicCardType != GraphicCardI2CCtrl.GRAPHIC_CARD.INTEL)
&& (((GraphicCardI2CCtrl)_simI2cCtrl).GetGraphicCardType != GraphicCardI2CCtrl.GRAPHIC_CARD.INTEL_IGCL))
{
QueryConnectedMonitorInfo();
}
else
{
ClearConnectedMonitorInfo();
WriteLog("Skip optional monitor identity query on Intel path.", "debug");
}
}
else
{
pnlConnState.BackColor = Color.Red;
_chipType = 0;
ClearConnectedMonitorInfo();
}
_chipType = chipType;
@@ -1638,7 +1934,15 @@ namespace WinISP
case 2: { lblMTKChipType.Text = "MST9U"; } break;
}
Application.DoEvents();
DDC_GetVersion();
if ((((GraphicCardI2CCtrl)_simI2cCtrl).GetGraphicCardType != GraphicCardI2CCtrl.GRAPHIC_CARD.INTEL)
&& (((GraphicCardI2CCtrl)_simI2cCtrl).GetGraphicCardType != GraphicCardI2CCtrl.GRAPHIC_CARD.INTEL_IGCL))
{
DDC_GetVersion();
}
else
{
WriteLog("Skip optional firmware version query on Intel path.", "debug");
}
Application.DoEvents();
DDC_SetToolFlag(false);
lblConnectedPort.Text = ((GraphicCardI2CCtrl)_simI2cCtrl).GetConnectedPortTypeByIdx((Byte)cboConnectedMonitor.SelectedIndex).ToString();
@@ -1700,7 +2004,7 @@ namespace WinISP
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
if (offset > fs.Length - 1)
throw new ArgumentOutOfRangeException(nameof(offset), "Offset is beyond file length.");
throw new ArgumentOutOfRangeException("offset", "Offset is beyond file length.");
fs.Seek(offset, SeekOrigin.Begin);
int bytesRead = fs.Read(buffer, 0, length);