altosdroid: Check for missing values
[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.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;
50 import android.location.Location;
51
52 import org.altusmetrum.altoslib_1.*;
53
54 public class AltosDroid extends FragmentActivity {
55         // Debugging
56         private static final String TAG = "AltosDroid";
57         private static final boolean D = true;
58
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;
65
66         // Intent request codes
67         private static final int REQUEST_CONNECT_DEVICE = 1;
68         private static final int REQUEST_ENABLE_BT      = 2;
69
70         // Layout Views
71         private TextView mTitle;
72
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;
80
81         // field to display the version at the bottom of the screen
82         private TextView mVersion;
83
84         // Tabs
85         TabHost     mTabHost;
86         AltosViewPager   mViewPager;
87         TabsAdapter mTabsAdapter;
88         ArrayList<AltosDroidTab> mTabs = new ArrayList<AltosDroidTab>();
89
90         // Timer and Saved flight state for Age calculation
91         private Timer timer = new Timer();
92         AltosState saved_state;
93         Location saved_location;
94
95         // Service
96         private boolean mIsBound   = false;
97         private Messenger mService = null;
98         final Messenger mMessenger = new Messenger(new IncomingHandler(this));
99
100         // Preferences
101         private AltosDroidPreferences prefs = null;
102
103         // TeleBT Config data
104         private AltosConfigData mConfigData = null;
105         // Local Bluetooth adapter
106         private BluetoothAdapter mBluetoothAdapter = null;
107
108         // Text to Speech
109         private AltosVoice mAltosVoice = null;
110
111         // The Handler that gets information back from the Telemetry Service
112         static class IncomingHandler extends Handler {
113                 private final WeakReference<AltosDroid> mAltosDroid;
114                 IncomingHandler(AltosDroid ad) { mAltosDroid = new WeakReference<AltosDroid>(ad); }
115
116                 @Override
117                 public void handleMessage(Message msg) {
118                         AltosDroid ad = mAltosDroid.get();
119                         switch (msg.what) {
120                         case MSG_STATE_CHANGE:
121                                 if(D) Log.d(TAG, "MSG_STATE_CHANGE: " + msg.arg1);
122                                 switch (msg.arg1) {
123                                 case TelemetryService.STATE_CONNECTED:
124                                         ad.mConfigData = (AltosConfigData) msg.obj;
125                                         String str = String.format(" %s S/N: %d", ad.mConfigData.product, ad.mConfigData.serial);
126                                         ad.mTitle.setText(R.string.title_connected_to);
127                                         ad.mTitle.append(str);
128                                         Toast.makeText(ad.getApplicationContext(), "Connected to " + str, Toast.LENGTH_SHORT).show();
129                                         break;
130                                 case TelemetryService.STATE_CONNECTING:
131                                         ad.mTitle.setText(R.string.title_connecting);
132                                         break;
133                                 case TelemetryService.STATE_READY:
134                                 case TelemetryService.STATE_NONE:
135                                         ad.mConfigData = null;
136                                         ad.mTitle.setText(R.string.title_not_connected);
137                                         break;
138                                 }
139                                 break;
140                         case MSG_TELEMETRY:
141                                 ad.update_ui((AltosState) msg.obj);
142                                 break;
143                         case MSG_LOCATION:
144                                 ad.set_location((Location) msg.obj);
145                                 break;
146                         case MSG_CRC_ERROR:
147                         case MSG_UPDATE_AGE:
148                                 if (ad.saved_state != null) {
149                                         ad.mAgeView.setText(String.format("%d", (System.currentTimeMillis() - ad.saved_state.report_time + 500) / 1000));
150                                 }
151                                 break;
152                         }
153                 }
154         };
155
156
157         private ServiceConnection mConnection = new ServiceConnection() {
158                 public void onServiceConnected(ComponentName className, IBinder service) {
159                         mService = new Messenger(service);
160                         try {
161                                 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
162                                 msg.replyTo = mMessenger;
163                                 mService.send(msg);
164                         } catch (RemoteException e) {
165                                 // In this case the service has crashed before we could even do anything with it
166                         }
167                 }
168
169                 public void onServiceDisconnected(ComponentName className) {
170                         // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
171                         mService = null;
172                 }
173         };
174
175         void doBindService() {
176                 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
177                 mIsBound = true;
178         }
179
180         void doUnbindService() {
181                 if (mIsBound) {
182                         // If we have received the service, and hence registered with it, then now is the time to unregister.
183                         if (mService != null) {
184                                 try {
185                                         Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
186                                         msg.replyTo = mMessenger;
187                                         mService.send(msg);
188                                 } catch (RemoteException e) {
189                                         // There is nothing special we need to do if the service has crashed.
190                                 }
191                         }
192                         // Detach our existing connection.
193                         unbindService(mConnection);
194                         mIsBound = false;
195                 }
196         }
197
198         public void registerTab(AltosDroidTab mTab) {
199                 mTabs.add(mTab);
200         }
201
202         public void unregisterTab(AltosDroidTab mTab) {
203                 mTabs.remove(mTab);
204         }
205
206         void set_location(Location location) {
207                 saved_location = location;
208                 update_ui(saved_state);
209         }
210
211         void update_ui(AltosState state) {
212                 if (state != null && saved_state != null) {
213                         if (saved_state.state != state.state) {
214                                 String currentTab = mTabHost.getCurrentTabTag();
215                                 switch (state.state) {
216                                 case AltosLib.ao_flight_boost:
217                                         if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("ascent");
218                                         break;
219                                 case AltosLib.ao_flight_drogue:
220                                         if (currentTab.equals("ascent")) mTabHost.setCurrentTabByTag("descent");
221                                         break;
222                                 case AltosLib.ao_flight_landed:
223                                         if (currentTab.equals("descent")) mTabHost.setCurrentTabByTag("landed");
224                                         break;
225                                 }
226                         }
227                 }
228                 saved_state = state;
229
230                 AltosGreatCircle from_receiver = null;
231
232                 if (state != null && saved_location != null && state.gps != null && state.gps.locked) {
233                         double altitude = 0;
234                         if (saved_location.hasAltitude())
235                                 altitude = saved_location.getAltitude();
236                         from_receiver = new AltosGreatCircle(saved_location.getLatitude(),
237                                                              saved_location.getLongitude(),
238                                                              altitude,
239                                                              state.gps.lat,
240                                                              state.gps.lon,
241                                                              state.gps.alt);
242                 }
243
244                 if (state != null) {
245                         mCallsignView.setText(state.data.callsign);
246                         mSerialView.setText(String.format("%d", state.data.serial));
247                         mFlightView.setText(String.format("%d", state.data.flight));
248                         mStateView.setText(state.data.state());
249                         mRSSIView.setText(String.format("%d", state.data.rssi));
250                 }
251
252                 for (AltosDroidTab mTab : mTabs)
253                         mTab.update_ui(state, from_receiver, saved_location);
254
255                 if (state != null)
256                         mAltosVoice.tell(state);
257         }
258
259         private void onTimerTick() {
260                 try {
261                         mMessenger.send(Message.obtain(null, MSG_UPDATE_AGE));
262                 } catch (RemoteException e) {
263                 }
264         }
265
266         static String pos(double p, String pos, String neg) {
267                 String  h = pos;
268                 if (p == AltosRecord.MISSING)
269                         return "";
270                 if (p < 0) {
271                         h = neg;
272                         p = -p;
273                 }
274                 int deg = (int) Math.floor(p);
275                 double min = (p - Math.floor(p)) * 60.0;
276                 return String.format("%d°%9.4f\" %s", deg, min, h);
277         }
278
279         static String number(String format, double value) {
280                 if (value == AltosRecord.MISSING)
281                         return "";
282                 return String.format(format, value);
283         }
284
285         @Override
286         public void onCreate(Bundle savedInstanceState) {
287                 super.onCreate(savedInstanceState);
288                 if(D) Log.e(TAG, "+++ ON CREATE +++");
289
290                 // Get local Bluetooth adapter
291                 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
292
293                 // If the adapter is null, then Bluetooth is not supported
294                 if (mBluetoothAdapter == null) {
295                         Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
296                         finish();
297                         return;
298                 }
299
300                 // Initialise preferences
301                 prefs = new AltosDroidPreferences(this);
302                 AltosPreferences.init(prefs);
303
304                 // Set up the window layout
305                 requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
306                 setContentView(R.layout.altosdroid);
307                 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
308
309                 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
310                 mTabHost.setup();
311
312                 mViewPager = (AltosViewPager)findViewById(R.id.pager);
313                 mViewPager.setOffscreenPageLimit(4);
314
315                 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
316
317                 mTabsAdapter.addTab(mTabHost.newTabSpec("pad").setIndicator("Pad"), TabPad.class, null);
318                 mTabsAdapter.addTab(mTabHost.newTabSpec("ascent").setIndicator("Ascent"), TabAscent.class, null);
319                 mTabsAdapter.addTab(mTabHost.newTabSpec("descent").setIndicator("Descent"), TabDescent.class, null);
320                 mTabsAdapter.addTab(mTabHost.newTabSpec("landed").setIndicator("Landed"), TabLanded.class, null);
321                 mTabsAdapter.addTab(mTabHost.newTabSpec("map").setIndicator("Map"), TabMap.class, null);
322
323                 for (int i = 0; i < 5; i++)
324                         mTabHost.getTabWidget().getChildAt(i).getLayoutParams().height = 45;
325
326                 // Set up the custom title
327                 mTitle = (TextView) findViewById(R.id.title_left_text);
328                 mTitle.setText(R.string.app_name);
329                 mTitle = (TextView) findViewById(R.id.title_right_text);
330
331                 // Display the Version
332                 mVersion = (TextView) findViewById(R.id.version);
333                 mVersion.setText("Version: " + BuildInfo.version +
334                                  "  Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
335                                  "  (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
336
337                 mCallsignView  = (TextView) findViewById(R.id.callsign_value);
338                 mRSSIView      = (TextView) findViewById(R.id.rssi_value);
339                 mSerialView    = (TextView) findViewById(R.id.serial_value);
340                 mFlightView    = (TextView) findViewById(R.id.flight_value);
341                 mStateView     = (TextView) findViewById(R.id.state_value);
342                 mAgeView       = (TextView) findViewById(R.id.age_value);
343
344                 timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 1000L, 100L);
345
346                 mAltosVoice = new AltosVoice(this);
347         }
348
349         @Override
350         public void onStart() {
351                 super.onStart();
352                 if(D) Log.e(TAG, "++ ON START ++");
353
354                 if (!mBluetoothAdapter.isEnabled()) {
355                         Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
356                         startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
357                 }
358
359                 // Start Telemetry Service
360                 startService(new Intent(AltosDroid.this, TelemetryService.class));
361
362                 doBindService();
363         }
364
365         @Override
366         public synchronized void onResume() {
367                 super.onResume();
368                 if(D) Log.e(TAG, "+ ON RESUME +");
369         }
370
371         @Override
372         public synchronized void onPause() {
373                 super.onPause();
374                 if(D) Log.e(TAG, "- ON PAUSE -");
375         }
376
377         @Override
378         public void onStop() {
379                 super.onStop();
380                 if(D) Log.e(TAG, "-- ON STOP --");
381
382                 doUnbindService();
383         }
384
385         @Override
386         public void onDestroy() {
387                 super.onDestroy();
388                 if(D) Log.e(TAG, "--- ON DESTROY ---");
389
390                 mAltosVoice.stop();
391         }
392
393         public void onActivityResult(int requestCode, int resultCode, Intent data) {
394                 if(D) Log.d(TAG, "onActivityResult " + resultCode);
395                 switch (requestCode) {
396                 case REQUEST_CONNECT_DEVICE:
397                         // When DeviceListActivity returns with a device to connect to
398                         if (resultCode == Activity.RESULT_OK) {
399                                 connectDevice(data);
400                         }
401                         break;
402                 case REQUEST_ENABLE_BT:
403                         // When the request to enable Bluetooth returns
404                         if (resultCode == Activity.RESULT_OK) {
405                                 // Bluetooth is now enabled, so set up a chat session
406                                 //setupChat();
407                         } else {
408                                 // User did not enable Bluetooth or an error occured
409                                 Log.e(TAG, "BT not enabled");
410                                 stopService(new Intent(AltosDroid.this, TelemetryService.class));
411                                 Toast.makeText(this, R.string.bt_not_enabled, Toast.LENGTH_SHORT).show();
412                                 finish();
413                         }
414                         break;
415                 }
416         }
417
418         private void connectDevice(Intent data) {
419                 // Get the device MAC address
420                 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
421                 // Get the BLuetoothDevice object
422                 BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
423                 // Attempt to connect to the device
424                 try {
425                         if (D) Log.d(TAG, "Connecting to " + device.getName());
426                         mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, device));
427                 } catch (RemoteException e) {
428                 }
429         }
430
431         @Override
432         public boolean onCreateOptionsMenu(Menu menu) {
433                 MenuInflater inflater = getMenuInflater();
434                 inflater.inflate(R.menu.option_menu, menu);
435                 return true;
436         }
437
438         void setFrequency(double freq) {
439                 try {
440                         mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
441                 } catch (RemoteException e) {
442                 }
443         }
444
445         void setFrequency(String freq) {
446                 try {
447                         setFrequency (Double.parseDouble(freq.substring(11, 17)));
448                 } catch (NumberFormatException e) {
449                 }
450         }
451
452         @Override
453         public boolean onOptionsItemSelected(MenuItem item) {
454                 Intent serverIntent = null;
455                 switch (item.getItemId()) {
456                 case R.id.connect_scan:
457                         // Launch the DeviceListActivity to see devices and do scan
458                         serverIntent = new Intent(this, DeviceListActivity.class);
459                         startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
460                         return true;
461                 case R.id.select_freq:
462                         // Set the TBT radio frequency
463
464                         final String[] frequencies = {
465                                 "Channel 0 (434.550MHz)",
466                                 "Channel 1 (434.650MHz)",
467                                 "Channel 2 (434.750MHz)",
468                                 "Channel 3 (434.850MHz)",
469                                 "Channel 4 (434.950MHz)",
470                                 "Channel 5 (435.050MHz)",
471                                 "Channel 6 (435.150MHz)",
472                                 "Channel 7 (435.250MHz)",
473                                 "Channel 8 (435.350MHz)",
474                                 "Channel 9 (435.450MHz)"
475                         };
476
477                         AlertDialog.Builder builder = new AlertDialog.Builder(this);
478                         builder.setTitle("Pick a frequency");
479                         builder.setItems(frequencies,
480                                          new DialogInterface.OnClickListener() {
481                                                  public void onClick(DialogInterface dialog, int item) {
482                                                          setFrequency(frequencies[item]);
483                                                  }
484                                          });
485                         AlertDialog alert = builder.create();
486                         alert.show();
487                         return true;
488                 }
489                 return false;
490         }
491
492 }