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.*;
66 SavedState(AltosState state) {
67 received_time = state.received_time;
68 this.state = state.state();
69 if (state.gps != null)
70 locked = state.gps.locked;
73 callsign = state.cal_data.callsign;
74 serial = state.cal_data.serial;
75 flight = state.cal_data.flight;
80 public class AltosDroid extends FragmentActivity implements AltosUnitsListener, LocationListener {
82 // Actions sent to the telemetry server at startup time
84 public static final String ACTION_BLUETOOTH = "org.altusmetrum.AltosDroid.BLUETOOTH";
85 public static final String ACTION_USB = "org.altusmetrum.AltosDroid.USB";
87 // Message types received by our Handler
89 public static final int MSG_STATE = 1;
90 public static final int MSG_UPDATE_AGE = 2;
91 public static final int MSG_IDLE_MODE = 3;
92 public static final int MSG_IGNITER_STATUS = 4;
94 // Intent request codes
95 public static final int REQUEST_CONNECT_DEVICE = 1;
96 public static final int REQUEST_ENABLE_BT = 2;
97 public static final int REQUEST_PRELOAD_MAPS = 3;
98 public static final int REQUEST_IDLE_MODE = 5;
99 public static final int REQUEST_IGNITERS = 6;
100 public static final int REQUEST_SETUP = 7;
102 public static final String EXTRA_IDLE_MODE = "idle_mode";
103 public static final String EXTRA_IDLE_RESULT = "idle_result";
104 public static final String EXTRA_TELEMETRY_SERVICE = "telemetry_service";
107 public static final int SETUP_BAUD = 1;
108 public static final int SETUP_UNITS = 2;
109 public static final int SETUP_MAP_SOURCE = 4;
110 public static final int SETUP_MAP_TYPE = 8;
112 public static FragmentManager fm;
114 private BluetoothAdapter mBluetoothAdapter = null;
116 // Flight state values
117 private TextView mCallsignView;
118 private TextView mRSSIView;
119 private TextView mSerialView;
120 private TextView mFlightView;
121 private RelativeLayout mStateLayout;
122 private TextView mStateView;
123 private TextView mAgeView;
124 private boolean mAgeViewOld;
125 private int mAgeNewColor;
126 private int mAgeOldColor;
128 public static final String tab_pad_name = "pad";
129 public static final String tab_flight_name = "flight";
130 public static final String tab_recover_name = "recover";
131 public static final String tab_map_name = "map";
133 // field to display the version at the bottom of the screen
134 private TextView mVersion;
136 private boolean idle_mode = false;
138 public Location location = null;
140 private AltosState state;
141 private SavedState saved_state;
145 AltosViewPager mViewPager;
146 TabsAdapter mTabsAdapter;
147 ArrayList<AltosDroidTab> mTabs = new ArrayList<AltosDroidTab>();
150 // Timer and Saved flight state for Age calculation
153 TelemetryState telemetry_state;
156 UsbDevice pending_usb_device;
157 boolean start_with_usb;
160 private boolean mIsBound = false;
161 private Messenger mService = null;
162 final Messenger mMessenger = new Messenger(new IncomingHandler(this));
165 private AltosVoice mAltosVoice = null;
167 // The Handler that gets information back from the Telemetry Service
168 static class IncomingHandler extends Handler {
169 private final WeakReference<AltosDroid> mAltosDroid;
170 IncomingHandler(AltosDroid ad) { mAltosDroid = new WeakReference<AltosDroid>(ad); }
173 public void handleMessage(Message msg) {
174 AltosDroid ad = mAltosDroid.get();
178 if (msg.obj == null) {
179 AltosDebug.debug("telemetry_state null!");
182 ad.update_state((TelemetryState) msg.obj);
188 ad.idle_mode = (Boolean) msg.obj;
189 ad.update_state(null);
196 private ServiceConnection mConnection = new ServiceConnection() {
197 public void onServiceConnected(ComponentName className, IBinder service) {
198 mService = new Messenger(service);
200 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
201 msg.replyTo = mMessenger;
203 } catch (RemoteException e) {
204 // In this case the service has crashed before we could even do anything with it
206 if (pending_usb_device != null) {
208 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, pending_usb_device));
209 pending_usb_device = null;
210 } catch (RemoteException e) {
215 public void onServiceDisconnected(ComponentName className) {
216 // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
221 void doBindService() {
222 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
226 void doUnbindService() {
228 // If we have received the service, and hence registered with it, then now is the time to unregister.
229 if (mService != null) {
231 Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
232 msg.replyTo = mMessenger;
234 } catch (RemoteException e) {
235 // There is nothing special we need to do if the service has crashed.
238 // Detach our existing connection.
239 unbindService(mConnection);
244 public void registerTab(AltosDroidTab mTab) {
248 public void unregisterTab(AltosDroidTab mTab) {
252 public void units_changed(boolean imperial_units) {
253 for (AltosDroidTab mTab : mTabs)
254 mTab.units_changed(imperial_units);
257 void update_title(TelemetryState telemetry_state) {
258 switch (telemetry_state.connect) {
259 case TelemetryState.CONNECT_CONNECTED:
260 if (telemetry_state.config != null) {
261 String str = String.format("S/N %d %6.3f MHz%s", telemetry_state.config.serial,
262 telemetry_state.frequency, idle_mode ? " (idle)" : "");
263 if (telemetry_state.telemetry_rate != AltosLib.ao_telemetry_rate_38400)
264 str = str.concat(String.format(" %d bps",
265 AltosLib.ao_telemetry_rate_values[telemetry_state.telemetry_rate]));
268 setTitle(R.string.title_connected_to);
271 case TelemetryState.CONNECT_CONNECTING:
272 if (telemetry_state.address != null)
273 setTitle(String.format("Connecting to %s...", telemetry_state.address.name));
275 setTitle("Connecting to something...");
277 case TelemetryState.CONNECT_DISCONNECTED:
278 case TelemetryState.CONNECT_NONE:
279 setTitle(R.string.title_not_connected);
287 timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 1000L, 1000L);
299 int selected_serial = 0;
303 void set_switch_time() {
304 switch_time = System.currentTimeMillis();
308 boolean registered_units_listener;
310 void update_state(TelemetryState new_telemetry_state) {
312 if (new_telemetry_state != null)
313 telemetry_state = new_telemetry_state;
315 if (selected_serial != 0)
316 current_serial = selected_serial;
318 if (current_serial == 0)
319 current_serial = telemetry_state.latest_serial;
321 if (!registered_units_listener) {
322 registered_units_listener = true;
323 AltosPreferences.register_units_listener(this);
326 serials = telemetry_state.states.keySet().toArray(new Integer[0]);
327 Arrays.sort(serials);
329 update_title(telemetry_state);
331 AltosState state = null;
334 if (telemetry_state.states.containsKey(current_serial)) {
335 state = telemetry_state.states.get(current_serial);
336 int age = state_age(state.received_time);
339 if (current_serial == selected_serial)
341 else if (switch_time != 0 && (switch_time - state.received_time) > 0)
346 AltosState newest_state = null;
349 for (int serial : telemetry_state.states.keySet()) {
350 AltosState existing = telemetry_state.states.get(serial);
351 int existing_age = state_age(existing.received_time);
353 if (newest_state == null || existing_age < newest_age) {
354 newest_state = existing;
355 newest_age = existing_age;
359 if (newest_state != null)
360 state = newest_state;
363 update_ui(telemetry_state, state, telemetry_state.quiet);
368 boolean same_string(String a, String b) {
381 private int blend_component(int a, int b, double r, int shift, int mask) {
382 return ((int) (((a >> shift) & mask) * r + ((b >> shift) & mask) * (1 - r)) & mask) << shift;
384 private int blend_color(int a, int b, double r) {
385 return (blend_component(a, b, r, 0, 0xff) |
386 blend_component(a, b, r, 8, 0xff) |
387 blend_component(a, b, r, 16, 0xff) |
388 blend_component(a, b, r, 24, 0xff));
391 int state_age(long received_time) {
392 return (int) ((System.currentTimeMillis() - received_time + 500) / 1000);
395 void set_screen_on(int age) {
397 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
399 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
403 if (saved_state != null) {
404 int age = state_age(saved_state.received_time);
406 double age_scale = age / 100.0;
411 mAgeView.setTextColor(blend_color(mAgeOldColor, mAgeNewColor, age_scale));
417 text = String.format("%ds", age);
418 else if (age < 60 * 60)
419 text = String.format("%dm", age / 60);
420 else if (age < 60 * 60 * 24)
421 text = String.format("%dh", age / (60 * 60));
423 text = String.format("%dd", age / (24 * 60 * 60));
424 mAgeView.setText(text);
428 void update_ui(TelemetryState telem_state, AltosState state, boolean quiet) {
432 int prev_state = AltosLib.ao_flight_invalid;
434 AltosGreatCircle from_receiver = null;
436 if (saved_state != null)
437 prev_state = saved_state.state;
440 set_screen_on(state_age(state.received_time));
442 if (state.state() == AltosLib.ao_flight_stateless) {
443 boolean prev_locked = false;
444 boolean locked = false;
446 if(state.gps != null)
447 locked = state.gps.locked;
448 if (saved_state != null)
449 prev_locked = saved_state.locked;
450 if (prev_locked != locked) {
451 String currentTab = mTabHost.getCurrentTabTag();
453 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
455 if (currentTab.equals(tab_flight_name)) mTabHost.setCurrentTabByTag(tab_pad_name);
459 if (prev_state != state.state()) {
460 String currentTab = mTabHost.getCurrentTabTag();
461 switch (state.state()) {
462 case AltosLib.ao_flight_boost:
463 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
465 case AltosLib.ao_flight_landed:
466 if (currentTab.equals(tab_flight_name)) mTabHost.setCurrentTabByTag(tab_recover_name);
468 case AltosLib.ao_flight_stateless:
469 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
475 if (location != null && state.gps != null && state.gps.locked) {
477 if (location.hasAltitude())
478 altitude = location.getAltitude();
479 from_receiver = new AltosGreatCircle(location.getLatitude(),
480 location.getLongitude(),
487 if (saved_state == null || !same_string(saved_state.callsign, state.cal_data.callsign)) {
488 mCallsignView.setText(state.cal_data.callsign);
490 if (saved_state == null || state.cal_data.serial != saved_state.serial) {
491 if (state.cal_data.serial == AltosLib.MISSING)
492 mSerialView.setText("");
494 mSerialView.setText(String.format("%d", state.cal_data.serial));
496 if (saved_state == null || state.cal_data.flight != saved_state.flight) {
497 if (state.cal_data.flight == AltosLib.MISSING)
498 mFlightView.setText("");
500 mFlightView.setText(String.format("%d", state.cal_data.flight));
502 if (saved_state == null || state.state() != saved_state.state) {
503 if (state.state() == AltosLib.ao_flight_stateless) {
504 mStateLayout.setVisibility(View.GONE);
506 mStateView.setText(state.state_name());
507 mStateLayout.setVisibility(View.VISIBLE);
510 if (saved_state == null || state.rssi != saved_state.rssi) {
511 if (state.rssi == AltosLib.MISSING)
512 mRSSIView.setText("");
514 mRSSIView.setText(String.format("%d", state.rssi));
516 saved_state = new SavedState(state);
519 for (AltosDroidTab mTab : mTabs)
520 mTab.update_ui(telem_state, state, from_receiver, location, mTab == mTabsAdapter.currentItem());
522 AltosDebug.debug("quiet %b\n", quiet);
523 if (mAltosVoice != null)
524 mAltosVoice.tell(telem_state, state, from_receiver, location, (AltosDroidTab) mTabsAdapter.currentItem(), quiet);
528 private void onTimerTick() {
530 mMessenger.send(Message.obtain(null, MSG_UPDATE_AGE));
531 } catch (RemoteException e) {
535 static String pos(double p, String pos, String neg) {
537 if (p == AltosLib.MISSING)
543 int deg = (int) Math.floor(p);
544 double min = (p - Math.floor(p)) * 60.0;
545 return String.format("%d°%9.4f\" %s", deg, min, h);
548 static String number(String format, double value) {
549 if (value == AltosLib.MISSING)
551 return String.format(format, value);
554 static String integer(String format, int value) {
555 if (value == AltosLib.MISSING)
557 return String.format(format, value);
560 private View create_tab_view(String label) {
561 LayoutInflater inflater = (LayoutInflater) this.getLayoutInflater();
562 View tab_view = inflater.inflate(R.layout.tab_layout, null);
563 TextView text_view = (TextView) tab_view.findViewById (R.id.tabLabel);
564 text_view.setText(label);
569 public void onCreate(Bundle savedInstanceState) {
570 super.onCreate(savedInstanceState);
571 AltosDebug.init(this);
572 AltosDebug.debug("+++ ON CREATE +++");
574 // Initialise preferences
575 AltosDroidPreferences.init(this);
577 fm = getSupportFragmentManager();
579 // Set up the window layout
580 setContentView(R.layout.altosdroid);
582 // Create the Tabs and ViewPager
583 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
586 mViewPager = (AltosViewPager)findViewById(R.id.pager);
587 mViewPager.setOffscreenPageLimit(4);
589 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
591 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_pad_name).setIndicator(create_tab_view("Pad")), TabPad.class, null);
592 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_flight_name).setIndicator(create_tab_view("Flight")), TabFlight.class, null);
593 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_recover_name).setIndicator(create_tab_view("Recover")), TabRecover.class, null);
594 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_map_name).setIndicator(create_tab_view("Map")), TabMap.class, null);
596 // Display the Version
597 mVersion = (TextView) findViewById(R.id.version);
598 mVersion.setText("Version: " + BuildInfo.version +
599 (AltosVersion.has_google_maps_api_key() ? " maps" : "") +
600 " Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
601 " (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
603 mCallsignView = (TextView) findViewById(R.id.callsign_value);
604 mRSSIView = (TextView) findViewById(R.id.rssi_value);
605 mSerialView = (TextView) findViewById(R.id.serial_value);
606 mFlightView = (TextView) findViewById(R.id.flight_value);
607 mStateLayout = (RelativeLayout) findViewById(R.id.state_container);
608 mStateView = (TextView) findViewById(R.id.state_value);
609 mAgeView = (TextView) findViewById(R.id.age_value);
610 mAgeNewColor = mAgeView.getTextColors().getDefaultColor();
611 mAgeOldColor = getResources().getColor(R.color.old_color);
614 private void ensureBluetooth() {
615 // Get local Bluetooth adapter
616 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
618 /* if there is a BT adapter and it isn't turned on, then turn it on */
619 if (mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) {
620 Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
621 startActivityForResult(enableIntent, AltosDroid.REQUEST_ENABLE_BT);
625 private boolean check_usb() {
626 UsbDevice device = AltosUsb.find_device(this, AltosLib.product_basestation);
628 if (device != null) {
629 Intent i = new Intent(this, AltosDroid.class);
630 PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent("hello world", null, this, AltosDroid.class), 0);
632 if (AltosUsb.request_permission(this, device, pi)) {
635 start_with_usb = true;
639 start_with_usb = false;
644 private void noticeIntent(Intent intent) {
646 /* Ok, this is pretty convenient.
648 * When a USB device is plugged in, and our 'hotplug'
649 * intent registration fires, we get an Intent with
652 * When we start up and see a usb device and request
653 * permission to access it, that queues a
654 * PendingIntent, which has the EXTRA_DEVICE added in,
655 * along with the EXTRA_PERMISSION_GRANTED field as
658 * So, in both cases, we get the device name using the
659 * same call. We check to see if access was granted,
660 * in which case we ignore the device field and do our
661 * usual startup thing.
664 UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
665 boolean granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, true);
667 AltosDebug.debug("intent %s device %s granted %s", intent, device, granted);
672 if (device != null) {
673 AltosDebug.debug("intent has usb device " + device.toString());
677 /* 'granted' is only false if this intent came
678 * from the request_permission call and
679 * permission was denied. In which case, we
680 * don't want to loop forever...
683 AltosDebug.debug("check for a USB device at startup");
687 AltosDebug.debug("Starting by looking for bluetooth devices");
693 public void onStart() {
695 AltosDebug.debug("++ ON START ++");
699 noticeIntent(getIntent());
701 // Start Telemetry Service
702 String action = start_with_usb ? ACTION_USB : ACTION_BLUETOOTH;
704 startService(new Intent(action, null, AltosDroid.this, TelemetryService.class));
708 if (mAltosVoice == null)
709 mAltosVoice = new AltosVoice(this);
714 public void onNewIntent(Intent intent) {
715 super.onNewIntent(intent);
716 AltosDebug.debug("onNewIntent");
717 noticeIntent(intent);
721 public void onResume() {
723 AltosDebug.debug("+ ON RESUME +");
725 // Listen for GPS and Network position updates
726 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
727 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
729 location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
731 if (location != null)
732 AltosDebug.debug("Resume, location is %f,%f\n",
733 location.getLatitude(),
734 location.getLongitude());
736 update_ui(telemetry_state, state, true);
740 public void onPause() {
742 AltosDebug.debug("- ON PAUSE -");
743 // Stop listening for location updates
744 ((LocationManager) getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
748 public void onStop() {
750 AltosDebug.debug("-- ON STOP --");
754 public void onDestroy() {
756 AltosDebug.debug("--- ON DESTROY ---");
759 if (mAltosVoice != null) {
766 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
767 AltosDebug.debug("onActivityResult " + resultCode);
768 switch (requestCode) {
769 case REQUEST_CONNECT_DEVICE:
770 // When DeviceListActivity returns with a device to connect to
771 if (resultCode == Activity.RESULT_OK) {
775 case REQUEST_ENABLE_BT:
776 // When the request to enable Bluetooth returns
777 if (resultCode == Activity.RESULT_OK) {
778 // Bluetooth is now enabled, so set up a chat session
780 AltosDebug.debug("BT enabled");
781 bluetoothEnabled(data);
783 // User did not enable Bluetooth or an error occured
784 AltosDebug.debug("BT not enabled");
787 case REQUEST_IDLE_MODE:
788 if (resultCode == Activity.RESULT_OK)
791 case REQUEST_IGNITERS:
794 if (resultCode == Activity.RESULT_OK)
795 note_setup_changes(data);
800 private void note_setup_changes(Intent data) {
801 int changes = data.getIntExtra(SetupActivity.EXTRA_SETUP_CHANGES, 0);
803 if ((changes & SETUP_BAUD) != 0) {
805 mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD,
806 AltosPreferences.telemetry_rate(1)));
807 } catch (RemoteException re) {
810 if ((changes & SETUP_UNITS) != 0) {
811 /* nothing to do here */
813 if ((changes & SETUP_MAP_SOURCE) != 0) {
814 /* nothing to do here */
816 if ((changes & SETUP_MAP_TYPE) != 0) {
817 /* nothing to do here */
822 private void connectUsb(UsbDevice device) {
823 if (mService == null)
824 pending_usb_device = device;
826 // Attempt to connect to the device
828 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, device));
829 AltosDebug.debug("Sent OPEN_USB message");
830 } catch (RemoteException e) {
831 AltosDebug.debug("connect device message failed");
836 private void bluetoothEnabled(Intent data) {
838 mService.send(Message.obtain(null, TelemetryService.MSG_BLUETOOTH_ENABLED, null));
839 } catch (RemoteException e) {
840 AltosDebug.debug("send BT enabled message failed");
844 private void connectDevice(Intent data) {
845 // Attempt to connect to the device
847 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
848 String name = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_NAME);
850 AltosDebug.debug("Connecting to " + address + " " + name);
851 DeviceAddress a = new DeviceAddress(address, name);
852 mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, a));
853 AltosDebug.debug("Sent connecting message");
854 } catch (RemoteException e) {
855 AltosDebug.debug("connect device message failed");
859 private void disconnectDevice(boolean remember) {
861 mService.send(Message.obtain(null, TelemetryService.MSG_DISCONNECT, (Boolean) remember));
862 } catch (RemoteException e) {
866 private void idle_mode(Intent data) {
867 int type = data.getIntExtra(IdleModeActivity.EXTRA_IDLE_RESULT, -1);
870 AltosDebug.debug("intent idle_mode %d", type);
872 case IdleModeActivity.IDLE_MODE_CONNECT:
873 msg = Message.obtain(null, TelemetryService.MSG_MONITOR_IDLE_START);
876 } catch (RemoteException re) {
879 case IdleModeActivity.IDLE_MODE_DISCONNECT:
880 msg = Message.obtain(null, TelemetryService.MSG_MONITOR_IDLE_STOP);
883 } catch (RemoteException re) {
886 case IdleModeActivity.IDLE_MODE_REBOOT:
887 msg = Message.obtain(null, TelemetryService.MSG_REBOOT);
890 } catch (RemoteException re) {
893 case IdleModeActivity.IDLE_MODE_IGNITERS:
894 Intent serverIntent = new Intent(this, IgniterActivity.class);
895 startActivityForResult(serverIntent, REQUEST_IGNITERS);
901 public boolean onCreateOptionsMenu(Menu menu) {
902 MenuInflater inflater = getMenuInflater();
903 inflater.inflate(R.menu.option_menu, menu);
907 void setFrequency(double freq) {
909 mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
911 } catch (RemoteException e) {
915 void setFrequency(AltosFrequency frequency) {
916 setFrequency (frequency.frequency);
919 void setBaud(int baud) {
921 mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD, baud));
923 } catch (RemoteException e) {
927 void setBaud(String baud) {
929 int value = Integer.parseInt(baud);
930 int rate = AltosLib.ao_telemetry_rate_38400;
933 rate = AltosLib.ao_telemetry_rate_2400;
936 rate = AltosLib.ao_telemetry_rate_9600;
939 rate = AltosLib.ao_telemetry_rate_38400;
943 } catch (NumberFormatException e) {
947 void select_tracker(int serial) {
950 AltosDebug.debug("select tracker %d\n", serial);
952 if (serial == selected_serial) {
953 AltosDebug.debug("%d already selected\n", serial);
958 for (i = 0; i < serials.length; i++)
959 if (serials[i] == serial)
962 if (i == serials.length) {
963 AltosDebug.debug("attempt to select unknown tracker %d\n", serial);
968 current_serial = selected_serial = serial;
972 void touch_trackers(Integer[] serials) {
973 AlertDialog.Builder builder_tracker = new AlertDialog.Builder(this);
974 builder_tracker.setTitle("Select Tracker");
975 final String[] trackers = new String[serials.length + 1];
976 trackers[0] = "Auto";
977 for (int i = 0; i < serials.length; i++)
978 trackers[i+1] = String.format("%d", serials[i]);
979 builder_tracker.setItems(trackers,
980 new DialogInterface.OnClickListener() {
981 public void onClick(DialogInterface dialog, int item) {
985 select_tracker(Integer.parseInt(trackers[item]));
988 AlertDialog alert_tracker = builder_tracker.create();
989 alert_tracker.show();
992 void delete_track(int serial) {
994 mService.send(Message.obtain(null, TelemetryService.MSG_DELETE_SERIAL, (Integer) serial));
995 } catch (Exception ex) {
1000 public boolean onOptionsItemSelected(MenuItem item) {
1001 Intent serverIntent = null;
1002 switch (item.getItemId()) {
1003 case R.id.connect_scan:
1005 // Launch the DeviceListActivity to see devices and do scan
1006 serverIntent = new Intent(this, DeviceListActivity.class);
1007 startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
1009 case R.id.disconnect:
1010 /* Disconnect the device
1012 disconnectDevice(false);
1015 AltosDebug.debug("R.id.quit");
1016 disconnectDevice(true);
1020 serverIntent = new Intent(this, SetupActivity.class);
1021 startActivityForResult(serverIntent, REQUEST_SETUP);
1023 case R.id.select_freq:
1024 // Set the TBT radio frequency
1026 final AltosFrequency[] frequencies = AltosPreferences.common_frequencies();
1027 String[] frequency_strings = new String[frequencies.length];
1028 for (int i = 0; i < frequencies.length; i++)
1029 frequency_strings[i] = frequencies[i].toString();
1031 AlertDialog.Builder builder_freq = new AlertDialog.Builder(this);
1032 builder_freq.setTitle("Pick a frequency");
1033 builder_freq.setItems(frequency_strings,
1034 new DialogInterface.OnClickListener() {
1035 public void onClick(DialogInterface dialog, int item) {
1036 setFrequency(frequencies[item]);
1039 AlertDialog alert_freq = builder_freq.create();
1042 case R.id.select_tracker:
1043 if (serials != null) {
1044 String[] trackers = new String[serials.length+1];
1045 trackers[0] = "Auto";
1046 for (int i = 0; i < serials.length; i++)
1047 trackers[i+1] = String.format("%d", serials[i]);
1048 AlertDialog.Builder builder_serial = new AlertDialog.Builder(this);
1049 builder_serial.setTitle("Select a tracker");
1050 builder_serial.setItems(trackers,
1051 new DialogInterface.OnClickListener() {
1052 public void onClick(DialogInterface dialog, int item) {
1056 select_tracker(serials[item-1]);
1059 AlertDialog alert_serial = builder_serial.create();
1060 alert_serial.show();
1064 case R.id.delete_track:
1065 if (serials != null) {
1066 String[] trackers = new String[serials.length];
1067 for (int i = 0; i < serials.length; i++)
1068 trackers[i] = String.format("%d", serials[i]);
1069 AlertDialog.Builder builder_serial = new AlertDialog.Builder(this);
1070 builder_serial.setTitle("Delete a track");
1071 builder_serial.setItems(trackers,
1072 new DialogInterface.OnClickListener() {
1073 public void onClick(DialogInterface dialog, int item) {
1074 delete_track(serials[item]);
1077 AlertDialog alert_serial = builder_serial.create();
1078 alert_serial.show();
1082 case R.id.idle_mode:
1083 serverIntent = new Intent(this, IdleModeActivity.class);
1084 serverIntent.putExtra(EXTRA_IDLE_MODE, idle_mode);
1085 startActivityForResult(serverIntent, REQUEST_IDLE_MODE);
1091 static String direction(AltosGreatCircle from_receiver,
1092 Location receiver) {
1093 if (from_receiver == null)
1096 if (receiver == null)
1099 if (!receiver.hasBearing())
1102 float bearing = receiver.getBearing();
1103 float heading = (float) from_receiver.bearing - bearing;
1105 while (heading <= -180.0f)
1107 while (heading > 180.0f)
1110 int iheading = (int) (heading + 0.5f);
1112 if (-1 < iheading && iheading < 1)
1114 else if (iheading < -179 || 179 < iheading)
1116 else if (iheading < 0)
1117 return String.format("left %d°", -iheading);
1119 return String.format("right %d°", iheading);
1122 public void onLocationChanged(Location location) {
1123 this.location = location;
1124 AltosDebug.debug("Location changed to %f,%f",
1125 location.getLatitude(),
1126 location.getLongitude());
1127 update_ui(telemetry_state, state, false);
1130 public void onStatusChanged(String provider, int status, Bundle extras) {
1131 AltosDebug.debug("Location status now %d\n", status);
1134 public void onProviderEnabled(String provider) {
1135 AltosDebug.debug("Location provider enabled %s\n", provider);
1138 public void onProviderDisabled(String provider) {
1139 AltosDebug.debug("Location provider disabled %s\n", provider);