881682892c39132e89fbd3fb1f729a46bc03a6ec
[fw/altos] / altosdroid / app / src / main / java / org / altusmetrum / AltosDroid / AltosDroid.java
1 /*
2  * Copyright © 2012-2013 Mike Beattie <mike@ethernal.org>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
17  */
18
19 package org.altusmetrum.AltosDroid;
20
21 import java.lang.ref.WeakReference;
22 import java.util.*;
23
24 import android.Manifest;
25 import android.app.Activity;
26 import android.app.PendingIntent;
27 import android.bluetooth.BluetoothAdapter;
28 import android.content.Intent;
29 import android.content.Context;
30 import android.content.ComponentName;
31 import android.content.ServiceConnection;
32 import android.content.DialogInterface;
33 import android.os.IBinder;
34 import android.os.Bundle;
35 import android.os.Handler;
36 import android.os.Message;
37 import android.os.Messenger;
38 import android.os.RemoteException;
39 import androidx.fragment.app.FragmentActivity;
40 import androidx.fragment.app.FragmentManager;
41 import android.view.*;
42 import android.widget.*;
43 import android.app.AlertDialog;
44 import android.location.Location;
45 import android.location.LocationManager;
46 import android.location.LocationListener;
47 import android.hardware.usb.*;
48 import android.content.pm.PackageManager;
49 import androidx.core.app.ActivityCompat;
50 import org.altusmetrum.altoslib_13.*;
51
52 class SavedState {
53         long    received_time;
54         int     state;
55         boolean locked;
56         String  callsign;
57         int     serial;
58         int     flight;
59         int     rssi;
60
61         SavedState(AltosState state) {
62                 received_time = state.received_time;
63                 this.state = state.state();
64                 if (state.gps != null)
65                         locked = state.gps.locked;
66                 else
67                         locked = false;
68                 callsign = state.cal_data().callsign;
69                 serial = state.cal_data().serial;
70                 flight = state.cal_data().flight;
71                 rssi = state.rssi;
72         }
73 }
74
75 class Tracker implements CharSequence, Comparable {
76         int     serial;
77         String  call;
78         double  frequency;
79
80         String  display;
81
82         public Tracker(int serial, String call, double frequency) {
83                 if (call == null)
84                         call = "none";
85
86                 this.serial = serial;
87                 this.call = call;
88                 this.frequency = frequency;
89                 if (frequency == 0.0)
90                         display = "Auto";
91                 else if (frequency == AltosLib.MISSING) {
92                         display = String.format("%-8.8s  %6d", call, serial);
93                 } else {
94                         display = String.format("%-8.8s %7.3f %6d", call, frequency, serial);
95                 }
96         }
97
98         public Tracker(AltosState s) {
99                 this(s == null ? 0 : s.cal_data().serial,
100                      s == null ? null : s.cal_data().callsign,
101                      s == null ? 0.0 : s.frequency);
102         }
103
104         /* CharSequence */
105         public char charAt(int index) {
106                 return display.charAt(index);
107         }
108
109         public int length() {
110                 return display.length();
111         }
112
113         public CharSequence subSequence(int start, int end) throws IndexOutOfBoundsException {
114                 return display.subSequence(start, end);
115         }
116
117         public String toString() {
118                 return display.toString();
119         }
120
121         /* Comparable */
122         public int compareTo (Object other) {
123                 Tracker o = (Tracker) other;
124                 if (frequency == 0.0) {
125                         if (o.frequency == 0.0)
126                                 return 0;
127                         return -1;
128                 }
129                 if (o.frequency == 0.0)
130                         return 1;
131
132                 int     a = serial - o.serial;
133                 int     b = call.compareTo(o.call);
134                 int     c = (int) Math.signum(frequency - o.frequency);
135
136                 if (b != 0)
137                         return b;
138                 if (c != 0)
139                         return c;
140                 return a;
141         }
142 }
143
144 public class AltosDroid extends FragmentActivity implements AltosUnitsListener, LocationListener, ActivityCompat.OnRequestPermissionsResultCallback {
145
146         // Actions sent to the telemetry server at startup time
147
148         public static final String ACTION_BLUETOOTH = "org.altusmetrum.AltosDroid.BLUETOOTH";
149         public static final String ACTION_USB = "org.altusmetrum.AltosDroid.USB";
150
151         // Message types received by our Handler
152
153         public static final int MSG_STATE           = 1;
154         public static final int MSG_UPDATE_AGE      = 2;
155         public static final int MSG_IDLE_MODE       = 3;
156         public static final int MSG_IGNITER_STATUS  = 4;
157
158         // Intent request codes
159         public static final int REQUEST_CONNECT_DEVICE = 1;
160         public static final int REQUEST_ENABLE_BT      = 2;
161         public static final int REQUEST_PRELOAD_MAPS   = 3;
162         public static final int REQUEST_IDLE_MODE      = 5;
163         public static final int REQUEST_IGNITERS       = 6;
164         public static final int REQUEST_SETUP          = 7;
165
166         public static final String EXTRA_IDLE_MODE = "idle_mode";
167         public static final String EXTRA_IDLE_RESULT = "idle_result";
168         public static final String EXTRA_TELEMETRY_SERVICE = "telemetry_service";
169
170         // Setup result bits
171         public static final int SETUP_BAUD = 1;
172         public static final int SETUP_UNITS = 2;
173         public static final int SETUP_MAP_SOURCE = 4;
174         public static final int SETUP_MAP_TYPE = 8;
175
176         public static FragmentManager   fm;
177
178         private BluetoothAdapter mBluetoothAdapter = null;
179
180         // Flight state values
181         private TextView mCallsignView;
182         private TextView mRSSIView;
183         private TextView mSerialView;
184         private TextView mFlightView;
185         private RelativeLayout mStateLayout;
186         private TextView mStateView;
187         private TextView mAgeView;
188         private boolean  mAgeViewOld;
189         private int mAgeNewColor;
190         private int mAgeOldColor;
191
192         public static final String      tab_pad_name = "pad";
193         public static final String      tab_flight_name = "flight";
194         public static final String      tab_recover_name = "recover";
195         public static final String      tab_map_name = "map";
196
197         // field to display the version at the bottom of the screen
198         private TextView mVersion;
199
200         private boolean idle_mode = false;
201
202         public Location location = null;
203
204         private AltosState      state;
205         private SavedState      saved_state;
206
207         // Tabs
208         TabHost         mTabHost;
209         AltosViewPager  mViewPager;
210         TabsAdapter     mTabsAdapter;
211         ArrayList<AltosDroidTab> mTabs = new ArrayList<AltosDroidTab>();
212         int             tabHeight;
213
214         // Timer and Saved flight state for Age calculation
215         private Timer timer;
216
217         TelemetryState  telemetry_state;
218         Tracker[]       trackers;
219
220
221         UsbDevice       pending_usb_device;
222         boolean         start_with_usb;
223
224         // Service
225         private boolean mIsBound   = false;
226         private Messenger mService = null;
227         final Messenger mMessenger = new Messenger(new IncomingHandler(this));
228
229         // Text to Speech
230         private AltosVoice mAltosVoice = null;
231
232         // The Handler that gets information back from the Telemetry Service
233         static class IncomingHandler extends Handler {
234                 private final WeakReference<AltosDroid> mAltosDroid;
235                 IncomingHandler(AltosDroid ad) { mAltosDroid = new WeakReference<AltosDroid>(ad); }
236
237                 @Override
238                 public void handleMessage(Message msg) {
239                         AltosDroid ad = mAltosDroid.get();
240
241                         switch (msg.what) {
242                         case MSG_STATE:
243                                 if (msg.obj == null) {
244                                         AltosDebug.debug("telemetry_state null!");
245                                         return;
246                                 }
247                                 ad.update_state((TelemetryState) msg.obj);
248                                 break;
249                         case MSG_UPDATE_AGE:
250                                 ad.update_age();
251                                 break;
252                         case MSG_IDLE_MODE:
253                                 ad.idle_mode = (Boolean) msg.obj;
254                                 ad.update_state(null);
255                                 break;
256                         }
257                 }
258         };
259
260
261         private ServiceConnection mConnection = new ServiceConnection() {
262                 public void onServiceConnected(ComponentName className, IBinder service) {
263                         mService = new Messenger(service);
264                         try {
265                                 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
266                                 msg.replyTo = mMessenger;
267                                 mService.send(msg);
268                         } catch (RemoteException e) {
269                                 // In this case the service has crashed before we could even do anything with it
270                         }
271                         if (pending_usb_device != null) {
272                                 try {
273                                         mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, pending_usb_device));
274                                         pending_usb_device = null;
275                                 } catch (RemoteException e) {
276                                 }
277                         }
278                 }
279
280                 public void onServiceDisconnected(ComponentName className) {
281                         // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
282                         mService = null;
283                 }
284         };
285
286         void doBindService() {
287                 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
288                 mIsBound = true;
289         }
290
291         void doUnbindService() {
292                 if (mIsBound) {
293                         // If we have received the service, and hence registered with it, then now is the time to unregister.
294                         if (mService != null) {
295                                 try {
296                                         Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
297                                         msg.replyTo = mMessenger;
298                                         mService.send(msg);
299                                 } catch (RemoteException e) {
300                                         // There is nothing special we need to do if the service has crashed.
301                                 }
302                         }
303                         // Detach our existing connection.
304                         unbindService(mConnection);
305                         mIsBound = false;
306                 }
307         }
308
309         public void registerTab(AltosDroidTab mTab) {
310                 mTabs.add(mTab);
311         }
312
313         public void unregisterTab(AltosDroidTab mTab) {
314                 mTabs.remove(mTab);
315         }
316
317         public void units_changed(boolean imperial_units) {
318                 for (AltosDroidTab mTab : mTabs)
319                         mTab.units_changed(imperial_units);
320         }
321
322         void update_title(TelemetryState telemetry_state) {
323                 switch (telemetry_state.connect) {
324                 case TelemetryState.CONNECT_CONNECTED:
325                         if (telemetry_state.config != null) {
326                                 String str = String.format("S/N %d %6.3f MHz%s", telemetry_state.config.serial,
327                                                            telemetry_state.frequency, idle_mode ? " (idle)" : "");
328                                 if (telemetry_state.telemetry_rate != AltosLib.ao_telemetry_rate_38400)
329                                         str = str.concat(String.format(" %d bps",
330                                                                        AltosLib.ao_telemetry_rate_values[telemetry_state.telemetry_rate]));
331                                 setTitle(str);
332                         } else {
333                                 setTitle(R.string.title_connected_to);
334                         }
335                         break;
336                 case TelemetryState.CONNECT_CONNECTING:
337                         if (telemetry_state.address != null)
338                                 setTitle(String.format("Connecting to %s...", telemetry_state.address.name));
339                         else
340                                 setTitle("Connecting to something...");
341                         break;
342                 case TelemetryState.CONNECT_DISCONNECTED:
343                 case TelemetryState.CONNECT_NONE:
344                         setTitle(R.string.title_not_connected);
345                         break;
346                 }
347         }
348
349         void start_timer() {
350                 if (timer == null) {
351                         timer = new Timer();
352                         timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 1000L, 1000L);
353                 }
354         }
355
356         void stop_timer() {
357                 if (timer != null) {
358                         timer.cancel();
359                         timer.purge();
360                         timer = null;
361                 }
362         }
363
364         int     selected_serial = 0;
365         int     current_serial;
366         long    switch_time;
367
368         void set_switch_time() {
369                 switch_time = System.currentTimeMillis();
370                 selected_serial = 0;
371         }
372
373         boolean registered_units_listener;
374
375         void update_state(TelemetryState new_telemetry_state) {
376
377                 if (new_telemetry_state != null)
378                         telemetry_state = new_telemetry_state;
379
380                 if (selected_serial != 0)
381                         current_serial = selected_serial;
382
383                 if (current_serial == 0)
384                         current_serial = telemetry_state.latest_serial;
385
386                 if (!registered_units_listener) {
387                         registered_units_listener = true;
388                         AltosPreferences.register_units_listener(this);
389                 }
390
391                 int     num_trackers = 0;
392                 for (AltosState s : telemetry_state.states.values()) {
393                         num_trackers++;
394                 }
395
396                 trackers = new Tracker[num_trackers + 1];
397
398                 int n = 0;
399                 trackers[n++] = new Tracker(0, "auto", 0.0);
400
401                 for (AltosState s : telemetry_state.states.values())
402                         trackers[n++] = new Tracker(s);
403
404                 Arrays.sort(trackers);
405
406                 update_title(telemetry_state);
407
408                 AltosState      state = null;
409                 boolean         aged = true;
410
411                 if (telemetry_state.states.containsKey(current_serial)) {
412                         state = telemetry_state.states.get(current_serial);
413                         int age = state_age(state.received_time);
414                         if (age < 20)
415                                 aged = false;
416                         if (current_serial == selected_serial)
417                                 aged = false;
418                         else if (switch_time != 0 && (switch_time - state.received_time) > 0)
419                                 aged = true;
420                 }
421
422                 if (aged) {
423                         AltosState      newest_state = null;
424                         int             newest_age = 0;
425
426                         for (int serial : telemetry_state.states.keySet()) {
427                                 AltosState      existing = telemetry_state.states.get(serial);
428                                 int             existing_age = state_age(existing.received_time);
429
430                                 if (newest_state == null || existing_age < newest_age) {
431                                         newest_state = existing;
432                                         newest_age = existing_age;
433                                 }
434                         }
435
436                         if (newest_state != null)
437                                 state = newest_state;
438                 }
439
440                 update_ui(telemetry_state, state, telemetry_state.quiet);
441
442                 start_timer();
443         }
444
445         boolean same_string(String a, String b) {
446                 if (a == null) {
447                         if (b == null)
448                                 return true;
449                         return false;
450                 } else {
451                         if (b == null)
452                                 return false;
453                         return a.equals(b);
454                 }
455         }
456
457
458         private int blend_component(int a, int b, double r, int shift, int mask) {
459                 return ((int) (((a >> shift) & mask) * r + ((b >> shift) & mask) * (1 - r)) & mask) << shift;
460         }
461         private int blend_color(int a, int b, double r) {
462                 return (blend_component(a, b, r, 0, 0xff) |
463                         blend_component(a, b, r, 8, 0xff) |
464                         blend_component(a, b, r, 16, 0xff) |
465                         blend_component(a, b, r, 24, 0xff));
466         }
467
468         int state_age(long received_time) {
469                 return (int) ((System.currentTimeMillis() - received_time + 500) / 1000);
470         }
471
472         void set_screen_on(int age) {
473                 if (age < 60)
474                         getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
475                 else
476                         getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
477         }
478
479         void update_age() {
480                 if (saved_state != null) {
481                         int age = state_age(saved_state.received_time);
482
483                         double age_scale = age / 100.0;
484
485                         if (age_scale > 1.0)
486                                 age_scale = 1.0;
487
488                         mAgeView.setTextColor(blend_color(mAgeOldColor, mAgeNewColor, age_scale));
489
490                         set_screen_on(age);
491
492                         String  text;
493                         if (age < 60)
494                                 text = String.format("%ds", age);
495                         else if (age < 60 * 60)
496                                 text = String.format("%dm", age / 60);
497                         else if (age < 60 * 60 * 24)
498                                 text = String.format("%dh", age / (60 * 60));
499                         else
500                                 text = String.format("%dd", age / (24 * 60 * 60));
501                         mAgeView.setText(text);
502                 }
503         }
504
505         void update_ui(TelemetryState telem_state, AltosState state, boolean quiet) {
506
507                 this.state = state;
508
509                 int prev_state = AltosLib.ao_flight_invalid;
510
511                 AltosGreatCircle from_receiver = null;
512
513                 if (saved_state != null)
514                         prev_state = saved_state.state;
515
516                 if (state != null) {
517                         set_screen_on(state_age(state.received_time));
518
519                         if (state.state() == AltosLib.ao_flight_stateless) {
520                                 boolean prev_locked = false;
521                                 boolean locked = false;
522
523                                 if(state.gps != null)
524                                         locked = state.gps.locked;
525                                 if (saved_state != null)
526                                         prev_locked = saved_state.locked;
527                                 if (prev_locked != locked) {
528                                         String currentTab = mTabHost.getCurrentTabTag();
529                                         if (locked) {
530                                                 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
531                                         } else {
532                                                 if (currentTab.equals(tab_flight_name)) mTabHost.setCurrentTabByTag(tab_pad_name);
533                                         }
534                                 }
535                         } else {
536                                 if (prev_state != state.state()) {
537                                         String currentTab = mTabHost.getCurrentTabTag();
538                                         switch (state.state()) {
539                                         case AltosLib.ao_flight_boost:
540                                                 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
541                                                 break;
542                                         case AltosLib.ao_flight_landed:
543                                                 if (currentTab.equals(tab_flight_name)) mTabHost.setCurrentTabByTag(tab_recover_name);
544                                                 break;
545                                         case AltosLib.ao_flight_stateless:
546                                                 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
547                                                 break;
548                                         }
549                                 }
550                         }
551
552                         if (location != null && state.gps != null && state.gps.locked) {
553                                 double altitude = 0;
554                                 if (location.hasAltitude())
555                                         altitude = location.getAltitude();
556                                 from_receiver = new AltosGreatCircle(location.getLatitude(),
557                                                                      location.getLongitude(),
558                                                                      altitude,
559                                                                      state.gps.lat,
560                                                                      state.gps.lon,
561                                                                      state.gps.alt);
562                         }
563
564                         if (saved_state == null || !same_string(saved_state.callsign, state.cal_data().callsign)) {
565                                 mCallsignView.setText(state.cal_data().callsign);
566                         }
567                         if (saved_state == null || state.cal_data().serial != saved_state.serial) {
568                                 if (state.cal_data().serial == AltosLib.MISSING)
569                                         mSerialView.setText("");
570                                 else
571                                         mSerialView.setText(String.format("%d", state.cal_data().serial));
572                         }
573                         if (saved_state == null || state.cal_data().flight != saved_state.flight) {
574                                 if (state.cal_data().flight == AltosLib.MISSING)
575                                         mFlightView.setText("");
576                                 else
577                                         mFlightView.setText(String.format("%d", state.cal_data().flight));
578                         }
579                         if (saved_state == null || state.state() != saved_state.state) {
580                                 if (state.state() == AltosLib.ao_flight_stateless) {
581                                         mStateLayout.setVisibility(View.GONE);
582                                 } else {
583                                         mStateView.setText(state.state_name());
584                                         mStateLayout.setVisibility(View.VISIBLE);
585                                 }
586                         }
587                         if (saved_state == null || state.rssi != saved_state.rssi) {
588                                 if (state.rssi == AltosLib.MISSING)
589                                         mRSSIView.setText("");
590                                 else
591                                         mRSSIView.setText(String.format("%d", state.rssi));
592                         }
593                         saved_state = new SavedState(state);
594                 }
595
596                 for (AltosDroidTab mTab : mTabs)
597                         mTab.update_ui(telem_state, state, from_receiver, location, mTab == mTabsAdapter.currentItem());
598
599                 AltosDebug.debug("quiet %b\n", quiet);
600                 if (mAltosVoice != null && mTabsAdapter.currentItem() != null)
601                         mAltosVoice.tell(telem_state, state, from_receiver, location, (AltosDroidTab) mTabsAdapter.currentItem(), quiet);
602
603         }
604
605         private void onTimerTick() {
606                 try {
607                         mMessenger.send(Message.obtain(null, MSG_UPDATE_AGE));
608                 } catch (RemoteException e) {
609                 }
610         }
611
612         static String pos(double p, String pos, String neg) {
613                 String  h = pos;
614                 if (p == AltosLib.MISSING)
615                         return "";
616                 if (p < 0) {
617                         h = neg;
618                         p = -p;
619                 }
620                 int deg = (int) Math.floor(p);
621                 double min = (p - Math.floor(p)) * 60.0;
622                 return String.format("%d°%9.4f\" %s", deg, min, h);
623         }
624
625         static String number(String format, double value) {
626                 if (value == AltosLib.MISSING)
627                         return "";
628                 return String.format(format, value);
629         }
630
631         static String integer(String format, int value) {
632                 if (value == AltosLib.MISSING)
633                         return "";
634                 return String.format(format, value);
635         }
636
637         private View create_tab_view(String label) {
638                 LayoutInflater inflater = (LayoutInflater) this.getLayoutInflater();
639                 View tab_view = inflater.inflate(R.layout.tab_layout, null);
640                 TextView text_view = (TextView) tab_view.findViewById (R.id.tabLabel);
641                 text_view.setText(label);
642                 return tab_view;
643         }
644
645         @Override
646         public void onCreate(Bundle savedInstanceState) {
647                 super.onCreate(savedInstanceState);
648                 AltosDebug.init(this);
649                 AltosDebug.debug("+++ ON CREATE +++");
650
651                 // Initialise preferences
652                 AltosDroidPreferences.init(this);
653
654                 fm = getSupportFragmentManager();
655
656                 // Set up the window layout
657                 setContentView(R.layout.altosdroid);
658
659                 // Create the Tabs and ViewPager
660                 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
661                 mTabHost.setup();
662
663                 mViewPager = (AltosViewPager)findViewById(R.id.pager);
664                 mViewPager.setOffscreenPageLimit(4);
665
666                 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
667
668                 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_pad_name).setIndicator(create_tab_view("Pad")), TabPad.class, null);
669                 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_flight_name).setIndicator(create_tab_view("Flight")), TabFlight.class, null);
670                 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_recover_name).setIndicator(create_tab_view("Recover")), TabRecover.class, null);
671                 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_map_name).setIndicator(create_tab_view("Map")), TabMap.class, null);
672
673                 // Display the Version
674                 mVersion = (TextView) findViewById(R.id.version);
675                 mVersion.setText("Version: " + BuildInfo.version +
676                                  " Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
677                                  " (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
678
679                 mCallsignView  = (TextView) findViewById(R.id.callsign_value);
680                 mRSSIView      = (TextView) findViewById(R.id.rssi_value);
681                 mSerialView    = (TextView) findViewById(R.id.serial_value);
682                 mFlightView    = (TextView) findViewById(R.id.flight_value);
683                 mStateLayout   = (RelativeLayout) findViewById(R.id.state_container);
684                 mStateView     = (TextView) findViewById(R.id.state_value);
685                 mAgeView       = (TextView) findViewById(R.id.age_value);
686                 mAgeNewColor   = mAgeView.getTextColors().getDefaultColor();
687                 mAgeOldColor   = getResources().getColor(R.color.old_color);
688         }
689
690         private void ensureBluetooth() {
691                 // Get local Bluetooth adapter
692                 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
693
694                 /* if there is a BT adapter and it isn't turned on, then turn it on */
695                 if (mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) {
696                         Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
697                         startActivityForResult(enableIntent, AltosDroid.REQUEST_ENABLE_BT);
698                 }
699         }
700
701         private boolean check_usb() {
702                 UsbDevice       device = AltosUsb.find_device(this, AltosLib.product_basestation);
703
704                 if (device != null) {
705                         Intent          i = new Intent(this, AltosDroid.class);
706                         PendingIntent   pi = PendingIntent.getActivity(this, 0, new Intent("hello world", null, this, AltosDroid.class), 0);
707
708                         if (AltosUsb.request_permission(this, device, pi)) {
709                                 connectUsb(device);
710                         }
711                         start_with_usb = true;
712                         return true;
713                 }
714
715                 start_with_usb = false;
716
717                 return false;
718         }
719
720         private void noticeIntent(Intent intent) {
721
722                 /* Ok, this is pretty convenient.
723                  *
724                  * When a USB device is plugged in, and our 'hotplug'
725                  * intent registration fires, we get an Intent with
726                  * EXTRA_DEVICE set.
727                  *
728                  * When we start up and see a usb device and request
729                  * permission to access it, that queues a
730                  * PendingIntent, which has the EXTRA_DEVICE added in,
731                  * along with the EXTRA_PERMISSION_GRANTED field as
732                  * well.
733                  *
734                  * So, in both cases, we get the device name using the
735                  * same call. We check to see if access was granted,
736                  * in which case we ignore the device field and do our
737                  * usual startup thing.
738                  */
739
740                 UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
741                 boolean granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, true);
742
743                 AltosDebug.debug("intent %s device %s granted %s", intent, device, granted);
744
745                 if (!granted)
746                         device = null;
747
748                 if (device != null) {
749                         AltosDebug.debug("intent has usb device " + device.toString());
750                         connectUsb(device);
751                 } else {
752
753                         /* 'granted' is only false if this intent came
754                          * from the request_permission call and
755                          * permission was denied. In which case, we
756                          * don't want to loop forever...
757                          */
758                         if (granted) {
759                                 AltosDebug.debug("check for a USB device at startup");
760                                 if (check_usb())
761                                         return;
762                         }
763                         AltosDebug.debug("Starting by looking for bluetooth devices");
764                         ensureBluetooth();
765                 }
766         }
767
768         @Override
769         public void onStart() {
770                 super.onStart();
771                 AltosDebug.debug("++ ON START ++");
772
773                 set_switch_time();
774
775                 noticeIntent(getIntent());
776
777                 // Start Telemetry Service
778                 String  action = start_with_usb ? ACTION_USB : ACTION_BLUETOOTH;
779
780                 startService(new Intent(action, null, AltosDroid.this, TelemetryService.class));
781
782                 doBindService();
783
784                 if (mAltosVoice == null)
785                         mAltosVoice = new AltosVoice(this);
786
787         }
788
789         @Override
790         public void onNewIntent(Intent intent) {
791                 super.onNewIntent(intent);
792                 AltosDebug.debug("onNewIntent");
793                 noticeIntent(intent);
794         }
795
796         private void enable_location_updates() {
797                 // Listen for GPS and Network position updates
798                 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
799                 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
800
801                 location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
802
803                 if (location != null)
804                         AltosDebug.debug("Resume, location is %f,%f\n",
805                                          location.getLatitude(),
806                                          location.getLongitude());
807
808                 update_ui(telemetry_state, state, true);
809         }
810
811         static final int MY_PERMISSION_REQUEST_FINE_POSITION = 1001;
812
813         public boolean have_location_permission = false;
814         public boolean asked_location_permission = false;
815
816         AltosMapOnline map_online;
817
818         void
819         tell_map_permission(AltosMapOnline map_online) {
820                 this.map_online = map_online;
821         }
822
823         @Override
824         public void onRequestPermissionsResult(int requestCode, String[] permissions,
825                                                int[] grantResults) {
826                 switch (requestCode) {
827                 case MY_PERMISSION_REQUEST_FINE_POSITION:
828                         if (grantResults.length > 0 &&
829                             grantResults[0] == PackageManager.PERMISSION_GRANTED) {
830                                 have_location_permission = true;
831                                 enable_location_updates();
832                                 if (map_online != null)
833                                         map_online.position_permission();
834                         }
835                         break;
836                 }
837         }
838
839         @Override
840         public void onResume() {
841                 super.onResume();
842                 AltosDebug.debug("+ ON RESUME +");
843
844                 if (!asked_location_permission) {
845                         asked_location_permission = true;
846                         if (ActivityCompat.checkSelfPermission(this,
847                                                               Manifest.permission.ACCESS_FINE_LOCATION)
848                             == PackageManager.PERMISSION_GRANTED)
849                         {
850                                 have_location_permission = true;
851                         }
852                         else
853                         {
854                                 ActivityCompat.requestPermissions(this,
855                                                                   new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
856                                                                   MY_PERMISSION_REQUEST_FINE_POSITION);
857                         }
858                 }
859                 if (have_location_permission)
860                         enable_location_updates();
861         }
862
863         @Override
864         public void onPause() {
865                 super.onPause();
866                 AltosDebug.debug("- ON PAUSE -");
867                 // Stop listening for location updates
868                 if (have_location_permission)
869                         ((LocationManager) getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
870         }
871
872         @Override
873         public void onStop() {
874                 super.onStop();
875                 AltosDebug.debug("-- ON STOP --");
876         }
877
878         @Override
879         public void onDestroy() {
880                 super.onDestroy();
881                 AltosDebug.debug("--- ON DESTROY ---");
882
883                 doUnbindService();
884                 if (mAltosVoice != null) {
885                         mAltosVoice.stop();
886                         mAltosVoice = null;
887                 }
888                 stop_timer();
889         }
890
891         protected void onActivityResult(int requestCode, int resultCode, Intent data) {
892                 AltosDebug.debug("onActivityResult " + resultCode);
893                 switch (requestCode) {
894                 case REQUEST_CONNECT_DEVICE:
895                         // When DeviceListActivity returns with a device to connect to
896                         if (resultCode == Activity.RESULT_OK) {
897                                 connectDevice(data);
898                         }
899                         break;
900                 case REQUEST_ENABLE_BT:
901                         // When the request to enable Bluetooth returns
902                         if (resultCode == Activity.RESULT_OK) {
903                                 // Bluetooth is now enabled, so set up a chat session
904                                 //setupChat();
905                                 AltosDebug.debug("BT enabled");
906                                 bluetoothEnabled(data);
907                         } else {
908                                 // User did not enable Bluetooth or an error occured
909                                 AltosDebug.debug("BT not enabled");
910                         }
911                         break;
912                 case REQUEST_IDLE_MODE:
913                         if (resultCode == Activity.RESULT_OK)
914                                 idle_mode(data);
915                         break;
916                 case REQUEST_IGNITERS:
917                         break;
918                 case REQUEST_SETUP:
919                         if (resultCode == Activity.RESULT_OK)
920                                 note_setup_changes(data);
921                         break;
922                 }
923         }
924
925         private void note_setup_changes(Intent data) {
926                 int changes = data.getIntExtra(SetupActivity.EXTRA_SETUP_CHANGES, 0);
927
928                 if ((changes & SETUP_BAUD) != 0) {
929                         try {
930                                 mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD,
931                                                              AltosPreferences.telemetry_rate(1)));
932                         } catch (RemoteException re) {
933                         }
934                 }
935                 if ((changes & SETUP_UNITS) != 0) {
936                         /* nothing to do here */
937                 }
938                 if ((changes & SETUP_MAP_SOURCE) != 0) {
939                         /* nothing to do here */
940                 }
941                 if ((changes & SETUP_MAP_TYPE) != 0) {
942                         /* nothing to do here */
943                 }
944                 set_switch_time();
945         }
946
947         private void connectUsb(UsbDevice device) {
948                 if (mService == null)
949                         pending_usb_device = device;
950                 else {
951                         // Attempt to connect to the device
952                         try {
953                                 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, device));
954                                 AltosDebug.debug("Sent OPEN_USB message");
955                         } catch (RemoteException e) {
956                                 AltosDebug.debug("connect device message failed");
957                         }
958                 }
959         }
960
961         private void bluetoothEnabled(Intent data) {
962                 try {
963                         mService.send(Message.obtain(null, TelemetryService.MSG_BLUETOOTH_ENABLED, null));
964                 } catch (RemoteException e) {
965                         AltosDebug.debug("send BT enabled message failed");
966                 }
967         }
968
969         private void connectDevice(Intent data) {
970                 // Attempt to connect to the device
971                 try {
972                         String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
973                         String name = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_NAME);
974
975                         AltosDebug.debug("Connecting to " + address + " " + name);
976                         DeviceAddress   a = new DeviceAddress(address, name);
977                         mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, a));
978                         AltosDebug.debug("Sent connecting message");
979                 } catch (RemoteException e) {
980                         AltosDebug.debug("connect device message failed");
981                 }
982         }
983
984         private void disconnectDevice(boolean remember) {
985                 try {
986                         mService.send(Message.obtain(null, TelemetryService.MSG_DISCONNECT, (Boolean) remember));
987                 } catch (RemoteException e) {
988                 }
989         }
990
991         private void idle_mode(Intent data) {
992                 int type = data.getIntExtra(IdleModeActivity.EXTRA_IDLE_RESULT, -1);
993                 Message msg;
994
995                 AltosDebug.debug("intent idle_mode %d", type);
996                 switch (type) {
997                 case IdleModeActivity.IDLE_MODE_CONNECT:
998                         msg = Message.obtain(null, TelemetryService.MSG_MONITOR_IDLE_START);
999                         try {
1000                                 mService.send(msg);
1001                         } catch (RemoteException re) {
1002                         }
1003                         break;
1004                 case IdleModeActivity.IDLE_MODE_DISCONNECT:
1005                         msg = Message.obtain(null, TelemetryService.MSG_MONITOR_IDLE_STOP);
1006                         try {
1007                                 mService.send(msg);
1008                         } catch (RemoteException re) {
1009                         }
1010                         break;
1011                 case IdleModeActivity.IDLE_MODE_REBOOT:
1012                         msg = Message.obtain(null, TelemetryService.MSG_REBOOT);
1013                         try {
1014                                 mService.send(msg);
1015                         } catch (RemoteException re) {
1016                         }
1017                         break;
1018                 case IdleModeActivity.IDLE_MODE_IGNITERS:
1019                         Intent serverIntent = new Intent(this, IgniterActivity.class);
1020                         startActivityForResult(serverIntent, REQUEST_IGNITERS);
1021                         break;
1022                 }
1023         }
1024
1025         @Override
1026         public boolean onCreateOptionsMenu(Menu menu) {
1027                 MenuInflater inflater = getMenuInflater();
1028                 inflater.inflate(R.menu.option_menu, menu);
1029                 return true;
1030         }
1031
1032         void setFrequency(double freq) {
1033                 try {
1034                         mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
1035                         set_switch_time();
1036                 } catch (RemoteException e) {
1037                 }
1038         }
1039
1040         void setFrequency(AltosFrequency frequency) {
1041                 setFrequency (frequency.frequency);
1042         }
1043
1044         void setBaud(int baud) {
1045                 try {
1046                         mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD, baud));
1047                         set_switch_time();
1048                 } catch (RemoteException e) {
1049                 }
1050         }
1051
1052         void setBaud(String baud) {
1053                 try {
1054                         int     value = Integer.parseInt(baud);
1055                         int     rate = AltosLib.ao_telemetry_rate_38400;
1056                         switch (value) {
1057                         case 2400:
1058                                 rate = AltosLib.ao_telemetry_rate_2400;
1059                                 break;
1060                         case 9600:
1061                                 rate = AltosLib.ao_telemetry_rate_9600;
1062                                 break;
1063                         case 38400:
1064                                 rate = AltosLib.ao_telemetry_rate_38400;
1065                                 break;
1066                         }
1067                         setBaud(rate);
1068                 } catch (NumberFormatException e) {
1069                 }
1070         }
1071
1072         void select_tracker(int serial) {
1073                 int i;
1074
1075                 AltosDebug.debug("select tracker %d\n", serial);
1076
1077                 if (serial == selected_serial) {
1078                         AltosDebug.debug("%d already selected\n", serial);
1079                         return;
1080                 }
1081
1082                 if (serial != 0) {
1083                         for (i = 0; i < trackers.length; i++)
1084                                 if (trackers[i].serial == serial)
1085                                         break;
1086
1087                         if (i == trackers.length) {
1088                                 AltosDebug.debug("attempt to select unknown tracker %d\n", serial);
1089                                 return;
1090                         }
1091                 }
1092
1093                 current_serial = selected_serial = serial;
1094                 update_state(null);
1095         }
1096
1097         void touch_trackers(Integer[] serials) {
1098                 AlertDialog.Builder builder_tracker = new AlertDialog.Builder(this);
1099                 builder_tracker.setTitle("Select Tracker");
1100
1101                 final Tracker[] my_trackers = new Tracker[serials.length + 1];
1102
1103                 my_trackers[0] = new Tracker(null);
1104
1105                 for (int i = 0; i < serials.length; i++) {
1106                         AltosState      s = telemetry_state.states.get(serials[i]);
1107                         my_trackers[i+1] = new Tracker(s);
1108                 }
1109                 builder_tracker.setItems(my_trackers,
1110                                          new DialogInterface.OnClickListener() {
1111                                                  public void onClick(DialogInterface dialog, int item) {
1112                                                          if (item == 0)
1113                                                                  select_tracker(0);
1114                                                          else
1115                                                                  select_tracker(my_trackers[item].serial);
1116                                                  }
1117                                          });
1118                 AlertDialog alert_tracker = builder_tracker.create();
1119                 alert_tracker.show();
1120         }
1121
1122         void delete_track(int serial) {
1123                 try {
1124                         mService.send(Message.obtain(null, TelemetryService.MSG_DELETE_SERIAL, (Integer) serial));
1125                 } catch (Exception ex) {
1126                 }
1127         }
1128
1129         @Override
1130         public boolean onOptionsItemSelected(MenuItem item) {
1131                 Intent serverIntent = null;
1132                 switch (item.getItemId()) {
1133                 case R.id.connect_scan:
1134                         ensureBluetooth();
1135                         // Launch the DeviceListActivity to see devices and do scan
1136                         serverIntent = new Intent(this, DeviceListActivity.class);
1137                         startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
1138                         return true;
1139                 case R.id.disconnect:
1140                         /* Disconnect the device
1141                          */
1142                         disconnectDevice(false);
1143                         return true;
1144                 case R.id.quit:
1145                         AltosDebug.debug("R.id.quit");
1146                         disconnectDevice(true);
1147                         finish();
1148                         return true;
1149                 case R.id.setup:
1150                         serverIntent = new Intent(this, SetupActivity.class);
1151                         startActivityForResult(serverIntent, REQUEST_SETUP);
1152                         return true;
1153                 case R.id.select_freq:
1154                         // Set the TBT radio frequency
1155
1156                         final AltosFrequency[] frequencies = AltosPreferences.common_frequencies();
1157                         String[] frequency_strings = new String[frequencies.length];
1158                         for (int i = 0; i < frequencies.length; i++)
1159                                 frequency_strings[i] = frequencies[i].toString();
1160
1161                         AlertDialog.Builder builder_freq = new AlertDialog.Builder(this);
1162                         builder_freq.setTitle("Pick a frequency");
1163                         builder_freq.setItems(frequency_strings,
1164                                          new DialogInterface.OnClickListener() {
1165                                                  public void onClick(DialogInterface dialog, int item) {
1166                                                          setFrequency(frequencies[item]);
1167                                                  }
1168                                          });
1169                         AlertDialog alert_freq = builder_freq.create();
1170                         alert_freq.show();
1171                         return true;
1172                 case R.id.select_tracker:
1173                         if (trackers != null) {
1174                                 AlertDialog.Builder builder_serial = new AlertDialog.Builder(this);
1175                                 builder_serial.setTitle("Select a tracker");
1176                                 builder_serial.setItems(trackers,
1177                                                         new DialogInterface.OnClickListener() {
1178                                                                 public void onClick(DialogInterface dialog, int item) {
1179                                                                         System.out.printf("select item %d %s\n", item, trackers[item].display);
1180                                                                         if (item == 0)
1181                                                                                 select_tracker(0);
1182                                                                         else
1183                                                                                 select_tracker(trackers[item].serial);
1184                                                                 }
1185                                                         });
1186                                 AlertDialog alert_serial = builder_serial.create();
1187                                 alert_serial.show();
1188
1189                         }
1190                         return true;
1191                 case R.id.delete_track:
1192                         if (trackers != null) {
1193                                 AlertDialog.Builder builder_serial = new AlertDialog.Builder(this);
1194                                 builder_serial.setTitle("Delete a track");
1195                                 final Tracker[] my_trackers = new Tracker[trackers.length - 1];
1196                                 for (int i = 0; i < trackers.length - 1; i++)
1197                                         my_trackers[i] = trackers[i+1];
1198                                 builder_serial.setItems(my_trackers,
1199                                                         new DialogInterface.OnClickListener() {
1200                                                                 public void onClick(DialogInterface dialog, int item) {
1201                                                                         delete_track(my_trackers[item].serial);
1202                                                                 }
1203                                                         });
1204                                 AlertDialog alert_serial = builder_serial.create();
1205                                 alert_serial.show();
1206
1207                         }
1208                         return true;
1209                 case R.id.idle_mode:
1210                         serverIntent = new Intent(this, IdleModeActivity.class);
1211                         serverIntent.putExtra(EXTRA_IDLE_MODE, idle_mode);
1212                         startActivityForResult(serverIntent, REQUEST_IDLE_MODE);
1213                         return true;
1214                 }
1215                 return false;
1216         }
1217
1218         static String direction(AltosGreatCircle from_receiver,
1219                                 Location receiver) {
1220                 if (from_receiver == null)
1221                         return null;
1222
1223                 if (receiver == null)
1224                         return null;
1225
1226                 if (!receiver.hasBearing())
1227                         return null;
1228
1229                 float   bearing = receiver.getBearing();
1230                 float   heading = (float) from_receiver.bearing - bearing;
1231
1232                 while (heading <= -180.0f)
1233                         heading += 360.0f;
1234                 while (heading > 180.0f)
1235                         heading -= 360.0f;
1236
1237                 int iheading = (int) (heading + 0.5f);
1238
1239                 if (-1 < iheading && iheading < 1)
1240                         return "ahead";
1241                 else if (iheading < -179 || 179 < iheading)
1242                         return "backwards";
1243                 else if (iheading < 0)
1244                         return String.format("left %d°", -iheading);
1245                 else
1246                         return String.format("right %d°", iheading);
1247         }
1248
1249         public void onLocationChanged(Location location) {
1250                 this.location = location;
1251                 AltosDebug.debug("Location changed to %f,%f",
1252                                  location.getLatitude(),
1253                                  location.getLongitude());
1254                 update_ui(telemetry_state, state, false);
1255         }
1256
1257         public void onStatusChanged(String provider, int status, Bundle extras) {
1258                 AltosDebug.debug("Location status now %d\n", status);
1259         }
1260
1261         public void onProviderEnabled(String provider) {
1262                 AltosDebug.debug("Location provider enabled %s\n", provider);
1263         }
1264
1265         public void onProviderDisabled(String provider) {
1266                 AltosDebug.debug("Location provider disabled %s\n", provider);
1267         }
1268 }