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;
67 public static final int MSG_IDLE_MODE = 3;
68 public static final int MSG_IGNITER_STATUS = 4;
70 // Intent request codes
71 public static final int REQUEST_CONNECT_DEVICE = 1;
72 public static final int REQUEST_ENABLE_BT = 2;
73 public static final int REQUEST_PRELOAD_MAPS = 3;
74 public static final int REQUEST_IDLE_MODE = 5;
75 public static final int REQUEST_IGNITERS = 6;
76 public static final int REQUEST_SETUP = 7;
78 public static final String EXTRA_IDLE_MODE = "idle_mode";
79 public static final String EXTRA_IDLE_RESULT = "idle_result";
80 public static final String EXTRA_TELEMETRY_SERVICE = "telemetry_service";
83 public static final int SETUP_BAUD = 1;
84 public static final int SETUP_UNITS = 2;
85 public static final int SETUP_MAP_SOURCE = 4;
86 public static final int SETUP_MAP_TYPE = 8;
88 public static FragmentManager fm;
90 private BluetoothAdapter mBluetoothAdapter = null;
92 // Flight state values
93 private TextView mCallsignView;
94 private TextView mRSSIView;
95 private TextView mSerialView;
96 private TextView mFlightView;
97 private RelativeLayout mStateLayout;
98 private TextView mStateView;
99 private TextView mAgeView;
100 private boolean mAgeViewOld;
101 private int mAgeNewColor;
102 private int mAgeOldColor;
104 public static final String tab_pad_name = "pad";
105 public static final String tab_flight_name = "flight";
106 public static final String tab_recover_name = "recover";
107 public static final String tab_map_name = "map";
109 // field to display the version at the bottom of the screen
110 private TextView mVersion;
112 private double frequency;
113 private int telemetry_rate;
115 private boolean idle_mode = false;
117 public Location location = null;
121 AltosViewPager mViewPager;
122 TabsAdapter mTabsAdapter;
123 ArrayList<AltosDroidTab> mTabs = new ArrayList<AltosDroidTab>();
126 // Timer and Saved flight state for Age calculation
128 AltosState saved_state;
129 TelemetryState telemetry_state;
132 UsbDevice pending_usb_device;
133 boolean start_with_usb;
136 private boolean mIsBound = false;
137 private Messenger mService = null;
138 final Messenger mMessenger = new Messenger(new IncomingHandler(this));
141 private AltosVoice mAltosVoice = null;
143 // The Handler that gets information back from the Telemetry Service
144 static class IncomingHandler extends Handler {
145 private final WeakReference<AltosDroid> mAltosDroid;
146 IncomingHandler(AltosDroid ad) { mAltosDroid = new WeakReference<AltosDroid>(ad); }
149 public void handleMessage(Message msg) {
150 AltosDroid ad = mAltosDroid.get();
154 if (msg.obj == null) {
155 AltosDebug.debug("telemetry_state null!");
158 ad.update_state((TelemetryState) msg.obj);
164 ad.idle_mode = (Boolean) msg.obj;
165 ad.update_state(null);
172 private ServiceConnection mConnection = new ServiceConnection() {
173 public void onServiceConnected(ComponentName className, IBinder service) {
174 mService = new Messenger(service);
176 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
177 msg.replyTo = mMessenger;
179 } catch (RemoteException e) {
180 // In this case the service has crashed before we could even do anything with it
182 if (pending_usb_device != null) {
184 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, pending_usb_device));
185 pending_usb_device = null;
186 } catch (RemoteException e) {
191 public void onServiceDisconnected(ComponentName className) {
192 // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
197 void doBindService() {
198 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
202 void doUnbindService() {
204 // If we have received the service, and hence registered with it, then now is the time to unregister.
205 if (mService != null) {
207 Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
208 msg.replyTo = mMessenger;
210 } catch (RemoteException e) {
211 // There is nothing special we need to do if the service has crashed.
214 // Detach our existing connection.
215 unbindService(mConnection);
220 public void registerTab(AltosDroidTab mTab) {
224 public void unregisterTab(AltosDroidTab mTab) {
228 public void units_changed(boolean imperial_units) {
229 for (AltosDroidTab mTab : mTabs)
230 mTab.units_changed(imperial_units);
233 void update_title(TelemetryState telemetry_state) {
234 switch (telemetry_state.connect) {
235 case TelemetryState.CONNECT_CONNECTED:
236 if (telemetry_state.config != null) {
237 String str = String.format("S/N %d %6.3f MHz%s", telemetry_state.config.serial,
238 telemetry_state.frequency, idle_mode ? " (idle)" : "");
239 if (telemetry_state.telemetry_rate != AltosLib.ao_telemetry_rate_38400)
240 str = str.concat(String.format(" %d bps",
241 AltosLib.ao_telemetry_rate_values[telemetry_state.telemetry_rate]));
244 setTitle(R.string.title_connected_to);
247 case TelemetryState.CONNECT_CONNECTING:
248 if (telemetry_state.address != null)
249 setTitle(String.format("Connecting to %s...", telemetry_state.address.name));
251 setTitle("Connecting to something...");
253 case TelemetryState.CONNECT_DISCONNECTED:
254 case TelemetryState.CONNECT_NONE:
255 setTitle(R.string.title_not_connected);
263 timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 1000L, 1000L);
275 int selected_serial = 0;
279 void set_switch_time() {
280 switch_time = System.currentTimeMillis();
284 boolean registered_units_listener;
286 void update_state(TelemetryState new_telemetry_state) {
288 if (new_telemetry_state != null)
289 telemetry_state = new_telemetry_state;
291 if (selected_serial != 0)
292 current_serial = selected_serial;
294 if (current_serial == 0)
295 current_serial = telemetry_state.latest_serial;
297 if (!registered_units_listener) {
298 registered_units_listener = true;
299 AltosPreferences.register_units_listener(this);
302 serials = telemetry_state.states.keySet().toArray(new Integer[0]);
303 Arrays.sort(serials);
305 update_title(telemetry_state);
307 AltosState state = null;
310 if (telemetry_state.states.containsKey(current_serial)) {
311 state = telemetry_state.states.get(current_serial);
312 int age = state_age(state);
315 if (current_serial == selected_serial)
317 else if (switch_time != 0 && (switch_time - state.received_time) > 0)
322 AltosState newest_state = null;
325 for (int serial : telemetry_state.states.keySet()) {
326 AltosState existing = telemetry_state.states.get(serial);
327 int existing_age = state_age(existing);
329 if (newest_state == null || existing_age < newest_age) {
330 newest_state = existing;
331 newest_age = existing_age;
335 if (newest_state != null)
336 state = newest_state;
339 update_ui(telemetry_state, state);
344 boolean same_string(String a, String b) {
357 private int blend_component(int a, int b, double r, int shift, int mask) {
358 return ((int) (((a >> shift) & mask) * r + ((b >> shift) & mask) * (1 - r)) & mask) << shift;
360 private int blend_color(int a, int b, double r) {
361 return (blend_component(a, b, r, 0, 0xff) |
362 blend_component(a, b, r, 8, 0xff) |
363 blend_component(a, b, r, 16, 0xff) |
364 blend_component(a, b, r, 24, 0xff));
367 int state_age(AltosState state) {
368 return (int) ((System.currentTimeMillis() - state.received_time + 500) / 1000);
371 void set_screen_on(int age) {
373 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
375 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
379 if (saved_state != null) {
380 int age = state_age(saved_state);
382 double age_scale = age / 100.0;
387 mAgeView.setTextColor(blend_color(mAgeOldColor, mAgeNewColor, age_scale));
393 text = String.format("%ds", age);
394 else if (age < 60 * 60)
395 text = String.format("%dm", age / 60);
396 else if (age < 60 * 60 * 24)
397 text = String.format("%dh", age / (60 * 60));
399 text = String.format("%dd", age / (24 * 60 * 60));
400 mAgeView.setText(text);
404 void update_ui(TelemetryState telem_state, AltosState state) {
406 int prev_state = AltosLib.ao_flight_invalid;
408 AltosGreatCircle from_receiver = null;
410 if (saved_state != null)
411 prev_state = saved_state.state();
414 set_screen_on(state_age(state));
416 if (state.state() == AltosLib.ao_flight_stateless) {
417 boolean prev_locked = false;
418 boolean locked = false;
420 if(state.gps != null)
421 locked = state.gps.locked;
422 if (saved_state != null && saved_state.gps != null)
423 prev_locked = saved_state.gps.locked;
424 if (prev_locked != locked) {
425 String currentTab = mTabHost.getCurrentTabTag();
427 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
429 if (currentTab.equals(tab_flight_name)) mTabHost.setCurrentTabByTag(tab_pad_name);
433 if (prev_state != state.state()) {
434 String currentTab = mTabHost.getCurrentTabTag();
435 switch (state.state()) {
436 case AltosLib.ao_flight_boost:
437 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
439 case AltosLib.ao_flight_landed:
440 if (currentTab.equals(tab_flight_name)) mTabHost.setCurrentTabByTag(tab_recover_name);
442 case AltosLib.ao_flight_stateless:
443 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
449 if (location != null && state.gps != null && state.gps.locked) {
451 if (location.hasAltitude())
452 altitude = location.getAltitude();
453 from_receiver = new AltosGreatCircle(location.getLatitude(),
454 location.getLongitude(),
461 if (saved_state == null || !same_string(saved_state.callsign, state.callsign)) {
462 mCallsignView.setText(state.callsign);
464 if (saved_state == null || state.serial != saved_state.serial) {
465 if (state.serial == AltosLib.MISSING)
466 mSerialView.setText("");
468 mSerialView.setText(String.format("%d", state.serial));
470 if (saved_state == null || state.flight != saved_state.flight) {
471 if (state.flight == AltosLib.MISSING)
472 mFlightView.setText("");
474 mFlightView.setText(String.format("%d", state.flight));
476 if (saved_state == null || state.state() != saved_state.state()) {
477 if (state.state() == AltosLib.ao_flight_stateless) {
478 mStateLayout.setVisibility(View.GONE);
480 mStateView.setText(state.state_name());
481 mStateLayout.setVisibility(View.VISIBLE);
484 if (saved_state == null || state.rssi != saved_state.rssi) {
485 if (state.rssi == AltosLib.MISSING)
486 mRSSIView.setText("");
488 mRSSIView.setText(String.format("%d", state.rssi));
492 for (AltosDroidTab mTab : mTabs)
493 mTab.update_ui(telem_state, state, from_receiver, location, mTab == mTabsAdapter.currentItem());
495 if (mAltosVoice != null)
496 mAltosVoice.tell(telem_state, state, from_receiver, location, (AltosDroidTab) mTabsAdapter.currentItem());
501 private void onTimerTick() {
503 mMessenger.send(Message.obtain(null, MSG_UPDATE_AGE));
504 } catch (RemoteException e) {
508 static String pos(double p, String pos, String neg) {
510 if (p == AltosLib.MISSING)
516 int deg = (int) Math.floor(p);
517 double min = (p - Math.floor(p)) * 60.0;
518 return String.format("%d°%9.4f\" %s", deg, min, h);
521 static String number(String format, double value) {
522 if (value == AltosLib.MISSING)
524 return String.format(format, value);
527 static String integer(String format, int value) {
528 if (value == AltosLib.MISSING)
530 return String.format(format, value);
533 private View create_tab_view(String label) {
534 LayoutInflater inflater = (LayoutInflater) this.getLayoutInflater();
535 View tab_view = inflater.inflate(R.layout.tab_layout, null);
536 TextView text_view = (TextView) tab_view.findViewById (R.id.tabLabel);
537 text_view.setText(label);
542 public void onCreate(Bundle savedInstanceState) {
543 super.onCreate(savedInstanceState);
544 AltosDebug.init(this);
545 AltosDebug.debug("+++ ON CREATE +++");
547 // Initialise preferences
548 AltosDroidPreferences.init(this);
550 fm = getSupportFragmentManager();
552 // Set up the window layout
553 setContentView(R.layout.altosdroid);
555 // Create the Tabs and ViewPager
556 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
559 mViewPager = (AltosViewPager)findViewById(R.id.pager);
560 mViewPager.setOffscreenPageLimit(4);
562 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
564 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_pad_name).setIndicator(create_tab_view("Pad")), TabPad.class, null);
565 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_flight_name).setIndicator(create_tab_view("Flight")), TabFlight.class, null);
566 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_recover_name).setIndicator(create_tab_view("Recover")), TabRecover.class, null);
567 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_map_name).setIndicator(create_tab_view("Map")), TabMap.class, null);
569 // Display the Version
570 mVersion = (TextView) findViewById(R.id.version);
571 mVersion.setText("Version: " + BuildInfo.version +
572 " Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
573 " (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
575 mCallsignView = (TextView) findViewById(R.id.callsign_value);
576 mRSSIView = (TextView) findViewById(R.id.rssi_value);
577 mSerialView = (TextView) findViewById(R.id.serial_value);
578 mFlightView = (TextView) findViewById(R.id.flight_value);
579 mStateLayout = (RelativeLayout) findViewById(R.id.state_container);
580 mStateView = (TextView) findViewById(R.id.state_value);
581 mAgeView = (TextView) findViewById(R.id.age_value);
582 mAgeNewColor = mAgeView.getTextColors().getDefaultColor();
583 mAgeOldColor = getResources().getColor(R.color.old_color);
586 private void ensureBluetooth() {
587 // Get local Bluetooth adapter
588 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
590 /* if there is a BT adapter and it isn't turned on, then turn it on */
591 if (mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) {
592 Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
593 startActivityForResult(enableIntent, AltosDroid.REQUEST_ENABLE_BT);
597 private boolean check_usb() {
598 UsbDevice device = AltosUsb.find_device(this, AltosLib.product_basestation);
600 if (device != null) {
601 Intent i = new Intent(this, AltosDroid.class);
602 PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent("hello world", null, this, AltosDroid.class), 0);
604 if (AltosUsb.request_permission(this, device, pi)) {
607 start_with_usb = true;
611 start_with_usb = false;
616 private void noticeIntent(Intent intent) {
618 /* Ok, this is pretty convenient.
620 * When a USB device is plugged in, and our 'hotplug'
621 * intent registration fires, we get an Intent with
624 * When we start up and see a usb device and request
625 * permission to access it, that queues a
626 * PendingIntent, which has the EXTRA_DEVICE added in,
627 * along with the EXTRA_PERMISSION_GRANTED field as
630 * So, in both cases, we get the device name using the
631 * same call. We check to see if access was granted,
632 * in which case we ignore the device field and do our
633 * usual startup thing.
636 UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
637 boolean granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, true);
639 AltosDebug.debug("intent %s device %s granted %s", intent, device, granted);
644 if (device != null) {
645 AltosDebug.debug("intent has usb device " + device.toString());
649 /* 'granted' is only false if this intent came
650 * from the request_permission call and
651 * permission was denied. In which case, we
652 * don't want to loop forever...
655 AltosDebug.debug("check for a USB device at startup");
659 AltosDebug.debug("Starting by looking for bluetooth devices");
665 public void onStart() {
667 AltosDebug.debug("++ ON START ++");
671 noticeIntent(getIntent());
673 // Start Telemetry Service
674 String action = start_with_usb ? ACTION_USB : ACTION_BLUETOOTH;
676 startService(new Intent(action, null, AltosDroid.this, TelemetryService.class));
680 if (mAltosVoice == null)
681 mAltosVoice = new AltosVoice(this);
686 public void onNewIntent(Intent intent) {
687 super.onNewIntent(intent);
688 AltosDebug.debug("onNewIntent");
689 noticeIntent(intent);
693 public void onResume() {
695 AltosDebug.debug("+ ON RESUME +");
697 // Listen for GPS and Network position updates
698 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
699 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
701 location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
703 if (location != null)
704 AltosDebug.debug("Resume, location is %f,%f\n",
705 location.getLatitude(),
706 location.getLongitude());
708 update_ui(telemetry_state, saved_state);
712 public void onPause() {
714 AltosDebug.debug("- ON PAUSE -");
715 // Stop listening for location updates
716 ((LocationManager) getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
720 public void onStop() {
722 AltosDebug.debug("-- ON STOP --");
726 public void onDestroy() {
728 AltosDebug.debug("--- ON DESTROY ---");
731 if (mAltosVoice != null) {
738 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
739 AltosDebug.debug("onActivityResult " + resultCode);
740 switch (requestCode) {
741 case REQUEST_CONNECT_DEVICE:
742 // When DeviceListActivity returns with a device to connect to
743 if (resultCode == Activity.RESULT_OK) {
747 case REQUEST_ENABLE_BT:
748 // When the request to enable Bluetooth returns
749 if (resultCode == Activity.RESULT_OK) {
750 // Bluetooth is now enabled, so set up a chat session
752 AltosDebug.debug("BT enabled");
753 bluetoothEnabled(data);
755 // User did not enable Bluetooth or an error occured
756 AltosDebug.debug("BT not enabled");
759 case REQUEST_IDLE_MODE:
760 if (resultCode == Activity.RESULT_OK)
763 case REQUEST_IGNITERS:
766 if (resultCode == Activity.RESULT_OK)
767 note_setup_changes(data);
772 private void note_setup_changes(Intent data) {
773 int changes = data.getIntExtra(SetupActivity.EXTRA_SETUP_CHANGES, 0);
775 if ((changes & SETUP_BAUD) != 0) {
777 mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD,
778 AltosPreferences.telemetry_rate(1)));
779 } catch (RemoteException re) {
782 if ((changes & SETUP_UNITS) != 0) {
783 /* nothing to do here */
785 if ((changes & SETUP_MAP_SOURCE) != 0) {
786 /* nothing to do here */
788 if ((changes & SETUP_MAP_TYPE) != 0) {
789 /* nothing to do here */
794 private void connectUsb(UsbDevice device) {
795 if (mService == null)
796 pending_usb_device = device;
798 // Attempt to connect to the device
800 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, device));
801 AltosDebug.debug("Sent OPEN_USB message");
802 } catch (RemoteException e) {
803 AltosDebug.debug("connect device message failed");
808 private void bluetoothEnabled(Intent data) {
810 mService.send(Message.obtain(null, TelemetryService.MSG_BLUETOOTH_ENABLED, null));
811 } catch (RemoteException e) {
812 AltosDebug.debug("send BT enabled message failed");
816 private void connectDevice(Intent data) {
817 // Attempt to connect to the device
819 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
820 String name = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_NAME);
822 AltosDebug.debug("Connecting to " + address + " " + name);
823 DeviceAddress a = new DeviceAddress(address, name);
824 mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, a));
825 AltosDebug.debug("Sent connecting message");
826 } catch (RemoteException e) {
827 AltosDebug.debug("connect device message failed");
831 private void disconnectDevice() {
833 mService.send(Message.obtain(null, TelemetryService.MSG_DISCONNECT, null));
834 } catch (RemoteException e) {
838 private void idle_mode(Intent data) {
839 int type = data.getIntExtra(IdleModeActivity.EXTRA_IDLE_RESULT, -1);
842 AltosDebug.debug("intent idle_mode %d", type);
844 case IdleModeActivity.IDLE_MODE_CONNECT:
845 msg = Message.obtain(null, TelemetryService.MSG_MONITOR_IDLE_START);
848 } catch (RemoteException re) {
851 case IdleModeActivity.IDLE_MODE_DISCONNECT:
852 msg = Message.obtain(null, TelemetryService.MSG_MONITOR_IDLE_STOP);
855 } catch (RemoteException re) {
858 case IdleModeActivity.IDLE_MODE_REBOOT:
859 msg = Message.obtain(null, TelemetryService.MSG_REBOOT);
862 } catch (RemoteException re) {
865 case IdleModeActivity.IDLE_MODE_IGNITERS:
866 Intent serverIntent = new Intent(this, IgniterActivity.class);
867 startActivityForResult(serverIntent, REQUEST_IGNITERS);
873 public boolean onCreateOptionsMenu(Menu menu) {
874 MenuInflater inflater = getMenuInflater();
875 inflater.inflate(R.menu.option_menu, menu);
879 void setFrequency(double freq) {
881 mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
883 } catch (RemoteException e) {
887 void setFrequency(String freq) {
889 setFrequency (AltosParse.parse_double_net(freq.substring(11, 17)));
890 } catch (ParseException e) {
894 void setBaud(int baud) {
896 mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD, baud));
898 } catch (RemoteException e) {
902 void setBaud(String baud) {
904 int value = Integer.parseInt(baud);
905 int rate = AltosLib.ao_telemetry_rate_38400;
908 rate = AltosLib.ao_telemetry_rate_2400;
911 rate = AltosLib.ao_telemetry_rate_9600;
914 rate = AltosLib.ao_telemetry_rate_38400;
918 } catch (NumberFormatException e) {
922 void select_tracker(int serial) {
925 AltosDebug.debug("select tracker %d\n", serial);
927 if (serial == selected_serial) {
928 AltosDebug.debug("%d already selected\n", serial);
933 for (i = 0; i < serials.length; i++)
934 if (serials[i] == serial)
937 if (i == serials.length) {
938 AltosDebug.debug("attempt to select unknown tracker %d\n", serial);
943 current_serial = selected_serial = serial;
947 void touch_trackers(Integer[] serials) {
948 AlertDialog.Builder builder_tracker = new AlertDialog.Builder(this);
949 builder_tracker.setTitle("Select Tracker");
950 final String[] trackers = new String[serials.length + 1];
951 trackers[0] = "Auto";
952 for (int i = 0; i < serials.length; i++)
953 trackers[i+1] = String.format("%d", serials[i]);
954 builder_tracker.setItems(trackers,
955 new DialogInterface.OnClickListener() {
956 public void onClick(DialogInterface dialog, int item) {
960 select_tracker(Integer.parseInt(trackers[item]));
963 AlertDialog alert_tracker = builder_tracker.create();
964 alert_tracker.show();
967 void delete_track(int serial) {
969 mService.send(Message.obtain(null, TelemetryService.MSG_DELETE_SERIAL, (Integer) serial));
970 } catch (Exception ex) {
975 public boolean onOptionsItemSelected(MenuItem item) {
976 Intent serverIntent = null;
977 switch (item.getItemId()) {
978 case R.id.connect_scan:
980 // Launch the DeviceListActivity to see devices and do scan
981 serverIntent = new Intent(this, DeviceListActivity.class);
982 startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
984 case R.id.disconnect:
985 /* Disconnect the device
990 AltosDebug.debug("R.id.quit");
995 serverIntent = new Intent(this, SetupActivity.class);
996 startActivityForResult(serverIntent, REQUEST_SETUP);
998 case R.id.select_freq:
999 // Set the TBT radio frequency
1001 final String[] frequencies = {
1002 "Channel 0 (434.550MHz)",
1003 "Channel 1 (434.650MHz)",
1004 "Channel 2 (434.750MHz)",
1005 "Channel 3 (434.850MHz)",
1006 "Channel 4 (434.950MHz)",
1007 "Channel 5 (435.050MHz)",
1008 "Channel 6 (435.150MHz)",
1009 "Channel 7 (435.250MHz)",
1010 "Channel 8 (435.350MHz)",
1011 "Channel 9 (435.450MHz)"
1014 AlertDialog.Builder builder_freq = new AlertDialog.Builder(this);
1015 builder_freq.setTitle("Pick a frequency");
1016 builder_freq.setItems(frequencies,
1017 new DialogInterface.OnClickListener() {
1018 public void onClick(DialogInterface dialog, int item) {
1019 setFrequency(frequencies[item]);
1022 AlertDialog alert_freq = builder_freq.create();
1025 case R.id.select_tracker:
1026 if (serials != null) {
1027 String[] trackers = new String[serials.length+1];
1028 trackers[0] = "Auto";
1029 for (int i = 0; i < serials.length; i++)
1030 trackers[i+1] = String.format("%d", serials[i]);
1031 AlertDialog.Builder builder_serial = new AlertDialog.Builder(this);
1032 builder_serial.setTitle("Select a tracker");
1033 builder_serial.setItems(trackers,
1034 new DialogInterface.OnClickListener() {
1035 public void onClick(DialogInterface dialog, int item) {
1039 select_tracker(serials[item-1]);
1042 AlertDialog alert_serial = builder_serial.create();
1043 alert_serial.show();
1047 case R.id.delete_track:
1048 if (serials != null) {
1049 String[] trackers = new String[serials.length];
1050 for (int i = 0; i < serials.length; i++)
1051 trackers[i] = String.format("%d", serials[i]);
1052 AlertDialog.Builder builder_serial = new AlertDialog.Builder(this);
1053 builder_serial.setTitle("Delete a track");
1054 builder_serial.setItems(trackers,
1055 new DialogInterface.OnClickListener() {
1056 public void onClick(DialogInterface dialog, int item) {
1057 delete_track(serials[item]);
1060 AlertDialog alert_serial = builder_serial.create();
1061 alert_serial.show();
1065 case R.id.idle_mode:
1066 serverIntent = new Intent(this, IdleModeActivity.class);
1067 serverIntent.putExtra(EXTRA_IDLE_MODE, idle_mode);
1068 startActivityForResult(serverIntent, REQUEST_IDLE_MODE);
1074 static String direction(AltosGreatCircle from_receiver,
1075 Location receiver) {
1076 if (from_receiver == null)
1079 if (receiver == null)
1082 if (!receiver.hasBearing())
1085 float bearing = receiver.getBearing();
1086 float heading = (float) from_receiver.bearing - bearing;
1088 while (heading <= -180.0f)
1090 while (heading > 180.0f)
1093 int iheading = (int) (heading + 0.5f);
1095 if (-1 < iheading && iheading < 1)
1097 else if (iheading < -179 || 179 < iheading)
1099 else if (iheading < 0)
1100 return String.format("left %d°", -iheading);
1102 return String.format("right %d°", iheading);
1105 public void onLocationChanged(Location location) {
1106 this.location = location;
1107 AltosDebug.debug("Location changed to %f,%f",
1108 location.getLatitude(),
1109 location.getLongitude());
1110 update_ui(telemetry_state, saved_state);
1113 public void onStatusChanged(String provider, int status, Bundle extras) {
1114 AltosDebug.debug("Location status now %d\n", status);
1117 public void onProviderEnabled(String provider) {
1118 AltosDebug.debug("Location provider enabled %s\n", provider);
1121 public void onProviderDisabled(String provider) {
1122 AltosDebug.debug("Location provider disabled %s\n", provider);