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;
24 import android.Manifest;
25 import android.app.Activity;
26 import android.app.PendingIntent;
27 import android.bluetooth.BluetoothAdapter;
28 import android.content.Intent;
29 import android.content.Context;
30 import android.content.ComponentName;
31 import android.content.ServiceConnection;
32 import android.content.DialogInterface;
33 import android.os.IBinder;
34 import android.os.Bundle;
35 import android.os.Handler;
36 import android.os.Message;
37 import android.os.Messenger;
38 import android.os.RemoteException;
39 import android.os.Parcelable;
40 import androidx.fragment.app.FragmentActivity;
41 import androidx.fragment.app.FragmentManager;
42 import android.view.*;
43 import android.widget.*;
44 import android.app.AlertDialog;
45 import android.location.Location;
46 import android.location.LocationManager;
47 import android.location.LocationListener;
48 import android.hardware.usb.*;
49 import android.content.pm.PackageManager;
50 import androidx.core.app.ActivityCompat;
51 import org.altusmetrum.altoslib_13.*;
62 SavedState(AltosState state) {
63 received_time = state.received_time;
64 this.state = state.state();
65 if (state.gps != null)
66 locked = state.gps.locked;
69 callsign = state.cal_data().callsign;
70 serial = state.cal_data().serial;
71 flight = state.cal_data().flight;
76 public class AltosDroid extends FragmentActivity implements AltosUnitsListener, LocationListener, ActivityCompat.OnRequestPermissionsResultCallback {
78 // Actions sent to the telemetry server at startup time
80 public static final String ACTION_BLUETOOTH = "org.altusmetrum.AltosDroid.BLUETOOTH";
81 public static final String ACTION_USB = "org.altusmetrum.AltosDroid.USB";
83 // Message types received by our Handler
85 public static final int MSG_STATE = 1;
86 public static final int MSG_UPDATE_AGE = 2;
87 public static final int MSG_IDLE_MODE = 3;
88 public static final int MSG_IGNITER_STATUS = 4;
90 // Intent request codes
91 public static final int REQUEST_CONNECT_DEVICE = 1;
92 public static final int REQUEST_ENABLE_BT = 2;
93 public static final int REQUEST_PRELOAD_MAPS = 3;
94 public static final int REQUEST_IDLE_MODE = 5;
95 public static final int REQUEST_IGNITERS = 6;
96 public static final int REQUEST_SETUP = 7;
97 public static final int REQUEST_SELECT_TRACKER = 8;
99 public static final String EXTRA_IDLE_MODE = "idle_mode";
100 public static final String EXTRA_IDLE_RESULT = "idle_result";
101 public static final String EXTRA_FREQUENCY = "frequency";
102 public static final String EXTRA_TELEMETRY_SERVICE = "telemetry_service";
103 public static final String EXTRA_TRACKERS = "trackers";
106 public static final int SETUP_BAUD = 1;
107 public static final int SETUP_UNITS = 2;
108 public static final int SETUP_MAP_SOURCE = 4;
109 public static final int SETUP_MAP_TYPE = 8;
110 public static final int SETUP_FONT_SIZE = 16;
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, telemetry_state.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;
302 void set_switch_time() {
303 switch_time = System.currentTimeMillis();
307 boolean registered_units_listener;
309 void update_state(TelemetryState new_telemetry_state) {
311 if (new_telemetry_state != null)
312 telemetry_state = new_telemetry_state;
314 if (selected_frequency != AltosLib.MISSING) {
315 AltosState selected_state = telemetry_state.get(selected_serial);
316 AltosState latest_state = telemetry_state.get(telemetry_state.latest_serial);
318 if (selected_state != null && selected_state.frequency == selected_frequency) {
319 selected_frequency = AltosLib.MISSING;
320 } else if ((selected_state == null || selected_state.frequency != selected_frequency) &&
321 (latest_state != null && latest_state.frequency == selected_frequency))
323 selected_frequency = AltosLib.MISSING;
324 selected_serial = telemetry_state.latest_serial;
328 if (!telemetry_state.containsKey(selected_serial)) {
329 selected_serial = telemetry_state.latest_serial;
330 AltosDebug.debug("selected serial set to %d", selected_serial);
333 int shown_serial = selected_serial;
335 if (telemetry_state.idle_mode)
336 shown_serial = telemetry_state.latest_serial;
338 if (!registered_units_listener) {
339 registered_units_listener = true;
340 AltosPreferences.register_units_listener(this);
343 int num_trackers = 0;
345 for (AltosState s : telemetry_state.values()) {
349 trackers = new Tracker[num_trackers + 1];
352 trackers[n++] = new Tracker(0, "auto", 0.0);
354 for (AltosState s : telemetry_state.values())
355 trackers[n++] = new Tracker(s);
357 Arrays.sort(trackers);
359 if (telemetry_state.frequency != AltosLib.MISSING)
360 telem_frequency = telemetry_state.frequency;
362 update_title(telemetry_state);
364 AltosState state = telemetry_state.get(shown_serial);
366 update_ui(telemetry_state, state, telemetry_state.quiet);
371 boolean same_string(String a, String b) {
384 private int blend_component(int a, int b, double r, int shift, int mask) {
385 return ((int) (((a >> shift) & mask) * r + ((b >> shift) & mask) * (1 - r)) & mask) << shift;
387 private int blend_color(int a, int b, double r) {
388 return (blend_component(a, b, r, 0, 0xff) |
389 blend_component(a, b, r, 8, 0xff) |
390 blend_component(a, b, r, 16, 0xff) |
391 blend_component(a, b, r, 24, 0xff));
394 int state_age(long received_time) {
395 return (int) ((System.currentTimeMillis() - received_time + 500) / 1000);
398 void set_screen_on(int age) {
400 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
402 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
405 static String age_string(int age) {
408 text = String.format("%ds", age);
409 else if (age < 60 * 60)
410 text = String.format("%dm", age / 60);
411 else if (age < 60 * 60 * 24)
412 text = String.format("%dh", age / (60 * 60));
414 text = String.format("%dd", age / (24 * 60 * 60));
419 if (saved_state != null) {
420 int age = state_age(saved_state.received_time);
422 double age_scale = age / 100.0;
427 mAgeView.setTextColor(blend_color(mAgeOldColor, mAgeNewColor, age_scale));
431 mAgeView.setText(age_string(age));
435 void update_ui(TelemetryState telem_state, AltosState state, boolean quiet) {
439 int prev_state = AltosLib.ao_flight_invalid;
441 AltosGreatCircle from_receiver = null;
443 if (saved_state != null)
444 prev_state = saved_state.state;
447 set_screen_on(state_age(state.received_time));
449 if (state.state() == AltosLib.ao_flight_stateless) {
450 boolean prev_locked = false;
451 boolean locked = false;
453 if(state.gps != null)
454 locked = state.gps.locked;
455 if (saved_state != null)
456 prev_locked = saved_state.locked;
457 if (prev_locked != locked) {
458 String currentTab = mTabHost.getCurrentTabTag();
460 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
462 if (currentTab.equals(tab_flight_name)) mTabHost.setCurrentTabByTag(tab_pad_name);
466 if (prev_state != state.state()) {
467 String currentTab = mTabHost.getCurrentTabTag();
468 switch (state.state()) {
469 case AltosLib.ao_flight_boost:
470 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
472 case AltosLib.ao_flight_landed:
473 if (currentTab.equals(tab_flight_name)) mTabHost.setCurrentTabByTag(tab_recover_name);
475 case AltosLib.ao_flight_stateless:
476 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
482 if (location != null && state.gps != null && state.gps.locked) {
484 if (location.hasAltitude())
485 altitude = location.getAltitude();
486 from_receiver = new AltosGreatCircle(location.getLatitude(),
487 location.getLongitude(),
494 if (saved_state == null || !same_string(saved_state.callsign, state.cal_data().callsign)) {
495 mCallsignView.setText(state.cal_data().callsign);
497 if (saved_state == null || state.cal_data().serial != saved_state.serial) {
498 if (state.cal_data().serial == AltosLib.MISSING)
499 mSerialView.setText("");
501 mSerialView.setText(String.format("%d", state.cal_data().serial));
503 if (saved_state == null || state.cal_data().flight != saved_state.flight) {
504 if (state.cal_data().flight == AltosLib.MISSING)
505 mFlightView.setText("");
507 mFlightView.setText(String.format("%d", state.cal_data().flight));
509 if (saved_state == null || state.state() != saved_state.state) {
510 if (state.state() == AltosLib.ao_flight_stateless) {
511 mStateLayout.setVisibility(View.GONE);
513 mStateView.setText(state.state_name());
514 mStateLayout.setVisibility(View.VISIBLE);
517 if (saved_state == null || state.rssi != saved_state.rssi) {
518 if (state.rssi == AltosLib.MISSING)
519 mRSSIView.setText("");
521 mRSSIView.setText(String.format("%d", state.rssi));
523 saved_state = new SavedState(state);
526 for (AltosDroidTab mTab : mTabs)
527 mTab.update_ui(telem_state, state, from_receiver, location, mTab == mTabsAdapter.currentItem());
529 if (mAltosVoice != null && mTabsAdapter.currentItem() != null)
530 mAltosVoice.tell(telem_state, state, from_receiver, location, (AltosDroidTab) mTabsAdapter.currentItem(), quiet);
534 private void onTimerTick() {
536 mMessenger.send(Message.obtain(null, MSG_UPDATE_AGE));
537 } catch (RemoteException e) {
541 static String pos(double p, String pos, String neg) {
543 if (p == AltosLib.MISSING)
549 int deg = (int) Math.floor(p);
550 double min = (p - Math.floor(p)) * 60.0;
551 return String.format("%d° %7.4f\" %s", deg, min, h);
554 static String number(String format, double value) {
555 if (value == AltosLib.MISSING)
557 return String.format(format, value);
560 static String integer(String format, int value) {
561 if (value == AltosLib.MISSING)
563 return String.format(format, value);
566 private View create_tab_view(String label) {
567 LayoutInflater inflater = (LayoutInflater) this.getLayoutInflater();
568 View tab_view = inflater.inflate(R.layout.tab_layout, null);
569 TextView text_view = (TextView) tab_view.findViewById (R.id.tabLabel);
570 text_view.setText(label);
574 static public int[] themes = {
581 static public int[] dialog_themes = {
582 R.style.Small_Dialog,
583 R.style.Medium_Dialog,
584 R.style.Large_Dialog,
589 public void onCreate(Bundle savedInstanceState) {
590 // Initialise preferences
591 AltosDroidPreferences.init(this);
592 setTheme(themes[AltosDroidPreferences.font_size()]);
593 super.onCreate(savedInstanceState);
594 AltosDebug.init(this);
595 AltosDebug.debug("+++ ON CREATE +++");
598 fm = getSupportFragmentManager();
600 // Set up the window layout
601 setContentView(R.layout.altosdroid);
603 // Create the Tabs and ViewPager
604 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
607 mViewPager = (AltosViewPager)findViewById(R.id.pager);
608 mViewPager.setOffscreenPageLimit(4);
610 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
612 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_pad_name).setIndicator(create_tab_view("Pad")), TabPad.class, null);
613 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_flight_name).setIndicator(create_tab_view("Flight")), TabFlight.class, null);
614 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_recover_name).setIndicator(create_tab_view("Recover")), TabRecover.class, null);
615 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_map_name).setIndicator(create_tab_view("Map")), TabMap.class, null);
617 // Display the Version
618 mVersion = (TextView) findViewById(R.id.version);
619 mVersion.setText("Version: " + BuildInfo.version +
620 " Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
621 " (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
623 mCallsignView = (TextView) findViewById(R.id.callsign_value);
624 mRSSIView = (TextView) findViewById(R.id.rssi_value);
625 mSerialView = (TextView) findViewById(R.id.serial_value);
626 mFlightView = (TextView) findViewById(R.id.flight_value);
627 mStateLayout = (RelativeLayout) findViewById(R.id.state_container);
628 mStateView = (TextView) findViewById(R.id.state_value);
629 mAgeView = (TextView) findViewById(R.id.age_value);
630 mAgeNewColor = mAgeView.getTextColors().getDefaultColor();
631 mAgeOldColor = getResources().getColor(R.color.old_color, getTheme());
634 private void ensureBluetooth() {
635 // Get local Bluetooth adapter
636 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
638 /* if there is a BT adapter and it isn't turned on, then turn it on */
639 if (mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) {
640 Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
641 startActivityForResult(enableIntent, AltosDroid.REQUEST_ENABLE_BT);
645 private boolean check_usb() {
646 UsbDevice device = AltosUsb.find_device(this, AltosLib.product_basestation);
648 if (device != null) {
649 Intent i = new Intent(this, AltosDroid.class);
650 PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent("hello world", null, this, AltosDroid.class), 0);
652 if (AltosUsb.request_permission(this, device, pi)) {
655 start_with_usb = true;
659 start_with_usb = false;
664 private void noticeIntent(Intent intent) {
666 /* Ok, this is pretty convenient.
668 * When a USB device is plugged in, and our 'hotplug'
669 * intent registration fires, we get an Intent with
672 * When we start up and see a usb device and request
673 * permission to access it, that queues a
674 * PendingIntent, which has the EXTRA_DEVICE added in,
675 * along with the EXTRA_PERMISSION_GRANTED field as
678 * So, in both cases, we get the device name using the
679 * same call. We check to see if access was granted,
680 * in which case we ignore the device field and do our
681 * usual startup thing.
684 UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
685 boolean granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, true);
687 AltosDebug.debug("intent %s device %s granted %s", intent, device, granted);
692 if (device != null) {
693 AltosDebug.debug("intent has usb device " + device.toString());
697 /* 'granted' is only false if this intent came
698 * from the request_permission call and
699 * permission was denied. In which case, we
700 * don't want to loop forever...
703 AltosDebug.debug("check for a USB device at startup");
707 AltosDebug.debug("Starting by looking for bluetooth devices");
713 public void onStart() {
715 AltosDebug.debug("++ ON START ++");
719 noticeIntent(getIntent());
721 // Start Telemetry Service
722 String action = start_with_usb ? ACTION_USB : ACTION_BLUETOOTH;
724 startService(new Intent(action, null, AltosDroid.this, TelemetryService.class));
728 if (mAltosVoice == null)
729 mAltosVoice = new AltosVoice(this);
734 public void onNewIntent(Intent intent) {
735 super.onNewIntent(intent);
736 AltosDebug.debug("onNewIntent");
737 noticeIntent(intent);
740 private void enable_location_updates() {
741 // Listen for GPS and Network position updates
742 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
743 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
745 location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
747 if (location != null)
748 AltosDebug.debug("Resume, location is %f,%f\n",
749 location.getLatitude(),
750 location.getLongitude());
752 update_ui(telemetry_state, state, true);
755 static final int MY_PERMISSION_REQUEST = 1001;
757 public boolean have_location_permission = false;
758 public boolean have_storage_permission = false;
759 public boolean asked_permission = false;
761 AltosMapOnline map_online;
764 tell_map_permission(AltosMapOnline map_online) {
765 this.map_online = map_online;
769 public void onRequestPermissionsResult(int requestCode, String[] permissions,
770 int[] grantResults) {
771 if (requestCode == MY_PERMISSION_REQUEST) {
772 for (int i = 0; i < grantResults.length; i++) {
773 if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
774 if (permissions[i].equals(Manifest.permission.ACCESS_FINE_LOCATION)) {
775 have_location_permission = true;
776 enable_location_updates();
777 if (map_online != null)
778 map_online.position_permission();
780 if (permissions[i].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
781 have_storage_permission = true;
789 public void onResume() {
791 AltosDebug.debug("+ ON RESUME +");
793 if (!asked_permission) {
794 asked_permission = true;
795 if (ActivityCompat.checkSelfPermission(this,
796 Manifest.permission.ACCESS_FINE_LOCATION)
797 == PackageManager.PERMISSION_GRANTED)
799 have_location_permission = true;
801 if (ActivityCompat.checkSelfPermission(this,
802 Manifest.permission.WRITE_EXTERNAL_STORAGE)
803 == PackageManager.PERMISSION_GRANTED)
805 have_storage_permission = true;
807 int count = (have_location_permission ? 0 : 1) + (have_storage_permission ? 0 : 1);
810 String[] permissions = new String[count];
812 if (!have_location_permission)
813 permissions[i++] = Manifest.permission.ACCESS_FINE_LOCATION;
814 if (!have_location_permission)
815 permissions[i++] = Manifest.permission.WRITE_EXTERNAL_STORAGE;
816 ActivityCompat.requestPermissions(this, permissions, MY_PERMISSION_REQUEST);
819 if (have_location_permission)
820 enable_location_updates();
824 public void onPause() {
826 AltosDebug.debug("- ON PAUSE -");
827 // Stop listening for location updates
828 if (have_location_permission)
829 ((LocationManager) getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
833 public void onStop() {
835 AltosDebug.debug("-- ON STOP --");
839 public void onDestroy() {
841 AltosDebug.debug("--- ON DESTROY ---");
844 if (mAltosVoice != null) {
851 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
852 AltosDebug.debug("onActivityResult request %d result %d", requestCode, resultCode);
853 switch (requestCode) {
854 case REQUEST_CONNECT_DEVICE:
855 // When DeviceListActivity returns with a device to connect to
856 if (resultCode == Activity.RESULT_OK) {
860 case REQUEST_ENABLE_BT:
861 // When the request to enable Bluetooth returns
862 if (resultCode == Activity.RESULT_OK) {
863 // Bluetooth is now enabled, so set up a chat session
865 AltosDebug.debug("BT enabled");
866 bluetoothEnabled(data);
868 // User did not enable Bluetooth or an error occured
869 AltosDebug.debug("BT not enabled");
872 case REQUEST_IDLE_MODE:
873 if (resultCode == Activity.RESULT_OK)
876 case REQUEST_IGNITERS:
879 if (resultCode == Activity.RESULT_OK)
880 note_setup_changes(data);
882 case REQUEST_SELECT_TRACKER:
883 if (resultCode == Activity.RESULT_OK)
884 select_tracker(data);
889 private void note_setup_changes(Intent data) {
890 int changes = data.getIntExtra(SetupActivity.EXTRA_SETUP_CHANGES, 0);
892 AltosDebug.debug("note_setup_changes changes %d\n", changes);
894 if ((changes & SETUP_BAUD) != 0) {
896 mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD,
897 AltosPreferences.telemetry_rate(1)));
898 } catch (RemoteException re) {
901 if ((changes & SETUP_UNITS) != 0) {
902 /* nothing to do here */
904 if ((changes & SETUP_MAP_SOURCE) != 0) {
905 /* nothing to do here */
907 if ((changes & SETUP_MAP_TYPE) != 0) {
908 /* nothing to do here */
911 if ((changes & SETUP_FONT_SIZE) != 0) {
912 AltosDebug.debug(" ==== Recreate to switch font sizes ==== ");
914 startActivity(getIntent());
918 private void connectUsb(UsbDevice device) {
919 if (mService == null)
920 pending_usb_device = device;
922 // Attempt to connect to the device
924 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, device));
925 AltosDebug.debug("Sent OPEN_USB message");
926 } catch (RemoteException e) {
927 AltosDebug.debug("connect device message failed");
932 private void bluetoothEnabled(Intent data) {
933 if (mService != null) {
935 mService.send(Message.obtain(null, TelemetryService.MSG_BLUETOOTH_ENABLED, null));
936 } catch (RemoteException e) {
937 AltosDebug.debug("send BT enabled message failed");
942 private void connectDevice(Intent data) {
943 // Attempt to connect to the device
945 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
946 String name = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_NAME);
948 AltosDebug.debug("Connecting to " + address + " " + name);
949 DeviceAddress a = new DeviceAddress(address, name);
950 mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, a));
951 AltosDebug.debug("Sent connecting message");
952 } catch (RemoteException e) {
953 AltosDebug.debug("connect device message failed");
957 private void disconnectDevice(boolean remember) {
959 mService.send(Message.obtain(null, TelemetryService.MSG_DISCONNECT, (Boolean) remember));
960 } catch (RemoteException e) {
964 private void idle_mode(Intent data) {
965 int type = data.getIntExtra(IdleModeActivity.EXTRA_IDLE_RESULT, -1);
968 AltosDebug.debug("intent idle_mode %d", type);
970 case IdleModeActivity.IDLE_MODE_CONNECT:
971 msg = Message.obtain(null, TelemetryService.MSG_MONITOR_IDLE_START);
974 } catch (RemoteException re) {
977 case IdleModeActivity.IDLE_MODE_DISCONNECT:
978 msg = Message.obtain(null, TelemetryService.MSG_MONITOR_IDLE_STOP);
981 } catch (RemoteException re) {
984 case IdleModeActivity.IDLE_MODE_REBOOT:
985 msg = Message.obtain(null, TelemetryService.MSG_REBOOT);
988 } catch (RemoteException re) {
991 case IdleModeActivity.IDLE_MODE_IGNITERS:
992 Intent serverIntent = new Intent(this, IgniterActivity.class);
993 startActivityForResult(serverIntent, REQUEST_IGNITERS);
999 public boolean onCreateOptionsMenu(Menu menu) {
1000 MenuInflater inflater = getMenuInflater();
1001 inflater.inflate(R.menu.option_menu, menu);
1005 double telem_frequency = 434.550;
1006 double selected_frequency = AltosLib.MISSING;
1008 void setFrequency(double freq) {
1009 telem_frequency = freq;
1010 selected_frequency = AltosLib.MISSING;
1012 mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
1014 } catch (RemoteException e) {
1018 void setFrequency(AltosFrequency frequency) {
1019 setFrequency (frequency.frequency);
1022 void setBaud(int baud) {
1024 mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD, baud));
1026 } catch (RemoteException e) {
1030 void setBaud(String baud) {
1032 int value = Integer.parseInt(baud);
1033 int rate = AltosLib.ao_telemetry_rate_38400;
1036 rate = AltosLib.ao_telemetry_rate_2400;
1039 rate = AltosLib.ao_telemetry_rate_9600;
1042 rate = AltosLib.ao_telemetry_rate_38400;
1046 } catch (NumberFormatException e) {
1050 void select_tracker(int serial, double frequency) {
1052 AltosDebug.debug("select tracker %d %7.3f\n", serial, frequency);
1054 if (serial == selected_serial) {
1055 AltosDebug.debug("%d already selected\n", serial);
1061 for (i = 0; i < trackers.length; i++)
1062 if (trackers[i].serial == serial)
1065 if (i == trackers.length) {
1066 AltosDebug.debug("attempt to select unknown tracker %d\n", serial);
1069 if (frequency != 0.0 && frequency != AltosLib.MISSING)
1070 setFrequency(frequency);
1073 selected_serial = serial;
1077 void select_tracker(Intent data) {
1078 int serial = data.getIntExtra(SelectTrackerActivity.EXTRA_SERIAL_NUMBER, 0);
1079 double frequency = data.getDoubleExtra(SelectTrackerActivity.EXTRA_FREQUENCY, 0.0);
1080 select_tracker(serial, frequency);
1083 void touch_trackers(Integer[] serials) {
1084 AlertDialog.Builder builder_tracker = new AlertDialog.Builder(this);
1085 builder_tracker.setTitle("Select Tracker");
1087 final Tracker[] my_trackers = new Tracker[serials.length + 1];
1089 my_trackers[0] = new Tracker(null);
1091 for (int i = 0; i < serials.length; i++) {
1092 AltosState s = telemetry_state.get(serials[i]);
1093 my_trackers[i+1] = new Tracker(s);
1095 builder_tracker.setItems(my_trackers,
1096 new DialogInterface.OnClickListener() {
1097 public void onClick(DialogInterface dialog, int item) {
1099 select_tracker(0, 0.0);
1101 select_tracker(my_trackers[item].serial, my_trackers[item].frequency);
1104 AlertDialog alert_tracker = builder_tracker.create();
1105 alert_tracker.show();
1108 void delete_track(int serial) {
1110 mService.send(Message.obtain(null, TelemetryService.MSG_DELETE_SERIAL, (Integer) serial));
1111 } catch (Exception ex) {
1116 public boolean onOptionsItemSelected(MenuItem item) {
1117 Intent serverIntent = null;
1118 switch (item.getItemId()) {
1119 case R.id.connect_scan:
1121 // Launch the DeviceListActivity to see devices and do scan
1122 serverIntent = new Intent(this, DeviceListActivity.class);
1123 startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
1125 case R.id.disconnect:
1126 /* Disconnect the device
1128 disconnectDevice(false);
1131 AltosDebug.debug("R.id.quit");
1132 disconnectDevice(true);
1136 serverIntent = new Intent(this, SetupActivity.class);
1137 startActivityForResult(serverIntent, REQUEST_SETUP);
1139 case R.id.select_freq:
1140 // Set the TBT radio frequency
1142 final AltosFrequency[] frequencies = AltosPreferences.common_frequencies();
1143 String[] frequency_strings = new String[frequencies.length];
1144 for (int i = 0; i < frequencies.length; i++)
1145 frequency_strings[i] = frequencies[i].toString();
1147 AlertDialog.Builder builder_freq = new AlertDialog.Builder(this);
1148 builder_freq.setTitle("Pick a frequency");
1149 builder_freq.setItems(frequency_strings,
1150 new DialogInterface.OnClickListener() {
1151 public void onClick(DialogInterface dialog, int item) {
1152 setFrequency(frequencies[item]);
1153 selected_frequency = frequencies[item].frequency;
1156 AlertDialog alert_freq = builder_freq.create();
1159 case R.id.select_tracker:
1160 serverIntent = new Intent(this, SelectTrackerActivity.class);
1161 if (trackers != null) {
1162 ArrayList<Tracker> tracker_array = new ArrayList<Tracker>(Arrays.asList(trackers));
1163 serverIntent.putParcelableArrayListExtra(EXTRA_TRACKERS, tracker_array);
1165 serverIntent.putExtra(EXTRA_TRACKERS, (Parcelable[]) null);
1167 startActivityForResult(serverIntent, REQUEST_SELECT_TRACKER);
1169 case R.id.delete_track:
1170 if (trackers != null) {
1171 AlertDialog.Builder builder_serial = new AlertDialog.Builder(this);
1172 builder_serial.setTitle("Delete a track");
1173 final Tracker[] my_trackers = new Tracker[trackers.length - 1];
1174 for (int i = 0; i < trackers.length - 1; i++)
1175 my_trackers[i] = trackers[i+1];
1176 builder_serial.setItems(my_trackers,
1177 new DialogInterface.OnClickListener() {
1178 public void onClick(DialogInterface dialog, int item) {
1179 delete_track(my_trackers[item].serial);
1182 AlertDialog alert_serial = builder_serial.create();
1183 alert_serial.show();
1187 case R.id.idle_mode:
1188 serverIntent = new Intent(this, IdleModeActivity.class);
1189 serverIntent.putExtra(EXTRA_IDLE_MODE, idle_mode);
1190 serverIntent.putExtra(EXTRA_FREQUENCY, telem_frequency);
1191 startActivityForResult(serverIntent, REQUEST_IDLE_MODE);
1197 static String direction(AltosGreatCircle from_receiver,
1198 Location receiver) {
1199 if (from_receiver == null)
1202 if (receiver == null)
1205 if (!receiver.hasBearing())
1208 float bearing = receiver.getBearing();
1209 float heading = (float) from_receiver.bearing - bearing;
1211 while (heading <= -180.0f)
1213 while (heading > 180.0f)
1216 int iheading = (int) (heading + 0.5f);
1218 if (-1 < iheading && iheading < 1)
1220 else if (iheading < -179 || 179 < iheading)
1222 else if (iheading < 0)
1223 return String.format("left %d°", -iheading);
1225 return String.format("right %d°", iheading);
1228 public void onLocationChanged(Location location) {
1229 this.location = location;
1230 AltosDebug.debug("Location changed to %f,%f",
1231 location.getLatitude(),
1232 location.getLongitude());
1233 update_ui(telemetry_state, state, false);
1236 public void onStatusChanged(String provider, int status, Bundle extras) {
1237 AltosDebug.debug("Location status now %d\n", status);
1240 public void onProviderEnabled(String provider) {
1241 AltosDebug.debug("Location provider enabled %s\n", provider);
1244 public void onProviderDisabled(String provider) {
1245 AltosDebug.debug("Location provider disabled %s\n", provider);