bbb2970f44d0aa676e8cbb6120fda68274a71dfc
[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 /**
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_DEVNAME         = 2;
57         public static final int MSG_TOAST           = 3;
58         public static final int MSG_DEVCONFIG       = 4;
59         public static final int MSG_TELEMETRY       = 5;
60
61         // Intent request codes
62         private static final int REQUEST_CONNECT_DEVICE = 1;
63         private static final int REQUEST_ENABLE_BT      = 2;
64
65         // Layout Views
66         private TextView mTitle;
67         private TextView mSerialView;
68
69         // Service
70         private boolean mIsBound   = false;
71         private Messenger mService = null;
72         final Messenger mMessenger = new Messenger(new IncomingHandler(this));
73
74         // Name of the connected device
75         private String mConnectedDeviceName = null;
76         // Local Bluetooth adapter
77         private BluetoothAdapter mBluetoothAdapter = null;
78
79         // Text to Speech
80         private TextToSpeech tts    = null;
81         private boolean tts_enabled = false;
82
83         // The Handler that gets information back from the Telemetry Service
84         static class IncomingHandler extends Handler {
85                 private final WeakReference<AltosDroid> mAltosDroid;
86                 IncomingHandler(AltosDroid ad) { mAltosDroid = new WeakReference<AltosDroid>(ad); }
87
88                 @Override
89                 public void handleMessage(Message msg) {
90                         AltosDroid ad = mAltosDroid.get();
91                         switch (msg.what) {
92                         case MSG_STATE_CHANGE:
93                                 if(D) Log.d(TAG, "MSG_STATE_CHANGE: " + msg.arg1);
94                                 switch (msg.arg1) {
95                                 case TelemetryService.STATE_CONNECTED:
96                                         ad.mTitle.setText(R.string.title_connected_to);
97                                         ad.mTitle.append(ad.mConnectedDeviceName);
98                                         ad.mSerialView.setText("");
99                                         break;
100                                 case TelemetryService.STATE_CONNECTING:
101                                         ad.mTitle.setText(R.string.title_connecting);
102                                         break;
103                                 case TelemetryService.STATE_READY:
104                                 case TelemetryService.STATE_NONE:
105                                         ad.mTitle.setText(R.string.title_not_connected);
106                                         break;
107                                 }
108                                 break;
109                         case MSG_DEVCONFIG:
110                         case MSG_TELEMETRY:
111                                 //byte[] buf = (byte[]) msg.obj;
112                                 // construct a string from the buffer
113                                 //String telem = new String(buf);
114                                 //ad.mSerialView.append(telem);
115                                 break;
116                         case MSG_DEVNAME:
117                                 // save the connected device's name
118                                 ad.mConnectedDeviceName = (String) msg.obj;
119                                 if (ad.mConnectedDeviceName != null)
120                                         Toast.makeText(ad.getApplicationContext(), "Connected to "
121                                                         + ad.mConnectedDeviceName, Toast.LENGTH_SHORT).show();
122                                 break;
123                         case MSG_TOAST:
124                                 Toast.makeText(
125                                                 ad.getApplicationContext(),
126                                                 (String) msg.obj,
127                                                 Toast.LENGTH_SHORT).show();
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         @Override
154         public void onCreate(Bundle savedInstanceState) {
155                 super.onCreate(savedInstanceState);
156                 if(D) Log.e(TAG, "+++ ON CREATE +++");
157
158                 // Set up the window layout
159                 requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
160                 setContentView(R.layout.main);
161                 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
162
163                 // Set up the custom title
164                 mTitle = (TextView) findViewById(R.id.title_left_text);
165                 mTitle.setText(R.string.app_name);
166                 mTitle = (TextView) findViewById(R.id.title_right_text);
167
168                 // Set up the temporary Text View
169                 mSerialView = (TextView) findViewById(R.id.in);
170                 mSerialView.setMovementMethod(new ScrollingMovementMethod());
171                 mSerialView.setClickable(false);
172                 mSerialView.setLongClickable(false);
173
174                 // Get local Bluetooth adapter
175                 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
176
177                 // If the adapter is null, then Bluetooth is not supported
178                 if (mBluetoothAdapter == null) {
179                         Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
180                         finish();
181                         return;
182                 }
183
184                 // Enable Text to Speech
185                 tts = new TextToSpeech(this, new OnInitListener() {
186                         public void onInit(int status) {
187                                 if (status == TextToSpeech.SUCCESS) tts_enabled = true;
188                                 if (tts_enabled) tts.speak("AltosDroid ready", TextToSpeech.QUEUE_ADD, null );
189                         }
190                 });
191
192                 // Start Telemetry Service
193                 startService(new Intent(AltosDroid.this, TelemetryService.class));
194
195                 doBindService();
196         }
197
198         @Override
199         public void onStart() {
200                 super.onStart();
201                 if(D) Log.e(TAG, "++ ON START ++");
202
203                 if (!mBluetoothAdapter.isEnabled()) {
204                         Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
205                         startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
206                 }
207         }
208
209         @Override
210         public synchronized void onResume() {
211                 super.onResume();
212                 if(D) Log.e(TAG, "+ ON RESUME +");
213
214         }
215
216         @Override
217         public synchronized void onPause() {
218                 super.onPause();
219                 if(D) Log.e(TAG, "- ON PAUSE -");
220         }
221
222         @Override
223         public void onStop() {
224                 super.onStop();
225                 if(D) Log.e(TAG, "-- ON STOP --");
226         }
227
228         @Override
229         public void onDestroy() {
230                 super.onDestroy();
231
232                 doUnbindService();
233
234                 if (tts != null) tts.shutdown();
235
236                 if(D) Log.e(TAG, "--- ON DESTROY ---");
237         }
238
239
240
241
242         public void onActivityResult(int requestCode, int resultCode, Intent data) {
243                 if(D) Log.d(TAG, "onActivityResult " + resultCode);
244                 switch (requestCode) {
245                 case REQUEST_CONNECT_DEVICE:
246                         // When DeviceListActivity returns with a device to connect to
247                         if (resultCode == Activity.RESULT_OK) {
248                                 connectDevice(data);
249                         }
250                         break;
251                 case REQUEST_ENABLE_BT:
252                         // When the request to enable Bluetooth returns
253                         if (resultCode == Activity.RESULT_OK) {
254                                 // Bluetooth is now enabled, so set up a chat session
255                                 //setupChat();
256                         } else {
257                                 // User did not enable Bluetooth or an error occured
258                                 Log.e(TAG, "BT not enabled");
259                                 stopService(new Intent(AltosDroid.this, TelemetryService.class));
260                                 Toast.makeText(this, R.string.bt_not_enabled, Toast.LENGTH_SHORT).show();
261                                 finish();
262                         }
263                         break;
264                 }
265         }
266
267         private void connectDevice(Intent data) {
268                 // Get the device MAC address
269                 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
270                 // Get the BLuetoothDevice object
271                 BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
272                 // Attempt to connect to the device
273                 try {
274                         if (D) Log.d(TAG, "Connecting to " + device.getName());
275                         mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, device));
276                 } catch (RemoteException e) {
277                 }
278         }
279
280         @Override
281         public boolean onCreateOptionsMenu(Menu menu) {
282                 MenuInflater inflater = getMenuInflater();
283                 inflater.inflate(R.menu.option_menu, menu);
284                 return true;
285         }
286
287         @Override
288         public boolean onOptionsItemSelected(MenuItem item) {
289                 Intent serverIntent = null;
290                 switch (item.getItemId()) {
291                 case R.id.connect_scan:
292                         // Launch the DeviceListActivity to see devices and do scan
293                         serverIntent = new Intent(this, DeviceListActivity.class);
294                         startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
295                         return true;
296                 }
297                 return false;
298         }
299
300
301         void doBindService() {
302                 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
303                 mIsBound = true;
304         }
305
306         void doUnbindService() {
307                 if (mIsBound) {
308                         // If we have received the service, and hence registered with it, then now is the time to unregister.
309                         if (mService != null) {
310                                 try {
311                                         Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
312                                         msg.replyTo = mMessenger;
313                                         mService.send(msg);
314                                 } catch (RemoteException e) {
315                                         // There is nothing special we need to do if the service has crashed.
316                                 }
317                         }
318                         // Detach our existing connection.
319                         unbindService(mConnection);
320                         mIsBound = false;
321                 }
322         }
323
324 }