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