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