| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- using RJCP.IO.Ports;
- using SHJX.Service.Common.ReadXML;
- using SHJX.Service.ServerClient.RS485;
- using SHJX.Service.Common.Logging;
- using Microsoft.Extensions.Logging;
- namespace SHJX.Service.ServerClient
- {
- public sealed class ClientPort
- {
- private readonly bool _isAuto;
- private readonly string _port;
- private static readonly ILogger logger = LogFactory.BuildLogger(typeof(ClientPort));
- public ClientPort( ReadConfigUtil config)
- {
- _port = config.Port;
- _isAuto = config.IsAutoGetPort;
- }
- /// <summary>
- /// 打开连接
- /// </summary>
- /// <returns></returns>
- public (string, bool) OpenClient()
- {
- Rs485Client.InitPort();
- if (Rs485Client.IsValid)
- {
- return (Rs485Client.Sport.PortName, Rs485Client.IsValid);
- }
- if (_isAuto)
- {
- var portStr = FindMoonsMotor();
- if (string.IsNullOrWhiteSpace(portStr))
- {
- return ("NULL", false);
- }
- Rs485Client.Open(portStr);
- }
- else
- {
- Rs485Client.Open(_port);
- }
- return (Rs485Client.Sport.PortName, Rs485Client.IsValid);
- }
- /// <summary>
- /// 遍历所有COM口,查找鸣志电机通信口.
- /// </summary>
- /// <param name="addr">电机RS485地址号</param>
- /// <returns>找到的端口名,否则为string.Empty</returns>
- private string FindMoonsMotor(char addr = '1')
- {
-
- var portName = string.Empty; // 记录找到的端口
- foreach (var comport in SerialPortStream.GetPortNames())
- {
- Rs485Client.Open(comport);
- if (!Rs485Client.IsValid) continue;
- var strCmd = $"{addr}SC\r";
- var strRes = Rs485Client.SendData(strCmd, '\r');
- Rs485Client.Close();
- if (string.IsNullOrEmpty(strRes) || !strRes.Contains("SC="))
- continue;
- portName = comport;// OK,找到端口
- break;
- }
- return portName;
- }
- }
- }
|