altosdroid: re-work connect/thread handling in AltosBluetooth
[fw/altos] / altosdroid / src / org / altusmetrum / AltosDroid / AltosBluetooth.java
1 /*
2  * Copyright © 2011 Keith Packard <keithp@keithp.com>
3  * Copyright © 2012 Mike Beattie <mike@ethernal.org>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; version 2 of the License.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
17  */
18
19 package org.altusmetrum.AltosDroid;
20
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.io.OutputStream;
24 import java.util.UUID;
25
26 import android.bluetooth.BluetoothAdapter;
27 import android.bluetooth.BluetoothDevice;
28 import android.bluetooth.BluetoothSocket;
29 import android.os.Handler;
30 import android.util.Log;
31
32 import org.altusmetrum.AltosLib.*;
33
34 public class AltosBluetooth extends AltosLink {
35
36         // Debugging
37         private static final String TAG = "AltosBluetooth";
38         private static final boolean D = true;
39
40         private ConnectThread    connect_thread = null;
41         private Thread           input_thread   = null;
42
43         private Handler          handler;
44
45         private BluetoothAdapter adapter;
46         private BluetoothDevice  device;
47         private BluetoothSocket  socket;
48         private InputStream      input;
49         private OutputStream     output;
50
51         // Constructor
52         public AltosBluetooth(BluetoothDevice in_device, Handler in_handler) {
53                 adapter = BluetoothAdapter.getDefaultAdapter();
54                 device = in_device;
55                 handler = in_handler;
56
57                 connect_thread = new ConnectThread(device);
58                 connect_thread.start();
59
60                 input_thread = new Thread(this);
61                 input_thread.start();
62         }
63
64         private class ConnectThread extends Thread {
65                 private final UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
66
67                 public ConnectThread(BluetoothDevice device) {
68                         BluetoothSocket tmp_socket = null;
69
70                         try {
71                                 tmp_socket = device.createInsecureRfcommSocketToServiceRecord(SPP_UUID);
72                         } catch (IOException e) {
73                                 e.printStackTrace();
74                         }
75                         socket = tmp_socket;
76                 }
77
78                 public void run() {
79                         if (D) Log.i(TAG, "ConnectThread: BEGIN");
80                         setName("ConnectThread");
81
82                         // Always cancel discovery because it will slow down a connection
83                         adapter.cancelDiscovery();
84
85                         synchronized (AltosBluetooth.this) {
86                                 // Make a connection to the BluetoothSocket
87                                 try {
88                                         // This is a blocking call and will only return on a
89                                         // successful connection or an exception
90                                         socket.connect();
91
92                                         input = socket.getInputStream();
93                                         output = socket.getOutputStream();
94                                 } catch (IOException e) {
95                                         // Close the socket
96                                         try {
97                                                 socket.close();
98                                         } catch (IOException e2) {
99                                                 if (D) Log.e(TAG, "ConnectThread: Failed to close() socket after failed connection");
100                                         }
101                                         input = null;
102                                         output = null;
103                                         AltosBluetooth.this.notifyAll();
104                                         if (D) Log.e(TAG, "ConnectThread: Failed to establish connection");
105                                         return;
106                                 }
107
108                                 // Configure the newly connected device for telemetry
109                                 print("~\nE 0\n");
110                                 set_monitor(false);
111
112                                 // Reset the ConnectThread because we're done
113                                 connect_thread = null;
114
115                                 // Notify other waiting threads, now that we're connected
116                                 AltosBluetooth.this.notifyAll();
117
118                                 if (D) Log.i(TAG, "ConnectThread: Connect completed");
119                         }
120                 }
121
122                 public void cancel() {
123                         try {
124                                 if (socket != null)
125                                         socket.close();
126                         } catch (IOException e) {
127                                 if (D) Log.e(TAG, "ConnectThread: close() of connect socket failed", e);
128                         }
129                 }
130         }
131
132         private synchronized void wait_connected() throws InterruptedException, IOException {
133                 if (D) Log.i(TAG, "wait_connected(): begin");
134                 if (input == null) {
135                         if (D) Log.i(TAG, "wait_connected(): waiting");
136                         wait();
137                         if (D) Log.i(TAG, "wait_connected(): wait ended..");
138                         if (input == null) throw new IOException();
139                 }
140         }
141
142         private void connection_failed() {
143                 if (D) Log.e(TAG, "Bluetooth Socket IO failed!");
144         }
145         
146         public void print(String data) {
147                 byte[] bytes = data.getBytes();
148                 if (D) Log.i(TAG, "print(): begin");
149                 try {
150                         wait_connected();
151                         output.write(bytes);
152                         if (D) Log.i(TAG, "print(): Wrote bytes: '" + data.replace('\n', '\\') + "'");
153                 } catch (IOException e) {
154                         connection_failed();
155                 } catch (InterruptedException e) {
156                         connection_failed();
157                 }
158         }
159
160         public int getchar() {
161                 if (D) Log.i(TAG, "getchar(): begin");
162                 try {
163                         wait_connected();
164                         if (D) Log.i(TAG, "getchar(): proceeding");
165                         return input.read();
166                 } catch (IOException e) {
167                         connection_failed();
168                 } catch (java.lang.InterruptedException e) {
169                         connection_failed();
170                 }
171                 return AltosLink.ERROR;
172         }
173                         
174         public void close() {
175                 if (D) Log.i(TAG, "close(): begin");
176                 synchronized(this) {
177                         if (D) Log.i(TAG, "close(): synched");
178
179                         if (connect_thread != null) {
180                                 if (D) Log.i(TAG, "close(): stopping connect_thread");
181                                 connect_thread.cancel();
182                                 connect_thread = null;
183                         }
184                         if (D) Log.i(TAG, "close(): Closing socket");
185                         try {
186                                 socket.close();
187                         } catch (IOException e) {
188                                 if (D) Log.e(TAG, "close(): unable to close() socket");
189                         }
190                         if (input_thread != null) {
191                                 if (D) Log.i(TAG, "close(): stopping input_thread");
192                                 try {
193                                         if (D) Log.i(TAG, "close(): input_thread.interrupt().....");
194                                         input_thread.interrupt();
195                                         if (D) Log.i(TAG, "close(): input_thread.join().....");
196                                         input_thread.join();
197                                 } catch (Exception e) {}
198                                 input_thread = null;
199                         }
200                         input = null;
201                         output = null;
202                         notifyAll();
203                 }
204         }
205
206
207         //public void flush_output() { super.flush_output(); }
208
209         public boolean can_cancel_reply()   { return false; }
210         public boolean show_reply_timeout() { return true; }
211         public void hide_reply_timeout()    { }
212
213 }