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