|
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Runtime.InteropServices;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace CommcationLibray
- {
- /// <summary>
- /// ModbusRTU / ModbusAscll / ModbusTCP
- /// 通用公共抽象类
- /// </summary>
- public abstract class ModbusBase
- {
- /// <summary>
- /// 封装公共报文区域
- /// </summary>
- /// <param name="unit_id"></param>
- /// <param name="func_code"></param>
- /// <param name="start_addr"></param>
- /// <param name="count"></param>
- /// <returns></returns>
- public byte[] ReadCommandBytes(byte unit_id, byte func_code, ushort start_addr, ushort count)
- {
- byte[] req_bytes = new byte[] {
- unit_id,
- func_code,
- (byte)(start_addr/256),
- (byte)(start_addr%256),
- (byte)(count/256),
- (byte)(count%256)
- };
-
- return req_bytes;
- }
- /// <summary>
- /// 获取对应的数据类型
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="data_bytes"></param>
- /// <returns></returns>
- public T[] GetValues<T>(byte[] data_bytes)
- {
- //GetValues<ushort> data_bytes 每两个字节转换成一个数字 float 4Bytes double 8
- //2 ushort short int16 uint16
- //4 int uint int32 uint32 float
- //8 double
- //16 decimal
- List<T> list = new List<T>();
- try
- {
- //检查类型的长度
- var type_len = Marshal.SizeOf(typeof(T));
- for (int i = 0; i < data_bytes.Length; i+= type_len)
- {
- //取出对应类型字节
- var temp_bytes = data_bytes.ToList().GetRange(i, type_len);
- if (BitConverter.IsLittleEndian)
- {
- temp_bytes.Reverse();
- }
-
- Type bitConverter_type = typeof(BitConverter);
- var mis = bitConverter_type.GetMethods().ToList();
- var mi = mis.FirstOrDefault(mi => mi.ReturnType == typeof(T) && mi.GetParameters().Length == 2);
- if (mi == null)
- {
- throw new Exception("数据转换类型出错!");
- }
-
- object value = mi.Invoke(bitConverter_type, new object[] { temp_bytes.ToArray(), 0 });
-
- list.Add((T)value);
-
- }
- }
- catch (Exception ex)
- {
-
- throw ex;
- }
- return list.ToArray();
- }
-
- public object[] GetValues(byte[] data_bytes, Type[] types)
- {
- object[] values = new object[types.Length];
- int index = 0;
- int i =0;
- foreach (var type in types)
- {
- var type_len = Marshal.SizeOf(type);
- var temp_bytes = data_bytes.ToList().GetRange(index, type_len);
- temp_bytes.Reverse();
-
- index += type_len;
-
- Type bitConverter_type = typeof(BitConverter);
- var mis = bitConverter_type.GetMethods().ToList();
- var mi = mis.FirstOrDefault(mi => mi.ReturnType == type && mi.GetParameters().Length == 2);
- if (mi == null)
- {
- throw new Exception("数据转换类型出错!");
- }
-
- object value = mi.Invoke(bitConverter_type, new object[] { temp_bytes.ToArray(), 0 });
-
- values[i++] = value;
- }
- return values;
- }
-
- }
- }
|