index.js 6.72 KB
Newer Older
李纪文's avatar
李纪文 committed
1 2 3
import React, { useEffect } from 'react';
import MqttClient from 'mqtt-client';
import PropTypes from 'prop-types';
4
import CryptoJS from 'crypto-js';
李纪文's avatar
李纪文 committed
5 6
class MqttView {
  constructor(props) {
7 8
    this.userName = props.userName;
    this.password = props.password;
李纪文's avatar
李纪文 committed
9 10 11 12 13 14 15
    this.mqttIP = props.mqttIP;
    this.mqttPath = props.mqttPath;
    this.mqttSsl = props.mqttSsl;
    this.siteCode = props.siteCode;
    this.devices = props.devices;
    this.callback = props.callback;
    this.controlback = props.controlback;
16
    this.alarmback = props.alarmback;
17
    this.params = props.params || {};
18
    this.isAlarm = props.isAlarm || false;
李纪文's avatar
李纪文 committed
19 20 21 22 23 24 25 26 27 28 29 30 31
    this.flag = false;
  }

  //Mqtt第一步
  saveWaterMqtt() {
    const hostname = this.mqttIP.split(':')[0],
      port = this.mqttIP.split(':')[1] * 1,
      clientId = 'PandaWeb-' + this.createGuid(),
      timeout = 50,
      keepAlive = 60,
      cleanSession = true,
      ssl = this.mqttSsl,
      path = this.mqttPath,
32 33
      userName = this.userName || 'admin',
      password = this.password ? getDecryptedValue(this.password) : 'public';
34
    const queryStr = this.toQueryString(this.params);
李纪文's avatar
李纪文 committed
35
    this.saveWaCount = 0;
36 37 38
    this.saveWaClient = new MqttClient.Client(
      hostname,
      port,
39
      `${path}?_site=${this.siteCode}${queryStr ? '&' + queryStr : ''}`,
40 41
      clientId,
    );
李纪文's avatar
李纪文 committed
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
    this.saveWaOptions = {
      invocationContext: {
        host: hostname,
        port: port,
        path: path,
        clientId: clientId,
      },
      timeout: timeout,
      keepAliveInterval: keepAlive,
      cleanSession: cleanSession,
      useSSL: ssl,
      userName: userName,
      password: password,
      onSuccess: this.onSaveWaConnect.bind(this),
      onFailure: function (e) {
        console.log(e);
      },
    };
    //注册连接断开处理事件
    this.saveWaClient.onConnectionLost = this.onSaveWaConnectionLost.bind(this);
    //注册消息接收处理事件
    this.saveWaClient.onMessageArrived = this.onSaveWaMessageArrived.bind(this);
    this.saveWaClient.connect(this.saveWaOptions);
  }

  //消息接收方法
  onSaveWaMessageArrived(message) {
    this.onMessageArrived(message, 'saveWaType');
  }

