altosdroid: Skip updating hidden UI elements
[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                 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 void putchar(byte c) {
166                 byte[] bytes = { c };
167                 if (D) Log.d(TAG, "print(): begin");
168                 try {
169                         wait_connected();
170                         output.write(bytes);
171                         if (D) Log.d(TAG, "print(): Wrote byte: '" + c + "'");
172                 } catch (IOException e) {
173                         connection_lost();
174                 } catch (InterruptedException e) {
175                         connection_lost();
176                 }
177         }
178
179         private static final int buffer_size = 1024;
180
181         private byte[] buffer = new byte[buffer_size];
182         private int buffer_len = 0;
183         private int buffer_off = 0;
184
185         public int getchar() {
186                 while (buffer_off == buffer_len) {
187                         try {
188                                 wait_connected();
189                                 buffer_len = input.read(buffer);
190                                 buffer_off = 0;
191                         } catch (IOException e) {
192                                 connection_lost();
193                                 return AltosLink.ERROR;
194                         } catch (java.lang.InterruptedException e) {
195                                 connection_lost();
196                                 return AltosLink.ERROR;
197                         }
198                 }
199                 return buffer[buffer_off++];
200         }
201
202         public void close() {
203                 if (D) Log.d(TAG, "close(): begin");
204                 synchronized(this) {
205                         if (D) Log.d(TAG, "close(): synched");
206
207                         if (connect_thread != null) {
208                                 if (D) Log.d(TAG, "close(): stopping connect_thread");
209                                 connect_thread.cancel();
210                                 connect_thread = null;
211                         }
212                         if (D) Log.d(TAG, "close(): Closing socket");
213                         try {
214                                 socket.close();
215                         } catch (IOException e) {
216                                 if (D) Log.e(TAG, "close(): unable to close() socket");
217                         }
218                         if (input_thread != null) {
219                                 if (D) Log.d(TAG, "close(): stopping input_thread");
220                                 try {
221                                         if (D) Log.d(TAG, "close(): input_thread.interrupt().....");
222                                         input_thread.interrupt();
223                                         if (D) Log.d(TAG, "close(): input_thread.join().....");
224                                         input_thread.join();
225                                 } catch (Exception e) {}
226                                 input_thread = null;
227                         }
228                         input = null;
229                         output = null;
230                         notifyAll();
231                 }
232         }
233
234
235         // We override this method so that we can add some debugging. Not 100% elegant, but more useful
236         // than debugging one char at a time above in getchar()!
237         public void add_reply(AltosLine line) throws InterruptedException {
238                 if (D) Log.d(TAG, String.format("Got REPLY: %s", line.line));
239                 super.add_reply(line);
240         }
241
242         //public void flush_output() { super.flush_output(); }
243
244         // Stubs of required methods when extending AltosLink
245         public boolean can_cancel_reply()   { return false; }
246         public boolean show_reply_timeout() { return true; }
247         public void hide_reply_timeout()    { }
248
249 }