connect method
Common client connection method.
Implementation
Future<MqttClientConnectionStatus?> connect(
[String? username, String? password]) async {
// Protect against an incorrect instantiation
if (!instantiationCorrect) {
throw IncorrectInstantiationException();
}
// Generate the client id for logging
MqttLogger.clientId++;
checkCredentials(username, password);
// Set the authentication parameters in the connection
// message if we have one.
connectionMessage?.authenticateAs(username, password);
// Do the connection
final connectionHandler = this.connectionHandler;
if (connectionHandler == null) {
throw StateError('connectionHandler is null');
}
if (websocketProtocolString != null) {
connectionHandler.websocketProtocols = websocketProtocolString;
}
connectionHandler.onDisconnected = internalDisconnect;
connectionHandler.onConnected = onConnected;
connectionHandler.onAutoReconnect = onAutoReconnect;
connectionHandler.onAutoReconnected = onAutoReconnected;
MqttLogger.log(
'MqttClient::connect - Connection timeout period is $connectTimeoutPeriod milliseconds');
publishingManager = PublishingManager(connectionHandler, clientEventBus);
publishingManager!.manuallyAcknowledgeQos1 = _manuallyAcknowledgeQos1;
subscriptionsManager = SubscriptionsManager(
connectionHandler, publishingManager, clientEventBus);
subscriptionsManager!.onSubscribed = onSubscribed;
subscriptionsManager!.onUnsubscribed = onUnsubscribed;
subscriptionsManager!.onSubscribeFail = onSubscribeFail;
subscriptionsManager!.resubscribeOnAutoReconnect =
resubscribeOnAutoReconnect;
if (keepAlivePeriod != MqttClientConstants.defaultKeepAlive) {
MqttLogger.log(
'MqttClient::connect - keep alive is enabled with a value of $keepAlivePeriod seconds');
keepAlive = MqttConnectionKeepAlive(connectionHandler, clientEventBus,
keepAlivePeriod, disconnectOnNoResponsePeriod);
if (pongCallback != null) {
keepAlive!.pongCallback = pongCallback;
}
} else {
MqttLogger.log('MqttClient::connect - keep alive is disabled');
}
final connectMessage = getConnectMessage(username, password);
// If the client id is not set in the connection message use the one
// supplied in the constructor.
if (connectMessage.payload.clientIdentifier.isEmpty) {
connectMessage.payload.clientIdentifier = clientIdentifier;
}
// Set keep alive period.
connectMessage.variableHeader?.keepAlive = keepAlivePeriod;
connectionMessage = connectMessage;
return connectionHandler.connect(server, port, connectMessage);
}