-
Notifications
You must be signed in to change notification settings - Fork 31
/
fsgps.c
2587 lines (2261 loc) · 95.8 KB
/
fsgps.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
/****************************************************************************
* fsgps.c - A 'full stack' GPS recevier - goes from raw
* samples to a position fix
*
* Author: Mike Field <[email protected]>
*
*****************************************************************************
MIT License
Copyright (c) 2017 Mike Field
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
#include <memory.h>
#include <math.h>
#include <time.h>
/*******************************************************************
* What information should be printed, and how often
*******************************************************************/
/* How often should the table of channel states be printed */
#define SHOW_TIMING_SNAPSHOT_FREQ_MS (20)
/* How often should an attempt to solve for position be made */
#define SHOW_SOLUTION_MS (20)
/*******************************************************************
* Constants based on the GPS signals for decoding BPSK data
*******************************************************************/
/* How many 'chips' are sent each milliseconds */
#define CHIPS_PER_MS (1023)
/* Each BPSH bit is MS_PER_BIT milliseconds long */
#define MS_PER_BIT (20)
#define BIT_LENGTH (MS_PER_BIT)
/* There are BITS_PER_FRAME bits in each NAV frame */
#define BITS_PER_FRAME (300)
/* How many unexpected phase transitions will we receive
until we consider the signal lost */
#define MAX_BAD_BIT_TRANSITIONS (500)
/*******************************************************************
* Factors that control the feedback loops for tracking the signals
*******************************************************************/
/* The factor used to smooth the early and late power levels */
#define LATE_EARLY_IIR_FACTOR 16
/* Filter constants for the angle and change in angle
* used for carrier locking */
#define LOCK_DELTA_IIR_FACTOR 8
#define LOCK_ANGLE_IIR_FACTOR 8
/*******************************************************************
* To print out debugging information
*******************************************************************/
/* Print the ATAN2 lookup table as it is generated */
#define PRINT_ATAN2_TABLE 0
/* Set PRINT_SAMPLE_NUMBERS to 1 to Print out the number
* of samples processed every PRINT_SAMPLE_FREQUENCY */
#define PRINT_SAMPLE_NUMBERS 0
#define PRINT_SAMPLE_FREQUENCY 1000
/* Set PRINT_ACQUIRE_POWERS to 1 to see the power levels
* during the acqusition phase. Powers less than
* PRINT_ACQUIRE_SQUETCH are not printed */
#define PRINT_ACQUIRE_POWERS 0
#define PRINT_ACQUIRE_SQUETCH 50000
/* Set PRINT_TRACK_POWER to '1' to print out the
* power levels during the track phase */
#define PRINT_TRACK_POWER 0
#define PRINT_TRACK_SQUETCH 0
/* Print out if a space vheicle falls out of lock */
#define SHOW_LOCK_UNLOCK 1
/* Do we show the code NCO values? */
#define PRINT_LOCKED_NCO_VALUES 0
/* Show the initial values used for the NCOs when a lock
* is obtained */
#define LOCK_SHOW_INITIAL 1
/* Show the power levels each millisecond */
#define LOCK_SHOW_PER_MS_POWER 0
/* Show each bit as it is received */
#define LOCK_SHOW_PER_BIT 0
/* Show the state of the late/early filters */
#define LOCK_SHOW_EARLY_LATE_TREND 0
/* Show the I+Q power levels each millisecond */
#define LOCK_SHOW_PER_MS_IQ 0
/* Show the I+Q vector each millisecond */
#define LOCK_SHOW_ANGLES 0
/* Show each BSPK Bit is it is received */
#define LOCK_SHOW_BITS 0
#define LOCK_SHOW_BPSK_PHASE_PER_MS 0
#define SHOW_NAV_FRAMING 0
/* Do we want to print out each timing snapshot */
#define SHOW_TIMING_SNAPSHOT_DETAILS 1
/* Do we want to write the snapshots to a file, for later analysis? */
#define LOG_TIMING_SNAPSHOT_TO_FILE 1
#define LOG_POSITION_FIX_TO_FILE 1
/* Add extra checks to make sure nothing is awry */
#define DOUBLECHECK_PROMPT_CODE_INDEX 0
/*************************************************************/
/******************** END OF DEFINES *************************/
/*************************************************************/
/* Standard data types */
typedef int int_32;
typedef unsigned int uint_32;
typedef unsigned char uint_8;
typedef signed char int_8;
typedef unsigned long long uint_64;
uint_32 samples_per_ms;
uint_32 if_cycles_per_ms;
uint_32 samples_for_acquire;
uint_32 acquire_bitmap_size_u32;
uint_32 code_offset_in_ms;
uint_32 ms_for_acquire = 2;
uint_32 acquire_min_power;
uint_32 track_unlock_power;
uint_32 lock_lost_power;
uint_64 sample_count = 0;
enum e_state {state_acquiring, state_tracking, state_locked};
FILE *snapshot_file;
FILE *position_file;
/***************************************************************************
* Physical constants and others defined in the GPS specifications
***************************************************************************/
static const double EARTHS_RADIUS = 6317000.0;
static const double SPEED_OF_LIGHT = 299792458.0;
static const double PI = 3.1415926535898;
static const double mu = 3.986005e14; /* Earth's universal gravitation parameter */
static const double omegaDot_e = 7.2921151467e-5; /* Earth's rotation (radians per second) */
static const int TIME_EPOCH = 315964800;
/**************************************************************************/
/* time/clock data received from the Space Vehicles */
struct Nav_time {
uint_8 time_good;
uint_32 week_no;
uint_32 user_range_accuracy;
uint_32 health;
uint_32 issue_of_data;
double group_delay; /* Tgd */
double reference_time; /* Toc */
double correction_f2; /* a_f2 */
double correction_f1; /* a_f1 */
double correction_f0; /* a_f0 */
};
/* Orbit parameters recevied from the Space Vehicles */
struct Nav_orbit {
/* Orbit data */
uint_8 fit_flag;
uint_8 orbit_valid;
uint_32 iode;
uint_32 time_of_ephemeris; // Toe
uint_32 aodo;
double mean_motion_at_ephemeris; // M0
double sqrt_A;
double Cus;
double Cuc;
double Cis;
double Cic;
double Crc;
double Crs;
double delta_n;
double e;
double omega_0;
double idot;
double omega_dot;
double inclination_at_ephemeris; // i_0
double w;
};
/* Data used during the acquire phase */
struct Acquire {
uint_32 *gold_code_stretched;
uint_32 **seek_in_phase;
uint_32 **seek_quadrature;
uint_32 max_power;
uint_8 max_band;
uint_32 max_offset;
};
/* Data used during the tracking phase */
struct Track {
uint_8 percent_locked;
uint_8 band;
uint_32 offset;
uint_32 power[3][3];
uint_32 max_power;
uint_8 max_band;
uint_32 max_offset;
};
/* Data used once the signal is locked */
struct Lock {
uint_32 filtered_power;
uint_32 phase_nco_sine;
uint_32 phase_nco_cosine;
int_32 phase_nco_step;
uint_32 code_nco_step;
uint_32 code_nco_filter;
uint_32 code_nco;
int_32 code_nco_trend;
int_32 early_sine;
int_32 early_cosine;
uint_32 early_sine_count;
uint_32 early_cosine_count;
uint_32 early_sine_count_last;
uint_32 early_cosine_count_last;
int_32 prompt_sine;
int_32 prompt_cosine;
uint_32 prompt_sine_count;
uint_32 prompt_cosine_count;
uint_32 prompt_sine_count_last;
uint_32 prompt_cosine_count_last;
int_32 late_sine;
int_32 late_cosine;
uint_32 late_sine_count;
uint_32 late_cosine_count;
uint_32 late_sine_count_last;
uint_32 late_cosine_count_last;
int_32 early_power;
int_32 early_power_not_reset;
int_32 prompt_power;
int_32 late_power;
int_32 late_power_not_reset;
uint_8 last_angle;
int_32 delta_filtered;
int_32 angle_filtered;
uint_8 ms_of_bit;
int_32 ms_of_frame;
uint_8 last_bit;
};
struct Navdata {
uint_32 seq;
uint_8 synced;
uint_32 subframe_of_week;
/* Last 32 bits of data received*/
uint_8 part_in_bit;
uint_8 subframe_in_frame;
uint_32 new_word;
/* A count of where we are upto in the subframe (-1 means unsynced) */
int_32 valid_bits;
int_32 bit_errors;
/* Uncoming, incomplete frame */
uint_32 new_subframe[10];
/* Complete NAV data frames (only 1 to 5 is used, zero is empty) */
uint_8 valid_subframe[6];
uint_32 subframes[7][10];
};
struct Space_vehicle {
/* ID of the space vehicle, and the taps used to generate the Gold Codes */
uint_8 id;
uint_8 tap1;
uint_8 tap2;
enum e_state state;
uint_8 gold_code[CHIPS_PER_MS];
/* For holding data in each state */
struct Acquire acquire;
struct Track track;
struct Lock lock;
struct Navdata navdata;
struct Nav_time nav_time;
struct Nav_orbit nav_orbit;
/* For calculating Space vehicle position */
double time_raw;
double pos_x;
double pos_y;
double pos_z;
double pos_t;
double pos_t_valid;
/* Handles for writing data out */
FILE *bits_file;
FILE *nav_file;
} space_vehicles[] = {
{ 1, 2, 6},
{ 2, 3, 7},
{ 3, 4, 8},
{ 4, 5, 9},
{ 5, 1, 9},
{ 6, 2,10},
{ 7, 1, 8},
{ 8, 2, 9},
{ 9, 3,10},
{10, 2, 3},
{11, 3, 4},
{12, 5, 6},
{13, 6, 7},
{14, 7, 8},
{15, 8, 9},
{16, 9,10},
{17, 1, 4},
{18, 2, 5},
{19, 3, 6},
{20, 4, 7},
{21, 5, 8},
{22, 6, 9},
{23, 1, 3},
{24, 4, 6},
{25, 5, 7},
{26, 6, 8},
{27, 7, 9},
{28, 8,10},
{29, 1, 6},
{30, 2, 7},
{31, 3, 8},
{32, 4, 9}
};
#define N_SV (sizeof(space_vehicles)/sizeof(struct Space_vehicle))
#define MAX_SV 32
unsigned bitmap_size_u32;
unsigned search_bands;
unsigned band_bandwidth;
unsigned *sample_history;
unsigned *work_buffer;
#define ATAN2_SIZE 128
uint_8 atan2_lookup[ATAN2_SIZE][ATAN2_SIZE];
struct Location {
double x;
double y;
double z;
double time;
};
struct Snapshot_entry {
uint_32 nav_week_no;
uint_32 nav_subframe_of_week;
uint_32 nav_subframe_in_frame;
uint_32 lock_code_nco;
uint_32 lock_ms_of_frame;
uint_8 lock_ms_of_bit;
uint_8 nav_valid_bits;
uint_8 state;
uint_8 id;
};
#define SNAPSHOT_STATE_ORBIT_VALID (0x01)
#define SNAPSHOT_STATE_TIME_VALID (0x02)
#define SNAPSHOT_STATE_ACQUIRE (0x80)
#define SNAPSHOT_STATE_TRACK (0x40)
#define SNAPSHOT_STATE_LOCKED (0x20)
struct Snapshot {
uint_32 sample_count_l;
uint_32 sample_count_h;
struct Snapshot_entry entries[MAX_SV];
};
/*********************************************************************************************************/
/*********************************************************************************************************/
/************************ THIS CODE IS TAKEN FROM ANOTHER SOURCE *****************************************/
/*********************************************************************************************************/
/*********************************************************************************************************/
//////////////////////////////////////////////////////////////////////////
// Homemade GPS Receiver
// Copyright (C) 2013 Andrew Holme
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// http://www.aholme.co.uk/GPS/Main.htm
//////////////////////////////////////////////////////////////////////////
#include <memory.h>
#define MAX_ITER 20
#define WGS84_A (6378137.0)
#define WGS84_F_INV (298.257223563)
#define WGS84_B (6356752.31424518)
#define WGS84_E2 (0.00669437999014132)
#define OMEGA_E (7.2921151467e-5) /* Earth's rotation rate */
///////////////////////////////////////////////////////////////////////////////////////////////
#define NUM_CHANS 10
int A_solve(int chans, struct Location *sv_l, struct Location *p) {
int i, j, r, c;
double t_tx[NUM_CHANS]; // Clock replicas in seconds since start of week
double x_sv[NUM_CHANS],
y_sv[NUM_CHANS],
z_sv[NUM_CHANS];
double t_pc; // Uncorrected system time when clock replica snapshots taken
double t_rx; // Corrected GPS time
double dPR[NUM_CHANS]; // Pseudo range error
double jac[NUM_CHANS][4], ma[4][4], mb[4][4], mc[4][NUM_CHANS], md[4];
double weight[NUM_CHANS];
p->x = p->y = p->z = p->time = t_pc = 0.0;
for (i=0; i<chans && i < NUM_CHANS; i++) {
weight[i] = 1.0;
x_sv[i] = sv_l[i].x;
y_sv[i] = sv_l[i].y;
z_sv[i] = sv_l[i].z;
t_tx[i] = sv_l[i].time;
t_pc += sv_l[i].time;
}
// Approximate starting value for receiver clock
t_pc = t_pc/chans + 75e-3;
// Iterate to user xyzt solution using Taylor Series expansion:
double err_mag;
for(j=0; j<MAX_ITER; j++) {
t_rx = t_pc - p->time;
for (i=0; i<chans; i++) {
// Convert SV position to ECI coords (20.3.3.4.3.3.2)
double theta = (t_tx[i] - t_rx) * OMEGA_E;
double x_sv_eci = x_sv[i]*cos(theta) - y_sv[i]*sin(theta);
double y_sv_eci = x_sv[i]*sin(theta) + y_sv[i]*cos(theta);
double z_sv_eci = z_sv[i];
// Geometric range (20.3.3.4.3.4)
double gr = sqrt(pow(p->x - x_sv_eci, 2) +
pow(p->y - y_sv_eci, 2) +
pow(p->z - z_sv_eci, 2));
dPR[i] = SPEED_OF_LIGHT*(t_rx - t_tx[i]) - gr;
jac[i][0] = (p->x - x_sv_eci) / gr;
jac[i][1] = (p->y - y_sv_eci) / gr;
jac[i][2] = (p->z - z_sv_eci) / gr;
jac[i][3] = SPEED_OF_LIGHT;
}
// ma = transpose(H) * W * H
for (r=0; r<4; r++)
for (c=0; c<4; c++) {
ma[r][c] = 0;
for (i=0; i<chans; i++) ma[r][c] += jac[i][r]*weight[i]*jac[i][c];
}
double determinant =
ma[0][3]*ma[1][2]*ma[2][1]*ma[3][0] - ma[0][2]*ma[1][3]*ma[2][1]*ma[3][0] - ma[0][3]*ma[1][1]*ma[2][2]*ma[3][0] + ma[0][1]*ma[1][3]*ma[2][2]*ma[3][0]+
ma[0][2]*ma[1][1]*ma[2][3]*ma[3][0] - ma[0][1]*ma[1][2]*ma[2][3]*ma[3][0] - ma[0][3]*ma[1][2]*ma[2][0]*ma[3][1] + ma[0][2]*ma[1][3]*ma[2][0]*ma[3][1]+
ma[0][3]*ma[1][0]*ma[2][2]*ma[3][1] - ma[0][0]*ma[1][3]*ma[2][2]*ma[3][1] - ma[0][2]*ma[1][0]*ma[2][3]*ma[3][1] + ma[0][0]*ma[1][2]*ma[2][3]*ma[3][1]+
ma[0][3]*ma[1][1]*ma[2][0]*ma[3][2] - ma[0][1]*ma[1][3]*ma[2][0]*ma[3][2] - ma[0][3]*ma[1][0]*ma[2][1]*ma[3][2] + ma[0][0]*ma[1][3]*ma[2][1]*ma[3][2]+
ma[0][1]*ma[1][0]*ma[2][3]*ma[3][2] - ma[0][0]*ma[1][1]*ma[2][3]*ma[3][2] - ma[0][2]*ma[1][1]*ma[2][0]*ma[3][3] + ma[0][1]*ma[1][2]*ma[2][0]*ma[3][3]+
ma[0][2]*ma[1][0]*ma[2][1]*ma[3][3] - ma[0][0]*ma[1][2]*ma[2][1]*ma[3][3] - ma[0][1]*ma[1][0]*ma[2][2]*ma[3][3] + ma[0][0]*ma[1][1]*ma[2][2]*ma[3][3];
// mb = inverse(ma) = inverse(transpose(H)*W*H)
mb[0][0] = (ma[1][2]*ma[2][3]*ma[3][1] - ma[1][3]*ma[2][2]*ma[3][1] + ma[1][3]*ma[2][1]*ma[3][2] - ma[1][1]*ma[2][3]*ma[3][2] - ma[1][2]*ma[2][1]*ma[3][3] + ma[1][1]*ma[2][2]*ma[3][3]) / determinant;
mb[0][1] = (ma[0][3]*ma[2][2]*ma[3][1] - ma[0][2]*ma[2][3]*ma[3][1] - ma[0][3]*ma[2][1]*ma[3][2] + ma[0][1]*ma[2][3]*ma[3][2] + ma[0][2]*ma[2][1]*ma[3][3] - ma[0][1]*ma[2][2]*ma[3][3]) / determinant;
mb[0][2] = (ma[0][2]*ma[1][3]*ma[3][1] - ma[0][3]*ma[1][2]*ma[3][1] + ma[0][3]*ma[1][1]*ma[3][2] - ma[0][1]*ma[1][3]*ma[3][2] - ma[0][2]*ma[1][1]*ma[3][3] + ma[0][1]*ma[1][2]*ma[3][3]) / determinant;
mb[0][3] = (ma[0][3]*ma[1][2]*ma[2][1] - ma[0][2]*ma[1][3]*ma[2][1] - ma[0][3]*ma[1][1]*ma[2][2] + ma[0][1]*ma[1][3]*ma[2][2] + ma[0][2]*ma[1][1]*ma[2][3] - ma[0][1]*ma[1][2]*ma[2][3]) / determinant;
mb[1][0] = (ma[1][3]*ma[2][2]*ma[3][0] - ma[1][2]*ma[2][3]*ma[3][0] - ma[1][3]*ma[2][0]*ma[3][2] + ma[1][0]*ma[2][3]*ma[3][2] + ma[1][2]*ma[2][0]*ma[3][3] - ma[1][0]*ma[2][2]*ma[3][3]) / determinant;
mb[1][1] = (ma[0][2]*ma[2][3]*ma[3][0] - ma[0][3]*ma[2][2]*ma[3][0] + ma[0][3]*ma[2][0]*ma[3][2] - ma[0][0]*ma[2][3]*ma[3][2] - ma[0][2]*ma[2][0]*ma[3][3] + ma[0][0]*ma[2][2]*ma[3][3]) / determinant;
mb[1][2] = (ma[0][3]*ma[1][2]*ma[3][0] - ma[0][2]*ma[1][3]*ma[3][0] - ma[0][3]*ma[1][0]*ma[3][2] + ma[0][0]*ma[1][3]*ma[3][2] + ma[0][2]*ma[1][0]*ma[3][3] - ma[0][0]*ma[1][2]*ma[3][3]) / determinant;
mb[1][3] = (ma[0][2]*ma[1][3]*ma[2][0] - ma[0][3]*ma[1][2]*ma[2][0] + ma[0][3]*ma[1][0]*ma[2][2] - ma[0][0]*ma[1][3]*ma[2][2] - ma[0][2]*ma[1][0]*ma[2][3] + ma[0][0]*ma[1][2]*ma[2][3]) / determinant;
mb[2][0] = (ma[1][1]*ma[2][3]*ma[3][0] - ma[1][3]*ma[2][1]*ma[3][0] + ma[1][3]*ma[2][0]*ma[3][1] - ma[1][0]*ma[2][3]*ma[3][1] - ma[1][1]*ma[2][0]*ma[3][3] + ma[1][0]*ma[2][1]*ma[3][3]) / determinant;
mb[2][1] = (ma[0][3]*ma[2][1]*ma[3][0] - ma[0][1]*ma[2][3]*ma[3][0] - ma[0][3]*ma[2][0]*ma[3][1] + ma[0][0]*ma[2][3]*ma[3][1] + ma[0][1]*ma[2][0]*ma[3][3] - ma[0][0]*ma[2][1]*ma[3][3]) / determinant;
mb[2][2] = (ma[0][1]*ma[1][3]*ma[3][0] - ma[0][3]*ma[1][1]*ma[3][0] + ma[0][3]*ma[1][0]*ma[3][1] - ma[0][0]*ma[1][3]*ma[3][1] - ma[0][1]*ma[1][0]*ma[3][3] + ma[0][0]*ma[1][1]*ma[3][3]) / determinant;
mb[2][3] = (ma[0][3]*ma[1][1]*ma[2][0] - ma[0][1]*ma[1][3]*ma[2][0] - ma[0][3]*ma[1][0]*ma[2][1] + ma[0][0]*ma[1][3]*ma[2][1] + ma[0][1]*ma[1][0]*ma[2][3] - ma[0][0]*ma[1][1]*ma[2][3]) / determinant;
mb[3][0] = (ma[1][2]*ma[2][1]*ma[3][0] - ma[1][1]*ma[2][2]*ma[3][0] - ma[1][2]*ma[2][0]*ma[3][1] + ma[1][0]*ma[2][2]*ma[3][1] + ma[1][1]*ma[2][0]*ma[3][2] - ma[1][0]*ma[2][1]*ma[3][2]) / determinant;
mb[3][1] = (ma[0][1]*ma[2][2]*ma[3][0] - ma[0][2]*ma[2][1]*ma[3][0] + ma[0][2]*ma[2][0]*ma[3][1] - ma[0][0]*ma[2][2]*ma[3][1] - ma[0][1]*ma[2][0]*ma[3][2] + ma[0][0]*ma[2][1]*ma[3][2]) / determinant;
mb[3][2] = (ma[0][2]*ma[1][1]*ma[3][0] - ma[0][1]*ma[1][2]*ma[3][0] - ma[0][2]*ma[1][0]*ma[3][1] + ma[0][0]*ma[1][2]*ma[3][1] + ma[0][1]*ma[1][0]*ma[3][2] - ma[0][0]*ma[1][1]*ma[3][2]) / determinant;
mb[3][3] = (ma[0][1]*ma[1][2]*ma[2][0] - ma[0][2]*ma[1][1]*ma[2][0] + ma[0][2]*ma[1][0]*ma[2][1] - ma[0][0]*ma[1][2]*ma[2][1] - ma[0][1]*ma[1][0]*ma[2][2] + ma[0][0]*ma[1][1]*ma[2][2]) / determinant;
// mc = inverse(transpose(H)*W*H) * transpose(H)
for (r=0; r<4; r++)
for (c=0; c<chans; c++) {
mc[r][c] = 0;
for (i=0; i<4; i++) mc[r][c] += mb[r][i]*jac[c][i];
}
// md = inverse(transpose(H)*W*H) * transpose(H) * W * dPR
for (r=0; r<4; r++) {
md[r] = 0;
for (i=0; i<chans; i++) md[r] += mc[r][i]*weight[i]*dPR[i];
}
double dx = md[0];
double dy = md[1];
double dz = md[2];
double dt = md[3];
err_mag = sqrt(dx*dx + dy*dy + dz*dz);
if (err_mag<1.0) break;
p->x += dx;
p->y += dy;
p->z += dz;
p->time += dt;
}
return j;
}
///////////////////////////////////////////////////////////////////////////////////////////////
static void LatLonAlt(
double x_n, double y_n, double z_n,
double *lat, double *lon, double *alt) {
int iterations = 100;
const double a = WGS84_A;
const double e2 = WGS84_E2;
const double p = sqrt(x_n*x_n + y_n*y_n);
*lon = 2.0 * atan2(y_n, x_n + p);
*lat = atan(z_n / (p * (1.0 - e2)));
*alt = 0.0;
while(iterations > 0) {
double tmp = *alt;
double N = a / sqrt(1.0 - e2*pow(sin(*lat),2));
*alt = p/cos(*lat) - N;
*lat = atan(z_n / (p * (1.0 - e2*N/(N + *alt))));
if(fabs(*alt-tmp)<1e-3)
break;
iterations--;
}
}
/*********************************************************************************************************/
/*********************************************************************************************************/
/************************ END OF CODE TAKEN FROM ANOTHER SOURCE ******************************************/
/*********************************************************************************************************/
/*********************************************************************************************************/
static double orbit_ecc_anom(struct Space_vehicle *sv, double t) {
int iterations = 200;
double delta = pow(10,-10);
double estimate, correction, semi_major_axis, computed_mean_motion;
double time_from_ephemeris, correct_mean_motion, mean_anomaly;
semi_major_axis = sv->nav_orbit.sqrt_A * sv->nav_orbit.sqrt_A;
computed_mean_motion = sqrt(mu / pow(semi_major_axis,3.0));
time_from_ephemeris = t - sv->nav_orbit.time_of_ephemeris;
if(time_from_ephemeris > 302400) time_from_ephemeris -= 604800;
if(time_from_ephemeris < -302400) time_from_ephemeris += 604800;
correct_mean_motion = computed_mean_motion + sv->nav_orbit.delta_n;
/* Add on how much we have moved through the orbit since ephemeris */
mean_anomaly = sv->nav_orbit.mean_motion_at_ephemeris + correct_mean_motion * time_from_ephemeris;
/* First estimate */
estimate = (sv->nav_orbit.e<0.8) ? mean_anomaly : PI;
correction = estimate - (mean_anomaly + sv->nav_orbit.e*sin(mean_anomaly));
/* Solve iteratively */
while ((fabs(correction)>delta) && iterations > 0) {
double last = estimate;
estimate = mean_anomaly + sv->nav_orbit.e * sin(estimate);
correction = estimate - last;
iterations--;
}
if(iterations == 0) {
printf("Error calculating Eccentric Anomaly\n");
}
return estimate;
}
/*************************************************************************/
static void sv_calc_corrected_time(int i) {
double delta_t, delta_tr, ek, time_correction;
struct Space_vehicle *sv;
sv = space_vehicles+i;
sv->pos_t_valid = 0;
/* Calulate the time for the adjustment */
delta_t = sv->time_raw - sv->nav_time.reference_time;
if(delta_t > 302400) delta_t -= 604800;
if(delta_t < -302400) delta_t += 604800;
/* Relativistic term */
ek = orbit_ecc_anom(sv, sv->time_raw);
delta_tr = -4.442807633e-10 * sv->nav_orbit.e * sv->nav_orbit.sqrt_A * sin(ek);
time_correction = sv->nav_time.correction_f0
+ (sv->nav_time.correction_f1 * delta_t)
+ (sv->nav_time.correction_f2 * delta_t * delta_t)
+ delta_tr
- sv->nav_time.group_delay;
sv->pos_t = sv->time_raw - time_correction;
sv->pos_t_valid = 1;
return;
}
/**************************************************************************
* Calculate where the Space Vehicle will be at time "pos_t"
**************************************************************************/
static int orbit_calc_position(struct Space_vehicle *sv, struct Location *l)
{
double time_from_ephemeris, semi_major_axis;
double ek, true_anomaly, corrected_argument_of_latitude;
double argument_of_latitude, argument_of_latitude_correction;
double radius_correction, corrected_radius;
double correction_of_inclination;
double pos_in_orbial_plane_x, pos_in_orbial_plane_y;
double corrected_inclination, corrected_angle_of_ascending_node;
/***********************
* Calculate orbit
***********************/
time_from_ephemeris = sv->pos_t - sv->nav_orbit.time_of_ephemeris;
if(time_from_ephemeris > 302400) time_from_ephemeris -= 604800;
if(time_from_ephemeris < -302400) time_from_ephemeris += 604800;
semi_major_axis = sv->nav_orbit.sqrt_A * sv->nav_orbit.sqrt_A;
ek = orbit_ecc_anom(sv, sv->pos_t);
/* Now calculate the first approximation of the latitude */
true_anomaly = atan2( sqrt(1-sv->nav_orbit.e * sv->nav_orbit.e) * sin(ek), cos(ek) - sv->nav_orbit.e);
argument_of_latitude = true_anomaly + sv->nav_orbit.w;
/*****************************************
* Second Harmonic Perbturbations
*****************************************/
argument_of_latitude_correction = sv->nav_orbit.Cus * sin(2*argument_of_latitude)
+ sv->nav_orbit.Cuc * cos(2*argument_of_latitude);
radius_correction = sv->nav_orbit.Crc * cos(2*argument_of_latitude)
+ sv->nav_orbit.Crs * sin(2*argument_of_latitude);
correction_of_inclination = sv->nav_orbit.Cic * cos(2*argument_of_latitude)
+ sv->nav_orbit.Cis * sin(2*argument_of_latitude);
corrected_argument_of_latitude = argument_of_latitude + argument_of_latitude_correction;
corrected_radius = semi_major_axis * (1- sv->nav_orbit.e * cos(ek)) + radius_correction;
corrected_inclination = sv->nav_orbit.inclination_at_ephemeris + correction_of_inclination
+ sv->nav_orbit.idot*time_from_ephemeris;
pos_in_orbial_plane_x = corrected_radius * cos(corrected_argument_of_latitude);
pos_in_orbial_plane_y = corrected_radius * sin(corrected_argument_of_latitude);
corrected_angle_of_ascending_node = sv->nav_orbit.omega_0
+ (sv->nav_orbit.omega_dot - omegaDot_e)*time_from_ephemeris
- omegaDot_e * sv->nav_orbit.time_of_ephemeris;
/******************************************************
* Project into Earth Centered, Earth Fixed coordinates
******************************************************/
l->x = pos_in_orbial_plane_x * cos(corrected_angle_of_ascending_node)
- pos_in_orbial_plane_y * cos(corrected_inclination) * sin(corrected_angle_of_ascending_node);
l->y = pos_in_orbial_plane_x * sin(corrected_angle_of_ascending_node)
+ pos_in_orbial_plane_y * cos(corrected_inclination) * cos(corrected_angle_of_ascending_node);
l->z = pos_in_orbial_plane_y * sin(corrected_inclination);
l->time = sv->pos_t;
return 1;
}
/*************************************************************************/
static int sv_calc_location(int id, struct Location *l)
{
l->time = space_vehicles[id].pos_t;
orbit_calc_position(space_vehicles+id, l);
return 1;
}
/****************************************************************************/
static void attempt_solution(struct Snapshot *s) {
int sv_count = 0;
int sv_ids[N_SV];
int i;
struct Location predicted_location;
struct Location *sv_location;
double lat,lon,alt;
int q, valid_locations;
/* First, filter out who we can use in the solution */
for(i = 0; i < MAX_SV; i++) {
int id, j;
/* Find a valid entry in the snapshot */
if(!(s->entries[i].state & SNAPSHOT_STATE_LOCKED) ) continue;
if(!(s->entries[i].state & SNAPSHOT_STATE_ORBIT_VALID) ) continue;
if(!(s->entries[i].state & SNAPSHOT_STATE_TIME_VALID) ) continue;
id = s->entries[i].id;
/* Check we can find the matching entry in the Space_vehicle table */
for(j = 0 ; j < N_SV; j++) {
if(space_vehicles[j].id == id)
break;
}
/* If not found */
if(j == N_SV) continue;
/* Yes, we will use this ID */
sv_ids[sv_count] = id;
sv_count++;
}
/* Not enough vaild data to find the location! */
if(sv_count < 4) {
return;
}
/* Allocate space to hold the space vehicle locations */
sv_location = malloc(sizeof (struct Location)*sv_count);
if(sv_location == NULL) {
printf("Out of memory \n");
return;
}
/* Calculate the Space Vehicle positions at time of transmit */
valid_locations = 0;
for(q = 0; q < sv_count; q++) {
int e, sv;
unsigned phase_in_gold_code; /* value is 0 to (1023*64-1) */
/* Find the Snapshot entry for this ID */
for(e = 0; e < MAX_SV; e++) {
if(s->entries[e].id == sv_ids[q])
break;
}
if(e == MAX_SV) {
printf("UNEXPECTED! Unable to find snapshot entry for id %02i!\n",sv_ids[q]);
continue;
}
/* Find the Space Vehicle entry for this ID */
for(sv = 0; sv < N_SV; sv++) {
if(space_vehicles[sv].id == sv_ids[q])
break;
}
if(sv == N_SV) {
printf("UNEXPECTED! Unable to find Space Vehicle entry!\n");
continue;
}
phase_in_gold_code = (s->entries[e].lock_code_nco >> 1) & 0x7FFFFFFF;
/* calc transmit time milliseconds */
space_vehicles[sv].time_raw = s->entries[e].nav_subframe_of_week * 6000 + s->entries[e].lock_ms_of_frame
+ ((double)phase_in_gold_code)/(1023*(1<<21));
/* Convert from milliseconds to seconds */
space_vehicles[sv].time_raw /= 1000.0;
/* Correct the time using calibration factors */
space_vehicles[sv].pos_t_valid = 0;
sv_calc_corrected_time(sv);
/* calculate the location of the space vehicle */
sv_calc_location(sv, sv_location+valid_locations);
/* Verify that the location is valid */
if(sv_location[valid_locations].x < 40000000 && sv_location[valid_locations].x > -40000000)
if(sv_location[valid_locations].y < 40000000 && sv_location[valid_locations].y > -40000000)
if(sv_location[valid_locations].z < 40000000 && sv_location[valid_locations].z > -40000000)
valid_locations++;
}
#if 1
for(q = 0; q < valid_locations; q++) {
printf("Location is (%16.5f, %16.5f, %16.5f) @ %15.8f\n", sv_location[q].x, sv_location[q].y, sv_location[q].z, sv_location[q].time);
}
#endif
if(valid_locations < 4) {
free(sv_location);
return;
}
A_solve(valid_locations, sv_location, &predicted_location);
#if 1
printf("\nSolved is (%20f, %20f, %20f) @ %20f (alt %20f)\n",
predicted_location.x, predicted_location.y, predicted_location.z, predicted_location.time,
sqrt(predicted_location.x*predicted_location.x
+ predicted_location.y*predicted_location.y
+ predicted_location.z*predicted_location.z));
#endif
LatLonAlt(predicted_location.x, predicted_location.y, predicted_location.z, &lat, &lon, &alt);
printf("Lat/Lon/Alt : %20.6f, %20.6f, %20.1f\n", lat*180/PI, lon*180/PI, alt);
if(position_file != NULL) {
fprintf(position_file,"%16.5f, %16.5f, %16.5f, %15.8f, %20.6f, %20.6f, %20.1f\n",
predicted_location.x, predicted_location.y, predicted_location.z, predicted_location.time,
lat*180/PI, lon*180/PI, alt);
}
free(sv_location);
return;
}
/*****************************************************************************
******************************************************************************
* Routines for processing NAV messages (50 bps BSPK from the satellites) *
******************************************************************************
*****************************************************************************/
static const unsigned char parity[32] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0x25,
0x0B, 0x16, 0x2C, 0x19, 0x32, 0x26, 0x0E, 0x1F,
0x3E, 0x3D, 0x38, 0x31, 0x23, 0x07, 0x0D, 0x1A,
0x37, 0x2F, 0x1C, 0x3B, 0x34, 0x2A, 0x16, 0x29};
static int nav_test_parity(uint_32 d)
{
int i;
/* 'd' holds the 32 bits received, and this function will
* return true if the low 30 bits is a valid subframe -
* the most recent bit is held in bit zero */
i = d>>30;
/* If the last bit of the last subframe is set
* then the data in this frame is flipped */
if(i & 1)
d ^= 0x3FFFFFC0;
for(i = 6; i < 32; i++) {
if(d&(1<<i)) d ^= parity[i];
}
if((d & 0x3F) != 0) return 0;
return 1; /* Success! */
}
/*****************************************************************************
* Used for pulling data out of the raw NAV frames
******************************************************************************/
static unsigned int mask(unsigned u, int n_bits) {
return u & ((1<<n_bits)-1);
}
/******************************************************************************/
static int sign_extend(unsigned u,int len) {
if(len < 32 && u >0)
if(u>>(len-1)&1) u |= 0xFFFFFFFF << len;
return (int)u;
}
/******************************************************************************/
static unsigned int bits(int val, int offset, int len) {
return mask(val >> offset,len);
}
/******************************************************************************/
static unsigned join_bits_u(int val1, int offset1, int len1, int val2, int offset2, int len2) {
return (bits(val1, offset1, len1) << len2) | bits(val2, offset2, len2);
}
/******************************************************************************/
static signed join_bits_s(int val1, int offset1, int len1, int val2, int offset2, int len2) {
return sign_extend(join_bits_u(val1, offset1, len1, val2, offset2, len2),len1+len2);
}
/*****************************************************************************
******************************************************************************
* Routines for dumping out data while debugging *
******************************************************************************
*****************************************************************************/
static void debug_print_orbit(struct Space_vehicle *sv) {
printf("\nOrbit parameters for SV %i:\n", sv->id);
printf("iode %02X\n", sv->nav_orbit.iode);
printf("double M0 = %2.30g;\n", sv->nav_orbit.mean_motion_at_ephemeris);
printf("double delta_n = %2.30g;\n", sv->nav_orbit.delta_n);
printf("double e = %2.30g;\n", sv->nav_orbit.e);
printf("double sqrt_A = %2.30g;\n", sv->nav_orbit.sqrt_A);
printf("double omega_0 = %2.30g;\n", sv->nav_orbit.omega_0);
printf("double i_0 = %2.30g;\n", sv->nav_orbit.inclination_at_ephemeris);
printf("double w = %2.30g;\n", sv->nav_orbit.w);
printf("double omega_dot = %2.30g;\n", sv->nav_orbit.omega_dot);
printf("double idot = %2.30g;\n", sv->nav_orbit.idot);
printf("double Cuc = %2.30g;\n", sv->nav_orbit.Cuc);
printf("double Cus = %2.30g;\n", sv->nav_orbit.Cus);
printf("double Crc = %2.30g;\n", sv->nav_orbit.Crc);
printf("double Crs = %2.30g;\n", sv->nav_orbit.Crs);
printf("double Cic = %2.30g;\n", sv->nav_orbit.Cic);
printf("double Cis = %2.30g;\n", sv->nav_orbit.Cis);
printf("unsigned Toe = %u;\n", sv->nav_orbit.time_of_ephemeris);
printf("Fit %01x\n", sv->nav_orbit.fit_flag);
printf("aodo %02X\n", sv->nav_orbit.aodo);
printf("\n");
}
void debug_print_time(struct Space_vehicle *sv) {
struct tm ts;
char buf[80];
time_t timestamp;
printf("\nTime parameters for SV %i:\n", sv->id);
printf("Week No %i\n", sv->nav_time.week_no);
printf("Accuracy %i\n", sv->nav_time.user_range_accuracy);
printf("Health %i\n", sv->nav_time.health);
printf("IDOC %i\n", sv->nav_time.issue_of_data);
printf("double T_gd = %2.30g;\n", sv->nav_time.group_delay);
printf("double T_oc = %2.30g;\n", sv->nav_time.reference_time);
printf("double a_f2 = %2.30g;\n", sv->nav_time.correction_f2);
printf("double a_f1 = %2.30g;\n", sv->nav_time.correction_f1);
printf("double a_f0 = %2.30g;\n", sv->nav_time.correction_f0);
printf("\n");
timestamp = TIME_EPOCH + sv->nav_time.week_no * 604800;
ts = *localtime(×tamp);
strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", &ts);
printf("Epoch is %u (%s)\n", (unsigned)timestamp, buf);
}
/******************************************************************************
* This is called everytime we have a frame of 300 bits, that passes validation
******************************************************************************/
static void nav_save_frame(struct Space_vehicle *sv) {
unsigned int unflipped[10];
unsigned int handover_word;
int i;
int frame_type = 0;
/* Key the initial inversion for subframe 0 off the preamble.
If the LSB is 0, then it is flipped */
if(sv->navdata.new_subframe[0] & 1)
unflipped[0] = sv->navdata.new_subframe[0];
else
unflipped[0] = ~sv->navdata.new_subframe[0];
/* The next 9 depend on the value of bit 0 of the previous subframe */
for(i = 1; i < 10; i++) {
if(sv->navdata.new_subframe[i-1] & 1)
unflipped[i] = ~sv->navdata.new_subframe[i];
else
unflipped[i] = sv->navdata.new_subframe[i];
}
/* Handover word is in subframe 1 of every frame. It includes
the time of start for the NEXT frame. It gets held in
next_time_of_week till the end of frame occurs */
handover_word = unflipped[1];