-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
254 lines (211 loc) · 9.39 KB
/
Program.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
using System;
using System.CommandLine;
using System.CommandLine.Invocation;
using System.IO.Ports;
using System.Linq;
namespace DotCOM
{
public class Program
{
private static int[] SUPPORTED_BAUD = { 4800, 9600, 19200, 38400, 57600, 115200 };
private const int DEFAULT_BAUD = 115200;
private const string DEFAULT_CONFIG = "8N1";
private const string DEFAULT_LINE_ENDING = "NONE";
private static SerialPort serialPort;
private static int Main(string[] args)
{
var rootCommand = new RootCommand("A serial port cli for windows");
// Options
var portOption = new Option<string>("--port", "Device portname (e.g. com12)");
portOption.AddAlias("--device");
portOption.AddAlias("-d");
portOption.Argument.Arity = ArgumentArity.ExactlyOne;
portOption.IsRequired = true;
var baudOption = new Option<int>("--baudrate", "Communication baudrate");
baudOption.AddAlias("-b");
baudOption.Argument.SetDefaultValue(DEFAULT_BAUD);
baudOption.Argument.Arity = ArgumentArity.ExactlyOne;
var paramsOption = new Option<string>("--params", "Communications parameters");
paramsOption.AddAlias("-p");
paramsOption.Argument.SetDefaultValue(DEFAULT_CONFIG);
paramsOption.Argument.Arity = ArgumentArity.ExactlyOne;
var lineEndingOption = new Option<string>("--line-end", "Appends a line-ending symbol at the end (valid values: LF, CRLF)");
lineEndingOption.AddAlias("-l");
lineEndingOption.Argument.SetDefaultValue(DEFAULT_LINE_ENDING);
lineEndingOption.Argument.Arity = ArgumentArity.ExactlyOne;
var echoOption = new Option<bool>("--echo", "Echoes back the message");
echoOption.AddAlias("-e");
echoOption.Argument.SetDefaultValue(true);
echoOption.Argument.Arity = ArgumentArity.ExactlyOne;
// Send single command
var singleCommand = new Command("single", "Sends a single message to the specified port");
singleCommand.AddAlias("send");
singleCommand.AddAlias("send-string");
singleCommand.AddArgument(new Argument<string>("message", "The message to be sent to the device"));
singleCommand.AddOption(portOption);
singleCommand.AddOption(baudOption);
singleCommand.AddOption(paramsOption);
singleCommand.AddOption(lineEndingOption);
singleCommand.Handler = CommandHandler.Create<string, string, int, string, string>((message, port, baudrate, @params, lineEnd) => {
Console.WriteLine($"{baudrate}|{port}|{@params}");
Console.WriteLine($"message = {message}");
if (!SetupPort(baudrate, port, @params))
{
ConsoleUtils.Print(ConsoleColor.Yellow, "Aborted command due to error");
return;
}
SendOnce(message, lineEnd);
});
// Send bytes command
var sendBytesCommand = new Command("send-bytes", "Sends one or more byte values to the specified port");
sendBytesCommand.AddArgument(new Argument<byte[]>("bytes", "The bytes to be sent to the device. Supports both decimal and hex values"));
sendBytesCommand.AddOption(portOption);
sendBytesCommand.AddOption(baudOption);
sendBytesCommand.AddOption(paramsOption);
sendBytesCommand.Handler = CommandHandler.Create<byte[], string, int, string>((bytes, port, baudrate, @params) => {
if (!SetupPort(baudrate, port, @params))
{
ConsoleUtils.Print(ConsoleColor.Yellow, "Aborted command due to error");
return;
}
SendBytes(bytes);
});
var listCommand = new Command("list", "Lists the available serial ports");
listCommand.Handler = CommandHandler.Create(ListSerialPorts);
var openCommand = new Command("open", "Open serial communication with the specified port");
openCommand.AddOption(portOption);
openCommand.AddOption(baudOption);
openCommand.AddOption(paramsOption);
openCommand.AddOption(lineEndingOption);
openCommand.AddOption(echoOption);
openCommand.Handler = CommandHandler.Create<string, int, string, string, bool>((port, baudrate, @params, lineEnd, echo) => {
if (!SetupPort(baudrate, port, @params))
{
ConsoleUtils.Print(ConsoleColor.Yellow, "Aborted command due to error");
return;
}
OpenTerminal(lineEnd, echo);
});
rootCommand.AddCommand(singleCommand);
rootCommand.AddCommand(sendBytesCommand);
rootCommand.AddCommand(listCommand);
rootCommand.AddCommand(openCommand);
return rootCommand.InvokeAsync(args).Result;
}
private static void ListSerialPorts()
{
int portCount = SerialPort.GetPortNames().Length;
if (portCount < 1)
{
ConsoleUtils.Error("No available ports");
return;
}
Console.WriteLine($"Found {portCount} available ports:");
foreach (string s in SerialPort.GetPortNames())
{
Console.WriteLine($"* {s}");
}
}
private static bool SetupPort(int baudrate, string port, string @params)
{
serialPort = new SerialPort();
// Check port name
if (!SerialPort.GetPortNames().Contains(port.ToUpper()))
{
ConsoleUtils.Error($"Could not find any COM port with name {port}", "Use [list] command to get a list of available ports");
return false;
}
serialPort.PortName = port;
// Check baud rate
if (!SUPPORTED_BAUD.Contains(baudrate))
{
ConsoleUtils.Error($"The provided baudrate is not supported (received {baudrate})");
return false;
}
serialPort.BaudRate = baudrate;
// Parse params
@params = @params.ToUpper();
int dataBits;
Parity parityBit;
StopBits stopBits;
if (!Int32.TryParse(@params[0] + "", out dataBits))
{
ConsoleUtils.Error($"Invalid value for data bits (received {@params[0]})");
return false;
}
if ((dataBits < 5) || (dataBits > 9))
{
ConsoleUtils.Error("Data bits out of range (valid range: [5 .. 9])");
return false;
}
switch (@params[1])
{
case 'E': parityBit = Parity.Even; break;
case 'M': parityBit = Parity.Mark; break;
case 'N': parityBit = Parity.None; break;
case 'O': parityBit = Parity.Odd; break;
case 'S': parityBit = Parity.Space; break;
default:
ConsoleUtils.Error($"Invalid parity parameter (received {@params[1]})");
return false;
}
switch (@params[2])
{
case '1': stopBits = StopBits.One; break;
case '2': stopBits = StopBits.Two; break;
default:
ConsoleUtils.Error($"Invalid stop bits parameter (received {@params[2]})");
return false;
}
serialPort.DataBits = dataBits;
serialPort.Parity = parityBit;
serialPort.StopBits = stopBits;
return true;
}
private static void SendOnce(string message, string lineEnd)
{
try
{
switch (ConsoleUtils.ParseLineEnding(lineEnd))
{
case LineEnd.CRLF: message += "\r\n"; break;
case LineEnd.LF: message += "\n"; break;
}
}
catch (ArgumentException e)
{
ConsoleUtils.Error(e.Message);
ConsoleUtils.Print(ConsoleColor.Yellow, "Skipping line-ending symbol");
}
serialPort.Open();
serialPort.Write(message);
serialPort.Close();
}
private static void SendBytes(byte[] bytes)
{
if (bytes == null)
{
ConsoleUtils.Error("bytes value cannot be null");
return;
}
serialPort.Open();
serialPort.Write(bytes, 0, bytes.Length);
serialPort.Close();
}
private static void OpenTerminal(string lineEnd, bool echo = true)
{
var lineEndValue = LineEnd.NONE;
try
{
lineEndValue = ConsoleUtils.ParseLineEnding(lineEnd);
}
catch (ArgumentException e)
{
ConsoleUtils.Error(e.Message);
ConsoleUtils.Print(ConsoleColor.Yellow, "Skipping line-ending symbol");
}
var serialTerminal = new SerialTerminal(ref serialPort, lineEndValue, echo);
serialTerminal.Init("Welcome to DotCOM. Press <ESC> to exit");
}
}
}