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