概要
Raspberry Pi 2の上で動作するWindows 10 IoT版で、EddyStoneの信号を受信するアプリを書いてみた。EddyStone URLのみデコードして、デバックコンソールに出力する。
動作環境
- Raspberry Pi 2 + Windows 10 IoT (Build 10.0.10240.16384)
- Bluetooth USB Dongle(GH-BHDA42) ちなみに、CSR8510 A10と認識されるデバイス
開発環境
- Windows 10 + Visual Studio 2015
注意点
Bluetoothを使ったアプリケーションを作成する際は、Package.appmanifestに、Bluetoothを使うよと宣言しないと、関連APIが実行時にエラーになるので、どうしたらいいか?は、こちらの投稿をご覧ください。
ソースコード
MainPage.xaml.cs
using System;
using System.Diagnostics;
using Windows.Devices.Bluetooth.Advertisement;
using Windows.Storage.Streams;
using Windows.UI.Xaml.Controls;
// 空白ページのアイテム テンプレートについては、http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 を参照してください
namespace EddyStone2
{
/// <summary>
/// それ自体で使用できる空白ページまたはフレーム内に移動できる空白ページ。
/// </summary>
public sealed partial class MainPage : Page
{
private BluetoothLEAdvertisementWatcher watch;
public MainPage()
{
this.InitializeComponent();
watch = new BluetoothLEAdvertisementWatcher();
watch.Received += Watch_Received;
watch.Start();
}
private void Watch_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args)
{
if (args.Advertisement.ServiceUuids.Count == 1)
{
if (args.Advertisement.ServiceUuids[0].CompareTo(new Guid("0000feaa-0000-1000-8000-00805f9b34fb")) != 0)
{
return;
}
if (args.Advertisement.DataSections.Count > 0)
{
for (int i = 0; i < args.Advertisement.DataSections.Count; i++)
{
var secData = args.Advertisement.DataSections[i];
var data = new byte[secData.Data.Length];
using (var reader = DataReader.FromBuffer(secData.Data))
{
reader.ReadBytes(data);
}
if (secData.DataType == 0x16)
{
if ((data[0] == 0xaa) && (data[1] == 0xfe))
{
if (data[2] == 0x0)
{
// Eddystone UID
Debug.WriteLine("eddystone UID");
}
else if (data[2] == 0x10)
{
// Eddystone URLの場合
// data[3]は送信パワーを示す。
String url = "";
switch (data[4])
{
case 0x0:
url = "http://www.";
break;
case 0x1:
url = "https://www.";
break;
case 0x2:
url = "http://";
break;
case 0x3:
url = "https://";
break;
}
for (int j = 5; j < data.Length; j++)
{
switch (data[j])
{
case 0x0:
url = url + ".com/";
break;
case 0x1:
url = url + ".org/";
break;
case 0x2:
url = url + ".edu/";
break;
case 0x3:
url = url + ".net/";
break;
case 0x4:
url = url + ".info/";
break;
case 0x5:
url = url + ".biz/";
break;
case 0x6:
url = url + ".gov/";
break;
case 0x7:
url = url + ".com";
break;
case 0x8:
url = url + ".org";
break;
case 0x9:
url = url + ".edu";
break;
case 0xa:
url = url + ".net";
break;
case 0xb:
url = url + ".info";
break;
case 0xc:
url = url + ".biz";
break;
case 0xd:
url = url + ".gov";
break;
}
if (data[j] >= 0x21 && data[j] <= 0x7e)
{
url = url + System.Text.Encoding.ASCII.GetString(data, j, 1);
}
}
Debug.WriteLine(url);
}
else if (data[2] == 0x20)
{
// Eddystone TLM
Debug.WriteLine("eddystone TLM");
}
}
}
}
}
}
}
}
}
以上、ご参考までに