首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在Win物联网上开发树莓Pi3的蓝牙应用

在Win物联网上开发树莓Pi3的蓝牙应用
EN

Stack Overflow用户
提问于 2016-09-10 05:27:37
回答 1查看 1.1K关注 0票数 0

我是个为Windows IOT开发软件的新手。我有关于.Net 3.5和4的信息。当我开始为Win IOT开发时,我发现很多事情都发生了变化。有很多新单词async,await,Task等等。

现在我想从蓝牙读取和写入数据。我可以这样做,但如果我试图在无限循环中写入和读取数据,它会抛出异常。

我有两个函数

阅读:

代码语言:javascript
运行
复制
    private async Task ReadAsync(CancellationToken cancellationToken)
    {
        uint ReadBufferLength = 1024;

        Task<UInt32> loadAsyncTask;

        // If task cancellation was requested, comply
        cancellationToken.ThrowIfCancellationRequested();

        // Set InputStreamOptions to complete the asynchronous read operation when one or more bytes is available
        dataReaderObject.InputStreamOptions = InputStreamOptions.Partial;

        // Create a task object to wait for data on the serialPort.InputStream
        loadAsyncTask = dataReaderObject.LoadAsync(ReadBufferLength).AsTask(cancellationToken);

        // Launch the task and wait
        UInt32 bytesRead = await loadAsyncTask;
        if (bytesRead > 0)
        {
            receivedData = dataReaderObject.ReadString(bytesRead);
        }
        else
        {
            receivedData = "";
        }
    }

写入:

代码语言:javascript
运行
复制
    private async Task SendData(string data)
    {
        if (deviceService != null)
        {
            //send data
            if (string.IsNullOrEmpty(data))
            {
                uiTxtError.Text = "Please specify the string you are going to send";
            }
            else
            {
                //DataWriter dwriter = new DataWriter(streamSocket.OutputStream);              
                UInt32 len = dwriter.MeasureString(data);
                dwriter.WriteUInt32(len);
                dwriter.WriteString(data);
                await dwriter.StoreAsync();
                await dwriter.FlushAsync();


            }

        }
        else
        {
            uiTxtError.Text = "Bluetooth is not connected correctly!";
        }
    }

使用读写的函数。

代码语言:javascript
运行
复制
        await SendData("010C" + Environment.NewLine);
        await ReadAsync(ReadCancellationTokenSource.Token);


        if (!string.IsNullOrEmpty(receivedData))
        {
            string[] splitted = receivedData.Replace("\r", "").Replace(">", "").Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            int a = 0;
            int b = 0;
            if (int.TryParse(splitted[splitted.Length - 1], System.Globalization.NumberStyles.HexNumber, null as IFormatProvider, out b))
            {

                if(int.TryParse(splitted[splitted.Length - 2], System.Globalization.NumberStyles.HexNumber, null as IFormatProvider, out a))
                {
                    uiGaugeRpm.Value = ((a * 256) + b) / 4;
                }

            }

            receivedData = "";

        }

我在一个具有200ms延迟的无限循环中调用上面的函数(Task.Delay( 200 ))。

代码语言:javascript
运行
复制
        ReadCancellationTokenSource = new CancellationTokenSource();
        if (streamSocket.InputStream != null)
        {
            dataReaderObject = new DataReader(streamSocket.InputStream);

            try
            {
                while (true)
                {
                    await GetRPM();
                    await Task.Delay(200);
                }
            }
            catch (Exception excp)
            {
                MessageDialog dialog = new MessageDialog(excp.Message);
                await dialog.ShowAsync();
            }


        }

循环开始后,它会得到正确无误的数据,但在几次循环之后,它会抛出异常。

如果我在write函数中创建数据写入器对象,它会抛出未处理的异常并停止应用程序。我通过在连接后只创建一次这个对象来解决这个问题。现在我得到了新的异常。

loadAsyncTask = dataReaderObject.LoadAsync(ReadBufferLength).AsTask(cancellationToken);

在这一行我得到了ObjectDisposedException,我观察到了对象,但我看不到任何被处理的东西。

我正在使用rfcomm协议连接到ELM327蓝牙设备。我是为Win IOT开发的新手。

此外,我不能将绑定与异步函数一起使用。

你能帮帮我吗?

EN

回答 1

Stack Overflow用户

发布于 2016-09-12 20:58:50

是的,不幸的是,现在都是关于任务的。线程在UWP框架中不可用。仅核心。

我建议你使用几个自动收报机来处理这个问题。1个报价器用于发送,1个用于接收。

例如:

代码语言:javascript
运行
复制
DispatcherTimer receiveTimer;
DispatcherTimer senderTimer;

//class MainPage : Page  ... etc ...


private async Task SetupAsync()
{
    this.bluetoothApp = await Bluetooth.CreateAsync();

    this.receiveTimer = new DispatcherTimer();
    this.receiveTimer.Interval = TimeSpan.FromMilliseconds(1000);
    this.receiveTimer.Tick += this.ReceiveTimer_Tick;
    this.receiveTimer.Start();

    this.senderTimer = new DispatcherTimer();
    this.senderTimer.Interval = TimeSpan.FromMilliseconds(1000);
    this.senderTimer.Tick += this.SenderTimer_Tick;
    this.senderTimer.Start();
}

然后为每个自动收报机提供几种方法:

代码语言:javascript
运行
复制
private void ReceiveTimer_Tick(object sender, object e)
{
    //Receive stuff
}


private void SenderTimer_Tick(object sender, object e)
{
    //Send stuff
}

最后,将其添加到您的主页:

代码语言:javascript
运行
复制
private async void Page_Loaded(object sender, RoutedEventArgs e)
{
    await SetupAsync();
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39419943

复制
相关文章

相似问题

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