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.widget.TabHost;
48 import android.widget.TextView;
49 import android.widget.Toast;
50 import android.app.AlertDialog;
51 import android.location.Location;
53 import org.altusmetrum.altoslib_5.*;
55 public class AltosDroid extends FragmentActivity {
57 static final String TAG = "AltosDroid";
58 static final boolean D = true;
60 // Message types received by our Handler
61 public static final int MSG_STATE_CHANGE = 1;
62 public static final int MSG_TELEMETRY = 2;
63 public static final int MSG_UPDATE_AGE = 3;
64 public static final int MSG_LOCATION = 4;
65 public static final int MSG_CRC_ERROR = 5;
67 // Intent request codes
68 private static final int REQUEST_CONNECT_DEVICE = 1;
69 private static final int REQUEST_ENABLE_BT = 2;
71 public static FragmentManager fm;
74 private TextView mTitle;
76 // Flight state values
77 private TextView mCallsignView;
78 private TextView mRSSIView;
79 private TextView mSerialView;
80 private TextView mFlightView;
81 private TextView mStateView;
82 private TextView mAgeView;
84 // field to display the version at the bottom of the screen
85 private TextView mVersion;
89 AltosViewPager mViewPager;
90 TabsAdapter mTabsAdapter;
91 ArrayList<AltosDroidTab> mTabs = new ArrayList<AltosDroidTab>();
94 // Timer and Saved flight state for Age calculation
95 private Timer timer = new Timer();
96 AltosState saved_state;
97 Location saved_location;
100 private boolean mIsBound = false;
101 private Messenger mService = null;
102 final Messenger mMessenger = new Messenger(new IncomingHandler(this));
104 // TeleBT Config data
105 private AltosConfigData mConfigData = null;
106 // Local Bluetooth adapter
107 private BluetoothAdapter mBluetoothAdapter = null;
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();
121 case MSG_STATE_CHANGE:
122 if(D) Log.d(TAG, "MSG_STATE_CHANGE: " + msg.arg1);
124 case TelemetryService.STATE_CONNECTED:
125 ad.mConfigData = (AltosConfigData) msg.obj;
126 String str = String.format(" %s S/N: %d", ad.mConfigData.product, ad.mConfigData.serial);
127 ad.mTitle.setText(R.string.title_connected_to);
128 ad.mTitle.append(str);
129 Toast.makeText(ad.getApplicationContext(), "Connected to " + str, Toast.LENGTH_SHORT).show();
131 case TelemetryService.STATE_CONNECTING:
132 ad.mTitle.setText(R.string.title_connecting);
134 case TelemetryService.STATE_READY:
135 case TelemetryService.STATE_NONE:
136 ad.mConfigData = null;
137 ad.mTitle.setText(R.string.title_not_connected);
142 ad.update_ui((AltosState) msg.obj);
145 ad.set_location((Location) msg.obj);
150 if (ad.saved_state != null) {
151 ad.mAgeView.setText(String.format("%d", (System.currentTimeMillis() - ad.saved_state.received_time + 500) / 1000));
159 private ServiceConnection mConnection = new ServiceConnection() {
160 public void onServiceConnected(ComponentName className, IBinder service) {
161 mService = new Messenger(service);
163 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
164 msg.replyTo = mMessenger;
166 } catch (RemoteException e) {
167 // In this case the service has crashed before we could even do anything with it
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 void set_location(Location location) {
209 saved_location = location;
210 Log.d(TAG, "set_location");
211 update_ui(saved_state);
214 boolean same_string(String a, String b) {
226 void update_ui(AltosState state) {
228 Log.d(TAG, "update_ui");
229 if (state != null && saved_state != null) {
230 if (saved_state.state != state.state) {
231 String currentTab = mTabHost.getCurrentTabTag();
232 Log.d(TAG, "switch state");
233 switch (state.state) {
234 case AltosLib.ao_flight_boost:
235 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("ascent");
237 case AltosLib.ao_flight_drogue:
238 if (currentTab.equals("ascent")) mTabHost.setCurrentTabByTag("descent");
240 case AltosLib.ao_flight_landed:
241 if (currentTab.equals("descent")) mTabHost.setCurrentTabByTag("landed");
247 AltosGreatCircle from_receiver = null;
249 if (state != null && saved_location != null && state.gps != null && state.gps.locked) {
251 if (saved_location.hasAltitude())
252 altitude = saved_location.getAltitude();
253 from_receiver = new AltosGreatCircle(saved_location.getLatitude(),
254 saved_location.getLongitude(),
262 if (saved_state == null || !same_string(saved_state.callsign, state.callsign)) {
263 Log.d(TAG, "update callsign");
264 mCallsignView.setText(state.callsign);
266 if (saved_state == null || state.serial != saved_state.serial) {
267 Log.d(TAG, "update serial");
268 mSerialView.setText(String.format("%d", state.serial));
270 if (saved_state == null || state.flight != saved_state.flight) {
271 Log.d(TAG, "update flight");
272 mFlightView.setText(String.format("%d", state.flight));
274 if (saved_state == null || state.state != saved_state.state) {
275 Log.d(TAG, "update state");
276 mStateView.setText(state.state_name());
278 if (saved_state == null || state.rssi != saved_state.rssi) {
279 Log.d(TAG, "update rssi");
280 mRSSIView.setText(String.format("%d", state.rssi));
284 for (AltosDroidTab mTab : mTabs)
285 mTab.update_ui(state, from_receiver, saved_location, mTab == mTabsAdapter.currentItem());
288 mAltosVoice.tell(state);
293 private void onTimerTick() {
295 mMessenger.send(Message.obtain(null, MSG_UPDATE_AGE));
296 } catch (RemoteException e) {
300 static String pos(double p, String pos, String neg) {
302 if (p == AltosLib.MISSING)
308 int deg = (int) Math.floor(p);
309 double min = (p - Math.floor(p)) * 60.0;
310 return String.format("%d°%9.4f\" %s", deg, min, h);
313 static String number(String format, double value) {
314 if (value == AltosLib.MISSING)
316 return String.format(format, value);
319 static String integer(String format, int value) {
320 if (value == AltosLib.MISSING)
322 return String.format(format, value);
326 public void onCreate(Bundle savedInstanceState) {
327 super.onCreate(savedInstanceState);
328 if(D) Log.e(TAG, "+++ ON CREATE +++");
330 fm = getSupportFragmentManager();
332 // Get local Bluetooth adapter
333 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
335 // If the adapter is null, then Bluetooth is not supported
336 if (mBluetoothAdapter == null) {
337 Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
342 // Initialise preferences
343 AltosDroidPreferences.init(this);
345 // Set up the window layout
346 requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
347 setContentView(R.layout.altosdroid);
348 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
350 // Create the Tabs and ViewPager
351 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
354 mViewPager = (AltosViewPager)findViewById(R.id.pager);
355 mViewPager.setOffscreenPageLimit(4);
357 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
359 mTabsAdapter.addTab(mTabHost.newTabSpec("pad").setIndicator("Pad"), TabPad.class, null);
360 mTabsAdapter.addTab(mTabHost.newTabSpec("ascent").setIndicator("Ascent"), TabAscent.class, null);
361 mTabsAdapter.addTab(mTabHost.newTabSpec("descent").setIndicator("Descent"), TabDescent.class, null);
362 mTabsAdapter.addTab(mTabHost.newTabSpec("landed").setIndicator("Landed"), TabLanded.class, null);
363 mTabsAdapter.addTab(mTabHost.newTabSpec("map").setIndicator("Map"), TabMap.class, null);
366 // Scale the size of the Tab bar for different screen densities
367 // This probably won't be needed when we start supporting ICS+ tabs.
368 DisplayMetrics metrics = new DisplayMetrics();
369 getWindowManager().getDefaultDisplay().getMetrics(metrics);
370 int density = metrics.densityDpi;
372 if (density==DisplayMetrics.DENSITY_XHIGH)
374 else if (density==DisplayMetrics.DENSITY_HIGH)
376 else if (density==DisplayMetrics.DENSITY_MEDIUM)
378 else if (density==DisplayMetrics.DENSITY_LOW)
383 for (int i = 0; i < 5; i++)
384 mTabHost.getTabWidget().getChildAt(i).getLayoutParams().height = tabHeight;
387 // Set up the custom title
388 mTitle = (TextView) findViewById(R.id.title_left_text);
389 mTitle.setText(R.string.app_name);
390 mTitle = (TextView) findViewById(R.id.title_right_text);
392 // Display the Version
393 mVersion = (TextView) findViewById(R.id.version);
394 mVersion.setText("Version: " + BuildInfo.version +
395 " Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
396 " (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
398 mCallsignView = (TextView) findViewById(R.id.callsign_value);
399 mRSSIView = (TextView) findViewById(R.id.rssi_value);
400 mSerialView = (TextView) findViewById(R.id.serial_value);
401 mFlightView = (TextView) findViewById(R.id.flight_value);
402 mStateView = (TextView) findViewById(R.id.state_value);
403 mAgeView = (TextView) findViewById(R.id.age_value);
405 timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 1000L, 100L);
407 mAltosVoice = new AltosVoice(this);
411 public void onStart() {
413 if(D) Log.e(TAG, "++ ON START ++");
415 if (!mBluetoothAdapter.isEnabled()) {
416 Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
417 startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
420 // Start Telemetry Service
421 startService(new Intent(AltosDroid.this, TelemetryService.class));
427 public synchronized void onResume() {
429 if(D) Log.e(TAG, "+ ON RESUME +");
433 public synchronized void onPause() {
435 if(D) Log.e(TAG, "- ON PAUSE -");
439 public void onStop() {
441 if(D) Log.e(TAG, "-- ON STOP --");
447 public void onDestroy() {
449 if(D) Log.e(TAG, "--- ON DESTROY ---");
451 if (mAltosVoice != null) mAltosVoice.stop();
454 public void onActivityResult(int requestCode, int resultCode, Intent data) {
455 if(D) Log.d(TAG, "onActivityResult " + resultCode);
456 switch (requestCode) {
457 case REQUEST_CONNECT_DEVICE:
458 // When DeviceListActivity returns with a device to connect to
459 if (resultCode == Activity.RESULT_OK) {
463 case REQUEST_ENABLE_BT:
464 // When the request to enable Bluetooth returns
465 if (resultCode == Activity.RESULT_OK) {
466 // Bluetooth is now enabled, so set up a chat session
469 // User did not enable Bluetooth or an error occured
470 Log.e(TAG, "BT not enabled");
471 stopService(new Intent(AltosDroid.this, TelemetryService.class));
472 Toast.makeText(this, R.string.bt_not_enabled, Toast.LENGTH_SHORT).show();
479 private void connectDevice(String address) {
480 // Get the BLuetoothDevice object
481 BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
482 // Attempt to connect to the device
484 if (D) Log.d(TAG, "Connecting to " + device.getName());
485 mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, device));
486 } catch (RemoteException e) {
490 private void connectDevice(Intent data) {
491 // Get the device MAC address
492 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
493 connectDevice(address);
497 public boolean onCreateOptionsMenu(Menu menu) {
498 MenuInflater inflater = getMenuInflater();
499 inflater.inflate(R.menu.option_menu, menu);
503 void setFrequency(double freq) {
505 mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
506 } catch (RemoteException e) {
510 void setFrequency(String freq) {
512 setFrequency (Double.parseDouble(freq.substring(11, 17)));
513 } catch (NumberFormatException e) {
517 void setBaud(int baud) {
519 mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD, baud));
520 } catch (RemoteException e) {
524 void setBaud(String baud) {
526 int value = Integer.parseInt(baud);
527 int rate = AltosLib.ao_telemetry_rate_38400;
530 rate = AltosLib.ao_telemetry_rate_2400;
533 rate = AltosLib.ao_telemetry_rate_9600;
536 rate = AltosLib.ao_telemetry_rate_38400;
540 } catch (NumberFormatException e) {
545 public boolean onOptionsItemSelected(MenuItem item) {
546 Intent serverIntent = null;
547 switch (item.getItemId()) {
548 case R.id.connect_scan:
549 // Launch the DeviceListActivity to see devices and do scan
550 serverIntent = new Intent(this, DeviceListActivity.class);
551 startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
553 case R.id.select_freq:
554 // Set the TBT radio frequency
556 final String[] frequencies = {
557 "Channel 0 (434.550MHz)",
558 "Channel 1 (434.650MHz)",
559 "Channel 2 (434.750MHz)",
560 "Channel 3 (434.850MHz)",
561 "Channel 4 (434.950MHz)",
562 "Channel 5 (435.050MHz)",
563 "Channel 6 (435.150MHz)",
564 "Channel 7 (435.250MHz)",
565 "Channel 8 (435.350MHz)",
566 "Channel 9 (435.450MHz)"
569 AlertDialog.Builder builder_freq = new AlertDialog.Builder(this);
570 builder_freq.setTitle("Pick a frequency");
571 builder_freq.setItems(frequencies,
572 new DialogInterface.OnClickListener() {
573 public void onClick(DialogInterface dialog, int item) {
574 setFrequency(frequencies[item]);
577 AlertDialog alert_freq = builder_freq.create();
580 case R.id.select_rate:
581 // Set the TBT baud rate
583 final String[] rates = {
589 AlertDialog.Builder builder_rate = new AlertDialog.Builder(this);
590 builder_rate.setTitle("Pick a baud rate");
591 builder_rate.setItems(rates,
592 new DialogInterface.OnClickListener() {
593 public void onClick(DialogInterface dialog, int item) {
594 setBaud(rates[item]);
597 AlertDialog alert_rate = builder_rate.create();