HirataR4RobotConnection.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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.RobotHirataR4
  8. {
  9. public class HirataR4RobotMessage : AsciiMessage
  10. {
  11. public string Data { get; set; }
  12. public string ErrorText { get; set; }
  13. }
  14. public class HirataR4RobotConnection : 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. public HirataR4RobotConnection(string portName, int baudRate = 19200, int dataBits = 7, Parity parity = Parity.Even, StopBits stopBits = StopBits.One)
  20. : base(portName, baudRate, dataBits, parity, stopBits, "\0", false)
  21. {
  22. }
  23. public override bool SendMessage(byte[] message)
  24. {
  25. _lstCacheBuffer.Clear();
  26. return base.SendMessage(message);
  27. }
  28. protected override MessageBase ParseResponse(byte[] rawBuffer)
  29. {
  30. _lstCacheBuffer.AddRange(rawBuffer);
  31. byte[] temps = _lstCacheBuffer.ToArray();
  32. HirataR4RobotMessage msg = new HirataR4RobotMessage();
  33. msg.IsFormatError = false;
  34. msg.IsComplete = false;
  35. msg.IsEvent = false;
  36. if (temps.Length <= 7) return msg;
  37. byte lrc = 0x00;
  38. for (int i=1;i<temps.Length -1;i++)
  39. {
  40. lrc ^= temps[i];
  41. }
  42. if (temps[temps.Length - 1] != lrc) return msg;
  43. string rawText = Encoding.ASCII.GetString(temps);
  44. msg.RawMessage = rawText;
  45. //remove '\0'
  46. rawText = rawText.Substring(0, rawText.Length - 1);
  47. string content = rawText.Substring(4, rawText.Length - 5).
  48. Replace(Encoding.ASCII.GetString(new byte[] { 0x3 }), ""); ;
  49. content = content.Trim();
  50. if (content.First() == 'E')
  51. {
  52. msg.IsError = true;
  53. }
  54. msg.Data = content;
  55. msg.IsResponse = true;
  56. msg.IsAck = true;
  57. msg.IsComplete = true;
  58. _lstCacheBuffer.Clear();
  59. return msg;
  60. }
  61. private static byte CalcLRC(List<byte> data)
  62. {
  63. byte ret = 0x00;
  64. for (var i = 0; i < data.Count; i++)
  65. {
  66. ret ^= data[i];
  67. }
  68. return ret;
  69. }
  70. }
  71. }