Skip to content

Commit 5c89f41

Browse files
committed
doc: 更新文档
1 parent d9bddcb commit 5c89f41

File tree

4 files changed

+80
-206
lines changed

4 files changed

+80
-206
lines changed

src/BootstrapBlazor.Server/Components/Samples/WebSerials.razor

Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,8 +71,55 @@ private ISerialService? SerialService { get; set; }</Pre>
7171
</GroupBox>
7272
</DemoBlock>
7373

74+
<p class="code-label mt-3">1. 服务注入</p>
7475

75-
<AttributeTable Items="@GetAttributes()" />
76+
<Pre>[Inject]
77+
[NotNull]
78+
private ISerialService? SerialService { get; set; }</Pre>
79+
80+
<p class="code-label">2. 申请串口权限</p>
81+
<p>调用 <code>SerialService</code> 实例方法 <code>GetPort</code> 即可,通过 <code>IsSupport</code> 进行浏览器是否支持判断</p>
82+
83+
<Pre>_serialPort = await SerialService.GetPort();
84+
if (SerialService.IsSupport == false)
85+
{
86+
await ToastService.Error(Localizer["NotSupportSerialTitle"], Localizer["NotSupportSerialContent"]);
87+
}</Pre>
88+
89+
<p class="code-label">3. 打开串口</p>
7690

77-
<AttributeTable Title="@Localizer["WebSerialOptionsText"]" Items="@GetWebSerialOptionsAttributes()" />
91+
<ul class="ul-demo">
92+
<li>如果需要读取数据,请先设置 <code>ISerialPort</code> 实例 <code>DataReceive</code> 参数</li>
93+
<li>调用 <code>ISerialPort</code> 实例方法 <code>Open</code> 打开串口,可通过参数设置 <code>波特率</code> 等信息</li>
94+
</ul>
7895

96+
<Pre>private async Task OpenPort()
97+
{
98+
if (_serialPort != null)
99+
{
100+
_serialPort.DataReceive = async data =>
101+
{
102+
_messages.Add(new ConsoleMessageItem()
103+
{
104+
IsHtml = true,
105+
Message = $"{DateTime.Now}: --> Text: {Encoding.ASCII.GetString(data)} HEX: {Convert.ToHexString(data)}"
106+
});
107+
await InvokeAsync(StateHasChanged);
108+
};
109+
await _serialPort.Open(_serialOptions);
110+
}
111+
}</Pre>
112+
113+
<p class="code-label">4. 关闭串口</p>
114+
115+
<p>调用 <code>ISerialPort</code> 实例方法 <code>Close</code> 关闭串口,请注意路由切换时,请调用其 <code>DisposeAsync</code> 方法释放资源</p>
116+
117+
<Pre>private async Task ClosePort()
118+
{
119+
if (_serialPort != null)
120+
{
121+
await _serialPort.Close();
122+
}
123+
}</Pre>
124+
125+
<AttributeTable Items="@GetAttributes()" />

src/BootstrapBlazor.Server/Components/Samples/WebSerials.razor.cs

Lines changed: 21 additions & 202 deletions
Original file line numberDiff line numberDiff line change
@@ -9,19 +9,14 @@ namespace BootstrapBlazor.Server.Components.Samples;
99
/// <summary>
1010
/// WebSerials 组件
1111
/// </summary>
12-
public partial class WebSerials : IDisposable
12+
public partial class WebSerials : IAsyncDisposable
1313
{
1414
private string _sendData = "";
1515
private int _sendInterval = 1000;
1616
private bool _appendCRLF;
1717
private bool _isHEX;
1818
private bool _isLoop;
19-
private ConsoleMessageCollection _messages = new(8);
20-
21-
private string? _message;
22-
private string? _statusMessage;
23-
private string? _errorMessage;
24-
private readonly WebSerialOptions options = new() { BaudRate = 115200, AutoGetSignals = true };
19+
private readonly ConsoleMessageCollection _messages = new(8);
2520

2621
private readonly List<SelectedItem> _baudRateList =
2722
[
@@ -45,21 +40,15 @@ public partial class WebSerials : IDisposable
4540

4641
private readonly List<SelectedItem> _stopBits = [new("1", "1"), new("2", "2")];
4742

48-
private bool Flag { get; set; }
49-
50-
private bool IsConnected { get; set; }
51-
52-
/// <summary>
53-
/// 收到的信号数据
54-
/// </summary>
55-
public WebSerialSignals Signals { get; set; } = new WebSerialSignals();
56-
5743
[Inject, NotNull]
5844
private ISerialService? SerialService { get; set; }
5945

46+
[Inject, NotNull]
47+
private ToastService? ToastService { get; set; }
48+
6049
private ISerialPort? _serialPort;
6150

62-
private SerialOptions _serialOptions = new();
51+
private readonly SerialOptions _serialOptions = new();
6352

6453
private bool CheckOpen => _serialPort is not { IsOpen: false };
6554

@@ -68,6 +57,10 @@ public partial class WebSerials : IDisposable
6857
private async Task GetPort()
6958
{
7059
_serialPort = await SerialService.GetPort();
60+
if (SerialService.IsSupport == false)
61+
{
62+
await ToastService.Error(Localizer["NotSupportSerialTitle"], Localizer["NotSupportSerialContent"]);
63+
}
7164
}
7265

7366
private async Task OpenPort()
@@ -84,6 +77,11 @@ private async Task OpenPort()
8477
await InvokeAsync(StateHasChanged);
8578
};
8679
await _serialPort.Open(_serialOptions);
80+
81+
if (_serialPort.IsOpen == false)
82+
{
83+
await ToastService.Error(Localizer["OpenPortSerialTitle"], Localizer["OpenPortSerialContent"]);
84+
}
8785
}
8886
}
8987

