Git Product home page Git Product logo

Comments (6)

RangerMauve avatar RangerMauve commented on June 29, 2024 2

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.

RangerMauve avatar RangerMauve commented on June 29, 2024

Would you be interested in submitting a PR with the examples by any chance?

from async-mqtt.

tvld avatar tvld commented on June 29, 2024

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.

tvld avatar tvld commented on June 29, 2024

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.

sopoour avatar sopoour commented on June 29, 2024

@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.

RangerMauve avatar RangerMauve commented on June 29, 2024

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)

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.