@jiabaida/tools 1.0.2 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- import { decimalToTwoByteHexArray, decimalToHex, getParamBaseValue } from '../BleDataProcess.js'
2
- import { readExistFactory, getDDA5FAAsync, enterFactory, getDDA5OldAsync, existFactory, setDDA5FAAsync, setDDA5OldAsync } from './BleCmdDD.js'
1
+ import { decimalToHex, decimalToTwoByteHexArray } from '../BleDataProcess.js';
2
+ import { enterFactory, existFactory, getDDA5FAAsync, getDDA5OldAsync, readExistFactory, setDDA5FAAsync, setDDA5OldAsync } from './BleCmdDD.js';
3
3
 
4
4
  // #region 发指令读取参数
5
5
  /**
@@ -258,16 +258,18 @@ export const setCapacityParamCmd = (chipType, deviceId, paramInfo) => {
258
258
  }
259
259
  };
260
260
  const handleParam = async (paramObj) => {
261
- const { address, oldAddress, length } = paramObj;
262
- const hexValues = decimalToTwoByteHexArray(Number(paramObj.values) * 100);
261
+ const { paramNo, oldParamNo, paramLength } = paramObj;
262
+ const value = Math.round(Number(paramObj.values) / paramInfo.divisor);
263
+ console.log('value: ', value);
264
+ const hexValues = decimalToTwoByteHexArray(value);
263
265
  /** 地址转换为16进制 */
264
- const hexAddress = decimalToTwoByteHexArray(address);
266
+ const hexAddress = decimalToTwoByteHexArray(paramNo);
265
267
  // 长度转换为16进制
266
- const hexLength = decimalToHex(length);
268
+ const hexLength = decimalToHex(paramLength / 2);
267
269
  if (chipType) {
268
270
  return await handleSet(() => setDDA5FAAsync(deviceId, hexAddress, hexLength, hexValues), 7);
269
271
  } else {
270
- return await handleSet(() => setDDA5OldAsync(deviceId, oldAddress, hexValues), 4);
272
+ return await handleSet(() => setDDA5OldAsync(deviceId, oldParamNo, hexValues), 4);
271
273
  }
272
274
  };
