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