Alter ValueHelper

This commit is contained in:
luosheng
2023-06-27 17:38:47 +08:00
parent d9678ee31c
commit 34a49e22da
16 changed files with 466 additions and 150 deletions

View File

@@ -67,9 +67,9 @@ namespace Modbus.Net.Modbus
var transaction = (ushort)(_sendCount % 65536 + 1); var transaction = (ushort)(_sendCount % 65536 + 1);
var tag = (ushort)0; var tag = (ushort)0;
var leng = (ushort)content.Length; var leng = (ushort)content.Length;
Array.Copy(BigEndianValueHelper.Instance.GetBytes(transaction), 0, newFormat, 0, 2); Array.Copy(BigEndianLsbValueHelper.Instance.GetBytes(transaction), 0, newFormat, 0, 2);
Array.Copy(BigEndianValueHelper.Instance.GetBytes(tag), 0, newFormat, 2, 2); Array.Copy(BigEndianLsbValueHelper.Instance.GetBytes(tag), 0, newFormat, 2, 2);
Array.Copy(BigEndianValueHelper.Instance.GetBytes(leng), 0, newFormat, 4, 2); Array.Copy(BigEndianLsbValueHelper.Instance.GetBytes(leng), 0, newFormat, 4, 2);
Array.Copy(content, 0, newFormat, 6, content.Length); Array.Copy(content, 0, newFormat, 6, content.Length);
_sendCount++; _sendCount++;
} }

View File

@@ -96,11 +96,24 @@ namespace Modbus.Net.Opc
if (tag != null) if (tag != null)
{ {
var result = await Client.ReadAsync<object>(tag); var result = await Client.ReadAsync<object>(tag);
logger.LogInformation($"Opc Machine {ConnectionToken} Read Opc tag {tag} for value {result.Value}"); object resultTrans;
if (result.Value.ToString() == "False")
{
resultTrans = (byte)0;
}
else if (result.Value.ToString() == "True")
{
resultTrans = (byte)1;
}
else
{
resultTrans = result.Value;
}
logger.LogInformation($"Opc Machine {ConnectionToken} Read Opc tag {tag} for value {result.Value} {result.Value.GetType().FullName}");
return new OpcParamOut return new OpcParamOut
{ {
Success = true, Success = true,
Value = BigEndianValueHelper.Instance.GetBytes(result.Value, result.Value.GetType()) Value = BigEndianLsbValueHelper.Instance.GetBytes(resultTrans, resultTrans.GetType())
}; };
} }
return new OpcParamOut return new OpcParamOut

View File

@@ -171,7 +171,7 @@
/// <returns>结构化的输出数据</returns> /// <returns>结构化的输出数据</returns>
public override IOutputStruct Unformat(OpcParamOut messageBytes, ref int pos) public override IOutputStruct Unformat(OpcParamOut messageBytes, ref int pos)
{ {
var ansByte = BigEndianValueHelper.Instance.GetByte(messageBytes.Value, ref pos); var ansByte = BigEndianLsbValueHelper.Instance.GetByte(messageBytes.Value, ref pos);
var ans = ansByte != 0; var ans = ansByte != 0;
return new WriteRequestOpcOutputStruct(ans); return new WriteRequestOpcOutputStruct(ans);
} }

View File

