HirataRobotIIConnection.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System.Collections.Generic;
  2. using System.IO.Ports;
  3. using System.Linq;
  4. using System.Text;
  5. using Aitex.Core.RT.Log;
  6. using MECF.Framework.Common.Communications;
  7. namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Robots.HirataRobotII
  8. {
  9. public class HirataRobotIIMessage : AsciiMessage
  10. {
  11. public string Data { get; set; }
  12. public string ErrorText { get; set; }
  13. }
  14. public class HirataRobotIIConnection : SerialPortConnectionBase
  15. {
  16. //private bool _isAckMode = false;//should read from config file
  17. private string _cachedBuffer = string.Empty;
  18. private List<byte> _lstCacheBuffer = new List<byte>();
  19. private HirataRobotII _robot;
  20. public HirataRobotIIConnection(string portName, HirataRobotII robot=null,int baudRate = 19200, int dataBits = 7, Parity parity = Parity.Even, StopBits stopBits = StopBits.One)
  21. : base(portName, baudRate, dataBits, parity, stopBits, "\0", false)
  22. {
  23. _robot = robot;
  24. }
  25. public override bool SendMessage(byte[] message)
  26. {
  27. _lstCacheBuffer.Clear();
  28. return base.SendMessage(message);
  29. }
  30. protected override MessageBase ParseResponse(byte[] rawBuffer)
  31. {
  32. _lstCacheBuffer.AddRange(rawBuffer);
  33. byte[] temps = _lstCacheBuffer.ToArray();
  34. HirataRobotIIMessage msg = new HirataRobotIIMessage();
  35. msg.IsFormatError = false;
  36. msg.IsResponse = false;
  37. msg.IsComplete = false;
  38. msg.IsEvent = false;
  39. if (temps.Length <= 7) return msg;
  40. byte lrc = 0x00;
  41. for (int i=1;i<temps.Length -1;i++)
  42. {
  43. lrc ^= temps[i];
  44. }
  45. if (temps[temps.Length - 1] != lrc) return msg;
  46. if (temps[temps.Length - 2] != 0x3 && !_robot.isSimulatorMode) return msg;
  47. msg.IsResponse = true;
  48. string rawText = Encoding.ASCII.GetString(temps);
  49. msg.RawMessage = rawText;
  50. //remove '\0'
  51. rawText = rawText.Substring(0, rawText.Length - 1);
  52. string content = rawText.Substring(4, rawText.Length - 5).
  53. Replace(Encoding.ASCII.GetString(new byte[] { 0x3 }), ""); ;
  54. content = content.Trim();
  55. if (content.First() == 'E')
  56. {
  57. msg.IsError = true;
  58. }
  59. msg.Data = content;
  60. msg.IsResponse = true;
  61. msg.IsAck = true;
  62. msg.IsComplete = true;
  63. _lstCacheBuffer.Clear();
  64. return msg;
  65. }
  66. private static byte CalcLRC(List<byte> data)
  67. {
  68. byte ret = 0x00;
  69. for (var i = 0; i < data.Count; i++)
  70. {
  71. ret ^= data[i];
  72. }
  73. return ret;
  74. }
  75. }
  76. }