Files
laatzen/Common/OmniPlus/Connections/UniProStream.cs
T

87 lines
2.2 KiB
C#

namespace OmniPlus.Connections
{
using System;
using System.Threading;
internal class UniProStream : SerialDataReader
{
private readonly UniProEncoder encoder;
public UniProStream(SerialPortSettings settings) : base(settings)
{
this.encoder = new UniProEncoder();
}
public byte[] Write(params byte[] bytes)
{
this.StartListening();
this.WriteBytes(bytes);
var response = new byte[0];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
var message = this.DequeueMessage();
if (message != null)
{
if (this.encoder.TryDecode(message, out response))
{
this.ClearMessages();
break;
}
else
{
Thread.Sleep(200);
}
}
else
{
Thread.Sleep(200);
}
}
if (response.Length > 0)
{
break;
}
Thread.Sleep(200);
}
this.StopListening();
return response;
}
public override void WriteBytes(params byte[] bytes)
{
if (this.encoder.TryEncode(bytes, out byte[] message))
{
base.WriteBytes(message);
}
}
protected override void BeginRead(byte[] buffer)
{
var start = Array.IndexOf(buffer, this.encoder.Device2PC);
if (start >= 0)
{
if (this.encoder.TryDecode(buffer, out byte[] message))
{
this.EnqueueMessage(message);
this.RemoveRange(message.Length);
}
}
else
{
this.RemoveRange(buffer.Length);
}
}
}
}