Compare commits

...

5 Commits

14 changed files with 434 additions and 304 deletions

View File

@ -6,4 +6,7 @@ export const SerialPortTag = '[SerialPortTag]';
export const UsbTag = '[UsbTag]';
//voice tag
export const VoiceTag = '[VoiceTag]';
export const VoiceTag = '[VoiceTag]';
//video tag
export const VideoTag = '[VideoTag]';

View File

@ -1,10 +0,0 @@
/*
* @Author: wangzhongjie
* @Date: 2024-03-07 10:54:19
* @LastEditors: wangzhongjie
* @LastEditTime: 2024-03-07 11:15:11
* @Description:
* @Email: shutdown0630@163.com
*/
export * from "./global"
export * from "./judge"

View File

@ -7,6 +7,4 @@
* @Email: shutdown0630@163.com
*/
export const JudgeConfig={
}

View File

@ -0,0 +1,4 @@
export interface TakePhotoCallbackData {
fileSize: number;
errorCode: number
}

View File

@ -17,3 +17,5 @@ export * from "./CarCheck"
export * from "./api"
export * from "./TableColumn"
export * from "./Other"

View File

@ -367,8 +367,8 @@ struct Index {
GetSyncData<MASYSSETTableType>("MA_SYSSET").then((res: MASYSSETTableType[]) => {
res.forEach((element) => {
if (element.v_no === "305") {
delPic(Number(element.v_value), 1)
delPic(Number(element.v_value), 2)
delPic(Number(element.v_value), 1, this.context)
delPic(Number(element.v_value), 2, this.context)
}
});
});

View File

@ -1,6 +1,6 @@
import router from '@ohos.router'
import { CarCheckDataType } from '../model/CarCheck'
import { BaseInfoType } from '../model/Common'
import { BaseInfoType, CarInfoType } from '../model/Common'
import TopLogo from './compontents/TopLogo'
@Entry
@ -9,7 +9,7 @@ struct Index {
@State ratio: number = 1280 / 960
@State url: string = ''
@State baseInfo: BaseInfoType = {}
@State carInfo: CarCheckDataType = {}
@State carInfo: CarInfoType = {}
@State @Watch('outClick') outFlag: boolean = false;
build() {
@ -88,8 +88,8 @@ struct Index {
aboutToAppear() {
// this.vocObj = new voiceService(async (status, val, next) => {
// });
this.carInfo = AppStorage.get('carInfo')
this.baseInfo = AppStorage.get('baseinfo') as BaseInfoType
this.carInfo = AppStorage.get<CarInfoType>('carInfo')
this.baseInfo = AppStorage.get<BaseInfoType>('baseInfo')
}
outClick() {

View File

@ -711,10 +711,12 @@ struct UserInfo {
this.startExam = true
}
listData.id = index.toString()
// TODO 需要修改
// for (let i in listData) {
// listData[i] = decodeURI(listData[i])
// }
Object.keys(listData).forEach((key) => {
Reflect.set(listData, key, decodeURI(Reflect.get(listData, key)));
});
if (this.systemParam.Param828Str == '1' || this.systemParam.Param828Str == '2') {
// listData.ksy2=listData.ksy1;
listData.ksy2 = this.examinerLoginInfo.kgxm
@ -1402,15 +1404,3 @@ struct LabelBlock {
}
}
interface systemParam {
'Param341': boolean, //是否按顺序考试
'Param803Str': string, //开始考试前必须解开安全带或关车门
'Param612Str': string, //开始考试触发方式
'Param305Str': string, //视频保存天数
'Param352Str': string, //车上考试过一次就不能缺考
'Param828Str': string, //828考生待考界面安全员显示考试员
'Param770Str': string, //车上没有缺考功能
'Param830Str': string, //同一学员连续第二次考试时不再验证身份
'Param364': string, //考前上车准备
'Param398': string, //考前上车准备
}

View File

@ -55,11 +55,12 @@ struct Index {
TopLogo({ outFlag: $outFlag })
Flex({ justifyContent: FlexAlign.SpaceBetween }) {
Flex({ wrap: FlexWrap.Wrap, direction: FlexDirection.Row }) {
ForEach(this.videoArr, (item: VideoItemType, index) => {
ForEach(this.videoArr, (item: VideoItemType) => {
Video({
src: this.openFlag ?
`rtsp://${this.param.userName}:${this.param.pwd}@${this.param.ip}:${this.param.port}/h264/ch${this.getTdValueByTd(item.td)}/main/av_stream` :
'',
// `rtsp://${this.param.userName}:${this.param.pwd}@${this.param.ip}:${this.param.port}/h264/ch${this.param[item.td]}/main/av_stream` : '',
`rtsp://${this.param.userName}:${this.param.pwd}@${this.param.ip}:${this.param.port}/h264/ch${Reflect.get(this.param,
'port')}/main/av_stream` : '',
currentProgressRate: this.curRate,
controller: item.controller
})
@ -103,11 +104,11 @@ struct Index {
this.videoStartFlag = true
// for (let i = 1; i <= 4; i++) {
// if (this.param['videoRecord'+i]) {
// await this.getFileHandleCode(i)
// await this.getfilehandleCode(i)
// }
// }
for (let i = 1; i <= 4; i++) {
if (this.getVideoRecordValue(i)) {
if (Reflect.get(this.param, 'videoRecord' + i)) {
await this.getFileHandleCode(i);
}
}
@ -124,18 +125,19 @@ struct Index {
.margin({ bottom: 10 * this.ratio })
.onClick(() => {
// for (let i = 1; i <= 4; i++) {
// console.log('rocord_handle', i, JSON.stringify(this.rocordHandleObj))
// if (this.rocordHandleObj['rocord_handle'+i]) {
// endRecordVideo(this.rocordHandleObj['rocord_handle'+i])
// endRecordVideo(this.rocordHandleObj)
// this.rocordHandleObj['rocord_handle'+i] = 0
// }
// }
for (let i = 1; i <= 4; i++) {
const handle: ESObject = this.getRecordHandle(i);
if (handle) {
endRecordVideo(handle);
this.setRecordHandle(i, 0);
if (Reflect.get(this.rocordHandleObj, 'rocord_handle' + i)) {
Reflect.set(this.rocordHandleObj, 'rocord_handle' + i, 0);
}
}
endRecordVideo(this.rocordHandleObj);
promptAction.showToast({
message: '录像结束',
duration: 3000
@ -356,7 +358,11 @@ struct Index {
.onChange((value: string) => {
this.param.ip = value
})
TextInput({ text: this.getTdValueByIndex((Number(index) + 1)), controller: this.inputController })
// TextInput({ text: this.param['td'+(Number(index) + 1)], controller: this.inputController })
TextInput({
text: Reflect.get(this.param, 'td' + (Number(index) + 1)),
controller: this.inputController
})
.type(InputType.Normal)
.borderRadius(2)
.width(96 * this.ratio)
@ -366,7 +372,7 @@ struct Index {
.fontSize(this.inputFontSize * this.ratio)
.onChange((value: string) => {
// this.param['td'+(Number(index) + 1)] = value
this.setTdValue(Number(index) + 1, value)
Reflect.set(this.param, 'td' + (Number(index) + 1), value);
})
TextInput({ text: this.param.userName, controller: this.inputController })
.type(InputType.Normal)
@ -583,8 +589,8 @@ struct Index {
}
aboutToAppear() {
const radio = AppStorage.get('ratio') as number
this.ratio = radio
// this.ratio = globalThis.ratio
this.ratio = AppStorage.get<number>('ratio')
this.openFlag = true
const fileUtil = new FileUtil(this.context)
this.fileUtil = fileUtil
@ -592,105 +598,13 @@ struct Index {
}
async getFileHandleCode(td: number): Promise<void> {
return new Promise<void>(async (resolve, reject) => {
const record_handle: ESObject = await startRecordVideo(this.param, td, this.context, 'lp');
this.setRecordHandle(td, record_handle);
resolve();
});
}
return new Promise(async (resolve, reject) => {
const record_handle = await startRecordVideo(this.param, td, this.context, 'lp')
// this.rocordHandleObj['rocord_handle'+td] = record_handle
Reflect.set(this.rocordHandleObj, 'rocord_handle' + td, record_handle);
resolve()
})
getRecordHandle(index: number): ESObject {
switch (index) {
case 1:
return this.rocordHandleObj.rocord_handle1;
case 2:
return this.rocordHandleObj.rocord_handle2;
case 3:
return this.rocordHandleObj.rocord_handle3;
case 4:
return this.rocordHandleObj.rocord_handle4;
default:
return null;
}
}
getVideoRecordValue(index: number): boolean {
switch (index) {
case 1:
return this.param.videoRecord1;
case 2:
return this.param.videoRecord2;
case 3:
return this.param.videoRecord3;
case 4:
return this.param.videoRecord4;
default:
return false;
}
}
getTdValueByTd(td: string): string {
switch (td) {
case 'td1':
return this.param.td1;
case 'td2':
return this.param.td2;
case 'td3':
return this.param.td3;
case 'td4':
return this.param.td4;
default:
return '';
}
}
getTdValueByIndex(index: number): string {
switch (index) {
case 1:
return this.param.td1;
case 2:
return this.param.td2;
case 3:
return this.param.td3;
case 4:
return this.param.td4;
default:
return '';
}
}
setTdValue(index: number, value: string): void {
switch (index) {
case 1:
this.param.td1 = value;
break;
case 2:
this.param.td2 = value;
break;
case 3:
this.param.td3 = value;
break;
case 4:
this.param.td4 = value;
break;
}
}
setRecordHandle(td: number, record_handle: ESObject): void {
switch (td) {
case 1:
this.rocordHandleObj.rocord_handle1 = record_handle;
break;
case 2:
this.rocordHandleObj.rocord_handle2 = record_handle;
break;
case 3:
this.rocordHandleObj.rocord_handle3 = record_handle;
break;
case 4:
this.rocordHandleObj.rocord_handle4 = record_handle;
break;
}
}
outClick() {

View File

@ -13,7 +13,6 @@ import JudgeTask from './utils/judgeTask';
import { judgeConfig } from './utils/judgeConfig';
import UsbService from '../../service/usbService';
import { KF, LANE } from '../judgeSDK/api/judgeSDK.d';
import { endRecordVideo, saveStartRecordVideo } from '../../service/videoService';
import {
Array2Byte,
convertGpsCoord2,
@ -53,6 +52,8 @@ import {
examJudgeVersion
} from './api/index';
import { writeObjectOut } from '../../api/judge';
import { saveStartRecordVideo } from '../../utils/Video';
import common from '@ohos.app.ability.common';
const judgeTag = 'SURENJUN_JUDGE'
@ -143,6 +144,7 @@ export default class Judge {
}
}
public plcStr: string
private context: common.UIAbilityContext
private judgeUI
// 检测扣分、结束项目时该项目是否开始
checkProjectIsStart = async (xmdm, currentType: 1 | 2, kf?: KF) => {
@ -1252,7 +1254,6 @@ export default class Judge {
const bytes = await this.getMessageHeartbeat(true);
globalThis.judgeUdp.send(bytes)
}
await endExam()
} catch (e) {
console.info(judgeTag, JSON.stringify(e))
// setTimeout(() => {
@ -1260,6 +1261,7 @@ export default class Judge {
// router.back();
// }, 3000)
}
await endExam()
});
}
@ -1788,7 +1790,7 @@ export default class Judge {
avPlayer.playAudio([globalThis.singlePlay ? 'voice/ksks.wav' : 'voice/监管成功.mp3'])
if (!globalThis.singlePlay) {
this.videoData = await saveStartRecordVideo(`${name}_${kssycs}`)
this.videoData = await saveStartRecordVideo(`${name}_${kssycs}`, this.context)
}
const { examSubject, projectsObj } = this.judgeUI

View File

@ -3,6 +3,7 @@ import Prompt from '@system.prompt';
import url from '@ohos.url';
import fileuri from "@ohos.file.fileuri";
import mediaLibrary from '@ohos.multimedia.mediaLibrary';
import common from '@ohos.app.ability.common';
const TAG = 'VoiceAnnounce'
@ -125,7 +126,7 @@ class AVPlayer {
resolve()
});
try {
const context = AppStorage.get('context')
const context: common.UIAbilityContext = AppStorage.get('context')
this.avPlayer.fdSrc = await context.resourceManager.getRawFd(name);
} catch (e) {
Prompt.showToast({
@ -175,7 +176,6 @@ class AVPlayer {
// 注册avplayer回调函数
setAVPlayerCallback(callBack) {
this.avPlayer.on('error', (err) => {
this.avPlayer && this.avPlayer.stop()
this.avPlayer && this.avPlayer.reset()

View File

@ -0,0 +1,291 @@
import media from '@ohos.multimedia.media';
import common from '@ohos.app.ability.common';
import fs from '@ohos.file.fs';
export enum PlayStatus {
/**
* 闲置状态, Player刚被创建或者调用了reset方法之后, 进入该状态, 触发idle回调事件
*/
Idle,
/**
* 资源初始化, 调用setSource进入该状态, 触发initialized回调事件
*/
Init,
/**
* 已准备状态, 在Init状态调用prepare方法后进入该状态, 触发prepared回调事件
*/
Prepared,
/**
* 正在播放状态, Prepared/Paused/Completed状态调用play方法进入该状态, 触发playing回调事件
*/
Playing,
/**
* 暂停状态, 在Playing状态调用pause方法进入该状态, 触发paused回调事件
*/
Paused,
/**
* 播放至结尾状态, loop为false时播放到结尾进入该状态, 此时调用play会进入Playing状态和重播, 调用stop进入Stopped状态, 触发completed回调
*/
Completed,
/**
* 停止状态, Prepared/Playing/Paused/Completed状态调用stop方法进入该状态, 触发stopped回调
*/
Stopped,
/**
* 销毁状态, 调用release方法后进入该状态, 触发released回调
*/
Released,
/**
* 错误状态, 当播放引擎发生不可逆的错误进入该状态, 可以调用reset重置, 也可以调用release销毁重建, 触发error回调
*/
Error
}
interface PlayerOption {
mode: "audio" | "video"
loop: boolean
}
export type PlayerSourceType = "network" | "raw" | "local"
type PlayerEvent = media.AVPlayerState | "status"
interface PlayerSourceOption {
/**
* 资源类型 默认为network:网络类型, raw:app预置到resource/rawfile的文件, local:应用沙箱内文件
*/
type?: PlayerSourceType
/**
* type为network时, 传入网络url type为raw时, 传入相对路径 type为local时, 传入沙箱相对路径
*/
url: string
}
export class MediaPlayer {
private context: common.UIAbilityContext
private player?: media.AVPlayer
private option: PlayerOption = {
mode: "video",
loop: false
}
private callback: Map<PlayerEvent, Function[]> = new Map()
constructor(context: common.UIAbilityContext, option?: Partial<PlayerOption>) {
this.context = context
this.option.mode = option?.mode || "video"
this.option.loop = option?.loop || false
}
private _status: PlayStatus = PlayStatus.Idle
/**
* 获取当前播放器状态
* @returns
*/
get status() {
return this._status
}
/**
* 获取媒体资源长度
* @returns
*/
get duration() {
return this.player?.duration ?? 0
}
/**
* 获取媒体资源当前播放进度
* @returns
*/
get current() {
return this.player?.currentTime ?? 0
}
/**
* 设置avplayer输出控件id 仅播放视频需要
* @param id
*/
set surfaceId(id: string) {
this.player!.surfaceId = id
}
/**
* 设置播放音量
* @param volume
*/
set volume(volume: number) {
this.player?.setVolume(volume)
}
/**
* 设置是否循环播放
* @param loop
*/
set loop(loop: boolean) {
if ([PlayStatus.Prepared, PlayStatus.Playing, PlayStatus.Paused, PlayStatus.Completed].includes(this._status)) {
this.player!.loop = loop
}
this.option.loop = loop
}
async create() {
this.player = await media.createAVPlayer()
this.registerPlayerCallback()
}
/**
* 设置播放资源
* @param option
*/
async setSource(option: PlayerSourceOption) {
let fdPath = 'fd://';
if (option.type === "raw") {
let fileDescriptor = await this.context.resourceManager.getRawFd(option.url)
this.player!.fdSrc = fileDescriptor
} else if (option.type === "local") {
let path = this.context.filesDir + option.url;
let file = fs.openSync(path)
this.player!.url = fdPath + file.fd
} else {
this.player!.url = option.url
}
}
async prepare() {
await this.player?.prepare()
}
async play() {
await this.player?.play()
}
async pause() {
await this.player?.pause()
}
async stop() {
await this.player?.stop()
}
async reset() {
await this.player?.reset()
}
async release() {
await this.player?.release()
this.callback.clear()
}
seek(time: number, mode?: media.SeekMode) {
this.player?.seek(time, mode || media.SeekMode.SEEK_PREV_SYNC)
}
speed(speed: media.PlaybackSpeed) {
this.player?.setSpeed(speed)
}
on(type: PlayerEvent, cb: Function) {
if (!this.callback.has(type)) {
this.callback.set(type, [])
}
this.callback.get(type)?.push(cb)
}
once(type: PlayerEvent, cb: Function) {
let onceFn = () => {
cb()
this.off(type, onceFn)
}
this.on(type, onceFn)
}
off(type: PlayerEvent, cb: Function) {
if (!this.callback.has(type)) {
return
}
let cbs = this.callback.get(type)
cbs = cbs?.filter(el => el != cb)
}
private registerPlayerCallback() {
this.player?.on("stateChange", (state, reason) => {
switch (state) {
case "idle": {
this._status = PlayStatus.Idle
this.callback.get("idle")?.forEach(cb => {
cb()
})
break
}
case "initialized": {
this._status = PlayStatus.Init
this.callback.get("initialized")?.forEach(cb => {
cb()
})
this.prepare()
break
}
case "prepared": {
this._status = PlayStatus.Prepared
this.loop = this.option.loop
this.callback.get("prepared")?.forEach(cb => {
cb()
})
break
}
case "playing": {
this._status = PlayStatus.Playing
this.loop = this.option.loop
this.callback.get("playing")?.forEach(cb => {
cb()
})
break
}
case "paused": {
this._status = PlayStatus.Paused
this.loop = this.option.loop
this.callback.get("paused")?.forEach(cb => {
cb()
})
break
}
case "completed": {
this._status = PlayStatus.Completed
this.loop = this.option.loop
this.callback.get("completed")?.forEach(cb => {
cb()
})
break
}
case "stopped": {
this._status = PlayStatus.Stopped
this.callback.get("stopped")?.forEach(cb => {
cb()
})
break
}
case "released": {
this._status = PlayStatus.Released
this.callback.get("released")?.forEach(cb => {
cb()
})
break
}
case "error": {
this._status = PlayStatus.Error
this.callback.get("error")?.forEach(cb => {
cb()
})
break
}
default:
break
}
this.callback.get("status")?.forEach(cb => {
cb(this._status, reason)
})
})
}
}

View File

@ -1,13 +1,15 @@
import photoAccessHelper from '@ohos.file.photoAccessHelper';
import dataSharePredicates from '@ohos.data.dataSharePredicates';
import { dateFormat, getCurrentTime } from '../common/utils/tools';
import photoAccessHelper from '@ohos.file.photoAccessHelper'
import dataSharePredicates from '@ohos.data.dataSharePredicates'
import record from '@ohos.rtsprecord';
import promptAction from '@ohos.promptAction';
import { GetCurrentTime, IsDaysAgo } from './Common';
import { RecordHandleType, TakePhotoCallbackData, VideoConfig } from '../model';
import common from '@ohos.app.ability.common';
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';
import dayTs from './Date';
import { GlobalConfig, VideoTag } from '../config';
import { BusinessError } from '@ohos.base';
const rtsp_server = record.createServer();
//开始录屏
@ -25,137 +27,89 @@ const FILE_ASSET_FETCH_COLUMNS = [
photoAccessHelper.PhotoKeys.ORIENTATION,
photoAccessHelper.PhotoKeys.FAVORITE,
photoAccessHelper.PhotoKeys.TITLE,
// photoAccessHelper.PhotoKeys.POSITION,
// photoAccessHelper.PhotoKeys.DATE_TRASHED,
// photoAccessHelper.PhotoKeys.HIDDEN
photoAccessHelper.PhotoKeys.POSITION,
photoAccessHelper.PhotoKeys.DATE_TRASHED,
photoAccessHelper.PhotoKeys.HIDDEN
];
// const rtsp_server = record.createServer();
export async function startRecordVideo(param, td, context, dir, path?, index?) {
return new Promise(async (reslove, reject) => {
// const date=dateFormat(new Date).split(' ')[0]
// const folderPath = await fileUtil.initFolder(`/PLC/${date}/${dir}`);
var video_uri = `rtsp://${param.userName}:${param.pwd}@${param.ip}:${param.port}/h264/ch${td}/main/av_stream`;
export async function startRecordVideo(param: VideoConfig, td: number, context: common.UIAbilityContext, dir: string,
path?: string,
index?: number): Promise<number> {
return new Promise(async (resolve, reject) => {
let video_uri = `rtsp://${param.userName}:${param.pwd}@${param.ip}:${param.port}/h264/ch${td}/main/av_stream`;
if (rtsp_server != null) {
console.log(`Rtsprecord startRecordVideo begin,video_uri`, video_uri);
console.log(VideoTag, `Rtsprecord startRecordVideo begin`, video_uri);
const num = Math.floor(Math.random() * 10000)
let fileName
const time = await getCurrentTime()
let fileName: string
const time = await GetCurrentTime()
const date = time.split(' ')[0]
if (!path) {
fileName = `${date}_movie_record${num}.mp4`
} else {
fileName = `${date}_${path}_${index || num}.mp4`
}
var recordResult = rtsp_server.startRecordVideo(context, video_uri, fileName, date, dir);
fileName = !path ? `${date}_movie_record${num}.mp4` : `${date}_${path}_${index || num}.mp4`;
let recordResult = rtsp_server.startRecordVideo(context, video_uri, fileName, date);
const handleId = recordResult.dataInt;
reslove(handleId)
resolve(handleId)
} else {
console.log(`Rtsprecord startRecordVideo rtsp_server isnull`);
reslove(0)
console.log(VideoTag, `Rtsprecord startRecordVideo rtsp_server isnull`);
resolve(0)
}
console.log(`Rtsprecord startRecordVideo end`);
console.log(VideoTag, `Rtsprecord startRecordVideo end`);
})
}
//结束录屏
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`);
var recordResult = rtsp_server.endRecordVideo(record_handleObj[key]);
console.log(`Rtsprecord endRecordVideo record_handle` + record_handleObj[key].dataInt + ` filename:` +
record_handleObj[key].fileName);
export async function endRecordVideo(record_handleObj: RecordHandleType) {
const handleIds = [
record_handleObj.rocord_handle1,
record_handleObj.rocord_handle2,
record_handleObj.rocord_handle3,
record_handleObj.rocord_handle4
];
for (const handleId of handleIds) {
if (rtsp_server != null && handleId > 0) {
console.log(`Rtsprecord endRecordVideo begin`);
const recordResult = rtsp_server.endRecordVideo(handleId);
console.log(`Rtsprecord endRecordVideo record_handle` + recordResult.dataInt + ` filename:` +
recordResult.fileName);
} else {
console.log(`Rtsprecord endRecordVideo handleId isnull`);
}
}
}
export async function saveStartRecordVideo(path) {
return new Promise(async (reslove, reject) => {
const context = AppStorage.get('context')
export async function saveStartRecordVideo(path: string, context?: common.UIAbilityContext): Promise<RecordHandleType> {
return new Promise(async (resolve, reject) => {
const fileUtil = new FileUtil(context)
const fileHelper = new FileHelper();
const date = dateFormat(new Date).split(' ')[0]
// const date = dateFormat(new Date).split(' ')[0]
const date = dayTs().format('YYYY-MM-DD HH:mm:ss').split(' ')[0]
fileHelper.createAlbum(date);
// const folderPath = await fileUtil.initFolder(`/${path}/${date}`);
const data = await fileUtil.readFile(GlobalConfig.comoonfileWriteAddress + '/config/config3.txt');
const param = JSON.parse(data)
const record_handle = {
1: 0,
2: 1,
3: 2,
4: 3
const data: string = await fileUtil.readFile(GlobalConfig.comoonfileWriteAddress + '/config/config3.txt');
const param: VideoConfig = JSON.parse(data)
const record_handle: RecordHandleType = {
rocord_handle1: 0,
rocord_handle2: 1,
rocord_handle3: 2,
rocord_handle4: 3
}
for (let i = 1; i <= 4; i++) {
if (param['videoRecord'+i]) {
console.log('pathpath0', path)
// if (param['videoRecord'+i]) {
//
// record_handle[i] = await getFilehandleCode(i, param, date, path, i)
// }
if (Reflect.get(param, 'videoRecord' + i)) {
// Reflect.set(record_handle, i, await getFileHandleCode(i, param, date, path, i));
const data = await startRecordVideo(param, i, context, date, path, i);
Reflect.set(record_handle, i, data);
record_handle[i] = await getfilehandleCode(i, param, date, path, i)
}
}
reslove(record_handle)
resolve(record_handle)
})
}
async function getfilehandleCode(td, param, dir, path, index) {
return new Promise(async (reslove, reject) => {
console.log('pathpath1', path)
const context = AppStorage.get('context')
const record_handle = await startRecordVideo(param, td, context, dir, path, index)
// this.rocordHandleObj['rocord_handle'+td] = record_handle
reslove(record_handle)
})
}
export async function getUserAlbumItemByDisplayName(displayName: string, day?,
type?): Promise<photoAccessHelper.Album> {
let fetchResult = null
let album: photoAccessHelper.Album = null
try {
console.log('getUserAlbumItemByDisplayName');
let predicates = new dataSharePredicates.DataSharePredicates();
predicates.equalTo(photoAccessHelper.AlbumKeys.ALBUM_NAME, displayName)
let fetchOptions = {
fetchColumns: [],
predicates: predicates
};
const context = AppStorage.get('context')
const userFileMgr = photoAccessHelper.getPhotoAccessHelper(context);
fetchResult =
await userFileMgr.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC,
fetchOptions);
console.log('get getUserAlbumItemByDisplayName, count: ' + JSON.stringify(fetchResult));
if (fetchResult.getCount() > 0) {
const albums = await fetchResult.getLastObject();
console.log('get getUserAlbumItemByDisplayName album111', albums.albumName)
if (IsDaysAgo(albums.albumName, day)) {
deleteAllFileByPiC(albums.albumName, type)
}
console.log('get getUserAlbumItemByDisplayName album',)
}
} catch (err) {
console.log('get Album getUserAlbumItemByDisplayName fetchResult failed with err: ' + err);
} finally {
if (fetchResult != null) {
fetchResult.close();
}
}
return album;
}
/**
*拍照
@ -181,8 +135,7 @@ interface takePhotoParam {
*/
const fileHelper = new FileHelper();
export async function delPic(day: number, type: number) {
const context: common.UIAbilityContext = AppStorage.get('context')
export async function delPic(day: number, type: number, context?: common.UIAbilityContext) {
let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
console.info('albumGetAssetsDemoCallback');
let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
@ -200,102 +153,85 @@ export async function delPic(day: number, type: number) {
let albums = await albumList.getAllObjects();
for (let i = 0; i <= albums.length; i++) {
let albumName = albums[i].albumName
// isSevenDaysAgo(albumName, day)
console.log('albumNamealbumName', albumName)
if (IsDaysAgo(albumName, day) && albumName != 'jt' && albumName != 'pz') {
deleteAllFileByPiC(albumName, type)
}
}
}
export async function takePhoto(param, context, dir, flag = 1, callback?) {
var video_uri = `rtsp://${param.userName}:${param.pwd}@${param.ip}:${param.port}/h264/ch${param.pztd}/main/av_stream`;
// var video_uri = `rtsp://admin:openharmony1@192.168.1.66:554/Streaming/Channels/3`;
export async function takePhoto(param: VideoConfig, context: common.UIAbilityContext, dir: string, flag = 1,
callback?: (data: TakePhotoCallbackData) => void) {
let video_uri = `rtsp://${param.userName}:${param.pwd}@${param.ip}:${param.port}/h264/ch${param.pztd}/main/av_stream`;
const num = Math.floor(Math.random() * 10000)
const fileName = `picture_record${num}.jpg`
console.log('baoyihubaoyihu', video_uri, flag)
console.log(`baoyihu Rtsprecord baohaowen getVideoSnapshot fileName` + fileName);
// var snapResult = rtsp_server.getVideoSnapshot(context, video_uri, '', dir);
if (flag == 0) {
rtsp_server.detectVideoSnapshotSize(video_uri, fileName, (err, snapResult) => {
console.log("baohaowen_detectLoop round end size1:" + snapResult.fileSize);
rtsp_server.detectVideoSnapshotSize(video_uri, fileName, (err: BusinessError, snapResult: record.RtspResult) => {
callback({ fileSize: snapResult.fileSize, errorCode: snapResult.errorCode })
});
} else {
return new Promise<takePhotoParam>(async (resolve, reject) => {
const time = await getCurrentTime()
const time = await GetCurrentTime()
const date = time.split(' ')[0]
let dirName = dir ? dir : date
rtsp_server.getVideoSnapshot(context, video_uri, fileName, dirName, true, async (err, snapResult) => {
if (snapResult.result && snapResult.errorCode == 0) {
resolve({
base64: snapResult.dataString,
name: snapResult.fileName,
fileSize: snapResult.fileSize,
errorCode: snapResult.errorCode
})
} else {
promptAction.showToast({
message: `拍照失败`,
duration: 3000
});
reject(false)
// reject()
}
rtsp_server.getVideoSnapshot(context, video_uri, fileName, dirName, true,
async (err: BusinessError, snapResult: record.RtspResult) => {
if (snapResult.result && snapResult.errorCode == 0) {
resolve({
base64: snapResult.dataString,
name: snapResult.fileName,
fileSize: snapResult.fileSize,
errorCode: snapResult.errorCode
})
} else {
promptAction.showToast({
message: `拍照失败`,
duration: 3000
});
reject(false)
// reject()
}
});
});
})
}
}
export async function deleteAllPicturesFn() {
fileHelper.deleteAllPictures();
const context = AppStorage.get('context')
deleteAllVideos(context, photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.VIDEO)
}
//type:1 是图片 2是视频
export async function deleteAllFileByPiC(dirName, type = 1) {
export async function deleteAllFileByPiC(dirName: string, type = 1) {
// const fileHelper = new FileHelper();
fileHelper.deleteFileOfAlbum(dirName, type);
}
export async function deleteAllVideos(context, type: photoAccessHelper.AlbumType,
export async function deleteAllVideos(context: common.UIAbilityContext, type: photoAccessHelper.AlbumType,
subType: photoAccessHelper.AlbumSubtype): Promise<void> {
let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.Album> = null;
try {
const userFileMgr = photoAccessHelper.getPhotoAccessHelper(context);
fetchResult = await userFileMgr.getAlbums(type, subType);
console.log('baoyihu get Album fetchResult, count: ' + fetchResult.getCount());
for (let i = 0; i < fetchResult.getCount(); i++) {
let albumAsset: photoAccessHelper.Album = await fetchResult.getObjectByPosition(i);
let photoFetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = null;
let count = 0;
try {
let predicates = new dataSharePredicates.DataSharePredicates();
let fetchOptions = {
let fetchOptions: photoAccessHelper.FetchOptions = {
fetchColumns: FILE_ASSET_FETCH_COLUMNS,
predicates: predicates
};
photoFetchResult = await albumAsset.getAssets(fetchOptions);
count = photoFetchResult.getCount();
console.log('baoyihu photoFetchResult count: ' + count);
var all_fileAsset = await photoFetchResult.getAllObjects();
var uri_array = []
console.log('baoyihu batch delete begin');
let all_fileAsset = await photoFetchResult.getAllObjects();
let uri_array: string[] = []
for (let onfile of all_fileAsset) {
console.log('baoyihu push one uri : ' + onfile.uri);
uri_array.push(onfile.uri);
}
await userFileMgr.deleteAssets(uri_array);
console.log('baoyihu batch delete end');
} catch (err) {
console.log('baoyihu get Album getPhotoAssets failed with err: ' + err);
console.log(VideoTag, 'deleteAllVideos error:', JSON.parse(err));
} finally {
if (photoFetchResult != null) {
photoFetchResult.close();
@ -303,7 +239,7 @@ export async function deleteAllVideos(context, type: photoAccessHelper.AlbumType
}
}
} catch (err) {
console.log('baoyihu get Album fetchResult failed with err: ' + err);
console.log(VideoTag, 'deleteAllVideos error:', JSON.parse(err));
} finally {
if (fetchResult != null) {
fetchResult.close();