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