using System;
using System.IO;
using System.IO.Ports;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace COM_test_2
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private void connect ()
{
string[] ports = SerialPort.GetPortNames();
SerialPort[] serialPort = new SerialPort[ports.Length];
foreach (string port in ports)
{
int i = Array.IndexOf(ports, port);
//serialPort[i] = new SerialPort();
serialPort[i].PortName = port;
serialPort[i].BaudRate = 9600;
serialPort[i].Open();
serialPort[i].DataReceived += serialPort_DataReceived;
comboBox.Items.Add(port);
}
}
private void serialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
SerialPort serialPort1 = sender as SerialPort;
byte[] data = new byte[serialPort1.BytesToRead];
Stream portStream = serialPort1.BaseStream;
portStream.Read(data, 0, data.Length);
}
}
}
private void Main_Load(object sender, EventArgs e)
{
var portNames = SerialPort.GetPortNames();
portSelectorComboBox.Items.AddRange(portNames);
}
private void portSelectorComboBox_TextChanged(object sender, EventArgs e)
{
_portName = portSelectorComboBox.SelectedItem.ToString();
}
private void portOpenButton_Click(object sender, EventArgs e)
{
try
{
port = new SerialPort(_portName, 115200, Parity.None, 8, StopBits.Two);
port.ReceivedBytesThreshold = 1;
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
port.Open();
portStatusText.Text = "Ok, port open";
}
catch (Exception)
{
portStatusText.Text = "Error";
MessageBox.Show("неправильно выбран порт, попробуйте еще раз");
}
}
void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
}
using System.Management;
public static Dictionary<string, ManagementBaseObject> EnumerateComPorts()
{
Dictionary<string, ManagementBaseObject> result = new Dictionary<string, ManagementBaseObject>();
string[] ports = SerialPort.GetPortNames();
foreach (string port in ports)
{
using (var entitySearcher = new ManagementObjectSearcher(
"root\\CIMV2", $"SELECT * FROM Win32_PnPEntity WHERE Caption LIKE '%{port}%'"))
{
var matchingEntity = entitySearcher.Get().Cast<ManagementBaseObject>().FirstOrDefault();
if (null != matchingEntity)
{
result.Add(port, matchingEntity);
}
} // using
} // foreach
return result;
} // EnumerateComPorts
public RS232Listener(string portname)
{
m_queue = new Queue<string>();
try
{
if (null != m_port)
{
m_port.Close();
m_port.Dispose();
GC.Collect();
GC.WaitForPendingFinalizers();
}
m_port = new SerialPort(portname, 9600, Parity.None, 8, StopBits.One);
m_port.DataReceived += this.M_port_DataReceived;
m_port.ErrorReceived += this.M_port_ErrorReceived;
m_port.Open();
} // try
catch(Exception ex)
{
Logger.LogError("RS232Listener constructor", ex.Message, ex);
ErrorMessage = ex.Message;
ErrorState = true;
}
} // RS232Listener constructor