0

I am new at developing softwares for Windows IOT. I have information about .Net 3.5 and 4. When I start to develop for Win IOT, I saw that lots of things have changed. There are a lot of new words async, await, Task etc.

Now I want to read and write data from bluetooth. I can do it but if I try to write and read data in a infinite loop it throws exceptions.

I have 2 functions

Read :

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

Write :

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

Function that use read and write.

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

        }

I call function above in a infinite loop with 200 ms delays (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();
            }


        }

After loop starts, it gets data true and fine, but a few loop later it throws exceptions.

If I create datawriter object in write function it throws unhandled exception and stops application. I solve this by creating this object only one time after connection. Now I get new exception.

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

At this line I get ObjectDisposedException, I observed the objects but I could not see anything disposed.

I am connecting to ELM327 bluetooth device with rfcomm protocol. I am newbie at developing for Win IOT.

Also I could not use bindings with async functions.

Please, could you help me?

Paul Andrew
  • 3,233
  • 2
  • 17
  • 37
MIrchhh
  • 19
  • 1
  • 5
  • The exception seems pretty clear to me. You're trying to use an object that's been disposed. If you want help here, you need to provide a good [mcve] that reliably reproduces the problem. See also [ask] for information on how to present your question in a clear, answerable way. – Peter Duniho Sep 09 '16 at 22:42

1 Answers1

0

Yes unfortunately it's all about Tasks now. Threading isn't available in the UWP framework. Only Core.

I would suggest you use a couple of tickers to handle this. 1 ticker for sending and 1 for receiving.

For example:

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

Then a couple of methods for each ticker:

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


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

Finally add that to your main page:

private async void Page_Loaded(object sender, RoutedEventArgs e)
{
    await SetupAsync();
}
Paul Andrew
  • 3,233
  • 2
  • 17
  • 37
  • I try same application on my computer. I developed a dummy elm327 application. It sends data of speed, rpm and temperature. I have a bluetooth module. I connect its TTL side with a FTDI chip and bluetooth side with a bluetooth. TTL side sends data for the commands. Same thing happen on my computer. First a few seconds, my application gets data and shows it on gauges. Later, System.ObjectDisposedException occurs. I could not understand why it is happen. – MIrchhh Sep 12 '16 at 16:24
  • I find the line that exception occurs. after calling DataReader.LoadAsync function this exception fired. I find http://stackoverflow.com/questions/16110561/winrt-datareader-loadasync-exception-with-streamsocket-tcp but this solution does not solve my problem. – MIrchhh Sep 12 '16 at 16:28