Comments (6)
So, the regular MQTT.js examples more or less apply to async-mqtt. The main difference is that anywhere you see a callback in MQTT.js, you should instead use a Promise in async-mqtt.
A more complete example could look something like:
const MQTT = require("async-mqtt");
const client = MQTT.connect("tcp://somehost.com:1883");
// When passing async functions as event listeners, make sure to have a try catch block
const doStuff = async () => {
console.log("Starting");
try {
client.on('message', (topic, message) => console.log(topic, message);
await client.subscribe("wow/#");
await client.publish("wow/so/cool", "It works!");
// This line doesn't run until the server responds to the publish
await client.unsubscribe("wow/#");
await client.publish("wow/so/cool", "Won't show up since it's not subscribed!");
await client.end();
// This line doesn't run until the client has disconnected without error
console.log("Done");
} catch (e){
// Do something about it!
console.log(e.stack);
process.exit();
}
}
client.on("connect", doStuff);
from async-mqtt.
Would you be interested in submitting a PR with the examples by any chance?
from async-mqtt.
Well.. I surely would. But it's my first time with this lib... and as I failed so far in making sensible use..so far I can't. I thought maybe someone could drop some code what they have here. If I then take it on, I will be happy to submit PR))
from async-mqtt.
Thank you. My confusion came from the fact that doStuff
is called every few minutes: each time when server needs to reconnect after a time-out.
Appearantly that is by design and related to MQTT.js and not the async part.
Thanks!
from async-mqtt.
@RangerMauve I was trying your approach but somehow it skips the client.on("message" completely and just runs through the other await methods.
In our case we try to implement this in a chaincode with Hyperledger so it might be because of that. Our message is also a JSON object that is parsed and passed on to the smart contract within the client.on("message"). I know this is quite specific in regards to Blockchain but do you see anything that we did wrong here?
`console.log("connecting to broker");
const client = mqtt.connect("mqtt://192.168.43.217");
const run = async() =>{
console.log("Starting");
try {
client.on("message", (topic, message) =>{
var rfidPayload = JSON.parse(message.toString());
console.log(rfidPayload);
var carKeyIn = rfidPayload.carKey;
var renterIDIn = rfidPayload.renterID;
var timestampIn = rfidPayload.timestamp;
contract.submitTransaction('openCar', carKeyIn, renterIDIn, timestampIn);
return console.log('Transaction has been submitted');
});
await client.subscribe("rfidData");
console.log("Subscribed")
// This line doesn't run until the server responds to the publish
await client.end();
// This line doesn't run until the client has disconnected without error
console.log("Done");
} catch (e){
// Do something about it!
console.log(e.stack);
process.exit(2);
}
}
client.on("connect", run)`
from async-mqtt.
Is it that you'd like the message to be emitted before you continue on? When you invoke client.on('message')
, you're synchronously adding a callback which will get invoked asynchronously once the message has been sent from your broker.
I think all you'd need to change in your example is to invoke client.end() within your on('message')
callback instead of after subscribe()
since it would close the connection before getting messages otherwise.
e.g.
const run = async() =>{
console.log("Starting");
try {
client.on("message", (topic, message) =>{
var rfidPayload = JSON.parse(message.toString());
console.log(rfidPayload);
var carKeyIn = rfidPayload.carKey;
var renterIDIn = rfidPayload.renterID;
var timestampIn = rfidPayload.timestamp;
contract.submitTransaction('openCar', carKeyIn, renterIDIn, timestampIn);
console.log('Transaction has been submitted');
// This line doesn't run until the server responds to the publish
await client.end();
// This line doesn't run until the client has disconnected without error
console.log("Done");
});
await client.subscribe("rfidData");
console.log("Subscribed")
} catch (e){
// Do something about it!
console.log(e.stack);
process.exit(2);
}
}
client.on("connect", run)
from async-mqtt.
Related Issues (20)
- How to get message from mqtt in async way? HOT 2
- How to make client keep recieving message after subscribe to the topic? HOT 1
- MaxListenersExceededWarning: Possible EventEmitter memory leak detected. HOT 7
- TypeError: WS is not a constructor HOT 3
- connectAsync blocking, promise not rejecting when mqtt server is not running HOT 3
- publish options not working HOT 2
- New Release HOT 3
- Promise based RPC feature discussion HOT 3
- Await/Promise for receiving next message feature discussion HOT 3
- publish does not block or throw even if there is no Internet connection HOT 2
- How to use an broker SRV record to connect? HOT 1
- MQTT connection holds nodejs event loop open HOT 1
- TLS error not caught by error event HOT 3
- Call publish with QoS 2 but broker receive with 1. HOT 1
- glob-parent before 5.1.2 vulnerable to Regular Expression Denial of Service in enclosure regex HOT 3
- MQTT with TLS enabled causes a ECONNRESET when issuing await client.end() HOT 1
- passing certificate content instead of filepath HOT 2
- Buffer is not defined HOT 1
- How to catch errors like `access_refused` when using `client.publish` HOT 1
- MQTTjs v5 HOT 1
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 async-mqtt.