97373ab8da30e70b9890438022e7c5c9a1b501c1
[fw/altos] / altosdroid / src / org / altusmetrum / AltosDroid / AltosDroid.java
1 /*
2  * Copyright © 2012-2013 Mike Beattie <mike@ethernal.org>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; version 2 of the License.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
16  */
17
18 package org.altusmetrum.AltosDroid;
19
20 import java.lang.ref.WeakReference;
21 import java.util.ArrayList;
22 import java.util.Timer;
23 import java.util.TimerTask;
24 import java.text.*;
25
26 import android.app.Activity;
27 import android.app.PendingIntent;
28 import android.bluetooth.BluetoothAdapter;
29 import android.bluetooth.BluetoothDevice;
30 import android.content.Intent;
31 import android.content.Context;
32 import android.content.ComponentName;
33 import android.content.ServiceConnection;
34 import android.content.DialogInterface;
35 import android.os.IBinder;
36 import android.os.Bundle;
37 import android.os.Handler;
38 import android.os.Message;
39 import android.os.Messenger;
40 import android.os.RemoteException;
41 import android.content.res.Resources;
42 import android.support.v4.app.FragmentActivity;
43 import android.support.v4.app.FragmentManager;
44 import android.util.DisplayMetrics;
45 import android.view.Menu;
46 import android.view.MenuInflater;
47 import android.view.MenuItem;
48 import android.view.Window;
49 import android.view.View;
50 import android.view.LayoutInflater;
51 import android.widget.TabHost;
52 import android.widget.TextView;
53 import android.widget.RelativeLayout;
54 import android.widget.Toast;
55 import android.app.AlertDialog;
56 import android.location.Location;
57 import android.hardware.usb.*;
58
59 import org.altusmetrum.altoslib_7.*;
60
61 public class AltosDroid extends FragmentActivity implements AltosUnitsListener {
62
63         // Actions sent to the telemetry server at startup time
64
65         public static final String ACTION_BLUETOOTH = "org.altusmetrum.AltosDroid.BLUETOOTH";
66         public static final String ACTION_USB = "org.altusmetrum.AltosDroid.USB";
67
68         // Message types received by our Handler
69
70         public static final int MSG_STATE           = 1;
71         public static final int MSG_UPDATE_AGE      = 2;
72
73         // Intent request codes
74         public static final int REQUEST_CONNECT_DEVICE = 1;
75         public static final int REQUEST_ENABLE_BT      = 2;
76         public static final int REQUEST_PRELOAD_MAPS   = 3;
77         public static final int REQUEST_MAP_TYPE       = 4;
78
79         public static FragmentManager   fm;
80
81         private BluetoothAdapter mBluetoothAdapter = null;
82
83         // Layout Views
84         private TextView mTitle;
85
86         // Flight state values
87         private TextView mCallsignView;
88         private TextView mRSSIView;
89         private TextView mSerialView;
90         private TextView mFlightView;
91         private RelativeLayout mStateLayout;
92         private TextView mStateView;
93         private TextView mAgeView;
94
95         // field to display the version at the bottom of the screen
96         private TextView mVersion;
97
98         private double frequency;
99         private int telemetry_rate;
100
101         // Tabs
102         TabHost         mTabHost;
103         AltosViewPager  mViewPager;
104         TabsAdapter     mTabsAdapter;
105         ArrayList<AltosDroidTab> mTabs = new ArrayList<AltosDroidTab>();
106         int             tabHeight;
107
108         // Timer and Saved flight state for Age calculation
109         private Timer timer;
110         AltosState saved_state;
111
112         UsbDevice       pending_usb_device;
113         boolean         start_with_usb;
114
115         // Service
116         private boolean mIsBound   = false;
117         private Messenger mService = null;
118         final Messenger mMessenger = new Messenger(new IncomingHandler(this));
119
120         // Text to Speech
121         private AltosVoice mAltosVoice = null;
122
123         // The Handler that gets information back from the Telemetry Service
124         static class IncomingHandler extends Handler {
125                 private final WeakReference<AltosDroid> mAltosDroid;
126                 IncomingHandler(AltosDroid ad) { mAltosDroid = new WeakReference<AltosDroid>(ad); }
127
128                 @Override
129                 public void handleMessage(Message msg) {
130                         AltosDroid ad = mAltosDroid.get();
131
132                         switch (msg.what) {
133                         case MSG_STATE:
134                                 AltosDebug.debug("MSG_STATE");
135                                 TelemetryState telemetry_state = (TelemetryState) msg.obj;
136                                 if (telemetry_state == null) {
137                                         AltosDebug.debug("telemetry_state null!");
138                                         return;
139                                 }
140
141                                 ad.update_state(telemetry_state);
142                                 break;
143                         case MSG_UPDATE_AGE:
144                                 AltosDebug.debug("MSG_UPDATE_AGE");
145                                 ad.update_age();
146                                 break;
147                         }
148                 }
149         };
150
151
152         private ServiceConnection mConnection = new ServiceConnection() {
153                 public void onServiceConnected(ComponentName className, IBinder service) {
154                         mService = new Messenger(service);
155                         try {
156                                 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
157                                 msg.replyTo = mMessenger;
158                                 mService.send(msg);
159                         } catch (RemoteException e) {
160                                 // In this case the service has crashed before we could even do anything with it
161                         }
162                         if (pending_usb_device != null) {
163                                 try {
164                                         mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, pending_usb_device));
165                                         pending_usb_device = null;
166                                 } catch (RemoteException e) {
167                                 }
168                         }
169                 }
170
171                 public void onServiceDisconnected(ComponentName className) {
172                         // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
173                         mService = null;
174                 }
175         };
176
177         void doBindService() {
178                 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
179                 mIsBound = true;
180         }
181
182         void doUnbindService() {
183                 if (mIsBound) {
184                         // If we have received the service, and hence registered with it, then now is the time to unregister.
185                         if (mService != null) {
186                                 try {
187                                         Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
188                                         msg.replyTo = mMessenger;
189                                         mService.send(msg);
190                                 } catch (RemoteException e) {
191                                         // There is nothing special we need to do if the service has crashed.
192                                 }
193                         }
194                         // Detach our existing connection.
195                         unbindService(mConnection);
196                         mIsBound = false;
197                 }
198         }
199
200         public void registerTab(AltosDroidTab mTab) {
201                 mTabs.add(mTab);
202         }
203
204         public void unregisterTab(AltosDroidTab mTab) {
205                 mTabs.remove(mTab);
206         }
207
208         public void units_changed(boolean imperial_units) {
209                 for (AltosDroidTab mTab : mTabs)
210                         mTab.units_changed(imperial_units);
211         }
212
213         void update_title(TelemetryState telemetry_state) {
214                 switch (telemetry_state.connect) {
215                 case TelemetryState.CONNECT_CONNECTED:
216                         if (telemetry_state.config != null) {
217                                 String str = String.format("S/N %d %6.3f MHz", telemetry_state.config.serial,
218                                                            telemetry_state.frequency);
219                                 if (telemetry_state.telemetry_rate != AltosLib.ao_telemetry_rate_38400)
220                                         str = str.concat(String.format(" %d bps",
221                                                                        AltosLib.ao_telemetry_rate_values[telemetry_state.telemetry_rate]));
222                                 mTitle.setText(str);
223                         } else {
224                                 mTitle.setText(R.string.title_connected_to);
225                         }
226                         break;
227                 case TelemetryState.CONNECT_CONNECTING:
228                         if (telemetry_state.address != null)
229                                 mTitle.setText(String.format("Connecting to %s...", telemetry_state.address.name));
230                         else
231                                 mTitle.setText("Connecting to something...");
232                         break;
233                 case TelemetryState.CONNECT_DISCONNECTED:
234                 case TelemetryState.CONNECT_NONE:
235                         mTitle.setText(R.string.title_not_connected);
236                         break;
237                 }
238         }
239
240         void start_timer() {
241                 if (timer == null) {
242                         timer = new Timer();
243                         timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 1000L, 1000L);
244                 }
245         }
246
247         void stop_timer() {
248                 if (timer != null) {
249                         timer.cancel();
250                         timer.purge();
251                         timer = null;
252                 }
253         }
254
255         boolean registered_units_listener;
256
257         void update_state(TelemetryState telemetry_state) {
258
259                 if (!registered_units_listener) {
260                         registered_units_listener = true;
261                         AltosPreferences.register_units_listener(this);
262                 }
263
264                 update_title(telemetry_state);
265                 update_ui(telemetry_state.state, telemetry_state.location);
266                 if (telemetry_state.connect == TelemetryState.CONNECT_CONNECTED)
267                         start_timer();
268         }
269
270         boolean same_string(String a, String b) {
271                 if (a == null) {
272                         if (b == null)
273                                 return true;
274                         return false;
275                 } else {
276                         if (b == null)
277                                 return false;
278                         return a.equals(b);
279                 }
280         }
281
282         void update_age() {
283                 if (saved_state != null)
284                         mAgeView.setText(String.format("%d", (System.currentTimeMillis() - saved_state.received_time + 500) / 1000));
285         }
286
287         void update_ui(AltosState state, Location location) {
288
289                 int prev_state = AltosLib.ao_flight_invalid;
290
291                 AltosGreatCircle from_receiver = null;
292
293                 if (saved_state != null)
294                         prev_state = saved_state.state;
295
296                 if (state != null) {
297                         if (state.state == AltosLib.ao_flight_stateless) {
298                                 boolean prev_locked = false;
299                                 boolean locked = false;
300
301                                 if(state.gps != null)
302                                         locked = state.gps.locked;
303                                 if (saved_state != null && saved_state.gps != null)
304                                         prev_locked = saved_state.gps.locked;
305                                 if (prev_locked != locked) {
306                                         String currentTab = mTabHost.getCurrentTabTag();
307                                         if (locked) {
308                                                 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("descent");
309                                         } else {
310                                                 if (currentTab.equals("descent")) mTabHost.setCurrentTabByTag("pad");
311                                         }
312                                 }
313                         } else {
314                                 if (prev_state != state.state) {
315                                         String currentTab = mTabHost.getCurrentTabTag();
316                                         switch (state.state) {
317                                         case AltosLib.ao_flight_boost:
318                                                 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("ascent");
319                                                 break;
320                                         case AltosLib.ao_flight_drogue:
321                                                 if (currentTab.equals("ascent")) mTabHost.setCurrentTabByTag("descent");
322                                                 break;
323                                         case AltosLib.ao_flight_landed:
324                                                 if (currentTab.equals("descent")) mTabHost.setCurrentTabByTag("landed");
325                                                 break;
326                                         case AltosLib.ao_flight_stateless:
327                                                 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("descent");
328                                                 break;
329                                         }
330                                 }
331                         }
332
333                         if (location != null && state.gps != null && state.gps.locked) {
334                                 double altitude = 0;
335                                 if (location.hasAltitude())
336                                         altitude = location.getAltitude();
337                                 from_receiver = new AltosGreatCircle(location.getLatitude(),
338                                                                      location.getLongitude(),
339                                                                      altitude,
340                                                                      state.gps.lat,
341                                                                      state.gps.lon,
342                                                                      state.gps.alt);
343                         }
344
345                         if (saved_state == null || !same_string(saved_state.callsign, state.callsign)) {
346                                 mCallsignView.setText(state.callsign);
347                         }
348                         if (saved_state == null || state.serial != saved_state.serial) {
349                                 mSerialView.setText(String.format("%d", state.serial));
350                         }
351                         if (saved_state == null || state.flight != saved_state.flight) {
352                                 if (state.flight == AltosLib.MISSING)
353                                         mFlightView.setText("");
354                                 else
355                                         mFlightView.setText(String.format("%d", state.flight));
356                         }
357                         if (saved_state == null || state.state != saved_state.state) {
358                                 if (state.state == AltosLib.ao_flight_stateless) {
359                                         mStateLayout.setVisibility(View.GONE);
360                                 } else {
361                                         mStateView.setText(state.state_name());
362                                         mStateLayout.setVisibility(View.VISIBLE);
363                                 }
364                         }
365                         if (saved_state == null || state.rssi != saved_state.rssi) {
366                                 mRSSIView.setText(String.format("%d", state.rssi));
367                         }
368                 }
369
370                 for (AltosDroidTab mTab : mTabs)
371                         mTab.update_ui(state, from_receiver, location, mTab == mTabsAdapter.currentItem());
372
373                 if (state != null && mAltosVoice != null)
374                         mAltosVoice.tell(state, from_receiver);
375
376                 saved_state = state;
377         }
378
379         private void onTimerTick() {
380                 try {
381                         mMessenger.send(Message.obtain(null, MSG_UPDATE_AGE));
382                 } catch (RemoteException e) {
383                 }
384         }
385
386         static String pos(double p, String pos, String neg) {
387                 String  h = pos;
388                 if (p == AltosLib.MISSING)
389                         return "";
390                 if (p < 0) {
391                         h = neg;
392                         p = -p;
393                 }
394                 int deg = (int) Math.floor(p);
395                 double min = (p - Math.floor(p)) * 60.0;
396                 return String.format("%d°%9.4f\" %s", deg, min, h);
397         }
398
399         static String number(String format, double value) {
400                 if (value == AltosLib.MISSING)
401                         return "";
402                 return String.format(format, value);
403         }
404
405         static String integer(String format, int value) {
406                 if (value == AltosLib.MISSING)
407                         return "";
408                 return String.format(format, value);
409         }
410
411         private View create_tab_view(String label) {
412                 LayoutInflater inflater = (LayoutInflater) this.getLayoutInflater();
413                 View tab_view = inflater.inflate(R.layout.tab_layout, null);
414                 TextView text_view = (TextView) tab_view.findViewById (R.id.tabLabel);
415                 text_view.setText(label);
416                 return tab_view;
417         }
418
419         @Override
420         public void onCreate(Bundle savedInstanceState) {
421                 super.onCreate(savedInstanceState);
422                 AltosDebug.debug("+++ ON CREATE +++");
423
424                 fm = getSupportFragmentManager();
425
426                 // Set up the window layout
427                 requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
428                 setContentView(R.layout.altosdroid);
429                 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
430
431                 // Create the Tabs and ViewPager
432                 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
433                 mTabHost.setup();
434
435                 mViewPager = (AltosViewPager)findViewById(R.id.pager);
436                 mViewPager.setOffscreenPageLimit(4);
437
438                 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
439
440                 mTabsAdapter.addTab(mTabHost.newTabSpec("pad").setIndicator(create_tab_view("Pad")), TabPad.class, null);
441                 mTabsAdapter.addTab(mTabHost.newTabSpec("ascent").setIndicator(create_tab_view("Ascent")), TabAscent.class, null);
442                 mTabsAdapter.addTab(mTabHost.newTabSpec("descent").setIndicator(create_tab_view("Descent")), TabDescent.class, null);
443                 mTabsAdapter.addTab(mTabHost.newTabSpec("landed").setIndicator(create_tab_view("Landed")), TabLanded.class, null);
444                 mTabsAdapter.addTab(mTabHost.newTabSpec("map").setIndicator(create_tab_view("Map")), TabMap.class, null);
445                 mTabsAdapter.addTab(mTabHost.newTabSpec("offmap").setIndicator(create_tab_view("OffMap")), TabMapOffline.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                 AltosDebug.debug("intent %s device %s granted %s", intent, device, granted);
528
529                 if (!granted)
530                         device = null;
531
532                 if (device != null) {
533                         AltosDebug.debug("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                                 AltosDebug.debug("check for a USB device at startup");
544                                 if (check_usb())
545                                         return;
546                         }
547                         AltosDebug.debug("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                 AltosDebug.debug("++ 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                 AltosDebug.debug("onNewIntent");
577                 noticeIntent(intent);
578         }
579
580         @Override
581         public void onResume() {
582                 super.onResume();
583                 AltosDebug.debug("+ ON RESUME +");
584         }
585
586         @Override
587         public void onPause() {
588                 super.onPause();
589                 AltosDebug.debug("- ON PAUSE -");
590         }
591
592         @Override
593         public void onStop() {
594                 super.onStop();
595                 AltosDebug.debug("-- 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                 AltosDebug.debug("--- 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                 AltosDebug.debug("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                                 AltosDebug.error("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                 case REQUEST_MAP_TYPE:
636                         if (resultCode == Activity.RESULT_OK)
637                                 set_map_type(data);
638                         break;
639                 }
640         }
641
642         private void connectUsb(UsbDevice device) {
643                 if (mService == null)
644                         pending_usb_device = device;
645                 else {
646                         // Attempt to connect to the device
647                         try {
648                                 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, device));
649                                 AltosDebug.debug("Sent OPEN_USB message");
650                         } catch (RemoteException e) {
651                                 AltosDebug.debug("connect device message failed");
652                         }
653                 }
654         }
655
656         private void connectDevice(Intent data) {
657                 // Attempt to connect to the device
658                 try {
659                         String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
660                         String name = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_NAME);
661
662                         AltosDebug.debug("Connecting to " + address + " " + name);
663                         DeviceAddress   a = new DeviceAddress(address, name);
664                         mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, a));
665                         AltosDebug.debug("Sent connecting message");
666                 } catch (RemoteException e) {
667                         AltosDebug.debug("connect device message failed");
668                 }
669         }
670
671         private void disconnectDevice() {
672                 try {
673                         mService.send(Message.obtain(null, TelemetryService.MSG_DISCONNECT, null));
674                 } catch (RemoteException e) {
675                 }
676         }
677
678         private void set_map_type(Intent data) {
679                 int     mode = data.getIntExtra(MapTypeActivity.EXTRA_MAP_TYPE, -1);
680
681                 AltosDebug.debug("intent set_map_type %d\n", mode);
682                 if (mode != -1) {
683                         for (AltosDroidTab mTab : mTabs)
684                                 mTab.set_map_type(mode);
685                 }
686         }
687
688         @Override
689         public boolean onCreateOptionsMenu(Menu menu) {
690                 MenuInflater inflater = getMenuInflater();
691                 inflater.inflate(R.menu.option_menu, menu);
692                 return true;
693         }
694
695         void setFrequency(double freq) {
696                 try {
697                         mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
698                 } catch (RemoteException e) {
699                 }
700         }
701
702         void setFrequency(String freq) {
703                 try {
704                         setFrequency (AltosParse.parse_double_net(freq.substring(11, 17)));
705                 } catch (ParseException e) {
706                 }
707         }
708
709         void setBaud(int baud) {
710                 try {
711                         mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD, baud));
712                 } catch (RemoteException e) {
713                 }
714         }
715
716         void setBaud(String baud) {
717                 try {
718                         int     value = Integer.parseInt(baud);
719                         int     rate = AltosLib.ao_telemetry_rate_38400;
720                         switch (value) {
721                         case 2400:
722                                 rate = AltosLib.ao_telemetry_rate_2400;
723                                 break;
724                         case 9600:
725                                 rate = AltosLib.ao_telemetry_rate_9600;
726                                 break;
727                         case 38400:
728                                 rate = AltosLib.ao_telemetry_rate_38400;
729                                 break;
730                         }
731                         setBaud(rate);
732                 } catch (NumberFormatException e) {
733                 }
734         }
735
736         @Override
737         public boolean onOptionsItemSelected(MenuItem item) {
738                 Intent serverIntent = null;
739                 switch (item.getItemId()) {
740                 case R.id.connect_scan:
741                         if (ensureBluetooth()) {
742                                 // Launch the DeviceListActivity to see devices and do scan
743                                 serverIntent = new Intent(this, DeviceListActivity.class);
744                                 startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
745                         }
746                         return true;
747                 case R.id.disconnect:
748                         /* Disconnect the device
749                          */
750                         disconnectDevice();
751                         return true;
752                 case R.id.quit:
753                         AltosDebug.debug("R.id.quit");
754                         disconnectDevice();
755                         finish();
756                         return true;
757                 case R.id.select_freq:
758                         // Set the TBT radio frequency
759
760                         final String[] frequencies = {
761                                 "Channel 0 (434.550MHz)",
762                                 "Channel 1 (434.650MHz)",
763                                 "Channel 2 (434.750MHz)",
764                                 "Channel 3 (434.850MHz)",
765                                 "Channel 4 (434.950MHz)",
766                                 "Channel 5 (435.050MHz)",
767                                 "Channel 6 (435.150MHz)",
768                                 "Channel 7 (435.250MHz)",
769                                 "Channel 8 (435.350MHz)",
770                                 "Channel 9 (435.450MHz)"
771                         };
772
773                         AlertDialog.Builder builder_freq = new AlertDialog.Builder(this);
774                         builder_freq.setTitle("Pick a frequency");
775                         builder_freq.setItems(frequencies,
776                                          new DialogInterface.OnClickListener() {
777                                                  public void onClick(DialogInterface dialog, int item) {
778                                                          setFrequency(frequencies[item]);
779                                                  }
780                                          });
781                         AlertDialog alert_freq = builder_freq.create();
782                         alert_freq.show();
783                         return true;
784                 case R.id.select_rate:
785                         // Set the TBT baud rate
786
787                         final String[] rates = {
788                                 "38400",
789                                 "9600",
790                                 "2400",
791                         };
792
793                         AlertDialog.Builder builder_rate = new AlertDialog.Builder(this);
794                         builder_rate.setTitle("Pick a baud rate");
795                         builder_rate.setItems(rates,
796                                          new DialogInterface.OnClickListener() {
797                                                  public void onClick(DialogInterface dialog, int item) {
798                                                          setBaud(rates[item]);
799                                                  }
800                                          });
801                         AlertDialog alert_rate = builder_rate.create();
802                         alert_rate.show();
803                         return true;
804                 case R.id.change_units:
805                         boolean imperial = AltosPreferences.imperial_units();
806                         AltosPreferences.set_imperial_units(!imperial);
807                         return true;
808                 case R.id.preload_maps:
809                         serverIntent = new Intent(this, PreloadMapActivity.class);
810                         startActivityForResult(serverIntent, REQUEST_PRELOAD_MAPS);
811                         return true;
812                 case R.id.map_type:
813                         serverIntent = new Intent(this, MapTypeActivity.class);
814                         startActivityForResult(serverIntent, REQUEST_MAP_TYPE);
815                         return true;
816                 }
817                 return false;
818         }
819
820 }