-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCiiClient.cs
More file actions
809 lines (650 loc) · 26.3 KB
/
CiiClient.cs
File metadata and controls
809 lines (650 loc) · 26.3 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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;
namespace TAInstruments.CommonInstrumentInterface
{
public class CiiClient : ICiiClient, IDisposable
{
#region Dispose Logic
// Track whether Dispose has been called.
private bool disposed = false;
public void Dispose()
{
Dispose(true);
// Use SupressFinalize in case a subclass
// of this type implements a finalizer.
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
// If you need thread safety, use a lock around these
// operations, as well as in your methods that use the resource.
if (!disposed)
{
if (disposing)
{
if (loginAcceptEvent != null)
loginAcceptEvent.Close();
if (asyncErrorEvent != null)
asyncErrorEvent.Close();
}
// Indicate that the instance has been disposed.
loginAcceptEvent = null;
asyncErrorEvent = null;
disposed = true;
}
}
#endregion
#region Message Types
private enum CiiMessageType
{
MtUninitialized = 0x0,
MtGetCommand = 0x20544547, /* "GET " */
MtActionCommand = 0x4E544341, /* "ACTN" */
MtLogin = 0x4E474F4C, /* "LOGN" */
MtAccept = 0x54504341, /* "ACPT" */
MtAck = 0x204B4341, /* "ACK " */
MtNak = 0x204B414E, /* "NAK " */
MtResponse = 0x20505352, /* "RSP " */
MtStatus = 0x54415453, /* "STAT" */
}
private readonly byte[] MessageTypeGet;
private readonly byte[] MessageTypeAction;
private readonly byte[] BytesLogin;
#endregion
#region Async Errors
public event AsyncErrorEventHandler AsyncErrorEvent;
public void SendAsyncError(string errorDescription)
{
logger.Log(errorDescription, null, 0);
//
// If we aren't connected, filter out superfluous errors.
//
if ((connectionState == ConnectionState.Connected) ||
(connectionState == ConnectionState.WaitingForLogin))
{
lock (asyncErrorsLock)
{
asyncErrors.Enqueue(errorDescription);
asyncErrorEvent.Set();
}
}
}
private void AsyncErrorThread()
{
while (true)
{
asyncErrorEvent.WaitOne();
lock(asyncErrorsLock)
{
while (asyncErrors.Count != 0)
{
string errorString = asyncErrors.Dequeue();
AsyncErrorEventHandler e = AsyncErrorEvent;
if (e != null)
{
e(this, new CiiAsyncErrorEventArgs(errorString));
}
}
}
}
}
#endregion
#region Private variables
private CiiMessagesInFlight messagesInFlight;
private volatile CiiAccessLevel grantedAccess;
private AutoResetEvent loginAcceptEvent;
private AutoResetEvent asyncErrorEvent;
private const int LoginTimeout = 10000; // in ms
private Queue<string> asyncErrors;
private object asyncErrorsLock;
private Thread asyncErrorThread;
private Logger logger;
private enum ConnectionState
{
NotConnected,
WaitingForLogin,
Connected,
DisconnectInProgress,
}
private volatile ConnectionState connectionState;
#endregion
#region Accessors
public CiiAccessLevel GrantedAccess
{
get
{
return grantedAccess;
}
}
public bool IsConnected
{
get
{
return connectionState == ConnectionState.Connected;
}
}
#endregion
public CiiClient()
{
logger = Logger.Instance;
StatusCallbacks = new Dictionary<uint, ReceiveStatusHandler>();
statusCallbacksLock = new object();
loginAcceptEvent = new AutoResetEvent(false);
messagesInFlight = new CiiMessagesInFlight();
connectionState = ConnectionState.NotConnected;
//
// Prebuild the Communications arrays
//
MessageTypeGet = BitConverter.GetBytes((uint)CiiMessageType.MtGetCommand);
MessageTypeAction = BitConverter.GetBytes((uint)CiiMessageType.MtActionCommand);
BytesLogin = BitConverter.GetBytes((uint)CiiMessageType.MtLogin);
asyncErrorEvent = new AutoResetEvent(false);
asyncErrors = new Queue<string>();
asyncErrorsLock = new object();
asyncErrorThread = new Thread(AsyncErrorThread);
asyncErrorThread.IsBackground = true;
asyncErrorThread.Priority = ThreadPriority.AboveNormal;
asyncErrorThread.Name = "AsyncErrorThread";
asyncErrorThread.Start();
}
/// <summary>
/// This is the heart of the CII. This takes data blobs from the backend manager
/// and interprets it according to the spec.
/// </summary>
/// <remarks>
/// This is called by the backend connected to us. It needs to know about
/// the CiiClient. This always runs on a worker thread internal to this
/// library. A user should never call this.
/// </remarks>
/// <param name="buffer">The byte array where our data lives.</param>
/// <param name="dataLength">Length valid data in the array. (dataLength != buffer.Length)</param>
public void RouteReceivedMessage(byte[] buffer, int dataLength)
{
uint sequenceNumber;
uint statusCode;
uint subcommand;
CiiMessageTracker messageTracker;
uint substatus;
CiiMessageType type = (CiiMessageType)BitConverter.ToUInt32(buffer, 0);
switch (type)
{
case CiiMessageType.MtAccept:
logger.Log("ACCEPT", buffer, dataLength);
grantedAccess = (CiiAccessLevel)BitConverter.ToInt32(buffer, 4);
loginAcceptEvent.Set();
break;
case CiiMessageType.MtAck:
logger.Log("ACK", buffer, dataLength);
sequenceNumber = BitConverter.ToUInt32(buffer, 4);
messageTracker = messagesInFlight.Retrieve(sequenceNumber);
if (messageTracker == null)
{
SendAsyncError("Protocol Failure - Unexpected ACK");
break;
}
if (messageTracker.AckReceived)
{
//
// Error! Double ACK!
//
messagesInFlight.Delete(sequenceNumber);
SendAsyncError("Protocol Failure - Double ACK");
break;
}
else
{
messageTracker.AckReceived = true;
}
if ((messageTracker.Completion != null) && (messageTracker.Completion.AckHandler != null))
{
messageTracker.Completion.AckHandler(
messageTracker.Completion.UserData,
sequenceNumber);
}
else
{
Debug.WriteLine("Discarding ACK for Sequence # " + sequenceNumber);
}
break;
case CiiMessageType.MtNak:
logger.Log("NAK", buffer, dataLength);
sequenceNumber = BitConverter.ToUInt32(buffer, 4);
statusCode = BitConverter.ToUInt32(buffer, 8);
messageTracker = messagesInFlight.Retrieve(sequenceNumber);
if (messageTracker == null)
{
SendAsyncError("Protocol Failure - Unexpected NAK");
break;
}
messagesInFlight.Delete(sequenceNumber);
if (messageTracker.AckReceived)
{
//
// Error! ACK / NAK!
//
SendAsyncError("Protocol Failure - ACK - NAK");
break;
}
if ((messageTracker.Completion != null) && (messageTracker.Completion.NakHandler != null))
{
messageTracker.Completion.NakHandler(
messageTracker.Completion.UserData,
sequenceNumber,
statusCode);
}
else
{
Debug.WriteLine("Discarding NAK for Sequence # " + sequenceNumber);
}
messageTracker = null;
break;
case CiiMessageType.MtResponse:
logger.Log("RSP", buffer, dataLength);
sequenceNumber = BitConverter.ToUInt32(buffer, 4);
subcommand = BitConverter.ToUInt32(buffer, 8);
statusCode = BitConverter.ToUInt32(buffer, 12);
messageTracker = messagesInFlight.Retrieve(sequenceNumber);
if (messageTracker == null)
{
SendAsyncError("Protocol Failure - Unexpected RSP");
break;
}
messagesInFlight.Delete(sequenceNumber);
if (!messageTracker.AckReceived)
{
//
// Error! No ACK!
//
SendAsyncError("Protocol Failure - Missing ACK");
break;
}
if ((messageTracker.Completion != null) && (messageTracker.Completion.ResponseHandler != null))
{
messageTracker.Completion.ResponseHandler( messageTracker.Completion.UserData,
sequenceNumber,
subcommand,
statusCode,
buffer,
16,
dataLength - 16);
}
else
{
Debug.WriteLine("Discarding RSP for Sequence # " + sequenceNumber);
}
break;
case CiiMessageType.MtStatus:
logger.Log("STAT", buffer, dataLength);
substatus = BitConverter.ToUInt32(buffer, 4);
if (connectionState != ConnectionState.Connected)
{
Debug.WriteLine("Throwing away early status message");
break;
}
lock (statusCallbacksLock)
{
ReceiveStatusHandler callback;
StatusCallbacks.TryGetValue(substatus, out callback);
if ((callback != null) && (dataLength >= 8))
{
callback(substatus, buffer, 8, dataLength - 8);
}
else if ((UnhandledStatusCallback != null) && (dataLength >= 8))
{
UnhandledStatusCallback(substatus, buffer, 8, dataLength - 8);
}
}
break;
//
// We should never see another type of message here.
// This is an asymetric protocol between client and server.
//
default:
logger.Log("UNKNOWN", buffer, dataLength);
SendAsyncError("Unknown MessageType! " + type.ToString());
break;
}
}
#region Connect / Disconnect
/// <summary>
/// Client invoked code.
/// </summary>
/// <param name="requestedAccess"></param>
/// <returns></returns>
public bool Connect(CiiAccessLevel requestedAccess)
{
if (connectionState != ConnectionState.NotConnected)
{
return false;
}
bool success = BackEndManager.Connect();
if (success)
{
connectionState = ConnectionState.WaitingForLogin;
success = Login(requestedAccess);
if (success)
{
connectionState = ConnectionState.Connected;
ConnectEventHandler callbacks = ConnectEvent;
if (callbacks != null)
{
callbacks(this, new EventArgs());
}
}
else
{
BackEndManager.Disconnect();
connectionState = ConnectionState.NotConnected;
}
}
return success;
}
/// <summary>
/// Client invoked code.
/// </summary>
public void Disconnect()
{
if (connectionState == ConnectionState.Connected)
{
connectionState = ConnectionState.DisconnectInProgress;
messagesInFlight.Clear();
BackEndManager.Disconnect();
connectionState = ConnectionState.NotConnected;
DisconnectEventHandler callbacks = DisconnectEvent;
if (callbacks != null)
{
callbacks(this, new EventArgs());
}
}
}
public event ConnectEventHandler ConnectEvent;
public event DisconnectEventHandler DisconnectEvent;
public event DisconnectWarningEventHandler DisconnectWarning;
public event DisconnectErrorEventHandler DisconnectError;
private int warningDelay = 5;
private int errorDelay = 30;
public void SetCommFailureTimeouts(int warningDelay, int errorDelay)
{
if (warningDelay <= 0)
{
return;
}
if (errorDelay <= warningDelay)
{
return;
}
this.warningDelay = warningDelay;
this.errorDelay = errorDelay;
}
//
// This is running on the existing ReaderThread...
//
private void AsyncUnexpectedDisconnectHandler(object sender, EventArgs e)
{
messagesInFlight.Clear();
if (connectionState != ConnectionState.Connected)
{
//
// If we haven't established a good connection, DON'T try
// to recover!!!
//
Debug.WriteLine(
"CiiClient.AsyncUnexpectedDisconnectHandler() leaving early, not connected."
+ connectionState.ToString());
return;
}
DisconnectEventHandler callbacks = DisconnectEvent;
if (callbacks != null)
{
callbacks(this, new EventArgs());
}
connectionState = ConnectionState.NotConnected;
bool Success;
int delayInMs = 1000;
bool warningSent = false;
DateTime start = DateTime.Now;
TimeSpan errorTimeSpan = TimeSpan.FromSeconds(errorDelay);
TimeSpan warningTimeSpan = TimeSpan.FromSeconds(warningDelay);
do
{
Debug.WriteLine("CiiClient.AsyncUnexpectedDisconnectHandler waiting " + delayInMs + "ms");
Thread.Sleep(delayInMs);
Success = Connect(grantedAccess);
DateTime end = DateTime.Now;
if (!Success)
{
TimeSpan diff = end - start;
//
// We know that "errorDelay > warningDelay > 0".
//
if (TimeSpan.Compare(errorTimeSpan, diff) < 0)
{
Debug.WriteLine(
"CiiClient.AsyncUnexpectedDisconnectHandler() dispatching error");
DisconnectErrorEventHandler err = DisconnectError;
if (err != null)
{
err(this, new EventArgs());
}
Debug.WriteLine(
"CiiClient.AsyncUnexpectedDisconnectHandler() Aborting retries.");
return;
}
else if (TimeSpan.Compare(warningTimeSpan, diff) < 0)
{
if (warningSent)
{
continue;
}
else
{
warningSent = true;
}
Debug.WriteLine(
"CiiClient.AsyncUnexpectedDisconnectHandler() dispatching warning.");
DisconnectWarningEventHandler warn = DisconnectWarning;
if (warn != null)
{
warn(this, new EventArgs());
}
}
}
} while (!Success);
Debug.WriteLine("---CiiClient.BackendManagerDisconnectHandler()");
}
#endregion
#region Status Callback code
/// <summary>
/// Synchronizes adding Status callbacks with calling them.
/// </summary>
private object statusCallbacksLock;
private Dictionary<uint, ReceiveStatusHandler> StatusCallbacks;
private ReceiveStatusHandler UnhandledStatusCallback;
public bool RegisterStatusHandler(uint statusMessage, ReceiveStatusHandler statusDelegate)
{
lock (statusCallbacksLock)
{
if (StatusCallbacks.ContainsKey(statusMessage))
{
return false;
}
StatusCallbacks.Add(statusMessage, statusDelegate);
}
return true;
}
public bool RegisterUnhandledStatusHandler(ReceiveStatusHandler statusDelegate)
{
lock (statusCallbacksLock)
{
if (UnhandledStatusCallback != null)
{
return false;
}
UnhandledStatusCallback = statusDelegate;
}
return true;
}
#endregion
#region Backend Manager Interface
private IClientBackEndManager backEndManager;
protected IClientBackEndManager BackEndManager
{
//
// Only intended to be called once ever.
//
set
{
Debug.Assert(backEndManager == null);
backEndManager = value;
backEndManager.AsyncDisconnectEvent += AsyncUnexpectedDisconnectHandler;
}
get
{
return backEndManager;
}
}
#endregion
private bool Login(CiiAccessLevel requestedAccess)
{
byte[] LoginBuffer;
byte[] MyAddress = BackEndManager.GetLocalAddress();
byte[] Access = BitConverter.GetBytes((uint)requestedAccess);
int CopyLength;
#if WindowsCE
byte[] Username = System.Text.Encoding.UTF8.GetBytes("Display");
byte[] MachineName = System.Text.Encoding.UTF8.GetBytes("Cortex");
#else
byte[] Username = System.Text.Encoding.UTF8.GetBytes(Environment.UserName);
byte[] MachineName = System.Text.Encoding.UTF8.GetBytes(Environment.MachineName);
#endif
LoginBuffer = new byte[BytesLogin.Length + Access.Length + MyAddress.Length + 64 + 64];
Array.Copy(BytesLogin, 0, LoginBuffer, 0, BytesLogin.Length);
Array.Copy(Access, 0, LoginBuffer, 4, Access.Length);
Array.Copy(MyAddress, 0, LoginBuffer, 8, MyAddress.Length);
CopyLength = Username.Length > 64 ? 64 : Username.Length;
Array.Copy(Username, 0, LoginBuffer, 12, CopyLength);
CopyLength = MachineName.Length > 64 ? 64 : MachineName.Length;
Array.Copy(MachineName, 0, LoginBuffer, 76, CopyLength);
loginAcceptEvent.Reset();
logger.Log("LOGIN", LoginBuffer, LoginBuffer.Length);
bool Success = BackEndManager.SendMessage(LoginBuffer);
if (!Success)
{
SendAsyncError("Failed Login!");
}
else
{
Success = loginAcceptEvent.WaitOne(LoginTimeout, false);
if (!Success)
{
SendAsyncError("Login Accept timed out! " + LoginTimeout + " ms");
}
}
return Success;
}
#region Send Actions and Gets
private bool SendCommand( byte[] type,
uint subcommand,
byte[] data,
CommandCompletion completion,
out uint sequenceNumber)
{
if (connectionState != ConnectionState.Connected)
{
Debug.WriteLine("Failing SendCommand() - not connected!");
sequenceNumber = 0;
return false;
}
uint newSequenceNumber = messagesInFlight.SequenceNumber;
byte[] sequenceBytes = BitConverter.GetBytes(newSequenceNumber);
byte[] subcommandBytes = BitConverter.GetBytes(subcommand);
byte[] SendBuffer;
sequenceNumber = newSequenceNumber;
//
// Can't optimize this, we need a single buffer to send.
// We have to do the memcpy.
//
if (data != null)
{
SendBuffer = new byte[type.Length +
sequenceBytes.Length +
subcommandBytes.Length +
data.Length];
}
else
{
SendBuffer = new byte[type.Length +
sequenceBytes.Length +
subcommandBytes.Length];
}
int destIndex = 0;
Array.Copy(type, 0, SendBuffer, destIndex, type.Length);
destIndex += type.Length;
Array.Copy(sequenceBytes, 0, SendBuffer, destIndex, sequenceBytes.Length);
destIndex += sequenceBytes.Length;
Array.Copy(subcommandBytes, 0, SendBuffer, destIndex, subcommandBytes.Length);
if (data != null)
{
destIndex += subcommandBytes.Length;
Array.Copy(data, 0, SendBuffer, destIndex, data.Length);
}
logger.Log("COMMAND", SendBuffer, SendBuffer.Length);
messagesInFlight.Add(newSequenceNumber, completion);
bool Success = backEndManager.SendMessage(SendBuffer);
if (!Success)
{
messagesInFlight.Delete(newSequenceNumber);
sequenceNumber = 0;
}
return Success;
}
public bool SendActionCommand( uint subcommand,
byte[] data,
CommandCompletion completion,
out uint sequenceNumber)
{
if ((grantedAccess == CiiAccessLevel.AlEngineering) ||
(grantedAccess == CiiAccessLevel.AlMaster) ||
(grantedAccess == CiiAccessLevel.AlLocalUI))
{
return SendCommand(MessageTypeAction, subcommand, data, completion, out sequenceNumber);
}
else
{
sequenceNumber = 0;
return false;
}
}
public bool SendActionCommand(uint subcommand,
byte[] data,
CommandCompletion completion)
{
uint sequenceNumber;
return SendActionCommand(subcommand, data, completion, out sequenceNumber);
}
public bool SendGetCommand(uint subcommand,
byte[] data,
CommandCompletion completion,
out uint sequenceNumber)
{
return SendCommand(MessageTypeGet, subcommand, data, completion, out sequenceNumber);
}
public bool SendGetCommand(uint subcommand,
byte[] data,
CommandCompletion completion)
{
uint sequenceNumber;
return SendGetCommand(subcommand, data, completion, out sequenceNumber);
}
#endregion
public void DeleteCommandInProgress(uint sequenceNumber)
{
messagesInFlight.Delete(sequenceNumber);
}
}
}