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.view.ViewPager;
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;
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;
63 // Intent request codes
64 private static final int REQUEST_CONNECT_DEVICE = 1;
65 private static final int REQUEST_ENABLE_BT = 2;
68 private TextView mTitle;
70 // Flight state values
71 private TextView mCallsignView;
72 private TextView mRSSIView;
73 private TextView mSerialView;
74 private TextView mFlightView;
75 private TextView mStateView;
76 private TextView mAgeView;
78 // field to display the version at the bottom of the screen
79 private TextView mVersion;
83 AltosViewPager mViewPager;
84 TabsAdapter mTabsAdapter;
85 ArrayList<AltosDroidTab> mTabs = new ArrayList<AltosDroidTab>();
87 // Timer and Saved flight state for Age calculation
88 private Timer timer = new Timer();
89 AltosState saved_state;
92 private boolean mIsBound = false;
93 private Messenger mService = null;
94 final Messenger mMessenger = new Messenger(new IncomingHandler(this));
97 private AltosDroidPreferences prefs = null;
100 private AltosConfigData mConfigData = null;
101 // Local Bluetooth adapter
102 private BluetoothAdapter mBluetoothAdapter = null;
105 private AltosVoice mAltosVoice = null;
107 // The Handler that gets information back from the Telemetry Service
108 static class IncomingHandler extends Handler {
109 private final WeakReference<AltosDroid> mAltosDroid;
110 IncomingHandler(AltosDroid ad) { mAltosDroid = new WeakReference<AltosDroid>(ad); }
113 public void handleMessage(Message msg) {
114 AltosDroid ad = mAltosDroid.get();
116 case MSG_STATE_CHANGE:
117 if(D) Log.d(TAG, "MSG_STATE_CHANGE: " + msg.arg1);
119 case TelemetryService.STATE_CONNECTED:
120 ad.mConfigData = (AltosConfigData) msg.obj;
121 String str = String.format(" %s S/N: %d", ad.mConfigData.product, ad.mConfigData.serial);
122 ad.mTitle.setText(R.string.title_connected_to);
123 ad.mTitle.append(str);
124 Toast.makeText(ad.getApplicationContext(), "Connected to " + str, Toast.LENGTH_SHORT).show();
125 ad.mAltosVoice.speak("Connected");
127 case TelemetryService.STATE_CONNECTING:
128 ad.mTitle.setText(R.string.title_connecting);
130 case TelemetryService.STATE_READY:
131 case TelemetryService.STATE_NONE:
132 ad.mConfigData = null;
133 ad.mTitle.setText(R.string.title_not_connected);
138 ad.update_ui((AltosState) msg.obj);
141 if (ad.saved_state != null) {
142 ad.mAgeView.setText(String.format("%d", (System.currentTimeMillis() - ad.saved_state.report_time + 500) / 1000));
150 private ServiceConnection mConnection = new ServiceConnection() {
151 public void onServiceConnected(ComponentName className, IBinder service) {
152 mService = new Messenger(service);
154 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
155 msg.replyTo = mMessenger;
157 } catch (RemoteException e) {
158 // In this case the service has crashed before we could even do anything with it
162 public void onServiceDisconnected(ComponentName className) {
163 // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
168 void doBindService() {
169 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
173 void doUnbindService() {
175 // If we have received the service, and hence registered with it, then now is the time to unregister.
176 if (mService != null) {
178 Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
179 msg.replyTo = mMessenger;
181 } catch (RemoteException e) {
182 // There is nothing special we need to do if the service has crashed.
185 // Detach our existing connection.
186 unbindService(mConnection);
191 public void registerTab(AltosDroidTab mTab) {
195 public void unregisterTab(AltosDroidTab mTab) {
199 void update_ui(AltosState state) {
200 if (saved_state != null) {
201 if (saved_state.state != state.state) {
202 String currentTab = mTabHost.getCurrentTabTag();
203 switch (state.state) {
204 case AltosLib.ao_flight_boost:
205 if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("ascent");
207 case AltosLib.ao_flight_drogue:
208 if (currentTab.equals("ascent")) mTabHost.setCurrentTabByTag("descent");
210 case AltosLib.ao_flight_landed:
211 if (currentTab.equals("descent")) mTabHost.setCurrentTabByTag("landed");
218 mCallsignView.setText(state.data.callsign);
219 mSerialView.setText(String.format("%d", state.data.serial));
220 mFlightView.setText(String.format("%d", state.data.flight));
221 mStateView.setText(state.data.state());
222 mRSSIView.setText(String.format("%d", state.data.rssi));
224 for (AltosDroidTab mTab : mTabs)
225 mTab.update_ui(state);
227 mAltosVoice.tell(state);
230 private void onTimerTick() {
232 mMessenger.send(Message.obtain(null, MSG_UPDATE_AGE));
233 } catch (RemoteException e) {
237 static String pos(double p, String pos, String neg) {
243 int deg = (int) Math.floor(p);
244 double min = (p - Math.floor(p)) * 60.0;
245 return String.format("%d° %9.6f\" %s", deg, min, h);
249 public void onCreate(Bundle savedInstanceState) {
250 super.onCreate(savedInstanceState);
251 if(D) Log.e(TAG, "+++ ON CREATE +++");
253 // Get local Bluetooth adapter
254 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
256 // If the adapter is null, then Bluetooth is not supported
257 if (mBluetoothAdapter == null) {
258 Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
263 // Initialise preferences
264 prefs = new AltosDroidPreferences(this);
265 AltosPreferences.init(prefs);
267 // Set up the window layout
268 requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
269 setContentView(R.layout.altosdroid);
270 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
272 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
275 mViewPager = (AltosViewPager)findViewById(R.id.pager);
276 mViewPager.setOffscreenPageLimit(4);
278 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
280 mTabsAdapter.addTab(mTabHost.newTabSpec("pad").setIndicator("Pad"), TabPad.class, null);
281 mTabsAdapter.addTab(mTabHost.newTabSpec("ascent").setIndicator("Ascent"), TabAscent.class, null);
282 mTabsAdapter.addTab(mTabHost.newTabSpec("descent").setIndicator("Descent"), TabDescent.class, null);
283 mTabsAdapter.addTab(mTabHost.newTabSpec("landed").setIndicator("Landed"), TabLanded.class, null);
284 mTabsAdapter.addTab(mTabHost.newTabSpec("map").setIndicator("Map"), TabMap.class, null);
287 // Set up the custom title
288 mTitle = (TextView) findViewById(R.id.title_left_text);
289 mTitle.setText(R.string.app_name);
290 mTitle = (TextView) findViewById(R.id.title_right_text);
292 // Display the Version
293 mVersion = (TextView) findViewById(R.id.version);
294 mVersion.setText("Version: " + BuildInfo.version +
295 " Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
296 " (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
298 mCallsignView = (TextView) findViewById(R.id.callsign_value);
299 mRSSIView = (TextView) findViewById(R.id.rssi_value);
300 mSerialView = (TextView) findViewById(R.id.serial_value);
301 mFlightView = (TextView) findViewById(R.id.flight_value);
302 mStateView = (TextView) findViewById(R.id.state_value);
303 mAgeView = (TextView) findViewById(R.id.age_value);
305 timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 1000L, 100L);
307 mAltosVoice = new AltosVoice(this);
311 public void onStart() {
313 if(D) Log.e(TAG, "++ ON START ++");
315 if (!mBluetoothAdapter.isEnabled()) {
316 Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
317 startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
320 // Start Telemetry Service
321 startService(new Intent(AltosDroid.this, TelemetryService.class));
327 public synchronized void onResume() {
329 if(D) Log.e(TAG, "+ ON RESUME +");
333 public synchronized void onPause() {
335 if(D) Log.e(TAG, "- ON PAUSE -");
339 public void onStop() {
341 if(D) Log.e(TAG, "-- ON STOP --");
347 public void onDestroy() {
349 if(D) Log.e(TAG, "--- ON DESTROY ---");
354 public void onActivityResult(int requestCode, int resultCode, Intent data) {
355 if(D) Log.d(TAG, "onActivityResult " + resultCode);
356 switch (requestCode) {
357 case REQUEST_CONNECT_DEVICE:
358 // When DeviceListActivity returns with a device to connect to
359 if (resultCode == Activity.RESULT_OK) {
363 case REQUEST_ENABLE_BT:
364 // When the request to enable Bluetooth returns
365 if (resultCode == Activity.RESULT_OK) {
366 // Bluetooth is now enabled, so set up a chat session
369 // User did not enable Bluetooth or an error occured
370 Log.e(TAG, "BT not enabled");
371 stopService(new Intent(AltosDroid.this, TelemetryService.class));
372 Toast.makeText(this, R.string.bt_not_enabled, Toast.LENGTH_SHORT).show();
379 private void connectDevice(Intent data) {
380 // Get the device MAC address
381 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
382 // Get the BLuetoothDevice object
383 BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
384 // Attempt to connect to the device
386 if (D) Log.d(TAG, "Connecting to " + device.getName());
387 mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, device));
388 } catch (RemoteException e) {
393 public boolean onCreateOptionsMenu(Menu menu) {
394 MenuInflater inflater = getMenuInflater();
395 inflater.inflate(R.menu.option_menu, menu);
399 void setFrequency(double freq) {
401 mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
402 } catch (RemoteException e) {
406 void setFrequency(String freq) {
408 setFrequency (Double.parseDouble(freq.substring(11, 17)));
409 } catch (NumberFormatException e) {
414 public boolean onOptionsItemSelected(MenuItem item) {
415 Intent serverIntent = null;
416 switch (item.getItemId()) {
417 case R.id.connect_scan:
418 // Launch the DeviceListActivity to see devices and do scan
419 serverIntent = new Intent(this, DeviceListActivity.class);
420 startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
422 case R.id.select_freq:
423 // Set the TBT radio frequency
425 final String[] frequencies = {
426 "Channel 0 (434.550MHz)",
427 "Channel 1 (434.650MHz)",
428 "Channel 2 (434.750MHz)",
429 "Channel 3 (434.850MHz)",
430 "Channel 4 (434.950MHz)",
431 "Channel 5 (435.050MHz)",
432 "Channel 6 (435.150MHz)",
433 "Channel 7 (435.250MHz)",
434 "Channel 8 (435.350MHz)",
435 "Channel 9 (435.450MHz)"
438 AlertDialog.Builder builder = new AlertDialog.Builder(this);
439 builder.setTitle("Pick a frequency");
440 builder.setItems(frequencies,
441 new DialogInterface.OnClickListener() {
442 public void onClick(DialogInterface dialog, int item) {
443 setFrequency(frequencies[item]);
446 AlertDialog alert = builder.create();