xiaokuaisong-shopapp/uniapp05/components/gprint/websocket.js

190 lines
4.5 KiB
JavaScript
Raw Normal View History

2024-10-18 08:05:19 +00:00
import {
websocketStore
} from '../../pinia/webSocket.js'
import {
getBaseUrl
} from '../../api/requets'
export class WebsocketUtil {
constructor(url, time) {
this.is_open_socket = false; // 避免重复连接
this.url = url; // 地址
this.timeout = time; // 心跳检测时间间隔
this.heartbeatInterval = null; // 心跳检测定时器
this.reconnectTimeOut = null; // 重连定时器
try {
// if (isMerchantLoggedInLocally()) {
if (!this.is_open_socket) {
this.connectSocketInit();
}
// }
} catch (e) {
console.log('连接失败', e);
this.is_open_socket = false;
this.reconnect();
}
}
// 创建 WebSocket 连接
connectSocketInit() {
this.socketTask = uni.connectSocket({
url: this.url,
success: (res) => {
console.log(res)
}
});
this.socketTask.onOpen((res) => {
console.log("WebSocket连接正常");
clearTimeout(this.reconnectTimeOut);
clearTimeout(this.heartbeatInterval);
this.is_open_socket = true;
this.start();
setTimeout(async () => {
await this.Close()
}, 120000)
this.getMessage((res) => {});
});
this.socketTask.onClose(async () => {
await this.reconnect();
})
}
// 主动关闭websocket
Close() {
if (!this.is_open_socket) {
return
}
this.is_open_socket = false
this.socketTask.close({
success() {
console.log('websocket已经关闭')
}
});
}
// 开启心跳检测(可用于维持连接,不发送具体消息)
start() {
this.heartbeatInterval = setInterval(() => {
console.log("心跳检测");
this.send()
this.getConnectedBluetooth()
// 这里可以保留心跳逻辑,但不发送具体消息
}, this.timeout);
}
getConnectedBluetooth() {
let that = this
let arr = [uni.getStorageSync('characteristicId')]
uni.getConnectedBluetoothDevices({
services: arr,
fail(res) {
uni.openBluetoothAdapter({
success(res) {
uni.createBLEConnection({
deviceId: uni.getStorageSync('deviceId'),
success: res => {
setTimeout(() => {
uni.getBLEDeviceServices({
deviceId: uni.getStorageSync(
'deviceId'),
success: res => {
for (let i = 0; i < res
.services
.length; i++) {
let serviceId = res
.services[i]
.uuid
that.getBLEDeviceCharacteristics(
uni
.getStorageSync(
'deviceId'
),
serviceId);
}
}
})
}, 1000)
}
})
},
fail(error) {
uni.showToast({
title: '请打开蓝牙',
icon: 'error'
})
}
})
}
})
}
/*
获取蓝牙设备某个服务中所有特征值(characteristic)
characteristic:
uuid:蓝牙设备特征值的 uuid
properties:该特征值支持的操作类型
*/
getBLEDeviceCharacteristics(deviceId, serviceId) {
console.log(1)
uni.getBLEDeviceCharacteristics({
// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
deviceId: deviceId,
serviceId,
success: (res) => {
console.log(2)
let result = JSON.parse(JSON.stringify(res))
for (let i = 0; i < result.characteristics.length; i++) {
if (result.characteristics[i].properties.write == true) {
let uuid = result.characteristics[i].uuid
uni.setStorageSync('serviceId', serviceId)
uni.setStorageSync('characteristicId', uuid)
console.log(uni.getStorageSync('serviceId'))
console.log(uni.getStorageSync('characteristicId'))
break
}
}
}
})
}
send() {
let userId = uni.getStorageSync('userInfo')?.userId
var messageVO = {
"type": 1,
"userId": userId,
"toUserId": userId,
"content": "ok"
}
this.socketTask.send({
data: JSON.stringify(messageVO),
success: (res) => {
console.log('已发送')
}
});
}
// 重连逻辑
reconnect() {
clearInterval(this.heartbeatInterval);
clearTimeout(this.reconnectTimeOut);
console.log('监听到关闭了')
if (!this.is_open_socket) {
this.reconnectTimeOut = setTimeout(() => {
console.log('已重连websocket')
this.connectSocketInit();
}, 300);
}
}
// 外部获取消息
getMessage(callback) {
console.log('小猫老弟');
this.socketTask.onMessage((res) => {
let websocket = websocketStore();
let obj = JSON.parse(res.data);
console.log(obj.content, '你好');
console.log(obj)
websocket.getMyOrders(obj.content);
return callback(res);
});
}
}