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