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;
77 public static FragmentManager fm;
79 private BluetoothAdapter mBluetoothAdapter = null;
82 private TextView mTitle;
84 // Flight state values
85 private TextView mCallsignView;
86 private TextView mRSSIView;
87 private TextView mSerialView;
88 private TextView mFlightView;
89 private RelativeLayout mStateLayout;
90 private TextView mStateView;
91 private TextView mAgeView;
93 // field to display the version at the bottom of the screen
94 private TextView mVersion;
96 private double frequency;
97 private int telemetry_rate;
101 AltosViewPager mViewPager;
102 TabsAdapter mTabsAdapter;
103 ArrayList<AltosDroidTab> mTabs = new ArrayList<AltosDroidTab>();
106 // Timer and Saved flight state for Age calculation
108 AltosState saved_state;
110 UsbDevice pending_usb_device;
111 boolean start_with_usb;
114 private boolean mIsBound = false;
115 private Messenger mService = null;
116 final Messenger mMessenger = new Messenger(new IncomingHandler(this));
119 private AltosVoice mAltosVoice = null;
121 // The Handler that gets information back from the Telemetry Service
122 static class IncomingHandler extends Handler {
123 private final WeakReference<AltosDroid> mAltosDroid;
124 IncomingHandler(AltosDroid ad) { mAltosDroid = new WeakReference<AltosDroid>(ad); }
127 public void handleMessage(Message msg) {
128 AltosDroid ad = mAltosDroid.get();
132 AltosDebug.debug("MSG_STATE");
133 TelemetryState telemetry_state = (TelemetryState) msg.obj;
134 if (telemetry_state == null) {
135 AltosDebug.debug("telemetry_state null!");
139 ad.update_state(telemetry_state);
142 AltosDebug.debug("MSG_UPDATE_AGE");
150 private ServiceConnection mConnection = new ServiceConnection() {
151 public void onServiceConnected(ComponentName className, IBinder service) {
152 mService = new Messenger(service);
154 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
155 msg.replyTo = mMessenger;
157 } catch (RemoteException e) {
158 // In this case the service has crashed before we could even do anything with it
160 if (pending_usb_device != null) {
162 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, pending_usb_device));
163 pending_usb_device = null;
164 } catch (RemoteException e) {
169 public void onServiceDisconnected(ComponentName className) {
170 // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
175 void doBindService() {
176 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
180 void doUnbindService() {
182 // If we have received the service, and hence registered with it, then now is the time to unregister.
183 if (mService != null) {
185 Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
186 msg.replyTo = mMessenger;
188 } catch (RemoteException e) {
189 // There is nothing special we need to do if the service has crashed.
192 // Detach our existing connection.
193 unbindService(mConnection);
198 public void registerTab(AltosDroidTab mTab) {
202 public void unregisterTab(AltosDroidTab mTab) {
206 public void units_changed(boolean imperial_units) {
207 for (AltosDroidTab mTab : mTabs)
208 mTab.units_changed(imperial_units);
211 void update_title(TelemetryState telemetry_state) {
212 switch (telemetry_state.connect) {
213 case TelemetryState.CONNECT_CONNECTED:
214 if (telemetry_state.config != null) {
215 String str = String.format("S/N %d %6.3f MHz", telemetry_state.config.serial,
216 telemetry_state.frequency);
217 if (telemetry_state.telemetry_rate != AltosLib.ao_telemetry_rate_38400)
218 str = str.concat(String.format(" %d bps",
219 AltosLib.ao_telemetry_rate_values[telemetry_state.telemetry_rate]));
222 mTitle.setText(R.string.title_connected_to);
225 case TelemetryState.CONNECT_CONNECTING:
226 if (telemetry_state.address != null)
227 mTitle.setText(String.format("Connecting to %s...", telemetry_state.address.name));
229 mTitle.setText("Connecting to something...");
231 case TelemetryState.CONNECT_DISCONNECTED:
232 case TelemetryState.CONNECT_NONE:
233 mTitle.setText(R.string.title_not_connected);
241 timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 1000L, 1000L);
253 boolean registered_units_listener;
255 void update_state(TelemetryState telemetry_state) {
257 if (!registered_units_listener) {
258 registered_units_listener = true;
259 AltosPreferences.register_units_listener(this);
262 update_title(telemetry_state);
263 update_ui(telemetry_state.state, telemetry_state.location);
264 if (telemetry_state.connect == TelemetryState.CONNECT_CONNECTED)
268 boolean same_string(String a, String b) {
281 if (saved_state != null)
282 mAgeView.setText(String.format("%d", (System.currentTimeMillis() - saved_state.received_time + 500) / 1000));
285 void update_ui(AltosState state, Location location) {
287 int prev_state = AltosLib.ao_flight_invalid;
289 AltosGreatCircle from_receiver = null;
291 if (saved_state != null)
292 prev_state = saved_state.state;
295 if (state.state == AltosLib.ao_flight_stateless) {
296 boolean prev_locked = false;
297 boolean locked = false;
299 if(state.gps != null)
300 locked = state.gps.locked;
301 if (saved_state != null && saved_state.gps != null)
302 prev_locked = saved_state.gps.locked;
303 if (prev_locked != locked) {
304 String currentTab = mTabHost.getCurrentTabTag();
306 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("descent");
308 if (currentTab.equals("descent")) mTabHost.setCurrentTabByTag("pad");
312 if (prev_state != state.state) {
313 String currentTab = mTabHost.getCurrentTabTag();
314 switch (state.state) {
315 case AltosLib.ao_flight_boost:
316 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("ascent");
318 case AltosLib.ao_flight_drogue:
319 if (currentTab.equals("ascent")) mTabHost.setCurrentTabByTag("descent");
321 case AltosLib.ao_flight_landed:
322 if (currentTab.equals("descent")) mTabHost.setCurrentTabByTag("landed");
324 case AltosLib.ao_flight_stateless:
325 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("descent");
331 if (location != null && state.gps != null && state.gps.locked) {
333 if (location.hasAltitude())
334 altitude = location.getAltitude();
335 from_receiver = new AltosGreatCircle(location.getLatitude(),
336 location.getLongitude(),
343 if (saved_state == null || !same_string(saved_state.callsign, state.callsign)) {
344 mCallsignView.setText(state.callsign);
346 if (saved_state == null || state.serial != saved_state.serial) {
347 mSerialView.setText(String.format("%d", state.serial));
349 if (saved_state == null || state.flight != saved_state.flight) {
350 if (state.flight == AltosLib.MISSING)
351 mFlightView.setText("");
353 mFlightView.setText(String.format("%d", state.flight));
355 if (saved_state == null || state.state != saved_state.state) {
356 if (state.state == AltosLib.ao_flight_stateless) {
357 mStateLayout.setVisibility(View.GONE);
359 mStateView.setText(state.state_name());
360 mStateLayout.setVisibility(View.VISIBLE);
363 if (saved_state == null || state.rssi != saved_state.rssi) {
364 mRSSIView.setText(String.format("%d", state.rssi));
368 for (AltosDroidTab mTab : mTabs)
369 mTab.update_ui(state, from_receiver, location, mTab == mTabsAdapter.currentItem());
371 if (state != null && mAltosVoice != null)
372 mAltosVoice.tell(state, from_receiver);
377 private void onTimerTick() {
379 mMessenger.send(Message.obtain(null, MSG_UPDATE_AGE));
380 } catch (RemoteException e) {
384 static String pos(double p, String pos, String neg) {
386 if (p == AltosLib.MISSING)
392 int deg = (int) Math.floor(p);
393 double min = (p - Math.floor(p)) * 60.0;
394 return String.format("%d°%9.4f\" %s", deg, min, h);
397 static String number(String format, double value) {
398 if (value == AltosLib.MISSING)
400 return String.format(format, value);
403 static String integer(String format, int value) {
404 if (value == AltosLib.MISSING)
406 return String.format(format, value);
409 private View create_tab_view(String label) {
410 LayoutInflater inflater = (LayoutInflater) this.getLayoutInflater();
411 View tab_view = inflater.inflate(R.layout.tab_layout, null);
412 TextView text_view = (TextView) tab_view.findViewById (R.id.tabLabel);
413 text_view.setText(label);
418 public void onCreate(Bundle savedInstanceState) {
419 super.onCreate(savedInstanceState);
420 AltosDebug.debug("+++ ON CREATE +++");
422 fm = getSupportFragmentManager();
424 // Set up the window layout
425 requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
426 setContentView(R.layout.altosdroid);
427 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
429 // Create the Tabs and ViewPager
430 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
433 mViewPager = (AltosViewPager)findViewById(R.id.pager);
434 mViewPager.setOffscreenPageLimit(4);
436 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
438 mTabsAdapter.addTab(mTabHost.newTabSpec("pad").setIndicator(create_tab_view("Pad")), TabPad.class, null);
439 mTabsAdapter.addTab(mTabHost.newTabSpec("ascent").setIndicator(create_tab_view("Ascent")), TabAscent.class, null);
440 mTabsAdapter.addTab(mTabHost.newTabSpec("descent").setIndicator(create_tab_view("Descent")), TabDescent.class, null);
441 mTabsAdapter.addTab(mTabHost.newTabSpec("landed").setIndicator(create_tab_view("Landed")), TabLanded.class, null);
442 mTabsAdapter.addTab(mTabHost.newTabSpec("map").setIndicator(create_tab_view("Map")), TabMap.class, null);
443 mTabsAdapter.addTab(mTabHost.newTabSpec("offmap").setIndicator(create_tab_view("OffMap")), TabMapOffline.class, null);
445 // Set up the custom title
446 mTitle = (TextView) findViewById(R.id.title_left_text);
447 mTitle.setText(R.string.app_name);
448 mTitle = (TextView) findViewById(R.id.title_right_text);
450 // Display the Version
451 mVersion = (TextView) findViewById(R.id.version);
452 mVersion.setText("Version: " + BuildInfo.version +
453 " Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
454 " (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
456 mCallsignView = (TextView) findViewById(R.id.callsign_value);
457 mRSSIView = (TextView) findViewById(R.id.rssi_value);
458 mSerialView = (TextView) findViewById(R.id.serial_value);
459 mFlightView = (TextView) findViewById(R.id.flight_value);
460 mStateLayout = (RelativeLayout) findViewById(R.id.state_container);
461 mStateView = (TextView) findViewById(R.id.state_value);
462 mAgeView = (TextView) findViewById(R.id.age_value);
465 private boolean ensureBluetooth() {
466 // Get local Bluetooth adapter
467 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
469 // If the adapter is null, then Bluetooth is not supported
470 if (mBluetoothAdapter == null) {
471 Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
475 if (!mBluetoothAdapter.isEnabled()) {
476 Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
477 startActivityForResult(enableIntent, AltosDroid.REQUEST_ENABLE_BT);
483 private boolean check_usb() {
484 UsbDevice device = AltosUsb.find_device(this, AltosLib.product_basestation);
486 if (device != null) {
487 Intent i = new Intent(this, AltosDroid.class);
488 PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent("hello world", null, this, AltosDroid.class), 0);
490 if (AltosUsb.request_permission(this, device, pi)) {
493 start_with_usb = true;
497 start_with_usb = false;
502 private void noticeIntent(Intent intent) {
504 /* Ok, this is pretty convenient.
506 * When a USB device is plugged in, and our 'hotplug'
507 * intent registration fires, we get an Intent with
510 * When we start up and see a usb device and request
511 * permission to access it, that queues a
512 * PendingIntent, which has the EXTRA_DEVICE added in,
513 * along with the EXTRA_PERMISSION_GRANTED field as
516 * So, in both cases, we get the device name using the
517 * same call. We check to see if access was granted,
518 * in which case we ignore the device field and do our
519 * usual startup thing.
522 UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
523 boolean granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, true);
525 AltosDebug.debug("intent %s device %s granted %s", intent, device, granted);
530 if (device != null) {
531 AltosDebug.debug("intent has usb device " + device.toString());
535 /* 'granted' is only false if this intent came
536 * from the request_permission call and
537 * permission was denied. In which case, we
538 * don't want to loop forever...
541 AltosDebug.debug("check for a USB device at startup");
545 AltosDebug.debug("Starting by looking for bluetooth devices");
546 if (ensureBluetooth())
553 public void onStart() {
555 AltosDebug.debug("++ ON START ++");
557 noticeIntent(getIntent());
559 // Start Telemetry Service
560 String action = start_with_usb ? ACTION_USB : ACTION_BLUETOOTH;
562 startService(new Intent(action, null, AltosDroid.this, TelemetryService.class));
566 if (mAltosVoice == null)
567 mAltosVoice = new AltosVoice(this);
572 public void onNewIntent(Intent intent) {
573 super.onNewIntent(intent);
574 AltosDebug.debug("onNewIntent");
575 noticeIntent(intent);
579 public void onResume() {
581 AltosDebug.debug("+ ON RESUME +");
585 public void onPause() {
587 AltosDebug.debug("- ON PAUSE -");
591 public void onStop() {
593 AltosDebug.debug("-- ON STOP --");
596 if (mAltosVoice != null) {
603 public void onDestroy() {
605 AltosDebug.debug("--- ON DESTROY ---");
607 if (mAltosVoice != null) mAltosVoice.stop();
611 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
612 AltosDebug.debug("onActivityResult " + resultCode);
613 switch (requestCode) {
614 case REQUEST_CONNECT_DEVICE:
615 // When DeviceListActivity returns with a device to connect to
616 if (resultCode == Activity.RESULT_OK) {
620 case REQUEST_ENABLE_BT:
621 // When the request to enable Bluetooth returns
622 if (resultCode == Activity.RESULT_OK) {
623 // Bluetooth is now enabled, so set up a chat session
626 // User did not enable Bluetooth or an error occured
627 AltosDebug.error("BT not enabled");
628 stopService(new Intent(AltosDroid.this, TelemetryService.class));
629 Toast.makeText(this, R.string.bt_not_enabled, Toast.LENGTH_SHORT).show();
636 private void connectUsb(UsbDevice device) {
637 if (mService == null)
638 pending_usb_device = device;
640 // Attempt to connect to the device
642 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, device));
643 AltosDebug.debug("Sent OPEN_USB message");
644 } catch (RemoteException e) {
645 AltosDebug.debug("connect device message failed");
650 private void connectDevice(Intent data) {
651 // Attempt to connect to the device
653 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
654 String name = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_NAME);
656 AltosDebug.debug("Connecting to " + address + " " + name);
657 DeviceAddress a = new DeviceAddress(address, name);
658 mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, a));
659 AltosDebug.debug("Sent connecting message");
660 } catch (RemoteException e) {
661 AltosDebug.debug("connect device message failed");
665 private void disconnectDevice() {
667 mService.send(Message.obtain(null, TelemetryService.MSG_DISCONNECT, null));
668 } catch (RemoteException e) {
673 public boolean onCreateOptionsMenu(Menu menu) {
674 MenuInflater inflater = getMenuInflater();
675 inflater.inflate(R.menu.option_menu, menu);
679 void setFrequency(double freq) {
681 mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
682 } catch (RemoteException e) {
686 void setFrequency(String freq) {
688 setFrequency (AltosParse.parse_double_net(freq.substring(11, 17)));
689 } catch (ParseException e) {
693 void setBaud(int baud) {
695 mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD, baud));
696 } catch (RemoteException e) {
700 void setBaud(String baud) {
702 int value = Integer.parseInt(baud);
703 int rate = AltosLib.ao_telemetry_rate_38400;
706 rate = AltosLib.ao_telemetry_rate_2400;
709 rate = AltosLib.ao_telemetry_rate_9600;
712 rate = AltosLib.ao_telemetry_rate_38400;
716 } catch (NumberFormatException e) {
721 public boolean onOptionsItemSelected(MenuItem item) {
722 Intent serverIntent = null;
723 switch (item.getItemId()) {
724 case R.id.connect_scan:
725 if (ensureBluetooth()) {
726 // Launch the DeviceListActivity to see devices and do scan
727 serverIntent = new Intent(this, DeviceListActivity.class);
728 startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
731 case R.id.disconnect:
732 /* Disconnect the device
737 AltosDebug.debug("R.id.quit");
741 case R.id.select_freq:
742 // Set the TBT radio frequency
744 final String[] frequencies = {
745 "Channel 0 (434.550MHz)",
746 "Channel 1 (434.650MHz)",
747 "Channel 2 (434.750MHz)",
748 "Channel 3 (434.850MHz)",
749 "Channel 4 (434.950MHz)",
750 "Channel 5 (435.050MHz)",
751 "Channel 6 (435.150MHz)",
752 "Channel 7 (435.250MHz)",
753 "Channel 8 (435.350MHz)",
754 "Channel 9 (435.450MHz)"
757 AlertDialog.Builder builder_freq = new AlertDialog.Builder(this);
758 builder_freq.setTitle("Pick a frequency");
759 builder_freq.setItems(frequencies,
760 new DialogInterface.OnClickListener() {
761 public void onClick(DialogInterface dialog, int item) {
762 setFrequency(frequencies[item]);
765 AlertDialog alert_freq = builder_freq.create();
768 case R.id.select_rate:
769 // Set the TBT baud rate
771 final String[] rates = {
777 AlertDialog.Builder builder_rate = new AlertDialog.Builder(this);
778 builder_rate.setTitle("Pick a baud rate");
779 builder_rate.setItems(rates,
780 new DialogInterface.OnClickListener() {
781 public void onClick(DialogInterface dialog, int item) {
782 setBaud(rates[item]);
785 AlertDialog alert_rate = builder_rate.create();
788 case R.id.change_units:
789 boolean imperial = AltosPreferences.imperial_units();
790 AltosPreferences.set_imperial_units(!imperial);