feat: 修复了一些问题,重构部分接口 (#4)

This commit is contained in:
iAMD
2022-09-30 17:46:52 +08:00
committed by GitHub
parent 9ec2449694
commit 3abe9d5b3d
65 changed files with 2321 additions and 2984 deletions

View File

@ -1,3 +1,9 @@
## 1.1.0
- Fix the crash by onMtuChanged called multi-times on Android.
- Fix the finalizer doesn't work issue.
- Make some break changes.
## 1.0.0 ## 1.0.0
- Upgrade to flutter 3.x. - Upgrade to flutter 3.x.

View File

@ -6,11 +6,11 @@ include: package:flutter_lints/flutter.yaml
analyzer: analyzer:
exclude: exclude:
- "**/*.g.dart" - "**/*.g.dart"
- "**/*.mocks.dart"
- "**/*.pb.dart" - "**/*.pb.dart"
- "**/*.pbenum.dart" - "**/*.pbenum.dart"
- "**/*.pbjson.dart" - "**/*.pbjson.dart"
- "**/*.pbserver.dart" - "**/*.pbserver.dart"
- "**/*.mocks.dart"
linter: linter:
rules: rules:

View File

@ -1,5 +1,6 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="dev.yanshouwang.bluetooth_low_energy"> package="dev.yanshouwang.bluetooth_low_energy">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.BLUETOOTH" <uses-permission android:name="android.permission.BLUETOOTH"

View File

@ -1,4 +1,4 @@
// Autogenerated from Pigeon (v4.0.2), do not edit directly. // Autogenerated from Pigeon (v4.2.0), do not edit directly.
// See also: https://pub.dev/packages/pigeon // See also: https://pub.dev/packages/pigeon
package dev.yanshouwang.bluetooth_low_energy.pigeon; package dev.yanshouwang.bluetooth_low_energy.pigeon;
@ -20,7 +20,7 @@ import java.util.HashMap;
/**Generated class from Pigeon. */ /**Generated class from Pigeon. */
@SuppressWarnings({"unused", "unchecked", "CodeBlock2Expr", "RedundantSuppression"}) @SuppressWarnings({"unused", "unchecked", "CodeBlock2Expr", "RedundantSuppression"})
public class Api { public class Messages {
public interface Result<T> { public interface Result<T> {
void success(T result); void success(T result);
@ -35,11 +35,8 @@ public class Api {
public interface CentralManagerHostApi { public interface CentralManagerHostApi {
void authorize(Result<Boolean> result); void authorize(Result<Boolean> result);
@NonNull Long getState(); @NonNull Long getState();
void addStateObserver();
void removeStateObserver();
void startScan(@Nullable List<byte[]> uuidBuffers, Result<Void> result); void startScan(@Nullable List<byte[]> uuidBuffers, Result<Void> result);
void stopScan(); void stopScan();
void connect(@NonNull byte[] uuidBuffer, Result<byte[]> result);
/** The codec used by CentralManagerHostApi. */ /** The codec used by CentralManagerHostApi. */
static MessageCodec<Object> getCodec() { static MessageCodec<Object> getCodec() {
@ -96,44 +93,6 @@ public class Api {
channel.setMessageHandler(null); channel.setMessageHandler(null);
} }
} }
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.CentralManagerHostApi.addStateObserver", getCodec());
if (api != null) {
channel.setMessageHandler((message, reply) -> {
Map<String, Object> wrapped = new HashMap<>();
try {
api.addStateObserver();
wrapped.put("result", null);
}
catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception));
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.CentralManagerHostApi.removeStateObserver", getCodec());
if (api != null) {
channel.setMessageHandler((message, reply) -> {
Map<String, Object> wrapped = new HashMap<>();
try {
api.removeStateObserver();
wrapped.put("result", null);
}
catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception));
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{ {
BasicMessageChannel<Object> channel = BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.CentralManagerHostApi.startScan", getCodec()); new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.CentralManagerHostApi.startScan", getCodec());
@ -184,40 +143,6 @@ public class Api {
channel.setMessageHandler(null); channel.setMessageHandler(null);
} }
} }
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.CentralManagerHostApi.connect", getCodec());
if (api != null) {
channel.setMessageHandler((message, reply) -> {
Map<String, Object> wrapped = new HashMap<>();
try {
ArrayList<Object> args = (ArrayList<Object>)message;
byte[] uuidBufferArg = (byte[])args.get(0);
if (uuidBufferArg == null) {
throw new NullPointerException("uuidBufferArg unexpectedly null.");
}
Result<byte[]> resultCallback = new Result<byte[]>() {
public void success(byte[] result) {
wrapped.put("result", result);
reply.reply(wrapped);
}
public void error(Throwable error) {
wrapped.put("error", wrapError(error));
reply.reply(wrapped);
}
};
api.connect(uuidBufferArg, resultCallback);
}
catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception));
reply.reply(wrapped);
}
});
} else {
channel.setMessageHandler(null);
}
}
} }
} }
private static class CentralManagerFlutterApiCodec extends StandardMessageCodec { private static class CentralManagerFlutterApiCodec extends StandardMessageCodec {
@ -238,17 +163,17 @@ public class Api {
return CentralManagerFlutterApiCodec.INSTANCE; return CentralManagerFlutterApiCodec.INSTANCE;
} }
public void notifyState(@NonNull Long stateNumberArg, Reply<Void> callback) { public void onStateChanged(@NonNull Long stateNumberArg, Reply<Void> callback) {
BasicMessageChannel<Object> channel = BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.CentralManagerFlutterApi.notifyState", getCodec()); new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.CentralManagerFlutterApi.onStateChanged", getCodec());
channel.send(new ArrayList<Object>(Arrays.asList(stateNumberArg)), channelReply -> { channel.send(new ArrayList<Object>(Arrays.asList(stateNumberArg)), channelReply -> {
callback.reply(null); callback.reply(null);
}); });
} }
public void notifyAdvertisement(@NonNull byte[] advertisementBufferArg, Reply<Void> callback) { public void onScanned(@NonNull byte[] broadcastBufferArg, Reply<Void> callback) {
BasicMessageChannel<Object> channel = BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.CentralManagerFlutterApi.notifyAdvertisement", getCodec()); new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.CentralManagerFlutterApi.onScanned", getCodec());
channel.send(new ArrayList<Object>(Arrays.asList(advertisementBufferArg)), channelReply -> { channel.send(new ArrayList<Object>(Arrays.asList(broadcastBufferArg)), channelReply -> {
callback.reply(null); callback.reply(null);
}); });
} }
@ -260,10 +185,11 @@ public class Api {
/** Generated interface from Pigeon that represents a handler of messages from Flutter. */ /** Generated interface from Pigeon that represents a handler of messages from Flutter. */
public interface PeripheralHostApi { public interface PeripheralHostApi {
void allocate(@NonNull Long id, @NonNull Long instanceId); void free(@NonNull String id);
void free(@NonNull Long id); void connect(@NonNull String id, Result<Void> result);
void disconnect(@NonNull Long id, Result<Void> result); void disconnect(@NonNull String id, Result<Void> result);
void discoverServices(@NonNull Long id, Result<List<byte[]>> result); void requestMtu(@NonNull String id, Result<Long> result);
void discoverServices(@NonNull String id, Result<List<byte[]>> result);
/** The codec used by PeripheralHostApi. */ /** The codec used by PeripheralHostApi. */
static MessageCodec<Object> getCodec() { static MessageCodec<Object> getCodec() {
@ -272,34 +198,6 @@ public class Api {
/**Sets up an instance of `PeripheralHostApi` to handle messages through the `binaryMessenger`. */ /**Sets up an instance of `PeripheralHostApi` to handle messages through the `binaryMessenger`. */
static void setup(BinaryMessenger binaryMessenger, PeripheralHostApi api) { static void setup(BinaryMessenger binaryMessenger, PeripheralHostApi api) {
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.PeripheralHostApi.allocate", getCodec());
if (api != null) {
channel.setMessageHandler((message, reply) -> {
Map<String, Object> wrapped = new HashMap<>();
try {
ArrayList<Object> args = (ArrayList<Object>)message;
Number idArg = (Number)args.get(0);
if (idArg == null) {
throw new NullPointerException("idArg unexpectedly null.");
}
Number instanceIdArg = (Number)args.get(1);
if (instanceIdArg == null) {
throw new NullPointerException("instanceIdArg unexpectedly null.");
}
api.allocate((idArg == null) ? null : idArg.longValue(), (instanceIdArg == null) ? null : instanceIdArg.longValue());
wrapped.put("result", null);
}
catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception));
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{ {
BasicMessageChannel<Object> channel = BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.PeripheralHostApi.free", getCodec()); new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.PeripheralHostApi.free", getCodec());
@ -308,11 +206,11 @@ public class Api {
Map<String, Object> wrapped = new HashMap<>(); Map<String, Object> wrapped = new HashMap<>();
try { try {
ArrayList<Object> args = (ArrayList<Object>)message; ArrayList<Object> args = (ArrayList<Object>)message;
Number idArg = (Number)args.get(0); String idArg = (String)args.get(0);
if (idArg == null) { if (idArg == null) {
throw new NullPointerException("idArg unexpectedly null."); throw new NullPointerException("idArg unexpectedly null.");
} }
api.free((idArg == null) ? null : idArg.longValue()); api.free(idArg);
wrapped.put("result", null); wrapped.put("result", null);
} }
catch (Error | RuntimeException exception) { catch (Error | RuntimeException exception) {
@ -326,13 +224,13 @@ public class Api {
} }
{ {
BasicMessageChannel<Object> channel = BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.PeripheralHostApi.disconnect", getCodec()); new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.PeripheralHostApi.connect", getCodec());
if (api != null) { if (api != null) {
channel.setMessageHandler((message, reply) -> { channel.setMessageHandler((message, reply) -> {
Map<String, Object> wrapped = new HashMap<>(); Map<String, Object> wrapped = new HashMap<>();
try { try {
ArrayList<Object> args = (ArrayList<Object>)message; ArrayList<Object> args = (ArrayList<Object>)message;
Number idArg = (Number)args.get(0); String idArg = (String)args.get(0);
if (idArg == null) { if (idArg == null) {
throw new NullPointerException("idArg unexpectedly null."); throw new NullPointerException("idArg unexpectedly null.");
} }
@ -347,7 +245,75 @@ public class Api {
} }
}; };
api.disconnect((idArg == null) ? null : idArg.longValue(), resultCallback); api.connect(idArg, resultCallback);
}
catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception));
reply.reply(wrapped);
}
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.PeripheralHostApi.disconnect", getCodec());
if (api != null) {
channel.setMessageHandler((message, reply) -> {
Map<String, Object> wrapped = new HashMap<>();
try {
ArrayList<Object> args = (ArrayList<Object>)message;
String idArg = (String)args.get(0);
if (idArg == null) {
throw new NullPointerException("idArg unexpectedly null.");
}
Result<Void> resultCallback = new Result<Void>() {
public void success(Void result) {
wrapped.put("result", null);
reply.reply(wrapped);
}
public void error(Throwable error) {
wrapped.put("error", wrapError(error));
reply.reply(wrapped);
}
};
api.disconnect(idArg, resultCallback);
}
catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception));
reply.reply(wrapped);
}
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.PeripheralHostApi.requestMtu", getCodec());
if (api != null) {
channel.setMessageHandler((message, reply) -> {
Map<String, Object> wrapped = new HashMap<>();
try {
ArrayList<Object> args = (ArrayList<Object>)message;
String idArg = (String)args.get(0);
if (idArg == null) {
throw new NullPointerException("idArg unexpectedly null.");
}
Result<Long> resultCallback = new Result<Long>() {
public void success(Long result) {
wrapped.put("result", result);
reply.reply(wrapped);
}
public void error(Throwable error) {
wrapped.put("error", wrapError(error));
reply.reply(wrapped);
}
};
api.requestMtu(idArg, resultCallback);
} }
catch (Error | RuntimeException exception) { catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception)); wrapped.put("error", wrapError(exception));
@ -366,7 +332,7 @@ public class Api {
Map<String, Object> wrapped = new HashMap<>(); Map<String, Object> wrapped = new HashMap<>();
try { try {
ArrayList<Object> args = (ArrayList<Object>)message; ArrayList<Object> args = (ArrayList<Object>)message;
Number idArg = (Number)args.get(0); String idArg = (String)args.get(0);
if (idArg == null) { if (idArg == null) {
throw new NullPointerException("idArg unexpectedly null."); throw new NullPointerException("idArg unexpectedly null.");
} }
@ -381,7 +347,7 @@ public class Api {
} }
}; };
api.discoverServices((idArg == null) ? null : idArg.longValue(), resultCallback); api.discoverServices(idArg, resultCallback);
} }
catch (Error | RuntimeException exception) { catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception)); wrapped.put("error", wrapError(exception));
@ -412,10 +378,10 @@ public class Api {
return PeripheralFlutterApiCodec.INSTANCE; return PeripheralFlutterApiCodec.INSTANCE;
} }
public void notifyConnectionLost(@NonNull Long idArg, @NonNull byte[] errorBufferArg, Reply<Void> callback) { public void onConnectionLost(@NonNull String idArg, @NonNull String errorMessageArg, Reply<Void> callback) {
BasicMessageChannel<Object> channel = BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.PeripheralFlutterApi.notifyConnectionLost", getCodec()); new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.PeripheralFlutterApi.onConnectionLost", getCodec());
channel.send(new ArrayList<Object>(Arrays.asList(idArg, errorBufferArg)), channelReply -> { channel.send(new ArrayList<Object>(Arrays.asList(idArg, errorMessageArg)), channelReply -> {
callback.reply(null); callback.reply(null);
}); });
} }
@ -427,9 +393,8 @@ public class Api {
/** Generated interface from Pigeon that represents a handler of messages from Flutter. */ /** Generated interface from Pigeon that represents a handler of messages from Flutter. */
public interface GattServiceHostApi { public interface GattServiceHostApi {
void allocate(@NonNull Long id, @NonNull Long instanceId); void free(@NonNull String id);
void free(@NonNull Long id); void discoverCharacteristics(@NonNull String id, Result<List<byte[]>> result);
void discoverCharacteristics(@NonNull Long id, Result<List<byte[]>> result);
/** The codec used by GattServiceHostApi. */ /** The codec used by GattServiceHostApi. */
static MessageCodec<Object> getCodec() { static MessageCodec<Object> getCodec() {
@ -438,34 +403,6 @@ public class Api {
/**Sets up an instance of `GattServiceHostApi` to handle messages through the `binaryMessenger`. */ /**Sets up an instance of `GattServiceHostApi` to handle messages through the `binaryMessenger`. */
static void setup(BinaryMessenger binaryMessenger, GattServiceHostApi api) { static void setup(BinaryMessenger binaryMessenger, GattServiceHostApi api) {
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.GattServiceHostApi.allocate", getCodec());
if (api != null) {
channel.setMessageHandler((message, reply) -> {
Map<String, Object> wrapped = new HashMap<>();
try {
ArrayList<Object> args = (ArrayList<Object>)message;
Number idArg = (Number)args.get(0);
if (idArg == null) {
throw new NullPointerException("idArg unexpectedly null.");
}
Number instanceIdArg = (Number)args.get(1);
if (instanceIdArg == null) {
throw new NullPointerException("instanceIdArg unexpectedly null.");
}
api.allocate((idArg == null) ? null : idArg.longValue(), (instanceIdArg == null) ? null : instanceIdArg.longValue());
wrapped.put("result", null);
}
catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception));
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{ {
BasicMessageChannel<Object> channel = BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.GattServiceHostApi.free", getCodec()); new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.GattServiceHostApi.free", getCodec());
@ -474,11 +411,11 @@ public class Api {
Map<String, Object> wrapped = new HashMap<>(); Map<String, Object> wrapped = new HashMap<>();
try { try {
ArrayList<Object> args = (ArrayList<Object>)message; ArrayList<Object> args = (ArrayList<Object>)message;
Number idArg = (Number)args.get(0); String idArg = (String)args.get(0);
if (idArg == null) { if (idArg == null) {
throw new NullPointerException("idArg unexpectedly null."); throw new NullPointerException("idArg unexpectedly null.");
} }
api.free((idArg == null) ? null : idArg.longValue()); api.free(idArg);
wrapped.put("result", null); wrapped.put("result", null);
} }
catch (Error | RuntimeException exception) { catch (Error | RuntimeException exception) {
@ -498,7 +435,7 @@ public class Api {
Map<String, Object> wrapped = new HashMap<>(); Map<String, Object> wrapped = new HashMap<>();
try { try {
ArrayList<Object> args = (ArrayList<Object>)message; ArrayList<Object> args = (ArrayList<Object>)message;
Number idArg = (Number)args.get(0); String idArg = (String)args.get(0);
if (idArg == null) { if (idArg == null) {
throw new NullPointerException("idArg unexpectedly null."); throw new NullPointerException("idArg unexpectedly null.");
} }
@ -513,7 +450,7 @@ public class Api {
} }
}; };
api.discoverCharacteristics((idArg == null) ? null : idArg.longValue(), resultCallback); api.discoverCharacteristics(idArg, resultCallback);
} }
catch (Error | RuntimeException exception) { catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception)); wrapped.put("error", wrapError(exception));
@ -533,12 +470,11 @@ public class Api {
/** Generated interface from Pigeon that represents a handler of messages from Flutter. */ /** Generated interface from Pigeon that represents a handler of messages from Flutter. */
public interface GattCharacteristicHostApi { public interface GattCharacteristicHostApi {
void allocate(@NonNull Long id, @NonNull Long instanceId); void free(@NonNull String id);
void free(@NonNull Long id); void discoverDescriptors(@NonNull String id, Result<List<byte[]>> result);
void discoverDescriptors(@NonNull Long id, Result<List<byte[]>> result); void read(@NonNull String id, Result<byte[]> result);
void read(@NonNull Long id, Result<byte[]> result); void write(@NonNull String id, @NonNull byte[] value, @NonNull Boolean withoutResponse, Result<Void> result);
void write(@NonNull Long id, @NonNull byte[] value, @NonNull Boolean withoutResponse, Result<Void> result); void setNotify(@NonNull String id, @NonNull Boolean value, Result<Void> result);
void setNotify(@NonNull Long id, @NonNull Boolean value, Result<Void> result);
/** The codec used by GattCharacteristicHostApi. */ /** The codec used by GattCharacteristicHostApi. */
static MessageCodec<Object> getCodec() { static MessageCodec<Object> getCodec() {
@ -547,34 +483,6 @@ public class Api {
/**Sets up an instance of `GattCharacteristicHostApi` to handle messages through the `binaryMessenger`. */ /**Sets up an instance of `GattCharacteristicHostApi` to handle messages through the `binaryMessenger`. */
static void setup(BinaryMessenger binaryMessenger, GattCharacteristicHostApi api) { static void setup(BinaryMessenger binaryMessenger, GattCharacteristicHostApi api) {
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.GattCharacteristicHostApi.allocate", getCodec());
if (api != null) {
channel.setMessageHandler((message, reply) -> {
Map<String, Object> wrapped = new HashMap<>();
try {
ArrayList<Object> args = (ArrayList<Object>)message;
Number idArg = (Number)args.get(0);
if (idArg == null) {
throw new NullPointerException("idArg unexpectedly null.");
}
Number instanceIdArg = (Number)args.get(1);
if (instanceIdArg == null) {
throw new NullPointerException("instanceIdArg unexpectedly null.");
}
api.allocate((idArg == null) ? null : idArg.longValue(), (instanceIdArg == null) ? null : instanceIdArg.longValue());
wrapped.put("result", null);
}
catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception));
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{ {
BasicMessageChannel<Object> channel = BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.GattCharacteristicHostApi.free", getCodec()); new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.GattCharacteristicHostApi.free", getCodec());
@ -583,11 +491,11 @@ public class Api {
Map<String, Object> wrapped = new HashMap<>(); Map<String, Object> wrapped = new HashMap<>();
try { try {
ArrayList<Object> args = (ArrayList<Object>)message; ArrayList<Object> args = (ArrayList<Object>)message;
Number idArg = (Number)args.get(0); String idArg = (String)args.get(0);
if (idArg == null) { if (idArg == null) {
throw new NullPointerException("idArg unexpectedly null."); throw new NullPointerException("idArg unexpectedly null.");
} }
api.free((idArg == null) ? null : idArg.longValue()); api.free(idArg);
wrapped.put("result", null); wrapped.put("result", null);
} }
catch (Error | RuntimeException exception) { catch (Error | RuntimeException exception) {
@ -607,7 +515,7 @@ public class Api {
Map<String, Object> wrapped = new HashMap<>(); Map<String, Object> wrapped = new HashMap<>();
try { try {
ArrayList<Object> args = (ArrayList<Object>)message; ArrayList<Object> args = (ArrayList<Object>)message;
Number idArg = (Number)args.get(0); String idArg = (String)args.get(0);
if (idArg == null) { if (idArg == null) {
throw new NullPointerException("idArg unexpectedly null."); throw new NullPointerException("idArg unexpectedly null.");
} }
@ -622,7 +530,7 @@ public class Api {
} }
}; };
api.discoverDescriptors((idArg == null) ? null : idArg.longValue(), resultCallback); api.discoverDescriptors(idArg, resultCallback);
} }
catch (Error | RuntimeException exception) { catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception)); wrapped.put("error", wrapError(exception));
@ -641,7 +549,7 @@ public class Api {
Map<String, Object> wrapped = new HashMap<>(); Map<String, Object> wrapped = new HashMap<>();
try { try {
ArrayList<Object> args = (ArrayList<Object>)message; ArrayList<Object> args = (ArrayList<Object>)message;
Number idArg = (Number)args.get(0); String idArg = (String)args.get(0);
if (idArg == null) { if (idArg == null) {
throw new NullPointerException("idArg unexpectedly null."); throw new NullPointerException("idArg unexpectedly null.");
} }
@ -656,7 +564,7 @@ public class Api {
} }
}; };
api.read((idArg == null) ? null : idArg.longValue(), resultCallback); api.read(idArg, resultCallback);
} }
catch (Error | RuntimeException exception) { catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception)); wrapped.put("error", wrapError(exception));
@ -675,7 +583,7 @@ public class Api {
Map<String, Object> wrapped = new HashMap<>(); Map<String, Object> wrapped = new HashMap<>();
try { try {
ArrayList<Object> args = (ArrayList<Object>)message; ArrayList<Object> args = (ArrayList<Object>)message;
Number idArg = (Number)args.get(0); String idArg = (String)args.get(0);
if (idArg == null) { if (idArg == null) {
throw new NullPointerException("idArg unexpectedly null."); throw new NullPointerException("idArg unexpectedly null.");
} }
@ -698,7 +606,7 @@ public class Api {
} }
}; };
api.write((idArg == null) ? null : idArg.longValue(), valueArg, withoutResponseArg, resultCallback); api.write(idArg, valueArg, withoutResponseArg, resultCallback);
} }
catch (Error | RuntimeException exception) { catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception)); wrapped.put("error", wrapError(exception));
@ -717,7 +625,7 @@ public class Api {
Map<String, Object> wrapped = new HashMap<>(); Map<String, Object> wrapped = new HashMap<>();
try { try {
ArrayList<Object> args = (ArrayList<Object>)message; ArrayList<Object> args = (ArrayList<Object>)message;
Number idArg = (Number)args.get(0); String idArg = (String)args.get(0);
if (idArg == null) { if (idArg == null) {
throw new NullPointerException("idArg unexpectedly null."); throw new NullPointerException("idArg unexpectedly null.");
} }
@ -736,7 +644,7 @@ public class Api {
} }
}; };
api.setNotify((idArg == null) ? null : idArg.longValue(), valueArg, resultCallback); api.setNotify(idArg, valueArg, resultCallback);
} }
catch (Error | RuntimeException exception) { catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception)); wrapped.put("error", wrapError(exception));
@ -767,9 +675,9 @@ public class Api {
return GattCharacteristicFlutterApiCodec.INSTANCE; return GattCharacteristicFlutterApiCodec.INSTANCE;
} }
public void notifyValue(@NonNull Long idArg, @NonNull byte[] valueArg, Reply<Void> callback) { public void onValueChanged(@NonNull String idArg, @NonNull byte[] valueArg, Reply<Void> callback) {
BasicMessageChannel<Object> channel = BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.GattCharacteristicFlutterApi.notifyValue", getCodec()); new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.GattCharacteristicFlutterApi.onValueChanged", getCodec());
channel.send(new ArrayList<Object>(Arrays.asList(idArg, valueArg)), channelReply -> { channel.send(new ArrayList<Object>(Arrays.asList(idArg, valueArg)), channelReply -> {
callback.reply(null); callback.reply(null);
}); });
@ -782,10 +690,9 @@ public class Api {
/** Generated interface from Pigeon that represents a handler of messages from Flutter. */ /** Generated interface from Pigeon that represents a handler of messages from Flutter. */
public interface GattDescriptorHostApi { public interface GattDescriptorHostApi {
void allocate(@NonNull Long id, @NonNull Long instanceId); void free(@NonNull String id);
void free(@NonNull Long id); void read(@NonNull String id, Result<byte[]> result);
void read(@NonNull Long id, Result<byte[]> result); void write(@NonNull String id, @NonNull byte[] value, Result<Void> result);
void write(@NonNull Long id, @NonNull byte[] value, Result<Void> result);
/** The codec used by GattDescriptorHostApi. */ /** The codec used by GattDescriptorHostApi. */
static MessageCodec<Object> getCodec() { static MessageCodec<Object> getCodec() {
@ -794,34 +701,6 @@ public class Api {
/**Sets up an instance of `GattDescriptorHostApi` to handle messages through the `binaryMessenger`. */ /**Sets up an instance of `GattDescriptorHostApi` to handle messages through the `binaryMessenger`. */
static void setup(BinaryMessenger binaryMessenger, GattDescriptorHostApi api) { static void setup(BinaryMessenger binaryMessenger, GattDescriptorHostApi api) {
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.GattDescriptorHostApi.allocate", getCodec());
if (api != null) {
channel.setMessageHandler((message, reply) -> {
Map<String, Object> wrapped = new HashMap<>();
try {
ArrayList<Object> args = (ArrayList<Object>)message;
Number idArg = (Number)args.get(0);
if (idArg == null) {
throw new NullPointerException("idArg unexpectedly null.");
}
Number instanceIdArg = (Number)args.get(1);
if (instanceIdArg == null) {
throw new NullPointerException("instanceIdArg unexpectedly null.");
}
api.allocate((idArg == null) ? null : idArg.longValue(), (instanceIdArg == null) ? null : instanceIdArg.longValue());
wrapped.put("result", null);
}
catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception));
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{ {
BasicMessageChannel<Object> channel = BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.GattDescriptorHostApi.free", getCodec()); new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.GattDescriptorHostApi.free", getCodec());
@ -830,11 +709,11 @@ public class Api {
Map<String, Object> wrapped = new HashMap<>(); Map<String, Object> wrapped = new HashMap<>();
try { try {
ArrayList<Object> args = (ArrayList<Object>)message; ArrayList<Object> args = (ArrayList<Object>)message;
Number idArg = (Number)args.get(0); String idArg = (String)args.get(0);
if (idArg == null) { if (idArg == null) {
throw new NullPointerException("idArg unexpectedly null."); throw new NullPointerException("idArg unexpectedly null.");
} }
api.free((idArg == null) ? null : idArg.longValue()); api.free(idArg);
wrapped.put("result", null); wrapped.put("result", null);
} }
catch (Error | RuntimeException exception) { catch (Error | RuntimeException exception) {
@ -854,7 +733,7 @@ public class Api {
Map<String, Object> wrapped = new HashMap<>(); Map<String, Object> wrapped = new HashMap<>();
try { try {
ArrayList<Object> args = (ArrayList<Object>)message; ArrayList<Object> args = (ArrayList<Object>)message;
Number idArg = (Number)args.get(0); String idArg = (String)args.get(0);
if (idArg == null) { if (idArg == null) {
throw new NullPointerException("idArg unexpectedly null."); throw new NullPointerException("idArg unexpectedly null.");
} }
@ -869,7 +748,7 @@ public class Api {
} }
}; };
api.read((idArg == null) ? null : idArg.longValue(), resultCallback); api.read(idArg, resultCallback);
} }
catch (Error | RuntimeException exception) { catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception)); wrapped.put("error", wrapError(exception));
@ -888,7 +767,7 @@ public class Api {
Map<String, Object> wrapped = new HashMap<>(); Map<String, Object> wrapped = new HashMap<>();
try { try {
ArrayList<Object> args = (ArrayList<Object>)message; ArrayList<Object> args = (ArrayList<Object>)message;
Number idArg = (Number)args.get(0); String idArg = (String)args.get(0);
if (idArg == null) { if (idArg == null) {
throw new NullPointerException("idArg unexpectedly null."); throw new NullPointerException("idArg unexpectedly null.");
} }
@ -907,7 +786,7 @@ public class Api {
} }
}; };
api.write((idArg == null) ? null : idArg.longValue(), valueArg, resultCallback); api.write(idArg, valueArg, resultCallback);
} }
catch (Error | RuntimeException exception) { catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception)); wrapped.put("error", wrapError(exception));
@ -920,7 +799,7 @@ public class Api {
} }
} }
} }
private static Map<String, Object> wrapError(Throwable exception) { @NonNull private static Map<String, Object> wrapError(@NonNull Throwable exception) {
Map<String, Object> errorMap = new HashMap<>(); Map<String, Object> errorMap = new HashMap<>();
errorMap.put("message", exception.toString()); errorMap.put("message", exception.toString());
errorMap.put("code", exception.getClass().getSimpleName()); errorMap.put("code", exception.getClass().getSimpleName());

View File

@ -1,559 +0,0 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: proto/messages.proto
package dev.yanshouwang.bluetooth_low_energy.proto;
/**
* Protobuf type {@code proto.BluetoothLowEnergyException}
*/
public final class BluetoothLowEnergyException extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:proto.BluetoothLowEnergyException)
BluetoothLowEnergyExceptionOrBuilder {
private static final long serialVersionUID = 0L;
// Use BluetoothLowEnergyException.newBuilder() to construct.
private BluetoothLowEnergyException(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private BluetoothLowEnergyException() {
message_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new BluetoothLowEnergyException();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private BluetoothLowEnergyException(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
java.lang.String s = input.readStringRequireUtf8();
message_ = s;
break;
}
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return dev.yanshouwang.bluetooth_low_energy.proto.Messages.internal_static_proto_BluetoothLowEnergyException_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return dev.yanshouwang.bluetooth_low_energy.proto.Messages.internal_static_proto_BluetoothLowEnergyException_fieldAccessorTable
.ensureFieldAccessorsInitialized(
dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException.class, dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException.Builder.class);
}
public static final int MESSAGE_FIELD_NUMBER = 1;
private volatile java.lang.Object message_;
/**
* <code>string message = 1;</code>
* @return The message.
*/
@java.lang.Override
public java.lang.String getMessage() {
java.lang.Object ref = message_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
message_ = s;
return s;
}
}
/**
* <code>string message = 1;</code>
* @return The bytes for message.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getMessageBytes() {
java.lang.Object ref = message_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
message_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(message_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, message_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(message_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, message_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException)) {
return super.equals(obj);
}
dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException other = (dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException) obj;
if (!getMessage()
.equals(other.getMessage())) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + MESSAGE_FIELD_NUMBER;
hash = (53 * hash) + getMessage().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code proto.BluetoothLowEnergyException}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:proto.BluetoothLowEnergyException)
dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyExceptionOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return dev.yanshouwang.bluetooth_low_energy.proto.Messages.internal_static_proto_BluetoothLowEnergyException_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return dev.yanshouwang.bluetooth_low_energy.proto.Messages.internal_static_proto_BluetoothLowEnergyException_fieldAccessorTable
.ensureFieldAccessorsInitialized(
dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException.class, dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException.Builder.class);
}
// Construct using dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
@java.lang.Override
public Builder clear() {
super.clear();
message_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return dev.yanshouwang.bluetooth_low_energy.proto.Messages.internal_static_proto_BluetoothLowEnergyException_descriptor;
}
@java.lang.Override
public dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException getDefaultInstanceForType() {
return dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException.getDefaultInstance();
}
@java.lang.Override
public dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException build() {
dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException buildPartial() {
dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException result = new dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException(this);
result.message_ = message_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException) {
return mergeFrom((dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException other) {
if (other == dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException.getDefaultInstance()) return this;
if (!other.getMessage().isEmpty()) {
message_ = other.message_;
onChanged();
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object message_ = "";
/**
* <code>string message = 1;</code>
* @return The message.
*/
public java.lang.String getMessage() {
java.lang.Object ref = message_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
message_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>string message = 1;</code>
* @return The bytes for message.
*/
public com.google.protobuf.ByteString
getMessageBytes() {
java.lang.Object ref = message_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
message_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>string message = 1;</code>
* @param value The message to set.
* @return This builder for chaining.
*/
public Builder setMessage(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
message_ = value;
onChanged();
return this;
}
/**
* <code>string message = 1;</code>
* @return This builder for chaining.
*/
public Builder clearMessage() {
message_ = getDefaultInstance().getMessage();
onChanged();
return this;
}
/**
* <code>string message = 1;</code>
* @param value The bytes for message to set.
* @return This builder for chaining.
*/
public Builder setMessageBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
message_ = value;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:proto.BluetoothLowEnergyException)
}
// @@protoc_insertion_point(class_scope:proto.BluetoothLowEnergyException)
private static final dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException();
}
public static dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<BluetoothLowEnergyException>
PARSER = new com.google.protobuf.AbstractParser<BluetoothLowEnergyException>() {
@java.lang.Override
public BluetoothLowEnergyException parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new BluetoothLowEnergyException(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<BluetoothLowEnergyException> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<BluetoothLowEnergyException> getParserForType() {
return PARSER;
}
@java.lang.Override
public dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}

View File

@ -1,21 +0,0 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: proto/messages.proto
package dev.yanshouwang.bluetooth_low_energy.proto;
public interface BluetoothLowEnergyExceptionOrBuilder extends
// @@protoc_insertion_point(interface_extends:proto.BluetoothLowEnergyException)
com.google.protobuf.MessageOrBuilder {
/**
* <code>string message = 1;</code>
* @return The message.
*/
java.lang.String getMessage();
/**
* <code>string message = 1;</code>
* @return The bytes for message.
*/
com.google.protobuf.ByteString
getMessageBytes();
}

View File

@ -4,18 +4,18 @@
package dev.yanshouwang.bluetooth_low_energy.proto; package dev.yanshouwang.bluetooth_low_energy.proto;
/** /**
* Protobuf type {@code proto.Advertisement} * Protobuf type {@code proto.Broadcast}
*/ */
public final class Advertisement extends public final class Broadcast extends
com.google.protobuf.GeneratedMessageV3 implements com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:proto.Advertisement) // @@protoc_insertion_point(message_implements:proto.Broadcast)
AdvertisementOrBuilder { BroadcastOrBuilder {
private static final long serialVersionUID = 0L; private static final long serialVersionUID = 0L;
// Use Advertisement.newBuilder() to construct. // Use Broadcast.newBuilder() to construct.
private Advertisement(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { private Broadcast(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder); super(builder);
} }
private Advertisement() { private Broadcast() {
data_ = com.google.protobuf.ByteString.EMPTY; data_ = com.google.protobuf.ByteString.EMPTY;
localName_ = ""; localName_ = "";
manufacturerSpecificData_ = com.google.protobuf.ByteString.EMPTY; manufacturerSpecificData_ = com.google.protobuf.ByteString.EMPTY;
@ -28,7 +28,7 @@ private static final long serialVersionUID = 0L;
@SuppressWarnings({"unused"}) @SuppressWarnings({"unused"})
protected java.lang.Object newInstance( protected java.lang.Object newInstance(
UnusedPrivateParameter unused) { UnusedPrivateParameter unused) {
return new Advertisement(); return new Broadcast();
} }
@java.lang.Override @java.lang.Override
@ -36,7 +36,7 @@ private static final long serialVersionUID = 0L;
getUnknownFields() { getUnknownFields() {
return this.unknownFields; return this.unknownFields;
} }
private Advertisement( private Broadcast(
com.google.protobuf.CodedInputStream input, com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry) com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException { throws com.google.protobuf.InvalidProtocolBufferException {
@ -56,14 +56,14 @@ private static final long serialVersionUID = 0L;
done = true; done = true;
break; break;
case 10: { case 10: {
dev.yanshouwang.bluetooth_low_energy.proto.UUID.Builder subBuilder = null; dev.yanshouwang.bluetooth_low_energy.proto.Peripheral.Builder subBuilder = null;
if (uuid_ != null) { if (peripheral_ != null) {
subBuilder = uuid_.toBuilder(); subBuilder = peripheral_.toBuilder();
} }
uuid_ = input.readMessage(dev.yanshouwang.bluetooth_low_energy.proto.UUID.parser(), extensionRegistry); peripheral_ = input.readMessage(dev.yanshouwang.bluetooth_low_energy.proto.Peripheral.parser(), extensionRegistry);
if (subBuilder != null) { if (subBuilder != null) {
subBuilder.mergeFrom(uuid_); subBuilder.mergeFrom(peripheral_);
uuid_ = subBuilder.buildPartial(); peripheral_ = subBuilder.buildPartial();
} }
break; break;
@ -158,42 +158,42 @@ private static final long serialVersionUID = 0L;
} }
public static final com.google.protobuf.Descriptors.Descriptor public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() { getDescriptor() {
return dev.yanshouwang.bluetooth_low_energy.proto.Messages.internal_static_proto_Advertisement_descriptor; return dev.yanshouwang.bluetooth_low_energy.proto.Messages.internal_static_proto_Broadcast_descriptor;
} }
@java.lang.Override @java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() { internalGetFieldAccessorTable() {
return dev.yanshouwang.bluetooth_low_energy.proto.Messages.internal_static_proto_Advertisement_fieldAccessorTable return dev.yanshouwang.bluetooth_low_energy.proto.Messages.internal_static_proto_Broadcast_fieldAccessorTable
.ensureFieldAccessorsInitialized( .ensureFieldAccessorsInitialized(
dev.yanshouwang.bluetooth_low_energy.proto.Advertisement.class, dev.yanshouwang.bluetooth_low_energy.proto.Advertisement.Builder.class); dev.yanshouwang.bluetooth_low_energy.proto.Broadcast.class, dev.yanshouwang.bluetooth_low_energy.proto.Broadcast.Builder.class);
} }
private int bitField0_; private int bitField0_;
public static final int UUID_FIELD_NUMBER = 1; public static final int PERIPHERAL_FIELD_NUMBER = 1;
private dev.yanshouwang.bluetooth_low_energy.proto.UUID uuid_; private dev.yanshouwang.bluetooth_low_energy.proto.Peripheral peripheral_;
/** /**
* <code>.proto.UUID uuid = 1;</code> * <code>.proto.Peripheral peripheral = 1;</code>
* @return Whether the uuid field is set. * @return Whether the peripheral field is set.
*/ */
@java.lang.Override @java.lang.Override
public boolean hasUuid() { public boolean hasPeripheral() {
return uuid_ != null; return peripheral_ != null;
} }
/** /**
* <code>.proto.UUID uuid = 1;</code> * <code>.proto.Peripheral peripheral = 1;</code>
* @return The uuid. * @return The peripheral.
*/ */
@java.lang.Override @java.lang.Override
public dev.yanshouwang.bluetooth_low_energy.proto.UUID getUuid() { public dev.yanshouwang.bluetooth_low_energy.proto.Peripheral getPeripheral() {
return uuid_ == null ? dev.yanshouwang.bluetooth_low_energy.proto.UUID.getDefaultInstance() : uuid_; return peripheral_ == null ? dev.yanshouwang.bluetooth_low_energy.proto.Peripheral.getDefaultInstance() : peripheral_;
} }
/** /**
* <code>.proto.UUID uuid = 1;</code> * <code>.proto.Peripheral peripheral = 1;</code>
*/ */
@java.lang.Override @java.lang.Override
public dev.yanshouwang.bluetooth_low_energy.proto.UUIDOrBuilder getUuidOrBuilder() { public dev.yanshouwang.bluetooth_low_energy.proto.PeripheralOrBuilder getPeripheralOrBuilder() {
return getUuid(); return getPeripheral();
} }
public static final int RSSI_FIELD_NUMBER = 2; public static final int RSSI_FIELD_NUMBER = 2;
@ -447,8 +447,8 @@ private static final long serialVersionUID = 0L;
@java.lang.Override @java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException { throws java.io.IOException {
if (uuid_ != null) { if (peripheral_ != null) {
output.writeMessage(1, getUuid()); output.writeMessage(1, getPeripheral());
} }
if (rssi_ != 0) { if (rssi_ != 0) {
output.writeInt32(2, rssi_); output.writeInt32(2, rssi_);
@ -486,9 +486,9 @@ private static final long serialVersionUID = 0L;
if (size != -1) return size; if (size != -1) return size;
size = 0; size = 0;
if (uuid_ != null) { if (peripheral_ != null) {
size += com.google.protobuf.CodedOutputStream size += com.google.protobuf.CodedOutputStream
.computeMessageSize(1, getUuid()); .computeMessageSize(1, getPeripheral());
} }
if (rssi_ != 0) { if (rssi_ != 0) {
size += com.google.protobuf.CodedOutputStream size += com.google.protobuf.CodedOutputStream
@ -535,15 +535,15 @@ private static final long serialVersionUID = 0L;
if (obj == this) { if (obj == this) {
return true; return true;
} }
if (!(obj instanceof dev.yanshouwang.bluetooth_low_energy.proto.Advertisement)) { if (!(obj instanceof dev.yanshouwang.bluetooth_low_energy.proto.Broadcast)) {
return super.equals(obj); return super.equals(obj);
} }
dev.yanshouwang.bluetooth_low_energy.proto.Advertisement other = (dev.yanshouwang.bluetooth_low_energy.proto.Advertisement) obj; dev.yanshouwang.bluetooth_low_energy.proto.Broadcast other = (dev.yanshouwang.bluetooth_low_energy.proto.Broadcast) obj;
if (hasUuid() != other.hasUuid()) return false; if (hasPeripheral() != other.hasPeripheral()) return false;
if (hasUuid()) { if (hasPeripheral()) {
if (!getUuid() if (!getPeripheral()
.equals(other.getUuid())) return false; .equals(other.getPeripheral())) return false;
} }
if (getRssi() if (getRssi()
!= other.getRssi()) return false; != other.getRssi()) return false;
@ -583,9 +583,9 @@ private static final long serialVersionUID = 0L;
} }
int hash = 41; int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode(); hash = (19 * hash) + getDescriptor().hashCode();
if (hasUuid()) { if (hasPeripheral()) {
hash = (37 * hash) + UUID_FIELD_NUMBER; hash = (37 * hash) + PERIPHERAL_FIELD_NUMBER;
hash = (53 * hash) + getUuid().hashCode(); hash = (53 * hash) + getPeripheral().hashCode();
} }
hash = (37 * hash) + RSSI_FIELD_NUMBER; hash = (37 * hash) + RSSI_FIELD_NUMBER;
hash = (53 * hash) + getRssi(); hash = (53 * hash) + getRssi();
@ -623,69 +623,69 @@ private static final long serialVersionUID = 0L;
return hash; return hash;
} }
public static dev.yanshouwang.bluetooth_low_energy.proto.Advertisement parseFrom( public static dev.yanshouwang.bluetooth_low_energy.proto.Broadcast parseFrom(
java.nio.ByteBuffer data) java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException { throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data); return PARSER.parseFrom(data);
} }
public static dev.yanshouwang.bluetooth_low_energy.proto.Advertisement parseFrom( public static dev.yanshouwang.bluetooth_low_energy.proto.Broadcast parseFrom(
java.nio.ByteBuffer data, java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry) com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException { throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry); return PARSER.parseFrom(data, extensionRegistry);
} }
public static dev.yanshouwang.bluetooth_low_energy.proto.Advertisement parseFrom( public static dev.yanshouwang.bluetooth_low_energy.proto.Broadcast parseFrom(
com.google.protobuf.ByteString data) com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException { throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data); return PARSER.parseFrom(data);
} }
public static dev.yanshouwang.bluetooth_low_energy.proto.Advertisement parseFrom( public static dev.yanshouwang.bluetooth_low_energy.proto.Broadcast parseFrom(
com.google.protobuf.ByteString data, com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry) com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException { throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry); return PARSER.parseFrom(data, extensionRegistry);
} }
public static dev.yanshouwang.bluetooth_low_energy.proto.Advertisement parseFrom(byte[] data) public static dev.yanshouwang.bluetooth_low_energy.proto.Broadcast parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException { throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data); return PARSER.parseFrom(data);
} }
public static dev.yanshouwang.bluetooth_low_energy.proto.Advertisement parseFrom( public static dev.yanshouwang.bluetooth_low_energy.proto.Broadcast parseFrom(
byte[] data, byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry) com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException { throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry); return PARSER.parseFrom(data, extensionRegistry);
} }
public static dev.yanshouwang.bluetooth_low_energy.proto.Advertisement parseFrom(java.io.InputStream input) public static dev.yanshouwang.bluetooth_low_energy.proto.Broadcast parseFrom(java.io.InputStream input)
throws java.io.IOException { throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3 return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input); .parseWithIOException(PARSER, input);
} }
public static dev.yanshouwang.bluetooth_low_energy.proto.Advertisement parseFrom( public static dev.yanshouwang.bluetooth_low_energy.proto.Broadcast parseFrom(
java.io.InputStream input, java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry) com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException { throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3 return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry); .parseWithIOException(PARSER, input, extensionRegistry);
} }
public static dev.yanshouwang.bluetooth_low_energy.proto.Advertisement parseDelimitedFrom(java.io.InputStream input) public static dev.yanshouwang.bluetooth_low_energy.proto.Broadcast parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException { throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3 return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input); .parseDelimitedWithIOException(PARSER, input);
} }
public static dev.yanshouwang.bluetooth_low_energy.proto.Advertisement parseDelimitedFrom( public static dev.yanshouwang.bluetooth_low_energy.proto.Broadcast parseDelimitedFrom(
java.io.InputStream input, java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry) com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException { throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3 return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry); .parseDelimitedWithIOException(PARSER, input, extensionRegistry);
} }
public static dev.yanshouwang.bluetooth_low_energy.proto.Advertisement parseFrom( public static dev.yanshouwang.bluetooth_low_energy.proto.Broadcast parseFrom(
com.google.protobuf.CodedInputStream input) com.google.protobuf.CodedInputStream input)
throws java.io.IOException { throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3 return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input); .parseWithIOException(PARSER, input);
} }
public static dev.yanshouwang.bluetooth_low_energy.proto.Advertisement parseFrom( public static dev.yanshouwang.bluetooth_low_energy.proto.Broadcast parseFrom(
com.google.protobuf.CodedInputStream input, com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry) com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException { throws java.io.IOException {
@ -698,7 +698,7 @@ private static final long serialVersionUID = 0L;
public static Builder newBuilder() { public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder(); return DEFAULT_INSTANCE.toBuilder();
} }
public static Builder newBuilder(dev.yanshouwang.bluetooth_low_energy.proto.Advertisement prototype) { public static Builder newBuilder(dev.yanshouwang.bluetooth_low_energy.proto.Broadcast prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
} }
@java.lang.Override @java.lang.Override
@ -714,26 +714,26 @@ private static final long serialVersionUID = 0L;
return builder; return builder;
} }
/** /**
* Protobuf type {@code proto.Advertisement} * Protobuf type {@code proto.Broadcast}
*/ */
public static final class Builder extends public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:proto.Advertisement) // @@protoc_insertion_point(builder_implements:proto.Broadcast)
dev.yanshouwang.bluetooth_low_energy.proto.AdvertisementOrBuilder { dev.yanshouwang.bluetooth_low_energy.proto.BroadcastOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() { getDescriptor() {
return dev.yanshouwang.bluetooth_low_energy.proto.Messages.internal_static_proto_Advertisement_descriptor; return dev.yanshouwang.bluetooth_low_energy.proto.Messages.internal_static_proto_Broadcast_descriptor;
} }
@java.lang.Override @java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() { internalGetFieldAccessorTable() {
return dev.yanshouwang.bluetooth_low_energy.proto.Messages.internal_static_proto_Advertisement_fieldAccessorTable return dev.yanshouwang.bluetooth_low_energy.proto.Messages.internal_static_proto_Broadcast_fieldAccessorTable
.ensureFieldAccessorsInitialized( .ensureFieldAccessorsInitialized(
dev.yanshouwang.bluetooth_low_energy.proto.Advertisement.class, dev.yanshouwang.bluetooth_low_energy.proto.Advertisement.Builder.class); dev.yanshouwang.bluetooth_low_energy.proto.Broadcast.class, dev.yanshouwang.bluetooth_low_energy.proto.Broadcast.Builder.class);
} }
// Construct using dev.yanshouwang.bluetooth_low_energy.proto.Advertisement.newBuilder() // Construct using dev.yanshouwang.bluetooth_low_energy.proto.Broadcast.newBuilder()
private Builder() { private Builder() {
maybeForceBuilderInitialization(); maybeForceBuilderInitialization();
} }
@ -754,11 +754,11 @@ private static final long serialVersionUID = 0L;
@java.lang.Override @java.lang.Override
public Builder clear() { public Builder clear() {
super.clear(); super.clear();
if (uuidBuilder_ == null) { if (peripheralBuilder_ == null) {
uuid_ = null; peripheral_ = null;
} else { } else {
uuid_ = null; peripheral_ = null;
uuidBuilder_ = null; peripheralBuilder_ = null;
} }
rssi_ = 0; rssi_ = 0;
@ -796,17 +796,17 @@ private static final long serialVersionUID = 0L;
@java.lang.Override @java.lang.Override
public com.google.protobuf.Descriptors.Descriptor public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() { getDescriptorForType() {
return dev.yanshouwang.bluetooth_low_energy.proto.Messages.internal_static_proto_Advertisement_descriptor; return dev.yanshouwang.bluetooth_low_energy.proto.Messages.internal_static_proto_Broadcast_descriptor;
} }
@java.lang.Override @java.lang.Override
public dev.yanshouwang.bluetooth_low_energy.proto.Advertisement getDefaultInstanceForType() { public dev.yanshouwang.bluetooth_low_energy.proto.Broadcast getDefaultInstanceForType() {
return dev.yanshouwang.bluetooth_low_energy.proto.Advertisement.getDefaultInstance(); return dev.yanshouwang.bluetooth_low_energy.proto.Broadcast.getDefaultInstance();
} }
@java.lang.Override @java.lang.Override
public dev.yanshouwang.bluetooth_low_energy.proto.Advertisement build() { public dev.yanshouwang.bluetooth_low_energy.proto.Broadcast build() {
dev.yanshouwang.bluetooth_low_energy.proto.Advertisement result = buildPartial(); dev.yanshouwang.bluetooth_low_energy.proto.Broadcast result = buildPartial();
if (!result.isInitialized()) { if (!result.isInitialized()) {
throw newUninitializedMessageException(result); throw newUninitializedMessageException(result);
} }
@ -814,14 +814,14 @@ private static final long serialVersionUID = 0L;
} }
@java.lang.Override @java.lang.Override
public dev.yanshouwang.bluetooth_low_energy.proto.Advertisement buildPartial() { public dev.yanshouwang.bluetooth_low_energy.proto.Broadcast buildPartial() {
dev.yanshouwang.bluetooth_low_energy.proto.Advertisement result = new dev.yanshouwang.bluetooth_low_energy.proto.Advertisement(this); dev.yanshouwang.bluetooth_low_energy.proto.Broadcast result = new dev.yanshouwang.bluetooth_low_energy.proto.Broadcast(this);
int from_bitField0_ = bitField0_; int from_bitField0_ = bitField0_;
int to_bitField0_ = 0; int to_bitField0_ = 0;
if (uuidBuilder_ == null) { if (peripheralBuilder_ == null) {
result.uuid_ = uuid_; result.peripheral_ = peripheral_;
} else { } else {
result.uuid_ = uuidBuilder_.build(); result.peripheral_ = peripheralBuilder_.build();
} }
result.rssi_ = rssi_; result.rssi_ = rssi_;
if (((from_bitField0_ & 0x00000001) != 0)) { if (((from_bitField0_ & 0x00000001) != 0)) {
@ -904,18 +904,18 @@ private static final long serialVersionUID = 0L;
} }
@java.lang.Override @java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) { public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof dev.yanshouwang.bluetooth_low_energy.proto.Advertisement) { if (other instanceof dev.yanshouwang.bluetooth_low_energy.proto.Broadcast) {
return mergeFrom((dev.yanshouwang.bluetooth_low_energy.proto.Advertisement)other); return mergeFrom((dev.yanshouwang.bluetooth_low_energy.proto.Broadcast)other);
} else { } else {
super.mergeFrom(other); super.mergeFrom(other);
return this; return this;
} }
} }
public Builder mergeFrom(dev.yanshouwang.bluetooth_low_energy.proto.Advertisement other) { public Builder mergeFrom(dev.yanshouwang.bluetooth_low_energy.proto.Broadcast other) {
if (other == dev.yanshouwang.bluetooth_low_energy.proto.Advertisement.getDefaultInstance()) return this; if (other == dev.yanshouwang.bluetooth_low_energy.proto.Broadcast.getDefaultInstance()) return this;
if (other.hasUuid()) { if (other.hasPeripheral()) {
mergeUuid(other.getUuid()); mergePeripheral(other.getPeripheral());
} }
if (other.getRssi() != 0) { if (other.getRssi() != 0) {
setRssi(other.getRssi()); setRssi(other.getRssi());
@ -1030,11 +1030,11 @@ private static final long serialVersionUID = 0L;
com.google.protobuf.CodedInputStream input, com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry) com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException { throws java.io.IOException {
dev.yanshouwang.bluetooth_low_energy.proto.Advertisement parsedMessage = null; dev.yanshouwang.bluetooth_low_energy.proto.Broadcast parsedMessage = null;
try { try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) { } catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (dev.yanshouwang.bluetooth_low_energy.proto.Advertisement) e.getUnfinishedMessage(); parsedMessage = (dev.yanshouwang.bluetooth_low_energy.proto.Broadcast) e.getUnfinishedMessage();
throw e.unwrapIOException(); throw e.unwrapIOException();
} finally { } finally {
if (parsedMessage != null) { if (parsedMessage != null) {
@ -1045,123 +1045,123 @@ private static final long serialVersionUID = 0L;
} }
private int bitField0_; private int bitField0_;
private dev.yanshouwang.bluetooth_low_energy.proto.UUID uuid_; private dev.yanshouwang.bluetooth_low_energy.proto.Peripheral peripheral_;
private com.google.protobuf.SingleFieldBuilderV3< private com.google.protobuf.SingleFieldBuilderV3<
dev.yanshouwang.bluetooth_low_energy.proto.UUID, dev.yanshouwang.bluetooth_low_energy.proto.UUID.Builder, dev.yanshouwang.bluetooth_low_energy.proto.UUIDOrBuilder> uuidBuilder_; dev.yanshouwang.bluetooth_low_energy.proto.Peripheral, dev.yanshouwang.bluetooth_low_energy.proto.Peripheral.Builder, dev.yanshouwang.bluetooth_low_energy.proto.PeripheralOrBuilder> peripheralBuilder_;
/** /**
* <code>.proto.UUID uuid = 1;</code> * <code>.proto.Peripheral peripheral = 1;</code>
* @return Whether the uuid field is set. * @return Whether the peripheral field is set.
*/ */
public boolean hasUuid() { public boolean hasPeripheral() {
return uuidBuilder_ != null || uuid_ != null; return peripheralBuilder_ != null || peripheral_ != null;
} }
/** /**
* <code>.proto.UUID uuid = 1;</code> * <code>.proto.Peripheral peripheral = 1;</code>
* @return The uuid. * @return The peripheral.
*/ */
public dev.yanshouwang.bluetooth_low_energy.proto.UUID getUuid() { public dev.yanshouwang.bluetooth_low_energy.proto.Peripheral getPeripheral() {
if (uuidBuilder_ == null) { if (peripheralBuilder_ == null) {
return uuid_ == null ? dev.yanshouwang.bluetooth_low_energy.proto.UUID.getDefaultInstance() : uuid_; return peripheral_ == null ? dev.yanshouwang.bluetooth_low_energy.proto.Peripheral.getDefaultInstance() : peripheral_;
} else { } else {
return uuidBuilder_.getMessage(); return peripheralBuilder_.getMessage();
} }
} }
/** /**
* <code>.proto.UUID uuid = 1;</code> * <code>.proto.Peripheral peripheral = 1;</code>
*/ */
public Builder setUuid(dev.yanshouwang.bluetooth_low_energy.proto.UUID value) { public Builder setPeripheral(dev.yanshouwang.bluetooth_low_energy.proto.Peripheral value) {
if (uuidBuilder_ == null) { if (peripheralBuilder_ == null) {
if (value == null) { if (value == null) {
throw new NullPointerException(); throw new NullPointerException();
} }
uuid_ = value; peripheral_ = value;
onChanged(); onChanged();
} else { } else {
uuidBuilder_.setMessage(value); peripheralBuilder_.setMessage(value);
} }
return this; return this;
} }
/** /**
* <code>.proto.UUID uuid = 1;</code> * <code>.proto.Peripheral peripheral = 1;</code>
*/ */
public Builder setUuid( public Builder setPeripheral(
dev.yanshouwang.bluetooth_low_energy.proto.UUID.Builder builderForValue) { dev.yanshouwang.bluetooth_low_energy.proto.Peripheral.Builder builderForValue) {
if (uuidBuilder_ == null) { if (peripheralBuilder_ == null) {
uuid_ = builderForValue.build(); peripheral_ = builderForValue.build();
onChanged(); onChanged();
} else { } else {
uuidBuilder_.setMessage(builderForValue.build()); peripheralBuilder_.setMessage(builderForValue.build());
} }
return this; return this;
} }
/** /**
* <code>.proto.UUID uuid = 1;</code> * <code>.proto.Peripheral peripheral = 1;</code>
*/ */
public Builder mergeUuid(dev.yanshouwang.bluetooth_low_energy.proto.UUID value) { public Builder mergePeripheral(dev.yanshouwang.bluetooth_low_energy.proto.Peripheral value) {
if (uuidBuilder_ == null) { if (peripheralBuilder_ == null) {
if (uuid_ != null) { if (peripheral_ != null) {
uuid_ = peripheral_ =
dev.yanshouwang.bluetooth_low_energy.proto.UUID.newBuilder(uuid_).mergeFrom(value).buildPartial(); dev.yanshouwang.bluetooth_low_energy.proto.Peripheral.newBuilder(peripheral_).mergeFrom(value).buildPartial();
} else { } else {
uuid_ = value; peripheral_ = value;
} }
onChanged(); onChanged();
} else { } else {
uuidBuilder_.mergeFrom(value); peripheralBuilder_.mergeFrom(value);
} }
return this; return this;
} }
/** /**
* <code>.proto.UUID uuid = 1;</code> * <code>.proto.Peripheral peripheral = 1;</code>
*/ */
public Builder clearUuid() { public Builder clearPeripheral() {
if (uuidBuilder_ == null) { if (peripheralBuilder_ == null) {
uuid_ = null; peripheral_ = null;
onChanged(); onChanged();
} else { } else {
uuid_ = null; peripheral_ = null;
uuidBuilder_ = null; peripheralBuilder_ = null;
} }
return this; return this;
} }
/** /**
* <code>.proto.UUID uuid = 1;</code> * <code>.proto.Peripheral peripheral = 1;</code>
*/ */
public dev.yanshouwang.bluetooth_low_energy.proto.UUID.Builder getUuidBuilder() { public dev.yanshouwang.bluetooth_low_energy.proto.Peripheral.Builder getPeripheralBuilder() {
onChanged(); onChanged();
return getUuidFieldBuilder().getBuilder(); return getPeripheralFieldBuilder().getBuilder();
} }
/** /**
* <code>.proto.UUID uuid = 1;</code> * <code>.proto.Peripheral peripheral = 1;</code>
*/ */
public dev.yanshouwang.bluetooth_low_energy.proto.UUIDOrBuilder getUuidOrBuilder() { public dev.yanshouwang.bluetooth_low_energy.proto.PeripheralOrBuilder getPeripheralOrBuilder() {
if (uuidBuilder_ != null) { if (peripheralBuilder_ != null) {
return uuidBuilder_.getMessageOrBuilder(); return peripheralBuilder_.getMessageOrBuilder();
} else { } else {
return uuid_ == null ? return peripheral_ == null ?
dev.yanshouwang.bluetooth_low_energy.proto.UUID.getDefaultInstance() : uuid_; dev.yanshouwang.bluetooth_low_energy.proto.Peripheral.getDefaultInstance() : peripheral_;
} }
} }
/** /**
* <code>.proto.UUID uuid = 1;</code> * <code>.proto.Peripheral peripheral = 1;</code>
*/ */
private com.google.protobuf.SingleFieldBuilderV3< private com.google.protobuf.SingleFieldBuilderV3<
dev.yanshouwang.bluetooth_low_energy.proto.UUID, dev.yanshouwang.bluetooth_low_energy.proto.UUID.Builder, dev.yanshouwang.bluetooth_low_energy.proto.UUIDOrBuilder> dev.yanshouwang.bluetooth_low_energy.proto.Peripheral, dev.yanshouwang.bluetooth_low_energy.proto.Peripheral.Builder, dev.yanshouwang.bluetooth_low_energy.proto.PeripheralOrBuilder>
getUuidFieldBuilder() { getPeripheralFieldBuilder() {
if (uuidBuilder_ == null) { if (peripheralBuilder_ == null) {
uuidBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< peripheralBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
dev.yanshouwang.bluetooth_low_energy.proto.UUID, dev.yanshouwang.bluetooth_low_energy.proto.UUID.Builder, dev.yanshouwang.bluetooth_low_energy.proto.UUIDOrBuilder>( dev.yanshouwang.bluetooth_low_energy.proto.Peripheral, dev.yanshouwang.bluetooth_low_energy.proto.Peripheral.Builder, dev.yanshouwang.bluetooth_low_energy.proto.PeripheralOrBuilder>(
getUuid(), getPeripheral(),
getParentForChildren(), getParentForChildren(),
isClean()); isClean());
uuid_ = null; peripheral_ = null;
} }
return uuidBuilder_; return peripheralBuilder_;
} }
private int rssi_ ; private int rssi_ ;
@ -2156,41 +2156,41 @@ private static final long serialVersionUID = 0L;
} }
// @@protoc_insertion_point(builder_scope:proto.Advertisement) // @@protoc_insertion_point(builder_scope:proto.Broadcast)
} }
// @@protoc_insertion_point(class_scope:proto.Advertisement) // @@protoc_insertion_point(class_scope:proto.Broadcast)
private static final dev.yanshouwang.bluetooth_low_energy.proto.Advertisement DEFAULT_INSTANCE; private static final dev.yanshouwang.bluetooth_low_energy.proto.Broadcast DEFAULT_INSTANCE;
static { static {
DEFAULT_INSTANCE = new dev.yanshouwang.bluetooth_low_energy.proto.Advertisement(); DEFAULT_INSTANCE = new dev.yanshouwang.bluetooth_low_energy.proto.Broadcast();
} }
public static dev.yanshouwang.bluetooth_low_energy.proto.Advertisement getDefaultInstance() { public static dev.yanshouwang.bluetooth_low_energy.proto.Broadcast getDefaultInstance() {
return DEFAULT_INSTANCE; return DEFAULT_INSTANCE;
} }
private static final com.google.protobuf.Parser<Advertisement> private static final com.google.protobuf.Parser<Broadcast>
PARSER = new com.google.protobuf.AbstractParser<Advertisement>() { PARSER = new com.google.protobuf.AbstractParser<Broadcast>() {
@java.lang.Override @java.lang.Override
public Advertisement parsePartialFrom( public Broadcast parsePartialFrom(
com.google.protobuf.CodedInputStream input, com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry) com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException { throws com.google.protobuf.InvalidProtocolBufferException {
return new Advertisement(input, extensionRegistry); return new Broadcast(input, extensionRegistry);
} }
}; };
public static com.google.protobuf.Parser<Advertisement> parser() { public static com.google.protobuf.Parser<Broadcast> parser() {
return PARSER; return PARSER;
} }
@java.lang.Override @java.lang.Override
public com.google.protobuf.Parser<Advertisement> getParserForType() { public com.google.protobuf.Parser<Broadcast> getParserForType() {
return PARSER; return PARSER;
} }
@java.lang.Override @java.lang.Override
public dev.yanshouwang.bluetooth_low_energy.proto.Advertisement getDefaultInstanceForType() { public dev.yanshouwang.bluetooth_low_energy.proto.Broadcast getDefaultInstanceForType() {
return DEFAULT_INSTANCE; return DEFAULT_INSTANCE;
} }

View File

@ -3,24 +3,24 @@
package dev.yanshouwang.bluetooth_low_energy.proto; package dev.yanshouwang.bluetooth_low_energy.proto;
public interface AdvertisementOrBuilder extends public interface BroadcastOrBuilder extends
// @@protoc_insertion_point(interface_extends:proto.Advertisement) // @@protoc_insertion_point(interface_extends:proto.Broadcast)
com.google.protobuf.MessageOrBuilder { com.google.protobuf.MessageOrBuilder {
/** /**
* <code>.proto.UUID uuid = 1;</code> * <code>.proto.Peripheral peripheral = 1;</code>
* @return Whether the uuid field is set. * @return Whether the peripheral field is set.
*/ */
boolean hasUuid(); boolean hasPeripheral();
/** /**
* <code>.proto.UUID uuid = 1;</code> * <code>.proto.Peripheral peripheral = 1;</code>
* @return The uuid. * @return The peripheral.
*/ */
dev.yanshouwang.bluetooth_low_energy.proto.UUID getUuid(); dev.yanshouwang.bluetooth_low_energy.proto.Peripheral getPeripheral();
/** /**
* <code>.proto.UUID uuid = 1;</code> * <code>.proto.Peripheral peripheral = 1;</code>
*/ */
dev.yanshouwang.bluetooth_low_energy.proto.UUIDOrBuilder getUuidOrBuilder(); dev.yanshouwang.bluetooth_low_energy.proto.PeripheralOrBuilder getPeripheralOrBuilder();
/** /**
* <code>int32 rssi = 2;</code> * <code>int32 rssi = 2;</code>

View File

@ -16,6 +16,7 @@ private static final long serialVersionUID = 0L;
super(builder); super(builder);
} }
private GattCharacteristic() { private GattCharacteristic() {
id_ = "";
} }
@java.lang.Override @java.lang.Override
@ -48,9 +49,10 @@ private static final long serialVersionUID = 0L;
case 0: case 0:
done = true; done = true;
break; break;
case 8: { case 10: {
java.lang.String s = input.readStringRequireUtf8();
id_ = input.readInt64(); id_ = s;
break; break;
} }
case 18: { case 18: {
@ -121,14 +123,41 @@ private static final long serialVersionUID = 0L;
} }
public static final int ID_FIELD_NUMBER = 1; public static final int ID_FIELD_NUMBER = 1;
private long id_; private volatile java.lang.Object id_;
/** /**
* <code>int64 id = 1;</code> * <code>string id = 1;</code>
* @return The id. * @return The id.
*/ */
@java.lang.Override @java.lang.Override
public long getId() { public java.lang.String getId() {
return id_; java.lang.Object ref = id_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
id_ = s;
return s;
}
}
/**
* <code>string id = 1;</code>
* @return The bytes for id.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getIdBytes() {
java.lang.Object ref = id_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
id_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
} }
public static final int UUID_FIELD_NUMBER = 2; public static final int UUID_FIELD_NUMBER = 2;
@ -215,8 +244,8 @@ private static final long serialVersionUID = 0L;
@java.lang.Override @java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException { throws java.io.IOException {
if (id_ != 0L) { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(id_)) {
output.writeInt64(1, id_); com.google.protobuf.GeneratedMessageV3.writeString(output, 1, id_);
} }
if (uuid_ != null) { if (uuid_ != null) {
output.writeMessage(2, getUuid()); output.writeMessage(2, getUuid());
@ -242,9 +271,8 @@ private static final long serialVersionUID = 0L;
if (size != -1) return size; if (size != -1) return size;
size = 0; size = 0;
if (id_ != 0L) { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(id_)) {
size += com.google.protobuf.CodedOutputStream size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, id_);
.computeInt64Size(1, id_);
} }
if (uuid_ != null) { if (uuid_ != null) {
size += com.google.protobuf.CodedOutputStream size += com.google.protobuf.CodedOutputStream
@ -281,8 +309,8 @@ private static final long serialVersionUID = 0L;
} }
dev.yanshouwang.bluetooth_low_energy.proto.GattCharacteristic other = (dev.yanshouwang.bluetooth_low_energy.proto.GattCharacteristic) obj; dev.yanshouwang.bluetooth_low_energy.proto.GattCharacteristic other = (dev.yanshouwang.bluetooth_low_energy.proto.GattCharacteristic) obj;
if (getId() if (!getId()
!= other.getId()) return false; .equals(other.getId())) return false;
if (hasUuid() != other.hasUuid()) return false; if (hasUuid() != other.hasUuid()) return false;
if (hasUuid()) { if (hasUuid()) {
if (!getUuid() if (!getUuid()
@ -308,8 +336,7 @@ private static final long serialVersionUID = 0L;
int hash = 41; int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode(); hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + ID_FIELD_NUMBER; hash = (37 * hash) + ID_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong( hash = (53 * hash) + getId().hashCode();
getId());
if (hasUuid()) { if (hasUuid()) {
hash = (37 * hash) + UUID_FIELD_NUMBER; hash = (37 * hash) + UUID_FIELD_NUMBER;
hash = (53 * hash) + getUuid().hashCode(); hash = (53 * hash) + getUuid().hashCode();
@ -459,7 +486,7 @@ private static final long serialVersionUID = 0L;
@java.lang.Override @java.lang.Override
public Builder clear() { public Builder clear() {
super.clear(); super.clear();
id_ = 0L; id_ = "";
if (uuidBuilder_ == null) { if (uuidBuilder_ == null) {
uuid_ = null; uuid_ = null;
@ -559,8 +586,9 @@ private static final long serialVersionUID = 0L;
public Builder mergeFrom(dev.yanshouwang.bluetooth_low_energy.proto.GattCharacteristic other) { public Builder mergeFrom(dev.yanshouwang.bluetooth_low_energy.proto.GattCharacteristic other) {
if (other == dev.yanshouwang.bluetooth_low_energy.proto.GattCharacteristic.getDefaultInstance()) return this; if (other == dev.yanshouwang.bluetooth_low_energy.proto.GattCharacteristic.getDefaultInstance()) return this;
if (other.getId() != 0L) { if (!other.getId().isEmpty()) {
setId(other.getId()); id_ = other.id_;
onChanged();
} }
if (other.hasUuid()) { if (other.hasUuid()) {
mergeUuid(other.getUuid()); mergeUuid(other.getUuid());
@ -606,33 +634,78 @@ private static final long serialVersionUID = 0L;
return this; return this;
} }
private long id_ ; private java.lang.Object id_ = "";
/** /**
* <code>int64 id = 1;</code> * <code>string id = 1;</code>
* @return The id. * @return The id.
*/ */
@java.lang.Override public java.lang.String getId() {
public long getId() { java.lang.Object ref = id_;
return id_; if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
id_ = s;
return s;
} else {
return (java.lang.String) ref;
}
} }
/** /**
* <code>int64 id = 1;</code> * <code>string id = 1;</code>
* @return The bytes for id.
*/
public com.google.protobuf.ByteString
getIdBytes() {
java.lang.Object ref = id_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
id_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>string id = 1;</code>
* @param value The id to set. * @param value The id to set.
* @return This builder for chaining. * @return This builder for chaining.
*/ */
public Builder setId(long value) { public Builder setId(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
id_ = value; id_ = value;
onChanged(); onChanged();
return this; return this;
} }
/** /**
* <code>int64 id = 1;</code> * <code>string id = 1;</code>
* @return This builder for chaining. * @return This builder for chaining.
*/ */
public Builder clearId() { public Builder clearId() {
id_ = 0L; id_ = getDefaultInstance().getId();
onChanged();
return this;
}
/**
* <code>string id = 1;</code>
* @param value The bytes for id to set.
* @return This builder for chaining.
*/
public Builder setIdBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
id_ = value;
onChanged(); onChanged();
return this; return this;
} }

View File

@ -8,10 +8,16 @@ public interface GattCharacteristicOrBuilder extends
com.google.protobuf.MessageOrBuilder { com.google.protobuf.MessageOrBuilder {
/** /**
* <code>int64 id = 1;</code> * <code>string id = 1;</code>
* @return The id. * @return The id.
*/ */
long getId(); java.lang.String getId();
/**
* <code>string id = 1;</code>
* @return The bytes for id.
*/
com.google.protobuf.ByteString
getIdBytes();
/** /**
* <code>.proto.UUID uuid = 2;</code> * <code>.proto.UUID uuid = 2;</code>

View File

@ -16,6 +16,7 @@ private static final long serialVersionUID = 0L;
super(builder); super(builder);
} }
private GattDescriptor() { private GattDescriptor() {
id_ = "";
} }
@java.lang.Override @java.lang.Override
@ -48,9 +49,10 @@ private static final long serialVersionUID = 0L;
case 0: case 0:
done = true; done = true;
break; break;
case 8: { case 10: {
java.lang.String s = input.readStringRequireUtf8();
id_ = input.readInt64(); id_ = s;
break; break;
} }
case 18: { case 18: {
@ -101,14 +103,41 @@ private static final long serialVersionUID = 0L;
} }
public static final int ID_FIELD_NUMBER = 1; public static final int ID_FIELD_NUMBER = 1;
private long id_; private volatile java.lang.Object id_;
/** /**
* <code>int64 id = 1;</code> * <code>string id = 1;</code>
* @return The id. * @return The id.
*/ */
@java.lang.Override @java.lang.Override
public long getId() { public java.lang.String getId() {
return id_; java.lang.Object ref = id_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
id_ = s;
return s;
}
}
/**
* <code>string id = 1;</code>
* @return The bytes for id.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getIdBytes() {
java.lang.Object ref = id_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
id_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
} }
public static final int UUID_FIELD_NUMBER = 2; public static final int UUID_FIELD_NUMBER = 2;
@ -151,8 +180,8 @@ private static final long serialVersionUID = 0L;
@java.lang.Override @java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException { throws java.io.IOException {
if (id_ != 0L) { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(id_)) {
output.writeInt64(1, id_); com.google.protobuf.GeneratedMessageV3.writeString(output, 1, id_);
} }
if (uuid_ != null) { if (uuid_ != null) {
output.writeMessage(2, getUuid()); output.writeMessage(2, getUuid());
@ -166,9 +195,8 @@ private static final long serialVersionUID = 0L;
if (size != -1) return size; if (size != -1) return size;
size = 0; size = 0;
if (id_ != 0L) { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(id_)) {
size += com.google.protobuf.CodedOutputStream size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, id_);
.computeInt64Size(1, id_);
} }
if (uuid_ != null) { if (uuid_ != null) {
size += com.google.protobuf.CodedOutputStream size += com.google.protobuf.CodedOutputStream
@ -189,8 +217,8 @@ private static final long serialVersionUID = 0L;
} }
dev.yanshouwang.bluetooth_low_energy.proto.GattDescriptor other = (dev.yanshouwang.bluetooth_low_energy.proto.GattDescriptor) obj; dev.yanshouwang.bluetooth_low_energy.proto.GattDescriptor other = (dev.yanshouwang.bluetooth_low_energy.proto.GattDescriptor) obj;
if (getId() if (!getId()
!= other.getId()) return false; .equals(other.getId())) return false;
if (hasUuid() != other.hasUuid()) return false; if (hasUuid() != other.hasUuid()) return false;
if (hasUuid()) { if (hasUuid()) {
if (!getUuid() if (!getUuid()
@ -208,8 +236,7 @@ private static final long serialVersionUID = 0L;
int hash = 41; int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode(); hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + ID_FIELD_NUMBER; hash = (37 * hash) + ID_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong( hash = (53 * hash) + getId().hashCode();
getId());
if (hasUuid()) { if (hasUuid()) {
hash = (37 * hash) + UUID_FIELD_NUMBER; hash = (37 * hash) + UUID_FIELD_NUMBER;
hash = (53 * hash) + getUuid().hashCode(); hash = (53 * hash) + getUuid().hashCode();
@ -347,7 +374,7 @@ private static final long serialVersionUID = 0L;
@java.lang.Override @java.lang.Override
public Builder clear() { public Builder clear() {
super.clear(); super.clear();
id_ = 0L; id_ = "";
if (uuidBuilder_ == null) { if (uuidBuilder_ == null) {
uuid_ = null; uuid_ = null;
@ -435,8 +462,9 @@ private static final long serialVersionUID = 0L;
public Builder mergeFrom(dev.yanshouwang.bluetooth_low_energy.proto.GattDescriptor other) { public Builder mergeFrom(dev.yanshouwang.bluetooth_low_energy.proto.GattDescriptor other) {
if (other == dev.yanshouwang.bluetooth_low_energy.proto.GattDescriptor.getDefaultInstance()) return this; if (other == dev.yanshouwang.bluetooth_low_energy.proto.GattDescriptor.getDefaultInstance()) return this;
if (other.getId() != 0L) { if (!other.getId().isEmpty()) {
setId(other.getId()); id_ = other.id_;
onChanged();
} }
if (other.hasUuid()) { if (other.hasUuid()) {
mergeUuid(other.getUuid()); mergeUuid(other.getUuid());
@ -470,33 +498,78 @@ private static final long serialVersionUID = 0L;
return this; return this;
} }
private long id_ ; private java.lang.Object id_ = "";
/** /**
* <code>int64 id = 1;</code> * <code>string id = 1;</code>
* @return The id. * @return The id.
*/ */
@java.lang.Override public java.lang.String getId() {
public long getId() { java.lang.Object ref = id_;
return id_; if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
id_ = s;
return s;
} else {
return (java.lang.String) ref;
}
} }
/** /**
* <code>int64 id = 1;</code> * <code>string id = 1;</code>
* @return The bytes for id.
*/
public com.google.protobuf.ByteString
getIdBytes() {
java.lang.Object ref = id_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
id_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>string id = 1;</code>
* @param value The id to set. * @param value The id to set.
* @return This builder for chaining. * @return This builder for chaining.
*/ */
public Builder setId(long value) { public Builder setId(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
id_ = value; id_ = value;
onChanged(); onChanged();
return this; return this;
} }
/** /**
* <code>int64 id = 1;</code> * <code>string id = 1;</code>
* @return This builder for chaining. * @return This builder for chaining.
*/ */
public Builder clearId() { public Builder clearId() {
id_ = 0L; id_ = getDefaultInstance().getId();
onChanged();
return this;
}
/**
* <code>string id = 1;</code>
* @param value The bytes for id to set.
* @return This builder for chaining.
*/
public Builder setIdBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
id_ = value;
onChanged(); onChanged();
return this; return this;
} }

View File

@ -8,10 +8,16 @@ public interface GattDescriptorOrBuilder extends
com.google.protobuf.MessageOrBuilder { com.google.protobuf.MessageOrBuilder {
/** /**
* <code>int64 id = 1;</code> * <code>string id = 1;</code>
* @return The id. * @return The id.
*/ */
long getId(); java.lang.String getId();
/**
* <code>string id = 1;</code>
* @return The bytes for id.
*/
com.google.protobuf.ByteString
getIdBytes();
/** /**
* <code>.proto.UUID uuid = 2;</code> * <code>.proto.UUID uuid = 2;</code>

View File

@ -16,6 +16,7 @@ private static final long serialVersionUID = 0L;
super(builder); super(builder);
} }
private GattService() { private GattService() {
id_ = "";
} }
@java.lang.Override @java.lang.Override
@ -48,9 +49,10 @@ private static final long serialVersionUID = 0L;
case 0: case 0:
done = true; done = true;
break; break;
case 8: { case 10: {
java.lang.String s = input.readStringRequireUtf8();
id_ = input.readInt64(); id_ = s;
break; break;
} }
case 18: { case 18: {
@ -101,14 +103,41 @@ private static final long serialVersionUID = 0L;
} }
public static final int ID_FIELD_NUMBER = 1; public static final int ID_FIELD_NUMBER = 1;
private long id_; private volatile java.lang.Object id_;
/** /**
* <code>int64 id = 1;</code> * <code>string id = 1;</code>
* @return The id. * @return The id.
*/ */
@java.lang.Override @java.lang.Override
public long getId() { public java.lang.String getId() {
return id_; java.lang.Object ref = id_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
id_ = s;
return s;
}
}
/**
* <code>string id = 1;</code>
* @return The bytes for id.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getIdBytes() {
java.lang.Object ref = id_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
id_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
} }
public static final int UUID_FIELD_NUMBER = 2; public static final int UUID_FIELD_NUMBER = 2;
@ -151,8 +180,8 @@ private static final long serialVersionUID = 0L;
@java.lang.Override @java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException { throws java.io.IOException {
if (id_ != 0L) { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(id_)) {
output.writeInt64(1, id_); com.google.protobuf.GeneratedMessageV3.writeString(output, 1, id_);
} }
if (uuid_ != null) { if (uuid_ != null) {
output.writeMessage(2, getUuid()); output.writeMessage(2, getUuid());
@ -166,9 +195,8 @@ private static final long serialVersionUID = 0L;
if (size != -1) return size; if (size != -1) return size;
size = 0; size = 0;
if (id_ != 0L) { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(id_)) {
size += com.google.protobuf.CodedOutputStream size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, id_);
.computeInt64Size(1, id_);
} }
if (uuid_ != null) { if (uuid_ != null) {
size += com.google.protobuf.CodedOutputStream size += com.google.protobuf.CodedOutputStream
@ -189,8 +217,8 @@ private static final long serialVersionUID = 0L;
} }
dev.yanshouwang.bluetooth_low_energy.proto.GattService other = (dev.yanshouwang.bluetooth_low_energy.proto.GattService) obj; dev.yanshouwang.bluetooth_low_energy.proto.GattService other = (dev.yanshouwang.bluetooth_low_energy.proto.GattService) obj;
if (getId() if (!getId()
!= other.getId()) return false; .equals(other.getId())) return false;
if (hasUuid() != other.hasUuid()) return false; if (hasUuid() != other.hasUuid()) return false;
if (hasUuid()) { if (hasUuid()) {
if (!getUuid() if (!getUuid()
@ -208,8 +236,7 @@ private static final long serialVersionUID = 0L;
int hash = 41; int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode(); hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + ID_FIELD_NUMBER; hash = (37 * hash) + ID_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong( hash = (53 * hash) + getId().hashCode();
getId());
if (hasUuid()) { if (hasUuid()) {
hash = (37 * hash) + UUID_FIELD_NUMBER; hash = (37 * hash) + UUID_FIELD_NUMBER;
hash = (53 * hash) + getUuid().hashCode(); hash = (53 * hash) + getUuid().hashCode();
@ -347,7 +374,7 @@ private static final long serialVersionUID = 0L;
@java.lang.Override @java.lang.Override
public Builder clear() { public Builder clear() {
super.clear(); super.clear();
id_ = 0L; id_ = "";
if (uuidBuilder_ == null) { if (uuidBuilder_ == null) {
uuid_ = null; uuid_ = null;
@ -435,8 +462,9 @@ private static final long serialVersionUID = 0L;
public Builder mergeFrom(dev.yanshouwang.bluetooth_low_energy.proto.GattService other) { public Builder mergeFrom(dev.yanshouwang.bluetooth_low_energy.proto.GattService other) {
if (other == dev.yanshouwang.bluetooth_low_energy.proto.GattService.getDefaultInstance()) return this; if (other == dev.yanshouwang.bluetooth_low_energy.proto.GattService.getDefaultInstance()) return this;
if (other.getId() != 0L) { if (!other.getId().isEmpty()) {
setId(other.getId()); id_ = other.id_;
onChanged();
} }
if (other.hasUuid()) { if (other.hasUuid()) {
mergeUuid(other.getUuid()); mergeUuid(other.getUuid());
@ -470,33 +498,78 @@ private static final long serialVersionUID = 0L;
return this; return this;
} }
private long id_ ; private java.lang.Object id_ = "";
/** /**
* <code>int64 id = 1;</code> * <code>string id = 1;</code>
* @return The id. * @return The id.
*/ */
@java.lang.Override public java.lang.String getId() {
public long getId() { java.lang.Object ref = id_;
return id_; if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
id_ = s;
return s;
} else {
return (java.lang.String) ref;
}
} }
/** /**
* <code>int64 id = 1;</code> * <code>string id = 1;</code>
* @return The bytes for id.
*/
public com.google.protobuf.ByteString
getIdBytes() {
java.lang.Object ref = id_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
id_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>string id = 1;</code>
* @param value The id to set. * @param value The id to set.
* @return This builder for chaining. * @return This builder for chaining.
*/ */
public Builder setId(long value) { public Builder setId(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
id_ = value; id_ = value;
onChanged(); onChanged();
return this; return this;
} }
/** /**
* <code>int64 id = 1;</code> * <code>string id = 1;</code>
* @return This builder for chaining. * @return This builder for chaining.
*/ */
public Builder clearId() { public Builder clearId() {
id_ = 0L; id_ = getDefaultInstance().getId();
onChanged();
return this;
}
/**
* <code>string id = 1;</code>
* @param value The bytes for id to set.
* @return This builder for chaining.
*/
public Builder setIdBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
id_ = value;
onChanged(); onChanged();
return this; return this;
} }

View File

@ -8,10 +8,16 @@ public interface GattServiceOrBuilder extends
com.google.protobuf.MessageOrBuilder { com.google.protobuf.MessageOrBuilder {
/** /**
* <code>int64 id = 1;</code> * <code>string id = 1;</code>
* @return The id. * @return The id.
*/ */
long getId(); java.lang.String getId();
/**
* <code>string id = 1;</code>
* @return The bytes for id.
*/
com.google.protobuf.ByteString
getIdBytes();
/** /**
* <code>.proto.UUID uuid = 2;</code> * <code>.proto.UUID uuid = 2;</code>

View File

@ -15,10 +15,10 @@ public final class Messages {
(com.google.protobuf.ExtensionRegistryLite) registry); (com.google.protobuf.ExtensionRegistryLite) registry);
} }
static final com.google.protobuf.Descriptors.Descriptor static final com.google.protobuf.Descriptors.Descriptor
internal_static_proto_Advertisement_descriptor; internal_static_proto_Broadcast_descriptor;
static final static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_proto_Advertisement_fieldAccessorTable; internal_static_proto_Broadcast_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor static final com.google.protobuf.Descriptors.Descriptor
internal_static_proto_Peripheral_descriptor; internal_static_proto_Peripheral_descriptor;
static final static final
@ -49,11 +49,6 @@ public final class Messages {
static final static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_proto_ServiceData_fieldAccessorTable; internal_static_proto_ServiceData_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_proto_BluetoothLowEnergyException_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_proto_BluetoothLowEnergyException_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() { getDescriptor() {
@ -63,49 +58,48 @@ public final class Messages {
descriptor; descriptor;
static { static {
java.lang.String[] descriptorData = { java.lang.String[] descriptorData = {
"\n\024proto/messages.proto\022\005proto\"\351\002\n\rAdvert" + "\n\024proto/messages.proto\022\005proto\"\361\002\n\tBroadc" +
"isement\022\031\n\004uuid\030\001 \001(\0132\013.proto.UUID\022\014\n\004rs" + "ast\022%\n\nperipheral\030\001 \001(\0132\021.proto.Peripher" +
"si\030\002 \001(\005\022\030\n\013connectable\030\003 \001(\010H\000\210\001\001\022\014\n\004da" + "al\022\014\n\004rssi\030\002 \001(\005\022\030\n\013connectable\030\003 \001(\010H\000\210" +
"ta\030\004 \001(\014\022\027\n\nlocal_name\030\005 \001(\tH\001\210\001\001\022\"\n\032man" + "\001\001\022\014\n\004data\030\004 \001(\014\022\027\n\nlocal_name\030\005 \001(\tH\001\210\001" +
"ufacturer_specific_data\030\006 \001(\014\022)\n\rservice" + "\001\022\"\n\032manufacturer_specific_data\030\006 \001(\014\022)\n" +
"_datas\030\007 \003(\0132\022.proto.ServiceData\022\"\n\rserv" + "\rservice_datas\030\007 \003(\0132\022.proto.ServiceData" +
"ice_uuids\030\010 \003(\0132\013.proto.UUID\022,\n\027solicite" + "\022\"\n\rservice_uuids\030\010 \003(\0132\013.proto.UUID\022,\n\027" +
"d_service_uuids\030\t \003(\0132\013.proto.UUID\022\033\n\016tx" + "solicited_service_uuids\030\t \003(\0132\013.proto.UU" +
"_power_level\030\n \001(\005H\002\210\001\001B\016\n\014_connectableB" + "ID\022\033\n\016tx_power_level\030\n \001(\005H\002\210\001\001B\016\n\014_conn" +
"\r\n\013_local_nameB\021\n\017_tx_power_level\"6\n\nPer" + "ectableB\r\n\013_local_nameB\021\n\017_tx_power_leve" +
"ipheral\022\n\n\002id\030\001 \001(\003\022\034\n\024maximum_write_len" + "l\"3\n\nPeripheral\022\n\n\002id\030\001 \001(\t\022\031\n\004uuid\030\002 \001(" +
"gth\030\002 \001(\005\"4\n\013GattService\022\n\n\002id\030\001 \001(\003\022\031\n\004" + "\0132\013.proto.UUID\"4\n\013GattService\022\n\n\002id\030\001 \001(" +
"uuid\030\002 \001(\0132\013.proto.UUID\"\230\001\n\022GattCharacte" + "\t\022\031\n\004uuid\030\002 \001(\0132\013.proto.UUID\"\230\001\n\022GattCha" +
"ristic\022\n\n\002id\030\001 \001(\003\022\031\n\004uuid\030\002 \001(\0132\013.proto" + "racteristic\022\n\n\002id\030\001 \001(\t\022\031\n\004uuid\030\002 \001(\0132\013." +
".UUID\022\020\n\010can_read\030\003 \001(\010\022\021\n\tcan_write\030\004 \001" + "proto.UUID\022\020\n\010can_read\030\003 \001(\010\022\021\n\tcan_writ" +
"(\010\022\"\n\032can_write_without_response\030\005 \001(\010\022\022" + "e\030\004 \001(\010\022\"\n\032can_write_without_response\030\005 " +
"\n\ncan_notify\030\006 \001(\010\"7\n\016GattDescriptor\022\n\n\002" + "\001(\010\022\022\n\ncan_notify\030\006 \001(\010\"7\n\016GattDescripto" +
"id\030\001 \001(\003\022\031\n\004uuid\030\002 \001(\0132\013.proto.UUID\"\025\n\004U" + "r\022\n\n\002id\030\001 \001(\t\022\031\n\004uuid\030\002 \001(\0132\013.proto.UUID" +
"UID\022\r\n\005value\030\001 \001(\t\"6\n\013ServiceData\022\031\n\004uui" + "\"\025\n\004UUID\022\r\n\005value\030\001 \001(\t\"6\n\013ServiceData\022\031" +
"d\030\001 \001(\0132\013.proto.UUID\022\014\n\004data\030\002 \001(\014\".\n\033Bl" + "\n\004uuid\030\001 \001(\0132\013.proto.UUID\022\014\n\004data\030\002 \001(\014*" +
"uetoothLowEnergyException\022\017\n\007message\030\001 \001" + "r\n\016BluetoothState\022\037\n\033BLUETOOTH_STATE_UNS" +
"(\t*r\n\016BluetoothState\022\037\n\033BLUETOOTH_STATE_" + "UPPORTED\020\000\022\037\n\033BLUETOOTH_STATE_POWERED_OF" +
"UNSUPPORTED\020\000\022\037\n\033BLUETOOTH_STATE_POWERED" + "F\020\001\022\036\n\032BLUETOOTH_STATE_POWERED_ON\020\002B.\n*d" +
"_OFF\020\001\022\036\n\032BLUETOOTH_STATE_POWERED_ON\020\002B." + "ev.yanshouwang.bluetooth_low_energy.prot" +
"\n*dev.yanshouwang.bluetooth_low_energy.p" + "oP\001b\006proto3"
"rotoP\001b\006proto3"
}; };
descriptor = com.google.protobuf.Descriptors.FileDescriptor descriptor = com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData, .internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] { new com.google.protobuf.Descriptors.FileDescriptor[] {
}); });
internal_static_proto_Advertisement_descriptor = internal_static_proto_Broadcast_descriptor =
getDescriptor().getMessageTypes().get(0); getDescriptor().getMessageTypes().get(0);
internal_static_proto_Advertisement_fieldAccessorTable = new internal_static_proto_Broadcast_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_proto_Advertisement_descriptor, internal_static_proto_Broadcast_descriptor,
new java.lang.String[] { "Uuid", "Rssi", "Connectable", "Data", "LocalName", "ManufacturerSpecificData", "ServiceDatas", "ServiceUuids", "SolicitedServiceUuids", "TxPowerLevel", "Connectable", "LocalName", "TxPowerLevel", }); new java.lang.String[] { "Peripheral", "Rssi", "Connectable", "Data", "LocalName", "ManufacturerSpecificData", "ServiceDatas", "ServiceUuids", "SolicitedServiceUuids", "TxPowerLevel", "Connectable", "LocalName", "TxPowerLevel", });
internal_static_proto_Peripheral_descriptor = internal_static_proto_Peripheral_descriptor =
getDescriptor().getMessageTypes().get(1); getDescriptor().getMessageTypes().get(1);
internal_static_proto_Peripheral_fieldAccessorTable = new internal_static_proto_Peripheral_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_proto_Peripheral_descriptor, internal_static_proto_Peripheral_descriptor,
new java.lang.String[] { "Id", "MaximumWriteLength", }); new java.lang.String[] { "Id", "Uuid", });
internal_static_proto_GattService_descriptor = internal_static_proto_GattService_descriptor =
getDescriptor().getMessageTypes().get(2); getDescriptor().getMessageTypes().get(2);
internal_static_proto_GattService_fieldAccessorTable = new internal_static_proto_GattService_fieldAccessorTable = new
@ -136,12 +130,6 @@ public final class Messages {
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_proto_ServiceData_descriptor, internal_static_proto_ServiceData_descriptor,
new java.lang.String[] { "Uuid", "Data", }); new java.lang.String[] { "Uuid", "Data", });
internal_static_proto_BluetoothLowEnergyException_descriptor =
getDescriptor().getMessageTypes().get(7);
internal_static_proto_BluetoothLowEnergyException_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_proto_BluetoothLowEnergyException_descriptor,
new java.lang.String[] { "Message", });
} }
// @@protoc_insertion_point(outer_class_scope) // @@protoc_insertion_point(outer_class_scope)

View File

@ -16,6 +16,7 @@ private static final long serialVersionUID = 0L;
super(builder); super(builder);
} }
private Peripheral() { private Peripheral() {
id_ = "";
} }
@java.lang.Override @java.lang.Override
@ -48,14 +49,23 @@ private static final long serialVersionUID = 0L;
case 0: case 0:
done = true; done = true;
break; break;
case 8: { case 10: {
java.lang.String s = input.readStringRequireUtf8();
id_ = input.readInt64(); id_ = s;
break; break;
} }
case 16: { case 18: {
dev.yanshouwang.bluetooth_low_energy.proto.UUID.Builder subBuilder = null;
if (uuid_ != null) {
subBuilder = uuid_.toBuilder();
}
uuid_ = input.readMessage(dev.yanshouwang.bluetooth_low_energy.proto.UUID.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(uuid_);
uuid_ = subBuilder.buildPartial();
}
maximumWriteLength_ = input.readInt32();
break; break;
} }
default: { default: {
@ -93,25 +103,67 @@ private static final long serialVersionUID = 0L;
} }
public static final int ID_FIELD_NUMBER = 1; public static final int ID_FIELD_NUMBER = 1;
private long id_; private volatile java.lang.Object id_;
/** /**
* <code>int64 id = 1;</code> * <code>string id = 1;</code>
* @return The id. * @return The id.
*/ */
@java.lang.Override @java.lang.Override
public long getId() { public java.lang.String getId() {
return id_; java.lang.Object ref = id_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
id_ = s;
return s;
}
} }
public static final int MAXIMUM_WRITE_LENGTH_FIELD_NUMBER = 2;
private int maximumWriteLength_;
/** /**
* <code>int32 maximum_write_length = 2;</code> * <code>string id = 1;</code>
* @return The maximumWriteLength. * @return The bytes for id.
*/ */
@java.lang.Override @java.lang.Override
public int getMaximumWriteLength() { public com.google.protobuf.ByteString
return maximumWriteLength_; getIdBytes() {
java.lang.Object ref = id_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
id_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int UUID_FIELD_NUMBER = 2;
private dev.yanshouwang.bluetooth_low_energy.proto.UUID uuid_;
/**
* <code>.proto.UUID uuid = 2;</code>
* @return Whether the uuid field is set.
*/
@java.lang.Override
public boolean hasUuid() {
return uuid_ != null;
}
/**
* <code>.proto.UUID uuid = 2;</code>
* @return The uuid.
*/
@java.lang.Override
public dev.yanshouwang.bluetooth_low_energy.proto.UUID getUuid() {
return uuid_ == null ? dev.yanshouwang.bluetooth_low_energy.proto.UUID.getDefaultInstance() : uuid_;
}
/**
* <code>.proto.UUID uuid = 2;</code>
*/
@java.lang.Override
public dev.yanshouwang.bluetooth_low_energy.proto.UUIDOrBuilder getUuidOrBuilder() {
return getUuid();
} }
private byte memoizedIsInitialized = -1; private byte memoizedIsInitialized = -1;
@ -128,11 +180,11 @@ private static final long serialVersionUID = 0L;
@java.lang.Override @java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException { throws java.io.IOException {
if (id_ != 0L) { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(id_)) {
output.writeInt64(1, id_); com.google.protobuf.GeneratedMessageV3.writeString(output, 1, id_);
} }
if (maximumWriteLength_ != 0) { if (uuid_ != null) {
output.writeInt32(2, maximumWriteLength_); output.writeMessage(2, getUuid());
} }
unknownFields.writeTo(output); unknownFields.writeTo(output);
} }
@ -143,13 +195,12 @@ private static final long serialVersionUID = 0L;
if (size != -1) return size; if (size != -1) return size;
size = 0; size = 0;
if (id_ != 0L) { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(id_)) {
size += com.google.protobuf.CodedOutputStream size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, id_);
.computeInt64Size(1, id_);
} }
if (maximumWriteLength_ != 0) { if (uuid_ != null) {
size += com.google.protobuf.CodedOutputStream size += com.google.protobuf.CodedOutputStream
.computeInt32Size(2, maximumWriteLength_); .computeMessageSize(2, getUuid());
} }
size += unknownFields.getSerializedSize(); size += unknownFields.getSerializedSize();
memoizedSize = size; memoizedSize = size;
@ -166,10 +217,13 @@ private static final long serialVersionUID = 0L;
} }
dev.yanshouwang.bluetooth_low_energy.proto.Peripheral other = (dev.yanshouwang.bluetooth_low_energy.proto.Peripheral) obj; dev.yanshouwang.bluetooth_low_energy.proto.Peripheral other = (dev.yanshouwang.bluetooth_low_energy.proto.Peripheral) obj;
if (getId() if (!getId()
!= other.getId()) return false; .equals(other.getId())) return false;
if (getMaximumWriteLength() if (hasUuid() != other.hasUuid()) return false;
!= other.getMaximumWriteLength()) return false; if (hasUuid()) {
if (!getUuid()
.equals(other.getUuid())) return false;
}
if (!unknownFields.equals(other.unknownFields)) return false; if (!unknownFields.equals(other.unknownFields)) return false;
return true; return true;
} }
@ -182,10 +236,11 @@ private static final long serialVersionUID = 0L;
int hash = 41; int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode(); hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + ID_FIELD_NUMBER; hash = (37 * hash) + ID_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong( hash = (53 * hash) + getId().hashCode();
getId()); if (hasUuid()) {
hash = (37 * hash) + MAXIMUM_WRITE_LENGTH_FIELD_NUMBER; hash = (37 * hash) + UUID_FIELD_NUMBER;
hash = (53 * hash) + getMaximumWriteLength(); hash = (53 * hash) + getUuid().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode(); hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash; memoizedHashCode = hash;
return hash; return hash;
@ -319,10 +374,14 @@ private static final long serialVersionUID = 0L;
@java.lang.Override @java.lang.Override
public Builder clear() { public Builder clear() {
super.clear(); super.clear();
id_ = 0L; id_ = "";
maximumWriteLength_ = 0;
if (uuidBuilder_ == null) {
uuid_ = null;
} else {
uuid_ = null;
uuidBuilder_ = null;
}
return this; return this;
} }
@ -350,7 +409,11 @@ private static final long serialVersionUID = 0L;
public dev.yanshouwang.bluetooth_low_energy.proto.Peripheral buildPartial() { public dev.yanshouwang.bluetooth_low_energy.proto.Peripheral buildPartial() {
dev.yanshouwang.bluetooth_low_energy.proto.Peripheral result = new dev.yanshouwang.bluetooth_low_energy.proto.Peripheral(this); dev.yanshouwang.bluetooth_low_energy.proto.Peripheral result = new dev.yanshouwang.bluetooth_low_energy.proto.Peripheral(this);
result.id_ = id_; result.id_ = id_;
result.maximumWriteLength_ = maximumWriteLength_; if (uuidBuilder_ == null) {
result.uuid_ = uuid_;
} else {
result.uuid_ = uuidBuilder_.build();
}
onBuilt(); onBuilt();
return result; return result;
} }
@ -399,11 +462,12 @@ private static final long serialVersionUID = 0L;
public Builder mergeFrom(dev.yanshouwang.bluetooth_low_energy.proto.Peripheral other) { public Builder mergeFrom(dev.yanshouwang.bluetooth_low_energy.proto.Peripheral other) {
if (other == dev.yanshouwang.bluetooth_low_energy.proto.Peripheral.getDefaultInstance()) return this; if (other == dev.yanshouwang.bluetooth_low_energy.proto.Peripheral.getDefaultInstance()) return this;
if (other.getId() != 0L) { if (!other.getId().isEmpty()) {
setId(other.getId()); id_ = other.id_;
onChanged();
} }
if (other.getMaximumWriteLength() != 0) { if (other.hasUuid()) {
setMaximumWriteLength(other.getMaximumWriteLength()); mergeUuid(other.getUuid());
} }
this.mergeUnknownFields(other.unknownFields); this.mergeUnknownFields(other.unknownFields);
onChanged(); onChanged();
@ -434,67 +498,200 @@ private static final long serialVersionUID = 0L;
return this; return this;
} }
private long id_ ; private java.lang.Object id_ = "";
/** /**
* <code>int64 id = 1;</code> * <code>string id = 1;</code>
* @return The id. * @return The id.
*/ */
@java.lang.Override public java.lang.String getId() {
public long getId() { java.lang.Object ref = id_;
return id_; if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
id_ = s;
return s;
} else {
return (java.lang.String) ref;
}
} }
/** /**
* <code>int64 id = 1;</code> * <code>string id = 1;</code>
* @return The bytes for id.
*/
public com.google.protobuf.ByteString
getIdBytes() {
java.lang.Object ref = id_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
id_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>string id = 1;</code>
* @param value The id to set. * @param value The id to set.
* @return This builder for chaining. * @return This builder for chaining.
*/ */
public Builder setId(long value) { public Builder setId(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
id_ = value; id_ = value;
onChanged(); onChanged();
return this; return this;
} }
/** /**
* <code>int64 id = 1;</code> * <code>string id = 1;</code>
* @return This builder for chaining. * @return This builder for chaining.
*/ */
public Builder clearId() { public Builder clearId() {
id_ = 0L; id_ = getDefaultInstance().getId();
onChanged(); onChanged();
return this; return this;
} }
private int maximumWriteLength_ ;
/** /**
* <code>int32 maximum_write_length = 2;</code> * <code>string id = 1;</code>
* @return The maximumWriteLength. * @param value The bytes for id to set.
*/
@java.lang.Override
public int getMaximumWriteLength() {
return maximumWriteLength_;
}
/**
* <code>int32 maximum_write_length = 2;</code>
* @param value The maximumWriteLength to set.
* @return This builder for chaining. * @return This builder for chaining.
*/ */
public Builder setMaximumWriteLength(int value) { public Builder setIdBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
maximumWriteLength_ = value; id_ = value;
onChanged(); onChanged();
return this; return this;
} }
/**
* <code>int32 maximum_write_length = 2;</code>
* @return This builder for chaining.
*/
public Builder clearMaximumWriteLength() {
maximumWriteLength_ = 0; private dev.yanshouwang.bluetooth_low_energy.proto.UUID uuid_;
private com.google.protobuf.SingleFieldBuilderV3<
dev.yanshouwang.bluetooth_low_energy.proto.UUID, dev.yanshouwang.bluetooth_low_energy.proto.UUID.Builder, dev.yanshouwang.bluetooth_low_energy.proto.UUIDOrBuilder> uuidBuilder_;
/**
* <code>.proto.UUID uuid = 2;</code>
* @return Whether the uuid field is set.
*/
public boolean hasUuid() {
return uuidBuilder_ != null || uuid_ != null;
}
/**
* <code>.proto.UUID uuid = 2;</code>
* @return The uuid.
*/
public dev.yanshouwang.bluetooth_low_energy.proto.UUID getUuid() {
if (uuidBuilder_ == null) {
return uuid_ == null ? dev.yanshouwang.bluetooth_low_energy.proto.UUID.getDefaultInstance() : uuid_;
} else {
return uuidBuilder_.getMessage();
}
}
/**
* <code>.proto.UUID uuid = 2;</code>
*/
public Builder setUuid(dev.yanshouwang.bluetooth_low_energy.proto.UUID value) {
if (uuidBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
uuid_ = value;
onChanged(); onChanged();
} else {
uuidBuilder_.setMessage(value);
}
return this; return this;
} }
/**
* <code>.proto.UUID uuid = 2;</code>
*/
public Builder setUuid(
dev.yanshouwang.bluetooth_low_energy.proto.UUID.Builder builderForValue) {
if (uuidBuilder_ == null) {
uuid_ = builderForValue.build();
onChanged();
} else {
uuidBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <code>.proto.UUID uuid = 2;</code>
*/
public Builder mergeUuid(dev.yanshouwang.bluetooth_low_energy.proto.UUID value) {
if (uuidBuilder_ == null) {
if (uuid_ != null) {
uuid_ =
dev.yanshouwang.bluetooth_low_energy.proto.UUID.newBuilder(uuid_).mergeFrom(value).buildPartial();
} else {
uuid_ = value;
}
onChanged();
} else {
uuidBuilder_.mergeFrom(value);
}
return this;
}
/**
* <code>.proto.UUID uuid = 2;</code>
*/
public Builder clearUuid() {
if (uuidBuilder_ == null) {
uuid_ = null;
onChanged();
} else {
uuid_ = null;
uuidBuilder_ = null;
}
return this;
}
/**
* <code>.proto.UUID uuid = 2;</code>
*/
public dev.yanshouwang.bluetooth_low_energy.proto.UUID.Builder getUuidBuilder() {
onChanged();
return getUuidFieldBuilder().getBuilder();
}
/**
* <code>.proto.UUID uuid = 2;</code>
*/
public dev.yanshouwang.bluetooth_low_energy.proto.UUIDOrBuilder getUuidOrBuilder() {
if (uuidBuilder_ != null) {
return uuidBuilder_.getMessageOrBuilder();
} else {
return uuid_ == null ?
dev.yanshouwang.bluetooth_low_energy.proto.UUID.getDefaultInstance() : uuid_;
}
}
/**
* <code>.proto.UUID uuid = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
dev.yanshouwang.bluetooth_low_energy.proto.UUID, dev.yanshouwang.bluetooth_low_energy.proto.UUID.Builder, dev.yanshouwang.bluetooth_low_energy.proto.UUIDOrBuilder>
getUuidFieldBuilder() {
if (uuidBuilder_ == null) {
uuidBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
dev.yanshouwang.bluetooth_low_energy.proto.UUID, dev.yanshouwang.bluetooth_low_energy.proto.UUID.Builder, dev.yanshouwang.bluetooth_low_energy.proto.UUIDOrBuilder>(
getUuid(),
getParentForChildren(),
isClean());
uuid_ = null;
}
return uuidBuilder_;
}
@java.lang.Override @java.lang.Override
public final Builder setUnknownFields( public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) { final com.google.protobuf.UnknownFieldSet unknownFields) {

View File

@ -8,14 +8,29 @@ public interface PeripheralOrBuilder extends
com.google.protobuf.MessageOrBuilder { com.google.protobuf.MessageOrBuilder {
/** /**
* <code>int64 id = 1;</code> * <code>string id = 1;</code>
* @return The id. * @return The id.
*/ */
long getId(); java.lang.String getId();
/**
* <code>string id = 1;</code>
* @return The bytes for id.
*/
com.google.protobuf.ByteString
getIdBytes();
/** /**
* <code>int32 maximum_write_length = 2;</code> * <code>.proto.UUID uuid = 2;</code>
* @return The maximumWriteLength. * @return Whether the uuid field is set.
*/ */
int getMaximumWriteLength(); boolean hasUuid();
/**
* <code>.proto.UUID uuid = 2;</code>
* @return The uuid.
*/
dev.yanshouwang.bluetooth_low_energy.proto.UUID getUuid();
/**
* <code>.proto.UUID uuid = 2;</code>
*/
dev.yanshouwang.bluetooth_low_energy.proto.UUIDOrBuilder getUuidOrBuilder();
} }

View File

@ -5,50 +5,56 @@ import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager import android.bluetooth.BluetoothManager
import android.bluetooth.le.ScanRecord import android.bluetooth.le.ScanRecord
import android.content.Context import android.content.Context
import android.content.IntentFilter
import android.content.pm.PackageManager import android.content.pm.PackageManager
import android.os.Handler import android.os.Handler
import androidx.annotation.NonNull import android.util.Log
import androidx.core.content.ContextCompat import androidx.core.content.ContextCompat
import dev.yanshouwang.bluetooth_low_energy.pigeon.Api
import dev.yanshouwang.bluetooth_low_energy.proto.BluetoothState import dev.yanshouwang.bluetooth_low_energy.proto.BluetoothState
import dev.yanshouwang.bluetooth_low_energy.proto.UUID
import dev.yanshouwang.bluetooth_low_energy.proto.uUID
import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import java.util.concurrent.Executor import java.util.concurrent.Executor
import dev.yanshouwang.bluetooth_low_energy.pigeon.Messages as Pigeon
/** BluetoothLowEnergyPlugin */ /** BluetoothLowEnergyPlugin */
class BluetoothLowEnergyPlugin : FlutterPlugin, ActivityAware { class BluetoothLowEnergyPlugin : FlutterPlugin, ActivityAware {
override fun onAttachedToEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) { override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
val binaryMessenger = binding.binaryMessenger val binaryMessenger = binding.binaryMessenger
items[KEY_CENTRAL_MANAGER_FLUTTER_API] = Api.CentralManagerFlutterApi(binaryMessenger) instances[KEY_CENTRAL_MANAGER_FLUTTER_API] = Pigeon.CentralManagerFlutterApi(binaryMessenger)
items[KEY_PERIPHERAL_FLUTTER_API] = Api.PeripheralFlutterApi(binaryMessenger) instances[KEY_PERIPHERAL_FLUTTER_API] = Pigeon.PeripheralFlutterApi(binaryMessenger)
items[KEY_GATT_CHARACTERISTIC_FLUTTER_API] = Api.GattCharacteristicFlutterApi(binaryMessenger) instances[KEY_GATT_CHARACTERISTIC_FLUTTER_API] = Pigeon.GattCharacteristicFlutterApi(binaryMessenger)
Api.CentralManagerHostApi.setup(binaryMessenger, MyCentralManagerHostApi) Pigeon.CentralManagerHostApi.setup(binaryMessenger, MyCentralManagerHostApi)
Api.PeripheralHostApi.setup(binaryMessenger, MyPeripheralHostApi) Pigeon.PeripheralHostApi.setup(binaryMessenger, MyPeripheralHostApi)
Api.GattServiceHostApi.setup(binaryMessenger, MyGattServiceHostApi) Pigeon.GattServiceHostApi.setup(binaryMessenger, MyGattServiceHostApi)
Api.GattCharacteristicHostApi.setup(binaryMessenger, MyGattCharacteristicHostApi) Pigeon.GattCharacteristicHostApi.setup(binaryMessenger, MyGattCharacteristicHostApi)
Api.GattDescriptorHostApi.setup(binaryMessenger, MyGattDescriptorHostApi) Pigeon.GattDescriptorHostApi.setup(binaryMessenger, MyGattDescriptorHostApi)
} }
override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) { override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
val binaryMessenger = binding.binaryMessenger val binaryMessenger = binding.binaryMessenger
items.remove(KEY_CENTRAL_MANAGER_FLUTTER_API) instances.remove(KEY_CENTRAL_MANAGER_FLUTTER_API)
items.remove(KEY_PERIPHERAL_FLUTTER_API) instances.remove(KEY_PERIPHERAL_FLUTTER_API)
items.remove(KEY_GATT_CHARACTERISTIC_FLUTTER_API) instances.remove(KEY_GATT_CHARACTERISTIC_FLUTTER_API)
Api.CentralManagerHostApi.setup(binaryMessenger, null) Pigeon.CentralManagerHostApi.setup(binaryMessenger, null)
Api.PeripheralHostApi.setup(binaryMessenger, null) Pigeon.PeripheralHostApi.setup(binaryMessenger, null)
Api.GattServiceHostApi.setup(binaryMessenger, null) Pigeon.GattServiceHostApi.setup(binaryMessenger, null)
Api.GattCharacteristicHostApi.setup(binaryMessenger, null) Pigeon.GattCharacteristicHostApi.setup(binaryMessenger, null)
Api.GattDescriptorHostApi.setup(binaryMessenger, null) Pigeon.GattDescriptorHostApi.setup(binaryMessenger, null)
} }
override fun onAttachedToActivity(binding: ActivityPluginBinding) { override fun onAttachedToActivity(binding: ActivityPluginBinding) {
items[KEY_ACTIVITY_PLUGIN_BINDING] = binding instances[KEY_ACTIVITY_PLUGIN_BINDING] = binding
binding.addRequestPermissionsResultListener(MyRequestPermissionsResultListener) binding.addRequestPermissionsResultListener(MyRequestPermissionsResultListener)
// Register the central manager state changed receiver.
val filter = IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED)
activity.registerReceiver(MyBroadcastReceiver, filter)
} }
override fun onDetachedFromActivityForConfigChanges() { override fun onDetachedFromActivityForConfigChanges() {
@ -60,7 +66,10 @@ class BluetoothLowEnergyPlugin : FlutterPlugin, ActivityAware {
} }
override fun onDetachedFromActivity() { override fun onDetachedFromActivity() {
val binding = items.remove(KEY_ACTIVITY_PLUGIN_BINDING) as ActivityPluginBinding // Unregister the central manager state changed receiver.
activity.unregisterReceiver(MyBroadcastReceiver)
val binding = instances.remove(KEY_ACTIVITY_PLUGIN_BINDING) as ActivityPluginBinding
binding.removeRequestPermissionsResultListener(MyRequestPermissionsResultListener) binding.removeRequestPermissionsResultListener(MyRequestPermissionsResultListener)
} }
} }
@ -69,24 +78,27 @@ const val KEY_CENTRAL_MANAGER_FLUTTER_API = "KEY_CENTRAL_MANAGER_FLUTTER_API"
const val KEY_PERIPHERAL_FLUTTER_API = "KEY_PERIPHERAL_FLUTTER_API" const val KEY_PERIPHERAL_FLUTTER_API = "KEY_PERIPHERAL_FLUTTER_API"
const val KEY_GATT_CHARACTERISTIC_FLUTTER_API = "KEY_GATT_CHARACTERISTIC_FLUTTER_API" const val KEY_GATT_CHARACTERISTIC_FLUTTER_API = "KEY_GATT_CHARACTERISTIC_FLUTTER_API"
const val KEY_ACTIVITY_PLUGIN_BINDING = "KEY_ACTIVITY_PLUGIN_BINDING" const val KEY_ACTIVITY_PLUGIN_BINDING = "KEY_ACTIVITY_PLUGIN_BINDING"
const val REQUEST_CODE = 443 const val KEY_COUNT = "KEY_COUNT"
const val KEY_DEVICE = "KEY_DEVICE"
const val KEY_GATT = "KEY_GATT"
const val KEY_SERVICE = "KEY_SERVICE"
const val KEY_CHARACTERISTIC = "KEY_CHARACTERISTIC"
const val KEY_DESCRIPTOR = "KEY_DESCRIPTOR"
const val KEY_AUTHORIZE_RESULT = "KEY_AUTHORIZE_RESULT" const val KEY_AUTHORIZE_RESULT = "KEY_AUTHORIZE_RESULT"
const val KEY_START_SCAN_ERROR = "KEY_START_SCAN_ERROR" const val KEY_START_SCAN_ERROR = "KEY_START_SCAN_ERROR"
const val KEY_CONNECT_RESULT = "KEY_CONNECT_RESULT" const val KEY_CONNECT_RESULT = "KEY_CONNECT_RESULT"
const val KEY_DISCONNECT_RESULT = "KEY_DISCONNECT_RESULT" const val KEY_DISCONNECT_RESULT = "KEY_DISCONNECT_RESULT"
const val KEY_REQUEST_MTU_RESULT = "KEY_REQUEST_MTU_RESULT"
const val KEY_DISCOVER_SERVICES_RESULT = "KEY_DISCOVER_SERVICES_RESULT" const val KEY_DISCOVER_SERVICES_RESULT = "KEY_DISCOVER_SERVICES_RESULT"
const val KEY_READ_RESULT = "KEY_READ_RESULT" const val KEY_READ_RESULT = "KEY_READ_RESULT"
const val KEY_WRITE_RESULT = "KEY_WRITE_RESULT" const val KEY_WRITE_RESULT = "KEY_WRITE_RESULT"
const val DATA_TYPE_MANUFACTURER_SPECIFIC_DATA = 0xFF;
val items = mutableMapOf<String, Any>() val instances = mutableMapOf<String, Any>()
val instances = mutableMapOf<Long, Any>()
val identifiers = mutableMapOf<Any, Long>()
val activity get() = (items[KEY_ACTIVITY_PLUGIN_BINDING] as ActivityPluginBinding).activity val activity get() = (instances[KEY_ACTIVITY_PLUGIN_BINDING] as ActivityPluginBinding).activity
val centralFlutterApi get() = items[KEY_CENTRAL_MANAGER_FLUTTER_API] as Api.CentralManagerFlutterApi val centralFlutterApi get() = instances[KEY_CENTRAL_MANAGER_FLUTTER_API] as Pigeon.CentralManagerFlutterApi
val peripheralFlutterApi get() = items[KEY_PERIPHERAL_FLUTTER_API] as Api.PeripheralFlutterApi val peripheralFlutterApi get() = instances[KEY_PERIPHERAL_FLUTTER_API] as Pigeon.PeripheralFlutterApi
val characteristicFlutterApi get() = items[KEY_GATT_CHARACTERISTIC_FLUTTER_API] as Api.GattCharacteristicFlutterApi val characteristicFlutterApi get() = instances[KEY_GATT_CHARACTERISTIC_FLUTTER_API] as Pigeon.GattCharacteristicFlutterApi
val bluetoothManager get() = activity.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager val bluetoothManager get() = activity.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
val bluetoothAdapter get() = bluetoothManager.adapter as BluetoothAdapter val bluetoothAdapter get() = bluetoothManager.adapter as BluetoothAdapter
@ -94,39 +106,80 @@ val bluetoothAvailable get() = activity.packageManager.hasSystemFeature(PackageM
val mainHandler get() = Handler(activity.mainLooper) val mainHandler get() = Handler(activity.mainLooper)
val mainExecutor: Executor get() = ContextCompat.getMainExecutor(activity) val mainExecutor: Executor get() = ContextCompat.getMainExecutor(activity)
val Int.bluetoothState fun register(id: String): MutableMap<String, Any> {
get() = when (this) { var items = instances[id] as MutableMap<String, Any>?
if (items == null) {
items = mutableMapOf()
instances[id] = items
Log.d(BluetoothLowEnergyPlugin::class.java.simpleName, "register: $id")
}
var count = items[KEY_COUNT] as Int? ?: 0
count += 1
items[KEY_COUNT] = count
return items
}
fun unregister(id: String): MutableMap<String, Any> {
val items = instances[id] as MutableMap<String, Any>
var count = items[KEY_COUNT] as Int
count -= 1
items[KEY_COUNT] = count
if (count < 1) {
instances.remove(id)
Log.d(BluetoothLowEnergyPlugin::class.java.simpleName, "unregister: $id")
}
return items
}
val Any.TAG: String get() = this::class.java.simpleName
val Int.stateNumber: Long
get() {
val state = when (this) {
BluetoothAdapter.STATE_OFF -> BluetoothState.BLUETOOTH_STATE_POWERED_OFF BluetoothAdapter.STATE_OFF -> BluetoothState.BLUETOOTH_STATE_POWERED_OFF
BluetoothAdapter.STATE_TURNING_ON -> BluetoothState.BLUETOOTH_STATE_POWERED_OFF BluetoothAdapter.STATE_TURNING_ON -> BluetoothState.BLUETOOTH_STATE_POWERED_OFF
BluetoothAdapter.STATE_ON -> BluetoothState.BLUETOOTH_STATE_POWERED_ON BluetoothAdapter.STATE_ON -> BluetoothState.BLUETOOTH_STATE_POWERED_ON
BluetoothAdapter.STATE_TURNING_OFF -> BluetoothState.BLUETOOTH_STATE_POWERED_ON BluetoothAdapter.STATE_TURNING_OFF -> BluetoothState.BLUETOOTH_STATE_POWERED_ON
else -> throw IllegalArgumentException() else -> throw IllegalArgumentException()
} }
return state.number.toLong()
}
val BluetoothDevice.uuidString: String val BluetoothAdapter.stateNumber: Long
get() {
return if (bluetoothAvailable) {
state.stateNumber
} else {
BluetoothState.BLUETOOTH_STATE_UNSUPPORTED.number.toLong()
}
}
val BluetoothDevice.uuid: UUID
get() { get() {
val node = address.filter { char -> char != ':' }.lowercase() val node = address.filter { char -> char != ':' }.lowercase()
// We don't know the timestamp of the bluetooth device, use nil UUID as prefix. // We don't know the timestamp of the bluetooth device, use nil UUID as prefix.
return "00000000-0000-0000-$node" return uUID {
this.value = "00000000-0000-0000-$node"
}
} }
val String.address: String //val UUID.address: String
get() = takeLast(12).chunked(2).joinToString(":").uppercase() // get() = value.takeLast(12).chunked(2).joinToString(":").uppercase()
val ScanRecord.rawManufacturerSpecificData: ByteArray? val ScanRecord.rawManufacturerSpecificData: ByteArray?
get() { get() {
var offset = 0; var begin = 0
while (offset < bytes.size) { while (begin < bytes.size) {
val length = bytes[offset++].toInt() and 0xff val length = bytes[begin++].toInt() and 0xff
if (length == 0) { if (length == 0) {
break break
} }
val end = offset + length val end = begin + length
val type = bytes[offset++].toInt() and 0xff val type = bytes[begin++].toInt() and 0xff
if (type == DATA_TYPE_MANUFACTURER_SPECIFIC_DATA) { if (type == MyScanCallback.DATA_TYPE_MANUFACTURER_SPECIFIC_DATA) {
return bytes.slice(offset until end).toByteArray() return bytes.slice(begin until end).toByteArray()
} }
offset = end begin = end
} }
return null return null
} }

View File

@ -1,104 +1,73 @@
package dev.yanshouwang.bluetooth_low_energy package dev.yanshouwang.bluetooth_low_energy
import android.bluetooth.* import android.bluetooth.*
import android.bluetooth.BluetoothGattCallback import android.util.Log
import dev.yanshouwang.bluetooth_low_energy.pigeon.Api import dev.yanshouwang.bluetooth_low_energy.pigeon.Messages as Pigeon
import dev.yanshouwang.bluetooth_low_energy.proto.bluetoothLowEnergyException
import dev.yanshouwang.bluetooth_low_energy.proto.gattService import dev.yanshouwang.bluetooth_low_energy.proto.gattService
import dev.yanshouwang.bluetooth_low_energy.proto.peripheral
import dev.yanshouwang.bluetooth_low_energy.proto.uUID import dev.yanshouwang.bluetooth_low_energy.proto.uUID
// TODO: Clear results when connection state changed or central manager state changed.
object MyBluetoothGattCallback : BluetoothGattCallback() { object MyBluetoothGattCallback : BluetoothGattCallback() {
override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) { override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
super.onConnectionStateChange(gatt, status, newState) super.onConnectionStateChange(gatt, status, newState)
Log.d(TAG, "onConnectionStateChange: $gatt, $status, $newState")
val id = gatt.device.hashCode().toString()
if (status == BluetoothGatt.GATT_SUCCESS) { if (status == BluetoothGatt.GATT_SUCCESS) {
if (newState == BluetoothProfile.STATE_CONNECTED) { if (newState == BluetoothProfile.STATE_CONNECTED) {
// Connect succeed. // Must be connected.
val requested = gatt.requestMtu(512) val result = instances.remove("$id/$KEY_CONNECT_RESULT") as Pigeon.Result<Void>
if (!requested) { result.success(null)
gatt.disconnect()
}
} else { } else {
// Maybe disconnect succeed, connection failed or connection lost. // Must be disconnected.
gatt.close() gatt.close()
val connectResult = items.remove("${gatt.hashCode()}/${KEY_CONNECT_RESULT}") as Api.Result<ByteArray>? val result = instances.remove("$id/$KEY_DISCONNECT_RESULT") as Pigeon.Result<Void>
if (connectResult == null) { result.success(null)
val disconnectResult = items.remove("${gatt.hashCode()}/${KEY_DISCONNECT_RESULT}") as Api.Result<Void>?
if (disconnectResult == null) {
val id = identifiers[gatt] as Long
val errorBuffer = bluetoothLowEnergyException {
this.message = "GATT connection lost."
}.toByteArray()
mainExecutor.execute {
peripheralFlutterApi.notifyConnectionLost(id, errorBuffer) {}
} }
} else { } else {
disconnectResult.success(null)
}
} else {
val errorMessage = "GATT connection lost."
val error = BluetoothLowEnergyException(errorMessage)
connectResult.error(error)
}
}
} else {
// Maybe connect failed, disconnect failed or connection lost.
gatt.close() gatt.close()
val connectResult = items.remove("${gatt.hashCode()}/${KEY_CONNECT_RESULT}") as Api.Result<ByteArray>? val result = instances.remove("$id/$KEY_CONNECT_RESULT") as Pigeon.Result<Void>?
if (connectResult == null) { if (result == null) {
val disconnectResult = items.remove("${gatt.hashCode()}/${KEY_DISCONNECT_RESULT}") as Api.Result<Void>? // Connection lost.
if (disconnectResult == null) { val errorMessage = "GATT error with status: $status."
val id = identifiers[gatt] as Long
val errorBuffer = bluetoothLowEnergyException {
this.message = "GATT error with status: $status"
}.toByteArray()
mainExecutor.execute { mainExecutor.execute {
peripheralFlutterApi.notifyConnectionLost(id, errorBuffer) {} peripheralFlutterApi.onConnectionLost(id, errorMessage) {}
} }
} else { } else {
val error = BluetoothLowEnergyException("GATT error with status: $status") // Connect failed.
disconnectResult.error(error) val error = BluetoothLowEnergyException("GATT error with status: $status.")
} result.error(error)
} else {
val error = BluetoothLowEnergyException("GATT error with status: $status")
connectResult.error(error)
} }
} }
} }
override fun onMtuChanged(gatt: BluetoothGatt, mtu: Int, status: Int) { override fun onMtuChanged(gatt: BluetoothGatt, mtu: Int, status: Int) {
super.onMtuChanged(gatt, mtu, status) super.onMtuChanged(gatt, mtu, status)
Log.d(TAG, "onMtuChanged: $gatt, $mtu, $status")
val id = gatt.device.hashCode().toString()
// Maybe triggered in response to a connection event.
val result = instances.remove("$id/$KEY_REQUEST_MTU_RESULT") as Pigeon.Result<Long>? ?: return
when (status) { when (status) {
BluetoothGatt.GATT_SUCCESS -> { BluetoothGatt.GATT_SUCCESS -> {
val connectResult = items.remove("${gatt.hashCode()}/${KEY_CONNECT_RESULT}") as Api.Result<ByteArray> val maximumWriteLength = (mtu - 3).toLong()
val gattId = gatt.hashCode().toLong() result.success(maximumWriteLength)
instances[gattId] = gatt
val peripheralValue = peripheral {
this.id = gattId
this.maximumWriteLength = mtu - 3
}.toByteArray()
connectResult.success(peripheralValue)
} }
else -> { else -> {
gatt.disconnect() val error = BluetoothLowEnergyException("GATT request MTU failed with status: $status")
result.error(error)
} }
} }
} }
override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) { override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {
super.onServicesDiscovered(gatt, status) super.onServicesDiscovered(gatt, status)
val result = items.remove("${gatt.hashCode()}/${KEY_DISCOVER_SERVICES_RESULT}") as Api.Result<MutableList<ByteArray>> Log.d(TAG, "onServicesDiscovered: $gatt, $status")
val id = gatt.device.hashCode().toString()
val result = instances.remove("$id/$KEY_DISCOVER_SERVICES_RESULT") as Pigeon.Result<MutableList<ByteArray>>
if (status == BluetoothGatt.GATT_SUCCESS) { if (status == BluetoothGatt.GATT_SUCCESS) {
val serviceValues = mutableListOf<ByteArray>() val serviceValues = mutableListOf<ByteArray>()
for (service in gatt.services) { for (service in gatt.services) {
val serviceId = service.hashCode().toLong() val serviceValue = registerService(gatt, service)
instances[serviceId] = listOf(gatt, service)
val serviceValue = gattService {
this.id = serviceId
this.uuid = uUID {
this.value = service.uuid.toString()
}
}.toByteArray()
serviceValues.add(serviceValue) serviceValues.add(serviceValue)
} }
result.success(serviceValues) result.success(serviceValues)
@ -108,9 +77,24 @@ object MyBluetoothGattCallback : BluetoothGattCallback() {
} }
} }
private fun registerService(gatt: BluetoothGatt, service: BluetoothGattService): ByteArray {
val id = service.hashCode().toString()
val items = register(id)
items[KEY_GATT] = gatt
items[KEY_SERVICE] = service
return gattService {
this.id = id
this.uuid = uUID {
this.value = service.uuid.toString()
}
}.toByteArray()
}
override fun onCharacteristicRead(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) { override fun onCharacteristicRead(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) {
super.onCharacteristicRead(gatt, characteristic, status) super.onCharacteristicRead(gatt, characteristic, status)
val result = items.remove("${characteristic.hashCode()}/${KEY_READ_RESULT}") as Api.Result<ByteArray> Log.d(TAG, "onCharacteristicRead: $gatt, $characteristic, $status")
val id = characteristic.hashCode().toString()
val result = instances.remove("$id/$KEY_READ_RESULT") as Pigeon.Result<ByteArray>
if (status == BluetoothGatt.GATT_SUCCESS) { if (status == BluetoothGatt.GATT_SUCCESS) {
result.success(characteristic.value) result.success(characteristic.value)
} else { } else {
@ -121,7 +105,9 @@ object MyBluetoothGattCallback : BluetoothGattCallback() {
override fun onCharacteristicWrite(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) { override fun onCharacteristicWrite(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) {
super.onCharacteristicWrite(gatt, characteristic, status) super.onCharacteristicWrite(gatt, characteristic, status)
val result = items.remove("${characteristic.hashCode()}/${KEY_WRITE_RESULT}") as Api.Result<Void> Log.d(TAG, "onCharacteristicWrite: $gatt, $characteristic, $status")
val id = characteristic.hashCode().toString()
val result = instances.remove("$id/$KEY_WRITE_RESULT") as Pigeon.Result<Void>
if (status == BluetoothGatt.GATT_SUCCESS) { if (status == BluetoothGatt.GATT_SUCCESS) {
result.success(null) result.success(null)
} else { } else {
@ -132,16 +118,19 @@ object MyBluetoothGattCallback : BluetoothGattCallback() {
override fun onCharacteristicChanged(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic) { override fun onCharacteristicChanged(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic) {
super.onCharacteristicChanged(gatt, characteristic) super.onCharacteristicChanged(gatt, characteristic)
val id = identifiers[characteristic] as Long Log.d(TAG, "onCharacteristicChanged: $gatt, $characteristic")
val id = characteristic.hashCode().toString()
val value = characteristic.value val value = characteristic.value
mainExecutor.execute { mainExecutor.execute {
characteristicFlutterApi.notifyValue(id, value) {} characteristicFlutterApi.onValueChanged(id, value) {}
} }
} }
override fun onDescriptorRead(gatt: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int) { override fun onDescriptorRead(gatt: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int) {
super.onDescriptorRead(gatt, descriptor, status) super.onDescriptorRead(gatt, descriptor, status)
val result = items.remove("${descriptor.hashCode()}/${KEY_READ_RESULT}") as Api.Result<ByteArray> Log.d(TAG, "onDescriptorRead: $gatt, $descriptor, $status")
val id = descriptor.hashCode().toString()
val result = instances.remove("$id/$KEY_READ_RESULT") as Pigeon.Result<ByteArray>
if (status == BluetoothGatt.GATT_SUCCESS) { if (status == BluetoothGatt.GATT_SUCCESS) {
result.success(descriptor.value) result.success(descriptor.value)
} else { } else {
@ -152,7 +141,9 @@ object MyBluetoothGattCallback : BluetoothGattCallback() {
override fun onDescriptorWrite(gatt: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int) { override fun onDescriptorWrite(gatt: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int) {
super.onDescriptorWrite(gatt, descriptor, status) super.onDescriptorWrite(gatt, descriptor, status)
val result = items.remove("${descriptor.hashCode()}/${KEY_WRITE_RESULT}") as Api.Result<Void> Log.d(TAG, "onDescriptorWrite: $gatt, $descriptor, $status")
val id = descriptor.hashCode().toString()
val result = instances.remove("$id/$KEY_WRITE_RESULT") as Pigeon.Result<Void>
if (status == BluetoothGatt.GATT_SUCCESS) { if (status == BluetoothGatt.GATT_SUCCESS) {
result.success(null) result.success(null)
} else { } else {
@ -160,4 +151,29 @@ object MyBluetoothGattCallback : BluetoothGattCallback() {
result.error(error) result.error(error)
} }
} }
override fun onPhyRead(gatt: BluetoothGatt, txPhy: Int, rxPhy: Int, status: Int) {
super.onPhyRead(gatt, txPhy, rxPhy, status)
Log.d(TAG, "onPhyRead: $gatt, $txPhy, $rxPhy, $status")
}
override fun onPhyUpdate(gatt: BluetoothGatt, txPhy: Int, rxPhy: Int, status: Int) {
super.onPhyUpdate(gatt, txPhy, rxPhy, status)
Log.d(TAG, "onPhyUpdate: $gatt, $txPhy, $rxPhy, $status")
}
override fun onReadRemoteRssi(gatt: BluetoothGatt, rssi: Int, status: Int) {
super.onReadRemoteRssi(gatt, rssi, status)
Log.d(TAG, "onReadRemoteRssi: $gatt, $rssi, $status")
}
override fun onReliableWriteCompleted(gatt: BluetoothGatt, status: Int) {
super.onReliableWriteCompleted(gatt, status)
Log.d(TAG, "onReliableWriteCompleted: $gatt, $status")
}
override fun onServiceChanged(gatt: BluetoothGatt) {
super.onServiceChanged(gatt)
Log.d(TAG, "onServiceChanged: $gatt")
}
} }

View File

@ -4,16 +4,17 @@ import android.bluetooth.BluetoothAdapter
import android.content.BroadcastReceiver import android.content.BroadcastReceiver
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import android.util.Log
object MyBroadcastReceiver : BroadcastReceiver() { object MyBroadcastReceiver : BroadcastReceiver() {
private const val STATE_UNKNOWN = -1 private const val STATE_UNKNOWN = -1
override fun onReceive(context: Context, intent: Intent) { override fun onReceive(context: Context, intent: Intent) {
val previousState = Log.d(TAG, "onReceive: $context, $intent")
intent.getIntExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, STATE_UNKNOWN).bluetoothState val previousStateNumber =
val state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, STATE_UNKNOWN).bluetoothState intent.getIntExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, STATE_UNKNOWN).stateNumber
if (state == previousState) return val stateNumber = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, STATE_UNKNOWN).stateNumber
val stateNumber = state.number.toLong() if (stateNumber == previousStateNumber) return
centralFlutterApi.notifyState(stateNumber) {} centralFlutterApi.onStateChanged(stateNumber) {}
} }
} }

View File

@ -1,20 +1,20 @@
package dev.yanshouwang.bluetooth_low_energy package dev.yanshouwang.bluetooth_low_energy
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.le.ScanFilter import android.bluetooth.le.ScanFilter
import android.bluetooth.le.ScanSettings import android.bluetooth.le.ScanSettings
import android.content.IntentFilter
import android.content.pm.PackageManager import android.content.pm.PackageManager
import android.os.Build import android.os.Build
import android.os.ParcelUuid import android.os.ParcelUuid
import android.util.Log
import androidx.core.app.ActivityCompat import androidx.core.app.ActivityCompat
import dev.yanshouwang.bluetooth_low_energy.pigeon.Api
import dev.yanshouwang.bluetooth_low_energy.proto.BluetoothState
import dev.yanshouwang.bluetooth_low_energy.proto.UUID import dev.yanshouwang.bluetooth_low_energy.proto.UUID
import dev.yanshouwang.bluetooth_low_energy.pigeon.Messages as Pigeon
object MyCentralManagerHostApi : Api.CentralManagerHostApi { object MyCentralManagerHostApi : Pigeon.CentralManagerHostApi {
override fun authorize(result: Api.Result<Boolean>) { const val REQUEST_CODE = 443
override fun authorize(result: Pigeon.Result<Boolean>) {
Log.d(TAG, "authorize: ")
val permissions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { val permissions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.BLUETOOTH_SCAN, android.Manifest.permission.BLUETOOTH_CONNECT) arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.BLUETOOTH_SCAN, android.Manifest.permission.BLUETOOTH_CONNECT)
} else { } else {
@ -27,39 +27,28 @@ object MyCentralManagerHostApi : Api.CentralManagerHostApi {
result.success(true) result.success(true)
} else { } else {
ActivityCompat.requestPermissions(activity, permissions, REQUEST_CODE) ActivityCompat.requestPermissions(activity, permissions, REQUEST_CODE)
items[KEY_AUTHORIZE_RESULT] = result instances[KEY_AUTHORIZE_RESULT] = result
} }
} }
override fun getState(): Long { override fun getState(): Long {
val state = if (bluetoothAvailable) { Log.d(TAG, "getState: ")
bluetoothAdapter.state.bluetoothState return bluetoothAdapter.stateNumber
} else {
BluetoothState.BLUETOOTH_STATE_UNSUPPORTED
}
return state.number.toLong()
} }
override fun addStateObserver() { override fun startScan(uuidBuffers: MutableList<ByteArray>?, result: Pigeon.Result<Void>) {
val filter = IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED) Log.d(TAG, "startScan: $uuidBuffers")
activity.registerReceiver(MyBroadcastReceiver, filter)
}
override fun removeStateObserver() {
activity.unregisterReceiver(MyBroadcastReceiver)
}
override fun startScan(uuidBuffers: MutableList<ByteArray>?, result: Api.Result<Void>) {
val filters = uuidBuffers?.map { buffer -> val filters = uuidBuffers?.map { buffer ->
val uuid = UUID.parseFrom(buffer).value val uuid = UUID.parseFrom(buffer).value
val serviceUUID = ParcelUuid.fromString(uuid) val serviceUUID = ParcelUuid.fromString(uuid)
ScanFilter.Builder().setServiceUuid(serviceUUID).build() ScanFilter.Builder().setServiceUuid(serviceUUID).build()
} }
val settings = ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build() val settings = ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.build()
bluetoothAdapter.bluetoothLeScanner.startScan(filters, settings, MyScanCallback) bluetoothAdapter.bluetoothLeScanner.startScan(filters, settings, MyScanCallback)
// Use main handler.post to delay until ScanCallback.onScanFailed executed. // Use main handler.post to delay until ScanCallback.onScanFailed executed.
mainHandler.post { mainHandler.post {
val error = items.remove(KEY_START_SCAN_ERROR) as Throwable? val error = instances.remove(KEY_START_SCAN_ERROR) as Throwable?
if (error == null) { if (error == null) {
result.success(null) result.success(null)
} else { } else {
@ -69,19 +58,7 @@ object MyCentralManagerHostApi : Api.CentralManagerHostApi {
} }
override fun stopScan() { override fun stopScan() {
Log.d(TAG, "stopScan: ")
bluetoothAdapter.bluetoothLeScanner.stopScan(MyScanCallback) bluetoothAdapter.bluetoothLeScanner.stopScan(MyScanCallback)
} }
override fun connect(uuidBuffer: ByteArray, result: Api.Result<ByteArray>) {
val address = UUID.parseFrom(uuidBuffer).value.address
val device = bluetoothAdapter.getRemoteDevice(address)
val autoConnect = false
val gatt = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val transport = BluetoothDevice.TRANSPORT_LE
device.connectGatt(activity, autoConnect, MyBluetoothGattCallback, transport)
} else {
device.connectGatt(activity, autoConnect, MyBluetoothGattCallback)
}
items["${gatt.hashCode()}/${KEY_CONNECT_RESULT}"] = result
}
} }

View File

@ -3,63 +3,65 @@ package dev.yanshouwang.bluetooth_low_energy
import android.bluetooth.BluetoothGatt import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothGattCharacteristic import android.bluetooth.BluetoothGattCharacteristic
import android.bluetooth.BluetoothGattDescriptor import android.bluetooth.BluetoothGattDescriptor
import dev.yanshouwang.bluetooth_low_energy.pigeon.Api import android.util.Log
import dev.yanshouwang.bluetooth_low_energy.pigeon.Messages as Pigeon
import dev.yanshouwang.bluetooth_low_energy.proto.gattDescriptor import dev.yanshouwang.bluetooth_low_energy.proto.gattDescriptor
import dev.yanshouwang.bluetooth_low_energy.proto.uUID import dev.yanshouwang.bluetooth_low_energy.proto.uUID
import java.util.UUID import java.util.UUID
object MyGattCharacteristicHostApi : Api.GattCharacteristicHostApi { object MyGattCharacteristicHostApi : Pigeon.GattCharacteristicHostApi {
private const val CLIENT_CHARACTERISTIC_CONFIG = "00002902-0000-1000-8000-00805f9b34fb" private const val CLIENT_CHARACTERISTIC_CONFIG = "00002902-0000-1000-8000-00805f9b34fb"
override fun allocate(id: Long, instanceId: Long) { override fun free(id: String) {
val list = instances.remove(instanceId) as List<Any> Log.d(TAG, "free: $id")
val characteristic = list[1] unregister(id)
instances[id] = list
identifiers[characteristic] = id
} }
override fun free(id: Long) { override fun discoverDescriptors(id: String, result: Pigeon.Result<MutableList<ByteArray>>) {
val list = instances.remove(id) as List<Any> Log.d(TAG, "discoverDescriptors: $id")
val characteristic = list[1] val items = instances[id] as MutableMap<String, Any>
identifiers.remove(characteristic) val gatt = items[KEY_GATT] as BluetoothGatt
} val characteristic = items[KEY_CHARACTERISTIC] as BluetoothGattCharacteristic
override fun discoverDescriptors(id: Long, result: Api.Result<MutableList<ByteArray>>) {
val list = instances[id] as List<Any>
val gatt = list[0] as BluetoothGatt
val characteristic = list[1] as BluetoothGattCharacteristic
val descriptorValues = mutableListOf<ByteArray>() val descriptorValues = mutableListOf<ByteArray>()
for (descriptor in characteristic.descriptors) { for (descriptor in characteristic.descriptors) {
val descriptorId = descriptor.hashCode().toLong() val descriptorValue = registerDescriptor(gatt, descriptor)
instances[descriptorId] = listOf(gatt, descriptor)
val descriptorValue = gattDescriptor {
this.id = descriptorId
this.uuid = uUID {
this.value = descriptor.uuid.toString()
}
}.toByteArray()
descriptorValues.add(descriptorValue) descriptorValues.add(descriptorValue)
} }
result.success(descriptorValues) result.success(descriptorValues)
} }
override fun read(id: Long, result: Api.Result<ByteArray>) { private fun registerDescriptor(gatt: BluetoothGatt, descriptor: BluetoothGattDescriptor): ByteArray {
val list = instances[id] as List<Any> val id = descriptor.hashCode().toString()
val gatt = list[0] as BluetoothGatt val items = register(id)
val characteristic = list[1] as BluetoothGattCharacteristic items[KEY_GATT] = gatt
items[KEY_DESCRIPTOR] = descriptor
return gattDescriptor {
this.id = id
this.uuid = uUID {
this.value = descriptor.uuid.toString()
}
}.toByteArray()
}
override fun read(id: String, result: Pigeon.Result<ByteArray>) {
Log.d(TAG, "read: $id")
val items = instances[id] as MutableMap<String, Any>
val gatt = items[KEY_GATT] as BluetoothGatt
val characteristic = items[KEY_CHARACTERISTIC] as BluetoothGattCharacteristic
val succeed = gatt.readCharacteristic(characteristic) val succeed = gatt.readCharacteristic(characteristic)
if (succeed) { if (succeed) {
items["${characteristic.hashCode()}/$KEY_READ_RESULT"] = result instances["$id/$KEY_READ_RESULT"] = result
} else { } else {
val error = BluetoothLowEnergyException("GATT read characteristic failed.") val error = BluetoothLowEnergyException("GATT read characteristic failed.")
result.error(error) result.error(error)
} }
} }
override fun write(id: Long, value: ByteArray, withoutResponse: Boolean, result: Api.Result<Void>) { override fun write(id: String, value: ByteArray, withoutResponse: Boolean, result: Pigeon.Result<Void>) {
val list = instances[id] as List<Any> Log.d(TAG, "write: $id, $value")
val gatt = list[0] as BluetoothGatt val items = instances[id] as MutableMap<String, Any>
val characteristic = list[1] as BluetoothGattCharacteristic val gatt = items[KEY_GATT] as BluetoothGatt
val characteristic = items[KEY_CHARACTERISTIC] as BluetoothGattCharacteristic
characteristic.writeType = if (withoutResponse) { characteristic.writeType = if (withoutResponse) {
BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE
} else { } else {
@ -68,19 +70,28 @@ object MyGattCharacteristicHostApi : Api.GattCharacteristicHostApi {
characteristic.value = value characteristic.value = value
val succeed = gatt.writeCharacteristic(characteristic) val succeed = gatt.writeCharacteristic(characteristic)
if (succeed) { if (succeed) {
items["${characteristic.hashCode()}/$KEY_WRITE_RESULT"] = result instances["$id/$KEY_WRITE_RESULT"] = result
} else { } else {
val error = BluetoothLowEnergyException("GATT write characteristic failed.") val error = BluetoothLowEnergyException("GATT write characteristic failed.")
result.error(error) result.error(error)
} }
} }
override fun setNotify(id: Long, value: Boolean, result: Api.Result<Void>) { override fun setNotify(id: String, value: Boolean, result: Pigeon.Result<Void>) {
val list = instances[id] as List<Any> Log.d(TAG, "setNotify: $id, $value")
val gatt = list[0] as BluetoothGatt val items = instances[id] as MutableMap<String, Any>
val characteristic = list[1] as BluetoothGattCharacteristic val gatt = items[KEY_GATT] as BluetoothGatt
val setNotificationSucceed = gatt.setCharacteristicNotification(characteristic, value) val characteristic = items[KEY_CHARACTERISTIC] as BluetoothGattCharacteristic
if (setNotificationSucceed) { val succeed = gatt.setCharacteristicNotification(characteristic, value)
if (succeed) {
writeClientCharacteristicConfig(gatt, characteristic, value, result)
} else {
val error = BluetoothLowEnergyException("GATT set characteristic notification failed.")
result.error(error)
}
}
private fun writeClientCharacteristicConfig(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, value: Boolean, result: Pigeon.Result<Void>) {
val uuid = UUID.fromString(CLIENT_CHARACTERISTIC_CONFIG) val uuid = UUID.fromString(CLIENT_CHARACTERISTIC_CONFIG)
val descriptor = characteristic.getDescriptor(uuid) val descriptor = characteristic.getDescriptor(uuid)
descriptor.value = if (value) { descriptor.value = if (value) {
@ -88,15 +99,12 @@ object MyGattCharacteristicHostApi : Api.GattCharacteristicHostApi {
} else { } else {
BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE
} }
val writeSucceed = gatt.writeDescriptor(descriptor) val succeed = gatt.writeDescriptor(descriptor)
if (writeSucceed) { if (succeed) {
items["${descriptor.hashCode()}/${KEY_WRITE_RESULT}"] = result val id = descriptor.hashCode().toString()
instances["$id/$KEY_WRITE_RESULT"] = result
} else { } else {
val error = BluetoothLowEnergyException("GATT write <client characteristic config> descriptor failed.") val error = BluetoothLowEnergyException("GATT write client characteristic config failed.")
result.error(error)
}
} else {
val error = BluetoothLowEnergyException("GATT set characteristic notification failed.")
result.error(error) result.error(error)
} }
} }

View File

@ -2,43 +2,38 @@ package dev.yanshouwang.bluetooth_low_energy
import android.bluetooth.BluetoothGatt import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothGattDescriptor import android.bluetooth.BluetoothGattDescriptor
import dev.yanshouwang.bluetooth_low_energy.pigeon.Api import android.util.Log
import dev.yanshouwang.bluetooth_low_energy.pigeon.Messages as Pigeon
object MyGattDescriptorHostApi : Api.GattDescriptorHostApi { object MyGattDescriptorHostApi : Pigeon.GattDescriptorHostApi {
override fun allocate(id: Long, instanceId: Long) { override fun free(id: String) {
val list = instances.remove(instanceId) as List<Any> Log.d(TAG, "free: $id")
val descriptor = list[1] unregister(id)
instances[id] = list
identifiers[descriptor] = id
} }
override fun free(id: Long) { override fun read(id: String, result: Pigeon.Result<ByteArray>) {
val list = instances.remove(id) as List<Any> Log.d(TAG, "read: $id")
val descriptor = list[1] val items = instances[id] as MutableMap<String, Any>
identifiers.remove(descriptor) val gatt = items[KEY_GATT] as BluetoothGatt
} val descriptor = items[KEY_DESCRIPTOR] as BluetoothGattDescriptor
override fun read(id: Long, result: Api.Result<ByteArray>) {
val list = instances[id] as List<Any>
val gatt = list[0] as BluetoothGatt
val descriptor = list[1] as BluetoothGattDescriptor
val succeed = gatt.readDescriptor(descriptor) val succeed = gatt.readDescriptor(descriptor)
if (succeed) { if (succeed) {
items["${descriptor.hashCode()}/$KEY_READ_RESULT"] = result instances["$id/$KEY_READ_RESULT"] = result
} else { } else {
val error = BluetoothLowEnergyException("GATT read descriptor failed.") val error = BluetoothLowEnergyException("GATT read descriptor failed.")
result.error(error) result.error(error)
} }
} }
override fun write(id: Long, value: ByteArray, result: Api.Result<Void>) { override fun write(id: String, value: ByteArray, result: Pigeon.Result<Void>) {
val list = instances[id] as List<Any> Log.d(TAG, "write: $id, $value")
val gatt = list[0] as BluetoothGatt val items = instances[id] as MutableMap<String, Any>
val descriptor = list[1] as BluetoothGattDescriptor val gatt = items[KEY_GATT] as BluetoothGatt
val descriptor = items[KEY_DESCRIPTOR] as BluetoothGattDescriptor
descriptor.value = value descriptor.value = value
val succeed = gatt.writeDescriptor(descriptor) val succeed = gatt.writeDescriptor(descriptor)
if (succeed) { if (succeed) {
items["${descriptor.hashCode()}/$KEY_WRITE_RESULT"] = result instances["$id/$KEY_WRITE_RESULT"] = result
} else { } else {
val error = BluetoothLowEnergyException("GATT write descriptor failed.") val error = BluetoothLowEnergyException("GATT write descriptor failed.")
result.error(error) result.error(error)

View File

@ -3,34 +3,37 @@ package dev.yanshouwang.bluetooth_low_energy
import android.bluetooth.BluetoothGatt import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothGattCharacteristic import android.bluetooth.BluetoothGattCharacteristic
import android.bluetooth.BluetoothGattService import android.bluetooth.BluetoothGattService
import dev.yanshouwang.bluetooth_low_energy.pigeon.Api import android.util.Log
import dev.yanshouwang.bluetooth_low_energy.pigeon.Messages as Pigeon
import dev.yanshouwang.bluetooth_low_energy.proto.gattCharacteristic import dev.yanshouwang.bluetooth_low_energy.proto.gattCharacteristic
import dev.yanshouwang.bluetooth_low_energy.proto.uUID import dev.yanshouwang.bluetooth_low_energy.proto.uUID
object MyGattServiceHostApi : Api.GattServiceHostApi { object MyGattServiceHostApi : Pigeon.GattServiceHostApi {
override fun allocate(id: Long, instanceId: Long) { override fun free(id: String) {
val list = instances.remove(instanceId) as List<Any> Log.d(TAG, "free: $id")
val service = list[1] unregister(id)
instances[id] = list
identifiers[service] = id
} }
override fun free(id: Long) { override fun discoverCharacteristics(id: String, result: Pigeon.Result<MutableList<ByteArray>>) {
val list = instances.remove(id) as List<Any> Log.d(TAG, "discoverCharacteristics: $id")
val service = list[1] val items = instances[id] as MutableMap<String, Any>
identifiers.remove(service) val gatt = items[KEY_GATT] as BluetoothGatt
} val service = items[KEY_SERVICE] as BluetoothGattService
override fun discoverCharacteristics(id: Long, result: Api.Result<MutableList<ByteArray>>) {
val list = instances[id] as List<Any>
val gatt = list[0] as BluetoothGatt
val service = list[1] as BluetoothGattService
val characteristicValues = mutableListOf<ByteArray>() val characteristicValues = mutableListOf<ByteArray>()
for (characteristic in service.characteristics) { for (characteristic in service.characteristics) {
val characteristicId = characteristic.hashCode().toLong() val characteristicValue = registerCharacteristic(gatt, characteristic)
instances[characteristicId] = listOf(gatt, characteristic) characteristicValues.add(characteristicValue)
val characteristicValue = gattCharacteristic { }
this.id = characteristicId result.success(characteristicValues)
}
private fun registerCharacteristic(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic): ByteArray {
val id = characteristic.hashCode().toString()
val items = register(id)
items[KEY_GATT] = gatt
items[KEY_CHARACTERISTIC] = characteristic
return gattCharacteristic {
this.id = id
this.uuid = uUID { this.uuid = uUID {
this.value = characteristic.uuid.toString() this.value = characteristic.uuid.toString()
} }
@ -40,8 +43,5 @@ object MyGattServiceHostApi : Api.GattServiceHostApi {
characteristic.properties and BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE != 0 characteristic.properties and BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE != 0
this.canNotify = characteristic.properties and BluetoothGattCharacteristic.PROPERTY_NOTIFY != 0 this.canNotify = characteristic.properties and BluetoothGattCharacteristic.PROPERTY_NOTIFY != 0
}.toByteArray() }.toByteArray()
characteristicValues.add(characteristicValue)
}
result.success(characteristicValues)
} }
} }

View File

@ -1,33 +1,62 @@
package dev.yanshouwang.bluetooth_low_energy package dev.yanshouwang.bluetooth_low_energy
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothGatt import android.bluetooth.BluetoothGatt
import dev.yanshouwang.bluetooth_low_energy.pigeon.Api import android.os.Build
import android.util.Log
import dev.yanshouwang.bluetooth_low_energy.pigeon.Messages as Pigeon
object MyPeripheralHostApi : Api.PeripheralHostApi { object MyPeripheralHostApi : Pigeon.PeripheralHostApi {
override fun allocate(id: Long, instanceId: Long) { override fun free(id: String) {
val gatt = instances.remove(instanceId) as BluetoothGatt Log.d(TAG, "free: $id")
instances[id] = gatt unregister(id)
identifiers[gatt] = id
} }
override fun free(id: Long) { override fun connect(id: String, result: Pigeon.Result<Void>) {
val gatt = instances.remove(id) as BluetoothGatt Log.d(TAG, "connect: $id")
identifiers.remove(gatt) val items = instances[id] as MutableMap<String, Any>
} val device = items[KEY_DEVICE] as BluetoothDevice
val autoConnect = false
override fun disconnect(id: Long, result: Api.Result<Void>) { val gatt = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val gatt = instances[id] as BluetoothGatt val transport = BluetoothDevice.TRANSPORT_LE
gatt.disconnect() device.connectGatt(activity, autoConnect, MyBluetoothGattCallback, transport)
items["${gatt.hashCode()}/$KEY_DISCONNECT_RESULT"] = result
}
override fun discoverServices(id: Long, result: Api.Result<MutableList<ByteArray>>) {
val gatt = instances[id] as BluetoothGatt
val started = gatt.discoverServices()
if (started) {
items["${gatt.hashCode()}/$KEY_DISCOVER_SERVICES_RESULT"] = result
} else { } else {
val error = BluetoothLowEnergyException("Start discover services failed.") device.connectGatt(activity, autoConnect, MyBluetoothGattCallback)
}
items[KEY_GATT] = gatt
instances["$id/$KEY_CONNECT_RESULT"] = result
}
override fun disconnect(id: String, result: Pigeon.Result<Void>) {
Log.d(TAG, "disconnect: $id")
val items = instances[id] as MutableMap<String, Any>
val gatt = items[KEY_GATT] as BluetoothGatt
gatt.disconnect()
instances["$id/$KEY_DISCONNECT_RESULT"] = result
}
override fun requestMtu(id: String, result: Pigeon.Result<Long>) {
Log.d(TAG, "requestMtu: $id")
val items = instances[id] as MutableMap<String, Any>
val gatt = items[KEY_GATT] as BluetoothGatt
val succeed = gatt.requestMtu(512)
if (succeed) {
instances["$id/$KEY_REQUEST_MTU_RESULT"] = result
} else {
val error = BluetoothLowEnergyException("GATT request MTU failed.")
result.error(error)
}
}
override fun discoverServices(id: String, result: Pigeon.Result<MutableList<ByteArray>>) {
Log.d(TAG, "discoverServices: $id")
val items = instances[id] as MutableMap<String, Any>
val gatt = items[KEY_GATT] as BluetoothGatt
val succeed = gatt.discoverServices()
if (succeed) {
instances["$id/$KEY_DISCOVER_SERVICES_RESULT"] = result
} else {
val error = BluetoothLowEnergyException("GATT discover services failed.")
result.error(error) result.error(error)
} }
} }

View File

@ -1,14 +1,16 @@
package dev.yanshouwang.bluetooth_low_energy package dev.yanshouwang.bluetooth_low_energy
import android.content.pm.PackageManager import android.content.pm.PackageManager
import dev.yanshouwang.bluetooth_low_energy.pigeon.Api import android.util.Log
import dev.yanshouwang.bluetooth_low_energy.pigeon.Messages as Pigeon
import io.flutter.plugin.common.PluginRegistry.RequestPermissionsResultListener import io.flutter.plugin.common.PluginRegistry.RequestPermissionsResultListener
object MyRequestPermissionsResultListener : RequestPermissionsResultListener { object MyRequestPermissionsResultListener : RequestPermissionsResultListener {
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray): Boolean { override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray): Boolean {
Log.d(TAG, "onRequestPermissionsResult: $requestCode, $permissions, $grantResults")
return when (requestCode) { return when (requestCode) {
REQUEST_CODE -> { MyCentralManagerHostApi.REQUEST_CODE -> {
val result = items.remove(KEY_AUTHORIZE_RESULT) as Api.Result<Boolean> val result = instances.remove(KEY_AUTHORIZE_RESULT) as Pigeon.Result<Boolean>
val authorized = grantResults.all { grantResult -> grantResult == PackageManager.PERMISSION_GRANTED } val authorized = grantResults.all { grantResult -> grantResult == PackageManager.PERMISSION_GRANTED }
result.success(authorized) result.success(authorized)
true true

View File

@ -2,25 +2,44 @@ package dev.yanshouwang.bluetooth_low_energy
import android.bluetooth.le.ScanCallback import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanResult import android.bluetooth.le.ScanResult
import android.bluetooth.le.ScanSettings
import android.os.Build import android.os.Build
import android.util.Log
import com.google.protobuf.ByteString import com.google.protobuf.ByteString
import dev.yanshouwang.bluetooth_low_energy.proto.advertisement import dev.yanshouwang.bluetooth_low_energy.proto.*
import dev.yanshouwang.bluetooth_low_energy.proto.serviceData
import dev.yanshouwang.bluetooth_low_energy.proto.uUID
object MyScanCallback : ScanCallback() { object MyScanCallback : ScanCallback() {
const val DATA_TYPE_MANUFACTURER_SPECIFIC_DATA = 0xff
override fun onScanFailed(errorCode: Int) { override fun onScanFailed(errorCode: Int) {
super.onScanFailed(errorCode) super.onScanFailed(errorCode)
Log.d(TAG, "onScanFailed: $errorCode")
val error = BluetoothLowEnergyException("Start scan failed with code: $errorCode") val error = BluetoothLowEnergyException("Start scan failed with code: $errorCode")
items[KEY_START_SCAN_ERROR] = error instances[KEY_START_SCAN_ERROR] = error
} }
override fun onScanResult(callbackType: Int, result: ScanResult) { override fun onScanResult(callbackType: Int, result: ScanResult) {
super.onScanResult(callbackType, result) super.onScanResult(callbackType, result)
val advertisementValue = advertisement { Log.d(TAG, "onScanResult: $callbackType, $result")
this.uuid = uUID { onScanned(result)
this.value = result.device.uuidString }
override fun onBatchScanResults(results: MutableList<ScanResult>) {
super.onBatchScanResults(results)
Log.d(TAG, "onBatchScanResults: $results")
for (result in results) {
onScanned(result)
}
}
private fun onScanned(result: ScanResult): Unit {
val device = result.device
val id = device.hashCode().toString()
val items = register(id)
items[KEY_DEVICE] = device
val broadcastValue = broadcast {
this.peripheral = peripheral {
this.id = id
this.uuid = result.device.uuid
} }
this.rssi = result.rssi this.rssi = result.rssi
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
@ -68,14 +87,6 @@ object MyScanCallback : ScanCallback() {
this.txPowerLevel = scanRecord.txPowerLevel this.txPowerLevel = scanRecord.txPowerLevel
} }
}.toByteArray() }.toByteArray()
centralFlutterApi.notifyAdvertisement(advertisementValue) {} centralFlutterApi.onScanned(broadcastValue) {}
}
override fun onBatchScanResults(results: MutableList<ScanResult>) {
super.onBatchScanResults(results)
for (result in results) {
onScanResult(ScanSettings.CALLBACK_TYPE_ALL_MATCHES, result)
}
} }
} }

View File

@ -1,46 +0,0 @@
//Generated by the protocol buffer compiler. DO NOT EDIT!
// source: proto/messages.proto
package dev.yanshouwang.bluetooth_low_energy.proto;
@kotlin.jvm.JvmName("-initializebluetoothLowEnergyException")
inline fun bluetoothLowEnergyException(block: dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyExceptionKt.Dsl.() -> kotlin.Unit): dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException =
dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyExceptionKt.Dsl._create(dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException.newBuilder()).apply { block() }._build()
object BluetoothLowEnergyExceptionKt {
@kotlin.OptIn(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)
@com.google.protobuf.kotlin.ProtoDslMarker
class Dsl private constructor(
private val _builder: dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException.Builder
) {
companion object {
@kotlin.jvm.JvmSynthetic
@kotlin.PublishedApi
internal fun _create(builder: dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException.Builder): Dsl = Dsl(builder)
}
@kotlin.jvm.JvmSynthetic
@kotlin.PublishedApi
internal fun _build(): dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException = _builder.build()
/**
* <code>string message = 1;</code>
*/
var message: kotlin.String
@JvmName("getMessage")
get() = _builder.getMessage()
@JvmName("setMessage")
set(value) {
_builder.setMessage(value)
}
/**
* <code>string message = 1;</code>
*/
fun clearMessage() {
_builder.clearMessage()
}
}
}
@kotlin.jvm.JvmSynthetic
inline fun dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException.copy(block: dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyExceptionKt.Dsl.() -> kotlin.Unit): dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyException =
dev.yanshouwang.bluetooth_low_energy.proto.BluetoothLowEnergyExceptionKt.Dsl._create(this.toBuilder()).apply { block() }._build()

View File

@ -3,47 +3,47 @@
package dev.yanshouwang.bluetooth_low_energy.proto; package dev.yanshouwang.bluetooth_low_energy.proto;
@kotlin.jvm.JvmName("-initializeadvertisement") @kotlin.jvm.JvmName("-initializebroadcast")
inline fun advertisement(block: dev.yanshouwang.bluetooth_low_energy.proto.AdvertisementKt.Dsl.() -> kotlin.Unit): dev.yanshouwang.bluetooth_low_energy.proto.Advertisement = inline fun broadcast(block: dev.yanshouwang.bluetooth_low_energy.proto.BroadcastKt.Dsl.() -> kotlin.Unit): dev.yanshouwang.bluetooth_low_energy.proto.Broadcast =
dev.yanshouwang.bluetooth_low_energy.proto.AdvertisementKt.Dsl._create(dev.yanshouwang.bluetooth_low_energy.proto.Advertisement.newBuilder()).apply { block() }._build() dev.yanshouwang.bluetooth_low_energy.proto.BroadcastKt.Dsl._create(dev.yanshouwang.bluetooth_low_energy.proto.Broadcast.newBuilder()).apply { block() }._build()
object AdvertisementKt { object BroadcastKt {
@kotlin.OptIn(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class) @kotlin.OptIn(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)
@com.google.protobuf.kotlin.ProtoDslMarker @com.google.protobuf.kotlin.ProtoDslMarker
class Dsl private constructor( class Dsl private constructor(
private val _builder: dev.yanshouwang.bluetooth_low_energy.proto.Advertisement.Builder private val _builder: dev.yanshouwang.bluetooth_low_energy.proto.Broadcast.Builder
) { ) {
companion object { companion object {
@kotlin.jvm.JvmSynthetic @kotlin.jvm.JvmSynthetic
@kotlin.PublishedApi @kotlin.PublishedApi
internal fun _create(builder: dev.yanshouwang.bluetooth_low_energy.proto.Advertisement.Builder): Dsl = Dsl(builder) internal fun _create(builder: dev.yanshouwang.bluetooth_low_energy.proto.Broadcast.Builder): Dsl = Dsl(builder)
} }
@kotlin.jvm.JvmSynthetic @kotlin.jvm.JvmSynthetic
@kotlin.PublishedApi @kotlin.PublishedApi
internal fun _build(): dev.yanshouwang.bluetooth_low_energy.proto.Advertisement = _builder.build() internal fun _build(): dev.yanshouwang.bluetooth_low_energy.proto.Broadcast = _builder.build()
/** /**
* <code>.proto.UUID uuid = 1;</code> * <code>.proto.Peripheral peripheral = 1;</code>
*/ */
var uuid: dev.yanshouwang.bluetooth_low_energy.proto.UUID var peripheral: dev.yanshouwang.bluetooth_low_energy.proto.Peripheral
@JvmName("getUuid") @JvmName("getPeripheral")
get() = _builder.getUuid() get() = _builder.getPeripheral()
@JvmName("setUuid") @JvmName("setPeripheral")
set(value) { set(value) {
_builder.setUuid(value) _builder.setPeripheral(value)
} }
/** /**
* <code>.proto.UUID uuid = 1;</code> * <code>.proto.Peripheral peripheral = 1;</code>
*/ */
fun clearUuid() { fun clearPeripheral() {
_builder.clearUuid() _builder.clearPeripheral()
} }
/** /**
* <code>.proto.UUID uuid = 1;</code> * <code>.proto.Peripheral peripheral = 1;</code>
* @return Whether the uuid field is set. * @return Whether the peripheral field is set.
*/ */
fun hasUuid(): kotlin.Boolean { fun hasPeripheral(): kotlin.Boolean {
return _builder.hasUuid() return _builder.hasPeripheral()
} }
/** /**
@ -387,9 +387,9 @@ object AdvertisementKt {
} }
} }
@kotlin.jvm.JvmSynthetic @kotlin.jvm.JvmSynthetic
inline fun dev.yanshouwang.bluetooth_low_energy.proto.Advertisement.copy(block: dev.yanshouwang.bluetooth_low_energy.proto.AdvertisementKt.Dsl.() -> kotlin.Unit): dev.yanshouwang.bluetooth_low_energy.proto.Advertisement = inline fun dev.yanshouwang.bluetooth_low_energy.proto.Broadcast.copy(block: dev.yanshouwang.bluetooth_low_energy.proto.BroadcastKt.Dsl.() -> kotlin.Unit): dev.yanshouwang.bluetooth_low_energy.proto.Broadcast =
dev.yanshouwang.bluetooth_low_energy.proto.AdvertisementKt.Dsl._create(this.toBuilder()).apply { block() }._build() dev.yanshouwang.bluetooth_low_energy.proto.BroadcastKt.Dsl._create(this.toBuilder()).apply { block() }._build()
val dev.yanshouwang.bluetooth_low_energy.proto.AdvertisementOrBuilder.uuidOrNull: dev.yanshouwang.bluetooth_low_energy.proto.UUID? val dev.yanshouwang.bluetooth_low_energy.proto.BroadcastOrBuilder.peripheralOrNull: dev.yanshouwang.bluetooth_low_energy.proto.Peripheral?
get() = if (hasUuid()) getUuid() else null get() = if (hasPeripheral()) getPeripheral() else null

View File

@ -23,9 +23,9 @@ object GattCharacteristicKt {
internal fun _build(): dev.yanshouwang.bluetooth_low_energy.proto.GattCharacteristic = _builder.build() internal fun _build(): dev.yanshouwang.bluetooth_low_energy.proto.GattCharacteristic = _builder.build()
/** /**
* <code>int64 id = 1;</code> * <code>string id = 1;</code>
*/ */
var id: kotlin.Long var id: kotlin.String
@JvmName("getId") @JvmName("getId")
get() = _builder.getId() get() = _builder.getId()
@JvmName("setId") @JvmName("setId")
@ -33,7 +33,7 @@ object GattCharacteristicKt {
_builder.setId(value) _builder.setId(value)
} }
/** /**
* <code>int64 id = 1;</code> * <code>string id = 1;</code>
*/ */
fun clearId() { fun clearId() {
_builder.clearId() _builder.clearId()

View File

@ -23,9 +23,9 @@ object GattDescriptorKt {
internal fun _build(): dev.yanshouwang.bluetooth_low_energy.proto.GattDescriptor = _builder.build() internal fun _build(): dev.yanshouwang.bluetooth_low_energy.proto.GattDescriptor = _builder.build()
/** /**
* <code>int64 id = 1;</code> * <code>string id = 1;</code>
*/ */
var id: kotlin.Long var id: kotlin.String
@JvmName("getId") @JvmName("getId")
get() = _builder.getId() get() = _builder.getId()
@JvmName("setId") @JvmName("setId")
@ -33,7 +33,7 @@ object GattDescriptorKt {
_builder.setId(value) _builder.setId(value)
} }
/** /**
* <code>int64 id = 1;</code> * <code>string id = 1;</code>
*/ */
fun clearId() { fun clearId() {
_builder.clearId() _builder.clearId()

View File

@ -23,9 +23,9 @@ object GattServiceKt {
internal fun _build(): dev.yanshouwang.bluetooth_low_energy.proto.GattService = _builder.build() internal fun _build(): dev.yanshouwang.bluetooth_low_energy.proto.GattService = _builder.build()
/** /**
* <code>int64 id = 1;</code> * <code>string id = 1;</code>
*/ */
var id: kotlin.Long var id: kotlin.String
@JvmName("getId") @JvmName("getId")
get() = _builder.getId() get() = _builder.getId()
@JvmName("setId") @JvmName("setId")
@ -33,7 +33,7 @@ object GattServiceKt {
_builder.setId(value) _builder.setId(value)
} }
/** /**
* <code>int64 id = 1;</code> * <code>string id = 1;</code>
*/ */
fun clearId() { fun clearId() {
_builder.clearId() _builder.clearId()

View File

@ -23,9 +23,9 @@ object PeripheralKt {
internal fun _build(): dev.yanshouwang.bluetooth_low_energy.proto.Peripheral = _builder.build() internal fun _build(): dev.yanshouwang.bluetooth_low_energy.proto.Peripheral = _builder.build()
/** /**
* <code>int64 id = 1;</code> * <code>string id = 1;</code>
*/ */
var id: kotlin.Long var id: kotlin.String
@JvmName("getId") @JvmName("getId")
get() = _builder.getId() get() = _builder.getId()
@JvmName("setId") @JvmName("setId")
@ -33,27 +33,34 @@ object PeripheralKt {
_builder.setId(value) _builder.setId(value)
} }
/** /**
* <code>int64 id = 1;</code> * <code>string id = 1;</code>
*/ */
fun clearId() { fun clearId() {
_builder.clearId() _builder.clearId()
} }
/** /**
* <code>int32 maximum_write_length = 2;</code> * <code>.proto.UUID uuid = 2;</code>
*/ */
var maximumWriteLength: kotlin.Int var uuid: dev.yanshouwang.bluetooth_low_energy.proto.UUID
@JvmName("getMaximumWriteLength") @JvmName("getUuid")
get() = _builder.getMaximumWriteLength() get() = _builder.getUuid()
@JvmName("setMaximumWriteLength") @JvmName("setUuid")
set(value) { set(value) {
_builder.setMaximumWriteLength(value) _builder.setUuid(value)
} }
/** /**
* <code>int32 maximum_write_length = 2;</code> * <code>.proto.UUID uuid = 2;</code>
*/ */
fun clearMaximumWriteLength() { fun clearUuid() {
_builder.clearMaximumWriteLength() _builder.clearUuid()
}
/**
* <code>.proto.UUID uuid = 2;</code>
* @return Whether the uuid field is set.
*/
fun hasUuid(): kotlin.Boolean {
return _builder.hasUuid()
} }
} }
} }
@ -61,3 +68,6 @@ object PeripheralKt {
inline fun dev.yanshouwang.bluetooth_low_energy.proto.Peripheral.copy(block: dev.yanshouwang.bluetooth_low_energy.proto.PeripheralKt.Dsl.() -> kotlin.Unit): dev.yanshouwang.bluetooth_low_energy.proto.Peripheral = inline fun dev.yanshouwang.bluetooth_low_energy.proto.Peripheral.copy(block: dev.yanshouwang.bluetooth_low_energy.proto.PeripheralKt.Dsl.() -> kotlin.Unit): dev.yanshouwang.bluetooth_low_energy.proto.Peripheral =
dev.yanshouwang.bluetooth_low_energy.proto.PeripheralKt.Dsl._create(this.toBuilder()).apply { block() }._build() dev.yanshouwang.bluetooth_low_energy.proto.PeripheralKt.Dsl._create(this.toBuilder()).apply { block() }._build()
val dev.yanshouwang.bluetooth_low_energy.proto.PeripheralOrBuilder.uuidOrNull: dev.yanshouwang.bluetooth_low_energy.proto.UUID?
get() = if (hasUuid()) getUuid() else null

View File

@ -6,6 +6,8 @@ import 'package:convert/convert.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
CentralManager get central => CentralManager.instance;
void main() { void main() {
const app = MyApp(); const app = MyApp();
runApp(app); runApp(app);
@ -20,9 +22,10 @@ class MyApp extends StatelessWidget {
home: const HomeView(), home: const HomeView(),
routes: { routes: {
'device': (context) { 'device': (context) {
final uuid = ModalRoute.of(context)?.settings.arguments as UUID; final peripheral =
ModalRoute.of(context)?.settings.arguments as Peripheral;
return DeviceView( return DeviceView(
uuid: uuid, peripheral: peripheral,
); );
}, },
}, },
@ -40,10 +43,9 @@ class HomeView extends StatefulWidget {
class _HomeViewState extends State<HomeView> { class _HomeViewState extends State<HomeView> {
late ValueNotifier<bool> state; late ValueNotifier<bool> state;
late ValueNotifier<bool> discovering; late ValueNotifier<bool> discovering;
late ValueNotifier<List<Advertisement>> advertisements; late ValueNotifier<List<Broadcast>> broadcasts;
late Stream<Advertisement> advertisementStream;
late StreamSubscription<BluetoothState> stateStreamSubscription; late StreamSubscription<BluetoothState> stateStreamSubscription;
late StreamSubscription<Advertisement> advertisementStreamSubscription; late StreamSubscription<Broadcast> broadcastStreamSubscription;
@override @override
void initState() { void initState() {
@ -51,22 +53,35 @@ class _HomeViewState extends State<HomeView> {
state = ValueNotifier(false); state = ValueNotifier(false);
discovering = ValueNotifier(false); discovering = ValueNotifier(false);
advertisements = ValueNotifier([]); broadcasts = ValueNotifier([]);
advertisementStream = CentralManager.instance.getAdvertisementStream();
state.addListener(onStateChanged); state.addListener(onStateChanged);
stateStreamSubscription = CentralManager.instance.stateStream.listen( stateStreamSubscription = central.stateChanged.listen(
(state) => this.state.value = state == BluetoothState.poweredOn, (state) => this.state.value = state == BluetoothState.poweredOn,
); );
broadcastStreamSubscription = central.scanned.listen(
(broadcast) {
final broadcasts = this.broadcasts.value;
final i = broadcasts.indexWhere(
(element) => element.peripheral.uuid == broadcast.peripheral.uuid,
);
if (i < 0) {
this.broadcasts.value = [...broadcasts, broadcast];
} else {
broadcasts[i] = broadcast;
this.broadcasts.value = [...broadcasts];
}
},
);
setup(); setup();
} }
void setup() async { void setup() async {
final authorized = await CentralManager.instance.authorize(); final authorized = await central.authorize();
if (!authorized) { if (!authorized) {
throw UnimplementedError(); throw UnimplementedError();
} }
final state = await CentralManager.instance.getState(); final state = await central.state;
this.state.value = state == BluetoothState.poweredOn; this.state.value = state == BluetoothState.poweredOn;
} }
@ -87,10 +102,11 @@ class _HomeViewState extends State<HomeView> {
stopScan(); stopScan();
state.removeListener(onStateChanged); state.removeListener(onStateChanged);
stateStreamSubscription.cancel(); stateStreamSubscription.cancel();
broadcastStreamSubscription.cancel();
state.dispose(); state.dispose();
discovering.dispose(); discovering.dispose();
advertisements.dispose(); broadcasts.dispose();
super.dispose(); super.dispose();
} }
@ -109,17 +125,7 @@ class _HomeViewState extends State<HomeView> {
if (discovering.value || !state.value) { if (discovering.value || !state.value) {
return; return;
} }
advertisementStreamSubscription = advertisementStream.listen( await central.startScan();
(advertisement) {
final index = advertisements.value.indexWhere(
(element) => element.uuid == advertisement.uuid,
);
if (index >= 0) {
return;
}
advertisements.value = [...advertisements.value, advertisement];
},
);
discovering.value = true; discovering.value = true;
} }
@ -127,25 +133,25 @@ class _HomeViewState extends State<HomeView> {
if (!discovering.value || !state.value) { if (!discovering.value || !state.value) {
return; return;
} }
await advertisementStreamSubscription.cancel(); await central.stopScan();
advertisements.value = []; broadcasts.value = [];
discovering.value = false; discovering.value = false;
} }
void showAdvertisement(Advertisement advertisement) { void showBroadcast(Broadcast advertisement) {
showModalBottomSheet( showModalBottomSheet(
context: context, context: context,
backgroundColor: Colors.transparent, backgroundColor: Colors.transparent,
elevation: 0.0, elevation: 0.0,
builder: (context) => buildAdvertisementView(advertisement), builder: (context) => buildBroadcastView(advertisement),
); );
} }
void showDeviceView(UUID uuid) async { void showDeviceView(Peripheral peripheral) async {
stopScan(); stopScan();
await Navigator.of(context).pushNamed( await Navigator.of(context).pushNamed(
'device', 'device',
arguments: uuid, arguments: peripheral,
); );
startScan(); startScan();
} }
@ -156,9 +162,7 @@ extension on _HomeViewState {
return ValueListenableBuilder( return ValueListenableBuilder(
valueListenable: state, valueListenable: state,
builder: (context, bool state, child) { builder: (context, bool state, child) {
return state return state ? buildBroadcastsView(context) : buildClosedView(context);
? buildAdvertisementsView(context)
: buildClosedView(context);
}, },
); );
} }
@ -169,18 +173,18 @@ extension on _HomeViewState {
); );
} }
Widget buildAdvertisementsView(BuildContext context) { Widget buildBroadcastsView(BuildContext context) {
return RefreshIndicator( return RefreshIndicator(
onRefresh: () async => advertisements.value = [], onRefresh: () async => broadcasts.value = [],
child: ValueListenableBuilder( child: ValueListenableBuilder(
valueListenable: advertisements, valueListenable: broadcasts,
builder: (context, List<Advertisement> advertisements, child) { builder: (context, List<Broadcast> broadcasts, child) {
return ListView.builder( return ListView.builder(
padding: const EdgeInsets.all(6.0), padding: const EdgeInsets.all(6.0),
itemCount: advertisements.length, itemCount: broadcasts.length,
itemBuilder: (context, i) { itemBuilder: (context, i) {
final advertisement = advertisements.elementAt(i); final broadcast = broadcasts.elementAt(i);
final connectable = advertisement.connectable ?? true; final connectable = broadcast.connectable ?? true;
return Card( return Card(
color: connectable ? Colors.amber : Colors.grey, color: connectable ? Colors.amber : Colors.grey,
clipBehavior: Clip.antiAlias, clipBehavior: Clip.antiAlias,
@ -191,13 +195,13 @@ extension on _HomeViewState {
), ),
), ),
margin: const EdgeInsets.all(6.0), margin: const EdgeInsets.all(6.0),
key: Key('${advertisement.uuid}'), key: Key(broadcast.peripheral.uuid.value),
child: InkWell( child: InkWell(
splashColor: Colors.purple, splashColor: Colors.purple,
onTap: connectable onTap: connectable
? () => showDeviceView(advertisement.uuid) ? () => showDeviceView(broadcast.peripheral)
: null, : null,
onLongPress: () => showAdvertisement(advertisement), onLongPress: () => showBroadcast(broadcast),
child: Container( child: Container(
height: 100.0, height: 100.0,
padding: const EdgeInsets.all(12.0), padding: const EdgeInsets.all(12.0),
@ -209,9 +213,9 @@ extension on _HomeViewState {
child: Column( child: Column(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: [
Text(advertisement.localName ?? 'UNKNOWN'), Text(broadcast.localName ?? 'UNKNOWN'),
Text( Text(
advertisement.uuid.toString(), broadcast.peripheral.uuid.value,
softWrap: true, softWrap: true,
), ),
], ],
@ -220,7 +224,7 @@ extension on _HomeViewState {
Expanded( Expanded(
flex: 1, flex: 1,
child: Text( child: Text(
advertisement.rssi.toString(), broadcast.rssi.toString(),
textAlign: TextAlign.center, textAlign: TextAlign.center,
), ),
), ),
@ -236,7 +240,7 @@ extension on _HomeViewState {
); );
} }
Widget buildAdvertisementView(Advertisement advertisement) { Widget buildBroadcastView(Broadcast advertisement) {
final widgets = <Widget>[ final widgets = <Widget>[
Row( Row(
children: const [ children: const [
@ -295,11 +299,11 @@ extension on _HomeViewState {
} }
class DeviceView extends StatefulWidget { class DeviceView extends StatefulWidget {
final UUID uuid; final Peripheral peripheral;
const DeviceView({ const DeviceView({
Key? key, Key? key,
required this.uuid, required this.peripheral,
}) : super(key: key); }) : super(key: key);
@override @override
@ -307,7 +311,7 @@ class DeviceView extends StatefulWidget {
} }
class _DeviceViewState extends State<DeviceView> { class _DeviceViewState extends State<DeviceView> {
late Peripheral peripheral; late StreamSubscription<Exception> connectionLostStreamSubscription;
late Map<GattService, List<GattCharacteristic>> services; late Map<GattService, List<GattCharacteristic>> services;
late ValueNotifier<ConnectionState> state; late ValueNotifier<ConnectionState> state;
late ValueNotifier<GattService?> service; late ValueNotifier<GattService?> service;
@ -320,6 +324,18 @@ class _DeviceViewState extends State<DeviceView> {
void initState() { void initState() {
super.initState(); super.initState();
connectionLostStreamSubscription = widget.peripheral.connectionLost.listen(
(error) {
for (var subscription in notifies.value.values) {
subscription.cancel();
}
service.value = null;
characteristic.value = null;
notifies.value.clear();
logs.value.clear();
state.value = ConnectionState.disconnected;
},
);
services = {}; services = {};
state = ValueNotifier(ConnectionState.disconnected); state = ValueNotifier(ConnectionState.disconnected);
service = ValueNotifier(null); service = ValueNotifier(null);
@ -333,7 +349,7 @@ class _DeviceViewState extends State<DeviceView> {
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
title: Text('${widget.uuid}'), title: Text(widget.peripheral.uuid.value),
actions: [ actions: [
buildConnectionState(context), buildConnectionState(context),
], ],
@ -355,6 +371,7 @@ class _DeviceViewState extends State<DeviceView> {
disconnect(); disconnect();
} }
} else { } else {
connectionLostStreamSubscription.cancel();
state.dispose(); state.dispose();
service.dispose(); service.dispose();
characteristic.dispose(); characteristic.dispose();
@ -370,6 +387,7 @@ class _DeviceViewState extends State<DeviceView> {
break; break;
case ConnectionState.disconnected: case ConnectionState.disconnected:
state.removeListener(disposeListener!); state.removeListener(disposeListener!);
connectionLostStreamSubscription.cancel();
state.dispose(); state.dispose();
service.dispose(); service.dispose();
characteristic.dispose(); characteristic.dispose();
@ -384,22 +402,10 @@ class _DeviceViewState extends State<DeviceView> {
void connect() async { void connect() async {
try { try {
state.value = ConnectionState.connecting; state.value = ConnectionState.connecting;
peripheral = await CentralManager.instance.connect( await widget.peripheral.connect();
widget.uuid,
onConnectionLost: (error) {
for (var subscription in notifies.value.values) {
subscription.cancel();
}
service.value = null;
characteristic.value = null;
notifies.value.clear();
logs.value.clear();
state.value = ConnectionState.disconnected;
},
);
try { try {
final items0 = <GattService, List<GattCharacteristic>>{}; final items0 = <GattService, List<GattCharacteristic>>{};
final services = await peripheral.discoverServices(); final services = await widget.peripheral.discoverServices();
for (var service in services) { for (var service in services) {
final items1 = <GattCharacteristic>[]; final items1 = <GattCharacteristic>[];
final characteristics = await service.discoverCharacteristics(); final characteristics = await service.discoverCharacteristics();
@ -410,7 +416,7 @@ class _DeviceViewState extends State<DeviceView> {
} }
this.services = items0; this.services = items0;
} catch (e) { } catch (e) {
peripheral.disconnect(); widget.peripheral.disconnect();
rethrow; rethrow;
} }
state.value = ConnectionState.connected; state.value = ConnectionState.connected;
@ -425,7 +431,7 @@ class _DeviceViewState extends State<DeviceView> {
for (var subscription in notifies.value.values) { for (var subscription in notifies.value.values) {
subscription.cancel(); subscription.cancel();
} }
await peripheral.disconnect(); await widget.peripheral.disconnect();
services = {}; services = {};
service.value = null; service.value = null;
characteristic.value = null; characteristic.value = null;
@ -579,15 +585,17 @@ extension on _DeviceViewState {
await notifiesValue await notifiesValue
.remove(characteristic)! .remove(characteristic)!
.cancel(); .cancel();
await characteristic.setNotify(false);
} else { } else {
notifiesValue[characteristic] = notifiesValue[characteristic] =
characteristic.valueStream characteristic.valueChanged
.listen((value) { .listen((value) {
final time = DateTime.now().display; final time = DateTime.now().display;
final log = final log =
'[$time][NOTIFY] ${hex.encode(value)}'; '[$time][NOTIFY] ${hex.encode(value)}';
logs.value = [...logs.value, log]; logs.value = [...logs.value, log];
}); });
await characteristic.setNotify(true);
} }
notifies.value = {...notifiesValue}; notifies.value = {...notifiesValue};
} }
@ -603,7 +611,7 @@ extension on _DeviceViewState {
final controllerView = TextField( final controllerView = TextField(
controller: writeController, controller: writeController,
decoration: InputDecoration( decoration: InputDecoration(
hintText: 'MTU: ${peripheral.maximumWriteLength}', // hintText: 'MTU: ${peripheral.maximumWriteLength}',
suffixIcon: IconButton( suffixIcon: IconButton(
onPressed: canWrite onPressed: canWrite
? () { ? () {

View File

@ -35,7 +35,7 @@ packages:
path: ".." path: ".."
relative: true relative: true
source: path source: path
version: "1.0.0" version: "1.1.0"
boolean_selector: boolean_selector:
dependency: transitive dependency: transitive
description: description:

View File

@ -12,26 +12,29 @@ class MyCentralManagerDelegate: NSObject, CBCentralManagerDelegate {
func centralManagerDidUpdateState(_ central: CBCentralManager) { func centralManagerDidUpdateState(_ central: CBCentralManager) {
// Checks whether the authorize completion is nil. // Checks whether the authorize completion is nil.
let state = central.state let state = central.state
let completion = items.removeValue(forKey: KEY_AUTHORIZE_COMPLETION) as? (NSNumber?, FlutterError?) -> Void let completion = instances.removeValue(forKey: KEY_AUTHORIZE_COMPLETION) as? (NSNumber?, FlutterError?) -> Void
if state != .unknown && completion != nil { if state != .unknown && completion != nil {
let authorized = NSNumber(value: central.state != .unauthorized) let authorized = NSNumber(value: state != .unauthorized)
completion!(authorized, nil) completion!(authorized, nil)
} }
// Checks whether the state is changed. // Checks whether the state is changed.
let oldNumber = items[KEY_STATE_OBSERVER] as? Int let oldNumber = instances[KEY_STATE_NUMBER] as? Int
if oldNumber == nil {
return
}
let number = central.stateNumber let number = central.stateNumber
if number == oldNumber { if number == oldNumber {
return return
} }
items[KEY_STATE_OBSERVER] = number instances[KEY_STATE_NUMBER] = number
let stateNumber = NSNumber(value: number) let stateNumber = NSNumber(value: number)
centralFlutterApi.notifyState(stateNumber) {_ in } centralFlutterApi.onStateChanged(stateNumber) {_ in }
} }
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) { func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
peripheral.delegate = peripheralDelegate
let id = String(peripheral.hash)
var items = register(id)
items[KEY_PERIPHERAL] = peripheral
// This is a copy on write.
instances[id] = items
let connectable = advertisementData[CBAdvertisementDataIsConnectable] as? Bool let connectable = advertisementData[CBAdvertisementDataIsConnectable] as? Bool
let localName = advertisementData[CBAdvertisementDataLocalNameKey] as? String let localName = advertisementData[CBAdvertisementDataLocalNameKey] as? String
let manufacturerSpecificData = advertisementData[CBAdvertisementDataManufacturerDataKey] as? Data ?? Data() let manufacturerSpecificData = advertisementData[CBAdvertisementDataManufacturerDataKey] as? Data ?? Data()
@ -39,10 +42,13 @@ class MyCentralManagerDelegate: NSObject, CBCentralManagerDelegate {
let serviceUUIDs = advertisementData[CBAdvertisementDataServiceUUIDsKey] as? [CBUUID] ?? [CBUUID]() let serviceUUIDs = advertisementData[CBAdvertisementDataServiceUUIDsKey] as? [CBUUID] ?? [CBUUID]()
let solicitedServiceUUIDs = advertisementData[CBAdvertisementDataSolicitedServiceUUIDsKey] as? [CBUUID] ?? [CBUUID]() let solicitedServiceUUIDs = advertisementData[CBAdvertisementDataSolicitedServiceUUIDsKey] as? [CBUUID] ?? [CBUUID]()
let txPowerLevel = advertisementData[CBAdvertisementDataTxPowerLevelKey] as? NSNumber let txPowerLevel = advertisementData[CBAdvertisementDataTxPowerLevelKey] as? NSNumber
let data = try! Proto_Advertisement.with { let data = try! Proto_Broadcast.with {
$0.peripheral = Proto_Peripheral.with {
$0.id = id
$0.uuid = Proto_UUID.with { $0.uuid = Proto_UUID.with {
$0.value = peripheral.identifier.uuidString $0.value = peripheral.identifier.uuidString
} }
}
$0.rssi = RSSI.int32Value $0.rssi = RSSI.int32Value
if(connectable != nil) { if(connectable != nil) {
$0.connectable = connectable! $0.connectable = connectable!
@ -75,43 +81,32 @@ class MyCentralManagerDelegate: NSObject, CBCentralManagerDelegate {
$0.txPowerLevel = txPowerLevel!.int32Value $0.txPowerLevel = txPowerLevel!.int32Value
} }
}.serializedData() }.serializedData()
let advertisementBuffer = FlutterStandardTypedData(bytes: data) let broadcastBuffer = FlutterStandardTypedData(bytes: data)
centralFlutterApi.notifyAdvertisement(advertisementBuffer) {_ in } centralFlutterApi.onScanned(broadcastBuffer) {_ in }
} }
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
let completion = items.removeValue(forKey: "\(peripheral.hash)/\(KEY_CONNECT_COMPLETION)") as! (FlutterStandardTypedData?, FlutterError?) -> Void let id = String(peripheral.hash)
let data = try! Proto_Peripheral.with { let completion = instances.removeValue(forKey: "\(id)/\(KEY_CONNECT_COMPLETION)") as! (FlutterError?) -> Void
$0.id = Int64(peripheral.hash) completion(nil)
$0.maximumWriteLength = Int32(peripheral.maximumWriteLength)
}.serializedData()
let peripheralValue = FlutterStandardTypedData(bytes: data)
completion(peripheralValue, nil)
} }
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) { func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
let completion = items.removeValue(forKey: "\(peripheral.hash)/\(KEY_CONNECT_COMPLETION)") as! (FlutterStandardTypedData?, FlutterError?) -> Void let id = String(peripheral.hash)
let completion = instances.removeValue(forKey: "\(id)/\(KEY_CONNECT_COMPLETION)") as! (FlutterError?) -> Void
let errorMessage = error?.localizedDescription let errorMessage = error?.localizedDescription
let error = FlutterError(code: BLUETOOTH_LOW_ENERGY_ERROR, message: errorMessage, details: nil) let flutterError = FlutterError(code: BLUETOOTH_LOW_ENERGY_ERROR, message: errorMessage, details: nil)
completion(nil, error) completion(flutterError)
let id = NSNumber(value: peripheral.hash)
instances.removeValue(forKey: id)
} }
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) { func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
let completion = items.removeValue(forKey: "\(peripheral.hash)/\(KEY_DISCONNECT_COMPLETION)") as? (FlutterError?) -> Void let id = String(peripheral.hash)
if completion == nil { if error == nil {
let id = identifiers[peripheral]! let completion = instances.removeValue(forKey: "\(id)/\(KEY_DISCONNECT_COMPLETION)") as! (FlutterError?) -> Void
let data = try! Proto_BluetoothLowEnergyException.with { completion(nil)
$0.message = error?.localizedDescription ?? "Peripheral connection lost."
}.serializedData()
let errorBuffer = FlutterStandardTypedData(bytes: data)
peripheralFlutterApi.notifyConnectionLost(id, errorBuffer: errorBuffer) {_ in }
} else if error == nil {
completion!(nil)
} else { } else {
let flutterError = FlutterError(code: BLUETOOTH_LOW_ENERGY_ERROR, message: error!.localizedDescription, details: nil) let errorMessage = error!.localizedDescription
completion!(flutterError) peripheralFlutterApi.onConnectionLost(id, errorMessage: errorMessage) {_ in }
} }
} }
} }

View File

@ -12,7 +12,7 @@ class MyCentralManagerHostApi: NSObject, PigeonCentralManagerHostApi {
func authorize(_ completion: @escaping (NSNumber?, FlutterError?) -> Void) { func authorize(_ completion: @escaping (NSNumber?, FlutterError?) -> Void) {
let state = central.state let state = central.state
if state == .unknown { if state == .unknown {
items[KEY_AUTHORIZE_COMPLETION] = completion instances[KEY_AUTHORIZE_COMPLETION] = completion
} else { } else {
let authorized = NSNumber(value: state != .unauthorized) let authorized = NSNumber(value: state != .unauthorized)
completion(authorized, nil) completion(authorized, nil)
@ -23,14 +23,6 @@ class MyCentralManagerHostApi: NSObject, PigeonCentralManagerHostApi {
return NSNumber(value: central.stateNumber) return NSNumber(value: central.stateNumber)
} }
func addStateObserver(_ error: AutoreleasingUnsafeMutablePointer<FlutterError?>) {
items[KEY_STATE_OBSERVER] = central.stateNumber
}
func removeStateObserver(_ error: AutoreleasingUnsafeMutablePointer<FlutterError?>) {
items.removeValue(forKey: KEY_STATE_OBSERVER)
}
func startScan(_ uuidBuffers: [FlutterStandardTypedData]?, completion: @escaping (FlutterError?) -> Void) { func startScan(_ uuidBuffers: [FlutterStandardTypedData]?, completion: @escaping (FlutterError?) -> Void) {
let withServices: [CBUUID]? = uuidBuffers?.map { let withServices: [CBUUID]? = uuidBuffers?.map {
let uuid = try! Proto_UUID(serializedData: $0.data) let uuid = try! Proto_UUID(serializedData: $0.data)
@ -44,15 +36,4 @@ class MyCentralManagerHostApi: NSObject, PigeonCentralManagerHostApi {
func stopScan(_ error: AutoreleasingUnsafeMutablePointer<FlutterError?>) { func stopScan(_ error: AutoreleasingUnsafeMutablePointer<FlutterError?>) {
central.stopScan() central.stopScan()
} }
func connect(_ uuidBuffer: FlutterStandardTypedData, completion: @escaping (FlutterStandardTypedData?, FlutterError?) -> Void) {
let uuid = try! Proto_UUID(serializedData: uuidBuffer.data)
let withIdentifiers = [UUID(uuidString: uuid.value)!]
let peripheral = central.retrievePeripherals(withIdentifiers: withIdentifiers).first!
central.connect(peripheral)
items["\(peripheral.hash)/\(KEY_CONNECT_COMPLETION)"] = completion
// Keep a refrence right now to avoid system cancel the connection.
let id = NSNumber(value: peripheral.hash)
instances[id] = peripheral
}
} }

View File

@ -9,44 +9,41 @@ import Foundation
import CoreBluetooth import CoreBluetooth
class MyGattCharacteristicHostApi: NSObject, PigeonGattCharacteristicHostApi { class MyGattCharacteristicHostApi: NSObject, PigeonGattCharacteristicHostApi {
func allocate(_ id: NSNumber, instanceId: NSNumber, error: AutoreleasingUnsafeMutablePointer<FlutterError?>) { func free(_ id: String, error: AutoreleasingUnsafeMutablePointer<FlutterError?>) {
let instance = instances.removeValue(forKey: instanceId) as! CBCharacteristic unregister(id)
instances[id] = instance
identifiers[instance] = id
} }
func free(_ id: NSNumber, error: AutoreleasingUnsafeMutablePointer<FlutterError?>) { func discoverDescriptors(_ id: String, completion: @escaping ([FlutterStandardTypedData]?, FlutterError?) -> Void) {
let instance = instances.removeValue(forKey: id) as! CBCharacteristic let items = instances[id] as! [String: Any]
identifiers.removeValue(forKey: instance) let characteristic = items[KEY_CHARACTERISTIC] as! CBCharacteristic
}
func discoverDescriptors(_ id: NSNumber, completion: @escaping ([FlutterStandardTypedData]?, FlutterError?) -> Void) {
let characteristic = instances[id] as! CBCharacteristic
let peripheral = characteristic.service!.peripheral! let peripheral = characteristic.service!.peripheral!
peripheral.discoverDescriptors(for: characteristic) peripheral.discoverDescriptors(for: characteristic)
items["\(characteristic.hash)/\(KEY_DISCOVER_DESCRIPTORS_COMPLETION)"] = completion instances["\(id)/\(KEY_DISCOVER_DESCRIPTORS_COMPLETION)"] = completion
} }
func read(_ id: NSNumber, completion: @escaping (FlutterStandardTypedData?, FlutterError?) -> Void) { func read(_ id: String, completion: @escaping (FlutterStandardTypedData?, FlutterError?) -> Void) {
let characteristic = instances[id] as! CBCharacteristic let items = instances[id] as! [String: Any]
let characteristic = items[KEY_CHARACTERISTIC] as! CBCharacteristic
let peripheral = characteristic.service!.peripheral! let peripheral = characteristic.service!.peripheral!
peripheral.readValue(for: characteristic) peripheral.readValue(for: characteristic)
items["\(characteristic.hash)/\(KEY_READ_COMPLETION)"] = completion instances["\(id)/\(KEY_READ_COMPLETION)"] = completion
} }
func write(_ id: NSNumber, value: FlutterStandardTypedData, withoutResponse: NSNumber, completion: @escaping (FlutterError?) -> Void) { func write(_ id: String, value: FlutterStandardTypedData, withoutResponse: NSNumber, completion: @escaping (FlutterError?) -> Void) {
let characteristic = instances[id] as! CBCharacteristic let items = instances[id] as! [String: Any]
let characteristic = items[KEY_CHARACTERISTIC] as! CBCharacteristic
let peripheral = characteristic.service!.peripheral! let peripheral = characteristic.service!.peripheral!
let data = value.data let data = value.data
let type: CBCharacteristicWriteType = withoutResponse.boolValue ? .withoutResponse : .withResponse let type: CBCharacteristicWriteType = withoutResponse.boolValue ? .withoutResponse : .withResponse
peripheral.writeValue(data, for: characteristic, type: type) peripheral.writeValue(data, for: characteristic, type: type)
items["\(characteristic.hash)/\(KEY_WRITE_COMPLETION)"] = completion instances["\(id)/\(KEY_WRITE_COMPLETION)"] = completion
} }
func setNotify(_ id: NSNumber, value: NSNumber, completion: @escaping (FlutterError?) -> Void) { func setNotify(_ id: String, value: NSNumber, completion: @escaping (FlutterError?) -> Void) {
let characteristic = instances[id] as! CBCharacteristic let items = instances[id] as! [String: Any]
let characteristic = items[KEY_CHARACTERISTIC] as! CBCharacteristic
let peripheral = characteristic.service!.peripheral! let peripheral = characteristic.service!.peripheral!
peripheral.setNotifyValue(value.boolValue, for: characteristic) peripheral.setNotifyValue(value.boolValue, for: characteristic)
items["\(characteristic.hash)/\(KEY_SET_NOTIFY_COMPLETION)"] = completion instances["\(id)/\(KEY_SET_NOTIFY_COMPLETION)"] = completion
} }
} }

View File

@ -9,29 +9,24 @@ import Foundation
import CoreBluetooth import CoreBluetooth
class MyGattDescriptorHostApi: NSObject, PigeonGattDescriptorHostApi { class MyGattDescriptorHostApi: NSObject, PigeonGattDescriptorHostApi {
func allocate(_ id: NSNumber, instanceId: NSNumber, error: AutoreleasingUnsafeMutablePointer<FlutterError?>) { func free(_ id: String, error: AutoreleasingUnsafeMutablePointer<FlutterError?>) {
let instance = instances.removeValue(forKey: instanceId) as! CBDescriptor unregister(id)
instances[id] = instance
identifiers[instance] = id
} }
func free(_ id: NSNumber, error: AutoreleasingUnsafeMutablePointer<FlutterError?>) { func read(_ id: String, completion: @escaping (FlutterStandardTypedData?, FlutterError?) -> Void) {
let instance = instances.removeValue(forKey: id) as! CBDescriptor let items = instances[id] as! [String: Any]
identifiers.removeValue(forKey: instance) let descriptor = items[KEY_DESCRIPTOR] as! CBDescriptor
}
func read(_ id: NSNumber, completion: @escaping (FlutterStandardTypedData?, FlutterError?) -> Void) {
let descriptor = instances[id] as! CBDescriptor
let peripheral = descriptor.characteristic!.service!.peripheral! let peripheral = descriptor.characteristic!.service!.peripheral!
peripheral.readValue(for: descriptor) peripheral.readValue(for: descriptor)
items["\(descriptor.hash)/\(KEY_READ_COMPLETION)"] = completion instances["\(id)/\(KEY_READ_COMPLETION)"] = completion
} }
func write(_ id: NSNumber, value: FlutterStandardTypedData, completion: @escaping (FlutterError?) -> Void) { func write(_ id: String, value: FlutterStandardTypedData, completion: @escaping (FlutterError?) -> Void) {
let descriptor = instances[id] as! CBDescriptor let items = instances[id] as! [String: Any]
let descriptor = items[KEY_DESCRIPTOR] as! CBDescriptor
let peripheral = descriptor.characteristic!.service!.peripheral! let peripheral = descriptor.characteristic!.service!.peripheral!
let data = value.data let data = value.data
peripheral.writeValue(data, for: descriptor) peripheral.writeValue(data, for: descriptor)
items["\(descriptor.hash)/\(KEY_WRITE_COMPLETION)"] = completion instances["\(id)/\(KEY_WRITE_COMPLETION)"] = completion
} }
} }

View File

@ -9,21 +9,15 @@ import Foundation
import CoreBluetooth import CoreBluetooth
class MyGattServiceHostApi: NSObject, PigeonGattServiceHostApi { class MyGattServiceHostApi: NSObject, PigeonGattServiceHostApi {
func allocate(_ id: NSNumber, instanceId: NSNumber, error: AutoreleasingUnsafeMutablePointer<FlutterError?>) { func free(_ id: String, error: AutoreleasingUnsafeMutablePointer<FlutterError?>) {
let instance = instances.removeValue(forKey: instanceId) as! CBService unregister(id)
instances[id] = instance
identifiers[instance] = id
} }
func free(_ id: NSNumber, error: AutoreleasingUnsafeMutablePointer<FlutterError?>) { func discoverCharacteristics(_ id: String, completion: @escaping ([FlutterStandardTypedData]?, FlutterError?) -> Void) {
let instance = instances.removeValue(forKey: id) as! CBService let items = instances[id] as! [String: Any]
identifiers.removeValue(forKey: instance) let service = items[KEY_SERVICE] as! CBService
}
func discoverCharacteristics(_ id: NSNumber, completion: @escaping ([FlutterStandardTypedData]?, FlutterError?) -> Void) {
let service = instances[id] as! CBService
let peripheral = service.peripheral! let peripheral = service.peripheral!
peripheral.discoverCharacteristics(nil, for: service) peripheral.discoverCharacteristics(nil, for: service)
items["\(service.hash)/\(KEY_DISCOVER_CHARACTERISTICS_COMPLETION)"] = completion instances["\(id)/\(KEY_DISCOVER_CHARACTERISTICS_COMPLETION)"] = completion
} }
} }

View File

@ -10,133 +10,108 @@ import CoreBluetooth
class MyPeripheralDelegate: NSObject, CBPeripheralDelegate { class MyPeripheralDelegate: NSObject, CBPeripheralDelegate {
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
let completion = items.removeValue(forKey: "\(peripheral.hash)/\(KEY_DISCOVER_SERVICES_COMPLETION)") as! ([FlutterStandardTypedData]?, FlutterError?) -> Void let id = String(peripheral.hash)
let completion = instances.removeValue(forKey: "\(id)/\(KEY_DISCOVER_SERVICES_COMPLETION)") as! ([FlutterStandardTypedData]?, FlutterError?) -> Void
if error == nil { if error == nil {
var serviceBuffers = [FlutterStandardTypedData]()
let services = peripheral.services let services = peripheral.services
if services == nil { if services != nil {
let serviceBuffers = [FlutterStandardTypedData]()
completion(serviceBuffers, nil)
} else {
let serviceBuffers: [FlutterStandardTypedData] = services!.map { service in
let data = try! Proto_GattService.with {
$0.id = Int64(service.hash)
$0.uuid = Proto_UUID.with {
$0.value = service.uuid.uuidString
}
}.serializedData()
return FlutterStandardTypedData(bytes: data)
}
completion(serviceBuffers, nil)
for service in services! { for service in services! {
let id = NSNumber(value: service.hash) let serviceBuffer = registerService(service)
instances[id] = service serviceBuffers.append(serviceBuffer)
} }
} }
completion(serviceBuffers, nil)
} else { } else {
let flutterError = FlutterError(code: BLUETOOTH_LOW_ENERGY_ERROR, message: error!.localizedDescription, details: nil) let errorMessage = error!.localizedDescription
let flutterError = FlutterError(code: BLUETOOTH_LOW_ENERGY_ERROR, message: errorMessage, details: nil)
completion(nil, flutterError) completion(nil, flutterError)
} }
} }
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
let completion = items.removeValue(forKey: "\(service.hash)/\(KEY_DISCOVER_CHARACTERISTICS_COMPLETION)") as! ([FlutterStandardTypedData]?, FlutterError?) -> Void let id = String(service.hash)
let completion = instances.removeValue(forKey: "\(id)/\(KEY_DISCOVER_CHARACTERISTICS_COMPLETION)") as! ([FlutterStandardTypedData]?, FlutterError?) -> Void
if error == nil { if error == nil {
var characteristicBuffers = [FlutterStandardTypedData]()
let characteristics = service.characteristics let characteristics = service.characteristics
if characteristics == nil { if characteristics != nil {
let characteristicBuffers = [FlutterStandardTypedData]()
completion(characteristicBuffers, nil)
} else {
let characteristicBuffers: [FlutterStandardTypedData] = characteristics!.map { characteristic in
let data = try! Proto_GattCharacteristic.with {
$0.id = Int64(characteristic.hash)
$0.uuid = Proto_UUID.with {
$0.value = characteristic.uuid.uuidString
}
$0.canRead = characteristic.properties.contains(.read)
$0.canWrite = characteristic.properties.contains(.write)
$0.canWriteWithoutResponse = characteristic.properties.contains(.writeWithoutResponse)
$0.canNotify = characteristic.properties.contains(.notify)
}.serializedData()
return FlutterStandardTypedData(bytes: data)
}
completion(characteristicBuffers, nil)
for characteristic in characteristics! { for characteristic in characteristics! {
let id = NSNumber(value: characteristic.hash) let characteristicBuffer = registerCharacteristic(characteristic)
instances[id] = characteristic characteristicBuffers.append(characteristicBuffer)
} }
} }
completion(characteristicBuffers, nil)
} else { } else {
let flutterError = FlutterError(code: BLUETOOTH_LOW_ENERGY_ERROR, message: error!.localizedDescription, details: nil) let errorMessage = error!.localizedDescription
let flutterError = FlutterError(code: BLUETOOTH_LOW_ENERGY_ERROR, message: errorMessage, details: nil)
completion(nil, flutterError) completion(nil, flutterError)
} }
} }
func peripheral(_ peripheral: CBPeripheral, didDiscoverDescriptorsFor characteristic: CBCharacteristic, error: Error?) { func peripheral(_ peripheral: CBPeripheral, didDiscoverDescriptorsFor characteristic: CBCharacteristic, error: Error?) {
let completion = items.removeValue(forKey: "\(characteristic.hash)/\(KEY_DISCOVER_DESCRIPTORS_COMPLETION)") as! ([FlutterStandardTypedData]?, FlutterError?) -> Void let id = String(characteristic.hash)
let completion = instances.removeValue(forKey: "\(id)/\(KEY_DISCOVER_DESCRIPTORS_COMPLETION)") as! ([FlutterStandardTypedData]?, FlutterError?) -> Void
if error == nil { if error == nil {
var descriptorBuffers = [FlutterStandardTypedData]()
let descriptors = characteristic.descriptors let descriptors = characteristic.descriptors
if descriptors == nil { if descriptors != nil {
let descriptorBuffers = [FlutterStandardTypedData]()
completion(descriptorBuffers, nil)
} else {
let descriptorBuffers: [FlutterStandardTypedData] = descriptors!.map { descriptor in
let data = try! Proto_GattDescriptor.with {
$0.id = Int64(descriptor.hash)
$0.uuid = Proto_UUID.with {
$0.value = descriptor.uuid.uuidString
}
}.serializedData()
return FlutterStandardTypedData(bytes: data)
}
completion(descriptorBuffers, nil)
for descriptor in descriptors! { for descriptor in descriptors! {
let id = NSNumber(value: descriptor.hash) let descriptorBuffer = registerDescriptor(descriptor)
instances[id] = descriptor descriptorBuffers.append(descriptorBuffer)
} }
} }
completion(descriptorBuffers, nil)
} else { } else {
let flutterError = FlutterError(code: BLUETOOTH_LOW_ENERGY_ERROR, message: error!.localizedDescription, details: nil) let errorMessage = error!.localizedDescription
let flutterError = FlutterError(code: BLUETOOTH_LOW_ENERGY_ERROR, message: errorMessage, details: nil)
completion(nil, flutterError) completion(nil, flutterError)
} }
} }
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
let completion = items.removeValue(forKey: "\(characteristic.hash)/\(KEY_READ_COMPLETION)") as? (FlutterStandardTypedData?, FlutterError?) -> Void let id = String(characteristic.hash)
let completion = instances.removeValue(forKey: "\(id)/\(KEY_READ_COMPLETION)") as? (FlutterStandardTypedData?, FlutterError?) -> Void
let characteristicValue = characteristic.value let characteristicValue = characteristic.value
let value = characteristicValue == nil ? FlutterStandardTypedData() : FlutterStandardTypedData(bytes: characteristicValue!) let value = characteristicValue == nil ? FlutterStandardTypedData() : FlutterStandardTypedData(bytes: characteristicValue!)
if completion == nil { if completion == nil {
let id = identifiers[characteristic]! characteristicFlutterApi.onValueChanged(id, value: value) {_ in }
characteristicFlutterApi.notifyValue(id, value: value) {_ in }
} else if error == nil { } else if error == nil {
completion!(value, nil) completion!(value, nil)
} else { } else {
let flutterError = FlutterError(code: BLUETOOTH_LOW_ENERGY_ERROR, message: error!.localizedDescription, details: nil) let errorMessage = error!.localizedDescription
let flutterError = FlutterError(code: BLUETOOTH_LOW_ENERGY_ERROR, message: errorMessage, details: nil)
completion!(nil, flutterError) completion!(nil, flutterError)
} }
} }
func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) { func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
let completion = items.removeValue(forKey: "\(characteristic.hash)/\(KEY_WRITE_COMPLETION)") as! (FlutterError?) -> Void let id = String(characteristic.hash)
let completion = instances.removeValue(forKey: "\(id)/\(KEY_WRITE_COMPLETION)") as! (FlutterError?) -> Void
if error == nil { if error == nil {
completion(nil) completion(nil)
} else { } else {
let flutterError = FlutterError(code: BLUETOOTH_LOW_ENERGY_ERROR, message: error!.localizedDescription, details: nil) let errorMessage = error!.localizedDescription
let flutterError = FlutterError(code: BLUETOOTH_LOW_ENERGY_ERROR, message: errorMessage, details: nil)
completion(flutterError) completion(flutterError)
} }
} }
func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) { func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
let completion = items.removeValue(forKey: "\(characteristic.hash)/\(KEY_SET_NOTIFY_COMPLETION)") as! (FlutterError?) -> Void let id = String(characteristic.hash)
let completion = instances.removeValue(forKey: "\(id)/\(KEY_SET_NOTIFY_COMPLETION)") as! (FlutterError?) -> Void
if error == nil { if error == nil {
completion(nil) completion(nil)
} else { } else {
let flutterError = FlutterError(code: BLUETOOTH_LOW_ENERGY_ERROR, message: error!.localizedDescription, details: nil) let errorMessage = error!.localizedDescription
let flutterError = FlutterError(code: BLUETOOTH_LOW_ENERGY_ERROR, message: errorMessage, details: nil)
completion(flutterError) completion(flutterError)
} }
} }
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor descriptor: CBDescriptor, error: Error?) { func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor descriptor: CBDescriptor, error: Error?) {
let completion = items.removeValue(forKey: "\(descriptor.hash)/\(KEY_READ_COMPLETION)") as! (FlutterStandardTypedData?, FlutterError?) -> Void let id = String(descriptor.hash)
let completion = instances.removeValue(forKey: "\(id)/\(KEY_READ_COMPLETION)") as! (FlutterStandardTypedData?, FlutterError?) -> Void
if error == nil { if error == nil {
let value: FlutterStandardTypedData let value: FlutterStandardTypedData
if descriptor.value == nil { if descriptor.value == nil {
@ -167,18 +142,70 @@ class MyPeripheralDelegate: NSObject, CBPeripheralDelegate {
} }
completion(value, nil) completion(value, nil)
} else { } else {
let flutterError = FlutterError(code: BLUETOOTH_LOW_ENERGY_ERROR, message: error!.localizedDescription, details: nil) let errorMessage = error!.localizedDescription
let flutterError = FlutterError(code: BLUETOOTH_LOW_ENERGY_ERROR, message: errorMessage, details: nil)
completion(nil, flutterError) completion(nil, flutterError)
} }
} }
func peripheral(_ peripheral: CBPeripheral, didWriteValueFor descriptor: CBDescriptor, error: Error?) { func peripheral(_ peripheral: CBPeripheral, didWriteValueFor descriptor: CBDescriptor, error: Error?) {
let completion = items.removeValue(forKey: "\(descriptor.hash)/\(KEY_WRITE_COMPLETION)") as! (FlutterError?) -> Void let id = String(descriptor.hash)
let completion = instances.removeValue(forKey: "\(id)/\(KEY_WRITE_COMPLETION)") as! (FlutterError?) -> Void
if error == nil { if error == nil {
completion(nil) completion(nil)
} else { } else {
let flutterError = FlutterError(code: BLUETOOTH_LOW_ENERGY_ERROR, message: error!.localizedDescription, details: nil) let errorMessage = error!.localizedDescription
let flutterError = FlutterError(code: BLUETOOTH_LOW_ENERGY_ERROR, message: errorMessage, details: nil)
completion(flutterError) completion(flutterError)
} }
} }
private func registerService(_ service: CBService) -> FlutterStandardTypedData {
let id = String(service.hash)
var items = register(id)
items[KEY_SERVICE] = service
// This is a copy on write.
instances[id] = items
let data = try! Proto_GattService.with {
$0.id = id
$0.uuid = Proto_UUID.with {
$0.value = service.uuid.uuidString
}
}.serializedData()
return FlutterStandardTypedData(bytes: data)
}
private func registerCharacteristic(_ characteristic: CBCharacteristic) -> FlutterStandardTypedData {
let id = String(characteristic.hash)
var items = register(id)
items[KEY_CHARACTERISTIC] = characteristic
// This is a copy on write.
instances[id] = items
let data = try! Proto_GattCharacteristic.with {
$0.id = id
$0.uuid = Proto_UUID.with {
$0.value = characteristic.uuid.uuidString
}
$0.canRead = characteristic.properties.contains(.read)
$0.canWrite = characteristic.properties.contains(.write)
$0.canWriteWithoutResponse = characteristic.properties.contains(.writeWithoutResponse)
$0.canNotify = characteristic.properties.contains(.notify)
}.serializedData()
return FlutterStandardTypedData(bytes: data)
}
private func registerDescriptor(_ descriptor: CBDescriptor) -> FlutterStandardTypedData {
let id = String(descriptor.hash)
var items = register(id)
items[KEY_DESCRIPTOR] = descriptor
// This is a copy on write.
instances[id] = items
let data = try! Proto_GattDescriptor.with {
$0.id = id
$0.uuid = Proto_UUID.with {
$0.value = descriptor.uuid.uuidString
}
}.serializedData()
return FlutterStandardTypedData(bytes: data)
}
} }

View File

@ -9,27 +9,36 @@ import Foundation
import CoreBluetooth import CoreBluetooth
class MyPeripheralHostApi: NSObject, PigeonPeripheralHostApi { class MyPeripheralHostApi: NSObject, PigeonPeripheralHostApi {
func allocate(_ id: NSNumber, instanceId: NSNumber, error: AutoreleasingUnsafeMutablePointer<FlutterError?>) { func free(_ id: String, error: AutoreleasingUnsafeMutablePointer<FlutterError?>) {
let instance = instances.removeValue(forKey: instanceId) as! CBPeripheral unregister(id)
instances[id] = instance
identifiers[instance] = id
instance.delegate = peripheralDelegate
} }
func free(_ id: NSNumber, error: AutoreleasingUnsafeMutablePointer<FlutterError?>) { func connect(_ id: String, completion: @escaping (FlutterError?) -> Void) {
let instance = instances.removeValue(forKey: id) as! CBPeripheral let items = instances[id] as! [String: Any]
identifiers.removeValue(forKey: instance) let peripheral = items[KEY_PERIPHERAL] as! CBPeripheral
central.connect(peripheral)
instances["\(id)/\(KEY_CONNECT_COMPLETION)"] = completion
} }
func disconnect(_ id: NSNumber, completion: @escaping (FlutterError?) -> Void) { func disconnect(_ id: String, completion: @escaping (FlutterError?) -> Void) {
let peripheral = instances[id] as! CBPeripheral let items = instances[id] as! [String: Any]
let peripheral = items[KEY_PERIPHERAL] as! CBPeripheral
central.cancelPeripheralConnection(peripheral) central.cancelPeripheralConnection(peripheral)
items["\(peripheral.hash)/\(KEY_DISCONNECT_COMPLETION)"] = completion instances["\(id)/\(KEY_DISCONNECT_COMPLETION)"] = completion
} }
func discoverServices(_ id: NSNumber, completion: @escaping ([FlutterStandardTypedData]?, FlutterError?) -> Void) { func requestMtu(_ id: String, completion: @escaping (NSNumber?, FlutterError?) -> Void) {
let peripheral = instances[id] as! CBPeripheral let items = instances[id] as! [String: Any]
let peripheral = items[KEY_PERIPHERAL] as! CBPeripheral
let value = peripheral.maximumWriteValueLength(for: .withoutResponse)
let maximumWriteLength = NSNumber(value: value)
completion(maximumWriteLength, nil)
}
func discoverServices(_ id: String, completion: @escaping ([FlutterStandardTypedData]?, FlutterError?) -> Void) {
let items = instances[id] as! [String: Any]
let peripheral = items[KEY_PERIPHERAL] as! CBPeripheral
peripheral.discoverServices(nil) peripheral.discoverServices(nil)
items["\(peripheral.hash)/\(KEY_DISCOVER_SERVICES_COMPLETION)"] = completion instances["\(id)/\(KEY_DISCOVER_SERVICES_COMPLETION)"] = completion
} }
} }

View File

@ -12,9 +12,9 @@ public class SwiftBluetoothLowEnergyPlugin: NSObject, FlutterPlugin {
PigeonGattCharacteristicHostApiSetup(binaryMessenger, characteristicHostApi) PigeonGattCharacteristicHostApiSetup(binaryMessenger, characteristicHostApi)
PigeonGattDescriptorHostApiSetup(binaryMessenger, descriptorHostApi) PigeonGattDescriptorHostApiSetup(binaryMessenger, descriptorHostApi)
items[KEY_CENTRAL_MANAGER_FLUTTER_API] = PigeonCentralManagerFlutterApi(binaryMessenger: binaryMessenger) instances[KEY_CENTRAL_MANAGER_FLUTTER_API] = PigeonCentralManagerFlutterApi(binaryMessenger: binaryMessenger)
items[KEY_PERIPHERAL_FLUTTER_API] = PigeonPeripheralFlutterApi(binaryMessenger: binaryMessenger) instances[KEY_PERIPHERAL_FLUTTER_API] = PigeonPeripheralFlutterApi(binaryMessenger: binaryMessenger)
items[KEY_GATT_CHARACTERISTIC_FLUTTER_API] = PigeonGattCharacteristicFlutterApi(binaryMessenger: binaryMessenger) instances[KEY_GATT_CHARACTERISTIC_FLUTTER_API] = PigeonGattCharacteristicFlutterApi(binaryMessenger: binaryMessenger)
} }
} }
@ -22,8 +22,13 @@ let BLUETOOTH_LOW_ENERGY_ERROR = "BLUETOOTH_LOW_ENERGY_ERROR"
let KEY_CENTRAL_MANAGER_FLUTTER_API = "KEY_CENTRAL_MANAGER_FLUTTER_API" let KEY_CENTRAL_MANAGER_FLUTTER_API = "KEY_CENTRAL_MANAGER_FLUTTER_API"
let KEY_PERIPHERAL_FLUTTER_API = "KEY_PERIPHERAL_FLUTTER_API" let KEY_PERIPHERAL_FLUTTER_API = "KEY_PERIPHERAL_FLUTTER_API"
let KEY_GATT_CHARACTERISTIC_FLUTTER_API = "KEY_GATT_CHARACTERISTIC_FLUTTER_API" let KEY_GATT_CHARACTERISTIC_FLUTTER_API = "KEY_GATT_CHARACTERISTIC_FLUTTER_API"
let KEY_STATE_NUMBER = "KEY_STATE_NUMBER"
let KEY_COUNT = "KEY_COUNT"
let KEY_PERIPHERAL = "KEY_PERIPHERAL"
let KEY_SERVICE = "KEY_SERVICE"
let KEY_CHARACTERISTIC = "KEY_CHARACTERISTIC"
let KEY_DESCRIPTOR = "KEY_DESCRIPTOR"
let KEY_AUTHORIZE_COMPLETION = "KEY_AUTHORIZE_COMPLETION" let KEY_AUTHORIZE_COMPLETION = "KEY_AUTHORIZE_COMPLETION"
let KEY_STATE_OBSERVER = "KEY_STATE_OBSERVER"
let KEY_CONNECT_COMPLETION = "KEY_CONNECT_COMPLETION" let KEY_CONNECT_COMPLETION = "KEY_CONNECT_COMPLETION"
let KEY_DISCONNECT_COMPLETION = "KEY_DISCONNECT_COMPLETION" let KEY_DISCONNECT_COMPLETION = "KEY_DISCONNECT_COMPLETION"
let KEY_DISCOVER_SERVICES_COMPLETION = "KEY_DISCOVER_SERVICES_COMPLETION" let KEY_DISCOVER_SERVICES_COMPLETION = "KEY_DISCOVER_SERVICES_COMPLETION"
@ -33,9 +38,7 @@ let KEY_READ_COMPLETION = "KEY_READ_COMPLETION"
let KEY_WRITE_COMPLETION = "KEY_WRITE_COMPLETION" let KEY_WRITE_COMPLETION = "KEY_WRITE_COMPLETION"
let KEY_SET_NOTIFY_COMPLETION = "KEY_SET_NOTIFY_COMPLETION" let KEY_SET_NOTIFY_COMPLETION = "KEY_SET_NOTIFY_COMPLETION"
var items = [String: Any]() var instances = [String: Any]()
var instances = [NSNumber: NSObject]()
var identifiers = [NSObject: NSNumber]()
let central = CBCentralManager(delegate: centralManagerDelegate, queue: nil) let central = CBCentralManager(delegate: centralManagerDelegate, queue: nil)
let centralManagerDelegate = MyCentralManagerDelegate() let centralManagerDelegate = MyCentralManagerDelegate()
@ -47,9 +50,34 @@ let serviceHostApi = MyGattServiceHostApi()
let characteristicHostApi = MyGattCharacteristicHostApi() let characteristicHostApi = MyGattCharacteristicHostApi()
let descriptorHostApi = MyGattDescriptorHostApi() let descriptorHostApi = MyGattDescriptorHostApi()
var centralFlutterApi: PigeonCentralManagerFlutterApi { return items[KEY_CENTRAL_MANAGER_FLUTTER_API] as! PigeonCentralManagerFlutterApi } var centralFlutterApi: PigeonCentralManagerFlutterApi { return instances[KEY_CENTRAL_MANAGER_FLUTTER_API] as! PigeonCentralManagerFlutterApi }
var peripheralFlutterApi: PigeonPeripheralFlutterApi { return items[KEY_PERIPHERAL_FLUTTER_API] as! PigeonPeripheralFlutterApi } var peripheralFlutterApi: PigeonPeripheralFlutterApi { return instances[KEY_PERIPHERAL_FLUTTER_API] as! PigeonPeripheralFlutterApi }
var characteristicFlutterApi: PigeonGattCharacteristicFlutterApi { return items[KEY_GATT_CHARACTERISTIC_FLUTTER_API] as! PigeonGattCharacteristicFlutterApi } var characteristicFlutterApi: PigeonGattCharacteristicFlutterApi { return instances[KEY_GATT_CHARACTERISTIC_FLUTTER_API] as! PigeonGattCharacteristicFlutterApi }
func register(_ id:String) -> [String:Any] {
var items = instances[id] as? [String: Any] ?? [String: Any]()
var count = items[KEY_COUNT] as? Int ?? 0
count += 1
items[KEY_COUNT] = count
// This is a copy on write.
instances[id] = items
debugPrint("register: \(id)")
return items
}
func unregister(_ id: String) {
var items = instances[id] as! [String: Any]
var count = items[KEY_COUNT] as! Int
count -= 1
items[KEY_COUNT] = count
if count < 1 {
instances.removeValue(forKey: id)
debugPrint("unregister: \(id)")
} else {
// This is a copy on write.
instances[id] = items
}
}
extension CBCentralManager { extension CBCentralManager {
var stateNumber: Int { var stateNumber: Int {
@ -63,15 +91,6 @@ extension CBCentralManager {
} }
} }
extension CBPeripheral {
var maximumWriteLength: Int {
let maximumWriteLengthWithResponse = maximumWriteValueLength(for: .withResponse)
let maximumWriteLengthWithoutResponse = maximumWriteValueLength(for: .withoutResponse)
let maximumWriteLength = min(maximumWriteLengthWithResponse, maximumWriteLengthWithoutResponse)
return maximumWriteLength
}
}
extension NSNumber { extension NSNumber {
var data: Data { var data: Data {
var source = self var source = self

View File

@ -1,4 +1,4 @@
// Autogenerated from Pigeon (v4.0.2), do not edit directly. // Autogenerated from Pigeon (v4.2.0), do not edit directly.
// See also: https://pub.dev/packages/pigeon // See also: https://pub.dev/packages/pigeon
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
@protocol FlutterBinaryMessenger; @protocol FlutterBinaryMessenger;
@ -16,11 +16,8 @@ NSObject<FlutterMessageCodec> *PigeonCentralManagerHostApiGetCodec(void);
- (void)authorize:(void(^)(NSNumber *_Nullable, FlutterError *_Nullable))completion; - (void)authorize:(void(^)(NSNumber *_Nullable, FlutterError *_Nullable))completion;
/// @return `nil` only when `error != nil`. /// @return `nil` only when `error != nil`.
- (nullable NSNumber *)getState:(FlutterError *_Nullable *_Nonnull)error; - (nullable NSNumber *)getState:(FlutterError *_Nullable *_Nonnull)error;
- (void)addStateObserver:(FlutterError *_Nullable *_Nonnull)error;
- (void)removeStateObserver:(FlutterError *_Nullable *_Nonnull)error;
- (void)startScan:(nullable NSArray<FlutterStandardTypedData *> *)uuidBuffers completion:(void(^)(FlutterError *_Nullable))completion; - (void)startScan:(nullable NSArray<FlutterStandardTypedData *> *)uuidBuffers completion:(void(^)(FlutterError *_Nullable))completion;
- (void)stopScan:(FlutterError *_Nullable *_Nonnull)error; - (void)stopScan:(FlutterError *_Nullable *_Nonnull)error;
- (void)connect:(FlutterStandardTypedData *)uuidBuffer completion:(void(^)(FlutterStandardTypedData *_Nullable, FlutterError *_Nullable))completion;
@end @end
extern void PigeonCentralManagerHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger, NSObject<PigeonCentralManagerHostApi> *_Nullable api); extern void PigeonCentralManagerHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger, NSObject<PigeonCentralManagerHostApi> *_Nullable api);
@ -30,17 +27,18 @@ NSObject<FlutterMessageCodec> *PigeonCentralManagerFlutterApiGetCodec(void);
@interface PigeonCentralManagerFlutterApi : NSObject @interface PigeonCentralManagerFlutterApi : NSObject
- (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger; - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger;
- (void)notifyState:(NSNumber *)stateNumber completion:(void(^)(NSError *_Nullable))completion; - (void)onStateChanged:(NSNumber *)stateNumber completion:(void(^)(NSError *_Nullable))completion;
- (void)notifyAdvertisement:(FlutterStandardTypedData *)advertisementBuffer completion:(void(^)(NSError *_Nullable))completion; - (void)onScanned:(FlutterStandardTypedData *)broadcastBuffer completion:(void(^)(NSError *_Nullable))completion;
@end @end
///The codec used by PigeonPeripheralHostApi. ///The codec used by PigeonPeripheralHostApi.
NSObject<FlutterMessageCodec> *PigeonPeripheralHostApiGetCodec(void); NSObject<FlutterMessageCodec> *PigeonPeripheralHostApiGetCodec(void);
@protocol PigeonPeripheralHostApi @protocol PigeonPeripheralHostApi
- (void)allocate:(NSNumber *)id instanceId:(NSNumber *)instanceId error:(FlutterError *_Nullable *_Nonnull)error; - (void)free:(NSString *)id error:(FlutterError *_Nullable *_Nonnull)error;
- (void)free:(NSNumber *)id error:(FlutterError *_Nullable *_Nonnull)error; - (void)connect:(NSString *)id completion:(void(^)(FlutterError *_Nullable))completion;
- (void)disconnect:(NSNumber *)id completion:(void(^)(FlutterError *_Nullable))completion; - (void)disconnect:(NSString *)id completion:(void(^)(FlutterError *_Nullable))completion;
- (void)discoverServices:(NSNumber *)id completion:(void(^)(NSArray<FlutterStandardTypedData *> *_Nullable, FlutterError *_Nullable))completion; - (void)requestMtu:(NSString *)id completion:(void(^)(NSNumber *_Nullable, FlutterError *_Nullable))completion;
- (void)discoverServices:(NSString *)id completion:(void(^)(NSArray<FlutterStandardTypedData *> *_Nullable, FlutterError *_Nullable))completion;
@end @end
extern void PigeonPeripheralHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger, NSObject<PigeonPeripheralHostApi> *_Nullable api); extern void PigeonPeripheralHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger, NSObject<PigeonPeripheralHostApi> *_Nullable api);
@ -50,15 +48,14 @@ NSObject<FlutterMessageCodec> *PigeonPeripheralFlutterApiGetCodec(void);
@interface PigeonPeripheralFlutterApi : NSObject @interface PigeonPeripheralFlutterApi : NSObject
- (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger; - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger;
- (void)notifyConnectionLost:(NSNumber *)id errorBuffer:(FlutterStandardTypedData *)errorBuffer completion:(void(^)(NSError *_Nullable))completion; - (void)onConnectionLost:(NSString *)id errorMessage:(NSString *)errorMessage completion:(void(^)(NSError *_Nullable))completion;
@end @end
///The codec used by PigeonGattServiceHostApi. ///The codec used by PigeonGattServiceHostApi.
NSObject<FlutterMessageCodec> *PigeonGattServiceHostApiGetCodec(void); NSObject<FlutterMessageCodec> *PigeonGattServiceHostApiGetCodec(void);
@protocol PigeonGattServiceHostApi @protocol PigeonGattServiceHostApi
- (void)allocate:(NSNumber *)id instanceId:(NSNumber *)instanceId error:(FlutterError *_Nullable *_Nonnull)error; - (void)free:(NSString *)id error:(FlutterError *_Nullable *_Nonnull)error;
- (void)free:(NSNumber *)id error:(FlutterError *_Nullable *_Nonnull)error; - (void)discoverCharacteristics:(NSString *)id completion:(void(^)(NSArray<FlutterStandardTypedData *> *_Nullable, FlutterError *_Nullable))completion;
- (void)discoverCharacteristics:(NSNumber *)id completion:(void(^)(NSArray<FlutterStandardTypedData *> *_Nullable, FlutterError *_Nullable))completion;
@end @end
extern void PigeonGattServiceHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger, NSObject<PigeonGattServiceHostApi> *_Nullable api); extern void PigeonGattServiceHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger, NSObject<PigeonGattServiceHostApi> *_Nullable api);
@ -67,12 +64,11 @@ extern void PigeonGattServiceHostApiSetup(id<FlutterBinaryMessenger> binaryMesse
NSObject<FlutterMessageCodec> *PigeonGattCharacteristicHostApiGetCodec(void); NSObject<FlutterMessageCodec> *PigeonGattCharacteristicHostApiGetCodec(void);
@protocol PigeonGattCharacteristicHostApi @protocol PigeonGattCharacteristicHostApi
- (void)allocate:(NSNumber *)id instanceId:(NSNumber *)instanceId error:(FlutterError *_Nullable *_Nonnull)error; - (void)free:(NSString *)id error:(FlutterError *_Nullable *_Nonnull)error;
- (void)free:(NSNumber *)id error:(FlutterError *_Nullable *_Nonnull)error; - (void)discoverDescriptors:(NSString *)id completion:(void(^)(NSArray<FlutterStandardTypedData *> *_Nullable, FlutterError *_Nullable))completion;
- (void)discoverDescriptors:(NSNumber *)id completion:(void(^)(NSArray<FlutterStandardTypedData *> *_Nullable, FlutterError *_Nullable))completion; - (void)read:(NSString *)id completion:(void(^)(FlutterStandardTypedData *_Nullable, FlutterError *_Nullable))completion;
- (void)read:(NSNumber *)id completion:(void(^)(FlutterStandardTypedData *_Nullable, FlutterError *_Nullable))completion; - (void)write:(NSString *)id value:(FlutterStandardTypedData *)value withoutResponse:(NSNumber *)withoutResponse completion:(void(^)(FlutterError *_Nullable))completion;
- (void)write:(NSNumber *)id value:(FlutterStandardTypedData *)value withoutResponse:(NSNumber *)withoutResponse completion:(void(^)(FlutterError *_Nullable))completion; - (void)setNotify:(NSString *)id value:(NSNumber *)value completion:(void(^)(FlutterError *_Nullable))completion;
- (void)setNotify:(NSNumber *)id value:(NSNumber *)value completion:(void(^)(FlutterError *_Nullable))completion;
@end @end
extern void PigeonGattCharacteristicHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger, NSObject<PigeonGattCharacteristicHostApi> *_Nullable api); extern void PigeonGattCharacteristicHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger, NSObject<PigeonGattCharacteristicHostApi> *_Nullable api);
@ -82,16 +78,15 @@ NSObject<FlutterMessageCodec> *PigeonGattCharacteristicFlutterApiGetCodec(void);
@interface PigeonGattCharacteristicFlutterApi : NSObject @interface PigeonGattCharacteristicFlutterApi : NSObject
- (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger; - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger;
- (void)notifyValue:(NSNumber *)id value:(FlutterStandardTypedData *)value completion:(void(^)(NSError *_Nullable))completion; - (void)onValueChanged:(NSString *)id value:(FlutterStandardTypedData *)value completion:(void(^)(NSError *_Nullable))completion;
@end @end
///The codec used by PigeonGattDescriptorHostApi. ///The codec used by PigeonGattDescriptorHostApi.
NSObject<FlutterMessageCodec> *PigeonGattDescriptorHostApiGetCodec(void); NSObject<FlutterMessageCodec> *PigeonGattDescriptorHostApiGetCodec(void);
@protocol PigeonGattDescriptorHostApi @protocol PigeonGattDescriptorHostApi
- (void)allocate:(NSNumber *)id instanceId:(NSNumber *)instanceId error:(FlutterError *_Nullable *_Nonnull)error; - (void)free:(NSString *)id error:(FlutterError *_Nullable *_Nonnull)error;
- (void)free:(NSNumber *)id error:(FlutterError *_Nullable *_Nonnull)error; - (void)read:(NSString *)id completion:(void(^)(FlutterStandardTypedData *_Nullable, FlutterError *_Nullable))completion;
- (void)read:(NSNumber *)id completion:(void(^)(FlutterStandardTypedData *_Nullable, FlutterError *_Nullable))completion; - (void)write:(NSString *)id value:(FlutterStandardTypedData *)value completion:(void(^)(FlutterError *_Nullable))completion;
- (void)write:(NSNumber *)id value:(FlutterStandardTypedData *)value completion:(void(^)(FlutterError *_Nullable))completion;
@end @end
extern void PigeonGattDescriptorHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger, NSObject<PigeonGattDescriptorHostApi> *_Nullable api); extern void PigeonGattDescriptorHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger, NSObject<PigeonGattDescriptorHostApi> *_Nullable api);

View File

@ -1,6 +1,6 @@
// Autogenerated from Pigeon (v4.0.2), do not edit directly. // Autogenerated from Pigeon (v4.2.0), do not edit directly.
// See also: https://pub.dev/packages/pigeon // See also: https://pub.dev/packages/pigeon
#import "Api.h" #import "Messages.h"
#import <Flutter/Flutter.h> #import <Flutter/Flutter.h>
#if !__has_feature(objc_arc) #if !__has_feature(objc_arc)
@ -101,42 +101,6 @@ void PigeonCentralManagerHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger
[channel setMessageHandler:nil]; [channel setMessageHandler:nil];
} }
} }
{
FlutterBasicMessageChannel *channel =
[[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.CentralManagerHostApi.addStateObserver"
binaryMessenger:binaryMessenger
codec:PigeonCentralManagerHostApiGetCodec() ];
if (api) {
NSCAssert([api respondsToSelector:@selector(addStateObserver:)], @"PigeonCentralManagerHostApi api (%@) doesn't respond to @selector(addStateObserver:)", api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
FlutterError *error;
[api addStateObserver:&error];
callback(wrapResult(nil, error));
}];
}
else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel =
[[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.CentralManagerHostApi.removeStateObserver"
binaryMessenger:binaryMessenger
codec:PigeonCentralManagerHostApiGetCodec() ];
if (api) {
NSCAssert([api respondsToSelector:@selector(removeStateObserver:)], @"PigeonCentralManagerHostApi api (%@) doesn't respond to @selector(removeStateObserver:)", api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
FlutterError *error;
[api removeStateObserver:&error];
callback(wrapResult(nil, error));
}];
}
else {
[channel setMessageHandler:nil];
}
}
{ {
FlutterBasicMessageChannel *channel = FlutterBasicMessageChannel *channel =
[[FlutterBasicMessageChannel alloc] [[FlutterBasicMessageChannel alloc]
@ -175,26 +139,6 @@ void PigeonCentralManagerHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger
[channel setMessageHandler:nil]; [channel setMessageHandler:nil];
} }
} }
{
FlutterBasicMessageChannel *channel =
[[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.CentralManagerHostApi.connect"
binaryMessenger:binaryMessenger
codec:PigeonCentralManagerHostApiGetCodec() ];
if (api) {
NSCAssert([api respondsToSelector:@selector(connect:completion:)], @"PigeonCentralManagerHostApi api (%@) doesn't respond to @selector(connect:completion:)", api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
FlutterStandardTypedData *arg_uuidBuffer = GetNullableObjectAtIndex(args, 0);
[api connect:arg_uuidBuffer completion:^(FlutterStandardTypedData *_Nullable output, FlutterError *_Nullable error) {
callback(wrapResult(output, error));
}];
}];
}
else {
[channel setMessageHandler:nil];
}
}
} }
@interface PigeonCentralManagerFlutterApiCodecReader : FlutterStandardReader @interface PigeonCentralManagerFlutterApiCodecReader : FlutterStandardReader
@end @end
@ -241,23 +185,23 @@ NSObject<FlutterMessageCodec> *PigeonCentralManagerFlutterApiGetCodec() {
} }
return self; return self;
} }
- (void)notifyState:(NSNumber *)arg_stateNumber completion:(void(^)(NSError *_Nullable))completion { - (void)onStateChanged:(NSNumber *)arg_stateNumber completion:(void(^)(NSError *_Nullable))completion {
FlutterBasicMessageChannel *channel = FlutterBasicMessageChannel *channel =
[FlutterBasicMessageChannel [FlutterBasicMessageChannel
messageChannelWithName:@"dev.flutter.pigeon.CentralManagerFlutterApi.notifyState" messageChannelWithName:@"dev.flutter.pigeon.CentralManagerFlutterApi.onStateChanged"
binaryMessenger:self.binaryMessenger binaryMessenger:self.binaryMessenger
codec:PigeonCentralManagerFlutterApiGetCodec()]; codec:PigeonCentralManagerFlutterApiGetCodec()];
[channel sendMessage:@[arg_stateNumber ?: [NSNull null]] reply:^(id reply) { [channel sendMessage:@[arg_stateNumber ?: [NSNull null]] reply:^(id reply) {
completion(nil); completion(nil);
}]; }];
} }
- (void)notifyAdvertisement:(FlutterStandardTypedData *)arg_advertisementBuffer completion:(void(^)(NSError *_Nullable))completion { - (void)onScanned:(FlutterStandardTypedData *)arg_broadcastBuffer completion:(void(^)(NSError *_Nullable))completion {
FlutterBasicMessageChannel *channel = FlutterBasicMessageChannel *channel =
[FlutterBasicMessageChannel [FlutterBasicMessageChannel
messageChannelWithName:@"dev.flutter.pigeon.CentralManagerFlutterApi.notifyAdvertisement" messageChannelWithName:@"dev.flutter.pigeon.CentralManagerFlutterApi.onScanned"
binaryMessenger:self.binaryMessenger binaryMessenger:self.binaryMessenger
codec:PigeonCentralManagerFlutterApiGetCodec()]; codec:PigeonCentralManagerFlutterApiGetCodec()];
[channel sendMessage:@[arg_advertisementBuffer ?: [NSNull null]] reply:^(id reply) { [channel sendMessage:@[arg_broadcastBuffer ?: [NSNull null]] reply:^(id reply) {
completion(nil); completion(nil);
}]; }];
} }
@ -298,17 +242,16 @@ void PigeonPeripheralHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger, NS
{ {
FlutterBasicMessageChannel *channel = FlutterBasicMessageChannel *channel =
[[FlutterBasicMessageChannel alloc] [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.PeripheralHostApi.allocate" initWithName:@"dev.flutter.pigeon.PeripheralHostApi.free"
binaryMessenger:binaryMessenger binaryMessenger:binaryMessenger
codec:PigeonPeripheralHostApiGetCodec() ]; codec:PigeonPeripheralHostApiGetCodec() ];
if (api) { if (api) {
NSCAssert([api respondsToSelector:@selector(allocate:instanceId:error:)], @"PigeonPeripheralHostApi api (%@) doesn't respond to @selector(allocate:instanceId:error:)", api); NSCAssert([api respondsToSelector:@selector(free:error:)], @"PigeonPeripheralHostApi api (%@) doesn't respond to @selector(free:error:)", api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message; NSArray *args = message;
NSNumber *arg_id = GetNullableObjectAtIndex(args, 0); NSString *arg_id = GetNullableObjectAtIndex(args, 0);
NSNumber *arg_instanceId = GetNullableObjectAtIndex(args, 1);
FlutterError *error; FlutterError *error;
[api allocate:arg_id instanceId:arg_instanceId error:&error]; [api free:arg_id error:&error];
callback(wrapResult(nil, error)); callback(wrapResult(nil, error));
}]; }];
} }
@ -319,18 +262,18 @@ void PigeonPeripheralHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger, NS
{ {
FlutterBasicMessageChannel *channel = FlutterBasicMessageChannel *channel =
[[FlutterBasicMessageChannel alloc] [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.PeripheralHostApi.free" initWithName:@"dev.flutter.pigeon.PeripheralHostApi.connect"
binaryMessenger:binaryMessenger binaryMessenger:binaryMessenger
codec:PigeonPeripheralHostApiGetCodec() ]; codec:PigeonPeripheralHostApiGetCodec() ];
if (api) { if (api) {
NSCAssert([api respondsToSelector:@selector(free:error:)], @"PigeonPeripheralHostApi api (%@) doesn't respond to @selector(free:error:)", api); NSCAssert([api respondsToSelector:@selector(connect:completion:)], @"PigeonPeripheralHostApi api (%@) doesn't respond to @selector(connect:completion:)", api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message; NSArray *args = message;
NSNumber *arg_id = GetNullableObjectAtIndex(args, 0); NSString *arg_id = GetNullableObjectAtIndex(args, 0);
FlutterError *error; [api connect:arg_id completion:^(FlutterError *_Nullable error) {
[api free:arg_id error:&error];
callback(wrapResult(nil, error)); callback(wrapResult(nil, error));
}]; }];
}];
} }
else { else {
[channel setMessageHandler:nil]; [channel setMessageHandler:nil];
@ -346,7 +289,7 @@ void PigeonPeripheralHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger, NS
NSCAssert([api respondsToSelector:@selector(disconnect:completion:)], @"PigeonPeripheralHostApi api (%@) doesn't respond to @selector(disconnect:completion:)", api); NSCAssert([api respondsToSelector:@selector(disconnect:completion:)], @"PigeonPeripheralHostApi api (%@) doesn't respond to @selector(disconnect:completion:)", api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message; NSArray *args = message;
NSNumber *arg_id = GetNullableObjectAtIndex(args, 0); NSString *arg_id = GetNullableObjectAtIndex(args, 0);
[api disconnect:arg_id completion:^(FlutterError *_Nullable error) { [api disconnect:arg_id completion:^(FlutterError *_Nullable error) {
callback(wrapResult(nil, error)); callback(wrapResult(nil, error));
}]; }];
@ -356,6 +299,26 @@ void PigeonPeripheralHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger, NS
[channel setMessageHandler:nil]; [channel setMessageHandler:nil];
} }
} }
{
FlutterBasicMessageChannel *channel =
[[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.PeripheralHostApi.requestMtu"
binaryMessenger:binaryMessenger
codec:PigeonPeripheralHostApiGetCodec() ];
if (api) {
NSCAssert([api respondsToSelector:@selector(requestMtu:completion:)], @"PigeonPeripheralHostApi api (%@) doesn't respond to @selector(requestMtu:completion:)", api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSString *arg_id = GetNullableObjectAtIndex(args, 0);
[api requestMtu:arg_id completion:^(NSNumber *_Nullable output, FlutterError *_Nullable error) {
callback(wrapResult(output, error));
}];
}];
}
else {
[channel setMessageHandler:nil];
}
}
{ {
FlutterBasicMessageChannel *channel = FlutterBasicMessageChannel *channel =
[[FlutterBasicMessageChannel alloc] [[FlutterBasicMessageChannel alloc]
@ -366,7 +329,7 @@ void PigeonPeripheralHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger, NS
NSCAssert([api respondsToSelector:@selector(discoverServices:completion:)], @"PigeonPeripheralHostApi api (%@) doesn't respond to @selector(discoverServices:completion:)", api); NSCAssert([api respondsToSelector:@selector(discoverServices:completion:)], @"PigeonPeripheralHostApi api (%@) doesn't respond to @selector(discoverServices:completion:)", api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message; NSArray *args = message;
NSNumber *arg_id = GetNullableObjectAtIndex(args, 0); NSString *arg_id = GetNullableObjectAtIndex(args, 0);
[api discoverServices:arg_id completion:^(NSArray<FlutterStandardTypedData *> *_Nullable output, FlutterError *_Nullable error) { [api discoverServices:arg_id completion:^(NSArray<FlutterStandardTypedData *> *_Nullable output, FlutterError *_Nullable error) {
callback(wrapResult(output, error)); callback(wrapResult(output, error));
}]; }];
@ -422,13 +385,13 @@ NSObject<FlutterMessageCodec> *PigeonPeripheralFlutterApiGetCodec() {
} }
return self; return self;
} }
- (void)notifyConnectionLost:(NSNumber *)arg_id errorBuffer:(FlutterStandardTypedData *)arg_errorBuffer completion:(void(^)(NSError *_Nullable))completion { - (void)onConnectionLost:(NSString *)arg_id errorMessage:(NSString *)arg_errorMessage completion:(void(^)(NSError *_Nullable))completion {
FlutterBasicMessageChannel *channel = FlutterBasicMessageChannel *channel =
[FlutterBasicMessageChannel [FlutterBasicMessageChannel
messageChannelWithName:@"dev.flutter.pigeon.PeripheralFlutterApi.notifyConnectionLost" messageChannelWithName:@"dev.flutter.pigeon.PeripheralFlutterApi.onConnectionLost"
binaryMessenger:self.binaryMessenger binaryMessenger:self.binaryMessenger
codec:PigeonPeripheralFlutterApiGetCodec()]; codec:PigeonPeripheralFlutterApiGetCodec()];
[channel sendMessage:@[arg_id ?: [NSNull null], arg_errorBuffer ?: [NSNull null]] reply:^(id reply) { [channel sendMessage:@[arg_id ?: [NSNull null], arg_errorMessage ?: [NSNull null]] reply:^(id reply) {
completion(nil); completion(nil);
}]; }];
} }
@ -466,27 +429,6 @@ NSObject<FlutterMessageCodec> *PigeonGattServiceHostApiGetCodec() {
void PigeonGattServiceHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger, NSObject<PigeonGattServiceHostApi> *api) { void PigeonGattServiceHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger, NSObject<PigeonGattServiceHostApi> *api) {
{
FlutterBasicMessageChannel *channel =
[[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.GattServiceHostApi.allocate"
binaryMessenger:binaryMessenger
codec:PigeonGattServiceHostApiGetCodec() ];
if (api) {
NSCAssert([api respondsToSelector:@selector(allocate:instanceId:error:)], @"PigeonGattServiceHostApi api (%@) doesn't respond to @selector(allocate:instanceId:error:)", api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_id = GetNullableObjectAtIndex(args, 0);
NSNumber *arg_instanceId = GetNullableObjectAtIndex(args, 1);
FlutterError *error;
[api allocate:arg_id instanceId:arg_instanceId error:&error];
callback(wrapResult(nil, error));
}];
}
else {
[channel setMessageHandler:nil];
}
}
{ {
FlutterBasicMessageChannel *channel = FlutterBasicMessageChannel *channel =
[[FlutterBasicMessageChannel alloc] [[FlutterBasicMessageChannel alloc]
@ -497,7 +439,7 @@ void PigeonGattServiceHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger, N
NSCAssert([api respondsToSelector:@selector(free:error:)], @"PigeonGattServiceHostApi api (%@) doesn't respond to @selector(free:error:)", api); NSCAssert([api respondsToSelector:@selector(free:error:)], @"PigeonGattServiceHostApi api (%@) doesn't respond to @selector(free:error:)", api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message; NSArray *args = message;
NSNumber *arg_id = GetNullableObjectAtIndex(args, 0); NSString *arg_id = GetNullableObjectAtIndex(args, 0);
FlutterError *error; FlutterError *error;
[api free:arg_id error:&error]; [api free:arg_id error:&error];
callback(wrapResult(nil, error)); callback(wrapResult(nil, error));
@ -517,7 +459,7 @@ void PigeonGattServiceHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger, N
NSCAssert([api respondsToSelector:@selector(discoverCharacteristics:completion:)], @"PigeonGattServiceHostApi api (%@) doesn't respond to @selector(discoverCharacteristics:completion:)", api); NSCAssert([api respondsToSelector:@selector(discoverCharacteristics:completion:)], @"PigeonGattServiceHostApi api (%@) doesn't respond to @selector(discoverCharacteristics:completion:)", api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message; NSArray *args = message;
NSNumber *arg_id = GetNullableObjectAtIndex(args, 0); NSString *arg_id = GetNullableObjectAtIndex(args, 0);
[api discoverCharacteristics:arg_id completion:^(NSArray<FlutterStandardTypedData *> *_Nullable output, FlutterError *_Nullable error) { [api discoverCharacteristics:arg_id completion:^(NSArray<FlutterStandardTypedData *> *_Nullable output, FlutterError *_Nullable error) {
callback(wrapResult(output, error)); callback(wrapResult(output, error));
}]; }];
@ -561,27 +503,6 @@ NSObject<FlutterMessageCodec> *PigeonGattCharacteristicHostApiGetCodec() {
void PigeonGattCharacteristicHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger, NSObject<PigeonGattCharacteristicHostApi> *api) { void PigeonGattCharacteristicHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger, NSObject<PigeonGattCharacteristicHostApi> *api) {
{
FlutterBasicMessageChannel *channel =
[[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.GattCharacteristicHostApi.allocate"
binaryMessenger:binaryMessenger
codec:PigeonGattCharacteristicHostApiGetCodec() ];
if (api) {
NSCAssert([api respondsToSelector:@selector(allocate:instanceId:error:)], @"PigeonGattCharacteristicHostApi api (%@) doesn't respond to @selector(allocate:instanceId:error:)", api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_id = GetNullableObjectAtIndex(args, 0);
NSNumber *arg_instanceId = GetNullableObjectAtIndex(args, 1);
FlutterError *error;
[api allocate:arg_id instanceId:arg_instanceId error:&error];
callback(wrapResult(nil, error));
}];
}
else {
[channel setMessageHandler:nil];
}
}
{ {
FlutterBasicMessageChannel *channel = FlutterBasicMessageChannel *channel =
[[FlutterBasicMessageChannel alloc] [[FlutterBasicMessageChannel alloc]
@ -592,7 +513,7 @@ void PigeonGattCharacteristicHostApiSetup(id<FlutterBinaryMessenger> binaryMesse
NSCAssert([api respondsToSelector:@selector(free:error:)], @"PigeonGattCharacteristicHostApi api (%@) doesn't respond to @selector(free:error:)", api); NSCAssert([api respondsToSelector:@selector(free:error:)], @"PigeonGattCharacteristicHostApi api (%@) doesn't respond to @selector(free:error:)", api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message; NSArray *args = message;
NSNumber *arg_id = GetNullableObjectAtIndex(args, 0); NSString *arg_id = GetNullableObjectAtIndex(args, 0);
FlutterError *error; FlutterError *error;
[api free:arg_id error:&error]; [api free:arg_id error:&error];
callback(wrapResult(nil, error)); callback(wrapResult(nil, error));
@ -612,7 +533,7 @@ void PigeonGattCharacteristicHostApiSetup(id<FlutterBinaryMessenger> binaryMesse
NSCAssert([api respondsToSelector:@selector(discoverDescriptors:completion:)], @"PigeonGattCharacteristicHostApi api (%@) doesn't respond to @selector(discoverDescriptors:completion:)", api); NSCAssert([api respondsToSelector:@selector(discoverDescriptors:completion:)], @"PigeonGattCharacteristicHostApi api (%@) doesn't respond to @selector(discoverDescriptors:completion:)", api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message; NSArray *args = message;
NSNumber *arg_id = GetNullableObjectAtIndex(args, 0); NSString *arg_id = GetNullableObjectAtIndex(args, 0);
[api discoverDescriptors:arg_id completion:^(NSArray<FlutterStandardTypedData *> *_Nullable output, FlutterError *_Nullable error) { [api discoverDescriptors:arg_id completion:^(NSArray<FlutterStandardTypedData *> *_Nullable output, FlutterError *_Nullable error) {
callback(wrapResult(output, error)); callback(wrapResult(output, error));
}]; }];
@ -632,7 +553,7 @@ void PigeonGattCharacteristicHostApiSetup(id<FlutterBinaryMessenger> binaryMesse
NSCAssert([api respondsToSelector:@selector(read:completion:)], @"PigeonGattCharacteristicHostApi api (%@) doesn't respond to @selector(read:completion:)", api); NSCAssert([api respondsToSelector:@selector(read:completion:)], @"PigeonGattCharacteristicHostApi api (%@) doesn't respond to @selector(read:completion:)", api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message; NSArray *args = message;
NSNumber *arg_id = GetNullableObjectAtIndex(args, 0); NSString *arg_id = GetNullableObjectAtIndex(args, 0);
[api read:arg_id completion:^(FlutterStandardTypedData *_Nullable output, FlutterError *_Nullable error) { [api read:arg_id completion:^(FlutterStandardTypedData *_Nullable output, FlutterError *_Nullable error) {
callback(wrapResult(output, error)); callback(wrapResult(output, error));
}]; }];
@ -652,7 +573,7 @@ void PigeonGattCharacteristicHostApiSetup(id<FlutterBinaryMessenger> binaryMesse
NSCAssert([api respondsToSelector:@selector(write:value:withoutResponse:completion:)], @"PigeonGattCharacteristicHostApi api (%@) doesn't respond to @selector(write:value:withoutResponse:completion:)", api); NSCAssert([api respondsToSelector:@selector(write:value:withoutResponse:completion:)], @"PigeonGattCharacteristicHostApi api (%@) doesn't respond to @selector(write:value:withoutResponse:completion:)", api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message; NSArray *args = message;
NSNumber *arg_id = GetNullableObjectAtIndex(args, 0); NSString *arg_id = GetNullableObjectAtIndex(args, 0);
FlutterStandardTypedData *arg_value = GetNullableObjectAtIndex(args, 1); FlutterStandardTypedData *arg_value = GetNullableObjectAtIndex(args, 1);
NSNumber *arg_withoutResponse = GetNullableObjectAtIndex(args, 2); NSNumber *arg_withoutResponse = GetNullableObjectAtIndex(args, 2);
[api write:arg_id value:arg_value withoutResponse:arg_withoutResponse completion:^(FlutterError *_Nullable error) { [api write:arg_id value:arg_value withoutResponse:arg_withoutResponse completion:^(FlutterError *_Nullable error) {
@ -674,7 +595,7 @@ void PigeonGattCharacteristicHostApiSetup(id<FlutterBinaryMessenger> binaryMesse
NSCAssert([api respondsToSelector:@selector(setNotify:value:completion:)], @"PigeonGattCharacteristicHostApi api (%@) doesn't respond to @selector(setNotify:value:completion:)", api); NSCAssert([api respondsToSelector:@selector(setNotify:value:completion:)], @"PigeonGattCharacteristicHostApi api (%@) doesn't respond to @selector(setNotify:value:completion:)", api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message; NSArray *args = message;
NSNumber *arg_id = GetNullableObjectAtIndex(args, 0); NSString *arg_id = GetNullableObjectAtIndex(args, 0);
NSNumber *arg_value = GetNullableObjectAtIndex(args, 1); NSNumber *arg_value = GetNullableObjectAtIndex(args, 1);
[api setNotify:arg_id value:arg_value completion:^(FlutterError *_Nullable error) { [api setNotify:arg_id value:arg_value completion:^(FlutterError *_Nullable error) {
callback(wrapResult(nil, error)); callback(wrapResult(nil, error));
@ -731,10 +652,10 @@ NSObject<FlutterMessageCodec> *PigeonGattCharacteristicFlutterApiGetCodec() {
} }
return self; return self;
} }
- (void)notifyValue:(NSNumber *)arg_id value:(FlutterStandardTypedData *)arg_value completion:(void(^)(NSError *_Nullable))completion { - (void)onValueChanged:(NSString *)arg_id value:(FlutterStandardTypedData *)arg_value completion:(void(^)(NSError *_Nullable))completion {
FlutterBasicMessageChannel *channel = FlutterBasicMessageChannel *channel =
[FlutterBasicMessageChannel [FlutterBasicMessageChannel
messageChannelWithName:@"dev.flutter.pigeon.GattCharacteristicFlutterApi.notifyValue" messageChannelWithName:@"dev.flutter.pigeon.GattCharacteristicFlutterApi.onValueChanged"
binaryMessenger:self.binaryMessenger binaryMessenger:self.binaryMessenger
codec:PigeonGattCharacteristicFlutterApiGetCodec()]; codec:PigeonGattCharacteristicFlutterApiGetCodec()];
[channel sendMessage:@[arg_id ?: [NSNull null], arg_value ?: [NSNull null]] reply:^(id reply) { [channel sendMessage:@[arg_id ?: [NSNull null], arg_value ?: [NSNull null]] reply:^(id reply) {
@ -775,27 +696,6 @@ NSObject<FlutterMessageCodec> *PigeonGattDescriptorHostApiGetCodec() {
void PigeonGattDescriptorHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger, NSObject<PigeonGattDescriptorHostApi> *api) { void PigeonGattDescriptorHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger, NSObject<PigeonGattDescriptorHostApi> *api) {
{
FlutterBasicMessageChannel *channel =
[[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.GattDescriptorHostApi.allocate"
binaryMessenger:binaryMessenger
codec:PigeonGattDescriptorHostApiGetCodec() ];
if (api) {
NSCAssert([api respondsToSelector:@selector(allocate:instanceId:error:)], @"PigeonGattDescriptorHostApi api (%@) doesn't respond to @selector(allocate:instanceId:error:)", api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_id = GetNullableObjectAtIndex(args, 0);
NSNumber *arg_instanceId = GetNullableObjectAtIndex(args, 1);
FlutterError *error;
[api allocate:arg_id instanceId:arg_instanceId error:&error];
callback(wrapResult(nil, error));
}];
}
else {
[channel setMessageHandler:nil];
}
}
{ {
FlutterBasicMessageChannel *channel = FlutterBasicMessageChannel *channel =
[[FlutterBasicMessageChannel alloc] [[FlutterBasicMessageChannel alloc]
@ -806,7 +706,7 @@ void PigeonGattDescriptorHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger
NSCAssert([api respondsToSelector:@selector(free:error:)], @"PigeonGattDescriptorHostApi api (%@) doesn't respond to @selector(free:error:)", api); NSCAssert([api respondsToSelector:@selector(free:error:)], @"PigeonGattDescriptorHostApi api (%@) doesn't respond to @selector(free:error:)", api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message; NSArray *args = message;
NSNumber *arg_id = GetNullableObjectAtIndex(args, 0); NSString *arg_id = GetNullableObjectAtIndex(args, 0);
FlutterError *error; FlutterError *error;
[api free:arg_id error:&error]; [api free:arg_id error:&error];
callback(wrapResult(nil, error)); callback(wrapResult(nil, error));
@ -826,7 +726,7 @@ void PigeonGattDescriptorHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger
NSCAssert([api respondsToSelector:@selector(read:completion:)], @"PigeonGattDescriptorHostApi api (%@) doesn't respond to @selector(read:completion:)", api); NSCAssert([api respondsToSelector:@selector(read:completion:)], @"PigeonGattDescriptorHostApi api (%@) doesn't respond to @selector(read:completion:)", api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message; NSArray *args = message;
NSNumber *arg_id = GetNullableObjectAtIndex(args, 0); NSString *arg_id = GetNullableObjectAtIndex(args, 0);
[api read:arg_id completion:^(FlutterStandardTypedData *_Nullable output, FlutterError *_Nullable error) { [api read:arg_id completion:^(FlutterStandardTypedData *_Nullable output, FlutterError *_Nullable error) {
callback(wrapResult(output, error)); callback(wrapResult(output, error));
}]; }];
@ -846,7 +746,7 @@ void PigeonGattDescriptorHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger
NSCAssert([api respondsToSelector:@selector(write:value:completion:)], @"PigeonGattDescriptorHostApi api (%@) doesn't respond to @selector(write:value:completion:)", api); NSCAssert([api respondsToSelector:@selector(write:value:completion:)], @"PigeonGattDescriptorHostApi api (%@) doesn't respond to @selector(write:value:completion:)", api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message; NSArray *args = message;
NSNumber *arg_id = GetNullableObjectAtIndex(args, 0); NSString *arg_id = GetNullableObjectAtIndex(args, 0);
FlutterStandardTypedData *arg_value = GetNullableObjectAtIndex(args, 1); FlutterStandardTypedData *arg_value = GetNullableObjectAtIndex(args, 1);
[api write:arg_id value:arg_value completion:^(FlutterError *_Nullable error) { [api write:arg_id value:arg_value completion:^(FlutterError *_Nullable error) {
callback(wrapResult(nil, error)); callback(wrapResult(nil, error));

View File

@ -64,19 +64,19 @@ extension Proto_BluetoothState: CaseIterable {
#endif // swift(>=4.2) #endif // swift(>=4.2)
struct Proto_Advertisement { struct Proto_Broadcast {
// SwiftProtobuf.Message conformance is added in an extension below. See the // SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for // `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages. // methods supported on all messages.
var uuid: Proto_UUID { var peripheral: Proto_Peripheral {
get {return _uuid ?? Proto_UUID()} get {return _peripheral ?? Proto_Peripheral()}
set {_uuid = newValue} set {_peripheral = newValue}
} }
/// Returns true if `uuid` has been explicitly set. /// Returns true if `peripheral` has been explicitly set.
var hasUuid: Bool {return self._uuid != nil} var hasPeripheral: Bool {return self._peripheral != nil}
/// Clears the value of `uuid`. Subsequent reads from it will return its default value. /// Clears the value of `peripheral`. Subsequent reads from it will return its default value.
mutating func clearUuid() {self._uuid = nil} mutating func clearPeripheral() {self._peripheral = nil}
var rssi: Int32 = 0 var rssi: Int32 = 0
@ -121,7 +121,7 @@ struct Proto_Advertisement {
init() {} init() {}
fileprivate var _uuid: Proto_UUID? = nil fileprivate var _peripheral: Proto_Peripheral? = nil
fileprivate var _connectable: Bool? = nil fileprivate var _connectable: Bool? = nil
fileprivate var _localName: String? = nil fileprivate var _localName: String? = nil
fileprivate var _txPowerLevel: Int32? = nil fileprivate var _txPowerLevel: Int32? = nil
@ -132,13 +132,22 @@ struct Proto_Peripheral {
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for // `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages. // methods supported on all messages.
var id: Int64 = 0 var id: String = String()
var maximumWriteLength: Int32 = 0 var uuid: Proto_UUID {
get {return _uuid ?? Proto_UUID()}
set {_uuid = newValue}
}
/// Returns true if `uuid` has been explicitly set.
var hasUuid: Bool {return self._uuid != nil}
/// Clears the value of `uuid`. Subsequent reads from it will return its default value.
mutating func clearUuid() {self._uuid = nil}
var unknownFields = SwiftProtobuf.UnknownStorage() var unknownFields = SwiftProtobuf.UnknownStorage()
init() {} init() {}
fileprivate var _uuid: Proto_UUID? = nil
} }
struct Proto_GattService { struct Proto_GattService {
@ -146,7 +155,7 @@ struct Proto_GattService {
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for // `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages. // methods supported on all messages.
var id: Int64 = 0 var id: String = String()
var uuid: Proto_UUID { var uuid: Proto_UUID {
get {return _uuid ?? Proto_UUID()} get {return _uuid ?? Proto_UUID()}
@ -169,7 +178,7 @@ struct Proto_GattCharacteristic {
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for // `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages. // methods supported on all messages.
var id: Int64 = 0 var id: String = String()
var uuid: Proto_UUID { var uuid: Proto_UUID {
get {return _uuid ?? Proto_UUID()} get {return _uuid ?? Proto_UUID()}
@ -200,7 +209,7 @@ struct Proto_GattDescriptor {
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for // `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages. // methods supported on all messages.
var id: Int64 = 0 var id: String = String()
var uuid: Proto_UUID { var uuid: Proto_UUID {
get {return _uuid ?? Proto_UUID()} get {return _uuid ?? Proto_UUID()}
@ -253,28 +262,15 @@ struct Proto_ServiceData {
fileprivate var _uuid: Proto_UUID? = nil fileprivate var _uuid: Proto_UUID? = nil
} }
struct Proto_BluetoothLowEnergyException {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var message: String = String()
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
#if swift(>=5.5) && canImport(_Concurrency) #if swift(>=5.5) && canImport(_Concurrency)
extension Proto_BluetoothState: @unchecked Sendable {} extension Proto_BluetoothState: @unchecked Sendable {}
extension Proto_Advertisement: @unchecked Sendable {} extension Proto_Broadcast: @unchecked Sendable {}
extension Proto_Peripheral: @unchecked Sendable {} extension Proto_Peripheral: @unchecked Sendable {}
extension Proto_GattService: @unchecked Sendable {} extension Proto_GattService: @unchecked Sendable {}
extension Proto_GattCharacteristic: @unchecked Sendable {} extension Proto_GattCharacteristic: @unchecked Sendable {}
extension Proto_GattDescriptor: @unchecked Sendable {} extension Proto_GattDescriptor: @unchecked Sendable {}
extension Proto_UUID: @unchecked Sendable {} extension Proto_UUID: @unchecked Sendable {}
extension Proto_ServiceData: @unchecked Sendable {} extension Proto_ServiceData: @unchecked Sendable {}
extension Proto_BluetoothLowEnergyException: @unchecked Sendable {}
#endif // swift(>=5.5) && canImport(_Concurrency) #endif // swift(>=5.5) && canImport(_Concurrency)
// MARK: - Code below here is support for the SwiftProtobuf runtime. // MARK: - Code below here is support for the SwiftProtobuf runtime.
@ -289,10 +285,10 @@ extension Proto_BluetoothState: SwiftProtobuf._ProtoNameProviding {
] ]
} }
extension Proto_Advertisement: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { extension Proto_Broadcast: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".Advertisement" static let protoMessageName: String = _protobuf_package + ".Broadcast"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "uuid"), 1: .same(proto: "peripheral"),
2: .same(proto: "rssi"), 2: .same(proto: "rssi"),
3: .same(proto: "connectable"), 3: .same(proto: "connectable"),
4: .same(proto: "data"), 4: .same(proto: "data"),
@ -310,7 +306,7 @@ extension Proto_Advertisement: SwiftProtobuf.Message, SwiftProtobuf._MessageImpl
// allocates stack space for every case branch when no optimizations are // allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034 // enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber { switch fieldNumber {
case 1: try { try decoder.decodeSingularMessageField(value: &self._uuid) }() case 1: try { try decoder.decodeSingularMessageField(value: &self._peripheral) }()
case 2: try { try decoder.decodeSingularInt32Field(value: &self.rssi) }() case 2: try { try decoder.decodeSingularInt32Field(value: &self.rssi) }()
case 3: try { try decoder.decodeSingularBoolField(value: &self._connectable) }() case 3: try { try decoder.decodeSingularBoolField(value: &self._connectable) }()
case 4: try { try decoder.decodeSingularBytesField(value: &self.data) }() case 4: try { try decoder.decodeSingularBytesField(value: &self.data) }()
@ -330,7 +326,7 @@ extension Proto_Advertisement: SwiftProtobuf.Message, SwiftProtobuf._MessageImpl
// allocates stack space for every if/case branch local when no optimizations // allocates stack space for every if/case branch local when no optimizations
// are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and
// https://github.com/apple/swift-protobuf/issues/1182 // https://github.com/apple/swift-protobuf/issues/1182
try { if let v = self._uuid { try { if let v = self._peripheral {
try visitor.visitSingularMessageField(value: v, fieldNumber: 1) try visitor.visitSingularMessageField(value: v, fieldNumber: 1)
} }() } }()
if self.rssi != 0 { if self.rssi != 0 {
@ -363,8 +359,8 @@ extension Proto_Advertisement: SwiftProtobuf.Message, SwiftProtobuf._MessageImpl
try unknownFields.traverse(visitor: &visitor) try unknownFields.traverse(visitor: &visitor)
} }
static func ==(lhs: Proto_Advertisement, rhs: Proto_Advertisement) -> Bool { static func ==(lhs: Proto_Broadcast, rhs: Proto_Broadcast) -> Bool {
if lhs._uuid != rhs._uuid {return false} if lhs._peripheral != rhs._peripheral {return false}
if lhs.rssi != rhs.rssi {return false} if lhs.rssi != rhs.rssi {return false}
if lhs._connectable != rhs._connectable {return false} if lhs._connectable != rhs._connectable {return false}
if lhs.data != rhs.data {return false} if lhs.data != rhs.data {return false}
@ -383,7 +379,7 @@ extension Proto_Peripheral: SwiftProtobuf.Message, SwiftProtobuf._MessageImpleme
static let protoMessageName: String = _protobuf_package + ".Peripheral" static let protoMessageName: String = _protobuf_package + ".Peripheral"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "id"), 1: .same(proto: "id"),
2: .standard(proto: "maximum_write_length"), 2: .same(proto: "uuid"),
] ]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
@ -392,26 +388,30 @@ extension Proto_Peripheral: SwiftProtobuf.Message, SwiftProtobuf._MessageImpleme
// allocates stack space for every case branch when no optimizations are // allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034 // enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber { switch fieldNumber {
case 1: try { try decoder.decodeSingularInt64Field(value: &self.id) }() case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()
case 2: try { try decoder.decodeSingularInt32Field(value: &self.maximumWriteLength) }() case 2: try { try decoder.decodeSingularMessageField(value: &self._uuid) }()
default: break default: break
} }
} }
} }
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if self.id != 0 { // The use of inline closures is to circumvent an issue where the compiler
try visitor.visitSingularInt64Field(value: self.id, fieldNumber: 1) // allocates stack space for every if/case branch local when no optimizations
} // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and
if self.maximumWriteLength != 0 { // https://github.com/apple/swift-protobuf/issues/1182
try visitor.visitSingularInt32Field(value: self.maximumWriteLength, fieldNumber: 2) if !self.id.isEmpty {
try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)
} }
try { if let v = self._uuid {
try visitor.visitSingularMessageField(value: v, fieldNumber: 2)
} }()
try unknownFields.traverse(visitor: &visitor) try unknownFields.traverse(visitor: &visitor)
} }
static func ==(lhs: Proto_Peripheral, rhs: Proto_Peripheral) -> Bool { static func ==(lhs: Proto_Peripheral, rhs: Proto_Peripheral) -> Bool {
if lhs.id != rhs.id {return false} if lhs.id != rhs.id {return false}
if lhs.maximumWriteLength != rhs.maximumWriteLength {return false} if lhs._uuid != rhs._uuid {return false}
if lhs.unknownFields != rhs.unknownFields {return false} if lhs.unknownFields != rhs.unknownFields {return false}
return true return true
} }
@ -430,7 +430,7 @@ extension Proto_GattService: SwiftProtobuf.Message, SwiftProtobuf._MessageImplem
// allocates stack space for every case branch when no optimizations are // allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034 // enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber { switch fieldNumber {
case 1: try { try decoder.decodeSingularInt64Field(value: &self.id) }() case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()
case 2: try { try decoder.decodeSingularMessageField(value: &self._uuid) }() case 2: try { try decoder.decodeSingularMessageField(value: &self._uuid) }()
default: break default: break
} }
@ -442,8 +442,8 @@ extension Proto_GattService: SwiftProtobuf.Message, SwiftProtobuf._MessageImplem
// allocates stack space for every if/case branch local when no optimizations // allocates stack space for every if/case branch local when no optimizations
// are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and
// https://github.com/apple/swift-protobuf/issues/1182 // https://github.com/apple/swift-protobuf/issues/1182
if self.id != 0 { if !self.id.isEmpty {
try visitor.visitSingularInt64Field(value: self.id, fieldNumber: 1) try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)
} }
try { if let v = self._uuid { try { if let v = self._uuid {
try visitor.visitSingularMessageField(value: v, fieldNumber: 2) try visitor.visitSingularMessageField(value: v, fieldNumber: 2)
@ -476,7 +476,7 @@ extension Proto_GattCharacteristic: SwiftProtobuf.Message, SwiftProtobuf._Messag
// allocates stack space for every case branch when no optimizations are // allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034 // enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber { switch fieldNumber {
case 1: try { try decoder.decodeSingularInt64Field(value: &self.id) }() case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()
case 2: try { try decoder.decodeSingularMessageField(value: &self._uuid) }() case 2: try { try decoder.decodeSingularMessageField(value: &self._uuid) }()
case 3: try { try decoder.decodeSingularBoolField(value: &self.canRead) }() case 3: try { try decoder.decodeSingularBoolField(value: &self.canRead) }()
case 4: try { try decoder.decodeSingularBoolField(value: &self.canWrite) }() case 4: try { try decoder.decodeSingularBoolField(value: &self.canWrite) }()
@ -492,8 +492,8 @@ extension Proto_GattCharacteristic: SwiftProtobuf.Message, SwiftProtobuf._Messag
// allocates stack space for every if/case branch local when no optimizations // allocates stack space for every if/case branch local when no optimizations
// are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and
// https://github.com/apple/swift-protobuf/issues/1182 // https://github.com/apple/swift-protobuf/issues/1182
if self.id != 0 { if !self.id.isEmpty {
try visitor.visitSingularInt64Field(value: self.id, fieldNumber: 1) try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)
} }
try { if let v = self._uuid { try { if let v = self._uuid {
try visitor.visitSingularMessageField(value: v, fieldNumber: 2) try visitor.visitSingularMessageField(value: v, fieldNumber: 2)
@ -538,7 +538,7 @@ extension Proto_GattDescriptor: SwiftProtobuf.Message, SwiftProtobuf._MessageImp
// allocates stack space for every case branch when no optimizations are // allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034 // enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber { switch fieldNumber {
case 1: try { try decoder.decodeSingularInt64Field(value: &self.id) }() case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()
case 2: try { try decoder.decodeSingularMessageField(value: &self._uuid) }() case 2: try { try decoder.decodeSingularMessageField(value: &self._uuid) }()
default: break default: break
} }
@ -550,8 +550,8 @@ extension Proto_GattDescriptor: SwiftProtobuf.Message, SwiftProtobuf._MessageImp
// allocates stack space for every if/case branch local when no optimizations // allocates stack space for every if/case branch local when no optimizations
// are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and
// https://github.com/apple/swift-protobuf/issues/1182 // https://github.com/apple/swift-protobuf/issues/1182
if self.id != 0 { if !self.id.isEmpty {
try visitor.visitSingularInt64Field(value: self.id, fieldNumber: 1) try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)
} }
try { if let v = self._uuid { try { if let v = self._uuid {
try visitor.visitSingularMessageField(value: v, fieldNumber: 2) try visitor.visitSingularMessageField(value: v, fieldNumber: 2)
@ -640,35 +640,3 @@ extension Proto_ServiceData: SwiftProtobuf.Message, SwiftProtobuf._MessageImplem
return true return true
} }
} }
extension Proto_BluetoothLowEnergyException: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".BluetoothLowEnergyException"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "message"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularStringField(value: &self.message) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.message.isEmpty {
try visitor.visitSingularStringField(value: self.message, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Proto_BluetoothLowEnergyException, rhs: Proto_BluetoothLowEnergyException) -> Bool {
if lhs.message != rhs.message {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}

View File

@ -4,6 +4,5 @@ export 'src/gatt_service.dart';
export 'src/gatt_characteristic.dart'; export 'src/gatt_characteristic.dart';
export 'src/gatt_descriptor.dart'; export 'src/gatt_descriptor.dart';
export 'src/bluetooth_state.dart'; export 'src/bluetooth_state.dart';
export 'src/advertisement.dart'; export 'src/broadcast.dart';
export 'src/uuid.dart'; export 'src/uuid.dart';
export 'src/exception.dart';

View File

@ -24,16 +24,13 @@ abstract class CentralManagerApi extends PlatformInterface {
_instance = instance; _instance = instance;
} }
Stream<int> get stateStream; Future<int> get state;
Stream<Uint8List> get advertisementStream; Stream<int> get stateChanged;
Stream<Uint8List> get scanned;
Future<bool> authorize(); Future<bool> authorize();
Future<int> getState();
Future<void> addStateObserver();
Future<void> removeStateObserver();
Future<void> startScan(List<Uint8List>? uuidBuffers); Future<void> startScan(List<Uint8List>? uuidBuffers);
Future<void> stopScan(); Future<void> stopScan();
Future<Uint8List> connect(Uint8List uuidBuffer);
} }
abstract class PeripheralApi extends PlatformInterface { abstract class PeripheralApi extends PlatformInterface {
@ -55,12 +52,13 @@ abstract class PeripheralApi extends PlatformInterface {
_instance = instance; _instance = instance;
} }
Stream<Tuple2<int, Uint8List>> get connectionLostStream; Stream<Tuple2<String, String>> get connectionLost;
Future<void> allocate(int id, int instanceId); Future<void> free(String id);
Future<void> free(int id); Future<void> connect(String id);
Future<void> disconnect(int id); Future<void> disconnect(String id);
Future<List<Uint8List>> discoverServices(int id); Future<int> requestMtu(String id);
Future<List<Uint8List>> discoverServices(String id);
} }
abstract class GattServiceApi extends PlatformInterface { abstract class GattServiceApi extends PlatformInterface {
@ -82,9 +80,8 @@ abstract class GattServiceApi extends PlatformInterface {
_instance = instance; _instance = instance;
} }
Future<void> allocate(int id, int instanceId); Future<void> free(String id);
Future<void> free(int id); Future<List<Uint8List>> discoverCharacteristics(String id);
Future<List<Uint8List>> discoverCharacteristics(int id);
} }
abstract class GattCharacteristicApi extends PlatformInterface { abstract class GattCharacteristicApi extends PlatformInterface {
@ -106,14 +103,13 @@ abstract class GattCharacteristicApi extends PlatformInterface {
_instance = instance; _instance = instance;
} }
Stream<Tuple2<int, Uint8List>> get valueStream; Stream<Tuple2<String, Uint8List>> get valueChanged;
Future<void> allocate(int id, int instanceId); Future<void> free(String id);
Future<void> free(int id); Future<List<Uint8List>> discoverDescriptors(String id);
Future<List<Uint8List>> discoverDescriptors(int id); Future<Uint8List> read(String id);
Future<Uint8List> read(int id); Future<void> write(String id, Uint8List value, bool withoutResponse);
Future<void> write(int id, Uint8List value, bool withoutResponse); Future<void> setNotify(String id, bool value);
Future<void> setNotify(int id, bool value);
} }
abstract class GattDescriptorApi extends PlatformInterface { abstract class GattDescriptorApi extends PlatformInterface {
@ -135,8 +131,7 @@ abstract class GattDescriptorApi extends PlatformInterface {
_instance = instance; _instance = instance;
} }
Future<void> allocate(int id, int instanceId); Future<void> free(String id);
Future<void> free(int id); Future<Uint8List> read(String id);
Future<Uint8List> read(int id); Future<void> write(String id, Uint8List value);
Future<void> write(int id, Uint8List value);
} }

View File

@ -1,9 +1,10 @@
import 'dart:typed_data'; import 'dart:typed_data';
import 'peripheral.dart';
import 'uuid.dart'; import 'uuid.dart';
abstract class Advertisement { abstract class Broadcast {
UUID get uuid; Peripheral get peripheral;
int get rssi; int get rssi;
bool? get connectable; bool? get connectable;
Uint8List get data; Uint8List get data;

View File

@ -1,19 +1,17 @@
import 'advertisement.dart'; import 'broadcast.dart';
import 'impl.dart'; import 'impl.dart';
import 'bluetooth_state.dart'; import 'bluetooth_state.dart';
import 'peripheral.dart';
import 'uuid.dart'; import 'uuid.dart';
abstract class CentralManager { abstract class CentralManager {
Stream<BluetoothState> get stateStream; Future<BluetoothState> get state;
Stream<BluetoothState> get stateChanged;
Stream<Broadcast> get scanned;
Future<bool> authorize(); Future<bool> authorize();
Future<BluetoothState> getState(); Future<void> startScan({List<UUID>? uuids});
Stream<Advertisement> getAdvertisementStream({List<UUID>? uuids}); Future<void> stopScan();
Future<Peripheral> connect(
UUID uuid, {
Function(Exception)? onConnectionLost,
});
static CentralManager instance = MyCentralManager(); static final _instance = MyCentralManager();
static CentralManager get instance => _instance;
} }

View File

@ -1,9 +0,0 @@
import 'impl.dart';
abstract class BluetoothLowEnergyException implements Exception {
String get message;
factory BluetoothLowEnergyException({required String message}) {
return MyBluetoothLowEnergyException(message: message);
}
}

View File

@ -9,9 +9,10 @@ abstract class GattCharacteristic {
bool get canWrite; bool get canWrite;
bool get canWriteWithoutResponse; bool get canWriteWithoutResponse;
bool get canNotify; bool get canNotify;
Stream<Uint8List> get valueStream; Stream<Uint8List> get valueChanged;
Future<List<GattDescriptor>> discoverDescriptors(); Future<List<GattDescriptor>> discoverDescriptors();
Future<Uint8List> read(); Future<Uint8List> read();
Future<void> write(Uint8List value, {bool withoutResponse = false}); Future<void> write(Uint8List value, {bool withoutResponse = false});
Future<void> setNotify(bool value);
} }

View File

@ -1,13 +1,12 @@
import 'dart:async'; import 'dart:async';
import 'dart:typed_data';
import 'package:flutter/services.dart';
import 'package:tuple/tuple.dart'; import 'package:tuple/tuple.dart';
import 'advertisement.dart'; import 'broadcast.dart';
import 'api.dart'; import 'api.dart';
import 'bluetooth_state.dart'; import 'bluetooth_state.dart';
import 'central_manager.dart'; import 'central_manager.dart';
import 'exception.dart';
import 'gatt_characteristic.dart'; import 'gatt_characteristic.dart';
import 'gatt_descriptor.dart'; import 'gatt_descriptor.dart';
import 'gatt_service.dart'; import 'gatt_service.dart';
@ -16,45 +15,30 @@ import 'pigeon.dart';
import 'proto.dart' as proto; import 'proto.dart' as proto;
import 'uuid.dart'; import 'uuid.dart';
final finalizer = Finalizer<void Function()>((free) => free()); const bluetoothLowEnergyError = 'bluetoothLowEnergyError';
class MyCentralManagerApi extends CentralManagerApi class MyCentralManagerApi extends CentralManagerApi
implements CentralManagerFlutterApi { implements CentralManagerFlutterApi {
final hostApi = CentralManagerHostApi(); final hostApi = CentralManagerHostApi();
final stateStreamController = StreamController<int>.broadcast(); final stateStreamController = StreamController<int>.broadcast();
final advertisementStreamController = StreamController<Uint8List>.broadcast(); final broadcastStreamController = StreamController<Uint8List>.broadcast();
MyCentralManagerApi() { MyCentralManagerApi() {
CentralManagerFlutterApi.setup(this); CentralManagerFlutterApi.setup(this);
} }
@override @override
Stream<int> get stateStream => stateStreamController.stream; Future<int> get state => hostApi.getState();
@override @override
Stream<Uint8List> get advertisementStream => Stream<int> get stateChanged => stateStreamController.stream;
advertisementStreamController.stream; @override
Stream<Uint8List> get scanned => broadcastStreamController.stream;
@override @override
Future<bool> authorize() { Future<bool> authorize() {
return hostApi.authorize(); return hostApi.authorize();
} }
@override
Future<int> getState() {
return hostApi.getState();
}
@override
Future<void> addStateObserver() {
return hostApi.addStateObserver();
}
@override
Future<void> removeStateObserver() {
return hostApi.removeStateObserver();
}
@override @override
Future<void> startScan(List<Uint8List>? uuidBuffers) { Future<void> startScan(List<Uint8List>? uuidBuffers) {
return hostApi.startScan(uuidBuffers); return hostApi.startScan(uuidBuffers);
@ -66,57 +50,57 @@ class MyCentralManagerApi extends CentralManagerApi
} }
@override @override
Future<Uint8List> connect(Uint8List uuidBuffer) { void onStateChanged(int stateNumber) {
return hostApi.connect(uuidBuffer);
}
@override
void notifyState(int stateNumber) {
stateStreamController.add(stateNumber); stateStreamController.add(stateNumber);
} }
@override @override
void notifyAdvertisement(Uint8List advertisementBuffer) { void onScanned(Uint8List broadcastBuffer) {
advertisementStreamController.add(advertisementBuffer); broadcastStreamController.add(broadcastBuffer);
} }
} }
class MyPeripheralApi extends PeripheralApi implements PeripheralFlutterApi { class MyPeripheralApi extends PeripheralApi implements PeripheralFlutterApi {
final hostApi = PeripheralHostApi(); final hostApi = PeripheralHostApi();
final connectionLostStreamController = final connectionLostStreamController =
StreamController<Tuple2<int, Uint8List>>.broadcast(); StreamController<Tuple2<String, String>>.broadcast();
MyPeripheralApi() { MyPeripheralApi() {
PeripheralFlutterApi.setup(this); PeripheralFlutterApi.setup(this);
} }
@override @override
Stream<Tuple2<int, Uint8List>> get connectionLostStream => Stream<Tuple2<String, String>> get connectionLost =>
connectionLostStreamController.stream; connectionLostStreamController.stream;
@override @override
Future<void> allocate(int id, int instanceId) { Future<void> free(String id) {
return hostApi.allocate(id, instanceId);
}
@override
Future<void> free(int id) {
return hostApi.free(id); return hostApi.free(id);
} }
@override @override
Future<void> disconnect(int id) { Future<void> connect(String id) {
return hostApi.connect(id);
}
@override
Future<void> disconnect(String id) {
return hostApi.disconnect(id); return hostApi.disconnect(id);
} }
@override @override
Future<List<Uint8List>> discoverServices(int id) { Future<int> requestMtu(String id) {
return hostApi.discoverServices(id).then((value) => value.cast()); return hostApi.requestMtu(id);
} }
@override @override
void notifyConnectionLost(int id, Uint8List errorBuffer) { Future<List<Uint8List>> discoverServices(String id) {
final event = Tuple2(id, errorBuffer); return hostApi.discoverServices(id).then((buffers) => buffers.cast());
}
@override
void onConnectionLost(String id, String errorMessage) {
final event = Tuple2(id, errorMessage);
connectionLostStreamController.add(event); connectionLostStreamController.add(event);
} }
} }
@ -125,17 +109,12 @@ class MyGattServiceApi extends GattServiceApi {
final hostApi = GattServiceHostApi(); final hostApi = GattServiceHostApi();
@override @override
Future<void> allocate(int id, int instanceId) { Future<void> free(String id) {
return hostApi.allocate(id, instanceId);
}
@override
Future<void> free(int id) {
return hostApi.free(id); return hostApi.free(id);
} }
@override @override
Future<List<Uint8List>> discoverCharacteristics(int id) { Future<List<Uint8List>> discoverCharacteristics(String id) {
return hostApi return hostApi
.discoverCharacteristics(id) .discoverCharacteristics(id)
.then((buffers) => buffers.cast()); .then((buffers) => buffers.cast());
@ -151,44 +130,39 @@ class MyGattCharacteristicApi extends GattCharacteristicApi
} }
final valueStreamController = final valueStreamController =
StreamController<Tuple2<int, Uint8List>>.broadcast(); StreamController<Tuple2<String, Uint8List>>.broadcast();
@override @override
Stream<Tuple2<int, Uint8List>> get valueStream => Stream<Tuple2<String, Uint8List>> get valueChanged =>
valueStreamController.stream; valueStreamController.stream;
@override @override
Future<void> allocate(int id, int instanceId) { Future<void> free(String id) {
return hostApi.allocate(id, instanceId);
}
@override
Future<void> free(int id) {
return hostApi.free(id); return hostApi.free(id);
} }
@override @override
Future<List<Uint8List>> discoverDescriptors(int id) { Future<List<Uint8List>> discoverDescriptors(String id) {
return hostApi.discoverDescriptors(id).then((buffers) => buffers.cast()); return hostApi.discoverDescriptors(id).then((buffers) => buffers.cast());
} }
@override @override
Future<Uint8List> read(int id) { Future<Uint8List> read(String id) {
return hostApi.read(id); return hostApi.read(id);
} }
@override @override
Future<void> write(int id, Uint8List value, bool withoutResponse) { Future<void> write(String id, Uint8List value, bool withoutResponse) {
return hostApi.write(id, value, withoutResponse); return hostApi.write(id, value, withoutResponse);
} }
@override @override
Future<void> setNotify(int id, bool value) { Future<void> setNotify(String id, bool value) {
return hostApi.setNotify(id, value); return hostApi.setNotify(id, value);
} }
@override @override
void notifyValue(int id, Uint8List value) { void onValueChanged(String id, Uint8List value) {
final event = Tuple2(id, value); final event = Tuple2(id, value);
valueStreamController.add(event); valueStreamController.add(event);
} }
@ -198,89 +172,54 @@ class MyGattDescriptorApi extends GattDescriptorApi {
final hostApi = GattDescriptorHostApi(); final hostApi = GattDescriptorHostApi();
@override @override
Future<void> allocate(int id, int instanceId) { Future<void> free(String id) {
return hostApi.allocate(id, instanceId);
}
@override
Future<void> free(int id) {
return hostApi.free(id); return hostApi.free(id);
} }
@override @override
Future<Uint8List> read(int id) { Future<Uint8List> read(String id) {
return hostApi.read(id); return hostApi.read(id);
} }
@override @override
Future<void> write(int id, Uint8List value) { Future<void> write(String id, Uint8List value) {
return hostApi.write(id, value); return hostApi.write(id, value);
} }
} }
class MyCentralManager implements CentralManager { class MyCentralManager implements CentralManager {
static CentralManagerApi get api => CentralManagerApi.instance;
@override @override
Stream<Advertisement> getAdvertisementStream({List<UUID>? uuids}) { Future<BluetoothState> get state =>
return CentralManagerApi.instance.advertisementStream api.state.then((number) => BluetoothState.values[number]);
.map((buffer) => MyAdvertisement.fromBuffer(buffer)) @override
.asBroadcastStream( Stream<BluetoothState> get stateChanged =>
onListen: (subscription) async { api.stateChanged.map((number) => BluetoothState.values[number]);
subscription.resume(); @override
final uuidBuffers = uuids Stream<Broadcast> get scanned =>
?.map((e) => proto.UUID(value: e.value).writeToBuffer()) api.scanned.map((buffer) => MyBroadcast.fromBuffer(buffer));
.toList();
await CentralManagerApi.instance.startScan(uuidBuffers);
},
onCancel: (subscription) async {
// TODO: the stream can't listen again when use `subscription.cancel()`.
await CentralManagerApi.instance.stopScan();
subscription.pause();
},
);
}
@override @override
Future<bool> authorize() { Future<bool> authorize() {
return CentralManagerApi.instance.authorize(); return api.authorize();
} }
@override @override
Future<BluetoothState> getState() { Future<void> startScan({List<UUID>? uuids}) {
return CentralManagerApi.instance final uuidBuffers = uuids?.map((uuid) => uuid.buffer).toList();
.getState() return api.startScan(uuidBuffers);
.then((number) => BluetoothState.values[number]);
} }
@override @override
Stream<BluetoothState> get stateStream => Future<void> stopScan() {
CentralManagerApi.instance.stateStream return api.stopScan();
.map((number) => BluetoothState.values[number])
.asBroadcastStream(
onListen: (subscription) async {
subscription.resume();
await CentralManagerApi.instance.addStateObserver();
},
onCancel: (subscription) async {
// TODO: the stream can't listen again when use `subscription.cancel()`.
await CentralManagerApi.instance.removeStateObserver();
subscription.pause();
},
);
@override
Future<Peripheral> connect(
UUID uuid, {
Function(Exception)? onConnectionLost,
}) {
return CentralManagerApi.instance
.connect(uuid.buffer)
.then((buffer) => MyPeripheral.fromBuffer(buffer, onConnectionLost));
} }
} }
class MyAdvertisement implements Advertisement { class MyBroadcast implements Broadcast {
@override @override
final UUID uuid; final Peripheral peripheral;
@override @override
final int rssi; final int rssi;
@override @override
@ -300,8 +239,8 @@ class MyAdvertisement implements Advertisement {
@override @override
final int? txPowerLevel; final int? txPowerLevel;
MyAdvertisement({ MyBroadcast({
required this.uuid, required this.peripheral,
required this.rssi, required this.rssi,
required this.connectable, required this.connectable,
required this.data, required this.data,
@ -313,31 +252,29 @@ class MyAdvertisement implements Advertisement {
required this.txPowerLevel, required this.txPowerLevel,
}); });
factory MyAdvertisement.fromBuffer(Uint8List buffer) { factory MyBroadcast.fromBuffer(Uint8List buffer) {
final advertisement = proto.Advertisement.fromBuffer(buffer); final broadcast = proto.Broadcast.fromBuffer(buffer);
final uuid = MyUUID.fromProto(advertisement.uuid); final peripheral = MyPeripheral.fromProto(broadcast.peripheral);
final rssi = advertisement.rssi; final rssi = broadcast.rssi;
final connectable = final connectable =
advertisement.hasConnectable() ? advertisement.connectable : null; broadcast.hasConnectable() ? broadcast.connectable : null;
final data = Uint8List.fromList(advertisement.data); final data = Uint8List.fromList(broadcast.data);
final localName = final localName = broadcast.hasLocalName() ? broadcast.localName : null;
advertisement.hasLocalName() ? advertisement.localName : null;
final manufacturerSpecificData = final manufacturerSpecificData =
Uint8List.fromList(advertisement.manufacturerSpecificData); Uint8List.fromList(broadcast.manufacturerSpecificData);
final serviceData = { final serviceData = {
for (var serviceData in advertisement.serviceDatas) for (var serviceData in broadcast.serviceDatas)
MyUUID.fromProto(serviceData.uuid): Uint8List.fromList(serviceData.data) MyUUID.fromProto(serviceData.uuid): Uint8List.fromList(serviceData.data)
}; };
final serviceUUIDs = advertisement.serviceUuids final serviceUUIDs =
.map((uuid) => MyUUID.fromProto(uuid)) broadcast.serviceUuids.map((uuid) => MyUUID.fromProto(uuid)).toList();
.toList(); final solicitedServiceUUIDs = broadcast.solicitedServiceUuids
final solicitedServiceUUIDs = advertisement.solicitedServiceUuids
.map((uuid) => MyUUID.fromProto(uuid)) .map((uuid) => MyUUID.fromProto(uuid))
.toList(); .toList();
final txPowerLevel = final txPowerLevel =
advertisement.hasTxPowerLevel() ? advertisement.txPowerLevel : null; broadcast.hasTxPowerLevel() ? broadcast.txPowerLevel : null;
return MyAdvertisement( return MyBroadcast(
uuid: uuid, peripheral: peripheral,
rssi: rssi, rssi: rssi,
connectable: connectable, connectable: connectable,
data: data, data: data,
@ -352,54 +289,57 @@ class MyAdvertisement implements Advertisement {
} }
class MyPeripheral implements Peripheral { class MyPeripheral implements Peripheral {
late StreamSubscription<Tuple2<int, Uint8List>> static PeripheralApi get api => PeripheralApi.instance;
connectionLostStreamSubscription;
@override static final finalizer = Finalizer<String>((id) {
final int maximumWriteLength; api.free(id);
MyPeripheral({
required this.maximumWriteLength,
required int instanceId,
Function(Exception)? onConnectionLost,
}) {
PeripheralApi.instance.allocate(hashCode, instanceId);
connectionLostStreamSubscription = PeripheralApi
.instance.connectionLostStream
.where((event) => event.item1 == hashCode)
.listen((event) {
final error = MyBluetoothLowEnergyException.fromBuffer(event.item2);
onConnectionLost?.call(error);
}); });
final String id;
@override
final UUID uuid;
MyPeripheral({required this.id, required this.uuid}) {
finalizer.attach( finalizer.attach(
this, this,
() { id,
connectionLostStreamSubscription.cancel();
PeripheralApi.instance.free(hashCode);
},
); );
} }
factory MyPeripheral.fromBuffer( factory MyPeripheral.fromProto(proto.Peripheral peripheral) {
Uint8List buffer,
Function(Exception)? onConnectionLost,
) {
final peripheral = proto.Peripheral.fromBuffer(buffer);
return MyPeripheral( return MyPeripheral(
maximumWriteLength: peripheral.maximumWriteLength, id: peripheral.id,
instanceId: peripheral.id.toInt(), uuid: MyUUID.fromProto(peripheral.uuid),
onConnectionLost: onConnectionLost,
); );
} }
@override
Stream<Exception> get connectionLost =>
api.connectionLost.where((event) => event.item1 == id).map(
(event) => PlatformException(
code: bluetoothLowEnergyError,
message: event.item2,
),
);
@override
Future<void> connect() {
return api.connect(id);
}
@override @override
Future<void> disconnect() { Future<void> disconnect() {
return PeripheralApi.instance.disconnect(hashCode); return api.disconnect(id);
}
@override
Future<int> requestMtu() {
return api.requestMtu(id);
} }
@override @override
Future<List<GattService>> discoverServices() { Future<List<GattService>> discoverServices() {
return PeripheralApi.instance.discoverServices(hashCode).then( return api.discoverServices(id).then(
(buffers) => buffers (buffers) => buffers
.map((buffer) => MyGattService.fromBuffer(buffer)) .map((buffer) => MyGattService.fromBuffer(buffer))
.toList(), .toList(),
@ -408,14 +348,20 @@ class MyPeripheral implements Peripheral {
} }
class MyGattService extends GattService { class MyGattService extends GattService {
static GattServiceApi get api => GattServiceApi.instance;
static final finalizer = Finalizer<String>((id) {
api.free(id);
});
final String id;
@override @override
final UUID uuid; final UUID uuid;
MyGattService({required this.uuid, required int instanceId}) { MyGattService({required this.id, required this.uuid}) {
GattServiceApi.instance.allocate(hashCode, instanceId);
finalizer.attach( finalizer.attach(
this, this,
() => GattServiceApi.instance.free(hashCode), id,
); );
} }
@ -423,14 +369,14 @@ class MyGattService extends GattService {
final service = proto.GattService.fromBuffer(buffer); final service = proto.GattService.fromBuffer(buffer);
final uuid = MyUUID.fromProto(service.uuid); final uuid = MyUUID.fromProto(service.uuid);
return MyGattService( return MyGattService(
id: service.id,
uuid: uuid, uuid: uuid,
instanceId: service.id.toInt(),
); );
} }
@override @override
Future<List<GattCharacteristic>> discoverCharacteristics() { Future<List<GattCharacteristic>> discoverCharacteristics() {
return GattServiceApi.instance.discoverCharacteristics(hashCode).then( return api.discoverCharacteristics(id).then(
(buffers) => buffers (buffers) => buffers
.map((buffer) => MyGattCharacteristic.fromBuffer(buffer)) .map((buffer) => MyGattCharacteristic.fromBuffer(buffer))
.toList(), .toList(),
@ -439,6 +385,13 @@ class MyGattService extends GattService {
} }
class MyGattCharacteristic extends GattCharacteristic { class MyGattCharacteristic extends GattCharacteristic {
static GattCharacteristicApi get api => GattCharacteristicApi.instance;
static final finalizer = Finalizer<String>((id) {
api.free(id);
});
final String id;
@override @override
final UUID uuid; final UUID uuid;
@override @override
@ -451,17 +404,16 @@ class MyGattCharacteristic extends GattCharacteristic {
final bool canNotify; final bool canNotify;
MyGattCharacteristic({ MyGattCharacteristic({
required this.id,
required this.uuid, required this.uuid,
required this.canRead, required this.canRead,
required this.canWrite, required this.canWrite,
required this.canWriteWithoutResponse, required this.canWriteWithoutResponse,
required this.canNotify, required this.canNotify,
required int instanceId,
}) { }) {
GattCharacteristicApi.instance.allocate(hashCode, instanceId);
finalizer.attach( finalizer.attach(
this, this,
() => GattCharacteristicApi.instance.free(hashCode), id,
); );
} }
@ -473,35 +425,23 @@ class MyGattCharacteristic extends GattCharacteristic {
final canWriteWithoutResponse = characteristic.canWriteWithoutResponse; final canWriteWithoutResponse = characteristic.canWriteWithoutResponse;
final canNotify = characteristic.canNotify; final canNotify = characteristic.canNotify;
return MyGattCharacteristic( return MyGattCharacteristic(
id: characteristic.id,
uuid: uuid, uuid: uuid,
canRead: canRead, canRead: canRead,
canWrite: canWrite, canWrite: canWrite,
canWriteWithoutResponse: canWriteWithoutResponse, canWriteWithoutResponse: canWriteWithoutResponse,
canNotify: canNotify, canNotify: canNotify,
instanceId: characteristic.id.toInt(),
); );
} }
@override @override
Stream<Uint8List> get valueStream => Stream<Uint8List> get valueChanged => api.valueChanged
GattCharacteristicApi.instance.valueStream .where((event) => event.item1 == id)
.where((event) => event.item1 == hashCode) .map((event) => event.item2);
.map((event) => event.item2)
.asBroadcastStream(
onListen: (subscription) async {
subscription.resume();
await GattCharacteristicApi.instance.setNotify(hashCode, true);
},
onCancel: (subscription) async {
// TODO: the stream can't listen again when use `subscription.cancel()`.
await GattCharacteristicApi.instance.setNotify(hashCode, false);
subscription.pause();
},
);
@override @override
Future<List<GattDescriptor>> discoverDescriptors() { Future<List<GattDescriptor>> discoverDescriptors() {
return GattCharacteristicApi.instance.discoverDescriptors(hashCode).then( return api.discoverDescriptors(id).then(
(buffers) => buffers (buffers) => buffers
.map((buffer) => MyGattDescriptor.fromBuffer(buffer)) .map((buffer) => MyGattDescriptor.fromBuffer(buffer))
.toList(), .toList(),
@ -510,28 +450,35 @@ class MyGattCharacteristic extends GattCharacteristic {
@override @override
Future<Uint8List> read() { Future<Uint8List> read() {
return GattCharacteristicApi.instance.read(hashCode); return api.read(id);
} }
@override @override
Future<void> write(Uint8List value, {bool withoutResponse = false}) { Future<void> write(Uint8List value, {bool withoutResponse = false}) {
return GattCharacteristicApi.instance.write( return api.write(id, value, withoutResponse);
hashCode, }
value,
withoutResponse, @override
); Future<void> setNotify(bool value) {
return api.setNotify(id, value);
} }
} }
class MyGattDescriptor extends GattDescriptor { class MyGattDescriptor extends GattDescriptor {
static GattDescriptorApi get api => GattDescriptorApi.instance;
static final finalizer = Finalizer<String>((id) {
GattDescriptorApi.instance.free(id);
});
final String id;
@override @override
final UUID uuid; final UUID uuid;
MyGattDescriptor({required this.uuid, required int instanceId}) { MyGattDescriptor({required this.id, required this.uuid}) {
GattDescriptorApi.instance.allocate(hashCode, instanceId);
finalizer.attach( finalizer.attach(
this, this,
() => GattDescriptorApi.instance.free(hashCode), id,
); );
} }
@ -539,19 +486,19 @@ class MyGattDescriptor extends GattDescriptor {
final descriptor = proto.GattDescriptor.fromBuffer(buffer); final descriptor = proto.GattDescriptor.fromBuffer(buffer);
final uuid = MyUUID.fromProto(descriptor.uuid); final uuid = MyUUID.fromProto(descriptor.uuid);
return MyGattDescriptor( return MyGattDescriptor(
id: descriptor.id,
uuid: uuid, uuid: uuid,
instanceId: descriptor.id.toInt(),
); );
} }
@override @override
Future<Uint8List> read() { Future<Uint8List> read() {
return GattDescriptorApi.instance.read(hashCode); return api.read(id);
} }
@override @override
Future<void> write(Uint8List value) { Future<void> write(Uint8List value) {
return GattDescriptorApi.instance.write(hashCode, value); return api.write(id, value);
} }
} }
@ -562,15 +509,10 @@ class MyUUID implements UUID {
MyUUID({required this.value}); MyUUID({required this.value});
factory MyUUID.fromProto(proto.UUID uuid) { factory MyUUID.fromProto(proto.UUID uuid) {
final value = uuid.value; final value = uuid.value.toLowerCase();
return MyUUID(value: value); return MyUUID(value: value);
} }
factory MyUUID.fromBuffer(Uint8List buffer) {
final uuid = proto.UUID.fromBuffer(buffer);
return MyUUID.fromProto(uuid);
}
@override @override
String toString() { String toString() {
return 'UUID: $value'; return 'UUID: $value';
@ -585,23 +527,6 @@ class MyUUID implements UUID {
} }
} }
class MyBluetoothLowEnergyException implements BluetoothLowEnergyException {
@override
final String message;
MyBluetoothLowEnergyException({required this.message});
factory MyBluetoothLowEnergyException.fromBuffer(Uint8List buffer) {
final error = proto.BluetoothLowEnergyException.fromBuffer(buffer);
return MyBluetoothLowEnergyException(message: error.message);
}
@override
String toString() {
return 'BluetoothLowEnergyException: $message';
}
}
extension on UUID { extension on UUID {
Uint8List get buffer => proto.UUID(value: value).writeToBuffer(); Uint8List get buffer => proto.UUID(value: value).writeToBuffer();
} }

View File

@ -1,8 +1,13 @@
import 'gatt_service.dart'; import 'gatt_service.dart';
import 'uuid.dart';
abstract class Peripheral { abstract class Peripheral {
int get maximumWriteLength; UUID get uuid;
Stream<Exception> get connectionLost;
Future<void> connect();
Future<void> disconnect(); Future<void> disconnect();
Future<int> requestMtu();
Future<List<GattService>> discoverServices(); Future<List<GattService>> discoverServices();
} }

View File

@ -1 +1 @@
export 'pigeon/api.g.dart'; export 'pigeon/messages.g.dart';

View File

@ -1,4 +1,4 @@
// Autogenerated from Pigeon (v4.0.2), do not edit directly. // Autogenerated from Pigeon (v4.2.0), do not edit directly.
// See also: https://pub.dev/packages/pigeon // See also: https://pub.dev/packages/pigeon
// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import
import 'dart:async'; import 'dart:async';
@ -75,50 +75,6 @@ class CentralManagerHostApi {
} }
} }
Future<void> addStateObserver() async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.CentralManagerHostApi.addStateObserver', codec, binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(null) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error = (replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else {
return;
}
}
Future<void> removeStateObserver() async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.CentralManagerHostApi.removeStateObserver', codec, binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(null) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error = (replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else {
return;
}
}
Future<void> startScan(List<Uint8List?>? arg_uuidBuffers) async { Future<void> startScan(List<Uint8List?>? arg_uuidBuffers) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.CentralManagerHostApi.startScan', codec, binaryMessenger: _binaryMessenger); 'dev.flutter.pigeon.CentralManagerHostApi.startScan', codec, binaryMessenger: _binaryMessenger);
@ -162,33 +118,6 @@ class CentralManagerHostApi {
return; return;
} }
} }
Future<Uint8List> connect(Uint8List arg_uuidBuffer) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.CentralManagerHostApi.connect', codec, binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(<Object?>[arg_uuidBuffer]) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error = (replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else if (replyMap['result'] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (replyMap['result'] as Uint8List?)!;
}
}
} }
class _CentralManagerFlutterApiCodec extends StandardMessageCodec { class _CentralManagerFlutterApiCodec extends StandardMessageCodec {
@ -197,37 +126,37 @@ class _CentralManagerFlutterApiCodec extends StandardMessageCodec {
abstract class CentralManagerFlutterApi { abstract class CentralManagerFlutterApi {
static const MessageCodec<Object?> codec = _CentralManagerFlutterApiCodec(); static const MessageCodec<Object?> codec = _CentralManagerFlutterApiCodec();
void notifyState(int stateNumber); void onStateChanged(int stateNumber);
void notifyAdvertisement(Uint8List advertisementBuffer); void onScanned(Uint8List broadcastBuffer);
static void setup(CentralManagerFlutterApi? api, {BinaryMessenger? binaryMessenger}) { static void setup(CentralManagerFlutterApi? api, {BinaryMessenger? binaryMessenger}) {
{ {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.CentralManagerFlutterApi.notifyState', codec, binaryMessenger: binaryMessenger); 'dev.flutter.pigeon.CentralManagerFlutterApi.onStateChanged', codec, binaryMessenger: binaryMessenger);
if (api == null) { if (api == null) {
channel.setMessageHandler(null); channel.setMessageHandler(null);
} else { } else {
channel.setMessageHandler((Object? message) async { channel.setMessageHandler((Object? message) async {
assert(message != null, 'Argument for dev.flutter.pigeon.CentralManagerFlutterApi.notifyState was null.'); assert(message != null, 'Argument for dev.flutter.pigeon.CentralManagerFlutterApi.onStateChanged was null.');
final List<Object?> args = (message as List<Object?>?)!; final List<Object?> args = (message as List<Object?>?)!;
final int? arg_stateNumber = (args[0] as int?); final int? arg_stateNumber = (args[0] as int?);
assert(arg_stateNumber != null, 'Argument for dev.flutter.pigeon.CentralManagerFlutterApi.notifyState was null, expected non-null int.'); assert(arg_stateNumber != null, 'Argument for dev.flutter.pigeon.CentralManagerFlutterApi.onStateChanged was null, expected non-null int.');
api.notifyState(arg_stateNumber!); api.onStateChanged(arg_stateNumber!);
return; return;
}); });
} }
} }
{ {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.CentralManagerFlutterApi.notifyAdvertisement', codec, binaryMessenger: binaryMessenger); 'dev.flutter.pigeon.CentralManagerFlutterApi.onScanned', codec, binaryMessenger: binaryMessenger);
if (api == null) { if (api == null) {
channel.setMessageHandler(null); channel.setMessageHandler(null);
} else { } else {
channel.setMessageHandler((Object? message) async { channel.setMessageHandler((Object? message) async {
assert(message != null, 'Argument for dev.flutter.pigeon.CentralManagerFlutterApi.notifyAdvertisement was null.'); assert(message != null, 'Argument for dev.flutter.pigeon.CentralManagerFlutterApi.onScanned was null.');
final List<Object?> args = (message as List<Object?>?)!; final List<Object?> args = (message as List<Object?>?)!;
final Uint8List? arg_advertisementBuffer = (args[0] as Uint8List?); final Uint8List? arg_broadcastBuffer = (args[0] as Uint8List?);
assert(arg_advertisementBuffer != null, 'Argument for dev.flutter.pigeon.CentralManagerFlutterApi.notifyAdvertisement was null, expected non-null Uint8List.'); assert(arg_broadcastBuffer != null, 'Argument for dev.flutter.pigeon.CentralManagerFlutterApi.onScanned was null, expected non-null Uint8List.');
api.notifyAdvertisement(arg_advertisementBuffer!); api.onScanned(arg_broadcastBuffer!);
return; return;
}); });
} }
@ -249,29 +178,7 @@ class PeripheralHostApi {
static const MessageCodec<Object?> codec = _PeripheralHostApiCodec(); static const MessageCodec<Object?> codec = _PeripheralHostApiCodec();
Future<void> allocate(int arg_id, int arg_instanceId) async { Future<void> free(String arg_id) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PeripheralHostApi.allocate', codec, binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(<Object?>[arg_id, arg_instanceId]) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error = (replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else {
return;
}
}
Future<void> free(int arg_id) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PeripheralHostApi.free', codec, binaryMessenger: _binaryMessenger); 'dev.flutter.pigeon.PeripheralHostApi.free', codec, binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap = final Map<Object?, Object?>? replyMap =
@ -293,7 +200,29 @@ class PeripheralHostApi {
} }
} }
Future<void> disconnect(int arg_id) async { Future<void> connect(String arg_id) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PeripheralHostApi.connect', codec, binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(<Object?>[arg_id]) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error = (replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else {
return;
}
}
Future<void> disconnect(String arg_id) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PeripheralHostApi.disconnect', codec, binaryMessenger: _binaryMessenger); 'dev.flutter.pigeon.PeripheralHostApi.disconnect', codec, binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap = final Map<Object?, Object?>? replyMap =
@ -315,7 +244,34 @@ class PeripheralHostApi {
} }
} }
Future<List<Uint8List?>> discoverServices(int arg_id) async { Future<int> requestMtu(String arg_id) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PeripheralHostApi.requestMtu', codec, binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(<Object?>[arg_id]) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error = (replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else if (replyMap['result'] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (replyMap['result'] as int?)!;
}
}
Future<List<Uint8List?>> discoverServices(String arg_id) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PeripheralHostApi.discoverServices', codec, binaryMessenger: _binaryMessenger); 'dev.flutter.pigeon.PeripheralHostApi.discoverServices', codec, binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap = final Map<Object?, Object?>? replyMap =
@ -349,22 +305,22 @@ class _PeripheralFlutterApiCodec extends StandardMessageCodec {
abstract class PeripheralFlutterApi { abstract class PeripheralFlutterApi {
static const MessageCodec<Object?> codec = _PeripheralFlutterApiCodec(); static const MessageCodec<Object?> codec = _PeripheralFlutterApiCodec();
void notifyConnectionLost(int id, Uint8List errorBuffer); void onConnectionLost(String id, String errorMessage);
static void setup(PeripheralFlutterApi? api, {BinaryMessenger? binaryMessenger}) { static void setup(PeripheralFlutterApi? api, {BinaryMessenger? binaryMessenger}) {
{ {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PeripheralFlutterApi.notifyConnectionLost', codec, binaryMessenger: binaryMessenger); 'dev.flutter.pigeon.PeripheralFlutterApi.onConnectionLost', codec, binaryMessenger: binaryMessenger);
if (api == null) { if (api == null) {
channel.setMessageHandler(null); channel.setMessageHandler(null);
} else { } else {
channel.setMessageHandler((Object? message) async { channel.setMessageHandler((Object? message) async {
assert(message != null, 'Argument for dev.flutter.pigeon.PeripheralFlutterApi.notifyConnectionLost was null.'); assert(message != null, 'Argument for dev.flutter.pigeon.PeripheralFlutterApi.onConnectionLost was null.');
final List<Object?> args = (message as List<Object?>?)!; final List<Object?> args = (message as List<Object?>?)!;
final int? arg_id = (args[0] as int?); final String? arg_id = (args[0] as String?);
assert(arg_id != null, 'Argument for dev.flutter.pigeon.PeripheralFlutterApi.notifyConnectionLost was null, expected non-null int.'); assert(arg_id != null, 'Argument for dev.flutter.pigeon.PeripheralFlutterApi.onConnectionLost was null, expected non-null String.');
final Uint8List? arg_errorBuffer = (args[1] as Uint8List?); final String? arg_errorMessage = (args[1] as String?);
assert(arg_errorBuffer != null, 'Argument for dev.flutter.pigeon.PeripheralFlutterApi.notifyConnectionLost was null, expected non-null Uint8List.'); assert(arg_errorMessage != null, 'Argument for dev.flutter.pigeon.PeripheralFlutterApi.onConnectionLost was null, expected non-null String.');
api.notifyConnectionLost(arg_id!, arg_errorBuffer!); api.onConnectionLost(arg_id!, arg_errorMessage!);
return; return;
}); });
} }
@ -386,29 +342,7 @@ class GattServiceHostApi {
static const MessageCodec<Object?> codec = _GattServiceHostApiCodec(); static const MessageCodec<Object?> codec = _GattServiceHostApiCodec();
Future<void> allocate(int arg_id, int arg_instanceId) async { Future<void> free(String arg_id) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.GattServiceHostApi.allocate', codec, binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(<Object?>[arg_id, arg_instanceId]) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error = (replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else {
return;
}
}
Future<void> free(int arg_id) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.GattServiceHostApi.free', codec, binaryMessenger: _binaryMessenger); 'dev.flutter.pigeon.GattServiceHostApi.free', codec, binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap = final Map<Object?, Object?>? replyMap =
@ -430,7 +364,7 @@ class GattServiceHostApi {
} }
} }
Future<List<Uint8List?>> discoverCharacteristics(int arg_id) async { Future<List<Uint8List?>> discoverCharacteristics(String arg_id) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.GattServiceHostApi.discoverCharacteristics', codec, binaryMessenger: _binaryMessenger); 'dev.flutter.pigeon.GattServiceHostApi.discoverCharacteristics', codec, binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap = final Map<Object?, Object?>? replyMap =
@ -472,29 +406,7 @@ class GattCharacteristicHostApi {
static const MessageCodec<Object?> codec = _GattCharacteristicHostApiCodec(); static const MessageCodec<Object?> codec = _GattCharacteristicHostApiCodec();
Future<void> allocate(int arg_id, int arg_instanceId) async { Future<void> free(String arg_id) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.GattCharacteristicHostApi.allocate', codec, binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(<Object?>[arg_id, arg_instanceId]) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error = (replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else {
return;
}
}
Future<void> free(int arg_id) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.GattCharacteristicHostApi.free', codec, binaryMessenger: _binaryMessenger); 'dev.flutter.pigeon.GattCharacteristicHostApi.free', codec, binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap = final Map<Object?, Object?>? replyMap =
@ -516,7 +428,7 @@ class GattCharacteristicHostApi {
} }
} }
Future<List<Uint8List?>> discoverDescriptors(int arg_id) async { Future<List<Uint8List?>> discoverDescriptors(String arg_id) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.GattCharacteristicHostApi.discoverDescriptors', codec, binaryMessenger: _binaryMessenger); 'dev.flutter.pigeon.GattCharacteristicHostApi.discoverDescriptors', codec, binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap = final Map<Object?, Object?>? replyMap =
@ -543,7 +455,7 @@ class GattCharacteristicHostApi {
} }
} }
Future<Uint8List> read(int arg_id) async { Future<Uint8List> read(String arg_id) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.GattCharacteristicHostApi.read', codec, binaryMessenger: _binaryMessenger); 'dev.flutter.pigeon.GattCharacteristicHostApi.read', codec, binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap = final Map<Object?, Object?>? replyMap =
@ -570,7 +482,7 @@ class GattCharacteristicHostApi {
} }
} }
Future<void> write(int arg_id, Uint8List arg_value, bool arg_withoutResponse) async { Future<void> write(String arg_id, Uint8List arg_value, bool arg_withoutResponse) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.GattCharacteristicHostApi.write', codec, binaryMessenger: _binaryMessenger); 'dev.flutter.pigeon.GattCharacteristicHostApi.write', codec, binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap = final Map<Object?, Object?>? replyMap =
@ -592,7 +504,7 @@ class GattCharacteristicHostApi {
} }
} }
Future<void> setNotify(int arg_id, bool arg_value) async { Future<void> setNotify(String arg_id, bool arg_value) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.GattCharacteristicHostApi.setNotify', codec, binaryMessenger: _binaryMessenger); 'dev.flutter.pigeon.GattCharacteristicHostApi.setNotify', codec, binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap = final Map<Object?, Object?>? replyMap =
@ -621,22 +533,22 @@ class _GattCharacteristicFlutterApiCodec extends StandardMessageCodec {
abstract class GattCharacteristicFlutterApi { abstract class GattCharacteristicFlutterApi {
static const MessageCodec<Object?> codec = _GattCharacteristicFlutterApiCodec(); static const MessageCodec<Object?> codec = _GattCharacteristicFlutterApiCodec();
void notifyValue(int id, Uint8List value); void onValueChanged(String id, Uint8List value);
static void setup(GattCharacteristicFlutterApi? api, {BinaryMessenger? binaryMessenger}) { static void setup(GattCharacteristicFlutterApi? api, {BinaryMessenger? binaryMessenger}) {
{ {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.GattCharacteristicFlutterApi.notifyValue', codec, binaryMessenger: binaryMessenger); 'dev.flutter.pigeon.GattCharacteristicFlutterApi.onValueChanged', codec, binaryMessenger: binaryMessenger);
if (api == null) { if (api == null) {
channel.setMessageHandler(null); channel.setMessageHandler(null);
} else { } else {
channel.setMessageHandler((Object? message) async { channel.setMessageHandler((Object? message) async {
assert(message != null, 'Argument for dev.flutter.pigeon.GattCharacteristicFlutterApi.notifyValue was null.'); assert(message != null, 'Argument for dev.flutter.pigeon.GattCharacteristicFlutterApi.onValueChanged was null.');
final List<Object?> args = (message as List<Object?>?)!; final List<Object?> args = (message as List<Object?>?)!;
final int? arg_id = (args[0] as int?); final String? arg_id = (args[0] as String?);
assert(arg_id != null, 'Argument for dev.flutter.pigeon.GattCharacteristicFlutterApi.notifyValue was null, expected non-null int.'); assert(arg_id != null, 'Argument for dev.flutter.pigeon.GattCharacteristicFlutterApi.onValueChanged was null, expected non-null String.');
final Uint8List? arg_value = (args[1] as Uint8List?); final Uint8List? arg_value = (args[1] as Uint8List?);
assert(arg_value != null, 'Argument for dev.flutter.pigeon.GattCharacteristicFlutterApi.notifyValue was null, expected non-null Uint8List.'); assert(arg_value != null, 'Argument for dev.flutter.pigeon.GattCharacteristicFlutterApi.onValueChanged was null, expected non-null Uint8List.');
api.notifyValue(arg_id!, arg_value!); api.onValueChanged(arg_id!, arg_value!);
return; return;
}); });
} }
@ -658,29 +570,7 @@ class GattDescriptorHostApi {
static const MessageCodec<Object?> codec = _GattDescriptorHostApiCodec(); static const MessageCodec<Object?> codec = _GattDescriptorHostApiCodec();
Future<void> allocate(int arg_id, int arg_instanceId) async { Future<void> free(String arg_id) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.GattDescriptorHostApi.allocate', codec, binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(<Object?>[arg_id, arg_instanceId]) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error = (replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else {
return;
}
}
Future<void> free(int arg_id) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.GattDescriptorHostApi.free', codec, binaryMessenger: _binaryMessenger); 'dev.flutter.pigeon.GattDescriptorHostApi.free', codec, binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap = final Map<Object?, Object?>? replyMap =
@ -702,7 +592,7 @@ class GattDescriptorHostApi {
} }
} }
Future<Uint8List> read(int arg_id) async { Future<Uint8List> read(String arg_id) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.GattDescriptorHostApi.read', codec, binaryMessenger: _binaryMessenger); 'dev.flutter.pigeon.GattDescriptorHostApi.read', codec, binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap = final Map<Object?, Object?>? replyMap =
@ -729,7 +619,7 @@ class GattDescriptorHostApi {
} }
} }
Future<void> write(int arg_id, Uint8List arg_value) async { Future<void> write(String arg_id, Uint8List arg_value) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.GattDescriptorHostApi.write', codec, binaryMessenger: _binaryMessenger); 'dev.flutter.pigeon.GattDescriptorHostApi.write', codec, binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap = final Map<Object?, Object?>? replyMap =

View File

@ -1 +1,3 @@
export 'proto/messages.pb.dart'; export 'proto/messages.pb.dart';
export 'proto/messages.pbenum.dart';
export 'proto/messages.pbjson.dart';

View File

@ -7,14 +7,13 @@
import 'dart:core' as $core; import 'dart:core' as $core;
import 'package:fixnum/fixnum.dart' as $fixnum;
import 'package:protobuf/protobuf.dart' as $pb; import 'package:protobuf/protobuf.dart' as $pb;
export 'messages.pbenum.dart'; export 'messages.pbenum.dart';
class Advertisement extends $pb.GeneratedMessage { class Broadcast extends $pb.GeneratedMessage {
static final $pb.BuilderInfo _i = $pb.BuilderInfo(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'Advertisement', package: const $pb.PackageName(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'proto'), createEmptyInstance: create) static final $pb.BuilderInfo _i = $pb.BuilderInfo(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'Broadcast', package: const $pb.PackageName(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'proto'), createEmptyInstance: create)
..aOM<UUID>(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'uuid', subBuilder: UUID.create) ..aOM<Peripheral>(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'peripheral', subBuilder: Peripheral.create)
..a<$core.int>(2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'rssi', $pb.PbFieldType.O3) ..a<$core.int>(2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'rssi', $pb.PbFieldType.O3)
..aOB(3, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'connectable') ..aOB(3, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'connectable')
..a<$core.List<$core.int>>(4, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'data', $pb.PbFieldType.OY) ..a<$core.List<$core.int>>(4, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'data', $pb.PbFieldType.OY)
@ -27,9 +26,9 @@ class Advertisement extends $pb.GeneratedMessage {
..hasRequiredFields = false ..hasRequiredFields = false
; ;
Advertisement._() : super(); Broadcast._() : super();
factory Advertisement({ factory Broadcast({
UUID? uuid, Peripheral? peripheral,
$core.int? rssi, $core.int? rssi,
$core.bool? connectable, $core.bool? connectable,
$core.List<$core.int>? data, $core.List<$core.int>? data,
@ -41,8 +40,8 @@ class Advertisement extends $pb.GeneratedMessage {
$core.int? txPowerLevel, $core.int? txPowerLevel,
}) { }) {
final _result = create(); final _result = create();
if (uuid != null) { if (peripheral != null) {
_result.uuid = uuid; _result.peripheral = peripheral;
} }
if (rssi != null) { if (rssi != null) {
_result.rssi = rssi; _result.rssi = rssi;
@ -73,37 +72,37 @@ class Advertisement extends $pb.GeneratedMessage {
} }
return _result; return _result;
} }
factory Advertisement.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); factory Broadcast.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r);
factory Advertisement.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); factory Broadcast.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r);
@$core.Deprecated( @$core.Deprecated(
'Using this can add significant overhead to your binary. ' 'Using this can add significant overhead to your binary. '
'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. '
'Will be removed in next major version') 'Will be removed in next major version')
Advertisement clone() => Advertisement()..mergeFromMessage(this); Broadcast clone() => Broadcast()..mergeFromMessage(this);
@$core.Deprecated( @$core.Deprecated(
'Using this can add significant overhead to your binary. ' 'Using this can add significant overhead to your binary. '
'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' 'Use [GeneratedMessageGenericExtensions.rebuild] instead. '
'Will be removed in next major version') 'Will be removed in next major version')
Advertisement copyWith(void Function(Advertisement) updates) => super.copyWith((message) => updates(message as Advertisement)) as Advertisement; // ignore: deprecated_member_use Broadcast copyWith(void Function(Broadcast) updates) => super.copyWith((message) => updates(message as Broadcast)) as Broadcast; // ignore: deprecated_member_use
$pb.BuilderInfo get info_ => _i; $pb.BuilderInfo get info_ => _i;
@$core.pragma('dart2js:noInline') @$core.pragma('dart2js:noInline')
static Advertisement create() => Advertisement._(); static Broadcast create() => Broadcast._();
Advertisement createEmptyInstance() => create(); Broadcast createEmptyInstance() => create();
static $pb.PbList<Advertisement> createRepeated() => $pb.PbList<Advertisement>(); static $pb.PbList<Broadcast> createRepeated() => $pb.PbList<Broadcast>();
@$core.pragma('dart2js:noInline') @$core.pragma('dart2js:noInline')
static Advertisement getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<Advertisement>(create); static Broadcast getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<Broadcast>(create);
static Advertisement? _defaultInstance; static Broadcast? _defaultInstance;
@$pb.TagNumber(1) @$pb.TagNumber(1)
UUID get uuid => $_getN(0); Peripheral get peripheral => $_getN(0);
@$pb.TagNumber(1) @$pb.TagNumber(1)
set uuid(UUID v) { setField(1, v); } set peripheral(Peripheral v) { setField(1, v); }
@$pb.TagNumber(1) @$pb.TagNumber(1)
$core.bool hasUuid() => $_has(0); $core.bool hasPeripheral() => $_has(0);
@$pb.TagNumber(1) @$pb.TagNumber(1)
void clearUuid() => clearField(1); void clearPeripheral() => clearField(1);
@$pb.TagNumber(1) @$pb.TagNumber(1)
UUID ensureUuid() => $_ensure(0); Peripheral ensurePeripheral() => $_ensure(0);
@$pb.TagNumber(2) @$pb.TagNumber(2)
$core.int get rssi => $_getIZ(1); $core.int get rssi => $_getIZ(1);
@ -171,22 +170,22 @@ class Advertisement extends $pb.GeneratedMessage {
class Peripheral extends $pb.GeneratedMessage { class Peripheral extends $pb.GeneratedMessage {
static final $pb.BuilderInfo _i = $pb.BuilderInfo(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'Peripheral', package: const $pb.PackageName(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'proto'), createEmptyInstance: create) static final $pb.BuilderInfo _i = $pb.BuilderInfo(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'Peripheral', package: const $pb.PackageName(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'proto'), createEmptyInstance: create)
..aInt64(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'id') ..aOS(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'id')
..a<$core.int>(2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'maximumWriteLength', $pb.PbFieldType.O3) ..aOM<UUID>(2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'uuid', subBuilder: UUID.create)
..hasRequiredFields = false ..hasRequiredFields = false
; ;
Peripheral._() : super(); Peripheral._() : super();
factory Peripheral({ factory Peripheral({
$fixnum.Int64? id, $core.String? id,
$core.int? maximumWriteLength, UUID? uuid,
}) { }) {
final _result = create(); final _result = create();
if (id != null) { if (id != null) {
_result.id = id; _result.id = id;
} }
if (maximumWriteLength != null) { if (uuid != null) {
_result.maximumWriteLength = maximumWriteLength; _result.uuid = uuid;
} }
return _result; return _result;
} }
@ -212,34 +211,36 @@ class Peripheral extends $pb.GeneratedMessage {
static Peripheral? _defaultInstance; static Peripheral? _defaultInstance;
@$pb.TagNumber(1) @$pb.TagNumber(1)
$fixnum.Int64 get id => $_getI64(0); $core.String get id => $_getSZ(0);
@$pb.TagNumber(1) @$pb.TagNumber(1)
set id($fixnum.Int64 v) { $_setInt64(0, v); } set id($core.String v) { $_setString(0, v); }
@$pb.TagNumber(1) @$pb.TagNumber(1)
$core.bool hasId() => $_has(0); $core.bool hasId() => $_has(0);
@$pb.TagNumber(1) @$pb.TagNumber(1)
void clearId() => clearField(1); void clearId() => clearField(1);
@$pb.TagNumber(2) @$pb.TagNumber(2)
$core.int get maximumWriteLength => $_getIZ(1); UUID get uuid => $_getN(1);
@$pb.TagNumber(2) @$pb.TagNumber(2)
set maximumWriteLength($core.int v) { $_setSignedInt32(1, v); } set uuid(UUID v) { setField(2, v); }
@$pb.TagNumber(2) @$pb.TagNumber(2)
$core.bool hasMaximumWriteLength() => $_has(1); $core.bool hasUuid() => $_has(1);
@$pb.TagNumber(2) @$pb.TagNumber(2)
void clearMaximumWriteLength() => clearField(2); void clearUuid() => clearField(2);
@$pb.TagNumber(2)
UUID ensureUuid() => $_ensure(1);
} }
class GattService extends $pb.GeneratedMessage { class GattService extends $pb.GeneratedMessage {
static final $pb.BuilderInfo _i = $pb.BuilderInfo(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'GattService', package: const $pb.PackageName(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'proto'), createEmptyInstance: create) static final $pb.BuilderInfo _i = $pb.BuilderInfo(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'GattService', package: const $pb.PackageName(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'proto'), createEmptyInstance: create)
..aInt64(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'id') ..aOS(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'id')
..aOM<UUID>(2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'uuid', subBuilder: UUID.create) ..aOM<UUID>(2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'uuid', subBuilder: UUID.create)
..hasRequiredFields = false ..hasRequiredFields = false
; ;
GattService._() : super(); GattService._() : super();
factory GattService({ factory GattService({
$fixnum.Int64? id, $core.String? id,
UUID? uuid, UUID? uuid,
}) { }) {
final _result = create(); final _result = create();
@ -273,9 +274,9 @@ class GattService extends $pb.GeneratedMessage {
static GattService? _defaultInstance; static GattService? _defaultInstance;
@$pb.TagNumber(1) @$pb.TagNumber(1)
$fixnum.Int64 get id => $_getI64(0); $core.String get id => $_getSZ(0);
@$pb.TagNumber(1) @$pb.TagNumber(1)
set id($fixnum.Int64 v) { $_setInt64(0, v); } set id($core.String v) { $_setString(0, v); }
@$pb.TagNumber(1) @$pb.TagNumber(1)
$core.bool hasId() => $_has(0); $core.bool hasId() => $_has(0);
@$pb.TagNumber(1) @$pb.TagNumber(1)
@ -295,7 +296,7 @@ class GattService extends $pb.GeneratedMessage {
class GattCharacteristic extends $pb.GeneratedMessage { class GattCharacteristic extends $pb.GeneratedMessage {
static final $pb.BuilderInfo _i = $pb.BuilderInfo(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'GattCharacteristic', package: const $pb.PackageName(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'proto'), createEmptyInstance: create) static final $pb.BuilderInfo _i = $pb.BuilderInfo(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'GattCharacteristic', package: const $pb.PackageName(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'proto'), createEmptyInstance: create)
..aInt64(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'id') ..aOS(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'id')
..aOM<UUID>(2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'uuid', subBuilder: UUID.create) ..aOM<UUID>(2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'uuid', subBuilder: UUID.create)
..aOB(3, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'canRead') ..aOB(3, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'canRead')
..aOB(4, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'canWrite') ..aOB(4, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'canWrite')
@ -306,7 +307,7 @@ class GattCharacteristic extends $pb.GeneratedMessage {
GattCharacteristic._() : super(); GattCharacteristic._() : super();
factory GattCharacteristic({ factory GattCharacteristic({
$fixnum.Int64? id, $core.String? id,
UUID? uuid, UUID? uuid,
$core.bool? canRead, $core.bool? canRead,
$core.bool? canWrite, $core.bool? canWrite,
@ -356,9 +357,9 @@ class GattCharacteristic extends $pb.GeneratedMessage {
static GattCharacteristic? _defaultInstance; static GattCharacteristic? _defaultInstance;
@$pb.TagNumber(1) @$pb.TagNumber(1)
$fixnum.Int64 get id => $_getI64(0); $core.String get id => $_getSZ(0);
@$pb.TagNumber(1) @$pb.TagNumber(1)
set id($fixnum.Int64 v) { $_setInt64(0, v); } set id($core.String v) { $_setString(0, v); }
@$pb.TagNumber(1) @$pb.TagNumber(1)
$core.bool hasId() => $_has(0); $core.bool hasId() => $_has(0);
@$pb.TagNumber(1) @$pb.TagNumber(1)
@ -414,14 +415,14 @@ class GattCharacteristic extends $pb.GeneratedMessage {
class GattDescriptor extends $pb.GeneratedMessage { class GattDescriptor extends $pb.GeneratedMessage {
static final $pb.BuilderInfo _i = $pb.BuilderInfo(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'GattDescriptor', package: const $pb.PackageName(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'proto'), createEmptyInstance: create) static final $pb.BuilderInfo _i = $pb.BuilderInfo(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'GattDescriptor', package: const $pb.PackageName(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'proto'), createEmptyInstance: create)
..aInt64(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'id') ..aOS(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'id')
..aOM<UUID>(2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'uuid', subBuilder: UUID.create) ..aOM<UUID>(2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'uuid', subBuilder: UUID.create)
..hasRequiredFields = false ..hasRequiredFields = false
; ;
GattDescriptor._() : super(); GattDescriptor._() : super();
factory GattDescriptor({ factory GattDescriptor({
$fixnum.Int64? id, $core.String? id,
UUID? uuid, UUID? uuid,
}) { }) {
final _result = create(); final _result = create();
@ -455,9 +456,9 @@ class GattDescriptor extends $pb.GeneratedMessage {
static GattDescriptor? _defaultInstance; static GattDescriptor? _defaultInstance;
@$pb.TagNumber(1) @$pb.TagNumber(1)
$fixnum.Int64 get id => $_getI64(0); $core.String get id => $_getSZ(0);
@$pb.TagNumber(1) @$pb.TagNumber(1)
set id($fixnum.Int64 v) { $_setInt64(0, v); } set id($core.String v) { $_setString(0, v); }
@$pb.TagNumber(1) @$pb.TagNumber(1)
$core.bool hasId() => $_has(0); $core.bool hasId() => $_has(0);
@$pb.TagNumber(1) @$pb.TagNumber(1)
@ -585,50 +586,3 @@ class ServiceData extends $pb.GeneratedMessage {
void clearData() => clearField(2); void clearData() => clearField(2);
} }
class BluetoothLowEnergyException extends $pb.GeneratedMessage {
static final $pb.BuilderInfo _i = $pb.BuilderInfo(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'BluetoothLowEnergyException', package: const $pb.PackageName(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'proto'), createEmptyInstance: create)
..aOS(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'message')
..hasRequiredFields = false
;
BluetoothLowEnergyException._() : super();
factory BluetoothLowEnergyException({
$core.String? message,
}) {
final _result = create();
if (message != null) {
_result.message = message;
}
return _result;
}
factory BluetoothLowEnergyException.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r);
factory BluetoothLowEnergyException.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r);
@$core.Deprecated(
'Using this can add significant overhead to your binary. '
'Use [GeneratedMessageGenericExtensions.deepCopy] instead. '
'Will be removed in next major version')
BluetoothLowEnergyException clone() => BluetoothLowEnergyException()..mergeFromMessage(this);
@$core.Deprecated(
'Using this can add significant overhead to your binary. '
'Use [GeneratedMessageGenericExtensions.rebuild] instead. '
'Will be removed in next major version')
BluetoothLowEnergyException copyWith(void Function(BluetoothLowEnergyException) updates) => super.copyWith((message) => updates(message as BluetoothLowEnergyException)) as BluetoothLowEnergyException; // ignore: deprecated_member_use
$pb.BuilderInfo get info_ => _i;
@$core.pragma('dart2js:noInline')
static BluetoothLowEnergyException create() => BluetoothLowEnergyException._();
BluetoothLowEnergyException createEmptyInstance() => create();
static $pb.PbList<BluetoothLowEnergyException> createRepeated() => $pb.PbList<BluetoothLowEnergyException>();
@$core.pragma('dart2js:noInline')
static BluetoothLowEnergyException getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<BluetoothLowEnergyException>(create);
static BluetoothLowEnergyException? _defaultInstance;
@$pb.TagNumber(1)
$core.String get message => $_getSZ(0);
@$pb.TagNumber(1)
set message($core.String v) { $_setString(0, v); }
@$pb.TagNumber(1)
$core.bool hasMessage() => $_has(0);
@$pb.TagNumber(1)
void clearMessage() => clearField(1);
}

View File

@ -20,11 +20,11 @@ const BluetoothState$json = const {
/// Descriptor for `BluetoothState`. Decode as a `google.protobuf.EnumDescriptorProto`. /// Descriptor for `BluetoothState`. Decode as a `google.protobuf.EnumDescriptorProto`.
final $typed_data.Uint8List bluetoothStateDescriptor = $convert.base64Decode('Cg5CbHVldG9vdGhTdGF0ZRIfChtCTFVFVE9PVEhfU1RBVEVfVU5TVVBQT1JURUQQABIfChtCTFVFVE9PVEhfU1RBVEVfUE9XRVJFRF9PRkYQARIeChpCTFVFVE9PVEhfU1RBVEVfUE9XRVJFRF9PThAC'); final $typed_data.Uint8List bluetoothStateDescriptor = $convert.base64Decode('Cg5CbHVldG9vdGhTdGF0ZRIfChtCTFVFVE9PVEhfU1RBVEVfVU5TVVBQT1JURUQQABIfChtCTFVFVE9PVEhfU1RBVEVfUE9XRVJFRF9PRkYQARIeChpCTFVFVE9PVEhfU1RBVEVfUE9XRVJFRF9PThAC');
@$core.Deprecated('Use advertisementDescriptor instead') @$core.Deprecated('Use broadcastDescriptor instead')
const Advertisement$json = const { const Broadcast$json = const {
'1': 'Advertisement', '1': 'Broadcast',
'2': const [ '2': const [
const {'1': 'uuid', '3': 1, '4': 1, '5': 11, '6': '.proto.UUID', '10': 'uuid'}, const {'1': 'peripheral', '3': 1, '4': 1, '5': 11, '6': '.proto.Peripheral', '10': 'peripheral'},
const {'1': 'rssi', '3': 2, '4': 1, '5': 5, '10': 'rssi'}, const {'1': 'rssi', '3': 2, '4': 1, '5': 5, '10': 'rssi'},
const {'1': 'connectable', '3': 3, '4': 1, '5': 8, '9': 0, '10': 'connectable', '17': true}, const {'1': 'connectable', '3': 3, '4': 1, '5': 8, '9': 0, '10': 'connectable', '17': true},
const {'1': 'data', '3': 4, '4': 1, '5': 12, '10': 'data'}, const {'1': 'data', '3': 4, '4': 1, '5': 12, '10': 'data'},
@ -42,35 +42,35 @@ const Advertisement$json = const {
], ],
}; };
/// Descriptor for `Advertisement`. Decode as a `google.protobuf.DescriptorProto`. /// Descriptor for `Broadcast`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List advertisementDescriptor = $convert.base64Decode('Cg1BZHZlcnRpc2VtZW50Eh8KBHV1aWQYASABKAsyCy5wcm90by5VVUlEUgR1dWlkEhIKBHJzc2kYAiABKAVSBHJzc2kSJQoLY29ubmVjdGFibGUYAyABKAhIAFILY29ubmVjdGFibGWIAQESEgoEZGF0YRgEIAEoDFIEZGF0YRIiCgpsb2NhbF9uYW1lGAUgASgJSAFSCWxvY2FsTmFtZYgBARI8ChptYW51ZmFjdHVyZXJfc3BlY2lmaWNfZGF0YRgGIAEoDFIYbWFudWZhY3R1cmVyU3BlY2lmaWNEYXRhEjcKDXNlcnZpY2VfZGF0YXMYByADKAsyEi5wcm90by5TZXJ2aWNlRGF0YVIMc2VydmljZURhdGFzEjAKDXNlcnZpY2VfdXVpZHMYCCADKAsyCy5wcm90by5VVUlEUgxzZXJ2aWNlVXVpZHMSQwoXc29saWNpdGVkX3NlcnZpY2VfdXVpZHMYCSADKAsyCy5wcm90by5VVUlEUhVzb2xpY2l0ZWRTZXJ2aWNlVXVpZHMSKQoOdHhfcG93ZXJfbGV2ZWwYCiABKAVIAlIMdHhQb3dlckxldmVsiAEBQg4KDF9jb25uZWN0YWJsZUINCgtfbG9jYWxfbmFtZUIRCg9fdHhfcG93ZXJfbGV2ZWw='); final $typed_data.Uint8List broadcastDescriptor = $convert.base64Decode('CglCcm9hZGNhc3QSMQoKcGVyaXBoZXJhbBgBIAEoCzIRLnByb3RvLlBlcmlwaGVyYWxSCnBlcmlwaGVyYWwSEgoEcnNzaRgCIAEoBVIEcnNzaRIlCgtjb25uZWN0YWJsZRgDIAEoCEgAUgtjb25uZWN0YWJsZYgBARISCgRkYXRhGAQgASgMUgRkYXRhEiIKCmxvY2FsX25hbWUYBSABKAlIAVIJbG9jYWxOYW1liAEBEjwKGm1hbnVmYWN0dXJlcl9zcGVjaWZpY19kYXRhGAYgASgMUhhtYW51ZmFjdHVyZXJTcGVjaWZpY0RhdGESNwoNc2VydmljZV9kYXRhcxgHIAMoCzISLnByb3RvLlNlcnZpY2VEYXRhUgxzZXJ2aWNlRGF0YXMSMAoNc2VydmljZV91dWlkcxgIIAMoCzILLnByb3RvLlVVSURSDHNlcnZpY2VVdWlkcxJDChdzb2xpY2l0ZWRfc2VydmljZV91dWlkcxgJIAMoCzILLnByb3RvLlVVSURSFXNvbGljaXRlZFNlcnZpY2VVdWlkcxIpCg50eF9wb3dlcl9sZXZlbBgKIAEoBUgCUgx0eFBvd2VyTGV2ZWyIAQFCDgoMX2Nvbm5lY3RhYmxlQg0KC19sb2NhbF9uYW1lQhEKD190eF9wb3dlcl9sZXZlbA==');
@$core.Deprecated('Use peripheralDescriptor instead') @$core.Deprecated('Use peripheralDescriptor instead')
const Peripheral$json = const { const Peripheral$json = const {
'1': 'Peripheral', '1': 'Peripheral',
'2': const [ '2': const [
const {'1': 'id', '3': 1, '4': 1, '5': 3, '10': 'id'}, const {'1': 'id', '3': 1, '4': 1, '5': 9, '10': 'id'},
const {'1': 'maximum_write_length', '3': 2, '4': 1, '5': 5, '10': 'maximumWriteLength'}, const {'1': 'uuid', '3': 2, '4': 1, '5': 11, '6': '.proto.UUID', '10': 'uuid'},
], ],
}; };
/// Descriptor for `Peripheral`. Decode as a `google.protobuf.DescriptorProto`. /// Descriptor for `Peripheral`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List peripheralDescriptor = $convert.base64Decode('CgpQZXJpcGhlcmFsEg4KAmlkGAEgASgDUgJpZBIwChRtYXhpbXVtX3dyaXRlX2xlbmd0aBgCIAEoBVISbWF4aW11bVdyaXRlTGVuZ3Ro'); final $typed_data.Uint8List peripheralDescriptor = $convert.base64Decode('CgpQZXJpcGhlcmFsEg4KAmlkGAEgASgJUgJpZBIfCgR1dWlkGAIgASgLMgsucHJvdG8uVVVJRFIEdXVpZA==');
@$core.Deprecated('Use gattServiceDescriptor instead') @$core.Deprecated('Use gattServiceDescriptor instead')
const GattService$json = const { const GattService$json = const {
'1': 'GattService', '1': 'GattService',
'2': const [ '2': const [
const {'1': 'id', '3': 1, '4': 1, '5': 3, '10': 'id'}, const {'1': 'id', '3': 1, '4': 1, '5': 9, '10': 'id'},
const {'1': 'uuid', '3': 2, '4': 1, '5': 11, '6': '.proto.UUID', '10': 'uuid'}, const {'1': 'uuid', '3': 2, '4': 1, '5': 11, '6': '.proto.UUID', '10': 'uuid'},
], ],
}; };
/// Descriptor for `GattService`. Decode as a `google.protobuf.DescriptorProto`. /// Descriptor for `GattService`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List gattServiceDescriptor = $convert.base64Decode('CgtHYXR0U2VydmljZRIOCgJpZBgBIAEoA1ICaWQSHwoEdXVpZBgCIAEoCzILLnByb3RvLlVVSURSBHV1aWQ='); final $typed_data.Uint8List gattServiceDescriptor = $convert.base64Decode('CgtHYXR0U2VydmljZRIOCgJpZBgBIAEoCVICaWQSHwoEdXVpZBgCIAEoCzILLnByb3RvLlVVSURSBHV1aWQ=');
@$core.Deprecated('Use gattCharacteristicDescriptor instead') @$core.Deprecated('Use gattCharacteristicDescriptor instead')
const GattCharacteristic$json = const { const GattCharacteristic$json = const {
'1': 'GattCharacteristic', '1': 'GattCharacteristic',
'2': const [ '2': const [
const {'1': 'id', '3': 1, '4': 1, '5': 3, '10': 'id'}, const {'1': 'id', '3': 1, '4': 1, '5': 9, '10': 'id'},
const {'1': 'uuid', '3': 2, '4': 1, '5': 11, '6': '.proto.UUID', '10': 'uuid'}, const {'1': 'uuid', '3': 2, '4': 1, '5': 11, '6': '.proto.UUID', '10': 'uuid'},
const {'1': 'can_read', '3': 3, '4': 1, '5': 8, '10': 'canRead'}, const {'1': 'can_read', '3': 3, '4': 1, '5': 8, '10': 'canRead'},
const {'1': 'can_write', '3': 4, '4': 1, '5': 8, '10': 'canWrite'}, const {'1': 'can_write', '3': 4, '4': 1, '5': 8, '10': 'canWrite'},
@ -80,18 +80,18 @@ const GattCharacteristic$json = const {
}; };
/// Descriptor for `GattCharacteristic`. Decode as a `google.protobuf.DescriptorProto`. /// Descriptor for `GattCharacteristic`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List gattCharacteristicDescriptor = $convert.base64Decode('ChJHYXR0Q2hhcmFjdGVyaXN0aWMSDgoCaWQYASABKANSAmlkEh8KBHV1aWQYAiABKAsyCy5wcm90by5VVUlEUgR1dWlkEhkKCGNhbl9yZWFkGAMgASgIUgdjYW5SZWFkEhsKCWNhbl93cml0ZRgEIAEoCFIIY2FuV3JpdGUSOwoaY2FuX3dyaXRlX3dpdGhvdXRfcmVzcG9uc2UYBSABKAhSF2NhbldyaXRlV2l0aG91dFJlc3BvbnNlEh0KCmNhbl9ub3RpZnkYBiABKAhSCWNhbk5vdGlmeQ=='); final $typed_data.Uint8List gattCharacteristicDescriptor = $convert.base64Decode('ChJHYXR0Q2hhcmFjdGVyaXN0aWMSDgoCaWQYASABKAlSAmlkEh8KBHV1aWQYAiABKAsyCy5wcm90by5VVUlEUgR1dWlkEhkKCGNhbl9yZWFkGAMgASgIUgdjYW5SZWFkEhsKCWNhbl93cml0ZRgEIAEoCFIIY2FuV3JpdGUSOwoaY2FuX3dyaXRlX3dpdGhvdXRfcmVzcG9uc2UYBSABKAhSF2NhbldyaXRlV2l0aG91dFJlc3BvbnNlEh0KCmNhbl9ub3RpZnkYBiABKAhSCWNhbk5vdGlmeQ==');
@$core.Deprecated('Use gattDescriptorDescriptor instead') @$core.Deprecated('Use gattDescriptorDescriptor instead')
const GattDescriptor$json = const { const GattDescriptor$json = const {
'1': 'GattDescriptor', '1': 'GattDescriptor',
'2': const [ '2': const [
const {'1': 'id', '3': 1, '4': 1, '5': 3, '10': 'id'}, const {'1': 'id', '3': 1, '4': 1, '5': 9, '10': 'id'},
const {'1': 'uuid', '3': 2, '4': 1, '5': 11, '6': '.proto.UUID', '10': 'uuid'}, const {'1': 'uuid', '3': 2, '4': 1, '5': 11, '6': '.proto.UUID', '10': 'uuid'},
], ],
}; };
/// Descriptor for `GattDescriptor`. Decode as a `google.protobuf.DescriptorProto`. /// Descriptor for `GattDescriptor`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List gattDescriptorDescriptor = $convert.base64Decode('Cg5HYXR0RGVzY3JpcHRvchIOCgJpZBgBIAEoA1ICaWQSHwoEdXVpZBgCIAEoCzILLnByb3RvLlVVSURSBHV1aWQ='); final $typed_data.Uint8List gattDescriptorDescriptor = $convert.base64Decode('Cg5HYXR0RGVzY3JpcHRvchIOCgJpZBgBIAEoCVICaWQSHwoEdXVpZBgCIAEoCzILLnByb3RvLlVVSURSBHV1aWQ=');
@$core.Deprecated('Use uUIDDescriptor instead') @$core.Deprecated('Use uUIDDescriptor instead')
const UUID$json = const { const UUID$json = const {
'1': 'UUID', '1': 'UUID',
@ -113,13 +113,3 @@ const ServiceData$json = const {
/// Descriptor for `ServiceData`. Decode as a `google.protobuf.DescriptorProto`. /// Descriptor for `ServiceData`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List serviceDataDescriptor = $convert.base64Decode('CgtTZXJ2aWNlRGF0YRIfCgR1dWlkGAEgASgLMgsucHJvdG8uVVVJRFIEdXVpZBISCgRkYXRhGAIgASgMUgRkYXRh'); final $typed_data.Uint8List serviceDataDescriptor = $convert.base64Decode('CgtTZXJ2aWNlRGF0YRIfCgR1dWlkGAEgASgLMgsucHJvdG8uVVVJRFIEdXVpZBISCgRkYXRhGAIgASgMUgRkYXRh');
@$core.Deprecated('Use bluetoothLowEnergyExceptionDescriptor instead')
const BluetoothLowEnergyException$json = const {
'1': 'BluetoothLowEnergyException',
'2': const [
const {'1': 'message', '3': 1, '4': 1, '5': 9, '10': 'message'},
],
};
/// Descriptor for `BluetoothLowEnergyException`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List bluetoothLowEnergyExceptionDescriptor = $convert.base64Decode('ChtCbHVldG9vdGhMb3dFbmVyZ3lFeGNlcHRpb24SGAoHbWVzc2FnZRgBIAEoCVIHbWVzc2FnZQ==');

View File

@ -2,20 +2,19 @@ import 'package:pigeon/pigeon.dart';
@ConfigurePigeon( @ConfigurePigeon(
PigeonOptions( PigeonOptions(
dartOut: 'lib/src/pigeon/api.g.dart', dartOut: 'lib/src/pigeon/messages.g.dart',
dartTestOut: 'test/pigeon/test_api.g.dart', dartTestOut: 'test/pigeon/test_messages.g.dart',
javaOut: javaOut:
'android/src/main/java/dev/yanshouwang/bluetooth_low_energy/pigeon/Api.java', 'android/src/main/java/dev/yanshouwang/bluetooth_low_energy/pigeon/Messages.java',
javaOptions: JavaOptions( javaOptions: JavaOptions(
package: 'dev.yanshouwang.bluetooth_low_energy.pigeon', package: 'dev.yanshouwang.bluetooth_low_energy.pigeon',
), ),
objcHeaderOut: 'ios/Classes/pigeon/Api.h', objcHeaderOut: 'ios/Classes/pigeon/Messages.h',
objcSourceOut: 'ios/Classes/pigeon/Api.m', objcSourceOut: 'ios/Classes/pigeon/Messages.m',
objcOptions: ObjcOptions( objcOptions: ObjcOptions(
header: 'ios/Classes/pigeon/Api.h', header: 'ios/Classes/pigeon/Messages.h',
prefix: 'Pigeon', prefix: 'Pigeon',
), ),
// swiftOut: 'ios/Classes/pigeon/api.swift',
), ),
) )
@HostApi(dartHostTestHandler: 'TestCentralControllerHostApi') @HostApi(dartHostTestHandler: 'TestCentralControllerHostApi')
@ -25,95 +24,86 @@ abstract class CentralManagerHostApi {
bool authorize(); bool authorize();
@ObjCSelector('getState') @ObjCSelector('getState')
int getState(); int getState();
@ObjCSelector('addStateObserver')
void addStateObserver();
@ObjCSelector('removeStateObserver')
void removeStateObserver();
@ObjCSelector('startScan:') @ObjCSelector('startScan:')
@async @async
void startScan(List<Uint8List>? uuidBuffers); void startScan(List<Uint8List>? uuidBuffers);
@ObjCSelector('stopScan') @ObjCSelector('stopScan')
void stopScan(); void stopScan();
@ObjCSelector('connect:')
@async
Uint8List connect(Uint8List uuidBuffer);
} }
@FlutterApi() @FlutterApi()
abstract class CentralManagerFlutterApi { abstract class CentralManagerFlutterApi {
@ObjCSelector('notifyState:') @ObjCSelector('onStateChanged:')
void notifyState(int stateNumber); void onStateChanged(int stateNumber);
@ObjCSelector('notifyAdvertisement:') @ObjCSelector('onScanned:')
void notifyAdvertisement(Uint8List advertisementBuffer); void onScanned(Uint8List broadcastBuffer);
} }
@HostApi(dartHostTestHandler: 'TestPeripheralHostApi') @HostApi(dartHostTestHandler: 'TestPeripheralHostApi')
abstract class PeripheralHostApi { abstract class PeripheralHostApi {
@ObjCSelector('allocate:instanceId:')
void allocate(int id, int instanceId);
@ObjCSelector('free:') @ObjCSelector('free:')
void free(int id); void free(String id);
@ObjCSelector('connect:')
@async
void connect(String id);
@ObjCSelector('disconnect:') @ObjCSelector('disconnect:')
@async @async
void disconnect(int id); void disconnect(String id);
@ObjCSelector('requestMtu:')
@async
int requestMtu(String id);
@ObjCSelector('discoverServices:') @ObjCSelector('discoverServices:')
@async @async
List<Uint8List> discoverServices(int id); List<Uint8List> discoverServices(String id);
} }
@FlutterApi() @FlutterApi()
abstract class PeripheralFlutterApi { abstract class PeripheralFlutterApi {
@ObjCSelector('notifyConnectionLost:errorBuffer:') @ObjCSelector('onConnectionLost:errorMessage:')
void notifyConnectionLost(int id, Uint8List errorBuffer); void onConnectionLost(String id, String errorMessage);
} }
@HostApi(dartHostTestHandler: 'TestGattServiceHostApi') @HostApi(dartHostTestHandler: 'TestGattServiceHostApi')
abstract class GattServiceHostApi { abstract class GattServiceHostApi {
@ObjCSelector('allocate:instanceId:')
void allocate(int id, int instanceId);
@ObjCSelector('free:') @ObjCSelector('free:')
void free(int id); void free(String id);
@ObjCSelector('discoverCharacteristics:') @ObjCSelector('discoverCharacteristics:')
@async @async
List<Uint8List> discoverCharacteristics(int id); List<Uint8List> discoverCharacteristics(String id);
} }
@HostApi(dartHostTestHandler: 'TestGattCharacteristicHostApi') @HostApi(dartHostTestHandler: 'TestGattCharacteristicHostApi')
abstract class GattCharacteristicHostApi { abstract class GattCharacteristicHostApi {
@ObjCSelector('allocate:instanceId:')
void allocate(int id, int instanceId);
@ObjCSelector('free:') @ObjCSelector('free:')
void free(int id); void free(String id);
@ObjCSelector('discoverDescriptors:') @ObjCSelector('discoverDescriptors:')
@async @async
List<Uint8List> discoverDescriptors(int id); List<Uint8List> discoverDescriptors(String id);
@ObjCSelector('read:') @ObjCSelector('read:')
@async @async
Uint8List read(int id); Uint8List read(String id);
@ObjCSelector('write:value:withoutResponse:') @ObjCSelector('write:value:withoutResponse:')
@async @async
void write(int id, Uint8List value, bool withoutResponse); void write(String id, Uint8List value, bool withoutResponse);
@ObjCSelector('setNotify:value:') @ObjCSelector('setNotify:value:')
@async @async
void setNotify(int id, bool value); void setNotify(String id, bool value);
} }
@FlutterApi() @FlutterApi()
abstract class GattCharacteristicFlutterApi { abstract class GattCharacteristicFlutterApi {
@ObjCSelector('notifyValue:value:') @ObjCSelector('onValueChanged:value:')
void notifyValue(int id, Uint8List value); void onValueChanged(String id, Uint8List value);
} }
@HostApi(dartHostTestHandler: 'TestGattDescriptorHostApi') @HostApi(dartHostTestHandler: 'TestGattDescriptorHostApi')
abstract class GattDescriptorHostApi { abstract class GattDescriptorHostApi {
@ObjCSelector('allocate:instanceId:')
void allocate(int id, int instanceId);
@ObjCSelector('free:') @ObjCSelector('free:')
void free(int id); void free(String id);
@ObjCSelector('read:') @ObjCSelector('read:')
@async @async
Uint8List read(int id); Uint8List read(String id);
@ObjCSelector('write:value:') @ObjCSelector('write:value:')
@async @async
void write(int id, Uint8List value); void write(String id, Uint8List value);
} }

View File

@ -4,8 +4,8 @@ package proto;
option java_package = "dev.yanshouwang.bluetooth_low_energy.proto"; option java_package = "dev.yanshouwang.bluetooth_low_energy.proto";
option java_multiple_files = true; option java_multiple_files = true;
message Advertisement { message Broadcast {
UUID uuid = 1; Peripheral peripheral = 1;
int32 rssi = 2; int32 rssi = 2;
optional bool connectable = 3; optional bool connectable = 3;
bytes data = 4; bytes data = 4;
@ -18,17 +18,17 @@ message Advertisement {
} }
message Peripheral { message Peripheral {
int64 id = 1; string id = 1;
int32 maximum_write_length = 2; UUID uuid = 2;
} }
message GattService { message GattService {
int64 id = 1; string id = 1;
UUID uuid = 2; UUID uuid = 2;
} }
message GattCharacteristic { message GattCharacteristic {
int64 id = 1; string id = 1;
UUID uuid = 2; UUID uuid = 2;
bool can_read = 3; bool can_read = 3;
bool can_write = 4; bool can_write = 4;
@ -37,7 +37,7 @@ message GattCharacteristic {
} }
message GattDescriptor { message GattDescriptor {
int64 id = 1; string id = 1;
UUID uuid = 2; UUID uuid = 2;
} }
@ -55,7 +55,3 @@ message ServiceData {
UUID uuid = 1; UUID uuid = 1;
bytes data = 2; bytes data = 2;
} }
message BluetoothLowEnergyException {
string message = 1;
}

View File

@ -1,6 +1,6 @@
name: bluetooth_low_energy name: bluetooth_low_energy
description: A bluetooth low energy plugin for flutter, which can be used to develope central role apps. description: A bluetooth low energy plugin for flutter, which can be used to develope central role apps.
version: 1.0.0 version: 1.1.0
homepage: https://github.com/yanshouwang/bluetooth_low_energy homepage: https://github.com/yanshouwang/bluetooth_low_energy
environment: environment:

View File

@ -31,4 +31,4 @@ else
mkdir -p $SWIFT_OUT mkdir -p $SWIFT_OUT
fi fi
flutter pub run pigeon --input pigeon/api.dart flutter pub run pigeon --input pigeon/messages.dart

View File

@ -50,4 +50,4 @@ protoc \
--java_out $JAVA_OUT \ --java_out $JAVA_OUT \
--kotlin_out $KOTLIN_OUT \ --kotlin_out $KOTLIN_OUT \
--swift_out $SWIFT_OUT \ --swift_out $SWIFT_OUT \
proto/*.proto proto/messages.proto

View File

@ -1,4 +1,4 @@
// Autogenerated from Pigeon (v4.0.2), do not edit directly. // Autogenerated from Pigeon (v4.2.0), do not edit directly.
// See also: https://pub.dev/packages/pigeon // See also: https://pub.dev/packages/pigeon
// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, unnecessary_import // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, unnecessary_import
// ignore_for_file: avoid_relative_lib_imports // ignore_for_file: avoid_relative_lib_imports
@ -8,7 +8,7 @@ import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer;
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:bluetooth_low_energy/src/pigeon/api.g.dart'; import 'package:bluetooth_low_energy/src/pigeon/messages.g.dart';
class _TestCentralControllerHostApiCodec extends StandardMessageCodec { class _TestCentralControllerHostApiCodec extends StandardMessageCodec {
const _TestCentralControllerHostApiCodec(); const _TestCentralControllerHostApiCodec();
@ -18,11 +18,8 @@ abstract class TestCentralControllerHostApi {
Future<bool> authorize(); Future<bool> authorize();
int getState(); int getState();
void addStateObserver();
void removeStateObserver();
Future<void> startScan(List<Uint8List?>? uuidBuffers); Future<void> startScan(List<Uint8List?>? uuidBuffers);
void stopScan(); void stopScan();
Future<Uint8List> connect(Uint8List uuidBuffer);
static void setup(TestCentralControllerHostApi? api, {BinaryMessenger? binaryMessenger}) { static void setup(TestCentralControllerHostApi? api, {BinaryMessenger? binaryMessenger}) {
{ {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
@ -50,32 +47,6 @@ abstract class TestCentralControllerHostApi {
}); });
} }
} }
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.CentralManagerHostApi.addStateObserver', codec, binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
// ignore message
api.addStateObserver();
return <Object?, Object?>{};
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.CentralManagerHostApi.removeStateObserver', codec, binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
// ignore message
api.removeStateObserver();
return <Object?, Object?>{};
});
}
}
{ {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.CentralManagerHostApi.startScan', codec, binaryMessenger: binaryMessenger); 'dev.flutter.pigeon.CentralManagerHostApi.startScan', codec, binaryMessenger: binaryMessenger);
@ -104,22 +75,6 @@ abstract class TestCentralControllerHostApi {
}); });
} }
} }
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.CentralManagerHostApi.connect', codec, binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null, 'Argument for dev.flutter.pigeon.CentralManagerHostApi.connect was null.');
final List<Object?> args = (message as List<Object?>?)!;
final Uint8List? arg_uuidBuffer = (args[0] as Uint8List?);
assert(arg_uuidBuffer != null, 'Argument for dev.flutter.pigeon.CentralManagerHostApi.connect was null, expected non-null Uint8List.');
final Uint8List output = await api.connect(arg_uuidBuffer!);
return <Object?, Object?>{'result': output};
});
}
}
} }
} }
@ -129,29 +84,12 @@ class _TestPeripheralHostApiCodec extends StandardMessageCodec {
abstract class TestPeripheralHostApi { abstract class TestPeripheralHostApi {
static const MessageCodec<Object?> codec = _TestPeripheralHostApiCodec(); static const MessageCodec<Object?> codec = _TestPeripheralHostApiCodec();
void allocate(int id, int instanceId); void free(String id);
void free(int id); Future<void> connect(String id);
Future<void> disconnect(int id); Future<void> disconnect(String id);
Future<List<Uint8List?>> discoverServices(int id); Future<int> requestMtu(String id);
Future<List<Uint8List?>> discoverServices(String id);
static void setup(TestPeripheralHostApi? api, {BinaryMessenger? binaryMessenger}) { static void setup(TestPeripheralHostApi? api, {BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PeripheralHostApi.allocate', codec, binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null, 'Argument for dev.flutter.pigeon.PeripheralHostApi.allocate was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_id = (args[0] as int?);
assert(arg_id != null, 'Argument for dev.flutter.pigeon.PeripheralHostApi.allocate was null, expected non-null int.');
final int? arg_instanceId = (args[1] as int?);
assert(arg_instanceId != null, 'Argument for dev.flutter.pigeon.PeripheralHostApi.allocate was null, expected non-null int.');
api.allocate(arg_id!, arg_instanceId!);
return <Object?, Object?>{};
});
}
}
{ {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PeripheralHostApi.free', codec, binaryMessenger: binaryMessenger); 'dev.flutter.pigeon.PeripheralHostApi.free', codec, binaryMessenger: binaryMessenger);
@ -161,13 +99,29 @@ abstract class TestPeripheralHostApi {
channel.setMockMessageHandler((Object? message) async { channel.setMockMessageHandler((Object? message) async {
assert(message != null, 'Argument for dev.flutter.pigeon.PeripheralHostApi.free was null.'); assert(message != null, 'Argument for dev.flutter.pigeon.PeripheralHostApi.free was null.');
final List<Object?> args = (message as List<Object?>?)!; final List<Object?> args = (message as List<Object?>?)!;
final int? arg_id = (args[0] as int?); final String? arg_id = (args[0] as String?);
assert(arg_id != null, 'Argument for dev.flutter.pigeon.PeripheralHostApi.free was null, expected non-null int.'); assert(arg_id != null, 'Argument for dev.flutter.pigeon.PeripheralHostApi.free was null, expected non-null String.');
api.free(arg_id!); api.free(arg_id!);
return <Object?, Object?>{}; return <Object?, Object?>{};
}); });
} }
} }
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PeripheralHostApi.connect', codec, binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null, 'Argument for dev.flutter.pigeon.PeripheralHostApi.connect was null.');
final List<Object?> args = (message as List<Object?>?)!;
final String? arg_id = (args[0] as String?);
assert(arg_id != null, 'Argument for dev.flutter.pigeon.PeripheralHostApi.connect was null, expected non-null String.');
await api.connect(arg_id!);
return <Object?, Object?>{};
});
}
}
{ {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PeripheralHostApi.disconnect', codec, binaryMessenger: binaryMessenger); 'dev.flutter.pigeon.PeripheralHostApi.disconnect', codec, binaryMessenger: binaryMessenger);
@ -177,13 +131,29 @@ abstract class TestPeripheralHostApi {
channel.setMockMessageHandler((Object? message) async { channel.setMockMessageHandler((Object? message) async {
assert(message != null, 'Argument for dev.flutter.pigeon.PeripheralHostApi.disconnect was null.'); assert(message != null, 'Argument for dev.flutter.pigeon.PeripheralHostApi.disconnect was null.');
final List<Object?> args = (message as List<Object?>?)!; final List<Object?> args = (message as List<Object?>?)!;
final int? arg_id = (args[0] as int?); final String? arg_id = (args[0] as String?);
assert(arg_id != null, 'Argument for dev.flutter.pigeon.PeripheralHostApi.disconnect was null, expected non-null int.'); assert(arg_id != null, 'Argument for dev.flutter.pigeon.PeripheralHostApi.disconnect was null, expected non-null String.');
await api.disconnect(arg_id!); await api.disconnect(arg_id!);
return <Object?, Object?>{}; return <Object?, Object?>{};
}); });
} }
} }
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PeripheralHostApi.requestMtu', codec, binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null, 'Argument for dev.flutter.pigeon.PeripheralHostApi.requestMtu was null.');
final List<Object?> args = (message as List<Object?>?)!;
final String? arg_id = (args[0] as String?);
assert(arg_id != null, 'Argument for dev.flutter.pigeon.PeripheralHostApi.requestMtu was null, expected non-null String.');
final int output = await api.requestMtu(arg_id!);
return <Object?, Object?>{'result': output};
});
}
}
{ {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PeripheralHostApi.discoverServices', codec, binaryMessenger: binaryMessenger); 'dev.flutter.pigeon.PeripheralHostApi.discoverServices', codec, binaryMessenger: binaryMessenger);
@ -193,8 +163,8 @@ abstract class TestPeripheralHostApi {
channel.setMockMessageHandler((Object? message) async { channel.setMockMessageHandler((Object? message) async {
assert(message != null, 'Argument for dev.flutter.pigeon.PeripheralHostApi.discoverServices was null.'); assert(message != null, 'Argument for dev.flutter.pigeon.PeripheralHostApi.discoverServices was null.');
final List<Object?> args = (message as List<Object?>?)!; final List<Object?> args = (message as List<Object?>?)!;
final int? arg_id = (args[0] as int?); final String? arg_id = (args[0] as String?);
assert(arg_id != null, 'Argument for dev.flutter.pigeon.PeripheralHostApi.discoverServices was null, expected non-null int.'); assert(arg_id != null, 'Argument for dev.flutter.pigeon.PeripheralHostApi.discoverServices was null, expected non-null String.');
final List<Uint8List?> output = await api.discoverServices(arg_id!); final List<Uint8List?> output = await api.discoverServices(arg_id!);
return <Object?, Object?>{'result': output}; return <Object?, Object?>{'result': output};
}); });
@ -209,28 +179,9 @@ class _TestGattServiceHostApiCodec extends StandardMessageCodec {
abstract class TestGattServiceHostApi { abstract class TestGattServiceHostApi {
static const MessageCodec<Object?> codec = _TestGattServiceHostApiCodec(); static const MessageCodec<Object?> codec = _TestGattServiceHostApiCodec();
void allocate(int id, int instanceId); void free(String id);
void free(int id); Future<List<Uint8List?>> discoverCharacteristics(String id);
Future<List<Uint8List?>> discoverCharacteristics(int id);
static void setup(TestGattServiceHostApi? api, {BinaryMessenger? binaryMessenger}) { static void setup(TestGattServiceHostApi? api, {BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.GattServiceHostApi.allocate', codec, binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null, 'Argument for dev.flutter.pigeon.GattServiceHostApi.allocate was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_id = (args[0] as int?);
assert(arg_id != null, 'Argument for dev.flutter.pigeon.GattServiceHostApi.allocate was null, expected non-null int.');
final int? arg_instanceId = (args[1] as int?);
assert(arg_instanceId != null, 'Argument for dev.flutter.pigeon.GattServiceHostApi.allocate was null, expected non-null int.');
api.allocate(arg_id!, arg_instanceId!);
return <Object?, Object?>{};
});
}
}
{ {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.GattServiceHostApi.free', codec, binaryMessenger: binaryMessenger); 'dev.flutter.pigeon.GattServiceHostApi.free', codec, binaryMessenger: binaryMessenger);
@ -240,8 +191,8 @@ abstract class TestGattServiceHostApi {
channel.setMockMessageHandler((Object? message) async { channel.setMockMessageHandler((Object? message) async {
assert(message != null, 'Argument for dev.flutter.pigeon.GattServiceHostApi.free was null.'); assert(message != null, 'Argument for dev.flutter.pigeon.GattServiceHostApi.free was null.');
final List<Object?> args = (message as List<Object?>?)!; final List<Object?> args = (message as List<Object?>?)!;
final int? arg_id = (args[0] as int?); final String? arg_id = (args[0] as String?);
assert(arg_id != null, 'Argument for dev.flutter.pigeon.GattServiceHostApi.free was null, expected non-null int.'); assert(arg_id != null, 'Argument for dev.flutter.pigeon.GattServiceHostApi.free was null, expected non-null String.');
api.free(arg_id!); api.free(arg_id!);
return <Object?, Object?>{}; return <Object?, Object?>{};
}); });
@ -256,8 +207,8 @@ abstract class TestGattServiceHostApi {
channel.setMockMessageHandler((Object? message) async { channel.setMockMessageHandler((Object? message) async {
assert(message != null, 'Argument for dev.flutter.pigeon.GattServiceHostApi.discoverCharacteristics was null.'); assert(message != null, 'Argument for dev.flutter.pigeon.GattServiceHostApi.discoverCharacteristics was null.');
final List<Object?> args = (message as List<Object?>?)!; final List<Object?> args = (message as List<Object?>?)!;
final int? arg_id = (args[0] as int?); final String? arg_id = (args[0] as String?);
assert(arg_id != null, 'Argument for dev.flutter.pigeon.GattServiceHostApi.discoverCharacteristics was null, expected non-null int.'); assert(arg_id != null, 'Argument for dev.flutter.pigeon.GattServiceHostApi.discoverCharacteristics was null, expected non-null String.');
final List<Uint8List?> output = await api.discoverCharacteristics(arg_id!); final List<Uint8List?> output = await api.discoverCharacteristics(arg_id!);
return <Object?, Object?>{'result': output}; return <Object?, Object?>{'result': output};
}); });
@ -272,31 +223,12 @@ class _TestGattCharacteristicHostApiCodec extends StandardMessageCodec {
abstract class TestGattCharacteristicHostApi { abstract class TestGattCharacteristicHostApi {
static const MessageCodec<Object?> codec = _TestGattCharacteristicHostApiCodec(); static const MessageCodec<Object?> codec = _TestGattCharacteristicHostApiCodec();
void allocate(int id, int instanceId); void free(String id);
void free(int id); Future<List<Uint8List?>> discoverDescriptors(String id);
Future<List<Uint8List?>> discoverDescriptors(int id); Future<Uint8List> read(String id);
Future<Uint8List> read(int id); Future<void> write(String id, Uint8List value, bool withoutResponse);
Future<void> write(int id, Uint8List value, bool withoutResponse); Future<void> setNotify(String id, bool value);
Future<void> setNotify(int id, bool value);
static void setup(TestGattCharacteristicHostApi? api, {BinaryMessenger? binaryMessenger}) { static void setup(TestGattCharacteristicHostApi? api, {BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.GattCharacteristicHostApi.allocate', codec, binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null, 'Argument for dev.flutter.pigeon.GattCharacteristicHostApi.allocate was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_id = (args[0] as int?);
assert(arg_id != null, 'Argument for dev.flutter.pigeon.GattCharacteristicHostApi.allocate was null, expected non-null int.');
final int? arg_instanceId = (args[1] as int?);
assert(arg_instanceId != null, 'Argument for dev.flutter.pigeon.GattCharacteristicHostApi.allocate was null, expected non-null int.');
api.allocate(arg_id!, arg_instanceId!);
return <Object?, Object?>{};
});
}
}
{ {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.GattCharacteristicHostApi.free', codec, binaryMessenger: binaryMessenger); 'dev.flutter.pigeon.GattCharacteristicHostApi.free', codec, binaryMessenger: binaryMessenger);
@ -306,8 +238,8 @@ abstract class TestGattCharacteristicHostApi {
channel.setMockMessageHandler((Object? message) async { channel.setMockMessageHandler((Object? message) async {
assert(message != null, 'Argument for dev.flutter.pigeon.GattCharacteristicHostApi.free was null.'); assert(message != null, 'Argument for dev.flutter.pigeon.GattCharacteristicHostApi.free was null.');
final List<Object?> args = (message as List<Object?>?)!; final List<Object?> args = (message as List<Object?>?)!;
final int? arg_id = (args[0] as int?); final String? arg_id = (args[0] as String?);
assert(arg_id != null, 'Argument for dev.flutter.pigeon.GattCharacteristicHostApi.free was null, expected non-null int.'); assert(arg_id != null, 'Argument for dev.flutter.pigeon.GattCharacteristicHostApi.free was null, expected non-null String.');
api.free(arg_id!); api.free(arg_id!);
return <Object?, Object?>{}; return <Object?, Object?>{};
}); });
@ -322,8 +254,8 @@ abstract class TestGattCharacteristicHostApi {
channel.setMockMessageHandler((Object? message) async { channel.setMockMessageHandler((Object? message) async {
assert(message != null, 'Argument for dev.flutter.pigeon.GattCharacteristicHostApi.discoverDescriptors was null.'); assert(message != null, 'Argument for dev.flutter.pigeon.GattCharacteristicHostApi.discoverDescriptors was null.');
final List<Object?> args = (message as List<Object?>?)!; final List<Object?> args = (message as List<Object?>?)!;
final int? arg_id = (args[0] as int?); final String? arg_id = (args[0] as String?);
assert(arg_id != null, 'Argument for dev.flutter.pigeon.GattCharacteristicHostApi.discoverDescriptors was null, expected non-null int.'); assert(arg_id != null, 'Argument for dev.flutter.pigeon.GattCharacteristicHostApi.discoverDescriptors was null, expected non-null String.');
final List<Uint8List?> output = await api.discoverDescriptors(arg_id!); final List<Uint8List?> output = await api.discoverDescriptors(arg_id!);
return <Object?, Object?>{'result': output}; return <Object?, Object?>{'result': output};
}); });
@ -338,8 +270,8 @@ abstract class TestGattCharacteristicHostApi {
channel.setMockMessageHandler((Object? message) async { channel.setMockMessageHandler((Object? message) async {
assert(message != null, 'Argument for dev.flutter.pigeon.GattCharacteristicHostApi.read was null.'); assert(message != null, 'Argument for dev.flutter.pigeon.GattCharacteristicHostApi.read was null.');
final List<Object?> args = (message as List<Object?>?)!; final List<Object?> args = (message as List<Object?>?)!;
final int? arg_id = (args[0] as int?); final String? arg_id = (args[0] as String?);
assert(arg_id != null, 'Argument for dev.flutter.pigeon.GattCharacteristicHostApi.read was null, expected non-null int.'); assert(arg_id != null, 'Argument for dev.flutter.pigeon.GattCharacteristicHostApi.read was null, expected non-null String.');
final Uint8List output = await api.read(arg_id!); final Uint8List output = await api.read(arg_id!);
return <Object?, Object?>{'result': output}; return <Object?, Object?>{'result': output};
}); });
@ -354,8 +286,8 @@ abstract class TestGattCharacteristicHostApi {
channel.setMockMessageHandler((Object? message) async { channel.setMockMessageHandler((Object? message) async {
assert(message != null, 'Argument for dev.flutter.pigeon.GattCharacteristicHostApi.write was null.'); assert(message != null, 'Argument for dev.flutter.pigeon.GattCharacteristicHostApi.write was null.');
final List<Object?> args = (message as List<Object?>?)!; final List<Object?> args = (message as List<Object?>?)!;
final int? arg_id = (args[0] as int?); final String? arg_id = (args[0] as String?);
assert(arg_id != null, 'Argument for dev.flutter.pigeon.GattCharacteristicHostApi.write was null, expected non-null int.'); assert(arg_id != null, 'Argument for dev.flutter.pigeon.GattCharacteristicHostApi.write was null, expected non-null String.');
final Uint8List? arg_value = (args[1] as Uint8List?); final Uint8List? arg_value = (args[1] as Uint8List?);
assert(arg_value != null, 'Argument for dev.flutter.pigeon.GattCharacteristicHostApi.write was null, expected non-null Uint8List.'); assert(arg_value != null, 'Argument for dev.flutter.pigeon.GattCharacteristicHostApi.write was null, expected non-null Uint8List.');
final bool? arg_withoutResponse = (args[2] as bool?); final bool? arg_withoutResponse = (args[2] as bool?);
@ -374,8 +306,8 @@ abstract class TestGattCharacteristicHostApi {
channel.setMockMessageHandler((Object? message) async { channel.setMockMessageHandler((Object? message) async {
assert(message != null, 'Argument for dev.flutter.pigeon.GattCharacteristicHostApi.setNotify was null.'); assert(message != null, 'Argument for dev.flutter.pigeon.GattCharacteristicHostApi.setNotify was null.');
final List<Object?> args = (message as List<Object?>?)!; final List<Object?> args = (message as List<Object?>?)!;
final int? arg_id = (args[0] as int?); final String? arg_id = (args[0] as String?);
assert(arg_id != null, 'Argument for dev.flutter.pigeon.GattCharacteristicHostApi.setNotify was null, expected non-null int.'); assert(arg_id != null, 'Argument for dev.flutter.pigeon.GattCharacteristicHostApi.setNotify was null, expected non-null String.');
final bool? arg_value = (args[1] as bool?); final bool? arg_value = (args[1] as bool?);
assert(arg_value != null, 'Argument for dev.flutter.pigeon.GattCharacteristicHostApi.setNotify was null, expected non-null bool.'); assert(arg_value != null, 'Argument for dev.flutter.pigeon.GattCharacteristicHostApi.setNotify was null, expected non-null bool.');
await api.setNotify(arg_id!, arg_value!); await api.setNotify(arg_id!, arg_value!);
@ -392,29 +324,10 @@ class _TestGattDescriptorHostApiCodec extends StandardMessageCodec {
abstract class TestGattDescriptorHostApi { abstract class TestGattDescriptorHostApi {
static const MessageCodec<Object?> codec = _TestGattDescriptorHostApiCodec(); static const MessageCodec<Object?> codec = _TestGattDescriptorHostApiCodec();
void allocate(int id, int instanceId); void free(String id);
void free(int id); Future<Uint8List> read(String id);
Future<Uint8List> read(int id); Future<void> write(String id, Uint8List value);
Future<void> write(int id, Uint8List value);
static void setup(TestGattDescriptorHostApi? api, {BinaryMessenger? binaryMessenger}) { static void setup(TestGattDescriptorHostApi? api, {BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.GattDescriptorHostApi.allocate', codec, binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null, 'Argument for dev.flutter.pigeon.GattDescriptorHostApi.allocate was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_id = (args[0] as int?);
assert(arg_id != null, 'Argument for dev.flutter.pigeon.GattDescriptorHostApi.allocate was null, expected non-null int.');
final int? arg_instanceId = (args[1] as int?);
assert(arg_instanceId != null, 'Argument for dev.flutter.pigeon.GattDescriptorHostApi.allocate was null, expected non-null int.');
api.allocate(arg_id!, arg_instanceId!);
return <Object?, Object?>{};
});
}
}
{ {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.GattDescriptorHostApi.free', codec, binaryMessenger: binaryMessenger); 'dev.flutter.pigeon.GattDescriptorHostApi.free', codec, binaryMessenger: binaryMessenger);
@ -424,8 +337,8 @@ abstract class TestGattDescriptorHostApi {
channel.setMockMessageHandler((Object? message) async { channel.setMockMessageHandler((Object? message) async {
assert(message != null, 'Argument for dev.flutter.pigeon.GattDescriptorHostApi.free was null.'); assert(message != null, 'Argument for dev.flutter.pigeon.GattDescriptorHostApi.free was null.');
final List<Object?> args = (message as List<Object?>?)!; final List<Object?> args = (message as List<Object?>?)!;
final int? arg_id = (args[0] as int?); final String? arg_id = (args[0] as String?);
assert(arg_id != null, 'Argument for dev.flutter.pigeon.GattDescriptorHostApi.free was null, expected non-null int.'); assert(arg_id != null, 'Argument for dev.flutter.pigeon.GattDescriptorHostApi.free was null, expected non-null String.');
api.free(arg_id!); api.free(arg_id!);
return <Object?, Object?>{}; return <Object?, Object?>{};
}); });
@ -440,8 +353,8 @@ abstract class TestGattDescriptorHostApi {
channel.setMockMessageHandler((Object? message) async { channel.setMockMessageHandler((Object? message) async {
assert(message != null, 'Argument for dev.flutter.pigeon.GattDescriptorHostApi.read was null.'); assert(message != null, 'Argument for dev.flutter.pigeon.GattDescriptorHostApi.read was null.');
final List<Object?> args = (message as List<Object?>?)!; final List<Object?> args = (message as List<Object?>?)!;
final int? arg_id = (args[0] as int?); final String? arg_id = (args[0] as String?);
assert(arg_id != null, 'Argument for dev.flutter.pigeon.GattDescriptorHostApi.read was null, expected non-null int.'); assert(arg_id != null, 'Argument for dev.flutter.pigeon.GattDescriptorHostApi.read was null, expected non-null String.');
final Uint8List output = await api.read(arg_id!); final Uint8List output = await api.read(arg_id!);
return <Object?, Object?>{'result': output}; return <Object?, Object?>{'result': output};
}); });
@ -456,8 +369,8 @@ abstract class TestGattDescriptorHostApi {
channel.setMockMessageHandler((Object? message) async { channel.setMockMessageHandler((Object? message) async {
assert(message != null, 'Argument for dev.flutter.pigeon.GattDescriptorHostApi.write was null.'); assert(message != null, 'Argument for dev.flutter.pigeon.GattDescriptorHostApi.write was null.');
final List<Object?> args = (message as List<Object?>?)!; final List<Object?> args = (message as List<Object?>?)!;
final int? arg_id = (args[0] as int?); final String? arg_id = (args[0] as String?);
assert(arg_id != null, 'Argument for dev.flutter.pigeon.GattDescriptorHostApi.write was null, expected non-null int.'); assert(arg_id != null, 'Argument for dev.flutter.pigeon.GattDescriptorHostApi.write was null, expected non-null String.');
final Uint8List? arg_value = (args[1] as Uint8List?); final Uint8List? arg_value = (args[1] as Uint8List?);
assert(arg_value != null, 'Argument for dev.flutter.pigeon.GattDescriptorHostApi.write was null, expected non-null Uint8List.'); assert(arg_value != null, 'Argument for dev.flutter.pigeon.GattDescriptorHostApi.write was null, expected non-null Uint8List.');
await api.write(arg_id!, arg_value!); await api.write(arg_id!, arg_value!);