4a1fc3716c9320d6cbf8bca44990832d1edce89c
[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_5.*;
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 //              set_debug(D);
56                 adapter = BluetoothAdapter.getDefaultAdapter();
57                 device = in_device;
58                 handler = in_handler;
59
60                 connect_thread = new ConnectThread(device);
61                 connect_thread.start();
62
63         }
64
65         private class ConnectThread extends Thread {
66                 private final UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
67
68                 public ConnectThread(BluetoothDevice device) {
69                         BluetoothSocket tmp_socket = null;
70
71                         try {
72                                 tmp_socket = device.createInsecureRfcommSocketToServiceRecord(SPP_UUID);
73                         } catch (IOException e) {
74                                 e.printStackTrace();
75                         }
76                         socket = tmp_socket;
77                 }
78
79                 public void run() {
80                         if (D) Log.d(TAG, "ConnectThread: BEGIN");
81                         setName("ConnectThread");
82
83                         // Always cancel discovery because it will slow down a connection
84                         adapter.cancelDiscovery();
85
86                         synchronized (AltosBluetooth.this) {
87                                 // Make a connection to the BluetoothSocket
88                                 try {
89                                         // This is a blocking call and will only return on a
90                                         // successful connection or an exception
91                                         socket.connect();
92
93                                         input = socket.getInputStream();
94                                         output = socket.getOutputStream();
95                                 } catch (IOException e) {
96                                         // Close the socket
97                                         try {
98                                                 socket.close();
99                                         } catch (IOException e2) {
100                                                 if (D) Log.e(TAG, "ConnectThread: Failed to close() socket after failed connection");
101                                         }
102                                         input = null;
103                                         output = null;
104                                         AltosBluetooth.this.notifyAll();
105                                         handler.obtainMessage(TelemetryService.MSG_CONNECT_FAILED).sendToTarget();
106                                         if (D) Log.e(TAG, "ConnectThread: Failed to establish connection");
107                                         return;
108                                 }
109
110                                 input_thread = new Thread(AltosBluetooth.this);
111                                 input_thread.start();
112
113                                 // Configure the newly connected device for telemetry
114                                 print("~\nE 0\n");
115                                 set_monitor(false);
116
117                                 // Let TelemetryService know we're connected
118                                 handler.obtainMessage(TelemetryService.MSG_CONNECTED).sendToTarget();
119
120                                 // Notify other waiting threads, now that we're connected
121                                 AltosBluetooth.this.notifyAll();
122
123                                 // Reset the ConnectThread because we're done
124                                 connect_thread = null;
125
126                                 if (D) Log.d(TAG, "ConnectThread: Connect completed");
127                         }
128                 }
129
130                 public void cancel() {
131                         try {
132                                 if (socket != null)
133                                         socket.close();
134                         } catch (IOException e) {
135                                 if (D) Log.e(TAG, "ConnectThread: close() of connect socket failed", e);
136                         }
137                 }
138         }
139
140         public double frequency() {
141                 return frequency;
142         }
143
144         public int telemetry_rate() {
145                 return telemetry_rate;
146         }
147
148         public void save_frequency() {
149                 AltosPreferences.set_frequency(serial, frequency);
150         }
151
152         public void save_telemetry_rate() {
153                 AltosPreferences.set_telemetry_rate(serial, telemetry_rate);
154         }
155
156         private synchronized void wait_connected() throws InterruptedException, IOException {
157                 if (input == null) {
158                         wait();
159                         if (input == null) throw new IOException();
160                 }
161         }
162
163         private void connection_lost() {
164                 if (D) Log.e(TAG, "Connection lost during I/O");
165                 handler.obtainMessage(TelemetryService.MSG_DISCONNECTED).sendToTarget();
166         }
167
168         public void print(String data) {
169                 byte[] bytes = data.getBytes();
170                 if (D) Log.d(TAG, "print(): begin");
171                 try {
172                         wait_connected();
173                         output.write(bytes);
174                         if (D) Log.d(TAG, "print(): Wrote bytes: '" + data.replace('\n', '\\') + "'");
175                 } catch (IOException e) {
176                         connection_lost();
177                 } catch (InterruptedException e) {
178                         connection_lost();
179                 }
180         }
181
182         public void putchar(byte c) {
183                 byte[] bytes = { c };
184                 if (D) Log.d(TAG, "print(): begin");
185                 try {
186                         wait_connected();
187                         output.write(bytes);
188                         if (D) Log.d(TAG, "print(): Wrote byte: '" + c + "'");
189                 } catch (IOException e) {
190                         connection_lost();
191                 } catch (InterruptedException e) {
192                         connection_lost();
193                 }
194         }
195
196         private static final int buffer_size = 1024;
197
198         private byte[] buffer = new byte[buffer_size];
199         private int buffer_len = 0;
200         private int buffer_off = 0;
201
202         public int getchar() {
203                 while (buffer_off == buffer_len) {
204                         try {
205                                 wait_connected();
206                                 buffer_len = input.read(buffer);
207                                 buffer_off = 0;
208                         } catch (IOException e) {
209                                 connection_lost();
210                                 return AltosLink.ERROR;
211                         } catch (java.lang.InterruptedException e) {
212                                 connection_lost();
213                                 return AltosLink.ERROR;
214                         }
215                 }
216                 return buffer[buffer_off++];
217         }
218
219         public void close() {
220                 if (D) Log.d(TAG, "close(): begin");
221                 synchronized(this) {
222                         if (D) Log.d(TAG, "close(): synched");
223
224                         if (connect_thread != null) {
225                                 if (D) Log.d(TAG, "close(): stopping connect_thread");
226                                 connect_thread.cancel();
227                                 connect_thread = null;
228                         }
229                         if (D) Log.d(TAG, "close(): Closing socket");
230                         try {
231                                 socket.close();
232                         } catch (IOException e) {
233                                 if (D) Log.e(TAG, "close(): unable to close() socket");
234                         }
235                         if (input_thread != null) {
236                                 if (D) Log.d(TAG, "close(): stopping input_thread");
237                                 try {
238                                         if (D) Log.d(TAG, "close(): input_thread.interrupt().....");
239                                         input_thread.interrupt();
240                                         if (D) Log.d(TAG, "close(): input_thread.join().....");
241                                         input_thread.join();
242                                 } catch (Exception e) {}
243                                 input_thread = null;
244                         }
245                         input = null;
246                         output = null;
247                         notifyAll();
248                 }
249         }
250
251
252         // We override this method so that we can add some debugging. Not 100% elegant, but more useful
253         // than debugging one char at a time above in getchar()!
254         public void add_reply(AltosLine line) throws InterruptedException {
255                 if (D) Log.d(TAG, String.format("Got REPLY: %s", line.line));
256                 super.add_reply(line);
257         }
258
259         //public void flush_output() { super.flush_output(); }
260
261         // Stubs of required methods when extending AltosLink
262         public boolean can_cancel_reply()   { return false; }
263         public boolean show_reply_timeout() { return true; }
264         public void hide_reply_timeout()    { }
265
266 }