Code cleanup

This commit is contained in:
Morten Nielsen 2018-07-25 21:02:54 -07:00
parent b6f806c95a
commit 45665413d1
4 changed files with 107 additions and 122 deletions

View file

@ -1,18 +1,18 @@
//
// Copyright (c) 2014 Morten Nielsen
//
// Licensed under the Microsoft Public License (Ms-PL) (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://opensource.org/licenses/Ms-PL.html
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
// Copyright (c) 2014 Morten Nielsen
//
// Licensed under the Microsoft Public License (Ms-PL) (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://opensource.org/licenses/Ms-PL.html
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#if NETFX_CORE
using System;
using System.Collections.Generic;
@ -23,11 +23,9 @@ using System.Threading.Tasks;
using Windows.Networking.Sockets;
using Windows.Devices.Bluetooth.Rfcomm;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading;
using Windows.Devices.Enumeration;
#if WINDOWS_UWP
using System.Threading;
using Windows.Devices.Enumeration;
using Windows.Networking.Proximity;
#endif
namespace NmeaParser
{
@ -37,39 +35,36 @@ namespace NmeaParser
public class BluetoothDevice : NmeaDevice
{
private Windows.Devices.Bluetooth.Rfcomm.RfcommDeviceService m_deviceService;
#if WINDOWS_UWP
private Windows.Networking.Proximity.PeerInformation m_devicePeer;
#endif
private StreamSocket m_socket;
private bool m_disposeService;
/// <summary>
/// Gets a list of bluetooth devices that supports serial communication
/// </summary>
private StreamSocket m_socket;
private bool m_disposeService;
private SemaphoreSlim m_semaphoreSlim = new SemaphoreSlim(1, 1);
/// <summary>
/// Gets a list of bluetooth devices that supports serial communication
/// </summary>
/// <returns></returns>
public static async Task<IEnumerable<RfcommDeviceService>> GetBluetoothSerialDevicesAsync()
{
string serialDeviceType = RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort);
var devices = await DeviceInformation.FindAllAsync(serialDeviceType);
List<RfcommDeviceService> services = new List<RfcommDeviceService>();
foreach(var d in devices)
services.Add(await RfcommDeviceService.FromIdAsync(d.Id));
return services;
}
{
string serialDeviceType = RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort);
var devices = await DeviceInformation.FindAllAsync(serialDeviceType);
List<RfcommDeviceService> services = new List<RfcommDeviceService>();
foreach(var d in devices)
services.Add(await RfcommDeviceService.FromIdAsync(d.Id));
return services;
}
/// <summary>
/// Initializes a new instance of the <see cref="BluetoothDevice"/> class.
/// </summary>
/// <param name="service">The RF Comm Device service.</param>
/// <param name="service">The RF Comm Device service.</param>
/// <param name="disposeService">Whether this devicee should also dispose the RfcommDeviceService provided when this device disposes.</param>
public BluetoothDevice(RfcommDeviceService service, bool disposeService = false)
{
m_deviceService = service;
m_disposeService = disposeService;
m_disposeService = disposeService;
}
#if WINDOWS_UWP
/// <summary>
/// Initializes a new instance of the <see cref="BluetoothDevice"/> class.
/// </summary>
@ -78,16 +73,15 @@ namespace NmeaParser
{
m_devicePeer = peer;
}
#endif
/// <inheritdoc />
protected override void Dispose(bool disposing)
{
if (m_disposeService && m_deviceService != null)
m_deviceService.Dispose();
m_deviceService = null;
m_devicePeer = null;
base.Dispose(disposing);
protected override void Dispose(bool disposing)
{
if (m_disposeService && m_deviceService != null)
m_deviceService.Dispose();
m_deviceService = null;
m_devicePeer = null;
base.Dispose(disposing);
}
/// <summary>
@ -98,18 +92,16 @@ namespace NmeaParser
{
var socket = new Windows.Networking.Sockets.StreamSocket();
socket.Control.KeepAlive = true;
#if WINDOWS_UWP
if (m_devicePeer != null)
{
await socket.ConnectAsync(m_devicePeer.HostName, "1");
}
else
#endif
{
await socket.ConnectAsync(m_deviceService.ConnectionHostName, m_deviceService.ConnectionServiceName);
}
m_socket = socket;
return null; //We're going to use WinRT buffers instead and will handle read/write, so no reason to return a stream
return null; //We're going to use WinRT buffers instead and will handle read/write, so no reason to return a stream. This is mainly done to avoid locking issues reading and writing at the same time
}
/// <summary>
@ -119,51 +111,50 @@ namespace NmeaParser
/// <returns></returns>
protected override Task CloseStreamAsync(System.IO.Stream stream)
{
if(m_socket == null)
throw new InvalidOperationException("No connection to close");
if(m_socket == null)
throw new InvalidOperationException("No connection to close");
m_socket.Dispose();
m_socket = null;
return Task.FromResult(true);
}
private static SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1, 1);
/// <inheritdoc />
protected override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
// Reading and writing to the Bluetooth serial connection at the same time seems very unstable in UWP,
// so we use a semaphore to ensure we don't read and write at the same time
await semaphoreSlim.WaitAsync().ConfigureAwait(false);
try
{
var r = await m_socket.InputStream.ReadAsync(buffer.AsBuffer(), (uint)count, Windows.Storage.Streams.InputStreamOptions.None);
return (int)r.Length;
}
finally
{
semaphoreSlim.Release();
}
protected override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
// Reading and writing to the Bluetooth serial connection at the same time seems very unstable in UWP,
// so we use a semaphore to ensure we don't read and write at the same time
await m_semaphoreSlim.WaitAsync().ConfigureAwait(false);
try
{
var r = await m_socket.InputStream.ReadAsync(buffer.AsBuffer(), (uint)count, Windows.Storage.Streams.InputStreamOptions.None);
return (int)r.Length;
}
finally
{
m_semaphoreSlim.Release();
}
}
/// <inheritdoc />
public override bool CanWrite => true;
/// <inheritdoc />
public override async Task WriteAsync(byte[] buffer, int offset, int length)
{
if (m_socket == null)
throw new InvalidOperationException("Device not open");
// Reading and writing to the Bluetooth serial connection at the same time seems very unstable in UWP,
// so we use a semaphore to ensure we don't read and write at the same time
await semaphoreSlim.WaitAsync().ConfigureAwait(false);
try
{
await m_socket.OutputStream.WriteAsync(buffer.AsBuffer(offset, length)).AsTask().ConfigureAwait(false);
}
finally
{
semaphoreSlim.Release();
}
public override async Task WriteAsync(byte[] buffer, int offset, int length)
{
if (m_socket == null)
throw new InvalidOperationException("Device not open");
// Reading and writing to the Bluetooth serial connection at the same time seems very unstable in UWP,
// so we use a semaphore to ensure we don't read and write at the same time
await m_semaphoreSlim.WaitAsync().ConfigureAwait(false);
try
{
await m_socket.OutputStream.WriteAsync(buffer.AsBuffer(offset, length)).AsTask().ConfigureAwait(false);
}
finally
{
m_semaphoreSlim.Release();
}
}
}
}

