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