ClientPort.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using RJCP.IO.Ports;
  2. using SHJX.Service.Common.ReadXML;
  3. using SHJX.Service.ServerClient.RS485;
  4. using SHJX.Service.Common.Logging;
  5. using Microsoft.Extensions.Logging;
  6. namespace SHJX.Service.ServerClient
  7. {
  8. public sealed class ClientPort
  9. {
  10. private readonly bool _isAuto;
  11. private readonly string _port;
  12. private static readonly ILogger logger = LogFactory.BuildLogger(typeof(ClientPort));
  13. public ClientPort( ReadConfigUtil config)
  14. {
  15. _port = config.Port;
  16. _isAuto = config.IsAutoGetPort;
  17. }
  18. /// <summary>
  19. /// 打开连接
  20. /// </summary>
  21. /// <returns></returns>
  22. public (string, bool) OpenClient()
  23. {
  24. Rs485Client.InitPort();
  25. if (Rs485Client.IsValid)
  26. {
  27. return (Rs485Client.Sport.PortName, Rs485Client.IsValid);
  28. }
  29. if (_isAuto)
  30. {
  31. var portStr = FindMoonsMotor();
  32. if (string.IsNullOrWhiteSpace(portStr))
  33. {
  34. return ("NULL", false);
  35. }
  36. Rs485Client.Open(portStr);
  37. }
  38. else
  39. {
  40. Rs485Client.Open(_port);
  41. }
  42. return (Rs485Client.Sport.PortName, Rs485Client.IsValid);
  43. }
  44. /// <summary>
  45. /// 遍历所有COM口,查找鸣志电机通信口.
  46. /// </summary>
  47. /// <param name="addr">电机RS485地址号</param>
  48. /// <returns>找到的端口名,否则为string.Empty</returns>
  49. private string FindMoonsMotor(char addr = '1')
  50. {
  51. var portName = string.Empty; // 记录找到的端口
  52. foreach (var comport in SerialPortStream.GetPortNames())
  53. {
  54. Rs485Client.Open(comport);
  55. if (!Rs485Client.IsValid) continue;
  56. var strCmd = $"{addr}SC\r";
  57. var strRes = Rs485Client.SendData(strCmd, '\r');
  58. Rs485Client.Close();
  59. if (string.IsNullOrEmpty(strRes) || !strRes.Contains("SC="))
  60. continue;
  61. portName = comport;// OK,找到端口
  62. break;
  63. }
  64. return portName;
  65. }
  66. }
  67. }