altosdroid: stop sending device name, just send config data
[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_DEVNAME         = 2;
59         public static final int MSG_TOAST           = 3;
60         public static final int MSG_DEVCONFIG       = 4;
61         public static final int MSG_TELEMETRY       = 5;
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
71         // Service
72         private boolean mIsBound   = false;
73         private Messenger mService = null;
74         final Messenger mMessenger = new Messenger(new IncomingHandler(this));
75
76         // TeleBT Config data
77         private AltosConfigData mConfigData = null;
78         // Local Bluetooth adapter
79         private BluetoothAdapter mBluetoothAdapter = null;
80
81         // Text to Speech
82         private TextToSpeech tts    = null;
83         private boolean tts_enabled = false;
84
85         // The Handler that gets information back from the Telemetry Service
86         static class IncomingHandler extends Handler {
87                 private final WeakReference<AltosDroid> mAltosDroid;
88                 IncomingHandler(AltosDroid ad) { mAltosDroid = new WeakReference<AltosDroid>(ad); }
89
90                 @Override
91                 public void handleMessage(Message msg) {
92                         AltosDroid ad = mAltosDroid.get();
93                         switch (msg.what) {
94                         case MSG_STATE_CHANGE:
95                                 if(D) Log.d(TAG, "MSG_STATE_CHANGE: " + msg.arg1);
96                                 switch (msg.arg1) {
97                                 case TelemetryService.STATE_CONNECTED:
98                                         ad.mConfigData = (AltosConfigData) msg.obj;
99                                         String str = String.format(" %s S/N: %d", ad.mConfigData.product, ad.mConfigData.serial);
100                                         ad.mTitle.setText(R.string.title_connected_to);
101                                         ad.mTitle.append(str);
102                                         Toast.makeText(ad.getApplicationContext(), "Connected to " + str, Toast.LENGTH_SHORT).show();
103                                         break;
104                                 case TelemetryService.STATE_CONNECTING:
105                                         ad.mTitle.setText(R.string.title_connecting);
106                                         break;
107                                 case TelemetryService.STATE_READY:
108                                 case TelemetryService.STATE_NONE:
109                                         ad.mConfigData = null;
110                                         ad.mTitle.setText(R.string.title_not_connected);
111                                         ad.mSerialView.setText("");
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                 // Set up the temporary Text View
175                 mSerialView = (TextView) findViewById(R.id.in);
176                 mSerialView.setMovementMethod(new ScrollingMovementMethod());
177                 mSerialView.setClickable(false);
178                 mSerialView.setLongClickable(false);
179
180                 // Get local Bluetooth adapter
181                 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
182
183                 // If the adapter is null, then Bluetooth is not supported
184                 if (mBluetoothAdapter == null) {
185                         Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
186                         finish();
187                         return;
188                 }
189
190                 // Enable Text to Speech
191                 tts = new TextToSpeech(this, new OnInitListener() {
192                         public void onInit(int status) {
193                                 if (status == TextToSpeech.SUCCESS) tts_enabled = true;
194                                 if (tts_enabled) tts.speak("AltosDroid ready", TextToSpeech.QUEUE_ADD, null );
195                         }
196                 });
197
198                 // Start Telemetry Service
199                 startService(new Intent(AltosDroid.this, TelemetryService.class));
200
201                 doBindService();
202         }
203
204         @Override
205         public void onStart() {
206                 super.onStart();
207                 if(D) Log.e(TAG, "++ ON START ++");
208
209                 if (!mBluetoothAdapter.isEnabled()) {
210                         Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
211                         startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
212                 }
213         }
214
215         @Override
216         public synchronized void onResume() {
217                 super.onResume();
218                 if(D) Log.e(TAG, "+ ON RESUME +");
219
220         }
221
222         @Override
223         public synchronized void onPause() {
224                 super.onPause();
225                 if(D) Log.e(TAG, "- ON PAUSE -");
226         }
227
228         @Override
229         public void onStop() {
230                 super.onStop();
231                 if(D) Log.e(TAG, "-- ON STOP --");
232         }
233
234         @Override
235         public void onDestroy() {
236                 super.onDestroy();
237
238                 doUnbindService();
239
240                 if (tts != null) tts.shutdown();
241
242                 if(D) Log.e(TAG, "--- ON DESTROY ---");
243         }
244
245
246
247
248         public void onActivityResult(int requestCode, int resultCode, Intent data) {
249                 if(D) Log.d(TAG, "onActivityResult " + resultCode);
250                 switch (requestCode) {
251                 case REQUEST_CONNECT_DEVICE:
252                         // When DeviceListActivity returns with a device to connect to
253                         if (resultCode == Activity.RESULT_OK) {
254                                 connectDevice(data);
255                         }
256                         break;
257                 case REQUEST_ENABLE_BT:
258                         // When the request to enable Bluetooth returns
259                         if (resultCode == Activity.RESULT_OK) {
260                                 // Bluetooth is now enabled, so set up a chat session
261                                 //setupChat();
262                         } else {
263                                 // User did not enable Bluetooth or an error occured
264                                 Log.e(TAG, "BT not enabled");
265                                 stopService(new Intent(AltosDroid.this, TelemetryService.class));
266                                 Toast.makeText(this, R.string.bt_not_enabled, Toast.LENGTH_SHORT).show();
267                                 finish();
268                         }
269                         break;
270                 }
271         }
272
273         private void connectDevice(Intent data) {
274                 // Get the device MAC address
275                 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
276                 // Get the BLuetoothDevice object
277                 BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
278                 // Attempt to connect to the device
279                 try {
280                         if (D) Log.d(TAG, "Connecting to " + device.getName());
281                         mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, device));
282                 } catch (RemoteException e) {
283                 }
284         }
285
286         @Override
287         public boolean onCreateOptionsMenu(Menu menu) {
288                 MenuInflater inflater = getMenuInflater();
289                 inflater.inflate(R.menu.option_menu, menu);
290                 return true;
291         }
292
293         @Override
294         public boolean onOptionsItemSelected(MenuItem item) {
295                 Intent serverIntent = null;
296                 switch (item.getItemId()) {
297                 case R.id.connect_scan:
298                         // Launch the DeviceListActivity to see devices and do scan
299                         serverIntent = new Intent(this, DeviceListActivity.class);
300                         startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
301                         return true;
302                 }
303                 return false;
304         }
305
306
307         void doBindService() {
308                 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
309                 mIsBound = true;
310         }
311
312         void doUnbindService() {
313                 if (mIsBound) {
314                         // If we have received the service, and hence registered with it, then now is the time to unregister.
315                         if (mService != null) {
316                                 try {
317                                         Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
318                                         msg.replyTo = mMessenger;
319                                         mService.send(msg);
320                                 } catch (RemoteException e) {
321                                         // There is nothing special we need to do if the service has crashed.
322                                 }
323                         }
324                         // Detach our existing connection.
325                         unbindService(mConnection);
326                         mIsBound = false;
327                 }
328         }
329
330 }