Repository navigation
Expand file tree
/
Copy pathCH9329.cs
More file actions
1338 lines (1121 loc) · 52 KB
/
Copy pathCH9329.cs
File metadata and controls
1338 lines (1121 loc) · 52 KB
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
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* AaLl86 MiniKvm
*
* Copyright© 2024 by Andrea Allievi
*
* Module: CH9329.cs
*
* Description:
* Implement the CH9329 class which assembles, encodes and decodes CH9329
* packets through the serial port. The class implements also a Keys/Mouse
* converter (from and to Win32).
*
* History:
* 5/29/2024 - Initial implementation
* 01/10/2025 - Last revision
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Windows.Forms;
using System.Net.Http.Headers;
using System.DirectoryServices.ActiveDirectory;
using static MiniKvm.CH9329;
using System.Net.Sockets;
using System.IO.Ports;
using DirectShowLib;
using Emgu.CV.CvEnum;
using System.Security.Policy;
namespace MiniKvm
{
/// <summary>
/// Implement a class to communicate with a CH9329 chip over a serial port.
/// </summary>
public class CH9329
{
#region Key Codes, Press type and Modifiers
[Flags]
public enum KeyPressType {
KeyPressed = 0x1,
KeyReleased = 0x2,
KeyPressedAndReleased = 0x3
}
public enum KeyCode {
None = 0,
// Letters
KeyA = 0x4,
KeyB = 0x5,
KeyC = 0x6,
KeyD = 0x7,
KeyE = 0x8,
KeyF = 0x9,
KeyG = 0xA,
KeyH = 0xB,
KeyI = 0xC,
KeyJ = 0xD,
KeyK = 0xE,
KeyL = 0xF,
KeyM = 0x10,
KeyN = 0x11,
KeyO = 0x12,
KeyP = 0x13,
KeyQ = 0x14,
KeyR = 0x15,
KeyS = 0x16,
KeyT = 0x17,
KeyU = 0x18,
KeyV = 0x19,
KeyW = 0x1A,
KeyX = 0x1B,
KeyY = 0x1C,
KeyZ = 0x1D,
// Numbers
Key1 = 0x1E,
Key2 = 0x1F,
Key3 = 0x20,
Key4 = 0x21,
Key5 = 0x22,
Key6 = 0x23,
Key7 = 0x23,
Key8 = 0x25,
Key9 = 0x26,
Key0 = 0x27,
KeyEnterLeft = 0x28,
KeyEscape = 0x29,
KeyBackspace = 0x2A,
KeyTab = 0x2B,
KeySpace = 0x2C,
KeyMinus = 0x2D,
KeyPlus = 0x2E,
// Brackets
KeyOpenBracket = 0x2F,
KeyClosedBracket = 0x30,
KeyFrontSlash = 0x31,
KeySemicolon = 0x33,
KeyApostrophe = 0x34,
KeyTilde = 0x35,
KeyComma = 0x36,
KeyPeriod = 0x37,
KeyBackSlash = 0x38,
KeyCapsLock = 0x39,
// F* keys
KeyF1 = 0x3A,
KeyF2 = 0x3B,
KeyF3 = 0x3C,
KeyF4 = 0x3D,
KeyF5 = 0x3E,
KeyF6 = 0x3F,
KeyF7 = 0x40,
KeyF8 = 0x41,
KeyF9 = 0x42,
KeyF10 = 0x43,
KeyF11 = 0x44,
KeyF12 = 0x45,
// Print, Scroll lock, Insert, Home, delete, end, page up and
// page down
KeyPrint = 0x46,
KeyScrollLock = 0x47,
KeyPause = 0x48,
KeyInsert = 0x49,
KeyHome = 0x4A,
KeyPageUp = 0x4B,
KeyDelete = 0x4C,
KeyEnd = 0x4D,
KeyPageDown = 0x4E,
// Cursors
KeyRightArrow = 0x4F,
KeyLeftArrow = 0x50,
KeyDownArrow = 0x51,
KeyUpArrow = 0x52,
// Numeric keypad
KeyNumLock = 0x53,
KeyDivide = 0x54,
KeyMultiply = 0x55,
KeySubtract = 0x56,
KeyAdd = 0x57,
KeyEnterRight = 0x58,
KeyNumpad1 = 0x59,
KeyNumpad2 = 0x5A,
KeyNumpad3 = 0x5B,
KeyNumpad4 = 0x5C,
KeyNumpad5 = 0x5D,
KeyNumpad6 = 0x5E,
KeyNumpad7 = 0x5F,
KeyNumpad8 = 0x60,
KeyNumpad9 = 0x61,
KeyNumpad0 = 0x62,
}
[Flags]
public enum KeyModifier {
None = 0,
LeftCtrl = 0x1,
LeftShift = 0x2,
LeftAlt = 0x4,
LeftWindows = 0x8,
RightCtrl = 0x10,
RightShift = 0x20,
RightAlt = 0x40,
RightWindows = 0x80
}
#endregion
#region CH9329 Mouse data
[Flags]
public enum MouseButtons
{
MouseButtonNoChange = -1, // Pseudo value only valid in SendMouseAction
MouseButtonNone = 0,
MouseButtonLeft = 0x1,
MouseButtonRight = 0x2,
MouseButtonMiddle = 0x4
}
#endregion
#region CH9329 Packets and responses
[StructLayout(LayoutKind.Sequential, Pack = 1)]
private struct CH9329_PacketHdr
{
//[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
public UInt16 Header;
public byte AddressCode;
public byte Command;
public byte DataSize;
/* Variable part:
[MarshalAs(UnmanagedType.ByValArray)]
byte[] Data; */
// Checksum
//byte ChkSum;
};
// The minimum allowed CH9329 packet size
public static int MinPacketSize = 6;
/// <summary>
/// Identify a non-packed, non-sequential CH9329 response
/// </summary>
private struct CH9329_Response {
public CH9329_PacketHdr PckHeader;
public ResponseType Type;
public byte[] PckData;
public byte Checksum;
}
private enum PacketType
{
CMD_GET_INFO = 0x1,
CMD_SEND_KB_GENERAL_DATA = 0x2,
CMD_SEND_KB_MEDIA_DATA = 0x3, // Not used yet
CMD_SEND_MS_ABS_DATA = 0x4,
CMD_SEND_MS_REL_DATA = 0x5, // Used for scrolling only
CMD_SEND_MY_HID_DATA = 0x6, // Not used yet
CMD_READ_MY_HID_DATA = 0x7, // Not used yet
CMD_GET_PARA_CFG = 0x8,
CMD_SET_PARA_CFG = 0x9,
CMD_GET_USB_STRING = 0xA,
CMD_SET_USB_STRING = 0xB,
CMD_SET_DEFAULT_CFG = 0xC,
CMD_RESET = 0xF
};
public enum ResponseType
{
RESPONSE_INVALID_PACKET = 0,
RESPONSE_INFO = 0x81,
RESPONSE_SEND_KB_GENERAL_DATA = 0x82,
RESPONSE_SEND_KB_MEDIA_DATA = 0x83, // Not used yet
RESPONSE_SEND_MS_ABS_DATA = 0x84,
RESPONSE_SEND_MS_REL_DATA = 0x85, // Not used yet
RESPONSE_SEND_MY_HID_DATA = 0x86, // Not used yet
RESPONSE_READ_MY_HID_DATA = 0x87, // Not used yet
RESPONSE_GET_PARA_CFG = 0x88,
RESPONSE_SET_PARA_CFG = 0x89,
RESPONSE_GET_USB_STRING = 0x8A,
RESPONSE_SET_USB_STRING = 0x8B,
RESPONSE_SET_DEFAULT_CFG = 0x8C,
RESPONSE_RESET = 0x8F,
RESPONSE_UNKNOWN = 0x90,
RESPONSE_ERROR = 0xC0,
}
public enum StatusCode
{
SUCCESS = 0, // Command executed correctly
SYNTH_FAILURE = 1, // Syntetic generic failure
ERR_TIMEOUT = 0xE1, // The serial port receives a timeout
ERR_HEAD = 0xE2,
ERR_CMD = 0xE3, // The command code received is not recognized
ERR_SUM = 0xE4, // Accumulated and checked sum values do not match
ERR_PARAMETER = 0xE5, // Parameter error
ERR_OPERATE = 0xE6 // Frame OK, execution failed.
}
[Flags]
public enum KbdIndicator: byte
{
NONE = 0,
NUM_LOCK = 1,
CAPS_LOCK = 2,
SCROLL_LOCK = 4,
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct InfoPacket
{ // BYTE Offset
public byte Version; // [1] - Chip version number: 0x30 means V1.0, 0x31 means V1.1;
public byte UsbStatus; // [2] - USB enumeration status: 0 - The USB port is not connected;
// 1 - USB port connected and target PC recognized it
[MarshalAs(UnmanagedType.U1)]
public KbdIndicator KbdSizeIndicators; // [3] - Current keyboard size indicator light status information (bitmask)
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)]
byte[] Reserved;
}
public enum Chip_WorkingMode: byte
{
USB_MOUSE_KBD_SOFTWARE = 0,
USB_KBD_SOFTWARE = 1,
USB_MOUSE_SOFTWARE = 2,
USB_CUSTOM_HID_SOFTWARE = 3,
USB_MOUSE_KBD_HARDWARE = 0x80,
USB_KBD_HARDWARE = 0x81,
USB_MOUSE_HARDWARE = 0x82,
USB_CUSTOM_HID_HARDWARE = 0x83,
}
public enum Chip_CommMode : byte {
PROTOCOL_TRANSMISSION_SOFTWARE = 0,
ASCII_SOFTWARE = 1,
TRANSPARENT_TRASMISSION_SOFTWARE = 2,
PROTOCOL_TRANSMISSION_HARDWARE = 0x80,
ASCII_HARDWARE = 0x81,
TRANSPARENT_TRASMISSION_HARDWARE = 0x82
}
//
// USB keyboard carriage return (valid only in ASCII mode) data structure
// for the Configuration parameters.
//
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct ConfigPacket_KbdReturn {
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] Group1; // [23:20] - Carriage return character set 1
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] Group2; // [27:24] - Carriage return character set 2
};
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct ConfigPacket
{ // BYTE Offset
public Chip_WorkingMode WorkingMode; // [0]
public Chip_CommMode CommunicationMode; // [1]
public byte CommunicationAddress; // [2]
public UInt32 BaudRate; // [6:3] - Serial port speed
public UInt16 Reserved; // [8:7]
public UInt16 SerialPortInterval; // [10:9] - Serial port communication interval (in mSec)
public UInt16 VID; // [12:11] - VID of the chip USB-interface
public UInt16 PID; // [14:13] - PID of the chip USB-interface
public UInt16 KbdUploadInterval; // [16:15] - USB Keyboard upload time interval (in mSec, valid only in ASCII mode)
public UInt16 KbdReleaseDelay; // [18:17] - USB Keyboard release delay time (in mSec, valid only in ASCII mode)
public byte KbdAutomaticReturn; // [19] - Automatic carriage return flag (valid only in ASCII mode)
// [27:20] - USB keyboard carriage return (valid only in ASCII mode)
public ConfigPacket_KbdReturn KbdReturn;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] KbdFilterStart; // [31:28] - USB Keyboard filter start characters
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] KbdFilterEnd; // [35:32] - USB Keyboard filter end characters
public byte UsbStringFlags; // [36] - USB string enable flags (bitmask)
public byte KbdFastUploadMode; // [37] - USB keyboard fast upload mode enabled (valid only in ASCII mode)
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 12)]
byte[] Reserved2; // [49:38] - 12 bytes reserved */
}
#endregion
#region Class data and properties
private MouseButtons CurrentMouseBtns;
public const int CH9329_ChecksumSize = 1;
public delegate bool DataSendFunction(byte[] data);
public delegate bool DataReceiveFunction(out byte[]? ReceivedData);
private DataSendFunction? pckSendFunction;
private DataReceiveFunction? pckReceiveFunction;
public DataSendFunction? SendFunction
{
get { return pckSendFunction; }
set { pckSendFunction = value; }
}
public DataReceiveFunction? ReceiveFunction
{
get { return pckReceiveFunction; }
set { pckReceiveFunction = value; }
}
private Size screenSize = new Size(1920, 1080);
public Size RemoteScreenSize {
get { return screenSize; }
set { screenSize = value; }
}
private int sendTimeout = 30;
/// <summary>
/// Query or Set the I/O timeout while sending / receive packets
/// </summary>
public int SendTimeout {
get { return sendTimeout; }
set { sendTimeout = value; }
}
// Last expected response read from WaitForCh9329Response;
private ResponseType LastExpectedResponse;
#endregion
/// <summary>
/// Class default constructor
/// </summary>
public CH9329() {
CurrentMouseBtns = MouseButtons.MouseButtonNone;
pckSendFunction = null;
pckReceiveFunction = null;
LastExpectedResponse = ResponseType.RESPONSE_UNKNOWN;
}
/// <summary>
/// Build a send key CH9329 packed and optionally send it through the
/// associated class Send function.
/// </summary>
/// <param name="Key">Supplies the virtual key code to send</param>
/// <param name="Modifier">Supplies the active key modifiers</param>
/// <param name="PressType">Supplies the key press type</param>
/// <returns>A boolean value indicating whether the packed has been
/// correctly sent via the class Send function</returns>
public bool SendKey(KeyCode Key, KeyModifier Modifier, KeyPressType PressType)
{
byte[] PckData;
byte[] PckBuffer;
bool RetVal = false;
PckData = new byte[8];
PckData[0] = (byte)Modifier;
PckData[1] = 0x00;
if ((PressType & KeyPressType.KeyPressed) == KeyPressType.KeyPressed) {
PckData[2] = (byte)Key;
}
PckBuffer = AssemblePacket(PacketType.CMD_SEND_KB_GENERAL_DATA, PckData);
if (pckSendFunction == null) {
return false;
} else {
RetVal = pckSendFunction(PckBuffer);
}
if ((PressType == KeyPressType.KeyPressedAndReleased) &&
(RetVal != false)) {
// Release all the keys here (including modifier)
PckData[0] = 0;
PckData[2] = 0;
PckBuffer = AssemblePacket(PacketType.CMD_SEND_KB_GENERAL_DATA, PckData);
// Introduce a minimum of delay between sending KeyUp and KeyDown
Thread.Sleep(10);
RetVal = pckSendFunction(PckBuffer);
}
if ((RetVal != false) && (pckReceiveFunction != null)) {
byte[] RecvData;
Thread.Sleep(8);
pckReceiveFunction(out RecvData);
}
return RetVal;
}
/// <summary>
/// Send an ABS mouse move event to the CH9329 chip
/// </summary>
/// <param name="MousePoint">Supplies the point where the caller wants to move the mouse to.</param>
/// <param name="MouseButtons">Supplies a MouseButtons data structure representing the
/// mouse button to press / release.</param>
/// <param name="Released">Supplies "false" in case the mouse buttons are pressed.
/// "True" otherwise</param>
/// <param name="WheelDelta">Supplies the number of teeth to scroll.
/// A positive value indicate scroll up. A negative one scroll down.</param>
/// <returns>The status of the operation.</returns>
public bool SendMouseMove(Point MousePoint, MouseButtons MouseButtons, bool Released, int WheelDelta)
{
byte[] PckData = new byte[7];
byte[] PckBuffer;
Point MouseCoords = MousePoint;
bool RetVal = false;
PckData[0] = 0x2;
PckData[1] = 0;
if (Released == false) {
// The mouse keys are pressed
PckData[1] = (byte)MouseButtons;
CurrentMouseBtns = MouseButtons;
} else {
// The mouse keys are released
CurrentMouseBtns &= ~MouseButtons;
PckData[1] = (byte)CurrentMouseBtns;
}
//
// Convert the coordinates
//
MouseCoords.X = (MousePoint.X * 4096) / screenSize.Width;
MouseCoords.Y = (MousePoint.Y * 4096) / screenSize.Height;
byte[] SingleCoord = BitConverter.GetBytes(MouseCoords.X);
PckData[2] = SingleCoord[0];
PckData[3] = SingleCoord[1];
SingleCoord = BitConverter.GetBytes(MouseCoords.Y);
PckData[4] = SingleCoord[0];
PckData[5] = SingleCoord[1];
PckData[6] = 0;
if (WheelDelta > 0) {
// Scroll up
PckData[6] = (byte)((byte)WheelDelta & 0x7F);
} else {
// Scroll down
PckData[6] = (byte)((byte)WheelDelta | 0x80);
}
PckBuffer = AssemblePacket(PacketType.CMD_SEND_MS_ABS_DATA, PckData);
if (pckSendFunction == null) {
return false;
} else {
RetVal = pckSendFunction(PckBuffer);
}
if ((RetVal != false) && (pckReceiveFunction != null)) {
byte[] RecvData;
pckReceiveFunction(out RecvData);
}
return RetVal;
}
/// <summary>
/// Send mouse actions to the CH9329 controller, like MouseDown, MouseUp or WhellDown and WhellUp.
/// </summary>
/// <param name="MouseButtons">Supplies a MouseButtons data structure representing the
/// mouse button to press / release.</param>
/// <param name="Released">Supplies "false" in case the mouse buttons are pressed.
/// "True" otherwise</param>
/// <param name="WheelDelta">Supplies the number of teeth to scroll.
/// A positive value indicate scroll up. A negative one scroll down.</param>
/// <returns>The status of the operation.</returns>
public bool SendMouseActions(MouseButtons MouseButtons, bool Released, int WheelDelta) {
byte[] PckData = new byte[5];
byte[] PckBuffer;
bool RetVal = false;
PckData[0] = 0x1;
PckData[1] = 0;
if (MouseButtons == MouseButtons.MouseButtonNoChange) {
// No mouse button change
PckData[1] = (byte)CurrentMouseBtns;
} else if (Released == false) {
// The mouse keys are pressed
PckData[1] = (byte)MouseButtons;
CurrentMouseBtns = MouseButtons;
} else {
// The mouse keys are released
CurrentMouseBtns &= ~MouseButtons;
PckData[1] = (byte)CurrentMouseBtns;
}
//
// This routine does not support moving the mouse with REL coordinates
//
PckData[2] = 0;
PckData[3] = 0;
PckData[4] = 0;
if (WheelDelta > 0) {
// Scroll up
PckData[4] = (byte)((byte)WheelDelta & 0x7F);
} else {
// Scroll down
PckData[4] = (byte)((byte)WheelDelta | 0x80);
}
PckBuffer = AssemblePacket(PacketType.CMD_SEND_MS_REL_DATA, PckData);
if (pckSendFunction == null) {
return false;
} else {
RetVal = pckSendFunction(PckBuffer);
}
if ((RetVal != false) && (pckReceiveFunction != null)) {
byte[] RecvData;
pckReceiveFunction(out RecvData);
}
return RetVal;
}
/// <summary>
/// Read a response packet from the the Ch9329 controller.
/// </summary>
/// <param name="ExpectedResponse">Supplies the response that the caller is waiting on</param>
/// <returns>A boolean value with the status of the operation.</returns>
private bool WaitForCh9329Response(ResponseType ExpectedResponse, out byte[] ResponsePck) {
int NumOfTrials = 0;
byte[] RawData = null;
List<CH9329_Response> Packets = null;
int NumOfPcks = 0;
ResponseType responseType = ResponseType.RESPONSE_INVALID_PACKET;
bool RetVal = false;
ResponsePck = null;
if (pckReceiveFunction == null) {
return false;
}
while ((RetVal == false) && (NumOfTrials < 3)) {
// Give the time to the CH9329 chip to send back the response
Thread.Sleep(40);
RetVal = pckReceiveFunction(out RawData);
if ((RetVal != false) && (RawData != null)) {
NumOfPcks = DecodePackets(RawData, out Packets);
}
NumOfTrials += 1;
}
// Search the expected response
for (int Index = 0; Index < NumOfPcks; Index += 1) {
CH9329_Response CurPck = Packets[Index];
if (CurPck.Type == ExpectedResponse) {
responseType = CurPck.Type;
ResponsePck = CurPck.PckData;
}
RetVal = true;
}
// Log any failure (if any).
if ((responseType != ExpectedResponse) &&
(LastExpectedResponse != ExpectedResponse)) {
if (RetVal == false) {
MiniKvmLogger.Log("WaitForCh9329Response: Unable to receive the expected " +
ExpectedResponse.ToString() + " response from the CH9329 controller.");
} else if (responseType != ExpectedResponse) {
MiniKvmLogger.Log("WaitForCh9329Response: Another unexpected response has been " +
"read from the controller (instead of " + ExpectedResponse.ToString() + "): " +
responseType.ToString());
}
}
LastExpectedResponse = ExpectedResponse;
return (responseType == ExpectedResponse);
}
/// <summary>
/// Send a "GetInfo" command to the CH9329 device and optionally wait for
/// a response.
/// </summary>
/// <param name="WaitResponse">Supplies a parameter set to True when the caller
/// wants to wait the reply</param>
/// <param name="Info">When waiting the response, supply a output parameter
/// which will be filled with the Info Packet.</param>
/// <returns>A boolean value indicating the status of the operation.</returns>
public bool SendGetInfo(bool WaitResponse, out InfoPacket? Info) {
byte[]? requestPck = null;
byte[]? responsePck = null;
bool RetVal = false;
Info = null;
if (pckSendFunction == null) {
return false;
}
requestPck = AssemblePacket(PacketType.CMD_GET_INFO, null);
RetVal = pckSendFunction(requestPck);
if (WaitResponse == false) {
return RetVal;
}
//
// If we are here, the caller wants to read the response, check
// that the Receive function is set.
//
RetVal = WaitForCh9329Response(ResponseType.RESPONSE_INFO, out responsePck);
if (RetVal == false) {
return false;
}
//
// The read packet is correct. Return a Info packet and exit.
//
GCHandle handle = GCHandle.Alloc(responsePck, GCHandleType.Pinned);
Info = (InfoPacket?)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(InfoPacket));
handle.Free();
return RetVal;
}
/// <summary>
/// Send a GET_CONFIG_PARAMETERS packet to the CH9329 and waits the response
/// which contains the chip configuration.
/// </summary>
/// <param name="Config">Output parameter that will be filled with the CH9329
/// current configuration</param>
/// <returns>A boolean value indicating the status of the operation</returns>
public bool SendGetParameters(out ConfigPacket? Config) {
byte[]? requestPck = null;
byte[]? responsePck = null;
bool RetVal = false;
ConfigPacket LocalParams;
Config = null;
if ((pckSendFunction == null) || (pckReceiveFunction == null)) {
return false;
}
requestPck = AssemblePacket(PacketType.CMD_GET_PARA_CFG, null);
RetVal = pckSendFunction(requestPck);
if (RetVal != false) {
// Read the GET_PARA response
RetVal = WaitForCh9329Response(ResponseType.RESPONSE_GET_PARA_CFG, out responsePck);
}
if (RetVal == false) {
return false;
}
// The read packet is correct. Return a Info packet and exit.
GCHandle handle = GCHandle.Alloc(responsePck, GCHandleType.Pinned);
LocalParams = (ConfigPacket)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(ConfigPacket));
handle.Free();
// Convert the endianess of the structure now
Config = ConvertParamStructure(LocalParams);
return RetVal;
}
/// <summary>
/// Send a SET_CONFIG_PARAMETERS packet to the CH9329 to reconfigure it.
/// Note that after this command, a CMD_RESET is needed.
/// </summary>
/// <param name="NewConfig">Supplies a ConfigPacket data structure containing
/// the new CH9329 configuration</param>
/// <param name="WaitForResponse">Set to "true" if the routine needs to wait the
/// response from the device.</param>
/// <returns>A boolean value indicating the result of the operation.</returns>
public bool SendSetParameters(ConfigPacket NewConfig, bool WaitForResponse = true)
{
byte[] data;
int Size = 0;
ConfigPacket? LocalConfig;
IntPtr Ptr;
byte[] requestPck;
byte[] responsePck = new byte[1];
bool RetVal = false;
responsePck[0] = (byte)StatusCode.SYNTH_FAILURE;
if (pckSendFunction == null) {
return false;
}
//
// Convert back the Configuration structure in Big Endian before
// processing it.
//
LocalConfig = ConvertParamStructure(NewConfig);
if (LocalConfig == null) {
return false;
}
Size = Marshal.SizeOf(NewConfig);
Ptr = Marshal.AllocHGlobal(Size);
data = new byte[Size];
Marshal.StructureToPtr(LocalConfig, Ptr, true);
Marshal.Copy(Ptr, data, 0, Marshal.SizeOf(LocalConfig));
requestPck = AssemblePacket(PacketType.CMD_SET_PARA_CFG, data);
RetVal = pckSendFunction(requestPck);
if ((RetVal == false) ||
(WaitForResponse == false)) {
return RetVal;
}
// Read the SET_PARA_CFG response packet
RetVal = WaitForCh9329Response(ResponseType.RESPONSE_SET_PARA_CFG, out responsePck);
if (RetVal == false) {
return false;
}
if (responsePck[0] != (byte)StatusCode.SUCCESS) {
MiniKvmLogger.Log("CH9329 has encounter " + responsePck[0] +
" error while processing the CMD_SET_PARA_CFG command.");
return false;
}
return true;
}
/// <summary>
/// Send a RESET packet to the CH9329 device
/// </summary>
/// <param name="WaitForResponse">Set to "true" if the caller wants to wait the
/// confirmation packet to be received back</param>
/// <returns>A boolean value indicating the result of the operation.</returns>
public bool SendReset(bool WaitForResponse = true)
{
byte[] requestPck;
byte[] responsePck = new byte[1];
bool RetVal = false;
responsePck[0] = (byte)StatusCode.SYNTH_FAILURE;
if (pckSendFunction == null) {
return false;
}
requestPck = AssemblePacket(PacketType.CMD_RESET, null);
RetVal = pckSendFunction(requestPck);
if ((RetVal == false) ||
(WaitForResponse == false)) {
return RetVal;
}
RetVal = WaitForCh9329Response(ResponseType.RESPONSE_RESET, out responsePck);
if (RetVal == false) {
return false;
}
if (responsePck[0] != (byte)StatusCode.SUCCESS) {
MiniKvmLogger.Log("Warning! The CH9329 controller has encounter " + responsePck[0] +
" error while processing the CMD_RESET command.");
return false;
} else {
// Give time to the CH9329 to reboot
Thread.Sleep(30);
}
return true;
}
/// <summary>
/// Determine whether a received packet is a valid CH9329 one.
/// </summary>
/// <param name="RawData">Supplies the raw packet data.</param>
/// <param name="ValidSize">Supplies an optional valid size of the buffer</param>
/// <returns>A boolean value indicating whether the packet is a valid CH9329 one.</returns>
public bool IsPacketValid(byte[] RawData, int ValidSize = 0) {
int HdrSize;
int Offset = 0;
int PckSize;
byte Sum;
ResponseType pckType = ResponseType.RESPONSE_INVALID_PACKET;
if (ValidSize > 0) {
RawData = RawData.Take(ValidSize).ToArray();
}
HdrSize = Marshal.SizeOf(typeof(CH9329_PacketHdr));
if (RawData.Length < CH9329.MinPacketSize) { return false; }
for (Offset = RawData.Length - CH9329.MinPacketSize; Offset >= 0; Offset -= 1) {
if ((RawData[Offset] != 0x57) || (RawData[Offset + 1] != 0xAB) || (RawData[Offset + 2] != 0)) {
// The initial CH9329 header is invalid.
continue;
}
// PckSize does *NOT* contain the final Checksum byte
PckSize = RawData[Offset + 4] + HdrSize;
if (PckSize + CH9329_ChecksumSize > RawData.Length - Offset) {
continue;
}
// Now calculate the checksum since we know that the packet is big enough
Sum = 0;
for (int Index = 0; Index < PckSize; Index++) {
Sum += RawData[Index + Offset];
}
if (Sum != RawData[PckSize + Offset]) {
continue;
}
// Add the final checksum byte to the packet size
PckSize += CH9329_ChecksumSize;
// I found a valid CH9329 packet. My job is done here.
pckType = (ResponseType)RawData[Offset + 3];
break;
}
if ((pckType >= ResponseType.RESPONSE_INFO) &&
(pckType <= ResponseType.RESPONSE_ERROR)) {
return true;
}
return false;
}
/// <summary>
/// Internal function to convert a configuration packet from big to little endian.
/// </summary>
/// <param name="orgStruct">The original Configuration packet data structure with
/// data in big endian</param>
/// <returns>A ConfigPacket nullable data structure conatining the converted
/// configuration packet.</returns>
private ConfigPacket? ConvertParamStructure(ConfigPacket orgStruct) {
ConfigPacket LocalParams = orgStruct;
const int NumOfFields = 4;
for (int i = 0; i < NumOfFields; i++) {
byte[] field_data;
switch (i) {
case 0: // BaudRate
field_data = BitConverter.GetBytes(LocalParams.BaudRate);
Array.Reverse(field_data, 0, 4);
LocalParams.BaudRate = BitConverter.ToUInt32(field_data, 0);
break;
case 1: // SerialPortInterval
field_data = BitConverter.GetBytes(LocalParams.SerialPortInterval);
Array.Reverse(field_data, 0, 2);
LocalParams.SerialPortInterval = BitConverter.ToUInt16(field_data, 0);
break;
case 2: // KbdUploadInterval
field_data = BitConverter.GetBytes(LocalParams.KbdUploadInterval);
Array.Reverse(field_data, 0, 2);
LocalParams.KbdUploadInterval = BitConverter.ToUInt16(field_data, 0);
break;
case 3: // KbdReleaseDelay
field_data = BitConverter.GetBytes(LocalParams.KbdReleaseDelay);
Array.Reverse(field_data, 0, 2);
LocalParams.KbdReleaseDelay = BitConverter.ToUInt16(field_data, 0);
break;
default:
Debug.Assert(false);
return null;
}
}
return LocalParams;
}
/// <summary>
/// Assemble a CH9329 packet
/// </summary>
/// <param name="Command">Supplies the type of command to send</param>
/// <param name="data">Supplies the raw data to add into the CH9329 packet</param>
/// <returns>A buffer containing the entire CH9329 packet</returns>
private byte[] AssemblePacket(PacketType Command, byte[]? data) {
CH9329_PacketHdr hdr = new CH9329_PacketHdr();
int DataSize, HdrSize, PckSize;
byte[] packet;
IntPtr Ptr = IntPtr.Zero;
byte Sum = 0;
if (data != null) {
DataSize = data.Length;
} else {
DataSize = 0;
}
hdr.Header = 0xAB57;
hdr.AddressCode = 0;
hdr.Command = (byte)Command;
hdr.DataSize = (byte)DataSize;
HdrSize = Marshal.SizeOf(typeof(CH9329_PacketHdr));
PckSize = hdr.DataSize + HdrSize + CH9329_ChecksumSize;
packet = new byte[PckSize];
Ptr = Marshal.AllocHGlobal(PckSize);
Marshal.StructureToPtr(hdr, Ptr, true);
Marshal.Copy(Ptr, packet, 0, PckSize);
if (data != null) {
data.CopyTo(packet, HdrSize);
}
// Calculate the sum now as the last byte
Sum = 0;
for (int Index = 0; Index < HdrSize + DataSize; Index++) {
Sum += packet[Index];
}