Merge branch 'master' of ssh://git.gag.com/scm/git/fw/altos
[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.Bundle;
30 import android.os.Handler;
31 //import android.os.Message;
32 import android.util.Log;
33
34 import org.altusmetrum.AltosLib.*;
35
36 public class AltosBluetooth extends AltosLink {
37
38         // Debugging
39         private static final String TAG = "AltosBluetooth";
40         private static final boolean D = true;
41
42         private ConnectThread    connect_thread = null;
43         private Thread           input_thread   = null;
44
45         private Handler          handler;
46
47         private BluetoothAdapter adapter;
48         private BluetoothDevice  device;
49         private BluetoothSocket  socket;
50         private InputStream      input;
51         private OutputStream     output;
52
53         // Constructor
54         public AltosBluetooth(BluetoothDevice in_device, Handler in_handler) {
55                 adapter = BluetoothAdapter.getDefaultAdapter();
56                 device = in_device;
57                 handler = in_handler;
58
59                 connect_thread = new ConnectThread(device);
60                 connect_thread.start();
61
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.d(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                                         handler.obtainMessage(TelemetryService.MSG_CONNECT_FAILED).sendToTarget();
105                                         if (D) Log.e(TAG, "ConnectThread: Failed to establish connection");
106                                         return;
107                                 }
108
109                                 input_thread = new Thread(AltosBluetooth.this);
110                                 input_thread.start();
111
112                                 // Configure the newly connected device for telemetry
113                                 print("~\nE 0\n");
114                                 set_monitor(false);
115
116                                 // Let TelemetryService know we're connected
117                                 handler.obtainMessage(TelemetryService.MSG_CONNECTED).sendToTarget();
118
119                                 // Notify other waiting threads, now that we're connected
120                                 AltosBluetooth.this.notifyAll();
121
122                                 // Reset the ConnectThread because we're done
123                                 connect_thread = null;
124
125                                 if (D) Log.d(TAG, "ConnectThread: Connect completed");
126                         }
127                 }
128
129                 public void cancel() {
130                         try {
131                                 if (socket != null)
132                                         socket.close();
133                         } catch (IOException e) {
134                                 if (D) Log.e(TAG, "ConnectThread: close() of connect socket failed", e);
135                         }
136                 }
137         }
138
139         private synchronized void wait_connected() throws InterruptedException, IOException {
140                 if (input == null) {
141                         wait();
142                         if (input == null) throw new IOException();
143                 }
144         }
145
146         private void connection_lost() {
147                 if (D) Log.e(TAG, "Connection lost during I/O");
148                 handler.obtainMessage(TelemetryService.MSG_DISCONNECTED).sendToTarget();
149         }
150
151         public void print(String data) {
152                 byte[] bytes = data.getBytes();
153                 if (D) Log.d(TAG, "print(): begin");
154                 try {
155                         wait_connected();
156                         output.write(bytes);
157                         if (D) Log.d(TAG, "print(): Wrote bytes: '" + data.replace('\n', '\\') + "'");
158                 } catch (IOException e) {
159                         connection_lost();
160                 } catch (InterruptedException e) {
161                         connection_lost();
162                 }
163         }
164
165         public int getchar() {
166                 try {
167                         wait_connected();
168                         return input.read();
169                 } catch (IOException e) {
170                         connection_lost();
171                 } catch (java.lang.InterruptedException e) {
172                         connection_lost();
173                 }
174                 return AltosLink.ERROR;
175         }
176
177         public void close() {
178                 if (D) Log.d(TAG, "close(): begin");
179                 synchronized(this) {
180                         if (D) Log.d(TAG, "close(): synched");
181
182                         if (connect_thread != null) {
183                                 if (D) Log.d(TAG, "close(): stopping connect_thread");
184                                 connect_thread.cancel();
185                                 connect_thread = null;
186                         }
187                         if (D) Log.d(TAG, "close(): Closing socket");
188                         try {
189                                 socket.close();
190                         } catch (IOException e) {
191                                 if (D) Log.e(TAG, "close(): unable to close() socket");
192                         }
193                         if (input_thread != null) {
194                                 if (D) Log.d(TAG, "close(): stopping input_thread");
195                                 try {
196                                         if (D) Log.d(TAG, "close(): input_thread.interrupt().....");
197                                         input_thread.interrupt();
198                                         if (D) Log.d(TAG, "close(): input_thread.join().....");
199                                         input_thread.join();
200                                 } catch (Exception e) {}
201                                 input_thread = null;
202                         }
203                         input = null;
204                         output = null;
205                         notifyAll();
206                 }
207         }
208
209
210         // We override this method so that we can add some debugging. Not 100% elegant, but more useful
211         // than debugging one char at a time above in getchar()!
212         public void add_reply(AltosLine line) throws InterruptedException {
213                 if (D) Log.d(TAG, String.format("Got REPLY: %s", line.line));
214                 super.add_reply(line);
215         }
216
217         //public void flush_output() { super.flush_output(); }
218
219         // Stubs of required methods when extending AltosLink
220         public boolean can_cancel_reply()   { return false; }
221         public boolean show_reply_timeout() { return true; }
222         public void hide_reply_timeout()    { }
223
224 }