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 {
59 static final String TAG = "AltosDroid";
60 static final boolean D = true;
62 // Message types received by our Handler
63 public static final int MSG_STATE_CHANGE = 1;
64 public static final int MSG_TELEMETRY = 2;
65 public static final int MSG_UPDATE_AGE = 3;
66 public static final int MSG_LOCATION = 4;
67 public static final int MSG_CRC_ERROR = 5;
68 public static final int MSG_FREQUENCY = 6;
69 public static final int MSG_TELEMETRY_RATE = 7;
71 // Intent request codes
72 private static final int REQUEST_CONNECT_DEVICE = 1;
73 private static final int REQUEST_ENABLE_BT = 2;
75 public static FragmentManager fm;
78 private TextView mTitle;
80 // Flight state values
81 private TextView mCallsignView;
82 private TextView mRSSIView;
83 private TextView mSerialView;
84 private TextView mFlightView;
85 private RelativeLayout mStateLayout;
86 private TextView mStateView;
87 private TextView mAgeView;
89 // field to display the version at the bottom of the screen
90 private TextView mVersion;
92 private double frequency;
93 private int telemetry_rate;
97 AltosViewPager mViewPager;
98 TabsAdapter mTabsAdapter;
99 ArrayList<AltosDroidTab> mTabs = new ArrayList<AltosDroidTab>();
102 // Timer and Saved flight state for Age calculation
103 private Timer timer = new Timer();
104 AltosState saved_state;
105 Location saved_location;
108 private boolean mIsBound = false;
109 private Messenger mService = null;
110 final Messenger mMessenger = new Messenger(new IncomingHandler(this));
112 // TeleBT Config data
113 private AltosConfigData mConfigData = null;
114 // Local Bluetooth adapter
115 private BluetoothAdapter mBluetoothAdapter = null;
118 private AltosVoice mAltosVoice = null;
120 // The Handler that gets information back from the Telemetry Service
121 static class IncomingHandler extends Handler {
122 private final WeakReference<AltosDroid> mAltosDroid;
123 IncomingHandler(AltosDroid ad) { mAltosDroid = new WeakReference<AltosDroid>(ad); }
126 public void handleMessage(Message msg) {
127 AltosDroid ad = mAltosDroid.get();
129 case MSG_STATE_CHANGE:
130 if(D) Log.d(TAG, "MSG_STATE_CHANGE: " + msg.arg1);
132 case TelemetryService.STATE_CONNECTED:
133 ad.set_config_data((AltosConfigData) msg.obj);
135 case TelemetryService.STATE_CONNECTING:
136 ad.mTitle.setText(R.string.title_connecting);
138 case TelemetryService.STATE_READY:
139 case TelemetryService.STATE_NONE:
140 ad.mConfigData = null;
141 ad.mTitle.setText(R.string.title_not_connected);
142 String active_device = AltosDroidPreferences.active_device();
143 if (active_device != null)
144 ad.connectDevice(active_device);
149 ad.update_ui((AltosState) msg.obj);
152 ad.set_location((Location) msg.obj);
157 if (ad.saved_state != null) {
158 ad.mAgeView.setText(String.format("%d", (System.currentTimeMillis() - ad.saved_state.received_time + 500) / 1000));
162 ad.set_frequency((Double) msg.obj);
164 case MSG_TELEMETRY_RATE:
165 ad.set_telemetry_rate((Integer) msg.obj);
172 private ServiceConnection mConnection = new ServiceConnection() {
173 public void onServiceConnected(ComponentName className, IBinder service) {
174 mService = new Messenger(service);
176 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
177 msg.replyTo = mMessenger;
179 } catch (RemoteException e) {
180 // In this case the service has crashed before we could even do anything with it
184 public void onServiceDisconnected(ComponentName className) {
185 // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
190 void doBindService() {
191 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
195 void doUnbindService() {
197 // If we have received the service, and hence registered with it, then now is the time to unregister.
198 if (mService != null) {
200 Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
201 msg.replyTo = mMessenger;
203 } catch (RemoteException e) {
204 // There is nothing special we need to do if the service has crashed.
207 // Detach our existing connection.
208 unbindService(mConnection);
213 public void registerTab(AltosDroidTab mTab) {
217 public void unregisterTab(AltosDroidTab mTab) {
221 void set_location(Location location) {
222 saved_location = location;
223 Log.d(TAG, "set_location");
224 update_ui(saved_state);
228 if (mConfigData != null) {
229 String str = String.format("S/N %d %6.3f MHz", mConfigData.serial, frequency);
231 if (telemetry_rate != AltosLib.ao_telemetry_rate_38400)
232 str = str.concat(String.format(" %d bps", AltosLib.ao_telemetry_rate_values[telemetry_rate]));
237 void set_frequency(double frequency) {
238 if (D) Log.d(TAG, String.format("AltosDroid: set_frequency %f\n", frequency));
239 this.frequency = frequency;
243 void set_telemetry_rate(int telemetry_rate) {
244 if (D) Log.d(TAG, String.format("AltosDroid: set_telemetry_rate %d\n", telemetry_rate));
245 this.telemetry_rate = telemetry_rate;
249 void set_config_data(AltosConfigData config_data) {
250 mConfigData = config_data;
254 boolean same_string(String a, String b) {
266 void update_ui(AltosState state) {
268 Log.d(TAG, "update_ui");
270 int prev_state = AltosLib.ao_flight_invalid;
272 if (saved_state != null)
273 prev_state = saved_state.state;
276 Log.d(TAG, String.format("prev state %d new state %d\n", prev_state, state.state));
277 if (prev_state != state.state) {
278 String currentTab = mTabHost.getCurrentTabTag();
279 Log.d(TAG, "switch state");
280 switch (state.state) {
281 case AltosLib.ao_flight_boost:
282 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("ascent");
284 case AltosLib.ao_flight_drogue:
285 if (currentTab.equals("ascent")) mTabHost.setCurrentTabByTag("descent");
287 case AltosLib.ao_flight_landed:
288 if (currentTab.equals("descent")) mTabHost.setCurrentTabByTag("landed");
290 case AltosLib.ao_flight_stateless:
291 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("descent");
297 AltosGreatCircle from_receiver = null;
299 if (state != null && saved_location != null && state.gps != null && state.gps.locked) {
301 if (saved_location.hasAltitude())
302 altitude = saved_location.getAltitude();
303 from_receiver = new AltosGreatCircle(saved_location.getLatitude(),
304 saved_location.getLongitude(),
312 if (saved_state == null || !same_string(saved_state.callsign, state.callsign)) {
313 Log.d(TAG, "update callsign");
314 mCallsignView.setText(state.callsign);
316 if (saved_state == null || state.serial != saved_state.serial) {
317 Log.d(TAG, "update serial");
318 mSerialView.setText(String.format("%d", state.serial));
320 if (saved_state == null || state.flight != saved_state.flight) {
321 Log.d(TAG, "update flight");
322 mFlightView.setText(String.format("%d", state.flight));
324 if (saved_state == null || state.state != saved_state.state) {
325 Log.d(TAG, "update state");
326 if (state.state == AltosLib.ao_flight_stateless) {
327 mStateLayout.setVisibility(View.GONE);
329 mStateView.setText(state.state_name());
330 mStateLayout.setVisibility(View.VISIBLE);
333 if (saved_state == null || state.rssi != saved_state.rssi) {
334 Log.d(TAG, "update rssi");
335 mRSSIView.setText(String.format("%d", state.rssi));
339 for (AltosDroidTab mTab : mTabs)
340 mTab.update_ui(state, from_receiver, saved_location, mTab == mTabsAdapter.currentItem());
343 mAltosVoice.tell(state);
348 private void onTimerTick() {
350 mMessenger.send(Message.obtain(null, MSG_UPDATE_AGE));
351 } catch (RemoteException e) {
355 static String pos(double p, String pos, String neg) {
357 if (p == AltosLib.MISSING)
363 int deg = (int) Math.floor(p);
364 double min = (p - Math.floor(p)) * 60.0;
365 return String.format("%d°%9.4f\" %s", deg, min, h);
368 static String number(String format, double value) {
369 if (value == AltosLib.MISSING)
371 return String.format(format, value);
374 static String integer(String format, int value) {
375 if (value == AltosLib.MISSING)
377 return String.format(format, value);
381 public void onCreate(Bundle savedInstanceState) {
382 super.onCreate(savedInstanceState);
383 if(D) Log.e(TAG, "+++ ON CREATE +++");
385 fm = getSupportFragmentManager();
387 // Get local Bluetooth adapter
388 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
390 // If the adapter is null, then Bluetooth is not supported
391 if (mBluetoothAdapter == null) {
392 Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
397 // Initialise preferences
398 AltosDroidPreferences.init(this);
400 // Set up the window layout
401 requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
402 setContentView(R.layout.altosdroid);
403 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
405 // Create the Tabs and ViewPager
406 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
409 mViewPager = (AltosViewPager)findViewById(R.id.pager);
410 mViewPager.setOffscreenPageLimit(4);
412 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
414 mTabsAdapter.addTab(mTabHost.newTabSpec("pad").setIndicator("Pad"), TabPad.class, null);
415 mTabsAdapter.addTab(mTabHost.newTabSpec("ascent").setIndicator("Ascent"), TabAscent.class, null);
416 mTabsAdapter.addTab(mTabHost.newTabSpec("descent").setIndicator("Descent"), TabDescent.class, null);
417 mTabsAdapter.addTab(mTabHost.newTabSpec("landed").setIndicator("Landed"), TabLanded.class, null);
418 mTabsAdapter.addTab(mTabHost.newTabSpec("map").setIndicator("Map"), TabMap.class, null);
421 // Scale the size of the Tab bar for different screen densities
422 // This probably won't be needed when we start supporting ICS+ tabs.
423 DisplayMetrics metrics = new DisplayMetrics();
424 getWindowManager().getDefaultDisplay().getMetrics(metrics);
425 int density = metrics.densityDpi;
427 if (density==DisplayMetrics.DENSITY_XHIGH)
429 else if (density==DisplayMetrics.DENSITY_HIGH)
431 else if (density==DisplayMetrics.DENSITY_MEDIUM)
433 else if (density==DisplayMetrics.DENSITY_LOW)
438 for (int i = 0; i < 5; i++)
439 mTabHost.getTabWidget().getChildAt(i).getLayoutParams().height = tabHeight;
442 // Set up the custom title
443 mTitle = (TextView) findViewById(R.id.title_left_text);
444 mTitle.setText(R.string.app_name);
445 mTitle = (TextView) findViewById(R.id.title_right_text);
447 // Display the Version
448 mVersion = (TextView) findViewById(R.id.version);
449 mVersion.setText("Version: " + BuildInfo.version +
450 " Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
451 " (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
453 mCallsignView = (TextView) findViewById(R.id.callsign_value);
454 mRSSIView = (TextView) findViewById(R.id.rssi_value);
455 mSerialView = (TextView) findViewById(R.id.serial_value);
456 mFlightView = (TextView) findViewById(R.id.flight_value);
457 mStateLayout = (RelativeLayout) findViewById(R.id.state_container);
458 mStateView = (TextView) findViewById(R.id.state_value);
459 mAgeView = (TextView) findViewById(R.id.age_value);
461 timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 1000L, 100L);
463 mAltosVoice = new AltosVoice(this);
467 public void onStart() {
469 if(D) Log.e(TAG, "++ ON START ++");
471 if (!mBluetoothAdapter.isEnabled()) {
472 Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
473 startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
476 // Start Telemetry Service
477 startService(new Intent(AltosDroid.this, TelemetryService.class));
484 public synchronized void onResume() {
486 if(D) Log.e(TAG, "+ ON RESUME +");
490 public synchronized void onPause() {
492 if(D) Log.e(TAG, "- ON PAUSE -");
496 public void onStop() {
498 if(D) Log.e(TAG, "-- ON STOP --");
504 public void onDestroy() {
506 if(D) Log.e(TAG, "--- ON DESTROY ---");
508 if (mAltosVoice != null) mAltosVoice.stop();
511 public void onActivityResult(int requestCode, int resultCode, Intent data) {
512 if(D) Log.d(TAG, "onActivityResult " + resultCode);
513 switch (requestCode) {
514 case REQUEST_CONNECT_DEVICE:
515 // When DeviceListActivity returns with a device to connect to
516 if (resultCode == Activity.RESULT_OK) {
520 case REQUEST_ENABLE_BT:
521 // When the request to enable Bluetooth returns
522 if (resultCode == Activity.RESULT_OK) {
523 // Bluetooth is now enabled, so set up a chat session
526 // User did not enable Bluetooth or an error occured
527 Log.e(TAG, "BT not enabled");
528 stopService(new Intent(AltosDroid.this, TelemetryService.class));
529 Toast.makeText(this, R.string.bt_not_enabled, Toast.LENGTH_SHORT).show();
536 private void connectDevice(String address) {
537 // Get the BLuetoothDevice object
538 BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
539 // Attempt to connect to the device
541 if (D) Log.d(TAG, "Connecting to " + device.getName());
542 mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, device));
543 } catch (RemoteException e) {
547 private void connectDevice(Intent data) {
548 // Get the device MAC address
549 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
550 AltosDroidPreferences.set_active_device(address);
551 connectDevice(address);
555 public boolean onCreateOptionsMenu(Menu menu) {
556 MenuInflater inflater = getMenuInflater();
557 inflater.inflate(R.menu.option_menu, menu);
561 void setFrequency(double freq) {
563 mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
564 } catch (RemoteException e) {
568 void setFrequency(String freq) {
570 setFrequency (Double.parseDouble(freq.substring(11, 17)));
571 } catch (NumberFormatException e) {
575 void setBaud(int baud) {
577 mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD, baud));
578 } catch (RemoteException e) {
582 void setBaud(String baud) {
584 int value = Integer.parseInt(baud);
585 int rate = AltosLib.ao_telemetry_rate_38400;
588 rate = AltosLib.ao_telemetry_rate_2400;
591 rate = AltosLib.ao_telemetry_rate_9600;
594 rate = AltosLib.ao_telemetry_rate_38400;
598 } catch (NumberFormatException e) {
603 public boolean onOptionsItemSelected(MenuItem item) {
604 Intent serverIntent = null;
605 switch (item.getItemId()) {
606 case R.id.connect_scan:
607 // Launch the DeviceListActivity to see devices and do scan
608 serverIntent = new Intent(this, DeviceListActivity.class);
609 startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
612 Log.d(TAG, "R.id.quit");
613 stopService(new Intent(AltosDroid.this, TelemetryService.class));
616 case R.id.select_freq:
617 // Set the TBT radio frequency
619 final String[] frequencies = {
620 "Channel 0 (434.550MHz)",
621 "Channel 1 (434.650MHz)",
622 "Channel 2 (434.750MHz)",
623 "Channel 3 (434.850MHz)",
624 "Channel 4 (434.950MHz)",
625 "Channel 5 (435.050MHz)",
626 "Channel 6 (435.150MHz)",
627 "Channel 7 (435.250MHz)",
628 "Channel 8 (435.350MHz)",
629 "Channel 9 (435.450MHz)"
632 AlertDialog.Builder builder_freq = new AlertDialog.Builder(this);
633 builder_freq.setTitle("Pick a frequency");
634 builder_freq.setItems(frequencies,
635 new DialogInterface.OnClickListener() {
636 public void onClick(DialogInterface dialog, int item) {
637 setFrequency(frequencies[item]);
640 AlertDialog alert_freq = builder_freq.create();
643 case R.id.select_rate:
644 // Set the TBT baud rate
646 final String[] rates = {
652 AlertDialog.Builder builder_rate = new AlertDialog.Builder(this);
653 builder_rate.setTitle("Pick a baud rate");
654 builder_rate.setItems(rates,
655 new DialogInterface.OnClickListener() {
656 public void onClick(DialogInterface dialog, int item) {
657 setBaud(rates[item]);
660 AlertDialog alert_rate = builder_rate.create();