UTS插件
import { MqttAsync } from '@ohos/mqtt'
export function mqttUtil(): MqttAsync {
return MqttAsync
}
页面
<template>
<view class="content">
<image class="logo" src="/static/logo.png"></image>
<view class="text-area">
<button @click="connect">连接MQTT</button>
</view>
</view>
</template>
<script setup lang="uts">
import { mqttUtil } from '@/uni_modules/chengzan-mqtt'
const connect = () => { // 获取电量信息
let mqttAsyncClient;
mqttAsyncClient = mqttUtil().createMqtt({
url: 'broker.emqx.io:1883',
clientId: '71627cb01e9b8a02-rNfbb0v',
persistenceType: 1,
})
let options = {
//set userName and password
userName: "",
password: "",
connectTimeout: 30,
version: 4,
};
mqttAsyncClient.connect(options).then((data) => {
console.log("mqtt connect success "+ JSON.stringify(data));
}).catch((err) => {
console.log("mqtt connect fail"+JSON.stringify(err))
})
}
</script>