UNPKG

daq-sdk-js

Version:

Data Acquisition JS SDK of Monster

155 lines (147 loc) 3.2 kB
const md5 = require("md5"); // 采集sdk const daq = {}; // 工具 const _ = { options: {}, logger: function() {}, // 日志工具 }; daq.param = { prefix: "/mst-solar-api/data/coll", server_url: "", // 服务地址 token: "", // 商户密钥 ID,商户固定暂定 project: "", // 项目名称 channel: "", // PC: 1 APP AND 2 IOS 3 微信小程序 4 }; // 设置请求工具 daq.initRequest = function(request) { this.request = request; }; /** * 初始化数据采集工具 * @param {Object} param */ daq.initial = function(param) { this.param = { ...daq.param, ...param, }; _.options.showLog = param.showLog || false; }; /** * 发送采集的数据 * @param {Object} param */ daq.sendEvent = function({ tenantId = this.param.tenantId, project = this.param.project, channel = this.param.channel, event = "", timestamp = _.now(), nonce = _.getRandom(), data = {}, }) { try { const url = this.param.server_url + this.param.prefix; const token = this.param.token; const time = _.now(); const sign = _.getSign(token, timestamp, nonce); _.logger({ message: "准备请求" + url + "\ntoken:" + token + "\nsign:" + sign, }); this.request.post( url, { tenantId, project, channel, event, time, data, }, { // // credentials: "include", // timeout: 3000, // // prefix: this.param.prefix, headers: { // "Content-Type": "application/json", token, // 用户令牌 timestamp, //当前时间戳 nonce, // 随机正整数 sign, //签名,,上述三个参数加起来,计算32位MD5摘要值,并转为16进制字符串 }, } ); } catch (e) { _.logger({ type: "error", message: e && e.message ? e.message + "\n" : e, }); } }; // ---------- 工具定义 // 日志工具 // type : log,warn,error _.logger = function({ message = "", type = "log" }) { if (!this.options.showLog) { return; } console[type](_.fmtDate(), message); }; /** * 当前时间戳 */ _.now = function() { return new Date().getTime(); }; /** * 当前格式化的日期 */ _.fmtDate = function() { const d = new Date(); return ( d.getFullYear() + "-" + _.dig2(d.getMonth() + 1) + "-" + _.dig2(d.getDate()) + " " + _.dig2(d.getHours()) + ":" + _.dig2(d.getMinutes()) + ":" + _.dig2(d.getSeconds()) ); }; /** * 最低2位数 * @param {*} number */ _.dig2 = function(number) { const numberStr = `${number}`; if (numberStr.length == 1) { return "0" + number; } else { return numberStr; } }; /** * 格式化sign token,timestamp,nonce三个参数加起来,计算32位MD5摘要值,并转为16进制字符串 * @param {string} token * @param {string} timestamp * @param {string} nonce */ _.getSign = function(token, timestamp, nonce) { const sum = `${token}${timestamp}${nonce}`; return md5(sum); }; /** * 获取随机数 */ _.getRandom = function() { return Math.round(Math.random() * 100000); }; if (window) { window.daq = daq; } module.exports = daq;