-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
227 lines (185 loc) · 7.55 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
using CommandLine;
using Microsoft.Extensions.Configuration;
using Serilog;
using Serilog.Core;
using Serilog.Events;
using Denon.Serial.Test;
using System.Reflection;
using SerialPortLib;
using System.Text;
using System.Timers;
using System.Threading;
CommandLine.Parser.Default.ParseArguments<OptionsMutuallyExclusive>(args)
.WithParsed(RunProcess)
.WithNotParsed(HandleParseError);
static void RunProcess(OptionsMutuallyExclusive opts)
{
int exitCode = 0;
System.Timers.Timer responseWaitTimer;
// Get default App Configuration
var appConfig = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", true)
.Build();
// Setup Logging
var loggerLevelSwitch = new LoggingLevelSwitch();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(appConfig)
.MinimumLevel.ControlledBy(loggerLevelSwitch)
.CreateLogger();
var serialPort = new SerialPortInput();
try
{
String inputCommand;
StringBuilder responseCache = new();
Boolean comPortConnected = false;
Boolean responseReady = false;
Boolean responsReturned = false;
Boolean inCommandResponseCapture = false;
// Message header
if (!opts.Quiet) Console.WriteLine($"Denon.Serial.Test {Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion}");
// Setup serial port
serialPort.ConnectionStatusChanged += delegate (object sender, ConnectionStatusChangedEventArgs args)
{
comPortConnected = args.Connected;
//Console.Write("\b\b\b\b\b\b\b\b\bChatter: {0}\nConnection: ", args.Connected);
};
serialPort.MessageReceived += delegate (object sender, MessageReceivedEventArgs args)
{
responsReturned = true;
String response = Encoding.UTF8.GetString(args.Data, 0, args.Data.Length);
if (!opts.Quiet)
{
response = response.Replace("\r", "\\r");
response = response.Replace("\n", "\\n");
}
if (inCommandResponseCapture)
{
if (opts.HexDisplay && !opts.Quiet)
{
Console.WriteLine($"Recieving: {BitConverter.ToString(System.Text.Encoding.UTF8.GetBytes(response))}");
}
responseCache.Append(response);
}
else
{
if (!opts.Quiet) Console.Write("\b\b\b\b\b\b\b\b\bChatter: {0}\nCommand: ", response);
}
};
// Set port options
serialPort.SetPort(opts.ComPortName, opts.ComSpeed, GetStopBits(opts), GetParity(opts), GetDataBits(opts));
// Connect the serial port
serialPort.Connect();
if (!opts.Quiet)
{
if (comPortConnected)
{
Console.WriteLine("Serial port is connected");
Console.WriteLine("Type Denon Commands Like 'PW?', 'ZM?', 'MV?', or 'q' to quit");
}
else
{
Console.WriteLine($"Serial port failed to connect with port=[{opts.ComPortName}], speed=[{opts.ComSpeed}], stop bits=[{opts.StopBits}], parity=[{opts.Parity}], data bits=[{opts.DataBits}]");
}
}
// Read and process commands
while (true)
{
// Run a command supplied to read commands interactively
if (!String.IsNullOrEmpty(opts.Command))
{
inputCommand = opts.Command;
}
else
{
// Get input
Console.Write("Command: ");
inputCommand = Console.ReadLine();
if (inputCommand == "q") { break; }
}
// Send command to serial port, wait for response
var message = System.Text.Encoding.UTF8.GetBytes($"{inputCommand}\r");
responseReady = false;
responsReturned = false;
inCommandResponseCapture = true;
if (opts.HexDisplay && !opts.Quiet) Console.WriteLine($"Sending: {BitConverter.ToString(message)}");
serialPort.SendMessage(message);
// Set response timer
responseWaitTimer = new System.Timers.Timer(opts.ResponseWaitTime);
responseWaitTimer.Elapsed += delegate (Object source, ElapsedEventArgs e)
{
responseReady = true;
};
responseWaitTimer.AutoReset = false;
responseWaitTimer.Enabled = true;
int timeout = 100;
//int currentTimeout = 0;
while (responseReady == false)
{
Thread.Sleep(timeout);
}
if (responsReturned)
{
if (!opts.Quiet)
{
Console.WriteLine("Response: {0}", responseCache.ToString());
}
else
{
Console.Write(responseCache.ToString());
}
}
else
{
if (!opts.Quiet) Console.WriteLine("Timeout: Command did not respond within the Response Wait Time.");
}
inCommandResponseCapture = false;
responseCache.Clear();
if (!String.IsNullOrEmpty(opts.Command)) break; // exit if a command was supplied.
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
finally
{
if (serialPort.IsConnected) serialPort.Disconnect();
Log.CloseAndFlush();
exitCode = exitCode + 1;
}
}
static void HandleParseError(IEnumerable<Error> errs)
{
Log.CloseAndFlush();
Environment.Exit(-1);
}
static System.IO.Ports.StopBits GetStopBits(OptionsMutuallyExclusive opts)
{
System.IO.Ports.StopBits returnValue = System.IO.Ports.StopBits.One;
if (opts.StopBits == 0) returnValue = System.IO.Ports.StopBits.None;
if (opts.StopBits == 1) returnValue = System.IO.Ports.StopBits.One;
if (opts.StopBits == 1.5) returnValue = System.IO.Ports.StopBits.OnePointFive;
if (opts.StopBits == 2) returnValue = System.IO.Ports.StopBits.Two;
return returnValue;
}
static System.IO.Ports.Parity GetParity(OptionsMutuallyExclusive opts)
{
System.IO.Ports.Parity returnValue = System.IO.Ports.Parity.None;
if (opts.Parity.ToLower().Equals("none")) returnValue = System.IO.Ports.Parity.None;
if (opts.Parity.ToLower().Equals("mark")) returnValue = System.IO.Ports.Parity.Mark;
if (opts.Parity.ToLower().Equals("odd")) returnValue = System.IO.Ports.Parity.Odd;
if (opts.Parity.ToLower().Equals("even")) returnValue = System.IO.Ports.Parity.Even;
if (opts.Parity.ToLower().Equals("space")) returnValue = System.IO.Ports.Parity.Space;
return returnValue;
}
static DataBits GetDataBits(OptionsMutuallyExclusive opts)
{
DataBits returnValue = DataBits.Eight;
if (opts.DataBits == 5) returnValue = DataBits.Five;
if (opts.DataBits == 6) returnValue = DataBits.Six;
if (opts.DataBits == 7) returnValue = DataBits.Seven;
if (opts.DataBits == 8) returnValue = DataBits.Eight;
return returnValue;
}