Compare commits

...

2 Commits

Author SHA1 Message Date
c39f688115 fix: mother board reactive problem 2025-05-16 16:38:57 +08:00
1eded97c76 fix: remote update failed and template not found 2025-05-15 20:23:48 +08:00
17 changed files with 1384 additions and 687 deletions

View File

@@ -20,9 +20,7 @@ update:
# 生成Restful API到网页客户端 # 生成Restful API到网页客户端
gen-api: gen-api:
cd server && dotnet run & npm run gen-api
npx nswag openapi2tsclient /input:http://localhost:5000/swagger/v1/swagger.json /output:src/APIClient.ts
pkill server
# 构建服务器包含win与linux平台 # 构建服务器包含win与linux平台
[working-directory: "server"] [working-directory: "server"]
@@ -32,8 +30,10 @@ build-server self-contained=isSelfContained: _show-dir
rsync -avz --delete ../wwwroot/ ./bin/Release/net9.0/linux-x64/publish/wwwroot/ rsync -avz --delete ../wwwroot/ ./bin/Release/net9.0/linux-x64/publish/wwwroot/
rsync -avz --delete ../wwwroot/ ./bin/Release/net9.0/win-x64/publish/wwwroot/ rsync -avz --delete ../wwwroot/ ./bin/Release/net9.0/win-x64/publish/wwwroot/
run: run-server
run-server: (build-server "true") run-server: (build-server "true")
exec ./server/bin/Release/net9.0/linux-x64/publish/server ./server/bin/Release/net9.0/linux-x64/publish/server
run-web: run-web:
npm run build npm run build

View File

@@ -9,7 +9,7 @@
"preview": "vite preview", "preview": "vite preview",
"build-only": "vite build", "build-only": "vite build",
"type-check": "vue-tsc --build", "type-check": "vue-tsc --build",
"pregen-api": "cd server && dotnet run &", "pregen-api": "cd server && dotnet run --property:Configuration=Release &",
"gen-api": "npx nswag openapi2tsclient /input:http://localhost:5000/swagger/v1/swagger.json /output:src/APIClient.ts", "gen-api": "npx nswag openapi2tsclient /input:http://localhost:5000/swagger/v1/swagger.json /output:src/APIClient.ts",
"postgen-api": "pkill server" "postgen-api": "pkill server"
}, },

View File

@@ -94,13 +94,31 @@ try
logger.Info($"Use Static Files : {Path.Combine(Directory.GetCurrentDirectory(), "wwwroot")}"); logger.Info($"Use Static Files : {Path.Combine(Directory.GetCurrentDirectory(), "wwwroot")}");
app.UseDefaultFiles(); app.UseDefaultFiles();
app.UseStaticFiles(); // Serves files from wwwroot by default app.UseStaticFiles(); // Serves files from wwwroot by default
// Assets Files
app.UseStaticFiles(new StaticFileOptions app.UseStaticFiles(new StaticFileOptions
{ {
FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "assets")), FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "assets")),
RequestPath = "/assets" RequestPath = "/assets"
}); });
// Public Files
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "EquipmentTemplates")),
RequestPath = "/public/EquipmentTemplates"
});
// Log Files
if (!Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), "log")))
{
Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), "log"));
}
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "log")),
RequestPath = "/log"
});
app.MapFallbackToFile("index.html"); app.MapFallbackToFile("index.html");
} }
// Add logs
app.UseHttpsRedirection(); app.UseHttpsRedirection();
app.UseRouting(); app.UseRouting();
app.UseCors(); app.UseCors();

View File

