connect method
Connects to a BITalino device address.
Returns true
if the device is connected successfully, false
otherwise.
A valid bluetooth device address must be provided.
A onConnectionLost
callback can also be provided.
Throws BITalinoException(BITalinoErrorType.ALREADY_CONNECTING) if a connection attempt is already in progress. Throws BITalinoException(BITalinoErrorType.TIMEOUT) if the timeout limit is reached. Throws BITalinoException(BITalinoErrorType.BT_DEVICE_NOT_CONNECTED) if a device is not connected. Throws BITalinoException(BITalinoErrorType.BT_DEVICE_ALREADY_CONNECTED) if a device is already connected. Throws BITalinoException(BITalinoErrorType.BT_DEVICE_FAILED_CONNECT) if the device fails to connect. Throws BITalinoException(BITalinoErrorType.CUSTOM) if a native exception was raised.
Implementation
Future<bool> connect({OnConnectionLost? onConnectionLost}) async {
if (_connecting)
throw BITalinoException(BITalinoErrorType.ALREADY_CONNECTING);
if (connected)
throw BITalinoException(BITalinoErrorType.BT_DEVICE_ALREADY_CONNECTED);
try {
_connecting = true;
if (Platform.isAndroid) {
connected = await _channel.invokeMethod(
"connect", <String, dynamic>{"address": address}).timeout(timeout);
} else if (Platform.isIOS) {
connected = await _channel.invokeMethod("connect").timeout(timeout);
}
} on TimeoutException {
_connecting = false;
throw BITalinoException(BITalinoErrorType.TIMEOUT);
} catch (e) {
_connecting = false;
throw BITalinoException(BITalinoErrorType.BT_DEVICE_FAILED_CONNECT);
}
_connecting = false;
if (connected) {
_onConnectionLost = onConnectionLost;
return true;
} else {
throw BITalinoException(BITalinoErrorType.BT_DEVICE_FAILED_CONNECT);
}
}