View file

@ -27,40 +27,33 @@ namespace NmeaParser
/// A Serial Port NMEA device
/// </summary>
public class SerialPortDevice : NmeaDevice
{
private System.IO.Ports.SerialPort m_port;
/// <summary>
/// Initializes a new instance of the <see cref="SerialPortDevice" /> class.
/// </summary>
/// <param name="port">The serial port.</param>
/// <exception cref="System.ArgumentNullException">port</exception>
public SerialPortDevice(System.IO.Ports.SerialPort port)
{
/// <summary>
/// Initializes a new instance of the <see cref="SerialPortDevice" /> class.
/// </summary>
/// <param name="port">The serial port.</param>
/// <exception cref="System.ArgumentNullException">port</exception>
public SerialPortDevice(System.IO.Ports.SerialPort port)
{
if (port == null)
throw new ArgumentNullException("port");
m_port = port;
}
/// <summary>
/// Gets the active serial port.
/// </summary>
public System.IO.Ports.SerialPort Port
Port = port;
}
/// <summary>
/// Gets the active serial port.
/// </summary>
public System.IO.Ports.SerialPort Port { get; }
/// <summary>
/// Creates the stream the NmeaDevice is working on top off.
/// </summary>
/// <returns></returns>
protected override Task<System.IO.Stream> OpenStreamAsync()
{
get
{
return m_port;
}
}
/// <summary>
/// Creates the stream the NmeaDevice is working on top off.
/// </summary>
/// <returns></returns>
protected override Task<System.IO.Stream> OpenStreamAsync()
{
m_port.Open();
return Task.FromResult<System.IO.Stream>(m_port.BaseStream);
if (!Port.IsOpen)
Port.Open();
return Task.FromResult<System.IO.Stream>(Port.BaseStream);
}
/// <summary>
@ -69,9 +62,10 @@ namespace NmeaParser
/// <param name="stream">The stream.</param>
/// <returns></returns>
protected override Task CloseStreamAsync(System.IO.Stream stream)
{
m_port.Close();
return Task.FromResult(true);
{
if (Port.IsOpen)
Port.Close();
return Task.FromResult<object>(null);
}
/// <summary>
@ -84,7 +78,7 @@ namespace NmeaParser
[Obsolete("Use WriteAsync")]
public void Write(byte[] buffer, int offset, int count)
{
m_port.Write(buffer, offset, count);
Port.Write(buffer, offset, count);
}
/// <inheritdoc />
@ -93,10 +87,10 @@ namespace NmeaParser
/// <inheritdoc />
public override Task WriteAsync(byte[] buffer, int offset, int length)
{
if (!m_port.IsOpen)
if (!Port.IsOpen)
throw new InvalidOperationException("Device not open");
m_port.Write(buffer, offset, length);
Port.Write(buffer, offset, length);
return Task.FromResult<object>(null);
}
}

View file

@ -71,7 +71,8 @@ namespace NmeaParser
/// <returns></returns>
protected override Task CloseStreamAsync(System.IO.Stream stream)
{
return Task.FromResult(true);
stream.Dispose();
return Task.CompletedTask;
}
/// <summary>

View file

@ -68,7 +68,6 @@ namespace NmeaParser
m_stream = null;
}
/// <inheritdoc />
public override bool CanWrite => m_stream?.CanWrite == true;