initializeMQTTClient method

void initializeMQTTClient({
  1. bool logging = kDebugMode,
  2. String? hostConfig,
  3. int? portConfig,
  4. bool? useWebSocket,
  5. int? keepAlivePeriod,
  6. bool? autoReconnect,
  7. bool setProtocolV311 = true,
})

Implementation

void initializeMQTTClient({
  bool logging = kDebugMode,
  String? hostConfig,
  int? portConfig,
  bool? useWebSocket,
  int? keepAlivePeriod,
  bool? autoReconnect,
  bool setProtocolV311 = true,
}) {
  String host =
      hostConfig ?? (appMqttUrl != null ? 'wss://$appMqttUrl/mqtt' : '');
  int port = portConfig ?? appMqttPort ?? 80;

  client = MqttBrowserClient(host, _identifier)
    ..setProtocolV311()
    ..autoReconnect = autoReconnect ?? true
    ..port = port
    ..keepAlivePeriod = keepAlivePeriod ?? 200
    // ..useWebSocket = useWebSocket ?? true
    ..logging(on: logging)

    /// Add the successful connection callback
    ..onConnected = onConnected
    ..onDisconnected = onDisconnected
    ..onAutoReconnected = onReConnected
    ..onSubscribed = onSubscribed;

  if (setProtocolV311) {
    client!.setProtocolV311();
  }
  if (useWebSocket ?? true) {
    client!.websocketProtocols = MqttClientConstants.protocolsSingleDefault;
  }

  final MqttConnectMessage connMess = MqttConnectMessage()
      .withClientIdentifier(_identifier)
      // .withWillTopic(
      //     'willtopic') // If you set this you must set a will message
      // .withWillMessage('My Will message')
      // .startClean() // Non persistent session for testing
      .withWillQos(MqttQos.atMostOnce);
  if (_allowPrintLog) print('MQTT::Mosquitto client connecting....');
  client!.connectionMessage = connMess;
}