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 int map_type = AltosMap.maptype_hybrid;
81 public static FragmentManager fm;
83 private BluetoothAdapter mBluetoothAdapter = null;
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 AltosDebug.debug("MSG_STATE");
134 TelemetryState telemetry_state = (TelemetryState) msg.obj;
135 if (telemetry_state == null) {
136 AltosDebug.debug("telemetry_state null!");
140 ad.update_state(telemetry_state);
143 AltosDebug.debug("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 setTitle(R.string.title_connected_to);
226 case TelemetryState.CONNECT_CONNECTING:
227 if (telemetry_state.address != null)
228 setTitle(String.format("Connecting to %s...", telemetry_state.address.name));
230 setTitle("Connecting to something...");
232 case TelemetryState.CONNECT_DISCONNECTED:
233 case TelemetryState.CONNECT_NONE:
234 setTitle(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);
410 private View create_tab_view(String label) {
411 LayoutInflater inflater = (LayoutInflater) this.getLayoutInflater();
412 View tab_view = inflater.inflate(R.layout.tab_layout, null);
413 TextView text_view = (TextView) tab_view.findViewById (R.id.tabLabel);
414 text_view.setText(label);
419 public void onCreate(Bundle savedInstanceState) {
420 super.onCreate(savedInstanceState);
421 AltosDebug.init(this);
422 AltosDebug.debug("+++ ON CREATE +++");
424 fm = getSupportFragmentManager();
426 // Set up the window layout
427 setContentView(R.layout.altosdroid);
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 // Display the Version
446 mVersion = (TextView) findViewById(R.id.version);
447 mVersion.setText("Version: " + BuildInfo.version +
448 " Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
449 " (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
451 mCallsignView = (TextView) findViewById(R.id.callsign_value);
452 mRSSIView = (TextView) findViewById(R.id.rssi_value);
453 mSerialView = (TextView) findViewById(R.id.serial_value);
454 mFlightView = (TextView) findViewById(R.id.flight_value);
455 mStateLayout = (RelativeLayout) findViewById(R.id.state_container);
456 mStateView = (TextView) findViewById(R.id.state_value);
457 mAgeView = (TextView) findViewById(R.id.age_value);
460 private boolean ensureBluetooth() {
461 // Get local Bluetooth adapter
462 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
464 // If the adapter is null, then Bluetooth is not supported
465 if (mBluetoothAdapter == null) {
466 Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
470 if (!mBluetoothAdapter.isEnabled()) {
471 Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
472 startActivityForResult(enableIntent, AltosDroid.REQUEST_ENABLE_BT);
478 private boolean check_usb() {
479 UsbDevice device = AltosUsb.find_device(this, AltosLib.product_basestation);
481 if (device != null) {
482 Intent i = new Intent(this, AltosDroid.class);
483 PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent("hello world", null, this, AltosDroid.class), 0);
485 if (AltosUsb.request_permission(this, device, pi)) {
488 start_with_usb = true;
492 start_with_usb = false;
497 private void noticeIntent(Intent intent) {
499 /* Ok, this is pretty convenient.
501 * When a USB device is plugged in, and our 'hotplug'
502 * intent registration fires, we get an Intent with
505 * When we start up and see a usb device and request
506 * permission to access it, that queues a
507 * PendingIntent, which has the EXTRA_DEVICE added in,
508 * along with the EXTRA_PERMISSION_GRANTED field as
511 * So, in both cases, we get the device name using the
512 * same call. We check to see if access was granted,
513 * in which case we ignore the device field and do our
514 * usual startup thing.
517 UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
518 boolean granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, true);
520 AltosDebug.debug("intent %s device %s granted %s", intent, device, granted);
525 if (device != null) {
526 AltosDebug.debug("intent has usb device " + device.toString());
530 /* 'granted' is only false if this intent came
531 * from the request_permission call and
532 * permission was denied. In which case, we
533 * don't want to loop forever...
536 AltosDebug.debug("check for a USB device at startup");
540 AltosDebug.debug("Starting by looking for bluetooth devices");
541 if (ensureBluetooth())
548 public void onStart() {
550 AltosDebug.debug("++ ON START ++");
552 noticeIntent(getIntent());
554 // Start Telemetry Service
555 String action = start_with_usb ? ACTION_USB : ACTION_BLUETOOTH;
557 startService(new Intent(action, null, AltosDroid.this, TelemetryService.class));
561 if (mAltosVoice == null)
562 mAltosVoice = new AltosVoice(this);
567 public void onNewIntent(Intent intent) {
568 super.onNewIntent(intent);
569 AltosDebug.debug("onNewIntent");
570 noticeIntent(intent);
574 public void onResume() {
576 AltosDebug.debug("+ ON RESUME +");
580 public void onPause() {
582 AltosDebug.debug("- ON PAUSE -");
586 public void onStop() {
588 AltosDebug.debug("-- ON STOP --");
591 if (mAltosVoice != null) {
598 public void onDestroy() {
600 AltosDebug.debug("--- ON DESTROY ---");
602 if (mAltosVoice != null) mAltosVoice.stop();
606 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
607 AltosDebug.debug("onActivityResult " + resultCode);
608 switch (requestCode) {
609 case REQUEST_CONNECT_DEVICE:
610 // When DeviceListActivity returns with a device to connect to
611 if (resultCode == Activity.RESULT_OK) {
615 case REQUEST_ENABLE_BT:
616 // When the request to enable Bluetooth returns
617 if (resultCode == Activity.RESULT_OK) {
618 // Bluetooth is now enabled, so set up a chat session
621 // User did not enable Bluetooth or an error occured
622 AltosDebug.error("BT not enabled");
623 stopService(new Intent(AltosDroid.this, TelemetryService.class));
624 Toast.makeText(this, R.string.bt_not_enabled, Toast.LENGTH_SHORT).show();
628 case REQUEST_MAP_TYPE:
629 if (resultCode == Activity.RESULT_OK)
635 private void connectUsb(UsbDevice device) {
636 if (mService == null)
637 pending_usb_device = device;
639 // Attempt to connect to the device
641 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, device));
642 AltosDebug.debug("Sent OPEN_USB message");
643 } catch (RemoteException e) {
644 AltosDebug.debug("connect device message failed");
649 private void connectDevice(Intent data) {
650 // Attempt to connect to the device
652 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
653 String name = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_NAME);
655 AltosDebug.debug("Connecting to " + address + " " + name);
656 DeviceAddress a = new DeviceAddress(address, name);
657 mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, a));
658 AltosDebug.debug("Sent connecting message");
659 } catch (RemoteException e) {
660 AltosDebug.debug("connect device message failed");
664 private void disconnectDevice() {
666 mService.send(Message.obtain(null, TelemetryService.MSG_DISCONNECT, null));
667 } catch (RemoteException e) {
671 private void set_map_type(Intent data) {
672 int type = data.getIntExtra(MapTypeActivity.EXTRA_MAP_TYPE, -1);
674 AltosDebug.debug("intent set_map_type %d\n", type);
677 for (AltosDroidTab mTab : mTabs)
678 mTab.set_map_type(map_type);
683 public boolean onCreateOptionsMenu(Menu menu) {
684 MenuInflater inflater = getMenuInflater();
685 inflater.inflate(R.menu.option_menu, menu);
689 void setFrequency(double freq) {
691 mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
692 } catch (RemoteException e) {
696 void setFrequency(String freq) {
698 setFrequency (AltosParse.parse_double_net(freq.substring(11, 17)));
699 } catch (ParseException e) {
703 void setBaud(int baud) {
705 mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD, baud));
706 } catch (RemoteException e) {
710 void setBaud(String baud) {
712 int value = Integer.parseInt(baud);
713 int rate = AltosLib.ao_telemetry_rate_38400;
716 rate = AltosLib.ao_telemetry_rate_2400;
719 rate = AltosLib.ao_telemetry_rate_9600;
722 rate = AltosLib.ao_telemetry_rate_38400;
726 } catch (NumberFormatException e) {
731 public boolean onOptionsItemSelected(MenuItem item) {
732 Intent serverIntent = null;
733 switch (item.getItemId()) {
734 case R.id.connect_scan:
735 if (ensureBluetooth()) {
736 // Launch the DeviceListActivity to see devices and do scan
737 serverIntent = new Intent(this, DeviceListActivity.class);
738 startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
741 case R.id.disconnect:
742 /* Disconnect the device
747 AltosDebug.debug("R.id.quit");
751 case R.id.select_freq:
752 // Set the TBT radio frequency
754 final String[] frequencies = {
755 "Channel 0 (434.550MHz)",
756 "Channel 1 (434.650MHz)",
757 "Channel 2 (434.750MHz)",
758 "Channel 3 (434.850MHz)",
759 "Channel 4 (434.950MHz)",
760 "Channel 5 (435.050MHz)",
761 "Channel 6 (435.150MHz)",
762 "Channel 7 (435.250MHz)",
763 "Channel 8 (435.350MHz)",
764 "Channel 9 (435.450MHz)"
767 AlertDialog.Builder builder_freq = new AlertDialog.Builder(this);
768 builder_freq.setTitle("Pick a frequency");
769 builder_freq.setItems(frequencies,
770 new DialogInterface.OnClickListener() {
771 public void onClick(DialogInterface dialog, int item) {
772 setFrequency(frequencies[item]);
775 AlertDialog alert_freq = builder_freq.create();
778 case R.id.select_rate:
779 // Set the TBT baud rate
781 final String[] rates = {
787 AlertDialog.Builder builder_rate = new AlertDialog.Builder(this);
788 builder_rate.setTitle("Pick a baud rate");
789 builder_rate.setItems(rates,
790 new DialogInterface.OnClickListener() {
791 public void onClick(DialogInterface dialog, int item) {
792 setBaud(rates[item]);
795 AlertDialog alert_rate = builder_rate.create();
798 case R.id.change_units:
799 boolean imperial = AltosPreferences.imperial_units();
800 AltosPreferences.set_imperial_units(!imperial);
802 case R.id.preload_maps:
803 serverIntent = new Intent(this, PreloadMapActivity.class);
804 startActivityForResult(serverIntent, REQUEST_PRELOAD_MAPS);
807 serverIntent = new Intent(this, MapTypeActivity.class);
808 startActivityForResult(serverIntent, REQUEST_MAP_TYPE);