/
orbuculum.c
1499 lines (1198 loc) · 46 KB
/
orbuculum.c
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
/* SPDX-License-Identifier: BSD-3-Clause */
/*
* Orbuculum main receiver and TPIU demux
* ======================================
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <ctype.h>
#include <assert.h>
#ifdef WIN32
#include <winsock2.h>
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <libgen.h>
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <strings.h>
#include <string.h>
#include <pthread.h>
#include <getopt.h>
#if defined OSX
#include <sys/ioctl.h>
#include <libusb.h>
#include <termios.h>
#elif defined LINUX
#include <libusb-1.0/libusb.h>
#include <asm/ioctls.h>
#if defined TCGETS2
#include <asm/termios.h>
/* Manual declaration to avoid conflict. */
extern int ioctl ( int __fd, unsigned long int __request, ... ) ;
#else
#include <sys/ioctl.h>
#include <termios.h>
#endif
#elif defined FREEBSD
#include <libusb.h>
#include <sys/ioctl.h>
#include <termios.h>
#elif defined WIN32
#include <libusb.h>
#else
#error "Unknown OS"
#endif
#include <signal.h>
#include "git_version_info.h"
#include "generics.h"
#include "tpiuDecoder.h"
#include "nwclient.h"
#include "orbtraceIf.h"
#include "stream.h"
#ifndef O_BINARY
#define O_BINARY 0
#endif
/* How many transfer buffers from the source to allocate */
#define NUM_RAW_BLOCKS (32)
#define MAX_LINE_LEN (1024)
#define ORBTRACE "orbtrace"
#define ORBTRACEENVNAME "ORBTRACE"
/* Record for options, either defaults or from command line */
struct Options
{
/* Config information */
bool nwserver; /* Using a nw server source */
/* Source information */
char *nwserverHost; /* NW Server host connection */
int32_t nwserverPort; /* ...and port */
char *port; /* Serial host connection */
int speed; /* Speed of serial link */
bool useTPIU; /* Are we using TPIU, and stripping TPIU frames? */
uint32_t dataSpeed; /* Effective data speed (can be less than link speed!) */
char *file; /* File host connection */
bool fileTerminate; /* Terminate when file read isn't successful */
char *outfile; /* Output file for raw data dumping */
char *otcl; /* Orbtrace command line options */
uint32_t intervalReportTime; /* If we want interval reports about performance */
bool mono; /* Supress colour in output */
int paceDelay; /* Delay between blocks of data transmission in file readout */
char *channelList; /* List of TPIU channels to be serviced */
bool hiresTime; /* Use hiresolution time (shorter timeouts...more accurate but higher load */
char *sn; /* Any part serial number for identifying a specific device */
/* Network link */
int listenPort; /* Listening port for network */
};
struct handlers
{
int channel; /* Channel number for this handler */
uint64_t intervalBytes; /* Number of depacketised bytes output on this channel */
struct dataBlock *strippedBlock; /* Processed buffers for output to clients */
struct nwclientsHandle *n; /* Link to the network client subsystem */
};
struct RunTime
{
struct TPIUDecoder t; /* TPIU decoder instance, in case we need it */
struct OrbtraceIf *o; /* For accessing ORBTrace devices + BMPs */
uint64_t intervalBytes; /* Number of bytes transferred in current interval */
pthread_t intervalThread; /* Thread reporting on intervals */
pthread_t processThread; /* Thread for processing prior to distributing to clients */
pthread_t usbThread; /* Thread for usb thread (this sometimes dies, so needs restarting) */
pthread_cond_t dataForClients; /* Semaphore counting data for clients */
pthread_mutex_t dataForClients_m; /* Mutex for counting data for clients */
bool ending; /* Flag indicating app is terminating */
bool errored; /* Flag indicating problem in reception process */
bool conn; /* Flag indicating that we have a good connection */
int f; /* File handle to data source */
int opFileHandle; /* Handle if we're writing orb output locally */
struct Options *options; /* Command line options (reference to above) */
int wp; /* Read and write pointers into transfer buffers */
int rp;
struct dataBlock rawBlock[NUM_RAW_BLOCKS]; /* Transfer buffers from the receiver */
int numHandlers; /* Number of TPIU channel handlers in use */
struct handlers *handler;
struct nwclientsHandle *n; /* Link to the network client subsystem (used for non-TPIU case) */
char *sn; /* Serial number for any device we've established contact with */
};
#ifdef WIN32
// https://stackoverflow.com/a/14388707/995351
#define SO_REUSEPORT SO_REUSEADDR
#endif
#define NWSERVER_HOST "localhost" /* Address to connect to NW Server */
#define NWSERVER_PORT (2332)
#define NUM_TPIU_CHANNELS 0x80
#define INTERVAL_100US (100U)
#define INTERVAL_1MS (10*INTERVAL_100US)
#define INTERVAL_100MS (100*INTERVAL_1MS)
#define INTERVAL_1S (10*INTERVAL_100MS)
//#define DUMP_BLOCK
struct Options _options =
{
.listenPort = NWCLIENT_SERVER_PORT,
.nwserverHost = NWSERVER_HOST,
};
struct RunTime _r;
// ====================================================================================================
// ====================================================================================================
// ====================================================================================================
// Private routines
// ====================================================================================================
// ====================================================================================================
// ====================================================================================================
#if defined(LINUX) && defined (TCGETS2)
// ====================================================================================================
// Linux Specific Drivers
// ====================================================================================================
static int _setSerialConfig ( int f, speed_t speed )
{
// Use Linux specific termios2.
struct termios2 settings;
int ret = ioctl( f, TCGETS2, &settings );
if ( ret < 0 )
{
return ( -3 );
}
settings.c_iflag &= ~( ISTRIP | INLCR | IGNCR | ICRNL | IXON | IXOFF );
settings.c_lflag &= ~( ICANON | ECHO | ECHOE | ISIG );
settings.c_cflag &= ~PARENB; /* no parity */
settings.c_cflag &= ~CSTOPB; /* 1 stop bit */
settings.c_cflag &= ~CSIZE;
settings.c_cflag &= ~( CBAUD | CIBAUD );
settings.c_cflag |= CS8 | CLOCAL; /* 8 bits */
settings.c_oflag &= ~OPOST; /* raw output */
settings.c_cflag |= BOTHER;
settings.c_ispeed = speed;
settings.c_ospeed = speed;
ret = ioctl( f, TCSETS2, &settings );
if ( ret < 0 )
{
genericsReport( V_ERROR, "Unsupported baudrate" EOL );
return ( -3 );
}
// Check configuration is ok.
ret = ioctl( f, TCGETS2, &settings );
if ( ret < 0 )
{
return ( -3 );
}
if ( ( settings.c_ispeed != speed ) || ( settings.c_ospeed != speed ) )
{
genericsReport( V_ERROR, "Failed to set baudrate" EOL );
return -4;
}
// Flush port.
ioctl( f, TCFLSH, TCIOFLUSH );
return 0;
}
#elif defined WIN32
// ====================================================================================================
// WIN32 Specific Driver
// ====================================================================================================
static bool _setSerialSpeed( HANDLE handle, int speed )
{
DCB dcb;
SecureZeroMemory( &dcb, sizeof( DCB ) );
dcb.DCBlength = sizeof( DCB );
BOOL ok = GetCommState( handle, &dcb );
if ( !ok )
{
return false;
}
dcb.BaudRate = speed;
dcb.ByteSize = 8;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;
ok = SetCommState( handle, &dcb );
if ( !ok )
{
return false;
}
// Set timeouts
COMMTIMEOUTS timeouts;
ok = GetCommTimeouts( handle, &timeouts );
if ( !ok )
{
return false;
}
timeouts.ReadIntervalTimeout = 0;
timeouts.ReadTotalTimeoutConstant = 0;
timeouts.ReadTotalTimeoutMultiplier = 0;
ok = SetCommTimeouts( handle, &timeouts );
if ( !ok )
{
return false;
}
return true;
}
#else
// =========================================================================================================
// Default Drivers ( OSX and Linux without TCGETS2 )
// =========================================================================================================
static int _setSerialConfig ( int f, speed_t speed )
{
struct termios settings;
if ( tcgetattr( f, &settings ) < 0 )
{
perror( "tcgetattr" );
return ( -3 );
}
if ( cfsetspeed( &settings, speed ) < 0 )
{
genericsReport( V_ERROR, "Error Setting input speed" EOL );
return ( -3 );
}
settings.c_iflag &= ~( ISTRIP | INLCR | IGNCR | ICRNL | IXON | IXOFF );
settings.c_lflag &= ~( ICANON | ECHO | ECHOE | ISIG );
settings.c_cflag &= ~PARENB; /* no parity */
settings.c_cflag &= ~CSTOPB; /* 1 stop bit */
settings.c_cflag &= ~CSIZE;
settings.c_cflag |= CS8 | CLOCAL; /* 8 bits */
settings.c_oflag &= ~OPOST; /* raw output */
if ( tcsetattr( f, TCSANOW, &settings ) < 0 )
{
genericsReport( V_ERROR, "Unsupported baudrate" EOL );
return ( -3 );
}
tcflush( f, TCOFLUSH );
return 0;
}
#endif
// ====================================================================================================
static void _doExit( void )
{
_r.ending = true;
nwclientShutdown( _r.n );
/* Give them a bit of time, then we're leaving anyway */
usleep( INTERVAL_100MS );
if ( _r.opFileHandle )
{
close( _r.opFileHandle );
_r.opFileHandle = 0;
}
/* Need to nudge our own process in case it's stuck in a read or similar */
_exit( 0 );
}
// ====================================================================================================
static void _intHandler( int sig )
{
/* CTRL-C exit is not an error... */
_doExit();
}
// ====================================================================================================
void _printHelp( const char *const progName )
{
genericsPrintf( "Usage: %s [options]" EOL, progName );
genericsPrintf( " -a, --serial-speed: <serialSpeed> to use" EOL );
genericsPrintf( " -E, --eof: When reading from file, terminate at end of file" EOL );
genericsPrintf( " -f, --input-file: <filename> Take input from specified file" EOL );
genericsPrintf( " -h, --help: This help" EOL );
genericsPrintf( " -H, --hires: High resolution time (much higher CPU load though!)" EOL );
genericsPrintf( " -l, --listen-port: <port> Listen port for the incoming connections (defaults to %d)" EOL, NWCLIENT_SERVER_PORT );
genericsPrintf( " -m, --monitor: <interval> Output monitor information about the link at <interval>ms" EOL );
genericsPrintf( " -M, --no-colour: Supress colour in output" EOL );
genericsPrintf( " -n, --serial-number: <Serial> any part of serial number to differentiate specific OrbTrace device" EOL );
genericsPrintf( " -o, --output-file: <filename> to be used for dump file" EOL );
genericsPrintf( " -O, --orbtrace: \"<options>\" run orbtrace with specified options on each new ORBTrace device connect" EOL );
genericsPrintf( " -p, --serial-port: <serialPort> to use" EOL );
genericsPrintf( " -P, --pace: <microseconds> delay in block of data transmission to clients. Used when source is a file." EOL );
genericsPrintf( " -s, --server: <Server>:<Port> to use" EOL );
genericsPrintf( " -t, --tpiu: <Channel , ...> Use TPIU channels (and strip TPIU framing from output flows)" EOL );
genericsPrintf( " -v, --verbose: <level> Verbose mode 0(errors)..3(debug)" EOL );
genericsPrintf( " -V, --version: Print version and exit" EOL );
}
// ====================================================================================================
void _printVersion( void )
{
genericsPrintf( "orbuculum version " GIT_DESCRIBE );
}
// ====================================================================================================
static struct option _longOptions[] =
{
{"serial-speed", required_argument, NULL, 'a'},
{"eof", no_argument, NULL, 'E'},
{"input-file", required_argument, NULL, 'f'},
{"help", no_argument, NULL, 'h'},
{"hires", no_argument, NULL, 'H'},
{"listen-port", required_argument, NULL, 'l'},
{"monitor", required_argument, NULL, 'm'},
{"no-colour", no_argument, NULL, 'M'},
{"no-color", no_argument, NULL, 'M'},
{"serial-number", required_argument, NULL, 'n'},
{"output-file", required_argument, NULL, 'o'},
{"orbtrace", required_argument, NULL, 'O'},
{"serial-port", required_argument, NULL, 'p'},
{"pace", required_argument, NULL, 'P'},
{"server", required_argument, NULL, 's'},
{"tpiu", required_argument, NULL, 't'},
{"verbose", required_argument, NULL, 'v'},
{"version", no_argument, NULL, 'V'},
{NULL, no_argument, NULL, 0}
};
// ====================================================================================================
bool _processOptions( int argc, char *argv[], struct RunTime *r )
{
int c, optionIndex = 0;
#define DELIMITER ','
while ( ( c = getopt_long ( argc, argv, "a:Ef:hHVl:m:Mn:o:O:p:P:s:t:v:", _longOptions, &optionIndex ) ) != -1 )
switch ( c )
{
// ------------------------------------
case 'a':
r->options->speed = atoi( optarg );
r->options->dataSpeed = r->options->speed;
break;
// ------------------------------------
case 'E':
r->options->fileTerminate = true;
break;
// ------------------------------------
case 'f':
r->options->file = optarg;
break;
// ------------------------------------
case 'h':
_printHelp( argv[0] );
return false;
// ------------------------------------
case 'H':
r->options->hiresTime = true;
break;
// ------------------------------------
case 'V':
_printVersion();
return false;
// ------------------------------------
case 'l':
r->options->listenPort = atoi( optarg );
break;
// ------------------------------------
case 'm':
r->options->intervalReportTime = atoi( optarg );
break;
// ------------------------------------
case 'M':
r->options->mono = true;
break;
// ------------------------------------
case 'n':
r->options->sn = optarg;
break;
// ------------------------------------
case 'o':
r->options->outfile = optarg;
break;
// ------------------------------------
case 'O':
r->options->otcl = optarg;
break;
// ------------------------------------
case 'p':
r->options->port = optarg;
break;
// ------------------------------------
case 'P':
r->options->paceDelay = atoi( optarg );
break;
// ------------------------------------
case 's':
r->options->nwserverHost = optarg;
// See if we have an optional port number too
char *a = optarg;
while ( ( *a ) && ( *a != ':' ) )
{
a++;
}
if ( *a == ':' )
{
*a = 0;
r->options->nwserverPort = atoi( ++a );
}
if ( !r->options->nwserverPort )
{
r->options->nwserverPort = NWSERVER_PORT;
}
break;
// ------------------------------------
case 't':
r->options->useTPIU = true;
r->options->channelList = optarg;
break;
// ------------------------------------
case 'v':
if ( !isdigit( *optarg ) )
{
genericsReport( V_ERROR, "-v requires a numeric argument." EOL );
return false;
}
genericsSetReportLevel( atoi( optarg ) );
break;
// ------------------------------------
case '?':
if ( optopt == 'b' )
{
genericsReport( V_ERROR, "Option '%c' requires an argument." EOL, optopt );
}
else if ( !isprint ( optopt ) )
{
genericsReport( V_ERROR, "Unknown option character `\\x%x'." EOL, optopt );
}
return false;
// ------------------------------------
default:
genericsReport( V_ERROR, "Unrecognised option '%c'" EOL, c );
return false;
// ------------------------------------
}
/* ... and dump the config if we're being verbose */
genericsReport( V_INFO, "orbuculum version " GIT_DESCRIBE EOL );
if ( r->options->intervalReportTime )
{
genericsReport( V_INFO, "Report Intv : %d mS" EOL, r->options->intervalReportTime );
}
if ( r->options->port )
{
genericsReport( V_INFO, "Serial Port : %s" EOL, r->options->port );
}
if ( r->options->speed )
{
genericsReport( V_INFO, "Serial Speed : %d baud" EOL, r->options->speed );
}
if ( r->options->sn )
{
genericsReport( V_INFO, "Serial Nummber : %s" EOL, r->options->sn );
}
if ( r->options->dataSpeed )
{
genericsReport( V_INFO, "Max Data Rt : %d bps" EOL, r->options->dataSpeed );
}
if ( r->options->outfile )
{
genericsReport( V_INFO, "Raw Output file: %s" EOL, r->options->outfile );
}
if ( r->options->nwserverPort )
{
genericsReport( V_INFO, "NW SERVER H&P : %s:%d" EOL, r->options->nwserverHost, r->options->nwserverPort );
}
if ( r->options->useTPIU )
{
genericsReport( V_INFO, "Use/Strip TPIU : True (Channel List %s)" EOL, r->options->channelList );
}
else
{
genericsReport( V_INFO, "Use/Strip TPIU : False" EOL );
}
if ( r->options->otcl )
{
genericsReport( V_INFO, "Orbtrace CL : %s" EOL, r->options->otcl );
}
if ( r->options->hiresTime )
{
genericsReport( V_INFO, "High Res Time" EOL );
}
if ( r->options->file )
{
genericsReport( V_INFO, "Input File : %s" EOL, r->options->file );
genericsReport( V_INFO, "Pace Delay : %dus" EOL, r->options->paceDelay );
if ( r->options->fileTerminate )
{
genericsReport( V_INFO, " (Terminate on exhaustion)" EOL );
}
else
{
genericsReport( V_INFO, " (Ongoing read)" EOL );
}
}
if ( ( r->options->file ) && ( ( r->options->port ) || ( r->options->nwserverPort ) ) )
{
genericsReport( V_ERROR, "Cannot specify file and port or NW Server at same time" EOL );
return false;
}
if ( ( r->options->paceDelay ) && ( !r->options->file ) )
{
genericsReport( V_ERROR, "Pace Delay only makes sense when input is from a file" EOL );
return false;
}
if ( ( r->options->port ) && ( r->options->nwserverPort ) )
{
genericsReport( V_ERROR, "Cannot specify port and NW Server at same time" EOL );
return false;
}
return true;
}
// ====================================================================================================
void *_checkInterval( void *params )
/* Perform any interval reporting that may be needed */
{
struct RunTime *r = ( struct RunTime * )params;
uint64_t snapInterval;
struct handlers *h;
while ( !r->ending )
{
usleep( r->options->intervalReportTime * INTERVAL_1MS );
/* Grab the interval and scale to 1 second */
snapInterval = r->intervalBytes * 1000 / r->options->intervalReportTime;
snapInterval *= 8;
if ( r->conn )
{
genericsPrintf( C_PREV_LN C_CLR_LN C_DATA );
if ( snapInterval / 1000000 )
{
genericsPrintf( "%4d.%d " C_RESET "MBits/sec ", snapInterval / 1000000, ( snapInterval * 1 / 100000 ) % 10 );
}
else if ( snapInterval / 1000 )
{
genericsPrintf( "%4d.%d " C_RESET "KBits/sec ", snapInterval / 1000, ( snapInterval / 100 ) % 10 );
}
else
{
genericsPrintf( " %4d " C_RESET " Bits/sec ", snapInterval );
}
h = r->handler;
uint64_t totalDat = 0;
if ( ( r->intervalBytes ) && ( r->options->useTPIU ) )
{
for ( int chIndex = 0; chIndex < r->numHandlers; chIndex++ )
{
genericsPrintf( " %d:%3d%% ", h->channel, ( h->intervalBytes * 100 ) / r->intervalBytes );
totalDat += h->intervalBytes;
/* TODO: This needs a mutex */
h->intervalBytes = 0;
h++;
}
genericsPrintf( " Waste:%3d%% ", 100 - ( ( totalDat * 100 ) / r->intervalBytes ) );
}
r->intervalBytes = 0;
if ( r->options->dataSpeed > 100 )
{
/* Conversion to percentage done as a division to avoid overflow */
uint32_t fullPercent = ( snapInterval * 100 ) / r->options->dataSpeed;
genericsPrintf( "(" C_DATA " %3d%% " C_RESET "full)", ( fullPercent > 100 ) ? 100 : fullPercent );
}
genericsPrintf( C_RESET EOL );
}
}
return NULL;
}
// ====================================================================================================
static void _purgeBlock( struct RunTime *r )
{
/* Now send any packets to clients who want it */
if ( r->options->useTPIU )
{
struct handlers *h = r->handler;
int i = r->numHandlers;
while ( i-- )
{
if ( h->strippedBlock->fillLevel )
{
nwclientSend( h->n, h->strippedBlock->fillLevel, h->strippedBlock->buffer, ( r->options->file != NULL ) );
h->intervalBytes += h->strippedBlock->fillLevel;
h->strippedBlock->fillLevel = 0;
}
h++;
}
}
}
// ====================================================================================================
static void _TPIUpacketRxed( enum TPIUPumpEvent e, struct TPIUPacket *p, void *param )
/* Callback for when a TPIU frame has been assembled */
{
struct RunTime *r = ( struct RunTime * )param;
struct handlers *h = NULL;
int cachedChannel = -1;
int chIndex = 0;
switch ( e )
{
case TPIU_EV_RXEDPACKET:
/* Iterate through the packet, putting it into the correct output buffers */
for ( uint32_t g = 0; g < p->len; g++ )
{
if ( cachedChannel != p->packet[g].s )
{
/* Whatever happens, cache this result */
cachedChannel = p->packet[g].s;
/* Search for channel */
h = r->handler;
for ( chIndex = 0; chIndex < r->numHandlers; chIndex++ )
{
if ( h->channel == p->packet[g].s )
{
break;
}
h++;
}
}
if ( ( chIndex != r->numHandlers ) && ( h ) )
{
/* We must have found a match for this at some point, so add it to the queue */
h->strippedBlock->buffer[h->strippedBlock->fillLevel++] = p->packet[g].d;
}
else
{
genericsReport( V_WARN, "No handler for %d" EOL, p->packet[g].s );
}
}
break;
case TPIU_EV_ERROR:
genericsReport( V_WARN, "****ERROR****%s" EOL, ( r->options->intervalReportTime ) ? EOL : "" );
break;
case TPIU_EV_NEWSYNC:
case TPIU_EV_SYNCED:
case TPIU_EV_RXING:
case TPIU_EV_NONE:
case TPIU_EV_UNSYNCED:
default:
break;
}
}
// ====================================================================================================
static void _processBlock( struct RunTime *r, ssize_t fillLevel, uint8_t *buffer )
{
genericsReport( V_DEBUG, "RXED Packet of %d bytes%s" EOL, fillLevel, ( r->options->intervalReportTime ) ? EOL : "" );
if ( fillLevel )
{
/* Account for this reception */
r->intervalBytes += fillLevel;
#ifdef DUMP_BLOCK
uint8_t *c = buffer;
uint32_t y = fillLevel;
genericsPrintf( EOL );
while ( y-- )
{
genericsPrintf( "%02X ", *c++ );
if ( !( y % 16 ) )
{
genericsPrinttf( EOL );
}
}
#endif
if ( r->opFileHandle )
{
if ( write( r->opFileHandle, buffer, fillLevel ) <= 0 )
{
genericsExit( -3, "Writing to file failed" EOL );
}
}
if ( r-> options->useTPIU )
{
/* Strip the TPIU framing from this input */
TPIUPump2( &r->t, r->rawBlock[r->rp].buffer, r->rawBlock[r->rp].fillLevel, _TPIUpacketRxed, r );
_purgeBlock( r );
}
else
{
/* Do it the old fashioned way and send out the unfettered block */
nwclientSend( _r.n, r->rawBlock[r->rp].fillLevel, r->rawBlock[r->rp].buffer, ( r->options->file != NULL ) );
}
}
}
// ====================================================================================================
static void *_processBlocksQueue( void *params )
/* Generic block processor task for received data */
{
struct RunTime *r = ( struct RunTime * )params;
while ( !r->ending )
{
pthread_cond_wait( &r->dataForClients, &r->dataForClients_m );
while ( r->rp != r->wp )
{
_processBlock( r, r->rawBlock[r->rp].fillLevel, r->rawBlock[r->rp].buffer );
r->rp = ( r->rp + 1 ) % NUM_RAW_BLOCKS;
}
}
return NULL;
}
// ====================================================================================================
static void _dataAvailable( struct RunTime *r )
{
pthread_cond_signal( &r->dataForClients );
}
// ====================================================================================================
static void _usb_callback( struct libusb_transfer *t )
/* For the USB case the ringbuffer isn't used .. packets are sent directly from this callback */
{
/* Whatever the status that comes back, there may be data... */
if ( t->actual_length > 0 )
{
_r.intervalBytes += t->actual_length;
if ( _r.opFileHandle )
{
if ( write( _r.opFileHandle, t->buffer, t->actual_length ) < 0 )
{
genericsExit( -4, "Writing to file failed (%s)" EOL, strerror( errno ) );
}
}
#ifdef DUMP_BLOCK
uint8_t *c = t->buffer;
uint32_t y = t->actual_length;
genericsPrintf( stderr, EOL );
while ( y-- )
{
genericsPrintf( stderr, "%02X ", *c++ );
if ( !( y % 16 ) )
{
genericsPrintf( stderr, EOL );
}
}
#endif
if ( _r.options->useTPIU )
{
/* Strip the TPIU framing from this input */
TPIUPump2( &_r.t, t->buffer, t->actual_length, _TPIUpacketRxed, &_r );
_purgeBlock( &_r );
}
else
{
/* Do it the old fashioned way and send out the unfettered block */
nwclientSend( _r.n, t->actual_length, t->buffer, false );
}
}
if ( ( t->status != LIBUSB_TRANSFER_COMPLETED ) &&
( t->status != LIBUSB_TRANSFER_TIMED_OUT ) &&
( t->status != LIBUSB_TRANSFER_CANCELLED )
)
{
if ( !_r.errored )
{
genericsReport( V_WARN, "Errored out with status %d (%s)" EOL, t->status, libusb_error_name( t->status ) );
}
_r.errored = true;
}
else
{
if ( t->status != LIBUSB_TRANSFER_CANCELLED )
{
libusb_submit_transfer( t );
}
}
}
// ====================================================================================================
void _actionOrbtraceCommand( struct RunTime *r, char *sn, enum ORBTraceDevice d )
{
char commandLine[MAX_LINE_LEN];
/* If we have any configuration to do on this device, go ahead */
if ( r->options->otcl )
{
if ( getenv( ORBTRACEENVNAME ) )
{
snprintf( commandLine, MAX_LINE_LEN, "%s %s %s %s", getenv( ORBTRACEENVNAME ), r->options->otcl, sn ? ( ( d == DEVICE_ORBTRACE_MINI ) ? "-n " : "-s " ) : "", sn ? sn : "" );
}
else
{
char *baseDirectory = genericsGetBaseDirectory( );
if ( !baseDirectory )
{
genericsExit( -1, "Failed to establish base directory" EOL );
}
snprintf( commandLine, MAX_LINE_LEN, "%s" ORBTRACE " %s %s %s", baseDirectory, r->options->otcl, sn ? ( ( d == DEVICE_ORBTRACE_MINI ) ? "-n " : "-s " ) : "", sn ? sn : "" );
free( baseDirectory );
}
genericsReport( V_INFO, "%s" EOL, commandLine );
if ( system( commandLine ) )
{
genericsReport( V_ERROR, "Invoking orbtrace failed" EOL );
}
}
}
// ====================================================================================================
static int _usbFeeder( struct RunTime *r )
{
int workingDev;
/* Copy any part serial number across */
if ( r->options->sn )
{
r->sn = strdup( r->options->sn );
}
while ( !r->ending )