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