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