WitCanProtocolUtils.cs 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using Wit.SDK.Utils;
  7. namespace Wit.SDK.Modular.Sensor.Utils
  8. {
  9. /// <summary>
  10. /// 维特CAN传感器协议工具类(需要使用TTL-CAN)
  11. /// </summary>
  12. public class WitCanProtocolUtils
  13. {
  14. /// <summary>
  15. /// 获得帧ID
  16. /// </summary>
  17. /// <param name="id">帧ID(10进制)</param>
  18. /// <param name="frameFormat">帧格式 0=标准 1=扩展</param>
  19. /// <param name="frmaeType">帧类型 0=数据 ; 1=远程</param>
  20. public static int GetFrameId(int id, int frameFormat, int frmaeType)
  21. {
  22. int frameId = frameFormat == 1 ? id << 3 | 0x04 : id <<= 21;
  23. if (frmaeType == 1) { frameId |= 0x02; }
  24. return frameId;
  25. }
  26. #region 获得读写命令
  27. /// <summary>
  28. /// 获得标准数据桢写命令
  29. /// </summary>
  30. /// <param name="canId"></param>
  31. /// <param name="reg"></param>
  32. /// <param name="value"></param>
  33. /// <returns></returns>
  34. public static byte[] GetStandWrite(int canId, byte reg, short value)
  35. {
  36. // 返回结果
  37. List<byte> byteList = new List<byte>();
  38. // 数据
  39. byte[] dataFrame = new byte[] { 0xff, 0xaa, reg, (byte)(value), (byte)(value >> 8) };
  40. // AT(2byte)
  41. byteList.AddRange(Encoding.Default.GetBytes("AT"));
  42. // 帧ID(4byte)
  43. int frameId = GetFrameId(canId, 0, 0);
  44. byteList.AddRange(BitConverter.GetBytes(frameId));
  45. // 数据长度(2byte)
  46. byteList.AddRange(new byte[] { (byte)(dataFrame.Length >> 8), (byte)(dataFrame.Length) });
  47. // 帧数据
  48. byteList.AddRange(dataFrame);
  49. // 回车换行(2byte)
  50. byteList.AddRange(Encoding.Default.GetBytes("\r\n"));
  51. return byteList.ToArray();
  52. }
  53. /// <summary>
  54. /// 获得标准数据桢读命令
  55. /// </summary>
  56. /// <param name="canId"></param>
  57. /// <param name="reg"></param>
  58. /// <param name="count"></param>
  59. /// <returns></returns>
  60. public static byte[] GetStandRead(int canId, byte reg)
  61. {
  62. // 返回结果
  63. List<byte> byteList = new List<byte>();
  64. // 数据
  65. byte[] dataFrame = new byte[] { 0xff, 0xaa, 0x27, reg, 00 };
  66. // AT(2byte)
  67. byteList.AddRange(Encoding.Default.GetBytes("AT"));
  68. // 帧ID(4byte)
  69. int frameId = GetFrameId(canId, 0, 0);
  70. byteList.AddRange(BitConverter.GetBytes(frameId));
  71. // 数据长度(2byte)
  72. byteList.AddRange(new byte[] { (byte)(dataFrame.Length >> 8),(byte)(dataFrame.Length) });
  73. // 帧数据
  74. byteList.AddRange(dataFrame);
  75. // 回车换行(2byte)
  76. byteList.AddRange(Encoding.Default.GetBytes("\r\n"));
  77. return byteList.ToArray();
  78. }
  79. #endregion
  80. }
  81. }