加速度センサの計測結果をBLEで飛ばすっていう試み。XIAO nRF52840と秋月AE-ADXL367を使って。
で、nRF52840で飛ばしたデータをWindowsで受信する方法について考えてみる。
こちらのサイト(https://coskxlabsite.stars.ne.jp/html/for_students/iot/XIAOESP32S3/ESP32S3BLEServer_WinPC.html)に掲載のBLE_serial_terminalを使ってログ採って後でデータを解析するってんで十分なんだけど、データをすぐ見たい、とか、本当にリアルタイムでデータを収集しているのを見たいとか、いろんなことを要求されることあるよね、、、で、なんでWindowsなのかというと、AndroidでBLE受信とかはまぁまぁやってる人が多いので、まぁなんていうか、後で考えようって。で、まぁやってみるわけだよ、そすっと、
dotnet new console
で、Program.csに
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.Advertisement;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
って入れようもんなら、
ってな感じで、怒られちゃう( •̥ࡇ•̥ )で、こっから年をまたいだ格闘があったわけで(すまソ、ちょっとだらだらしてただけ)、で結局、
csprojファイルのTargetFrameworkを変えちゃえばいいっていう結論に達した、、、Visual Studio Community Edition入れてUWPアプリとして作るってのが正攻法っぽいけど、Visual Studio Community EditionのLicense Termsがいやだから使いたくないんよね、、、エンタープライズではほぼ教育以外の目的では使ってはいけないように読み取れる。つまりエンタープライズでは実用アプリをVisual Studio Community Editionで作ってはいけない<--これは明確に書いてある。
こちら
こういうのがプログラミングの裾野の拡大を妨げていると思う。ちと考えろやB111 6A7E5 <(`^´)>
で、日曜技術者活動は完全に個人の趣味だけど、誠に勝手ながらエンタープライズの社員によるトレースをすら想定しています(’-’)なので、VS Community Editionは使わない。
本筋に戻ると、
<targetframework>net8.0</targetframework>
を
<targetframework>net6.0-windows10.0.22000.0</targetframework>
ってする。、、、様々な検討の結果がこれよ┐(´∀`)┌
んでもって、こんな感じにする。
study2.csproj
- <Project Sdk="Microsoft.NET.Sdk">
-
- <PropertyGroup>
- <OutputType>Exe</OutputType>
- <TargetFramework>net6.0-windows10.0.22000.0</TargetFramework>
- <ImplicitUsings>enable</ImplicitUsings>
- <Nullable>enable</Nullable>
- </PropertyGroup>
-
- </Project>
Program.cs
- //using System;
- //using System.Collections.Generic;
- //using System.Collections.ObjectModel;
- //using System.Linq;
- //using System.Threading.Tasks;
- using Windows.Devices.Bluetooth;
- using Windows.Devices.Bluetooth.Advertisement;
- using Windows.Devices.Bluetooth.GenericAttributeProfile;
-
- namespace BLEScanner{
- class Program{
- static Dictionary<ulong, (string Name,string LocalName, string Uuid)> BleDevices = new Dictionary<ulong, (string Name, string LocalName,string Uuid)>();
- static async Task Main(string[] args){
- var watcher = new BluetoothLEAdvertisementWatcher();
- watcher.Received += OnAdvertisementReceived;
- watcher.ScanningMode = BluetoothLEScanningMode.Active;
- watcher.Start();
- //Console.WriteLine("Scanning for BLE devices... Press Enter to exit.");
- //Console.ReadLine();
- Console.WriteLine("Scanning for BLE devices in 30sec...");
- await Task.Delay(30000);
- watcher.Stop();
-
- foreach(var bledev in BleDevices){
- Console.WriteLine($"{bledev.Key} : {bledev.Value}");
- }
- }
- private static async void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args){
- var device = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress);
-
- if (device != null){
- string deviceName = string.IsNullOrEmpty(device.Name) ? "Unknown" : device.Name;
- string deviceLocalName = string.IsNullOrEmpty(device.Name) ? "Unknown" : args.Advertisement.LocalName;
- string deviceUuid = await GetDeviceUuid(device);
- BleDevices.TryAdd(device.BluetoothAddress,(deviceName,deviceLocalName, deviceUuid));
- //Console.WriteLine($"Found device: {deviceName} -{deviceLocalName}- ({device.BluetoothAddress}) with UUID: {deviceUuid}");
- }
- }
- private static async Task<string> GetDeviceUuid(BluetoothLEDevice device){
- var services = await device.GetGattServicesAsync();
- if (services.Status == GattCommunicationStatus.Success){
- var service = services.Services.FirstOrDefault();
- return service?.Uuid.ToString() ?? "UUID not found";
- }
- return "UUID not found";
- }
- }
- }
BLEをScanするのはもうあっちこっちに似たようなのがあって、どれを参考にしたのかわからなくなった。で、見つかったデバイスをリスト化するにあたってはDictionaryにBLE Address/Name/service uuidを追加していくってして、同じのがあったらはじかれるのを利用して重複を回避している。まぁ1つのデバイスで複数のservice uuidを持っていることもあるんだけど、そういうのは後で考える、、、
Bad programmers worry about the code. Good programmers worry about data structures and their relationships.(Linus Torvalds)
↑日曜技術者はプログラマーではないのでごめんなさい
んでもって、実行するとこうなる
たぶんうまくいっている。
そんでもって、じゃぁnRF52840が飛ばしているデータを取ろうじゃないか、、、ServiceUUIDとCharacteristicUUIDを指定してとるってなら簡単なんだけど、最終的には固定値で指定するとしても、こいつらをリストアップするのもできんといかんやん?で、ムズイていうよりクソメンドクサイ。
で、結局こんな感じ
- //using System;
- //using System.Collections.Generic;
- //using System.Collections.ObjectModel;
- //using System.Linq;
- //using System.Threading.Tasks;
-
- using Windows.Devices.Bluetooth;
- using Windows.Devices.Bluetooth.Advertisement;
- using Windows.Devices.Bluetooth.GenericAttributeProfile;
-
- namespace BLEScanner{
- class Program{
- static Dictionary<ulong, (ulong Address, string Name,string LocalName)> BleDevices = new Dictionary<ulong, (ulong Address, string Name, string LocalName)>();
-
- static async Task Main(string[] args){
- string xiao_nrf52840_name="XIAO nRF52840";
- ulong xiao_nrf52840_device_address=0;
- var watcher = new BluetoothLEAdvertisementWatcher();
- watcher.Received += OnAdvertisementReceived;
- watcher.ScanningMode = BluetoothLEScanningMode.Active;
-
- watcher.Start();
- //Console.WriteLine("Scanning for BLE devices... Press Enter to exit.");
- //Console.ReadLine();
- Console.WriteLine("Scanning for BLE devices in 30sec...");
- await Task.Delay(30000);
- watcher.Stop();
-
- foreach(var bledev in BleDevices){
- Console.WriteLine($"{bledev.Key} : {bledev.Value}");
- if(bledev.Value.Name.Contains(xiao_nrf52840_name)){
- xiao_nrf52840_device_address=bledev.Key;
- }
- }
- if(xiao_nrf52840_device_address>0){
- Console.WriteLine($"{xiao_nrf52840_name} was found.");
- Console.WriteLine($"Address : {xiao_nrf52840_device_address}");
- var xiao_nrf52840_device = await BluetoothLEDevice.FromBluetoothAddressAsync(xiao_nrf52840_device_address);
- var xiao_nrf52840_device_services=await xiao_nrf52840_device.GetGattServicesAsync();
- foreach(var serv in xiao_nrf52840_device_services.Services){
- Console.WriteLine($" service uuid: {serv.Uuid}");
- var xiao_nrf52840_device_characteristics=await serv.GetCharacteristicsAsync();
- foreach(var chr in xiao_nrf52840_device_characteristics.Characteristics){
- Console.WriteLine($" characterisitics uuid: {chr.Uuid}");
- }
- }
- var xiao_nrf52840_device_service=await xiao_nrf52840_device.GetGattServicesForUuidAsync(new Guid("6e400001-b5a3-f393-e0a9-e50e24dcca9e"));
- var xiao_nrf52840_device_char_uartrx=await xiao_nrf52840_device_service.Services[0].GetCharacteristicsForUuidAsync(new Guid("6e400003-b5a3-f393-e0a9-e50e24dcca9e"));
- var rx_characteristics=xiao_nrf52840_device_char_uartrx.Characteristics[0];
- rx_characteristics.ValueChanged += OnDataReceived;
- await rx_characteristics.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
- while (true){
- //
- }
- }
- }
- static void OnDataReceived(GattCharacteristic sender, GattValueChangedEventArgs eventArgs) {
- //Console.WriteLine(sender);
- //Console.WriteLine(eventArgs);
- byte[] data = new byte[eventArgs.CharacteristicValue.Length];
- Windows.Storage.Streams.DataReader.FromBuffer(eventArgs.CharacteristicValue).ReadBytes(data);
- var encoding = System.Text.Encoding.GetEncoding("UTF-8");
- var text = encoding.GetString(data);
- Console.WriteLine(text.TrimEnd());
- }
- private static async void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args){
- var device = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress);
- if (device != null){
- string deviceName = string.IsNullOrEmpty(device.Name) ? "Unknown" : device.Name;
- string deviceLocalName = string.IsNullOrEmpty(device.Name) ? "Unknown" : args.Advertisement.LocalName;
- BleDevices.TryAdd(device.BluetoothAddress,(device.BluetoothAddress,deviceName,deviceLocalName));
- //Console.WriteLine($"Found device: {deviceName} -{deviceLocalName}- ({device.BluetoothAddress}) with UUID: {deviceUuid}");
- }
- }
- }
- }
BLEアドレスからServicesをとってひとつひとつのServiceでCharacteristicsをとって要素を表示している。この結果を制御に使ってるわけじゃないけど、こういうことができるってことを知っていると何かイイコトがあるかもしれない。
で、dotnet runするとこんな感じ
まぁうまくいったっしょ。
あぁ~だいぶさぼっちゃった( ˙꒳˙)
おっさんになると壁にぶつかってダウンしたときに起き上がるのに時間がかかっちゃう。pythonではbleakってライブラリ使って簡単にできるんだけどな、、、が、最近C#好きなんよね、、、なんとなく。