Code Monkey home page Code Monkey logo

Comments (4)

shamblett avatar shamblett commented on August 30, 2024

So are you saying that messages you publish do not get to listening clients but you can receive publish messages from them?. The log should show your publish messages being sent, is this happening?

from mqtt_client.

sanrixue avatar sanrixue commented on August 30, 2024

The following is my practical operation based on a case study,
Unable to listen for subscription information after a long connection.
Because I need to maintain a long-term connection, I removed the startClean() method。

const deviceID = "XXXX";
const pubTopic = 'XXX';
const username = "XXXX";
const password = "XXXXX";
const willTopic = "XXXXX";

MqttServerClient? client;

class MqttClientServer {
Future createMqtt() async {
/// Set logging on if needed, defaults to off
// client.logging(on: true);

client = MqttServerClient('wss://XXXX', deviceID, maxConnectionAttempts: 10);

client!.port = 443;

client!.useWebSocket = true;

client!.websocketProtocols = MqttClientConstants.protocolsMultipleDefault;

// client!.port = 1883;  //use IP address

/// Set the correct MQTT protocol for testing against mosquito
client!.setProtocolV311();

/// If you intend to use a keep alive you must set it here otherwise keep alive will be disabled.
client!.keepAlivePeriod = 5;

/// The connection timeout period can be set if needed, the default is 5 seconds.
client!.connectTimeoutPeriod = 2000; // milliseconds

/// Set auto reconnect
client!.autoReconnect = true;

/// If you do not want active confirmed subscriptions to be automatically re subscribed
/// by the auto connect sequence do the following, otherwise leave this defaulted.
client!.resubscribeOnAutoReconnect = false;

/// Add an auto reconnect callback.
/// This is the 'pre' auto re connect callback, called before the sequence starts.
client!.onAutoReconnect = onAutoReconnect;

/// Add an auto reconnect callback.
/// This is the 'post' auto re connect callback, called after the sequence
/// has completed. Note that re subscriptions may be occurring when this callback
/// is invoked. See [resubscribeOnAutoReconnect] above.
client!.onAutoReconnected = onAutoReconnected;

/// Add the successful connection callback if you need one.
/// This will be called after [onAutoReconnect] but before [onAutoReconnected]
client!.onConnected = onConnected;

/// Add a subscribed callback, there is also an unsubscribed callback if you need it.
/// You can add these before connection or change them dynamically after connection if
/// you wish. There is also an onSubscribeFail callback for failed subscriptions, these
/// can fail either because you have tried to subscribe to an invalid topic or the broker
/// rejects the subscribe request.
client!.onSubscribed = onSubscribed;

/// Set a ping received callback if needed, called whenever a ping response(pong) is received
/// from the broker.
client!.pongCallback = pong;

/// Create a connection message to use or use the default one. The default one sets the
/// client identifier, any supplied username/password and clean session,
/// an example of a specific one below.
final connMess = MqttConnectMessage()
    .authenticateAs(username, password)
    .withClientIdentifier(deviceID)
    .withWillTopic(willTopic)
    .withWillMessage('$deviceID下线')
    .withWillQos(MqttQos.exactlyOnce);
print('EXAMPLE::Mosquitto client connecting....');
client!.connectionMessage = connMess;

/// Connect the client, any errors here are communicated by raising of the appropriate exception. Note
/// in some circumstances the broker will just disconnect us, see the spec about this, we however will
/// never send malformed messages.
try {
  await client!.connect(username, password);
} on Exception catch (e) {
  print('EXAMPLE::client exception - $e');
  client!.disconnect();
}

/// Check we are connected
if (client!.connectionStatus!.state == MqttConnectionState.connected) {
  print('EXAMPLE::Mosquitto client connected');
} else {
  /// Use status here rather than state if you also want the broker return code.
  print('EXAMPLE::ERROR Mosquitto client connection failed - disconnecting, status is ${client!.connectionStatus}');
  client!.disconnect();
  exit(-1);
}

client!.subscribe(deviceID, MqttQos.atMostOnce);

/// The client has a change notifier object(see the Observable class) which we then listen to to get
/// notifications of published updates to each subscribed topic.
client!.updates!.listen((List<MqttReceivedMessage<MqttMessage?>>? c) {
  final recMess = c![0].payload as MqttPublishMessage;
  final pt = MqttPublishPayload.bytesToStringAsString(recMess.payload.message);
  print('EXAMPLE::Change notification:: topic is <${c[0].topic}>, payload is <-- $pt -->');
  print('');
});

/// If needed you can listen for published messages that have completed the publishing
/// handshake which is Qos dependant. Any message received on this stream has completed its
/// publishing handshake with the broker.
client!.published!.listen((MqttPublishMessage message) {
  print(
      'EXAMPLE::Published notification:: topic is ${message.variableHeader!.topicName}, with Qos ${message.header!.qos}');
});

/// Lets publish to our topic
/// Use the payload builder rather than a raw buffer
/// Our known topic to publish to
final builder = MqttClientPayloadBuilder();
builder.addString('Hello from mqtt_client');

// /// Subscribe to it
// print('EXAMPLE::Subscribing to the Dart/Mqtt_client/testtopic topic');
// client!.subscribe(deviceID, MqttQos.exactlyOnce);

client!.publishMessage(pubTopic, MqttQos.exactlyOnce, builder.payload!);

return 0;

}

/// The subscribed callback
void onSubscribed(String topic) {
print('EXAMPLE::Subscription confirmed for topic $topic');
}

/// The pre auto re connect callback
void onAutoReconnect() {
print('EXAMPLE::onAutoReconnect client callback - Client auto reconnection sequence will start');
}

/// The post auto re connect callback
void onAutoReconnected() {
print('EXAMPLE::onAutoReconnected client callback - Client auto reconnection sequence has completed');
}

/// The successful connect callback
void onConnected() {
print('EXAMPLE::OnConnected client callback - Client connection was successful');
}

/// Pong callback
void pong() {
print('EXAMPLE::Ping response client callback invoked - you may want to disconnect your broker here');
}
}

from mqtt_client.

sanrixue avatar sanrixue commented on August 30, 2024

So are you saying that messages you publish do not get to listening clients but you can receive publish messages from them?. The log should show your publish messages being sent, is this happening?

I can send messages from the client to my subscribed server.
But after a long time (which cannot be estimated), the client cannot listen to the information.
And My ping log continues to be:
EXAMPLE::Ping response client callback invoked - you may want to disconnect your broker here

from mqtt_client.

shamblett avatar shamblett commented on August 30, 2024

I can't do anything without a log, I need to see if any received publish messages are being processed or not and indeed if they are being received at all. Keep alive only shows that the client and broker are connected, not that the broker is sending publish messages.

from mqtt_client.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.