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