@jiabaida/tools 1.0.3 → 1.0.7
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.
- package/dist/cjs/core/BleApiManager.js +1 -1
- package/dist/cjs/core/BleCmdAnalysis/BaseParamProtocol.js +1 -1
- package/dist/cjs/core/BleCmdAnalysis/BleCmdAnalysis.js +1 -1
- package/dist/cjs/core/BleCmdAnalysis/BleCmdDD.js +1 -1
- package/dist/cjs/core/BleCmdAnalysis/BleCmdDDA4.js +1 -0
- package/dist/cjs/core/BleDataProcess.js +1 -1
- package/dist/cjs/core/OtaUpgrade.js +1 -1
- package/dist/cjs/core/Transfer.js +1 -1
- package/dist/cjs/core/commonfun.js +1 -1
- package/dist/cjs/core/dataJson/baseParamsJson.js +1 -1
- package/dist/cjs/core/mqttServer.js +1 -0
- package/dist/cjs/core/rsaEncrypt.js +1 -0
- package/dist/cjs/index.js +1 -1
- package/dist/esm/core/BleApiManager.js +1 -1
- package/dist/esm/core/BleCmdAnalysis/BaseParamProtocol.js +1 -1
- package/dist/esm/core/BleCmdAnalysis/BleCmdAnalysis.js +1 -1
- package/dist/esm/core/BleCmdAnalysis/BleCmdDD.js +1 -1
- package/dist/esm/core/BleCmdAnalysis/BleCmdDDA4.js +1 -0
- package/dist/esm/core/BleDataProcess.js +1 -1
- package/dist/esm/core/OtaUpgrade.js +1 -1
- package/dist/esm/core/Transfer.js +1 -1
- package/dist/esm/core/commonfun.js +1 -1
- package/dist/esm/core/dataJson/baseParamsJson.js +1 -1
- package/dist/esm/core/mqttServer.js +1 -0
- package/dist/esm/core/rsaEncrypt.js +1 -0
- package/dist/esm/index.js +1 -1
- package/package.json +4 -3
- package/src/core/BleApiManager.js +113 -75
- package/src/core/BleCmdAnalysis/BaseParamProtocol.js +35 -6
- package/src/core/BleCmdAnalysis/BleCmdAnalysis.js +3 -2
- package/src/core/BleCmdAnalysis/BleCmdDD.js +132 -5
- package/src/core/BleCmdAnalysis/BleCmdDDA4.js +74 -11
- package/src/core/BleCmdAnalysis/index.js +6 -5
- package/src/core/BleDataProcess.js +40 -0
- package/src/core/OtaUpgrade.js +16 -4
- package/src/core/Transfer.js +1 -1
- package/src/core/commonfun.js +2 -1
- package/src/core/dataJson/baseParamsJson.js +135 -33
- package/src/core/mqttServer.js +9 -9
- package/src/core/rsaEncrypt.js +1 -1
- package/src/index.js +4 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var vue=require("vue"),BleDataProcess=require("./BleDataProcess.js"),commonfun=require("./commonfun.js");const serviceId="0000FF00-0000-1000-8000-00805F9B34FB",bluetoothAdapterState=vue.ref({available:!1,discovering:!1}),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)}})}),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?BleDataProcess.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?BleDataProcess.hexToDecimal(tempVoltage):"",tempCurrent=advHex.slice(26,28),current=tempCurrent||0==tempCurrent?BleDataProcess.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&&commonfun.eventBus.emit("setBluetoothDeviceFound",device)})},onFoundDevice=callback=>{commonfun.eventBus.on("setBluetoothDeviceFound",callback)},onBluetoothAdapterStateChange=async()=>{uni.onBluetoothAdapterStateChange(res=>{console.log("onBluetoothAdapterStateChange监听蓝牙适配器变化",res),bluetoothAdapterState.value=res})},onBLECharacteristicValueChange=async()=>{uni.onBLECharacteristicValueChange(characteristic=>{const decimalArr=BleDataProcess.ab2decimalArr(characteristic.value);console.warn("decimalArr: 监听到的回复-------------------",decimalArr),commonfun.eventBus.emit("setBleChangedCharacteristicValue",characteristic)})},onBLEConnectionStateChange=async()=>{uni.onBLEConnectionStateChange(characteristic=>{console.log("onBLEConnectionStateChange",characteristic),commonfun.eventBus.emit("setBleChangedConnectionState",characteristic)})},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})}),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)};exports.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)}}),exports.createBLEConnection=createBLEConnection,exports.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 断开连接")}})}),exports.foundScanDevice=foundScanDevice,exports.getBLEDeviceCharacteristics=getBLEDeviceCharacteristics,exports.getBLEDeviceServices=getBLEDeviceServices,exports.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)}})}),exports.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}=commonfun.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})}},exports.notify=notify,exports.onBLECharacteristicValueChange=onBLECharacteristicValueChange,exports.onBLEConnectionStateChange=onBLEConnectionStateChange,exports.onBleChangedConnectionState=callback=>{commonfun.eventBus.on("setBleChangedConnectionState",callback)},exports.onBluetoothAdapterStateChange=onBluetoothAdapterStateChange,exports.onBluetoothDeviceFound=onBluetoothDeviceFound,exports.onFoundDevice=onFoundDevice,exports.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}=commonfun.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)}})},exports.startDevicesDiscovery=startDevicesDiscovery,exports.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("停止广播设备 取消订阅"),commonfun.eventBus.off("setBluetoothDeviceFound")}})});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var vue=require("vue"),BleDataProcess=require("./BleDataProcess.js"),commonfun=require("./commonfun.js");const serviceId="0000FF00-0000-1000-8000-00805F9B34FB",{isAndroid:isAndroid,isIOS:isIOS}=commonfun.getOS(),bluetoothAdapterState=vue.ref({available:!1,discovering:!1});exports.isInit=!1;const enhanceDevice=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?BleDataProcess.hexToDecimal(socHex):"",productType=advHex.slice(18,20);let protocolVersion=advHex.slice(20,22);if(protocolVersion){const v=BleDataProcess.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?BleDataProcess.hexToDecimal(tempVoltage):"",tempCurrent=advHex.slice(26,28),current=tempCurrent||0==tempCurrent?BleDataProcess.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},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}},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)}})}),onBluetoothDeviceFound=async()=>{uni.onBluetoothDeviceFound(characteristic=>{console.log("setBluetoothDeviceFound",characteristic);const device=enhanceDevice(characteristic.devices[0]);device&&commonfun.eventBus.emit("setBluetoothDeviceFound",device)})},onFoundDevice=callback=>{commonfun.eventBus.on("setBluetoothDeviceFound",callback)},onBluetoothAdapterStateChange=async()=>{uni.onBluetoothAdapterStateChange(res=>{console.log("onBluetoothAdapterStateChange监听蓝牙适配器变化",res),bluetoothAdapterState.value=res})},onBLECharacteristicValueChange=async()=>{uni.onBLECharacteristicValueChange(characteristic=>{const decimalArr=BleDataProcess.ab2decimalArr(characteristic.value);console.warn("decimalArr: 监听到的回复-------------------",decimalArr),commonfun.eventBus.emit("setBleChangedCharacteristicValue",characteristic)})},onBLEConnectionStateChange=async()=>{uni.onBLEConnectionStateChange(characteristic=>{console.log("onBLEConnectionStateChange",characteristic),commonfun.eventBus.emit("setBleChangedConnectionState",characteristic)})},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})}),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)};exports.checkBluetoothStatus=checkBluetoothStatus,exports.checkLocationStatus=checkLocationStatus,exports.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)}}),exports.createBLEConnection=createBLEConnection,exports.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 断开连接")}})}),exports.enhanceDevice=enhanceDevice,exports.foundScanDevice=foundScanDevice,exports.getBLEDeviceCharacteristics=getBLEDeviceCharacteristics,exports.getBLEDeviceServices=getBLEDeviceServices,exports.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)}})}),exports.getBluetoothPermission=getBluetoothPermission,exports.initBle=async()=>await getBluetoothPermission(()=>{console.log("初始化蓝牙成功initBluetoothSuccessCb1");try{if(exports.isInit)return;onBluetoothDeviceFound(),onBLECharacteristicValueChange(),onBLEConnectionStateChange(),onBluetoothAdapterStateChange(),exports.isInit=!0}catch(error){throw error}}),exports.notify=notify,exports.onBLECharacteristicValueChange=onBLECharacteristicValueChange,exports.onBLEConnectionStateChange=onBLEConnectionStateChange,exports.onBleChangedConnectionState=callback=>{commonfun.eventBus.on("setBleChangedConnectionState",callback)},exports.onBluetoothAdapterStateChange=onBluetoothAdapterStateChange,exports.onBluetoothDeviceFound=onBluetoothDeviceFound,exports.onFoundDevice=onFoundDevice,exports.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)}})},exports.startDevicesDiscovery=startDevicesDiscovery,exports.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("停止广播设备 取消订阅"),commonfun.eventBus.off("setBluetoothDeviceFound")}})}));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var readAndSetParam=require("./readAndSetParam.js"),BleDataProcess=require("../BleDataProcess.js"),baseParamsJson=require("../dataJson/baseParamsJson.js"),BleCmdDD=require("./BleCmdDD.js");function format(value,n=1,offset=0,scope=0){if(!value)return null;value=value.map(el=>{const hexValue=BleDataProcess.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 BleCmdDD.enterFactory(deviceId);index<params.length;){const item=params[index];try{const basedata=await readAndSetParam.getSysParamCmd(chipType,deviceId,item,!1);datasInfo[item.key]=basedata,index++}catch(error){console.error(`获取参数 ${item.key} 失败:`,error),index++}}chipType||await BleCmdDD.readExistFactory(deviceId)};let crsDivisor=.1;const 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+=BleDataProcess.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+=BleDataProcess.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={};baseParamsJson.funcJson.forEach((item,index)=>{item.key&&(func[item.key]=binaryFuncArr[index])});const tempFunc={};return baseParamsJson.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)});exports.getBaseInfo=getBaseInfo,exports.getBaseParams=async(chipType,deviceData,index,paramObj)=>{console.log("chipType: ",chipType);const deviceId=deviceData?.deviceId,protocolVersion=deviceData?.protocolVersion||"00";console.warn("protocolVersion: ",protocolVersion);const v=BleDataProcess.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,baseParamsJson.batteryInfoJson),dataInfo=getBaseInfo(datasInfo1),dataInfo;case 2:let datasInfo2={};if(chipType){const capData=await readAndSetParam.getSysParamCmd(chipType,deviceId,{...baseParamsJson.capInfoJson[0],paramLength:4});console.warn("capData: ",capData),datasInfo2.normCap=capData?.slice(0,2),datasInfo2.cycleCap=capData?.slice(2,4);const capData2=await readAndSetParam.getSysParamCmd(chipType,deviceId,baseParamsJson.capInfoJson[2]);datasInfo2.fullCap=capData2?.slice(0,2)}else await sendCmdSeq(datasInfo2,chipType,deviceId,baseParamsJson.capInfoJson);return dataInfo=getCapInfo(datasInfo2),dataInfo;case 3:let datasInfo3={};if(chipType){let vindex=baseParamsJson.voltageInfoJson.findIndex(el=>16==el.paramNo);console.log("vindex: ------------",vindex);let vindex1=baseParamsJson.voltageInfoJson.findIndex(el=>48==el.paramNo),vindex2=baseParamsJson.voltageInfoJson.findIndex(el=>38==el.paramNo);const voltageData=await readAndSetParam.getSysParamCmd(chipType,deviceId,{...baseParamsJson.voltageInfoJson[vindex],paramLength:16}),voltageData1=await readAndSetParam.getSysParamCmd(chipType,deviceId,{...baseParamsJson.voltageInfoJson[vindex1],paramLength:8}),voltageData2=await readAndSetParam.getSysParamCmd(chipType,deviceId,{...baseParamsJson.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,baseParamsJson.voltageInfoJson);return dataInfo=getVoltageInfo(datasInfo3,chipType),dataInfo;case 4:let datasInfo4={};if(chipType){let cindex=baseParamsJson.currentInfoJson.findIndex(el=>24==el.paramNo),cindex1=baseParamsJson.currentInfoJson.findIndex(el=>52==el.paramNo),cindex2=baseParamsJson.currentInfoJson.findIndex(el=>40==el.paramNo);const currentData=await readAndSetParam.getSysParamCmd(chipType,deviceId,{...baseParamsJson.currentInfoJson[cindex],paramLength:4}),currentData1=await readAndSetParam.getSysParamCmd(chipType,deviceId,{...baseParamsJson.currentInfoJson[cindex1],paramLength:8}),currentData2=await readAndSetParam.getSysParamCmd(chipType,deviceId,{...baseParamsJson.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,baseParamsJson.currentInfoJson);return dataInfo=getCurrentInfo(datasInfo4,chipType),dataInfo;case 5:let datasInfo5={};if(chipType){let tindex=baseParamsJson.tempInfoJson.findIndex(el=>8==el.paramNo),tindex1=baseParamsJson.tempInfoJson.findIndex(el=>44==el.paramNo);const tempData=await readAndSetParam.getSysParamCmd(chipType,deviceId,{...baseParamsJson.tempInfoJson[tindex],paramLength:16}),tempData1=await readAndSetParam.getSysParamCmd(chipType,deviceId,{...baseParamsJson.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,baseParamsJson.tempInfoJson);return dataInfo=getTempInfo(datasInfo5,chipType),dataInfo;case 6:let datasInfo6={};if(chipType){const equalizerFunData=await readAndSetParam.getSysParamCmd(chipType,deviceId,{...baseParamsJson.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,baseParamsJson.equalizerFunJson);return dataInfo=getEqualizerFunInfo(datasInfo6),dataInfo;case 7:let datasInfo7={};if(chipType){let capVolIndex=baseParamsJson.capVolInfoJson.findIndex(el=>34==el.paramNo),capVolIndex1=baseParamsJson.capVolInfoJson.findIndex(el=>106==el.paramNo);const capVolInfoData=await readAndSetParam.getSysParamCmd(chipType,deviceId,{...baseParamsJson.capVolInfoJson[0],paramLength:4}),capVolInfoData1=await readAndSetParam.getSysParamCmd(chipType,deviceId,{...baseParamsJson.capVolInfoJson[capVolIndex],paramLength:8}),capVolInfoData2=await readAndSetParam.getSysParamCmd(chipType,deviceId,{...baseParamsJson.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,baseParamsJson.capVolInfoJson);return dataInfo=getcapVolInfoInfo(datasInfo7,chipType),dataInfo;case 9:let datasInfo9={};if(chipType){const funcAndTempFuncData=await readAndSetParam.getSysParamCmd(chipType,deviceId,{...baseParamsJson.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,baseParamsJson.funcAndTempFuncJson);return dataInfo=getFuncAndTempFuncInfo(datasInfo9),dataInfo;case 10:let datasInfo10={};return await sendCmdSeq(datasInfo10,chipType,deviceId,baseParamsJson.systemJson),dataInfo=getSystemInfo(datasInfo10),dataInfo;case 11:const counts=await BleCmdDD.getProtectCountCmd(deviceId);return console.log("counts: ",counts),counts;default:if(!paramObj)return null;let defaultDataInfo={};const onedata=await readAndSetParam.getSysParamCmd(chipType,deviceId,paramObj);return defaultDataInfo[paramObj.key]=onedata?.slice(0,2),defaultDataInfo}}catch(error){throw console.error("error: 读系统参数报错 getBaseParams",error),error}},exports.getResistance=async(chipType,deviceId)=>{try{const rsnsValue=await readAndSetParam.getSysParamCmd(chipType,deviceId,baseParamsJson.systemJson[2]);return format(rsnsValue,crsDivisor,0,2)}catch(error){throw console.error("error: 读检流阻值报错 getResistance",error),error}};
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var readAndSetParam=require("./readAndSetParam.js"),BleDataProcess=require("../BleDataProcess.js"),baseParamsJson=require("../dataJson/baseParamsJson.js"),BleCmdDD=require("./BleCmdDD.js");function format(value,n=1,offset=0,scope=0){if(!value)return null;value=value.map(el=>{const hexValue=BleDataProcess.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 BleCmdDD.enterFactory(deviceId);index<params.length;){const item=params[index];try{const basedata=await readAndSetParam.getSysParamCmd(chipType,deviceId,item,!1);datasInfo[item.key]=basedata,index++}catch(error){console.error(`获取参数 ${item.key} 失败:`,error),index++}}chipType||await BleCmdDD.readExistFactory(deviceId)};let crsDivisor=.1;const 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+=BleDataProcess.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+=BleDataProcess.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={};baseParamsJson.funcJson.forEach((item,index)=>{item.key&&(func[item.key]=binaryFuncArr[index])});const tempFunc={};return baseParamsJson.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}};exports.getBaseInfo=getBaseInfo,exports.getBaseParams=async(chipType,deviceData,index,paramObj)=>{console.log("chipType: ",chipType);const deviceId=deviceData?.deviceId,protocolVersion=deviceData?.protocolVersion||"00";console.warn("protocolVersion: ",protocolVersion);const v=BleDataProcess.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,baseParamsJson.batteryInfoJson(crsDivisor)),dataInfo=getBaseInfo(datasInfo1),dataInfo;case 2:let datasInfo2={};if(chipType){const capData=await readAndSetParam.getSysParamCmd(chipType,deviceId,{...baseParamsJson.capInfoJson[0],paramLength:4});console.warn("capData: ",capData),datasInfo2.normCap=capData?.slice(0,2),datasInfo2.cycleCap=capData?.slice(2,4);const capData2=await readAndSetParam.getSysParamCmd(chipType,deviceId,baseParamsJson.capInfoJson[2]);datasInfo2.fullCap=capData2?.slice(0,2)}else await sendCmdSeq(datasInfo2,chipType,deviceId,baseParamsJson.capInfoJson);return dataInfo=getCapInfo(datasInfo2),dataInfo;case 3:let datasInfo3={};if(chipType){let vindex=baseParamsJson.voltageInfoJson.findIndex(el=>16==el.paramNo);console.log("vindex: ------------",vindex);let vindex1=baseParamsJson.voltageInfoJson.findIndex(el=>48==el.paramNo),vindex2=baseParamsJson.voltageInfoJson.findIndex(el=>38==el.paramNo);const voltageData=await readAndSetParam.getSysParamCmd(chipType,deviceId,{...baseParamsJson.voltageInfoJson[vindex],paramLength:16}),voltageData1=await readAndSetParam.getSysParamCmd(chipType,deviceId,{...baseParamsJson.voltageInfoJson[vindex1],paramLength:8}),voltageData2=await readAndSetParam.getSysParamCmd(chipType,deviceId,{...baseParamsJson.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,baseParamsJson.voltageInfoJson);return dataInfo=getVoltageInfo(datasInfo3,chipType),dataInfo;case 4:let datasInfo4={};if(chipType){let cindex=baseParamsJson.currentInfoJson.findIndex(el=>24==el.paramNo),cindex1=baseParamsJson.currentInfoJson.findIndex(el=>52==el.paramNo),cindex2=baseParamsJson.currentInfoJson.findIndex(el=>40==el.paramNo);const currentData=await readAndSetParam.getSysParamCmd(chipType,deviceId,{...baseParamsJson.currentInfoJson[cindex],paramLength:4}),currentData1=await readAndSetParam.getSysParamCmd(chipType,deviceId,{...baseParamsJson.currentInfoJson[cindex1],paramLength:8}),currentData2=await readAndSetParam.getSysParamCmd(chipType,deviceId,{...baseParamsJson.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,baseParamsJson.currentInfoJson);return dataInfo=getCurrentInfo(datasInfo4,chipType),dataInfo;case 5:let datasInfo5={};if(chipType){let tindex=baseParamsJson.tempInfoJson.findIndex(el=>8==el.paramNo),tindex1=baseParamsJson.tempInfoJson.findIndex(el=>44==el.paramNo),tindex2=baseParamsJson.tempInfoJson.findIndex(el=>202==el.paramNo);const tempData=await readAndSetParam.getSysParamCmd(chipType,deviceId,{...baseParamsJson.tempInfoJson[tindex],paramLength:16}),tempData1=await readAndSetParam.getSysParamCmd(chipType,deviceId,{...baseParamsJson.tempInfoJson[tindex1],paramLength:8}),tempData2=await readAndSetParam.getSysParamCmd(chipType,deviceId,{...baseParamsJson.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,baseParamsJson.tempInfoJson);return dataInfo=getTempInfo(datasInfo5,chipType),dataInfo;case 6:let datasInfo6={};if(chipType){const equalizerFunData=await readAndSetParam.getSysParamCmd(chipType,deviceId,{...baseParamsJson.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,baseParamsJson.equalizerFunJson);return dataInfo=getEqualizerFunInfo(datasInfo6),dataInfo;case 7:let datasInfo7={};if(chipType){let capVolIndex=baseParamsJson.capVolInfoJson.findIndex(el=>34==el.paramNo),capVolIndex1=baseParamsJson.capVolInfoJson.findIndex(el=>106==el.paramNo);const capVolInfoData=await readAndSetParam.getSysParamCmd(chipType,deviceId,{...baseParamsJson.capVolInfoJson[0],paramLength:4}),capVolInfoData1=await readAndSetParam.getSysParamCmd(chipType,deviceId,{...baseParamsJson.capVolInfoJson[capVolIndex],paramLength:8}),capVolInfoData2=await readAndSetParam.getSysParamCmd(chipType,deviceId,{...baseParamsJson.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,baseParamsJson.capVolInfoJson);return dataInfo=getcapVolInfoInfo(datasInfo7,chipType),dataInfo;case 9:let datasInfo9={};if(chipType){const funcAndTempFuncData=await readAndSetParam.getSysParamCmd(chipType,deviceId,{...baseParamsJson.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,baseParamsJson.funcAndTempFuncJson);return dataInfo=getFuncAndTempFuncInfo(datasInfo9),dataInfo;case 10:let datasInfo10={};return await sendCmdSeq(datasInfo10,chipType,deviceId,baseParamsJson.systemJson),dataInfo=getSystemInfo(datasInfo10),dataInfo;case 11:const counts=await BleCmdDD.getProtectCountCmd(deviceId);return console.log("counts: ",counts),counts;default:if(!paramObj)return null;let defaultDataInfo={};const onedata=await readAndSetParam.getSysParamCmd(chipType,deviceId,paramObj);return defaultDataInfo[paramObj.key]=onedata?.slice(0,2),defaultDataInfo}}catch(error){throw console.error("error: 读系统参数报错 getBaseParams",error),error}},exports.getResistance=async(chipType,deviceId)=>{try{const rsnsValue=await readAndSetParam.getSysParamCmd(chipType,deviceId,baseParamsJson.systemJson[2]);return format(rsnsValue,crsDivisor,0,2)}catch(error){throw console.error("error: 读检流阻值报错 getResistance",error),error}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var BleDataProcess=require("../BleDataProcess.js"),commonfun=require("../commonfun.js");async function _writeAsync(deviceId,value){return console.log("deviceId, value: ",deviceId,value),!(!deviceId||!value)&&new Promise(resolve=>{const{isAndroid:isAndroid,isIOS:isIOS}=commonfun.getOS(),platform=commonfun.getPlatform();console.log("platform: ",platform),console.log("isAndroid, isIOS: ",isAndroid,isIOS);const writeType="mp-weixin"===platform||isAndroid?"writeNoResponse":"write";uni.writeBLECharacteristicValue({deviceId:deviceId,serviceId:"0000FF00-0000-1000-8000-00805F9B34FB",characteristicId:"0000FF02-0000-1000-8000-00805F9B34FB",writeType:writeType,value:value,success:res=>{console.error("res: 写入成功",res),resolve(!0)},fail:e=>{console.error("写入失败",e),resolve(!1)}}),isIOS&&setTimeout(()=>resolve(!0),50)})}exports.getData=async(deviceId,{command:command,commandVerifyHandler:commandVerifyHandler=hexArr=>({verified:!1,pkgLen:null}),pkgVerifyHandler:pkgVerifyHandler=pkg=>({verified:!1}),maxRetries:maxRetries=2,retryInterval:retryInterval=300},tag="")=>{if(!deviceId)throw new Error("deviceId is required");if(!command||command.length<=0)throw new Error("command is required");return new Promise((resolve,reject)=>{let isCompleted=!1,timeoutId=null,responsed=!1,len=null,pkg=[];const cmdContent=BleDataProcess.hexArr2ab(command),cleanup=()=>{isCompleted||(isCompleted=!0,clearTimeout(timeoutId),commonfun.eventBus.off("setBleChangedCharacteristicValue",dataHandler))},dataHandler=payload=>{if(!payload||payload.deviceId!==deviceId||!payload.value)return;const hexArr=BleDataProcess.ab2decimalArr(payload.value);if(console.log("hexArr: ",hexArr),console.warn(tag,"接收到数据:",BleDataProcess.hexArr2string(hexArr)),0!==hexArr.length){if(null===len){const{verified:verified,pkgLen:pkgLen}=commandVerifyHandler(hexArr);console.log("指令验证结果:",{verified:verified,pkgLen:pkgLen}),verified&&(len=pkgLen)}if(len){if(pkg=[...pkg,...hexArr],console.log("当前数据包:",pkg,`长度: ${pkg.length}/${len}`),pkg.length>=len){pkg=pkg.slice(0,len);const{verified:verified}=pkgVerifyHandler(pkg);console.log("数据包验证结果:",{verified:verified}),verified?(responsed=!0,cleanup(),resolve([...pkg])):(len=null,pkg=[])}}else pkg=[]}},writeToDevice=async(attempt=1)=>{try{console.warn(tag,`第${attempt}次写入指令:`,command.join("").replace(/0x/g,"").toUpperCase());const writeSucceed=await async function(deviceId,value){return console.log("value: ",value),console.log("deviceId: ",deviceId),!(!deviceId||!value)&&new Promise(async resolve=>{const n=Math.ceil(value.byteLength/20);let res;for(let i=0;i<n;i++){const _value=value.slice(20*i,20*(i+1));if(console.log("分包写入_value: ",_value),await BleDataProcess.sleep(150),res=await _writeAsync(deviceId,_value),console.log(`分包写入结果 ${i+1}/${n} : ${res}`),!res)return resolve(!1)}resolve(res)})}(deviceId,cmdContent);if(console.warn(tag,`第${attempt}次写入结果:`,writeSucceed?"成功":"失败"),!writeSucceed)return void(attempt<maxRetries?setTimeout(()=>writeToDevice(attempt+1),retryInterval):(cleanup(),resolve(null)));await BleDataProcess.sleep(retryInterval),!responsed&&attempt<maxRetries?(console.log(tag,`未收到响应,准备第${attempt+1}次重试`),writeToDevice(attempt+1)):responsed||(console.warn(tag,`达到最大重试次数(${maxRetries}),未收到响应`),cleanup(),resolve(null))}catch(error){console.error(tag,"写入过程发生错误:",error),cleanup(),reject(error)}};timeoutId=setTimeout(()=>{console.warn(tag,"操作超时"),cleanup(),resolve(null)},(maxRetries+2)*retryInterval),commonfun.eventBus.on("setBleChangedCharacteristicValue",dataHandler),writeToDevice().catch(error=>{cleanup(),reject(error)})})},exports.setMTUAsync=(deviceId,mtu=512,delay=2500)=>new Promise((resolve,reject)=>{try{if(commonfun.getOS().isIOS)return resolve(!0);setTimeout(async()=>{await uni.setBLEMTU({deviceId:deviceId,mtu:mtu}),resolve(!0)},delay)}catch(error){console.error(error),reject(error)}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var BleDataProcess=require("../BleDataProcess.js"),commonfun=require("../commonfun.js");async function _writeAsync(deviceId,value){return console.log("deviceId, value: ",deviceId,value),!(!deviceId||!value)&&new Promise(resolve=>{const{isAndroid:isAndroid,isIOS:isIOS}=commonfun.getOS(),platform=commonfun.getPlatform();console.log("platform: ",platform),console.log("isAndroid, isIOS: ",isAndroid,isIOS);const writeType="mp-weixin"===platform||isAndroid?"writeNoResponse":"write";console.log("writeType: ",writeType),uni.writeBLECharacteristicValue({deviceId:deviceId,serviceId:"0000FF00-0000-1000-8000-00805F9B34FB",characteristicId:"0000FF02-0000-1000-8000-00805F9B34FB",writeType:writeType,value:value,success:res=>{console.error("res: 写入成功",res),resolve(!0)},fail:e=>{console.error("写入失败",e),resolve(!1)}}),isIOS&&setTimeout(()=>resolve(!0),50)})}exports.getData=async(deviceId,{command:command,commandVerifyHandler:commandVerifyHandler=hexArr=>({verified:!1,pkgLen:null}),pkgVerifyHandler:pkgVerifyHandler=pkg=>({verified:!1}),maxRetries:maxRetries=2,retryInterval:retryInterval=300},tag="")=>{if(!deviceId)throw new Error("deviceId is required");if(!command||command.length<=0)throw new Error("command is required");return new Promise((resolve,reject)=>{let isCompleted=!1,timeoutId=null,responsed=!1,len=null,pkg=[];const cmdContent=BleDataProcess.hexArr2ab(command),cleanup=()=>{isCompleted||(isCompleted=!0,clearTimeout(timeoutId),commonfun.eventBus.off("setBleChangedCharacteristicValue",dataHandler))},dataHandler=payload=>{if(!payload||payload.deviceId!==deviceId||!payload.value)return;const hexArr=BleDataProcess.ab2decimalArr(payload.value);if(console.log("hexArr: ",hexArr),console.warn(tag,"接收到数据:",BleDataProcess.hexArr2string(hexArr)),0!==hexArr.length){if(null===len){const{verified:verified,pkgLen:pkgLen}=commandVerifyHandler(hexArr);console.log("指令验证结果:",{verified:verified,pkgLen:pkgLen}),verified&&(len=pkgLen)}if(len){if(pkg=[...pkg,...hexArr],console.log("当前数据包:",pkg,`长度: ${pkg.length}/${len}`),pkg.length>=len){pkg=pkg.slice(0,len);const{verified:verified}=pkgVerifyHandler(pkg);console.log("数据包验证结果:",{verified:verified}),verified?(responsed=!0,cleanup(),resolve([...pkg])):(len=null,pkg=[])}}else pkg=[]}},writeToDevice=async(attempt=1)=>{try{console.warn(tag,`第${attempt}次写入指令:`,command.join("").replace(/0x/g,"").toUpperCase());const writeSucceed=await async function(deviceId,value){return console.log("value: ",value),console.log("deviceId: ",deviceId),!(!deviceId||!value)&&new Promise(async resolve=>{const n=Math.ceil(value.byteLength/20);let res;for(let i=0;i<n;i++){const _value=value.slice(20*i,20*(i+1));if(console.log("分包写入_value: ",_value),await BleDataProcess.sleep(150),res=await _writeAsync(deviceId,_value),console.log(`分包写入结果 ${i+1}/${n} : ${res}`),!res)return resolve(!1)}resolve(res)})}(deviceId,cmdContent);if(console.warn(tag,`第${attempt}次写入结果:`,writeSucceed?"成功":"失败"),!writeSucceed)return void(attempt<maxRetries?setTimeout(()=>writeToDevice(attempt+1),retryInterval):(cleanup(),resolve(null)));await BleDataProcess.sleep(retryInterval),!responsed&&attempt<maxRetries?(console.log(tag,`未收到响应,准备第${attempt+1}次重试`),writeToDevice(attempt+1)):responsed||(console.warn(tag,`达到最大重试次数(${maxRetries}),未收到响应`),cleanup(),resolve(null))}catch(error){console.error(tag,"写入过程发生错误:",error),cleanup(),reject(error)}};timeoutId=setTimeout(()=>{console.warn(tag,"操作超时"),cleanup(),resolve(null)},(maxRetries+2)*retryInterval),commonfun.eventBus.on("setBleChangedCharacteristicValue",dataHandler),writeToDevice().catch(error=>{cleanup(),reject(error)})})},exports.setMTUAsync=(deviceId,mtu=512,delay=2500)=>new Promise((resolve,reject)=>{try{if(commonfun.getOS().isIOS)return resolve(!0);setTimeout(async()=>{await uni.setBLEMTU({deviceId:deviceId,mtu:mtu}),resolve(!0)},delay)}catch(error){console.error(error),reject(error)}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var BleDataProcess=require("../BleDataProcess.js"),BleCmdAnalysis=require("./BleCmdAnalysis.js"),BleCmdFFAA=require("./BleCmdFFAA.js");const 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 BleCmdAnalysis.getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"PlanCMD_DD");if(data){const dataStr=BleDataProcess.hexArr2string(data),content=data.slice(4,data.length-3);result={data:data,dataStr:dataStr,status:BleDataProcess.hex2string(data[2]),len:data[3],content:content}}else result={status:0,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${BleDataProcess.decimalToHex(data.length,2)}`],check=BleDataProcess.generateCrc16modbusCheck([...addressCode,...commandCode,...dataLength,...data],!1),command=["0x3b","0x3c",...addressCode,...commandCode,...dataLength,...data,...check,"0x0d"];return BleCmdAnalysis.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]=BleDataProcess.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:BleDataProcess.hexArr2string(data),status:BleDataProcess.hex2string(data[10]),addr:BleDataProcess.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=BleDataProcess.hex2string(v1),result.productLen=v2,v)){const[productType,frontType,protocolV,level]=v.map(o=>BleDataProcess.hex2string(o));Object.assign(result,{productType:productType,frontType:frontType,protocolV:protocolV,level:level})}2==v1&&(result.hardwareFlag=BleDataProcess.hex2string(v1),result.hardwareLen=v2,result.hardwareV=BleDataProcess.hexArr2Assic(v)),3==v1&&(result.sofewareFlag=BleDataProcess.hex2string(v1),result.sofewareLen=v2,result.sofewareV=BleDataProcess.hexArr2Assic(v)),4==v1&&(result.pcbFlag=BleDataProcess.hex2string(v1),result.pcbLen=v2,result.pcbContent=BleDataProcess.hexArr2Assic(v))}return result},getDDA503Async=async deviceId=>{const hex=await BleCmdAnalysis.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]=BleDataProcess.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=BleDataProcess.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=BleDataProcess.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=BleDataProcess.decimalToHex(data[8])+BleDataProcess.decimalToHex(data[9]),surplusCapacity=Number((BleDataProcess.hexToDecimal(volumeHex)/n).toFixed(2)),normCapHex=BleDataProcess.decimalToHex(data[10])+BleDataProcess.decimalToHex(data[11]),normCap=Number((BleDataProcess.hexToDecimal(normCapHex)/n).toFixed(2)),cycleHex=BleDataProcess.decimalToHex(data[12])+BleDataProcess.decimalToHex(data[13]),cycleIndex=BleDataProcess.hexToDecimal(cycleHex),fccHex=BleDataProcess.decimalToHex(data[humidityIndex+3])+BleDataProcess.decimalToHex(data[humidityIndex+4]),fullChargeCapacity=Number((BleDataProcess.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=BleDataProcess.decimalToHex(data[20])+BleDataProcess.decimalToHex(data[21]),protVal=BleDataProcess.hexToDecimal(protectStateHex);let alarmIndex=2*data[26]+28,alarmStateHex=BleDataProcess.decimalToHex(data[alarmIndex])+BleDataProcess.decimalToHex(data[alarmIndex+1]),alarmsState=BleDataProcess.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:BleDataProcess.hex2string(data[2]),len:data[3],softwareV:BleDataProcess.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 BleCmdAnalysis.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]=BleDataProcess.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=BleDataProcess.hexArr2string(data),voltageList=[];for(let index=4;index<parseInt(data[3])+4;index+=2){let voltageHex=BleDataProcess.decimalToHex(data[index])+BleDataProcess.decimalToHex(data[index+1]),voltage=BleDataProcess.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}},resolveDDA500=data=>{if(!data)return null;return{dataStr:BleDataProcess.hexArr2string(data),status:BleDataProcess.hex2string(data[2]),len:data[3],type:data[5]}},getDD5AFBAsync=async(deviceId,type,value)=>{const _command=["0xFB","0x02",type,value],checks=BleDataProcess.generateCrcCheckSum(_command),command=["0xDD","0x5A",..._command,...checks,"0x77"];return console.log("command: ",command),BleCmdAnalysis.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=BleDataProcess.hexArr2string(data),content=data.slice(4,data.length-3);return{dataStr:dataStr,status:BleDataProcess.hex2string(data[2]),len:data[3],content:content}},getDDA505Async=async deviceId=>BleCmdAnalysis.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]=BleDataProcess.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:BleDataProcess.hexArr2string(data),status:BleDataProcess.hex2string(data[2]),len:data[3],hardwareV:BleDataProcess.hexArr2Assic(data.slice(4,data.length-3))}},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}};exports.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 BleDataProcess.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}},exports.enterFactory=async deviceId=>set_PlanCMD_DD(deviceId,"DD5A00025678FF3077"),exports.existFactory=async deviceId=>set_PlanCMD_DD(deviceId,"DD5A01022828ffad77"),exports.get3B3CAsync=get3B3CAsync,exports.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 BleCmdFFAA.getFFAA80Async(deviceId,"AT^VERSION?");_ffaa_80=BleCmdFFAA.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)}}),exports.getChipTypeAsync=async deviceId=>{const hex=await BleCmdAnalysis.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]=BleDataProcess.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},exports.getDD5A0AAsync=async(deviceId,value)=>{const _command=["0x0A","0x02",...BleDataProcess.stringToTwoHexArray(value)],checks=BleDataProcess.generateCrcCheckSum(_command),command=["0xDD","0x5A",..._command,...checks,"0x77"];return console.log("command: ",command),BleCmdAnalysis.getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&10==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},`DD5A_0A_${value}`)},exports.getDD5A0EAsync=async deviceId=>BleCmdAnalysis.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_复位"),exports.getDD5A17Async=async deviceId=>BleCmdAnalysis.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-清除电池循环次数"),exports.getDD5AAllAsync=async(deviceId,path,lengthHex,values,type)=>{const _command=[path,lengthHex,...values],checks=BleDataProcess.generateCrcCheckSum(_command),command=["0xDD","0x5A",..._command,...checks,"0x77"];return BleCmdAnalysis.getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&hexArr[1]==path,pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},`DD5A_${path}_${type}`)},exports.getDD5AE0Async=async(deviceId,value)=>{const hex=100*value,hexStr=BleDataProcess.decimalToHex(hex,4),_values=[`0x${hexStr.slice(0,2)}`,`0x${hexStr.slice(2,4)}`],_command=["0xE0","0x02",..._values],checks=BleDataProcess.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}),BleCmdAnalysis.getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&224==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"DD5A_E0")},exports.getDD5AE1Async=async(deviceId,value)=>{const _command=["0xE1","0x02","0x00",value],checks=BleDataProcess.generateCrcCheckSum(_command),command=["0xDD","0x5A",..._command,...checks,"0x77"];return BleCmdAnalysis.getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&225==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"DD5A_E1")},exports.getDD5AE4Async=async deviceId=>BleCmdAnalysis.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"),exports.getDD5AFAAsync=async(deviceId,value)=>{const hex=100*value,hexStr=BleDataProcess.decimalToHex(hex,4),_command=["0xFA","0x05","0x00","0x70","0x01",...[`0x${hexStr.slice(0,2)}`,`0x${hexStr.slice(2,4)}`]],checks=BleDataProcess.generateCrcCheckSum(_command),command=["0xDD","0x5A",..._command,...checks,"0x77"];return BleCmdAnalysis.getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&250==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"DD5A_FA")},exports.getDD5AFBAsync=getDD5AFBAsync,exports.getDDA503Async=getDDA503Async,exports.getDDA504Async=getDDA504Async,exports.getDDA505Async=getDDA505Async,exports.getDDA507Async=async deviceId=>BleCmdAnalysis.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]=BleDataProcess.generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA5_07历史运行履历总数"),exports.getDDA508Async=async(deviceId,i=0)=>{const _command=["0x08",`0x${i.toString(16).padStart(2,0)}`],checks=BleDataProcess.generateCrcCheckSum(_command),command=["0xDD","0xA5",..._command,...checks,"0x77"];return BleCmdAnalysis.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]=BleDataProcess.generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA5_08读取履历详情")},exports.getDDA5DCAsync=deviceId=>{const _command=["0xDE","0x00"],checks=BleDataProcess.generateCrcCheckSum(_command),command=["0xDD","0xA5",..._command,...checks,"0x77"];return BleCmdAnalysis.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]=BleDataProcess.generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA5_DC")},exports.getDDA5FAAsync=async(deviceId,paramNo,length)=>{const _values=[...paramNo,length],_command=["0xFA",BleDataProcess.decimalToHex(_values.length),..._values],checks=BleDataProcess.generateCrcCheckSum(_command),command=["0xDD","0xA5",..._command,...checks,"0x77"];return BleCmdAnalysis.getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&250==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"READ_DDA5_FA")},exports.getDDA5OldAsync=async(deviceId,path)=>{const values=[path,"0x00"],checks=BleDataProcess.generateCrcCheckSum(values),command=["0xDD","0xa5",...values,...checks,"0x77"];return BleCmdAnalysis.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]=BleDataProcess.generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA5_读旧协议读参")},exports.getProtectCountCmd=async deviceId=>{const data=await BleCmdAnalysis.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},exports.readExistFactory=async deviceId=>set_PlanCMD_DD(deviceId,"DD5A01020000FFFD77"),exports.resetCapacity=deviceId=>BleCmdAnalysis.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"),exports.resolve3B3C=resolve3B3C,exports.resolveBMSCmd=data=>{if(!data)return null;return{dataStr:BleDataProcess.hexArr2string(data),status:BleDataProcess.hex2string(data[2]),len:data[3]}},exports.resolveBaseDD=resolveBaseDD,exports.resolveDD5A0A=data=>{if(!data)return null;const dataStr=BleDataProcess.hexArr2string(data),statusDec=data[2],len=data[3],succeeded=0===statusDec;return{dataStr:dataStr,status:BleDataProcess.hex2string(statusDec),len:len,succeeded:succeeded,message:succeeded?"CMD_EXEC_SUCCESS":"CMD_EXEC_FAIL"}},exports.resolveDDA500=resolveDDA500,exports.resolveDDA503=resolveDDA503,exports.resolveDDA504=resolveDDA504,exports.resolveDDA505=resolveDDA505,exports.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:BleDataProcess.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("")}},exports.resolveDDA5DC=data=>{if(!data)return null;const dataStr=BleDataProcess.hexArr2string(data),status=BleDataProcess.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}},exports.resolveDDA5FA=data=>{if(!data)return null;return{dataStr:BleDataProcess.hexArr2string(data),status:BleDataProcess.hex2string(data[2]),len:data[3],type:data[5],value:data.slice(7,-3)}},exports.resolveProtections=resolveProtections,exports.sendBMSAsync=async(deviceId,values)=>{const command=values.match(/[0-9a-fA-F]{2}/g)?.map(item=>`0x${item}`)||[];return BleCmdAnalysis.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]}`)},exports.setDDA5FAAsync=async(deviceId,paramNo,valueLength,content)=>{const _values=[...paramNo,valueLength,...content],_command=["0xFA",BleDataProcess.decimalToHex(_values.length),..._values],checks=BleDataProcess.generateCrcCheckSum(_command),command=["0xDD","0x5A",..._command,...checks,"0x77"];return BleCmdAnalysis.getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&250==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"SET_DDA5_FA")},exports.setDDA5OldAsync=async(deviceId,path,value,type="")=>{const values=[path,"0x02",...value],checks=BleDataProcess.generateCrcCheckSum(values),command=["0xDD","0x5A",...values,...checks,"0x77"];return BleCmdAnalysis.getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&hexArr[1]==path,pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"DDA5_写旧协议读参"+type)},exports.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 BleCmdAnalysis.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=BleDataProcess.hexArr2string(data),content=data.slice(12,data.length-3);result={dataStr:dataStr,status:128==data[10]?1:0,addr:BleDataProcess.hexArr2string(data.slice(2,10)),content:content}}}catch(error){console.error(error)}return result},exports.set_PlanCMD_DD=set_PlanCMD_DD;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var BleDataProcess=require("../BleDataProcess.js"),BleCmdAnalysis=require("./BleCmdAnalysis.js"),BleCmdFFAA=require("./BleCmdFFAA.js");const 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 BleCmdAnalysis.getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"PlanCMD_DD");if(data){const dataStr=BleDataProcess.hexArr2string(data),content=data.slice(4,data.length-3);result={data:data,dataStr:dataStr,status:BleDataProcess.hex2string(data[2]),len:data[3],content:content}}else result={status:0,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${BleDataProcess.decimalToHex(data.length,2)}`],check=BleDataProcess.generateCrc16modbusCheck([...addressCode,...commandCode,...dataLength,...data],!1),command=["0x3b","0x3c",...addressCode,...commandCode,...dataLength,...data,...check,"0x0d"];return BleCmdAnalysis.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]=BleDataProcess.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:BleDataProcess.hexArr2string(data),status:BleDataProcess.hex2string(data[10]),addr:BleDataProcess.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=BleDataProcess.hex2string(v1),result.productLen=v2,v)){const[productType,frontType,protocolV,level]=v.map(o=>BleDataProcess.hex2string(o));Object.assign(result,{productType:productType,frontType:frontType,protocolV:protocolV,level:level})}2==v1&&(result.hardwareFlag=BleDataProcess.hex2string(v1),result.hardwareLen=v2,result.hardwareV=BleDataProcess.hexArr2Assic(v)),3==v1&&(result.sofewareFlag=BleDataProcess.hex2string(v1),result.sofewareLen=v2,result.sofewareV=BleDataProcess.hexArr2Assic(v)),4==v1&&(result.pcbFlag=BleDataProcess.hex2string(v1),result.pcbLen=v2,result.pcbContent=BleDataProcess.hexArr2Assic(v))}return result},getDDA503Async=async deviceId=>{const hex=await BleCmdAnalysis.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]=BleDataProcess.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=BleDataProcess.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=BleDataProcess.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=BleDataProcess.decimalToHex(data[8])+BleDataProcess.decimalToHex(data[9]),surplusCapacity=Number((BleDataProcess.hexToDecimal(volumeHex)/n).toFixed(2)),normCapHex=BleDataProcess.decimalToHex(data[10])+BleDataProcess.decimalToHex(data[11]),normCap=Number((BleDataProcess.hexToDecimal(normCapHex)/n).toFixed(2)),cycleHex=BleDataProcess.decimalToHex(data[12])+BleDataProcess.decimalToHex(data[13]),cycleIndex=BleDataProcess.hexToDecimal(cycleHex),fccHex=BleDataProcess.decimalToHex(data[humidityIndex+3])+BleDataProcess.decimalToHex(data[humidityIndex+4]),fullChargeCapacity=Number((BleDataProcess.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=BleDataProcess.decimalToHex(data[20])+BleDataProcess.decimalToHex(data[21]),protVal=BleDataProcess.hexToDecimal(protectStateHex);let alarmIndex=2*data[26]+28,alarmStateHex=BleDataProcess.decimalToHex(data[alarmIndex])+BleDataProcess.decimalToHex(data[alarmIndex+1]),alarmsState=BleDataProcess.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:BleDataProcess.hex2string(data[2]),len:data[3],softwareV:BleDataProcess.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 BleCmdAnalysis.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]=BleDataProcess.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=BleDataProcess.hexArr2string(data),voltageList=[];for(let index=4;index<parseInt(data[3])+4;index+=2){let voltageHex=BleDataProcess.decimalToHex(data[index])+BleDataProcess.decimalToHex(data[index+1]),voltage=BleDataProcess.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}},resolveDDA500=data=>{if(!data)return null;return{dataStr:BleDataProcess.hexArr2string(data),status:BleDataProcess.hex2string(data[2]),len:data[3],type:data[5]}},getDD5AFBAsync=async(deviceId,type,value)=>{const _command=["0xFB","0x02",type,value],checks=BleDataProcess.generateCrcCheckSum(_command),command=["0xDD","0x5A",..._command,...checks,"0x77"];return console.log("command: ",command),BleCmdAnalysis.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=BleDataProcess.hexArr2string(data),content=data.slice(4,data.length-3);return{dataStr:dataStr,status:BleDataProcess.hex2string(data[2]),len:data[3],content:content}},getDDA505Async=async deviceId=>BleCmdAnalysis.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]=BleDataProcess.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:BleDataProcess.hexArr2string(data),status:BleDataProcess.hex2string(data[2]),len:data[3],hardwareV:BleDataProcess.hexArr2Assic(data.slice(4,data.length-3))}},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}};exports.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 BleDataProcess.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}},exports.enterFactory=async deviceId=>set_PlanCMD_DD(deviceId,"DD5A00025678FF3077"),exports.existFactory=async deviceId=>set_PlanCMD_DD(deviceId,"DD5A01022828ffad77"),exports.get3B3CAsync=get3B3CAsync,exports.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 BleCmdFFAA.getFFAA80Async(deviceId,"AT^VERSION?");_ffaa_80=BleCmdFFAA.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)}}),exports.getChipTypeAsync=async deviceId=>{const hex=await BleCmdAnalysis.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]=BleDataProcess.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},exports.getDD5A0AAsync=async(deviceId,value)=>{const _command=["0x0A","0x02",...BleDataProcess.stringToTwoHexArray(value)],checks=BleDataProcess.generateCrcCheckSum(_command),command=["0xDD","0x5A",..._command,...checks,"0x77"];return console.log("command: ",command),BleCmdAnalysis.getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&10==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},`DD5A_0A_${value}`)},exports.getDD5A0EAsync=async deviceId=>BleCmdAnalysis.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_复位"),exports.getDD5A17Async=async deviceId=>BleCmdAnalysis.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-清除电池循环次数"),exports.getDD5AAllAsync=async(deviceId,path,lengthHex,values,type)=>{const _command=[path,lengthHex,...values],checks=BleDataProcess.generateCrcCheckSum(_command),command=["0xDD","0x5A",..._command,...checks,"0x77"];return BleCmdAnalysis.getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&hexArr[1]==path,pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},`DD5A_${path}_${type}`)},exports.getDD5AE0Async=async(deviceId,value)=>{const hex=100*value,hexStr=BleDataProcess.decimalToHex(hex,4),_values=[`0x${hexStr.slice(0,2)}`,`0x${hexStr.slice(2,4)}`],_command=["0xE0","0x02",..._values],checks=BleDataProcess.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}),BleCmdAnalysis.getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&224==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"DD5A_E0")},exports.getDD5AE1Async=async(deviceId,value)=>{const _command=["0xE1","0x02","0x00",value],checks=BleDataProcess.generateCrcCheckSum(_command),command=["0xDD","0x5A",..._command,...checks,"0x77"];return BleCmdAnalysis.getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&225==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"DD5A_E1")},exports.getDD5AE4Async=async deviceId=>BleCmdAnalysis.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"),exports.getDD5AFAAsync=async(deviceId,value)=>{const hex=100*value,hexStr=BleDataProcess.decimalToHex(hex,4),_command=["0xFA","0x05","0x00","0x70","0x01",...[`0x${hexStr.slice(0,2)}`,`0x${hexStr.slice(2,4)}`]],checks=BleDataProcess.generateCrcCheckSum(_command),command=["0xDD","0x5A",..._command,...checks,"0x77"];return BleCmdAnalysis.getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&250==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"DD5A_FA")},exports.getDD5AFBAsync=getDD5AFBAsync,exports.getDDA4F0Async=async deviceId=>{const command=["0xDD","0xA4","0xF0","0x00"],checks=BleDataProcess.generateCrcCheckSum(command.slice(2)),fullCommand=[...command,...checks,"0x77"];return BleCmdAnalysis.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]=BleDataProcess.generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA4_F0")},exports.getDDA503Async=getDDA503Async,exports.getDDA504Async=getDDA504Async,exports.getDDA505Async=getDDA505Async,exports.getDDA506Async=async deviceId=>BleCmdAnalysis.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]=BleDataProcess.generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA5_06"),exports.getDDA507Async=async deviceId=>BleCmdAnalysis.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]=BleDataProcess.generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA5_07历史运行履历总数"),exports.getDDA508Async=async(deviceId,i=0)=>{const _command=["0x08",`0x${i.toString(16).padStart(2,0)}`],checks=BleDataProcess.generateCrcCheckSum(_command),command=["0xDD","0xA5",..._command,...checks,"0x77"];return BleCmdAnalysis.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]=BleDataProcess.generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA5_08读取履历详情")},exports.getDDA5DCAsync=deviceId=>{const _command=["0xDE","0x00"],checks=BleDataProcess.generateCrcCheckSum(_command),command=["0xDD","0xA5",..._command,...checks,"0x77"];return BleCmdAnalysis.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]=BleDataProcess.generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA5_DC")},exports.getDDA5FAAsync=async(deviceId,paramNo,length)=>{const _values=[...paramNo,length],_command=["0xFA",BleDataProcess.decimalToHex(_values.length),..._values],checks=BleDataProcess.generateCrcCheckSum(_command),command=["0xDD","0xA5",..._command,...checks,"0x77"];return BleCmdAnalysis.getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&250==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"READ_DDA5_FA")},exports.getDDA5OldAsync=async(deviceId,path)=>{const values=[path,"0x00"],checks=BleDataProcess.generateCrcCheckSum(values),command=["0xDD","0xa5",...values,...checks,"0x77"];return BleCmdAnalysis.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]=BleDataProcess.generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA5_读旧协议读参")},exports.getProtectCountCmd=async deviceId=>{const data=await BleCmdAnalysis.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},exports.readExistFactory=async deviceId=>set_PlanCMD_DD(deviceId,"DD5A01020000FFFD77"),exports.resetCapacity=deviceId=>BleCmdAnalysis.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"),exports.resolve3B3C=resolve3B3C,exports.resolveBMSCmd=data=>{if(!data)return null;return{dataStr:BleDataProcess.hexArr2string(data),status:BleDataProcess.hex2string(data[2]),len:data[3]}},exports.resolveBaseDD=resolveBaseDD,exports.resolveDD5A0A=data=>{if(!data)return null;const dataStr=BleDataProcess.hexArr2string(data),statusDec=data[2],len=data[3],succeeded=0===statusDec;return{dataStr:dataStr,status:BleDataProcess.hex2string(statusDec),len:len,succeeded:succeeded,message:succeeded?"CMD_EXEC_SUCCESS":"CMD_EXEC_FAIL"}},exports.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:BleDataProcess.hexArr2string(data)}}return null},exports.resolveDDA500=resolveDDA500,exports.resolveDDA503=resolveDDA503,exports.resolveDDA504=resolveDDA504,exports.resolveDDA505=resolveDDA505,exports.resolveDDA506=data=>{if(!data)return null;if(6==data[1]&&0==data[2]&&6==data[3]){const seconds=BleDataProcess.fromBCD(data[4]),minutes=BleDataProcess.fromBCD(data[5]),hours=BleDataProcess.fromBCD(data[6]),day=BleDataProcess.fromBCD(data[7]),month=BleDataProcess.fromBCD(data[8]),timeStr=`${2e3+BleDataProcess.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,BleDataProcess.isWithin30Minutes(timeStr)),BleDataProcess.isWithin30Minutes(timeStr)}return!1},exports.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:BleDataProcess.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("")}},exports.resolveDDA5DC=data=>{if(!data)return null;const dataStr=BleDataProcess.hexArr2string(data),status=BleDataProcess.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}},exports.resolveDDA5FA=data=>{if(!data)return null;return{dataStr:BleDataProcess.hexArr2string(data),status:BleDataProcess.hex2string(data[2]),len:data[3],type:data[5],value:data.slice(7,-3)}},exports.resolveProtections=resolveProtections,exports.sendBMSAsync=async(deviceId,values)=>{const command=values.match(/[0-9a-fA-F]{2}/g)?.map(item=>`0x${item}`)||[];return BleCmdAnalysis.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]}`)},exports.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",...[BleDataProcess.toBCD(seconds),BleDataProcess.toBCD(minutes),128|BleDataProcess.toBCD(hours),BleDataProcess.toBCD(day),BleDataProcess.toBCD(month),BleDataProcess.toBCD(year-2e3)].map(b=>"0x"+b.toString(16).padStart(2,"0"))],checks=BleDataProcess.generateCrcCheckSum(content),command=["0xDD","0x5A",...content,...checks,"0x77"];return console.log("command: ",command),BleCmdAnalysis.getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&227==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"SET_DDA5_E3")},exports.setDDA5FAAsync=async(deviceId,paramNo,valueLength,content)=>{const _values=[...paramNo,valueLength,...content],_command=["0xFA",BleDataProcess.decimalToHex(_values.length),..._values],checks=BleDataProcess.generateCrcCheckSum(_command),command=["0xDD","0x5A",..._command,...checks,"0x77"];return BleCmdAnalysis.getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&250==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"SET_DDA5_FA")},exports.setDDA5OldAsync=async(deviceId,path,value,type="")=>{const values=[path,"0x02",...value],checks=BleDataProcess.generateCrcCheckSum(values),command=["0xDD","0x5A",...values,...checks,"0x77"];return BleCmdAnalysis.getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&hexArr[1]==path,pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"DDA5_写旧协议读参"+type)},exports.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 BleCmdAnalysis.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=BleDataProcess.hexArr2string(data),content=data.slice(12,data.length-3);result={dataStr:dataStr,status:128==data[10]?1:0,addr:BleDataProcess.hexArr2string(data.slice(2,10)),content:content}}}catch(error){console.error(error)}return result},exports.set_PlanCMD_DD=set_PlanCMD_DD;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var BleDataProcess=require("../BleDataProcess.js"),BleCmdAnalysis=require("./BleCmdAnalysis.js");exports.getDDA420Async=async deviceId=>{const _command=["0x20","0x00"],checks=BleDataProcess.generateCrcCheckSum(_command),command=["0xdd","0xa4",..._command,...checks,"0x77"];return BleCmdAnalysis.getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&32==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=BleDataProcess.generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA420")},exports.getDDA421Async=async deviceId=>{const _command=["0x21","0x00"],checks=BleDataProcess.generateCrcCheckSum(_command),command=["0xdd","0xa4",..._command,...checks,"0x77"];return(void 0).getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&33==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=BleDataProcess.generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA421")},exports.getDDA422Async=async(deviceId,startReg,endReg)=>{const startRegHex=BleDataProcess.decimalToHex(startReg,4),endRegHex=BleDataProcess.decimalToHex(endReg,4),_command=["0x22","0x04",...[parseInt(startRegHex.slice(0,2),16),parseInt(startRegHex.slice(2,4),16)],...[parseInt(endRegHex.slice(0,2),16),parseInt(endRegHex.slice(2,4),16)]],checks=BleDataProcess.generateCrcCheckSum(_command),command=["0xDD","0xA4",..._command,...checks,"0x77"];return BleCmdAnalysis.getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&34==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=BleDataProcess.generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA422")},exports.getDDA423Async=async(deviceId,startReg,endReg,values,valuesLength)=>{const startRegHex=BleDataProcess.decimalToHex(startReg,4),startRegArr=[parseInt(startRegHex.slice(0,2),16),parseInt(startRegHex.slice(2,4),16)],endRegHex=BleDataProcess.decimalToHex(endReg,4),endRegArr=[parseInt(endRegHex.slice(0,2),16),parseInt(endRegHex.slice(2,4),16)],valueRegHex=BleDataProcess.decimalToHex(values,2*valuesLength);let valueArr=[];for(let i=0;i<valuesLength;i++){const hex=valueRegHex.slice(2*i,2*i+2);valueArr.push(parseInt(hex.slice(0,2),16))}const _command=["0x23",BleDataProcess.decimalToHex(4+valuesLength,2),...startRegArr,...endRegArr,...valueArr],checks=BleDataProcess.generateCrcCheckSum(_command),command=["0xDD","0xA4",..._command,...checks,"0x77"];return BleCmdAnalysis.getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&35==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=BleDataProcess.generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA423")},exports.getDDA425Async=async(deviceId,type)=>{const _command=["0x25","0x01",type],checks=BleDataProcess.generateCrcCheckSum(_command),command=["0xDD","0xA4",..._command,...checks,"0x77"];return console.log("command: ",command),BleCmdAnalysis.getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&37==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"DDA425")},exports.getDDA426Async=async(deviceId,testMode=0,outputVoltage=0,outputCurrent=0)=>{const clamp32=v=>((v=Number(v)||0)<0&&(v=0),v>4294967295&&(v=4294967295),v);testMode=2===testMode?2:0,outputVoltage=clamp32(outputVoltage),outputCurrent=clamp32(outputCurrent);const to4Bytes=val=>{const hex=commonfun.decimalToHex(val,8);return[0,2,4,6].map(i=>parseInt(hex.slice(i,i+2),16))},voltageArr=to4Bytes(outputVoltage),currentArr=to4Bytes(outputCurrent),_command=["0x26",`0x${commonfun.decimalToHex(9,2)}`,255&testMode,...voltageArr,...currentArr].map(o=>"number"==typeof o?`0x${("00"+o.toString(16)).slice(-2)}`:o),_commandNums=_command.map(h=>parseInt(h,16)),checks=BleDataProcess.generateCrcCheckSum(_commandNums),command=["0xDD","0xA4",..._command,...checks,"0x77"];return BleCmdAnalysis.getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&38==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"DDA426(充电测试)")},exports.getDDA427Async=async(deviceId,startTime,endTime,granularity=2,type=1)=>{const startTimeHex=startTime.toString(16).padStart(8,"0"),endTimeHex=endTime.toString(16).padStart(8,"0"),startTimeArr=[parseInt(startTimeHex.slice(0,2),16),parseInt(startTimeHex.slice(2,4),16),parseInt(startTimeHex.slice(4,6),16),parseInt(startTimeHex.slice(6,8),16)],endTimeArr=[parseInt(endTimeHex.slice(0,2),16),parseInt(endTimeHex.slice(2,4),16),parseInt(endTimeHex.slice(4,6),16),parseInt(endTimeHex.slice(6,8),16)],historyType=BleDataProcess.decimalToHex(type,2),granularityArr=BleDataProcess.decimalToHex(granularity,2),_command=["0x27","0x0A",...startTimeArr,...endTimeArr,historyType,granularityArr],checks=BleDataProcess.generateCrcCheckSum(_command),command=["0xDD","0xA4",..._command,...checks,"0x77"];return console.log("getDDA427Async getDDA427Async",startTimeHex,endTimeHex,startTimeArr,endTimeArr,granularity,command),BleCmdAnalysis.getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&39==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=BleDataProcess.generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA427")},exports.getDDA429Async=async(deviceId,id)=>{const idHex=BleDataProcess.decimalToHex(id,8),_command=["0x29","0x04",...[parseInt(idHex.slice(0,2),16),parseInt(idHex.slice(2,4),16),parseInt(idHex.slice(4,6),16),parseInt(idHex.slice(4,6),16),parseInt(idHex.slice(6,8),16)]],checks=BleDataProcess.generateCrcCheckSum(_command),command=["0xdd","0xa4",..._command,...checks,"0x77"];return BleCmdAnalysis.getData(deviceId,{command:command,commandVerifyHandler:hexArr=>{if(221!=hexArr[0]||41!=hexArr[1])return{verified:!1,pkgLen:null};if(hexArr.length<8)return{verified:!1,pkgLen:null};if(hexArr.length>=36){const respIdHex=BleDataProcess.decimalToHex(hexArr[32])+BleDataProcess.decimalToHex(hexArr[33])+BleDataProcess.decimalToHex(hexArr[34])+BleDataProcess.decimalToHex(hexArr[35]);if(BleDataProcess.hexToDecimal(respIdHex)!==id)return{verified:!1,pkgLen:null}}return{verified:!0,pkgLen:hexArr[3]+7}},pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=BleDataProcess.generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA429")},exports.resolveDDA420=data=>{if(!data)return null;const dataStr=BleDataProcess.hexArr2string(data);let n=4;const workStatus=data[n++],chargeStatus=data[n++],chargeVoltage=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),chargeElectricity=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),chargePower=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),chargeTemperature=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++]))/10,chargeCapacity=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),chargeTime=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),chargeRemainTime=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),chargeCompleteTime=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),outputVoltagePercent=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),outputElectricityPercent=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),outputVoltage=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),outputElectricity=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),batteryVoltage=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),swtichStatusArr=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])).toString(2).padStart(16,"0").split("").reverse(),chargeSwitch="1"==swtichStatusArr[0],preChargeSwitch="1"==swtichStatusArr[1],fanSwitch="1"==swtichStatusArr[2],protectStatusArr=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])).toString(2).padStart(32,"0").split("").reverse();let protectStatusIndexs=[];for(let i=0;i<protectStatusArr.length;i++)"1"==protectStatusArr[i]&&protectStatusIndexs.push(i);const alarmStatusArr=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])).toString(2).padStart(32,"0").split("").reverse();let alarmStatusIndexs=[];for(let i=0;i<alarmStatusArr.length;i++)"1"==alarmStatusArr[i]&&alarmStatusIndexs.push(i);return{dataStr:dataStr,workStatus:workStatus,chargeStatus:chargeStatus,chargeVoltage:chargeVoltage,chargeElectricity:chargeElectricity,chargePower:chargePower,chargeTemperature:chargeTemperature,chargeCapacity:chargeCapacity,chargeTime:chargeTime,chargeRemainTime:chargeRemainTime,chargeCompleteTime:chargeCompleteTime,outputVoltagePercent:outputVoltagePercent,outputElectricityPercent:outputElectricityPercent,outputVoltage:outputVoltage,outputElectricity:outputElectricity,batteryVoltage:batteryVoltage,chargeSwitch:chargeSwitch,preChargeSwitch:preChargeSwitch,fanSwitch:fanSwitch,protectStatusIndexs:protectStatusIndexs,alarmStatusIndexs:alarmStatusIndexs,communicationMode:data[n++]}},exports.resolveDDA421=data=>{if(!data)return null;const dataStr=BleDataProcess.hexArr2string(data),batteryVoltageHex=BleDataProcess.decimalToHex(data[4])+BleDataProcess.decimalToHex(data[5])+BleDataProcess.decimalToHex(data[6])+BleDataProcess.decimalToHex(data[7]),batteryVoltage=BleDataProcess.hexToDecimal(batteryVoltageHex),batteryCurrentHex=BleDataProcess.decimalToHex(data[8])+BleDataProcess.decimalToHex(data[9])+BleDataProcess.decimalToHex(data[10])+BleDataProcess.decimalToHex(data[11]),batteryCurrent=BleDataProcess.hexToDecimal(batteryCurrentHex),batteryType=data[12],batterySeries=data[13],batteryCapacityHex=BleDataProcess.decimalToHex(data[14])+BleDataProcess.decimalToHex(data[15])+BleDataProcess.decimalToHex(data[16])+BleDataProcess.decimalToHex(data[17]),batteryCapacity=BleDataProcess.hexToDecimal(batteryCapacityHex),batterySOC=data[18],batteryTempHex=BleDataProcess.decimalToHex(data[19])+BleDataProcess.decimalToHex(data[20]),batteryTemperature=BleDataProcess.hexToDecimal(batteryTempHex)/10,heatingStatus=data[21],heatingCurrentHex=BleDataProcess.decimalToHex(data[22])+BleDataProcess.decimalToHex(data[23])+BleDataProcess.decimalToHex(data[24])+BleDataProcess.decimalToHex(data[25]),heatingCurrent=BleDataProcess.hexToDecimal(heatingCurrentHex),protectStatusHex=BleDataProcess.decimalToHex(data[26])+BleDataProcess.decimalToHex(data[27]),protectStatusArr=BleDataProcess.hexToDecimal(protectStatusHex).toString(2).padStart(16,"0").split("").reverse();let protectStatusIndexs=[];for(let i=0;i<protectStatusArr.length;i++)"1"==protectStatusArr[i]&&protectStatusIndexs.push(i);const alarmStatusHex=BleDataProcess.decimalToHex(data[28])+BleDataProcess.decimalToHex(data[29]),alarmStatusArr=BleDataProcess.hexToDecimal(alarmStatusHex).toString(2).padStart(16,"0").split("").reverse();let alarmStatusIndexs=[];for(let i=0;i<alarmStatusArr.length;i++)"1"==alarmStatusArr[i]&&alarmStatusIndexs.push(i);return{dataStr:dataStr,batteryVoltage:batteryVoltage,batteryCurrent:batteryCurrent,batteryType:batteryType,batterySeries:batterySeries,batteryCapacity:batteryCapacity,batterySOC:batterySOC,batteryTemperature:batteryTemperature,heatingStatus:heatingStatus,heatingCurrent:heatingCurrent,protectStatusIndexs:protectStatusIndexs,alarmStatusIndexs:alarmStatusIndexs}},exports.resolveDDA422=data=>{if(!data)return null;const dataStr=BleDataProcess.hexArr2string(data),startRegHex=BleDataProcess.decimalToHex(data[4])+BleDataProcess.decimalToHex(data[5]),startReg=BleDataProcess.hexToDecimal(startRegHex),endRegHex=BleDataProcess.decimalToHex(data[6])+BleDataProcess.decimalToHex(data[7]);return{dataStr:dataStr,startReg:startReg,endReg:BleDataProcess.hexToDecimal(endRegHex),regData:data.slice(8,data.length-3)}},exports.resolveDDA423=data=>{if(!data)return null;return{dataStr:BleDataProcess.hexArr2string(data),status:BleDataProcess.hex2string(data[2])}},exports.resolveDDA425=data=>{if(!data)return null;return{dataStr:BleDataProcess.hexArr2string(data),status:BleDataProcess.hex2string(data[2])}},exports.resolveDDA426=data=>{if(!data)return null;return{dataStr:BleDataProcess.hexArr2string(data),status:BleDataProcess.hex2string(data[2])}},exports.resolveDDA427=data=>{if(!data)return null;const dataStr=BleDataProcess.hexArr2string(data),startTimeHex=BleDataProcess.decimalToHex(data[4])+BleDataProcess.decimalToHex(data[5])+BleDataProcess.decimalToHex(data[6])+BleDataProcess.decimalToHex(data[7]),startTime=BleDataProcess.hexToDecimal(startTimeHex),endTimeHex=BleDataProcess.decimalToHex(data[8])+BleDataProcess.decimalToHex(data[9])+BleDataProcess.decimalToHex(data[10])+BleDataProcess.decimalToHex(data[11]),endTime=BleDataProcess.hexToDecimal(endTimeHex),historyType=data[12],granularity=data[13],count=data[14];let history=[];for(let i=0;i<count;i++){const base=15+8*i,voltageHex=BleDataProcess.decimalToHex(data[base])+BleDataProcess.decimalToHex(data[base+1])+BleDataProcess.decimalToHex(data[base+2])+BleDataProcess.decimalToHex(data[base+3]),voltage=BleDataProcess.hexToDecimal(voltageHex),currentHex=BleDataProcess.decimalToHex(data[base+4])+BleDataProcess.decimalToHex(data[base+5])+BleDataProcess.decimalToHex(data[base+6])+BleDataProcess.decimalToHex(data[base+7]),current=BleDataProcess.hexToDecimal(currentHex);history.push({current:current,voltage:voltage})}return console.log("historyType",historyType),{dataStr:dataStr,startTime:startTime,endTime:endTime,historyType:historyType,granularity:granularity,count:count,history:history}},exports.resolveDDA429=data=>{if(!data)return null;const dataStr=BleDataProcess.hexArr2string(data);let n=4;const workStatus=data[n++],chargeStatus=data[n++],chargeVoltage=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),chargeElectricity=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),chargePower=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),chargeTemperature=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++]))/10,chargeCapacity=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),chargeTime=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),chargeRemainTime=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),chargeCompleteTime=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),outputVoltagePercent=data[n++],outputElectricityPercent=data[n++],id1=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),outputElectricity=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),id=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),swtichStatusArr=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])).toString(2).padStart(16,"0").split("").reverse(),chargeSwitch="1"==swtichStatusArr[0],preChargeSwitch="1"==swtichStatusArr[1],fanSwitch="1"==swtichStatusArr[2],protectStatusArr=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])).toString(2).padStart(32,"0").split("").reverse();let protectStatusIndexs=[];for(let i=0;i<protectStatusArr.length;i++)"1"==protectStatusArr[i]&&protectStatusIndexs.push(i);const alarmStatusArr=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])).toString(2).padStart(32,"0").split("").reverse();let alarmStatusIndexs=[];for(let i=0;i<alarmStatusArr.length;i++)"1"==alarmStatusArr[i]&&alarmStatusIndexs.push(i);return{dataStr:dataStr,workStatus:workStatus,chargeStatus:chargeStatus,chargeVoltage:chargeVoltage,chargeElectricity:chargeElectricity,chargePower:chargePower,chargeTemperature:chargeTemperature,chargeCapacity:chargeCapacity,chargeTime:chargeTime,chargeRemainTime:chargeRemainTime,chargeCompleteTime:chargeCompleteTime,outputVoltagePercent:outputVoltagePercent,outputElectricityPercent:outputElectricityPercent,id:id,outputElectricity:outputElectricity,id1:id1,chargeSwitch:chargeSwitch,preChargeSwitch:preChargeSwitch,fanSwitch:fanSwitch,protectStatusIndexs:protectStatusIndexs,alarmStatusIndexs:alarmStatusIndexs}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});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},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},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)}`]},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}),decimalToHex=(decimal,padding=2)=>Number(decimal).toString(16).padStart(padding,"0"),hex2string=hex=>("00"+hex.toString(16)).slice(-2).toUpperCase(),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,"")};exports.ab2decimalArr=buffer=>Array.prototype.map.call(new Uint8Array(buffer),bit=>bit),exports.ab2hex=buffer=>Array.prototype.map.call(new Uint8Array(buffer),function(bit){return("00"+bit.toString(16)).slice(-2)}).join(""),exports.arrayBufferToHexArray=arrayBufferToHexArray,exports.base64ToHexArray=(base64,withPrefix=!0)=>{const arrayBuffer=uni.base64ToArrayBuffer(base64);return arrayBufferToHexArray(arrayBuffer,withPrefix)},exports.checkSum=checkSum,exports.crc16modbus=crc16modbus,exports.crcCheckSum=crcCheckSum,exports.decimalToHex=decimalToHex,exports.decimalToHex0x=(decimal,padding=2)=>"0x"+Number(decimal).toString(16).padStart(padding,"0"),exports.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)}`]},exports.extractBits=(number,start,end)=>number>>start&(1<<end-start+1)-1,exports.generateCheckSum=generateCheckSum,exports.generateCrc16modbusCheck=(data,swapNeed=!1)=>{const hex=crc16modbus(data,swapNeed),hexStr=decimalToHex(hex,4);return[`0x${hexStr.slice(0,2)}`,`0x${hexStr.slice(2,4)}`]},exports.generateCrcCheckSum=data=>{const hex=crcCheckSum(data),hexStr=decimalToHex(hex,4);return[`0x${hexStr.slice(0,2)}`,`0x${hexStr.slice(2,4)}`]},exports.getParamBaseValue=arr=>{const hexString=arr.map(el=>decimalToHex(el)).join("");return parseInt(hexString,16)},exports.hex2Ascii=(value=[])=>{const hexString=value.join("");return hexStrAscii(hexString)},exports.hex2Binary=(hex,len=0)=>parseInt(hex,16).toString(2).padStart(len,"0"),exports.hex2string=hex2string,exports.hexArr2Assic=(hexArr=[])=>String.fromCharCode(...hexArr).replace(/\u0000/g,""),exports.hexArr2ab=hexArr=>{const buffer=new ArrayBuffer(hexArr.length),dataView=new DataView(buffer);return hexArr.forEach((hex,i)=>dataView.setUint8(i,hex)),buffer},exports.hexArr2string=(hexArr=[],connector="")=>hexArr.map(o=>hex2string(o)).join(connector),exports.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},exports.hexStrAscii=hexStrAscii,exports.hexStringToBinary=hexString=>parseInt(hexString,16).toString(2),exports.hexToDecimal=hex=>parseInt(hex,16),exports.sleep=(n=500)=>new Promise(r=>setTimeout(()=>r(!0),n)),exports.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},exports.stringToTwoHexArray=str=>{const paddedStr=str.padStart(4,"0");return[`0x${paddedStr.slice(0,2)}`,`0x${paddedStr.slice(2,4)}`]};
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});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},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},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)}`]},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}),decimalToHex=(decimal,padding=2)=>Number(decimal).toString(16).padStart(padding,"0"),hex2string=hex=>("00"+hex.toString(16)).slice(-2).toUpperCase(),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,"")},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()};exports.ab2decimalArr=buffer=>Array.prototype.map.call(new Uint8Array(buffer),bit=>bit),exports.ab2hex=buffer=>Array.prototype.map.call(new Uint8Array(buffer),function(bit){return("00"+bit.toString(16)).slice(-2)}).join(""),exports.arrayBufferToHexArray=arrayBufferToHexArray,exports.base64ToHexArray=(base64,withPrefix=!0)=>{const arrayBuffer=uni.base64ToArrayBuffer(base64);return arrayBufferToHexArray(arrayBuffer,withPrefix)},exports.checkSum=checkSum,exports.crc16modbus=crc16modbus,exports.crcCheckSum=crcCheckSum,exports.decimalToHex=decimalToHex,exports.decimalToHex0x=(decimal,padding=2)=>"0x"+Number(decimal).toString(16).padStart(padding,"0"),exports.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)}`]},exports.extractBits=(number,start,end)=>number>>start&(1<<end-start+1)-1,exports.fromBCD=bcd=>10*((bcd&=255)>>4&15)+(15&bcd),exports.generateCheckSum=generateCheckSum,exports.generateCrc16modbusCheck=(data,swapNeed=!1)=>{const hex=crc16modbus(data,swapNeed),hexStr=decimalToHex(hex,4);return[`0x${hexStr.slice(0,2)}`,`0x${hexStr.slice(2,4)}`]},exports.generateCrcCheckSum=data=>{const hex=crcCheckSum(data),hexStr=decimalToHex(hex,4);return[`0x${hexStr.slice(0,2)}`,`0x${hexStr.slice(2,4)}`]},exports.getParamBaseValue=arr=>{const hexString=arr.map(el=>decimalToHex(el)).join("");return parseInt(hexString,16)},exports.hex2Ascii=(value=[])=>{const hexString=value.join("");return hexStrAscii(hexString)},exports.hex2Binary=(hex,len=0)=>parseInt(hex,16).toString(2).padStart(len,"0"),exports.hex2string=hex2string,exports.hexArr2Assic=(hexArr=[])=>String.fromCharCode(...hexArr).replace(/\u0000/g,""),exports.hexArr2ab=hexArr=>{const buffer=new ArrayBuffer(hexArr.length),dataView=new DataView(buffer);return hexArr.forEach((hex,i)=>dataView.setUint8(i,hex)),buffer},exports.hexArr2string=(hexArr=[],connector="")=>hexArr.map(o=>hex2string(o)).join(connector),exports.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},exports.hexStrAscii=hexStrAscii,exports.hexStringToBinary=hexString=>parseInt(hexString,16).toString(2),exports.hexToDecimal=hex=>parseInt(hex,16),exports.isWithin30Minutes=timeStr=>{const now=Date.now(),targetTime=parseDateTime(timeStr);if(null===targetTime)return console.error("时间字符串格式错误:",timeStr),!1;return Math.abs(now-targetTime)>=18e5},exports.parseDateTime=parseDateTime,exports.sleep=(n=500)=>new Promise(r=>setTimeout(()=>r(!0),n)),exports.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},exports.stringToTwoHexArray=str=>{const paddedStr=str.padStart(4,"0");return[`0x${paddedStr.slice(0,2)}`,`0x${paddedStr.slice(2,4)}`]},exports.toBCD=num=>{if(num<0||num>99)throw new Error("BCD only supports 0-99");return Math.floor(num/10)<<4|num%10};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var commonfun=require("./commonfun.js"),TelinkApi=require("./TelinkApi.js"),Transfer=require("./Transfer.js");const max=Transfer.BLE.PACKAGE_MAX_LENGTH,delayDefault=Transfer.BLE.WRITE_DELAY,{isIOS:isIOS,isAndroid:isAndroid}=commonfun.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.TelinkApi.isTeLink&&TelinkApi.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.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.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(()=>{Transfer.BLE.writeATCmd(this.otaInfo,this.deviceId,this.fail.bind(this))
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var commonfun=require("./commonfun.js"),TelinkApi=require("./TelinkApi.js"),Transfer=require("./Transfer.js");const max=Transfer.BLE.PACKAGE_MAX_LENGTH,delayDefault=Transfer.BLE.WRITE_DELAY,{isIOS:isIOS,isAndroid:isAndroid}=commonfun.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.TelinkApi.isTeLink&&TelinkApi.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.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.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(()=>{Transfer.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.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.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.TelinkApi.genCheck([...pkgValue]),pkg=[...pkgValue,...crc];this.write(pkg,5)}addBLECharValueChangeListener(){console.log("添加蓝牙特征值变化监听");const that=this;uni.notifyBLECharacteristicValueChange({deviceId:that.deviceId,serviceId:Transfer.BLE.serviceId,characteristicId:Transfer.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==Transfer.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];Transfer.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.Transfer.decimalToTwoByteHexArray(this.finishedTimes);Transfer.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(){Transfer.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))}}exports.OTAUpgrade=OTAUpgrade,exports.default=OTAUpgrade;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var commonfun=require("./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:
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var commonfun=require("./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){commonfun.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}};exports.BLE=BLE,exports.Logger=class{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}},exports.Observer=class{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)}}},exports.Transfer=Transfer,exports.default=Transfer;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";function isEmpty(v){return null==v||""===v}Object.defineProperty(exports,"__esModule",{value:!0});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))}};exports.eventBus=eventBus,exports.formatTimeHHmm=function(hours){const hour=Math.floor(hours),minute=Math.floor(60*(hours-hour));return console.log("H5环境"),`${hour}H:${minute}m`},exports.getOS=function(){const os=uni.getSystemInfoSync()?.osName;return{isIOS:"ios"==os,isAndroid:"android"==os}},exports.getPlatform=function(){return uni.getSystemInfoSync()?.uniPlatform||""},exports.inArray=function(arr,key,val){for(let i=0;i<arr.length;i++)if(arr[i][key]===val)return i;return-1},exports.isEmpty=isEmpty,exports.isNotEmpty=function(v){return!isEmpty(v)};
|
|
1
|
+
"use strict";function isEmpty(v){return null==v||""===v}Object.defineProperty(exports,"__esModule",{value:!0});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))}};exports.eventBus=eventBus,exports.formatTimeHHmm=function(hours){const hour=Math.floor(hours),minute=Math.floor(60*(hours-hour));return console.log("H5环境"),`${hour}H:${minute}m`},exports.getOS=function(){const os=uni.getSystemInfoSync()?.osName;return{isIOS:"ios"==os,isAndroid:"android"==os||"openharmonyos"==os,isHarmony:"harmony"===os||"openharmonyos"===os}},exports.getPlatform=function(){return uni.getSystemInfoSync()?.uniPlatform||""},exports.inArray=function(arr,key,val){for(let i=0;i<arr.length;i++)if(arr[i][key]===val)return i;return-1},exports.isEmpty=isEmpty,exports.isNotEmpty=function(v){return!isEmpty(v)};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});const tempFuncJson=Array.from({length:8},(_,index)=>({name:""+(0===index?"保护板温度":`电池温度${index}`),value:"",newValue:"",checked:!1,unit:"",key:`tempera${index}`}));exports.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:
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});const tempFuncJson=Array.from({length:8},(_,index)=>({name:""+(0===index?"保护板温度":`电池温度${index}`),value:"",newValue:"",checked:!1,unit:"",key:`tempera${index}`}));exports.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}],exports.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}],exports.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}],exports.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}],exports.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"}],exports.funcAndTempFuncJson=[{paramNo:29,oldParamNo:"0x2D",paramLength:2,key:"func"},{paramNo:30,oldParamNo:"0x2E",paramLength:2,key:"tempFunc"}],exports.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"}],exports.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}],exports.tempFuncJson=tempFuncJson,exports.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"}],exports.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}];
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var SHA256=require("crypto-js/sha256"),mqtt=require("mqtt/dist/mqtt.min.js"),BleCmdDD=require("./BleCmdAnalysis/BleCmdDD.js"),BleCmdFFAA=require("./BleCmdAnalysis/BleCmdFFAA.js"),BleCmdHVES=require("./BleCmdAnalysis/BleCmdHVES.js"),BleDataProcess=require("./BleDataProcess.js"),rsaEncrypt=require("./rsaEncrypt.js"),Transfer=require("./Transfer.js");function _interopDefaultLegacy(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var SHA256__default=_interopDefaultLegacy(SHA256),mqtt__default=_interopDefaultLegacy(mqtt);exports.MqttServer=class{constructor({mqttClient:mqttClient={},MQTT_HOST:MQTT_HOST="wxs://mqtt.jiabaida.com/mqtt",DELAY_TIME:DELAY_TIME=300,networkModelUrl:networkModelUrl="https://cloud.jiabaida.com/bluetooth/server/device/networkModel",request:request}){this.timer=null,this.productKey="bms_wifi",this.is0f=!1,this.publishObj={},this.cmdCode="",this.callbackId="",this.mqttCode="",this.mqttPublish=!1,this.mqttClient=mqttClient,this.MQTT_HOST=MQTT_HOST,this.DELAY_TIME=DELAY_TIME,this.networkModelUrl=networkModelUrl,this.request=request}async getParams(item){try{return await this.request({url:`${this.networkModelUrl}?macAddr=${item.macAddr}`,method:"get"})}catch(error){throw console.error("getnetworkModel-error",error),error}}async connectMqtt(deviceObj){try{const modalData=await this.getParams(deviceObj);if(!modalData||200!==modalData.data.code)return;const mqttParam=modalData.data.data,clientId=rsaEncrypt.decrypt(mqttParam.clientId),username=mqttParam.mqttUsername,password=rsaEncrypt.decrypt(mqttParam.mqttSecret);console.log("连接 MQTT...");const options={clean:!0,connectTimeout:4e3,clientId:clientId,username:username,password:SHA256__default.default(password).toString(),deviceId:deviceObj.deviceId},client=mqtt__default.default.connect(this.MQTT_HOST,options);console.log("MQTT 客户端创建成功:",client),client.on("connect",res=>{console.log("res连接成功",res),client.productKey=this.productKey,this.handleMqttConnect(client,deviceObj)}),client.on("message",(topic,message)=>{this.handleMqttMessage(topic,message,client)}),client.on("reconnect",res=>console.log("MQTT 重连中...",res,client)),client.on("close",res=>this.handleMqttClose(client,res)),client.on("offline",res=>console.log("MQTT 脱机状态",res,client)),client.on("error",res=>console.error("MQTT 连接错误",res,client)),client.on("disconnect",res=>console.log("MQTT 断开连接",res,client))}catch(e){console.error("MQTT 连接异常:",e)}}handleMqttConnect(client,deviceObj){console.log("MQTT 连接成功 client",client),console.log("MQTT 连接成功 deviceObj",deviceObj),this.storeMqttClient(client),this.publishInOrder(client,deviceObj).then(()=>this.subscribeInOrder(client))}storeMqttClient(client){this.mqttClient[`${client.options.deviceId}_mqtt`]=client,console.log("存储的 MQTT 客户端:",this.mqttClient)}getTopicsAndMessages(client,deviceObj){const{productType:productType,soc:soc,moduleType:moduleType,macAddr:macAddr}=deviceObj,message=JSON.stringify({productKey:productType,soc:soc,moduleTypeKey:moduleType,macAddr:macAddr});return[{topic:`/${client.productKey}/${client.options.clientId}/device/login`,message:message}]}async publishInOrder(client,deviceObj){const topicsAndMessages=this.getTopicsAndMessages(client,deviceObj);try{for(const item of topicsAndMessages)await new Promise(resolve=>{client.publish(item.topic,item.message,()=>{resolve()})})}catch(error){console.error(`处理发布时出现错误: ${error}`)}}getSubscribeTopics(client){const{productKey:productKey}=client,clientId=client.options.clientId;return[`/${productKey}/${clientId}/device/login/reply`,`/${productKey}/${clientId}/device/passthrough/reply`,`/${productKey}/${clientId}/plat/cmd`,`/${productKey}/${clientId}/plat/passthrough`]}async subscribeInOrder(client){const subscribeTopics=this.getSubscribeTopics(client);try{for(const topic of subscribeTopics)await new Promise((resolve,reject)=>{client.subscribe(topic,err=>{err?reject(err):resolve()})})}catch(error){console.error(`订阅主题时出现错误: ${error}`)}}handleMqttMessage(topic,message,client){const clientId=topic.split("/")[2];topic!==`/${(client=Object.values(this.mqttClient).find(c=>c?.options?.clientId===clientId)||client).productKey}/${client.options.clientId}/plat/passthrough`&&topic!==`/${client.productKey}/${client.options.clientId}/plat/cmd`||this.processMessageAsync(client,message.toString())}async processMessageAsync(client,message){const msg=JSON.parse(message);this.callbackId=msg.callbackId,this.cmdCode=msg.cmdCode;let resultArray=[],codeValue=[];if("jbdPWD"===this.cmdCode){const cmdContent={2:"FFAA23010125",3:"FFAA1F010121",4:"FFAA20010122",5:"FFAA23010226"}[msg.value];codeValue=cmdContent?cmdContent.split(","):[]}else codeValue=msg.value?msg.value.split(","):[],this.is0f=2===codeValue.length;resultArray=codeValue[0]?codeValue[0].match(/.{1,2}/g):[];try{"FF"===resultArray[0]?.toUpperCase()&&"AA"===resultArray[1]?.toUpperCase()||"78"===resultArray[1]?.toUpperCase()||resultArray[1]?.toUpperCase();const publishObj={deviceId:client.options.deviceId,clientId:client.options.clientId,productKey:client.productKey,callbackId:this.callbackId,cmdCode:this.cmdCode,is0f:this.is0f,isLast:msg.isLast};this.publishObj=publishObj,this.cmdCode.toLowerCase().includes("wifi_")?await this.publishATHandle(msg.value):(this.writePublishInfoCmd(resultArray),await BleDataProcess.sleep(this.DELAY_TIME))}catch(error){console.error("error: 处理后台发指令错误",error)}}async publishATHandle(ATvalue){const{deviceId:deviceId,cmdCode:cmdCode,callbackId:callbackId,productKey:productKey,clientId:clientId,isLast:isLast}=this.publishObj,client=this.mqttClient[`${deviceId}_mqtt`];try{if(client){const hex=await BleCmdFFAA.getFFAA80Async(deviceId,ATvalue),res=BleCmdFFAA.resolveFFAA80(hex);if(res&&res.moduleVersion){const value=res.moduleVersion;client.publish(`/${productKey}/${clientId}/plat/cmd/reply`,JSON.stringify({value:value,cmdCode:cmdCode,callbackId:callbackId}),()=>{})}}isLast&&(await BleDataProcess.sleep(300),this.mqttPublish=!1,uni.removeStorageSync&&uni.removeStorageSync(`${deviceId}_mqttPublish`))}catch(error){console.error(error)}}handleMqttClose(client,res){console.log("MQTT 连接关闭",res,client),client.end(()=>{this.mqttClient[`${client.options.deviceId}_mqtt`]=null})}async publishHandle(value,baseValue,voltageValue){const client=this.mqttClient[`${this.publishObj.deviceId}_mqtt`];this.publishObj.is0f&&(value=baseValue+","+voltageValue);const msg=JSON.stringify({value:value,cmdCode:this.publishObj.cmdCode,callbackId:this.publishObj.callbackId});client&&client.publish(`/${this.publishObj.productKey}/${this.publishObj.clientId}/plat/passthrough/reply`,msg,()=>{}),this.publishObj.isLast&&(await BleDataProcess.sleep(300),this.mqttPublish=!1,uni.removeStorageSync&&uni.removeStorageSync(`${this.publishObj.deviceId}_mqttPublish`))}publishPassthroughHandle({value:value,cmdCode:cmdCode},deviceId,timeOffset=3e4){const client=this.mqttClient[`${deviceId}_mqtt`];if(client){const clientTime=(new Date).getTime(),{laseCmdCode:laseCmdCode,lastPassthroughTime:lastPassthroughTime,clientId:clientId}=client?.options;if(laseCmdCode!=cmdCode||!(lastPassthroughTime&&clientTime-lastPassthroughTime<timeOffset)){const topic=`/${client?.productKey}/${clientId}/device/passthrough`,payload=JSON.stringify({value:value,cmdCode:cmdCode,clientTime:clientTime});client.publish(topic,payload,()=>{client.options.lastPassthroughTime=clientTime,client.options.laseCmdCode=cmdCode})}}}async writePublishInfoCmd(values){clearTimeout(this.timer),this.mqttPublish=!0,this.mqttCode=values[2];let res=null;res="FF"===values[0]?.toUpperCase()&&"AA"===values[1]?.toUpperCase()?await BleCmdFFAA.set_PlanCMD_FFAA(this.publishObj.deviceId,values.join("")):"78"===values[1]?.toUpperCase()||"50"===values[1]?.toUpperCase()?await BleCmdHVES.getCMDESInfoAsync(this.publishObj.deviceId,values.join("")):await BleCmdDD.set_PlanCMD_DD(this.publishObj.deviceId,values.join(""));const content=res?.data||[];let code=Transfer.Transfer.decimalToHex(content[1]);255==content[0]&&170==content[1]&&(code=Transfer.Transfer.decimalToHex(content[2])),console.log("code: 回复的code",code),code.toUpperCase()==this.mqttCode.toUpperCase()&&this.publishHandle(res?.dataStr),this.timer=setTimeout(()=>{this.mqttPublish=!1},3e4)}};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";function _interopDefaultLegacy(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}Object.defineProperty(exports,"__esModule",{value:!0});var JSEncrypt__default=_interopDefaultLegacy(require("jsencrypt"));const publicKey="MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANL378k3RiZHWx5AfJqdH9xRNBmD9wGD\n2iRe41HdTNF8RUhNnHit5NpMNtGL0NPTSSpPjjI1kJfVorRvaQerUgkCAwEAAQ==";function decrypt(txt){const encryptor=new JSEncrypt__default.default;return encryptor.setPrivateKey("MIIBVgIBADANBgkqhkiG9w0BAQEFAASCAUAwggE8AgEAAkEA4cWDRXldfRIqc2Mg\nJSAiKqvRGa0v7a4fC0j3YjzpxcIArm1Ui5d9DN8Ly7vGdUnltPuy7yC9nVQuW89+\nJ6PnowIDAQABAkEApgP1/l07KJ/2BTkrxwD0/smvDaFzL+QswcCa4GsIP7iBvPna\n003yp3UGSXfEZWiQzHfehW2UHB5DIh5YbghaqQIhAPkB8LWgJlsaC8WP90ztg0nl\n+6VBLiunF6dV0Q7eJzMlAiEA6ByIpg2ZvT+X8Zzmkw32Si/Aw5VZ/ulJ5D6/MKuS\nmScCIAjcRNBxrmu3dYvGH6qhGPbcNCQhOZ9cBr9xkkrRJNvxAiEAvVapUWs+wdWi\nSIFIxSRah+G0SNcH9pyunfVhWH5cs3kCIQDGArpiAGQ4WOO+tFDqUVaDXwhQnx2H\n5OGt/FZJpmDnUw=="),encryptor.decrypt(txt)}exports.decrypt=decrypt,exports.decrypt2=function(txt){const encryptor=new JSEncrypt__default.default;return encryptor.setPrivateKey(publicKey),encryptor.decrypt(txt)},exports.decryptUsername=txt=>{const text=decrypt(txt);if(text)return text.substring(0,text.length-13)},exports.encrypt=function(txt){const encryptor=new JSEncrypt__default.default;return encryptor.setPublicKey(publicKey),encryptor.encrypt(txt)};
|