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