首页 > 其他分享 >Vue_MQTT项目搭建记录

Vue_MQTT项目搭建记录

时间:2023-11-14 22:24:58浏览次数:38  
标签:Vue const mqtt MQTT client params options 搭建

新建vue3项目

# 新建 vite + vue3的项目
npm init vue@latest

yarn 安装依赖包

yarn add mqtt

初探 - 连接阿里云物联网平台

代码:

<template>
  <div>
    <h1>LED - IOT</h1>
    <button @click="connectToBroker">Connect</button>
    <button @click="subscribe">Subscribe</button>
    <button @click="publish">Publish</button>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import mqtt from 'mqtt'
import hexHmacSha1 from '../utils/hex_hmac_sha1'

export default {
  name: 'LED',
  setup() {
    const deviceConfig = {
      productKey: 'xx',
      deviceName: 'led_1',
      deviceSecret: 'xxxx',
      regionId: 'cn-shanghai', // 根据自己的区域替换
    }

    const client = ref(null)

    const connectToBroker = () => {
      const options = initializeMqttOptions(deviceConfig)
      console.log(options)
      client.value = mqtt.connect(
        'wss://productKey.iot-as-mqtt.cn-shanghai.aliyuncs.com',
        options
      )
      client.value.on('connect', () => {
        console.log('Successfully connected to the server')
        
      })
      client.value.on('message', (topic, message) => {
        let msg = message.toString()
        console.log('Received message: ' + msg)
        // Close the connection: client.value.end()
      })
    }
    const publish = ()=>{
      if (client.value) {
        client.value.publish(`/sys/${deviceConfig.productKey}/${deviceConfig.deviceName}/thing/event/property/post`, {
          "NightLightSwitch": "0"
        })
      }
    }

    const subscribe = ()=>{
      client.value.subscribe('/productKey/deviceName/user/get', (err) => {
          if (!err) {
            console.log('Successfully subscribed!')
          }
        })
    }
    const initializeMqttOptions = (deviceConfig) => {
      const params = {
        productKey: deviceConfig.productKey,
        deviceName: deviceConfig.deviceName,
        timestamp: Date.now(),
        clientId: Math.random().toString(36).substr(2),
      }
      const options = {
        keepalive: 60,
        clean: true,
        protocolVersion: 4,
      }
      options.password = generateHmacSha1Signature(params, deviceConfig.deviceSecret)
      options.clientId = `${params.clientId}|securemode=2,signmethod=hmacsha1,timestamp=${params.timestamp}|`
      options.username = `${params.deviceName}&${params.productKey}`
      return options
    }

    const generateHmacSha1Signature = (params, deviceSecret) => {
      let keys = Object.keys(params).sort()
      const list = []
      keys.forEach((key) => {
        list.push(`${key}${params[key]}`)
      })
      const contentStr = list.join('')
      return hexHmacSha1(deviceSecret, contentStr)
    }

    onMounted(() => {
      connectToBroker()
    })

    return {
      connectToBroker,
      initializeMqttOptions,
      generateHmacSha1Signature,
      publish
    }
  },
}
</script>

<style></style>

放弃探索阿里云物联网平台,好像有不少的坑...

转向自己搭建emqx

参考文章

MQTT.js 入门教程 | EMQ (emqx.com)

【精选】微信小程序使用MQTT.js连接阿里云IoT物联网平台_阿里 mqtt js版本-CSDN博客

踩的坑

Node.js和浏览器的不同

注意是MQTT基于的协议不同

Node.js中mqtt是基于tcp

而浏览器的mqtt是基于websocket

因此配置的端口号和路径会有所不一样。

进阶 - 转向 本地emqx

下载emqx:

https://www.emqx.com/zh/downloads-and-install?product=broker&version=5.3.0&os=Windows&oslabel=Windows

启动emqx:

bin/emqx start

打开管理后台:

localhost:18083

账号密码:

admin

public

示例代码:

// Node.js
const mqtt = require('mqtt');
// MQTT连接地址
const broker = 'mqtt://a1sIKncPskh.iot-as-mqtt.cn-shanghai.aliyuncs.com:1883';

// MQTT连接选项
const options = {
  clientId: 'a1sIKncPskh.led_1|securemode=2,signmethod=hmacsha256,timestamp=1699678758528|',
  username: 'led_1&a1sIKncPskh',
  password: '74ee471ac5e5ac4b99bbb82652905127c2ecca77c38d198b114fd5c4bfee9158',
  keepalive: 60,
  clean: true,
};

