f664510582d291a6f902052cdb2a93ed35f8d502
[fw/altos] / altosdroid / src / 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; version 2 of the License.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
16  */
17
18 package org.altusmetrum.AltosDroid;
19
20 import java.lang.ref.WeakReference;
21 import java.util.ArrayList;
22 import java.util.Timer;
23 import java.util.TimerTask;
24 import java.text.*;
25
26 import android.app.Activity;
27 import android.app.PendingIntent;
28 import android.bluetooth.BluetoothAdapter;
29 import android.bluetooth.BluetoothDevice;
30 import android.content.Intent;
31 import android.content.Context;
32 import android.content.ComponentName;
33 import android.content.ServiceConnection;
34 import android.content.DialogInterface;
35 import android.os.IBinder;
36 import android.os.Bundle;
37 import android.os.Handler;
38 import android.os.Message;
39 import android.os.Messenger;
40 import android.os.RemoteException;
41 import android.content.res.Resources;
42 import android.support.v4.app.FragmentActivity;
43 import android.support.v4.app.FragmentManager;
44 import android.util.DisplayMetrics;
45 import android.view.*;
46 import android.widget.*;
47 import android.app.AlertDialog;
48 import android.location.Location;
49 import android.hardware.usb.*;
50 import android.graphics.*;
51 import android.graphics.drawable.*;
52
53 import org.altusmetrum.altoslib_7.*;
54
55 public class AltosDroid extends FragmentActivity implements AltosUnitsListener {
56
57         // Actions sent to the telemetry server at startup time
58
59         public static final String ACTION_BLUETOOTH = "org.altusmetrum.AltosDroid.BLUETOOTH";
60         public static final String ACTION_USB = "org.altusmetrum.AltosDroid.USB";
61
62         // Message types received by our Handler
63
64         public static final int MSG_STATE           = 1;
65         public static final int MSG_UPDATE_AGE      = 2;
66
67         // Intent request codes
68         public static final int REQUEST_CONNECT_DEVICE = 1;
69         public static final int REQUEST_ENABLE_BT      = 2;
70         public static final int REQUEST_PRELOAD_MAPS   = 3;
71         public static final int REQUEST_MAP_TYPE       = 4;
72
73         public int map_type = AltosMap.maptype_hybrid;
74
75         public static FragmentManager   fm;
76
77         private BluetoothAdapter mBluetoothAdapter = null;
78
79         // Flight state values
80         private TextView mCallsignView;
81         private TextView mRSSIView;
82         private TextView mSerialView;
83         private TextView mFlightView;
84         private RelativeLayout mStateLayout;
85         private TextView mStateView;
86         private TextView mAgeView;
87         private boolean  mAgeViewOld;
88         private int mAgeNewColor;
89         private int mAgeOldColor;
90
91         // field to display the version at the bottom of the screen
92         private TextView mVersion;
93
94         private double frequency;
95         private int telemetry_rate;
96
97         // Tabs
98         TabHost         mTabHost;
99         AltosViewPager  mViewPager;
100         TabsAdapter     mTabsAdapter;
101         ArrayList<AltosDroidTab> mTabs = new ArrayList<AltosDroidTab>();
102         int             tabHeight;
103
104         // Timer and Saved flight state for Age calculation
105         private Timer timer;
106         AltosState saved_state;
107         TelemetryState  telemetry_state;
108         Integer[]       serials;
109
110         UsbDevice       pending_usb_device;
111         boolean         start_with_usb;
112
113         // Service
114         private boolean mIsBound   = false;
115         private Messenger mService = null;
116         final Messenger mMessenger = new Messenger(new IncomingHandler(this));
117
118         // Text to Speech
119         private AltosVoice mAltosVoice = null;
120
121         // The Handler that gets information back from the Telemetry Service
122         static class IncomingHandler extends Handler {
123                 private final WeakReference<AltosDroid> mAltosDroid;
124                 IncomingHandler(AltosDroid ad) { mAltosDroid = new WeakReference<AltosDroid>(ad); }
125
126                 @Override
127                 public void handleMessage(Message msg) {
128                         AltosDroid ad = mAltosDroid.get();
129
130                         switch (msg.what) {
131                         case MSG_STATE:
132                                 AltosDebug.debug("MSG_STATE");
133                                 if (msg.obj == null) {
134                                         AltosDebug.debug("telemetry_state null!");
135                                         return;
136                                 }
137                                 ad.update_state((TelemetryState) msg.obj);
138                                 break;
139                         case MSG_UPDATE_AGE:
140                                 AltosDebug.debug("MSG_UPDATE_AGE");
141                                 ad.update_age();
142                                 break;
143                         }
144                 }
145         };
146
147
148         private ServiceConnection mConnection = new ServiceConnection() {
149                 public void onServiceConnected(ComponentName className, IBinder service) {
150                         mService = new Messenger(service);
151                         try {
152                                 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
153                                 msg.replyTo = mMessenger;
154                                 mService.send(msg);
155                         } catch (RemoteException e) {
156                                 // In this case the service has crashed before we could even do anything with it
157                         }
158                         if (pending_usb_device != null) {
159                                 try {
160                                         mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, pending_usb_device));
161                                         pending_usb_device = null;
162                                 } catch (RemoteException e) {
163                                 }
164                         }
165                 }
166
167                 public void onServiceDisconnected(ComponentName className) {
168                         // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
169                         mService = null;
170                 }
171         };
172
173         void doBindService() {
174                 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
175                 mIsBound = true;
176         }
177
178         void doUnbindService() {
179                 if (mIsBound) {
180                         // If we have received the service, and hence registered with it, then now is the time to unregister.
181                         if (mService != null) {
182                                 try {
183                                         Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
184                                         msg.replyTo = mMessenger;
185                                         mService.send(msg);
186                                 } catch (RemoteException e) {
187                                         // There is nothing special we need to do if the service has crashed.
188                                 }
189                         }
190                         // Detach our existing connection.
191                         unbindService(mConnection);
192                         mIsBound = false;
193                 }
194         }
195
196         public void registerTab(AltosDroidTab mTab) {
197                 mTabs.add(mTab);
198         }
199
200         public void unregisterTab(AltosDroidTab mTab) {
201                 mTabs.remove(mTab);
202         }
203
204         public void units_changed(boolean imperial_units) {
205                 for (AltosDroidTab mTab : mTabs)
206                         mTab.units_changed(imperial_units);
207         }
208
209         void update_title(TelemetryState telemetry_state) {
210                 switch (telemetry_state.connect) {
211                 case TelemetryState.CONNECT_CONNECTED:
212                         if (telemetry_state.config != null) {
213                                 String str = String.format("S/N %d %6.3f MHz", telemetry_state.config.serial,
214                                                            telemetry_state.frequency);
215                                 if (telemetry_state.telemetry_rate != AltosLib.ao_telemetry_rate_38400)
216                                         str = str.concat(String.format(" %d bps",
217                                                                        AltosLib.ao_telemetry_rate_values[telemetry_state.telemetry_rate]));
218                                 setTitle(str);
219                         } else {
220                                 setTitle(R.string.title_connected_to);
221                         }
222                         break;
223                 case TelemetryState.CONNECT_CONNECTING:
224                         if (telemetry_state.address != null)
225                                 setTitle(String.format("Connecting to %s...", telemetry_state.address.name));
226                         else
227                                 setTitle("Connecting to something...");
228                         break;
229                 case TelemetryState.CONNECT_DISCONNECTED:
230                 case TelemetryState.CONNECT_NONE:
231                         setTitle(R.string.title_not_connected);
232                         break;
233                 }
234         }
235
236         void start_timer() {
237                 if (timer == null) {
238                         timer = new Timer();
239                         timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 1000L, 1000L);
240                 }
241         }
242
243         void stop_timer() {
244                 if (timer != null) {
245                         timer.cancel();
246                         timer.purge();
247                         timer = null;
248                 }
249         }
250
251         int     current_serial;
252         long    switch_time;
253
254         void set_switch_time() {
255                 switch_time = System.currentTimeMillis();
256         }
257
258         boolean registered_units_listener;
259
260         void update_state(TelemetryState new_telemetry_state) {
261
262                 if (new_telemetry_state != null)
263                         telemetry_state = new_telemetry_state;
264
265                 if (current_serial == 0)
266                         current_serial = telemetry_state.latest_serial;
267
268                 if (!registered_units_listener) {
269                         registered_units_listener = true;
270                         AltosPreferences.register_units_listener(this);
271                 }
272
273                 serials = telemetry_state.states.keySet().toArray(new Integer[0]);
274
275                 update_title(telemetry_state);
276
277                 AltosState      state = null;
278                 boolean         aged = true;
279
280                 if (telemetry_state.states.containsKey(current_serial)) {
281                         state = telemetry_state.states.get(current_serial);
282                         int age = state_age(state);
283                         if (age < 20)
284                                 aged = false;
285                         if (switch_time != 0 && (switch_time - state.received_time) > 0)
286                                 aged = true;
287                 }
288
289                 if (aged) {
290                         AltosState      newest_state = null;
291                         int             newest_age = 0;
292
293                         for (int serial : telemetry_state.states.keySet()) {
294                                 AltosState      existing = telemetry_state.states.get(serial);
295                                 int             existing_age = state_age(existing);
296
297                                 if (newest_state == null || existing_age < newest_age) {
298                                         newest_state = existing;
299                                         newest_age = existing_age;
300                                 }
301                         }
302
303                         if (newest_state != null)
304                                 state = newest_state;
305                 }
306
307                 update_ui(telemetry_state, state, telemetry_state.location);
308
309                 start_timer();
310         }
311
312         boolean same_string(String a, String b) {
313                 if (a == null) {
314                         if (b == null)
315                                 return true;
316                         return false;
317                 } else {
318                         if (b == null)
319                                 return false;
320                         return a.equals(b);
321                 }
322         }
323
324
325         private int blend_component(int a, int b, double r, int shift, int mask) {
326                 return ((int) (((a >> shift) & mask) * r + ((b >> shift) & mask) * (1 - r)) & mask) << shift;
327         }
328         private int blend_color(int a, int b, double r) {
329                 return (blend_component(a, b, r, 0, 0xff) |
330                         blend_component(a, b, r, 8, 0xff) |
331                         blend_component(a, b, r, 16, 0xff) |
332                         blend_component(a, b, r, 24, 0xff));
333         }
334
335         int state_age(AltosState state) {
336                 return (int) ((System.currentTimeMillis() - state.received_time + 500) / 1000);
337         }
338
339         void set_screen_on(int age) {
340                 if (age < 60)
341                         getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
342                 else
343                         getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
344         }
345
346         void update_age() {
347                 if (saved_state != null) {
348                         int age = state_age(saved_state);
349
350                         double age_scale = age / 100.0;
351
352                         if (age_scale > 1.0)
353                                 age_scale = 1.0;
354
355                         mAgeView.setTextColor(blend_color(mAgeOldColor, mAgeNewColor, age_scale));
356
357                         set_screen_on(age);
358
359                         String  text;
360                         if (age < 60)
361                                 text = String.format("%ds", age);
362                         else if (age < 60 * 60)
363                                 text = String.format("%dm", age / 60);
364                         else if (age < 60 * 60 * 24)
365                                 text = String.format("%dh", age / (60 * 60));
366                         else
367                                 text = String.format("%dd", age / (24 * 60 * 60));
368                         mAgeView.setText(text);
369                 }
370         }
371
372         void update_ui(TelemetryState telem_state, AltosState state, Location location) {
373
374                 int prev_state = AltosLib.ao_flight_invalid;
375
376                 AltosGreatCircle from_receiver = null;
377
378                 if (saved_state != null)
379                         prev_state = saved_state.state;
380
381                 if (state != null) {
382                         set_screen_on(state_age(state));
383
384                         if (state.state == AltosLib.ao_flight_stateless) {
385                                 boolean prev_locked = false;
386                                 boolean locked = false;
387
388                                 if(state.gps != null)
389                                         locked = state.gps.locked;
390                                 if (saved_state != null && saved_state.gps != null)
391                                         prev_locked = saved_state.gps.locked;
392                                 if (prev_locked != locked) {
393                                         String currentTab = mTabHost.getCurrentTabTag();
394                                         if (locked) {
395                                                 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("descent");
396                                         } else {
397                                                 if (currentTab.equals("descent")) mTabHost.setCurrentTabByTag("pad");
398                                         }
399                                 }
400                         } else {
401                                 if (prev_state != state.state) {
402                                         String currentTab = mTabHost.getCurrentTabTag();
403                                         switch (state.state) {
404                                         case AltosLib.ao_flight_boost:
405                                                 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("ascent");
406                                                 break;
407                                         case AltosLib.ao_flight_drogue:
408                                                 if (currentTab.equals("ascent")) mTabHost.setCurrentTabByTag("descent");
409                                                 break;
410                                         case AltosLib.ao_flight_landed:
411                                                 if (currentTab.equals("descent")) mTabHost.setCurrentTabByTag("landed");
412                                                 break;
413                                         case AltosLib.ao_flight_stateless:
414                                                 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("descent");
415                                                 break;
416                                         }
417                                 }
418                         }
419
420                         if (location != null && state.gps != null && state.gps.locked) {
421                                 double altitude = 0;
422                                 if (location.hasAltitude())
423                                         altitude = location.getAltitude();
424                                 from_receiver = new AltosGreatCircle(location.getLatitude(),
425                                                                      location.getLongitude(),
426                                                                      altitude,
427                                                                      state.gps.lat,
428                                                                      state.gps.lon,
429                                                                      state.gps.alt);
430                         }
431
432                         if (saved_state == null || !same_string(saved_state.callsign, state.callsign)) {
433                                 mCallsignView.setText(state.callsign);
434                         }
435                         if (saved_state == null || state.serial != saved_state.serial) {
436                                 mSerialView.setText(String.format("%d", state.serial));
437                         }
438                         if (saved_state == null || state.flight != saved_state.flight) {
439                                 if (state.flight == AltosLib.MISSING)
440                                         mFlightView.setText("");
441                                 else
442                                         mFlightView.setText(String.format("%d", state.flight));
443                         }
444                         if (saved_state == null || state.state != saved_state.state) {
445                                 if (state.state == AltosLib.ao_flight_stateless) {
446                                         mStateLayout.setVisibility(View.GONE);
447                                 } else {
448                                         mStateView.setText(state.state_name());
449                                         mStateLayout.setVisibility(View.VISIBLE);
450                                 }
451                         }
452                         if (saved_state == null || state.rssi != saved_state.rssi) {
453                                 mRSSIView.setText(String.format("%d", state.rssi));
454                         }
455                 }
456
457                 for (AltosDroidTab mTab : mTabs)
458                         mTab.update_ui(telem_state, state, from_receiver, location, mTab == mTabsAdapter.currentItem());
459
460                 if (state != null && mAltosVoice != null)
461                         mAltosVoice.tell(state, from_receiver);
462
463                 saved_state = state;
464         }
465
466         private void onTimerTick() {
467                 try {
468                         mMessenger.send(Message.obtain(null, MSG_UPDATE_AGE));
469                 } catch (RemoteException e) {
470                 }
471         }
472
473         static String pos(double p, String pos, String neg) {
474                 String  h = pos;
475                 if (p == AltosLib.MISSING)
476                         return "";
477                 if (p < 0) {
478                         h = neg;
479                         p = -p;
480                 }
481                 int deg = (int) Math.floor(p);
482                 double min = (p - Math.floor(p)) * 60.0;
483                 return String.format("%d°%9.4f\" %s", deg, min, h);
484         }
485
486         static String number(String format, double value) {
487                 if (value == AltosLib.MISSING)
488                         return "";
489                 return String.format(format, value);
490         }
491
492         static String integer(String format, int value) {
493                 if (value == AltosLib.MISSING)
494                         return "";
495                 return String.format(format, value);
496         }
497
498         private View create_tab_view(String label) {
499                 LayoutInflater inflater = (LayoutInflater) this.getLayoutInflater();
500                 View tab_view = inflater.inflate(R.layout.tab_layout, null);
501                 TextView text_view = (TextView) tab_view.findViewById (R.id.tabLabel);
502                 text_view.setText(label);
503                 return tab_view;
504         }
505
506         public void set_map_source(int source) {
507                 for (AltosDroidTab mTab : mTabs)
508                         mTab.set_map_source(source);
509         }
510
511         @Override
512         public void onCreate(Bundle savedInstanceState) {
513                 super.onCreate(savedInstanceState);
514                 AltosDebug.init(this);
515                 AltosDebug.debug("+++ ON CREATE +++");
516
517                 // Initialise preferences
518                 AltosDroidPreferences.init(this);
519
520                 fm = getSupportFragmentManager();
521
522                 // Set up the window layout
523                 setContentView(R.layout.altosdroid);
524
525                 // Create the Tabs and ViewPager
526                 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
527                 mTabHost.setup();
528
529                 mViewPager = (AltosViewPager)findViewById(R.id.pager);
530                 mViewPager.setOffscreenPageLimit(4);
531
532                 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
533
534                 mTabsAdapter.addTab(mTabHost.newTabSpec("pad").setIndicator(create_tab_view("Pad")), TabPad.class, null);
535                 mTabsAdapter.addTab(mTabHost.newTabSpec("ascent").setIndicator(create_tab_view("Ascent")), TabAscent.class, null);
536                 mTabsAdapter.addTab(mTabHost.newTabSpec("descent").setIndicator(create_tab_view("Descent")), TabDescent.class, null);
537                 mTabsAdapter.addTab(mTabHost.newTabSpec("landed").setIndicator(create_tab_view("Landed")), TabLanded.class, null);
538                 mTabsAdapter.addTab(mTabHost.newTabSpec("map").setIndicator(create_tab_view("Map")), TabMap.class, null);
539
540                 // Display the Version
541                 mVersion = (TextView) findViewById(R.id.version);
542                 mVersion.setText("Version: " + BuildInfo.version +
543                                  "  Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
544                                  "  (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
545
546                 mCallsignView  = (TextView) findViewById(R.id.callsign_value);
547                 mRSSIView      = (TextView) findViewById(R.id.rssi_value);
548                 mSerialView    = (TextView) findViewById(R.id.serial_value);
549                 mFlightView    = (TextView) findViewById(R.id.flight_value);
550                 mStateLayout   = (RelativeLayout) findViewById(R.id.state_container);
551                 mStateView     = (TextView) findViewById(R.id.state_value);
552                 mAgeView       = (TextView) findViewById(R.id.age_value);
553                 mAgeNewColor   = mAgeView.getTextColors().getDefaultColor();
554                 mAgeOldColor   = getResources().getColor(R.color.old_color);
555         }
556
557         private boolean ensureBluetooth() {
558                 // Get local Bluetooth adapter
559                 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
560
561                 // If the adapter is null, then Bluetooth is not supported
562                 if (mBluetoothAdapter == null) {
563                         Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
564                         return false;
565                 }
566
567                 if (!mBluetoothAdapter.isEnabled()) {
568                         Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
569                         startActivityForResult(enableIntent, AltosDroid.REQUEST_ENABLE_BT);
570                 }
571
572                 return true;
573         }
574
575         private boolean check_usb() {
576                 UsbDevice       device = AltosUsb.find_device(this, AltosLib.product_basestation);
577
578                 if (device != null) {
579                         Intent          i = new Intent(this, AltosDroid.class);
580                         PendingIntent   pi = PendingIntent.getActivity(this, 0, new Intent("hello world", null, this, AltosDroid.class), 0);
581
582                         if (AltosUsb.request_permission(this, device, pi)) {
583                                 connectUsb(device);
584                         }
585                         start_with_usb = true;
586                         return true;
587                 }
588
589                 start_with_usb = false;
590
591                 return false;
592         }
593
594         private void noticeIntent(Intent intent) {
595
596                 /* Ok, this is pretty convenient.
597                  *
598                  * When a USB device is plugged in, and our 'hotplug'
599                  * intent registration fires, we get an Intent with
600                  * EXTRA_DEVICE set.
601                  *
602                  * When we start up and see a usb device and request
603                  * permission to access it, that queues a
604                  * PendingIntent, which has the EXTRA_DEVICE added in,
605                  * along with the EXTRA_PERMISSION_GRANTED field as
606                  * well.
607                  *
608                  * So, in both cases, we get the device name using the
609                  * same call. We check to see if access was granted,
610                  * in which case we ignore the device field and do our
611                  * usual startup thing.
612                  */
613
614                 UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
615                 boolean granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, true);
616
617                 AltosDebug.debug("intent %s device %s granted %s", intent, device, granted);
618
619                 if (!granted)
620                         device = null;
621
622                 if (device != null) {
623                         AltosDebug.debug("intent has usb device " + device.toString());
624                         connectUsb(device);
625                 } else {
626
627                         /* 'granted' is only false if this intent came
628                          * from the request_permission call and
629                          * permission was denied. In which case, we
630                          * don't want to loop forever...
631                          */
632                         if (granted) {
633                                 AltosDebug.debug("check for a USB device at startup");
634                                 if (check_usb())
635                                         return;
636                         }
637                         AltosDebug.debug("Starting by looking for bluetooth devices");
638                         if (ensureBluetooth())
639                                 return;
640                         finish();
641                 }
642         }
643
644         @Override
645         public void onStart() {
646                 super.onStart();
647                 AltosDebug.debug("++ ON START ++");
648
649                 noticeIntent(getIntent());
650
651                 // Start Telemetry Service
652                 String  action = start_with_usb ? ACTION_USB : ACTION_BLUETOOTH;
653
654                 startService(new Intent(action, null, AltosDroid.this, TelemetryService.class));
655
656                 doBindService();
657
658                 if (mAltosVoice == null)
659                         mAltosVoice = new AltosVoice(this);
660
661         }
662
663         @Override
664         public void onNewIntent(Intent intent) {
665                 super.onNewIntent(intent);
666                 AltosDebug.debug("onNewIntent");
667                 noticeIntent(intent);
668         }
669
670         @Override
671         public void onResume() {
672                 super.onResume();
673                 AltosDebug.debug("+ ON RESUME +");
674         }
675
676         @Override
677         public void onPause() {
678                 super.onPause();
679                 AltosDebug.debug("- ON PAUSE -");
680         }
681
682         @Override
683         public void onStop() {
684                 super.onStop();
685                 AltosDebug.debug("-- ON STOP --");
686
687                 doUnbindService();
688                 if (mAltosVoice != null) {
689                         mAltosVoice.stop();
690                         mAltosVoice = null;
691                 }
692         }
693
694         @Override
695         public void onDestroy() {
696                 super.onDestroy();
697                 AltosDebug.debug("--- ON DESTROY ---");
698
699                 if (mAltosVoice != null) mAltosVoice.stop();
700                 stop_timer();
701         }
702
703         protected void onActivityResult(int requestCode, int resultCode, Intent data) {
704                 AltosDebug.debug("onActivityResult " + resultCode);
705                 switch (requestCode) {
706                 case REQUEST_CONNECT_DEVICE:
707                         // When DeviceListActivity returns with a device to connect to
708                         if (resultCode == Activity.RESULT_OK) {
709                                 connectDevice(data);
710                         }
711                         break;
712                 case REQUEST_ENABLE_BT:
713                         // When the request to enable Bluetooth returns
714                         if (resultCode == Activity.RESULT_OK) {
715                                 // Bluetooth is now enabled, so set up a chat session
716                                 //setupChat();
717                         } else {
718                                 // User did not enable Bluetooth or an error occured
719                                 AltosDebug.error("BT not enabled");
720                                 stopService(new Intent(AltosDroid.this, TelemetryService.class));
721                                 Toast.makeText(this, R.string.bt_not_enabled, Toast.LENGTH_SHORT).show();
722                                 finish();
723                         }
724                         break;
725                 case REQUEST_MAP_TYPE:
726                         if (resultCode == Activity.RESULT_OK)
727                                 set_map_type(data);
728                         break;
729                 }
730         }
731
732         private void connectUsb(UsbDevice device) {
733                 if (mService == null)
734                         pending_usb_device = device;
735                 else {
736                         // Attempt to connect to the device
737                         try {
738                                 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, device));
739                                 AltosDebug.debug("Sent OPEN_USB message");
740                         } catch (RemoteException e) {
741                                 AltosDebug.debug("connect device message failed");
742                         }
743                 }
744         }
745
746         private void connectDevice(Intent data) {
747                 // Attempt to connect to the device
748                 try {
749                         String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
750                         String name = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_NAME);
751
752                         AltosDebug.debug("Connecting to " + address + " " + name);
753                         DeviceAddress   a = new DeviceAddress(address, name);
754                         mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, a));
755                         AltosDebug.debug("Sent connecting message");
756                 } catch (RemoteException e) {
757                         AltosDebug.debug("connect device message failed");
758                 }
759         }
760
761         private void disconnectDevice() {
762                 try {
763                         mService.send(Message.obtain(null, TelemetryService.MSG_DISCONNECT, null));
764                 } catch (RemoteException e) {
765                 }
766         }
767
768         private void set_map_type(Intent data) {
769                 int type = data.getIntExtra(MapTypeActivity.EXTRA_MAP_TYPE, -1);
770
771                 AltosDebug.debug("intent set_map_type %d\n", type);
772                 if (type != -1) {
773                         map_type = type;
774                         for (AltosDroidTab mTab : mTabs)
775                                 mTab.set_map_type(map_type);
776                 }
777         }
778
779         @Override
780         public boolean onCreateOptionsMenu(Menu menu) {
781                 MenuInflater inflater = getMenuInflater();
782                 inflater.inflate(R.menu.option_menu, menu);
783                 return true;
784         }
785
786         void setFrequency(double freq) {
787                 try {
788                         mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
789                         set_switch_time();
790                 } catch (RemoteException e) {
791                 }
792         }
793
794         void setFrequency(String freq) {
795                 try {
796                         setFrequency (AltosParse.parse_double_net(freq.substring(11, 17)));
797                 } catch (ParseException e) {
798                 }
799         }
800
801         void setBaud(int baud) {
802                 try {
803                         mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD, baud));
804                         set_switch_time();
805                 } catch (RemoteException e) {
806                 }
807         }
808
809         void setBaud(String baud) {
810                 try {
811                         int     value = Integer.parseInt(baud);
812                         int     rate = AltosLib.ao_telemetry_rate_38400;
813                         switch (value) {
814                         case 2400:
815                                 rate = AltosLib.ao_telemetry_rate_2400;
816                                 break;
817                         case 9600:
818                                 rate = AltosLib.ao_telemetry_rate_9600;
819                                 break;
820                         case 38400:
821                                 rate = AltosLib.ao_telemetry_rate_38400;
822                                 break;
823                         }
824                         setBaud(rate);
825                 } catch (NumberFormatException e) {
826                 }
827         }
828
829         void select_tracker(int serial) {
830                 int i;
831                 for (i = 0; i < serials.length; i++)
832                         if (serials[i] == serial)
833                                 break;
834                 if (i == serials.length)
835                         return;
836
837                 current_serial = serial;
838                 update_state(null);
839         }
840
841         void delete_track(int serial) {
842                 try {
843                         mService.send(Message.obtain(null, TelemetryService.MSG_DELETE_SERIAL, (Integer) serial));
844                 } catch (Exception ex) {
845                 }
846         }
847
848         @Override
849         public boolean onOptionsItemSelected(MenuItem item) {
850                 Intent serverIntent = null;
851                 switch (item.getItemId()) {
852                 case R.id.connect_scan:
853                         if (ensureBluetooth()) {
854                                 // Launch the DeviceListActivity to see devices and do scan
855                                 serverIntent = new Intent(this, DeviceListActivity.class);
856                                 startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
857                         }
858                         return true;
859                 case R.id.disconnect:
860                         /* Disconnect the device
861                          */
862                         disconnectDevice();
863                         return true;
864                 case R.id.quit:
865                         AltosDebug.debug("R.id.quit");
866                         disconnectDevice();
867                         finish();
868                         return true;
869                 case R.id.select_freq:
870                         // Set the TBT radio frequency
871
872                         final String[] frequencies = {
873                                 "Channel 0 (434.550MHz)",
874                                 "Channel 1 (434.650MHz)",
875                                 "Channel 2 (434.750MHz)",
876                                 "Channel 3 (434.850MHz)",
877                                 "Channel 4 (434.950MHz)",
878                                 "Channel 5 (435.050MHz)",
879                                 "Channel 6 (435.150MHz)",
880                                 "Channel 7 (435.250MHz)",
881                                 "Channel 8 (435.350MHz)",
882                                 "Channel 9 (435.450MHz)"
883                         };
884
885                         AlertDialog.Builder builder_freq = new AlertDialog.Builder(this);
886                         builder_freq.setTitle("Pick a frequency");
887                         builder_freq.setItems(frequencies,
888                                          new DialogInterface.OnClickListener() {
889                                                  public void onClick(DialogInterface dialog, int item) {
890                                                          setFrequency(frequencies[item]);
891                                                  }
892                                          });
893                         AlertDialog alert_freq = builder_freq.create();
894                         alert_freq.show();
895                         return true;
896                 case R.id.select_rate:
897                         // Set the TBT baud rate
898
899                         final String[] rates = {
900                                 "38400",
901                                 "9600",
902                                 "2400",
903                         };
904
905                         AlertDialog.Builder builder_rate = new AlertDialog.Builder(this);
906                         builder_rate.setTitle("Pick a baud rate");
907                         builder_rate.setItems(rates,
908                                          new DialogInterface.OnClickListener() {
909                                                  public void onClick(DialogInterface dialog, int item) {
910                                                          setBaud(rates[item]);
911                                                  }
912                                          });
913                         AlertDialog alert_rate = builder_rate.create();
914                         alert_rate.show();
915                         return true;
916                 case R.id.change_units:
917                         boolean imperial = AltosPreferences.imperial_units();
918                         AltosPreferences.set_imperial_units(!imperial);
919                         return true;
920                 case R.id.preload_maps:
921                         serverIntent = new Intent(this, PreloadMapActivity.class);
922                         startActivityForResult(serverIntent, REQUEST_PRELOAD_MAPS);
923                         return true;
924                 case R.id.map_type:
925                         serverIntent = new Intent(this, MapTypeActivity.class);
926                         startActivityForResult(serverIntent, REQUEST_MAP_TYPE);
927                         return true;
928                 case R.id.map_source:
929                         int source = AltosDroidPreferences.map_source();
930                         int new_source = source == AltosDroidPreferences.MAP_SOURCE_ONLINE ? AltosDroidPreferences.MAP_SOURCE_OFFLINE : AltosDroidPreferences.MAP_SOURCE_ONLINE;
931                         AltosDroidPreferences.set_map_source(new_source);
932                         set_map_source(new_source);
933                         return true;
934                 case R.id.select_tracker:
935                         if (serials != null) {
936                                 String[] trackers = new String[serials.length];
937                                 for (int i = 0; i < serials.length; i++)
938                                         trackers[i] = String.format("%d", serials[i]);
939                                 AlertDialog.Builder builder_serial = new AlertDialog.Builder(this);
940                                 builder_serial.setTitle("Select a tracker");
941                                 builder_serial.setItems(trackers,
942                                                         new DialogInterface.OnClickListener() {
943                                                                 public void onClick(DialogInterface dialog, int item) {
944                                                                         select_tracker(serials[item]);
945                                                                 }
946                                                         });
947                                 AlertDialog alert_serial = builder_serial.create();
948                                 alert_serial.show();
949
950                         }
951                         return true;
952                 case R.id.delete_track:
953                         if (serials != null) {
954                                 String[] trackers = new String[serials.length];
955                                 for (int i = 0; i < serials.length; i++)
956                                         trackers[i] = String.format("%d", serials[i]);
957                                 AlertDialog.Builder builder_serial = new AlertDialog.Builder(this);
958                                 builder_serial.setTitle("Delete a track");
959                                 builder_serial.setItems(trackers,
960                                                         new DialogInterface.OnClickListener() {
961                                                                 public void onClick(DialogInterface dialog, int item) {
962                                                                         delete_track(serials[item]);
963                                                                 }
964                                                         });
965                                 AlertDialog alert_serial = builder_serial.create();
966                                 alert_serial.show();
967
968                         }
969                         return true;
970                 }
971                 return false;
972         }
973 }