はつねの日記

Kinect, Windows 10 UWP, Windows Azure, IoT, 電子工作

Windows Phone 8からbluetooth経由でデバイスと接続する

なんか似たようなネタがあったような気がしますが気にせず Windows Phone Advent Calendar 2013の11日目 として投稿。

Windows 8.1からbluetoothとの接続が「Windows.Devices.Bluetooth.Rfcomm」でできるようになったのは有名な話ですが、Windwos Pnone 8ならば最初から同じことができていました。

ただしクラスは「Windows.Devices.Bluetooth.Rfcomm」ほど洗練されておらず「Windows.Networking.Proximity」や「Windows.Networking.Sockets」を使うことになります。

例えば、Lego Mindstorm EV3と接続するには

PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
IReadOnlyList<PeerInformation> peers = await PeerFinder.FindAllPeersAsync();
PeerInformation peer = (from p in peers where p.DisplayName == _deviceName select p).FirstOrDefault();
if(peer == null)
{     throw new Exception(_deviceName + " Brick not found");
}
else
{     _socket = new StreamSocket();     await _socket.ConnectAsync(peer.HostName, "1");
}
のようなコードで記述できます。
このあたりの相違をうまくクラスライブラリで吸収すると、WIndows 8.1とWindows Phone 8で同じようなアプリケーションを効率よく作成するエコシステムが完成します。
すでにストアで公開しているBrick Controller EV3のロジック部分では
Windows Phone 8

Imports System.ComponentModel
Imports System.Runtime.CompilerServices
Imports System.Windows.Threading
Imports System.Collections.ObjectModel
Imports System.Threading.Tasks

 

Windows 8.1

Imports System.ComponentModel
Imports System.Runtime.CompilerServices

 

と明示的に追加でImportsするクラスライブラリが異なるだけでまったくの同一コードになっています。

 

ぜひ、Windows 8.1とWindows Phone 8でアプリをリリースするエコシステムでbluetoothを使うアプリ構築を楽しんでみてください。