@jiabaida/tools 1.0.3 → 1.0.6

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 +1 @@
1
- import{ref}from"vue";import{ab2decimalArr,hexToDecimal}from"./BleDataProcess.js";import{getOS,eventBus}from"./commonfun.js";const serviceId="0000FF00-0000-1000-8000-00805F9B34FB",bluetoothAdapterState=ref({available:!1,discovering:!1}),initBle=async()=>{const checkBluetoothStatus=async()=>new Promise((resolve,reject)=>{uni.openBluetoothAdapter({success:async res=>{console.log("openBluetoothAdapter success",res),resolve(res);try{onBluetoothDeviceFound(),onBLECharacteristicValueChange(),onBLEConnectionStateChange(),onBluetoothAdapterStateChange()}catch(error){console.log("error: ",error),reject(error)}},fail:err=>{console.log("openBluetoothAdapter fail",err),reject(err)}})});try{const{isAndroid:isAndroid}=getOS();isAndroid?(async()=>{const timeoutPromise=new Promise((resolve,reject)=>{setTimeout(()=>{reject(new Error("网络信号差或连接异常,请检查网络情况"))},1e4)}),locationPromise=new Promise((resolve,reject)=>{uni.getLocation({type:"wgs84",success:res=>{console.log("位置信息-----------",res),resolve(res)},fail:err=>{console.log("位置信息err",err),reject(err)}})});Promise.race([locationPromise,timeoutPromise]).then(res=>{checkBluetoothStatus()}).catch(err=>{console.log("位置获取失败或超时:",err),Promise.reject({code:1})})})():checkBluetoothStatus()}catch(error){console.error("初始化蓝牙失败:",error),Promise.reject({code:error.code||error.errCode||-1})}},getBluetoothAdapterState=async()=>new Promise((resolve,reject)=>{uni.getBluetoothAdapterState({success:res=>{console.log("getBluetoothAdapterState success",res),resolve(res)},fail:err=>{console.log("getBluetoothAdapterState fail",err),reject(err)}})}),startDevicesDiscovery=async(allowDuplicatesKey=!0)=>new Promise((resolve,reject)=>{bluetoothAdapterState.value.discovering?reject(new Error("蓝牙设备搜索已在进行中")):uni.startBluetoothDevicesDiscovery({services:[serviceId],allowDuplicatesKey:allowDuplicatesKey,success:async res=>{console.log("广播设备 success",res),resolve(res)},fail:err=>{console.log("广播设备 fail",err),reject(err)}})}),stopBluetoothDevicesDiscovery=async()=>new Promise((resolve,reject)=>{uni.stopBluetoothDevicesDiscovery({success:res=>{console.log("停止广播设备 success",res),resolve(res)},fail:err=>{console.log("停止广播设备 fail",err),reject(err)},complete:res=>{console.log("停止广播设备 取消订阅"),eventBus.off("setBluetoothDeviceFound")}})}),onBluetoothDeviceFound=async()=>{uni.onBluetoothDeviceFound(characteristic=>{console.log("setBluetoothDeviceFound",characteristic);const device=(device=>{const adv=device?.advertisData;if(!adv)return null;if(adv){const advHex=Array.prototype.map.call(new Uint8Array(adv),o=>("00"+o.toString(16)).slice(-2)).join("").toUpperCase();let macAddr=advHex.slice(0,12).toUpperCase(),arr=macAddr.match(/(.{2})/g);const flag=macAddr.slice(-4);"C1A4"!=flag&&"C2A5"!=flag&&"C2A8"!=flag||arr.reverse(),macAddr=arr.join(":"),device.hasFound=!0;const moduleType=advHex.slice(12,16),socHex=advHex.slice(16,18),soc=socHex||0==socHex?hexToDecimal(socHex):"",productType=advHex.slice(18,20),protocolVersion=advHex.slice(20,22),appkeyStatus=advHex.slice(22,24),tempVoltage=advHex.slice(24,26),voltage=tempVoltage||0==tempVoltage?hexToDecimal(tempVoltage):"",tempCurrent=advHex.slice(26,28),current=tempCurrent||0==tempCurrent?hexToDecimal(tempCurrent):"",broadcastLen=advHex.length/2,isNewAppKey=advHex.length>=24;device={...device,macAddr:macAddr,moduleType:moduleType,soc:soc,productType:productType,advHex:advHex,protocolVersion:protocolVersion,appkeyStatus:appkeyStatus,broadcastLen:broadcastLen,isNewAppKey:isNewAppKey,voltage:voltage,current:current}}return device})(characteristic.devices[0]);device&&eventBus.emit("setBluetoothDeviceFound",device)})},onFoundDevice=callback=>{eventBus.on("setBluetoothDeviceFound",callback)},onBluetoothAdapterStateChange=async()=>{uni.onBluetoothAdapterStateChange(res=>{console.log("onBluetoothAdapterStateChange监听蓝牙适配器变化",res),bluetoothAdapterState.value=res})},onBLECharacteristicValueChange=async()=>{uni.onBLECharacteristicValueChange(characteristic=>{const decimalArr=ab2decimalArr(characteristic.value);console.warn("decimalArr: 监听到的回复-------------------",decimalArr),eventBus.emit("setBleChangedCharacteristicValue",characteristic)})},onBLEConnectionStateChange=async()=>{uni.onBLEConnectionStateChange(characteristic=>{console.log("onBLEConnectionStateChange",characteristic),eventBus.emit("setBleChangedConnectionState",characteristic)})},onBleChangedConnectionState=callback=>{eventBus.on("setBleChangedConnectionState",callback)},createBLEConnection=async(deviceId,timeout=1e4)=>new Promise((resolve,reject)=>{console.log(deviceId,"点击的设备信息"),uni.createBLEConnection({deviceId:deviceId,timeout:timeout,success:res=>{console.log(res,"连接成功"),resolve(!0)},fail:err=>{console.log(err,"Connection"),-1==(err.code||err.errCode)?resolve(!0):reject(err)}})}),withRetry=async(asyncOperation,maxRetries=20,retryInterval=100,type)=>new Promise((resolve,reject)=>{let retryCount=0;const attempt=async()=>{try{const result=await asyncOperation();resolve(result)}catch(error){if(retryCount>=maxRetries)return void reject(new Error(`${type}失败,${error.message} (已重试${maxRetries}次)`));retryCount++,console.warn(`${type}失败,第${retryCount}次重试:`,error.message),setTimeout(attempt,retryInterval)}};attempt()}),getBLEDeviceServices=deviceId=>withRetry(async()=>{const res=await new Promise((resolve,reject)=>{uni.getBLEDeviceServices({deviceId:deviceId,success:resolve,fail:reject})});if(console.log("获取蓝牙服务成功:",res),0===res.services.length)throw new Error("未找到蓝牙服务");return await getBLEDeviceCharacteristics(deviceId),res.services},20,100,"获取蓝牙服务"),getBLEDeviceCharacteristics=async deviceId=>withRetry(async()=>{const res=await new Promise((resolve,reject)=>{uni.getBLEDeviceCharacteristics({deviceId:deviceId,serviceId:serviceId,success:resolve,fail:reject})});return console.log("获取特征值成功:",res),res.characteristics},20,100,"获取蓝牙特征值"),notify=async deviceId=>new Promise((resolve,reject)=>{uni.notifyBLECharacteristicValueChange({deviceId:deviceId,serviceId:serviceId,characteristicId:"0000FF01-0000-1000-8000-00805F9B34FB",state:!0,success:res=>{console.log("订阅===========",res),resolve(res)},fail:reject})}),disConnect=deviceId=>new Promise((resolve,reject)=>{uni.closeBLEConnection({deviceId:deviceId,success:res=>{resolve(res),console.log(res,"断开连接成功")},fail:err=>{reject(err),console.log(err,"err 断开连接")}})}),connectAsync=async(deviceId,timeout=1e4)=>new Promise(async(resolve,reject)=>{try{await createBLEConnection(deviceId,timeout),await getBLEDeviceServices(deviceId),await notify(deviceId),resolve(!0)}catch(error){console.log("error: ",error),reject(error)}}),scanHandle=(historyConnectedList=[],connectFn=device=>{},failScanFn=err=>{})=>{uni.scanCode({scanType:["barCode","qrCode"],success:async({result:result})=>{console.log("扫描内容: "+result);let searchKey=result;try{const formatMacAddress=mac=>mac.replace(/(.{2})/g,"$1:").slice(0,-1).toUpperCase();let isMac=!1;result.includes("?qrCodeInfo=")?(searchKey=result.split("?qrCodeInfo=")[1],searchKey.includes(":")?(searchKey=searchKey.slice(-17).toUpperCase(),isMac=!0):(searchKey=searchKey.slice(-12),searchKey=formatMacAddress(searchKey),isMac=!0)):17===result.length&&result.includes(":")?(searchKey=result.toUpperCase(),isMac=!0):12===result.length&&(searchKey=formatMacAddress(result),isMac=!0);const{isAndroid:isAndroid}=getOS(),matchedHistoryDevice=historyConnectedList.find(item=>item.macAddr==searchKey);if(matchedHistoryDevice)return void connectFn(matchedHistoryDevice);isAndroid&&isMac?connectFn({deviceId:searchKey,macAddr:searchKey,name:searchKey}):foundScanDevice(searchKey,connectFn)}catch(error){console.log(error)}},complete:err=>{console.log("scanCode err",err),failScanFn(err)}})},foundScanDevice=async(result,connectFn)=>{const deviceList=[];await startDevicesDiscovery(),onFoundDevice(device=>{deviceList.push(device);const findDevice=device.macAddr===result||device.name===result;findDevice?(scanTimeout&&(clearTimeout(scanTimeout),scanTimeout=null),uni.stopBluetoothDevicesDiscovery(),connectFn(findDevice)):console.log("未找到设备,继续搜索中...")});let scanTimeout=setTimeout(async()=>{try{console.log("stopBluetoothDevicesDiscovery",deviceList),clearInterval(scanTimer),scanTimer=null,uni.stopBluetoothDevicesDiscovery();const findDevice=deviceList.find(device=>device.macAddr===result||device.name===result);connectFn(findDevice)}finally{}},5e3)};export{connectAsync,createBLEConnection,disConnect,foundScanDevice,getBLEDeviceCharacteristics,getBLEDeviceServices,getBluetoothAdapterState,initBle,notify,onBLECharacteristicValueChange,onBLEConnectionStateChange,onBleChangedConnectionState,onBluetoothAdapterStateChange,onBluetoothDeviceFound,onFoundDevice,scanHandle,startDevicesDiscovery,stopBluetoothDevicesDiscovery};
1
+ import{ref}from"vue";import{ab2decimalArr,hexToDecimal}from"./BleDataProcess.js";import{getOS,eventBus}from"./commonfun.js";const serviceId="0000FF00-0000-1000-8000-00805F9B34FB",{isAndroid:isAndroid,isIOS:isIOS}=getOS(),bluetoothAdapterState=ref({available:!1,discovering:!1});var isInit=!1;const checkBluetoothStatus=async(successCallback=()=>{})=>new Promise((resolve,reject)=>{uni.openBluetoothAdapter({success:async res=>{successCallback&&successCallback(res),resolve(res)},fail:err=>{console.log("openBluetoothAdapter fail4-----",err),err&&3==err?.errno&&reject({code:105,message:"请授权微信位置信息和蓝牙权限"}),err&&103==err?.errno&&reject({code:106,message:"请授权蓝牙和位置权限,并重启小程序"}),reject({code:102,message:"当前手机蓝牙不可用,请检查手机蓝牙状态"})}})}),checkLocationStatus=async(successCallback=()=>{})=>{const timeoutPromise=new Promise((resolve,reject)=>{setTimeout(()=>{reject({code:101,message:"网络信号差或连接异常,请检查网络情况"})},1e4)}),locationPromise=new Promise((resolve,reject)=>{uni.getLocation({type:"wgs84",success:res=>{console.log("位置信息-----------",res),resolve(res)},fail:err=>{console.log("位置信息err",err),err&&103==err?.errno&&reject({code:103,message:"请授权小程序位置信息权限, 并重启小程序。"}),err&&2==err?.errCode&&reject({code:101,message:"网络信号差或连接异常,请检查网络情况"}),reject({code:104,message:"请授权微信位置信息权限, 并重启小程序。"})}})});return Promise.race([locationPromise,timeoutPromise]).then(async res=>await checkBluetoothStatus(successCallback))},getBluetoothPermission=async(successCallback=()=>{})=>{try{return isAndroid?await checkLocationStatus(successCallback):await checkBluetoothStatus(successCallback)}catch(error){throw console.error("初始化蓝牙失败:",error),error}},initBle=async()=>await getBluetoothPermission(()=>{try{onBluetoothDeviceFound(),onBLECharacteristicValueChange(),onBLEConnectionStateChange(),onBluetoothAdapterStateChange(),isInit=!0}catch(error){throw error}}),getBluetoothAdapterState=async()=>new Promise((resolve,reject)=>{uni.getBluetoothAdapterState({success:res=>{console.log("getBluetoothAdapterState success",res),resolve(res)},fail:err=>{console.log("getBluetoothAdapterState fail",err),reject(err)}})}),startDevicesDiscovery=async(allowDuplicatesKey=!0)=>new Promise((resolve,reject)=>{bluetoothAdapterState.value.discovering?reject(new Error("蓝牙设备搜索已在进行中")):uni.startBluetoothDevicesDiscovery({services:[serviceId],allowDuplicatesKey:allowDuplicatesKey,success:async res=>{console.log("广播设备 success",res),resolve(res)},fail:err=>{console.log("广播设备 fail",err),reject(err)}})}),stopBluetoothDevicesDiscovery=async()=>(bluetoothAdapterState.value={available:bluetoothAdapterState.value.available,discovering:!1},new Promise((resolve,reject)=>{uni.stopBluetoothDevicesDiscovery({success:res=>{console.log("停止广播设备 success",res),resolve(res)},fail:err=>{console.log("停止广播设备 fail",err),reject(err)},complete:res=>{console.log("停止广播设备 取消订阅"),eventBus.off("setBluetoothDeviceFound")}})})),onBluetoothDeviceFound=async()=>{uni.onBluetoothDeviceFound(characteristic=>{console.log("setBluetoothDeviceFound",characteristic);const device=(device=>{const adv=device?.advertisData;if(!adv)return null;if(adv){const advHex=Array.prototype.map.call(new Uint8Array(adv),o=>("00"+o.toString(16)).slice(-2)).join("").toUpperCase();let macAddr=advHex.slice(0,12).toUpperCase(),arr=macAddr.match(/(.{2})/g);const flag=macAddr.slice(-4);"C1A4"!=flag&&"C2A5"!=flag&&"C2A8"!=flag||arr.reverse(),macAddr=arr.join(":"),device.hasFound=!0;const moduleType=advHex.slice(12,16),socHex=advHex.slice(16,18),soc=socHex||0==socHex?hexToDecimal(socHex):"",productType=advHex.slice(18,20);let protocolVersion=advHex.slice(20,22);if(protocolVersion){const v=hexToDecimal(protocolVersion);macAddr.startsWith("A5:C2")&&v<=35&&(protocolVersion="01")}const appkeyStatus=advHex.slice(22,24),tempVoltage=advHex.slice(24,26),voltage=tempVoltage||0==tempVoltage?hexToDecimal(tempVoltage):"",tempCurrent=advHex.slice(26,28),current=tempCurrent||0==tempCurrent?hexToDecimal(tempCurrent):"",broadcastLen=advHex.length/2,isNewAppKey=advHex.length>=24;device={...device,macAddr:macAddr,moduleType:moduleType,soc:soc,productType:productType,advHex:advHex,protocolVersion:protocolVersion,appkeyStatus:appkeyStatus,broadcastLen:broadcastLen,isNewAppKey:isNewAppKey,voltage:voltage,current:current}}return device})(characteristic.devices[0]);device&&eventBus.emit("setBluetoothDeviceFound",device)})},onFoundDevice=callback=>{eventBus.on("setBluetoothDeviceFound",callback)},onBluetoothAdapterStateChange=async()=>{uni.onBluetoothAdapterStateChange(res=>{console.log("onBluetoothAdapterStateChange监听蓝牙适配器变化",res),bluetoothAdapterState.value=res})},onBLECharacteristicValueChange=async()=>{uni.onBLECharacteristicValueChange(characteristic=>{const decimalArr=ab2decimalArr(characteristic.value);console.warn("decimalArr: 监听到的回复-------------------",decimalArr),eventBus.emit("setBleChangedCharacteristicValue",characteristic)})},onBLEConnectionStateChange=async()=>{uni.onBLEConnectionStateChange(characteristic=>{console.log("onBLEConnectionStateChange",characteristic),eventBus.emit("setBleChangedConnectionState",characteristic)})},onBleChangedConnectionState=callback=>{eventBus.on("setBleChangedConnectionState",callback)},createBLEConnection=async(deviceId,timeout=1e4)=>new Promise((resolve,reject)=>{console.log(deviceId,"点击的设备信息"),uni.createBLEConnection({deviceId:deviceId,timeout:timeout,success:res=>{console.log(res,"连接成功"),resolve(!0)},fail:err=>{console.log(err,"Connection"),-1==(err.code||err.errCode)?resolve(!0):reject(err)}})}),withRetry=async(asyncOperation,maxRetries=20,retryInterval=100,type)=>new Promise((resolve,reject)=>{let retryCount=0;const attempt=async()=>{try{const result=await asyncOperation();resolve(result)}catch(error){if(retryCount>=maxRetries)return void reject(new Error(`${type}失败,${error.message} (已重试${maxRetries}次)`));retryCount++,console.warn(`${type}失败,第${retryCount}次重试:`,error.message),setTimeout(attempt,retryInterval)}};attempt()}),getBLEDeviceServices=deviceId=>withRetry(async()=>{const res=await new Promise((resolve,reject)=>{uni.getBLEDeviceServices({deviceId:deviceId,success:resolve,fail:reject})});if(console.log("获取蓝牙服务成功:",res),0===res.services.length)throw new Error("未找到蓝牙服务");return await getBLEDeviceCharacteristics(deviceId),res.services},20,100,"获取蓝牙服务"),getBLEDeviceCharacteristics=async deviceId=>withRetry(async()=>{const res=await new Promise((resolve,reject)=>{uni.getBLEDeviceCharacteristics({deviceId:deviceId,serviceId:serviceId,success:resolve,fail:reject})});return console.log("获取特征值成功:",res),res.characteristics},20,100,"获取蓝牙特征值"),notify=async deviceId=>new Promise((resolve,reject)=>{uni.notifyBLECharacteristicValueChange({deviceId:deviceId,serviceId:serviceId,characteristicId:"0000FF01-0000-1000-8000-00805F9B34FB",state:!0,success:res=>{console.log("订阅===========",res),resolve(res)},fail:reject})}),disConnect=deviceId=>new Promise((resolve,reject)=>{uni.closeBLEConnection({deviceId:deviceId,success:res=>{resolve(res),console.log(res,"断开连接成功")},fail:err=>{reject(err),console.log(err,"err 断开连接")}})}),connectAsync=async(deviceId,timeout=1e4)=>new Promise(async(resolve,reject)=>{try{await createBLEConnection(deviceId,timeout),await getBLEDeviceServices(deviceId),await notify(deviceId),resolve(!0)}catch(error){console.log("error: ",error),reject(error)}}),scanHandle=(historyConnectedList=[],connectFn=device=>{},failScanFn=err=>{})=>{uni.scanCode({scanType:["barCode","qrCode"],success:async({result:result})=>{console.log("扫描内容: "+result);let searchKey=result;try{const formatMacAddress=mac=>mac.replace(/(.{2})/g,"$1:").slice(0,-1).toUpperCase();let isMac=!1;result.includes("?qrCodeInfo=")?(searchKey=result.split("?qrCodeInfo=")[1],searchKey.includes(":")?(searchKey=searchKey.slice(-17).toUpperCase(),isMac=!0):(searchKey=searchKey.slice(-12),searchKey=formatMacAddress(searchKey),isMac=!0)):17===result.length&&result.includes(":")?(searchKey=result.toUpperCase(),isMac=!0):12===result.length&&(searchKey=formatMacAddress(result),isMac=!0);const matchedHistoryDevice=historyConnectedList.find(item=>item.macAddr==searchKey);if(matchedHistoryDevice)return void connectFn(matchedHistoryDevice);isAndroid&&isMac?connectFn({deviceId:searchKey,macAddr:searchKey,name:searchKey}):foundScanDevice(searchKey,connectFn)}catch(error){console.log(error)}},complete:err=>{},fail:err=>{console.log("scanCode err",err),failScanFn(err)}})},foundScanDevice=async(result,connectFn)=>{const deviceList=[];await startDevicesDiscovery(isIOS),onFoundDevice(device=>{deviceList.push(device);const findDevice=device.macAddr===result||device.name===result;findDevice?(scanTimeout&&(clearTimeout(scanTimeout),scanTimeout=null),uni.stopBluetoothDevicesDiscovery(),connectFn(findDevice)):console.log("未找到设备,继续搜索中...")});let scanTimeout=setTimeout(async()=>{try{console.log("stopBluetoothDevicesDiscovery",deviceList),uni.stopBluetoothDevicesDiscovery();const findDevice=deviceList.find(device=>device.macAddr===result||device.name===result);connectFn(findDevice)}finally{}},5e3)};export{checkBluetoothStatus,checkLocationStatus,connectAsync,createBLEConnection,disConnect,foundScanDevice,getBLEDeviceCharacteristics,getBLEDeviceServices,getBluetoothAdapterState,getBluetoothPermission,initBle,isInit,notify,onBLECharacteristicValueChange,onBLEConnectionStateChange,onBleChangedConnectionState,onBluetoothAdapterStateChange,onBluetoothDeviceFound,onFoundDevice,scanHandle,startDevicesDiscovery,stopBluetoothDevicesDiscovery};
@@ -1 +1 @@
1
- import{getSysParamCmd}from"./readAndSetParam.js";import{decimalToHex,hexToDecimal}from"../BleDataProcess.js";import{systemJson,funcAndTempFuncJson,capVolInfoJson,equalizerFunJson,tempInfoJson,currentInfoJson,voltageInfoJson,capInfoJson,batteryInfoJson,funcJson,tempFuncJson}from"../dataJson/baseParamsJson.js";import{getProtectCountCmd,enterFactory,readExistFactory}from"./BleCmdDD.js";function format(value,n=1,offset=0,scope=0){if(!value)return null;value=value.map(el=>{const hexValue=decimalToHex(el);return console.log("el: ------------",hexValue),hexValue});const v=parseInt(value.join(""),16)*n+offset;if(null==scope)return v;const formatted=v.toFixed(scope);return Number(formatted)}function formatTemp(arr){if(!arr)return null;let string="0x"+toHexString(arr),value=parseInt(string,16);return value=(value-2731)/10,Number(value)}function formatBinary(arr){if(!arr)return null;return arr.map(num=>num.toString(2).padStart(8,"0")).join("").split("").map(Number).reverse()}const sendCmdSeq=async(datasInfo,chipType,deviceId,params)=>{let index=0;for(chipType||await enterFactory(deviceId);index<params.length;){const item=params[index];try{const basedata=await getSysParamCmd(chipType,deviceId,item,!1);datasInfo[item.key]=basedata,index++}catch(error){console.error(`获取参数 ${item.key} 失败:`,error),index++}}chipType||await readExistFactory(deviceId)};let crsDivisor=.1;const getBaseParams=async(chipType,deviceData,index,paramObj)=>{console.log("chipType: ",chipType);const deviceId=deviceData?.deviceId,protocolVersion=deviceData?.protocolVersion||"00";console.warn("protocolVersion: ",protocolVersion);const v=hexToDecimal(protocolVersion);(2==v||v>=20&&v<80)&&(crsDivisor=.01),console.log("v: ",v);try{let dataInfo={};switch(index){case 1:let datasInfo1={};return await sendCmdSeq(datasInfo1,chipType,deviceId,batteryInfoJson),dataInfo=getBaseInfo(datasInfo1),dataInfo;case 2:let datasInfo2={};if(chipType){const capData=await getSysParamCmd(chipType,deviceId,{...capInfoJson[0],paramLength:4});console.warn("capData: ",capData),datasInfo2.normCap=capData?.slice(0,2),datasInfo2.cycleCap=capData?.slice(2,4);const capData2=await getSysParamCmd(chipType,deviceId,capInfoJson[2]);datasInfo2.fullCap=capData2?.slice(0,2)}else await sendCmdSeq(datasInfo2,chipType,deviceId,capInfoJson);return dataInfo=getCapInfo(datasInfo2),dataInfo;case 3:let datasInfo3={};if(chipType){let vindex=voltageInfoJson.findIndex(el=>16==el.paramNo);console.log("vindex: ------------",vindex);let vindex1=voltageInfoJson.findIndex(el=>48==el.paramNo),vindex2=voltageInfoJson.findIndex(el=>38==el.paramNo);const voltageData=await getSysParamCmd(chipType,deviceId,{...voltageInfoJson[vindex],paramLength:16}),voltageData1=await getSysParamCmd(chipType,deviceId,{...voltageInfoJson[vindex1],paramLength:8}),voltageData2=await getSysParamCmd(chipType,deviceId,{...voltageInfoJson[vindex2],paramLength:4});console.log("voltageData: ",voltageData),datasInfo3.allOvervoltageProtect=voltageData?.slice(0,2),datasInfo3.allOverpressureRecovery=voltageData?.slice(2,4),datasInfo3.allLowvoltageProtect=voltageData?.slice(4,6),datasInfo3.allLowvoltageRecover=voltageData?.slice(6,8),datasInfo3.singleOvervoltageProtect=voltageData?.slice(8,10),datasInfo3.singleOverpressureRecovery=voltageData?.slice(10,12),datasInfo3.singleLowvoltageProtect=voltageData?.slice(12,14),datasInfo3.singleLowvoltageRecover=voltageData?.slice(14,16),datasInfo3.allLowvoltageDelay=voltageData1?.slice(0,2),datasInfo3.allOverpressureDelay=voltageData1?.slice(2,4),datasInfo3.singleLowvoltageDelayed=voltageData1?.slice(4,6),datasInfo3.singleOverpressureDelay=voltageData1?.slice(6,8),datasInfo3.hardwareOV=voltageData2?.slice(0,2),datasInfo3.hardwareUV=voltageData2?.slice(2,4)}else await sendCmdSeq(datasInfo3,chipType,deviceId,voltageInfoJson);return dataInfo=getVoltageInfo(datasInfo3,chipType),dataInfo;case 4:let datasInfo4={};if(chipType){let cindex=currentInfoJson.findIndex(el=>24==el.paramNo),cindex1=currentInfoJson.findIndex(el=>52==el.paramNo),cindex2=currentInfoJson.findIndex(el=>40==el.paramNo);const currentData=await getSysParamCmd(chipType,deviceId,{...currentInfoJson[cindex],paramLength:4}),currentData1=await getSysParamCmd(chipType,deviceId,{...currentInfoJson[cindex1],paramLength:8}),currentData2=await getSysParamCmd(chipType,deviceId,{...currentInfoJson[cindex2],paramLength:8});console.log("currentData: ",currentData),datasInfo4.occhg=currentData?.slice(0,2),datasInfo4.dischargeOvercurrentProtect=currentData?.slice(2,4),datasInfo4.chargeOvercurrentDelay=currentData1?.slice(0,2),datasInfo4.chargeOvercurrentRecoverDelay=currentData1?.slice(2,4),datasInfo4.dischargeOvercurrentDelay=currentData1?.slice(4,6),datasInfo4.dischargeOvercurrentRecoverDelay=currentData1?.slice(6,8),datasInfo4.level2OvercurrentProtect=currentData2?.slice(0,2),datasInfo4.level2OvercurrentProtectV=currentData2?.slice(2,4),datasInfo4.shortcircuiProtectRecoverDelay=currentData2?.slice(6,8)}else await sendCmdSeq(datasInfo4,chipType,deviceId,currentInfoJson);return dataInfo=getCurrentInfo(datasInfo4,chipType),dataInfo;case 5:let datasInfo5={};if(chipType){let tindex=tempInfoJson.findIndex(el=>8==el.paramNo),tindex1=tempInfoJson.findIndex(el=>44==el.paramNo);const tempData=await getSysParamCmd(chipType,deviceId,{...tempInfoJson[tindex],paramLength:16}),tempData1=await getSysParamCmd(chipType,deviceId,{...tempInfoJson[tindex1],paramLength:8});console.log("tempData: ",tempData),datasInfo5.chargeHightempProtect=tempData?.slice(0,2),datasInfo5.chargeHightempRecover=tempData?.slice(2,4),datasInfo5.chargeLowtempProtect=tempData?.slice(4,6),datasInfo5.chargeLowtempRecover=tempData?.slice(6,8),datasInfo5.dischargingHightempProtect=tempData?.slice(8,10),datasInfo5.dischargingHightempRecover=tempData?.slice(10,12),datasInfo5.dischargingLowtempProtect=tempData?.slice(12,14),datasInfo5.dischargingLowtempRecover=tempData?.slice(14,16),datasInfo5.chargeLowtempDelay=tempData1?.slice(0,2),datasInfo5.chargeHightempDelay=tempData1?.slice(2,4),datasInfo5.dischargingLowtempDelay=tempData1?.slice(4,6),datasInfo5.dischargingHightempDelay=tempData1?.slice(6,8)}else await sendCmdSeq(datasInfo5,chipType,deviceId,tempInfoJson);return dataInfo=getTempInfo(datasInfo5,chipType),dataInfo;case 6:let datasInfo6={};if(chipType){const equalizerFunData=await getSysParamCmd(chipType,deviceId,{...equalizerFunJson[0],paramLength:4});console.log("equalizerFunData: ",equalizerFunData),datasInfo6.equalizingVoltage=equalizerFunData?.slice(0,2),datasInfo6.accuracyEqualization=equalizerFunData?.slice(2,4)}else await sendCmdSeq(datasInfo6,chipType,deviceId,equalizerFunJson);return dataInfo=getEqualizerFunInfo(datasInfo6),dataInfo;case 7:let datasInfo7={};if(chipType){let capVolIndex=capVolInfoJson.findIndex(el=>34==el.paramNo),capVolIndex1=capVolInfoJson.findIndex(el=>106==el.paramNo);const capVolInfoData=await getSysParamCmd(chipType,deviceId,{...capVolInfoJson[0],paramLength:4}),capVolInfoData1=await getSysParamCmd(chipType,deviceId,{...capVolInfoJson[capVolIndex],paramLength:8}),capVolInfoData2=await getSysParamCmd(chipType,deviceId,{...capVolInfoJson[capVolIndex1],paramLength:12});console.log("capVolInfoData: ",capVolInfoData),datasInfo7.fullVolt=capVolInfoData?.slice(0,2),datasInfo7.emptyVolt=capVolInfoData?.slice(2,4),datasInfo7.voltage80p=capVolInfoData1?.slice(0,2),datasInfo7.voltage60p=capVolInfoData1?.slice(2,4),datasInfo7.voltage40p=capVolInfoData1?.slice(4,6),datasInfo7.voltage20p=capVolInfoData1?.slice(6,8),datasInfo7.voltage90p=capVolInfoData2?.slice(0,2),datasInfo7.voltage70p=capVolInfoData2?.slice(2,4),datasInfo7.voltage50p=capVolInfoData2?.slice(4,6),datasInfo7.voltage30p=capVolInfoData2?.slice(6,8),datasInfo7.voltage10p=capVolInfoData2?.slice(8,10),datasInfo7.voltage100p=capVolInfoData2?.slice(10,12)}else await sendCmdSeq(datasInfo7,chipType,deviceId,capVolInfoJson);return dataInfo=getcapVolInfoInfo(datasInfo7,chipType),dataInfo;case 9:let datasInfo9={};if(chipType){const funcAndTempFuncData=await getSysParamCmd(chipType,deviceId,{...funcAndTempFuncJson[0],paramLength:4});console.log("funcAndTempFuncData: ",funcAndTempFuncData),datasInfo9.func=funcAndTempFuncData?.slice(0,2),datasInfo9.tempFunc=funcAndTempFuncData?.slice(2,4)}else await sendCmdSeq(datasInfo9,chipType,deviceId,funcAndTempFuncJson);return dataInfo=getFuncAndTempFuncInfo(datasInfo9),dataInfo;case 10:let datasInfo10={};return await sendCmdSeq(datasInfo10,chipType,deviceId,systemJson),dataInfo=getSystemInfo(datasInfo10),dataInfo;case 11:const counts=await getProtectCountCmd(deviceId);return console.log("counts: ",counts),counts;default:if(!paramObj)return null;let defaultDataInfo={};const onedata=await getSysParamCmd(chipType,deviceId,paramObj);return defaultDataInfo[paramObj.key]=onedata?.slice(0,2),defaultDataInfo}}catch(error){throw console.error("error: 读系统参数报错 getBaseParams",error),error}},getResistance=async(chipType,deviceId)=>{try{const rsnsValue=await getSysParamCmd(chipType,deviceId,systemJson[2]);return format(rsnsValue,crsDivisor,0,2)}catch(error){throw console.error("error: 读检流阻值报错 getResistance",error),error}},getBaseInfo=async datas=>{try{console.log("datas: ",datas);const barCode=getCharCodeConnect(datas?.barCode),manufacturer=getCharCodeConnect(datas?.manufacturer),model=getCharCodeConnect(datas?.model),bmsModel=getCharCodeConnect(datas?.bmsModel,!0),producedDate=function(content){if(!content)return null;let arr=content.splice(0,2),string="0x";return arr.forEach(el=>{string+=decimalToHex(el)}),console.log(string,"string日期"),`${2e3+(string>>9)}-${string>>5&15}-${31&string}`}(datas?.producedDate);return{barCode:barCode,manufacturer:manufacturer,model:model,bmsModel:bmsModel,producedDate:producedDate,bmsAddr:function(content){if(!content)return null;return console.log(content,"content======"),toHexString(content.splice(0,12))}(datas?.bmsAddr)}}catch(error){console.error("error: ",error)}},getCharCodeConnect=(content,clearZero=!1)=>{if(console.log("content: ---------------",content),!content)return null;const length=content[0];let arr=content.splice(1,length);if(clearZero)for(;0===arr[arr.length-1];)arr.pop();return console.log("arr: -------------------",arr),String.fromCharCode(...arr)};function toHexString(arr){let string="";return arr.forEach(el=>{string+=decimalToHex(el)}),string}const getCapInfo=async datas=>{console.log("datas: ",datas);return{normCap:format(datas.normCap,.01,0,2),cycleCap:format(datas.cycleCap,.01,0,2),fullCap:format(datas.fullCap,.01,0,2)}},getVoltageInfo=async(datas,chipType)=>{console.log("datas: ",datas);const allOvervoltageProtect=format(datas.allOvervoltageProtect,.01,0,3),allOverpressureRecovery=format(datas.allOverpressureRecovery,.01,0,3),allLowvoltageProtect=format(datas.allLowvoltageProtect,.01,0,3),allLowvoltageRecover=format(datas.allLowvoltageRecover,.01,0,3),singleOvervoltageProtect=format(datas.singleOvervoltageProtect,.001,0,3),singleOverpressureRecovery=format(datas.singleOverpressureRecovery,.001,0,3),singleLowvoltageProtect=format(datas.singleLowvoltageProtect,.001,0,3),singleLowvoltageRecover=format(datas.singleLowvoltageRecover,.001,0,3),hardwareOV=format(datas.hardwareOV,.001,0,3),hardwareUV=format(datas.hardwareUV,.001,0,3);let singleOverpressureDelay=null,singleLowvoltageDelayed=null,allLowvoltageDelay=null,allOverpressureDelay=null;return chipType?(singleOverpressureDelay=format(datas.singleOverpressureDelay,1),singleLowvoltageDelayed=format(datas.singleLowvoltageDelayed,1),allLowvoltageDelay=format(datas.allLowvoltageDelay,1),allOverpressureDelay=format(datas.allOverpressureDelay,1)):(singleLowvoltageDelayed=datas.singleLowvoltageDelayed[0],singleOverpressureDelay=datas.singleLowvoltageDelayed[1],allLowvoltageDelay=datas.allLowvoltageDelay[0],allOverpressureDelay=datas.allLowvoltageDelay[1]),{allOvervoltageProtect:allOvervoltageProtect,allOverpressureRecovery:allOverpressureRecovery,allLowvoltageProtect:allLowvoltageProtect,allLowvoltageRecover:allLowvoltageRecover,singleOvervoltageProtect:singleOvervoltageProtect,singleOverpressureRecovery:singleOverpressureRecovery,singleLowvoltageProtect:singleLowvoltageProtect,singleLowvoltageRecover:singleLowvoltageRecover,singleOverpressureDelay:singleOverpressureDelay,singleLowvoltageDelayed:singleLowvoltageDelayed,hardwareOV:hardwareOV,hardwareUV:hardwareUV,allLowvoltageDelay:allLowvoltageDelay,allOverpressureDelay:allOverpressureDelay}},getCurrentInfo=async(datas,chipType)=>{console.log("datas: ",datas);const occhg=format(datas.occhg,.01,0,3),dischargeOvercurrentProtect=(datas.dischargeOvercurrentProtect||0==datas.dischargeOvercurrentProtect)&&.01*(format(datas.dischargeOvercurrentProtect,1,0,3)-65536);let chargeOvercurrentDelay=null,chargeOvercurrentRecoverDelay=null,dischargeOvercurrentDelay=null,dischargeOvercurrentRecoverDelay=null,shortcircuiProtectRecoverDelay=null,leve2OvercurrentDelay=0,level2OvercurrentProtect=0,shortcircuiProtect=0,shortcircuiProtectDelay=0,level2OvercurrentProtectV=null,overAndUnderDelay=0;return chipType?(chargeOvercurrentDelay=format(datas.chargeOvercurrentDelay,1),chargeOvercurrentRecoverDelay=format(datas.chargeOvercurrentRecoverDelay,1),dischargeOvercurrentDelay=format(datas.dischargeOvercurrentDelay,1),dischargeOvercurrentRecoverDelay=format(datas.dischargeOvercurrentRecoverDelay,1),shortcircuiProtectRecoverDelay=format(datas.shortcircuiProtectRecoverDelay,1),level2OvercurrentProtect=getNewProtectAndDelay(datas.level2OvercurrentProtect).value1,leve2OvercurrentDelay=getNewProtectAndDelay(datas.level2OvercurrentProtect).value2,shortcircuiProtect=getNewProtectAndDelay(datas.level2OvercurrentProtectV).value1,shortcircuiProtectDelay=getNewProtectAndDelay(datas.level2OvercurrentProtectV).value2):(chargeOvercurrentDelay=datas.chargeOvercurrentDelay[0],chargeOvercurrentRecoverDelay=datas.chargeOvercurrentDelay[1],dischargeOvercurrentDelay=datas.dischargeOvercurrentDelay[0],dischargeOvercurrentRecoverDelay=datas.dischargeOvercurrentDelay[1],overAndUnderDelay=datas.shortcircuiProtectRecoverDelay[0],shortcircuiProtectRecoverDelay=datas.shortcircuiProtectRecoverDelay[1],level2OvercurrentProtectV=getOldProtectAndDelay(datas.level2OvercurrentProtect).double,shortcircuiProtect=getOldProtectAndDelay(datas.level2OvercurrentProtect).value1,shortcircuiProtectDelay=getOldProtectAndDelay(datas.level2OvercurrentProtect).value2,level2OvercurrentProtect=getOldProtectAndDelay(datas.level2OvercurrentProtect).value3,leve2OvercurrentDelay=getOldProtectAndDelay(datas.level2OvercurrentProtect).value4),{occhg:occhg,dischargeOvercurrentProtect:dischargeOvercurrentProtect,chargeOvercurrentDelay:chargeOvercurrentDelay,chargeOvercurrentRecoverDelay:chargeOvercurrentRecoverDelay,dischargeOvercurrentDelay:dischargeOvercurrentDelay,dischargeOvercurrentRecoverDelay:dischargeOvercurrentRecoverDelay,leve2OvercurrentDelay:leve2OvercurrentDelay,level2OvercurrentProtectV:level2OvercurrentProtectV,shortcircuiProtectRecoverDelay:shortcircuiProtectRecoverDelay,shortcircuiProtect:shortcircuiProtect,shortcircuiProtectDelay:shortcircuiProtectDelay,level2OvercurrentProtect:level2OvercurrentProtect,overAndUnderDelay:overAndUnderDelay}};function getNewProtectAndDelay(arr){if(2!==arr?.length)return{value1:0,value2:0};let resultArray=arr.map(num=>num.toString(2).padStart(8,"0")).join("").split("").map(Number),arr1=resultArray.slice(8,12),arr2=resultArray.slice(12);return{value1:parseInt(arr1.join(""),2),value2:parseInt(arr2.join(""),2)}}function getOldProtectAndDelay(arr){if(2!==arr?.length)return{double:!1,value1:0,value2:0,value3:0,value4:0};const binaryString=arr.map(num=>num.toString(2).padStart(8,"0")).join("");console.log("【解析硬件过流及短路】",binaryString);const resultArray=binaryString.split("").map(Number),arr1=[0,...resultArray.slice(5,8)],arr2=resultArray.slice(1,5),arr3=resultArray.slice(12),arr4=resultArray.slice(8,12),value1=parseInt(arr1.join(""),2),value2=parseInt(arr2.join(""),2),value3=parseInt(arr3.join(""),2),value4=parseInt(arr4.join(""),2);return{double:1===resultArray[0],value1:value1,value2:value2,value3:value3,value4:value4}}const getTempInfo=(datas,chipType)=>{console.log("datas: ",datas);const chargeHightempProtect=formatTemp(datas.chargeHightempProtect),chargeHightempRecover=formatTemp(datas.chargeHightempRecover),chargeLowtempProtect=formatTemp(datas.chargeLowtempProtect),chargeLowtempRecover=formatTemp(datas.chargeLowtempRecover),dischargingHightempProtect=formatTemp(datas.dischargingHightempProtect),dischargingHightempRecover=formatTemp(datas.dischargingHightempRecover),dischargingLowtempProtect=formatTemp(datas.dischargingLowtempProtect),dischargingLowtempRecover=formatTemp(datas.dischargingLowtempRecover);let chargeHightempDelay=null,chargeLowtempDelay=null,dischargingHightempDelay=null,dischargingLowtempDelay=null;return chipType?(chargeHightempDelay=format(datas.chargeHightempDelay,1),chargeLowtempDelay=format(datas.chargeLowtempDelay,1),dischargingHightempDelay=format(datas.dischargingHightempDelay,1),dischargingLowtempDelay=format(datas.dischargingLowtempDelay,1)):(chargeHightempDelay=datas.chargeLowtempDelay[1],chargeLowtempDelay=datas.chargeLowtempDelay[0],dischargingHightempDelay=datas.dischargingLowtempDelay[1],dischargingLowtempDelay=datas.dischargingLowtempDelay[0]),{chargeHightempProtect:chargeHightempProtect,chargeHightempRecover:chargeHightempRecover,chargeLowtempProtect:chargeLowtempProtect,chargeLowtempRecover:chargeLowtempRecover,dischargingHightempProtect:dischargingHightempProtect,dischargingHightempRecover:dischargingHightempRecover,dischargingLowtempProtect:dischargingLowtempProtect,dischargingLowtempRecover:dischargingLowtempRecover,chargeHightempDelay:chargeHightempDelay,chargeLowtempDelay:chargeLowtempDelay,dischargingHightempDelay:dischargingHightempDelay,dischargingLowtempDelay:dischargingLowtempDelay}},getEqualizerFunInfo=datas=>({equalizingVoltage:format(datas.equalizingVoltage,.001,0,3),accuracyEqualization:format(datas.accuracyEqualization,1,0,2)}),getcapVolInfoInfo=datas=>({fullVolt:format(datas.fullVolt,.001,0,3),emptyVolt:format(datas.emptyVolt,.001,0,3),voltage10p:format(datas.voltage10p,.001,0,3),voltage20p:format(datas.voltage20p,.001,0,3),voltage30p:format(datas.voltage30p,.001,0,3),voltage40p:format(datas.voltage40p,.001,0,3),voltage50p:format(datas.voltage50p,.001,0,3),voltage60p:format(datas.voltage60p,.001,0,3),voltage70p:format(datas.voltage70p,.001,0,3),voltage80p:format(datas.voltage80p,.001,0,3),voltage90p:format(datas.voltage90p,.001,0,3),voltage100p:format(datas.voltage100p,.001,0,3)}),getFuncAndTempFuncInfo=datas=>{const binaryFuncArr=formatBinary(datas.func),binaryTempArr=formatBinary(datas.tempFunc),func={};funcJson.forEach((item,index)=>{item.key&&(func[item.key]=binaryFuncArr[index])});const tempFunc={};return tempFuncJson.forEach((item,index)=>{item.key&&(tempFunc[item.key]=binaryTempArr[index])}),{func:func,tempFunc:tempFunc}},getSystemInfo=datas=>({serialNumber:format(datas.serialNumber,1),cycleCount:format(datas.cycleCount,1),strCount:format(datas.strCount,1),rsnsValue:format(datas.rsnsValue,crsDivisor,0,2)});export{getBaseInfo,getBaseParams,getResistance};
1
+ import{getSysParamCmd}from"./readAndSetParam.js";import{decimalToHex,hexToDecimal}from"../BleDataProcess.js";import{systemJson,funcAndTempFuncJson,capVolInfoJson,equalizerFunJson,tempInfoJson,currentInfoJson,voltageInfoJson,capInfoJson,batteryInfoJson,funcJson,tempFuncJson}from"../dataJson/baseParamsJson.js";import{getProtectCountCmd,enterFactory,readExistFactory}from"./BleCmdDD.js";function format(value,n=1,offset=0,scope=0){if(!value)return null;value=value.map(el=>{const hexValue=decimalToHex(el);return console.log("el: ------------",hexValue),hexValue});const v=parseInt(value.join(""),16)*n+offset;if(null==scope)return v;const formatted=v.toFixed(scope);return Number(formatted)}function formatTemp(arr){if(!arr)return null;let string="0x"+toHexString(arr),value=parseInt(string,16);return value=(value-2731)/10,Number(value)}function formatBinary(arr){if(!arr)return null;return arr.map(num=>num.toString(2).padStart(8,"0")).join("").split("").map(Number).reverse()}const sendCmdSeq=async(datasInfo,chipType,deviceId,params)=>{let index=0;for(chipType||await enterFactory(deviceId);index<params.length;){const item=params[index];try{const basedata=await getSysParamCmd(chipType,deviceId,item,!1);datasInfo[item.key]=basedata,index++}catch(error){console.error(`获取参数 ${item.key} 失败:`,error),index++}}chipType||await readExistFactory(deviceId)};let crsDivisor=.1;const getBaseParams=async(chipType,deviceData,index,paramObj)=>{console.log("chipType: ",chipType);const deviceId=deviceData?.deviceId,protocolVersion=deviceData?.protocolVersion||"00";console.warn("protocolVersion: ",protocolVersion);const v=hexToDecimal(protocolVersion);(2==v||v>=20&&v<80)&&(crsDivisor=.01),console.log("v: ",v);try{let dataInfo={};switch(index){case 1:let datasInfo1={};return await sendCmdSeq(datasInfo1,chipType,deviceId,batteryInfoJson(crsDivisor)),dataInfo=getBaseInfo(datasInfo1),dataInfo;case 2:let datasInfo2={};if(chipType){const capData=await getSysParamCmd(chipType,deviceId,{...capInfoJson[0],paramLength:4});console.warn("capData: ",capData),datasInfo2.normCap=capData?.slice(0,2),datasInfo2.cycleCap=capData?.slice(2,4);const capData2=await getSysParamCmd(chipType,deviceId,capInfoJson[2]);datasInfo2.fullCap=capData2?.slice(0,2)}else await sendCmdSeq(datasInfo2,chipType,deviceId,capInfoJson);return dataInfo=getCapInfo(datasInfo2),dataInfo;case 3:let datasInfo3={};if(chipType){let vindex=voltageInfoJson.findIndex(el=>16==el.paramNo);console.log("vindex: ------------",vindex);let vindex1=voltageInfoJson.findIndex(el=>48==el.paramNo),vindex2=voltageInfoJson.findIndex(el=>38==el.paramNo);const voltageData=await getSysParamCmd(chipType,deviceId,{...voltageInfoJson[vindex],paramLength:16}),voltageData1=await getSysParamCmd(chipType,deviceId,{...voltageInfoJson[vindex1],paramLength:8}),voltageData2=await getSysParamCmd(chipType,deviceId,{...voltageInfoJson[vindex2],paramLength:4});console.log("voltageData: ",voltageData),datasInfo3.allOvervoltageProtect=voltageData?.slice(0,2),datasInfo3.allOverpressureRecovery=voltageData?.slice(2,4),datasInfo3.allLowvoltageProtect=voltageData?.slice(4,6),datasInfo3.allLowvoltageRecover=voltageData?.slice(6,8),datasInfo3.singleOvervoltageProtect=voltageData?.slice(8,10),datasInfo3.singleOverpressureRecovery=voltageData?.slice(10,12),datasInfo3.singleLowvoltageProtect=voltageData?.slice(12,14),datasInfo3.singleLowvoltageRecover=voltageData?.slice(14,16),datasInfo3.allLowvoltageDelay=voltageData1?.slice(0,2),datasInfo3.allOverpressureDelay=voltageData1?.slice(2,4),datasInfo3.singleLowvoltageDelayed=voltageData1?.slice(4,6),datasInfo3.singleOverpressureDelay=voltageData1?.slice(6,8),datasInfo3.hardwareOV=voltageData2?.slice(0,2),datasInfo3.hardwareUV=voltageData2?.slice(2,4)}else await sendCmdSeq(datasInfo3,chipType,deviceId,voltageInfoJson);return dataInfo=getVoltageInfo(datasInfo3,chipType),dataInfo;case 4:let datasInfo4={};if(chipType){let cindex=currentInfoJson.findIndex(el=>24==el.paramNo),cindex1=currentInfoJson.findIndex(el=>52==el.paramNo),cindex2=currentInfoJson.findIndex(el=>40==el.paramNo);const currentData=await getSysParamCmd(chipType,deviceId,{...currentInfoJson[cindex],paramLength:4}),currentData1=await getSysParamCmd(chipType,deviceId,{...currentInfoJson[cindex1],paramLength:8}),currentData2=await getSysParamCmd(chipType,deviceId,{...currentInfoJson[cindex2],paramLength:8});console.log("currentData: ",currentData),datasInfo4.occhg=currentData?.slice(0,2),datasInfo4.dischargeOvercurrentProtect=currentData?.slice(2,4),datasInfo4.chargeOvercurrentDelay=currentData1?.slice(0,2),datasInfo4.chargeOvercurrentRecoverDelay=currentData1?.slice(2,4),datasInfo4.dischargeOvercurrentDelay=currentData1?.slice(4,6),datasInfo4.dischargeOvercurrentRecoverDelay=currentData1?.slice(6,8),datasInfo4.level2OvercurrentProtect=currentData2?.slice(0,2),datasInfo4.level2OvercurrentProtectV=currentData2?.slice(2,4),datasInfo4.shortcircuiProtectRecoverDelay=currentData2?.slice(6,8)}else await sendCmdSeq(datasInfo4,chipType,deviceId,currentInfoJson);return dataInfo=getCurrentInfo(datasInfo4,chipType),dataInfo;case 5:let datasInfo5={};if(chipType){let tindex=tempInfoJson.findIndex(el=>8==el.paramNo),tindex1=tempInfoJson.findIndex(el=>44==el.paramNo),tindex2=tempInfoJson.findIndex(el=>202==el.paramNo);const tempData=await getSysParamCmd(chipType,deviceId,{...tempInfoJson[tindex],paramLength:16}),tempData1=await getSysParamCmd(chipType,deviceId,{...tempInfoJson[tindex1],paramLength:8}),tempData2=await getSysParamCmd(chipType,deviceId,{...tempInfoJson[tindex2],paramLength:4});console.log("tempData: ",tempData,tempData2),datasInfo5.chargeHightempProtect=tempData?.slice(0,2),datasInfo5.chargeHightempRecover=tempData?.slice(2,4),datasInfo5.chargeLowtempProtect=tempData?.slice(4,6),datasInfo5.chargeLowtempRecover=tempData?.slice(6,8),datasInfo5.dischargingHightempProtect=tempData?.slice(8,10),datasInfo5.dischargingHightempRecover=tempData?.slice(10,12),datasInfo5.dischargingLowtempProtect=tempData?.slice(12,14),datasInfo5.dischargingLowtempRecover=tempData?.slice(14,16),datasInfo5.chargeLowtempDelay=tempData1?.slice(0,2),datasInfo5.chargeHightempDelay=tempData1?.slice(2,4),datasInfo5.dischargingLowtempDelay=tempData1?.slice(4,6),datasInfo5.dischargingHightempDelay=tempData1?.slice(6,8),datasInfo5.overtempProtect=tempData2?.slice(0,2),datasInfo5.overtempRecover=tempData2?.slice(2,4)}else await sendCmdSeq(datasInfo5,chipType,deviceId,tempInfoJson);return dataInfo=getTempInfo(datasInfo5,chipType),dataInfo;case 6:let datasInfo6={};if(chipType){const equalizerFunData=await getSysParamCmd(chipType,deviceId,{...equalizerFunJson[0],paramLength:4});console.log("equalizerFunData: ",equalizerFunData),datasInfo6.equalizingVoltage=equalizerFunData?.slice(0,2),datasInfo6.accuracyEqualization=equalizerFunData?.slice(2,4)}else await sendCmdSeq(datasInfo6,chipType,deviceId,equalizerFunJson);return dataInfo=getEqualizerFunInfo(datasInfo6),dataInfo;case 7:let datasInfo7={};if(chipType){let capVolIndex=capVolInfoJson.findIndex(el=>34==el.paramNo),capVolIndex1=capVolInfoJson.findIndex(el=>106==el.paramNo);const capVolInfoData=await getSysParamCmd(chipType,deviceId,{...capVolInfoJson[0],paramLength:4}),capVolInfoData1=await getSysParamCmd(chipType,deviceId,{...capVolInfoJson[capVolIndex],paramLength:8}),capVolInfoData2=await getSysParamCmd(chipType,deviceId,{...capVolInfoJson[capVolIndex1],paramLength:12});console.log("capVolInfoData: ",capVolInfoData),datasInfo7.fullVolt=capVolInfoData?.slice(0,2),datasInfo7.emptyVolt=capVolInfoData?.slice(2,4),datasInfo7.voltage80p=capVolInfoData1?.slice(0,2),datasInfo7.voltage60p=capVolInfoData1?.slice(2,4),datasInfo7.voltage40p=capVolInfoData1?.slice(4,6),datasInfo7.voltage20p=capVolInfoData1?.slice(6,8),datasInfo7.voltage90p=capVolInfoData2?.slice(0,2),datasInfo7.voltage70p=capVolInfoData2?.slice(2,4),datasInfo7.voltage50p=capVolInfoData2?.slice(4,6),datasInfo7.voltage30p=capVolInfoData2?.slice(6,8),datasInfo7.voltage10p=capVolInfoData2?.slice(8,10),datasInfo7.voltage100p=capVolInfoData2?.slice(10,12)}else await sendCmdSeq(datasInfo7,chipType,deviceId,capVolInfoJson);return dataInfo=getcapVolInfoInfo(datasInfo7,chipType),dataInfo;case 9:let datasInfo9={};if(chipType){const funcAndTempFuncData=await getSysParamCmd(chipType,deviceId,{...funcAndTempFuncJson[0],paramLength:4});console.log("funcAndTempFuncData: ",funcAndTempFuncData),datasInfo9.func=funcAndTempFuncData?.slice(0,2),datasInfo9.tempFunc=funcAndTempFuncData?.slice(2,4)}else await sendCmdSeq(datasInfo9,chipType,deviceId,funcAndTempFuncJson);return dataInfo=getFuncAndTempFuncInfo(datasInfo9),dataInfo;case 10:let datasInfo10={};return await sendCmdSeq(datasInfo10,chipType,deviceId,systemJson),dataInfo=getSystemInfo(datasInfo10),dataInfo;case 11:const counts=await getProtectCountCmd(deviceId);return console.log("counts: ",counts),counts;default:if(!paramObj)return null;let defaultDataInfo={};const onedata=await getSysParamCmd(chipType,deviceId,paramObj);return defaultDataInfo[paramObj.key]=onedata?.slice(0,2),defaultDataInfo}}catch(error){throw console.error("error: 读系统参数报错 getBaseParams",error),error}},getResistance=async(chipType,deviceId)=>{try{const rsnsValue=await getSysParamCmd(chipType,deviceId,systemJson[2]);return format(rsnsValue,crsDivisor,0,2)}catch(error){throw console.error("error: 读检流阻值报错 getResistance",error),error}},getBaseInfo=async datas=>{try{console.log("datas: ",datas);const barCode=getCharCodeConnect(datas?.barCode),manufacturer=getCharCodeConnect(datas?.manufacturer),model=getCharCodeConnect(datas?.model),bmsModel=getCharCodeConnect(datas?.bmsModel,!0),producedDate=function(content){if(!content)return null;let arr=content.splice(0,2),string="0x";return arr.forEach(el=>{string+=decimalToHex(el)}),console.log(string,"string日期"),`${2e3+(string>>9)}-${string>>5&15}-${31&string}`}(datas?.producedDate);return{barCode:barCode,manufacturer:manufacturer,model:model,bmsModel:bmsModel,producedDate:producedDate,bmsAddr:function(content){if(!content)return null;return console.log(content,"content======"),toHexString(content.splice(0,12))}(datas?.bmsAddr)}}catch(error){console.error("error: ",error)}},getCharCodeConnect=(content,clearZero=!1)=>{if(console.log("content: ---------------",content),!content)return null;const length=content[0];let arr=content.splice(1,length);if(clearZero)for(;0===arr[arr.length-1];)arr.pop();return console.log("arr: -------------------",arr),String.fromCharCode(...arr)};function toHexString(arr){let string="";return arr.forEach(el=>{string+=decimalToHex(el)}),string}const getCapInfo=async datas=>{console.log("datas: ",datas);return{normCap:format(datas.normCap,.01,0,2),cycleCap:format(datas.cycleCap,.01,0,2),fullCap:format(datas.fullCap,.01,0,2)}},getVoltageInfo=async(datas,chipType)=>{console.log("datas: ",datas);const allOvervoltageProtect=format(datas.allOvervoltageProtect,.01,0,3),allOverpressureRecovery=format(datas.allOverpressureRecovery,.01,0,3),allLowvoltageProtect=format(datas.allLowvoltageProtect,.01,0,3),allLowvoltageRecover=format(datas.allLowvoltageRecover,.01,0,3),singleOvervoltageProtect=format(datas.singleOvervoltageProtect,.001,0,3),singleOverpressureRecovery=format(datas.singleOverpressureRecovery,.001,0,3),singleLowvoltageProtect=format(datas.singleLowvoltageProtect,.001,0,3),singleLowvoltageRecover=format(datas.singleLowvoltageRecover,.001,0,3),hardwareOV=format(datas.hardwareOV,.001,0,3),hardwareUV=format(datas.hardwareUV,.001,0,3);let singleOverpressureDelay=null,singleLowvoltageDelayed=null,allLowvoltageDelay=null,allOverpressureDelay=null;return chipType?(singleOverpressureDelay=format(datas.singleOverpressureDelay,1),singleLowvoltageDelayed=format(datas.singleLowvoltageDelayed,1),allLowvoltageDelay=format(datas.allLowvoltageDelay,1),allOverpressureDelay=format(datas.allOverpressureDelay,1)):(singleLowvoltageDelayed=datas.singleLowvoltageDelayed[0],singleOverpressureDelay=datas.singleLowvoltageDelayed[1],allLowvoltageDelay=datas.allLowvoltageDelay[0],allOverpressureDelay=datas.allLowvoltageDelay[1]),{allOvervoltageProtect:allOvervoltageProtect,allOverpressureRecovery:allOverpressureRecovery,allLowvoltageProtect:allLowvoltageProtect,allLowvoltageRecover:allLowvoltageRecover,singleOvervoltageProtect:singleOvervoltageProtect,singleOverpressureRecovery:singleOverpressureRecovery,singleLowvoltageProtect:singleLowvoltageProtect,singleLowvoltageRecover:singleLowvoltageRecover,singleOverpressureDelay:singleOverpressureDelay,singleLowvoltageDelayed:singleLowvoltageDelayed,hardwareOV:hardwareOV,hardwareUV:hardwareUV,allLowvoltageDelay:allLowvoltageDelay,allOverpressureDelay:allOverpressureDelay}},getCurrentInfo=async(datas,chipType)=>{console.log("datas: ",datas);const occhg=format(datas.occhg,.01,0,3),dischargeOvercurrentProtect=(datas.dischargeOvercurrentProtect||0==datas.dischargeOvercurrentProtect)&&Number((.01*(format(datas.dischargeOvercurrentProtect,1,0,3)-65536)).toFixed(3));let chargeOvercurrentDelay=null,chargeOvercurrentRecoverDelay=null,dischargeOvercurrentDelay=null,dischargeOvercurrentRecoverDelay=null,shortcircuiProtectRecoverDelay=null,leve2OvercurrentDelay=0,level2OvercurrentProtect=0,shortcircuiProtect=0,shortcircuiProtectDelay=0,level2OvercurrentProtectV=null,overAndUnderDelay=0;return chipType?(chargeOvercurrentDelay=format(datas.chargeOvercurrentDelay,1),chargeOvercurrentRecoverDelay=format(datas.chargeOvercurrentRecoverDelay,1),dischargeOvercurrentDelay=format(datas.dischargeOvercurrentDelay,1),dischargeOvercurrentRecoverDelay=format(datas.dischargeOvercurrentRecoverDelay,1),shortcircuiProtectRecoverDelay=format(datas.shortcircuiProtectRecoverDelay,1),level2OvercurrentProtect=getNewProtectAndDelay(datas.level2OvercurrentProtect).value1,leve2OvercurrentDelay=getNewProtectAndDelay(datas.level2OvercurrentProtect).value2,shortcircuiProtect=getNewProtectAndDelay(datas.level2OvercurrentProtectV).value1,shortcircuiProtectDelay=getNewProtectAndDelay(datas.level2OvercurrentProtectV).value2):(chargeOvercurrentDelay=datas.chargeOvercurrentDelay[0],chargeOvercurrentRecoverDelay=datas.chargeOvercurrentDelay[1],dischargeOvercurrentDelay=datas.dischargeOvercurrentDelay[0],dischargeOvercurrentRecoverDelay=datas.dischargeOvercurrentDelay[1],overAndUnderDelay=datas.shortcircuiProtectRecoverDelay[0],shortcircuiProtectRecoverDelay=datas.shortcircuiProtectRecoverDelay[1],level2OvercurrentProtectV=getOldProtectAndDelay(datas.level2OvercurrentProtect).double,shortcircuiProtect=getOldProtectAndDelay(datas.level2OvercurrentProtect).value1,shortcircuiProtectDelay=getOldProtectAndDelay(datas.level2OvercurrentProtect).value2,level2OvercurrentProtect=getOldProtectAndDelay(datas.level2OvercurrentProtect).value3,leve2OvercurrentDelay=getOldProtectAndDelay(datas.level2OvercurrentProtect).value4),{occhg:occhg,dischargeOvercurrentProtect:dischargeOvercurrentProtect,chargeOvercurrentDelay:chargeOvercurrentDelay,chargeOvercurrentRecoverDelay:chargeOvercurrentRecoverDelay,dischargeOvercurrentDelay:dischargeOvercurrentDelay,dischargeOvercurrentRecoverDelay:dischargeOvercurrentRecoverDelay,leve2OvercurrentDelay:leve2OvercurrentDelay,level2OvercurrentProtectV:level2OvercurrentProtectV,shortcircuiProtectRecoverDelay:shortcircuiProtectRecoverDelay,shortcircuiProtect:shortcircuiProtect,shortcircuiProtectDelay:shortcircuiProtectDelay,level2OvercurrentProtect:level2OvercurrentProtect,overAndUnderDelay:overAndUnderDelay}};function getNewProtectAndDelay(arr){if(2!==arr?.length)return{value1:0,value2:0};let resultArray=arr.map(num=>num.toString(2).padStart(8,"0")).join("").split("").map(Number),arr1=resultArray.slice(8,12),arr2=resultArray.slice(12);return{value1:parseInt(arr1.join(""),2),value2:parseInt(arr2.join(""),2)}}function getOldProtectAndDelay(arr){if(2!==arr?.length)return{double:!1,value1:0,value2:0,value3:0,value4:0};const binaryString=arr.map(num=>num.toString(2).padStart(8,"0")).join("");console.log("【解析硬件过流及短路】",binaryString);const resultArray=binaryString.split("").map(Number),arr1=[0,...resultArray.slice(5,8)],arr2=resultArray.slice(1,5),arr3=resultArray.slice(12),arr4=resultArray.slice(8,12),value1=parseInt(arr1.join(""),2),value2=parseInt(arr2.join(""),2),value3=parseInt(arr3.join(""),2),value4=parseInt(arr4.join(""),2);return{double:1===resultArray[0],value1:value1,value2:value2,value3:value3,value4:value4}}const getTempInfo=(datas,chipType)=>{console.log("datas: ",datas);const chargeHightempProtect=formatTemp(datas.chargeHightempProtect),chargeHightempRecover=formatTemp(datas.chargeHightempRecover),chargeLowtempProtect=formatTemp(datas.chargeLowtempProtect),chargeLowtempRecover=formatTemp(datas.chargeLowtempRecover),dischargingHightempProtect=formatTemp(datas.dischargingHightempProtect),dischargingHightempRecover=formatTemp(datas.dischargingHightempRecover),dischargingLowtempProtect=formatTemp(datas.dischargingLowtempProtect),dischargingLowtempRecover=formatTemp(datas.dischargingLowtempRecover),overtempProtect=formatTemp(datas.overtempProtect),overtempRecover=formatTemp(datas.overtempRecover);let chargeHightempDelay=null,chargeLowtempDelay=null,dischargingHightempDelay=null,dischargingLowtempDelay=null;return chipType?(chargeHightempDelay=format(datas.chargeHightempDelay,1),chargeLowtempDelay=format(datas.chargeLowtempDelay,1),dischargingHightempDelay=format(datas.dischargingHightempDelay,1),dischargingLowtempDelay=format(datas.dischargingLowtempDelay,1)):(chargeHightempDelay=datas.chargeLowtempDelay[1],chargeLowtempDelay=datas.chargeLowtempDelay[0],dischargingHightempDelay=datas.dischargingLowtempDelay[1],dischargingLowtempDelay=datas.dischargingLowtempDelay[0]),{chargeHightempProtect:chargeHightempProtect,chargeHightempRecover:chargeHightempRecover,chargeLowtempProtect:chargeLowtempProtect,chargeLowtempRecover:chargeLowtempRecover,dischargingHightempProtect:dischargingHightempProtect,dischargingHightempRecover:dischargingHightempRecover,dischargingLowtempProtect:dischargingLowtempProtect,dischargingLowtempRecover:dischargingLowtempRecover,chargeHightempDelay:chargeHightempDelay,chargeLowtempDelay:chargeLowtempDelay,dischargingHightempDelay:dischargingHightempDelay,dischargingLowtempDelay:dischargingLowtempDelay,overtempProtect:overtempProtect,overtempRecover:overtempRecover}},getEqualizerFunInfo=datas=>({equalizingVoltage:format(datas.equalizingVoltage,.001,0,3),accuracyEqualization:format(datas.accuracyEqualization,1,0,2)}),getcapVolInfoInfo=datas=>({fullVolt:format(datas.fullVolt,.001,0,3),emptyVolt:format(datas.emptyVolt,.001,0,3),voltage10p:format(datas.voltage10p,.001,0,3),voltage20p:format(datas.voltage20p,.001,0,3),voltage30p:format(datas.voltage30p,.001,0,3),voltage40p:format(datas.voltage40p,.001,0,3),voltage50p:format(datas.voltage50p,.001,0,3),voltage60p:format(datas.voltage60p,.001,0,3),voltage70p:format(datas.voltage70p,.001,0,3),voltage80p:format(datas.voltage80p,.001,0,3),voltage90p:format(datas.voltage90p,.001,0,3),voltage100p:format(datas.voltage100p,.001,0,3)}),getFuncAndTempFuncInfo=datas=>{const binaryFuncArr=formatBinary(datas.func),binaryTempArr=formatBinary(datas.tempFunc),func={};funcJson.forEach((item,index)=>{item.key&&(func[item.key]=binaryFuncArr[index])});const tempFunc={};return tempFuncJson.forEach((item,index)=>{item.key&&(tempFunc[item.key]=binaryTempArr[index])}),{func:func,tempFunc:tempFunc}},splitNumberTo1Byte=(combined=0)=>({val1:255&(combined=Number(combined)),val2:combined>>8&255}),getSystemInfo=datas=>{const serialNumber=format(datas.serialNumber,1),cycleCount=format(datas.cycleCount,1),strCount=format(datas.strCount,1),rsnsValue=format(datas.rsnsValue,crsDivisor,0,2),param1911=splitNumberTo1Byte(format(datas.param1911)).val1,param1912=splitNumberTo1Byte(format(datas.param1911)).val2,param1981=splitNumberTo1Byte(format(datas.param1981)).val1,param1982=splitNumberTo1Byte(format(datas.param1981)).val2;return{serialNumber:serialNumber,cycleCount:cycleCount,strCount:strCount,rsnsValue:rsnsValue,param1911:param1911,param1912:param1912,param1951:splitNumberTo1Byte(format(datas.param1951)).val1,param1952:splitNumberTo1Byte(format(datas.param1951)).val2,param1981:param1981,param1982:param1982}};export{getBaseInfo,getBaseParams,getResistance};
@@ -1 +1 @@
1
- import{hexArr2string,hex2string,decimalToHex,generateCrc16modbusCheck,hexArr2Assic,generateCrcCheckSum,hexToDecimal,stringToTwoHexArray,sleep}from"../BleDataProcess.js";import{getData}from"./BleCmdAnalysis.js";import{getFFAA80Async,resolveFFAA80}from"./BleCmdFFAA.js";const enterFactory=async deviceId=>set_PlanCMD_DD(deviceId,"DD5A00025678FF3077"),existFactory=async deviceId=>set_PlanCMD_DD(deviceId,"DD5A01022828ffad77"),readExistFactory=async deviceId=>set_PlanCMD_DD(deviceId,"DD5A01020000FFFD77"),set_PlanCMD_DD=async(deviceId,command)=>{"string"==typeof command&&(command=command.match(/(.{2})/g).map(o=>`0x${o}`));let result=null;try{const data=await getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"PlanCMD_DD");if(data){const dataStr=hexArr2string(data),content=data.slice(4,data.length-3);result={data:data,dataStr:dataStr,status:hex2string(data[2]),len:data[3],content:content}}else result={status:0,content:[]}}catch(error){console.error(error)}return result},set_PlanCMD_3B3C=async(deviceId,command)=>{"string"==typeof command&&(command=command.match(/(.{2})/g).map(o=>`0x${o}`));let result=null;try{const data=await getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:59==hexArr[0]&&60==hexArr[1],pkgLen:hexArr[11]+15}),pkgVerifyHandler:pkg=>({verified:!0})},"PlanCMD_3B3C");if(data){const dataStr=hexArr2string(data),content=data.slice(12,data.length-3);result={dataStr:dataStr,status:128==data[10]?1:0,addr:hexArr2string(data.slice(2,10)),content:content}}}catch(error){console.error(error)}return result},get3B3CAsync=async deviceId=>{const addressCode=["0x00","0x00","0x00","0x00","0x00","0x00","0x00","0x00"],commandCode=["0x01"],data=[],dataLength=[`0x${decimalToHex(data.length,2)}`],check=generateCrc16modbusCheck([...addressCode,...commandCode,...dataLength,...data],!1),command=["0x3b","0x3c",...addressCode,...commandCode,...dataLength,...data,...check,"0x0d"];return getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:59==hexArr[0]&&60==hexArr[1],pkgLen:hexArr[11]+15}),pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=generateCrc16modbusCheck(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"3B3C")},resolve3B3C=data=>{if(!data)return null;let result={dataStr:hexArr2string(data),status:hex2string(data[10]),addr:hexArr2string(data.slice(2,10))};const content=data.slice(12,data.length-3);for(;content.length>0;){const[v1,v2,...v]=content.splice(0,content[1]+2);if(1==v1&&(result.productFlag=hex2string(v1),result.productLen=v2,v)){const[productType,frontType,protocolV,level]=v.map(o=>hex2string(o));Object.assign(result,{productType:productType,frontType:frontType,protocolV:protocolV,level:level})}2==v1&&(result.hardwareFlag=hex2string(v1),result.hardwareLen=v2,result.hardwareV=hexArr2Assic(v)),3==v1&&(result.sofewareFlag=hex2string(v1),result.sofewareLen=v2,result.sofewareV=hexArr2Assic(v)),4==v1&&(result.pcbFlag=hex2string(v1),result.pcbLen=v2,result.pcbContent=hexArr2Assic(v))}return result},getDDA503Async=async deviceId=>{const hex=await 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]=generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA5_03");return hex?resolveDDA503(hex):null},resolveDDA503=data=>{if(!data)return null;const cmdResp03=hexArr2string(data),content=data.slice(4,data.length-3),binArr=data[24].toString(2).padStart(8,"0").split("").reverse(),balances=data.slice(16,20).flatMap(byte=>byte.toString(2).padStart(8,"0").split("").reverse());console.warn("BC: ---------------",balances);const fet=data[24],chargeSwitch=!!Number(binArr[0]),dischargeSwitch=!!Number(binArr[1]),BMSVersion=decimalToHex(data[22]),humidityIndex=2*data[26]+27,humidity=data[humidityIndex],n=Number(binArr[7])||136==humidity?10:100,totalVoltage=Number((((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=Number((totalVoltage*electricity).toFixed(2)),soc=data[23]??0,seriesNum=data[25]??0,volumeHex=decimalToHex(data[8])+decimalToHex(data[9]),surplusCapacity=Number((hexToDecimal(volumeHex)/n).toFixed(2)),normCapHex=decimalToHex(data[10])+decimalToHex(data[11]),normCap=Number((hexToDecimal(normCapHex)/n).toFixed(2)),cycleHex=decimalToHex(data[12])+decimalToHex(data[13]),cycleIndex=hexToDecimal(cycleHex),fccHex=decimalToHex(data[humidityIndex+3])+decimalToHex(data[humidityIndex+4]),fullChargeCapacity=Number((hexToDecimal(fccHex)/n).toFixed(2)),SOH=cycleIndex<=100?100:Math.min(100,fullChargeCapacity/normCap*100),heatingState=!!Number(binArr[4])||!!Number(binArr[3]);let heatingCurrent=null;const hasHeatingCurrent=data[3]+7>=humidityIndex+9+4+1,hasEquilCurrent=data[3]+7>=humidityIndex+7+4+1;if(heatingState&&hasHeatingCurrent){const i=humidityIndex+9;heatingCurrent=heatingCurrent=((data[i]<<8|data[i+1])/100).toFixed(2)}let equilibriumCurrent=null;if(hasEquilCurrent){const i=humidityIndex+7;let equilCurrent=(data[i]<<8)+(255&data[i+1]);equilCurrent=equilCurrent>32768?(equilCurrent-65536)/1e3:equilCurrent/1e3,equilibriumCurrent=Number(equilCurrent.toFixed(2))}const isFactoryMode=!!Number(binArr[6]),equilibriumStatus=!(0===data[16]&&0===data[17]),protectStatus=!(0===data[20]&&0===data[21]),protectStateHex=decimalToHex(data[20])+decimalToHex(data[21]),protVal=hexToDecimal(protectStateHex);let alarmIndex=2*data[26]+28,alarmStateHex=decimalToHex(data[alarmIndex])+decimalToHex(data[alarmIndex+1]),alarmsState=hexToDecimal(alarmStateHex);const 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=[];temperaturesList.forEach(el=>{const value=1.8*Number(el)+32;fahTempList.push(value.toFixed(1))});const temperatures=temperaturesList.map((item,index)=>({name:index+1,value:item}));return{cmdResp03:cmdResp03,status:hex2string(data[2]),len:data[3],softwareV:hex2string(content[18]),balances:balances,BMSVersion:BMSVersion,soc:soc,normCap:normCap,surplusCapacity:surplusCapacity,totalVoltage:totalVoltage,electricity:electricity,power:power,cycleIndex:cycleIndex,equilibriumStatus:equilibriumStatus,chargeSwitch:chargeSwitch,dischargeSwitch:dischargeSwitch,temperatures:temperatures,humidity:humidity,protectStatus:protectStatus,fullChargeCapacity:fullChargeCapacity,SOH:SOH,heatingState:heatingState,heatingCurrent:heatingCurrent,equilibriumCurrent:equilibriumCurrent,isFactoryMode:isFactoryMode,protVal:protVal,alarmsState:alarmsState,ntcNums:ntcNums,temperaturesList:temperaturesList,fahTempList:fahTempList,fet:fet,seriesNum:seriesNum}},getDDA504Async=async(deviceId,dataScope)=>{const hex=await getData(deviceId,{command:["0xdd","0xa5","0x04","0x00","0xff","0xfc","0x77"],commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&4==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA5_04");return hex?resolveDDA504(hex,dataScope):null},resolveDDA504=(data,dataScope)=>{if(console.log("data: ",data),!data)return null;const cmdResp04=hexArr2string(data),voltageList=[];for(let index=4;index<parseInt(data[3])+4;index+=2){let voltageHex=decimalToHex(data[index])+decimalToHex(data[index+1]),voltage=hexToDecimal(voltageHex);voltageList.push(Number(voltage))}let highestVoltage=null,lowestVoltage=null,averageVoltage=null,dropoutVoltage=null;if(voltageList.length>0){highestVoltage=Math.max(...voltageList),lowestVoltage=Math.min(...voltageList);averageVoltage=voltageList.reduce((acc,cur)=>acc+cur,0)/voltageList.length;const dropout=highestVoltage-lowestVoltage,precision=dataScope?3:2;highestVoltage=Number((highestVoltage/1e3).toFixed(precision)),lowestVoltage=Number((lowestVoltage/1e3).toFixed(precision)),averageVoltage=Number((averageVoltage/1e3).toFixed(precision)),dropoutVoltage=Number((dropout/1e3).toFixed(precision))}voltageList.forEach((v,i)=>{let newV=v/1e3;voltageList[i]=Number(newV.toFixed(dataScope?3:2))});const voltageSeries=voltageList.map((item,index)=>({name:index+1,value:item}));return{cmdResp04:cmdResp04,voltageList:voltageList,voltageSeries:voltageSeries,highestVoltage:highestVoltage,lowestVoltage:lowestVoltage,averageVoltage:averageVoltage,dropoutVoltage:dropoutVoltage}},getChipTypeAsync=async deviceId=>{const hex=await getData(deviceId,{command:["0xdd","0xa5","0x00","0x00","0x00","0x00","0x77"],commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&0==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA5_00");return hex?resolveDDA500(hex):null},resolveDDA500=data=>{if(!data)return null;return{dataStr:hexArr2string(data),status:hex2string(data[2]),len:data[3],type:data[5]}},getDD5AE1Async=async(deviceId,value)=>{const _command=["0xE1","0x02","0x00",value],checks=generateCrcCheckSum(_command),command=["0xDD","0x5A",..._command,...checks,"0x77"];return getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&225==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"DD5A_E1")},getDD5AFBAsync=async(deviceId,type,value)=>{const _command=["0xFB","0x02",type,value],checks=generateCrcCheckSum(_command),command=["0xDD","0x5A",..._command,...checks,"0x77"];return console.log("command: ",command),getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&251==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"DD5A_FB")},resolveBaseDD=data=>{if(!data)return null;const dataStr=hexArr2string(data),content=data.slice(4,data.length-3);return{dataStr:dataStr,status:hex2string(data[2]),len:data[3],content:content}},getDD5A0AAsync=async(deviceId,value)=>{const _command=["0x0A","0x02",...stringToTwoHexArray(value)],checks=generateCrcCheckSum(_command),command=["0xDD","0x5A",..._command,...checks,"0x77"];return console.log("command: ",command),getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&10==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},`DD5A_0A_${value}`)},resolveDD5A0A=data=>{if(!data)return null;const dataStr=hexArr2string(data),statusDec=data[2],len=data[3],succeeded=0===statusDec;return{dataStr:dataStr,status:hex2string(statusDec),len:len,succeeded:succeeded,message:succeeded?"CMD_EXEC_SUCCESS":"CMD_EXEC_FAIL"}},getDD5AFAAsync=async(deviceId,value)=>{const hexStr=decimalToHex(100*value,4),_command=["0xFA","0x05","0x00","0x70","0x01",...[`0x${hexStr.slice(0,2)}`,`0x${hexStr.slice(2,4)}`]],checks=generateCrcCheckSum(_command),command=["0xDD","0x5A",..._command,...checks,"0x77"];return getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&250==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"DD5A_FA")},getDDA505Async=async deviceId=>getData(deviceId,{command:["0xdd","0xa5","0x05","0x00","0xff","0xfb","0x77"],commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&5==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA5_05"),resolveDDA505=data=>{if(!data)return null;return{dataStr:hexArr2string(data),status:hex2string(data[2]),len:data[3],hardwareV:hexArr2Assic(data.slice(4,data.length-3))}},getDDA5FAAsync=async(deviceId,paramNo,length)=>{const _values=[...paramNo,length],_command=["0xFA",decimalToHex(_values.length),..._values],checks=generateCrcCheckSum(_command),command=["0xDD","0xA5",..._command,...checks,"0x77"];return getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&250==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"READ_DDA5_FA")},setDDA5FAAsync=async(deviceId,paramNo,valueLength,content)=>{const _values=[...paramNo,valueLength,...content],_command=["0xFA",decimalToHex(_values.length),..._values],checks=generateCrcCheckSum(_command),command=["0xDD","0x5A",..._command,...checks,"0x77"];return getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&250==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"SET_DDA5_FA")},resolveDDA5FA=data=>{if(!data)return null;return{dataStr:hexArr2string(data),status:hex2string(data[2]),len:data[3],type:data[5],value:data.slice(7,-3)}},getDDA5OldAsync=async(deviceId,path)=>{const values=[path,"0x00"],checks=generateCrcCheckSum(values),command=["0xDD","0xa5",...values,...checks,"0x77"];return getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&hexArr[1]==path,pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA5_读旧协议读参")},setDDA5OldAsync=async(deviceId,path,value,type="")=>{const values=[path,"0x02",...value],checks=generateCrcCheckSum(values),command=["0xDD","0x5A",...values,...checks,"0x77"];return getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&hexArr[1]==path,pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"DDA5_写旧协议读参"+type)},getDD5AE0Async=async(deviceId,value)=>{const hex=100*value,hexStr=decimalToHex(hex,4),_values=[`0x${hexStr.slice(0,2)}`,`0x${hexStr.slice(2,4)}`],_command=["0xE0","0x02",..._values],checks=generateCrcCheckSum(_command),command=["0xDD","0x5A",..._command,...checks,"0x77"];return console.warn("=======CCCCCCC=SET===",{value:value,hex:hex,hexStr:hexStr,_values:_values,_command:_command,checks:checks,command:command}),getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&224==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"DD5A_E0")},getDD5A0EAsync=async deviceId=>getData(deviceId,{command:["0xDD","0x5A","0x0E","0x02","0x81","0x18","0xFF","0x57","0x77"],commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&14==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"DD5A_0E_复位"),getDD5AE4Async=async deviceId=>getData(deviceId,{command:["0xdd","0x5a","0xe4","0x02","0x18","0x81","0xfe","0x81","0x77"],commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&228==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"DD5A_E4"),getDD5AAllAsync=async(deviceId,path,lengthHex,values,type)=>{const _command=[path,lengthHex,...values],checks=generateCrcCheckSum(_command),command=["0xDD","0x5A",..._command,...checks,"0x77"];return getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&hexArr[1]==path,pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},`DD5A_${path}_${type}`)},sendBMSAsync=async(deviceId,values)=>{const command=values.match(/[0-9a-fA-F]{2}/g)?.map(item=>`0x${item}`)||[];return getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&hexArr[1]==command[2],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},`DD5A_${command[2]}`)},resolveBMSCmd=data=>{if(!data)return null;return{dataStr:hexArr2string(data),status:hex2string(data[2]),len:data[3]}},getProtectCountCmd=async deviceId=>{const data=await getData(deviceId,{command:["0xdd","0xa5","0xaa","0x00","0xff","0x56","0x77"],commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&170==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"DDA5_AA保护次数"),arr=[];for(let i=4;i<data.length-4;i+=2){const offset=i;console.log("offset",offset);let value=((255&data[offset])<<8)+(255&data[offset+1]);arr.push(value)}return arr},getDD5A17Async=async deviceId=>getData(deviceId,{command:["0xDD","0x5A","0x17","0x02","0x00","0x01","0xFF","0xE6","0x77"],commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&23==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"DD5A_17-清除电池循环次数"),getDDA507Async=async deviceId=>getData(deviceId,{command:["0xDD","0xA5","0x07","0x00","0xFF","0xF9","0x77"],commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&7==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA5_07历史运行履历总数"),getDDA508Async=async(deviceId,i=0)=>{const _command=["0x08",`0x${i.toString(16).padStart(2,0)}`],checks=generateCrcCheckSum(_command),command=["0xDD","0xA5",..._command,...checks,"0x77"];return getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&8==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA5_08读取履历详情")},resolveProtections=binary=>{const arr=binary.split("").reverse(),map=["device.0041","device.0042","device.0043","device.0044","device.0045","device.0046","device.0047","device.0048","device.0049","device.0050","device.0051","device.0052","device.0053","device.0054","device.0055","device.00551"];let _arr=[],_indexs=[];for(let i=0;i<arr.length;i++)1==arr[i]&&(_arr.push(map[i]),_indexs.push(i));return{_arr:_arr,_indexs:_indexs}},resolveDDA508=data=>{if(!data)return null;if(!data)return null;const hexArr=data.map(o=>o.toString(16).padStart(2,"0").toUpperCase()),f=s=>parseInt(s,16),fet=data[40].toString(2).padStart(8,"0").split("").reverse(),protection=f(hexArr[23]+hexArr[22]).toString(2).padStart(16,"0"),n=Number(fet[7])?10:100;let current=(hexArr[16]<<8)+(255&hexArr[17]);current=current>32768?(current-65536)/n:current/n;const electricity=Number(current.toFixed(2)),sysTime=65536*data[30]+256*data[31]+data[32];console.log("hexArr[30], hexArr[31], hexArr[32]",hexArr[30],hexArr[31],hexArr[32]),console.warn("sysTime: ",sysTime);const reportTime=65536*data[11]+256*data[12]+data[13];console.log("data[11], data[12], data[13]",data[11],data[12],data[13]),console.warn("reportTime: ",reportTime);const time=60*Math.abs(sysTime-reportTime)*1e3;console.warn("time: ",time);const timestamp=(new Date).getTime()-time;return console.warn("new Date().getTime(): ",(new Date).getTime()),{dataStr:hexArr.join(""),status:hex2string(data[2]),len:data[3],total:f(hexArr[4]+hexArr[5]),page:f(hexArr[6]+hexArr[7]),type:data[8],sysTime:sysTime,timestamp:timestamp,sumV:(f(hexArr[15]+hexArr[14])/100).toFixed(2),sumE:electricity,restC:(f(hexArr[19]+hexArr[18])/n).toFixed(2),designC:(f(hexArr[21]+hexArr[20])/n).toFixed(2),protections:resolveProtections(protection)._arr,protectionIndex:resolveProtections(protection)._indexs,tH:((f(hexArr[27]+hexArr[26])-2731)/10).toFixed(2),tL:((f(hexArr[29]+hexArr[28])-2731)/10).toFixed(2),vH:(f(hexArr[35]+hexArr[34])/1e3).toFixed(3),vL:(f(hexArr[37]+hexArr[36])/1e3).toFixed(3),nH:f(hexArr[38]),nL:f(hexArr[39]),fet:fet.join("")}},get3B3CInfo=({deviceId:deviceId,macAddr:macAddr,moduleType:moduleType,productType:productType})=>new Promise(async(resolve,reject)=>{let reportData={macAddr:macAddr,moduleTypeKey:moduleType,productKey:productType},_3b3c=null,_dda5_03=null,_dda5_05=null,_ffaa_80=null;try{if(!deviceId)throw new Error("deviceId required");const _ffaa_80_hex=await getFFAA80Async(deviceId,"AT^VERSION?");_ffaa_80=resolveFFAA80(_ffaa_80_hex),console.warn("Report-3B3C _ffaa_80 ",{_ffaa_80_hex:_ffaa_80_hex,_ffaa_80:_ffaa_80}),_ffaa_80&&(reportData.moduleVersion=_ffaa_80?.moduleVersion);const _3b3c_hex=await get3B3CAsync(deviceId);if(_3b3c=resolve3B3C(_3b3c_hex),console.warn("Report-3B3C _3b3c ",{_3b3c_hex:_3b3c_hex,_3b3c:_3b3c}),_3b3c)reportData.cmdContent=_3b3c?.dataStr;else{const _dda5_03_hex=await getDDA503Async(deviceId);_dda5_03=resolveDDA503(_dda5_03_hex),console.warn("Report-3B3C _dda5_03 ",{_dda5_03_hex:_dda5_03_hex,_dda5_03:_dda5_03}),_dda5_03&&(reportData.bmsVersion=_dda5_03?.softwareV);const _dda5_05_hex=await getDDA505Async(deviceId);_dda5_05=resolveDDA505(_dda5_05_hex),console.warn("Report-3B3C _dda5_05 ",{_dda5_05_hex:_dda5_05_hex,_dda5_05:_dda5_05}),_dda5_05&&(reportData.bmsSn=_dda5_05?.hardwareV)}resolve({reportData:reportData,_3b3c:_3b3c,_dda5_03:_dda5_03,_dda5_05:_dda5_05,_ffaa_80:_ffaa_80})}catch(error){reject(error)}}),activateAsync=async deviceId=>{const startTime=+new Date,disChargMOSHex=await getDD5AFBAsync(deviceId,"0x00","0x00"),disChargMOSRes=resolveBaseDD(disChargMOSHex)?.dataStr,disChargEndTime=+new Date,activeHex=await getDD5AFBAsync(deviceId,"0x05","0x01"),activeRes=resolveBaseDD(disChargMOSHex)?.dataStr;let baseInfo=null;const endTime=+new Date;await sleep(300),baseInfo=await getDDA503Async(deviceId);return{disChargMOSHex:disChargMOSHex,disChargMOSRes:disChargMOSRes,activeHex:activeHex,activeRes:activeRes,baseInfo:baseInfo,voltageInfo:await getDDA504Async(deviceId),startTime:startTime,disChargEndTime:disChargEndTime,endTime:endTime}},getDDA5DCAsync=deviceId=>{const _command=["0xDE","0x00"],checks=generateCrcCheckSum(_command),command=["0xDD","0xA5",..._command,...checks,"0x77"];return getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&222==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA5_DC")},resolveDDA5DC=data=>{if(!data)return null;const dataStr=hexArr2string(data),status=hex2string(data[2]),len=255&data[3],resistances_milliohm=[];for(let i=4;i<4+len;i+=2){const value=((255&data[i])<<8)+(255&data[i+1]);resistances_milliohm.push(value)}console.log("均衡线电阻(mΩ): ",resistances_milliohm,data);let maxResistance=null,minResistance=null,avgResistance=null;resistances_milliohm.length&&(maxResistance=Math.max(...resistances_milliohm),minResistance=Math.min(...resistances_milliohm),avgResistance=resistances_milliohm.reduce((a,c)=>a+c,0)/resistances_milliohm.length);const resistances_ohm=resistances_milliohm.map(v=>Number((v/1e3).toFixed(3))),resistancesSeries=resistances_ohm.map((v,idx)=>({name:idx+1,value:v}));return{dataStr:dataStr,status:status,len:len,resistances_milliohm:resistances_milliohm,resistances_ohm:resistances_ohm,maxResistance_milliohm:maxResistance,minResistance_milliohm:minResistance,avgResistance_milliohm:avgResistance,maxResistance_ohm:null!=maxResistance?Number((maxResistance/1e3).toFixed(3)):null,minResistance_ohm:null!=minResistance?Number((minResistance/1e3).toFixed(3)):null,avgResistance_ohm:null!=avgResistance?Number((avgResistance/1e3).toFixed(3)):null,resistancesSeries:resistancesSeries}},resetCapacity=deviceId=>getData(deviceId,{command:["0xDD","0x5A","0x0A","0x02","0x01","0x00","0xFF","0xF3","0x77"],commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&10==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"DD5A_0A");export{activateAsync,enterFactory,existFactory,get3B3CAsync,get3B3CInfo,getChipTypeAsync,getDD5A0AAsync,getDD5A0EAsync,getDD5A17Async,getDD5AAllAsync,getDD5AE0Async,getDD5AE1Async,getDD5AE4Async,getDD5AFAAsync,getDD5AFBAsync,getDDA503Async,getDDA504Async,getDDA505Async,getDDA507Async,getDDA508Async,getDDA5DCAsync,getDDA5FAAsync,getDDA5OldAsync,getProtectCountCmd,readExistFactory,resetCapacity,resolve3B3C,resolveBMSCmd,resolveBaseDD,resolveDD5A0A,resolveDDA500,resolveDDA503,resolveDDA504,resolveDDA505,resolveDDA508,resolveDDA5DC,resolveDDA5FA,resolveProtections,sendBMSAsync,setDDA5FAAsync,setDDA5OldAsync,set_PlanCMD_3B3C,set_PlanCMD_DD};
1
+ import{hexArr2string,hex2string,decimalToHex,generateCrc16modbusCheck,hexArr2Assic,generateCrcCheckSum,hexToDecimal,stringToTwoHexArray,sleep,fromBCD,isWithin30Minutes,toBCD}from"../BleDataProcess.js";import{getData}from"./BleCmdAnalysis.js";import{getFFAA80Async,resolveFFAA80}from"./BleCmdFFAA.js";const enterFactory=async deviceId=>set_PlanCMD_DD(deviceId,"DD5A00025678FF3077"),existFactory=async deviceId=>set_PlanCMD_DD(deviceId,"DD5A01022828ffad77"),readExistFactory=async deviceId=>set_PlanCMD_DD(deviceId,"DD5A01020000FFFD77"),set_PlanCMD_DD=async(deviceId,command)=>{"string"==typeof command&&(command=command.match(/(.{2})/g).map(o=>`0x${o}`));let result=null;try{const data=await getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"PlanCMD_DD");if(data){const dataStr=hexArr2string(data),content=data.slice(4,data.length-3);result={data:data,dataStr:dataStr,status:hex2string(data[2]),len:data[3],content:content}}else result={status:0,content:[]}}catch(error){console.error(error)}return result},set_PlanCMD_3B3C=async(deviceId,command)=>{"string"==typeof command&&(command=command.match(/(.{2})/g).map(o=>`0x${o}`));let result=null;try{const data=await getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:59==hexArr[0]&&60==hexArr[1],pkgLen:hexArr[11]+15}),pkgVerifyHandler:pkg=>({verified:!0})},"PlanCMD_3B3C");if(data){const dataStr=hexArr2string(data),content=data.slice(12,data.length-3);result={dataStr:dataStr,status:128==data[10]?1:0,addr:hexArr2string(data.slice(2,10)),content:content}}}catch(error){console.error(error)}return result},get3B3CAsync=async deviceId=>{const addressCode=["0x00","0x00","0x00","0x00","0x00","0x00","0x00","0x00"],commandCode=["0x01"],data=[],dataLength=[`0x${decimalToHex(data.length,2)}`],check=generateCrc16modbusCheck([...addressCode,...commandCode,...dataLength,...data],!1),command=["0x3b","0x3c",...addressCode,...commandCode,...dataLength,...data,...check,"0x0d"];return getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:59==hexArr[0]&&60==hexArr[1],pkgLen:hexArr[11]+15}),pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=generateCrc16modbusCheck(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"3B3C")},resolve3B3C=data=>{if(!data)return null;let result={dataStr:hexArr2string(data),status:hex2string(data[10]),addr:hexArr2string(data.slice(2,10))};const content=data.slice(12,data.length-3);for(;content.length>0;){const[v1,v2,...v]=content.splice(0,content[1]+2);if(1==v1&&(result.productFlag=hex2string(v1),result.productLen=v2,v)){const[productType,frontType,protocolV,level]=v.map(o=>hex2string(o));Object.assign(result,{productType:productType,frontType:frontType,protocolV:protocolV,level:level})}2==v1&&(result.hardwareFlag=hex2string(v1),result.hardwareLen=v2,result.hardwareV=hexArr2Assic(v)),3==v1&&(result.sofewareFlag=hex2string(v1),result.sofewareLen=v2,result.sofewareV=hexArr2Assic(v)),4==v1&&(result.pcbFlag=hex2string(v1),result.pcbLen=v2,result.pcbContent=hexArr2Assic(v))}return result},getDDA503Async=async deviceId=>{const hex=await 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]=generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA5_03");return hex?resolveDDA503(hex):null},resolveDDA503=data=>{if(!data)return null;const cmdResp03=hexArr2string(data),content=data.slice(4,data.length-3),binArr=data[24].toString(2).padStart(8,"0").split("").reverse(),BC1=(data[16]<<8|data[17]).toString(2).padStart(16,"0").split("").reverse();console.log("BC1: ",BC1);const BC2=(data[18]<<8|data[19]).toString(2).padStart(16,"0").split("").reverse(),balances=BC1.concat(BC2);console.warn("BC: ---------------",balances);const fet=data[24],chargeSwitch=!!Number(binArr[0]),dischargeSwitch=!!Number(binArr[1]),BMSVersion=decimalToHex(data[22]),humidityIndex=2*data[26]+27,humidity=data[humidityIndex],n=Number(binArr[7])||136==humidity?10:100,totalVoltage=Number((((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=Number((totalVoltage*electricity).toFixed(2)),soc=data[23]??0,seriesNum=data[25]??0,volumeHex=decimalToHex(data[8])+decimalToHex(data[9]),surplusCapacity=Number((hexToDecimal(volumeHex)/n).toFixed(2)),normCapHex=decimalToHex(data[10])+decimalToHex(data[11]),normCap=Number((hexToDecimal(normCapHex)/n).toFixed(2)),cycleHex=decimalToHex(data[12])+decimalToHex(data[13]),cycleIndex=hexToDecimal(cycleHex),fccHex=decimalToHex(data[humidityIndex+3])+decimalToHex(data[humidityIndex+4]),fullChargeCapacity=Number((hexToDecimal(fccHex)/n).toFixed(2)),SOH=cycleIndex<=100?100:Math.min(100,fullChargeCapacity/normCap*100),heatingState=!!Number(binArr[4])||!!Number(binArr[3]);let heatingCurrent=null;const hasHeatingCurrent=data[3]+7>=humidityIndex+9+4+1,hasEquilCurrent=data[3]+7>=humidityIndex+7+4+1;if(heatingState&&hasHeatingCurrent){const i=humidityIndex+9;heatingCurrent=heatingCurrent=((data[i]<<8|data[i+1])/100).toFixed(2)}let equilibriumCurrent=null;if(hasEquilCurrent){const i=humidityIndex+7;let equilCurrent=(data[i]<<8)+(255&data[i+1]);equilCurrent=equilCurrent>32768?(equilCurrent-65536)/1e3:equilCurrent/1e3,equilibriumCurrent=Number(equilCurrent.toFixed(2))}const isFactoryMode=!!Number(binArr[6]),equilibriumStatus=!(0===data[16]&&0===data[17]),protectStatus=!(0===data[20]&&0===data[21]),protectStateHex=decimalToHex(data[20])+decimalToHex(data[21]),protVal=hexToDecimal(protectStateHex);let alarmIndex=2*data[26]+28,alarmStateHex=decimalToHex(data[alarmIndex])+decimalToHex(data[alarmIndex+1]),alarmsState=hexToDecimal(alarmStateHex);const 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=[];temperaturesList.forEach(el=>{const value=1.8*Number(el)+32;fahTempList.push(value.toFixed(1))});const temperatures=temperaturesList.map((item,index)=>({name:index+1,value:item}));return{cmdResp03:cmdResp03,status:hex2string(data[2]),len:data[3],softwareV:hex2string(content[18]),balances:balances,BMSVersion:BMSVersion,soc:soc,normCap:normCap,surplusCapacity:surplusCapacity,totalVoltage:totalVoltage,electricity:electricity,power:power,cycleIndex:cycleIndex,equilibriumStatus:equilibriumStatus,chargeSwitch:chargeSwitch,dischargeSwitch:dischargeSwitch,temperatures:temperatures,humidity:humidity,protectStatus:protectStatus,fullChargeCapacity:fullChargeCapacity,SOH:SOH,heatingState:heatingState,heatingCurrent:heatingCurrent,equilibriumCurrent:equilibriumCurrent,isFactoryMode:isFactoryMode,protVal:protVal,alarmsState:alarmsState,ntcNums:ntcNums,temperaturesList:temperaturesList,fahTempList:fahTempList,fet:fet,seriesNum:seriesNum}},getDDA504Async=async(deviceId,dataScope)=>{const hex=await getData(deviceId,{command:["0xdd","0xa5","0x04","0x00","0xff","0xfc","0x77"],commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&4==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA5_04");return hex?resolveDDA504(hex,dataScope):null},resolveDDA504=(data,dataScope)=>{if(console.log("data: ",data),!data)return null;const cmdResp04=hexArr2string(data),voltageList=[];for(let index=4;index<parseInt(data[3])+4;index+=2){let voltageHex=decimalToHex(data[index])+decimalToHex(data[index+1]),voltage=hexToDecimal(voltageHex);voltageList.push(Number(voltage))}let highestVoltage=null,lowestVoltage=null,averageVoltage=null,dropoutVoltage=null;if(voltageList.length>0){highestVoltage=Math.max(...voltageList),lowestVoltage=Math.min(...voltageList);averageVoltage=voltageList.reduce((acc,cur)=>acc+cur,0)/voltageList.length;const dropout=highestVoltage-lowestVoltage,precision=dataScope?3:2;highestVoltage=Number((highestVoltage/1e3).toFixed(precision)),lowestVoltage=Number((lowestVoltage/1e3).toFixed(precision)),averageVoltage=Number((averageVoltage/1e3).toFixed(precision)),dropoutVoltage=Number((dropout/1e3).toFixed(precision))}voltageList.forEach((v,i)=>{let newV=v/1e3;voltageList[i]=Number(newV.toFixed(dataScope?3:2))});const voltageSeries=voltageList.map((item,index)=>({name:index+1,value:item}));return{cmdResp04:cmdResp04,voltageList:voltageList,voltageSeries:voltageSeries,highestVoltage:highestVoltage,lowestVoltage:lowestVoltage,averageVoltage:averageVoltage,dropoutVoltage:dropoutVoltage}},getChipTypeAsync=async deviceId=>{const hex=await getData(deviceId,{command:["0xdd","0xa5","0x00","0x00","0x00","0x00","0x77"],commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&0==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA5_00");return hex?resolveDDA500(hex):null},resolveDDA500=data=>{if(!data)return null;return{dataStr:hexArr2string(data),status:hex2string(data[2]),len:data[3],type:data[5]}},getDD5AE1Async=async(deviceId,value)=>{const _command=["0xE1","0x02","0x00",value],checks=generateCrcCheckSum(_command),command=["0xDD","0x5A",..._command,...checks,"0x77"];return getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&225==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"DD5A_E1")},getDD5AFBAsync=async(deviceId,type,value)=>{const _command=["0xFB","0x02",type,value],checks=generateCrcCheckSum(_command),command=["0xDD","0x5A",..._command,...checks,"0x77"];return console.log("command: ",command),getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&251==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"DD5A_FB")},resolveBaseDD=data=>{if(!data)return null;const dataStr=hexArr2string(data),content=data.slice(4,data.length-3);return{dataStr:dataStr,status:hex2string(data[2]),len:data[3],content:content}},getDD5A0AAsync=async(deviceId,value)=>{const _command=["0x0A","0x02",...stringToTwoHexArray(value)],checks=generateCrcCheckSum(_command),command=["0xDD","0x5A",..._command,...checks,"0x77"];return console.log("command: ",command),getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&10==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},`DD5A_0A_${value}`)},resolveDD5A0A=data=>{if(!data)return null;const dataStr=hexArr2string(data),statusDec=data[2],len=data[3],succeeded=0===statusDec;return{dataStr:dataStr,status:hex2string(statusDec),len:len,succeeded:succeeded,message:succeeded?"CMD_EXEC_SUCCESS":"CMD_EXEC_FAIL"}},getDD5AFAAsync=async(deviceId,value)=>{const hexStr=decimalToHex(100*value,4),_command=["0xFA","0x05","0x00","0x70","0x01",...[`0x${hexStr.slice(0,2)}`,`0x${hexStr.slice(2,4)}`]],checks=generateCrcCheckSum(_command),command=["0xDD","0x5A",..._command,...checks,"0x77"];return getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&250==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"DD5A_FA")},getDDA505Async=async deviceId=>getData(deviceId,{command:["0xdd","0xa5","0x05","0x00","0xff","0xfb","0x77"],commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&5==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA5_05"),resolveDDA505=data=>{if(!data)return null;return{dataStr:hexArr2string(data),status:hex2string(data[2]),len:data[3],hardwareV:hexArr2Assic(data.slice(4,data.length-3))}},getDDA5FAAsync=async(deviceId,paramNo,length)=>{const _values=[...paramNo,length],_command=["0xFA",decimalToHex(_values.length),..._values],checks=generateCrcCheckSum(_command),command=["0xDD","0xA5",..._command,...checks,"0x77"];return getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&250==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"READ_DDA5_FA")},setDDA5FAAsync=async(deviceId,paramNo,valueLength,content)=>{const _values=[...paramNo,valueLength,...content],_command=["0xFA",decimalToHex(_values.length),..._values],checks=generateCrcCheckSum(_command),command=["0xDD","0x5A",..._command,...checks,"0x77"];return getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&250==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"SET_DDA5_FA")},resolveDDA5FA=data=>{if(!data)return null;return{dataStr:hexArr2string(data),status:hex2string(data[2]),len:data[3],type:data[5],value:data.slice(7,-3)}},getDDA5OldAsync=async(deviceId,path)=>{const values=[path,"0x00"],checks=generateCrcCheckSum(values),command=["0xDD","0xa5",...values,...checks,"0x77"];return getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&hexArr[1]==path,pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA5_读旧协议读参")},setDDA5OldAsync=async(deviceId,path,value,type="")=>{const values=[path,"0x02",...value],checks=generateCrcCheckSum(values),command=["0xDD","0x5A",...values,...checks,"0x77"];return getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&hexArr[1]==path,pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"DDA5_写旧协议读参"+type)},getDD5AE0Async=async(deviceId,value)=>{const hex=100*value,hexStr=decimalToHex(hex,4),_values=[`0x${hexStr.slice(0,2)}`,`0x${hexStr.slice(2,4)}`],_command=["0xE0","0x02",..._values],checks=generateCrcCheckSum(_command),command=["0xDD","0x5A",..._command,...checks,"0x77"];return console.warn("=======CCCCCCC=SET===",{value:value,hex:hex,hexStr:hexStr,_values:_values,_command:_command,checks:checks,command:command}),getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&224==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"DD5A_E0")},getDD5A0EAsync=async deviceId=>getData(deviceId,{command:["0xDD","0x5A","0x0E","0x02","0x81","0x18","0xFF","0x57","0x77"],commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&14==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"DD5A_0E_复位"),getDD5AE4Async=async deviceId=>getData(deviceId,{command:["0xdd","0x5a","0xe4","0x02","0x18","0x81","0xfe","0x81","0x77"],commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&228==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"DD5A_E4"),getDD5AAllAsync=async(deviceId,path,lengthHex,values,type)=>{const _command=[path,lengthHex,...values],checks=generateCrcCheckSum(_command),command=["0xDD","0x5A",..._command,...checks,"0x77"];return getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&hexArr[1]==path,pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},`DD5A_${path}_${type}`)},sendBMSAsync=async(deviceId,values)=>{const command=values.match(/[0-9a-fA-F]{2}/g)?.map(item=>`0x${item}`)||[];return getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&hexArr[1]==command[2],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},`DD5A_${command[2]}`)},resolveBMSCmd=data=>{if(!data)return null;return{dataStr:hexArr2string(data),status:hex2string(data[2]),len:data[3]}},getProtectCountCmd=async deviceId=>{const data=await getData(deviceId,{command:["0xdd","0xa5","0xaa","0x00","0xff","0x56","0x77"],commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&170==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"DDA5_AA保护次数"),arr=[];for(let i=4;i<data.length-4;i+=2){const offset=i;console.log("offset",offset);let value=((255&data[offset])<<8)+(255&data[offset+1]);arr.push(value)}return arr},getDD5A17Async=async deviceId=>getData(deviceId,{command:["0xDD","0x5A","0x17","0x02","0x00","0x01","0xFF","0xE6","0x77"],commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&23==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"DD5A_17-清除电池循环次数"),getDDA507Async=async deviceId=>getData(deviceId,{command:["0xDD","0xA5","0x07","0x00","0xFF","0xF9","0x77"],commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&7==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA5_07历史运行履历总数"),getDDA508Async=async(deviceId,i=0)=>{const _command=["0x08",`0x${i.toString(16).padStart(2,0)}`],checks=generateCrcCheckSum(_command),command=["0xDD","0xA5",..._command,...checks,"0x77"];return getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&8==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA5_08读取履历详情")},resolveProtections=binary=>{const arr=binary.split("").reverse(),map=["device.0041","device.0042","device.0043","device.0044","device.0045","device.0046","device.0047","device.0048","device.0049","device.0050","device.0051","device.0052","device.0053","device.0054","device.0055","device.00551"];let _arr=[],_indexs=[];for(let i=0;i<arr.length;i++)1==arr[i]&&(_arr.push(map[i]),_indexs.push(i));return{_arr:_arr,_indexs:_indexs}},resolveDDA508=data=>{if(!data)return null;if(!data)return null;const hexArr=data.map(o=>o.toString(16).padStart(2,"0").toUpperCase()),f=s=>parseInt(s,16),fet=data[40].toString(2).padStart(8,"0").split("").reverse(),protection=f(hexArr[23]+hexArr[22]).toString(2).padStart(16,"0"),n=Number(fet[7])?10:100;let current=(hexArr[16]<<8)+(255&hexArr[17]);current=current>32768?(current-65536)/n:current/n;const electricity=Number(current.toFixed(2)),sysTime=65536*data[30]+256*data[31]+data[32];console.log("hexArr[30], hexArr[31], hexArr[32]",hexArr[30],hexArr[31],hexArr[32]),console.warn("sysTime: ",sysTime);const reportTime=65536*data[11]+256*data[12]+data[13];console.log("data[11], data[12], data[13]",data[11],data[12],data[13]),console.warn("reportTime: ",reportTime);const time=60*Math.abs(sysTime-reportTime)*1e3;console.warn("time: ",time);const timestamp=(new Date).getTime()-time;return console.warn("new Date().getTime(): ",(new Date).getTime()),{dataStr:hexArr.join(""),status:hex2string(data[2]),len:data[3],total:f(hexArr[4]+hexArr[5]),page:f(hexArr[6]+hexArr[7]),type:data[8],sysTime:sysTime,timestamp:timestamp,sumV:(f(hexArr[15]+hexArr[14])/100).toFixed(2),sumE:electricity,restC:(f(hexArr[19]+hexArr[18])/n).toFixed(2),designC:(f(hexArr[21]+hexArr[20])/n).toFixed(2),protections:resolveProtections(protection)._arr,protectionIndex:resolveProtections(protection)._indexs,tH:((f(hexArr[27]+hexArr[26])-2731)/10).toFixed(2),tL:((f(hexArr[29]+hexArr[28])-2731)/10).toFixed(2),vH:(f(hexArr[35]+hexArr[34])/1e3).toFixed(3),vL:(f(hexArr[37]+hexArr[36])/1e3).toFixed(3),nH:f(hexArr[38]),nL:f(hexArr[39]),fet:fet.join("")}},get3B3CInfo=({deviceId:deviceId,macAddr:macAddr,moduleType:moduleType,productType:productType})=>new Promise(async(resolve,reject)=>{let reportData={macAddr:macAddr,moduleTypeKey:moduleType,productKey:productType},_3b3c=null,_dda5_03=null,_dda5_05=null,_ffaa_80=null;try{if(!deviceId)throw new Error("deviceId required");const _ffaa_80_hex=await getFFAA80Async(deviceId,"AT^VERSION?");_ffaa_80=resolveFFAA80(_ffaa_80_hex),console.warn("Report-3B3C _ffaa_80 ",{_ffaa_80_hex:_ffaa_80_hex,_ffaa_80:_ffaa_80}),_ffaa_80&&(reportData.moduleVersion=_ffaa_80?.moduleVersion);const _3b3c_hex=await get3B3CAsync(deviceId);if(_3b3c=resolve3B3C(_3b3c_hex),console.warn("Report-3B3C _3b3c ",{_3b3c_hex:_3b3c_hex,_3b3c:_3b3c}),_3b3c)reportData.cmdContent=_3b3c?.dataStr;else{const _dda5_03_hex=await getDDA503Async(deviceId);_dda5_03=resolveDDA503(_dda5_03_hex),console.warn("Report-3B3C _dda5_03 ",{_dda5_03_hex:_dda5_03_hex,_dda5_03:_dda5_03}),_dda5_03&&(reportData.bmsVersion=_dda5_03?.softwareV);const _dda5_05_hex=await getDDA505Async(deviceId);_dda5_05=resolveDDA505(_dda5_05_hex),console.warn("Report-3B3C _dda5_05 ",{_dda5_05_hex:_dda5_05_hex,_dda5_05:_dda5_05}),_dda5_05&&(reportData.bmsSn=_dda5_05?.hardwareV)}resolve({reportData:reportData,_3b3c:_3b3c,_dda5_03:_dda5_03,_dda5_05:_dda5_05,_ffaa_80:_ffaa_80})}catch(error){reject(error)}}),activateAsync=async deviceId=>{const startTime=+new Date,disChargMOSHex=await getDD5AFBAsync(deviceId,"0x00","0x00"),disChargMOSRes=resolveBaseDD(disChargMOSHex)?.dataStr,disChargEndTime=+new Date,activeHex=await getDD5AFBAsync(deviceId,"0x05","0x01"),activeRes=resolveBaseDD(disChargMOSHex)?.dataStr;let baseInfo=null;const endTime=+new Date;await sleep(300),baseInfo=await getDDA503Async(deviceId);return{disChargMOSHex:disChargMOSHex,disChargMOSRes:disChargMOSRes,activeHex:activeHex,activeRes:activeRes,baseInfo:baseInfo,voltageInfo:await getDDA504Async(deviceId),startTime:startTime,disChargEndTime:disChargEndTime,endTime:endTime}},getDDA5DCAsync=deviceId=>{const _command=["0xDE","0x00"],checks=generateCrcCheckSum(_command),command=["0xDD","0xA5",..._command,...checks,"0x77"];return getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&222==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA5_DC")},resolveDDA5DC=data=>{if(!data)return null;const dataStr=hexArr2string(data),status=hex2string(data[2]),len=255&data[3],resistances_milliohm=[];for(let i=4;i<4+len;i+=2){const value=((255&data[i])<<8)+(255&data[i+1]);resistances_milliohm.push(value)}console.log("均衡线电阻(mΩ): ",resistances_milliohm,data);let maxResistance=null,minResistance=null,avgResistance=null;resistances_milliohm.length&&(maxResistance=Math.max(...resistances_milliohm),minResistance=Math.min(...resistances_milliohm),avgResistance=resistances_milliohm.reduce((a,c)=>a+c,0)/resistances_milliohm.length);const resistances_ohm=resistances_milliohm.map(v=>Number((v/1e3).toFixed(3))),resistancesSeries=resistances_ohm.map((v,idx)=>({name:idx+1,value:v}));return{dataStr:dataStr,status:status,len:len,resistances_milliohm:resistances_milliohm,resistances_ohm:resistances_ohm,maxResistance_milliohm:maxResistance,minResistance_milliohm:minResistance,avgResistance_milliohm:avgResistance,maxResistance_ohm:null!=maxResistance?Number((maxResistance/1e3).toFixed(3)):null,minResistance_ohm:null!=minResistance?Number((minResistance/1e3).toFixed(3)):null,avgResistance_ohm:null!=avgResistance?Number((avgResistance/1e3).toFixed(3)):null,resistancesSeries:resistancesSeries}},resetCapacity=deviceId=>getData(deviceId,{command:["0xDD","0x5A","0x0A","0x02","0x01","0x00","0xFF","0xF3","0x77"],commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&10==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"DD5A_0A"),getDDA506Async=async deviceId=>getData(deviceId,{command:["0xdd","0xa5","0x06","0x00","0xff","0xfa","0x77"],commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&6==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA5_06"),resolveDDA506=data=>{if(!data)return null;if(6==data[1]&&0==data[2]&&6==data[3]){const seconds=fromBCD(data[4]),minutes=fromBCD(data[5]),hours=fromBCD(data[6]),day=fromBCD(data[7]),month=fromBCD(data[8]),timeStr=`${2e3+fromBCD(data[9])}-${String(month).padStart(2,0)}-${String(day).padStart(2,0)} ${String(hours).padStart(2,0)}:${String(minutes).padStart(2,0)}:${String(seconds).padStart(2,0)}`;return console.log("timeStr: ",timeStr,isWithin30Minutes(timeStr)),isWithin30Minutes(timeStr)}return!1},setDD5AE3sync=async deviceId=>{const now=new Date,year=now.getFullYear(),month=now.getMonth()+1,day=now.getDate(),hours=now.getHours(),minutes=now.getMinutes(),seconds=now.getSeconds(),content=["0xE3","0x07","0x06",...[toBCD(seconds),toBCD(minutes),128|toBCD(hours),toBCD(day),toBCD(month),toBCD(year-2e3)].map(b=>"0x"+b.toString(16).padStart(2,"0"))],checks=generateCrcCheckSum(content),command=["0xDD","0x5A",...content,...checks,"0x77"];return console.log("command: ",command),getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&227==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"SET_DDA5_E3")},getDDA4F0Async=async deviceId=>{const command=["0xDD","0xA4","0xF0","0x00"],checks=generateCrcCheckSum(command.slice(2)),fullCommand=[...command,...checks,"0x77"];return getData(deviceId,{command:fullCommand,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&240==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA4_F0")},resolveDDA4F0=data=>{if(!data)return null;if(240==data[1]&&4==data[3]){const runTime=data[4]<<24|data[5]<<16|data[6]<<8|data[7];return{runTime:runTime,runTimeHour:(runTime/3600).toFixed(2),raw:hexArr2string(data)}}return null};export{activateAsync,enterFactory,existFactory,get3B3CAsync,get3B3CInfo,getChipTypeAsync,getDD5A0AAsync,getDD5A0EAsync,getDD5A17Async,getDD5AAllAsync,getDD5AE0Async,getDD5AE1Async,getDD5AE4Async,getDD5AFAAsync,getDD5AFBAsync,getDDA4F0Async,getDDA503Async,getDDA504Async,getDDA505Async,getDDA506Async,getDDA507Async,getDDA508Async,getDDA5DCAsync,getDDA5FAAsync,getDDA5OldAsync,getProtectCountCmd,readExistFactory,resetCapacity,resolve3B3C,resolveBMSCmd,resolveBaseDD,resolveDD5A0A,resolveDDA4F0,resolveDDA500,resolveDDA503,resolveDDA504,resolveDDA505,resolveDDA506,resolveDDA508,resolveDDA5DC,resolveDDA5FA,resolveProtections,sendBMSAsync,setDD5AE3sync,setDDA5FAAsync,setDDA5OldAsync,set_PlanCMD_3B3C,set_PlanCMD_DD};
@@ -1 +1 @@
1
- const crc16modbus=(data,swapNeed=!1)=>{let crc=65535;for(let i=0;i<data.length;i++){crc^=data[i];for(let j=0;j<8;j++)1&crc?crc=crc>>1^40961:crc>>=1}return swapNeed&&(crc=(255&crc)<<8|crc>>8&255),65535&crc},generateCrc16modbusCheck=(data,swapNeed=!1)=>{const hex=crc16modbus(data,swapNeed),hexStr=decimalToHex(hex,4);return[`0x${hexStr.slice(0,2)}`,`0x${hexStr.slice(2,4)}`]},crcCheckSum=(data,offset=1)=>{console.log("data: --------",data);let hex=0;for(let i=0;i<data.length;i++)hex+=255&data[i];return hex^=65535,hex+=offset,console.log("hex: -------------",hex),hex},generateCrcCheckSum=data=>{const hex=crcCheckSum(data),hexStr=decimalToHex(hex,4);return[`0x${hexStr.slice(0,2)}`,`0x${hexStr.slice(2,4)}`]},checkSum=(data=[])=>{const sum=data.map(o=>parseInt(o,16)).reduce((a,c)=>a+c,0);let sumHex="0x"+decimalToHex(sum,2);return sumHex&=255,sumHex},generateCheckSum=data=>{const hex=checkSum(data);return[`0x${decimalToHex(hex,2)}`]},ab2decimalArr=buffer=>Array.prototype.map.call(new Uint8Array(buffer),bit=>bit),ab2hex=buffer=>Array.prototype.map.call(new Uint8Array(buffer),function(bit){return("00"+bit.toString(16)).slice(-2)}).join(""),arrayBufferToHexArray=(arrayBuffer,withPrefix=!0)=>Array.prototype.map.call(new Uint8Array(arrayBuffer),x=>{let hex=("00"+x.toString(16)).slice(-2);return withPrefix?`0x${hex}`:hex}),base64ToHexArray=(base64,withPrefix=!0)=>{const arrayBuffer=uni.base64ToArrayBuffer(base64);return arrayBufferToHexArray(arrayBuffer,withPrefix)},hexArrayToModuleArrayBuffer=(fields,hexArray,withCheck=!0,withPrefix=!0)=>{const fieldsLength=fields.length;let offset=fieldsLength+1;withCheck&&offset++;let bufferLength=hexArray.length+offset;const buffer=new ArrayBuffer(bufferLength),dataView=new DataView(buffer),lengthCode=decimalToHex(hexArray.length);fields.forEach((field,i)=>{dataView.setUint8(i,field)}),dataView.setUint8(fieldsLength,"0x"+lengthCode);let indexNum=fieldsLength+1;if(hexArray.forEach((el,index)=>{dataView.setUint8(indexNum,withPrefix?"0x"+el:el),indexNum+=1}),withCheck){const code=fields[2].toString(16);let check=generateCheckSum([code,lengthCode,...hexArray]);dataView.setUint8(bufferLength-1,check[0])}return buffer},getParamBaseValue=arr=>{const hexString=arr.map(el=>decimalToHex(el)).join("");return parseInt(hexString,16)},decimalToHex=(decimal,padding=2)=>Number(decimal).toString(16).padStart(padding,"0"),decimalToHex0x=(decimal,padding=2)=>"0x"+Number(decimal).toString(16).padStart(padding,"0"),hexToDecimal=hex=>parseInt(hex,16),hexArr2ab=hexArr=>{const buffer=new ArrayBuffer(hexArr.length),dataView=new DataView(buffer);return hexArr.forEach((hex,i)=>dataView.setUint8(i,hex)),buffer},hex2string=hex=>("00"+hex.toString(16)).slice(-2).toUpperCase(),string2hexArr=str=>{let hexArray=[];for(let i=0;i<str.length;i++){const charCode=str.charCodeAt(i).toString(16).padStart(2,"0");hexArray.push(charCode)}return hexArray},hexArr2Assic=(hexArr=[])=>String.fromCharCode(...hexArr).replace(/\u0000/g,""),hexStrAscii=hexString=>{let asciiString="";for(let i=0;i<hexString.length;i+=2){const hexPair=hexString.substr(i,2),decimalValue=parseInt(hexPair,16);asciiString+=String.fromCharCode(decimalValue)}return asciiString.replace(/\u0000/g,"")},hex2Ascii=(value=[])=>{const hexString=value.join("");return hexStrAscii(hexString)},hexArr2string=(hexArr=[],connector="")=>hexArr.map(o=>hex2string(o)).join(connector),hex2Binary=(hex,len=0)=>parseInt(hex,16).toString(2).padStart(len,"0"),extractBits=(number,start,end)=>number>>start&(1<<end-start+1)-1,sleep=(n=500)=>new Promise(r=>setTimeout(()=>r(!0),n)),decimalToTwoByteHexArray=decimal=>{if("number"!=typeof decimal||!Number.isInteger(decimal))throw new Error("输入必须为整数");if(decimal<0||decimal>65535)throw new Error("输入的十进制数超出 16 位无符号整数范围(0 - 65535)");return[`0x${`00${(decimal>>8).toString(16)}`.slice(-2)}`,`0x${`00${(255&decimal).toString(16)}`.slice(-2)}`]},stringToTwoHexArray=str=>{const paddedStr=str.padStart(4,"0");return[`0x${paddedStr.slice(0,2)}`,`0x${paddedStr.slice(2,4)}`]},hexStringToBinary=hexString=>parseInt(hexString,16).toString(2);export{ab2decimalArr,ab2hex,arrayBufferToHexArray,base64ToHexArray,checkSum,crc16modbus,crcCheckSum,decimalToHex,decimalToHex0x,decimalToTwoByteHexArray,extractBits,generateCheckSum,generateCrc16modbusCheck,generateCrcCheckSum,getParamBaseValue,hex2Ascii,hex2Binary,hex2string,hexArr2Assic,hexArr2ab,hexArr2string,hexArrayToModuleArrayBuffer,hexStrAscii,hexStringToBinary,hexToDecimal,sleep,string2hexArr,stringToTwoHexArray};
1
+ const crc16modbus=(data,swapNeed=!1)=>{let crc=65535;for(let i=0;i<data.length;i++){crc^=data[i];for(let j=0;j<8;j++)1&crc?crc=crc>>1^40961:crc>>=1}return swapNeed&&(crc=(255&crc)<<8|crc>>8&255),65535&crc},generateCrc16modbusCheck=(data,swapNeed=!1)=>{const hex=crc16modbus(data,swapNeed),hexStr=decimalToHex(hex,4);return[`0x${hexStr.slice(0,2)}`,`0x${hexStr.slice(2,4)}`]},crcCheckSum=(data,offset=1)=>{console.log("data: --------",data);let hex=0;for(let i=0;i<data.length;i++)hex+=255&data[i];return hex^=65535,hex+=offset,console.log("hex: -------------",hex),hex},generateCrcCheckSum=data=>{const hex=crcCheckSum(data),hexStr=decimalToHex(hex,4);return[`0x${hexStr.slice(0,2)}`,`0x${hexStr.slice(2,4)}`]},checkSum=(data=[])=>{const sum=data.map(o=>parseInt(o,16)).reduce((a,c)=>a+c,0);let sumHex="0x"+decimalToHex(sum,2);return sumHex&=255,sumHex},generateCheckSum=data=>{const hex=checkSum(data);return[`0x${decimalToHex(hex,2)}`]},ab2decimalArr=buffer=>Array.prototype.map.call(new Uint8Array(buffer),bit=>bit),ab2hex=buffer=>Array.prototype.map.call(new Uint8Array(buffer),function(bit){return("00"+bit.toString(16)).slice(-2)}).join(""),arrayBufferToHexArray=(arrayBuffer,withPrefix=!0)=>Array.prototype.map.call(new Uint8Array(arrayBuffer),x=>{let hex=("00"+x.toString(16)).slice(-2);return withPrefix?`0x${hex}`:hex}),base64ToHexArray=(base64,withPrefix=!0)=>{const arrayBuffer=uni.base64ToArrayBuffer(base64);return arrayBufferToHexArray(arrayBuffer,withPrefix)},hexArrayToModuleArrayBuffer=(fields,hexArray,withCheck=!0,withPrefix=!0)=>{const fieldsLength=fields.length;let offset=fieldsLength+1;withCheck&&offset++;let bufferLength=hexArray.length+offset;const buffer=new ArrayBuffer(bufferLength),dataView=new DataView(buffer),lengthCode=decimalToHex(hexArray.length);fields.forEach((field,i)=>{dataView.setUint8(i,field)}),dataView.setUint8(fieldsLength,"0x"+lengthCode);let indexNum=fieldsLength+1;if(hexArray.forEach((el,index)=>{dataView.setUint8(indexNum,withPrefix?"0x"+el:el),indexNum+=1}),withCheck){const code=fields[2].toString(16);let check=generateCheckSum([code,lengthCode,...hexArray]);dataView.setUint8(bufferLength-1,check[0])}return buffer},getParamBaseValue=arr=>{const hexString=arr.map(el=>decimalToHex(el)).join("");return parseInt(hexString,16)},decimalToHex=(decimal,padding=2)=>Number(decimal).toString(16).padStart(padding,"0"),decimalToHex0x=(decimal,padding=2)=>"0x"+Number(decimal).toString(16).padStart(padding,"0"),hexToDecimal=hex=>parseInt(hex,16),hexArr2ab=hexArr=>{const buffer=new ArrayBuffer(hexArr.length),dataView=new DataView(buffer);return hexArr.forEach((hex,i)=>dataView.setUint8(i,hex)),buffer},hex2string=hex=>("00"+hex.toString(16)).slice(-2).toUpperCase(),string2hexArr=str=>{let hexArray=[];for(let i=0;i<str.length;i++){const charCode=str.charCodeAt(i).toString(16).padStart(2,"0");hexArray.push(charCode)}return hexArray},hexArr2Assic=(hexArr=[])=>String.fromCharCode(...hexArr).replace(/\u0000/g,""),hexStrAscii=hexString=>{let asciiString="";for(let i=0;i<hexString.length;i+=2){const hexPair=hexString.substr(i,2),decimalValue=parseInt(hexPair,16);asciiString+=String.fromCharCode(decimalValue)}return asciiString.replace(/\u0000/g,"")},hex2Ascii=(value=[])=>{const hexString=value.join("");return hexStrAscii(hexString)},hexArr2string=(hexArr=[],connector="")=>hexArr.map(o=>hex2string(o)).join(connector),hex2Binary=(hex,len=0)=>parseInt(hex,16).toString(2).padStart(len,"0"),extractBits=(number,start,end)=>number>>start&(1<<end-start+1)-1,sleep=(n=500)=>new Promise(r=>setTimeout(()=>r(!0),n)),decimalToTwoByteHexArray=decimal=>{if("number"!=typeof decimal||!Number.isInteger(decimal))throw new Error("输入必须为整数");if(decimal<0||decimal>65535)throw new Error("输入的十进制数超出 16 位无符号整数范围(0 - 65535)");return[`0x${`00${(decimal>>8).toString(16)}`.slice(-2)}`,`0x${`00${(255&decimal).toString(16)}`.slice(-2)}`]},stringToTwoHexArray=str=>{const paddedStr=str.padStart(4,"0");return[`0x${paddedStr.slice(0,2)}`,`0x${paddedStr.slice(2,4)}`]},hexStringToBinary=hexString=>parseInt(hexString,16).toString(2),fromBCD=bcd=>10*((bcd&=255)>>4&15)+(15&bcd),parseDateTime=str=>{const match=str.match(/^(\d{4})-(\d{1,2})-(\d{1,2})\s+(\d{1,2}):(\d{1,2}):(\d{1,2})$/);if(!match)return null;const[,y,m,d,h,i,s]=match.map(Number);return new Date(y,m-1,d,h,i,s).getTime()},isWithin30Minutes=timeStr=>{const now=Date.now(),targetTime=parseDateTime(timeStr);if(null===targetTime)return console.error("时间字符串格式错误:",timeStr),!1;return Math.abs(now-targetTime)>=18e5},toBCD=num=>{if(num<0||num>99)throw new Error("BCD only supports 0-99");return Math.floor(num/10)<<4|num%10};export{ab2decimalArr,ab2hex,arrayBufferToHexArray,base64ToHexArray,checkSum,crc16modbus,crcCheckSum,decimalToHex,decimalToHex0x,decimalToTwoByteHexArray,extractBits,fromBCD,generateCheckSum,generateCrc16modbusCheck,generateCrcCheckSum,getParamBaseValue,hex2Ascii,hex2Binary,hex2string,hexArr2Assic,hexArr2ab,hexArr2string,hexArrayToModuleArrayBuffer,hexStrAscii,hexStringToBinary,hexToDecimal,isWithin30Minutes,parseDateTime,sleep,string2hexArr,stringToTwoHexArray,toBCD};
@@ -1 +1 @@
1
- import{getOS}from"./commonfun.js";import{TelinkApi}from"./TelinkApi.js";import{BLE,Transfer}from"./Transfer.js";const max=BLE.PACKAGE_MAX_LENGTH,delayDefault=BLE.WRITE_DELAY,{isIOS:isIOS,isAndroid:isAndroid}=getOS();class OTAUpgrade{constructor({deviceId:deviceId,filePath:filePath,otaInfo:otaInfo,otaStart:otaStart,otaReStart:otaReStart,macAddr:macAddr,onProgress:onProgress,onSuccess:onSuccess,onError:onError,delay:delay,platform:platform="APP"}){this.deviceId=deviceId,this.filePath=filePath,this.otaInfo=otaInfo,this.otaStart=otaStart,this.otaReStart=otaReStart,this.macAddr=macAddr,this.platform=platform,this.isTeLink=!!TelinkApi.isTeLink&&TelinkApi.isTeLink(macAddr),this.onProgress=onProgress,this.onSuccess=onSuccess,this.onError=onError,this.delay=delay||delayDefault,this.fileHexArray=[],this.totalTimes=1,this.finishedTimes=0,this.succeed=!1,this.ready=!0,this.timer=null,this.s_progress=0,this.progressType="download"}async start(){this.progressType="download";try{await this.download()}catch(e){this.fail("下载失败: "+e.message)}}async download(){const that=this;return new Promise((resolve,reject)=>{const downloadTask=uni.downloadFile({url:that.filePath,success:({tempFilePath:tempFilePath})=>{that.resolve(tempFilePath).then(resolve).catch(reject)},fail:res=>{that.fail("固件下载失败"),reject(res)}});downloadTask.onProgressUpdate&&downloadTask.onProgressUpdate(({progress:progress})=>{that.onProgress&&that.onProgress({type:"download",percent:progress})})})}async resolve(tempFilePath){const that=this;return new Promise((resolve,reject)=>{uni.saveFile({tempFilePath:tempFilePath,success:({savedFilePath:savedFilePath})=>{if("APP"===this.platform)plus.io.resolveLocalFileSystemURL(savedFilePath,entry=>{entry.file(file=>{var fileReader=new plus.io.FileReader;fileReader.readAsDataURL(file),fileReader.onloadend=e=>{let base64=e.target.result.split(",")[1];const hexArray=Transfer.base64ToHexArray(base64),times=Math.ceil(hexArray.length/(that.isTeLink?16:max));that.fileHexArray=hexArray,that.totalTimes=times,that.finishedTimes=0,that.progressType="upgrade",that.isTeLink?that.telinkUpgrade():that.normalUpgrade(),resolve()},fileReader.onerror=e=>{that.fail("固件解析失败"),reject(e)}})},err=>{that.fail("固件保存失败"),reject(err)});else if("MP"===this.platform){wx.getFileSystemManager().readFile({filePath:savedFilePath,encoding:"base64",success:res=>{let base64=res.data;const hexArray=Transfer.base64ToHexArray(base64),times=Math.ceil(hexArray.length/(that.isTeLink?16:max));that.fileHexArray=hexArray,that.totalTimes=times,that.finishedTimes=0,that.progressType="upgrade",that.isTeLink?that.telinkUpgrade():that.normalUpgrade(),resolve()},fail:err=>{console.error("[OTA] resolve failed:",JSON.stringify(err)),that.failed("文件解析失败")}})}},fail:res=>{that.fail("固件保存失败"),reject(res)}})})}normalUpgrade(){setTimeout(()=>{BLE.writeATCmd(this.otaInfo,this.deviceId,this.fail.bind(this)),this.addBLECharValueChangeListener()},2600)}telinkUpgrade(){this.write(["0x00","0xff"],0)}write(pkg,type){const value=function(hexArr){const buffer=new ArrayBuffer(hexArr.length),dataView=new DataView(buffer);return hexArr.forEach((hex,i)=>dataView.setUint8(i,hex)),buffer}(pkg.map(o=>parseInt(o,16))),opt={deviceId:this.deviceId,serviceId:"00010203-0405-0607-0809-0a0b0c0d1912",characteristicId:"00010203-0405-0607-0809-0a0b0c0d2b12",value:value,success:()=>this.onSucceed(type),fail:async()=>{await this.sleep(2*this.delay),uni.writeBLECharacteristicValue({...opt,fail:async()=>{await this.sleep(2*this.delay),uni.writeBLECharacteristicValue({...opt,fail:this.fail.bind(this)})}})}};uni.writeBLECharacteristicValue(opt),isIOS&&setTimeout(()=>this.onSucceed(type),5)}onSucceed(type){0==type?this.write(["0x01","0xff"],1):1==type?this.sendNextOtaPacketCommand():2==type?(this.finishedTimes++,this.sendNextOtaPacketCommand()):3==type?this.sendNextOtaPacketCommand():4==type?this.sendOtaEndCommand():5==type&&(this.finishedTimes++,this.succeed=!0,this.onSuccess&&this.onSuccess()),this.onProgress&&this.onProgress({type:"upgrade",percent:Math.floor(100*this.finishedTimes/this.totalTimes)})}async sendNextOtaPacketCommand(){const i=this.finishedTimes,index=TelinkApi.getIndexHexArr(i);let pkgValue=this.fileHexArray.slice(16*i,16*(i+1));pkgValue.length<16&&(pkgValue=pkgValue.concat([...Array(16-pkgValue.length)].map(()=>"0xFF")));const crc=TelinkApi.genCheck([...index,...pkgValue]),pkg=[...index,...pkgValue,...crc],type=i>=this.totalTimes-1?4:2;await this.sleep(this.delay),this.write(pkg,type)}sendOtaEndCommand(){const pkgValue=function(i,c=65282){return[255&c,c>>8&255,255&i,i>>8&255,255&~i,~i>>8&255].map(o=>`0x${`00${o.toString(16)}`.slice(-2)}`.toUpperCase())}(this.totalTimes-1),crc=TelinkApi.genCheck([...pkgValue]),pkg=[...pkgValue,...crc];this.write(pkg,5)}addBLECharValueChangeListener(){const that=this;uni.notifyBLECharacteristicValueChange({deviceId:that.deviceId,serviceId:BLE.serviceId,characteristicId:BLE.readUUID,state:!0,success:()=>{},fail:()=>{}}),that.ready=!0,that.readValue=[],that.receiveLength=null,uni.onBLECharacteristicValueChange(({deviceId:deviceId,serviceId:serviceId,characteristicId:characteristicId,value:value})=>{if(that.ready&&deviceId==that.deviceId&&serviceId==BLE.serviceId){const intArr=Array.prototype.map.call(new Uint8Array(value),x=>x);intArr.length>0&&(null==that.receiveLength&&255==intArr[0]&&170==intArr[1]&&(that.receiveLength=intArr[3]+5),that.receiveLength?(that.readValue=that.readValue.concat(intArr),that.readValue.length==that.receiveLength&&(that.doWithResponse([...that.readValue]),that.readValue=[],that.receiveLength=null)):(that.readValue=[],that.receiveLength=null))}})}async doWithResponse(intArr){if(128==intArr[2]){let str=String.fromCharCode(...intArr.slice(4,-1));if(str.indexOf(this.otaInfo)>-1&&(this.finishedTimes=0,this.transferFirmwareFile()),str.indexOf(this.otaStart)>-1){if(str.toUpperCase().includes("ERROR"))return void this.fail(str);str.toUpperCase().indexOf("S100")>-1&&(this.succeed=!0,this.onSuccess&&this.onSuccess())}}80==intArr[2]&&(0==intArr[4]?(this.finishedTimes++,this.transferFirmwareFile()):this.transferFirmwareFile()),81==intArr[2]&&(0==intArr[4]?this.startOTA():this.fail("升级失败"))}transferFirmwareFile(){let nextTime=this.finishedTimes+1;if(nextTime>this.totalTimes){const pkg=[0];BLE.transferFirmwareFileCmd(this.deviceId,pkg,!0,this.fail.bind(this))}else{const pkg=this.fileHexArray.slice(this.finishedTimes*max,nextTime*max),index=Transfer.decimalToTwoByteHexArray(nextTime);BLE.transferFirmwareFileCmd(this.deviceId,index.concat(pkg),!1,this.fail.bind(this))}this.onProgress&&this.onProgress({type:"upgrade",percent:Math.floor(100*this.finishedTimes/this.totalTimes)})}async startOTA(){BLE.writeATCmd(this.otaStart,this.deviceId,this.fail.bind(this))}fail(msg){this.succeed=!1,this.onError&&this.onError(msg)}sleep(n=50){return new Promise(r=>setTimeout(()=>r(!0),n))}}export{OTAUpgrade,OTAUpgrade as default};
1
+ import{getOS}from"./commonfun.js";import{TelinkApi}from"./TelinkApi.js";import{BLE,Transfer}from"./Transfer.js";const max=BLE.PACKAGE_MAX_LENGTH,delayDefault=BLE.WRITE_DELAY,{isIOS:isIOS,isAndroid:isAndroid}=getOS();class OTAUpgrade{constructor({deviceId:deviceId,filePath:filePath,otaInfo:otaInfo,otaStart:otaStart,otaReStart:otaReStart,macAddr:macAddr,onProgress:onProgress,onSuccess:onSuccess,onError:onError,delay:delay,platform:platform="APP"}){this.deviceId=deviceId,this.filePath=filePath,this.otaInfo=otaInfo,this.otaStart=otaStart,this.otaReStart=otaReStart,this.macAddr=macAddr,this.platform=platform,this.isTeLink=!!TelinkApi.isTeLink&&TelinkApi.isTeLink({macAddr:macAddr}),this.onProgress=onProgress,this.onSuccess=onSuccess,this.onError=onError,this.delay=delay||delayDefault,this.fileHexArray=[],this.totalTimes=1,this.finishedTimes=0,this.succeed=!1,this.ready=!0,this.timer=null,this.s_progress=0,this.otaStarting=!1,this.progressType="download"}async start(){this.progressType="download";try{await this.download()}catch(e){this.fail("下载失败: "+e.message)}}async download(){const that=this;return new Promise((resolve,reject)=>{const downloadTask=uni.downloadFile({url:that.filePath,success:({tempFilePath:tempFilePath})=>{this.addBLECharValueChangeListener(),that.resolve(tempFilePath).then(resolve).catch(reject)},fail:res=>{that.fail("固件下载失败"),reject(res)}});downloadTask.onProgressUpdate&&downloadTask.onProgressUpdate(({progress:progress})=>{that.onProgress&&that.onProgress({type:"download",percent:progress})})})}async resolve(tempFilePath){const that=this;return new Promise((resolve,reject)=>{uni.saveFile({tempFilePath:tempFilePath,success:({savedFilePath:savedFilePath})=>{if("APP"===this.platform)plus.io.resolveLocalFileSystemURL(savedFilePath,entry=>{entry.file(file=>{var fileReader=new plus.io.FileReader;fileReader.readAsDataURL(file),fileReader.onloadend=e=>{let base64=e.target.result.split(",")[1];const hexArray=Transfer.base64ToHexArray(base64),times=Math.ceil(hexArray.length/(that.isTeLink?16:max));that.fileHexArray=hexArray,that.totalTimes=times,that.finishedTimes=0,that.progressType="upgrade",that.isTeLink?that.telinkUpgrade():that.normalUpgrade(),resolve()},fileReader.onerror=e=>{that.fail("固件解析失败"),reject(e)}})},err=>{that.fail("固件保存失败"),reject(err)});else if("MP"===this.platform){wx.getFileSystemManager().readFile({filePath:savedFilePath,encoding:"base64",success:res=>{let base64=res.data;const hexArray=Transfer.base64ToHexArray(base64),times=Math.ceil(hexArray.length/(that.isTeLink?16:max));that.fileHexArray=hexArray,that.totalTimes=times,that.finishedTimes=0,that.progressType="upgrade",that.isTeLink?that.telinkUpgrade():that.normalUpgrade(),resolve()},fail:err=>{console.error("[OTA] resolve failed:",JSON.stringify(err)),that.failed("文件解析失败")}})}},fail:res=>{that.fail("固件保存失败"),reject(res)}})})}normalUpgrade(){setTimeout(()=>{BLE.writeATCmd(this.otaInfo,this.deviceId,this.fail.bind(this))},2600)}telinkUpgrade(){this.write(["0x00","0xff"],0)}write(pkg,type){const value=function(hexArr){const buffer=new ArrayBuffer(hexArr.length),dataView=new DataView(buffer);return hexArr.forEach((hex,i)=>dataView.setUint8(i,hex)),buffer}(pkg.map(o=>parseInt(o,16))),opt={deviceId:this.deviceId,serviceId:"00010203-0405-0607-0809-0a0b0c0d1912",characteristicId:"00010203-0405-0607-0809-0a0b0c0d2b12",value:value,success:()=>this.onSucceed(type),fail:async()=>{await this.sleep(2*this.delay),uni.writeBLECharacteristicValue({...opt,fail:async()=>{await this.sleep(2*this.delay),uni.writeBLECharacteristicValue({...opt,fail:this.fail.bind(this)})}})}};uni.writeBLECharacteristicValue(opt),isIOS&&setTimeout(()=>this.onSucceed(type),5)}onSucceed(type){0==type?this.write(["0x01","0xff"],1):1==type?this.sendNextOtaPacketCommand():2==type?(this.finishedTimes++,this.sendNextOtaPacketCommand()):3==type?this.sendNextOtaPacketCommand():4==type?this.sendOtaEndCommand():5==type&&(this.finishedTimes++,this.succeed=!0,this.onSuccess&&this.onSuccess()),this.onProgress&&this.onProgress({type:"upgrade",percent:Math.floor(100*this.finishedTimes/this.totalTimes)})}async sendNextOtaPacketCommand(){const i=this.finishedTimes,index=TelinkApi.getIndexHexArr(i);let pkgValue=this.fileHexArray.slice(16*i,16*(i+1));pkgValue.length<16&&(pkgValue=pkgValue.concat([...Array(16-pkgValue.length)].map(()=>"0xFF")));const crc=TelinkApi.genCheck([...index,...pkgValue]),pkg=[...index,...pkgValue,...crc],type=i>=this.totalTimes-1?4:2;await this.sleep(this.delay),this.write(pkg,type)}sendOtaEndCommand(){const pkgValue=function(i,c=65282){return[255&c,c>>8&255,255&i,i>>8&255,255&~i,~i>>8&255].map(o=>`0x${`00${o.toString(16)}`.slice(-2)}`.toUpperCase())}(this.totalTimes-1),crc=TelinkApi.genCheck([...pkgValue]),pkg=[...pkgValue,...crc];this.write(pkg,5)}addBLECharValueChangeListener(){console.log("添加蓝牙特征值变化监听");const that=this;uni.notifyBLECharacteristicValueChange({deviceId:that.deviceId,serviceId:BLE.serviceId,characteristicId:BLE.readUUID,state:!0,success:()=>{},fail:()=>{}}),that.ready=!0,that.readValue=[],that.receiveLength=null,uni.onBLECharacteristicValueChange(({deviceId:deviceId,serviceId:serviceId,characteristicId:characteristicId,value:value})=>{if(that.ready&&deviceId==that.deviceId&&serviceId==BLE.serviceId){const intArr=Array.prototype.map.call(new Uint8Array(value),x=>x);intArr.length>0&&(null==that.receiveLength&&255==intArr[0]&&170==intArr[1]&&(that.receiveLength=intArr[3]+5),that.receiveLength?(that.readValue=that.readValue.concat(intArr),that.readValue.length==that.receiveLength&&(that.doWithResponse([...that.readValue]),that.readValue=[],that.receiveLength=null)):(that.readValue=[],that.receiveLength=null))}})}async doWithResponse(intArr){if(console.log("收到设备响应: ",intArr[2]),128==intArr[2]){let str=String.fromCharCode(...intArr.slice(4,-1));if(console.log("doWithResponse otaStart1",str),str.indexOf(this.otaInfo)>-1&&(this.finishedTimes=0,this.transferFirmwareFile()),str.indexOf(this.otaStart)>-1||this.otaStarting){if(str.indexOf(this.otaStart)>-1&&(this.otaStarting=!0),console.log("doWithResponse otaStart2",str),str.toUpperCase().includes("ERROR"))return void this.fail(str);str.toUpperCase().indexOf("S100")>-1&&(this.succeed=!0,this.onSuccess&&this.onSuccess())}}80==intArr[2]&&(0==intArr[4]?(this.finishedTimes++,this.transferFirmwareFile()):this.transferFirmwareFile()),81==intArr[2]&&(0==intArr[4]?this.startOTA():this.fail("升级失败"))}transferFirmwareFile(){let nextTime=this.finishedTimes+1;if(nextTime>this.totalTimes){const pkg=[0];BLE.transferFirmwareFileCmd(this.deviceId,pkg,!0,this.fail.bind(this)),console.log("[OTA]","=== Send 51 ===",this.finishedTimes,this.totalTimes,pkg)}else{const pkg=this.fileHexArray.slice(this.finishedTimes*max,nextTime*max),index=Transfer.decimalToTwoByteHexArray(this.finishedTimes);BLE.transferFirmwareFileCmd(this.deviceId,index.concat(pkg),!1,this.fail.bind(this)),console.log("[OTA]",`S50-${this.finishedTimes}/${this.totalTimes}`)}this.onProgress&&this.onProgress({type:"upgrade",percent:Math.floor(100*this.finishedTimes/this.totalTimes)})}async startOTA(){BLE.writeATCmd(this.otaStart,this.deviceId,this.fail.bind(this))}fail(msg){this.succeed=!1,this.onError&&this.onError(msg)}sleep(n=50){return new Promise(r=>setTimeout(()=>r(!0),n))}}export{OTAUpgrade,OTAUpgrade as default};
@@ -1 +1 @@
1
- import{getOS}from"./commonfun.js";const Transfer={hexStringToBinary:hexString=>parseInt(hexString,16).toString(2),inArray(arr,key,val){for(let i=0;i<arr.length;i++)if(arr[i][key]===val)return i;return-1},decimalToHex(decimal,padding=2){const hexDigits=[],hexMap={10:"A",11:"B",12:"C",13:"D",14:"E",15:"F"};for(;decimal>0;){const remainder=decimal%16;remainder>=10?hexDigits.unshift(hexMap[remainder]):hexDigits.unshift(`${remainder}`),decimal=Math.floor(decimal/16)}return hexDigits.join("").padStart(padding,"0")},decimalToHexArray(decimal,padding=2){const inputHex=this.decimalToHex(decimal,padding);return[("0"+inputHex.slice(-4,-2)).slice(-2),("0"+inputHex.slice(-2)).slice(-2)].map(o=>`0x${o}`)},hexToDecimal(hex){let decimal=0;const hexMap={A:10,B:11,C:12,D:13,E:14,F:15};for(let i=0;i<hex.length;i++){const currentDigit=hex[i];decimal=hexMap.hasOwnProperty(currentDigit)?16*decimal+hexMap[currentDigit]:16*decimal+parseFloat(currentDigit,16)}return decimal},arrayBufferToHex(arrayBuffer){return this.arrayBufferToHexArray(arrayBuffer,!1).join("")},arrayBufferToHexArray:(arrayBuffer,withPrefix=!0)=>Array.prototype.map.call(new Uint8Array(arrayBuffer),x=>{let hex=("00"+x.toString(16)).slice(-2);return withPrefix?`0x${hex}`:hex}),areArraysEqual:(arr1,arr2)=>arr1.length===arr2.length&&arr1.every((value,index)=>value===arr2[index]),convertASCIItoHex(asciiVal){let asciiCode=asciiVal.charCodeAt(0);return this.decimalToHex(asciiCode)},getParamCheck(content){let sum=0;for(let i=0;i<content.length;i++)sum+=255&content[i];return sum^=65535,sum+=1,sum=this.decimalToHex(sum),{check1:"0x"+sum.substr(0,2),check2:"0x"+sum.substr(2,2)}},splitNumberToHexArray(decimalNumber){let hexString=decimalNumber.toString(16);hexString=hexString.length%2==0?hexString:"0"+hexString;let hexArray=hexString.match(/.{1,2}/g);for(;hexArray.length<2;)hexArray.unshift("00");return hexArray.map(hex=>"0x"+hex)},base64ToHexArray(base64,withPrefix=!0){const arrayBuffer=uni.base64ToArrayBuffer(base64);return this.arrayBufferToHexArray(arrayBuffer,withPrefix)},decimalToTwoByteHexArray:decimal=>[`0x${("00"+(decimal>>8)).slice(-2)}`,`0x${`00${(255&decimal).toString(16)}`.slice(-2)}`],stringToHexArray(str){const hexArray=[];for(let i=0;i<str.length;i++){let charCode=str.charCodeAt(i).toString(16);charCode=1===charCode.length?"0"+charCode:charCode,hexArray.push(charCode)}return hexArray},getAtValueCheck(cmdCode,lengthCode,hexArray){let sum=0;return hexArray.forEach(hexValue=>{sum+=parseInt(hexValue,16)}),this.getCheck(cmdCode,lengthCode,sum)},getCheck(cmdCode,lengthCode,sum){let checkSum=this.hexToDecimal(cmdCode)+this.hexToDecimal(lengthCode)+sum,codeHex="0x"+this.decimalToHex(checkSum);return codeHex&=255,"0x"+this.decimalToHex(codeHex)},hexArrayToModuleArrayBuffer(fields,hexArray,withCheck=!0,withPrefix=!0){const fieldsLength=fields.length;let offset=fieldsLength+1;withCheck&&offset++;let bufferLength=hexArray.length+offset;const buffer=new ArrayBuffer(bufferLength),dataView=new DataView(buffer),lengthCode=this.decimalToHex(hexArray.length);fields.forEach((field,i)=>{dataView.setUint8(i,field)}),dataView.setUint8(fieldsLength,"0x"+lengthCode);let indexNum=fieldsLength+1;if(hexArray.forEach((el,index)=>{dataView.setUint8(indexNum,withPrefix?"0x"+el:el),indexNum+=1}),withCheck){const code=fields[2].toString(16);let check=this.getAtValueCheck(code,lengthCode,hexArray);dataView.setUint8(bufferLength-1,check)}return buffer}},TAG="[BLE_OTA]",BLE={serviceId:"0000FF00-0000-1000-8000-00805F9B34FB",writeUUID:"0000FF02-0000-1000-8000-00805F9B34FB",readUUID:"0000FF01-0000-1000-8000-00805F9B34FB",TAG:"[BLE_OTA]",WRITE_DELAY:25,PACKAGE_MAX_LENGTH:240,sendMsgToKey(buffer,deviceId,fail){getOS();console.log(TAG,`大包数据: Len=${buffer.byteLength} writeType=writeNoResponse`),console.log(TAG,"写入中..."),uni.writeBLECharacteristicValue({deviceId:deviceId,serviceId:"0000FF00-0000-1000-8000-00805F9B34FB",characteristicId:"0000FF02-0000-1000-8000-00805F9B34FB",value:buffer,writeType:"writeNoResponse",success:()=>{console.log(TAG,"写入成功")},fail:res=>{console.log(TAG,"Error-写入失败"),fail?.(JSON.stringify(res))}})},sendDelay:(delay,buffer)=>new Promise((resolve,reject)=>{setTimeout(()=>resolve(buffer),delay)}),sendMsg(deviceId,value,fail){uni.writeBLECharacteristicValue({deviceId:deviceId,serviceId:this.serviceId,characteristicId:this.writeUUID,value:value,writeType:"writeNoResponse",success:res=>{console.log("[OTA] sendMsg succeed")},fail:res=>{console.error("[OTA] sendMsg failed",JSON.stringify(res)),fail?.(JSON.stringify(res))}})},sendMsgDelay(delay,deviceId,value,fail){return new Promise((resolve,reject)=>{setTimeout(()=>{uni.writeBLECharacteristicValue({deviceId:deviceId,serviceId:this.serviceId,characteristicId:this.writeUUID,value:value,writeType:"writeNoResponse",success:res=>{resolve(!0)},fail:res=>{console.error("[OTA] sendMsg failed",JSON.stringify(res)),resolve(!1)}})},delay)})},retryWarpper(asyncFunc,defaultRetryTime=2,retryInterval=20){let retryTime=defaultRetryTime;const retryCallback=async function(...args){try{return await asyncFunc(...args)}catch(e){if(retryTime<=0)throw e;return console.log(`写入失败,将在 ${retryInterval} 毫秒后重试,剩余重试次数 ${retryTime}`),retryTime-=1,await new Promise(reslove=>setTimeout(reslove,retryInterval)),await retryCallback(...args)}};return retryCallback},write(buffer,deviceId,delay=20){return console.log("write",deviceId,buffer.byteLength),new Promise((resolve,reject)=>setTimeout(()=>{uni.writeBLECharacteristicValue({deviceId:deviceId,serviceId:this.serviceId,characteristicId:this.writeUUID,value:buffer,writeType:"writeNoResponse",success:res=>{resolve("ok")},fail:res=>{reject(JSON.stringify(res))}})},delay))},async loopSendMsg(buffer,deviceId,fail){console.log("loopSendMsg",deviceId,buffer.byteLength);let _this=this;const fetchDataWithRetry=_this.retryWarpper(_this.write);let bytes=buffer.byteLength,pos=0;for(;bytes>0;){let endPos=bytes>20?pos+20:pos+bytes;const tempBuffer=buffer.slice(pos,endPos);pos+=20,bytes-=20;if(!await fetchDataWithRetry(tempBuffer,deviceId,_this.WRITE_DELAY).catch(e=>fail?.(e)))break}},writeATCmd(atValue,deviceId,fail){const hexArray=Transfer.stringToHexArray(atValue+"\r\n");let ab=Transfer.hexArrayToModuleArrayBuffer([255,170,128],hexArray,!0,!0);this.sendMsgToKey(ab,deviceId,fail)},transferFirmwareFileCmd(deviceId,hexArray,isEnd=!1,fail){let ab=Transfer.hexArrayToModuleArrayBuffer([255,170,isEnd?81:80],hexArray,!0,!1);this.sendMsgToKey(ab,deviceId,fail)},formatOTAContent(content){if(""!=content){const[_otaInfo,otaStart,otaReStart]=content.split(";"),[p1,p2,p3,filePath]=_otaInfo.split(",");return{filePath:filePath,otaInfo:_otaInfo.replace(filePath,"local"),otaStart:otaStart,otaReStart:otaReStart}}return null}};class Observer{constructor(exec){this.listeners=new Set,exec({next:value=>this.listeners.forEach(({next:next})=>next&&next(value)),error:err=>this.listeners.forEach(({error:error})=>error&&error(err)),complete:value=>this.listeners.forEach(({complete:complete})=>complete&&complete(value))})}subscribe(listeners){return this.listeners.add(listeners),{unsubscribe:()=>this.listeners.delete(listeners)}}}class Logger{key;temp;constructor(key){this.key=key,this.temp={}}log(...args){console.log(this.key,"[OTA] ",...args)}error(...args){console.error(this.key,"[OTA] ",...args)}time(key){const obj=this.temp;obj.hasOwnProperty(key)&&this.error(`Timer '${key}' already exists`),obj[key]=(new Date).getTime()}timeEnd(key){const obj=this.temp;if(!obj.hasOwnProperty(key))return void this.error(`Timer '${key}' does not exist`);let s=obj[key],e=(new Date).getTime();return this.log(`${key}: ${e-s}ms`),delete obj[key],e-s}}export{BLE,Logger,Observer,Transfer,Transfer as default};
1
+ import{getOS}from"./commonfun.js";const Transfer={hexStringToBinary:hexString=>parseInt(hexString,16).toString(2),inArray(arr,key,val){for(let i=0;i<arr.length;i++)if(arr[i][key]===val)return i;return-1},decimalToHex(decimal,padding=2){const hexDigits=[],hexMap={10:"A",11:"B",12:"C",13:"D",14:"E",15:"F"};for(;decimal>0;){const remainder=decimal%16;remainder>=10?hexDigits.unshift(hexMap[remainder]):hexDigits.unshift(`${remainder}`),decimal=Math.floor(decimal/16)}return hexDigits.join("").padStart(padding,"0")},decimalToHexArray(decimal,padding=2){const inputHex=this.decimalToHex(decimal,padding);return[("0"+inputHex.slice(-4,-2)).slice(-2),("0"+inputHex.slice(-2)).slice(-2)].map(o=>`0x${o}`)},hexToDecimal(hex){let decimal=0;const hexMap={A:10,B:11,C:12,D:13,E:14,F:15};for(let i=0;i<hex.length;i++){const currentDigit=hex[i];decimal=hexMap.hasOwnProperty(currentDigit)?16*decimal+hexMap[currentDigit]:16*decimal+parseFloat(currentDigit,16)}return decimal},arrayBufferToHex(arrayBuffer){return this.arrayBufferToHexArray(arrayBuffer,!1).join("")},arrayBufferToHexArray:(arrayBuffer,withPrefix=!0)=>Array.prototype.map.call(new Uint8Array(arrayBuffer),x=>{let hex=("00"+x.toString(16)).slice(-2);return withPrefix?`0x${hex}`:hex}),areArraysEqual:(arr1,arr2)=>arr1.length===arr2.length&&arr1.every((value,index)=>value===arr2[index]),convertASCIItoHex(asciiVal){let asciiCode=asciiVal.charCodeAt(0);return this.decimalToHex(asciiCode)},getParamCheck(content){let sum=0;for(let i=0;i<content.length;i++)sum+=255&content[i];return sum^=65535,sum+=1,sum=this.decimalToHex(sum),{check1:"0x"+sum.substr(0,2),check2:"0x"+sum.substr(2,2)}},splitNumberToHexArray(decimalNumber){let hexString=decimalNumber.toString(16);hexString=hexString.length%2==0?hexString:"0"+hexString;let hexArray=hexString.match(/.{1,2}/g);for(;hexArray.length<2;)hexArray.unshift("00");return hexArray.map(hex=>"0x"+hex)},base64ToHexArray(base64,withPrefix=!0){const arrayBuffer=uni.base64ToArrayBuffer(base64);return this.arrayBufferToHexArray(arrayBuffer,withPrefix)},decimalToTwoByteHexArray:decimal=>[`0x${("00"+(decimal>>8)).slice(-2)}`,`0x${`00${(255&decimal).toString(16)}`.slice(-2)}`],stringToHexArray(str){const hexArray=[];for(let i=0;i<str.length;i++){let charCode=str.charCodeAt(i).toString(16);charCode=1===charCode.length?"0"+charCode:charCode,hexArray.push(charCode)}return hexArray},getAtValueCheck(cmdCode,lengthCode,hexArray){let sum=0;return hexArray.forEach(hexValue=>{sum+=parseInt(hexValue,16)}),this.getCheck(cmdCode,lengthCode,sum)},getCheck(cmdCode,lengthCode,sum){let checkSum=this.hexToDecimal(cmdCode)+this.hexToDecimal(lengthCode)+sum,codeHex="0x"+this.decimalToHex(checkSum);return codeHex&=255,"0x"+this.decimalToHex(codeHex)},hexArrayToModuleArrayBuffer(fields,hexArray,withCheck=!0,withPrefix=!0){const fieldsLength=fields.length;let offset=fieldsLength+1;withCheck&&offset++;let bufferLength=hexArray.length+offset;const buffer=new ArrayBuffer(bufferLength),dataView=new DataView(buffer),lengthCode=this.decimalToHex(hexArray.length);fields.forEach((field,i)=>{dataView.setUint8(i,field)}),dataView.setUint8(fieldsLength,"0x"+lengthCode);let indexNum=fieldsLength+1;if(hexArray.forEach((el,index)=>{dataView.setUint8(indexNum,withPrefix?"0x"+el:el),indexNum+=1}),withCheck){const code=fields[2].toString(16);let check=this.getAtValueCheck(code,lengthCode,hexArray);dataView.setUint8(bufferLength-1,check)}return buffer}},TAG="[BLE_OTA]",BLE={serviceId:"0000FF00-0000-1000-8000-00805F9B34FB",writeUUID:"0000FF02-0000-1000-8000-00805F9B34FB",readUUID:"0000FF01-0000-1000-8000-00805F9B34FB",TAG:"[BLE_OTA]",WRITE_DELAY:25,PACKAGE_MAX_LENGTH:237,sendMsgToKey(buffer,deviceId,fail){getOS();console.log(TAG,`大包数据: Len=${buffer.byteLength} writeType=writeNoResponse`),console.log(TAG,"写入中..."),uni.writeBLECharacteristicValue({deviceId:deviceId,serviceId:"0000FF00-0000-1000-8000-00805F9B34FB",characteristicId:"0000FF02-0000-1000-8000-00805F9B34FB",value:buffer,writeType:"writeNoResponse",success:()=>{console.log(TAG,"写入成功")},fail:res=>{console.log(TAG,"Error-写入失败"),fail?.(JSON.stringify(res))}})},sendDelay:(delay,buffer)=>new Promise((resolve,reject)=>{setTimeout(()=>resolve(buffer),delay)}),sendMsg(deviceId,value,fail){uni.writeBLECharacteristicValue({deviceId:deviceId,serviceId:this.serviceId,characteristicId:this.writeUUID,value:value,writeType:"writeNoResponse",success:res=>{console.log("[OTA] sendMsg succeed")},fail:res=>{console.error("[OTA] sendMsg failed",JSON.stringify(res)),fail?.(JSON.stringify(res))}})},sendMsgDelay(delay,deviceId,value,fail){return new Promise((resolve,reject)=>{setTimeout(()=>{uni.writeBLECharacteristicValue({deviceId:deviceId,serviceId:this.serviceId,characteristicId:this.writeUUID,value:value,writeType:"writeNoResponse",success:res=>{resolve(!0)},fail:res=>{console.error("[OTA] sendMsg failed",JSON.stringify(res)),resolve(!1)}})},delay)})},retryWarpper(asyncFunc,defaultRetryTime=2,retryInterval=20){let retryTime=defaultRetryTime;const retryCallback=async function(...args){try{return await asyncFunc(...args)}catch(e){if(retryTime<=0)throw e;return console.log(`写入失败,将在 ${retryInterval} 毫秒后重试,剩余重试次数 ${retryTime}`),retryTime-=1,await new Promise(reslove=>setTimeout(reslove,retryInterval)),await retryCallback(...args)}};return retryCallback},write(buffer,deviceId,delay=20){return console.log("write",deviceId,buffer.byteLength),new Promise((resolve,reject)=>setTimeout(()=>{uni.writeBLECharacteristicValue({deviceId:deviceId,serviceId:this.serviceId,characteristicId:this.writeUUID,value:buffer,writeType:"writeNoResponse",success:res=>{resolve("ok")},fail:res=>{reject(JSON.stringify(res))}})},delay))},async loopSendMsg(buffer,deviceId,fail){console.log("loopSendMsg",deviceId,buffer.byteLength);let _this=this;const fetchDataWithRetry=_this.retryWarpper(_this.write);let bytes=buffer.byteLength,pos=0;for(;bytes>0;){let endPos=bytes>20?pos+20:pos+bytes;const tempBuffer=buffer.slice(pos,endPos);pos+=20,bytes-=20;if(!await fetchDataWithRetry(tempBuffer,deviceId,_this.WRITE_DELAY).catch(e=>fail?.(e)))break}},writeATCmd(atValue,deviceId,fail){const hexArray=Transfer.stringToHexArray(atValue+"\r\n");let ab=Transfer.hexArrayToModuleArrayBuffer([255,170,128],hexArray,!0,!0);this.sendMsgToKey(ab,deviceId,fail)},transferFirmwareFileCmd(deviceId,hexArray,isEnd=!1,fail){let ab=Transfer.hexArrayToModuleArrayBuffer([255,170,isEnd?81:80],hexArray,!0,!1);this.sendMsgToKey(ab,deviceId,fail)},formatOTAContent(content){if(""!=content){const[_otaInfo,otaStart,otaReStart]=content.split(";"),[p1,p2,p3,filePath]=_otaInfo.split(",");return{filePath:filePath,otaInfo:_otaInfo.replace(filePath,"local"),otaStart:otaStart,otaReStart:otaReStart}}return null}};class Observer{constructor(exec){this.listeners=new Set,exec({next:value=>this.listeners.forEach(({next:next})=>next&&next(value)),error:err=>this.listeners.forEach(({error:error})=>error&&error(err)),complete:value=>this.listeners.forEach(({complete:complete})=>complete&&complete(value))})}subscribe(listeners){return this.listeners.add(listeners),{unsubscribe:()=>this.listeners.delete(listeners)}}}class Logger{key;temp;constructor(key){this.key=key,this.temp={}}log(...args){console.log(this.key,"[OTA] ",...args)}error(...args){console.error(this.key,"[OTA] ",...args)}time(key){const obj=this.temp;obj.hasOwnProperty(key)&&this.error(`Timer '${key}' already exists`),obj[key]=(new Date).getTime()}timeEnd(key){const obj=this.temp;if(!obj.hasOwnProperty(key))return void this.error(`Timer '${key}' does not exist`);let s=obj[key],e=(new Date).getTime();return this.log(`${key}: ${e-s}ms`),delete obj[key],e-s}}export{BLE,Logger,Observer,Transfer,Transfer as default};
@@ -1 +1 @@
1
- function isEmpty(v){return null==v||""===v}function isNotEmpty(v){return!isEmpty(v)}function inArray(arr,key,val){for(let i=0;i<arr.length;i++)if(arr[i][key]===val)return i;return-1}function formatTimeHHmm(hours){const hour=Math.floor(hours),minute=Math.floor(60*(hours-hour));return console.log("H5环境"),`${hour}H:${minute}m`}function getOS(){const os=uni.getSystemInfoSync()?.osName;return{isIOS:"ios"==os,isAndroid:"android"==os}}function getPlatform(){return uni.getSystemInfoSync()?.uniPlatform||""}const eventBus={events:{},on(event,callback){this.events[event]||(this.events[event]=[]),this.events[event].push(callback)},off(event,callback){this.events[event]&&(callback?(this.events[event]=this.events[event].filter(cb=>cb!==callback),0===this.events[event].length&&delete this.events[event]):delete this.events[event])},emit(event,...args){this.events[event]&&this.events[event].forEach(callback=>callback(...args))}};export{eventBus,formatTimeHHmm,getOS,getPlatform,inArray,isEmpty,isNotEmpty};
1
+ function isEmpty(v){return null==v||""===v}function isNotEmpty(v){return!isEmpty(v)}function inArray(arr,key,val){for(let i=0;i<arr.length;i++)if(arr[i][key]===val)return i;return-1}function formatTimeHHmm(hours){const hour=Math.floor(hours),minute=Math.floor(60*(hours-hour));return console.log("H5环境"),`${hour}H:${minute}m`}function getOS(){const os=uni.getSystemInfoSync()?.osName;return{isIOS:"ios"==os,isAndroid:"android"==os||"openharmonyos"==os,isHarmony:"harmony"===os||"openharmonyos"===os}}function getPlatform(){return uni.getSystemInfoSync()?.uniPlatform||""}const eventBus={events:{},on(event,callback){this.events[event]||(this.events[event]=[]),this.events[event].push(callback)},off(event,callback){this.events[event]&&(callback?(this.events[event]=this.events[event].filter(cb=>cb!==callback),0===this.events[event].length&&delete this.events[event]):delete this.events[event])},emit(event,...args){this.events[event]&&this.events[event].forEach(callback=>callback(...args))}};export{eventBus,formatTimeHHmm,getOS,getPlatform,inArray,isEmpty,isNotEmpty};
@@ -1 +1 @@
1
- const batteryInfoJson=[{key:"barCode",paramNo:88,paramLength:32,oldParamNo:"0xA2"},{key:"manufacturer",paramNo:56,oldParamNo:"0xA0",paramLength:32},{key:"producedDate",paramNo:5,oldParamNo:"0x15",paramLength:2},{key:"model",paramNo:158,oldParamNo:"",paramLength:24},{key:"bmsModel",paramNo:176,oldParamNo:"",paramLength:16},{key:"bmsAddr",paramNo:170,oldParamNo:"",paramLength:12}],capInfoJson=[{key:"normCap",paramNo:0,oldParamNo:"0x10",paramLength:2},{key:"cycleCap",paramNo:1,oldParamNo:"0x11",paramLength:2},{key:"fullCap",paramNo:112,oldParamNo:"",paramLength:2}],voltageInfoJson=[{key:"allOvervoltageProtect",value:"",newValue:"",unit:"V",paramNo:16,oldParamNo:"0x20",paramLength:2},{key:"allOverpressureRecovery",value:"",newValue:"",unit:"V",paramNo:17,oldParamNo:"0x21",paramLength:2},{key:"allLowvoltageProtect",value:"",newValue:"",unit:"V",paramNo:18,oldParamNo:"0x22",paramLength:2},{key:"allLowvoltageRecover",value:"",newValue:"",unit:"V",paramNo:19,oldParamNo:"0x23",paramLength:2},{key:"singleOvervoltageProtect",value:"",newValue:"",unit:"V",paramNo:20,oldParamNo:"0x24",paramLength:2},{key:"singleOverpressureRecovery",value:"",newValue:"",unit:"V",paramNo:21,oldParamNo:"0x25",paramLength:2},{key:"singleLowvoltageProtect",value:"",newValue:"",unit:"V",paramNo:22,oldParamNo:"0x26",paramLength:2},{key:"singleLowvoltageRecover",value:"",newValue:"",unit:"V",paramNo:23,oldParamNo:"0x27",paramLength:2},{key:"allLowvoltageDelay",value:"",newValue:"",unit:"S",paramNo:48,oldParamNo:"0x3C",paramLength:2},{key:"allOverpressureDelay",value:"",newValue:"",unit:"S",paramNo:49,oldParamNo:"",paramLength:2},{key:"singleLowvoltageDelayed",value:"",newValue:"",unit:"S",paramNo:50,oldParamNo:"0x3d",paramLength:2},{key:"singleOverpressureDelay",value:"",newValue:"",unit:"S",paramNo:51,oldParamNo:"",paramLength:2},{key:"hardwareOV",value:null,newValue:"",unit:"V",paramNo:38,oldParamNo:"0x36",paramLength:2},{key:"hardwareUV",value:null,newValue:"",unit:"V",paramNo:39,oldParamNo:"0x37",paramLength:2}],currentInfoJson=[{value:"",newValue:"",unit:"A",paramNo:24,oldParamNo:"0x28",paramLength:2,key:"occhg"},{value:"",newValue:"",unit:"A",paramNo:25,oldParamNo:"0x29",paramLength:2,key:"dischargeOvercurrentProtect"},{value:"",newValue:"",unit:"S",paramNo:52,oldParamNo:"0x3E",paramLength:2,key:"chargeOvercurrentDelay"},{value:"",newValue:"",unit:"S",paramNo:53,oldParamNo:"",paramLength:2,key:"chargeOvercurrentRecoverDelay"},{value:"",newValue:"",unit:"S",paramNo:54,oldParamNo:"0x3F",paramLength:2,key:"dischargeOvercurrentDelay"},{value:"",newValue:"",unit:"S",paramNo:55,oldParamNo:"",paramLength:2,key:"dischargeOvercurrentRecoverDelay"},{value:null,newValue:"",unit:"(mV)",paramNo2:"1012",paramNo:40,oldParamNo:"0x38",paramLength:2,method:!0,key:"level2OvercurrentProtect"},{value:null,newValue:"",unit:"(mS)",paramNo2:"1013",paramNo:40,oldParamNo:"",paramLength:2,method:!0,key:"leve2OvercurrentDelay"},{checked:!1,isSwitch:!0,paramNo2:"1016",paramNo:41,oldParamNo:"",paramLength:2,key:"level2OvercurrentProtectV"},{value:null,newValue:"",unit:"(mV)",paramNo2:"1014",paramNo:41,oldParamNo:"",paramLength:2,method:!0,key:"shortcircuiProtect"},{value:null,newValue:"",unit:"(uS)",paramNo2:"1015",paramNo:41,oldParamNo:"",paramLength:2,method:!0,key:"shortcircuiProtectDelay"},{value:"",newValue:"",unit:"S",paramNo:43,oldParamNo:"0x39",paramLength:2,key:"shortcircuiProtectRecoverDelay",divisor:1}],tempInfoJson=[{value:"",newValue:"",unit:"℃",paramNo:8,oldParamNo:"0x18",paramLength:2,key:"chargeHightempProtect"},{value:"",newValue:"",unit:"℃",paramNo:9,oldParamNo:"0x19",paramLength:2,key:"chargeHightempRecover"},{value:"",newValue:"",unit:"℃",paramNo:10,oldParamNo:"0x1A",paramLength:2,key:"chargeLowtempProtect"},{value:"",newValue:"",unit:"℃",paramNo:11,oldParamNo:"0x1B",paramLength:2,key:"chargeLowtempRecover"},{value:"",newValue:"",unit:"℃",paramNo:12,oldParamNo:"0x1C",paramLength:2,key:"dischargingHightempProtect"},{value:"",newValue:"",unit:"℃",paramNo:13,oldParamNo:"0x1D",paramLength:2,key:"dischargingHightempRecover"},{value:"",newValue:"",unit:"℃",paramNo:14,oldParamNo:"0x1E",paramLength:2,key:"dischargingLowtempProtect"},{value:"",newValue:"",unit:"℃",paramNo:15,oldParamNo:"0x1F",paramLength:2,key:"dischargingLowtempRecover"},{value:"",newValue:"",unit:"S",paramNo:44,oldParamNo:"0x3A",paramLength:2,key:"chargeLowtempDelay"},{value:"",newValue:"",unit:"S",paramNo:45,oldParamNo:"",paramLength:2,key:"chargeHightempDelay"},{value:"",newValue:"",unit:"S",paramNo:46,oldParamNo:"0x3B",paramLength:2,key:"dischargingLowtempDelay"},{value:"",newValue:"",unit:"S",paramNo:47,oldParamNo:"",paramLength:2,key:"dischargingHightempDelay"}],equalizerFunJson=[{value:"",newValue:"",unit:"V",paramNo:26,oldParamNo:"0x2A",paramLength:2,key:"equalizingVoltage"},{value:"",newValue:"",unit:"V",paramNo:27,oldParamNo:"0x2B",paramLength:2,key:"accuracyEqualization"}],capVolInfoJson=[{value:null,newValue:"",unit:"V",paramNo:2,oldParamNo:"0x12",paramLength:2,isHidden:!1,key:"fullVolt"},{value:null,newValue:"",unit:"V",paramNo:3,oldParamNo:"0x13",paramLength:2,isHidden:!1,key:"emptyVolt"},{name:"容量80%",value:"",newValue:"",unit:"V",paramNo:34,oldParamNo:"0x32",paramLength:2,key:"voltage80p"},{name:"容量60%",value:"",newValue:"",unit:"V",paramNo:35,oldParamNo:"0x33",paramLength:2,key:"voltage60p"},{name:"容量40%",value:"",newValue:"",unit:"V",paramNo:36,oldParamNo:"0x34",paramLength:2,key:"voltage40p"},{name:"容量20%",value:"",newValue:"",unit:"V",paramNo:37,oldParamNo:"0x35",paramLength:2,key:"voltage20p"},{name:"容量90%",value:"",newValue:"",unit:"V",paramNo:106,oldParamNo:"0x42",paramLength:2,key:"voltage90p"},{name:"容量70%",value:"",newValue:"",unit:"V",paramNo:107,oldParamNo:"0x43",paramLength:2,key:"voltage70p"},{name:"容量50%",value:"",newValue:"",unit:"V",paramNo:108,oldParamNo:"0x44",paramLength:2,key:"voltage50p"},{name:"容量30%",value:"",newValue:"",unit:"V",paramNo:109,oldParamNo:"0x45",paramLength:2,key:"voltage30p"},{name:"容量10%",value:"",newValue:"",unit:"V",paramNo:110,oldParamNo:"0x46",paramLength:2,key:"voltage10p"},{name:"容量100%",value:"",newValue:"",unit:"V",paramNo:111,oldParamNo:"0x47",paramLength:2,key:"voltage100p"}],funcAndTempFuncJson=[{paramNo:29,oldParamNo:"0x2D",paramLength:2,key:"func"},{paramNo:30,oldParamNo:"0x2E",paramLength:2,key:"tempFunc"}],funcJson=[{paramNo2:"1001",value:"",newValue:"",checked:!1,unit:"mAH",key:"onOff"},{paramNo2:"1002",value:"",newValue:"",checked:!1,unit:"mAH",key:"loadCheck"},{paramNo2:"1003",value:"",newValue:"",checked:!1,unit:"mAH",key:"equalizerFun"},{paramNo2:"1004",value:"",newValue:"",checked:!1,method:!0,unit:"mAH",key:"equalization"},{paramNo2:"1005",value:"",newValue:"",checked:!1,unit:"mAH",key:"led"},{paramNo2:"1006",value:"",newValue:"",checked:!1,unit:"mAH",key:"ledCount"},{paramNo2:"1008",value:"",newValue:"",checked:!1,unit:"mAH",key:"rtc"},{paramNo2:"1007",value:"",newValue:"",checked:!1,unit:"mAH",key:"fccLimit"},{paramNo2:"1009",value:"",newValue:"",checked:!1,unit:"mAH",key:"charingHandle"},{paramNo2:"1010",value:"",newValue:"",checked:!1,unit:"mAH",key:"gps"},{paramNo2:"1011",value:"",newValue:"",checked:!1,unit:"mAH",key:"beepDevice"}],tempFuncJson=Array.from({length:8},(_,index)=>({name:""+(0===index?"保护板温度":`电池温度${index}`),value:"",newValue:"",checked:!1,unit:"",key:`tempera${index}`})),systemJson=[{value:"",newValue:"",unit:"",paramNo:6,oldParamNo:"",paramLength:2,isHidden:!0,key:"serialNumber"},{value:"",newValue:"",unit:"",paramNo:7,oldParamNo:"",paramLength:2,isHidden:!0,key:"cycleCount"},{name:"检流阻值",value:"",newValue:"",unit:"mR",paramNo:28,oldParamNo:"0x2C",paramLength:2,isHidden:!1,key:"rsnsValue"},{name:"串数设置",value:"",newValue:"",unit:"",paramNo:31,oldParamNo:"0x2F",paramLength:2,isHidden:!0,key:"strCount"}];export{batteryInfoJson,capInfoJson,capVolInfoJson,currentInfoJson,equalizerFunJson,funcAndTempFuncJson,funcJson,systemJson,tempFuncJson,tempInfoJson,voltageInfoJson};
1
+ const batteryInfoJson=crsDivisor=>[{key:"barCode",paramNo:88,paramLength:32,oldParamNo:"0xA2"},{key:"manufacturer",paramNo:56,oldParamNo:"0xA0",paramLength:32},{key:"producedDate",paramNo:5,oldParamNo:"0x15",paramLength:2},{key:"model",paramNo:.1==crsDivisor?158:316,oldParamNo:"",paramLength:24},{key:"bmsModel",paramNo:.1==crsDivisor?176:72,oldParamNo:"",paramLength:.1==crsDivisor?16:32}],capInfoJson=[{key:"normCap",paramNo:0,oldParamNo:"0x10",paramLength:2,divisor:10},{key:"cycleCap",paramNo:1,oldParamNo:"0x11",paramLength:2,divisor:10},{key:"fullCap",paramNo:112,oldParamNo:"",paramLength:2,divisor:10}],voltageInfoJson=[{key:"allOvervoltageProtect",value:"",newValue:"",unit:"V",paramNo:16,oldParamNo:"0x20",paramLength:2,divisor:100},{key:"allOverpressureRecovery",value:"",newValue:"",unit:"V",paramNo:17,oldParamNo:"0x21",paramLength:2,divisor:100},{key:"allLowvoltageProtect",value:"",newValue:"",unit:"V",paramNo:18,oldParamNo:"0x22",paramLength:2,divisor:100},{key:"allLowvoltageRecover",value:"",newValue:"",unit:"V",paramNo:19,oldParamNo:"0x23",paramLength:2,divisor:100},{key:"singleOvervoltageProtect",value:"",newValue:"",unit:"V",paramNo:20,oldParamNo:"0x24",paramLength:2,divisor:1e3},{key:"singleOverpressureRecovery",value:"",newValue:"",unit:"V",paramNo:21,oldParamNo:"0x25",paramLength:2,divisor:1e3},{key:"singleLowvoltageProtect",value:"",newValue:"",unit:"V",paramNo:22,oldParamNo:"0x26",paramLength:2,divisor:1e3},{key:"singleLowvoltageRecover",value:"",newValue:"",unit:"V",paramNo:23,oldParamNo:"0x27",paramLength:2,divisor:1e3},{key:"allLowvoltageDelay",value:"",newValue:"",unit:"S",paramNo:48,oldParamNo:"0x3C",paramLength:2,divisor:1},{key:"allOverpressureDelay",value:"",newValue:"",unit:"S",paramNo:49,oldParamNo:"",paramLength:2,divisor:1},{key:"singleLowvoltageDelayed",value:"",newValue:"",unit:"S",paramNo:50,oldParamNo:"0x3d",paramLength:2,divisor:1},{key:"singleOverpressureDelay",value:"",newValue:"",unit:"S",paramNo:51,oldParamNo:"",paramLength:2,divisor:1},{key:"hardwareOV",value:null,newValue:"",unit:"V",paramNo:38,oldParamNo:"0x36",paramLength:2,divisor:1e3},{key:"hardwareUV",value:null,newValue:"",unit:"V",paramNo:39,oldParamNo:"0x37",paramLength:2,divisor:1e3}],currentInfoJson=[{value:"",newValue:"",unit:"A",paramNo:24,oldParamNo:"0x28",paramLength:2,key:"occhg",divisor:100},{value:"",newValue:"",unit:"A",paramNo:25,oldParamNo:"0x29",paramLength:2,key:"dischargeOvercurrentProtect",divisor:1e3},{value:"",newValue:"",unit:"S",paramNo:52,oldParamNo:"0x3E",paramLength:2,key:"chargeOvercurrentDelay",divisor:1},{value:"",newValue:"",unit:"S",paramNo:53,oldParamNo:"",paramLength:2,key:"chargeOvercurrentRecoverDelay",divisor:1},{value:"",newValue:"",unit:"S",paramNo:54,oldParamNo:"0x3F",paramLength:2,key:"dischargeOvercurrentDelay",divisor:1},{value:"",newValue:"",unit:"S",paramNo:55,oldParamNo:"",paramLength:2,key:"dischargeOvercurrentRecoverDelay",divisor:1},{value:null,newValue:"",unit:"(mV)",paramNo2:"1012",paramNo:40,oldParamNo:"0x38",paramLength:2,method:!0,key:"level2OvercurrentProtect"},{value:null,newValue:"",unit:"(mS)",paramNo2:"1013",paramNo:40,oldParamNo:"",paramLength:2,method:!0,key:"leve2OvercurrentDelay"},{checked:!1,isSwitch:!0,paramNo2:"1016",paramNo:41,oldParamNo:"",paramLength:2,key:"level2OvercurrentProtectV"},{value:null,newValue:"",unit:"(mV)",paramNo2:"1014",paramNo:41,oldParamNo:"",paramLength:2,method:!0,key:"shortcircuiProtect"},{value:null,newValue:"",unit:"(uS)",paramNo2:"1015",paramNo:41,oldParamNo:"",paramLength:2,method:!0,key:"shortcircuiProtectDelay"},{value:"",newValue:"",unit:"S",paramNo:43,oldParamNo:"0x39",paramLength:2,key:"shortcircuiProtectRecoverDelay",divisor:1}],tempInfoJson=[{value:"",newValue:"",unit:"℃",paramNo:8,oldParamNo:"0x18",paramLength:2,key:"chargeHightempProtect"},{value:"",newValue:"",unit:"℃",paramNo:9,oldParamNo:"0x19",paramLength:2,key:"chargeHightempRecover"},{value:"",newValue:"",unit:"℃",paramNo:10,oldParamNo:"0x1A",paramLength:2,key:"chargeLowtempProtect"},{value:"",newValue:"",unit:"℃",paramNo:11,oldParamNo:"0x1B",paramLength:2,key:"chargeLowtempRecover"},{value:"",newValue:"",unit:"℃",paramNo:12,oldParamNo:"0x1C",paramLength:2,key:"dischargingHightempProtect"},{value:"",newValue:"",unit:"℃",paramNo:13,oldParamNo:"0x1D",paramLength:2,key:"dischargingHightempRecover"},{value:"",newValue:"",unit:"℃",paramNo:14,oldParamNo:"0x1E",paramLength:2,key:"dischargingLowtempProtect"},{value:"",newValue:"",unit:"℃",paramNo:15,oldParamNo:"0x1F",paramLength:2,key:"dischargingLowtempRecover"},{value:"",newValue:"",unit:"S",paramNo:44,oldParamNo:"0x3A",paramLength:2,key:"chargeLowtempDelay"},{value:"",newValue:"",unit:"S",paramNo:45,oldParamNo:"",paramLength:2,key:"chargeHightempDelay"},{value:"",newValue:"",unit:"S",paramNo:46,oldParamNo:"0x3B",paramLength:2,key:"dischargingLowtempDelay"},{value:"",newValue:"",unit:"S",paramNo:47,oldParamNo:"",paramLength:2,key:"dischargingHightempDelay"},{name:"",value:"",newValue:"",unit:"℃",paramNo:202,oldParamNo:"0x2E",paramLength:2,key:"overtempProtect"},{name:"",value:"",newValue:"",unit:"℃",paramNo:203,oldParamNo:"0x2F",paramLength:2,key:"overtempRecover"}],equalizerFunJson=[{value:"",newValue:"",unit:"V",paramNo:26,oldParamNo:"0x2A",paramLength:2,key:"equalizingVoltage"},{value:"",newValue:"",unit:"V",paramNo:27,oldParamNo:"0x2B",paramLength:2,key:"accuracyEqualization"}],capVolInfoJson=[{value:null,newValue:"",unit:"V",paramNo:2,oldParamNo:"0x12",paramLength:2,isHidden:!1,key:"fullVolt",divisor:1e3},{value:null,newValue:"",unit:"V",paramNo:3,oldParamNo:"0x13",paramLength:2,isHidden:!1,key:"emptyVolt",divisor:1e3},{name:"容量80%",value:"",newValue:"",unit:"V",paramNo:34,oldParamNo:"0x32",paramLength:2,key:"voltage80p",divisor:1e3},{name:"容量60%",value:"",newValue:"",unit:"V",paramNo:35,oldParamNo:"0x33",paramLength:2,key:"voltage60p",divisor:1e3},{name:"容量40%",value:"",newValue:"",unit:"V",paramNo:36,oldParamNo:"0x34",paramLength:2,key:"voltage40p",divisor:1e3},{name:"容量20%",value:"",newValue:"",unit:"V",paramNo:37,oldParamNo:"0x35",paramLength:2,key:"voltage20p",divisor:1e3},{name:"容量90%",value:"",newValue:"",unit:"V",paramNo:106,oldParamNo:"0x42",paramLength:2,key:"voltage90p",divisor:1e3},{name:"容量70%",value:"",newValue:"",unit:"V",paramNo:107,oldParamNo:"0x43",paramLength:2,key:"voltage70p",divisor:1e3},{name:"容量50%",value:"",newValue:"",unit:"V",paramNo:108,oldParamNo:"0x44",paramLength:2,key:"voltage50p",divisor:1e3},{name:"容量30%",value:"",newValue:"",unit:"V",paramNo:109,oldParamNo:"0x45",paramLength:2,key:"voltage30p",divisor:1e3},{name:"容量10%",value:"",newValue:"",unit:"V",paramNo:110,oldParamNo:"0x46",paramLength:2,key:"voltage10p",divisor:1e3},{name:"容量100%",value:"",newValue:"",unit:"V",paramNo:111,oldParamNo:"0x47",paramLength:2,key:"voltage100p",divisor:1e3}],funcAndTempFuncJson=[{paramNo:29,oldParamNo:"0x2D",paramLength:2,key:"func"},{paramNo:30,oldParamNo:"0x2E",paramLength:2,key:"tempFunc"}],funcJson=[{paramNo2:"1001",value:"",newValue:"",checked:!1,unit:"mAH",key:"onOff"},{paramNo2:"1002",value:"",newValue:"",checked:!1,unit:"mAH",key:"loadCheck"},{paramNo2:"1003",value:"",newValue:"",checked:!1,unit:"mAH",key:"equalizerFun"},{paramNo2:"1004",value:"",newValue:"",checked:!1,method:!0,unit:"mAH",key:"equalization"},{paramNo2:"1005",value:"",newValue:"",checked:!1,unit:"mAH",key:"led"},{paramNo2:"1006",value:"",newValue:"",checked:!1,unit:"mAH",key:"ledCount"},{paramNo2:"1008",value:"",newValue:"",checked:!1,unit:"mAH",key:"rtc"},{paramNo2:"1007",value:"",newValue:"",checked:!1,unit:"mAH",key:"fccLimit"},{paramNo2:"1009",value:"",newValue:"",checked:!1,unit:"mAH",key:"charingHandle"},{paramNo2:"1010",value:"",newValue:"",checked:!1,unit:"mAH",key:"gps"},{paramNo2:"1011",value:"",newValue:"",checked:!1,unit:"mAH",key:"beepDevice"}],tempFuncJson=Array.from({length:8},(_,index)=>({name:""+(0===index?"保护板温度":`电池温度${index}`),value:"",newValue:"",checked:!1,unit:"",key:`tempera${index}`})),systemJson=[{value:"",newValue:"",unit:"",paramNo:6,oldParamNo:"",paramLength:2,isHidden:!0,key:"serialNumber",divisor:1},{value:"",newValue:"",unit:"",paramNo:7,oldParamNo:"",paramLength:2,isHidden:!0,key:"cycleCount",divisor:1},{name:"检流阻值",value:"",newValue:"",unit:"mR",paramNo:28,oldParamNo:"0x2C",paramLength:2,isHidden:!1,key:"rsnsValue",divisor:1e3},{name:"串数设置",value:"",newValue:"",unit:"",paramNo:31,oldParamNo:"0x2F",paramLength:2,isHidden:!0,key:"strCount",divisor:1},{name:"自动关机",value:"",newValue:"",unit:"",paramNo:191,paramLength:2,notShow:!1,switch:!0,key:"param1911",divisor:1},{name:"低电保护功能",value:"",newValue:"",unit:"",paramNo:198,paramLength:2,notShow:!1,switch:!0,key:"param1981",divisor:1},{name:"UART协议设定",value:"",newValue:"",unit:"",paramNo:195,paramLength:2,notShow:!1,key:"param1951",divisor:1,method:!0}];export{batteryInfoJson,capInfoJson,capVolInfoJson,currentInfoJson,equalizerFunJson,funcAndTempFuncJson,funcJson,systemJson,tempFuncJson,tempInfoJson,voltageInfoJson};
package/dist/esm/index.js CHANGED
@@ -1 +1 @@
1
- export{chunk,unique}from"./core/array.js";export{connectAsync,createBLEConnection,disConnect,foundScanDevice,getBLEDeviceCharacteristics,getBLEDeviceServices,getBluetoothAdapterState,initBle,notify,onBLECharacteristicValueChange,onBLEConnectionStateChange,onBleChangedConnectionState,onBluetoothAdapterStateChange,onBluetoothDeviceFound,onFoundDevice,scanHandle,startDevicesDiscovery,stopBluetoothDevicesDiscovery}from"./core/BleApiManager.js";export{eventBus,formatTimeHHmm,getOS,getPlatform,inArray,isEmpty,isNotEmpty}from"./core/commonfun.js";export{ALLOWED_MAC_PREFIX,APP_KEY_STATUS,extractModuleInfo,getRandomNum,getTypeBuyCmd,handleNewAppKey,handleOldAppKey,sendAppKey,sendEnableOrVerifyKey,sendOldAppKey,sendVerifyPwd,sendWrite1LevelPwd,verify3LevelPassword,verifyMacAddrAndKey}from"./core/keyAndPwdManager.js";export{OTAUpgrade}from"./core/OtaUpgrade.js";export{TelinkApi}from"./core/TelinkApi.js";export{BLE,Logger,Observer,Transfer}from"./core/Transfer.js";export{ab2decimalArr,ab2hex,arrayBufferToHexArray,base64ToHexArray,checkSum,crc16modbus,crcCheckSum,decimalToHex,decimalToHex0x,decimalToTwoByteHexArray,extractBits,generateCheckSum,generateCrc16modbusCheck,generateCrcCheckSum,getParamBaseValue,hex2Ascii,hex2Binary,hex2string,hexArr2Assic,hexArr2ab,hexArr2string,hexArrayToModuleArrayBuffer,hexStrAscii,hexStringToBinary,hexToDecimal,sleep,string2hexArr,stringToTwoHexArray}from"./core/BleDataProcess.js";export{getData,setMTUAsync}from"./core/BleCmdAnalysis/BleCmdAnalysis.js";export{clearPrimaryKey,getBluetoothName,getBroadcastDataCmd,getFFAA03Async,getFFAA17Async,getFFAA25Async,getFFAA26Async,getFFAA80Async,getFFAAKeyAsync,getWiFiIP,resetFactoryData,resetSecondaryKey,resolveFFAA25,resolveFFAA26,resolveFFAA80,resolveFFAAKey,setBluetoothName,setWiFi,setWiFiSta,set_PlanCMD_FFAA,set_PlanCMD_FFAA80}from"./core/BleCmdAnalysis/BleCmdFFAA.js";export{activateAsync,enterFactory,existFactory,get3B3CAsync,get3B3CInfo,getChipTypeAsync,getDD5A0AAsync,getDD5A0EAsync,getDD5A17Async,getDD5AAllAsync,getDD5AE0Async,getDD5AE1Async,getDD5AE4Async,getDD5AFAAsync,getDD5AFBAsync,getDDA503Async,getDDA504Async,getDDA505Async,getDDA507Async,getDDA508Async,getDDA5DCAsync,getDDA5FAAsync,getDDA5OldAsync,getProtectCountCmd,readExistFactory,resetCapacity,resolve3B3C,resolveBMSCmd,resolveBaseDD,resolveDD5A0A,resolveDDA500,resolveDDA503,resolveDDA504,resolveDDA505,resolveDDA508,resolveDDA5DC,resolveDDA5FA,resolveProtections,sendBMSAsync,setDDA5FAAsync,setDDA5OldAsync,set_PlanCMD_3B3C,set_PlanCMD_DD}from"./core/BleCmdAnalysis/BleCmdDD.js";export{getSysParamCmd,readParamCmd,setCapacityParamCmd,setParamCmd,setSysParamCmd}from"./core/BleCmdAnalysis/readAndSetParam.js";export{getBaseInfo,getBaseParams,getResistance}from"./core/BleCmdAnalysis/BaseParamProtocol.js";export{getCMDESInfoAsync,getHVESInfoAsync,resolveHVESBMUInfo,resolveHVESBaseInfo,resolveHVESCalibrationC1Info,resolveHVESCalibrationC2Info,resolveHVESCalibrationConfigInfo,resolveHVESCalibrationInfo,resolveHVESCtInfo,resolveHVESDisCtInfo,resolveHVESElectrodeHTInfo,resolveHVESEtInfo,resolveHVESInsulationLRInfo,resolveHVESLSocInfo,resolveHVESMonoVolInfo,resolveHVESOeInfo,resolveHVESOtRisingInfo,resolveHVESOtrInfo,resolveHVESOvrInfo,resolveHVESPackInfo,resolveHVESParamsInfo,resolveHVESSumInfo,resolveHVESSumVolInfo,resolveHVESVersionInfo}from"./core/BleCmdAnalysis/BleCmdHVES.js";export{HostProtocol}from"./core/BleCmdAnalysis/ESHostProtocol.js";export{batteryInfoJson,capInfoJson,capVolInfoJson,currentInfoJson,equalizerFunJson,funcAndTempFuncJson,funcJson,systemJson,tempFuncJson,tempInfoJson,voltageInfoJson}from"./core/dataJson/baseParamsJson.js";
1
+ export{chunk,unique}from"./core/array.js";export{checkBluetoothStatus,checkLocationStatus,connectAsync,createBLEConnection,disConnect,foundScanDevice,getBLEDeviceCharacteristics,getBLEDeviceServices,getBluetoothAdapterState,getBluetoothPermission,initBle,isInit,notify,onBLECharacteristicValueChange,onBLEConnectionStateChange,onBleChangedConnectionState,onBluetoothAdapterStateChange,onBluetoothDeviceFound,onFoundDevice,scanHandle,startDevicesDiscovery,stopBluetoothDevicesDiscovery}from"./core/BleApiManager.js";export{eventBus,formatTimeHHmm,getOS,getPlatform,inArray,isEmpty,isNotEmpty}from"./core/commonfun.js";export{ALLOWED_MAC_PREFIX,APP_KEY_STATUS,extractModuleInfo,getRandomNum,getTypeBuyCmd,handleNewAppKey,handleOldAppKey,sendAppKey,sendEnableOrVerifyKey,sendOldAppKey,sendVerifyPwd,sendWrite1LevelPwd,verify3LevelPassword,verifyMacAddrAndKey}from"./core/keyAndPwdManager.js";export{OTAUpgrade}from"./core/OtaUpgrade.js";export{TelinkApi}from"./core/TelinkApi.js";export{BLE,Logger,Observer,Transfer}from"./core/Transfer.js";export{ab2decimalArr,ab2hex,arrayBufferToHexArray,base64ToHexArray,checkSum,crc16modbus,crcCheckSum,decimalToHex,decimalToHex0x,decimalToTwoByteHexArray,extractBits,fromBCD,generateCheckSum,generateCrc16modbusCheck,generateCrcCheckSum,getParamBaseValue,hex2Ascii,hex2Binary,hex2string,hexArr2Assic,hexArr2ab,hexArr2string,hexArrayToModuleArrayBuffer,hexStrAscii,hexStringToBinary,hexToDecimal,isWithin30Minutes,parseDateTime,sleep,string2hexArr,stringToTwoHexArray,toBCD}from"./core/BleDataProcess.js";export{getData,setMTUAsync}from"./core/BleCmdAnalysis/BleCmdAnalysis.js";export{clearPrimaryKey,getBluetoothName,getBroadcastDataCmd,getFFAA03Async,getFFAA17Async,getFFAA25Async,getFFAA26Async,getFFAA80Async,getFFAAKeyAsync,getWiFiIP,resetFactoryData,resetSecondaryKey,resolveFFAA25,resolveFFAA26,resolveFFAA80,resolveFFAAKey,setBluetoothName,setWiFi,setWiFiSta,set_PlanCMD_FFAA,set_PlanCMD_FFAA80}from"./core/BleCmdAnalysis/BleCmdFFAA.js";export{activateAsync,enterFactory,existFactory,get3B3CAsync,get3B3CInfo,getChipTypeAsync,getDD5A0AAsync,getDD5A0EAsync,getDD5A17Async,getDD5AAllAsync,getDD5AE0Async,getDD5AE1Async,getDD5AE4Async,getDD5AFAAsync,getDD5AFBAsync,getDDA4F0Async,getDDA503Async,getDDA504Async,getDDA505Async,getDDA506Async,getDDA507Async,getDDA508Async,getDDA5DCAsync,getDDA5FAAsync,getDDA5OldAsync,getProtectCountCmd,readExistFactory,resetCapacity,resolve3B3C,resolveBMSCmd,resolveBaseDD,resolveDD5A0A,resolveDDA4F0,resolveDDA500,resolveDDA503,resolveDDA504,resolveDDA505,resolveDDA506,resolveDDA508,resolveDDA5DC,resolveDDA5FA,resolveProtections,sendBMSAsync,setDD5AE3sync,setDDA5FAAsync,setDDA5OldAsync,set_PlanCMD_3B3C,set_PlanCMD_DD}from"./core/BleCmdAnalysis/BleCmdDD.js";export{getSysParamCmd,readParamCmd,setCapacityParamCmd,setParamCmd,setSysParamCmd}from"./core/BleCmdAnalysis/readAndSetParam.js";export{getBaseInfo,getBaseParams,getResistance}from"./core/BleCmdAnalysis/BaseParamProtocol.js";export{getCMDESInfoAsync,getHVESInfoAsync,resolveHVESBMUInfo,resolveHVESBaseInfo,resolveHVESCalibrationC1Info,resolveHVESCalibrationC2Info,resolveHVESCalibrationConfigInfo,resolveHVESCalibrationInfo,resolveHVESCtInfo,resolveHVESDisCtInfo,resolveHVESElectrodeHTInfo,resolveHVESEtInfo,resolveHVESInsulationLRInfo,resolveHVESLSocInfo,resolveHVESMonoVolInfo,resolveHVESOeInfo,resolveHVESOtRisingInfo,resolveHVESOtrInfo,resolveHVESOvrInfo,resolveHVESPackInfo,resolveHVESParamsInfo,resolveHVESSumInfo,resolveHVESSumVolInfo,resolveHVESVersionInfo}from"./core/BleCmdAnalysis/BleCmdHVES.js";export{HostProtocol}from"./core/BleCmdAnalysis/ESHostProtocol.js";export{batteryInfoJson,capInfoJson,capVolInfoJson,currentInfoJson,equalizerFunJson,funcAndTempFuncJson,funcJson,systemJson,tempFuncJson,tempInfoJson,voltageInfoJson}from"./core/dataJson/baseParamsJson.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jiabaida/tools",
3
- "version": "1.0.3",
3
+ "version": "1.0.6",
4
4
  "main": "dist/cjs/index.js",
5
5
  "module": "dist/esm/index.js",
6
6
  "exports": {