Exemple #1
0
        public Tuple <string, byte> DoDetectEx()
        {
            _detectEvent.Reset();
            string connectedCom = string.Empty;

            string[]      portNames  = SerialPort.GetPortNames();//new string[] { "COM1" };//
            List <Thread> threadPool = new List <Thread>();
            List <SerialPortCommunication> serialPortPool = new List <SerialPortCommunication>();

            _bufferByCom.Clear();
            foreach (string port in portNames)
            {
                //开启多线程,每个串口开一个
                _bufferByCom.Add(port, new List <byte>());
                Thread detectThread = new Thread(new ParameterizedThreadStart(ProcDetectting));
                SerialPortCommunication serialPort = new SerialPortCommunication();
                serialPort.InitializeDevice(port, _baudRate, _dataBits, _stopBits, _parity);
                serialPort.DataReceived += OnDetectDataReceived;
                try
                {
                    serialPort.Open();
                }
                catch
                {
                    continue;
                }
                serialPortPool.Add(serialPort);
                threadPool.Add(detectThread);
                detectThread.Start(serialPort);
                //Thread.Sleep(500);
            }
            for (int i = 0; i < threadPool.Count; i++)
            {
                threadPool[i].Join();
            }
            if (_detectEvent.WaitOne(WAITFOREVENTTIMEOUT))
            {
            }
            for (int i = 0; i < serialPortPool.Count; i++)
            {
                serialPortPool[i].Close();
            }
            for (int i = 0; i < threadPool.Count; i++)
            {
                threadPool[i].Abort();
            }
            return(new Tuple <string, byte>(_detectedPortName, _detectedProductID));
        }
Exemple #2
0
 /// <summary>
 /// 打开串口
 /// </summary>
 /// <returns></returns>
 public bool Open()
 {
     if (null == _communicateDevice)
     {
         _communicateDevice = new SerialPortCommunication();
     }
     if (_communicateDevice.IsOpen())
     {
         _communicateDevice.Close();
     }
     _communicateDevice.InitializeDevice(_portName, _baudRate, _dataBits, _stopBits, _parity, Handshake.None);
     _communicateDevice.DataReceived += ReceiveData;
     try
     {
         _communicateDevice.Open();
     }
     catch
     {
         return(false);
     }
     return(true);
 }