Skip to content

Commit

Permalink
little refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
genemars committed Dec 2, 2018
1 parent d6d6525 commit a9918ca
Show file tree
Hide file tree
Showing 4 changed files with 258 additions and 284 deletions.
20 changes: 9 additions & 11 deletions XTenLib/Drivers/CM11.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ limitations under the License.
*/

using System;
using System.IO;
using System.IO.Ports;

namespace XTenLib.Drivers
Expand All @@ -32,8 +31,10 @@ namespace XTenLib.Drivers
/// </summary>
public class CM11 : XTenInterface
{
const int BufferLength = 32;

private SerialPort serialPort;
private string portName = "";
private readonly string portName;

/// <summary>
/// Initializes a new instance of the <see cref="XTenLib.Drivers.CM11"/> class.
Expand All @@ -50,7 +51,6 @@ public CM11(string port)
public bool Open()
{
bool success = false;
//
try
{
bool tryOpen = (serialPort == null);
Expand All @@ -72,21 +72,20 @@ public bool Open()

// DataReceived event won't work under Linux / Mono
//serialPort.DataReceived += HandleDataReceived;
//serialPort.ErrorReceived += HanldeErrorReceived;
//serialPort.ErrorReceived += HandleErrorReceived;
}
if (serialPort.IsOpen == false)
{
serialPort.Open();
}
// Send staus request on connection
this.WriteData(new byte[] { 0x8B });
WriteData(new byte[] { 0x8B });
success = true;
}
catch (Exception e)
{
XTenManager.logger.Error(e);
}

return success;
}

