private void RefreshPortNames()
        {
            // get two lists, and if not the same, replace one
            var physicalNames = SerialPort.GetPortNames();
            var localNames    = PortNames.ToArray(); // local copy to prevent locking/size changing issues

            var matches = physicalNames.Length == localNames.Length;

            if (matches)
            {
                // same length, check contents
                foreach (var name in physicalNames)
                {
                    matches &= localNames.Contains(name);
                }
                foreach (var name in localNames)
                {
                    matches &= physicalNames.Contains(name);
                }
            }
            if (!matches)
            {
                var msg = Messager;
                if (msg != null)
                {
                    msg.AddMessage("COM Ports changed");
                }
                // replace internals
                var curSelected = SelectedPortName;

                // copy in new ones
                PortNames.Clear();
                foreach (var name in physicalNames)
                {
                    PortNames.Add(name);
                }

                var oldNameOk = !String.IsNullOrEmpty(curSelected) && PortNames.Contains(curSelected);

                if (oldNameOk)
                {
                    SelectedPortName = curSelected;
                }
                else if (PortNames.Any())
                {
                    SelectedPortName = PortNames[0];
                }
                else
                {
                    SelectedPortName = "";
                }

                // todo - disconnect when pulled? handle crashes?
            }
        }
Example #2
0
 public ComPortViewModels()
 {
     if (!PortNames.Any())
     {
         throw new ArgumentException("Нет ни одного COM порта");
     }
     _serialPort = new SerialPort {
         Parity = Parity.None, DataBits = 8, StopBits = StopBits.One
     };
     PortName  = PortNames.Last();
     PortSpeed = 9600;
     _serialPort.DataReceived += SerialPortOnDataReceived;
 }