@@ -151,60 +149,6 @@ private static byte[] ConvertToHex(string data)
151149
return [.. ret];
152150
}
153151

154-
private Task OnSignals(WebSerialSignals? signals)
155-
{
156-
if (signals is null) return Task.CompletedTask;
157-
158-
Signals = signals;
159-
160-
if (!options.AutoGetSignals)
161-
{
162-
// 仅在不自动获取信号时才显示
163-
_message = $"{DateTime.Now:hh:mm:ss} 收到信号数据: {Environment.NewLine}" +
164-
$"RING: {signals.RING}{Environment.NewLine}" +
165-
$"DSR: {signals.DSR}{Environment.NewLine}" +
166-
$"CTS: {signals.CTS}{Environment.NewLine}" +
167-
$"DCD: {signals.DCD}{Environment.NewLine}" +
168-
$"{_message}{Environment.NewLine}";
169-
}
170-
171-
StateHasChanged();
172-
return Task.CompletedTask;
173-
}
174-
175-
private Task OnConnect(bool flag)
176-
{
177-
IsConnected = flag;
178-
if (flag)
179-
{
180-
_message = null;
181-
_statusMessage = null;
182-
_errorMessage = null;
183-
}
184-
StateHasChanged();
185-
return Task.CompletedTask;
186-
}
187-
188-
private Task OnLog(string message)
189-
{
190-
_statusMessage = message;
191-
StateHasChanged();
192-
return Task.CompletedTask;
193-
}
194-
195-
private Task OnError(string message)
196-
{
197-
_errorMessage = message;
198-
StateHasChanged();
199-
return Task.CompletedTask;
200-
}
201-
202-
private void OnApply()
203-
{
204-
//options.BaudRate = SelectedBaudRate;
205-
//Flag = !Flag;
206-
}
207-
208152
/// <summary>
209153
/// 获得属性方法
210154
/// </summary>
@@ -292,151 +236,26 @@ private static AttributeItem[] GetAttributes() =>
292236
}
293237
];
294238

