logicanalyzer/Software/LogicAnalyzer/SharedDriver/LogicAnalyzerDriver.cs

433 lines
14 KiB
C#
Raw Normal View History

2022-07-13 15:07:56 +00:00
using System.IO.Ports;
2023-01-31 22:12:43 +00:00
using System.Net.Sockets;
using System.Runtime.CompilerServices;
2022-07-03 14:07:25 +00:00
using System.Runtime.InteropServices;
using System.Text;
2023-01-31 22:12:43 +00:00
using System.Text.RegularExpressions;
2022-07-03 14:07:25 +00:00
2022-07-13 15:07:56 +00:00
namespace SharedDriver
2022-07-03 14:07:25 +00:00
{
public class LogicAnalyzerDriver : IDisposable
{
2023-01-31 22:12:43 +00:00
Regex regAddressPort = new Regex("([0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+)\\:([0-9]+)");
2022-07-03 14:07:25 +00:00
StreamReader readResponse;
BinaryReader readData;
Stream baseStream;
SerialPort sp;
2023-01-31 22:12:43 +00:00
TcpClient tcpClient;
2022-07-03 14:07:25 +00:00
public string? DeviceVersion { get; set; }
2022-07-13 15:07:56 +00:00
public event EventHandler<CaptureEventArgs>? CaptureCompleted;
2022-07-03 14:07:25 +00:00
bool capturing = false;
private int channelCount;
private int triggerChannel;
private int preSamples;
2022-07-13 15:07:56 +00:00
private Action<CaptureEventArgs>? currentCaptureHandler;
2022-07-03 14:07:25 +00:00
2023-01-31 22:12:43 +00:00
public bool IsNetwork { get; private set; }
2022-07-03 14:07:25 +00:00
public LogicAnalyzerDriver(string SerialPort, int Bauds)
{
sp = new SerialPort(SerialPort, Bauds);
sp.RtsEnable = true;
sp.DtrEnable = true;
sp.NewLine = "\n";
2022-07-30 22:26:07 +00:00
sp.ReadBufferSize = 1024 * 1024;
sp.WriteBufferSize = 1024 * 1024;
2022-09-03 08:48:59 +00:00
2022-07-03 14:07:25 +00:00
sp.Open();
baseStream = sp.BaseStream;
readResponse = new StreamReader(baseStream);
readData = new BinaryReader(baseStream);
OutputPacket pack = new OutputPacket();
pack.AddByte(0);
baseStream.Write(pack.Serialize());
baseStream.ReadTimeout = 10000;
DeviceVersion = readResponse.ReadLine();
baseStream.ReadTimeout = Timeout.Infinite;
}
2023-01-31 22:12:43 +00:00
public LogicAnalyzerDriver(string AddressPort)
{
var match = regAddressPort.Match(AddressPort);
if (match == null || !match.Success)
throw new ArgumentException("Specified address/port is invalid");
string addr = match.Groups[1].Value;
string port = match.Groups[2].Value;
ushort uport;
if(!ushort.TryParse(port, out uport))
throw new ArgumentException("Specified address/port is invalid");
tcpClient = new TcpClient();
tcpClient.Connect(addr, uport);
baseStream = tcpClient.GetStream();
readResponse = new StreamReader(baseStream);
readData = new BinaryReader(baseStream);
OutputPacket pack = new OutputPacket();
pack.AddByte(0);
baseStream.Write(pack.Serialize());
baseStream.ReadTimeout = 10000;
DeviceVersion = readResponse.ReadLine();
baseStream.ReadTimeout = Timeout.Infinite;
IsNetwork = true;
}
public unsafe bool SendNetworkConfig(string AccesPointName, string Password, string IPAddress, ushort Port)
{
if(IsNetwork)
return false;
NetConfig request = new NetConfig { Port = Port };
byte[] name = Encoding.ASCII.GetBytes(AccesPointName);
byte[] pass = Encoding.ASCII.GetBytes(Password);
byte[] addr = Encoding.ASCII.GetBytes(IPAddress);
Marshal.Copy(name, 0, new IntPtr(request.AccessPointName), name.Length);
Marshal.Copy(pass, 0, new IntPtr(request.Password), pass.Length);
Marshal.Copy(addr, 0, new IntPtr(request.IPAddress), addr.Length);
OutputPacket pack = new OutputPacket();
pack.AddByte(2);
pack.AddStruct(request);
baseStream.Write(pack.Serialize());
baseStream.Flush();
baseStream.ReadTimeout = 5000;
var result = readResponse.ReadLine();
baseStream.ReadTimeout = Timeout.Infinite;
if (result == "SETTINGS_SAVED")
return true;
return false;
}
2023-01-29 15:59:57 +00:00
public CaptureError StartCapture(int Frequency, int PreSamples, int PostSamples, int[] Channels, int TriggerChannel, bool TriggerInverted, Action<CaptureEventArgs>? CaptureCompletedHandler = null)
2022-07-03 14:07:25 +00:00
{
if (capturing)
2023-01-29 15:59:57 +00:00
return CaptureError.Busy;
2022-07-03 14:07:25 +00:00
2023-01-29 15:59:57 +00:00
if (Channels == null || Channels.Length == 0 || PreSamples < 2 || PreSamples > (30 * 1024 - 1) || PostSamples < 512 || (PreSamples + PostSamples) >= (32 * 1024) || Frequency < 3100 || Frequency > 100000000)
return CaptureError.BadParams;
2022-07-03 14:07:25 +00:00
channelCount = Channels.Length;
triggerChannel = Array.IndexOf(Channels, TriggerChannel);
preSamples = PreSamples;
2022-07-13 15:07:56 +00:00
currentCaptureHandler = CaptureCompletedHandler;
2022-07-03 14:07:25 +00:00
CaptureRequest request = new CaptureRequest
{
triggerType = 0,
trigger = (byte)TriggerChannel,
invertedOrCount = TriggerInverted ? (byte)1 : (byte)0,
channels = new byte[32],
channelCount = (byte)Channels.Length,
frequency = (uint)Frequency,
preSamples = (uint)PreSamples,
postSamples = (uint)PostSamples
};
2022-07-13 15:07:56 +00:00
for (int buc = 0; buc < Channels.Length; buc++)
2022-07-03 14:07:25 +00:00
request.channels[buc] = (byte)Channels[buc];
OutputPacket pack = new OutputPacket();
pack.AddByte(1);
pack.AddStruct(request);
baseStream.Write(pack.Serialize());
baseStream.Flush();
baseStream.ReadTimeout = 10000;
var result = readResponse.ReadLine();
baseStream.ReadTimeout = Timeout.Infinite;
if (result == "CAPTURE_STARTED")
{
capturing = true;
2022-07-30 22:26:07 +00:00
Task.Run(() => ReadCapture(PreSamples + PostSamples));
2023-01-29 15:59:57 +00:00
return CaptureError.None;
2022-07-03 14:07:25 +00:00
}
2023-01-29 15:59:57 +00:00
return CaptureError.HardwareError;
2022-07-03 14:07:25 +00:00
}
2023-01-29 15:59:57 +00:00
public CaptureError StartPatternCapture(int Frequency, int PreSamples, int PostSamples, int[] Channels, int TriggerChannel, int TriggerBitCount, UInt16 TriggerPattern, bool Fast, Action<CaptureEventArgs>? CaptureCompletedHandler = null)
2022-07-03 14:07:25 +00:00
{
if (capturing)
2023-01-29 15:59:57 +00:00
return CaptureError.Busy;
2022-07-03 14:07:25 +00:00
2023-01-29 15:59:57 +00:00
if (Channels == null || Channels.Length == 0 || PreSamples < 2 || PreSamples > (30 * 1024 - 1) || PostSamples < 512 || (PreSamples + PostSamples) >= (32 * 1024) || Frequency < 3100 || Frequency > 100000000)
return CaptureError.BadParams;
2022-07-03 14:07:25 +00:00
channelCount = Channels.Length;
triggerChannel = Array.IndexOf(Channels, TriggerChannel);
preSamples = PreSamples;
2022-07-13 15:07:56 +00:00
currentCaptureHandler = CaptureCompletedHandler;
2022-07-03 14:07:25 +00:00
CaptureRequest request = new CaptureRequest
{
triggerType = (byte)(Fast ? 2 : 1),
trigger = (byte)TriggerChannel,
invertedOrCount = (byte)TriggerBitCount,
triggerValue = (UInt16)TriggerPattern,
channels = new byte[32],
channelCount = (byte)Channels.Length,
frequency = (uint)Frequency,
preSamples = (uint)PreSamples,
postSamples = (uint)PostSamples
};
for (int buc = 0; buc < Channels.Length; buc++)
request.channels[buc] = (byte)Channels[buc];
OutputPacket pack = new OutputPacket();
pack.AddByte(1);
pack.AddStruct(request);
baseStream.Write(pack.Serialize());
baseStream.Flush();
baseStream.ReadTimeout = 10000;
var result = readResponse.ReadLine();
baseStream.ReadTimeout = Timeout.Infinite;
if (result == "CAPTURE_STARTED")
{
capturing = true;
2022-07-30 22:26:07 +00:00
Task.Run(() => ReadCapture(PreSamples + PostSamples));
2023-01-29 15:59:57 +00:00
return CaptureError.None;
2022-07-03 14:07:25 +00:00
}
2023-01-29 15:59:57 +00:00
return CaptureError.HardwareError;
2022-07-03 14:07:25 +00:00
}
2022-09-03 08:48:59 +00:00
public bool StopCapture()
{
if (!capturing)
return false;
capturing = false;
sp.Write(new byte[] { 0xFF }, 0, 1);
sp.BaseStream.Flush();
Thread.Sleep(1);
sp.Close();
Thread.Sleep(1);
sp.Open();
baseStream = sp.BaseStream;
readResponse = new StreamReader(baseStream);
readData = new BinaryReader(baseStream);
return true;
}
2022-07-03 14:07:25 +00:00
public void Dispose()
{
try
{
sp.Close();
sp.Dispose();
}
catch { }
2023-01-31 22:12:43 +00:00
try
{
tcpClient.Close();
tcpClient.Dispose();
} catch { }
2022-07-13 15:07:56 +00:00
try
2022-07-03 14:07:25 +00:00
{
baseStream.Close();
baseStream.Dispose();
}
catch { }
2022-07-13 15:07:56 +00:00
try
2022-07-03 14:07:25 +00:00
{
readData.Close();
readData.Dispose();
}
catch { }
2022-07-13 15:07:56 +00:00
2022-07-03 14:07:25 +00:00
try
{
readResponse.Close();
readResponse.Dispose();
}
catch { }
sp = null;
baseStream = null;
readData = null;
readData = null;
DeviceVersion = null;
CaptureCompleted = null;
}
2022-07-30 22:26:07 +00:00
void ReadCapture(int Samples)
2022-07-03 14:07:25 +00:00
{
2022-07-30 22:26:07 +00:00
try
{
2023-01-31 22:12:43 +00:00
/*
2022-07-30 22:26:07 +00:00
byte[] readBuffer = new byte[Samples * 4 + 4];
int left = readBuffer.Length;
int pos = 0;
2022-09-03 08:48:59 +00:00
while (left > 0 && sp.IsOpen)
2022-07-30 22:26:07 +00:00
{
pos += sp.Read(readBuffer, pos, left);
left = readBuffer.Length - pos;
}
uint[] samples;
using (MemoryStream ms = new MemoryStream(readBuffer))
{
using (BinaryReader br = new BinaryReader(ms))
{
uint length = br.ReadUInt32();
samples = new uint[length];
for (int buc = 0; buc < length; buc++)
samples[buc] = br.ReadUInt32();
}
}
2023-01-31 22:12:43 +00:00
*/
uint length = readData.ReadUInt32();
uint[] samples = new uint[length];
for (int buc = 0; buc < length; buc++)
samples[buc] = readData.ReadUInt32();
2022-07-30 22:26:07 +00:00
if (currentCaptureHandler != null)
currentCaptureHandler(new CaptureEventArgs { Samples = samples, ChannelCount = channelCount, TriggerChannel = triggerChannel, PreSamples = preSamples });
else if (CaptureCompleted != null)
CaptureCompleted(this, new CaptureEventArgs { Samples = samples, ChannelCount = channelCount, TriggerChannel = triggerChannel, PreSamples = preSamples });
capturing = false;
}
catch(Exception ex)
{
Console.WriteLine(ex.Message + " - " + ex.StackTrace);
}
2022-07-03 14:07:25 +00:00
}
class OutputPacket
{
List<byte> dataBuffer = new List<byte>();
public void AddByte(byte newByte)
{
dataBuffer.Add(newByte);
}
public void AddBytes(IEnumerable<byte> newBytes)
{
dataBuffer.AddRange(newBytes);
}
public void AddString(string newString)
{
dataBuffer.AddRange(Encoding.ASCII.GetBytes(newString));
}
public void AddStruct(object newStruct)
{
int rawSize = Marshal.SizeOf(newStruct);
IntPtr buffer = Marshal.AllocHGlobal(rawSize);
Marshal.StructureToPtr(newStruct, buffer, false);
byte[] rawDatas = new byte[rawSize];
Marshal.Copy(buffer, rawDatas, 0, rawSize);
Marshal.FreeHGlobal(buffer);
dataBuffer.AddRange(rawDatas);
}
public void Clear()
{
dataBuffer.Clear();
}
public byte[] Serialize()
{
List<byte> finalData = new List<byte>();
finalData.Add(0x55);
finalData.Add(0xAA);
2022-07-13 15:07:56 +00:00
for (int buc = 0; buc < dataBuffer.Count; buc++)
2022-07-03 14:07:25 +00:00
{
if (dataBuffer[buc] == 0xAA || dataBuffer[buc] == 0x55 || dataBuffer[buc] == 0xF0)
{
finalData.Add(0xF0);
finalData.Add((byte)(dataBuffer[buc] ^ 0xF0));
}
else
finalData.Add(dataBuffer[buc]);
}
2022-07-13 15:07:56 +00:00
2022-07-03 14:07:25 +00:00
finalData.Add(0xAA);
finalData.Add(0x55);
return finalData.ToArray();
2022-07-13 15:07:56 +00:00
2022-07-03 14:07:25 +00:00
}
}
[StructLayout(LayoutKind.Sequential)]
struct CaptureRequest
{
public byte triggerType;
public byte trigger;
public byte invertedOrCount;
public UInt16 triggerValue;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 24)]
public byte[] channels;
public byte channelCount;
public UInt32 frequency;
public UInt32 preSamples;
public UInt32 postSamples;
}
2023-01-31 22:12:43 +00:00
[StructLayout(LayoutKind.Sequential)]
unsafe struct NetConfig
{
public fixed byte AccessPointName[33];
public fixed byte Password[64];
public fixed byte IPAddress[16];
public UInt16 Port;
}
2022-07-03 14:07:25 +00:00
}
2023-01-29 15:59:57 +00:00
public enum CaptureError
{
None,
Busy,
BadParams,
HardwareError
}
2022-07-03 14:07:25 +00:00
public class CaptureEventArgs : EventArgs
{
public int TriggerChannel { get; set; }
public int ChannelCount { get; set; }
public int PreSamples { get; set; }
public uint[] Samples { get; set; }
}
2022-07-13 15:07:56 +00:00
}