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;
25 import android.app.Activity;
26 import android.app.PendingIntent;
27 import android.bluetooth.BluetoothAdapter;
28 import android.bluetooth.BluetoothDevice;
29 import android.content.Intent;
30 import android.content.Context;
31 import android.content.ComponentName;
32 import android.content.ServiceConnection;
33 import android.content.DialogInterface;
34 import android.os.IBinder;
35 import android.os.Bundle;
36 import android.os.Handler;
37 import android.os.Message;
38 import android.os.Messenger;
39 import android.os.RemoteException;
40 import android.support.v4.app.FragmentActivity;
41 import android.support.v4.app.FragmentManager;
42 import android.util.DisplayMetrics;
43 import android.util.Log;
44 import android.view.Menu;
45 import android.view.MenuInflater;
46 import android.view.MenuItem;
47 import android.view.Window;
48 import android.view.View;
49 import android.widget.TabHost;
50 import android.widget.TextView;
51 import android.widget.RelativeLayout;
52 import android.widget.Toast;
53 import android.app.AlertDialog;
54 import android.location.Location;
55 import android.hardware.usb.*;
57 import org.altusmetrum.altoslib_6.*;
59 public class AltosDroid extends FragmentActivity implements AltosUnitsListener {
61 static final String TAG = "AltosDroid";
62 static final boolean D = true;
64 // Actions sent to the telemetry server at startup time
66 public static final String ACTION_BLUETOOTH = "org.altusmetrum.AltosDroid.BLUETOOTH";
67 public static final String ACTION_USB = "org.altusmetrum.AltosDroid.USB";
69 // Message types received by our Handler
71 public static final int MSG_STATE = 1;
72 public static final int MSG_UPDATE_AGE = 2;
74 // Intent request codes
75 public static final int REQUEST_CONNECT_DEVICE = 1;
76 public static final int REQUEST_ENABLE_BT = 2;
78 public static FragmentManager fm;
80 private BluetoothAdapter mBluetoothAdapter = null;
83 private TextView mTitle;
85 // Flight state values
86 private TextView mCallsignView;
87 private TextView mRSSIView;
88 private TextView mSerialView;
89 private TextView mFlightView;
90 private RelativeLayout mStateLayout;
91 private TextView mStateView;
92 private TextView mAgeView;
94 // field to display the version at the bottom of the screen
95 private TextView mVersion;
97 private double frequency;
98 private int telemetry_rate;
102 AltosViewPager mViewPager;
103 TabsAdapter mTabsAdapter;
104 ArrayList<AltosDroidTab> mTabs = new ArrayList<AltosDroidTab>();
107 // Timer and Saved flight state for Age calculation
109 AltosState saved_state;
111 UsbDevice pending_usb_device;
112 boolean start_with_usb;
115 private boolean mIsBound = false;
116 private Messenger mService = null;
117 final Messenger mMessenger = new Messenger(new IncomingHandler(this));
120 private AltosVoice mAltosVoice = null;
122 // The Handler that gets information back from the Telemetry Service
123 static class IncomingHandler extends Handler {
124 private final WeakReference<AltosDroid> mAltosDroid;
125 IncomingHandler(AltosDroid ad) { mAltosDroid = new WeakReference<AltosDroid>(ad); }
128 public void handleMessage(Message msg) {
129 AltosDroid ad = mAltosDroid.get();
133 if(D) Log.d(TAG, "MSG_STATE");
134 TelemetryState telemetry_state = (TelemetryState) msg.obj;
135 if (telemetry_state == null) {
136 Log.d(TAG, "telemetry_state null!");
140 ad.update_state(telemetry_state);
143 if(D) Log.d(TAG, "MSG_UPDATE_AGE");
151 private ServiceConnection mConnection = new ServiceConnection() {
152 public void onServiceConnected(ComponentName className, IBinder service) {
153 mService = new Messenger(service);
155 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
156 msg.replyTo = mMessenger;
158 } catch (RemoteException e) {
159 // In this case the service has crashed before we could even do anything with it
161 if (pending_usb_device != null) {
163 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, pending_usb_device));
164 pending_usb_device = null;
165 } catch (RemoteException e) {
170 public void onServiceDisconnected(ComponentName className) {
171 // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
176 void doBindService() {
177 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
181 void doUnbindService() {
183 // If we have received the service, and hence registered with it, then now is the time to unregister.
184 if (mService != null) {
186 Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
187 msg.replyTo = mMessenger;
189 } catch (RemoteException e) {
190 // There is nothing special we need to do if the service has crashed.
193 // Detach our existing connection.
194 unbindService(mConnection);
199 public void registerTab(AltosDroidTab mTab) {
203 public void unregisterTab(AltosDroidTab mTab) {
207 public void units_changed(boolean imperial_units) {
208 for (AltosDroidTab mTab : mTabs)
209 mTab.units_changed(imperial_units);
212 void update_title(TelemetryState telemetry_state) {
213 switch (telemetry_state.connect) {
214 case TelemetryState.CONNECT_CONNECTED:
215 if (telemetry_state.config != null) {
216 String str = String.format("S/N %d %6.3f MHz", telemetry_state.config.serial,
217 telemetry_state.frequency);
218 if (telemetry_state.telemetry_rate != AltosLib.ao_telemetry_rate_38400)
219 str = str.concat(String.format(" %d bps",
220 AltosLib.ao_telemetry_rate_values[telemetry_state.telemetry_rate]));
223 mTitle.setText(R.string.title_connected_to);
226 case TelemetryState.CONNECT_CONNECTING:
227 if (telemetry_state.address != null)
228 mTitle.setText(String.format("Connecting to %s...", telemetry_state.address.name));
230 mTitle.setText("Connecting to something...");
232 case TelemetryState.CONNECT_DISCONNECTED:
233 case TelemetryState.CONNECT_NONE:
234 mTitle.setText(R.string.title_not_connected);
242 timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 1000L, 1000L);
254 boolean registered_units_listener;
256 void update_state(TelemetryState telemetry_state) {
258 if (!registered_units_listener) {
259 registered_units_listener = true;
260 AltosPreferences.register_units_listener(this);
263 update_title(telemetry_state);
264 update_ui(telemetry_state.state, telemetry_state.location);
265 if (telemetry_state.connect == TelemetryState.CONNECT_CONNECTED)
269 boolean same_string(String a, String b) {
282 if (saved_state != null)
283 mAgeView.setText(String.format("%d", (System.currentTimeMillis() - saved_state.received_time + 500) / 1000));
286 void update_ui(AltosState state, Location location) {
288 int prev_state = AltosLib.ao_flight_invalid;
290 AltosGreatCircle from_receiver = null;
292 if (saved_state != null)
293 prev_state = saved_state.state;
296 if (state.state == AltosLib.ao_flight_stateless) {
297 boolean prev_locked = false;
298 boolean locked = false;
300 if(state.gps != null)
301 locked = state.gps.locked;
302 if (saved_state != null && saved_state.gps != null)
303 prev_locked = saved_state.gps.locked;
304 if (prev_locked != locked) {
305 String currentTab = mTabHost.getCurrentTabTag();
307 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("descent");
309 if (currentTab.equals("descent")) mTabHost.setCurrentTabByTag("pad");
313 if (prev_state != state.state) {
314 String currentTab = mTabHost.getCurrentTabTag();
315 switch (state.state) {
316 case AltosLib.ao_flight_boost:
317 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("ascent");
319 case AltosLib.ao_flight_drogue:
320 if (currentTab.equals("ascent")) mTabHost.setCurrentTabByTag("descent");
322 case AltosLib.ao_flight_landed:
323 if (currentTab.equals("descent")) mTabHost.setCurrentTabByTag("landed");
325 case AltosLib.ao_flight_stateless:
326 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("descent");
332 if (location != null && state.gps != null && state.gps.locked) {
334 if (location.hasAltitude())
335 altitude = location.getAltitude();
336 from_receiver = new AltosGreatCircle(location.getLatitude(),
337 location.getLongitude(),
344 if (saved_state == null || !same_string(saved_state.callsign, state.callsign)) {
345 mCallsignView.setText(state.callsign);
347 if (saved_state == null || state.serial != saved_state.serial) {
348 mSerialView.setText(String.format("%d", state.serial));
350 if (saved_state == null || state.flight != saved_state.flight) {
351 if (state.flight == AltosLib.MISSING)
352 mFlightView.setText("");
354 mFlightView.setText(String.format("%d", state.flight));
356 if (saved_state == null || state.state != saved_state.state) {
357 if (state.state == AltosLib.ao_flight_stateless) {
358 mStateLayout.setVisibility(View.GONE);
360 mStateView.setText(state.state_name());
361 mStateLayout.setVisibility(View.VISIBLE);
364 if (saved_state == null || state.rssi != saved_state.rssi) {
365 mRSSIView.setText(String.format("%d", state.rssi));
369 for (AltosDroidTab mTab : mTabs)
370 mTab.update_ui(state, from_receiver, location, mTab == mTabsAdapter.currentItem());
372 if (state != null && mAltosVoice != null)
373 mAltosVoice.tell(state, from_receiver);
378 private void onTimerTick() {
380 mMessenger.send(Message.obtain(null, MSG_UPDATE_AGE));
381 } catch (RemoteException e) {
385 static String pos(double p, String pos, String neg) {
387 if (p == AltosLib.MISSING)
393 int deg = (int) Math.floor(p);
394 double min = (p - Math.floor(p)) * 60.0;
395 return String.format("%d°%9.4f\" %s", deg, min, h);
398 static String number(String format, double value) {
399 if (value == AltosLib.MISSING)
401 return String.format(format, value);
404 static String integer(String format, int value) {
405 if (value == AltosLib.MISSING)
407 return String.format(format, value);
411 public void onCreate(Bundle savedInstanceState) {
412 super.onCreate(savedInstanceState);
413 if(D) Log.e(TAG, "+++ ON CREATE +++");
415 fm = getSupportFragmentManager();
417 // Set up the window layout
418 requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
419 setContentView(R.layout.altosdroid);
420 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
422 // Create the Tabs and ViewPager
423 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
426 mViewPager = (AltosViewPager)findViewById(R.id.pager);
427 mViewPager.setOffscreenPageLimit(4);
429 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
431 mTabsAdapter.addTab(mTabHost.newTabSpec("pad").setIndicator("Pad"), TabPad.class, null);
432 mTabsAdapter.addTab(mTabHost.newTabSpec("ascent").setIndicator("Ascent"), TabAscent.class, null);
433 mTabsAdapter.addTab(mTabHost.newTabSpec("descent").setIndicator("Descent"), TabDescent.class, null);
434 mTabsAdapter.addTab(mTabHost.newTabSpec("landed").setIndicator("Landed"), TabLanded.class, null);
435 mTabsAdapter.addTab(mTabHost.newTabSpec("map").setIndicator("Map"), TabMap.class, null);
438 // Scale the size of the Tab bar for different screen densities
439 // This probably won't be needed when we start supporting ICS+ tabs.
440 DisplayMetrics metrics = new DisplayMetrics();
441 getWindowManager().getDefaultDisplay().getMetrics(metrics);
442 int density = metrics.densityDpi;
444 if (density==DisplayMetrics.DENSITY_XHIGH)
446 else if (density==DisplayMetrics.DENSITY_HIGH)
448 else if (density==DisplayMetrics.DENSITY_MEDIUM)
450 else if (density==DisplayMetrics.DENSITY_LOW)
455 for (int i = 0; i < 5; i++)
456 mTabHost.getTabWidget().getChildAt(i).getLayoutParams().height = tabHeight;
458 // Set up the custom title
459 mTitle = (TextView) findViewById(R.id.title_left_text);
460 mTitle.setText(R.string.app_name);
461 mTitle = (TextView) findViewById(R.id.title_right_text);
463 // Display the Version
464 mVersion = (TextView) findViewById(R.id.version);
465 mVersion.setText("Version: " + BuildInfo.version +
466 " Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
467 " (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
469 mCallsignView = (TextView) findViewById(R.id.callsign_value);
470 mRSSIView = (TextView) findViewById(R.id.rssi_value);
471 mSerialView = (TextView) findViewById(R.id.serial_value);
472 mFlightView = (TextView) findViewById(R.id.flight_value);
473 mStateLayout = (RelativeLayout) findViewById(R.id.state_container);
474 mStateView = (TextView) findViewById(R.id.state_value);
475 mAgeView = (TextView) findViewById(R.id.age_value);
478 private boolean ensureBluetooth() {
479 // Get local Bluetooth adapter
480 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
482 // If the adapter is null, then Bluetooth is not supported
483 if (mBluetoothAdapter == null) {
484 Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
488 if (!mBluetoothAdapter.isEnabled()) {
489 Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
490 startActivityForResult(enableIntent, AltosDroid.REQUEST_ENABLE_BT);
496 private boolean check_usb() {
497 UsbDevice device = AltosUsb.find_device(this, AltosLib.product_basestation);
499 if (device != null) {
500 Intent i = new Intent(this, AltosDroid.class);
501 PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent("hello world", null, this, AltosDroid.class), 0);
503 if (AltosUsb.request_permission(this, device, pi)) {
506 start_with_usb = true;
510 start_with_usb = false;
515 private void noticeIntent(Intent intent) {
517 /* Ok, this is pretty convenient.
519 * When a USB device is plugged in, and our 'hotplug'
520 * intent registration fires, we get an Intent with
523 * When we start up and see a usb device and request
524 * permission to access it, that queues a
525 * PendingIntent, which has the EXTRA_DEVICE added in,
526 * along with the EXTRA_PERMISSION_GRANTED field as
529 * So, in both cases, we get the device name using the
530 * same call. We check to see if access was granted,
531 * in which case we ignore the device field and do our
532 * usual startup thing.
535 UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
536 boolean granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, true);
538 if (D) Log.e(TAG, "intent " + intent + " device " + device + " granted " + granted);
543 if (device != null) {
544 if (D) Log.d(TAG, "intent has usb device " + device.toString());
548 /* 'granted' is only false if this intent came
549 * from the request_permission call and
550 * permission was denied. In which case, we
551 * don't want to loop forever...
554 if (D) Log.d(TAG, "check for a USB device at startup");
558 if (D) Log.d(TAG, "Starting by looking for bluetooth devices");
559 if (ensureBluetooth())
566 public void onStart() {
568 if(D) Log.e(TAG, "++ ON START ++");
570 noticeIntent(getIntent());
572 // Start Telemetry Service
573 String action = start_with_usb ? ACTION_USB : ACTION_BLUETOOTH;
575 startService(new Intent(action, null, AltosDroid.this, TelemetryService.class));
579 if (mAltosVoice == null)
580 mAltosVoice = new AltosVoice(this);
585 public void onNewIntent(Intent intent) {
586 super.onNewIntent(intent);
587 if(D) Log.d(TAG, "onNewIntent");
588 noticeIntent(intent);
592 public void onResume() {
594 if(D) Log.e(TAG, "+ ON RESUME +");
598 public void onPause() {
600 if(D) Log.e(TAG, "- ON PAUSE -");
604 public void onStop() {
606 if(D) Log.e(TAG, "-- ON STOP --");
609 if (mAltosVoice != null) {
616 public void onDestroy() {
618 if(D) Log.e(TAG, "--- ON DESTROY ---");
620 if (mAltosVoice != null) mAltosVoice.stop();
624 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
625 if(D) Log.d(TAG, "onActivityResult " + resultCode);
626 switch (requestCode) {
627 case REQUEST_CONNECT_DEVICE:
628 // When DeviceListActivity returns with a device to connect to
629 if (resultCode == Activity.RESULT_OK) {
633 case REQUEST_ENABLE_BT:
634 // When the request to enable Bluetooth returns
635 if (resultCode == Activity.RESULT_OK) {
636 // Bluetooth is now enabled, so set up a chat session
639 // User did not enable Bluetooth or an error occured
640 Log.e(TAG, "BT not enabled");
641 stopService(new Intent(AltosDroid.this, TelemetryService.class));
642 Toast.makeText(this, R.string.bt_not_enabled, Toast.LENGTH_SHORT).show();
649 private void connectUsb(UsbDevice device) {
650 if (mService == null)
651 pending_usb_device = device;
653 // Attempt to connect to the device
655 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, device));
656 if (D) Log.d(TAG, "Sent OPEN_USB message");
657 } catch (RemoteException e) {
658 if (D) Log.e(TAG, "connect device message failed");
663 private void connectDevice(Intent data) {
664 // Attempt to connect to the device
666 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
667 String name = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_NAME);
669 if (D) Log.d(TAG, "Connecting to " + address + " " + name);
670 DeviceAddress a = new DeviceAddress(address, name);
671 mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, a));
672 if (D) Log.d(TAG, "Sent connecting message");
673 } catch (RemoteException e) {
674 if (D) Log.e(TAG, "connect device message failed");
678 private void disconnectDevice() {
680 mService.send(Message.obtain(null, TelemetryService.MSG_DISCONNECT, null));
681 } catch (RemoteException e) {
686 public boolean onCreateOptionsMenu(Menu menu) {
687 MenuInflater inflater = getMenuInflater();
688 inflater.inflate(R.menu.option_menu, menu);
692 void setFrequency(double freq) {
694 mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
695 } catch (RemoteException e) {
699 void setFrequency(String freq) {
701 setFrequency (Double.parseDouble(freq.substring(11, 17)));
702 } catch (NumberFormatException e) {
706 void setBaud(int baud) {
708 mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD, baud));
709 } catch (RemoteException e) {
713 void setBaud(String baud) {
715 int value = Integer.parseInt(baud);
716 int rate = AltosLib.ao_telemetry_rate_38400;
719 rate = AltosLib.ao_telemetry_rate_2400;
722 rate = AltosLib.ao_telemetry_rate_9600;
725 rate = AltosLib.ao_telemetry_rate_38400;
729 } catch (NumberFormatException e) {
734 public boolean onOptionsItemSelected(MenuItem item) {
735 Intent serverIntent = null;
736 switch (item.getItemId()) {
737 case R.id.connect_scan:
738 if (ensureBluetooth()) {
739 // Launch the DeviceListActivity to see devices and do scan
740 serverIntent = new Intent(this, DeviceListActivity.class);
741 startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
744 case R.id.disconnect:
745 /* Disconnect the device
750 Log.d(TAG, "R.id.quit");
754 case R.id.select_freq:
755 // Set the TBT radio frequency
757 final String[] frequencies = {
758 "Channel 0 (434.550MHz)",
759 "Channel 1 (434.650MHz)",
760 "Channel 2 (434.750MHz)",
761 "Channel 3 (434.850MHz)",
762 "Channel 4 (434.950MHz)",
763 "Channel 5 (435.050MHz)",
764 "Channel 6 (435.150MHz)",
765 "Channel 7 (435.250MHz)",
766 "Channel 8 (435.350MHz)",
767 "Channel 9 (435.450MHz)"
770 AlertDialog.Builder builder_freq = new AlertDialog.Builder(this);
771 builder_freq.setTitle("Pick a frequency");
772 builder_freq.setItems(frequencies,
773 new DialogInterface.OnClickListener() {
774 public void onClick(DialogInterface dialog, int item) {
775 setFrequency(frequencies[item]);
778 AlertDialog alert_freq = builder_freq.create();
781 case R.id.select_rate:
782 // Set the TBT baud rate
784 final String[] rates = {
790 AlertDialog.Builder builder_rate = new AlertDialog.Builder(this);
791 builder_rate.setTitle("Pick a baud rate");
792 builder_rate.setItems(rates,
793 new DialogInterface.OnClickListener() {
794 public void onClick(DialogInterface dialog, int item) {
795 setBaud(rates[item]);
798 AlertDialog alert_rate = builder_rate.create();
801 case R.id.change_units:
802 boolean imperial = AltosPreferences.imperial_units();
803 AltosPreferences.set_imperial_units(!imperial);