static public List <String> GetBoardPorts(String supportedBoards, List <String> allowedPorts = null, List <String> deniedPorts = null) { if (supportedBoards == null || supportedBoards == String.Empty) { throw new Exception("ArduinoDeviceManager:Connect no supportedBoards provided"); } //all ports that match supported boards List <String> boardPorts = SerialPorts.Find(supportedBoards.Trim()); bool allowAllPorts = (allowedPorts == null || allowedPorts.Count == 0); bool denySomePorts = (deniedPorts != null && deniedPorts.Count > 0); if (allowAllPorts && !denySomePorts) { return(boardPorts); } else { List <String> ports2return = new List <String>(); foreach (var p in boardPorts) { if (deniedPorts != null && deniedPorts.Contains(p)) { continue; } if (allowedPorts != null && allowedPorts.Contains(p)) { ports2return.Add(p); } } return(ports2return); } }
virtual protected void ResetPort(String port, Exception e) { //ensure that if an ADM is connected then we disconnect it first DisconnectADM(port); System.Threading.Thread.Sleep(500); if (SerialPorts.IsOpen(port)) { throw new Exception("Serial port is open on " + port); } //now we disable-enable the device connected to the port DeviceManager devMgr = DeviceManager.GetInstance(); List <DeviceManager.DeviceInfo> ar = devMgr.GetDevices("(" + port + ")"); if (ar.Count == 1) { DeviceManager.DeviceInfo di = ar[0]; Tracing?.TraceEvent(TraceEventType.Information, 0, "Attempting reset of device {0} of status {1} on port {2}", di.Description, di.Status, port);; Process proc = devMgr.ResetDevice(di.InstanceID); String output = proc.StandardOutput.ReadToEnd(); Tracing?.TraceEvent(TraceEventType.Information, 0, output); } else { Tracing?.TraceEvent(TraceEventType.Warning, 0, "ADMService::ResetPort Could not find a unique device for port {0}", port); } }
public void TestSerialPortsSearch() { var serialPorts = new SerialPorts(); var portsCount = serialPorts.GetPortsCount(); if (portsCount <= 0) { LogAssert.Expect(LogType.Error, "no ports"); } for (uint i = 0; i < portsCount; i++) { var portInfo = serialPorts.GetPortAt(i); Assert.True(portInfo.IsValid); var portInfo2 = serialPorts.GetPortByName(portInfo.port); Assert.True(portInfo2.IsValid); Assert.True(portInfo == portInfo2); } // invalid port name { var portInfo2 = serialPorts.GetPortByName("<invalid port name>"); Assert.True(!portInfo2.IsValid); } }
private void SelectSerialPortByDeviceId(string deviceId) { SelectedSerialPort = SerialPorts.FirstOrDefault(p => string.Equals(p.DeviceID, deviceId, StringComparison.Ordinal)); if (SelectedSerialPort == null) { SelectedSerialPortDeviceId = deviceId; } }
public MainViewModel() { _Random = new Random(); SerialPorts = SerialPort.GetPortNames(); BaudRates = new[] { 300, 600, 1200, 2400, 9600, 14400, 19200, 38400, 57600, 115200 }; SelectedSerialPort = SerialPorts.Where(p => p == DefaultPortName).FirstOrDefault(); SelectedBaudRate = BaudRates.Where(r => r == DefaultBaudRate).FirstOrDefault(); InitialiseSerialPort(); }
protected void AddAllowedPorts(String allowedPorts) { if (allowedPorts == null || allowedPorts == String.Empty) { return; } List <String> p2a = SerialPorts.ExpandComPortRanges(allowedPorts); AllowedPorts.AddRange(p2a); }
private void RefreshCSerialPorts_Click(object sender, RoutedEventArgs e) { var refreshedPorts = OutputSerialDeviceHandler.GetPorts(); SerialPorts.Clear(); foreach (var port in refreshedPorts) { SerialPorts.Add(port); } }
protected void AddDeniedPorts(String deniedPorts) { if (deniedPorts == null || deniedPorts == String.Empty) { return; } List <String> p2a = SerialPorts.ExpandComPortRanges(deniedPorts); DeniedPorts.AddRange(p2a); }
private async Task Initialize() { var serialPortSelector = Windows.Devices.SerialCommunication.SerialDevice.GetDeviceSelector(); var devices = await DeviceInformation.FindAllAsync(serialPortSelector); foreach (var item in devices) { SerialPorts.Add(new SerialPortInfo(item.Id, item.Name)); Debug.WriteLine("SerialPorts Added Id = [" + item.Id + "], name = [" + item.Name + "]"); } }
public ComStatusViewModel(MainViewModel parent, MophAppProxy mophApp) { _parent = parent; _mophApp = mophApp; _mophApp.LogOutput += OnLogOutput; SelectedSerialPort = "None"; SerialPorts.Add(SelectedSerialPort); foreach (var port in SerialPort.GetPortNames()) { SerialPorts.Add(port); } }
private void DeviceRemoved(object sender, DeviceChangeEventArgs e) { if ((e.Type == INTV.Core.Model.Device.ConnectionType.Serial) && DeviceChange.IsDeviceChangeFromSystem(e.State)) { var removedDevice = SerialPorts.FirstOrDefault(p => p.PortName == e.Name); if ((removedDevice != null) && SerialPorts.Remove(removedDevice)) { INTV.Shared.ComponentModel.CommandManager.InvalidateRequerySuggested(); } } RaisePropertyChanged("IsPortValid"); }
private void DeviceAdded(object sender, DeviceChangeEventArgs e) { if ((e.Type == INTV.Core.Model.Device.ConnectionType.Serial) && DeviceChange.IsDeviceChangeFromSystem(e.State)) { var acceptPort = IsNotExclusivePort(Connection.CreatePseudoConnection(e.Name, ConnectionType.Serial)); if (acceptPort && !SerialPorts.Any(p => p.PortName == e.Name)) { SerialPorts.Add(new SerialPortViewModel(e.Name)); } INTV.Shared.ComponentModel.CommandManager.InvalidateRequerySuggested(); } RaisePropertyChanged("IsPortValid"); }
private void DisconnectNode() { if (SerialPorts.IsOpen) { SendData("STOP"); AddNodeLine("Ya no se escucha la conexión."); AddLogLine("CONEXIÓN ELIMINADA."); BtnOn.Enabled = true; btnOff.Enabled = false; PortsDisplay.Enabled = true; ConnectData.Enabled = false; isConnected = false; ConnectionEnable = false; btnIniciar.Visible = false; btnIniciar.Enabled = false; SerialPorts.Close(); } }
public async Task Initialize() { #if NETFX_CORE var userPath = Windows.Storage.ApplicationData.Current.LocalFolder.Path; #else var userPath = ""; #endif ZWOptions.Instance.Initialize(); // Add any app specific options here... // ordinarily, just write "Detail" level messages to the log //m_options.AddOptionInt("SaveLogLevel", (int)ZWLogLevel.Detail); // save recent messages with "Debug" level messages to be dumped if an error occurs //m_options.AddOptionInt("QueueLogLevel", (int)ZWLogLevel.Debug); // only "dump" Debug to the log emessages when an error-level message is logged //m_options.AddOptionInt("DumpTriggerLevel", (int)ZWLogLevel.Error); // Lock the options ZWOptions.Instance.Lock(); // Create the OpenZWave Manager ZWManager.Instance.Initialize(); ZWManager.Instance.OnNotification += OnNodeNotification; #if NETFX_CORE var serialPortSelector = Windows.Devices.SerialCommunication.SerialDevice.GetDeviceSelector(); var devices = await DeviceInformation.FindAllAsync(serialPortSelector); foreach (var item in devices) { SerialPorts.Add(new SerialPortInfo(item)); } #else foreach (var item in System.IO.Ports.SerialPort.GetPortNames()) { SerialPorts.Add(new SerialPortInfo(item)); } #endif }
public async Task RefreshSerialPortsAsync() { var activePorts = SerialPorts.Where(p => p.IsActive).Select(p => p.PortID).ToList(); SerialPorts.Clear(); #if NETFX_CORE var serialPortSelector = Windows.Devices.SerialCommunication.SerialDevice.GetDeviceSelector(); var devices = await DeviceInformation.FindAllAsync(serialPortSelector); foreach (var item in devices) { bool isActive = activePorts.Contains(item.Id); SerialPorts.Add(new SerialPortInfo(item.Id, item.Name, isActive)); if (isActive) { activePorts.Remove(item.Id); } } #else //.NET foreach (var item in System.IO.Ports.SerialPort.GetPortNames()) { bool isActive = activePorts.Contains(item); SerialPorts.Add(new SerialPortInfo(item, item, isActive)); if (isActive) { activePorts.Remove(item.Id); } } #endif #if DEBUG // SerialPorts.Add(new SerialPortInfo("//COM-TEST/1", "Test Port 1")); // SerialPorts.Add(new SerialPortInfo("//COM-TEST/2", "Test Port 2")); // SerialPorts.Add(new SerialPortInfo("//COM-TEST/3", "Test Port 3")); // SerialPorts.Add(new SerialPortInfo("//COM-TEST/4", "Test Port 4")); #endif // Remove controllers on ports that were active but lost foreach (var item in activePorts) { Watcher.Instance.RemoveController(item); } }
void Start() { var ports = new SerialPorts(); Label.text = "Start test:\n"; var portsCount = ports.GetPortsCount(); Label.text += "Ports count: " + portsCount + "\n"; for (uint i = 0; i < portsCount + 1; i++) { Label.text += "Port #" + i + ": " + ports.GetPortAt(i) + "\n"; } Label.text += "Port \"/dev/cu.usbmodem14C1\": " + ports.GetPortByName("/dev/cu.usbmodem14C1") + "\n"; Label.text += "Done.\n"; }
public async Task RefreshPorts() { var token = _cancellationSource.Token; IsRefreshBusy = true; await Task.Delay(750, token).ConfigureAwait(true); var lastSelectedDeviceId = SelectedSerialPortDeviceId; SerialPorts.Clear(); try { var scope = new ManagementScope("\\\\.\\ROOT\\cimv2"); var observer = new ManagementOperationObserver(); using var searcher = new ManagementObjectSearcher(scope, new SelectQuery("Win32_PnPEntity")); observer.ObjectReady += (_, e) => { var portInfo = SerialPortInfo.FromManagementObject(e.NewObject as ManagementObject); if (portInfo == null) { return; } SerialPorts.Add(portInfo); }; var taskCompletion = new TaskCompletionSource(); observer.Completed += (_, _) => taskCompletion.TrySetResult(); searcher.Get(observer); using (token.Register(() => taskCompletion.TrySetCanceled())) await taskCompletion.Task.WaitAsync(token).ConfigureAwait(true); } catch { } SelectSerialPortByDeviceId(lastSelectedDeviceId); await Task.Delay(250, token).ConfigureAwait(true); IsRefreshBusy = false; }
/// <summary> /// Programación del Puerto Serie. /// - Configura el nombre del puerto segun la configuracion local. /// - Pone las líneas de salida al estado marcado por la configuración. /// - Inicializa la estructura de ultimo estado conocido en líneas. /// </summary> private void SetSerialPort() { SerialPorts port = local_settings.puerto_serie; string strPort = port == SerialPorts.COM1 ? "COM1" : port == SerialPorts.COM2 ? "COM2" : port == SerialPorts.COM3 ? "COM3" : port == SerialPorts.COM4 ? "COM4" : port == SerialPorts.COM4 ? "COM5" : port == SerialPorts.COM4 ? "COM6" : port == SerialPorts.COM4 ? "COM7" : port == SerialPorts.COM4 ? "COM8" : "Error"; serial_port.PortName = strPort; serial_port.Handshake = Handshake.None; serial_port.RtsEnable = local_settings.ps_salida == HskOut.RTS ? true : false; serial_port.DtrEnable = local_settings.ps_salida == HskOut.DTR ? true : false; last_state.cd = false; last_state.cts = false; last_state.dsr = false; }
public void TestSerialPortsList() { var serialPorts = new SerialPorts(); var portsCount = serialPorts.GetPortsCount(); if (portsCount <= 0) { LogAssert.Expect(LogType.Error, "no ports"); } for (uint i = 0; i < portsCount; i++) { var portInfo = serialPorts.GetPortAt(i); Assert.True(portInfo.IsValid); } // invalid port index { var portInfo = serialPorts.GetPortAt(portsCount + 1); Assert.True(!portInfo.IsValid); } }
private void ConnectToNode() { string SelectedPort = PortsDisplay.GetItemText(PortsDisplay.SelectedItem); try { SerialPorts.DataReceived += new SerialDataReceivedEventHandler(SerialPorts_DataReceived); SerialPorts.Open(); AddNodeLine("== CONEXIÓN ESTABLECIDA =="); AddLogLine("== CONEXIÓN ESTABLECIDA =="); isConnected = true; BtnOn.Enabled = false; btnOff.Enabled = true; ConnectData.Enabled = true; PortsDisplay.Enabled = false; AddLogLine("Puerto en uso:" + PortsDisplay.GetItemText(PortsDisplay.SelectedItem)); } catch (Exception ex) { MessageBox.Show("Ha ocurrido un error:" + ex); } }
void ReadingData() { while (true) { Thread.Sleep(300); if (!isConnected) { TimerX.Suspend(); break; } try { string TextToRead = SerialPorts.ReadExisting(); AddNodeLine("Listening: " + TextToRead); AddRealLine(TextToRead); GetCommand(TextToRead); Thread.Sleep(250); } catch (Exception ex) {} } }
private async Task Initialize() { #if NETFX_CORE var serialPortSelector = Windows.Devices.SerialCommunication.SerialDevice.GetDeviceSelector(); var devices = await DeviceInformation.FindAllAsync(serialPortSelector); foreach (var item in devices) { SerialPorts.Add(new SerialPortInfo(item.Id, item.Name)); } #else //.NET foreach (var item in System.IO.Ports.SerialPort.GetPortNames()) { SerialPorts.Add(new SerialPortInfo(item, item)); } #endif #if DEBUG // SerialPorts.Add(new SerialPortInfo("//COM-TEST/1", "Test Port 1")); // SerialPorts.Add(new SerialPortInfo("//COM-TEST/2", "Test Port 2")); // SerialPorts.Add(new SerialPortInfo("//COM-TEST/3", "Test Port 3")); // SerialPorts.Add(new SerialPortInfo("//COM-TEST/4", "Test Port 4")); #endif }
private void ButtonConnector_OnNewPortNames(List <string> names) { if (names.Count >= SerialPorts.Count) { for (int i = 0; i < names.Count; ++i) { if (i >= SerialPorts.Count) { SerialPorts.Add(names[i]); } else if (SerialPorts[i] != names[i]) { SerialPorts[i] = names[i]; } } } else { for (int i = names.Count; i < SerialPorts.Count; ++i) { SerialPorts.RemoveAt(i); } } }
void SerialPortPinChangedEvent(object source, SerialPorts.SerialEventArgs e) { }
private void SerialPort_PinChanged(object source, SerialPorts.SerialEventArgs e) { }
private bool Initialize(DeviceEntry entry) { this.Name = entry[DeviceEntry.Name].ToString(); this.Id = entry[DeviceEntry.Identity].ToString(); this.DeviceConfigPath = entry[DeviceEntry.Path].ToString(); this.Version = entry[DeviceEntry.Version].ToString(); this.baudRate = this.GetValue(entry, DeviceEntry.BaudRate, 9600); this.readTimeout = this.GetValue(entry, DeviceEntry.ReadTimeout, 12000); this.dataBits = this.GetValue(entry, DeviceEntry.DataBits, ComDataBits); this.stopBits = (StopBits)this.GetValue(entry, DeviceEntry.StopBits, (int)StopBits.One); StringValue parity = (StringValue)entry[DeviceEntry.Parity]; this.parity = SerialPorts.ParseParity(parity); // this.actionSend1 = Encoding.ASCII.GetBytes((StringValue)entry["ActionSend1"]); this.actionSend2 = Encoding.ASCII.GetBytes((StringValue)entry["ActionSend2"]); // Virtual On string isVirtual = (StringValue)entry[DeviceEntry.Virtual]; if (isVirtual != null && isVirtual.ToLower() == "true") { this.isVirtual = true; } string bufferSleepString = (StringValue)entry["BufferSleep"]; if (bufferSleepString != null) { this.bufferSleep = int.Parse(bufferSleepString); } // this.actionDelay = (StringValue)entry[DeviceEntry.ActionDelay]; const int DefaultRecordInterval = 30; this.actionInterval = this.GetValue(entry, DeviceEntry.ActionInterval, DefaultRecordInterval); this.RecordInterval = this.GetValue(entry, DeviceEntry.RecordInterval, DefaultRecordInterval); this.recordTimePolicy.Interval = this.RecordInterval; string tableName = (StringValue)entry[DeviceEntry.TableName]; if (!string.IsNullOrEmpty(tableName)) { string tableFields = (StringValue)entry[DeviceEntry.TableFields]; string[] fields = tableFields.Split(','); string atList = string.Empty; for (int i = 0; i < fields.Length; ++i) { string at = string.Format("@{0}, ", i + 1); atList += at; } atList = atList.TrimEnd(',', ' '); // Insert into string cmd = string.Format("insert into {0}({1}) values({2})", tableName, tableFields, atList); this.insertIntoCommand = cmd; } string fieldsConfigStr = (StringValue)entry[DeviceEntry.FieldsConfig]; List <FieldConfig> fieldConfigList = ParseDataFieldConfig(fieldsConfigStr); this.fieldsConfig = fieldConfigList.ToArray <FieldConfig>(); if (!this.IsRealDevice) { string el = (StringValue)entry[DeviceEntry.ExampleLine]; el = el.Replace("\\r", "\r"); el = el.Replace("\\n", "\n"); this.exampleLine = el; } return(true); }
public void Initialize() { SerialPorts = SerialPortService.GetPortNames(); if (SettingsService.PortName == null) { SerialPort = SerialPorts.FirstOrDefault(); } else { SerialPort = SettingsService.PortName; } DataBitsItems = new[] { 5, 6, 7, 8 }; DataBits = SettingsService.DataBits; BaudRateItems = new[] { 9600, 19200, 38400, 57600, 115200, 230400, 460800, 921600 }; BaudRate = SettingsService.BaudRate; ParityItems = (Parity[])Enum.GetValues(typeof(Parity)); Parity = SettingsService.Parity; StopBitsItems = ((StopBits[])Enum.GetValues(typeof(StopBits))).Skip(1); StopBits = SettingsService.StopBits; HandshakesItems = (Handshake[])Enum.GetValues(typeof(Handshake)); Handshake = SettingsService.Handshake; DtrEnabled = SettingsService.DtrEnable; RtsEnabled = SettingsService.RtsEnable; Encodings = new[] { "ASCII", "UTF-8", "Unicode", "BigEndianUnicode" }; Encoding = SettingsService.Encoding; OutputFormatList = (Format[])Enum.GetValues(typeof(Format)); OutputFormat = SettingsService.OutputFormat; IntputFormatList = (Format[])Enum.GetValues(typeof(Format)); InputFormat = SettingsService.InputFormat; PrintInputToScreen = SettingsService.PrintInput; LinePushDelay = SettingsService.LinePushDelay; NewLine = Regex.Escape(SettingsService.NewLine); }
override public bool HandleCommand(Connection cnn, Message message, String cmd, List <Object> args, Message response) { bool respond = true; MessageSchema schema = new ADMService.MessageSchema(response); DeviceManager devMgr; ArduinoDeviceManager adm; switch (cmd) { case "status": schema.AddADMS(ADMS); List <String> ports = ArduinoDeviceManager.GetBoardPorts(SupportedBoards, AllowedPorts, DeniedPorts); schema.AddPorts(ports); schema.AddRequiredBoards(RequiredBoards); devMgr = DeviceManager.GetInstance(); List <String> portDevices = new List <String>(); foreach (String port in ports) { List <DeviceManager.DeviceInfo> devs = devMgr.GetDevices("(" + port + ")"); foreach (DeviceManager.DeviceInfo devInfo in devs) { String s = String.Format("{0} ({1}): {2}", devInfo.Description, devInfo.InstanceID, devInfo.Status); portDevices.Add(s); } } response.AddValue("PortDevices", portDevices); break; case "disable-port": case "enable-port": case "reset-port": if (args.Count != 1 || args[0] == null || args[0].ToString() == String.Empty) { throw new Exception("No port specified"); } String devicePort = args[0].ToString().ToUpper(); devMgr = DeviceManager.GetInstance(); List <DeviceManager.DeviceInfo> ar = devMgr.GetDevices("(" + devicePort + ")"); if (ar.Count != 1) { throw new Exception("Cannot find device on port " + devicePort); } DeviceManager.DeviceInfo di = ar[0]; //first we check if there is an ADM on this port String output = ""; lock (_lockMonitorADM) { if (ADMS.ContainsKey(devicePort)) { output += String.Format("Found ADM on port {0} so disconnecting first", devicePort) + Environment.NewLine; DisconnectADM(devicePort); System.Threading.Thread.Sleep(500); if (SerialPorts.IsOpen(devicePort)) { throw new Exception("Serial port is open on " + devicePort); } } Process proc = null; if (cmd == "disable-port") { proc = devMgr.DisableDevice(di.InstanceID); } else if (cmd == "enable-port") { proc = devMgr.EnableDevice(di.InstanceID); } else { proc = devMgr.ResetDevice(di.InstanceID); } output += proc.StandardOutput.ReadToEnd(); } response.Value = output; break; default: var tgtcmd = cmd.Split(':'); if (tgtcmd.Length < 2) { throw new Exception(String.Format("ADM: Unrecognised command {0}", cmd)); } //Check that there are any boards connected if (ADMS.Count == 0) { throw new Exception("ADM: No boards connected"); } //so this is an ADM command, find the board first adm = GetADM(tgtcmd[0]); if (adm == null) { throw new Exception(String.Format("ADM: Cannot find ADM {0}", tgtcmd[0])); } if (!adm.IsConnected) { throw new Exception(String.Format("ADM: {0} is not conntected", adm.BoardID)); } //handle commands related to the board (i.e. not to a specific added device) if (tgtcmd.Length == 2) { int repeat; //frequently used var name int delay; //frequently used var name switch (tgtcmd[1].ToLower()) { case "status": AddADMRequest(adm, adm.RequestStatus(), response.Target); respond = false; break; case "ping": AddADMRequest(adm, adm.Ping(), response.Target); respond = false; break; case "pingloadtest": repeat = args != null && args.Count > 0 ? System.Convert.ToInt16(args[0]) : 10; delay = args != null && args.Count > 1 ? System.Convert.ToInt16(args[1]) : 500; Task.Run(() => { for (int i = 0; i < repeat; i++) { adm.Ping(); System.Threading.Thread.Sleep(delay); } }); respond = false; break; case "capability": var lbc = adm.ListBoardCapability(); response.AddValue("PinCount: ", lbc.Count); response.AddValue("Pins", lbc); break; case "disconnect": DisconnectADM(adm.Port); break; case "setdigitalpin": if (args.Count < 2) { throw new Exception("Insufficient arguments ... must supply a pin number and value"); } int pin = System.Convert.ToInt16(args[0]); bool val = Chetch.Utilities.Convert.ToBoolean(args[1]); if (!adm.IsPinCapable(pin, Solid.Arduino.Firmata.PinMode.DigitalOutput)) { throw new Exception(String.Format("Pin {0} is not capabale of digital output", pin)); } if (adm.GetDevicesByPin(pin) != null) { throw new Exception(String.Format("Pin {0} is being used by a device", pin)); } adm.SetDigitalPinMode(pin, Solid.Arduino.Firmata.PinMode.DigitalOutput); adm.SetDigitalPin(pin, val); break; case "setdigitalport": if (args.Count < 2) { throw new Exception("Insufficient arguments ... must supply a port number and value"); } int port = System.Convert.ToInt16(args[0]); bool enable = Chetch.Utilities.Convert.ToBoolean(args[1]); adm.SetDigitalReportMode(port, enable); //adm.G break; case "list-devices": schema.AddDevices(adm.GetDevices()); break; case "list-pins": break; default: throw new Exception(String.Format("No ADM direct command {0}", tgtcmd[1])); } } else { //handle command specific to device try { respond = HandleADMDeviceCommand(adm, tgtcmd[1], tgtcmd[2], args, response); } catch (Exception e) { Tracing?.TraceEvent(TraceEventType.Error, 0, "Exception: {0}", e.Message); throw e; } } if (response.Value == null || response.Value == String.Empty) { response.Value = "Handled " + cmd; } break; } return(respond); }
public PortDialog() { InitializeComponent(); DataContext = new SerialPorts(); }
private void SerialPort_Error(object source, SerialPorts.SerialEventArgs e) { }
private void SendData(string data) { SerialPorts.Write(data); }
/* Methode zum Auflisten der seriellen Ports des Systems */ public static SerialPorts EnumSerialPorts() { // SerialPorts-Instanz für die Rückgabe erzeugen SerialPorts ports = new SerialPorts(); // WMI-Auflistung der Objekte der Win32_SerialPort erzeugen ManagementClass mc = new ManagementClass("Win32_SerialPort"); ManagementObjectCollection moc = mc.GetInstances(); // Die einzelnen Objekte durchgehen foreach (ManagementBaseObject mbo in moc) { // SerialPort-Instanz erzeugen und initialisieren SerialPort port = new SerialPort(); try{ port.DeviceId = (string)mbo["DeviceId"]; } catch {} try{ port.MaxBaudRate = (uint)mbo["MaxBaudRate"]; } catch {} try{ port.Supports16BitMode = (bool)mbo["Supports16BitMode"]; } catch {} try{ port.SupportsDTRDSR = (bool)mbo["SupportsDTRDSR"]; } catch {} try { port.SupportsElapsedTimeouts = (bool)mbo["SupportsElapsedTimeouts"]; } catch {} try{ port.SupportsIntTimeouts = (bool)mbo["SupportsIntTimeouts"]; } catch {} try{ port.SupportsParityCheck = (bool)mbo["SupportsParityCheck"]; } catch {} try{ port.SupportsRLSD = (bool)mbo["SupportsRLSD"]; } catch {} try{ port.SupportsRTSCTS = (bool)mbo["SupportsRTSCTS"]; } catch {} try { port.SupportsSpecialCharacters = (bool)mbo["SupportsSpecialCharacters"]; } catch {} try{ port.SupportsXOnXOff = (bool)mbo["SupportsXOnXOff"]; } catch {} try{ port.SupportsXOnXOffSet = (bool)mbo["SupportsXOnXOffSet"]; } catch {} try{ port.StatusInfo = (SerialPortStatusInfo)mbo["StatusInfo"]; } catch {} // Fähigkeiten aus dem Capabilities-Array auslesen try { uint[] caps = (uint[])mbo["Capabilities"]; for (int i = 0; i < caps.Length; i++) { switch (caps[i]) { case 1: // Other port.Capabilities.Other = true; break; case 2: // Unknown port.Capabilities.Unknown = true; break; case 3: // XT/AT Compatible port.Capabilities.CompatibleXTAT = true; break; case 4: // 16450 Compatible port.Capabilities.Compatible16450 = true; break; case 5: // 16550 Compatible port.Capabilities.Compatible16550 = true; break; case 6: // 16550A Compatible port.Capabilities.Compatible16550A = true; break; case 160: // 8251 Compatible port.Capabilities.Compatible8251 = true; break; case 161: // 8251FIFO Compatible port.Capabilities.Compatible8251FIFO = true; break; } } } catch {} // SerialPort-Instanz an die Auflistung anfügen ports.Add(port); } // Speicher des WMI-Objekts freigeben um den Arbeitsspeicher möglichst // schnell zu entlasten moc.Dispose(); mc.Dispose(); // Ergebnis zurückgeben return(ports); }
private void SerialPort_ReceivedData(object source, SerialPorts.SerialEventArgs e) { /*Debug.Write("Serial Debug: "); while(com_port.InBufferBytes > 0) Debug.Write(com_port.ReadByte().ToString("X")+" "); Debug.WriteLine("");*/ /*string s = com_port.ReadLine(); Debug.WriteLine("Serial Debug: "+s); if(s[1] == 'D') last_rx = s;*/ }
void SerialPortReceivedEvent(object source, SerialPorts.SerialEventArgs e) { int num_to_read = commPort.InBufferBytes; byte[] inbuf = new byte[num_to_read]; commPort.Read(inbuf, 0, num_to_read); serial_rx_event(this, new SDRSerialSupportII.SerialRXEvent(inbuf, (uint)num_to_read)); }
void SerialPortErrorEvent(object source, SerialPorts.SerialEventArgs e) { }
private bool Initialize(DeviceEntry entry) { this.Name = entry[DeviceEntry.Name].ToString(); this.Id = entry[DeviceEntry.Identity].ToString(); this.DeviceConfigPath = entry[DeviceEntry.Path].ToString(); this.Version = entry[DeviceEntry.Version].ToString(); this.baudRate = this.GetValue(entry, DeviceEntry.BaudRate, 9600); this.readTimeout = this.GetValue(entry, DeviceEntry.ReadTimeout, 12000); this.dataBits = this.GetValue(entry, DeviceEntry.DataBits, ComDataBits); this.stopBits = (StopBits)this.GetValue(entry, DeviceEntry.StopBits, (int)StopBits.One); StringValue parity = (StringValue)entry[DeviceEntry.Parity]; this.parity = SerialPorts.ParseParity(parity); // Virtual On string isVirtual = (StringValue)entry[DeviceEntry.Virtual]; if (isVirtual != null && isVirtual.ToLower() == "true") { this.isVirtual = true; } string bufferSleepString = (StringValue)entry["BufferSleep"]; if (bufferSleepString != null) { this.bufferSleep = int.Parse(bufferSleepString); } this.actionCondition = (StringValue)entry[DeviceEntry.ActionCondition]; string actionSendInHex = (StringValue)entry[DeviceEntry.ActionSendInHex]; if (actionSendInHex != "true") { string actionSend = (StringValue)entry[DeviceEntry.ActionSend]; if (actionSend != null) { actionSend = actionSend.Replace("\\r", "\r"); this.actionSend = Encoding.ASCII.GetBytes(actionSend); } } else { this.actionSendInHex = true; string hexes = (StringValue)entry[DeviceEntry.ActionSend]; if (!string.IsNullOrEmpty(hexes)) { hexes = hexes.Trim(); this.actionSend = DeviceEntry.ParseHex(hexes); } } // this.actionDelay = (StringValue)entry[DeviceEntry.ActionDelay]; const int DefaultRecordInterval = 30; this.actionInterval = this.GetValue(entry, DeviceEntry.ActionInterval, DefaultRecordInterval); this.RecordInterval = this.GetValue(entry, DeviceEntry.RecordInterval, DefaultRecordInterval); this.recordTimePolicy.Interval = this.RecordInterval; /* * var sensitive = this.GetValue(entry, DeviceEntry.Sensitive, "false"); * this.sensitive = (sensitive.ToLower() == "true"); * * string sensitiveIndexStr = this.GetValue(entry, "SensitiveIndex", "-1"); * this.sensitiveIndex = int.Parse(sensitiveIndexStr); * * this.sensitiveDataTable = this.GetValue(entry, "SensitiveDataTable", ""); */ this.calcDataWithLastData = this.GetValue(entry, "CalcLast", 0) == 1; // Set DataParser & factors string dataParserClz = (StringValue)entry[DeviceEntry.DataParser]; this.dataParser = this.GetDataParser(dataParserClz); this.SetDataParserFactors(this.dataParser, entry); string tableName = (StringValue)entry[DeviceEntry.TableName]; if (!string.IsNullOrEmpty(tableName)) { string tableFields = (StringValue)entry[DeviceEntry.TableFields]; string[] fields = tableFields.Split(','); string atList = string.Empty; for (int i = 0; i < fields.Length; ++i) { string at = string.Format("@{0}, ", i + 1); atList += at; } atList = atList.TrimEnd(',', ' '); // Insert into string cmd = string.Format("insert into {0}({1}) values({2})", tableName, tableFields, atList); this.insertIntoCommand = cmd; } string fieldsConfigStr = (StringValue)entry[DeviceEntry.FieldsConfig]; List <FieldConfig> fieldConfigList = ParseDataFieldConfig(fieldsConfigStr); this.fieldsConfig = fieldConfigList.ToArray <FieldConfig>(); /* * if (this.sensitive) * { * string sensitiveFieldsConfigStr = (StringValue)entry["SensitiveFieldsConfig"]; * List<FieldConfig> sensitiveFieldConfigList = ParseDataFieldConfig(sensitiveFieldsConfigStr); * this.sensitiveFieldsConfig = sensitiveFieldConfigList.ToArray<FieldConfig>(); * } */ if (!this.IsRealDevice) { string el = (StringValue)entry[DeviceEntry.ExampleLine]; el = el.Replace("\\r", "\r"); el = el.Replace("\\n", "\n"); this.exampleLine = el; } return(true); }