How to use the mqtt.connect function in mqtt

To help you get started, we’ve selected a few mqtt examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github thingsboard / thingsboard.github.io / docs / user-guide / rule-engine-2-0 / tutorials / resources / RotatingSystemEmulator.js View on Github external
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;
github aerogear / ionic-showcase / server / src / subscriptions.js View on Github external
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()
github eclipse / thingweb.node-wot / packages / binding-mqtt / src / mqtt-client.ts View on Github external
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);
github intel / intel-iot-services-orchestration-layer / node_modules / hope-message / impl_broker_clients / mqtt.js View on Github external
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);
      }
    });
  });
};
github svrooij / ipcam2mqtt / src / server.js View on Github external
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()
github mqttjs / async-mqtt / index.js View on Github external
connectAsync (brokerURL, opts, allowRetries=true) {
    const client = mqtt.connect(brokerURL, opts);
    const asyncClient = new AsyncClient(client);

    return new Promise((resolve, reject) => {
      // Listeners added to client to trigger promise resolution
      const promiseResolutionListeners = {
        connect: (connack) => {
          removePromiseResolutionListeners();
          resolve(asyncClient);   // Resolve on connect
        },
        end: () => {
          removePromiseResolutionListeners();
          resolve(asyncClient);   // Resolve on end
        },
        error: (err) => {
          removePromiseResolutionListeners();
          client.end();
github confluentinc / training-developer-src / labs / create-producer-node / server.js View on Github external
const mqtt = require('mqtt');

///journey////////////
const topic = '/hfp/v1/journey/ongoing/+/+/+/+/+/+/+/+/+/#';

const client  = mqtt.connect('mqtts://mqtt.hsl.fi:8883');

client.on('connect', function () {
  client.subscribe(topic);
  console.log('Connected');
});
 
let count = 0;

client.on('message', function (topic, message) {
    const vehicle_position = JSON.parse(message).VP;

    //Skip vehicles with invalid location
    if (!vehicle_position.lat || !vehicle_position.long) {
      return;
    }
github bigclownlabs / bch-playground / src / render / model / MqttLog.js View on Github external
connect(url) {
        if (this._url == url) return;

        if (this.mqttConnect) {
            this.client.end(true);
            this.mqttConnect = false;
        }

        this._url = url;

        this.client = mqtt.connect(this._url);

        this.client.on("connect", () => {
            this._connect = true;
            this.emit("connect", true);

            for (let i in this._subscribed) {
                this.client.subscribe(this._subscribed[i]);
            }
        });

        this.client.on("disconnect", () => {
            this._connect = false;
            this.emit("connect", false);
        });

        this.client.on("message", (topic, data) => {
github workswithweb / MQTTBox / src / app / workers / ClientConnection.js View on Github external
this.publishBrokerStatus(AppConstants.ONLINE);
            }.bind(this));

            this.client.on('close', function () {
                this.publishBrokerStatus(AppConstants.OFFLINE);
            }.bind(this));

            this.client.on('offline', function () {
                this.publishBrokerStatus(AppConstants.OFFLINE);
            }.bind(this));

            this.client.on('error', function (err) {
                this.publishBrokerStatus(AppConstants.OFFLINE);
            }.bind(this));

            this.client.on('message', function (topic, message,packet) {
                var topics = _.uniq(this._matcher.match(topic));
                if(message!=null && topics!=null && topics.length>0) {
                    for(var i=0;i
github aliyun / alibabacloud-iot-device-sdk / src / thing.js View on Github external
_createClient() {
    this._mqttClient = mqtt.connect(this.model.brokerUrl, this.model.genConnectPrarms());
  }