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;
176 public static FragmentManager fm;
178 private BluetoothAdapter mBluetoothAdapter = null;
180 // Flight state values
181 private TextView mCallsignView;
182 private TextView mRSSIView;
183 private TextView mSerialView;
184 private TextView mFlightView;
185 private RelativeLayout mStateLayout;
186 private TextView mStateView;
187 private TextView mAgeView;
188 private boolean mAgeViewOld;
189 private int mAgeNewColor;
190 private int mAgeOldColor;
192 public static final String tab_pad_name = "pad";
193 public static final String tab_flight_name = "flight";
194 public static final String tab_recover_name = "recover";
195 public static final String tab_map_name = "map";
197 // field to display the version at the bottom of the screen
198 private TextView mVersion;
200 private boolean idle_mode = false;
202 public Location location = null;
204 private AltosState state;
205 private SavedState saved_state;
209 AltosViewPager mViewPager;
210 TabsAdapter mTabsAdapter;
211 ArrayList<AltosDroidTab> mTabs = new ArrayList<AltosDroidTab>();
214 // Timer and Saved flight state for Age calculation
217 TelemetryState telemetry_state;
221 UsbDevice pending_usb_device;
222 boolean start_with_usb;
225 private boolean mIsBound = false;
226 private Messenger mService = null;
227 final Messenger mMessenger = new Messenger(new IncomingHandler(this));
230 private AltosVoice mAltosVoice = null;
232 // The Handler that gets information back from the Telemetry Service
233 static class IncomingHandler extends Handler {
234 private final WeakReference<AltosDroid> mAltosDroid;
235 IncomingHandler(AltosDroid ad) { mAltosDroid = new WeakReference<AltosDroid>(ad); }
238 public void handleMessage(Message msg) {
239 AltosDroid ad = mAltosDroid.get();
243 if (msg.obj == null) {
244 AltosDebug.debug("telemetry_state null!");
247 ad.update_state((TelemetryState) msg.obj);
253 ad.idle_mode = (Boolean) msg.obj;
254 ad.update_state(null);
261 private ServiceConnection mConnection = new ServiceConnection() {
262 public void onServiceConnected(ComponentName className, IBinder service) {
263 mService = new Messenger(service);
265 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
266 msg.replyTo = mMessenger;
268 } catch (RemoteException e) {
269 // In this case the service has crashed before we could even do anything with it
271 if (pending_usb_device != null) {
273 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, pending_usb_device));
274 pending_usb_device = null;
275 } catch (RemoteException e) {
280 public void onServiceDisconnected(ComponentName className) {
281 // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
286 void doBindService() {
287 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
291 void doUnbindService() {
293 // If we have received the service, and hence registered with it, then now is the time to unregister.
294 if (mService != null) {
296 Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
297 msg.replyTo = mMessenger;
299 } catch (RemoteException e) {
300 // There is nothing special we need to do if the service has crashed.
303 // Detach our existing connection.
304 unbindService(mConnection);
309 public void registerTab(AltosDroidTab mTab) {
313 public void unregisterTab(AltosDroidTab mTab) {
317 public void units_changed(boolean imperial_units) {
318 for (AltosDroidTab mTab : mTabs)
319 mTab.units_changed(imperial_units);
322 void update_title(TelemetryState telemetry_state) {
323 switch (telemetry_state.connect) {
324 case TelemetryState.CONNECT_CONNECTED:
325 if (telemetry_state.config != null) {
326 String str = String.format("S/N %d %6.3f MHz%s", telemetry_state.config.serial,
327 telemetry_state.frequency, idle_mode ? " (idle)" : "");
328 if (telemetry_state.telemetry_rate != AltosLib.ao_telemetry_rate_38400)
329 str = str.concat(String.format(" %d bps",
330 AltosLib.ao_telemetry_rate_values[telemetry_state.telemetry_rate]));
333 setTitle(R.string.title_connected_to);
336 case TelemetryState.CONNECT_CONNECTING:
337 if (telemetry_state.address != null)
338 setTitle(String.format("Connecting to %s...", telemetry_state.address.name));
340 setTitle("Connecting to something...");
342 case TelemetryState.CONNECT_DISCONNECTED:
343 case TelemetryState.CONNECT_NONE:
344 setTitle(R.string.title_not_connected);
352 timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 1000L, 1000L);
364 int selected_serial = 0;
368 void set_switch_time() {
369 switch_time = System.currentTimeMillis();
373 boolean registered_units_listener;
375 void update_state(TelemetryState new_telemetry_state) {
377 if (new_telemetry_state != null)
378 telemetry_state = new_telemetry_state;
380 if (selected_serial != 0)
381 current_serial = selected_serial;
383 if (current_serial == 0)
384 current_serial = telemetry_state.latest_serial;
386 if (!registered_units_listener) {
387 registered_units_listener = true;
388 AltosPreferences.register_units_listener(this);
391 int num_trackers = 0;
392 for (AltosState s : telemetry_state.states.values()) {
396 trackers = new Tracker[num_trackers + 1];
399 trackers[n++] = new Tracker(0, "auto", 0.0);
401 for (AltosState s : telemetry_state.states.values())
402 trackers[n++] = new Tracker(s);
404 Arrays.sort(trackers);
406 update_title(telemetry_state);
408 AltosState state = null;
411 if (telemetry_state.states.containsKey(current_serial)) {
412 state = telemetry_state.states.get(current_serial);
413 int age = state_age(state.received_time);
416 if (current_serial == selected_serial)
418 else if (switch_time != 0 && (switch_time - state.received_time) > 0)
423 AltosState newest_state = null;
426 for (int serial : telemetry_state.states.keySet()) {
427 AltosState existing = telemetry_state.states.get(serial);
428 int existing_age = state_age(existing.received_time);
430 if (newest_state == null || existing_age < newest_age) {
431 newest_state = existing;
432 newest_age = existing_age;
436 if (newest_state != null)
437 state = newest_state;
440 update_ui(telemetry_state, state, telemetry_state.quiet);
445 boolean same_string(String a, String b) {
458 private int blend_component(int a, int b, double r, int shift, int mask) {
459 return ((int) (((a >> shift) & mask) * r + ((b >> shift) & mask) * (1 - r)) & mask) << shift;
461 private int blend_color(int a, int b, double r) {
462 return (blend_component(a, b, r, 0, 0xff) |
463 blend_component(a, b, r, 8, 0xff) |
464 blend_component(a, b, r, 16, 0xff) |
465 blend_component(a, b, r, 24, 0xff));
468 int state_age(long received_time) {
469 return (int) ((System.currentTimeMillis() - received_time + 500) / 1000);
472 void set_screen_on(int age) {
474 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
476 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
480 if (saved_state != null) {
481 int age = state_age(saved_state.received_time);
483 double age_scale = age / 100.0;
488 mAgeView.setTextColor(blend_color(mAgeOldColor, mAgeNewColor, age_scale));
494 text = String.format("%ds", age);
495 else if (age < 60 * 60)
496 text = String.format("%dm", age / 60);
497 else if (age < 60 * 60 * 24)
498 text = String.format("%dh", age / (60 * 60));
500 text = String.format("%dd", age / (24 * 60 * 60));
501 mAgeView.setText(text);
505 void update_ui(TelemetryState telem_state, AltosState state, boolean quiet) {
509 int prev_state = AltosLib.ao_flight_invalid;
511 AltosGreatCircle from_receiver = null;
513 if (saved_state != null)
514 prev_state = saved_state.state;
517 set_screen_on(state_age(state.received_time));
519 if (state.state() == AltosLib.ao_flight_stateless) {
520 boolean prev_locked = false;
521 boolean locked = false;
523 if(state.gps != null)
524 locked = state.gps.locked;
525 if (saved_state != null)
526 prev_locked = saved_state.locked;
527 if (prev_locked != locked) {
528 String currentTab = mTabHost.getCurrentTabTag();
530 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
532 if (currentTab.equals(tab_flight_name)) mTabHost.setCurrentTabByTag(tab_pad_name);
536 if (prev_state != state.state()) {
537 String currentTab = mTabHost.getCurrentTabTag();
538 switch (state.state()) {
539 case AltosLib.ao_flight_boost:
540 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
542 case AltosLib.ao_flight_landed:
543 if (currentTab.equals(tab_flight_name)) mTabHost.setCurrentTabByTag(tab_recover_name);
545 case AltosLib.ao_flight_stateless:
546 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
552 if (location != null && state.gps != null && state.gps.locked) {
554 if (location.hasAltitude())
555 altitude = location.getAltitude();
556 from_receiver = new AltosGreatCircle(location.getLatitude(),
557 location.getLongitude(),
564 if (saved_state == null || !same_string(saved_state.callsign, state.cal_data().callsign)) {
565 mCallsignView.setText(state.cal_data().callsign);
567 if (saved_state == null || state.cal_data().serial != saved_state.serial) {
568 if (state.cal_data().serial == AltosLib.MISSING)
569 mSerialView.setText("");
571 mSerialView.setText(String.format("%d", state.cal_data().serial));
573 if (saved_state == null || state.cal_data().flight != saved_state.flight) {
574 if (state.cal_data().flight == AltosLib.MISSING)
575 mFlightView.setText("");
577 mFlightView.setText(String.format("%d", state.cal_data().flight));
579 if (saved_state == null || state.state() != saved_state.state) {
580 if (state.state() == AltosLib.ao_flight_stateless) {
581 mStateLayout.setVisibility(View.GONE);
583 mStateView.setText(state.state_name());
584 mStateLayout.setVisibility(View.VISIBLE);
587 if (saved_state == null || state.rssi != saved_state.rssi) {
588 if (state.rssi == AltosLib.MISSING)
589 mRSSIView.setText("");
591 mRSSIView.setText(String.format("%d", state.rssi));
593 saved_state = new SavedState(state);
596 for (AltosDroidTab mTab : mTabs)
597 mTab.update_ui(telem_state, state, from_receiver, location, mTab == mTabsAdapter.currentItem());
599 AltosDebug.debug("quiet %b\n", quiet);
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°%9.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);
646 public void onCreate(Bundle savedInstanceState) {
647 super.onCreate(savedInstanceState);
648 AltosDebug.init(this);
649 AltosDebug.debug("+++ ON CREATE +++");
651 // Initialise preferences
652 AltosDroidPreferences.init(this);
654 fm = getSupportFragmentManager();
656 // Set up the window layout
657 setContentView(R.layout.altosdroid);
659 // Create the Tabs and ViewPager
660 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
663 mViewPager = (AltosViewPager)findViewById(R.id.pager);
664 mViewPager.setOffscreenPageLimit(4);
666 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
668 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_pad_name).setIndicator(create_tab_view("Pad")), TabPad.class, null);
669 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_flight_name).setIndicator(create_tab_view("Flight")), TabFlight.class, null);
670 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_recover_name).setIndicator(create_tab_view("Recover")), TabRecover.class, null);
671 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_map_name).setIndicator(create_tab_view("Map")), TabMap.class, null);
673 // Display the Version
674 mVersion = (TextView) findViewById(R.id.version);
675 mVersion.setText("Version: " + BuildInfo.version +
676 " Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
677 " (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
679 mCallsignView = (TextView) findViewById(R.id.callsign_value);
680 mRSSIView = (TextView) findViewById(R.id.rssi_value);
681 mSerialView = (TextView) findViewById(R.id.serial_value);
682 mFlightView = (TextView) findViewById(R.id.flight_value);
683 mStateLayout = (RelativeLayout) findViewById(R.id.state_container);
684 mStateView = (TextView) findViewById(R.id.state_value);
685 mAgeView = (TextView) findViewById(R.id.age_value);
686 mAgeNewColor = mAgeView.getTextColors().getDefaultColor();
687 mAgeOldColor = getResources().getColor(R.color.old_color);
690 private void ensureBluetooth() {
691 // Get local Bluetooth adapter
692 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
694 /* if there is a BT adapter and it isn't turned on, then turn it on */
695 if (mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) {
696 Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
697 startActivityForResult(enableIntent, AltosDroid.REQUEST_ENABLE_BT);
701 private boolean check_usb() {
702 UsbDevice device = AltosUsb.find_device(this, AltosLib.product_basestation);
704 if (device != null) {
705 Intent i = new Intent(this, AltosDroid.class);
706 PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent("hello world", null, this, AltosDroid.class), 0);
708 if (AltosUsb.request_permission(this, device, pi)) {
711 start_with_usb = true;
715 start_with_usb = false;
720 private void noticeIntent(Intent intent) {
722 /* Ok, this is pretty convenient.
724 * When a USB device is plugged in, and our 'hotplug'
725 * intent registration fires, we get an Intent with
728 * When we start up and see a usb device and request
729 * permission to access it, that queues a
730 * PendingIntent, which has the EXTRA_DEVICE added in,
731 * along with the EXTRA_PERMISSION_GRANTED field as
734 * So, in both cases, we get the device name using the
735 * same call. We check to see if access was granted,
736 * in which case we ignore the device field and do our
737 * usual startup thing.
740 UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
741 boolean granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, true);
743 AltosDebug.debug("intent %s device %s granted %s", intent, device, granted);
748 if (device != null) {
749 AltosDebug.debug("intent has usb device " + device.toString());
753 /* 'granted' is only false if this intent came
754 * from the request_permission call and
755 * permission was denied. In which case, we
756 * don't want to loop forever...
759 AltosDebug.debug("check for a USB device at startup");
763 AltosDebug.debug("Starting by looking for bluetooth devices");
769 public void onStart() {
771 AltosDebug.debug("++ ON START ++");
775 noticeIntent(getIntent());
777 // Start Telemetry Service
778 String action = start_with_usb ? ACTION_USB : ACTION_BLUETOOTH;
780 startService(new Intent(action, null, AltosDroid.this, TelemetryService.class));
784 if (mAltosVoice == null)
785 mAltosVoice = new AltosVoice(this);
790 public void onNewIntent(Intent intent) {
791 super.onNewIntent(intent);
792 AltosDebug.debug("onNewIntent");
793 noticeIntent(intent);
796 private void enable_location_updates() {
797 // Listen for GPS and Network position updates
798 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
799 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
801 location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
803 if (location != null)
804 AltosDebug.debug("Resume, location is %f,%f\n",
805 location.getLatitude(),
806 location.getLongitude());
808 update_ui(telemetry_state, state, true);
811 static final int MY_PERMISSION_REQUEST_FINE_POSITION = 1001;
813 public boolean have_location_permission = false;
814 public boolean asked_location_permission = false;
816 AltosMapOnline map_online;
819 tell_map_permission(AltosMapOnline map_online) {
820 this.map_online = map_online;
824 public void onRequestPermissionsResult(int requestCode, String[] permissions,
825 int[] grantResults) {
826 switch (requestCode) {
827 case MY_PERMISSION_REQUEST_FINE_POSITION:
828 if (grantResults.length > 0 &&
829 grantResults[0] == PackageManager.PERMISSION_GRANTED) {
830 have_location_permission = true;
831 enable_location_updates();
832 if (map_online != null)
833 map_online.position_permission();
840 public void onResume() {
842 AltosDebug.debug("+ ON RESUME +");
844 if (!asked_location_permission) {
845 asked_location_permission = true;
846 if (ActivityCompat.checkSelfPermission(this,
847 Manifest.permission.ACCESS_FINE_LOCATION)
848 == PackageManager.PERMISSION_GRANTED)
850 have_location_permission = true;
854 ActivityCompat.requestPermissions(this,
855 new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
856 MY_PERMISSION_REQUEST_FINE_POSITION);
859 if (have_location_permission)
860 enable_location_updates();
864 public void onPause() {
866 AltosDebug.debug("- ON PAUSE -");
867 // Stop listening for location updates
868 if (have_location_permission)
869 ((LocationManager) getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
873 public void onStop() {
875 AltosDebug.debug("-- ON STOP --");
879 public void onDestroy() {
881 AltosDebug.debug("--- ON DESTROY ---");
884 if (mAltosVoice != null) {
891 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
892 AltosDebug.debug("onActivityResult " + resultCode);
893 switch (requestCode) {
894 case REQUEST_CONNECT_DEVICE:
895 // When DeviceListActivity returns with a device to connect to
896 if (resultCode == Activity.RESULT_OK) {
900 case REQUEST_ENABLE_BT:
901 // When the request to enable Bluetooth returns
902 if (resultCode == Activity.RESULT_OK) {
903 // Bluetooth is now enabled, so set up a chat session
905 AltosDebug.debug("BT enabled");
906 bluetoothEnabled(data);
908 // User did not enable Bluetooth or an error occured
909 AltosDebug.debug("BT not enabled");
912 case REQUEST_IDLE_MODE:
913 if (resultCode == Activity.RESULT_OK)
916 case REQUEST_IGNITERS:
919 if (resultCode == Activity.RESULT_OK)
920 note_setup_changes(data);
925 private void note_setup_changes(Intent data) {
926 int changes = data.getIntExtra(SetupActivity.EXTRA_SETUP_CHANGES, 0);
928 if ((changes & SETUP_BAUD) != 0) {
930 mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD,
931 AltosPreferences.telemetry_rate(1)));
932 } catch (RemoteException re) {
935 if ((changes & SETUP_UNITS) != 0) {
936 /* nothing to do here */
938 if ((changes & SETUP_MAP_SOURCE) != 0) {
939 /* nothing to do here */
941 if ((changes & SETUP_MAP_TYPE) != 0) {
942 /* nothing to do here */
947 private void connectUsb(UsbDevice device) {
948 if (mService == null)
949 pending_usb_device = device;
951 // Attempt to connect to the device
953 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, device));
954 AltosDebug.debug("Sent OPEN_USB message");
955 } catch (RemoteException e) {
956 AltosDebug.debug("connect device message failed");
961 private void bluetoothEnabled(Intent data) {
963 mService.send(Message.obtain(null, TelemetryService.MSG_BLUETOOTH_ENABLED, null));
964 } catch (RemoteException e) {
965 AltosDebug.debug("send BT enabled message failed");
969 private void connectDevice(Intent data) {
970 // Attempt to connect to the device
972 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
973 String name = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_NAME);
975 AltosDebug.debug("Connecting to " + address + " " + name);
976 DeviceAddress a = new DeviceAddress(address, name);
977 mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, a));
978 AltosDebug.debug("Sent connecting message");
979 } catch (RemoteException e) {
980 AltosDebug.debug("connect device message failed");
984 private void disconnectDevice(boolean remember) {
986 mService.send(Message.obtain(null, TelemetryService.MSG_DISCONNECT, (Boolean) remember));
987 } catch (RemoteException e) {
991 private void idle_mode(Intent data) {
992 int type = data.getIntExtra(IdleModeActivity.EXTRA_IDLE_RESULT, -1);
995 AltosDebug.debug("intent idle_mode %d", type);
997 case IdleModeActivity.IDLE_MODE_CONNECT:
998 msg = Message.obtain(null, TelemetryService.MSG_MONITOR_IDLE_START);
1001 } catch (RemoteException re) {
1004 case IdleModeActivity.IDLE_MODE_DISCONNECT:
1005 msg = Message.obtain(null, TelemetryService.MSG_MONITOR_IDLE_STOP);
1008 } catch (RemoteException re) {
1011 case IdleModeActivity.IDLE_MODE_REBOOT:
1012 msg = Message.obtain(null, TelemetryService.MSG_REBOOT);
1015 } catch (RemoteException re) {
1018 case IdleModeActivity.IDLE_MODE_IGNITERS:
1019 Intent serverIntent = new Intent(this, IgniterActivity.class);
1020 startActivityForResult(serverIntent, REQUEST_IGNITERS);
1026 public boolean onCreateOptionsMenu(Menu menu) {
1027 MenuInflater inflater = getMenuInflater();
1028 inflater.inflate(R.menu.option_menu, menu);
1032 void setFrequency(double freq) {
1034 mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
1036 } catch (RemoteException e) {
1040 void setFrequency(AltosFrequency frequency) {
1041 setFrequency (frequency.frequency);
1044 void setBaud(int baud) {
1046 mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD, baud));
1048 } catch (RemoteException e) {
1052 void setBaud(String baud) {
1054 int value = Integer.parseInt(baud);
1055 int rate = AltosLib.ao_telemetry_rate_38400;
1058 rate = AltosLib.ao_telemetry_rate_2400;
1061 rate = AltosLib.ao_telemetry_rate_9600;
1064 rate = AltosLib.ao_telemetry_rate_38400;
1068 } catch (NumberFormatException e) {
1072 void select_tracker(int serial) {
1075 AltosDebug.debug("select tracker %d\n", serial);
1077 if (serial == selected_serial) {
1078 AltosDebug.debug("%d already selected\n", serial);
1083 for (i = 0; i < trackers.length; i++)
1084 if (trackers[i].serial == serial)
1087 if (i == trackers.length) {
1088 AltosDebug.debug("attempt to select unknown tracker %d\n", serial);
1093 current_serial = selected_serial = serial;
1097 void touch_trackers(Integer[] serials) {
1098 AlertDialog.Builder builder_tracker = new AlertDialog.Builder(this);
1099 builder_tracker.setTitle("Select Tracker");
1101 final Tracker[] my_trackers = new Tracker[serials.length + 1];
1103 my_trackers[0] = new Tracker(null);
1105 for (int i = 0; i < serials.length; i++) {
1106 AltosState s = telemetry_state.states.get(serials[i]);
1107 my_trackers[i+1] = new Tracker(s);
1109 builder_tracker.setItems(my_trackers,
1110 new DialogInterface.OnClickListener() {
1111 public void onClick(DialogInterface dialog, int item) {
1115 select_tracker(my_trackers[item].serial);
1118 AlertDialog alert_tracker = builder_tracker.create();
1119 alert_tracker.show();
1122 void delete_track(int serial) {
1124 mService.send(Message.obtain(null, TelemetryService.MSG_DELETE_SERIAL, (Integer) serial));
1125 } catch (Exception ex) {
1130 public boolean onOptionsItemSelected(MenuItem item) {
1131 Intent serverIntent = null;
1132 switch (item.getItemId()) {
1133 case R.id.connect_scan:
1135 // Launch the DeviceListActivity to see devices and do scan
1136 serverIntent = new Intent(this, DeviceListActivity.class);
1137 startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
1139 case R.id.disconnect:
1140 /* Disconnect the device
1142 disconnectDevice(false);
1145 AltosDebug.debug("R.id.quit");
1146 disconnectDevice(true);
1150 serverIntent = new Intent(this, SetupActivity.class);
1151 startActivityForResult(serverIntent, REQUEST_SETUP);
1153 case R.id.select_freq:
1154 // Set the TBT radio frequency
1156 final AltosFrequency[] frequencies = AltosPreferences.common_frequencies();
1157 String[] frequency_strings = new String[frequencies.length];
1158 for (int i = 0; i < frequencies.length; i++)
1159 frequency_strings[i] = frequencies[i].toString();
1161 AlertDialog.Builder builder_freq = new AlertDialog.Builder(this);
1162 builder_freq.setTitle("Pick a frequency");
1163 builder_freq.setItems(frequency_strings,
1164 new DialogInterface.OnClickListener() {
1165 public void onClick(DialogInterface dialog, int item) {
1166 setFrequency(frequencies[item]);
1169 AlertDialog alert_freq = builder_freq.create();
1172 case R.id.select_tracker:
1173 if (trackers != null) {
1174 AlertDialog.Builder builder_serial = new AlertDialog.Builder(this);
1175 builder_serial.setTitle("Select a tracker");
1176 builder_serial.setItems(trackers,
1177 new DialogInterface.OnClickListener() {
1178 public void onClick(DialogInterface dialog, int item) {
1179 System.out.printf("select item %d %s\n", item, trackers[item].display);
1183 select_tracker(trackers[item].serial);
1186 AlertDialog alert_serial = builder_serial.create();
1187 alert_serial.show();
1191 case R.id.delete_track:
1192 if (trackers != null) {
1193 AlertDialog.Builder builder_serial = new AlertDialog.Builder(this);
1194 builder_serial.setTitle("Delete a track");
1195 final Tracker[] my_trackers = new Tracker[trackers.length - 1];
1196 for (int i = 0; i < trackers.length - 1; i++)
1197 my_trackers[i] = trackers[i+1];
1198 builder_serial.setItems(my_trackers,
1199 new DialogInterface.OnClickListener() {
1200 public void onClick(DialogInterface dialog, int item) {
1201 delete_track(my_trackers[item].serial);
1204 AlertDialog alert_serial = builder_serial.create();
1205 alert_serial.show();
1209 case R.id.idle_mode:
1210 serverIntent = new Intent(this, IdleModeActivity.class);
1211 serverIntent.putExtra(EXTRA_IDLE_MODE, idle_mode);
1212 startActivityForResult(serverIntent, REQUEST_IDLE_MODE);
1218 static String direction(AltosGreatCircle from_receiver,
1219 Location receiver) {
1220 if (from_receiver == null)
1223 if (receiver == null)
1226 if (!receiver.hasBearing())
1229 float bearing = receiver.getBearing();
1230 float heading = (float) from_receiver.bearing - bearing;
1232 while (heading <= -180.0f)
1234 while (heading > 180.0f)
1237 int iheading = (int) (heading + 0.5f);
1239 if (-1 < iheading && iheading < 1)
1241 else if (iheading < -179 || 179 < iheading)
1243 else if (iheading < 0)
1244 return String.format("left %d°", -iheading);
1246 return String.format("right %d°", iheading);
1249 public void onLocationChanged(Location location) {
1250 this.location = location;
1251 AltosDebug.debug("Location changed to %f,%f",
1252 location.getLatitude(),
1253 location.getLongitude());
1254 update_ui(telemetry_state, state, false);
1257 public void onStatusChanged(String provider, int status, Bundle extras) {
1258 AltosDebug.debug("Location status now %d\n", status);
1261 public void onProviderEnabled(String provider) {
1262 AltosDebug.debug("Location provider enabled %s\n", provider);
1265 public void onProviderDisabled(String provider) {
1266 AltosDebug.debug("Location provider disabled %s\n", provider);