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; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
19 package org.altusmetrum.AltosDroid;
21 import java.lang.ref.WeakReference;
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.*;
46 import android.widget.*;
47 import android.app.AlertDialog;
48 import android.location.Location;
49 import android.location.LocationManager;
50 import android.location.LocationListener;
51 import android.hardware.usb.*;
52 import android.graphics.*;
53 import android.graphics.drawable.*;
55 import org.altusmetrum.altoslib_11.*;
57 public class AltosDroid extends FragmentActivity implements AltosUnitsListener, LocationListener {
59 // Actions sent to the telemetry server at startup time
61 public static final String ACTION_BLUETOOTH = "org.altusmetrum.AltosDroid.BLUETOOTH";
62 public static final String ACTION_USB = "org.altusmetrum.AltosDroid.USB";
64 // Message types received by our Handler
66 public static final int MSG_STATE = 1;
67 public static final int MSG_UPDATE_AGE = 2;
68 public static final int MSG_IDLE_MODE = 3;
69 public static final int MSG_IGNITER_STATUS = 4;
71 // Intent request codes
72 public static final int REQUEST_CONNECT_DEVICE = 1;
73 public static final int REQUEST_ENABLE_BT = 2;
74 public static final int REQUEST_PRELOAD_MAPS = 3;
75 public static final int REQUEST_IDLE_MODE = 5;
76 public static final int REQUEST_IGNITERS = 6;
77 public static final int REQUEST_SETUP = 7;
79 public static final String EXTRA_IDLE_MODE = "idle_mode";
80 public static final String EXTRA_IDLE_RESULT = "idle_result";
81 public static final String EXTRA_TELEMETRY_SERVICE = "telemetry_service";
84 public static final int SETUP_BAUD = 1;
85 public static final int SETUP_UNITS = 2;
86 public static final int SETUP_MAP_SOURCE = 4;
87 public static final int SETUP_MAP_TYPE = 8;
89 public static FragmentManager fm;
91 private BluetoothAdapter mBluetoothAdapter = null;
93 // Flight state values
94 private TextView mCallsignView;
95 private TextView mRSSIView;
96 private TextView mSerialView;
97 private TextView mFlightView;
98 private RelativeLayout mStateLayout;
99 private TextView mStateView;
100 private TextView mAgeView;
101 private boolean mAgeViewOld;
102 private int mAgeNewColor;
103 private int mAgeOldColor;
105 public static final String tab_pad_name = "pad";
106 public static final String tab_flight_name = "flight";
107 public static final String tab_recover_name = "recover";
108 public static final String tab_map_name = "map";
110 // field to display the version at the bottom of the screen
111 private TextView mVersion;
113 private boolean idle_mode = false;
115 public Location location = null;
119 AltosViewPager mViewPager;
120 TabsAdapter mTabsAdapter;
121 ArrayList<AltosDroidTab> mTabs = new ArrayList<AltosDroidTab>();
124 // Timer and Saved flight state for Age calculation
126 AltosState saved_state;
127 TelemetryState telemetry_state;
130 UsbDevice pending_usb_device;
131 boolean start_with_usb;
134 private boolean mIsBound = false;
135 private Messenger mService = null;
136 final Messenger mMessenger = new Messenger(new IncomingHandler(this));
139 private AltosVoice mAltosVoice = null;
141 // The Handler that gets information back from the Telemetry Service
142 static class IncomingHandler extends Handler {
143 private final WeakReference<AltosDroid> mAltosDroid;
144 IncomingHandler(AltosDroid ad) { mAltosDroid = new WeakReference<AltosDroid>(ad); }
147 public void handleMessage(Message msg) {
148 AltosDroid ad = mAltosDroid.get();
152 if (msg.obj == null) {
153 AltosDebug.debug("telemetry_state null!");
156 ad.update_state((TelemetryState) msg.obj);
162 ad.idle_mode = (Boolean) msg.obj;
163 ad.update_state(null);
170 private ServiceConnection mConnection = new ServiceConnection() {
171 public void onServiceConnected(ComponentName className, IBinder service) {
172 mService = new Messenger(service);
174 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
175 msg.replyTo = mMessenger;
177 } catch (RemoteException e) {
178 // In this case the service has crashed before we could even do anything with it
180 if (pending_usb_device != null) {
182 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, pending_usb_device));
183 pending_usb_device = null;
184 } catch (RemoteException e) {
189 public void onServiceDisconnected(ComponentName className) {
190 // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
195 void doBindService() {
196 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
200 void doUnbindService() {
202 // If we have received the service, and hence registered with it, then now is the time to unregister.
203 if (mService != null) {
205 Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
206 msg.replyTo = mMessenger;
208 } catch (RemoteException e) {
209 // There is nothing special we need to do if the service has crashed.
212 // Detach our existing connection.
213 unbindService(mConnection);
218 public void registerTab(AltosDroidTab mTab) {
222 public void unregisterTab(AltosDroidTab mTab) {
226 public void units_changed(boolean imperial_units) {
227 for (AltosDroidTab mTab : mTabs)
228 mTab.units_changed(imperial_units);
231 void update_title(TelemetryState telemetry_state) {
232 switch (telemetry_state.connect) {
233 case TelemetryState.CONNECT_CONNECTED:
234 if (telemetry_state.config != null) {
235 String str = String.format("S/N %d %6.3f MHz%s", telemetry_state.config.serial,
236 telemetry_state.frequency, idle_mode ? " (idle)" : "");
237 if (telemetry_state.telemetry_rate != AltosLib.ao_telemetry_rate_38400)
238 str = str.concat(String.format(" %d bps",
239 AltosLib.ao_telemetry_rate_values[telemetry_state.telemetry_rate]));
242 setTitle(R.string.title_connected_to);
245 case TelemetryState.CONNECT_CONNECTING:
246 if (telemetry_state.address != null)
247 setTitle(String.format("Connecting to %s...", telemetry_state.address.name));
249 setTitle("Connecting to something...");
251 case TelemetryState.CONNECT_DISCONNECTED:
252 case TelemetryState.CONNECT_NONE:
253 setTitle(R.string.title_not_connected);
261 timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 1000L, 1000L);
273 int selected_serial = 0;
277 void set_switch_time() {
278 switch_time = System.currentTimeMillis();
282 boolean registered_units_listener;
284 void update_state(TelemetryState new_telemetry_state) {
286 if (new_telemetry_state != null)
287 telemetry_state = new_telemetry_state;
289 if (selected_serial != 0)
290 current_serial = selected_serial;
292 if (current_serial == 0)
293 current_serial = telemetry_state.latest_serial;
295 if (!registered_units_listener) {
296 registered_units_listener = true;
297 AltosPreferences.register_units_listener(this);
300 serials = telemetry_state.states.keySet().toArray(new Integer[0]);
301 Arrays.sort(serials);
303 update_title(telemetry_state);
305 AltosState state = null;
308 if (telemetry_state.states.containsKey(current_serial)) {
309 state = telemetry_state.states.get(current_serial);
310 int age = state_age(state);
313 if (current_serial == selected_serial)
315 else if (switch_time != 0 && (switch_time - state.received_time) > 0)
320 AltosState newest_state = null;
323 for (int serial : telemetry_state.states.keySet()) {
324 AltosState existing = telemetry_state.states.get(serial);
325 int existing_age = state_age(existing);
327 if (newest_state == null || existing_age < newest_age) {
328 newest_state = existing;
329 newest_age = existing_age;
333 if (newest_state != null)
334 state = newest_state;
337 update_ui(telemetry_state, state);
342 boolean same_string(String a, String b) {
355 private int blend_component(int a, int b, double r, int shift, int mask) {
356 return ((int) (((a >> shift) & mask) * r + ((b >> shift) & mask) * (1 - r)) & mask) << shift;
358 private int blend_color(int a, int b, double r) {
359 return (blend_component(a, b, r, 0, 0xff) |
360 blend_component(a, b, r, 8, 0xff) |
361 blend_component(a, b, r, 16, 0xff) |
362 blend_component(a, b, r, 24, 0xff));
365 int state_age(AltosState state) {
366 return (int) ((System.currentTimeMillis() - state.received_time + 500) / 1000);
369 void set_screen_on(int age) {
371 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
373 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
377 if (saved_state != null) {
378 int age = state_age(saved_state);
380 double age_scale = age / 100.0;
385 mAgeView.setTextColor(blend_color(mAgeOldColor, mAgeNewColor, age_scale));
391 text = String.format("%ds", age);
392 else if (age < 60 * 60)
393 text = String.format("%dm", age / 60);
394 else if (age < 60 * 60 * 24)
395 text = String.format("%dh", age / (60 * 60));
397 text = String.format("%dd", age / (24 * 60 * 60));
398 mAgeView.setText(text);
402 void update_ui(TelemetryState telem_state, AltosState state) {
404 int prev_state = AltosLib.ao_flight_invalid;
406 AltosGreatCircle from_receiver = null;
408 if (saved_state != null)
409 prev_state = saved_state.state();
412 set_screen_on(state_age(state));
414 if (state.state() == AltosLib.ao_flight_stateless) {
415 boolean prev_locked = false;
416 boolean locked = false;
418 if(state.gps != null)
419 locked = state.gps.locked;
420 if (saved_state != null && saved_state.gps != null)
421 prev_locked = saved_state.gps.locked;
422 if (prev_locked != locked) {
423 String currentTab = mTabHost.getCurrentTabTag();
425 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
427 if (currentTab.equals(tab_flight_name)) mTabHost.setCurrentTabByTag(tab_pad_name);
431 if (prev_state != state.state()) {
432 String currentTab = mTabHost.getCurrentTabTag();
433 switch (state.state()) {
434 case AltosLib.ao_flight_boost:
435 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
437 case AltosLib.ao_flight_landed:
438 if (currentTab.equals(tab_flight_name)) mTabHost.setCurrentTabByTag(tab_recover_name);
440 case AltosLib.ao_flight_stateless:
441 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
447 if (location != null && state.gps != null && state.gps.locked) {
449 if (location.hasAltitude())
450 altitude = location.getAltitude();
451 from_receiver = new AltosGreatCircle(location.getLatitude(),
452 location.getLongitude(),
459 if (saved_state == null || !same_string(saved_state.callsign, state.callsign)) {
460 mCallsignView.setText(state.callsign);
462 if (saved_state == null || state.serial != saved_state.serial) {
463 if (state.serial == AltosLib.MISSING)
464 mSerialView.setText("");
466 mSerialView.setText(String.format("%d", state.serial));
468 if (saved_state == null || state.flight != saved_state.flight) {
469 if (state.flight == AltosLib.MISSING)
470 mFlightView.setText("");
472 mFlightView.setText(String.format("%d", state.flight));
474 if (saved_state == null || state.state() != saved_state.state()) {
475 if (state.state() == AltosLib.ao_flight_stateless) {
476 mStateLayout.setVisibility(View.GONE);
478 mStateView.setText(state.state_name());
479 mStateLayout.setVisibility(View.VISIBLE);
482 if (saved_state == null || state.rssi != saved_state.rssi) {
483 if (state.rssi == AltosLib.MISSING)
484 mRSSIView.setText("");
486 mRSSIView.setText(String.format("%d", state.rssi));
490 for (AltosDroidTab mTab : mTabs)
491 mTab.update_ui(telem_state, state, from_receiver, location, mTab == mTabsAdapter.currentItem());
493 if (mAltosVoice != null)
494 mAltosVoice.tell(telem_state, state, from_receiver, location, (AltosDroidTab) mTabsAdapter.currentItem());
499 private void onTimerTick() {
501 mMessenger.send(Message.obtain(null, MSG_UPDATE_AGE));
502 } catch (RemoteException e) {
506 static String pos(double p, String pos, String neg) {
508 if (p == AltosLib.MISSING)
514 int deg = (int) Math.floor(p);
515 double min = (p - Math.floor(p)) * 60.0;
516 return String.format("%d°%9.4f\" %s", deg, min, h);
519 static String number(String format, double value) {
520 if (value == AltosLib.MISSING)
522 return String.format(format, value);
525 static String integer(String format, int value) {
526 if (value == AltosLib.MISSING)
528 return String.format(format, value);
531 private View create_tab_view(String label) {
532 LayoutInflater inflater = (LayoutInflater) this.getLayoutInflater();
533 View tab_view = inflater.inflate(R.layout.tab_layout, null);
534 TextView text_view = (TextView) tab_view.findViewById (R.id.tabLabel);
535 text_view.setText(label);
540 public void onCreate(Bundle savedInstanceState) {
541 super.onCreate(savedInstanceState);
542 AltosDebug.init(this);
543 AltosDebug.debug("+++ ON CREATE +++");
545 // Initialise preferences
546 AltosDroidPreferences.init(this);
548 fm = getSupportFragmentManager();
550 // Set up the window layout
551 setContentView(R.layout.altosdroid);
553 // Create the Tabs and ViewPager
554 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
557 mViewPager = (AltosViewPager)findViewById(R.id.pager);
558 mViewPager.setOffscreenPageLimit(4);
560 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
562 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_pad_name).setIndicator(create_tab_view("Pad")), TabPad.class, null);
563 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_flight_name).setIndicator(create_tab_view("Flight")), TabFlight.class, null);
564 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_recover_name).setIndicator(create_tab_view("Recover")), TabRecover.class, null);
565 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_map_name).setIndicator(create_tab_view("Map")), TabMap.class, null);
567 // Display the Version
568 mVersion = (TextView) findViewById(R.id.version);
569 mVersion.setText("Version: " + BuildInfo.version +
570 " Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
571 " (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
573 mCallsignView = (TextView) findViewById(R.id.callsign_value);
574 mRSSIView = (TextView) findViewById(R.id.rssi_value);
575 mSerialView = (TextView) findViewById(R.id.serial_value);
576 mFlightView = (TextView) findViewById(R.id.flight_value);
577 mStateLayout = (RelativeLayout) findViewById(R.id.state_container);
578 mStateView = (TextView) findViewById(R.id.state_value);
579 mAgeView = (TextView) findViewById(R.id.age_value);
580 mAgeNewColor = mAgeView.getTextColors().getDefaultColor();
581 mAgeOldColor = getResources().getColor(R.color.old_color);
584 private void ensureBluetooth() {
585 // Get local Bluetooth adapter
586 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
588 /* if there is a BT adapter and it isn't turned on, then turn it on */
589 if (mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) {
590 Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
591 startActivityForResult(enableIntent, AltosDroid.REQUEST_ENABLE_BT);
595 private boolean check_usb() {
596 UsbDevice device = AltosUsb.find_device(this, AltosLib.product_basestation);
598 if (device != null) {
599 Intent i = new Intent(this, AltosDroid.class);
600 PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent("hello world", null, this, AltosDroid.class), 0);
602 if (AltosUsb.request_permission(this, device, pi)) {
605 start_with_usb = true;
609 start_with_usb = false;
614 private void noticeIntent(Intent intent) {
616 /* Ok, this is pretty convenient.
618 * When a USB device is plugged in, and our 'hotplug'
619 * intent registration fires, we get an Intent with
622 * When we start up and see a usb device and request
623 * permission to access it, that queues a
624 * PendingIntent, which has the EXTRA_DEVICE added in,
625 * along with the EXTRA_PERMISSION_GRANTED field as
628 * So, in both cases, we get the device name using the
629 * same call. We check to see if access was granted,
630 * in which case we ignore the device field and do our
631 * usual startup thing.
634 UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
635 boolean granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, true);
637 AltosDebug.debug("intent %s device %s granted %s", intent, device, granted);
642 if (device != null) {
643 AltosDebug.debug("intent has usb device " + device.toString());
647 /* 'granted' is only false if this intent came
648 * from the request_permission call and
649 * permission was denied. In which case, we
650 * don't want to loop forever...
653 AltosDebug.debug("check for a USB device at startup");
657 AltosDebug.debug("Starting by looking for bluetooth devices");
663 public void onStart() {
665 AltosDebug.debug("++ ON START ++");
669 noticeIntent(getIntent());
671 // Start Telemetry Service
672 String action = start_with_usb ? ACTION_USB : ACTION_BLUETOOTH;
674 startService(new Intent(action, null, AltosDroid.this, TelemetryService.class));
678 if (mAltosVoice == null)
679 mAltosVoice = new AltosVoice(this);
684 public void onNewIntent(Intent intent) {
685 super.onNewIntent(intent);
686 AltosDebug.debug("onNewIntent");
687 noticeIntent(intent);
691 public void onResume() {
693 AltosDebug.debug("+ ON RESUME +");
695 // Listen for GPS and Network position updates
696 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
697 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
699 location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
701 if (location != null)
702 AltosDebug.debug("Resume, location is %f,%f\n",
703 location.getLatitude(),
704 location.getLongitude());
706 update_ui(telemetry_state, saved_state);
710 public void onPause() {
712 AltosDebug.debug("- ON PAUSE -");
713 // Stop listening for location updates
714 ((LocationManager) getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
718 public void onStop() {
720 AltosDebug.debug("-- ON STOP --");
724 public void onDestroy() {
726 AltosDebug.debug("--- ON DESTROY ---");
729 if (mAltosVoice != null) {
736 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
737 AltosDebug.debug("onActivityResult " + resultCode);
738 switch (requestCode) {
739 case REQUEST_CONNECT_DEVICE:
740 // When DeviceListActivity returns with a device to connect to
741 if (resultCode == Activity.RESULT_OK) {
745 case REQUEST_ENABLE_BT:
746 // When the request to enable Bluetooth returns
747 if (resultCode == Activity.RESULT_OK) {
748 // Bluetooth is now enabled, so set up a chat session
750 AltosDebug.debug("BT enabled");
751 bluetoothEnabled(data);
753 // User did not enable Bluetooth or an error occured
754 AltosDebug.debug("BT not enabled");
757 case REQUEST_IDLE_MODE:
758 if (resultCode == Activity.RESULT_OK)
761 case REQUEST_IGNITERS:
764 if (resultCode == Activity.RESULT_OK)
765 note_setup_changes(data);
770 private void note_setup_changes(Intent data) {
771 int changes = data.getIntExtra(SetupActivity.EXTRA_SETUP_CHANGES, 0);
773 if ((changes & SETUP_BAUD) != 0) {
775 mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD,
776 AltosPreferences.telemetry_rate(1)));
777 } catch (RemoteException re) {
780 if ((changes & SETUP_UNITS) != 0) {
781 /* nothing to do here */
783 if ((changes & SETUP_MAP_SOURCE) != 0) {
784 /* nothing to do here */
786 if ((changes & SETUP_MAP_TYPE) != 0) {
787 /* nothing to do here */
792 private void connectUsb(UsbDevice device) {
793 if (mService == null)
794 pending_usb_device = device;
796 // Attempt to connect to the device
798 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, device));
799 AltosDebug.debug("Sent OPEN_USB message");
800 } catch (RemoteException e) {
801 AltosDebug.debug("connect device message failed");
806 private void bluetoothEnabled(Intent data) {
808 mService.send(Message.obtain(null, TelemetryService.MSG_BLUETOOTH_ENABLED, null));
809 } catch (RemoteException e) {
810 AltosDebug.debug("send BT enabled message failed");
814 private void connectDevice(Intent data) {
815 // Attempt to connect to the device
817 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
818 String name = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_NAME);
820 AltosDebug.debug("Connecting to " + address + " " + name);
821 DeviceAddress a = new DeviceAddress(address, name);
822 mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, a));
823 AltosDebug.debug("Sent connecting message");
824 } catch (RemoteException e) {
825 AltosDebug.debug("connect device message failed");
829 private void disconnectDevice(boolean remember) {
831 mService.send(Message.obtain(null, TelemetryService.MSG_DISCONNECT, (Boolean) remember));
832 } catch (RemoteException e) {
836 private void idle_mode(Intent data) {
837 int type = data.getIntExtra(IdleModeActivity.EXTRA_IDLE_RESULT, -1);
840 AltosDebug.debug("intent idle_mode %d", type);
842 case IdleModeActivity.IDLE_MODE_CONNECT:
843 msg = Message.obtain(null, TelemetryService.MSG_MONITOR_IDLE_START);
846 } catch (RemoteException re) {
849 case IdleModeActivity.IDLE_MODE_DISCONNECT:
850 msg = Message.obtain(null, TelemetryService.MSG_MONITOR_IDLE_STOP);
853 } catch (RemoteException re) {
856 case IdleModeActivity.IDLE_MODE_REBOOT:
857 msg = Message.obtain(null, TelemetryService.MSG_REBOOT);
860 } catch (RemoteException re) {
863 case IdleModeActivity.IDLE_MODE_IGNITERS:
864 Intent serverIntent = new Intent(this, IgniterActivity.class);
865 startActivityForResult(serverIntent, REQUEST_IGNITERS);
871 public boolean onCreateOptionsMenu(Menu menu) {
872 MenuInflater inflater = getMenuInflater();
873 inflater.inflate(R.menu.option_menu, menu);
877 void setFrequency(double freq) {
879 mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
881 } catch (RemoteException e) {
885 void setFrequency(AltosFrequency frequency) {
886 setFrequency (frequency.frequency);
889 void setBaud(int baud) {
891 mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD, baud));
893 } catch (RemoteException e) {
897 void setBaud(String baud) {
899 int value = Integer.parseInt(baud);
900 int rate = AltosLib.ao_telemetry_rate_38400;
903 rate = AltosLib.ao_telemetry_rate_2400;
906 rate = AltosLib.ao_telemetry_rate_9600;
909 rate = AltosLib.ao_telemetry_rate_38400;
913 } catch (NumberFormatException e) {
917 void select_tracker(int serial) {
920 AltosDebug.debug("select tracker %d\n", serial);
922 if (serial == selected_serial) {
923 AltosDebug.debug("%d already selected\n", serial);
928 for (i = 0; i < serials.length; i++)
929 if (serials[i] == serial)
932 if (i == serials.length) {
933 AltosDebug.debug("attempt to select unknown tracker %d\n", serial);
938 current_serial = selected_serial = serial;
942 void touch_trackers(Integer[] serials) {
943 AlertDialog.Builder builder_tracker = new AlertDialog.Builder(this);
944 builder_tracker.setTitle("Select Tracker");
945 final String[] trackers = new String[serials.length + 1];
946 trackers[0] = "Auto";
947 for (int i = 0; i < serials.length; i++)
948 trackers[i+1] = String.format("%d", serials[i]);
949 builder_tracker.setItems(trackers,
950 new DialogInterface.OnClickListener() {
951 public void onClick(DialogInterface dialog, int item) {
955 select_tracker(Integer.parseInt(trackers[item]));
958 AlertDialog alert_tracker = builder_tracker.create();
959 alert_tracker.show();
962 void delete_track(int serial) {
964 mService.send(Message.obtain(null, TelemetryService.MSG_DELETE_SERIAL, (Integer) serial));
965 } catch (Exception ex) {
970 public boolean onOptionsItemSelected(MenuItem item) {
971 Intent serverIntent = null;
972 switch (item.getItemId()) {
973 case R.id.connect_scan:
975 // Launch the DeviceListActivity to see devices and do scan
976 serverIntent = new Intent(this, DeviceListActivity.class);
977 startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
979 case R.id.disconnect:
980 /* Disconnect the device
982 disconnectDevice(false);
985 AltosDebug.debug("R.id.quit");
986 disconnectDevice(true);
990 serverIntent = new Intent(this, SetupActivity.class);
991 startActivityForResult(serverIntent, REQUEST_SETUP);
993 case R.id.select_freq:
994 // Set the TBT radio frequency
996 final AltosFrequency[] frequencies = AltosPreferences.common_frequencies();
997 String[] frequency_strings = new String[frequencies.length];
998 for (int i = 0; i < frequencies.length; i++)
999 frequency_strings[i] = frequencies[i].toString();
1001 AlertDialog.Builder builder_freq = new AlertDialog.Builder(this);
1002 builder_freq.setTitle("Pick a frequency");
1003 builder_freq.setItems(frequency_strings,
1004 new DialogInterface.OnClickListener() {
1005 public void onClick(DialogInterface dialog, int item) {
1006 setFrequency(frequencies[item]);
1009 AlertDialog alert_freq = builder_freq.create();
1012 case R.id.select_tracker:
1013 if (serials != null) {
1014 String[] trackers = new String[serials.length+1];
1015 trackers[0] = "Auto";
1016 for (int i = 0; i < serials.length; i++)
1017 trackers[i+1] = String.format("%d", serials[i]);
1018 AlertDialog.Builder builder_serial = new AlertDialog.Builder(this);
1019 builder_serial.setTitle("Select a tracker");
1020 builder_serial.setItems(trackers,
1021 new DialogInterface.OnClickListener() {
1022 public void onClick(DialogInterface dialog, int item) {
1026 select_tracker(serials[item-1]);
1029 AlertDialog alert_serial = builder_serial.create();
1030 alert_serial.show();
1034 case R.id.delete_track:
1035 if (serials != null) {
1036 String[] trackers = new String[serials.length];
1037 for (int i = 0; i < serials.length; i++)
1038 trackers[i] = String.format("%d", serials[i]);
1039 AlertDialog.Builder builder_serial = new AlertDialog.Builder(this);
1040 builder_serial.setTitle("Delete a track");
1041 builder_serial.setItems(trackers,
1042 new DialogInterface.OnClickListener() {
1043 public void onClick(DialogInterface dialog, int item) {
1044 delete_track(serials[item]);
1047 AlertDialog alert_serial = builder_serial.create();
1048 alert_serial.show();
1052 case R.id.idle_mode:
1053 serverIntent = new Intent(this, IdleModeActivity.class);
1054 serverIntent.putExtra(EXTRA_IDLE_MODE, idle_mode);
1055 startActivityForResult(serverIntent, REQUEST_IDLE_MODE);
1061 static String direction(AltosGreatCircle from_receiver,
1062 Location receiver) {
1063 if (from_receiver == null)
1066 if (receiver == null)
1069 if (!receiver.hasBearing())
1072 float bearing = receiver.getBearing();
1073 float heading = (float) from_receiver.bearing - bearing;
1075 while (heading <= -180.0f)
1077 while (heading > 180.0f)
1080 int iheading = (int) (heading + 0.5f);
1082 if (-1 < iheading && iheading < 1)
1084 else if (iheading < -179 || 179 < iheading)
1086 else if (iheading < 0)
1087 return String.format("left %d°", -iheading);
1089 return String.format("right %d°", iheading);
1092 public void onLocationChanged(Location location) {
1093 this.location = location;
1094 AltosDebug.debug("Location changed to %f,%f",
1095 location.getLatitude(),
1096 location.getLongitude());
1097 update_ui(telemetry_state, saved_state);
1100 public void onStatusChanged(String provider, int status, Bundle extras) {
1101 AltosDebug.debug("Location status now %d\n", status);
1104 public void onProviderEnabled(String provider) {
1105 AltosDebug.debug("Location provider enabled %s\n", provider);
1108 public void onProviderDisabled(String provider) {
1109 AltosDebug.debug("Location provider disabled %s\n", provider);