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