-
Notifications
You must be signed in to change notification settings - Fork 376
/
BertyDevice.java
95 lines (79 loc) · 2.91 KB
/
BertyDevice.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package chat.berty.ble;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.os.Build;
import android.util.Log;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
public class BertyDevice {
public static String TAG = "chat.berty.ble.BertyDevice";
public String addr;
public String peerID;
public String ma;
public int mtu;
protected BluetoothGattCharacteristic acceptCharacteristic;
protected BluetoothGattCharacteristic maCharacteristic;
protected BluetoothGattCharacteristic peerIDCharacteristic;
protected BluetoothGattCharacteristic writerCharacteristic;
protected BluetoothGattCharacteristic isRdyCharacteristic;
protected BluetoothGattCharacteristic closerCharacteristic;
public BluetoothGatt gatt;
public BluetoothDevice device;
public CountDownLatch waitReady;
public Semaphore isWaiting;
public List<byte[]> toSend;
public BertyDevice(BluetoothDevice device, BluetoothGatt gatt, String address) {
this.gatt = gatt;
this.addr = address;
this.device = device;
this.isWaiting = new Semaphore(1);
waitReady = new CountDownLatch(8);
this.toSend = new ArrayList<>();
new Thread(new Runnable() {
@Override
public void run() {
isRdy();
}
}).start();
}
public void isRdy() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
try {
waitReady.await();
isRdyCharacteristic.setValue("");
while (!gatt.writeCharacteristic(isRdyCharacteristic)) {
/** intentionally empty */
}
} catch (Exception e) {
Log.e(TAG, "Error waiting/writing " + e.getMessage());
}
}
}
public void write(byte[] p) throws InterruptedException {
waitReady.await();
synchronized (toSend) {
int length = p.length;
int offset = 0;
do {
int chunckSize = length - offset > mtu ? mtu : length - offset;
byte[] chunck = Arrays.copyOfRange(p, offset, chunckSize);
offset += chunckSize;
toSend.add(chunck);
} while (offset < length);
while (!toSend.isEmpty()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
writerCharacteristic.setValue(toSend.get(0));
while (!gatt.writeCharacteristic(writerCharacteristic)) {
/** intentionally empty */
}
isWaiting.acquire();
}
toSend.remove(0);
}
}
}
}