using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO.Ports; using System.Text.RegularExpressions; using Microsoft.Win32; namespace TinyFPGA_VisualProgrammer { public class SerialController { SerialPort mainSerial = new SerialPort(); public List sPortsList { get; private set; } public string comPortName { get; set; } public SerialController() { mainSerial.BaudRate = 9600; List usbPorts = ComPortNames("1D50", "6130"); if (usbPorts.Count > 0) { sPortsList = new List(); foreach (string s in SerialPort.GetPortNames()) { if (usbPorts.Contains(s)) sPortsList.Add(s); } } } public void OpenPort() { mainSerial.PortName = comPortName; mainSerial.ReadTimeout = 2000; mainSerial.WriteTimeout = 5000; try { mainSerial.Open(); } catch { } } public void ClosePort() { try { mainSerial.Close(); } catch { } } public bool GetPortOpened() { return mainSerial.IsOpen; } public void SendBytes(byte[] db, int dc) { mainSerial.WriteTimeout = 5000; try { mainSerial.Write(db, 0, dc); } catch { } } public byte[] WaitForBytes(int dc) { byte[] result = new byte[dc]; mainSerial.ReadTimeout = 2000; try { mainSerial.Read(result, 0, dc); } catch { } return result; } /// /// Compile an array of COM port names associated with given VID and PID /// /// /// /// List ComPortNames(String VID, String PID) { String pattern = String.Format("^VID_{0}.PID_{1}", VID, PID); Regex _rx = new Regex(pattern, RegexOptions.IgnoreCase); List comports = new List(); RegistryKey rk1 = Registry.LocalMachine; RegistryKey rk2 = rk1.OpenSubKey("SYSTEM\\CurrentControlSet\\Enum"); foreach (String s3 in rk2.GetSubKeyNames()) { RegistryKey rk3 = rk2.OpenSubKey(s3); foreach (String s in rk3.GetSubKeyNames()) { if (_rx.Match(s).Success) { RegistryKey rk4 = rk3.OpenSubKey(s); foreach (String s2 in rk4.GetSubKeyNames()) { RegistryKey rk5 = rk4.OpenSubKey(s2); RegistryKey rk6 = rk5.OpenSubKey("Device Parameters"); comports.Add((string)rk6.GetValue("PortName")); } } } } return comports; } } }