-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcortex.cpp
More file actions
1328 lines (1090 loc) · 39.2 KB
/
Copy pathcortex.cpp
File metadata and controls
1328 lines (1090 loc) · 39.2 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
/*=========================================================
//
// File: Cortex.cpp v200
//
// Created by Ned Phipps, Oct-2004
//
=============================================================================*/
/*! \file Cortex.cpp
This file implements the API for ethernet communication of data
between Cortex and multiple client programs.
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <ctype.h>
#include <netdb.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <pthread.h>
#include <semaphore.h>
#include <sys/errno.h>
#include "cortex.h" // Users will include this header
#include "m3x3.h"
#include "cortex_intern.h"
#include "cortex_socket.h"
#include "cortex_unpack.h"
//#include "cmetered.h"
const unsigned char MyVersionNumber[4] = { 4, 1, 3, 1 }; // ProgramID, Major, Minor, Bugfix
LOCAL int bInitialized = 0;
LOCAL sHostInfo HostInfo;
LOCAL int User_VerbosityLevel = VL_Warning;
LOCAL int SendToCortex(sPacket *Packet);
LOCAL void GetHostName_ASYNC();
LOCAL sBodyDefs* pNewBodyDefs = NULL;
LOCAL sPacket PacketOut;
LOCAL sPacket PacketIn_Frame;
LOCAL sPacket PacketIn;
//LOCAL char *pBodyDefBuffer = NULL; // Gets allocated the same size as the received packet.
LOCAL sFrameOfData LatestFrameOfData;
LOCAL sFrameOfData Polled_FrameOfData;
//LOCAL unsigned short wMyPort = 1600; // My outgoing port (Cortex auto-replies to me here)
LOCAL unsigned short wMyPort = 0; // Let the socket library find an available port
LOCAL unsigned short wCortexPort = 1002; // 1002; // Cortex is listening at this port
LOCAL unsigned short wMultiCastPort = 1001; // Cortex sends frames to this port and associated address
//LOCAL unsigned short wMultiCastPort = 1511; // Cortex sends frames to this port and associated address
//LOCAL in_addr MyNicCardAddress={ 10, 1, 2,199}; // My local IP address
//LOCAL in_addr MultiCastAddress={225, 1, 1, 1}; // Cortex sends frames to this address and associated port
// LOCAL in_addr MyNicCardAddress = { (10 << 24) + (1 << 16) + (2 << 8) + 199 }; // My local IP address
// LOCAL in_addr MultiCastAddress = { (225 << 24) + (1 << 16) + (1 << 8) + 1 }; // Cortex sends frames to this address and associated port
//LOCAL in_addr CortexNicCardAddress={0,0,0,0};
//LOCAL in_addr CortexNicCardAddress={255,255,255,255};
//LOCAL in_addr CortexNicCardAddress = { (255 << 24) + (255 << 16) + (255 << 8) + 255 };
/* ///////////////////////////// my addresses ///////////////////////// */
LOCAL in_addr MyNicCardAddress = { (10 << 24) + (1 << 16) + (1 << 8) + 200 }; // My local IP address
LOCAL in_addr MultiCastAddress = { 3774939393 };//{ (225 << 24) + (1<< 16) + (1 << 8) + 1 }; // Cortex sends frames to this address and associated port
// // convert IP address to integer;
//http://www.aboutmyip.com/AboutMyXApp/IP2Integer.jsp?ipAddress=255.255.255.1
// LOCAL in_addr CortexNicCardAddress = { (10 << 24) + (1 << 16) + (1 << 8) + 190 };
LOCAL in_addr CortexNicCardAddress = { (10 << 24) + (1 << 16) + (1 << 8) + 190 };
/* ///////////////////////////// my addresses ///////////////////////// */
LOCAL sockaddr_in CortexAddr; // This gets filled out when Cortex replies.
LOCAL SOCKET CommandSocket = -1;
LOCAL SOCKET MultiCastReaderSocket = -1;
// For use with waiting for replies from Cortex.
LOCAL sem_t EH_CommandConfirmed;
LOCAL pthread_t CortexListenThread_ID;
LOCAL void* CortexListenThread_Func(void *);
LOCAL pthread_t ReadDataThread_ID;
LOCAL void* ReadDataThread_Func(void *);
LOCAL pthread_t GetHostNameThread_ID;
// === Logging ===
void Dummy_CB_ErrorMsgHandler(int iLevel, const char *szMessage)
{
}
void
(*CB_ErrorMsgHandler)(int iLevel, const char *szMessage) = Dummy_CB_ErrorMsgHandler;
void LogMessage(int iLevel, const char *szMsg, ...)
{
if (iLevel <= User_VerbosityLevel) {
// create char* from input
char* str_tmp = NULL;
va_list arg_list;
va_start(arg_list, szMsg);
(void) vasprintf(&str_tmp, szMsg, arg_list);
CB_ErrorMsgHandler(iLevel, str_tmp);
free(str_tmp);
}
}
//=============================================================================
LOCAL void Dummy_CB_DataHandler(sFrameOfData *FrameOfData)
{
}
GLOBAL void (*CB_DataHandler)(sFrameOfData *FrameOfData) = Dummy_CB_DataHandler;
//=============================================================================
#if 0 // muellerj: not used
LOCAL int Broadcast(sPacket *Packet)
{
return Broadcast(CommandSocket, wCortexPort, (const char *) Packet, Packet->nBytes + 4);
}
#endif
void FoundHost()
{
HostInfo.bFoundHost = 1;
LogMessage(VL_Info,
"AutoConnected to: %s Version %d.%d.%d at %d.%d.%d.%d (%s)",
HostInfo.szHostProgramName, HostInfo.HostProgramVersion[1],
HostInfo.HostProgramVersion[2], HostInfo.HostProgramVersion[3],
HostInfo.HostMachineAddress[0], HostInfo.HostMachineAddress[1],
HostInfo.HostMachineAddress[2], HostInfo.HostMachineAddress[3],
HostInfo.szHostMachineName);
}
//===================================================================
//-------------------------------------------------------------------
LOCAL void* CortexListenThread_Func(void *)
{
//hostent *pHostEnt;
socklen_t addr_len;
int nBytesReceived;
int Count = 0;
sockaddr_in TheirAddress;
//memset(&CortexAddr, 0, sizeof(sockaddr_in));
addr_len = sizeof(struct sockaddr);
while (1) {
// Block further processing until we receive a datagram from anyone,
// including ourself, over the network.
// This thread will spend most if its time asleep in this recvfrom
// function.
nBytesReceived = recvfrom(CommandSocket, (char *) &PacketIn,
sizeof(sPacket), 0,
(struct sockaddr *) &TheirAddress, &addr_len);
LogMessage(VL_Debug, "Got reply of %d bytes of data", nBytesReceived);
// We shutdown and closed the socket from Cortex_Exit()
if (nBytesReceived == 0 || nBytesReceived == SOCKET_ERROR) {
break;
}
Count++;
if (memcmp(&TheirAddress.sin_addr.s_addr, HostInfo.HostMachineAddress, 4)
== 0) {
#if 0
if (!HostInfo.bFoundHost)
{
FoundHost();
}
#endif
LogMessage(VL_Debug, "Packet return address matches Cortex address");
HostInfo.LatestConfirmationTime = clock();
}
LogMessage(VL_Debug,
"CommandReplyReader received from %s: Command=%d, nBytes=%d",
inet_ntoa(TheirAddress.sin_addr), (int) PacketIn.iCommand,
(int) PacketIn.nBytes);
// First send SerialCommand Confirmation
// Now handle the data
switch (PacketIn.iCommand) {
case PKT2_HELLO_WORLD:
LogMessage(VL_Debug, "HELLO_WORLD: %s, Version %d.%d.%d",
PacketIn.Data.Me.szName,
//PacketIn.Data.Me.Version[0],
PacketIn.Data.Me.Version[1], PacketIn.Data.Me.Version[2],
PacketIn.Data.Me.Version[3]);
break;
case PKT2_HERE_I_AM:
if (*(unsigned long*) HostInfo.HostMachineAddress != 0
&& *(unsigned long*) HostInfo.HostMachineAddress != 0xFFFFFFFF
&& *(unsigned long*) HostInfo.HostMachineAddress
!= TheirAddress.sin_addr.s_addr) {
LogMessage(VL_Debug, "Ignoring HERE_I_AM message from another machine");
break;
}
LogMessage(VL_Debug, "HERE_I_AM message");
CortexAddr = TheirAddress;
strcpy(HostInfo.szHostProgramName, PacketIn.Data.Me.szName);
memcpy(HostInfo.HostProgramVersion, PacketIn.Data.Me.Version, 4);
memcpy(HostInfo.HostMachineAddress, &CortexAddr.sin_addr.s_addr, 4);
GetHostName_ASYNC();
if (!HostInfo.bFoundHost) {
FoundHost();
}
#if 0
LogMessage(VL_Debug, "HERE_I_AM: %s, Version %d.%d.%d",
PacketIn.Data.Me.szName,
//PacketIn.Data.Me.Version[0],
PacketIn.Data.Me.Version[1],
PacketIn.Data.Me.Version[2],
PacketIn.Data.Me.Version[3]);
#endif
break;
case PKT2_BODYDEFS:
pNewBodyDefs = Unpack_BodyDefs(PacketIn.Data.cData, PacketIn.nBytes);
sem_post(&EH_CommandConfirmed);
break;
case PKT2_FRAME_OF_DATA:
Unpack_FrameOfData(PacketIn.Data.cData, PacketIn.nBytes,
&Polled_FrameOfData);
//CB_DataHandler(&Polled_FrameOfData);
sem_post(&EH_CommandConfirmed);
break;
case PKT2_GENERAL_REPLY:
sem_post(&EH_CommandConfirmed);
break;
case PKT2_UNRECOGNIZED_REQUEST:
sem_post(&EH_CommandConfirmed);
break;
case PKT2_UNRECOGNIZED_COMMAND:
sem_post(&EH_CommandConfirmed);
break;
case PKT2_COMMENT:
LogMessage(VL_Debug, "COMMENT: %s\n", PacketIn.Data.String);
break;
default:
LogMessage(
VL_Warning,
"CommandReplyReader, unexpected value, PacketIn.iCommand== %d\n",
PacketIn.iCommand);
break;
}
}
// Unreachable
return 0;
}
//===================================================================
//-------------------------------------------------------------------
LOCAL void* ReadDataThread_Func(void *)
{
sockaddr_in TheirAddress;
socklen_t addr_len;
int nBytesReceived;
int Count = 0;
if (MultiCastReaderSocket != -1) {
close(MultiCastReaderSocket);
MultiCastReaderSocket = -1;
}
MultiCastReaderSocket = Socket_CreateLargeMultiCast(MyNicCardAddress,
wMultiCastPort,
MultiCastAddress);
if (MultiCastReaderSocket == -1) {
LogMessage(VL_Error, "Unable to initialize FrameReader");
return 0;
} else {
LogMessage(VL_Info, "Initialized multi-cast frame reader");
}
// TestRead(MultiCastReaderSocket);
memset(&TheirAddress, 0, sizeof(sockaddr));
memset(&LatestFrameOfData, 0, sizeof(sFrameOfData));
while (1) {
addr_len = sizeof(struct sockaddr);
// Block further processing until we receive a datagram from anyone,
// including ourself, over the network.
// This thread should spend most if its time asleep in this recvfrom
// function.
nBytesReceived = recvfrom(MultiCastReaderSocket, (char *) &PacketIn_Frame,
sizeof(sPacket), 0, (sockaddr *) &TheirAddress,
&addr_len);
LogMessage(VL_Debug, "Multicast: received %d bytes of data\n",
nBytesReceived);
// We shutdown and closed the socket from Cortex_Exit()
if (nBytesReceived == 0 || nBytesReceived == SOCKET_ERROR) {
break;
}
Count++;
if (memcmp(&TheirAddress.sin_addr.s_addr, HostInfo.HostMachineAddress, 4)
== 0) {
// Officially? found on the OTHER socket, since that's where we make the requests.
if (!HostInfo.bFoundHost) {
FoundHost();
}
//HostInfo.bFoundHost = 1;
LogMessage(VL_Debug,
"MultiCast packet return address matches Cortex host address");
HostInfo.LatestConfirmationTime = clock();
} else {
LogMessage(VL_Debug, "MultiCastReader Ignoring packet from %s",
inet_ntoa(TheirAddress.sin_addr));
continue;
}
LogMessage(VL_Debug,
"MultiCastReader Received From %s: Command=%d, nBytes=%d",
inet_ntoa(TheirAddress.sin_addr), (int) PacketIn_Frame.iCommand,
(int) PacketIn_Frame.nBytes);
// First send SerialCommand Confirmation
// Now handle the data
switch (PacketIn_Frame.iCommand) {
case PKT2_FRAME_OF_DATA:
Unpack_FrameOfData(PacketIn_Frame.Data.cData, PacketIn_Frame.nBytes,
&LatestFrameOfData);
// if (g_Meterer.IsActive()) {
// g_Meterer.StoreFrame(&LatestFrameOfData);
// } else {
CB_DataHandler(&LatestFrameOfData);
// }
break;
case PKT2_HELLO_WORLD:
case PKT2_HERE_I_AM:
if (PacketIn_Frame.Data.Me.Version[0] != 1) // Not from Cortex: Ignore it
break;
//if (HostInfo.HostMachineAddress[0] == 0)
if (*(unsigned long*) HostInfo.HostMachineAddress == 0
|| *(unsigned long*) HostInfo.HostMachineAddress == 0xFFFFFFFF
|| *(unsigned long*) HostInfo.HostMachineAddress
== TheirAddress.sin_addr.s_addr) {
CortexAddr.sin_addr.s_addr = TheirAddress.sin_addr.s_addr;
memcpy(&HostInfo.HostMachineAddress, &TheirAddress.sin_addr.s_addr, 4);
strcpy(HostInfo.szHostProgramName, PacketIn_Frame.Data.Me.szName);
memcpy(&HostInfo.HostProgramVersion, PacketIn_Frame.Data.Me.Version, 4);
GetHostName_ASYNC();
if (!HostInfo.bFoundHost) {
FoundHost();
}
#if 0
HostInfo.bFoundHost = 1;
LogMessage(VL_Info, "AutoConnected to: %s Version %d.%d.%d at %d.%d.%d.%d (%s)",
HostInfo.szHostProgramName,
HostInfo.HostProgramVersion[1],
HostInfo.HostProgramVersion[2],
HostInfo.HostProgramVersion[3],
HostInfo.HostMachineAddress[0],
HostInfo.HostMachineAddress[1],
HostInfo.HostMachineAddress[2],
HostInfo.HostMachineAddress[3],
HostInfo.szHostMachineName);
#endif
}
break;
case PKT2_COMMENT:
LogMessage(VL_Debug, "DataStream Comment: %s\n",
PacketIn_Frame.Data.String);
break;
}
}
// Unreachable
return 0;
}
//===================================================================
//-------------------------------------------------------------------
LOCAL int Initialize_ListenForReplies()
{
if (CommandSocket != -1) {
return OK;
}
LogMessage(VL_Debug, "Creating Socket for commands");
CommandSocket
= Socket_CreateForBroadcasting(MyNicCardAddress.s_addr, wMyPort);
if (CommandSocket == -1) {
LogMessage(VL_Error, "Unable to initialize SDK Sockets.");
return RC_NetworkError;
}
int status = pthread_create(&CortexListenThread_ID, NULL,
CortexListenThread_Func, NULL);
if (status != 0) {
LogMessage(VL_Error,
"%s: pthread_create error starting CortexListenThread thread",
__PRETTY_FUNCTION__);
}
return OK;
}
#if 0
int TestRead(SOCKET socket)
{
sockaddr TheirAddress;
int addr_len;
int nBytesReceived;
int Count=0;
memset(&TheirAddress, 0, sizeof(sockaddr));
addr_len = sizeof(struct sockaddr);
// Block further processing until we receive a datagram from anyone,
nBytesReceived = recvfrom(
socket,
(char *)&PacketIn,
sizeof(sPacket),
0,
&TheirAddress,
&addr_len);
printf("Received MultiCast of %d bytes.\n", nBytesReceived);
return nBytesReceived;
}
#endif
//===================================================================
//-------------------------------------------------------------------
LOCAL int Initialize_ListenForFramesOfData()
{
int status = pthread_create(&ReadDataThread_ID, NULL, ReadDataThread_Func,
NULL);
if (status != 0) {
LogMessage(
VL_Error,
"Initialize_ListenForFramesOfData(), pthread_create error starting ReadDataThread thread");
}
return OK;
}
//==================================================================
/** This function defines the connection routes to talk to Cortex.
*
* Machines can have more than one ethernet interface. This function
* is used to either set the ethernet interface to use, or to let
* the SDK auto-select the local interface, and/or the Cortex host.
* This function should only be called once at startup.
*
* \param szMyNicCardAddress - "a.b.c.d" or HostName. "" and NULL mean AutoSelect
*
* \param szCortexNicCardAddress - "a.b.c.d" or HostName. "" and NULL mean AutoSelect
*
* \return maReturnCode - RC_Okay, RC_ApiError, RC_NetworkError, RC_GeneralError
*/
int Cortex_Initialize(const char* szMyNicCardAddress,
const char* szCortexNicCardAddress)
{
int retval;
in_addr MyAddresses[10];
int nAddresses;
// Initialization only happens once.
if (bInitialized) {
LogMessage(VL_Warning, "Already Initialized");
return RC_GeneralError;
}
nAddresses = Cortex_GetAllOfMyAddresses((unsigned long *) MyAddresses, 10);
if (nAddresses < 0) {
LogMessage(VL_Error, "Unable to find my own machine");
return RC_NetworkError;
} else if (nAddresses == 0) {
LogMessage(VL_Error, "This machine has no ethernet interfaces");
return RC_NetworkError;
}
if (szMyNicCardAddress == NULL || szMyNicCardAddress[0] == 0) {
if (nAddresses > 1) {
LogMessage(
VL_Warning,
"The local machine has more than one ethernet interface. Using the first one found.");
}
MyNicCardAddress = MyAddresses[0];
LogMessage(VL_Info, "Initializing using my default ethernet address: %s",
inet_ntoa(MyNicCardAddress));
} else {
retval = ConvertToIPAddress(szMyNicCardAddress, &MyNicCardAddress);
if (retval != OK) {
LogMessage(VL_Error, "Unable to find MyNicCardAddress \"%s\"",
szMyNicCardAddress);
Cortex_Exit();
return RC_NetworkError;
}
LogMessage(VL_Info, "Initializing using my address: %s",
inet_ntoa(MyNicCardAddress));
}
if (ConvertToIPAddress(szCortexNicCardAddress, &CortexNicCardAddress) != OK) {
LogMessage(VL_Error, "Unable to convert \"%s\" to IP Address for Cortex",
szCortexNicCardAddress);
return RC_NetworkError;
}
memset(&CortexAddr, 0, sizeof(CortexAddr));
CortexAddr.sin_family = AF_INET; // host byte order
CortexAddr.sin_port = htons(wCortexPort); // short, network byte order
CortexAddr.sin_addr = CortexNicCardAddress;
LogMessage(VL_Info, "Initializing using Cortex host address: %s",
inet_ntoa(CortexNicCardAddress));
memset(&HostInfo, 0, sizeof(sHostInfo));
memcpy(HostInfo.HostMachineAddress, &CortexNicCardAddress, 4);
memset(&Polled_FrameOfData, 0, sizeof(sFrameOfData));
memset(&LatestFrameOfData, 0, sizeof(sFrameOfData));
// Get the semaphore technique initialized (CL)
if (sem_init(&EH_CommandConfirmed, 0, 0) != 0) {
LogMessage(VL_Error, "Unable to initialize semaphore: %d", errno);
}
Initialize_ListenForReplies();
usleep(10000);
Initialize_ListenForFramesOfData();
usleep(10000); // Give the ListenThread time to be ready for an answer to the startup packet
// Let the world know we are here.
PacketOut.iCommand = PKT2_HELLO_WORLD;
PacketOut.nBytes = sizeof(sMe);
strcpy(PacketOut.Data.Me.szName, "ClientTest");
memcpy(PacketOut.Data.Me.Version, MyVersionNumber, 4);
//Broadcast(&PacketOut);
//Broadcast(CommandSocket, wCortexPort, (char *)&PacketOut, PacketOut.nBytes + 4);
// At this point, if szCortexNicCardAddress was not specified,
// then CortexAddr should be the broadcast address.
// The ListenForReplies thread will hear the response and get the actual address
SendToCortex(&PacketOut);
usleep(100000); // sleep until threads are running
bInitialized = 1;
return RC_Okay;
}
//==================================================================
/** The user supplied function will be called whenever a frame of data arrives.
*
* The ethernet servicing is done via a thread created
* when the connection to Cortex is made. This function is
* called from that thread. Some tasks are not sharable
* directly across threads. Window redrawing, for example,
* should be done via events or messages.
*
* \param MyFunction - This user supply callback function handles the streaming data
*
* \return maReturnCode - RC_Okay
*
* Notes: The data parameter points to "hot" data. That frame of data
* will be overwritten with the next call to the callback function.
*/
int Cortex_SetDataHandlerFunc(void(*MyFunction)(sFrameOfData *FrameOfData))
{
CB_DataHandler = MyFunction;
return RC_Okay;
}
//==================================================================
/** The user supplied function handles text messages posted from within the SDK.
*
* Logging messages is done as a utility to help code and/or run using the SDK.
* Various messages get posted for help with error conditions or events that happen.
* Each message has a Log-Level assigned to it so the user can.
* \sa Cortex_SetVerbosityLevel
*
*
* \param MyFunction - This user defined function handles messages from the SDK.
*
* \return maReturnCode - RC_Okay
*/
int Cortex_SetErrorMsgHandlerFunc(void(*MyFunction)(int iLogLevel,
const char *szLogMessage))
{
CB_ErrorMsgHandler = MyFunction;
return RC_Okay;
}
//==================================================================
/** This function stops all activity of the SDK.
*
* This function should be called once before exiting.
*/
int Cortex_Exit()
{
if (!bInitialized) {
return -1;
}
// Close sockets first, this will cause the threads to exit their functions
if (CommandSocket != -1) {
close(CommandSocket);
CommandSocket = -1;
}
if (MultiCastReaderSocket != -1) {
close(MultiCastReaderSocket);
MultiCastReaderSocket = -1;
}
//TODO: kill threads
bInitialized = 0;
return 0;
}
//==================================================================
/** This function queries Cortex for its set of tracking objects.
*
* \return sBodyDefs* - This is a pointer to the internal storage of
* the results of the latest call to this function.
*
* \sa Cortex_FreeBodyDefs
*/
sBodyDefs* Cortex_GetBodyDefs()
{
int nTries = 3;
PacketOut.iCommand = PKT2_REQUEST_BODYDEFS;
PacketOut.nBytes = 0;
// Sleep for a long enough time to expect a response
// Currently set to 20 ms.
// Set semaphore to wait for response.
while (nTries--) {
// In Linux, POSIX semaphores are of the auto-reset type
// ResetEvent(EH_CommandConfirmed);
SendToCortex(&PacketOut);
// Sleep for a long enough time to expect a response
int count = 10000;
while (count--) {
int retCode = sem_trywait(&EH_CommandConfirmed);
if (!retCode) {
/* Event is signaled */
return pNewBodyDefs;
} else {
/* check whether somebody else has the semaphore locked */
if (errno == EAGAIN) {
usleep(10); /* sleep for 10us */
} else {
LogMessage(VL_Debug,
"Error in semaphore timeout in GetBodyDefs (error %d)",
errno);
}
}
}
}
LogMessage(VL_Error, "No response from Cortex");
return NULL;
}
//==================================================================
/** This function frees the memory allocated by Cortex_GetBodyDefs
*
* The data within the structure is freed and also the structure itself.
* \param pBodyDefs - The item to free.
*
* \return RC_Okay
*/
int Cortex_FreeBodyDefs(sBodyDefs* pBodyDefs)
{
int nBodies = pBodyDefs->nBodyDefs;
int iBody;
for (iBody = 0; iBody < nBodies; iBody++) {
sBodyDef *pBody = &pBodyDefs->BodyDefs[iBody];
// Free each array of pointers to the names
if (pBody->szMarkerNames != NULL)
free(pBody->szMarkerNames);
if (pBody->Hierarchy.szSegmentNames != NULL)
free(pBody->Hierarchy.szSegmentNames);
if (pBody->Hierarchy.iParents != NULL)
free(pBody->Hierarchy.iParents);
if (pBody->szDofNames != NULL)
free(pBody->szDofNames);
}
if (pBodyDefs->szAnalogChannelNames != NULL)
free(pBodyDefs->szAnalogChannelNames);
// Free the big space that contains all the names
if (pBodyDefs->AllocatedSpace != NULL)
free(pBodyDefs->AllocatedSpace);
memset(pBodyDefs, 0, sizeof(sBodyDef)); // not needed anymore
free(pBodyDefs);
return RC_Okay;
}
//==================================================================
/** This function returns a 4-byte version number.
*
* \param Version - An array of four bytes: ModuleID, Major, Minor, Bugfix
*
* \return RC_Okay
*/
int Cortex_GetSdkVersion(unsigned char Version[4])
{
memcpy(Version, MyVersionNumber, 4);
return RC_Okay;
}
//==================================================================
/** This function sends commands to Cortex and returns a response.
*
* This function is an extendable interface between the Client programs
* and the Host (Cortex) program. The commands are sent as readable text strings.
* The response is returned unaltered.
*
* \param szCommand - The request to send the Cortex
* \param Response - The reply
* \param pnBytes - The number of bytes in the response
*
\verbatim
Example:
void *pResponse=NULL;
Cortex_Request("GetFrameRate", &pResponse, sizeof(void*));
fFrameRate = *(float*)pResponse;
\endverbatim
*
* \return RC_Okay, RC_TimeOut, RC_NotRecognized, RC_GeneralError
*/
int Cortex_Request(const char* szCommand, void** Response, int *pnBytes)
{
const char* FRAME_QUERY = "GetFrameOfData";
int nTries = 10;
int expectingFrame = 0;
*pnBytes = 0;
LogMessage(VL_Debug, "Requesting: %s", szCommand);
PacketOut.iCommand = PKT2_GENERAL_REQUEST;
PacketOut.nBytes = (int) strlen(szCommand) + 1;
strcpy(PacketOut.Data.String, szCommand);
// Is this a request for a frame of data
if (strncmp(szCommand, FRAME_QUERY, strlen(FRAME_QUERY)) == 0) {
expectingFrame = 1;
}
while (nTries--) {
SendToCortex(&PacketOut);
int count = 10000;
while (count--) {
int retCode = sem_trywait(&EH_CommandConfirmed);
if (!retCode) {
if (PacketIn.iCommand == PKT2_GENERAL_REPLY) {
*Response = PacketIn.Data.cData;
*pnBytes = PacketIn.nBytes;
return RC_Okay;
} else if (PacketIn.iCommand == PKT2_FRAME_OF_DATA && expectingFrame) {
*Response = &Polled_FrameOfData;
*pnBytes = PacketIn.nBytes;
return RC_Okay;
} else if (PacketIn.iCommand == PKT2_UNRECOGNIZED_REQUEST) {
*Response = NULL;
return RC_Unrecognized;
} else {
return RC_GeneralError;
}
}
usleep(10); // wait because response not yet available
}
}
LogMessage(VL_Warning, "Cortex_Request, Request Timeout");
*Response = NULL;
return RC_TimeOut;
}
//==================================================================
/** This function sets the filter level of the LogMessages.
*
* The default verbosity level is VL_Warning.
*
* \param iLevel - one of the maVerbosityLevel enum values.
*
* \return RC_Okay
*/
int Cortex_SetVerbosityLevel(int iLevel)
{
User_VerbosityLevel = iLevel;
return RC_Okay;
}
//==================================================================
/** This function gets information about the connection to Cortex
*
* This function returns IP-Address information and Cortex version information.
* The version info can be used to handle incompatible changes in either our code
* or your code.
*
* \param pHostInfo - Structure containing connection information
*
* \return RC_Okay, RC_NetworkError
*/
int Cortex_GetHostInfo(sHostInfo *pHostInfo)
{
if (HostInfo.HostMachineAddress[0] == 0) {
return RC_NetworkError;
}
memcpy(pHostInfo, &HostInfo, sizeof(sHostInfo));
return RC_Okay;
}
//==================================================================
/** This function polls Cortex for the current frame
*
* The SDK user has the streaming data available via the callback function.
* In addition, this function is available to get a frame directly.
*
* Note: Cortex considers the current frame to be the latest LiveMode frame completed or,
* if not in LiveMode, the current frame is the one that is displayed on the screen.
*
* \return sFrameOfData
*/
sFrameOfData* Cortex_GetCurrentFrame()
{
PacketOut.iCommand = PKT2_REQUEST_FRAME;
PacketOut.nBytes = 0;
int bytesSent = SendToCortex(&PacketOut);
LogMessage(VL_Debug, "Cortex_GetCurrentFrame(), SendToCortex sent %d bytes",
bytesSent);
int nTries = 2000;
while (nTries--) {
int retCode = sem_trywait(&EH_CommandConfirmed);
if (!retCode) {
if (PacketIn.iCommand == PKT2_FRAME_OF_DATA) {
LogMessage(VL_Debug, "FRAME_OF_DATA message");
return &Polled_FrameOfData;
} else if (PacketIn.iCommand == PKT2_GENERAL_REPLY) {
LogMessage(VL_Debug, "GENERAL_REPLY message");
}
} else {
if (errno == EAGAIN) { // semaphore still locked
usleep(10);
} else {
LogMessage(VL_Debug,
"Error in semaphore timeout in GetCurrentFrame: %s",
strerror(errno));
}
}
}
return NULL;
}
//==================================================================
/** This function copies a frame of data.
*
* The Destination frame should start initialized to all zeros. The CopyFrame
* and FreeFrame functions will handle the memory allocations necessary to fill
* out the data.
*
* \param pSrc - The frame to copy FROM.
* \param pDst - The frame to copy TO
*
* \return RC_Okay, RC_MemoryError
*/
int Cortex_CopyFrame(const sFrameOfData* pSrc, sFrameOfData* pDst)
{
int iBody;
int nBodies = pSrc->nBodies;
const sBodyData* SrcBody;
sBodyData* DstBody;
int n;
void *ptr;
int size;
pDst->iFrame = pSrc->iFrame;
pDst->nBodies = nBodies;
for (iBody = 0; iBody < nBodies; iBody++) {
SrcBody = &pSrc->BodyData[iBody];
DstBody = &pDst->BodyData[iBody];
// Copy Markers
n = SrcBody->nMarkers;
size = n * sizeof(tMarkerData);
if (DstBody->nMarkers != n) {
ptr = realloc(DstBody->Markers, size);
if (size > 0 && ptr == NULL) {
Cortex_FreeFrame(pDst);
return RC_MemoryError;
}
DstBody->nMarkers = n;
DstBody->Markers = (tMarkerData*) ptr;
}
memcpy(DstBody->Markers, SrcBody->Markers, size);
// Copy Segments
n = SrcBody->nSegments;
size = n * sizeof(tSegmentData);
if (DstBody->nSegments != n) {
ptr = realloc(DstBody->Segments, size);
if (size > 0 && ptr == NULL) {
Cortex_FreeFrame(pDst);