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.util.DisplayMetrics;
41 import android.util.Log;
42 import android.view.Menu;
43 import android.view.MenuInflater;
44 import android.view.MenuItem;
45 import android.view.Window;
46 import android.widget.TabHost;
47 import android.widget.TextView;
48 import android.widget.Toast;
49 import android.app.AlertDialog;
50 import android.location.Location;
52 import org.altusmetrum.altoslib_2.*;
54 public class AltosDroid extends FragmentActivity {
56 private static final String TAG = "AltosDroid";
57 private static final boolean D = true;
59 // Message types received by our Handler
60 public static final int MSG_STATE_CHANGE = 1;
61 public static final int MSG_TELEMETRY = 2;
62 public static final int MSG_UPDATE_AGE = 3;
63 public static final int MSG_LOCATION = 4;
64 public static final int MSG_CRC_ERROR = 5;
66 // Intent request codes
67 private static final int REQUEST_CONNECT_DEVICE = 1;
68 private static final int REQUEST_ENABLE_BT = 2;
71 private TextView mTitle;
73 // Flight state values
74 private TextView mCallsignView;
75 private TextView mRSSIView;
76 private TextView mSerialView;
77 private TextView mFlightView;
78 private TextView mStateView;
79 private TextView mAgeView;
81 // field to display the version at the bottom of the screen
82 private TextView mVersion;
86 AltosViewPager mViewPager;
87 TabsAdapter mTabsAdapter;
88 ArrayList<AltosDroidTab> mTabs = new ArrayList<AltosDroidTab>();
91 // Timer and Saved flight state for Age calculation
92 private Timer timer = new Timer();
93 AltosState saved_state;
94 Location saved_location;
97 private boolean mIsBound = false;
98 private Messenger mService = null;
99 final Messenger mMessenger = new Messenger(new IncomingHandler(this));
102 private AltosDroidPreferences prefs = null;
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);
149 if (ad.saved_state != null) {
150 ad.mAgeView.setText(String.format("%d", (System.currentTimeMillis() - ad.saved_state.received_time + 500) / 1000));
158 private ServiceConnection mConnection = new ServiceConnection() {
159 public void onServiceConnected(ComponentName className, IBinder service) {
160 mService = new Messenger(service);
162 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
163 msg.replyTo = mMessenger;
165 } catch (RemoteException e) {
166 // In this case the service has crashed before we could even do anything with it
170 public void onServiceDisconnected(ComponentName className) {
171 // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
176 void doBindService() {
177 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
181 void doUnbindService() {
183 // If we have received the service, and hence registered with it, then now is the time to unregister.
184 if (mService != null) {
186 Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
187 msg.replyTo = mMessenger;
189 } catch (RemoteException e) {
190 // There is nothing special we need to do if the service has crashed.
193 // Detach our existing connection.
194 unbindService(mConnection);
199 public void registerTab(AltosDroidTab mTab) {
203 public void unregisterTab(AltosDroidTab mTab) {
207 void set_location(Location location) {
208 saved_location = location;
209 update_ui(saved_state);
212 void update_ui(AltosState state) {
213 if (state != null && saved_state != null) {
214 if (saved_state.state != state.state) {
215 String currentTab = mTabHost.getCurrentTabTag();
216 switch (state.state) {
217 case AltosLib.ao_flight_boost:
218 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("ascent");
220 case AltosLib.ao_flight_drogue:
221 if (currentTab.equals("ascent")) mTabHost.setCurrentTabByTag("descent");
223 case AltosLib.ao_flight_landed:
224 if (currentTab.equals("descent")) mTabHost.setCurrentTabByTag("landed");
231 AltosGreatCircle from_receiver = null;
233 if (state != null && saved_location != null && state.gps != null && state.gps.locked) {
235 if (saved_location.hasAltitude())
236 altitude = saved_location.getAltitude();
237 from_receiver = new AltosGreatCircle(saved_location.getLatitude(),
238 saved_location.getLongitude(),
246 mCallsignView.setText(state.callsign);
247 mSerialView.setText(String.format("%d", state.serial));
248 mFlightView.setText(String.format("%d", state.flight));
249 mStateView.setText(state.state_name());
250 mRSSIView.setText(String.format("%d", state.rssi));
253 for (AltosDroidTab mTab : mTabs)
254 mTab.update_ui(state, from_receiver, saved_location);
257 mAltosVoice.tell(state);
260 private void onTimerTick() {
262 mMessenger.send(Message.obtain(null, MSG_UPDATE_AGE));
263 } catch (RemoteException e) {
267 static String pos(double p, String pos, String neg) {
269 if (p == AltosLib.MISSING)
275 int deg = (int) Math.floor(p);
276 double min = (p - Math.floor(p)) * 60.0;
277 return String.format("%d°%9.4f\" %s", deg, min, h);
280 static String number(String format, double value) {
281 if (value == AltosLib.MISSING)
283 return String.format(format, value);
286 static String integer(String format, int value) {
287 if (value == AltosLib.MISSING)
289 return String.format(format, value);
293 public void onCreate(Bundle savedInstanceState) {
294 super.onCreate(savedInstanceState);
295 if(D) Log.e(TAG, "+++ ON CREATE +++");
297 // Get local Bluetooth adapter
298 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
300 // If the adapter is null, then Bluetooth is not supported
301 if (mBluetoothAdapter == null) {
302 Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
307 // Initialise preferences
308 prefs = new AltosDroidPreferences(this);
309 AltosPreferences.init(prefs);
311 // Set up the window layout
312 requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
313 setContentView(R.layout.altosdroid);
314 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
316 // Create the Tabs and ViewPager
317 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
320 mViewPager = (AltosViewPager)findViewById(R.id.pager);
321 mViewPager.setOffscreenPageLimit(4);
323 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
325 mTabsAdapter.addTab(mTabHost.newTabSpec("pad").setIndicator("Pad"), TabPad.class, null);
326 mTabsAdapter.addTab(mTabHost.newTabSpec("ascent").setIndicator("Ascent"), TabAscent.class, null);
327 mTabsAdapter.addTab(mTabHost.newTabSpec("descent").setIndicator("Descent"), TabDescent.class, null);
328 mTabsAdapter.addTab(mTabHost.newTabSpec("landed").setIndicator("Landed"), TabLanded.class, null);
329 mTabsAdapter.addTab(mTabHost.newTabSpec("map").setIndicator("Map"), TabMap.class, null);
332 // Scale the size of the Tab bar for different screen densities
333 // This probably won't be needed when we start supporting ICS+ tabs.
334 DisplayMetrics metrics = new DisplayMetrics();
335 getWindowManager().getDefaultDisplay().getMetrics(metrics);
336 int density = metrics.densityDpi;
338 if (density==DisplayMetrics.DENSITY_XHIGH)
340 else if (density==DisplayMetrics.DENSITY_HIGH)
342 else if (density==DisplayMetrics.DENSITY_MEDIUM)
344 else if (density==DisplayMetrics.DENSITY_LOW)
349 for (int i = 0; i < 5; i++)
350 mTabHost.getTabWidget().getChildAt(i).getLayoutParams().height = tabHeight;
353 // Set up the custom title
354 mTitle = (TextView) findViewById(R.id.title_left_text);
355 mTitle.setText(R.string.app_name);
356 mTitle = (TextView) findViewById(R.id.title_right_text);
358 // Display the Version
359 mVersion = (TextView) findViewById(R.id.version);
360 mVersion.setText("Version: " + BuildInfo.version +
361 " Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
362 " (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
364 mCallsignView = (TextView) findViewById(R.id.callsign_value);
365 mRSSIView = (TextView) findViewById(R.id.rssi_value);
366 mSerialView = (TextView) findViewById(R.id.serial_value);
367 mFlightView = (TextView) findViewById(R.id.flight_value);
368 mStateView = (TextView) findViewById(R.id.state_value);
369 mAgeView = (TextView) findViewById(R.id.age_value);
371 timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 1000L, 100L);
373 mAltosVoice = new AltosVoice(this);
377 public void onStart() {
379 if(D) Log.e(TAG, "++ ON START ++");
381 if (!mBluetoothAdapter.isEnabled()) {
382 Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
383 startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
386 // Start Telemetry Service
387 startService(new Intent(AltosDroid.this, TelemetryService.class));
393 public synchronized void onResume() {
395 if(D) Log.e(TAG, "+ ON RESUME +");
399 public synchronized void onPause() {
401 if(D) Log.e(TAG, "- ON PAUSE -");
405 public void onStop() {
407 if(D) Log.e(TAG, "-- ON STOP --");
413 public void onDestroy() {
415 if(D) Log.e(TAG, "--- ON DESTROY ---");
417 if (mAltosVoice != null) mAltosVoice.stop();
420 public void onActivityResult(int requestCode, int resultCode, Intent data) {
421 if(D) Log.d(TAG, "onActivityResult " + resultCode);
422 switch (requestCode) {
423 case REQUEST_CONNECT_DEVICE:
424 // When DeviceListActivity returns with a device to connect to
425 if (resultCode == Activity.RESULT_OK) {
429 case REQUEST_ENABLE_BT:
430 // When the request to enable Bluetooth returns
431 if (resultCode == Activity.RESULT_OK) {
432 // Bluetooth is now enabled, so set up a chat session
435 // User did not enable Bluetooth or an error occured
436 Log.e(TAG, "BT not enabled");
437 stopService(new Intent(AltosDroid.this, TelemetryService.class));
438 Toast.makeText(this, R.string.bt_not_enabled, Toast.LENGTH_SHORT).show();
445 private void connectDevice(Intent data) {
446 // Get the device MAC address
447 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
448 // Get the BLuetoothDevice object
449 BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
450 // Attempt to connect to the device
452 if (D) Log.d(TAG, "Connecting to " + device.getName());
453 mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, device));
454 } catch (RemoteException e) {
459 public boolean onCreateOptionsMenu(Menu menu) {
460 MenuInflater inflater = getMenuInflater();
461 inflater.inflate(R.menu.option_menu, menu);
465 void setFrequency(double freq) {
467 mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
468 } catch (RemoteException e) {
472 void setFrequency(String freq) {
474 setFrequency (Double.parseDouble(freq.substring(11, 17)));
475 } catch (NumberFormatException e) {
480 public boolean onOptionsItemSelected(MenuItem item) {
481 Intent serverIntent = null;
482 switch (item.getItemId()) {
483 case R.id.connect_scan:
484 // Launch the DeviceListActivity to see devices and do scan
485 serverIntent = new Intent(this, DeviceListActivity.class);
486 startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
488 case R.id.select_freq:
489 // Set the TBT radio frequency
491 final String[] frequencies = {
492 "Channel 0 (434.550MHz)",
493 "Channel 1 (434.650MHz)",
494 "Channel 2 (434.750MHz)",
495 "Channel 3 (434.850MHz)",
496 "Channel 4 (434.950MHz)",
497 "Channel 5 (435.050MHz)",
498 "Channel 6 (435.150MHz)",
499 "Channel 7 (435.250MHz)",
500 "Channel 8 (435.350MHz)",
501 "Channel 9 (435.450MHz)"
504 AlertDialog.Builder builder = new AlertDialog.Builder(this);
505 builder.setTitle("Pick a frequency");
506 builder.setItems(frequencies,
507 new DialogInterface.OnClickListener() {
508 public void onClick(DialogInterface dialog, int item) {
509 setFrequency(frequencies[item]);
512 AlertDialog alert = builder.create();