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));
105 private AltosDroidPreferences prefs = null;
107 // TeleBT Config data
108 private AltosConfigData mConfigData = null;
109 // Local Bluetooth adapter
110 private BluetoothAdapter mBluetoothAdapter = null;
113 private AltosVoice mAltosVoice = null;
115 // The Handler that gets information back from the Telemetry Service
116 static class IncomingHandler extends Handler {
117 private final WeakReference<AltosDroid> mAltosDroid;
118 IncomingHandler(AltosDroid ad) { mAltosDroid = new WeakReference<AltosDroid>(ad); }
121 public void handleMessage(Message msg) {
122 AltosDroid ad = mAltosDroid.get();
124 case MSG_STATE_CHANGE:
125 if(D) Log.d(TAG, "MSG_STATE_CHANGE: " + msg.arg1);
127 case TelemetryService.STATE_CONNECTED:
128 ad.mConfigData = (AltosConfigData) msg.obj;
129 String str = String.format(" %s S/N: %d", ad.mConfigData.product, ad.mConfigData.serial);
130 ad.mTitle.setText(R.string.title_connected_to);
131 ad.mTitle.append(str);
132 Toast.makeText(ad.getApplicationContext(), "Connected to " + str, Toast.LENGTH_SHORT).show();
134 case TelemetryService.STATE_CONNECTING:
135 ad.mTitle.setText(R.string.title_connecting);
137 case TelemetryService.STATE_READY:
138 case TelemetryService.STATE_NONE:
139 ad.mConfigData = null;
140 ad.mTitle.setText(R.string.title_not_connected);
145 ad.update_ui((AltosState) msg.obj);
148 ad.set_location((Location) msg.obj);
153 if (ad.saved_state != null) {
154 ad.mAgeView.setText(String.format("%d", (System.currentTimeMillis() - ad.saved_state.received_time + 500) / 1000));
162 private ServiceConnection mConnection = new ServiceConnection() {
163 public void onServiceConnected(ComponentName className, IBinder service) {
164 mService = new Messenger(service);
166 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
167 msg.replyTo = mMessenger;
169 } catch (RemoteException e) {
170 // In this case the service has crashed before we could even do anything with it
174 public void onServiceDisconnected(ComponentName className) {
175 // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
180 void doBindService() {
181 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
185 void doUnbindService() {
187 // If we have received the service, and hence registered with it, then now is the time to unregister.
188 if (mService != null) {
190 Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
191 msg.replyTo = mMessenger;
193 } catch (RemoteException e) {
194 // There is nothing special we need to do if the service has crashed.
197 // Detach our existing connection.
198 unbindService(mConnection);
203 public void registerTab(AltosDroidTab mTab) {
207 public void unregisterTab(AltosDroidTab mTab) {
211 void set_location(Location location) {
212 saved_location = location;
213 Log.d(TAG, "set_location");
214 update_ui(saved_state);
217 boolean same_string(String a, String b) {
229 void update_ui(AltosState state) {
231 Log.d(TAG, "update_ui");
232 if (state != null && saved_state != null) {
233 if (saved_state.state != state.state) {
234 String currentTab = mTabHost.getCurrentTabTag();
235 Log.d(TAG, "switch state");
236 switch (state.state) {
237 case AltosLib.ao_flight_boost:
238 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("ascent");
240 case AltosLib.ao_flight_drogue:
241 if (currentTab.equals("ascent")) mTabHost.setCurrentTabByTag("descent");
243 case AltosLib.ao_flight_landed:
244 if (currentTab.equals("descent")) mTabHost.setCurrentTabByTag("landed");
250 AltosGreatCircle from_receiver = null;
252 if (state != null && saved_location != null && state.gps != null && state.gps.locked) {
254 if (saved_location.hasAltitude())
255 altitude = saved_location.getAltitude();
256 from_receiver = new AltosGreatCircle(saved_location.getLatitude(),
257 saved_location.getLongitude(),
265 if (saved_state == null || !same_string(saved_state.callsign, state.callsign)) {
266 Log.d(TAG, "update callsign");
267 mCallsignView.setText(state.callsign);
269 if (saved_state == null || state.serial != saved_state.serial) {
270 Log.d(TAG, "update serial");
271 mSerialView.setText(String.format("%d", state.serial));
273 if (saved_state == null || state.flight != saved_state.flight) {
274 Log.d(TAG, "update flight");
275 mFlightView.setText(String.format("%d", state.flight));
277 if (saved_state == null || state.state != saved_state.state) {
278 Log.d(TAG, "update state");
279 mStateView.setText(state.state_name());
281 if (saved_state == null || state.rssi != saved_state.rssi) {
282 Log.d(TAG, "update rssi");
283 mRSSIView.setText(String.format("%d", state.rssi));
287 for (AltosDroidTab mTab : mTabs)
288 mTab.update_ui(state, from_receiver, saved_location, mTab == mTabsAdapter.currentItem());
291 mAltosVoice.tell(state);
296 private void onTimerTick() {
298 mMessenger.send(Message.obtain(null, MSG_UPDATE_AGE));
299 } catch (RemoteException e) {
303 static String pos(double p, String pos, String neg) {
305 if (p == AltosLib.MISSING)
311 int deg = (int) Math.floor(p);
312 double min = (p - Math.floor(p)) * 60.0;
313 return String.format("%d°%9.4f\" %s", deg, min, h);
316 static String number(String format, double value) {
317 if (value == AltosLib.MISSING)
319 return String.format(format, value);
322 static String integer(String format, int value) {
323 if (value == AltosLib.MISSING)
325 return String.format(format, value);
329 public void onCreate(Bundle savedInstanceState) {
330 super.onCreate(savedInstanceState);
331 if(D) Log.e(TAG, "+++ ON CREATE +++");
333 fm = getSupportFragmentManager();
335 // Get local Bluetooth adapter
336 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
338 // If the adapter is null, then Bluetooth is not supported
339 if (mBluetoothAdapter == null) {
340 Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
345 // Initialise preferences
346 prefs = new AltosDroidPreferences(this);
347 AltosPreferences.init(prefs);
349 // Set up the window layout
350 requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
351 setContentView(R.layout.altosdroid);
352 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
354 // Create the Tabs and ViewPager
355 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
358 mViewPager = (AltosViewPager)findViewById(R.id.pager);
359 mViewPager.setOffscreenPageLimit(4);
361 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
363 mTabsAdapter.addTab(mTabHost.newTabSpec("pad").setIndicator("Pad"), TabPad.class, null);
364 mTabsAdapter.addTab(mTabHost.newTabSpec("ascent").setIndicator("Ascent"), TabAscent.class, null);
365 mTabsAdapter.addTab(mTabHost.newTabSpec("descent").setIndicator("Descent"), TabDescent.class, null);
366 mTabsAdapter.addTab(mTabHost.newTabSpec("landed").setIndicator("Landed"), TabLanded.class, null);
367 mTabsAdapter.addTab(mTabHost.newTabSpec("map").setIndicator("Map"), TabMap.class, null);
370 // Scale the size of the Tab bar for different screen densities
371 // This probably won't be needed when we start supporting ICS+ tabs.
372 DisplayMetrics metrics = new DisplayMetrics();
373 getWindowManager().getDefaultDisplay().getMetrics(metrics);
374 int density = metrics.densityDpi;
376 if (density==DisplayMetrics.DENSITY_XHIGH)
378 else if (density==DisplayMetrics.DENSITY_HIGH)
380 else if (density==DisplayMetrics.DENSITY_MEDIUM)
382 else if (density==DisplayMetrics.DENSITY_LOW)
387 for (int i = 0; i < 5; i++)
388 mTabHost.getTabWidget().getChildAt(i).getLayoutParams().height = tabHeight;
391 // Set up the custom title
392 mTitle = (TextView) findViewById(R.id.title_left_text);
393 mTitle.setText(R.string.app_name);
394 mTitle = (TextView) findViewById(R.id.title_right_text);
396 // Display the Version
397 mVersion = (TextView) findViewById(R.id.version);
398 mVersion.setText("Version: " + BuildInfo.version +
399 " Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
400 " (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
402 mCallsignView = (TextView) findViewById(R.id.callsign_value);
403 mRSSIView = (TextView) findViewById(R.id.rssi_value);
404 mSerialView = (TextView) findViewById(R.id.serial_value);
405 mFlightView = (TextView) findViewById(R.id.flight_value);
406 mStateView = (TextView) findViewById(R.id.state_value);
407 mAgeView = (TextView) findViewById(R.id.age_value);
409 timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 1000L, 100L);
411 mAltosVoice = new AltosVoice(this);
415 public void onStart() {
417 if(D) Log.e(TAG, "++ ON START ++");
419 if (!mBluetoothAdapter.isEnabled()) {
420 Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
421 startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
424 // Start Telemetry Service
425 startService(new Intent(AltosDroid.this, TelemetryService.class));
431 public synchronized void onResume() {
433 if(D) Log.e(TAG, "+ ON RESUME +");
437 public synchronized void onPause() {
439 if(D) Log.e(TAG, "- ON PAUSE -");
443 public void onStop() {
445 if(D) Log.e(TAG, "-- ON STOP --");
451 public void onDestroy() {
453 if(D) Log.e(TAG, "--- ON DESTROY ---");
455 if (mAltosVoice != null) mAltosVoice.stop();
458 public void onActivityResult(int requestCode, int resultCode, Intent data) {
459 if(D) Log.d(TAG, "onActivityResult " + resultCode);
460 switch (requestCode) {
461 case REQUEST_CONNECT_DEVICE:
462 // When DeviceListActivity returns with a device to connect to
463 if (resultCode == Activity.RESULT_OK) {
467 case REQUEST_ENABLE_BT:
468 // When the request to enable Bluetooth returns
469 if (resultCode == Activity.RESULT_OK) {
470 // Bluetooth is now enabled, so set up a chat session
473 // User did not enable Bluetooth or an error occured
474 Log.e(TAG, "BT not enabled");
475 stopService(new Intent(AltosDroid.this, TelemetryService.class));
476 Toast.makeText(this, R.string.bt_not_enabled, Toast.LENGTH_SHORT).show();
483 private void connectDevice(Intent data) {
484 // Get the device MAC address
485 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
486 // Get the BLuetoothDevice object
487 BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
488 // Attempt to connect to the device
490 if (D) Log.d(TAG, "Connecting to " + device.getName());
491 mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, device));
492 } catch (RemoteException e) {
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();