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