This repository has been archived by the owner on Oct 20, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathSerialPortCtrl.cs
110 lines (97 loc) · 2.37 KB
/
SerialPortCtrl.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
/*
* Author: Pawel Walczak (pewusoft)
* Date: 2015-01-12 20:50
*
*/
using System;
using System.IO.Ports;
using System.IO;
using System.Windows.Forms;
namespace SDRSharp.SerialController
{
public class SerialPortCtrl
{
public bool IsOpen {
get { return _port != null && _port.IsOpen; }
}
SerialPort _port;
ProtocolInterface _protocol;
string _received;
public SerialPortCtrl(ProtocolInterface protocol)
{
_protocol = protocol;
_received = "";
}
public static string[] GetAllPorts()
{
try {
return SerialPort.GetPortNames();
}
catch (Exception e) {
MessageBox.Show("Couldn't read port list:\n"+e.ToString(), "SerialController", MessageBoxButtons.OK, MessageBoxIcon.Error);
return new string[0];
}
}
public bool openPort(string portName)
{
try {
if (_port != null && _port.IsOpen)
return false;
if (portName == null || (portName.Trim().Equals("")))
return false;
_port = new SerialPort(portName, 9600, Parity.None, 8, StopBits.One);
_port.DataReceived += new SerialDataReceivedEventHandler( DataReceivedHandler );
if (_port != null) {
_port.Open();
return true;
}
return false;
}
catch (Exception e) {
MessageBox.Show("Couldn't open port "+portName+":\n"+e.ToString(), "SerialController",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
public bool closePort()
{
if (_port != null) {
if (_port.IsOpen) {
try {
_port.Close();
return true;
}
catch (IOException) {
return false;
}
}
else {
return false;
}
}
return false;
}
void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
while (_port.BytesToRead > 0) {
if (_received.Length > _protocol.MaxLen)
_received = "";
string input = ((char)_port.ReadChar()).ToString();
if (input == _protocol.EndMarker) {
string response = _protocol.PktReceiver(_received);
if (! string.IsNullOrEmpty(response)) {
DataTransmit(response);
}
_received = "";
}
else {
_received += input;
}
}
}
public void DataTransmit(string data)
{
_port.Write(data);
}
}
}