js使用mqtt请求数据

Posted lia二娃

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js使用mqtt请求数据相关的知识,希望对你有一定的参考价值。

1.引入mqtt的js库,地址链接https://blog.csdn.net/qq_28877125/article/details/78360170

<script src="./static/js/mqttws31.js" type="text/javascript"></script>

  出现format报错的话引入如下js,问题是由于ES6中取消了new Date的format()方法,所以要使用此js引入到依赖中。

(function () {
  // Defining locale
  Date.shortMonths = [‘Jan‘, ‘Feb‘, ‘Mar‘, ‘Apr‘, ‘May‘, ‘Jun‘, ‘Jul‘, ‘Aug‘, ‘Sep‘, ‘Oct‘, ‘Nov‘, ‘Dec‘]
  Date.longMonths = [‘January‘, ‘February‘, ‘March‘, ‘April‘, ‘May‘, ‘June‘, ‘July‘, ‘August‘, ‘September‘, ‘October‘, ‘November‘, ‘December‘]
  Date.shortDays = [‘Sun‘, ‘Mon‘, ‘Tue‘, ‘Wed‘, ‘Thu‘, ‘Fri‘, ‘Sat‘]
  Date.longDays = [‘Sunday‘, ‘Monday‘, ‘Tuesday‘, ‘Wednesday‘, ‘Thursday‘, ‘Friday‘, ‘Saturday‘]
  // Defining patterns
  var replaceChars = {
    // Day
    d: function () { var d = this.getDate(); return (d < 10 ? ‘0‘ : ‘‘) + d },
    D: function () { return Date.shortDays[this.getDay()] },
    j: function () { return this.getDate() },
    l: function () { return Date.longDays[this.getDay()] },
    N: function () { var N = this.getDay(); return (N === 0 ? 7 : N) },
    S: function () { var S = this.getDate(); return (S % 10 === 1 && S !== 11 ? ‘st‘ : (S % 10 === 2 && S !== 12 ? ‘nd‘ : (S % 10 === 3 && S !== 13 ? ‘rd‘ : ‘th‘))) },
    w: function () { return this.getDay() },
    z: function () { var d = new Date(this.getFullYear(), 0, 1); return Math.ceil((this - d) / 86400000) },
    // Week
    W: function () {
      var target = new Date(this.valueOf())
      var dayNr = (this.getDay() + 6) % 7
      target.setDate(target.getDate() - dayNr + 3)
      var firstThursday = target.valueOf()
      target.setMonth(0, 1)
      if (target.getDay() !== 4) {
        target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7)
      }
      var retVal = 1 + Math.ceil((firstThursday - target) / 604800000)

      return (retVal < 10 ? ‘0‘ + retVal : retVal)
    },
    // Month
    F: function () { return Date.longMonths[this.getMonth()] },
    m: function () { var m = this.getMonth(); return (m < 9 ? ‘0‘ : ‘‘) + (m + 1) },
    M: function () { return Date.shortMonths[this.getMonth()] },
    n: function () { return this.getMonth() + 1 },
    t: function () {
      var year = this.getFullYear()
      var nextMonth = this.getMonth() + 1
      if (nextMonth === 12) {
        year = year++
        nextMonth = 0
      }
      return new Date(year, nextMonth, 0).getDate()
    },
    // Year
    L: function () { var L = this.getFullYear(); return (L % 400 === 0 || (L % 100 !== 0 && L % 4 === 0)) },
    o: function () { var d = new Date(this.valueOf()); d.setDate(d.getDate() - ((this.getDay() + 6) % 7) + 3); return d.getFullYear() },
    Y: function () { return this.getFullYear() },
    y: function () { return (‘‘ + this.getFullYear()).substr(2) },
    // Time
    a: function () { return this.getHours() < 12 ? ‘am‘ : ‘pm‘ },
    A: function () { return this.getHours() < 12 ? ‘AM‘ : ‘PM‘ },
    B: function () { return Math.floor((((this.getUTCHours() + 1) % 24) + this.getUTCMinutes() / 60 + this.getUTCSeconds() / 3600) * 1000 / 24) },
    g: function () { return this.getHours() % 12 || 12 },
    G: function () { return this.getHours() },
    h: function () { var h = this.getHours(); return ((h % 12 || 12) < 10 ? ‘0‘ : ‘‘) + (h % 12 || 12) },
    H: function () { var H = this.getHours(); return (H < 10 ? ‘0‘ : ‘‘) + H },
    i: function () { var i = this.getMinutes(); return (i < 10 ? ‘0‘ : ‘‘) + i },
    s: function () { var s = this.getSeconds(); return (s < 10 ? ‘0‘ : ‘‘) + s },
    v: function () { var v = this.getMilliseconds(); return (v < 10 ? ‘00‘ : (v < 100 ? ‘0‘ : ‘‘)) + v },
    // Timezone
    e: function () { return Intl.DateTimeFormat().resolvedOptions().timeZone },
    I: function () {
      var DST = null
      for (var i = 0; i < 12; ++i) {
        var d = new Date(this.getFullYear(), i, 1)
        var offset = d.getTimezoneOffset()

        if (DST === null) DST = offset
        else if (offset < DST) { DST = offset; break } else if (offset > DST) break
      }
      return (this.getTimezoneOffset() === DST) | 0
    },
    O: function () { var O = this.getTimezoneOffset(); return (-O < 0 ? ‘-‘ : ‘+‘) + (Math.abs(O / 60) < 10 ? ‘0‘ : ‘‘) + Math.floor(Math.abs(O / 60)) + (Math.abs(O % 60) === 0 ? ‘00‘ : ((Math.abs(O % 60) < 10 ? ‘0‘ : ‘‘)) + (Math.abs(O % 60))) },
    P: function () { var P = this.getTimezoneOffset(); return (-P < 0 ? ‘-‘ : ‘+‘) + (Math.abs(P / 60) < 10 ? ‘0‘ : ‘‘) + Math.floor(Math.abs(P / 60)) + ‘:‘ + (Math.abs(P % 60) === 0 ? ‘00‘ : ((Math.abs(P % 60) < 10 ? ‘0‘ : ‘‘)) + (Math.abs(P % 60))) },
    T: function () { var tz = this.toLocaleTimeString(navigator.language, {timeZoneName: ‘short‘}).split(‘ ‘); return tz[tz.length - 1] },
    Z: function () { return -this.getTimezoneOffset() * 60 },
    // Full Date/Time
    c: function () { return this.Format(‘Y-m-d\TH:i:sP‘) },
    r: function () { return this.toString() },
    U: function () { return Math.floor(this.getTime() / 1000) }
  }

  // Simulates php‘s date function
  Date.prototype.Format = function (format) {
    var date = this
    return format.replace(/(\?)(.)/g, function (_, esc, chr) {
      return (esc === ‘‘ && replaceChars[chr]) ? replaceChars[chr].call(date) : chr
    })
  }
}).call(this)

