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