@@ -162,9 +162,9 @@ namespace Modbus.Net.Siemens
public override IOutputStruct Unformat(byte[] messageBytes, ref int pos) public override IOutputStruct Unformat(byte[] messageBytes, ref int pos)
{ {
pos = 1; pos = 1;
var masterAddress = BigEndianValueHelper.Instance.GetByte(messageBytes, ref pos); var masterAddress = BigEndianLsbValueHelper.Instance.GetByte(messageBytes, ref pos);
var slaveAddress = BigEndianValueHelper.Instance.GetByte(messageBytes, ref pos); var slaveAddress = BigEndianLsbValueHelper.Instance.GetByte(messageBytes, ref pos);
var confirmMessage = BigEndianValueHelper.Instance.GetByte(messageBytes, ref pos); var confirmMessage = BigEndianLsbValueHelper.Instance.GetByte(messageBytes, ref pos);
return new ComCreateReferenceSiemensOutputStruct(slaveAddress, masterAddress, confirmMessage); return new ComCreateReferenceSiemensOutputStruct(slaveAddress, masterAddress, confirmMessage);
} }
} }
@@ -236,19 +236,19 @@ namespace Modbus.Net.Siemens
case 0xc0: case 0xc0:
{ {
pos += 2; pos += 2;
tdpuSize = BigEndianValueHelper.Instance.GetByte(messageBytes, ref pos); tdpuSize = BigEndianLsbValueHelper.Instance.GetByte(messageBytes, ref pos);
break; break;
} }
case 0xc1: case 0xc1:
{ {
pos += 2; pos += 2;
srcTsap = BigEndianValueHelper.Instance.GetUShort(messageBytes, ref pos); srcTsap = BigEndianLsbValueHelper.Instance.GetUShort(messageBytes, ref pos);
break; break;
} }
case 0xc2: case 0xc2:
{ {
pos += 2; pos += 2;
dstTsap = BigEndianValueHelper.Instance.GetUShort(messageBytes, ref pos); dstTsap = BigEndianLsbValueHelper.Instance.GetUShort(messageBytes, ref pos);
break; break;
} }
} }
@@ -334,7 +334,7 @@ namespace Modbus.Net.Siemens
/// <returns>输出数据</returns> /// <returns>输出数据</returns>
public override IOutputStruct Unformat(byte[] messageBytes, ref int pos) public override IOutputStruct Unformat(byte[] messageBytes, ref int pos)
{ {
var confirmByte = BigEndianValueHelper.Instance.GetByte(messageBytes, ref pos); var confirmByte = BigEndianLsbValueHelper.Instance.GetByte(messageBytes, ref pos);
return new ComConfirmMessageSiemensOutputStruct(confirmByte); return new ComConfirmMessageSiemensOutputStruct(confirmByte);
} }
} }
@@ -399,11 +399,11 @@ namespace Modbus.Net.Siemens
public override IOutputStruct Unformat(byte[] messageBytes, ref int pos) public override IOutputStruct Unformat(byte[] messageBytes, ref int pos)
{ {
pos = 4; pos = 4;
var pduRef = BigEndianValueHelper.Instance.GetUShort(messageBytes, ref pos); var pduRef = BigEndianLsbValueHelper.Instance.GetUShort(messageBytes, ref pos);
pos = 14; pos = 14;
var maxCalling = BigEndianValueHelper.Instance.GetUShort(messageBytes, ref pos); var maxCalling = BigEndianLsbValueHelper.Instance.GetUShort(messageBytes, ref pos);
var maxCalled = BigEndianValueHelper.Instance.GetUShort(messageBytes, ref pos); var maxCalled = BigEndianLsbValueHelper.Instance.GetUShort(messageBytes, ref pos);
var maxPdu = BigEndianValueHelper.Instance.GetUShort(messageBytes, ref pos); var maxPdu = BigEndianLsbValueHelper.Instance.GetUShort(messageBytes, ref pos);
return new EstablishAssociationSiemensOutputStruct(pduRef, maxCalling, maxCalled, maxPdu); return new EstablishAssociationSiemensOutputStruct(pduRef, maxCalling, maxCalled, maxPdu);
} }
} }
@@ -563,7 +563,7 @@ namespace Modbus.Net.Siemens
var dbBlock = r_message.DbBlock; var dbBlock = r_message.DbBlock;
var area = r_message.Area; var area = r_message.Area;
var offsetBit = r_message.Offset * 8; var offsetBit = r_message.Offset * 8;
var offsetBitBytes = BigEndianValueHelper.Instance.GetBytes(offsetBit); var offsetBitBytes = BigEndianLsbValueHelper.Instance.GetBytes(offsetBit);
return Format(new byte[4], slaveAddress, masterAddress, (byte)0x6c, protoId, rosctr, redId, pduRef, parLg, return Format(new byte[4], slaveAddress, masterAddress, (byte)0x6c, protoId, rosctr, redId, pduRef, parLg,
datLg, serviceId, numberOfVariables datLg, serviceId, numberOfVariables
, variableSpec, vAddrLg, syntaxId, type, numberOfElements, dbBlock, area, , variableSpec, vAddrLg, syntaxId, type, numberOfElements, dbBlock, area,
@@ -579,11 +579,11 @@ namespace Modbus.Net.Siemens
public override IOutputStruct Unformat(byte[] messageBytes, ref int pos) public override IOutputStruct Unformat(byte[] messageBytes, ref int pos)
{ {
pos = 4; pos = 4;
var pduRef = BigEndianValueHelper.Instance.GetUShort(messageBytes, ref pos); var pduRef = BigEndianLsbValueHelper.Instance.GetUShort(messageBytes, ref pos);
pos = 14; pos = 14;
var accessResult = BigEndianValueHelper.Instance.GetByte(messageBytes, ref pos); var accessResult = BigEndianLsbValueHelper.Instance.GetByte(messageBytes, ref pos);
var dataType = BigEndianValueHelper.Instance.GetByte(messageBytes, ref pos); var dataType = BigEndianLsbValueHelper.Instance.GetByte(messageBytes, ref pos);
var length = BigEndianValueHelper.Instance.GetUShort(messageBytes, ref pos); var length = BigEndianLsbValueHelper.Instance.GetUShort(messageBytes, ref pos);
var byteLength = length / 8; var byteLength = length / 8;
var values = new byte[byteLength]; var values = new byte[byteLength];
Array.Copy(messageBytes, pos, values, 0, byteLength); Array.Copy(messageBytes, pos, values, 0, byteLength);
@@ -700,7 +700,7 @@ namespace Modbus.Net.Siemens
public override byte[] Format(IInputStruct message) public override byte[] Format(IInputStruct message)
{ {
var r_message = (WriteRequestSiemensInputStruct)message; var r_message = (WriteRequestSiemensInputStruct)message;
var valueBytes = BigEndianValueHelper.Instance.ObjectArrayToByteArray(r_message.WriteValue); var valueBytes = BigEndianLsbValueHelper.Instance.ObjectArrayToByteArray(r_message.WriteValue);
var slaveAddress = r_message.SlaveAddress; var slaveAddress = r_message.SlaveAddress;
var masterAddress = r_message.MasterAddress; var masterAddress = r_message.MasterAddress;
const byte protoId = 0x32; const byte protoId = 0x32;
@@ -719,7 +719,7 @@ namespace Modbus.Net.Siemens
var dbBlock = r_message.DbBlock; var dbBlock = r_message.DbBlock;
var area = r_message.Area; var area = r_message.Area;
var offsetBit = r_message.Offset * 8; var offsetBit = r_message.Offset * 8;
var offsetBitBytes = BigEndianValueHelper.Instance.GetBytes(offsetBit); var offsetBitBytes = BigEndianLsbValueHelper.Instance.GetBytes(offsetBit);
const byte reserved = 0x00; const byte reserved = 0x00;
const byte type = (byte)SiemensDataType.OtherAccess; const byte type = (byte)SiemensDataType.OtherAccess;
var numberOfWriteBits = (ushort)(valueBytes.Length * 8); var numberOfWriteBits = (ushort)(valueBytes.Length * 8);
@@ -739,16 +739,16 @@ namespace Modbus.Net.Siemens
{ {
if (messageBytes.Length == 1) if (messageBytes.Length == 1)
{ {
var accessResult = BigEndianValueHelper.Instance.GetByte(messageBytes, ref pos); var accessResult = BigEndianLsbValueHelper.Instance.GetByte(messageBytes, ref pos);
return new WriteRequestSiemensOutputStruct(0, return new WriteRequestSiemensOutputStruct(0,
accessResult == 0xe5 ? SiemensAccessResult.NoError : SiemensAccessResult.InvalidAddress); accessResult == 0xe5 ? SiemensAccessResult.NoError : SiemensAccessResult.InvalidAddress);
} }
else else
{ {
pos = 4; pos = 4;
var pduRef = BigEndianValueHelper.Instance.GetUShort(messageBytes, ref pos); var pduRef = BigEndianLsbValueHelper.Instance.GetUShort(messageBytes, ref pos);
pos = 14; pos = 14;
var accessResult = BigEndianValueHelper.Instance.GetByte(messageBytes, ref pos); var accessResult = BigEndianLsbValueHelper.Instance.GetByte(messageBytes, ref pos);
return new WriteRequestSiemensOutputStruct(pduRef, (SiemensAccessResult)accessResult); return new WriteRequestSiemensOutputStruct(pduRef, (SiemensAccessResult)accessResult);
} }
} }

View File

@@ -15,7 +15,7 @@ namespace Modbus.Net.Siemens
public byte[] BytesExtend(byte[] content) public byte[] BytesExtend(byte[] content)
{ {
Array.Copy(new byte[] { 0x03, 0x00, 0x00, 0x00, 0x02, 0xf0, 0x80 }, 0, content, 0, 7); Array.Copy(new byte[] { 0x03, 0x00, 0x00, 0x00, 0x02, 0xf0, 0x80 }, 0, content, 0, 7);
Array.Copy(BigEndianValueHelper.Instance.GetBytes((ushort)content.Length), 0, content, 2, 2); Array.Copy(BigEndianLsbValueHelper.Instance.GetBytes((ushort)content.Length), 0, content, 2, 2);
return content; return content;
} }

View File

@@ -7,9 +7,9 @@
get get
{ {
var pos = 15; var pos = 15;
return BigEndianValueHelper.Instance.GetBit(BigEndianValueHelper.Instance.GetBytes(TodValue), ref pos); return BigEndianLsbValueHelper.Instance.GetBit(BigEndianLsbValueHelper.Instance.GetBytes(TodValue), ref pos);
} }
set { TodValue = BigEndianValueHelper.Instance.SetBit(BigEndianValueHelper.Instance.GetBytes(TodValue), 15, value); } set { TodValue = BigEndianLsbValueHelper.Instance.SetBit(BigEndianLsbValueHelper.Instance.GetBytes(TodValue), 15, value); }
} }
public byte K0_4 public byte K0_4
@@ -17,13 +17,13 @@
get get
{ {
var pos = 0; var pos = 0;
var byteValue = BigEndianValueHelper.Instance.GetByte(BigEndianValueHelper.Instance.GetBytes(TodValue), ref pos); var byteValue = BigEndianLsbValueHelper.Instance.GetByte(BigEndianLsbValueHelper.Instance.GetBytes(TodValue), ref pos);
return (byte)(byteValue%64/4); return (byte)(byteValue%64/4);
} }
set set
{ {
var pos = 0; var pos = 0;
var byteValue = BigEndianValueHelper.Instance.GetByte(BigEndianValueHelper.Instance.GetBytes(TodValue), ref pos); var byteValue = BigEndianLsbValueHelper.Instance.GetByte(BigEndianLsbValueHelper.Instance.GetBytes(TodValue), ref pos);
byteValue = (byte)(byteValue - (byteValue%128/4) + value); byteValue = (byte)(byteValue - (byteValue%128/4) + value);
TodValue = (ushort)(TodValue%128 + byteValue*128); TodValue = (ushort)(TodValue%128 + byteValue*128);
} }
@@ -34,9 +34,9 @@
get get
{ {
var pos = 5; var pos = 5;
return BigEndianValueHelper.Instance.GetBit(BigEndianValueHelper.Instance.GetBytes(TodValue), ref pos); return BigEndianLsbValueHelper.Instance.GetBit(BigEndianLsbValueHelper.Instance.GetBytes(TodValue), ref pos);
} }
set { TodValue = BigEndianValueHelper.Instance.SetBit(BigEndianValueHelper.Instance.GetBytes(TodValue), 5, value); } set { TodValue = BigEndianLsbValueHelper.Instance.SetBit(BigEndianLsbValueHelper.Instance.GetBytes(TodValue), 5, value); }
} }
public byte UA public byte UA
@@ -44,15 +44,15 @@
get get
{ {
var pos = 3; var pos = 3;
var low = BigEndianValueHelper.Instance.GetBit(BigEndianValueHelper.Instance.GetBytes(TodValue), ref pos) ? 1 : 0; var low = BigEndianLsbValueHelper.Instance.GetBit(BigEndianLsbValueHelper.Instance.GetBytes(TodValue), ref pos) ? 1 : 0;
var high = BigEndianValueHelper.Instance.GetBit(BigEndianValueHelper.Instance.GetBytes(TodValue), ref pos) ? 1 : 0; var high = BigEndianLsbValueHelper.Instance.GetBit(BigEndianLsbValueHelper.Instance.GetBytes(TodValue), ref pos) ? 1 : 0;
high *= 2; high *= 2;
return (byte) (high + low); return (byte) (high + low);
} }
set set
{ {
TodValue = BigEndianValueHelper.Instance.SetBit(BigEndianValueHelper.Instance.GetBytes(TodValue), 3, value % 2 >= 1); TodValue = BigEndianLsbValueHelper.Instance.SetBit(BigEndianLsbValueHelper.Instance.GetBytes(TodValue), 3, value % 2 >= 1);
TodValue = BigEndianValueHelper.Instance.SetBit(BigEndianValueHelper.Instance.GetBytes(TodValue), 4, value / 2 >= 1); TodValue = BigEndianLsbValueHelper.Instance.SetBit(BigEndianLsbValueHelper.Instance.GetBytes(TodValue), 4, value / 2 >= 1);
} }
} }
public bool UZS public bool UZS
@@ -60,9 +60,9 @@
get get
{ {
var pos = 2; var pos = 2;
return BigEndianValueHelper.Instance.GetBit(BigEndianValueHelper.Instance.GetBytes(TodValue), ref pos); return BigEndianLsbValueHelper.Instance.GetBit(BigEndianLsbValueHelper.Instance.GetBytes(TodValue), ref pos);
} }
set { TodValue = BigEndianValueHelper.Instance.SetBit(BigEndianValueHelper.Instance.GetBytes(TodValue), 2, value); } set { TodValue = BigEndianLsbValueHelper.Instance.SetBit(BigEndianLsbValueHelper.Instance.GetBytes(TodValue), 2, value); }
} }
public bool ESY public bool ESY
@@ -70,9 +70,9 @@
get get
{ {
var pos = 1; var pos = 1;
return BigEndianValueHelper.Instance.GetBit(BigEndianValueHelper.Instance.GetBytes(TodValue), ref pos); return BigEndianLsbValueHelper.Instance.GetBit(BigEndianLsbValueHelper.Instance.GetBytes(TodValue), ref pos);
} }
set { TodValue = BigEndianValueHelper.Instance.SetBit(BigEndianValueHelper.Instance.GetBytes(TodValue), 1, value); } set { TodValue = BigEndianLsbValueHelper.Instance.SetBit(BigEndianLsbValueHelper.Instance.GetBytes(TodValue), 1, value); }
} }
public bool SYA public bool SYA
@@ -80,9 +80,9 @@
get get
{ {
var pos = 0; var pos = 0;
return BigEndianValueHelper.Instance.GetBit(BigEndianValueHelper.Instance.GetBytes(TodValue), ref pos); return BigEndianLsbValueHelper.Instance.GetBit(BigEndianLsbValueHelper.Instance.GetBytes(TodValue), ref pos);
} }
set { TodValue = BigEndianValueHelper.Instance.SetBit(BigEndianValueHelper.Instance.GetBytes(TodValue), 0, value); } set { TodValue = BigEndianLsbValueHelper.Instance.SetBit(BigEndianLsbValueHelper.Instance.GetBytes(TodValue), 0, value); }
} }
public ushort TodValue { get; set; } public ushort TodValue { get; set; }