// 创建MQTT客户端
const client = mqtt.connect(broker, options);

// 连接成功回调
client.on('connect', function () {
  console.log('Connected to Aliyun IoT Platform');
});

// 订阅主题
client.subscribe('your_topic');

// 接收消息回调
client.on('message', function (topic, message) {
  console.log('Received message:', message.toString());
});

// 发布消息
client.publish('your_topic', 'Hello, IoT Platform');

标签:Vue,const,mqtt,MQTT,client,params,options,搭建
From: https://www.cnblogs.com/yecss/p/17832727.html

相关文章

  • Arduino之ESP8266开发环境搭建
    1、下载arduino官网:https://www.arduino.cc/en/software页面下滑,建议选择旧版本下载2、安装ESP8266开发包因为ArduinoIDE默认是给Arduino开发板用的,默认只有Arduino开发板的相关开发资源。要想在在ArduinoIDE中使用ESP8266,需要额外安装ESP8266的开发包。安装方式有两种,一种......
  • pikachu靶场搭建
    皮卡丘下载链接pikachuPikachu是一个带有漏洞的Web应用系统,在这里包含了常见的web安全漏洞。如果你是一个Web渗透测试学习人员且正发愁没有合适的靶场进行练习,那么Pikachu可能正合你意。Pikachu上的漏洞类型列表如下:BurtForce(暴力破解漏洞)XSS(跨站脚本漏洞)CSRF(跨站请......
  • vue3源码学习api-vue-sfc文件编译
    vue最有代表性质的就是.VUE的文件,每一个vue文件都是一个组件,那么vue组件的编译过程是什么样的呢Vue单文件组件(SFC)和指令ast语法树一个Vue单文件组件(SFC),通常使用*.vue作为文件扩展名,它是一种使用了类似HTML语法的自定义文件格式,用于定义Vue组件。一个Vue单......
  • Vue 组件里的定时器要怎么销毁?
    如果页面上有很多定时器,可以在data选项中创建一个对象timer,给每个定时器取个名字一一映射在对象timer中,在beforeDestroy构造函数中清除,beforeDestroy(){ for(letkinthis.timer){ clearInterval(k) }}如果页面只有单个定时器,可以这么做consttimer=setInterv......
  • 记录--Vue2屎山之 Table 屎山
    这里给大家分享我在网上总结出来的一些知识,希望对大家有所帮助前言Vue2将在2023年年底停止维护了,但是Vue2的代码却不会在2023年消失,还会越来越多;难以想象几十万行或者几百万行的Vue2代码迁移到Vue3,这是不可能办到的;老一点的前端程序员肯定经历过把大型项目从jQue......
  • windows ewomail docker搭建流程记录
     一、安装命令dockerrun-d-hmail.dowhere.com--restart=always-p25:25-p109:109-p110:110-p143:143-p465:465-p587:587-p993:993-p995:995-p8182:80-p8181:8080-p13307:3306-vD:/dockercontainer/ewomail/mysql/:/mysql/data/-vD:/dockerconta......
  • Unity3D 如何用unity引擎然后用c#语言搭建自己的服务器
    Unity3D是一款强大的游戏开发引擎,可以用于创建各种类型的游戏。在游戏开发过程中,经常需要与服务器进行通信来实现一些功能,比如保存和加载游戏数据、实现多人游戏等。本文将介绍如何使用Unity引擎和C#语言搭建自己的服务器,并给出技术详解以及代码实现。对惹,这里有一个游戏开发交流......
  • 使用 nginx 和 rtmp 插件搭建视频直播和点播服务器
    使用nginx和rtmp模块,可以很容易地搭建一个视频直播和点播服务器出来。下面我们来看一下具体实施步骤:1.安装nginx和rtmp模块有关nginx的编译和安装比较简单,这里就不介绍了,看参考文献。这里提示以下几点:(1)安装好nginx后,配置文件在这里:/usr/local/nginx/conf/nginx.co......
  • 在Window系统中安装VMware虚拟机搭建Linux服务器
    1、什么是VMwareWorkstationVMwareWorkstationPro是一款桌面虚拟化软件。我们可以通过WorkstationPro在Windows或LinuxPC上运行多个操作系统作为虚拟机。它是运行虚拟机的行业通用标准,可以方便快速地使用Windows或者Linux。官网介绍:跨一系列不同的设备、平台和云构建、测试......
  • VUE 前端读取excel表格内容
    <el-uploadclass="upload-demo":action="''":show-file-list="false":auto-upload="false":before-upload="beforeUpload":on-success="handleSuccess&quo......