Added COM port connection to SIRT

This commit is contained in:
Stoyan Zlatev
2024-06-07 10:44:35 +02:00
parent b840e3cbba
commit 495c910d11
19 changed files with 974 additions and 61 deletions
@@ -0,0 +1,54 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{B23BFAF9-08AE-4311-8C08-FB2BB49EA2AD}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Common.Hardware.Interfaces.Ports.SIRT</RootNamespace>
<AssemblyName>Common.Hardware.Interfaces.Ports.SIRT</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="SIRTMessage.cs" />
<Compile Include="SIRTPort.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Common.Hardware.Interfaces.Ports\Common.Hardware.Interfaces.Ports.csproj">
<Project>{9ae071c0-db12-4e09-a3c7-43f6dcd518d6}</Project>
<Name>Common.Hardware.Interfaces.Ports</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Common.Hardware.Interfaces.Ports.SIRT")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Common.Hardware.Interfaces.Ports.SIRT")]
[assembly: AssemblyCopyright("Copyright © 2024")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b23bfaf9-08ae-4311-8c08-fb2bb49ea2ad")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
@@ -0,0 +1,159 @@
namespace Common.Hardware.Interfaces.Ports.SIRT
{
using System;
public class SIRTMessage
{
public const Int32 LengthI = 8;
public const Int32 MinLength = 12;
public const Int32 PC2SIRT = 0x55;
public const Int32 SIRT2PC = 0xFF;
public const Int32 STOP = 0x16;
private const Int32 StartI = 0;
private const Int32 DirectionI = 1;
private const Int32 P1I = 2;
private const Int32 P2I = 3;
private const Int32 AddressI = 4;
private const Int32 AddressL = 4;
private const Int32 DataI = 9;
private const Int32 CRCI = -3;
private const Int32 CRCL = 2;
private const Int32 StopI = -1;
private readonly Byte[] bytes;
public SIRTMessage(Byte[] bytes)
=> this.bytes = bytes;
public SIRTMessage()
{
this.bytes = new Byte[MinLength];
this.bytes[StartI] = PC2SIRT;
this.bytes[this.Length + StopI] = STOP;
}
public Int32 Length
{
get => this.bytes.Length;
}
public Byte Start
{
get => this.bytes[StartI];
}
public Byte Direction
{
get => this.bytes[DirectionI];
set => this.bytes[DirectionI] = value;
}
public Byte P1
{
get => this.bytes[P1I];
set => this.bytes[P1I] = value;
}
public Byte P2
{
get => this.bytes[P2I];
set => this.bytes[P2I] = value;
}
public Byte[] Address
{
get => this.bytes.SubArray(AddressI, AddressL);
set => this.bytes.SubArray(AddressI, value);
}
public Byte DataLength
{
get => this.bytes[LengthI];
}
public Byte[] Data
{
get => this.bytes.SubArray(DataI, this.DataLength);
set
{
this.bytes[LengthI] = (Byte)value.Length;
this.bytes.Insert(DataI, value);
this.CalculateCRCCCITT();
}
}
public Byte[] CRC
{
get => this.bytes.SubArray(this.Length + CRCI, CRCL);
set => this.bytes.SubArray(this.Length + CRCI, value);
}
public byte Stop
{
get => this.bytes[this.Length + StopI];
}
public override String ToString()
=> BitConverter.ToString(this.bytes);
private void CalculateCRCCCITT()
{
UInt32 ccitt(UInt16 start, UInt16 length)
{
Byte zeichen, test;
UInt16 crc_result;
UInt16 ui_index;
Byte h;
if (this.Length < start + length)
{
return 0;
}
crc_result = 0xFFFF;
ui_index = start;
while (ui_index < length + start)
{
zeichen = this.bytes[ui_index];
ui_index++;
for (h = 0; h < 8; h++)
{
test = 0;
if ((crc_result & 0x8000) != 0)
{
test = 0x80;
}
crc_result <<= 1;
if (((zeichen & 0x80) ^ test) != 0)
{
crc_result ^= 0x1021;
}
zeichen <<= 1;
}
}
return crc_result;
}
var crci = this.Length + CRCI;
var crc = ccitt(1, (UInt16)crci);
var crcBytes = BitConverter.GetBytes(crc);
this.bytes[crci + 0] = crcBytes[1];
this.bytes[crci + 1] = crcBytes[0];
}
public static implicit operator Byte[] (SIRTMessage message)
=> message.bytes;
public static implicit operator SIRTMessage(Byte[] bytes)
=> new SIRTMessage(bytes);
}
}
@@ -0,0 +1,138 @@
namespace Common.Hardware.Interfaces.Ports.SIRT
{
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
public class SIRTPort : SerialPort
{
private readonly List<Byte> buffer;
public SIRTPort(String serialPortName) : base(new SerialPortSettings
{
BaudRate = SerialPortBaudRate.X115200,
DataBits = SerialPortDataBits.X8,
Parity = SerialPortParity.None,
PortName = serialPortName,
StopBits = SerialPortStopBits.One
}) => this.buffer = new List<Byte>();
public event Action<SIRTMessage> MessageReceived;
public override void Open()
{
base.Open();
Task.Factory
.StartNew(this.StartParsing, this, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)
.ContinueWith(task =>
{
if (task.Exception != null)
{
this.NotifyInfoMessage(task.Exception.ToString());
}
this.Close();
});
this.Write(new SIRTMessage()
{
Direction = 0x84,
P2 = 0x04,
Address = new Byte[] { 0x20, 0x00, 0x00, 0x00 },
Data = new Byte[] { 0x00, 0x80, 0x80, 0x01 },
});
}
public void Write(SIRTMessage message)
=> base.Write(message, 0, message.Length);
private void StartParsing(object state)
{
var SIRTPort = state as SIRTPort;
if (SIRTPort is null)
{
return;
}
var buffer = new List<Byte>();
var reading = true;
var readingTask = Task.Factory
.StartNew(this.StartReading, state, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)
.ContinueWith(task =>
{
if (task.Exception != null)
{
this.NotifyInfoMessage(task.Exception.ToString());
}
reading = false;
});
var messageReceived = SIRTPort.MessageReceived;
while (reading)
{
var bufferLength = buffer.Count;
if (bufferLength < SIRTMessage.MinLength)
{
continue;
}
var start = buffer.IndexOf(SIRTMessage.SIRT2PC);
if (start < 0)
{
buffer.RemoveRange(0, bufferLength);
continue;
}
var lengthIndex = start + SIRTMessage.LengthI;
if (lengthIndex >= bufferLength)
{
continue;
}
var length = buffer[lengthIndex];
var dataLength = length + SIRTMessage.MinLength;
if (start + dataLength > bufferLength)
{
continue;
}
var data = new Byte[dataLength];
buffer.CopyTo(start, data, 0, dataLength);
buffer.RemoveRange(0, start + dataLength);
messageReceived?.Invoke(data);
}
}
private void StartReading(object state)
{
var SIRTPort = state as SIRTPort;
if (SIRTPort is null)
{
return;
}
var buffer = SIRTPort.buffer;
while (true)
{
var bytes = SIRTPort.Read();
if (bytes.Length > 0)
{
buffer.AddRange(bytes);
}
}
}
}
}
@@ -0,0 +1,53 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{9AE071C0-DB12-4E09-A3C7-43F6DCD518D6}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Common.Hardware.Interfaces.Ports</RootNamespace>
<AssemblyName>Common.Hardware.Interfaces.Ports</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="SerialPort.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SerialPortBaudRate.cs" />
<Compile Include="SerialPortDataBits.cs" />
<Compile Include="SerialPortParity.cs" />
<Compile Include="SerialPortSettings.cs" />
<Compile Include="SerialPortStopBits.cs" />
<Compile Include="SystemExtensions.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Common.Hardware.Interfaces.Ports")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Common.Hardware.Interfaces.Ports")]
[assembly: AssemblyCopyright("Copyright © 2024")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9ae071c0-db12-4e09-a3c7-43f6dcd518d6")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
@@ -0,0 +1,160 @@
namespace Common.Hardware.Interfaces.Ports
{
using System;
using System.Collections.Concurrent;
using SystemSerialPort = System.IO.Ports.SerialPort;
public class SerialPort
{
private static readonly ConcurrentDictionary<String, SystemSerialPort> serialPorts
= new ConcurrentDictionary<String, SystemSerialPort>();
private readonly SerialPortSettings settings;
public SerialPort(SerialPortSettings settings)
=> this.settings = settings;
public event Action<String> Logging;
public String PortName
=> this.settings?.PortName;
public Boolean IsOpen
=> serialPorts.TryGetValue(this.PortName, out var serialPort)
? serialPort?.IsOpen ?? default(Boolean)
: default(Boolean);
public Int32 ReadBufferSize
=> serialPorts.TryGetValue(this.PortName, out var serialPort)
? serialPort?.ReadBufferSize ?? default(Int32)
: default(Int32);
public virtual void Close()
{
try
{
if (serialPorts.TryRemove(this.PortName, out var serialPort))
{
if (serialPort != null)
{
serialPort.Close();
serialPort.Dispose();
serialPort = null;
this.NotifyInfoMessage($"Disconnected: {this}");
}
else
{
this.NotifyInfoMessage($"{this.PortName} is null!");
}
}
else
{
this.NotifyInfoMessage($"{this.PortName} dose not exists!");
}
}
catch (Exception e)
{
this.NotifyInfoMessage(e.ToString());
}
}
public virtual void Open()
{
try
{
if (serialPorts.TryGetValue(this.PortName, out var serialPort))
{
serialPort.Close();
}
serialPort = new SystemSerialPort
{
BaudRate = this.settings.BaudRate,
DataBits = this.settings.DataBits,
Parity = this.settings.Parity,
PortName = this.PortName,
StopBits = this.settings.StopBits,
DtrEnable = true
};
if (serialPorts.TryAdd(this.PortName, serialPort))
{
serialPort.Open();
this.NotifyInfoMessage($"Connected: {this}");
}
else
{
this.NotifyInfoMessage($"{this.PortName} cann't be addedd!");
}
}
catch (Exception e)
{
this.NotifyInfoMessage(e.ToString());
}
}
public override String ToString()
=> serialPorts.TryGetValue(this.PortName, out var serialPort)
? $"{serialPort.PortName}, " +
$"{serialPort.BaudRate}, " +
$"{serialPort.DataBits}, " +
$"{serialPort.Parity}, " +
$"{serialPort.StopBits}"
: $"{this.settings.PortName}, " +
$"{this.settings.BaudRate}, " +
$"{this.settings.DataBits}, " +
$"{this.settings.Parity}, " +
$"{this.settings.StopBits}";
protected void NotifyInfoMessage(String state)
=> this.Logging?.Invoke(state);
protected virtual Byte[] Read()
{
var bytes = new Byte[0];
if (serialPorts.TryGetValue(this.PortName, out var serialPort) && serialPort.IsOpen)
{
var size = this.ReadBufferSize;
var buffer = new Byte[size];
try
{
var bytesToCopy = serialPort.Read(buffer, 0, size);
bytes = new Byte[bytesToCopy];
Buffer.BlockCopy(buffer, 0, bytes, 0, bytesToCopy);
this.NotifyInfoMessage(BitConverter.ToString(bytes));
}
catch (Exception e)
{
this.NotifyInfoMessage(e.ToString());
}
}
return bytes;
}
protected void Write(Byte[] bytes, Int32 start, Int32 length)
{
if (serialPorts.TryGetValue(this.PortName, out var serialPort) && serialPort.IsOpen)
{
try
{
serialPort.Write(bytes, 0, length);
this.NotifyInfoMessage(BitConverter.ToString(bytes));
}
catch (Exception e)
{
this.NotifyInfoMessage(e.ToString());
}
}
}
}
}
@@ -0,0 +1,36 @@
namespace Common.Hardware.Interfaces.Ports
{
using System;
public struct SerialPortBaudRate
{
private readonly Int32 value;
private SerialPortBaudRate(Int32 value)
=> this.value = value;
public override String ToString()
=> this.value.ToString();
public static readonly SerialPortBaudRate X110 = 110;
public static readonly SerialPortBaudRate X300 = 300;
public static readonly SerialPortBaudRate X600 = 600;
public static readonly SerialPortBaudRate X1200 = 1200;
public static readonly SerialPortBaudRate X2400 = 2400;
public static readonly SerialPortBaudRate X4800 = 4800;
public static readonly SerialPortBaudRate X9600 = 9600;
public static readonly SerialPortBaudRate X14400 = 14400;
public static readonly SerialPortBaudRate X19200 = 19200;
public static readonly SerialPortBaudRate X38400 = 38400;
public static readonly SerialPortBaudRate X57600 = 57600;
public static readonly SerialPortBaudRate X115200 = 115200;
public static readonly SerialPortBaudRate X128000 = 128000;
public static readonly SerialPortBaudRate X256000 = 256000;
public static implicit operator SerialPortBaudRate(Int32 baudRate)
=> new SerialPortBaudRate(baudRate);
public static implicit operator Int32(SerialPortBaudRate baudRate)
=> baudRate.value;
}
}
@@ -0,0 +1,24 @@
namespace Common.Hardware.Interfaces.Ports
{
using System;
public struct SerialPortDataBits
{
private readonly Int32 value;
private SerialPortDataBits(Int32 value)
=> this.value = value;
public override String ToString()
=> this.value.ToString();
public static readonly SerialPortDataBits X7 = 7;
public static readonly SerialPortDataBits X8 = 8;
public static implicit operator SerialPortDataBits(Int32 dataBits)
=> new SerialPortDataBits(dataBits);
public static implicit operator Int32(SerialPortDataBits dataBits)
=> dataBits.value;
}
}
@@ -0,0 +1,28 @@
namespace Common.Hardware.Interfaces.Ports
{
using System;
using System.IO.Ports;
public struct SerialPortParity
{
private readonly Parity value;
private SerialPortParity(Parity value)
=> this.value = value;
public override String ToString()
=> this.value.ToString();
public static readonly SerialPortParity None = Parity.None;
public static readonly SerialPortParity Odd = Parity.Odd;
public static readonly SerialPortParity Even = Parity.Even;
public static readonly SerialPortParity Mark = Parity.Mark;
public static readonly SerialPortParity Space = Parity.Space;
public static implicit operator SerialPortParity(Parity parity)
=> new SerialPortParity(parity);
public static implicit operator Parity(SerialPortParity parity)
=> parity.value;
}
}
@@ -0,0 +1,17 @@
namespace Common.Hardware.Interfaces.Ports
{
using System;
public class SerialPortSettings
{
public SerialPortBaudRate BaudRate { get; set; }
public SerialPortDataBits DataBits { get; set; }
public SerialPortParity Parity { get; set; }
public String PortName { get; set; }
public SerialPortStopBits StopBits { get; set; }
}
}
@@ -0,0 +1,27 @@
namespace Common.Hardware.Interfaces.Ports
{
using System;
using System.IO.Ports;
public struct SerialPortStopBits
{
private readonly StopBits value;
private SerialPortStopBits(StopBits value)
=> this.value = value;
public override String ToString()
=> this.value.ToString();
public static readonly SerialPortStopBits None = StopBits.None;
public static readonly SerialPortStopBits One = StopBits.One;
public static readonly SerialPortStopBits Two = StopBits.Two;
public static readonly SerialPortStopBits OnePointFive = StopBits.OnePointFive;
public static implicit operator SerialPortStopBits(StopBits stopBits)
=> new SerialPortStopBits(stopBits);
public static implicit operator StopBits(SerialPortStopBits stopBits)
=> stopBits.value;
}
}
@@ -0,0 +1,37 @@
namespace Common.Hardware.Interfaces.Ports
{
using System;
public static class SystemExtensions
{
public static T[] Insert<T>(this T[] array, Int32 index, T[] items)
{
var arrayLength = array.Length;
var itemsLength = items.Length;
var newArray = new Byte[arrayLength + itemsLength];
var crci = arrayLength - 3;
Buffer.BlockCopy(array, 0, newArray, 0, index);
Buffer.BlockCopy(items, 0, newArray, index, itemsLength);
Buffer.BlockCopy(array, crci, newArray, crci, 3);
return array;
}
public static T[] SubArray<T>(this T[] array, Int32 index, Int32 count)
{
var subArray = new T[count];
Buffer.BlockCopy(array, index, subArray, 0, count);
return array;
}
public static T[] SubArray<T>(this T[] array, Int32 index, T[] items)
{
Buffer.BlockCopy(items, 0, array, index, items.Length);
return array;
}
}
}