mqtt协议测试
This commit is contained in:
@ -75,184 +75,227 @@
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import {
|
||||
formList
|
||||
} from '@/common/form.js'
|
||||
import {
|
||||
Langlist
|
||||
} from '@/common/lang'
|
||||
import pako from 'pako'
|
||||
import { formList } from "@/common/form.js";
|
||||
import { Langlist } from "@/common/lang";
|
||||
import pako from "pako";
|
||||
import mqtt from "mqtt";
|
||||
export default {
|
||||
data() {
|
||||
return {
|
||||
formList: formList,
|
||||
background: {
|
||||
backgroundColor: "#0EA17E",
|
||||
},
|
||||
lang: 'en',
|
||||
socketTask: null,
|
||||
backData: {},
|
||||
smallArr: [],
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
language() {
|
||||
return this.vuex_language
|
||||
}
|
||||
},
|
||||
watch: {
|
||||
language: {
|
||||
handler(val) {
|
||||
this.lang = Langlist.find(v => v.prop == val).value
|
||||
},
|
||||
immediate: true,
|
||||
deep: true,
|
||||
},
|
||||
},
|
||||
onShow() {
|
||||
if (!this.socketTask) {
|
||||
this.init()
|
||||
}
|
||||
this.send({
|
||||
fun: 'GET',
|
||||
type: 'WJ_Get_NewControlSystem',
|
||||
content: 0
|
||||
})
|
||||
this.socketTask.onMessage(res => {
|
||||
let dataZip = this.decodeGzipBase64(res.data)
|
||||
if (dataZip.type == 'WJ_Get_NewControlSystem') {
|
||||
this.control(dataZip.content)
|
||||
}
|
||||
})
|
||||
},
|
||||
beforeDestroy() {
|
||||
this.socketTask = null
|
||||
},
|
||||
methods: {
|
||||
decodeGzipBase64(base64Str) {
|
||||
// 1. base64 → Uint8Array
|
||||
const binaryStr = atob(base64Str);
|
||||
const len = binaryStr.length;
|
||||
const bytes = new Uint8Array(len);
|
||||
data() {
|
||||
return {
|
||||
formList: formList,
|
||||
background: {
|
||||
backgroundColor: "#0EA17E",
|
||||
},
|
||||
lang: 'en',
|
||||
mqttClient: null,
|
||||
backData: {},
|
||||
smallArr: [],
|
||||
};
|
||||
},
|
||||
computed: {
|
||||
language() {
|
||||
return this.$store.state.vuex_language
|
||||
}
|
||||
},
|
||||
watch: {
|
||||
language: {
|
||||
handler(val) {
|
||||
// console.log(val)
|
||||
// this.lang.value = Langlist.find(v => v.prop == val)
|
||||
// console.log(this.lang)
|
||||
},
|
||||
immediate: true,
|
||||
deep: true,
|
||||
},
|
||||
},
|
||||
onShow() {
|
||||
if (!this.mqttClient) {
|
||||
this.initMQTT()
|
||||
}
|
||||
},
|
||||
beforeDestroy() {
|
||||
if (this.mqttClient) {
|
||||
this.mqttClient.end()
|
||||
this.mqttClient = null
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
decodeGzipBase64(base64Str) {
|
||||
// 1. base64 → Uint8Array
|
||||
const binaryStr = atob(base64Str);
|
||||
const len = binaryStr.length;
|
||||
const bytes = new Uint8Array(len);
|
||||
|
||||
for (let i = 0; i < len; i++) {
|
||||
bytes[i] = binaryStr.charCodeAt(i);
|
||||
}
|
||||
for (let i = 0; i < len; i++) {
|
||||
bytes[i] = binaryStr.charCodeAt(i);
|
||||
}
|
||||
|
||||
// 2. gunzip 解压
|
||||
const decompressed = pako.ungzip(bytes, {
|
||||
to: "string"
|
||||
});
|
||||
// 3. 转 JSON(如果是 JSON)
|
||||
return JSON.parse(decompressed);
|
||||
},
|
||||
getSelectList(item) {
|
||||
if (item.selectArr && item.selectArr.length > 0) {
|
||||
return item.selectArr.map(option => ({
|
||||
value: option.value.toString(),
|
||||
label: option[`label_${this.lang}`] || option.label
|
||||
}))
|
||||
}
|
||||
return []
|
||||
},
|
||||
control(NewControlSystemShow_data) {
|
||||
this.formList.forEach(item => {
|
||||
if (item.type == "Switch") {
|
||||
item.value = NewControlSystemShow_data?.params[item.prop] ? true : false
|
||||
} else {
|
||||
item.value = NewControlSystemShow_data?.params[item.prop] || item.default
|
||||
}
|
||||
if (item.type == 'Select') {
|
||||
item.selectLabel = item.selectArr.find(v => v.value == item.value)?.[`label_${this.lang}`]
|
||||
}
|
||||
item.isShow = false
|
||||
})
|
||||
this.backData = NewControlSystemShow_data
|
||||
this.smallArr = this.formList.filter(v => NewControlSystemShow_data?.smallScreen.includes(v.prop))
|
||||
},
|
||||
confirm(val, item) {
|
||||
if (val && val.length > 0) {
|
||||
item.value = val[0].value
|
||||
item.selectLabel = val[0].label
|
||||
}
|
||||
item.isShow = false
|
||||
},
|
||||
handleInput(item, event) {
|
||||
try {
|
||||
let inputValue = event.detail.value;
|
||||
let iptval = String(inputValue).replace(/[^0-9.]/g, '');
|
||||
const parts = iptval.split('.');
|
||||
if (parts.length > 2) {
|
||||
iptval = parts[0] + '.' + parts.slice(1).join('');
|
||||
}
|
||||
if (!iptval || iptval === '.') {
|
||||
item.value = 0;
|
||||
return;
|
||||
}
|
||||
let numVal = Number(iptval);
|
||||
if (item.min !== undefined && item.min !== null) {
|
||||
numVal = Math.max(numVal, item.min);
|
||||
}
|
||||
if (item.max !== undefined && item.max !== null) {
|
||||
numVal = Math.min(numVal, item.max);
|
||||
}
|
||||
numVal = isNaN(numVal) ? 0 : numVal;
|
||||
item.value = numVal;
|
||||
} catch (error) {
|
||||
console.log('handleInput方法错误:', error);
|
||||
}
|
||||
},
|
||||
init() {
|
||||
this.socketTask = uni.connectSocket({
|
||||
url: "ws://192.168.1.136:9002", //仅为示例,并非真实接口地址。
|
||||
// url: 'wss://remotec.zzkj-cloud.com/ws/',
|
||||
complete: (res) => {
|
||||
|
||||
},
|
||||
});
|
||||
},
|
||||
send(msg) {
|
||||
if (this.socketTask) {
|
||||
this.socketTask.send({
|
||||
data: JSON.stringify(msg || {}),
|
||||
complete: (res) => {
|
||||
console.log('消息发送成功:', res)
|
||||
}
|
||||
})
|
||||
} else {
|
||||
console.log('socketTask未初始化')
|
||||
this.init()
|
||||
setTimeout(() => {
|
||||
this.send(msg)
|
||||
}, 500)
|
||||
}
|
||||
},
|
||||
toback() {
|
||||
uni.navigateBack()
|
||||
},
|
||||
selectShow(val, index) {
|
||||
val.isShow = true
|
||||
},
|
||||
submitDevice() {
|
||||
let smallParam = this.smallArr.reduce((pre, cur) => {
|
||||
pre[cur.prop] = cur.type == "Switch" ? cur.value ? 1 : 0 : cur.value
|
||||
pre[cur.prop] = Number(pre[cur.prop])
|
||||
return pre
|
||||
}, {})
|
||||
this.send({
|
||||
fun: 'SET',
|
||||
type: 'WJ_Set_NewControlSystem',
|
||||
content: {
|
||||
...this.backData,
|
||||
params: {
|
||||
...this.backData.params,
|
||||
...smallParam
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
// 2. gunzip 解压
|
||||
const decompressed = pako.ungzip(bytes, {
|
||||
to: "string"
|
||||
});
|
||||
// 3. 转 JSON(如果是 JSON)
|
||||
return JSON.parse(decompressed);
|
||||
},
|
||||
getSelectList(item) {
|
||||
if (item.selectArr && item.selectArr.length > 0) {
|
||||
return item.selectArr.map(option => ({
|
||||
value: option.value.toString(),
|
||||
label: option[`label_${this.lang}`] || option.label
|
||||
}))
|
||||
}
|
||||
return []
|
||||
},
|
||||
control(NewControlSystemShow_data) {
|
||||
this.formList.forEach(item => {
|
||||
if (item.type == "Switch") {
|
||||
item.value = NewControlSystemShow_data?.params[item.prop] ? true : false
|
||||
} else {
|
||||
item.value = NewControlSystemShow_data?.params[item.prop] || item.default
|
||||
}
|
||||
if (item.type == 'Select') {
|
||||
item.selectLabel = item.selectArr.find(v => v.value == item.value)?.[`label_${this.lang}`]
|
||||
}
|
||||
item.isShow = false
|
||||
})
|
||||
this.backData = NewControlSystemShow_data
|
||||
this.smallArr = this.formList.filter(v => NewControlSystemShow_data?.smallScreen.includes(v.prop))
|
||||
},
|
||||
confirm(val, item) {
|
||||
if (val && val.length > 0) {
|
||||
item.value = val[0].value
|
||||
item.selectLabel = val[0].label
|
||||
}
|
||||
item.isShow = false
|
||||
},
|
||||
handleInput(item, event) {
|
||||
try {
|
||||
let inputValue = event.detail.value;
|
||||
let iptval = String(inputValue).replace(/[^0-9.]/g, '');
|
||||
const parts = iptval.split('.');
|
||||
if (parts.length > 2) {
|
||||
iptval = parts[0] + '.' + parts.slice(1).join('');
|
||||
}
|
||||
if (!iptval || iptval === '.') {
|
||||
item.value = 0;
|
||||
return;
|
||||
}
|
||||
let numVal = Number(iptval);
|
||||
if (item.min !== undefined && item.min !== null) {
|
||||
numVal = Math.max(numVal, item.min);
|
||||
}
|
||||
if (item.max !== undefined && item.max !== null) {
|
||||
numVal = Math.min(numVal, item.max);
|
||||
}
|
||||
numVal = isNaN(numVal) ? 0 : numVal;
|
||||
item.value = numVal;
|
||||
} catch (error) {
|
||||
console.log('handleInput方法错误:', error);
|
||||
}
|
||||
},
|
||||
initMQTT() {
|
||||
// 使用mqtt.js库创建MQTT连接
|
||||
const options = {
|
||||
clientId: 'client_' + Math.random().toString(36).substr(2, 9),
|
||||
username: 'admin',
|
||||
password: 'zzkj@688737',
|
||||
keepalive: 60,
|
||||
clean: true,
|
||||
reconnectPeriod: 5000,
|
||||
connectTimeout: 30 * 1000
|
||||
};
|
||||
|
||||
// 使用WebSocket连接到MQTT broker
|
||||
const brokerURL = 'ws://13.39.200.14:8083/mqtt';
|
||||
this.mqttClient = mqtt.connect(brokerURL, options);
|
||||
|
||||
// 连接成功
|
||||
this.mqttClient.on('connect', () => {
|
||||
console.log('MQTT连接成功!');
|
||||
// 订阅主题
|
||||
this.mqttClient.subscribe('WJ_Get_NewControlSystem', (err) => {
|
||||
if (err) {
|
||||
console.log('订阅主题失败:', err);
|
||||
} else {
|
||||
console.log('订阅主题成功: WJ_Get_NewControlSystem');
|
||||
// 发送获取数据的消息
|
||||
this.sendMQTTMessage('WJ_Get_NewControlSystem', JSON.stringify({
|
||||
fun: 'GET',
|
||||
type: 'WJ_Get_NewControlSystem',
|
||||
content: 0
|
||||
}));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// 连接错误
|
||||
this.mqttClient.on('error', (err) => {
|
||||
console.error('MQTT连接错误:', err);
|
||||
});
|
||||
|
||||
// 连接关闭
|
||||
this.mqttClient.on('close', () => {
|
||||
console.log('MQTT连接关闭');
|
||||
});
|
||||
|
||||
// 重连
|
||||
this.mqttClient.on('reconnect', () => {
|
||||
console.log('MQTT正在重连...');
|
||||
});
|
||||
|
||||
// 收到消息
|
||||
this.mqttClient.on('message', (topic, message) => {
|
||||
console.log('收到MQTT消息:', topic, message.toString());
|
||||
try {
|
||||
// let data = JSON.parse(message.toString());
|
||||
// if (data.type == 'WJ_Get_NewControlSystem') {
|
||||
// this.control(data.content);
|
||||
// }
|
||||
} catch (error) {
|
||||
console.log('解析MQTT消息错误:', error);
|
||||
}
|
||||
});
|
||||
},
|
||||
sendMQTTMessage(topic, payload) {
|
||||
if (this.mqttClient && this.mqttClient.connected) {
|
||||
this.mqttClient.publish(topic, payload);
|
||||
console.log('MQTT消息发送成功:', topic, payload);
|
||||
} else {
|
||||
console.log('MQTT客户端未连接');
|
||||
if (!this.mqttClient) {
|
||||
this.initMQTT();
|
||||
}
|
||||
setTimeout(() => {
|
||||
this.sendMQTTMessage(topic, payload);
|
||||
}, 1000);
|
||||
}
|
||||
},
|
||||
toback() {
|
||||
uni.navigateBack()
|
||||
},
|
||||
selectShow(val, index) {
|
||||
val.isShow = true
|
||||
},
|
||||
submitDevice() {
|
||||
let smallParam = this.smallArr.reduce((pre, cur) => {
|
||||
pre[cur.prop] = cur.type == "Switch" ? cur.value ? 1 : 0 : cur.value
|
||||
pre[cur.prop] = Number(pre[cur.prop])
|
||||
return pre
|
||||
}, {})
|
||||
this.sendMQTTMessage("WJ_Set_NewControlSystem", JSON.stringify({
|
||||
fun: 'SET',
|
||||
type: 'WJ_Set_NewControlSystem',
|
||||
content: {
|
||||
...this.backData,
|
||||
params: {
|
||||
...this.backData.params,
|
||||
...smallParam
|
||||
}
|
||||
}
|
||||
}))
|
||||
},
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
@ -263,4 +306,4 @@ export default {
|
||||
box-shadow: 0px 4rpx 16rpx rgba(0, 0, 0, 0.1);
|
||||
border-radius: 8rpx;
|
||||
}
|
||||
</style>
|
||||
</style>
|
||||
|
||||
Reference in New Issue
Block a user