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.bluetooth.BluetoothAdapter;
27 import android.bluetooth.BluetoothDevice;
28 import android.content.Intent;
29 import android.content.Context;
30 import android.content.ComponentName;
31 import android.content.ServiceConnection;
32 import android.content.DialogInterface;
33 import android.os.IBinder;
34 import android.os.Bundle;
35 import android.os.Handler;
36 import android.os.Message;
37 import android.os.Messenger;
38 import android.os.RemoteException;
39 import android.support.v4.app.FragmentActivity;
40 import android.support.v4.app.FragmentManager;
41 import android.util.DisplayMetrics;
42 import android.util.Log;
43 import android.view.Menu;
44 import android.view.MenuInflater;
45 import android.view.MenuItem;
46 import android.view.Window;
47 import android.view.View;
48 import android.widget.TabHost;
49 import android.widget.TextView;
50 import android.widget.RelativeLayout;
51 import android.widget.Toast;
52 import android.app.AlertDialog;
53 import android.location.Location;
55 import org.altusmetrum.altoslib_5.*;
57 public class AltosDroid extends FragmentActivity implements AltosUnitsListener {
59 static final String TAG = "AltosDroid";
60 static final boolean D = true;
62 // Message types received by our Handler
64 public static final int MSG_STATE = 1;
65 public static final int MSG_UPDATE_AGE = 2;
67 // Intent request codes
68 public static final int REQUEST_CONNECT_DEVICE = 1;
69 public static final int REQUEST_ENABLE_BT = 2;
71 public static FragmentManager fm;
73 private BluetoothAdapter mBluetoothAdapter = null;
76 private TextView mTitle;
78 // Flight state values
79 private TextView mCallsignView;
80 private TextView mRSSIView;
81 private TextView mSerialView;
82 private TextView mFlightView;
83 private RelativeLayout mStateLayout;
84 private TextView mStateView;
85 private TextView mAgeView;
87 // field to display the version at the bottom of the screen
88 private TextView mVersion;
90 private double frequency;
91 private int telemetry_rate;
95 AltosViewPager mViewPager;
96 TabsAdapter mTabsAdapter;
97 ArrayList<AltosDroidTab> mTabs = new ArrayList<AltosDroidTab>();
100 // Timer and Saved flight state for Age calculation
102 AltosState saved_state;
105 private boolean mIsBound = false;
106 private Messenger mService = null;
107 final Messenger mMessenger = new Messenger(new IncomingHandler(this));
110 private AltosVoice mAltosVoice = null;
112 // The Handler that gets information back from the Telemetry Service
113 static class IncomingHandler extends Handler {
114 private final WeakReference<AltosDroid> mAltosDroid;
115 IncomingHandler(AltosDroid ad) { mAltosDroid = new WeakReference<AltosDroid>(ad); }
118 public void handleMessage(Message msg) {
119 AltosDroid ad = mAltosDroid.get();
123 if(D) Log.d(TAG, "MSG_STATE");
124 TelemetryState telemetry_state = (TelemetryState) msg.obj;
125 if (telemetry_state == null) {
126 Log.d(TAG, "telemetry_state null!");
130 ad.update_state(telemetry_state);
133 if(D) Log.d(TAG, "MSG_UPDATE_AGE");
141 private ServiceConnection mConnection = new ServiceConnection() {
142 public void onServiceConnected(ComponentName className, IBinder service) {
143 mService = new Messenger(service);
145 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
146 msg.replyTo = mMessenger;
148 } catch (RemoteException e) {
149 // In this case the service has crashed before we could even do anything with it
153 public void onServiceDisconnected(ComponentName className) {
154 // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
159 void doBindService() {
160 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
164 void doUnbindService() {
166 // If we have received the service, and hence registered with it, then now is the time to unregister.
167 if (mService != null) {
169 Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
170 msg.replyTo = mMessenger;
172 } catch (RemoteException e) {
173 // There is nothing special we need to do if the service has crashed.
176 // Detach our existing connection.
177 unbindService(mConnection);
182 public void registerTab(AltosDroidTab mTab) {
186 public void unregisterTab(AltosDroidTab mTab) {
190 public void units_changed(boolean imperial_units) {
191 for (AltosDroidTab mTab : mTabs)
192 mTab.units_changed(imperial_units);
195 void update_title(TelemetryState telemetry_state) {
196 switch (telemetry_state.connect) {
197 case TelemetryState.CONNECT_CONNECTED:
198 if (telemetry_state.config != null) {
199 String str = String.format("S/N %d %6.3f MHz", telemetry_state.config.serial,
200 telemetry_state.frequency);
201 if (telemetry_state.telemetry_rate != AltosLib.ao_telemetry_rate_38400)
202 str = str.concat(String.format(" %d bps",
203 AltosLib.ao_telemetry_rate_values[telemetry_state.telemetry_rate]));
206 mTitle.setText(R.string.title_connected_to);
209 case TelemetryState.CONNECT_CONNECTING:
210 mTitle.setText(R.string.title_connecting);
212 case TelemetryState.CONNECT_READY:
213 case TelemetryState.CONNECT_NONE:
214 mTitle.setText(R.string.title_not_connected);
222 timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 1000L, 1000L);
234 boolean registered_units_listener;
236 void update_state(TelemetryState telemetry_state) {
238 if (!registered_units_listener) {
239 registered_units_listener = true;
240 AltosPreferences.register_units_listener(this);
243 update_title(telemetry_state);
244 update_ui(telemetry_state.state, telemetry_state.location);
245 if (telemetry_state.connect == TelemetryState.CONNECT_CONNECTED)
251 boolean same_string(String a, String b) {
264 if (saved_state != null)
265 mAgeView.setText(String.format("%d", (System.currentTimeMillis() - saved_state.received_time + 500) / 1000));
268 void update_ui(AltosState state, Location location) {
270 Log.d(TAG, "update_ui");
272 int prev_state = AltosLib.ao_flight_invalid;
274 AltosGreatCircle from_receiver = null;
276 if (saved_state != null)
277 prev_state = saved_state.state;
280 Log.d(TAG, String.format("prev state %d new state %d\n", prev_state, state.state));
281 if (state.state == AltosLib.ao_flight_stateless) {
282 boolean prev_locked = false;
283 boolean locked = false;
285 if(state.gps != null)
286 locked = state.gps.locked;
287 if (saved_state != null && saved_state.gps != null)
288 prev_locked = saved_state.gps.locked;
289 if (prev_locked != locked) {
290 String currentTab = mTabHost.getCurrentTabTag();
292 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("descent");
294 if (currentTab.equals("descent")) mTabHost.setCurrentTabByTag("pad");
298 if (prev_state != state.state) {
299 String currentTab = mTabHost.getCurrentTabTag();
300 Log.d(TAG, "switch state");
301 switch (state.state) {
302 case AltosLib.ao_flight_boost:
303 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("ascent");
305 case AltosLib.ao_flight_drogue:
306 if (currentTab.equals("ascent")) mTabHost.setCurrentTabByTag("descent");
308 case AltosLib.ao_flight_landed:
309 if (currentTab.equals("descent")) mTabHost.setCurrentTabByTag("landed");
311 case AltosLib.ao_flight_stateless:
312 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("descent");
318 if (location != null && state.gps != null && state.gps.locked) {
320 if (location.hasAltitude())
321 altitude = location.getAltitude();
322 from_receiver = new AltosGreatCircle(location.getLatitude(),
323 location.getLongitude(),
330 if (saved_state == null || !same_string(saved_state.callsign, state.callsign)) {
331 Log.d(TAG, "update callsign");
332 mCallsignView.setText(state.callsign);
334 if (saved_state == null || state.serial != saved_state.serial) {
335 Log.d(TAG, "update serial");
336 mSerialView.setText(String.format("%d", state.serial));
338 if (saved_state == null || state.flight != saved_state.flight) {
339 Log.d(TAG, "update flight");
340 mFlightView.setText(String.format("%d", state.flight));
342 if (saved_state == null || state.state != saved_state.state) {
343 Log.d(TAG, "update state");
344 if (state.state == AltosLib.ao_flight_stateless) {
345 mStateLayout.setVisibility(View.GONE);
347 mStateView.setText(state.state_name());
348 mStateLayout.setVisibility(View.VISIBLE);
351 if (saved_state == null || state.rssi != saved_state.rssi) {
352 Log.d(TAG, "update rssi");
353 mRSSIView.setText(String.format("%d", state.rssi));
357 for (AltosDroidTab mTab : mTabs)
358 mTab.update_ui(state, from_receiver, location, mTab == mTabsAdapter.currentItem());
361 mAltosVoice.tell(state, from_receiver);
366 private void onTimerTick() {
368 mMessenger.send(Message.obtain(null, MSG_UPDATE_AGE));
369 } catch (RemoteException e) {
373 static String pos(double p, String pos, String neg) {
375 if (p == AltosLib.MISSING)
381 int deg = (int) Math.floor(p);
382 double min = (p - Math.floor(p)) * 60.0;
383 return String.format("%d°%9.4f\" %s", deg, min, h);
386 static String number(String format, double value) {
387 if (value == AltosLib.MISSING)
389 return String.format(format, value);
392 static String integer(String format, int value) {
393 if (value == AltosLib.MISSING)
395 return String.format(format, value);
399 public void onCreate(Bundle savedInstanceState) {
400 super.onCreate(savedInstanceState);
401 if(D) Log.e(TAG, "+++ ON CREATE +++");
403 // Get local Bluetooth adapter
404 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
406 // If the adapter is null, then Bluetooth is not supported
407 if (mBluetoothAdapter == null) {
408 Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
412 fm = getSupportFragmentManager();
414 // Set up the window layout
415 requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
416 setContentView(R.layout.altosdroid);
417 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
419 // Create the Tabs and ViewPager
420 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
423 mViewPager = (AltosViewPager)findViewById(R.id.pager);
424 mViewPager.setOffscreenPageLimit(4);
426 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
428 mTabsAdapter.addTab(mTabHost.newTabSpec("pad").setIndicator("Pad"), TabPad.class, null);
429 mTabsAdapter.addTab(mTabHost.newTabSpec("ascent").setIndicator("Ascent"), TabAscent.class, null);
430 mTabsAdapter.addTab(mTabHost.newTabSpec("descent").setIndicator("Descent"), TabDescent.class, null);
431 mTabsAdapter.addTab(mTabHost.newTabSpec("landed").setIndicator("Landed"), TabLanded.class, null);
432 mTabsAdapter.addTab(mTabHost.newTabSpec("map").setIndicator("Map"), TabMap.class, null);
435 // Scale the size of the Tab bar for different screen densities
436 // This probably won't be needed when we start supporting ICS+ tabs.
437 DisplayMetrics metrics = new DisplayMetrics();
438 getWindowManager().getDefaultDisplay().getMetrics(metrics);
439 int density = metrics.densityDpi;
441 if (density==DisplayMetrics.DENSITY_XHIGH)
443 else if (density==DisplayMetrics.DENSITY_HIGH)
445 else if (density==DisplayMetrics.DENSITY_MEDIUM)
447 else if (density==DisplayMetrics.DENSITY_LOW)
452 for (int i = 0; i < 5; i++)
453 mTabHost.getTabWidget().getChildAt(i).getLayoutParams().height = tabHeight;
455 // Set up the custom title
456 mTitle = (TextView) findViewById(R.id.title_left_text);
457 mTitle.setText(R.string.app_name);
458 mTitle = (TextView) findViewById(R.id.title_right_text);
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);
474 mAltosVoice = new AltosVoice(this);
478 public void onStart() {
480 if(D) Log.e(TAG, "++ ON START ++");
482 // Start Telemetry Service
483 startService(new Intent(AltosDroid.this, TelemetryService.class));
485 if (!mBluetoothAdapter.isEnabled()) {
486 Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
487 startActivityForResult(enableIntent, AltosDroid.REQUEST_ENABLE_BT);
495 public synchronized void onResume() {
497 if(D) Log.e(TAG, "+ ON RESUME +");
501 public synchronized void onPause() {
503 if(D) Log.e(TAG, "- ON PAUSE -");
507 public void onStop() {
509 if(D) Log.e(TAG, "-- ON STOP --");
515 public void onDestroy() {
517 if(D) Log.e(TAG, "--- ON DESTROY ---");
519 if (mAltosVoice != null) mAltosVoice.stop();
523 public void onActivityResult(int requestCode, int resultCode, Intent data) {
524 if(D) Log.d(TAG, "onActivityResult " + resultCode);
525 switch (requestCode) {
526 case REQUEST_CONNECT_DEVICE:
527 // When DeviceListActivity returns with a device to connect to
528 if (resultCode == Activity.RESULT_OK) {
532 case REQUEST_ENABLE_BT:
533 // When the request to enable Bluetooth returns
534 if (resultCode == Activity.RESULT_OK) {
535 // Bluetooth is now enabled, so set up a chat session
538 // User did not enable Bluetooth or an error occured
539 Log.e(TAG, "BT not enabled");
540 stopService(new Intent(AltosDroid.this, TelemetryService.class));
541 Toast.makeText(this, R.string.bt_not_enabled, Toast.LENGTH_SHORT).show();
548 private void connectDevice(String address) {
549 // Attempt to connect to the device
551 if (D) Log.d(TAG, "Connecting to " + address);
552 mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, address));
553 } catch (RemoteException e) {
557 private void connectDevice(Intent data) {
558 // Get the device MAC address
559 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
560 connectDevice(address);
564 public boolean onCreateOptionsMenu(Menu menu) {
565 MenuInflater inflater = getMenuInflater();
566 inflater.inflate(R.menu.option_menu, menu);
570 void setFrequency(double freq) {
572 mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
573 } catch (RemoteException e) {
577 void setFrequency(String freq) {
579 setFrequency (Double.parseDouble(freq.substring(11, 17)));
580 } catch (NumberFormatException e) {
584 void setBaud(int baud) {
586 mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD, baud));
587 } catch (RemoteException e) {
591 void setBaud(String baud) {
593 int value = Integer.parseInt(baud);
594 int rate = AltosLib.ao_telemetry_rate_38400;
597 rate = AltosLib.ao_telemetry_rate_2400;
600 rate = AltosLib.ao_telemetry_rate_9600;
603 rate = AltosLib.ao_telemetry_rate_38400;
607 } catch (NumberFormatException e) {
612 public boolean onOptionsItemSelected(MenuItem item) {
613 Intent serverIntent = null;
614 switch (item.getItemId()) {
615 case R.id.connect_scan:
616 // Launch the DeviceListActivity to see devices and do scan
617 serverIntent = new Intent(this, DeviceListActivity.class);
618 startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
621 Log.d(TAG, "R.id.quit");
622 stopService(new Intent(AltosDroid.this, TelemetryService.class));
625 case R.id.select_freq:
626 // Set the TBT radio frequency
628 final String[] frequencies = {
629 "Channel 0 (434.550MHz)",
630 "Channel 1 (434.650MHz)",
631 "Channel 2 (434.750MHz)",
632 "Channel 3 (434.850MHz)",
633 "Channel 4 (434.950MHz)",
634 "Channel 5 (435.050MHz)",
635 "Channel 6 (435.150MHz)",
636 "Channel 7 (435.250MHz)",
637 "Channel 8 (435.350MHz)",
638 "Channel 9 (435.450MHz)"
641 AlertDialog.Builder builder_freq = new AlertDialog.Builder(this);
642 builder_freq.setTitle("Pick a frequency");
643 builder_freq.setItems(frequencies,
644 new DialogInterface.OnClickListener() {
645 public void onClick(DialogInterface dialog, int item) {
646 setFrequency(frequencies[item]);
649 AlertDialog alert_freq = builder_freq.create();
652 case R.id.select_rate:
653 // Set the TBT baud rate
655 final String[] rates = {
661 AlertDialog.Builder builder_rate = new AlertDialog.Builder(this);
662 builder_rate.setTitle("Pick a baud rate");
663 builder_rate.setItems(rates,
664 new DialogInterface.OnClickListener() {
665 public void onClick(DialogInterface dialog, int item) {
666 setBaud(rates[item]);
669 AlertDialog alert_rate = builder_rate.create();
672 case R.id.change_units:
673 boolean imperial = AltosPreferences.imperial_units();
674 AltosPreferences.set_imperial_units(!imperial);