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; version 2 of the License.
8 * This program is distributed in the hope that it will be useful, but
9 * WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
18 package org.altusmetrum.AltosDroid;
20 import java.lang.ref.WeakReference;
21 import java.util.ArrayList;
22 import java.util.Timer;
23 import java.util.TimerTask;
26 import android.app.Activity;
27 import android.app.PendingIntent;
28 import android.bluetooth.BluetoothAdapter;
29 import android.bluetooth.BluetoothDevice;
30 import android.content.Intent;
31 import android.content.Context;
32 import android.content.ComponentName;
33 import android.content.ServiceConnection;
34 import android.content.DialogInterface;
35 import android.os.IBinder;
36 import android.os.Bundle;
37 import android.os.Handler;
38 import android.os.Message;
39 import android.os.Messenger;
40 import android.os.RemoteException;
41 import android.content.res.Resources;
42 import android.support.v4.app.FragmentActivity;
43 import android.support.v4.app.FragmentManager;
44 import android.util.DisplayMetrics;
45 import android.view.Menu;
46 import android.view.MenuInflater;
47 import android.view.MenuItem;
48 import android.view.Window;
49 import android.view.View;
50 import android.view.LayoutInflater;
51 import android.widget.TabHost;
52 import android.widget.TextView;
53 import android.widget.RelativeLayout;
54 import android.widget.Toast;
55 import android.app.AlertDialog;
56 import android.location.Location;
57 import android.hardware.usb.*;
59 import org.altusmetrum.altoslib_7.*;
61 public class AltosDroid extends FragmentActivity implements AltosUnitsListener {
63 // Actions sent to the telemetry server at startup time
65 public static final String ACTION_BLUETOOTH = "org.altusmetrum.AltosDroid.BLUETOOTH";
66 public static final String ACTION_USB = "org.altusmetrum.AltosDroid.USB";
68 // Message types received by our Handler
70 public static final int MSG_STATE = 1;
71 public static final int MSG_UPDATE_AGE = 2;
73 // Intent request codes
74 public static final int REQUEST_CONNECT_DEVICE = 1;
75 public static final int REQUEST_ENABLE_BT = 2;
76 public static final int REQUEST_PRELOAD_MAPS = 3;
77 public static final int REQUEST_MAP_TYPE = 4;
79 public static FragmentManager fm;
81 private BluetoothAdapter mBluetoothAdapter = null;
84 private TextView mTitle;
86 // Flight state values
87 private TextView mCallsignView;
88 private TextView mRSSIView;
89 private TextView mSerialView;
90 private TextView mFlightView;
91 private RelativeLayout mStateLayout;
92 private TextView mStateView;
93 private TextView mAgeView;
95 // field to display the version at the bottom of the screen
96 private TextView mVersion;
98 private double frequency;
99 private int telemetry_rate;
103 AltosViewPager mViewPager;
104 TabsAdapter mTabsAdapter;
105 ArrayList<AltosDroidTab> mTabs = new ArrayList<AltosDroidTab>();
108 // Timer and Saved flight state for Age calculation
110 AltosState saved_state;
112 UsbDevice pending_usb_device;
113 boolean start_with_usb;
116 private boolean mIsBound = false;
117 private Messenger mService = null;
118 final Messenger mMessenger = new Messenger(new IncomingHandler(this));
121 private AltosVoice mAltosVoice = null;
123 // The Handler that gets information back from the Telemetry Service
124 static class IncomingHandler extends Handler {
125 private final WeakReference<AltosDroid> mAltosDroid;
126 IncomingHandler(AltosDroid ad) { mAltosDroid = new WeakReference<AltosDroid>(ad); }
129 public void handleMessage(Message msg) {
130 AltosDroid ad = mAltosDroid.get();
134 AltosDebug.debug("MSG_STATE");
135 TelemetryState telemetry_state = (TelemetryState) msg.obj;
136 if (telemetry_state == null) {
137 AltosDebug.debug("telemetry_state null!");
141 ad.update_state(telemetry_state);
144 AltosDebug.debug("MSG_UPDATE_AGE");
152 private ServiceConnection mConnection = new ServiceConnection() {
153 public void onServiceConnected(ComponentName className, IBinder service) {
154 mService = new Messenger(service);
156 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
157 msg.replyTo = mMessenger;
159 } catch (RemoteException e) {
160 // In this case the service has crashed before we could even do anything with it
162 if (pending_usb_device != null) {
164 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, pending_usb_device));
165 pending_usb_device = null;
166 } catch (RemoteException e) {
171 public void onServiceDisconnected(ComponentName className) {
172 // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
177 void doBindService() {
178 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
182 void doUnbindService() {
184 // If we have received the service, and hence registered with it, then now is the time to unregister.
185 if (mService != null) {
187 Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
188 msg.replyTo = mMessenger;
190 } catch (RemoteException e) {
191 // There is nothing special we need to do if the service has crashed.
194 // Detach our existing connection.
195 unbindService(mConnection);
200 public void registerTab(AltosDroidTab mTab) {
204 public void unregisterTab(AltosDroidTab mTab) {
208 public void units_changed(boolean imperial_units) {
209 for (AltosDroidTab mTab : mTabs)
210 mTab.units_changed(imperial_units);
213 void update_title(TelemetryState telemetry_state) {
214 switch (telemetry_state.connect) {
215 case TelemetryState.CONNECT_CONNECTED:
216 if (telemetry_state.config != null) {
217 String str = String.format("S/N %d %6.3f MHz", telemetry_state.config.serial,
218 telemetry_state.frequency);
219 if (telemetry_state.telemetry_rate != AltosLib.ao_telemetry_rate_38400)
220 str = str.concat(String.format(" %d bps",
221 AltosLib.ao_telemetry_rate_values[telemetry_state.telemetry_rate]));
224 mTitle.setText(R.string.title_connected_to);
227 case TelemetryState.CONNECT_CONNECTING:
228 if (telemetry_state.address != null)
229 mTitle.setText(String.format("Connecting to %s...", telemetry_state.address.name));
231 mTitle.setText("Connecting to something...");
233 case TelemetryState.CONNECT_DISCONNECTED:
234 case TelemetryState.CONNECT_NONE:
235 mTitle.setText(R.string.title_not_connected);
243 timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 1000L, 1000L);
255 boolean registered_units_listener;
257 void update_state(TelemetryState telemetry_state) {
259 if (!registered_units_listener) {
260 registered_units_listener = true;
261 AltosPreferences.register_units_listener(this);
264 update_title(telemetry_state);
265 update_ui(telemetry_state.state, telemetry_state.location);
266 if (telemetry_state.connect == TelemetryState.CONNECT_CONNECTED)
270 boolean same_string(String a, String b) {
283 if (saved_state != null)
284 mAgeView.setText(String.format("%d", (System.currentTimeMillis() - saved_state.received_time + 500) / 1000));
287 void update_ui(AltosState state, Location location) {
289 int prev_state = AltosLib.ao_flight_invalid;
291 AltosGreatCircle from_receiver = null;
293 if (saved_state != null)
294 prev_state = saved_state.state;
297 if (state.state == AltosLib.ao_flight_stateless) {
298 boolean prev_locked = false;
299 boolean locked = false;
301 if(state.gps != null)
302 locked = state.gps.locked;
303 if (saved_state != null && saved_state.gps != null)
304 prev_locked = saved_state.gps.locked;
305 if (prev_locked != locked) {
306 String currentTab = mTabHost.getCurrentTabTag();
308 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("descent");
310 if (currentTab.equals("descent")) mTabHost.setCurrentTabByTag("pad");
314 if (prev_state != state.state) {
315 String currentTab = mTabHost.getCurrentTabTag();
316 switch (state.state) {
317 case AltosLib.ao_flight_boost:
318 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("ascent");
320 case AltosLib.ao_flight_drogue:
321 if (currentTab.equals("ascent")) mTabHost.setCurrentTabByTag("descent");
323 case AltosLib.ao_flight_landed:
324 if (currentTab.equals("descent")) mTabHost.setCurrentTabByTag("landed");
326 case AltosLib.ao_flight_stateless:
327 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("descent");
333 if (location != null && state.gps != null && state.gps.locked) {
335 if (location.hasAltitude())
336 altitude = location.getAltitude();
337 from_receiver = new AltosGreatCircle(location.getLatitude(),
338 location.getLongitude(),
345 if (saved_state == null || !same_string(saved_state.callsign, state.callsign)) {
346 mCallsignView.setText(state.callsign);
348 if (saved_state == null || state.serial != saved_state.serial) {
349 mSerialView.setText(String.format("%d", state.serial));
351 if (saved_state == null || state.flight != saved_state.flight) {
352 if (state.flight == AltosLib.MISSING)
353 mFlightView.setText("");
355 mFlightView.setText(String.format("%d", state.flight));
357 if (saved_state == null || state.state != saved_state.state) {
358 if (state.state == AltosLib.ao_flight_stateless) {
359 mStateLayout.setVisibility(View.GONE);
361 mStateView.setText(state.state_name());
362 mStateLayout.setVisibility(View.VISIBLE);
365 if (saved_state == null || state.rssi != saved_state.rssi) {
366 mRSSIView.setText(String.format("%d", state.rssi));
370 for (AltosDroidTab mTab : mTabs)
371 mTab.update_ui(state, from_receiver, location, mTab == mTabsAdapter.currentItem());
373 if (state != null && mAltosVoice != null)
374 mAltosVoice.tell(state, from_receiver);
379 private void onTimerTick() {
381 mMessenger.send(Message.obtain(null, MSG_UPDATE_AGE));
382 } catch (RemoteException e) {
386 static String pos(double p, String pos, String neg) {
388 if (p == AltosLib.MISSING)
394 int deg = (int) Math.floor(p);
395 double min = (p - Math.floor(p)) * 60.0;
396 return String.format("%d°%9.4f\" %s", deg, min, h);
399 static String number(String format, double value) {
400 if (value == AltosLib.MISSING)
402 return String.format(format, value);
405 static String integer(String format, int value) {
406 if (value == AltosLib.MISSING)
408 return String.format(format, value);
411 private View create_tab_view(String label) {
412 LayoutInflater inflater = (LayoutInflater) this.getLayoutInflater();
413 View tab_view = inflater.inflate(R.layout.tab_layout, null);
414 TextView text_view = (TextView) tab_view.findViewById (R.id.tabLabel);
415 text_view.setText(label);
420 public void onCreate(Bundle savedInstanceState) {
421 super.onCreate(savedInstanceState);
422 AltosDebug.init(this);
423 AltosDebug.debug("+++ ON CREATE +++");
425 fm = getSupportFragmentManager();
427 // Set up the window layout
428 requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
429 setContentView(R.layout.altosdroid);
430 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
432 // Create the Tabs and ViewPager
433 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
436 mViewPager = (AltosViewPager)findViewById(R.id.pager);
437 mViewPager.setOffscreenPageLimit(4);
439 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
441 mTabsAdapter.addTab(mTabHost.newTabSpec("pad").setIndicator(create_tab_view("Pad")), TabPad.class, null);
442 mTabsAdapter.addTab(mTabHost.newTabSpec("ascent").setIndicator(create_tab_view("Ascent")), TabAscent.class, null);
443 mTabsAdapter.addTab(mTabHost.newTabSpec("descent").setIndicator(create_tab_view("Descent")), TabDescent.class, null);
444 mTabsAdapter.addTab(mTabHost.newTabSpec("landed").setIndicator(create_tab_view("Landed")), TabLanded.class, null);
445 mTabsAdapter.addTab(mTabHost.newTabSpec("map").setIndicator(create_tab_view("Map")), TabMap.class, null);
446 mTabsAdapter.addTab(mTabHost.newTabSpec("offmap").setIndicator(create_tab_view("OffMap")), TabMapOffline.class, null);
448 // Set up the custom title
449 mTitle = (TextView) findViewById(R.id.title_left_text);
450 mTitle.setText(R.string.app_name);
451 mTitle = (TextView) findViewById(R.id.title_right_text);
453 // Display the Version
454 mVersion = (TextView) findViewById(R.id.version);
455 mVersion.setText("Version: " + BuildInfo.version +
456 " Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
457 " (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
459 mCallsignView = (TextView) findViewById(R.id.callsign_value);
460 mRSSIView = (TextView) findViewById(R.id.rssi_value);
461 mSerialView = (TextView) findViewById(R.id.serial_value);
462 mFlightView = (TextView) findViewById(R.id.flight_value);
463 mStateLayout = (RelativeLayout) findViewById(R.id.state_container);
464 mStateView = (TextView) findViewById(R.id.state_value);
465 mAgeView = (TextView) findViewById(R.id.age_value);
468 private boolean ensureBluetooth() {
469 // Get local Bluetooth adapter
470 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
472 // If the adapter is null, then Bluetooth is not supported
473 if (mBluetoothAdapter == null) {
474 Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
478 if (!mBluetoothAdapter.isEnabled()) {
479 Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
480 startActivityForResult(enableIntent, AltosDroid.REQUEST_ENABLE_BT);
486 private boolean check_usb() {
487 UsbDevice device = AltosUsb.find_device(this, AltosLib.product_basestation);
489 if (device != null) {
490 Intent i = new Intent(this, AltosDroid.class);
491 PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent("hello world", null, this, AltosDroid.class), 0);
493 if (AltosUsb.request_permission(this, device, pi)) {
496 start_with_usb = true;
500 start_with_usb = false;
505 private void noticeIntent(Intent intent) {
507 /* Ok, this is pretty convenient.
509 * When a USB device is plugged in, and our 'hotplug'
510 * intent registration fires, we get an Intent with
513 * When we start up and see a usb device and request
514 * permission to access it, that queues a
515 * PendingIntent, which has the EXTRA_DEVICE added in,
516 * along with the EXTRA_PERMISSION_GRANTED field as
519 * So, in both cases, we get the device name using the
520 * same call. We check to see if access was granted,
521 * in which case we ignore the device field and do our
522 * usual startup thing.
525 UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
526 boolean granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, true);
528 AltosDebug.debug("intent %s device %s granted %s", intent, device, granted);
533 if (device != null) {
534 AltosDebug.debug("intent has usb device " + device.toString());
538 /* 'granted' is only false if this intent came
539 * from the request_permission call and
540 * permission was denied. In which case, we
541 * don't want to loop forever...
544 AltosDebug.debug("check for a USB device at startup");
548 AltosDebug.debug("Starting by looking for bluetooth devices");
549 if (ensureBluetooth())
556 public void onStart() {
558 AltosDebug.debug("++ ON START ++");
560 noticeIntent(getIntent());
562 // Start Telemetry Service
563 String action = start_with_usb ? ACTION_USB : ACTION_BLUETOOTH;
565 startService(new Intent(action, null, AltosDroid.this, TelemetryService.class));
569 if (mAltosVoice == null)
570 mAltosVoice = new AltosVoice(this);
575 public void onNewIntent(Intent intent) {
576 super.onNewIntent(intent);
577 AltosDebug.debug("onNewIntent");
578 noticeIntent(intent);
582 public void onResume() {
584 AltosDebug.debug("+ ON RESUME +");
588 public void onPause() {
590 AltosDebug.debug("- ON PAUSE -");
594 public void onStop() {
596 AltosDebug.debug("-- ON STOP --");
599 if (mAltosVoice != null) {
606 public void onDestroy() {
608 AltosDebug.debug("--- ON DESTROY ---");
610 if (mAltosVoice != null) mAltosVoice.stop();
614 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
615 AltosDebug.debug("onActivityResult " + resultCode);
616 switch (requestCode) {
617 case REQUEST_CONNECT_DEVICE:
618 // When DeviceListActivity returns with a device to connect to
619 if (resultCode == Activity.RESULT_OK) {
623 case REQUEST_ENABLE_BT:
624 // When the request to enable Bluetooth returns
625 if (resultCode == Activity.RESULT_OK) {
626 // Bluetooth is now enabled, so set up a chat session
629 // User did not enable Bluetooth or an error occured
630 AltosDebug.error("BT not enabled");
631 stopService(new Intent(AltosDroid.this, TelemetryService.class));
632 Toast.makeText(this, R.string.bt_not_enabled, Toast.LENGTH_SHORT).show();
636 case REQUEST_MAP_TYPE:
637 if (resultCode == Activity.RESULT_OK)
643 private void connectUsb(UsbDevice device) {
644 if (mService == null)
645 pending_usb_device = device;
647 // Attempt to connect to the device
649 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, device));
650 AltosDebug.debug("Sent OPEN_USB message");
651 } catch (RemoteException e) {
652 AltosDebug.debug("connect device message failed");
657 private void connectDevice(Intent data) {
658 // Attempt to connect to the device
660 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
661 String name = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_NAME);
663 AltosDebug.debug("Connecting to " + address + " " + name);
664 DeviceAddress a = new DeviceAddress(address, name);
665 mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, a));
666 AltosDebug.debug("Sent connecting message");
667 } catch (RemoteException e) {
668 AltosDebug.debug("connect device message failed");
672 private void disconnectDevice() {
674 mService.send(Message.obtain(null, TelemetryService.MSG_DISCONNECT, null));
675 } catch (RemoteException e) {
679 private void set_map_type(Intent data) {
680 int mode = data.getIntExtra(MapTypeActivity.EXTRA_MAP_TYPE, -1);
682 AltosDebug.debug("intent set_map_type %d\n", mode);
684 for (AltosDroidTab mTab : mTabs)
685 mTab.set_map_type(mode);
690 public boolean onCreateOptionsMenu(Menu menu) {
691 MenuInflater inflater = getMenuInflater();
692 inflater.inflate(R.menu.option_menu, menu);
696 void setFrequency(double freq) {
698 mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
699 } catch (RemoteException e) {
703 void setFrequency(String freq) {
705 setFrequency (AltosParse.parse_double_net(freq.substring(11, 17)));
706 } catch (ParseException e) {
710 void setBaud(int baud) {
712 mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD, baud));
713 } catch (RemoteException e) {
717 void setBaud(String baud) {
719 int value = Integer.parseInt(baud);
720 int rate = AltosLib.ao_telemetry_rate_38400;
723 rate = AltosLib.ao_telemetry_rate_2400;
726 rate = AltosLib.ao_telemetry_rate_9600;
729 rate = AltosLib.ao_telemetry_rate_38400;
733 } catch (NumberFormatException e) {
738 public boolean onOptionsItemSelected(MenuItem item) {
739 Intent serverIntent = null;
740 switch (item.getItemId()) {
741 case R.id.connect_scan:
742 if (ensureBluetooth()) {
743 // Launch the DeviceListActivity to see devices and do scan
744 serverIntent = new Intent(this, DeviceListActivity.class);
745 startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
748 case R.id.disconnect:
749 /* Disconnect the device
754 AltosDebug.debug("R.id.quit");
758 case R.id.select_freq:
759 // Set the TBT radio frequency
761 final String[] frequencies = {
762 "Channel 0 (434.550MHz)",
763 "Channel 1 (434.650MHz)",
764 "Channel 2 (434.750MHz)",
765 "Channel 3 (434.850MHz)",
766 "Channel 4 (434.950MHz)",
767 "Channel 5 (435.050MHz)",
768 "Channel 6 (435.150MHz)",
769 "Channel 7 (435.250MHz)",
770 "Channel 8 (435.350MHz)",
771 "Channel 9 (435.450MHz)"
774 AlertDialog.Builder builder_freq = new AlertDialog.Builder(this);
775 builder_freq.setTitle("Pick a frequency");
776 builder_freq.setItems(frequencies,
777 new DialogInterface.OnClickListener() {
778 public void onClick(DialogInterface dialog, int item) {
779 setFrequency(frequencies[item]);
782 AlertDialog alert_freq = builder_freq.create();
785 case R.id.select_rate:
786 // Set the TBT baud rate
788 final String[] rates = {
794 AlertDialog.Builder builder_rate = new AlertDialog.Builder(this);
795 builder_rate.setTitle("Pick a baud rate");
796 builder_rate.setItems(rates,
797 new DialogInterface.OnClickListener() {
798 public void onClick(DialogInterface dialog, int item) {
799 setBaud(rates[item]);
802 AlertDialog alert_rate = builder_rate.create();
805 case R.id.change_units:
806 boolean imperial = AltosPreferences.imperial_units();
807 AltosPreferences.set_imperial_units(!imperial);
809 case R.id.preload_maps:
810 serverIntent = new Intent(this, PreloadMapActivity.class);
811 startActivityForResult(serverIntent, REQUEST_PRELOAD_MAPS);
814 serverIntent = new Intent(this, MapTypeActivity.class);
815 startActivityForResult(serverIntent, REQUEST_MAP_TYPE);