-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
KW1281Dialog.cs
896 lines (765 loc) · 28.7 KB
/
KW1281Dialog.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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
using BitFab.KW1281Test.Blocks;
using BitFab.KW1281Test.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace BitFab.KW1281Test
{
/// <summary>
/// Manages a dialog with a VW controller using the KW1281 protocol.
/// </summary>
internal interface IKW1281Dialog
{
ControllerInfo Connect();
void EndCommunication();
void SetDisconnected();
void Login(ushort code, int workshopCode);
List<ControllerIdent> ReadIdent();
/// <summary>
/// Corresponds to VDS-Pro function 19
/// </summary>
List<byte>? ReadEeprom(ushort address, byte count);
bool WriteEeprom(ushort address, List<byte> values);
/// <summary>
/// Corresponds to VDS-Pro functions 21 and 22
/// </summary>
List<byte> ReadRomEeprom(ushort address, byte count);
/// <summary>
/// Corresponds to VDS-Pro functions 20 and 25
/// </summary>
List<byte>? ReadRam(ushort address, byte count);
bool AdaptationRead(byte channelNumber);
bool AdaptationTest(byte channelNumber, ushort channelValue);
bool AdaptationSave(byte channelNumber, ushort channelValue, int workshopCode);
void SendBlock(List<byte> blockBytes);
List<Block> ReceiveBlocks();
List<byte>? ReadCcmRom(byte seg, byte msb, byte lsb, byte count);
/// <summary>
/// Keep the dialog alive by sending an ACK and receiving a response.
/// </summary>
void KeepAlive();
ActuatorTestResponseBlock? ActuatorTest(byte value);
List<FaultCode>? ReadFaultCodes();
/// <summary>
/// Clear all of the controllers fault codes.
/// </summary>
/// <param name="controllerAddress"></param>
/// <returns>Any remaining fault codes.</returns>
List<FaultCode>? ClearFaultCodes(int controllerAddress);
/// <summary>
/// Set the controller's software coding and workshop code.
/// </summary>
/// <param name="controllerAddress"></param>
/// <param name="softwareCoding"></param>
/// <param name="workshopCode"></param>
/// <returns>True if successful.</returns>
bool SetSoftwareCoding(int controllerAddress, int softwareCoding, int workshopCode);
bool GroupRead(byte groupNumber, bool useBasicSetting = false);
public IKwpCommon KwpCommon { get; }
Block ReceiveBlock();
}
internal class KW1281Dialog : IKW1281Dialog
{
public ControllerInfo Connect()
{
_isConnected = true;
var blocks = ReceiveBlocks();
return new ControllerInfo(blocks.Where(b => !b.IsAckNak));
}
public void Login(ushort code, int workshopCode)
{
Log.WriteLine("Sending Login block");
SendBlock(new List<byte>
{
(byte)BlockTitle.Login,
(byte)(code >> 8),
(byte)(code & 0xFF),
(byte)(workshopCode >> 16),
(byte)((workshopCode >> 8) & 0xFF),
(byte)(workshopCode & 0xFF)
});
_ = ReceiveBlocks();
}
public List<ControllerIdent> ReadIdent()
{
var idents = new List<ControllerIdent>();
bool moreAvailable;
do
{
Log.WriteLine("Sending ReadIdent block");
SendBlock(new List<byte> { (byte)BlockTitle.ReadIdent });
var blocks = ReceiveBlocks();
var ident = new ControllerIdent(blocks.Where(b => !b.IsAckNak));
idents.Add(ident);
moreAvailable = blocks
.OfType<AsciiDataBlock>()
.Any(b => b.MoreDataAvailable);
} while (moreAvailable);
return idents;
}
/// <summary>
/// Reads a range of bytes from the EEPROM.
/// </summary>
/// <param name="address"></param>
/// <param name="count"></param>
/// <returns>The bytes or null if the bytes could not be read</returns>
public List<byte>? ReadEeprom(ushort address, byte count)
{
Log.WriteLine($"Sending ReadEeprom block (Address: ${address:X4}, Count: ${count:X2})");
SendBlock(new List<byte>
{
(byte)BlockTitle.ReadEeprom,
count,
(byte)(address >> 8),
(byte)(address & 0xFF)
});
var blocks = ReceiveBlocks();
if (blocks.Count == 1 && blocks[0] is NakBlock)
{
// Permissions issue
return null;
}
blocks = blocks.Where(b => !b.IsAckNak).ToList();
if (blocks.Count != 1)
{
throw new InvalidOperationException($"ReadEeprom returned {blocks.Count} blocks instead of 1");
}
return blocks[0].Body.ToList();
}
/// <summary>
/// Reads a range of bytes from the RAM.
/// </summary>
/// <param name="address"></param>
/// <param name="count"></param>
/// <returns>The bytes or null if the bytes could not be read</returns>
public List<byte>? ReadRam(ushort address, byte count)
{
Log.WriteLine($"Sending ReadRam block (Address: ${address:X4}, Count: ${count:X2})");
SendBlock(new List<byte>
{
(byte)BlockTitle.ReadRam,
count,
(byte)(address >> 8),
(byte)(address & 0xFF)
});
var blocks = ReceiveBlocks();
if (blocks.Count == 1 && blocks[0] is NakBlock)
{
// Permissions issue
return null;
}
blocks = blocks.Where(b => !b.IsAckNak).ToList();
if (blocks.Count != 1)
{
throw new InvalidOperationException($"ReadEeprom returned {blocks.Count} blocks instead of 1");
}
return blocks[0].Body.ToList();
}
/// <summary>
/// Reads a range of bytes from the CCM ROM.
/// </summary>
/// <param name="seg">0-15</param>
/// <param name="msb">0-15</param>
/// <param name="lsb">0-255</param>
/// <param name="count">8(-12?)</param>
/// <returns>The bytes or null if the bytes could not be read</returns>
public List<byte>? ReadCcmRom(byte seg, byte msb, byte lsb, byte count)
{
Log.WriteLine(
$"Sending ReadEeprom block (Address: ${seg:X2}{msb:X2}{lsb:X2}, Count: ${count:X2})");
var block = new List<byte>
{
(byte)BlockTitle.ReadEeprom,
count,
msb,
lsb,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
(byte)(seg << 4)
};
Log.WriteLine($"SEND {Utils.Dump(block)}");
SendBlock(block);
var blocks = ReceiveBlocks();
#if true
foreach (var b in blocks)
{
Log.WriteLine($"Received:{Utils.Dump(b.Bytes)}");
}
#endif
if (blocks.Count == 1 && blocks[0] is NakBlock)
{
// Log.WriteLine($"RECV {Utils.Dump(blocks.First().Bytes)}");
// Permissions issue
return null;
}
blocks = blocks.Where(b => !b.IsAckNak).ToList();
if (blocks.Count != 1)
{
throw new InvalidOperationException($"ReadEeprom returned {blocks.Count} blocks instead of 1");
}
return blocks[0].Body.ToList();
}
public bool WriteEeprom(ushort address, List<byte> values)
{
Log.WriteLine($"Sending WriteEeprom block (Address: ${address:X4}, Values: {Utils.DumpBytes(values)}");
byte count = (byte)values.Count;
var sendBody = new List<byte>
{
(byte)BlockTitle.WriteEeprom,
count,
(byte)(address >> 8),
(byte)(address & 0xFF),
};
sendBody.AddRange(values);
SendBlock(sendBody.ToList());
var blocks = ReceiveBlocks();
if (blocks.Count == 1 && blocks[0] is NakBlock)
{
// Permissions issue
Log.WriteLine("WriteEeprom failed");
return false;
}
blocks = blocks.Where(b => !b.IsAckNak).ToList();
if (blocks.Count != 1)
{
Log.WriteLine($"WriteEeprom returned {blocks.Count} blocks instead of 1");
return false;
}
var block = blocks[0];
if (block is not WriteEepromResponseBlock)
{
Log.WriteLine($"Expected WriteEepromResponseBlock but got {block.GetType()}");
return false;
}
if (!Enumerable.SequenceEqual(block.Body, sendBody.Skip(1).Take(4)))
{
Log.WriteLine("WriteEepromResponseBlock body does not match WriteEepromBlock");
return false;
}
return true;
}
public List<byte> ReadRomEeprom(ushort address, byte count)
{
Log.WriteLine($"Sending ReadRomEeprom block (Address: ${address:X4}, Count: ${count:X2})");
SendBlock(new List<byte>
{
(byte)BlockTitle.ReadRomEeprom,
count,
(byte)(address >> 8),
(byte)(address & 0xFF)
});
var blocks = ReceiveBlocks();
if (blocks.Count == 1 && blocks[0] is NakBlock)
{
return new List<byte>();
}
blocks = blocks.Where(b => !b.IsAckNak).ToList();
if (blocks.Count != 1)
{
throw new InvalidOperationException($"ReadRomEeprom returned {blocks.Count} blocks instead of 1");
}
return blocks[0].Body.ToList();
}
public void EndCommunication()
{
if (_isConnected)
{
Log.WriteLine("Sending EndCommunication block");
SendBlock(new List<byte> { (byte)BlockTitle.End });
_isConnected = false;
}
}
public void SetDisconnected()
{
_isConnected = false;
_blockCounter = null;
}
public void SendBlock(List<byte> blockBytes)
{
var blockLength = (byte)(blockBytes.Count + 2);
blockBytes.Insert(0, _blockCounter!.Value);
_blockCounter++;
blockBytes.Insert(0, blockLength);
Thread.Sleep(TimeInterval.R6);
foreach (var b in blockBytes)
{
WriteByteAndReadAck(b);
Thread.Sleep(TimeInterval.R6);
}
KwpCommon.WriteByte(0x03); // Block end, does not get ACK'd
}
public List<Block> ReceiveBlocks()
{
var blocks = new List<Block>();
try
{
while (true)
{
var block = ReceiveBlock();
blocks.Add(block); // TODO: Maybe don't add the block if it's an Ack
if (block is AckBlock || block is NakBlock)
{
break;
}
SendAckBlock();
}
}
catch (Exception ex)
{
Log.WriteLine($"Error receiving blocks: {ex.Message}");
if (blocks.Count > 0)
{
Log.WriteLine("Blocks received:");
foreach (var block in blocks)
{
Log.WriteLine($"Block: {Utils.DumpBytes(block.Bytes)}");
}
}
throw;
}
return blocks;
}
private void WriteByteAndReadAck(byte b)
{
KwpCommon.WriteByte(b);
KwpCommon.ReadComplement(b);
}
public Block ReceiveBlock()
{
var blockBytes = new List<byte>();
try
{
var blockLength = ReadAndAckByte();
blockBytes.Add(blockLength);
var blockCounter = ReadBlockCounter();
blockBytes.Add(blockCounter);
var blockTitle = ReadAndAckByte();
blockBytes.Add(blockTitle);
for (var i = 0; i < blockLength - 3; i++)
{
var b = ReadAndAckByte();
blockBytes.Add(b);
}
var blockEnd = KwpCommon.ReadByte();
blockBytes.Add(blockEnd);
if (blockEnd != 0x03)
{
throw new InvalidOperationException(
$"Received block end ${blockEnd:X2} but expected $03. Block bytes: {Utils.Dump(blockBytes)}");
}
return (BlockTitle)blockTitle switch
{
BlockTitle.ACK => new AckBlock(blockBytes),
BlockTitle.GroupReadResponseWithText => new GroupReadResponseWithTextBlock(blockBytes),
BlockTitle.ActuatorTestResponse => new ActuatorTestResponseBlock(blockBytes),
BlockTitle.AsciiData =>
blockBytes[3] == 0x00 ? new CodingWscBlock(blockBytes) : new AsciiDataBlock(blockBytes),
BlockTitle.Custom => new CustomBlock(blockBytes),
BlockTitle.NAK => new NakBlock(blockBytes),
BlockTitle.ReadEepromResponse => new ReadEepromResponseBlock(blockBytes),
BlockTitle.FaultCodesResponse => new FaultCodesBlock(blockBytes),
BlockTitle.ReadRomEepromResponse => new ReadRomEepromResponse(blockBytes),
BlockTitle.WriteEepromResponse => new WriteEepromResponseBlock(blockBytes),
BlockTitle.AdaptationResponse => new AdaptationResponseBlock(blockBytes),
BlockTitle.GroupReadResponse => new GroupReadResponseBlock(blockBytes),
BlockTitle.RawDataReadResponse => new RawDataReadResponseBlock(blockBytes),
BlockTitle.SecurityAccessMode2 => new SecurityAccessMode2Block(blockBytes),
_ => new UnknownBlock(blockBytes),
};
}
catch (Exception ex)
{
Log.WriteLine($"Error receiving block: {ex.Message}");
Log.WriteLine($"Partial block: {Utils.DumpBytes(blockBytes)}");
if (ex is TimeoutException)
{
Log.WriteLine($"Read timeout: {KwpCommon.Interface.ReadTimeout}");
Log.WriteLine($"Write timeout: {KwpCommon.Interface.WriteTimeout}");
}
throw;
}
}
private void SendAckBlock()
{
var blockBytes = new List<byte> { (byte)BlockTitle.ACK };
SendBlock(blockBytes);
}
private byte ReadBlockCounter()
{
var blockCounter = ReadAndAckByte();
if (!_blockCounter.HasValue)
{
// First block
_blockCounter = blockCounter;
}
else if (blockCounter != _blockCounter)
{
throw new InvalidOperationException(
$"Received block counter ${blockCounter:X2} but expected ${_blockCounter:X2}");
}
_blockCounter++;
return blockCounter;
}
private byte ReadAndAckByte()
{
var b = KwpCommon.ReadByte();
Thread.Sleep(TimeInterval.R6);
var complement = (byte)~b;
KwpCommon.WriteByte(complement);
return b;
}
public void KeepAlive()
{
SendAckBlock();
var block = ReceiveBlock();
if (block is not AckBlock)
{
throw new InvalidOperationException(
$"Received 0x{block.Title:X2} block but expected ACK");
}
}
public ActuatorTestResponseBlock? ActuatorTest(byte value)
{
Log.WriteLine($"Sending actuator test 0x{value:X2} block");
SendBlock(new List<byte>
{
(byte)BlockTitle.ActuatorTest,
value
});
var blocks = ReceiveBlocks();
blocks = blocks.Where(b => !b.IsAckNak).ToList();
if (blocks.Count != 1)
{
Log.WriteLine($"ActuatorTest returned {blocks.Count} blocks instead of 1");
return null;
}
var block = blocks[0];
if (block is not ActuatorTestResponseBlock)
{
Log.WriteLine($"Expected ActuatorTestResponseBlock but got {block.GetType()}");
return null;
}
return (ActuatorTestResponseBlock)block;
}
public List<FaultCode>? ReadFaultCodes()
{
Log.WriteLine($"Sending ReadFaultCodes block");
SendBlock(new List<byte>
{
(byte)BlockTitle.FaultCodesRead
});
var blocks = ReceiveBlocks();
blocks = blocks.Where(b => !b.IsAckNak).ToList();
var faultCodes = new List<FaultCode>();
foreach (var block in blocks)
{
if (block is not FaultCodesBlock)
{
Log.WriteLine($"Expected FaultCodesBlock but got {block.GetType()}");
return null;
}
var faultCodesBlock = (FaultCodesBlock)block;
faultCodes.AddRange(faultCodesBlock.FaultCodes);
}
return faultCodes;
}
public List<FaultCode>? ClearFaultCodes(int controllerAddress)
{
Log.WriteLine($"Sending ClearFaultCodes block");
SendBlock(new List<byte>
{
(byte)BlockTitle.FaultCodesDelete
});
var blocks = ReceiveBlocks();
blocks = blocks.Where(b => !b.IsAckNak).ToList();
var faultCodes = new List<FaultCode>();
foreach (var block in blocks)
{
if (block is not FaultCodesBlock)
{
Log.WriteLine($"Expected FaultCodesBlock but got {block.GetType()}");
return null;
}
var faultCodesBlock = (FaultCodesBlock)block;
faultCodes.AddRange(faultCodesBlock.FaultCodes);
}
return faultCodes;
}
public bool SetSoftwareCoding(int controllerAddress, int softwareCoding, int workshopCode)
{
// Workshop codes > 65535 overflow into the low bit of the software coding
var bytes = new List<byte>
{
(byte)BlockTitle.SoftwareCoding,
(byte)((softwareCoding * 2) / 256),
(byte)((softwareCoding * 2) % 256),
(byte)((workshopCode & 65535) / 256),
(byte)(workshopCode % 256)
};
if (workshopCode > 65535)
{
bytes[2]++;
}
Log.WriteLine($"Sending SoftwareCoding block");
SendBlock(bytes);
var blocks = ReceiveBlocks();
if (blocks.Count == 1 && blocks[0] is NakBlock)
{
return false;
}
var controllerInfo = new ControllerInfo(blocks.Where(b => !b.IsAckNak));
return
controllerInfo.SoftwareCoding == softwareCoding &&
controllerInfo.WorkshopCode == workshopCode;
}
public bool AdaptationRead(byte channelNumber)
{
var bytes = new List<byte>
{
(byte)BlockTitle.AdaptationRead,
channelNumber
};
Log.WriteLine($"Sending AdaptationRead block");
SendBlock(bytes);
return ReceiveAdaptationBlock();
}
public bool AdaptationTest(byte channelNumber, ushort channelValue)
{
var bytes = new List<byte>
{
(byte)BlockTitle.AdaptationTest,
channelNumber,
(byte)(channelValue / 256),
(byte)(channelValue % 256)
};
Log.WriteLine($"Sending AdaptationTest block");
SendBlock(bytes);
return ReceiveAdaptationBlock();
}
public bool AdaptationSave(byte channelNumber, ushort channelValue, int workshopCode)
{
var bytes = new List<byte>
{
(byte)BlockTitle.AdaptationSave,
channelNumber,
(byte)(channelValue / 256),
(byte)(channelValue % 256),
(byte)(workshopCode >> 16),
(byte)((workshopCode >> 8) & 0xFF),
(byte)(workshopCode & 0xFF)
};
Log.WriteLine($"Sending AdaptationSave block");
SendBlock(bytes);
return ReceiveAdaptationBlock();
}
private bool ReceiveAdaptationBlock()
{
var responseBlock = ReceiveBlock();
if (responseBlock is NakBlock)
{
Log.WriteLine($"Received a NAK.");
return false;
}
if (responseBlock is not AdaptationResponseBlock adaptationResponse)
{
Log.WriteLine($"Expected an Adaptation response block but received a ${responseBlock.Title:X2} block.");
return false;
}
Log.WriteLine($"Adaptation value: {adaptationResponse.ChannelValue}");
return true;
}
public bool GroupRead(byte groupNumber, bool useBasicSetting = false)
{
if (groupNumber == 0)
{
return RawDataRead(useBasicSetting);
}
if (useBasicSetting)
{
Log.WriteLine($"Sending Basic Setting Read blocks...");
}
else
{
Log.WriteLine($"Sending Group Read blocks...");
}
GroupReadResponseWithTextBlock? textBlock = null;
Log.WriteLine("[Up arrow | Down arrow | Q to quit]", LogDest.Console);
while (true)
{
if (Console.KeyAvailable)
{
var keyInfo = Console.ReadKey(intercept: true);
if (keyInfo.Key == ConsoleKey.UpArrow)
{
if (groupNumber < 255)
{
groupNumber++;
}
}
else if (keyInfo.Key == ConsoleKey.DownArrow)
{
if (groupNumber > 1)
{
groupNumber--;
}
}
else if (keyInfo.Key == ConsoleKey.Q)
{
break;
}
}
var bytes = new List<byte>
{
(byte)(useBasicSetting ? BlockTitle.BasicSettingRead : BlockTitle.GroupRead),
groupNumber
};
SendBlock(bytes);
var responseBlock = ReceiveBlock();
if (responseBlock is NakBlock)
{
Overlay($"Group {groupNumber:D3}: Not Available");
}
else if (responseBlock is GroupReadResponseWithTextBlock groupReadResponseWithText)
{
Log.WriteLine($"{groupReadResponseWithText}", LogDest.File);
textBlock = groupReadResponseWithText;
}
else if (responseBlock is GroupReadResponseBlock groupReading)
{
Overlay($"Group {groupNumber:D3}: {groupReading}");
}
else if (responseBlock is RawDataReadResponseBlock rawData)
{
if (textBlock != null && rawData.Body.Count > 0)
{
var sb = new StringBuilder($"Group {groupNumber:D3}: ");
sb.Append(textBlock.GetText(rawData.Body[0]));
sb.Append(Utils.DumpDecimal(rawData.Body.Skip(1)));
Overlay(sb.ToString());
}
else
{
Overlay($"Group {groupNumber:D3}: {rawData}");
}
}
else
{
Log.WriteLine($"Expected a Group Reading response block but received a ${responseBlock.Title:X2} block.");
return false;
}
}
Log.WriteLine(LogDest.Console);
return true;
}
private bool RawDataRead(bool useBasicSetting)
{
if (useBasicSetting)
{
Log.WriteLine($"Sending Basic Setting Raw Data Read block");
}
else
{
Log.WriteLine($"Sending Raw Data Read block");
}
Log.WriteLine("[Press a key to quit]", LogDest.Console);
while (!Console.KeyAvailable)
{
var bytes = new List<byte>
{
(byte)(useBasicSetting ? BlockTitle.BasicSettingRawDataRead : BlockTitle.RawDataRead)
};
SendBlock(bytes);
var responseBlock = ReceiveBlock();
if (responseBlock is not RawDataReadResponseBlock rawDataReadResponse)
{
Log.WriteLine($"Expected a Raw Data Read response block but received a ${responseBlock.Title:X2} block.");
return false;
}
Overlay(rawDataReadResponse.ToString());
}
Log.WriteLine(LogDest.Console);
return true;
}
/// <summary>
/// Erase the current console line and replace it with message.
/// Also writes the message to the log.
/// </summary>
private static void Overlay(string message)
{
(int left, int top) = Console.GetCursorPosition();
Console.SetCursorPosition(0, top);
if (left > 0)
{
Log.Write(new string(' ', left), LogDest.Console);
Console.SetCursorPosition(0, top);
}
Log.Write(message, LogDest.Console);
Log.WriteLine(message, LogDest.File);
}
private static class TimeInterval
{
/// <summary>
/// Time to wait in milliseconds after receiving a byte from the ECU before sending the next byte.
/// Valid range: 1-50ms (according to SAE J2818)
/// </summary>
public const int R6 = 2;
}
public IKwpCommon KwpCommon { get; }
private bool _isConnected;
private byte? _blockCounter;
public KW1281Dialog(IKwpCommon kwpCommon)
{
KwpCommon = kwpCommon;
_isConnected = false;
_blockCounter = null;
}
}
/// <summary>
/// Used for commands such as ActuatorTest which need to be kept alive with ACKs while waiting
/// for user input.
/// </summary>
internal class KW1281KeepAlive : IDisposable
{
private readonly IKW1281Dialog _kw1281Dialog;
private volatile bool _cancel = false;
private Task? _keepAliveTask = null;
public KW1281KeepAlive(IKW1281Dialog kw1281Dialog)
{
_kw1281Dialog = kw1281Dialog;
}
public ActuatorTestResponseBlock? ActuatorTest(byte value)
{
Pause();
var result = _kw1281Dialog.ActuatorTest(value);
Resume();
return result;
}
public void Dispose()
{
Pause();
}
private void Pause()
{
_cancel = true;
if (_keepAliveTask != null)
{
_keepAliveTask.Wait();
}
}
private void Resume()
{
_keepAliveTask = Task.Run(KeepAlive);
}
private void KeepAlive()
{
_cancel = false;
while (!_cancel)
{
_kw1281Dialog.KeepAlive();
Log.Write(".", LogDest.Console);
}
}
}
}