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;
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) {
202 mCallsignView.setText(state.data.callsign);
203 mSerialView.setText(String.format("%d", state.data.serial));
204 mFlightView.setText(String.format("%d", state.data.flight));
205 mStateView.setText(state.data.state());
206 mRSSIView.setText(String.format("%d", state.data.rssi));
208 for (AltosDroidTab mTab : mTabs)
209 mTab.update_ui(state);
211 mAltosVoice.tell(state);
214 private void onTimerTick() {
216 mMessenger.send(Message.obtain(null, MSG_UPDATE_AGE));
217 } catch (RemoteException e) {
221 static String pos(double p, String pos, String neg) {
227 int deg = (int) Math.floor(p);
228 double min = (p - Math.floor(p)) * 60.0;
229 return String.format("%d° %9.6f\" %s", deg, min, h);
233 public void onCreate(Bundle savedInstanceState) {
234 super.onCreate(savedInstanceState);
235 if(D) Log.e(TAG, "+++ ON CREATE +++");
237 // Get local Bluetooth adapter
238 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
240 // If the adapter is null, then Bluetooth is not supported
241 if (mBluetoothAdapter == null) {
242 Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
247 // Initialise preferences
248 prefs = new AltosDroidPreferences(this);
249 AltosPreferences.init(prefs);
251 // Set up the window layout
252 requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
253 setContentView(R.layout.altosdroid);
254 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
256 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
259 mViewPager = (ViewPager)findViewById(R.id.pager);
260 mViewPager.setOffscreenPageLimit(4);
262 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
264 mTabsAdapter.addTab(mTabHost.newTabSpec("pad").setIndicator("Pad"), TabPad.class, null);
265 mTabsAdapter.addTab(mTabHost.newTabSpec("ascent").setIndicator("Ascent"), TabAscent.class, null);
266 mTabsAdapter.addTab(mTabHost.newTabSpec("descent").setIndicator("Descent"), TabDescent.class, null);
267 mTabsAdapter.addTab(mTabHost.newTabSpec("landed").setIndicator("Landed"), TabLanded.class, null);
268 mTabsAdapter.addTab(mTabHost.newTabSpec("map").setIndicator("Map"), TabMap.class, null);
271 // Set up the custom title
272 mTitle = (TextView) findViewById(R.id.title_left_text);
273 mTitle.setText(R.string.app_name);
274 mTitle = (TextView) findViewById(R.id.title_right_text);
276 // Display the Version
277 mVersion = (TextView) findViewById(R.id.version);
278 mVersion.setText("Version: " + BuildInfo.version +
279 " Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
280 " (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
282 mCallsignView = (TextView) findViewById(R.id.callsign_value);
283 mRSSIView = (TextView) findViewById(R.id.rssi_value);
284 mSerialView = (TextView) findViewById(R.id.serial_value);
285 mFlightView = (TextView) findViewById(R.id.flight_value);
286 mStateView = (TextView) findViewById(R.id.state_value);
287 mAgeView = (TextView) findViewById(R.id.age_value);
289 timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 1000L, 100L);
291 mAltosVoice = new AltosVoice(this);
295 public void onStart() {
297 if(D) Log.e(TAG, "++ ON START ++");
299 if (!mBluetoothAdapter.isEnabled()) {
300 Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
301 startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
304 // Start Telemetry Service
305 startService(new Intent(AltosDroid.this, TelemetryService.class));
311 public synchronized void onResume() {
313 if(D) Log.e(TAG, "+ ON RESUME +");
317 public synchronized void onPause() {
319 if(D) Log.e(TAG, "- ON PAUSE -");
323 public void onStop() {
325 if(D) Log.e(TAG, "-- ON STOP --");
331 public void onDestroy() {
333 if(D) Log.e(TAG, "--- ON DESTROY ---");
338 public void onActivityResult(int requestCode, int resultCode, Intent data) {
339 if(D) Log.d(TAG, "onActivityResult " + resultCode);
340 switch (requestCode) {
341 case REQUEST_CONNECT_DEVICE:
342 // When DeviceListActivity returns with a device to connect to
343 if (resultCode == Activity.RESULT_OK) {
347 case REQUEST_ENABLE_BT:
348 // When the request to enable Bluetooth returns
349 if (resultCode == Activity.RESULT_OK) {
350 // Bluetooth is now enabled, so set up a chat session
353 // User did not enable Bluetooth or an error occured
354 Log.e(TAG, "BT not enabled");
355 stopService(new Intent(AltosDroid.this, TelemetryService.class));
356 Toast.makeText(this, R.string.bt_not_enabled, Toast.LENGTH_SHORT).show();
363 private void connectDevice(Intent data) {
364 // Get the device MAC address
365 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
366 // Get the BLuetoothDevice object
367 BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
368 // Attempt to connect to the device
370 if (D) Log.d(TAG, "Connecting to " + device.getName());
371 mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, device));
372 } catch (RemoteException e) {
377 public boolean onCreateOptionsMenu(Menu menu) {
378 MenuInflater inflater = getMenuInflater();
379 inflater.inflate(R.menu.option_menu, menu);
383 void setFrequency(double freq) {
385 mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
386 } catch (RemoteException e) {
390 void setFrequency(String freq) {
392 setFrequency (Double.parseDouble(freq.substring(11, 17)));
393 } catch (NumberFormatException e) {
398 public boolean onOptionsItemSelected(MenuItem item) {
399 Intent serverIntent = null;
400 switch (item.getItemId()) {
401 case R.id.connect_scan:
402 // Launch the DeviceListActivity to see devices and do scan
403 serverIntent = new Intent(this, DeviceListActivity.class);
404 startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
406 case R.id.select_freq:
407 // Set the TBT radio frequency
409 final String[] frequencies = {
410 "Channel 0 (434.550MHz)",
411 "Channel 1 (434.650MHz)",
412 "Channel 2 (434.750MHz)",
413 "Channel 3 (434.850MHz)",
414 "Channel 4 (434.950MHz)",
415 "Channel 5 (435.050MHz)",
416 "Channel 6 (435.150MHz)",
417 "Channel 7 (435.250MHz)",
418 "Channel 8 (435.350MHz)",
419 "Channel 9 (435.450MHz)"
422 AlertDialog.Builder builder = new AlertDialog.Builder(this);
423 builder.setTitle("Pick a frequency");
424 builder.setItems(frequencies,
425 new DialogInterface.OnClickListener() {
426 public void onClick(DialogInterface dialog, int item) {
427 setFrequency(frequencies[item]);
430 AlertDialog alert = builder.create();