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.content.res.Resources;
41 import android.support.v4.app.FragmentActivity;
42 import android.support.v4.app.FragmentManager;
43 import android.util.DisplayMetrics;
44 import android.util.Log;
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_6.*;
61 public class AltosDroid extends FragmentActivity implements AltosUnitsListener {
63 static final String TAG = "AltosDroid";
64 static final boolean D = true;
66 // Actions sent to the telemetry server at startup time
68 public static final String ACTION_BLUETOOTH = "org.altusmetrum.AltosDroid.BLUETOOTH";
69 public static final String ACTION_USB = "org.altusmetrum.AltosDroid.USB";
71 // Message types received by our Handler
73 public static final int MSG_STATE = 1;
74 public static final int MSG_UPDATE_AGE = 2;
76 // Intent request codes
77 public static final int REQUEST_CONNECT_DEVICE = 1;
78 public static final int REQUEST_ENABLE_BT = 2;
80 public static FragmentManager fm;
82 private BluetoothAdapter mBluetoothAdapter = null;
85 private TextView mTitle;
87 // Flight state values
88 private TextView mCallsignView;
89 private TextView mRSSIView;
90 private TextView mSerialView;
91 private TextView mFlightView;
92 private RelativeLayout mStateLayout;
93 private TextView mStateView;
94 private TextView mAgeView;
96 // field to display the version at the bottom of the screen
97 private TextView mVersion;
99 private double frequency;
100 private int telemetry_rate;
104 AltosViewPager mViewPager;
105 TabsAdapter mTabsAdapter;
106 ArrayList<AltosDroidTab> mTabs = new ArrayList<AltosDroidTab>();
109 // Timer and Saved flight state for Age calculation
111 AltosState saved_state;
113 UsbDevice pending_usb_device;
114 boolean start_with_usb;
117 private boolean mIsBound = false;
118 private Messenger mService = null;
119 final Messenger mMessenger = new Messenger(new IncomingHandler(this));
122 private AltosVoice mAltosVoice = null;
124 // The Handler that gets information back from the Telemetry Service
125 static class IncomingHandler extends Handler {
126 private final WeakReference<AltosDroid> mAltosDroid;
127 IncomingHandler(AltosDroid ad) { mAltosDroid = new WeakReference<AltosDroid>(ad); }
130 public void handleMessage(Message msg) {
131 AltosDroid ad = mAltosDroid.get();
135 if(D) Log.d(TAG, "MSG_STATE");
136 TelemetryState telemetry_state = (TelemetryState) msg.obj;
137 if (telemetry_state == null) {
138 Log.d(TAG, "telemetry_state null!");
142 ad.update_state(telemetry_state);
145 if(D) Log.d(TAG, "MSG_UPDATE_AGE");
153 private ServiceConnection mConnection = new ServiceConnection() {
154 public void onServiceConnected(ComponentName className, IBinder service) {
155 mService = new Messenger(service);
157 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
158 msg.replyTo = mMessenger;
160 } catch (RemoteException e) {
161 // In this case the service has crashed before we could even do anything with it
163 if (pending_usb_device != null) {
165 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, pending_usb_device));
166 pending_usb_device = null;
167 } catch (RemoteException e) {
172 public void onServiceDisconnected(ComponentName className) {
173 // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
178 void doBindService() {
179 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
183 void doUnbindService() {
185 // If we have received the service, and hence registered with it, then now is the time to unregister.
186 if (mService != null) {
188 Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
189 msg.replyTo = mMessenger;
191 } catch (RemoteException e) {
192 // There is nothing special we need to do if the service has crashed.
195 // Detach our existing connection.
196 unbindService(mConnection);
201 public void registerTab(AltosDroidTab mTab) {
205 public void unregisterTab(AltosDroidTab mTab) {
209 public void units_changed(boolean imperial_units) {
210 for (AltosDroidTab mTab : mTabs)
211 mTab.units_changed(imperial_units);
214 void update_title(TelemetryState telemetry_state) {
215 switch (telemetry_state.connect) {
216 case TelemetryState.CONNECT_CONNECTED:
217 if (telemetry_state.config != null) {
218 String str = String.format("S/N %d %6.3f MHz", telemetry_state.config.serial,
219 telemetry_state.frequency);
220 if (telemetry_state.telemetry_rate != AltosLib.ao_telemetry_rate_38400)
221 str = str.concat(String.format(" %d bps",
222 AltosLib.ao_telemetry_rate_values[telemetry_state.telemetry_rate]));
225 mTitle.setText(R.string.title_connected_to);
228 case TelemetryState.CONNECT_CONNECTING:
229 if (telemetry_state.address != null)
230 mTitle.setText(String.format("Connecting to %s...", telemetry_state.address.name));
232 mTitle.setText("Connecting to something...");
234 case TelemetryState.CONNECT_DISCONNECTED:
235 case TelemetryState.CONNECT_NONE:
236 mTitle.setText(R.string.title_not_connected);
244 timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 1000L, 1000L);
256 boolean registered_units_listener;
258 void update_state(TelemetryState telemetry_state) {
260 if (!registered_units_listener) {
261 registered_units_listener = true;
262 AltosPreferences.register_units_listener(this);
265 update_title(telemetry_state);
266 update_ui(telemetry_state.state, telemetry_state.location);
267 if (telemetry_state.connect == TelemetryState.CONNECT_CONNECTED)
271 boolean same_string(String a, String b) {
284 if (saved_state != null)
285 mAgeView.setText(String.format("%d", (System.currentTimeMillis() - saved_state.received_time + 500) / 1000));
288 void update_ui(AltosState state, Location location) {
290 int prev_state = AltosLib.ao_flight_invalid;
292 AltosGreatCircle from_receiver = null;
294 if (saved_state != null)
295 prev_state = saved_state.state;
298 if (state.state == AltosLib.ao_flight_stateless) {
299 boolean prev_locked = false;
300 boolean locked = false;
302 if(state.gps != null)
303 locked = state.gps.locked;
304 if (saved_state != null && saved_state.gps != null)
305 prev_locked = saved_state.gps.locked;
306 if (prev_locked != locked) {
307 String currentTab = mTabHost.getCurrentTabTag();
309 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("descent");
311 if (currentTab.equals("descent")) mTabHost.setCurrentTabByTag("pad");
315 if (prev_state != state.state) {
316 String currentTab = mTabHost.getCurrentTabTag();
317 switch (state.state) {
318 case AltosLib.ao_flight_boost:
319 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("ascent");
321 case AltosLib.ao_flight_drogue:
322 if (currentTab.equals("ascent")) mTabHost.setCurrentTabByTag("descent");
324 case AltosLib.ao_flight_landed:
325 if (currentTab.equals("descent")) mTabHost.setCurrentTabByTag("landed");
327 case AltosLib.ao_flight_stateless:
328 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("descent");
334 if (location != null && state.gps != null && state.gps.locked) {
336 if (location.hasAltitude())
337 altitude = location.getAltitude();
338 from_receiver = new AltosGreatCircle(location.getLatitude(),
339 location.getLongitude(),
346 if (saved_state == null || !same_string(saved_state.callsign, state.callsign)) {
347 mCallsignView.setText(state.callsign);
349 if (saved_state == null || state.serial != saved_state.serial) {
350 mSerialView.setText(String.format("%d", state.serial));
352 if (saved_state == null || state.flight != saved_state.flight) {
353 if (state.flight == AltosLib.MISSING)
354 mFlightView.setText("");
356 mFlightView.setText(String.format("%d", state.flight));
358 if (saved_state == null || state.state != saved_state.state) {
359 if (state.state == AltosLib.ao_flight_stateless) {
360 mStateLayout.setVisibility(View.GONE);
362 mStateView.setText(state.state_name());
363 mStateLayout.setVisibility(View.VISIBLE);
366 if (saved_state == null || state.rssi != saved_state.rssi) {
367 mRSSIView.setText(String.format("%d", state.rssi));
371 for (AltosDroidTab mTab : mTabs)
372 mTab.update_ui(state, from_receiver, location, mTab == mTabsAdapter.currentItem());
374 if (state != null && mAltosVoice != null)
375 mAltosVoice.tell(state, from_receiver);
380 private void onTimerTick() {
382 mMessenger.send(Message.obtain(null, MSG_UPDATE_AGE));
383 } catch (RemoteException e) {
387 static String pos(double p, String pos, String neg) {
389 if (p == AltosLib.MISSING)
395 int deg = (int) Math.floor(p);
396 double min = (p - Math.floor(p)) * 60.0;
397 return String.format("%d°%9.4f\" %s", deg, min, h);
400 static String number(String format, double value) {
401 if (value == AltosLib.MISSING)
403 return String.format(format, value);
406 static String integer(String format, int value) {
407 if (value == AltosLib.MISSING)
409 return String.format(format, value);
412 private View create_tab_view(String label) {
413 LayoutInflater inflater = (LayoutInflater) this.getLayoutInflater();
414 View tab_view = inflater.inflate(R.layout.tab_layout, null);
415 TextView text_view = (TextView) tab_view.findViewById (R.id.tabLabel);
416 text_view.setText(label);
421 public void onCreate(Bundle savedInstanceState) {
422 super.onCreate(savedInstanceState);
423 if(D) Log.e(TAG, "+++ 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);
447 // Set up the custom title
448 mTitle = (TextView) findViewById(R.id.title_left_text);
449 mTitle.setText(R.string.app_name);
450 mTitle = (TextView) findViewById(R.id.title_right_text);
452 // Display the Version
453 mVersion = (TextView) findViewById(R.id.version);
454 mVersion.setText("Version: " + BuildInfo.version +
455 " Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
456 " (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
458 mCallsignView = (TextView) findViewById(R.id.callsign_value);
459 mRSSIView = (TextView) findViewById(R.id.rssi_value);
460 mSerialView = (TextView) findViewById(R.id.serial_value);
461 mFlightView = (TextView) findViewById(R.id.flight_value);
462 mStateLayout = (RelativeLayout) findViewById(R.id.state_container);
463 mStateView = (TextView) findViewById(R.id.state_value);
464 mAgeView = (TextView) findViewById(R.id.age_value);
467 private boolean ensureBluetooth() {
468 // Get local Bluetooth adapter
469 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
471 // If the adapter is null, then Bluetooth is not supported
472 if (mBluetoothAdapter == null) {
473 Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
477 if (!mBluetoothAdapter.isEnabled()) {
478 Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
479 startActivityForResult(enableIntent, AltosDroid.REQUEST_ENABLE_BT);
485 private boolean check_usb() {
486 UsbDevice device = AltosUsb.find_device(this, AltosLib.product_basestation);
488 if (device != null) {
489 Intent i = new Intent(this, AltosDroid.class);
490 PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent("hello world", null, this, AltosDroid.class), 0);
492 if (AltosUsb.request_permission(this, device, pi)) {
495 start_with_usb = true;
499 start_with_usb = false;
504 private void noticeIntent(Intent intent) {
506 /* Ok, this is pretty convenient.
508 * When a USB device is plugged in, and our 'hotplug'
509 * intent registration fires, we get an Intent with
512 * When we start up and see a usb device and request
513 * permission to access it, that queues a
514 * PendingIntent, which has the EXTRA_DEVICE added in,
515 * along with the EXTRA_PERMISSION_GRANTED field as
518 * So, in both cases, we get the device name using the
519 * same call. We check to see if access was granted,
520 * in which case we ignore the device field and do our
521 * usual startup thing.
524 UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
525 boolean granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, true);
527 if (D) Log.e(TAG, "intent " + intent + " device " + device + " granted " + granted);
532 if (device != null) {
533 if (D) Log.d(TAG, "intent has usb device " + device.toString());
537 /* 'granted' is only false if this intent came
538 * from the request_permission call and
539 * permission was denied. In which case, we
540 * don't want to loop forever...
543 if (D) Log.d(TAG, "check for a USB device at startup");
547 if (D) Log.d(TAG, "Starting by looking for bluetooth devices");
548 if (ensureBluetooth())
555 public void onStart() {
557 if(D) Log.e(TAG, "++ ON START ++");
559 noticeIntent(getIntent());
561 // Start Telemetry Service
562 String action = start_with_usb ? ACTION_USB : ACTION_BLUETOOTH;
564 startService(new Intent(action, null, AltosDroid.this, TelemetryService.class));
568 if (mAltosVoice == null)
569 mAltosVoice = new AltosVoice(this);
574 public void onNewIntent(Intent intent) {
575 super.onNewIntent(intent);
576 if(D) Log.d(TAG, "onNewIntent");
577 noticeIntent(intent);
581 public void onResume() {
583 if(D) Log.e(TAG, "+ ON RESUME +");
587 public void onPause() {
589 if(D) Log.e(TAG, "- ON PAUSE -");
593 public void onStop() {
595 if(D) Log.e(TAG, "-- ON STOP --");
598 if (mAltosVoice != null) {
605 public void onDestroy() {
607 if(D) Log.e(TAG, "--- ON DESTROY ---");
609 if (mAltosVoice != null) mAltosVoice.stop();
613 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
614 if(D) Log.d(TAG, "onActivityResult " + resultCode);
615 switch (requestCode) {
616 case REQUEST_CONNECT_DEVICE:
617 // When DeviceListActivity returns with a device to connect to
618 if (resultCode == Activity.RESULT_OK) {
622 case REQUEST_ENABLE_BT:
623 // When the request to enable Bluetooth returns
624 if (resultCode == Activity.RESULT_OK) {
625 // Bluetooth is now enabled, so set up a chat session
628 // User did not enable Bluetooth or an error occured
629 Log.e(TAG, "BT not enabled");
630 stopService(new Intent(AltosDroid.this, TelemetryService.class));
631 Toast.makeText(this, R.string.bt_not_enabled, Toast.LENGTH_SHORT).show();
638 private void connectUsb(UsbDevice device) {
639 if (mService == null)
640 pending_usb_device = device;
642 // Attempt to connect to the device
644 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, device));
645 if (D) Log.d(TAG, "Sent OPEN_USB message");
646 } catch (RemoteException e) {
647 if (D) Log.e(TAG, "connect device message failed");
652 private void connectDevice(Intent data) {
653 // Attempt to connect to the device
655 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
656 String name = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_NAME);
658 if (D) Log.d(TAG, "Connecting to " + address + " " + name);
659 DeviceAddress a = new DeviceAddress(address, name);
660 mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, a));
661 if (D) Log.d(TAG, "Sent connecting message");
662 } catch (RemoteException e) {
663 if (D) Log.e(TAG, "connect device message failed");
667 private void disconnectDevice() {
669 mService.send(Message.obtain(null, TelemetryService.MSG_DISCONNECT, null));
670 } catch (RemoteException e) {
675 public boolean onCreateOptionsMenu(Menu menu) {
676 MenuInflater inflater = getMenuInflater();
677 inflater.inflate(R.menu.option_menu, menu);
681 void setFrequency(double freq) {
683 mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
684 } catch (RemoteException e) {
688 void setFrequency(String freq) {
690 setFrequency (Double.parseDouble(freq.substring(11, 17)));
691 } catch (NumberFormatException e) {
695 void setBaud(int baud) {
697 mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD, baud));
698 } catch (RemoteException e) {
702 void setBaud(String baud) {
704 int value = Integer.parseInt(baud);
705 int rate = AltosLib.ao_telemetry_rate_38400;
708 rate = AltosLib.ao_telemetry_rate_2400;
711 rate = AltosLib.ao_telemetry_rate_9600;
714 rate = AltosLib.ao_telemetry_rate_38400;
718 } catch (NumberFormatException e) {
723 public boolean onOptionsItemSelected(MenuItem item) {
724 Intent serverIntent = null;
725 switch (item.getItemId()) {
726 case R.id.connect_scan:
727 if (ensureBluetooth()) {
728 // Launch the DeviceListActivity to see devices and do scan
729 serverIntent = new Intent(this, DeviceListActivity.class);
730 startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
733 case R.id.disconnect:
734 /* Disconnect the device
739 Log.d(TAG, "R.id.quit");
743 case R.id.select_freq:
744 // Set the TBT radio frequency
746 final String[] frequencies = {
747 "Channel 0 (434.550MHz)",
748 "Channel 1 (434.650MHz)",
749 "Channel 2 (434.750MHz)",
750 "Channel 3 (434.850MHz)",
751 "Channel 4 (434.950MHz)",
752 "Channel 5 (435.050MHz)",
753 "Channel 6 (435.150MHz)",
754 "Channel 7 (435.250MHz)",
755 "Channel 8 (435.350MHz)",
756 "Channel 9 (435.450MHz)"
759 AlertDialog.Builder builder_freq = new AlertDialog.Builder(this);
760 builder_freq.setTitle("Pick a frequency");
761 builder_freq.setItems(frequencies,
762 new DialogInterface.OnClickListener() {
763 public void onClick(DialogInterface dialog, int item) {
764 setFrequency(frequencies[item]);
767 AlertDialog alert_freq = builder_freq.create();
770 case R.id.select_rate:
771 // Set the TBT baud rate
773 final String[] rates = {
779 AlertDialog.Builder builder_rate = new AlertDialog.Builder(this);
780 builder_rate.setTitle("Pick a baud rate");
781 builder_rate.setItems(rates,
782 new DialogInterface.OnClickListener() {
783 public void onClick(DialogInterface dialog, int item) {
784 setBaud(rates[item]);
787 AlertDialog alert_rate = builder_rate.create();
790 case R.id.change_units:
791 boolean imperial = AltosPreferences.imperial_units();
792 AltosPreferences.set_imperial_units(!imperial);