mqtt

// 開源sdk地址:https://github.com/mqttjs/MQTT.js
import { uuid } from "vue-uuid";
const mqtt = require("mqtt"); // uuid object is also exported to things

class Client {
  constructor() {
    this.endPoint = "..";
    this.accessKey = "";
    this.secretKey = "xxxx";
    this.groupId = "GID_123@@@";
    this.UUID = uuid.v1();

    this.clientId = this.groupId + this.UUID;
    this.instanceId = "";
    this.topic = "";

    this.token =
    this.username = "Token|" + this.accessKey + "|" + this.instanceId;
    this.password = "RW|" + this.token;
    this.options = {
      username: this.username,
      password: this.password,
      clientId: this.clientId,
      cleanSession: true,
      keepalive: 90,
      connectTimeout: 3000
    };
    this.client = null;
    this.messageMap = {};
  }

  // 建立鏈接
  MQTTconnect() {
    const client = mqtt.connect("tcp://" + this.endPoint + ":80", this.options);
    this.client = client;
    client.on("connect", () => {
      this.onConnect();
    });
    client.on("message", (topic, message) => this.onMessage(topic, message));
    client.on("error", error => {
      this.onError(error);
    });
  }

  // 建立連接成功
  onConnect() {
    this.onReceiver({ Event: "open" });
  }

  // 收到消息
  onMessage(topic, message) {
    // console.log(topic, message);
    const mqttdata = JSON.parse(this.unzip(message));
    if (mqttdata.code === 0) {
      const params = {
        topic: topic,
        data: mqttdata.data
      };
      // console.log(params);

      this.onReceiver({ Event: "message", Data: params });
    }
  }

  // 訂閱消息
  subscibe(topic) {
    this.client.subscribe(topic, { qos: 2 });
  }

  // 取消訂閱
  unsubscibe(topic) {
    console.log("取消訂閱" + topic);

    this.client.unsubscribe(topic);
  }

  // 關(guān)閉mqtt
  end() {
    this.client.end({ force: true });
  }

  // 自定義監(jiān)聽
  on(name, handler) {
    this.messageMap[name] = handler;
  }

  // 錯誤信息
  onError(error) {
    console.log(error);
  }

  // 回調(diào)數(shù)據(jù)
  onReceiver(data) {
    const callback = this.messageMap[data.Event];
    if (callback) callback(data.Data);
  }

  // 解壓方法
  unzip(b64Data) {
    var strData = atob(b64Data);
    // Convert binary string to character-number array
    var charData = strData.split("").map(function(x) {
      return x.charCodeAt(0);
    });
    // Turn number array into byte-array
    var binData = new Uint8Array(charData);
    // // unzip
    // eslint-disable-next-line no-undef
    var data = pako.inflate(binData);
    // Convert gunzipped byteArray back to ascii string:
    // strData   = String.fromCharCode.apply(null, new Uint16Array(data));
    var array = new Uint16Array(data);
    var res = "";
    var chunk = 8 * 1024;
    var i;
    for (i = 0; i < array.length / chunk; i++) {
      res += String.fromCharCode.apply(
        null,
        array.slice(i * chunk, (i + 1) * chunk)
      );
    }
    res += String.fromCharCode.apply(null, array.slice(i * chunk));

    strData = res;
    return strData;
  }
}
export default Client;

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市泰涂,隨后出現(xiàn)的幾起案子状原,更是在濱河造成了極大的恐慌剥哑,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,110評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件堕汞,死亡現(xiàn)場離奇詭異但狭,居然都是意外死亡税课,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,443評論 3 395
  • 文/潘曉璐 我一進(jìn)店門端壳,熙熙樓的掌柜王于貴愁眉苦臉地迎上來告丢,“玉大人,你說我怎么就攤上這事损谦♂猓” “怎么了岳颇?”我有些...
    開封第一講書人閱讀 165,474評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長颅湘。 經(jīng)常有香客問我话侧,道長,這世上最難降的妖魔是什么闯参? 我笑而不...
    開封第一講書人閱讀 58,881評論 1 295
  • 正文 為了忘掉前任瞻鹏,我火速辦了婚禮,結(jié)果婚禮上赢赊,老公的妹妹穿的比我還像新娘乙漓。我一直安慰自己,他們只是感情好释移,可當(dāng)我...
    茶點故事閱讀 67,902評論 6 392
  • 文/花漫 我一把揭開白布叭披。 她就那樣靜靜地躺著,像睡著了一般玩讳。 火紅的嫁衣襯著肌膚如雪涩蜘。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,698評論 1 305
  • 那天熏纯,我揣著相機與錄音同诫,去河邊找鬼。 笑死樟澜,一個胖子當(dāng)著我的面吹牛误窖,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播秩贰,決...
    沈念sama閱讀 40,418評論 3 419
  • 文/蒼蘭香墨 我猛地睜開眼霹俺,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了毒费?” 一聲冷哼從身側(cè)響起丙唧,我...
    開封第一講書人閱讀 39,332評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎觅玻,沒想到半個月后想际,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,796評論 1 316
  • 正文 獨居荒郊野嶺守林人離奇死亡溪厘,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,968評論 3 337
  • 正文 我和宋清朗相戀三年胡本,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片畸悬。...
    茶點故事閱讀 40,110評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡打瘪,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情闺骚,我是刑警寧澤彩扔,帶...
    沈念sama閱讀 35,792評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站僻爽,受9級特大地震影響虫碉,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜胸梆,卻給世界環(huán)境...
    茶點故事閱讀 41,455評論 3 331
  • 文/蒙蒙 一敦捧、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧碰镜,春花似錦兢卵、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,003評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至柠横,卻和暖如春窃款,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背牍氛。 一陣腳步聲響...
    開封第一講書人閱讀 33,130評論 1 272
  • 我被黑心中介騙來泰國打工晨继, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人搬俊。 一個月前我還...
    沈念sama閱讀 48,348評論 3 373
  • 正文 我出身青樓紊扬,卻偏偏與公主長得像,于是被迫代替她去往敵國和親唉擂。 傳聞我的和親對象是個殘疾皇子珠月,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,047評論 2 355