  //主题建立连接
  onSaveWaConnect() {
    this.flag = true;
    this.devices.forEach((item) => {
      if (item) {
        var saveWaTopic = this.siteCode + '/' + item.replace(/[#+]/g, '@');
        this.saveWaClient.subscribe(saveWaTopic);
      }
    });
    this.devices.forEach((item) => {
      if (item) {
        this.saveWaClient.subscribe(
          'callback/control/' + this.siteCode + '/' + item.replace(/[#+]/g, '@') + '/#',
        );
      }
    });
88 89 90 91 92 93 94
    this.isAlarm &&
      this.devices.forEach((item) => {
        if (item) {
          var saveWaTopic = this.siteCode + '/' + item.replace(/[#+]/g, '@') + '/alarm' + '/#';
          this.saveWaClient.subscribe(saveWaTopic);
        }
      });
李纪文's avatar
李纪文 committed
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
  }

  //主题断开连接
  disSaveWaconnect() {
    if (this.saveWaClient) {
      this.flag = false;
      // this.saveWaClient.disconnect();
      if (this.saveWaClient.isConnected()) this.saveWaClient.disconnect();
      if (this.saveWatester) {
        clearInterval(this.saveWatester);
        this.saveWatester = null;
      }
    }
  }

  //主题掉线重连接
  onSaveWaConnectionLost() {
    if (this.flag) this.saveWaClient.connect(this.saveWaOptions);
    this.saveWatester = setInterval(() => {
      if (this.saveWaClient.isConnected()) {
        clearInterval(this.saveWatester);
        this.saveWatester = null;
      } else {
        this.saveWaClient.connect(this.saveWaOptions);
      }
    }, 1000);
  }

李纪文's avatar
李纪文 committed
123
  //消息接收(控制和订阅)
李纪文's avatar
李纪文 committed
124 125 126 127 128 129 130
  onMessageArrived(message, infoType) {
    var topic = message.topic;
    var code = topic.split('/')[topic.split('/').length - 1];
    if (topic.indexOf('callback/control/' + this.siteCode) > -1) {
      this.controlback(message.payloadString, code, topic);
      return false;
    }
131 132 133 134 135
    if (topic.indexOf('alarm') > -1) {
      var alarmCode = topic.split('/')[1];
      this.alarmback(message.payloadString, alarmCode, topic);
      return false;
    }
李纪文's avatar
李纪文 committed
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
    this.callback(message.payloadString, code, topic);
  }

  //消息发送
  onSendWaMessageArrived(
    userName,
    password,
    callbackGuid,
    devicecode,
    tag,
    type,
    val,
    controlMode,
  ) {
    var info = {
      userName: userName,
      password: password,
      callbackGuid: callbackGuid,
      type: '',
      operateType: type,
      controlValue: val || String(val) != '' ? val : '',
      sitecode: this.siteCode,
      devicecode: devicecode,
      controlMode: controlMode ? controlMode : '',
      tag: tag,
    };
162
    var message = new MqttClient.Message(JSON.stringify(info));
李纪文's avatar
李纪文 committed
163 164 165 166 167 168 169 170 171 172 173 174 175 176
    message.destinationName = 'setdata/' + this.siteCode + '/' + devicecode;
    this.saveWaClient.send(message);
  }

  //生成GUID
  createGuid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
      .replace(/[xy]/g, function (c) {
        var r = (Math.random() * 16) | 0,
          v = c == 'x' ? r : (r & 0x3) | 0x8;
        return v.toString(16);
      })
      .toUpperCase();
  }
177 178 179 180 181 182 183

  // 转为url参数
  toQueryString(obj) {
    return Object.keys(obj)
      .map((key) => encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]))
      .join('&');
  }
李纪文's avatar
李纪文 committed
184 185 186
}

MqttView.propTypes = {
187 188
  userName: PropTypes.string,
  password: PropTypes.string,
李纪文's avatar
李纪文 committed
189 190 191 192 193
  mqttIP: PropTypes.string,
  mqttPath: PropTypes.string,
  mqttSsl: PropTypes.bool,
  siteCode: PropTypes.string,
  devices: PropTypes.array,
194
  params: PropTypes.object,
195
  isAlarm: PropTypes.bool,
李纪文's avatar
李纪文 committed
196 197
  callback: PropTypes.func,
  controlback: PropTypes.func,
198
  alarmback: PropTypes.func,
李纪文's avatar
李纪文 committed
199 200 201
};

MqttView.defaultProps = {
202 203
  userName: 'admin',
  password: 'public',
李纪文's avatar
李纪文 committed
204 205 206 207 208
  mqttIP: '',
  mqttPath: '/mqtt',
  mqttSsl: false,
  siteCode: '',
  devices: [],
209
  params: {},
210
  isAlarm: false,
李纪文's avatar
李纪文 committed
211 212
  callback: () => {},
  controlback: () => {},
213
  alarmback: () => {},
李纪文's avatar
李纪文 committed
214 215
};

216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
// 解密
export const getDecryptedValue = (encryptedText) => {
  const AESKey = '1p2a3n4d5a6o7m8s9a10n1e2t3c4o5re'; //32位
  const AES_IV = '1234567890000000'; //16位
  const key = CryptoJS.enc.Utf8.parse(AESKey);
  const iv = CryptoJS.enc.Utf8.parse(AES_IV);

  // 解密
  const decrypted = CryptoJS.AES.decrypt(
    { ciphertext: CryptoJS.enc.Hex.parse(encryptedText) },
    key,
    { iv: iv },
  );
  // 转换为明文
  const plaintext = decrypted.toString(CryptoJS.enc.Utf8);

  return plaintext;
};

// 加密
export const getEncryptedValue = (password) => {
  const AESKey = '1p2a3n4d5a6o7m8s9a10n1e2t3c4o5re'; //32位
  const AES_IV = '1234567890000000'; //16位
  const key = CryptoJS.enc.Utf8.parse(AESKey);
  const iv = CryptoJS.enc.Utf8.parse(AES_IV);

  const psd = CryptoJS.AES.encrypt(password, key, { iv: iv })
    .ciphertext.toString(CryptoJS.enc.Hex)
    .toUpperCase();

  return psd;
};

李纪文's avatar
李纪文 committed
249
export default MqttView;