CanManagerClass.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace CCDCount.DLL.CanBus
  7. {
  8. public class CanManagerClass
  9. {
  10. UInt32 m_devtype = 4;//USBCAN2
  11. UInt32 m_devind = 0;
  12. UInt32 m_canind = 0;
  13. int DataLen = 8;
  14. int SendCount = 0;
  15. VCI_INIT_CONFIG config = new VCI_INIT_CONFIG();
  16. public void OpenDevice()
  17. {
  18. if (CanLibraryClass.VCI_OpenDevice(m_devtype, m_devind, 0) == 0)
  19. {
  20. Console.WriteLine("打开设备失败,请检查设备类型和设备索引号是否正确");
  21. return;
  22. }
  23. }
  24. public void InitCan()
  25. {
  26. //初始化CAN
  27. config.AccCode = Convert.ToUInt32("0x00000000", 16);
  28. config.AccMask = Convert.ToUInt32("0xFFFFFFFF", 16);
  29. config.Timing0 = Convert.ToByte("0x00", 16);
  30. config.Timing1 = Convert.ToByte("0x14", 16);
  31. config.Filter = (Byte)1;
  32. config.Mode = (Byte)0;
  33. if (CanLibraryClass.VCI_InitCAN(m_devtype, m_devind, m_canind, ref config) == 0)
  34. {
  35. Console.WriteLine("初始化Can失败");
  36. return;
  37. }
  38. if (CanLibraryClass.VCI_StartCAN(m_devtype, m_devind, m_canind) == 0)
  39. {
  40. Console.WriteLine("开启Can失败");
  41. return;
  42. }
  43. }
  44. public unsafe void SenMessage(byte[] bytes)
  45. {
  46. VCI_CAN_OBJ sendobj = new VCI_CAN_OBJ();
  47. sendobj.RemoteFlag = (byte)(0);
  48. sendobj.ExternFlag = (byte)(0);
  49. sendobj.ID = Convert.ToUInt32(Convert.ToString(SendCount, 16), 16);
  50. sendobj.DataLen = Convert.ToByte(bytes.Length > 8 ? 8 : bytes.Length);
  51. for (int i = 0; i < DataLen; i++)
  52. {
  53. sendobj.Data[i] = bytes[i];
  54. }
  55. if (CanLibraryClass.VCI_Transmit(m_devtype, m_devind, m_canind, ref sendobj, 1) == 0)
  56. {
  57. Console.WriteLine("发送失败");
  58. return;
  59. }
  60. }
  61. public void CloseCan()
  62. {
  63. CanLibraryClass.VCI_ResetCAN(m_devtype, m_devind, m_canind);
  64. }
  65. }
  66. }