altosdroid: Change tracker selection dialog
[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_serial == 0 || telemetry_state.get(selected_serial) == null) {
315                         AltosDebug.debug("selected serial set to %d", selected_serial);
316                         selected_serial = telemetry_state.latest_serial;
317                 }
318
319                 int shown_serial = selected_serial;
320
321                 if (telemetry_state.idle_mode)
322                         shown_serial = telemetry_state.latest_serial;
323
324                 if (!registered_units_listener) {
325                         registered_units_listener = true;
326                         AltosPreferences.register_units_listener(this);
327                 }
328
329                 int     num_trackers = 0;
330
331                 for (AltosState s : telemetry_state.values()) {
332                         num_trackers++;
333                 }
334
335                 trackers = new Tracker[num_trackers + 1];
336
337                 int n = 0;
338                 trackers[n++] = new Tracker(0, "auto", 0.0);
339
340                 for (AltosState s : telemetry_state.values())
341                         trackers[n++] = new Tracker(s);
342
343                 Arrays.sort(trackers);
344
345                 if (telemetry_state.frequency != AltosLib.MISSING)
346                         telem_frequency = telemetry_state.frequency;
347
348                 update_title(telemetry_state);
349
350                 AltosState      state = telemetry_state.get(shown_serial);
351
352                 update_ui(telemetry_state, state, telemetry_state.quiet);
353
354                 start_timer();
355         }
356
357         boolean same_string(String a, String b) {
358                 if (a == null) {
359                         if (b == null)
360                                 return true;
361                         return false;
362                 } else {
363                         if (b == null)
364                                 return false;
365                         return a.equals(b);
366                 }
367         }
368
369
370         private int blend_component(int a, int b, double r, int shift, int mask) {
371                 return ((int) (((a >> shift) & mask) * r + ((b >> shift) & mask) * (1 - r)) & mask) << shift;
372         }
373         private int blend_color(int a, int b, double r) {
374                 return (blend_component(a, b, r, 0, 0xff) |
375                         blend_component(a, b, r, 8, 0xff) |
376                         blend_component(a, b, r, 16, 0xff) |
377                         blend_component(a, b, r, 24, 0xff));
378         }
379
380         int state_age(long received_time) {
381                 return (int) ((System.currentTimeMillis() - received_time + 500) / 1000);
382         }
383
384         void set_screen_on(int age) {
385                 if (age < 60)
386                         getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
387                 else
388                         getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
389         }
390
391         static String age_string(int age) {
392                 String  text;
393                 if (age < 60)
394                         text = String.format("%ds", age);
395                 else if (age < 60 * 60)
396                         text = String.format("%dm", age / 60);
397                 else if (age < 60 * 60 * 24)
398                         text = String.format("%dh", age / (60 * 60));
399                 else
400                         text = String.format("%dd", age / (24 * 60 * 60));
401                 return text;
402         }
403
404         void update_age() {
405                 if (saved_state != null) {
406                         int age = state_age(saved_state.received_time);
407
408                         double age_scale = age / 100.0;
409
410                         if (age_scale > 1.0)
411                                 age_scale = 1.0;
412
413                         mAgeView.setTextColor(blend_color(mAgeOldColor, mAgeNewColor, age_scale));
414
415                         set_screen_on(age);
416
417                         mAgeView.setText(age_string(age));
418                 }
419         }
420
421         void update_ui(TelemetryState telem_state, AltosState state, boolean quiet) {
422
423                 this.state = state;
424
425                 int prev_state = AltosLib.ao_flight_invalid;
426
427                 AltosGreatCircle from_receiver = null;
428
429                 if (saved_state != null)
430                         prev_state = saved_state.state;
431
432                 if (state != null) {
433                         set_screen_on(state_age(state.received_time));
434
435                         if (state.state() == AltosLib.ao_flight_stateless) {
436                                 boolean prev_locked = false;
437                                 boolean locked = false;
438
439                                 if(state.gps != null)
440                                         locked = state.gps.locked;
441                                 if (saved_state != null)
442                                         prev_locked = saved_state.locked;
443                                 if (prev_locked != locked) {
444                                         String currentTab = mTabHost.getCurrentTabTag();
445                                         if (locked) {
446                                                 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
447                                         } else {
448                                                 if (currentTab.equals(tab_flight_name)) mTabHost.setCurrentTabByTag(tab_pad_name);
449                                         }
450                                 }
451                         } else {
452                                 if (prev_state != state.state()) {
453                                         String currentTab = mTabHost.getCurrentTabTag();
454                                         switch (state.state()) {
455                                         case AltosLib.ao_flight_boost:
456                                                 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
457                                                 break;
458                                         case AltosLib.ao_flight_landed:
459                                                 if (currentTab.equals(tab_flight_name)) mTabHost.setCurrentTabByTag(tab_recover_name);
460                                                 break;
461                                         case AltosLib.ao_flight_stateless:
462                                                 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
463                                                 break;
464                                         }
465                                 }
466                         }
467
468                         if (location != null && state.gps != null && state.gps.locked) {
469                                 double altitude = 0;
470                                 if (location.hasAltitude())
471                                         altitude = location.getAltitude();
472                                 from_receiver = new AltosGreatCircle(location.getLatitude(),
473                                                                      location.getLongitude(),
474                                                                      altitude,
475                                                                      state.gps.lat,
476                                                                      state.gps.lon,
477                                                                      state.gps.alt);
478                         }
479
480                         if (saved_state == null || !same_string(saved_state.callsign, state.cal_data().callsign)) {
481                                 mCallsignView.setText(state.cal_data().callsign);
482                         }
483                         if (saved_state == null || state.cal_data().serial != saved_state.serial) {
484                                 if (state.cal_data().serial == AltosLib.MISSING)
485                                         mSerialView.setText("");
486                                 else
487                                         mSerialView.setText(String.format("%d", state.cal_data().serial));
488                         }
489                         if (saved_state == null || state.cal_data().flight != saved_state.flight) {
490                                 if (state.cal_data().flight == AltosLib.MISSING)
491                                         mFlightView.setText("");
492                                 else
493                                         mFlightView.setText(String.format("%d", state.cal_data().flight));
494                         }
495                         if (saved_state == null || state.state() != saved_state.state) {
496                                 if (state.state() == AltosLib.ao_flight_stateless) {
497                                         mStateLayout.setVisibility(View.GONE);
498                                 } else {
499                                         mStateView.setText(state.state_name());
500                                         mStateLayout.setVisibility(View.VISIBLE);
501                                 }
502                         }
503                         if (saved_state == null || state.rssi != saved_state.rssi) {
504                                 if (state.rssi == AltosLib.MISSING)
505                                         mRSSIView.setText("");
506                                 else
507                                         mRSSIView.setText(String.format("%d", state.rssi));
508                         }
509                         saved_state = new SavedState(state);
510                 }
511
512                 for (AltosDroidTab mTab : mTabs)
513                         mTab.update_ui(telem_state, state, from_receiver, location, mTab == mTabsAdapter.currentItem());
514
515                 if (mAltosVoice != null && mTabsAdapter.currentItem() != null)
516                         mAltosVoice.tell(telem_state, state, from_receiver, location, (AltosDroidTab) mTabsAdapter.currentItem(), quiet);
517
518         }
519
520         private void onTimerTick() {
521                 try {
522                         mMessenger.send(Message.obtain(null, MSG_UPDATE_AGE));
523                 } catch (RemoteException e) {
524                 }
525         }
526
527         static String pos(double p, String pos, String neg) {
528                 String  h = pos;
529                 if (p == AltosLib.MISSING)
530                         return "";
531                 if (p < 0) {
532                         h = neg;
533                         p = -p;
534                 }
535                 int deg = (int) Math.floor(p);
536                 double min = (p - Math.floor(p)) * 60.0;
537                 return String.format("%d° %7.4f\" %s", deg, min, h);
538         }
539
540         static String number(String format, double value) {
541                 if (value == AltosLib.MISSING)
542                         return "";
543                 return String.format(format, value);
544         }
545
546         static String integer(String format, int value) {
547                 if (value == AltosLib.MISSING)
548                         return "";
549                 return String.format(format, value);
550         }
551
552         private View create_tab_view(String label) {
553                 LayoutInflater inflater = (LayoutInflater) this.getLayoutInflater();
554                 View tab_view = inflater.inflate(R.layout.tab_layout, null);
555                 TextView text_view = (TextView) tab_view.findViewById (R.id.tabLabel);
556                 text_view.setText(label);
557                 return tab_view;
558         }
559
560         static public int[] themes = {
561                 R.style.Small,
562                 R.style.Medium,
563                 R.style.Large,
564                 R.style.Extra
565         };
566
567         static public int[] dialog_themes = {
568                 R.style.Small_Dialog,
569                 R.style.Medium_Dialog,
570                 R.style.Large_Dialog,
571                 R.style.Extra_Dialog
572         };
573
574         @Override
575         public void onCreate(Bundle savedInstanceState) {
576                 // Initialise preferences
577                 AltosDroidPreferences.init(this);
578                 setTheme(themes[AltosDroidPreferences.font_size()]);
579                 super.onCreate(savedInstanceState);
580                 AltosDebug.init(this);
581                 AltosDebug.debug("+++ ON CREATE +++");
582
583
584                 fm = getSupportFragmentManager();
585
586                 // Set up the window layout
587                 setContentView(R.layout.altosdroid);
588
589                 // Create the Tabs and ViewPager
590                 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
591                 mTabHost.setup();
592
593                 mViewPager = (AltosViewPager)findViewById(R.id.pager);
594                 mViewPager.setOffscreenPageLimit(4);
595
596                 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
597
598                 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_pad_name).setIndicator(create_tab_view("Pad")), TabPad.class, null);
599                 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_flight_name).setIndicator(create_tab_view("Flight")), TabFlight.class, null);
600                 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_recover_name).setIndicator(create_tab_view("Recover")), TabRecover.class, null);
601                 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_map_name).setIndicator(create_tab_view("Map")), TabMap.class, null);
602
603                 // Display the Version
604                 mVersion = (TextView) findViewById(R.id.version);
605                 mVersion.setText("Version: " + BuildInfo.version +
606                                  " Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
607                                  " (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
608
609                 mCallsignView  = (TextView) findViewById(R.id.callsign_value);
610                 mRSSIView      = (TextView) findViewById(R.id.rssi_value);
611                 mSerialView    = (TextView) findViewById(R.id.serial_value);
612                 mFlightView    = (TextView) findViewById(R.id.flight_value);
613                 mStateLayout   = (RelativeLayout) findViewById(R.id.state_container);
614                 mStateView     = (TextView) findViewById(R.id.state_value);
615                 mAgeView       = (TextView) findViewById(R.id.age_value);
616                 mAgeNewColor   = mAgeView.getTextColors().getDefaultColor();
617                 mAgeOldColor   = getResources().getColor(R.color.old_color, getTheme());
618         }
619
620         private void ensureBluetooth() {
621                 // Get local Bluetooth adapter
622                 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
623
624                 /* if there is a BT adapter and it isn't turned on, then turn it on */
625                 if (mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) {
626                         Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
627                         startActivityForResult(enableIntent, AltosDroid.REQUEST_ENABLE_BT);
628                 }
629         }
630
631         private boolean check_usb() {
632                 UsbDevice       device = AltosUsb.find_device(this, AltosLib.product_basestation);
633
634                 if (device != null) {
635                         Intent          i = new Intent(this, AltosDroid.class);
636                         PendingIntent   pi = PendingIntent.getActivity(this, 0, new Intent("hello world", null, this, AltosDroid.class), 0);
637
638                         if (AltosUsb.request_permission(this, device, pi)) {
639                                 connectUsb(device);
640                         }
641                         start_with_usb = true;
642                         return true;
643                 }
644
645                 start_with_usb = false;
646
647                 return false;
648         }
649
650         private void noticeIntent(Intent intent) {
651
652                 /* Ok, this is pretty convenient.
653                  *
654                  * When a USB device is plugged in, and our 'hotplug'
655                  * intent registration fires, we get an Intent with
656                  * EXTRA_DEVICE set.
657                  *
658                  * When we start up and see a usb device and request
659                  * permission to access it, that queues a
660                  * PendingIntent, which has the EXTRA_DEVICE added in,
661                  * along with the EXTRA_PERMISSION_GRANTED field as
662                  * well.
663                  *
664                  * So, in both cases, we get the device name using the
665                  * same call. We check to see if access was granted,
666                  * in which case we ignore the device field and do our
667                  * usual startup thing.
668                  */
669
670                 UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
671                 boolean granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, true);
672
673                 AltosDebug.debug("intent %s device %s granted %s", intent, device, granted);
674
675                 if (!granted)
676                         device = null;
677
678                 if (device != null) {
679                         AltosDebug.debug("intent has usb device " + device.toString());
680                         connectUsb(device);
681                 } else {
682
683                         /* 'granted' is only false if this intent came
684                          * from the request_permission call and
685                          * permission was denied. In which case, we
686                          * don't want to loop forever...
687                          */
688                         if (granted) {
689                                 AltosDebug.debug("check for a USB device at startup");
690                                 if (check_usb())
691                                         return;
692                         }
693                         AltosDebug.debug("Starting by looking for bluetooth devices");
694                         ensureBluetooth();
695                 }
696         }
697
698         @Override
699         public void onStart() {
700                 super.onStart();
701                 AltosDebug.debug("++ ON START ++");
702
703                 set_switch_time();
704
705                 noticeIntent(getIntent());
706
707                 // Start Telemetry Service
708                 String  action = start_with_usb ? ACTION_USB : ACTION_BLUETOOTH;
709
710                 startService(new Intent(action, null, AltosDroid.this, TelemetryService.class));
711
712                 doBindService();
713
714                 if (mAltosVoice == null)
715                         mAltosVoice = new AltosVoice(this);
716
717         }
718
719         @Override
720         public void onNewIntent(Intent intent) {
721                 super.onNewIntent(intent);
722                 AltosDebug.debug("onNewIntent");
723                 noticeIntent(intent);
724         }
725
726         private void enable_location_updates() {
727                 // Listen for GPS and Network position updates
728                 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
729                 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
730
731                 location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
732
733                 if (location != null)
734                         AltosDebug.debug("Resume, location is %f,%f\n",
735                                          location.getLatitude(),
736                                          location.getLongitude());
737
738                 update_ui(telemetry_state, state, true);
739         }
740
741         static final int MY_PERMISSION_REQUEST = 1001;
742
743         public boolean have_location_permission = false;
744         public boolean have_storage_permission = false;
745         public boolean asked_permission = false;
746
747         AltosMapOnline map_online;
748
749         void
750         tell_map_permission(AltosMapOnline map_online) {
751                 this.map_online = map_online;
752         }
753
754         @Override
755         public void onRequestPermissionsResult(int requestCode, String[] permissions,
756                                                int[] grantResults) {
757                 if (requestCode == MY_PERMISSION_REQUEST) {
758                         for (int i = 0; i < grantResults.length; i++) {
759                                 if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
760                                         if (permissions[i].equals(Manifest.permission.ACCESS_FINE_LOCATION)) {
761                                                 have_location_permission = true;
762                                                 enable_location_updates();
763                                                 if (map_online != null)
764                                                         map_online.position_permission();
765                                         }
766                                         if (permissions[i].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
767                                                 have_storage_permission = true;
768                                         }
769                                 }
770                         }
771                 }
772         }
773
774         @Override
775         public void onResume() {
776                 super.onResume();
777                 AltosDebug.debug("+ ON RESUME +");
778
779                 if (!asked_permission) {
780                         asked_permission = true;
781                         if (ActivityCompat.checkSelfPermission(this,
782                                                               Manifest.permission.ACCESS_FINE_LOCATION)
783                             == PackageManager.PERMISSION_GRANTED)
784                         {
785                                 have_location_permission = true;
786                         }
787                         if (ActivityCompat.checkSelfPermission(this,
788                                                                Manifest.permission.WRITE_EXTERNAL_STORAGE)
789                             == PackageManager.PERMISSION_GRANTED)
790                         {
791                                 have_storage_permission = true;
792                         }
793                         int count = (have_location_permission ? 0 : 1) + (have_storage_permission ? 0 : 1);
794                         if (count > 0)
795                         {
796                                 String[] permissions = new String[count];
797                                 int i = 0;
798                                 if (!have_location_permission)
799                                         permissions[i++] = Manifest.permission.ACCESS_FINE_LOCATION;
800                                 if (!have_location_permission)
801                                         permissions[i++] = Manifest.permission.WRITE_EXTERNAL_STORAGE;
802                                 ActivityCompat.requestPermissions(this, permissions, MY_PERMISSION_REQUEST);
803                         }
804                 }
805                 if (have_location_permission)
806                         enable_location_updates();
807         }
808
809         @Override
810         public void onPause() {
811                 super.onPause();
812                 AltosDebug.debug("- ON PAUSE -");
813                 // Stop listening for location updates
814                 if (have_location_permission)
815                         ((LocationManager) getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
816         }
817
818         @Override
819         public void onStop() {
820                 super.onStop();
821                 AltosDebug.debug("-- ON STOP --");
822         }
823
824         @Override
825         public void onDestroy() {
826                 super.onDestroy();
827                 AltosDebug.debug("--- ON DESTROY ---");
828
829                 doUnbindService();
830                 if (mAltosVoice != null) {
831                         mAltosVoice.stop();
832                         mAltosVoice = null;
833                 }
834                 stop_timer();
835         }
836
837         protected void onActivityResult(int requestCode, int resultCode, Intent data) {
838                 AltosDebug.debug("onActivityResult request %d result %d", requestCode, resultCode);
839                 switch (requestCode) {
840                 case REQUEST_CONNECT_DEVICE:
841                         // When DeviceListActivity returns with a device to connect to
842                         if (resultCode == Activity.RESULT_OK) {
843                                 connectDevice(data);
844                         }
845                         break;
846                 case REQUEST_ENABLE_BT:
847                         // When the request to enable Bluetooth returns
848                         if (resultCode == Activity.RESULT_OK) {
849                                 // Bluetooth is now enabled, so set up a chat session
850                                 //setupChat();
851                                 AltosDebug.debug("BT enabled");
852                                 bluetoothEnabled(data);
853                         } else {
854                                 // User did not enable Bluetooth or an error occured
855                                 AltosDebug.debug("BT not enabled");
856                         }
857                         break;
858                 case REQUEST_IDLE_MODE:
859                         if (resultCode == Activity.RESULT_OK)
860                                 idle_mode(data);
861                         break;
862                 case REQUEST_IGNITERS:
863                         break;
864                 case REQUEST_SETUP:
865                         if (resultCode == Activity.RESULT_OK)
866                                 note_setup_changes(data);
867                         break;
868                 case REQUEST_SELECT_TRACKER:
869                         if (resultCode == Activity.RESULT_OK)
870                                 select_tracker(data);
871                         break;
872                 }
873         }
874
875         private void note_setup_changes(Intent data) {
876                 int changes = data.getIntExtra(SetupActivity.EXTRA_SETUP_CHANGES, 0);
877
878                 AltosDebug.debug("note_setup_changes changes %d\n", changes);
879
880                 if ((changes & SETUP_BAUD) != 0) {
881                         try {
882                                 mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD,
883                                                              AltosPreferences.telemetry_rate(1)));
884                         } catch (RemoteException re) {
885                         }
886                 }
887                 if ((changes & SETUP_UNITS) != 0) {
888                         /* nothing to do here */
889                 }
890                 if ((changes & SETUP_MAP_SOURCE) != 0) {
891                         /* nothing to do here */
892                 }
893                 if ((changes & SETUP_MAP_TYPE) != 0) {
894                         /* nothing to do here */
895                 }
896                 set_switch_time();
897                 if ((changes & SETUP_FONT_SIZE) != 0) {
898                         AltosDebug.debug(" ==== Recreate to switch font sizes ==== ");
899                         finish();
900                         startActivity(getIntent());
901                 }
902         }
903
904         private void connectUsb(UsbDevice device) {
905                 if (mService == null)
906                         pending_usb_device = device;
907                 else {
908                         // Attempt to connect to the device
909                         try {
910                                 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, device));
911                                 AltosDebug.debug("Sent OPEN_USB message");
912                         } catch (RemoteException e) {
913                                 AltosDebug.debug("connect device message failed");
914                         }
915                 }
916         }
917
918         private void bluetoothEnabled(Intent data) {
919                 if (mService != null) {
920                         try {
921                                 mService.send(Message.obtain(null, TelemetryService.MSG_BLUETOOTH_ENABLED, null));
922                         } catch (RemoteException e) {
923                                 AltosDebug.debug("send BT enabled message failed");
924                         }
925                 }
926         }
927
928         private void connectDevice(Intent data) {
929                 // Attempt to connect to the device
930                 try {
931                         String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
932                         String name = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_NAME);
933
934                         AltosDebug.debug("Connecting to " + address + " " + name);
935                         DeviceAddress   a = new DeviceAddress(address, name);
936                         mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, a));
937                         AltosDebug.debug("Sent connecting message");
938                 } catch (RemoteException e) {
939                         AltosDebug.debug("connect device message failed");
940                 }
941         }
942
943         private void disconnectDevice(boolean remember) {
944                 try {
945                         mService.send(Message.obtain(null, TelemetryService.MSG_DISCONNECT, (Boolean) remember));
946                 } catch (RemoteException e) {
947                 }
948         }
949
950         private void idle_mode(Intent data) {
951                 int type = data.getIntExtra(IdleModeActivity.EXTRA_IDLE_RESULT, -1);
952                 Message msg;
953
954                 AltosDebug.debug("intent idle_mode %d", type);
955                 switch (type) {
956                 case IdleModeActivity.IDLE_MODE_CONNECT:
957                         msg = Message.obtain(null, TelemetryService.MSG_MONITOR_IDLE_START);
958                         try {
959                                 mService.send(msg);
960                         } catch (RemoteException re) {
961                         }
962                         break;
963                 case IdleModeActivity.IDLE_MODE_DISCONNECT:
964                         msg = Message.obtain(null, TelemetryService.MSG_MONITOR_IDLE_STOP);
965                         try {
966                                 mService.send(msg);
967                         } catch (RemoteException re) {
968                         }
969                         break;
970                 case IdleModeActivity.IDLE_MODE_REBOOT:
971                         msg = Message.obtain(null, TelemetryService.MSG_REBOOT);
972                         try {
973                                 mService.send(msg);
974                         } catch (RemoteException re) {
975                         }
976                         break;
977                 case IdleModeActivity.IDLE_MODE_IGNITERS:
978                         Intent serverIntent = new Intent(this, IgniterActivity.class);
979                         startActivityForResult(serverIntent, REQUEST_IGNITERS);
980                         break;
981                 }
982         }
983
984         @Override
985         public boolean onCreateOptionsMenu(Menu menu) {
986                 MenuInflater inflater = getMenuInflater();
987                 inflater.inflate(R.menu.option_menu, menu);
988                 return true;
989         }
990
991         double telem_frequency = 434.550;
992
993         void setFrequency(double freq) {
994                 telem_frequency = freq;
995                 try {
996                         mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
997                         set_switch_time();
998                 } catch (RemoteException e) {
999                 }
1000         }
1001
1002         void setFrequency(AltosFrequency frequency) {
1003                 setFrequency (frequency.frequency);
1004         }
1005
1006         void setBaud(int baud) {
1007                 try {
1008                         mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD, baud));
1009                         set_switch_time();
1010                 } catch (RemoteException e) {
1011                 }
1012         }
1013
1014         void setBaud(String baud) {
1015                 try {
1016                         int     value = Integer.parseInt(baud);
1017                         int     rate = AltosLib.ao_telemetry_rate_38400;
1018                         switch (value) {
1019                         case 2400:
1020                                 rate = AltosLib.ao_telemetry_rate_2400;
1021                                 break;
1022                         case 9600:
1023                                 rate = AltosLib.ao_telemetry_rate_9600;
1024                                 break;
1025                         case 38400:
1026                                 rate = AltosLib.ao_telemetry_rate_38400;
1027                                 break;
1028                         }
1029                         setBaud(rate);
1030                 } catch (NumberFormatException e) {
1031                 }
1032         }
1033
1034         void select_tracker(int serial, double frequency) {
1035
1036                 AltosDebug.debug("select tracker %d %7.3f\n", serial, frequency);
1037
1038                 if (serial == selected_serial) {
1039                         AltosDebug.debug("%d already selected\n", serial);
1040                         return;
1041                 }
1042
1043                 if (serial != 0) {
1044                         int i;
1045                         for (i = 0; i < trackers.length; i++)
1046                                 if (trackers[i].serial == serial)
1047                                         break;
1048
1049                         if (i == trackers.length) {
1050                                 AltosDebug.debug("attempt to select unknown tracker %d\n", serial);
1051                                 return;
1052                         }
1053                         if (frequency != 0.0 && frequency != AltosLib.MISSING)
1054                                 setFrequency(frequency);
1055                 }
1056
1057                 selected_serial = serial;
1058                 update_state(null);
1059         }
1060
1061         void select_tracker(Intent data) {
1062                 int serial = data.getIntExtra(SelectTrackerActivity.EXTRA_SERIAL_NUMBER, 0);
1063                 double frequency = data.getDoubleExtra(SelectTrackerActivity.EXTRA_FREQUENCY, 0.0);
1064                 select_tracker(serial, frequency);
1065         }
1066
1067         void touch_trackers(Integer[] serials) {
1068                 AlertDialog.Builder builder_tracker = new AlertDialog.Builder(this);
1069                 builder_tracker.setTitle("Select Tracker");
1070
1071                 final Tracker[] my_trackers = new Tracker[serials.length + 1];
1072
1073                 my_trackers[0] = new Tracker(null);
1074
1075                 for (int i = 0; i < serials.length; i++) {
1076                         AltosState      s = telemetry_state.get(serials[i]);
1077                         my_trackers[i+1] = new Tracker(s);
1078                 }
1079                 builder_tracker.setItems(my_trackers,
1080                                          new DialogInterface.OnClickListener() {
1081                                                  public void onClick(DialogInterface dialog, int item) {
1082                                                          if (item == 0)
1083                                                                  select_tracker(0, 0.0);
1084                                                          else
1085                                                                  select_tracker(my_trackers[item].serial, my_trackers[item].frequency);
1086                                                  }
1087                                          });
1088                 AlertDialog alert_tracker = builder_tracker.create();
1089                 alert_tracker.show();
1090         }
1091
1092         void delete_track(int serial) {
1093                 try {
1094                         mService.send(Message.obtain(null, TelemetryService.MSG_DELETE_SERIAL, (Integer) serial));
1095                 } catch (Exception ex) {
1096                 }
1097         }
1098
1099         @Override
1100         public boolean onOptionsItemSelected(MenuItem item) {
1101                 Intent serverIntent = null;
1102                 switch (item.getItemId()) {
1103                 case R.id.connect_scan:
1104                         ensureBluetooth();
1105                         // Launch the DeviceListActivity to see devices and do scan
1106                         serverIntent = new Intent(this, DeviceListActivity.class);
1107                         startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
1108                         return true;
1109                 case R.id.disconnect:
1110                         /* Disconnect the device
1111                          */
1112                         disconnectDevice(false);
1113                         return true;
1114                 case R.id.quit:
1115                         AltosDebug.debug("R.id.quit");
1116                         disconnectDevice(true);
1117                         finish();
1118                         return true;
1119                 case R.id.setup:
1120                         serverIntent = new Intent(this, SetupActivity.class);
1121                         startActivityForResult(serverIntent, REQUEST_SETUP);
1122                         return true;
1123                 case R.id.select_freq:
1124                         // Set the TBT radio frequency
1125
1126                         final AltosFrequency[] frequencies = AltosPreferences.common_frequencies();
1127                         String[] frequency_strings = new String[frequencies.length];
1128                         for (int i = 0; i < frequencies.length; i++)
1129                                 frequency_strings[i] = frequencies[i].toString();
1130
1131                         AlertDialog.Builder builder_freq = new AlertDialog.Builder(this);
1132                         builder_freq.setTitle("Pick a frequency");
1133                         builder_freq.setItems(frequency_strings,
1134                                          new DialogInterface.OnClickListener() {
1135                                                  public void onClick(DialogInterface dialog, int item) {
1136                                                          setFrequency(frequencies[item]);
1137                                                  }
1138                                          });
1139                         AlertDialog alert_freq = builder_freq.create();
1140                         alert_freq.show();
1141                         return true;
1142                 case R.id.select_tracker:
1143                         serverIntent = new Intent(this, SelectTrackerActivity.class);
1144                         if (trackers != null) {
1145                                 ArrayList<Tracker> tracker_array = new ArrayList<Tracker>(Arrays.asList(trackers));
1146                                 serverIntent.putParcelableArrayListExtra(EXTRA_TRACKERS, tracker_array);
1147                         } else {
1148                                 serverIntent.putExtra(EXTRA_TRACKERS, (Parcelable[]) null);
1149                         }
1150                         startActivityForResult(serverIntent, REQUEST_SELECT_TRACKER);
1151                         return true;
1152                 case R.id.delete_track:
1153                         if (trackers != null) {
1154                                 AlertDialog.Builder builder_serial = new AlertDialog.Builder(this);
1155                                 builder_serial.setTitle("Delete a track");
1156                                 final Tracker[] my_trackers = new Tracker[trackers.length - 1];
1157                                 for (int i = 0; i < trackers.length - 1; i++)
1158                                         my_trackers[i] = trackers[i+1];
1159                                 builder_serial.setItems(my_trackers,
1160                                                         new DialogInterface.OnClickListener() {
1161                                                                 public void onClick(DialogInterface dialog, int item) {
1162                                                                         delete_track(my_trackers[item].serial);
1163                                                                 }
1164                                                         });
1165                                 AlertDialog alert_serial = builder_serial.create();
1166                                 alert_serial.show();
1167
1168                         }
1169                         return true;
1170                 case R.id.idle_mode:
1171                         serverIntent = new Intent(this, IdleModeActivity.class);
1172                         serverIntent.putExtra(EXTRA_IDLE_MODE, idle_mode);
1173                         serverIntent.putExtra(EXTRA_FREQUENCY, telem_frequency);
1174                         startActivityForResult(serverIntent, REQUEST_IDLE_MODE);
1175                         return true;
1176                 }
1177                 return false;
1178         }
1179
1180         static String direction(AltosGreatCircle from_receiver,
1181                                 Location receiver) {
1182                 if (from_receiver == null)
1183                         return null;
1184
1185                 if (receiver == null)
1186                         return null;
1187
1188                 if (!receiver.hasBearing())
1189                         return null;
1190
1191                 float   bearing = receiver.getBearing();
1192                 float   heading = (float) from_receiver.bearing - bearing;
1193
1194                 while (heading <= -180.0f)
1195                         heading += 360.0f;
1196                 while (heading > 180.0f)
1197                         heading -= 360.0f;
1198
1199                 int iheading = (int) (heading + 0.5f);
1200
1201                 if (-1 < iheading && iheading < 1)
1202                         return "ahead";
1203                 else if (iheading < -179 || 179 < iheading)
1204                         return "backwards";
1205                 else if (iheading < 0)
1206                         return String.format("left %d°", -iheading);
1207                 else
1208                         return String.format("right %d°", iheading);
1209         }
1210
1211         public void onLocationChanged(Location location) {
1212                 this.location = location;
1213                 AltosDebug.debug("Location changed to %f,%f",
1214                                  location.getLatitude(),
1215                                  location.getLongitude());
1216                 update_ui(telemetry_state, state, false);
1217         }
1218
1219         public void onStatusChanged(String provider, int status, Bundle extras) {
1220                 AltosDebug.debug("Location status now %d\n", status);
1221         }
1222
1223         public void onProviderEnabled(String provider) {
1224                 AltosDebug.debug("Location provider enabled %s\n", provider);
1225         }
1226
1227         public void onProviderDisabled(String provider) {
1228                 AltosDebug.debug("Location provider disabled %s\n", provider);
1229         }
1230 }