Stripped out JavaScript MQTT module that does basic PUB/SUB, by @olliephillips. Espruino also contains a more complete MQTT module , but it uses substantially (3x) more memory.
Using the Espruino Web IDE you can just require the module directly:
var mqtt = require("tinyMQTT");
var mqtt = require("tinyMQTT").create(server);
mqtt.connect(); // Connects on default port of 1883
var mqtt = require("tinyMQTT").create(server, {
username: "username",
password: "password",
port: 8883
});
mqtt.connect();
var mqtt = require("tinyMQTT").create("test.mosquitto.org");
mqtt.on("connected", function(){
mqtt.subscribe("espruino/test");
});
mqtt.on("message", function(msg){
console.log(msg.topic);
console.log(msg.message);
});
mqtt.on("published", function(){
console.log("message sent");
});
mqtt.on("disconnected", function(){
console.log("disconnected");
});
var wifi = require("Wifi");
wifi.connect("username", {password:"mypassword"}, function(){
mqtt.connect();
});
If you want to reconnect in event of broker disconnection or wifi outage add mqtt.connect();
to the disconnected event listener. Reconnection will be attempted indefinitely, by default at 2 second intervals (though this can be configured). Once reconnected publishing should restart, and subscriptions will be honoured.
mqtt.on("disconnected", function(){
console.log("disconnected");
mqtt.connect();
});
tinyMQTT only supports short messages. The length of the topic plus the length of the payload must be less than 128 characters. If it's longer, the library throws a tMQTT-TL
exception.
@gfwilliams, @tve, @HyGy, @MaBecker, @gulfaraz, @The-Futur1st, @wanglingsong and @AkosLukacs. Thanks for the advice, tips, testing and pull requests!
This page is auto-generated from GitHub. If you see any mistakes or have suggestions, please let us know.