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.*;
58 import android.graphics.*;
59 import android.graphics.drawable.*;
61 import org.altusmetrum.altoslib_7.*;
63 public class AltosDroid extends FragmentActivity implements AltosUnitsListener {
65 // Actions sent to the telemetry server at startup time
67 public static final String ACTION_BLUETOOTH = "org.altusmetrum.AltosDroid.BLUETOOTH";
68 public static final String ACTION_USB = "org.altusmetrum.AltosDroid.USB";
70 // Message types received by our Handler
72 public static final int MSG_STATE = 1;
73 public static final int MSG_UPDATE_AGE = 2;
75 // Intent request codes
76 public static final int REQUEST_CONNECT_DEVICE = 1;
77 public static final int REQUEST_ENABLE_BT = 2;
78 public static final int REQUEST_PRELOAD_MAPS = 3;
79 public static final int REQUEST_MAP_TYPE = 4;
81 public int map_type = AltosMap.maptype_hybrid;
83 public static FragmentManager fm;
85 private BluetoothAdapter mBluetoothAdapter = null;
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;
95 private boolean mAgeViewOld;
96 private int mAgeNewColor;
97 private int mAgeOldColor;
99 // field to display the version at the bottom of the screen
100 private TextView mVersion;
102 private double frequency;
103 private int telemetry_rate;
107 AltosViewPager mViewPager;
108 TabsAdapter mTabsAdapter;
109 ArrayList<AltosDroidTab> mTabs = new ArrayList<AltosDroidTab>();
112 // Timer and Saved flight state for Age calculation
114 AltosState saved_state;
116 UsbDevice pending_usb_device;
117 boolean start_with_usb;
120 private boolean mIsBound = false;
121 private Messenger mService = null;
122 final Messenger mMessenger = new Messenger(new IncomingHandler(this));
125 private AltosVoice mAltosVoice = null;
127 // The Handler that gets information back from the Telemetry Service
128 static class IncomingHandler extends Handler {
129 private final WeakReference<AltosDroid> mAltosDroid;
130 IncomingHandler(AltosDroid ad) { mAltosDroid = new WeakReference<AltosDroid>(ad); }
133 public void handleMessage(Message msg) {
134 AltosDroid ad = mAltosDroid.get();
138 AltosDebug.debug("MSG_STATE");
139 TelemetryState telemetry_state = (TelemetryState) msg.obj;
140 if (telemetry_state == null) {
141 AltosDebug.debug("telemetry_state null!");
145 ad.update_state(telemetry_state);
148 AltosDebug.debug("MSG_UPDATE_AGE");
156 private ServiceConnection mConnection = new ServiceConnection() {
157 public void onServiceConnected(ComponentName className, IBinder service) {
158 mService = new Messenger(service);
160 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
161 msg.replyTo = mMessenger;
163 } catch (RemoteException e) {
164 // In this case the service has crashed before we could even do anything with it
166 if (pending_usb_device != null) {
168 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, pending_usb_device));
169 pending_usb_device = null;
170 } catch (RemoteException e) {
175 public void onServiceDisconnected(ComponentName className) {
176 // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
181 void doBindService() {
182 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
186 void doUnbindService() {
188 // If we have received the service, and hence registered with it, then now is the time to unregister.
189 if (mService != null) {
191 Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
192 msg.replyTo = mMessenger;
194 } catch (RemoteException e) {
195 // There is nothing special we need to do if the service has crashed.
198 // Detach our existing connection.
199 unbindService(mConnection);
204 public void registerTab(AltosDroidTab mTab) {
208 public void unregisterTab(AltosDroidTab mTab) {
212 public void units_changed(boolean imperial_units) {
213 for (AltosDroidTab mTab : mTabs)
214 mTab.units_changed(imperial_units);
217 void update_title(TelemetryState telemetry_state) {
218 switch (telemetry_state.connect) {
219 case TelemetryState.CONNECT_CONNECTED:
220 if (telemetry_state.config != null) {
221 String str = String.format("S/N %d %6.3f MHz", telemetry_state.config.serial,
222 telemetry_state.frequency);
223 if (telemetry_state.telemetry_rate != AltosLib.ao_telemetry_rate_38400)
224 str = str.concat(String.format(" %d bps",
225 AltosLib.ao_telemetry_rate_values[telemetry_state.telemetry_rate]));
228 setTitle(R.string.title_connected_to);
231 case TelemetryState.CONNECT_CONNECTING:
232 if (telemetry_state.address != null)
233 setTitle(String.format("Connecting to %s...", telemetry_state.address.name));
235 setTitle("Connecting to something...");
237 case TelemetryState.CONNECT_DISCONNECTED:
238 case TelemetryState.CONNECT_NONE:
239 setTitle(R.string.title_not_connected);
247 timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 1000L, 1000L);
259 boolean registered_units_listener;
261 void update_state(TelemetryState telemetry_state) {
263 if (!registered_units_listener) {
264 registered_units_listener = true;
265 AltosPreferences.register_units_listener(this);
268 update_title(telemetry_state);
269 update_ui(telemetry_state.state, telemetry_state.location);
270 if (telemetry_state.connect == TelemetryState.CONNECT_CONNECTED)
274 boolean same_string(String a, String b) {
287 if (saved_state != null) {
288 int age = (int) ((System.currentTimeMillis() - saved_state.received_time + 500) / 1000);
289 boolean old = age >= 10;
290 if (old != mAgeViewOld) {
292 mAgeView.setTextColor(mAgeOldColor);
294 mAgeView.setTextColor(mAgeNewColor);
297 mAgeView.setText(String.format("%d", age));
301 void update_ui(AltosState state, Location location) {
303 int prev_state = AltosLib.ao_flight_invalid;
305 AltosGreatCircle from_receiver = null;
307 if (saved_state != null)
308 prev_state = saved_state.state;
311 if (state.state == AltosLib.ao_flight_stateless) {
312 boolean prev_locked = false;
313 boolean locked = false;
315 if(state.gps != null)
316 locked = state.gps.locked;
317 if (saved_state != null && saved_state.gps != null)
318 prev_locked = saved_state.gps.locked;
319 if (prev_locked != locked) {
320 String currentTab = mTabHost.getCurrentTabTag();
322 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("descent");
324 if (currentTab.equals("descent")) mTabHost.setCurrentTabByTag("pad");
328 if (prev_state != state.state) {
329 String currentTab = mTabHost.getCurrentTabTag();
330 switch (state.state) {
331 case AltosLib.ao_flight_boost:
332 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("ascent");
334 case AltosLib.ao_flight_drogue:
335 if (currentTab.equals("ascent")) mTabHost.setCurrentTabByTag("descent");
337 case AltosLib.ao_flight_landed:
338 if (currentTab.equals("descent")) mTabHost.setCurrentTabByTag("landed");
340 case AltosLib.ao_flight_stateless:
341 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("descent");
347 if (location != null && state.gps != null && state.gps.locked) {
349 if (location.hasAltitude())
350 altitude = location.getAltitude();
351 from_receiver = new AltosGreatCircle(location.getLatitude(),
352 location.getLongitude(),
359 if (saved_state == null || !same_string(saved_state.callsign, state.callsign)) {
360 mCallsignView.setText(state.callsign);
362 if (saved_state == null || state.serial != saved_state.serial) {
363 mSerialView.setText(String.format("%d", state.serial));
365 if (saved_state == null || state.flight != saved_state.flight) {
366 if (state.flight == AltosLib.MISSING)
367 mFlightView.setText("");
369 mFlightView.setText(String.format("%d", state.flight));
371 if (saved_state == null || state.state != saved_state.state) {
372 if (state.state == AltosLib.ao_flight_stateless) {
373 mStateLayout.setVisibility(View.GONE);
375 mStateView.setText(state.state_name());
376 mStateLayout.setVisibility(View.VISIBLE);
379 if (saved_state == null || state.rssi != saved_state.rssi) {
380 mRSSIView.setText(String.format("%d", state.rssi));
384 for (AltosDroidTab mTab : mTabs)
385 mTab.update_ui(state, from_receiver, location, mTab == mTabsAdapter.currentItem());
387 if (state != null && mAltosVoice != null)
388 mAltosVoice.tell(state, from_receiver);
393 private void onTimerTick() {
395 mMessenger.send(Message.obtain(null, MSG_UPDATE_AGE));
396 } catch (RemoteException e) {
400 static String pos(double p, String pos, String neg) {
402 if (p == AltosLib.MISSING)
408 int deg = (int) Math.floor(p);
409 double min = (p - Math.floor(p)) * 60.0;
410 return String.format("%d°%9.4f\" %s", deg, min, h);
413 static String number(String format, double value) {
414 if (value == AltosLib.MISSING)
416 return String.format(format, value);
419 static String integer(String format, int value) {
420 if (value == AltosLib.MISSING)
422 return String.format(format, value);
425 private View create_tab_view(String label) {
426 LayoutInflater inflater = (LayoutInflater) this.getLayoutInflater();
427 View tab_view = inflater.inflate(R.layout.tab_layout, null);
428 TextView text_view = (TextView) tab_view.findViewById (R.id.tabLabel);
429 text_view.setText(label);
434 public void onCreate(Bundle savedInstanceState) {
435 super.onCreate(savedInstanceState);
436 AltosDebug.init(this);
437 AltosDebug.debug("+++ ON CREATE +++");
439 fm = getSupportFragmentManager();
441 // Set up the window layout
442 setContentView(R.layout.altosdroid);
444 // Create the Tabs and ViewPager
445 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
448 mViewPager = (AltosViewPager)findViewById(R.id.pager);
449 mViewPager.setOffscreenPageLimit(4);
451 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
453 mTabsAdapter.addTab(mTabHost.newTabSpec("pad").setIndicator(create_tab_view("Pad")), TabPad.class, null);
454 mTabsAdapter.addTab(mTabHost.newTabSpec("ascent").setIndicator(create_tab_view("Ascent")), TabAscent.class, null);
455 mTabsAdapter.addTab(mTabHost.newTabSpec("descent").setIndicator(create_tab_view("Descent")), TabDescent.class, null);
456 mTabsAdapter.addTab(mTabHost.newTabSpec("landed").setIndicator(create_tab_view("Landed")), TabLanded.class, null);
457 mTabsAdapter.addTab(mTabHost.newTabSpec("map").setIndicator(create_tab_view("Map")), TabMap.class, null);
458 mTabsAdapter.addTab(mTabHost.newTabSpec("offmap").setIndicator(create_tab_view("OffMap")), TabMapOffline.class, null);
460 // Display the Version
461 mVersion = (TextView) findViewById(R.id.version);
462 mVersion.setText("Version: " + BuildInfo.version +
463 " Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
464 " (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
466 mCallsignView = (TextView) findViewById(R.id.callsign_value);
467 mRSSIView = (TextView) findViewById(R.id.rssi_value);
468 mSerialView = (TextView) findViewById(R.id.serial_value);
469 mFlightView = (TextView) findViewById(R.id.flight_value);
470 mStateLayout = (RelativeLayout) findViewById(R.id.state_container);
471 mStateView = (TextView) findViewById(R.id.state_value);
472 mAgeView = (TextView) findViewById(R.id.age_value);
473 mAgeNewColor = mAgeView.getTextColors().getDefaultColor();
474 mAgeOldColor = getResources().getColor(R.color.old_color);
477 private boolean ensureBluetooth() {
478 // Get local Bluetooth adapter
479 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
481 // If the adapter is null, then Bluetooth is not supported
482 if (mBluetoothAdapter == null) {
483 Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
487 if (!mBluetoothAdapter.isEnabled()) {
488 Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
489 startActivityForResult(enableIntent, AltosDroid.REQUEST_ENABLE_BT);
495 private boolean check_usb() {
496 UsbDevice device = AltosUsb.find_device(this, AltosLib.product_basestation);
498 if (device != null) {
499 Intent i = new Intent(this, AltosDroid.class);
500 PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent("hello world", null, this, AltosDroid.class), 0);
502 if (AltosUsb.request_permission(this, device, pi)) {
505 start_with_usb = true;
509 start_with_usb = false;
514 private void noticeIntent(Intent intent) {
516 /* Ok, this is pretty convenient.
518 * When a USB device is plugged in, and our 'hotplug'
519 * intent registration fires, we get an Intent with
522 * When we start up and see a usb device and request
523 * permission to access it, that queues a
524 * PendingIntent, which has the EXTRA_DEVICE added in,
525 * along with the EXTRA_PERMISSION_GRANTED field as
528 * So, in both cases, we get the device name using the
529 * same call. We check to see if access was granted,
530 * in which case we ignore the device field and do our
531 * usual startup thing.
534 UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
535 boolean granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, true);
537 AltosDebug.debug("intent %s device %s granted %s", intent, device, granted);
542 if (device != null) {
543 AltosDebug.debug("intent has usb device " + device.toString());
547 /* 'granted' is only false if this intent came
548 * from the request_permission call and
549 * permission was denied. In which case, we
550 * don't want to loop forever...
553 AltosDebug.debug("check for a USB device at startup");
557 AltosDebug.debug("Starting by looking for bluetooth devices");
558 if (ensureBluetooth())
565 public void onStart() {
567 AltosDebug.debug("++ ON START ++");
569 noticeIntent(getIntent());
571 // Start Telemetry Service
572 String action = start_with_usb ? ACTION_USB : ACTION_BLUETOOTH;
574 startService(new Intent(action, null, AltosDroid.this, TelemetryService.class));
578 if (mAltosVoice == null)
579 mAltosVoice = new AltosVoice(this);
584 public void onNewIntent(Intent intent) {
585 super.onNewIntent(intent);
586 AltosDebug.debug("onNewIntent");
587 noticeIntent(intent);
591 public void onResume() {
593 AltosDebug.debug("+ ON RESUME +");
597 public void onPause() {
599 AltosDebug.debug("- ON PAUSE -");
603 public void onStop() {
605 AltosDebug.debug("-- ON STOP --");
608 if (mAltosVoice != null) {
615 public void onDestroy() {
617 AltosDebug.debug("--- ON DESTROY ---");
619 if (mAltosVoice != null) mAltosVoice.stop();
623 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
624 AltosDebug.debug("onActivityResult " + resultCode);
625 switch (requestCode) {
626 case REQUEST_CONNECT_DEVICE:
627 // When DeviceListActivity returns with a device to connect to
628 if (resultCode == Activity.RESULT_OK) {
632 case REQUEST_ENABLE_BT:
633 // When the request to enable Bluetooth returns
634 if (resultCode == Activity.RESULT_OK) {
635 // Bluetooth is now enabled, so set up a chat session
638 // User did not enable Bluetooth or an error occured
639 AltosDebug.error("BT not enabled");
640 stopService(new Intent(AltosDroid.this, TelemetryService.class));
641 Toast.makeText(this, R.string.bt_not_enabled, Toast.LENGTH_SHORT).show();
645 case REQUEST_MAP_TYPE:
646 if (resultCode == Activity.RESULT_OK)
652 private void connectUsb(UsbDevice device) {
653 if (mService == null)
654 pending_usb_device = device;
656 // Attempt to connect to the device
658 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, device));
659 AltosDebug.debug("Sent OPEN_USB message");
660 } catch (RemoteException e) {
661 AltosDebug.debug("connect device message failed");
666 private void connectDevice(Intent data) {
667 // Attempt to connect to the device
669 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
670 String name = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_NAME);
672 AltosDebug.debug("Connecting to " + address + " " + name);
673 DeviceAddress a = new DeviceAddress(address, name);
674 mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, a));
675 AltosDebug.debug("Sent connecting message");
676 } catch (RemoteException e) {
677 AltosDebug.debug("connect device message failed");
681 private void disconnectDevice() {
683 mService.send(Message.obtain(null, TelemetryService.MSG_DISCONNECT, null));
684 } catch (RemoteException e) {
688 private void set_map_type(Intent data) {
689 int type = data.getIntExtra(MapTypeActivity.EXTRA_MAP_TYPE, -1);
691 AltosDebug.debug("intent set_map_type %d\n", type);
694 for (AltosDroidTab mTab : mTabs)
695 mTab.set_map_type(map_type);
700 public boolean onCreateOptionsMenu(Menu menu) {
701 MenuInflater inflater = getMenuInflater();
702 inflater.inflate(R.menu.option_menu, menu);
706 void setFrequency(double freq) {
708 mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
709 } catch (RemoteException e) {
713 void setFrequency(String freq) {
715 setFrequency (AltosParse.parse_double_net(freq.substring(11, 17)));
716 } catch (ParseException e) {
720 void setBaud(int baud) {
722 mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD, baud));
723 } catch (RemoteException e) {
727 void setBaud(String baud) {
729 int value = Integer.parseInt(baud);
730 int rate = AltosLib.ao_telemetry_rate_38400;
733 rate = AltosLib.ao_telemetry_rate_2400;
736 rate = AltosLib.ao_telemetry_rate_9600;
739 rate = AltosLib.ao_telemetry_rate_38400;
743 } catch (NumberFormatException e) {
748 public boolean onOptionsItemSelected(MenuItem item) {
749 Intent serverIntent = null;
750 switch (item.getItemId()) {
751 case R.id.connect_scan:
752 if (ensureBluetooth()) {
753 // Launch the DeviceListActivity to see devices and do scan
754 serverIntent = new Intent(this, DeviceListActivity.class);
755 startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
758 case R.id.disconnect:
759 /* Disconnect the device
764 AltosDebug.debug("R.id.quit");
768 case R.id.select_freq:
769 // Set the TBT radio frequency
771 final String[] frequencies = {
772 "Channel 0 (434.550MHz)",
773 "Channel 1 (434.650MHz)",
774 "Channel 2 (434.750MHz)",
775 "Channel 3 (434.850MHz)",
776 "Channel 4 (434.950MHz)",
777 "Channel 5 (435.050MHz)",
778 "Channel 6 (435.150MHz)",
779 "Channel 7 (435.250MHz)",
780 "Channel 8 (435.350MHz)",
781 "Channel 9 (435.450MHz)"
784 AlertDialog.Builder builder_freq = new AlertDialog.Builder(this);
785 builder_freq.setTitle("Pick a frequency");
786 builder_freq.setItems(frequencies,
787 new DialogInterface.OnClickListener() {
788 public void onClick(DialogInterface dialog, int item) {
789 setFrequency(frequencies[item]);
792 AlertDialog alert_freq = builder_freq.create();
795 case R.id.select_rate:
796 // Set the TBT baud rate
798 final String[] rates = {
804 AlertDialog.Builder builder_rate = new AlertDialog.Builder(this);
805 builder_rate.setTitle("Pick a baud rate");
806 builder_rate.setItems(rates,
807 new DialogInterface.OnClickListener() {
808 public void onClick(DialogInterface dialog, int item) {
809 setBaud(rates[item]);
812 AlertDialog alert_rate = builder_rate.create();
815 case R.id.change_units:
816 boolean imperial = AltosPreferences.imperial_units();
817 AltosPreferences.set_imperial_units(!imperial);
819 case R.id.preload_maps:
820 serverIntent = new Intent(this, PreloadMapActivity.class);
821 startActivityForResult(serverIntent, REQUEST_PRELOAD_MAPS);
824 serverIntent = new Intent(this, MapTypeActivity.class);
825 startActivityForResult(serverIntent, REQUEST_MAP_TYPE);