2 * Copyright © 2012-2013 Mike Beattie <mike@ethernal.org>
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.
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.
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.
18 package org.altusmetrum.AltosDroid;
20 import java.lang.ref.WeakReference;
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.view.*;
45 import android.widget.*;
46 import android.app.AlertDialog;
47 import android.location.Location;
48 import android.location.LocationManager;
49 import android.location.LocationListener;
50 import android.hardware.usb.*;
51 import android.graphics.*;
52 import android.graphics.drawable.*;
54 import org.altusmetrum.altoslib_11.*;
56 public class AltosDroid extends FragmentActivity implements AltosUnitsListener, LocationListener {
58 // Actions sent to the telemetry server at startup time
60 public static final String ACTION_BLUETOOTH = "org.altusmetrum.AltosDroid.BLUETOOTH";
61 public static final String ACTION_USB = "org.altusmetrum.AltosDroid.USB";
63 // Message types received by our Handler
65 public static final int MSG_STATE = 1;
66 public static final int MSG_UPDATE_AGE = 2;
67 public static final int MSG_IDLE_MODE = 3;
68 public static final int MSG_IGNITER_STATUS = 4;
70 // Intent request codes
71 public static final int REQUEST_CONNECT_DEVICE = 1;
72 public static final int REQUEST_ENABLE_BT = 2;
73 public static final int REQUEST_PRELOAD_MAPS = 3;
74 public static final int REQUEST_IDLE_MODE = 5;
75 public static final int REQUEST_IGNITERS = 6;
76 public static final int REQUEST_SETUP = 7;
78 public static final String EXTRA_IDLE_MODE = "idle_mode";
79 public static final String EXTRA_IDLE_RESULT = "idle_result";
80 public static final String EXTRA_TELEMETRY_SERVICE = "telemetry_service";
83 public static final int SETUP_BAUD = 1;
84 public static final int SETUP_UNITS = 2;
85 public static final int SETUP_MAP_SOURCE = 4;
86 public static final int SETUP_MAP_TYPE = 8;
88 public static FragmentManager fm;
90 private BluetoothAdapter mBluetoothAdapter = null;
92 // Flight state values
93 private TextView mCallsignView;
94 private TextView mRSSIView;
95 private TextView mSerialView;
96 private TextView mFlightView;
97 private RelativeLayout mStateLayout;
98 private TextView mStateView;
99 private TextView mAgeView;
100 private boolean mAgeViewOld;
101 private int mAgeNewColor;
102 private int mAgeOldColor;
104 public static final String tab_pad_name = "pad";
105 public static final String tab_flight_name = "flight";
106 public static final String tab_recover_name = "recover";
107 public static final String tab_map_name = "map";
109 // field to display the version at the bottom of the screen
110 private TextView mVersion;
112 private boolean idle_mode = false;
114 public Location location = null;
118 AltosViewPager mViewPager;
119 TabsAdapter mTabsAdapter;
120 ArrayList<AltosDroidTab> mTabs = new ArrayList<AltosDroidTab>();
123 // Timer and Saved flight state for Age calculation
125 AltosState saved_state;
126 TelemetryState telemetry_state;
129 UsbDevice pending_usb_device;
130 boolean start_with_usb;
133 private boolean mIsBound = false;
134 private Messenger mService = null;
135 final Messenger mMessenger = new Messenger(new IncomingHandler(this));
138 private AltosVoice mAltosVoice = null;
140 // The Handler that gets information back from the Telemetry Service
141 static class IncomingHandler extends Handler {
142 private final WeakReference<AltosDroid> mAltosDroid;
143 IncomingHandler(AltosDroid ad) { mAltosDroid = new WeakReference<AltosDroid>(ad); }
146 public void handleMessage(Message msg) {
147 AltosDroid ad = mAltosDroid.get();
151 if (msg.obj == null) {
152 AltosDebug.debug("telemetry_state null!");
155 ad.update_state((TelemetryState) msg.obj);
161 ad.idle_mode = (Boolean) msg.obj;
162 ad.update_state(null);
169 private ServiceConnection mConnection = new ServiceConnection() {
170 public void onServiceConnected(ComponentName className, IBinder service) {
171 mService = new Messenger(service);
173 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
174 msg.replyTo = mMessenger;
176 } catch (RemoteException e) {
177 // In this case the service has crashed before we could even do anything with it
179 if (pending_usb_device != null) {
181 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, pending_usb_device));
182 pending_usb_device = null;
183 } catch (RemoteException e) {
188 public void onServiceDisconnected(ComponentName className) {
189 // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
194 void doBindService() {
195 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
199 void doUnbindService() {
201 // If we have received the service, and hence registered with it, then now is the time to unregister.
202 if (mService != null) {
204 Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
205 msg.replyTo = mMessenger;
207 } catch (RemoteException e) {
208 // There is nothing special we need to do if the service has crashed.
211 // Detach our existing connection.
212 unbindService(mConnection);
217 public void registerTab(AltosDroidTab mTab) {
221 public void unregisterTab(AltosDroidTab mTab) {
225 public void units_changed(boolean imperial_units) {
226 for (AltosDroidTab mTab : mTabs)
227 mTab.units_changed(imperial_units);
230 void update_title(TelemetryState telemetry_state) {
231 switch (telemetry_state.connect) {
232 case TelemetryState.CONNECT_CONNECTED:
233 if (telemetry_state.config != null) {
234 String str = String.format("S/N %d %6.3f MHz%s", telemetry_state.config.serial,
235 telemetry_state.frequency, idle_mode ? " (idle)" : "");
236 if (telemetry_state.telemetry_rate != AltosLib.ao_telemetry_rate_38400)
237 str = str.concat(String.format(" %d bps",
238 AltosLib.ao_telemetry_rate_values[telemetry_state.telemetry_rate]));
241 setTitle(R.string.title_connected_to);
244 case TelemetryState.CONNECT_CONNECTING:
245 if (telemetry_state.address != null)
246 setTitle(String.format("Connecting to %s...", telemetry_state.address.name));
248 setTitle("Connecting to something...");
250 case TelemetryState.CONNECT_DISCONNECTED:
251 case TelemetryState.CONNECT_NONE:
252 setTitle(R.string.title_not_connected);
260 timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 1000L, 1000L);
272 int selected_serial = 0;
276 void set_switch_time() {
277 switch_time = System.currentTimeMillis();
281 boolean registered_units_listener;
283 void update_state(TelemetryState new_telemetry_state) {
285 if (new_telemetry_state != null)
286 telemetry_state = new_telemetry_state;
288 if (selected_serial != 0)
289 current_serial = selected_serial;
291 if (current_serial == 0)
292 current_serial = telemetry_state.latest_serial;
294 if (!registered_units_listener) {
295 registered_units_listener = true;
296 AltosPreferences.register_units_listener(this);
299 serials = telemetry_state.states.keySet().toArray(new Integer[0]);
300 Arrays.sort(serials);
302 update_title(telemetry_state);
304 AltosState state = null;
307 if (telemetry_state.states.containsKey(current_serial)) {
308 state = telemetry_state.states.get(current_serial);
309 int age = state_age(state);
312 if (current_serial == selected_serial)
314 else if (switch_time != 0 && (switch_time - state.received_time) > 0)
319 AltosState newest_state = null;
322 for (int serial : telemetry_state.states.keySet()) {
323 AltosState existing = telemetry_state.states.get(serial);
324 int existing_age = state_age(existing);
326 if (newest_state == null || existing_age < newest_age) {
327 newest_state = existing;
328 newest_age = existing_age;
332 if (newest_state != null)
333 state = newest_state;
336 update_ui(telemetry_state, state);
341 boolean same_string(String a, String b) {
354 private int blend_component(int a, int b, double r, int shift, int mask) {
355 return ((int) (((a >> shift) & mask) * r + ((b >> shift) & mask) * (1 - r)) & mask) << shift;
357 private int blend_color(int a, int b, double r) {
358 return (blend_component(a, b, r, 0, 0xff) |
359 blend_component(a, b, r, 8, 0xff) |
360 blend_component(a, b, r, 16, 0xff) |
361 blend_component(a, b, r, 24, 0xff));
364 int state_age(AltosState state) {
365 return (int) ((System.currentTimeMillis() - state.received_time + 500) / 1000);
368 void set_screen_on(int age) {
370 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
372 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
376 if (saved_state != null) {
377 int age = state_age(saved_state);
379 double age_scale = age / 100.0;
384 mAgeView.setTextColor(blend_color(mAgeOldColor, mAgeNewColor, age_scale));
390 text = String.format("%ds", age);
391 else if (age < 60 * 60)
392 text = String.format("%dm", age / 60);
393 else if (age < 60 * 60 * 24)
394 text = String.format("%dh", age / (60 * 60));
396 text = String.format("%dd", age / (24 * 60 * 60));
397 mAgeView.setText(text);
401 void update_ui(TelemetryState telem_state, AltosState state) {
403 int prev_state = AltosLib.ao_flight_invalid;
405 AltosGreatCircle from_receiver = null;
407 if (saved_state != null)
408 prev_state = saved_state.state();
411 set_screen_on(state_age(state));
413 if (state.state() == AltosLib.ao_flight_stateless) {
414 boolean prev_locked = false;
415 boolean locked = false;
417 if(state.gps != null)
418 locked = state.gps.locked;
419 if (saved_state != null && saved_state.gps != null)
420 prev_locked = saved_state.gps.locked;
421 if (prev_locked != locked) {
422 String currentTab = mTabHost.getCurrentTabTag();
424 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
426 if (currentTab.equals(tab_flight_name)) mTabHost.setCurrentTabByTag(tab_pad_name);
430 if (prev_state != state.state()) {
431 String currentTab = mTabHost.getCurrentTabTag();
432 switch (state.state()) {
433 case AltosLib.ao_flight_boost:
434 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
436 case AltosLib.ao_flight_landed:
437 if (currentTab.equals(tab_flight_name)) mTabHost.setCurrentTabByTag(tab_recover_name);
439 case AltosLib.ao_flight_stateless:
440 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
446 if (location != null && state.gps != null && state.gps.locked) {
448 if (location.hasAltitude())
449 altitude = location.getAltitude();
450 from_receiver = new AltosGreatCircle(location.getLatitude(),
451 location.getLongitude(),
458 if (saved_state == null || !same_string(saved_state.callsign, state.callsign)) {
459 mCallsignView.setText(state.callsign);
461 if (saved_state == null || state.serial != saved_state.serial) {
462 if (state.serial == AltosLib.MISSING)
463 mSerialView.setText("");
465 mSerialView.setText(String.format("%d", state.serial));
467 if (saved_state == null || state.flight != saved_state.flight) {
468 if (state.flight == AltosLib.MISSING)
469 mFlightView.setText("");
471 mFlightView.setText(String.format("%d", state.flight));
473 if (saved_state == null || state.state() != saved_state.state()) {
474 if (state.state() == AltosLib.ao_flight_stateless) {
475 mStateLayout.setVisibility(View.GONE);
477 mStateView.setText(state.state_name());
478 mStateLayout.setVisibility(View.VISIBLE);
481 if (saved_state == null || state.rssi != saved_state.rssi) {
482 if (state.rssi == AltosLib.MISSING)
483 mRSSIView.setText("");
485 mRSSIView.setText(String.format("%d", state.rssi));
489 for (AltosDroidTab mTab : mTabs)
490 mTab.update_ui(telem_state, state, from_receiver, location, mTab == mTabsAdapter.currentItem());
492 if (mAltosVoice != null)
493 mAltosVoice.tell(telem_state, state, from_receiver, location, (AltosDroidTab) mTabsAdapter.currentItem());
498 private void onTimerTick() {
500 mMessenger.send(Message.obtain(null, MSG_UPDATE_AGE));
501 } catch (RemoteException e) {
505 static String pos(double p, String pos, String neg) {
507 if (p == AltosLib.MISSING)
513 int deg = (int) Math.floor(p);
514 double min = (p - Math.floor(p)) * 60.0;
515 return String.format("%d°%9.4f\" %s", deg, min, h);
518 static String number(String format, double value) {
519 if (value == AltosLib.MISSING)
521 return String.format(format, value);
524 static String integer(String format, int value) {
525 if (value == AltosLib.MISSING)
527 return String.format(format, value);
530 private View create_tab_view(String label) {
531 LayoutInflater inflater = (LayoutInflater) this.getLayoutInflater();
532 View tab_view = inflater.inflate(R.layout.tab_layout, null);
533 TextView text_view = (TextView) tab_view.findViewById (R.id.tabLabel);
534 text_view.setText(label);
539 public void onCreate(Bundle savedInstanceState) {
540 super.onCreate(savedInstanceState);
541 AltosDebug.init(this);
542 AltosDebug.debug("+++ ON CREATE +++");
544 // Initialise preferences
545 AltosDroidPreferences.init(this);
547 fm = getSupportFragmentManager();
549 // Set up the window layout
550 setContentView(R.layout.altosdroid);
552 // Create the Tabs and ViewPager
553 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
556 mViewPager = (AltosViewPager)findViewById(R.id.pager);
557 mViewPager.setOffscreenPageLimit(4);
559 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
561 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_pad_name).setIndicator(create_tab_view("Pad")), TabPad.class, null);
562 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_flight_name).setIndicator(create_tab_view("Flight")), TabFlight.class, null);
563 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_recover_name).setIndicator(create_tab_view("Recover")), TabRecover.class, null);
564 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_map_name).setIndicator(create_tab_view("Map")), TabMap.class, null);
566 // Display the Version
567 mVersion = (TextView) findViewById(R.id.version);
568 mVersion.setText("Version: " + BuildInfo.version +
569 " Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
570 " (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
572 mCallsignView = (TextView) findViewById(R.id.callsign_value);
573 mRSSIView = (TextView) findViewById(R.id.rssi_value);
574 mSerialView = (TextView) findViewById(R.id.serial_value);
575 mFlightView = (TextView) findViewById(R.id.flight_value);
576 mStateLayout = (RelativeLayout) findViewById(R.id.state_container);
577 mStateView = (TextView) findViewById(R.id.state_value);
578 mAgeView = (TextView) findViewById(R.id.age_value);
579 mAgeNewColor = mAgeView.getTextColors().getDefaultColor();
580 mAgeOldColor = getResources().getColor(R.color.old_color);
583 private void ensureBluetooth() {
584 // Get local Bluetooth adapter
585 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
587 /* if there is a BT adapter and it isn't turned on, then turn it on */
588 if (mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) {
589 Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
590 startActivityForResult(enableIntent, AltosDroid.REQUEST_ENABLE_BT);
594 private boolean check_usb() {
595 UsbDevice device = AltosUsb.find_device(this, AltosLib.product_basestation);
597 if (device != null) {
598 Intent i = new Intent(this, AltosDroid.class);
599 PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent("hello world", null, this, AltosDroid.class), 0);
601 if (AltosUsb.request_permission(this, device, pi)) {
604 start_with_usb = true;
608 start_with_usb = false;
613 private void noticeIntent(Intent intent) {
615 /* Ok, this is pretty convenient.
617 * When a USB device is plugged in, and our 'hotplug'
618 * intent registration fires, we get an Intent with
621 * When we start up and see a usb device and request
622 * permission to access it, that queues a
623 * PendingIntent, which has the EXTRA_DEVICE added in,
624 * along with the EXTRA_PERMISSION_GRANTED field as
627 * So, in both cases, we get the device name using the
628 * same call. We check to see if access was granted,
629 * in which case we ignore the device field and do our
630 * usual startup thing.
633 UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
634 boolean granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, true);
636 AltosDebug.debug("intent %s device %s granted %s", intent, device, granted);
641 if (device != null) {
642 AltosDebug.debug("intent has usb device " + device.toString());
646 /* 'granted' is only false if this intent came
647 * from the request_permission call and
648 * permission was denied. In which case, we
649 * don't want to loop forever...
652 AltosDebug.debug("check for a USB device at startup");
656 AltosDebug.debug("Starting by looking for bluetooth devices");
662 public void onStart() {
664 AltosDebug.debug("++ ON START ++");
668 noticeIntent(getIntent());
670 // Start Telemetry Service
671 String action = start_with_usb ? ACTION_USB : ACTION_BLUETOOTH;
673 startService(new Intent(action, null, AltosDroid.this, TelemetryService.class));
677 if (mAltosVoice == null)
678 mAltosVoice = new AltosVoice(this);
683 public void onNewIntent(Intent intent) {
684 super.onNewIntent(intent);
685 AltosDebug.debug("onNewIntent");
686 noticeIntent(intent);
690 public void onResume() {
692 AltosDebug.debug("+ ON RESUME +");
694 // Listen for GPS and Network position updates
695 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
696 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
698 location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
700 if (location != null)
701 AltosDebug.debug("Resume, location is %f,%f\n",
702 location.getLatitude(),
703 location.getLongitude());
705 update_ui(telemetry_state, saved_state);
709 public void onPause() {
711 AltosDebug.debug("- ON PAUSE -");
712 // Stop listening for location updates
713 ((LocationManager) getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
717 public void onStop() {
719 AltosDebug.debug("-- ON STOP --");
723 public void onDestroy() {
725 AltosDebug.debug("--- ON DESTROY ---");
728 if (mAltosVoice != null) {
735 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
736 AltosDebug.debug("onActivityResult " + resultCode);
737 switch (requestCode) {
738 case REQUEST_CONNECT_DEVICE:
739 // When DeviceListActivity returns with a device to connect to
740 if (resultCode == Activity.RESULT_OK) {
744 case REQUEST_ENABLE_BT:
745 // When the request to enable Bluetooth returns
746 if (resultCode == Activity.RESULT_OK) {
747 // Bluetooth is now enabled, so set up a chat session
749 AltosDebug.debug("BT enabled");
750 bluetoothEnabled(data);
752 // User did not enable Bluetooth or an error occured
753 AltosDebug.debug("BT not enabled");
756 case REQUEST_IDLE_MODE:
757 if (resultCode == Activity.RESULT_OK)
760 case REQUEST_IGNITERS:
763 if (resultCode == Activity.RESULT_OK)
764 note_setup_changes(data);
769 private void note_setup_changes(Intent data) {
770 int changes = data.getIntExtra(SetupActivity.EXTRA_SETUP_CHANGES, 0);
772 if ((changes & SETUP_BAUD) != 0) {
774 mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD,
775 AltosPreferences.telemetry_rate(1)));
776 } catch (RemoteException re) {
779 if ((changes & SETUP_UNITS) != 0) {
780 /* nothing to do here */
782 if ((changes & SETUP_MAP_SOURCE) != 0) {
783 /* nothing to do here */
785 if ((changes & SETUP_MAP_TYPE) != 0) {
786 /* nothing to do here */
791 private void connectUsb(UsbDevice device) {
792 if (mService == null)
793 pending_usb_device = device;
795 // Attempt to connect to the device
797 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, device));
798 AltosDebug.debug("Sent OPEN_USB message");
799 } catch (RemoteException e) {
800 AltosDebug.debug("connect device message failed");
805 private void bluetoothEnabled(Intent data) {
807 mService.send(Message.obtain(null, TelemetryService.MSG_BLUETOOTH_ENABLED, null));
808 } catch (RemoteException e) {
809 AltosDebug.debug("send BT enabled message failed");
813 private void connectDevice(Intent data) {
814 // Attempt to connect to the device
816 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
817 String name = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_NAME);
819 AltosDebug.debug("Connecting to " + address + " " + name);
820 DeviceAddress a = new DeviceAddress(address, name);
821 mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, a));
822 AltosDebug.debug("Sent connecting message");
823 } catch (RemoteException e) {
824 AltosDebug.debug("connect device message failed");
828 private void disconnectDevice(boolean remember) {
830 mService.send(Message.obtain(null, TelemetryService.MSG_DISCONNECT, (Boolean) remember));
831 } catch (RemoteException e) {
835 private void idle_mode(Intent data) {
836 int type = data.getIntExtra(IdleModeActivity.EXTRA_IDLE_RESULT, -1);
839 AltosDebug.debug("intent idle_mode %d", type);
841 case IdleModeActivity.IDLE_MODE_CONNECT:
842 msg = Message.obtain(null, TelemetryService.MSG_MONITOR_IDLE_START);
845 } catch (RemoteException re) {
848 case IdleModeActivity.IDLE_MODE_DISCONNECT:
849 msg = Message.obtain(null, TelemetryService.MSG_MONITOR_IDLE_STOP);
852 } catch (RemoteException re) {
855 case IdleModeActivity.IDLE_MODE_REBOOT:
856 msg = Message.obtain(null, TelemetryService.MSG_REBOOT);
859 } catch (RemoteException re) {
862 case IdleModeActivity.IDLE_MODE_IGNITERS:
863 Intent serverIntent = new Intent(this, IgniterActivity.class);
864 startActivityForResult(serverIntent, REQUEST_IGNITERS);
870 public boolean onCreateOptionsMenu(Menu menu) {
871 MenuInflater inflater = getMenuInflater();
872 inflater.inflate(R.menu.option_menu, menu);
876 void setFrequency(double freq) {
878 mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
880 } catch (RemoteException e) {
884 void setFrequency(AltosFrequency frequency) {
885 setFrequency (frequency.frequency);
888 void setBaud(int baud) {
890 mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD, baud));
892 } catch (RemoteException e) {
896 void setBaud(String baud) {
898 int value = Integer.parseInt(baud);
899 int rate = AltosLib.ao_telemetry_rate_38400;
902 rate = AltosLib.ao_telemetry_rate_2400;
905 rate = AltosLib.ao_telemetry_rate_9600;
908 rate = AltosLib.ao_telemetry_rate_38400;
912 } catch (NumberFormatException e) {
916 void select_tracker(int serial) {
919 AltosDebug.debug("select tracker %d\n", serial);
921 if (serial == selected_serial) {
922 AltosDebug.debug("%d already selected\n", serial);
927 for (i = 0; i < serials.length; i++)
928 if (serials[i] == serial)
931 if (i == serials.length) {
932 AltosDebug.debug("attempt to select unknown tracker %d\n", serial);
937 current_serial = selected_serial = serial;
941 void touch_trackers(Integer[] serials) {
942 AlertDialog.Builder builder_tracker = new AlertDialog.Builder(this);
943 builder_tracker.setTitle("Select Tracker");
944 final String[] trackers = new String[serials.length + 1];
945 trackers[0] = "Auto";
946 for (int i = 0; i < serials.length; i++)
947 trackers[i+1] = String.format("%d", serials[i]);
948 builder_tracker.setItems(trackers,
949 new DialogInterface.OnClickListener() {
950 public void onClick(DialogInterface dialog, int item) {
954 select_tracker(Integer.parseInt(trackers[item]));
957 AlertDialog alert_tracker = builder_tracker.create();
958 alert_tracker.show();
961 void delete_track(int serial) {
963 mService.send(Message.obtain(null, TelemetryService.MSG_DELETE_SERIAL, (Integer) serial));
964 } catch (Exception ex) {
969 public boolean onOptionsItemSelected(MenuItem item) {
970 Intent serverIntent = null;
971 switch (item.getItemId()) {
972 case R.id.connect_scan:
974 // Launch the DeviceListActivity to see devices and do scan
975 serverIntent = new Intent(this, DeviceListActivity.class);
976 startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
978 case R.id.disconnect:
979 /* Disconnect the device
981 disconnectDevice(false);
984 AltosDebug.debug("R.id.quit");
985 disconnectDevice(true);
989 serverIntent = new Intent(this, SetupActivity.class);
990 startActivityForResult(serverIntent, REQUEST_SETUP);
992 case R.id.select_freq:
993 // Set the TBT radio frequency
995 final AltosFrequency[] frequencies = AltosPreferences.common_frequencies();
996 String[] frequency_strings = new String[frequencies.length];
997 for (int i = 0; i < frequencies.length; i++)
998 frequency_strings[i] = frequencies[i].toString();
1000 AlertDialog.Builder builder_freq = new AlertDialog.Builder(this);
1001 builder_freq.setTitle("Pick a frequency");
1002 builder_freq.setItems(frequency_strings,
1003 new DialogInterface.OnClickListener() {
1004 public void onClick(DialogInterface dialog, int item) {
1005 setFrequency(frequencies[item]);
1008 AlertDialog alert_freq = builder_freq.create();
1011 case R.id.select_tracker:
1012 if (serials != null) {
1013 String[] trackers = new String[serials.length+1];
1014 trackers[0] = "Auto";
1015 for (int i = 0; i < serials.length; i++)
1016 trackers[i+1] = String.format("%d", serials[i]);
1017 AlertDialog.Builder builder_serial = new AlertDialog.Builder(this);
1018 builder_serial.setTitle("Select a tracker");
1019 builder_serial.setItems(trackers,
1020 new DialogInterface.OnClickListener() {
1021 public void onClick(DialogInterface dialog, int item) {
1025 select_tracker(serials[item-1]);
1028 AlertDialog alert_serial = builder_serial.create();
1029 alert_serial.show();
1033 case R.id.delete_track:
1034 if (serials != null) {
1035 String[] trackers = new String[serials.length];
1036 for (int i = 0; i < serials.length; i++)
1037 trackers[i] = String.format("%d", serials[i]);
1038 AlertDialog.Builder builder_serial = new AlertDialog.Builder(this);
1039 builder_serial.setTitle("Delete a track");
1040 builder_serial.setItems(trackers,
1041 new DialogInterface.OnClickListener() {
1042 public void onClick(DialogInterface dialog, int item) {
1043 delete_track(serials[item]);
1046 AlertDialog alert_serial = builder_serial.create();
1047 alert_serial.show();
1051 case R.id.idle_mode:
1052 serverIntent = new Intent(this, IdleModeActivity.class);
1053 serverIntent.putExtra(EXTRA_IDLE_MODE, idle_mode);
1054 startActivityForResult(serverIntent, REQUEST_IDLE_MODE);
1060 static String direction(AltosGreatCircle from_receiver,
1061 Location receiver) {
1062 if (from_receiver == null)
1065 if (receiver == null)
1068 if (!receiver.hasBearing())
1071 float bearing = receiver.getBearing();
1072 float heading = (float) from_receiver.bearing - bearing;
1074 while (heading <= -180.0f)
1076 while (heading > 180.0f)
1079 int iheading = (int) (heading + 0.5f);
1081 if (-1 < iheading && iheading < 1)
1083 else if (iheading < -179 || 179 < iheading)
1085 else if (iheading < 0)
1086 return String.format("left %d°", -iheading);
1088 return String.format("right %d°", iheading);
1091 public void onLocationChanged(Location location) {
1092 this.location = location;
1093 AltosDebug.debug("Location changed to %f,%f",
1094 location.getLatitude(),
1095 location.getLongitude());
1096 update_ui(telemetry_state, saved_state);
1099 public void onStatusChanged(String provider, int status, Bundle extras) {
1100 AltosDebug.debug("Location status now %d\n", status);
1103 public void onProviderEnabled(String provider) {
1104 AltosDebug.debug("Location provider enabled %s\n", provider);
1107 public void onProviderDisabled(String provider) {
1108 AltosDebug.debug("Location provider disabled %s\n", provider);