通信模块

import Vue from 'vue'
import $router from '../router'
import $store from '../store'
import { core_md5 } from '../plugins/md5.js'
import UUID from 'uuid-js'

var CRC32Table = [
  0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
  0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
  0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
  0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
  0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
  0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
  0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,
  0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
  0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,
  0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
  0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,
  0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
  0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,
  0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
  0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
  0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
  0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,
  0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
  0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,
  0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
  0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
  0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
  0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,
  0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
  0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
  0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
  0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,
  0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
  0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,
  0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
  0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,
  0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
  0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,
  0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
  0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
  0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
  0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,
  0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
  0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,
  0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
  0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,
  0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
  0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
];

function CRC32(u8) {
  if (u8 == null || !(u8 instanceof Uint8Array) || u8.byteLength == 0)
    return 0;
  var i, crc = 0xffffffff;
  for (i = 0; i < u8.byteLength; i++)
    crc = CRC32Table[(crc & 0xff) ^ u8[i]] ^ (crc >>> 8);
  return new Uint32Array([crc])[0];
}

function Pad4Bytes(size) {
  const left = size & (4 - 1);
  return left ? (size + 4 - left) : size;
}

// blob 可以是一个 File 实例
function blob2str(blob, callback) {
  var reader = new FileReader();
  reader.onload = function (e) {
    callback(reader.result);
  };
  reader.readAsText(blob, "utf-8");
}

function blob2ab(blob, callback) {
  var reader = new FileReader();
  reader.onload = function (e) {
    callback(reader.result);
  };
  reader.readAsArrayBuffer(blob);
}

// 数据封装成blob
function Pack(arr, callback) {
  if (!(arr instanceof Array)) {
    console.log("arr isn't Array");
    return false;
  }
  if (arr.length == 0) {
    console.log("arr length is 0");
    return false;
  }

  var content = [];
  for (var i = 0; i < arr.length; i++) {
    var data = null;
    if ((typeof arr[i] != 'string') && !(arr[i] instanceof Blob)) { 	//如果不是字符串也不是Blob则是json对象,需转换成字符串
      try {
        var str = JSON.stringify(arr[i]);
        data = new Blob([str]);
      } catch (e) {
        console.log("error: " + e);
        return false;
      }
    } else {
      data = new Blob([arr[i]]);
    }
    var len = new Uint32Array(1);
    len[0] = data.size;
    var left = len[0] & (4 - 1);
    var pad = 4 - left;
    content.push(new Blob([len]));
    content.push(data);
    if (left > 0) {
      switch (pad) {  //以空格填充补充到4字节对齐
        case 1: content.push(new Blob([" "])); break;
        case 2: content.push(new Blob(["  "])); break;
        case 3: content.push(new Blob(["   "])); break;
      }
    }
  }

  var blob = new Blob(content);
  blob2ab(blob, function (ab) {
    var u8 = new Uint8Array(ab);
    var header = new Uint32Array(2);
    var crc32 = CRC32(u8);
    var CRC32_LEN_BYTES = 4;
    header[0] = CRC32_LEN_BYTES + u8.byteLength;   //packSize, 4 bytes
    header[1] = crc32;  //CRC32, 4 bytes
    var pack = new Blob([header, blob]);
    callback(pack);
  });
  return true;
}

function Send(ws, arr) {
  if (!(ws instanceof WebSocket) || ws.readyState != WebSocket.OPEN) {
    console.log("ws isn't instanceof WebSocket&nbs***bsp;the readyState of ws isn't OPEN!");
    return false;
  }

  return Pack(arr, function (pack) {
    ws.send(pack);
  });
}

