/
NTRIPService.java
1624 lines (1497 loc) · 53.9 KB
/
NTRIPService.java
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
package com.ntrip;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.util.Base64;
import android.widget.Toast;
//import android.util.Log;
public class NTRIPService extends Service {
//private static final String NTAG = "NTRIPThread";
//private static final String BTAG = "BTThread";
Thread nThread;
Socket nsocket; // Network Socket
InputStream nis = null; // Network Input Stream
OutputStream nos = null; // Network Output Stream
private BluetoothAdapter mBluetoothAdapter = null;
private BTConnectThread mBTConnectThread;
private BTConnectedThread mBTConnectedThread;
private int mBTState;
public static final int STATE_NONE = 0; // we're doing nothing
public static final int STATE_LISTEN = 1; // now listening for incoming connections
public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
public static final int STATE_CONNECTED = 3; // now connected to a remote device
private Boolean BTShouldAutoSwitch = false;
private Boolean BTwasDisabled = false;
private static boolean isRunning = false;
private Timer timer = new Timer();
private String logmsgs = "";
private String lognmea = "";
private int DisplayMsgType = 0;
ArrayList<Messenger> mClients = new ArrayList<Messenger>(); // Keeps track of all current registered clients.
int mValue = 0; // Holds last value set by a client.
static final int MSG_THREAD_SUICIDE = 0;
static final int MSG_REGISTER_CLIENT = 1;
static final int MSG_UNREGISTER_CLIENT = 2;
static final int MSG_UPDATE_STATUS = 3;
static final int MSG_UPDATE_BYTESIN = 4;
static final int MSG_SHOW_PROGRESSBAR = 5;
static final int MSG_UPDATE_LOG_APPEND = 6;
static final int MSG_UPDATE_LOG_FULL = 7;
static final int MSG_TOGGLE_LOG_TYPE = 8;
static final int MSG_ADD_NOTE_TO_NMEA = 9;
static final int MSG_RELOAD_PREFERENCES = 10;
static final int MSG_TIMER_TICK = 100;
static final int MSG_NETWORK_GOT_DATA = 101;
static final int MSG_NETWORK_TIMEOUT = 198;
static final int MSG_NETWORK_FINISHED = 199;
static final int MSG_BT_LOG_MESSAGE = 200;
static final int MSG_BT_GOT_DATA = 201;
static final int MSG_BT_FINISHED = 299;
static final int MSG_UPDATE_POSITION = 300;
final Messenger mMessenger = new Messenger(new IncomingHandler()); //Target we publish for clients to send messages to IncomingHandler.
//private Boolean NTRIPShouldBeConnected = false;
private String NetworkProtocol = "none";
private String SERVERIP = "";
private int SERVERPORT = 10000;
private String USERNAME = "";
private String PASSWORD = "";
private String MOUNTPOINT = "";
private Boolean NetworkTestingMode = false;
private Boolean NetworkIsConnected = false;
private int NetworkReceivedByteCount = 0;
private int NetworkReConnectInTicks = 2;
private int NetworkConnectionAttempts = 0;
private Boolean NTRIPStreamRequiresGGA = false;
private int NTRIPTicksSinceGGASent = 0;
private int NetworkDataMode = 0;
private String NTRIPResponse = "";
private String NMEA = "";
private String MACAddress = "00:00:00:00:00:00";
private Boolean UseHTCConnectionWorkaround = false;
private String AutoConfigReceiver = "none";
private int SaveDataStreamToFileType = 0;
private String NMEADataToSave = "";
private byte[] BinaryDataToSave = new byte[4096];
private int BinaryDataToSaveIndex = 0;
private Boolean UseManualLocation = false;
private Double ManualLat = 41.0;
private Double ManualLon = -91.0;
private boolean completeline;
private String MostRecentGGA = ""; //"$GPGGA,154223,4000,N,08312,W,4,10,1,200,M,1,M,8,0*7F"; // $GPGGA,213711.00,4158.8440010,N,09147.4414792,W,9,04,4.9,266.536,M,-32.00,M,03,0138*6C";
private int FixType = 10;
private int SatsTracked = 0;
private String HDOP = "";
private String CorrectionAge = "?";
private float Elevation = 0;
private float Speed = 0;
private float Heading = 0;
private int TicksSinceLastStatusSent = 0;
private int outInfo1 = 1;
private int outInfo2 = 4;
@Override
public IBinder onBind(Intent intent) {
return mMessenger.getBinder();
}
class IncomingHandler extends Handler { // Handler of incoming messages from clients.
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_REGISTER_CLIENT:
mClients.add(msg.replyTo);
break;
case MSG_UNREGISTER_CLIENT:
mClients.remove(msg.replyTo);
break;
case MSG_UPDATE_STATUS:
sendStatusMessageToUI(); // Client requested a status update
break;
case MSG_RELOAD_PREFERENCES:
LoadPreferences(true); // Client requested that the service reload the shared preferences
break;
case MSG_UPDATE_LOG_FULL:
sendAllLogMessagesToUI(); // Client requested all of the log messages.
if (!isRunning) {
InformActivityOfThreadSuicide();
}
if (NetworkReceivedByteCount > 0) {
SendByteCountProgressBarVisibility(1);
SendByteCountToActivity();
}
break;
case MSG_TOGGLE_LOG_TYPE:
if (DisplayMsgType == 0) {
SetDisplayMsgType(1);
} else {
SetDisplayMsgType(0);
}
break;
case MSG_ADD_NOTE_TO_NMEA:
Bundle b1 = msg.getData();
SaveNMEALineToFile("#" + b1.getString("note"));
break;
default:
super.handleMessage(msg);
}
}
}
private void InformActivityOfThreadSuicide() {
for (int i = mClients.size() - 1; i >= 0; i--) {
try {
mClients.get(i).send(Message.obtain(null, MSG_THREAD_SUICIDE, 0, 0));
//Log.i("MyService", "Service informed Activity of Suicide. +");
} catch (RemoteException e) {
// The client is dead. Remove it from the list; we are going
// through the list from back to front so this is safe to do
// inside the loop.
mClients.remove(i);
//Log.i("MyService", "Service informed Activity of Suicide. -");
}
}
//Log.i("MyService", "Service informed Activity of Suicide.");
}
private void LogMessage(String m) {
// Check if log is too long, shorten if necessary.
if (logmsgs.length() > 1000) {
int tempi = logmsgs.length();
tempi = logmsgs.indexOf("\n", tempi - 500);
logmsgs = logmsgs.substring(tempi + 1);
}
// Append new message to the log.
logmsgs += "\n" + TheTimeIs() + m;
if (DisplayMsgType == 0) {
// Build bundle
Bundle b = new Bundle();
b.putString("logappend", TheTimeIs() + m);
for (int i = mClients.size() - 1; i >= 0; i--) {
try {
Message msg = Message.obtain(null, MSG_UPDATE_LOG_APPEND);
msg.setData(b);
mClients.get(i).send(msg);
} catch (RemoteException e) {
// The client is dead. Remove it from the list; we are going
// through the list from back to front so this is safe to do
// inside the loop.
mClients.remove(i);
}
}
}
}
private void LogNMEA(String m) {
// Check if log is too long, shorten if necessary.
if (lognmea.length() > 1000) {
int tempi = lognmea.length();
tempi = lognmea.indexOf("\n", tempi - 500);
lognmea = lognmea.substring(tempi + 1);
}
// Append new message to the log.
lognmea += "\n" + m;
if (DisplayMsgType == 1) {
// Build bundle
Bundle b = new Bundle();
b.putString("logappend", m);
for (int i = mClients.size() - 1; i >= 0; i--) {
try {
Message msg = Message.obtain(null, MSG_UPDATE_LOG_APPEND);
msg.setData(b);
mClients.get(i).send(msg);
} catch (RemoteException e) {
// The client is dead. Remove it from the list; we are going
// through the list from back to front so this is safe to do
// inside the loop.
mClients.remove(i);
}
}
}
}
private void sendAllLogMessagesToUI() {
Bundle b = new Bundle();
if (DisplayMsgType == 1) {
b.putString("logfull", lognmea);
} else {
b.putString("logfull", logmsgs);
}
for (int i = mClients.size() - 1; i >= 0; i--) {
try {
Message msg = Message.obtain(null, MSG_UPDATE_LOG_FULL);
msg.setData(b);
mClients.get(i).send(msg);
} catch (RemoteException e) {
// The client is dead. Remove it from the list; we are going
// through the list from back to front so this is safe to do
// inside the loop.
mClients.remove(i);
}
}
}
private void SetDisplayMsgType(int MsgType) {
if (lognmea.length() == 0 && MsgType == 1) { //Can't change to NMEA, no data there
MsgType = 0;
}
if (DisplayMsgType != MsgType) { //Type changed. Need to re-send everything
DisplayMsgType = MsgType;
sendAllLogMessagesToUI();
}
}
private void sendStatusMessageToUI() {
// Build bundle
String textFix;
switch (FixType) {
case 0:
textFix = "Invalid";
break;
case 1:
textFix = "GPS";
break;
case 2:
textFix = "DGPS";
break;
case 3:
textFix = "PPS";
break;
case 4:
textFix = "RTK";
break;
case 5:
textFix = "FloatRTK";
break;
case 6:
textFix = "Estimated";
break;
case 7:
textFix = "Manual";
break;
case 8:
textFix = "Simulation";
break;
case 9:
textFix = "WAAS";
break;
case 10:
textFix = "No Data";
break;
default:
textFix = "Unknown";
}
if (FixType < 10) {
textFix += ":" + SatsTracked;
}
Bundle b = new Bundle();
b.putString("fixtype", textFix);
b.putString("info1", GetOutputInfo(outInfo1));
b.putString("info2", GetOutputInfo(outInfo2));
for (int i = mClients.size() - 1; i >= 0; i--) {
try {
Message msg = Message.obtain(null, MSG_UPDATE_STATUS);
msg.setData(b);
mClients.get(i).send(msg);
} catch (RemoteException e) {
// The client is dead. Remove it from the list; we are going
// through the list from back to front so this is safe to do
// inside the loop.
mClients.remove(i);
}
}
TicksSinceLastStatusSent = 0; // Reset to zero
}
private String GetOutputInfo(int infotype) {
switch (infotype) {
case 1: // Correction Age
return "Age: " + CorrectionAge + "s";
case 2: // Elevation Feet
return new DecimalFormat("0.0").format(Elevation * 3.2808399) + "'";
case 3: // Elevation Meters
return new DecimalFormat("0.000").format(Elevation) + "m";
case 4: // Speed MPH
return new DecimalFormat("0.0").format(Speed * 1.15077945) + " MPH";
case 5: // Speed Km/h
return new DecimalFormat("0.0").format(Speed * 1.852) + " km/h";
case 6: // Heading
return new DecimalFormat("0.0").format(Heading) + "°";
case 7: // H-DOP
return "HDOP:" + HDOP;
case 8: // V-DOP
return "VDOP";
case 9: // P-DOP
return "PDOP";
default: // Nothing
return "";
}
}
@Override
public void onCreate() {
super.onCreate();
//Log.i("MyService", "Service Started.");
logmsgs = TheTimeIs() + "Service Started";
isRunning = true;
LoadPreferences(false);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
timer.scheduleAtFixedRate(new TimerTask(){ public void run()
{onTimerTick_TimerThread();}}, 0, 1000L);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Log.i("MyService", "Received start id " + startId + ": " + intent);
return START_STICKY; // run until explicitly stopped.
}
private void LoadPreferences(Boolean NotifyOfChanges) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
Boolean NetworkSettingsChanged = false;
try {
outInfo1 = Integer.parseInt(preferences.getString("info1", "1"));
outInfo2 = Integer.parseInt(preferences.getString("info2", "4"));
AutoConfigReceiver = preferences.getString("receiverautoconfig", "none");
//android.util.Log.d("Debug",""+outInfo1);
//android.util.Log.d("Debug",""+outInfo2);
//android.util.Log.d("Debug",""+AutoConfigReceiver);
BTShouldAutoSwitch = preferences.getBoolean("autoswitchbluetooth", false);
UseHTCConnectionWorkaround = preferences.getBoolean("htcconnectworkaround", false);
Boolean tNetworkTestingMode = preferences.getBoolean("ntriptestmode", false);
if (tNetworkTestingMode) { //Now in testing mode, try to stop BT in case it is running.
BTstop();
LogMessage("Network Testing Mode. Will not connect to receiver.");
}
NetworkTestingMode = tNetworkTestingMode;
String newSaveDataType = preferences.getString("savedatatype", "none");
if (newSaveDataType.equals("allbinary")) {
SaveDataStreamToFileType = 1;
} else if (newSaveDataType.equals("nmeaggarmc")) {
SaveDataStreamToFileType = 2;
} else {
SaveDataStreamToFileType = 0;
}
String tNetworkProtocol = preferences.getString("networkprotocol", "none");
if (!tNetworkProtocol.equals(NetworkProtocol)) {
NetworkProtocol = tNetworkProtocol;
NetworkSettingsChanged = true;
}
//android.util.Log.d("Debug","NP "+NetworkProtocol);
//NTRIPShouldBeConnected = preferences.getBoolean("usentrip", false);
String newMACAddress = preferences.getString("bluetooth_mac", "00:00:00:00:00:00");
if (newMACAddress != MACAddress) {
if (!MACAddress.equals("00:00:00:00:00:00")) {
LogMessage("BT: Target Device Changed. You will need to Disconnet/Reconnect.");
}
MACAddress = newMACAddress;
BTstop();
}
String tSERVERIP = preferences.getString("ntripcasterip", "165.206.203.10");
if (tSERVERIP.length() > 2) {
if (!tSERVERIP.equals(SERVERIP)) {
SERVERIP = tSERVERIP;
NetworkSettingsChanged = true;
}
} else {
LogMessage("Error: Server IP is too short");
//NTRIPShouldBeConnected = false;
NetworkProtocol = "none";
}
//android.util.Log.d("Debug","SI "+SERVERIP);
String tSERVERPORT = preferences.getString("ntripcasterport", "10000");
if (isInteger(tSERVERPORT)) {
int iSERVERPORT = Integer.parseInt(tSERVERPORT);
if (iSERVERPORT > 0 && iSERVERPORT < 65536) {
if (SERVERPORT != iSERVERPORT) {
SERVERPORT = iSERVERPORT;
NetworkSettingsChanged = true;
}
} else {
LogMessage("Error: Port number is invalid");
//NTRIPShouldBeConnected = false;
NetworkProtocol = "none";
}
}
//android.util.Log.d("Debug","SP "+SERVERPORT);
String tUSERNAME = preferences.getString("ntripusername", "");
if (!tUSERNAME.equals(USERNAME)) {
USERNAME = tUSERNAME;
NetworkSettingsChanged = true;
}
//android.util.Log.d("Debug","UN "+USERNAME);
String tPASSWORD = preferences.getString("ntrippassword", "");
if (!tPASSWORD.equals(PASSWORD)) {
PASSWORD = tPASSWORD;
NetworkSettingsChanged = true;
}
String tMOUNTPOINT = preferences.getString("ntripstream", "");
if (!tMOUNTPOINT.equals(MOUNTPOINT)) {
MOUNTPOINT = tMOUNTPOINT;
NetworkSettingsChanged = true;
}
//android.util.Log.d("Debug","MP "+MOUNTPOINT);
String tUseManualLocation = preferences.getString("ntriplocation", "auto");
Boolean uUseManualLocation = false;
if (tUseManualLocation.equals("manual")) {uUseManualLocation = true;}
if (uUseManualLocation != UseManualLocation) {
UseManualLocation = uUseManualLocation;
NetworkSettingsChanged = true;
}
if (UseManualLocation) {
String tLat = preferences.getString("ntriplatitude", "");
String tLon = preferences.getString("ntriplongitude", "");
Double dLat = 1000.0;
Double dLon = 1000.0;
try {
dLat = Double.parseDouble(tLat);
} catch(NumberFormatException nfe) {}
try {
dLon = Double.parseDouble(tLon);
} catch(NumberFormatException nfe) {}
if (dLat != ManualLat) {
ManualLat = dLat;
NetworkSettingsChanged = true;
}
if (dLon != ManualLon) {
ManualLon = dLon;
NetworkSettingsChanged = true;
}
}
} catch (NumberFormatException nfe) {}
if (!NetworkProtocol.equals("none")) { //Should be connected
if (NetworkSettingsChanged) {
if (NetworkIsConnected) { // Need to disconnect and reconnect
TerminateNTRIPThread(true);
LogMessage("Network: Disconnected");
} else { // Just need to connect
NetworkReConnectInTicks = 2;
}
}
} else { //Should not be connected
if (NetworkIsConnected) {
TerminateNTRIPThread(false);
LogMessage("Network: Disconnected");
}
LogMessage("Network: Disabled");
}
/*String sourcetable = preferences.getString("ntripsourcetable", "");
// Log.i("sourcetable", sourcetable);
String[] lines = sourcetable.split("\\r?\\n");
for (int i = 0; i < lines.length; i++) {
String[] fields = lines[i].split(";");
if (fields.length > 4) {
if (fields[0].toLowerCase().equals("str")) {
if (fields[1].equals(MOUNTPOINT)) { // Found the right stream
if (fields[11].equals("1")) { // Stream requires GGA
NTRIPStreamRequiresGGA = true;
//Log.i("LoadPreferences", "This stream requires GGA data");
} else {
NTRIPStreamRequiresGGA = false;
//Log.i("LoadPreferences", "This stream does NOT require GGA data");
}
}
}
}
}*/
NTRIPStreamRequiresGGA = preferences.getBoolean("ntripsendggatocaster",NTRIPStreamRequiresGGA);
if (NotifyOfChanges) {
if (NetworkSettingsChanged) {
LogMessage("Network settings changed.");
}
}
}
public boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (Exception e) {
return false;
}
}
public static boolean isRunning() {
return isRunning;
}
private String TheTimeIs() {
Calendar calendar = Calendar.getInstance();
int hours = calendar.get(Calendar.HOUR);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);
return Make2Digits(hours) + ":" + Make2Digits(minutes) + ":"
+ Make2Digits(seconds) + " ";
}
private String Make2Digits(int i) {
if (i < 10) {
return "0" + i;
} else {
return Integer.toString(i);
}
}
private void onTimerTick_TimerThread() {
// This is running on a separate thread. Cannot do UI stuff from here.
// Send a message to the handler to do that stuff on the main thread.
handler.sendMessage(handler.obtainMessage(MSG_TIMER_TICK));
}
private void onTimerTick() { // Back on the main thread.
TicksSinceLastStatusSent++;
if (TicksSinceLastStatusSent > 4) {
if (FixType != 10) { // Only log this once
LogMessage("Fix type is now Unknown");
FixType = 10;// No data coming in for 5 seconds
}
SatsTracked = 0;
HDOP = "?";
CorrectionAge = "?";
Elevation = 0;
sendStatusMessageToUI();
}
if (getBTState() == STATE_NONE && !NetworkTestingMode) { //We're not connected, and not in testing mode, try to start.
if (mBluetoothAdapter == null) { //No adapter. Fail
//Log.e("Bluetooth", "getDefaultAdapter returned null");
Toast.makeText(this, "This device does not support Bluetooth.", Toast.LENGTH_SHORT).show();
LogMessage("Bluetooth is NOT supported.");
isRunning = false;
InformActivityOfThreadSuicide();
if (timer != null) {timer.cancel();}
this.stopSelf();
} else {
if (!mBluetoothAdapter.isEnabled()) { //Bluetooth disabled
if (BTShouldAutoSwitch) { //At least auto-switch is enabled
if (!BTwasDisabled) { //We need to turn on Bluetooth
//Log.i("Bluetooth", "Turning on");
mBluetoothAdapter.enable();
BTwasDisabled = true;
LogMessage("Waiting for Bluetooth...");
} else { //We need to wait until bluetooth comes online
//Log.i("Bluetooth", "Waiting for for Bluetooth to turn on");
}
} else { //and auto-switch is disabled. Fail
//Log.e("Bluetooth", "Bluetooth is Disabled and we can't autoswitch it on");
Toast.makeText(this, "Bluetooth is Disabled", Toast.LENGTH_SHORT).show();
LogMessage("Bluetooth is Disabled");
isRunning = false;
InformActivityOfThreadSuicide();
if (timer != null) {timer.cancel();}
this.stopSelf();
}
} else {
BTstart();
}
}
}
// Log.i("handleMessage", "NTRIPIsConnected: " + NTRIPIsConnected);
if (!NetworkProtocol.equals("none") && !NetworkIsConnected && (getBTState() == STATE_CONNECTED || NetworkTestingMode)) { // Network Thread is currently not running
if (NetworkReConnectInTicks > 0) { // We are counting down to time to start the Network thread
// Do we need to wait for a GGA sentences?
if (NTRIPStreamRequiresGGA) {
if (UseManualLocation) { //We don't need to wait for a GGA, but should check the lat/lon
if (NetworkReConnectInTicks == 1) { //This is where we check the lat/lon
boolean BadLatLon = false;
//Log.i("BadLatLon", "Lat='" + ManualLat + "', Lon='" + ManualLon + "'");
if (ManualLat >= 90) {BadLatLon = true;}
if (ManualLat <= -90) {BadLatLon = true;}
if (ManualLon > 180) {BadLatLon = true;}
if (ManualLon <= -180) {BadLatLon = true;}
if (BadLatLon) {
LogMessage("NTRIP: Manual Location Latitude or Longitude is out of range.");
//NTRIPShouldBeConnected = false;
NetworkProtocol = "none";
NetworkReConnectInTicks++; // To counter the -- below, hold here
}
}
} else {
if (MostRecentGGA.length() < 5) { //We don't have a GGA yet.
if (NetworkReConnectInTicks == 2) {
if (NetworkTestingMode) { //Testing mode means no receiver, but stream requires a GGA, and we're set on automatic.
LogMessage("Error: This stream requires a GGA sentence. Please enter a manual Lat/Lon for network testing mode.");
} else {
LogMessage("NTRIP: Waiting for GGA from Receiver");
}
}
if (NetworkReConnectInTicks == 1) {
NetworkReConnectInTicks++; // To counter the -- below, hold here
}
}
}
}
NetworkReConnectInTicks--;
if (NetworkReConnectInTicks == 0) { // It is time to start the NTRIP thread
NetworkConnectionAttempts++;
if (NetworkConnectionAttempts == 1) {
LogMessage("Network: Connecting...");
} else {
LogMessage("Network: Connecting... Attempt " + NetworkConnectionAttempts);
}
NTRIPResponse = "";
NetworkReceivedByteCount = 0;
NetworkDataMode = 0;
if (NetworkProtocol.equals("rawtcpip")) {
NetworkDataMode = 99;
}
nThread = new Thread(new NetworkClient(NetworkProtocol, SERVERIP, SERVERPORT, MOUNTPOINT, USERNAME, PASSWORD));
nThread.start();
NetworkIsConnected = true;
}
}
}
if (NetworkIsConnected && NTRIPStreamRequiresGGA && !UseManualLocation) {
NTRIPTicksSinceGGASent++;
if (NTRIPTicksSinceGGASent > 29) {
SendGGAToCaster();
} // 30 seconds have passed, time for a re-send
}
}
// Network Data Stuff
public class NetworkClient implements Runnable {
String nProtocol = "";
String nServer = "";
int nPort = 2101;
String nMountpoint = "";
String nUsername = "";
String nPassword = "";
public NetworkClient(String pProtocol, String pServer, int pPort, String pMountpoint, String pUsername, String pPassword) {
nProtocol = pProtocol;
nServer = pServer;
nPort = pPort;
nMountpoint = pMountpoint;
nUsername = pUsername;
nPassword = pPassword;
}
public void run() {
try {
//Log.i(NTAG, "Creating socket");
SocketAddress sockaddr = new InetSocketAddress(nServer, nPort);
nsocket = new Socket();
nsocket.connect(sockaddr, 10 * 1000); // 10 second connection timeout
if (nsocket.isConnected()) {
nsocket.setSoTimeout(20 * 1000); // 20 second timeout once data is flowing
nis = nsocket.getInputStream();
nos = nsocket.getOutputStream();
//Log.i(NTAG, "Socket created, streams assigned");
if (nProtocol.equals("ntripv1")) {
// Build request message
//Log.i(NTAG, "This is a NTRIP connection");
String requestmsg = "GET /" + nMountpoint + " HTTP/1.0\r\n";
requestmsg += "User-Agent: NTRIP LefebureAndroidNTRIPClient/20120614\r\n";
requestmsg += "Accept: */*\r\n";
requestmsg += "Connection: close\r\n";
if (nUsername.length() > 0) {
requestmsg += "Authorization: Basic " + ToBase64(nUsername + ":" + nPassword);
}
requestmsg += "\r\n";
nos.write(requestmsg.getBytes());
//Log.i("Request", requestmsg);
} else {
//Log.i(NTAG, "This is a raw TCP/IP connection");
}
//Log.i(NTAG, "Waiting for inital data...");
byte[] buffer = new byte[4096];
int read = nis.read(buffer, 0, 4096); // This is blocking
while (read != -1) {
byte[] tempdata = new byte[read];
System.arraycopy(buffer, 0, tempdata, 0, read);
// Log.i(NTAG, "Got data: " + new String(tempdata));
handler.sendMessage(handler.obtainMessage(MSG_NETWORK_GOT_DATA, tempdata));
read = nis.read(buffer, 0, 4096); // This is blocking
}
}
} catch (SocketTimeoutException ex) {
handler.sendMessage(handler.obtainMessage(MSG_NETWORK_TIMEOUT));
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
nis.close();
nos.close();
nsocket.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
//Log.i(NTAG, "Finished");
handler.sendMessage(handler.obtainMessage(MSG_NETWORK_FINISHED));
}
}
private String ToBase64(String in) {
return Base64.encodeToString(in.getBytes(), 4);
}
}
public void SendDataToNetwork(String cmd) { // You run this from the main thread.
try {
if (nsocket != null) {
if (nsocket.isConnected()) {
if (!nsocket.isClosed()) {
//Log.i("SendDataToNetwork", "SendDataToNetwork: Writing message to socket");
nos.write(cmd.getBytes());
} else {
//Log.i("SendDataToNetwork", "SendDataToNetwork: Cannot send message. Socket is closed");
}
} else {
//Log.i("SendDataToNetwork", "SendDataToNetwork: Cannot send message. Socket is not connected");
}
}
} catch (Exception e) {
//Log.i("SendDataToNetwork", "SendDataToNetwork: Message send failed. Caught an exception");
}
}
private void ParseNetworkDataStream(byte[] buffer) {
// Log.i("handleMessage", "bytes from network:" + buffer.length + ", " + new String(buffer));
if (NetworkDataMode == 0) { // We're just starting up.
NTRIPResponse += new String(buffer); // Add what we got to the string, in case the response spans more than one packet.
if (NTRIPResponse.startsWith("ICY 200 OK")) {// Data stream confirmed.
if (NTRIPStreamRequiresGGA) {
SendGGAToCaster();
}
NetworkDataMode = 99; // Put in to data mode
LogMessage("NTRIP: Connected to caster");
} else if (NTRIPResponse.indexOf("401 Unauthorized") > 1) {
//Log.i("handleMessage", "Invalid Username or Password.");
LogMessage("NTRIP: Bad username or password.");
TerminateNTRIPThread(false);
} else if (NTRIPResponse.startsWith("SOURCETABLE 200 OK")) {
LogMessage("NTRIP: Downloading stream list");
//NTRIPShouldBeConnected = false; // So it doesn't reconnect over and over
NetworkProtocol = "none"; // So it doesn't reconnect over and over
NetworkDataMode = 1; // Put into source table mode
NTRIPResponse = NTRIPResponse.substring(20); // Drop the beginning of the data
CheckIfDownloadedSourceTableIsComplete();
} else if (NTRIPResponse.length() > 1024) { // We've received 1KB of data but no start command. WTF?
LogMessage("NTRIP: Unrecognized server response:");
LogMessage(NTRIPResponse);
TerminateNTRIPThread(true);
}
} else if (NetworkDataMode == 1) { // Save SourceTable
NTRIPResponse += new String(buffer); // Add what we got to the string, in case the response spans more than one packet.
CheckIfDownloadedSourceTableIsComplete();
} else { // Data streaming mode. Forward data to bluetooth socket
if (NetworkReceivedByteCount == 0) {
if (NetworkProtocol.equals("rawtcpip")) {
LogMessage("Network: Connected to server " + SERVERIP + ":" + SERVERPORT);
}
SendByteCountProgressBarVisibility(1);
}
NetworkReceivedByteCount += buffer.length;
SendByteCountToActivity();
SendDataToBluetooth(buffer);
}
}
private void SendByteCountToActivity() {
for (int i = mClients.size() - 1; i >= 0; i--) {
try {
mClients.get(i).send(Message.obtain(null, MSG_UPDATE_BYTESIN, NetworkReceivedByteCount, 0));
} catch (RemoteException e) {
// The client is dead. Remove it from the list; we are going
// through the list from back to front so this is safe to do
// inside the loop.
mClients.remove(i);
}
}
}
private void SendByteCountProgressBarVisibility(int val) {
for (int i = mClients.size() - 1; i >= 0; i--) {
try {
mClients.get(i).send(Message.obtain(null, MSG_SHOW_PROGRESSBAR, val, 0));
} catch (RemoteException e) {
// The client is dead. Remove it from the list; we are going
// through the list from back to front so this is safe to do
// inside the loop.
mClients.remove(i);
}
}
}
private void CheckIfDownloadedSourceTableIsComplete() {
if (NTRIPResponse.indexOf("\r\nENDSOURCETABLE") > 0) {
//Log.i("Sourcetable", "Found the end");
LogMessage("NTRIP: Downloaded stream list");
LogMessage("Please select a stream");
LogMessage("Network: Disabled");
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("ntripsourcetable", NTRIPResponse);
editor.commit();
}
}
private void SendGGAToCaster() {
if (UseManualLocation) {
SendDataToNetwork(GenerateGGAFromLatLon() + "\r\n");
} else {
SendDataToNetwork(MostRecentGGA + "\r\n");
}
NTRIPTicksSinceGGASent = 0;
}
private String GenerateGGAFromLatLon() {
String gga = "GPGGA,000001,";
double posnum = Math.abs(ManualLat);
double latmins = posnum % 1;
int ggahours = (int)(posnum - latmins);
latmins = latmins * 60;
double latfracmins = latmins % 1;
int ggamins = (int)(latmins - latfracmins);
int ggafracmins = (int)(latfracmins * 10000);
ggahours = ggahours * 100 + ggamins;
if (ggahours < 1000) {
gga += "0";
if (ggahours < 100) {
gga += "0";
}
}
gga += ggahours + ".";
if (ggafracmins < 1000) {
gga += "0";
if (ggafracmins < 100) {
gga += "0";
if (ggafracmins < 10) {
gga += "0";
}
}
}
gga += ggafracmins;
if (ManualLat > 0) {
gga += ",N,";
} else {
gga += ",S,";
}
posnum = Math.abs(ManualLon);
latmins = posnum % 1;
ggahours = (int)(posnum - latmins);
latmins = latmins * 60;
latfracmins = latmins % 1;
ggamins = (int)(latmins - latfracmins);
ggafracmins = (int)(latfracmins * 10000);
ggahours = ggahours * 100 + ggamins;
if (ggahours < 10000) {
gga += "0";
if (ggahours < 1000) {
gga += "0";
if (ggahours < 100) {
gga += "0";
}
}
}
gga += ggahours + ".";
if (ggafracmins < 1000) {
gga += "0";
if (ggafracmins < 100) {
gga += "0";
if (ggafracmins < 10) {
gga += "0";
}
}
}
gga += ggafracmins;
if (ManualLon > 0) {
gga += ",E,";
} else {
gga += ",W,";
}
gga += "1,8,1,0,M,-32,M,3,0";
String checksum = CalculateChecksum(gga);
//Log.i("Manual GGA", "$" + gga + "*" + checksum);
return "$" + gga + "*" + checksum;
}
// Bluetooth Data Stuff
private synchronized void setBTState(int state) {
//Log.i(BTAG, "setBTState() " + mBTState + " -> " + state);
mBTState = state;
}
public synchronized int getBTState() {
return mBTState;
}
public synchronized void BTstart() {
SetDisplayMsgType(0);
//Log.i(BTAG, "BTstart");
// Cancel any thread attempting to make a connection
if (mBTConnectThread != null) {mBTConnectThread.cancel(); mBTConnectThread = null;}
// Cancel any thread currently running a connection
if (mBTConnectedThread != null) {mBTConnectedThread.cancel(); mBTConnectedThread = null;}
if (!BluetoothAdapter.checkBluetoothAddress(MACAddress)) {
LogMessage("Invalid Bluetooth MAC Address: \"" + MACAddress + "\"");
InformActivityOfThreadSuicide();
} else if (MACAddress.equals("00:00:00:00:00:00")) {
LogMessage("Error: No Bluetooth device has been selected.");
isRunning = false;
InformActivityOfThreadSuicide();
if (timer != null) {timer.cancel();}
this.stopSelf();
} else {