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; mainSerial.ReceivedBytesThreshold = 1; mainSerial.ReadBufferSize = 4096; mainSerial.WriteBufferSize = 4096; mainSerial.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); 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); } } } private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) { SerialPort sp = (SerialPort)sender; string indata = sp.ReadExisting(); Console.WriteLine("Data Received:"); Console.Write(indata); } public void OpenPort() { mainSerial.PortName = comPortName; mainSerial.ReadTimeout = 1000; mainSerial.WriteTimeout = 1000; try { mainSerial.Open(); } catch { } } public void ClosePort() { try { mainSerial.Close(); } catch { } } public bool GetPortOpened() { return mainSerial.IsOpen; } public void clearBuffer() { mainSerial.DiscardInBuffer(); mainSerial.DiscardOutBuffer(); } public void SendBytes(byte[] db, int dc) { try { mainSerial.Write(db, 0, dc); } catch { } //while (mainSerial.BytesToWrite >= 0) { } //mainSerial.DiscardOutBuffer(); } public byte[] WaitForBytes(int dc) { byte[] result = new byte[dc]; try { mainSerial.Read(result, 0, dc); } catch { } //while (mainSerial.BytesToRead >= 0) { } //mainSerial.DiscardOutBuffer(); 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; } } }