Comments (9)
OK I'll need a log from the autoreconnect point onwards.
When you say you resubscribed do you have an onSubscribe callback to check if the subscription worked?
from mqtt_client.
Thanks, @shamblett for your quick response.
Before subscribing to a topic, I am checking existing subscriptions and if a new topic does not exist then only I am subscribing.
Subscriptions are happening correctly, but I am not sure what should I do when the network changes by User.
I am not receiving updates while user has only this case,
Let's say as an example, that User A has Mobile Data and Wifi both connected while using the app but when the user turns off the WIFI, I get a callback from the network listener about the network being disconnected and that same time, I am disconnecting the MQTT and when I am receiving callback of network about mobile data is connected, I am calling below connectMQTT function. This same function calls(main function) when a user opens an app from killed mode.
connectMQTT(){
try {
debugPrint('NEW 🦟 MQTT2 🦟 CONNECT FROM $from');
await newMQTTclient!.connect();
if (newMQTTclient!.connectionStatus!.state ==
MqttConnectionState.connected) {
debugPrint('NEW 🦟 MQTT2 🦟 CONNECTED');
} else {
/// Use status here rather than state if you also want the broker return code.
debugPrint(
'NEW 🦟 MQTT2 🦟 DISCONNECTING ${newMQTTclient!.connectionStatus}');
newMQTTclient!.disconnect();
exit(-1);
}
debugPrint('NEW 🦟 MQTT2-CHECK:: ${newMQTTclient == null}');
debugPrint(
'NEW 🦟 MQTT2-UPDATE CHECK:: ${newMQTTclient!.updates == null}');
newMQTTclient!.published!.listen((MqttPublishMessage message) {
var payload =
MqttPublishPayload.bytesToStringAsString(message.payload.message);
debugPrint('NEW 🦟 MQTT2 PUBLISHED:: ${payload}');
});
newMQTTclient!.updates!.listen(
(List<MqttReceivedMessage<MqttMessage?>>? c) {
debugPrint('NEW 🦟 MQTT2 ON UPDATES - {$c}');
for (int i = 0; i < c!.length; i++) {
final MqttPublishMessage message =
c[i].payload as MqttPublishMessage;
var payload = MqttPublishPayload.bytesToStringAsString(
message.payload.message);
debugPrint(
"NEW 🦟 MQTT2 🦟 RESPONSE NEW ${DateTime.now()} $payload");
DeviceResponseUtils()
.handleResponse(str: payload, ipAddress: "", isMqtt: true);
}
},
cancelOnError: true,
onError: (Object error) {
debugPrint('NEW 🦟 MQTT2 ON ERROR - UPDATES');
},
onDone: () {
debugPrint('NEW 🦟 MQTT2 ON DONE - UPDATES');
},
);
} on NoConnectionException catch (e) {
debugPrint('${DateTime.now()} NEW 🦟 MQTT2 🦟 :client exception - $e');
newMQTTclient!.disconnect();
} on SocketException catch (e) {
debugPrint('${DateTime.now()} NEW 🦟 MQTT2 🦟 :socket exception - $e');
newMQTTclient!.disconnect();
}
subscribeDevices();
}
void subscribeDevices({String? from}) {
await Device().fetchAllNewDevices().then((listDevice) {
for (var device in listDevice) {
subscribeTopics(device, from: from);
}
});
}
Future<void> subscribeTopics(DeviceResponse? deviceResponse,
{String? from}) async {
if (newMQTTclient != null &&
newMQTTclient!.connectionStatus!.state ==
MqttConnectionState.connected) {
String topicToSubscribe =
generateSlaveFromDeviceId(deviceId: deviceResponse!.deviceId!) +
newMqttSubscribeTopic;
debugPrint("NEW 🦟 MQTT2 🦟 TOPIC TO SUBSCRIBE --> $topicToSubscribe");
debugPrint(
"NEW 🦟 MQTT2 🦟 SUBSCRIPTIONS --> ${newMQTTclient!.subscriptionsManager!.subscriptions}");
if (newMQTTclient!.subscriptionsManager != null &&
newMQTTclient!.subscriptionsManager!.subscriptions
.containsKey(topicToSubscribe)) {
debugPrint(
"NEW 🦟 MQTT2 🦟 SUBSCRIBE ALREADY ACTIVE--> $topicToSubscribe");
sendDS(deviceResponse);
} else {
debugPrint(
"NEW 🦟 MQTT2 🦟 CURRENT SUBSCRIPTIONS--> ${newMQTTclient!.subscriptionsManager!.subscriptions}}");
newMQTTclient!.subscribe(topicToSubscribe, MqttQos.atMostOnce);
}
}
}
from mqtt_client.
OK but I still need a log as I said above, I need to see whats happening at run time.
from mqtt_client.
Okay, I got an issue and this time you don't need logs.
.....
mqttClient!.autoReconnect = true;
mqttClient!.onAutoReconnected = onAutoReconnected;
await mqttClient!.connect();
.....
I am using an app with Mobile and Wifi both in ON status and when I switch off the Wifi, the Network listener callback with No Internet and at that time I am doing client. disconnect()
and just after microseconds, I again got a callback from Network Listener is, Network is connected to Mobile and in that case, I am calling the function to connect to MQTT again.
I also got a connected event when I connect to MQTT again but I also got the event in the onAutoReconnected
function which is of 1st MQTT connection and just after that updates stopped working.
And so for a final solution, I set autoReconnect
as false and manually connect and disconnect when the network state changes.
ONE IMPORTANT THING IS,
WHY I AM GETTING EVENT IN onAutoReconnected
if I already did client. disconnect()
from mqtt_client.
from mqtt_client.
I'm not unerstanding you, why can't you use the onConnected and onDisconnected callbacks? Note the API comment from onDisconnected -
/// Client disconnect callback, called on unsolicited disconnect.
/// This will not be called even if set if [autoReconnect} is set,instead
/// [AutoReconnectCallback] will be called.
from mqtt_client.
from mqtt_client.
Please have a look at the API -
/// Client disconnect callback, called on unsolicited disconnect.
/// This will not be called even if set if [autoReconnect} is set,instead
/// [AutoReconnectCallback] will be called.
DisconnectCallback? onDisconnected;
/// Client connect callback, called on successful connect
ConnectCallback? onConnected;
/// Auto reconnect callback, if auto reconnect is selected this callback will
/// be called before auto reconnect processing is invoked to allow the user to
/// perform any pre auto reconnect actions.
AutoReconnectCallback? onAutoReconnect;
/// Auto reconnected callback, if auto reconnect is selected this callback will
/// be called after auto reconnect processing is completed to allow the user to
/// perform any post auto reconnect actions.
AutoReconnectCompleteCallback? onAutoReconnected;
If you hook these up(assuming you are using autoreconnect) then when onAutoReconnect is called then you can tell your user that they are disconnected until onAutoReconnected is called, similarly if you are not using autoreconnect for onDisconnected/onConnected.
from mqtt_client.
from mqtt_client.
Related Issues (20)
- retain:true publishing issue (using IoT Core) HOT 3
- Differences in automatic reconnection between IOS and Android HOT 1
- '400 Bad Request' response while connecting with websocket to rabbitmq HOT 3
- How to connect mqtt with socket header options? HOT 3
- mqttjs:client _checkPing :: checking ping... Runs twice in rapid succession some times HOT 1
- How to determine the cause of the disconnect? HOT 1
- Available bytes is less than the message size HOT 4
- error:Bad state: Cannot add new events after calling close HOT 8
- AWS IoT Certificate - Use .bks file certificate HOT 1
- NoConnectionException: Missing Connection Acknowledgement HOT 4
- Ping triggers client.update and brings the same message multiple times HOT 1
- How can I receive a complete offline message? HOT 1
- Unhandled Exception: mqtt-client::NoConnectionException: MqttWs2Connection::TLS connection unexpectedly closed HOT 15
- onDisconnect callback when autoconnect is false or onAutoReconnect callback when autoconnect is set to true not invoking immediately in ios when wifi is turned off HOT 2
- Review outdated packages in version 10.3.0 HOT 1
- Parsing problems for web socket URLs HOT 2
- How can i subscribe multi topic? HOT 2
- CERTIFICATE_VERIFY_FAILED: unable to get local issuer certificate HOT 4
- Dependency Resolution Failure after upgrading to 10.4.0 HOT 8
- Problems maintaining connection to AWS IoT MQTT broker: Connection was not upgraded to websocket HOT 11
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from mqtt_client.