View File

@@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Modbus.Net
{
/// <summary>
/// 程序集辅助类
/// </summary>
public static class AssemblyHelper
{
/// <summary>
/// 获取与Modbus.Net相关的所有程序集
/// </summary>
/// <returns></returns>
public static List<Assembly> GetAllLibraryAssemblies()
{
List<Assembly> allAssemblies = new List<Assembly>();
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
allAssemblies.Add(Assembly.Load("Modbus.Net"));
foreach (string dll in Directory.GetFiles(path, "Modbus.Net.*.dll"))
allAssemblies.Add(Assembly.LoadFile(dll));
return allAssemblies;
}
}
}

View File

@@ -8,16 +8,17 @@ using System.Text;
namespace Modbus.Net namespace Modbus.Net
{ {
/// <summary> /// <summary>
/// 值与字节数组之间转换的辅助类小端格式这是一个Singleton类 /// 值与字节数组之间转换的辅助类
/// </summary> /// </summary>
public class ValueHelper public abstract class ValueHelper
{ {
private static readonly ILogger<ValueHelper> logger = LogProvider.CreateLogger<ValueHelper>();
/// <summary> /// <summary>
/// 兼容数据类型对应的字节长度 /// 兼容数据类型对应的字节长度
/// </summary> /// </summary>
public Dictionary<string, double> ByteLength = new Dictionary<string, double> /// <summary>
/// 兼容数据类型对应的字节长度
/// </summary>
public static Dictionary<string, double> ByteLength => new Dictionary<string, double>
{ {
{"System.Boolean", 0.125}, {"System.Boolean", 0.125},
{"System.Byte", 1}, {"System.Byte", 1},
@@ -31,10 +32,301 @@ namespace Modbus.Net
{"System.Double", 8} {"System.Double", 8}
}; };
/// <summary>
/// 将一个byte数字转换为一个byte元素的数组。
/// </summary>
/// <param name="value">byte数字</param>
/// <returns>byte数组</returns>
public abstract byte[] GetBytes(byte value);
/// <summary>
/// 将short数字转换为byte数组
/// </summary>
/// <param name="value">待转换的值</param>
/// <returns>转换后的byte数组</returns>
public abstract byte[] GetBytes(short value);
/// <summary>
/// 将int数字转换为byte数组
/// </summary>
/// <param name="value">待转换的值</param>
/// <returns>转换后的byte数组</returns>
public abstract byte[] GetBytes(int value);
/// <summary>
/// 将long数字转换为byte数组
/// </summary>
/// <param name="value">待转换的值</param>
/// <returns>转换后的byte数组</returns>
public abstract byte[] GetBytes(long value);
/// <summary>
/// 将ushort数字转换为byte数组
/// </summary>
/// <param name="value">待转换的值</param>
/// <returns>转换后的byte数组</returns>
public abstract byte[] GetBytes(ushort value);
/// <summary>
/// 将uint数字转换为byte数组
/// </summary>
/// <param name="value">待转换的值</param>
/// <returns>转换后的byte数组</returns>
public abstract byte[] GetBytes(uint value);
/// <summary>
/// 将ulong数字转换为byte数组
/// </summary>
/// <param name="value">待转换的值</param>
/// <returns>转换后的byte数组</returns>
public abstract byte[] GetBytes(ulong value);
/// <summary>
/// 将float数字转换为byte数组
/// </summary>
/// <param name="value">待转换的值</param>
/// <returns>转换后的byte数组</returns>
public abstract byte[] GetBytes(float value);
/// <summary>
/// 将double数字转换为byte数组
/// </summary>
/// <param name="value">待转换的值</param>
/// <returns>转换后的byte数组</returns>
public abstract byte[] GetBytes(double value);
/// <summary>
/// 将object数字转换为byte数组
/// </summary>
/// <param name="value">待转换的值</param>
/// <param name="type">待转换的值的类型</param>
/// <returns>转换后的byte数组</returns>
public abstract byte[] GetBytes(object value, Type type);
/// <summary>
/// 将byte数组中相应的位置转换为对应类型的数字
/// </summary>
/// <param name="data">待转换的字节数组</param>
/// <param name="pos">转换数字的位置</param>
/// <param name="subPos">转换数字的比特位置仅Type为bool的时候有效</param>
/// <param name="t">转换的类型</param>
/// <returns>转换出的数字</returns>
public abstract object GetValue(byte[] data, ref int pos, ref int subPos, Type t);
/// <summary>
/// 将byte数组中相应的位置转换为byte数字
/// </summary>
/// <param name="data">待转换的数组</param>
/// <param name="pos">转换数字的位置</param>
/// <returns>转换出的数字</returns>
public abstract byte GetByte(byte[] data, ref int pos);
/// <summary>
/// 将byte数组中相应的位置转换为short数字
/// </summary>
/// <param name="data">待转换的数组</param>
/// <param name="pos">转换数字的位置</param>
/// <returns>转换出的数字</returns>
public abstract short GetShort(byte[] data, ref int pos);
/// <summary>
/// 将byte数组中相应的位置转换为int数字
/// </summary>
/// <param name="data">待转换的数组</param>
/// <param name="pos">转换数字的位置</param>
/// <returns>转换出的数字</returns>
public abstract int GetInt(byte[] data, ref int pos);
/// <summary>
/// 将byte数组中相应的位置转换为long数字
/// </summary>
/// <param name="data">待转换的数组</param>
/// <param name="pos">转换数字的位置</param>
/// <returns>转换出的数字</returns>
public abstract long GetLong(byte[] data, ref int pos);
/// <summary>
/// 将byte数组中相应的位置转换为ushort数字
/// </summary>
/// <param name="data">待转换的数组</param>
/// <param name="pos">转换数字的位置</param>
/// <returns>转换出的数字</returns>
public abstract ushort GetUShort(byte[] data, ref int pos);
/// <summary>
/// 将byte数组中相应的位置转换为uint数字
/// </summary>
/// <param name="data">待转换的数组</param>
/// <param name="pos">转换数字的位置</param>
/// <returns>转换出的数字</returns>
public abstract uint GetUInt(byte[] data, ref int pos);
/// <summary>
/// 将byte数组中相应的位置转换为ulong数字
/// </summary>
/// <param name="data">待转换的数组</param>
/// <param name="pos">转换数字的位置</param>
/// <returns>转换出的数字</returns>
public abstract ulong GetULong(byte[] data, ref int pos);
/// <summary>
/// 将byte数组中相应的位置转换为float数字
/// </summary>
/// <param name="data">待转换的数组</param>
/// <param name="pos">转换数字的位置</param>
/// <returns>转换出的数字</returns>
public abstract float GetFloat(byte[] data, ref int pos);
/// <summary>
/// 将byte数组中相应的位置转换为double数字
/// </summary>
/// <param name="data">待转换的数组</param>
/// <param name="pos">转换数字的位置</param>
/// <returns>转换出的数字</returns>
public abstract double GetDouble(byte[] data, ref int pos);
/// <summary>
/// 将byte数组中相应的位置转换为字符串
/// </summary>
/// <param name="data">待转换的数组</param>
/// <param name="count">转换的个数</param>
/// <param name="pos">转换数字的位置</param>
/// <param name="encoding">编码方法</param>
/// <returns>转换出的字符串</returns>
public abstract string GetString(byte[] data, int count, ref int pos, Encoding encoding);
/// <summary>
/// 将byte数组中相应的位置转换为8个bit数字
/// </summary>
/// <param name="data">待转换的数组</param>
/// <param name="pos">转换数字的位置</param>
/// <returns>转换出的位数组</returns>
public abstract bool[] GetBits(byte[] data, ref int pos);
/// <summary>
/// 获取一个byte中相对应的bit数组展开中第n个位置中的bit元素。
/// </summary>
/// <param name="number">byte数字</param>
/// <param name="pos">bit数组中的对应位置</param>
/// <param name="subPos">小数位</param>
/// <returns>对应位置的bit元素</returns>
public abstract bool GetBit(byte number, ref int pos, ref int subPos);
/// <summary>
/// 获取一个字节数组中某个Bit位的数据
/// </summary>
/// <param name="number">byte数字</param>
/// <param name="pos">bit数组中的对应位置</param>
/// <param name="subPos">小数位</param>
/// <returns>对应位置的bit元素</returns>
public abstract bool GetBit(byte[] number, ref int pos, ref int subPos);
/// <summary>
/// 反转一个字节的8个Bit位
/// </summary>
/// <param name="originalByte">原始bit数组</param>
/// <returns>反转的bit数组</returns>
public abstract byte ReverseByte(byte originalByte);
/// <summary>
/// 将待转换的对象数组转换为需要发送的byte数组
/// </summary>
/// <param name="contents">object数组</param>
/// <returns>byte数组</returns>
public abstract byte[] ObjectArrayToByteArray(object[] contents);
/// <summary>
/// 将byte数组转换为用户指定类型的数组通过object数组的方式返回用户需要再把object转换为自己需要的类型或调用ObjectArrayToDestinationArray返回单一类型的目标数组。
/// </summary>
/// <param name="contents">byte数组</param>
/// <param name="translateTypeAndCount">单一的类型和需要转换的个数的键值对</param>
/// <returns>object数组</returns>
public abstract object[] ByteArrayToObjectArray(byte[] contents, KeyValuePair<Type, int> translateTypeAndCount);
/// <summary>
/// 将一个byte数组转换成用户指定类型的数组使用模板参数确定需要转换的类型
/// </summary>
/// <typeparam name="T">目标数组类型</typeparam>
/// <param name="contents">待转换的数组</param>
/// <param name="getCount">转换的个数</param>
/// <returns>以T为类型的数组</returns>
public abstract T[] ByteArrayToDestinationArray<T>(byte[] contents, int getCount);
/// <summary>
/// 将byte数组转换为用户指定类型的数组通过object数组的方式返回用户需要再把object转换为自己需要的类型或调用ObjectArrayToDestinationArray返回单一类型的目标数组。
/// </summary>
/// <param name="contents">byte数组</param>
/// <param name="translateTypeAndCount">
/// 一连串类型和需要转换的个数的键值对该方法会依次转换每一个需要转的目标数据类型。比如typeof(int),5; typeof(short),3
/// 会转换出8个元素当然前提是byte数组足够长的时候5个int和3个short然后全部变为object类型返回。
/// </param>
/// <returns>object数组</returns>
public abstract object[] ByteArrayToObjectArray(byte[] contents, IEnumerable<KeyValuePair<Type, int>> translateTypeAndCount);
/// <summary>
/// 将object数组转换为目标类型的单一数组
/// </summary>
/// <typeparam name="T">需要转换的目标类型</typeparam>
/// <param name="contents">object数组</param>
/// <returns>目标数组</returns>
public abstract T[] ObjectArrayToDestinationArray<T>(object[] contents);
/// <summary>
/// 在一个数组中写一个值
/// </summary>
/// <param name="contents">待写入的字节数组</param>
/// <param name="setPos">设置的位置</param>
/// <param name="subPos">设置的比特位位置仅setValue为bit的时候有效</param>
/// <param name="setValue">写入的值</param>
/// <returns>写入是否成功</returns>
public abstract bool SetValue(byte[] contents, int setPos, int subPos, object setValue);
/// <summary>
/// 将short值设置到byte数组中
/// </summary>
/// <param name="contents">待设置的byte数组</param>
/// <param name="pos">设置的位置</param>
/// <param name="setValue">要设置的值</param>
/// <returns>设置是否成功</returns>
public abstract bool SetValue(byte[] contents, int pos, object setValue);
/// <summary>
/// 设置一组数据中的一个bit
/// </summary>
/// <param name="contents">待设置的字节数组</param>
/// <param name="pos">位置</param>
/// <param name="subPos">bit位置</param>
/// <param name="setValue">bit数</param>
/// <returns>设置是否成功</returns>
public abstract bool SetBit(byte[] contents, int pos, int subPos, bool setValue);
/// <summary>
/// 根据端格式获取ValueHelper实例
/// </summary>
/// <param name="endian">端格式</param>
/// <returns>对应的ValueHelper实例</returns>
public static ValueHelper GetInstance(Endian endian)
{
foreach (var assembly in AssemblyHelper.GetAllLibraryAssemblies())
{
var valueHelper = assembly.GetType("Modbus.Net."+endian.ToString() + "ValueHelper")?.GetProperty("Instance")?.GetValue(null, null) as ValueHelper;
if (valueHelper != null) return valueHelper;
}
return null;
}
}
/// <summary>
/// 值与字节数组之间转换的辅助类小端格式这是一个Singleton类
/// </summary>
public class LittleEndianLsbValueHelper : ValueHelper
{
private static readonly ILogger<LittleEndianLsbValueHelper> logger = LogProvider.CreateLogger<LittleEndianLsbValueHelper>();
/// <summary> /// <summary>
/// 构造器 /// 构造器
/// </summary> /// </summary>
protected ValueHelper() protected LittleEndianLsbValueHelper()
{ {
} }
@@ -53,7 +345,7 @@ namespace Modbus.Net
/// </summary> /// </summary>
/// <param name="value">byte数字</param> /// <param name="value">byte数字</param>
/// <returns>byte数组</returns> /// <returns>byte数组</returns>
public byte[] GetBytes(byte value) public override byte[] GetBytes(byte value)
{ {
return new[] { value }; return new[] { value };
} }
@@ -63,7 +355,7 @@ namespace Modbus.Net
/// </summary> /// </summary>
/// <param name="value">待转换的值</param> /// <param name="value">待转换的值</param>
/// <returns>转换后的byte数组</returns> /// <returns>转换后的byte数组</returns>
public virtual byte[] GetBytes(short value) public override byte[] GetBytes(short value)
{ {
return BitConverter.GetBytes(value); return BitConverter.GetBytes(value);
} }
@@ -73,7 +365,7 @@ namespace Modbus.Net
/// </summary> /// </summary>
/// <param name="value">待转换的值</param> /// <param name="value">待转换的值</param>
/// <returns>转换后的byte数组</returns> /// <returns>转换后的byte数组</returns>
public virtual byte[] GetBytes(int value) public override byte[] GetBytes(int value)
{ {
return BitConverter.GetBytes(value); return BitConverter.GetBytes(value);
} }
@@ -83,7 +375,7 @@ namespace Modbus.Net
/// </summary> /// </summary>
/// <param name="value">待转换的值</param> /// <param name="value">待转换的值</param>
/// <returns>转换后的byte数组</returns> /// <returns>转换后的byte数组</returns>
public virtual byte[] GetBytes(long value) public override byte[] GetBytes(long value)
{ {
return BitConverter.GetBytes(value); return BitConverter.GetBytes(value);
} }
@@ -93,7 +385,7 @@ namespace Modbus.Net
/// </summary> /// </summary>
/// <param name="value">待转换的值</param> /// <param name="value">待转换的值</param>
/// <returns>转换后的byte数组</returns> /// <returns>转换后的byte数组</returns>
public virtual byte[] GetBytes(ushort value) public override byte[] GetBytes(ushort value)
{ {
return BitConverter.GetBytes(value); return BitConverter.GetBytes(value);
} }
@@ -103,7 +395,7 @@ namespace Modbus.Net
/// </summary> /// </summary>
/// <param name="value">待转换的值</param> /// <param name="value">待转换的值</param>
/// <returns>转换后的byte数组</returns> /// <returns>转换后的byte数组</returns>
public virtual byte[] GetBytes(uint value) public override byte[] GetBytes(uint value)
{ {
return BitConverter.GetBytes(value); return BitConverter.GetBytes(value);
} }
@@ -113,7 +405,7 @@ namespace Modbus.Net
/// </summary> /// </summary>
/// <param name="value">待转换的值</param> /// <param name="value">待转换的值</param>
/// <returns>转换后的byte数组</returns> /// <returns>转换后的byte数组</returns>
public virtual byte[] GetBytes(ulong value) public override byte[] GetBytes(ulong value)
{ {
return BitConverter.GetBytes(value); return BitConverter.GetBytes(value);
} }
@@ -123,7 +415,7 @@ namespace Modbus.Net
/// </summary> /// </summary>
/// <param name="value">待转换的值</param> /// <param name="value">待转换的值</param>
/// <returns>转换后的byte数组</returns> /// <returns>转换后的byte数组</returns>
public virtual byte[] GetBytes(float value) public override byte[] GetBytes(float value)
{ {
return BitConverter.GetBytes(value); return BitConverter.GetBytes(value);
} }
@@ -133,7 +425,7 @@ namespace Modbus.Net
/// </summary> /// </summary>
/// <param name="value">待转换的值</param> /// <param name="value">待转换的值</param>
/// <returns>转换后的byte数组</returns> /// <returns>转换后的byte数组</returns>
public virtual byte[] GetBytes(double value) public override byte[] GetBytes(double value)
{ {
return BitConverter.GetBytes(value); return BitConverter.GetBytes(value);
} }
@@ -144,7 +436,7 @@ namespace Modbus.Net
/// <param name="value">待转换的值</param> /// <param name="value">待转换的值</param>
/// <param name="type">待转换的值的类型</param> /// <param name="type">待转换的值的类型</param>
/// <returns>转换后的byte数组</returns> /// <returns>转换后的byte数组</returns>
public virtual byte[] GetBytes(object value, Type type) public override byte[] GetBytes(object value, Type type)
{ {
switch (type.FullName) switch (type.FullName)
{ {
@@ -193,6 +485,11 @@ namespace Modbus.Net
var bytes = _Instance.GetBytes((byte)value); var bytes = _Instance.GetBytes((byte)value);
return bytes; return bytes;
} }
case "System.Boolean":
{
var bytes = _Instance.GetBytes((bool)value ? (byte)1 : (byte)0);
return bytes;
}
default: default:
{ {
throw new NotImplementedException("没有实现除整数以外的其它转换方式"); throw new NotImplementedException("没有实现除整数以外的其它转换方式");
@@ -208,7 +505,7 @@ namespace Modbus.Net
/// <param name="subPos">转换数字的比特位置仅Type为bool的时候有效</param> /// <param name="subPos">转换数字的比特位置仅Type为bool的时候有效</param>
/// <param name="t">转换的类型</param> /// <param name="t">转换的类型</param>
/// <returns>转换出的数字</returns> /// <returns>转换出的数字</returns>
public virtual object GetValue(byte[] data, ref int pos, ref int subPos, Type t) public override object GetValue(byte[] data, ref int pos, ref int subPos, Type t)
{ {
switch (t.FullName) switch (t.FullName)
{ {
@@ -275,7 +572,7 @@ namespace Modbus.Net
/// <param name="data">待转换的数组</param> /// <param name="data">待转换的数组</param>
/// <param name="pos">转换数字的位置</param> /// <param name="pos">转换数字的位置</param>
/// <returns>转换出的数字</returns> /// <returns>转换出的数字</returns>
public virtual byte GetByte(byte[] data, ref int pos) public override byte GetByte(byte[] data, ref int pos)
{ {
var t = data[pos]; var t = data[pos];
pos += 1; pos += 1;
@@ -288,7 +585,7 @@ namespace Modbus.Net
/// <param name="data">待转换的数组</param> /// <param name="data">待转换的数组</param>
/// <param name="pos">转换数字的位置</param> /// <param name="pos">转换数字的位置</param>
/// <returns>转换出的数字</returns> /// <returns>转换出的数字</returns>
public virtual short GetShort(byte[] data, ref int pos) public override short GetShort(byte[] data, ref int pos)
{ {
var t = BitConverter.ToInt16(data, pos); var t = BitConverter.ToInt16(data, pos);
pos += 2; pos += 2;
@@ -301,7 +598,7 @@ namespace Modbus.Net
/// <param name="data">待转换的数组</param> /// <param name="data">待转换的数组</param>
/// <param name="pos">转换数字的位置</param> /// <param name="pos">转换数字的位置</param>
/// <returns>转换出的数字</returns> /// <returns>转换出的数字</returns>
public virtual int GetInt(byte[] data, ref int pos) public override int GetInt(byte[] data, ref int pos)
{ {
var t = BitConverter.ToInt32(data, pos); var t = BitConverter.ToInt32(data, pos);
pos += 4; pos += 4;
@@ -314,7 +611,7 @@ namespace Modbus.Net
/// <param name="data">待转换的数组</param> /// <param name="data">待转换的数组</param>
/// <param name="pos">转换数字的位置</param> /// <param name="pos">转换数字的位置</param>
/// <returns>转换出的数字</returns> /// <returns>转换出的数字</returns>
public virtual long GetLong(byte[] data, ref int pos) public override long GetLong(byte[] data, ref int pos)
{ {
var t = BitConverter.ToInt64(data, pos); var t = BitConverter.ToInt64(data, pos);
pos += 8; pos += 8;
@@ -327,7 +624,7 @@ namespace Modbus.Net
/// <param name="data">待转换的数组</param> /// <param name="data">待转换的数组</param>
/// <param name="pos">转换数字的位置</param> /// <param name="pos">转换数字的位置</param>
/// <returns>转换出的数字</returns> /// <returns>转换出的数字</returns>
public virtual ushort GetUShort(byte[] data, ref int pos) public override ushort GetUShort(byte[] data, ref int pos)
{ {
var t = BitConverter.ToUInt16(data, pos); var t = BitConverter.ToUInt16(data, pos);
pos += 2; pos += 2;
@@ -340,7 +637,7 @@ namespace Modbus.Net
/// <param name="data">待转换的数组</param> /// <param name="data">待转换的数组</param>
/// <param name="pos">转换数字的位置</param> /// <param name="pos">转换数字的位置</param>
/// <returns>转换出的数字</returns> /// <returns>转换出的数字</returns>
public virtual uint GetUInt(byte[] data, ref int pos) public override uint GetUInt(byte[] data, ref int pos)
{ {
var t = BitConverter.ToUInt32(data, pos); var t = BitConverter.ToUInt32(data, pos);
pos += 4; pos += 4;
@@ -353,7 +650,7 @@ namespace Modbus.Net
/// <param name="data">待转换的数组</param> /// <param name="data">待转换的数组</param>
/// <param name="pos">转换数字的位置</param> /// <param name="pos">转换数字的位置</param>
/// <returns>转换出的数字</returns> /// <returns>转换出的数字</returns>
public virtual ulong GetULong(byte[] data, ref int pos) public override ulong GetULong(byte[] data, ref int pos)
{ {
var t = BitConverter.ToUInt64(data, pos); var t = BitConverter.ToUInt64(data, pos);
pos += 8; pos += 8;
@@ -366,7 +663,7 @@ namespace Modbus.Net
/// <param name="data">待转换的数组</param> /// <param name="data">待转换的数组</param>
/// <param name="pos">转换数字的位置</param> /// <param name="pos">转换数字的位置</param>
/// <returns>转换出的数字</returns> /// <returns>转换出的数字</returns>
public virtual float GetFloat(byte[] data, ref int pos) public override float GetFloat(byte[] data, ref int pos)
{ {
var t = BitConverter.ToSingle(data, pos); var t = BitConverter.ToSingle(data, pos);
pos += 4; pos += 4;
@@ -379,7 +676,7 @@ namespace Modbus.Net
/// <param name="data">待转换的数组</param> /// <param name="data">待转换的数组</param>
/// <param name="pos">转换数字的位置</param> /// <param name="pos">转换数字的位置</param>
/// <returns>转换出的数字</returns> /// <returns>转换出的数字</returns>
public virtual double GetDouble(byte[] data, ref int pos) public override double GetDouble(byte[] data, ref int pos)
{ {
var t = BitConverter.ToDouble(data, pos); var t = BitConverter.ToDouble(data, pos);
pos += 8; pos += 8;
@@ -394,7 +691,7 @@ namespace Modbus.Net
/// <param name="pos">转换数字的位置</param> /// <param name="pos">转换数字的位置</param>
/// <param name="encoding">编码方法</param> /// <param name="encoding">编码方法</param>
/// <returns>转换出的字符串</returns> /// <returns>转换出的字符串</returns>
public virtual string GetString(byte[] data, int count, ref int pos, Encoding encoding) public override string GetString(byte[] data, int count, ref int pos, Encoding encoding)
{ {
var t = encoding.GetString(data, pos, count); var t = encoding.GetString(data, pos, count);
pos += count; pos += count;
@@ -407,7 +704,7 @@ namespace Modbus.Net
/// <param name="data">待转换的数组</param> /// <param name="data">待转换的数组</param>
/// <param name="pos">转换数字的位置</param> /// <param name="pos">转换数字的位置</param>
/// <returns>转换出的位数组</returns> /// <returns>转换出的位数组</returns>
public virtual bool[] GetBits(byte[] data, ref int pos) public override bool[] GetBits(byte[] data, ref int pos)
{ {
var t = new bool[8]; var t = new bool[8];
var temp = data[pos]; var temp = data[pos];
@@ -427,7 +724,7 @@ namespace Modbus.Net
/// <param name="pos">bit数组中的对应位置</param> /// <param name="pos">bit数组中的对应位置</param>
/// <param name="subPos">小数位</param> /// <param name="subPos">小数位</param>
/// <returns>对应位置的bit元素</returns> /// <returns>对应位置的bit元素</returns>
public bool GetBit(byte number, ref int pos, ref int subPos) public override bool GetBit(byte number, ref int pos, ref int subPos)
{ {
if (subPos < 0 && subPos >= 8) throw new IndexOutOfRangeException(); if (subPos < 0 && subPos >= 8) throw new IndexOutOfRangeException();
var ans = number % 2; var ans = number % 2;
@@ -454,7 +751,7 @@ namespace Modbus.Net
/// <param name="pos">bit数组中的对应位置</param> /// <param name="pos">bit数组中的对应位置</param>
/// <param name="subPos">小数位</param> /// <param name="subPos">小数位</param>
/// <returns>对应位置的bit元素</returns> /// <returns>对应位置的bit元素</returns>
public virtual bool GetBit(byte[] number, ref int pos, ref int subPos) public override bool GetBit(byte[] number, ref int pos, ref int subPos)
{ {
return GetBit(number[pos], ref pos, ref subPos); return GetBit(number[pos], ref pos, ref subPos);
} }
@@ -464,7 +761,7 @@ namespace Modbus.Net
/// </summary> /// </summary>
/// <param name="originalByte">原始bit数组</param> /// <param name="originalByte">原始bit数组</param>
/// <returns>反转的bit数组</returns> /// <returns>反转的bit数组</returns>
public virtual byte ReverseByte(byte originalByte) public override byte ReverseByte(byte originalByte)
{ {
byte result = 0; byte result = 0;
for (var i = 0; i < 8; i++) for (var i = 0; i < 8; i++)
@@ -481,7 +778,7 @@ namespace Modbus.Net
/// </summary> /// </summary>
/// <param name="contents">object数组</param> /// <param name="contents">object数组</param>
/// <returns>byte数组</returns> /// <returns>byte数组</returns>
public virtual byte[] ObjectArrayToByteArray(object[] contents) public override byte[] ObjectArrayToByteArray(object[] contents)
{ {
var b = false; var b = false;
//先查找传入的结构中有没有数组,有的话将其打开 //先查找传入的结构中有没有数组,有的话将其打开
@@ -604,7 +901,7 @@ namespace Modbus.Net
/// <param name="contents">byte数组</param> /// <param name="contents">byte数组</param>
/// <param name="translateTypeAndCount">单一的类型和需要转换的个数的键值对</param> /// <param name="translateTypeAndCount">单一的类型和需要转换的个数的键值对</param>
/// <returns>object数组</returns> /// <returns>object数组</returns>
public virtual object[] ByteArrayToObjectArray(byte[] contents, KeyValuePair<Type, int> translateTypeAndCount) public override object[] ByteArrayToObjectArray(byte[] contents, KeyValuePair<Type, int> translateTypeAndCount)
{ {
return ByteArrayToObjectArray(contents, new List<KeyValuePair<Type, int>> { translateTypeAndCount }); return ByteArrayToObjectArray(contents, new List<KeyValuePair<Type, int>> { translateTypeAndCount });
} }
@@ -616,7 +913,7 @@ namespace Modbus.Net
/// <param name="contents">待转换的数组</param> /// <param name="contents">待转换的数组</param>
/// <param name="getCount">转换的个数</param> /// <param name="getCount">转换的个数</param>
/// <returns>以T为类型的数组</returns> /// <returns>以T为类型的数组</returns>
public virtual T[] ByteArrayToDestinationArray<T>(byte[] contents, int getCount) public override T[] ByteArrayToDestinationArray<T>(byte[] contents, int getCount)
{ {
var objectArray = _Instance.ByteArrayToObjectArray(contents, var objectArray = _Instance.ByteArrayToObjectArray(contents,
new KeyValuePair<Type, int>(typeof(T), getCount)); new KeyValuePair<Type, int>(typeof(T), getCount));
@@ -632,7 +929,7 @@ namespace Modbus.Net
/// 会转换出8个元素当然前提是byte数组足够长的时候5个int和3个short然后全部变为object类型返回。 /// 会转换出8个元素当然前提是byte数组足够长的时候5个int和3个short然后全部变为object类型返回。
/// </param> /// </param>
/// <returns>object数组</returns> /// <returns>object数组</returns>
public virtual object[] ByteArrayToObjectArray(byte[] contents, public override object[] ByteArrayToObjectArray(byte[] contents,
IEnumerable<KeyValuePair<Type, int>> translateTypeAndCount) IEnumerable<KeyValuePair<Type, int>> translateTypeAndCount)
{ {
var translation = new List<object>(); var translation = new List<object>();
@@ -729,7 +1026,7 @@ namespace Modbus.Net
/// <typeparam name="T">需要转换的目标类型</typeparam> /// <typeparam name="T">需要转换的目标类型</typeparam>
/// <param name="contents">object数组</param> /// <param name="contents">object数组</param>
/// <returns>目标数组</returns> /// <returns>目标数组</returns>
public T[] ObjectArrayToDestinationArray<T>(object[] contents) public override T[] ObjectArrayToDestinationArray<T>(object[] contents)
{ {
var array = new T[contents.Length]; var array = new T[contents.Length];
Array.Copy(contents, array, contents.Length); Array.Copy(contents, array, contents.Length);
@@ -744,7 +1041,7 @@ namespace Modbus.Net
/// <param name="subPos">设置的比特位位置仅setValue为bit的时候有效</param> /// <param name="subPos">设置的比特位位置仅setValue为bit的时候有效</param>
/// <param name="setValue">写入的值</param> /// <param name="setValue">写入的值</param>
/// <returns>写入是否成功</returns> /// <returns>写入是否成功</returns>
public bool SetValue(byte[] contents, int setPos, int subPos, object setValue) public override bool SetValue(byte[] contents, int setPos, int subPos, object setValue)
{ {
var type = setValue.GetType(); var type = setValue.GetType();
@@ -814,7 +1111,7 @@ namespace Modbus.Net
/// <param name="pos">设置的位置</param> /// <param name="pos">设置的位置</param>
/// <param name="setValue">要设置的值</param> /// <param name="setValue">要设置的值</param>
/// <returns>设置是否成功</returns> /// <returns>设置是否成功</returns>
public virtual bool SetValue(byte[] contents, int pos, object setValue) public override bool SetValue(byte[] contents, int pos, object setValue)
{ {
try try
{ {
@@ -864,7 +1161,7 @@ namespace Modbus.Net
/// <param name="subPos">bit位置</param> /// <param name="subPos">bit位置</param>
/// <param name="setValue">bit数</param> /// <param name="setValue">bit数</param>
/// <returns>设置是否成功</returns> /// <returns>设置是否成功</returns>
public virtual bool SetBit(byte[] contents, int pos, int subPos, bool setValue) public override bool SetBit(byte[] contents, int pos, int subPos, bool setValue)
{ {
try try
{ {
@@ -890,35 +1187,7 @@ namespace Modbus.Net
/// <summary> /// <summary>
/// ValueHelper单例的实例 /// ValueHelper单例的实例
/// </summary> /// </summary>
public static ValueHelper Instance => _instance ?? (_instance = new ValueHelper()); public static ValueHelper Instance => _instance ?? (_instance = new LittleEndianLsbValueHelper());
/// <summary>
/// 根据端格式获取ValueHelper实例
/// </summary>
/// <param name="endian">端格式</param>
/// <returns>对应的ValueHelper实例</returns>
public static ValueHelper GetInstance(Endian endian)
{
switch (endian)
{
case Endian.LittleEndianLsb:
{
return Instance;
}
case Endian.BigEndianLsb:
{
return BigEndianValueHelper.Instance;
}
case Endian.BigEndianMsb:
{
return BigEndianMsbValueHelper.Instance;
}
default:
{
return Instance;
}
}
}
#endregion #endregion
} }
@@ -926,14 +1195,14 @@ namespace Modbus.Net
/// <summary> /// <summary>
/// 值与字节数组之间转换的辅助类大端格式这是一个Singleton类 /// 值与字节数组之间转换的辅助类大端格式这是一个Singleton类
/// </summary> /// </summary>
public class BigEndianValueHelper : ValueHelper public class BigEndianLsbValueHelper : LittleEndianLsbValueHelper
{ {
private static BigEndianValueHelper _bigEndianInstance; private static BigEndianLsbValueHelper _bigEndianInstance;
/// <summary> /// <summary>
/// 构造器 /// 构造器
/// </summary> /// </summary>
protected BigEndianValueHelper() protected BigEndianLsbValueHelper()
{ {
} }
@@ -950,8 +1219,8 @@ namespace Modbus.Net
/// <summary> /// <summary>
/// 覆盖的获取实例的方法 /// 覆盖的获取实例的方法
/// </summary> /// </summary>
public new static BigEndianValueHelper Instance public new static BigEndianLsbValueHelper Instance
=> _bigEndianInstance ?? (_bigEndianInstance = new BigEndianValueHelper()); => _bigEndianInstance ?? (_bigEndianInstance = new BigEndianLsbValueHelper());
/// <summary> /// <summary>
/// 将short数字转换为byte数组 /// 将short数字转换为byte数组
@@ -1169,9 +1438,9 @@ namespace Modbus.Net
/// <summary> /// <summary>
/// 值与字节数组之间转换的辅助类(大端-大端位格式这是一个Singleton类 /// 值与字节数组之间转换的辅助类(大端-大端位格式这是一个Singleton类
/// </summary> /// </summary>
public class BigEndianMsbValueHelper : BigEndianValueHelper public class BigEndianMsbValueHelper : BigEndianLsbValueHelper
{ {
private static BigEndianValueHelper _bigEndianInstance; private static BigEndianMsbValueHelper _bigEndianInstance;
/// <summary> /// <summary>
/// 构造函数 /// 构造函数
@@ -1198,7 +1467,7 @@ namespace Modbus.Net
/// <summary> /// <summary>
/// 覆盖的实例获取方法 /// 覆盖的实例获取方法
/// </summary> /// </summary>
public new static BigEndianValueHelper Instance public new static BigEndianMsbValueHelper Instance
=> _bigEndianInstance ?? (_bigEndianInstance = new BigEndianMsbValueHelper()); => _bigEndianInstance ?? (_bigEndianInstance = new BigEndianMsbValueHelper());
/// <summary> /// <summary>

View File

@@ -124,7 +124,7 @@ namespace Modbus.Net
AddressHelper.MapProtocolGetCountToAbstractByteCount( AddressHelper.MapProtocolGetCountToAbstractByteCount(
preNum - (int)Math.Floor(initNum), preNum - (int)Math.Floor(initNum),
AddressTranslator.GetAreaByteLength(address.Area), AddressTranslator.GetAreaByteLength(address.Area),
BigEndianValueHelper.Instance.ByteLength[preType.FullName])), ValueHelper.ByteLength[preType.FullName])),
DataType = typeof(byte), DataType = typeof(byte),
OriginalAddresses = originalAddresses.ToList() OriginalAddresses = originalAddresses.ToList()
}); });
@@ -153,7 +153,7 @@ namespace Modbus.Net
Math.Ceiling( Math.Ceiling(
AddressHelper.MapProtocolGetCountToAbstractByteCount( AddressHelper.MapProtocolGetCountToAbstractByteCount(
preNum - (int)Math.Floor(initNum), AddressTranslator.GetAreaByteLength(area), preNum - (int)Math.Floor(initNum), AddressTranslator.GetAreaByteLength(area),
BigEndianValueHelper.Instance.ByteLength[preType.FullName])), ValueHelper.ByteLength[preType.FullName])),
DataType = typeof(byte), DataType = typeof(byte),
OriginalAddresses = originalAddresses.ToList() OriginalAddresses = originalAddresses.ToList()
}); });
@@ -173,9 +173,9 @@ namespace Modbus.Net
foreach (var communicationUnit in ans) foreach (var communicationUnit in ans)
{ {
var oldByteCount = communicationUnit.GetCount * var oldByteCount = communicationUnit.GetCount *
BigEndianValueHelper.Instance.ByteLength[communicationUnit.DataType.FullName]; ValueHelper.ByteLength[communicationUnit.DataType.FullName];
var oldOriginalAddresses = communicationUnit.OriginalAddresses.ToList(); var oldOriginalAddresses = communicationUnit.OriginalAddresses.ToList();
while (oldByteCount * BigEndianValueHelper.Instance.ByteLength[communicationUnit.DataType.FullName] > while (oldByteCount * ValueHelper.ByteLength[communicationUnit.DataType.FullName] >
MaxLength) MaxLength)
{ {
var newOriginalAddresses = new List<AddressUnit<TKey>>(); var newOriginalAddresses = new List<AddressUnit<TKey>>();
@@ -184,9 +184,9 @@ namespace Modbus.Net
do do
{ {
var currentAddressUnit = oldOriginalAddresses.First(); var currentAddressUnit = oldOriginalAddresses.First();
newByteCount += BigEndianValueHelper.Instance.ByteLength[currentAddressUnit.DataType.FullName]; newByteCount += ValueHelper.ByteLength[currentAddressUnit.DataType.FullName];
if (newByteCount > MaxLength) break; if (newByteCount > MaxLength) break;
oldByteCount -= BigEndianValueHelper.Instance.ByteLength[currentAddressUnit.DataType.FullName]; oldByteCount -= ValueHelper.ByteLength[currentAddressUnit.DataType.FullName];
newOriginalAddresses.Add(currentAddressUnit); newOriginalAddresses.Add(currentAddressUnit);
oldOriginalAddresses.RemoveAt(0); oldOriginalAddresses.RemoveAt(0);
} while (newByteCount < MaxLength); } while (newByteCount < MaxLength);
@@ -199,7 +199,7 @@ namespace Modbus.Net
GetCount = GetCount =
(int) (int)
Math.Ceiling(newByteCount / Math.Ceiling(newByteCount /
BigEndianValueHelper.Instance.ByteLength[communicationUnit.DataType.FullName]), ValueHelper.ByteLength[communicationUnit.DataType.FullName]),
OriginalAddresses = newOriginalAddresses OriginalAddresses = newOriginalAddresses
}; };
@@ -214,7 +214,7 @@ namespace Modbus.Net
communicationUnit.GetCount = communicationUnit.GetCount =
(int) (int)
Math.Ceiling(oldByteCount / Math.Ceiling(oldByteCount /
BigEndianValueHelper.Instance.ByteLength[communicationUnit.DataType.FullName]); ValueHelper.ByteLength[communicationUnit.DataType.FullName]);
communicationUnit.OriginalAddresses = oldOriginalAddresses; communicationUnit.OriginalAddresses = oldOriginalAddresses;
newAns.Add(communicationUnit); newAns.Add(communicationUnit);
} }
@@ -309,7 +309,7 @@ namespace Modbus.Net
continusAddress.Address, preCommunicationUnit.Address, continusAddress.Address, preCommunicationUnit.Address,
AddressTranslator.GetAreaByteLength(continusAddress.Area)) - AddressTranslator.GetAreaByteLength(continusAddress.Area)) -
preCommunicationUnit.GetCount * preCommunicationUnit.GetCount *
BigEndianValueHelper.Instance.ByteLength[ ValueHelper.ByteLength[
preCommunicationUnit.DataType.FullName]) preCommunicationUnit.DataType.FullName])
}; };
addressesGaps.Add(gap); addressesGaps.Add(gap);
@@ -327,8 +327,8 @@ namespace Modbus.Net
nowAddress = continusAddresses[index]; nowAddress = continusAddresses[index];
index--; index--;
var preAddress = continusAddresses[index]; var preAddress = continusAddresses[index];
if (nowAddress.GetCount * BigEndianValueHelper.Instance.ByteLength[nowAddress.DataType.FullName] + if (nowAddress.GetCount * ValueHelper.ByteLength[nowAddress.DataType.FullName] +
preAddress.GetCount * BigEndianValueHelper.Instance.ByteLength[preAddress.DataType.FullName] + preAddress.GetCount * ValueHelper.ByteLength[preAddress.DataType.FullName] +
orderedGap.GapNumber > MaxLength) continue; orderedGap.GapNumber > MaxLength) continue;
jumpNumberInner -= orderedGap.GapNumber; jumpNumberInner -= orderedGap.GapNumber;
if (jumpNumberInner < 0) break; if (jumpNumberInner < 0) break;
@@ -341,10 +341,10 @@ namespace Modbus.Net
Address = preAddress.Address, Address = preAddress.Address,
GetCount = GetCount =
(int) (int)
(preAddress.GetCount * BigEndianValueHelper.Instance.ByteLength[preAddress.DataType.FullName]) + (preAddress.GetCount * ValueHelper.ByteLength[preAddress.DataType.FullName]) +
orderedGap.GapNumber + orderedGap.GapNumber +
(int) (int)
(nowAddress.GetCount * BigEndianValueHelper.Instance.ByteLength[nowAddress.DataType.FullName]), (nowAddress.GetCount * ValueHelper.ByteLength[nowAddress.DataType.FullName]),
DataType = typeof(byte), DataType = typeof(byte),
OriginalAddresses = preAddress.OriginalAddresses.ToList().Union(nowAddress.OriginalAddresses) OriginalAddresses = preAddress.OriginalAddresses.ToList().Union(nowAddress.OriginalAddresses)
}; };
@@ -385,7 +385,7 @@ namespace Modbus.Net
public override IEnumerable<CommunicationUnit<TKey>> Combine(IEnumerable<AddressUnit<TKey>> addresses) public override IEnumerable<CommunicationUnit<TKey>> Combine(IEnumerable<AddressUnit<TKey>> addresses)
{ {
var addressUnits = addresses as IList<AddressUnit<TKey>> ?? addresses.ToList(); var addressUnits = addresses as IList<AddressUnit<TKey>> ?? addresses.ToList();
var count = addressUnits.Sum(address => BigEndianValueHelper.Instance.ByteLength[address.DataType.FullName]); var count = addressUnits.Sum(address => ValueHelper.ByteLength[address.DataType.FullName]);
return return
new AddressCombinerNumericJump<TKey>((int)(count * Percentage / 100.0), MaxLength, AddressTranslator) new AddressCombinerNumericJump<TKey>((int)(count * Percentage / 100.0), MaxLength, AddressTranslator)
.Combine( .Combine(

View File

@@ -80,7 +80,7 @@ namespace Modbus.Net
double byteLength) double byteLength)
{ {
return protocolAddress + return protocolAddress +
BigEndianValueHelper.Instance.ByteLength[nextPositionBetweenType.FullName] / byteLength; ValueHelper.ByteLength[nextPositionBetweenType.FullName] / byteLength;
} }
/// <summary> /// <summary>
@@ -92,7 +92,7 @@ namespace Modbus.Net
public static double GetAbstractCoordinateNextPosition(double abstractAddress, Type nextPositionBetweenType) public static double GetAbstractCoordinateNextPosition(double abstractAddress, Type nextPositionBetweenType)
{ {
return abstractAddress + return abstractAddress +
BigEndianValueHelper.Instance.ByteLength[nextPositionBetweenType.FullName]; ValueHelper.ByteLength[nextPositionBetweenType.FullName];
} }
} }
} }

View File

@@ -192,7 +192,7 @@ namespace Modbus.Net
communicateAddress.SubAddress), communicateAddress.SubAddress),
(int) (int)
Math.Ceiling(communicateAddress.GetCount * Math.Ceiling(communicateAddress.GetCount *
BigEndianValueHelper.Instance.ByteLength[ ValueHelper.ByteLength[
communicateAddress.DataType.FullName])); communicateAddress.DataType.FullName]));
@@ -210,7 +210,7 @@ namespace Modbus.Net
else if (datas.Datas.Length != 0 && datas.Datas.Length < else if (datas.Datas.Length != 0 && datas.Datas.Length <
(int) (int)
Math.Ceiling(communicateAddress.GetCount * Math.Ceiling(communicateAddress.GetCount *
BigEndianValueHelper.Instance.ByteLength[ ValueHelper.ByteLength[
communicateAddress.DataType.FullName])) communicateAddress.DataType.FullName]))
{ {
return new ReturnStruct<Dictionary<string, ReturnUnit<double>>>() return new ReturnStruct<Dictionary<string, ReturnUnit<double>>>()
@@ -437,7 +437,7 @@ namespace Modbus.Net
AddressFormater.FormatAddress(communicateAddress.Area, communicateAddress.Address, 0), AddressFormater.FormatAddress(communicateAddress.Area, communicateAddress.Address, 0),
(int) (int)
Math.Ceiling(communicateAddress.GetCount * Math.Ceiling(communicateAddress.GetCount *
BigEndianValueHelper.Instance.ByteLength[ ValueHelper.ByteLength[
communicateAddress.DataType.FullName])); communicateAddress.DataType.FullName]));
var valueHelper = ValueHelper.GetInstance(BaseUtility.Endian); var valueHelper = ValueHelper.GetInstance(BaseUtility.Endian);
@@ -458,7 +458,7 @@ namespace Modbus.Net
else if (datas.Datas.Length < else if (datas.Datas.Length <
(int) (int)
Math.Ceiling(communicateAddress.GetCount * Math.Ceiling(communicateAddress.GetCount *
BigEndianValueHelper.Instance.ByteLength[ ValueHelper.ByteLength[
communicateAddress.DataType.FullName])) communicateAddress.DataType.FullName]))
return new ReturnStruct<bool>() return new ReturnStruct<bool>()
{ {

View File

@@ -288,7 +288,8 @@ But after ":", property should match constructor except protocol, which refer to
The main target of Modbus.Net is building a high extensable hardware communication protocol, so we allow everyone to extend the protocol. The main target of Modbus.Net is building a high extensable hardware communication protocol, so we allow everyone to extend the protocol.
To extend Modbus.Net, first of all ValueHelper.cs in Modbus.Net is a really powerful tool that you can use to modify values in byte array.There are two ValueHelpers: ValueHelper(Little Endian) and BigEndianValueHelper(Big Endian). Remember using the correct one. To extend Modbus.Net, first of all ValueHelper.cs in Modbus.Net is a really powerful tool that you can use to modify values in byte array.There are three ValueHelpers: LittleEndianLsbValueHelper(Little Endian), BigEndianLsbValueHelper(Big Endian) and BigEndianMsbValueHelper(Big Endian with bit reverse). Remember using the correct one.<br>
If you want to write a new one, just write in namespace "Modbus.Net" in assmenly start with "Modbus.Net." and Modbus.Net will automatically load it.
In this tutorial I will use Modbus.Net.Modbus to tell you how to implement your own protocol. In this tutorial I will use Modbus.Net.Modbus to tell you how to implement your own protocol.
@@ -314,9 +315,9 @@ public class ReadDataModbusProtocol : ProtocolUnit
public override IOutputStruct Unformat(byte[] messageBytes, ref int pos) public override IOutputStruct Unformat(byte[] messageBytes, ref int pos)
{ {
byte slaveAddress = BigEndianValueHelper.Instance.GetByte(messageBytes, ref pos); byte slaveAddress = BigEndianLsbValueHelper.Instance.GetByte(messageBytes, ref pos);
byte functionCode = BigEndianValueHelper.Instance.GetByte(messageBytes, ref pos); byte functionCode = BigEndianLsbValueHelper.Instance.GetByte(messageBytes, ref pos);
byte dataCount = BigEndianValueHelper.Instance.GetByte(messageBytes, ref pos); byte dataCount = BigEndianLsbValueHelper.Instance.GetByte(messageBytes, ref pos);
byte[] dataValue = new byte[dataCount]; byte[] dataValue = new byte[dataCount];
Array.Copy(messageBytes, 3, dataValue, 0, dataCount); Array.Copy(messageBytes, 3, dataValue, 0, dataCount);
return new ReadDataModbusOutputStruct(slaveAddress, functionCode, dataCount, dataValue); return new ReadDataModbusOutputStruct(slaveAddress, functionCode, dataCount, dataValue);
@@ -368,8 +369,8 @@ public class ModbusTcpProtocolLinkerBytesExtend : ProtocolLinkerBytesExtend
byte[] newFormat = new byte[6 + content.Length]; byte[] newFormat = new byte[6 + content.Length];
int tag = 0; int tag = 0;
ushort leng = (ushort)content.Length; ushort leng = (ushort)content.Length;
Array.Copy(BigEndianValueHelper.Instance.GetBytes(tag), 0, newFormat, 0, 4); Array.Copy(BigEndianLsbValueHelper.Instance.GetBytes(tag), 0, newFormat, 0, 4);
Array.Copy(BigEndianValueHelper.Instance.GetBytes(leng), 0, newFormat, 4, 2); Array.Copy(BigEndianLsbValueHelper.Instance.GetBytes(leng), 0, newFormat, 4, 2);
Array.Copy(content, 0, newFormat, 6, content.Length); Array.Copy(content, 0, newFormat, 6, content.Length);
return newFormat; return newFormat;
} }

View File

@@ -109,7 +109,7 @@ namespace Modbus.Net
try try
{ {
var typeName = getTypeAndCount.Key.FullName; var typeName = getTypeAndCount.Key.FullName;
var bCount = BigEndianValueHelper.Instance.ByteLength[typeName]; var bCount = ValueHelper.ByteLength[typeName];
var getReturnValue = await GetDatasAsync(startAddress, var getReturnValue = await GetDatasAsync(startAddress,
(int)Math.Ceiling(bCount * getTypeAndCount.Value)); (int)Math.Ceiling(bCount * getTypeAndCount.Value));
var getBytes = getReturnValue; var getBytes = getReturnValue;
@@ -230,7 +230,7 @@ namespace Modbus.Net
var bAllCount = ( var bAllCount = (
from getTypeAndCount in translateTypeAndCount from getTypeAndCount in translateTypeAndCount
let typeName = getTypeAndCount.Key.FullName let typeName = getTypeAndCount.Key.FullName
let bCount = BigEndianValueHelper.Instance.ByteLength[typeName] let bCount = ValueHelper.ByteLength[typeName]
select (int)Math.Ceiling(bCount * getTypeAndCount.Value)).Sum(); select (int)Math.Ceiling(bCount * getTypeAndCount.Value)).Sum();
var getReturnValue = await GetDatasAsync(startAddress, bAllCount); var getReturnValue = await GetDatasAsync(startAddress, bAllCount);
var getBytes = getReturnValue; var getBytes = getReturnValue;

View File

@@ -35,7 +35,7 @@ namespace CrossLamp.Controllers
} }
Lamp light = new Lamp(); Lamp light = new Lamp();
object[] lampsbyte = (await _utility.GetDatasAsync("0X 1", new KeyValuePair<Type, int>(typeof(bool), 7))).Datas; object[] lampsbyte = (await _utility.GetDatasAsync("0X 1", new KeyValuePair<Type, int>(typeof(bool), 7))).Datas;
bool[] lamps = BigEndianValueHelper.Instance.ObjectArrayToDestinationArray<bool>(lampsbyte); bool[] lamps = BigEndianLsbValueHelper.Instance.ObjectArrayToDestinationArray<bool>(lampsbyte);
if (lamps[0]) if (lamps[0])
{ {
light.MainLamp = LightLamp.Red.ToString(); light.MainLamp = LightLamp.Red.ToString();

View File

@@ -46,7 +46,7 @@ namespace TripleAdd.Controllers
await utility.ConnectAsync(); await utility.ConnectAsync();
} }
object[] getNum = (await utility.GetDatasAsync("4X 1", new KeyValuePair<Type, int>(typeof(ushort), 4))).Datas; object[] getNum = (await utility.GetDatasAsync("4X 1", new KeyValuePair<Type, int>(typeof(ushort), 4))).Datas;
ushort[] getNumUshorts = BigEndianValueHelper.Instance.ObjectArrayToDestinationArray<ushort>(getNum); ushort[] getNumUshorts = BigEndianLsbValueHelper.Instance.ObjectArrayToDestinationArray<ushort>(getNum);
return SetValue(getNumUshorts); return SetValue(getNumUshorts);
} }