function Parse(blob, callback) {
  if (!(blob instanceof Blob) || typeof callback != 'function') {
    console.log("the argument of function Parse is invalid, they must be called like this: Parse(Blob, function(Array))");
    return;
  }
  var PACK_LEN_BYTES = 4;
  var CRC32_LEN_BYTES = 4;
  var FRAME_LEN_BYTES = 4;
  var arr = [];
  var data = [];
  var i = 0;

  function str2json(str) {
    try {
      arr.push(str);
      if (arr.length < data.length) {
        blob2str(data[i++], str2json);
      } else {
        callback(arr);
      }
    } catch (e) {
      console.log("convert to JSON fail, str is " + str);
    }
  }

  blob2ab(blob.slice(0, PACK_LEN_BYTES), function (ab) {
    var packSize = new Uint32Array(ab);
    if (packSize[0] + PACK_LEN_BYTES != blob.size) {
      console.log("pack size check fail, packSize = " + packSize[0] + ", blob.size = " + blob.size);
      return;
    }

    var content = blob.slice(PACK_LEN_BYTES, blob.size);
    blob2ab(content, function (ab) {
      //检验MD5
      var crc32 = new Uint32Array(ab, 0, CRC32_LEN_BYTES)[0];
      if (crc32 != CRC32(new Uint8Array(ab, CRC32_LEN_BYTES, ab.byteLength - CRC32_LEN_BYTES))) {
        console.log("crc32 check is invalid!");
        return;
      }
      //解析数据帧
      var offset = CRC32_LEN_BYTES;
      var frameLen = 0;
      do {
        frameLen = new Uint32Array(ab, offset, 1)[0];
        offset += FRAME_LEN_BYTES;
        if (offset + frameLen > ab.byteLength) {
          console.log("recv data format is invalid!");
          return;
        }
        data.push(content.slice(offset, offset + frameLen));
        offset += Pad4Bytes(frameLen);  //把长度补齐到4字节做偏移
      } while (offset + FRAME_LEN_BYTES < ab.byteLength);
      //递归转换数据帧为字符串
      blob2str(data[i++], str2json);
    });
  });
}


/* Unpack.js */
// RC4 对称加密
function RC4_decode(data) {
  if (data == null || data.length == 0 || !(data instanceof Uint8Array))  return;
  const key = [0x12, 0x1e, 0x6, 0x10, 0x17, 0x19, 0x1, 0x1a,
    0x1b, 0xd, 0x18, 0x13, 0x1f, 0x0, 0xa, 0xf,
    0x3, 0x8, 0x2, 0x15, 0xc, 0x14, 0xb, 0x16,
    0x4, 0x1c, 0x9, 0xe, 0x5, 0x7, 0x11, 0x1d];
  const mask = key.length - 1;
  var i = 0, j = 0;
  for (var n = 0; n < data.length; n++) {
    i = (i + 1) & mask;
    j = (j + key[i]) & mask;
    var tmp = key[i];
    key[i] = key[j];
    key[j] = tmp;
    data[n] ^= key[(key[i] + key[j]) & mask];
  }
}

function CheckSum(data) {
  var sum = 0;
  for (var i = 0; i < data.length; i++)
    sum += data[i];
  return sum;
}

const PackageHeaderLen = 64;  // 每个切片的头部长度
const FileHeaderLen = 56;     // 文件头部信息长度
const TSC_MAGIC_NUMBER = 0xa1b2c3d4;
// 解析切片头
function ParsePackageHeader(u8) {
  RC4_decode(u8);  // 对文件头进行 RC4 解密
  const u32 = new Uint32Array(u8.buffer, 0, PackageHeaderLen / 4);
  const packageHeader = {
    magic_number: u32[0],
    header_checksum: u32[1],
    header_length: u32[2],
    file_nums: u32[3],
    language: u32[4],
    device_class: u32[5],
    oemCode: u32[6],
    softwareVersion: u32[7],
    devType: u32[8],
  };
  return packageHeader;
}

function Uint8Array2str(u8) {
  for (var i = 0; i < u8.length; i++) {
    if (u8[i] == 0) break;
  }                                       
  return String.fromCharCode.apply(null, u8.subarray(0, i));//注意要从0开始截断
}

function ParseFileHeader(u8, count) {
  function ParseOneFileHeader(data) {
    var FILENAME_LEN = 32;
    var u32 = new Uint32Array(data.buffer, data.byteOffset, FileHeaderLen / 4);
    var index = FILENAME_LEN / 4;
    var fileHeader = {
      fileName: Uint8Array2str(data.subarray(0, FILENAME_LEN)),
      startOffset: u32[index],
      fileLen: u32[index + 1],
      md5: u32.subarray(index + 2),
    };
    return fileHeader;
  }

  var fileHeaders = [];
  var offset = 0;
  for (var i = 0; i < count; i++) {
    var data = u8.subarray(offset, offset + FileHeaderLen);
    fileHeaders[i] = ParseOneFileHeader(data);
    offset += FileHeaderLen;
  }
  return fileHeaders;
}

function GetUpdatePackageNameFromDevice(hv) {
  var name = '';
  if (hv === "XHJ-CW-GA-HK3")
    name = "hiktsc300-update.tar.gz";
  else if (hv === "XHJ-CW-GA-HK4")
    name = "firmware.tar.gz";
  else if (hv === "XHJ-CW-GA-HK5")
    name = "hiktsc-update.tar.gz";
  return name;
}