Expand All @@ -98,7 +97,7 @@ public void Close()
if (serialPort != null)
{
//serialPort.DataReceived -= HandleDataReceived
//serialPort.ErrorReceived -= HanldeErrorReceived;
//serialPort.ErrorReceived -= HandleErrorReceived;
try
{
//serialPort.Dispose();
Expand All @@ -118,19 +117,18 @@ public void Close()
/// <returns>The data.</returns>
public byte[] ReadData()
{
int buflen = 32;
int length = 0;
int readBytes = 0;
byte[] buffer = new byte[buflen];
byte[] buffer = new byte[BufferLength];
do
{
readBytes = serialPort.Read(buffer, length, buflen - length);
readBytes = serialPort.Read(buffer, length, BufferLength - length);
length += readBytes;
if (length > 1 && buffer[0] < length)
break;
else if (buffer[0] > 0x10 && serialPort.BytesToRead == 0)
break;
} while (readBytes > 0 && (buflen - length > 0));
} while (readBytes > 0 && (BufferLength - length > 0));

byte[] readData = new byte[length + 1];
if (length > 1 && length < 13)
Expand Down
141 changes: 63 additions & 78 deletions XTenLib/Drivers/CM15.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ limitations under the License.
using System.Threading;

using LibUsbDotNet;
using LibUsbDotNet.Info;
using LibUsbDotNet.Main;

namespace XTenLib.Drivers
Expand All @@ -35,21 +34,18 @@ namespace XTenLib.Drivers
/// </summary>
public class CM15 : XTenInterface, IDisposable
{
private UsbDeviceFinder MyUsbFinder = new UsbDeviceFinder(0x0BC7, 0x0001);
//Use the first read endpoint
//private readonly byte TRANFER_ENDPOINT = UsbConstants.ENDPOINT_DIR_MASK;
// Number of transfers to sumbit before waiting begins</summary>
//private readonly int TRANFER_MAX_OUTSTANDING_IO = 3;
// Number of transfers before terminating the test
//private readonly int TRANSFER_COUNT = 30;
// Size of each transfer
//private int TRANFER_SIZE = 16;
// Timeout
private const int TransferTimeout = 1000;
// Max size of each transfer
private const int TransferSize = 8;
// Max packet size
private const int MaxPacketSize = 16;

//private DateTime startTime = DateTime.MinValue;
private readonly UsbDeviceFinder myUsbFinder = new UsbDeviceFinder(0x0BC7, 0x0001);
private UsbDevice myUsbDevice;

private UsbEndpointReader reader = null;
private UsbEndpointWriter writer = null;
private UsbEndpointReader reader;
private UsbEndpointWriter writer;

/// <summary>
/// Releases all resource used by the <see cref="XTenLib.Drivers.CM15"/> object.
Expand All @@ -60,24 +56,22 @@ public class CM15 : XTenInterface, IDisposable
/// the garbage collector can reclaim the memory that the <see cref="XTenLib.Drivers.CM15"/> was occupying.</remarks>
public void Dispose()
{
if (myUsbDevice != null && myUsbDevice.IsOpen)
if (myUsbDevice == null || !myUsbDevice.IsOpen) return;
try
{
try
{
reader.Abort();
}
catch (Exception e)
{
XTenManager.logger.Error(e);
}
try
{
writer.Abort();
}
catch (Exception e)
{
XTenManager.logger.Error(e);
}
reader.Abort();
}
catch (Exception e)
{
XTenManager.logger.Error(e);
}
try
{
writer.Abort();
}
catch (Exception e)
{
XTenManager.logger.Error(e);
}
}

Expand All @@ -91,7 +85,7 @@ public bool Open()
try
{
// Find and open the usb device.
myUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);
myUsbDevice = UsbDevice.OpenUsbDevice(myUsbFinder);
// If the device is open and ready
if (myUsbDevice == null)
throw new Exception("X10 CM15Pro device not connected.");
Expand All @@ -114,8 +108,8 @@ public bool Open()
reader = myUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);
// open write endpoint 2.
writer = myUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep02);
// status request
this.WriteData(new byte[] { 0x8B });
// CM15 initialization / status request
WriteData(new byte[] { 0x8B });
}
catch (Exception e)
{
Expand All @@ -130,23 +124,21 @@ public bool Open()
/// </summary>
public void Close()
{
if (myUsbDevice != null)
if (myUsbDevice == null) return;
if (myUsbDevice.DriverMode == UsbDevice.DriverModeType.MonoLibUsb)
{
if (myUsbDevice.DriverMode == UsbDevice.DriverModeType.MonoLibUsb)
try
{
try
{
myUsbDevice.Close();
}
catch (Exception e)
{
XTenManager.logger.Error(e);
}
myUsbDevice.Close();
}
catch (Exception e)
{
XTenManager.logger.Error(e);
}
myUsbDevice = null;
UsbDevice.Exit();
this.Dispose();
}
myUsbDevice = null;
UsbDevice.Exit();
Dispose();
}

/// <summary>
Expand All @@ -155,28 +147,26 @@ public void Close()
/// <returns>The data.</returns>
public byte[] ReadData()
{
ErrorCode ecRead;
int transferredIn;
UsbTransfer usbReadTransfer = null;
byte[] readBuffer;
UsbTransfer usbReadTransfer;
//
readBuffer = new byte[16];
ecRead = reader.SubmitAsyncTransfer(readBuffer, 0, 8, 1000, out usbReadTransfer);
var readBuffer = new byte[MaxPacketSize];
var ecRead = reader.SubmitAsyncTransfer(readBuffer, 0, TransferSize, TransferTimeout, out usbReadTransfer);
if (ecRead != ErrorCode.None)
{
throw new Exception("Submit Async Read Failed.");
}
WaitHandle.WaitAll(new WaitHandle[] { usbReadTransfer.AsyncWaitHandle }, 1000, false);
WaitHandle.WaitAll(new WaitHandle[] { usbReadTransfer.AsyncWaitHandle }, TransferTimeout, false);
ecRead = usbReadTransfer.Wait(out transferredIn);

if (!usbReadTransfer.IsCompleted)
{
ecRead = reader.SubmitAsyncTransfer(readBuffer, 8, 8, 1000, out usbReadTransfer);
ecRead = reader.SubmitAsyncTransfer(readBuffer, transferredIn, MaxPacketSize-transferredIn, TransferTimeout, out usbReadTransfer);
if (ecRead != ErrorCode.None)
{
throw new Exception("Submit Async Read Failed.");
}
WaitHandle.WaitAll(new WaitHandle[] { usbReadTransfer.AsyncWaitHandle }, 1000, false);
WaitHandle.WaitAll(new WaitHandle[] { usbReadTransfer.AsyncWaitHandle }, TransferTimeout, false);
}

if (!usbReadTransfer.IsCompleted)
Expand All @@ -191,10 +181,10 @@ public byte[] ReadData()
}
usbReadTransfer.Dispose();

byte[] readdata = new byte[transferredIn];
Array.Copy(readBuffer, readdata, transferredIn);
byte[] readData = new byte[transferredIn];
Array.Copy(readBuffer, readData, transferredIn);

return readdata;
return readData;
}