295-
/// <summary>s
296-
/// 获得WebSerialOptions属性方法
297-
/// </summary>
298-
/// <returns></returns>
299-
private static AttributeItem[] GetWebSerialOptionsAttributes() =>
300-
[
301-
new()
302-
{
303-
Name = "BaudRate",
304-
Description = "波特率",
305-
Type = "int",
306-
ValueList = "-",
307-
DefaultValue = "9600"
308-
},
309-
new()
310-
{
311-
Name = "DataBits",
312-
Description = "数据位",
313-
Type = "int",
314-
ValueList = "7|8",
315-
DefaultValue = "8"
316-
},
317-
new()
318-
{
319-
Name = "StopBits",
320-
Description = "停止位",
321-
Type = "int",
322-
ValueList = "1|2",
323-
DefaultValue = "1"
324-
},
325-
new()
326-
{
327-
Name = "ParityType",
328-
Description = "流控制",
329-
Type = "WebSerialFlowControlType",
330-
ValueList = "none|even|odd",
331-
DefaultValue = "none"
332-
},
333-
new()
334-
{
335-
Name = "BufferSize",
336-
Description = "读写缓冲区",
337-
Type = "int",
338-
ValueList = "-",
339-
DefaultValue = "255"
340-
},
341-
new()
342-
{
343-
Name = "FlowControlType",
344-
Description = "校验",
345-
Type = "WebSerialParityType",
346-
ValueList = "none|hardware",
347-
DefaultValue = "none"
348-
},
349-
new()
350-
{
351-
Name =nameof(WebSerialOptions.InputWithHex),
352-
Description = "HEX发送",
353-
Type = "bool",
354-
ValueList = "-",
355-
DefaultValue = "false"
356-
},
357-
new()
358-
{
359-
Name =nameof(WebSerialOptions.OutputInHex),
360-
Description = "HEX接收",
361-
Type = "bool",
362-
ValueList = "-",
363-
DefaultValue ="false"
364-
},
365-
new()
366-
{
367-
Name =nameof(WebSerialOptions.AutoConnect),
368-
Description = "自动连接设备",
369-
Type = "bool",
370-
ValueList = "-",
371-
DefaultValue ="true"
372-
},
373-
new()
374-
{
375-
Name =nameof(WebSerialOptions.AutoFrameBreakType),
376-
Description = "自动断帧方式",
377-
Type = "AutoFrameBreakType",
378-
ValueList = "-",
379-
DefaultValue ="Character"
380-
},
381-
new(){
382-
Name =nameof(WebSerialOptions.FrameBreakChar),
383-
Description = "断帧字符",
384-
Type = "string",
385-
ValueList = "-",
386-
DefaultValue ="\\n"
387-
},
388-
new()
389-
{
390-
Name = nameof(WebSerialOptions.ConnectBtnTitle),
391-
Description = "获得/设置 连接按钮文本",
392-
Type = "string",
393-
ValueList = "",
394-
DefaultValue = "连接"
395-
},
396-
new()
397-
{
398-
Name = nameof(WebSerialOptions.DisconnectBtnTitle),
399-
Description = "获得/设置 断开连接按钮文本",
400-
Type = "string",
401-
ValueList = "",
402-
DefaultValue = "连接"
403-
},
404-
new()
405-
{
406-
Name = nameof(WebSerialOptions.WriteBtnTitle),
407-
Description = "获得/设置 写入按钮文本",
408-
Type = "string",
409-
ValueList = "",
410-
DefaultValue = "写入"
411-
},
412-
new()
413-
{
414-
Name = nameof(WebSerialOptions.AutoGetSignals),
415-
Description = "获得/设置 自动检查状态",
416-
Type = "bool",
417-
ValueList = "-",
418-
DefaultValue ="false"
419-
}
420-
];
421-
422-
private void Dispose(bool disposing)
239+
private async ValueTask DisposeAsync(bool disposing)
423240
{
424241
if (disposing)
425-
{
426242
if (_loopSendTokenSource != null)
427243
{
428244
_loopSendTokenSource.Cancel();
429245
_loopSendTokenSource = null;
430246
}
247+
if (_serialPort != null)
248+
{
249+
await _serialPort.DisposeAsync();
431250
}
432251
}
433252

434253
/// <summary>
435254
/// <inheritdoc/>
436255
/// </summary>
437-
public void Dispose()
256+
public async ValueTask DisposeAsync()
438257
{
439-
Dispose(true);
258+
await DisposeAsync(true);
440259
GC.SuppressFinalize(this);
441260
}
442261
}

src/BootstrapBlazor.Server/Locales/en-US.json

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6319,7 +6319,11 @@
63196319
"LoopIntervalText": "Interval(ms)",
63206320
"WebSerialTipsLi1": "This feature is available only in secure contexts (HTTPS)",
63216321
"WebSerialTipsLi2": "This is an experimental technology Check the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/SerialPort#browser_compatibility\" target=\"_blank\">Browser compatibility table</a> carefully before using this in production",
6322-
"WebSerialTipsTitle": ""
6322+
"WebSerialTipsTitle": "Note: The <code>ISerialPort</code> interface instance inherits <code>IAsyncDisposable</code>. When switching routes, you need to release its resources by calling its <code>DisposeAsync</code>",
6323+
"NotSupportSerialTitle": "Get Port",
6324+
"NotSupportSerialContent": "The current browser does not support serial port operations. Please change to Edge or Chrome browser.",
6325+
"OpenPortSerialTitle": "Open Port",
6326+
"OpenPortSerialContent": "Failed to open the serial port"
63236327
},
63246328
"BootstrapBlazor.Server.Components.Samples.MindMaps": {
63256329
"MindMapTitle": "Mind Map",

src/BootstrapBlazor.Server/Locales/zh-CN.json

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6319,7 +6319,11 @@
63196319
"LoopIntervalText": "发送间隔(ms)",
63206320
"WebSerialTipsLi1": "该功能仅在部分或所有支持浏览器的安全上下文(HTTPS)中可用",
63216321
"WebSerialTipsLi2": "这是一项实验性技术,在生产中使用之前请仔细,检查 <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/SerialPort#browser_compatibility\" target=\"_blank\">浏览器兼容性表</a>",
6322-
"WebSerialTipsTitle": ""
6322+
"WebSerialTipsTitle": "注意:<code>ISerialPort</code> 接口实例继承 <code>IAsyncDisposable</code> 路由切换时需要对其进行资源释放,调用其 <code>DisposeAsync</code> 即可",
6323+
"NotSupportSerialTitle": "申请串口权限",
6324+
"NotSupportSerialContent": "当前浏览器不支持串口操作,请更换 Edge 或者 Chrome 浏览器",
6325+
"OpenPortSerialTitle": "打开串口操作",
6326+
"OpenPortSerialContent": "打开串口失败"
63236327
},
63246328
"BootstrapBlazor.Server.Components.Samples.MindMaps": {
63256329
"MindMapTitle": "Mind Map 思维导图",

0 commit comments

Comments
 (0)