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 = {
653 public void onCreate(Bundle savedInstanceState) {
654 // Initialise preferences
655 AltosDroidPreferences.init(this);
656 setTheme(themes[AltosDroidPreferences.font_size()]);
657 super.onCreate(savedInstanceState);
658 AltosDebug.init(this);
659 AltosDebug.debug("+++ ON CREATE +++");
662 fm = getSupportFragmentManager();
664 // Set up the window layout
665 setContentView(R.layout.altosdroid);
667 // Create the Tabs and ViewPager
668 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
671 mViewPager = (AltosViewPager)findViewById(R.id.pager);
672 mViewPager.setOffscreenPageLimit(4);
674 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
676 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_pad_name).setIndicator(create_tab_view("Pad")), TabPad.class, null);
677 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_flight_name).setIndicator(create_tab_view("Flight")), TabFlight.class, null);
678 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_recover_name).setIndicator(create_tab_view("Recover")), TabRecover.class, null);
679 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_map_name).setIndicator(create_tab_view("Map")), TabMap.class, null);
681 // Display the Version
682 mVersion = (TextView) findViewById(R.id.version);
683 mVersion.setText("Version: " + BuildInfo.version +
684 " Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
685 " (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
687 mCallsignView = (TextView) findViewById(R.id.callsign_value);
688 mRSSIView = (TextView) findViewById(R.id.rssi_value);
689 mSerialView = (TextView) findViewById(R.id.serial_value);
690 mFlightView = (TextView) findViewById(R.id.flight_value);
691 mStateLayout = (RelativeLayout) findViewById(R.id.state_container);
692 mStateView = (TextView) findViewById(R.id.state_value);
693 mAgeView = (TextView) findViewById(R.id.age_value);
694 mAgeNewColor = mAgeView.getTextColors().getDefaultColor();
695 mAgeOldColor = getResources().getColor(R.color.old_color);
698 private void ensureBluetooth() {
699 // Get local Bluetooth adapter
700 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
702 /* if there is a BT adapter and it isn't turned on, then turn it on */
703 if (mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) {
704 Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
705 startActivityForResult(enableIntent, AltosDroid.REQUEST_ENABLE_BT);
709 private boolean check_usb() {
710 UsbDevice device = AltosUsb.find_device(this, AltosLib.product_basestation);
712 if (device != null) {
713 Intent i = new Intent(this, AltosDroid.class);
714 PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent("hello world", null, this, AltosDroid.class), 0);
716 if (AltosUsb.request_permission(this, device, pi)) {
719 start_with_usb = true;
723 start_with_usb = false;
728 private void noticeIntent(Intent intent) {
730 /* Ok, this is pretty convenient.
732 * When a USB device is plugged in, and our 'hotplug'
733 * intent registration fires, we get an Intent with
736 * When we start up and see a usb device and request
737 * permission to access it, that queues a
738 * PendingIntent, which has the EXTRA_DEVICE added in,
739 * along with the EXTRA_PERMISSION_GRANTED field as
742 * So, in both cases, we get the device name using the
743 * same call. We check to see if access was granted,
744 * in which case we ignore the device field and do our
745 * usual startup thing.
748 UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
749 boolean granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, true);
751 AltosDebug.debug("intent %s device %s granted %s", intent, device, granted);
756 if (device != null) {
757 AltosDebug.debug("intent has usb device " + device.toString());
761 /* 'granted' is only false if this intent came
762 * from the request_permission call and
763 * permission was denied. In which case, we
764 * don't want to loop forever...
767 AltosDebug.debug("check for a USB device at startup");
771 AltosDebug.debug("Starting by looking for bluetooth devices");
777 public void onStart() {
779 AltosDebug.debug("++ ON START ++");
783 noticeIntent(getIntent());
785 // Start Telemetry Service
786 String action = start_with_usb ? ACTION_USB : ACTION_BLUETOOTH;
788 startService(new Intent(action, null, AltosDroid.this, TelemetryService.class));
792 if (mAltosVoice == null)
793 mAltosVoice = new AltosVoice(this);
798 public void onNewIntent(Intent intent) {
799 super.onNewIntent(intent);
800 AltosDebug.debug("onNewIntent");
801 noticeIntent(intent);
804 private void enable_location_updates() {
805 // Listen for GPS and Network position updates
806 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
807 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
809 location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
811 if (location != null)
812 AltosDebug.debug("Resume, location is %f,%f\n",
813 location.getLatitude(),
814 location.getLongitude());
816 update_ui(telemetry_state, state, true);
819 static final int MY_PERMISSION_REQUEST = 1001;
821 public boolean have_location_permission = false;
822 public boolean have_storage_permission = false;
823 public boolean asked_permission = false;
825 AltosMapOnline map_online;
828 tell_map_permission(AltosMapOnline map_online) {
829 this.map_online = map_online;
833 public void onRequestPermissionsResult(int requestCode, String[] permissions,
834 int[] grantResults) {
835 if (requestCode == MY_PERMISSION_REQUEST) {
836 for (int i = 0; i < grantResults.length; i++) {
837 if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
838 if (permissions[i].equals(Manifest.permission.ACCESS_FINE_LOCATION)) {
839 have_location_permission = true;
840 enable_location_updates();
841 if (map_online != null)
842 map_online.position_permission();
844 if (permissions[i].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
845 have_storage_permission = true;
853 public void onResume() {
855 AltosDebug.debug("+ ON RESUME +");
857 if (!asked_permission) {
858 asked_permission = true;
859 if (ActivityCompat.checkSelfPermission(this,
860 Manifest.permission.ACCESS_FINE_LOCATION)
861 == PackageManager.PERMISSION_GRANTED)
863 have_location_permission = true;
865 if (ActivityCompat.checkSelfPermission(this,
866 Manifest.permission.WRITE_EXTERNAL_STORAGE)
867 == PackageManager.PERMISSION_GRANTED)
869 have_storage_permission = true;
871 int count = (have_location_permission ? 0 : 1) + (have_storage_permission ? 0 : 1);
874 String[] permissions = new String[count];
876 if (!have_location_permission)
877 permissions[i++] = Manifest.permission.ACCESS_FINE_LOCATION;
878 if (!have_location_permission)
879 permissions[i++] = Manifest.permission.WRITE_EXTERNAL_STORAGE;
880 ActivityCompat.requestPermissions(this, permissions, MY_PERMISSION_REQUEST);
883 if (have_location_permission)
884 enable_location_updates();
888 public void onPause() {
890 AltosDebug.debug("- ON PAUSE -");
891 // Stop listening for location updates
892 if (have_location_permission)
893 ((LocationManager) getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
897 public void onStop() {
899 AltosDebug.debug("-- ON STOP --");
903 public void onDestroy() {
905 AltosDebug.debug("--- ON DESTROY ---");
908 if (mAltosVoice != null) {
915 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
916 AltosDebug.debug("onActivityResult request %d result %d", requestCode, resultCode);
917 switch (requestCode) {
918 case REQUEST_CONNECT_DEVICE:
919 // When DeviceListActivity returns with a device to connect to
920 if (resultCode == Activity.RESULT_OK) {
924 case REQUEST_ENABLE_BT:
925 // When the request to enable Bluetooth returns
926 if (resultCode == Activity.RESULT_OK) {
927 // Bluetooth is now enabled, so set up a chat session
929 AltosDebug.debug("BT enabled");
930 bluetoothEnabled(data);
932 // User did not enable Bluetooth or an error occured
933 AltosDebug.debug("BT not enabled");
936 case REQUEST_IDLE_MODE:
937 if (resultCode == Activity.RESULT_OK)
940 case REQUEST_IGNITERS:
943 if (resultCode == Activity.RESULT_OK)
944 note_setup_changes(data);
949 private void note_setup_changes(Intent data) {
950 int changes = data.getIntExtra(SetupActivity.EXTRA_SETUP_CHANGES, 0);
952 AltosDebug.debug("note_setup_changes changes %d\n", changes);
954 if ((changes & SETUP_BAUD) != 0) {
956 mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD,
957 AltosPreferences.telemetry_rate(1)));
958 } catch (RemoteException re) {
961 if ((changes & SETUP_UNITS) != 0) {
962 /* nothing to do here */
964 if ((changes & SETUP_MAP_SOURCE) != 0) {
965 /* nothing to do here */
967 if ((changes & SETUP_MAP_TYPE) != 0) {
968 /* nothing to do here */
971 if ((changes & SETUP_FONT_SIZE) != 0) {
972 AltosDebug.debug(" ==== Recreate to switch font sizes ==== ");
974 startActivity(getIntent());
978 private void connectUsb(UsbDevice device) {
979 if (mService == null)
980 pending_usb_device = device;
982 // Attempt to connect to the device
984 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, device));
985 AltosDebug.debug("Sent OPEN_USB message");
986 } catch (RemoteException e) {
987 AltosDebug.debug("connect device message failed");
992 private void bluetoothEnabled(Intent data) {
993 if (mService != null) {
995 mService.send(Message.obtain(null, TelemetryService.MSG_BLUETOOTH_ENABLED, null));
996 } catch (RemoteException e) {
997 AltosDebug.debug("send BT enabled message failed");
1002 private void connectDevice(Intent data) {
1003 // Attempt to connect to the device
1005 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
1006 String name = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_NAME);
1008 AltosDebug.debug("Connecting to " + address + " " + name);
1009 DeviceAddress a = new DeviceAddress(address, name);
1010 mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, a));
1011 AltosDebug.debug("Sent connecting message");
1012 } catch (RemoteException e) {
1013 AltosDebug.debug("connect device message failed");
1017 private void disconnectDevice(boolean remember) {
1019 mService.send(Message.obtain(null, TelemetryService.MSG_DISCONNECT, (Boolean) remember));
1020 } catch (RemoteException e) {
1024 private void idle_mode(Intent data) {
1025 int type = data.getIntExtra(IdleModeActivity.EXTRA_IDLE_RESULT, -1);
1028 AltosDebug.debug("intent idle_mode %d", type);
1030 case IdleModeActivity.IDLE_MODE_CONNECT:
1031 msg = Message.obtain(null, TelemetryService.MSG_MONITOR_IDLE_START);
1034 } catch (RemoteException re) {
1037 case IdleModeActivity.IDLE_MODE_DISCONNECT:
1038 msg = Message.obtain(null, TelemetryService.MSG_MONITOR_IDLE_STOP);
1041 } catch (RemoteException re) {
1044 case IdleModeActivity.IDLE_MODE_REBOOT:
1045 msg = Message.obtain(null, TelemetryService.MSG_REBOOT);
1048 } catch (RemoteException re) {
1051 case IdleModeActivity.IDLE_MODE_IGNITERS:
1052 Intent serverIntent = new Intent(this, IgniterActivity.class);
1053 startActivityForResult(serverIntent, REQUEST_IGNITERS);
1059 public boolean onCreateOptionsMenu(Menu menu) {
1060 MenuInflater inflater = getMenuInflater();
1061 inflater.inflate(R.menu.option_menu, menu);
1065 void setFrequency(double freq) {
1067 mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
1069 } catch (RemoteException e) {
1073 void setFrequency(AltosFrequency frequency) {
1074 setFrequency (frequency.frequency);
1077 void setBaud(int baud) {
1079 mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD, baud));
1081 } catch (RemoteException e) {
1085 void setBaud(String baud) {
1087 int value = Integer.parseInt(baud);
1088 int rate = AltosLib.ao_telemetry_rate_38400;
1091 rate = AltosLib.ao_telemetry_rate_2400;
1094 rate = AltosLib.ao_telemetry_rate_9600;
1097 rate = AltosLib.ao_telemetry_rate_38400;
1101 } catch (NumberFormatException e) {
1105 void select_tracker(int serial) {
1108 AltosDebug.debug("select tracker %d\n", serial);
1110 if (serial == selected_serial) {
1111 AltosDebug.debug("%d already selected\n", serial);
1116 for (i = 0; i < trackers.length; i++)
1117 if (trackers[i].serial == serial)
1120 if (i == trackers.length) {
1121 AltosDebug.debug("attempt to select unknown tracker %d\n", serial);
1126 current_serial = selected_serial = serial;
1130 void touch_trackers(Integer[] serials) {
1131 AlertDialog.Builder builder_tracker = new AlertDialog.Builder(this);
1132 builder_tracker.setTitle("Select Tracker");
1134 final Tracker[] my_trackers = new Tracker[serials.length + 1];
1136 my_trackers[0] = new Tracker(null);
1138 for (int i = 0; i < serials.length; i++) {
1139 AltosState s = telemetry_state.states.get(serials[i]);
1140 my_trackers[i+1] = new Tracker(s);
1142 builder_tracker.setItems(my_trackers,
1143 new DialogInterface.OnClickListener() {
1144 public void onClick(DialogInterface dialog, int item) {
1148 select_tracker(my_trackers[item].serial);
1151 AlertDialog alert_tracker = builder_tracker.create();
1152 alert_tracker.show();
1155 void delete_track(int serial) {
1157 mService.send(Message.obtain(null, TelemetryService.MSG_DELETE_SERIAL, (Integer) serial));
1158 } catch (Exception ex) {
1163 public boolean onOptionsItemSelected(MenuItem item) {
1164 Intent serverIntent = null;
1165 switch (item.getItemId()) {
1166 case R.id.connect_scan:
1168 // Launch the DeviceListActivity to see devices and do scan
1169 serverIntent = new Intent(this, DeviceListActivity.class);
1170 startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
1172 case R.id.disconnect:
1173 /* Disconnect the device
1175 disconnectDevice(false);
1178 AltosDebug.debug("R.id.quit");
1179 disconnectDevice(true);
1183 serverIntent = new Intent(this, SetupActivity.class);
1184 startActivityForResult(serverIntent, REQUEST_SETUP);
1186 case R.id.select_freq:
1187 // Set the TBT radio frequency
1189 final AltosFrequency[] frequencies = AltosPreferences.common_frequencies();
1190 String[] frequency_strings = new String[frequencies.length];
1191 for (int i = 0; i < frequencies.length; i++)
1192 frequency_strings[i] = frequencies[i].toString();
1194 AlertDialog.Builder builder_freq = new AlertDialog.Builder(this);
1195 builder_freq.setTitle("Pick a frequency");
1196 builder_freq.setItems(frequency_strings,
1197 new DialogInterface.OnClickListener() {
1198 public void onClick(DialogInterface dialog, int item) {
1199 setFrequency(frequencies[item]);
1202 AlertDialog alert_freq = builder_freq.create();
1205 case R.id.select_tracker:
1206 if (trackers != null) {
1207 AlertDialog.Builder builder_serial = new AlertDialog.Builder(this);
1208 builder_serial.setTitle("Select a tracker");
1209 builder_serial.setItems(trackers,
1210 new DialogInterface.OnClickListener() {
1211 public void onClick(DialogInterface dialog, int item) {
1212 System.out.printf("select item %d %s\n", item, trackers[item].display);
1216 select_tracker(trackers[item].serial);
1219 AlertDialog alert_serial = builder_serial.create();
1220 alert_serial.show();
1224 case R.id.delete_track:
1225 if (trackers != null) {
1226 AlertDialog.Builder builder_serial = new AlertDialog.Builder(this);
1227 builder_serial.setTitle("Delete a track");
1228 final Tracker[] my_trackers = new Tracker[trackers.length - 1];
1229 for (int i = 0; i < trackers.length - 1; i++)
1230 my_trackers[i] = trackers[i+1];
1231 builder_serial.setItems(my_trackers,
1232 new DialogInterface.OnClickListener() {
1233 public void onClick(DialogInterface dialog, int item) {
1234 delete_track(my_trackers[item].serial);
1237 AlertDialog alert_serial = builder_serial.create();
1238 alert_serial.show();
1242 case R.id.idle_mode:
1243 serverIntent = new Intent(this, IdleModeActivity.class);
1244 serverIntent.putExtra(EXTRA_IDLE_MODE, idle_mode);
1245 startActivityForResult(serverIntent, REQUEST_IDLE_MODE);
1251 static String direction(AltosGreatCircle from_receiver,
1252 Location receiver) {
1253 if (from_receiver == null)
1256 if (receiver == null)
1259 if (!receiver.hasBearing())
1262 float bearing = receiver.getBearing();
1263 float heading = (float) from_receiver.bearing - bearing;
1265 while (heading <= -180.0f)
1267 while (heading > 180.0f)
1270 int iheading = (int) (heading + 0.5f);
1272 if (-1 < iheading && iheading < 1)
1274 else if (iheading < -179 || 179 < iheading)
1276 else if (iheading < 0)
1277 return String.format("left %d°", -iheading);
1279 return String.format("right %d°", iheading);
1282 public void onLocationChanged(Location location) {
1283 this.location = location;
1284 AltosDebug.debug("Location changed to %f,%f",
1285 location.getLatitude(),
1286 location.getLongitude());
1287 update_ui(telemetry_state, state, false);
1290 public void onStatusChanged(String provider, int status, Bundle extras) {
1291 AltosDebug.debug("Location status now %d\n", status);
1294 public void onProviderEnabled(String provider) {
1295 AltosDebug.debug("Location provider enabled %s\n", provider);
1298 public void onProviderDisabled(String provider) {
1299 AltosDebug.debug("Location provider disabled %s\n", provider);