-
Notifications
You must be signed in to change notification settings - Fork 0
/
marvelmind.c
1525 lines (1309 loc) · 49.5 KB
/
marvelmind.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
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#if defined(WIN32) || defined(_WIN64)
#include <windows.h>
#include <process.h>
#else
#include <unistd.h>
#include <termios.h>
#include <fcntl.h>
#include <pthread.h>
#include <sys/poll.h>
#endif // WIN32
#include "marvelmind.h"
//////////////////////////////////////////////////////////////////////////////
// Calculate CRC (Modbus) for array of bytes
// buf: input buffer
// len: size of buffer
// returncode: CRC value
//////////////////////////////////////////////////////////////////////////////
uint16_t CalcCrcModbus_(uint8_t * buf, int len)
{
uint16_t crc = 0xFFFF;
int pos;
for (pos = 0; pos < len; pos++)
{
crc ^= (uint16_t)buf[pos]; // XOR byte into least sig. byte of crc
int i;
for (i = 8; i != 0; i--) // Loop over each bit
{
if ((crc & 0x0001) != 0) // If the LSB is set
{
crc >>= 1; // Shift right and XOR 0xA001
crc ^= 0xA001;
}
else // Else LSB is not set
crc >>= 1; // Just shift right
}
}
return crc;
}
#if defined(WIN32) || defined(_WIN64)
#define SERIAL_PORT_HANDLE HANDLE
#define PORT_NOT_OPENED INVALID_HANDLE_VALUE
//////////////////////////////////////////////////////////////////////////////
// Open Serial Port (Windows only)
// portFileName: alias of port (e.g. "COM3"). Add prefix "\\\\.\\" before alias
// to open higher ports (e.g. COM12)
// baudrate: baudRate rate (e.g. 19200)
// verbose: print errors
// returncode: valid handle if port is successfully opened or
// INVALID_HANDLE_VALUE on error
//////////////////////////////////////////////////////////////////////////////
HANDLE OpenSerialPort_ (SERIAL_FILENAME portFileName, uint32_t baudrate,
bool verbose)
{
#ifdef _WIN64
HANDLE ttyHandle = CreateFileW( portFileName, GENERIC_READ, 0,
NULL, OPEN_EXISTING, 0/*FILE_FLAG_OVERLAPPED*/, NULL);
#else
HANDLE ttyHandle = CreateFileA(portFileName, GENERIC_READ, 0,
NULL, OPEN_EXISTING, 0/*FILE_FLAG_OVERLAPPED*/, NULL);
#endif
if (ttyHandle==INVALID_HANDLE_VALUE)
{
if (verbose)
puts ("Error: unable to open serial connection "
"(possibly serial port is not available)");
return INVALID_HANDLE_VALUE;
}
COMMTIMEOUTS timeouts= {3000,3000,3000,3000,3000};
bool returnCode=SetCommTimeouts (ttyHandle, &timeouts);
if (!returnCode)
{
if (verbose) puts ("Error: unable to set serial port timeouts");
CloseHandle (ttyHandle);
return INVALID_HANDLE_VALUE;
}
DCB dcb= {0};
returnCode=GetCommState (ttyHandle, &dcb);
if (!returnCode)
{
if (verbose) puts ("Error: unable to get serial port parameters");
CloseHandle (ttyHandle);
return INVALID_HANDLE_VALUE;
}
dcb.BaudRate = baudrate;
dcb.fAbortOnError=true;
returnCode=SetCommState (ttyHandle, &dcb);
if (!returnCode)
{
if (verbose) puts ("Error: unable to set serial port parameters");
CloseHandle (ttyHandle);
return INVALID_HANDLE_VALUE;
}
return ttyHandle;
}
#else
//////////////////////////////////////////////////////////////////////////////
// Converts baudrate value to baudRate code (Linux only)
// baudrate: value of baudRate rate (e.g. 19200)
// verbose: show errors
// returncode: code of baudRate rate (e.g. B19200)
//////////////////////////////////////////////////////////////////////////////
uint32_t _GetBaudCode (uint32_t baudrate, bool verbose)
{
switch (baudrate)
{
case 50:
return B50;
case 75:
return B75;
case 110:
return B110;
case 134:
return B134;
case 150:
return B150;
case 200:
return B200;
case 300:
return B300;
case 600:
return B600;
case 1200:
return B1200;
case 1800:
return B1800;
case 2400:
return B2400;
case 4800:
return B4800;
case 9600:
return B9600;
case 19200:
return B19200;
case 38400:
return B38400;
case 57600:
return B57600;
case 115200:
return B115200;
case 230400:
return B230400;
case 460800:
return B460800;
case 500000:
return B500000;
case 576000:
return B576000;
case 921600:
return B921600;
case 1000000:
return B1000000;
case 1152000:
return B1152000;
default:
if (verbose)
printf ("Warning: unsupported baudrate %u. Using 9600.\n",
baudrate);
return B9600;
}
}
#define SERIAL_PORT_HANDLE int
#define PORT_NOT_OPENED -1
//////////////////////////////////////////////////////////////////////////////
// Open Serial Port (Linux only)
// portFileName: alias of port (e.g. "/dev/ttyACM0")
// baudrate: baudRate rate (e.g. 19200)
// verbose: show errors
// returncode: valid handle if port is successfully opened or -1 on error
//////////////////////////////////////////////////////////////////////////////
int OpenSerialPort_ (const char * portFileName, uint32_t baudrate, bool verbose)
{
int ttyHandle = open(portFileName, O_RDWR| O_NONBLOCK | O_NDELAY );
if (ttyHandle<0)
{
if (verbose)
puts ("Error: unable to open serial connection "
"(possibly serial port is not available)");
return -1;
}
struct termios ttyCtrl;
memset (&ttyCtrl, 0, sizeof ttyCtrl);
if ( tcgetattr ( ttyHandle, &ttyCtrl ) != 0 )
{
if (verbose) puts ("Error: unable to get serial port parameters");
return -1;
}
uint32_t baudCode=_GetBaudCode(baudrate, verbose);
cfsetospeed (&ttyCtrl, baudCode);
cfsetispeed (&ttyCtrl, baudCode);
// 8N1, no flow control
ttyCtrl.c_cflag &= ~(PARENB|CSTOPB|CSIZE|CRTSCTS);
ttyCtrl.c_cflag |= CS8;
// no signaling chars, no echo, no canonical processing
ttyCtrl.c_lflag = 0;
ttyCtrl.c_oflag = 0; // no remapping, no delays
ttyCtrl.c_cc[VMIN] = 0; // read doesn't block
ttyCtrl.c_cc[VTIME] = 30; // 3 seconds read timeout
ttyCtrl.c_cflag |= CREAD | CLOCAL; // turn on READ & ignore ctrl lines
ttyCtrl.c_iflag &= ~(IXON | IXOFF | IXANY);// turn off s/w flow ctrl
ttyCtrl.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // make raw
ttyCtrl.c_oflag &= ~OPOST; // make raw
tcflush(ttyHandle, TCIFLUSH ); // Flush port
if (tcsetattr (ttyHandle, TCSANOW, &ttyCtrl) != 0)
{
if (verbose) puts ("Error: unable to set serial port parameters");
return -1;
}
return ttyHandle;
}
#endif
enum
{
RECV_HDR,
RECV_DGRAM
};
//////////////////////////////////////////////////////////////////////////////
static uint16_t get_uint16(uint8_t *buffer)
{
uint16_t res= buffer[0] |
(((uint16_t ) buffer[1])<<8);
return res;
}
static int16_t get_int16(uint8_t *buffer)
{
int16_t res= buffer[0] |
(((uint16_t ) buffer[1])<<8);
return res;
}
static uint32_t get_uint32(uint8_t *buffer)
{
uint32_t res= buffer[0] |
(((uint32_t ) buffer[1])<<8) |
(((uint32_t ) buffer[2])<<16) |
(((uint32_t ) buffer[3])<<24);
return res;
}
static int32_t get_int32(uint8_t *buffer)
{
int32_t res= buffer[0] |
(((uint32_t ) buffer[1])<<8) |
(((uint32_t ) buffer[2])<<16) |
(((uint32_t ) buffer[3])<<24);
return res;
}
//////////////////////////////////////////////////////////////////////////////
// Thread function started by MarvelmindHedge_start
//////////////////////////////////////////////////////////////////////////////
static uint8_t markPositionReady(struct MarvelmindHedge * hedge)
{uint8_t ind= hedge->lastValues_next;
uint8_t indCur= ind;
hedge->positionBuffer[ind].ready=
true;
hedge->positionBuffer[ind].processed=
false;
ind++;
if (ind>= MAX_BUFFERED_POSITIONS)
ind=0;
if (hedge->lastValuesCount_<MAX_BUFFERED_POSITIONS)
hedge->lastValuesCount_++;
hedge->haveNewValues_=true;
hedge->lastValues_next= ind;
return indCur;
}
static struct PositionValue process_position_datagram(struct MarvelmindHedge * hedge, uint8_t *buffer)
{uint8_t ind= hedge->lastValues_next;
hedge->positionBuffer[ind].address=
buffer[16];
hedge->positionBuffer[ind].timestamp.timestamp32=
buffer[5] |
(((uint32_t ) buffer[6])<<8) |
(((uint32_t ) buffer[7])<<16) |
(((uint32_t ) buffer[8])<<24);
hedge->positionBuffer[ind].realTime= false;
int16_t vx= buffer[9] |
(((uint16_t ) buffer[10])<<8);
hedge->positionBuffer[ind].x= vx*10;// millimeters
int16_t vy= buffer[11] |
(((uint16_t ) buffer[12])<<8);
hedge->positionBuffer[ind].y= vy*10;// millimeters
int16_t vz= buffer[13] |
(((uint16_t ) buffer[14])<<8);
hedge->positionBuffer[ind].z= vz*10;// millimeters
hedge->positionBuffer[ind].flags= buffer[15];
uint16_t vang= buffer[17] |
(((uint16_t ) buffer[18])<<8);
hedge->positionBuffer[ind].angle= ((float) (vang & 0x0fff))/10.0f;
hedge->positionBuffer[ind].highResolution= false;
ind= markPositionReady(hedge);
return hedge->positionBuffer[ind];
}
static struct PositionValue process_position_highres_datagram_main(struct MarvelmindHedge * hedge, uint8_t *buffer, uint8_t ind) {
hedge->positionBuffer[ind].address=
buffer[22];
int32_t vx= buffer[9] |
(((uint32_t ) buffer[10])<<8) |
(((uint32_t ) buffer[11])<<16) |
(((uint32_t ) buffer[12])<<24);
hedge->positionBuffer[ind].x= vx;
int32_t vy= buffer[13] |
(((uint32_t ) buffer[14])<<8) |
(((uint32_t ) buffer[15])<<16) |
(((uint32_t ) buffer[16])<<24);
hedge->positionBuffer[ind].y= vy;
int32_t vz= buffer[17] |
(((uint32_t ) buffer[18])<<8) |
(((uint32_t ) buffer[19])<<16) |
(((uint32_t ) buffer[20])<<24);
hedge->positionBuffer[ind].z= vz;
hedge->positionBuffer[ind].flags= buffer[21];
uint16_t vang= buffer[23] |
(((uint16_t ) buffer[24])<<8);
hedge->positionBuffer[ind].angle= ((float) (vang & 0x0fff))/10.0f;
hedge->positionBuffer[ind].highResolution= true;
ind= markPositionReady(hedge);
return hedge->positionBuffer[ind];
}
static struct PositionValue process_position_highres_datagram(struct MarvelmindHedge * hedge, uint8_t *buffer)
{uint8_t ind= hedge->lastValues_next;
hedge->positionBuffer[ind].timestamp.timestamp32=
buffer[5] |
(((uint32_t ) buffer[6])<<8) |
(((uint32_t ) buffer[7])<<16) |
(((uint32_t ) buffer[8])<<24);
hedge->positionBuffer[ind].realTime= false;
return process_position_highres_datagram_main(hedge, buffer, ind);
}
static struct PositionValue process_nt_position_highres_datagram(struct MarvelmindHedge * hedge, uint8_t *buffer)
{uint8_t ind= hedge->lastValues_next;
memcpy(&hedge->positionBuffer[ind].timestamp, &buffer[5], 8);
hedge->positionBuffer[ind].realTime= true;
return process_position_highres_datagram_main(hedge, &buffer[4], ind);
}
static struct StationaryBeaconPosition *getOrAllocBeacon(struct MarvelmindHedge * hedge,uint8_t address)
{
uint8_t i;
uint8_t n_used= hedge->positionsBeacons.numBeacons;
if (n_used != 0)
for(i=0;i<n_used;i++)
{
if (hedge->positionsBeacons.beacons[i].address == address)
{
return &hedge->positionsBeacons.beacons[i];
}
}
if (n_used >= (MAX_STATIONARY_BEACONS-1))
return NULL;
hedge->positionsBeacons.numBeacons= (n_used + 1);
return &hedge->positionsBeacons.beacons[n_used];
}
static void process_beacons_positions_datagram(struct MarvelmindHedge * hedge, uint8_t *buffer)
{
uint8_t n= buffer[5];// number of beacons in packet
uint8_t i,ofs;
uint8_t address;
int16_t x,y,z;
struct StationaryBeaconPosition *b;
if ((1+n*8)!=buffer[4])
return;// incorrect size
for(i=0;i<n;i++)
{
ofs= 6+i*8;
address= buffer[ofs+0];
x= buffer[ofs+1] |
(((uint16_t ) buffer[ofs+2])<<8);
y= buffer[ofs+3] |
(((uint16_t ) buffer[ofs+4])<<8);
z= buffer[ofs+5] |
(((uint16_t ) buffer[ofs+6])<<8);
b= getOrAllocBeacon(hedge, address);
if (b != NULL)
{
b->address= address;
b->x= x*10;// millimeters
b->y= y*10;// millimeters
b->z= z*10;// millimeters
b->highResolution= false;
hedge->positionsBeacons.updated= true;
}
}
}
static void process_beacons_positions_highres_datagram(struct MarvelmindHedge * hedge, uint8_t *buffer)
{
uint8_t n= buffer[5];// number of beacons in packet
uint8_t i,ofs;
uint8_t address;
int32_t x,y,z;
struct StationaryBeaconPosition *b;
if ((1+n*14)!=buffer[4])
return;// incorrect size
for(i=0;i<n;i++)
{
ofs= 6+i*14;
address= buffer[ofs+0];
x= buffer[ofs+1] |
(((uint32_t ) buffer[ofs+2])<<8) |
(((uint32_t ) buffer[ofs+3])<<16) |
(((uint32_t ) buffer[ofs+4])<<24);
y= buffer[ofs+5] |
(((uint32_t ) buffer[ofs+6])<<8) |
(((uint32_t ) buffer[ofs+7])<<16) |
(((uint32_t ) buffer[ofs+8])<<24);
z= buffer[ofs+9] |
(((uint32_t ) buffer[ofs+10])<<8) |
(((uint32_t ) buffer[ofs+11])<<16) |
(((uint32_t ) buffer[ofs+12])<<24);
b= getOrAllocBeacon(hedge, address);
if (b != NULL)
{
b->address= address;
b->x= x;
b->y= y;
b->z= z;
b->highResolution= true;
hedge->positionsBeacons.updated= true;
}
}
}
static void process_imu_raw_datagram_main(struct MarvelmindHedge * hedge, uint8_t *buffer)
{uint8_t *dataBuf= &buffer[5];
hedge->rawIMU.acc_x= get_int16(&dataBuf[0]);
hedge->rawIMU.acc_y= get_int16(&dataBuf[2]);
hedge->rawIMU.acc_z= get_int16(&dataBuf[4]);
//
hedge->rawIMU.gyro_x= get_int16(&dataBuf[6]);
hedge->rawIMU.gyro_y= get_int16(&dataBuf[8]);
hedge->rawIMU.gyro_z= get_int16(&dataBuf[10]);
//
hedge->rawIMU.compass_x= get_int16(&dataBuf[12]);
hedge->rawIMU.compass_y= get_int16(&dataBuf[14]);
hedge->rawIMU.compass_z= get_int16(&dataBuf[16]);
hedge->rawIMU.updated= true;
}
static void process_imu_raw_datagram(struct MarvelmindHedge * hedge, uint8_t *buffer)
{uint8_t *dataBuf= &buffer[5];
process_imu_raw_datagram_main(hedge, buffer);
hedge->rawIMU.timestamp.timestamp32= get_uint32(&dataBuf[24]);
hedge->rawIMU.realTime= false;
}
static void process_nt_imu_raw_datagram(struct MarvelmindHedge * hedge, uint8_t *buffer)
{uint8_t *dataBuf= &buffer[5];
process_imu_raw_datagram_main(hedge, buffer);
memcpy(&hedge->rawIMU.timestamp, &dataBuf[24], 8);
hedge->rawIMU.realTime= true;
}
static void process_imu_fusion_datagram_main(struct MarvelmindHedge * hedge, uint8_t *buffer)
{uint8_t *dataBuf= &buffer[5];
hedge->fusionIMU.x= get_int32(&dataBuf[0]);
hedge->fusionIMU.y= get_int32(&dataBuf[4]);
hedge->fusionIMU.z= get_int32(&dataBuf[8]);
hedge->fusionIMU.qw= get_int16(&dataBuf[12]);
hedge->fusionIMU.qx= get_int16(&dataBuf[14]);
hedge->fusionIMU.qy= get_int16(&dataBuf[16]);
hedge->fusionIMU.qz= get_int16(&dataBuf[18]);
hedge->fusionIMU.vx= get_int16(&dataBuf[20]);
hedge->fusionIMU.vy= get_int16(&dataBuf[22]);
hedge->fusionIMU.vz= get_int16(&dataBuf[24]);
hedge->fusionIMU.ax= get_int16(&dataBuf[26]);
hedge->fusionIMU.ay= get_int16(&dataBuf[28]);
hedge->fusionIMU.az= get_int16(&dataBuf[30]);
hedge->fusionIMU.updated= true;
}
static void process_imu_fusion_datagram(struct MarvelmindHedge * hedge, uint8_t *buffer)
{uint8_t *dataBuf= &buffer[5];
process_imu_fusion_datagram_main(hedge, buffer);
hedge->fusionIMU.timestamp.timestamp32= get_uint32(&dataBuf[34]);
hedge->fusionIMU.realTime= false;
}
static void process_nt_imu_fusion_datagram(struct MarvelmindHedge * hedge, uint8_t *buffer)
{uint8_t *dataBuf= &buffer[5];
process_imu_fusion_datagram_main(hedge, buffer);
memcpy(&hedge->fusionIMU.timestamp, &dataBuf[34], 8);
hedge->fusionIMU.realTime= true;
}
static void process_raw_distances_datagram_main(struct MarvelmindHedge * hedge, uint8_t *buffer)
{uint8_t *dataBuf= &buffer[5];
uint8_t ofs, i;
hedge->rawDistances.address_hedge= dataBuf[0];
ofs= 1;
for(i=0;i<4;i++)
{
hedge->rawDistances.distances[i].address_beacon= dataBuf[ofs+0];
hedge->rawDistances.distances[i].distance= get_uint32(&dataBuf[ofs+1]);
ofs+= 6;
}
hedge->rawDistances.updated= true;
}
static void process_raw_distances_datagram(struct MarvelmindHedge * hedge, uint8_t *buffer)
{uint8_t *dataBuf= &buffer[5];
process_raw_distances_datagram_main(hedge, buffer);
hedge->rawDistances.timestamp.timestamp32= get_uint32(&dataBuf[25]);
hedge->rawDistances.realTime= false;
hedge->rawDistances.timeShift= get_uint16(&dataBuf[29]);
}
static void process_nt_raw_distances_datagram(struct MarvelmindHedge * hedge, uint8_t *buffer)
{uint8_t *dataBuf= &buffer[5];
process_raw_distances_datagram_main(hedge, buffer);
memcpy(&hedge->rawDistances.timestamp, &dataBuf[25], 8);
hedge->rawDistances.realTime= true;
hedge->rawDistances.timeShift= get_uint16(&dataBuf[33]);
}
static void process_telemetry_datagram(struct MarvelmindHedge * hedge, uint8_t *buffer)
{uint8_t *dataBuf= &buffer[5];
hedge->telemetry.vbat_mv= get_uint16(&dataBuf[0]);
hedge->telemetry.rssi_dbm= (int8_t) dataBuf[2];
hedge->telemetry.updated= true;
}
static void process_quality_datagram(struct MarvelmindHedge * hedge, uint8_t *buffer)
{uint8_t *dataBuf= &buffer[5];
hedge->quality.address= dataBuf[0];
hedge->quality.quality_per= dataBuf[1];
hedge->quality.updated= true;
}
static void process_waypoint_data(struct MarvelmindHedge * hedge, uint8_t *buffer)
{uint8_t i;
for(i=0;i<16;i++) {
printf("%03d, ", buffer[i]);
}
printf("\n");
}
////////////////////////
void
#if (!defined(WIN32)) && (!defined(_WIN64))
*
#endif // WIN32
Marvelmind_Thread_ (void* param)
{
struct MarvelmindHedge * hedge=(struct MarvelmindHedge*) param;
struct PositionValue curPosition;
uint8_t input_buffer[256];
uint8_t recvState=RECV_HDR; // current state of receive data
uint8_t nBytesInBlockReceived=0; // bytes received
uint16_t dataId;
#if (!defined(WIN32)) && (!defined(_WIN64))
struct pollfd fds[1];
int pollrc;
#endif
SERIAL_PORT_HANDLE ttyHandle=OpenSerialPort_(hedge->ttyFileName,
hedge->baudRate, hedge->verbose);
if (ttyHandle==PORT_NOT_OPENED) hedge->terminationRequired=true;
else if (hedge->verbose) printf ("Opened serial port %s with baudrate %u\n",
hedge->ttyFileName, hedge->baudRate);
while (hedge->terminationRequired==false)
{
uint8_t receivedChar;
bool readSuccessed=true;
#if defined(WIN32) || defined(_WIN64)
DWORD nBytesRead;
OVERLAPPED osReader = {0};
osReader.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (osReader.hEvent == NULL) {
printf ("Failed create event\n");
hedge->terminationRequired= true;
continue;
}
readSuccessed= ReadFile(ttyHandle, &receivedChar, 1, &nBytesRead, NULL);//&osReader);
/* if (!readSuccessed)
{
dwRes = WaitForSingleObject(osReader.hEvent, 1000);
if (dwRes == WAIT_OBJECT_0)
{
if (GetOverlappedResult(ttyHandle, &osReader, &nBytesRead, FALSE))
{
readSuccessed= true;
}
}
}
*/
CloseHandle(osReader.hEvent);
#else
int32_t nBytesRead;
fds[0].fd = ttyHandle;
fds[0].events = POLLIN ;
pollrc = poll( fds, 1, 1000);
if (pollrc<=0) continue;
if ((fds[0].revents & POLLIN )==0) continue;
nBytesRead=read(ttyHandle, &receivedChar, 1);
if (nBytesRead<0) readSuccessed=false;
#endif
if (nBytesRead && readSuccessed)
{
bool goodByte= false;
input_buffer[nBytesInBlockReceived]= receivedChar;
switch (recvState)
{
case RECV_HDR:
switch(nBytesInBlockReceived)
{
case 0:
goodByte= (receivedChar == 0xff);
break;
case 1:
goodByte= (receivedChar == 0x47) || (receivedChar == 0x4a);
break;
case 2:
goodByte= true;
break;
case 3:
dataId= (((uint16_t) receivedChar)<<8) + input_buffer[2];
goodByte= (dataId == POSITION_DATAGRAM_ID) ||
(dataId == BEACONS_POSITIONS_DATAGRAM_ID) ||
(dataId == POSITION_DATAGRAM_HIGHRES_ID) ||
(dataId == BEACONS_POSITIONS_DATAGRAM_HIGHRES_ID) ||
(dataId == IMU_RAW_DATAGRAM_ID) ||
(dataId == IMU_FUSION_DATAGRAM_ID) ||
(dataId == BEACON_RAW_DISTANCE_DATAGRAM_ID) ||
(dataId == TELEMETRY_DATAGRAM_ID) ||
(dataId == QUALITY_DATAGRAM_ID) ||
(dataId == WAYPOINT_DATAGRAM_ID) ||
(dataId == NT_POSITION_DATAGRAM_HIGHRES_ID) ||
(dataId == NT_IMU_RAW_DATAGRAM_ID) ||
(dataId == NT_BEACON_RAW_DISTANCE_DATAGRAM_ID) ||
(dataId == NT_IMU_FUSION_DATAGRAM_ID);
break;
case 4:
switch(dataId )
{
case POSITION_DATAGRAM_ID:
goodByte= (receivedChar == 0x10);
break;
case BEACONS_POSITIONS_DATAGRAM_ID:
case BEACONS_POSITIONS_DATAGRAM_HIGHRES_ID:
goodByte= true;
break;
case POSITION_DATAGRAM_HIGHRES_ID:
goodByte= (receivedChar == 0x16);
break;
case IMU_RAW_DATAGRAM_ID:
goodByte= (receivedChar == 0x20);
break;
case IMU_FUSION_DATAGRAM_ID:
goodByte= (receivedChar == 0x2a);
break;
case BEACON_RAW_DISTANCE_DATAGRAM_ID:
goodByte= (receivedChar == 0x20);
break;
case TELEMETRY_DATAGRAM_ID:
goodByte= (receivedChar == 0x10);
break;
case QUALITY_DATAGRAM_ID:
goodByte= (receivedChar == 0x10);
break;
case WAYPOINT_DATAGRAM_ID:
goodByte= (receivedChar == 0x0c);
break;
case NT_POSITION_DATAGRAM_HIGHRES_ID:
case NT_IMU_RAW_DATAGRAM_ID:
case NT_BEACON_RAW_DISTANCE_DATAGRAM_ID:
case NT_IMU_FUSION_DATAGRAM_ID:
goodByte= true;
break;
}
if (goodByte)
recvState=RECV_DGRAM;
break;
}
if (goodByte)
{
// correct header byte
nBytesInBlockReceived++;
}
else
{
// ...or incorrect
recvState=RECV_HDR;
nBytesInBlockReceived=0;
}
break;
case RECV_DGRAM:
nBytesInBlockReceived++;
if (nBytesInBlockReceived>=7+input_buffer[4])
{
// parse dgram
uint16_t blockCrc=
CalcCrcModbus_(input_buffer,nBytesInBlockReceived);
if (blockCrc==0)
{
#if defined(WIN32) || defined(_WIN64)
EnterCriticalSection(&hedge->lock_);
#else
pthread_mutex_lock (&hedge->lock_);
#endif
switch(dataId )
{
case POSITION_DATAGRAM_ID:
// add to positionBuffer
curPosition= process_position_datagram(hedge, input_buffer);
break;
case BEACONS_POSITIONS_DATAGRAM_ID:
process_beacons_positions_datagram(hedge, input_buffer);
break;
case POSITION_DATAGRAM_HIGHRES_ID:
// add to positionBuffer
curPosition= process_position_highres_datagram(hedge, input_buffer);
break;
case NT_POSITION_DATAGRAM_HIGHRES_ID:
curPosition= process_nt_position_highres_datagram(hedge, input_buffer);
break;
case BEACONS_POSITIONS_DATAGRAM_HIGHRES_ID:
process_beacons_positions_highres_datagram(hedge, input_buffer);
break;
case IMU_RAW_DATAGRAM_ID:
process_imu_raw_datagram(hedge, input_buffer);
break;
case NT_IMU_RAW_DATAGRAM_ID:
process_nt_imu_raw_datagram(hedge, input_buffer);
break;
case IMU_FUSION_DATAGRAM_ID:
process_imu_fusion_datagram(hedge, input_buffer);
break;
case NT_IMU_FUSION_DATAGRAM_ID:
process_nt_imu_fusion_datagram(hedge, input_buffer);
break;
case BEACON_RAW_DISTANCE_DATAGRAM_ID:
process_raw_distances_datagram(hedge, input_buffer);
break;
case NT_BEACON_RAW_DISTANCE_DATAGRAM_ID:
process_nt_raw_distances_datagram(hedge, input_buffer);
break;
case TELEMETRY_DATAGRAM_ID:
process_telemetry_datagram(hedge, input_buffer);
break;
case QUALITY_DATAGRAM_ID:
process_quality_datagram(hedge, input_buffer);
break;
case WAYPOINT_DATAGRAM_ID:
process_waypoint_data(hedge, input_buffer);
break;
}
#if defined(WIN32) || defined(_WIN64)
LeaveCriticalSection(&hedge->lock_);
#else
pthread_mutex_unlock (&hedge->lock_);
#endif
// callback
if (hedge->anyInputPacketCallback)
{
hedge->anyInputPacketCallback();
}
if (hedge->receiveDataCallback)
{
if (dataId == POSITION_DATAGRAM_ID)
{
hedge->receiveDataCallback (curPosition);
}
}
}
// and repeat
recvState=RECV_HDR;
nBytesInBlockReceived=0;
}
}
}
}
// #if (!defined(WIN32)) && (!defined(_WIN64))
// return NULL;
// #endif
#if defined(WIN32) || defined(_WIN64)
if(ttyHandle != PORT_NOT_OPENED) {
CloseHandle(ttyHandle);
}
#else
close(ttyHandle);
#endif
#if defined(WIN32) || defined(_WIN64)
return 0;
#else
return NULL;
#endif
}
//////////////////////////////////////////////////////////////////////////////
// Create an initialize MarvelmindHedge structure
// returncode: pointer to structure on success or NULL on error
//////////////////////////////////////////////////////////////////////////////
struct MarvelmindHedge * createMarvelmindHedge ()
{
struct MarvelmindHedge * hedge=malloc (sizeof (struct MarvelmindHedge));
if (hedge)
{
hedge->ttyFileName=DEFAULT_TTY_FILENAME;
hedge->baudRate=115200;//9600;//115200;//9600;
hedge->positionBuffer=NULL;
hedge->verbose=false;
hedge->receiveDataCallback=NULL;
hedge->anyInputPacketCallback= NULL;
hedge->lastValuesCount_=0;
hedge->lastValues_next= 0;
hedge->haveNewValues_=false;
hedge->terminationRequired= false;
hedge->rawIMU.updated= false;
hedge->fusionIMU.updated= false;
hedge->rawDistances.updated= false;
#if defined(WIN32) || defined(_WIN64)
InitializeCriticalSection(&hedge->lock_);
#else
pthread_mutex_init (&hedge->lock_, NULL);
#endif
}
else puts ("Not enough memory");
return hedge;
}
//////////////////////////////////////////////////////////////////////////////
// Initialize and start work thread
//////////////////////////////////////////////////////////////////////////////
static int timezone_offset() {
time_t zero = 0;
struct tm* lt = localtime( &zero );
if (lt == NULL) return 0;
//return 0;
//int unaligned = lt->tm_sec + ( lt->tm_min + ( lt->tm_hour * 6 ) ) * 6;
int unaligned = lt->tm_sec + ( lt->tm_min + ( lt->tm_hour * 60 ) ) * 60;
return lt->tm_mon ? unaligned - 24*60*60 : unaligned;
}
void startMarvelmindHedge (struct MarvelmindHedge * hedge)
{uint8_t i;
hedge->positionBuffer=
malloc(sizeof (struct PositionValue)*MAX_BUFFERED_POSITIONS);
if (hedge->positionBuffer==NULL)
{
if (hedge->verbose) puts ("Not enough memory");
hedge->terminationRequired=true;
return;
}
for(i=0;i<MAX_BUFFERED_POSITIONS;i++)
{
hedge->positionBuffer[i].ready= false;
hedge->positionBuffer[i].processed= false;
}
hedge->positionsBeacons.numBeacons= 0;
hedge->positionsBeacons.updated= false;
hedge->telemetry.updated= false;
hedge->quality.updated= false;
hedge->timeOffset= timezone_offset();
//printf("TZ= %d\r\n",(int) hedge->timeOffset);
#if defined(WIN32) || defined(_WIN64)
// _beginthread (Marvelmind_Thread_, 0, hedge);
hedge->thread_ = (HANDLE)_beginthreadex(NULL, 0, Marvelmind_Thread_, (void*)hedge, 0, NULL);
#else
pthread_create (&hedge->thread_, NULL, Marvelmind_Thread_, hedge);
#endif
}
//////////////////////////////////////////////////////////////////////////////
// Write average position coordinates
// hedge: MarvelmindHedge structure
// position: pointer to PositionValue for write coordinates
// returncode: true if position is valid
//////////////////////////////////////////////////////////////////////////////
static bool getPositionFromMarvelmindHedgeByAddress (struct MarvelmindHedge * hedge,
struct PositionValue * position, uint8_t address)
{
uint8_t i;
int32_t avg_x=0, avg_y=0, avg_z=0;
double avg_ang= 0.0;
int64_t max_timestamp=0;
TimestampOpt max_timestamp_opt;
bool isRealTime= false;
bool position_valid;
bool highRes= false;
uint8_t flags;
#if defined(WIN32) || defined(_WIN64)
EnterCriticalSection(&hedge->lock_);
#else
pthread_mutex_lock (&hedge->lock_);
#endif
if (hedge->lastValuesCount_)
{
uint8_t real_values_count= MAX_BUFFERED_POSITIONS;
uint8_t nFound= 0;