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