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.debug("+++ ON CREATE +++");
424 fm = getSupportFragmentManager();
426 // Set up the window layout
427 requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
428 setContentView(R.layout.altosdroid);
429 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
431 // Create the Tabs and ViewPager
432 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
435 mViewPager = (AltosViewPager)findViewById(R.id.pager);
436 mViewPager.setOffscreenPageLimit(4);
438 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
440 mTabsAdapter.addTab(mTabHost.newTabSpec("pad").setIndicator(create_tab_view("Pad")), TabPad.class, null);
441 mTabsAdapter.addTab(mTabHost.newTabSpec("ascent").setIndicator(create_tab_view("Ascent")), TabAscent.class, null);
442 mTabsAdapter.addTab(mTabHost.newTabSpec("descent").setIndicator(create_tab_view("Descent")), TabDescent.class, null);
443 mTabsAdapter.addTab(mTabHost.newTabSpec("landed").setIndicator(create_tab_view("Landed")), TabLanded.class, null);
444 mTabsAdapter.addTab(mTabHost.newTabSpec("map").setIndicator(create_tab_view("Map")), TabMap.class, null);
445 mTabsAdapter.addTab(mTabHost.newTabSpec("offmap").setIndicator(create_tab_view("OffMap")), TabMapOffline.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 AltosDebug.debug("intent %s device %s granted %s", intent, device, granted);
532 if (device != null) {
533 AltosDebug.debug("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 AltosDebug.debug("check for a USB device at startup");
547 AltosDebug.debug("Starting by looking for bluetooth devices");
548 if (ensureBluetooth())
555 public void onStart() {
557 AltosDebug.debug("++ 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 AltosDebug.debug("onNewIntent");
577 noticeIntent(intent);
581 public void onResume() {
583 AltosDebug.debug("+ ON RESUME +");
587 public void onPause() {
589 AltosDebug.debug("- ON PAUSE -");
593 public void onStop() {
595 AltosDebug.debug("-- ON STOP --");
598 if (mAltosVoice != null) {
605 public void onDestroy() {
607 AltosDebug.debug("--- ON DESTROY ---");
609 if (mAltosVoice != null) mAltosVoice.stop();
613 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
614 AltosDebug.debug("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 AltosDebug.error("BT not enabled");
630 stopService(new Intent(AltosDroid.this, TelemetryService.class));
631 Toast.makeText(this, R.string.bt_not_enabled, Toast.LENGTH_SHORT).show();
635 case REQUEST_MAP_TYPE:
636 if (resultCode == Activity.RESULT_OK)
642 private void connectUsb(UsbDevice device) {
643 if (mService == null)
644 pending_usb_device = device;
646 // Attempt to connect to the device
648 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, device));
649 AltosDebug.debug("Sent OPEN_USB message");
650 } catch (RemoteException e) {
651 AltosDebug.debug("connect device message failed");
656 private void connectDevice(Intent data) {
657 // Attempt to connect to the device
659 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
660 String name = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_NAME);
662 AltosDebug.debug("Connecting to " + address + " " + name);
663 DeviceAddress a = new DeviceAddress(address, name);
664 mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, a));
665 AltosDebug.debug("Sent connecting message");
666 } catch (RemoteException e) {
667 AltosDebug.debug("connect device message failed");
671 private void disconnectDevice() {
673 mService.send(Message.obtain(null, TelemetryService.MSG_DISCONNECT, null));
674 } catch (RemoteException e) {
678 private void set_map_type(Intent data) {
679 int mode = data.getIntExtra(MapTypeActivity.EXTRA_MAP_TYPE, -1);
681 AltosDebug.debug("intent set_map_type %d\n", mode);
683 for (AltosDroidTab mTab : mTabs)
684 mTab.set_map_type(mode);
689 public boolean onCreateOptionsMenu(Menu menu) {
690 MenuInflater inflater = getMenuInflater();
691 inflater.inflate(R.menu.option_menu, menu);
695 void setFrequency(double freq) {
697 mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
698 } catch (RemoteException e) {
702 void setFrequency(String freq) {
704 setFrequency (AltosParse.parse_double_net(freq.substring(11, 17)));
705 } catch (ParseException e) {
709 void setBaud(int baud) {
711 mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD, baud));
712 } catch (RemoteException e) {
716 void setBaud(String baud) {
718 int value = Integer.parseInt(baud);
719 int rate = AltosLib.ao_telemetry_rate_38400;
722 rate = AltosLib.ao_telemetry_rate_2400;
725 rate = AltosLib.ao_telemetry_rate_9600;
728 rate = AltosLib.ao_telemetry_rate_38400;
732 } catch (NumberFormatException e) {
737 public boolean onOptionsItemSelected(MenuItem item) {
738 Intent serverIntent = null;
739 switch (item.getItemId()) {
740 case R.id.connect_scan:
741 if (ensureBluetooth()) {
742 // Launch the DeviceListActivity to see devices and do scan
743 serverIntent = new Intent(this, DeviceListActivity.class);
744 startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
747 case R.id.disconnect:
748 /* Disconnect the device
753 AltosDebug.debug("R.id.quit");
757 case R.id.select_freq:
758 // Set the TBT radio frequency
760 final String[] frequencies = {
761 "Channel 0 (434.550MHz)",
762 "Channel 1 (434.650MHz)",
763 "Channel 2 (434.750MHz)",
764 "Channel 3 (434.850MHz)",
765 "Channel 4 (434.950MHz)",
766 "Channel 5 (435.050MHz)",
767 "Channel 6 (435.150MHz)",
768 "Channel 7 (435.250MHz)",
769 "Channel 8 (435.350MHz)",
770 "Channel 9 (435.450MHz)"
773 AlertDialog.Builder builder_freq = new AlertDialog.Builder(this);
774 builder_freq.setTitle("Pick a frequency");
775 builder_freq.setItems(frequencies,
776 new DialogInterface.OnClickListener() {
777 public void onClick(DialogInterface dialog, int item) {
778 setFrequency(frequencies[item]);
781 AlertDialog alert_freq = builder_freq.create();
784 case R.id.select_rate:
785 // Set the TBT baud rate
787 final String[] rates = {
793 AlertDialog.Builder builder_rate = new AlertDialog.Builder(this);
794 builder_rate.setTitle("Pick a baud rate");
795 builder_rate.setItems(rates,
796 new DialogInterface.OnClickListener() {
797 public void onClick(DialogInterface dialog, int item) {
798 setBaud(rates[item]);
801 AlertDialog alert_rate = builder_rate.create();
804 case R.id.change_units:
805 boolean imperial = AltosPreferences.imperial_units();
806 AltosPreferences.set_imperial_units(!imperial);
808 case R.id.preload_maps:
809 serverIntent = new Intent(this, PreloadMapActivity.class);
810 startActivityForResult(serverIntent, REQUEST_PRELOAD_MAPS);
813 serverIntent = new Intent(this, MapTypeActivity.class);
814 startActivityForResult(serverIntent, REQUEST_MAP_TYPE);