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_10.*;
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;
68 // Intent request codes
69 public static final int REQUEST_CONNECT_DEVICE = 1;
70 public static final int REQUEST_ENABLE_BT = 2;
71 public static final int REQUEST_PRELOAD_MAPS = 3;
72 public static final int REQUEST_MAP_TYPE = 4;
74 public int map_type = AltosMap.maptype_hybrid;
76 public static FragmentManager fm;
78 private BluetoothAdapter mBluetoothAdapter = null;
80 // Flight state values
81 private TextView mCallsignView;
82 private TextView mRSSIView;
83 private TextView mSerialView;
84 private TextView mFlightView;
85 private RelativeLayout mStateLayout;
86 private TextView mStateView;
87 private TextView mAgeView;
88 private boolean mAgeViewOld;
89 private int mAgeNewColor;
90 private int mAgeOldColor;
92 public static final String tab_pad_name = "pad";
93 public static final String tab_flight_name = "flight";
94 public static final String tab_recover_name = "recover";
95 public static final String tab_map_name = "map";
97 // field to display the version at the bottom of the screen
98 private TextView mVersion;
100 private double frequency;
101 private int telemetry_rate;
103 public Location location = null;
107 AltosViewPager mViewPager;
108 TabsAdapter mTabsAdapter;
109 ArrayList<AltosDroidTab> mTabs = new ArrayList<AltosDroidTab>();
112 // Timer and Saved flight state for Age calculation
114 AltosState saved_state;
115 TelemetryState telemetry_state;
118 UsbDevice pending_usb_device;
119 boolean start_with_usb;
122 private boolean mIsBound = false;
123 private Messenger mService = null;
124 final Messenger mMessenger = new Messenger(new IncomingHandler(this));
127 private AltosVoice mAltosVoice = null;
129 // The Handler that gets information back from the Telemetry Service
130 static class IncomingHandler extends Handler {
131 private final WeakReference<AltosDroid> mAltosDroid;
132 IncomingHandler(AltosDroid ad) { mAltosDroid = new WeakReference<AltosDroid>(ad); }
135 public void handleMessage(Message msg) {
136 AltosDroid ad = mAltosDroid.get();
140 if (msg.obj == null) {
141 AltosDebug.debug("telemetry_state null!");
144 ad.update_state((TelemetryState) msg.obj);
154 private ServiceConnection mConnection = new ServiceConnection() {
155 public void onServiceConnected(ComponentName className, IBinder service) {
156 mService = new Messenger(service);
158 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
159 msg.replyTo = mMessenger;
161 } catch (RemoteException e) {
162 // In this case the service has crashed before we could even do anything with it
164 if (pending_usb_device != null) {
166 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, pending_usb_device));
167 pending_usb_device = null;
168 } catch (RemoteException e) {
173 public void onServiceDisconnected(ComponentName className) {
174 // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
179 void doBindService() {
180 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
184 void doUnbindService() {
186 // If we have received the service, and hence registered with it, then now is the time to unregister.
187 if (mService != null) {
189 Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
190 msg.replyTo = mMessenger;
192 } catch (RemoteException e) {
193 // There is nothing special we need to do if the service has crashed.
196 // Detach our existing connection.
197 unbindService(mConnection);
202 public void registerTab(AltosDroidTab mTab) {
206 public void unregisterTab(AltosDroidTab mTab) {
210 public void units_changed(boolean imperial_units) {
211 for (AltosDroidTab mTab : mTabs)
212 mTab.units_changed(imperial_units);
215 void update_title(TelemetryState telemetry_state) {
216 switch (telemetry_state.connect) {
217 case TelemetryState.CONNECT_CONNECTED:
218 if (telemetry_state.config != null) {
219 String str = String.format("S/N %d %6.3f MHz", telemetry_state.config.serial,
220 telemetry_state.frequency);
221 if (telemetry_state.telemetry_rate != AltosLib.ao_telemetry_rate_38400)
222 str = str.concat(String.format(" %d bps",
223 AltosLib.ao_telemetry_rate_values[telemetry_state.telemetry_rate]));
226 setTitle(R.string.title_connected_to);
229 case TelemetryState.CONNECT_CONNECTING:
230 if (telemetry_state.address != null)
231 setTitle(String.format("Connecting to %s...", telemetry_state.address.name));
233 setTitle("Connecting to something...");
235 case TelemetryState.CONNECT_DISCONNECTED:
236 case TelemetryState.CONNECT_NONE:
237 setTitle(R.string.title_not_connected);
245 timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 1000L, 1000L);
257 int selected_serial = 0;
261 void set_switch_time() {
262 switch_time = System.currentTimeMillis();
266 boolean registered_units_listener;
268 void update_state(TelemetryState new_telemetry_state) {
270 if (new_telemetry_state != null)
271 telemetry_state = new_telemetry_state;
273 if (selected_serial != 0)
274 current_serial = selected_serial;
276 if (current_serial == 0)
277 current_serial = telemetry_state.latest_serial;
279 if (!registered_units_listener) {
280 registered_units_listener = true;
281 AltosPreferences.register_units_listener(this);
284 serials = telemetry_state.states.keySet().toArray(new Integer[0]);
285 Arrays.sort(serials);
287 update_title(telemetry_state);
289 AltosState state = null;
292 if (telemetry_state.states.containsKey(current_serial)) {
293 state = telemetry_state.states.get(current_serial);
294 int age = state_age(state);
297 if (current_serial == selected_serial)
299 else if (switch_time != 0 && (switch_time - state.received_time) > 0)
304 AltosState newest_state = null;
307 for (int serial : telemetry_state.states.keySet()) {
308 AltosState existing = telemetry_state.states.get(serial);
309 int existing_age = state_age(existing);
311 if (newest_state == null || existing_age < newest_age) {
312 newest_state = existing;
313 newest_age = existing_age;
317 if (newest_state != null)
318 state = newest_state;
321 update_ui(telemetry_state, state);
326 boolean same_string(String a, String b) {
339 private int blend_component(int a, int b, double r, int shift, int mask) {
340 return ((int) (((a >> shift) & mask) * r + ((b >> shift) & mask) * (1 - r)) & mask) << shift;
342 private int blend_color(int a, int b, double r) {
343 return (blend_component(a, b, r, 0, 0xff) |
344 blend_component(a, b, r, 8, 0xff) |
345 blend_component(a, b, r, 16, 0xff) |
346 blend_component(a, b, r, 24, 0xff));
349 int state_age(AltosState state) {
350 return (int) ((System.currentTimeMillis() - state.received_time + 500) / 1000);
353 void set_screen_on(int age) {
355 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
357 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
361 if (saved_state != null) {
362 int age = state_age(saved_state);
364 double age_scale = age / 100.0;
369 mAgeView.setTextColor(blend_color(mAgeOldColor, mAgeNewColor, age_scale));
375 text = String.format("%ds", age);
376 else if (age < 60 * 60)
377 text = String.format("%dm", age / 60);
378 else if (age < 60 * 60 * 24)
379 text = String.format("%dh", age / (60 * 60));
381 text = String.format("%dd", age / (24 * 60 * 60));
382 mAgeView.setText(text);
386 void update_ui(TelemetryState telem_state, AltosState state) {
388 int prev_state = AltosLib.ao_flight_invalid;
390 AltosGreatCircle from_receiver = null;
392 if (saved_state != null)
393 prev_state = saved_state.state();
396 set_screen_on(state_age(state));
398 if (state.state() == AltosLib.ao_flight_stateless) {
399 boolean prev_locked = false;
400 boolean locked = false;
402 if(state.gps != null)
403 locked = state.gps.locked;
404 if (saved_state != null && saved_state.gps != null)
405 prev_locked = saved_state.gps.locked;
406 if (prev_locked != locked) {
407 String currentTab = mTabHost.getCurrentTabTag();
409 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
411 if (currentTab.equals(tab_flight_name)) mTabHost.setCurrentTabByTag(tab_pad_name);
415 if (prev_state != state.state()) {
416 String currentTab = mTabHost.getCurrentTabTag();
417 switch (state.state()) {
418 case AltosLib.ao_flight_boost:
419 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
421 case AltosLib.ao_flight_landed:
422 if (currentTab.equals(tab_flight_name)) mTabHost.setCurrentTabByTag(tab_recover_name);
424 case AltosLib.ao_flight_stateless:
425 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
431 if (location != null && state.gps != null && state.gps.locked) {
433 if (location.hasAltitude())
434 altitude = location.getAltitude();
435 from_receiver = new AltosGreatCircle(location.getLatitude(),
436 location.getLongitude(),
443 if (saved_state == null || !same_string(saved_state.callsign, state.callsign)) {
444 mCallsignView.setText(state.callsign);
446 if (saved_state == null || state.serial != saved_state.serial) {
447 mSerialView.setText(String.format("%d", state.serial));
449 if (saved_state == null || state.flight != saved_state.flight) {
450 if (state.flight == AltosLib.MISSING)
451 mFlightView.setText("");
453 mFlightView.setText(String.format("%d", state.flight));
455 if (saved_state == null || state.state() != saved_state.state()) {
456 if (state.state() == AltosLib.ao_flight_stateless) {
457 mStateLayout.setVisibility(View.GONE);
459 mStateView.setText(state.state_name());
460 mStateLayout.setVisibility(View.VISIBLE);
463 if (saved_state == null || state.rssi != saved_state.rssi) {
464 mRSSIView.setText(String.format("%d", state.rssi));
468 for (AltosDroidTab mTab : mTabs)
469 mTab.update_ui(telem_state, state, from_receiver, location, mTab == mTabsAdapter.currentItem());
471 if (mAltosVoice != null)
472 mAltosVoice.tell(telem_state, state, from_receiver, location, (AltosDroidTab) mTabsAdapter.currentItem());
477 private void onTimerTick() {
479 mMessenger.send(Message.obtain(null, MSG_UPDATE_AGE));
480 } catch (RemoteException e) {
484 static String pos(double p, String pos, String neg) {
486 if (p == AltosLib.MISSING)
492 int deg = (int) Math.floor(p);
493 double min = (p - Math.floor(p)) * 60.0;
494 return String.format("%d°%9.4f\" %s", deg, min, h);
497 static String number(String format, double value) {
498 if (value == AltosLib.MISSING)
500 return String.format(format, value);
503 static String integer(String format, int value) {
504 if (value == AltosLib.MISSING)
506 return String.format(format, value);
509 private View create_tab_view(String label) {
510 LayoutInflater inflater = (LayoutInflater) this.getLayoutInflater();
511 View tab_view = inflater.inflate(R.layout.tab_layout, null);
512 TextView text_view = (TextView) tab_view.findViewById (R.id.tabLabel);
513 text_view.setText(label);
517 public void set_map_source(int source) {
518 for (AltosDroidTab mTab : mTabs)
519 mTab.set_map_source(source);
523 public void onCreate(Bundle savedInstanceState) {
524 super.onCreate(savedInstanceState);
525 AltosDebug.init(this);
526 AltosDebug.debug("+++ ON CREATE +++");
528 // Initialise preferences
529 AltosDroidPreferences.init(this);
531 fm = getSupportFragmentManager();
533 // Set up the window layout
534 setContentView(R.layout.altosdroid);
536 // Create the Tabs and ViewPager
537 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
540 mViewPager = (AltosViewPager)findViewById(R.id.pager);
541 mViewPager.setOffscreenPageLimit(4);
543 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
545 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_pad_name).setIndicator(create_tab_view("Pad")), TabPad.class, null);
546 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_flight_name).setIndicator(create_tab_view("Flight")), TabFlight.class, null);
547 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_recover_name).setIndicator(create_tab_view("Recover")), TabRecover.class, null);
548 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_map_name).setIndicator(create_tab_view("Map")), TabMap.class, null);
550 // Display the Version
551 mVersion = (TextView) findViewById(R.id.version);
552 mVersion.setText("Version: " + BuildInfo.version +
553 " Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
554 " (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
556 mCallsignView = (TextView) findViewById(R.id.callsign_value);
557 mRSSIView = (TextView) findViewById(R.id.rssi_value);
558 mSerialView = (TextView) findViewById(R.id.serial_value);
559 mFlightView = (TextView) findViewById(R.id.flight_value);
560 mStateLayout = (RelativeLayout) findViewById(R.id.state_container);
561 mStateView = (TextView) findViewById(R.id.state_value);
562 mAgeView = (TextView) findViewById(R.id.age_value);
563 mAgeNewColor = mAgeView.getTextColors().getDefaultColor();
564 mAgeOldColor = getResources().getColor(R.color.old_color);
567 private void ensureBluetooth() {
568 // Get local Bluetooth adapter
569 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
571 /* if there is a BT adapter and it isn't turned on, then turn it on */
572 if (mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) {
573 Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
574 startActivityForResult(enableIntent, AltosDroid.REQUEST_ENABLE_BT);
578 private boolean check_usb() {
579 UsbDevice device = AltosUsb.find_device(this, AltosLib.product_basestation);
581 if (device != null) {
582 Intent i = new Intent(this, AltosDroid.class);
583 PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent("hello world", null, this, AltosDroid.class), 0);
585 if (AltosUsb.request_permission(this, device, pi)) {
588 start_with_usb = true;
592 start_with_usb = false;
597 private void noticeIntent(Intent intent) {
599 /* Ok, this is pretty convenient.
601 * When a USB device is plugged in, and our 'hotplug'
602 * intent registration fires, we get an Intent with
605 * When we start up and see a usb device and request
606 * permission to access it, that queues a
607 * PendingIntent, which has the EXTRA_DEVICE added in,
608 * along with the EXTRA_PERMISSION_GRANTED field as
611 * So, in both cases, we get the device name using the
612 * same call. We check to see if access was granted,
613 * in which case we ignore the device field and do our
614 * usual startup thing.
617 UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
618 boolean granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, true);
620 AltosDebug.debug("intent %s device %s granted %s", intent, device, granted);
625 if (device != null) {
626 AltosDebug.debug("intent has usb device " + device.toString());
630 /* 'granted' is only false if this intent came
631 * from the request_permission call and
632 * permission was denied. In which case, we
633 * don't want to loop forever...
636 AltosDebug.debug("check for a USB device at startup");
640 AltosDebug.debug("Starting by looking for bluetooth devices");
646 public void onStart() {
648 AltosDebug.debug("++ ON START ++");
652 noticeIntent(getIntent());
654 // Start Telemetry Service
655 String action = start_with_usb ? ACTION_USB : ACTION_BLUETOOTH;
657 startService(new Intent(action, null, AltosDroid.this, TelemetryService.class));
661 if (mAltosVoice == null)
662 mAltosVoice = new AltosVoice(this);
667 public void onNewIntent(Intent intent) {
668 super.onNewIntent(intent);
669 AltosDebug.debug("onNewIntent");
670 noticeIntent(intent);
674 public void onResume() {
676 AltosDebug.debug("+ ON RESUME +");
678 // Listen for GPS and Network position updates
679 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
680 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
682 location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
684 AltosDebug.debug("Resume, location is %f,%f\n",
685 location.getLatitude(),
686 location.getLongitude());
688 update_ui(telemetry_state, saved_state);
692 public void onPause() {
694 AltosDebug.debug("- ON PAUSE -");
695 // Stop listening for location updates
696 ((LocationManager) getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
700 public void onStop() {
702 AltosDebug.debug("-- ON STOP --");
706 public void onDestroy() {
708 AltosDebug.debug("--- ON DESTROY ---");
711 if (mAltosVoice != null) {
718 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
719 AltosDebug.debug("onActivityResult " + resultCode);
720 switch (requestCode) {
721 case REQUEST_CONNECT_DEVICE:
722 // When DeviceListActivity returns with a device to connect to
723 if (resultCode == Activity.RESULT_OK) {
727 case REQUEST_ENABLE_BT:
728 // When the request to enable Bluetooth returns
729 if (resultCode == Activity.RESULT_OK) {
730 // Bluetooth is now enabled, so set up a chat session
732 AltosDebug.debug("BT enabled");
733 bluetoothEnabled(data);
735 // User did not enable Bluetooth or an error occured
736 AltosDebug.debug("BT not enabled");
739 case REQUEST_MAP_TYPE:
740 if (resultCode == Activity.RESULT_OK)
746 private void connectUsb(UsbDevice device) {
747 if (mService == null)
748 pending_usb_device = device;
750 // Attempt to connect to the device
752 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, device));
753 AltosDebug.debug("Sent OPEN_USB message");
754 } catch (RemoteException e) {
755 AltosDebug.debug("connect device message failed");
760 private void bluetoothEnabled(Intent data) {
762 mService.send(Message.obtain(null, TelemetryService.MSG_BLUETOOTH_ENABLED, null));
763 } catch (RemoteException e) {
764 AltosDebug.debug("send BT enabled message failed");
768 private void connectDevice(Intent data) {
769 // Attempt to connect to the device
771 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
772 String name = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_NAME);
774 AltosDebug.debug("Connecting to " + address + " " + name);
775 DeviceAddress a = new DeviceAddress(address, name);
776 mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, a));
777 AltosDebug.debug("Sent connecting message");
778 } catch (RemoteException e) {
779 AltosDebug.debug("connect device message failed");
783 private void disconnectDevice() {
785 mService.send(Message.obtain(null, TelemetryService.MSG_DISCONNECT, null));
786 } catch (RemoteException e) {
790 private void set_map_type(Intent data) {
791 int type = data.getIntExtra(MapTypeActivity.EXTRA_MAP_TYPE, -1);
793 AltosDebug.debug("intent set_map_type %d\n", type);
796 for (AltosDroidTab mTab : mTabs)
797 mTab.set_map_type(map_type);
802 public boolean onCreateOptionsMenu(Menu menu) {
803 MenuInflater inflater = getMenuInflater();
804 inflater.inflate(R.menu.option_menu, menu);
808 void setFrequency(double freq) {
810 mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
812 } catch (RemoteException e) {
816 void setFrequency(String freq) {
818 setFrequency (AltosParse.parse_double_net(freq.substring(11, 17)));
819 } catch (ParseException e) {
823 void setBaud(int baud) {
825 mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD, baud));
827 } catch (RemoteException e) {
831 void setBaud(String baud) {
833 int value = Integer.parseInt(baud);
834 int rate = AltosLib.ao_telemetry_rate_38400;
837 rate = AltosLib.ao_telemetry_rate_2400;
840 rate = AltosLib.ao_telemetry_rate_9600;
843 rate = AltosLib.ao_telemetry_rate_38400;
847 } catch (NumberFormatException e) {
851 void select_tracker(int serial) {
854 AltosDebug.debug("select tracker %d\n", serial);
856 if (serial == selected_serial) {
857 AltosDebug.debug("%d already selected\n", serial);
862 for (i = 0; i < serials.length; i++)
863 if (serials[i] == serial)
866 if (i == serials.length) {
867 AltosDebug.debug("attempt to select unknown tracker %d\n", serial);
872 current_serial = selected_serial = serial;
876 void touch_trackers(Integer[] serials) {
877 AlertDialog.Builder builder_tracker = new AlertDialog.Builder(this);
878 builder_tracker.setTitle("Select Tracker");
879 final String[] trackers = new String[serials.length + 1];
880 trackers[0] = "Auto";
881 for (int i = 0; i < serials.length; i++)
882 trackers[i+1] = String.format("%d", serials[i]);
883 builder_tracker.setItems(trackers,
884 new DialogInterface.OnClickListener() {
885 public void onClick(DialogInterface dialog, int item) {
889 select_tracker(Integer.parseInt(trackers[item]));
892 AlertDialog alert_tracker = builder_tracker.create();
893 alert_tracker.show();
896 void delete_track(int serial) {
898 mService.send(Message.obtain(null, TelemetryService.MSG_DELETE_SERIAL, (Integer) serial));
899 } catch (Exception ex) {
904 public boolean onOptionsItemSelected(MenuItem item) {
905 Intent serverIntent = null;
906 switch (item.getItemId()) {
907 case R.id.connect_scan:
909 // Launch the DeviceListActivity to see devices and do scan
910 serverIntent = new Intent(this, DeviceListActivity.class);
911 startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
913 case R.id.disconnect:
914 /* Disconnect the device
919 AltosDebug.debug("R.id.quit");
923 case R.id.select_freq:
924 // Set the TBT radio frequency
926 final String[] frequencies = {
927 "Channel 0 (434.550MHz)",
928 "Channel 1 (434.650MHz)",
929 "Channel 2 (434.750MHz)",
930 "Channel 3 (434.850MHz)",
931 "Channel 4 (434.950MHz)",
932 "Channel 5 (435.050MHz)",
933 "Channel 6 (435.150MHz)",
934 "Channel 7 (435.250MHz)",
935 "Channel 8 (435.350MHz)",
936 "Channel 9 (435.450MHz)"
939 AlertDialog.Builder builder_freq = new AlertDialog.Builder(this);
940 builder_freq.setTitle("Pick a frequency");
941 builder_freq.setItems(frequencies,
942 new DialogInterface.OnClickListener() {
943 public void onClick(DialogInterface dialog, int item) {
944 setFrequency(frequencies[item]);
947 AlertDialog alert_freq = builder_freq.create();
950 case R.id.select_rate:
951 // Set the TBT baud rate
953 final String[] rates = {
959 AlertDialog.Builder builder_rate = new AlertDialog.Builder(this);
960 builder_rate.setTitle("Pick a baud rate");
961 builder_rate.setItems(rates,
962 new DialogInterface.OnClickListener() {
963 public void onClick(DialogInterface dialog, int item) {
964 setBaud(rates[item]);
967 AlertDialog alert_rate = builder_rate.create();
970 case R.id.change_units:
971 boolean imperial = AltosPreferences.imperial_units();
972 AltosPreferences.set_imperial_units(!imperial);
974 case R.id.preload_maps:
975 serverIntent = new Intent(this, PreloadMapActivity.class);
976 startActivityForResult(serverIntent, REQUEST_PRELOAD_MAPS);
979 serverIntent = new Intent(this, MapTypeActivity.class);
980 startActivityForResult(serverIntent, REQUEST_MAP_TYPE);
982 case R.id.map_source:
983 int source = AltosDroidPreferences.map_source();
984 int new_source = source == AltosDroidPreferences.MAP_SOURCE_ONLINE ? AltosDroidPreferences.MAP_SOURCE_OFFLINE : AltosDroidPreferences.MAP_SOURCE_ONLINE;
985 AltosDroidPreferences.set_map_source(new_source);
986 set_map_source(new_source);
988 case R.id.select_tracker:
989 if (serials != null) {
990 String[] trackers = new String[serials.length+1];
991 trackers[0] = "Auto";
992 for (int i = 0; i < serials.length; i++)
993 trackers[i+1] = String.format("%d", serials[i]);
994 AlertDialog.Builder builder_serial = new AlertDialog.Builder(this);
995 builder_serial.setTitle("Select a tracker");
996 builder_serial.setItems(trackers,
997 new DialogInterface.OnClickListener() {
998 public void onClick(DialogInterface dialog, int item) {
1002 select_tracker(serials[item-1]);
1005 AlertDialog alert_serial = builder_serial.create();
1006 alert_serial.show();
1010 case R.id.delete_track:
1011 if (serials != null) {
1012 String[] trackers = new String[serials.length];
1013 for (int i = 0; i < serials.length; i++)
1014 trackers[i] = String.format("%d", serials[i]);
1015 AlertDialog.Builder builder_serial = new AlertDialog.Builder(this);
1016 builder_serial.setTitle("Delete a track");
1017 builder_serial.setItems(trackers,
1018 new DialogInterface.OnClickListener() {
1019 public void onClick(DialogInterface dialog, int item) {
1020 delete_track(serials[item]);
1023 AlertDialog alert_serial = builder_serial.create();
1024 alert_serial.show();
1032 static String direction(AltosGreatCircle from_receiver,
1033 Location receiver) {
1034 if (from_receiver == null)
1037 if (receiver == null)
1040 if (!receiver.hasBearing())
1043 float bearing = receiver.getBearing();
1044 float heading = (float) from_receiver.bearing - bearing;
1046 while (heading <= -180.0f)
1048 while (heading > 180.0f)
1051 int iheading = (int) (heading + 0.5f);
1053 if (-1 < iheading && iheading < 1)
1055 else if (iheading < -179 || 179 < iheading)
1057 else if (iheading < 0)
1058 return String.format("left %d°", -iheading);
1060 return String.format("right %d°", iheading);
1063 public void onLocationChanged(Location location) {
1064 this.location = location;
1065 AltosDebug.debug("Location changed to %f,%f",
1066 location.getLatitude(),
1067 location.getLongitude());
1068 update_ui(telemetry_state, saved_state);
1071 public void onStatusChanged(String provider, int status, Bundle extras) {
1072 AltosDebug.debug("Location status now %d\n", status);
1075 public void onProviderEnabled(String provider) {
1076 AltosDebug.debug("Location provider enabled %s\n", provider);
1079 public void onProviderDisabled(String provider) {
1080 AltosDebug.debug("Location provider disabled %s\n", provider);