altosdroid: tidy up old messages
[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
22 import android.app.Activity;
23 import android.bluetooth.BluetoothAdapter;
24 import android.bluetooth.BluetoothDevice;
25 import android.content.Intent;
26 import android.content.Context;
27 import android.content.ComponentName;
28 import android.content.ServiceConnection;
29 import android.os.IBinder;
30 import android.os.Bundle;
31 import android.os.Handler;
32 import android.os.Message;
33 import android.os.Messenger;
34 import android.os.RemoteException;
35 import android.speech.tts.TextToSpeech;
36 import android.speech.tts.TextToSpeech.OnInitListener;
37 import android.text.method.ScrollingMovementMethod;
38 import android.util.Log;
39 import android.view.Menu;
40 import android.view.MenuInflater;
41 import android.view.MenuItem;
42 import android.view.Window;
43 import android.widget.TextView;
44 import android.widget.Toast;
45
46 import org.altusmetrum.AltosLib.*;
47
48 /**
49  * This is the main Activity that displays the current chat session.
50  */
51 public class AltosDroid extends Activity {
52         // Debugging
53         private static final String TAG = "AltosDroid";
54         private static final boolean D = true;
55
56         // Message types received by our Handler
57         public static final int MSG_STATE_CHANGE    = 1;
58         public static final int MSG_TELEMETRY       = 2;
59
60         // Intent request codes
61         private static final int REQUEST_CONNECT_DEVICE = 1;
62         private static final int REQUEST_ENABLE_BT      = 2;
63
64         // Layout Views
65         private TextView mTitle;
66         private TextView mSerialView;
67
68         // Service
69         private boolean mIsBound   = false;
70         private Messenger mService = null;
71         final Messenger mMessenger = new Messenger(new IncomingHandler(this));
72
73         // TeleBT Config data
74         private AltosConfigData mConfigData = null;
75         // Local Bluetooth adapter
76         private BluetoothAdapter mBluetoothAdapter = null;
77
78         // Text to Speech
79         private TextToSpeech tts    = null;
80         private boolean tts_enabled = false;
81
82         // The Handler that gets information back from the Telemetry Service
83         static class IncomingHandler extends Handler {
84                 private final WeakReference<AltosDroid> mAltosDroid;
85                 IncomingHandler(AltosDroid ad) { mAltosDroid = new WeakReference<AltosDroid>(ad); }
86
87                 @Override
88                 public void handleMessage(Message msg) {
89                         AltosDroid ad = mAltosDroid.get();
90                         switch (msg.what) {
91                         case MSG_STATE_CHANGE:
92                                 if(D) Log.d(TAG, "MSG_STATE_CHANGE: " + msg.arg1);
93                                 switch (msg.arg1) {
94                                 case TelemetryService.STATE_CONNECTED:
95                                         ad.mConfigData = (AltosConfigData) msg.obj;
96                                         String str = String.format(" %s S/N: %d", ad.mConfigData.product, ad.mConfigData.serial);
97                                         ad.mTitle.setText(R.string.title_connected_to);
98                                         ad.mTitle.append(str);
99                                         Toast.makeText(ad.getApplicationContext(), "Connected to " + str, Toast.LENGTH_SHORT).show();
100                                         break;
101                                 case TelemetryService.STATE_CONNECTING:
102                                         ad.mTitle.setText(R.string.title_connecting);
103                                         break;
104                                 case TelemetryService.STATE_READY:
105                                 case TelemetryService.STATE_NONE:
106                                         ad.mConfigData = null;
107                                         ad.mTitle.setText(R.string.title_not_connected);
108                                         ad.mSerialView.setText("");
109                                         break;
110                                 }
111                                 break;
112                         case MSG_TELEMETRY:
113                                 //byte[] buf = (byte[]) msg.obj;
114                                 // construct a string from the buffer
115                                 //String telem = new String(buf);
116                                 //ad.mSerialView.append(telem);
117                                 break;
118                         }
119                 }
120         };
121
122
123         private ServiceConnection mConnection = new ServiceConnection() {
124                 public void onServiceConnected(ComponentName className, IBinder service) {
125                         mService = new Messenger(service);
126                         try {
127                                 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
128                                 msg.replyTo = mMessenger;
129                                 mService.send(msg);
130                         } catch (RemoteException e) {
131                                 // In this case the service has crashed before we could even do anything with it
132                         }
133                 }
134
135                 public void onServiceDisconnected(ComponentName className) {
136                         // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
137                         mService = null;
138                 }
139         };
140
141
142         @Override
143         public void onCreate(Bundle savedInstanceState) {
144                 super.onCreate(savedInstanceState);
145                 if(D) Log.e(TAG, "+++ ON CREATE +++");
146
147                 // Set up the window layout
148                 requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
149                 setContentView(R.layout.main);
150                 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
151
152                 // Set up the custom title
153                 mTitle = (TextView) findViewById(R.id.title_left_text);
154                 mTitle.setText(R.string.app_name);
155                 mTitle = (TextView) findViewById(R.id.title_right_text);
156
157                 // Set up the temporary Text View
158                 mSerialView = (TextView) findViewById(R.id.in);
159                 mSerialView.setMovementMethod(new ScrollingMovementMethod());
160                 mSerialView.setClickable(false);
161                 mSerialView.setLongClickable(false);
162
163                 // Get local Bluetooth adapter
164                 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
165
166                 // If the adapter is null, then Bluetooth is not supported
167                 if (mBluetoothAdapter == null) {
168                         Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
169                         finish();
170                         return;
171                 }
172
173                 // Enable Text to Speech
174                 tts = new TextToSpeech(this, new OnInitListener() {
175                         public void onInit(int status) {
176                                 if (status == TextToSpeech.SUCCESS) tts_enabled = true;
177                                 if (tts_enabled) tts.speak("AltosDroid ready", TextToSpeech.QUEUE_ADD, null );
178                         }
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                 }
196         }
197
198         @Override
199         public synchronized void onResume() {
200                 super.onResume();
201                 if(D) Log.e(TAG, "+ ON RESUME +");
202
203         }
204
205         @Override
206         public synchronized void onPause() {
207                 super.onPause();
208                 if(D) Log.e(TAG, "- ON PAUSE -");
209         }
210
211         @Override
212         public void onStop() {
213                 super.onStop();
214                 if(D) Log.e(TAG, "-- ON STOP --");
215         }
216
217         @Override
218         public void onDestroy() {
219                 super.onDestroy();
220
221                 doUnbindService();
222
223                 if (tts != null) tts.shutdown();
224
225                 if(D) Log.e(TAG, "--- ON DESTROY ---");
226         }
227
228
229
230
231         public void onActivityResult(int requestCode, int resultCode, Intent data) {
232                 if(D) Log.d(TAG, "onActivityResult " + resultCode);
233                 switch (requestCode) {
234                 case REQUEST_CONNECT_DEVICE:
235                         // When DeviceListActivity returns with a device to connect to
236                         if (resultCode == Activity.RESULT_OK) {
237                                 connectDevice(data);
238                         }
239                         break;
240                 case REQUEST_ENABLE_BT:
241                         // When the request to enable Bluetooth returns
242                         if (resultCode == Activity.RESULT_OK) {
243                                 // Bluetooth is now enabled, so set up a chat session
244                                 //setupChat();
245                         } else {
246                                 // User did not enable Bluetooth or an error occured
247                                 Log.e(TAG, "BT not enabled");
248                                 stopService(new Intent(AltosDroid.this, TelemetryService.class));
249                                 Toast.makeText(this, R.string.bt_not_enabled, Toast.LENGTH_SHORT).show();
250                                 finish();
251                         }
252                         break;
253                 }
254         }
255
256         private void connectDevice(Intent data) {
257                 // Get the device MAC address
258                 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
259                 // Get the BLuetoothDevice object
260                 BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
261                 // Attempt to connect to the device
262                 try {
263                         if (D) Log.d(TAG, "Connecting to " + device.getName());
264                         mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, device));
265                 } catch (RemoteException e) {
266                 }
267         }
268
269         @Override
270         public boolean onCreateOptionsMenu(Menu menu) {
271                 MenuInflater inflater = getMenuInflater();
272                 inflater.inflate(R.menu.option_menu, menu);
273                 return true;
274         }
275
276         @Override
277         public boolean onOptionsItemSelected(MenuItem item) {
278                 Intent serverIntent = null;
279                 switch (item.getItemId()) {
280                 case R.id.connect_scan:
281                         // Launch the DeviceListActivity to see devices and do scan
282                         serverIntent = new Intent(this, DeviceListActivity.class);
283                         startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
284                         return true;
285                 }
286                 return false;
287         }
288
289
290         void doBindService() {
291                 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
292                 mIsBound = true;
293         }
294
295         void doUnbindService() {
296                 if (mIsBound) {
297                         // If we have received the service, and hence registered with it, then now is the time to unregister.
298                         if (mService != null) {
299                                 try {
300                                         Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
301                                         msg.replyTo = mMessenger;
302                                         mService.send(msg);
303                                 } catch (RemoteException e) {
304                                         // There is nothing special we need to do if the service has crashed.
305                                 }
306                         }
307                         // Detach our existing connection.
308                         unbindService(mConnection);
309                         mIsBound = false;
310                 }
311         }
312
313 }