我在串口通信上遇到问题。 问题是端口是打开的,但是当我检查是否(_cc.port.IsOpen)没有任何反应时它会跳转到其他地方尝试打开端口。好吧,端口无法打开,因为它已经打开了。
COMcon.CS
private void connectSerial(string indata, string password)
{
port = new SerialPort(indata, 9600, Parity.None, 8, StopBits.One);
DateTime dt = DateTime.Now;
string time = dt.ToShortTimeString();
try
{
port.Open();
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
if (port.IsOpen)
{
port.WriteLine(Environment.NewLine);
port.WriteLine("no");
port.WriteLine("enable");
if (password != String.Empty)
{
port.WriteLine(password);
}
port.WriteLine("terminal length 0");
port.WriteLine("config terminal");
}
}
catch (Exception ex) { Console.WriteLine("Error" + ex); }
CommandManager.CS
public bool rCommand(string command)
{
try
{
if (_cc.port.IsOpen)
{
_cc.port.WriteLine(command);
log.WriteLine(command);
return true; // True?
}
else
{
_cc.port.Open();
log.Write(logger.logHandler("CODE1"));
if (_cc.port.IsOpen)
log.Write(logger.logHandler("CODE2"));
return false;
}
}
catch (Exception ex) { Console.WriteLine("Error: " + ex); log.Write("Error: " + ex); return false; } // Error
}