// 升级文件校验
function fileValid(arrayBuffer, device) {
  if (arrayBuffer.byteLength <= PackageHeaderLen + FileHeaderLen) {
    alert("升级包大小不够");
    return null;
  }
  if (device === null) {
    alert("设备名称为null");
    return null;
  }

  var ph = ParsePackageHeader(new Uint8Array(arrayBuffer, 0, PackageHeaderLen));
  if (ph.magic_number != TSC_MAGIC_NUMBER || ph.header_length >= arrayBuffer.byteLength
    || ph.file_nums != (ph.header_length - PackageHeaderLen) / FileHeaderLen) {
    alert("升级包的包头校验失败");
    return null;
  }
  var checkSum = CheckSum(new Uint8Array(arrayBuffer, 12, ph.header_length - 12));
  if (ph.header_checksum != checkSum) {
    alert("升级包校验和不匹配");
    return null;
  }

  function MD5Check(fh, u8) {
    var bin = Array();
    var val = 0;
    var j = 0;
    for (var i = 0; i < u8.length; i++) {
      val |= u8[i] << (j * 8);
      if (++j == 4) {
        bin.push(val);
        val = 0;
        j = 0;
      }
    }
    if (j > 0) bin.push(val);
    var result = core_md5(bin, u8.length * 8);
    if (result.length != fh.md5.length) {
      return false;
    }
    for (var i = 0; i < result.length; i++) {
      var gap = fh.md5[i] - result[i];
      if (gap != 0 && gap != 0x100000000) {    //因为result中可能有负数
        console.log("the package " + fh.fileName + " result != fh.md5");
        return false;
      }
    }
    return true;
  }

  var totalsize = ph.header_length;
  var fhs = ParseFileHeader(new Uint8Array(arrayBuffer, PackageHeaderLen, ph.header_length - PackageHeaderLen), ph.file_nums);
  var packageName = GetUpdatePackageNameFromDevice(device);
  for (var i = 0; i < ph.file_nums; i++) {
    totalsize += Pad4Bytes(fhs[i].fileLen);
    var file = new Uint8Array(arrayBuffer, fhs[i].startOffset, fhs[i].fileLen);
    if (totalsize > arrayBuffer.byteLength) {
      alert("升级包的内容长度超过包的总长度");
      return null;
    }
    if (!MD5Check(fhs[i], file)) {  // 此处对文件进行一个完整性校验,文件头信息中包含了 MD5 值,与 根据文件内容计算出的 MD5 值进行匹配
      alert("升级包的MD5校验无效");
      return null;
    }
    if (fhs[i].fileName === packageName) {
      var ret = { start: file.byteOffset, end: (file.byteOffset + file.byteLength) };
    }
  }

  if (ret) return ret;
  else {
    alert("升级包中没有涵盖此设备升级所需的数据");
    return null;
  }
};
let device = null

// 升级
const PACKAGE_PART_SIZE = 1024 * 1024;
let updatePackage = null;
let totalSize = null;
function SendUpdatePackage(ws) {
  if (!updatePackage || !(updatePackage instanceof Blob))
    return -1;
  if (updatePackage.size > PACKAGE_PART_SIZE) {
    let part = updatePackage.slice(0, PACKAGE_PART_SIZE);
    updatePackage = updatePackage.slice(PACKAGE_PART_SIZE);
    ws.send(part);
    return Math.floor((totalSize - updatePackage.size) / totalSize * 100)
  } else {  // 最后一次
    ws.send(updatePackage);
    updatePackage = null;
    return 100
  }
}
function Package(arr, callback) {
  if (!(arr instanceof Array)) {
    console.log("arr isn't Array");
    return false;
  }
  if (arr.length == 0) {
    console.log("arr length is 0");
    return false;
  }

  var content = [];
  for (var i = 0; i < arr.length; i++) {
    var data = null;
    if ((typeof arr[i] != 'string') && !(arr[i] instanceof Blob)) {
      try {	//如果不是字符串也不是Blob则是json对象,需转换成字符串
        var str = JSON.stringify(arr[i]);
        data = new Blob([str]);
      } catch (e) {
        console.log("error: " + e);
        return false;
      }
    } else {
      data = new Blob([arr[i]]);
    }
    var len = new Uint32Array(1);
    len[0] = data.size;
    var left = len[0] & (4 - 1);
    var pad = 4 - left;
    //console.log("data size is " + data.size);
    //if (left > 0)
    //    len[0] += pad;    注释掉此句,长度依旧是源长度只是把数据补齐到4字节对齐
    content.push(new Blob([len]));
    content.push(data);
    if (left > 0) {
      switch (pad) {  //以空格填充补充到4字节对齐
        case 1: content.push(new Blob([" "])); break;
        case 2: content.push(new Blob(["  "])); break;
        case 3: content.push(new Blob(["   "])); break;
      }
    }
  }

  var blob = new Blob(content);
  blob2ab(blob, function (ab) {
    var u8 = new Uint8Array(ab);
    var header = new Uint32Array(2);
    var crc32 = CRC32(u8);
    var CRC32_LEN_BYTES = 4;
    header[0] = CRC32_LEN_BYTES + u8.byteLength;   //packageSize, 4 bytes
    header[1] = crc32;  //CRC32, 4 bytes
    callback(new Blob([header, blob]));
  });
  return true;
}

