Compare commits
46
Commits
ec02bc7bcc
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e53c7be976 | ||
|
|
99598c14fe | ||
|
|
876ea68622 | ||
|
|
9f32185b78 | ||
|
|
d70bbfed13 | ||
|
|
6da0474e59 | ||
|
|
a6cc776a0d | ||
|
|
90ab682a44 | ||
|
|
b0b310a7b0 | ||
|
|
f5cc27a30d | ||
|
|
7a583419c5 | ||
|
|
2d7594514c | ||
|
|
52217c3f6a | ||
|
|
dd7d927044 | ||
|
|
1601787ecf | ||
|
|
81be281bcd | ||
|
|
56813159c4 | ||
|
|
ca70d55f7e | ||
|
|
a4a7dea4ba | ||
|
|
c6f6e4f317 | ||
|
|
4ae98b622b | ||
|
|
6bad5ba08e | ||
|
|
2edbeb8714 | ||
|
|
56d6e87ef3 | ||
|
|
57f19407dd | ||
|
|
3bc712870d | ||
|
|
e7f82ac9e7 | ||
|
|
4cdaceda76 | ||
|
|
fc0cab1ee8 | ||
|
|
4db9b4a5ed | ||
|
|
2af636b946 | ||
|
|
7223b8c380 | ||
|
|
321b94a486 | ||
|
|
99bcd1f4fb | ||
|
|
86e724cc8c | ||
|
|
829baedeac | ||
|
|
0ab45a1d9d | ||
|
|
4e4c071697 | ||
|
|
820186e132 | ||
|
|
f036c5e134 | ||
|
|
206bd70461 | ||
|
|
c911bbb547 | ||
|
|
2d4f106dd7 | ||
|
|
5955e369e4 | ||
|
|
fbb58a8d99 | ||
|
|
b87fea7fb3 |
@@ -0,0 +1,3 @@
|
|||||||
|
|
||||||
|
classes/
|
||||||
|
cb.ast
|
||||||
@@ -0,0 +1,308 @@
|
|||||||
|
package st.wow.git.ble;
|
||||||
|
|
||||||
|
import java.lang.String;
|
||||||
|
import java.lang.Runnable;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
import android.app.Activity;
|
||||||
|
import android.app.Fragment;
|
||||||
|
import android.app.FragmentTransaction;
|
||||||
|
import android.bluetooth.BluetoothAdapter;
|
||||||
|
import android.bluetooth.BluetoothGatt;
|
||||||
|
import android.bluetooth.BluetoothGattCharacteristic;
|
||||||
|
import android.bluetooth.BluetoothGattDescriptor;
|
||||||
|
import android.bluetooth.BluetoothGattService;
|
||||||
|
import android.bluetooth.BluetoothManager;
|
||||||
|
import android.bluetooth.le.ScanResult;
|
||||||
|
import android.content.BroadcastReceiver;
|
||||||
|
import android.content.Context;
|
||||||
|
import android.content.Intent;
|
||||||
|
import android.content.IntentFilter;
|
||||||
|
import android.content.pm.PackageManager;
|
||||||
|
import android.Manifest;
|
||||||
|
import android.os.Handler;
|
||||||
|
import android.util.Log;
|
||||||
|
import android.view.View;
|
||||||
|
|
||||||
|
import com.welie.blessed.BluetoothCentral;
|
||||||
|
import com.welie.blessed.BluetoothCentralCallback;
|
||||||
|
import com.welie.blessed.BluetoothPeripheral;
|
||||||
|
import com.welie.blessed.BluetoothPeripheralCallback;
|
||||||
|
|
||||||
|
public class BlessedConnect extends Fragment {
|
||||||
|
BluetoothCentral central;
|
||||||
|
boolean wantScan = false;
|
||||||
|
|
||||||
|
final int PERMISSION_REQUEST = 1;
|
||||||
|
final int REQUEST_ENABLE_BT = 2;
|
||||||
|
final int PERMISSION_REQUEST_BLE = 3;
|
||||||
|
|
||||||
|
public BlessedConnect() {
|
||||||
|
Log.d("gio", "BlessedConnect()");
|
||||||
|
}
|
||||||
|
|
||||||
|
public void register(View view) {
|
||||||
|
Log.d("gio", "BlessedConnect: register()");
|
||||||
|
Context ctx = view.getContext();
|
||||||
|
Handler handler = new Handler(ctx.getMainLooper());
|
||||||
|
BlessedConnect inst = this;
|
||||||
|
handler.post(new Runnable() {
|
||||||
|
public void run() {
|
||||||
|
Activity act = (Activity)ctx;
|
||||||
|
FragmentTransaction ft = act.getFragmentManager().beginTransaction();
|
||||||
|
ft.add(inst, "BlessedConnect");
|
||||||
|
if (android.os.Build.VERSION.SDK_INT >= 24) {
|
||||||
|
ft.commitNowAllowingStateLoss();
|
||||||
|
} else {
|
||||||
|
ft.commitNow();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override public void onAttach(Context ctx) {
|
||||||
|
super.onAttach(ctx);
|
||||||
|
Log.d("gio", "BlessedConnect: onAttach()");
|
||||||
|
ctx.registerReceiver(receiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
|
||||||
|
if (android.os.Build.VERSION.SDK_INT >= 31) {
|
||||||
|
// BLE on Android 12+ needs the BLUETOOTH_SCAN/CONNECT runtime
|
||||||
|
// permissions. BLUETOOTH_SCAN is declared with
|
||||||
|
// usesPermissionFlags="neverForLocation", so no location
|
||||||
|
// permission is required for scanning.
|
||||||
|
requestPermissions(new String[]{
|
||||||
|
"android.permission.BLUETOOTH_SCAN",
|
||||||
|
"android.permission.BLUETOOTH_CONNECT"}, PERMISSION_REQUEST_BLE);
|
||||||
|
} else if (ctx.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
|
||||||
|
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST);
|
||||||
|
}
|
||||||
|
central = new BluetoothCentral(ctx, centralCallback, null);
|
||||||
|
System.loadLibrary("gio");
|
||||||
|
installComplete(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
private final BroadcastReceiver receiver = new BroadcastReceiver() {
|
||||||
|
@Override
|
||||||
|
public void onReceive(Context context, Intent intent) {
|
||||||
|
Log.d("gio", "Received broadcast");
|
||||||
|
if (intent.getAction().equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
|
||||||
|
updateState(intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
public boolean enabled() {
|
||||||
|
Context ctx = getContext();
|
||||||
|
//The Blessed library does not expose this functionality, so
|
||||||
|
//we need to get our own BluetoothAdapter and check its status.
|
||||||
|
BluetoothAdapter adapter = ((BluetoothManager)ctx.getSystemService(ctx.BLUETOOTH_SERVICE)).getAdapter();
|
||||||
|
return (adapter != null && adapter.isEnabled());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onDestroy() {
|
||||||
|
Log.d("gio","onDestroy()");
|
||||||
|
stopScan();
|
||||||
|
getContext().unregisterReceiver(receiver);
|
||||||
|
super.onDestroy();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void scan() {
|
||||||
|
if (enabled()) {
|
||||||
|
central.scanForPeripherals();
|
||||||
|
} else {
|
||||||
|
wantScan = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void stopScan() {
|
||||||
|
central.stopScan();
|
||||||
|
}
|
||||||
|
|
||||||
|
private final BluetoothCentralCallback centralCallback = new BluetoothCentralCallback() {
|
||||||
|
@Override
|
||||||
|
public void onDiscoveredPeripheral(BluetoothPeripheral peripheral, ScanResult scanResult) {
|
||||||
|
Log.d("gio", "BlessedConnect: onDiscoveredPeripheral(): " + peripheral.getName());
|
||||||
|
onScan(peripheral.getName(), peripheral.getAddress(), scanResult.getRssi(), peripheral);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onConnectedPeripheral(BluetoothPeripheral peripheral) {
|
||||||
|
if (peripheral.getState() == peripheral.STATE_CONNECTED) {
|
||||||
|
Log.d("gio", "BlessedConnect: Connected to " + peripheral.getName());
|
||||||
|
Log.d("gio", "BlessedConnect: Address = " + peripheral.getAddress());
|
||||||
|
|
||||||
|
onConnect(peripheral, peripheral.getAddress());
|
||||||
|
} else {
|
||||||
|
onDisconnect(peripheral, peripheral.getAddress());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onConnectionFailed(BluetoothPeripheral peripheral, int status) {
|
||||||
|
Log.d("gio", "BlessedConnect: onConnectionFailed()");
|
||||||
|
onDisconnect(peripheral, peripheral.getAddress());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onDisconnectedPeripheral(BluetoothPeripheral peripheral, int status) {
|
||||||
|
Log.d("gio", "BlessedConnect: Disconnected");
|
||||||
|
onDisconnect(peripheral, peripheral.getAddress());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onScanFailed(int errorCode) {
|
||||||
|
Log.d("gio", "BlessedConnect: Scan failed");
|
||||||
|
}
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
private final BluetoothPeripheralCallback peripheralCallback = new BluetoothPeripheralCallback() {
|
||||||
|
public void onBondingFailed(BluetoothPeripheral peripheral) {
|
||||||
|
Log.d("gio", "BlessedConnect: onBondingFailed()");
|
||||||
|
}
|
||||||
|
public void onBondingStarted(BluetoothPeripheral peripheral) {
|
||||||
|
Log.d("gio", "BlessedConnect: onBondingStarted()");
|
||||||
|
}
|
||||||
|
public void onBondingSucceeded(BluetoothPeripheral peripheral) {
|
||||||
|
Log.d("gio", "BlessedConnect: onBondingSucceeded()");
|
||||||
|
}
|
||||||
|
public void onBondLost(BluetoothPeripheral peripheral) {
|
||||||
|
Log.d("gio", "BlessedConnect: onBondLost()");
|
||||||
|
}
|
||||||
|
public void onCharacteristicUpdate(BluetoothPeripheral peripheral, byte[] value, BluetoothGattCharacteristic characteristic, int status) {
|
||||||
|
Log.d("gio", "BlessedConnect: onCharacteristicUpdate()");
|
||||||
|
characteristicChanged(peripheral.getAddress(), characteristic.getUuid().toString(), characteristic, value, value.length);
|
||||||
|
}
|
||||||
|
public void onCharacteristicWrite(BluetoothPeripheral peripheral, byte[] value, android.bluetooth.BluetoothGattCharacteristic characteristic, int status) {
|
||||||
|
Log.d("gio", "onCharacteristicWrite(): " + characteristic.getUuid().toString());
|
||||||
|
}
|
||||||
|
public void onDescriptorRead(BluetoothPeripheral peripheral, byte[] value, android.bluetooth.BluetoothGattDescriptor descriptor, int status) {
|
||||||
|
Log.d("gio", "onDescriptorRead()");
|
||||||
|
}
|
||||||
|
public void onDescriptorWrite(BluetoothPeripheral peripheral, byte[] value, android.bluetooth.BluetoothGattDescriptor descriptor, int status) {
|
||||||
|
Log.d("gio", "onDescriptorWrite(): " + descriptor.getUuid().toString());
|
||||||
|
}
|
||||||
|
public void onMtuChanged(BluetoothPeripheral peripheral, int mtu, int status) {
|
||||||
|
Log.d("gio", "onMtuChanged()");
|
||||||
|
}
|
||||||
|
public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
|
||||||
|
Log.d("gio", "onReadRemoteRssi");
|
||||||
|
}
|
||||||
|
public void onNotificationStateUpdate(BluetoothPeripheral peripheral, BluetoothGattCharacteristic characteristic, int status) {
|
||||||
|
if (status == BluetoothGatt.GATT_SUCCESS) {
|
||||||
|
if(peripheral.isNotifying(characteristic)) {
|
||||||
|
Log.i("gio", String.format("BlessedConnect: Notify set to 'on' for %s", characteristic.getUuid()));
|
||||||
|
} else {
|
||||||
|
Log.i("gio", String.format("BlessedConnect: Notify set to 'off' for %s", characteristic.getUuid()));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Log.d("gio", "BlessedConnect: onNotificationStateUpdate(): failed");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
public void onServicesDiscovered(BluetoothPeripheral peripheral) {
|
||||||
|
Log.d("gio", "BlessedConnect: onServicesDiscovered()");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
public void connect(BluetoothPeripheral peripheral) {
|
||||||
|
if (peripheral == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Log.d("gio","BlessedConnect: connect");
|
||||||
|
central.connectPeripheral(peripheral, peripheralCallback);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void disconnect(BluetoothPeripheral peripheral) {
|
||||||
|
if (peripheral == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Log.d("gio","BlessedConnect: disconnect");
|
||||||
|
peripheral.cancelConnection();
|
||||||
|
onDisconnect(peripheral, peripheral.getAddress());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void discoverServices(BluetoothPeripheral peripheral) {
|
||||||
|
if (peripheral == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
List<BluetoothGattService> services = peripheral.getServices();
|
||||||
|
for (BluetoothGattService serv : services) {
|
||||||
|
onDiscoverService(peripheral.getAddress(), serv.getUuid().toString(), serv);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void discoverCharacteristics(BluetoothPeripheral peripheral, BluetoothGattService serv) {
|
||||||
|
if (peripheral == null || serv == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
List<BluetoothGattCharacteristic> chrs = serv.getCharacteristics();
|
||||||
|
for (BluetoothGattCharacteristic chr : chrs) {
|
||||||
|
onDiscoverCharacteristic(peripheral.getAddress(), serv.getUuid().toString(), serv, chr.getUuid().toString(), chr);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void readCharacteristic(BluetoothPeripheral peripheral, BluetoothGattCharacteristic chr) {
|
||||||
|
if (peripheral == null || chr == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
peripheral.readCharacteristic(chr);
|
||||||
|
}
|
||||||
|
public boolean setCharacteristicNotification(BluetoothPeripheral peripheral, BluetoothGattCharacteristic chr) {
|
||||||
|
if (peripheral == null || chr == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return peripheral.setNotify(chr, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
|
||||||
|
Log.d("gio", "BlessedConnect: onActivityResult()");
|
||||||
|
if (requestCode == REQUEST_ENABLE_BT) {
|
||||||
|
Log.d("gio", "BlessedConnect: onActivityResult() REQUEST_ENABLE_BT");
|
||||||
|
switch (resultCode) {
|
||||||
|
case Activity.RESULT_OK: {
|
||||||
|
Log.d("gio", "BlessedConnect: onActivityResult() -- OK");
|
||||||
|
if (wantScan) {
|
||||||
|
scan();
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case Activity.RESULT_CANCELED: {
|
||||||
|
Log.d("gio", "BlessedConnect: onActivityResult() -- Cancelled");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onRequestPermissionsResult (int requestCode, String[] permissions, int[] grantResults) {
|
||||||
|
Log.d("gio", "BlessedConnect: onRequestPermissionsResult");
|
||||||
|
if (requestCode == PERMISSION_REQUEST || requestCode == PERMISSION_REQUEST_BLE) {
|
||||||
|
boolean granted = true;
|
||||||
|
for (int x : grantResults) {
|
||||||
|
if (x == PackageManager.PERMISSION_DENIED) {
|
||||||
|
granted = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!granted) {
|
||||||
|
Log.d("gio", "BlessedConnect: permissions not granted");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Log.d("gio", "BlessedConnect: permissions granted");
|
||||||
|
if (wantScan) {
|
||||||
|
scan();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static private native void installComplete(BlessedConnect p);
|
||||||
|
|
||||||
|
static private native void updateState(int s);
|
||||||
|
static private native void onScan(String name, String id, int rssi, BluetoothPeripheral peripheral);
|
||||||
|
static private native void onConnect(BluetoothPeripheral peripheral, String id);
|
||||||
|
static private native void onDisconnect(BluetoothPeripheral peripheral, String id);
|
||||||
|
static private native void onDiscoverService(String id, String uuid, BluetoothGattService serv);
|
||||||
|
static private native void onDiscoverCharacteristic(String id, String suuid, BluetoothGattService serv, String cuuid, BluetoothGattCharacteristic chr);
|
||||||
|
static private native void characteristicChanged(String id, String cuuid, BluetoothGattCharacteristic chr, byte[] value, int length);
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
The MIT License (MIT)
|
||||||
|
|
||||||
|
Copyright (c) 2019 Gregory Pomerantz
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in
|
||||||
|
all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
|
THE SOFTWARE.
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2019 Martijn van Welie
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
+202
@@ -0,0 +1,202 @@
|
|||||||
|
|
||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright [yyyy] [name of copyright owner]
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
# BLE
|
||||||
|
|
||||||
|
A modern, cross-platform Go library for Bluetooth Low Energy
|
||||||
|
|
||||||
|
This package is a working but incomplete interface for access to Bluetooth
|
||||||
|
Low Energy devices. It is intended to support multiple operating systems
|
||||||
|
with a uniform API. Currently, MacOS and Android are supported. Android
|
||||||
|
support requires the use of [Gio](https://gioui.org).
|
||||||
|
|
||||||
|
The API is asyncrhonous and event driven. To access Bluetooth hardware,
|
||||||
|
first create a `BLE` variable with `NewBLE()`. On Android, you must also
|
||||||
|
call `Enable` with a pointer to your Gio Window.
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
...
|
||||||
|
"git.wow.st/gmp/ble"
|
||||||
|
"gioui.org/app"
|
||||||
|
)
|
||||||
|
|
||||||
|
func runloop() {
|
||||||
|
b := ble.NewBle()
|
||||||
|
w := app.NewWindow()
|
||||||
|
b.Enable(w)
|
||||||
|
...
|
||||||
|
```
|
||||||
|
|
||||||
|
Once enabled, you can call the primary API functions, `Scan`, `StopScan`,
|
||||||
|
`Connect`, and `CancelConnection`. You can also query the state of the
|
||||||
|
Bluetooth hardware by calling `State`.
|
||||||
|
|
||||||
|
Calling `Events` on your `BLE` object returns a channel on which API events
|
||||||
|
are delivered. These events notify your program when the state of the
|
||||||
|
BLE hardware changes (e.g. powered on or off), peripherals are connected,
|
||||||
|
services or characteristics are discovered, or values for characteristics
|
||||||
|
are updated.
|
||||||
|
|
||||||
|
Using Gio, your main event loop will look something like this:
|
||||||
|
|
||||||
|
```
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case e := <-b.Events():
|
||||||
|
switch e := e.(type) {
|
||||||
|
// Handle BLE Events
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case e := <-w.Events():
|
||||||
|
switch e := e.(type) {
|
||||||
|
// Handle Gio events
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
An example heart rate monitor app can be found at [git.wow.st/gmp/hrm](https://git.wow.st/gmp/hrm).
|
||||||
@@ -0,0 +1,284 @@
|
|||||||
|
package ble
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.wow.st/gmp/ble/gatt"
|
||||||
|
)
|
||||||
|
|
||||||
|
type BLE struct {
|
||||||
|
state bleState
|
||||||
|
events chan interface{}
|
||||||
|
peripherals Peripherals
|
||||||
|
handle bleHandle
|
||||||
|
|
||||||
|
ready, wantScan bool
|
||||||
|
sync.Mutex
|
||||||
|
|
||||||
|
connections Connections
|
||||||
|
}
|
||||||
|
|
||||||
|
type PeripheralListItem struct {
|
||||||
|
p Peripheral
|
||||||
|
seen time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
type Peripherals struct {
|
||||||
|
items []PeripheralListItem
|
||||||
|
sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
type ConnectionListItem struct {
|
||||||
|
p Peripheral
|
||||||
|
state chan string
|
||||||
|
}
|
||||||
|
|
||||||
|
type Connections struct {
|
||||||
|
items []ConnectionListItem
|
||||||
|
close chan struct{}
|
||||||
|
sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Connections) UpdateState(p Peripheral, s string) {
|
||||||
|
var ch chan string
|
||||||
|
c.Lock()
|
||||||
|
for _, item := range c.items {
|
||||||
|
if p.Identifier == item.p.Identifier {
|
||||||
|
ch = item.state
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c.Unlock()
|
||||||
|
ch <- s
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ps *Peripherals) Add(x Peripheral) bool {
|
||||||
|
ps.Lock()
|
||||||
|
defer ps.Unlock()
|
||||||
|
found := false
|
||||||
|
for n, item := range ps.items {
|
||||||
|
if item.p.Identifier == x.Identifier {
|
||||||
|
item.p = x
|
||||||
|
item.seen = time.Now()
|
||||||
|
ps.items[n] = item
|
||||||
|
found = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if found {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
//take ownership of this object
|
||||||
|
x.Retain()
|
||||||
|
item := PeripheralListItem{p: x, seen: time.Now()}
|
||||||
|
ps.items = append(ps.items, item)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cs *Connections) Add(x ConnectionListItem) bool {
|
||||||
|
cs.Lock()
|
||||||
|
defer cs.Unlock()
|
||||||
|
found := false
|
||||||
|
for _, item := range cs.items {
|
||||||
|
if item.p.Identifier == x.p.Identifier {
|
||||||
|
// are we allowed to have multiple connections to the same peripheral?
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if found {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
cs.items = append(cs.items, x)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
type UpdateStateEvent struct {
|
||||||
|
State string
|
||||||
|
}
|
||||||
|
|
||||||
|
type DiscoverPeripheralEvent struct {
|
||||||
|
Peripheral Peripheral
|
||||||
|
}
|
||||||
|
|
||||||
|
//FIXME: create a Service type that is platform dependent to make the
|
||||||
|
//event platform independent
|
||||||
|
type DiscoverServiceEvent struct {
|
||||||
|
Peripheral Peripheral
|
||||||
|
Gatt gatt.Service
|
||||||
|
Service Service
|
||||||
|
}
|
||||||
|
|
||||||
|
//FIXME: create a Characteristic type that is platform dependent to make the
|
||||||
|
//event platform independent
|
||||||
|
type DiscoverCharacteristicEvent struct {
|
||||||
|
Peripheral Peripheral
|
||||||
|
Gatt gatt.Characteristic
|
||||||
|
Service Service
|
||||||
|
Characteristic Characteristic
|
||||||
|
}
|
||||||
|
|
||||||
|
//FIXME: create a Characteristic type that is platform dependent to make the
|
||||||
|
//event platform independent
|
||||||
|
type UpdateValueEvent struct {
|
||||||
|
Peripheral Peripheral
|
||||||
|
Characteristic Characteristic
|
||||||
|
Data []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
type ConnectEvent struct {
|
||||||
|
Peripheral Peripheral
|
||||||
|
}
|
||||||
|
|
||||||
|
type DisconnectEvent struct {
|
||||||
|
Peripheral Peripheral
|
||||||
|
}
|
||||||
|
|
||||||
|
type ConnectTimeoutEvent struct {
|
||||||
|
Peripheral Peripheral
|
||||||
|
}
|
||||||
|
|
||||||
|
type UpdageValueEvent struct {
|
||||||
|
Peripheral Peripheral
|
||||||
|
Characteristic gatt.Characteristic
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *BLE) Events() chan interface{} {
|
||||||
|
return b.events
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *BLE) State() string {
|
||||||
|
b.Lock()
|
||||||
|
defer b.Unlock()
|
||||||
|
return b.stringState()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *BLE) Scan() {
|
||||||
|
b.Lock()
|
||||||
|
defer b.Unlock()
|
||||||
|
if b.readyToScan() {
|
||||||
|
log.Printf("ready to scan")
|
||||||
|
b.peripherals.Lock()
|
||||||
|
b.peripherals.items = b.peripherals.items[:0]
|
||||||
|
b.peripherals.Unlock()
|
||||||
|
fmt.Printf("Go: Scanning\n")
|
||||||
|
b.scan()
|
||||||
|
} else {
|
||||||
|
b.wantScan = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *BLE) StopScan() {
|
||||||
|
b.Lock()
|
||||||
|
if !b.ready {
|
||||||
|
b.Unlock()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
b.Unlock()
|
||||||
|
fmt.Printf("Go: stopping scan\n")
|
||||||
|
b.stopScan()
|
||||||
|
}
|
||||||
|
|
||||||
|
func CancelConnection(p Peripheral) {
|
||||||
|
b := peripheralLookup(p)
|
||||||
|
if b == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
b.connections.Lock()
|
||||||
|
var ch chan string;
|
||||||
|
for _, item := range b.connections.items {
|
||||||
|
if item.p.Identifier == p.Identifier {
|
||||||
|
ch = item.state
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b.connections.Unlock()
|
||||||
|
if ch != nil {
|
||||||
|
ch <- "cancel"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func connectTracker(b *BLE, x ConnectionListItem) bool {
|
||||||
|
fmt.Printf("connectTracker(): %s\n", x.p.Name)
|
||||||
|
b.connections.Lock()
|
||||||
|
for _, item := range b.connections.items {
|
||||||
|
if item.p.Identifier == x.p.Identifier {
|
||||||
|
fmt.Printf("connectTracker(): already connecting to %s\n", x.p.Name)
|
||||||
|
b.connections.Unlock()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b.connections.items = append(b.connections.items, x)
|
||||||
|
b.connections.Unlock()
|
||||||
|
b.connectPeripheral(x.p)
|
||||||
|
|
||||||
|
cancel := func() {
|
||||||
|
b.cancelConnection(x.p)
|
||||||
|
b.connections.Lock()
|
||||||
|
for n, item := range b.connections.items {
|
||||||
|
if item.p.Identifier == x.p.Identifier {
|
||||||
|
b.connections.items = append(b.connections.items[:n], b.connections.items[n+1:]...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b.connections.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
tick := time.NewTicker(time.Second * 60)
|
||||||
|
select {
|
||||||
|
case <-b.connections.close:
|
||||||
|
fmt.Printf("connectTracker(): Closing connection to %s\n", x.p.Name)
|
||||||
|
b.cancelConnection(x.p)
|
||||||
|
case <-tick.C:
|
||||||
|
fmt.Printf("connectTracker(): Connection to %s timed out\n", x.p.Name)
|
||||||
|
cancel()
|
||||||
|
b.events <- ConnectTimeoutEvent{x.p}
|
||||||
|
case state := <-x.state:
|
||||||
|
if state == "cancel" {
|
||||||
|
cancel()
|
||||||
|
}
|
||||||
|
fmt.Printf("connectTracker(): state %s\n", state)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *BLE) Connect(p Peripheral) bool {
|
||||||
|
b.Lock()
|
||||||
|
if !b.ready {
|
||||||
|
b.Unlock()
|
||||||
|
fmt.Printf("--BLE not ready\n")
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
b.Unlock()
|
||||||
|
if p.IsIncomplete() {
|
||||||
|
var ok bool
|
||||||
|
p, ok = b.knownPeripheral(p)
|
||||||
|
if !ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
item := ConnectionListItem{p, make(chan string)}
|
||||||
|
fmt.Printf("BLE.Connect() calling connectTracker\n")
|
||||||
|
return connectTracker(b, item)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Disconnect(p Peripheral) {
|
||||||
|
b := peripheralLookup(p)
|
||||||
|
found := false
|
||||||
|
b.connections.Lock()
|
||||||
|
for i, item := range b.connections.items {
|
||||||
|
if item.p.Identifier == p.Identifier {
|
||||||
|
found = true
|
||||||
|
b.connections.items = append(b.connections.items[:i], b.connections.items[i+1:]...)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b.connections.Unlock()
|
||||||
|
if !found {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
b.cancelConnection(p)
|
||||||
|
}
|
||||||
|
|
||||||
+412
@@ -0,0 +1,412 @@
|
|||||||
|
//go:generate mkdir -p classes
|
||||||
|
//go:generate javac -bootclasspath $ANDROID_HOME/platforms/android-29/android.jar -classpath blessed-full.jar -d classes BlessedConnect.java
|
||||||
|
//go:generate jar cf Ble.jar -C classes .
|
||||||
|
//go:generate rm -rf classes
|
||||||
|
|
||||||
|
package ble
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
"sync"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
|
"gioui.org/app"
|
||||||
|
_ "gioui.org/app/permission/bluetooth"
|
||||||
|
|
||||||
|
"git.wow.st/gmp/ble/gatt"
|
||||||
|
)
|
||||||
|
|
||||||
|
/*
|
||||||
|
#include "jni_android.h"
|
||||||
|
*/
|
||||||
|
import "C"
|
||||||
|
|
||||||
|
// Types required for ble.go
|
||||||
|
|
||||||
|
type bleHandle struct {
|
||||||
|
BlessedConnect C.jobject
|
||||||
|
state int
|
||||||
|
}
|
||||||
|
|
||||||
|
type bleState string
|
||||||
|
|
||||||
|
type Peripheral struct {
|
||||||
|
Name string
|
||||||
|
RSSI int
|
||||||
|
Identifier string
|
||||||
|
peripheral C.jobject
|
||||||
|
}
|
||||||
|
|
||||||
|
type Service struct {
|
||||||
|
UUID string
|
||||||
|
service C.jobject
|
||||||
|
}
|
||||||
|
|
||||||
|
type Characteristic struct {
|
||||||
|
UUID string
|
||||||
|
characteristic C.jobject
|
||||||
|
}
|
||||||
|
|
||||||
|
// Internal global variables
|
||||||
|
|
||||||
|
var (
|
||||||
|
gBLE *BLE // FIXME: move to lookup tables as in ble_darwin.go?
|
||||||
|
|
||||||
|
// FIXME: lifecycle, this may need to fire again? Or can I depend
|
||||||
|
// on my Fragment re-starting? Or call setRetained(true) from the
|
||||||
|
// fragment so we don't have to re-discover our BluetoothGatt and
|
||||||
|
// BluetoothDevice objects?
|
||||||
|
installCompleteOnce sync.Once
|
||||||
|
waitch chan struct{}
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html
|
||||||
|
// FIXME: create a type for these?
|
||||||
|
STATE_OFF int = 10
|
||||||
|
STATE_TURNING_ON = 11
|
||||||
|
STATE_ON = 12
|
||||||
|
STATE_TURNING_OFF = 13
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
waitch = make(chan struct{})
|
||||||
|
}
|
||||||
|
|
||||||
|
func connect() {
|
||||||
|
<-waitch
|
||||||
|
}
|
||||||
|
|
||||||
|
// Functions required by API
|
||||||
|
|
||||||
|
//peripheralLookup returns a pointer to a BLE struct related to the given
|
||||||
|
//Peripheral.
|
||||||
|
func peripheralLookup(p Peripheral) *BLE {
|
||||||
|
return gBLE
|
||||||
|
}
|
||||||
|
|
||||||
|
//newPeripheral creates a new Peripheral struct
|
||||||
|
// FIXME: check what happens with "incomplete" Peripherals that have only
|
||||||
|
// an Identifier set. Do the other functions on Peripherals do something
|
||||||
|
// sensible?
|
||||||
|
func newPeripheral(name, id string, rssi int, peripheral C.jobject) Peripheral {
|
||||||
|
return Peripheral{
|
||||||
|
Name: name,
|
||||||
|
RSSI: rssi,
|
||||||
|
Identifier: id,
|
||||||
|
peripheral: peripheral,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p Peripheral) IsIncomplete() bool {
|
||||||
|
if p.peripheral == 0 {
|
||||||
|
return true
|
||||||
|
} else {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// FIXME: should I call NewGlobalRef() here?
|
||||||
|
func (p Peripheral) Retain() {
|
||||||
|
}
|
||||||
|
|
||||||
|
//stringState returns a string version of the BLE state
|
||||||
|
func (b *BLE) stringState() string {
|
||||||
|
switch b.handle.state {
|
||||||
|
case STATE_OFF:
|
||||||
|
return "powered off"
|
||||||
|
case STATE_TURNING_ON:
|
||||||
|
return "turning on"
|
||||||
|
case STATE_ON:
|
||||||
|
return "powered on"
|
||||||
|
case STATE_TURNING_OFF:
|
||||||
|
return "turning off"
|
||||||
|
default:
|
||||||
|
return "no state"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//readyToScan returns true if the hardware is ready to initiate a scan
|
||||||
|
func (b *BLE) readyToScan() bool {
|
||||||
|
connect()
|
||||||
|
var ret bool
|
||||||
|
runInJVM(func(env *C.JNIEnv) {
|
||||||
|
ret = C.enabled(env, b.handle.BlessedConnect) == C.JNI_TRUE
|
||||||
|
})
|
||||||
|
return ret
|
||||||
|
}
|
||||||
|
|
||||||
|
//scan puts the BLE hardware into scanning mode
|
||||||
|
func (b *BLE) scan() {
|
||||||
|
connect()
|
||||||
|
runInJVM(func(env *C.JNIEnv) {
|
||||||
|
C.scan(env, b.handle.BlessedConnect);
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
//stopScan stops a scan in progress
|
||||||
|
func (b *BLE) stopScan() {
|
||||||
|
connect()
|
||||||
|
runInJVM(func(env *C.JNIEnv) {
|
||||||
|
C.stopScan(env, b.handle.BlessedConnect);
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
//connectPeripheral attempts to connect to a Peripheral
|
||||||
|
func (b *BLE) connectPeripheral(x Peripheral) {
|
||||||
|
runInJVM(func(env *C.JNIEnv) {
|
||||||
|
C.connect(env, b.handle.BlessedConnect, x.peripheral)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
//cancelConnection cancels an in-progress connection attempt
|
||||||
|
func (b *BLE) cancelConnection(p Peripheral) {
|
||||||
|
connect()
|
||||||
|
runInJVM(func(env *C.JNIEnv) {
|
||||||
|
C.disconnect(env, b.handle.BlessedConnect, p.peripheral)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
//knownPeripheral returns a Peripheral that is known to the system without
|
||||||
|
//scanning
|
||||||
|
//Not implemented for Android
|
||||||
|
func (b *BLE) knownPeripheral(p Peripheral) (Peripheral, bool) {
|
||||||
|
return Peripheral{}, false
|
||||||
|
}
|
||||||
|
|
||||||
|
//DiscoverServices asks a Peripheral for its Services
|
||||||
|
func (p Peripheral) DiscoverServices() {
|
||||||
|
//launch a goroutine because this function calls back directly
|
||||||
|
//from the same thread (the underlying Java call is synchronous)
|
||||||
|
go func() {
|
||||||
|
connect()
|
||||||
|
log.Printf("discovering services")
|
||||||
|
runInJVM(func(env *C.JNIEnv) {
|
||||||
|
C.discoverServices(env, gBLE.handle.BlessedConnect, p.peripheral)
|
||||||
|
})
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
//DiscoverCharacteristics asks a Peripheral for the Characteristics related
|
||||||
|
//to a Service
|
||||||
|
func (p Peripheral) DiscoverCharacteristics(serv Service) {
|
||||||
|
//launch a goroutine because this function calls back directly
|
||||||
|
//from the same thread (the underlying Java call is synchronous)
|
||||||
|
go func() {
|
||||||
|
connect()
|
||||||
|
log.Printf("discovering characteristics")
|
||||||
|
runInJVM(func(env *C.JNIEnv) {
|
||||||
|
C.discoverCharacteristics(env, gBLE.handle.BlessedConnect, p.peripheral, serv.service)
|
||||||
|
})
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
//SetNotifyValue subscribes to a characteristic
|
||||||
|
func (p Peripheral) SetNotifyValue(c Characteristic) {
|
||||||
|
runInJVM(func(env *C.JNIEnv) {
|
||||||
|
result := (C.setCharacteristicNotification(env, gBLE.handle.BlessedConnect, p.peripheral, c.characteristic) == C.JNI_TRUE)
|
||||||
|
if (!result) {
|
||||||
|
log.Printf("setCharacteristicNotification: %s failed", c.UUID)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
//NewBLE returns a pointer to a BLE struct after setting up the OS
|
||||||
|
//Bluetooth API.
|
||||||
|
func NewBLE() *BLE {
|
||||||
|
ps := Peripherals{items: make([]PeripheralListItem, 0)}
|
||||||
|
gBLE = &BLE{
|
||||||
|
events: make(chan interface{}),
|
||||||
|
peripherals: ps,
|
||||||
|
}
|
||||||
|
return gBLE
|
||||||
|
}
|
||||||
|
|
||||||
|
//Enable
|
||||||
|
func (b *BLE) Enable(view uintptr) {
|
||||||
|
log.Printf("ble.Enable()")
|
||||||
|
// view == 0 is Gio's detach signal (GioView.onDestroyView sends
|
||||||
|
// ViewEvent{View: 0} when the view is destroyed, e.g. the activity
|
||||||
|
// going away on a recents-wipe). Nothing to register; passing the null
|
||||||
|
// ref on would abort in JNI (GetObjectClass on null). A re-attach
|
||||||
|
// arrives as a fresh event with a live view. Callers that forward the
|
||||||
|
// event unfiltered are protected by this guard.
|
||||||
|
if view == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
setJVM(app.JavaVM())
|
||||||
|
runInJVM(func(env *JNIEnv) {
|
||||||
|
log.Printf("ble.Enable(): inside runInJVM()")
|
||||||
|
C.registerFragment(env, (C.jobject)(unsafe.Pointer(view)))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Go callbacks from Java
|
||||||
|
|
||||||
|
//export Java_st_wow_git_ble_BlessedConnect_installComplete
|
||||||
|
func Java_st_wow_git_ble_BlessedConnect_installComplete(env *C.JNIEnv, class C.jclass, b C.jobject) {
|
||||||
|
log.Printf("installComplete()")
|
||||||
|
if (b == 0) {
|
||||||
|
log.Printf("BlessedConnect object is nil!")
|
||||||
|
}
|
||||||
|
gBLE.handle.BlessedConnect = (C.NewGlobalRef)(env,b)
|
||||||
|
if C.enabled(env, gBLE.handle.BlessedConnect) == C.JNI_TRUE {
|
||||||
|
gBLE.handle.state = STATE_ON
|
||||||
|
gBLE.ready = true
|
||||||
|
gBLE.events <- UpdateStateEvent{State: gBLE.stringState()}
|
||||||
|
}
|
||||||
|
installCompleteOnce.Do(func() {
|
||||||
|
close(waitch)
|
||||||
|
})
|
||||||
|
log.Printf("installComplete() returning")
|
||||||
|
}
|
||||||
|
|
||||||
|
//export Java_st_wow_git_ble_BlessedConnect_updateState
|
||||||
|
func Java_st_wow_git_ble_BlessedConnect_updateState(env *C.JNIEnv, class C.jclass, s C.jint) {
|
||||||
|
log.Printf("UpdateState: %d", s)
|
||||||
|
gBLE.handle.state = (int)(s)
|
||||||
|
if gBLE.handle.state == STATE_ON {
|
||||||
|
gBLE.ready = true
|
||||||
|
}
|
||||||
|
gBLE.events <- UpdateStateEvent{State: gBLE.stringState()}
|
||||||
|
}
|
||||||
|
|
||||||
|
//export goOnScan
|
||||||
|
func goOnScan(cname, cid *C.char, rssi C.int, dev C.jobject) {
|
||||||
|
name := C.GoString(cname);
|
||||||
|
id := C.GoString(cid);
|
||||||
|
if name == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
peripheral := newPeripheral(name, id, (int)(rssi), dev)
|
||||||
|
if ok := gBLE.peripherals.Add(peripheral); ok {
|
||||||
|
gBLE.events <- DiscoverPeripheralEvent{Peripheral: peripheral}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//export goOnConnect
|
||||||
|
func goOnConnect(p C.jobject, cid *C.char) {
|
||||||
|
id := C.GoString(cid)
|
||||||
|
|
||||||
|
peripheral := gBLE.retrievePeripheral(id, p)
|
||||||
|
|
||||||
|
if peripheral.peripheral == 0 {
|
||||||
|
log.Printf("goOnConnect(): peripheral == null")
|
||||||
|
}
|
||||||
|
|
||||||
|
gBLE.connections.UpdateState(peripheral, "connected")
|
||||||
|
gBLE.events <- ConnectEvent{peripheral}
|
||||||
|
log.Printf("Go: goOnConnect returning\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
//export goOnDisconnect
|
||||||
|
func goOnDisconnect(p C.jobject, cid *C.char) {
|
||||||
|
id := C.GoString(cid)
|
||||||
|
|
||||||
|
peripheral := gBLE.retrievePeripheral(id)
|
||||||
|
|
||||||
|
if peripheral.peripheral == 0 {
|
||||||
|
log.Printf("goOnDisconnect(): peripheral == null")
|
||||||
|
}
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
gBLE.connections.UpdateState(peripheral, "cancel")
|
||||||
|
gBLE.events <- DisconnectEvent{peripheral}
|
||||||
|
}()
|
||||||
|
log.Printf("Go: goOnDisconnect returning\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
//export goOnDiscoverService
|
||||||
|
func goOnDiscoverService(cid, cuuid *C.char, serv C.jobject) {
|
||||||
|
id := C.GoString(cid)
|
||||||
|
uuid := C.GoString(cuuid)
|
||||||
|
|
||||||
|
peripheral := gBLE.retrievePeripheral(id)
|
||||||
|
|
||||||
|
service := Service{
|
||||||
|
UUID: uuid,
|
||||||
|
service: serv,
|
||||||
|
}
|
||||||
|
gBLE.events <- DiscoverServiceEvent{
|
||||||
|
Peripheral: peripheral,
|
||||||
|
Gatt: gatt.Service{uuid},
|
||||||
|
Service: service,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//export goOnDiscoverCharacteristic
|
||||||
|
func goOnDiscoverCharacteristic(cid, csuuid *C.char, serv C.jobject, ccuuid *C.char, characteristic C.jobject) {
|
||||||
|
id := C.GoString(cid)
|
||||||
|
suuid := C.GoString(csuuid)
|
||||||
|
cuuid := C.GoString(ccuuid)
|
||||||
|
log.Printf("goOnDiscoverCharacteristic: %s", cuuid)
|
||||||
|
|
||||||
|
peripheral := gBLE.retrievePeripheral(id)
|
||||||
|
|
||||||
|
service := Service{
|
||||||
|
UUID: suuid,
|
||||||
|
service: serv,
|
||||||
|
}
|
||||||
|
|
||||||
|
ch := Characteristic{
|
||||||
|
UUID: cuuid,
|
||||||
|
characteristic: characteristic,
|
||||||
|
}
|
||||||
|
|
||||||
|
gBLE.events <- DiscoverCharacteristicEvent{
|
||||||
|
Peripheral: peripheral,
|
||||||
|
Service: service,
|
||||||
|
Characteristic: ch,
|
||||||
|
Gatt: gatt.Characteristic{cuuid},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//export goOnCharacteristicChanged
|
||||||
|
func goOnCharacteristicChanged(cid, ccuuid *C.char, characteristic C.jobject, cvalue *C.char, length C.jint) {
|
||||||
|
id := C.GoString(cid)
|
||||||
|
cuuid := C.GoString(ccuuid)
|
||||||
|
|
||||||
|
peripheral := gBLE.retrievePeripheral(id)
|
||||||
|
|
||||||
|
ch := Characteristic{
|
||||||
|
UUID: cuuid,
|
||||||
|
characteristic: characteristic,
|
||||||
|
}
|
||||||
|
|
||||||
|
gBLE.events <- UpdateValueEvent{
|
||||||
|
Peripheral: peripheral,
|
||||||
|
Characteristic: ch,
|
||||||
|
Data: C.GoBytes(unsafe.Pointer(cvalue), length),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// internal convenience functions
|
||||||
|
|
||||||
|
func (b *BLE) retrievePeripheral(id string, devs ...C.jobject) Peripheral {
|
||||||
|
var dev C.jobject
|
||||||
|
if len(devs) > 0 {
|
||||||
|
dev = devs[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
found := false
|
||||||
|
var peripheral Peripheral
|
||||||
|
|
||||||
|
gBLE.peripherals.Lock()
|
||||||
|
for i, item := range gBLE.peripherals.items {
|
||||||
|
if item.p.Identifier == id {
|
||||||
|
peripheral = item.p
|
||||||
|
if dev != 0 {
|
||||||
|
peripheral.peripheral = dev
|
||||||
|
}
|
||||||
|
found = true
|
||||||
|
gBLE.peripherals.items[i].p = peripheral
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
gBLE.peripherals.Unlock()
|
||||||
|
|
||||||
|
if !found {
|
||||||
|
log.Printf("Go: peripheral not found!")
|
||||||
|
}
|
||||||
|
return peripheral
|
||||||
|
}
|
||||||
+195
-300
@@ -3,10 +3,8 @@ package ble
|
|||||||
import "C"
|
import "C"
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/binary"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"runtime"
|
"runtime"
|
||||||
"sync"
|
|
||||||
"time"
|
"time"
|
||||||
"unsafe"
|
"unsafe"
|
||||||
|
|
||||||
@@ -14,26 +12,15 @@ import (
|
|||||||
"git.wow.st/gmp/ble/ns"
|
"git.wow.st/gmp/ble/ns"
|
||||||
)
|
)
|
||||||
|
|
||||||
type BLE struct {
|
// Types required for ble.go
|
||||||
state ns.CBManagerState
|
|
||||||
events chan interface{}
|
type bleState ns.CBManagerState
|
||||||
peripherals Peripherals
|
|
||||||
|
type bleHandle struct {
|
||||||
cd *ns.CBDelegate
|
cd *ns.CBDelegate
|
||||||
cm *ns.CBCentralManager
|
cm *ns.CBCentralManager
|
||||||
|
|
||||||
ready, wantScan bool
|
|
||||||
sync.Mutex
|
|
||||||
|
|
||||||
connections Connections
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var cdLookup map[unsafe.Pointer]*BLE
|
|
||||||
var pdLookup map[unsafe.Pointer]*BLE
|
|
||||||
var pcache map[unsafe.Pointer]*Peripheral
|
|
||||||
|
|
||||||
|
|
||||||
type State string
|
|
||||||
|
|
||||||
type Peripheral struct {
|
type Peripheral struct {
|
||||||
Name string
|
Name string
|
||||||
RSSI int
|
RSSI int
|
||||||
@@ -42,15 +29,24 @@ type Peripheral struct {
|
|||||||
p *ns.CBPeripheral
|
p *ns.CBPeripheral
|
||||||
}
|
}
|
||||||
|
|
||||||
func peripheralName(p *ns.CBPeripheral) string {
|
type Service *ns.CBService
|
||||||
var ret string
|
type Characteristic *ns.CBCharacteristic
|
||||||
nsname := p.Name()
|
|
||||||
if nsname.Ptr() != nil {
|
// Internal global variables
|
||||||
ret = nsname.String()
|
|
||||||
}
|
var cdLookup map[unsafe.Pointer]*BLE
|
||||||
return ret
|
var pdLookup map[unsafe.Pointer]*BLE
|
||||||
|
var pcache map[unsafe.Pointer]*Peripheral
|
||||||
|
|
||||||
|
// Functions required by API
|
||||||
|
|
||||||
|
//peripheralLookup returns a pointer to a BLE struct related to the given
|
||||||
|
//Peripheral.
|
||||||
|
func peripheralLookup(p Peripheral) *BLE {
|
||||||
|
return pdLookup[p.p.Ptr()]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//newPeripheral creates a new Peripheral struct
|
||||||
func newPeripheral(x *ns.CBPeripheral) Peripheral {
|
func newPeripheral(x *ns.CBPeripheral) Peripheral {
|
||||||
if pcache == nil {
|
if pcache == nil {
|
||||||
pcache = make(map[unsafe.Pointer]*Peripheral)
|
pcache = make(map[unsafe.Pointer]*Peripheral)
|
||||||
@@ -68,233 +64,151 @@ func newPeripheral(x *ns.CBPeripheral) Peripheral {
|
|||||||
return ret
|
return ret
|
||||||
}
|
}
|
||||||
|
|
||||||
type PeripheralListItem struct {
|
func (p Peripheral) IsIncomplete() bool {
|
||||||
p Peripheral
|
return p.p == nil
|
||||||
seen time.Time
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type Peripherals struct {
|
func (x Peripheral) Retain() {
|
||||||
items []PeripheralListItem
|
//NOTE: ns.ObjectAtIndex() calls SetFinalizer for us, which will be a problem
|
||||||
sync.Mutex
|
//later when we call GC(), so we always first clear the finalizer before
|
||||||
}
|
//setting a new one.
|
||||||
|
runtime.SetFinalizer(x.p, nil)
|
||||||
type ConnectionListItem struct {
|
|
||||||
p Peripheral
|
|
||||||
state chan string
|
|
||||||
}
|
|
||||||
|
|
||||||
type Connections struct {
|
|
||||||
items []ConnectionListItem
|
|
||||||
close chan struct{}
|
|
||||||
sync.Mutex
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Connections) UpdateState(p Peripheral, s string) {
|
|
||||||
var ch chan string
|
|
||||||
c.Lock()
|
|
||||||
for _, item := range c.items {
|
|
||||||
if p.Identifier == item.p.Identifier {
|
|
||||||
ch = item.state
|
|
||||||
}
|
|
||||||
}
|
|
||||||
c.Unlock()
|
|
||||||
ch <- s
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ps *Peripherals) Add(x Peripheral) bool {
|
|
||||||
ps.Lock()
|
|
||||||
defer ps.Unlock()
|
|
||||||
found := false
|
|
||||||
for n, item := range ps.items {
|
|
||||||
if item.p.Identifier == x.Identifier {
|
|
||||||
item.p = x
|
|
||||||
item.seen = time.Now()
|
|
||||||
ps.items[n] = item
|
|
||||||
found = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if found {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
//take ownership of this Objective-C object
|
|
||||||
x.p.Retain()
|
x.p.Retain()
|
||||||
x.p.GC()
|
x.p.GC()
|
||||||
item := PeripheralListItem{p: x, seen: time.Now()}
|
|
||||||
ps.items = append(ps.items, item)
|
|
||||||
return true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cs *Connections) Add(x ConnectionListItem) bool {
|
//stringState returns a string version of the BLE state
|
||||||
cs.Lock()
|
func (b *BLE) stringState() string {
|
||||||
defer cs.Unlock()
|
x := b.state
|
||||||
found := false
|
switch (ns.NSInteger)(x) {
|
||||||
for _, item := range cs.items {
|
case ns.CBManagerStateResetting:
|
||||||
if item.p.Identifier == x.p.Identifier {
|
|
||||||
// are we allowed to have multiple connections to the same peripheral?
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if found {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
cs.items = append(cs.items, x)
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
type UpdateStateEvent struct {
|
|
||||||
State string
|
|
||||||
}
|
|
||||||
|
|
||||||
type DiscoverPeripheralEvent struct {
|
|
||||||
Peripheral Peripheral
|
|
||||||
}
|
|
||||||
|
|
||||||
type DiscoverServiceEvent struct {
|
|
||||||
Peripheral Peripheral
|
|
||||||
Gatt gatt.Service
|
|
||||||
Service *ns.CBService
|
|
||||||
}
|
|
||||||
|
|
||||||
type DiscoverCharacteristicEvent struct {
|
|
||||||
Peripheral Peripheral
|
|
||||||
Gatt gatt.Characteristic
|
|
||||||
Service *ns.CBService
|
|
||||||
Characteristic *ns.CBCharacteristic
|
|
||||||
}
|
|
||||||
|
|
||||||
type UpdateValueEvent struct {
|
|
||||||
Data []byte
|
|
||||||
}
|
|
||||||
|
|
||||||
type ConnectEvent struct {
|
|
||||||
Peripheral Peripheral
|
|
||||||
}
|
|
||||||
type ConnectTimeoutEvent struct {
|
|
||||||
Peripheral Peripheral
|
|
||||||
}
|
|
||||||
|
|
||||||
type UpdageValueEvent struct {
|
|
||||||
Peripheral Peripheral
|
|
||||||
Characteristic gatt.Characteristic
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *BLE) Events() chan interface{} {
|
|
||||||
return b.events
|
|
||||||
}
|
|
||||||
|
|
||||||
func stringState(x ns.CBManagerState) string {
|
|
||||||
switch x {
|
|
||||||
case (ns.CBManagerState)(ns.CBManagerStateResetting):
|
|
||||||
return "resetting"
|
return "resetting"
|
||||||
case (ns.CBManagerState)(ns.CBManagerStateUnsupported):
|
case ns.CBManagerStateUnsupported:
|
||||||
return "unsupported"
|
return "unsupported"
|
||||||
case (ns.CBManagerState)(ns.CBManagerStateUnauthorized):
|
case ns.CBManagerStateUnauthorized:
|
||||||
return "unauthorized"
|
return "unauthorized"
|
||||||
case (ns.CBManagerState)(ns.CBManagerStatePoweredOff):
|
case ns.CBManagerStatePoweredOff:
|
||||||
return "powered off"
|
return "powered off"
|
||||||
case (ns.CBManagerState)(ns.CBManagerStatePoweredOn):
|
case ns.CBManagerStatePoweredOn:
|
||||||
return "powered on"
|
return "powered on"
|
||||||
case (ns.CBManagerState)(ns.CBManagerStateUnknown):
|
case ns.CBManagerStateUnknown:
|
||||||
return "unknown"
|
return "unknown"
|
||||||
default:
|
default:
|
||||||
return "no state"
|
return "no state"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *BLE) State() string {
|
//readyToScan returns true if the hardware is ready to initiate a scan
|
||||||
b.Lock()
|
func (b *BLE) readyToScan() bool {
|
||||||
defer b.Unlock()
|
return b.state == (bleState)(ns.CBManagerStatePoweredOn)
|
||||||
return stringState(b.state)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *BLE) setState(x ns.CBManagerState) {
|
//scan puts the BLE hardware into scanning mode
|
||||||
b.Lock()
|
func (b *BLE) scan() {
|
||||||
defer b.Unlock()
|
b.handle.cm.ScanForPeripheralsWithServices(nil, nil)
|
||||||
b.state = x
|
|
||||||
if b.ready && b.wantScan {
|
|
||||||
fmt.Printf("Go: Scanning\n")
|
|
||||||
b.cm.ScanForPeripheralsWithServices(nil, nil)
|
|
||||||
b.wantScan = false
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *BLE) Scan() {
|
//stopScan stops a scan in progress
|
||||||
b.Lock()
|
func (b *BLE) stopScan() {
|
||||||
defer b.Unlock()
|
b.handle.cm.StopScan()
|
||||||
if b.state != (ns.CBManagerState)(ns.CBManagerStatePoweredOn) {
|
|
||||||
b.wantScan = true
|
|
||||||
} else {
|
|
||||||
fmt.Printf("Go: Scanning\n")
|
|
||||||
b.cm.ScanForPeripheralsWithServices(nil, nil)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *BLE) StopScan() {
|
|
||||||
b.Lock()
|
//connectPeripheral attempts to connect to a Peripheral
|
||||||
if !b.ready {
|
func (b *BLE) connectPeripheral(x Peripheral) {
|
||||||
b.Unlock()
|
fmt.Printf("BLE.Connect(): calling cm.ConnectPeripheral(%p)\n", x.p.Ptr())
|
||||||
return
|
b.handle.cm.ConnectPeripheral(x.p, nil)
|
||||||
}
|
|
||||||
b.Unlock()
|
|
||||||
fmt.Printf("Go: stopping scan\n")
|
|
||||||
b.cm.StopScan()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func connectTracker(b *BLE, x ConnectionListItem) {
|
//cancelConnection cancels an in-progress connection attempt
|
||||||
fmt.Printf("connectTracker(): %s\n", x.p.Name)
|
func (b *BLE) cancelConnection(p Peripheral) {
|
||||||
tick := time.NewTicker(time.Second * 5)
|
b.handle.cm.CancelPeripheralConnection(p.p)
|
||||||
select {
|
|
||||||
case <-b.connections.close:
|
|
||||||
fmt.Printf("Closing connection to %s\n", x.p.Name)
|
|
||||||
b.cm.CancelPeripheralConnection(x.p.p)
|
|
||||||
case <-tick.C:
|
|
||||||
fmt.Printf("Connection to %s timed out\n", x.p.Name)
|
|
||||||
b.cm.CancelPeripheralConnection(x.p.p)
|
|
||||||
b.connections.Lock()
|
|
||||||
for n, item := range b.connections.items {
|
|
||||||
if item.p.Identifier == x.p.Identifier {
|
|
||||||
b.connections.items = append(b.connections.items[:n], b.connections.items[n+1:]...)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
b.connections.Unlock()
|
|
||||||
b.events <- ConnectTimeoutEvent{x.p}
|
|
||||||
case state := <-x.state:
|
|
||||||
fmt.Printf("connectTracker: state\n")
|
|
||||||
if state == "connected" {
|
|
||||||
fmt.Printf("--connected")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *BLE) Connect(p Peripheral) {
|
//knownPeripheral returns a Peripheral that is known to the system without
|
||||||
b.Lock()
|
//scanning
|
||||||
if !b.ready {
|
func (b *BLE) knownPeripheral(p Peripheral) (Peripheral, bool) {
|
||||||
b.Unlock()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
b.Unlock()
|
|
||||||
if p.p == nil {
|
|
||||||
fmt.Printf("RetrievePeripheralsWithIdentifiers\n")
|
fmt.Printf("RetrievePeripheralsWithIdentifiers\n")
|
||||||
ps := b.cm.RetrievePeripheralsWithIdentifiers(ns.NSArrayWithObjects(ns.NSUUIDAlloc().InitWithUUIDString(ns.NSStringWithGoString(p.Identifier))))
|
ps := b.handle.cm.RetrievePeripheralsWithIdentifiers(ns.NSArrayWithObjects(ns.NSUUIDAlloc().InitWithUUIDString(ns.NSStringWithGoString(p.Identifier))))
|
||||||
if x := (int)(ps.Count()); x > 0 {
|
if x := (int)(ps.Count()); x > 0 {
|
||||||
fmt.Printf("--found %d\n", x)
|
fmt.Printf("--found %d\n", x)
|
||||||
p.p = ps.ObjectAtIndex(0).CBPeripheral()
|
cbp := ps.ObjectAtIndex(0).CBPeripheral()
|
||||||
|
return newPeripheral(cbp), true
|
||||||
} else {
|
} else {
|
||||||
fmt.Printf("--none found\n")
|
fmt.Printf("--none found\n")
|
||||||
return
|
return p, false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
item := ConnectionListItem{p, make(chan string)}
|
|
||||||
b.connections.Add(item)
|
|
||||||
go connectTracker(b, item)
|
|
||||||
//time.Sleep(time.Second/10)
|
|
||||||
fmt.Printf("BLE.Connect(): calling cm.ConnectPeripheral(%p)\n", p.p.Ptr())
|
|
||||||
b.cm.ConnectPeripheral(p.p, nil)
|
|
||||||
fmt.Printf("BLE.Connect() returned\n")
|
|
||||||
}
|
|
||||||
|
|
||||||
func updateState(c *ns.CBCentralManager) {
|
//DiscoverServices asks a Peripheral for its Services
|
||||||
|
func (x Peripheral) DiscoverServices() {
|
||||||
|
fmt.Printf("Discovering services on %s\n", x.Name)
|
||||||
|
|
||||||
|
// discover all services on this device
|
||||||
|
x.p.DiscoverServices(nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
//DiscoverCharacteristics asks a Peripheral for the Characteristics related
|
||||||
|
//to a Service
|
||||||
|
func (p Peripheral) DiscoverCharacteristics(serv Service) {
|
||||||
|
p.p.DiscoverCharacteristics(nil, serv)
|
||||||
|
}
|
||||||
|
|
||||||
|
//SetNotifyValue subscribes to a characteristic
|
||||||
|
func (p Peripheral) SetNotifyValue(c Characteristic) {
|
||||||
|
p.p.SetNotifyValue((ns.BOOL)(true), c)
|
||||||
|
}
|
||||||
|
|
||||||
|
//NewBLE returns a pointer to a BLE struct after setting up the OS
|
||||||
|
//Bluetooth API.
|
||||||
|
func NewBLE() *BLE {
|
||||||
|
ps := Peripherals{items: make([]PeripheralListItem, 0)}
|
||||||
|
ble := &BLE{events: make(chan interface{}), peripherals: ps}
|
||||||
|
|
||||||
|
queue := ns.DispatchQueueCreate(ns.CharWithGoString("go_hrm_queue"), nil)
|
||||||
|
|
||||||
|
cd := ns.CBDelegateAlloc()
|
||||||
|
|
||||||
|
cd.CentralManagerDidUpdateStateCallback(didUpdateState)
|
||||||
|
cd.CentralManagerDidDiscoverPeripheralCallback(didDiscoverPeripheral)
|
||||||
|
cd.CentralManagerDidConnectPeripheralCallback(didConnectPeripheral)
|
||||||
|
cd.CentralManagerDidDisconnectPeripheralCallback(didDisconnectPeripheral)
|
||||||
|
cd.PeripheralDidDiscoverServicesCallback(didDiscoverServices)
|
||||||
|
cd.PeripheralDidDiscoverCharacteristicsForServiceCallback(didDiscoverCharacteristics)
|
||||||
|
cd.PeripheralDidUpdateValueForCharacteristicCallback(didUpdateValue)
|
||||||
|
|
||||||
|
|
||||||
|
ble.handle.cd = cd
|
||||||
|
if cdLookup == nil {
|
||||||
|
cdLookup = make(map[unsafe.Pointer]*BLE, 0)
|
||||||
|
}
|
||||||
|
if pdLookup == nil {
|
||||||
|
pdLookup = make(map[unsafe.Pointer]*BLE, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
// We defined our own queue because this won't work on the main queue.
|
||||||
|
ble.handle.cm = ns.CBCentralManagerAlloc().InitWithDelegateQueue(cd, queue)
|
||||||
|
cdLookup[ble.handle.cm.Ptr()] = ble
|
||||||
|
|
||||||
|
// For debugging purposes, run GC every second to make sure things are
|
||||||
|
// not over-released.
|
||||||
|
go func() {
|
||||||
|
for {
|
||||||
|
runtime.GC()
|
||||||
|
time.Sleep(time.Second * 30)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
return ble
|
||||||
|
}
|
||||||
|
|
||||||
|
//Enable is not required for Darwin.
|
||||||
|
func (b *BLE) Enable(v uintptr) {
|
||||||
|
}
|
||||||
|
|
||||||
|
// Core Bluetooth callback functions
|
||||||
|
|
||||||
|
func didUpdateState(d ns.CBDelegate, c *ns.CBCentralManager) {
|
||||||
|
fmt.Print("didUpdateState")
|
||||||
b := cdLookup[c.Ptr()]
|
b := cdLookup[c.Ptr()]
|
||||||
st := c.CBManager.State()
|
st := c.CBManager.State()
|
||||||
if st == (ns.CBManagerState)(ns.CBManagerStatePoweredOn) {
|
if st == (ns.CBManagerState)(ns.CBManagerStatePoweredOn) {
|
||||||
@@ -303,37 +217,43 @@ func updateState(c *ns.CBCentralManager) {
|
|||||||
} else {
|
} else {
|
||||||
if b.ready {
|
if b.ready {
|
||||||
close(b.connections.close)
|
close(b.connections.close)
|
||||||
|
b.connections.Lock()
|
||||||
for _, item := range b.connections.items {
|
for _, item := range b.connections.items {
|
||||||
fmt.Printf("Closing connection to %s\n", item.p.Name)
|
fmt.Printf("Closing connection to %s\n", item.p.Name)
|
||||||
b.cm.CancelPeripheralConnection(item.p.p)
|
b.handle.cm.CancelPeripheralConnection(item.p.p)
|
||||||
}
|
}
|
||||||
b.connections.items = b.connections.items[:0]
|
b.connections.items = b.connections.items[:0]
|
||||||
|
b.connections.Unlock()
|
||||||
b.ready = false
|
b.ready = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
b.setState(st)
|
b.setState(st)
|
||||||
b.events <- UpdateStateEvent{State: stringState(st)}
|
b.events <- UpdateStateEvent{State: b.stringState()}
|
||||||
}
|
}
|
||||||
|
|
||||||
func discoverPeripheral(c *ns.CBCentralManager, p *ns.CBPeripheral, d *ns.NSDictionary, rssi *ns.NSNumber) {
|
func didDiscoverPeripheral(d_ ns.CBDelegate, c *ns.CBCentralManager, p *ns.CBPeripheral, d *ns.NSDictionary, rssi *ns.NSNumber) {
|
||||||
b := cdLookup[c.Ptr()]
|
b := cdLookup[c.Ptr()]
|
||||||
peripheral := newPeripheral(p)
|
peripheral := newPeripheral(p)
|
||||||
peripheral.RSSI = (int)(rssi.IntValue())
|
peripheral.RSSI = (int)(rssi.IntValue())
|
||||||
|
_didDiscoverPeripheral(b, peripheral)
|
||||||
|
}
|
||||||
|
|
||||||
|
func _didDiscoverPeripheral(b *BLE, peripheral Peripheral) {
|
||||||
if peripheral.Name == "" {
|
if peripheral.Name == "" {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if ok := b.peripherals.Add(peripheral); ok {
|
if ok := b.peripherals.Add(peripheral); ok {
|
||||||
pdLookup[p.Ptr()] = b
|
pdLookup[peripheral.p.Ptr()] = b
|
||||||
b.events <- DiscoverPeripheralEvent{Peripheral: peripheral}
|
b.events <- DiscoverPeripheralEvent{Peripheral: peripheral}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func connectPeripheral(c *ns.CBCentralManager, p *ns.CBPeripheral) {
|
func didConnectPeripheral(d ns.CBDelegate, c *ns.CBCentralManager, p *ns.CBPeripheral) {
|
||||||
fmt.Printf("Did connect peripheral\n")
|
fmt.Printf("Did connect peripheral\n")
|
||||||
b := cdLookup[c.Ptr()]
|
b := cdLookup[c.Ptr()]
|
||||||
|
|
||||||
// set ourselves up as a peripheral delegate
|
// set ourselves up as a peripheral delegate
|
||||||
p.SetDelegate(b.cd)
|
p.SetDelegate(b.handle.cd)
|
||||||
|
|
||||||
uuidstring := p.Identifier().UUIDString().String()
|
uuidstring := p.Identifier().UUIDString().String()
|
||||||
peripheral := newPeripheral(p)
|
peripheral := newPeripheral(p)
|
||||||
@@ -358,19 +278,41 @@ func connectPeripheral(c *ns.CBCentralManager, p *ns.CBPeripheral) {
|
|||||||
|
|
||||||
b.connections.UpdateState(peripheral, "connected")
|
b.connections.UpdateState(peripheral, "connected")
|
||||||
b.events <- ConnectEvent{peripheral}
|
b.events <- ConnectEvent{peripheral}
|
||||||
fmt.Printf("Go: connectPeripheral returning\n")
|
fmt.Printf("Go: didConnectPeripheral returning\n")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (x Peripheral) DiscoverServices() {
|
func didDisconnectPeripheral(d ns.CBDelegate, c *ns.CBCentralManager, p *ns.CBPeripheral, e *ns.NSError) {
|
||||||
fmt.Printf("Discovering services on %s\n", x.Name)
|
fmt.Printf("Did disconnect peripheral\n");
|
||||||
p := x.p
|
b := cdLookup[c.Ptr()]
|
||||||
|
|
||||||
// discover all services on this device
|
uuidstring := p.Identifier().UUIDString().String()
|
||||||
|
peripheral := newPeripheral(p)
|
||||||
|
found := false
|
||||||
|
|
||||||
p.DiscoverServices(nil)
|
b.peripherals.Lock()
|
||||||
|
for _, item := range b.peripherals.items {
|
||||||
|
if item.p.Identifier == uuidstring {
|
||||||
|
peripheral = item.p
|
||||||
|
found = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b.peripherals.Unlock()
|
||||||
|
|
||||||
|
if !found {
|
||||||
|
peripheral.Name = peripheralName(p)
|
||||||
|
if ok := b.peripherals.Add(peripheral); ok {
|
||||||
|
pdLookup[p.Ptr()] = b
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func discoverServices(p *ns.CBPeripheral, e *ns.NSError) {
|
go func() {
|
||||||
|
b.connections.UpdateState(peripheral, "cancelled")
|
||||||
|
b.events <- DisconnectEvent{peripheral}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
func didDiscoverServices(d ns.CBDelegate, p *ns.CBPeripheral, e *ns.NSError) {
|
||||||
b := pdLookup[p.Ptr()]
|
b := pdLookup[p.Ptr()]
|
||||||
fmt.Printf("Did discover services\n")
|
fmt.Printf("Did discover services\n")
|
||||||
p.Services().ObjectEnumerator().ForIn(func(o *ns.Id) bool {
|
p.Services().ObjectEnumerator().ForIn(func(o *ns.Id) bool {
|
||||||
@@ -383,27 +325,10 @@ func discoverServices(p *ns.CBPeripheral, e *ns.NSError) {
|
|||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
})
|
})
|
||||||
fmt.Printf("Go: discoverServices returning\n")
|
fmt.Printf("Go: didDiscoverServices returning\n")
|
||||||
}
|
}
|
||||||
|
|
||||||
func hr(d *ns.NSData) int {
|
func didDiscoverCharacteristics(d ns.CBDelegate, p *ns.CBPeripheral, s *ns.CBService, e *ns.NSError) {
|
||||||
if l := int(d.Length()); l < 4 {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
x := C.GoBytes(d.Bytes(), 4)
|
|
||||||
flags := x[0]
|
|
||||||
if flags&0x80 != 0 { // uint16 format
|
|
||||||
return int(binary.BigEndian.Uint16(x[1:2]))
|
|
||||||
} else {
|
|
||||||
return int(x[1])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p Peripheral) DiscoverCharacteristics(serv *ns.CBService) {
|
|
||||||
p.p.DiscoverCharacteristics(nil, serv)
|
|
||||||
}
|
|
||||||
|
|
||||||
func discoverCharacteristics(p *ns.CBPeripheral, s *ns.CBService, e *ns.NSError) {
|
|
||||||
b := pdLookup[p.Ptr()]
|
b := pdLookup[p.Ptr()]
|
||||||
fmt.Printf("Did discover characteristics\n")
|
fmt.Printf("Did discover characteristics\n")
|
||||||
s.Characteristics().ObjectEnumerator().ForIn(func(o *ns.Id) bool {
|
s.Characteristics().ObjectEnumerator().ForIn(func(o *ns.Id) bool {
|
||||||
@@ -418,68 +343,38 @@ func discoverCharacteristics(p *ns.CBPeripheral, s *ns.CBService, e *ns.NSError)
|
|||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
})
|
})
|
||||||
fmt.Printf("Go: discoverCharacteristics returning\n")
|
fmt.Printf("Go: didDiscoverCharacteristics returning\n")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p Peripheral) SetNotifyValue(c *ns.CBCharacteristic) {
|
func didUpdateValue(d ns.CBDelegate, p *ns.CBPeripheral, chr *ns.CBCharacteristic, e *ns.NSError) {
|
||||||
p.p.SetNotifyValue(1, c)
|
|
||||||
}
|
|
||||||
|
|
||||||
func updateValue(p *ns.CBPeripheral, chr *ns.CBCharacteristic, e *ns.NSError) {
|
|
||||||
b := pdLookup[p.Ptr()]
|
b := pdLookup[p.Ptr()]
|
||||||
v := chr.Value()
|
v := chr.Value()
|
||||||
b.events <-UpdateValueEvent{
|
b.events <-UpdateValueEvent{
|
||||||
|
Peripheral: newPeripheral(p),
|
||||||
|
Characteristic: chr,
|
||||||
Data: C.GoBytes(v.Bytes(), (C.int)(v.Length())),
|
Data: C.GoBytes(v.Bytes(), (C.int)(v.Length())),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
// internal convenience functions
|
||||||
hrm_uuid *ns.CBUUID
|
|
||||||
hrv_uuid *ns.CBUUID
|
|
||||||
info_uuid *ns.CBUUID
|
|
||||||
|
|
||||||
gble *BLE
|
func peripheralName(p *ns.CBPeripheral) string {
|
||||||
)
|
var ret string
|
||||||
|
nsname := p.Name()
|
||||||
func NewBLE() *BLE {
|
if nsname.Ptr() != nil {
|
||||||
ps := Peripherals{items: make([]PeripheralListItem, 0)}
|
ret = nsname.String()
|
||||||
ble := &BLE{events: make(chan interface{}), peripherals: ps}
|
|
||||||
gble = ble
|
|
||||||
|
|
||||||
queue := ns.DispatchQueueCreate(ns.CharWithGoString("go_hrm_queue"), nil)
|
|
||||||
|
|
||||||
cd := ns.CBDelegateAlloc()
|
|
||||||
|
|
||||||
cd.CentralManagerDidUpdateStateCallback(updateState)
|
|
||||||
cd.CentralManagerDidDiscoverPeripheralCallback(discoverPeripheral)
|
|
||||||
cd.CentralManagerDidConnectPeripheralCallback(connectPeripheral)
|
|
||||||
cd.PeripheralDidDiscoverServicesCallback(discoverServices)
|
|
||||||
cd.PeripheralDidDiscoverCharacteristicsForServiceCallback(discoverCharacteristics)
|
|
||||||
cd.PeripheralDidUpdateValueForCharacteristicCallback(updateValue)
|
|
||||||
|
|
||||||
hrm_uuid = ns.CBUUIDWithGoString("180D")
|
|
||||||
hrv_uuid = ns.CBUUIDWithGoString("2A37")
|
|
||||||
info_uuid = ns.CBUUIDWithGoString("180A")
|
|
||||||
|
|
||||||
ble.cd = cd
|
|
||||||
if cdLookup == nil {
|
|
||||||
cdLookup = make(map[unsafe.Pointer]*BLE, 0)
|
|
||||||
}
|
}
|
||||||
if pdLookup == nil {
|
return ret
|
||||||
pdLookup = make(map[unsafe.Pointer]*BLE, 0)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// We defined our own queue because this won't work on the main queue.
|
func (b *BLE) setState(x ns.CBManagerState) {
|
||||||
ble.cm = ns.CBCentralManagerAlloc().InitWithDelegateQueue(cd, queue)
|
b.Lock()
|
||||||
cdLookup[ble.cm.Ptr()] = ble
|
defer b.Unlock()
|
||||||
|
b.state = (bleState)(x)
|
||||||
|
if b.ready && b.wantScan {
|
||||||
|
fmt.Printf("Go: Scanning\n")
|
||||||
|
b.scan()
|
||||||
|
b.wantScan = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// For debugging purposes, run GC every second to make sure things are
|
|
||||||
// not over-released.
|
|
||||||
go func() {
|
|
||||||
for {
|
|
||||||
runtime.GC()
|
|
||||||
time.Sleep(time.Second * 30)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
return ble
|
|
||||||
}
|
|
||||||
|
|||||||
Binary file not shown.
@@ -0,0 +1,14 @@
|
|||||||
|
//go:generate rm -rf blessed-android timber
|
||||||
|
//go:generate git clone https://github.com/weliem/blessed-android
|
||||||
|
//go:generate git -C blessed-android checkout be74941512ba08e33eb1fd6d0030ad4a4d332365
|
||||||
|
//go:generate blessed-android/gradlew -x lint -x lintVitalRelease -x test -x check -p blessed-android build
|
||||||
|
//go:generate mv blessed-android/blessed/build/intermediates/full_jar/release/createFullJarRelease/full.jar ../blessed-full.jar
|
||||||
|
//go:generate rm -rf blessed-android
|
||||||
|
|
||||||
|
//go:generate git clone https://github.com/JakeWharton/timber.git
|
||||||
|
//go:generate git -C timber checkout 4.7.1
|
||||||
|
//go:generate timber/gradlew -x lint -x lintVitalRelease -x test -x check -p timber build
|
||||||
|
//go:generate mv timber/timber/build/intermediates/intermediate-jars/release/classes.jar ../timber.jar
|
||||||
|
//go:generate rm -rf timber
|
||||||
|
|
||||||
|
package depjars
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package gatt
|
||||||
|
|
||||||
|
func (s Service) IsHRM() bool {
|
||||||
|
return len(s.UUID) >= 8 && s.UUID[:8] == "0000180d"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c Characteristic) IsHRV() bool {
|
||||||
|
return len(c.UUID) >= 0 && c.UUID[:8] == "00002a37"
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package gatt
|
||||||
|
|
||||||
|
func (s Service) IsHRM() bool {
|
||||||
|
return s.UUID == "180D"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c Characteristic) IsHRV() bool {
|
||||||
|
return c.UUID == "2A37"
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
module git.wow.st/gmp/ble
|
||||||
|
|
||||||
|
go 1.13
|
||||||
|
|
||||||
|
require gioui.org v0.0.0-20200829162755-829ee4559c5a
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
|
||||||
|
gioui.org v0.0.0-20191126175243-2ca2e5462f16 h1:p31rtmKm51xpj2QtqGNlljAyHEP1oStU8MDRl2Dv7Gs=
|
||||||
|
gioui.org v0.0.0-20191126175243-2ca2e5462f16/go.mod h1:KqFFi2Dq5gYA3FJ0sDOt8OBXoMsuxMtE8v2f0JExXAY=
|
||||||
|
gioui.org v0.0.0-20200612151431-2dc19a36959c h1:sGUKyRMv2bbfbsRyG8ghOI12l+WCGta+PivmznjuLgo=
|
||||||
|
gioui.org v0.0.0-20200612151431-2dc19a36959c/go.mod h1:AHI9rFr6AEEHCb8EPVtb/p5M+NMJRKH58IOp8O3Je04=
|
||||||
|
gioui.org v0.0.0-20200619121558-88ced59dad93 h1:Llh4Tigdbu++FrRXL/KzqDHnH2Q5LPmAEk0djh6NLwk=
|
||||||
|
gioui.org v0.0.0-20200619121558-88ced59dad93/go.mod h1:jiUwifN9cRl/zmco43aAqh0aV+s9GbhG13KcD+gEpkU=
|
||||||
|
gioui.org v0.0.0-20200829162755-829ee4559c5a h1:mciXRGzQwU0TbgCILZzl6L1nYIWU31lDGIb+8RYige8=
|
||||||
|
gioui.org v0.0.0-20200829162755-829ee4559c5a/go.mod h1:Y+uS7hHMvku1Q+ooaoq6fYD5B2LGoT8JtFgvmYmRzTw=
|
||||||
|
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
|
||||||
|
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
|
||||||
|
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||||
|
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||||
|
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||||
|
golang.org/x/exp v0.0.0-20191002040644-a1355ae1e2c3/go.mod h1:NOZ3BPKG0ec/BKJQgnvsSFpcKLM5xXVWnvZS97DWHgE=
|
||||||
|
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
|
||||||
|
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
|
||||||
|
golang.org/x/image v0.0.0-20200618115811-c13761719519/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
|
||||||
|
golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o=
|
||||||
|
golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY=
|
||||||
|
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||||
|
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||||
|
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
|
golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a h1:aYOabOQFp6Vj6W1F80affTUvO9UxmJRx8K0gsfABByQ=
|
||||||
|
golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20200124204421-9fbb57f87de9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||||
|
golang.org/x/tools v0.0.0-20190927191325-030b2cf1153e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||||
|
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
+173
@@ -0,0 +1,173 @@
|
|||||||
|
#include <stdlib.h>
|
||||||
|
#include <jni.h>
|
||||||
|
#include <android/log.h>
|
||||||
|
#include "_cgo_export.h"
|
||||||
|
|
||||||
|
void
|
||||||
|
registerFragment(JNIEnv *env, jobject view) {
|
||||||
|
if (view == NULL) {
|
||||||
|
// Detach signal (Gio sends ViewEvent{View: 0} when the view is
|
||||||
|
// destroyed, e.g. the activity going away on a recents-wipe).
|
||||||
|
// The Go side already filters these; this guard keeps the JNI
|
||||||
|
// calls safe if one ever slips through (GetObjectClass on null
|
||||||
|
// aborts the process).
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
jclass cls = (*env)->GetObjectClass(env, view);
|
||||||
|
jmethodID mid = (*env)->GetMethodID(env, cls, "getContext", "()Landroid/content/Context;");
|
||||||
|
jobject ctx = (*env)->CallObjectMethod(env, view, mid);
|
||||||
|
cls = (*env)->GetObjectClass(env, ctx);
|
||||||
|
mid = (*env)->GetMethodID(env, cls, "getClassLoader", "()Ljava/lang/ClassLoader;");
|
||||||
|
jobject loader = (*env)->CallObjectMethod(env, ctx, mid);
|
||||||
|
cls = (*env)->GetObjectClass(env, loader);
|
||||||
|
mid = (*env)->GetMethodID(env, cls, "findClass", "(Ljava/lang/String;)Ljava/lang/Class;");
|
||||||
|
jstring str = (*env)->NewStringUTF(env, "st/wow/git/ble/BlessedConnect");
|
||||||
|
cls = (*env)->CallObjectMethod(env, loader, mid, str);
|
||||||
|
mid = (*env)->GetMethodID(env, cls, "<init>", "()V");
|
||||||
|
jobject inst = (*env)->NewObject(env, cls, mid);
|
||||||
|
mid = (*env)->GetMethodID(env, cls, "register", "(Landroid/view/View;)V");
|
||||||
|
(*env)->CallVoidMethod(env, inst, mid, view);
|
||||||
|
}
|
||||||
|
|
||||||
|
jboolean
|
||||||
|
enabled(JNIEnv *env, jobject b) {
|
||||||
|
jclass cls = (*env)->GetObjectClass(env, b);
|
||||||
|
jmethodID mid = (*env)->GetMethodID(env, cls, "enabled", "()Z");
|
||||||
|
return (*env)->CallBooleanMethod(env, b, mid);
|
||||||
|
}
|
||||||
|
|
||||||
|
void
|
||||||
|
scan(JNIEnv *env, jobject b) {
|
||||||
|
jclass cls = (*env)->GetObjectClass(env, b);
|
||||||
|
jmethodID mid = (*env)->GetMethodID(env, cls, "scan", "()V");
|
||||||
|
(*env)->CallVoidMethod(env, b, mid);
|
||||||
|
}
|
||||||
|
|
||||||
|
void
|
||||||
|
stopScan(JNIEnv *env, jobject b) {
|
||||||
|
jclass cls = (*env)->GetObjectClass(env, b);
|
||||||
|
jmethodID mid = (*env)->GetMethodID(env, cls, "stopScan", "()V");
|
||||||
|
(*env)->CallVoidMethod(env, b, mid);
|
||||||
|
}
|
||||||
|
|
||||||
|
void
|
||||||
|
connect(JNIEnv *env, jobject b, jobject d) {
|
||||||
|
jclass cls = (*env)->GetObjectClass(env, b);
|
||||||
|
jmethodID mid = (*env)->GetMethodID(env, cls, "connect", "(Lcom/welie/blessed/BluetoothPeripheral;)V");
|
||||||
|
(*env)->CallObjectMethod(env, b, mid, d);
|
||||||
|
}
|
||||||
|
|
||||||
|
void
|
||||||
|
disconnect(JNIEnv *env, jobject b, jobject g) {
|
||||||
|
jclass cls = (*env)->GetObjectClass(env, b);
|
||||||
|
jmethodID mid = (*env)->GetMethodID(env, cls, "disconnect", "(Lcom/welie/blessed/BluetoothPeripheral;)V");
|
||||||
|
(*env)->CallVoidMethod(env, b, mid, g);
|
||||||
|
}
|
||||||
|
|
||||||
|
void
|
||||||
|
discoverServices(JNIEnv *env, jobject b, jobject p) {
|
||||||
|
jclass cls = (*env)->GetObjectClass(env, b);
|
||||||
|
jmethodID mid = (*env)->GetMethodID(env, cls, "discoverServices", "(Lcom/welie/blessed/BluetoothPeripheral;)V");
|
||||||
|
(*env)->CallVoidMethod(env, b, mid, p);
|
||||||
|
}
|
||||||
|
|
||||||
|
void
|
||||||
|
discoverCharacteristics(JNIEnv *env, jobject b, jobject g, jobject s) {
|
||||||
|
jclass cls = (*env)->GetObjectClass(env, b);
|
||||||
|
jmethodID mid = (*env)->GetMethodID(env, cls, "discoverCharacteristics", "(Lcom/welie/blessed/BluetoothPeripheral;Landroid/bluetooth/BluetoothGattService;)V");
|
||||||
|
(*env)->CallVoidMethod(env, b, mid, g, s);
|
||||||
|
}
|
||||||
|
|
||||||
|
jboolean
|
||||||
|
setCharacteristicNotification(JNIEnv *env, jobject b, jobject g, jobject c) {
|
||||||
|
jclass cls = (*env)->GetObjectClass(env, b);
|
||||||
|
jmethodID mid = (*env)->GetMethodID(env, cls, "setCharacteristicNotification", "(Lcom/welie/blessed/BluetoothPeripheral;Landroid/bluetooth/BluetoothGattCharacteristic;)Z");
|
||||||
|
return (*env)->CallBooleanMethod(env, b, mid, g, c);
|
||||||
|
}
|
||||||
|
|
||||||
|
void
|
||||||
|
readCharacteristic(JNIEnv *env, jobject b, jobject g, jobject c) {
|
||||||
|
jclass cls = (*env)->GetObjectClass(env, b);
|
||||||
|
jmethodID mid = (*env)->GetMethodID(env, cls, "readCharacteristic", "(Lcom/welie/blessed/BluetoothPeripheral;Landroid/bluetooth/BluetoothGattCharacteristic;)V");
|
||||||
|
(*env)->CallBooleanMethod(env, b, mid, g, c);
|
||||||
|
}
|
||||||
|
|
||||||
|
jint
|
||||||
|
GetEnv(JavaVM *vm, JNIEnv **env, jint version) {
|
||||||
|
return (*vm)->GetEnv(vm, (void **)env, version);
|
||||||
|
}
|
||||||
|
|
||||||
|
jint
|
||||||
|
AttachCurrentThread(JavaVM *vm, JNIEnv **p_env, void *thr_args) {
|
||||||
|
return (*vm)->AttachCurrentThread(vm, p_env, thr_args);
|
||||||
|
}
|
||||||
|
|
||||||
|
jint
|
||||||
|
DetachCurrentThread(JavaVM *vm) {
|
||||||
|
return (*vm)->DetachCurrentThread(vm);
|
||||||
|
}
|
||||||
|
|
||||||
|
jobject
|
||||||
|
NewGlobalRef(JNIEnv *env, jobject o) {
|
||||||
|
return (*env)->NewGlobalRef(env, o);
|
||||||
|
}
|
||||||
|
|
||||||
|
void
|
||||||
|
Java_st_wow_git_ble_BlessedConnect_onScan(JNIEnv *env, jclass class, jstring jname, jstring jid, jint jrssi, jobject dev) {
|
||||||
|
const char* name = (*env)->GetStringUTFChars(env, jname, NULL);
|
||||||
|
const char* id = (*env)->GetStringUTFChars(env, jid, NULL);
|
||||||
|
jobject gdev = (*env)->NewGlobalRef(env, dev);
|
||||||
|
goOnScan(name, id, (int)jrssi, gdev);
|
||||||
|
(*env)->ReleaseStringUTFChars(env, jname, name);
|
||||||
|
(*env)->ReleaseStringUTFChars(env, jid, id);
|
||||||
|
}
|
||||||
|
|
||||||
|
void
|
||||||
|
Java_st_wow_git_ble_BlessedConnect_onConnect(JNIEnv *env, jclass class, jobject peripheral, jstring jid) {
|
||||||
|
const char* id = (*env)->GetStringUTFChars(env, jid, NULL);
|
||||||
|
jobject gperipheral = (*env)->NewGlobalRef(env, peripheral);
|
||||||
|
goOnConnect(gperipheral, id);
|
||||||
|
(*env)->ReleaseStringUTFChars(env, jid, id);
|
||||||
|
}
|
||||||
|
|
||||||
|
void
|
||||||
|
Java_st_wow_git_ble_BlessedConnect_onDisconnect(JNIEnv *env, jclass class, jobject peripheral, jstring jid) {
|
||||||
|
const char* id = (*env)->GetStringUTFChars(env, jid, NULL);
|
||||||
|
jobject gperipheral = (*env)->NewGlobalRef(env, peripheral);
|
||||||
|
goOnDisconnect(gperipheral, id);
|
||||||
|
(*env)->ReleaseStringUTFChars(env, jid, id);
|
||||||
|
}
|
||||||
|
|
||||||
|
void
|
||||||
|
Java_st_wow_git_ble_BlessedConnect_onDiscoverService(JNIEnv *env, jclass class, jstring jid, jstring juuid, jobject serv) {
|
||||||
|
const char* id = (*env)->GetStringUTFChars(env, jid, NULL);
|
||||||
|
const char* uuid = (*env)->GetStringUTFChars(env, juuid, NULL);
|
||||||
|
jobject gserv = (*env)->NewGlobalRef(env, serv);
|
||||||
|
goOnDiscoverService(id, uuid, gserv);
|
||||||
|
(*env)->ReleaseStringUTFChars(env, jid, id);
|
||||||
|
(*env)->ReleaseStringUTFChars(env, juuid, uuid);
|
||||||
|
}
|
||||||
|
|
||||||
|
void
|
||||||
|
Java_st_wow_git_ble_BlessedConnect_onDiscoverCharacteristic(JNIEnv *env, jclass class, jstring jid, jstring jsuuid, jobject serv, jstring jcuuid, jobject chr) {
|
||||||
|
const char* id = (*env)->GetStringUTFChars(env, jid, NULL);
|
||||||
|
const char* suuid = (*env)->GetStringUTFChars(env, jsuuid, NULL);
|
||||||
|
const char* cuuid = (*env)->GetStringUTFChars(env, jcuuid, NULL);
|
||||||
|
jobject gchr = (*env)->NewGlobalRef(env, chr);
|
||||||
|
goOnDiscoverCharacteristic(id, suuid, serv, cuuid, gchr);
|
||||||
|
(*env)->ReleaseStringUTFChars(env, jid, id);
|
||||||
|
(*env)->ReleaseStringUTFChars(env, jsuuid, suuid);
|
||||||
|
(*env)->ReleaseStringUTFChars(env, jcuuid, cuuid);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
void
|
||||||
|
Java_st_wow_git_ble_BlessedConnect_characteristicChanged(JNIEnv *env, jclass class, jstring jid, jstring jcuuid, jobject chr, jbyteArray jvalue, jint len) {
|
||||||
|
const char* id = (*env)->GetStringUTFChars(env, jid, NULL);
|
||||||
|
const char* cuuid = (*env)->GetStringUTFChars(env, jcuuid, NULL);
|
||||||
|
jbyte* value = (*env)->GetByteArrayElements(env, jvalue, NULL);
|
||||||
|
goOnCharacteristicChanged(id, cuuid, chr, value, len);
|
||||||
|
(*env)->ReleaseStringUTFChars(env, jid, id);
|
||||||
|
(*env)->ReleaseStringUTFChars(env, jcuuid, cuuid);
|
||||||
|
(*env)->ReleaseByteArrayElements(env, jvalue, value, len);
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package ble
|
||||||
|
|
||||||
|
/*
|
||||||
|
#cgo LDFLAGS: -landroid -llog
|
||||||
|
|
||||||
|
#import "jni_android.h"
|
||||||
|
*/
|
||||||
|
import "C"
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"runtime"
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
var theJVM *C.JavaVM
|
||||||
|
|
||||||
|
type JNIEnv = C.JNIEnv
|
||||||
|
|
||||||
|
func setJVM(jvm uintptr) {
|
||||||
|
log.Printf("set theJVM")
|
||||||
|
theJVM = (*C.JavaVM)(unsafe.Pointer(jvm))
|
||||||
|
if theJVM == nil {
|
||||||
|
log.Printf("theJVM is nil!")
|
||||||
|
} else {
|
||||||
|
log.Printf("theJVM is not nil")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func runInJVM(f func(env *C.JNIEnv)) {
|
||||||
|
runtime.LockOSThread()
|
||||||
|
defer runtime.UnlockOSThread()
|
||||||
|
var env *C.JNIEnv
|
||||||
|
var detach bool
|
||||||
|
//log.Printf("RunInJVM(): theJVM = %d", uintptr(unsafe.Pointer(theJVM)))
|
||||||
|
if res := C.GetEnv(theJVM, &env, C.JNI_VERSION_1_6); res != C.JNI_OK {
|
||||||
|
if res != C.JNI_EDETACHED {
|
||||||
|
panic(fmt.Errorf("JNI GetEnv failed with error %d", res))
|
||||||
|
}
|
||||||
|
if C.AttachCurrentThread(theJVM, &env, nil) != C.JNI_OK {
|
||||||
|
panic(errors.New("runInJVM: AttachCurrentThread failed"))
|
||||||
|
}
|
||||||
|
detach = true
|
||||||
|
}
|
||||||
|
|
||||||
|
if detach {
|
||||||
|
defer func() {
|
||||||
|
C.DetachCurrentThread(theJVM)
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
f(env)
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
#include <jni.h>
|
||||||
|
|
||||||
|
void registerFragment(JNIEnv *env, jobject view);
|
||||||
|
jboolean enabled(JNIEnv *env, jobject p);
|
||||||
|
void scan(JNIEnv *env, jobject b);
|
||||||
|
void stopScan(JNIEnv *env, jobject b);
|
||||||
|
void connect(JNIEnv *env, jobject b, jobject d);
|
||||||
|
void disconnect(JNIEnv *env, jobject b, jobject g);
|
||||||
|
void discoverServices(JNIEnv *env, jobject b, jobject p);
|
||||||
|
void discoverCharacteristics(JNIEnv *env, jobject b, jobject g, jobject s);
|
||||||
|
void readCharacteristic(JNIEnv *env, jobject b, jobject g, jobject c);
|
||||||
|
jboolean setCharacteristicNotification(JNIEnv *env, jobject b, jobject g, jobject c);
|
||||||
|
jint GetEnv(JavaVM *vm, JNIEnv **env, jint version);
|
||||||
|
jint AttachCurrentThread(JavaVM *vm, JNIEnv **p_env, void *thr_args);
|
||||||
|
jint DetachCurrentThread(JavaVM *vm);
|
||||||
|
jobject NewGlobalRef(JNIEnv *env, jobject o);
|
||||||
+43
-15
@@ -15,27 +15,34 @@ import "C"
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"unsafe"
|
"unsafe"
|
||||||
|
"fmt"
|
||||||
)
|
)
|
||||||
|
|
||||||
//export CBDelegateCentralManagerDidUpdateState
|
|
||||||
func CBDelegateCentralManagerDidUpdateState(o unsafe.Pointer, central unsafe.Pointer) {
|
|
||||||
CBDelegateMux.RLock()
|
|
||||||
cb := CBDelegateLookup[o].CentralManagerDidUpdateState
|
|
||||||
CBDelegateMux.RUnlock()
|
|
||||||
if cb == nil { return }
|
|
||||||
a1 := &CBCentralManager{}; a1.ptr = central
|
|
||||||
cb(a1)
|
|
||||||
}
|
|
||||||
|
|
||||||
//export CBDelegateCentralManagerDidConnectPeripheral
|
//export CBDelegateCentralManagerDidConnectPeripheral
|
||||||
func CBDelegateCentralManagerDidConnectPeripheral(o unsafe.Pointer, central unsafe.Pointer, peripheral unsafe.Pointer) {
|
func CBDelegateCentralManagerDidConnectPeripheral(o unsafe.Pointer, central unsafe.Pointer, peripheral unsafe.Pointer) {
|
||||||
CBDelegateMux.RLock()
|
CBDelegateMux.RLock()
|
||||||
cb := CBDelegateLookup[o].CentralManagerDidConnectPeripheral
|
cb := CBDelegateLookup[o].CentralManagerDidConnectPeripheral
|
||||||
CBDelegateMux.RUnlock()
|
CBDelegateMux.RUnlock()
|
||||||
if cb == nil { return }
|
if cb == nil { return }
|
||||||
|
self := CBDelegate{}
|
||||||
|
self.ptr = o
|
||||||
a1 := &CBCentralManager{}; a1.ptr = central
|
a1 := &CBCentralManager{}; a1.ptr = central
|
||||||
a2 := &CBPeripheral{}; a2.ptr = peripheral
|
a2 := &CBPeripheral{}; a2.ptr = peripheral
|
||||||
cb(a1, a2)
|
cb(self, a1, a2)
|
||||||
|
}
|
||||||
|
|
||||||
|
//export CBDelegateCentralManagerDidDisconnectPeripheral
|
||||||
|
func CBDelegateCentralManagerDidDisconnectPeripheral(o unsafe.Pointer, central unsafe.Pointer, peripheral unsafe.Pointer, error unsafe.Pointer) {
|
||||||
|
CBDelegateMux.RLock()
|
||||||
|
cb := CBDelegateLookup[o].CentralManagerDidDisconnectPeripheral
|
||||||
|
CBDelegateMux.RUnlock()
|
||||||
|
if cb == nil { return }
|
||||||
|
self := CBDelegate{}
|
||||||
|
self.ptr = o
|
||||||
|
a1 := &CBCentralManager{}; a1.ptr = central
|
||||||
|
a2 := &CBPeripheral{}; a2.ptr = peripheral
|
||||||
|
a3 := &NSError{}; a3.ptr = error
|
||||||
|
cb(self, a1, a2, a3)
|
||||||
}
|
}
|
||||||
|
|
||||||
//export CBDelegateCentralManagerDidDiscoverPeripheral
|
//export CBDelegateCentralManagerDidDiscoverPeripheral
|
||||||
@@ -44,11 +51,26 @@ func CBDelegateCentralManagerDidDiscoverPeripheral(o unsafe.Pointer, central uns
|
|||||||
cb := CBDelegateLookup[o].CentralManagerDidDiscoverPeripheral
|
cb := CBDelegateLookup[o].CentralManagerDidDiscoverPeripheral
|
||||||
CBDelegateMux.RUnlock()
|
CBDelegateMux.RUnlock()
|
||||||
if cb == nil { return }
|
if cb == nil { return }
|
||||||
|
self := CBDelegate{}
|
||||||
|
self.ptr = o
|
||||||
a1 := &CBCentralManager{}; a1.ptr = central
|
a1 := &CBCentralManager{}; a1.ptr = central
|
||||||
a2 := &CBPeripheral{}; a2.ptr = peripheral
|
a2 := &CBPeripheral{}; a2.ptr = peripheral
|
||||||
a3 := &NSDictionary{}; a3.ptr = advertisementData
|
a3 := &NSDictionary{}; a3.ptr = advertisementData
|
||||||
a4 := &NSNumber{}; a4.ptr = RSSI
|
a4 := &NSNumber{}; a4.ptr = RSSI
|
||||||
cb(a1, a2, a3, a4)
|
cb(self, a1, a2, a3, a4)
|
||||||
|
}
|
||||||
|
|
||||||
|
//export CBDelegateCentralManagerDidUpdateState
|
||||||
|
func CBDelegateCentralManagerDidUpdateState(o unsafe.Pointer, central unsafe.Pointer) {
|
||||||
|
fmt.Print("CentralManagerDidUpdateState")
|
||||||
|
CBDelegateMux.RLock()
|
||||||
|
cb := CBDelegateLookup[o].CentralManagerDidUpdateState
|
||||||
|
CBDelegateMux.RUnlock()
|
||||||
|
if cb == nil { return }
|
||||||
|
self := CBDelegate{}
|
||||||
|
self.ptr = o
|
||||||
|
a1 := &CBCentralManager{}; a1.ptr = central
|
||||||
|
cb(self, a1)
|
||||||
}
|
}
|
||||||
|
|
||||||
//export CBDelegatePeripheralDidDiscoverServices
|
//export CBDelegatePeripheralDidDiscoverServices
|
||||||
@@ -57,9 +79,11 @@ func CBDelegatePeripheralDidDiscoverServices(o unsafe.Pointer, peripheral unsafe
|
|||||||
cb := CBDelegateLookup[o].PeripheralDidDiscoverServices
|
cb := CBDelegateLookup[o].PeripheralDidDiscoverServices
|
||||||
CBDelegateMux.RUnlock()
|
CBDelegateMux.RUnlock()
|
||||||
if cb == nil { return }
|
if cb == nil { return }
|
||||||
|
self := CBDelegate{}
|
||||||
|
self.ptr = o
|
||||||
a1 := &CBPeripheral{}; a1.ptr = peripheral
|
a1 := &CBPeripheral{}; a1.ptr = peripheral
|
||||||
a2 := &NSError{}; a2.ptr = error
|
a2 := &NSError{}; a2.ptr = error
|
||||||
cb(a1, a2)
|
cb(self, a1, a2)
|
||||||
}
|
}
|
||||||
|
|
||||||
//export CBDelegatePeripheralDidDiscoverCharacteristicsForService
|
//export CBDelegatePeripheralDidDiscoverCharacteristicsForService
|
||||||
@@ -68,10 +92,12 @@ func CBDelegatePeripheralDidDiscoverCharacteristicsForService(o unsafe.Pointer,
|
|||||||
cb := CBDelegateLookup[o].PeripheralDidDiscoverCharacteristicsForService
|
cb := CBDelegateLookup[o].PeripheralDidDiscoverCharacteristicsForService
|
||||||
CBDelegateMux.RUnlock()
|
CBDelegateMux.RUnlock()
|
||||||
if cb == nil { return }
|
if cb == nil { return }
|
||||||
|
self := CBDelegate{}
|
||||||
|
self.ptr = o
|
||||||
a1 := &CBPeripheral{}; a1.ptr = peripheral
|
a1 := &CBPeripheral{}; a1.ptr = peripheral
|
||||||
a2 := &CBService{}; a2.ptr = service
|
a2 := &CBService{}; a2.ptr = service
|
||||||
a3 := &NSError{}; a3.ptr = error
|
a3 := &NSError{}; a3.ptr = error
|
||||||
cb(a1, a2, a3)
|
cb(self, a1, a2, a3)
|
||||||
}
|
}
|
||||||
|
|
||||||
//export CBDelegatePeripheralDidUpdateValueForCharacteristic
|
//export CBDelegatePeripheralDidUpdateValueForCharacteristic
|
||||||
@@ -80,8 +106,10 @@ func CBDelegatePeripheralDidUpdateValueForCharacteristic(o unsafe.Pointer, perip
|
|||||||
cb := CBDelegateLookup[o].PeripheralDidUpdateValueForCharacteristic
|
cb := CBDelegateLookup[o].PeripheralDidUpdateValueForCharacteristic
|
||||||
CBDelegateMux.RUnlock()
|
CBDelegateMux.RUnlock()
|
||||||
if cb == nil { return }
|
if cb == nil { return }
|
||||||
|
self := CBDelegate{}
|
||||||
|
self.ptr = o
|
||||||
a1 := &CBPeripheral{}; a1.ptr = peripheral
|
a1 := &CBPeripheral{}; a1.ptr = peripheral
|
||||||
a2 := &CBCharacteristic{}; a2.ptr = characteristic
|
a2 := &CBCharacteristic{}; a2.ptr = characteristic
|
||||||
a3 := &NSError{}; a3.ptr = error
|
a3 := &NSError{}; a3.ptr = error
|
||||||
cb(a1, a2, a3)
|
cb(self, a1, a2, a3)
|
||||||
}
|
}
|
||||||
|
|||||||
+53392
-54959
File diff suppressed because it is too large
Load Diff
+3
-2
@@ -1,6 +1,6 @@
|
|||||||
inputfiles:
|
inputfiles:
|
||||||
- /System/Library/Frameworks/Foundation.framework/Headers/Foundation.h
|
- /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.h
|
||||||
- /System/Library/Frameworks/CoreBluetooth.framework/Headers/CoreBluetooth.h
|
- /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/CoreBluetooth.framework/Headers/CoreBluetooth.h
|
||||||
|
|
||||||
classes:
|
classes:
|
||||||
- NSObject
|
- NSObject
|
||||||
@@ -35,6 +35,7 @@ delegates:
|
|||||||
- centralManagerDidUpdateState
|
- centralManagerDidUpdateState
|
||||||
- centralManagerDidDiscoverPeripheral
|
- centralManagerDidDiscoverPeripheral
|
||||||
- centralManagerDidConnectPeripheral
|
- centralManagerDidConnectPeripheral
|
||||||
|
- centralManagerDidDisconnectPeripheral
|
||||||
CBPeripheralDelegate:
|
CBPeripheralDelegate:
|
||||||
- peripheralDidDiscoverServices
|
- peripheralDidDiscoverServices
|
||||||
- peripheralDidDiscoverCharacteristicsForService
|
- peripheralDidDiscoverCharacteristicsForService
|
||||||
|
|||||||
BIN
Binary file not shown.
Reference in New Issue
Block a user