altosdroid: miscellaneous cleanup
[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                 input_thread = new Thread(this);
63                 input_thread.start();
64         }
65
66         private class ConnectThread extends Thread {
67                 private final UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
68
69                 public ConnectThread(BluetoothDevice device) {
70                         BluetoothSocket tmp_socket = null;
71
72                         try {
73                                 tmp_socket = device.createInsecureRfcommSocketToServiceRecord(SPP_UUID);
74                         } catch (IOException e) {
75                                 e.printStackTrace();
76                         }
77                         socket = tmp_socket;
78                 }
79
80                 public void run() {
81                         if (D) Log.i(TAG, "ConnectThread: BEGIN");
82                         setName("ConnectThread");
83
84                         // Always cancel discovery because it will slow down a connection
85                         adapter.cancelDiscovery();
86
87                         synchronized (AltosBluetooth.this) {
88                                 // Make a connection to the BluetoothSocket
89                                 try {
90                                         // This is a blocking call and will only return on a
91                                         // successful connection or an exception
92                                         socket.connect();
93
94                                         input = socket.getInputStream();
95                                         output = socket.getOutputStream();
96                                 } catch (IOException e) {
97                                         // Close the socket
98                                         try {
99                                                 socket.close();
100                                         } catch (IOException e2) {
101                                                 if (D) Log.e(TAG, "ConnectThread: Failed to close() socket after failed connection");
102                                         }
103                                         input = null;
104                                         output = null;
105                                         AltosBluetooth.this.notifyAll();
106                                         handler.obtainMessage(TelemetryService.MSG_CONNECT_FAILED).sendToTarget();
107                                         if (D) Log.e(TAG, "ConnectThread: Failed to establish connection");
108                                         return;
109                                 }
110
111                                 // Configure the newly connected device for telemetry
112                                 print("~\nE 0\n");
113                                 set_monitor(false);
114
115                                 // Reset the ConnectThread because we're done
116                                 connect_thread = null;
117
118                                 // Send the device name back to the Telemetry Service
119                                 name = device.getName();
120                                 handler.obtainMessage(TelemetryService.MSG_CONNECTED).sendToTarget();
121
122                                 // Notify other waiting threads, now that we're connected
123                                 AltosBluetooth.this.notifyAll();
124
125                                 if (D) Log.i(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 (D) Log.i(TAG, "wait_connected(): begin");
141                 if (input == null) {
142                         if (D) Log.i(TAG, "wait_connected(): waiting");
143                         wait();
144                         if (D) Log.i(TAG, "wait_connected(): wait ended..");
145                         if (input == null) throw new IOException();
146                 }
147         }
148
149         private void connection_failed() {
150                 if (D) Log.e(TAG, "Bluetooth Socket IO failed!");
151                 handler.obtainMessage(TelemetryService.MSG_DISCONNECTED).sendToTarget();
152         }
153
154         public void print(String data) {
155                 byte[] bytes = data.getBytes();
156                 if (D) Log.i(TAG, "print(): begin");
157                 try {
158                         wait_connected();
159                         output.write(bytes);
160                         if (D) Log.i(TAG, "print(): Wrote bytes: '" + data.replace('\n', '\\') + "'");
161                 } catch (IOException e) {
162                         connection_failed();
163                 } catch (InterruptedException e) {
164                         connection_failed();
165                 }
166         }
167
168         public int getchar() {
169                 if (D) Log.i(TAG, "getchar(): begin");
170                 try {
171                         wait_connected();
172                         if (D) Log.i(TAG, "getchar(): proceeding");
173                         return input.read();
174                 } catch (IOException e) {
175                         connection_failed();
176                 } catch (java.lang.InterruptedException e) {
177                         connection_failed();
178                 }
179                 return AltosLink.ERROR;
180         }
181
182         public void close() {
183                 if (D) Log.i(TAG, "close(): begin");
184                 synchronized(this) {
185                         if (D) Log.i(TAG, "close(): synched");
186
187                         if (connect_thread != null) {
188                                 if (D) Log.i(TAG, "close(): stopping connect_thread");
189                                 connect_thread.cancel();
190                                 connect_thread = null;
191                         }
192                         if (D) Log.i(TAG, "close(): Closing socket");
193                         try {
194                                 socket.close();
195                         } catch (IOException e) {
196                                 if (D) Log.e(TAG, "close(): unable to close() socket");
197                         }
198                         if (input_thread != null) {
199                                 if (D) Log.i(TAG, "close(): stopping input_thread");
200                                 try {
201                                         if (D) Log.i(TAG, "close(): input_thread.interrupt().....");
202                                         input_thread.interrupt();
203                                         if (D) Log.i(TAG, "close(): input_thread.join().....");
204                                         input_thread.join();
205                                 } catch (Exception e) {}
206                                 input_thread = null;
207                         }
208                         input = null;
209                         output = null;
210                         notifyAll();
211                 }
212         }
213
214
215         //public void flush_output() { super.flush_output(); }
216
217         public boolean can_cancel_reply()   { return false; }
218         public boolean show_reply_timeout() { return true; }
219         public void hide_reply_timeout()    { }
220
221 }