SHARE
TWEET

Untitled

a guest Oct 10th, 2019 125 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const mqtt = require("mqtt");
  2. const initCassandra = require("./cassandra");
  3. const uuidV4 = require("uuid/v4");
  4.  
  5. const WebSocket_URL = "ws://localhost:8083/mqtt";
  6.  
  7. // TCP/TLS connect url
  8. // const TCP_URL = "mqtt://localhost:1883";
  9. // const TCP_TLS_URL = "mqtts://localhost:8883";
  10.  
  11. const options = {
  12.   connectTimeout: 4000,
  13.  
  14.   // Authentication
  15.   clientId: "emqx_123",
  16.   // username: 'emqx',
  17.   // password: 'emqx',
  18.  
  19.   keepalive: 60,
  20.   clean: false
  21. };
  22.  
  23. const client = mqtt.connect(WebSocket_URL, options);
  24. const cassandra = initCassandra();
  25.  
  26. const messagePayload = "This is message payload";
  27.  
  28. try {
  29.   // after connect
  30.   client.on("connect", () => {
  31.     console.log("Connected to", WebSocket_URL);
  32.  
  33.     client.subscribe("hello", { qos: 1 }, err => {
  34.       console.log(err || "Subscribe Success");
  35.       // if (!err) {
  36.       //     cosnole.log('Subscribe Success')
  37.       //     client.publish('hello', 'Hello EMQ X', { qos: 1, rein: false }, (error) => {
  38.       //         console.log(error || 'Publish Success')
  39.       //     })
  40.       // }
  41.     });
  42.  
  43.     client.publish("hello", messagePayload, { qos: 1 }, err => {
  44.       console.log(err || "Publish Success");
  45.  
  46.       const payload = JSON.stringify({
  47.         id: uuidV4(),
  48.         message: messagePayload
  49.       });
  50.  
  51.       //   console.log(payload)
  52.       cassandra.execute(`INSERT INTO hello.chat JSON '${payload}'`);
  53.     });
  54.   });
  55.  
  56.   // // handle message event
  57.   client.on("message", (topic, message) => {
  58.     console.log("Received from", topic, ":", message.toString());
  59.     // console.log(message.toString());
  60.     let messagePayload = JSON.parse(message.toString());
  61.  
  62.     // const payload = JSON.stringify({
  63.     //   id: uuidV4(),
  64.     //   message: messagePayload.msg
  65.     // });
  66.  
  67.     // //   console.log(payload)
  68.     // cassandra.execute(`INSERT INTO hello.chat JSON '${payload}'`);
  69.     // disconnect
  70.     // client.end();
  71.   });
  72.  
  73.   client.on("reconnect", error => {
  74.     console.log("reconnecting:", error);
  75.   });
  76.  
  77.   client.on("error", error => {
  78.     console.log("Connect Error:", error);
  79.   });
  80. } catch (err) {
  81.   console.log("ERROR ==> ", err);
  82. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top