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.Log;
41 import android.view.Menu;
42 import android.view.MenuInflater;
43 import android.view.MenuItem;
44 import android.view.Window;
45 import android.widget.TabHost;
46 import android.widget.TextView;
47 import android.widget.Toast;
48 import android.app.AlertDialog;
49 import android.location.Location;
51 import org.altusmetrum.altoslib_1.*;
53 public class AltosDroid extends FragmentActivity {
55 private static final String TAG = "AltosDroid";
56 private static final boolean D = true;
58 // Message types received by our Handler
59 public static final int MSG_STATE_CHANGE = 1;
60 public static final int MSG_TELEMETRY = 2;
61 public static final int MSG_UPDATE_AGE = 3;
62 public static final int MSG_LOCATION = 4;
63 public static final int MSG_CRC_ERROR = 5;
65 // Intent request codes
66 private static final int REQUEST_CONNECT_DEVICE = 1;
67 private static final int REQUEST_ENABLE_BT = 2;
70 private TextView mTitle;
72 // Flight state values
73 private TextView mCallsignView;
74 private TextView mRSSIView;
75 private TextView mSerialView;
76 private TextView mFlightView;
77 private TextView mStateView;
78 private TextView mAgeView;
80 // field to display the version at the bottom of the screen
81 private TextView mVersion;
85 AltosViewPager mViewPager;
86 TabsAdapter mTabsAdapter;
87 ArrayList<AltosDroidTab> mTabs = new ArrayList<AltosDroidTab>();
89 // Timer and Saved flight state for Age calculation
90 private Timer timer = new Timer();
91 AltosState saved_state;
92 Location saved_location;
95 private boolean mIsBound = false;
96 private Messenger mService = null;
97 final Messenger mMessenger = new Messenger(new IncomingHandler(this));
100 private AltosDroidPreferences prefs = null;
102 // TeleBT Config data
103 private AltosConfigData mConfigData = null;
104 // Local Bluetooth adapter
105 private BluetoothAdapter mBluetoothAdapter = null;
108 private AltosVoice mAltosVoice = null;
110 // The Handler that gets information back from the Telemetry Service
111 static class IncomingHandler extends Handler {
112 private final WeakReference<AltosDroid> mAltosDroid;
113 IncomingHandler(AltosDroid ad) { mAltosDroid = new WeakReference<AltosDroid>(ad); }
116 public void handleMessage(Message msg) {
117 AltosDroid ad = mAltosDroid.get();
119 case MSG_STATE_CHANGE:
120 if(D) Log.d(TAG, "MSG_STATE_CHANGE: " + msg.arg1);
122 case TelemetryService.STATE_CONNECTED:
123 ad.mConfigData = (AltosConfigData) msg.obj;
124 String str = String.format(" %s S/N: %d", ad.mConfigData.product, ad.mConfigData.serial);
125 ad.mTitle.setText(R.string.title_connected_to);
126 ad.mTitle.append(str);
127 Toast.makeText(ad.getApplicationContext(), "Connected to " + str, Toast.LENGTH_SHORT).show();
129 case TelemetryService.STATE_CONNECTING:
130 ad.mTitle.setText(R.string.title_connecting);
132 case TelemetryService.STATE_READY:
133 case TelemetryService.STATE_NONE:
134 ad.mConfigData = null;
135 ad.mTitle.setText(R.string.title_not_connected);
140 ad.update_ui((AltosState) msg.obj);
143 ad.set_location((Location) msg.obj);
147 if (ad.saved_state != null) {
148 ad.mAgeView.setText(String.format("%d", (System.currentTimeMillis() - ad.saved_state.report_time + 500) / 1000));
156 private ServiceConnection mConnection = new ServiceConnection() {
157 public void onServiceConnected(ComponentName className, IBinder service) {
158 mService = new Messenger(service);
160 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
161 msg.replyTo = mMessenger;
163 } catch (RemoteException e) {
164 // In this case the service has crashed before we could even do anything with it
168 public void onServiceDisconnected(ComponentName className) {
169 // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
174 void doBindService() {
175 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
179 void doUnbindService() {
181 // If we have received the service, and hence registered with it, then now is the time to unregister.
182 if (mService != null) {
184 Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
185 msg.replyTo = mMessenger;
187 } catch (RemoteException e) {
188 // There is nothing special we need to do if the service has crashed.
191 // Detach our existing connection.
192 unbindService(mConnection);
197 public void registerTab(AltosDroidTab mTab) {
201 public void unregisterTab(AltosDroidTab mTab) {
205 void set_location(Location location) {
206 saved_location = location;
207 update_ui(saved_state);
210 void update_ui(AltosState state) {
211 if (state != null && saved_state != null) {
212 if (saved_state.state != state.state) {
213 String currentTab = mTabHost.getCurrentTabTag();
214 switch (state.state) {
215 case AltosLib.ao_flight_boost:
216 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("ascent");
218 case AltosLib.ao_flight_drogue:
219 if (currentTab.equals("ascent")) mTabHost.setCurrentTabByTag("descent");
221 case AltosLib.ao_flight_landed:
222 if (currentTab.equals("descent")) mTabHost.setCurrentTabByTag("landed");
229 AltosGreatCircle from_receiver = null;
231 if (state != null && saved_location != null && state.gps != null && state.gps.locked) {
233 if (saved_location.hasAltitude())
234 altitude = saved_location.getAltitude();
235 from_receiver = new AltosGreatCircle(saved_location.getLatitude(),
236 saved_location.getLongitude(),
244 mCallsignView.setText(state.data.callsign);
245 mSerialView.setText(String.format("%d", state.data.serial));
246 mFlightView.setText(String.format("%d", state.data.flight));
247 mStateView.setText(state.data.state());
248 mRSSIView.setText(String.format("%d", state.data.rssi));
251 for (AltosDroidTab mTab : mTabs)
252 mTab.update_ui(state, from_receiver, saved_location);
255 mAltosVoice.tell(state);
258 private void onTimerTick() {
260 mMessenger.send(Message.obtain(null, MSG_UPDATE_AGE));
261 } catch (RemoteException e) {
265 static String pos(double p, String pos, String neg) {
267 if (p == AltosRecord.MISSING)
273 int deg = (int) Math.floor(p);
274 double min = (p - Math.floor(p)) * 60.0;
275 return String.format("%d°%9.4f\" %s", deg, min, h);
278 static String number(String format, double value) {
279 if (value == AltosRecord.MISSING)
281 return String.format(format, value);
284 static String integer(String format, int value) {
285 if (value == AltosRecord.MISSING)
287 return String.format(format, value);
291 public void onCreate(Bundle savedInstanceState) {
292 super.onCreate(savedInstanceState);
293 if(D) Log.e(TAG, "+++ ON CREATE +++");
295 // Get local Bluetooth adapter
296 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
298 // If the adapter is null, then Bluetooth is not supported
299 if (mBluetoothAdapter == null) {
300 Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
305 // Initialise preferences
306 prefs = new AltosDroidPreferences(this);
307 AltosPreferences.init(prefs);
309 // Set up the window layout
310 requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
311 setContentView(R.layout.altosdroid);
312 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
314 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
317 mViewPager = (AltosViewPager)findViewById(R.id.pager);
318 mViewPager.setOffscreenPageLimit(4);
320 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
322 mTabsAdapter.addTab(mTabHost.newTabSpec("pad").setIndicator("Pad"), TabPad.class, null);
323 mTabsAdapter.addTab(mTabHost.newTabSpec("ascent").setIndicator("Ascent"), TabAscent.class, null);
324 mTabsAdapter.addTab(mTabHost.newTabSpec("descent").setIndicator("Descent"), TabDescent.class, null);
325 mTabsAdapter.addTab(mTabHost.newTabSpec("landed").setIndicator("Landed"), TabLanded.class, null);
326 mTabsAdapter.addTab(mTabHost.newTabSpec("map").setIndicator("Map"), TabMap.class, null);
328 for (int i = 0; i < 5; i++)
329 mTabHost.getTabWidget().getChildAt(i).getLayoutParams().height = 45;
331 // Set up the custom title
332 mTitle = (TextView) findViewById(R.id.title_left_text);
333 mTitle.setText(R.string.app_name);
334 mTitle = (TextView) findViewById(R.id.title_right_text);
336 // Display the Version
337 mVersion = (TextView) findViewById(R.id.version);
338 mVersion.setText("Version: " + BuildInfo.version +
339 " Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
340 " (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
342 mCallsignView = (TextView) findViewById(R.id.callsign_value);
343 mRSSIView = (TextView) findViewById(R.id.rssi_value);
344 mSerialView = (TextView) findViewById(R.id.serial_value);
345 mFlightView = (TextView) findViewById(R.id.flight_value);
346 mStateView = (TextView) findViewById(R.id.state_value);
347 mAgeView = (TextView) findViewById(R.id.age_value);
349 timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 1000L, 100L);
351 mAltosVoice = new AltosVoice(this);
355 public void onStart() {
357 if(D) Log.e(TAG, "++ ON START ++");
359 if (!mBluetoothAdapter.isEnabled()) {
360 Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
361 startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
364 // Start Telemetry Service
365 startService(new Intent(AltosDroid.this, TelemetryService.class));
371 public synchronized void onResume() {
373 if(D) Log.e(TAG, "+ ON RESUME +");
377 public synchronized void onPause() {
379 if(D) Log.e(TAG, "- ON PAUSE -");
383 public void onStop() {
385 if(D) Log.e(TAG, "-- ON STOP --");
391 public void onDestroy() {
393 if(D) Log.e(TAG, "--- ON DESTROY ---");
398 public void onActivityResult(int requestCode, int resultCode, Intent data) {
399 if(D) Log.d(TAG, "onActivityResult " + resultCode);
400 switch (requestCode) {
401 case REQUEST_CONNECT_DEVICE:
402 // When DeviceListActivity returns with a device to connect to
403 if (resultCode == Activity.RESULT_OK) {
407 case REQUEST_ENABLE_BT:
408 // When the request to enable Bluetooth returns
409 if (resultCode == Activity.RESULT_OK) {
410 // Bluetooth is now enabled, so set up a chat session
413 // User did not enable Bluetooth or an error occured
414 Log.e(TAG, "BT not enabled");
415 stopService(new Intent(AltosDroid.this, TelemetryService.class));
416 Toast.makeText(this, R.string.bt_not_enabled, Toast.LENGTH_SHORT).show();
423 private void connectDevice(Intent data) {
424 // Get the device MAC address
425 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
426 // Get the BLuetoothDevice object
427 BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
428 // Attempt to connect to the device
430 if (D) Log.d(TAG, "Connecting to " + device.getName());
431 mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, device));
432 } catch (RemoteException e) {
437 public boolean onCreateOptionsMenu(Menu menu) {
438 MenuInflater inflater = getMenuInflater();
439 inflater.inflate(R.menu.option_menu, menu);
443 void setFrequency(double freq) {
445 mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
446 } catch (RemoteException e) {
450 void setFrequency(String freq) {
452 setFrequency (Double.parseDouble(freq.substring(11, 17)));
453 } catch (NumberFormatException e) {
458 public boolean onOptionsItemSelected(MenuItem item) {
459 Intent serverIntent = null;
460 switch (item.getItemId()) {
461 case R.id.connect_scan:
462 // Launch the DeviceListActivity to see devices and do scan
463 serverIntent = new Intent(this, DeviceListActivity.class);
464 startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
466 case R.id.select_freq:
467 // Set the TBT radio frequency
469 final String[] frequencies = {
470 "Channel 0 (434.550MHz)",
471 "Channel 1 (434.650MHz)",
472 "Channel 2 (434.750MHz)",
473 "Channel 3 (434.850MHz)",
474 "Channel 4 (434.950MHz)",
475 "Channel 5 (435.050MHz)",
476 "Channel 6 (435.150MHz)",
477 "Channel 7 (435.250MHz)",
478 "Channel 8 (435.350MHz)",
479 "Channel 9 (435.450MHz)"
482 AlertDialog.Builder builder = new AlertDialog.Builder(this);
483 builder.setTitle("Pick a frequency");
484 builder.setItems(frequencies,
485 new DialogInterface.OnClickListener() {
486 public void onClick(DialogInterface dialog, int item) {
487 setFrequency(frequencies[item]);
490 AlertDialog alert = builder.create();