273
275
  try {
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var BleDataProcess=require("./BleDataProcess.js"),commonfun=require("./commonfun.js");class BleCmdAnalysis extends BleDataProcess.default{static async _writeAsync(deviceId,value){return console.log("deviceId, value: ",deviceId,value),!(!deviceId||!value)&&new Promise(resolve=>{const characteristicId=this.UUID_WRITE,{isAndroid:isAndroid,isIOS:isIOS}=commonfun.getOS();console.log("isAndroid, isIOS: ",isAndroid,isIOS);const writeType=isAndroid?"writeNoResponse":"write";uni.writeBLECharacteristicValue({deviceId:deviceId,serviceId:this.serviceId,characteristicId:characteristicId,writeType:writeType,value:value,success:res=>{console.error("res: 写入成功",res),resolve(!0)},fail:e=>{console.error("写入失败",e),resolve(!1)}}),isIOS&&setTimeout(()=>resolve(!0),50)})}static async writeAsync(deviceId,value){return console.log("value: ",value),console.log("deviceId: ",deviceId),!(!deviceId||!value)&&new Promise(async resolve=>{const n=Math.ceil(value.byteLength/20);let res;for(let i=0;i<n;i++){const _value=value.slice(20*i,20*(i+1));if(console.log("分包写入_value: ",_value),await this.sleep(150),res=await this._writeAsync(deviceId,_value),console.log(`分包写入结果 ${i+1}/${n} : ${res}`),!res)return resolve(!1)}resolve(res)})}static async getData(deviceId,{command:command,commandVerifyHandler:commandVerifyHandler=hexArr=>({verified:!1,pkgLen:null}),pkgVerifyHandler:pkgVerifyHandler=pkg=>({verified:!1}),maxRetries:maxRetries=2,retryInterval:retryInterval=300},tag=""){if(!deviceId)throw new Error("deviceId is required");if(!command||command.length<=0)throw new Error("command is required");return new Promise((resolve,reject)=>{let isCompleted=!1,timeoutId=null,responsed=!1,len=null,pkg=[];const cmdContent=this.hexArr2ab(command),cleanup=()=>{isCompleted||(isCompleted=!0,clearTimeout(timeoutId),commonfun.eventBus.off("setBleChangedCharacteristicValue",dataHandler))},dataHandler=payload=>{if(!payload||payload.deviceId!==deviceId||!payload.value)return;const hexArr=this.ab2decimalArr(payload.value);if(console.warn(tag,"接收到数据:",this.hexArr2string(hexArr)),0!==hexArr.length){if(null===len){const{verified:verified,pkgLen:pkgLen}=commandVerifyHandler(hexArr);console.log("指令验证结果:",{verified:verified,pkgLen:pkgLen}),verified&&(len=pkgLen)}if(len){if(pkg=[...pkg,...hexArr],console.log("当前数据包:",pkg,`长度: ${pkg.length}/${len}`),pkg.length>=len){pkg=pkg.slice(0,len);const{verified:verified}=pkgVerifyHandler(pkg);console.log("数据包验证结果:",{verified:verified}),verified?(responsed=!0,cleanup(),resolve([...pkg])):(len=null,pkg=[])}}else pkg=[]}},writeToDevice=async(attempt=1)=>{try{console.warn(tag,`第${attempt}次写入指令:`,command.join("").replace(/0x/g,"").toUpperCase());const writeSucceed=await this.writeAsync(deviceId,cmdContent);if(console.warn(tag,`第${attempt}次写入结果:`,writeSucceed?"成功":"失败"),!writeSucceed)return void(attempt<maxRetries?setTimeout(()=>writeToDevice(attempt+1),retryInterval):(cleanup(),resolve(null)));await this.sleep(retryInterval),!responsed&&attempt<maxRetries?(console.log(tag,`未收到响应,准备第${attempt+1}次重试`),writeToDevice(attempt+1)):responsed||(console.warn(tag,`达到最大重试次数(${maxRetries}),未收到响应`),cleanup(),resolve(null))}catch(error){console.error(tag,"写入过程发生错误:",error),cleanup(),reject(error)}};timeoutId=setTimeout(()=>{console.warn(tag,"操作超时"),cleanup(),resolve(null)},(maxRetries+2)*retryInterval),commonfun.eventBus.on("setBleChangedCharacteristicValue",dataHandler),writeToDevice().catch(error=>{cleanup(),reject(error)})})}static async getDDA503Async(deviceId){const hex=await this.getData(deviceId,{command:["0xdd","0xa5","0x03","0x00","0xff","0xfd","0x77"],commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&3==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=this.generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA5_03");return hex?this.resolveDDA503(hex):null}static resolveDDA503(data){if(!data)return null;const dataStr=this.hexArr2string(data),content=data.slice(4,data.length-3),binArr=data[24].toString(2).padStart(8,"0").split("").reverse(),n=Number(binArr[7])?10:100,fet=data[24],chargeSwitch=1==fet||3==fet,dischargeSwitch=2==fet||3==fet,BMSVersion=this.decimalToHex(data[22]),totalVoltage=(((data[4]<<8)+(255&data[5]))/100).toFixed(2);let current=(data[6]<<8)+(255&data[7]);current=current>32768?(current-65536)/n:current/n;const electricity=Number(current.toFixed(2)),power=(parseFloat(totalVoltage)*electricity).toFixed(2),soc=data[23]??0,volumeHex=this.decimalToHex(data[8])+this.decimalToHex(data[9]),seriesNum=data[25]??0,surplusCapacity=Number((this.hexToDecimal(volumeHex)/n).toFixed(2)),normCapHex=this.decimalToHex(data[10])+this.decimalToHex(data[11]),normCap=Number((this.hexToDecimal(normCapHex)/n).toFixed(2)),humidityIndex=2*data[26]+27,humidity=data[humidityIndex],cycleHex=this.decimalToHex(data[12])+this.decimalToHex(data[13]),cycleIndex=this.hexToDecimal(cycleHex),fccHex=this.decimalToHex(data[humidityIndex+3])+this.decimalToHex(data[humidityIndex+4]),fullChargeCapacity=10*this.hexToDecimal(fccHex)/1e3,SOH=cycleIndex<=100?100:Math.min(100,fullChargeCapacity/normCap*100),isHeating=!!Number(binArr[4]);let heatingCurrent=0;if(isHeating){const i=humidityIndex+9;heatingCurrent=10*parseInt([data[i],data[i+1]].map(o=>o.toString(16)).join(""),16)}const isFactoryMode=!!Number(binArr[6]),equilibriumStatus=!(0===data[16]&&0===data[17]),protectStatus=!(0===data[20]&&0===data[21]),protectStateHex=this.decimalToHex(data[20])+this.decimalToHex(data[21]),protectState=this.hexToDecimal(protectStateHex);let protectStatusIndexs=[];for(let i=0;i<16;i++)protectState&1<<i&&protectStatusIndexs.push(i);const protectStatusIndex=protectStatusIndexs.join(","),ntcNums=255&data[26],temperaturesList=Array.from({length:ntcNums},(_,i)=>((256*(255&data[26+2*i+1])+(255&data[26+2*i+2])-2731)/10).toFixed(1)),fahTempList=[];return temperaturesList.forEach(el=>{const value=1.8*Number(el)+32;fahTempList.push(value.toFixed(1))}),{dataStr:dataStr,status:this.hex2string(data[2]),len:data[3],softwareV:this.hex2string(content[18]),chargeSwitch:chargeSwitch,dischargeSwitch:dischargeSwitch,BMSVersion:BMSVersion,totalVoltage:totalVoltage,electricity:electricity,power:power,soc:soc,surplusCapacity:surplusCapacity,normCap:normCap,humidity:humidity,cycleIndex:cycleIndex,fullChargeCapacity:fullChargeCapacity,SOH:SOH,isHeating:isHeating,heatingCurrent:heatingCurrent,isFactoryMode:isFactoryMode,equilibriumStatus:equilibriumStatus,protectStatus:protectStatus,protectStatusIndex:protectStatusIndex,ntcNums:ntcNums,temperaturesList:temperaturesList,fahTempList:fahTempList,fet:fet,seriesNum:seriesNum}}static getFFAA17Async(deviceId){return this.getData(deviceId,{command:["0xFF","0xAA","0x17","0x00","0x17"],commandVerifyHandler:hexArr=>({verified:255==hexArr[0]&&170==hexArr[1]&&23==hexArr[2],pkgLen:hexArr[3]+5}),pkgVerifyHandler:pkg=>{const _pkg=pkg.map(o=>this.hex2string(o)),len=pkg.length,[c1]=this.generateCheckSum(_pkg.slice(2,len-1));return{verified:c1==pkg[len-1]}}},"FFAA_17(获取随机数)")}static getFFAAKeyAsync(deviceId,code,content,type){const commandCode=[code],data=[...content],dataLength=[`0x${this.decimalToHex(data.length,2)}`],check=this.generateCheckSum([...commandCode,...dataLength,...data]),command=["0xff","0xaa",...commandCode,...dataLength,...data,...check];return console.log("command: ---------------",command),this.getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:255==hexArr[0]&&170==hexArr[1]&&hexArr[2]==this.hexToDecimal(code),pkgLen:hexArr[3]+5}),pkgVerifyHandler:pkg=>{const _pkg=pkg.map(o=>this.hex2string(o)),len=pkg.length,[c1]=this.generateCheckSum(_pkg.slice(2,len-1));return{verified:c1==pkg[len-1]}}},`FFAA_${code}(${type})`)}static resolveFFAAKey(data){if(!data)return null;const dataStr=this.hexArr2string(data),response=data[data.length-2];return{dataStr:dataStr,response:response,status:response}}static getBroadcastDataCmd(deviceId){return this.getFFAAKeyAsync(deviceId,"0x19",["0x01"],"广播数据")}static getDD5AE1Async(deviceId,value){const _command=["0xE1","0x02","0x00",value],checks=this.generateCrcCheckSum(_command),command=["0xDD","0x5A",..._command,...checks,"0x77"];return this.getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&225==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"DD5A_E1")}}exports.BleCmdAnalysis=BleCmdAnalysis,exports.default=BleCmdAnalysis;
@@ -1 +0,0 @@
1
- import BleDataProcess from"./BleDataProcess.js";import{getOS,eventBus}from"./commonfun.js";class BleCmdAnalysis extends BleDataProcess{static async _writeAsync(deviceId,value){return console.log("deviceId, value: ",deviceId,value),!(!deviceId||!value)&&new Promise(resolve=>{const characteristicId=this.UUID_WRITE,{isAndroid:isAndroid,isIOS:isIOS}=getOS();console.log("isAndroid, isIOS: ",isAndroid,isIOS);const writeType=isAndroid?"writeNoResponse":"write";uni.writeBLECharacteristicValue({deviceId:deviceId,serviceId:this.serviceId,characteristicId:characteristicId,writeType:writeType,value:value,success:res=>{console.error("res: 写入成功",res),resolve(!0)},fail:e=>{console.error("写入失败",e),resolve(!1)}}),isIOS&&setTimeout(()=>resolve(!0),50)})}static async writeAsync(deviceId,value){return console.log("value: ",value),console.log("deviceId: ",deviceId),!(!deviceId||!value)&&new Promise(async resolve=>{const n=Math.ceil(value.byteLength/20);let res;for(let i=0;i<n;i++){const _value=value.slice(20*i,20*(i+1));if(console.log("分包写入_value: ",_value),await this.sleep(150),res=await this._writeAsync(deviceId,_value),console.log(`分包写入结果 ${i+1}/${n} : ${res}`),!res)return resolve(!1)}resolve(res)})}static async getData(deviceId,{command:command,commandVerifyHandler:commandVerifyHandler=hexArr=>({verified:!1,pkgLen:null}),pkgVerifyHandler:pkgVerifyHandler=pkg=>({verified:!1}),maxRetries:maxRetries=2,retryInterval:retryInterval=300},tag=""){if(!deviceId)throw new Error("deviceId is required");if(!command||command.length<=0)throw new Error("command is required");return new Promise((resolve,reject)=>{let isCompleted=!1,timeoutId=null,responsed=!1,len=null,pkg=[];const cmdContent=this.hexArr2ab(command),cleanup=()=>{isCompleted||(isCompleted=!0,clearTimeout(timeoutId),eventBus.off("setBleChangedCharacteristicValue",dataHandler))},dataHandler=payload=>{if(!payload||payload.deviceId!==deviceId||!payload.value)return;const hexArr=this.ab2decimalArr(payload.value);if(console.warn(tag,"接收到数据:",this.hexArr2string(hexArr)),0!==hexArr.length){if(null===len){const{verified:verified,pkgLen:pkgLen}=commandVerifyHandler(hexArr);console.log("指令验证结果:",{verified:verified,pkgLen:pkgLen}),verified&&(len=pkgLen)}if(len){if(pkg=[...pkg,...hexArr],console.log("当前数据包:",pkg,`长度: ${pkg.length}/${len}`),pkg.length>=len){pkg=pkg.slice(0,len);const{verified:verified}=pkgVerifyHandler(pkg);console.log("数据包验证结果:",{verified:verified}),verified?(responsed=!0,cleanup(),resolve([...pkg])):(len=null,pkg=[])}}else pkg=[]}},writeToDevice=async(attempt=1)=>{try{console.warn(tag,`第${attempt}次写入指令:`,command.join("").replace(/0x/g,"").toUpperCase());const writeSucceed=await this.writeAsync(deviceId,cmdContent);if(console.warn(tag,`第${attempt}次写入结果:`,writeSucceed?"成功":"失败"),!writeSucceed)return void(attempt<maxRetries?setTimeout(()=>writeToDevice(attempt+1),retryInterval):(cleanup(),resolve(null)));await this.sleep(retryInterval),!responsed&&attempt<maxRetries?(console.log(tag,`未收到响应,准备第${attempt+1}次重试`),writeToDevice(attempt+1)):responsed||(console.warn(tag,`达到最大重试次数(${maxRetries}),未收到响应`),cleanup(),resolve(null))}catch(error){console.error(tag,"写入过程发生错误:",error),cleanup(),reject(error)}};timeoutId=setTimeout(()=>{console.warn(tag,"操作超时"),cleanup(),resolve(null)},(maxRetries+2)*retryInterval),eventBus.on("setBleChangedCharacteristicValue",dataHandler),writeToDevice().catch(error=>{cleanup(),reject(error)})})}static async getDDA503Async(deviceId){const hex=await this.getData(deviceId,{command:["0xdd","0xa5","0x03","0x00","0xff","0xfd","0x77"],commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&3==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=this.generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA5_03");return hex?this.resolveDDA503(hex):null}static resolveDDA503(data){if(!data)return null;const dataStr=this.hexArr2string(data),content=data.slice(4,data.length-3),binArr=data[24].toString(2).padStart(8,"0").split("").reverse(),n=Number(binArr[7])?10:100,fet=data[24],chargeSwitch=1==fet||3==fet,dischargeSwitch=2==fet||3==fet,BMSVersion=this.decimalToHex(data[22]),totalVoltage=(((data[4]<<8)+(255&data[5]))/100).toFixed(2);let current=(data[6]<<8)+(255&data[7]);current=current>32768?(current-65536)/n:current/n;const electricity=Number(current.toFixed(2)),power=(parseFloat(totalVoltage)*electricity).toFixed(2),soc=data[23]??0,volumeHex=this.decimalToHex(data[8])+this.decimalToHex(data[9]),seriesNum=data[25]??0,surplusCapacity=Number((this.hexToDecimal(volumeHex)/n).toFixed(2)),normCapHex=this.decimalToHex(data[10])+this.decimalToHex(data[11]),normCap=Number((this.hexToDecimal(normCapHex)/n).toFixed(2)),humidityIndex=2*data[26]+27,humidity=data[humidityIndex],cycleHex=this.decimalToHex(data[12])+this.decimalToHex(data[13]),cycleIndex=this.hexToDecimal(cycleHex),fccHex=this.decimalToHex(data[humidityIndex+3])+this.decimalToHex(data[humidityIndex+4]),fullChargeCapacity=10*this.hexToDecimal(fccHex)/1e3,SOH=cycleIndex<=100?100:Math.min(100,fullChargeCapacity/normCap*100),isHeating=!!Number(binArr[4]);let heatingCurrent=0;if(isHeating){const i=humidityIndex+9;heatingCurrent=10*parseInt([data[i],data[i+1]].map(o=>o.toString(16)).join(""),16)}const isFactoryMode=!!Number(binArr[6]),equilibriumStatus=!(0===data[16]&&0===data[17]),protectStatus=!(0===data[20]&&0===data[21]),protectStateHex=this.decimalToHex(data[20])+this.decimalToHex(data[21]),protectState=this.hexToDecimal(protectStateHex);let protectStatusIndexs=[];for(let i=0;i<16;i++)protectState&1<<i&&protectStatusIndexs.push(i);const protectStatusIndex=protectStatusIndexs.join(","),ntcNums=255&data[26],temperaturesList=Array.from({length:ntcNums},(_,i)=>((256*(255&data[26+2*i+1])+(255&data[26+2*i+2])-2731)/10).toFixed(1)),fahTempList=[];return temperaturesList.forEach(el=>{const value=1.8*Number(el)+32;fahTempList.push(value.toFixed(1))}),{dataStr:dataStr,status:this.hex2string(data[2]),len:data[3],softwareV:this.hex2string(content[18]),chargeSwitch:chargeSwitch,dischargeSwitch:dischargeSwitch,BMSVersion:BMSVersion,totalVoltage:totalVoltage,electricity:electricity,power:power,soc:soc,surplusCapacity:surplusCapacity,normCap:normCap,humidity:humidity,cycleIndex:cycleIndex,fullChargeCapacity:fullChargeCapacity,SOH:SOH,isHeating:isHeating,heatingCurrent:heatingCurrent,isFactoryMode:isFactoryMode,equilibriumStatus:equilibriumStatus,protectStatus:protectStatus,protectStatusIndex:protectStatusIndex,ntcNums:ntcNums,temperaturesList:temperaturesList,fahTempList:fahTempList,fet:fet,seriesNum:seriesNum}}static getFFAA17Async(deviceId){return this.getData(deviceId,{command:["0xFF","0xAA","0x17","0x00","0x17"],commandVerifyHandler:hexArr=>({verified:255==hexArr[0]&&170==hexArr[1]&&23==hexArr[2],pkgLen:hexArr[3]+5}),pkgVerifyHandler:pkg=>{const _pkg=pkg.map(o=>this.hex2string(o)),len=pkg.length,[c1]=this.generateCheckSum(_pkg.slice(2,len-1));return{verified:c1==pkg[len-1]}}},"FFAA_17(获取随机数)")}static getFFAAKeyAsync(deviceId,code,content,type){const commandCode=[code],data=[...content],dataLength=[`0x${this.decimalToHex(data.length,2)}`],check=this.generateCheckSum([...commandCode,...dataLength,...data]),command=["0xff","0xaa",...commandCode,...dataLength,...data,...check];return console.log("command: ---------------",command),this.getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:255==hexArr[0]&&170==hexArr[1]&&hexArr[2]==this.hexToDecimal(code),pkgLen:hexArr[3]+5}),pkgVerifyHandler:pkg=>{const _pkg=pkg.map(o=>this.hex2string(o)),len=pkg.length,[c1]=this.generateCheckSum(_pkg.slice(2,len-1));return{verified:c1==pkg[len-1]}}},`FFAA_${code}(${type})`)}static resolveFFAAKey(data){if(!data)return null;const dataStr=this.hexArr2string(data),response=data[data.length-2];return{dataStr:dataStr,response:response,status:response}}static getBroadcastDataCmd(deviceId){return this.getFFAAKeyAsync(deviceId,"0x19",["0x01"],"广播数据")}static getDD5AE1Async(deviceId,value){const _command=["0xE1","0x02","0x00",value],checks=this.generateCrcCheckSum(_command),command=["0xDD","0x5A",..._command,...checks,"0x77"];return this.getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&225==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"DD5A_E1")}}export{BleCmdAnalysis,BleCmdAnalysis as default};