3.发布主题与订阅主题

export default {
    data() {
        return {
         data:{}//用于接收返回的数据
            clientId:"",
            userName: "",
            password: "",
            deviceid:"",
            cmd:‘search‘,
            topic_get: ‘订阅的主题‘,
            topic_send: ‘发布的主题‘,
            client: {},
            options: {},
            count: 0,
            time:‘‘,
            devlist_data_one:‘‘,
        };
    },
    mixins:[clientIp],
    created(){
        console.log(this.hostname)this.client = new Paho.MQTT.Client(
            this.hostname,
            this.port,
            this.clientId
        );
        let that=this
        console.log(this.client);
        this.options = {
            invocationContext: {
                host:this.hostname,
                port:this.port,
                path:this.client.path,
                clientId:this.clientId
            },
            userName:this.userName,
            password:this.password,
            onSuccess: function() {//连接成功
                console.log("onSuccess")
                that.send();
            },
            onFailure: function(e) {//连接失败
                console.log("onFailure")
                console.log(e);
            }
        };
        this.client.connect(this.options); //连接服务器并注册连接成功处理事件
        this.client.onConnectionLost = this.onConnectionLost; //注册连接断开处理事件

        this.client.onMessageArrived = this.onMessageArrived; //注册消息接收处理事件
    },
    methods: {
        jumpNum(val){
            this.$router.push({path:‘/devinfo/devstate‘,query:{devId:val.number}})
        },
        onMessageArrived(message) {
            this.data=message.payloadString;
            console.log(this.data);//返回的数据
        },

        onConnectionLost(responseObject) {
            if (responseObject.errorCode !== 0) {
                console.log("onConnectionLost:" + responseObject);
                console.log(responseObject);
                console.log("连接已断开");
            }
        },
        send:function(){
            this.time=this.fromDate(new Date())
            let device_id=JSON.stringify(this.deviceid)
            var sendMsg = ‘{"device_id":"‘ + this.deviceid + ‘","cmd":"‘+this.cmd+‘","time":"‘+this.time+‘","from":"web console"}‘;
            console.log(sendMsg)
            var message = new Paho.MQTT.Message(sendMsg);
            message.destinationName = this.topic_send;//发送主题
            this.client.subscribe(this.topic_get);//订阅主题
            this.client.send(message);
        },
      fromDate(date) {
             // var date = new Date(parseInt(timestamp, 10));
             var date= new Date(Date.parse(date));
             var Y = date.getFullYear() ;
             var M = (date.getMonth() + 1 < 10 ? ‘0‘ + (date.getMonth() + 1) : date.getMonth() + 1);
             var D = date.getDate() ;
             var h = date.getHours() < 10 ? ‘0‘ + date.getHours() : date.getHours() ;
             var m = date.getMinutes() < 10 ? ‘0‘ + date.getMinutes() : date.getMinutes();
             var s = date.getSeconds() < 10 ? ‘0‘ + date.getSeconds() : date.getSeconds();
             return Y + ‘-‘ + M + ‘-‘ + D + ‘ ‘ + h + ‘:‘ + m + ‘:‘ + s;
         }
  }

注:1.mqtt为短连接,要想实时更新可使用定时器执性send()函数。

  2.this.options中还有其他参数,需要的话自行查找

  3.发送数据为json格式,可用JSON.stringify()转换字符串,文中是拼接的。

以上是关于js使用mqtt请求数据的主要内容,如果未能解决你的问题,请参考以下文章

js 连接mqtt

超级有用的9个PHP代码片段

JavaScript使用MQTT

回归 | js实用代码片段的封装与总结(持续更新中...)

实例:使用MQTT进行交互

MQTT和Websocket的区别是啥