-
Notifications
You must be signed in to change notification settings - Fork 13
/
rrlpserver.erl
executable file
·1382 lines (1262 loc) · 51 KB
/
rrlpserver.erl
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
% Copyright 2011 Range Networks, Inc.
% Copyright 2011 Free Software Foundation, Inc.
%
% This software is distributed under the terms of the GNU Affero Public License.
% See the COPYING file in the main directory for details.
%
% This use of this software may be subject to additional restrictions.
% See the LEGAL file in the main directory for details.
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU Affero 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 Affero General Public License for more details.
%
% You should have received a copy of the GNU Affero General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
-module(rrlpserver).
-export([run/0]).
-include("RRLP.hrl").
-include_lib("kernel/include/file.hrl").
% Here are my suggestions for reading and reference for an experienced
% programmer who is new to erlang, who wants to focus on the features
% used in rrlpserver.erl. If you read the Readings and use the
% References, you should be off to a good start, and may even have
% all you need to mess about with the rrlp server.
%
% Readings:
%
% http://www.erlang.org/course/sequential_programming.html
% http://www.erlang.org/doc/programming_examples/list_comprehensions.html
%
% Reference:
%
% http://www.erlang.org/doc/reference_manual/expressions.html
% http://www.erlang.org/doc/man/string.html
% http://www.erlang.org/doc/man/lists.html
% http://www.erlang.org/doc/man/calendar.html
% http://www.erlang.org/doc/man/io.html
% This is an HTTP server that receives GET queries for encoding and decoding APDUs
% for RRLP, along with queries for self-testing. The queries:
%
% input
% query=loc
% output
% apdu=<hex encoding of apdu requesting gps location, including reference location,
% minimum accuracy, and maximum response time>
%
% input
% query=assist
% output
% apdu=<hex encoding of apdu containing assist information to aid the gps receiver.
% there are several apdu=<...> lines, due to the mobile's inability to handle segmented lines.>
%
% input
% query=apdu
% apdu=<hex encoding of apdu to decode>
% output for ack
% ack=
% output for position response
% latitude=<latitude in degrees>
% longitude=<longitude in degrees>
% altitude=<altitude in meters>
% positionError=<position uncertainty in meters>
% output for protocol error
% error=protocolError <protocol error>
%
% input
% query=decode
% apdu=<hex-encoded apdu>
% output
% bits=<bits of apdu>
% decode=<decoded apdu>
%
% input
% query=raw
% apdu=<hex-encoded apdu>
% output
% bits=<bits of apdu>
% raw decode=<decoded apdu, not assuming PDU as in "decode", above>
%
% input
% query=testpos
% output
% lists satellites and their positions
%
% input
% query=testlled
% output
% tests encoding and decoding of latitude and longitude
%
% optional outputs of all commands:
% error=<error string. implies query failed>
% note=<informative note>
% info=<informative note>
% and there are other outputs that get ignored
%
% Configuration parameters are also included in the QUERY_STRING:
% GSM.RRLP.ACCURACY
% minimum accuracy for location request, in meters
% K in 10(1.1**K-1). See 3GPP 03.32, sect 6.2
% GSM.RRLP.ALMANAC.ASSIST.PRESENT
% 0=>Don't include almanac in assist apdu
% 1=>DO include it
% GSM.RRLP.ALMANAC.REFRESH.TIME
% Number of hours after which to refresh almanac file
% GSM.RRLP.ALMANAC.URL
% URL from which to get almanac file
% GSM.RRLP.EPHEMERIS.ASSIST.COUNT
% Number of satellites to include in ephemeris assist data (navigation model)
% GSM.RRLP.EPHEMERIS.REFRESH.TIME
% Number of hours after which to refresh ephemeris file
% GSM.RRLP.EPHEMERIS.URL
% URL from which to get ephemeris file
% GSM.RRLP.RESPONSETIME
% maximum response time in seconds
% N in 2**N. See 3GPP 04.31 sect A.2.2.1
% Note that OpenBTS timeout is 130 sec = max response time + 2
% GSM.RRLP.SEED.ALTITUDE
% seed altitude in meters
% GSM.RRLP.SEED.LATITUDE
% seed latitude in degrees
% 0=equator, 90=north pole, -90=south pole
% GSM.RRLP.SEED.LONGITUDE
% seed longitude in degrees
% 0=Greenwich, +=east, -=west
% Execution starts in "run" because it's exported (above) and the erl
% command in rrlpserver.cgi says to start in "run".
% HTTP puts the query in environment variable QUERY_STRING.
% Queries are in the form of "key=value", separated by ampersands.
% All the queries are numbers or simple strings, except for the two URLs,
% which would mess up decoding, so the two URLs are hex-encoded.
run() ->
io:format("Content-type: text/html\n\n"),
case os:getenv("QUERY_STRING") of
false ->
io:format("error=no QUERY_STRING\n");
"" ->
io:format("error=empty QUERY_STRING\n");
QUERY_STRING ->
io:format("QUERY_STRING=~p\n", [QUERY_STRING]),
% decode QUERY_STRING into list of [key,value] lists
LofL = [string:tokens(Y,"=") || Y <- string:tokens(QUERY_STRING, "&")],
% convert it to list of {key,value} tuples because that's what dict:from_list wants
LofT = [list_to_tuple(X) || X <- LofL],
% generate a dictionary
Dict = dict:from_list(LofT),
% put the dictionary into the "process dictionary", a global dictionary
queryStringToProcessDictionary(LofT),
% take a look at the query and do something with it
case dict:find("query", Dict) of
{ok,"testpos"} -> testpos();
{ok,"testlled"} -> testlled();
{ok,"raw"} -> raw(Dict);
{ok,"decode"} -> decode(Dict);
{ok,"assist"} -> pduOut(assist());
{ok,"loc"} -> locate();
{ok,"apdu"} ->
case dict:find("apdu", Dict) of
{ok,APDU} ->
respond(APDU);
error ->
io:format("error=no apdu\n")
end;
{ok,_} ->
io:format("error=unknown query\n");
error ->
io:format("error=no query\n")
end
end.
% Put the QUERY_STRING {key,value} dictionary into the (global) process dictionary.
% It's generally frowned upon to use global data in erlang, but the configuration data
% is global in OpenBTS, so I'm making it global here.
queryStringToProcessDictionary([]) -> nop;
% queryStringToProcessDictionary([[Key,Val] | Rest]) ->
queryStringToProcessDictionary([{Key,Val0}|Rest]) ->
% check if the key has .URL in it
case (string:str(Key,".URL")) of
0 ->
% it doesn't, so not conversion needed
Val = Val0;
_ ->
% it does, so it's on of the URLs, needing hex decoding
Val = hexToString(Val0)
end,
% this puts the key and value into the process dictionary
erlang:put(Key, Val),
queryStringToProcessDictionary(Rest).
hexToString([]) -> [];
hexToString([A,B|T]) ->
% take the next two hex digits and turn them into an ascii character, and recurse
[unhex(A)*16+unhex(B) | hexToString(T)].
% turn hex digits into their binary values
unhex(C) when C >= $0, C =< $9 -> C - $0;
unhex(C) when C >= $a, C =< $f -> C - $a + 10;
unhex(C) when C >= $A, C =< $F -> C - $A + 10.
% lookup Key in the process dictionary and return Value
getStr(Key) ->
case erlang:get(Key) of
undefined ->
io:format("missing configuration value for ~p\n", [Key]),
undefined;
Value ->
Value
end.
% lookey Key in the process dictionary and return numeric Value
getNum(Key) ->
Value = getStr(Key),
to_num(Value).
% test - apdu-encode and apdu-decode two sets of latitude and longitude
testlled() ->
testlled(30.1234, -120.5678),
testlled(-30.1234, 120.5678).
% apdu-encode latitude and longitude and decode, printing before and after to see if you get back the original
testlled(Lat, Long) ->
A = encodeLatitude(Lat),
B = encodeLongitude(Long),
C = decodeLatitude(A),
D = decodeLongitude(B),
io:format("~p\n", [Lat]),
io:format("~p\n", [C]),
io:format("~p\n", [Long]),
io:format("~p\n", [D]).
% display raw decode of apdu
raw(Dict) ->
% get the apdu
{ok,APDU} = dict:find("apdu", Dict),
% turn it into binary
Bin = util:hex_to_bin(APDU),
io:format("bits=~p\n", [Bin]),
% decode binary. This calls a routine built by the ASN1 compiler.
X = 'RRLP':decode('PDU', Bin),
io:format("raw decode = ~p\n", [X]).
% Like raw, but assumes some structure to the apdu
decode(Dict) ->
{ok,APDU} = dict:find("apdu", Dict),
Bin = util:hex_to_bin(APDU),
io:format("bits=~p\n", [Bin]),
case 'RRLP':decode('PDU', Bin) of
{ok, {'PDU', _, Component}} ->
io:format("decode=~p\n", [Component]);
Else ->
io:format("error=~p\n", [Else])
end.
% This takes a list of apdus and prints them out one per line.
% We have to break up the assist apdu into several apdus because
% the mobile devices don't handle segmentation described in the spec.
pduOut([]) -> nop;
pduOut([Pdu|Rest]) ->
apdu(Pdu),
pduOut(Rest).
% generate and print apdu for location request
locate() ->
% read ephemeris because the location request includes reference time, which needs info in the ephemeris
Ephemeris = readEphemeris(),
% {_,Asts} = Ephemeris,
% io:format("~p\n", [[1+dictFetch("satelliteID", Ast) || Ast <- Asts]]),
% generate the request apdu
% desired accuracy and response time are configuration parameters
Req = locationRequest(getNum("GSM.RRLP.ACCURACY"), getNum("GSM.RRLP.RESPONSETIME"), Ephemeris),
% print the apdu
apdu(Req).
% print an apdu
apdu(APDU) ->
% encode into binary, using routine generated by ASN1 compiler
case xrrlp:encodePDU(APDU) of
{ok, Binary} ->
% hex encode
Hex = util:bin_to_uhex_string(Binary),
io:format("note=apdu lth = ~p bytes\n", [length(Hex)/2]),
% print it
io:format("apdu=~s\n", [Hex]);
Else ->
io:format("error=encode returns ~p\n", [Else])
end.
% APDU is a hex-encoded response from the mobile
respond(APDU) ->
% io:format("APDU = ~p<br>\n", [APDU]),
% convert it to binary
Bin = util:hex_to_bin(APDU),
case 'RRLP':decode('PDU', Bin) of
{ok, {'PDU', _, Component}} -> % ignoring reference number
case Component of
{assistanceDataAck,_} ->
% an acknowledge to assistance data we sent
io:format("ack=\n");
{msrPositionRsp, MsrPositionRsp} ->
% a position response from a position request
positionResponse(MsrPositionRsp);
{protocolError, ProtocolError} ->
% a protocol error
ErrorCause = ProtocolError#'ProtocolError'.errorCause,
io:format("error=protocolError ~w\n", [ErrorCause]);
_ ->
io:format("error=unexpected apdu component: ~w\n", [Component])
end;
Else ->
io:format("error=~w\n", [Else])
end.
% generate the apdu for a location request
locationRequest(Accuracy, ResponseTime, Ephemeris) ->
#'PDU'{referenceNumber=1,
component={msrPositionReq, #'MsrPosition-Req'{
% you can include all the assistance data you want within the loc req
%'gps-AssistData'=#'GPS-AssistData'{
% we're just going with reference time
% the rest of the assistance data goes separately
% controlHeader=#'ControlHeader'{
% referenceTime=referenceTime(Ephemeris)
% }
%},
% here's the loc req, telling about method, accuracy, response time
positionInstruct=#'PositionInstruct'{
methodType={msBased, Accuracy}, % did the spec change?
positionMethod=gps,
measureResponseTime=ResponseTime,
useMultipleSets=oneSet
}}}}.
% decode the position response to our position request
positionResponse(MsrPositionRsp) ->
io:format("info=~w\n", [MsrPositionRsp]),
% extract the location info from the response
Loc = MsrPositionRsp#'MsrPosition-Rsp'.locationInfo,
% extract the position estimate from the location info
Pos = Loc#'LocationInfo'.posEstimate,
% lat and long are always in same place regardless of position estimate type
Lat = decodeLatitude(string:sub_string(Pos, 2, 4)),
Long = decodeLongitude(string:sub_string(Pos, 5, 7)),
io:format("latitude=~w\n", [Lat]),
io:format("longitude=~w\n", [Long]),
% where the altitude and position error are depends on position estimate type
% see 23.032, sect 7
case lists:nth(1,Pos) bsr 4 of
1 ->
Altitude = 0,
K = lists:nth(8, Pos),
C = 10,
X = 0.1,
Error = C*(math:pow(1+X,K)-1);
3 ->
Altitude = 0,
Error = lists:nth(8, Pos);
8 ->
Altitude = decodeAltitude(Pos),
Error = 0;
9 ->
Altitude = decodeAltitude(Pos),
Error = lists:nth(10, Pos);
_ ->
Altitude = 0,
Error = 0
end,
io:format("altitude=~w\n", [Altitude]),
io:format("positionError=~w\n", [Error]).
% decode altitude
% see 23.032, sect 7.3.5
decodeAltitude(Pos) ->
Mag = ((lists:nth(8,Pos) bsl 8) bor lists:nth(9,Pos)) band 16#7fff,
case lists:nth(8,Pos) band 16#80 == 0 of
true -> Mag;
false -> -Mag
end.
% encode latitude
% see 23.032, sect 7.3.1
encodeLatitude(Lat) ->
X = oneElseNegOne(Lat > 0) * Lat / (180 * math:pow(2, -24)),
encodeOctets(X, 3, Lat < 0).
% decode latitude
% see 23.032, sect 7.3.1
decodeLatitude([A,B,C]) ->
X = ((A rem 128) bsl 16) bor (B bsl 8) bor C,
oneElseNegOne(A < 128) * X * 180 * math:pow(2, -24).
% decode longitude
% see 23.032, sect 7.3.1
decodeLongitude([A,B,C]) ->
X = (A bsl 16) bor (B bsl 8) bor C,
Y = X * 180 * math:pow(2, -23),
Y - 360 * oneElseZero(Y > 180).
% encode longitude
% see 23.032, sect 7.3.1
encodeLongitude(Long) ->
X = Long + 360 * oneElseZero(Long < 0),
Y = X / (180 * math:pow(2, -23)),
encodeOctets(Y, 3, false).
% encode a value into a list of octets
% if sign is true, set the sign bit in the first octet
encodeOctets(Value, Octets, Sign) ->
X = lists:reverse(lists:seq(0,Octets-1)),
Y = [(round(Value) bsr (8*B)) band 16#ff || B <- X],
[hd(Y) + 128 * oneElseZero(Sign) | tl(Y)].
% a handy function to avoid case statements
oneElseZero(true) -> 1;
oneElseZero(false) -> 0.
% another handy function to avoid case statements
oneElseNegOne(true) -> 1;
oneElseNegOne(false) -> -1.
% returns a list of assistance pdu's, to be sent separately and safely to the mobile
%
assist() ->
% we need the ephemeris for the global data (utc and ionospheric)
Ephemeris=readEphemeris(),
% the small ephemeris stuff is the ref location and utc and ionospheric data
SmallEphemerisStuff = [smallEphemerisStuff(Ephemeris)],
% data from the almanac
AlmanacStuff = genAlmanacStuff(),
% navigation model - data from the ephemeris
EphemerisStuff = genEphemerisStuff(Ephemeris),
% put them all together into a list of pdu's
% AlmanacStuff ++ SmallEphemerisStuff ++ EphemerisStuff.
AlmanacStuff ++ EphemerisStuff ++ SmallEphemerisStuff.
% generate ephemeris apdus
genEphemerisStuff({Global,Sats}) ->
% get the ephemeris count (number of satellites we want) from config params
EphemerisCount = getNum("GSM.RRLP.EPHEMERIS.ASSIST.COUNT"),
case EphemerisCount of
0 ->
% if it's 0, then return empty list
[];
_ ->
% otherwise take that many satellites, and break them into safe-size apdus
genBestEphemeris({Global, lists:sublist(Sats,1,EphemerisCount)})
end.
% recursive function that breaks list of satellites into groups of 3 (while actually generating the apdu)
genBestEphemeris({_,[]}) -> [];
genBestEphemeris({Global,Sats}) ->
[navigationModelSubset({Global,Sats}, 1, 3) | genBestEphemeris({Global, safeNthTail(3, Sats)})].
% generate almanac apdus
genAlmanacStuff() ->
% get the almanac flag (whether we want any almanac data) from config params
AlmanacFlag = getNum("GSM.RRLP.ALMANAC.ASSIST.PRESENT"),
case AlmanacFlag of
0 ->
% if 0, then return empty list
[];
1 ->
% otherwise read the almanac and generate the apdus
Almanac = readAlmanac(),
genAlmanacStuff(Almanac)
end.
% recursive function that breaks list of satellites into groups of 8 (while actually generating the apdu)
genAlmanacStuff({_,[]}) -> [];
genAlmanacStuff({Global,Sats}) ->
[almanacSubset({Global,Sats}, 1, 8) | genAlmanacStuff({Global, safeNthTail(8, Sats)})].
% lists:nthtail fails if you go path the end of a list.
% this function returns [] if you go past the end
safeNthTail(N, List) when length(List) =< N -> [];
safeNthTail(N, List) -> lists:nthtail(N, List).
% generate an apdu that contains reference location and utc and ionospheric info
smallEphemerisStuff(Ephemeris) ->
#'PDU'{referenceNumber=1,
component={assistanceData, #'AssistanceData'{
'gps-AssistData'=#'GPS-AssistData'{
controlHeader=#'ControlHeader'{
% reference time is moved to the location request
% referenceTime=referenceTime(Ephemeris),
refLocation=refLocation(),
ionosphericModel=ionosphericModel(Ephemeris),
utcModel=utcModel(Ephemeris)
}
},
moreAssDataToBeSent='noMoreMessages'
}
}
}.
% generate the apdu for Length satellites in the ephmeris, starting with First
navigationModelSubset(Ephemeris, First, Length) ->
#'PDU'{referenceNumber=1,
component={assistanceData, #'AssistanceData'{
'gps-AssistData'=#'GPS-AssistData'{
controlHeader=#'ControlHeader'{
navigationModel=navigationModel(Ephemeris, First, Length)
}
},
moreAssDataToBeSent='moreMessagesOnTheWay'
}
}
}.
% generate the apdu for Length satellites in the almanac, starting with First
almanacSubset(Almanac, First, Length) ->
{Week, Elements} = Almanac,
ElementsSubset = lists:sublist(Elements, First, Length),
#'PDU'{referenceNumber=1,
component={assistanceData, #'AssistanceData'{
'gps-AssistData'=#'GPS-AssistData'{
controlHeader=#'ControlHeader'{
almanac=#'Almanac'{alamanacWNa=Week, almanacList=ElementsSubset}
}}}}}.
% generate apdu for reference time
referenceTime(Ephemeris) ->
% current utc
{Today,Time} = erlang:universaltime(),
% break out pieces of it
{Year, Month, DayOfMonth} = Today,
{Hours, Minutes, Seconds} = Time,
% what nice, handy functions!
DayOfWeek7 = calendar:day_of_the_week(Today),
% day_of_the_week returns 7 for Sunday, but we need it to be 0
DayOfWeek = DayOfWeek7 rem 7,
% utc seconds into the week
UtcSow = ((DayOfWeek * 24 + Hours) * 60 + Minutes) * 60 + Seconds,
% get a day number for Jan 6, 1980 (when gps time started)
DaysToWeek0 = calendar:date_to_gregorian_days(1980,1,6),
% get a day number for the beginning of this week
DaysToLastSunday = calendar:date_to_gregorian_days(Year,Month,DayOfMonth) - DayOfWeek,
% what is the utc week number for this week
UtcWeek = round((DaysToLastSunday - DaysToWeek0) / 7),
% get leap second difference
{GlobalAst, _} = Ephemeris,
UtcDeltaTls = dictFetch("utcDeltaTls", GlobalAst),
% convert utc to gps time
Diff = UtcSow - UtcDeltaTls,
case Diff < 0 of
true ->
GpsSow = Diff + 604800,
GpsWeekFull = UtcWeek - 1;
false ->
GpsSow = Diff,
GpsWeekFull = UtcWeek
end,
% encode the gps time for the apdu
GPSTOW23b = roundAndCheck("GPSTOW23b", 0, GpsSow/0.08, 0, 7559999),
GpsWeek = GpsWeekFull rem 1024,
% generate the apdu
#'ReferenceTime'{
gpsTime = #'GPSTime'{
gpsTOW23b = GPSTOW23b,
gpsWeek = GpsWeek
}
}.
% generate the apdu for reference location
refLocation() ->
% get latitude, longitude, and altitude from config params
Lat = getNum("GSM.RRLP.SEED.LATITUDE"),
Long = getNum("GSM.RRLP.SEED.LONGITUDE"),
Altitude = round(getNum("GSM.RRLP.SEED.ALTITUDE")),
% generate the apdu
% see 23.032, sect 7.3.6
EllipsoidPointWithAltitudeAndUncertaintyEllipsoid = [144] ++ encodeLatitude(Lat) ++ encodeLongitude(Long) ++ encodeOctets(Altitude, 2, false) ++ [7,7,0,7,0],
#'RefLocation'{threeDLocation = EllipsoidPointWithAltitudeAndUncertaintyEllipsoid}.
% generate navigation model apdu from Length satellite asts, starting at First
navigationModel({_, SatAsts}, First, Length) ->
% get the satellite asts we want
SatAstsOfInterest = lists:sublist(SatAsts, First, Length),
% turn them into apdu elements
SeqOfNavModelElement = [seqOfNavModelElement(SatAst) || SatAst <- SatAstsOfInterest],
% generate the apdu
#'NavigationModel'{navModelList=SeqOfNavModelElement}.
% given a dictionary of satellite ephemeris parameters, generate apdu encoding for navigation model
seqOfNavModelElement(SatAst) ->
#'NavModelElement'{
satelliteID = dictFetch("satelliteID", SatAst)+1,
satStatus = {newSatelliteAndModelUC, uncompressedEphemeris(SatAst)}}.
% fetch the parameters from the dictionary, and generate a big old apdu record
uncompressedEphemeris(SatAst) ->
#'UncompressedEphemeris'{
ephemCodeOnL2 = dictFetch("ephemCodeOnL2", SatAst),
ephemURA = dictFetch("ephemURA", SatAst),
ephemSVhealth = dictFetch("ephemSVhealth", SatAst),
ephemIODC = dictFetch("ephemIODC", SatAst),
ephemL2Pflag = dictFetch("ephemL2Pflag", SatAst),
ephemSF1Rsvd = #'EphemerisSubframe1Reserved'{
reserved1 = 0,
reserved2 = 0,
reserved3 = 0,
reserved4 = 0},
ephemTgd = dictFetch("ephemTgd", SatAst),
ephemToc = dictFetch("ephemToc", SatAst),
ephemAF2 = dictFetch("ephemAF2", SatAst),
ephemAF1 = dictFetch("ephemAF1", SatAst),
ephemAF0 = dictFetch("ephemAF0", SatAst),
ephemCrs = dictFetch("ephemCrs", SatAst),
ephemDeltaN = dictFetch("ephemDeltaN", SatAst),
ephemM0 = dictFetch("ephemM0", SatAst),
ephemCuc = dictFetch("ephemCuc", SatAst),
ephemE = dictFetch("ephemE", SatAst),
ephemCus = dictFetch("ephemCus", SatAst),
ephemAPowerHalf = dictFetch("ephemAPowerHalf", SatAst),
ephemToe = dictFetch("ephemToe", SatAst),
ephemFitFlag = dictFetch("ephemFitFlag", SatAst),
ephemAODA = 0, % dictFetch("ephemAODA", SatAst), % TODO - can't find it
ephemCic = dictFetch("ephemCic", SatAst),
ephemOmegaA0 = dictFetch("ephemOmegaA0", SatAst),
ephemCis = dictFetch("ephemCis", SatAst),
ephemI0 = dictFetch("ephemI0", SatAst),
ephemCrc = dictFetch("ephemCrc", SatAst),
ephemW = dictFetch("ephemW", SatAst),
ephemOmegaADot = dictFetch("ephemOmegaADot", SatAst),
ephemIDot = dictFetch("ephemIDot", SatAst)}.
% same as above for ionospheric model
ionosphericModel({GlobalAst, _}) ->
#'IonosphericModel'{
alfa0 = dictFetch("alfa0", GlobalAst),
alfa1 = dictFetch("alfa1", GlobalAst),
alfa2 = dictFetch("alfa2", GlobalAst),
alfa3 = dictFetch("alfa3", GlobalAst),
beta0 = dictFetch("beta0", GlobalAst),
beta1 = dictFetch("beta1", GlobalAst),
beta2 = dictFetch("beta2", GlobalAst),
beta3 = dictFetch("beta3", GlobalAst)}.
% same as above for utc model
utcModel({GlobalAst, _}) ->
#'UTCModel'{
utcA1 = dictFetch("utcA1", GlobalAst),
utcA0 = dictFetch("utcA0", GlobalAst),
utcTot = dictFetch("utcTot", GlobalAst),
utcWNt = dictFetch("utcWNt", GlobalAst),
utcDeltaTls = dictFetch("utcDeltaTls", GlobalAst),
utcWNlsf = dictFetch("utcWNlsf", GlobalAst),
utcDN = dictFetch("utcDN", GlobalAst),
utcDeltaTlsf = dictFetch("utcDeltaTlsf", GlobalAst)}.
% get almanac or ephemeris file from Url and cache it in Filename.
% cache for up to MaxAgeInHours.
% TODO - It might be better to use one of erlang's own (indirect) locking mechanisms, but
% that would require deciding whether to use some persistent store (mnesia?) or a daemon
% that updates and serves this info. And coding it.
% [I used to think it would be better to cache the encoded APDUs instead of the files, but
% now I think that would not be good, because the APDUs have time information that goes bad
% immediately, and satellite ordering which can also go bad immediately.]
% Gotta lock before checking age of file, because someone else could lock, replace the file,
% and unlock between when you check age and try to lock. So end up locking just to read.
% Not optimal.
getFile(FileName, Url, MaxAgeInHours) ->
% attempt a lock
LockFile = FileName ++ ".lock",
R = os:cmd("lockfile -r0 " ++ LockFile),
% check if the output of lockfile command has "Sorry" in it
T = string:str(R, "Sorry"),
if
T == 0 ->
% "Sorry" not in output
% file was not locked - read (or update and read), and remove lock
F = getFile1(FileName, Url, MaxAgeInHours),
os:cmd("rm -f " ++ LockFile),
F;
true ->
% "Sorry" IS in output
% file was locked - wait a sec and try again
io:format("waiting\n"),
timer:sleep(1000),
getFile(FileName, Url, MaxAgeInHours)
end.
% if Filename is younger than MaxAgeInHours, return contents of Filename
% if older, refresh from Url, then return contents
getFile1(FileName, Url, MaxAgeInHours) ->
% get age of file
MaxAgeInSeconds = round(60*60*MaxAgeInHours),
Now = calendar:datetime_to_gregorian_seconds(erlang:localtime()),
case file:read_file_info(FileName) of
% if we can't get file info, it's probably not there. assume file is Very Very Old
{error, _} -> ModTime = 0;
% otherwise get the last modified time of the file
{ok, FileInfo} -> ModTime = calendar:datetime_to_gregorian_seconds(FileInfo#'file_info'.mtime)
end,
% calculate the age of the file
AgeInSeconds = Now - ModTime,
io:format("info=~p is ~.1f hours old\n", [FileName, AgeInSeconds/3600]),
% check if it's too old
if
AgeInSeconds > MaxAgeInSeconds ->
% it's too old - update
QuotedUrl = string:join(["'", Url, "'"], ""),
Cmd = string:join(["wget -q -O", FileName, QuotedUrl], " "),
io:format("info=~p\n", [Cmd]),
os:cmd(Cmd);
true ->
% it's not too old - do nothing
nop
end,
% and now read
case file:open(FileName, [read]) of
{error, Reason} -> io:format("error=~p\n", [Reason]), [];
{ok, Device} -> get_all_lines(Device, [])
end.
% read and return all the lines from Device
get_all_lines(Device, Accum) ->
% get_line reads one line
case io:get_line(Device, "") of
% if eof, then close Device, reverse the list of lines, and return it
eof -> file:close(Device), lists:reverse(Accum);
% otherwise clean the line and recursively build a (backwards, for efficiency) list of lines
Line -> get_all_lines(Device, [cleanLine(Line)|Accum])
end.
% read the almanac file, and parse it into a dictionary of global data and satellite fields
% also massage the data (unit conversions, scaling, etc) to go into the apdu
readAlmanac() ->
% get the parse table
Table = parseTable(),
% read the file
% the url and max cache time are config params
Lines = getFile("/tmp/almanac", getStr("GSM.RRLP.ALMANAC.URL"), getNum("GSM.RRLP.ALMANAC.REFRESH.TIME")),
% io:format("Lines=~p\n", [Lines]),
% Apply the parser to the lines.
parseAlmanac([], Lines, [], Table, 0).
% parseAlmanac reads a line a calls itself, building a list of fields culled form the almanac,
% periodically turning that list into a dictionary and building a list of dictionaries, which
% eventually becomes the almanac apdu. And the final wart is the single piece of global data,
% the week, which, when found, gets passed along as a separate argument to parseAlmanac.
% 1st arg: Ast = the list of (label,value) pairs for a satellite
% 2nd arg: Lines = lines remaining from almanac
% 3rd arg: AlmanacSoFar = list of apdu elements, one for each satellite
% 4th arg: Table = the parse table
% 5th arg: Week = which week is this
%
% when there are no more lines, return a tuple with the week (global) and almanac (satellite list)
parseAlmanac(_, [], AlmanacSoFar, _, Week) -> {Week, AlmanacSoFar};
% otherwise...
parseAlmanac(Ast, Lines, AlmanacSoFar, Table, Week) ->
% peel off next line
[NextLine|RestOfLines] = Lines,
% io:format("line=~s\n", [NextLine]),
% get the first and last fields from the line
case parseNextAlmanacLine(NextLine) of
% ignore the lines with asterisks in the first field
{"********",_} -> parseAlmanac(Ast, RestOfLines, AlmanacSoFar, Table, Week);
% save week for global alamanacWNa
{"week:",SetWeek} -> parseAlmanac(Ast, RestOfLines, AlmanacSoFar, Table, setWeek(SetWeek));
% blank line: convert ast to element and add to almanac
{"",_} -> parseAlmanac([], RestOfLines, [astToElement(Ast) | AlmanacSoFar], Table, Week);
% otherwise first field is index into parse table, and last field is value
{FirstField,LastField} ->
% get encoding info from parse table
{ok, [Label, Correction, Scale, Min, Max]} = dict:find(FirstField, Table),
% encode the value
AstEntry = {Label,encodeAndCheck(Label, LastField, Correction, Scale, Min, Max)},
% add {label,encoded value} to Ast
parseAlmanac([AstEntry|Ast], RestOfLines, AlmanacSoFar, Table, Week)
end.
% I really want to replace this with to_num, but I'm documenting now, and if
% you change too much code while documenting you end up breaking things.
setWeek(Week) ->
case string:to_integer(Week) of
{error, _} -> 0;
{Num, _} -> Num rem 256
end.
% return a parse table that tells what almanac fields go where, and how to encode them for the apdu
parseTable() -> dict:from_list ([
% name of field in almanac file
% name in ASN records, correction type, scaling (exponent of 2), min after scaling, max after scaling
% The post-scaling values are what go into the ASN elements.
{"ID:", ["satelliteID", 4, 0, 0, 63]},
{"Eccentricity:", ["almanacE", 0, -21, 0, 65535]},
{"Time", ["alamanacToa", 0, 12, 0, 255]},
{"Orbital", ["almanacKsii", 2, -19, -32768, 32767]},
{"Rate", ["almanacOmegaDot", 1, -38, -32768, 32767]},
{"Health:", ["almanacSVhealth", 0, 0, 0, 255]},
{"SQRT(A)", ["almanacAPowerHalf", 0, -11, 0, 16777215]},
{"Right", ["almanacOmega0", 1, -23, -8388608, 8388607]},
{"Argument", ["almanacW", 1, -23, -8388608, 8388607]},
{"Mean", ["almanacM0", 1, -23, -8388608, 8388607]},
{"Af0(s):", ["almanacAF0", 0, -20, -1024, 1023]},
{"Af1(s/s):", ["almanacAF1", 0, -38, -1024, 1023]}]).
% turn a list of {label,value} for a satellite tuples into an apdu almanac element
astToElement(Ast) ->
Dict = dict:from_list(Ast),
#'AlmanacElement'{
satelliteID = dictFetch("satelliteID", Dict),
almanacE = dictFetch("almanacE", Dict),
alamanacToa = dictFetch("alamanacToa", Dict),
almanacKsii = dictFetch("almanacKsii", Dict),
almanacOmegaDot = dictFetch("almanacOmegaDot", Dict),
almanacSVhealth = dictFetch("almanacSVhealth", Dict),
almanacAPowerHalf = dictFetch("almanacAPowerHalf", Dict),
almanacOmega0 = dictFetch("almanacOmega0", Dict),
almanacW = dictFetch("almanacW", Dict),
almanacM0 = dictFetch("almanacM0", Dict),
almanacAF0 = dictFetch("almanacAF0", Dict),
almanacAF1 = dictFetch("almanacAF1", Dict)}.
% return the first and last field of an almanac line
parseNextAlmanacLine(Line) ->
% tokenize the line
Fields = string:tokens(Line, " "),
case length(Fields) of
0 ->
% blank line
{"",undefined};
_ ->
% otherwise return first and last fields
FirstField = lists:nth(1, Fields),
LastField = lists:last(Fields),
{FirstField, LastField}
end.
% convert string representation of number into a number
to_num(String) ->
Zeroed = case String of
% to_float doesn't like numbers that start with decimal point, so prepend 0
[$. | Rest] -> [$0, $. | Rest];
% similarly, -.digits -> -0.digits
[$-, $. | Rest] -> [$-, $0, $. | Rest];
% otherwise do nothing
_ -> String
end,
{Converted,_} = case string:to_float(Zeroed) of
% if to_float fails, then do to_integer
{error,_} -> string:to_integer(Zeroed);
% otherwise return the float number
Y -> Y
end,
Converted.
% The asn code does the range check too, but doesn't give good feedback.
% Plus when it's live we don't want to crash.
% Instead, we issue a warning, make the value legal, and keep going.
% Label = apdu element name, plus we use it for error message
% Value = the value
% Correction = code that tells what sort of unit conversion is needed
% Scale = scaling needed for apdu conversion
% Min, Max = range of legal values
encodeAndCheck(Label, Value, Correction, Scale, Min, Max) ->
% convert string to number
Converted = to_num(Value),
% apply correction
Corrected = case Correction of
% 0 => none
0 -> Converted;
% 1 => semicircles to radians
1 -> Converted / math:pi();
% 2 => semicircles to radians plus bias (for inclination)
2 -> Converted / math:pi() - 0.3;
% 3 => modulo 256
3 -> Converted rem 256;
% 4 => subtract one (for satellite number)
4 -> Converted - 1
end,
% apply the scaling
Scaled = Corrected / math:pow(2, Scale),
% turn into an integer, and check that its in the legal range
roundAndCheck(Label, Converted, Scaled, Min, Max).
% make sure value is in the range [min..max]
% if it isn't, issure warning and make it legal
roundAndCheck(Label, Converted, Value, Min, Max) ->
Rounded = round(Value),
case Rounded < Min of
true ->
rangeError(Label, Converted, Rounded, Min, Max),
Min;
false ->
case Rounded > Max of
true ->
rangeError(Label, Converted, Rounded, Min, Max),
Max;
false ->
Rounded
end
end.
% the out-of-range warning
rangeError(Label, Converted, Rounded, Min, Max) ->
io:format("range error=~s of ~p (~p) doesn't fit in (~p,~p)\n", [Label, Converted, Rounded, Min, Max]).
% read the ephemeris, return a dictionary of global params, and a list of dictionaries of satellite parameters
% the list is sorted, closest (to reference location) first
readEphemeris() ->
% read the adjustment table that gives corrections, scaling, etc
AdjustTable = ephemerisAdjustTable(),
% read the file. the url and max cache age are config params
Lines = getFile("/tmp/ephemeris", getStr("GSM.RRLP.EPHEMERIS.URL"), getNum("GSM.RRLP.EPHEMERIS.REFRESH.TIME")),
% io:format("Lines=~p\n", [Lines]),
% parse the lines from the global part of the ephemeris
% RestOfLines = the satellite part of the ephemeris
% GlobalAst = list of {label, value} tuples form the global part of the ephemeris
{RestOfLines, GlobalAst} = parseGlobalEphemeris(Lines, AdjustTable, []),
% turn global ast into global dictionary
GlobalAstDict = dict:from_list(GlobalAst),
% parse the lines from the non-global part of the ephemeris
% SatAsts = list of {label, value} tuples form the non-global part of the ephemeris
SatAsts = parseSatEphemeris(RestOfLines, AdjustTable, []),
% turn SatAsts into list of dictionaries
SatAstDicts = [dict:from_list(SatAst) || SatAst <- SatAsts],
% turn SatAsts into list of {dictionary,angle} where angle = the angle between ref loc and the satellite (wrt the center of the earth)
SatAstDictsAndAngles = [{SatAst,angleBetween(SatAst)} || SatAst <- SatAstDicts],
% sort them, smallest angle first
SortedDicts = mySort(SatAstDictsAndAngles),
% return the global dictionary and list of sorted satellite dictionaries
{GlobalAstDict, SortedDicts}.
% For [{Thing,Value},...], mySort will sort by Value, then return [Thing,...]
% In other words, if you have a list of things you want sorted, turn them into a
% list of tuples, and in each tuple you put the thing and the value associated with it,
% and this will sort so that min value comes first, then throw out the values, leaving
% just the things.
mySort(Unsorted) ->
% perform the sort
Sorted = lists:sort(fun mySorter/2, Unsorted),
% throw out the values, leaving just the things
[X || {X,_} <- Sorted].
% sort function, which extracts the values of two items, and returns their comparison.
mySorter({_,A}, {_,B}) -> A =< B.
% return the angle between a satellite (given its ast) and our reference location (earth center = vertex)
angleBetween(SatAst) ->
% locate satellite in cartesian coordinates
XYZ = ast2xyz(SatAst),
% convert to latitude and longitude
{SatLat,SatLong} = xyz2latlong(XYZ),
% get ref loc from config params, and convert to radians
MobLat = deg2rad(getNum("GSM.RRLP.SEED.LATITUDE")),
MobLong = deg2rad(getNum("GSM.RRLP.SEED.LONGITUDE")),
% use spherical law of cosines to get the cosine of the angle between the satellite and ref loc
CosAngleBetween = math:sin(MobLat) * math:sin(SatLat) +
math:cos(MobLat) * math:cos(SatLat) * math:cos(MobLong - SatLong),
% convert to angle
AngleBetween = math:acos(CosAngleBetween),
% and return it
AngleBetween.
% convert between radians and degrees
deg2rad(Deg) -> Deg * math:pi() / 180.
% rad2deg(Rad) -> Rad * 180 / math:pi().
% replace all whitespace and invisible characters with a space
cleanLine(Line) ->
% this applies blank/1 to each character of the line
[blank(X) || X <- Line].
blank(Char) ->
case Char < $ of
% if value of char is less than that of blank, then return blank
true -> $ ;
% otherwise no change
false -> Char
end.
% parse the global part of the ephemeris
% return the rest of the lines of the ephemeris, and a list of {label,value} tuples
% [NextLine|RestOfLines] = remaining lines of ephemeris
% AdjustTable = adjustment table for ephemeris
% GlobalAst = list of {label,value} tuples so far
parseGlobalEphemeris([NextLine|RestOfLines], AdjustTable, GlobalAst) ->
% tokenize the line
Tokens = string:tokens(NextLine, " "),
% we can tell what kind of line it is from the last field in the line
case lists:last(Tokens) of
"ALPHA" ->
% the first four fields are alfa[0..3]
% globalStuff puts the fields into the global ast, then recurses