c94f36fda0d82a233f599d1212b2950e13fa8e55
[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.app.FragmentManager;
41 import android.util.DisplayMetrics;
42 import android.util.Log;
43 import android.view.Menu;
44 import android.view.MenuInflater;
45 import android.view.MenuItem;
46 import android.view.Window;
47 import android.widget.TabHost;
48 import android.widget.TextView;
49 import android.widget.Toast;
50 import android.app.AlertDialog;
51 import android.location.Location;
52
53 import org.altusmetrum.altoslib_5.*;
54
55 public class AltosDroid extends FragmentActivity {
56         // Debugging
57         static final String TAG = "AltosDroid";
58         static final boolean D = true;
59
60         // Message types received by our Handler
61         public static final int MSG_STATE_CHANGE    = 1;
62         public static final int MSG_TELEMETRY       = 2;
63         public static final int MSG_UPDATE_AGE      = 3;
64         public static final int MSG_LOCATION        = 4;
65         public static final int MSG_CRC_ERROR       = 5;
66
67         // Intent request codes
68         private static final int REQUEST_CONNECT_DEVICE = 1;
69         private static final int REQUEST_ENABLE_BT      = 2;
70
71         public static FragmentManager   fm;
72
73         // Layout Views
74         private TextView mTitle;
75
76         // Flight state values
77         private TextView mCallsignView;
78         private TextView mRSSIView;
79         private TextView mSerialView;
80         private TextView mFlightView;
81         private TextView mStateView;
82         private TextView mAgeView;
83
84         // field to display the version at the bottom of the screen
85         private TextView mVersion;
86
87         // Tabs
88         TabHost         mTabHost;
89         AltosViewPager  mViewPager;
90         TabsAdapter     mTabsAdapter;
91         ArrayList<AltosDroidTab> mTabs = new ArrayList<AltosDroidTab>();
92         int             tabHeight;
93
94         // Timer and Saved flight state for Age calculation
95         private Timer timer = new Timer();
96         AltosState saved_state;
97         Location saved_location;
98
99         // Service
100         private boolean mIsBound   = false;
101         private Messenger mService = null;
102         final Messenger mMessenger = new Messenger(new IncomingHandler(this));
103
104         // TeleBT Config data
105         private AltosConfigData mConfigData = null;
106         // Local Bluetooth adapter
107         private BluetoothAdapter mBluetoothAdapter = null;
108
109         // Text to Speech
110         private AltosVoice mAltosVoice = null;
111
112         // The Handler that gets information back from the Telemetry Service
113         static class IncomingHandler extends Handler {
114                 private final WeakReference<AltosDroid> mAltosDroid;
115                 IncomingHandler(AltosDroid ad) { mAltosDroid = new WeakReference<AltosDroid>(ad); }
116
117                 @Override
118                 public void handleMessage(Message msg) {
119                         AltosDroid ad = mAltosDroid.get();
120                         switch (msg.what) {
121                         case MSG_STATE_CHANGE:
122                                 if(D) Log.d(TAG, "MSG_STATE_CHANGE: " + msg.arg1);
123                                 switch (msg.arg1) {
124                                 case TelemetryService.STATE_CONNECTED:
125                                         ad.mConfigData = (AltosConfigData) msg.obj;
126                                         String str = String.format(" %s S/N: %d", ad.mConfigData.product, ad.mConfigData.serial);
127                                         ad.mTitle.setText(R.string.title_connected_to);
128                                         ad.mTitle.append(str);
129                                         Toast.makeText(ad.getApplicationContext(), "Connected to " + str, Toast.LENGTH_SHORT).show();
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                                 break;
149                         case MSG_UPDATE_AGE:
150                                 if (ad.saved_state != null) {
151                                         ad.mAgeView.setText(String.format("%d", (System.currentTimeMillis() - ad.saved_state.received_time + 500) / 1000));
152                                 }
153                                 break;
154                         }
155                 }
156         };
157
158
159         private ServiceConnection mConnection = new ServiceConnection() {
160                 public void onServiceConnected(ComponentName className, IBinder service) {
161                         mService = new Messenger(service);
162                         try {
163                                 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
164                                 msg.replyTo = mMessenger;
165                                 mService.send(msg);
166                         } catch (RemoteException e) {
167                                 // In this case the service has crashed before we could even do anything with it
168                         }
169                 }
170
171                 public void onServiceDisconnected(ComponentName className) {
172                         // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
173                         mService = null;
174                 }
175         };
176
177         void doBindService() {
178                 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
179                 mIsBound = true;
180         }
181
182         void doUnbindService() {
183                 if (mIsBound) {
184                         // If we have received the service, and hence registered with it, then now is the time to unregister.
185                         if (mService != null) {
186                                 try {
187                                         Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
188                                         msg.replyTo = mMessenger;
189                                         mService.send(msg);
190                                 } catch (RemoteException e) {
191                                         // There is nothing special we need to do if the service has crashed.
192                                 }
193                         }
194                         // Detach our existing connection.
195                         unbindService(mConnection);
196                         mIsBound = false;
197                 }
198         }
199
200         public void registerTab(AltosDroidTab mTab) {
201                 mTabs.add(mTab);
202         }
203
204         public void unregisterTab(AltosDroidTab mTab) {
205                 mTabs.remove(mTab);
206         }
207
208         void set_location(Location location) {
209                 saved_location = location;
210                 Log.d(TAG, "set_location");
211                 update_ui(saved_state);
212         }
213
214         boolean same_string(String a, String b) {
215                 if (a == null) {
216                         if (b == null)
217                                 return true;
218                         return false;
219                 } else {
220                         if (b == null)
221                                 return false;
222                         return a.equals(b);
223                 }
224         }
225
226         void update_ui(AltosState state) {
227
228                 Log.d(TAG, "update_ui");
229                 if (state != null && saved_state != null) {
230                         if (saved_state.state != state.state) {
231                                 String currentTab = mTabHost.getCurrentTabTag();
232                                 Log.d(TAG, "switch state");
233                                 switch (state.state) {
234                                 case AltosLib.ao_flight_boost:
235                                         if (currentTab.equals("pad")) mTabHost.setCurrentTabByTag("ascent");
236                                         break;
237                                 case AltosLib.ao_flight_drogue:
238                                         if (currentTab.equals("ascent")) mTabHost.setCurrentTabByTag("descent");
239                                         break;
240                                 case AltosLib.ao_flight_landed:
241                                         if (currentTab.equals("descent")) mTabHost.setCurrentTabByTag("landed");
242                                         break;
243                                 }
244                         }
245                 }
246
247                 AltosGreatCircle from_receiver = null;
248
249                 if (state != null && saved_location != null && state.gps != null && state.gps.locked) {
250                         double altitude = 0;
251                         if (saved_location.hasAltitude())
252                                 altitude = saved_location.getAltitude();
253                         from_receiver = new AltosGreatCircle(saved_location.getLatitude(),
254                                                              saved_location.getLongitude(),
255                                                              altitude,
256                                                              state.gps.lat,
257                                                              state.gps.lon,
258                                                              state.gps.alt);
259                 }
260
261                 if (state != null) {
262                         if (saved_state == null || !same_string(saved_state.callsign, state.callsign)) {
263                                 Log.d(TAG, "update callsign");
264                                 mCallsignView.setText(state.callsign);
265                         }
266                         if (saved_state == null || state.serial != saved_state.serial) {
267                                 Log.d(TAG, "update serial");
268                                 mSerialView.setText(String.format("%d", state.serial));
269                         }
270                         if (saved_state == null || state.flight != saved_state.flight) {
271                                 Log.d(TAG, "update flight");
272                                 mFlightView.setText(String.format("%d", state.flight));
273                         }
274                         if (saved_state == null || state.state != saved_state.state) {
275                                 Log.d(TAG, "update state");
276                                 mStateView.setText(state.state_name());
277                         }
278                         if (saved_state == null || state.rssi != saved_state.rssi) {
279                                 Log.d(TAG, "update rssi");
280                                 mRSSIView.setText(String.format("%d", state.rssi));
281                         }
282                 }
283
284                 for (AltosDroidTab mTab : mTabs)
285                         mTab.update_ui(state, from_receiver, saved_location, mTab == mTabsAdapter.currentItem());
286
287                 if (state != null)
288                         mAltosVoice.tell(state);
289
290                 saved_state = state;
291         }
292
293         private void onTimerTick() {
294                 try {
295                         mMessenger.send(Message.obtain(null, MSG_UPDATE_AGE));
296                 } catch (RemoteException e) {
297                 }
298         }
299
300         static String pos(double p, String pos, String neg) {
301                 String  h = pos;
302                 if (p == AltosLib.MISSING)
303                         return "";
304                 if (p < 0) {
305                         h = neg;
306                         p = -p;
307                 }
308                 int deg = (int) Math.floor(p);
309                 double min = (p - Math.floor(p)) * 60.0;
310                 return String.format("%d°%9.4f\" %s", deg, min, h);
311         }
312
313         static String number(String format, double value) {
314                 if (value == AltosLib.MISSING)
315                         return "";
316                 return String.format(format, value);
317         }
318
319         static String integer(String format, int value) {
320                 if (value == AltosLib.MISSING)
321                         return "";
322                 return String.format(format, value);
323         }
324
325         @Override
326         public void onCreate(Bundle savedInstanceState) {
327                 super.onCreate(savedInstanceState);
328                 if(D) Log.e(TAG, "+++ ON CREATE +++");
329
330                 fm = getSupportFragmentManager();
331
332                 // Get local Bluetooth adapter
333                 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
334
335                 // If the adapter is null, then Bluetooth is not supported
336                 if (mBluetoothAdapter == null) {
337                         Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
338                         finish();
339                         return;
340                 }
341
342                 // Initialise preferences
343                 AltosDroidPreferences.init(this);
344
345                 // Set up the window layout
346                 requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
347                 setContentView(R.layout.altosdroid);
348                 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
349
350                 // Create the Tabs and ViewPager
351                 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
352                 mTabHost.setup();
353
354                 mViewPager = (AltosViewPager)findViewById(R.id.pager);
355                 mViewPager.setOffscreenPageLimit(4);
356
357                 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
358
359                 mTabsAdapter.addTab(mTabHost.newTabSpec("pad").setIndicator("Pad"), TabPad.class, null);
360                 mTabsAdapter.addTab(mTabHost.newTabSpec("ascent").setIndicator("Ascent"), TabAscent.class, null);
361                 mTabsAdapter.addTab(mTabHost.newTabSpec("descent").setIndicator("Descent"), TabDescent.class, null);
362                 mTabsAdapter.addTab(mTabHost.newTabSpec("landed").setIndicator("Landed"), TabLanded.class, null);
363                 mTabsAdapter.addTab(mTabHost.newTabSpec("map").setIndicator("Map"), TabMap.class, null);
364
365
366                 // Scale the size of the Tab bar for different screen densities
367                 // This probably won't be needed when we start supporting ICS+ tabs.
368                 DisplayMetrics metrics = new DisplayMetrics();
369                 getWindowManager().getDefaultDisplay().getMetrics(metrics);
370                 int density = metrics.densityDpi;
371
372                 if (density==DisplayMetrics.DENSITY_XHIGH)
373                         tabHeight = 65;
374                 else if (density==DisplayMetrics.DENSITY_HIGH)
375                         tabHeight = 45;
376                 else if (density==DisplayMetrics.DENSITY_MEDIUM)
377                         tabHeight = 35;
378                 else if (density==DisplayMetrics.DENSITY_LOW)
379                         tabHeight = 25;
380                 else
381                         tabHeight = 65;
382
383                 for (int i = 0; i < 5; i++)
384                         mTabHost.getTabWidget().getChildAt(i).getLayoutParams().height = tabHeight;
385
386
387                 // Set up the custom title
388                 mTitle = (TextView) findViewById(R.id.title_left_text);
389                 mTitle.setText(R.string.app_name);
390                 mTitle = (TextView) findViewById(R.id.title_right_text);
391
392                 // Display the Version
393                 mVersion = (TextView) findViewById(R.id.version);
394                 mVersion.setText("Version: " + BuildInfo.version +
395                                  "  Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
396                                  "  (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
397
398                 mCallsignView  = (TextView) findViewById(R.id.callsign_value);
399                 mRSSIView      = (TextView) findViewById(R.id.rssi_value);
400                 mSerialView    = (TextView) findViewById(R.id.serial_value);
401                 mFlightView    = (TextView) findViewById(R.id.flight_value);
402                 mStateView     = (TextView) findViewById(R.id.state_value);
403                 mAgeView       = (TextView) findViewById(R.id.age_value);
404
405                 timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 1000L, 100L);
406
407                 mAltosVoice = new AltosVoice(this);
408         }
409
410         @Override
411         public void onStart() {
412                 super.onStart();
413                 if(D) Log.e(TAG, "++ ON START ++");
414
415                 if (!mBluetoothAdapter.isEnabled()) {
416                         Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
417                         startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
418                 }
419
420                 // Start Telemetry Service
421                 startService(new Intent(AltosDroid.this, TelemetryService.class));
422
423                 doBindService();
424         }
425
426         @Override
427         public synchronized void onResume() {
428                 super.onResume();
429                 if(D) Log.e(TAG, "+ ON RESUME +");
430         }
431
432         @Override
433         public synchronized void onPause() {
434                 super.onPause();
435                 if(D) Log.e(TAG, "- ON PAUSE -");
436         }
437
438         @Override
439         public void onStop() {
440                 super.onStop();
441                 if(D) Log.e(TAG, "-- ON STOP --");
442
443                 doUnbindService();
444         }
445
446         @Override
447         public void onDestroy() {
448                 super.onDestroy();
449                 if(D) Log.e(TAG, "--- ON DESTROY ---");
450
451                 if (mAltosVoice != null) mAltosVoice.stop();
452         }
453
454         public void onActivityResult(int requestCode, int resultCode, Intent data) {
455                 if(D) Log.d(TAG, "onActivityResult " + resultCode);
456                 switch (requestCode) {
457                 case REQUEST_CONNECT_DEVICE:
458                         // When DeviceListActivity returns with a device to connect to
459                         if (resultCode == Activity.RESULT_OK) {
460                                 connectDevice(data);
461                         }
462                         break;
463                 case REQUEST_ENABLE_BT:
464                         // When the request to enable Bluetooth returns
465                         if (resultCode == Activity.RESULT_OK) {
466                                 // Bluetooth is now enabled, so set up a chat session
467                                 //setupChat();
468                         } else {
469                                 // User did not enable Bluetooth or an error occured
470                                 Log.e(TAG, "BT not enabled");
471                                 stopService(new Intent(AltosDroid.this, TelemetryService.class));
472                                 Toast.makeText(this, R.string.bt_not_enabled, Toast.LENGTH_SHORT).show();
473                                 finish();
474                         }
475                         break;
476                 }
477         }
478
479         private void connectDevice(String address) {
480                 // Get the BLuetoothDevice object
481                 BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
482                 // Attempt to connect to the device
483                 try {
484                         if (D) Log.d(TAG, "Connecting to " + device.getName());
485                         mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, device));
486                 } catch (RemoteException e) {
487                 }
488         }
489
490         private void connectDevice(Intent data) {
491                 // Get the device MAC address
492                 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
493                 connectDevice(address);
494         }
495
496         @Override
497         public boolean onCreateOptionsMenu(Menu menu) {
498                 MenuInflater inflater = getMenuInflater();
499                 inflater.inflate(R.menu.option_menu, menu);
500                 return true;
501         }
502
503         void setFrequency(double freq) {
504                 try {
505                         mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
506                 } catch (RemoteException e) {
507                 }
508         }
509
510         void setFrequency(String freq) {
511                 try {
512                         setFrequency (Double.parseDouble(freq.substring(11, 17)));
513                 } catch (NumberFormatException e) {
514                 }
515         }
516
517         void setBaud(int baud) {
518                 try {
519                         mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD, baud));
520                 } catch (RemoteException e) {
521                 }
522         }
523
524         void setBaud(String baud) {
525                 try {
526                         int     value = Integer.parseInt(baud);
527                         int     rate = AltosLib.ao_telemetry_rate_38400;
528                         switch (value) {
529                         case 2400:
530                                 rate = AltosLib.ao_telemetry_rate_2400;
531                                 break;
532                         case 9600:
533                                 rate = AltosLib.ao_telemetry_rate_9600;
534                                 break;
535                         case 38400:
536                                 rate = AltosLib.ao_telemetry_rate_38400;
537                                 break;
538                         }
539                         setBaud(rate);
540                 } catch (NumberFormatException e) {
541                 }
542         }
543
544         @Override
545         public boolean onOptionsItemSelected(MenuItem item) {
546                 Intent serverIntent = null;
547                 switch (item.getItemId()) {
548                 case R.id.connect_scan:
549                         // Launch the DeviceListActivity to see devices and do scan
550                         serverIntent = new Intent(this, DeviceListActivity.class);
551                         startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
552                         return true;
553                 case R.id.select_freq:
554                         // Set the TBT radio frequency
555
556                         final String[] frequencies = {
557                                 "Channel 0 (434.550MHz)",
558                                 "Channel 1 (434.650MHz)",
559                                 "Channel 2 (434.750MHz)",
560                                 "Channel 3 (434.850MHz)",
561                                 "Channel 4 (434.950MHz)",
562                                 "Channel 5 (435.050MHz)",
563                                 "Channel 6 (435.150MHz)",
564                                 "Channel 7 (435.250MHz)",
565                                 "Channel 8 (435.350MHz)",
566                                 "Channel 9 (435.450MHz)"
567                         };
568
569                         AlertDialog.Builder builder_freq = new AlertDialog.Builder(this);
570                         builder_freq.setTitle("Pick a frequency");
571                         builder_freq.setItems(frequencies,
572                                          new DialogInterface.OnClickListener() {
573                                                  public void onClick(DialogInterface dialog, int item) {
574                                                          setFrequency(frequencies[item]);
575                                                  }
576                                          });
577                         AlertDialog alert_freq = builder_freq.create();
578                         alert_freq.show();
579                         return true;
580                 case R.id.select_rate:
581                         // Set the TBT baud rate
582
583                         final String[] rates = {
584                                 "38400",
585                                 "9600",
586                                 "2400",
587                         };
588
589                         AlertDialog.Builder builder_rate = new AlertDialog.Builder(this);
590                         builder_rate.setTitle("Pick a baud rate");
591                         builder_rate.setItems(rates,
592                                          new DialogInterface.OnClickListener() {
593                                                  public void onClick(DialogInterface dialog, int item) {
594                                                          setBaud(rates[item]);
595                                                  }
596                                          });
597                         AlertDialog alert_rate = builder_rate.create();
598                         alert_rate.show();
599                         return true;
600                 }
601                 return false;
602         }
603
604 }