altosdroid: whitespace and import tidyup
[fw/altos] / altosdroid / src / org / altusmetrum / AltosDroid / AltosDroid.java
1 /*
2  * Copyright © 2012-2013 Mike Beattie <mike@ethernal.org>
3  *
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.
7  *
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.
12  *
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.
16  */
17
18 package org.altusmetrum.AltosDroid;
19
20 import java.lang.ref.WeakReference;
21 import java.util.ArrayList;
22 import java.util.Timer;
23 import java.util.TimerTask;
24
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;
50
51 import org.altusmetrum.altoslib_1.*;
52
53 public class AltosDroid extends FragmentActivity {
54         // Debugging
55         private static final String TAG = "AltosDroid";
56         private static final boolean D = true;
57
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;
64
65         // Intent request codes
66         private static final int REQUEST_CONNECT_DEVICE = 1;
67         private static final int REQUEST_ENABLE_BT      = 2;
68
69         // Layout Views
70         private TextView mTitle;
71
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;
79
80         // field to display the version at the bottom of the screen
81         private TextView mVersion;
82
83         // Tabs
84         TabHost         mTabHost;
85         AltosViewPager  mViewPager;
86         TabsAdapter     mTabsAdapter;
87         ArrayList<AltosDroidTab> mTabs = new ArrayList<AltosDroidTab>();
88
89         // Timer and Saved flight state for Age calculation
90         private Timer timer = new Timer();
91         AltosState saved_state;
92         Location saved_location;
93
94         // Service
95         private boolean mIsBound   = false;
96         private Messenger mService = null;
97         final Messenger mMessenger = new Messenger(new IncomingHandler(this));
98
99         // Preferences
100         private AltosDroidPreferences prefs = null;
101
102         // TeleBT Config data
103         private AltosConfigData mConfigData = null;
104         // Local Bluetooth adapter
105         private BluetoothAdapter mBluetoothAdapter = null;
106
107         // Text to Speech
108         private AltosVoice mAltosVoice = null;
109
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); }
114
115                 @Override
116                 public void handleMessage(Message msg) {
117                         AltosDroid ad = mAltosDroid.get();
118                         switch (msg.what) {
119                         case MSG_STATE_CHANGE:
120                                 if(D) Log.d(TAG, "MSG_STATE_CHANGE: " + msg.arg1);
121                                 switch (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();
128                                         break;
129                                 case TelemetryService.STATE_CONNECTING:
130                                         ad.mTitle.setText(R.string.title_connecting);
131                                         break;
132                                 case TelemetryService.STATE_READY:
133                                 case TelemetryService.STATE_NONE:
134                                         ad.mConfigData = null;
135                                         ad.mTitle.setText(R.string.title_not_connected);
136                                         break;
137                                 }
138                                 break;
139                         case MSG_TELEMETRY:
140                                 ad.update_ui((AltosState) msg.obj);
141                                 break;
142                         case MSG_LOCATION:
143                                 ad.set_location((Location) msg.obj);
144                                 break;
145                         case MSG_CRC_ERROR:
146                         case MSG_UPDATE_AGE:
147                                 if (ad.saved_state != null) {
148                                         ad.mAgeView.setText(String.format("%d", (System.currentTimeMillis() - ad.saved_state.report_time + 500) / 1000));
149                                 }
150                                 break;
151                         }
152                 }
153         };
154
155
156         private ServiceConnection mConnection = new ServiceConnection() {
157                 public void onServiceConnected(ComponentName className, IBinder service) {
158                         mService = new Messenger(service);
159                         try {
160                                 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
161                                 msg.replyTo = mMessenger;
162                                 mService.send(msg);
163                         } catch (RemoteException e) {
164                                 // In this case the service has crashed before we could even do anything with it
165                         }
166                 }
167
168                 public void onServiceDisconnected(ComponentName className) {
169                         // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
170                         mService = null;
171                 }
172         };
173
174         void doBindService() {
175                 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
176                 mIsBound = true;
177         }
178
179         void doUnbindService() {
180                 if (mIsBound) {
181                         // If we have received the service, and hence registered with it, then now is the time to unregister.
182                         if (mService != null) {
183                                 try {
184                                         Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
185                                         msg.replyTo = mMessenger;
186                                         mService.send(msg);
187                                 } catch (RemoteException e) {
188                                         // There is nothing special we need to do if the service has crashed.
189                                 }
190                         }
191                         // Detach our existing connection.
192                         unbindService(mConnection);
193                         mIsBound = false;
194                 }
195         }
196
197         public void registerTab(AltosDroidTab mTab) {
198                 mTabs.add(mTab);
199         }
200
201         public void unregisterTab(AltosDroidTab mTab) {
202                 mTabs.remove(mTab);
203         }
204
205         void set_location(Location location) {
206                 saved_location = location;
207                 update_ui(saved_state);
208         }
209
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");
217                                         break;
218                                 case AltosLib.ao_flight_drogue:
219                                         if (currentTab.equals("ascent")) mTabHost.setCurrentTabByTag("descent");
220                                         break;
221                                 case AltosLib.ao_flight_landed:
222                                         if (currentTab.equals("descent")) mTabHost.setCurrentTabByTag("landed");
223                                         break;
224                                 }
225                         }
226                 }
227                 saved_state = state;
228
229                 AltosGreatCircle from_receiver = null;
230
231                 if (state != null && saved_location != null && state.gps != null && state.gps.locked) {
232                         double altitude = 0;
233                         if (saved_location.hasAltitude())
234                                 altitude = saved_location.getAltitude();
235                         from_receiver = new AltosGreatCircle(saved_location.getLatitude(),
236                                                              saved_location.getLongitude(),
237                                                              altitude,
238                                                              state.gps.lat,
239                                                              state.gps.lon,
240                                                              state.gps.alt);
241                 }
242
243                 if (state != null) {
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));
249                 }
250
251                 for (AltosDroidTab mTab : mTabs)
252                         mTab.update_ui(state, from_receiver, saved_location);
253
254                 if (state != null)
255                         mAltosVoice.tell(state);
256         }
257
258         private void onTimerTick() {
259                 try {
260                         mMessenger.send(Message.obtain(null, MSG_UPDATE_AGE));
261                 } catch (RemoteException e) {
262                 }
263         }
264
265         static String pos(double p, String pos, String neg) {
266                 String  h = pos;
267                 if (p == AltosRecord.MISSING)
268                         return "";
269                 if (p < 0) {
270                         h = neg;
271                         p = -p;
272                 }
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);
276         }
277
278         static String number(String format, double value) {
279                 if (value == AltosRecord.MISSING)
280                         return "";
281                 return String.format(format, value);
282         }
283
284         static String integer(String format, int value) {
285                 if (value == AltosRecord.MISSING)
286                         return "";
287                 return String.format(format, value);
288         }
289
290         @Override
291         public void onCreate(Bundle savedInstanceState) {
292                 super.onCreate(savedInstanceState);
293                 if(D) Log.e(TAG, "+++ ON CREATE +++");
294
295                 // Get local Bluetooth adapter
296                 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
297
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();
301                         finish();
302                         return;
303                 }
304
305                 // Initialise preferences
306                 prefs = new AltosDroidPreferences(this);
307                 AltosPreferences.init(prefs);
308
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);
313
314                 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
315                 mTabHost.setup();
316
317                 mViewPager = (AltosViewPager)findViewById(R.id.pager);
318                 mViewPager.setOffscreenPageLimit(4);
319
320                 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
321
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);
327
328                 for (int i = 0; i < 5; i++)
329                         mTabHost.getTabWidget().getChildAt(i).getLayoutParams().height = 45;
330
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);
335
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 + ")");
341
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);
348
349                 timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 1000L, 100L);
350
351                 mAltosVoice = new AltosVoice(this);
352         }
353
354         @Override
355         public void onStart() {
356                 super.onStart();
357                 if(D) Log.e(TAG, "++ ON START ++");
358
359                 if (!mBluetoothAdapter.isEnabled()) {
360                         Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
361                         startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
362                 }
363
364                 // Start Telemetry Service
365                 startService(new Intent(AltosDroid.this, TelemetryService.class));
366
367                 doBindService();
368         }
369
370         @Override
371         public synchronized void onResume() {
372                 super.onResume();
373                 if(D) Log.e(TAG, "+ ON RESUME +");
374         }
375
376         @Override
377         public synchronized void onPause() {
378                 super.onPause();
379                 if(D) Log.e(TAG, "- ON PAUSE -");
380         }
381
382         @Override
383         public void onStop() {
384                 super.onStop();
385                 if(D) Log.e(TAG, "-- ON STOP --");
386
387                 doUnbindService();
388         }
389
390         @Override
391         public void onDestroy() {
392                 super.onDestroy();
393                 if(D) Log.e(TAG, "--- ON DESTROY ---");
394
395                 mAltosVoice.stop();
396         }
397
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) {
404                                 connectDevice(data);
405                         }
406                         break;
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
411                                 //setupChat();
412                         } else {
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();
417                                 finish();
418                         }
419                         break;
420                 }
421         }
422
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
429                 try {
430                         if (D) Log.d(TAG, "Connecting to " + device.getName());
431                         mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, device));
432                 } catch (RemoteException e) {
433                 }
434         }
435
436         @Override
437         public boolean onCreateOptionsMenu(Menu menu) {
438                 MenuInflater inflater = getMenuInflater();
439                 inflater.inflate(R.menu.option_menu, menu);
440                 return true;
441         }
442
443         void setFrequency(double freq) {
444                 try {
445                         mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
446                 } catch (RemoteException e) {
447                 }
448         }
449
450         void setFrequency(String freq) {
451                 try {
452                         setFrequency (Double.parseDouble(freq.substring(11, 17)));
453                 } catch (NumberFormatException e) {
454                 }
455         }
456
457         @Override
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);
465                         return true;
466                 case R.id.select_freq:
467                         // Set the TBT radio frequency
468
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)"
480                         };
481
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]);
488                                                  }
489                                          });
490                         AlertDialog alert = builder.create();
491                         alert.show();
492                         return true;
493                 }
494                 return false;
495         }
496
497 }