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