public void Read(SerialPort _serialPort, int commNum, string portName, Connection connection) { while (_continue) { try { int bytes = _serialPort.BytesToRead; //Console.WriteLine(bytes); if (bytes > 0) { watch.Start(); byte[] buffer = new byte[bytes]; _serialPort.Read(buffer, 0, bytes); decHand.readInput(buffer, commNum, decHand); freq += buffer.Length; if (watch.ElapsedMilliseconds > 5000) { watch.Stop(); Console.WriteLine("Sensor Node " + commNum + " Data Frequency (Bytes per Second): " + (freq / watch.Elapsed.Seconds));// 2 = freq/watch / 12 * 6 freq = 0; watch.Reset(); } } } catch (Exception exception) { Console.WriteLine("Read: " + exception.Message); Console.WriteLine(portName + " disconnected :" + commNum); DetectPortThread.connContainer.Remove(commNum); DetectPortThread.portList.Remove(portName); connection.disconnect(false); } }//end while }
public void connect(string port, Connection connection) { try { _serialPort = new SerialPort(); _serialPort.PortName = port; _serialPort.BaudRate = Program.baudRate; _serialPort.DataBits = 8; _serialPort.Parity = Parity.None; _serialPort.StopBits = StopBits.One; _serialPort.ReadBufferSize = 8; _serialPort.Open(); portDisc = false; } catch // (Exception exception) { //if port is physically disconnected this will repeat due to stale data //Console.WriteLine("Connect: " + exception.Message); disconnect(true); portDisc = true; } }
public void reset(int node, string port, Connection connection) { try { Console.WriteLine("Automatic reset in progress."); _serialPort.Close(); Console.WriteLine("Disconnected from port " + port + "."); for (int i = 0; i < 100; i++) { Thread.Sleep(120); Console.Write("\rReset progress: {0}%", i + 1); } Console.Write("\rReset progress: {0}%", 100); Console.WriteLine("\nReconnecting to " + port + "."); _serialPort.Open(); readClass = new ConsoleRead(); readClass._continue = true; readThread = new Thread(() => readClass.Read(_serialPort, node, port, connection)); readThread.Start(); Console.WriteLine("Port " + port + " connected as node " + node + "."); Console.WriteLine("Connection to port " + port + " successfully reset."); } catch (Exception exception) { Console.WriteLine("Reset: " + exception.Message); disconnect(false); } }
public static void connect() { while (_continue) { try { List<string> portDiff = new List<string>(SerialPort.GetPortNames().ToList().Except(portList)); foreach (string port in portDiff) { //CO 3 string[] portSplit = port.Split('M'); int portNumber = int.Parse(portSplit[1]); Connection connection = new Connection(); connection.connect(port, connection); if (connection.portDisc == false) { connContainer.Add(portNumber, connection); connection.reset(portNumber, port, connection); portList.Add(port); } /* else { Console.Write("\rPort not connected"); } */ } } catch (Exception exception) { Console.WriteLine(exception.Message); } }//end while }