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_serial == 0 || telemetry_state.get(selected_serial) == null) {
315 AltosDebug.debug("selected serial set to %d", selected_serial);
316 selected_serial = telemetry_state.latest_serial;
319 int shown_serial = selected_serial;
321 if (telemetry_state.idle_mode)
322 shown_serial = telemetry_state.latest_serial;
324 if (!registered_units_listener) {
325 registered_units_listener = true;
326 AltosPreferences.register_units_listener(this);
329 int num_trackers = 0;
331 for (AltosState s : telemetry_state.values()) {
335 trackers = new Tracker[num_trackers + 1];
338 trackers[n++] = new Tracker(0, "auto", 0.0);
340 for (AltosState s : telemetry_state.values())
341 trackers[n++] = new Tracker(s);
343 Arrays.sort(trackers);
345 if (telemetry_state.frequency != AltosLib.MISSING)
346 telem_frequency = telemetry_state.frequency;
348 update_title(telemetry_state);
350 AltosState state = telemetry_state.get(shown_serial);
352 update_ui(telemetry_state, state, telemetry_state.quiet);
357 boolean same_string(String a, String b) {
370 private int blend_component(int a, int b, double r, int shift, int mask) {
371 return ((int) (((a >> shift) & mask) * r + ((b >> shift) & mask) * (1 - r)) & mask) << shift;
373 private int blend_color(int a, int b, double r) {
374 return (blend_component(a, b, r, 0, 0xff) |
375 blend_component(a, b, r, 8, 0xff) |
376 blend_component(a, b, r, 16, 0xff) |
377 blend_component(a, b, r, 24, 0xff));
380 int state_age(long received_time) {
381 return (int) ((System.currentTimeMillis() - received_time + 500) / 1000);
384 void set_screen_on(int age) {
386 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
388 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
391 static String age_string(int age) {
394 text = String.format("%ds", age);
395 else if (age < 60 * 60)
396 text = String.format("%dm", age / 60);
397 else if (age < 60 * 60 * 24)
398 text = String.format("%dh", age / (60 * 60));
400 text = String.format("%dd", age / (24 * 60 * 60));
405 if (saved_state != null) {
406 int age = state_age(saved_state.received_time);
408 double age_scale = age / 100.0;
413 mAgeView.setTextColor(blend_color(mAgeOldColor, mAgeNewColor, age_scale));
417 mAgeView.setText(age_string(age));
421 void update_ui(TelemetryState telem_state, AltosState state, boolean quiet) {
425 int prev_state = AltosLib.ao_flight_invalid;
427 AltosGreatCircle from_receiver = null;
429 if (saved_state != null)
430 prev_state = saved_state.state;
433 set_screen_on(state_age(state.received_time));
435 if (state.state() == AltosLib.ao_flight_stateless) {
436 boolean prev_locked = false;
437 boolean locked = false;
439 if(state.gps != null)
440 locked = state.gps.locked;
441 if (saved_state != null)
442 prev_locked = saved_state.locked;
443 if (prev_locked != locked) {
444 String currentTab = mTabHost.getCurrentTabTag();
446 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
448 if (currentTab.equals(tab_flight_name)) mTabHost.setCurrentTabByTag(tab_pad_name);
452 if (prev_state != state.state()) {
453 String currentTab = mTabHost.getCurrentTabTag();
454 switch (state.state()) {
455 case AltosLib.ao_flight_boost:
456 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
458 case AltosLib.ao_flight_landed:
459 if (currentTab.equals(tab_flight_name)) mTabHost.setCurrentTabByTag(tab_recover_name);
461 case AltosLib.ao_flight_stateless:
462 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
468 if (location != null && state.gps != null && state.gps.locked) {
470 if (location.hasAltitude())
471 altitude = location.getAltitude();
472 from_receiver = new AltosGreatCircle(location.getLatitude(),
473 location.getLongitude(),
480 if (saved_state == null || !same_string(saved_state.callsign, state.cal_data().callsign)) {
481 mCallsignView.setText(state.cal_data().callsign);
483 if (saved_state == null || state.cal_data().serial != saved_state.serial) {
484 if (state.cal_data().serial == AltosLib.MISSING)
485 mSerialView.setText("");
487 mSerialView.setText(String.format("%d", state.cal_data().serial));
489 if (saved_state == null || state.cal_data().flight != saved_state.flight) {
490 if (state.cal_data().flight == AltosLib.MISSING)
491 mFlightView.setText("");
493 mFlightView.setText(String.format("%d", state.cal_data().flight));
495 if (saved_state == null || state.state() != saved_state.state) {
496 if (state.state() == AltosLib.ao_flight_stateless) {
497 mStateLayout.setVisibility(View.GONE);
499 mStateView.setText(state.state_name());
500 mStateLayout.setVisibility(View.VISIBLE);
503 if (saved_state == null || state.rssi != saved_state.rssi) {
504 if (state.rssi == AltosLib.MISSING)
505 mRSSIView.setText("");
507 mRSSIView.setText(String.format("%d", state.rssi));
509 saved_state = new SavedState(state);
512 for (AltosDroidTab mTab : mTabs)
513 mTab.update_ui(telem_state, state, from_receiver, location, mTab == mTabsAdapter.currentItem());
515 if (mAltosVoice != null && mTabsAdapter.currentItem() != null)
516 mAltosVoice.tell(telem_state, state, from_receiver, location, (AltosDroidTab) mTabsAdapter.currentItem(), quiet);
520 private void onTimerTick() {
522 mMessenger.send(Message.obtain(null, MSG_UPDATE_AGE));
523 } catch (RemoteException e) {
527 static String pos(double p, String pos, String neg) {
529 if (p == AltosLib.MISSING)
535 int deg = (int) Math.floor(p);
536 double min = (p - Math.floor(p)) * 60.0;
537 return String.format("%d° %7.4f\" %s", deg, min, h);
540 static String number(String format, double value) {
541 if (value == AltosLib.MISSING)
543 return String.format(format, value);
546 static String integer(String format, int value) {
547 if (value == AltosLib.MISSING)
549 return String.format(format, value);
552 private View create_tab_view(String label) {
553 LayoutInflater inflater = (LayoutInflater) this.getLayoutInflater();
554 View tab_view = inflater.inflate(R.layout.tab_layout, null);
555 TextView text_view = (TextView) tab_view.findViewById (R.id.tabLabel);
556 text_view.setText(label);
560 static public int[] themes = {
567 static public int[] dialog_themes = {
568 R.style.Small_Dialog,
569 R.style.Medium_Dialog,
570 R.style.Large_Dialog,
575 public void onCreate(Bundle savedInstanceState) {
576 // Initialise preferences
577 AltosDroidPreferences.init(this);
578 setTheme(themes[AltosDroidPreferences.font_size()]);
579 super.onCreate(savedInstanceState);
580 AltosDebug.init(this);
581 AltosDebug.debug("+++ ON CREATE +++");
584 fm = getSupportFragmentManager();
586 // Set up the window layout
587 setContentView(R.layout.altosdroid);
589 // Create the Tabs and ViewPager
590 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
593 mViewPager = (AltosViewPager)findViewById(R.id.pager);
594 mViewPager.setOffscreenPageLimit(4);
596 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
598 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_pad_name).setIndicator(create_tab_view("Pad")), TabPad.class, null);
599 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_flight_name).setIndicator(create_tab_view("Flight")), TabFlight.class, null);
600 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_recover_name).setIndicator(create_tab_view("Recover")), TabRecover.class, null);
601 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_map_name).setIndicator(create_tab_view("Map")), TabMap.class, null);
603 // Display the Version
604 mVersion = (TextView) findViewById(R.id.version);
605 mVersion.setText("Version: " + BuildInfo.version +
606 " Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
607 " (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
609 mCallsignView = (TextView) findViewById(R.id.callsign_value);
610 mRSSIView = (TextView) findViewById(R.id.rssi_value);
611 mSerialView = (TextView) findViewById(R.id.serial_value);
612 mFlightView = (TextView) findViewById(R.id.flight_value);
613 mStateLayout = (RelativeLayout) findViewById(R.id.state_container);
614 mStateView = (TextView) findViewById(R.id.state_value);
615 mAgeView = (TextView) findViewById(R.id.age_value);
616 mAgeNewColor = mAgeView.getTextColors().getDefaultColor();
617 mAgeOldColor = getResources().getColor(R.color.old_color, getTheme());
620 private void ensureBluetooth() {
621 // Get local Bluetooth adapter
622 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
624 /* if there is a BT adapter and it isn't turned on, then turn it on */
625 if (mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) {
626 Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
627 startActivityForResult(enableIntent, AltosDroid.REQUEST_ENABLE_BT);
631 private boolean check_usb() {
632 UsbDevice device = AltosUsb.find_device(this, AltosLib.product_basestation);
634 if (device != null) {
635 Intent i = new Intent(this, AltosDroid.class);
636 PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent("hello world", null, this, AltosDroid.class), 0);
638 if (AltosUsb.request_permission(this, device, pi)) {
641 start_with_usb = true;
645 start_with_usb = false;
650 private void noticeIntent(Intent intent) {
652 /* Ok, this is pretty convenient.
654 * When a USB device is plugged in, and our 'hotplug'
655 * intent registration fires, we get an Intent with
658 * When we start up and see a usb device and request
659 * permission to access it, that queues a
660 * PendingIntent, which has the EXTRA_DEVICE added in,
661 * along with the EXTRA_PERMISSION_GRANTED field as
664 * So, in both cases, we get the device name using the
665 * same call. We check to see if access was granted,
666 * in which case we ignore the device field and do our
667 * usual startup thing.
670 UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
671 boolean granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, true);
673 AltosDebug.debug("intent %s device %s granted %s", intent, device, granted);
678 if (device != null) {
679 AltosDebug.debug("intent has usb device " + device.toString());
683 /* 'granted' is only false if this intent came
684 * from the request_permission call and
685 * permission was denied. In which case, we
686 * don't want to loop forever...
689 AltosDebug.debug("check for a USB device at startup");
693 AltosDebug.debug("Starting by looking for bluetooth devices");
699 public void onStart() {
701 AltosDebug.debug("++ ON START ++");
705 noticeIntent(getIntent());
707 // Start Telemetry Service
708 String action = start_with_usb ? ACTION_USB : ACTION_BLUETOOTH;
710 startService(new Intent(action, null, AltosDroid.this, TelemetryService.class));
714 if (mAltosVoice == null)
715 mAltosVoice = new AltosVoice(this);
720 public void onNewIntent(Intent intent) {
721 super.onNewIntent(intent);
722 AltosDebug.debug("onNewIntent");
723 noticeIntent(intent);
726 private void enable_location_updates() {
727 // Listen for GPS and Network position updates
728 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
729 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
731 location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
733 if (location != null)
734 AltosDebug.debug("Resume, location is %f,%f\n",
735 location.getLatitude(),
736 location.getLongitude());
738 update_ui(telemetry_state, state, true);
741 static final int MY_PERMISSION_REQUEST = 1001;
743 public boolean have_location_permission = false;
744 public boolean have_storage_permission = false;
745 public boolean asked_permission = false;
747 AltosMapOnline map_online;
750 tell_map_permission(AltosMapOnline map_online) {
751 this.map_online = map_online;
755 public void onRequestPermissionsResult(int requestCode, String[] permissions,
756 int[] grantResults) {
757 if (requestCode == MY_PERMISSION_REQUEST) {
758 for (int i = 0; i < grantResults.length; i++) {
759 if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
760 if (permissions[i].equals(Manifest.permission.ACCESS_FINE_LOCATION)) {
761 have_location_permission = true;
762 enable_location_updates();
763 if (map_online != null)
764 map_online.position_permission();
766 if (permissions[i].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
767 have_storage_permission = true;
775 public void onResume() {
777 AltosDebug.debug("+ ON RESUME +");
779 if (!asked_permission) {
780 asked_permission = true;
781 if (ActivityCompat.checkSelfPermission(this,
782 Manifest.permission.ACCESS_FINE_LOCATION)
783 == PackageManager.PERMISSION_GRANTED)
785 have_location_permission = true;
787 if (ActivityCompat.checkSelfPermission(this,
788 Manifest.permission.WRITE_EXTERNAL_STORAGE)
789 == PackageManager.PERMISSION_GRANTED)
791 have_storage_permission = true;
793 int count = (have_location_permission ? 0 : 1) + (have_storage_permission ? 0 : 1);
796 String[] permissions = new String[count];
798 if (!have_location_permission)
799 permissions[i++] = Manifest.permission.ACCESS_FINE_LOCATION;
800 if (!have_location_permission)
801 permissions[i++] = Manifest.permission.WRITE_EXTERNAL_STORAGE;
802 ActivityCompat.requestPermissions(this, permissions, MY_PERMISSION_REQUEST);
805 if (have_location_permission)
806 enable_location_updates();
810 public void onPause() {
812 AltosDebug.debug("- ON PAUSE -");
813 // Stop listening for location updates
814 if (have_location_permission)
815 ((LocationManager) getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
819 public void onStop() {
821 AltosDebug.debug("-- ON STOP --");
825 public void onDestroy() {
827 AltosDebug.debug("--- ON DESTROY ---");
830 if (mAltosVoice != null) {
837 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
838 AltosDebug.debug("onActivityResult request %d result %d", requestCode, resultCode);
839 switch (requestCode) {
840 case REQUEST_CONNECT_DEVICE:
841 // When DeviceListActivity returns with a device to connect to
842 if (resultCode == Activity.RESULT_OK) {
846 case REQUEST_ENABLE_BT:
847 // When the request to enable Bluetooth returns
848 if (resultCode == Activity.RESULT_OK) {
849 // Bluetooth is now enabled, so set up a chat session
851 AltosDebug.debug("BT enabled");
852 bluetoothEnabled(data);
854 // User did not enable Bluetooth or an error occured
855 AltosDebug.debug("BT not enabled");
858 case REQUEST_IDLE_MODE:
859 if (resultCode == Activity.RESULT_OK)
862 case REQUEST_IGNITERS:
865 if (resultCode == Activity.RESULT_OK)
866 note_setup_changes(data);
868 case REQUEST_SELECT_TRACKER:
869 if (resultCode == Activity.RESULT_OK)
870 select_tracker(data);
875 private void note_setup_changes(Intent data) {
876 int changes = data.getIntExtra(SetupActivity.EXTRA_SETUP_CHANGES, 0);
878 AltosDebug.debug("note_setup_changes changes %d\n", changes);
880 if ((changes & SETUP_BAUD) != 0) {
882 mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD,
883 AltosPreferences.telemetry_rate(1)));
884 } catch (RemoteException re) {
887 if ((changes & SETUP_UNITS) != 0) {
888 /* nothing to do here */
890 if ((changes & SETUP_MAP_SOURCE) != 0) {
891 /* nothing to do here */
893 if ((changes & SETUP_MAP_TYPE) != 0) {
894 /* nothing to do here */
897 if ((changes & SETUP_FONT_SIZE) != 0) {
898 AltosDebug.debug(" ==== Recreate to switch font sizes ==== ");
900 startActivity(getIntent());
904 private void connectUsb(UsbDevice device) {
905 if (mService == null)
906 pending_usb_device = device;
908 // Attempt to connect to the device
910 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, device));
911 AltosDebug.debug("Sent OPEN_USB message");
912 } catch (RemoteException e) {
913 AltosDebug.debug("connect device message failed");
918 private void bluetoothEnabled(Intent data) {
919 if (mService != null) {
921 mService.send(Message.obtain(null, TelemetryService.MSG_BLUETOOTH_ENABLED, null));
922 } catch (RemoteException e) {
923 AltosDebug.debug("send BT enabled message failed");
928 private void connectDevice(Intent data) {
929 // Attempt to connect to the device
931 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
932 String name = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_NAME);
934 AltosDebug.debug("Connecting to " + address + " " + name);
935 DeviceAddress a = new DeviceAddress(address, name);
936 mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, a));
937 AltosDebug.debug("Sent connecting message");
938 } catch (RemoteException e) {
939 AltosDebug.debug("connect device message failed");
943 private void disconnectDevice(boolean remember) {
945 mService.send(Message.obtain(null, TelemetryService.MSG_DISCONNECT, (Boolean) remember));
946 } catch (RemoteException e) {
950 private void idle_mode(Intent data) {
951 int type = data.getIntExtra(IdleModeActivity.EXTRA_IDLE_RESULT, -1);
954 AltosDebug.debug("intent idle_mode %d", type);
956 case IdleModeActivity.IDLE_MODE_CONNECT:
957 msg = Message.obtain(null, TelemetryService.MSG_MONITOR_IDLE_START);
960 } catch (RemoteException re) {
963 case IdleModeActivity.IDLE_MODE_DISCONNECT:
964 msg = Message.obtain(null, TelemetryService.MSG_MONITOR_IDLE_STOP);
967 } catch (RemoteException re) {
970 case IdleModeActivity.IDLE_MODE_REBOOT:
971 msg = Message.obtain(null, TelemetryService.MSG_REBOOT);
974 } catch (RemoteException re) {
977 case IdleModeActivity.IDLE_MODE_IGNITERS:
978 Intent serverIntent = new Intent(this, IgniterActivity.class);
979 startActivityForResult(serverIntent, REQUEST_IGNITERS);
985 public boolean onCreateOptionsMenu(Menu menu) {
986 MenuInflater inflater = getMenuInflater();
987 inflater.inflate(R.menu.option_menu, menu);
991 double telem_frequency = 434.550;
993 void setFrequency(double freq) {
994 telem_frequency = freq;
996 mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
998 } catch (RemoteException e) {
1002 void setFrequency(AltosFrequency frequency) {
1003 setFrequency (frequency.frequency);
1006 void setBaud(int baud) {
1008 mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD, baud));
1010 } catch (RemoteException e) {
1014 void setBaud(String baud) {
1016 int value = Integer.parseInt(baud);
1017 int rate = AltosLib.ao_telemetry_rate_38400;
1020 rate = AltosLib.ao_telemetry_rate_2400;
1023 rate = AltosLib.ao_telemetry_rate_9600;
1026 rate = AltosLib.ao_telemetry_rate_38400;
1030 } catch (NumberFormatException e) {
1034 void select_tracker(int serial, double frequency) {
1036 AltosDebug.debug("select tracker %d %7.3f\n", serial, frequency);
1038 if (serial == selected_serial) {
1039 AltosDebug.debug("%d already selected\n", serial);
1045 for (i = 0; i < trackers.length; i++)
1046 if (trackers[i].serial == serial)
1049 if (i == trackers.length) {
1050 AltosDebug.debug("attempt to select unknown tracker %d\n", serial);
1053 if (frequency != 0.0 && frequency != AltosLib.MISSING)
1054 setFrequency(frequency);
1057 selected_serial = serial;
1061 void select_tracker(Intent data) {
1062 int serial = data.getIntExtra(SelectTrackerActivity.EXTRA_SERIAL_NUMBER, 0);
1063 double frequency = data.getDoubleExtra(SelectTrackerActivity.EXTRA_FREQUENCY, 0.0);
1064 select_tracker(serial, frequency);
1067 void touch_trackers(Integer[] serials) {
1068 AlertDialog.Builder builder_tracker = new AlertDialog.Builder(this);
1069 builder_tracker.setTitle("Select Tracker");
1071 final Tracker[] my_trackers = new Tracker[serials.length + 1];
1073 my_trackers[0] = new Tracker(null);
1075 for (int i = 0; i < serials.length; i++) {
1076 AltosState s = telemetry_state.get(serials[i]);
1077 my_trackers[i+1] = new Tracker(s);
1079 builder_tracker.setItems(my_trackers,
1080 new DialogInterface.OnClickListener() {
1081 public void onClick(DialogInterface dialog, int item) {
1083 select_tracker(0, 0.0);
1085 select_tracker(my_trackers[item].serial, my_trackers[item].frequency);
1088 AlertDialog alert_tracker = builder_tracker.create();
1089 alert_tracker.show();
1092 void delete_track(int serial) {
1094 mService.send(Message.obtain(null, TelemetryService.MSG_DELETE_SERIAL, (Integer) serial));
1095 } catch (Exception ex) {
1100 public boolean onOptionsItemSelected(MenuItem item) {
1101 Intent serverIntent = null;
1102 switch (item.getItemId()) {
1103 case R.id.connect_scan:
1105 // Launch the DeviceListActivity to see devices and do scan
1106 serverIntent = new Intent(this, DeviceListActivity.class);
1107 startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
1109 case R.id.disconnect:
1110 /* Disconnect the device
1112 disconnectDevice(false);
1115 AltosDebug.debug("R.id.quit");
1116 disconnectDevice(true);
1120 serverIntent = new Intent(this, SetupActivity.class);
1121 startActivityForResult(serverIntent, REQUEST_SETUP);
1123 case R.id.select_freq:
1124 // Set the TBT radio frequency
1126 final AltosFrequency[] frequencies = AltosPreferences.common_frequencies();
1127 String[] frequency_strings = new String[frequencies.length];
1128 for (int i = 0; i < frequencies.length; i++)
1129 frequency_strings[i] = frequencies[i].toString();
1131 AlertDialog.Builder builder_freq = new AlertDialog.Builder(this);
1132 builder_freq.setTitle("Pick a frequency");
1133 builder_freq.setItems(frequency_strings,
1134 new DialogInterface.OnClickListener() {
1135 public void onClick(DialogInterface dialog, int item) {
1136 setFrequency(frequencies[item]);
1139 AlertDialog alert_freq = builder_freq.create();
1142 case R.id.select_tracker:
1143 serverIntent = new Intent(this, SelectTrackerActivity.class);
1144 if (trackers != null) {
1145 ArrayList<Tracker> tracker_array = new ArrayList<Tracker>(Arrays.asList(trackers));
1146 serverIntent.putParcelableArrayListExtra(EXTRA_TRACKERS, tracker_array);
1148 serverIntent.putExtra(EXTRA_TRACKERS, (Parcelable[]) null);
1150 startActivityForResult(serverIntent, REQUEST_SELECT_TRACKER);
1152 case R.id.delete_track:
1153 if (trackers != null) {
1154 AlertDialog.Builder builder_serial = new AlertDialog.Builder(this);
1155 builder_serial.setTitle("Delete a track");
1156 final Tracker[] my_trackers = new Tracker[trackers.length - 1];
1157 for (int i = 0; i < trackers.length - 1; i++)
1158 my_trackers[i] = trackers[i+1];
1159 builder_serial.setItems(my_trackers,
1160 new DialogInterface.OnClickListener() {
1161 public void onClick(DialogInterface dialog, int item) {
1162 delete_track(my_trackers[item].serial);
1165 AlertDialog alert_serial = builder_serial.create();
1166 alert_serial.show();
1170 case R.id.idle_mode:
1171 serverIntent = new Intent(this, IdleModeActivity.class);
1172 serverIntent.putExtra(EXTRA_IDLE_MODE, idle_mode);
1173 serverIntent.putExtra(EXTRA_FREQUENCY, telem_frequency);
1174 startActivityForResult(serverIntent, REQUEST_IDLE_MODE);
1180 static String direction(AltosGreatCircle from_receiver,
1181 Location receiver) {
1182 if (from_receiver == null)
1185 if (receiver == null)
1188 if (!receiver.hasBearing())
1191 float bearing = receiver.getBearing();
1192 float heading = (float) from_receiver.bearing - bearing;
1194 while (heading <= -180.0f)
1196 while (heading > 180.0f)
1199 int iheading = (int) (heading + 0.5f);
1201 if (-1 < iheading && iheading < 1)
1203 else if (iheading < -179 || 179 < iheading)
1205 else if (iheading < 0)
1206 return String.format("left %d°", -iheading);
1208 return String.format("right %d°", iheading);
1211 public void onLocationChanged(Location location) {
1212 this.location = location;
1213 AltosDebug.debug("Location changed to %f,%f",
1214 location.getLatitude(),
1215 location.getLongitude());
1216 update_ui(telemetry_state, state, false);
1219 public void onStatusChanged(String provider, int status, Bundle extras) {
1220 AltosDebug.debug("Location status now %d\n", status);
1223 public void onProviderEnabled(String provider) {
1224 AltosDebug.debug("Location provider enabled %s\n", provider);
1227 public void onProviderDisabled(String provider) {
1228 AltosDebug.debug("Location provider disabled %s\n", provider);