Skip to content

Commit 3af183c

Browse files
authored
feat(IBluetootchDevice): add GetPrimaryServices method (#4504)
* refactor: 更改客户端输出 * doc: 更新示例 * refactor: 更改为错误提示信息 * refactor: 更新时区计算逻辑 * doc: 更新文档 * feat: 增加获取服务方法 * refactor: 重构代码 * feat: 增加 getPrimaryServices 方法 * feat: 增加 getCharacteristics 方法 * refactor: 增加 UUID 标签 * refactor: 更正脚本错误 * doc: 更新文档 * refactor: 标签重命名 * test: 增加单元测试 * refactor: 重构标签文件名称 * doc: 更新文档 * doc: 更新文档
1 parent c5e1e14 commit 3af183c

File tree

12 files changed

+366
-84
lines changed

12 files changed

+366
-84
lines changed

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

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,24 @@ private IBluetoothService? BluetoothService { get; set; }</Pre>
5858
}
5959
</div>
6060
</div>
61+
<div class="col-12">
62+
<Button Text="@Localizer["BluetoothGetServicesText"]" Icon="fa-solid fa-microchip" IsDisabled="@(_blueDevice is not { Connected: true })" OnClick="GetServices"></Button>
63+
</div>
64+
<div class="col-12">
65+
<Select Items="ServicesList" @bind-Value="_selectedService" class="flex-fill"></Select>
66+
</div>
67+
<div class="col-12">
68+
<Button Text="@Localizer["BluetoothGetCharacteristicsText"]" Icon="fa-solid fa-microchip" IsDisabled="@(_blueDevice is not { Connected: true })" OnClick="GetCharacteristics"></Button>
69+
</div>
70+
<div class="col-12">
71+
<Select Items="CharacteristicsList" @bind-Value="_selectedCharacteristic" class="flex-fill"></Select>
72+
</div>
73+
<div class="col-12">
74+
<Button Text="@Localizer["BluetoothReadValueText"]" Icon="fa-solid fa-microchip" IsDisabled="@(_blueDevice is not { Connected: true })" OnClick="ReadValue"></Button>
75+
</div>
76+
<div class="col-12">
77+
<Textarea Value="@_readValueString" rows="3" readonly></Textarea>
78+
</div>
6179
</div>
6280
</DemoBlock>
6381

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

Lines changed: 79 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
// See the LICENSE file in the project root for more information.
44
// Maintainer: Argo Zhang([email protected]) Website: https://www.blazor.zone
55

6+
using System.Reflection;
7+
68
namespace BootstrapBlazor.Server.Components.Samples;
79

810
/// <summary>
@@ -26,18 +28,52 @@ public partial class Bluetooth
2628

2729
private string? _currentTimeValueString = null;
2830

