UNPKG

mqttjs-mongeriot

Version:

A javascript library that allows you to send mqtt commands to an mqtt server.

41 lines (35 loc) 1.43 kB
import Paho from "paho-mqtt"; // What we need to send this command is array of devices, array of commands. In array of commands we need the action and the value/parameter class mqttCommandEmitter { sendMultiCommands(items, commands, connectionAddress, port) { let clientID = "clientID_" + parseInt(Math.random() * 100); let client = new Paho.Client(connectionAddress, Number(port), clientID); client.connect({ onSuccess: onMultiCommandsConnect }); function onMultiCommandsConnect() { for (let d = 0; d < items.length; d++) { let topic = `${items[d]}`; client.subscribe(topic); for (let c = 0; c < commands.length; c++) { let value = !commands[c].value; let message = `${commands[c]}:${value}`; client.publish(topic, message); } } } } sendCommand(item, commands, connectionAddress, port) { let clientID = "clientID_" + parseInt(Math.random() * 100); let client = new Paho.Client(connectionAddress, Number(port), clientID); client.connect({ onSuccess: onSingleCommandConnect }); function onSingleCommandConnect() { let topic = `${item}`; client.subscribe(topic); for (let c = 0; c < commands.length; c++) { let value = !commands[c].value; let message = `${commands[c]}:${value}`; client.publish(topic, message); } } } } export default mqttCommandEmitter;