更新记录
1.0.0(2025-04-13)
- usb授权
- 打开关闭usb串口,收发数据
平台兼容性
App |
快应用 |
微信小程序 |
支付宝小程序 |
百度小程序 |
字节小程序 |
QQ小程序 |
HBuilderX 3.6.8,Android:4.4,iOS:不支持,HarmonyNext:不支持 |
× |
× |
× |
× |
× |
× |
钉钉小程序 |
快手小程序 |
飞书小程序 |
京东小程序 |
鸿蒙元服务 |
× |
× |
× |
× |
× |
H5-Safari |
Android Browser |
微信浏览器(Android) |
QQ浏览器(Android) |
Chrome |
IE |
Edge |
Firefox |
PC-Safari |
× |
× |
× |
× |
× |
× |
× |
× |
× |
OTG USB串口、CP210X、CDC、FTDI、PL2303、CH34X等
开发文档
整体流程:监听USB设备的插拔-》获取USB设备列表-》选择其中一个设备-》请求设备权限-》打开设备-》设置波特率/数据位/停止位等 -》监听接收数据-》发送数据
接口
import {
UTSOTGUsb,
UTSUsbManager
} from "@/uni_modules/wrs-uts-otgusb"
// 一个设备对应一个变量,多个设备采用多个变量
let otgUsb = new UTSOTGUsb()
// let otgUsb1 = new UTSOTGUsb()
// let otgUsb2 = new UTSOTGUsb()
// 注册USB插拔监听
UTSUsbManager.registerReceiver(this.action, (resp) => {
let action = resp.action;
switch (action) {
// USB授权结果
case this.action: {
let granted = resp.granted
let action = resp.action
let device = resp.device
this.showMsg("有USB设备授权结果:" + JSON.stringify(resp));
if (granted) {
this.showMsg("有USB设备授权成功");
} else {
this.showMsg("有USB设备授权失败");
}
}
break;
// 监测到有USB拔出
case "android.hardware.usb.action.USB_DEVICE_DETACHED": {
this.showMsg("有USB设备拔出:" + JSON.stringify(resp));
}
break;
// 检测到有USB插入
case "android.hardware.usb.action.USB_DEVICE_ATTACHED": {
// USB插入时,有些设备会监听到USB插入-USB设备拔出-USB设备插入这么个过程,可能是系统或USB设备的bug
this.showMsg("有USB设备插入:" + JSON.stringify(resp));
}
break;
default:
break;
}
})
UTSUsbManager.unregisterReceiver()
let resp = UTSUsbManager.getDeviceList()
let devices = resp.devices;
权限结果在registerReceiver里回调
let device = devices[index];
let deviceId = device.deviceId;
let requestCode = this.requestCode;
let action = this.action;
// FLAG_IMMUTABLE = 67108864
// FLAG_ONE_SHOT = 1073741824
// FLAG_MUTABLE = 33554432
let flags = 67108864;
UTSUsbManager.requestPermission(deviceId, requestCode, action, flags);
let params = {}
params.deviceId = device.deviceId
let suc = otgUsb.open(params)
if(suc) {
this.showMsg("打开成功")
} else {
this.showMsg("打开失败")
}
// 设置监听接收数据
otgUsb.onRead((resp)=>{
let data = resp.data
this.showMsg("收到数据:" + JSON.stringify(resp))
})
otgUsb.setBaudrate(9600)
// 一般都是设置为8,取值范围5~8
otgUsb.setDataBits(8)
// 1: STOP_BITS_1 2: STOP_BITS_2 3: STOP_BITS_15
otgUsb.setStopBits(1)
// 0: FLOW_CONTROL_OFF 1: FLOW_CONTROL_RTS_CTS 2: FLOW_CONTROL_DSR_DTR 3: FLOW_CONTROL_XON_XOFF
otgUsb.setFlowControl(0)
let params = {}
// data为十六进制数据
params.data = [0x01, 0xFF]
otgUsb.write(params)
otgUsb.close()
或者
otgUsb.syncClose()
otgUsb.setRTS(true)
otgUsb.setDTR(true)