├── .gitattributes ├── .gitignore ├── README.md ├── UnitTestProject1 ├── Properties │ └── AssemblyInfo.cs ├── UnitTest1.cs └── UnitTestProject1.csproj ├── WpfBleApp.sln └── WpfBleApp ├── App.config ├── App.xaml ├── App.xaml.cs ├── Ble ├── BleDevice.cs ├── BleExtensions.cs ├── BleManager.cs └── Uuids.cs ├── CommPage.xaml ├── CommPage.xaml.cs ├── MainWindow.xaml ├── MainWindow.xaml.cs ├── Model ├── CommPageViewModel.cs ├── ObservableObject.cs └── ScanPageViewModel.cs ├── Properties ├── Resources.Designer.cs ├── Resources.resx ├── Settings.Designer.cs └── Settings.settings ├── ScanPage.xaml ├── ScanPage.xaml.cs ├── Utils ├── Extensions.cs └── Log.cs ├── Widget └── AutoScrollListBox.cs └── WpfBleApp.csproj /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Oo]ut/ 33 | [Ll]og/ 34 | [Ll]ogs/ 35 | 36 | # Visual Studio 2015/2017 cache/options directory 37 | .vs/ 38 | # Uncomment if you have tasks that create the project's static files in wwwroot 39 | #wwwroot/ 40 | 41 | # Visual Studio 2017 auto generated files 42 | Generated\ Files/ 43 | 44 | # MSTest test Results 45 | [Tt]est[Rr]esult*/ 46 | [Bb]uild[Ll]og.* 47 | 48 | # NUnit 49 | *.VisualState.xml 50 | TestResult.xml 51 | nunit-*.xml 52 | 53 | # Build Results of an ATL Project 54 | [Dd]ebugPS/ 55 | [Rr]eleasePS/ 56 | dlldata.c 57 | 58 | # Benchmark Results 59 | BenchmarkDotNet.Artifacts/ 60 | 61 | # .NET Core 62 | project.lock.json 63 | project.fragment.lock.json 64 | artifacts/ 65 | 66 | # ASP.NET Scaffolding 67 | ScaffoldingReadMe.txt 68 | 69 | # StyleCop 70 | StyleCopReport.xml 71 | 72 | # Files built by Visual Studio 73 | *_i.c 74 | *_p.c 75 | *_h.h 76 | *.ilk 77 | *.meta 78 | *.obj 79 | *.iobj 80 | *.pch 81 | *.pdb 82 | *.ipdb 83 | *.pgc 84 | *.pgd 85 | *.rsp 86 | *.sbr 87 | *.tlb 88 | *.tli 89 | *.tlh 90 | *.tmp 91 | *.tmp_proj 92 | *_wpftmp.csproj 93 | *.log 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio LightSwitch build output 298 | **/*.HTMLClient/GeneratedArtifacts 299 | **/*.DesktopClient/GeneratedArtifacts 300 | **/*.DesktopClient/ModelManifest.xml 301 | **/*.Server/GeneratedArtifacts 302 | **/*.Server/ModelManifest.xml 303 | _Pvt_Extensions 304 | 305 | # Paket dependency manager 306 | .paket/paket.exe 307 | paket-files/ 308 | 309 | # FAKE - F# Make 310 | .fake/ 311 | 312 | # CodeRush personal settings 313 | .cr/personal 314 | 315 | # Python Tools for Visual Studio (PTVS) 316 | __pycache__/ 317 | *.pyc 318 | 319 | # Cake - Uncomment if you are using it 320 | # tools/** 321 | # !tools/packages.config 322 | 323 | # Tabs Studio 324 | *.tss 325 | 326 | # Telerik's JustMock configuration file 327 | *.jmconfig 328 | 329 | # BizTalk build output 330 | *.btp.cs 331 | *.btm.cs 332 | *.odx.cs 333 | *.xsd.cs 334 | 335 | # OpenCover UI analysis results 336 | OpenCover/ 337 | 338 | # Azure Stream Analytics local run output 339 | ASALocalRun/ 340 | 341 | # MSBuild Binary and Structured Log 342 | *.binlog 343 | 344 | # NVidia Nsight GPU debugger configuration file 345 | *.nvuser 346 | 347 | # MFractors (Xamarin productivity tool) working folder 348 | .mfractor/ 349 | 350 | # Local History for Visual Studio 351 | .localhistory/ 352 | 353 | # BeatPulse healthcheck temp database 354 | healthchecksdb 355 | 356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 357 | MigrationBackup/ 358 | 359 | # Ionide (cross platform F# VS Code tools) working folder 360 | .ionide/ 361 | 362 | # Fody - auto-generated XML schema 363 | FodyWeavers.xsd -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # WpfBleApp 2 | 使用WPF编写的BLE(低功耗蓝牙)应用 3 | 4 | 相关引用的添加以及应用界面截图,[参考博文](https://blog.csdn.net/jjf19891208/article/details/128173735?csdn_share_tail=%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22article%22%2C%22rId%22%3A%22128173735%22%2C%22source%22%3A%22jjf19891208%22%7D) 5 | -------------------------------------------------------------------------------- /UnitTestProject1/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | [assembly: AssemblyTrademark("")] 5 | [assembly: AssemblyCulture("")] 6 | 7 | [assembly: ComVisible(false)] 8 | 9 | [assembly: Guid("9d05234c-1e00-4ef9-b4bd-5f25dbc6743e")] 10 | -------------------------------------------------------------------------------- /UnitTestProject1/UnitTest1.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using System; 3 | 4 | namespace UnitTestProject1 5 | { 6 | [TestClass] 7 | public class UnitTest1 8 | { 9 | [TestMethod] 10 | public void TestMethod1() 11 | { 12 | short rssi = -50; 13 | int i = rssi; 14 | Console.WriteLine($"i={i}"); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /UnitTestProject1/UnitTestProject1.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | net6.0 4 | false 5 | UnitTestProject1 6 | UnitTestProject1 7 | Copyright © 2022 8 | 1.0.0.0 9 | 1.0.0.0 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /WpfBleApp.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.32413.511 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WpfBleApp", "WpfBleApp\WpfBleApp.csproj", "{7B23D211-F9E4-40C9-AAF7-D7E1A895E7CF}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UnitTestProject1", "UnitTestProject1\UnitTestProject1.csproj", "{9D05234C-1E00-4EF9-B4BD-5F25DBC6743E}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {7B23D211-F9E4-40C9-AAF7-D7E1A895E7CF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {7B23D211-F9E4-40C9-AAF7-D7E1A895E7CF}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {7B23D211-F9E4-40C9-AAF7-D7E1A895E7CF}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {7B23D211-F9E4-40C9-AAF7-D7E1A895E7CF}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {9D05234C-1E00-4EF9-B4BD-5F25DBC6743E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {9D05234C-1E00-4EF9-B4BD-5F25DBC6743E}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {9D05234C-1E00-4EF9-B4BD-5F25DBC6743E}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {9D05234C-1E00-4EF9-B4BD-5F25DBC6743E}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {C628283C-B479-4FBF-8226-F6EBB60011E0} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /WpfBleApp/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /WpfBleApp/App.xaml: -------------------------------------------------------------------------------- 1 |  6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /WpfBleApp/App.xaml.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Configuration; 4 | using System.Data; 5 | using System.Linq; 6 | using System.Threading.Tasks; 7 | using System.Windows; 8 | 9 | namespace WpfBleApp 10 | { 11 | /// 12 | /// App.xaml 的交互逻辑 13 | /// 14 | public partial class App : Application 15 | { 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /WpfBleApp/Ble/BleDevice.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using Windows.Devices.Bluetooth; 6 | using Windows.Devices.Bluetooth.Advertisement; 7 | using Windows.Devices.Bluetooth.GenericAttributeProfile; 8 | using Windows.Devices.Enumeration; 9 | using Windows.Foundation; 10 | using Windows.Storage.Streams; 11 | using WpfBleApp.Model; 12 | using WpfBleApp.Utils; 13 | 14 | using CharacteristicDictionary = System.Collections.Generic.Dictionary>; 15 | 16 | //线程安全的版本,考虑到连接后不会更改。还是使用性能更好的 Dictionary 17 | //using ConcurrentGattDictionary = System.Collections.Concurrent.ConcurrentDictionary>; 18 | 19 | namespace WpfBleApp.Ble 20 | { 21 | public class BleDevice : ObservableObject 22 | { 23 | private readonly DeviceInformation _deviceInfo; 24 | private BluetoothLEDevice _device; 25 | private GattCharacteristic CharacteristicWrite; 26 | private GattCharacteristic CharacteristicNotify; 27 | private string _mac; 28 | private string _name; 29 | private byte[] _mfrData; 30 | private int _rssi; 31 | 32 | private readonly List GattServices = new List(); 33 | private readonly CharacteristicDictionary GattCharacteristics = new CharacteristicDictionary(); 34 | 35 | public event TypedEventHandler CharacteristicValueChanged; 36 | public event TypedEventHandler ConnectionStateChanged; 37 | 38 | public BleDevice() { } 39 | 40 | public BleDevice(DeviceInformation deviceInfo) 41 | { 42 | _deviceInfo = deviceInfo; 43 | _mac = deviceInfo.Mac(); 44 | _name = deviceInfo.Name; 45 | 46 | Log.Info("################# BleDevice #################"); 47 | foreach (KeyValuePair item in deviceInfo.Properties) 48 | { 49 | Log.Info($"{item.Key}={item.Value}"); 50 | } 51 | } 52 | 53 | public void Update(BleDevice other) 54 | { 55 | Name = other.Name; 56 | MfrData = other.MfrData; 57 | RSSI = other.RSSI; 58 | } 59 | 60 | public void Update(BluetoothLEAdvertisementReceivedEventArgs args) 61 | { 62 | //通过方法属性更新是为了通知UI刷新 63 | string localName = args.LocalName(); 64 | //有可能是广播回应包,不带LocalName,防止显示不出真实的名称 65 | if (!string.IsNullOrEmpty(localName)) 66 | { 67 | Name = localName; 68 | } 69 | 70 | byte[] mfrData = args.MfrData(); 71 | if (mfrData != null) 72 | { 73 | MfrData = args.MfrData(); 74 | } 75 | RSSI = args.RawSignalStrengthInDBm; 76 | } 77 | 78 | public byte[] MfrData 79 | { 80 | get => _mfrData; 81 | set 82 | { 83 | Set(ref _mfrData, value); 84 | OnPropertyChanged(nameof(MfrDataHex)); 85 | } 86 | } 87 | 88 | public string MfrDataHex => _mfrData?.ToHex(); 89 | 90 | public int RSSI 91 | { 92 | get => -_rssi; 93 | set => Set(ref _rssi, value); 94 | } 95 | 96 | public string Name 97 | { 98 | get => string.IsNullOrEmpty(_name) ? "Unknown Device" : _name; 99 | set => Set(ref _name, value); 100 | } 101 | 102 | //System.Devices.Aep.DeviceAddress 103 | public string Mac => _mac; 104 | 105 | public string Id => _deviceInfo.Id; 106 | 107 | public bool IsConnected => _device != null && _device.ConnectionStatus == BluetoothConnectionStatus.Connected; 108 | 109 | /// 110 | /// 连接设备 111 | /// 112 | public async void Connect() 113 | { 114 | //使用自定义的拓展方法 GetResultAsync() 115 | _device = await BluetoothLEDevice.FromIdAsync(Id); 116 | //监听连接状态 117 | _device.ConnectionStatusChanged += _device_ConnectionStatusChanged; 118 | Log.Info($"{DateTime.Now:HH:mm:ss.fff} - 开始连接: " + _device); 119 | DiscoverServices(); 120 | } 121 | 122 | private void _device_ConnectionStatusChanged(BluetoothLEDevice sender, object args) 123 | { 124 | Log.Info("_device_ConnectionStatusChanged() - ConnectionStatus=" + sender.ConnectionStatus); 125 | if (sender.ConnectionStatus == BluetoothConnectionStatus.Connected) 126 | { 127 | } 128 | else 129 | { 130 | Disconnected(); 131 | ConnectionStateChanged?.Invoke(this, false); 132 | } 133 | } 134 | 135 | private async void DiscoverServices() 136 | { 137 | GattServices.Clear(); 138 | GattCharacteristics.Clear(); 139 | 140 | GattDeviceServicesResult servicesResult = await _device.GetGattServicesAsync(); 141 | if (servicesResult.Status == GattCommunicationStatus.Success) 142 | { 143 | foreach (GattDeviceService service in servicesResult.Services) 144 | { 145 | //存储该服务下的特征值 146 | Dictionary characteristics = new Dictionary(); 147 | 148 | string serviceUuid = service.Uuid.ToString(); 149 | Log.Info($"Gatt Service: {serviceUuid}"); 150 | GattCharacteristicsResult characteristicsResult = await service.GetCharacteristicsAsync(); 151 | if (characteristicsResult.Status == GattCommunicationStatus.Success) 152 | { 153 | foreach (GattCharacteristic characteristic in characteristicsResult.Characteristics) 154 | { 155 | //存储该特征值 156 | characteristics[characteristic.Uuid.ToString()] = characteristic; 157 | 158 | string characteristicUuid = characteristic.Uuid.ToString(); 159 | Log.Info($"\tGatt Characteristic: {characteristicUuid}"); 160 | if (serviceUuid == Uuids.SERVICE) 161 | { 162 | if (characteristicUuid == Uuids.WRITE) 163 | { 164 | CharacteristicWrite = characteristic; 165 | } 166 | else if (characteristicUuid == Uuids.NOTIFY) 167 | { 168 | CharacteristicNotify = characteristic; 169 | } 170 | } 171 | } 172 | } 173 | GattCharacteristics[service.Uuid.ToString()] = characteristics; 174 | GattServices.Add(service); 175 | } 176 | //订阅通知 177 | if (CharacteristicNotify != null) 178 | { 179 | //需得用一个全局变量保持对 ValueChanged 回调函数的引用,不然收不到数据 180 | CharacteristicNotify.ValueChanged += CharacteristicNotify_ValueChanged; 181 | bool enabled = await EnableNotification(CharacteristicNotify); 182 | if (enabled) 183 | { 184 | Log.Info("订阅通知成功!" + CharacteristicNotify.Uuid); 185 | } 186 | } 187 | ConnectionStateChanged?.Invoke(this, true); 188 | } 189 | } 190 | 191 | private void CharacteristicNotify_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args) 192 | { 193 | byte[] data = args.CharacteristicValue.ToBytes(); 194 | Log.Info($"收到数据 <<< {data.ToHex()}"); 195 | CharacteristicValueChanged?.Invoke(sender, data); 196 | } 197 | 198 | private async Task EnableNotification(GattCharacteristic characteristic) 199 | { 200 | GattCommunicationStatus result = await characteristic 201 | .WriteClientCharacteristicConfigurationDescriptorAsync( 202 | GattClientCharacteristicConfigurationDescriptorValue.Notify 203 | ); 204 | return result == GattCommunicationStatus.Success; 205 | } 206 | 207 | public async Task Write(byte[] data) 208 | { 209 | if (CharacteristicWrite == null) 210 | { 211 | return false; 212 | } 213 | DataWriter writer = new DataWriter(); 214 | writer.WriteBytes(data); 215 | GattCommunicationStatus result = await CharacteristicWrite 216 | .WriteValueAsync(writer.DetachBuffer(), GattWriteOption.WriteWithoutResponse); 217 | return result == GattCommunicationStatus.Success; 218 | } 219 | 220 | public async Task Read(string serviceUuid, string characteristicUuid) 221 | { 222 | GattCharacteristic characteristic = GattCharacteristics[serviceUuid]?[characteristicUuid]; 223 | if (characteristic != null) 224 | { 225 | GattReadResult result = await characteristic.ReadValueAsync(); 226 | if (result.Status == GattCommunicationStatus.Success) 227 | { 228 | byte[] data = result.Value.ToBytes(); 229 | Log.Info($"读取数据 <<< {data.ToHex()} / {Encoding.UTF8.GetString(data)}"); 230 | return data; 231 | } 232 | } 233 | else 234 | { 235 | Log.Info($"未发现该特征: {serviceUuid} / {characteristicUuid}"); 236 | } 237 | return null; 238 | } 239 | 240 | 241 | public void Disconnect() 242 | { 243 | Log.Info("Disconnect()"); 244 | 245 | //必须释放服务才能断开连接 246 | foreach (GattDeviceService service in GattServices) 247 | { 248 | service.Dispose(); 249 | } 250 | 251 | Disconnected(); 252 | //_device = null;//赋值为 null 会导致收不到断线的通知 253 | //ConnectionStateChanged?.Invoke(this, false); 254 | } 255 | 256 | private void Disconnected() 257 | { 258 | GattServices.Clear(); 259 | GattCharacteristics.Clear(); 260 | CharacteristicWrite = null; 261 | CharacteristicNotify = null; 262 | 263 | if (_device != null) 264 | { 265 | _device.Dispose(); 266 | _device = null; 267 | } 268 | } 269 | 270 | public override string ToString() 271 | { 272 | return Name + "\r\n" + Mac; 273 | } 274 | } 275 | } 276 | -------------------------------------------------------------------------------- /WpfBleApp/Ble/BleExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using Windows.Devices.Bluetooth.Advertisement; 7 | using Windows.Devices.Enumeration; 8 | using WpfBleApp.Utils; 9 | 10 | namespace WpfBleApp.Ble 11 | { 12 | public static class BleExtensions 13 | { 14 | 15 | /// 16 | /// 通过 DeviceInformation 获取 MAC 地址 17 | /// 18 | /// 19 | /// 20 | public static string Mac(this DeviceInformation info) 21 | { 22 | return info.Properties["System.Devices.Aep.DeviceAddress"]?.ToString()?.ToUpper(); 23 | } 24 | 25 | 26 | public static string Mac(this BluetoothLEAdvertisementReceivedEventArgs args) 27 | { 28 | ulong address = args.BluetoothAddress; 29 | int len = 6; 30 | byte[] macArr = new byte[len]; 31 | for (int i = 0; i < len; i++) 32 | { 33 | macArr[i] = (byte)((address >> ((len - 1 - i) * 8)) & 0xff); 34 | } 35 | //macArr = $"{args.BluetoothAddress:X12}".ToData(); 36 | return string.Join(":", macArr.Select(b => $"{b:X2}")); 37 | } 38 | 39 | public static string LocalName(this BluetoothLEAdvertisementReceivedEventArgs args) 40 | { 41 | return args.Advertisement.LocalName; 42 | } 43 | 44 | public static byte[] MfrData(this BluetoothLEAdvertisementReceivedEventArgs args) 45 | { 46 | foreach (BluetoothLEAdvertisementDataSection section in args.Advertisement.DataSections) 47 | { 48 | if (section.DataType == 0xff) 49 | { 50 | return section.Data.ToBytes(); 51 | } 52 | } 53 | return null; 54 | } 55 | 56 | // 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /WpfBleApp/Ble/BleManager.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using Windows.Devices.Bluetooth; 8 | using Windows.Devices.Bluetooth.Advertisement; 9 | using Windows.Devices.Enumeration; 10 | using Windows.Foundation; 11 | using Windows.Storage.Streams; 12 | using WpfBleApp.Utils; 13 | 14 | namespace WpfBleApp.Ble 15 | { 16 | public class BleManager 17 | { 18 | // https://learn.microsoft.com/zh-cn/windows/uwp/devices-sensors/gatt-client 19 | // Query for extra properties you want returned 20 | private const string KeyIsConnected = "System.Devices.Aep.IsConnected"; 21 | private readonly string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", KeyIsConnected }; 22 | 23 | private readonly DeviceWatcher deviceWatcher; 24 | private readonly BluetoothLEAdvertisementWatcher advertisementWatcher = new BluetoothLEAdvertisementWatcher(); 25 | 26 | public static readonly BleManager Instance = new BleManager(); 27 | 28 | public event TypedEventHandler Started; 29 | public event TypedEventHandler FoundDevice; 30 | public event TypedEventHandler Stopped; 31 | 32 | //BleDevice 需要通过 MAC 组合 DeviceInformation 和 BluetoothLEAdvertisement 的数据 33 | //DeviceInformation 有可能是系统缓存的设备信息,以此信息作为缓存,以扫到的实时广播作为发现设备的依据 34 | //DeviceInformation 主要用来连接设备,广播保证设备的真实性 35 | private readonly ConcurrentDictionary CachedDevices = new ConcurrentDictionary(); 36 | 37 | 38 | private BleManager() 39 | { 40 | deviceWatcher = DeviceInformation.CreateWatcher( 41 | //BluetoothLEDevice.GetDeviceSelectorFromPairingState(false), 42 | BluetoothLEDevice.GetDeviceSelectorFromConnectionStatus(BluetoothConnectionStatus.Disconnected), 43 | requestedProperties, DeviceInformationKind.AssociationEndpoint); 44 | deviceWatcher.Added += DeviceWatcher_Added; 45 | deviceWatcher.Updated += DeviceWatcher_Updated; 46 | deviceWatcher.Removed += DeviceWatcher_Removed; 47 | deviceWatcher.EnumerationCompleted += DeviceWatcher_EnumerationCompleted; 48 | deviceWatcher.Stopped += DeviceWatcher_Stopped; 49 | 50 | advertisementWatcher.ScanningMode = BluetoothLEScanningMode.Passive; 51 | advertisementWatcher.Received += AdvertisementWatcher_Received; 52 | advertisementWatcher.Stopped += AdvertisementWatcher_Stopped; 53 | } 54 | 55 | private void DeviceWatcher_Stopped(DeviceWatcher sender, object args) 56 | { 57 | Log.Info("DeviceWatcher_Stopped"); 58 | } 59 | 60 | private void DeviceWatcher_EnumerationCompleted(DeviceWatcher sender, object args) 61 | { 62 | Log.Info("DeviceWatcher_EnumerationCompleted"); 63 | } 64 | 65 | private void DeviceWatcher_Removed(DeviceWatcher sender, DeviceInformationUpdate args) 66 | { 67 | //Log.Info("DeviceWatcher_Removed"); 68 | } 69 | 70 | private void DeviceWatcher_Updated(DeviceWatcher sender, DeviceInformationUpdate args) 71 | { 72 | Log.Info("################# DeviceWatcher_Updated #################"); 73 | foreach (KeyValuePair item in args.Properties) 74 | { 75 | Log.Info($"{item.Key}={item.Value}"); 76 | } 77 | } 78 | 79 | private void DeviceWatcher_Added(DeviceWatcher sender, DeviceInformation args) 80 | { 81 | //Log.Info("DeviceWatcher_Added"); 82 | if (!CachedDevices.ContainsKey(args.Mac())) 83 | { 84 | CachedDevices[args.Mac()] = new BleDevice(args); 85 | } 86 | } 87 | 88 | private void AdvertisementWatcher_Stopped(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementWatcherStoppedEventArgs args) 89 | { 90 | Log.Info("AdvertisementWatcher_Stopped"); 91 | Stopped?.Invoke(this, args); 92 | } 93 | 94 | private void AdvertisementWatcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) 95 | { 96 | Log.Info("~~~~~~~~~~~~~~ 广播信息 ~~~~~~~~~~~~~~"); 97 | Log.Info($"IsScanResponse={args.IsScanResponse}"); 98 | Log.Info($"LocalName={args.Advertisement.LocalName}"); 99 | Log.Info($"BluetoothAddress={args.Mac()}"); 100 | Log.Info($"rssi={args.RawSignalStrengthInDBm}"); 101 | PrintAdvertisement(args.Advertisement); 102 | 103 | if (CachedDevices.TryGetValue(args.Mac(), out BleDevice device)) 104 | { 105 | Log.Info($"发现设备 {args.Mac()} 的广播"); 106 | device.Update(args);//更新一下广播数据 107 | FoundDevice?.Invoke(this, device); 108 | } 109 | } 110 | 111 | 112 | private void PrintAdvertisement(BluetoothLEAdvertisement advertisement) 113 | { 114 | foreach (BluetoothLEManufacturerData mfrData in advertisement.ManufacturerData) 115 | { 116 | byte[] data = mfrData.Data.ToBytes(); 117 | byte[] rawBytes = new byte[data.Length + 2]; 118 | rawBytes[0] = (byte)((mfrData.CompanyId) & 0xff); 119 | rawBytes[1] = (byte)((mfrData.CompanyId >> 8) & 0xff); 120 | Array.Copy(data, 0, rawBytes, 2, data.Length); 121 | Log.Info($"厂商数据:{rawBytes.ToHex()}"); 122 | } 123 | /*foreach (BluetoothLEAdvertisementDataSection section in advertisement.DataSections) 124 | { 125 | Log.Info($"Data Type: 0x{section.DataType:X2}, Data: {section.Data.ToHex()}"); 126 | }*/ 127 | } 128 | 129 | public async void StartScan() 130 | { 131 | if(advertisementWatcher.Status != BluetoothLEAdvertisementWatcherStatus.Started) 132 | { 133 | CachedDevices.Clear();//清空缓存 134 | 135 | advertisementWatcher.Start(); 136 | deviceWatcher.Start(); 137 | Started?.Invoke(this, null); 138 | await Task.Delay(5000); 139 | StopScan(); 140 | } 141 | } 142 | 143 | public void StopScan() 144 | { 145 | //判断状态,防止 InvalidOperationException 146 | if (advertisementWatcher.Status == BluetoothLEAdvertisementWatcherStatus.Started) 147 | { 148 | advertisementWatcher.Stop(); 149 | deviceWatcher.Stop(); 150 | Log.Info("停止扫描"); 151 | } 152 | } 153 | 154 | // 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /WpfBleApp/Ble/Uuids.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Collections.ObjectModel; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace WpfBleApp.Ble 9 | { 10 | public class Uuids 11 | { 12 | public const string SERVICE = "00001000-0000-1000-8000-00805f9b34fb"; 13 | public const string WRITE = "00001001-0000-1000-8000-00805f9b34fb"; 14 | public const string NOTIFY = "00001002-0000-1000-8000-00805f9b34fb"; 15 | 16 | public const string GenericAccess = "00001800-0000-1000-8000-00805f9b34fb"; 17 | public const string DeviceName = "00002a00-0000-1000-8000-00805f9b34fb"; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /WpfBleApp/CommPage.xaml: -------------------------------------------------------------------------------- 1 |  10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 39 | 67 | 68 | -------------------------------------------------------------------------------- /WpfBleApp/CommPage.xaml.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.ObjectModel; 3 | using System.Diagnostics; 4 | using System.Text; 5 | using System.Windows; 6 | using System.Windows.Controls; 7 | using System.Windows.Media; 8 | using Windows.Devices.Bluetooth.GenericAttributeProfile; 9 | using WpfBleApp.Ble; 10 | using WpfBleApp.Model; 11 | using WpfBleApp.Utils; 12 | 13 | namespace WpfBleApp 14 | { 15 | /// 16 | /// 蓝牙通信页面 17 | /// 18 | public partial class CommPage : Page 19 | { 20 | private readonly CommPageViewModel ViewModel = new CommPageViewModel(); 21 | private readonly ObservableCollection Logs = new ObservableCollection(); 22 | private int LogCount; 23 | 24 | 25 | 26 | public CommPage() 27 | { 28 | InitializeComponent(); 29 | 30 | listBoxLog.ItemsSource = Logs; 31 | } 32 | 33 | private void AddLog(string msg) 34 | { 35 | listBoxLog.Dispatcher.Invoke(delegate 36 | { 37 | if (LogCount > 500) 38 | { 39 | Logs.RemoveAt(0); 40 | } 41 | Logs.Add($"{DateTime.Now:HH:mm:ss.fff} - {msg}"); 42 | LogCount++; 43 | 44 | }); 45 | } 46 | 47 | public CommPage(BleDevice device) : this() 48 | { 49 | ViewModel.BleDevice = device; 50 | ViewModel.BleDevice.CharacteristicValueChanged += BleDevice_CharacteristicValueChanged; 51 | ViewModel.BleDevice.ConnectionStateChanged += BleDevice_ConnectionStateChanged; 52 | DataContext = ViewModel; 53 | device.Connect(); 54 | } 55 | 56 | private void UpdateConnectButton(bool connected) 57 | { 58 | buttonConnect.Dispatcher.Invoke(delegate 59 | { 60 | if (connected) 61 | { 62 | buttonConnect.Content = "断开连接"; 63 | buttonConnect.Background = new SolidColorBrush(Color.FromRgb(199, 0, 6)); 64 | buttonConnect.Foreground = new SolidColorBrush(Colors.White); 65 | } 66 | else 67 | { 68 | buttonConnect.Content = "连接设备"; 69 | buttonConnect.Background = new SolidColorBrush(Colors.LightGray); 70 | buttonConnect.Foreground = new SolidColorBrush(Colors.Black); 71 | } 72 | }); 73 | } 74 | 75 | private void BleDevice_ConnectionStateChanged(BleDevice sender, bool args) 76 | { 77 | if (args) 78 | { 79 | AddLog("连接成功!"); 80 | } 81 | else 82 | { 83 | AddLog("连接已断开!"); 84 | } 85 | UpdateConnectButton(args); 86 | } 87 | 88 | private void BleDevice_CharacteristicValueChanged(GattCharacteristic sender, byte[] args) 89 | { 90 | AddLog($"收到数据 <<< {args.ToHex()}"); 91 | } 92 | 93 | private async void buttonSend_Click(object sender, RoutedEventArgs e) 94 | { 95 | byte[] data = ViewModel.TxDataHex.ToData(); 96 | bool success = await ViewModel.BleDevice.Write(data); 97 | if (success) 98 | { 99 | AddLog("发送成功 >>> " + data.ToHex()); 100 | } 101 | } 102 | 103 | private async void buttonRead_Click(object sender, RoutedEventArgs e) 104 | { 105 | byte[] data = await ViewModel.BleDevice.Read(Uuids.GenericAccess, Uuids.DeviceName); 106 | if (data != null) 107 | { 108 | AddLog($"读取的设备名称: {Encoding.UTF8.GetString(data)}"); 109 | } 110 | } 111 | 112 | private void buttonConnect_Click(object sender, RoutedEventArgs e) 113 | { 114 | if (ViewModel.BleDevice.IsConnected) 115 | { 116 | ViewModel.BleDevice.Disconnect(); 117 | } 118 | else 119 | { 120 | ViewModel.BleDevice.Connect(); 121 | } 122 | } 123 | 124 | private void Page_Unloaded(object sender, RoutedEventArgs e) 125 | { 126 | Debug.WriteLine("Page_Unloaded()"); 127 | ViewModel.BleDevice.CharacteristicValueChanged -= BleDevice_CharacteristicValueChanged; 128 | ViewModel.BleDevice.ConnectionStateChanged -= BleDevice_ConnectionStateChanged; 129 | ViewModel.BleDevice.Disconnect(); 130 | } 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /WpfBleApp/MainWindow.xaml: -------------------------------------------------------------------------------- 1 |  10 | 11 | 12 | -------------------------------------------------------------------------------- /WpfBleApp/MainWindow.xaml.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using System.Windows; 7 | using System.Windows.Controls; 8 | using System.Windows.Data; 9 | using System.Windows.Documents; 10 | using System.Windows.Input; 11 | using System.Windows.Media; 12 | using System.Windows.Media.Imaging; 13 | using System.Windows.Navigation; 14 | using System.Windows.Shapes; 15 | 16 | namespace WpfBleApp 17 | { 18 | /// 19 | /// MainWindow.xaml 的交互逻辑 20 | /// 21 | public partial class MainWindow : NavigationWindow 22 | { 23 | public MainWindow() 24 | { 25 | InitializeComponent(); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /WpfBleApp/Model/CommPageViewModel.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using WpfBleApp.Ble; 7 | 8 | namespace WpfBleApp.Model 9 | { 10 | class CommPageViewModel : ObservableObject 11 | { 12 | private BleDevice _bleDevice; 13 | private string _txDataHex = "AABBCC112233"; 14 | 15 | public BleDevice BleDevice 16 | { 17 | get => _bleDevice; 18 | set => Set(ref _bleDevice, value); 19 | } 20 | 21 | public string DeviceName 22 | { 23 | get => _bleDevice?.Name; 24 | } 25 | 26 | public string DeviceAddress 27 | { 28 | get => _bleDevice?.Mac; 29 | } 30 | 31 | public string TxDataHex 32 | { 33 | get => _txDataHex; 34 | set => Set(ref _txDataHex, value); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /WpfBleApp/Model/ObservableObject.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel; 4 | using System.Linq; 5 | using System.Runtime.CompilerServices; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace WpfBleApp.Model 10 | { 11 | public class ObservableObject : INotifyPropertyChanged 12 | { 13 | public event PropertyChangedEventHandler PropertyChanged; 14 | 15 | protected void OnPropertyChanged([CallerMemberName] string propertyName = "") 16 | { 17 | //Console.WriteLine("OnPropertyChanged() - " + propertyName); 18 | PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); 19 | } 20 | 21 | protected void Set(ref T field, T newValue, [CallerMemberName] string propertyName = "") 22 | { 23 | if(!object.Equals(field, newValue)) 24 | { 25 | field = newValue; 26 | OnPropertyChanged(propertyName); 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /WpfBleApp/Model/ScanPageViewModel.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Collections.ObjectModel; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using WpfBleApp.Ble; 8 | 9 | namespace WpfBleApp.Model 10 | { 11 | public class ScanPageViewModel : ObservableObject 12 | { 13 | public ObservableCollection Devices { get; } = new ObservableCollection(); 14 | 15 | public void AddDevice(BleDevice device) 16 | { 17 | if (!Devices.Any(d => d.Mac == device.Mac)) 18 | { 19 | Devices.Add(device); 20 | } 21 | else 22 | { 23 | Devices.First(d => d.Mac == device.Mac).Update(device); 24 | } 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /WpfBleApp/Properties/Resources.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // 此代码由工具生成。 4 | // 运行时版本: 4.0.30319.42000 5 | // 6 | // 对此文件的更改可能导致不正确的行为,如果 7 | // 重新生成代码,则所做更改将丢失。 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | 12 | namespace WpfBleApp.Properties 13 | { 14 | /// 15 | /// 强类型资源类,用于查找本地化字符串等。 16 | /// 17 | // 此类是由 StronglyTypedResourceBuilder 18 | // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 19 | // 若要添加或删除成员,请编辑 .ResX 文件,然后重新运行 ResGen 20 | // (以 /str 作为命令选项),或重新生成 VS 项目。 21 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] 22 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 23 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 24 | internal class Resources 25 | { 26 | 27 | private static global::System.Resources.ResourceManager resourceMan; 28 | 29 | private static global::System.Globalization.CultureInfo resourceCulture; 30 | 31 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] 32 | internal Resources() 33 | { 34 | } 35 | 36 | /// 37 | /// 返回此类使用的缓存 ResourceManager 实例。 38 | /// 39 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 40 | internal static global::System.Resources.ResourceManager ResourceManager 41 | { 42 | get 43 | { 44 | if ((resourceMan == null)) 45 | { 46 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WpfBleApp.Properties.Resources", typeof(Resources).Assembly); 47 | resourceMan = temp; 48 | } 49 | return resourceMan; 50 | } 51 | } 52 | 53 | /// 54 | /// 重写当前线程的 CurrentUICulture 属性,对 55 | /// 使用此强类型资源类的所有资源查找执行重写。 56 | /// 57 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 58 | internal static global::System.Globalization.CultureInfo Culture 59 | { 60 | get 61 | { 62 | return resourceCulture; 63 | } 64 | set 65 | { 66 | resourceCulture = value; 67 | } 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /WpfBleApp/Properties/Resources.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | text/microsoft-resx 107 | 108 | 109 | 2.0 110 | 111 | 112 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 113 | 114 | 115 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | -------------------------------------------------------------------------------- /WpfBleApp/Properties/Settings.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.42000 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | 12 | namespace WpfBleApp.Properties 13 | { 14 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 15 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] 16 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase 17 | { 18 | 19 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); 20 | 21 | public static Settings Default 22 | { 23 | get 24 | { 25 | return defaultInstance; 26 | } 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /WpfBleApp/Properties/Settings.settings: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /WpfBleApp/ScanPage.xaml: -------------------------------------------------------------------------------- 1 |  9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 50 | 51 | 53 | 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /WpfBleApp/ScanPage.xaml.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Collections.ObjectModel; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | using System.Windows; 9 | using System.Windows.Controls; 10 | using System.Windows.Data; 11 | using System.Windows.Documents; 12 | using System.Windows.Input; 13 | using System.Windows.Media; 14 | using System.Windows.Media.Imaging; 15 | using System.Windows.Navigation; 16 | using System.Windows.Shapes; 17 | using System.Windows.Threading; 18 | using Windows.Devices.Bluetooth; 19 | using Windows.Devices.Enumeration; 20 | using WpfBleApp.Ble; 21 | using WpfBleApp.Model; 22 | using WpfBleApp.Utils; 23 | 24 | namespace WpfBleApp 25 | { 26 | /// 27 | /// 蓝牙扫描页面 28 | /// 29 | public partial class ScanPage : Page 30 | { 31 | private readonly BleManager BleManager = BleManager.Instance; 32 | private readonly ScanPageViewModel ViewModel = new ScanPageViewModel(); 33 | 34 | public ScanPage() 35 | { 36 | InitializeComponent(); 37 | DataContext = ViewModel; 38 | 39 | //deviceListBox.ItemsSource = ViewModel.Devices; 40 | 41 | BleManager.Started += BleManager_Started; 42 | BleManager.FoundDevice += BleManager_FoundDevice; 43 | BleManager.Stopped += BleManager_Stopped; 44 | 45 | Log.Info($"扫描页面创建 0x{GetHashCode():X8}"); 46 | } 47 | 48 | ~ScanPage() 49 | { 50 | Log.Info($"扫描页面销毁 0x{GetHashCode():X8}"); 51 | } 52 | 53 | private void BleManager_Started(BleManager sender, object args) 54 | { 55 | btnStartScan.Dispatcher.Invoke(delegate 56 | { 57 | btnStartScan.Content = "停止扫描"; 58 | }); 59 | } 60 | 61 | private void BleManager_Stopped(BleManager sender, object args) 62 | { 63 | btnStartScan.Dispatcher.Invoke(delegate 64 | { 65 | btnStartScan.Content = "开始扫描"; 66 | }); 67 | } 68 | 69 | private void BleManager_FoundDevice(BleManager sender, BleDevice args) 70 | { 71 | deviceListBox.Dispatcher.Invoke(() => 72 | { 73 | ViewModel.AddDevice(args); 74 | }); 75 | } 76 | 77 | private void btnStartScan_Click(object sender, RoutedEventArgs e) 78 | { 79 | ViewModel.Devices.Clear(); 80 | BleManager.Instance.StartScan(); 81 | } 82 | 83 | private void btnConnect_Click(object sender, RoutedEventArgs e) 84 | { 85 | if (deviceListBox.SelectedItem is BleDevice device) 86 | { 87 | BleManager.Instance.StopScan(); 88 | NavigationService.Navigate(new CommPage(device)); 89 | } 90 | else 91 | { 92 | MessageBox.Show("请选择要连接的设备!"); 93 | } 94 | } 95 | 96 | private void deviceListBox_MouseDoubleClick(object sender, MouseButtonEventArgs e) 97 | { 98 | if (deviceListBox.SelectedItem is BleDevice device) 99 | { 100 | BleManager.Instance.StopScan(); 101 | NavigationService.Navigate(new CommPage(device)); 102 | } 103 | } 104 | 105 | // 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /WpfBleApp/Utils/Extensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using Windows.Foundation; 7 | using Windows.Storage.Streams; 8 | 9 | namespace WpfBleApp.Utils 10 | { 11 | public static class Extensions 12 | { 13 | public static async Task GetResultAsync(this IAsyncOperation asyncOperation){ 14 | return await Task.Run(() => 15 | { 16 | while (asyncOperation.Status == AsyncStatus.Started) 17 | { 18 | } 19 | return asyncOperation.GetResults();//这里会异常 20 | }); 21 | } 22 | 23 | public static string ToHex(this byte[] data) 24 | { 25 | return string.Join(" ", data.Select(b => $"{b:X2}")); 26 | } 27 | 28 | public static byte[] ToData(this string hex) 29 | { 30 | hex = hex.Replace(" ", "").Trim(); 31 | if (hex.Length % 2 == 1) 32 | { 33 | hex = $"0{hex}"; 34 | } 35 | int len = hex.Length / 2; 36 | byte[] data = new byte[len]; 37 | for (int i = 0; i < len; i++) 38 | { 39 | data[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16); 40 | } 41 | return data; 42 | } 43 | 44 | public static byte[] ToBytes(this IBuffer data) 45 | { 46 | byte[] bytes = new byte[data.Length]; 47 | DataReader.FromBuffer(data).ReadBytes(bytes); 48 | return bytes; 49 | } 50 | 51 | public static string ToHex(this IBuffer data) 52 | { 53 | return data.ToBytes().ToHex(); 54 | } 55 | 56 | // 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /WpfBleApp/Utils/Log.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace WpfBleApp.Utils 8 | { 9 | public class Log 10 | { 11 | private static string Timestamp => $"{DateTime.Now:HH:mm:ss.fff}"; 12 | 13 | public static void Info(string msg) 14 | { 15 | Console.WriteLine($"{Timestamp} - {msg}"); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /WpfBleApp/Widget/AutoScrollListBox.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Collections.Specialized; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using System.Windows.Controls; 8 | 9 | namespace WpfBleApp.Widget 10 | { 11 | public class AutoScrollListBox : ListBox 12 | { 13 | protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e) 14 | { 15 | if (e.NewItems == null) 16 | { 17 | return; 18 | } 19 | int count = e.NewItems.Count; 20 | if (count > 0) 21 | { 22 | ScrollIntoView(e.NewItems[count - 1]); 23 | } 24 | base.OnItemsChanged(e); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /WpfBleApp/WpfBleApp.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | net6.0-windows10.0.19041.0 4 | WinExe 5 | publish\ 6 | true 7 | Disk 8 | false 9 | Foreground 10 | 7 11 | Days 12 | false 13 | false 14 | true 15 | 0 16 | 1.0.0.%2a 17 | false 18 | false 19 | true 20 | false 21 | true 22 | true 23 | 24 | 25 | 26 | False 27 | Microsoft .NET Framework 4.6 %28x86 和 x64%29 28 | true 29 | 30 | 31 | False 32 | .NET Framework 3.5 SP1 33 | false 34 | 35 | 36 | 37 | 38 | 39 | 40 | --------------------------------------------------------------------------------