From a9cdc3c552868113dde79ee7ba8fefba857368d0 Mon Sep 17 00:00:00 2001 From: wangzhongjie Date: Mon, 24 Mar 2025 15:16:21 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0USB=E6=9C=8D=E5=8A=A1?= =?UTF-8?q?=E5=92=8C=E8=A7=86=E9=A2=91=E5=BD=95=E5=88=B6=E5=8A=9F=E8=83=BD?= =?UTF-8?q?=EF=BC=8C=E4=BC=98=E5=8C=96=E7=9B=B8=E5=85=B3=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E5=A4=84=E7=90=86=E5=92=8C=E6=8E=A5=E5=8F=A3=E8=B0=83=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- entry/src/main/ets/common/utils/tools.ts | 24 ++-- entry/src/main/ets/config/LogEnum.ets | 5 +- entry/src/main/ets/service/usbService.ts | 120 ------------------ entry/src/main/ets/utils/Common.ets | 13 ++ entry/src/main/ets/utils/USB.ets | 119 +++++++++++++++++ .../videoService.ts => utils/Video.ets} | 11 +- .../voiceService.ts => utils/Voice.ets} | 16 ++- 7 files changed, 161 insertions(+), 147 deletions(-) delete mode 100644 entry/src/main/ets/service/usbService.ts create mode 100644 entry/src/main/ets/utils/USB.ets rename entry/src/main/ets/{service/videoService.ts => utils/Video.ets} (97%) rename entry/src/main/ets/{service/voiceService.ts => utils/Voice.ets} (92%) diff --git a/entry/src/main/ets/common/utils/tools.ts b/entry/src/main/ets/common/utils/tools.ts index 5164af10..fed21a5e 100644 --- a/entry/src/main/ets/common/utils/tools.ts +++ b/entry/src/main/ets/common/utils/tools.ts @@ -1,17 +1,17 @@ import systemTime from '@ohos.systemDateTime'; -export function isSevenDaysAgo(date, days = 2) { - const today = new Date(); // 当前日期 - const target = new Date(date); // 需要判断的日期 - console.info("listFile succeed1", JSON.stringify(target)); - - const diff = today.getTime() - target.getTime(); // 计算两个日期之间的毫秒数差异 - const diffDays = diff / (1000 * 60 * 60 * 24); // 将毫秒转换为天数 - console.info("listFile succeed2", JSON.stringify(diffDays)); - // 如果差异天数正好是2,则原日期是当前日期的前2天 - console.log('diffDays', diffDays, days) - return diffDays >= (Number(days)); -} +// export function isSevenDaysAgo(date, days = 2) { +// const today = new Date(); // 当前日期 +// const target = new Date(date); // 需要判断的日期 +// console.info("listFile succeed1", JSON.stringify(target)); +// +// const diff = today.getTime() - target.getTime(); // 计算两个日期之间的毫秒数差异 +// const diffDays = diff / (1000 * 60 * 60 * 24); // 将毫秒转换为天数 +// console.info("listFile succeed2", JSON.stringify(diffDays)); +// // 如果差异天数正好是2,则原日期是当前日期的前2天 +// console.log('diffDays', diffDays, days) +// return diffDays >= (Number(days)); +// } // export async function writeLog(path,param){ // return diff --git a/entry/src/main/ets/config/LogEnum.ets b/entry/src/main/ets/config/LogEnum.ets index 679e1f61..9513281f 100644 --- a/entry/src/main/ets/config/LogEnum.ets +++ b/entry/src/main/ets/config/LogEnum.ets @@ -1,3 +1,6 @@ export const DbTag = '[DBTag]'; -export const SerialPortTag = '[SerialPortTag]'; \ No newline at end of file +export const SerialPortTag = '[SerialPortTag]'; + +// usb tag +export const UsbTag = '[UsbTag]'; \ No newline at end of file diff --git a/entry/src/main/ets/service/usbService.ts b/entry/src/main/ets/service/usbService.ts deleted file mode 100644 index 162ec92b..00000000 --- a/entry/src/main/ets/service/usbService.ts +++ /dev/null @@ -1,120 +0,0 @@ -// 导入USB接口api包。 -import usb from '@ohos.usbManager'; -const LOGTAG = 'USBSERVICES' - - -//字符串转字节 -function stringToArr(str){ - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - return arr -} - -//plc数据转成无锡科研所usb字节数据 -function plcStrToWXCodeArr(wuXiDataStr){ - const arr = stringToArr(wuXiDataStr); - //数据包总长度 有效长度 - let packetSize = 65,maxDataSize = 63; - let packetArr = [] - const loop = Math.ceil(arr.length / maxDataSize) - for(let i = 0; i< loop; i++){ - const thisPacket = arr.slice(i * maxDataSize,(i + 1) * maxDataSize) - const oSize = maxDataSize - thisPacket.length; - //补齐0x00 - if(oSize > 0){ - let oSizeArr = [] - for(let j = 0;j < oSize;j++){oSizeArr.push(0x00)} - packetArr.push([thisPacket.length].concat(thisPacket).concat(oSizeArr)); - }else{ - packetArr.push([thisPacket.length].concat(thisPacket)); - } - } - return packetArr -} - -export default class UsbService{ - private devicepipe : usb.USBDevicePipe - private outEndpoint: usb.USBEndpoint - public isWXUSBDevice:Boolean - - constructor() { - //是否是无锡检测设备 - this.isWXUSBDevice = false - this.devicepipe - this.init() - } - - init = async()=>{ - // 获取设备列表。 - let deviceList : Array = usb.getDevices(); - - deviceList.forEach(async (device:usb.USBDevice) => { - const {vendorId,productId} = device; - console.log(LOGTAG,JSON.stringify(device)); - //无锡所检测设备接入 - if(vendorId === 6790 && productId === 58409){ - // if(vendorId === 2385 && productId === 5734){ - // 申请操作指定的device的操作权限。 - try { - let bool = usb.hasRight(device.name); - console.info(LOGTAG,'bool =>' + bool) - const isExit = await usb.requestRight(device.name); - console.info(LOGTAG,'isExit =>' + isExit) - if(isExit){ - let devicepipe : usb.USBDevicePipe = usb.connectDevice(device); - let interfaces = device.configs[0].interfaces[0]; - let ret = usb.claimInterface(devicepipe, interfaces,true); - console.info(LOGTAG,'ret =>' + ret); - - if(ret === 0 ){ - let outEndpoint : usb.USBEndpoint = interfaces.endpoints[1]; - let inEndpoint : usb.USBEndpoint = interfaces.endpoints[0]; - this.isWXUSBDevice = true; - this.devicepipe = devicepipe - this.outEndpoint = outEndpoint - - }else{ - console.info(LOGTAG,'usb claimInterface failed') - } - - }else{ - console.info(LOGTAG,'isExit =>' +'false') - } - - } catch (e) { - console.info(LOGTAG,'e=>' + JSON.stringify(e)) - } - - } - }); - - } - - sendUSB =async (wuXiDataStr) => { - console.info(LOGTAG,'正在发送数据') - const {devicepipe,isWXUSBDevice,outEndpoint} = this; - console.info(LOGTAG,'正在发送数据') - if(isWXUSBDevice){ - console.info(LOGTAG,wuXiDataStr) - const codeArr = plcStrToWXCodeArr(wuXiDataStr); - for(let i = 0; i < codeArr.length;i++){ - try { - console.info(LOGTAG,'正在发送数据') - const f = await usb.bulkTransfer(devicepipe, outEndpoint, new Uint8Array(codeArr[i])) - console.info(LOGTAG,'发送成功数据长度为:' + f) - } catch (e) { - console.info(LOGTAG,JSON.stringify(e)) - } - } - }else{ - console.info(LOGTAG,'usb设备初始化失败') - } - - } -} - - - -// export default initUsbServicesFn diff --git a/entry/src/main/ets/utils/Common.ets b/entry/src/main/ets/utils/Common.ets index aae81ac8..617eec05 100644 --- a/entry/src/main/ets/utils/Common.ets +++ b/entry/src/main/ets/utils/Common.ets @@ -21,4 +21,17 @@ export function IsDaysAgo(date: string | number | Date, days: number = 2): boole const diffDays = today.diff(target, 'day'); // 如果差异天数大于等于指定天数,则返回 true return diffDays >= days; +} + +/** + * 字符串转字节数组 + * @param str + * @returns + */ +export function StringToBytes(str: string): Uint8Array { + const bytes = new Uint8Array(str.length); + for (let i = 0; i < str.length; i++) { + bytes[i] = str.charCodeAt(i); + } + return bytes; } \ No newline at end of file diff --git a/entry/src/main/ets/utils/USB.ets b/entry/src/main/ets/utils/USB.ets new file mode 100644 index 00000000..9356bb72 --- /dev/null +++ b/entry/src/main/ets/utils/USB.ets @@ -0,0 +1,119 @@ +// 导入USB接口api包。 +import usb from '@ohos.usbManager'; +import { UsbTag } from '../config'; +import { StringToBytes } from './Common'; + + +//plc数据转成无锡科研所usb字节数据 +function plcStrToWXCodeArr(wuXiDataStr: string) { + // const arr = stringToArr(wuXiDataStr); + const arr = StringToBytes(wuXiDataStr); + // 数据包总长度和有效长度 + const maxDataSize: number = 63; + + // 存储所有数据包的数组 + const packetArr: number[][] = []; + + // 计算需要的数据包数量 + const loop: number = Math.ceil(arr.length / maxDataSize); + + for (let i = 0; i < loop; i++) { + // 截取当前数据包的数据 + const thisPacket: number[] = Array.from(arr.slice(i * maxDataSize, (i + 1) * maxDataSize)); + + // 计算需要补齐的长度 + const oSize: number = maxDataSize - thisPacket.length; + + // 创建当前数据包 + const packet: number[] = [thisPacket.length, ...thisPacket]; + + // 如果需要补齐,则填充 0x00 + if (oSize > 0) { + packet.push(...new Array(oSize).fill(0x00)); + } + + // 将当前数据包添加到结果数组中 + packetArr.push(packet); + } + + return packetArr; +} + +export default class UsbService { + public isWXUSBDevice: Boolean + private devicepipe: usb.USBDevicePipe + private outEndpoint: usb.USBEndpoint + sendUSB = async (wuXiDataStr: string) => { + console.info(UsbTag, '正在发送数据') + console.info(UsbTag, '正在发送数据') + if (this.isWXUSBDevice) { + console.info(UsbTag, wuXiDataStr) + const codeArr = plcStrToWXCodeArr(wuXiDataStr); + for (let i = 0; i < codeArr.length; i++) { + try { + console.info(UsbTag, '正在发送数据') + const f = await usb.bulkTransfer(this.devicepipe, this.outEndpoint, new Uint8Array(codeArr[i])) + console.info(UsbTag, '发送成功数据长度为:' + f) + } catch (e) { + console.info(UsbTag, JSON.stringify(e)) + } + } + } else { + console.info(UsbTag, 'usb设备初始化失败') + } + + } + init = async () => { + // 获取设备列表。 + let deviceList: Array = usb.getDevices(); + + deviceList.forEach(async (device: usb.USBDevice) => { + console.log(UsbTag, JSON.stringify(device)); + //无锡所检测设备接入 + if (device.vendorId === 6790 && device.productId === 58409) { + // if(vendorId === 2385 && productId === 5734){ + // 申请操作指定的device的操作权限。 + try { + let bool = usb.hasRight(device.name); + console.info(UsbTag, 'bool =>' + bool) + const isExit = await usb.requestRight(device.name); + console.info(UsbTag, 'isExit =>' + isExit) + if (isExit) { + let devicepipe: usb.USBDevicePipe = usb.connectDevice(device); + let interfaces = device.configs[0].interfaces[0]; + let ret = usb.claimInterface(devicepipe, interfaces, true); + console.info(UsbTag, 'ret =>' + ret); + + if (ret === 0) { + let outEndpoint: usb.USBEndpoint = interfaces.endpoints[1]; + this.isWXUSBDevice = true; + this.devicepipe = devicepipe + this.outEndpoint = outEndpoint + + } else { + console.info(UsbTag, 'usb claimInterface failed') + } + + } else { + console.info(UsbTag, 'isExit =>' + 'false') + } + + } catch (e) { + console.info(UsbTag, 'e=>' + JSON.stringify(e)) + } + + } + }); + + } + + constructor() { + //是否是无锡检测设备 + this.isWXUSBDevice = false + this.devicepipe + this.init() + } +} + + +// export default initUsbServicesFn diff --git a/entry/src/main/ets/service/videoService.ts b/entry/src/main/ets/utils/Video.ets similarity index 97% rename from entry/src/main/ets/service/videoService.ts rename to entry/src/main/ets/utils/Video.ets index b072c4e6..f04ff315 100644 --- a/entry/src/main/ets/service/videoService.ts +++ b/entry/src/main/ets/utils/Video.ets @@ -1,13 +1,13 @@ import photoAccessHelper from '@ohos.file.photoAccessHelper'; import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import { dateFormat, getCurrentTime, isSevenDaysAgo } from '../common/utils/tools'; -// import rtsp_server from '@ohos.rtsprecord'; +import { dateFormat, getCurrentTime } from '../common/utils/tools'; import record from '@ohos.rtsprecord'; import { FileHelper } from '../common/service/FileHelper'; import FileUtil from '../common/utils/File'; import { GlobalConfig } from '../config'; import promptAction from '@ohos.promptAction'; import common from '@ohos.app.ability.common'; +import { IsDaysAgo } from './Common'; const rtsp_server = record.createServer(); //开始录屏 @@ -50,7 +50,6 @@ export async function startRecordVideo(param, td, context, dir, path?, index?) { fileName = `${date}_${path}_${index || num}.mp4` } - // @ts-ignore var recordResult = rtsp_server.startRecordVideo(context, video_uri, fileName, date, dir); const handleId = recordResult.dataInt; reslove(handleId) @@ -68,7 +67,6 @@ export async function endRecordVideo(record_handleObj) { for (let key in record_handleObj) { if (rtsp_server != null && record_handleObj[key] > 0) { console.log(`Rtsprecord endRecordVideo begin`); - // @ts-ignore var recordResult = rtsp_server.endRecordVideo(record_handleObj[key]); console.log(`Rtsprecord endRecordVideo record_handle` + record_handleObj[key].dataInt + ` filename:` + record_handleObj[key].fileName); @@ -144,7 +142,7 @@ export async function getUserAlbumItemByDisplayName(displayName: string, day?, const albums = await fetchResult.getLastObject(); console.log('get getUserAlbumItemByDisplayName album111', albums.albumName) - if (isSevenDaysAgo(albums.albumName, day)) { + if (IsDaysAgo(albums.albumName, day)) { deleteAllFileByPiC(albums.albumName, type) } console.log('get getUserAlbumItemByDisplayName album',) @@ -204,7 +202,7 @@ export async function delPic(day: number, type: number) { let albumName = albums[i].albumName // isSevenDaysAgo(albumName, day) console.log('albumNamealbumName', albumName) - if (isSevenDaysAgo(albumName, day) && albumName != 'jt' && albumName != 'pz') { + if (IsDaysAgo(albumName, day) && albumName != 'jt' && albumName != 'pz') { deleteAllFileByPiC(albumName, type) } @@ -220,7 +218,6 @@ export async function takePhoto(param, context, dir, flag = 1, callback?) { console.log('baoyihubaoyihu', video_uri, flag) console.log(`baoyihu Rtsprecord baohaowen getVideoSnapshot fileName:` + fileName); - // @ts-ignore // var snapResult = rtsp_server.getVideoSnapshot(context, video_uri, '', dir); if (flag == 0) { rtsp_server.detectVideoSnapshotSize(video_uri, fileName, (err, snapResult) => { diff --git a/entry/src/main/ets/service/voiceService.ts b/entry/src/main/ets/utils/Voice.ets similarity index 92% rename from entry/src/main/ets/service/voiceService.ts rename to entry/src/main/ets/utils/Voice.ets index e71fae9c..18496c2a 100644 --- a/entry/src/main/ets/service/voiceService.ts +++ b/entry/src/main/ets/utils/Voice.ets @@ -1,8 +1,10 @@ import media from '@ohos.multimedia.media'; -import App from '@system.app'; +import { BusinessError } from '@ohos.base'; + +type AVPlayerCallback = (status: string, val?: string) => void; export class voiceService { - private avPlayer: any = null; + private avPlayer: media.AVPlayer = null; private fileSize: number = -1; private fd: number = 0; private playerName: string = ''; @@ -10,7 +12,7 @@ export class voiceService { private endFlag: Boolean = false; private mediaArray: Array = []; - constructor(callBack) { + constructor(callBack: AVPlayerCallback) { // 创建avPlayer实例对象 media.createAVPlayer().then(video => { this.avPlayer = video @@ -21,11 +23,11 @@ export class voiceService { } // 注册avplayer回调函数 - setAVPlayerCallback(callBack) { + setAVPlayerCallback(callBack: AVPlayerCallback) { console.log('jiangsong avPlayerFdSrc setAVPlayerCallback begin') // error回调监听函数,当avPlayer在操作过程中出现错误时调用reset接口触发重置流程 - this.avPlayer.on('error', (err) => { + this.avPlayer.on('error', (err: BusinessError) => { console.error(`Invoke avPlayer failed, code is ${err.code}, message is ${err.message}`); this.avPlayer.reset(); // 调用reset重置资源,触发idle状态 }) @@ -52,7 +54,7 @@ export class voiceService { console.info('jiangsong AVPlayerstate initialized called.'); this.avPlayer.prepare().then(() => { console.info('jiangsong AVPlayer prepare succeeded.'); - }, (err) => { + }, (err: BusinessError) => { console.error(`jiangsong Invoke prepare failed, code is ${err.code}, message is ${err.message}`); }); callBack('initialized'); @@ -91,7 +93,7 @@ export class voiceService { // 以下为使用资源管理接口获取打包在HAP内的媒体资源文件并通过fdSrc属性进行播放示例 avPlayerFdSrc(name) { - const context=AppStorage.get('context') + const context = AppStorage.get('context') context.resourceManager.getRawFd(name, async (error, value) => { if (error != null) { console.log(`jiangsong callback getRawFd failed error code: ${error.code}, message: ${error.message}.`);