1059 lines
26 KiB
JavaScript
1059 lines
26 KiB
JavaScript
import commonConfig from 'common/config.js';
|
||
import cache from 'common/cache.js'
|
||
import HttpRequest from 'common/httpRequest'
|
||
|
||
/**
|
||
* 是否正在上传key常量
|
||
*/
|
||
export const KEY_UPLOAD_LOCATION = 'isUploadLocation';
|
||
|
||
/**
|
||
* socket连接key常量
|
||
*/
|
||
export const KEY_SOCKET_CONNECT = 'socketConnect';
|
||
|
||
/**
|
||
* 循环进程ID
|
||
*/
|
||
export const KEY_SOCKET_INTERVA_ID = 'socketIntervalId';
|
||
|
||
/**
|
||
* 是否上线
|
||
*/
|
||
export const KEY_SOCKET_GO_LIVE = 'socketGoLive';
|
||
|
||
/**
|
||
* 默认请求头
|
||
*/
|
||
export const defHeader = {
|
||
'content-type': 'application/json'
|
||
}
|
||
|
||
/**
|
||
* 存入全局变量库里
|
||
* @param { String } key 键
|
||
* @param { Object } obj 变量值
|
||
*/
|
||
export function setCommonData(key, obj) {
|
||
getApp().globalData[key] = obj;
|
||
}
|
||
|
||
/**
|
||
* 读取全局变量库
|
||
* @param { String } key 键
|
||
* @return { Object }
|
||
*/
|
||
export function getCommonData(key) {
|
||
return getApp().globalData[key];
|
||
}
|
||
|
||
export function set(...d) {
|
||
return setCommonData(...d);
|
||
}
|
||
|
||
export function get(...d) {
|
||
return getCommonData(...d);
|
||
}
|
||
|
||
/**
|
||
* 改变【是否上传中】变量
|
||
* @param { boolean } status 状态
|
||
*/
|
||
export function changeIsUploadLocation(status) {
|
||
setCommonData(KEY_UPLOAD_LOCATION, status);
|
||
}
|
||
|
||
/**
|
||
* 读取【是否上传中】变量
|
||
* @return { boolean }
|
||
*/
|
||
export function isUploadLocation() {
|
||
return getCommonData(KEY_UPLOAD_LOCATION);
|
||
}
|
||
|
||
/**
|
||
* 改变【是否上线】变量
|
||
* @param { boolean } status 、是否上线
|
||
*/
|
||
export function setGoLive(status) {
|
||
setCommonData(KEY_SOCKET_GO_LIVE, status);
|
||
}
|
||
|
||
/**
|
||
* 读取【是否上线】变量
|
||
* @return { boolean }
|
||
*/
|
||
export function isGoLive() {
|
||
return getCommonData(KEY_SOCKET_GO_LIVE);
|
||
}
|
||
|
||
/**
|
||
* 更改socket对象
|
||
* @param { Object } socket
|
||
*/
|
||
export function setSocketConnect(socket) {
|
||
setCommonData(KEY_SOCKET_CONNECT, socket);
|
||
}
|
||
|
||
/**
|
||
* 获取socket对象
|
||
*/
|
||
export function getSocketConnect() {
|
||
return getCommonData(KEY_SOCKET_CONNECT);
|
||
}
|
||
|
||
/**
|
||
* 更改循环对象标识
|
||
* @param { Number } id
|
||
*/
|
||
export function setSocketIntervalId(id) {
|
||
setCommonData(KEY_SOCKET_INTERVA_ID, id);
|
||
}
|
||
|
||
/**
|
||
* 获取循环对象标识
|
||
*/
|
||
export function getSocketIntervalId() {
|
||
return getCommonData(KEY_SOCKET_INTERVA_ID);
|
||
}
|
||
|
||
export function uuid() {
|
||
let s = []
|
||
let hexDigits = '0123456789abcdef'
|
||
for (let i = 0; i < 36; i++) {
|
||
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
|
||
}
|
||
s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
|
||
s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
|
||
s[8] = s[13] = s[18] = s[23] = '-'
|
||
|
||
let uuid = s.join('')
|
||
return uuid
|
||
}
|
||
|
||
/**
|
||
* 默认的连接成功回调
|
||
* @param { Object } res
|
||
*/
|
||
export function socketConnectSuccess(res) {
|
||
console.log('开启连接成功', res);
|
||
}
|
||
|
||
/**
|
||
* 默认的连接失败回调
|
||
* @param { Object } res
|
||
*/
|
||
export function socketConnectFail(res) {
|
||
console.log('开启连接失败', err);
|
||
}
|
||
|
||
/**
|
||
* 创建上传连接
|
||
* @param { String } deviceId 业务ID(唯一标识)
|
||
* @param { String } initMsg 连接时发生的消息
|
||
* @param { Object } header 请求头
|
||
* @param { String } method 接口请求方式
|
||
* @param { Function } success 连接成功回调
|
||
* @param { Function } fail 连接失败回调
|
||
* @return { Object } socketConnect连接对象
|
||
*/
|
||
export function creatSocket(url, deviceId, initMsg = '', header = defHeader, method = 'GET', success =
|
||
socketConnectSuccess, fail = socketConnectFail) {
|
||
console.log('url + deviceId ->', url + deviceId);
|
||
let socketConnect = uni.connectSocket({
|
||
url: url + deviceId,
|
||
data() {
|
||
return {
|
||
msg: initMsg
|
||
}
|
||
},
|
||
header,
|
||
method,
|
||
success,
|
||
fail,
|
||
});
|
||
return socketConnect;
|
||
}
|
||
|
||
export const defOnSocketOpenCellBack = (res) => {
|
||
console.log('onOpen', res);
|
||
}
|
||
|
||
/**
|
||
* 创建事件,连接打开回调
|
||
*/
|
||
export function createOnSocketOpen(socket, cellback = defOnSocketOpenCellBack) {
|
||
socket.onOpen(cellback);
|
||
//return uni.onSocketOpen(cellback);
|
||
}
|
||
|
||
export const defOnSocketErrorCellBack = (err) => {
|
||
console.log('onError', err);
|
||
}
|
||
|
||
/**
|
||
* 创建事件,连接失败回调
|
||
*/
|
||
export function createOnSocketError(socket, cellback = defOnSocketErrorCellBack) {
|
||
socket.onError(cellback);
|
||
//return uni.onSocketError(cellback);
|
||
}
|
||
|
||
export const defOnSocketMessageParser = (res) => {
|
||
console.log('onMessage', res)
|
||
}
|
||
|
||
/**
|
||
* 创建事件,接收消息回调
|
||
*/
|
||
export function createOnSocketMessage(socket, cellback = defOnSocketMessageParser) {
|
||
socket.onMessage(cellback);
|
||
//uni.onSocketMessage(cellback);
|
||
}
|
||
|
||
|
||
export const defOnSocketCloseCellBack = (res) => {
|
||
console.log('onClose', res)
|
||
}
|
||
|
||
/**
|
||
* 创建事件,关闭连接回调
|
||
*/
|
||
export function createOnSocketClose(socket, cellback = defOnSocketCloseCellBack) {
|
||
socket.onClose(cellback);
|
||
//uni.onSocketClose(cellback);
|
||
}
|
||
|
||
export const defSendMsgSuccessCellBack = (res) => {
|
||
console.log('向服务端发送消息成功!', res);
|
||
}
|
||
|
||
export const defSendMsgFailCellBack = (res) => {
|
||
console.log('向服务端发送消息失败', res)
|
||
}
|
||
|
||
export const defCompleteCellBack = (res) => {
|
||
console.log('向服务端发送消息结果', res)
|
||
}
|
||
|
||
|
||
/**
|
||
* 向服务端发送消息
|
||
* @param {Object} msg
|
||
*/
|
||
export function sendMsg(msg, successCellBack = defSendMsgSuccessCellBack, failCellBack = defSendMsgFailCellBack,
|
||
completeCellBack = defCompleteCellBack) {
|
||
let socket = getSocketConnect();
|
||
if (socket) {
|
||
socket.send({
|
||
data: JSON.stringify(msg),
|
||
success: successCellBack,
|
||
fail: failCellBack,
|
||
complete: completeCellBack
|
||
});
|
||
}
|
||
// uni.sendSocketMessage({
|
||
// data: JSON.stringify(msg),
|
||
// success: successCellBack,
|
||
// fail: failCellBack,
|
||
// });
|
||
}
|
||
|
||
export function getLocaton() {
|
||
//获取地理坐标
|
||
console.log('获取地址中...');
|
||
uni.getLocation({
|
||
// type: 'wgs84',
|
||
type: 'gcj02',
|
||
isHighAccuracy: true,
|
||
success: function(res) {
|
||
console.log('获取地址成功...');
|
||
console.log('当前位置的经度:' + res.longitude);
|
||
console.log('当前位置的纬度:' + res.latitude);
|
||
setCommonData('longitude', res.longitude);
|
||
setCommonData('latitude', res.latitude);
|
||
}
|
||
});
|
||
//读取缓存里面的经纬度
|
||
let longitude = getCommonData('longitude') || -1;
|
||
let latitude = getCommonData('latitude') || -1;
|
||
return {
|
||
latitude,
|
||
longitude
|
||
};
|
||
}
|
||
|
||
export function nllFn() {}
|
||
|
||
// 读取json文件
|
||
export function getFileJsonData(path) { //path:路径
|
||
return new Promise(resolve => {
|
||
plus.io.requestFileSystem(plus.io.PUBLIC_DOWNLOADS, fs => { //请求文件系统
|
||
fs.root.getFile(path, {
|
||
create: true /*当文件不存在时创建*/
|
||
}, fileEntry => {
|
||
fileEntry.file(function(file) {
|
||
let fileReader = new plus.io
|
||
.FileReader(); //new一个可以用来读取文件的对象fileReader
|
||
console.log('fileReader ->', fileReader);
|
||
//fileReader.readAsText(file, "utf-8"); //读文件的格式
|
||
fileReader.readAsBase64(file);
|
||
fileReader.onerror = e => { //读文件失败
|
||
// console.log("获取文件失败", fileReader.error);
|
||
// plus.nativeUI.toast("获取文件失败,请重启应用", {
|
||
// background: "#ffa38c",
|
||
// });
|
||
console.log("读取文件错误", e);
|
||
return;
|
||
};
|
||
fileReader.onload = e => { //读文件成功
|
||
console.log("读取文件成功", e);
|
||
let txtData = e.target.result;
|
||
resolve(txtData);
|
||
// 回调函数内的值想返回到函数外部 就用promise+resolve来返回出去
|
||
};
|
||
});
|
||
}, error => {
|
||
// console.log("2新建获取文件失败", error);
|
||
// plus.nativeUI.toast("获取文件失败,请重启应用", {
|
||
// background: "#ffa38c",
|
||
// });
|
||
return;
|
||
});
|
||
},
|
||
e => {
|
||
// console.log("1请求文件系统失败", e.message);
|
||
// plus.nativeUI.toast("请求系统失败,请重启应用", {
|
||
// background: "#ffa38c",
|
||
// });
|
||
return;
|
||
}
|
||
);
|
||
});
|
||
};
|
||
// 写入josn文件
|
||
export function changeData(path, seek, writeData) { //参数1:上传路径,参数2:seek方法可设置文件操作指定位置,参数3:写入的json数据
|
||
plus.nativeUI.showWaiting("正在保存信息");
|
||
return new Promise(resolve => {
|
||
plus.io.requestFileSystem(plus.io.PUBLIC_DOWNLOADS, fs => {
|
||
fs.root.getFile(path, {
|
||
create: true
|
||
}, fileEntry => {
|
||
fileEntry.file(file => {
|
||
fileEntry.createWriter(writer => {
|
||
//plus.nativeUI.showWaiting("正在保存信息");
|
||
writer.seek(seek); //覆盖文件
|
||
const writeDataTemp = JSON.stringify(writeData, null,
|
||
"\r").replace(/[\r]/g, "");
|
||
writer.write(writeDataTemp); // 整个文件重写
|
||
writer.onerror = function() {
|
||
//console.log("4写入文件失败", writer.error.message);
|
||
plus.nativeUI.closeWaiting();
|
||
plus.nativeUI.toast("修改信息失败,请重新操作", {
|
||
background: "#ffa38c",
|
||
});
|
||
return;
|
||
};
|
||
writer.onsuccess = function() { //填写文件成功
|
||
plus.nativeUI.closeWaiting();
|
||
// plus.nativeUI.toast("填写文件成功", {
|
||
// background: "rgba(255, 255, 255, 0.6)",
|
||
// });
|
||
resolve("1");
|
||
};
|
||
},
|
||
error => {
|
||
// console.log("3创建creactWriter失败", error);
|
||
// plus.nativeUI.toast("保存文件失败,请重新操作", {
|
||
// background: "#ffa38c",
|
||
// });
|
||
return;
|
||
});
|
||
});
|
||
},
|
||
error => {
|
||
// console.log("2获取文件失败", error);
|
||
// plus.nativeUI.toast("保存文件失败,请重新操作", {
|
||
// background: "#ffa38c",
|
||
// });
|
||
return;
|
||
}
|
||
);
|
||
}, e => {
|
||
//console.log("1请求文件系统失败", e.message);
|
||
plus.nativeUI.toast("请求系统失败,请重新操作", {
|
||
background: "#ffa38c",
|
||
});
|
||
return;
|
||
});
|
||
});
|
||
}
|
||
|
||
export async function saveFile(url, file, newfilename) {
|
||
let c = await creatDirs(url)
|
||
let isokm = moveDirectyOrFile(file, url + "/", newfilename);
|
||
return isokm
|
||
}
|
||
//循环创建目录 url:"_doc/...." _doc开头
|
||
export async function creatDirs(url) {
|
||
let urllist = url.split("/");
|
||
console.log(urllist)
|
||
//创建文件夹
|
||
let u = "";
|
||
for (let i = 0; i < urllist.length - 1; i++) {
|
||
let j = i;
|
||
if (i == 0) {
|
||
u = urllist[i];
|
||
} else {
|
||
u = u + "/" + urllist[i];
|
||
}
|
||
console.log(i + "-------------------")
|
||
console.log(u)
|
||
console.log(urllist[j + 1])
|
||
await CreateNewDir(u, urllist[j + 1]);
|
||
}
|
||
}
|
||
//重命名目录或文件名
|
||
export function moveDirectyOrFile(srcUrl, dstUrl, newName) { //srcUrl需要移动的目录或文件,dstUrl要移动到的目标目录(父级)
|
||
plus.io.resolveLocalFileSystemURL(srcUrl, function(srcEntry) {
|
||
//console.log(111)
|
||
plus.io.resolveLocalFileSystemURL(dstUrl, function(dstEntry) {
|
||
//console.log(222)
|
||
if (srcEntry.isDirectory) {
|
||
//console.log(33)
|
||
srcEntry.moveTo(dstEntry, newName, function(entry) {
|
||
//console.log("New Path: " + entry.fullPath);
|
||
return true;
|
||
}, function(e) {
|
||
return e;
|
||
//console.log(e.message);
|
||
});
|
||
} else {
|
||
srcEntry.moveTo(dstEntry, newName, function(entry) {
|
||
//console.log("New Path: " + entry.fullPath);
|
||
return true;
|
||
}, function(e) {
|
||
return e;
|
||
//console.log(e.message);
|
||
});
|
||
}
|
||
}, function(e) {
|
||
uni.showToast({
|
||
title: '获取目标目录失败:' + e.message,
|
||
duration: 2000,
|
||
icon: 'none'
|
||
});
|
||
});
|
||
}, function(e) {
|
||
uni.showToast({
|
||
title: '获取目录失败:' + e.message,
|
||
duration: 2000,
|
||
icon: 'none'
|
||
});
|
||
});
|
||
}
|
||
|
||
//创建一个新目录
|
||
export function CreateNewDir(url, dirName) {
|
||
//url值可支持相对路径URL、本地路径URL
|
||
return new Promise((resolver, reject) => {
|
||
plus.io.resolveLocalFileSystemURL(url, function(entry) {
|
||
entry.getDirectory(dirName, {
|
||
create: true,
|
||
exclusive: false
|
||
}, function(dir) {
|
||
resolver(true)
|
||
}, function(error) {
|
||
reject(error.message)
|
||
uni.showToast({
|
||
title: dirName + '目录创建失败:' + error.message,
|
||
duration: 2000,
|
||
icon: 'none'
|
||
});
|
||
});
|
||
}, function(e) {
|
||
reject(error.message)
|
||
uni.showToast({
|
||
title: '获取目录失败:' + e.message,
|
||
duration: 2000,
|
||
icon: 'none'
|
||
});
|
||
});
|
||
})
|
||
}
|
||
|
||
|
||
export function copyFileTo(url, newUrl, dirName, newName) {
|
||
if (url.length >= 7 && "file://" == url.substring(0, 7)) {
|
||
url = url.substring(7)
|
||
}
|
||
let tempUrl = url.substring(0, url.lastIndexOf('/'));
|
||
let addUrl = newUrl + '/' + dirName;
|
||
console.log(addUrl, tempUrl)
|
||
if (addUrl == tempUrl) {
|
||
return url;
|
||
}
|
||
console.log(newUrl, dirName, newName)
|
||
return new Promise((resolve, reject) => {
|
||
plus.io.resolveLocalFileSystemURL(url, async (entry) => {
|
||
if (entry.isFile) {
|
||
let c = await CreateNewDir(newUrl, dirName)
|
||
let u = await getDirsys(addUrl)
|
||
entry.copyTo(u, newName, en => {
|
||
resolve(en.fullPath);
|
||
}, e => {
|
||
console.log(e);
|
||
reject('错误:复制时出现错误')
|
||
uni.showModal({
|
||
title: "错误",
|
||
content: "复制时出现错误"
|
||
})
|
||
})
|
||
} else {
|
||
reject('错误:路径必须是文件')
|
||
uni.showModal({
|
||
title: "错误",
|
||
content: "路径必须是文件"
|
||
})
|
||
}
|
||
}, (e) => {
|
||
console.log(e);
|
||
reject(e)
|
||
uni.showModal({
|
||
title: "错误",
|
||
content: "打开文件系统时出错"
|
||
})
|
||
});
|
||
})
|
||
}
|
||
//获取目录对象
|
||
export function getDirsys(url) {
|
||
return new Promise((resolve, reject) => {
|
||
plus.io.resolveLocalFileSystemURL(url, (entry) => {
|
||
resolve(entry)
|
||
}, (e) => {
|
||
reject(e)
|
||
console.log(e);
|
||
});
|
||
})
|
||
}
|
||
|
||
export function getDate() {
|
||
let date = new Date();
|
||
let year = date.getFullYear();
|
||
let month = date.getMonth() + 1;
|
||
let day = date.getDate();
|
||
let fn = (d) => d > 9 ? d : '0' + d;
|
||
return year + '-' + fn(month) + '-' + fn(day);
|
||
}
|
||
|
||
|
||
|
||
export function blobToString(blob) {
|
||
return new Promise((resolve, reject) => {
|
||
const reader = new FileReader();
|
||
reader.onloadend = () => {
|
||
resolve(reader.result);
|
||
}
|
||
reader.onerror = reject;
|
||
reader.readAsText(blob);
|
||
});
|
||
}
|
||
|
||
// blob = new Blob(['Hello, World!'], { type: 'text/plain' });
|
||
// let str = await blobToString(blob);
|
||
// console.log('str ->',str);
|
||
|
||
export function config(name) {
|
||
var info = null;
|
||
if (name) {
|
||
var name2 = name.split("."); //字符分割
|
||
if (name2.length > 1) {
|
||
info = commonConfig[name2[0]][name2[1]] || null;
|
||
} else {
|
||
info = commonConfig[name] || null;
|
||
}
|
||
if (info == null) {
|
||
let web_config = cache.get("web_config");
|
||
if (web_config) {
|
||
if (name2.length > 1) {
|
||
info = web_config[name2[0]][name2[1]] || null;
|
||
} else {
|
||
info = web_config[name] || null;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
return info;
|
||
}
|
||
|
||
|
||
export function getBaseUrl() {
|
||
return config('APIHOST');
|
||
}
|
||
|
||
export function uploadFileUrl() {
|
||
return config('UPLOAD_PATH');
|
||
}
|
||
|
||
export function getWsBaseUrl() {
|
||
return config('WSHOST');
|
||
}
|
||
|
||
|
||
|
||
|
||
//----------------------------------业务相关--------------------------------------------
|
||
|
||
//------------------------------地图上传位置信息-----------------------------------------
|
||
export function closeMapSocket() {
|
||
let socket = getSocketConnect();
|
||
if (socket) {
|
||
socket.close();
|
||
}
|
||
//uni.closeSocket();
|
||
closeMapSocketInterval();
|
||
}
|
||
|
||
export function closeMapSocketInterval() {
|
||
clearInterval(getSocketIntervalId());
|
||
setSocketConnect(null);
|
||
setSocketIntervalId(null);
|
||
changeIsUploadLocation(false);
|
||
}
|
||
|
||
export function forSendMapMsg(sendFn, sendFnParam, time) {
|
||
if (getSocketIntervalId()) return;
|
||
let pointThread = setInterval(() => {
|
||
changeIsUploadLocation(true);
|
||
sendFn(sendFnParam);
|
||
}, time);
|
||
setSocketIntervalId(pointThread);
|
||
}
|
||
|
||
export function sendGetCoordinateMsg({
|
||
userId,
|
||
businessId
|
||
}) {
|
||
let msg = {
|
||
sendType: "getCoordinate",
|
||
userId,
|
||
businessId,
|
||
rkey: `map:location:${businessId}:*`
|
||
}
|
||
sendMsg(msg);
|
||
}
|
||
|
||
export function sendUploadCoordinateMsg({
|
||
userId,
|
||
businessId
|
||
}) {
|
||
let coordinate = '-1,-1';
|
||
//获取地理坐标
|
||
let {
|
||
latitude,
|
||
longitude
|
||
} = getLocaton();
|
||
coordinate = `${latitude},${longitude}`;
|
||
let msg = {
|
||
sendType: "coordinate",
|
||
userId,
|
||
businessId,
|
||
coordinate
|
||
}
|
||
console.log('准备向服务端发送坐标->', msg)
|
||
if (coordinate != '-1,-1') {
|
||
console.log('已向服务端发送坐标->', msg)
|
||
sendMsg(msg);
|
||
} else {
|
||
//重新获取地址
|
||
// getLocaton();
|
||
}
|
||
}
|
||
|
||
export const getMapPointOnSocketMessageParser = (res) => {
|
||
console.log('onMessage', res)
|
||
let datas = JSON.parse(res.data)
|
||
//解析点
|
||
this.pointMap = {};
|
||
switch (datas.type) {
|
||
case 'getCoordinate': {
|
||
this.pointMap = datas.data;
|
||
//that.creatMarker(that.cmap);
|
||
that.updateMarker(datas.data);
|
||
break;
|
||
}
|
||
default: {
|
||
|
||
}
|
||
}
|
||
}
|
||
|
||
export function initUploadMapSocket(deviceId, sendFnParam) {
|
||
console.log(deviceId, "2d2d2das..");
|
||
let socket = creatSocket(commonConfig.WS_UPLOAD_MAP_PATH, deviceId, '', defHeader, 'GET', () => {
|
||
//连接成功
|
||
//开启上传
|
||
forSendMapMsg(sendUploadCoordinateMsg, sendFnParam, 3 * 60 * 1000); //3分钟上传一次
|
||
});
|
||
|
||
setSocketConnect(socket);
|
||
createOnSocketOpen(socket);
|
||
//发生错误时停止循环
|
||
createOnSocketError(socket, (res) => {
|
||
console.log('map点位上传出现错误:', res);
|
||
closeMapSocketInterval();
|
||
});
|
||
//上传无需解析回执
|
||
createOnSocketMessage(socket, res => {
|
||
console.log('map点位上传回执:', res);
|
||
});
|
||
//关闭时停止循环
|
||
createOnSocketClose(socket, (res) => {
|
||
console.log('map点位上传关闭:', res);
|
||
closeMapSocketInterval();
|
||
});
|
||
}
|
||
|
||
export function getArtificerList(cellback = nllFn) {
|
||
console.log('查询?')
|
||
//TODO 查了详细信息?
|
||
//let curTab = this.tabs[this.tabIndex].status
|
||
let data = {
|
||
// status: null,
|
||
page: 1,
|
||
limit: -1,
|
||
artificerId: uni.getStorageSync('artificerId')
|
||
}
|
||
HttpRequest.get('/app/artificer/selectArtificerMassage', data).then(res => {
|
||
console.log('查完?', res, data)
|
||
setCommonData('userArtificerList', res.data.list)
|
||
cellback();
|
||
}).catch(() => {
|
||
console.log('出错?')
|
||
});
|
||
}
|
||
|
||
export function getArtificerIds() {
|
||
let list = getCommonData('userArtificerList');
|
||
if (list) {
|
||
let rList = []
|
||
list.forEach(x => {
|
||
rList.push(x.massageTypeId);
|
||
console.log('x.massageTypeId', x.massageTypeId);
|
||
});
|
||
return rList.join(',');
|
||
}
|
||
return '-1';
|
||
}
|
||
|
||
export function changeGoLiveFn(status) {
|
||
//获取项目
|
||
setGoLive(status);
|
||
if (status) {
|
||
//开启
|
||
let conn = getSocketConnect();
|
||
if (!conn) {
|
||
let userId = uni.getStorageSync('userId');
|
||
let businessId = getArtificerIds();
|
||
if (businessId == '-1') {
|
||
//重查
|
||
getArtificerList(() => {
|
||
let sendFnParam = {
|
||
userId,
|
||
businessId,
|
||
};
|
||
|
||
initUploadMapSocket(businessId, sendFnParam);
|
||
});
|
||
} else {
|
||
let sendFnParam = {
|
||
userId,
|
||
businessId,
|
||
};
|
||
initUploadMapSocket(businessId, sendFnParam);
|
||
}
|
||
} else if (!isUploadLocation()) {
|
||
//有链接,但是没执行
|
||
//看看有没有任务ID
|
||
if (!getSocketIntervalId()) {
|
||
//都没有,开启
|
||
forSendMapMsg(sendUploadCoordinateMsg, sendFnParam, 5000); //5秒上传一次
|
||
}
|
||
}
|
||
} else {
|
||
//关闭
|
||
closeMapSocket();
|
||
}
|
||
}
|
||
|
||
|
||
//---------------------------------地图上传位置信息END---------------------------------------------
|
||
|
||
//-----------------------------------持续上传录音-------------------------------------------------
|
||
export function closeRecSocket() {
|
||
let socket = getSocketConnect();
|
||
if (socket) {
|
||
socket.close();
|
||
}
|
||
// closeSocketInterval();
|
||
set('rec' + KEY_SOCKET_CONNECT, null);
|
||
set('sendRecorderParam', null);
|
||
set('recordFilePathMap', null);
|
||
set('recorderManagerIsRun', false);
|
||
}
|
||
|
||
// export function closeSocketInterval(){
|
||
// clearInterval(getSocketIntervalId());
|
||
// setSocketConnect(null);
|
||
// setSocketIntervalId(null);
|
||
// changeIsUploadLocation(false);
|
||
// }
|
||
|
||
// export function forSendMsg(sendFn, sendFnParam, time){
|
||
// if(getSocketIntervalId()) return;
|
||
// let pointThread = setInterval(()=>{
|
||
// changeIsUploadLocation(true);
|
||
// sendFn(sendFnParam);
|
||
// },time);
|
||
// setSocketIntervalId(pointThread);
|
||
// }
|
||
|
||
// export function sendUploadRecorderMsg({ userId, businessId }){
|
||
// let coordinate = '-1,-1';
|
||
// //获取地理坐标
|
||
// let { latitude, longitude } = getLocaton();
|
||
// coordinate = `${latitude},${longitude}`;
|
||
// let msg = {
|
||
// sendType: "coordinate",
|
||
// userId,
|
||
// businessId,
|
||
// coordinate
|
||
// }
|
||
// if(coordinate != '-1,-1'){
|
||
// sendMsg(msg);
|
||
// }
|
||
// }
|
||
|
||
//录音上传器
|
||
export function initUploadRecorderSocket(deviceId, cellback = nllFn) {
|
||
// 保持屏幕常亮
|
||
uni.setKeepScreenOn({
|
||
keepScreenOn: true
|
||
});
|
||
let socket = creatSocket(commonConfig.WS_UPLOAD_RECORDER_PATH, deviceId, '', defHeader, 'GET', () => {
|
||
//连接成功
|
||
//开启上传
|
||
//forSendMsg(sendUploadRecorderMsg, sendFnParam, 5000);//5秒上传一次
|
||
setTimeout(() => {
|
||
cellback();
|
||
}, 1000)
|
||
});
|
||
|
||
set('rec' + KEY_SOCKET_CONNECT, socket);
|
||
|
||
//发生错误时停止循环
|
||
createOnSocketError(socket, (res) => {
|
||
console.log('rec音频上传出现错误:', res);
|
||
//closeSocketInterval();
|
||
});
|
||
//上传无需解析回执
|
||
createOnSocketMessage(socket, res => {
|
||
console.log('rec音频上传回执:', res);
|
||
});
|
||
//关闭时停止循环
|
||
createOnSocketClose(socket, (res) => {
|
||
console.log('rec音频上传关闭:', res);
|
||
//closeSocketInterval();
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 向服务端发送消息
|
||
* @param {Object} msg
|
||
*/
|
||
export function sendRecorderMsg(msg, successCellBack = defSendMsgSuccessCellBack, failCellBack =
|
||
defSendMsgFailCellBack) {
|
||
console.log('向服务器发生的内容', msg)
|
||
let socket = get('rec' + KEY_SOCKET_CONNECT);
|
||
if (socket) {
|
||
socket.send({
|
||
data: JSON.stringify(msg),
|
||
success: successCellBack,
|
||
fail: failCellBack,
|
||
});
|
||
}
|
||
}
|
||
|
||
//开启报警
|
||
export function uploadAudioStart() {
|
||
// 保持屏幕常亮
|
||
uni.setKeepScreenOn({
|
||
keepScreenOn: true
|
||
});
|
||
//开始上传
|
||
console.log('开始上传!');
|
||
let uuid_s = uuid();
|
||
console.log('uuid: ' + uuid_s);
|
||
//开启ws连接
|
||
//创建发生参数
|
||
let sendRecorderParam = {
|
||
sendType: "creatFile",
|
||
userId: uni.getStorageSync('userId'),
|
||
businessId: uuid_s,
|
||
date: getDate()
|
||
}
|
||
set('sendRecorderParam', sendRecorderParam);
|
||
initUploadRecorderSocket(uuid_s, audioStart);
|
||
}
|
||
|
||
export function queueGetData(key) {
|
||
try {
|
||
const value = uni.getStorageSync(key);
|
||
if (value) {
|
||
return value;
|
||
}
|
||
} catch (e) {
|
||
// error
|
||
}
|
||
}
|
||
|
||
export function audioStart() {
|
||
//发生创建文件
|
||
let sendRecorderParam = get('sendRecorderParam');
|
||
|
||
let userId = queueGetData('userId');
|
||
let userName = queueGetData('userName');
|
||
sendRecorderParam.userId = userId;
|
||
sendRecorderParam.userName = userName;
|
||
|
||
let {
|
||
latitude,
|
||
longitude
|
||
} = getLocaton()
|
||
sendRecorderParam.typeId = longitude;
|
||
sendRecorderParam.typeName = latitude;
|
||
console.log('发生初始化内容:', sendRecorderParam); //不执行此步骤
|
||
sendRecorderMsg(sendRecorderParam);
|
||
|
||
let recorderManager = uni.getRecorderManager();
|
||
set('recorderManager', recorderManager);
|
||
set('recorderManagerIsRun', false);
|
||
recorderManager.onStart(() => {
|
||
console.log('开始录音!');
|
||
set('recorderManagerIsRun', true);
|
||
});
|
||
recorderManager.onStop(res => {
|
||
console.log('停止录音!', res);
|
||
if (get('recorderManagerIsRun')) {
|
||
//继续开启
|
||
recorderManager.start({
|
||
format: 'mp3',
|
||
//duration: 500,
|
||
//duration: 600000,
|
||
duration: 5000,
|
||
//frameSize: 1,
|
||
});
|
||
}
|
||
//set('recorderManagerIsRun', false);
|
||
//保存录音文件地址
|
||
let recordFilePathMap = get('recordFilePathMap');
|
||
if (recordFilePathMap) {
|
||
recordFilePathMap.maxKey++;
|
||
recordFilePathMap[recordFilePathMap.maxKey] = res.tempFilePath;
|
||
} else {
|
||
recordFilePathMap = {
|
||
currentUploadFragment: 0, //未开始
|
||
uploadEndFragment: 0, //未开始
|
||
maxKey: 1,
|
||
'1': res.tempFilePath
|
||
}
|
||
set('recordFilePathMap', recordFilePathMap);
|
||
//this.saveLocal(res.tempFilePath);
|
||
}
|
||
sendFile();
|
||
});
|
||
// recorderManager.onFrameRecorded(res => {
|
||
// console.log('切片1',res)
|
||
// })
|
||
console.log('开启了???1')
|
||
//最长10分钟,,
|
||
recorderManager.start({
|
||
format: 'mp3',
|
||
//duration: 600000,
|
||
//duration: 500,
|
||
duration: 5000,
|
||
//frameSize: 1,
|
||
});
|
||
console.log('开启了???2')
|
||
}
|
||
|
||
export function uploadAudioEnd() {
|
||
// 保持屏幕常亮
|
||
uni.setKeepScreenOn({
|
||
keepScreenOn: false
|
||
});
|
||
//结束上传
|
||
console.log('结束上传!');
|
||
let recorderManager = get('recorderManager'); //结束音频上传
|
||
recorderManager.stop();
|
||
//set('recorderManager', null);
|
||
set('recorderManagerIsRun', false); //拉闸
|
||
//get('sendRecorderParam',null);
|
||
|
||
}
|
||
|
||
export function sendFile() {
|
||
let recordFilePathMap = get('recordFilePathMap');
|
||
if (recordFilePathMap.maxKey != 0) {
|
||
//最大key不是0,说明有文件可以传
|
||
// if(recordFilePathMap.uploadEndFragment == 0){
|
||
// //上一个上传的文件是没有上传也就是头一个
|
||
// }else{
|
||
// //
|
||
// }
|
||
let currentUploadFragment = recordFilePathMap.currentUploadFragment + 1;
|
||
let filePath = recordFilePathMap[currentUploadFragment];
|
||
console.log(filePath, currentUploadFragment);
|
||
recordFilePathMap.currentUploadFragment = currentUploadFragment;
|
||
sendFileFetch(filePath, currentUploadFragment, recordFilePathMap);
|
||
}
|
||
}
|
||
|
||
export function sendFileFetch(url, currentUploadFragment, recordFilePathMap) {
|
||
console.log('fetch', fetch);
|
||
getFileJsonData(url).then(async blob => {
|
||
//整合数据,发生到后台
|
||
//console.log('blob',typeof blob);
|
||
//console.log('blob',blob);
|
||
recordFilePathMap.uploadEndFragment = currentUploadFragment;
|
||
|
||
let sendRecorderParam = Object.assign({}, get('sendRecorderParam'));
|
||
sendRecorderParam.sendType = 'uploadFileData';
|
||
sendRecorderParam.currentUploadFragment = currentUploadFragment;
|
||
sendRecorderParam.fileData = blob;
|
||
// let blobStr = await blobToString(blob);
|
||
// console.log('blobStr ->',blobStr);
|
||
// sendRecorderParam.fileData = blobStr;
|
||
sendRecorderMsg(sendRecorderParam, res => {
|
||
//判断需不需要关闭链接
|
||
recordFilePathMap.uploadEndFragment++;
|
||
let recorderManagerIsRun = get('recorderManagerIsRun');
|
||
console.log('recorderManagerIsRun ->', recorderManagerIsRun);
|
||
if (!recorderManagerIsRun) {
|
||
if (recordFilePathMap.maxKey == recordFilePathMap.currentUploadFragment) {
|
||
//传输完了
|
||
console.log('最后一个也传完了');
|
||
let endMsg = Object.assign({}, get('sendRecorderParam'));
|
||
endMsg.sendType = 'endUpload';
|
||
sendRecorderMsg(endMsg, res2 => {
|
||
console.log('结束语也发生完了,关闭吧');
|
||
closeRecSocket();
|
||
});
|
||
}
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
//-----------------------------------持续上传录音END-----------------------------------------------
|