altosdroid: remove complexity around message passing
[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 import android.app.Activity;
22 import android.bluetooth.BluetoothAdapter;
23 import android.bluetooth.BluetoothDevice;
24 import android.content.Intent;
25 import android.content.Context;
26 import android.content.ComponentName;
27 import android.content.ServiceConnection;
28 import android.os.IBinder;
29 import android.os.Bundle;
30 import android.os.Handler;
31 import android.os.Message;
32 import android.os.Messenger;
33 import android.os.RemoteException;
34 import android.speech.tts.TextToSpeech;
35 import android.speech.tts.TextToSpeech.OnInitListener;
36 import android.text.method.ScrollingMovementMethod;
37 import android.util.Log;
38 //import android.view.KeyEvent;
39 import android.view.Menu;
40 import android.view.MenuInflater;
41 import android.view.MenuItem;
42 //import android.view.View;
43 import android.view.Window;
44 //import android.view.View.OnClickListener;
45 //import android.view.inputmethod.EditorInfo;
46 //import android.widget.Button;
47 //import android.widget.EditText;
48 import android.widget.TextView;
49 import android.widget.Toast;
50 import org.altusmetrum.AltosDroid.R;
51
52 /**
53  * This is the main Activity that displays the current chat session.
54  */
55 public class AltosDroid extends Activity {
56         // Debugging
57         private static final String TAG = "AltosDroid";
58         private static final boolean D = true;
59
60         // Message types sent from the TelemetryService Handler
61         public static final int MSG_STATE_CHANGE    = 1;
62         public static final int MSG_DEVNAME         = 2;
63         public static final int MSG_INCOMING_TELEM  = 3;
64         public static final int MSG_TOAST           = 4;
65
66         // Key names received from the TelemetryService Handler
67         public static final String KEY_DEVNAME = "key_devname";
68         public static final String KEY_TOAST   = "key_toast";
69
70         // Intent request codes
71         private static final int REQUEST_CONNECT_DEVICE = 1;
72         private static final int REQUEST_ENABLE_BT      = 2;
73
74         // Layout Views
75         private TextView mTitle;
76         private TextView mSerialView;
77         //private EditText mOutEditText;
78         //private Button mSendButton;
79
80         private boolean mIsBound;
81         Messenger mService = null;
82         final Messenger mMessenger = new Messenger(new IncomingHandler(this));
83
84         // Name of the connected device
85         private String mConnectedDeviceName = null;
86         // Local Bluetooth adapter
87         private BluetoothAdapter mBluetoothAdapter = null;
88
89         private TextToSpeech tts;
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.i(TAG, "MSG_STATE_CHANGE: " + msg.arg1);
103                                 switch (msg.arg1) {
104                                 case TelemetryService.STATE_CONNECTED:
105                                         ad.mTitle.setText(R.string.title_connected_to);
106                                         ad.mTitle.append(ad.mConnectedDeviceName);
107                                         ad.mSerialView.setText("");
108                                         break;
109                                 case TelemetryService.STATE_CONNECTING:
110                                         ad.mTitle.setText(R.string.title_connecting);
111                                         break;
112                                 case TelemetryService.STATE_READY:
113                                 case TelemetryService.STATE_NONE:
114                                         ad.mTitle.setText(R.string.title_not_connected);
115                                         break;
116                                 }
117                                 break;
118                         case MSG_INCOMING_TELEM:
119                                 byte[] buf = (byte[]) msg.obj;
120                                 // construct a string from the buffer
121                                 String telem = new String(buf);
122                                 ad.mSerialView.append(telem);
123                                 break;
124                         case MSG_DEVNAME:
125                                 // save the connected device's name
126                                 ad.mConnectedDeviceName = (String) msg.obj;
127                                 if (ad.mConnectedDeviceName != null)
128                                         Toast.makeText(ad.getApplicationContext(), "Connected to "
129                                                         + ad.mConnectedDeviceName, Toast.LENGTH_SHORT).show();
130                                 break;
131                         case MSG_TOAST:
132                                 Toast.makeText(
133                                                 ad.getApplicationContext(),
134                                                 msg.getData().getString(KEY_TOAST),
135                                                 Toast.LENGTH_SHORT).show();
136                                 break;
137                         }
138                 }
139         };
140
141
142         private ServiceConnection mConnection = new ServiceConnection() {
143                 public void onServiceConnected(ComponentName className, IBinder service) {
144                         mService = new Messenger(service);
145                         try {
146                                 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
147                                 msg.replyTo = mMessenger;
148                                 mService.send(msg);
149                         } catch (RemoteException e) {
150                                 // In this case the service has crashed before we could even do anything with it
151                         }
152                 }
153
154                 public void onServiceDisconnected(ComponentName className) {
155                         // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
156                         mService = null;
157                 }
158         };
159
160
161         @Override
162         public void onCreate(Bundle savedInstanceState) {
163                 super.onCreate(savedInstanceState);
164                 if(D) Log.e(TAG, "+++ ON CREATE +++");
165
166                 // Set up the window layout
167                 requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
168                 setContentView(R.layout.main);
169                 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
170
171                 // Set up the custom title
172                 mTitle = (TextView) findViewById(R.id.title_left_text);
173                 mTitle.setText(R.string.app_name);
174                 mTitle = (TextView) findViewById(R.id.title_right_text);
175
176                 mSerialView = (TextView) findViewById(R.id.in);
177                 mSerialView.setMovementMethod(new ScrollingMovementMethod());
178                 mSerialView.setClickable(false);
179                 mSerialView.setLongClickable(false);
180
181                 // Get local Bluetooth adapter
182                 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
183
184                 // If the adapter is null, then Bluetooth is not supported
185                 if (mBluetoothAdapter == null) {
186                         Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
187                         finish();
188                         return;
189                 }
190
191                 // Enable Text to Speech
192                 tts = new TextToSpeech(this, new OnInitListener() {
193                         public void onInit(int status) {
194                                 if (status == TextToSpeech.SUCCESS) tts_enabled = true;
195                                 if (tts_enabled) tts.speak("AltosDroid ready", TextToSpeech.QUEUE_ADD, null );
196                         }
197                 });
198
199                 // Start Telemetry Service
200                 startService(new Intent(AltosDroid.this, TelemetryService.class));
201
202                 doBindService();
203         }
204
205         @Override
206         public void onStart() {
207                 super.onStart();
208                 if(D) Log.e(TAG, "++ ON START ++");
209
210                 if (!mBluetoothAdapter.isEnabled()) {
211                         Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
212                         startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
213                 } else {
214                         //if (mChatService == null) setupChat();
215                 }
216         }
217
218         @Override
219         public synchronized void onResume() {
220                 super.onResume();
221                 if(D) Log.e(TAG, "+ ON RESUME +");
222
223                 // Performing this check in onResume() covers the case in which BT was
224                 // not enabled during onStart(), so we were paused to enable it...
225                 // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
226                 //if (mChatService != null) {
227                         // Only if the state is STATE_NONE, do we know that we haven't started already
228                         //if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
229                         // Start the Bluetooth chat services
230                         //mChatService.start();
231                         //}
232                 //}
233         }
234
235         @Override
236         public synchronized void onPause() {
237                 super.onPause();
238                 if(D) Log.e(TAG, "- ON PAUSE -");
239         }
240
241         @Override
242         public void onStop() {
243                 super.onStop();
244                 if(D) Log.e(TAG, "-- ON STOP --");
245         }
246
247         @Override
248         public void onDestroy() {
249                 super.onDestroy();
250
251                 doUnbindService();
252
253                 if (tts != null) tts.shutdown();
254
255                 if(D) Log.e(TAG, "--- ON DESTROY ---");
256         }
257
258
259
260 /*
261         private void setupChat() {
262                 Log.d(TAG, "setupChat()");
263
264                 // Initialize the compose field with a listener for the return key
265                 mOutEditText = (EditText) findViewById(R.id.edit_text_out);
266                 mOutEditText.setOnEditorActionListener(mWriteListener);
267
268                 // Initialize the send button with a listener that for click events
269                 mSendButton = (Button) findViewById(R.id.button_send);
270                 mSendButton.setOnClickListener(new OnClickListener() {
271                         public void onClick(View v) {
272                                 // Send a message using content of the edit text widget
273                                 TextView view = (TextView) findViewById(R.id.edit_text_out);
274                                 String message = view.getText().toString();
275                                 sendMessage(message);
276                         }
277                 });
278
279                 // Initialize the BluetoothChatService to perform bluetooth connections
280                 mChatService = new BluetoothChatService(this, mHandler);
281
282                 // Initialize the buffer for outgoing messages
283                 mOutStringBuffer = new StringBuffer("");
284         }
285 */
286
287         /**
288          * Sends a message.
289          * @param message  A string of text to send.
290          */
291         /*
292         private void sendMessage(String message) {
293                 // Check that we're actually connected before trying anything
294                 if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
295                         Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
296                         return;
297                 }
298
299                 // Check that there's actually something to send
300                 if (message.length() > 0) {
301                         // Get the message bytes and tell the BluetoothChatService to write
302                         byte[] send = message.getBytes();
303                         mChatService.write(send);
304
305                         // Reset out string buffer to zero and clear the edit text field
306                         mOutStringBuffer.setLength(0);
307                         mOutEditText.setText(mOutStringBuffer);
308                 }
309         }
310
311
312         // The action listener for the EditText widget, to listen for the return key
313         private TextView.OnEditorActionListener mWriteListener =
314                 new TextView.OnEditorActionListener() {
315                 public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
316                         // If the action is a key-up event on the return key, send the message
317                         if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
318                                 String message = view.getText().toString();
319                                 sendMessage(message);
320                         }
321                         if(D) Log.i(TAG, "END onEditorAction");
322                         return true;
323                 }
324         };
325         */
326
327         public void onActivityResult(int requestCode, int resultCode, Intent data) {
328                 if(D) Log.d(TAG, "onActivityResult " + resultCode);
329                 switch (requestCode) {
330                 case REQUEST_CONNECT_DEVICE:
331                         // When DeviceListActivity returns with a device to connect to
332                         if (resultCode == Activity.RESULT_OK) {
333                                 connectDevice(data);
334                         }
335                         break;
336                 case REQUEST_ENABLE_BT:
337                         // When the request to enable Bluetooth returns
338                         if (resultCode == Activity.RESULT_OK) {
339                                 // Bluetooth is now enabled, so set up a chat session
340                                 //setupChat();
341                         } else {
342                                 // User did not enable Bluetooth or an error occured
343                                 Log.d(TAG, "BT not enabled");
344                                 stopService(new Intent(AltosDroid.this, TelemetryService.class));
345                                 Toast.makeText(this, R.string.bt_not_enabled, Toast.LENGTH_SHORT).show();
346                                 finish();
347                         }
348                         break;
349                 }
350         }
351
352         private void connectDevice(Intent data) {
353                 // Get the device MAC address
354                 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
355                 // Get the BLuetoothDevice object
356                 BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
357                 // Attempt to connect to the device
358                 try {
359                         //Message msg = Message.obtain(null, TelemetryService.MSG_CONNECT_TELEBT);
360                         //msg.obj = device;
361                         //mService.send(msg);
362                         if (D) Log.i(TAG, "Connecting to " + device.getName());
363                         mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, device));
364                 } catch (RemoteException e) {
365                         e.printStackTrace();
366                 }
367         }
368
369         @Override
370         public boolean onCreateOptionsMenu(Menu menu) {
371                 MenuInflater inflater = getMenuInflater();
372                 inflater.inflate(R.menu.option_menu, menu);
373                 return true;
374         }
375
376         @Override
377         public boolean onOptionsItemSelected(MenuItem item) {
378                 Intent serverIntent = null;
379                 switch (item.getItemId()) {
380                 case R.id.connect_scan:
381                         // Launch the DeviceListActivity to see devices and do scan
382                         serverIntent = new Intent(this, DeviceListActivity.class);
383                         startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
384                         return true;
385                 }
386                 return false;
387         }
388
389
390         void doBindService() {
391                 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
392                 mIsBound = true;
393         }
394
395         void doUnbindService() {
396                 if (mIsBound) {
397                         // If we have received the service, and hence registered with it, then now is the time to unregister.
398                         if (mService != null) {
399                                 try {
400                                         Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
401                                         msg.replyTo = mMessenger;
402                                         mService.send(msg);
403                                 } catch (RemoteException e) {
404                                         // There is nothing special we need to do if the service has crashed.
405                                 }
406                         }
407                         // Detach our existing connection.
408                         unbindService(mConnection);
409                         mIsBound = false;
410                 }
411         }
412
413 }