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