我正在上一门使用串行端口的课程。直到项目通过串口接收数据,类在主应用程序中引发事件,这一切都变得安静了。
我的问题是:如何将参数传递给委托并在我的班级中使用它,因为我的班级是如此独立。
在消息来源下方以及我喜欢在哪里花费代表。
类控制串口:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
namespace TCCExterna.Lib
{
public class PortaSerial //: IDisposable
{
private SerialPort serialPort;
private Queue<byte> recievedData = new Queue<byte>();
public PortaSerial()
{
serialPort = new SerialPort();
serialPort.DataReceived += serialPort_DataReceived;
}
public void Abrir(string porta, int velocidade)
{
serialPort.PortName = porta;
serialPort.BaudRate = velocidade;
serialPort.Open();
}
public string[] GetPortas()
{
return SerialPort.GetPortNames();
}
public string[] GetVelocidades()
{
return new string[] { "1200", "2400", "4800", "9600", "19200", "38400", "57600", "115200" };
}
void serialPort_DataReceived(object s, SerialDataReceivedEventArgs e)
{
byte[] data = new byte[serialPort.BytesToRead];
serialPort.Read(data, 0, data.Length);
data.ToList().ForEach(b => recievedData.Enqueue(b));
processData();
// like this use LineReceivedEvent or LineReceived
}
private void processData()
{
// Determine if we have a "packet" in the queue
if (recievedData.Count > 50)
{
var packet = Enumerable.Range(0, 50).Select(i => recievedData.Dequeue());
}
}
public void Dispose()
{
if (serialPort != null)
serialPort.Dispose();
}
}
}
程序:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using TCCExterna.Lib;
namespace TCCExterna
{
public partial class FormPrincipal : Form
{
PortaSerial sp1 = new PortaSerial(); // like this command passed LineReceivedEvent or LineReceived
public delegate void LineReceivedEvent(string line);
public void LineReceived(string line)
{
//What to do with the received line here
}
public FormPrincipal()
{
InitializeComponent();
cmbPortas.Items.AddRange(sp1.GetPortas());
cmbVelocidade.Items.AddRange(sp1.GetVelocidades());
}
}
}