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