Ejemplo n.º 1
0
        /// <summary>
        /// 检测线程函数,用于多线程检测
        /// </summary>
        /// <param name="com"></param>
        private void ProcDetectting(object com)
        {
            SerialPortCommunication serialPort = com as SerialPortCommunication;
            bool bOpen = serialPort.IsOpen();

            if (!bOpen)
            {
                return;
            }
            serialPort.SendData(_detectCommandBytes);
        }
Ejemplo n.º 2
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));
        }
Ejemplo n.º 3
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);
 }