Innovenergy_trunk/csharp/Lib/Protocols/Modbus/Reflection/Attributes/ModbusAttribute.cs

49 lines
1.4 KiB
C#
Raw Normal View History

2023-06-13 11:03:36 +00:00
using InnovEnergy.Lib.Protocols.Modbus.Protocol;
2023-05-04 07:32:35 +00:00
using static System.AttributeTargets;
namespace InnovEnergy.Lib.Protocols.Modbus.Reflection.Attributes;
2023-05-04 07:32:35 +00:00
[AttributeUsage(Field | Property)]
2023-06-13 11:03:36 +00:00
public abstract class ModbusAttribute : Attribute
{
2023-06-13 11:03:36 +00:00
public UInt16 Address { get; }
public UInt16 Size { get; }
public Type ModbusType { get; }
public ModbusKind Kind { get; }
2023-05-04 07:32:35 +00:00
2023-06-13 11:03:36 +00:00
protected ModbusAttribute(UInt16 address, UInt16 size, Type modbusType, ModbusKind kind)
2023-05-04 07:32:35 +00:00
{
Address = address;
2023-06-13 11:03:36 +00:00
Size = size;
2023-05-04 07:32:35 +00:00
ModbusType = modbusType;
2023-06-13 11:03:36 +00:00
Kind = kind;
}
2023-05-04 07:32:35 +00:00
2023-06-13 11:03:36 +00:00
protected ModbusAttribute(UInt16 address, Type modbusType, ModbusKind kind) : this(address, GetSize(modbusType), modbusType, kind)
{
}
private static UInt16 GetSize(Type modbusType)
{
if (!TypeToSize.TryGetValue(modbusType, out var size))
throw new ArgumentException("cannot infer size of" + nameof(modbusType), nameof(modbusType));
2023-05-04 07:32:35 +00:00
2023-06-13 11:03:36 +00:00
return size;
2023-05-04 07:32:35 +00:00
}
2023-06-13 11:03:36 +00:00
private static readonly Dictionary<Type, UInt16> TypeToSize = new()
{
[typeof(Boolean)] = 1,
[typeof(Int16)] = 1,
[typeof(UInt16)] = 1,
[typeof(Int32)] = 2,
[typeof(UInt32)] = 2,
[typeof(Single)] = 2,
[typeof(Int64)] = 4,
[typeof(UInt64)] = 4,
[typeof(Double)] = 4,
};
}