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.app.Activity;
25 import android.app.PendingIntent;
26 import android.bluetooth.BluetoothAdapter;
27 import android.content.Intent;
28 import android.content.Context;
29 import android.content.ComponentName;
30 import android.content.ServiceConnection;
31 import android.content.DialogInterface;
32 import android.os.IBinder;
33 import android.os.Bundle;
34 import android.os.Handler;
35 import android.os.Message;
36 import android.os.Messenger;
37 import android.os.RemoteException;
38 import androidx.fragment.app.FragmentActivity;
39 import androidx.fragment.app.FragmentManager;
40 import android.view.*;
41 import android.widget.*;
42 import android.app.AlertDialog;
43 import android.location.Location;
44 import android.location.LocationManager;
45 import android.location.LocationListener;
46 import android.hardware.usb.*;
48 import org.altusmetrum.altoslib_13.*;
59 SavedState(AltosState state) {
60 received_time = state.received_time;
61 this.state = state.state();
62 if (state.gps != null)
63 locked = state.gps.locked;
66 callsign = state.cal_data().callsign;
67 serial = state.cal_data().serial;
68 flight = state.cal_data().flight;
73 class Tracker implements CharSequence, Comparable {
80 public Tracker(int serial, String call, double frequency) {
86 this.frequency = frequency;
89 else if (frequency == AltosLib.MISSING) {
90 display = String.format("%-8.8s %6d", call, serial);
92 display = String.format("%-8.8s %7.3f %6d", call, frequency, serial);
96 public Tracker(AltosState s) {
97 this(s == null ? 0 : s.cal_data().serial,
98 s == null ? null : s.cal_data().callsign,
99 s == null ? 0.0 : s.frequency);
103 public char charAt(int index) {
104 return display.charAt(index);
107 public int length() {
108 return display.length();
111 public CharSequence subSequence(int start, int end) throws IndexOutOfBoundsException {
112 return display.subSequence(start, end);
115 public String toString() {
116 return display.toString();
120 public int compareTo (Object other) {
121 Tracker o = (Tracker) other;
122 if (frequency == 0.0) {
123 if (o.frequency == 0.0)
127 if (o.frequency == 0.0)
130 int a = serial - o.serial;
131 int b = call.compareTo(o.call);
132 int c = (int) Math.signum(frequency - o.frequency);
142 public class AltosDroid extends FragmentActivity implements AltosUnitsListener, LocationListener {
144 // Actions sent to the telemetry server at startup time
146 public static final String ACTION_BLUETOOTH = "org.altusmetrum.AltosDroid.BLUETOOTH";
147 public static final String ACTION_USB = "org.altusmetrum.AltosDroid.USB";
149 // Message types received by our Handler
151 public static final int MSG_STATE = 1;
152 public static final int MSG_UPDATE_AGE = 2;
153 public static final int MSG_IDLE_MODE = 3;
154 public static final int MSG_IGNITER_STATUS = 4;
156 // Intent request codes
157 public static final int REQUEST_CONNECT_DEVICE = 1;
158 public static final int REQUEST_ENABLE_BT = 2;
159 public static final int REQUEST_PRELOAD_MAPS = 3;
160 public static final int REQUEST_IDLE_MODE = 5;
161 public static final int REQUEST_IGNITERS = 6;
162 public static final int REQUEST_SETUP = 7;
164 public static final String EXTRA_IDLE_MODE = "idle_mode";
165 public static final String EXTRA_IDLE_RESULT = "idle_result";
166 public static final String EXTRA_TELEMETRY_SERVICE = "telemetry_service";
169 public static final int SETUP_BAUD = 1;
170 public static final int SETUP_UNITS = 2;
171 public static final int SETUP_MAP_SOURCE = 4;
172 public static final int SETUP_MAP_TYPE = 8;
174 public static FragmentManager fm;
176 private BluetoothAdapter mBluetoothAdapter = null;
178 // Flight state values
179 private TextView mCallsignView;
180 private TextView mRSSIView;
181 private TextView mSerialView;
182 private TextView mFlightView;
183 private RelativeLayout mStateLayout;
184 private TextView mStateView;
185 private TextView mAgeView;
186 private boolean mAgeViewOld;
187 private int mAgeNewColor;
188 private int mAgeOldColor;
190 public static final String tab_pad_name = "pad";
191 public static final String tab_flight_name = "flight";
192 public static final String tab_recover_name = "recover";
193 public static final String tab_map_name = "map";
195 // field to display the version at the bottom of the screen
196 private TextView mVersion;
198 private boolean idle_mode = false;
200 public Location location = null;
202 private AltosState state;
203 private SavedState saved_state;
207 AltosViewPager mViewPager;
208 TabsAdapter mTabsAdapter;
209 ArrayList<AltosDroidTab> mTabs = new ArrayList<AltosDroidTab>();
212 // Timer and Saved flight state for Age calculation
215 TelemetryState telemetry_state;
219 UsbDevice pending_usb_device;
220 boolean start_with_usb;
223 private boolean mIsBound = false;
224 private Messenger mService = null;
225 final Messenger mMessenger = new Messenger(new IncomingHandler(this));
228 private AltosVoice mAltosVoice = null;
230 // The Handler that gets information back from the Telemetry Service
231 static class IncomingHandler extends Handler {
232 private final WeakReference<AltosDroid> mAltosDroid;
233 IncomingHandler(AltosDroid ad) { mAltosDroid = new WeakReference<AltosDroid>(ad); }
236 public void handleMessage(Message msg) {
237 AltosDroid ad = mAltosDroid.get();
241 if (msg.obj == null) {
242 AltosDebug.debug("telemetry_state null!");
245 ad.update_state((TelemetryState) msg.obj);
251 ad.idle_mode = (Boolean) msg.obj;
252 ad.update_state(null);
259 private ServiceConnection mConnection = new ServiceConnection() {
260 public void onServiceConnected(ComponentName className, IBinder service) {
261 mService = new Messenger(service);
263 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
264 msg.replyTo = mMessenger;
266 } catch (RemoteException e) {
267 // In this case the service has crashed before we could even do anything with it
269 if (pending_usb_device != null) {
271 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, pending_usb_device));
272 pending_usb_device = null;
273 } catch (RemoteException e) {
278 public void onServiceDisconnected(ComponentName className) {
279 // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
284 void doBindService() {
285 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
289 void doUnbindService() {
291 // If we have received the service, and hence registered with it, then now is the time to unregister.
292 if (mService != null) {
294 Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
295 msg.replyTo = mMessenger;
297 } catch (RemoteException e) {
298 // There is nothing special we need to do if the service has crashed.
301 // Detach our existing connection.
302 unbindService(mConnection);
307 public void registerTab(AltosDroidTab mTab) {
311 public void unregisterTab(AltosDroidTab mTab) {
315 public void units_changed(boolean imperial_units) {
316 for (AltosDroidTab mTab : mTabs)
317 mTab.units_changed(imperial_units);
320 void update_title(TelemetryState telemetry_state) {
321 switch (telemetry_state.connect) {
322 case TelemetryState.CONNECT_CONNECTED:
323 if (telemetry_state.config != null) {
324 String str = String.format("S/N %d %6.3f MHz%s", telemetry_state.config.serial,
325 telemetry_state.frequency, idle_mode ? " (idle)" : "");
326 if (telemetry_state.telemetry_rate != AltosLib.ao_telemetry_rate_38400)
327 str = str.concat(String.format(" %d bps",
328 AltosLib.ao_telemetry_rate_values[telemetry_state.telemetry_rate]));
331 setTitle(R.string.title_connected_to);
334 case TelemetryState.CONNECT_CONNECTING:
335 if (telemetry_state.address != null)
336 setTitle(String.format("Connecting to %s...", telemetry_state.address.name));
338 setTitle("Connecting to something...");
340 case TelemetryState.CONNECT_DISCONNECTED:
341 case TelemetryState.CONNECT_NONE:
342 setTitle(R.string.title_not_connected);
350 timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 1000L, 1000L);
362 int selected_serial = 0;
366 void set_switch_time() {
367 switch_time = System.currentTimeMillis();
371 boolean registered_units_listener;
373 void update_state(TelemetryState new_telemetry_state) {
375 if (new_telemetry_state != null)
376 telemetry_state = new_telemetry_state;
378 if (selected_serial != 0)
379 current_serial = selected_serial;
381 if (current_serial == 0)
382 current_serial = telemetry_state.latest_serial;
384 if (!registered_units_listener) {
385 registered_units_listener = true;
386 AltosPreferences.register_units_listener(this);
389 int num_trackers = 0;
390 for (AltosState s : telemetry_state.states.values()) {
394 trackers = new Tracker[num_trackers + 1];
397 trackers[n++] = new Tracker(0, "auto", 0.0);
399 for (AltosState s : telemetry_state.states.values())
400 trackers[n++] = new Tracker(s);
402 Arrays.sort(trackers);
404 update_title(telemetry_state);
406 AltosState state = null;
409 if (telemetry_state.states.containsKey(current_serial)) {
410 state = telemetry_state.states.get(current_serial);
411 int age = state_age(state.received_time);
414 if (current_serial == selected_serial)
416 else if (switch_time != 0 && (switch_time - state.received_time) > 0)
421 AltosState newest_state = null;
424 for (int serial : telemetry_state.states.keySet()) {
425 AltosState existing = telemetry_state.states.get(serial);
426 int existing_age = state_age(existing.received_time);
428 if (newest_state == null || existing_age < newest_age) {
429 newest_state = existing;
430 newest_age = existing_age;
434 if (newest_state != null)
435 state = newest_state;
438 update_ui(telemetry_state, state, telemetry_state.quiet);
443 boolean same_string(String a, String b) {
456 private int blend_component(int a, int b, double r, int shift, int mask) {
457 return ((int) (((a >> shift) & mask) * r + ((b >> shift) & mask) * (1 - r)) & mask) << shift;
459 private int blend_color(int a, int b, double r) {
460 return (blend_component(a, b, r, 0, 0xff) |
461 blend_component(a, b, r, 8, 0xff) |
462 blend_component(a, b, r, 16, 0xff) |
463 blend_component(a, b, r, 24, 0xff));
466 int state_age(long received_time) {
467 return (int) ((System.currentTimeMillis() - received_time + 500) / 1000);
470 void set_screen_on(int age) {
472 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
474 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
478 if (saved_state != null) {
479 int age = state_age(saved_state.received_time);
481 double age_scale = age / 100.0;
486 mAgeView.setTextColor(blend_color(mAgeOldColor, mAgeNewColor, age_scale));
492 text = String.format("%ds", age);
493 else if (age < 60 * 60)
494 text = String.format("%dm", age / 60);
495 else if (age < 60 * 60 * 24)
496 text = String.format("%dh", age / (60 * 60));
498 text = String.format("%dd", age / (24 * 60 * 60));
499 mAgeView.setText(text);
503 void update_ui(TelemetryState telem_state, AltosState state, boolean quiet) {
507 int prev_state = AltosLib.ao_flight_invalid;
509 AltosGreatCircle from_receiver = null;
511 if (saved_state != null)
512 prev_state = saved_state.state;
515 set_screen_on(state_age(state.received_time));
517 if (state.state() == AltosLib.ao_flight_stateless) {
518 boolean prev_locked = false;
519 boolean locked = false;
521 if(state.gps != null)
522 locked = state.gps.locked;
523 if (saved_state != null)
524 prev_locked = saved_state.locked;
525 if (prev_locked != locked) {
526 String currentTab = mTabHost.getCurrentTabTag();
528 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
530 if (currentTab.equals(tab_flight_name)) mTabHost.setCurrentTabByTag(tab_pad_name);
534 if (prev_state != state.state()) {
535 String currentTab = mTabHost.getCurrentTabTag();
536 switch (state.state()) {
537 case AltosLib.ao_flight_boost:
538 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
540 case AltosLib.ao_flight_landed:
541 if (currentTab.equals(tab_flight_name)) mTabHost.setCurrentTabByTag(tab_recover_name);
543 case AltosLib.ao_flight_stateless:
544 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
550 if (location != null && state.gps != null && state.gps.locked) {
552 if (location.hasAltitude())
553 altitude = location.getAltitude();
554 from_receiver = new AltosGreatCircle(location.getLatitude(),
555 location.getLongitude(),
562 if (saved_state == null || !same_string(saved_state.callsign, state.cal_data().callsign)) {
563 mCallsignView.setText(state.cal_data().callsign);
565 if (saved_state == null || state.cal_data().serial != saved_state.serial) {
566 if (state.cal_data().serial == AltosLib.MISSING)
567 mSerialView.setText("");
569 mSerialView.setText(String.format("%d", state.cal_data().serial));
571 if (saved_state == null || state.cal_data().flight != saved_state.flight) {
572 if (state.cal_data().flight == AltosLib.MISSING)
573 mFlightView.setText("");
575 mFlightView.setText(String.format("%d", state.cal_data().flight));
577 if (saved_state == null || state.state() != saved_state.state) {
578 if (state.state() == AltosLib.ao_flight_stateless) {
579 mStateLayout.setVisibility(View.GONE);
581 mStateView.setText(state.state_name());
582 mStateLayout.setVisibility(View.VISIBLE);
585 if (saved_state == null || state.rssi != saved_state.rssi) {
586 if (state.rssi == AltosLib.MISSING)
587 mRSSIView.setText("");
589 mRSSIView.setText(String.format("%d", state.rssi));
591 saved_state = new SavedState(state);
594 for (AltosDroidTab mTab : mTabs)
595 mTab.update_ui(telem_state, state, from_receiver, location, mTab == mTabsAdapter.currentItem());
597 AltosDebug.debug("quiet %b\n", quiet);
598 if (mAltosVoice != null)
599 mAltosVoice.tell(telem_state, state, from_receiver, location, (AltosDroidTab) mTabsAdapter.currentItem(), quiet);
603 private void onTimerTick() {
605 mMessenger.send(Message.obtain(null, MSG_UPDATE_AGE));
606 } catch (RemoteException e) {
610 static String pos(double p, String pos, String neg) {
612 if (p == AltosLib.MISSING)
618 int deg = (int) Math.floor(p);
619 double min = (p - Math.floor(p)) * 60.0;
620 return String.format("%d°%9.4f\" %s", deg, min, h);
623 static String number(String format, double value) {
624 if (value == AltosLib.MISSING)
626 return String.format(format, value);
629 static String integer(String format, int value) {
630 if (value == AltosLib.MISSING)
632 return String.format(format, value);
635 private View create_tab_view(String label) {
636 LayoutInflater inflater = (LayoutInflater) this.getLayoutInflater();
637 View tab_view = inflater.inflate(R.layout.tab_layout, null);
638 TextView text_view = (TextView) tab_view.findViewById (R.id.tabLabel);
639 text_view.setText(label);
644 public void onCreate(Bundle savedInstanceState) {
645 super.onCreate(savedInstanceState);
646 AltosDebug.init(this);
647 AltosDebug.debug("+++ ON CREATE +++");
649 // Initialise preferences
650 AltosDroidPreferences.init(this);
652 fm = getSupportFragmentManager();
654 // Set up the window layout
655 setContentView(R.layout.altosdroid);
657 // Create the Tabs and ViewPager
658 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
661 mViewPager = (AltosViewPager)findViewById(R.id.pager);
662 mViewPager.setOffscreenPageLimit(4);
664 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
666 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_pad_name).setIndicator(create_tab_view("Pad")), TabPad.class, null);
667 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_flight_name).setIndicator(create_tab_view("Flight")), TabFlight.class, null);
668 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_recover_name).setIndicator(create_tab_view("Recover")), TabRecover.class, null);
669 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_map_name).setIndicator(create_tab_view("Map")), TabMap.class, null);
671 // Display the Version
672 mVersion = (TextView) findViewById(R.id.version);
673 mVersion.setText("Version: " + BuildInfo.version +
674 " Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
675 " (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
677 mCallsignView = (TextView) findViewById(R.id.callsign_value);
678 mRSSIView = (TextView) findViewById(R.id.rssi_value);
679 mSerialView = (TextView) findViewById(R.id.serial_value);
680 mFlightView = (TextView) findViewById(R.id.flight_value);
681 mStateLayout = (RelativeLayout) findViewById(R.id.state_container);
682 mStateView = (TextView) findViewById(R.id.state_value);
683 mAgeView = (TextView) findViewById(R.id.age_value);
684 mAgeNewColor = mAgeView.getTextColors().getDefaultColor();
685 mAgeOldColor = getResources().getColor(R.color.old_color);
688 private void ensureBluetooth() {
689 // Get local Bluetooth adapter
690 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
692 /* if there is a BT adapter and it isn't turned on, then turn it on */
693 if (mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) {
694 Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
695 startActivityForResult(enableIntent, AltosDroid.REQUEST_ENABLE_BT);
699 private boolean check_usb() {
700 UsbDevice device = AltosUsb.find_device(this, AltosLib.product_basestation);
702 if (device != null) {
703 Intent i = new Intent(this, AltosDroid.class);
704 PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent("hello world", null, this, AltosDroid.class), 0);
706 if (AltosUsb.request_permission(this, device, pi)) {
709 start_with_usb = true;
713 start_with_usb = false;
718 private void noticeIntent(Intent intent) {
720 /* Ok, this is pretty convenient.
722 * When a USB device is plugged in, and our 'hotplug'
723 * intent registration fires, we get an Intent with
726 * When we start up and see a usb device and request
727 * permission to access it, that queues a
728 * PendingIntent, which has the EXTRA_DEVICE added in,
729 * along with the EXTRA_PERMISSION_GRANTED field as
732 * So, in both cases, we get the device name using the
733 * same call. We check to see if access was granted,
734 * in which case we ignore the device field and do our
735 * usual startup thing.
738 UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
739 boolean granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, true);
741 AltosDebug.debug("intent %s device %s granted %s", intent, device, granted);
746 if (device != null) {
747 AltosDebug.debug("intent has usb device " + device.toString());
751 /* 'granted' is only false if this intent came
752 * from the request_permission call and
753 * permission was denied. In which case, we
754 * don't want to loop forever...
757 AltosDebug.debug("check for a USB device at startup");
761 AltosDebug.debug("Starting by looking for bluetooth devices");
767 public void onStart() {
769 AltosDebug.debug("++ ON START ++");
773 noticeIntent(getIntent());
775 // Start Telemetry Service
776 String action = start_with_usb ? ACTION_USB : ACTION_BLUETOOTH;
778 startService(new Intent(action, null, AltosDroid.this, TelemetryService.class));
782 if (mAltosVoice == null)
783 mAltosVoice = new AltosVoice(this);
788 public void onNewIntent(Intent intent) {
789 super.onNewIntent(intent);
790 AltosDebug.debug("onNewIntent");
791 noticeIntent(intent);
795 public void onResume() {
797 AltosDebug.debug("+ ON RESUME +");
799 // Listen for GPS and Network position updates
800 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
801 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
803 location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
805 if (location != null)
806 AltosDebug.debug("Resume, location is %f,%f\n",
807 location.getLatitude(),
808 location.getLongitude());
810 update_ui(telemetry_state, state, true);
814 public void onPause() {
816 AltosDebug.debug("- ON PAUSE -");
817 // Stop listening for location updates
818 ((LocationManager) getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
822 public void onStop() {
824 AltosDebug.debug("-- ON STOP --");
828 public void onDestroy() {
830 AltosDebug.debug("--- ON DESTROY ---");
833 if (mAltosVoice != null) {
840 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
841 AltosDebug.debug("onActivityResult " + resultCode);
842 switch (requestCode) {
843 case REQUEST_CONNECT_DEVICE:
844 // When DeviceListActivity returns with a device to connect to
845 if (resultCode == Activity.RESULT_OK) {
849 case REQUEST_ENABLE_BT:
850 // When the request to enable Bluetooth returns
851 if (resultCode == Activity.RESULT_OK) {
852 // Bluetooth is now enabled, so set up a chat session
854 AltosDebug.debug("BT enabled");
855 bluetoothEnabled(data);
857 // User did not enable Bluetooth or an error occured
858 AltosDebug.debug("BT not enabled");
861 case REQUEST_IDLE_MODE:
862 if (resultCode == Activity.RESULT_OK)
865 case REQUEST_IGNITERS:
868 if (resultCode == Activity.RESULT_OK)
869 note_setup_changes(data);
874 private void note_setup_changes(Intent data) {
875 int changes = data.getIntExtra(SetupActivity.EXTRA_SETUP_CHANGES, 0);
877 if ((changes & SETUP_BAUD) != 0) {
879 mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD,
880 AltosPreferences.telemetry_rate(1)));
881 } catch (RemoteException re) {
884 if ((changes & SETUP_UNITS) != 0) {
885 /* nothing to do here */
887 if ((changes & SETUP_MAP_SOURCE) != 0) {
888 /* nothing to do here */
890 if ((changes & SETUP_MAP_TYPE) != 0) {
891 /* nothing to do here */
896 private void connectUsb(UsbDevice device) {
897 if (mService == null)
898 pending_usb_device = device;
900 // Attempt to connect to the device
902 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, device));
903 AltosDebug.debug("Sent OPEN_USB message");
904 } catch (RemoteException e) {
905 AltosDebug.debug("connect device message failed");
910 private void bluetoothEnabled(Intent data) {
912 mService.send(Message.obtain(null, TelemetryService.MSG_BLUETOOTH_ENABLED, null));
913 } catch (RemoteException e) {
914 AltosDebug.debug("send BT enabled message failed");
918 private void connectDevice(Intent data) {
919 // Attempt to connect to the device
921 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
922 String name = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_NAME);
924 AltosDebug.debug("Connecting to " + address + " " + name);
925 DeviceAddress a = new DeviceAddress(address, name);
926 mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, a));
927 AltosDebug.debug("Sent connecting message");
928 } catch (RemoteException e) {
929 AltosDebug.debug("connect device message failed");
933 private void disconnectDevice(boolean remember) {
935 mService.send(Message.obtain(null, TelemetryService.MSG_DISCONNECT, (Boolean) remember));
936 } catch (RemoteException e) {
940 private void idle_mode(Intent data) {
941 int type = data.getIntExtra(IdleModeActivity.EXTRA_IDLE_RESULT, -1);
944 AltosDebug.debug("intent idle_mode %d", type);
946 case IdleModeActivity.IDLE_MODE_CONNECT:
947 msg = Message.obtain(null, TelemetryService.MSG_MONITOR_IDLE_START);
950 } catch (RemoteException re) {
953 case IdleModeActivity.IDLE_MODE_DISCONNECT:
954 msg = Message.obtain(null, TelemetryService.MSG_MONITOR_IDLE_STOP);
957 } catch (RemoteException re) {
960 case IdleModeActivity.IDLE_MODE_REBOOT:
961 msg = Message.obtain(null, TelemetryService.MSG_REBOOT);
964 } catch (RemoteException re) {
967 case IdleModeActivity.IDLE_MODE_IGNITERS:
968 Intent serverIntent = new Intent(this, IgniterActivity.class);
969 startActivityForResult(serverIntent, REQUEST_IGNITERS);
975 public boolean onCreateOptionsMenu(Menu menu) {
976 MenuInflater inflater = getMenuInflater();
977 inflater.inflate(R.menu.option_menu, menu);
981 void setFrequency(double freq) {
983 mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
985 } catch (RemoteException e) {
989 void setFrequency(AltosFrequency frequency) {
990 setFrequency (frequency.frequency);
993 void setBaud(int baud) {
995 mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD, baud));
997 } catch (RemoteException e) {
1001 void setBaud(String baud) {
1003 int value = Integer.parseInt(baud);
1004 int rate = AltosLib.ao_telemetry_rate_38400;
1007 rate = AltosLib.ao_telemetry_rate_2400;
1010 rate = AltosLib.ao_telemetry_rate_9600;
1013 rate = AltosLib.ao_telemetry_rate_38400;
1017 } catch (NumberFormatException e) {
1021 void select_tracker(int serial) {
1024 AltosDebug.debug("select tracker %d\n", serial);
1026 if (serial == selected_serial) {
1027 AltosDebug.debug("%d already selected\n", serial);
1032 for (i = 0; i < trackers.length; i++)
1033 if (trackers[i].serial == serial)
1036 if (i == trackers.length) {
1037 AltosDebug.debug("attempt to select unknown tracker %d\n", serial);
1042 current_serial = selected_serial = serial;
1046 void touch_trackers(Integer[] serials) {
1047 AlertDialog.Builder builder_tracker = new AlertDialog.Builder(this);
1048 builder_tracker.setTitle("Select Tracker");
1050 final Tracker[] my_trackers = new Tracker[serials.length + 1];
1052 my_trackers[0] = new Tracker(null);
1054 for (int i = 0; i < serials.length; i++) {
1055 AltosState s = telemetry_state.states.get(serials[i]);
1056 my_trackers[i+1] = new Tracker(s);
1058 builder_tracker.setItems(my_trackers,
1059 new DialogInterface.OnClickListener() {
1060 public void onClick(DialogInterface dialog, int item) {
1064 select_tracker(my_trackers[item].serial);
1067 AlertDialog alert_tracker = builder_tracker.create();
1068 alert_tracker.show();
1071 void delete_track(int serial) {
1073 mService.send(Message.obtain(null, TelemetryService.MSG_DELETE_SERIAL, (Integer) serial));
1074 } catch (Exception ex) {
1079 public boolean onOptionsItemSelected(MenuItem item) {
1080 Intent serverIntent = null;
1081 switch (item.getItemId()) {
1082 case R.id.connect_scan:
1084 // Launch the DeviceListActivity to see devices and do scan
1085 serverIntent = new Intent(this, DeviceListActivity.class);
1086 startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
1088 case R.id.disconnect:
1089 /* Disconnect the device
1091 disconnectDevice(false);
1094 AltosDebug.debug("R.id.quit");
1095 disconnectDevice(true);
1099 serverIntent = new Intent(this, SetupActivity.class);
1100 startActivityForResult(serverIntent, REQUEST_SETUP);
1102 case R.id.select_freq:
1103 // Set the TBT radio frequency
1105 final AltosFrequency[] frequencies = AltosPreferences.common_frequencies();
1106 String[] frequency_strings = new String[frequencies.length];
1107 for (int i = 0; i < frequencies.length; i++)
1108 frequency_strings[i] = frequencies[i].toString();
1110 AlertDialog.Builder builder_freq = new AlertDialog.Builder(this);
1111 builder_freq.setTitle("Pick a frequency");
1112 builder_freq.setItems(frequency_strings,
1113 new DialogInterface.OnClickListener() {
1114 public void onClick(DialogInterface dialog, int item) {
1115 setFrequency(frequencies[item]);
1118 AlertDialog alert_freq = builder_freq.create();
1121 case R.id.select_tracker:
1122 if (trackers != null) {
1123 AlertDialog.Builder builder_serial = new AlertDialog.Builder(this);
1124 builder_serial.setTitle("Select a tracker");
1125 builder_serial.setItems(trackers,
1126 new DialogInterface.OnClickListener() {
1127 public void onClick(DialogInterface dialog, int item) {
1128 System.out.printf("select item %d %s\n", item, trackers[item].display);
1132 select_tracker(trackers[item].serial);
1135 AlertDialog alert_serial = builder_serial.create();
1136 alert_serial.show();
1140 case R.id.delete_track:
1141 if (trackers != null) {
1142 AlertDialog.Builder builder_serial = new AlertDialog.Builder(this);
1143 builder_serial.setTitle("Delete a track");
1144 final Tracker[] my_trackers = new Tracker[trackers.length - 1];
1145 for (int i = 0; i < trackers.length - 1; i++)
1146 my_trackers[i] = trackers[i+1];
1147 builder_serial.setItems(my_trackers,
1148 new DialogInterface.OnClickListener() {
1149 public void onClick(DialogInterface dialog, int item) {
1150 delete_track(my_trackers[item].serial);
1153 AlertDialog alert_serial = builder_serial.create();
1154 alert_serial.show();
1158 case R.id.idle_mode:
1159 serverIntent = new Intent(this, IdleModeActivity.class);
1160 serverIntent.putExtra(EXTRA_IDLE_MODE, idle_mode);
1161 startActivityForResult(serverIntent, REQUEST_IDLE_MODE);
1167 static String direction(AltosGreatCircle from_receiver,
1168 Location receiver) {
1169 if (from_receiver == null)
1172 if (receiver == null)
1175 if (!receiver.hasBearing())
1178 float bearing = receiver.getBearing();
1179 float heading = (float) from_receiver.bearing - bearing;
1181 while (heading <= -180.0f)
1183 while (heading > 180.0f)
1186 int iheading = (int) (heading + 0.5f);
1188 if (-1 < iheading && iheading < 1)
1190 else if (iheading < -179 || 179 < iheading)
1192 else if (iheading < 0)
1193 return String.format("left %d°", -iheading);
1195 return String.format("right %d°", iheading);
1198 public void onLocationChanged(Location location) {
1199 this.location = location;
1200 AltosDebug.debug("Location changed to %f,%f",
1201 location.getLatitude(),
1202 location.getLongitude());
1203 update_ui(telemetry_state, state, false);
1206 public void onStatusChanged(String provider, int status, Bundle extras) {
1207 AltosDebug.debug("Location status now %d\n", status);
1210 public void onProviderEnabled(String provider) {
1211 AltosDebug.debug("Location provider enabled %s\n", provider);
1214 public void onProviderDisabled(String provider) {
1215 AltosDebug.debug("Location provider disabled %s\n", provider);