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