@@ -8,44 +8,6 @@ using WebProtocol;
namespace server.Controllers; namespace server.Controllers;
// /// <summary>
// /// [TODO:description]
// /// </summary>
// public class HomeController : ControllerBase
// {
// private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
//
// string INDEX_HTML_PATH = Path.Combine(Environment.CurrentDirectory, "index.html");
//
// /// <summary>
// /// [TODO:description]
// /// </summary>
// /// <returns>[TODO:return]</returns>
// [HttpGet("/")]
// public IResult Index()
// {
// return TypedResults.Content("Hello", "text/html");
// }
//
// // [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
// // public IResult Error()
// // {
// // return TypedResults.Ok();
// // }
//
// /// <summary>
// /// [TODO:description]
// /// </summary>
// /// <returns>[TODO:return]</returns>
// [HttpGet("/hello")]
// [HttpPost("/hello")]
// public IActionResult Hello()
// {
// string randomString = Guid.NewGuid().ToString();
// return this.Ok($"Hello World! GUID: {randomString}");
// }
// }
/// <summary> /// <summary>
/// UDP API /// UDP API
/// </summary> /// </summary>
@@ -524,9 +486,9 @@ public class RemoteUpdater : ControllerBase
/// <param name="bitstreamNum"> 比特流位号 </param> /// <param name="bitstreamNum"> 比特流位号 </param>
[HttpPost("DownloadBitstream")] [HttpPost("DownloadBitstream")]
[EnableCors("Users")] [EnableCors("Users")]
[ProducesResponseType(typeof(bool),StatusCodes.Status200OK)] [ProducesResponseType(typeof(bool), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ArgumentException),StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ArgumentException), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(Exception),StatusCodes.Status500InternalServerError)] [ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
public async ValueTask<IResult> UpdateBitstream(string address, int port, int bitstreamNum) public async ValueTask<IResult> UpdateBitstream(string address, int port, int bitstreamNum)
{ {
// 检查文件 // 检查文件
@@ -543,7 +505,7 @@ public class RemoteUpdater : ControllerBase
if (!fileBytes.IsSuccessful) return TypedResults.InternalServerError(fileBytes.Error); if (!fileBytes.IsSuccessful) return TypedResults.InternalServerError(fileBytes.Error);
// 下载比特流 // 下载比特流
var remoteUpdater = new RemoteUpdate.RemoteUpdateClient(address, port); var remoteUpdater = new RemoteUpdateClient.RemoteUpdater(address, port);
var ret = await remoteUpdater.UpdateBitstream(bitstreamNum, fileBytes.Value); var ret = await remoteUpdater.UpdateBitstream(bitstreamNum, fileBytes.Value);
if (ret.IsSuccessful) if (ret.IsSuccessful)
@@ -574,9 +536,9 @@ public class RemoteUpdater : ControllerBase
/// <returns>总共上传比特流的数量</returns> /// <returns>总共上传比特流的数量</returns>
[HttpPost("DownloadMultiBitstreams")] [HttpPost("DownloadMultiBitstreams")]
[EnableCors("Users")] [EnableCors("Users")]
[ProducesResponseType(typeof(int),StatusCodes.Status200OK)] [ProducesResponseType(typeof(int), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ArgumentException),StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ArgumentException), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(Exception),StatusCodes.Status500InternalServerError)] [ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
public async ValueTask<IResult> DownloadMultiBitstreams(string address, int port, int? bitstreamNum) public async ValueTask<IResult> DownloadMultiBitstreams(string address, int port, int? bitstreamNum)
{ {
// 检查文件 // 检查文件
@@ -603,7 +565,7 @@ public class RemoteUpdater : ControllerBase
} }
// 下载比特流 // 下载比特流
var remoteUpdater = new RemoteUpdate.RemoteUpdateClient(address, port); var remoteUpdater = new RemoteUpdateClient.RemoteUpdater(address, port);
{ {
var ret = await remoteUpdater.UploadBitstreams(bitstreams[0], bitstreams[1], bitstreams[2], bitstreams[3]); var ret = await remoteUpdater.UploadBitstreams(bitstreams[0], bitstreams[1], bitstreams[2], bitstreams[3]);
if (!ret.IsSuccessful) return TypedResults.InternalServerError(ret.Error); if (!ret.IsSuccessful) return TypedResults.InternalServerError(ret.Error);
@@ -634,12 +596,12 @@ public class RemoteUpdater : ControllerBase
/// <returns>操作结果</returns> /// <returns>操作结果</returns>
[HttpPost("HotResetBitstream")] [HttpPost("HotResetBitstream")]
[EnableCors("Users")] [EnableCors("Users")]
[ProducesResponseType(typeof(bool),StatusCodes.Status200OK)] [ProducesResponseType(typeof(bool), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ArgumentException),StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ArgumentException), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(Exception),StatusCodes.Status500InternalServerError)] [ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
public async ValueTask<IResult> HotResetBitstream(string address, int port, int bitstreamNum) public async ValueTask<IResult> HotResetBitstream(string address, int port, int bitstreamNum)
{ {
var remoteUpdater = new RemoteUpdate.RemoteUpdateClient(address, port); var remoteUpdater = new RemoteUpdateClient.RemoteUpdater(address, port);
var ret = await remoteUpdater.HotResetBitstream(bitstreamNum); var ret = await remoteUpdater.HotResetBitstream(bitstreamNum);
if (ret.IsSuccessful) if (ret.IsSuccessful)
@@ -662,12 +624,12 @@ public class RemoteUpdater : ControllerBase
/// <returns>[TODO:return]</returns> /// <returns>[TODO:return]</returns>
[HttpPost("GetFirmwareVersion")] [HttpPost("GetFirmwareVersion")]
[EnableCors("Users")] [EnableCors("Users")]
[ProducesResponseType(typeof(UInt32),StatusCodes.Status200OK)] [ProducesResponseType(typeof(UInt32), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ArgumentException),StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ArgumentException), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(Exception),StatusCodes.Status500InternalServerError)] [ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
public async ValueTask<IResult> GetFirmwareVersion(string address, int port) public async ValueTask<IResult> GetFirmwareVersion(string address, int port)
{ {
var remoteUpdater = new RemoteUpdate.RemoteUpdateClient(address, port); var remoteUpdater = new RemoteUpdateClient.RemoteUpdater(address, port);
var ret = await remoteUpdater.GetVersion(); var ret = await remoteUpdater.GetVersion();
if (ret.IsSuccessful) if (ret.IsSuccessful)
@@ -684,6 +646,110 @@ public class RemoteUpdater : ControllerBase
} }
/// <summary>
/// [TODO:description]
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class DDSController : ControllerBase
{
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
/// <summary>
/// [TODO:description]
/// </summary>
/// <param name="address">[TODO:parameter]</param>
/// <param name="port">[TODO:parameter]</param>
/// <param name="channelNum">[TODO:parameter]</param>
/// <param name="waveNum">[TODO:parameter]</param>
/// <returns>[TODO:return]</returns>
[HttpPost("SetWaveNum")]
[EnableCors("Users")]
[ProducesResponseType(typeof(bool), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ArgumentException), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
public async ValueTask<IResult> SetWaveNum(string address, int port, int channelNum, int waveNum)
{
var dds = new DDSClient.DDS(address, port);
var ret = await dds.SetWaveNum(channelNum, waveNum);
if (ret.IsSuccessful)
{
logger.Info($"Device {address} set output wave num successfully");
return TypedResults.Ok(ret.Value);
}
else
{
logger.Error(ret.Error);
return TypedResults.InternalServerError(ret.Error);
}
}
/// <summary>
/// [TODO:description]
/// </summary>
/// <param name="address">[TODO:parameter]</param>
/// <param name="port">[TODO:parameter]</param>
/// <param name="channelNum">[TODO:parameter]</param>
/// <param name="waveNum">[TODO:parameter]</param>
/// <param name="step">[TODO:parameter]</param>
/// <returns>[TODO:return]</returns>
[HttpPost("SetFreq")]
[EnableCors("Users")]
[ProducesResponseType(typeof(bool), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ArgumentException), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
public async ValueTask<IResult> SetFreq(string address, int port, int channelNum, int waveNum, UInt32 step)
{
var dds = new DDSClient.DDS(address, port);
var ret = await dds.SetFreq(channelNum, waveNum, step);
if (ret.IsSuccessful)
{
logger.Info($"Device {address} set output freqency successfully");
return TypedResults.Ok(ret.Value);
}
else
{
logger.Error(ret.Error);
return TypedResults.InternalServerError(ret.Error);
}
}
/// <summary>
/// [TODO:description]
/// </summary>
/// <param name="address">[TODO:parameter]</param>
/// <param name="port">[TODO:parameter]</param>
/// <param name="channelNum">[TODO:parameter]</param>
/// <param name="waveNum">[TODO:parameter]</param>
/// <param name="phase">[TODO:parameter]</param>
/// <returns>[TODO:return]</returns>
[HttpPost("SetPhase")]
[EnableCors("Users")]
[ProducesResponseType(typeof(bool), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ArgumentException), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
public async ValueTask<IResult> SetPhase(string address, int port, int channelNum, int waveNum, int phase)
{
var dds = new DDSClient.DDS(address, port);
var ret = await dds.SetPhase(channelNum, waveNum, phase);
if (ret.IsSuccessful)
{
logger.Info($"Device {address} set output phase successfully");
return TypedResults.Ok(ret.Value);
}
else
{
logger.Error(ret.Error);
return TypedResults.InternalServerError(ret.Error);
}
}
}
/// <summary> /// <summary>
/// 数据控制器 /// 数据控制器

170
server/src/DDSClient.cs Normal file
View File

@@ -0,0 +1,170 @@
using System.Net;
using DotNext;
namespace DDSClient;
static class DDSAddr
{
/*地址定义以2路输出4波形存储为例
00 R/W CHANNEL0 wave_sel
01 R/W CHANNEL0 STORE0 freq_ctrl
02 R/W CHANNEL0 STORE1 freq_ctrl
03 R/W CHANNEL0 STORE2 freq_ctrl
04 R/W CHANNEL0 STORE3 freq_ctrl
05 R/W CHANNEL0 STORE0 phase_ctrl
06 R/W CHANNEL0 STORE1 phase_ctrl
07 R/W CHANNEL0 STORE2 phase_ctrl
08 R/W CHANNEL0 STORE3 phase_ctrl
09 R/W CHANNEL0 dds_wr_enable
0A WO CHANNEL0 data
10 R/W CHANNEL1 wave_sel
11 R/W CHANNEL1 STORE0 freq_ctrl
12 R/W CHANNEL1 STORE1 freq_ctrl
13 R/W CHANNEL1 STORE2 freq_ctrl
14 R/W CHANNEL1 STORE3 freq_ctrl
15 R/W CHANNEL1 STORE0 phase_ctrl
16 R/W CHANNEL1 STORE1 phase_ctrl
17 R/W CHANNEL1 STORE2 phase_ctrl
18 R/W CHANNEL1 STORE3 phase_ctrl
19 R/W CHANNEL1 dds_wr_enable
1A WO CHANNEL1 data
*/
public const UInt32 Base = 0x4000_0000;
public static readonly ChannelAddr[] Channel = { new ChannelAddr(0x00), new ChannelAddr(0x10) };
public class ChannelAddr
{
private readonly UInt32 Offset;
public readonly UInt32 WaveSelect;
public readonly UInt32[] FreqCtrl;
public readonly UInt32[] PhaseCtrl;
public readonly UInt32 WriteEnable;
public readonly UInt32 WriteData;
public ChannelAddr(UInt32 offset)
{
this.Offset = offset;
this.WaveSelect = Base + Offset + 0x00;
this.FreqCtrl = new UInt32[]
{
Base + offset + 0x01,
Base + offset + 0x02,
Base + offset + 0x03,
Base + offset + 0x04
};
this.PhaseCtrl = new UInt32[] {
Base + Offset + 0x05,
Base + Offset + 0x06,
Base + Offset + 0x07,
Base + Offset + 0x08
};
this.WriteEnable = Base + Offset + 0x09;
this.WriteData = Base + Offset + 0x0A;
}
}
}
/// <summary>
/// [TODO:description]
/// </summary>
public class DDS
{
private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
readonly int timeout = 2000;
readonly int port;
readonly string address;
private IPEndPoint ep;
/// <summary>
/// [TODO:description]
/// </summary>
/// <param name="address">[TODO:parameter]</param>
/// <param name="port">[TODO:parameter]</param>
/// <param name="timeout">[TODO:parameter]</param>
/// <returns>[TODO:return]</returns>
public DDS(string address, int port, int timeout = 2000)
{
if (timeout < 0)
throw new ArgumentException("Timeout couldn't be negative", nameof(timeout));
this.address = address;
this.port = port;
this.ep = new IPEndPoint(IPAddress.Parse(address), port);
this.timeout = timeout;
}
/// <summary>
/// [TODO:description]
/// </summary>
/// <param name="channelNum">[TODO:parameter]</param>
/// <param name="waveNum">[TODO:parameter]</param>
/// <returns>[TODO:return]</returns>
public async ValueTask<Result<bool>> SetWaveNum(int channelNum, int waveNum)
{
if (channelNum < 0 || channelNum > 1) return new(new ArgumentException(
$"Channel number should be 0 ~ 1 instead of {channelNum}", nameof(channelNum)));
if (waveNum < 0 || waveNum > 3) return new(new ArgumentException(
$"Wave number should be 0 ~ 3 instead of {waveNum}", nameof(waveNum)));
await MsgBus.UDPServer.ClearUDPData(this.address);
logger.Trace("Clear udp data finished");
var ret = await UDPClientPool.WriteAddr(
this.ep, DDSAddr.Channel[channelNum].WaveSelect, (UInt32)waveNum, this.timeout);
if (!ret.IsSuccessful)
return new(ret.Error);
return ret.Value;
}
/// <summary>
/// [TODO:description]
/// </summary>
/// <param name="channelNum">[TODO:parameter]</param>
/// <param name="waveNum">[TODO:parameter]</param>
/// <param name="step">[TODO:parameter]</param>
/// <returns>[TODO:return]</returns>
public async ValueTask<Result<bool>> SetFreq(int channelNum, int waveNum, UInt32 step)
{
if (channelNum < 0 || channelNum > 1) return new(new ArgumentException(
$"Channel number should be 0 ~ 1 instead of {channelNum}", nameof(channelNum)));
if (waveNum < 0 || waveNum > 3) return new(new ArgumentException(
$"Wave number should be 0 ~ 3 instead of {waveNum}", nameof(waveNum)));
await MsgBus.UDPServer.ClearUDPData(this.address);
logger.Trace("Clear udp data finished");
var ret = await UDPClientPool.WriteAddr(
this.ep, DDSAddr.Channel[channelNum].FreqCtrl[waveNum], step, this.timeout);
if (!ret.IsSuccessful)
return new(ret.Error);
return ret.Value;
}
/// <summary>
/// [TODO:description]
/// </summary>
/// <param name="channelNum">[TODO:parameter]</param>
/// <param name="waveNum">[TODO:parameter]</param>
/// <param name="phase">[TODO:parameter]</param>
/// <returns>[TODO:return]</returns>
public async ValueTask<Result<bool>> SetPhase(int channelNum, int waveNum, int phase)
{
if (channelNum < 0 || channelNum > 1) return new(new ArgumentException(
$"Channel number should be 0 ~ 1 instead of {channelNum}", nameof(channelNum)));
if (waveNum < 0 || waveNum > 3) return new(new ArgumentException(
$"Wave number should be 0 ~ 3 instead of {waveNum}", nameof(waveNum)));
if (phase < 0 || phase > 4096) return new(new ArgumentException(
$"Phase should be 0 ~ 4096 instead of {phase}", nameof(phase)));
await MsgBus.UDPServer.ClearUDPData(this.address);
logger.Trace("Clear udp data finished");
var ret = await UDPClientPool.WriteAddr(
this.ep, DDSAddr.Channel[channelNum].PhaseCtrl[waveNum], (UInt32)phase, this.timeout);
if (!ret.IsSuccessful)
return new(ret.Error);
return ret.Value;
}
}

View File

@@ -1,8 +1,8 @@
using System.Net; using System.Net;
using DotNext; using DotNext;
namespace RemoteUpdate; namespace RemoteUpdateClient;
static class RemoteUpdateClientAddr static class RemoteUpdaterAddr
{ {
public const UInt32 Base = 0x20_00_00_00; public const UInt32 Base = 0x20_00_00_00;
@@ -91,7 +91,7 @@ static class FlashAddr
/// <summary> /// <summary>
/// [TODO:description] /// [TODO:description]
/// </summary> /// </summary>
public class RemoteUpdateClient public class RemoteUpdater
{ {
private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger(); private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
@@ -112,7 +112,7 @@ public class RemoteUpdateClient
/// <param name="timeout">[TODO:parameter]</param> /// <param name="timeout">[TODO:parameter]</param>
/// <param name="timeoutForWait">[TODO:parameter]</param> /// <param name="timeoutForWait">[TODO:parameter]</param>
/// <returns>[TODO:return]</returns> /// <returns>[TODO:return]</returns>
public RemoteUpdateClient(string address, int port, int timeout = 2000, int timeoutForWait = 60 * 1000) public RemoteUpdater(string address, int port, int timeout = 2000, int timeoutForWait = 60 * 1000)
{ {
if (timeout < 0) if (timeout < 0)
throw new ArgumentException("Timeout couldn't be negative", nameof(timeout)); throw new ArgumentException("Timeout couldn't be negative", nameof(timeout));
@@ -142,7 +142,7 @@ public class RemoteUpdateClient
{ {
var ret = await UDPClientPool.WriteAddr( var ret = await UDPClientPool.WriteAddr(
this.ep, RemoteUpdateClientAddr.WriteCtrl, this.ep, RemoteUpdaterAddr.WriteCtrl,
Convert.ToUInt32((writeSectorNum << 16) | (1 << 15) | Convert.ToInt32(flashAddr / 4096)), this.timeout); Convert.ToUInt32((writeSectorNum << 16) | (1 << 15) | Convert.ToInt32(flashAddr / 4096)), this.timeout);
if (!ret.IsSuccessful) return new(ret.Error); if (!ret.IsSuccessful) return new(ret.Error);
if (!ret.Value) return new(new Exception("Enable write flash failed")); if (!ret.Value) return new(new Exception("Enable write flash failed"));
@@ -150,7 +150,7 @@ public class RemoteUpdateClient
{ {
var ret = await UDPClientPool.ReadAddrWithWait( var ret = await UDPClientPool.ReadAddrWithWait(
this.ep, RemoteUpdateClientAddr.WriteSign, this.ep, RemoteUpdaterAddr.WriteSign,
0x00_00_00_01, 0x00_00_00_01, this.timeoutForWait); 0x00_00_00_01, 0x00_00_00_01, this.timeoutForWait);
if (!ret.IsSuccessful) return new(ret.Error); if (!ret.IsSuccessful) return new(ret.Error);
if (!ret.Value) return new(new Exception( if (!ret.Value) return new(new Exception(
@@ -158,14 +158,14 @@ public class RemoteUpdateClient
} }
{ {
var ret = await UDPClientPool.WriteAddr(this.ep, RemoteUpdateClientAddr.WriteFIFO, bytesData, this.timeout); var ret = await UDPClientPool.WriteAddr(this.ep, RemoteUpdaterAddr.WriteFIFO, bytesData, this.timeout);
if (!ret.IsSuccessful) return new(ret.Error); if (!ret.IsSuccessful) return new(ret.Error);
if (!ret.Value) return new(new Exception("Send data to flash failed")); if (!ret.Value) return new(new Exception("Send data to flash failed"));
} }
{ {
var ret = await UDPClientPool.ReadAddrWithWait( var ret = await UDPClientPool.ReadAddrWithWait(
this.ep, RemoteUpdateClientAddr.WriteSign, this.ep, RemoteUpdaterAddr.WriteSign,
0x00_00_01_00, 0x00_00_01_00, this.timeoutForWait); 0x00_00_01_00, 0x00_00_01_00, this.timeoutForWait);
if (!ret.IsSuccessful) return new(ret.Error); if (!ret.IsSuccessful) return new(ret.Error);
return ret.Value; return ret.Value;
@@ -314,14 +314,14 @@ public class RemoteUpdateClient
private async ValueTask<Result<bool>> CheckBitstreamCRC(int bitstreamNum, int bitstreamLen, UInt32 checkSum) private async ValueTask<Result<bool>> CheckBitstreamCRC(int bitstreamNum, int bitstreamLen, UInt32 checkSum)
{ {
{ {
var ret = await UDPClientPool.WriteAddr(this.ep, RemoteUpdateClientAddr.ReadCtrl2, 0x00_00_00_00, this.timeout); var ret = await UDPClientPool.WriteAddr(this.ep, RemoteUpdaterAddr.ReadCtrl2, 0x00_00_00_00, this.timeout);
if (!ret.IsSuccessful) return new(ret.Error); if (!ret.IsSuccessful) return new(ret.Error);
if (!ret.Value) return new(new Exception("Write read control 2 failed")); if (!ret.Value) return new(new Exception("Write read control 2 failed"));
} }
{ {
var ret = await UDPClientPool.WriteAddr( var ret = await UDPClientPool.WriteAddr(
this.ep, RemoteUpdateClientAddr.ReadCtrl1, this.ep, RemoteUpdaterAddr.ReadCtrl1,
Convert.ToUInt32((bitstreamLen << 16) | (1 << 15) | Convert.ToInt32(FlashAddr.Bitstream[bitstreamNum] / 4096)), Convert.ToUInt32((bitstreamLen << 16) | (1 << 15) | Convert.ToInt32(FlashAddr.Bitstream[bitstreamNum] / 4096)),
this.timeout); this.timeout);
if (!ret.IsSuccessful) return new(ret.Error); if (!ret.IsSuccessful) return new(ret.Error);
@@ -330,7 +330,7 @@ public class RemoteUpdateClient
{ {
var ret = await UDPClientPool.ReadAddrWithWait( var ret = await UDPClientPool.ReadAddrWithWait(
this.ep, RemoteUpdateClientAddr.ReadSign, this.ep, RemoteUpdaterAddr.ReadSign,
0x00_00_01_00, 0x00_00_01_00, this.timeoutForWait); 0x00_00_01_00, 0x00_00_01_00, this.timeoutForWait);
if (!ret.IsSuccessful) return new(ret.Error); if (!ret.IsSuccessful) return new(ret.Error);
if (!ret.Value) return new(new Exception( if (!ret.Value) return new(new Exception(
@@ -338,7 +338,7 @@ public class RemoteUpdateClient
} }
{ {
var ret = await UDPClientPool.ReadAddr(this.ep, RemoteUpdateClientAddr.ReadCRC, this.timeout); var ret = await UDPClientPool.ReadAddr(this.ep, RemoteUpdaterAddr.ReadCRC, this.timeout);
if (!ret.IsSuccessful) return new(ret.Error); if (!ret.IsSuccessful) return new(ret.Error);
var bytes = ret.Value.Options.Data; var bytes = ret.Value.Options.Data;
@@ -368,7 +368,7 @@ public class RemoteUpdateClient
$"Bitsteam num should be 0 ~ 3 for HotRest, but given {bitstreamNum}", nameof(bitstreamNum))); $"Bitsteam num should be 0 ~ 3 for HotRest, but given {bitstreamNum}", nameof(bitstreamNum)));
var ret = await UDPClientPool.WriteAddr( var ret = await UDPClientPool.WriteAddr(
this.ep, RemoteUpdateClientAddr.HotResetCtrl, this.ep, RemoteUpdaterAddr.HotResetCtrl,
((FlashAddr.Bitstream[bitstreamNum] << 8) | 1), this.timeout); ((FlashAddr.Bitstream[bitstreamNum] << 8) | 1), this.timeout);
if (!ret.IsSuccessful) return new(ret.Error); if (!ret.IsSuccessful) return new(ret.Error);
return ret.Value; return ret.Value;
@@ -542,7 +542,7 @@ public class RemoteUpdateClient
logger.Trace("Clear udp data finished"); logger.Trace("Clear udp data finished");
{ {
var ret = await UDPClientPool.ReadAddr(this.ep, RemoteUpdateClientAddr.Version, this.timeout); var ret = await UDPClientPool.ReadAddr(this.ep, RemoteUpdaterAddr.Version, this.timeout);
if (!ret.IsSuccessful) return new(ret.Error); if (!ret.IsSuccessful) return new(ret.Error);
var retData = ret.Value.Options.Data; var retData = ret.Value.Options.Data;

View File

@@ -1000,6 +1000,246 @@ export class RemoteUpdaterClient {
} }
} }
export class DDSClient {
private http: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> };
private baseUrl: string;
protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;
constructor(baseUrl?: string, http?: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> }) {
this.http = http ? http : window as any;
this.baseUrl = baseUrl ?? "http://localhost:5000";
}
/**
* [TODO:description]
* @param address (optional) [TODO:parameter]
* @param port (optional) [TODO:parameter]
* @param channelNum (optional) [TODO:parameter]
* @param waveNum (optional) [TODO:parameter]
* @return [TODO:return]
*/
setWaveNum(address: string | undefined, port: number | undefined, channelNum: number | undefined, waveNum: number | undefined): Promise<boolean> {
let url_ = this.baseUrl + "/api/DDS/SetWaveNum?";
if (address === null)
throw new Error("The parameter 'address' cannot be null.");
else if (address !== undefined)
url_ += "address=" + encodeURIComponent("" + address) + "&";
if (port === null)
throw new Error("The parameter 'port' cannot be null.");
else if (port !== undefined)
url_ += "port=" + encodeURIComponent("" + port) + "&";
if (channelNum === null)
throw new Error("The parameter 'channelNum' cannot be null.");
else if (channelNum !== undefined)
url_ += "channelNum=" + encodeURIComponent("" + channelNum) + "&";
if (waveNum === null)
throw new Error("The parameter 'waveNum' cannot be null.");
else if (waveNum !== undefined)
url_ += "waveNum=" + encodeURIComponent("" + waveNum) + "&";
url_ = url_.replace(/[?&]$/, "");
let options_: RequestInit = {
method: "POST",
headers: {
"Accept": "application/json"
}
};
return this.http.fetch(url_, options_).then((_response: Response) => {
return this.processSetWaveNum(_response);
});
}
protected processSetWaveNum(response: Response): Promise<boolean> {
const status = response.status;
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
if (status === 200) {
return response.text().then((_responseText) => {
let result200: any = null;
let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result200 = resultData200 !== undefined ? resultData200 : <any>null;
return result200;
});
} else if (status === 400) {
return response.text().then((_responseText) => {
let result400: any = null;
let resultData400 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result400 = ArgumentException.fromJS(resultData400);
return throwException("A server side error occurred.", status, _responseText, _headers, result400);
});
} else if (status === 500) {
return response.text().then((_responseText) => {
let result500: any = null;
let resultData500 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result500 = Exception.fromJS(resultData500);
return throwException("A server side error occurred.", status, _responseText, _headers, result500);
});
} else if (status !== 200 && status !== 204) {
return response.text().then((_responseText) => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
});
}
return Promise.resolve<boolean>(null as any);
}
/**
* [TODO:description]
* @param address (optional) [TODO:parameter]
* @param port (optional) [TODO:parameter]
* @param channelNum (optional) [TODO:parameter]
* @param waveNum (optional) [TODO:parameter]
* @param step (optional) [TODO:parameter]
* @return [TODO:return]
*/
setFreq(address: string | undefined, port: number | undefined, channelNum: number | undefined, waveNum: number | undefined, step: number | undefined): Promise<boolean> {
let url_ = this.baseUrl + "/api/DDS/SetFreq?";
if (address === null)
throw new Error("The parameter 'address' cannot be null.");
else if (address !== undefined)
url_ += "address=" + encodeURIComponent("" + address) + "&";
if (port === null)
throw new Error("The parameter 'port' cannot be null.");
else if (port !== undefined)
url_ += "port=" + encodeURIComponent("" + port) + "&";
if (channelNum === null)
throw new Error("The parameter 'channelNum' cannot be null.");
else if (channelNum !== undefined)
url_ += "channelNum=" + encodeURIComponent("" + channelNum) + "&";
if (waveNum === null)
throw new Error("The parameter 'waveNum' cannot be null.");
else if (waveNum !== undefined)
url_ += "waveNum=" + encodeURIComponent("" + waveNum) + "&";
if (step === null)
throw new Error("The parameter 'step' cannot be null.");
else if (step !== undefined)
url_ += "step=" + encodeURIComponent("" + step) + "&";
url_ = url_.replace(/[?&]$/, "");
let options_: RequestInit = {
method: "POST",
headers: {
"Accept": "application/json"
}
};
return this.http.fetch(url_, options_).then((_response: Response) => {
return this.processSetFreq(_response);
});
}
protected processSetFreq(response: Response): Promise<boolean> {
const status = response.status;
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
if (status === 200) {
return response.text().then((_responseText) => {
let result200: any = null;
let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result200 = resultData200 !== undefined ? resultData200 : <any>null;
return result200;
});
} else if (status === 400) {
return response.text().then((_responseText) => {
let result400: any = null;
let resultData400 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result400 = ArgumentException.fromJS(resultData400);
return throwException("A server side error occurred.", status, _responseText, _headers, result400);
});
} else if (status === 500) {
return response.text().then((_responseText) => {
let result500: any = null;
let resultData500 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result500 = Exception.fromJS(resultData500);
return throwException("A server side error occurred.", status, _responseText, _headers, result500);
});
} else if (status !== 200 && status !== 204) {
return response.text().then((_responseText) => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
});
}
return Promise.resolve<boolean>(null as any);
}
/**
* [TODO:description]
* @param address (optional) [TODO:parameter]
* @param port (optional) [TODO:parameter]
* @param channelNum (optional) [TODO:parameter]
* @param waveNum (optional) [TODO:parameter]
* @param phase (optional) [TODO:parameter]
* @return [TODO:return]
*/
setPhase(address: string | undefined, port: number | undefined, channelNum: number | undefined, waveNum: number | undefined, phase: number | undefined): Promise<boolean> {
let url_ = this.baseUrl + "/api/DDS/SetPhase?";
if (address === null)
throw new Error("The parameter 'address' cannot be null.");
else if (address !== undefined)
url_ += "address=" + encodeURIComponent("" + address) + "&";
if (port === null)
throw new Error("The parameter 'port' cannot be null.");
else if (port !== undefined)
url_ += "port=" + encodeURIComponent("" + port) + "&";
if (channelNum === null)
throw new Error("The parameter 'channelNum' cannot be null.");
else if (channelNum !== undefined)
url_ += "channelNum=" + encodeURIComponent("" + channelNum) + "&";
if (waveNum === null)
throw new Error("The parameter 'waveNum' cannot be null.");
else if (waveNum !== undefined)
url_ += "waveNum=" + encodeURIComponent("" + waveNum) + "&";
if (phase === null)
throw new Error("The parameter 'phase' cannot be null.");
else if (phase !== undefined)
url_ += "phase=" + encodeURIComponent("" + phase) + "&";
url_ = url_.replace(/[?&]$/, "");
let options_: RequestInit = {
method: "POST",
headers: {
"Accept": "application/json"
}
};
return this.http.fetch(url_, options_).then((_response: Response) => {
return this.processSetPhase(_response);
});
}
protected processSetPhase(response: Response): Promise<boolean> {
const status = response.status;
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
if (status === 200) {
return response.text().then((_responseText) => {
let result200: any = null;
let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result200 = resultData200 !== undefined ? resultData200 : <any>null;
return result200;
});
} else if (status === 400) {
return response.text().then((_responseText) => {
let result400: any = null;
let resultData400 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result400 = ArgumentException.fromJS(resultData400);
return throwException("A server side error occurred.", status, _responseText, _headers, result400);
});
} else if (status === 500) {
return response.text().then((_responseText) => {
let result500: any = null;
let resultData500 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result500 = Exception.fromJS(resultData500);
return throwException("A server side error occurred.", status, _responseText, _headers, result500);
});
} else if (status !== 200 && status !== 204) {
return response.text().then((_responseText) => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
});
}
return Promise.resolve<boolean>(null as any);
}
}
export class DataClient { export class DataClient {
private http: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> }; private http: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> };
private baseUrl: string; private baseUrl: string;
@@ -1394,7 +1634,6 @@ export interface ISystemException extends IException {
} }
export class ArgumentException extends SystemException implements IArgumentException { export class ArgumentException extends SystemException implements IArgumentException {
message?: string;
paramName?: string | undefined; paramName?: string | undefined;
constructor(data?: IArgumentException) { constructor(data?: IArgumentException) {

View File

@@ -5,10 +5,13 @@
<input id="component-drawer" type="checkbox" class="drawer-toggle" v-model="showComponentsMenu" /> <input id="component-drawer" type="checkbox" class="drawer-toggle" v-model="showComponentsMenu" />
<div class="drawer-side"> <div class="drawer-side">
<label for="component-drawer" aria-label="close sidebar" class="drawer-overlay !bg-opacity-50"></label> <label for="component-drawer" aria-label="close sidebar" class="drawer-overlay !bg-opacity-50"></label>
<div class="menu p-0 w-[460px] min-h-full bg-base-100 shadow-xl flex flex-col"> <!-- 菜单头部 --> <div class="menu p-0 w-[460px] min-h-full bg-base-100 shadow-xl flex flex-col">
<!-- 菜单头部 -->
<div class="p-6 border-b border-base-300 flex justify-between items-center"> <div class="p-6 border-b border-base-300 flex justify-between items-center">
<h3 class="text-xl font-bold text-primary flex items-center gap-2"> <h3 class="text-xl font-bold text-primary flex items-center gap-2">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-primary"> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
class="text-primary">
<circle cx="12" cy="12" r="10"></circle> <circle cx="12" cy="12" r="10"></circle>
<path d="M12 8v8"></path> <path d="M12 8v8"></path>
<path d="M8 12h8"></path> <path d="M8 12h8"></path>
@@ -16,7 +19,8 @@
添加元器件 添加元器件
</h3> </h3>
<label for="component-drawer" class="btn btn-ghost btn-sm btn-circle" @click="closeMenu"> <label for="component-drawer" class="btn btn-ghost btn-sm btn-circle" @click="closeMenu">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="18" y1="6" x2="6" y2="18"></line> <line x1="18" y1="6" x2="6" y2="18"></line>
<line x1="6" y1="6" x2="18" y2="18"></line> <line x1="6" y1="6" x2="18" y2="18"></line>
</svg> </svg>
@@ -25,7 +29,8 @@
<!-- 导航栏 --> <!-- 导航栏 -->
<div class="tabs tabs-boxed bg-base-200 mx-6 mt-4 rounded-box"> <div class="tabs tabs-boxed bg-base-200 mx-6 mt-4 rounded-box">
<a class="tab" :class="{ 'tab-active': activeTab === 'components' }" @click="activeTab = 'components'">元器件</a> <a class="tab" :class="{ 'tab-active': activeTab === 'components' }"
@click="activeTab = 'components'">元器件</a>
<a class="tab" :class="{ 'tab-active': activeTab === 'templates' }" @click="activeTab = 'templates'">模板</a> <a class="tab" :class="{ 'tab-active': activeTab === 'templates' }" @click="activeTab = 'templates'">模板</a>
<a class="tab" :class="{ 'tab-active': activeTab === 'virtual' }" @click="activeTab = 'virtual'">虚拟外设</a> <a class="tab" :class="{ 'tab-active': activeTab === 'virtual' }" @click="activeTab = 'virtual'">虚拟外设</a>
</div> </div>
@@ -34,19 +39,18 @@
<div class="px-6 py-4 border-b border-base-300"> <div class="px-6 py-4 border-b border-base-300">
<div class="join w-full"> <div class="join w-full">
<div class="join-item flex-1 relative"> <div class="join-item flex-1 relative">
<input <input type="text" placeholder="搜索..." class="input input-bordered input-sm w-full pl-10"
type="text" v-model="searchQuery" @keyup.enter="searchComponents" />
placeholder="搜索..." <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none"
class="input input-bordered input-sm w-full pl-10" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
v-model="searchQuery" class="absolute left-3 top-1/2 -translate-y-1/2 text-base-content opacity-60">
@keyup.enter="searchComponents"
/>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="absolute left-3 top-1/2 -translate-y-1/2 text-base-content opacity-60">
<circle cx="11" cy="11" r="8"></circle> <circle cx="11" cy="11" r="8"></circle>
<line x1="21" y1="21" x2="16.65" y2="16.65"></line> <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
</svg> </svg>
</div> </div>
<button class="btn btn-sm join-item" @click="searchComponents">搜索</button> <button class="btn btn-sm join-item" @click="searchComponents">
搜索
</button>
</div> </div>
</div> </div>
@@ -54,17 +58,14 @@
<div v-if="activeTab === 'components'" class="px-6 py-4 overflow-auto flex-1"> <div v-if="activeTab === 'components'" class="px-6 py-4 overflow-auto flex-1">
<div v-if="filteredComponents.length > 0" class="grid grid-cols-2 gap-4"> <div v-if="filteredComponents.length > 0" class="grid grid-cols-2 gap-4">
<div v-for="(component, index) in filteredComponents" :key="index" <div v-for="(component, index) in filteredComponents" :key="index"
class="card bg-base-200 hover:bg-base-300 transition-all duration-300 hover:shadow-md cursor-pointer" class="card bg-base-200 hover:bg-base-300 transition-all duration-300 hover:shadow-md cursor-pointer"
@click="addComponent(component)"> @click="addComponent(component)">
<div class="card-body p-3 items-center text-center"> <div class="card-body p-3 items-center text-center">
<div class="bg-base-100 rounded-lg w-full h-[90px] flex items-center justify-center overflow-hidden p-2"> <div
class="bg-base-100 rounded-lg w-full h-[90px] flex items-center justify-center overflow-hidden p-2">
<!-- 直接使用组件作为预览 --> <!-- 直接使用组件作为预览 -->
<component <component v-if="componentModules[component.type]" :is="componentModules[component.type].default"
v-if="componentModules[component.type]" class="component-preview" :size="getPreviewSize(component.type)" />
:is="componentModules[component.type].default"
class="component-preview"
:size="getPreviewSize(component.type)"
/>
<!-- 加载中状态 --> <!-- 加载中状态 -->
<span v-else class="text-xs text-gray-400">加载中...</span> <span v-else class="text-xs text-gray-400">加载中...</span>
</div> </div>
@@ -75,7 +76,9 @@
</div> </div>
<!-- 无搜索结果 --> <!-- 无搜索结果 -->
<div v-else class="py-16 text-center"> <div v-else class="py-16 text-center">
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="mx-auto text-base-300 mb-3"> <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"
class="mx-auto text-base-300 mb-3">
<circle cx="11" cy="11" r="8"></circle> <circle cx="11" cy="11" r="8"></circle>
<line x1="21" y1="21" x2="16.65" y2="16.65"></line> <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
<line x1="8" y1="11" x2="14" y2="11"></line> <line x1="8" y1="11" x2="14" y2="11"></line>
@@ -91,20 +94,26 @@
<div v-if="activeTab === 'templates'" class="px-6 py-4 overflow-auto flex-1"> <div v-if="activeTab === 'templates'" class="px-6 py-4 overflow-auto flex-1">
<div v-if="filteredTemplates.length > 0" class="grid grid-cols-2 gap-4"> <div v-if="filteredTemplates.length > 0" class="grid grid-cols-2 gap-4">
<div v-for="(template, index) in filteredTemplates" :key="index" <div v-for="(template, index) in filteredTemplates" :key="index"
class="card bg-base-200 hover:bg-base-300 transition-all duration-300 hover:shadow-md cursor-pointer" class="card bg-base-200 hover:bg-base-300 transition-all duration-300 hover:shadow-md cursor-pointer"
@click="addTemplate(template)"> @click="addTemplate(template)">
<div class="card-body p-3 items-center text-center"> <div class="card-body p-3 items-center text-center">
<div class="bg-base-100 rounded-lg w-full h-[90px] flex items-center justify-center overflow-hidden p-2"> <div
<img :src="template.thumbnailUrl || '/placeholder-template.png'" alt="Template thumbnail" class="max-h-full max-w-full object-contain" /> class="bg-base-100 rounded-lg w-full h-[90px] flex items-center justify-center overflow-hidden p-2">
<img :src="template.thumbnailUrl || '/placeholder-template.png'
" alt="Template thumbnail" class="max-h-full max-w-full object-contain" />
</div> </div>
<h3 class="card-title text-sm mt-2">{{ template.name }}</h3> <h3 class="card-title text-sm mt-2">{{ template.name }}</h3>
<p class="text-xs opacity-70">{{ template.description || '模板' }}</p> <p class="text-xs opacity-70">
{{ template.description || "模板" }}
</p>
</div> </div>
</div> </div>
</div> </div>
<!-- 无搜索结果 --> <!-- 无搜索结果 -->
<div v-else class="py-16 text-center"> <div v-else class="py-16 text-center">
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="mx-auto text-base-300 mb-3"> <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"
class="mx-auto text-base-300 mb-3">
<circle cx="11" cy="11" r="8"></circle> <circle cx="11" cy="11" r="8"></circle>
<line x1="21" y1="21" x2="16.65" y2="16.65"></line> <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
<line x1="8" y1="11" x2="14" y2="11"></line> <line x1="8" y1="11" x2="14" y2="11"></line>
@@ -115,21 +124,18 @@
</button> </button>
</div> </div>
</div> </div>
<!-- 虚拟外设列表 (虚拟外设选项卡) --> <!-- 虚拟外设列表 (虚拟外设选项卡) -->
<div v-if="activeTab === 'virtual'" class="px-6 py-4 overflow-auto flex-1"> <div v-if="activeTab === 'virtual'" class="px-6 py-4 overflow-auto flex-1">
<div v-if="filteredVirtualDevices.length > 0" class="grid grid-cols-2 gap-4"> <div v-if="filteredVirtualDevices.length > 0" class="grid grid-cols-2 gap-4">
<div v-for="(device, index) in filteredVirtualDevices" :key="index" <div v-for="(device, index) in filteredVirtualDevices" :key="index"
class="card bg-base-200 hover:bg-base-300 transition-all duration-300 hover:shadow-md cursor-pointer" class="card bg-base-200 hover:bg-base-300 transition-all duration-300 hover:shadow-md cursor-pointer"
@click="addComponent(device)"> @click="addComponent(device)">
<div class="card-body p-3 items-center text-center"> <div class="card-body p-3 items-center text-center">
<div class="bg-base-100 rounded-lg w-full h-[90px] flex items-center justify-center overflow-hidden p-2"> <div
class="bg-base-100 rounded-lg w-full h-[90px] flex items-center justify-center overflow-hidden p-2">
<!-- 直接使用组件作为预览 --> <!-- 直接使用组件作为预览 -->
<component <component v-if="componentModules[device.type]" :is="componentModules[device.type].default"
v-if="componentModules[device.type]" class="component-preview" :size="getPreviewSize(device.type)" />
:is="componentModules[device.type].default"
class="component-preview"
:size="getPreviewSize(device.type)"
/>
<!-- 加载中状态 --> <!-- 加载中状态 -->
<span v-else class="text-xs text-gray-400">加载中...</span> <span v-else class="text-xs text-gray-400">加载中...</span>
</div> </div>
@@ -140,7 +146,9 @@
</div> </div>
<!-- 无搜索结果 --> <!-- 无搜索结果 -->
<div v-else class="py-16 text-center"> <div v-else class="py-16 text-center">
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="mx-auto text-base-300 mb-3"> <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"
class="mx-auto text-base-300 mb-3">
<circle cx="11" cy="11" r="8"></circle> <circle cx="11" cy="11" r="8"></circle>
<line x1="21" y1="21" x2="16.65" y2="16.65"></line> <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
<line x1="8" y1="11" x2="14" y2="11"></line> <line x1="8" y1="11" x2="14" y2="11"></line>
@@ -155,7 +163,8 @@
<!-- 底部操作区 --> <!-- 底部操作区 -->
<div class="p-4 border-t border-base-300 bg-base-200 flex justify-between"> <div class="p-4 border-t border-base-300 bg-base-200 flex justify-between">
<label for="component-drawer" class="btn btn-sm btn-ghost" @click="closeMenu"> <label for="component-drawer" class="btn btn-sm btn-ghost" @click="closeMenu">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="mr-1"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="mr-1">
<path d="M19 12H5M12 19l-7-7 7-7"></path> <path d="M19 12H5M12 19l-7-7 7-7"></path>
</svg> </svg>
返回 返回
@@ -171,7 +180,8 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { ref, computed, shallowRef, onMounted } from 'vue'; import { ref, computed, shallowRef, onMounted } from "vue";
import motherboardSvg from "../components/equipments/svg/motherboard.svg";
// Props 定义 // Props 定义
interface Props { interface Props {
@@ -181,51 +191,54 @@ interface Props {
const props = defineProps<Props>(); const props = defineProps<Props>();
// 定义组件发出的事件 // 定义组件发出的事件
const emit = defineEmits(['close', 'add-component', 'add-template', 'update:open']); const emit = defineEmits([
"close",
"add-component",
"add-template",
"update:open",
]);
// 当前激活的选项卡 // 当前激活的选项卡
const activeTab = ref('components'); const activeTab = ref("components");
// --- 搜索功能 --- // --- 搜索功能 ---
const searchQuery = ref(''); const searchQuery = ref("");
// --- 可用元器件列表 --- // --- 可用元器件列表 ---
const availableComponents = [ const availableComponents = [
{ type: 'MechanicalButton', name: '机械按钮' }, { type: "MechanicalButton", name: "机械按钮" },
{ type: 'Switch', name: '开关' }, { type: "Switch", name: "开关" },
{ type: 'Pin', name: '引脚' }, { type: "Pin", name: "引脚" },
{ type: 'SMT_LED', name: '贴片LED' }, { type: "SMT_LED", name: "贴片LED" },
{ type: 'SevenSegmentDisplay', name: '数码管' }, { type: "SevenSegmentDisplay", name: "数码管" },
{ type: 'HDMI', name: 'HDMI接口' }, { type: "HDMI", name: "HDMI接口" },
{ type: 'DDR', name: 'DDR内存' }, { type: "DDR", name: "DDR内存" },
{ type: 'ETH', name: '以太网接口' }, { type: "ETH", name: "以太网接口" },
{ type: 'SD', name: 'SD卡插槽' }, { type: "SD", name: "SD卡插槽" },
{ type: 'SFP', name: 'SFP光纤模块' }, { type: "SFP", name: "SFP光纤模块" },
{ type: 'SMA', name: 'SMA连接器' }, { type: "SMA", name: "SMA连接器" },
{ type: 'MotherBoard', name: '主板' }, { type: "MotherBoard", name: "主板" },
{ type: 'PG2L100H_FBG676', name: 'PG2L100H FBG676芯片' } { type: "PG2L100H_FBG676", name: "PG2L100H FBG676芯片" },
]; ];
// --- 可用虚拟外设列表 --- // --- 可用虚拟外设列表 ---
const availableVirtualDevices = [ const availableVirtualDevices = [{ type: "DDS", name: "信号发生器" }];
{ type: 'DDS', name: '信号发生器' }
];
// --- 可用模板列表 --- // --- 可用模板列表 ---
const availableTemplates = ref([ const availableTemplates = ref([
{ {
name: 'PG2L100H 基础开发板', name: "PG2L100H 基础开发板",
id: 'PG2L100H_Pango100pro', id: "PG2L100H_Pango100pro",
description: '包含主板和两个LED的基本设置', description: "包含主板和两个LED的基本设置",
path: '/src/components/equipments/templates/PG2L100H_Pango100pro.json', path: "/public/EquipmentTemplates/PG2L100H_Pango100pro.json",
thumbnailUrl: '/src/components/equipments/svg/motherboard.svg' thumbnailUrl: motherboardSvg,
} },
]); ]);
// 显示/隐藏组件菜单 // 显示/隐藏组件菜单
const showComponentsMenu = computed({ const showComponentsMenu = computed({
get: () => props.open, get: () => props.open,
set: (value) => emit('update:open', value) set: (value) => emit("update:open", value),
}); });
// 组件模块缓存 // 组件模块缓存
@@ -241,7 +254,7 @@ async function loadComponentModule(type: string) {
// 将模块添加到缓存中 // 将模块添加到缓存中
componentModules.value = { componentModules.value = {
...componentModules.value, ...componentModules.value,
[type]: module [type]: module,
}; };
console.log(`Loaded module for ${type}:`, module); console.log(`Loaded module for ${type}:`, module);
@@ -278,19 +291,19 @@ async function preloadComponentModules() {
function getPreviewSize(componentType: string): number { function getPreviewSize(componentType: string): number {
// 根据组件类型返回适当的预览尺寸 // 根据组件类型返回适当的预览尺寸
const previewSizes: Record<string, number> = { const previewSizes: Record<string, number> = {
'MechanicalButton': 0.4, // 按钮较大,需要更小尺寸 MechanicalButton: 0.4, // 按钮较大,需要更小尺寸
'Switch': 0.35, // 开关较大,需要更小尺寸 Switch: 0.35, // 开关较大,需要更小尺寸
'Pin': 0.8, // 引脚较小,可以大一些 Pin: 0.8, // 引脚较小,可以大一些
'SMT_LED': 0.7, // LED可以保持适中 SMT_LED: 0.7, // LED可以保持适中
'SevenSegmentDisplay': 0.4, // 数码管较大,需要较小尺寸 SevenSegmentDisplay: 0.4, // 数码管较大,需要较小尺寸
'HDMI': 0.5, // HDMI接口较大 HDMI: 0.5, // HDMI接口较大
'DDR': 0.5, // DDR内存较大 DDR: 0.5, // DDR内存较大
'ETH': 0.5, // 以太网接口较大 ETH: 0.5, // 以太网接口较大
'SD': 0.6, // SD卡插槽适中 SD: 0.6, // SD卡插槽适中
'SFP': 0.4, // SFP光纤模块较大 SFP: 0.4, // SFP光纤模块较大
'SMA': 0.7, // SMA连接器可以适中 SMA: 0.7, // SMA连接器可以适中
'MotherBoard': 0.13, // 主板最大,需要最小尺寸 MotherBoard: 0.13, // 主板最大,需要最小尺寸
'DDS': 0.3 // 信号发生器较大,需要较小尺寸 DDS: 0.3, // 信号发生器较大,需要较小尺寸
}; };
// 返回对应尺寸如果没有特定配置则返回默认值0.5 // 返回对应尺寸如果没有特定配置则返回默认值0.5
@@ -306,7 +319,7 @@ function searchComponents() {
// 关闭菜单 // 关闭菜单
function closeMenu() { function closeMenu() {
showComponentsMenu.value = false; showComponentsMenu.value = false;
emit('close'); emit("close");
} }
// 添加新元器件 // 添加新元器件
@@ -316,23 +329,26 @@ async function addComponent(componentTemplate: { type: string; name: string }) {
let defaultProps: Record<string, any> = {}; let defaultProps: Record<string, any> = {};
// 尝试直接调用组件导出的getDefaultProps方法 // 尝试直接调用组件导出的getDefaultProps方法
if(moduleRef){ if (moduleRef) {
if (typeof moduleRef.getDefaultProps === 'function') { if (typeof moduleRef.getDefaultProps === "function") {
defaultProps = moduleRef.getDefaultProps(); defaultProps = moduleRef.getDefaultProps();
console.log(`Got default props from ${componentTemplate.type}:`, defaultProps); console.log(
`Got default props from ${componentTemplate.type}:`,
defaultProps,
);
} else { } else {
// 回退到配置文件 // 回退到配置文件
console.log(`No getDefaultProps found for ${componentTemplate.type}`); console.log(`No getDefaultProps found for ${componentTemplate.type}`);
} }
} else{ } else {
console.log(`Failed to load module for ${componentTemplate.type}`); console.log(`Failed to load module for ${componentTemplate.type}`);
} }
// 发送添加组件事件给父组件 // 发送添加组件事件给父组件
emit('add-component', { emit("add-component", {
type: componentTemplate.type, type: componentTemplate.type,
name: componentTemplate.name, name: componentTemplate.name,
props: defaultProps props: defaultProps,
}); });
// 关闭菜单 // 关闭菜单
@@ -349,56 +365,60 @@ async function addTemplate(template: any) {
} }
const templateData = await response.json(); const templateData = await response.json();
console.log('加载模板:', templateData); console.log("加载模板:", templateData);
// 发出事件,将模板数据传递给父组件 // 发出事件,将模板数据传递给父组件
emit('add-template', { emit("add-template", {
id: template.id, id: template.id,
name: template.name, name: template.name,
template: templateData template: templateData,
}); });
// 关闭菜单 // 关闭菜单
closeMenu(); closeMenu();
} catch (error) { } catch (error) {
console.error('加载模板出错:', error); console.error("加载模板出错:", error);
alert('无法加载模板文件,请检查控制台错误信息'); alert("无法加载模板文件,请检查控制台错误信息");
} }
} }
// 过滤后的元器件列表 (用于菜单) // 过滤后的元器件列表 (用于菜单)
const filteredComponents = computed(() => { const filteredComponents = computed(() => {
if (!searchQuery.value || activeTab.value !== 'components') { if (!searchQuery.value || activeTab.value !== "components") {
return availableComponents; return availableComponents;
} }
const query = searchQuery.value.toLowerCase(); const query = searchQuery.value.toLowerCase();
return availableComponents.filter(component => return availableComponents.filter(
component.name.toLowerCase().includes(query) || (component) =>
component.type.toLowerCase().includes(query) component.name.toLowerCase().includes(query) ||
component.type.toLowerCase().includes(query),
); );
}); });
// 过滤后的模板列表 (用于菜单) // 过滤后的模板列表 (用于菜单)
const filteredTemplates = computed(() => { const filteredTemplates = computed(() => {
if (!searchQuery.value || activeTab.value !== 'templates') { if (!searchQuery.value || activeTab.value !== "templates") {
return availableTemplates.value; return availableTemplates.value;
} }
const query = searchQuery.value.toLowerCase(); const query = searchQuery.value.toLowerCase();
return availableTemplates.value.filter(template => return availableTemplates.value.filter(
template.name.toLowerCase().includes(query) || (template) =>
(template.description && template.description.toLowerCase().includes(query)) template.name.toLowerCase().includes(query) ||
(template.description &&
template.description.toLowerCase().includes(query)),
); );
}); });
// 过滤后的虚拟外设列表 (用于菜单) // 过滤后的虚拟外设列表 (用于菜单)
const filteredVirtualDevices = computed(() => { const filteredVirtualDevices = computed(() => {
if (!searchQuery.value || activeTab.value !== 'virtual') { if (!searchQuery.value || activeTab.value !== "virtual") {
return availableVirtualDevices; return availableVirtualDevices;
} }
const query = searchQuery.value.toLowerCase(); const query = searchQuery.value.toLowerCase();
return availableVirtualDevices.filter(device => return availableVirtualDevices.filter(
device.name.toLowerCase().includes(query) || (device) =>
device.type.toLowerCase().includes(query) device.name.toLowerCase().includes(query) ||
device.type.toLowerCase().includes(query),
); );
}); });
@@ -427,6 +447,7 @@ onMounted(() => {
opacity: 0; opacity: 0;
transform: translateY(20px); transform: translateY(20px);
} }
to { to {
opacity: 1; opacity: 1;
transform: translateY(0); transform: translateY(0);

View File

@@ -152,7 +152,7 @@ const emit = defineEmits<{
}>(); }>();
// 控制折叠面板状态 // 控制折叠面板状态
const generalPropsExpanded = ref(true); const generalPropsExpanded = ref(false);
const componentPropsExpanded = ref(true); const componentPropsExpanded = ref(true);
// 更新组件属性方法 // 更新组件属性方法

View File

@@ -45,18 +45,10 @@
<CollapsibleSection title="组件功能" v-model:isExpanded="componentCapsExpanded" status="default" class="mt-4"> <CollapsibleSection title="组件功能" v-model:isExpanded="componentCapsExpanded" status="default" class="mt-4">
<div v-if="componentData && componentData.type"> <div v-if="componentData && componentData.type">
<component <component v-if="capabilityComponent" :is="capabilityComponent" v-bind="componentData.attrs" />
v-if="capabilityComponent" <div v-else class="text-gray-400">该组件没有提供特殊功能</div>
:is="capabilityComponent"
v-bind="componentData.attrs"
/>
<div v-else class="text-gray-400">
该组件没有提供特殊功能
</div>
</div>
<div v-else class="text-gray-400">
选择元件以查看其功能
</div> </div>
<div v-else class="text-gray-400">选择元件以查看其功能</div>
</CollapsibleSection> </CollapsibleSection>
<!-- 未来可以在这里添加更多的分区 --> <!-- 未来可以在这里添加更多的分区 -->
@@ -98,7 +90,7 @@ const props = defineProps<{
}>(); }>();
// 控制各个属性分区的展开状态 // 控制各个属性分区的展开状态
const propertySectionExpanded = ref(true); // 基本属性区域默认展开 const propertySectionExpanded = ref(false); // 基本属性区域默认展开
const pinsSectionExpanded = ref(false); // 引脚配置区域默认折叠 const pinsSectionExpanded = ref(false); // 引脚配置区域默认折叠
const componentCapsExpanded = ref(true); // 组件功能区域默认展开 const componentCapsExpanded = ref(true); // 组件功能区域默认展开
const wireSectionExpanded = ref(false); // 连线管理区域默认折叠 const wireSectionExpanded = ref(false); // 连线管理区域默认折叠
@@ -227,7 +219,7 @@ async function getExposedCapabilities(componentType: string) {
const Component = module.default; const Component = module.default;
// 创建一个临时div作为挂载点 // 创建一个临时div作为挂载点
const tempDiv = document.createElement('div'); const tempDiv = document.createElement("div");
// 创建临时应用实例并挂载组件 // 创建临时应用实例并挂载组件
let exposedMethods: any = null; let exposedMethods: any = null;
@@ -239,19 +231,22 @@ async function getExposedCapabilities(componentType: string) {
// 获取组件实例暴露的方法 // 获取组件实例暴露的方法
exposedMethods = el; exposedMethods = el;
} }
} },
}); });
} },
}); });
// 挂载应用 // 挂载应用
const vm = app.mount(tempDiv); const vm = app.mount(tempDiv);
// 确保实例已创建并获取到暴露的方法 // 确保实例已创建并获取到暴露的方法
await new Promise(resolve => setTimeout(resolve, 0)); await new Promise((resolve) => setTimeout(resolve, 0));
// 检查是否有getCapabilities方法 // 检查是否有getCapabilities方法
if (exposedMethods && typeof exposedMethods.getCapabilities === 'function') { if (
exposedMethods &&
typeof exposedMethods.getCapabilities === "function"
) {
// 获取能力组件定义 // 获取能力组件定义
const CapabilityComponent = exposedMethods.getCapabilities(); const CapabilityComponent = exposedMethods.getCapabilities();
@@ -280,7 +275,9 @@ watch(
if (newComponentData && newComponentData.type) { if (newComponentData && newComponentData.type) {
try { try {
// 首先尝试从实例中获取暴露的方法 // 首先尝试从实例中获取暴露的方法
const capsComponent = await getExposedCapabilities(newComponentData.type); const capsComponent = await getExposedCapabilities(
newComponentData.type,
);
if (capsComponent) { if (capsComponent) {
capabilityComponent.value = markRaw(capsComponent); capabilityComponent.value = markRaw(capsComponent);
@@ -289,10 +286,13 @@ watch(
} }
// 如果实例方法获取失败,回退到模块导出方法 // 如果实例方法获取失败,回退到模块导出方法
const module = await import(`./equipments/${newComponentData.type}.vue`); const module = await import(
`./equipments/${newComponentData.type}.vue`
);
if ( if (
(module.default && typeof module.default.getCapabilities === "function") || (module.default &&
typeof module.default.getCapabilities === "function") ||
typeof module.getCapabilities === "function" typeof module.getCapabilities === "function"
) { ) {
const getCapsFn = const getCapsFn =
@@ -318,7 +318,7 @@ watch(
capabilityComponent.value = null; capabilityComponent.value = null;
} }
}, },
{ immediate: true } { immediate: true },
); );
// 修改hasComponentCaps计算属性 // 修改hasComponentCaps计算属性

View File

@@ -6,22 +6,27 @@
<!-- Input File --> <!-- Input File -->
<fieldset class="fieldset w-full"> <fieldset class="fieldset w-full">
<legend class="fieldset-legend text-sm">选择或拖拽上传文件</legend> <legend class="fieldset-legend text-sm">选择或拖拽上传文件</legend>
<input type="file" class="file-input w-full" :value="fileInput" @change="handleFileChange" /> <input type="file" ref="fileInput" class="file-input w-full" @change="handleFileChange" />
<label class="fieldset-label">文件最大容量: {{ maxMemory }}MB</label> <label class="fieldset-label">文件最大容量: {{ maxMemory }}MB</label>
</fieldset> </fieldset>
<!-- Upload Button --> <!-- Upload Button -->
<div class="card-actions w-full"> <div class="card-actions w-full">
<button @click="handleClick" class="btn btn-primary grow"> <button @click="handleClick" class="btn btn-primary grow" :disabled="isUploading">
{{ buttonText }} <div v-if="isUploading">
<span class="loading loading-spinner"></span>
下载中...
</div>
<div v-else>
{{ buttonText }}
</div>
</button> </button>
</div> </div>
</div> </div>
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import { computed, ref } from "vue"; import { computed, ref, useTemplateRef, onMounted } from "vue";
import { useEquipments } from "@/stores/equipments";
import { useDialogStore } from "@/stores/dialog"; import { useDialogStore } from "@/stores/dialog";
import { isNull, isUndefined } from "lodash"; import { isNull, isUndefined } from "lodash";
@@ -41,16 +46,20 @@ const emits = defineEmits<{
}>(); }>();
const dialog = useDialogStore(); const dialog = useDialogStore();
const eqps = useEquipments();
const isUploading = ref(false);
const buttonText = computed(() => { const buttonText = computed(() => {
return isUndefined(props.downloadEvent) ? "上传" : "上传并下载"; return isUndefined(props.downloadEvent) ? "上传" : "上传并下载";
}); });
// var bitstream: File | null = null; const fileInput = useTemplateRef("fileInput");
const bitstream = defineModel<File | undefined>(); const bitstream = defineModel<File | undefined>();
const fileInput = computed(() => { onMounted(() => {
return !isUndefined(bitstream.value) ? bitstream.value.name : ""; if (!isUndefined(bitstream.value) && !isNull(fileInput.value)) {
let fileList = new DataTransfer();
fileList.items.add(bitstream.value);
fileInput.value.files = fileList.files;
}
}); });
function handleFileChange(event: Event): void { function handleFileChange(event: Event): void {
@@ -86,6 +95,7 @@ async function handleClick(event: Event): Promise<void> {
} }
// Upload - 修改这里传递bitstream.value而不是bitstream // Upload - 修改这里传递bitstream.value而不是bitstream
isUploading.value = true;
try { try {
const ret = await props.uploadEvent(event, bitstream.value); const ret = await props.uploadEvent(event, bitstream.value);
if (isUndefined(props.downloadEvent)) { if (isUndefined(props.downloadEvent)) {
@@ -110,8 +120,9 @@ async function handleClick(event: Event): Promise<void> {
dialog.error("下载失败"); dialog.error("下载失败");
console.error(e); console.error(e);
} }
}
isUploading.value = false;
}
</script> </script>
<style scoped lang="postcss"> <style scoped lang="postcss">

View File

@@ -1,4 +1,5 @@
<template> <div class="dds-property-editor"> <template>
<div class="dds-property-editor">
<CollapsibleSection title="信号发生器" :isExpanded="true"> <CollapsibleSection title="信号发生器" :isExpanded="true">
<div class="dds-editor-container"> <div class="dds-editor-container">
<div class="dds-display"> <div class="dds-display">
@@ -9,27 +10,35 @@
<path :d="currentWaveformPath" stroke="lime" stroke-width="2" fill="none" /> <path :d="currentWaveformPath" stroke="lime" stroke-width="2" fill="none" />
<!-- 频率和相位显示 --> <!-- 频率和相位显示 -->
<text x="20" y="25" fill="#0f0" font-size="14">{{ displayFrequency }}</text> <text x="20" y="25" fill="#0f0" font-size="14">
<text x="200" y="25" fill="#0f0" font-size="14">φ: {{ phase }}°</text> {{ displayFrequency }}
<text x="150" y="110" fill="#0f0" font-size="14" text-anchor="middle">{{ displayTimebase }}</text> </text>
<text x="200" y="25" fill="#0f0" font-size="14">
φ: {{ phase }}°
</text>
<text x="150" y="110" fill="#0f0" font-size="14" text-anchor="middle">
{{ displayTimebase }}
</text>
</svg> </svg>
<!-- 时基控制 --> <!-- 时基控制 -->
<div class="timebase-controls"> <div class="timebase-controls">
<button class="timebase-button" @click="decreaseTimebase">-</button> <button class="timebase-button" @click="decreaseTimebase">
-
</button>
<span class="timebase-label">时基</span> <span class="timebase-label">时基</span>
<button class="timebase-button" @click="increaseTimebase">+</button> <button class="timebase-button" @click="increaseTimebase">
+
</button>
</div> </div>
</div> </div>
<!-- 波形选择区 --> <!-- 波形选择区 -->
<div class="waveform-selector"> <div class="waveform-selector">
<div <div v-for="(name, index) in waveformNames" :key="`wave-${index}`" :class="[
v-for="(name, index) in waveformNames" 'waveform-option',
:key="`wave-${index}`" { active: currentWaveformIndex === index },
:class="['waveform-option', { active: currentWaveformIndex === index }]" ]" @click="selectWaveform(index)">
@click="selectWaveform(index)"
>
{{ name }} {{ name }}
</div> </div>
</div> </div>
@@ -39,15 +48,14 @@
<div class="control-group"> <div class="control-group">
<span class="control-label">频率:</span> <span class="control-label">频率:</span>
<div class="control-buttons"> <div class="control-buttons">
<button class="control-button" @click="decreaseFrequency">-</button> <button class="control-button" @click="decreaseFrequency">
<input -
v-model="frequencyInput" </button>
@blur="applyFrequencyInput" <input v-model="frequencyInput" @blur="applyFrequencyInput" @keyup.enter="applyFrequencyInput"
@keyup.enter="applyFrequencyInput" class="control-input" type="text" />
class="control-input" <button class="control-button" @click="increaseFrequency">
type="text" +
/> </button>
<button class="control-button" @click="increaseFrequency">+</button>
</div> </div>
</div> </div>
@@ -55,13 +63,8 @@
<span class="control-label">相位:</span> <span class="control-label">相位:</span>
<div class="control-buttons"> <div class="control-buttons">
<button class="control-button" @click="decreasePhase">-</button> <button class="control-button" @click="decreasePhase">-</button>
<input <input v-model="phaseInput" @blur="applyPhaseInput" @keyup.enter="applyPhaseInput" class="control-input"
v-model="phaseInput" type="text" />
@blur="applyPhaseInput"
@keyup.enter="applyPhaseInput"
class="control-input"
type="text"
/>
<button class="control-button" @click="increasePhase">+</button> <button class="control-button" @click="increasePhase">+</button>
</div> </div>
</div> </div>
@@ -69,53 +72,48 @@
<!-- 自定义波形输入 --> <!-- 自定义波形输入 -->
<div class="custom-waveform"> <div class="custom-waveform">
<div class="section-heading">自定义波形</div> <div class="input-group"> <div class="section-heading">自定义波形</div>
<div class="input-group">
<label class="input-label">函数表达式:</label> <label class="input-label">函数表达式:</label>
<input <input v-model="customWaveformExpression" class="function-input"
v-model="customWaveformExpression"
class="function-input"
placeholder="例如: sin(t) 或 x^(2/3)+0.9*sqrt(3.3-x^2)*sin(a*PI*x) [a=7.8]" placeholder="例如: sin(t) 或 x^(2/3)+0.9*sqrt(3.3-x^2)*sin(a*PI*x) [a=7.8]"
@keyup.enter="applyCustomWaveform" @keyup.enter="applyCustomWaveform" />
/> <button class="apply-button" @click="applyCustomWaveform">
<button class="apply-button" @click="applyCustomWaveform">应用</button> 应用
</button>
</div> </div>
<div class="example-functions"> <div class="example-functions">
<div class="example-label">示例函数:</div> <div class="example-label">示例函数:</div>
<div class="example-buttons"> <div class="example-buttons">
<button <button class="example-button" @click="applyExampleFunction('sin(t)')">
class="example-button" 正弦波
@click="applyExampleFunction('sin(t)')" </button>
>正弦波</button> <button class="example-button" @click="applyExampleFunction('sin(t)^3')">
<button 立方正弦
class="example-button" </button>
@click="applyExampleFunction('sin(t)^3')" <button class="example-button" @click="
>立方正弦</button> <button applyExampleFunction(
class="example-button" '((x)^(2/3)+0.9*sqrt(3.3-(x)^2)*sin(10*PI*(x)))*0.75',
@click="applyExampleFunction('((x)^(2/3)+0.9*sqrt(3.3-(x)^2)*sin(10*PI*(x)))*0.75')" )
>心形函数</button> ">
心形函数
</button>
</div> </div>
</div> </div>
<div class="drawing-area"> <div class="drawing-area">
<div class="section-heading">波形绘制</div> <div class="section-heading">波形绘制</div>
<div <div class="waveform-canvas-container" ref="canvasContainer">
class="waveform-canvas-container" <canvas ref="drawingCanvas" class="drawing-canvas" width="280" height="100" @mousedown="startDrawing"
ref="canvasContainer" @mousemove="draw" @mouseup="stopDrawing" @mouseleave="stopDrawing"></canvas>
>
<canvas
ref="drawingCanvas"
class="drawing-canvas"
width="280"
height="100"
@mousedown="startDrawing"
@mousemove="draw"
@mouseup="stopDrawing"
@mouseleave="stopDrawing"
></canvas>
<div class="canvas-actions"> <div class="canvas-actions">
<button class="canvas-button" @click="clearCanvas">清除</button> <button class="canvas-button" @click="clearCanvas">
<button class="canvas-button" @click="applyDrawnWaveform">应用绘制</button> 清除
</button>
<button class="canvas-button" @click="applyDrawnWaveform">
应用绘制
</button>
</div> </div>
</div> </div>
</div> </div>
@@ -125,22 +123,25 @@
<div class="saved-waveforms"> <div class="saved-waveforms">
<div class="section-heading">波形存储槽</div> <div class="section-heading">波形存储槽</div>
<div class="slot-container"> <div class="slot-container">
<div <div v-for="(slot, index) in waveformSlots" :key="`slot-${index}`"
v-for="(slot, index) in waveformSlots" :class="['waveform-slot', { empty: !slot.name }]" @click="loadWaveformSlot(index)">
:key="`slot-${index}`" <span class="slot-name">{{
:class="['waveform-slot', { empty: !slot.name }]" slot.name || `${index + 1}`
@click="loadWaveformSlot(index)" }}</span>
> <button class="save-button" @click.stop="saveCurrentToSlot(index)">
<span class="slot-name">{{ slot.name || `${index+1}` }}</span>
<button
class="save-button"
@click.stop="saveCurrentToSlot(index)"
>
保存 保存
</button> </button>
</div> </div>
</div> </div>
</div> </div>
<button class="btn btn-primary text-primary-content w-full" :disabled="isApplying" @click="applyOutputWave">
<div v-if="isApplying">
<span class="loading loading-spinner"></span>
应用中...
</div>
<div v-else>应用输出波形</div>
</button>
</div> </div>
</div> </div>
</CollapsibleSection> </CollapsibleSection>
@@ -148,22 +149,33 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'; import { ref, computed, watch, onMounted } from "vue";
import CollapsibleSection from '../CollapsibleSection.vue'; import CollapsibleSection from "../CollapsibleSection.vue";
import { DDSClient } from "@/APIClient";
import { useEquipments } from "@/stores/equipments";
import { useDialogStore } from "@/stores/dialog";
import { toInteger } from "lodash";
// Component Attributes
const props = defineProps<{ const props = defineProps<{
modelValue: any; modelValue: any;
}>(); }>();
const emit = defineEmits(['update:modelValue']); const emit = defineEmits(["update:modelValue"]);
// Global varibles
const dds = new DDSClient();
const eqps = useEquipments();
const dialog = useDialogStore();
// 波形状态 // 波形状态
const frequency = ref(props.modelValue?.frequency || 1000); const frequency = ref<number>(props.modelValue?.frequency || 1000);
const phase = ref(props.modelValue?.phase || 0); const phase = ref<number>(props.modelValue?.phase || 0);
const timebase = ref(props.modelValue?.timebase || 1); // 时基默认为1倍 const timebase = ref(props.modelValue?.timebase || 1); // 时基默认为1倍
const currentWaveformIndex = ref(0); const currentWaveformIndex = ref(0);
const waveformNames = ['正弦波', '方波', '三角波', '锯齿波', '自定义']; const waveformNames = ["正弦波", "方波", "三角波", "锯齿波", "自定义"];
const waveforms = ['sine', 'square', 'triangle', 'sawtooth', 'custom']; const waveforms = ["sine", "square", "triangle", "sawtooth", "custom"];
const isApplying = ref(false);
// 波形函数集合 // 波形函数集合
interface WaveformFunction { interface WaveformFunction {
@@ -176,45 +188,72 @@ interface WaveformFunctions {
const waveformFunctions: WaveformFunctions = { const waveformFunctions: WaveformFunctions = {
// 正弦波函数: sin(2π*x + φ) // 正弦波函数: sin(2π*x + φ)
sine: (x: number, width: number, height: number, phaseRad: number): number => { sine: (
return height/2 * Math.sin(2 * Math.PI * (x / width) * 2 + phaseRad); x: number,
width: number,
height: number,
phaseRad: number,
): number => {
return (height / 2) * Math.sin(2 * Math.PI * (x / width) * 2 + phaseRad);
}, },
// 方波函数: 周期性的高低电平 // 方波函数: 周期性的高低电平
square: (x: number, width: number, height: number, phaseRad: number): number => { square: (
x: number,
width: number,
height: number,
phaseRad: number,
): number => {
const normX = (x / width + phaseRad / (2 * Math.PI)) % 1; const normX = (x / width + phaseRad / (2 * Math.PI)) % 1;
return normX < 0.5 ? height/4 : -height/4; return normX < 0.5 ? height / 4 : -height / 4;
}, },
// 三角波函数: 线性上升和下降 // 三角波函数: 线性上升和下降
triangle: (x: number, width: number, height: number, phaseRad: number): number => { triangle: (
x: number,
width: number,
height: number,
phaseRad: number,
): number => {
const normX = (x / width + phaseRad / (2 * Math.PI)) % 1; const normX = (x / width + phaseRad / (2 * Math.PI)) % 1;
return height/2 - height * Math.abs(2 * normX - 1); return height / 2 - height * Math.abs(2 * normX - 1);
}, },
// 锯齿波函数: 线性上升,瞬间下降 // 锯齿波函数: 线性上升,瞬间下降
sawtooth: (x: number, width: number, height: number, phaseRad: number): number => { sawtooth: (
x: number,
width: number,
height: number,
phaseRad: number,
): number => {
const normX = (x / width + phaseRad / (2 * Math.PI)) % 1; const normX = (x / width + phaseRad / (2 * Math.PI)) % 1;
return height/2 - height/2 * (2 * normX); return height / 2 - (height / 2) * (2 * normX);
}, },
// 自定义波形函数占位符 // 自定义波形函数占位符
custom: (x: number, width: number, height: number, phaseRad: number): number => { custom: (
x: number,
width: number,
height: number,
phaseRad: number,
): number => {
return 0; // 默认返回0会在应用自定义表达式时更新 return 0; // 默认返回0会在应用自定义表达式时更新
} },
}; };
// 输入控制 // 输入控制
const frequencyInput = ref(formatFrequency(frequency.value)); const frequencyInput = ref(formatFrequency(frequency.value));
const phaseInput = ref(phase.value.toString()); const phaseInput = ref(phase.value.toString());
const customWaveformExpression = ref(''); const customWaveformExpression = ref("");
// 波形槽 // 波形槽
const waveformSlots = ref<{ name: string; type: string; data: number[][] | null }[]>([ const waveformSlots = ref<
{ name: '正弦波', type: 'sine', data: null }, { name: string; type: string; data: number[][] | null }[]
{ name: '方波', type: 'square', data: null }, >([
{ name: '三角波', type: 'triangle', data: null }, { name: "正弦波", type: "sine", data: null },
{ name: '', type: '', data: null } { name: "方波", type: "square", data: null },
{ name: "三角波", type: "triangle", data: null },
{ name: "", type: "", data: null },
]); ]);
// 绘图相关 // 绘图相关
@@ -283,7 +322,7 @@ const currentWaveformPath = computed(() => {
const xOffset = 0; const xOffset = 0;
const yOffset = 30; const yOffset = 30;
const currentWaveform = waveforms[currentWaveformIndex.value]; const currentWaveform = waveforms[currentWaveformIndex.value];
const phaseRadians = phase.value * Math.PI / 180; const phaseRadians = (phase.value * Math.PI) / 180;
// 时基和频率共同影响周期数量 // 时基和频率共同影响周期数量
// 频率因素 - 频率越高,一个屏幕内显示的周期越多 // 频率因素 - 频率越高,一个屏幕内显示的周期越多
@@ -297,9 +336,9 @@ const currentWaveformPath = computed(() => {
// 组合因素 // 组合因素
const scaleFactor = timebaseFactor * frequencyFactor; const scaleFactor = timebaseFactor * frequencyFactor;
let path = ''; let path = "";
// 使用函数生成波形 // 使用函数生成波形
if (currentWaveform === 'custom') { if (currentWaveform === "custom") {
// 自定义波形 // 自定义波形
if (drawPoints.value.length > 0) { if (drawPoints.value.length > 0) {
path = `M${xOffset + drawPoints.value[0][0]},${yOffset + drawPoints.value[0][1]}`; path = `M${xOffset + drawPoints.value[0][0]},${yOffset + drawPoints.value[0][1]}`;
@@ -308,32 +347,34 @@ const currentWaveformPath = computed(() => {
} }
} else { } else {
// 如果没有绘制点但选择了自定义波形,仍然使用函数生成 // 如果没有绘制点但选择了自定义波形,仍然使用函数生成
const waveFunction = waveformFunctions.custom; path = `M${xOffset},${yOffset + height/2}`; const waveFunction = waveformFunctions.custom;
path = `M${xOffset},${yOffset + height / 2}`;
for (let x = 0; x <= width; x++) { for (let x = 0; x <= width; x++) {
const scaledX = x * scaleFactor; const scaledX = x * scaleFactor;
const y = waveFunction(scaledX, width, height, phaseRadians); const y = waveFunction(scaledX, width, height, phaseRadians);
// 注意心形函数可能返回undefined或极端值需要处理 // 注意心形函数可能返回undefined或极端值需要处理
if (typeof y === 'number' && isFinite(y)) { if (typeof y === "number" && isFinite(y)) {
path += ` L${x + xOffset},${yOffset + height/2 - y}`; path += ` L${x + xOffset},${yOffset + height / 2 - y}`;
} else { } else {
// 如果返回异常值,保持当前位置 // 如果返回异常值,保持当前位置
path += ` L${x + xOffset},${yOffset + height/2}`; path += ` L${x + xOffset},${yOffset + height / 2}`;
} }
} }
} }
} else { } else {
// 使用预定义的波形函数 // 使用预定义的波形函数
const waveFunction = waveformFunctions[currentWaveform as keyof typeof waveformFunctions]; const waveFunction =
waveformFunctions[currentWaveform as keyof typeof waveformFunctions];
// 生成路径点 // 生成路径点
path = `M${xOffset},${yOffset + height/2}`; path = `M${xOffset},${yOffset + height / 2}`;
for (let x = 0; x <= width; x++) { for (let x = 0; x <= width; x++) {
// 应用组合缩放因素 - 影响x轴的缩放 // 应用组合缩放因素 - 影响x轴的缩放
const scaledX = x * scaleFactor; const scaledX = x * scaleFactor;
const y = waveFunction(scaledX, width, height, phaseRadians); const y = waveFunction(scaledX, width, height, phaseRadians);
path += ` L${x + xOffset},${yOffset + height/2 - y}`; path += ` L${x + xOffset},${yOffset + height / 2 - y}`;
} }
} }
@@ -346,6 +387,56 @@ function selectWaveform(index: number) {
updateModelValue(); updateModelValue();
} }
async function applyOutputWave() {
try {
isApplying.value = true;
{
const ret = await dds.setWaveNum(
eqps.boardAddr,
eqps.boardPort,
0,
currentWaveformIndex.value,
);
if (!ret) {
dialog.error("应用失败");
}
}
{
const ret = await dds.setFreq(
eqps.boardAddr,
eqps.boardPort,
0,
currentWaveformIndex.value,
frequency.value * Math.pow(2, 32 - 20),
);
if (!ret) {
dialog.error("应用失败");
}
}
{
const ret = await dds.setPhase(
eqps.boardAddr,
eqps.boardPort,
0,
currentWaveformIndex.value,
toInteger((phase.value * 4096) / 360),
);
if (ret) {
dialog.info("应用成功");
} else {
dialog.error("应用失败");
}
}
} catch (e) {
dialog.error("应用失败");
console.error(e);
} finally {
isApplying.value = false;
}
}
function increaseFrequency() { function increaseFrequency() {
if (frequency.value < 10) { if (frequency.value < 10) {
frequency.value += 0.1; frequency.value += 0.1;
@@ -390,11 +481,11 @@ function applyFrequencyInput() {
let value = parseFloat(frequencyInput.value); let value = parseFloat(frequencyInput.value);
// 处理单位 // 处理单位
if (frequencyInput.value.includes('MHz')) { if (frequencyInput.value.includes("MHz")) {
value = parseFloat(frequencyInput.value) * 1000000; value = parseFloat(frequencyInput.value) * 1000000;
} else if (frequencyInput.value.includes('kHz')) { } else if (frequencyInput.value.includes("kHz")) {
value = parseFloat(frequencyInput.value) * 1000; value = parseFloat(frequencyInput.value) * 1000;
} else if (frequencyInput.value.includes('Hz')) { } else if (frequencyInput.value.includes("Hz")) {
value = parseFloat(frequencyInput.value); value = parseFloat(frequencyInput.value);
} }
@@ -444,11 +535,11 @@ function applyCustomWaveform() {
try { try {
// 创建自定义波形函数 // 创建自定义波形函数
createCustomWaveformFunction(); createCustomWaveformFunction();
currentWaveformIndex.value = waveforms.indexOf('custom'); currentWaveformIndex.value = waveforms.indexOf("custom");
drawCustomWaveformFromExpression(); drawCustomWaveformFromExpression();
updateModelValue(); updateModelValue();
} catch (error) { } catch (error) {
console.error('Invalid expression:', error); console.error("Invalid expression:", error);
// 这里可以添加一些错误提示 // 这里可以添加一些错误提示
} }
} }
@@ -466,72 +557,90 @@ function createCustomWaveformFunction() {
const expression = customWaveformExpression.value; const expression = customWaveformExpression.value;
// 导入 mathjs // 导入 mathjs
import('mathjs').then((math) => { import("mathjs")
try { .then((math) => {
// 预编译表达式以提高性能 try {
const compiledExpression = math.compile(expression); // 预编译表达式以提高性能
const compiledExpression = math.compile(expression);
// 添加自定义函数到波形函数集合中 // 添加自定义函数到波形函数集合中
waveformFunctions.custom = (x: number, width: number, height: number, phaseRad: number): number => { waveformFunctions.custom = (
try { x: number,
// 相位调整 - 将相位转换为x轴的位移 width: number,
const phaseShift = phaseRad / (2 * Math.PI); height: number,
phaseRad: number,
): number => {
try {
// 相位调整 - 将相位转换为x轴的位移
const phaseShift = phaseRad / (2 * Math.PI);
// 标准化参数使x落在 0-1 范围内,并应用相位 // 标准化参数使x落在 0-1 范围内,并应用相位
let normalizedX = ((x / width) + phaseShift) % 1; let normalizedX = (x / width + phaseShift) % 1;
// 心形函数需要x映射到[-1.5,1.5]范围,以确保完整显示心形 // 心形函数需要x映射到[-1.5,1.5]范围,以确保完整显示心形
// 这个范围比[-1,1]稍大,确保心形两侧完整显示 // 这个范围比[-1,1]稍大,确保心形两侧完整显示
const scaledX = (normalizedX * 3) - 1.5; const scaledX = normalizedX * 3 - 1.5;
// 创建参数对象,包括各种变量和常量供表达式使用 // 创建参数对象,包括各种变量和常量供表达式使用
const scope = { const scope = {
x: scaledX, // 映射后的x变量 x: scaledX, // 映射后的x变量
t: normalizedX * 2 * Math.PI, // 角度变量 (0-2π),不包括相位 t: normalizedX * 2 * Math.PI, // 角度变量 (0-2π),不包括相位
phase: phaseRad, // 相位值,独立参数 phase: phaseRad, // 相位值,独立参数
PI: Math.PI, // 常量 PI PI: Math.PI, // 常量 PI
a: 7.8, // 心形函数振荡参数 a: 7.8, // 心形函数振荡参数
}; };
// 计算表达式 // 计算表达式
let result = compiledExpression.evaluate(scope); let result = compiledExpression.evaluate(scope);
// 确保结果在合理范围内 // 确保结果在合理范围内
if (typeof result !== 'number' || isNaN(result) || !isFinite(result)) { if (
result = 0; typeof result !== "number" ||
isNaN(result) ||
!isFinite(result)
) {
result = 0;
}
// 对于心形函数,我们可能需要额外调整振幅因子
// 确保振幅在合适范围内
result = Math.max(-1, Math.min(1, result));
// 返回适当的振幅
return (height / 2) * result;
} catch (e) {
console.error("Error evaluating expression:", e);
return 0;
} }
};
// 对于心形函数,我们可能需要额外调整振幅因子 // 立即更新波形显示
// 确保振幅在合适范围内 updateModelValue();
result = Math.max(-1, Math.min(1, result)); } catch (parseError) {
console.error("Error parsing expression:", parseError);
// 返回适当的振幅 // 解析错误时使用默认正弦波
return height/2 * result; waveformFunctions.custom = (
} catch (e) { x: number,
console.error('Error evaluating expression:', e); width: number,
return 0; height: number,
} phaseRad: number,
}; ): number => {
return (
// 立即更新波形显示 (height / 2) * Math.sin(2 * Math.PI * (x / width) * 2 + phaseRad)
updateModelValue(); );
} catch (parseError) { };
console.error('Error parsing expression:', parseError); }
// 解析错误时使用默认正弦波 })
waveformFunctions.custom = (x: number, width: number, height: number, phaseRad: number): number => { .catch((error) => {
return height/2 * Math.sin(2 * Math.PI * (x / width) * 2 + phaseRad); console.error("Error loading mathjs:", error);
}; });
} }
}).catch(error => {
console.error('Error loading mathjs:', error);
});
};
// 绘制自定义波形 // 绘制自定义波形
function drawCustomWaveformFromExpression() { function drawCustomWaveformFromExpression() {
const canvas = drawingCanvas.value; const canvas = drawingCanvas.value;
if (!canvas) return; if (!canvas) return;
const ctx = canvas.getContext('2d'); const ctx = canvas.getContext("2d");
if (!ctx) return; if (!ctx) return;
const width = canvas.width; const width = canvas.width;
@@ -539,13 +648,13 @@ function drawCustomWaveformFromExpression() {
// 清除画布 // 清除画布
ctx.clearRect(0, 0, width, height); ctx.clearRect(0, 0, width, height);
ctx.strokeStyle = '#0f0'; ctx.strokeStyle = "#0f0";
ctx.lineWidth = 2; ctx.lineWidth = 2;
// 创建自定义函数 - 先创建函数再绘制 // 创建自定义函数 - 先创建函数再绘制
createCustomWaveformFunction(); createCustomWaveformFunction();
// 使用波形函数来绘制 // 使用波形函数来绘制
const phaseRad = phase.value * Math.PI / 180; const phaseRad = (phase.value * Math.PI) / 180;
// 频率因素,与主波形显示保持一致 // 频率因素,与主波形显示保持一致
// 频率越高,显示的周期数就越多 // 频率越高,显示的周期数就越多
@@ -615,7 +724,7 @@ function startDrawing(event: MouseEvent) {
const x = event.clientX - rect.left; const x = event.clientX - rect.left;
const y = event.clientY - rect.top; const y = event.clientY - rect.top;
const ctx = canvas.getContext('2d'); const ctx = canvas.getContext("2d");
if (!ctx) return; if (!ctx) return;
// 清除画布 // 清除画布
@@ -624,7 +733,7 @@ function startDrawing(event: MouseEvent) {
// 开始新的绘制 // 开始新的绘制
drawPoints.value = [[x, y]]; drawPoints.value = [[x, y]];
ctx.beginPath(); ctx.beginPath();
ctx.strokeStyle = '#0f0'; ctx.strokeStyle = "#0f0";
ctx.lineWidth = 2; ctx.lineWidth = 2;
ctx.moveTo(x, y); ctx.moveTo(x, y);
} }
@@ -635,7 +744,7 @@ function draw(event: MouseEvent) {
const canvas = drawingCanvas.value; const canvas = drawingCanvas.value;
if (!canvas) return; if (!canvas) return;
const ctx = canvas.getContext('2d'); const ctx = canvas.getContext("2d");
if (!ctx) return; if (!ctx) return;
const rect = canvas.getBoundingClientRect(); const rect = canvas.getBoundingClientRect();
@@ -658,7 +767,7 @@ function clearCanvas() {
const canvas = drawingCanvas.value; const canvas = drawingCanvas.value;
if (!canvas) return; if (!canvas) return;
const ctx = canvas.getContext('2d'); const ctx = canvas.getContext("2d");
if (!ctx) return; if (!ctx) return;
ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.clearRect(0, 0, canvas.width, canvas.height);
@@ -667,7 +776,7 @@ function clearCanvas() {
function applyDrawnWaveform() { function applyDrawnWaveform() {
if (drawPoints.value.length > 0) { if (drawPoints.value.length > 0) {
currentWaveformIndex.value = waveforms.indexOf('custom'); currentWaveformIndex.value = waveforms.indexOf("custom");
updateModelValue(); updateModelValue();
} }
} }
@@ -677,9 +786,11 @@ function saveCurrentToSlot(index: number) {
waveformSlots.value[index] = { waveformSlots.value[index] = {
name: waveformNames[currentWaveformIndex.value], name: waveformNames[currentWaveformIndex.value],
type: waveforms[currentWaveformIndex.value], type: waveforms[currentWaveformIndex.value],
data: drawPoints.value.length > 0 && currentWaveformIndex.value === waveforms.indexOf('custom') data:
? [...drawPoints.value] drawPoints.value.length > 0 &&
: null currentWaveformIndex.value === waveforms.indexOf("custom")
? [...drawPoints.value]
: null,
}; };
} }
@@ -692,17 +803,17 @@ function loadWaveformSlot(index: number) {
currentWaveformIndex.value = waveformIndex; currentWaveformIndex.value = waveformIndex;
// 如果是自定义波形且有数据,加载数据 // 如果是自定义波形且有数据,加载数据
if (slot.type === 'custom' && slot.data !== null && slot.data.length > 0) { if (slot.type === "custom" && slot.data !== null && slot.data.length > 0) {
drawPoints.value = [...slot.data]; drawPoints.value = [...slot.data];
// 更新画布 // 更新画布
const canvas = drawingCanvas.value; const canvas = drawingCanvas.value;
if (canvas) { if (canvas) {
const ctx = canvas.getContext('2d'); const ctx = canvas.getContext("2d");
if (ctx) { if (ctx) {
ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath(); ctx.beginPath();
ctx.strokeStyle = '#0f0'; ctx.strokeStyle = "#0f0";
ctx.lineWidth = 2; ctx.lineWidth = 2;
for (let i = 0; i < slot.data.length; i++) { for (let i = 0; i < slot.data.length; i++) {
@@ -730,9 +841,12 @@ function updateModelValue() {
phase: phase.value, phase: phase.value,
timebase: timebase.value, timebase: timebase.value,
waveform: waveforms[currentWaveformIndex.value], waveform: waveforms[currentWaveformIndex.value],
customWaveformPoints: currentWaveformIndex.value === waveforms.indexOf('custom') ? [...drawPoints.value] : [] customWaveformPoints:
currentWaveformIndex.value === waveforms.indexOf("custom")
? [...drawPoints.value]
: [],
}; };
emit('update:modelValue', newValue); emit("update:modelValue", newValue);
} }
// 初始化 // 初始化
@@ -761,17 +875,23 @@ onMounted(() => {
} }
// 加载自定义波形点 // 加载自定义波形点
if (props.modelValue.customWaveformPoints && props.modelValue.customWaveformPoints.length > 0) { if (
props.modelValue.customWaveformPoints &&
props.modelValue.customWaveformPoints.length > 0
) {
drawPoints.value = [...props.modelValue.customWaveformPoints]; drawPoints.value = [...props.modelValue.customWaveformPoints];
// 绘制到画布上 // 绘制到画布上
const canvas = drawingCanvas.value; const canvas = drawingCanvas.value;
if (canvas && currentWaveformIndex.value === waveforms.indexOf('custom')) { if (
const ctx = canvas.getContext('2d'); canvas &&
currentWaveformIndex.value === waveforms.indexOf("custom")
) {
const ctx = canvas.getContext("2d");
if (ctx) { if (ctx) {
ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath(); ctx.beginPath();
ctx.strokeStyle = '#0f0'; ctx.strokeStyle = "#0f0";
ctx.lineWidth = 2; ctx.lineWidth = 2;
for (let i = 0; i < drawPoints.value.length; i++) { for (let i = 0; i < drawPoints.value.length; i++) {
@@ -790,28 +910,40 @@ onMounted(() => {
}); });
// 监听model变化 // 监听model变化
watch(() => props.modelValue, (newVal) => { watch(
if (newVal && newVal.frequency !== undefined && newVal.frequency !== frequency.value) { () => props.modelValue,
frequency.value = newVal.frequency; (newVal) => {
frequencyInput.value = formatFrequency(frequency.value); if (
} newVal &&
newVal.frequency !== undefined &&
if (newVal && newVal.phase !== undefined && newVal.phase !== phase.value) { newVal.frequency !== frequency.value
phase.value = newVal.phase; ) {
phaseInput.value = phase.value.toString(); frequency.value = newVal.frequency;
} frequencyInput.value = formatFrequency(frequency.value);
if (newVal && newVal.timebase !== undefined && newVal.timebase !== timebase.value) {
timebase.value = newVal.timebase;
}
if (newVal && newVal.waveform) {
const index = waveforms.indexOf(newVal.waveform);
if (index !== -1 && index !== currentWaveformIndex.value) {
currentWaveformIndex.value = index;
} }
}
}, { deep: true }); if (newVal && newVal.phase !== undefined && newVal.phase !== phase.value) {
phase.value = newVal.phase;
phaseInput.value = phase.value.toString();
}
if (
newVal &&
newVal.timebase !== undefined &&
newVal.timebase !== timebase.value
) {
timebase.value = newVal.timebase;
}
if (newVal && newVal.waveform) {
const index = waveforms.indexOf(newVal.waveform);
if (index !== -1 && index !== currentWaveformIndex.value) {
currentWaveformIndex.value = index;
}
}
},
{ deep: true },
);
</script> </script>
<style scoped> <style scoped>
@@ -1002,7 +1134,9 @@ watch(() => props.modelValue, (newVal) => {
border-radius: 4px; border-radius: 4px;
color: var(--base-content, #a6adbb); color: var(--base-content, #a6adbb);
cursor: pointer; cursor: pointer;
transition: background-color 0.2s ease, color 0.2s ease; transition:
background-color 0.2s ease,
color 0.2s ease;
font-size: 0.8rem; font-size: 0.8rem;
} }

View File

@@ -12,19 +12,15 @@
</template> </template>
<script setup lang="tsx"> <script setup lang="tsx">
import { JtagClient, type FileParameter } from "@/APIClient"; import MotherBoardCaps from "./MotherBoardCaps.vue";
import z from "zod";
import { useEquipments } from "@/stores/equipments"; import { useEquipments } from "@/stores/equipments";
import UploadCard from "@/components/UploadCard.vue"; import { ref, computed, defineComponent, watchEffect } from "vue";
import { useDialogStore } from "@/stores/dialog";
import { toNumber, toString } from "lodash";
import { computed, ref, defineComponent, watch } from "vue";
// 主板特有属性 // 主板特有属性
interface MotherBoardProps { export interface MotherBoardProps {
size?: number; size?: number;
jtagAddr?: string; boardAddr?: string;
jtagPort?: string; boardPort?: string;
} }
const props = withDefaults(defineProps<MotherBoardProps>(), getDefaultProps()); const props = withDefaults(defineProps<MotherBoardProps>(), getDefaultProps());
@@ -32,11 +28,14 @@ const props = withDefaults(defineProps<MotherBoardProps>(), getDefaultProps());
// 计算实际宽高 // 计算实际宽高
const width = computed(() => 800 * props.size); const width = computed(() => 800 * props.size);
const height = computed(() => 600 * props.size); const height = computed(() => 600 * props.size);
const eqps = useEquipments(); const eqps = useEquipments();
watch([props.jtagAddr, props.jtagPort], () => { const bitstreamFile = ref<File | null>();
eqps.jtagIPAddr = props.jtagAddr;
eqps.jtagPort = props.jtagPort; watchEffect(() => {
eqps.setAddr(props.boardAddr);
eqps.setPort(props.boardPort);
}); });
// 向外暴露方法 // 向外暴露方法
@@ -50,127 +49,13 @@ defineExpose({
getCapabilities: () => { getCapabilities: () => {
// 返回组件定义而不是直接返回JSX // 返回组件定义而不是直接返回JSX
return defineComponent({ return defineComponent({
name: "MotherBoardCapabilities", name: "MotherBoardCaps",
props: { setup() {
jtagAddr: {
type: String,
default: props.jtagAddr,
},
jtagPort: {
type: String,
default: props.jtagPort,
},
},
setup(props) {
const jtagController = new JtagClient();
const dialog = useDialogStore();
// 使用传入的属性或默认值
const jtagIDCode = ref("");
const boardAddress = computed(() => props.jtagAddr);
const boardPort = computed(() => toNumber(props.jtagPort));
async function uploadBitstream(event: Event, bitstream: File) {
if (!boardAddress.value || !boardPort.value) {
dialog.error("开发板地址或端口空缺");
return;
}
const fileParam = {
data: bitstream,
fileName: bitstream.name,
};
try {
const resp = await jtagController.uploadBitstream(
boardAddress.value,
fileParam,
);
return resp;
} catch (e) {
dialog.error("上传错误");
}
}
async function downloadBitstream() {
if (!boardAddress.value || !boardPort.value) {
dialog.error("开发板地址或端口空缺");
return;
}
try {
const resp = await jtagController.downloadBitstream(
boardAddress.value,
boardPort.value,
);
return resp;
} catch (e) {
dialog.error("上传错误");
console.error(e);
}
}
watch([boardAddress, boardPort], () => {
if (
z.string().ip().safeParse(boardAddress).success &&
z.number().positive().safeParse(boardPort).success
)
getIDCode();
});
async function getIDCode() {
if (!boardAddress.value || !boardPort.value) {
dialog.error("开发板地址或端口空缺");
return;
}
try {
const resp = await jtagController.getDeviceIDCode(
boardAddress.value,
boardPort.value,
);
jtagIDCode.value = toString(resp);
} catch (e) {
dialog.error("获取IDCode错误");
console.error(e);
}
}
return () => ( return () => (
<div> <MotherBoardCaps
<h1 class="font-bold text-center text-2xl">Jtag</h1> jtagAddr={eqps.boardAddr}
<div class="flex"> jtagPort={eqps.boardPort.toString()}
<p class="grow">IDCode: {jtagIDCode.value}</p> />
<button class="btn btn-circle w-8 h-8" onClick={getIDCode}>
<svg
class="icon opacity-70"
viewBox="0 0 1024 1024"
version="1.1"
xmlns="http://www.w3.org/2000/svg"
p-id="4865"
width="200"
height="200"
>
<path
d="M894.481158 505.727133c0 49.589418-9.711176 97.705276-28.867468 143.007041-18.501376 43.74634-44.98454 83.031065-78.712713 116.759237-33.728172 33.728172-73.012897 60.211337-116.759237 78.712713-45.311998 19.156292-93.417623 28.877701-143.007041 28.877701s-97.695043-9.721409-142.996808-28.877701c-43.756573-18.501376-83.031065-44.98454-116.76947-78.712713-33.728172-33.728172-60.211337-73.012897-78.712713-116.759237-19.156292-45.301765-28.867468-93.417623-28.867468-143.007041 0-49.579185 9.711176-97.695043 28.867468-142.996808 18.501376-43.74634 44.98454-83.031065 78.712713-116.759237 33.738405-33.728172 73.012897-60.211337 116.76947-78.712713 45.301765-19.166525 93.40739-28.877701 142.996808-28.877701 52.925397 0 104.008842 11.010775 151.827941 32.745798 46.192042 20.977777 86.909395 50.79692 121.016191 88.608084 4.389984 4.860704 8.646937 9.854439 12.781094 14.97097l0-136.263453c0-11.307533 9.168824-20.466124 20.466124-20.466124 11.307533 0 20.466124 9.15859 20.466124 20.466124l0 183.64253c0 5.433756-2.148943 10.632151-5.986341 14.46955-3.847631 3.837398-9.046027 5.996574-14.479783 5.996574l-183.64253-0.020466c-11.307533 0-20.466124-9.168824-20.466124-20.466124 0-11.307533 9.168824-20.466124 20.466124-20.466124l132.293025 0.020466c-3.960195-4.952802-8.063653-9.782807-12.289907-14.479783-30.320563-33.605376-66.514903-60.098773-107.549481-78.753645-42.467207-19.289322-87.850837-29.072129-134.902456-29.072129-87.195921 0-169.172981 33.9533-230.816946 95.597265-61.654198 61.654198-95.597265 143.621025-95.597265 230.816946s33.943067 169.172981 95.597265 230.816946c61.643965 61.654198 143.621025 95.607498 230.816946 95.607498s169.172981-33.9533 230.816946-95.607498c61.654198-61.643965 95.597265-143.621025 95.597265-230.816946 0-11.2973 9.168824-20.466124 20.466124-20.466124C885.322567 485.261009 894.481158 494.429833 894.481158 505.727133z"
p-id="4866"
></path>
</svg>
</button>
</div>
<div class="divider"></div>
<UploadCard
class="bg-base-200"
upload-event={uploadBitstream}
download-event={downloadBitstream}
defaultFile={eqps.jtagBitstream}
onFinishedUpload={(file: File) => {
eqps.jtagBitstream = file;
}}
>
{" "}
</UploadCard>
</div>
); );
}, },
}); });
@@ -179,12 +64,14 @@ defineExpose({
</script> </script>
<script lang="tsx"> <script lang="tsx">
const eqps = useEquipments();
// 添加一个静态方法来获取默认props // 添加一个静态方法来获取默认props
export function getDefaultProps() { export function getDefaultProps(): MotherBoardProps {
console.log(`board监听改动: ${eqps.boardAddr}:${eqps.boardPort}`);
return { return {
size: 1, size: 1,
jtagAddr: "127.0.0.1", boardAddr: eqps.boardAddr,
jtagPort: "1234", boardPort: eqps.boardPort.toString(),
}; };
} }
</script> </script>

View File

@@ -0,0 +1,119 @@
<template>
<div>
<h1 class="font-bold text-center text-2xl">Jtag</h1>
<div class="flex flex-col">
<p class="grow">Jtag Addr: {{ props.jtagAddr }}</p>
<p class="grow">Jtag Port: {{ props.jtagPort }}</p>
<div class="flex justify-between grow">
<p>IDCode: 0x{{ jtagIDCode.toString(16).padStart(8, "0") }}</p>
<button class="btn btn-circle w-8 h-8" :onclick="getIDCode">
<svg class="icon opacity-70" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
p-id="4865" width="200" height="200">
<path
d="M894.481158 505.727133c0 49.589418-9.711176 97.705276-28.867468 143.007041-18.501376 43.74634-44.98454 83.031065-78.712713 116.759237-33.728172 33.728172-73.012897 60.211337-116.759237 78.712713-45.311998 19.156292-93.417623 28.877701-143.007041 28.877701s-97.695043-9.721409-142.996808-28.877701c-43.756573-18.501376-83.031065-44.98454-116.76947-78.712713-33.728172-33.728172-60.211337-73.012897-78.712713-116.759237-19.156292-45.301765-28.867468-93.417623-28.867468-143.007041 0-49.579185 9.711176-97.695043 28.867468-142.996808 18.501376-43.74634 44.98454-83.031065 78.712713-116.759237 33.738405-33.728172 73.012897-60.211337 116.76947-78.712713 45.301765-19.166525 93.40739-28.877701 142.996808-28.877701 52.925397 0 104.008842 11.010775 151.827941 32.745798 46.192042 20.977777 86.909395 50.79692 121.016191 88.608084 4.389984 4.860704 8.646937 9.854439 12.781094 14.97097l0-136.263453c0-11.307533 9.168824-20.466124 20.466124-20.466124 11.307533 0 20.466124 9.15859 20.466124 20.466124l0 183.64253c0 5.433756-2.148943 10.632151-5.986341 14.46955-3.847631 3.837398-9.046027 5.996574-14.479783 5.996574l-183.64253-0.020466c-11.307533 0-20.466124-9.168824-20.466124-20.466124 0-11.307533 9.168824-20.466124 20.466124-20.466124l132.293025 0.020466c-3.960195-4.952802-8.063653-9.782807-12.289907-14.479783-30.320563-33.605376-66.514903-60.098773-107.549481-78.753645-42.467207-19.289322-87.850837-29.072129-134.902456-29.072129-87.195921 0-169.172981 33.9533-230.816946 95.597265-61.654198 61.654198-95.597265 143.621025-95.597265 230.816946s33.943067 169.172981 95.597265 230.816946c61.643965 61.654198 143.621025 95.607498 230.816946 95.607498s169.172981-33.9533 230.816946-95.607498c61.654198-61.643965 95.597265-143.621025 95.597265-230.816946 0-11.2973 9.168824-20.466124 20.466124-20.466124C885.322567 485.261009 894.481158 494.429833 894.481158 505.727133z"
p-id="4866"></path>
</svg>
</button>
</div>
</div>
<div class="divider"></div>
<UploadCard class="bg-base-200" :upload-event="uploadBitstream" :download-event="downloadBitstream">
</UploadCard>
</div>
</template>
<script lang="ts" setup>
import { JtagClient } from "@/APIClient";
import z from "zod";
import UploadCard from "@/components/UploadCard.vue";
import { useDialogStore } from "@/stores/dialog";
import { isUndefined, toNumber } from "lodash";
import { ref, computed, watch } from "vue";
interface CapsProps {
jtagAddr?: string;
jtagPort?: string;
}
const props = withDefaults(defineProps<CapsProps>(), {});
const jtagController = new JtagClient();
const dialog = useDialogStore();
// 使用传入的属性或默认值
const jtagIDCode = ref(0);
const boardAddress = computed(() => props.jtagAddr);
const boardPort = computed(() =>
isUndefined(props.jtagPort) ? undefined : toNumber(props.jtagPort),
);
async function uploadBitstream(event: Event, bitstream: File) {
if (!isUndefined(boardAddress.value) || !isUndefined(boardPort.value)) {
dialog.error("开发板地址或端口空缺");
return;
}
const fileParam = {
data: bitstream,
fileName: bitstream.name,
};
try {
const resp = await jtagController.uploadBitstream(
boardAddress.value,
fileParam,
);
return resp;
} catch (e) {
dialog.error("上传错误");
}
}
async function downloadBitstream() {
if (!boardAddress.value || !boardPort.value) {
dialog.error("开发板地址或端口空缺");
return;
}
try {
const resp = await jtagController.downloadBitstream(
boardAddress.value,
boardPort.value,
);
return resp;
} catch (e) {
dialog.error("上传错误");
console.error(e);
}
}
watch([boardAddress, boardPort], () => {
if (
z.string().ip().safeParse(boardAddress).success &&
z.number().positive().safeParse(boardPort).success
)
getIDCode();
});
async function getIDCode() {
if (!boardAddress.value || !boardPort.value) {
dialog.error("开发板地址或端口空缺");
return;
}
try {
const resp = await jtagController.getDeviceIDCode(
boardAddress.value,
boardPort.value,
);
jtagIDCode.value = resp;
} catch (e) {
dialog.error("获取IDCode错误");
console.error(e);
}
}
</script>
<style scoped lang="postcss">
@import "@/assets/main.css";
</style>

View File

@@ -1,21 +1,37 @@
import { ref, computed } from 'vue' import { ref, computed } from 'vue'
import { defineStore } from 'pinia' import { defineStore } from 'pinia'
import { isUndefined } from 'lodash'; import { isString, isUndefined, toNumber } from 'lodash';
import z from "zod"
import { isNumber } from 'mathjs';
export const useEquipments = defineStore('equipments', () => { export const useEquipments = defineStore('equipments', () => {
const jtagIPAddr = ref("127.0.0.1") const boardAddr = ref("127.0.0.1")
const jtagPort = ref("1234") const boardPort = ref(1234)
function setAddr(address: string) {
if (z.string().ip("4").safeParse(address).success)
boardAddr.value = address;
}
function setPort(port: string | number) {
if (isString(port) && port.length != 0) {
const portNumber = toNumber(port);
if (z.number().nonnegative().max(65535).safeParse(portNumber).success)
boardPort.value = portNumber;
}
else if (isNumber(port)) {
if (z.number().nonnegative().max(65535).safeParse(port).success)
boardPort.value = port;
}
}
const jtagBitstream = ref<File | undefined>() const jtagBitstream = ref<File | undefined>()
const remoteUpdateIPAddr = ref("127.0.0.1")
const remoteUpdatePort = ref("1234")
const remoteUpdateBitstream = ref<File | undefined>() const remoteUpdateBitstream = ref<File | undefined>()
return { return {
jtagIPAddr, boardAddr,
jtagPort, boardPort,
setAddr,
setPort,
jtagBitstream, jtagBitstream,
remoteUpdateIPAddr,
remoteUpdatePort,
remoteUpdateBitstream, remoteUpdateBitstream,
} }
}) })

View File

@@ -1,8 +1,8 @@
<template> <template>
<div class="bg-base-200 min-h-screen p-6"> <div class="bg-base-200 min-h-screen p-6">
<div class="flex flex-row align-middle"> <div class="flex flex-row justify-between items-center">
<h1 class="text-3xl font-bold mb-6">FPGA 设备管理</h1> <h1 class="text-3xl font-bold mb-6">FPGA 设备管理</h1>
<button class="btn btn-ghost self-end" @click=" <button class="btn btn-ghost text-error hover:underline" @click="
() => { () => {
isEditMode = !isEditMode; isEditMode = !isEditMode;
} }
@@ -13,16 +13,19 @@
<div class="card bg-base-100 shadow-xl"> <div class="card bg-base-100 shadow-xl">
<div class="card-body"> <div class="card-body">
<h2 class="card-title mb-4">IP 地址列表</h2> <div class="flex flex-row justify-between items-center">
<h2 class="card-title mb-4">IP 地址列表</h2>
<button class="btn btn-ghost" @click="">刷新</button>
</div>
<div class="overflow-x-auto"> <div class="overflow-x-auto">
<table class="table w-full"> <table class="table w-full">
<!-- 表头 --> <!-- 表头 -->
<thead> <thead>
<tr class="bg-base-300"> <tr class="bg-base-300">
<th>IP 地址</th> <th class="w-50">IP 地址</th>
<th>版本号</th> <th class="w-30">版本号</th>
<th>默认启动位流</th> <th class="w-50">默认启动位流</th>
<th class="w-80">黄金位流</th> <th class="w-80">黄金位流</th>
<th class="w-80">应用位流1</th> <th class="w-80">应用位流1</th>
<th class="w-80">应用位流2</th> <th class="w-80">应用位流2</th>
@@ -35,7 +38,7 @@
<tbody> <tbody>
<tr class="hover"> <tr class="hover">
<td class="font-medium"> <td class="font-medium">
<input v-if="isEditMode" type="text" placeholder="Type here" class="input" /> <input v-if="isEditMode" type="text" placeholder="Type here" class="input m-0" v-model="devAddr" />
<span v-else>{{ devAddr }}</span> <span v-else>{{ devAddr }}</span>
</td> </td>
<td>v1.2.3</td> <td>v1.2.3</td>
@@ -50,29 +53,25 @@
<!-- 黄金位流上传区 --> <!-- 黄金位流上传区 -->
<td> <td>
<div class="flex flex-col items-center gap-2"> <div class="flex flex-col items-center gap-2">
<input type="file" class="file-input file-input-primary" <input type="file" class="file-input file-input-primary" @change="handleFileChange($event, 0)" />
@change="handleFileChange($event, goldBitstreamFile)" />
</div> </div>
</td> </td>
<!-- 应用位流1上传区 --> <!-- 应用位流1上传区 -->
<td> <td>
<div class="flex flex-col items-center gap-2"> <div class="flex flex-col items-center gap-2">
<input type="file" class="file-input file-input-secondary" <input type="file" class="file-input file-input-secondary" @change="handleFileChange($event, 1)" />
@change="handleFileChange($event, appBitstream1File)" />
</div> </div>
</td> </td>
<!-- 应用位流2上传区 --> <!-- 应用位流2上传区 -->
<td> <td>
<div class="flex flex-col items-center gap-2"> <div class="flex flex-col items-center gap-2">
<input type="file" class="file-input file-input-accent" <input type="file" class="file-input file-input-accent" @change="handleFileChange($event, 2)" />
@change="handleFileChange($event, appBitstream2File)" />
</div> </div>
</td> </td>
<!-- 应用位流3上传区 --> <!-- 应用位流3上传区 -->
<td> <td>
<div class="flex flex-col items-center gap-2"> <div class="flex flex-col items-center gap-2">
<input type="file" class="file-input file-input-info" <input type="file" class="file-input file-input-info" @change="handleFileChange($event, 3)" />
@change="handleFileChange($event, appBitstream3File)" />
</div> </div>
</td> </td>
@@ -138,7 +137,7 @@ const devPort = 1234;
const remoteUpdater = new RemoteUpdaterClient(); const remoteUpdater = new RemoteUpdaterClient();
// 处理文件上传 // 处理文件上传
function handleFileChange(event: Event, fileRef: any) { function handleFileChange(event: Event, bistreamNum: number) {
const target = event.target as HTMLInputElement; const target = event.target as HTMLInputElement;
const file = target.files?.[0]; // 获取选中的第一个文件 const file = target.files?.[0]; // 获取选中的第一个文件
@@ -146,8 +145,16 @@ function handleFileChange(event: Event, fileRef: any) {
return; return;
} }
if (!isUndefined(fileRef)) { if (bistreamNum === 0) {
fileRef.value = file; goldBitstreamFile.value = file;
} else if (bistreamNum === 1) {
appBitstream1File.value = file;
} else if (bistreamNum === 2) {
appBitstream2File.value = file;
} else if (bistreamNum === 3) {
appBitstream3File.value = file;
} else {
goldBitstreamFile.value = file;
} }
} }
@@ -172,12 +179,13 @@ async function uploadAndDownloadBitstreams(
appBitstream3?: File, appBitstream3?: File,
) { ) {
let cnt = 0; let cnt = 0;
if (isUndefined(goldBitstream)) cnt++; if (!isUndefined(goldBitstream)) cnt++;
if (isUndefined(appBitstream1)) cnt++; if (!isUndefined(appBitstream1)) cnt++;
if (isUndefined(appBitstream2)) cnt++; if (!isUndefined(appBitstream2)) cnt++;
if (isUndefined(appBitstream3)) cnt++; if (!isUndefined(appBitstream3)) cnt++;
if ((cnt = 0)) { if (cnt === 0) {
dialog.error("未选择比特流"); dialog.error("未选择比特流");
return;
} }
try { try {
@@ -189,10 +197,9 @@ async function uploadAndDownloadBitstreams(
Common.toFileParameterOrNull(appBitstream2), Common.toFileParameterOrNull(appBitstream2),
Common.toFileParameterOrNull(appBitstream3), Common.toFileParameterOrNull(appBitstream3),
); );
if (ret) { if (!ret) {
dialog.warn("上传比特流出错"); dialog.warn("上传比特流出错");
} else { return;
dialog.info("上传比特流成功");
} }
} }
{ {
@@ -230,6 +237,15 @@ async function hotresetBitstream(devAddr: string, bitstreamNum: number) {
console.error(e); console.error(e);
} }
} }
async function refreshData() {
try {
const ret = await remoteUpdater.getFirmwareVersion(devAddr.value, devPort);
} catch (e) {
dialog.error("获取数据失败");
console.error(e);
}
}
</script> </script>
<style scoped lang="postcss"> <style scoped lang="postcss">