在Win IOT上为Raspberry Pi3开发蓝牙应用



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

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

我有两个函数

阅读:

    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 = "";
        }
    }

写:

    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!";
        }
    }

使用读写的函数。

        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 = "";
        }

在无限循环中调用上面的函数,延迟200毫秒(Task.Delay(200))。

        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();
            }

        }

在循环开始后,它得到正确的数据,但是在几个循环之后,它抛出异常。

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

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

在这行我得到ObjectDisposedException,我观察到对象,但我看不到任何被处置的

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

我也不能在async函数中使用绑定。

请你帮我一下好吗?

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

我建议你使用几个代码来处理这个问题。发送1个,接收1个。

例如:

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();
}

然后为每个计时器提供两个方法:

private void ReceiveTimer_Tick(object sender, object e)
{
    //Receive stuff
}

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

最后添加到你的主页:

private async void Page_Loaded(object sender, RoutedEventArgs e)
{
    await SetupAsync();
}

相关内容

  • 没有找到相关文章

最新更新