StreamSocket.ConnectAsync()

时间:2015-06-03 16:13:41

标签: c# silverlight bluetooth windows-phone-8.1 rfcomm

我现在因为试图与蓝牙设备(而不是BLE)进行通信而陷入困境数小时。

我使用的是Windows Phone 8.1 Silverlight应用程序。

我在appxmanifest中使用serviceid设置了DeviceCapability部分:

<!-- bluetooth -->
<m2:DeviceCapability Name="bluetooth.rfcomm">
  <m2:Device Id="any">

    <m2:Function Type="serviceId:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" />
  </m2:Device>
</m2:DeviceCapability>

我在appAppmanifest中的WPAppManifest和near中启用了ID_CAP_PROXIMITY和ID_CAP_NETWORKING。

我用两种可能的方式搜索我的设备(并且每次成功获得PeerInformation),或者使用配对的filter或serviceid:

        if(serviceId.HasValue)
        {
            // Filter devices with serviceId
            PeerFinder.AlternateIdentities["Bluetooth:SDP"] = "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}";
        }
        else
        {
            // Filter devices (all paired)
            PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
        }

        // Search
        var peers = await PeerFinder.FindAllPeersAsync();
        // Make some filtering to get right PeerInformation
        var peer = GetGoodPeerInformation();

当我尝试将一些数据写入我的设备时,我得到了“未找到元素”错误:

try
        {
            //PeerFinder.Start();

            //using (var streamSocket = await PeerFinder.ConnectAsync(Peer))
            using (var streamSocket = new StreamSocket())
            {
                // I have to put manually the serviceid because the ServiceId property in the PeerInformation object is always empty...
                await streamSocket.ConnectAsync(PeerInformation.HostName, "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}");
                // data is a byte[] filled earlier
                await streamSocket.OutputStream.WriteAsync(data.AsBuffer());
            }

            return true;
        }
        catch
        {
            return false;
        }
        finally
        {
            //PeerFinder.Stop();
        }

当我从ConnectAsync()中的ServiceId中删除花括号时,我有另一个错误(文件名不正确0x8007007B)。

如果您有任何想法,谢谢您的帮助!

[编辑:2015年6月4日]

我在WinRT(WP 8.1)应用程序上测试过,并且我成功连接到我的设备,改变了它的使用方式:

var devices = await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.FromUuid(new Guid("00001101-0000-1000-8000-00805F9B34FB"))));

        var device = devices.First();

        var service = await RfcommDeviceService.FromIdAsync(device.Id);

        byte[] data = new byte[] { 0xB0, 0x11, 0x11, 0x01, 0xAA, 0xFA, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xB6 };

        try
        {
            using (StreamSocket socket = new StreamSocket())
            {
                await socket.ConnectAsync(service.ConnectionHostName, service.ConnectionServiceName);
                await socket.OutputStream.WriteAsync(data.AsBuffer());
            }
        }
        catch (Exception)
        {
            throw;
        }

所以,我将这段代码移到我的WP8.1 Silverlight应用程序中,但变量服务总是为空...

0 个答案:

没有答案