Merge branch 'telescience-v0.2'
[fw/altos] / altosdroid / src / org / altusmetrum / AltosDroid / AltosDroid.java
1 /*
2  * Copyright © 2012 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
22 import android.app.Activity;
23 import android.bluetooth.BluetoothAdapter;
24 import android.bluetooth.BluetoothDevice;
25 import android.content.Intent;
26 import android.content.Context;
27 import android.content.ComponentName;
28 import android.content.ServiceConnection;
29 import android.content.DialogInterface;
30 import android.os.IBinder;
31 import android.os.Bundle;
32 import android.os.Handler;
33 import android.os.Message;
34 import android.os.Messenger;
35 import android.os.RemoteException;
36 import android.text.method.ScrollingMovementMethod;
37 import android.util.Log;
38 import android.view.Menu;
39 import android.view.MenuInflater;
40 import android.view.MenuItem;
41 import android.view.Window;
42 import android.widget.TextView;
43 import android.widget.Toast;
44 import android.app.AlertDialog;
45
46 import org.altusmetrum.altoslib_1.*;
47
48 /**
49  * This is the main Activity that displays the current chat session.
50  */
51 public class AltosDroid extends Activity {
52         // Debugging
53         private static final String TAG = "AltosDroid";
54         private static final boolean D = true;
55
56         // Message types received by our Handler
57         public static final int MSG_STATE_CHANGE    = 1;
58         public static final int MSG_TELEMETRY       = 2;
59
60         // Intent request codes
61         private static final int REQUEST_CONNECT_DEVICE = 1;
62         private static final int REQUEST_ENABLE_BT      = 2;
63
64         // Layout Views
65         private TextView mTitle;
66
67         // Flight state values
68         private TextView mCallsignView;
69         private TextView mRSSIView;
70         private TextView mSerialView;
71         private TextView mFlightView;
72         private TextView mStateView;
73         private TextView mSpeedView;
74         private TextView mAccelView;
75         private TextView mRangeView;
76         private TextView mHeightView;
77         private TextView mElevationView;
78         private TextView mBearingView;
79         private TextView mLatitudeView;
80         private TextView mLongitudeView;
81
82         // Generic field for extras at the bottom
83         private TextView mTextView;
84         private TextView mVersion;
85
86         // Service
87         private boolean mIsBound   = false;
88         private Messenger mService = null;
89         final Messenger mMessenger = new Messenger(new IncomingHandler(this));
90
91         // Preferences
92         private AltosDroidPreferences prefs = null;
93
94         // TeleBT Config data
95         private AltosConfigData mConfigData = null;
96         // Local Bluetooth adapter
97         private BluetoothAdapter mBluetoothAdapter = null;
98
99         // Text to Speech
100         private AltosVoice mAltosVoice = null;
101
102         // The Handler that gets information back from the Telemetry Service
103         static class IncomingHandler extends Handler {
104                 private final WeakReference<AltosDroid> mAltosDroid;
105                 IncomingHandler(AltosDroid ad) { mAltosDroid = new WeakReference<AltosDroid>(ad); }
106
107                 @Override
108                 public void handleMessage(Message msg) {
109                         AltosDroid ad = mAltosDroid.get();
110                         switch (msg.what) {
111                         case MSG_STATE_CHANGE:
112                                 if(D) Log.d(TAG, "MSG_STATE_CHANGE: " + msg.arg1);
113                                 switch (msg.arg1) {
114                                 case TelemetryService.STATE_CONNECTED:
115                                         ad.mConfigData = (AltosConfigData) msg.obj;
116                                         String str = String.format(" %s S/N: %d", ad.mConfigData.product, ad.mConfigData.serial);
117                                         ad.mTitle.setText(R.string.title_connected_to);
118                                         ad.mTitle.append(str);
119                                         Toast.makeText(ad.getApplicationContext(), "Connected to " + str, Toast.LENGTH_SHORT).show();
120                                         ad.mAltosVoice.speak("Connected");
121                                         //TEST!
122                                         //ad.mTextView.setText(Dumper.dump(ad.mConfigData));
123                                         break;
124                                 case TelemetryService.STATE_CONNECTING:
125                                         ad.mTitle.setText(R.string.title_connecting);
126                                         break;
127                                 case TelemetryService.STATE_READY:
128                                 case TelemetryService.STATE_NONE:
129                                         ad.mConfigData = null;
130                                         ad.mTitle.setText(R.string.title_not_connected);
131                                         ad.mTextView.setText("");
132                                         break;
133                                 }
134                                 break;
135                         case MSG_TELEMETRY:
136                                 ad.update_ui((AltosState) msg.obj);
137                                 // TEST!
138                                 //ad.mTextView.setText(Dumper.dump(msg.obj));
139                                 break;
140                         }
141                 }
142         };
143
144
145         private ServiceConnection mConnection = new ServiceConnection() {
146                 public void onServiceConnected(ComponentName className, IBinder service) {
147                         mService = new Messenger(service);
148                         try {
149                                 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
150                                 msg.replyTo = mMessenger;
151                                 mService.send(msg);
152                         } catch (RemoteException e) {
153                                 // In this case the service has crashed before we could even do anything with it
154                         }
155                 }
156
157                 public void onServiceDisconnected(ComponentName className) {
158                         // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
159                         mService = null;
160                 }
161         };
162
163
164         void doBindService() {
165                 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
166                 mIsBound = true;
167         }
168
169         void doUnbindService() {
170                 if (mIsBound) {
171                         // If we have received the service, and hence registered with it, then now is the time to unregister.
172                         if (mService != null) {
173                                 try {
174                                         Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
175                                         msg.replyTo = mMessenger;
176                                         mService.send(msg);
177                                 } catch (RemoteException e) {
178                                         // There is nothing special we need to do if the service has crashed.
179                                 }
180                         }
181                         // Detach our existing connection.
182                         unbindService(mConnection);
183                         mIsBound = false;
184                 }
185         }
186
187         void update_ui(AltosState state) {
188                 mCallsignView.setText(state.data.callsign);
189                 mRSSIView.setText(String.format("%d", state.data.rssi));
190                 mSerialView.setText(String.format("%d", state.data.serial));
191                 mFlightView.setText(String.format("%d", state.data.flight));
192                 mStateView.setText(state.data.state());
193                 mSpeedView.setText(String.format("%6.0f m/s", state.speed()));
194                 mAccelView.setText(String.format("%6.0f m/s²", state.acceleration));
195                 mRangeView.setText(String.format("%6.0f m", state.range));
196                 mHeightView.setText(String.format("%6.0f m", state.height));
197                 mElevationView.setText(String.format("%3.0f°", state.elevation));
198                 if (state.from_pad != null)
199                         mBearingView.setText(String.format("%3.0f°", state.from_pad.bearing));
200                 mLatitudeView.setText(pos(state.gps.lat, "N", "S"));
201                 mLongitudeView.setText(pos(state.gps.lon, "W", "E"));
202
203                 mAltosVoice.tell(state);
204         }
205
206         String pos(double p, String pos, String neg) {
207                 String  h = pos;
208                 if (p < 0) {
209                         h = neg;
210                         p = -p;
211                 }
212                 int deg = (int) Math.floor(p);
213                 double min = (p - Math.floor(p)) * 60.0;
214                 return String.format("%d° %9.6f\" %s", deg, min, h);
215         }
216
217         @Override
218         public void onCreate(Bundle savedInstanceState) {
219                 super.onCreate(savedInstanceState);
220                 if(D) Log.e(TAG, "+++ ON CREATE +++");
221
222                 // Get local Bluetooth adapter
223                 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
224
225                 // If the adapter is null, then Bluetooth is not supported
226                 if (mBluetoothAdapter == null) {
227                         Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
228                         finish();
229                         return;
230                 }
231
232                 // Initialise preferences
233                 prefs = new AltosDroidPreferences(this);
234                 AltosPreferences.init(prefs);
235
236                 // Set up the window layout
237                 requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
238                 //setContentView(R.layout.main);
239                 setContentView(R.layout.altosdroid);
240                 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
241
242                 // Set up the custom title
243                 mTitle = (TextView) findViewById(R.id.title_left_text);
244                 mTitle.setText(R.string.app_name);
245                 mTitle = (TextView) findViewById(R.id.title_right_text);
246
247                 // Set up the temporary Text View
248                 mTextView = (TextView) findViewById(R.id.text);
249                 mTextView.setMovementMethod(new ScrollingMovementMethod());
250                 mTextView.setClickable(false);
251                 mTextView.setLongClickable(false);
252
253                 mVersion = (TextView) findViewById(R.id.version);
254                 mVersion.setText("Version: " + BuildInfo.version +
255                                  "  Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
256                                  "  (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
257
258                 mCallsignView  = (TextView) findViewById(R.id.callsign_value);
259                 mRSSIView      = (TextView) findViewById(R.id.rssi_value);
260                 mSerialView    = (TextView) findViewById(R.id.serial_value);
261                 mFlightView    = (TextView) findViewById(R.id.flight_value);
262                 mStateView     = (TextView) findViewById(R.id.state_value);
263                 mSpeedView     = (TextView) findViewById(R.id.speed_value);
264                 mAccelView     = (TextView) findViewById(R.id.accel_value);
265                 mRangeView     = (TextView) findViewById(R.id.range_value);
266                 mHeightView    = (TextView) findViewById(R.id.height_value);
267                 mElevationView = (TextView) findViewById(R.id.elevation_value);
268                 mBearingView   = (TextView) findViewById(R.id.bearing_value);
269                 mLatitudeView  = (TextView) findViewById(R.id.latitude_value);
270                 mLongitudeView = (TextView) findViewById(R.id.longitude_value);
271
272                 mAltosVoice = new AltosVoice(this);
273         }
274
275         @Override
276         public void onStart() {
277                 super.onStart();
278                 if(D) Log.e(TAG, "++ ON START ++");
279
280                 if (!mBluetoothAdapter.isEnabled()) {
281                         Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
282                         startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
283                 }
284
285                 // Start Telemetry Service
286                 startService(new Intent(AltosDroid.this, TelemetryService.class));
287
288                 doBindService();
289         }
290
291         @Override
292         public synchronized void onResume() {
293                 super.onResume();
294                 if(D) Log.e(TAG, "+ ON RESUME +");
295         }
296
297         @Override
298         public synchronized void onPause() {
299                 super.onPause();
300                 if(D) Log.e(TAG, "- ON PAUSE -");
301         }
302
303         @Override
304         public void onStop() {
305                 super.onStop();
306                 if(D) Log.e(TAG, "-- ON STOP --");
307
308                 doUnbindService();
309         }
310
311         @Override
312         public void onDestroy() {
313                 super.onDestroy();
314                 if(D) Log.e(TAG, "--- ON DESTROY ---");
315
316                 mAltosVoice.stop();
317         }
318
319
320
321
322         public void onActivityResult(int requestCode, int resultCode, Intent data) {
323                 if(D) Log.d(TAG, "onActivityResult " + resultCode);
324                 switch (requestCode) {
325                 case REQUEST_CONNECT_DEVICE:
326                         // When DeviceListActivity returns with a device to connect to
327                         if (resultCode == Activity.RESULT_OK) {
328                                 connectDevice(data);
329                         }
330                         break;
331                 case REQUEST_ENABLE_BT:
332                         // When the request to enable Bluetooth returns
333                         if (resultCode == Activity.RESULT_OK) {
334                                 // Bluetooth is now enabled, so set up a chat session
335                                 //setupChat();
336                         } else {
337                                 // User did not enable Bluetooth or an error occured
338                                 Log.e(TAG, "BT not enabled");
339                                 stopService(new Intent(AltosDroid.this, TelemetryService.class));
340                                 Toast.makeText(this, R.string.bt_not_enabled, Toast.LENGTH_SHORT).show();
341                                 finish();
342                         }
343                         break;
344                 }
345         }
346
347         private void connectDevice(Intent data) {
348                 // Get the device MAC address
349                 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
350                 // Get the BLuetoothDevice object
351                 BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
352                 // Attempt to connect to the device
353                 try {
354                         if (D) Log.d(TAG, "Connecting to " + device.getName());
355                         mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, device));
356                 } catch (RemoteException e) {
357                 }
358         }
359
360         @Override
361         public boolean onCreateOptionsMenu(Menu menu) {
362                 MenuInflater inflater = getMenuInflater();
363                 inflater.inflate(R.menu.option_menu, menu);
364                 return true;
365         }
366
367         void setFrequency(double freq) {
368                 try {
369                         mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
370                 } catch (RemoteException e) {
371                 }
372         }
373
374         void setFrequency(String freq) {
375                 try {
376                         setFrequency (Double.parseDouble(freq.substring(11, 17)));
377                 } catch (NumberFormatException e) {
378                 }
379         }
380
381         @Override
382         public boolean onOptionsItemSelected(MenuItem item) {
383                 Intent serverIntent = null;
384                 switch (item.getItemId()) {
385                 case R.id.connect_scan:
386                         // Launch the DeviceListActivity to see devices and do scan
387                         serverIntent = new Intent(this, DeviceListActivity.class);
388                         startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
389                         return true;
390                 case R.id.select_freq:
391                         // Set the TBT radio frequency
392
393                         final String[] frequencies = {
394                                 "Channel 0 (434.550MHz)",
395                                 "Channel 1 (434.650MHz)",
396                                 "Channel 2 (434.750MHz)",
397                                 "Channel 3 (434.850MHz)",
398                                 "Channel 4 (434.950MHz)",
399                                 "Channel 5 (435.050MHz)",
400                                 "Channel 6 (435.150MHz)",
401                                 "Channel 7 (435.250MHz)",
402                                 "Channel 8 (435.350MHz)",
403                                 "Channel 9 (435.450MHz)"
404                         };
405
406                         AlertDialog.Builder builder = new AlertDialog.Builder(this);
407                         builder.setTitle("Pick a frequency");
408                         builder.setItems(frequencies,
409                                          new DialogInterface.OnClickListener() {
410                                                  public void onClick(DialogInterface dialog, int item) {
411                                                          setFrequency(frequencies[item]);
412                                                  }
413                                          });
414                         AlertDialog alert = builder.create();
415                         alert.show();
416                         return true;
417                 }
418                 return false;
419         }
420
421 }