2f98b64bfffeb0eb80a808911bb33132136c4268
[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         ViewPager   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                 saved_state = state;
201
202                 mCallsignView.setText(state.data.callsign);
203                 mSerialView.setText(String.format("%d", state.data.serial));
204                 mFlightView.setText(String.format("%d", state.data.flight));
205                 mStateView.setText(state.data.state());
206                 mRSSIView.setText(String.format("%d", state.data.rssi));
207
208                 for (AltosDroidTab mTab : mTabs)
209                         mTab.update_ui(state);
210
211                 mAltosVoice.tell(state);
212         }
213
214         private void onTimerTick() {
215                 try {
216                         mMessenger.send(Message.obtain(null, MSG_UPDATE_AGE));
217                 } catch (RemoteException e) {
218                 }
219         }
220
221         static String pos(double p, String pos, String neg) {
222                 String  h = pos;
223                 if (p < 0) {
224                         h = neg;
225                         p = -p;
226                 }
227                 int deg = (int) Math.floor(p);
228                 double min = (p - Math.floor(p)) * 60.0;
229                 return String.format("%d° %9.6f\" %s", deg, min, h);
230         }
231
232         @Override
233         public void onCreate(Bundle savedInstanceState) {
234                 super.onCreate(savedInstanceState);
235                 if(D) Log.e(TAG, "+++ ON CREATE +++");
236
237                 // Get local Bluetooth adapter
238                 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
239
240                 // If the adapter is null, then Bluetooth is not supported
241                 if (mBluetoothAdapter == null) {
242                         Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
243                         finish();
244                         return;
245                 }
246
247                 // Initialise preferences
248                 prefs = new AltosDroidPreferences(this);
249                 AltosPreferences.init(prefs);
250
251                 // Set up the window layout
252                 requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
253                 setContentView(R.layout.altosdroid);
254                 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
255
256                 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
257                 mTabHost.setup();
258
259                 mViewPager = (ViewPager)findViewById(R.id.pager);
260                 mViewPager.setOffscreenPageLimit(4);
261
262                 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
263
264                 mTabsAdapter.addTab(mTabHost.newTabSpec("pad").setIndicator("Pad"), TabPad.class, null);
265                 mTabsAdapter.addTab(mTabHost.newTabSpec("ascent").setIndicator("Ascent"), TabAscent.class, null);
266                 mTabsAdapter.addTab(mTabHost.newTabSpec("descent").setIndicator("Descent"), TabDescent.class, null);
267                 mTabsAdapter.addTab(mTabHost.newTabSpec("landed").setIndicator("Landed"), TabLanded.class, null);
268                 mTabsAdapter.addTab(mTabHost.newTabSpec("map").setIndicator("Map"), TabMap.class, null);
269
270
271                 // Set up the custom title
272                 mTitle = (TextView) findViewById(R.id.title_left_text);
273                 mTitle.setText(R.string.app_name);
274                 mTitle = (TextView) findViewById(R.id.title_right_text);
275
276                 // Display the Version
277                 mVersion = (TextView) findViewById(R.id.version);
278                 mVersion.setText("Version: " + BuildInfo.version +
279                                  "  Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
280                                  "  (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
281
282                 mCallsignView  = (TextView) findViewById(R.id.callsign_value);
283                 mRSSIView      = (TextView) findViewById(R.id.rssi_value);
284                 mSerialView    = (TextView) findViewById(R.id.serial_value);
285                 mFlightView    = (TextView) findViewById(R.id.flight_value);
286                 mStateView     = (TextView) findViewById(R.id.state_value);
287                 mAgeView       = (TextView) findViewById(R.id.age_value);
288
289                 timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 1000L, 100L);
290
291                 mAltosVoice = new AltosVoice(this);
292         }
293
294         @Override
295         public void onStart() {
296                 super.onStart();
297                 if(D) Log.e(TAG, "++ ON START ++");
298
299                 if (!mBluetoothAdapter.isEnabled()) {
300                         Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
301                         startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
302                 }
303
304                 // Start Telemetry Service
305                 startService(new Intent(AltosDroid.this, TelemetryService.class));
306
307                 doBindService();
308         }
309
310         @Override
311         public synchronized void onResume() {
312                 super.onResume();
313                 if(D) Log.e(TAG, "+ ON RESUME +");
314         }
315
316         @Override
317         public synchronized void onPause() {
318                 super.onPause();
319                 if(D) Log.e(TAG, "- ON PAUSE -");
320         }
321
322         @Override
323         public void onStop() {
324                 super.onStop();
325                 if(D) Log.e(TAG, "-- ON STOP --");
326
327                 doUnbindService();
328         }
329
330         @Override
331         public void onDestroy() {
332                 super.onDestroy();
333                 if(D) Log.e(TAG, "--- ON DESTROY ---");
334
335                 mAltosVoice.stop();
336         }
337
338         public void onActivityResult(int requestCode, int resultCode, Intent data) {
339                 if(D) Log.d(TAG, "onActivityResult " + resultCode);
340                 switch (requestCode) {
341                 case REQUEST_CONNECT_DEVICE:
342                         // When DeviceListActivity returns with a device to connect to
343                         if (resultCode == Activity.RESULT_OK) {
344                                 connectDevice(data);
345                         }
346                         break;
347                 case REQUEST_ENABLE_BT:
348                         // When the request to enable Bluetooth returns
349                         if (resultCode == Activity.RESULT_OK) {
350                                 // Bluetooth is now enabled, so set up a chat session
351                                 //setupChat();
352                         } else {
353                                 // User did not enable Bluetooth or an error occured
354                                 Log.e(TAG, "BT not enabled");
355                                 stopService(new Intent(AltosDroid.this, TelemetryService.class));
356                                 Toast.makeText(this, R.string.bt_not_enabled, Toast.LENGTH_SHORT).show();
357                                 finish();
358                         }
359                         break;
360                 }
361         }
362
363         private void connectDevice(Intent data) {
364                 // Get the device MAC address
365                 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
366                 // Get the BLuetoothDevice object
367                 BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
368                 // Attempt to connect to the device
369                 try {
370                         if (D) Log.d(TAG, "Connecting to " + device.getName());
371                         mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, device));
372                 } catch (RemoteException e) {
373                 }
374         }
375
376         @Override
377         public boolean onCreateOptionsMenu(Menu menu) {
378                 MenuInflater inflater = getMenuInflater();
379                 inflater.inflate(R.menu.option_menu, menu);
380                 return true;
381         }
382
383         void setFrequency(double freq) {
384                 try {
385                         mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
386                 } catch (RemoteException e) {
387                 }
388         }
389
390         void setFrequency(String freq) {
391                 try {
392                         setFrequency (Double.parseDouble(freq.substring(11, 17)));
393                 } catch (NumberFormatException e) {
394                 }
395         }
396
397         @Override
398         public boolean onOptionsItemSelected(MenuItem item) {
399                 Intent serverIntent = null;
400                 switch (item.getItemId()) {
401                 case R.id.connect_scan:
402                         // Launch the DeviceListActivity to see devices and do scan
403                         serverIntent = new Intent(this, DeviceListActivity.class);
404                         startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
405                         return true;
406                 case R.id.select_freq:
407                         // Set the TBT radio frequency
408
409                         final String[] frequencies = {
410                                 "Channel 0 (434.550MHz)",
411                                 "Channel 1 (434.650MHz)",
412                                 "Channel 2 (434.750MHz)",
413                                 "Channel 3 (434.850MHz)",
414                                 "Channel 4 (434.950MHz)",
415                                 "Channel 5 (435.050MHz)",
416                                 "Channel 6 (435.150MHz)",
417                                 "Channel 7 (435.250MHz)",
418                                 "Channel 8 (435.350MHz)",
419                                 "Channel 9 (435.450MHz)"
420                         };
421
422                         AlertDialog.Builder builder = new AlertDialog.Builder(this);
423                         builder.setTitle("Pick a frequency");
424                         builder.setItems(frequencies,
425                                          new DialogInterface.OnClickListener() {
426                                                  public void onClick(DialogInterface dialog, int item) {
427                                                          setFrequency(frequencies[item]);
428                                                  }
429                                          });
430                         AlertDialog alert = builder.create();
431                         alert.show();
432                         return true;
433                 }
434                 return false;
435         }
436
437 }