Cloud Defense Logo

Products

Solutions

Company

Book A Live Demo

Top 10 Examples of "mqtt in functional component" in JavaScript

Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'mqtt' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.

var facet = require("../lib/facet");
var mqtt = require("mqtt");

var basic = require("../lib/meems/basic");

var namespaces = {
		"basic" : basic
};

// test creating

console.log("ccreating BinaryScheduler");
var binaryScheduler = new basic.BinaryScheduler({});

// test the MeemFactory
var mqttClient = mqtt.createClient(1883, '192.168.0.23');
var meemBus = new MeemBus(mqttClient);
var mf = new MeemFactory(namespaces, meemBus);

console.log("using factory to create BinaryTimer");

var properties = {};
var meemDef = {
		id : "123456789ABCDEF",
		type: "basic.BinaryTimer",
		properties: properties,
};

var meem = mf.create(meemDef);
var mqtt = require('mqtt');

// Don't forget to update accessToken constant with your device access token
const thingsboardHost = "demo.thingsboard.io";
const ACCESS_TOKEN = "jSuvzrURCbw7q4LGtygc";
const minDirection = 0, maxDirection = 360;


// Initialization of mqtt client using Thingsboard host and device access token
console.log('Connecting to: %s using access token: %s', thingsboardHost, ACCESS_TOKEN);
var client  = mqtt.connect('mqtt://'+ thingsboardHost, { username: ACCESS_TOKEN });

var value = 350;
var spinFlag = {method: "spinRight", params: 0};

