Wednesday, 4 September 2013

External class handler interacting with UI

External class handler interacting with UI

I am currently working on a class that will communicate with an external
device through the SerialPort class, but I need to update the UI according
to the messages the device send back.
I tried the following code but it does not work:
using System.IO.Ports;
namespace LearningSteps
{
/// <summary>
/// Interaction logic for Comm.xaml
/// </summary>
///
public class Teste
{
private SerialPort _myPort;
public Teste(SerialPort P) { _myPort = P; }
public void Funcao(SerialDataReceivedEventHandler H)
{
_myPort.DataReceived += H;
byte[] vetor = new byte[] { 0x24, 0x24, 0xCF, 0x00, 0x01,
0x02, 0x25, 0x33, 0x7E };
_myPort.Write(vetor, 0, 9);
}
}
public partial class Comm : Window
{
SerialPort port;
Teste T;
public delegate void AtualizaCallBack(string message);
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
public Comm()
{
InitializeComponent();
port = new SerialPort("COM5",115200,Parity.None,8,StopBits.One);
port.RtsEnable = false;
port.DtrEnable = false;
port.Handshake = Handshake.None;
port.NewLine = "~";
port.Open();
T = new Teste(port);
}
private void Recebido(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
String indata = sp.ReadExisting();
my_label.Dispatcher.Invoke(new
AtualizaCallBack(this.atualiza),new object[]{indata});
}
private void bt_Click(object sender, RoutedEventArgs e)
{
T.Funcao(Recebido);
}
private void atualiza(string s)
{
byte[] vet = encoding.GetBytes(s);
my_label.Content = BitConverter.ToString(vet);
}
}
}
I get an error when I try to compile, which I think is because I'm trying
to send an internal SerialDataReceivedEventHandler as argument. But I
don't know how I could use T.Funcao and update my UI otherwise.
Can somebody help me please?

No comments:

Post a Comment