altosdroid: Add multi-tracker support
[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         boolean registered_units_listener;
252
253         int     current_serial;
254
255         void update_state(TelemetryState new_telemetry_state) {
256
257                 if (new_telemetry_state != null)
258                         telemetry_state = new_telemetry_state;
259
260                 if (current_serial == 0)
261                         current_serial = telemetry_state.latest_serial;
262
263                 if (!registered_units_listener) {
264                         registered_units_listener = true;
265                         AltosPreferences.register_units_listener(this);
266                 }
267
268                 serials = telemetry_state.states.keySet().toArray(new Integer[0]);
269
270                 update_title(telemetry_state);
271
272                 AltosDebug.debug("update state current serial %d\n", current_serial);
273
274                 AltosState      state = null;
275                 if (telemetry_state.states.containsKey(current_serial))
276                         state = telemetry_state.states.get(current_serial);
277
278                 update_ui(telemetry_state, state, telemetry_state.location);
279
280                 start_timer();
281         }
282
283         boolean same_string(String a, String b) {
284                 if (a == null) {
285                         if (b == null)
286                                 return true;
287                         return false;
288                 } else {
289                         if (b == null)
290                                 return false;
291                         return a.equals(b);
292                 }
293         }
294
295
296         private int blend_component(int a, int b, double r, int shift, int mask) {
297                 return ((int) (((a >> shift) & mask) * r + ((b >> shift) & mask) * (1 - r)) & mask) << shift;
298         }
299         private int blend_color(int a, int b, double r) {
300                 return (blend_component(a, b, r, 0, 0xff) |
301                         blend_component(a, b, r, 8, 0xff) |
302                         blend_component(a, b, r, 16, 0xff) |
303                         blend_component(a, b, r, 24, 0xff));
304         }
305
306         int state_age(AltosState state) {
307                 return (int) ((System.currentTimeMillis() - state.received_time + 500) / 1000);
308         }
309
310         void set_screen_on(int age) {
311                 if (age < 60)
312                         getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
313                 else
314                         getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
315         }
316
317         void update_age() {
318                 if (saved_state != null) {
319                         int age = state_age(saved_state);
320
321                         double age_scale = age / 100.0;
322
323                         if (age_scale > 1.0)
324                                 age_scale = 1.0;
325
326                         mAgeView.setTextColor(blend_color(mAgeOldColor, mAgeNewColor, age_scale));
327
328                         set_screen_on(age);
329
330                         String  text;
331                         if (age < 60)
332                                 text = String.format("%ds", age);
333                         else if (age < 60 * 60)
334                                 text = String.format("%dm", age / 60);
335                         else if (age < 60 * 60 * 24)
336                                 text = String.format("%dh", age / (60 * 60));
337                         else
338                                 text = String.format("%dd", age / (24 * 60 * 60));
339                         mAgeView.setText(text);
340                 }
341         }
342
343         void update_ui(TelemetryState telem_state, AltosState state, Location location) {
344
345                 int prev_state = AltosLib.ao_flight_invalid;
346
347                 AltosGreatCircle from_receiver = null;
348
349                 if (saved_state != null)
350                         prev_state = saved_state.state;
351
352                 if (state != null) {
353                         set_screen_on(state_age(state));
354
355                         if (state.state == AltosLib.ao_flight_stateless) {
356                                 boolean prev_locked = false;
357                                 boolean locked = false;
358
359                                 if(state.gps != null)
360                                         locked = state.gps.locked;
361                                 if (saved_state != null && saved_state.gps != null)
362                                         prev_locked = saved_state.gps.locked;
363                                 if (prev_locked != locked) {
364                                         String currentTab = mTabHost.getCurrentTabTag();
365                                         if (locked) {
366                                                 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("descent");
367                                         } else {
368                                                 if (currentTab.equals("descent")) mTabHost.setCurrentTabByTag("pad");
369                                         }
370                                 }
371                         } else {
372                                 if (prev_state != state.state) {
373                                         String currentTab = mTabHost.getCurrentTabTag();
374                                         switch (state.state) {
375                                         case AltosLib.ao_flight_boost:
376                                                 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("ascent");
377                                                 break;
378                                         case AltosLib.ao_flight_drogue:
379                                                 if (currentTab.equals("ascent")) mTabHost.setCurrentTabByTag("descent");
380                                                 break;
381                                         case AltosLib.ao_flight_landed:
382                                                 if (currentTab.equals("descent")) mTabHost.setCurrentTabByTag("landed");
383                                                 break;
384                                         case AltosLib.ao_flight_stateless:
385                                                 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("descent");
386                                                 break;
387                                         }
388                                 }
389                         }
390
391                         if (location != null && state.gps != null && state.gps.locked) {
392                                 double altitude = 0;
393                                 if (location.hasAltitude())
394                                         altitude = location.getAltitude();
395                                 from_receiver = new AltosGreatCircle(location.getLatitude(),
396                                                                      location.getLongitude(),
397                                                                      altitude,
398                                                                      state.gps.lat,
399                                                                      state.gps.lon,
400                                                                      state.gps.alt);
401                         }
402
403                         if (saved_state == null || !same_string(saved_state.callsign, state.callsign)) {
404                                 mCallsignView.setText(state.callsign);
405                         }
406                         if (saved_state == null || state.serial != saved_state.serial) {
407                                 mSerialView.setText(String.format("%d", state.serial));
408                         }
409                         if (saved_state == null || state.flight != saved_state.flight) {
410                                 if (state.flight == AltosLib.MISSING)
411                                         mFlightView.setText("");
412                                 else
413                                         mFlightView.setText(String.format("%d", state.flight));
414                         }
415                         if (saved_state == null || state.state != saved_state.state) {
416                                 if (state.state == AltosLib.ao_flight_stateless) {
417                                         mStateLayout.setVisibility(View.GONE);
418                                 } else {
419                                         mStateView.setText(state.state_name());
420                                         mStateLayout.setVisibility(View.VISIBLE);
421                                 }
422                         }
423                         if (saved_state == null || state.rssi != saved_state.rssi) {
424                                 mRSSIView.setText(String.format("%d", state.rssi));
425                         }
426                 }
427
428                 for (AltosDroidTab mTab : mTabs)
429                         mTab.update_ui(telem_state, state, from_receiver, location, mTab == mTabsAdapter.currentItem());
430
431                 if (state != null && mAltosVoice != null)
432                         mAltosVoice.tell(state, from_receiver);
433
434                 saved_state = state;
435         }
436
437         private void onTimerTick() {
438                 try {
439                         mMessenger.send(Message.obtain(null, MSG_UPDATE_AGE));
440                 } catch (RemoteException e) {
441                 }
442         }
443
444         static String pos(double p, String pos, String neg) {
445                 String  h = pos;
446                 if (p == AltosLib.MISSING)
447                         return "";
448                 if (p < 0) {
449                         h = neg;
450                         p = -p;
451                 }
452                 int deg = (int) Math.floor(p);
453                 double min = (p - Math.floor(p)) * 60.0;
454                 return String.format("%d°%9.4f\" %s", deg, min, h);
455         }
456
457         static String number(String format, double value) {
458                 if (value == AltosLib.MISSING)
459                         return "";
460                 return String.format(format, value);
461         }
462
463         static String integer(String format, int value) {
464                 if (value == AltosLib.MISSING)
465                         return "";
466                 return String.format(format, value);
467         }
468
469         private View create_tab_view(String label) {
470                 LayoutInflater inflater = (LayoutInflater) this.getLayoutInflater();
471                 View tab_view = inflater.inflate(R.layout.tab_layout, null);
472                 TextView text_view = (TextView) tab_view.findViewById (R.id.tabLabel);
473                 text_view.setText(label);
474                 return tab_view;
475         }
476
477         @Override
478         public void onCreate(Bundle savedInstanceState) {
479                 super.onCreate(savedInstanceState);
480                 AltosDebug.init(this);
481                 AltosDebug.debug("+++ ON CREATE +++");
482
483                 fm = getSupportFragmentManager();
484
485                 // Set up the window layout
486                 setContentView(R.layout.altosdroid);
487
488                 // Create the Tabs and ViewPager
489                 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
490                 mTabHost.setup();
491
492                 mViewPager = (AltosViewPager)findViewById(R.id.pager);
493                 mViewPager.setOffscreenPageLimit(4);
494
495                 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
496
497                 mTabsAdapter.addTab(mTabHost.newTabSpec("pad").setIndicator(create_tab_view("Pad")), TabPad.class, null);
498                 mTabsAdapter.addTab(mTabHost.newTabSpec("ascent").setIndicator(create_tab_view("Ascent")), TabAscent.class, null);
499                 mTabsAdapter.addTab(mTabHost.newTabSpec("descent").setIndicator(create_tab_view("Descent")), TabDescent.class, null);
500                 mTabsAdapter.addTab(mTabHost.newTabSpec("landed").setIndicator(create_tab_view("Landed")), TabLanded.class, null);
501                 mTabsAdapter.addTab(mTabHost.newTabSpec("map").setIndicator(create_tab_view("Map")), TabMap.class, null);
502                 mTabsAdapter.addTab(mTabHost.newTabSpec("offmap").setIndicator(create_tab_view("OffMap")), TabMapOffline.class, null);
503
504                 // Display the Version
505                 mVersion = (TextView) findViewById(R.id.version);
506                 mVersion.setText("Version: " + BuildInfo.version +
507                                  "  Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
508                                  "  (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
509
510                 mCallsignView  = (TextView) findViewById(R.id.callsign_value);
511                 mRSSIView      = (TextView) findViewById(R.id.rssi_value);
512                 mSerialView    = (TextView) findViewById(R.id.serial_value);
513                 mFlightView    = (TextView) findViewById(R.id.flight_value);
514                 mStateLayout   = (RelativeLayout) findViewById(R.id.state_container);
515                 mStateView     = (TextView) findViewById(R.id.state_value);
516                 mAgeView       = (TextView) findViewById(R.id.age_value);
517                 mAgeNewColor   = mAgeView.getTextColors().getDefaultColor();
518                 mAgeOldColor   = getResources().getColor(R.color.old_color);
519         }
520
521         private boolean ensureBluetooth() {
522                 // Get local Bluetooth adapter
523                 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
524
525                 // If the adapter is null, then Bluetooth is not supported
526                 if (mBluetoothAdapter == null) {
527                         Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
528                         return false;
529                 }
530
531                 if (!mBluetoothAdapter.isEnabled()) {
532                         Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
533                         startActivityForResult(enableIntent, AltosDroid.REQUEST_ENABLE_BT);
534                 }
535
536                 return true;
537         }
538
539         private boolean check_usb() {
540                 UsbDevice       device = AltosUsb.find_device(this, AltosLib.product_basestation);
541
542                 if (device != null) {
543                         Intent          i = new Intent(this, AltosDroid.class);
544                         PendingIntent   pi = PendingIntent.getActivity(this, 0, new Intent("hello world", null, this, AltosDroid.class), 0);
545
546                         if (AltosUsb.request_permission(this, device, pi)) {
547                                 connectUsb(device);
548                         }
549                         start_with_usb = true;
550                         return true;
551                 }
552
553                 start_with_usb = false;
554
555                 return false;
556         }
557
558         private void noticeIntent(Intent intent) {
559
560                 /* Ok, this is pretty convenient.
561                  *
562                  * When a USB device is plugged in, and our 'hotplug'
563                  * intent registration fires, we get an Intent with
564                  * EXTRA_DEVICE set.
565                  *
566                  * When we start up and see a usb device and request
567                  * permission to access it, that queues a
568                  * PendingIntent, which has the EXTRA_DEVICE added in,
569                  * along with the EXTRA_PERMISSION_GRANTED field as
570                  * well.
571                  *
572                  * So, in both cases, we get the device name using the
573                  * same call. We check to see if access was granted,
574                  * in which case we ignore the device field and do our
575                  * usual startup thing.
576                  */
577
578                 UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
579                 boolean granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, true);
580
581                 AltosDebug.debug("intent %s device %s granted %s", intent, device, granted);
582
583                 if (!granted)
584                         device = null;
585
586                 if (device != null) {
587                         AltosDebug.debug("intent has usb device " + device.toString());
588                         connectUsb(device);
589                 } else {
590
591                         /* 'granted' is only false if this intent came
592                          * from the request_permission call and
593                          * permission was denied. In which case, we
594                          * don't want to loop forever...
595                          */
596                         if (granted) {
597                                 AltosDebug.debug("check for a USB device at startup");
598                                 if (check_usb())
599                                         return;
600                         }
601                         AltosDebug.debug("Starting by looking for bluetooth devices");
602                         if (ensureBluetooth())
603                                 return;
604                         finish();
605                 }
606         }
607
608         @Override
609         public void onStart() {
610                 super.onStart();
611                 AltosDebug.debug("++ ON START ++");
612
613                 noticeIntent(getIntent());
614
615                 // Start Telemetry Service
616                 String  action = start_with_usb ? ACTION_USB : ACTION_BLUETOOTH;
617
618                 startService(new Intent(action, null, AltosDroid.this, TelemetryService.class));
619
620                 doBindService();
621
622                 if (mAltosVoice == null)
623                         mAltosVoice = new AltosVoice(this);
624
625         }
626
627         @Override
628         public void onNewIntent(Intent intent) {
629                 super.onNewIntent(intent);
630                 AltosDebug.debug("onNewIntent");
631                 noticeIntent(intent);
632         }
633
634         @Override
635         public void onResume() {
636                 super.onResume();
637                 AltosDebug.debug("+ ON RESUME +");
638         }
639
640         @Override
641         public void onPause() {
642                 super.onPause();
643                 AltosDebug.debug("- ON PAUSE -");
644         }
645
646         @Override
647         public void onStop() {
648                 super.onStop();
649                 AltosDebug.debug("-- ON STOP --");
650
651                 doUnbindService();
652                 if (mAltosVoice != null) {
653                         mAltosVoice.stop();
654                         mAltosVoice = null;
655                 }
656         }
657
658         @Override
659         public void onDestroy() {
660                 super.onDestroy();
661                 AltosDebug.debug("--- ON DESTROY ---");
662
663                 if (mAltosVoice != null) mAltosVoice.stop();
664                 stop_timer();
665         }
666
667         protected void onActivityResult(int requestCode, int resultCode, Intent data) {
668                 AltosDebug.debug("onActivityResult " + resultCode);
669                 switch (requestCode) {
670                 case REQUEST_CONNECT_DEVICE:
671                         // When DeviceListActivity returns with a device to connect to
672                         if (resultCode == Activity.RESULT_OK) {
673                                 connectDevice(data);
674                         }
675                         break;
676                 case REQUEST_ENABLE_BT:
677                         // When the request to enable Bluetooth returns
678                         if (resultCode == Activity.RESULT_OK) {
679                                 // Bluetooth is now enabled, so set up a chat session
680                                 //setupChat();
681                         } else {
682                                 // User did not enable Bluetooth or an error occured
683                                 AltosDebug.error("BT not enabled");
684                                 stopService(new Intent(AltosDroid.this, TelemetryService.class));
685                                 Toast.makeText(this, R.string.bt_not_enabled, Toast.LENGTH_SHORT).show();
686                                 finish();
687                         }
688                         break;
689                 case REQUEST_MAP_TYPE:
690                         if (resultCode == Activity.RESULT_OK)
691                                 set_map_type(data);
692                         break;
693                 }
694         }
695
696         private void connectUsb(UsbDevice device) {
697                 if (mService == null)
698                         pending_usb_device = device;
699                 else {
700                         // Attempt to connect to the device
701                         try {
702                                 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, device));
703                                 AltosDebug.debug("Sent OPEN_USB message");
704                         } catch (RemoteException e) {
705                                 AltosDebug.debug("connect device message failed");
706                         }
707                 }
708         }
709
710         private void connectDevice(Intent data) {
711                 // Attempt to connect to the device
712                 try {
713                         String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
714                         String name = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_NAME);
715
716                         AltosDebug.debug("Connecting to " + address + " " + name);
717                         DeviceAddress   a = new DeviceAddress(address, name);
718                         mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, a));
719                         AltosDebug.debug("Sent connecting message");
720                 } catch (RemoteException e) {
721                         AltosDebug.debug("connect device message failed");
722                 }
723         }
724
725         private void disconnectDevice() {
726                 try {
727                         mService.send(Message.obtain(null, TelemetryService.MSG_DISCONNECT, null));
728                 } catch (RemoteException e) {
729                 }
730         }
731
732         private void set_map_type(Intent data) {
733                 int type = data.getIntExtra(MapTypeActivity.EXTRA_MAP_TYPE, -1);
734
735                 AltosDebug.debug("intent set_map_type %d\n", type);
736                 if (type != -1) {
737                         map_type = type;
738                         for (AltosDroidTab mTab : mTabs)
739                                 mTab.set_map_type(map_type);
740                 }
741         }
742
743         @Override
744         public boolean onCreateOptionsMenu(Menu menu) {
745                 MenuInflater inflater = getMenuInflater();
746                 inflater.inflate(R.menu.option_menu, menu);
747                 return true;
748         }
749
750         void setFrequency(double freq) {
751                 try {
752                         mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
753                 } catch (RemoteException e) {
754                 }
755         }
756
757         void setFrequency(String freq) {
758                 try {
759                         setFrequency (AltosParse.parse_double_net(freq.substring(11, 17)));
760                 } catch (ParseException e) {
761                 }
762         }
763
764         void setBaud(int baud) {
765                 try {
766                         mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD, baud));
767                 } catch (RemoteException e) {
768                 }
769         }
770
771         void setBaud(String baud) {
772                 try {
773                         int     value = Integer.parseInt(baud);
774                         int     rate = AltosLib.ao_telemetry_rate_38400;
775                         switch (value) {
776                         case 2400:
777                                 rate = AltosLib.ao_telemetry_rate_2400;
778                                 break;
779                         case 9600:
780                                 rate = AltosLib.ao_telemetry_rate_9600;
781                                 break;
782                         case 38400:
783                                 rate = AltosLib.ao_telemetry_rate_38400;
784                                 break;
785                         }
786                         setBaud(rate);
787                 } catch (NumberFormatException e) {
788                 }
789         }
790
791         void select_tracker(int serial) {
792                 int i;
793                 for (i = 0; i < serials.length; i++)
794                         if (serials[i] == serial)
795                                 break;
796                 if (i == serials.length)
797                         return;
798
799                 AltosDebug.debug("Switching to serial %d\n", serial);
800                 current_serial = serial;
801                 update_state(null);
802         }
803
804         void delete_track(int serial) {
805                 try {
806                         mService.send(Message.obtain(null, TelemetryService.MSG_DELETE_SERIAL, (Integer) serial));
807                 } catch (Exception ex) {
808                 }
809         }
810
811         @Override
812         public boolean onOptionsItemSelected(MenuItem item) {
813                 Intent serverIntent = null;
814                 switch (item.getItemId()) {
815                 case R.id.connect_scan:
816                         if (ensureBluetooth()) {
817                                 // Launch the DeviceListActivity to see devices and do scan
818                                 serverIntent = new Intent(this, DeviceListActivity.class);
819                                 startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
820                         }
821                         return true;
822                 case R.id.disconnect:
823                         /* Disconnect the device
824                          */
825                         disconnectDevice();
826                         return true;
827                 case R.id.quit:
828                         AltosDebug.debug("R.id.quit");
829                         disconnectDevice();
830                         finish();
831                         return true;
832                 case R.id.select_freq:
833                         // Set the TBT radio frequency
834
835                         final String[] frequencies = {
836                                 "Channel 0 (434.550MHz)",
837                                 "Channel 1 (434.650MHz)",
838                                 "Channel 2 (434.750MHz)",
839                                 "Channel 3 (434.850MHz)",
840                                 "Channel 4 (434.950MHz)",
841                                 "Channel 5 (435.050MHz)",
842                                 "Channel 6 (435.150MHz)",
843                                 "Channel 7 (435.250MHz)",
844                                 "Channel 8 (435.350MHz)",
845                                 "Channel 9 (435.450MHz)"
846                         };
847
848                         AlertDialog.Builder builder_freq = new AlertDialog.Builder(this);
849                         builder_freq.setTitle("Pick a frequency");
850                         builder_freq.setItems(frequencies,
851                                          new DialogInterface.OnClickListener() {
852                                                  public void onClick(DialogInterface dialog, int item) {
853                                                          setFrequency(frequencies[item]);
854                                                  }
855                                          });
856                         AlertDialog alert_freq = builder_freq.create();
857                         alert_freq.show();
858                         return true;
859                 case R.id.select_rate:
860                         // Set the TBT baud rate
861
862                         final String[] rates = {
863                                 "38400",
864                                 "9600",
865                                 "2400",
866                         };
867
868                         AlertDialog.Builder builder_rate = new AlertDialog.Builder(this);
869                         builder_rate.setTitle("Pick a baud rate");
870                         builder_rate.setItems(rates,
871                                          new DialogInterface.OnClickListener() {
872                                                  public void onClick(DialogInterface dialog, int item) {
873                                                          setBaud(rates[item]);
874                                                  }
875                                          });
876                         AlertDialog alert_rate = builder_rate.create();
877                         alert_rate.show();
878                         return true;
879                 case R.id.change_units:
880                         boolean imperial = AltosPreferences.imperial_units();
881                         AltosPreferences.set_imperial_units(!imperial);
882                         return true;
883                 case R.id.preload_maps:
884                         serverIntent = new Intent(this, PreloadMapActivity.class);
885                         startActivityForResult(serverIntent, REQUEST_PRELOAD_MAPS);
886                         return true;
887                 case R.id.map_type:
888                         serverIntent = new Intent(this, MapTypeActivity.class);
889                         startActivityForResult(serverIntent, REQUEST_MAP_TYPE);
890                         return true;
891                 case R.id.select_tracker:
892                         if (serials != null) {
893                                 String[] trackers = new String[serials.length];
894                                 for (int i = 0; i < serials.length; i++)
895                                         trackers[i] = String.format("%d", serials[i]);
896                                 AlertDialog.Builder builder_serial = new AlertDialog.Builder(this);
897                                 builder_serial.setTitle("Select a tracker");
898                                 builder_serial.setItems(trackers,
899                                                         new DialogInterface.OnClickListener() {
900                                                                 public void onClick(DialogInterface dialog, int item) {
901                                                                         select_tracker(serials[item]);
902                                                                 }
903                                                         });
904                                 AlertDialog alert_serial = builder_serial.create();
905                                 alert_serial.show();
906
907                         }
908                         return true;
909                 case R.id.delete_track:
910                         if (serials != null) {
911                                 String[] trackers = new String[serials.length];
912                                 for (int i = 0; i < serials.length; i++)
913                                         trackers[i] = String.format("%d", serials[i]);
914                                 AlertDialog.Builder builder_serial = new AlertDialog.Builder(this);
915                                 builder_serial.setTitle("Delete a track");
916                                 builder_serial.setItems(trackers,
917                                                         new DialogInterface.OnClickListener() {
918                                                                 public void onClick(DialogInterface dialog, int item) {
919                                                                         delete_track(serials[item]);
920                                                                 }
921                                                         });
922                                 AlertDialog alert_serial = builder_serial.create();
923                                 alert_serial.show();
924
925                         }
926                         return true;
927                 }
928                 return false;
929         }
930 }