//RPC message handling sent to the client
client.on('message', function (topic, message) {
    console.log('request.topic: ' + topic);
    console.log('request.body: ' + message.toString());
    var tmp = JSON.parse(message.toString());
    if (tmp.method == "spinRight") {
        spinFlag = tmp;
        // Uploads telemetry data using 'v1/devices/me/telemetry' MQTT topic
        client.publish('v1/devices/me/telemetry', JSON.stringify({spinFlag: "rotating right"}));
    }
    if (tmp.method == "spinLeft") {
        spinFlag = tmp;
function getPubSub() {
  const mqttHost = process.env.MQTT_HOST

  if (mqttHost) {
    console.log('Using MQTT PubSub')
    const mqttOptions = {
      host: mqttHost,
      servername: mqttHost, // needed to work in OpenShift. Lookup SNI.
      username: process.env.MQTT_USERNAME || '',
      password: process.env.MQTT_PASSWORD || '' ,
      port: process.env.MQTT_PORT || '1883',
      protocol: process.env.MQTT_PROTOCOL || 'mqtt',
      rejectUnauthorized: false
    }
  
    const client = mqtt.connect(mqttHost, mqttOptions)
  
    console.log(`attempting to connect to messaging service ${mqttHost}`)
  
    client.on('connect', () => {
      console.log('connected to messaging service')
    })
  
    client.on('error', (error) => {
      console.log('error with mqtt connection')
      console.log(error)
    })

    return new MQTTPubSub({ client })
  }
  console.log('Using In Memory PubSub')
  return new PubSub()
public subscribeResource(form: MqttForm, next: ((value: any) => void), error?: (error: any) => void, complete?: () => void): any {

        // get MQTT-based metadata
        let contentType = form.contentType;
        let retain = form["mqtt:retain"]; // TODO: is this needed here?
        let qos = form["mqtt:qos"]; // TODO: is this needed here?
        let requestUri = url.parse(form['href']);
        let topic = requestUri.pathname;
        let brokerUri : String = "mqtt://"+requestUri.host;

        if(this.client==undefined) {
            this.client = mqtt.connect(brokerUri)
        }

        this.client.on('connect', () => this.client.subscribe(topic))
        this.client.on('message', (receivedTopic : string, payload : string, packet: IPublishPacket) => {
            console.log("Received MQTT message (topic, data): (" + receivedTopic + ", "+ payload + ")");
            if (receivedTopic === topic) {
                next({ contentType: contentType, body: Buffer.from(payload) });
            }
        })
        this.client.on('error', (error :any)  => {
            if (this.client) {
                this.client.end();
            }
            this.client == undefined;
            // TODO: error handling
            error(error);
// Handle MQTT Messages
  try{

    var mqttConfig = config.mqtt || {};
    var mqttsettings = {
      keepalive: 1000, // seconds
      protocolId: 'MQIsdp',
      protocolVersion: 3,
      //clientId: 'skynet',
      username: 'skynet',
      password: process.env.MQTT_PASS || mqttConfig.skynetPass
    };
    var mqttPort = process.env.MQTT_PORT || mqttConfig.port || 1833;
    var mqttHost = process.env.MQTT_HOST || mqttConfig.host || 'localhost';
    client = mqtt.createClient(mqttPort, mqttHost, mqttsettings);
  } catch(e){
    console.error('no mqtt server found', e);
  }

  return client;

};
WemoBinaryMqtt.prototype.init = function(options) {
	var self = this;
	
	if (TRACE) {
		console.log("initialise MQTT connection");
	}
	
	var clientId = crypto.randomBytes(24).toString("hex");
	
	// connect to MQTT service
	this.mqttClient = mqtt.createClient(options.port, options.host, {
		keepalive: 10000,
		client : clientId
	});
	
	// add handlers to MQTT client
	this.mqttClient.on('connect', function() {
		if (TRACE) {
			console.log('MQTT sessionOpened');
		}
		self.subscribe();	// subscribe to control and request topics
	});
	this.mqttClient.on('close', function() {
		if (TRACE) {
			console.log('MQTT close');
		}
	});
var mqtt = require("mqtt")
  , request = require("superagent")
  , total = 500
  , sent = 0
  , received = 0
  , listener = mqtt.createClient()
  , print = function(text) {
              process.stdout.write(text + "\n");
            }
  , start = null
  , publish = function() {
                  console.error("client connected, sending the message");
                  start = Date.now();
                  
                  for (i = 0; i < total; i++)
                    request
                        .put('http://localhost:3000/topics/hello')
                        .send("world")
                        .end(function(error, res){
                          //if (sent++ % (total / 10)) {
                          //  console.error("sent", sent)
                          //}
console.log('using websockets, will connect to \'' + url + '\'...');
         }

         options.url = url;
      } else if (protocol === 'wss-custom-auth') {
         options.url = prepareWebSocketCustomAuthUrl(options);
         if (options.debug === true) {
            console.log('using websockets custom auth, will connect to \'' + options.url + '\'...');
         }
         // Treat the request as a standard websocket request from here onwards
         protocol = 'wss';
      }
      return protocols[protocol](client, options);
   }

   var device = new mqtt.MqttClient(_wrapper, options);

   //handle events from the mqtt client

   //
   // Timeout expiry function for the connection timer; once a connection
   // is stable, reset the current reconnection time to the base value. 
   //
   function _markConnectionStable() {
      currentReconnectTimeMs = baseReconnectTimeMs;
      device.options.reconnectPeriod = currentReconnectTimeMs;
      //
      // Mark this timeout as expired
      //
      connectionTimer = null;
      connectionState = 'stable';
   }
return new Promise(function(resolve, reject) {
    if (self.status !== "disconnected") {
      reject("MQTT broker client should be disconnected before it connects");
      return;
    }
    self.status = "connecting";
    var timer = setTimeout(function() {
      log.error("connect", "Timeout to connect to", self.mnode.id, self.config.url, self.mqtt_config);
      reject("Timeout to connect to MQTT with url " + self.config.url);
    }, 10000);
    self.client = mqtt.connect(self.config.url, self.mqtt_config);
    self.client.on("connect", function() {  // this might be triggered upon REconnection
      if (self.status !== "connected") {
        log("connect", "connected", self.mnode.id, self.config.url, self.mqtt_config);
        self.status = "connected";
        clearTimeout(timer);
        self.client.on("error", function(err) {
          log.error("error event", err, "for", self.config.url, self.mqtt_config);
        });
        self.client.on("message", function(t, m) {
          self.handle_message(m);
        });
        resolve(self);
      }
    });
  });
};
function start () {
  log.setLevel(config.logging)
  log.info(pkg.name + ' ' + pkg.version + ' starting')

  const mqttOptions = { will: {
    topic: config.name + '/connected',
    message: 0,
    qos: 0
  } }

  client = mqtt.connect(config.mqtt, mqttOptions)
  setupMqttLogging()

  // Create root dir for uploads
  fs.access(tempdir, fs.constants.R_OK, (err) => {
    if (err) {
      fs.mkdir(tempdir, (err2) => {
        if (err2) { throw err2 }
        setupFtp()
      })
    } else {
      setupFtp()
    }
  })

  process.on('SIGINT', function () {
    server.close()

Is your System Free of Underlying Vulnerabilities?
Find Out Now