// 请求映射表,用于导入预览模式
const urlMap = {
  "/ISAPI/TSC/unit": "unit",
  "/ISAPI/TSC/pedcross": "pedcross",
  "/ISAPI/TSC/countdown": "countdown",
  "/ISAPI/TSC/wireless": "wireless",
  "/ISAPI/TSC/serial": "serial",
  "/ISAPI/TSC/redCheck": "redcheck",
  "/ISAPI/TSC/wireless": "wirelesskey",
  "/ISAPI/TSC/panel": "panelkey",
  "/ISAPI/TSC/selfadapt": "selfadapt",
  "/ISAPI/TSC/detector": "detector",
  "/ISAPI/TSC/basic": ["channel", "phase", "scheme", "timeinterval", "schedule", "lane", "lockplan", "detector"]
}

class WS {
  constructor() {
    const port = process.env.NODE_ENV === 'production' ? (window.location.port || 80) : 8000
    console.log("初始化通信模块, 端口:" + port)
    this.callbacks = {}       // 只执行一次
    this.keepCallbacks = {}   // 每次接收都执行
    if (process.env.NODE_ENV === 'production') {
      this.ws = new WebSocket(`ws://${location.hostname}:${port}`);
    } else {
      this.ws = new WebSocket("ws://10.10.114.196:80");
    }
    this.init()
  }
  init() {
    if (this.ws.readyState == WebSocket.OPEN) {
      this.receiveData()
    } else {
      this.ws.onopen = (e) => {
        console.log(e)
        this.receiveData()

        this.ws.onclose = (e) => {
          console.log(e)
          setTimeout(() => {
            location.reload()
          }, 6000)
        }
      }
    }
  }

