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