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