-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathProgram.cs
487 lines (458 loc) · 19.9 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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
/*
K5TOOL UV-K5 toolkit utility
Copyright (C) 2024 qrp73
https://github.com/qrp73/K5TOOL
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.IO;
using System.Linq;
using K5TOOL.Packets;
namespace K5TOOL
{
class Program
{
static Program()
{
CommandLineParser.RegisterCommand("-hello", OnCommand_Hello, "",
"Check connection with the radio");
CommandLineParser.RegisterCommand("-reboot", OnCommand_Reboot, "",
"Reboot the radio");
CommandLineParser.RegisterCommand("-rdadc", OnCommand_RdAdc, "",
"Read battery status from the radio");
CommandLineParser.RegisterCommand("-rdrssi", OnCommand_RdRssi, "",
"Read RSSI from the radio");
CommandLineParser.RegisterCommand("-rdee", OnCommand_RdEe, "[<offset> <size>] [<fileName>]",
"Read EEPROM data from the radio (default fileName=eeprom-{offset}-{size}.raw)");
CommandLineParser.RegisterCommand("-wree", OnCommand_WrEe, "[<offset>] <fileName>",
"Write EEPROM data to the radio");
CommandLineParser.RegisterCommand("-wrflash", OnCommand_WrFlash, "<fileName>",
"Write flash from packed image (default format) to the radio. Needs to be run in flashing mode.");
CommandLineParser.RegisterCommand("-wrflashraw", OnCommand_WrFlashRaw, "[<version>] <fileName>",
"Write flash from unpacked image to the radio. Needs to be run in flashing mode.");
CommandLineParser.RegisterCommand("-unpack", OnCommand_Unpack, "<fileName> [<outputName>]",
"Unpack packed flash image to unpacked flash image (default outputName=fileName-{version}.raw)");
CommandLineParser.RegisterCommand("-pack", OnCommand_Pack, "<version> <fileName> [<outputName>]",
"Pack unpacked flash image to packed flash image (default outputName=fileName.bin)");
CommandLineParser.RegisterCommand("-parse", OnCommand_Parse, "<hex data>",
"Parse provided hex data and print details");
CommandLineParser.RegisterCommand("-parse-plain",OnCommand_ParsePlain, "<hex data>",
"Parse provided hex data as plain packet (without envelope) and print details");
CommandLineParser.RegisterCommand("-sniffer", OnCommand_Sniffer, "",
"Sniffer mode (listen for packets parse and print it to console)");
CommandLineParser.RegisterCommand("-test", OnCommand_Test, null);
CommandLineParser.RegisterCommand("-simula", OnCommand_Simula, null);
}
static int Main(string[] args)
{
try
{
var portName = CommandLineParser.GetPortName(ref args);
if (portName == string.Empty)
{
// port list requested
foreach (var name in System.IO.Ports.SerialPort.GetPortNames())
{
Console.WriteLine("{0}", name);
}
return 0;
}
if (portName == null)
{
var ports = System.IO.Ports.SerialPort.GetPortNames();
var isLinuxStyle = ports.Any(arg => arg.StartsWith("/dev/tty", StringComparison.InvariantCulture));
if (isLinuxStyle)
{
// Linux: prefer ttyUSB* device as default
ports = ports
.OrderBy(arg => arg.IndexOf("USB", StringComparison.InvariantCultureIgnoreCase) >= 0)
.ToArray();
}
portName = ports.LastOrDefault();
if (portName == null)
throw new FileNotFoundException("Cannot find serial port");
}
return CommandLineParser.Process(portName, ref args);
}
catch (Exception ex)
{
Logger.Error(ex);
return -2;
}
}
private static int OnCommand_Hello(string name, string[] v)
{
using (var device = new Device(name))
{
ProtocolBase.Hello(device);
Console.WriteLine("Done");
return 0;
}
}
private static int OnCommand_Reboot(string name, string[] v)
{
using (var device = new Device(name))
{
var protocol = ProtocolBase.Hello(device);
protocol.Reboot();
Console.WriteLine("Done");
return 0;
}
}
private static int OnCommand_RdAdc(string name, string[] v)
{
using (var device = new Device(name))
{
var protocol = ProtocolBase.Hello(device);
var adc = protocol.ReadAdc();
Console.WriteLine(" Voltage: {0}", adc.Voltage);
Console.WriteLine(" Current: {0}", adc.Current);
Console.WriteLine("Done");
return 0;
}
}
private static int OnCommand_RdRssi(string name, string[] v)
{
using (var device = new Device(name))
{
var protocol = ProtocolBase.Hello(device);
var rssi = protocol.ReadRssi();
Console.WriteLine(" RSSI: {0}", rssi.RSSI);
Console.WriteLine(" ExNoiseIndicator: {0}", rssi.ExNoiseIndicator);
Console.WriteLine(" GlitchIndicator: {0}", rssi.GlitchIndicator);
Console.WriteLine("Done");
return 0;
}
}
private static int OnCommand_Pack(string name, string[] args)
{
string version = null;
string inputFile = null;
string outputFile = null;
// <version> <fileName> [<outputName>]
switch(args.Length)
{
case 2:
version = args[0];
inputFile = args[1];
outputFile = string.Format("{0}.bin",
Path.GetFileNameWithoutExtension(inputFile));
break;
case 3:
version = args[0];
inputFile = args[1];
outputFile = args[2];
break;
default:
Console.WriteLine("ERROR: invalid arguments");
return -1;
}
Console.WriteLine("Read {0}...", inputFile);
var decoded = File.ReadAllBytes(inputFile);
Console.WriteLine(" Version: \"{0}\"", version);
var encoded = FirmwareHelper.Pack(decoded, version);
Console.WriteLine("Write {0}...", outputFile);
File.WriteAllBytes(outputFile, encoded);
Console.WriteLine("Done");
return 0;
}
private static int OnCommand_Unpack(string name, string[] args)
{
string inputFile = null;
string outputFile = null;
// <fileName> [<outputName>]
switch (args.Length)
{
case 1:
inputFile = args[0];
break;
case 2:
inputFile = args[0];
outputFile = args[1];
break;
default:
Console.WriteLine("ERROR: invalid arguments");
return -1;
}
Console.WriteLine("Read {0}...", inputFile);
var encoded = File.ReadAllBytes(inputFile);
string version;
var decoded = FirmwareHelper.Unpack(encoded, out version);
Console.WriteLine(" Version: \"{0}\"", version);
if (outputFile == null)
{
outputFile = string.Format("{0}-{1}.raw",
Path.GetFileNameWithoutExtension(inputFile),
version);
}
Console.WriteLine("Write {0}...", outputFile);
File.WriteAllBytes(outputFile, decoded);
Console.WriteLine("Done");
return 0;
}
private static int OnCommand_WrFlashRaw(string name, string[] args)
{
string version = null;
string fileName = null;
// [<version>] <fileName>
switch (args.Length)
{
case 1:
fileName = args[0];
break;
case 2:
version = args[0];
fileName = args[1];
break;
default:
Console.WriteLine("ERROR: invalid arguments");
return -1;
}
using (var device = new Device(name))
{
if (!CommandHelper.WriteFlashUnpacked(device, version, fileName))
return -2;
Console.WriteLine("Done");
return 0;
}
}
private static int OnCommand_WrFlash(string name, string[] args)
{
string fileName = null;
// <fileName>
switch (args.Length)
{
case 1:
fileName = args[0];
break;
default:
Console.WriteLine("ERROR: invalid arguments");
return -1;
}
using (var device = new Device(name))
{
if (!CommandHelper.WriteFlashPacked(device, fileName))
return -2;
Console.WriteLine("Done");
return 0;
}
}
private static int OnCommand_RdEe(string name, string[] args)
{
var offset = 0;
var size = 0x2000;
string fileName = null;
// [<offset> <size>] [<fileName>]
switch (args.Length)
{
case 0:
break;
case 1:
fileName = args[0];
break;
case 2:
offset = Utils.ParseNumber(args[0]);
size = Utils.ParseNumber(args[1]);
break;
case 3:
offset = Utils.ParseNumber(args[0]);
size = Utils.ParseNumber(args[1]);
fileName = args[2];
break;
default:
Console.WriteLine("ERROR: invalid arguments");
return -1;
}
if (fileName == null)
{
fileName = string.Format("eeprom-{0:x4}-{1:x4}.raw", offset, size);
}
using (var device = new Device(name))
{
var protocol = ProtocolBase.Hello(device);
if (!CommandHelper.ReadEeprom(protocol, offset, size, fileName))
return -2;
Console.WriteLine("Done");
return 0;
}
}
private static int OnCommand_WrEe(string name, string[] args)
{
var offset = 0;
string fileName = null;
// [<offset>] <fileName>
switch (args.Length)
{
case 1:
offset = 0;
fileName = args[0];
break;
case 2:
offset = Utils.ParseNumber(args[0]);
fileName = args[1];
break;
default:
Console.WriteLine("ERROR: invalid arguments");
return -1;
}
using (var device = new Device(name))
{
var protocol = ProtocolBase.Hello(device);
if (!CommandHelper.WriteEeprom(protocol, offset, fileName))
return -2;
Console.WriteLine("Done");
return 0;
}
}
private static int OnCommand_Parse(string name, string[] args)
{
Logger.IsPrintRaw = true;
Logger.IsPrintPlain = true;
Logger.IsPrintPacket = true;
var data = Utils.FromHex(string.Join(" ", args));
Console.WriteLine("{0} bytes", data.Length);
new Envelope(data).Deserialize();
Console.WriteLine("Done");
return 0;
}
private static int OnCommand_ParsePlain(string name, string[] args)
{
Logger.IsPrintRaw = true;
Logger.IsPrintPlain = true;
Logger.IsPrintPacket = true;
var data = Utils.FromHex(string.Join(" ", args));
Console.WriteLine("{0} bytes", data.Length);
Logger.LogRx(data);
var packet = Packet.Deserialize(data);
Logger.LogRxPacket(packet);
Console.WriteLine("Done");
return 0;
}
private static int OnCommand_Sniffer(string name, string[] v)
{
using (var device = new Device(name))
{
Console.Error.WriteLine("===SNIFFER MODE===");
for (; ; )
{
try
{
var packet = device.Recv();
Console.WriteLine("{0}", packet);
}
catch (TimeoutException)
{
}
catch (Exception ex)
{
Console.Error.WriteLine("[ERROR] {0}: {1}", ex.GetType().Name, ex.Message);
}
}
}
}
private static int OnCommand_Simula(string name, string[] v)
{
// bootloader simulator
Envelope.IsRadioEndpoint = true;
using (var device = new Device(name)) // "/dev/serial0"
{
//var protocol = ProtocolBase.CreateV2(device);
var protocol = ProtocolBase.CreateV5(device);
var isMute = false;
byte[] fwdata = null;
string fwvers = null;
var packetFlashBeacon = protocol.CreatePacketFlashBeaconAck();
for (; ; )
{
if (!isMute)
device.Send(packetFlashBeacon);
try
{
var packet = device.Recv();
//Console.WriteLine("recv {0}", packet);
var packetVer = packet as PacketFlashVersionReq;
if (packetVer != null)
{
fwvers = packetVer.Version;
Console.WriteLine("flashVersion: {0}", packetVer.Version);
continue;
//device.Send(packetFlashBeacon);
}
var packetWrite = packet as PacketFlashWriteReq;
if (packetWrite != null)
{
Console.WriteLine("flash chunkNumber=0x{0:x4}, size=0x{1:x4}, chunkCount=0x{2:x4}", packetWrite.ChunkNumber, packetWrite.Size, packetWrite.ChunkCount);
if (fwdata == null)
{
protocol.DecryptFlashInit();
fwdata = new byte[packetWrite.ChunkCount*0x100];
if (packetWrite.ChunkNumber != 0)
{
Console.WriteLine("WARN: started from chunkNumber=0x{0:x4}", packetWrite.ChunkNumber);
}
}
else if (fwdata.Length != packetWrite.ChunkCount*0x100)
{
Console.WriteLine("WARN: chunkCount unexpectedly changed 0x{0:x4} => 0x{1:x4}", fwdata.Length/0x100, packetWrite.ChunkCount);
var expectedSize = packetWrite.ChunkCount * 0x100;
if (fwdata.Length < expectedSize)
{
var buf = new byte[expectedSize];
Array.Copy(fwdata, buf, fwdata.Length);
fwdata = buf;
}
}
device.Send(protocol.CreatePacketFlashWriteAck(packetWrite.ChunkNumber, packetWrite.SequenceId));
//Array.Copy(packetWrite.Data, 0, fwdata, packetWrite.Offset, packetWrite.Size);
var page = new byte[0x100];
Array.Copy(packetWrite.RawData, 16, page, 0, Math.Min(page.Length, packetWrite.HdrSize - 12));
protocol.DecryptFlashProcess(page, 0, fwdata, packetWrite.ChunkNumber * 0x100, packetWrite.HdrSize - 12);
// detect flashing complete event
if (packetWrite.ChunkNumber == packetWrite.ChunkCount-1)
{
protocol.DecryptFlashFinish();
var shrink = 0x100 - packetWrite.Size;
//var shrink = 0;
var buf = new byte[fwdata.Length - shrink];
Array.Copy(fwdata, buf, buf.Length);
fwdata = buf;
var fileName = string.Format("firmware-{0}.raw", fwvers);
Console.WriteLine("Write {0}", fileName);
File.WriteAllBytes(fileName, fwdata);
fwdata = null;
return 0;
}
}
isMute = true;
}
catch (TimeoutException)
{
}
}
}
}
private static int OnCommand_Test(string name, string[] args)
{
Logger.IsPrintRaw = true;
Logger.IsPrintPlain = true;
Logger.IsPrintPacket = true;
new Envelope(new PacketHelloReq(Utils.ToUnixTimeSeconds(DateTime.UtcNow))).Serialize();
//new Envelope(new PacketReqRdEEPROM(0x0080, 0x80)).Serialize();
//new Envelope(new PacketReqWrEEPROM(0xaabb, new byte[0x80])).Serialize();
//new Envelope(new PacketReqBatteryInfo()).Serialize();
//new Envelope(new PacketWriteFlashReq(0x1111, 0x0022, new byte[0x100])).Serialize();
//new Envelope(new PacketFlashVersionReq()).Serialize();
Console.WriteLine("Done");
return 0;
}
}
}