TMRAppBle/script/ble.js

477 lines
20 KiB
JavaScript

"use strict";
function initManager(param) {
ble.initManager(param, function (ret) {
if (ret.state === "poweredOn") {
// console.log("初始化成功");
scan({clean: true});
} else if (ret.state === 'poweredOff') {
api.hideProgress();
mui.alert('检查蓝牙是否打开');
document.getElementById('text').innerHTML = '检查蓝牙是否打开';
}
});
}
var times = 5;
var sta = true;
var scanInter;
function scan(param) {
if (!uuid){
uuid = api.getPrefs({
sync: true,
key: 'uuid'
});
}
if (uuid){
disconnect({peripheralUUID: uuid});
connect({peripheralUUID: uuid});
return false
}
sta = true
clearInterval(scanInter)
times = 5;
ble.scan(param, function (ret) {
if (ret.status) {
scanInter = setInterval(function (){
if (times>0){
times --;
api.showProgress({
title: '扫描中'+times+'...',
modal: true
});
}else {
if (sta){
api.hideProgress();
getPeripheral();
sta = false;
}
}
},1000)
}
});
}
function getPeripheral() {
ble.getPeripheral(function (ret) {
var ret2 = {};
if (ret.peripherals.length > 0) {
ret.peripherals.forEach(function (p) {
if (undefined !== p.name) {
console.log(p.name);
if (p.name.indexOf("BLUE2USART") !== -1) {
uuid = p.uuid;
api.setPrefs({
key: 'uuid',
value: uuid
});
ret2 = p;
if (ret2 !== {}) {
var wifiDom = document.getElementById('wifiDom');
wifiDom.innerHTML = "设备:" + ret2.name;
api.hideProgress();
api.showProgress({
title: '设备连接中...',
modal: true
});
document.getElementById('text').innerHTML = '设备连接中';
connect({peripheralUUID: ret2.uuid});
}
}
}
});
if (undefined === ret2.uuid){
mui.confirm('没有扫描到设备信息,继续扫描?', '提示', btnArray, function (e) {
if (e.index === 0) {} else {
scan({clean: true});
}
});
}
}
});
}
var connectTimes=0;
function connect(param) {
var wifiDom = document.getElementById('wifiDom');
wifiDom.innerHTML = "暂未连接";
api.showProgress({
title: '蓝牙连接中...',
modal: true
});
ble.connect(param, function (ret, err) {
if (ret.status) {
connetcedStatus = true
connectTimes = 0;
wifiDom.innerHTML = '已连接';
document.getElementById('text').innerHTML = '设备已连接';
text = '设备已连接';
console.log('连接成功')
initWeight();
discoverService({peripheralUUID: param.peripheralUUID});
}else {
connetcedStatus = false
connectTimes ++;
console.log('连接失败'+connectTimes+' '+uuid)
api.hideProgress();
setTimeout(function (){
if (connectTimes < 5 && !connetcedStatus && uuid){
console.log("连接失败!尝试重连" + uuid);
connect({peripheralUUID: uuid});
}
},3000)
}
});
}
function disconnect(param) {
ble.disconnect(param, function (ret, err) {
if (ret.status) {
console.log("断开连接成功!");
} else {
console.log("断开连接失败!");
}
});
}
var i;
function discoverService(param) {
ble.discoverService(param, function (ret) {
if (ret.services.length > 0) {
// console.log("发现服务成功!");
ret.services.forEach(function (ret4) {
if (ret4.indexOf("0000ffe") !== -1) {
if (ret4 && ret4.length > 0) {
discoverCharacteristics({
serviceUUID: ret4,
peripheralUUID: param.peripheralUUID
}, function (ret5) {
clearInterval(timer)
var timer = setInterval(function(){
if (msgList.length > 0) {
// 发送报文
var msg = msgList[0];
msgList.splice(0, 1);
// console.log(msg+ ' ' +new Date().getSeconds()*1000+ new Date().getMilliseconds())
// console.log('设备'+sbId + '班次' + classCode + '车次' + trainNumber +' '+ nowWeight + '/' + _weightSum + ' ' + feedName + _feedNum + '/' + _planSum);
var param1 = {
peripheralUUID: param.peripheralUUID,
serviceUUID: ret4,
characteristicUUID: ret5,
value: msg
};
writeValueForCharacteristic(param1, function (ret) {
// console.log(ret.status)
});
}
},150)
setNotify({
peripheralUUID: param.peripheralUUID,
serviceUUID: ret4,
characteristicUUID: ret5
}, function (ret6) {
if (ret6 !== undefined) {
if (isNaN(ret6)) {
return false
}
nowWeight = ret6;
// console.log(ret6)
if (first) {
first = false;
beforeWeight = nowWeight;
}
if (load) {
_feedNum = nowWeight - beforeWeight;
} else {
_feedNum = beforeWeight - nowWeight;
}
text = feedName + _planSum;
if (!isNaN(nowWeight)) {
// 实时重量保存
totalList.push({
time: currTimeFn(new Date()),
nowWeight: nowWeight
});
}
serviceUUID = ret4;
characteristicUUID = ret5;
// console.log(_feedNum,_weightSum,_planSum);
document.getElementById('feedNum').innerHTML = '<font style="color:blue">计划:' + _planSum + '</font>/<font style="color:green">已装:' + _feedNum + '</font>';
if (ledStatus && !isNaN(nowWeight)) {
getMess({
peripheralUUID: param.peripheralUUID,
serviceUUID: ret4,
characteristicUUID: ret5,
value: ret6
}, function (ret7) {
// console.log(JSON.stringify(ret7))
});
}
// feedMyChart.setOption({
// dataset: {
// source: [[1, _feedNum]]
// }
// });
// weightMyChart.setOption({
// dataset: {
// source: [[1, nowWeight]]
// }
// });
// 计划-饲喂
var feedErr = _planSum-_feedNum;
if (isNaN(feedErr)) {
return false
}
var count;
if (_planSum >= 500) {
count = 500
} else {
count = _planSum
}
var ration = feedErr / count;
// console.log("ration" + ration.toFixed(2));
if (ration > 0.2 ) {
if (statusEle) {
console.log(feedErr + ' ' + allow + ' ' + _feedNum + ' ' + _planSum);
ledStatus = false;
status = '';
statusEle = false;
msgList = [];
console.log("停止蜂鸣");
control("00", "00");
setTimeout(function () {
ledStatus = true;
}, 500);
}
} else if (0.1 < ration && ration <= 0.2) {
time = "05";
if (!statusEle || lastTime !== time) {
console.log(feedErr + ' ' + allow + ' ' + _feedNum + ' ' + _planSum);
lastTime = time;
ledStatus = false;
status = '间隔';
statusEle = true;
msgList = [];
console.log("开始蜂鸣" + time);
control("60", time);
setTimeout(function () {
ledStatus = true;
}, 500);
}
} else if (0.05 < ration && ration <= 0.1) {
time = "03";
if (!statusEle || lastTime !== time) {
console.log(feedErr + ' ' + allow + ' ' + _feedNum + ' ' + _planSum);
lastTime = time;
ledStatus = false;
status = '间隔';
statusEle = true;
msgList = [];
console.log("开始蜂鸣" + time);
control("60", time);
setTimeout(function () {
ledStatus = true;
}, 500);
}
} else if (0.02 < ration && ration <= 0.05) {
time = "01";
if (!statusEle || lastTime !== time) {
console.log(feedErr + ' ' + allow + ' ' + _feedNum + ' ' + _planSum);
lastTime = time;
ledStatus = false;
status = '间隔';
statusEle = true;
msgList = [];
console.log("开始蜂鸣" + time);
control("60", time);
setTimeout(function () {
ledStatus = true;
}, 500);
}
} else {
if (status === '间隔' || status === '') {
console.log(feedErr + ' ' + allow + ' ' + _feedNum + ' ' + _planSum);
ledStatus = false;
status = '长鸣';
statusEle = true;
msgList = [];
console.log("开始长鸣");
control("40", "02");
setTimeout(function () {
ledStatus = true;
}, 500);
setTimeout(function() {
console.log("开始长鸣")
control("40", "02");
setTimeout(function() {
ledStatus = true;
}, 500)
}, 500)
}
}
if (feedErr <= allow) {
var filteredValue = weightDataFilter.filter(nowWeight);
if (weightDataFilter.dataBuffer.length === 80) {
console.log("重量稳定", currTimeFn(new Date()));
weightDataFilter.dataBuffer = [];
// document.getElementById('submitData').click();
}
}
}
});
});
}
}
});
} else {
console.log("发现服务失败!");
}
});
}
function discoverCharacteristics(param, callback) {
ble.discoverCharacteristics(param, function (ret) {
var res = '';
if (ret.characteristics.length > 0) {
// console.log("发现特征成功!");
ret.characteristics.forEach(function (s) {
if (s.serviceUUID === param.serviceUUID) {
callback(s.uuid);
}
});
} else {
console.log("发现特征失败!");
callback(res);
}
});
}
function setNotify(param, callback) {
ble.setNotify(param, function (ret) {
// console.log(JSON.stringify(ret))
var value = ret.characteristic.value;
if (ret && value.indexOf('ff01') !== -1) {
var wei = value.substr(12, 12);
wei = Math.round(Number(hex2a(wei)));
}
callback(wei);
});
}
function writeValueForCharacteristic(param, callback) {
ble.writeValueForCharacteristic(param, function (ret) {
// console.log(JSON.stringify(ret));
if (ret.status) {
// console.log("发送成功");
} else {
console.log("发送失败");
}
callback(ret);
});
}
var lastCmd = "";
var lastTime = new Date().getSeconds()*1000+ new Date().getMilliseconds();
var count = 0;
/*组装报文并发数*/
function getMess(param, callback) {
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: ''
};
var newmsg = feedName;
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 + Math.abs(Number(_planSum - _feedNum)).toFixed(0) + 'kg';
// param1.msg = newmsg + Math.abs(Number(param.value)).toFixed(0) + 'kg'
// 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;
count ++;
if (count >= 5){
msgList.push(param.value);
// console.log(param.value + ' '+ new Date().getSeconds() + ' '+new Date().getMilliseconds())
renderUnload();
renderLoad();
feedMyChart.setOption({
dataset: {
source: [[1, _feedNum]]
}
});
weightMyChart.setOption({
dataset: {
source: [[1, nowWeight]]
}
});
count = 0 ;
}
});
}
function initWeight() {
api.showProgress({
title: '图表数据加装中...',
modal: true
});
weightStatus = true;
weightDataFilter = new WeightDataFilter(80, _weightSum);
renderUnload();
renderLoad();
feedMyChart.setOption({
dataset: {
source: [[1, _feedNum]]
}
});
weightMyChart.setOption({
dataset: {
source: [[1, nowWeight]]
}
});
api.hideProgress();
clearInterval(totalInterval);
totalAjax = true;
canUpload = true;
totalList = [];
totalInterval = setInterval(function () {
totalWeightUpload();
}, 3000);
document.getElementById('startLoad').setAttribute("class", 'btnc mui-btn-success dis');
document.getElementById('submitData').setAttribute("class", 'btnc mui-btn-success');
document.getElementById('text').innerHTML = 'V' + api.appVersion;
api.setGlobalData({key: 'startTime', value: currTimeFn(new Date())});
}