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 androidx.fragment.app.FragmentActivity;
40 import androidx.fragment.app.FragmentManager;
41 import android.view.*;
42 import android.widget.*;
43 import android.app.AlertDialog;
44 import android.location.Location;
45 import android.location.LocationManager;
46 import android.location.LocationListener;
47 import android.hardware.usb.*;
48 import android.content.pm.PackageManager;
49 import androidx.core.app.ActivityCompat;
50 import org.altusmetrum.altoslib_13.*;
61 SavedState(AltosState state) {
62 received_time = state.received_time;
63 this.state = state.state();
64 if (state.gps != null)
65 locked = state.gps.locked;
68 callsign = state.cal_data().callsign;
69 serial = state.cal_data().serial;
70 flight = state.cal_data().flight;
75 class Tracker implements CharSequence, Comparable {
82 public Tracker(int serial, String call, double frequency) {
88 this.frequency = frequency;
91 else if (frequency == AltosLib.MISSING) {
92 display = String.format("%-8.8s %6d", call, serial);
94 display = String.format("%-8.8s %7.3f %6d", call, frequency, serial);
98 public Tracker(AltosState s) {
99 this(s == null ? 0 : s.cal_data().serial,
100 s == null ? null : s.cal_data().callsign,
101 s == null ? 0.0 : s.frequency);
105 public char charAt(int index) {
106 return display.charAt(index);
109 public int length() {
110 return display.length();
113 public CharSequence subSequence(int start, int end) throws IndexOutOfBoundsException {
114 return display.subSequence(start, end);
117 public String toString() {
118 return display.toString();
122 public int compareTo (Object other) {
123 Tracker o = (Tracker) other;
124 if (frequency == 0.0) {
125 if (o.frequency == 0.0)
129 if (o.frequency == 0.0)
132 int a = serial - o.serial;
133 int b = call.compareTo(o.call);
134 int c = (int) Math.signum(frequency - o.frequency);
144 public class AltosDroid extends FragmentActivity implements AltosUnitsListener, LocationListener, ActivityCompat.OnRequestPermissionsResultCallback {
146 // Actions sent to the telemetry server at startup time
148 public static final String ACTION_BLUETOOTH = "org.altusmetrum.AltosDroid.BLUETOOTH";
149 public static final String ACTION_USB = "org.altusmetrum.AltosDroid.USB";
151 // Message types received by our Handler
153 public static final int MSG_STATE = 1;
154 public static final int MSG_UPDATE_AGE = 2;
155 public static final int MSG_IDLE_MODE = 3;
156 public static final int MSG_IGNITER_STATUS = 4;
158 // Intent request codes
159 public static final int REQUEST_CONNECT_DEVICE = 1;
160 public static final int REQUEST_ENABLE_BT = 2;
161 public static final int REQUEST_PRELOAD_MAPS = 3;
162 public static final int REQUEST_IDLE_MODE = 5;
163 public static final int REQUEST_IGNITERS = 6;
164 public static final int REQUEST_SETUP = 7;
166 public static final String EXTRA_IDLE_MODE = "idle_mode";
167 public static final String EXTRA_IDLE_RESULT = "idle_result";
168 public static final String EXTRA_TELEMETRY_SERVICE = "telemetry_service";
171 public static final int SETUP_BAUD = 1;
172 public static final int SETUP_UNITS = 2;
173 public static final int SETUP_MAP_SOURCE = 4;
174 public static final int SETUP_MAP_TYPE = 8;
175 public static final int SETUP_FONT_SIZE = 16;
177 public static FragmentManager fm;
179 private BluetoothAdapter mBluetoothAdapter = null;
181 // Flight state values
182 private TextView mCallsignView;
183 private TextView mRSSIView;
184 private TextView mSerialView;
185 private TextView mFlightView;
186 private RelativeLayout mStateLayout;
187 private TextView mStateView;
188 private TextView mAgeView;
189 private boolean mAgeViewOld;
190 private int mAgeNewColor;
191 private int mAgeOldColor;
193 public static final String tab_pad_name = "pad";
194 public static final String tab_flight_name = "flight";
195 public static final String tab_recover_name = "recover";
196 public static final String tab_map_name = "map";
198 // field to display the version at the bottom of the screen
199 private TextView mVersion;
201 private boolean idle_mode = false;
203 public Location location = null;
205 private AltosState state;
206 private SavedState saved_state;
210 AltosViewPager mViewPager;
211 TabsAdapter mTabsAdapter;
212 ArrayList<AltosDroidTab> mTabs = new ArrayList<AltosDroidTab>();
215 // Timer and Saved flight state for Age calculation
218 TelemetryState telemetry_state;
222 UsbDevice pending_usb_device;
223 boolean start_with_usb;
226 private boolean mIsBound = false;
227 private Messenger mService = null;
228 final Messenger mMessenger = new Messenger(new IncomingHandler(this));
231 private AltosVoice mAltosVoice = null;
233 // The Handler that gets information back from the Telemetry Service
234 static class IncomingHandler extends Handler {
235 private final WeakReference<AltosDroid> mAltosDroid;
236 IncomingHandler(AltosDroid ad) { mAltosDroid = new WeakReference<AltosDroid>(ad); }
239 public void handleMessage(Message msg) {
240 AltosDroid ad = mAltosDroid.get();
244 if (msg.obj == null) {
245 AltosDebug.debug("telemetry_state null!");
248 ad.update_state((TelemetryState) msg.obj);
254 ad.idle_mode = (Boolean) msg.obj;
255 ad.update_state(null);
262 private ServiceConnection mConnection = new ServiceConnection() {
263 public void onServiceConnected(ComponentName className, IBinder service) {
264 mService = new Messenger(service);
266 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
267 msg.replyTo = mMessenger;
269 } catch (RemoteException e) {
270 // In this case the service has crashed before we could even do anything with it
272 if (pending_usb_device != null) {
274 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, pending_usb_device));
275 pending_usb_device = null;
276 } catch (RemoteException e) {
281 public void onServiceDisconnected(ComponentName className) {
282 // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
287 void doBindService() {
288 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
292 void doUnbindService() {
294 // If we have received the service, and hence registered with it, then now is the time to unregister.
295 if (mService != null) {
297 Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
298 msg.replyTo = mMessenger;
300 } catch (RemoteException e) {
301 // There is nothing special we need to do if the service has crashed.
304 // Detach our existing connection.
305 unbindService(mConnection);
310 public void registerTab(AltosDroidTab mTab) {
314 public void unregisterTab(AltosDroidTab mTab) {
318 public void units_changed(boolean imperial_units) {
319 for (AltosDroidTab mTab : mTabs)
320 mTab.units_changed(imperial_units);
323 void update_title(TelemetryState telemetry_state) {
324 switch (telemetry_state.connect) {
325 case TelemetryState.CONNECT_CONNECTED:
326 if (telemetry_state.config != null) {
327 String str = String.format("S/N %d %6.3f MHz%s", telemetry_state.config.serial,
328 telemetry_state.frequency, idle_mode ? " (idle)" : "");
329 if (telemetry_state.telemetry_rate != AltosLib.ao_telemetry_rate_38400)
330 str = str.concat(String.format(" %d bps",
331 AltosLib.ao_telemetry_rate_values[telemetry_state.telemetry_rate]));
334 setTitle(R.string.title_connected_to);
337 case TelemetryState.CONNECT_CONNECTING:
338 if (telemetry_state.address != null)
339 setTitle(String.format("Connecting to %s...", telemetry_state.address.name));
341 setTitle("Connecting to something...");
343 case TelemetryState.CONNECT_DISCONNECTED:
344 case TelemetryState.CONNECT_NONE:
345 setTitle(R.string.title_not_connected);
353 timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 1000L, 1000L);
365 int selected_serial = 0;
369 void set_switch_time() {
370 switch_time = System.currentTimeMillis();
374 boolean registered_units_listener;
376 void update_state(TelemetryState new_telemetry_state) {
378 if (new_telemetry_state != null)
379 telemetry_state = new_telemetry_state;
381 if (selected_serial != 0)
382 current_serial = selected_serial;
384 if (current_serial == 0)
385 current_serial = telemetry_state.latest_serial;
387 if (!registered_units_listener) {
388 registered_units_listener = true;
389 AltosPreferences.register_units_listener(this);
392 int num_trackers = 0;
393 for (AltosState s : telemetry_state.states.values()) {
397 trackers = new Tracker[num_trackers + 1];
400 trackers[n++] = new Tracker(0, "auto", 0.0);
402 for (AltosState s : telemetry_state.states.values())
403 trackers[n++] = new Tracker(s);
405 Arrays.sort(trackers);
407 update_title(telemetry_state);
409 AltosState state = null;
412 if (telemetry_state.states.containsKey(current_serial)) {
413 state = telemetry_state.states.get(current_serial);
414 int age = state_age(state.received_time);
417 if (current_serial == selected_serial)
419 else if (switch_time != 0 && (switch_time - state.received_time) > 0)
424 AltosState newest_state = null;
427 for (int serial : telemetry_state.states.keySet()) {
428 AltosState existing = telemetry_state.states.get(serial);
429 int existing_age = state_age(existing.received_time);
431 if (newest_state == null || existing_age < newest_age) {
432 newest_state = existing;
433 newest_age = existing_age;
437 if (newest_state != null)
438 state = newest_state;
441 update_ui(telemetry_state, state, telemetry_state.quiet);
446 boolean same_string(String a, String b) {
459 private int blend_component(int a, int b, double r, int shift, int mask) {
460 return ((int) (((a >> shift) & mask) * r + ((b >> shift) & mask) * (1 - r)) & mask) << shift;
462 private int blend_color(int a, int b, double r) {
463 return (blend_component(a, b, r, 0, 0xff) |
464 blend_component(a, b, r, 8, 0xff) |
465 blend_component(a, b, r, 16, 0xff) |
466 blend_component(a, b, r, 24, 0xff));
469 int state_age(long received_time) {
470 return (int) ((System.currentTimeMillis() - received_time + 500) / 1000);
473 void set_screen_on(int age) {
475 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
477 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
481 if (saved_state != null) {
482 int age = state_age(saved_state.received_time);
484 double age_scale = age / 100.0;
489 mAgeView.setTextColor(blend_color(mAgeOldColor, mAgeNewColor, age_scale));
495 text = String.format("%ds", age);
496 else if (age < 60 * 60)
497 text = String.format("%dm", age / 60);
498 else if (age < 60 * 60 * 24)
499 text = String.format("%dh", age / (60 * 60));
501 text = String.format("%dd", age / (24 * 60 * 60));
502 mAgeView.setText(text);
506 void update_ui(TelemetryState telem_state, AltosState state, boolean quiet) {
510 int prev_state = AltosLib.ao_flight_invalid;
512 AltosGreatCircle from_receiver = null;
514 if (saved_state != null)
515 prev_state = saved_state.state;
518 set_screen_on(state_age(state.received_time));
520 if (state.state() == AltosLib.ao_flight_stateless) {
521 boolean prev_locked = false;
522 boolean locked = false;
524 if(state.gps != null)
525 locked = state.gps.locked;
526 if (saved_state != null)
527 prev_locked = saved_state.locked;
528 if (prev_locked != locked) {
529 String currentTab = mTabHost.getCurrentTabTag();
531 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
533 if (currentTab.equals(tab_flight_name)) mTabHost.setCurrentTabByTag(tab_pad_name);
537 if (prev_state != state.state()) {
538 String currentTab = mTabHost.getCurrentTabTag();
539 switch (state.state()) {
540 case AltosLib.ao_flight_boost:
541 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
543 case AltosLib.ao_flight_landed:
544 if (currentTab.equals(tab_flight_name)) mTabHost.setCurrentTabByTag(tab_recover_name);
546 case AltosLib.ao_flight_stateless:
547 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
553 if (location != null && state.gps != null && state.gps.locked) {
555 if (location.hasAltitude())
556 altitude = location.getAltitude();
557 from_receiver = new AltosGreatCircle(location.getLatitude(),
558 location.getLongitude(),
565 if (saved_state == null || !same_string(saved_state.callsign, state.cal_data().callsign)) {
566 mCallsignView.setText(state.cal_data().callsign);
568 if (saved_state == null || state.cal_data().serial != saved_state.serial) {
569 if (state.cal_data().serial == AltosLib.MISSING)
570 mSerialView.setText("");
572 mSerialView.setText(String.format("%d", state.cal_data().serial));
574 if (saved_state == null || state.cal_data().flight != saved_state.flight) {
575 if (state.cal_data().flight == AltosLib.MISSING)
576 mFlightView.setText("");
578 mFlightView.setText(String.format("%d", state.cal_data().flight));
580 if (saved_state == null || state.state() != saved_state.state) {
581 if (state.state() == AltosLib.ao_flight_stateless) {
582 mStateLayout.setVisibility(View.GONE);
584 mStateView.setText(state.state_name());
585 mStateLayout.setVisibility(View.VISIBLE);
588 if (saved_state == null || state.rssi != saved_state.rssi) {
589 if (state.rssi == AltosLib.MISSING)
590 mRSSIView.setText("");
592 mRSSIView.setText(String.format("%d", state.rssi));
594 saved_state = new SavedState(state);
597 for (AltosDroidTab mTab : mTabs)
598 mTab.update_ui(telem_state, state, from_receiver, location, mTab == mTabsAdapter.currentItem());
600 if (mAltosVoice != null && mTabsAdapter.currentItem() != null)
601 mAltosVoice.tell(telem_state, state, from_receiver, location, (AltosDroidTab) mTabsAdapter.currentItem(), quiet);
605 private void onTimerTick() {
607 mMessenger.send(Message.obtain(null, MSG_UPDATE_AGE));
608 } catch (RemoteException e) {
612 static String pos(double p, String pos, String neg) {
614 if (p == AltosLib.MISSING)
620 int deg = (int) Math.floor(p);
621 double min = (p - Math.floor(p)) * 60.0;
622 return String.format("%d° %7.4f\" %s", deg, min, h);
625 static String number(String format, double value) {
626 if (value == AltosLib.MISSING)
628 return String.format(format, value);
631 static String integer(String format, int value) {
632 if (value == AltosLib.MISSING)
634 return String.format(format, value);
637 private View create_tab_view(String label) {
638 LayoutInflater inflater = (LayoutInflater) this.getLayoutInflater();
639 View tab_view = inflater.inflate(R.layout.tab_layout, null);
640 TextView text_view = (TextView) tab_view.findViewById (R.id.tabLabel);
641 text_view.setText(label);
645 static public int[] themes = {
652 static public int[] dialog_themes = {
653 R.style.Small_Dialog,
654 R.style.Medium_Dialog,
655 R.style.Large_Dialog,
660 public void onCreate(Bundle savedInstanceState) {
661 // Initialise preferences
662 AltosDroidPreferences.init(this);
663 setTheme(themes[AltosDroidPreferences.font_size()]);
664 super.onCreate(savedInstanceState);
665 AltosDebug.init(this);
666 AltosDebug.debug("+++ ON CREATE +++");
669 fm = getSupportFragmentManager();
671 // Set up the window layout
672 setContentView(R.layout.altosdroid);
674 // Create the Tabs and ViewPager
675 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
678 mViewPager = (AltosViewPager)findViewById(R.id.pager);
679 mViewPager.setOffscreenPageLimit(4);
681 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
683 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_pad_name).setIndicator(create_tab_view("Pad")), TabPad.class, null);
684 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_flight_name).setIndicator(create_tab_view("Flight")), TabFlight.class, null);
685 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_recover_name).setIndicator(create_tab_view("Recover")), TabRecover.class, null);
686 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_map_name).setIndicator(create_tab_view("Map")), TabMap.class, null);
688 // Display the Version
689 mVersion = (TextView) findViewById(R.id.version);
690 mVersion.setText("Version: " + BuildInfo.version +
691 " Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
692 " (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
694 mCallsignView = (TextView) findViewById(R.id.callsign_value);
695 mRSSIView = (TextView) findViewById(R.id.rssi_value);
696 mSerialView = (TextView) findViewById(R.id.serial_value);
697 mFlightView = (TextView) findViewById(R.id.flight_value);
698 mStateLayout = (RelativeLayout) findViewById(R.id.state_container);
699 mStateView = (TextView) findViewById(R.id.state_value);
700 mAgeView = (TextView) findViewById(R.id.age_value);
701 mAgeNewColor = mAgeView.getTextColors().getDefaultColor();
702 mAgeOldColor = getResources().getColor(R.color.old_color);
705 private void ensureBluetooth() {
706 // Get local Bluetooth adapter
707 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
709 /* if there is a BT adapter and it isn't turned on, then turn it on */
710 if (mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) {
711 Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
712 startActivityForResult(enableIntent, AltosDroid.REQUEST_ENABLE_BT);
716 private boolean check_usb() {
717 UsbDevice device = AltosUsb.find_device(this, AltosLib.product_basestation);
719 if (device != null) {
720 Intent i = new Intent(this, AltosDroid.class);
721 PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent("hello world", null, this, AltosDroid.class), 0);
723 if (AltosUsb.request_permission(this, device, pi)) {
726 start_with_usb = true;
730 start_with_usb = false;
735 private void noticeIntent(Intent intent) {
737 /* Ok, this is pretty convenient.
739 * When a USB device is plugged in, and our 'hotplug'
740 * intent registration fires, we get an Intent with
743 * When we start up and see a usb device and request
744 * permission to access it, that queues a
745 * PendingIntent, which has the EXTRA_DEVICE added in,
746 * along with the EXTRA_PERMISSION_GRANTED field as
749 * So, in both cases, we get the device name using the
750 * same call. We check to see if access was granted,
751 * in which case we ignore the device field and do our
752 * usual startup thing.
755 UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
756 boolean granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, true);
758 AltosDebug.debug("intent %s device %s granted %s", intent, device, granted);
763 if (device != null) {
764 AltosDebug.debug("intent has usb device " + device.toString());
768 /* 'granted' is only false if this intent came
769 * from the request_permission call and
770 * permission was denied. In which case, we
771 * don't want to loop forever...
774 AltosDebug.debug("check for a USB device at startup");
778 AltosDebug.debug("Starting by looking for bluetooth devices");
784 public void onStart() {
786 AltosDebug.debug("++ ON START ++");
790 noticeIntent(getIntent());
792 // Start Telemetry Service
793 String action = start_with_usb ? ACTION_USB : ACTION_BLUETOOTH;
795 startService(new Intent(action, null, AltosDroid.this, TelemetryService.class));
799 if (mAltosVoice == null)
800 mAltosVoice = new AltosVoice(this);
805 public void onNewIntent(Intent intent) {
806 super.onNewIntent(intent);
807 AltosDebug.debug("onNewIntent");
808 noticeIntent(intent);
811 private void enable_location_updates() {
812 // Listen for GPS and Network position updates
813 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
814 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
816 location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
818 if (location != null)
819 AltosDebug.debug("Resume, location is %f,%f\n",
820 location.getLatitude(),
821 location.getLongitude());
823 update_ui(telemetry_state, state, true);
826 static final int MY_PERMISSION_REQUEST = 1001;
828 public boolean have_location_permission = false;
829 public boolean have_storage_permission = false;
830 public boolean asked_permission = false;
832 AltosMapOnline map_online;
835 tell_map_permission(AltosMapOnline map_online) {
836 this.map_online = map_online;
840 public void onRequestPermissionsResult(int requestCode, String[] permissions,
841 int[] grantResults) {
842 if (requestCode == MY_PERMISSION_REQUEST) {
843 for (int i = 0; i < grantResults.length; i++) {
844 if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
845 if (permissions[i].equals(Manifest.permission.ACCESS_FINE_LOCATION)) {
846 have_location_permission = true;
847 enable_location_updates();
848 if (map_online != null)
849 map_online.position_permission();
851 if (permissions[i].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
852 have_storage_permission = true;
860 public void onResume() {
862 AltosDebug.debug("+ ON RESUME +");
864 if (!asked_permission) {
865 asked_permission = true;
866 if (ActivityCompat.checkSelfPermission(this,
867 Manifest.permission.ACCESS_FINE_LOCATION)
868 == PackageManager.PERMISSION_GRANTED)
870 have_location_permission = true;
872 if (ActivityCompat.checkSelfPermission(this,
873 Manifest.permission.WRITE_EXTERNAL_STORAGE)
874 == PackageManager.PERMISSION_GRANTED)
876 have_storage_permission = true;
878 int count = (have_location_permission ? 0 : 1) + (have_storage_permission ? 0 : 1);
881 String[] permissions = new String[count];
883 if (!have_location_permission)
884 permissions[i++] = Manifest.permission.ACCESS_FINE_LOCATION;
885 if (!have_location_permission)
886 permissions[i++] = Manifest.permission.WRITE_EXTERNAL_STORAGE;
887 ActivityCompat.requestPermissions(this, permissions, MY_PERMISSION_REQUEST);
890 if (have_location_permission)
891 enable_location_updates();
895 public void onPause() {
897 AltosDebug.debug("- ON PAUSE -");
898 // Stop listening for location updates
899 if (have_location_permission)
900 ((LocationManager) getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
904 public void onStop() {
906 AltosDebug.debug("-- ON STOP --");
910 public void onDestroy() {
912 AltosDebug.debug("--- ON DESTROY ---");
915 if (mAltosVoice != null) {
922 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
923 AltosDebug.debug("onActivityResult request %d result %d", requestCode, resultCode);
924 switch (requestCode) {
925 case REQUEST_CONNECT_DEVICE:
926 // When DeviceListActivity returns with a device to connect to
927 if (resultCode == Activity.RESULT_OK) {
931 case REQUEST_ENABLE_BT:
932 // When the request to enable Bluetooth returns
933 if (resultCode == Activity.RESULT_OK) {
934 // Bluetooth is now enabled, so set up a chat session
936 AltosDebug.debug("BT enabled");
937 bluetoothEnabled(data);
939 // User did not enable Bluetooth or an error occured
940 AltosDebug.debug("BT not enabled");
943 case REQUEST_IDLE_MODE:
944 if (resultCode == Activity.RESULT_OK)
947 case REQUEST_IGNITERS:
950 if (resultCode == Activity.RESULT_OK)
951 note_setup_changes(data);
956 private void note_setup_changes(Intent data) {
957 int changes = data.getIntExtra(SetupActivity.EXTRA_SETUP_CHANGES, 0);
959 AltosDebug.debug("note_setup_changes changes %d\n", changes);
961 if ((changes & SETUP_BAUD) != 0) {
963 mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD,
964 AltosPreferences.telemetry_rate(1)));
965 } catch (RemoteException re) {
968 if ((changes & SETUP_UNITS) != 0) {
969 /* nothing to do here */
971 if ((changes & SETUP_MAP_SOURCE) != 0) {
972 /* nothing to do here */
974 if ((changes & SETUP_MAP_TYPE) != 0) {
975 /* nothing to do here */
978 if ((changes & SETUP_FONT_SIZE) != 0) {
979 AltosDebug.debug(" ==== Recreate to switch font sizes ==== ");
981 startActivity(getIntent());
985 private void connectUsb(UsbDevice device) {
986 if (mService == null)
987 pending_usb_device = device;
989 // Attempt to connect to the device
991 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, device));
992 AltosDebug.debug("Sent OPEN_USB message");
993 } catch (RemoteException e) {
994 AltosDebug.debug("connect device message failed");
999 private void bluetoothEnabled(Intent data) {
1000 if (mService != null) {
1002 mService.send(Message.obtain(null, TelemetryService.MSG_BLUETOOTH_ENABLED, null));
1003 } catch (RemoteException e) {
1004 AltosDebug.debug("send BT enabled message failed");
1009 private void connectDevice(Intent data) {
1010 // Attempt to connect to the device
1012 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
1013 String name = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_NAME);
1015 AltosDebug.debug("Connecting to " + address + " " + name);
1016 DeviceAddress a = new DeviceAddress(address, name);
1017 mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, a));
1018 AltosDebug.debug("Sent connecting message");
1019 } catch (RemoteException e) {
1020 AltosDebug.debug("connect device message failed");
1024 private void disconnectDevice(boolean remember) {
1026 mService.send(Message.obtain(null, TelemetryService.MSG_DISCONNECT, (Boolean) remember));
1027 } catch (RemoteException e) {
1031 private void idle_mode(Intent data) {
1032 int type = data.getIntExtra(IdleModeActivity.EXTRA_IDLE_RESULT, -1);
1035 AltosDebug.debug("intent idle_mode %d", type);
1037 case IdleModeActivity.IDLE_MODE_CONNECT:
1038 msg = Message.obtain(null, TelemetryService.MSG_MONITOR_IDLE_START);
1041 } catch (RemoteException re) {
1044 case IdleModeActivity.IDLE_MODE_DISCONNECT:
1045 msg = Message.obtain(null, TelemetryService.MSG_MONITOR_IDLE_STOP);
1048 } catch (RemoteException re) {
1051 case IdleModeActivity.IDLE_MODE_REBOOT:
1052 msg = Message.obtain(null, TelemetryService.MSG_REBOOT);
1055 } catch (RemoteException re) {
1058 case IdleModeActivity.IDLE_MODE_IGNITERS:
1059 Intent serverIntent = new Intent(this, IgniterActivity.class);
1060 startActivityForResult(serverIntent, REQUEST_IGNITERS);
1066 public boolean onCreateOptionsMenu(Menu menu) {
1067 MenuInflater inflater = getMenuInflater();
1068 inflater.inflate(R.menu.option_menu, menu);
1072 void setFrequency(double freq) {
1074 mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
1076 } catch (RemoteException e) {
1080 void setFrequency(AltosFrequency frequency) {
1081 setFrequency (frequency.frequency);
1084 void setBaud(int baud) {
1086 mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD, baud));
1088 } catch (RemoteException e) {
1092 void setBaud(String baud) {
1094 int value = Integer.parseInt(baud);
1095 int rate = AltosLib.ao_telemetry_rate_38400;
1098 rate = AltosLib.ao_telemetry_rate_2400;
1101 rate = AltosLib.ao_telemetry_rate_9600;
1104 rate = AltosLib.ao_telemetry_rate_38400;
1108 } catch (NumberFormatException e) {
1112 void select_tracker(int serial) {
1115 AltosDebug.debug("select tracker %d\n", serial);
1117 if (serial == selected_serial) {
1118 AltosDebug.debug("%d already selected\n", serial);
1123 for (i = 0; i < trackers.length; i++)
1124 if (trackers[i].serial == serial)
1127 if (i == trackers.length) {
1128 AltosDebug.debug("attempt to select unknown tracker %d\n", serial);
1133 current_serial = selected_serial = serial;
1137 void touch_trackers(Integer[] serials) {
1138 AlertDialog.Builder builder_tracker = new AlertDialog.Builder(this);
1139 builder_tracker.setTitle("Select Tracker");
1141 final Tracker[] my_trackers = new Tracker[serials.length + 1];
1143 my_trackers[0] = new Tracker(null);
1145 for (int i = 0; i < serials.length; i++) {
1146 AltosState s = telemetry_state.states.get(serials[i]);
1147 my_trackers[i+1] = new Tracker(s);
1149 builder_tracker.setItems(my_trackers,
1150 new DialogInterface.OnClickListener() {
1151 public void onClick(DialogInterface dialog, int item) {
1155 select_tracker(my_trackers[item].serial);
1158 AlertDialog alert_tracker = builder_tracker.create();
1159 alert_tracker.show();
1162 void delete_track(int serial) {
1164 mService.send(Message.obtain(null, TelemetryService.MSG_DELETE_SERIAL, (Integer) serial));
1165 } catch (Exception ex) {
1170 public boolean onOptionsItemSelected(MenuItem item) {
1171 Intent serverIntent = null;
1172 switch (item.getItemId()) {
1173 case R.id.connect_scan:
1175 // Launch the DeviceListActivity to see devices and do scan
1176 serverIntent = new Intent(this, DeviceListActivity.class);
1177 startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
1179 case R.id.disconnect:
1180 /* Disconnect the device
1182 disconnectDevice(false);
1185 AltosDebug.debug("R.id.quit");
1186 disconnectDevice(true);
1190 serverIntent = new Intent(this, SetupActivity.class);
1191 startActivityForResult(serverIntent, REQUEST_SETUP);
1193 case R.id.select_freq:
1194 // Set the TBT radio frequency
1196 final AltosFrequency[] frequencies = AltosPreferences.common_frequencies();
1197 String[] frequency_strings = new String[frequencies.length];
1198 for (int i = 0; i < frequencies.length; i++)
1199 frequency_strings[i] = frequencies[i].toString();
1201 AlertDialog.Builder builder_freq = new AlertDialog.Builder(this);
1202 builder_freq.setTitle("Pick a frequency");
1203 builder_freq.setItems(frequency_strings,
1204 new DialogInterface.OnClickListener() {
1205 public void onClick(DialogInterface dialog, int item) {
1206 setFrequency(frequencies[item]);
1209 AlertDialog alert_freq = builder_freq.create();
1212 case R.id.select_tracker:
1213 if (trackers != null) {
1214 AlertDialog.Builder builder_serial = new AlertDialog.Builder(this);
1215 builder_serial.setTitle("Select a tracker");
1216 builder_serial.setItems(trackers,
1217 new DialogInterface.OnClickListener() {
1218 public void onClick(DialogInterface dialog, int item) {
1219 System.out.printf("select item %d %s\n", item, trackers[item].display);
1223 select_tracker(trackers[item].serial);
1226 AlertDialog alert_serial = builder_serial.create();
1227 alert_serial.show();
1231 case R.id.delete_track:
1232 if (trackers != null) {
1233 AlertDialog.Builder builder_serial = new AlertDialog.Builder(this);
1234 builder_serial.setTitle("Delete a track");
1235 final Tracker[] my_trackers = new Tracker[trackers.length - 1];
1236 for (int i = 0; i < trackers.length - 1; i++)
1237 my_trackers[i] = trackers[i+1];
1238 builder_serial.setItems(my_trackers,
1239 new DialogInterface.OnClickListener() {
1240 public void onClick(DialogInterface dialog, int item) {
1241 delete_track(my_trackers[item].serial);
1244 AlertDialog alert_serial = builder_serial.create();
1245 alert_serial.show();
1249 case R.id.idle_mode:
1250 serverIntent = new Intent(this, IdleModeActivity.class);
1251 serverIntent.putExtra(EXTRA_IDLE_MODE, idle_mode);
1252 startActivityForResult(serverIntent, REQUEST_IDLE_MODE);
1258 static String direction(AltosGreatCircle from_receiver,
1259 Location receiver) {
1260 if (from_receiver == null)
1263 if (receiver == null)
1266 if (!receiver.hasBearing())
1269 float bearing = receiver.getBearing();
1270 float heading = (float) from_receiver.bearing - bearing;
1272 while (heading <= -180.0f)
1274 while (heading > 180.0f)
1277 int iheading = (int) (heading + 0.5f);
1279 if (-1 < iheading && iheading < 1)
1281 else if (iheading < -179 || 179 < iheading)
1283 else if (iheading < 0)
1284 return String.format("left %d°", -iheading);
1286 return String.format("right %d°", iheading);
1289 public void onLocationChanged(Location location) {
1290 this.location = location;
1291 AltosDebug.debug("Location changed to %f,%f",
1292 location.getLatitude(),
1293 location.getLongitude());
1294 update_ui(telemetry_state, state, false);
1297 public void onStatusChanged(String provider, int status, Bundle extras) {
1298 AltosDebug.debug("Location status now %d\n", status);
1301 public void onProviderEnabled(String provider) {
1302 AltosDebug.debug("Location provider enabled %s\n", provider);
1305 public void onProviderDisabled(String provider) {
1306 AltosDebug.debug("Location provider disabled %s\n", provider);