optimize bluetooth serial connection

This commit is contained in:
Roman Lumetsberger committed 2017-05-07 17:12:22 +02:00
1 parent 2eef2f5e88
commit 1a80a8729f
1 file changed
+11 -11
@@ -1,6 +1,6 @@
using System; using System;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text; using System.Text;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Windows.Devices.Bluetooth.Rfcomm; using Windows.Devices.Bluetooth.Rfcomm;
using Windows.Networking.Sockets; using Windows.Networking.Sockets;
@@ -12,7 +12,6 @@ namespace OBD.NET.Communication
{ {
private StreamSocket _socket; private StreamSocket _socket;
private DataReader _reader;
private DataWriter _writer; private DataWriter _writer;
private readonly byte[] _readBuffer = new byte[1024]; private readonly byte[] _readBuffer = new byte[1024];
@@ -51,6 +50,7 @@ namespace OBD.NET.Communication
service.ConnectionServiceName); service.ConnectionServiceName);
_writer = new DataWriter(_socket.OutputStream); _writer = new DataWriter(_socket.OutputStream);
StartReader(); StartReader();
IsOpen = true;
} }
@@ -60,24 +60,24 @@ namespace OBD.NET.Communication
{ {
Task.Factory.StartNew(async () => Task.Factory.StartNew(async () =>
{ {
_reader = new DataReader(_socket.InputStream);
var buffer = _readBuffer.AsBuffer();
while (true) while (true)
{ {
await _reader.LoadAsync(1); var readData = await _socket.InputStream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.Partial);
var data = _reader.ReadByte(); SerialPortOnDataReceived(readData);
_readBuffer[0] = data;
SerialPortOnDataReceived();
} }
}); });
} }
private void SerialPortOnDataReceived() private void SerialPortOnDataReceived(IBuffer buffer)
{ {
int count = 1;
for (int i = 0; i < count; i++) for (uint i = 0; i < buffer.Length; i++)
{ {
char c = (char)_readBuffer[i]; char c = (char)buffer.GetByte(i);
switch (c) switch (c)
{ {
case '\r': case '\r':