  send(msg, cb = function () { }, keep = false) {
    const sequence = UUID.create().toString()
    msg[0].sequence = sequence
    const szUrl = msg[0].URL
    const key = urlMap[szUrl]                     // 根据url获取缓存数据中的键
    const method = msg[0].method
    let totalData = $store.state.tempTotalConfig  // 非空表示进入了导入预览模式
    let decoratorCb = null
    // 参数导入预览状态下,不再向服务端发送请求,改为操作缓存数据
    if (totalData !== null && key) {
      if (method.toLocaleUpperCase() === 'GET') {
        if (key instanceof Array) {  // 如基础配置中一条url对应多个页面参数的情况
          let result = {}
          key.forEach(v => {
            result[v] = totalData[v] || []
          })
          cb([JSON.stringify({
            URL: szUrl,
            errorCode: 0,
            errorMsg: "",
            method: method,
            sequence: sequence
          }), JSON.stringify(result)])
          return;
        } else if(typeof key === "string") {
          if (totalData[key] === undefined) {        // 可能会存在导入的参数中缺失部分参数,则从服务端获取
            decoratorCb = (arr) => {
              totalData[key] = JSON.parse(arr[1])
              $store.commit('setTempTotalConfig', totalData)
              cb(arr)
            }
          } else {
            cb([JSON.stringify({
              URL: szUrl,
              errorCode: 0,
              errorMsg: "",
              method: method,
              sequence: sequence
            }), JSON.stringify(totalData[key])])
            return;
          }
        }
      } else if (method.toLocaleUpperCase() === 'POST') {
        let data = JSON.parse(JSON.stringify(msg[1]))
        if (key instanceof Array) {
          key.forEach(v => {
            if(data[v] !== undefined) totalData[v] = data[v]
          })
        }else {
          totalData[key] = data
        }
        $store.commit('setTempTotalConfig', totalData)
        cb([JSON.stringify({
          URL: szUrl,
          errorCode: 0,
          errorMsg: "",
          method: method,
          sequence: sequence
        })])
        return;
      }
    }

    this.registerCb(szUrl, method, decoratorCb ? decoratorCb : cb, keep, sequence)
    const ws = this.ws;
    if (ws) {
      if (ws.readyState == WebSocket.OPEN) {
        if (!Send(ws, msg)) {
          this.init()
          this.reConnect()
        }
      } else {
        ws.onopen = () => {
          this.receiveData()
          if (!Send(ws, msg)) {
            this.init()
            this.reConnect()
          }
        }
        ws.onclose = (e) => {
          console.log(e)
          setTimeout(() => {
            location.reload()
          }, 6000)
        }
      }
    }
  }
  receiveData() {
    const ws = this.ws;
    ws.onmessage = (event) => {
      Parse(event.data, (arr) => {
        let header = JSON.parse(arr[0]),
          fn = this.callbacks[header.URL + header.method + header.sequence],
          keepFn = this.keepCallbacks[header.URL + header.method + header.sequence];
        // 无权限时尝试自动登录,解决刷新页面权限丢失的问题
        if (header.errorCode === Vue.prototype.CONST.statusCode.noPermissions) {
          this.reConnect(() => {
            let _url = sessionStorage.getItem('lastNav')
            $store.commit('changeNav', _url)

            // 先跳转到其他路由再跳转至原先路由,以触发模块的mounted方法,后续寻找更优解 (可以尝试给模块加上key, 或者用 $fouceUpdate)
            $router.push({ path: '/null' })
            setTimeout(() => {
              $router.push({ path: _url })
            }, 0)
          })
        }
        if (header.errorMsg && header.errorCode !== Vue.prototype.CONST.statusCode.success) {
          console.log(header.URL + ": " + header.errorMsg)
          switch (header.errorCode) {
            case Vue.prototype.CONST.statusCode.noSupport:
              Vue.prototype.$message({
                showClose: true,
                message: header.errorMsg,
                type: 'error'
              });
              break;
            default:
              break;
          }
        }
        // 升级时做特殊处理, 加入进度
        if (header.URL === "/ISAPI/TSC/part") {
          arr.push(SendUpdatePackage(ws))
        }
        if (fn) {
          fn(arr)
          delete this.callbacks[header.URL + header.method + header.sequence]
        }
        if (keepFn) keepFn(arr)
      })
    }
  }
  registerCb(URL, type, cb, keep, sequence = "") {
    if (keep) {
      this.keepCallbacks[URL + type + sequence] = cb
    } else {
      this.callbacks[URL + type + sequence] = cb
    }
  }
  unRegisterCb(URL, type, sequence = "") {
    if (this.keepCallbacks[URL + type + sequence]) delete this.keepCallbacks[URL + type + sequence]
    if (this.callbacks[URL + type + sequence]) delete this.callbacks[URL + type + sequence]
  }
  // 升级
  upgrade(msg, _device, beforeSend, sending) {
    this.registerCb(msg[0].URL, msg[0].method, beforeSend, false)
    let file = msg[1]
    device = _device

    blob2ab(file, (ab) => {
      var ret = fileValid(ab, device);
      if (ret) {
        var head = { method: "POST", URL: msg[0].URL };
        Package([head, new Blob([device, file.slice(ret.start, ret.end)])], (blob) => {
          updatePackage = blob
          totalSize = blob.size
          SendUpdatePackage(this.ws)
          if (sending) sending()
        });
      }
    });
  }
  sendFile(msg, beforeSend, sending) {
    this.registerCb(msg[0].URL, msg[0].method, beforeSend, false);
    let file = msg[1];
    var head = { method: "POST", URL: msg[0].URL };
    Package([head, new Blob([file])], (blob) => {
      updatePackage = blob;
      totalSize = blob.size;
      SendUpdatePackage(this.ws);
      if (sending) sending();
    });
  }
  // 重连
  reConnect(successCb) {
    let username = sessionStorage.getItem('username')
    let password = atob(sessionStorage.getItem('password'))
    if (username && password) {
      if (this.logining) {
        console.log('正在重连中')
        return;
      }
      this.logining = true
      this.send([{ method: 'GET', URL: '/ISAPI/TSC/authorization' }], (arr) => {
        let auth = JSON.parse(arr[1]);
        let cmd = [
          { method: "POST", URL: "/ISAPI/TSC/login" },
          { username: username, password: Vue.prototype.cryptoJS.encrypt(auth, password), sessionID: auth.sessionID }
        ];
        this.send(cmd, (arr) => {
          this.logining = false
          let header = JSON.parse(arr[0])
          if (header.errorCode === Vue.prototype.CONST.statusCode.success) {
            $store.commit('setUsername', username)
            if (successCb) successCb()
          } else {
            $router.push({ path: '/' })
          }
        })
      })
    } else {
      location.href = '/'
    }
  }
}

export default new WS();

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务