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