132 lines
3.6 KiB
C#
132 lines
3.6 KiB
C#
using SerialComms;
|
|
using System;
|
|
using System.IO.Ports;
|
|
using System.Windows.Forms;
|
|
|
|
namespace Serial_Comms_CS
|
|
{
|
|
|
|
|
|
public partial class MainForm : Form
|
|
{
|
|
|
|
SerialConnector serialConnector = new SerialConnector();
|
|
|
|
void handleCalInt(string args)
|
|
{
|
|
Console.WriteLine("Callback CAL-INT called");
|
|
Console.WriteLine("Arguments: " + args);
|
|
}
|
|
|
|
void handleRead(string args)
|
|
{
|
|
Console.WriteLine("Callback READ called");
|
|
Console.WriteLine("Arguments: " + args);
|
|
}
|
|
|
|
public MainForm()
|
|
{
|
|
InitializeComponent();
|
|
|
|
// Determine which serial ports are available
|
|
string[] ports = SerialPort.GetPortNames();
|
|
|
|
if (ports.Length <= 0)
|
|
{
|
|
MessageBox.Show(
|
|
"Unable to find any COM ports",
|
|
"No COM ports",
|
|
MessageBoxButtons.OK,
|
|
MessageBoxIcon.Error
|
|
);
|
|
}
|
|
|
|
// Add the serial ports to the combobox
|
|
foreach (string port in ports)
|
|
{
|
|
serialPortBox.Items.Add(port);
|
|
}
|
|
|
|
try
|
|
{
|
|
serialConnector.OnCommand("CAL-NXT", (string args) => Console.WriteLine(args));
|
|
serialConnector.OnCommand("CAL-INT", handleCalInt);
|
|
serialConnector.OnCommand("READ", handleRead);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
MessageBox.Show(
|
|
ex.Message,
|
|
"Failed to register command",
|
|
MessageBoxButtons.OK,
|
|
MessageBoxIcon.Error
|
|
);
|
|
}
|
|
}
|
|
|
|
private void serialPortBox_SelectedIndexChanged(object sender, EventArgs e)
|
|
{
|
|
string selectedPort = serialPortBox.Text;
|
|
try
|
|
{
|
|
serialConnector.SetSerialPort(selectedPort);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
MessageBox.Show(
|
|
"Unable to set selected COM port\n" + ex.Message,
|
|
"Unable to open COM port",
|
|
MessageBoxButtons.OK,
|
|
MessageBoxIcon.Error
|
|
);
|
|
}
|
|
serialTimer.Enabled = true;
|
|
}
|
|
|
|
private void serialTimer_Tick(object sender, EventArgs e)
|
|
{
|
|
try
|
|
{
|
|
serialConnector.Cycle();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
MessageBox.Show(
|
|
"Encountered an error while parsing commands\n" + ex.Message,
|
|
"Command parse error",
|
|
MessageBoxButtons.OK,
|
|
MessageBoxIcon.Error
|
|
);
|
|
}
|
|
}
|
|
|
|
private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
|
|
{
|
|
serialConnector.CloseSerial();
|
|
}
|
|
|
|
private void sendBtn_Click(object sender, EventArgs e)
|
|
{
|
|
serialConnector.SendCommand("CAL-INT", "3");
|
|
}
|
|
|
|
private void reconnectBtn_Click(object sender, EventArgs e)
|
|
{
|
|
string selectedPort = serialPortBox.Text;
|
|
try
|
|
{
|
|
serialConnector.SetSerialPort(selectedPort);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
MessageBox.Show(
|
|
"Unable to set selected COM port\n" + ex.Message,
|
|
"Unable to open COM port",
|
|
MessageBoxButtons.OK,
|
|
MessageBoxIcon.Error
|
|
);
|
|
}
|
|
}
|
|
}
|
|
}
|