TMRAppBle/script/index.js

884 lines
32 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
// 版本更新
function updateApp() {
mui.toast(document.getElementById('text').innerHTML);
}
// 重量校准
function weightFix() {
if (!feedList.length > 0) {
mui.toast("没有装料信息");
return false;
}
var btnArray1 = [feedName + '已完成', feedName + '未开始'];
mui.confirm('<b style="color:red">如果已完成需要先上传</b>', '<b style="font-weight:900">校准前' + feedName + '状态</b>', btnArray1, function (e) {
if (e.index == 0) {
mui.toast('<b style="color:red">校准失败,已完成请先上传</b>');
} else {
beforeWeight = nowWeight;
allowAuto = true
document.getElementById('isfix').innerHTML = '<font style="color:green;font-size: x-large;">已校准</font>'
mui.toast("校准完成");
}
});
}
// 开始装料
function startLoad() {
if (!feedList.length > 0) {
mui.toast("没有装料信息");
return false;
}
api.showProgress({
title: '初始化服务中...',
modal: true
});
// 初始化查询称和字符卡配置信息
initService();
}
// 提交数据
function submitData() {
var date = new Date();
var dateOf = getDateStr(date);
var dateTime = currTimeFn(date);
var param = {
dateOf: dateOf,
name: feedName,
remark: remark,
planWeight: Number(_planSum),
rationCowAmount: feedList[feedIndex] ? feedList[feedIndex].cow : 0,
batchRation: feedList[feedIndex].batchRation,
feedWeight: _feedNum,
feedId: feedList[feedIndex].id,
driver: driverName,
type: feedList[feedIndex].batchRation ? 2 : 1,
sourceCow: api.getPrefs({sync: true, key: 'sourceCow'}),
classCode: classCode,
trainNumber: trainNumber,
templet: templateName,
templetType: templetType,
sbId: sbId,
createBy: driverName,
start: api.getGlobalData({key: 'startTime'}),
end: dateTime,
time: dateTime
};
// api.showProgress({
// title: '数据上传中...',
// modal: true
// });
var feedListCache = []
var cacheList = api.getPrefs({ sync: true, key: 'feedListCache' })
// 存在
if (cacheList && cacheList!=='' && cacheList!=='[]') {
feedListCache = JSON.parse(cacheList)
feedListCache.push(param)
api.setPrefs({
key: 'feedListCache',
value: feedListCache
});
}else{
feedListCache.push(param)
api.setPrefs({
key: 'feedListCache',
value: feedListCache
});
}
// api.hideProgress();
mui.toast(param.name + " 已上传 " + param.feedWeight,{duration:1500,type:'div'});
api.setGlobalData({key: 'startTime', value: currTimeFn(new Date())});
remark = '手动上传'
beforeWeight = nowWeight;
// document.getElementById('beforeWeight').innerHTML = '称实时/装料前:' + nowWeight + '/' + beforeWeight;
feedIndex = feedIndex + 1;
// 没有下一个饲料,车次加一
if (feedIndex > feedList.length - 1) {
trainIndex = trainIndex + 1;
// 没有下一个车次,饲喂完成
if (trainIndex > trainArr.length - 1) {
// mui.alert("本班次饲喂完成");
feedStatus = false
_feedNum = batchName+'次饲喂完成'
renderUnload();
renderLoad();
feedMyChart.setOption({
dataset: {
source: [[1, _feedNum]]
}
});
weightMyChart.setOption({
dataset: {
source: [[1, nowWeight]]
}
});
var param1 = {
SF: "AA A5 ",
LEN: '1A 00 ',
DES: 'FF FF ',
SRC: '12 34 ',
TID: 'B0 A1 ',
CMD1: '38 02 ',
X: '00 00 ',
Y: '00 00 ',
WIDTH: '40 00 ',
HEIGHT: '20 00 ',
FORMAT: '00 00 01 00 ',
CNT: '04 00 ',
CRC: '00 00 ',
EF: '5A 55 ',
msg: ''
};
// param1.msg = batchName+'饲喂完成'
var newmsg = batchName+'次';
var msglen = newmsg.getByteLen();
var ttr = '';
if (Number(_planSum - _feedNum) >= 0) {
ttr = '少';
echartsType = '少';
} else {
ttr = '多';
echartsType = '多';
}
if (msglen < 8) {
for (var i = 0; i < 8 - msglen; i++) {
newmsg = newmsg + ' ';
}
newmsg = newmsg + ttr;
} else {
newmsg = feedName + ttr;
}
param1.msg = newmsg + '饲喂完成';
// console.log(param1.msg)
zfk.getMsg(param1, function (ret, err) {
var str = ret.sendMsg;
str = str.replace(/\s+/g, "");
var num = str.length / 2;
param.value = "FF0500" + num.toString(16) + str;
msgList.push(param.value);
})
document.getElementById('submitData').setAttribute("class", 'btnc mui-btn-success dis');
document.getElementById('feedNum').innerHTML = param1.msg;
setTimeout(function(){
console.log("停止蜂鸣");
control("00", "00");
},500)
return false;
}
// 自动点击下一车,并定位,同时刷新下一个开始装料时间
document.getElementById('classeCode_' + classCode + 'train_' + trainIndex).click();
document.querySelector('#' + 'classeCode_' + classCode + 'train_' + trainIndex).scrollIntoView(true);
api.setGlobalData({key: 'startTime', value: currTimeFn(new Date())});
return false;
} else {
// 判断是否是圈舍
if (feedList[feedIndex].batchRation) {
load = false;
} else {
load = true;
}
// 设置下一个饲料选中状态
var doms = document.getElementsByClassName('mui-badge');
if (doms.length > 0) {
for (var i = 0; i < doms.length; i++) {
doms[i].setAttribute("class", 'mui-badge');
}
}
document.getElementById('feed_' + feedIndex).setAttribute("class", 'mui-badge mui-badge-purple');
}
// 刷新已装装料为0显示下一个饲料名称定位到下一个饲料位置刷新允许误差刷新计划重量刷新显示班次信息
_feedNum = 0;
feedName = feedList[feedIndex].name;
// document.getElementById("upload").innerHTML = '上传'+json[0].name
document.getElementById('submitData').innerHTML = '上传' + feedName;
// document.getElementById('fix').innerHTML = '装料前校准' + feedName;
if (load) {
document.getElementById('fix').innerHTML = '装料前校准';
} else {
document.getElementById('fix').innerHTML = '卸料前校准';
}
document.querySelector('#feed_' + feedIndex).scrollIntoView(true);
allow = feedList[feedIndex].allow;
_planSum = feedList[feedIndex].weight.toFixed(0);
renderUnload();
feedMyChart.setOption({
dataset: {
source: [[1, _feedNum]]
}
});
// 误差小于100必须校准才能自动跳转
allowAuto = false;
document.getElementById('isfix').innerHTML = '<font style="color:red;font-size: x-large;">未校准</font>'
text = feedName + _planSum;
document.getElementById('nowFeed').innerHTML = '<font style="color:blue;margin-left:10px;">' + batchName + ',' + feedName + '</font>';
if (load) {
document.getElementById('feedNum').innerHTML = '<font style="color:blue">:' + _planSum + '</font>/<font style="color:green">已装:' + _feedNum + '</font>';
} else {
document.getElementById('feedNum').innerHTML = '<font style="color:blue">:' + _planSum + '</font>/<font style="color:green">已卸:' + _feedNum + '</font>';
}
ledStatus = false;
// setTimeout(() => {
console.log("停止蜂鸣");
control("00", "00");
setTimeout(function () {
ledStatus = true;
statusEle = false;
}, 500);
// api.ajax({
// url: 'https://tmr.nxcyx.com/api/app/tmr/resultUpload',
// headers: {
// 'Content-Type': 'application/json;charset=utf-8' //建议key使用首字母大写的形式如 User-Agent
// },
// method: 'post',
// data: {
// body: param
// }
// }, function (ret, err) {
// if (ret && ret.code == 200) {
// api.hideProgress();
// mui.toast(param.name + " 已上传 " + param.feedWeight,{duration:1500,type:'div'});
// remark = '手动上传'
// beforeWeight = nowWeight;
// // document.getElementById('beforeWeight').innerHTML = '称实时/装料前:' + nowWeight + '/' + beforeWeight;
// feedIndex = feedIndex + 1;
// // 没有下一个饲料,车次加一
// if (feedIndex > feedList.length - 1) {
// trainIndex = trainIndex + 1;
// // 没有下一个车次,饲喂完成
// if (trainIndex > trainArr.length - 1) {
// // mui.alert("本班次饲喂完成");
// feedStatus = false
// _feedNum = batchName+'次饲喂完成'
// renderUnload();
// renderLoad();
// feedMyChart.setOption({
// dataset: {
// source: [[1, _feedNum]]
// }
// });
// weightMyChart.setOption({
// dataset: {
// source: [[1, nowWeight]]
// }
// });
// var param1 = {
// SF: "AA A5 ",
// LEN: '1A 00 ',
// DES: 'FF FF ',
// SRC: '12 34 ',
// TID: 'B0 A1 ',
// CMD1: '38 02 ',
// X: '00 00 ',
// Y: '00 00 ',
// WIDTH: '40 00 ',
// HEIGHT: '20 00 ',
// FORMAT: '00 00 01 00 ',
// CNT: '04 00 ',
// CRC: '00 00 ',
// EF: '5A 55 ',
// msg: ''
// };
// // param1.msg = batchName+'饲喂完成'
// var newmsg = batchName+'次';
// var msglen = newmsg.getByteLen();
// var ttr = '';
// if (Number(_planSum - _feedNum) >= 0) {
// ttr = '少';
// echartsType = '少';
// } else {
// ttr = '多';
// echartsType = '多';
// }
// if (msglen < 8) {
// for (var i = 0; i < 8 - msglen; i++) {
// newmsg = newmsg + ' ';
// }
// newmsg = newmsg + ttr;
// } else {
// newmsg = feedName + ttr;
// }
// param1.msg = newmsg + '饲喂完成';
// // console.log(param1.msg)
// zfk.getMsg(param1, function (ret, err) {
// var str = ret.sendMsg;
// str = str.replace(/\s+/g, "");
// var num = str.length / 2;
// param.value = "FF0500" + num.toString(16) + str;
// msgList.push(param.value);
// })
// document.getElementById('submitData').setAttribute("class", 'btnc mui-btn-success dis');
// document.getElementById('feedNum').innerHTML = param1.msg;
// setTimeout(function(){
// console.log("停止蜂鸣");
// control("00", "00");
// },500)
// return false;
// }
// // 自动点击下一车,并定位,同时刷新下一个开始装料时间
// document.getElementById('classeCode_' + classCode + 'train_' + trainIndex).click();
// document.querySelector('#' + 'classeCode_' + classCode + 'train_' + trainIndex).scrollIntoView(true);
// api.setGlobalData({key: 'startTime', value: currTimeFn(new Date())});
// return false;
// } else {
// // 判断是否是圈舍
// if (feedList[feedIndex].batchRation) {
// load = false;
// } else {
// load = true;
// }
// // 设置下一个饲料选中状态
// var doms = document.getElementsByClassName('mui-badge');
// if (doms.length > 0) {
// for (var i = 0; i < doms.length; i++) {
// doms[i].setAttribute("class", 'mui-badge');
// }
// }
// document.getElementById('feed_' + feedIndex).setAttribute("class", 'mui-badge mui-badge-purple');
// }
// // 刷新已装装料为0显示下一个饲料名称定位到下一个饲料位置刷新允许误差刷新计划重量刷新显示班次信息
// _feedNum = 0;
// feedName = feedList[feedIndex].name;
// // document.getElementById("upload").innerHTML = '上传'+json[0].name
// document.getElementById('submitData').innerHTML = '上传' + feedName;
// // document.getElementById('fix').innerHTML = '装料前校准' + feedName;
// if (load) {
// document.getElementById('fix').innerHTML = '装料前校准';
// } else {
// document.getElementById('fix').innerHTML = '卸料前校准';
// }
// document.querySelector('#feed_' + feedIndex).scrollIntoView(true);
// allow = feedList[feedIndex].allow;
// _planSum = feedList[feedIndex].weight.toFixed(0);
// renderUnload();
// feedMyChart.setOption({
// dataset: {
// source: [[1, _feedNum]]
// }
// });
// // 误差小于100必须校准才能自动跳转
// allowAuto = false;
// document.getElementById('isfix').innerHTML = '<font style="color:red;font-size: x-large;">未校准</font>'
// text = feedName + _planSum;
// document.getElementById('nowFeed').innerHTML = '<font style="color:blue;margin-left:10px;">' + batchName + ',' + feedName + '</font>';
// if (load) {
// document.getElementById('feedNum').innerHTML = '<font style="color:blue">:' + _planSum + '</font>/<font style="color:green">已装:' + _feedNum + '</font>';
// } else {
// document.getElementById('feedNum').innerHTML = '<font style="color:blue">:' + _planSum + '</font>/<font style="color:green">已卸:' + _feedNum + '</font>';
// }
// ledStatus = false;
// // setTimeout(() => {
// console.log("停止蜂鸣");
// control("00", "00");
// setTimeout(function () {
// ledStatus = true;
// statusEle = false;
// }, 500);
// // },500)
// } else if (err) {
// api.hideProgress();
// addNotice(4,'red','submitData,' + err.msg);
// mui.alert( err.msg);
// }
// });
}
var weightDataFilter;
var status = '';
var statusEle = false;
var ledStatus = true;
var uuid = '';
var serviceUUID = '';
var characteristicUUID = '';
var lastTime = "";
var time = "";
var feedStatus = false;
var connetcedStatus = false;
// 获取当前时间字符串
function currTimeFn(_date) {
var _year = _date.getFullYear();
var _month = _date.getMonth() + 1 < 10 ? '0' + (_date.getMonth() + 1) : _date.getMonth() + 1;
var _day = _date.getDate() < 10 ? '0' + _date.getDate() : _date.getDate();
var _hour = _date.getHours() < 10 ? '0' + _date.getHours() : _date.getHours();
var _minutes = _date.getMinutes() < 10 ? '0' + _date.getMinutes() : _date.getMinutes();
var _seconds = _date.getSeconds() < 10 ? '0' + _date.getSeconds() : _date.getSeconds();
return _year + "-" + _month + "-" + _day + " " + _hour + ":" + _minutes + ":" + _seconds;
}
// 显示字符卡称重配置信息和未上传数据
function showZifuka() {
initService();
}
/**
* 上传异常信息
*/
// ajax防止重复提交状态
var canUpload = true;
function uploadNotice() {
var notice = api.getPrefs({sync: true, key: 'notice'});
if (notice !== '' && canUpload) {
canUpload = false;
api.ajax({
url: 'https://tmr.nxcyx.com/api/app/tmr/noticeSave',
headers: {
'Content-Type': 'application/json;charset=utf-8' //建议key使用首字母大写的形式如 User-Agent
},
method: 'post',
data: {
body: notice
}
}, function (ret, err) {
if (ret && ret.code == 200) {
api.removePrefs({
key: 'notice'
});
} else if (err) {
mui.toast("noticeSave:" + err.msg);
}
canUpload = true;
});
}
}
/**
* 上传100条实时重量信息
*/
// 实时重量数组
var totalList = [];
// ajax防止重复提交状态
var totalAjax = true;
function uploadTotalWeight() {
if (totalList.length > 100 && totalAjax) {
totalAjax = false;
api.ajax({
url: 'https://tmr.nxcyx.com/api/app/tmr/totalWeightUpload',
// url: 'http://10.10.100.101:8088/app/tmr/totalWeightUpload',
headers: {
'Content-Type': 'application/json;charset=utf-8' //建议key使用首字母大写的形式如 User-Agent
},
method: 'post',
data: {
body: {
sbId: sbId,
weightList: totalList
}
}
}, function (ret, err) {
if (ret && ret.code === 200) {
totalList = [];
} else if (err) {
mui.toast("totalWeightUpload" + err.msg);
}
totalAjax = true;
});
}
}
/**
* 添加异常通知
* @param type
* @param color
* @param {} describe
*/
function addNotice(type,color,describe) {
var param = {
sourceCow: api.getPrefs({sync: true, key: 'sourceCow'}),
type: type?type:4,
color: color?color:'red',
time: currTimeFn(new Date()),
describe: describe
};
api.setPrefs({
key: 'notice',
value: param
});
}
/**
* 定时任务
*/
function totalWeightUpload() {
uploadNotice();
uploadTotalWeight();
}
function convertToPolarPoint(renderItemParams, radius, radian) {
return [Math.cos(radian) * radius + renderItemParams.coordSys.cx, -Math.sin(radian) * radius + renderItemParams.coordSys.cy];
}
function makePionterPoints(renderItemParams, polarEndRadian) {
return [convertToPolarPoint(renderItemParams, _outerRadius, polarEndRadian), convertToPolarPoint(renderItemParams, _outerRadius, polarEndRadian + Math.PI * 0.03), convertToPolarPoint(renderItemParams, _pointerInnerRadius, polarEndRadian)];
}
//计划量/已装量echarts参数
function renderItemFeed(params, api) {
var valOnRadian = api.value(1);
var coords = api.coord([api.value(0), valOnRadian]);
var polarEndRadian = coords[3];
var imageStyle = {
image: "https://tmr.nxcyx.com/img/custom-gauge-panel.png",
x: params.coordSys.cx - _outerRadius,
y: params.coordSys.cy - _outerRadius,
width: _outerRadius * 2,
height: _outerRadius * 2
};
return {
type: 'group',
children: [{
type: 'image',
style: imageStyle,
clipPath: {
type: 'sector',
shape: {
cx: params.coordSys.cx,
cy: params.coordSys.cy,
r: _outerRadius,
r0: _innerRadius,
startAngle: 0,
endAngle: -polarEndRadian,
transition: 'endAngle',
enterFrom: {endAngle: 0}
}
}
}, {
type: 'image',
style: imageStyle,
clipPath: {
type: 'polygon',
shape: {
points: makePionterPoints(params, polarEndRadian)
},
extra: {
polarEndRadian: polarEndRadian,
transition: 'polarEndRadian',
enterFrom: {polarEndRadian: 0}
},
during: function during(apiDuring) {
apiDuring.setShape('points', makePionterPoints(params, apiDuring.getExtra('polarEndRadian')));
}
}
}, {
type: 'circle',
shape: {
cx: params.coordSys.cx,
cy: params.coordSys.cy,
r: _insidePanelRadius
},
style: {
fill: '#fff',
shadowBlur: 25,
shadowOffsetX: 0,
shadowOffsetY: 0,
shadowColor: 'rgba(76,107,167,0.4)'
}
}, {
type: 'text',
extra: {
valOnRadian: valOnRadian,
transition: 'valOnRadian',
enterFrom: {valOnRadian: 0}
},
style: {
text: makeTextFeed(valOnRadian),
fontSize: fontsize,
fontWeight: 900,
x: params.coordSys.cx,
y: params.coordSys.cy,
fill: 'rgb(255, 0, 0)',
align: 'center',
verticalAlign: 'middle',
enterFrom: {opacity: 0}
},
during: function during(apiDuring) {
apiDuring.setStyle('text', makeTextFeed(apiDuring.getExtra('valOnRadian')));
}
}]
};
}
function makeTextFeed(valOnRadian) {
if (isNaN(_feedNum )) {
return batchName + '次' + '\n' + '饲喂完成'
}else if (Math.abs(_planSum - _feedNum) >= 0) {
// return '剩余应装\n' + valOnRadian.toFixed(1) + 'kg';
return feedName + '\n' + echartsType + Math.abs(_planSum - _feedNum).toFixed(0) + 'kg';
} else {
// return '剩余应卸\n' + valOnRadian.toFixed(1) + 'kg';
return feedName + '\n' + echartsType + Math.abs(_planSum - _feedNum).toFixed(0) + 'kg';
}
}
function renderLoad(title) {
var weightOption = {
animation: false,
dataset: {
source: [[1, nowWeight]]
},
tooltip: {},
angleAxis: {
type: 'value',
startAngle: 0,
show: false,
min: 0,
max: _weightSum
},
radiusAxis: {
type: 'value',
show: false
},
polar: {},
series: [{
type: 'custom',
coordinateSystem: 'polar',
renderItem: renderItemWeight
}]
};
weightOption && weightMyChart.setOption(weightOption);
}
function renderUnload() {
var feedOption = {
animation: false,
dataset: {
// source: [[1, _planSum]]
source: [[1, _feedNum]]
},
// title: {
// text:feedName + '计划'+ _feedNum +'kg'
// // text:title
// },
tooltip: {},
angleAxis: {
type: 'value',
startAngle: 0,
show: false,
min: 0,
max: _planSum
},
radiusAxis: {
type: 'value',
show: false
},
polar: {},
series: [{
type: 'custom',
coordinateSystem: 'polar',
renderItem: renderItemFeed
}]
};
feedOption && feedMyChart.setOption(feedOption);
}
//总重量/剩余量echarts参数
function renderItemWeight(params, api) {
var valOnRadian = api.value(1);
var coords = api.coord([api.value(0), valOnRadian]);
var polarEndRadian = coords[3];
var imageStyle = {
image: "https://tmr.nxcyx.com/img/custom-gauge-panel.png",
x: params.coordSys.cx - _outerRadius,
y: params.coordSys.cy - _outerRadius,
width: _outerRadius * 2,
height: _outerRadius * 2
};
return {
type: 'group',
children: [{
type: 'image',
style: imageStyle,
clipPath: {
type: 'sector',
shape: {
cx: params.coordSys.cx,
cy: params.coordSys.cy,
r: _outerRadius,
r0: _innerRadius,
startAngle: 0,
endAngle: -polarEndRadian,
transition: 'endAngle',
enterFrom: {endAngle: 0}
}
}
}, {
type: 'image',
style: imageStyle,
clipPath: {
type: 'polygon',
shape: {
points: makePionterPoints(params, polarEndRadian)
},
extra: {
polarEndRadian: polarEndRadian,
transition: 'polarEndRadian',
enterFrom: {polarEndRadian: 0}
},
during: function during(apiDuring) {
apiDuring.setShape('points', makePionterPoints(params, apiDuring.getExtra('polarEndRadian')));
}
}
}, {
type: 'circle',
shape: {
cx: params.coordSys.cx,
cy: params.coordSys.cy,
r: _insidePanelRadius
},
style: {
fill: '#fff',
shadowBlur: 25,
shadowOffsetX: 0,
shadowOffsetY: 0,
shadowColor: 'rgba(76,107,167,0.4)'
}
}, {
type: 'text',
extra: {
valOnRadian: valOnRadian,
transition: 'valOnRadian',
enterFrom: {valOnRadian: 0}
},
style: {
text: makeTextWeight(valOnRadian),
fontSize: fontsize,
fontWeight: 900,
x: params.coordSys.cx,
y: params.coordSys.cy,
fill: 'rgb(0, 0, 0)',
align: 'center',
verticalAlign: 'middle',
enterFrom: {opacity: 0}
},
during: function during(apiDuring) {
apiDuring.setStyle('text', makeTextWeight(apiDuring.getExtra('valOnRadian')));
}
}]
};
}
function makeTextWeight(valOnRadian) {
return '车内总重\n' + valOnRadian.toFixed(0) + 'kg';
}
function hex2a(hexx) {
var hex = hexx.toString(); //force conversion
var str = '';
for (var i = 0; i < hex.length; i += 2) {
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
}return str;
}
// function speakTest(text, speed) {
// // IFlyVoice.stopSpeaking();
// IFlyVoice.startSynthetic({
// text: text,
// commonPath_Android: 'widget://res/aisound/common.jet',
// pronouncePath_Android: 'widget://res/aisound/xiaofeng.jet',
// commonPath_iOS: 'widget://res/aisound/common.jet',
// pronouncePath_iOS: 'widget://res/aisound/xiaofeng.jet',
// pronounceName: 'xiaofeng',
// volume: '100',
// speed: speed
// }, function (ret, err) {
// if (ret.status) {
// console.log('合成成功');
// } else {}
// });
// }
function handleBackMain() {
mui.confirm('确认返回到首页?', '提示', btnArray, function (e) {
if (e.index === 0) {} else {
api.closeWin();
}
});
}
function closeApp() {
mui.confirm('确认关闭TMR饲喂系统', '提示', btnArray, function (e) {
if (e.index === 0) {} else {
api.closeWidget({
id: api.appId, //应用ID
retData: { name: 'closeWidget' },
silent: true
});
}
});
}
function execute(db, sql, callback) {
db.executeSql({
name: 'test',
sql: sql
}, function(ret, err) {
// console.log(JSON.stringify(ret)+'['+sql+']');
// console.log(JSON.stringify(err)+'['+sql+']');
callback(ret, err);
});
}
function select(db, selsql, callback) {
db.selectSql({
name: 'test',
sql: selsql
}, function(ret, err) {
// console.log(JSON.stringify(ret)+'['+selsql+']');
// console.log(JSON.stringify(err)+'['+selsql+']');
callback(ret, err);
});
}
// 以下是一个基于JavaScript的称重异常过滤程序示例该程序使用滑动窗口算法来过滤异常值
// 该程序使用一个dataBuffer数组来保存最近的一组测量值并返回这组值的平均值。程序在filter方法中将新的测量值加入到dataBuffer中并调用getAverageValue方法获取平均值。如果该平均值与上一个有效值的偏差小于maxDeviation则将该测量值视为有效值并返回该平均值否则将该测量值视为异常值并返回上一个有效值。
// 使用时可以创建一个WeightDataFilter实例并调用filter方法来传入新的测量值如下所示
// let weightDataFilter = new WeightDataFilter(10, 0.5);
// let filteredValue = weightDataFilter.filter(measurementValue);
// 其中10是窗口大小0.5是最大的偏差值可以根据实际需求进行调整。measurementValue是当前的测量值。
"use strict";
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var WeightDataFilter = function () {
function WeightDataFilter(windowSize, maxDeviation) {
_classCallCheck(this, WeightDataFilter);
this.windowSize = windowSize;
this.maxDeviation = maxDeviation;
this.dataBuffer = [];
this.lastValidValue = NaN;
}
_createClass(WeightDataFilter, [{
key: "filter",
value: function filter(value) {
this.dataBuffer.push(value);
if (this.dataBuffer.length > this.windowSize) {
this.dataBuffer.shift();
}
var filteredValue = this.getAverageValue();
if (isNaN(this.lastValidValue) || Math.abs(filteredValue - this.lastValidValue) <= this.maxDeviation) {
this.lastValidValue = filteredValue;
return filteredValue;
} else {
return this.lastValidValue;
}
}
}, {
key: "getAverageValue",
value: function getAverageValue() {
var sum = this.dataBuffer.reduce(function (total, value) {
return total + value;
}, 0);
return sum / this.dataBuffer.length;
}
}]);
return WeightDataFilter;
}();