首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >UWP蓝牙RFCOMM FindAllAsync

UWP蓝牙RFCOMM FindAllAsync
EN

Stack Overflow用户
提问于 2017-05-19 15:41:31
回答 2查看 633关注 0票数 1

我想建立两个简单的应用程序,使用蓝牙RFCOMM相互通信。

但是,当我运行客户端应用程序时,它找不到任何带有_devices = await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.ObexObjectPush));设备

_devices集合为空。

基于微软文档中的例子,我已经设法写出了类似这样的东西。

应用程序接收消息(服务器)-部署在Raspberry PI 3上。

代码语言:javascript
复制
namespace RaspRFCOMM
{
    public sealed partial class MainPage : Page
    {
        private RfcommServiceProvider _provider;

        public MainPage()
        {
            this.InitializeComponent();
            this.Initialize();
        }

        private async void Initialize()
        {
            msgStatus.Text = "Inicjalizacja...";

            // Initialize the provider for the hosted RFCOMM service
            _provider = await RfcommServiceProvider.CreateAsync(RfcommServiceId.ObexObjectPush);

            // Create a listener for this service and start listening
            StreamSocketListener listener = new StreamSocketListener();
            listener.ConnectionReceived += OnConnectionReceived;
            await listener.BindServiceNameAsync(
                _provider.ServiceId.AsString(),
                SocketProtectionLevel
                    .BluetoothEncryptionAllowNullAuthentication);

            // Set the SDP attributes and start advertising
            InitializeServiceSdpAttributes(_provider);
            _provider.StartAdvertising(listener, true);
        }

        const uint SERVICE_VERSION_ATTRIBUTE_ID = 0x0300;
        const byte SERVICE_VERSION_ATTRIBUTE_TYPE = 0x0A;   // UINT32
        const uint SERVICE_VERSION = 200;
        private void InitializeServiceSdpAttributes(RfcommServiceProvider provider)
        {
            DataWriter writer = new DataWriter();

            // First write the attribute type
            writer.WriteByte(SERVICE_VERSION_ATTRIBUTE_TYPE);
            // Then write the data
            writer.WriteUInt32(SERVICE_VERSION);

            IBuffer data = writer.DetachBuffer();
            provider.SdpRawAttributes.Add(SERVICE_VERSION_ATTRIBUTE_ID, data);
        }

        private async void OnConnectionReceived(
            StreamSocketListener listener,
            StreamSocketListenerConnectionReceivedEventArgs args)
        {
            msgStatus.Text = "Odczytuje...";

            _provider.StopAdvertising();
            listener.Dispose();

            StreamSocket _socket = args.Socket;
            StreamReader reader = new StreamReader(_socket.InputStream.AsStreamForRead());

            string response = await reader.ReadLineAsync();
            msgStatus.Text = "Odczytałem...";
            textboxMsg.Text = response + "To odczytalem";

        }
    }
}

发送消息:

代码语言:javascript
复制
namespace WinRFCOMM
{
    public sealed partial class MainPage : Page
    {
        private RfcommDeviceService _service;
        private StreamSocket _socket;
        private DeviceInformationCollection _devices;
        private StreamWriter _writer;

        public MainPage()
        {
            this.InitializeComponent();
            this.Initialize();
        }

        private async void Initialize()
        {
            msgStatus.Text = "Inicjalizacja...";
            _devices = await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.ObexObjectPush));

            this.PopulateDevicesListview(_devices);
            msgStatus.Text = "Oczekiwanie na wybór...";
        }

        private void PopulateDevicesListview(DeviceInformationCollection devices)
        {
            foreach (DeviceInformation di in devices)
            {
                String deviceInfo = di.Name + " - " + di.Id;
                lvDevices.Items.Add(deviceInfo);
            }
        }

        private void btnConnect_Click(object sender, RoutedEventArgs e)
        {
            var selected = lvDevices.SelectedIndex;
            if (selected != -1)
            {
                ConnectToRFC(_devices[selected]);
            }
        }

        private async void ConnectToRFC(DeviceInformation selectedDevice)
        {
            _service = await RfcommDeviceService.FromIdAsync(selectedDevice.Id);

            _socket = new StreamSocket();

            await _socket.ConnectAsync(
                _service.ConnectionHostName,
                _service.ConnectionServiceName,
                SocketProtectionLevel
                    .BluetoothEncryptionAllowNullAuthentication);

            msgStatus.Text = "Połączono...";

            _writer = new StreamWriter(_socket.OutputStream.AsStreamForWrite());
            _writer.WriteLineAsync("Test");
        }
    }
}

两者都有如下清单文件设置:

代码语言:javascript
复制
  <Capabilities>
    <Capability Name="internetClient" />
    <Capability Name="internetClientServer" />
    <Capability Name="privateNetworkClientServer" />
    <DeviceCapability Name="bluetooth" />
  </Capabilities>

我真的很感谢任何人的帮助,因为我已经被困了快两天了。

EN

回答 2

Stack Overflow用户

发布于 2017-05-22 17:59:36

问题不是存在于代码中。

在运行此RFCOMM示例之前,您首先需要配对两个设备。因为

使用RfcommDeviceService.GetDeviceSelector*函数帮助生成可用于枚举所需服务的成对设备实例的AQS查询。

参考:Send a file as a client

票数 0
EN

Stack Overflow用户

发布于 2017-08-30 00:00:24

我找到了this论坛的帖子,它帮我度过了难关。

我的问题是试图使用我发现的用于配对的DeviceInformation作为我与RFCOMM的连接点。

代码语言:javascript
复制
 <DeviceCapability Name="bluetooth.rfcomm">

  <Device Id="any">

   <Function Type ="name:serialPort"/>

  </Device>  

</DeviceCapability>   

而不是只有“蓝牙”这个名字。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44064230

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档