31+
private string? _readValueString = null;
32+
33+
private List<string> _services = [];
34+
35+
private List<string> _characteristics = [];
36+
37+
private string? _selectedService;
38+
39+
private string? _selectedCharacteristic;
40+
41+
private List<SelectedItem> ServicesList => _services.Select(i => new SelectedItem(i, FormatServiceName(i))).ToList();
42+
43+
private List<SelectedItem> CharacteristicsList => _characteristics.Select(i => new SelectedItem(i, FormatCharacteristicsName(i))).ToList();
44+
45+
private Dictionary<string, string> ServiceUUIDList = [];
46+
47+
/// <summary>
48+
/// <inheritdoc />
49+
/// </summary>
50+
protected override void OnInitialized()
51+
{
52+
base.OnInitialized();
53+
54+
ServiceUUIDList = Enum.GetNames(typeof(BluetoothServicesEnum)).Select(i =>
55+
{
56+
var attributes = typeof(BluetoothServicesEnum).GetField(i)!.GetCustomAttribute<BluetoothUUIDAttribute>(false)!;
57+
return new KeyValuePair<string, string>(attributes.Name.ToUpperInvariant(), i);
58+
}).ToDictionary();
59+
}
60+
61+
private string FormatServiceName(string serviceName)
62+
{
63+
var name = ServiceUUIDList[serviceName.ToUpperInvariant()];
64+
return $"{name}({serviceName.ToUpperInvariant()})";
65+
}
66+
67+
private string FormatCharacteristicsName(string characteristicName) => characteristicName.ToUpperInvariant();
68+
2969
private async Task RequestDevice()
3070
{
31-
_blueDevice = await BluetoothService.RequestDevice(new BluetoothRequestOptions()
71+
var options = new BluetoothRequestOptions()
3272
{
33-
Filters = [
34-
new BluetoothFilter()
35-
{
36-
NamePrefix = "Argo"
37-
}
38-
],
39-
OptionalServices = ["device_information"]
40-
});
73+
AcceptAllDevices = true,
74+
OptionalServices = ["device_information", "current_time", "battery_service"]
75+
};
76+
_blueDevice = await BluetoothService.RequestDevice(options);
4177
if (BluetoothService.IsSupport == false)
4278
{
4379
await ToastService.Error(Localizer["NotSupportBluetoothTitle"], Localizer["NotSupportBluetoothContent"]);
@@ -75,6 +111,10 @@ private async Task Disconnect()
75111
{
76112
_batteryValue = null;
77113
_batteryValueString = null;
114+
_deviceInfoList.Clear();
115+
_services.Clear();
116+
_characteristics.Clear();
117+
_readValueString = null;
78118
}
79119
}
80120
}
@@ -102,7 +142,7 @@ private async Task GetTimeValue()
102142
{
103143
_currentTimeValueString = null;
104144

105-
if(_blueDevice != null)
145+
if (_blueDevice != null)
106146
{
107147
var val = await _blueDevice.GetCurrentTime();
108148
if (val.HasValue && !string.IsNullOrEmpty(_blueDevice.ErrorMessage))
@@ -129,4 +169,33 @@ private async Task GetDeviceInfoValue()
129169
_deviceInfoList.Add($"Software Revision: {info?.SoftwareRevision}");
130170
}
131171
}
172+
173+
private async Task GetServices()
174+
{
175+
if (_blueDevice != null)
176+
{
177+
_services = await _blueDevice.GetPrimaryServices();
178+
}
179+
}
180+
181+
private async Task GetCharacteristics()
182+
{
183+
if (_blueDevice != null && !string.IsNullOrEmpty(_selectedService))
184+
{
185+
_characteristics = await _blueDevice.GetCharacteristics(_selectedService);
186+
}
187+
}
188+
189+
private async Task ReadValue()
190+
{
191+
_readValueString = null;
192+
if (_blueDevice != null && !string.IsNullOrEmpty(_selectedService) && !string.IsNullOrEmpty(_selectedCharacteristic))
193+
{
194+
var data = await _blueDevice.ReadValue(_selectedService, _selectedCharacteristic);
195+
if (data != null)
196+
{
197+
_readValueString = string.Join(" ", data.Select(i => Convert.ToString(i, 16).PadLeft(2, '0').ToUpperInvariant()));
198+
}
199+
}
200+
}
132201
}

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5904,7 +5904,10 @@
59045904
"BaseUsageIntro": "Request communication with Bluetooth devices through the <code>IBluetoothService</code> service",
59055905
"BluetoothGetCurrentTimeText": "Time",
59065906
"BluetoothDeviceInfoText": "Device Info",
5907-
"UsageDesc": "Click the Scan button and select the phone to test in the pop-up window"
5907+
"UsageDesc": "Click the Scan button and select the phone to test in the pop-up window",
5908+
"BluetoothGetServicesText": "Services",
5909+
"BluetoothGetCharacteristicsText": "Characteristics",
5910+
"BluetoothReadValueText": "ReadValue"
59085911
},
59095912
"BootstrapBlazor.Server.Components.Samples.FileIcons": {
59105913
"Title": "File Icon",

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5904,7 +5904,10 @@
59045904
"BaseUsageIntro": "通过 <code>IBluetoothService</code> 服务,请求与蓝牙设备通讯",
59055905
"BluetoothGetCurrentTimeText": "读取时间",
59065906
"BluetoothDeviceInfoText": "读取硬件信息",
5907-
"UsageDesc": "点击扫描按钮,在弹窗中选中手机进行测试"
5907+
"UsageDesc": "点击扫描按钮,在弹窗中选中手机进行测试",
5908+
"BluetoothGetServicesText": "读取服务列表",
5909+
"BluetoothGetCharacteristicsText": "读取特征列表",
5910+
"BluetoothReadValueText": "读取特征值"
59085911
},
59095912
"BootstrapBlazor.Server.Components.Samples.FileIcons": {
59105913
"Title": "File Icon 文件图标",

src/BootstrapBlazor/Extensions/BluetoothExtensions.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,10 @@ public static class BluetoothExtensions
1818
/// </summary>
1919
/// <param name="services"></param>
2020
/// <returns></returns>
21-
public static List<string> GetServicesList(this IEnumerable<BluetoothServices> services) => services.Select(i =>
21+
public static List<string> GetServicesList(this IEnumerable<BluetoothServicesEnum> services) => services.Select(i =>
2222
{
2323
var v = i.ToString();
24-
var attributes = typeof(BluetoothServices).GetField(v)!.GetCustomAttribute<JsonPropertyNameAttribute>(false)!;
24+
var attributes = typeof(BluetoothServicesEnum).GetField(v)!.GetCustomAttribute<JsonPropertyNameAttribute>(false)!;
2525
return attributes.Name;
2626
}).ToList();
2727
}

src/BootstrapBlazor/Services/Bluetooth/BluetoothDevice.cs

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,47 @@ public async Task<bool> Disconnect(CancellationToken token = default)
8484
return ret;
8585
}
8686

