3740f55d7f83a44d49cf7eabe08a150a4222fef6
[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_6.*;
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(0, frequency);
150         }
151
152         public void save_telemetry_rate() {
153                 AltosPreferences.set_telemetry_rate(0, telemetry_rate);
154         }
155
156         private synchronized void wait_connected() throws InterruptedException, IOException {
157                 if (input == null) {
158                         if (D) Log.d(TAG, "wait_connected...");
159                         wait();
160                         if (D) Log.d(TAG, "wait_connected done");
161                         if (input == null) throw new IOException();
162                 }
163         }
164
165         private void connection_lost() {
166                 if (D) Log.e(TAG, "Connection lost during I/O");
167                 handler.obtainMessage(TelemetryService.MSG_DISCONNECTED).sendToTarget();
168         }
169
170         public void print(String data) {
171                 byte[] bytes = data.getBytes();
172                 if (D) Log.d(TAG, "print(): begin");
173                 try {
174                         wait_connected();
175                         output.write(bytes);
176                         if (D) Log.d(TAG, "print(): Wrote bytes: '" + data.replace('\n', '\\') + "'");
177                 } catch (IOException e) {
178                         connection_lost();
179                 } catch (InterruptedException e) {
180                         connection_lost();
181                 }
182         }
183
184         public void putchar(byte c) {
185                 byte[] bytes = { c };
186                 if (D) Log.d(TAG, "print(): begin");
187                 try {
188                         wait_connected();
189                         output.write(bytes);
190                         if (D) Log.d(TAG, "print(): Wrote byte: '" + c + "'");
191                 } catch (IOException e) {
192                         connection_lost();
193                 } catch (InterruptedException e) {
194                         connection_lost();
195                 }
196         }
197
198         private static final int buffer_size = 1024;
199
200         private byte[] buffer = new byte[buffer_size];
201         private int buffer_len = 0;
202         private int buffer_off = 0;
203
204         public int getchar() {
205                 while (buffer_off == buffer_len) {
206                         try {
207                                 wait_connected();
208                                 buffer_len = input.read(buffer);
209                                 buffer_off = 0;
210                         } catch (IOException e) {
211                                 connection_lost();
212                                 return AltosLink.ERROR;
213                         } catch (java.lang.InterruptedException e) {
214                                 connection_lost();
215                                 return AltosLink.ERROR;
216                         }
217                 }
218                 return buffer[buffer_off++];
219         }
220
221         public void close() {
222                 if (D) Log.d(TAG, "close(): begin");
223                 synchronized(this) {
224                         if (D) Log.d(TAG, "close(): synched");
225
226                         if (connect_thread != null) {
227                                 if (D) Log.d(TAG, "close(): stopping connect_thread");
228                                 connect_thread.cancel();
229                                 connect_thread = null;
230                         }
231                         if (D) Log.d(TAG, "close(): Closing socket");
232                         try {
233                                 socket.close();
234                         } catch (IOException e) {
235                                 if (D) Log.e(TAG, "close(): unable to close() socket");
236                         }
237                         if (input_thread != null) {
238                                 if (D) Log.d(TAG, "close(): stopping input_thread");
239                                 try {
240                                         if (D) Log.d(TAG, "close(): input_thread.interrupt().....");
241                                         input_thread.interrupt();
242                                         if (D) Log.d(TAG, "close(): input_thread.join().....");
243                                         input_thread.join();
244                                 } catch (Exception e) {}
245                                 input_thread = null;
246                         }
247                         input = null;
248                         output = null;
249                         notifyAll();
250                 }
251         }
252
253
254         // We override this method so that we can add some debugging. Not 100% elegant, but more useful
255         // than debugging one char at a time above in getchar()!
256         public void add_reply(AltosLine line) throws InterruptedException {
257                 if (D) Log.d(TAG, String.format("Got REPLY: %s", line.line));
258                 super.add_reply(line);
259         }
260
261         //public void flush_output() { super.flush_output(); }
262
263         // Stubs of required methods when extending AltosLink
264         public boolean can_cancel_reply()   { return false; }
265         public boolean show_reply_timeout() { return true; }
266         public void hide_reply_timeout()    { }
267
268 }