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_13.*;
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 class Tracker implements CharSequence, Comparable {
87 public Tracker(int serial, String call, double frequency) {
93 this.frequency = frequency;
96 else if (frequency == AltosLib.MISSING) {
97 display = String.format("%-8.8s %6d", call, serial);
99 display = String.format("%-8.8s %7.3f %6d", call, frequency, serial);
103 public Tracker(AltosState s) {
104 this(s == null ? 0 : s.cal_data().serial,
105 s == null ? null : s.cal_data().callsign,
106 s == null ? 0.0 : s.frequency);
110 public char charAt(int index) {
111 return display.charAt(index);
114 public int length() {
115 return display.length();
118 public CharSequence subSequence(int start, int end) throws IndexOutOfBoundsException {
119 return display.subSequence(start, end);
122 public String toString() {
123 return display.toString();
127 public int compareTo (Object other) {
128 Tracker o = (Tracker) other;
129 if (frequency == 0.0) {
130 if (o.frequency == 0.0)
134 if (o.frequency == 0.0)
137 int a = serial - o.serial;
138 int b = call.compareTo(o.call);
139 int c = (int) Math.signum(frequency - o.frequency);
149 public class AltosDroid extends FragmentActivity implements AltosUnitsListener, LocationListener {
151 // Actions sent to the telemetry server at startup time
153 public static final String ACTION_BLUETOOTH = "org.altusmetrum.AltosDroid.BLUETOOTH";
154 public static final String ACTION_USB = "org.altusmetrum.AltosDroid.USB";
156 // Message types received by our Handler
158 public static final int MSG_STATE = 1;
159 public static final int MSG_UPDATE_AGE = 2;
160 public static final int MSG_IDLE_MODE = 3;
161 public static final int MSG_IGNITER_STATUS = 4;
163 // Intent request codes
164 public static final int REQUEST_CONNECT_DEVICE = 1;
165 public static final int REQUEST_ENABLE_BT = 2;
166 public static final int REQUEST_PRELOAD_MAPS = 3;
167 public static final int REQUEST_IDLE_MODE = 5;
168 public static final int REQUEST_IGNITERS = 6;
169 public static final int REQUEST_SETUP = 7;
171 public static final String EXTRA_IDLE_MODE = "idle_mode";
172 public static final String EXTRA_IDLE_RESULT = "idle_result";
173 public static final String EXTRA_TELEMETRY_SERVICE = "telemetry_service";
176 public static final int SETUP_BAUD = 1;
177 public static final int SETUP_UNITS = 2;
178 public static final int SETUP_MAP_SOURCE = 4;
179 public static final int SETUP_MAP_TYPE = 8;
181 public static FragmentManager fm;
183 private BluetoothAdapter mBluetoothAdapter = null;
185 // Flight state values
186 private TextView mCallsignView;
187 private TextView mRSSIView;
188 private TextView mSerialView;
189 private TextView mFlightView;
190 private RelativeLayout mStateLayout;
191 private TextView mStateView;
192 private TextView mAgeView;
193 private boolean mAgeViewOld;
194 private int mAgeNewColor;
195 private int mAgeOldColor;
197 public static final String tab_pad_name = "pad";
198 public static final String tab_flight_name = "flight";
199 public static final String tab_recover_name = "recover";
200 public static final String tab_map_name = "map";
202 // field to display the version at the bottom of the screen
203 private TextView mVersion;
205 private boolean idle_mode = false;
207 public Location location = null;
209 private AltosState state;
210 private SavedState saved_state;
214 AltosViewPager mViewPager;
215 TabsAdapter mTabsAdapter;
216 ArrayList<AltosDroidTab> mTabs = new ArrayList<AltosDroidTab>();
219 // Timer and Saved flight state for Age calculation
222 TelemetryState telemetry_state;
226 UsbDevice pending_usb_device;
227 boolean start_with_usb;
230 private boolean mIsBound = false;
231 private Messenger mService = null;
232 final Messenger mMessenger = new Messenger(new IncomingHandler(this));
235 private AltosVoice mAltosVoice = null;
237 // The Handler that gets information back from the Telemetry Service
238 static class IncomingHandler extends Handler {
239 private final WeakReference<AltosDroid> mAltosDroid;
240 IncomingHandler(AltosDroid ad) { mAltosDroid = new WeakReference<AltosDroid>(ad); }
243 public void handleMessage(Message msg) {
244 AltosDroid ad = mAltosDroid.get();
248 if (msg.obj == null) {
249 AltosDebug.debug("telemetry_state null!");
252 ad.update_state((TelemetryState) msg.obj);
258 ad.idle_mode = (Boolean) msg.obj;
259 ad.update_state(null);
266 private ServiceConnection mConnection = new ServiceConnection() {
267 public void onServiceConnected(ComponentName className, IBinder service) {
268 mService = new Messenger(service);
270 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
271 msg.replyTo = mMessenger;
273 } catch (RemoteException e) {
274 // In this case the service has crashed before we could even do anything with it
276 if (pending_usb_device != null) {
278 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, pending_usb_device));
279 pending_usb_device = null;
280 } catch (RemoteException e) {
285 public void onServiceDisconnected(ComponentName className) {
286 // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
291 void doBindService() {
292 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
296 void doUnbindService() {
298 // If we have received the service, and hence registered with it, then now is the time to unregister.
299 if (mService != null) {
301 Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
302 msg.replyTo = mMessenger;
304 } catch (RemoteException e) {
305 // There is nothing special we need to do if the service has crashed.
308 // Detach our existing connection.
309 unbindService(mConnection);
314 public void registerTab(AltosDroidTab mTab) {
318 public void unregisterTab(AltosDroidTab mTab) {
322 public void units_changed(boolean imperial_units) {
323 for (AltosDroidTab mTab : mTabs)
324 mTab.units_changed(imperial_units);
327 void update_title(TelemetryState telemetry_state) {
328 switch (telemetry_state.connect) {
329 case TelemetryState.CONNECT_CONNECTED:
330 if (telemetry_state.config != null) {
331 String str = String.format("S/N %d %6.3f MHz%s", telemetry_state.config.serial,
332 telemetry_state.frequency, idle_mode ? " (idle)" : "");
333 if (telemetry_state.telemetry_rate != AltosLib.ao_telemetry_rate_38400)
334 str = str.concat(String.format(" %d bps",
335 AltosLib.ao_telemetry_rate_values[telemetry_state.telemetry_rate]));
338 setTitle(R.string.title_connected_to);
341 case TelemetryState.CONNECT_CONNECTING:
342 if (telemetry_state.address != null)
343 setTitle(String.format("Connecting to %s...", telemetry_state.address.name));
345 setTitle("Connecting to something...");
347 case TelemetryState.CONNECT_DISCONNECTED:
348 case TelemetryState.CONNECT_NONE:
349 setTitle(R.string.title_not_connected);
357 timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 1000L, 1000L);
369 int selected_serial = 0;
373 void set_switch_time() {
374 switch_time = System.currentTimeMillis();
378 boolean registered_units_listener;
380 void update_state(TelemetryState new_telemetry_state) {
382 if (new_telemetry_state != null)
383 telemetry_state = new_telemetry_state;
385 if (selected_serial != 0)
386 current_serial = selected_serial;
388 if (current_serial == 0)
389 current_serial = telemetry_state.latest_serial;
391 if (!registered_units_listener) {
392 registered_units_listener = true;
393 AltosPreferences.register_units_listener(this);
396 int num_trackers = 0;
397 for (AltosState s : telemetry_state.states.values()) {
401 trackers = new Tracker[num_trackers + 1];
404 trackers[n++] = new Tracker(0, "auto", 0.0);
406 for (AltosState s : telemetry_state.states.values())
407 trackers[n++] = new Tracker(s);
409 Arrays.sort(trackers);
411 update_title(telemetry_state);
413 AltosState state = null;
416 if (telemetry_state.states.containsKey(current_serial)) {
417 state = telemetry_state.states.get(current_serial);
418 int age = state_age(state.received_time);
421 if (current_serial == selected_serial)
423 else if (switch_time != 0 && (switch_time - state.received_time) > 0)
428 AltosState newest_state = null;
431 for (int serial : telemetry_state.states.keySet()) {
432 AltosState existing = telemetry_state.states.get(serial);
433 int existing_age = state_age(existing.received_time);
435 if (newest_state == null || existing_age < newest_age) {
436 newest_state = existing;
437 newest_age = existing_age;
441 if (newest_state != null)
442 state = newest_state;
445 update_ui(telemetry_state, state, telemetry_state.quiet);
450 boolean same_string(String a, String b) {
463 private int blend_component(int a, int b, double r, int shift, int mask) {
464 return ((int) (((a >> shift) & mask) * r + ((b >> shift) & mask) * (1 - r)) & mask) << shift;
466 private int blend_color(int a, int b, double r) {
467 return (blend_component(a, b, r, 0, 0xff) |
468 blend_component(a, b, r, 8, 0xff) |
469 blend_component(a, b, r, 16, 0xff) |
470 blend_component(a, b, r, 24, 0xff));
473 int state_age(long received_time) {
474 return (int) ((System.currentTimeMillis() - received_time + 500) / 1000);
477 void set_screen_on(int age) {
479 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
481 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
485 if (saved_state != null) {
486 int age = state_age(saved_state.received_time);
488 double age_scale = age / 100.0;
493 mAgeView.setTextColor(blend_color(mAgeOldColor, mAgeNewColor, age_scale));
499 text = String.format("%ds", age);
500 else if (age < 60 * 60)
501 text = String.format("%dm", age / 60);
502 else if (age < 60 * 60 * 24)
503 text = String.format("%dh", age / (60 * 60));
505 text = String.format("%dd", age / (24 * 60 * 60));
506 mAgeView.setText(text);
510 void update_ui(TelemetryState telem_state, AltosState state, boolean quiet) {
514 int prev_state = AltosLib.ao_flight_invalid;
516 AltosGreatCircle from_receiver = null;
518 if (saved_state != null)
519 prev_state = saved_state.state;
522 set_screen_on(state_age(state.received_time));
524 if (state.state() == AltosLib.ao_flight_stateless) {
525 boolean prev_locked = false;
526 boolean locked = false;
528 if(state.gps != null)
529 locked = state.gps.locked;
530 if (saved_state != null)
531 prev_locked = saved_state.locked;
532 if (prev_locked != locked) {
533 String currentTab = mTabHost.getCurrentTabTag();
535 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
537 if (currentTab.equals(tab_flight_name)) mTabHost.setCurrentTabByTag(tab_pad_name);
541 if (prev_state != state.state()) {
542 String currentTab = mTabHost.getCurrentTabTag();
543 switch (state.state()) {
544 case AltosLib.ao_flight_boost:
545 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
547 case AltosLib.ao_flight_landed:
548 if (currentTab.equals(tab_flight_name)) mTabHost.setCurrentTabByTag(tab_recover_name);
550 case AltosLib.ao_flight_stateless:
551 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
557 if (location != null && state.gps != null && state.gps.locked) {
559 if (location.hasAltitude())
560 altitude = location.getAltitude();
561 from_receiver = new AltosGreatCircle(location.getLatitude(),
562 location.getLongitude(),
569 if (saved_state == null || !same_string(saved_state.callsign, state.cal_data().callsign)) {
570 mCallsignView.setText(state.cal_data().callsign);
572 if (saved_state == null || state.cal_data().serial != saved_state.serial) {
573 if (state.cal_data().serial == AltosLib.MISSING)
574 mSerialView.setText("");
576 mSerialView.setText(String.format("%d", state.cal_data().serial));
578 if (saved_state == null || state.cal_data().flight != saved_state.flight) {
579 if (state.cal_data().flight == AltosLib.MISSING)
580 mFlightView.setText("");
582 mFlightView.setText(String.format("%d", state.cal_data().flight));
584 if (saved_state == null || state.state() != saved_state.state) {
585 if (state.state() == AltosLib.ao_flight_stateless) {
586 mStateLayout.setVisibility(View.GONE);
588 mStateView.setText(state.state_name());
589 mStateLayout.setVisibility(View.VISIBLE);
592 if (saved_state == null || state.rssi != saved_state.rssi) {
593 if (state.rssi == AltosLib.MISSING)
594 mRSSIView.setText("");
596 mRSSIView.setText(String.format("%d", state.rssi));
598 saved_state = new SavedState(state);
601 for (AltosDroidTab mTab : mTabs)
602 mTab.update_ui(telem_state, state, from_receiver, location, mTab == mTabsAdapter.currentItem());
604 AltosDebug.debug("quiet %b\n", quiet);
605 if (mAltosVoice != null)
606 mAltosVoice.tell(telem_state, state, from_receiver, location, (AltosDroidTab) mTabsAdapter.currentItem(), quiet);
610 private void onTimerTick() {
612 mMessenger.send(Message.obtain(null, MSG_UPDATE_AGE));
613 } catch (RemoteException e) {
617 static String pos(double p, String pos, String neg) {
619 if (p == AltosLib.MISSING)
625 int deg = (int) Math.floor(p);
626 double min = (p - Math.floor(p)) * 60.0;
627 return String.format("%d°%9.4f\" %s", deg, min, h);
630 static String number(String format, double value) {
631 if (value == AltosLib.MISSING)
633 return String.format(format, value);
636 static String integer(String format, int value) {
637 if (value == AltosLib.MISSING)
639 return String.format(format, value);
642 private View create_tab_view(String label) {
643 LayoutInflater inflater = (LayoutInflater) this.getLayoutInflater();
644 View tab_view = inflater.inflate(R.layout.tab_layout, null);
645 TextView text_view = (TextView) tab_view.findViewById (R.id.tabLabel);
646 text_view.setText(label);
651 public void onCreate(Bundle savedInstanceState) {
652 super.onCreate(savedInstanceState);
653 AltosDebug.init(this);
654 AltosDebug.debug("+++ ON CREATE +++");
656 // Initialise preferences
657 AltosDroidPreferences.init(this);
659 fm = getSupportFragmentManager();
661 // Set up the window layout
662 setContentView(R.layout.altosdroid);
664 // Create the Tabs and ViewPager
665 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
668 mViewPager = (AltosViewPager)findViewById(R.id.pager);
669 mViewPager.setOffscreenPageLimit(4);
671 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
673 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_pad_name).setIndicator(create_tab_view("Pad")), TabPad.class, null);
674 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_flight_name).setIndicator(create_tab_view("Flight")), TabFlight.class, null);
675 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_recover_name).setIndicator(create_tab_view("Recover")), TabRecover.class, null);
676 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_map_name).setIndicator(create_tab_view("Map")), TabMap.class, null);
678 // Display the Version
679 mVersion = (TextView) findViewById(R.id.version);
680 mVersion.setText("Version: " + BuildInfo.version +
681 " Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
682 " (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
684 mCallsignView = (TextView) findViewById(R.id.callsign_value);
685 mRSSIView = (TextView) findViewById(R.id.rssi_value);
686 mSerialView = (TextView) findViewById(R.id.serial_value);
687 mFlightView = (TextView) findViewById(R.id.flight_value);
688 mStateLayout = (RelativeLayout) findViewById(R.id.state_container);
689 mStateView = (TextView) findViewById(R.id.state_value);
690 mAgeView = (TextView) findViewById(R.id.age_value);
691 mAgeNewColor = mAgeView.getTextColors().getDefaultColor();
692 mAgeOldColor = getResources().getColor(R.color.old_color);
695 private void ensureBluetooth() {
696 // Get local Bluetooth adapter
697 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
699 /* if there is a BT adapter and it isn't turned on, then turn it on */
700 if (mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) {
701 Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
702 startActivityForResult(enableIntent, AltosDroid.REQUEST_ENABLE_BT);
706 private boolean check_usb() {
707 UsbDevice device = AltosUsb.find_device(this, AltosLib.product_basestation);
709 if (device != null) {
710 Intent i = new Intent(this, AltosDroid.class);
711 PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent("hello world", null, this, AltosDroid.class), 0);
713 if (AltosUsb.request_permission(this, device, pi)) {
716 start_with_usb = true;
720 start_with_usb = false;
725 private void noticeIntent(Intent intent) {
727 /* Ok, this is pretty convenient.
729 * When a USB device is plugged in, and our 'hotplug'
730 * intent registration fires, we get an Intent with
733 * When we start up and see a usb device and request
734 * permission to access it, that queues a
735 * PendingIntent, which has the EXTRA_DEVICE added in,
736 * along with the EXTRA_PERMISSION_GRANTED field as
739 * So, in both cases, we get the device name using the
740 * same call. We check to see if access was granted,
741 * in which case we ignore the device field and do our
742 * usual startup thing.
745 UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
746 boolean granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, true);
748 AltosDebug.debug("intent %s device %s granted %s", intent, device, granted);
753 if (device != null) {
754 AltosDebug.debug("intent has usb device " + device.toString());
758 /* 'granted' is only false if this intent came
759 * from the request_permission call and
760 * permission was denied. In which case, we
761 * don't want to loop forever...
764 AltosDebug.debug("check for a USB device at startup");
768 AltosDebug.debug("Starting by looking for bluetooth devices");
774 public void onStart() {
776 AltosDebug.debug("++ ON START ++");
780 noticeIntent(getIntent());
782 // Start Telemetry Service
783 String action = start_with_usb ? ACTION_USB : ACTION_BLUETOOTH;
785 startService(new Intent(action, null, AltosDroid.this, TelemetryService.class));
789 if (mAltosVoice == null)
790 mAltosVoice = new AltosVoice(this);
795 public void onNewIntent(Intent intent) {
796 super.onNewIntent(intent);
797 AltosDebug.debug("onNewIntent");
798 noticeIntent(intent);
802 public void onResume() {
804 AltosDebug.debug("+ ON RESUME +");
806 // Listen for GPS and Network position updates
807 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
808 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
810 location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
812 if (location != null)
813 AltosDebug.debug("Resume, location is %f,%f\n",
814 location.getLatitude(),
815 location.getLongitude());
817 update_ui(telemetry_state, state, true);
821 public void onPause() {
823 AltosDebug.debug("- ON PAUSE -");
824 // Stop listening for location updates
825 ((LocationManager) getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
829 public void onStop() {
831 AltosDebug.debug("-- ON STOP --");
835 public void onDestroy() {
837 AltosDebug.debug("--- ON DESTROY ---");
840 if (mAltosVoice != null) {
847 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
848 AltosDebug.debug("onActivityResult " + resultCode);
849 switch (requestCode) {
850 case REQUEST_CONNECT_DEVICE:
851 // When DeviceListActivity returns with a device to connect to
852 if (resultCode == Activity.RESULT_OK) {
856 case REQUEST_ENABLE_BT:
857 // When the request to enable Bluetooth returns
858 if (resultCode == Activity.RESULT_OK) {
859 // Bluetooth is now enabled, so set up a chat session
861 AltosDebug.debug("BT enabled");
862 bluetoothEnabled(data);
864 // User did not enable Bluetooth or an error occured
865 AltosDebug.debug("BT not enabled");
868 case REQUEST_IDLE_MODE:
869 if (resultCode == Activity.RESULT_OK)
872 case REQUEST_IGNITERS:
875 if (resultCode == Activity.RESULT_OK)
876 note_setup_changes(data);
881 private void note_setup_changes(Intent data) {
882 int changes = data.getIntExtra(SetupActivity.EXTRA_SETUP_CHANGES, 0);
884 if ((changes & SETUP_BAUD) != 0) {
886 mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD,
887 AltosPreferences.telemetry_rate(1)));
888 } catch (RemoteException re) {
891 if ((changes & SETUP_UNITS) != 0) {
892 /* nothing to do here */
894 if ((changes & SETUP_MAP_SOURCE) != 0) {
895 /* nothing to do here */
897 if ((changes & SETUP_MAP_TYPE) != 0) {
898 /* nothing to do here */
903 private void connectUsb(UsbDevice device) {
904 if (mService == null)
905 pending_usb_device = device;
907 // Attempt to connect to the device
909 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, device));
910 AltosDebug.debug("Sent OPEN_USB message");
911 } catch (RemoteException e) {
912 AltosDebug.debug("connect device message failed");
917 private void bluetoothEnabled(Intent data) {
919 mService.send(Message.obtain(null, TelemetryService.MSG_BLUETOOTH_ENABLED, null));
920 } catch (RemoteException e) {
921 AltosDebug.debug("send BT enabled message failed");
925 private void connectDevice(Intent data) {
926 // Attempt to connect to the device
928 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
929 String name = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_NAME);
931 AltosDebug.debug("Connecting to " + address + " " + name);
932 DeviceAddress a = new DeviceAddress(address, name);
933 mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, a));
934 AltosDebug.debug("Sent connecting message");
935 } catch (RemoteException e) {
936 AltosDebug.debug("connect device message failed");
940 private void disconnectDevice(boolean remember) {
942 mService.send(Message.obtain(null, TelemetryService.MSG_DISCONNECT, (Boolean) remember));
943 } catch (RemoteException e) {
947 private void idle_mode(Intent data) {
948 int type = data.getIntExtra(IdleModeActivity.EXTRA_IDLE_RESULT, -1);
951 AltosDebug.debug("intent idle_mode %d", type);
953 case IdleModeActivity.IDLE_MODE_CONNECT:
954 msg = Message.obtain(null, TelemetryService.MSG_MONITOR_IDLE_START);
957 } catch (RemoteException re) {
960 case IdleModeActivity.IDLE_MODE_DISCONNECT:
961 msg = Message.obtain(null, TelemetryService.MSG_MONITOR_IDLE_STOP);
964 } catch (RemoteException re) {
967 case IdleModeActivity.IDLE_MODE_REBOOT:
968 msg = Message.obtain(null, TelemetryService.MSG_REBOOT);
971 } catch (RemoteException re) {
974 case IdleModeActivity.IDLE_MODE_IGNITERS:
975 Intent serverIntent = new Intent(this, IgniterActivity.class);
976 startActivityForResult(serverIntent, REQUEST_IGNITERS);
982 public boolean onCreateOptionsMenu(Menu menu) {
983 MenuInflater inflater = getMenuInflater();
984 inflater.inflate(R.menu.option_menu, menu);
988 void setFrequency(double freq) {
990 mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
992 } catch (RemoteException e) {
996 void setFrequency(AltosFrequency frequency) {
997 setFrequency (frequency.frequency);
1000 void setBaud(int baud) {
1002 mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD, baud));
1004 } catch (RemoteException e) {
1008 void setBaud(String baud) {
1010 int value = Integer.parseInt(baud);
1011 int rate = AltosLib.ao_telemetry_rate_38400;
1014 rate = AltosLib.ao_telemetry_rate_2400;
1017 rate = AltosLib.ao_telemetry_rate_9600;
1020 rate = AltosLib.ao_telemetry_rate_38400;
1024 } catch (NumberFormatException e) {
1028 void select_tracker(int serial) {
1031 AltosDebug.debug("select tracker %d\n", serial);
1033 if (serial == selected_serial) {
1034 AltosDebug.debug("%d already selected\n", serial);
1039 for (i = 0; i < trackers.length; i++)
1040 if (trackers[i].serial == serial)
1043 if (i == trackers.length) {
1044 AltosDebug.debug("attempt to select unknown tracker %d\n", serial);
1049 current_serial = selected_serial = serial;
1053 void touch_trackers(Integer[] serials) {
1054 AlertDialog.Builder builder_tracker = new AlertDialog.Builder(this);
1055 builder_tracker.setTitle("Select Tracker");
1057 final Tracker[] my_trackers = new Tracker[serials.length + 1];
1059 my_trackers[0] = new Tracker(null);
1061 for (int i = 0; i < serials.length; i++) {
1062 AltosState s = telemetry_state.states.get(serials[i]);
1063 my_trackers[i+1] = new Tracker(s);
1065 builder_tracker.setItems(my_trackers,
1066 new DialogInterface.OnClickListener() {
1067 public void onClick(DialogInterface dialog, int item) {
1071 select_tracker(my_trackers[item].serial);
1074 AlertDialog alert_tracker = builder_tracker.create();
1075 alert_tracker.show();
1078 void delete_track(int serial) {
1080 mService.send(Message.obtain(null, TelemetryService.MSG_DELETE_SERIAL, (Integer) serial));
1081 } catch (Exception ex) {
1086 public boolean onOptionsItemSelected(MenuItem item) {
1087 Intent serverIntent = null;
1088 switch (item.getItemId()) {
1089 case R.id.connect_scan:
1091 // Launch the DeviceListActivity to see devices and do scan
1092 serverIntent = new Intent(this, DeviceListActivity.class);
1093 startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
1095 case R.id.disconnect:
1096 /* Disconnect the device
1098 disconnectDevice(false);
1101 AltosDebug.debug("R.id.quit");
1102 disconnectDevice(true);
1106 serverIntent = new Intent(this, SetupActivity.class);
1107 startActivityForResult(serverIntent, REQUEST_SETUP);
1109 case R.id.select_freq:
1110 // Set the TBT radio frequency
1112 final AltosFrequency[] frequencies = AltosPreferences.common_frequencies();
1113 String[] frequency_strings = new String[frequencies.length];
1114 for (int i = 0; i < frequencies.length; i++)
1115 frequency_strings[i] = frequencies[i].toString();
1117 AlertDialog.Builder builder_freq = new AlertDialog.Builder(this);
1118 builder_freq.setTitle("Pick a frequency");
1119 builder_freq.setItems(frequency_strings,
1120 new DialogInterface.OnClickListener() {
1121 public void onClick(DialogInterface dialog, int item) {
1122 setFrequency(frequencies[item]);
1125 AlertDialog alert_freq = builder_freq.create();
1128 case R.id.select_tracker:
1129 if (trackers != null) {
1130 AlertDialog.Builder builder_serial = new AlertDialog.Builder(this);
1131 builder_serial.setTitle("Select a tracker");
1132 builder_serial.setItems(trackers,
1133 new DialogInterface.OnClickListener() {
1134 public void onClick(DialogInterface dialog, int item) {
1135 System.out.printf("select item %d %s\n", item, trackers[item].display);
1139 select_tracker(trackers[item].serial);
1142 AlertDialog alert_serial = builder_serial.create();
1143 alert_serial.show();
1147 case R.id.delete_track:
1148 if (trackers != null) {
1149 AlertDialog.Builder builder_serial = new AlertDialog.Builder(this);
1150 builder_serial.setTitle("Delete a track");
1151 final Tracker[] my_trackers = new Tracker[trackers.length - 1];
1152 for (int i = 0; i < trackers.length - 1; i++)
1153 my_trackers[i] = trackers[i+1];
1154 builder_serial.setItems(my_trackers,
1155 new DialogInterface.OnClickListener() {
1156 public void onClick(DialogInterface dialog, int item) {
1157 delete_track(my_trackers[item].serial);
1160 AlertDialog alert_serial = builder_serial.create();
1161 alert_serial.show();
1165 case R.id.idle_mode:
1166 serverIntent = new Intent(this, IdleModeActivity.class);
1167 serverIntent.putExtra(EXTRA_IDLE_MODE, idle_mode);
1168 startActivityForResult(serverIntent, REQUEST_IDLE_MODE);
1174 static String direction(AltosGreatCircle from_receiver,
1175 Location receiver) {
1176 if (from_receiver == null)
1179 if (receiver == null)
1182 if (!receiver.hasBearing())
1185 float bearing = receiver.getBearing();
1186 float heading = (float) from_receiver.bearing - bearing;
1188 while (heading <= -180.0f)
1190 while (heading > 180.0f)
1193 int iheading = (int) (heading + 0.5f);
1195 if (-1 < iheading && iheading < 1)
1197 else if (iheading < -179 || 179 < iheading)
1199 else if (iheading < 0)
1200 return String.format("left %d°", -iheading);
1202 return String.format("right %d°", iheading);
1205 public void onLocationChanged(Location location) {
1206 this.location = location;
1207 AltosDebug.debug("Location changed to %f,%f",
1208 location.getLatitude(),
1209 location.getLongitude());
1210 update_ui(telemetry_state, state, false);
1213 public void onStatusChanged(String provider, int status, Bundle extras) {
1214 AltosDebug.debug("Location status now %d\n", status);
1217 public void onProviderEnabled(String provider) {
1218 AltosDebug.debug("Location provider enabled %s\n", provider);
1221 public void onProviderDisabled(String provider) {
1222 AltosDebug.debug("Location provider disabled %s\n", provider);