87+
/// <summary>
88+
/// <inheritdoc />
89+
/// </summary>
90+
/// <param name="token"></param>
91+
/// <returns></returns>
92+
public async Task<List<string>> GetPrimaryServices(CancellationToken token = default)
93+
{
94+
var ret = new List<string>();
95+
if (Connected)
96+
{
97+
ErrorMessage = null;
98+
var services = await _module.InvokeAsync<List<string>?>("getPrimaryServices", token, _clientId, _interop, nameof(OnError));
99+
if (services != null)
100+
{
101+
ret.AddRange(services);
102+
}
103+
}
104+
return ret;
105+
}
106+
107+
/// <summary>
108+
/// <inheritdoc />
109+
/// </summary>
110+
/// <param name="serviceName"></param>
111+
/// <param name="token"></param>
112+
/// <returns></returns>
113+
public async Task<List<string>> GetCharacteristics(string serviceName, CancellationToken token = default)
114+
{
115+
var ret = new List<string>();
116+
if (Connected)
117+
{
118+
ErrorMessage = null;
119+
var characteristics = await _module.InvokeAsync<List<string>?>("getCharacteristics", token, _clientId, serviceName, _interop, nameof(OnError));
120+
if (characteristics != null)
121+
{
122+
ret.AddRange(characteristics);
123+
}
124+
}
125+
return ret;
126+
}
127+
87128
/// <summary>
88129
/// <inheritdoc/>
89130
/// </summary>
@@ -100,7 +141,7 @@ public async Task<bool> Disconnect(CancellationToken token = default)
100141
}
101142

102143
/// <summary>
103-
/// <inheritdoc />
144+
/// <inheritdoc/>
104145
/// </summary>
105146
/// <param name="token"></param>
106147
/// <returns></returns>

src/BootstrapBlazor/Services/Bluetooth/BluetoothRequestOptions.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,10 +48,10 @@ public class BluetoothRequestOptions
4848
/// 获得所有蓝牙服务
4949
/// </summary>
5050
/// <returns></returns>
51-
public static List<string> GetAllServices() => Enum.GetNames(typeof(BluetoothServices)).Select(i =>
51+
public static List<string> GetAllServices() => typeof(BluetoothServicesEnum).GetEnumNames().Select(i =>
5252
{
5353
var v = i.ToString();
54-
var attributes = typeof(BluetoothServices).GetField(v)!.GetCustomAttribute<JsonPropertyNameAttribute>(false)!;
54+
var attributes = typeof(BluetoothServicesEnum).GetField(v)!.GetCustomAttribute<JsonPropertyNameAttribute>(false)!;
5555
return attributes.Name;
5656
}).ToList();
5757
}

0 commit comments

Comments
 (0)