/// <summary>
Expand All @@ -204,28 +194,23 @@ public byte[] ReadData()
/// <param name="bytesToSend">Bytes to send.</param>
public bool WriteData(byte[] bytesToSend)
{
ErrorCode ecWrite;
int transferredOut;
UsbTransfer usbWriteTransfer = null;

if (myUsbDevice != null)
if (myUsbDevice == null) return false;
UsbTransfer usbWriteTransfer;
var ecWrite = writer.SubmitAsyncTransfer(bytesToSend, 0, bytesToSend.Length, TransferTimeout, out usbWriteTransfer);
if (ecWrite != ErrorCode.None)
{
ecWrite = writer.SubmitAsyncTransfer(bytesToSend, 0, bytesToSend.Length, 1000, out usbWriteTransfer);
if (ecWrite != ErrorCode.None)
{
throw new Exception("Submit Async Write Failed.");
}
throw new Exception("Submit Async Write Failed.");
}

WaitHandle.WaitAll(new WaitHandle[] { usbWriteTransfer.AsyncWaitHandle }, 1000, false);
WaitHandle.WaitAll(new WaitHandle[] { usbWriteTransfer.AsyncWaitHandle }, TransferTimeout, false);

if (!usbWriteTransfer.IsCompleted)
usbWriteTransfer.Cancel();
ecWrite = usbWriteTransfer.Wait(out transferredOut);
usbWriteTransfer.Dispose();
// TODO: should check if (transferredOut != bytesToSend.Length), and eventually resend?
return true;
}
return false;
if (!usbWriteTransfer.IsCompleted)
usbWriteTransfer.Cancel();
int transferredOut;
ecWrite = usbWriteTransfer.Wait(out transferredOut);
usbWriteTransfer.Dispose();
// TODO: should check if (transferredOut != bytesToSend.Length), and eventually resend?
return true;
}

internal static byte[] BuildTransceivedCodesMessage(string csMonitoredCodes)
Expand Down Expand Up @@ -300,8 +285,8 @@ internal static byte[] BuildTransceivedCodesMessage(string csMonitoredCodes)
byte b1 = (byte)(transceivedCodes >> 8);
byte b2 = (byte)(transceivedCodes);

//byte[] trcommand = new byte[] { 0xbb, 0xff, 0xff, 0x05, 0x00, 0x14, 0x20, 0x28, 0x24, 0x29 }; // transceive all
//byte[] trcommand = new byte[] { 0xbb, 0x40, 0x00, 0x05, 0x00, 0x14, 0x20, 0x28, 0x24, 0x29 }; // autodetect
//byte[] trCommand = new byte[] { 0xbb, 0xff, 0xff, 0x05, 0x00, 0x14, 0x20, 0x28, 0x24, 0x29 }; // transceive all
//byte[] trCommand = new byte[] { 0xbb, 0x40, 0x00, 0x05, 0x00, 0x14, 0x20, 0x28, 0x24, 0x29 }; // autodetect
byte[] trCommand = new byte[] { 0xbb, b1, b2, 0x05, 0x00, 0x14, 0x20, 0x28, 0x24, 0x29 };

return trCommand;
Expand Down
2 changes: 0 additions & 2 deletions XTenLib/Drivers/XTenInterface.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,6 @@ limitations under the License.
* Project Homepage: https://github.com/genielabs/x10-lib-dotnet
*/

using System;

namespace XTenLib.Drivers
{
/// <summary>
Expand Down
Loading

0 comments on commit a9918ca

Please sign in to comment.